Positional options (#1427)
Before adoption: this commit came in with the history the project adopted, so no landing records it.
* First cut at optionsBeforeArguments * Different to mix global options and subcommands, and options and arguments. * Different to mix global options and subcommands, and options and arguments. * Add _parseOptionsFollowingArguments * Use allow wording * Another try at naming * Exclude options from special processing, which fixes help * Add help checks for new option configuration * Rename after discovering needed for any positional options * Rework logic to hopefully cope with default commands. * Expand basic tests. Positional options are tricky! * Add first default command tests * Fill out more tests * Add setters, and throw when passThrough without enabling positional * Rename test file * Add TypeScript * Add tests. Fix help handling by making explicit. * Reorder tests * Use usual indentation * Make _enablePositionalOptions inherited to simpify nested commands * Add examples * Add tests for some less common setups * Test the boring true/false parameters * Fix typo * Add new section to README with parsing configuration. * Tweak wording in README
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
8 files+702 added−3 removed
- tests:+527 added−0 removed
- other:+175 added−3 removed
Provenance
- Commit
8ac84ec- Tree
e552b43- Author
John Gee <john@ruru.gen.nz>- Committer
GitHub <noreply@github.com>- Parent
1383870
8 files changed+702 added−3 removed
added:examples/pass-through-options.js+23 added
1234567891011121314151617181920212223#!/usr/bin/env node
// const { Command } = require('commander'); // (normal include)const { Command } = require('../'); // include commander in git clone of commander repoconst program = new Command();
program .arguments('<utility> [args...]') .passThroughOptions() .option('-d, --dry-run') .action((utility, args, options) => { const action = options.dryRun ? 'Would run' : 'Running'; console.log(`${action}: ${utility} ${args.join(' ')}`); });
program.parse();
// Try the following://// node pass-through-options.js git status// node pass-through-options.js git --version// node pass-through-options.js --dry-run git checkout -b new-branch// node pass-through-options.js git push --dry-runadded:examples/positional-options.js+27 added
123456789101112131415161718192021222324252627#!/usr/bin/env node
// const { Command } = require('commander'); // (normal include)const { Command } = require('../'); // include commander in git clone of commander repoconst program = new Command();
program .enablePositionalOptions() .option('-p, --progress');
program .command('upload <file>') .option('-p, --port <number>', 'port number', 80) .action((file, options) => { if (program.opts().progress) console.log('Starting upload...'); console.log(`Uploading ${file} to port ${options.port}`); if (program.opts().progress) console.log('Finished upload'); });
program.parse();
// Try the following://// node positional-options.js upload test.js// node positional-options.js -p upload test.js// node positional-options.js upload -p 8080 test.js// node positional-options.js -p upload -p 8080 test.jsmodified:tests/command.chain.test.js+12 added
139 unmodified linesExpand all140141142143144145146147148149150151152153154155156139 unmodified linesExpand all const program = new Command(); const result = program.configureOutput({ }); expect(result).toBe(program); });
test('when call .passThroughOptions() then returns this', () => { const program = new Command(); const result = program.passThroughOptions(); expect(result).toBe(program); });
test('when call .enablePositionalOptions() then returns this', () => { const program = new Command(); const result = program.enablePositionalOptions(); expect(result).toBe(program); });});added:tests/command.positionalOptions.test.js+515 added
1+const commander = require('../');2+3+// The changes to parsing for positional options are subtle, and took extra care to work with4+// implicit help and default commands. Lots of tests.5+6+describe('program with passThrough', () => {7+ function makeProgram() {8+ const program = new commander.Command();9+ program.passThroughOptions();10+ program11+ .option('-d, --debug')12+ .arguments('<args...>');13+ return program;14+ }15+16+ test('when option before command-argument then option parsed', () => {17+ const program = makeProgram();18+ program.parse(['--debug', 'arg'], { from: 'user' });19+ expect(program.args).toEqual(['arg']);20+ expect(program.opts().debug).toBe(true);21+ });22+23+ test('when known option after command-argument then option passed through', () => {24+ const program = makeProgram();25+ program.parse(['arg', '--debug'], { from: 'user' });26+ expect(program.args).toEqual(['arg', '--debug']);27+ expect(program.opts().debug).toBeUndefined();28+ });29+30+ test('when unknown option after command-argument then option passed through', () => {31+ const program = makeProgram();32+ program.parse(['arg', '--pass'], { from: 'user' });33+ expect(program.args).toEqual(['arg', '--pass']);34+ });35+36+ test('when action handler and unknown option after command-argument then option passed through', () => {37+ const program = makeProgram();38+ const mockAction = jest.fn();39+ program.action(mockAction);40+ program.parse(['arg', '--pass'], { from: 'user' });41+ expect(mockAction).toHaveBeenCalledWith(['arg', '--pass'], program.opts(), program);42+ });43+44+ test('when help option (without command-argument) then help called', () => {45+ const program = makeProgram();46+ const mockHelp = jest.fn(() => '');47+48+ program49+ .exitOverride()50+ .configureHelp({ formatHelp: mockHelp });51+ try {52+ program.parse(['--help'], { from: 'user' });53+ } catch (err) {54+ }55+ expect(mockHelp).toHaveBeenCalled();56+ });57+58+ test('when help option after command-argument then option passed through', () => {59+ const program = makeProgram();60+ program.parse(['arg', '--help'], { from: 'user' });61+ expect(program.args).toEqual(['arg', '--help']);62+ });63+64+ test('when version option after command-argument then option passed through', () => {65+ const program = makeProgram();66+ program.version('1.2.3');67+ program.parse(['arg', '--version'], { from: 'user' });68+ expect(program.args).toEqual(['arg', '--version']);69+ });70+});71+72+// -----------------------------------------------------------73+74+describe('program with positionalOptions and subcommand', () => {75+ function makeProgram() {76+ const program = new commander.Command();77+ program78+ .enablePositionalOptions()79+ .option('-s, --shared <value>')80+ .arguments('<args...>');81+ const sub = program82+ .command('sub')83+ .arguments('[arg]')84+ .option('-s, --shared <value>')85+ .action(() => {}); // Not used, but normal to have action handler on subcommand.86+ return { program, sub };87+ }88+89+ test('when global option before subcommand then global option parsed', () => {90+ const { program } = makeProgram();91+ program.parse(['--shared', 'program', 'sub'], { from: 'user' });92+ expect(program.opts().shared).toEqual('program');93+ });94+95+ test('when shared option after subcommand then parsed by subcommand', () => {96+ const { program, sub } = makeProgram();97+ program.parse(['sub', '--shared', 'local'], { from: 'user' });98+ expect(sub.opts().shared).toEqual('local');99+ expect(program.opts().shared).toBeUndefined();100+ });101+102+ test('when shared option after subcommand argument then parsed by subcommand', () => {103+ const { program, sub } = makeProgram();104+ program.parse(['sub', 'arg', '--shared', 'local'], { from: 'user' });105+ expect(sub.opts().shared).toEqual('local');106+ expect(sub.args).toEqual(['arg']);107+ expect(program.opts().shared).toBeUndefined();108+ });109+110+ test('when shared option before and after subcommand then both parsed', () => {111+ const { program, sub } = makeProgram();112+ program.parse(['--shared', 'program', 'sub', '--shared', 'local'], { from: 'user' });113+ expect(program.opts().shared).toEqual('program');114+ expect(sub.opts().shared).toEqual('local');115+ });116+117+ test.each([118+ [[], 1, 0],119+ [['sub'], 0, 0],120+ [['--help'], 1, 0],121+ [['sub', '--help'], 0, 1],122+ [['sub', 'foo', '--help'], 0, 1],123+ [['help'], 1, 0],124+ [['help', 'sub'], 0, 1]125+ ])('help: when user args %p then program/sub help called %p/%p', (userArgs, expectProgramHelpCount, expectSubHelpCount) => {126+ const { program, sub } = makeProgram();127+ const mockProgramHelp = jest.fn();128+ program129+ .exitOverride()130+ .configureHelp({ formatHelp: mockProgramHelp });131+ const mockSubHelp = jest.fn();132+ sub133+ .exitOverride()134+ .configureHelp({ formatHelp: mockSubHelp });135+136+ try {137+ program.parse(userArgs, { from: 'user' });138+ } catch (err) {139+ }140+ expect(mockProgramHelp).toHaveBeenCalledTimes(expectProgramHelpCount);141+ expect(mockSubHelp).toHaveBeenCalledTimes(expectSubHelpCount);142+ });143+});144+145+// ---------------------------------------------------------------146+147+describe('program with positionalOptions and default subcommand (called sub)', () => {148+ function makeProgram() {149+ const program = new commander.Command();150+ program151+ .enablePositionalOptions()152+ .option('-s, --shared')153+ .option('-g, --global')154+ .arguments('<args...>');155+ const sub = program156+ .command('sub', { isDefault: true })157+ .arguments('[args...]')158+ .option('-s, --shared')159+ .option('-d, --default')160+ .action(() => {}); // Not used, but normal to have action handler on subcommand.161+ program.command('another'); // Not used, but normal to have more than one subcommand if have a default.162+ return { program, sub };163+ }164+165+ test('when program option before sub option then program option read by program', () => {166+ const { program } = makeProgram();167+ program.parse(['--global', '--default'], { from: 'user' });168+ expect(program.opts().global).toBe(true);169+ });170+171+ test('when program option before sub option then sub option read by sub', () => {172+ const { program, sub } = makeProgram();173+ program.parse(['--global', '--default'], { from: 'user' });174+ expect(sub.opts().default).toBe(true);175+ });176+177+ test('when shared option before sub argument then option read by program', () => {178+ const { program } = makeProgram();179+ program.parse(['--shared', 'foo'], { from: 'user' });180+ expect(program.opts().shared).toBe(true);181+ });182+183+ test('when shared option after sub argument then option read by sub', () => {184+ const { program, sub } = makeProgram();185+ program.parse(['foo', '--shared'], { from: 'user' });186+ expect(sub.opts().shared).toBe(true);187+ });188+189+ test.each([190+ [[], 0, 0],191+ [['--help'], 1, 0],192+ [['help'], 1, 0]193+ ])('help: when user args %p then program/sub help called %p/%p', (userArgs, expectProgramHelpCount, expectSubHelpCount) => {194+ const { program, sub } = makeProgram();195+ const mockProgramHelp = jest.fn();196+ program197+ .exitOverride()198+ .configureHelp({ formatHelp: mockProgramHelp });199+ const mockSubHelp = jest.fn();200+ sub201+ .exitOverride()202+ .configureHelp({ formatHelp: mockSubHelp });203+204+ try {205+ program.parse(userArgs, { from: 'user' });206+ } catch (err) {207+ }208+ expect(mockProgramHelp).toHaveBeenCalledTimes(expectProgramHelpCount);209+ expect(mockSubHelp).toHaveBeenCalledTimes(expectSubHelpCount);210+ });211+});212+213+// ------------------------------------------------------------------------------214+215+describe('subcommand with passThrough', () => {216+ function makeProgram() {217+ const program = new commander.Command();218+ program219+ .enablePositionalOptions()220+ .option('-s, --shared <value>')221+ .arguments('<args...>');222+ const sub = program223+ .command('sub')224+ .passThroughOptions()225+ .arguments('[args...]')226+ .option('-s, --shared <value>')227+ .option('-d, --debug')228+ .action(() => {}); // Not used, but normal to have action handler on subcommand.229+ return { program, sub };230+ }231+232+ test('when option before command-argument then option parsed', () => {233+ const { program, sub } = makeProgram();234+ program.parse(['sub', '--debug', 'arg'], { from: 'user' });235+ expect(sub.args).toEqual(['arg']);236+ expect(sub.opts().debug).toBe(true);237+ });238+239+ test('when known option after command-argument then option passed through', () => {240+ const { program, sub } = makeProgram();241+ program.parse(['sub', 'arg', '--debug'], { from: 'user' });242+ expect(sub.args).toEqual(['arg', '--debug']);243+ expect(sub.opts().debug).toBeUndefined();244+ });245+246+ test('when unknown option after command-argument then option passed through', () => {247+ const { program, sub } = makeProgram();248+ program.parse(['sub', 'arg', '--pass'], { from: 'user' });249+ expect(sub.args).toEqual(['arg', '--pass']);250+ });251+252+ test('when action handler and unknown option after command-argument then option passed through', () => {253+ const { program, sub } = makeProgram();254+ const mockAction = jest.fn();255+ sub.action(mockAction);256+ program.parse(['sub', 'arg', '--pass'], { from: 'user' });257+ expect(mockAction).toHaveBeenCalledWith(['arg', '--pass'], sub.opts(), sub);258+ });259+260+ test('when help option after command-argument then option passed through', () => {261+ const { program, sub } = makeProgram();262+ program.parse(['sub', 'arg', '--help'], { from: 'user' });263+ expect(sub.args).toEqual(['arg', '--help']);264+ });265+266+ test('when version option after command-argument then option passed through', () => {267+ const { program, sub } = makeProgram();268+ program.version('1.2.3');269+ program.parse(['sub', 'arg', '--version'], { from: 'user' });270+ expect(sub.args).toEqual(['arg', '--version']);271+ });272+273+ test('when shared option before sub and after sub and after sub parameter then all three parsed', () => {274+ const { program, sub } = makeProgram();275+ program.parse(['--shared=global', 'sub', '--shared=local', 'arg', '--shared'], { from: 'user' });276+ expect(program.opts().shared).toEqual('global');277+ expect(sub.opts().shared).toEqual('local');278+ expect(sub.args).toEqual(['arg', '--shared']);279+ });280+});281+282+// ------------------------------------------------------------------------------283+284+describe('default command with passThrough', () => {285+ function makeProgram() {286+ const program = new commander.Command();287+ program288+ .enablePositionalOptions();289+ const sub = program290+ .command('sub', { isDefault: true })291+ .passThroughOptions()292+ .arguments('[args...]')293+ .option('-d, --debug')294+ .action(() => {}); // Not used, but normal to have action handler on subcommand.295+ return { program, sub };296+ }297+298+ test('when option before command-argument then option parsed', () => {299+ const { program, sub } = makeProgram();300+ program.parse(['--debug', 'arg'], { from: 'user' });301+ expect(sub.args).toEqual(['arg']);302+ expect(sub.opts().debug).toBe(true);303+ });304+305+ test('when known option after command-argument then option passed through', () => {306+ const { program, sub } = makeProgram();307+ program.parse(['arg', '--debug'], { from: 'user' });308+ expect(sub.args).toEqual(['arg', '--debug']);309+ expect(sub.opts().debug).toBeUndefined();310+ });311+312+ test('when unknown option after command-argument then option passed through', () => {313+ const { program, sub } = makeProgram();314+ program.parse(['arg', '--pass'], { from: 'user' });315+ expect(sub.args).toEqual(['arg', '--pass']);316+ });317+318+ test('when action handler and unknown option after command-argument then option passed through', () => {319+ const { program, sub } = makeProgram();320+ const mockAction = jest.fn();321+ sub.action(mockAction);322+ program.parse(['arg', '--pass'], { from: 'user' });323+ expect(mockAction).toHaveBeenCalledWith(['arg', '--pass'], sub.opts(), sub);324+ });325+});326+327+// ------------------------------------------------------------------------------328+329+describe('program with action handler and positionalOptions and subcommand', () => {330+ function makeProgram() {331+ const program = new commander.Command();332+ program333+ .enablePositionalOptions()334+ .option('-g, --global')335+ .arguments('<args...>')336+ .action(() => {});337+ const sub = program338+ .command('sub')339+ .arguments('[arg]')340+ .action(() => {});341+ return { program, sub };342+ }343+344+ test('when global option before parameter then global option parsed', () => {345+ const { program } = makeProgram();346+ program.parse(['--global', 'foo'], { from: 'user' });347+ expect(program.opts().global).toBe(true);348+ });349+350+ test('when global option after parameter then global option parsed', () => {351+ const { program } = makeProgram();352+ program.parse(['foo', '--global'], { from: 'user' });353+ expect(program.opts().global).toBe(true);354+ });355+356+ test('when global option after parameter with same name as subcommand then global option parsed', () => {357+ const { program } = makeProgram();358+ program.parse(['foo', 'sub', '--global'], { from: 'user' });359+ expect(program.opts().global).toBe(true);360+ });361+});362+363+// ------------------------------------------------------------------------------364+365+test('when program not positional and turn on passthrough in subcommand then error', () => {366+ const program = new commander.Command();367+ const sub = program.command('sub');368+369+ expect(() => {370+ sub.passThroughOptions();371+ }).toThrow();372+});373+374+// ------------------------------------------------------------------------------375+376+describe('program with action handler and passThrough and subcommand', () => {377+ function makeProgram() {378+ const program = new commander.Command();379+ program380+ .passThroughOptions()381+ .option('-g, --global')382+ .arguments('<args...>')383+ .action(() => {});384+ const sub = program385+ .command('sub')386+ .arguments('[arg]')387+ .option('-g, --group')388+ .option('-d, --debug')389+ .action(() => {});390+ return { program, sub };391+ }392+393+ test('when global option before parameter then global option parsed', () => {394+ const { program } = makeProgram();395+ program.parse(['--global', 'foo'], { from: 'user' });396+ expect(program.opts().global).toBe(true);397+ });398+399+ test('when global option after parameter then passed through', () => {400+ const { program } = makeProgram();401+ program.parse(['foo', '--global'], { from: 'user' });402+ expect(program.args).toEqual(['foo', '--global']);403+ });404+405+ test('when subcommand option after subcommand then option parsed', () => {406+ const { program, sub } = makeProgram();407+ program.parse(['sub', '--debug'], { from: 'user' });408+ expect(sub.opts().debug).toBe(true);409+ });410+411+ // This is somewhat of a side-affect of supporting previous test.412+ test('when shared option after subcommand then parsed by subcommand', () => {413+ const { program, sub } = makeProgram();414+ program.parse(['sub', '-g'], { from: 'user' });415+ expect(sub.opts().group).toBe(true);416+ expect(program.opts().global).toBeUndefined();417+ });418+});419+420+// ------------------------------------------------------------------------------421+422+describe('program with allowUnknownOption', () => {423+ test('when passThroughOptions and unknown option then arguments from unknown passed through', () => {424+ const program = new commander.Command();425+ program426+ .passThroughOptions()427+ .allowUnknownOption()428+ .option('--debug');429+430+ program.parse(['--unknown', '--debug'], { from: 'user' });431+ expect(program.args).toEqual(['--unknown', '--debug']);432+ });433+434+ test('when positionalOptions and unknown option then known options then known option parsed', () => {435+ const program = new commander.Command();436+ program437+ .enablePositionalOptions()438+ .allowUnknownOption()439+ .option('--debug');440+441+ program.parse(['--unknown', '--debug'], { from: 'user' });442+ expect(program.opts().debug).toBe(true);443+ expect(program.args).toEqual(['--unknown']);444+ });445+});446+447+// ------------------------------------------------------------------------------448+449+describe('passThroughOptions(xxx) and option after command-argument', () => {450+ function makeProgram() {451+ const program = new commander.Command();452+ program453+ .option('-d, --debug')454+ .arguments('<args...>');455+ return program;456+ }457+458+ test('when passThroughOptions() then option passed through', () => {459+ const program = makeProgram();460+ program.passThroughOptions();461+ program.parse(['foo', '--debug'], { from: 'user' });462+ expect(program.args).toEqual(['foo', '--debug']);463+ });464+465+ test('when passThroughOptions(true) then option passed through', () => {466+ const program = makeProgram();467+ program.passThroughOptions(true);468+ program.parse(['foo', '--debug'], { from: 'user' });469+ expect(program.args).toEqual(['foo', '--debug']);470+ });471+472+ test('when passThroughOptions(false) then option parsed', () => {473+ const program = makeProgram();474+ program.passThroughOptions(false);475+ program.parse(['foo', '--debug'], { from: 'user' });476+ expect(program.args).toEqual(['foo']);477+ expect(program.opts().debug).toEqual(true);478+ });479+});480+481+// ------------------------------------------------------------------------------482+483+describe('enablePositionalOptions(xxx) and shared option after subcommand', () => {484+ function makeProgram() {485+ const program = new commander.Command();486+ program487+ .option('-d, --debug');488+ const sub = program489+ .command('sub')490+ .option('-d, --debug');491+ return { program, sub };492+ }493+494+ test('when enablePositionalOptions() then option parsed by subcommand', () => {495+ const { program, sub } = makeProgram();496+ program.enablePositionalOptions();497+ program.parse(['sub', '--debug'], { from: 'user' });498+ expect(sub.opts().debug).toEqual(true);499+ });500+501+ test('when enablePositionalOptions(true) then option parsed by subcommand', () => {502+ const { program, sub } = makeProgram();503+ program.enablePositionalOptions(true);504+ program.parse(['sub', '--debug'], { from: 'user' });505+ expect(sub.opts().debug).toEqual(true);506+ });507+508+ test('when enablePositionalOptions(false) then option parsed by program', () => {509+ const { program, sub } = makeProgram();510+ program.enablePositionalOptions(false);511+ program.parse(['sub', '--debug'], { from: 'user' });512+ expect(sub.opts().debug).toBeUndefined();513+ expect(program.opts().debug).toEqual(true);514+ });515+});modified:typings/commander-tests.ts+8 added
149 unmodified lines150 // allowExcessArguments151 const allowExcessArgumentsThis1: commander.Command = program.allowExcessArguments();152 const allowExcessArgumentsThis2: commander.Command = program.allowExcessArguments(false);153 154+// enablePositionalOptions155+const enablePositionalOptionsThis1: commander.Command = program.enablePositionalOptions();156+const enablePositionalOptionsThis2: commander.Command = program.enablePositionalOptions(false);157+158+// passThroughOptions159+const passThroughOptionsThis1: commander.Command = program.passThroughOptions();160+const passThroughOptionsThis2: commander.Command = program.passThroughOptions(false);161+162 // parse163 const parseThis1: commander.Command = program.parse();164 const parseThis2: commander.Command = program.parse(process.argv);165 const parseThis3: commander.Command = program.parse(['node', 'script.js'], { from: 'node' });177 unmodified linesmodified:typings/index.d.ts+21 added
407 unmodified lines408 */409 allowExcessArguments(allowExcess?: boolean): this;410 411 /**412+ * Enable positional options. Positional means global options are specified before subcommands which lets413+ * subcommands reuse the same option names, and also enables subcommands to turn on passThroughOptions.414+ *415+ * The default behaviour is non-positional and global options may appear anywhere on the command line.416+ *417+ * @returns `this` command for chaining418+ */419+ enablePositionalOptions(positional?: boolean): this;420+421+ /**422+ * Pass through options that come after command-arguments rather than treat them as command-options,423+ * so actual command-options come before command-arguments. Turning this on for a subcommand requires424+ * positional options to have been enabled on the program (parent commands).425+ *426+ * The default behaviour is non-positional and options may appear before or after command-arguments.427+ *428+ * @returns `this` command for chaining429+ */430+ passThroughOptions(passThrough?: boolean): this;431+432+ /**433 * Parse `argv`, setting options and invoking commands when defined.434 *435 * The default expectation is that the arguments are from node and have the application as argv[0]436 * and the script being run in argv[1], with user parameters after that.185 unmodified linesmodified:index.js+61 added-2 removed
550 unmodified lines551 this._aliases = [];552 this._combineFlagAndOptionalValue = true;553 this._description = '';554 this._argsDescription = undefined;555+ this._enablePositionalOptions = false;556+ this._passThroughOptions = false;557 558 // see .configureOutput() for docs559 this._outputConfiguration = {560 writeOut: (str) => process.stdout.write(str),73 unmodified lines634 cmd._helpConfiguration = this._helpConfiguration;635 cmd._exitCallback = this._exitCallback;636 cmd._storeOptionsAsProperties = this._storeOptionsAsProperties;637 cmd._combineFlagAndOptionalValue = this._combineFlagAndOptionalValue;638+ cmd._enablePositionalOptions = this._enablePositionalOptions;639 640 cmd._executableFile = opts.executableFile || null; // Custom name for executable file, set missing to null to match constructor641 this.commands.push(cmd);642 cmd._parseExpectedArgs(args);493 unmodified lines1136 return this;1137 };1138 1139 /**1140+ * Enable positional options. Positional means global options are specified before subcommands which lets1141+ * subcommands reuse the same option names, and also enables subcommands to turn on passThroughOptions.1142+ * The default behaviour is non-positional and global options may appear anywhere on the command line.1143+ *1144+ * @param {Boolean} [positional=true]1145+ */1146+ enablePositionalOptions(positional = true) {1147+ this._enablePositionalOptions = !!positional;1148+ return this;1149+ };1150+1151+ /**1152+ * Pass through options that come after command-arguments rather than treat them as command-options,1153+ * so actual command-options come before command-arguments. Turning this on for a subcommand requires1154+ * positional options to have been enabled on the program (parent commands).1155+ * The default behaviour is non-positional and options may appear before or after command-arguments.1156+ *1157+ * @param {Boolean} [passThrough=true]1158+ * for unknown options.1159+ */1160+ passThroughOptions(passThrough = true) {1161+ this._passThroughOptions = !!passThrough;1162+ if (!!this.parent && passThrough && !this.parent._enablePositionalOptions) {1163+ throw new Error('passThroughOptions can not be used without turning on enablePositionOptions for parent command(s)');1164+ }1165+ return this;1166+ };1167+1168+ /**1169 * Whether to store option values as properties on command object,1170 * or store separately (specify false). In both cases the option values can be accessed using .opts().1171 *1172 * @param {boolean} [storeAsProperties=true]467 unmodified lines1640 continue;1641 }1642 }1643 1612- // looks like an option but unknown, unknowns from here1613- if (arg.length > 1 && arg[0] === '-') {1644+ // Not a recognised option by this command.1645+ // Might be a command-argument, or subcommand option, or unknown option, or help command or option.1646+1647+ // An unknown option means further arguments also classified as unknown so can be reprocessed by subcommands.1648+ if (maybeOption(arg)) {1649 dest = unknown;1650 }1651 1652+ // If using positionalOptions, stop processing our options at subcommand.1653+ if ((this._enablePositionalOptions || this._passThroughOptions) && operands.length === 0 && unknown.length === 0) {1654+ if (this._findCommand(arg)) {1655+ operands.push(arg);1656+ if (args.length > 0) unknown.push(...args);1657+ break;1658+ } else if (arg === this._helpCommandName && this._hasImplicitHelpCommand()) {1659+ operands.push(arg);1660+ if (args.length > 0) operands.push(...args);1661+ break;1662+ } else if (this._defaultCommandName) {1663+ unknown.push(arg);1664+ if (args.length > 0) unknown.push(...args);1665+ break;1666+ }1667+ }1668+1669+ // If using passThroughOptions, stop processing options at first command-argument.1670+ if (this._passThroughOptions) {1671+ dest.push(arg);1672+ if (args.length > 0) dest.push(...args);1673+ break;1674+ }1675+1676 // add arg1677 dest.push(arg);1678 }1679 521 unmodified linesmodified:Readme.md+35 added-1 removed
33 unmodified lines34 - [More configuration](#more-configuration-1)35 - [Custom event listeners](#custom-event-listeners)36 - [Bits and pieces](#bits-and-pieces)37 - [.parse() and .parseAsync()](#parse-and-parseasync)38+ - [Parsing Configuration](#parsing-configuration)39 - [Legacy options as properties](#legacy-options-as-properties)40 - [TypeScript](#typescript)41 - [createCommand()](#createcommand)42 - [Import into ECMAScript Module](#import-into-ecmascript-module)41 unmodified lines84 For example `-a -b -p 80` may be written as `-ab -p80` or even `-abp80`.85 86 You can use `--` to indicate the end of the options, and any remaining arguments will be used without being interpreted.87 87-Options on the command line are not positional, and can be specified before or after other arguments.88+By default options on the command line are not positional, and can be specified before or after other arguments.89 90 ### Common option types, boolean and value91 92 The two most used option types are a boolean option, and an option which takes its value591 unmodified lines684 program.parse(); // Implicit, and auto-detect electron685 program.parse(['-f', 'filename'], { from: 'user' });686 ```687 688+### Parsing Configuration689+690+If the default parsing does not suit your needs, there are some behaviours to support other usage patterns.691+692+By default program options are recognised before and after subcommands. To only look for program options before subcommands, use `.enablePositionalOptions()`. This lets you use693+an option for a different purpose in subcommands.694+695+Example file: [positional-options.js](./examples/positional-options.js)696+697+With positional options, the `-b` is a program option in the first line and a subcommand option in the second:698+699+```sh700+program -b subcommand701+program subcommand -b702+```703+704+By default options are recognised before and after command-arguments. To only process options that come705+before the command-arguments, use `.passThroughOptions()`. This lets you pass the arguments and following options through to another program706+without needing to use `--` to end the option processing. 707+To use pass through options in a subcommand, the program needs to enable positional options.708+709+Example file: [pass-through-options.js](./examples/pass-through-options.js)710+711+With pass through options, the `--port=80` is a program option in the line and passed through as a command-argument in the second:712+713+```sh714+program --port=80 arg715+program arg --port=80716+```717+718+719+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()`. This lets you mix known and unknown options.720+721 ### Legacy options as properties 722 723 Before Commander 7, the option values were stored as properties on the command.724 This was convenient to code but the downside was possible clashes with187 unmodified lines