|
2 | 2 | 'use strict'; |
3 | 3 |
|
4 | 4 | import fs from 'fs'; |
5 | | -import mri from 'mri'; |
| 5 | +import yargs from 'yargs'; |
6 | 6 | import globby from 'globby'; |
7 | 7 | import getStream from 'get-stream'; |
8 | 8 |
|
9 | 9 | import astGrep from '..'; |
10 | 10 |
|
11 | | -const { _: [grepPattern, ...filePatterns], ...args } = mri( |
12 | | - process.argv.slice(2), |
13 | | - { |
14 | | - alias: { |
15 | | - a: 'anonymous', |
16 | | - }, |
17 | | - boolean: ['anonymous'], |
18 | | - } |
19 | | -); |
| 11 | +yargs |
| 12 | + .option('anonymous', { |
| 13 | + alias: 'a', |
| 14 | + boolean: true, |
| 15 | + describe: 'Ignore all names in the AST', |
| 16 | + }) |
| 17 | + .option('file', { |
| 18 | + alias: 'f', |
| 19 | + string: true, |
| 20 | + describe: 'Load pattern from a file', |
| 21 | + }) |
| 22 | + .option('debug', { string: true, hidden: true }) |
| 23 | + .help() |
| 24 | + .version() |
| 25 | + .example( |
| 26 | + `$0 -a 'fn()' file.js`, |
| 27 | + `Find all no-arg function calls in 'file.js'.` |
| 28 | + ) |
| 29 | + .example( |
| 30 | + `$0 -f pattern.js '**/*.js'`, |
| 31 | + `Match the pattern in 'pattern.js' across all JS files.` |
| 32 | + ) |
| 33 | + .example(`echo 'foo' | $0 'pattern'`, `Match 'pattern' on standard input.`); |
20 | 34 |
|
21 | | -async function run() { |
22 | | - if (!grepPattern) { |
23 | | - console.error('usage: ast-grep pattern [glob ...]'); |
24 | | - return 1; |
| 35 | +async function run({ _: [grepPattern, ...filePatterns], ...args }) { |
| 36 | + if (!grepPattern && !args.file) { |
| 37 | + yargs.showHelp(); |
| 38 | + return 2; |
| 39 | + } |
| 40 | + if (args.file && grepPattern) { |
| 41 | + filePatterns.unshift(grepPattern); |
| 42 | + grepPattern = fs.readFileSync(args.file, 'utf8'); |
25 | 43 | } |
| 44 | + |
26 | 45 | if (filePatterns.length) { |
27 | 46 | const files = globby.sync(filePatterns); |
28 | 47 | if (!files.length) { |
@@ -62,10 +81,10 @@ function displayMatches(matches, file) { |
62 | 81 | } |
63 | 82 | } |
64 | 83 |
|
65 | | -run() |
| 84 | +run(yargs.argv) |
66 | 85 | .then(process.exit) |
67 | 86 | .catch(error => { |
68 | | - if (args.debug) { |
| 87 | + if (yargs.argv.debug) { |
69 | 88 | console.error(error); |
70 | 89 | } else { |
71 | 90 | console.error(`ast-grep: ${error.toString()}`); |
|
0 commit comments