From 14a3d95000f1cba937f3309d198a363ae65cf01f Mon Sep 17 00:00:00 2001 From: nlf Date: Thu, 20 Jan 2022 12:37:57 -0800 Subject: [PATCH] fix: resolve workspace paths from cwd when possible (#4265) --- lib/base-command.js | 8 ++++++++ lib/workspaces/get-workspaces.js | 6 +++--- test/lib/arborist-cmd.js | 2 +- 3 files changed, 12 insertions(+), 4 deletions(-) diff --git a/lib/base-command.js b/lib/base-command.js index ad261b5148bd2..f67f99f36367c 100644 --- a/lib/base-command.js +++ b/lib/base-command.js @@ -1,4 +1,7 @@ // Base class for npm commands + +const { relative } = require('path') + const usageUtil = require('./utils/usage.js') const ConfigDefinitions = require('./utils/config/definitions.js') const getWorkspaces = require('./workspaces/get-workspaces.js') @@ -78,9 +81,14 @@ class BaseCommand { this.includeWorkspaceRoot = false } + const relativeFrom = relative(this.npm.localPrefix, process.cwd()).startsWith('..') + ? this.npm.localPrefix + : process.cwd() + const ws = await getWorkspaces(filters, { path: this.npm.localPrefix, includeWorkspaceRoot: this.includeWorkspaceRoot, + relativeFrom, }) this.workspaces = ws this.workspaceNames = [...ws.keys()] diff --git a/lib/workspaces/get-workspaces.js b/lib/workspaces/get-workspaces.js index a59b5a6c54b70..0cddae2a462f1 100644 --- a/lib/workspaces/get-workspaces.js +++ b/lib/workspaces/get-workspaces.js @@ -5,7 +5,7 @@ const rpj = require('read-package-json-fast') // Returns an Map of paths to workspaces indexed by workspace name // { foo => '/path/to/foo' } -const getWorkspaces = async (filters, { path, includeWorkspaceRoot }) => { +const getWorkspaces = async (filters, { path, includeWorkspaceRoot, relativeFrom }) => { // TODO we need a better error to be bubbled up here if this rpj call fails const pkg = await rpj(resolve(path, 'package.json')) const workspaces = await mapWorkspaces({ cwd: path, pkg }) @@ -21,8 +21,8 @@ const getWorkspaces = async (filters, { path, includeWorkspaceRoot }) => { for (const filterArg of filters) { for (const [workspaceName, workspacePath] of workspaces.entries()) { if (filterArg === workspaceName - || resolve(path, filterArg) === workspacePath - || minimatch(workspacePath, `${resolve(path, filterArg)}/*`)) { + || resolve(relativeFrom || path, filterArg) === workspacePath + || minimatch(workspacePath, `${resolve(relativeFrom || path, filterArg)}/*`)) { res.set(workspaceName, workspacePath) } } diff --git a/test/lib/arborist-cmd.js b/test/lib/arborist-cmd.js index 3db862d233dc7..91d8a7b333bf9 100644 --- a/test/lib/arborist-cmd.js +++ b/test/lib/arborist-cmd.js @@ -98,7 +98,7 @@ t.test('handle getWorkspaces raising an error', async t => { }) class TestCmd extends ArboristCmd {} const cmd = new TestCmd() - cmd.npm = {} + cmd.npm = { localPrefix: t.testdir() } await t.rejects( cmd.execWorkspaces(['foo'], ['a']),