Skip to content

Using Option.parseArgs with variadic and default options #1641

@joshuakarp

Description

@joshuakarp

I'm trying to create an Option that supports:

  • argument validation (through a parseArgs function)
  • being variadic
  • retrieval from an environment variable, and
  • a default value (when none of the prior sources are available)

However, I'm noticing that there's some interference between my parseArgs function and specification of a default value. Consider the following minimal example, where I hypothetically want to provide multiple ports in the arguments, but want to default to a single port 80 if none are provided:

#!/usr/bin/env node

import commander from 'commander';
const program = new commander.Command();

function parsePorts(curr, prev) {
  return prev.concat([parseInt(curr)]);
}

program.addOption(new commander.Option('-p, --port [number...]', 'specify port number')
  .argParser(parsePorts)
  .default([80])
);

program.parse();
console.log(program.opts());

Executing this with --port 123 124 provides the following output:

{ port: [ 80, 123, 124 ] }

Without the argParser added, I get the expected { port: [ '123', '124' ] }, but I'm no longer able to validate the provided arguments. It seems that argParser is also parsing the default port as well, and appending this to the returned list. Is there a way to circumvent this?

Metadata

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