nodeca / argparse

CLI arguments parser for node.js. JS port of python's argparse module.
Other
487 stars 73 forks source link

Action.call: is 'values' a string or an array of strings? #135

Closed cakoose closed 5 years ago

cakoose commented 5 years ago

I'm trying to create a custom Action class and ran into something unexpected:

const argparse = require('argparse');

class MyAction extends argparse.Action {
    call(parser, namespace, values, optionString) {
        console.log(JSON.stringify({optionString, values}));
    }
}

const parser = argparse.ArgumentParser();
parser.addArgument(['-a'], {action: MyAction});
parser.addArgument(['-b'], {action: MyAction, nargs: '*'});
parser.parseArgs(['-a', 'x', '-b', 'y', '-b', 'z']);

Output:

{"optionString":"-a","values":"x"}
{"optionString":"-b","values":["y"]}
{"optionString":"-b","values":["z"]}

I'm not sure why values is an array in the nargs='*' case. Are there any circumstances where values will be something other than a 1-element array?

(BTW, I'm trying to add support for the Action class to the DefinitelyTyped type definitions for argparse. I'm stuck on this string vs Array<string> situation.)

cakoose commented 5 years ago

Oh, I think I figured it out:

parser.parseArgs(['-a', 'x', '-b', 'y', 'yy', '-b', 'z', 'zz']);

Output:

{"optionString":"-a","values":"x"}
{"optionString":"-b","values":["y","yy"]}
{"optionString":"-b","values":["z","zz"]}