From 06f41b65ace647f95aae15c389eb6771e96fbb6b Mon Sep 17 00:00:00 2001 From: terrainvidia Date: Thu, 27 Feb 2025 03:48:53 +0300 Subject: [PATCH] fix: issue/7114 make `npm run` autocompletes script names from workspace not root --- lib/commands/run-script.js | 6 +++++- test/lib/commands/run-script.js | 19 +++++++++++++++++++ 2 files changed, 24 insertions(+), 1 deletion(-) diff --git a/lib/commands/run-script.js b/lib/commands/run-script.js index 50c745d6d9c07..656a850894689 100644 --- a/lib/commands/run-script.js +++ b/lib/commands/run-script.js @@ -26,7 +26,11 @@ class RunScript extends BaseCommand { static async completion (opts, npm) { const argv = opts.conf.argv.remain if (argv.length === 2) { - const { content: { scripts = {} } } = await pkgJson.normalize(npm.localPrefix) + const workspacePrefixes = npm.config.get('workspace', 'default') + const localPrefix = workspacePrefixes.length + ? workspacePrefixes[0] + : npm.localPrefix + const { content: { scripts = {} } } = await pkgJson.normalize(localPrefix) .catch(() => ({ content: {} })) if (opts.isFish) { return Object.keys(scripts).map(s => `${s}\t${scripts[s].slice(0, 30)}`) diff --git a/test/lib/commands/run-script.js b/test/lib/commands/run-script.js index 6906a7de67d0b..56ae140311ac7 100644 --- a/test/lib/commands/run-script.js +++ b/test/lib/commands/run-script.js @@ -3,6 +3,7 @@ const { resolve } = require('node:path') const realRunScript = require('@npmcli/run-script') const mockNpm = require('../../fixtures/mock-npm') const { cleanCwd } = require('../../fixtures/clean-snapshot') +const path = require('node:path') const mockRs = async (t, { windows = false, runScript, ...opts } = {}) => { let RUN_SCRIPTS = [] @@ -491,6 +492,7 @@ t.test('workspaces', async t => { prefixDir, workspaces = true, exec = [], + chdir = ({ prefix }) => prefix, ...config } = {}) => { const mock = await mockRs(t, { @@ -554,6 +556,7 @@ t.test('workspaces', async t => { ...Array.isArray(workspaces) ? { workspace: workspaces } : { workspaces }, ...config, }, + chdir, runScript, }) if (exec) { @@ -562,6 +565,22 @@ t.test('workspaces', async t => { return mock } + t.test('completion', async t => { + t.test('in root dir', async t => { + const { runScript } = await mockWorkspaces(t) + const res = await runScript.completion({ conf: { argv: { remain: ['npm', 'run'] } } }) + t.strictSame(res, []) + }) + + t.test('in workspace dir', async t => { + const { runScript } = await mockWorkspaces(t, { + chdir: ({ prefix }) => path.join(prefix, 'packages/c'), + }) + const res = await runScript.completion({ conf: { argv: { remain: ['npm', 'run'] } } }) + t.strictSame(res, ['test', 'posttest', 'lorem']) + }) + }) + t.test('list all scripts', async t => { const { joinedOutput } = await mockWorkspaces(t) t.matchSnapshot(joinedOutput())