Avoid closing files multiple times in getInterpreter(#17665)

Co-authored-by: autofix-ci[bot] <114827586+autofix-ci[bot]@users.noreply.github.com>
Co-authored-by: fisker Cheung <lionkay@gmail.com>
This commit is contained in:
authored and GitHub committed 2025-06-25 14:27:33 +08:00
1 parent 0e6ec982df
commit 37f6e09589
2 files changed
+19 -18

No files matched your search

+8
View File
@@ -0,0 +1,8 @@
#### Avoid closing files multiple times (#17665 by @43081j)
When reading a file to infer the interpreter from a shebang, we use the
`n-readlines` library to read the first line in order to get the shebang.
This library closes files when it reaches EOF, and we later try close the same
files again. We now close files only if `n-readlines` did not already close
them.
+11 -18
View File
@@ -1,4 +1,3 @@
import fs from "node:fs";
import readlines from "n-readlines"; import readlines from "n-readlines";
/** /**
@@ -6,17 +5,17 @@ import readlines from "n-readlines";
* @returns {string | undefined} * @returns {string | undefined}
*/ */
function getInterpreter(file) { function getInterpreter(file) {
let fd;
try { try {
fd = fs.openSync(file, "r"); const liner = new readlines(file);
} catch { const firstLineBuffer = liner.next();
/* c8 ignore next */
return;
}
try { if (firstLineBuffer === false) {
const liner = new readlines(fd); return;
const firstLine = liner.next().toString("utf8"); }
liner.close();
const firstLine = firstLineBuffer.toString("utf8");
// #!/bin/env node, #!/usr/bin/env node // #!/bin/env node, #!/usr/bin/env node
const m1 = firstLine.match(/^#!\/(?:usr\/)?bin\/env\s+(\S+)/u); const m1 = firstLine.match(/^#!\/(?:usr\/)?bin\/env\s+(\S+)/u);
@@ -29,14 +28,8 @@ function getInterpreter(file) {
if (m2) { if (m2) {
return m2[1]; return m2[1];
} }
} finally { } catch {
try { // couldn't open the file
// 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
}
} }
} }