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:
2 files changed
+16
-15
No files matched your search
@@ -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.
|
||||
@@ -1,4 +1,3 @@
|
||||
import fs from "node:fs";
|
||||
import readlines from "n-readlines";
|
||||
|
||||
/**
|
||||
@@ -6,17 +5,17 @@ import readlines from "n-readlines";
|
||||
* @returns {string | undefined}
|
||||
*/
|
||||
function getInterpreter(file) {
|
||||
let fd;
|
||||
try {
|
||||
fd = fs.openSync(file, "r");
|
||||
} catch {
|
||||
/* c8 ignore next */
|
||||
const liner = new readlines(file);
|
||||
const firstLineBuffer = liner.next();
|
||||
|
||||
if (firstLineBuffer === false) {
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
const liner = new readlines(fd);
|
||||
const firstLine = liner.next().toString("utf8");
|
||||
liner.close();
|
||||
|
||||
const firstLine = firstLineBuffer.toString("utf8");
|
||||
|
||||
// #!/bin/env node, #!/usr/bin/env node
|
||||
const m1 = firstLine.match(/^#!\/(?:usr\/)?bin\/env\s+(\S+)/u);
|
||||
@@ -29,14 +28,8 @@ function getInterpreter(file) {
|
||||
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
|
||||
}
|
||||
// couldn't open the file
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
Reference in new issue
Block a user