Skip to content

Implement command parsing (git style)

Lloyd Brookes edited this page Jan 17, 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.

$ git <command> [options]

Example

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 */
let optionDefinitions = [
  { name: 'command', defaultOption: true }
]
const mainOptions = commandLineArgs(optionDefinitions, { stopAtFirstUnknown: true })
let argv = mainOptions._unknown || []

console.log('mainOptions')
console.log('===========')
console.log(mainOptions)

/* second - parse the merge command options */
if (mainOptions.command === 'merge') {
  optionDefinitions = [
    { name: 'squash', type: Boolean },
    { name: 'message', alias: 'm', type: String, multiple: true }
  ]
  const mergeOptions = commandLineArgs(optionDefinitions, { argv })

  console.log('\nmergeOptions')
  console.log('==========')
  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' ] }