Skip to content

Commit 37f6e09

Browse files
43081jautofix-ci[bot]fisker
authored
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 <[email protected]>
1 parent 0e6ec98 commit 37f6e09

File tree

2 files changed

+19
-18
lines changed

2 files changed

+19
-18
lines changed

changelog_unreleased/misc/17665.md

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,8 @@
1+
#### Avoid closing files multiple times (#17665 by @43081j)
2+
3+
When reading a file to infer the interpreter from a shebang, we use the
4+
`n-readlines` library to read the first line in order to get the shebang.
5+
6+
This library closes files when it reaches EOF, and we later try close the same
7+
files again. We now close files only if `n-readlines` did not already close
8+
them.

src/utils/get-interpreter.js

Lines changed: 11 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -1,22 +1,21 @@
1-
import fs from "node:fs";
21
import readlines from "n-readlines";
32

43
/**
54
* @param {string | URL} file
65
* @returns {string | undefined}
76
*/
87
function getInterpreter(file) {
9-
let fd;
108
try {
11-
fd = fs.openSync(file, "r");
12-
} catch {
13-
/* c8 ignore next */
14-
return;
15-
}
9+
const liner = new readlines(file);
10+
const firstLineBuffer = liner.next();
1611

17-
try {
18-
const liner = new readlines(fd);
19-
const firstLine = liner.next().toString("utf8");
12+
if (firstLineBuffer === false) {
13+
return;
14+
}
15+
16+
liner.close();
17+
18+
const firstLine = firstLineBuffer.toString("utf8");
2019

2120
// #!/bin/env node, #!/usr/bin/env node
2221
const m1 = firstLine.match(/^#!\/(?:usr\/)?bin\/env\s+(\S+)/u);
@@ -29,14 +28,8 @@ function getInterpreter(file) {
2928
if (m2) {
3029
return m2[1];
3130
}
32-
} finally {
33-
try {
34-
// There are some weird cases where paths are missing, causing Jest
35-
// failures. It's unclear what these correspond to in the real world.
36-
fs.closeSync(fd);
37-
} catch {
38-
// noop
39-
}
31+
} catch {
32+
// couldn't open the file
4033
}
4134
}
4235

0 commit comments

Comments
 (0)