Skip to content
This repository was archived by the owner on Apr 7, 2021. It is now read-only.

Commit ba4fe71

Browse files
committed
fix(perf): fast-path npx foo arg parsing
1 parent 549d413 commit ba4fe71

File tree

1 file changed

+44
-14
lines changed

1 file changed

+44
-14
lines changed

parse-args.js

Lines changed: 44 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -1,23 +1,53 @@
11
'use strict'
22

3-
const npa = require('npm-package-arg')
3+
let npa
44
const path = require('path')
5-
const yargs = require('yargs')
65

7-
const usage = `
8-
$0 [${Y()`options`}] <${Y()`command`}>[@${Y()`version`}] [${Y()`command-arg`}]...
9-
10-
$0 [${Y()`options`}] [-p|--package <${Y()`package`}>]... <${Y()`command`}> [${Y()`command-arg`}]...
11-
12-
$0 [${Y()`options`}] -c '<${Y()`command-string`}>'
13-
14-
$0 --shell-auto-fallback [${Y()`shell`}]
15-
`
6+
const DEFAULT_NPM = path.resolve(__dirname, 'node_modules', '.bin', 'npm')
167

178
module.exports = parseArgs
189
function parseArgs (argv) {
1910
argv = argv || process.argv
20-
const parser = yargs
11+
if (
12+
argv.length > 2 &&
13+
argv[2][0] !== '-'
14+
) {
15+
// fast-path around arg parsing! Don't even need to load yargs here.
16+
let parsedCmd
17+
let pkg
18+
if (argv[2].match(/^[a-z0-9_-]+$/i)) {
19+
parsedCmd = { registry: true, name: argv[2], raw: argv[2] }
20+
pkg = `${argv[2]}@latest`
21+
} else {
22+
npa = require('npm-package-arg')
23+
parsedCmd = npa(argv[2])
24+
pkg = [parsedCmd.toString()]
25+
}
26+
return {
27+
command: guessCmdName(parsedCmd),
28+
cmdOpts: argv.slice(3),
29+
packageRequested: false,
30+
cmdHadVersion: parsedCmd.name !== parsedCmd.raw,
31+
package: pkg,
32+
p: pkg,
33+
shell: false,
34+
install: true,
35+
npm: DEFAULT_NPM
36+
}
37+
}
38+
39+
npa = require('npm-package-arg')
40+
const usage = `
41+
$0 [${Y()`options`}] <${Y()`command`}>[@${Y()`version`}] [${Y()`command-arg`}]...
42+
43+
$0 [${Y()`options`}] [-p|--package <${Y()`package`}>]... <${Y()`command`}> [${Y()`command-arg`}]...
44+
45+
$0 [${Y()`options`}] -c '<${Y()`command-string`}>'
46+
47+
$0 --shell-auto-fallback [${Y()`shell`}]
48+
`
49+
50+
const parser = require('yargs')
2151
.usage(Y()`Execute binaries from npm packages.\n${usage}`)
2252
.option('package', {
2353
alias: 'p',
@@ -61,7 +91,7 @@ function parseArgs (argv) {
6191
.option('npm', {
6292
describe: Y()`npm binary to use for internal operations.`,
6393
type: 'string',
64-
default: path.resolve(__dirname, 'node_modules', '.bin', 'npm')
94+
default: DEFAULT_NPM
6595
})
6696
.version()
6797
.alias('version', 'v')
@@ -138,7 +168,7 @@ function parseArgs (argv) {
138168
}
139169
}
140170

141-
parseArgs.showHelp = () => yargs.showHelp()
171+
parseArgs.showHelp = () => require('yargs').showHelp()
142172

143173
module.exports._guessCmdName = guessCmdName
144174
function guessCmdName (spec) {

0 commit comments

Comments
 (0)