Skip to content

allowUnknownOption handling in .parseOptions() #1945

Closed
@aweebit

Description

The docs says:

By default the option processing shows an error for an unknown option. To have an unknown option treated as an ordinary command-argument and continue looking for options, use .allowUnknownOption().

However, unknown options are not treated as command-arguments by .parseOptions() when allowUnknownOption is used. That can be shown by a simple example:

const program = new Command().allowUnknownOption();
console.log(program.parseOptions(['arg'])); // { operands: [ 'arg' ], unknown: [] }
console.log(program.parseOptions(['--option'])); // { operands: [], unknown: [ '--option' ] }

This might seem harmless, but actually has consequences. The following test from tests/command.helpCommand.test.js, line 24 would have to fail if unknown options were treated as described in the docs since caughtErr.code would equal to 'commander.unknownCommand' instead of 'commander.help'.

test('when program has subcommands and specify only unknown option then display help', () => {
  const program = new commander.Command();
  program
    .configureHelp({ formatHelp: () => '' })
    .exitOverride()
    .allowUnknownOption()
    .command('foo');
  let caughtErr;
  try {
    program.parse(['--unknown'], { from: 'user' });
  } catch (err) {
    caughtErr = err;
  }
  expect(caughtErr.code).toEqual('commander.help');
});

Some possible solutions I see:

  • treat unknown options as command-arguments in .parseOptions() as suggested by the docs and
    • either remove / change the test accordingly
    • or make .unknownCommand() treat options specially
  • remove the part about treatment as a command-argument from the docs so that it is not misleading anymore

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions