Brett Zamir
Brett Zamir

Reputation: 14345

Avoid commander parser complaining when no arguments are present and just show helpInfo

I'm migrating a package from a much older version of commander (v2.20.3)

program.command(`install [pkg]`)
  .alias(`i`)
  .action(installPackageOrLocal)
  .option(`-S, --save`, `Save to dependencies`)
  .option(`-D, --save-dev`, `Save to devDependencies`)
  .option(`--production`, `Will not install modules listed in devDependencies`)
  .option(`--test`, `Exit with code 1 if package limits like maxPackagesNumber or maxSizeBites exceeded`);

I'd like for the default (when calling the CLI with no arguments at all) to continue being the display of the help and no erring out, but currently it errs with:

.../npm-reflect/node_modules/.pnpm/[email protected]/node_modules/commander/lib/command.js:142 const [, name, args] = nameAndArgs.match(/([^ ]+) (.)/);

I was able to get the mostly desired behavior by adding:

program.command('help', {isDefault: true})
  .action(() => {
    program.help();
  })
  .command(`install [pkg]`)
  // ...

...but this seems to be polluting things in the help by listing a new "help" command. How can I avoid the parser complaining when no arguments are present yet without adding a new command?

Upvotes: 0

Views: 605

Answers (1)

shadowspawn
shadowspawn

Reputation: 3825

  1. The default behaviour in latest Commander is to display the help if you have subcommands and do not specify a subcommand. Which sounds like what you want! Not sure how you are getting an error, you might want to open a Commander issue for help.

  2. In general, if you want some custom behaviour for no arguments then it may be simple and easy to check yourself before calling parse(). e.g.

if (process.argv.length < 3)
  program.help(); // exits
program.parse(process.argv);

Upvotes: 2

Related Questions