-
Notifications
You must be signed in to change notification settings - Fork 106
Implement command parsing (git style)
Lloyd Brookes edited this page Jan 25, 2018
·
3 revisions
We can use stopAtFirstUnknown
to parse an input argv
array several times, making complex scenarios possible.
As an example we'll recreate the git merge
command, which has this form.
$ git <command> [options]
This is the full example script. After the first commandLineArgs()
invocation, the _unknown
list is used as input to the next invocation.
const commandLineArgs = require('command-line-args')
/* first - parse the main command */
const mainDefinitions = [
{ name: 'command', defaultOption: true }
]
const mainOptions = commandLineArgs(mainDefinitions, { stopAtFirstUnknown: true })
const argv = mainOptions._unknown || []
console.log('mainOptions\n===========')
console.log(mainOptions)
/* second - parse the merge command options */
if (mainOptions.command === 'merge') {
const mergeDefinitions = [
{ name: 'squash', type: Boolean },
{ name: 'message', alias: 'm' }
]
const mergeOptions = commandLineArgs(mergeDefinitions, { argv })
console.log('\nmergeOptions\n============')
console.log(mergeOptions)
}
This command produces the following output.
$ node example.js merge --squash -m "This is my commit message"
mainOptions
===========
{ _unknown: [ '--squash', '-m', 'This is my commit message' ],
command: 'merge' }
mergeOptions
============
{ squash: true, message: 'This is my commit message' }