Skip to content
Myr

Refactor help option implementation to hold actual Option (#2006)

Before adoption: this commit came in with the history the project adopted, so no landing records it.

authored by John Gee · committed by GitHub · parent ff08a02 · Browse files · 11 files+184 added−84 removed
This commit

State

Before adoption: this commit came in with the history the project adopted, so no landing records it.

Diff stats

11 files+184 added−84 removed

  • tests:+70 added−8 removed
  • other:+114 added−76 removed

11 files+184 added−84 removed

modified:lib/command.js+55 added-27 removed
5 unmodified lines
67const { Argument, humanReadableArgName } = require('./argument.js');8const { CommanderError } = require('./error.js');9const { Help } = require('./help.js');10const { Option, splitOptionFlags, DualOptions } = require('./option.js');10const { Option, DualOptions } = require('./option.js');11const { suggestSimilar } = require('./suggestSimilar');1213class Command extends EventEmitter {14 /**
50 unmodified lines
65 outputError: (str, write) => write(str)66 };6768 this._hidden = false;69 this._hasHelpOption = true;70 this._helpFlags = '-h, --help';71 this._helpDescription = 'display help for command';72 this._helpShortFlag = '-h';73 this._helpLongFlag = '--help';69 /** @type {(Option | null | undefined)} */70 this._helpOption = undefined; // Lazy created on demand. May be null if help option is disabled.71 this._addImplicitHelpCommand = undefined; // undecided whether true or false yet, not inherited72 /** @type {Command} */73 this._helpCommand = undefined; // lazy initialised, inherited74 this._helpConfiguration = {};
8 unmodified lines
83 * @return {Command} `this` command for chaining84 */85 copyInheritedSettings(sourceCommand) {86 this._outputConfiguration = sourceCommand._outputConfiguration;90 this._hasHelpOption = sourceCommand._hasHelpOption;91 this._helpFlags = sourceCommand._helpFlags;92 this._helpDescription = sourceCommand._helpDescription;93 this._helpShortFlag = sourceCommand._helpShortFlag;94 this._helpLongFlag = sourceCommand._helpLongFlag;87 this._helpOption = sourceCommand._helpOption;88 this._helpCommand = sourceCommand._helpCommand;89 this._helpConfiguration = sourceCommand._helpConfiguration;90 this._exitCallback = sourceCommand._exitCallback;91 this._storeOptionsAsProperties = sourceCommand._storeOptionsAsProperties;
1089 unmodified lines
1181 }11821183 // Fallback to parsing the help flag to invoke the help.1184 return this._dispatchSubcommand(subcommandName, [], [1192 this._helpLongFlag || this._helpShortFlag1185 this._getHelpOption()?.long ?? this._getHelpOption()?.short ?? '--help'1186 ]);1187 }11881189 /**
803 unmodified lines
1993 const args = this.registeredArguments.map((arg) => {1994 return humanReadableArgName(arg);1995 });1996 return [].concat(2004 (this.options.length || this._hasHelpOption ? '[options]' : []),1997 (this.options.length || (this._helpOption !== null) ? '[options]' : []),1998 (this.commands.length ? '[command]' : []),1999 (this.registeredArguments.length ? args : [])2000 ).join(' ');2001 }
112 unmodified lines
2114 }2115 }2116 context.write(helpInformation);21172125 if (this._helpLongFlag) {2126 this.emit(this._helpLongFlag); // deprecated2118 if (this._getHelpOption()?.long) {2119 this.emit(this._getHelpOption().long); // deprecated2120 }2121 this.emit('afterHelp', context);2122 this._getCommandAndAncestors().forEach(command => command.emit('afterAllHelp', context));2123 }21242125 /**2133 * You can pass in flags and a description to override the help2134 * flags and help description for your command. Pass in false to2135 * disable the built-in help option.2126 * You can pass in flags and a description to customise the built-in help option.2127 * Pass in false to disable the built-in help option.2128 *2129 * @example2130 * program.helpOption('-?, --help' 'show help'); // customise2131 * program.helpOption(false); // disable2132 *2137 * @param {(string | boolean)} [flags]2133 * @param {(string | boolean)} flags2134 * @param {string} [description]2135 * @return {Command} `this` command for chaining2136 */21372138 helpOption(flags, description) {2139 // Support disabling built-in help option.2140 if (typeof flags === 'boolean') {2144 this._hasHelpOption = flags;2141 if (flags) {2142 this._helpOption = this._helpOption ?? undefined; // preserve existing option2143 } else {2144 this._helpOption = null; // disable2145 }2146 return this;2147 }2147 this._helpFlags = flags || this._helpFlags;2148 this._helpDescription = description || this._helpDescription;21482150 const helpFlags = splitOptionFlags(this._helpFlags);2151 this._helpShortFlag = helpFlags.shortFlag;2152 this._helpLongFlag = helpFlags.longFlag;2149 // Customise flags and description.2150 flags = flags ?? '-h, --help';2151 description = description ?? 'display help for command';2152 this._helpOption = this.createOption(flags, description);21532154 return this;2155 }21562157 /**2158 * Lazy create help option.2159 * Returns null if has been disabled with .helpOption(false).2160 *2161 * @returns {(Option | null)} the help option2162 * @package internal use only2163 */2164 _getHelpOption() {2165 // Lazy create help option on demand.2166 if (this._helpOption === undefined) {2167 this.helpOption(undefined, undefined);2168 }2169 return this._helpOption;2170 }21712172 /**2173 * Supply your own option to use for the built-in help option.2174 * This is an alternative to using helpOption() to customise the flags and description etc.2175 *2176 * @param {Option} option2177 * @return {Command} `this` command for chaining2178 */2179 addHelpOption(option) {2180 this._helpOption = option;2181 return this;2182 }21832184 /**2185 * Output help information and exit.2186 *2187 * Outputs built-in help, and custom text added using `.addHelpText()`.2188 *
49 unmodified lines
2238 * @private2239 */22402241 _outputHelpIfRequested(args) {2215 const helpOption = this._hasHelpOption && args.find(arg => arg === this._helpLongFlag || arg === this._helpShortFlag);2216 if (helpOption) {2242 const helpOption = this._getHelpOption();2243 const helpRequested = helpOption && args.find(arg => helpOption.is(arg));2244 if (helpRequested) {2245 this.outputHelp();2246 // (Do not have all displayed text available so only passing placeholder.)2247 this._exit(0, 'commander.helpDisplayed', '(outputHelp)');2248 }
51 unmodified lines
modified:lib/help.js+12 added-12 removed
61 unmodified lines
62 */6364 visibleOptions(cmd) {65 const visibleOptions = cmd.options.filter((option) => !option.hidden);66 // Implicit help67 const showShortHelpFlag = cmd._hasHelpOption && cmd._helpShortFlag && !cmd._findOption(cmd._helpShortFlag);68 const showLongHelpFlag = cmd._hasHelpOption && !cmd._findOption(cmd._helpLongFlag);69 if (showShortHelpFlag || showLongHelpFlag) {70 let helpOption;71 if (!showShortHelpFlag) {72 helpOption = cmd.createOption(cmd._helpLongFlag, cmd._helpDescription);73 } else if (!showLongHelpFlag) {74 helpOption = cmd.createOption(cmd._helpShortFlag, cmd._helpDescription);75 } else {76 helpOption = cmd.createOption(cmd._helpFlags, cmd._helpDescription);66 // Built-in help option.67 const helpOption = cmd._getHelpOption();68 if (helpOption && !helpOption.hidden) {69 // Automatically hide conflicting flags. Bit dubious but a historical behaviour that is convenient for single-command programs.70 const removeShort = helpOption.short && cmd._findOption(helpOption.short);71 const removeLong = helpOption.long && cmd._findOption(helpOption.long);72 if (!removeShort && !removeLong) {73 visibleOptions.push(helpOption); // no changes needed74 } else if (helpOption.long && !removeLong) {75 visibleOptions.push(cmd.createOption(helpOption.long, helpOption.description));76 } else if (helpOption.short && !removeShort) {77 visibleOptions.push(cmd.createOption(helpOption.short, helpOption.description));78 }78 visibleOptions.push(helpOption);79 }80 if (this.sortOptions) {81 visibleOptions.sort(this.compareOptions);82 }
375 unmodified lines
modified:lib/option.js-1 removed
322 unmodified lines
323 return { shortFlag, longFlag };324}325326exports.Option = Option;327exports.splitOptionFlags = splitOptionFlags;327exports.DualOptions = DualOptions;
added:tests/command.addHelpOption.test.js+54 added
modified:tests/command.chain.test.js+9 added-2 removed
170 unmodified lines
171 const result = program.name('easy');172 expect(result).toBe(program);173 });174175 test('when call .helpOption() then returns this', () => {175 test('when call .helpOption(flags) then returns this', () => {176 const program = new Command();177 const flags = '-h, --help';177 const result = program.helpOption(false);178 const result = program.helpOption(flags);179 expect(result).toBe(program);180 });181182 test('when call .addHelpOption() then returns this', () => {183 const program = new Command();184 const result = program.addHelpOption(new Option('-h, --help'));185 expect(result).toBe(program);186 });187188 test('when call .addHelpText() then returns this', () => {189 const program = new Command();190 const result = program.addHelpText('before', 'example');191 expect(result).toBe(program);
69 unmodified lines
modified:tests/command.copySettings.test.js+7 added-6 removed
modified:typings/index.d.ts+6 added
846 unmodified lines
847 */848 helpOption(flags?: string | boolean, description?: string): this;849850 /**851 * Supply your own option to use for the built-in help option.852 * This is an alternative to using helpOption() to customise the flags and description etc.853 */854 addHelpOption(option: Option): this;855856 /**857 * Output help information and exit.858 *859 * Outputs built-in help, and custom text added using `.addHelpText()`.860 */
39 unmodified lines
modified:typings/index.test-d.ts+3 added
308 unmodified lines
309expectType<commander.Command>(program.helpOption('-h,--help', 'custom description'));310expectType<commander.Command>(program.helpOption(undefined, 'custom description'));311expectType<commander.Command>(program.helpOption(false));312313// addHelpOption314expectType<commander.Command>(program.addHelpOption(new commander.Option('-h,--help')));315316// addHelpText317expectType<commander.Command>(program.addHelpText('after', 'text'));318expectType<commander.Command>(program.addHelpText('afterAll', 'text'));319expectType<commander.Command>(program.addHelpText('before', () => 'before'));
194 unmodified lines
modified:package-lock.json+35 added-35 removed
13 unmodified lines
14 "@typescript-eslint/eslint-plugin": "^6.7.5",15 "@typescript-eslint/parser": "^6.7.5",16 "eslint": "^8.30.0",17 "eslint-config-standard": "^17.0.0",18 "eslint-config-standard-with-typescript": "^39.1.1",18 "eslint-config-standard-with-typescript": "^40.0.0",19 "eslint-plugin-import": "^2.26.0",20 "eslint-plugin-jest": "^27.1.7",21 "eslint-plugin-n": "^16.2.0",22 "eslint-plugin-promise": "^6.1.1",
724 unmodified lines
747 "url": "https://opencollective.com/eslint"748 }749 },750 "node_modules/@eslint/js": {751 "version": "8.53.0",752 "resolved": "https://registry.npmjs.org/@eslint/js/-/js-8.53.0.tgz",753 "integrity": "sha512-Kn7K8dx/5U6+cT1yEhpX1w4PCSg0M+XyRILPgvwcEBjerFWCwQj5sbr3/VmxqV0JGHCBCzyd6LxypEuehypY1w==",751 "version": "8.54.0",752 "resolved": "https://registry.npmjs.org/@eslint/js/-/js-8.54.0.tgz",753 "integrity": "sha512-ut5V+D+fOoWPgGGNj83GGjnntO39xDy6DWxO0wb7Jp3DcMX0TfIqdzHF85VTQkerdyGmuuMD9AKAo5KiNlf/AQ==",754 "dev": true,755 "engines": {756 "node": "^12.22.0 || ^14.17.0 || >=16.0.0"757 }
728 unmodified lines
1486 }1487 }1488 },1489 "node_modules/@typescript-eslint/parser": {1490 "version": "6.10.0",1491 "resolved": "https://registry.npmjs.org/@typescript-eslint/parser/-/parser-6.10.0.tgz",1492 "integrity": "sha512-+sZwIj+s+io9ozSxIWbNB5873OSdfeBEH/FR0re14WLI6BaKuSOnnwCJ2foUiu8uXf4dRp1UqHP0vrZ1zXGrog==",1490 "version": "6.13.1",1491 "resolved": "https://registry.npmjs.org/@typescript-eslint/parser/-/parser-6.13.1.tgz",1492 "integrity": "sha512-fs2XOhWCzRhqMmQf0eicLa/CWSaYss2feXsy7xBD/pLyWke/jCIVc2s1ikEAtSW7ina1HNhv7kONoEfVNEcdDQ==",1493 "dev": true,1494 "dependencies": {1495 "@typescript-eslint/scope-manager": "6.10.0",1496 "@typescript-eslint/types": "6.10.0",1497 "@typescript-eslint/typescript-estree": "6.10.0",1498 "@typescript-eslint/visitor-keys": "6.10.0",1495 "@typescript-eslint/scope-manager": "6.13.1",1496 "@typescript-eslint/types": "6.13.1",1497 "@typescript-eslint/typescript-estree": "6.13.1",1498 "@typescript-eslint/visitor-keys": "6.13.1",1499 "debug": "^4.3.4"1500 },1501 "engines": {1502 "node": "^16.0.0 || >=18.0.0"
11 unmodified lines
1514 }1515 }1516 },1517 "node_modules/@typescript-eslint/parser/node_modules/@typescript-eslint/scope-manager": {1518 "version": "6.10.0",1519 "resolved": "https://registry.npmjs.org/@typescript-eslint/scope-manager/-/scope-manager-6.10.0.tgz",1520 "integrity": "sha512-TN/plV7dzqqC2iPNf1KrxozDgZs53Gfgg5ZHyw8erd6jd5Ta/JIEcdCheXFt9b1NYb93a1wmIIVW/2gLkombDg==",1518 "version": "6.13.1",1519 "resolved": "https://registry.npmjs.org/@typescript-eslint/scope-manager/-/scope-manager-6.13.1.tgz",1520 "integrity": "sha512-BW0kJ7ceiKi56GbT2KKzZzN+nDxzQK2DS6x0PiSMPjciPgd/JRQGMibyaN2cPt2cAvuoH0oNvn2fwonHI+4QUQ==",1521 "dev": true,1522 "dependencies": {1523 "@typescript-eslint/types": "6.10.0",1524 "@typescript-eslint/visitor-keys": "6.10.0"1523 "@typescript-eslint/types": "6.13.1",1524 "@typescript-eslint/visitor-keys": "6.13.1"1525 },1526 "engines": {1527 "node": "^16.0.0 || >=18.0.0"1528 },
2 unmodified lines
1531 "url": "https://opencollective.com/typescript-eslint"1532 }1533 },1534 "node_modules/@typescript-eslint/parser/node_modules/@typescript-eslint/types": {1535 "version": "6.10.0",1536 "resolved": "https://registry.npmjs.org/@typescript-eslint/types/-/types-6.10.0.tgz",1537 "integrity": "sha512-36Fq1PWh9dusgo3vH7qmQAj5/AZqARky1Wi6WpINxB6SkQdY5vQoT2/7rW7uBIsPDcvvGCLi4r10p0OJ7ITAeg==",1535 "version": "6.13.1",1536 "resolved": "https://registry.npmjs.org/@typescript-eslint/types/-/types-6.13.1.tgz",1537 "integrity": "sha512-gjeEskSmiEKKFIbnhDXUyiqVma1gRCQNbVZ1C8q7Zjcxh3WZMbzWVfGE9rHfWd1msQtPS0BVD9Jz9jded44eKg==",1538 "dev": true,1539 "engines": {1540 "node": "^16.0.0 || >=18.0.0"1541 },
2 unmodified lines
1544 "url": "https://opencollective.com/typescript-eslint"1545 }1546 },1547 "node_modules/@typescript-eslint/parser/node_modules/@typescript-eslint/typescript-estree": {1548 "version": "6.10.0",1549 "resolved": "https://registry.npmjs.org/@typescript-eslint/typescript-estree/-/typescript-estree-6.10.0.tgz",1550 "integrity": "sha512-ek0Eyuy6P15LJVeghbWhSrBCj/vJpPXXR+EpaRZqou7achUWL8IdYnMSC5WHAeTWswYQuP2hAZgij/bC9fanBg==",1548 "version": "6.13.1",1549 "resolved": "https://registry.npmjs.org/@typescript-eslint/typescript-estree/-/typescript-estree-6.13.1.tgz",1550 "integrity": "sha512-sBLQsvOC0Q7LGcUHO5qpG1HxRgePbT6wwqOiGLpR8uOJvPJbfs0mW3jPA3ujsDvfiVwVlWUDESNXv44KtINkUQ==",1551 "dev": true,1552 "dependencies": {1553 "@typescript-eslint/types": "6.10.0",1554 "@typescript-eslint/visitor-keys": "6.10.0",1553 "@typescript-eslint/types": "6.13.1",1554 "@typescript-eslint/visitor-keys": "6.13.1",1555 "debug": "^4.3.4",1556 "globby": "^11.1.0",1557 "is-glob": "^4.0.3",1558 "semver": "^7.5.4",
12 unmodified lines
1571 }1572 }1573 },1574 "node_modules/@typescript-eslint/parser/node_modules/@typescript-eslint/visitor-keys": {1575 "version": "6.10.0",1576 "resolved": "https://registry.npmjs.org/@typescript-eslint/visitor-keys/-/visitor-keys-6.10.0.tgz",1577 "integrity": "sha512-xMGluxQIEtOM7bqFCo+rCMh5fqI+ZxV5RUUOa29iVPz1OgCZrtc7rFnz5cLUazlkPKYqX+75iuDq7m0HQ48nCg==",1575 "version": "6.13.1",1576 "resolved": "https://registry.npmjs.org/@typescript-eslint/visitor-keys/-/visitor-keys-6.13.1.tgz",1577 "integrity": "sha512-NDhQUy2tg6XGNBGDRm1XybOHSia8mcXmlbKWoQP+nm1BIIMxa55shyJfZkHpEBN62KNPLrocSM2PdPcaLgDKMQ==",1578 "dev": true,1579 "dependencies": {1580 "@typescript-eslint/types": "6.10.0",1580 "@typescript-eslint/types": "6.13.1",1581 "eslint-visitor-keys": "^3.4.1"1582 },1583 "engines": {1584 "node": "^16.0.0 || >=18.0.0"
1113 unmodified lines
2698 "url": "https://github.com/sponsors/sindresorhus"2699 }2700 },2701 "node_modules/eslint": {2702 "version": "8.53.0",2703 "resolved": "https://registry.npmjs.org/eslint/-/eslint-8.53.0.tgz",2704 "integrity": "sha512-N4VuiPjXDUa4xVeV/GC/RV3hQW9Nw+Y463lkWaKKXKYMvmRiRDAtfpuPFLN+E1/6ZhyR8J2ig+eVREnYgUsiag==",2702 "version": "8.54.0",2703 "resolved": "https://registry.npmjs.org/eslint/-/eslint-8.54.0.tgz",2704 "integrity": "sha512-NY0DfAkM8BIZDVl6PgSa1ttZbx3xHgJzSNJKYcQglem6CppHyMhRIQkBVSSMaSRnLhig3jsDbEzOjwCVt4AmmA==",2705 "dev": true,2706 "dependencies": {2707 "@eslint-community/eslint-utils": "^4.2.0",2708 "@eslint-community/regexpp": "^4.6.1",2709 "@eslint/eslintrc": "^2.1.3",2710 "@eslint/js": "8.53.0",2710 "@eslint/js": "8.54.0",2711 "@humanwhocodes/config-array": "^0.11.13",2712 "@humanwhocodes/module-importer": "^1.0.1",2713 "@nodelib/fs.walk": "^1.2.8",2714 "@ungap/structured-clone": "^1.2.0",
67 unmodified lines
2782 "eslint-plugin-promise": "^6.0.0"2783 }2784 },2785 "node_modules/eslint-config-standard-with-typescript": {2786 "version": "39.1.1",2787 "resolved": "https://registry.npmjs.org/eslint-config-standard-with-typescript/-/eslint-config-standard-with-typescript-39.1.1.tgz",2788 "integrity": "sha512-t6B5Ep8E4I18uuoYeYxINyqcXb2UbC0SOOTxRtBSt2JUs+EzeXbfe2oaiPs71AIdnoWhXDO2fYOHz8df3kV84A==",2786 "version": "40.0.0",2787 "resolved": "https://registry.npmjs.org/eslint-config-standard-with-typescript/-/eslint-config-standard-with-typescript-40.0.0.tgz",2788 "integrity": "sha512-GXUJcwIXiTQaS3H4etv8a1lejVVdZYaxZNz3g7vt6GoJosQqMTurbmSC4FVGyHiGT/d1TjFr3+47A3xsHhsG+Q==",2789 "dev": true,2790 "dependencies": {2791 "@typescript-eslint/parser": "^6.4.0",2792 "eslint-config-standard": "17.1.0"
4097 unmodified lines
modified:package.json+1 added-1 removed
60 unmodified lines
61 "@typescript-eslint/eslint-plugin": "^6.7.5",62 "@typescript-eslint/parser": "^6.7.5",63 "eslint": "^8.30.0",64 "eslint-config-standard": "^17.0.0",65 "eslint-config-standard-with-typescript": "^39.1.1",65 "eslint-config-standard-with-typescript": "^40.0.0",66 "eslint-plugin-import": "^2.26.0",67 "eslint-plugin-jest": "^27.1.7",68 "eslint-plugin-n": "^16.2.0",69 "eslint-plugin-promise": "^6.1.1",
11 unmodified lines
modified:Readme.md+2 added
902 unmodified lines
903program904 .helpOption('-e, --HELP', 'read more information');905```906907(Or use `.addHelpOption()` to add an option you construct yourself.)908909### .helpCommand()910911A help command is added by default if your command has subcommands. You can explicitly turn on or off the implicit help command with `.helpCommand(true)` and `.helpCommand(false)`.912
242 unmodified lines