Skip to content

Commit 56749ca

Browse files
committed
fix: set the cwd to the nearest package.json direcotry
Closes #32
1 parent a24dca8 commit 56749ca

File tree

1 file changed

+35
-1
lines changed

1 file changed

+35
-1
lines changed

src/runner-worker.ts

Lines changed: 35 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@ import { Contract } from "@hediet/json-rpc";
22
import { NodeJsMessageStream } from "@hediet/json-rpc-streams/src";
33
import * as ansiColors from "ansi-colors";
44
import { spawn } from "child_process";
5+
import { promises as fs } from "fs";
56
import { connect } from "net";
67
import * as path from "path";
78
import { dirname, join } from "path";
@@ -56,6 +57,38 @@ const start: (typeof contract)["TClientHandler"]["start"] = async ({
5657
return null;
5758
};
5859

60+
const nearestPackageJsons = new Map<
61+
/* directory */ string,
62+
/* package.json path */ string | undefined
63+
>();
64+
65+
const getNearestPackageJson = async (dir: string): Promise<string | undefined> => {
66+
if (nearestPackageJsons.has(dir)) {
67+
return nearestPackageJsons.get(dir)!;
68+
}
69+
70+
const packageJson = join(dir, "package.json");
71+
const exists = await fs.stat(packageJson).then(
72+
() => true,
73+
() => false,
74+
);
75+
76+
if (exists) {
77+
nearestPackageJsons.set(dir, packageJson);
78+
return packageJson;
79+
}
80+
81+
const next = dirname(dir);
82+
if (next === dir) {
83+
nearestPackageJsons.set(dir, undefined);
84+
return undefined;
85+
}
86+
87+
const result = await getNearestPackageJson(next);
88+
nearestPackageJsons.set(dir, result);
89+
return result;
90+
};
91+
5992
async function doWork(
6093
prefix: string,
6194
queue: ITestRunFile[],
@@ -66,6 +99,7 @@ async function doWork(
6699
) {
67100
while (queue.length) {
68101
const next = queue.pop()!;
102+
const containingPackage = await getNearestPackageJson(dirname(next.path));
69103
await new Promise<void>((resolve) => {
70104
if (verbose) {
71105
server.output(`${prefix}starting ${ansiColors.underline(next.path)}`);
@@ -90,7 +124,7 @@ async function doWork(
90124
}
91125

92126
const cp = spawn(process.argv0, args, {
93-
cwd: dirname(next.path),
127+
cwd: dirname(containingPackage || next.path),
94128
stdio: "pipe",
95129
env: {
96130
// enable color for modules that use `supports-color` or similar

0 commit comments

Comments
 (0)