feat: expanded missing command error, including 'did you mean' (#6496)

close #6492

Co-authored-by: Zoltan Kochan <z@kochan.io>
This commit is contained in:
Josh Goldberg ✨
2023-05-14 20:22:26 -04:00
committed by GitHub
parent d58cdb9629
commit ee429b300b
12 changed files with 120 additions and 11 deletions

View File

@@ -0,0 +1,7 @@
---
"@pnpm/plugin-commands-script-runners": minor
"@pnpm/cli-utils": patch
"pnpm": patch
---
Expanded missing command error, including 'did you mean' [#6492](https://github.com/pnpm/pnpm/issues/6492).

View File

@@ -39,7 +39,7 @@ declare module '@pnpm/npm-package-arg' {
export = anything
}
declare module '@zkochan/which' {
declare module '@pnpm/which' {
const anything: any
export = anything
}

View File

@@ -23,7 +23,7 @@ export async function readProjectManifestOnly (
opts: {
engineStrict?: boolean
nodeVersion?: string
}
} = {}
): Promise<ProjectManifest> {
const manifest = await utils.readProjectManifestOnly(projectDir)
packageIsInstallable(projectDir, manifest as any, opts) // eslint-disable-line @typescript-eslint/no-explicit-any

View File

@@ -40,6 +40,7 @@
"@pnpm/registry-mock": "3.8.0",
"@types/is-windows": "^1.0.0",
"@types/ramda": "0.28.20",
"@types/which": "^2.0.2",
"is-windows": "^1.0.2",
"write-yaml-file": "^5.0.0"
},
@@ -58,6 +59,7 @@
"@pnpm/store-path": "workspace:*",
"@pnpm/types": "workspace:*",
"@zkochan/rimraf": "^2.1.2",
"didyoumean2": "^5.0.0",
"execa": "npm:safe-execa@0.1.2",
"p-limit": "^3.1.0",
"path-exists": "^4.0.0",
@@ -65,6 +67,7 @@
"ramda": "npm:@pnpm/ramda@0.28.1",
"realpath-missing": "^1.1.0",
"render-help": "^1.0.3",
"which": "npm:@pnpm/which@^3.0.1",
"write-json-file": "^4.3.0"
},
"peerDependencies": {

View File

@@ -0,0 +1,16 @@
import { type PackageScripts } from '@pnpm/types'
import didYouMean, { ReturnTypeEnums } from 'didyoumean2'
export function buildCommandNotFoundHint (scriptName: string, scripts?: PackageScripts | undefined) {
let hint = `Command "${scriptName}" not found.`
const nearestCommand = scripts && didYouMean(scriptName, Object.keys(scripts), {
returnType: ReturnTypeEnums.FIRST_CLOSEST_MATCH,
})
if (nearestCommand) {
hint += ` Did you mean "pnpm run ${nearestCommand}"?`
}
return hint
}

View File

@@ -1,5 +1,5 @@
import path from 'path'
import { docsUrl, type RecursiveSummary, throwOnCommandFail } from '@pnpm/cli-utils'
import { docsUrl, type RecursiveSummary, throwOnCommandFail, readProjectManifestOnly } from '@pnpm/cli-utils'
import { type Config, types } from '@pnpm/config'
import { makeNodeRequireOption } from '@pnpm/lifecycle'
import { logger } from '@pnpm/logger'
@@ -19,7 +19,9 @@ import {
shorthands as runShorthands,
} from './run'
import { PnpmError } from '@pnpm/error'
import which from 'which'
import writeJsonFile from 'write-json-file'
import { buildCommandNotFoundHint } from './buildCommandNotFoundHint'
export const shorthands = {
parallel: runShorthands.parallel,
@@ -208,7 +210,9 @@ export async function handler (
result[prefix].status = 'passed'
result[prefix].duration = getExecutionDuration(startTime)
} catch (err: any) { // eslint-disable-line
if (!opts.recursive && typeof err.exitCode === 'number') {
if (await isErrorCommandNotFound(params[0], err)) {
err.hint = buildCommandNotFoundHint(params[0], (await readProjectManifestOnly(opts.dir)).scripts)
} else if (!opts.recursive && typeof err.exitCode === 'number') {
exitCode = err.exitCode
return
}
@@ -248,3 +252,19 @@ export async function handler (
throwOnCommandFail('pnpm recursive exec', result)
return { exitCode }
}
interface CommandError extends Error {
originalMessage: string
shortMessage: string
}
async function isErrorCommandNotFound (command: string, error: CommandError) {
// Mac/Linux
if (error.originalMessage === `spawn ${command} ENOENT`) {
return true
}
// Windows
return error.shortMessage === `Command failed with exit code 1: ${command}` &&
!(await which(command, { nothrow: true }))
}

View File

@@ -21,6 +21,7 @@ import renderHelp from 'render-help'
import { runRecursive, type RecursiveRunOpts, getSpecifiedScripts as getSpecifiedScriptWithoutStartCommand } from './runRecursive'
import { existsInDir } from './existsInDir'
import { handler as exec } from './exec'
import { buildCommandNotFoundHint } from './buildCommandNotFoundHint'
export const IF_PRESENT_OPTION = {
'if-present': Boolean,
@@ -197,7 +198,10 @@ so you may run "pnpm -w run ${scriptName}"`,
})
}
}
throw new PnpmError('NO_SCRIPT', `Missing script: ${scriptName}`)
throw new PnpmError('NO_SCRIPT', `Missing script: ${scriptName}`, {
hint: buildCommandNotFoundHint(scriptName, manifest.scripts),
})
}
const lifecycleOpts: RunLifecycleHookOptions = {
depPath: dir,

View File

@@ -811,3 +811,26 @@ test('pnpm recursive exec report summary with --bail', async () => {
expect(executionStatus[path.resolve('project-3')].status).toBe('running')
expect(executionStatus[path.resolve('project-4')].status).toBe('queued')
})
test('pnpm exec command not found', async () => {
prepare({
scripts: {
build: 'echo hello',
},
})
const { selectedProjectsGraph } = await readProjects(process.cwd(), [])
let error!: Error & { hint: string }
try {
await exec.handler({
...DEFAULT_OPTS,
dir: process.cwd(),
recursive: false,
bail: true,
selectedProjectsGraph,
}, ['buil'])
} catch (err: any) { // eslint-disable-line
error = err
}
expect(error?.hint).toBe('Command "buil" not found. Did you mean "pnpm run build"?')
})

View File

@@ -585,3 +585,22 @@ test('pnpm run with RegExp script selector with flag should throw error', async
}
expect(err.message).toBe('RegExp flags are not supported in script command selector')
})
test('pnpm run with slightly incorrect command suggests correct one', async () => {
prepare({
scripts: {
build: 'echo 0',
},
})
await expect(run.handler({
dir: process.cwd(),
extraBinPaths: [],
extraEnv: {},
rawConfig: {},
workspaceConcurrency: 1,
}, ['buil'])).rejects.toEqual(expect.objectContaining({
code: 'ERR_PNPM_NO_SCRIPT',
hint: 'Command "buil" not found. Did you mean "pnpm run build"?',
}))
})

View File

@@ -90,7 +90,7 @@
"@yarnpkg/parsers": "3.0.0-rc.42",
"@zkochan/rimraf": "^2.1.2",
"@zkochan/table": "^2.0.1",
"@zkochan/which": "^2.0.3",
"@pnpm/which": "^3.0.1",
"chalk": "^4.1.2",
"ci-info": "^3.8.0",
"enquirer": "^2.3.6",

View File

@@ -1,5 +1,5 @@
import { promises as fs } from 'fs'
import which from '@zkochan/which'
import which from '@pnpm/which'
export async function getNodeExecPath () {
try {

25
pnpm-lock.yaml generated
View File

@@ -1246,6 +1246,9 @@ importers:
'@zkochan/rimraf':
specifier: ^2.1.2
version: 2.1.2
didyoumean2:
specifier: ^5.0.0
version: 5.0.0
execa:
specifier: npm:safe-execa@0.1.2
version: /safe-execa@0.1.2
@@ -1267,6 +1270,9 @@ importers:
render-help:
specifier: ^1.0.3
version: 1.0.3
which:
specifier: npm:@pnpm/which@^3.0.1
version: /@pnpm/which@3.0.1
write-json-file:
specifier: ^4.3.0
version: 4.3.0
@@ -1289,6 +1295,9 @@ importers:
'@types/ramda':
specifier: 0.28.20
version: 0.28.20
'@types/which':
specifier: ^2.0.2
version: 2.0.2
is-windows:
specifier: ^1.0.2
version: 1.0.2
@@ -3649,6 +3658,9 @@ importers:
'@pnpm/types':
specifier: workspace:*
version: link:../../packages/types
'@pnpm/which':
specifier: ^3.0.1
version: 3.0.1
'@pnpm/workspace.pkgs-graph':
specifier: workspace:*
version: link:../../workspace/pkgs-graph
@@ -3667,9 +3679,6 @@ importers:
'@zkochan/table':
specifier: ^2.0.1
version: 2.0.1
'@zkochan/which':
specifier: ^2.0.3
version: 2.0.3
chalk:
specifier: ^4.1.2
version: 4.1.2
@@ -8755,6 +8764,14 @@ packages:
semver-utils: 1.1.4
dev: true
/@pnpm/which@3.0.1:
resolution: {integrity: sha512-4ivtS12Oni9axgGefaq+gTPD+7N0VPCFdxFH8izCaWfnxLQblX3iVxba+25ZoagStlzUs8sQg8OMKlCVhyGWTw==}
engines: {node: ^14.17.0 || ^16.13.0 || >=18.0.0}
hasBin: true
dependencies:
isexe: 2.0.0
dev: false
/@pnpm/write-project-manifest@4.1.2:
resolution: {integrity: sha512-/C0j7SsE9tGoj++f0dwePIV7zNZHcX8TcYL6pXNvZZCq4HsOMCBsIlcU9oMI/AGe+KMDfHFQSayWPO9QUuGE5w==}
engines: {node: '>=14.6'}
@@ -17802,6 +17819,7 @@ time:
/@pnpm/semver-diff@1.1.0: '2021-11-16T12:40:59.941Z'
/@pnpm/tabtab@0.1.2: '2021-03-05T17:31:19.932Z'
/@pnpm/util.lex-comparator@1.0.0: '2022-11-04T01:03:46.134Z'
/@pnpm/which@3.0.1: '2023-05-14T22:08:27.551Z'
/@types/adm-zip@0.5.0: '2022-04-01T08:01:50.776Z'
/@types/archy@0.0.32: '2021-07-06T18:11:33.301Z'
/@types/byline@4.2.33: '2021-07-06T18:22:06.440Z'
@@ -17855,7 +17873,6 @@ time:
/@zkochan/retry@0.2.0: '2020-06-06T23:36:55.687Z'
/@zkochan/rimraf@2.1.2: '2022-01-30T23:37:31.206Z'
/@zkochan/table@2.0.1: '2023-03-20T00:49:51.928Z'
/@zkochan/which@2.0.3: '2021-09-14T23:50:27.657Z'
/adm-zip@0.5.10: '2022-12-20T11:08:08.848Z'
/ansi-diff@1.1.1: '2018-06-16T13:37:28.365Z'
/archy@1.0.0: '2014-09-14T07:57:58.806Z'