Skip to content

Commit

Permalink
fix(cli-repl): account for possibility of process.exit() throwing u…
Browse files Browse the repository at this point in the history
…nder coverage MONGOSH-1943 (#2298)

When running under `nyc` for coverage generation, the process's
`process.exit()` internals get monkey-patched to give `nyc` the opportunity
to write coverage data as part of that operation. However, for processes
running under changed working directories, `nyc` may try to write to an incorrect
directory, making the `fs.writeFile()` call fail with an exception,
and so `process.exit()` may not actually stop the process.

This commit adds a `process.abort()` call to make that accounts for this situation,
as well as improved debugging for it.
  • Loading branch information
addaleax authored Dec 13, 2024
1 parent 1bbd86c commit 5405fe4
Showing 1 changed file with 23 additions and 3 deletions.
26 changes: 23 additions & 3 deletions packages/cli-repl/src/run.ts
Original file line number Diff line number Diff line change
Expand Up @@ -232,9 +232,7 @@ async function main() {
process.env.TEST_USE_STDOUT_FOR_PASSWORD || process.stdout.isTTY
? process.stdout
: process.stderr,
// Node.js 20.0.0 made p.exit(undefined) behave as p.exit(0) rather than p.exit()
onExit: (code?: number | undefined) =>
code === undefined ? process.exit() : process.exit(code),
onExit,
shellHomePaths: shellHomePaths,
globalConfigPaths: globalConfigPaths,
});
Expand Down Expand Up @@ -341,3 +339,25 @@ function suppressExperimentalWarnings() {
};
}
}

function onExit(code?: number): never {
// Node.js 20.0.0 made p.exit(undefined) behave as p.exit(0) rather than p.exit(): (code?: number | undefined): never => {
try {
try {
if (code === undefined) process.exit();
else process.exit(code);
} finally {
if (code === undefined) process.exit();
else process.exit(code);
}
} catch (err) {
process.stderr.write(String(err) + '\n');
} finally {
// Should never be reachable anyway, but nyc monkey-patches process.exit()
// internals so that it can always write coverage files as part of the application
// shutdown, and that can throw an exception if the filesystem call to write
// the coverage file fails.
process.stderr.write('process.exit() returned -- aborting\n');
process.abort();
}
}

0 comments on commit 5405fe4

Please sign in to comment.