Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

How can I ensure that exactly one argument has been supplied? #1000

Closed
roxspring opened this issue Jul 20, 2019 · 4 comments
Closed

How can I ensure that exactly one argument has been supplied? #1000

roxspring opened this issue Jul 20, 2019 · 4 comments
Assignees
Milestone

Comments

@roxspring
Copy link

I've tried defining a command with a single required argument, and attempted to validate that exactly one source specified:

import * as program from 'commander';
import { version } from 'pjson';

program
  .version(version)
  .arguments('<source.md>')
  .action((source: string): void => {
    console.log('source=' + source);
    program.source = source;
  })
  .parse(process.argv);

console.log(program.args);
console.log(program.args.length);

if (program.args.length !== 1) {
  console.log('Invalid arguments');
  program.help();
}

console.log(program.source);

And running the program with no arguments, correctly prints 'Invalid arguments' since program.args.length is 0. But with 1 argument (program a) program.args.length is 2!? and outputs the following, claiming that program.args.length is 2!?

source=a
[
  'a',
  Command {
    ...
  }
]
2
Invalid arguments

Weirdly running with four arguments program a b c d also appears to drop the b argument somehow:

source=a
[
  'a',
  Command {
    ...
  },
  'c',
  'd'
]
4
Invalid arguments

So I guess I have two questions:

  1. Where's the second argument gone?
  2. (more importantly) how can I ensure that exactly one argument has been supplied?
@shadowspawn
Copy link
Collaborator

shadowspawn commented Jul 20, 2019

There is not currently error detection for excess arguments, and it is not currently easy to handle it yourself in a general way. In simple cases you can check the argument count of the original arguments (process.argv or program.rawArgs).

#749 covers the case with extra arguments passed to subcommands.

@shadowspawn
Copy link
Collaborator

There are improvements on the develop branch for the next release (#1030 and #1048).

@shadowspawn
Copy link
Collaborator

v4.0.0-0 prerelease published: #1067

@shadowspawn
Copy link
Collaborator

v4.0.0 has been released with a fix for program.args which was getting the command appended (matching the arguments passed to the action handler).

Hopefully more useful now!

Feel free to open a new issue if still problems, with new information and renewed interest.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants