leo / args

Toolkit for building command line interfaces
https://npmjs.com/args
MIT License
461 stars 30 forks source link

[Bug] Passing the `--help` option with a subcommand prints the primary command help instead #156

Open shortercode opened 3 years ago

shortercode commented 3 years ago

I'm trying to build a CLI app which follows the PROGRAM CATEGORY COMMAND syntax pattern, while testing the help generation I discovered that the help option only ever runs for the primary command. By debugging the library I found this in parse.js

// If default help is allowed, check for it
if (this.config.help) {
  this.checkHelp()
}

which runs before the subcommand interpretation, causing the application the print the primary command help instead of the subcommand help and never call the subcommand.

Example code

app.js

#!/usr/bin/env node
import args from 'args';

args.command('sub', 'Do the subcommand');
args.parse(process.argv);

app-sub.js

#!/usr/bin/env node
import args from 'args';

args.parse(process.argv);

Output

> app --help
  Usage: app [options] [command]

  Commands:
    help      Display help
    sub  Do the subcommand
    version   Display version

  Options:
    -h, --help     Output usage information
    -v, --version  Output the version number
> app sub --help
   Usage: app [options] [command]

  Commands:
    help      Display help
    sub  Do the subcommand
    version   Display version

  Options:
    -h, --help     Output usage information
    -v, --version  Output the version number
> app sub help
   Usage: app sub [command]

  Commands:
    help      Display help
    version   Display version

  Options:
    -h, --help     Output usage information
    -v, --version  Output the version number

The help subcommand appears to work correctly, looking at the contents of checkHelp it appears to immediately run help if the option is set. Whereas the sub command is registered before and interpreted later in the subcommand interpretation.

Removing the if (this.optionWasProvided('help')) check from checkHelp and placing it after the subcommand checks in parse would resolve this issue and make the help option consistent with the help subcommand.

The same issue appears to be true for versions as well, but I haven't tested this.

shortercode commented 3 years ago

I believe it's possible to workaround this, but requires a chunk of boilerplate

#!/usr/bin/env node
import args from 'args';

args.command('help', 'Display help', () => args.showHelp());
args.option('help', 'Output usage information');

const opts = args.parse(process.argv, { help: false });

if (opts.help) {
  args.showHelp();
}

Which would need to be defined on any commands that have subcommands.