Danielo515
Danielo515

Reputation: 7061

mandatory arguments with commander-js

I was wondering if it is possible to create a command on commander that looks like this

toggle (on|off) <args...>

Where (on|off) means that you must choose one or the other, mandatory.

Ideally, commander should take care of throwing the appropriate error and error message.

Upvotes: 0

Views: 1755

Answers (2)

shadowspawn
shadowspawn

Reputation: 3825

This is supported from Commander version 8.

import { Command, Argument } from 'commander';
const program = new Command();

program.command('toggle')
  .addArgument(new Argument('<state>', 'toggle state').choices(['on', 'off']))
  .argument('<args...>', 'further arguments')
  .action((state, args) => {
    console.log('state:', state);
    console.log('args:', args);
  });

program.parse();
$ node index.mjs toggle purple 1 2 3
error: command-argument value 'purple' is invalid for argument 'state'. Allowed choices are on, off.
$ node index.mjs toggle on 1 2 3    
state: on
args: [ '1', '2', '3' ]
$ node index.mjs toggle --help
Usage: index toggle [options] <state> <args...>

Arguments:
  state       toggle state (choices: "on", "off")
  args        further arguments

Options:
  -h, --help  display help for command

Upvotes: 0

Danielo515
Danielo515

Reputation: 7061

As @shadowspawn said, commander does not have support for this kind of construct. However you can simulate it by taking the mandatory parameter as an argument and make validation yourself. Then you can override the help output using the usage method. Something like this.

const assertOnOff = (str) => {
  if (!/^(on|off)$/.test(str)) {
    Logger.error('Toggle action must be either `on` or `off`');
    process.exit(1);
  }
};

const expandJson = str => JSON.stringify(JSON.parse(str), null, 2);

async function start(action, features) {
  assertOnOff(action);
  // ... do things
}


program.command('toggle <action> <FEATURE_NAME...>')
  .description('turns a feature on or off')
  .usage('(on|off) <FEATURE_NAME...>')
  .action(start);

Then when you call the command like this

toggle -h

You will get this help output

Usage: toggle (on|off) <FEATURE_NAME...>

turns a feature on or off

Options:
  -i, --institution [name]  Institution name
  -h, --help                output usage information

Upvotes: 1

Related Questions