forked from OKEAMAH/prettier
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathget-interpreter.js
More file actions
44 lines (38 loc) · 968 Bytes
/
get-interpreter.js
File metadata and controls
44 lines (38 loc) · 968 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
import fs from "node:fs";
import readlines from "n-readlines";
/**
* @param {string | URL} file
* @returns {string | undefined}
*/
function getInterpreter(file) {
let fd;
try {
fd = fs.openSync(file, "r");
} catch {
/* c8 ignore next */
return;
}
try {
const liner = new readlines(fd);
const firstLine = liner.next().toString("utf8");
// #!/bin/env node, #!/usr/bin/env node
const m1 = firstLine.match(/^#!\/(?:usr\/)?bin\/env\s+(\S+)/u);
if (m1) {
return m1[1];
}
// #!/bin/node, #!/usr/bin/node, #!/usr/local/bin/node
const m2 = firstLine.match(/^#!\/(?:usr\/(?:local\/)?)?bin\/(\S+)/u);
if (m2) {
return m2[1];
}
} finally {
try {
// There are some weird cases where paths are missing, causing Jest
// failures. It's unclear what these correspond to in the real world.
fs.closeSync(fd);
} catch {
// noop
}
}
}
export default getInterpreter;