Skip to content

Commit

Permalink
feat: expanded missing command error, including 'did you mean' (#6496)
Browse files Browse the repository at this point in the history
close #6492

Co-authored-by: Zoltan Kochan <z@kochan.io>
  • Loading branch information
JoshuaKGoldberg and zkochan committed May 15, 2023
1 parent d58cdb9 commit ee429b3
Show file tree
Hide file tree
Showing 12 changed files with 120 additions and 11 deletions.
7 changes: 7 additions & 0 deletions .changeset/pink-tips-rule.md
@@ -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).
2 changes: 1 addition & 1 deletion __typings__/local.d.ts
Expand Up @@ -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
}
Expand Down
2 changes: 1 addition & 1 deletion cli/cli-utils/src/readProjectManifest.ts
Expand Up @@ -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
Expand Down
3 changes: 3 additions & 0 deletions exec/plugin-commands-script-runners/package.json
Expand Up @@ -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"
},
Expand All @@ -58,13 +59,15 @@
"@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",
"path-name": "^1.0.0",
"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": {
Expand Down
@@ -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
}
24 changes: 22 additions & 2 deletions exec/plugin-commands-script-runners/src/exec.ts
@@ -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'
Expand All @@ -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,
Expand Down Expand Up @@ -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
}
Expand Down Expand Up @@ -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 }))
}
6 changes: 5 additions & 1 deletion exec/plugin-commands-script-runners/src/run.ts
Expand Up @@ -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,
Expand Down Expand Up @@ -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,
Expand Down
23 changes: 23 additions & 0 deletions exec/plugin-commands-script-runners/test/exec.e2e.ts
Expand Up @@ -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"?')
})
19 changes: 19 additions & 0 deletions exec/plugin-commands-script-runners/test/index.ts
Expand Up @@ -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"?',
}))
})
2 changes: 1 addition & 1 deletion pkg-manager/plugin-commands-installation/package.json
Expand Up @@ -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",
Expand Down
@@ -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 {
Expand Down
25 changes: 21 additions & 4 deletions pnpm-lock.yaml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

0 comments on commit ee429b3

Please sign in to comment.