Commander.js: Can not use action as option name

Created on 15 Aug 2019  路  7Comments  路  Source: tj/commander.js

Hi,

Consider following code:

    .command('command <name>')
    .option("-a, --action", "Action")
    .description('Demo')
    .action((name, options) => {
        console.log(`name: ${name}`);
        console.log(`action: ${options.action}`);
    });

When I call it like this: command NAME -a, the output will be:

name: NAME
action: undefined

But when I call it like this: command NAME -a -a, the output will be:

name: NAME
action: true

Now if I change .option("-a, --action", "Action") to .option("-a, --action_", "Action") and console.log(action: ${options.action}); to console.log(action: ${options.action_}); and call it like this command NAME -a, the output will be:

name: NAME
action: true

All 7 comments

The option values are added as properties on a Command object. This can conflict with properties which are already part of a Command, like in the case of an action option, the .action method!

This was a tradeoff in the original design. The work-around is to use a different option name.

The reference open bug is #183, and action mentioned back in #19.

I'm working on react related project and I have to use action as option name (_redux's action_) and using other name is not good for me. I think you should handle it, e.g: use something like __action.

Fixing the name pollution properly is hard due to existing client usage. The triage issue where I am collecting name pollution issues is #933. The draft Pull Request where I am experimenting is #951.

Great.

For now I used rawArgs to check if action is provided by user.

Added to the triage issue #933
Closing as duplicate of #183

Thank you for your contributions.

I have opened a Pull Request which allows storing option values separately rather than as command properties (access using .opts()), and passes the options (rather than the command) to the action handler.

See #1102

Added .storeOptionsAsProperties() and .passCommandToAction() in Commander 4.1.

See: https://github.com/tj/commander.js#avoiding-option-name-clashes

Was this page helpful?
0 / 5 - 0 ratings

Related issues

jeffschwartz picture jeffschwartz  路  3Comments

FerencH picture FerencH  路  4Comments

mwittig picture mwittig  路  4Comments

mathiasbynens picture mathiasbynens  路  3Comments

shadowspawn picture shadowspawn  路  3Comments