Files
test-repo/tests/integration/cli-worker.js
T

Ignoring revisions in .git-blame-ignore-revs. Click here to bypass and see the normal blame view.

81 lines
2.3 KiB
JavaScript
Raw Normal View History

2022-05-10 15:42:11 +08:00
import { workerData, parentPort } from "node:worker_threads";
import fs from "node:fs";
import path from "node:path";
2022-05-21 11:11:50 +08:00
import url from "node:url";
2022-07-13 14:10:22 +08:00
import { cosmiconfig } from "cosmiconfig";
2022-08-03 14:19:00 +08:00
import { prettierCli, thirdParty as thirdPartyModuleFile } from "./env.js";
2022-05-10 15:42:11 +08:00
async function run() {
2022-08-03 14:19:00 +08:00
const { options } = workerData;
2022-05-10 15:42:11 +08:00
Date.now = () => 0;
// eslint-disable-next-line require-await
fs.promises.writeFile = async (filename, content) => {
2022-10-25 01:42:41 +09:00
const error = (options.mockWriteFileErrors || {})[filename];
if (error) {
throw new Error(error);
}
2022-05-10 15:42:11 +08:00
parentPort.postMessage({
action: "write-file",
data: { filename, content },
});
};
/*
A fake non-existing directory to test plugin search won't crash.
See:
- `isDirectory` function in `src/common/load-plugins.js`
- Test file `./__tests__/plugin-virtual-directory.js`
- Pull request #5819
*/
const originalStat = fs.promises.stat;
fs.promises.statSync = (filename) =>
originalStat(
path.basename(filename) === "virtualDirectory"
? import.meta.url
: filename
);
process.stdin.isTTY = Boolean(options.isTTY);
process.stdout.isTTY = Boolean(options.stdoutIsTTY);
const { default: thirdParty } = await import(
url.pathToFileURL(thirdPartyModuleFile)
);
2022-05-10 15:42:11 +08:00
// We cannot use `jest.setMock("get-stream", impl)` here, because in the
// production build everything is bundled into one file so there is no
// "get-stream" module to mock.
// eslint-disable-next-line require-await
thirdParty.getStdin = async () => options.input || "";
thirdParty.isCI = () => Boolean(options.ci);
thirdParty.cosmiconfig = (moduleName, options) =>
2022-07-13 14:10:22 +08:00
cosmiconfig(moduleName, {
2022-05-10 15:42:11 +08:00
...options,
2022-07-13 14:10:22 +08:00
stopDir: url.fileURLToPath(new URL("./cli", import.meta.url)),
2022-05-10 15:42:11 +08:00
});
thirdParty.findParentDir = () => process.cwd();
2022-05-21 11:11:50 +08:00
const { promise } = await import(url.pathToFileURL(prettierCli));
await promise;
2022-05-10 15:42:11 +08:00
}
parentPort.on("message", async () => {
const originalExit = process.exit;
// https://github.com/nodejs/node/issues/30491
process.stdout.cork();
process.stderr.cork();
process.exit = (code) => {
process.stdout.end();
process.stderr.end();
originalExit(code);
};
try {
await run();
} finally {
process.exit();
}
});