Commander.js: running an unknown subcommand does not fail

Created on 7 Sep 2015  路  9Comments  路  Source: tj/commander.js

This may be by design, but I would have expected calling:

command <unknown-sub-command> 

...to fail. But instead it just exits immediately, this can lead to confusion when tired as you might think your command isn't working, but instead it's just spelt incorrectly.

Is there a flag or something to enable this error. Or should I just make a white list of known commands and fail when the first parameter isn't a known sub command?

enhancement

Most helpful comment

Here's a couple of lines of code to add to your top level command to fail for unknown subcommands:

const _ = require('lodash');


const subCmd = _.head(program.args);
const cmds = _.map(program.commands, '_name');

if (!_.includes(cmds, subCmd)) {
  program.help();
}

All 9 comments

You should fail in your parent command explicitly. Remember that some programs may do processing in the parent command while still having subcommands.

Yeah, this is what I ended up doing. Added some git style:

Unknown command. Did you you mean:
  push
  clone
  ...

It would be nice to have it fail if your "program chain" contains only .command and no .option. Or have the ability to turn on failing when there isn't a matching subcommand.

That said, this is definitely a feature request. Perhaps we could work together to create a pull request?

Here's a couple of lines of code to add to your top level command to fail for unknown subcommands:

const _ = require('lodash');


const subCmd = _.head(program.args);
const cmds = _.map(program.commands, '_name');

if (!_.includes(cmds, subCmd)) {
  program.help();
}

@gangstead Yeah, I ended up doing something like what git does. Where it detects if there isn't a match and then does a fuzzy match and asks you if you meant to type:

That's much nicer than my quick and lazy solution. Is that code anywhere I can check it out?

It's for our internal cli. Here's a gist though with the relevant parts isolated:
https://gist.github.com/francoislaberge/80ca6cbc33232c438680

By default, unknown subcommands show an error message in the published pre-release of Commander v5.0.0 (#1163)

Commander v5.0.0 has been released.

https://github.com/tj/commander.js/releases/tag/v5.0.0

Was this page helpful?
0 / 5 - 0 ratings