Skip to content

Commit cef14f5

Browse files
Only use npm_package_json when we know it's correct
Fixes #960
1 parent fe2a9c1 commit cef14f5

File tree

1 file changed

+18
-7
lines changed

1 file changed

+18
-7
lines changed

src/cli-options.ts

Lines changed: 18 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -17,14 +17,25 @@ import {QuietCiLogger, QuietLogger} from './logging/quiet-logger.js';
1717
import {DefaultLogger} from './logging/default-logger.js';
1818

1919
export const packageDir = await (async (): Promise<string | undefined> => {
20-
// Recent versions of npm set this environment variable that tells us the
21-
// package.
22-
const packageJsonPath = process.env.npm_package_json;
23-
if (packageJsonPath) {
24-
return pathlib.dirname(packageJsonPath);
20+
// Recent versions of npm and yarn set the `npm_package_json` environment
21+
// variable.
22+
//
23+
// yarn sets it to the package.json at the project root, even if we're in
24+
// another package.
25+
//
26+
// Therefore, trust `npm_package_json` when in npm, but introspect the
27+
// filesystem otherwise.
28+
29+
const agent = getNpmUserAgent();
30+
31+
if (agent === 'npm') {
32+
const packageJsonPath = process.env.npm_package_json;
33+
if (packageJsonPath) {
34+
return pathlib.dirname(packageJsonPath);
35+
}
2536
}
26-
// Older versions of npm, as well as yarn and pnpm, don't set this variable,
27-
// so we have to find the nearest package.json by walking up the filesystem.
37+
38+
// Find the nearest package.json by walking up the filesystem.
2839
let maybePackageDir = process.cwd();
2940
while (true) {
3041
try {

0 commit comments

Comments
 (0)