diff --git a/src/cli-options.ts b/src/cli-options.ts index 2534f91e4..4edee3e89 100644 --- a/src/cli-options.ts +++ b/src/cli-options.ts @@ -17,14 +17,25 @@ import {QuietCiLogger, QuietLogger} from './logging/quiet-logger.js'; import {DefaultLogger} from './logging/default-logger.js'; export const packageDir = await (async (): Promise => { - // Recent versions of npm set this environment variable that tells us the - // package. - const packageJsonPath = process.env.npm_package_json; - if (packageJsonPath) { - return pathlib.dirname(packageJsonPath); + // Recent versions of npm and yarn set the `npm_package_json` environment + // variable. + // + // yarn sets it to the package.json at the project root, even if we're in + // another package. + // + // Therefore, trust `npm_package_json` when in npm, but introspect the + // filesystem otherwise. + + const agent = getNpmUserAgent(); + + if (agent === 'npm') { + const packageJsonPath = process.env.npm_package_json; + if (packageJsonPath) { + return pathlib.dirname(packageJsonPath); + } } - // Older versions of npm, as well as yarn and pnpm, don't set this variable, - // so we have to find the nearest package.json by walking up the filesystem. + + // Find the nearest package.json by walking up the filesystem. let maybePackageDir = process.cwd(); while (true) { try {