Full Code of tj/commander.js for AI

master 8247364da749 cached
219 files
829.3 KB
217.3k tokens
317 symbols
1 requests
Download .txt
Showing preview only (886K chars total). Download the full file or copy to clipboard to get everything.
Repository: tj/commander.js
Branch: master
Commit: 8247364da749
Files: 219
Total size: 829.3 KB

Directory structure:
gitextract_758xjbrb/

├── .editorconfig
├── .gitattributes
├── .github/
│   ├── FUNDING.yml
│   ├── PULL_REQUEST_TEMPLATE.md
│   ├── dependabot.yml
│   └── workflows/
│       ├── codeql-analysis.yml
│       └── tests.yml
├── .gitignore
├── .prettierignore
├── .prettierrc.js
├── CHANGELOG.md
├── CONTRIBUTING.md
├── LICENSE
├── Readme.md
├── Readme_zh-CN.md
├── SECURITY.md
├── docs/
│   ├── deprecated.md
│   ├── help-in-depth.md
│   ├── options-in-depth.md
│   ├── parsing-and-hooks.md
│   ├── release-policy.md
│   ├── terminology.md
│   └── zh-CN/
│       ├── 不再推荐使用的功能.md
│       ├── 可变参数的选项.md
│       └── 术语表.md
├── eslint.config.js
├── esm.mjs
├── examples/
│   ├── action-this.js
│   ├── alias.js
│   ├── argument.js
│   ├── arguments-custom-processing.js
│   ├── arguments-extra.js
│   ├── color-help-replacement.mjs
│   ├── color-help.mjs
│   ├── configure-help.js
│   ├── configure-output.js
│   ├── custom-command-class.js
│   ├── custom-help
│   ├── custom-help-description
│   ├── custom-help-text.js
│   ├── custom-version
│   ├── defaultCommand.js
│   ├── deploy
│   ├── description
│   ├── global-options-added.js
│   ├── global-options-nested.js
│   ├── help-centered.mjs
│   ├── help-groups.js
│   ├── help-subcommands-usage.js
│   ├── hook.js
│   ├── man-style-help.mjs
│   ├── nestedCommands.js
│   ├── options-boolean-or-value.js
│   ├── options-common.js
│   ├── options-conflicts.js
│   ├── options-custom-processing.js
│   ├── options-defaults.js
│   ├── options-env.js
│   ├── options-extra.js
│   ├── options-implies.js
│   ├── options-negatable.js
│   ├── options-required.js
│   ├── options-variadic.js
│   ├── pass-through-options.js
│   ├── pizza
│   ├── pm
│   ├── pm-install
│   ├── pm-list.js
│   ├── positional-options.js
│   ├── split.js
│   ├── string-util.js
│   └── thank.js
├── index.js
├── jest.config.js
├── lib/
│   ├── argument.js
│   ├── command.js
│   ├── error.js
│   ├── help.js
│   ├── option.js
│   └── suggestSimilar.js
├── package-support.json
├── package.json
├── tests/
│   ├── args.literal.test.js
│   ├── args.variadic.test.js
│   ├── argument.chain.test.js
│   ├── argument.choices.test.js
│   ├── argument.custom-processing.test.js
│   ├── argument.required.test.js
│   ├── argument.variadic.test.js
│   ├── command.action.test.js
│   ├── command.addCommand.test.js
│   ├── command.addHelpOption.test.js
│   ├── command.addHelpText.test.js
│   ├── command.alias.test.js
│   ├── command.allowExcessArguments.test.js
│   ├── command.allowUnknownOption.test.js
│   ├── command.argumentVariations.test.js
│   ├── command.asterisk.test.js
│   ├── command.chain.test.js
│   ├── command.commandHelp.test.js
│   ├── command.configureHelp.test.js
│   ├── command.configureOutput.test.js
│   ├── command.copySettings.test.js
│   ├── command.createArgument.test.js
│   ├── command.createHelp.test.js
│   ├── command.createOption.test.js
│   ├── command.default.test.js
│   ├── command.description.test.js
│   ├── command.error.test.js
│   ├── command.executableSubcommand.inspect.test.js
│   ├── command.executableSubcommand.lookup.test.js
│   ├── command.executableSubcommand.mock.test.js
│   ├── command.executableSubcommand.search.test.js
│   ├── command.executableSubcommand.signals.test.js
│   ├── command.executableSubcommand.test.js
│   ├── command.exitOverride.test.js
│   ├── command.help.test.js
│   ├── command.helpCommand.test.js
│   ├── command.helpOption.test.js
│   ├── command.hook.test.js
│   ├── command.name.test.js
│   ├── command.nested.test.js
│   ├── command.onCommand.test.js
│   ├── command.option-misuse.test.js
│   ├── command.parse.test.js
│   ├── command.parseOptions.test.js
│   ├── command.positionalOptions.test.js
│   ├── command.registerClash.test.js
│   ├── command.showHelpAfterError.test.js
│   ├── command.showSuggestionAfterError.test.js
│   ├── command.summary.test.js
│   ├── command.unknownCommand.test.js
│   ├── command.unknownOption.test.js
│   ├── command.usage.test.js
│   ├── commander.configureCommand.test.js
│   ├── createCommand.test.js
│   ├── deprecated.test.js
│   ├── esm-imports-test.mjs
│   ├── fixtures/
│   │   ├── inspect-sub.js
│   │   ├── inspect.js
│   │   ├── pm
│   │   ├── pm-cache-clear.js
│   │   ├── pm-cache-validate.js
│   │   ├── pm-cache.js
│   │   ├── pm-default
│   │   ├── pm-echo.js
│   │   ├── pm-fail.js
│   │   ├── pm-install
│   │   ├── pm-listen
│   │   ├── pm-publish.js
│   │   ├── pm-search
│   │   ├── pm-silent
│   │   ├── pm-terminate.js
│   │   └── pmlink-install
│   ├── fixtures-extensions/
│   │   ├── pm-try-cjs.cjs
│   │   ├── pm-try-mjs.mjs
│   │   ├── pm-try-ts.ts
│   │   └── pm.js
│   ├── help.argumentDescription.test.js
│   ├── help.boxWrap.test.js
│   ├── help.commandTerm.test.js
│   ├── help.commandUsage.test.js
│   ├── help.longestArgumentTermLength.test.js
│   ├── help.longestCommandTermLength.test.js
│   ├── help.longestOptionTermLength.test.js
│   ├── help.minWidthToWrap.test.js
│   ├── help.optionDescription.test.js
│   ├── help.optionTerm.test.js
│   ├── help.padWidth.test.js
│   ├── help.preformatted.test.js
│   ├── help.showGlobalOptions.test.js
│   ├── help.sortCommands.test.js
│   ├── help.sortOptions.test.js
│   ├── help.stripAnsi.test.js
│   ├── help.style.test.js
│   ├── help.subcommandDescription.test.js
│   ├── help.suggestion.test.js
│   ├── help.visibleArguments.test.js
│   ├── help.visibleCommands.test.js
│   ├── help.visibleGlobalOptions.test.js
│   ├── help.visibleOptions.test.js
│   ├── helpGroup.test.js
│   ├── incrementNodeInspectorPort.test.js
│   ├── negatives.test.js
│   ├── option.bad-flags.test.js
│   ├── option.chain.test.js
│   ├── options.bool.combo.test.js
│   ├── options.bool.small.combined.test.js
│   ├── options.bool.test.js
│   ├── options.camelcase.test.js
│   ├── options.choices.test.js
│   ├── options.conflicts.test.js
│   ├── options.custom-processing.test.js
│   ├── options.default.test.js
│   ├── options.dual-options.test.js
│   ├── options.env.test.js
│   ├── options.flags.test.js
│   ├── options.getset.test.js
│   ├── options.implies.test.js
│   ├── options.mandatory.test.js
│   ├── options.optional.test.js
│   ├── options.opts.test.js
│   ├── options.optsWithGlobals.test.js
│   ├── options.preset.test.js
│   ├── options.registerClash.test.js
│   ├── options.required.test.js
│   ├── options.twice.test.js
│   ├── options.values.test.js
│   ├── options.variadic.test.js
│   ├── options.version.test.js
│   ├── program.test.js
│   ├── ts-imports.test.ts
│   └── useColor.test.js
├── tsconfig.js.json
├── tsconfig.json
├── tsconfig.ts.json
└── typings/
    ├── esm.d.mts
    ├── index.d.ts
    └── index.test-d.ts

================================================
FILE CONTENTS
================================================

================================================
FILE: .editorconfig
================================================
# EditorConfig is awesome: http://EditorConfig.org

# top-most EditorConfig file
root = true

[*]
end_of_line = lf
insert_final_newline = true
indent_style = space
indent_size = 2
tab_width = 2
# trim_trailing_whitespace = true


================================================
FILE: .gitattributes
================================================
# disable line-ending changes (otherwise Windows developers with default settings from git install see Prettier wanting to fix every file)
* -text


================================================
FILE: .github/FUNDING.yml
================================================
github: [shadowspawn, abetomo, tj]
tidelift: npm/commander


================================================
FILE: .github/PULL_REQUEST_TEMPLATE.md
================================================
<!--
The text in these markdown comments is instructions that will not appear in the displayed pull request,
and can be deleted.

Please submit pull requests against the develop branch.

Follow the existing code style. Check the tests succeed, including format and lint.
  npm run test
  npm run check

Don't update the CHANGELOG or package version number. That gets done by maintainers when preparing the release.

Commander currently has zero production dependencies. That isn't a hard requirement, but is a simple story. Requests which 
add a dependency are much less likely to be accepted, and we are likely to ask for alternative approaches to avoid the dependency.
-->

## Problem

<!--
What problem are you solving?
What Issues does this relate to?
Show the broken output if appropriate.
-->

## Solution

<!--
How did you solve the problem? 
Show the fixed output if appropriate.

There are a lot of forms of documentation which could need updating for a change in functionality. It
is ok if you want to show us the code to discuss before doing the extra work, and
you should say so in your comments so we focus on the concept first before talking about all the other pieces:

- TypeScript typings
- JSDoc documentation in code
- tests
- README
- examples/
-->

## ChangeLog

<!--
Optional. Suggest a line for adding to the CHANGELOG to summarise your change.
-->


================================================
FILE: .github/dependabot.yml
================================================
version: 2
updates:
  - package-ecosystem: "npm"
    target-branch: "develop"
    directory: "/"
    schedule:
      interval: "monthly"
  - package-ecosystem: "github-actions"
    target-branch: "develop"
    directory: "/"
    schedule:
      interval: "weekly"


================================================
FILE: .github/workflows/codeql-analysis.yml
================================================
name: "CodeQL"

on:
  push:
    branches: [ master, develop ]
  pull_request:
    # The branches below must be a subset of the branches above
    branches: [ master, develop ]
  schedule:
    - cron: '27 5 * * 6'

jobs:
  analyze:
    name: Analyze
    runs-on: ubuntu-latest
    permissions:
      actions: read
      contents: read
      security-events: write

    strategy:
      fail-fast: false
      matrix:
        language: [ 'javascript' ]

    steps:
    - name: Checkout repository
      uses: actions/checkout@v6

    # Initializes the CodeQL tools for scanning.
    - name: Initialize CodeQL
      uses: github/codeql-action/init@v4
      with:
        languages: ${{ matrix.language }}
        # If you wish to specify custom queries, you can do so here or in a config file.
        # By default, queries listed here will override any specified in a config file.
        # Prefix the list here with "+" to use these queries and those in the config file.
        # queries: ./path/to/local/query, your-org/your-repo/queries@main

    # Autobuild attempts to build any compiled languages  (C/C++, C#, or Java).
    # If this step fails, then you should remove it and run the build manually (see below)
    - name: Autobuild
      uses: github/codeql-action/autobuild@v4

    # ℹ️ Command-line programs to run using the OS shell.
    # 📚 https://git.io/JvXDl

    # ✏️ If the Autobuild fails above, remove it and uncomment the following three lines
    #    and modify them (or add more) to build your code if your project
    #    uses a compiled language

    #- run: |
    #   make bootstrap
    #   make release

    - name: Perform CodeQL Analysis
      uses: github/codeql-action/analyze@v4


================================================
FILE: .github/workflows/tests.yml
================================================
name: build

on: [push, pull_request]

permissions:
  contents: read

jobs:
  test:
    name: Test on node ${{ matrix.node-version }} and ${{ matrix.os }}
    runs-on: ${{ matrix.os }}
    strategy:
      fail-fast: false
      matrix:
        node-version: [20.x, 22.x, 24.x]
        os: [ubuntu-latest, windows-latest, macos-latest]

    steps:
    - uses: actions/checkout@v6
    - name: Use Node.js ${{ matrix.node-version }}
      uses: actions/setup-node@v6
      with:
        cache: 'npm'
        node-version: ${{ matrix.node-version }}
    # Use separate run commands so command status handled correctly on Windows
    - name: npm install
      run: npm ci
    - name: npm test
      run: npm test
    - name: npm run check
      run: npm run check


================================================
FILE: .gitignore
================================================
.DS_Store
node_modules
*.sock
.idea
.vscode/
coverage/


================================================
FILE: .prettierignore
================================================
# exclude everything, and opt-in to types we want to format
**.*
# add the filetypes we want to format
!**.js
!**.mjs
!**.cjs
!**.ts
!**.mts
!**.cts
!**.json


================================================
FILE: .prettierrc.js
================================================
const config = {
  singleQuote: true,
  overrides: [
    {
      files: ['tsconfig*.json'],
      options: { parser: 'jsonc' },
    },
  ],
};

module.exports = config;


================================================
FILE: CHANGELOG.md
================================================
# Changelog

All notable changes to this project will be documented in this file.

The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/),
and this project adheres to [Semantic Versioning](http://semver.org/spec/v2.0.0.html).

<!-- markdownlint-disable MD024 -->
<!-- markdownlint-disable MD004 -->

## [14.0.3] (2026-01-31)

### Added

- Release Policy document ([#2462])
  
### Changes

- old major versions now supported for 12 months instead of just previous major version, to give predictable end-of-life date ([#2462])
- clarify typing for deprecated callback parameter to `.outputHelp()` ([#2427])
- simple readability improvements to README ([#2465])
  
## [14.0.2] (2025-10-25)

### Changed

- improve negative number auto-detection test ([#2428])
- update (dev) dependencies

## [14.0.1] (2025-09-12)

### Fixed

- broken markdown link in README ([#2369])

### Changed

- improve code readability by using optional chaining ([#2394])
- use more idiomatic code with object spread instead of `Object.assign()` ([#2395])
- improve code readability using `string.endsWith()` instead of `string.slice()` ([#2396])
- refactor `.parseOptions()` to process args array in-place ([#2409])
- change private variadic support routines from `._concatValue()` to `._collectValue()` (change code from `array.concat()` to `array.push()`) ([#2410])
- update (dev) dependencies

## [14.0.0] (2025-05-18)

### Added

- support for groups of options and commands in the help using low-level `.helpGroup()` on `Option` and `Command`, and higher-level `.optionsGroup()` and `.commandsGroup()` which can be used in chaining way to specify group title for following options/commands ([#2328])
- support for unescaped negative numbers as option-arguments and command-arguments ([#2339])
- TypeScript: add `parseArg` property to `Argument` class ([#2359])

### Fixed

- remove bogus leading space in help when option has default value but not a description ([#2348])
- `.configureOutput()` now makes copy of settings instead of modifying in-place, fixing side-effects ([#2350])

### Changed

- *Breaking:* Commander 14 requires Node.js v20 or higher
- internal refactor of `Help` class adding `.formatItemList()` and `.groupItems()` methods ([#2328])

## [13.1.0] (2025-01-21)

### Added

- support a pair of long option flags to allow a memorable shortened flag, like `.option('--ws, --workspace')` ([#2312])

## [13.0.0] (2024-12-30)

### Added

- support multiple calls to `.parse()` with default settings ([#2299])
- add `.saveStateBeforeParse()` and `.restoreStateBeforeParse()` for use by subclasses ([#2299])
- style routines like `styleTitle()` to add color to help using `.configureHelp()` or Help subclass ([#2251])
- color related support in `.configureOutput()` for `getOutHasColors()`, `getErrHasColors()`, and `stripColor()` ([#2251])
- Help property for `minWidthToWrap` ([#2251])
- Help methods for `displayWidth()`, `boxWrap()`, `preformatted()` et al ([#2251])

### Changed

- *Breaking*: excess command-arguments cause an error by default, see migration tips ([#2223])
- *Breaking*: throw during Option construction for unsupported option flags, like multiple characters after single `-` ([#2270])
  - note: support for dual long option flags added in Commander 13.1
- *Breaking*: throw on multiple calls to `.parse()` if `storeOptionsAsProperties: true` ([#2299])
- TypeScript: include implicit `this` in parameters for action handler callback ([#2197])

### Deleted

- *Breaking*: `Help.wrap()` refactored into `formatItem()` and `boxWrap()` ([#2251])

### Migration Tips

**Excess command-arguments**

It is now an error for the user to specify more command-arguments than are expected. (`allowExcessArguments` is now false by default.)

Old code:

```js
program.option('-p, --port <number>', 'port number');
program.action((options) => {
  console.log(program.args);
});
```

Now shows an error:

```console
$ node example.js a b c
error: too many arguments. Expected 0 arguments but got 3.
```

You can declare the expected arguments. The help will then be more accurate too. Note that declaring
new arguments will change what is passed to the action handler.

```js
program.option('-p, --port <number>', 'port number');
program.argument('[args...]', 'remote command and arguments'); // expecting zero or more arguments
program.action((args, options) => {
  console.log(args);
});
```

Or you could suppress the error, useful for minimising changes in legacy code.

```js
program.option('-p, --port', 'port number');
program.allowExcessArguments();
program.action((options) => {
  console.log(program.args);
});
```

**Stricter option flag parsing**

Commander now throws an error for option flag combinations that are not supported.
In particular, a short flag with multiple characters is now an error.

```js
program.option('-ws, --workspace'); // throws error
```

A short option has a single character:

```js
program.option('-w, --workspace');
```

Or from Commander 13.1 you can have an extra long flag instead of a short flag to allow a more memorable shortcut for the full name:

```js
program.option('--ws, --workspace');
```

## [13.0.0-0] (2024-12-07)

(Released in 13.0.0)

## [12.1.0] (2024-05-18)

### Added

- auto-detect special node flags `node --eval` and `node --print` when call `.parse()` with no arguments ([#2164])

### Changed

- prefix require of Node.js core modules with `node:` ([#2170])
- format source files with Prettier ([#2180])
- switch from StandardJS to directly calling ESLint for linting ([#2153])
- extend security support for previous major version of Commander ([#2150])

### Removed

- removed unimplemented Option.fullDescription from TypeScript definition ([#2191])

## [12.0.0] (2024-02-03)

### Added

- `.addHelpOption()` as another way of configuring built-in help option ([#2006])
- `.helpCommand()` for configuring built-in help command ([#2087])

### Fixed

- *Breaking:* use non-zero exit code when spawned executable subcommand terminates due to a signal ([#2023])
- *Breaking:* check `passThroughOptions` constraints when using `.addCommand` and throw if parent command does not have `.enablePositionalOptions()` enabled ([#1937])

### Changed

- *Breaking:* Commander 12 requires Node.js v18 or higher ([#2027])
- *Breaking:* throw an error if add an option with a flag which is already in use ([#2055])
- *Breaking:* throw an error if add a command with name or alias which is already in use ([#2059])
- *Breaking:* throw error when calling `.storeOptionsAsProperties()` after setting an option value ([#1928])
- replace non-standard JSDoc of `@api private` with documented `@private` ([#1949])
- `.addHelpCommand()` now takes a Command (passing string or boolean still works as before but deprecated) ([#2087])
- refactor internal implementation of built-in help option ([#2006])
- refactor internal implementation of built-in help command ([#2087])

### Deprecated

- `.addHelpCommand()` passing string or boolean (use `.helpCommand()` or pass a Command) ([#2087])

### Removed

- *Breaking:* removed default export of a global Command instance from CommonJS (use the named `program` export instead) ([#2017])

### Migration Tips

**global program**

If you are using the [deprecated](./docs/deprecated.md#default-import-of-global-command-object) default import of the global Command object, you need to switch to using a named import (or create a new `Command`).

```js
// const program = require('commander');
const { program } = require('commander');
```

**option and command clashes**

A couple of configuration problems now throw an error, which will pick up issues in existing programs:

- adding an option which uses the same flag as a previous option
- adding a command which uses the same name or alias as a previous command

## [12.0.0-1] (2024-01-20)

(Released in 12.0.0)

## [12.0.0-0] (2023-11-11)

(Released in 12.0.0)

## [11.1.0] (2023-10-13)

### Fixed

- TypeScript: update `OptionValueSource` to allow any string, to match supported use of custom sources ([#1983])
- TypeScript: add that `Command.version()` can also be used as getter ([#1982])
- TypeScript: add null return type to `Commands.executableDir()`, for when not configured ([#1965])
- subcommands with an executable handler and only a short help flag are now handled correctly by the parent's help command ([#1930])

### Added

- `registeredArguments` property on `Command` with the array of defined `Argument` (like `Command.options` for `Option`) ([#2010])
- TypeScript declarations for Option properties: `envVar`, `presetArg` ([#2019])
- TypeScript declarations for Argument properties: `argChoices`, `defaultValue`, `defaultValueDescription` ([#2019])
- example file which shows how to configure help to display any custom usage in the list of subcommands ([#1896])

### Changed

- (developer) refactor TypeScript configs for multiple use-cases, and enable checks in JavaScript files in supporting editors ([#1969])

### Deprecated

- `Command._args` was private anyway, but now available as `registeredArguments` ([#2010])

## [11.0.0] (2023-06-16)

### Fixed

- help command works when help option is disabled ([#1864])

### Changed

- leading and trailing spaces are now ignored by the .arguments() method ([#1874])
- refine "types" exports for ESM to follow TypeScript guidelines ([#1886])
- *Breaking:* Commander 11 requires Node.js v16 or higher

## [10.0.1] (2023-04-15)

### Added

- improvements to documentation ([#1858], [#1859], [#1860])

### Fixed

- remove unused `Option.optionFlags` property from TypeScript definition ([#1844])

### Changed

- assume boolean option intended if caller passes string instead of hash to `.implies()` ([#1854])

## [10.0.0] (2023-01-13)

### Added

- wrap command description in help ([#1804])

### Changed

- *Breaking:* Commander 10 requires Node.js v14 or higher

## [9.5.0] (2023-01-07)

### Added

- `.getOptionValueSourceWithGlobals()` ([#1832])
- `showGlobalOptions` for `.configureHelp{}` and `Help` ([#1828])

## [9.4.1] (2022-09-30)

### Fixed

- `.setOptionValue()` now also clears option source ([#1795])
- TypeScript: add `implied` to `OptionValueSource` for option values set by using `.implies()` ([#1794])
- TypeScript : add `undefined` to return type of `.getOptionValueSource()` ([#1794])

### Changed

- additions to README

## [9.4.0] (2022-07-15)

### Added

- `preSubcommand` hook called before direct subcommands ([#1763])

### Fixed

- export `InvalidOptionArgumentError` in esm ([#1756])

### Changed

- update dependencies ([#1767])

## [9.3.0] (2022-05-28)

### Added

- `.summary()` for a short summary to use instead of description when listing subcommands in help ([#1726])
- `Option.implies()` to set other option values when the option is specified ([#1724])
- updated Chinese README with 9.x changes ([#1727])

### Fixed

- TypeScript: add `string[]` to `.options()` default value parameter type for use with variadic options ([#1721])

### Deprecated

- multi-character short option flag (e.g. `-ws`) ([#1718])

## [9.2.0] (2022-04-15)

### Added

- conditional export of 'types' for upcoming TypeScript module resolution ([#1703])
- example file showing two ways to add global options to subcommands ([#1708])

### Fixed

- detect option conflicts in parent commands of called subcommand ([#1710])

### Changed

- replace deprecated `String.prototype.substr` ([#1706])

## [9.1.0] (2022-03-19)

### Added

- Option `.conflicts()` to set conflicting options which can not be specified together ([#1678])
- (developer) CodeQL configuration for GitHub Actions ([#1698])

## [9.0.0] (2022-01-28)

### Added

- simpler ECMAScript import ([#1589])
- Option.preset() allows specifying value/arg for option when used without option-argument (especially optional, but also boolean option) ([#1652])
- `.executableDir()` for custom search for subcommands ([#1571])
- throw with helpful message if pass `Option` to `.option()` or `.requiredOption()` ([#1655])
- .`error()` for generating errors from client code just like Commander generated errors, with support for  `.configureOutput()`, `.exitOverride()`, and `.showHelpAfterError()` ([#1675])
- `.optsWithGlobals()` to return merged local and global options ([#1671])

### Changed

- *Breaking:* Commander 9 requires Node.js v12.20.0 or higher
- update package-lock.json to lockfile@2 format ([#1659])
- `showSuggestionAfterError` is now on by default ([#1657])
- *Breaking:* default value specified for boolean option now always used as default value (see .preset() to match some previous behaviours) ([#1652])
- default value for boolean option only shown in help if true/false ([#1652])
- use command name as prefix for subcommand stand-alone executable name (with fallback to script name for backwards compatibility) ([#1571])
- allow absolute path with `executableFile` ([#1571])
- removed restriction that nested subcommands must specify `executableFile` ([#1571])
- TypeScript: allow passing readonly string array to `.choices()` ([#1667])
- TypeScript: allow passing readonly string array to `.parse()`, `.parseAsync()`, `.aliases()` ([#1669])

### Fixed

- option with optional argument not supplied on command line now works when option already has a value, whether from default value or from previous arguments ([#1652])

### Removed

- *Breaking:* removed internal fallback to `require.main.filename` when script not known from arguments passed to `.parse()` (can supply details using `.name()`, and `.executableDir()` or `executableFile`) ([#1571])

## [9.0.0-1] (2022-01-15)

(Released in 9.0.0)

## [9.0.0-0] (2021-12-22)

(Released in 9.0.0)

## [8.3.0] (2021-10-22)

### Added

- `.getOptionValueSource()` and `.setOptionValueWithSource()`, where expected values for source are one of 'default', 'env', 'config', 'cli' ([#1613])

### Deprecated

- `.command('*')`, use default command instead ([#1612])
- `on('command:*')`, use `.showSuggestionAfterError()` instead ([#1612])

## [8.2.0] (2021-09-10)

### Added

- `.showSuggestionAfterError()` to show suggestions after unknown command or unknown option ([#1590])
- add `Option` support for values from environment variables using `.env()` ([#1587])

### Changed

- show error for unknown global option before subcommand (rather than just help) ([#1590])

### Removed

- TypeScript declaration of unimplemented `Option` method `argumentRejected`

## [8.1.0] (2021-07-27)

### Added

- `.copyInheritedSettings()` ([#1557])
- update Chinese translations of documentation for Commander v8 ([#1570])
- `Argument` methods for `.argRequired()` and `.argOptional()` ([#1567])

## [8.0.0] (2021-06-25)

### Added

- `.argument(name, description)` for adding command-arguments ([#1490])
  - supports default value for optional command-arguments ([#1508])
  - supports custom processing function ([#1508])
- `.createArgument()` factory method ([#1497])
- `.addArgument()` ([#1490])
- `Argument` supports `.choices()` ([#1525])
- `.showHelpAfterError()` to display full help or a custom message after an error ([#1534])
- `.hook()` with support for `'preAction'` and `'postAction'` callbacks ([#1514])
- client typing of `.opts()` return type using TypeScript generics ([#1539])
- the number of command-arguments is checked for programs without an action handler ([#1502])
- `.getOptionValue()` and `.setOptionValue()` ([#1521])

### Changed

- refactor and simplify TypeScript declarations (with no default export) ([#1520])
- `.parseAsync()` is now declared as `async` ([#1513])
- *Breaking:* `Help` method `.visibleArguments()` returns array of `Argument` ([#1490])
- *Breaking:* Commander 8 requires Node.js 12 or higher ([#1500])
- *Breaking:* `CommanderError` code `commander.invalidOptionArgument` renamed `commander.invalidArgument` ([#1508])
- *Breaking:* TypeScript declaration for `.addTextHelp()` callback no longer allows result of `undefined`, now just `string` ([#1516])
- refactor `index.tab` into a file per class ([#1522])
- remove help suggestion from "unknown command" error message (see `.showHelpAfterError()`) ([#1534])
- `Command` property `.arg` initialised to empty array (was previously undefined) ([#1529])
- update dependencies

### Deprecated

- second parameter of `cmd.description(desc, argDescriptions)` for adding argument descriptions ([#1490])
  - (use new `.argument(name, description)` instead)
- `InvalidOptionArgumentError` (replaced by `InvalidArgumentError`) ([#1508])

### Removed

- *Breaking:* TypeScript declaration for default export of global `Command` object ([#1520])
  - (still available as named `program` export)

### Migration Tips

If you have a simple program without an action handler, you will now get an error if
there are missing command-arguments.

```js
program
  .option('-d, --debug')
  .arguments('<file>');
program.parse();
```

```sh
$ node trivial.js 
error: missing required argument 'file'
```

If you want to show the help in this situation, you could check the arguments before parsing:

```js
if (process.argv.length === 2)
  program.help();
program.parse();
```

Or, you might choose to show the help after any user error:

```js
program.showHelpAfterError();
```

## [8.0.0-2] (2021-06-06)

(Released in 8.0.0)

## [8.0.0-1] (2021-05-30)

(Released in 8.0.0)

## [8.0.0-0] (2021-05-23)

(Released in 8.0.0)

## [7.2.0] (2021-03-22)

### Added

- TypeScript typing for `parent` property on `Command` ([#1475])
- TypeScript typing for `.attributeName()` on `Option` ([#1483])
- support information in package ([#1477])

### Changed

- improvements to error messages, README, and tests
- update dependencies

## [7.1.0] (2021-02-15)

### Added

- support for named imports from ECMAScript modules ([#1440])
- add `.cjs` to list of expected script file extensions ([#1449])
- allow using option choices and variadic together ([#1454])

### Fixed

- replace use of deprecated `process.mainModule` ([#1448])
- regression for legacy `command('*')` and call when command line includes options ([#1464])
- regression for `on('command:*', ...)` and call when command line includes unknown options ([#1464])
- display best error for combination of unknown command and unknown option (i.e. unknown command) ([#1464])

### Changed

- make TypeScript typings tests stricter ([#1453])
- improvements to README and tests

## [7.0.0] (2021-01-15)

### Added

- `.enablePositionalOptions()` to let program and subcommand reuse same option ([#1427])
- `.passThroughOptions()` to pass options through to other programs without needing `--` ([#1427])
- `.allowExcessArguments(false)` to show an error message if there are too many command-arguments on command line for the action handler ([#1409])
- `.configureOutput()` to modify use of stdout and stderr or customise display of errors ([#1387])
- use `.addHelpText()` to add text before or after the built-in help, for just current command or also for all subcommands ([#1296])
- enhance Option class ([#1331])
  - allow hiding options from help
  - allow restricting option arguments to a list of choices
  - allow setting how default value is shown in help
- `.createOption()` to support subclassing of automatically created options (like `.createCommand()`) ([#1380])
- refactor the code generating the help into a separate public Help class ([#1365])
  - support sorting subcommands and options in help
  - support specifying wrap width (columns)
  - allow subclassing Help class
  - allow configuring Help class without subclassing

### Changed

- *Breaking:* options are stored safely by default, not as properties on the command ([#1409])
  - this especially affects accessing options on program, use `program.opts()`
  - revert behaviour with `.storeOptionsAsProperties()`
- *Breaking:* action handlers are passed options and command separately ([#1409])
- deprecated callback parameter to `.help()` and `.outputHelp()` (removed from README) ([#1296])
- *Breaking:* errors now displayed using `process.stderr.write()` instead of `console.error()`
- deprecate `.on('--help')` (removed from README) ([#1296])
- initialise the command description to empty string (previously undefined) ([#1365])
- document and annotate deprecated routines ([#1349])

### Fixed

- wrapping bugs in help ([#1365])
  - first line of command description was wrapping two characters early
  - pad width calculation was not including help option and help command
  - pad width calculation was including hidden options and commands
- improve backwards compatibility for custom command event listeners ([#1403])
  
### Deleted

- *Breaking:* `.passCommandToAction()` ([#1409])
  - no longer needed as action handler is passed options and command
- *Breaking:* "extra arguments" parameter to action handler ([#1409])
  - if being used to detect excess arguments, there is now an error available by setting `.allowExcessArguments(false)`

### Migration Tips

The biggest change is the parsed option values. Previously the options were stored by default as properties on the command object, and now the options are stored separately.

If you wish to restore the old behaviour and get running quickly you can call `.storeOptionsAsProperties()`.
To allow you to move to the new code patterns incrementally, the action handler will be passed the command _twice_,
to match the new "options" and "command" parameters (see below).

**program options**

Use the `.opts()` method to access the options. This is available on any command but is used most with the program.

```js
program.option('-d, --debug');
program.parse();
// Old code before Commander 7
if (program.debug) console.log(`Program name is ${program.name()}`);
```

```js
// New code
const options = program.opts();
if (options.debug) console.log(`Program name is ${program.name()}`);
```

**action handler**

The action handler gets passed a parameter for each command-argument you declared. Previously by default the next parameter was the command object with the options as properties. Now the next two parameters are instead the options and the command. If you
only accessed the options there may be no code changes required.

```js
program
  .command('compress <filename>')
  .option('-t, --trace')
  // Old code before Commander 7
  .action((filename, cmd) => {
    if (cmd.trace) console.log(`Command name is ${cmd.name()}`);
  });
```

```js
  // New code
  .action((filename, options, command) => {
    if (options.trace) console.log(`Command name is ${command.name()}`);
  });
```

If you already set `.storeOptionsAsProperties(false)` you may still need to adjust your code.

```js
program
  .command('compress <filename>')
  .storeOptionsAsProperties(false)
  .option('-t, --trace')
  // Old code before Commander 7
  .action((filename, command) => {
    if (command.opts().trace) console.log(`Command name is ${command.name()}`);
  });
```

```js
   // New code
   .action((filename, options, command) => {
      if (command.opts().trace) console.log(`Command name is ${command.name()}`);
   });
```

## [7.0.0-2] (2020-12-14)

(Released in 7.0.0)

## [7.0.0-1] (2020-11-21)

(Released in 7.0.0)

## [7.0.0-0] (2020-10-25)

(Released in 7.0.0)

## [6.2.1] (2020-12-13)

### Fixed

- some tests failed if directory path included a space ([#1390])

## [6.2.0] (2020-10-25)

### Added

- added 'tsx' file extension for stand-alone executable subcommands ([#1368])
- documented second parameter to `.description()` to describe command arguments ([#1353])
- documentation of special cases with options taking varying numbers of option-arguments ([#1332])
- documentation for terminology ([#1361])
  
### Fixed

- add missing TypeScript definition for `.addHelpCommand()' ([#1375])
- removed blank line after "Arguments:" in help, to match "Options:" and "Commands:" ([#1360])

### Changed

- update dependencies

## [6.1.0] (2020-08-28)

### Added

- include URL to relevant section of README for error for potential conflict between Command properties and option values ([#1306])
- `.combineFlagAndOptionalValue(false)` to ease upgrade path from older versions of Commander ([#1326])
- allow disabling the built-in help option using `.helpOption(false)` ([#1325])
- allow just some arguments in `argumentDescription` to `.description()` ([#1323])

### Changed

- tidy async test and remove lint override ([#1312])

### Fixed

- executable subcommand launching when script path not known ([#1322])

## [6.0.0] (2020-07-21)

### Added

- add support for variadic options ([#1250])
- allow options to be added with just a short flag ([#1256])
  - *Breaking* the option property has same case as flag. e.g. flag `-n` accessed as `opts().n` (previously uppercase)
- *Breaking* throw an error if there might be a clash between option name and a Command property, with advice on how to resolve ([#1275])

### Fixed

- Options which contain -no- in the middle of the option flag should not be treated as negatable. ([#1301])

## [6.0.0-0] (2020-06-20)

(Released in 6.0.0)

## [5.1.0] (2020-04-25)

### Added

- support for multiple command aliases, the first of which is shown in the auto-generated help ([#531], [#1236])
- configuration support in `addCommand()` for `hidden` and `isDefault` ([#1232])

### Fixed

- omit masked help flags from the displayed help ([#645], [#1247])
- remove old short help flag when change help flags using `helpOption` ([#1248])

### Changed

- remove use of `arguments` to improve auto-generated help in editors ([#1235])
- rename `.command()` configuration `noHelp` to `hidden` (but not remove old support) ([#1232])
- improvements to documentation
- update dependencies
- update tested versions of node
- eliminate lint errors in TypeScript ([#1208])

## [5.0.0] (2020-03-14)

### Added

* support for nested commands with action-handlers ([#1] [#764] [#1149])
* `.addCommand()` for adding a separately configured command ([#764] [#1149])
* allow a non-executable to be set as the default command ([#742] [#1149])
* implicit help command when there are subcommands (previously only if executables) ([#1149])
* customise implicit help command with `.addHelpCommand()` ([#1149])
* display error message for unknown subcommand, by default ([#432] [#1088] [#1149])
* display help for missing subcommand, by default ([#1088] [#1149])
* combined short options as single argument may include boolean flags and value flag and value (e.g. `-a -b -p 80` can be written as `-abp80`) ([#1145])
* `.parseOption()` includes short flag and long flag expansions ([#1145])
* `.helpInformation()` returns help text as a string, previously a private routine ([#1169])
* `.parse()` implicitly uses `process.argv` if arguments not specified ([#1172])
* optionally specify where `.parse()` arguments "from", if not following node conventions ([#512] [#1172])
* suggest help option along with unknown command error ([#1179])
* TypeScript definition for `commands` property of `Command` ([#1184])
* export `program` property ([#1195])
* `createCommand` factory method to simplify subclassing ([#1191])

### Fixed

* preserve argument order in subcommands ([#508] [#962] [#1138])
* do not emit `command:*` for executable subcommands ([#809] [#1149])
* action handler called whether or not there are non-option arguments ([#1062] [#1149])
* combining option short flag and value in single argument now works for subcommands ([#1145])
* only add implicit help command when it will not conflict with other uses of argument ([#1153] [#1149])
* implicit help command works with command aliases ([#948] [#1149])
* options are validated whether or not there is an action handler ([#1149])

### Changed

* *Breaking* `.args` contains command arguments with just recognised options removed ([#1032] [#1138])
* *Breaking* display error if required argument for command is missing ([#995] [#1149])
* tighten TypeScript definition of custom option processing function passed to `.option()` ([#1119])
* *Breaking* `.allowUnknownOption()` ([#802] [#1138])
  * unknown options included in arguments passed to command action handler
  * unknown options included in `.args`
* only recognised option short flags and long flags are expanded (e.g. `-ab` or `--foo=bar`) ([#1145])
* *Breaking* `.parseOptions()` ([#1138])
  * `args` in returned result renamed `operands` and does not include anything after first unknown option
  * `unknown` in returned result has arguments after first unknown option including operands, not just options and values
* *Breaking* `.on('command:*', callback)` and other command events passed (changed) results from `.parseOptions`, i.e. operands and unknown  ([#1138])
* refactor Option from prototype to class ([#1133])
* refactor Command from prototype to class ([#1159])
* changes to error handling ([#1165])
  * throw for author error, not just display message
  * preflight for variadic error
  * add tips to missing subcommand executable
* TypeScript fluent return types changed to be more subclass friendly, return `this` rather than `Command` ([#1180])
* `.parseAsync` returns `Promise<this>` to be consistent with `.parse()` ([#1180])
* update dependencies

### Removed

* removed EventEmitter from TypeScript definition for Command, eliminating implicit peer dependency on `@types/node` ([#1146])
* removed private function `normalize` (the functionality has been integrated into `parseOptions`) ([#1145])
* `parseExpectedArgs` is now private ([#1149])

### Migration Tips

If you use `.on('command:*')` or more complicated tests to detect an unrecognised subcommand, you may be able to delete the code and rely on the default behaviour.

If you use `program.args` or more complicated tests to detect a missing subcommand, you may be able to delete the code and rely on the default behaviour.

If you use `.command('*')` to add a default command, you may be be able to switch to `isDefault:true` with a named command.

If you want to continue combining short options with optional values as though they were boolean flags, set `combineFlagAndOptionalValue(false)`
to expand `-fb` to `-f -b` rather than `-f b`.

## [5.0.0-4] (2020-03-03)

(Released in 5.0.0)

## [5.0.0-3] (2020-02-20)

(Released in 5.0.0)

## [5.0.0-2] (2020-02-10)

(Released in 5.0.0)

## [5.0.0-1] (2020-02-08)

(Released in 5.0.0)

## [5.0.0-0] (2020-02-02)

(Released in 5.0.0)

## [4.1.1] (2020-02-02)

### Fixed

* TypeScript definition for `.action()` should include Promise for async ([#1157])

## [4.1.0] (2020-01-06)

### Added

* two routines to change how option values are handled, and eliminate name clashes with command properties ([#933] [#1102])
  * see storeOptionsAsProperties and passCommandToAction in README
* `.parseAsync` to use instead of `.parse` if supply async action handlers ([#806] [#1118])

### Fixed

* Remove trailing blanks from wrapped help text ([#1096])

### Changed

* update dependencies
* extend security coverage for Commander 2.x to 2020-02-03
* improvements to README
* improvements to TypeScript definition documentation
* move old versions out of main CHANGELOG
* removed explicit use of `ts-node` in tests

## [4.0.1] (2019-11-12)

### Fixed

* display help when requested, even if there are missing required options ([#1091])

## [4.0.0] (2019-11-02)

### Added

* automatically wrap and indent help descriptions for options and commands ([#1051])
* `.exitOverride()` allows override of calls to `process.exit` for additional error handling and to keep program running ([#1040])
* support for declaring required options with `.requiredOptions()` ([#1071])
* GitHub Actions support ([#1027])
* translation links in README

### Changed

* dev: switch tests from Sinon+Should to Jest with major rewrite of tests ([#1035])
* call default subcommand even when there are unknown options ([#1047])
* *Breaking* Commander is only officially supported on Node 8 and above, and requires Node 6 ([#1053])

### Fixed

* *Breaking* keep command object out of program.args when action handler called ([#1048])
  * also, action handler now passed array of unknown arguments
* complain about unknown options when program argument supplied and action handler ([#1049])
  * this changes parameters to `command:*` event to include unknown arguments
* removed deprecated `customFds` option from call to `child_process.spawn` ([#1052])
* rework TypeScript declarations to bring all types into imported namespace ([#1081])

### Migration Tips

#### Testing for no arguments

If you were previously using code like:

```js
if (!program.args.length) ...
```

a partial replacement is:

```js
if (program.rawArgs.length < 3) ...
```

## [4.0.0-1] Prerelease (2019-10-08)

(Released in 4.0.0)

## [4.0.0-0] Prerelease (2019-10-01)

(Released in 4.0.0)

## [3.0.2] (2019-09-27)

<!-- markdownlint-disable MD024 -->

### Fixed

* Improve tracking of executable subcommands.

### Changed

* update development dependencies

## [3.0.1] (2019-08-30)

### Added

* .name and .usage to README ([#1010])
* Table of Contents to README ([#1010])
* TypeScript definition for `executableFile` in CommandOptions ([#1028])

### Changed

* consistently use `const` rather than `var` in README ([#1026])

### Fixed

* help for sub commands with custom executableFile ([#1018])

## [3.0.0] / 2019-08-08

* Add option to specify executable file name ([#999])
  * e.g. `.command('clone', 'clone description', { executableFile: 'myClone' })`
* Change docs for `.command` to contrast action handler vs git-style executable. ([#938] [#990])
* **Breaking** Change TypeScript to use overloaded function for `.command`. ([#938] [#990])
* Change to use straight quotes around strings in error messages (like 'this' instead of `this') ([#915])
* Add TypeScript "reference types" for node ([#974])
* Add support for hyphen as an option argument in subcommands ([#697])
* Add support for a short option flag and its value to be concatenated for action handler subcommands ([#599])
  * e.g. `-p 80` can also be supplied as `-p80`
* Add executable arguments to spawn in win32, for git-style executables ([#611])
  * e.g. `node --harmony myCommand.js clone`
* Add parent command as prefix of subcommand in help ([#980])
* Add optional custom description to `.version` ([#963])
  * e.g. `program.version('0.0.1', '-v, --vers', 'output the current version')`
* Add `.helpOption(flags, description)` routine to customise help flags and description ([#963])
  * e.g. `.helpOption('-e, --HELP', 'read more information')`
* Fix behavior of --no-* options ([#795])
  * can now define both `--foo` and `--no-foo`
  * **Breaking** custom event listeners: `--no-foo` on cli now emits `option:no-foo` (previously `option:foo`)
  * **Breaking** default value: defining `--no-foo` after defining `--foo` leaves the default value unchanged (previously set it to false)
  * allow boolean default value, such as from environment ([#987])
* Increment inspector port for spawned subcommands ([#991])
  * e.g. `node --inspect myCommand.js clone`

### Migration Tips

The custom event for a negated option like `--no-foo` is `option:no-foo` (previously `option:foo`).

```js
program
  .option('--no-foo')
  .on('option:no-foo', () => {
    console.log('removing foo');
  });
```

When using TypeScript, adding a command does not allow an explicit `undefined` for an unwanted executable description (e.g
for a command with an action handler).

```js
program
  .command('action1', undefined, { noHelp: true }) // No longer valid
  .command('action2', { noHelp: true }) // Correct
```

## 3.0.0-0 Prerelease / 2019-07-28

(Released as 3.0.0)

## [2.20.1] (2019-09-29)

### Fixed

* Improve tracking of executable subcommands.

### Changed

* update development dependencies

## 2.20.0 / 2019-04-02

* fix: resolve symbolic links completely when hunting for subcommands (#935)
* Update index.d.ts (#930)
* Update Readme.md (#924)
* Remove --save option as it isn't required anymore (#918)
* Add link to the license file (#900)
* Added example of receiving args from options (#858)
* Added missing semicolon (#882)
* Add extension to .eslintrc (#876)

## 2.19.0 / 2018-10-02

* Removed newline after Options and Commands headers (#864)
* Bugfix - Error output (#862)
* Fix to change default value to string (#856)

## 2.18.0 / 2018-09-07

* Standardize help output (#853)
* chmod 644 travis.yml (#851)
* add support for execute typescript subcommand via ts-node (#849)

## 2.17.1 / 2018-08-07

* Fix bug in command emit (#844)

## 2.17.0 / 2018-08-03

* fixed newline output after help information (#833)
* Fix to emit the action even without command (#778)
* npm update (#823)

## 2.16.0 / 2018-06-29

* Remove Makefile and `test/run` (#821)
* Make 'npm test' run on Windows (#820)
* Add badge to display install size (#807)
* chore: cache node_modules (#814)
* chore: remove Node.js 4 (EOL), add Node.js 10 (#813)
* fixed typo in readme (#812)
* Fix types (#804)
* Update eslint to resolve vulnerabilities in lodash (#799)
* updated readme with custom event listeners. (#791)
* fix tests (#794)

## 2.15.0 / 2018-03-07

* Update downloads badge to point to graph of downloads over time instead of duplicating link to npm
* Arguments description

## 2.14.1 / 2018-02-07

* Fix typing of help function

## 2.14.0 / 2018-02-05

* only register the option:version event once
* Fixes issue #727: Passing empty string for option on command is set to undefined
* enable eqeqeq rule
* resolves #754 add linter configuration to project
* resolves #560 respect custom name for version option
* document how to override the version flag
* document using options per command

## 2.13.0 / 2018-01-09

* Do not print default for --no-
* remove trailing spaces in command help
* Update CI's Node.js to LTS and latest version
* typedefs: Command and Option types added to commander namespace

## 2.12.2 / 2017-11-28

* fix: typings are not shipped

## 2.12.1 / 2017-11-23

* Move @types/node to dev dependency

## 2.12.0 / 2017-11-22

* add attributeName() method to Option objects
* Documentation updated for options with --no prefix
* typings: `outputHelp` takes a string as the first parameter
* typings: use overloads
* feat(typings): update to match js api
* Print default value in option help
* Fix translation error
* Fail when using same command and alias (#491)
* feat(typings): add help callback
* fix bug when description is add after command with options (#662)
* Format js code
* Rename History.md to CHANGELOG.md (#668)
* feat(typings): add typings to support TypeScript (#646)
* use current node

## 2.11.0 / 2017-07-03

* Fix help section order and padding (#652)
* feature: support for signals to subcommands (#632)
* Fixed #37, --help should not display first (#447)
* Fix translation errors. (#570)
* Add package-lock.json
* Remove engines
* Upgrade package version
* Prefix events to prevent conflicts between commands and options (#494)
* Removing dependency on graceful-readlink
* Support setting name in #name function and make it chainable
* Add .vscode directory to .gitignore (Visual Studio Code metadata)
* Updated link to ruby commander in readme files

## 2.10.0 / 2017-06-19

* Update .travis.yml. drop support for older node.js versions.
* Fix require arguments in README.md
* On SemVer you do not start from 0.0.1
* Add missing semi colon in readme
* Add save param to npm install
* node v6 travis test
* Update Readme_zh-CN.md
* Allow literal '--' to be passed-through as an argument
* Test subcommand alias help
* link build badge to master branch
* Support the alias of Git style sub-command
* added keyword commander for better search result on npm
* Fix Sub-Subcommands
* test node.js stable
* Fixes TypeError when a command has an option called `--description`
* Update README.md to make it beginner friendly and elaborate on the difference between angled and square brackets.
* Add chinese Readme file

## 2.9.0 / 2015-10-13

* Add option `isDefault` to set default subcommand #415 @Qix-
* Add callback to allow filtering or post-processing of help text #434 @djulien
* Fix `undefined` text in help information close #414 #416 @zhiyelee

## 2.8.1 / 2015-04-22

* Back out `support multiline description` Close #396 #397

## 2.8.0 / 2015-04-07

* Add `process.execArg` support, execution args like `--harmony` will be passed to sub-commands #387 @DigitalIO @zhiyelee
* Fix bug in Git-style sub-commands #372 @zhiyelee
* Allow commands to be hidden from help #383 @tonylukasavage
* When git-style sub-commands are in use, yet none are called, display help #382 @claylo
* Add ability to specify arguments syntax for top-level command #258 @rrthomas
* Support multiline descriptions #208 @zxqfox

## 2.7.1 / 2015-03-11

* Revert #347 (fix collisions when option and first arg have same name) which causes a bug in #367.

## 2.7.0 / 2015-03-09

* Fix git-style bug when installed globally. Close #335 #349 @zhiyelee
* Fix collisions when option and first arg have same name. Close #346 #347 @tonylukasavage
* Add support for camelCase on `opts()`. Close #353  @nkzawa
* Add node.js 0.12 and io.js to travis.yml
* Allow RegEx options. #337 @palanik
* Fixes exit code when sub-command failing.  Close #260 #332 @pirelenito
* git-style `bin` files in $PATH make sense. Close #196 #327  @zhiyelee

## 2.6.0 / 2014-12-30

* added `Command#allowUnknownOption` method. Close #138 #318 @doozr @zhiyelee
* Add application description to the help msg. Close #112 @dalssoft

## 2.5.1 / 2014-12-15

* fixed two bugs incurred by variadic arguments. Close #291 @Quentin01 #302 @zhiyelee

## 2.5.0 / 2014-10-24

* add support for variadic arguments. Closes #277 @whitlockjc

## 2.4.0 / 2014-10-17

* fixed a bug on executing the coercion function of subcommands option. Closes #270
* added `Command.prototype.name` to retrieve command name. Closes #264 #266 @tonylukasavage
* added `Command.prototype.opts` to retrieve all the options as a simple object of key-value pairs. Closes #262 @tonylukasavage
* fixed a bug on subcommand name. Closes #248 @jonathandelgado
* fixed function normalize doesn’t honor option terminator. Closes #216 @abbr

## 2.3.0 / 2014-07-16

* add command alias'. Closes PR #210
* fix: Typos. Closes #99
* fix: Unused fs module. Closes #217

## 2.2.0 / 2014-03-29

* add passing of previous option value
* fix: support subcommands on windows. Closes #142
* Now the defaultValue passed as the second argument of the coercion function.

## 2.1.0 / 2013-11-21

* add: allow cflag style option params, unit test, fixes #174

## 2.0.0 / 2013-07-18

* remove input methods (.prompt, .confirm, etc)

## 0.6.1 / 2012-06-01

* Added: append (yes or no) on confirmation
* Added: allow node.js v0.7.x

## 0.6.0 / 2012-04-10

* Added `.prompt(obj, callback)` support. Closes #49
* Added default support to .choose(). Closes #41
* Fixed the choice example

## 0.5.1 / 2011-12-20

* Fixed `password()` for recent nodes. Closes #36

## 0.5.0 / 2011-12-04

* Added sub-command option support [itay]

## 0.4.3 / 2011-12-04

* Fixed custom help ordering. Closes #32

## 0.4.2 / 2011-11-24

* Added travis support
* Fixed: line-buffered input automatically trimmed. Closes #31

## 0.4.1 / 2011-11-18

* Removed listening for "close" on --help

## 0.4.0 / 2011-11-15

* Added support for `--`. Closes #24

## 0.3.3 / 2011-11-14

* Fixed: wait for close event when writing help info [Jerry Hamlet]

## 0.3.2 / 2011-11-01

* Fixed long flag definitions with values [felixge]

## 0.3.1 / 2011-10-31

* Changed `--version` short flag to `-V` from `-v`
* Changed `.version()` so it's configurable [felixge]

## 0.3.0 / 2011-10-31

* Added support for long flags only. Closes #18

## 0.2.1 / 2011-10-24

* "node": ">= 0.4.x < 0.7.0". Closes #20

## 0.2.0 / 2011-09-26

* Allow for defaults that are not just boolean. Default reassignment only occurs for --no-*, optional, and required arguments. [Jim Isaacs]

## 0.1.0 / 2011-08-24

* Added support for custom `--help` output

## 0.0.5 / 2011-08-18

* Changed: when the user enters nothing prompt for password again
* Fixed issue with passwords beginning with numbers [NuckChorris]

## 0.0.4 / 2011-08-15

* Fixed `Commander#args`

## 0.0.3 / 2011-08-15

* Added default option value support

## 0.0.2 / 2011-08-15

* Added mask support to `Command#password(str[, mask], fn)`
* Added `Command#password(str, fn)`

## 0.0.1 / 2010-01-03

* Initial release

<!-- markdown reference links -->

[#948]: https://github.com/tj/commander.js/issues/948
[#1032]: https://github.com/tj/commander.js/issues/1032
[#1250]: https://github.com/tj/commander.js/pull/1250
[#1256]: https://github.com/tj/commander.js/pull/1256
[#1275]: https://github.com/tj/commander.js/pull/1275
[#1296]: https://github.com/tj/commander.js/pull/1296
[#1301]: https://github.com/tj/commander.js/issues/1301
[#1306]: https://github.com/tj/commander.js/pull/1306
[#1312]: https://github.com/tj/commander.js/pull/1312
[#1322]: https://github.com/tj/commander.js/pull/1322
[#1323]: https://github.com/tj/commander.js/pull/1323
[#1325]: https://github.com/tj/commander.js/pull/1325
[#1326]: https://github.com/tj/commander.js/pull/1326
[#1331]: https://github.com/tj/commander.js/pull/1331
[#1332]: https://github.com/tj/commander.js/pull/1332
[#1349]: https://github.com/tj/commander.js/pull/1349
[#1353]: https://github.com/tj/commander.js/pull/1353
[#1360]: https://github.com/tj/commander.js/pull/1360
[#1361]: https://github.com/tj/commander.js/pull/1361
[#1365]: https://github.com/tj/commander.js/pull/1365
[#1368]: https://github.com/tj/commander.js/pull/1368
[#1375]: https://github.com/tj/commander.js/pull/1375
[#1380]: https://github.com/tj/commander.js/pull/1380
[#1387]: https://github.com/tj/commander.js/pull/1387
[#1390]: https://github.com/tj/commander.js/pull/1390
[#1403]: https://github.com/tj/commander.js/pull/1403
[#1409]: https://github.com/tj/commander.js/pull/1409
[#1427]: https://github.com/tj/commander.js/pull/1427
[#1440]: https://github.com/tj/commander.js/pull/1440
[#1448]: https://github.com/tj/commander.js/pull/1448
[#1449]: https://github.com/tj/commander.js/pull/1449
[#1453]: https://github.com/tj/commander.js/pull/1453
[#1454]: https://github.com/tj/commander.js/pull/1454
[#1464]: https://github.com/tj/commander.js/pull/1464
[#1475]: https://github.com/tj/commander.js/pull/1475
[#1477]: https://github.com/tj/commander.js/pull/1477
[#1483]: https://github.com/tj/commander.js/pull/1483
[#1490]: https://github.com/tj/commander.js/pull/1490
[#1497]: https://github.com/tj/commander.js/pull/1497
[#1500]: https://github.com/tj/commander.js/pull/1500
[#1502]: https://github.com/tj/commander.js/pull/1502
[#1508]: https://github.com/tj/commander.js/pull/1508
[#1513]: https://github.com/tj/commander.js/pull/1513
[#1514]: https://github.com/tj/commander.js/pull/1514
[#1516]: https://github.com/tj/commander.js/pull/1516
[#1520]: https://github.com/tj/commander.js/pull/1520
[#1521]: https://github.com/tj/commander.js/pull/1521
[#1522]: https://github.com/tj/commander.js/pull/1522
[#1525]: https://github.com/tj/commander.js/pull/1525
[#1529]: https://github.com/tj/commander.js/pull/1529
[#1534]: https://github.com/tj/commander.js/pull/1534
[#1539]: https://github.com/tj/commander.js/pull/1539
[#1557]: https://github.com/tj/commander.js/pull/1557
[#1567]: https://github.com/tj/commander.js/pull/1567
[#1570]: https://github.com/tj/commander.js/pull/1570
[#1571]: https://github.com/tj/commander.js/pull/1571
[#1587]: https://github.com/tj/commander.js/pull/1587
[#1589]: https://github.com/tj/commander.js/pull/1589
[#1590]: https://github.com/tj/commander.js/pull/1590
[#1612]: https://github.com/tj/commander.js/pull/1612
[#1613]: https://github.com/tj/commander.js/pull/1613
[#1652]: https://github.com/tj/commander.js/pull/1652
[#1655]: https://github.com/tj/commander.js/pull/1655
[#1657]: https://github.com/tj/commander.js/pull/1657
[#1659]: https://github.com/tj/commander.js/pull/1659
[#1667]: https://github.com/tj/commander.js/pull/1667
[#1669]: https://github.com/tj/commander.js/pull/1669
[#1671]: https://github.com/tj/commander.js/pull/1671
[#1675]: https://github.com/tj/commander.js/pull/1675
[#1678]: https://github.com/tj/commander.js/pull/1678
[#1698]: https://github.com/tj/commander.js/pull/1698
[#1703]: https://github.com/tj/commander.js/pull/1703
[#1706]: https://github.com/tj/commander.js/pull/1706
[#1708]: https://github.com/tj/commander.js/pull/1708
[#1710]: https://github.com/tj/commander.js/pull/1710
[#1718]: https://github.com/tj/commander.js/pull/1718
[#1721]: https://github.com/tj/commander.js/pull/1721
[#1724]: https://github.com/tj/commander.js/pull/1724
[#1726]: https://github.com/tj/commander.js/pull/1726
[#1727]: https://github.com/tj/commander.js/pull/1727
[#1756]: https://github.com/tj/commander.js/pull/1756
[#1763]: https://github.com/tj/commander.js/pull/1763
[#1767]: https://github.com/tj/commander.js/pull/1767
[#1794]: https://github.com/tj/commander.js/pull/1794
[#1795]: https://github.com/tj/commander.js/pull/1795
[#1804]: https://github.com/tj/commander.js/pull/1804
[#1832]: https://github.com/tj/commander.js/pull/1832
[#1828]: https://github.com/tj/commander.js/pull/1828
[#1844]: https://github.com/tj/commander.js/pull/1844
[#1854]: https://github.com/tj/commander.js/pull/1854
[#1858]: https://github.com/tj/commander.js/pull/1858
[#1859]: https://github.com/tj/commander.js/pull/1859
[#1860]: https://github.com/tj/commander.js/pull/1860
[#1864]: https://github.com/tj/commander.js/pull/1864
[#1874]: https://github.com/tj/commander.js/pull/1874
[#1886]: https://github.com/tj/commander.js/pull/1886
[#1896]: https://github.com/tj/commander.js/pull/1896
[#1928]: https://github.com/tj/commander.js/pull/1928
[#1930]: https://github.com/tj/commander.js/pull/1930
[#1937]: https://github.com/tj/commander.js/pull/1937
[#1949]: https://github.com/tj/commander.js/pull/1949
[#1965]: https://github.com/tj/commander.js/pull/1965
[#1969]: https://github.com/tj/commander.js/pull/1969
[#1982]: https://github.com/tj/commander.js/pull/1982
[#1983]: https://github.com/tj/commander.js/pull/1983
[#2006]: https://github.com/tj/commander.js/pull/2006
[#2010]: https://github.com/tj/commander.js/pull/2010
[#2017]: https://github.com/tj/commander.js/pull/2017
[#2019]: https://github.com/tj/commander.js/pull/2019
[#2023]: https://github.com/tj/commander.js/pull/2023
[#2027]: https://github.com/tj/commander.js/pull/2027
[#2055]: https://github.com/tj/commander.js/pull/2055
[#2059]: https://github.com/tj/commander.js/pull/2059
[#2087]: https://github.com/tj/commander.js/pull/2087
[#2150]: https://github.com/tj/commander.js/pull/2150
[#2153]: https://github.com/tj/commander.js/pull/2153
[#2164]: https://github.com/tj/commander.js/pull/2164
[#2170]: https://github.com/tj/commander.js/pull/2170
[#2180]: https://github.com/tj/commander.js/pull/2180
[#2191]: https://github.com/tj/commander.js/pull/2191
[#2197]: https://github.com/tj/commander.js/pull/2197
[#2223]: https://github.com/tj/commander.js/pull/2223
[#2251]: https://github.com/tj/commander.js/pull/2251
[#2270]: https://github.com/tj/commander.js/pull/2270
[#2299]: https://github.com/tj/commander.js/pull/2299
[#2312]: https://github.com/tj/commander.js/pull/2312
[#2328]: https://github.com/tj/commander.js/pull/2328
[#2339]: https://github.com/tj/commander.js/pull/2339
[#2348]: https://github.com/tj/commander.js/pull/2348
[#2350]: https://github.com/tj/commander.js/pull/2350
[#2359]: https://github.com/tj/commander.js/pull/2359
[#2369]: https://github.com/tj/commander.js/pull/2369
[#2394]: https://github.com/tj/commander.js/pull/2394
[#2395]: https://github.com/tj/commander.js/pull/2395
[#2396]: https://github.com/tj/commander.js/pull/2396
[#2409]: https://github.com/tj/commander.js/pull/2409
[#2410]: https://github.com/tj/commander.js/pull/2410
[#2427]: https://github.com/tj/commander.js/pull/2427
[#2428]: https://github.com/tj/commander.js/pull/2428
[#2462]: https://github.com/tj/commander.js/pull/2462
[#2465]: https://github.com/tj/commander.js/pull/2465

<!-- Referenced in 5.x -->
[#1]: https://github.com/tj/commander.js/issues/1
[#432]: https://github.com/tj/commander.js/issues/432
[#508]: https://github.com/tj/commander.js/issues/508
[#512]: https://github.com/tj/commander.js/issues/512
[#531]: https://github.com/tj/commander.js/issues/531
[#645]: https://github.com/tj/commander.js/issues/645
[#742]: https://github.com/tj/commander.js/issues/742
[#764]: https://github.com/tj/commander.js/issues/764
[#802]: https://github.com/tj/commander.js/issues/802
[#809]: https://github.com/tj/commander.js/issues/809
[#962]: https://github.com/tj/commander.js/issues/962
[#995]: https://github.com/tj/commander.js/issues/995
[#1062]: https://github.com/tj/commander.js/pull/1062
[#1088]: https://github.com/tj/commander.js/issues/1088
[#1119]: https://github.com/tj/commander.js/pull/1119
[#1133]: https://github.com/tj/commander.js/pull/1133
[#1138]: https://github.com/tj/commander.js/pull/1138
[#1145]: https://github.com/tj/commander.js/pull/1145
[#1146]: https://github.com/tj/commander.js/pull/1146
[#1149]: https://github.com/tj/commander.js/pull/1149
[#1153]: https://github.com/tj/commander.js/issues/1153
[#1159]: https://github.com/tj/commander.js/pull/1159
[#1165]: https://github.com/tj/commander.js/pull/1165
[#1169]: https://github.com/tj/commander.js/pull/1169
[#1172]: https://github.com/tj/commander.js/pull/1172
[#1179]: https://github.com/tj/commander.js/pull/1179
[#1180]: https://github.com/tj/commander.js/pull/1180
[#1184]: https://github.com/tj/commander.js/pull/1184
[#1191]: https://github.com/tj/commander.js/pull/1191
[#1195]: https://github.com/tj/commander.js/pull/1195
[#1208]: https://github.com/tj/commander.js/pull/1208
[#1232]: https://github.com/tj/commander.js/pull/1232
[#1235]: https://github.com/tj/commander.js/pull/1235
[#1236]: https://github.com/tj/commander.js/pull/1236
[#1247]: https://github.com/tj/commander.js/pull/1247
[#1248]: https://github.com/tj/commander.js/pull/1248

<!-- Referenced in 4.x -->
[#933]: https://github.com/tj/commander.js/pull/933
[#1027]: https://github.com/tj/commander.js/pull/1027
[#1035]: https://github.com/tj/commander.js/pull/1035
[#1040]: https://github.com/tj/commander.js/pull/1040
[#1047]: https://github.com/tj/commander.js/pull/1047
[#1048]: https://github.com/tj/commander.js/pull/1048
[#1049]: https://github.com/tj/commander.js/pull/1049
[#1051]: https://github.com/tj/commander.js/pull/1051
[#1052]: https://github.com/tj/commander.js/pull/1052
[#1053]: https://github.com/tj/commander.js/pull/1053
[#1071]: https://github.com/tj/commander.js/pull/1071
[#1081]: https://github.com/tj/commander.js/pull/1081
[#1091]: https://github.com/tj/commander.js/pull/1091
[#1096]: https://github.com/tj/commander.js/pull/1096
[#1102]: https://github.com/tj/commander.js/pull/1102
[#1118]: https://github.com/tj/commander.js/pull/1118
[#1157]: https://github.com/tj/commander.js/pull/1157
[#806]: https://github.com/tj/commander.js/issues/806

<!-- Referenced in 3.x -->
[#599]: https://github.com/tj/commander.js/issues/599
[#611]: https://github.com/tj/commander.js/issues/611
[#697]: https://github.com/tj/commander.js/issues/697
[#795]: https://github.com/tj/commander.js/issues/795
[#915]: https://github.com/tj/commander.js/issues/915
[#938]: https://github.com/tj/commander.js/issues/938
[#963]: https://github.com/tj/commander.js/issues/963
[#974]: https://github.com/tj/commander.js/issues/974
[#980]: https://github.com/tj/commander.js/issues/980
[#987]: https://github.com/tj/commander.js/issues/987
[#990]: https://github.com/tj/commander.js/issues/990
[#991]: https://github.com/tj/commander.js/issues/991
[#999]: https://github.com/tj/commander.js/issues/999
[#1010]: https://github.com/tj/commander.js/pull/1010
[#1018]: https://github.com/tj/commander.js/pull/1018
[#1026]: https://github.com/tj/commander.js/pull/1026
[#1028]: https://github.com/tj/commander.js/pull/1028

[Unreleased]: https://github.com/tj/commander.js/compare/master...develop
[14.0.3]: https://github.com/tj/commander.js/compare/v14.0.2...v14.0.3
[14.0.2]: https://github.com/tj/commander.js/compare/v14.0.1...v14.0.2
[14.0.1]: https://github.com/tj/commander.js/compare/v14.0.0...v14.0.1
[14.0.0]: https://github.com/tj/commander.js/compare/v13.1.0...v14.0.0
[13.1.0]: https://github.com/tj/commander.js/compare/v13.0.0...v13.1.0
[13.0.0]: https://github.com/tj/commander.js/compare/v12.1.0...v13.0.0
[13.0.0-0]: https://github.com/tj/commander.js/compare/v12.1.0...v13.0.0-0
[12.1.0]: https://github.com/tj/commander.js/compare/v12.0.0...v12.1.0
[12.0.0]: https://github.com/tj/commander.js/compare/v11.1.0...v12.0.0
[12.0.0-1]: https://github.com/tj/commander.js/compare/v12.0.0-0...v12.0.0-1
[12.0.0-0]: https://github.com/tj/commander.js/compare/v11.1.0...v12.0.0-0
[11.1.0]: https://github.com/tj/commander.js/compare/v11.0.0...v11.1.0
[11.0.0]: https://github.com/tj/commander.js/compare/v10.0.1...v11.0.0
[10.0.1]: https://github.com/tj/commander.js/compare/v10.0.0...v10.0.1
[10.0.0]: https://github.com/tj/commander.js/compare/v9.5.0...v10.0.0
[9.5.0]: https://github.com/tj/commander.js/compare/v9.4.1...v9.5.0
[9.4.1]: https://github.com/tj/commander.js/compare/v9.4.0...v9.4.1
[9.4.0]: https://github.com/tj/commander.js/compare/v9.3.0...v9.4.0
[9.3.0]: https://github.com/tj/commander.js/compare/v9.2.0...v9.3.0
[9.2.0]: https://github.com/tj/commander.js/compare/v9.1.0...v9.2.0
[9.1.0]: https://github.com/tj/commander.js/compare/v9.0.0...v9.1.0
[9.0.0]: https://github.com/tj/commander.js/compare/v8.3.0...v9.0.0
[9.0.0-1]: https://github.com/tj/commander.js/compare/v9.0.0-0...v9.0.0-1
[9.0.0-0]: https://github.com/tj/commander.js/compare/v8.3.0...v9.0.0-0
[8.3.0]: https://github.com/tj/commander.js/compare/v8.2.0...v8.3.0
[8.2.0]: https://github.com/tj/commander.js/compare/v8.1.0...v8.2.0
[8.1.0]: https://github.com/tj/commander.js/compare/v8.0.0...v8.1.0
[8.0.0]: https://github.com/tj/commander.js/compare/v7.2.0...v8.0.0
[8.0.0-2]: https://github.com/tj/commander.js/compare/v8.0.0-1...v8.0.0-2
[8.0.0-1]: https://github.com/tj/commander.js/compare/v8.0.0-0...v8.0.0-1
[8.0.0-0]: https://github.com/tj/commander.js/compare/v7.2.0...v8.0.0-0
[7.2.0]: https://github.com/tj/commander.js/compare/v7.1.0...v7.2.0
[7.1.0]: https://github.com/tj/commander.js/compare/v7.0.0...v7.1.0
[7.0.0]: https://github.com/tj/commander.js/compare/v6.2.1...v7.0.0
[7.0.0-2]: https://github.com/tj/commander.js/compare/v7.0.0-1...v7.0.0-2
[7.0.0-1]: https://github.com/tj/commander.js/compare/v7.0.0-0...v7.0.0-1
[7.0.0-0]: https://github.com/tj/commander.js/compare/v6.2.0...v7.0.0-0
[6.2.1]: https://github.com/tj/commander.js/compare/v6.2.0..v6.2.1
[6.2.0]: https://github.com/tj/commander.js/compare/v6.1.0..v6.2.0
[6.1.0]: https://github.com/tj/commander.js/compare/v6.0.0..v6.1.0
[6.0.0]: https://github.com/tj/commander.js/compare/v5.1.0..v6.0.0
[6.0.0-0]: https://github.com/tj/commander.js/compare/v5.1.0..v6.0.0-0
[5.1.0]: https://github.com/tj/commander.js/compare/v5.0.0..v5.1.0
[5.0.0]: https://github.com/tj/commander.js/compare/v4.1.1..v5.0.0
[5.0.0-4]: https://github.com/tj/commander.js/compare/v5.0.0-3..v5.0.0-4
[5.0.0-3]: https://github.com/tj/commander.js/compare/v5.0.0-2..v5.0.0-3
[5.0.0-2]: https://github.com/tj/commander.js/compare/v5.0.0-1..v5.0.0-2
[5.0.0-1]: https://github.com/tj/commander.js/compare/v5.0.0-0..v5.0.0-1
[5.0.0-0]: https://github.com/tj/commander.js/compare/v4.1.1..v5.0.0-0
[4.1.1]: https://github.com/tj/commander.js/compare/v4.1.0..v4.1.1
[4.1.0]: https://github.com/tj/commander.js/compare/v4.0.1..v4.1.0
[4.0.1]: https://github.com/tj/commander.js/compare/v4.0.0..v4.0.1
[4.0.0]: https://github.com/tj/commander.js/compare/v3.0.2..v4.0.0
[4.0.0-1]: https://github.com/tj/commander.js/compare/v4.0.0-0..v4.0.0-1
[4.0.0-0]: https://github.com/tj/commander.js/compare/v3.0.2...v4.0.0-0
[3.0.2]: https://github.com/tj/commander.js/compare/v3.0.1...v3.0.2
[3.0.1]: https://github.com/tj/commander.js/compare/v3.0.0...v3.0.1
[3.0.0]: https://github.com/tj/commander.js/compare/v2.20.1...v3.0.0
[2.20.1]: https://github.com/tj/commander.js/compare/v2.20.0...v2.20.1


================================================
FILE: CONTRIBUTING.md
================================================
# Contributing

## Issues

New issues are welcome, whether questions or suggestions or reporting bugs.
You are also welcome to contribute by adding helpful comments on an existing issue.

We love reproducible code examples in questions and answers.

If you get a satisfactory reply to a question then please close your issue, but it is ok to leave an issue open for more replies or interest. Inactive issues may get closed after one month if they have an answer,
or after six months otherwise.

## Pull Requests

Pull Requests will be considered. Please submit pull requests against the develop branch.

Follow the existing code style. Check the tests succeed, including format and lint.

- `npm run test`
- `npm run check`

Don't update the CHANGELOG or command version number. That gets done by maintainers when preparing the release.

Useful things to include in your request description are:

- what problem are you solving?
- what Issues does this relate to?
- suggested summary for CHANGELOG

There are a lot of forms of documentation which could need updating for a change in functionality. It
is ok if you want to show us the code to discuss before doing the extra work, and
you should say so in your comments so we focus on the concept first before talking about all the other pieces:

- TypeScript typings
- JSDoc documentation in code
- tests
- README
- examples/

Commander currently has zero production dependencies. That isn't a hard requirement, but is a simple story. Requests which add a dependency are much less likely to be accepted, and we are likely to ask for alternative approaches to avoid the dependency.

- <https://devrant.com/rants/1854993/package-tsunami>
- <https://dev.to/leoat12/the-nodemodules-problem-29dc>


================================================
FILE: LICENSE
================================================
(The MIT License)

Copyright (c) 2011 TJ Holowaychuk <tj@vision-media.ca>

Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the
'Software'), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to
permit persons to whom the Software is furnished to do so, subject to
the following conditions:

The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.


================================================
FILE: Readme.md
================================================
# Commander.js

[![Build Status](https://github.com/tj/commander.js/workflows/build/badge.svg)](https://github.com/tj/commander.js/actions?query=workflow%3A%22build%22)
[![NPM Version](http://img.shields.io/npm/v/commander.svg?style=flat)](https://www.npmjs.org/package/commander)
[![NPM Downloads](https://img.shields.io/npm/dm/commander.svg?style=flat)](https://npmcharts.com/compare/commander?minimal=true)
[![Install Size](https://packagephobia.now.sh/badge?p=commander)](https://packagephobia.now.sh/result?p=commander)

The complete solution for [node.js](http://nodejs.org) command-line interfaces.

Read this in other languages: English | [简体中文](./Readme_zh-CN.md)

- [Commander.js](#commanderjs)
  - [Installation](#installation)
  - [Quick Start](#quick-start)
  - [Declaring _program_ variable](#declaring-program-variable)
  - [Options](#options)
    - [Common option types, boolean and value](#common-option-types-boolean-and-value)
    - [Default option value](#default-option-value)
    - [Other option types, negatable boolean and boolean|value](#other-option-types-negatable-boolean-and-booleanvalue)
    - [Required option](#required-option)
    - [Variadic option](#variadic-option)
    - [Version option](#version-option)
    - [More configuration](#more-configuration)
    - [Custom option processing](#custom-option-processing)
  - [Commands](#commands)
    - [Command-arguments](#command-arguments)
      - [More configuration](#more-configuration-1)
      - [Custom argument processing](#custom-argument-processing)
    - [Action handler](#action-handler)
    - [Stand-alone executable (sub)commands](#stand-alone-executable-subcommands)
    - [Life cycle hooks](#life-cycle-hooks)
  - [Automated help](#automated-help)
    - [Custom help](#custom-help)
    - [Display help after errors](#display-help-after-errors)
    - [Display help from code](#display-help-from-code)
    - [.name](#name)
    - [.usage](#usage)
    - [.description and .summary](#description-and-summary)
    - [.helpOption(flags, description)](#helpoptionflags-description)
    - [.helpCommand()](#helpcommand)
    - [Help Groups](#help-groups)
    - [More configuration](#more-configuration-2)
  - [Custom event listeners](#custom-event-listeners)
  - [Bits and pieces](#bits-and-pieces)
    - [.parse() and .parseAsync()](#parse-and-parseasync)
    - [Parsing Configuration](#parsing-configuration)
    - [Legacy options as properties](#legacy-options-as-properties)
    - [TypeScript](#typescript)
    - [createCommand()](#createcommand)
    - [Node options such as `--harmony`](#node-options-such-as---harmony)
    - [Debugging stand-alone executable subcommands](#debugging-stand-alone-executable-subcommands)
    - [npm run-script](#npm-run-script)
    - [Display error](#display-error)
    - [Override exit and output handling](#override-exit-and-output-handling)
    - [Additional documentation](#additional-documentation)
  - [Support](#support)
    - [Commander for enterprise](#commander-for-enterprise)

For information about terms used in this document see: [terminology](./docs/terminology.md)

## Installation

```sh
npm install commander
```

## Quick Start

You write code to describe your command line interface.
Commander looks after parsing the arguments into options and command-arguments,
displays usage errors for problems, and implements a help system.

Commander is strict and displays an error for unrecognised options.
The two most used option types are a boolean option, and an option which takes its value from the following argument.

Example file: [split.js](./examples/split.js)

```js
const { program } = require('commander');

program
  .option('--first')
  .option('-s, --separator <char>')
  .argument('<string>');

program.parse();

const options = program.opts();
const limit = options.first ? 1 : undefined;
console.log(program.args[0].split(options.separator, limit));
```

```console
$ node split.js -s / --fits a/b/c
error: unknown option '--fits'
(Did you mean --first?)
$ node split.js -s / --first a/b/c
[ 'a' ]
```

Here is a more complete program using a subcommand and with descriptions for the help. In a multi-command program, you have an action handler for each command (or stand-alone executables for the commands).

Example file: [string-util.js](./examples/string-util.js)

```js
const { Command } = require('commander');
const program = new Command();

program
  .name('string-util')
  .description('CLI to some JavaScript string utilities')
  .version('0.8.0');

program.command('split')
  .description('Split a string into substrings and display as an array')
  .argument('<string>', 'string to split')
  .option('--first', 'display just the first substring')
  .option('-s, --separator <char>', 'separator character', ',')
  .action((str, options) => {
    const limit = options.first ? 1 : undefined;
    console.log(str.split(options.separator, limit));
  });

program.parse();
```

```console
$ node string-util.js help split
Usage: string-util split [options] <string>

Split a string into substrings and display as an array.

Arguments:
  string                  string to split

Options:
  --first                 display just the first substring
  -s, --separator <char>  separator character (default: ",")
  -h, --help              display help for command

$ node string-util.js split --separator=/ a/b/c
[ 'a', 'b', 'c' ]
```

More samples can be found in the [examples](https://github.com/tj/commander.js/tree/master/examples) directory.

## Declaring _program_ variable

Commander exports a global object which is convenient for quick programs.
This is used in the examples in this README for brevity.

```js
// CommonJS (.cjs)
const { program } = require('commander');
```

For larger programs which may use commander in multiple ways, including unit testing, it is better to create a local `Command` object to use.

```js
// CommonJS (.cjs)
const { Command } = require('commander');
const program = new Command();
```

```js
// ECMAScript (.mjs)
import { Command } from 'commander';
const program = new Command();
```

```ts
// TypeScript (.ts)
import { Command } from 'commander';
const program = new Command();
```

## Options

Options are defined with the `.option()` method, also serving as documentation for the options. Each option can have a short flag (single character) and a long name, separated by a comma, a space, or a vertical bar (`|`). To allow a wider range of short-ish flags than just single characters, you may also have two long options.

```js
program
  .option('-p, --port <number>', 'server port number')
  .option('--trace', 'add extra debugging output')
  .option('--ws, --workspace <name>', 'use a custom workspace')
```

The parsed options can be accessed by calling `.opts()` on a `Command` object, and are passed to the action handler.

Multi-word options like `--template-engine` are normalized to camelCase option names, resulting in properties such as `program.opts().templateEngine`.

An option and its option-argument can be separated by a space, or combined into the same argument. The option-argument can follow the short option directly, or follow an `=` for a long option.

```sh
serve -p 80
serve -p80
serve --port 80
serve --port=80
```

You can use `--` to indicate the end of the options, and any remaining arguments will be used without being interpreted.

By default, options on the command line are not positional, and can be specified before or after other arguments.

There are additional related routines for when `.opts()` is not enough:

- `.optsWithGlobals()` returns merged local and global option values
- `.getOptionValue()` and `.setOptionValue()` work with a single option value
- `.getOptionValueSource()` and `.setOptionValueWithSource()` include where the option value came from

### Common option types, boolean and value

The two most used option types are a boolean option, and an option which takes its value
from the following argument (declared with angle brackets like `--expect <value>`). Both are `undefined` unless specified on command line.

Example file: [options-common.js](./examples/options-common.js)

```js
program
  .option('-d, --debug', 'output extra debugging')
  .option('-s, --small', 'small pizza size')
  .option('-p, --pizza-type <type>', 'flavour of pizza');

program.parse(process.argv);

const options = program.opts();
if (options.debug) console.log(options);
console.log('pizza details:');
if (options.small) console.log('- small pizza size');
if (options.pizzaType) console.log(`- ${options.pizzaType}`);
```

```console
$ pizza-options -p
error: option '-p, --pizza-type <type>' argument missing
$ pizza-options -d -s -p vegetarian
{ debug: true, small: true, pizzaType: 'vegetarian' }
pizza details:
- small pizza size
- vegetarian
$ pizza-options --pizza-type=cheese
pizza details:
- cheese
```

Multiple boolean short options may be combined following the dash, and may be followed by a single short option taking a value.
For example, `-d -s -p cheese` may be written as `-ds -p cheese` or even `-dsp cheese`.

Options with an expected option-argument are greedy and will consume the following argument whatever the value.
So `--id -xyz` reads `-xyz` as the option-argument.

`program.parse(arguments)` processes the arguments, leaving any args not consumed by the program options in the `program.args` array. The parameter is optional and defaults to `process.argv`.

### Default option value

You can specify a default value for an option.

Example file: [options-defaults.js](./examples/options-defaults.js)

```js
program
  .option('-c, --cheese <type>', 'add the specified type of cheese', 'blue');

program.parse();

console.log(`cheese: ${program.opts().cheese}`);
```

```console
$ pizza-options
cheese: blue
$ pizza-options --cheese stilton
cheese: stilton
```

### Other option types, negatable boolean and boolean|value

You can define a boolean option long name with a leading `no-` to set the option value to `false` when used.
Defined alone, this also makes the option `true` by default.

If you define `--foo` first, adding `--no-foo` does not change the default value from what it would
otherwise be.

Example file: [options-negatable.js](./examples/options-negatable.js)

```js
program
  .option('--no-sauce', 'Remove sauce')
  .option('--cheese <flavour>', 'cheese flavour', 'mozzarella')
  .option('--no-cheese', 'plain with no cheese')
  .parse();

const options = program.opts();
const sauceStr = options.sauce ? 'sauce' : 'no sauce';
const cheeseStr = (options.cheese === false) ? 'no cheese' : `${options.cheese} cheese`;
console.log(`You ordered a pizza with ${sauceStr} and ${cheeseStr}`);
```

```console
$ pizza-options
You ordered a pizza with sauce and mozzarella cheese
$ pizza-options --sauce
error: unknown option '--sauce'
$ pizza-options --cheese=blue
You ordered a pizza with sauce and blue cheese
$ pizza-options --no-sauce --no-cheese
You ordered a pizza with no sauce and no cheese
```

You can specify an option which may be used as a boolean option but may optionally take an option-argument
(declared with square brackets, like `--optional [value]`).

Example file: [options-boolean-or-value.js](./examples/options-boolean-or-value.js)

```js
program
  .option('-c, --cheese [type]', 'Add cheese with optional type');

program.parse(process.argv);

const options = program.opts();
if (options.cheese === undefined) console.log('no cheese');
else if (options.cheese === true) console.log('add cheese');
else console.log(`add cheese type ${options.cheese}`);
```

```console
$ pizza-options
no cheese
$ pizza-options --cheese
add cheese
$ pizza-options --cheese mozzarella
add cheese type mozzarella
```

Options with an optional option-argument are not greedy and will ignore arguments starting with a dash.
So `id` behaves as a boolean option for `--id -ABCD`, but you can use a combined form if needed like `--id=-ABCD`.
Negative numbers are special and are accepted as an option-argument.

For information about possible ambiguous cases, see [options taking varying arguments](./docs/options-in-depth.md).

### Required option

You may specify a required (mandatory) option using `.requiredOption()`. The option must have a value after parsing, usually specified on the command line, or perhaps from a default value (e.g., from environment). 

The method is otherwise the same as `.option()` in format, taking flags and description, and optional default value or custom processing.

Example file: [options-required.js](./examples/options-required.js)

```js
program
  .requiredOption('-c, --cheese <type>', 'pizza must have cheese');

program.parse();
```

```console
$ pizza
error: required option '-c, --cheese <type>' not specified
```

### Variadic option

You may make an option variadic by appending `...` to the value placeholder when declaring the option. On the command line you
can then specify multiple option-arguments, and the parsed option value will be an array. The extra arguments
are read until the first argument starting with a dash. The special argument `--` stops option processing entirely. If a value
is specified in the same argument as the option, then no further values are read.

Example file: [options-variadic.js](./examples/options-variadic.js)

```js
program
  .option('-n, --number <numbers...>', 'specify numbers')
  .option('-l, --letter [letters...]', 'specify letters');

program.parse();

console.log('Options: ', program.opts());
console.log('Remaining arguments: ', program.args);
```

```console
$ collect -n 1 2 3 --letter a b c
Options:  { number: [ '1', '2', '3' ], letter: [ 'a', 'b', 'c' ] }
Remaining arguments:  []
$ collect --letter=A -n80 operand
Options:  { number: [ '80' ], letter: [ 'A' ] }
Remaining arguments:  [ 'operand' ]
$ collect --letter -n 1 -n 2 3 -- operand
Options:  { number: [ '1', '2', '3' ], letter: true }
Remaining arguments:  [ 'operand' ]
```

For information about possible ambiguous cases, see [options taking varying arguments](./docs/options-in-depth.md).

### Version option

The optional `.version()` method adds handling for displaying the command version. The default option flags are `-V` and `--version`. When used, the command prints the version number and exits.

```js
program.version('0.0.1');
```

```console
$ ./examples/pizza -V
0.0.1
```

You may change the flags and description by passing additional parameters to the `.version()` method, using
the same syntax for flags as the `.option()` method.

```js
program.version('0.0.1', '-v, --vers', 'output the current version');
```

### More configuration

You can add most options using the `.option()` method, but there are some additional features available
by constructing an `Option` explicitly for less common cases.

Example files: [options-extra.js](./examples/options-extra.js), [options-env.js](./examples/options-env.js), [options-conflicts.js](./examples/options-conflicts.js), [options-implies.js](./examples/options-implies.js)

```js
program
  .addOption(new Option('-s, --secret').hideHelp())
  .addOption(new Option('-t, --timeout <delay>', 'timeout in seconds').default(60, 'one minute'))
  .addOption(new Option('-d, --drink <size>', 'drink size').choices(['small', 'medium', 'large']))
  .addOption(new Option('-p, --port <number>', 'port number').env('PORT'))
  .addOption(new Option('--donate [amount]', 'optional donation in dollars').preset('20').argParser(parseFloat))
  .addOption(new Option('--disable-server', 'disables the server').conflicts('port'))
  .addOption(new Option('--free-drink', 'small drink included free ').implies({ drink: 'small' }));
```

```console
$ extra --help
Usage: help [options]

Options:
  -t, --timeout <delay>  timeout in seconds (default: one minute)
  -d, --drink <size>     drink cup size (choices: "small", "medium", "large")
  -p, --port <number>    port number (env: PORT)
  --donate [amount]      optional donation in dollars (preset: "20")
  --disable-server       disables the server
  --free-drink           small drink included free
  -h, --help             display help for command

$ extra --drink huge
error: option '-d, --drink <size>' argument 'huge' is invalid. Allowed choices are small, medium, large.

$ PORT=80 extra --donate --free-drink
Options:  { timeout: 60, donate: 20, port: '80', freeDrink: true, drink: 'small' }

$ extra --disable-server --port 8000
error: option '--disable-server' cannot be used with option '-p, --port <number>'
```

Specify a required (mandatory) option using the `Option` method `.makeOptionMandatory()`. This matches the `Command` method [`.requiredOption()`](#required-option).

### Custom option processing

You may specify a function to do custom processing of option-arguments. The callback function receives two parameters,
the user specified option-argument and the previous value for the option. It returns the new value for the option.

This allows you to coerce the option-argument to the desired type, or accumulate values, or do entirely custom processing.

You can optionally specify the default/starting value for the option after the function parameter.

Example file: [options-custom-processing.js](./examples/options-custom-processing.js)

```js
function myParseInt(value, dummyPrevious) {
  // parseInt takes a string and a radix
  const parsedValue = parseInt(value, 10);
  if (isNaN(parsedValue)) {
    throw new commander.InvalidArgumentError('Not a number.');
  }
  return parsedValue;
}

function increaseVerbosity(dummyValue, previous) {
  return previous + 1;
}

function collect(value, previous) {
  return previous.concat([value]);
}

function commaSeparatedList(value, dummyPrevious) {
  return value.split(',');
}

program
  .option('-f, --float <number>', 'float argument', parseFloat)
  .option('-i, --integer <number>', 'integer argument', myParseInt)
  .option('-v, --verbose', 'verbosity that can be increased', increaseVerbosity, 0)
  .option('-c, --collect <value>', 'repeatable value', collect, [])
  .option('-l, --list <items>', 'comma separated list', commaSeparatedList)
;

program.parse();

const options = program.opts();
if (options.float !== undefined) console.log(`float: ${options.float}`);
if (options.integer !== undefined) console.log(`integer: ${options.integer}`);
if (options.verbose > 0) console.log(`verbosity: ${options.verbose}`);
if (options.collect.length > 0) console.log(options.collect);
if (options.list !== undefined) console.log(options.list);
```

```console
$ custom -f 1e2
float: 100
$ custom --integer 2
integer: 2
$ custom -v -v -v
verbose: 3
$ custom -c a -c b -c c
[ 'a', 'b', 'c' ]
$ custom --list x,y,z
[ 'x', 'y', 'z' ]
```

## Commands

You can specify (sub)commands using `.command()` or `.addCommand()`. There are two ways these can be implemented: using an `.action()` handler attached to the command; or as a stand-alone executable file. (More detail about this later.)

Subcommands may be nested. Example file: [nestedCommands.js](./examples/nestedCommands.js).

In the first parameter to `.command()` you specify the command name. You may append the command-arguments after the command name, or specify them separately using `.argument()`. The arguments may be `<required>` or `[optional]`, and the last argument may also be `variadic...`.

You can use `.addCommand()` to add an already configured subcommand to the program.

For example:

```js
// Command implemented using action handler (description is supplied separately to `.command`)
// Returns new command for configuring.
program
  .command('clone <source> [destination]')
  .description('clone a repository into a newly created directory')
  .action((source, destination) => {
    console.log('clone command called');
  });

// Command implemented using stand-alone executable file, indicated by adding description as second parameter to `.command`.
// Returns `this` for adding more commands.
program
  .command('start <service>', 'start named service')
  .command('stop [service]', 'stop named service, or all if no name supplied');

// Command prepared separately.
// Returns `this` for adding more commands.
program
  .addCommand(build.makeBuildCommand());
```

Configuration options can be passed with the call to `.command()` and `.addCommand()`. Specifying `hidden: true` will
remove the command from the generated help output. Specifying `isDefault: true` will run the subcommand if no other
subcommand is specified. (Example file: [defaultCommand.js](./examples/defaultCommand.js).)

You can add alternative names for a command with `.alias()`. (Example file: [alias.js](./examples/alias.js).)

`.command()` automatically copies the inherited settings from the parent command to the newly created subcommand. This is only done during creation; any later setting changes to the parent are not inherited.

For safety, `.addCommand()` does not automatically copy the inherited settings from the parent command. There is a helper routine `.copyInheritedSettings()` for copying the settings when they are wanted.

### Command-arguments

For subcommands, you can specify the argument syntax in the call to `.command()` (as shown above). This
is the only method usable for subcommands implemented using a stand-alone executable.

Alternatively, you can instead use the following method. To configure a command, you can use `.argument()` to specify each expected command-argument.
You supply the argument name and an optional description. The argument may be `<required>` or `[optional]`.
You can specify a default value for an optional command-argument.

Example file: [argument.js](./examples/argument.js)

```js
program
  .version('0.1.0')
  .argument('<username>', 'user to login')
  .argument('[password]', 'password for user, if required', 'no password given')
  .action((username, password) => {
    console.log('username:', username);
    console.log('password:', password);
  });
```

The last argument of a command can be variadic, and _only_ the last argument.  To make an argument variadic, simply
append `...` to the argument name.

A variadic argument is passed to the action handler as an array.

```js
program
  .version('0.1.0')
  .command('rmdir')
  .argument('<dirs...>')
  .action(function (dirs) {
    dirs.forEach((dir) => {
      console.log('rmdir %s', dir);
    });
  });
```

There is a convenience method to add multiple arguments at once, but without descriptions:

```js
program
  .arguments('<username> <password>');
```

#### More configuration

There are some additional features available by constructing an `Argument` explicitly for less common cases.

Example file: [arguments-extra.js](./examples/arguments-extra.js)

```js
program
  .addArgument(new commander.Argument('<drink-size>', 'drink cup size').choices(['small', 'medium', 'large']))
  .addArgument(new commander.Argument('[timeout]', 'timeout in seconds').default(60, 'one minute'))
```

#### Custom argument processing

You may specify a function to do custom processing of command-arguments (like for option-arguments).
The callback function receives two parameters, the user specified command-argument and the previous value for the argument.
It returns the new value for the argument.

The processed argument values are passed to the action handler, and saved as `.processedArgs`.

You can optionally specify the default/starting value for the argument after the function parameter.

Example file: [arguments-custom-processing.js](./examples/arguments-custom-processing.js)

```js
program
  .command('add')
  .argument('<first>', 'integer argument', myParseInt)
  .argument('[second]', 'integer argument', myParseInt, 1000)
  .action((first, second) => {
    console.log(`${first} + ${second} = ${first + second}`);
  })
;
```

### Action handler

The action handler gets passed a parameter for each command-argument you declared, and two additional parameters
which are the parsed options and the command object itself.

Example file: [thank.js](./examples/thank.js)

```js
program
  .argument('<name>')
  .option('-t, --title <honorific>', 'title to use before name')
  .option('-d, --debug', 'display some debugging')
  .action((name, options, command) => {
    if (options.debug) {
      console.error('Called %s with options %o', command.name(), options);
    }
    const title = options.title ? `${options.title} ` : '';
    console.log(`Thank-you ${title}${name}`);
  });
```

If you prefer, you can work with the command directly and skip declaring the parameters for the action handler. If you use a function expression (but not an arrow function), the `this` keyword is set to the running command.

Example file: [action-this.js](./examples/action-this.js)

```js
program
  .command('serve')
  .argument('<script>')
  .option('-p, --port <number>', 'port number', 80)
  .action(function() {
    console.error('Run script %s on port %s', this.args[0], this.opts().port);
  });
```

You may supply an `async` action handler, in which case you call `.parseAsync()` rather than `.parse()`.

```js
async function run() { /* code goes here */ }

async function main() {
  program
    .command('run')
    .action(run);
  await program.parseAsync(process.argv);
}
```

A command's options and arguments on the command line are validated when the command is used. Any unknown options, missing arguments, or excess arguments will be reported as an error. 

You can suppress the unknown option check with `.allowUnknownOption()`. You can suppress the excess arguments check with `.allowExcessArguments()`.

### Stand-alone executable (sub)commands

When `.command()` is invoked with a description argument, this tells Commander that you're going to use stand-alone executables for subcommands.
Commander will search the files in the directory of the entry script for a file with the name combination `command-subcommand` (like `pm-install` or `pm-search` in the example below). The search includes trying common file extensions, like `.js`.
You may specify a custom name (and path) with the `executableFile` configuration option.
You may specify a custom search directory for subcommands with `.executableDir()`.

You handle the options for an executable (sub)command in the executable, and don't declare them at the top-level.

Example file: [pm](./examples/pm)

```js
program
  .name('pm')
  .version('0.1.0')
  .command('install [package-names...]', 'install one or more packages')
  .command('search [query]', 'search with optional query')
  .command('update', 'update installed packages', { executableFile: 'myUpdateSubCommand' })
  .command('list', 'list packages installed', { isDefault: true });

program.parse(process.argv);
```

If the program is designed to be installed globally, make sure the executables have proper modes, like `755`.

### Life cycle hooks

You can add callback hooks to a command for life cycle events.

Example file: [hook.js](./examples/hook.js)

```js
program
  .option('-t, --trace', 'display trace statements for commands')
  .hook('preAction', (thisCommand, actionCommand) => {
    if (thisCommand.opts().trace) {
      console.log(`About to call action handler for subcommand: ${actionCommand.name()}`);
      console.log('arguments: %O', actionCommand.args);
      console.log('options: %o', actionCommand.opts());
    }
  });
```

The callback hook can be `async`, in which case you call `.parseAsync()` rather than `.parse()`. You can add multiple hooks per event.

The supported events are:

| event name | when hook called | callback parameters |
| :-- | :-- | :-- |
| `preAction`, `postAction` |  before/after action handler for this command and its nested subcommands |   `(thisCommand, actionCommand)` |
| `preSubcommand` | before parsing direct subcommand  | `(thisCommand, subcommand)` |

For an overview of the life cycle events, see [parsing life cycle and hooks](./docs/parsing-and-hooks.md).

## Automated help

The help information is auto-generated based on the information commander already knows about your program. The default
help option is `-h,--help`.

Example file: [pizza](./examples/pizza)

```console
$ node ./examples/pizza --help
Usage: pizza [options]

An application for pizza ordering

Options:
  -p, --peppers        Add peppers
  -c, --cheese <type>  Add the specified type of cheese (default: "marble")
  -C, --no-cheese      You do not want any cheese
  -h, --help           display help for command
```

A `help` command is added by default if your command has subcommands. It can be used alone, or with a subcommand name to show
further help for the subcommand. These are effectively the same if the `shell` program has implicit help:

```sh
shell help
shell --help

shell help spawn
shell spawn --help
```

Long descriptions are wrapped to fit the available width. (However, a description that includes a line-break followed by whitespace is assumed to be pre-formatted and not wrapped.)

### Custom help

You can add extra text to be displayed along with the built-in help.

Example file: [custom-help](./examples/custom-help)

```js
program
  .option('-f, --foo', 'enable some foo');

program.addHelpText('after', `

Example call:
  $ custom-help --help`);
```

Yields the following help output:

```Text
Usage: custom-help [options]

Options:
  -f, --foo   enable some foo
  -h, --help  display help for command

Example call:
  $ custom-help --help
```

The positions in order displayed are:

- `beforeAll`: add to the program for a global banner or header
- `before`: display extra information before built-in help
- `after`: display extra information after built-in help
- `afterAll`: add to the program for a global footer (epilog)

The positions "beforeAll" and "afterAll" apply to the command and all its subcommands.

The second parameter can be a string, or a function returning a string. The function is passed a context object for your convenience. The properties are:

- `error`: a boolean for whether the help is being displayed due to a usage error
- `command`: the `Command` which is displaying the help

### Display help after errors

The default behaviour for usage errors is to just display a short error message.
You can change the behaviour to show the full help or a custom help message after an error.

```js
program.showHelpAfterError();
// or
program.showHelpAfterError('(add --help for additional information)');
```

```console
$ pizza --unknown
error: unknown option '--unknown'
(add --help for additional information)
```

The default behaviour is to suggest correct spelling after an error for an unknown command or option. You
can disable this.

```js
program.showSuggestionAfterError(false);
```

```console
$ pizza --hepl
error: unknown option '--hepl'
(Did you mean --help?)
```

### Display help from code

`.help()`: display help information and exit immediately. You can optionally pass `{ error: true }` to display on stderr and exit with an error status.

`.outputHelp()`: output help information without exiting. You can optionally pass `{ error: true }` to display on stderr.

`.helpInformation()`: get the built-in command help information as a string for processing or displaying yourself.

### .name

The command name appears in the help, and is also used for locating stand-alone executable subcommands.

You may specify the program name using `.name()` or in the `Command` constructor. For the program, Commander will
fall back to using the script name from the full arguments passed into `.parse()`. However, the script name varies
depending on how your program is launched, so you may wish to specify it explicitly.

```js
program.name('pizza');
const pm = new Command('pm');
```

Subcommands get a name when specified using `.command()`. If you create the subcommand yourself to use with `.addCommand()`,
then set the name using `.name()` or in the `Command` constructor.

### .usage

This allows you to customise the usage description in the first line of the help. Given:

```js
program
  .name("my-command")
  .usage("[global options] command")
```

The help will start with:

```Text
Usage: my-command [global options] command
```

### .description and .summary

The description appears in the help for the command. You can optionally supply a shorter
summary to use when listed as a subcommand of the program.

```js
program
  .command("duplicate")
  .summary("make a copy")
  .description(`Make a copy of the current project.
This may require additional disk space.
  `);
```

### .helpOption(flags, description)

By default, every command has a help option. You may change the default help flags and description. Pass `false` to disable the built-in help option.

```js
program
  .helpOption('-e, --HELP', 'read more information');
```

Alternatively, use `.addHelpOption()` to add an option you construct yourself.

### .helpCommand()

A help command is added by default if your command has subcommands. You can explicitly turn the implicit help command on or off with `.helpCommand(true)` and `.helpCommand(false)`.

You can both turn on and customise the help command by supplying the name and description:

```js
program.helpCommand('assist [command]', 'show assistance');
```

Alternatively, use `.addHelpCommand()` to add a command you construct yourself.

### Help Groups

The help by default lists options under the the heading `Options:` and commands under `Commands:`. You can create your own groups
with different headings. 

- The high-level way is to set the desired group heading while adding the options and commands, using `.optionsGroup()` and `.commandsGroup()`. 
- The low-level way is using `.helpGroup()` on an individual `Option` or `Command`.

Example file: [help-groups.js](./examples/help-groups.js)

### More configuration

The built-in help is formatted using the `Help` class.
You can configure the help by modifying data properties and methods using `.configureHelp()`, or by subclassing `Help` using `.createHelp()` .

Simple properties include `sortSubcommands`, `sortOptions`, and `showGlobalOptions`. You can add color using the style methods like `.styleTitle()`.

For more detail and examples of changing the displayed text, color, and layout, see: [Help in Depth](./docs/help-in-depth.md).

## Custom event listeners

You can execute custom actions by listening to `command` and `option` events.

```js
program.on('option:verbose', function () {
  process.env.VERBOSE = this.opts().verbose;
});
```

## Bits and pieces

### .parse() and .parseAsync()

Call with no parameters to parse `process.argv`. Detects Electron and special node options like `node --eval`. Easy mode!

Or, call with an array of strings to parse, and optionally where the user arguments start by specifying where the arguments are `from`:

- `'node'`: default, `argv[0]` is the application and `argv[1]` is the script being run, with user arguments after that
- `'electron'`: `argv[0]` is the application and `argv[1]` varies depending on whether the electron application is packaged
- `'user'`: just user arguments

For example:

```js
program.parse(); // parse process.argv and auto-detect electron and special node flags
program.parse(process.argv); // assume argv[0] is app and argv[1] is script
program.parse(['--port', '80'], { from: 'user' }); // just user supplied arguments, nothing special about argv[0]
```

Use `.parseAsync()` instead of `.parse()` if any of your action handlers are async.

### Parsing Configuration

If the default parsing does not suit your needs, there are some behaviours to support other usage patterns.

By default, program options are recognised before and after subcommands. To only look for program options before subcommands, use `.enablePositionalOptions()`. This lets you use
an option for a different purpose in subcommands.

Example file: [positional-options.js](./examples/positional-options.js)

With positional options, the `-b` is a program option in the first line and a subcommand option in the second line:

```sh
program -b subcommand
program subcommand -b
```

By default, options are recognised before and after command-arguments. To only process options that come
before the command-arguments, use `.passThroughOptions()`. This lets you pass the arguments and following options through to another program
without needing to use `--` to end the option processing.
To use pass through options in a subcommand, the program needs to enable positional options.

Example file: [pass-through-options.js](./examples/pass-through-options.js)

With pass through options, the `--port=80` is a program option in the first line and passed through as a command-argument in the second line:

```sh
program --port=80 arg
program arg --port=80
```

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.

By default, the argument processing displays an error for more command-arguments than expected.
To suppress the error for excess arguments, use `.allowExcessArguments()`.

### Legacy options as properties

Before Commander 7, the option values were stored as properties on the command.
This was convenient to code, but the downside was possible clashes with
existing properties of `Command`. 

You can revert to the old behaviour to run unmodified legacy code by using `.storeOptionsAsProperties()`.

```js
program
  .storeOptionsAsProperties()
  .option('-d, --debug')
  .action((commandAndOptions) => {
    if (commandAndOptions.debug) {
      console.error(`Called ${commandAndOptions.name()}`);
    }
  });
```

### TypeScript

**extra-typings:** There is an optional project to infer extra type information from the option and argument definitions.
This adds strong typing to the options returned by `.opts()` and the parameters to `.action()`.
For more, see the repo: [commander-js/extra-typings](https://github.com/commander-js/extra-typings).

```ts
import { Command } from '@commander-js/extra-typings';
```

**ts-node:** If you use `ts-node` and stand-alone executable subcommands written as `.ts` files, you need to call your program through node to get the subcommands called correctly, e.g.:

```sh
node -r ts-node/register pm.ts
```

### createCommand()

This factory function creates a new command. It is exported and may be used instead of using `new`, like:

```js
const { createCommand } = require('commander');
const program = createCommand();
```

`createCommand()` is also a method of the `Command` object, and creates a new command rather than a subcommand. This gets used internally
when creating subcommands using `.command()`, and you may override it to
customise the new subcommand. Example file: [custom-command-class.js](./examples/custom-command-class.js).

### Node options such as `--harmony`

You can enable `--harmony` option in two ways:

- Use `#! /usr/bin/env node --harmony` in the subcommands scripts. (Note: Windows does not support this pattern.)
- Use the `--harmony` option when calling the command, like `node --harmony examples/pm publish`. The `--harmony` option will be preserved when spawning subcommand processes.

### Debugging stand-alone executable subcommands

An executable subcommand is launched as a separate child process.

If you are using the node inspector for [debugging](https://nodejs.org/en/docs/guides/debugging-getting-started/) executable subcommands using `node --inspect` et al.,
the inspector port is incremented by 1 for the spawned subcommand.

If you are using VSCode to debug executable subcommands you need to set the `"autoAttachChildProcesses": true` flag in your `launch.json` configuration.

### npm run-script

By default, when you call your program using `run-script`, `npm` will parse any options on the command-line and they will not reach your program. Use
 `--` to stop the npm option parsing and pass through all the arguments.

 The synopsis for [`npm run-script`](https://docs.npmjs.com/cli/v9/commands/npm-run-script) explicitly shows the `--` for this reason:

```console
npm run-script <command> [-- <args>]
```

### Display error

This routine is available to invoke the Commander error handling for your own error conditions. (See also the next section about exit handling.)

As well as the error message, you can optionally specify the `exitCode` (used with `process.exit()`)
and `code` (used with `CommanderError`).

```js
program.error('Password must be longer than four characters');
program.error('Custom processing has failed', { exitCode: 2, code: 'my.custom.error' });
```

### Override exit and output handling

By default, Commander calls `process.exit()` when it detects errors, or after displaying the help or version. You can override
this behaviour and optionally supply a callback. The default override throws a `CommanderError`.

The override callback is passed a `CommanderError` with the properties:
- `exitCode`: number
- `code`: string 
- `message`: string

Commander expects the callback to terminate the normal program flow, and will call `process.exit()` if the callback returns.
The normal display of error messages or version or help is not affected by the override, which is called after the display.

```js
program.exitOverride();

try {
  program.parse(process.argv);
} catch (err) {
  // custom processing...
}
```

By default, Commander is configured for a command-line application and writes to stdout and stderr.
You can modify this behaviour for custom applications. In addition, you can modify the display of error messages.

Example file: [configure-output.js](./examples/configure-output.js)

```js
function errorColor(str) {
  // Add ANSI escape codes to display text in red.
  return `\x1b[31m${str}\x1b[0m`;
}

program
  .configureOutput({
    // Visibly override write routines as example!
    writeOut: (str) => process.stdout.write(`[OUT] ${str}`),
    writeErr: (str) => process.stdout.write(`[ERR] ${str}`),
    // Highlight errors in color.
    outputError: (str, write) => write(errorColor(str))
  });
```

### Additional documentation

There is more information available about:

- [deprecated](./docs/deprecated.md) features still supported for backwards compatibility
- [Help in Depth](./docs/help-in-depth.md) configuring help output
- [options taking varying arguments](./docs/options-in-depth.md)
- [parsing life cycle and hooks](./docs/parsing-and-hooks.md)
- [Release Policy](./docs/release-policy.md)

## Support

The current version of Commander is fully supported on Long Term Support versions of Node.js, and requires at least v20.

Older major versions of Commander receive security updates for 12 months. For more see: [Release Policy](./docs/release-policy.md).

The main forum for free and community support is the project [Issues](https://github.com/tj/commander.js/issues) on GitHub.

### Commander for enterprise

Available as part of the Tidelift Subscription

The maintainers of Commander and thousands of other packages are working with Tidelift to deliver commercial support and maintenance for the open source dependencies you use to build your applications. Save time, reduce risk, and improve code health, while paying the maintainers of the exact dependencies you use. [Learn more.](https://tidelift.com/subscription/pkg/npm-commander?utm_source=npm-commander&utm_medium=referral&utm_campaign=enterprise&utm_term=repo)


================================================
FILE: Readme_zh-CN.md
================================================
# Commander.js

[![Build Status](https://github.com/tj/commander.js/workflows/build/badge.svg)](https://github.com/tj/commander.js/actions?query=workflow%3A%22build%22)
[![NPM Version](http://img.shields.io/npm/v/commander.svg?style=flat)](https://www.npmjs.org/package/commander)
[![NPM Downloads](https://img.shields.io/npm/dm/commander.svg?style=flat)](https://npmcharts.com/compare/commander?minimal=true)
[![Install Size](https://packagephobia.now.sh/badge?p=commander)](https://packagephobia.now.sh/result?p=commander)

完整的 [node.js](http://nodejs.org) 命令行解决方案。

使用其他语言阅读:[English](./Readme.md) | 简体中文

- [Commander.js](#commanderjs)
  - [安装](#%e5%ae%89%e8%a3%85)
  - [快速开始](#%E5%BF%AB%E9%80%9F%E5%BC%80%E5%A7%8B)
  - [声明 program 变量](#%e5%a3%b0%e6%98%8e-program-%e5%8f%98%e9%87%8f)
  - [选项](#%e9%80%89%e9%a1%b9)
    - [常用选项类型,boolean 型选项和带参数的选项](#%e5%b8%b8%e7%94%a8%e9%80%89%e9%a1%b9%e7%b1%bb%e5%9e%8bboolean-%e5%9e%8b%e9%80%89%e9%a1%b9%e5%92%8c%e5%b8%a6%e5%8f%82%e6%95%b0%e9%80%89%e9%a1%b9)
    - [选项的默认值](#%E9%80%89%E9%A1%B9%E7%9A%84%E9%BB%98%E8%AE%A4%E5%80%BC)
    - [其他的选项类型,取反选项,以及可选参数的选项](#%E5%85%B6%E4%BB%96%E7%9A%84%E9%80%89%E9%A1%B9%E7%B1%BB%E5%9E%8B%EF%BC%8C%E5%8F%96%E5%8F%8D%E9%80%89%E9%A1%B9%EF%BC%8C%E4%BB%A5%E5%8F%8A%E5%8F%AF%E9%80%89%E5%8F%82%E6%95%B0%E7%9A%84%E9%80%89%E9%A1%B9)
    - [必填选项](#%e5%bf%85%e5%a1%ab%e9%80%89%e9%a1%b9)
    - [变长参数选项](#%e5%8f%98%e9%95%bf%e5%8f%82%e6%95%b0%e9%80%89%e9%a1%b9)
    - [版本选项](#%e7%89%88%e6%9c%ac%e9%80%89%e9%a1%b9)
    - [其他选项配置](#%E5%85%B6%E4%BB%96%E9%80%89%E9%A1%B9%E9%85%8D%E7%BD%AE)
    - [自定义选项处理](#%E8%87%AA%E5%AE%9A%E4%B9%89%E9%80%89%E9%A1%B9%E5%A4%84%E7%90%86)
  - [命令](#%e5%91%bd%e4%bb%a4)
    - [命令参数](#%E5%91%BD%E4%BB%A4%E5%8F%82%E6%95%B0)
      - [其他参数配置](#%E5%85%B6%E4%BB%96%E5%8F%82%E6%95%B0%E9%85%8D%E7%BD%AE)
      - [自定义参数处理](#%E8%87%AA%E5%AE%9A%E4%B9%89%E5%8F%82%E6%95%B0%E5%A4%84%E7%90%86)
    - [处理函数](#%E5%A4%84%E7%90%86%E5%87%BD%E6%95%B0)
    - [独立的可执行(子)命令](#%E7%8B%AC%E7%AB%8B%E7%9A%84%E5%8F%AF%E6%89%A7%E8%A1%8C%EF%BC%88%E5%AD%90%EF%BC%89%E5%91%BD%E4%BB%A4)
    - [生命周期钩子](#%E7%94%9F%E5%91%BD%E5%91%A8%E6%9C%9F%E9%92%A9%E5%AD%90)
  - [自动化帮助信息](#%e8%87%aa%e5%8a%a8%e5%8c%96%e5%b8%ae%e5%8a%a9%e4%bf%a1%e6%81%af)
    - [自定义帮助](#%e8%87%aa%e5%ae%9a%e4%b9%89%e5%b8%ae%e5%8a%a9)
    - [在出错后展示帮助信息](#%E5%9C%A8%E5%87%BA%E9%94%99%E5%90%8E%E5%B1%95%E7%A4%BA%E5%B8%AE%E5%8A%A9%E4%BF%A1%E6%81%AF)
    - [使用代码展示帮助信息](#%E4%BD%BF%E7%94%A8%E4%BB%A3%E7%A0%81%E5%B1%95%E7%A4%BA%E5%B8%AE%E5%8A%A9%E4%BF%A1%E6%81%AF)
    - [.name](#name)
    - [.usage](#usage)
    - [.description 和 .summary](#description-%E5%92%8C-summary)
    - [.helpOption(flags, description)](#helpoptionflags-description)
    - [.addHelpCommand()](#addhelpcommand)
    - [其他帮助配置](#%E5%85%B6%E4%BB%96%E5%B8%AE%E5%8A%A9%E9%85%8D%E7%BD%AE)
  - [自定义事件监听](#%e8%87%aa%e5%ae%9a%e4%b9%89%e4%ba%8b%e4%bb%b6%e7%9b%91%e5%90%ac)
  - [零碎知识](#%e9%9b%b6%e7%a2%8e%e7%9f%a5%e8%af%86)
    - [.parse() 和 .parseAsync()](#parse-%e5%92%8c-parseasync)
    - [解析配置](#%E8%A7%A3%E6%9E%90%E9%85%8D%E7%BD%AE)
    - [作为属性的遗留选项](#%E4%BD%9C%E4%B8%BA%E5%B1%9E%E6%80%A7%E7%9A%84%E9%81%97%E7%95%99%E9%80%89%E9%A1%B9)
    - [TypeScript](#typescript)
    - [createCommand()](#createCommand)
    - [Node 选项,如 --harmony](#node-%E9%80%89%E9%A1%B9%EF%BC%8C%E5%A6%82---harmony)
    - [调试子命令](#%e8%b0%83%e8%af%95%e5%ad%90%e5%91%bd%e4%bb%a4)
    - [显示错误](#%E6%98%BE%E7%A4%BA%E9%94%99%E8%AF%AF)
    - [重写退出和输出](#%E9%87%8D%E5%86%99%E9%80%80%E5%87%BA%E5%92%8C%E8%BE%93%E5%87%BA)
    - [其他文档](#%E5%85%B6%E4%BB%96%E6%96%87%E6%A1%A3)
  - [支持](#%e6%94%af%e6%8c%81)
    - [企业使用 Commander](#%e4%bc%81%e4%b8%9a%e4%bd%bf%e7%94%a8-commander)

关于本文档中使用的术语,请见[术语表](./docs/zh-CN/%E6%9C%AF%E8%AF%AD%E8%A1%A8.md)

## 安装

```sh
npm install commander
```

## 快速开始

编写代码来描述你的命令行界面。
Commander 负责将参数解析为选项和命令参数,为问题显示使用错误,并实现一个有帮助的系统。

Commander 是严格的,并且会针对无法识别的选项显示错误。
两种最常用的选项类型是布尔选项,和从参数中获取值的选项。

示例代码:[split.js](./examples/split.js)

```js
const { program } = require('commander');

program
  .option('--first')
  .option('-s, --separator <char>')
  .argument('<string>');

program.parse();

const options = program.opts();
const limit = options.first ? 1 : undefined;
console.log(program.args[0].split(options.separator, limit));
```

```console
$ node split.js -s / --fits a/b/c
error: unknown option '--fits'
(Did you mean --first?)
$ node split.js -s / --first a/b/c
[ 'a' ]
```

这是一个使用子命令并带有帮助描述的更完整的程序。在多命令程序中,每个命令(或命令的独立可执行文件)都有一个操作处理程序。

示例代码:[string-util.js](./examples/string-util.js)

```js
const { Command } = require('commander');
const program = new Command();

program
  .name('string-util')
  .description('CLI to some JavaScript string utilities')
  .version('0.8.0');

program.command('split')
  .description('Split a string into substrings and display as an array')
  .argument('<string>', 'string to split')
  .option('--first', 'display just the first substring')
  .option('-s, --separator <char>', 'separator character', ',')
  .action((str, options) => {
    const limit = options.first ? 1 : undefined;
    console.log(str.split(options.separator, limit));
  });

program.parse();
```

```console
$ node string-util.js help split
Usage: string-util split [options] <string>

Split a string into substrings and display as an array.

Arguments:
  string                  string to split

Options:
  --first                 display just the first substring
  -s, --separator <char>  separator character (default: ",")
  -h, --help              display help for command

$ node string-util.js split --separator=/ a/b/c
[ 'a', 'b', 'c' ]
```

更多示例可以在 [examples](https://github.com/tj/commander.js/tree/master/examples) 目录中找到。

## 声明 program 变量

为简化使用,Commander 提供了一个全局对象。本文档的示例代码均按此方法使用:

```js
// CommonJS (.cjs)
const { program } = require('commander');
```

如果程序较为复杂,用户需要以多种方式来使用 Commander,如单元测试等。创建本地 Command 对象是一种更好的方式:

```js
// CommonJS (.cjs)
const { Command } = require('commander');
const program = new Command();
```

```js
// ECMAScript (.mjs)
import { Command } from 'commander';
const program = new Command();
```

```ts
// TypeScript (.ts)
import { Command } from 'commander';
const program = new Command();
```

## 选项

Commander 使用`.option()`方法来定义选项,同时可以附加选项的简介。每个选项可以定义一个短选项名称(-后面接单个字符)和一个长选项名称(--后面接一个或多个单词),使用逗号、空格或`|`分隔。

解析后的选项可以通过`Command`对象上的`.opts()`方法获取,同时会被传递给命令处理函数。

对于多个单词的长选项,选项名会转为驼峰命名法(camel-case),例如`--template-engine`选项可通过`program.opts().templateEngine`获取。

选项及其选项参数可以用空格分隔,也可以组合成同一个参数。选项参数可以直接跟在短选项之后,也可以在长选项后面加上 `=`。

```sh
serve -p 80
serve -p80
serve --port 80
serve --port=80
```

`--`可以标记选项的结束,后续的参数均不会被命令解释,可以正常使用。

默认情况下,选项在命令行中的顺序不固定,一个选项可以在其他参数之前或之后指定。

当`.opts()`不够用时,还有其他相关方法:

- `.optsWithGlobals()`返回合并的本地和全局选项值
- `.getOptionValue()`和`.setOptionValue()`操作单个选项的值
- `.getOptionValueSource()`和`.setOptionValueWithSource()`包括选项值的来源

### 常用选项类型,boolean 型选项和带参数选项

有两种最常用的选项,一类是 boolean 型选项,选项无需配置参数,另一类选项则可以设置参数(使用尖括号声明在该选项后,如`--expect <value>`)。如果在命令行中不指定具体的选项及参数,则会被定义为`undefined`。

示例代码:[options-common.js](./examples/options-common.js)

```js
program
  .option('-d, --debug', 'output extra debugging')
  .option('-s, --small', 'small pizza size')
  .option('-p, --pizza-type <type>', 'flavour of pizza');

program.parse(process.argv);

const options = program.opts();
if (options.debug) console.log(options);
console.log('pizza details:');
if (options.small) console.log('- small pizza size');
if (options.pizzaType) console.log(`- ${options.pizzaType}`);
```

```console
$ pizza-options -p
error: option '-p, --pizza-type <type>' argument missing
$ pizza-options -d -s -p vegetarian
{ debug: true, small: true, pizzaType: 'vegetarian' }
pizza details:
- small pizza size
- vegetarian
$ pizza-options --pizza-type=cheese
pizza details:
- cheese
```

多个布尔短选项可以在破折号之后组合在一起,并且可以跟一个取值的单一选项。
例如 `-d -s -p cheese` 可以写成 `-ds -p cheese` 甚至 `-dsp cheese`。

具有预期选项参数的选项是贪婪的,并且无论值如何,都会消耗参数。
所以 `--id -xyz` 读取 `-xyz` 作为选项参数。

通过`program.parse(arguments)`方法处理参数,没有被使用的选项会存放在`program.args`数组中。该方法的参数是可选的,默认值为`process.argv`。

### 选项的默认值

选项可以设置一个默认值。

示例代码:[options-defaults.js](./examples/options-defaults.js)

```js
program
  .option('-c, --cheese <type>', 'add the specified type of cheese', 'blue');

program.parse();

console.log(`cheese: ${program.opts().cheese}`);
```

```console
$ pizza-options
cheese: blue
$ pizza-options --cheese stilton
cheese: stilton
```

### 其他的选项类型,取反选项,以及可选参数的选项

可以定义一个以`no-`开头的 boolean 型长选项。在命令行中使用该选项时,会将对应选项的值置为`false`。当只定义了带`no-`的选项,未定义对应不带`no-`的选项时,该选项的默认值会被置为`true`。

如果已经定义了`--foo`,那么再定义`--no-foo`并不会改变它本来的默认值。

示例代码:[options-negatable.js](./examples/options-negatable.js)

```js
program
  .option('--no-sauce', 'Remove sauce')
  .option('--cheese <flavour>', 'cheese flavour', 'mozzarella')
  .option('--no-cheese', 'plain with no cheese')
  .parse();

const options = program.opts();
const sauceStr = options.sauce ? 'sauce' : 'no sauce';
const cheeseStr = (options.cheese === false) ? 'no cheese' : `${options.cheese} cheese`;
console.log(`You ordered a pizza with ${sauceStr} and ${cheeseStr}`);
```

```console
$ pizza-options
You ordered a pizza with sauce and mozzarella cheese
$ pizza-options --sauce
error: unknown option '--sauce'
$ pizza-options --cheese=blue
You ordered a pizza with sauce and blue cheese
$ pizza-options --no-sauce --no-cheese
You ordered a pizza with no sauce and no cheese
```

选项的参数使用方括号声明表示参数是可选参数(如`--optional [value]`)。该选项在不带参数时可用作 boolean 选项,在带有参数时则从参数中得到值。

示例代码:[options-boolean-or-value.js](./examples/options-boolean-or-value.js)

```js
program
  .option('-c, --cheese [type]', 'Add cheese with optional type');

program.parse(process.argv);

const options = program.opts();
if (options.cheese === undefined) console.log('no cheese');
else if (options.cheese === true) console.log('add cheese');
else console.log(`add cheese type ${options.cheese}`);
```

```console
$ pizza-options
no cheese
$ pizza-options --cheese
add cheese
$ pizza-options --cheese mozzarella
add cheese type mozzarella
```

带有可选选项参数的选项不是贪婪的,并且会忽略以破折号开头的参数。因此对于`--id -5`,`id`表现为布尔选项,但如果需要,您可以使用组合形式,例如 `--id=-5`。

关于可能有歧义的用例,请见[可变参数的选项](./docs/zh-CN/%E5%8F%AF%E5%8F%98%E5%8F%82%E6%95%B0%E7%9A%84%E9%80%89%E9%A1%B9.md)。

### 必填选项

通过`.requiredOption()`方法可以设置选项为必填。必填选项要么设有默认值,要么必须在命令行中输入,对应的属性字段在解析时必定会有赋值。该方法其余参数与`.option()`一致。

示例代码:[options-required.js](./examples/options-required.js)

```js
program
  .requiredOption('-c, --cheese <type>', 'pizza must have cheese');

program.parse();
```

```console
$ pizza
error: required option '-c, --cheese <type>' not specified
```

### 变长参数选项

定义选项时,可以通过使用`...`来设置参数为可变长参数。在命令行中,用户可以输入多个参数,解析后会以数组形式存储在对应属性字段中。在输入下一个选项前(`-`或`--`开头),用户输入的指令均会被视作变长参数。与普通参数一样的是,可以通过`--`标记当前命令的结束。

示例代码:[options-variadic.js](./examples/options-variadic.js)

```js
program
  .option('-n, --number <numbers...>', 'specify numbers')
  .option('-l, --letter [letters...]', 'specify letters');

program.parse();

console.log('Options: ', program.opts());
console.log('Remaining arguments: ', program.args);
```

```console
$ collect -n 1 2 3 --letter a b c
Options:  { number: [ '1', '2', '3' ], letter: [ 'a', 'b', 'c' ] }
Remaining arguments:  []
$ collect --letter=A -n80 operand
Options:  { number: [ '80' ], letter: [ 'A' ] }
Remaining arguments:  [ 'operand' ]
$ collect --letter -n 1 -n 2 3 -- operand
Options:  { number: [ '1', '2', '3' ], letter: true }
Remaining arguments:  [ 'operand' ]
```

关于可能有歧义的用例,请见[可变参数的选项](./docs/zh-CN/%E5%8F%AF%E5%8F%98%E5%8F%82%E6%95%B0%E7%9A%84%E9%80%89%E9%A1%B9.md)。

### 版本选项

`.version()`方法可以设置版本,其默认选项为`-V`和`--version`,设置了版本后,命令行会输出当前的版本号。

```js
program.version('0.0.1');
```

```console
$ ./examples/pizza -V
0.0.1
```

版本选项也支持自定义设置选项名称,可以在`.version()`方法里再传递一些参数(长选项名称、描述信息),用法与`.option()`方法类似。

```bash
program.version('0.0.1', '-v, --vers', 'output the current version');
```

### 其他选项配置

大多数情况下,选项均可通过`.option()`方法添加。但对某些不常见的用例,也可以直接构造`Option`对象,对选项进行更详尽的配置。

示例代码:[options-extra.js](./examples/options-extra.js), [options-env.js](./examples/options-env.js), [options-conflicts.js](./examples/options-conflicts.js), [options-implies.js](./examples/options-implies.js)

```js
program
  .addOption(new Option('-s, --secret').hideHelp())
  .addOption(new Option('-t, --timeout <delay>', 'timeout in seconds').default(60, 'one minute'))
  .addOption(new Option('-d, --drink <size>', 'drink size').choices(['small', 'medium', 'large']))
  .addOption(new Option('-p, --port <number>', 'port number').env('PORT'))
  .addOption(new Option('--donate [amount]', 'optional donation in dollars').preset('20').argParser(parseFloat))
  .addOption(new Option('--disable-server', 'disables the server').conflicts('port'))
  .addOption(new Option('--free-drink', 'small drink included free ').implies({ drink: 'small' }));
```

```console
$ extra --help
Usage: help [options]

Options:
  -t, --timeout <delay>  timeout in seconds (default: one minute)
  -d, --drink <size>     drink cup size (choices: "small", "medium", "large")
  -p, --port <number>    port number (env: PORT)
  --donate [amount]      optional donation in dollars (preset: "20")
  --disable-server       disables the server
  --free-drink           small drink included free
  -h, --help             display help for command

$ extra --drink huge
error: option '-d, --drink <size>' argument 'huge' is invalid. Allowed choices are small, medium, large.

$ PORT=80 extra --donate --free-drink
Options:  { timeout: 60, donate: 20, port: '80', freeDrink: true, drink: 'small' }

$ extra --disable-server --port 8000
error: option '--disable-server' cannot be used with option '-p, --port <number>'
```

### 自定义选项处理

选项的参数可以通过自定义函数来处理,该函数接收两个参数,即用户新输入的参数值和当前已有的参数值(即上一次调用自定义处理函数后的返回值),返回新的选项参数值。

自定义函数适用场景包括参数类型转换,参数暂存,或者其他自定义处理的场景。

可以在自定义函数的后面设置选项参数的默认值或初始值(例如参数用列表暂存时需要设置一个初始空列表)。

示例代码:[options-custom-processing.js](./examples/options-custom-processing.js)

```js
function myParseInt(value, dummyPrevious) {
  // parseInt 参数为字符串和进制数
  const parsedValue = parseInt(value, 10);
  if (isNaN(parsedValue)) {
    throw new commander.InvalidArgumentError('Not a number.');
  }
  return parsedValue;
}

function increaseVerbosity(dummyValue, previous) {
  return previous + 1;
}

function collect(value, previous) {
  return previous.concat([value]);
}

function commaSeparatedList(value, dummyPrevious) {
  return value.split(',');
}

program
  .option('-f, --float <number>', 'float argument', parseFloat)
  .option('-i, --integer <number>', 'integer argument', myParseInt)
  .option('-v, --verbose', 'verbosity that can be increased', increaseVerbosity, 0)
  .option('-c, --collect <value>', 'repeatable value', collect, [])
  .option('-l, --list <items>', 'comma separated list', commaSeparatedList)
;

program.parse();

const options = program.opts();
if (options.float !== undefined) console.log(`float: ${options.float}`);
if (options.integer !== undefined) console.log(`integer: ${options.integer}`);
if (options.verbose > 0) console.log(`verbosity: ${options.verbose}`);
if (options.collect.length > 0) console.log(options.collect);
if (options.list !== undefined) console.log(options.list);
```

```console
$ custom -f 1e2
float: 100
$ custom --integer 2
integer: 2
$ custom -v -v -v
verbose: 3
$ custom -c a -c b -c c
[ 'a', 'b', 'c' ]
$ custom --list x,y,z
[ 'x', 'y', 'z' ]
```

## 命令

通过`.command()`或`.addCommand()`可以配置命令,有两种实现方式:为命令绑定处理函数,或者将命令单独写成一个可执行文件(详述见后文)。子命令支持嵌套([示例代码](./examples/nestedCommands.js))。

`.command()`的第一个参数为命令名称。命令参数可以跟在名称后面,也可以用`.argument()`单独指定。参数可为必选的(尖括号表示)、可选的(方括号表示)或变长参数(点号表示,如果使用,只能是最后一个参数)。

使用`.addCommand()`向`program`增加配置好的子命令。

例如:

```js
// 通过绑定处理函数实现命令(这里的指令描述为放在`.command`中)
// 返回新生成的命令(即该子命令)以供继续配置
program
  .command('clone <source> [destination]')
  .description('clone a repository into a newly created directory')
  .action((source, destination) => {
    console.log('clone command called');
  });

// 通过独立的的可执行文件实现命令 (注意这里指令描述是作为`.command`的第二个参数)
// 返回最顶层的命令以供继续添加子命令
program
  .command('start <service>', 'start named service')
  .command('stop [service]', 'stop named service, or all if no name supplied');

// 分别装配命令
// 返回最顶层的命令以供继续添加子命令
program
  .addCommand(build.makeBuildCommand());
```

使用`.command()`和`addCommand()`来指定选项的相关设置。当设置`hidden: true`时,该命令不会打印在帮助信息里。当设置`isDefault: true`时,若没有指定其他子命令,则会默认执行这个命令([样例](./examples/defaultCommand.js))。

### 命令参数

如上所述,子命令的参数可以通过`.command()`指定。对于有独立可执行文件的子命令来说,参数只能以这种方法指定。而对其他子命令,参数也可用以下方法。

在`Command`对象上使用`.argument()`来按次序指定命令参数。该方法接受参数名称和参数描述。参数可为必选的(尖括号表示,例如`<required>`)或可选的(方括号表示,例如`[optional]`)。

示例代码:[argument.js](./examples/argument.js)

```js
program
  .version('0.1.0')
  .argument('<username>', 'user to login')
  .argument('[password]', 'password for user, if required', 'no password given')
  .action((username, password) => {
    console.log('username:', username);
    console.log('password:', password);
  });
```

在参数名后加上`...`来声明可变参数,且只有最后一个参数支持这种用法。可变参数会以数组的形式传递给处理函数。例如:

```js
program
  .version('0.1.0')
  .command('rmdir')
  .argument('<dirs...>')
  .action(function (dirs) {
    dirs.forEach((dir) => {
      console.log('rmdir %s', dir);
    });
  });
```

有一种便捷方式可以一次性指定多个参数,但不包含参数描述:

```js
program
  .arguments('<username> <password>');
```

#### 其他参数配置

有少数附加功能可以直接构造`Argument`对象,对参数进行更详尽的配置。

示例代码:[arguments-extra.js](./examples/arguments-extra.js)

```js
program
  .addArgument(new commander.Argument('<drink-size>', 'drink cup size').choices(['small', 'medium', 'large']))
  .addArgument(new commander.Argument('[timeout]', 'timeout in seconds').default(60, 'one minute'))
```

#### 自定义参数处理

选项的参数可以通过自定义函数来处理(与处理选项参数时类似),该函数接收两个参数:用户新输入的参数值和当前已有的参数值(即上一次调用自定义处理函数后的返回值),返回新的命令参数值。

处理后的参数值会传递给命令处理函数,同时可通过`.processedArgs`获取。

可以在自定义函数的后面设置命令参数的默认值或初始值。

示例代码:[arguments-custom-processing.js](./examples/arguments-custom-processing.js)

```js
program
  .command('add')
  .argument('<first>', 'integer argument', myParseInt)
  .argument('[second]', 'integer argument', myParseInt, 1000)
  .action((first, second) => {
    console.log(`${first} + ${second} = ${first + second}`);
  })
;
```

### 处理函数

命令处理函数的参数,为该命令声明的所有参数,除此之外还会附加两个额外参数:一个是解析出的选项,另一个则是该命令对象自身。

示例代码:[thank.js](./examples/thank.js)

```js
program
  .argument('<name>')
  .option('-t, --title <honorific>', 'title to use before name')
  .option('-d, --debug', 'display some debugging')
  .action((name, options, command) => {
    if (options.debug) {
      console.error('Called %s with options %o', command.name(), options);
    }
    const title = options.title ? `${options.title} ` : '';
    console.log(`Thank-you ${title}${name}`);
  });
```

如果你愿意,你可以跳过为处理函数声明参数直接使用 command。 `this` 关键字设置为运行命令,可以在函数表达式中使用(但不能从箭头函数中使用)。

示例代码:[action-this.js](./examples/action-this.js)

```js
program
  .command('serve')
  .argument('<script>')
  .option('-p, --port <number>', 'port number', 80)
  .action(function() {
    console.error('Run script %s on port %s', this.args[0], this.opts().port);
  });
```

处理函数支持`async`,相应的,需要使用`.parseAsync`代替`.parse`。

```js
async function run() { /* 在这里编写代码 */ }

async function main() {
  program
    .command('run')
    .action(run);
  await program.parseAsync(process.argv);
}
```

使用命令时,所给的选项和命令参数会被验证是否有效。凡是有未知的选项,或缺少所需的命令参数,都会报错。
如要允许使用未知的选项,可以调用`.allowUnknownOption()`。默认情况下,传入过多的参数并不报错,但也可以通过调用`.allowExcessArguments(false)`来启用过多参数的报错。

### 独立的可执行(子)命令

当`.command()`带有描述参数时,就意味着使用独立的可执行文件作为子命令。
Commander 会尝试在入口脚本的目录中搜索名称组合为 `command-subcommand` 的文件,如以下示例中的 `pm-install` 或 `pm-search`。搜索包括尝试常见的文件扩展名,如`.js`。
你可以使用 `executableFile` 配置选项指定自定义名称(和路径)。
你可以使用 `.executableDir()` 为子命令指定自定义搜索目录。

你可以在可执行文件里处理(子)命令的选项,而不必在顶层声明它们。

示例代码:[pm](./examples/pm)

```js
program
  .name('pm')
  .version('0.1.0')
  .command('install [name]', 'install one or more packages')
  .command('search [query]', 'search with optional query')
  .command('update', 'update installed packages', { executableFile: 'myUpdateSubCommand' })
  .command('list', 'list packages installed', { isDefault: true });

program.parse(process.argv);
```

如果该命令需要支持全局安装,请确保有对应的权限,例如`755`。

### 生命周期钩子

可以在命令的生命周期事件上设置回调函数。

示例代码:[hook.js](./examples/hook.js)

```js
program
  .option('-t, --trace', 'display trace statements for commands')
  .hook('preAction', (thisCommand, actionCommand) => {
    if (thisCommand.opts().trace) {
      console.log(`About to call action handler for subcommand: ${actionCommand.name()}`);
      console.log('arguments: %O', actionCommand.args);
      console.log('options: %o', actionCommand.opts());
    }
  });
```

钩子函数支持`async`,相应的,需要使用`.parseAsync`代替`.parse`。一个事件上可以添加多个钩子。

支持的事件有:

| 事件名称 | 触发时机 | 参数列表 |
| :-- | :-- | :-- |
| `preAction`, `postAction` | 本命令或其子命令的处理函数执行前/后 |   `(thisCommand, actionCommand)` |
| `preSubcommand` | 在其直接子命令解析之前调用  | `(thisCommand, subcommand)` |

## 自动化帮助信息

帮助信息是 Commander 基于你的程序自动生成的,默认的帮助选项是`-h,--help`。

示例代码:[pizza](./examples/pizza)

```console
$ node ./examples/pizza --help
Usage: pizza [options]

An application for pizza ordering

Options:
  -p, --peppers        Add peppers
  -c, --cheese <type>  Add the specified type of cheese (default: "marble")
  -C, --no-cheese      You do not want any cheese
  -h, --help           display help for command
```

如果你的命令中包含了子命令,会默认添加`help`命令,它可以单独使用,也可以与子命令一起使用来提示更多帮助信息。用法与`shell`程序类似:

```sh
shell help
shell --help

shell help spawn
shell spawn --help
```

### 自定义帮助

可以添加额外的帮助信息,与内建的帮助一同展示。

示例代码:[custom-help](./examples/custom-help)

```js
program
  .option('-f, --foo', 'enable some foo');

program.addHelpText('after', `

Example call:
  $ custom-help --help`);
```

将会输出以下的帮助信息:

```Text
Usage: custom-help [options]

Options:
  -f, --foo   enable some foo
  -h, --help  display help for command

Example call:
  $ custom-help --help
```

位置参数对应的展示方式如下:

- `beforeAll`:作为全局标头栏展示
- `before`:在内建帮助信息之前展示
- `after`:在内建帮助信息之后展示
- `afterAll`:作为全局末尾栏展示

`beforeAll`和`afterAll`两个参数作用于命令及其所有的子命令。

第二个参数可以是一个字符串,也可以是一个返回字符串的函数。对后者而言,为便于使用,该函数可以接受一个上下文对象,它有如下属性:

- `error`:boolean 值,代表该帮助信息是否由于不当使用而展示
- `command`:代表展示该帮助信息的`Command`对象

### 在出错后展示帮助信息

默认情况下,出现命令用法错误时只会显示错误信息。可以选择在出错后展示完整的帮助或自定义的帮助信息。

```js
program.showHelpAfterError();
// 或者
program.showHelpAfterError('(add --help for additional information)');
```

```console
$ pizza --unknown
error: unknown option '--unknown'
(add --help for additional information)
```

默认行为是在出现未知命令或选项错误后建议正确拼写。你可以禁用此功能。

```js
program.showSuggestionAfterError(false);
```

```console
$ pizza --hepl
error: unknown option '--hepl'
(Did you mean --help?)
```

### 使用代码展示帮助信息

`.help()`:展示帮助信息并退出。可以通过传入`{ error: true }`来让帮助信息从 stderr 输出,并以代表错误的状态码退出程序。

`.outputHelp()`:只展示帮助信息,不退出程序。传入`{ error: true }`可以让帮助信息从 stderr 输出。

`.helpInformation()`:得到字符串形式的内建的帮助信息,以便用于自定义的处理及展示。

### .name

命令名称出现在帮助中,也用于定位独立的可执行子命令。

你可以使用 `.name()` 或在 Command 构造函数中指定程序名称。对于 program ,Commander 会使用传递给 `.parse()` 的完整参数中的脚本名称。但是,脚本名称会根据程序的启动方式而有所不同,因此您可能希望明确指定它。

```js
program.name('pizza');
const pm = new Command('pm');
```

使用 `.command()` 指定时,子命令会获得名称。如果您自己创建子命令以与 `.addCommand()` 一起使用,则使用 `.name()` 或在 Command 构造函数中设置名称。

### .usage

通过这个选项可以修改帮助信息的首行提示,例如:

```js
program
  .name("my-command")
  .usage("[global options] command")
```

帮助信息开头如下:

```Text
Usage: my-command [global options] command
```

### .description 和 .summary

description 出现在命令的帮助中。当列为程序的子命令时,你可以选择提供更短的 summary 以供使用。

```js
program
  .command("duplicate")
  .summary("make a copy")
  .description(`Make a copy of the current project.
This may require additional disk space.
  `);
```

### .helpOption(flags, description)

每一个命令都带有一个默认的帮助选项。你可以改变 `flags` 和 `description` 参数。传入 `false` 则会禁用内建的帮助信息。

```js
program
  .helpOption('-e, --HELP', 'read more information');
```

### .addHelpCommand()

如果一个命令拥有子命令,它也将有一个默认的帮助子命令。使用`.addHelpCommand()`和`.addHelpCommand(false)`可以打开或关闭默认的帮助子命令。

也可以自定义名字和描述:

```js
program.addHelpCommand('assist [command]', 'show assistance');
```

### 其他帮助配置

内建帮助信息通过`Help`类进行格式化。如有需要,可以使用`.configureHelp()`来更改其数据属性和方法,或使用`.createHelp()`来创建子类,从而配置`Help`类的行为。

数据属性包括:

- `helpWidth`:指明帮助信息的宽度。可在单元测试中使用。
- `sortSubcommands`:以字母序排列子命令
- `sortOptions`:以字母序排列选项

可以得到可视化的参数列表,选项列表,以及子命令列表。列表的每个元素都具有`_term_`和`_description_`属性,并可以对其进行格式化。关于其使用方式,请参考`.formatHelp()`。

示例代码:[configure-help.js](./examples/configure-help.js)

```js
program.configureHelp({
  sortSubcommands: true,
  subcommandTerm: (cmd) => cmd.name() // 显示名称,而非用法
});
```

## 自定义事件监听

监听命令和选项可以执行自定义函数。

```js
program.on('option:verbose', function () {
  process.env.VERBOSE = this.opts().verbose;
});
```

## 零碎知识

### .parse() 和 .parseAsync()

`.parse`的第一个参数是要解析的字符串数组,也可以省略参数而使用`process.argv`。

如果参数遵循与 node 不同的约定,可以在第二个参数中传递`from`选项:

- `node`:默认值,`argv[0]`是应用,`argv[1]`是要跑的脚本,后续为用户参数;
- `electron`:`argv[1]`根据 electron 应用是否打包而变化;
- `user`:来自用户的所有参数。

例如:

```js
program.parse(process.argv); // 指明,按 node 约定
program.parse(); // 默认,自动识别 electron
program.parse(['-f', 'filename'], { from: 'user' });
```

### 解析配置

当默认的解析方式无法满足需要,Commander 也提供了其他的解析行为。

默认情况下,程序的选项在子命令前后均可被识别。如要只允许选项出现在子命令之前,可以使用`.enablePositionalOptions()`。这样可以在命令和子命令中使用意义不同的同名选项。

示例代码:[positional-options.js](./examples/positional-options.js)

当启用了带顺序的选项解析,以下程序中,`-b`选项在第一行中将被解析为程序顶层的选项,而在第二行中则被解析为子命令的选项:

```sh
program -b subcommand
program subcommand -b
```

默认情况下,选项在命令参数前后均可被识别。如要使选项仅在命令参数前被识别,可以使用`.passThroughOptions()`。这样可以把参数和跟随的选项传递给另一程序,而无需使用`--`来终止选项解析。
如要在子命令中使用此功能,必须首先启用带顺序的选项解析。

示例代码:[pass-through-options.js](./examples/pass-through-options.js)

当启用此功能时,以下程序中,`--port=80`在第一行中会被解析为程序的选项,而在第二行中则会被解析为一个命令参数:

```sh
program --port=80 arg
program arg --port=80
```

默认情况下,使用未知选项会提示错误。如要将未知选项视作普通命令参数,并继续处理其他部分,可以使用`.allowUnknownOption()`。这样可以混用已知和未知的选项。

默认情况下,传入过多的命令参数并不会报错。可以使用`.allowExcessArguments(false)`来启用这一检查。

### 作为属性的遗留选项

在 Commander 7 以前,选项的值是作为属性存储在命令对象上的。
这种处理方式便于实现,但缺点在于,选项可能会与`Command`的已有属性相冲突。通过使用`.storeOptionsAsProperties()`,可以恢复到这种旧的处理方式,并可以不加改动地继续运行遗留代码。

```js
program
  .storeOptionsAsProperties()
  .option('-d, --debug')
  .action((commandAndOptions) => {
    if (commandAndOptions.debug) {
      console.error(`Called ${commandAndOptions.name()}`);
    }
  });
```

### TypeScript

如果你使用 ts-node,并有`.ts`文件作为独立可执行文件,那么需要用 node 运行你的程序以使子命令能正确调用,例如:

```sh
node -r ts-node/register pm.ts
```

### createCommand()

使用这个工厂方法可以创建新命令,此时不需要使用`new`,如

```bash
const { createCommand } = require('commander');
const program = createCommand();
```

`createCommand`同时也是`Command`对象的一个方法,可以创建一个新的命令(而非子命令),使用`.command()`创建子命令时内部会调用该方法,具体使用方式可参考 [custom-command-class.js](./examples/custom-command-class.js)。

### Node 选项,如 --harmony

要使用`--harmony`等选项有以下两种方式:

- 在子命令脚本中加上`#!/usr/bin/env node --harmony`。注:Windows 系统不支持;
- 调用时加上`--harmony`参数,例如`node --harmony examples/pm publish`。`--harmony`选项在开启子进程时仍会保留。

### 调试子命令

一个可执行的子命令会作为单独的子进程执行。

如果使用 node inspector 的`node -inspect`等命令来[调试](https://nodejs.org/en/docs/guides/debugging-getting-started/)可执行命令,对于生成的子命令,inspector 端口会递增 1。

如果想使用 VSCode 调试,则需要在`launch.json`配置文件里设置`"autoAttachChildProcesses": true`。

### 显示错误

你可用于针对自己的错误情况调用 Commander 错误处理。(另请参阅下一节有关退出处理的内容)

除了错误消息,你还可以选择指定 `exitCode`(与 `process.exit` 一起使用)和 `code`(与 `CommanderError` 一起使用)

```js
program.error('Password must be longer than four characters');
program.error('Custom processing has failed', { exitCode: 2, code: 'my.custom.error' });
```

### 重写退出和输出

默认情况下,在检测到错误、打印帮助信息或版本信息时 Commander 会调用`process.exit`方法。其默认实现会抛出一个`CommanderError`,可以重写该方法并提供一个回调函数(可选)。

回调函数的参数为`CommanderError`,属性包括 Number 型的`exitCode`、String 型的`code`和`message`。子命令完成调用后会开始异步处理。正常情况下,打印错误信息、帮助信息或版本信息不会被重写影响,因为重写会发生在打印之后。

```js
program.exitOverride();

try {
  program.parse(process.argv);
} catch (err) {
  // 自定义处理...
}
```

Commander 默认用作命令行应用,其输出写入 stdout 和 stderr。
对于其他应用类型,这一行为可以修改。并且可以修改错误信息的展示方式。

示例代码:[configure-output.js](./examples/configure-output.js)

```js
function errorColor(str) {
  // 添加 ANSI 转义字符,以将文本输出为红色
  return `\x1b[31m${str}\x1b[0m`;
}

program
  .configureOutput({
    // 此处使输出变得容易区分
    writeOut: (str) => process.stdout.write(`[OUT] ${str}`),
    writeErr: (str) => process.stdout.write(`[ERR] ${str}`),
    // 将错误高亮显示
    outputError: (str, write) => write(errorColor(str))
  });
```

### 其他文档

请参考关于如下话题的其他文档:

- [不再推荐使用的功能](./docs/zh-CN/%E4%B8%8D%E5%86%8D%E6%8E%A8%E8%8D%90%E4%BD%BF%E7%94%A8%E7%9A%84%E5%8A%9F%E8%83%BD.md)。这些功能仍受到支持,以保证向后兼容。
- [可变参数的选项](./docs/zh-CN/%E5%8F%AF%E5%8F%98%E5%8F%82%E6%95%B0%E7%9A%84%E9%80%89%E9%A1%B9.md)

## 支持

当前版本的 Commander 在 LTS 版本的 Node.js 上完全支持。并且至少需要 v18。
(使用更低版本 Node.js 的用户建议安装更低版本的 Commander)

社区支持请访问项目的 [Issues](https://github.com/tj/commander.js/issues)。

### 企业使用 Commander

作为 Tidelift 订阅的一部分。

Commander 和很多其他包的维护者已与 Tidelift 合作,面向企业提供开源依赖的商业支持与维护。企业可以向相关依赖包的维护者支付一定的费用,帮助企业节省时间,降低风险,改进代码运行情况。[了解更多](https://tidelift.com/subscription/pkg/npm-commander?utm_source=npm-commander&utm_medium=referral&utm_campaign=enterprise&utm_term=repo)


================================================
FILE: SECURITY.md
================================================
# Security Policy

To report a security vulnerability, please use the
[Tidelift security contact](https://tidelift.com/security).
Tidelift will coordinate the fix and disclosure.

Please do not report security vulnerabilities through public GitHub issues or pull requests.


================================================
FILE: docs/deprecated.md
================================================
# Deprecated

These features are deprecated, which means they may go away in a future major version of Commander.
They are currently still available for backwards compatibility, but should not be used in new code.

- [Deprecated](#deprecated)
    - [RegExp .option() parameter](#regexp-option-parameter)
    - [noHelp](#nohelp)
    - [Callback to .help() and .outputHelp()](#callback-to-help-and-outputhelp)
    - [.on('--help')](#on--help)
    - [.on('command:\*')](#oncommand)
    - [.command('\*')](#command)
    - [cmd.description(cmdDescription, argDescriptions)](#cmddescriptioncmddescription-argdescriptions)
    - [InvalidOptionArgumentError](#invalidoptionargumenterror)
    - [Import from `commander/esm.mjs`](#import-from-commanderesmmjs)
    - [cmd.\_args](#cmd_args)
    - [.addHelpCommand(string|boolean|undefined)](#addhelpcommandstringbooleanundefined)
  - [Removed](#removed)
    - [Short option flag longer than a single character](#short-option-flag-longer-than-a-single-character)
    - [Default import of global Command object](#default-import-of-global-command-object)

### RegExp .option() parameter

The `.option()` method allowed a RegExp as the third parameter to restrict what values were accepted.

```js
program.option('-c,--coffee <type>', 'coffee', /short-white|long-black/);
```

Removed from README in Commander v3. Deprecated from Commander v7.

The newer functionality is the Option `.choices()` method, or using a custom option processing function.

### noHelp

This was an option passed to `.command()` to hide the command from the built-in help:

```js
program.command('example', 'example command', { noHelp: true });
```

The option was renamed `hidden` in Commander v5.1. Deprecated from Commander v7.

### Callback to .help() and .outputHelp()

These routines allowed a callback parameter to process the built-in help before display.

```js
program.outputHelp((text) => {
  return colors.red(text);
});
```

The newer approach is to directly access the built-in help text using `.helpInformation()`.

```js
console.error(colors.red(program.helpInformation()));
```

Deprecated from Commander v7.

### .on('--help')

This was the way to add custom help after the built-in help. From Commander v3.0.0 this used the custom long help option flags, if changed.

```js
program.on('--help', function() {
  console.log('')
  console.log('Examples:');
  console.log('  $ custom-help --help');
  console.log('  $ custom-help -h');
});
```

The replacement is `.addHelpText()`:

```js
program.addHelpText('after', `
Examples:
  $ custom-help --help
  $ custom-help -h`
);
```

Deprecated from Commander v7.

### .on('command:*')

This was emitted when the command argument did not match a known subcommand (as part of the implementation of `.command('*')`).

One use was for adding an error for an unknown subcommand. An error is now the default built-in behaviour.

A second related use was for making a suggestion for an unknown subcommand. The replacement built-in support is `.showSuggestionAfterError()`,
or for custom behaviour catch the `commander.unknownCommand` error.

Deprecated from Commander v8.3.

### .command('*')

This was used to add a default command to the program.

```js
program
  .command('*')
  .action(() => console.log('List files by default...'));
```

You may now pass a configuration option of `isDefault: true` when adding a command, whether using a subcommand with an action handler or a stand-alone executable subcommand.

```js
program
  .command('list', { isDefault: true })
  .action(() => console.log('List files by default...'));
```

Removed from README in Commander v5. Deprecated from Commander v8.3.

### cmd.description(cmdDescription, argDescriptions)

This was used to add command argument descriptions for the help.

```js
program
  .command('price <book>')
  .description('show price of book', {
    book: 'ISBN number for book'
  });
```

The new approach is to use the `.argument()` method.

```js
program
  .command('price')
  .description('show price of book')
  .argument('<book>', 'ISBN number for book');
```

Deprecated from Commander v8.

### InvalidOptionArgumentError

This was used for throwing an error from custom option processing, for a nice error message.

```js
function myParseInt(value, dummyPrevious) {
  // parseInt takes a string and a radix
  const parsedValue = parseInt(value, 10);
  if (isNaN(parsedValue)) {
    throw new commander.InvalidOptionArgumentError('Not a number.');
  }
  return parsedValue;
}
```

The replacement is `InvalidArgumentError` since can be used now for custom command-argument processing too.

```js
function myParseInt(value, dummyPrevious) {
  // parseInt takes a string and a radix
  const parsedValue = parseInt(value, 10);
  if (isNaN(parsedValue)) {
    throw new commander.InvalidArgumentError('Not a number.');
  }
  return parsedValue;
}
```

Deprecated from Commander v8.

### Import from `commander/esm.mjs`

The first support for named imports required an explicit entry file.

```js
import { Command } from 'commander/esm.mjs';
```

This is no longer required, just import directly from the module.

```js
import { Command } from 'commander';
```

README updated in Commander v9. Deprecated from Commander v9.

### cmd._args

This was always private, but was previously the only way to access the command `Argument` array.

```js
const registeredArguments = program._args;
```

The registered command arguments are now accessible via `.registeredArguments`.

```js
const registeredArguments = program.registeredArguments;
```

Deprecated from Commander v11.

### .addHelpCommand(string|boolean|undefined)

This was originally used with a variety of parameters, but not by passing a Command object despite the "add" name.

```js
program.addHelpCommand('assist  [command]');
program.addHelpCommand('assist', 'show assistance');
program.addHelpCommand(false);

```

In new code you configure the help command with `.helpCommand()`. Or use `.addHelpCommand()` which now takes a Command object, like `.addCommand()`.

```js
program.helpCommand('assist [command]');
program.helpCommand('assist', 'show assistance');
program.helpCommand(false);

program.addHelpCommand(new Command('assist').argument('[command]').description('show assistance'));
```

- Removed from README in Commander v12.
- Deprecated from Commander v12.

## Removed

### Short option flag longer than a single character

Short option flags like `-ws` were never supported, but the old README did not make this clear. The README now states that short options are a single character.

- README updated in Commander v3.
- Deprecated from Commander v9.
- Throws an exception in Commander v13. Deprecated and gone!
- Replacement added in Commander v13.1 with support for dual long options, like `--ws, --workspace`.

### Default import of global Command object

The default import was a global Command object.

```js
const program = require('commander');
```

The global Command object is exported as `program` from Commander v5, or import the Command object.

```js
const { program } = require('commander');
// or
const { Command } = require('commander');
const program = new Command()
```

- Removed from README in Commander v5.
- Deprecated from Commander v7.
- Removed from TypeScript declarations in Commander v8.
- Removed from CommonJS in Commander v12. Deprecated and gone!


================================================
FILE: docs/help-in-depth.md
================================================
# Help in Depth

The built-in help is formatted using the Help class.
You can configure the Help behaviour by modifying data properties and methods using `.configureHelp()`, or by subclassing using `.createHelp()` if you prefer.

Example file: [configure-help.js](../examples/configure-help.js)

```js
program.configureHelp({
  sortSubcommands: true,
  subcommandTerm: (cmd) => cmd.name() // Just show the name, instead of short usage.
});
```

- [Help in Depth](#help-in-depth)
  - [Data Properties](#data-properties)
  - [Stringify and Style](#stringify-and-style)
  - [Layout](#layout)

## Data Properties

The data properties are:

- `helpWidth`: specify the wrap width, useful for unit tests
- `minWidthToWrap`: specify required width to allow wrapping (default 40)
- `showGlobalOptions`: show a section with the global options from the parent command(s)
- `sortSubcommands`: sort the subcommands alphabetically
- `sortOptions`: sort the options alphabetically

Example files:
- [configure-help.js](../examples/configure-help.js)
- [global-options-nested.js](../examples/global-options-nested.js)

## Stringify and Style

The `Help` object has narrowly focused methods to allow customising the displayed help.

The stringify routines take an object (`Command` or `Option` or `Argument`) and produce a string. For example you could change the way subcommands are listed:

```js
program.configureHelp({
  subcommandTerm: (cmd) => cmd.name() // just show the name instead of usage
});
```

The style routines take just a string. For example to make the titles bold:

```js
import { styleText } from 'node:util';
program.configureHelp({
   styleTitle: (str) => styleText('bold', str)
});
```

There is built-in support for detecting whether the output has colors, and respecting environment variables for `NO_COLOR`, `FORCE_COLOR`, and `CLIFORCE_COLOR`. The style routines always get called and color is stripped afterwards if needed using `Command.configureOutput().stripColor()`.

This annotated help output shows where the stringify and style routines are used. The first output is for a program with subcommands, and the second output is for a subcommand with arguments. 


```text
Usage: color-help [options] [command]
<-1--> <-------------2-------------->
       <---a----> <---b---> <---c--->

program description
<--------3-------->

Options:
<--1--->
  -h, --help               display help for command
  <---4---->               <---------5------------>

Commands:
<---1--->
  print [options] <files>  print files
  <----------6---------->  <----7---->
  <-b-> <---c---> <--d-->
```

|  | stringify(object) | style(string) | default style |
| - | - | - | - |
| 1 | | styleTitle | |
| 2 | commandUsage | styleUsage | a, b, c, d |
| 3 | commandDescription | styleCommandDescription | styleDescriptionText |
| 4 | optionTerm | styleOptionTerm | styleOptionText |
| 5 | optionDescription | styleOptionDescription | styleDescriptionText |
| 6 | subcommandTerm | styleSubcommandTerm | b, c, d |
| 7 | subcommandDescription | styleSubcommandDescription |  styleDescriptionText|
| 8 | argumentTerm | styleArgumentTerm | styleArgumentText |
| 9 | argumentDescription | styleArgumentDescription | styleDescriptionText |
| a | | styleCommandText | |
| b | | styleOptionText | |
| c | | styleSubcommandText | |
| d | | styleArgumentText | |

```text
Usage: color-help print [options] <files...>
<-1--> <---------------2------------------->
       <---a----> <-c-> <---b---> <---d---->

Arguments:
<---1---->
  files  files to queue for printing
  <-8->  <------------9------------>
...
```

Color example files:

- [color-help.mjs](../examples/color-help.mjs)
- [color-help-replacement.mjs](../examples/color-help-replacement.mjs)

Stringify example files (`subcommandTerm`):

- [help-subcommands-usage.js](../examples/help-subcommands-usage.js)
- [configure-help.js](../examples/configure-help.js)

## Layout

Utility methods which control the layout include `padWidth`, `boxWrap`, and `formatItem`. These can be overridden to change the layout or replace with an alternative implementation.

Example files:

- `formatItem`: [help-centered.mjs](../examples/help-centered.mjs)
- `formatItem`: [man-style-help.mjs](../examples/man-style-help.mjs)
- `boxwrap`: [color-help-replacement.mjs](../examples/color-help-replacement.mjs)



================================================
FILE: docs/options-in-depth.md
================================================
<!-- omit from toc -->
# Options in Depth

The README covers declaring and using options, and mostly parsing will work the way you and your users expect. This page covers some special cases
and subtle issues in depth.

- [Options taking varying numbers of option-arguments](#options-taking-varying-numbers-of-option-arguments)
  - [Parsing ambiguity](#parsing-ambiguity)
    - [Alternative: Make `--` part of your syntax](#alternative-make----part-of-your-syntax)
    - [Alternative: Put options last](#alternative-put-options-last)
    - [Alternative: Use options instead of command-arguments](#alternative-use-options-instead-of-command-arguments)
- [Combining short options, and options taking arguments](#combining-short-options-and-options-taking-arguments)
  - [Combining short options as if boolean](#combining-short-options-as-if-boolean)

## Options taking varying numbers of option-arguments

Certain options take a varying number of arguments:

```js
program
   .option('-c, --compress [percentage]') // 0 or 1
   .option('--preprocess <file...>') // 1 or more
   .option('--test [name...]') // 0 or more
```

This section uses examples with options taking 0 or 1 arguments, but the discussions also apply to variadic options taking more arguments.

For information about terms used in this document see: [terminology](./terminology.md)

### Parsing ambiguity

There is a potential downside to be aware of. If a command has both
command-arguments and options with varying option-arguments, this introduces a parsing ambiguity which may affect the user of your program.
Commander looks for option-arguments first, but the user may
intend the argument following the option as a command or command-argument.

```js
program
  .name('cook')
  .argument('[technique]')
  .option('-i, --ingredient [ingredient]', 'add cheese or given ingredient')
  .action((technique, options) => {
    console.log(`technique: ${technique}`);
    const ingredient = (options.ingredient === true) ? 'cheese' : options.ingredient;
    console.log(`ingredient: ${ingredient}`);
  });

program.parse();
```

```sh
$ cook scrambled
technique: scrambled
ingredient: undefined

$ cook -i
technique: undefined
ingredient: cheese

$ cook -i egg
technique: undefined
ingredient: egg

$ cook -i scrambled  # oops
technique: undefined
ingredient: scrambled
```

The explicit way to resolve this is use `--` to indicate the end of the options and option-arguments:

```sh
$ node cook.js -i -- scrambled
technique: scrambled
ingredient: cheese
```

If you want to avoid your users needing to learn when to use `--`, there are a few approaches you could take.

#### Alternative: Make `--` part of your syntax

Rather than trying to teach your users what `--` does, you could just make it part of your syntax.

```js
program.usage('[options] -- [technique]');
```

```sh
$ cook --help
Usage: cook [options] -- [technique]

Options:
  -i, --ingredient [ingredient]  add cheese or given ingredient
  -h, --help                     display help for command

$ cook -- scrambled
technique: scrambled
ingredient: undefined

$ cook -i -- scrambled
technique: scrambled
ingredient: cheese
```

#### Alternative: Put options last

Commander follows the GNU convention for parsing and allows options before or after the command-arguments, or intermingled.
So by putting the options last, the command-arguments do not get confused with the option-arguments.

```js
program.usage('[technique] [options]');
```

```sh
$ cook --help
Usage: cook [technique] [options]

Options:
  -i, --ingredient [ingredient]  add cheese or given ingredient
  -h, --help                     display help for command

$ node cook.js scrambled -i
technique: scrambled
ingredient: cheese
```

#### Alternative: Use options instead of command-arguments

This is a bit more radical, but completely avoids the parsing ambiguity!

```js
program
  .name('cook')
  .option('-t, --technique <technique>', 'cooking technique')
  .option('-i, --ingredient [ingredient]', 'add cheese or given ingredient')
  .action((options) => {
    console.log(`technique: ${options.technique}`);
    const ingredient = (options.ingredient === true) ? 'cheese' : options.ingredient;
    console.log(`ingredient: ${ingredient}`);
  });
```

```sh
$ cook -i -t scrambled
technique: scrambled
ingredient: cheese
```

## Combining short options, and options taking arguments

Multiple boolean short options can be combined after a single `-`, like `ls -al`. You can also include just
a single short option which might take a value, as any following characters will
be taken as the value.

This means that by default you can not combine short options which may take an argument.

```js
program
  .name('collect')
  .option("-o, --other [count]", "other serving(s)")
  .option("-v, --vegan [count]", "vegan serving(s)")
  .option("-l, --halal [count]", "halal serving(s)");
program.parse(process.argv);

const opts = program.opts();
if (opts.other) console.log(`other servings: ${opts.other}`);
if (opts.vegan) console.log(`vegan servings: ${opts.vegan}`);
if (opts.halal) console.log(`halal servings: ${opts.halal}`);
```

```sh
$ collect -o 3
other servings: 3
$ collect -o3
other servings: 3
$ collect -l -v
vegan servings: true
halal servings: true
$ collect -lv  # oops
halal servings: v
```

If you wish to use options taking varying arguments as boolean options, you need to specify them separately.

```console
$ collect -a -v -l
any servings: true
vegan servings: true
halal servings: true
```

### Combining short options as if boolean

Before Commander v5, combining a short option and the value was not supported, and combined short flags were always expanded.
So `-avl` expanded to `-a -v -l`.

If you want backwards compatible behaviour, or prefer combining short options as booleans to combining short option and value,
you may change the behaviour.

To modify the parsing of options taking an optional value:

```js
.combineFlagAndOptionalValue(true)  // `-v45` is treated like `--vegan=45`, this is the default behaviour
.combineFlagAndOptionalValue(false) // `-vl` is treated like `-v -l`
```


================================================
FILE: docs/parsing-and-hooks.md
================================================
# Parsing life cycle and hooks

The processing starts with an array of args. Each command processes and removes the options it understands, and passes the remaining args to the next subcommand.
The final command calls the action handler.

Starting with top-level command (program):

- parse options: parse recognised options (for this command) and remove from args
- parse env: look for environment variables (for this command)
- process implied: set any implied option values (for this command)
- if the first arg is a subcommand
    - call `preSubcommand` hooks
    - pass remaining arguments to subcommand, and process same way

Once reach final (leaf) command:

- check for missing mandatory options
- check for conflicting options
- check for unknown options
- process remaining args as command-arguments
- call `preAction` hooks
- call action handler
- call `postAction` hooks


================================================
FILE: docs/release-policy.md
================================================
# Release Policy

We follow [Semantic Versioning](http://semver.org/spec/v2.0.0.html), and limit breaking changes to major versions.

There are major releases about every six months. We do a major release and bump the minimum required node version when LTS Node.js versions reach end-of-life.

The release notes for major versions highlight breaking changes, and include a section of migration tips for common changes required.
The [Changelog](../CHANGELOG.md) lists release notes for all versions.

The current release line gets all updates: features, bug fixes, and security updates. Older maintenance versions get just security updates for 12 months.

| Version | First Release | Release Note |  Status | End of Life |
| ------- | ------------- | - | ------- | ----------- |
| 14.x | 2025-05-18 | [14.0.0](https://github.com/tj/commander.js/releases/tag/v14.0.0) | current | - |
| 13.x | 2024-12-30 | [13.0.0](https://github.com/tj/commander.js/releases/tag/v13.0.0) | maintenance | 2026-05-18 |
| <13 | | | end of life | |


================================================
FILE: docs/terminology.md
================================================
# Terminology

The command line arguments are made up of options, option-arguments, commands, and command-arguments.

| Term | Explanation |
| --- | --- |
| option | an argument which is a `-` followed by a character, or `--` followed by a word (or hyphenated words), like `-s` or `--short` |
| option-argument| some options can take an argument |
| command | a program or command can have subcommands |
| command-argument | argument for the command (and not an option or option-argument) |

For example:

```sh
my-utility command -o --option option-argument command-argument-1 command-argument-2
```

In other references options are sometimes called flags, and command-arguments are sometimes called positional arguments or operands.


================================================
FILE: docs/zh-CN/不再推荐使用的功能.md
================================================
# 不再推荐使用的功能

本文中列出的功能不再推荐使用。它们在 Commander 未来的主要版本(major version)中可能被移除。为保证后向兼容,这些功能目前还可以使用,但它们不应被用在新代码中。

- [不再推荐使用的功能](#%E4%B8%8D%E5%86%8D%E6%8E%A8%E8%8D%90%E4%BD%BF%E7%94%A8%E7%9A%84%E5%8A%9F%E8%83%BD)
  - [.option() 方法的正则表达式参数](#option-%E6%96%B9%E6%B3%95%E7%9A%84%E6%AD%A3%E5%88%99%E8%A1%A8%E8%BE%BE%E5%BC%8F%E5%8F%82%E6%95%B0)
  - [noHelp](#nohelp)
  - [默认导入的全局 Command 对象](#%E9%BB%98%E8%AE%A4%E5%AF%BC%E5%85%A5%E7%9A%84%E5%85%A8%E5%B1%80-command-%E5%AF%B9%E8%B1%A1)
  - [.help() 与 .outputHelp() 的回调函数参数](#help-%E4%B8%8E-outputhelp-%E7%9A%84%E5%9B%9E%E8%B0%83%E5%87%BD%E6%95%B0%E5%8F%82%E6%95%B0)
  - [.on('--help')](#on--help)
  - [.on('command:*')](#oncommand)
  - [.command('*')](#command)
  - [cmd.description(cmdDescription, argDescriptions)](#cmddescriptioncmddescription-argdescriptions)
  - [InvalidOptionArgumentError](#invalidoptionargumenterror)
  - [短选项标志长于单个字符](#%E7%9F%AD%E9%80%89%E9%A1%B9%E6%A0%87%E5%BF%97%E9%95%BF%E4%BA%8E%E5%8D%95%E4%B8%AA%E5%AD%97%E7%AC%A6)


## .option() 方法的正则表达式参数

`.option()`方法可以接受一个正则表达式作为第三个参数,以规定可以接受的选项参数值。

```js
program.option('-c,--coffee <type>', 'coffee', /short-white|long-black/);
```

该功能从 Commander v3 的文档中被移除。自 Commander v7 起,该功能不再推荐使用。

新的写法是使用`Option`对象的`.choices()`方法,或者使用自定义选项处理函数。

## noHelp

此选项曾被用作传入`.command()`方法,以在内建的帮助信息中隐藏该命令:

```js
program.command('example', 'example command', { noHelp: true });
```

在 Commander v5.1 中,该选项被更名为`hidden`。自 Commander v7 起`noHelp`不再推荐使用。

## 默认导入的全局 Command 对象

Commander 的默认导入曾是一个全局的`Command`对象。

```js
const program = require('commander');
```

自 Commander v5 后,全局`Command`对象作为 `program`被导出。或者也可以导入`Command`对象。

```js
const { program } = require('commander');
// 或者
const { Command } = require('commander');
const program = new Command()
```

- 此功能在 Commander v5 的文档中被移除。
- 自 Commander v7 起不再推荐使用。
- 在 Commander v8 的 TypeScript 定义文件中被移除。

## .help() 与 .outputHelp() 的回调函数参数

这两个方法曾允许传入一个回调函数,以在展示前处理帮助信息。

```js
program.outputHelp((text) => {
  return colors.red(text);
});
```

新的写法是直接通过调用`.helpInformation()`来获取帮助文本。

```js
console.error(colors.red(program.helpInformation()));
```

自 Commander v7 起不再推荐使用。

## .on('--help')

此功能曾被用作在内建的帮助信息后输出自定义的帮助信息。自 Commander v3.0.0 起,如果有自定义的帮助选项,则此方法使用该自定义的帮助选项。

```js
program.on('--help', function() {
  console.log('')
  console.log('Examples:');
  console.log('  $ custom-help --help');
  console.log('  $ custom-help -h');
});
```

替代的方法是使用`.addHelpText()`:

```js
program.addHelpText('after', `
Examples:
  $ custom-help --help
  $ custom-help -h`
);
```

自 Commander v7 起不再推荐使用。

## .on('command:*')

当命令参数与已知子命令不匹配时发出此消息(作为 `.command('')` 实现的一部分)。

一种用途是为未知子命令添加错误。错误现在是默认的内置行为。

第二个相关用途是为未知子命令提出建议。替换内置支持是 `.showSuggestionAfterError()`,或者对于自定义行为捕获 `commander.unknownCommand` 错误。

自 Commander v8.3 起不再推荐使用。

## .command('*')

这用于向程序添加默认命令。

```js
program
  .command('*')
  .action(() => console.log('List files by default...'));
```

你现在可以在添加命令时传递 `isDefault: true` 的配置选项,无论是使用带有动作处理程序的子命令还是独立的可执行子命令。

```js
program
  .command('list', { isDefault: true })
  .action(() => console.log('List files by default...'));
```

从 Commander v5 的 README 中删除。自 Commander v8.3 起不再推荐使用。

## cmd.description(cmdDescription, argDescriptions)

此功能曾用来为命令参数添加描述信息。

```js
program
  .command('price <book>')
  .description('show price of book', {
    book: 'ISBN number for book'
  });
```

新的写法是使用`.argument()`方法。

```js
program
  .command('price')
  .description('show price of book')
  .argument('<book>', 'ISBN number for book');
```

自 Commander v8 起不再推荐使用。

## InvalidOptionArgumentError

此类曾被用来在自定义选项处理中抛出错误,以显示错误信息。

```js
function myParseInt(value, dummyPrevious) {
  // parseInt 参数为字符串和进制数
  const parsedValue = parseInt(value, 10);
  if (isNaN(parsedValue)) {
    throw new commander.InvalidOptionArgumentError('Not a number.');
  }
  return parsedValue;
}
```

替代的类是`InvalidArgumentError`,它也可用于自定义命令参数处理。

```js
function myParseInt(value, dummyPrevious) {
  // parseInt 参数为字符串和进制数
  const parsedValue = parseInt(value, 10);
  if (isNaN(parsedValue)) {
    throw new commander.InvalidArgumentError('Not a number.');
  }
  return parsedValue;
}
```

自 Commander v8 起不再推荐使用。

## 短选项标志长于单个字符

短选项从未支持像 `-ws` 的标识,但旧的 README 并没有明确说明这一点。README 现在声明短选项是单个字符。

README 在 Commander v3 更新。自 Commander v9 起不再推荐使用。


================================================
FILE: docs/zh-CN/可变参数的选项.md
================================================
# 可变参数的选项

README 文档介绍了选项的声明与使用。大多数情况下,选项的解析行为,与您和您程序用户的期望相符。本文将详述一些特殊用例和细节问题。

- [可变参数的选项](#%E5%8F%AF%E5%8F%98%E5%8F%82%E6%95%B0%E7%9A%84%E9%80%89%E9%A1%B9)
	- [解析中的歧义](#%E8%A7%A3%E6%9E%90%E4%B8%AD%E7%9A%84%E6%AD%A7%E4%B9%89)
		- [方案一:让`--`成为语法的一部分](#%E6%96%B9%E6%A1%88%E4%B8%80%EF%BC%9A%E8%AE%A9%60--%60%E6%88%90%E4%B8%BA%E8%AF%AD%E6%B3%95%E7%9A%84%E4%B8%80%E9%83%A8%E5%88%86)
		- [方案二:把选项放在最后](#%E6%96%B9%E6%A1%88%E4%BA%8C%EF%BC%9A%E6%8A%8A%E9%80%89%E9%A1%B9%E6%94%BE%E5%9C%A8%E6%9C%80%E5%90%8E)
		- [方案三:使用选项替代命令参数](#%E6%96%B9%E6%A1%88%E4%B8%89%EF%BC%9A%E4%BD%BF%E7%94%A8%E9%80%89%E9%A1%B9%E6%9B%BF%E4%BB%A3%E5%91%BD%E4%BB%A4%E5%8F%82%E6%95%B0)
	- [合并短选项,和带有参数的选项](#%E5%90%88%E5%B9%B6%E7%9F%AD%E9%80%89%E9%A1%B9%E5%92%8C%E5%B8%A6%E6%9C%89%E5%8F%82%E6%95%B0%E7%9A%84%E9%80%89%E9%A1%B9)
		- [将短选项视作 boolean 类型选项合并](#%E5%B0%86%E7%9F%AD%E9%80%89%E9%A1%B9%E8%A7%86%E4%BD%9C-boolean-%E7%B1%BB%E5%9E%8B%E9%80%89%E9%A1%B9%E5%90%88%E5%B9%B6)

有些选项可以接受可变数量的参数:

```js
program
   .option('-c, --compress [percentage]') // 0 或 1 个参数
   .option('--preprocess <file...>') // 至少 1 个参数
   .option('--test [name...]') // 0 或多个参数
```

本文中使用的示例代码接受 0 或 1 个参数。但相关的讨论对接受更多参数的选项同样适用。

关于本文档中使用的术语,参见[术语表](./%E6%9C%AF%E8%AF%AD%E8%A1%A8.md)。

## 解析中的歧义

解析选项时,有一些潜在的问题值得注意。当一个命令既有命令参数,又有选项的时候,在解析过程中有可能出现歧义。这可能会影响用户使用您的程序。
Commander 首先解析选项的参数,而用户有可能想将选项后面跟的参数作为命令,或是作为命令参数进行解析。

```js
program
  .name('cook')
  .argument('[technique]')
  .option('-i, --ingredient [ingredient]', 'add cheese or given ingredient')
  .action((technique, options) => {
    console.log(`technique: ${technique}`);
    const ingredient = (options.ingredient === true) ? 'cheese' : options.ingredient;
    console.log(`ingredient: ${ingredient}`);
  });

program.parse();
```

```sh
$ cook scrambled
technique: scrambled
ingredient: undefined

$ cook -i
technique: undefined
ingredient: cheese

$ cook -i egg
technique: undefined
ingredient: egg

$ cook -i scrambled  # oops
technique: undefined
ingredient: scrambled
```

可以通过使用`--`来表示选项和选项参数部分的结束,以此来显式地解决这一冲突:

```sh
$ node cook.js -i -- scrambled
technique: scrambled
ingredient: cheese
```

如果不希望强制用户掌握这种使用`--`的写法,您可以尝试以下几种方案。

### 方案一:让`--`成为语法的一部分

与其让用户理解`--`的用法,您也可以直接把它作为程序语法的一部分。

```js
program.usage('[options] -- [technique]');
```

```sh
$ cook --help
Usage: cook [options] -- [technique]

Options:
  -i, --ingredient [ingredient]  add cheese or given ingredient
  -h, --help                     display help for command

$ cook -- scrambled
technique: scrambled
ingredient: undefined

$ cook -i -- scrambled
technique: scrambled
ingredient: cheese
```

### 方案二:把选项放在最后

Commander 遵循 GNU 解析命令的惯例,允许选项出现在命令参数之前或者之后,也可以将选项和命令参数相互穿插。
因此,通过要求把选项放在最后,命令参数就不会和选项参数相混淆。

```js
program.usage('[technique] [options]');
```

```sh
$ cook --help
Usage: cook [technique] [options]

Options:
  -i, --ingredient [ingredient]  add cheese or given ingredient
  -h, --help                     display help for command

$ node cook.js scrambled -i
technique: scrambled
ingredient: cheese
```

### 方案三:使用选项替代命令参数

这个方案虽然有点激进,但是可以完美避免解析中的歧义。

```js
program
  .name('cook')
  .option('-t, --technique <technique>', 'cooking technique')
  .option('-i, --ingredient [ingredient]', 'add cheese or given ingredient')
  .action((options) => {
    console.log(`technique: ${options.technique}`);
    const ingredient = (options.ingredient === true) ? 'cheese' : options.ingredient;
    console.log(`ingredient: ${ingredient}`);
  });
```

```sh
$ cook -i -t scrambled
technique: scrambled
ingredient: cheese
```

## 合并短选项和带有参数的选项

多个 boolean 型的短选项可以合并起来写在同一个`-`号后面,比如`ls -al`。同时,你也可以在其中包括一个接受参数的短选项,此时,任何跟在其后的字符都将被视作这个选项的值。

这就是说,默认情况下并不可以把多个带参数的选项合并起来。

```js
program
  .name('collect')
  .option("-o, --other [count]", "other serving(s)")
  .option("-v, --vegan [count]", "vegan serving(s)")
  .option("-l, --halal [count]", "halal serving(s)");
program.parse(process.argv);

const opts = program.opts();
if (opts.other) console.log(`other servings: ${opts.other}`);
if (opts.vegan) console.log(`vegan servings: ${opts.vegan}`);
if (opts.halal) console.log(`halal servings: ${opts.halal}`);
```

```sh
$ collect -o 3
other servings: 3
$ collect -o3
other servings: 3
$ collect -l -v
vegan servings: true
halal servings: true
$ collect -lv  # oops
halal servings: v
```

如果需要使用多个既可用作 boolean,又可以接受参数的选项,只能把它们分别声明。

```
$ collect -a -v -l
any servings: true
vegan servings: true
halal servings: true
```

### 将短选项视作 boolean 类型选项合并

在 Commander v5 之前,并不支持合并短选项和值。合并的 boolean 类型选项会被展开。
因此,`-avl`将被展开为`-a -v -l`。

如果您需要后向兼容,或是倾向于在短选项合并的时候把它们视作 boolean 类型,可以改变此行为:

```js
.combineFlagAndOptionalValue(true)  // `-v45` 被视为 `--vegan=45`,这是默认的行为
.combineFlagAndOptionalValue(false) // `-vl` 被视为 `-v -l`
```


================================================
FILE: docs/zh-CN/术语表.md
================================================
# 术语表

命令行参数由选项(options)、选项参数(option-arguments)、命令(commands),以及命令参数(command-arguments)组成。

|术语|解释|
|---|---|
|选项(option)|`-`后跟单个字母,或`--`后跟单词(或以`-`连接的多个单词),例如`-s`及`--short`|
|选项参数(option-argument)|有的选项可以接受一个参数|
|命令(command)|一个程序或命令可以包含子命令|
|命令参数(command-argument)|传给命令的参数(不包含选项或选项参数)|

例如:

```sh
my-utility command -o --option option-argument command-argument-1 command-argument-2
```

在一些其他资料中,选项有时也称为标志(flags),而命令参数也被称为位置参数(positional arguments)或者操作数(operands)。


================================================
FILE: eslint.config.js
================================================
const globals = require('globals');
const esLintjs = require('@eslint/js');
const jest = require('eslint-plugin-jest');
const tseslint = require('typescript-eslint');
const prettier = require('eslint-config-prettier');

// Only run tseslint on the files that we have included for TypeScript.
const tsconfigTsFiles = ['**/*.{ts,mts}']; // match "include" in tsconfig.ts.json;
const tsconfigJsFiles = ['*.{js,mjs}', 'lib/**/*.{js,mjs}']; // match "include" in tsconfig.js.json

// Using tseslint.config adds some type safety and `extends` to simplify customising config array.
module.exports = tseslint.config(
  // Add recommended rules.
  esLintjs.configs.recommended,
  jest.configs['flat/recommended'],
  // tseslint with different setup for js/ts
  {
    files: tsconfigJsFiles,
    extends: [...tseslint.configs.recommended],
    languageOptions: {
      parserOptions: { project: './tsconfig.js.json' },
    },
    rules: {
      '@typescript-eslint/no-var-requires': 'off', // tseslint does not autodetect commonjs context
      '@typescript-eslint/no-require-imports': 'off', // tseslint does not autodetect commonjs context
    },
  },
  {
    files: tsconfigTsFiles,
    extends: [...tseslint.configs.recommended],
    languageOptions: {
      parserOptions: { project: './tsconfig.ts.json' },
    },
  },
  prettier, // Do Prettier last so it can override previous configs.

  // Customise rules.
  {
    files: ['**/*.{js,mjs,cjs}', '**/*.{ts,mts,cts}'],
    rules: {
      'no-else-return': ['error', { allowElseIf: false }],
    },
    languageOptions: {
      globals: {
        ...globals.node,
      },
    },
  },
  {
    files: ['**/*.test.{js,mjs,cjs}'],
    rules: {
      'no-unused-vars': 'off', // lots in tests, minimise churn for now
    },
  },
  {
    files: [...tsconfigTsFiles, ...tsconfigJsFiles],
    rules: {
      '@typescript-eslint/ban-ts-comment': [
        'error',
        {
          'ts-expect-error': 'allow-with-description',
          'ts-ignore': 'allow-with-description',
          'ts-nocheck': true,
          'ts-check': true,
        },
      ],
    },
  },
);


================================================
FILE: esm.mjs
================================================
import commander from './index.js';

// wrapper to provide named exports for ESM.
export const {
  program,
  createCommand,
  createArgument,
  createOption,
  CommanderError,
  InvalidArgumentError,
  InvalidOptionArgumentError, // deprecated old name
  Command,
  Argument,
  Option,
  Help,
} = commander;


================================================
FILE: examples/action-this.js
================================================
#!/usr/bin/env node

// This example is used as an example in the README for the action handler.

const { Command } = require('commander');
const program = new Command();

program
  .command('serve')
  .argument('<script>')
  .option('-p, --port <number>', 'port number', 80)
  .action(function () {
    console.error('Run script %s on port %s', this.args[0], this.opts().port);
  });

program.parse();

// Try the following:
//    node action-this.js serve --port 8080 index.js


================================================
FILE: examples/alias.js
================================================
#!/usr/bin/env node

// This example shows giving alternative names for a command.

const { Command } = require('commander');
const program = new Command();

program
  .command('exec')
  .argument('<script>')
  .alias('ex')
  .action((script) => {
    console.log(`execute: ${script}`);
  });

program
  .command('print')
  .argument('<file>')
  // Multiple aliases is unusual but supported! You can call alias multiple times,
  // and/or add multiple aliases at once. Only the first alias is displayed in the help.
  .alias('p')
  .alias('pr')
  .aliases(['display', 'show'])
  .action((file) => {
    console.log(`print: ${file}`);
  });

program.parse();

// Try the following:
//    node alias.js --help
//    node alias.js exec script
//    node alias.js ex script
//    node alias.js print file
//    node alias.js pr file
//    node alias.js show file


================================================
FILE: examples/argument.js
================================================
#!/usr/bin/env node

// This example shows specifying the command arguments using argument() function.

const { Command } = require('commander');
const program = new Command();

program
  .name('connect')
  .argument('<server>', 'connect to the specified server')
  .argument('[user]', 'user account for connection', 'guest')
  .description('Example program with argument descriptions')
  .action((server, user) => {
    console.log('server:', server);
    console.log('user:', user);
  });

program.parse();

// Try the following:
//    node argument.js --help
//    node argument.js main.remote.site
//    node argument.js main.remote.site admin


================================================
FILE: examples/arguments-custom-processing.js
================================================
#!/usr/bin/env node

// This is used as an example in the README for:
//    Custom argument processing
//    You may specify a function to do custom processing of argument values.

const commander = require('commander');
const program = new commander.Command();

function myParseInt(value) {
  // parseInt takes a string and a radix
  const parsedValue = parseInt(value, 10);
  if (isNaN(parsedValue)) {
    throw new commander.InvalidArgumentError('Not a number.');
  }
  return parsedValue;
}

// The previous value passed to the custom processing is used when processing variadic values.
function mySum(value, total) {
  return total + myParseInt(value);
}

program
  .command('add')
  .argument('<first>', 'integer argument', myParseInt)
  .argument('[second]', 'integer argument', myParseInt, 1000)
  .action((first, second) => {
    console.log(`${first} + ${second} = ${first + second}`);
  });

program
  .command('sum')
  .argument('<value...>', 'values to be summed', mySum, 0)
  .action((total) => {
    console.log(`sum is ${total}`);
  });

program.parse();

// Try the following:
//    node arguments-custom-processing add --help
//    node arguments-custom-processing add 2
//    node arguments-custom-processing add 12 56
//    node arguments-custom-processing sum 1 2 3
//    node arguments-custom-processing sum silly


================================================
FILE: examples/arguments-extra.js
================================================
#!/usr/bin/env node

// This is used as an example in the README for extra argument features.

const commander = require('commander');
const program = new commander.Command();

program
  .addArgument(
    new commander.Argument('<drink-size>', 'drink cup size').choices([
      'small',
      'medium',
      'large',
    ]),
  )
  .addArgument(
    new commander.Argument('[timeout]', 'timeout in seconds').default(
      60,
      'one minute',
    ),
  )
  .action((drinkSize, timeout) => {
    console.log(`Drink size: ${drinkSize}`);
    console.log(`Timeout (s): ${timeout}`);
  });

program.parse();

// Try the following:
//    node arguments-extra.js --help
//    node arguments-extra.js huge
//    node arguments-extra.js small
//    node arguments-extra.js medium 30


================================================
FILE: examples/color-help-replacement.mjs
================================================
import stripAnsi from 'strip-ansi';
import wrapAnsi from 'wrap-ansi';
import {
  default as chalkStdOut,
  chalkStderr as chalkStdErr,
  supportsColor as supportsColorStdout,
  supportsColorStderr,
} from 'chalk';
import { Command, Help } from 'commander';

// Replace default color and wrapping support with Chalk packages as an example of
// a deep replacement of layout and style support.

// This example requires chalk and wrap-ansi and strip-ansi, and won't run
// from a clone of Commander repo without installing them first.
//
// For example using npm:
//    npm install chalk wrap-ansi strip-ansi

class MyHelp extends Help {
  constructor() {
    super();
    this.chalk = chalkStdOut;
  }

  prepareContext(contextOptions) {
    super.prepareContext(contextOptions);
    if (contextOptions?.error) {
      this.chalk = chalkStdErr;
    }
  }

  displayWidth(str) {
    return stripAnsi(str).length; // use imported package
  }

  boxWrap(str, width) {
    return wrapAnsi(str, width, { hard: true }); // use imported package
  }

  styleTitle(str) {
    return this.chalk.bold(str);
  }
  styleCommandText(str) {
    return this.chalk.cyan(str);
  }
  styleCommandDescription(str) {
    return this.chalk.magenta(str);
  }
  styleDescriptionText(str) {
    return this.chalk.italic(str);
  }
  styleOptionText(str) {
    return this.chalk.green(str);
  }
  styleArgumentText(str) {
    return this.chalk.yellow(str);
  }
  styleSubcommandText(str) {
    return this.chalk.blue(str);
  }
}

class MyCommand extends Command {
  createCommand(name) {
    return new MyCommand(name);
  }
  createHelp() {
    return Object.assign(new MyHelp(), this.configureHelp());
  }
}

const program = new MyCommand();

// Override the color detection to use Chalk's detection.
// Chalk overrides color support based on the `FORCE_COLOR` environment variable,
// and looks for --color and --no-color command-line options.
// See https://github.com/chalk/chalk?tab=readme-ov-file#supportscolor
//
// In general we want stripColor() to be consistent with displayWidth().
program.configureOutput({
  getOutHasColors: () => supportsColorStdout,
  getErrHasColors: () => supportsColorStderr,
  stripColor: (str) => stripAnsi(str),
});

program.description('program description '.repeat(10));
program
  .option('-s', 'short description')
  .option('--long <number>', 'long description '.repeat(10))
  .option('--color', 'force color output') // implemented by chalk
  .option('--no-color', 'disable color output'); // implemented by chalk

program.addHelpText('after', (context) => {
  const chalk = context.error ? chalkStdErr : chalkStdOut;
  return chalk.italic('\nThis is additional help text.');
});

program.command('esses').description('sssss '.repeat(33));

program
  .command('print')
  .description('print files')
  .argument('<files...>', 'files to queue for printing')
  .option('--double-sided', 'print on both sides');

program.parse();

// Try the following (after installing the required packages):
//    node color-help-replacement.mjs --help
//    node color-help-replacement.mjs --no-color help
//    FORCE_COLOR=0 node color-help-replacement.mjs help
//    node color-help-replacement.mjs help print


================================================
FILE: examples/color-help.mjs
================================================
import { styleText } from 'node:util'; // from node v20.12.0
import { Command } from 'commander';

// Customise colours and styles for help output.

const program = new Command();

program.configureHelp({
  styleTitle: (str) => styleText('bold', str),
  styleCommandText: (str) => styleText('cyan', str),
  styleCommandDescription: (str) => styleText('magenta', str),
  styleDescriptionText: (str) => styleText('italic', str),
  styleOptionText: (str) => styleText('green', str),
  styleArgumentText: (str) => styleText('yellow', str),
  styleSubcommandText: (str) => styleText('blue', str),
});

program.description('program description '.repeat(10));
program
  .option('-s', 'short description')
  .option('--long <number>', 'long description '.repeat(10));

program.addHelpText(
  'after',
  styleText('italic', '\nThis is additional help text.'),
);

program.command('esses').description('sssss '.repeat(33));

program
  .command('print')
  .description('print files')
  .argument('<files...>', 'files to queue for printing')
  .option('--double-sided', 'print on both sides');

program.parse();

// Try the following:
//    node color-help.mjs --help
//    NO_COLOR=1 node color-help.mjs --help
//    node color-help.mjs help print


================================================
FILE: examples/configure-help.js
================================================
const commander = require('commander');
const program = new commander.Command();

// This example shows a simple use of configureHelp.
// This is used as an example in the README.
// Any method on the Help class can be overridden
// See: https://github.com/tj/commander.js/blob/master/lib/help.js

program.configureHelp({
  sortSubcommands: true,
  subcommandTerm: (cmd) => cmd.name(), // Just show the name, instead of short usage.
});

program.command(
  'zebra <herd-size>',
  'African equines with distinctive black-and-white striped coats',
);
program.command(
  'aardvark [colour]',
  'medium-sized, burrowing, nocturnal mammal',
);
program
  .command('beaver', 'large, semiaquatic rodent')
  .option('--pond')
  .option('--river');

program.parse();

// Try the following:
//    node configure-help.js --help


================================================
FILE: examples/configure-output.js
================================================
const commander = require('commander');
const program = new commander.Command();

function errorColor(str) {
  // Add ANSI escape codes to display text in red.
  return `\x1b[31m${str}\x1b[0m`;
}

program.configureOutput({
  // Visibly override write routines as example!
  writeOut: (str) => process.stdout.write(`[OUT] ${str}`),
  writeErr: (str) => process.stdout.write(`[ERR] ${str}`),
  // Output errors in red.
  outputError: (str, write) => write(errorColor(str)),
});

program.version('1.2.3').option('-c, --compress').command('sub-command');

program.parse();

// Try the following:
//    node configure-output.js --version
//    node configure-output.js --unknown
//    node configure-output.js --help
//    node configure-output.js


================================================
FILE: examples/custom-command-class.js
================================================
#!/usr/bin/env node
const commander = require('commander');

// Use a class override to customise the command and its subcommands.

class CommandWithTrace extends commander.Command {
  createCommand(name) {
    const cmd = new CommandWithTrace(name);
    // Add an option to subcommands created using `.command()`
    cmd.option('-t, --trace', 'display extra information when run command');
    return cmd;
  }
}

function inspectCommand(command) {
  // The option value is stored as property on command because we called .storeOptionsAsProperties()
  console.log(`Called '${command.name()}'`);
  console.log(`args: ${command.args}`);
  console.log('opts: %o', command.opts());
}

const program = new CommandWithTrace('program')
  .option('-v, ---verbose')
  .action((options, command) => {
    inspectCommand(command);
  });

program
  .command('serve [params...]')
  .option('-p, --port <number>', 'port number')
  .action((params, options, command) => {
    inspectCommand(command);
  });

program.command('build <target>').action((buildTarget, options, command) => {
  inspectCommand(command);
});

program.parse();

// Try the following:
//    node custom-command-class.js --help
//    node custom-command-class.js serve --help
//    node custom-command-class.js serve -t -p 80 a b c
//    node custom-command-class.js build --help
//    node custom-command-class.js build --trace foo


================================================
FILE: examples/custom-help
================================================
#!/usr/bin/env node

// This example shows a simple use of addHelpText.
// This is used as an example in the README.

const { Command } = require('commander');
const program = new Command();

program.option('-f, --foo', 'enable some foo');

program.addHelpText(
  'after',
  `

Example call:
  $ custom-help --help`,
);

program.parse(process.argv);

// Try the following:
//    node custom-help --help


================================================
FILE: examples/custom-help-description
================================================
#!/usr/bin/env node

// This example shows changing the flags and description for the help option.

const { Command } = require('commander');
const program = new Command();

program
  .helpOption('-c, --HELP', 'custom help message')
  .option('-s, --sessions', 'add session support')
  .option('-t, --template <engine>', 'specify template engine', 'jade');

program
  .command('child')
  .option('--gender', 'specific gender of child')
  .action((options) => {
    console.log('Childsubcommand...');
  });

program.parse(process.argv);

// Try the following:
//    node custom-help-description -c
//    node custom-help-description child --HELP


================================================
FILE: examples/custom-help-text.js
================================================
#!/usr/bin/env node

// This example shows using addHelpText.

const { Command } = require('commander');
const program = new Command();

program.name('awesome');

program
  .addHelpText('beforeAll', 'A W E S O M E\n')
  .addHelpText('afterAll', (context) => {
    if (context.error) {
      return '\nHelp being displayed for an error';
    }
    return '\nSee web site for further help';
  });

program
  .command('extra')
  .addHelpText('before', 'Note: the extra command does not do anything')
  .addHelpText(
    'after',
    `
Examples:
  awesome extra --help
  awesome help extra`,
  );

program.parse();

// Try the following:
//    node custom-help-text.js --help
//    node custom-help-text.js extra --help
//    node custom-help-text.js


================================================
FILE: examples/custom-version
================================================
#!/usr/bin/env node

// This example shows changing the flags and description for the version option.

const { Command } = require('commander');
const program = new Command();

program
  .version('0.0.1', '-v, --VERSION', 'new version message')
  .option('-s, --sessions', 'add session support')
  .option('-t, --template <engine>', 'specify template engine', 'jade');

program.parse(process.argv);

// Try the following:
//    node custom-version -v
//    node custom-version --VERSION


================================================
FILE: examples/defaultCommand.js
================================================
#!/usr/bin/env node

const commander = require('commander');
const program = new commander.Command();

// Example program using the command configuration option isDefault to specify the default command.

program
  .command('build')
  .description('build web site for deployment')
  .action(() => {
    console.log('build');
  });

program
  .command('deploy')
  .description('deploy web site to production')
  .action(() => {
    console.log('deploy');
  });

program
  .command('serve', { isDefault: true })
  .description('launch web server')
  .option('-p,--port <port_number>', 'web port')
  .action((options) => {
    console.log(`server on port ${options.port}`);
  });

program.parse(process.argv);

// Try the following:
//    node defaultCommand.js build
//    node defaultCommand.js serve -p 8080
//    node defaultCommand.js -p 443


================================================
FILE: examples/deploy
================================================
#!/usr/bin/env node

const { Command } = require('commander');
const program = new Command();

program
  .name('deploy')
  .version('0.0.1')
  .option('-c, --config <path>', 'set config path', './deploy.conf');

program
  .command('setup [env]')
  .description('run setup commands for all envs')
  .option('-s, --setup_mode <mode>', 'Which setup mode to use', 'normal')
  .action((env, options) => {
    env = env || 'all';
    console.log('read config from %s', program.opts().config);
    console.log('setup for %s env(s) with %s mode', env, options.setup_mode);
  });

program
  .command('exec <script>')
  .alias('ex')
  .description('execute the given remote cmd')
  .option('-e, --exec_mode <mode>', 'Which exec mode to use', 'fast')
  .action((script, options) => {
    console.log('read config from %s', program.opts().config);
    console.log(
      'exec "%s" using %s mode and config %s',
      script,
      options.exec_mode,
      program.opts().config,
    );
  })
  .addHelpText(
    'after',
    `
Examples:
  $ deploy exec sequential
  $ deploy exec async`,
  );

program.parse(process.argv);


================================================
FILE: examples/description
================================================
#!/usr/bin/env node

// This example shows adding a description which is displayed in the help.

const { Command } = require('commander');
const program = new Command();

program
  .version('0.0.1')
  .description('Application simple description')
  .option('-f, --foo', 'enable some foo')
  .option('-b, --bar', 'enable some bar')
  .option('-B, --baz', 'enable some baz');

program.parse(process.argv);

if (!program.args.length) program.help();

// Try the following on macOS or Linux:
//    ./description -h
//
// Try the following:
//    node description -h


================================================
FILE: examples/global-options-added.js
================================================
#!/usr/bin/env node

// This example shows a couple of ways to add a "global" option to all of the subcommands.
// The first approach is to use a subclass and add the option as the subcommand is created.
// The second approach is to loop over the subcommands after they have been created.
//
// The code in this example assumes there is just one level of subcommands.
//
// (A different pattern for a "global" option is to add it to the root command, rather
// than to the subcommand. See global-options-nested.js.)

const { Command } = require('commander');

// Common options can be added when subcommands are created by using a custom subclass.
// If the options are unsorted in the help, these will appear first.
class MyRootCommand extends Command {
  createCommand(name) {
    const cmd = new Command(name);
    cmd.option('-v, --verbose', 'use verbose logging');
    return cmd;
  }
}

const program = new MyRootCommand();

program
  .command('print')
  .option('--a4', 'Use A4 sized paper')
  .action((options) => {
    console.log('print options: %O', options);
  });

program
  .command('serve')
  .option('-p, --port <number>', 'port number for server')
  .action((options) => {
    console.log('serve options: %O', options);
  });

// Common options can be added manually after setting up program and subcommands.
// If the options are unsorted in the help, these will appear last.
program.commands.forEach((cmd) => {
  cmd.option('-d, --debug');
});

program.parse();

// Try the following:
//    node global-options-added.js --help
//    node global-options-added.js print --help
//    node global-options-added.js serve --help
//    node global-options-added.js serve --debug --verbose


================================================
FILE: examples/global-options-nested.js
================================================
#!/usr/bin/env node

// This example shows global options on the program which affect all the subcommands.
// See how to work with global options in the subcommand and display them in the help.
//
// (A different pattern for a "global" option is to add it to the subcommands, rather
// than to the program. See global-options-added.js.)

const { Command } = require('commander');
const program = new Command();

program.configureHelp({ showGlobalOptions: true }).option('-g, --global');

program
  .command('sub')
  .option('-l, --local')
  .action((options, cmd) => {
    console.log({
      opts: cmd.opts(),
      optsWithGlobals: cmd.optsWithGlobals(),
    });
  });

program.parse();

// Try the following:
//    node global-options-nested.js --global sub --local
//    node global-options-nested.js sub --help


================================================
FILE: examples/help-centered.mjs
================================================
import { Command, Help } from 'commander';

// Right-justify the terms in the help output.
// Setup a subclass so we can do simple tweak of formatItem.

class MyHelp extends Help {
  formatItem(term, termWidth, description, helper) {
    // Pre-pad the term at start instead of end.
    const paddedTerm = term.padStart(
      termWidth + term.length - helper.displayWidth(term),
    );

    return super.formatItem(paddedTerm, termWidth, description, helper);
  }
}

class MyCommand extends Command {
  createCommand(name) {
    return new MyCommand(name);
  }
  createHelp() {
    return Object.assign(new MyHelp(), this.configureHelp());
  }
}

const program = new MyCommand();

program.configureHelp({ MyCommand });

program
  .option('-s', 'short flag')
  .option('-f, --flag', 'short and long flag')
  .option('--long <number>', 'long flag');

program.command('compile').alias('c').description('compile something');

program.command('run', 'run something').command('print', 'print something');

program.parse();

// Try the following:
//    node help-centered.mjs --help


================================================
FILE: examples/help-groups.js
================================================
const { Command, Option } = require('commander');

// Show the two approaches for adding help groups, and how to customise the built-in help and version.

const program = new Command();
const devOptionsHeading = 'Development Options:';
const managementCommandsHeading = 'Management Commands:';

// The high-level approach is use .optionsGroup() and .commandsGroup() before adding the options/commands.
const docker1 = program
  .command('docker1')
  .description('help groups created using .optionsGroup() and .commandsGroup()')
  .addOption(new Option('-h, --hostname <name>', 'container host name'))
  .addOption(new Option('-p, --port <number>', 'container port number'))
  .optionsGroup(devOptionsHeading)
  .option('-d, --debug', 'add extra trace information')
  .option('-w, --watch', 'run and relaunch service on file changes');

docker1
  .command('run')
  .description('create and run a new container from an image');
docker1.command('exec').description('execute a command in a running container');

docker1.commandsGroup(managementCommandsHeading);
docker1.command('images').description('manage images');
docker1.command('volumes').description('manage volumes');

// The low-level approach is using .helpGroup() on the Option or Command.
const docker2 = program
  .command('docker2')
  .description('help groups created using .helpGroup()')
  .addOption(new Option('-h, --hostname <name>', 'container host name'))
  .addOption(new Option('-p, --port <number>', 'container port number'))
  .addOption(
    new Option('-d, --debug', 'ad
Download .txt
gitextract_758xjbrb/

├── .editorconfig
├── .gitattributes
├── .github/
│   ├── FUNDING.yml
│   ├── PULL_REQUEST_TEMPLATE.md
│   ├── dependabot.yml
│   └── workflows/
│       ├── codeql-analysis.yml
│       └── tests.yml
├── .gitignore
├── .prettierignore
├── .prettierrc.js
├── CHANGELOG.md
├── CONTRIBUTING.md
├── LICENSE
├── Readme.md
├── Readme_zh-CN.md
├── SECURITY.md
├── docs/
│   ├── deprecated.md
│   ├── help-in-depth.md
│   ├── options-in-depth.md
│   ├── parsing-and-hooks.md
│   ├── release-policy.md
│   ├── terminology.md
│   └── zh-CN/
│       ├── 不再推荐使用的功能.md
│       ├── 可变参数的选项.md
│       └── 术语表.md
├── eslint.config.js
├── esm.mjs
├── examples/
│   ├── action-this.js
│   ├── alias.js
│   ├── argument.js
│   ├── arguments-custom-processing.js
│   ├── arguments-extra.js
│   ├── color-help-replacement.mjs
│   ├── color-help.mjs
│   ├── configure-help.js
│   ├── configure-output.js
│   ├── custom-command-class.js
│   ├── custom-help
│   ├── custom-help-description
│   ├── custom-help-text.js
│   ├── custom-version
│   ├── defaultCommand.js
│   ├── deploy
│   ├── description
│   ├── global-options-added.js
│   ├── global-options-nested.js
│   ├── help-centered.mjs
│   ├── help-groups.js
│   ├── help-subcommands-usage.js
│   ├── hook.js
│   ├── man-style-help.mjs
│   ├── nestedCommands.js
│   ├── options-boolean-or-value.js
│   ├── options-common.js
│   ├── options-conflicts.js
│   ├── options-custom-processing.js
│   ├── options-defaults.js
│   ├── options-env.js
│   ├── options-extra.js
│   ├── options-implies.js
│   ├── options-negatable.js
│   ├── options-required.js
│   ├── options-variadic.js
│   ├── pass-through-options.js
│   ├── pizza
│   ├── pm
│   ├── pm-install
│   ├── pm-list.js
│   ├── positional-options.js
│   ├── split.js
│   ├── string-util.js
│   └── thank.js
├── index.js
├── jest.config.js
├── lib/
│   ├── argument.js
│   ├── command.js
│   ├── error.js
│   ├── help.js
│   ├── option.js
│   └── suggestSimilar.js
├── package-support.json
├── package.json
├── tests/
│   ├── args.literal.test.js
│   ├── args.variadic.test.js
│   ├── argument.chain.test.js
│   ├── argument.choices.test.js
│   ├── argument.custom-processing.test.js
│   ├── argument.required.test.js
│   ├── argument.variadic.test.js
│   ├── command.action.test.js
│   ├── command.addCommand.test.js
│   ├── command.addHelpOption.test.js
│   ├── command.addHelpText.test.js
│   ├── command.alias.test.js
│   ├── command.allowExcessArguments.test.js
│   ├── command.allowUnknownOption.test.js
│   ├── command.argumentVariations.test.js
│   ├── command.asterisk.test.js
│   ├── command.chain.test.js
│   ├── command.commandHelp.test.js
│   ├── command.configureHelp.test.js
│   ├── command.configureOutput.test.js
│   ├── command.copySettings.test.js
│   ├── command.createArgument.test.js
│   ├── command.createHelp.test.js
│   ├── command.createOption.test.js
│   ├── command.default.test.js
│   ├── command.description.test.js
│   ├── command.error.test.js
│   ├── command.executableSubcommand.inspect.test.js
│   ├── command.executableSubcommand.lookup.test.js
│   ├── command.executableSubcommand.mock.test.js
│   ├── command.executableSubcommand.search.test.js
│   ├── command.executableSubcommand.signals.test.js
│   ├── command.executableSubcommand.test.js
│   ├── command.exitOverride.test.js
│   ├── command.help.test.js
│   ├── command.helpCommand.test.js
│   ├── command.helpOption.test.js
│   ├── command.hook.test.js
│   ├── command.name.test.js
│   ├── command.nested.test.js
│   ├── command.onCommand.test.js
│   ├── command.option-misuse.test.js
│   ├── command.parse.test.js
│   ├── command.parseOptions.test.js
│   ├── command.positionalOptions.test.js
│   ├── command.registerClash.test.js
│   ├── command.showHelpAfterError.test.js
│   ├── command.showSuggestionAfterError.test.js
│   ├── command.summary.test.js
│   ├── command.unknownCommand.test.js
│   ├── command.unknownOption.test.js
│   ├── command.usage.test.js
│   ├── commander.configureCommand.test.js
│   ├── createCommand.test.js
│   ├── deprecated.test.js
│   ├── esm-imports-test.mjs
│   ├── fixtures/
│   │   ├── inspect-sub.js
│   │   ├── inspect.js
│   │   ├── pm
│   │   ├── pm-cache-clear.js
│   │   ├── pm-cache-validate.js
│   │   ├── pm-cache.js
│   │   ├── pm-default
│   │   ├── pm-echo.js
│   │   ├── pm-fail.js
│   │   ├── pm-install
│   │   ├── pm-listen
│   │   ├── pm-publish.js
│   │   ├── pm-search
│   │   ├── pm-silent
│   │   ├── pm-terminate.js
│   │   └── pmlink-install
│   ├── fixtures-extensions/
│   │   ├── pm-try-cjs.cjs
│   │   ├── pm-try-mjs.mjs
│   │   ├── pm-try-ts.ts
│   │   └── pm.js
│   ├── help.argumentDescription.test.js
│   ├── help.boxWrap.test.js
│   ├── help.commandTerm.test.js
│   ├── help.commandUsage.test.js
│   ├── help.longestArgumentTermLength.test.js
│   ├── help.longestCommandTermLength.test.js
│   ├── help.longestOptionTermLength.test.js
│   ├── help.minWidthToWrap.test.js
│   ├── help.optionDescription.test.js
│   ├── help.optionTerm.test.js
│   ├── help.padWidth.test.js
│   ├── help.preformatted.test.js
│   ├── help.showGlobalOptions.test.js
│   ├── help.sortCommands.test.js
│   ├── help.sortOptions.test.js
│   ├── help.stripAnsi.test.js
│   ├── help.style.test.js
│   ├── help.subcommandDescription.test.js
│   ├── help.suggestion.test.js
│   ├── help.visibleArguments.test.js
│   ├── help.visibleCommands.test.js
│   ├── help.visibleGlobalOptions.test.js
│   ├── help.visibleOptions.test.js
│   ├── helpGroup.test.js
│   ├── incrementNodeInspectorPort.test.js
│   ├── negatives.test.js
│   ├── option.bad-flags.test.js
│   ├── option.chain.test.js
│   ├── options.bool.combo.test.js
│   ├── options.bool.small.combined.test.js
│   ├── options.bool.test.js
│   ├── options.camelcase.test.js
│   ├── options.choices.test.js
│   ├── options.conflicts.test.js
│   ├── options.custom-processing.test.js
│   ├── options.default.test.js
│   ├── options.dual-options.test.js
│   ├── options.env.test.js
│   ├── options.flags.test.js
│   ├── options.getset.test.js
│   ├── options.implies.test.js
│   ├── options.mandatory.test.js
│   ├── options.optional.test.js
│   ├── options.opts.test.js
│   ├── options.optsWithGlobals.test.js
│   ├── options.preset.test.js
│   ├── options.registerClash.test.js
│   ├── options.required.test.js
│   ├── options.twice.test.js
│   ├── options.values.test.js
│   ├── options.variadic.test.js
│   ├── options.version.test.js
│   ├── program.test.js
│   ├── ts-imports.test.ts
│   └── useColor.test.js
├── tsconfig.js.json
├── tsconfig.json
├── tsconfig.ts.json
└── typings/
    ├── esm.d.mts
    ├── index.d.ts
    └── index.test-d.ts
Download .txt
SYMBOL INDEX (317 symbols across 45 files)

FILE: examples/arguments-custom-processing.js
  function myParseInt (line 10) | function myParseInt(value) {
  function mySum (line 20) | function mySum(value, total) {

FILE: examples/color-help-replacement.mjs
  class MyHelp (line 20) | class MyHelp extends Help {
    method constructor (line 21) | constructor() {
    method prepareContext (line 26) | prepareContext(contextOptions) {
    method displayWidth (line 33) | displayWidth(str) {
    method boxWrap (line 37) | boxWrap(str, width) {
    method styleTitle (line 41) | styleTitle(str) {
    method styleCommandText (line 44) | styleCommandText(str) {
    method styleCommandDescription (line 47) | styleCommandDescription(str) {
    method styleDescriptionText (line 50) | styleDescriptionText(str) {
    method styleOptionText (line 53) | styleOptionText(str) {
    method styleArgumentText (line 56) | styleArgumentText(str) {
    method styleSubcommandText (line 59) | styleSubcommandText(str) {
  class MyCommand (line 64) | class MyCommand extends Command {
    method createCommand (line 65) | createCommand(name) {
    method createHelp (line 68) | createHelp() {

FILE: examples/configure-output.js
  function errorColor (line 4) | function errorColor(str) {

FILE: examples/custom-command-class.js
  class CommandWithTrace (line 6) | class CommandWithTrace extends commander.Command {
    method createCommand (line 7) | createCommand(name) {
  function inspectCommand (line 15) | function inspectCommand(command) {

FILE: examples/global-options-added.js
  class MyRootCommand (line 16) | class MyRootCommand extends Command {
    method createCommand (line 17) | createCommand(name) {

FILE: examples/help-centered.mjs
  class MyHelp (line 6) | class MyHelp extends Help {
    method formatItem (line 7) | formatItem(term, termWidth, description, helper) {
  class MyCommand (line 17) | class MyCommand extends Command {
    method createCommand (line 18) | createCommand(name) {
    method createHelp (line 21) | createHelp() {

FILE: examples/man-style-help.mjs
  function formatItem (line 5) | function formatItem(term, termWidth, description, helper) {

FILE: examples/nestedCommands.js
  function makeHeatCommand (line 21) | function makeHeatCommand() {

FILE: examples/options-custom-processing.js
  function myParseInt (line 10) | function myParseInt(value) {
  function increaseVerbosity (line 19) | function increaseVerbosity(dummyValue, previous) {
  function collect (line 23) | function collect(value, previous) {
  function commaSeparatedList (line 27) | function commaSeparatedList(value) {

FILE: lib/argument.js
  class Argument (line 3) | class Argument {
    method constructor (line 13) | constructor(name, description) {
    method name (line 48) | name() {
    method _collectValue (line 56) | _collectValue(value, previous) {
    method default (line 73) | default(value, description) {
    method argParser (line 86) | argParser(fn) {
    method choices (line 98) | choices(values) {
    method argRequired (line 119) | argRequired() {
    method argOptional (line 129) | argOptional() {
  function humanReadableArgName (line 143) | function humanReadableArgName(arg) {

FILE: lib/command.js
  class Command (line 13) | class Command extends EventEmitter {
    method constructor (line 20) | constructor(name) {
    method copyInheritedSettings (line 99) | copyInheritedSettings(sourceCommand) {
    method _getCommandAndAncestors (line 121) | _getCommandAndAncestors() {
    method command (line 155) | command(nameAndArgs, actionOptsOrExecDesc, execOpts) {
    method createCommand (line 192) | createCommand(name) {
    method createHelp (line 203) | createHelp() {
    method configureHelp (line 215) | configureHelp(configuration) {
    method configureOutput (line 245) | configureOutput(configuration) {
    method showHelpAfterError (line 261) | showHelpAfterError(displayHelp = true) {
    method showSuggestionAfterError (line 273) | showSuggestionAfterError(displaySuggestion = true) {
    method addCommand (line 288) | addCommand(cmd, opts) {
    method createArgument (line 316) | createArgument(name, description) {
    method argument (line 336) | argument(name, description, parseArg, defaultValue) {
    method arguments (line 359) | arguments(names) {
    method addArgument (line 375) | addArgument(argument) {
    method helpCommand (line 409) | helpCommand(enableOrNameAndArgs, description) {
    method addHelpCommand (line 443) | addHelpCommand(helpCommand, deprecatedDescription) {
    method _getHelpCommand (line 463) | _getHelpCommand() {
    method hook (line 487) | hook(event, listener) {
    method exitOverride (line 508) | exitOverride(fn) {
    method _exit (line 533) | _exit(exitCode, code, message) {
    method action (line 556) | action(fn) {
    method createOption (line 585) | createOption(flags, description) {
    method _callParseArg (line 599) | _callParseArg(target, value, previous, invalidArgumentMessage) {
    method _registerOption (line 619) | _registerOption(option) {
    method _registerCommand (line 644) | _registerCommand(command) {
    method addOption (line 670) | addOption(option) {
    method _optionEx (line 741) | _optionEx(config, flags, description, fn, defaultValue) {
    method option (line 788) | option(flags, description, parseArg, defaultValue) {
    method requiredOption (line 805) | requiredOption(flags, description, parseArg, defaultValue) {
    method combineFlagAndOptionalValue (line 826) | combineFlagAndOptionalValue(combine = true) {
    method allowUnknownOption (line 837) | allowUnknownOption(allowUnknown = true) {
    method allowExcessArguments (line 848) | allowExcessArguments(allowExcess = true) {
    method enablePositionalOptions (line 861) | enablePositionalOptions(positional = true) {
    method passThroughOptions (line 875) | passThroughOptions(passThrough = true) {
    method _checkForBrokenPassThrough (line 885) | _checkForBrokenPassThrough() {
    method storeOptionsAsProperties (line 905) | storeOptionsAsProperties(storeAsProperties = true) {
    method getOptionValue (line 925) | getOptionValue(key) {
    method setOptionValue (line 940) | setOptionValue(key, value) {
    method setOptionValueWithSource (line 953) | setOptionValueWithSource(key, value, source) {
    method getOptionValueSource (line 971) | getOptionValueSource(key) {
    method getOptionValueSourceWithGlobals (line 983) | getOptionValueSourceWithGlobals(key) {
    method _prepareUserArgs (line 1001) | _prepareUserArgs(argv, parseOptions) {
    method parse (line 1090) | parse(argv, parseOptions) {
    method parseAsync (line 1119) | async parseAsync(argv, parseOptions) {
    method _prepareForParse (line 1127) | _prepareForParse() {
    method saveStateBeforeParse (line 1141) | saveStateBeforeParse() {
    method restoreStateBeforeParse (line 1158) | restoreStateBeforeParse() {
    method _checkForMissingExecutable (line 1183) | _checkForMissingExecutable(executableFile, executableDir, subcommandNa...
    method _executeSubCommand (line 1202) | _executeSubCommand(subcommand, args) {
    method _dispatchSubcommand (line 1352) | _dispatchSubcommand(commandName, operands, unknown) {
    method _dispatchHelpCommand (line 1380) | _dispatchHelpCommand(subcommandName) {
    method _checkNumberOfArguments (line 1403) | _checkNumberOfArguments() {
    method _processArguments (line 1428) | _processArguments() {
    method _chainOrCall (line 1481) | _chainOrCall(promise, fn) {
    method _chainOrCallHooks (line 1499) | _chainOrCallHooks(promise, event) {
    method _chainOrCallSubCommandHook (line 1531) | _chainOrCallSubCommandHook(promise, subCommand, event) {
    method _parseCommand (line 1550) | _parseCommand(operands, unknown) {
    method _findCommand (line 1649) | _findCommand(name) {
    method _findOption (line 1664) | _findOption(arg) {
    method _checkForMissingMandatoryOptions (line 1675) | _checkForMissingMandatoryOptions() {
    method _checkForConflictingLocalOptions (line 1694) | _checkForConflictingLocalOptions() {
    method _checkForConflictingOptions (line 1723) | _checkForConflictingOptions() {
    method parseOptions (line 1748) | parseOptions(args) {
    method opts (line 1902) | opts() {
    method optsWithGlobals (line 1924) | optsWithGlobals() {
    method error (line 1940) | error(message, errorOptions) {
    method _parseOptionsEnv (line 1966) | _parseOptionsEnv() {
    method _parseOptionsImplied (line 1996) | _parseOptionsImplied() {
    method missingArgument (line 2034) | missingArgument(name) {
    method optionMissingArgument (line 2046) | optionMissingArgument(option) {
    method missingMandatoryOptionValue (line 2058) | missingMandatoryOptionValue(option) {
    method _conflictingOption (line 2070) | _conflictingOption(option, conflictingOption) {
    method unknownOption (line 2114) | unknownOption(flag) {
    method _excessArguments (line 2146) | _excessArguments(receivedArgs) {
    method unknownCommand (line 2162) | unknownCommand() {
    method version (line 2195) | version(str, flags, description) {
    method description (line 2218) | description(str, argsDescription) {
    method summary (line 2234) | summary(str) {
    method alias (line 2249) | alias(alias) {
    method aliases (line 2289) | aliases(aliases) {
    method usage (line 2304) | usage(str) {
    method name (line 2331) | name(str) {
    method helpGroup (line 2344) | helpGroup(heading) {
    method commandsGroup (line 2363) | commandsGroup(heading) {
    method optionsGroup (line 2382) | optionsGroup(heading) {
    method _initOptionGroup (line 2392) | _initOptionGroup(option) {
    method _initCommandGroup (line 2401) | _initCommandGroup(cmd) {
    method nameFromFilename (line 2419) | nameFromFilename(filename) {
    method executableDir (line 2437) | executableDir(path) {
    method helpInformation (line 2450) | helpInformation(contextOptions) {
    method _getOutputContext (line 2475) | _getOutputContext(contextOptions) {
    method outputHelp (line 2505) | outputHelp(contextOptions) {
    method helpOption (line 2559) | helpOption(flags, description) {
    method _getHelpOption (line 2592) | _getHelpOption() {
    method addHelpOption (line 2607) | addHelpOption(option) {
    method help (line 2621) | help(contextOptions) {
    method addHelpText (line 2656) | addHelpText(position, text) {
    method _outputHelpIfRequested (line 2686) | _outputHelpIfRequested(args) {
  function incrementNodeInspectorPort (line 2705) | function incrementNodeInspectorPort(args) {
  function useColor (line 2752) | function useColor() {

FILE: lib/error.js
  class CommanderError (line 4) | class CommanderError extends Error {
    method constructor (line 11) | constructor(exitCode, code, message) {
  class InvalidArgumentError (line 25) | class InvalidArgumentError extends CommanderError {
    method constructor (line 30) | constructor(message) {

FILE: lib/help.js
  class Help (line 12) | class Help {
    method constructor (line 13) | constructor() {
    method prepareContext (line 29) | prepareContext(contextOptions) {
    method visibleCommands (line 40) | visibleCommands(cmd) {
    method compareOptions (line 62) | compareOptions(a, b) {
    method visibleOptions (line 79) | visibleOptions(cmd) {
    method visibleGlobalOptions (line 112) | visibleGlobalOptions(cmd) {
    method visibleArguments (line 139) | visibleArguments(cmd) {
    method subcommandTerm (line 162) | subcommandTerm(cmd) {
    method optionTerm (line 182) | optionTerm(option) {
    method argumentTerm (line 193) | argumentTerm(argument) {
    method longestSubcommandTermLength (line 205) | longestSubcommandTermLength(cmd, helper) {
    method longestOptionTermLength (line 224) | longestOptionTermLength(cmd, helper) {
    method longestGlobalOptionTermLength (line 241) | longestGlobalOptionTermLength(cmd, helper) {
    method longestArgumentTermLength (line 258) | longestArgumentTermLength(cmd, helper) {
    method commandUsage (line 276) | commandUsage(cmd) {
    method commandDescription (line 300) | commandDescription(cmd) {
    method subcommandDescription (line 313) | subcommandDescription(cmd) {
    method optionDescription (line 325) | optionDescription(option) {
    method argumentDescription (line 372) | argumentDescription(argument) {
    method formatItemList (line 403) | formatItemList(heading, items, helper) {
    method groupItems (line 417) | groupItems(unsortedItems, visibleItems, getGroup) {
    method formatHelp (line 443) | formatHelp(cmd, helper) {
    method displayWidth (line 535) | displayWidth(str) {
    method styleTitle (line 545) | styleTitle(str) {
    method styleUsage (line 549) | styleUsage(str) {
    method styleCommandDescription (line 563) | styleCommandDescription(str) {
    method styleOptionDescription (line 566) | styleOptionDescription(str) {
    method styleSubcommandDescription (line 569) | styleSubcommandDescription(str) {
    method styleArgumentDescription (line 572) | styleArgumentDescription(str) {
    method styleDescriptionText (line 575) | styleDescriptionText(str) {
    method styleOptionTerm (line 578) | styleOptionTerm(str) {
    method styleSubcommandTerm (line 581) | styleSubcommandTerm(str) {
    method styleArgumentTerm (line 594) | styleArgumentTerm(str) {
    method styleOptionText (line 597) | styleOptionText(str) {
    method styleArgumentText (line 600) | styleArgumentText(str) {
    method styleSubcommandText (line 603) | styleSubcommandText(str) {
    method styleCommandText (line 606) | styleCommandText(str) {
    method padWidth (line 618) | padWidth(cmd, helper) {
    method preformatted (line 633) | preformatted(str) {
    method formatItem (line 650) | formatItem(term, termWidth, description, helper) {
    method boxWrap (line 695) | boxWrap(str, width) {
  function stripColor (line 740) | function stripColor(str) {

FILE: lib/option.js
  class Option (line 3) | class Option {
    method constructor (line 11) | constructor(flags, description) {
    method default (line 47) | default(value, description) {
    method preset (line 65) | preset(arg) {
    method conflicts (line 82) | conflicts(names) {
    method implies (line 100) | implies(impliedOptionValues) {
    method env (line 120) | env(name) {
    method argParser (line 132) | argParser(fn) {
    method makeOptionMandatory (line 144) | makeOptionMandatory(mandatory = true) {
    method hideHelp (line 156) | hideHelp(hide = true) {
    method _collectValue (line 165) | _collectValue(value, previous) {
    method choices (line 181) | choices(values) {
    method name (line 203) | name() {
    method attributeName (line 217) | attributeName() {
    method helpGroup (line 230) | helpGroup(heading) {
    method is (line 243) | is(arg) {
    method isBoolean (line 256) | isBoolean() {
  class DualOptions (line 268) | class DualOptions {
    method constructor (line 272) | constructor(options) {
    method valueFromOption (line 297) | valueFromOption(value, option) {
  function camelcase (line 316) | function camelcase(str) {
  function splitOptionFlags (line 328) | function splitOptionFlags(flags) {

FILE: lib/suggestSimilar.js
  function editDistance (line 3) | function editDistance(a, b) {
  function suggestSimilar (line 56) | function suggestSimilar(word, candidates) {

FILE: tests/argument.custom-processing.test.js
  function justSayNo (line 169) | function justSayNo(value) {

FILE: tests/command.action.test.js
  function delay (line 115) | async function delay() {
  function getTestCases (line 128) | function getTestCases(arg) {

FILE: tests/command.allowExcessArguments.test.js
  function configureCommand (line 8) | function configureCommand(cmd) {

FILE: tests/command.argumentVariations.test.js
  function getSingleArgCases (line 90) | function getSingleArgCases(arg) {
  function getMultipleArgCases (line 112) | function getMultipleArgCases(arg1, arg2) {

FILE: tests/command.createArgument.test.js
  class MyArgument (line 3) | class MyArgument extends commander.Argument {
    method constructor (line 4) | constructor(name, description) {
  class MyCommand (line 10) | class MyCommand extends commander.Command {
    method createArgument (line 11) | createArgument(name, description) {
    method createCommand (line 16) | createCommand(name) {

FILE: tests/command.createHelp.test.js
  class MyHelp (line 4) | class MyHelp extends commander.Help {
    method formatHelp (line 5) | formatHelp(cmd, helper) {
  class MyCommand (line 10) | class MyCommand extends commander.Command {
    method createHelp (line 11) | createHelp() {

FILE: tests/command.createOption.test.js
  class MyOption (line 3) | class MyOption extends commander.Option {
    method constructor (line 4) | constructor(flags, description) {
  class MyCommand (line 10) | class MyCommand extends commander.Command {
    method createOption (line 11) | createOption(flags, description) {

FILE: tests/command.default.test.js
  function makeProgram (line 29) | function makeProgram() {
  function makeProgram (line 61) | function makeProgram() {

FILE: tests/command.executableSubcommand.mock.test.js
  function makeSystemError (line 8) | function makeSystemError(code) {

FILE: tests/command.executableSubcommand.search.test.js
  function extractMockSpawnArgs (line 11) | function extractMockSpawnArgs(mock) {
  function extractMockSpawnCommand (line 18) | function extractMockSpawnCommand(mock) {

FILE: tests/command.exitOverride.test.js
  function expectCommanderError (line 11) | function expectCommanderError(err, exitCode, code, message) {
  function justSayNo (line 355) | function justSayNo(value) {
  function justSayNo (line 378) | function justSayNo(value) {
  function justSayNo (line 449) | function justSayNo(value) {

FILE: tests/command.parse.test.js
  function collect (line 269) | function collect(value, previous) {
  function increaseVerbosity (line 283) | function increaseVerbosity(dummyValue, previous) {

FILE: tests/command.parseOptions.test.js
  function createProgram1032 (line 14) | function createProgram1032() {
  function createProgram (line 56) | function createProgram() {
  function createProgram (line 243) | function createProgram() {

FILE: tests/command.positionalOptions.test.js
  function makeProgram (line 7) | function makeProgram() {
  function makeProgram (line 76) | function makeProgram() {
  function makeProgram (line 151) | function makeProgram() {
  function makeProgram (line 219) | function makeProgram() {
  function makeProgram (line 291) | function makeProgram() {
  function makeProgram (line 335) | function makeProgram() {
  function makeProgram (line 393) | function makeProgram() {
  function makeProgram (line 462) | function makeProgram() {
  function makeProgram (line 494) | function makeProgram() {

FILE: tests/command.showHelpAfterError.test.js
  function makeProgram (line 6) | function makeProgram() {

FILE: tests/command.showSuggestionAfterError.test.js
  function getSuggestion (line 3) | function getSuggestion(program, arg) {

FILE: tests/createCommand.test.js
  class MyClass (line 11) | class MyClass extends commander.Command {
    method constructor (line 12) | constructor(name) {
    method createCommand (line 17) | createCommand(name) {
  function createCustom (line 27) | function createCustom(name) {

FILE: tests/esm-imports-test.mjs
  function check (line 19) | function check(condition, explanation) {
  function checkClass (line 26) | function checkClass(obj, name) {

FILE: tests/help.stripAnsi.test.js
  constant ESC (line 7) | const ESC = '\u001b';
  constant CSI (line 8) | const CSI = ESC + '[';

FILE: tests/help.style.test.js
  function red (line 3) | function red(str) {
  function stripRed (line 7) | function stripRed(str) {
  function displayWidth (line 10) | function displayWidth(str) {
  function makeProgram (line 16) | function makeProgram() {
  function makeProgram (line 232) | function makeProgram(hasColors) {

FILE: tests/help.suggestion.test.js
  function getSuggestion (line 6) | function getSuggestion(program, arg) {

FILE: tests/incrementNodeInspectorPort.test.js
  function makeProgram (line 29) | function makeProgram() {
  function extractMockExecArgs (line 38) | function extractMockExecArgs(mock) {

FILE: tests/options.bool.combo.test.js
  function createPepperProgram (line 8) | function createPepperProgram() {
  function createPepperProgramWithDefault (line 49) | function createPepperProgramWithDefault(defaultValue) {
  function createPepperProgramWithDefaultAndPreset (line 122) | function createPepperProgramWithDefaultAndPreset() {

FILE: tests/options.conflicts.test.js
  function makeProgram (line 5) | function makeProgram() {

FILE: tests/options.custom-processing.test.js
  function myParseInt (line 3) | function myParseInt(value, dummyPrevious) {
  function increaseVerbosity (line 8) | function increaseVerbosity(dummyValue, previous) {
  function collect (line 12) | function collect(value, previous) {
  function commaSeparatedList (line 16) | function commaSeparatedList(value, dummyPrevious) {

FILE: tests/options.values.test.js
  function createPortProgram (line 12) | function createPortProgram() {
  function createPortProgram (line 46) | function createPortProgram() {

FILE: tests/program.test.js
  function checkClass (line 20) | function checkClass(obj, name) {

FILE: tests/ts-imports.test.ts
  function checkClass (line 17) | function checkClass(obj: object, name: string): void {

FILE: typings/index.d.ts
  type LiteralUnion (line 12) | type LiteralUnion<LiteralType, BaseType extends string | number> =
  class CommanderError (line 16) | class CommanderError extends Error {
  class InvalidArgumentError (line 31) | class InvalidArgumentError extends CommanderError {
  type ErrorOptions (line 40) | interface ErrorOptions {
  class Argument (line 48) | class Argument {
  class Option (line 95) | class Option {
  class Help (line 210) | class Help {
  type HelpConfiguration (line 340) | type HelpConfiguration = Partial<Help>;
  type ParseOptions (line 342) | interface ParseOptions {
  type HelpContext (line 345) | interface HelpContext {
  type AddHelpTextContext (line 349) | interface AddHelpTextContext {
  type OutputConfiguration (line 354) | interface OutputConfiguration {
  type AddHelpTextPosition (line 367) | type AddHelpTextPosition = 'beforeAll' | 'before' | 'after' | 'afterAll';
  type HookEvent (line 368) | type HookEvent = 'preSubcommand' | 'preAction' | 'postAction';
  type OptionValueSource (line 370) | type OptionValueSource =
  type OptionValues (line 374) | type OptionValues = Record<string, any>;
  class Command (line 376) | class Command {
  type CommandOptions (line 1094) | interface CommandOptions {
  type ExecutableCommandOptions (line 1100) | interface ExecutableCommandOptions extends CommandOptions {
  type ParseOptionsResult (line 1104) | interface ParseOptionsResult {

FILE: typings/index.test-d.ts
  function myParseInt (line 168) | function myParseInt(value: string): number {
  function increaseVerbosity (line 172) | function increaseVerbosity(dummyValue: string, previous: number): number {
  function collect (line 176) | function collect(value: string, previous: string[]): string[] {
  function commaSeparatedList (line 180) | function commaSeparatedList(value: string): string[] {
  type MyCheeseOption (line 384) | interface MyCheeseOption {
  class MyCommand (line 509) | class MyCommand extends commander.Command {
    method createCommand (line 510) | createCommand(name?: string): MyCommand {
    method myFunction (line 514) | myFunction(): void {
Condensed preview — 219 files, each showing path, character count, and a content snippet. Download the .json file or copy for the full structured content (889K chars).
[
  {
    "path": ".editorconfig",
    "chars": 228,
    "preview": "# EditorConfig is awesome: http://EditorConfig.org\n\n# top-most EditorConfig file\nroot = true\n\n[*]\nend_of_line = lf\ninser"
  },
  {
    "path": ".gitattributes",
    "chars": 147,
    "preview": "# disable line-ending changes (otherwise Windows developers with default settings from git install see Prettier wanting "
  },
  {
    "path": ".github/FUNDING.yml",
    "chars": 59,
    "preview": "github: [shadowspawn, abetomo, tj]\ntidelift: npm/commander\n"
  },
  {
    "path": ".github/PULL_REQUEST_TEMPLATE.md",
    "chars": 1372,
    "preview": "<!--\nThe text in these markdown comments is instructions that will not appear in the displayed pull request,\nand can be "
  },
  {
    "path": ".github/dependabot.yml",
    "chars": 264,
    "preview": "version: 2\nupdates:\n  - package-ecosystem: \"npm\"\n    target-branch: \"develop\"\n    directory: \"/\"\n    schedule:\n      int"
  },
  {
    "path": ".github/workflows/codeql-analysis.yml",
    "chars": 1709,
    "preview": "name: \"CodeQL\"\n\non:\n  push:\n    branches: [ master, develop ]\n  pull_request:\n    # The branches below must be a subset "
  },
  {
    "path": ".github/workflows/tests.yml",
    "chars": 759,
    "preview": "name: build\n\non: [push, pull_request]\n\npermissions:\n  contents: read\n\njobs:\n  test:\n    name: Test on node ${{ matrix.no"
  },
  {
    "path": ".gitignore",
    "chars": 55,
    "preview": ".DS_Store\nnode_modules\n*.sock\n.idea\n.vscode/\ncoverage/\n"
  },
  {
    "path": ".prettierignore",
    "chars": 158,
    "preview": "# exclude everything, and opt-in to types we want to format\n**.*\n# add the filetypes we want to format\n!**.js\n!**.mjs\n!*"
  },
  {
    "path": ".prettierrc.js",
    "chars": 169,
    "preview": "const config = {\n  singleQuote: true,\n  overrides: [\n    {\n      files: ['tsconfig*.json'],\n      options: { parser: 'js"
  },
  {
    "path": "CHANGELOG.md",
    "chars": 60064,
    "preview": "# Changelog\n\nAll notable changes to this project will be documented in this file.\n\nThe format is based on [Keep a Change"
  },
  {
    "path": "CONTRIBUTING.md",
    "chars": 1741,
    "preview": "# Contributing\n\n## Issues\n\nNew issues are welcome, whether questions or suggestions or reporting bugs.\nYou are also welc"
  },
  {
    "path": "LICENSE",
    "chars": 1098,
    "preview": "(The MIT License)\n\nCopyright (c) 2011 TJ Holowaychuk <tj@vision-media.ca>\n\nPermission is hereby granted, free of charge,"
  },
  {
    "path": "Readme.md",
    "chars": 43361,
    "preview": "# Commander.js\n\n[![Build Status](https://github.com/tj/commander.js/workflows/build/badge.svg)](https://github.com/tj/co"
  },
  {
    "path": "Readme_zh-CN.md",
    "chars": 28641,
    "preview": "# Commander.js\n\n[![Build Status](https://github.com/tj/commander.js/workflows/build/badge.svg)](https://github.com/tj/co"
  },
  {
    "path": "SECURITY.md",
    "chars": 273,
    "preview": "# Security Policy\n\nTo report a security vulnerability, please use the\n[Tidelift security contact](https://tidelift.com/s"
  },
  {
    "path": "docs/deprecated.md",
    "chars": 7382,
    "preview": "# Deprecated\n\nThese features are deprecated, which means they may go away in a future major version of Commander.\nThey a"
  },
  {
    "path": "docs/help-in-depth.md",
    "chars": 4328,
    "preview": "# Help in Depth\n\nThe built-in help is formatted using the Help class.\nYou can configure the Help behaviour by modifying "
  },
  {
    "path": "docs/options-in-depth.md",
    "chars": 6120,
    "preview": "<!-- omit from toc -->\n# Options in Depth\n\nThe README covers declaring and using options, and mostly parsing will work t"
  },
  {
    "path": "docs/parsing-and-hooks.md",
    "chars": 883,
    "preview": "# Parsing life cycle and hooks\n\nThe processing starts with an array of args. Each command processes and removes the opti"
  },
  {
    "path": "docs/release-policy.md",
    "chars": 1027,
    "preview": "# Release Policy\n\nWe follow [Semantic Versioning](http://semver.org/spec/v2.0.0.html), and limit breaking changes to maj"
  },
  {
    "path": "docs/terminology.md",
    "chars": 735,
    "preview": "# Terminology\n\nThe command line arguments are made up of options, option-arguments, commands, and command-arguments.\n\n| "
  },
  {
    "path": "docs/zh-CN/不再推荐使用的功能.md",
    "chars": 4249,
    "preview": "# 不再推荐使用的功能\n\n本文中列出的功能不再推荐使用。它们在 Commander 未来的主要版本(major version)中可能被移除。为保证后向兼容,这些功能目前还可以使用,但它们不应被用在新代码中。\n\n- [不再推荐使用的功能]("
  },
  {
    "path": "docs/zh-CN/可变参数的选项.md",
    "chars": 4694,
    "preview": "# 可变参数的选项\n\nREADME 文档介绍了选项的声明与使用。大多数情况下,选项的解析行为,与您和您程序用户的期望相符。本文将详述一些特殊用例和细节问题。\n\n- [可变参数的选项](#%E5%8F%AF%E5%8F%98%E5%8F%82"
  },
  {
    "path": "docs/zh-CN/术语表.md",
    "chars": 464,
    "preview": "# 术语表\n\n命令行参数由选项(options)、选项参数(option-arguments)、命令(commands),以及命令参数(command-arguments)组成。\n\n|术语|解释|\n|---|---|\n|选项(option)"
  },
  {
    "path": "eslint.config.js",
    "chars": 2110,
    "preview": "const globals = require('globals');\nconst esLintjs = require('@eslint/js');\nconst jest = require('eslint-plugin-jest');\n"
  },
  {
    "path": "esm.mjs",
    "chars": 310,
    "preview": "import commander from './index.js';\n\n// wrapper to provide named exports for ESM.\nexport const {\n  program,\n  createComm"
  },
  {
    "path": "examples/action-this.js",
    "chars": 479,
    "preview": "#!/usr/bin/env node\n\n// This example is used as an example in the README for the action handler.\n\nconst { Command } = re"
  },
  {
    "path": "examples/alias.js",
    "chars": 859,
    "preview": "#!/usr/bin/env node\n\n// This example shows giving alternative names for a command.\n\nconst { Command } = require('command"
  },
  {
    "path": "examples/argument.js",
    "chars": 648,
    "preview": "#!/usr/bin/env node\n\n// This example shows specifying the command arguments using argument() function.\n\nconst { Command "
  },
  {
    "path": "examples/arguments-custom-processing.js",
    "chars": 1336,
    "preview": "#!/usr/bin/env node\n\n// This is used as an example in the README for:\n//    Custom argument processing\n//    You may spe"
  },
  {
    "path": "examples/arguments-extra.js",
    "chars": 778,
    "preview": "#!/usr/bin/env node\n\n// This is used as an example in the README for extra argument features.\n\nconst commander = require"
  },
  {
    "path": "examples/color-help-replacement.mjs",
    "chars": 3210,
    "preview": "import stripAnsi from 'strip-ansi';\nimport wrapAnsi from 'wrap-ansi';\nimport {\n  default as chalkStdOut,\n  chalkStderr a"
  },
  {
    "path": "examples/color-help.mjs",
    "chars": 1237,
    "preview": "import { styleText } from 'node:util'; // from node v20.12.0\nimport { Command } from 'commander';\n\n// Customise colours "
  },
  {
    "path": "examples/configure-help.js",
    "chars": 816,
    "preview": "const commander = require('commander');\nconst program = new commander.Command();\n\n// This example shows a simple use of "
  },
  {
    "path": "examples/configure-output.js",
    "chars": 743,
    "preview": "const commander = require('commander');\nconst program = new commander.Command();\n\nfunction errorColor(str) {\n  // Add AN"
  },
  {
    "path": "examples/custom-command-class.js",
    "chars": 1390,
    "preview": "#!/usr/bin/env node\nconst commander = require('commander');\n\n// Use a class override to customise the command and its su"
  },
  {
    "path": "examples/custom-help",
    "chars": 403,
    "preview": "#!/usr/bin/env node\n\n// This example shows a simple use of addHelpText.\n// This is used as an example in the README.\n\nco"
  },
  {
    "path": "examples/custom-help-description",
    "chars": 645,
    "preview": "#!/usr/bin/env node\n\n// This example shows changing the flags and description for the help option.\n\nconst { Command } = "
  },
  {
    "path": "examples/custom-help-text.js",
    "chars": 747,
    "preview": "#!/usr/bin/env node\n\n// This example shows using addHelpText.\n\nconst { Command } = require('commander');\nconst program ="
  },
  {
    "path": "examples/custom-version",
    "chars": 487,
    "preview": "#!/usr/bin/env node\n\n// This example shows changing the flags and description for the version option.\n\nconst { Command }"
  },
  {
    "path": "examples/defaultCommand.js",
    "chars": 843,
    "preview": "#!/usr/bin/env node\n\nconst commander = require('commander');\nconst program = new commander.Command();\n\n// Example progra"
  },
  {
    "path": "examples/deploy",
    "chars": 1111,
    "preview": "#!/usr/bin/env node\n\nconst { Command } = require('commander');\nconst program = new Command();\n\nprogram\n  .name('deploy')"
  },
  {
    "path": "examples/description",
    "chars": 563,
    "preview": "#!/usr/bin/env node\n\n// This example shows adding a description which is displayed in the help.\n\nconst { Command } = req"
  },
  {
    "path": "examples/global-options-added.js",
    "chars": 1701,
    "preview": "#!/usr/bin/env node\n\n// This example shows a couple of ways to add a \"global\" option to all of the subcommands.\n// The f"
  },
  {
    "path": "examples/global-options-nested.js",
    "chars": 816,
    "preview": "#!/usr/bin/env node\n\n// This example shows global options on the program which affect all the subcommands.\n// See how to"
  },
  {
    "path": "examples/help-centered.mjs",
    "chars": 1077,
    "preview": "import { Command, Help } from 'commander';\n\n// Right-justify the terms in the help output.\n// Setup a subclass so we can"
  },
  {
    "path": "examples/help-groups.js",
    "chars": 2708,
    "preview": "const { Command, Option } = require('commander');\n\n// Show the two approaches for adding help groups, and how to customi"
  },
  {
    "path": "examples/help-subcommands-usage.js",
    "chars": 1022,
    "preview": "const commander = require('commander');\n\n// By default the subcommand list includes a fairly simple usage. If you have a"
  },
  {
    "path": "examples/hook.js",
    "chars": 2230,
    "preview": "#!/usr/bin/env node\n\nconst { Command, Option } = require('commander');\nconst program = new Command();\n\n// This example s"
  },
  {
    "path": "examples/man-style-help.mjs",
    "chars": 1033,
    "preview": "import { Command } from 'commander';\n\n// Layout the help like a man page, with the description starting on the next line"
  },
  {
    "path": "examples/nestedCommands.js",
    "chars": 1018,
    "preview": "#!/usr/bin/env node\n\nconst commander = require('commander');\nconst program = new commander.Command();\n\n// Commander supp"
  },
  {
    "path": "examples/options-boolean-or-value.js",
    "chars": 779,
    "preview": "#!/usr/bin/env node\n\n// This is used as an example in the README for:\n//    Other option types, flag|value\n//    You can"
  },
  {
    "path": "examples/options-common.js",
    "chars": 764,
    "preview": "#!/usr/bin/env node\n\n// This is used as an example in the README for:\n//    Common option types, boolean and value\n\ncons"
  },
  {
    "path": "examples/options-conflicts.js",
    "chars": 2600,
    "preview": "#!/usr/bin/env node\nconst { Command, Option } = require('commander');\nconst program = new Command();\n\n// You can use .co"
  },
  {
    "path": "examples/options-custom-processing.js",
    "chars": 1759,
    "preview": "#!/usr/bin/env node\n\n// This is used as an example in the README for:\n//    Custom option processing\n//    You may speci"
  },
  {
    "path": "examples/options-defaults.js",
    "chars": 442,
    "preview": "#!/usr/bin/env node\n\n// This is used as an example in the README for:\n//    Default option value\n\nconst commander = requ"
  },
  {
    "path": "examples/options-env.js",
    "chars": 1063,
    "preview": "#!/usr/bin/env node\nconst { Command, Option } = require('commander');\nconst program = new Command();\n\nprogram.addOption("
  },
  {
    "path": "examples/options-extra.js",
    "chars": 1423,
    "preview": "#!/usr/bin/env node\n\n// This is used as an example in the README for extra option features.\n// See also options-env.js f"
  },
  {
    "path": "examples/options-implies.js",
    "chars": 903,
    "preview": "#!/usr/bin/env node\nconst { Command, Option } = require('commander');\nconst program = new Command();\n\nprogram\n  .addOpti"
  },
  {
    "path": "examples/options-negatable.js",
    "chars": 941,
    "preview": "#!/usr/bin/env node\n\n// This is used as an example in the README for:\n//    Other option types, negatable boolean\n//    "
  },
  {
    "path": "examples/options-required.js",
    "chars": 583,
    "preview": "#!/usr/bin/env node\n\n// This is used as an example in the README for:\n//    Required option\n//    You may specify a requ"
  },
  {
    "path": "examples/options-variadic.js",
    "chars": 600,
    "preview": "#!/usr/bin/env node\n\n// This is used as an example in the README for variadic options.\n\nconst commander = require('comma"
  },
  {
    "path": "examples/pass-through-options.js",
    "chars": 633,
    "preview": "#!/usr/bin/env node\n\nconst { Command } = require('commander');\nconst program = new Command();\n\nprogram\n  .argument('<uti"
  },
  {
    "path": "examples/pizza",
    "chars": 750,
    "preview": "#!/usr/bin/env node\n\nconst { Command } = require('commander');\nconst program = new Command();\n\nprogram\n  .description('A"
  },
  {
    "path": "examples/pm",
    "chars": 1080,
    "preview": "#!/usr/bin/env node\n\nconst { Command } = require('commander');\nconst program = new Command();\n\n// Example of subcommands"
  },
  {
    "path": "examples/pm-install",
    "chars": 488,
    "preview": "#!/usr/bin/env node\n\nconst { Command } = require('commander');\nconst program = new Command();\n\nprogram.option('-f, --for"
  },
  {
    "path": "examples/pm-list.js",
    "chars": 42,
    "preview": "#!/usr/bin/env node\n\nconsole.log('list');\n"
  },
  {
    "path": "examples/positional-options.js",
    "chars": 731,
    "preview": "#!/usr/bin/env node\n\nconst { Command } = require('commander');\nconst program = new Command();\n\nprogram.enablePositionalO"
  },
  {
    "path": "examples/split.js",
    "chars": 479,
    "preview": "const { program } = require('commander');\n\n// This is used as an example in the README for the Quick Start.\n\nprogram.opt"
  },
  {
    "path": "examples/string-util.js",
    "chars": 1181,
    "preview": "const { Command } = require('commander');\nconst program = new Command();\n\n// This is used as an example in the README fo"
  },
  {
    "path": "examples/thank.js",
    "chars": 720,
    "preview": "#!/usr/bin/env node\n\n// This example is used as an example in the README for the action handler.\n\nconst { Command } = re"
  },
  {
    "path": "index.js",
    "chars": 812,
    "preview": "const { Argument } = require('./lib/argument.js');\nconst { Command } = require('./lib/command.js');\nconst { CommanderErr"
  },
  {
    "path": "jest.config.js",
    "chars": 230,
    "preview": "const config = {\n  testEnvironment: 'node',\n  collectCoverage: true,\n  transform: {\n    '^.+\\\\.tsx?$': ['ts-jest', { tsc"
  },
  {
    "path": "lib/argument.js",
    "chars": 3208,
    "preview": "const { InvalidArgumentError } = require('./error.js');\n\nclass Argument {\n  /**\n   * Initialize a new command argument w"
  },
  {
    "path": "lib/command.js",
    "chars": 87209,
    "preview": "const EventEmitter = require('node:events').EventEmitter;\nconst childProcess = require('node:child_process');\nconst path"
  },
  {
    "path": "lib/error.js",
    "chars": 1170,
    "preview": "/**\n * CommanderError class\n */\nclass CommanderError extends Error {\n  /**\n   * Constructs the CommanderError class\n   *"
  },
  {
    "path": "lib/help.js",
    "chars": 21130,
    "preview": "const { humanReadableArgName } = require('./argument.js');\n\n/**\n * TypeScript import types for JSDoc, used by Visual Stu"
  },
  {
    "path": "lib/option.js",
    "chars": 10289,
    "preview": "const { InvalidArgumentError } = require('./error.js');\n\nclass Option {\n  /**\n   * Initialize a new `Option` with the gi"
  },
  {
    "path": "lib/suggestSimilar.js",
    "chars": 2772,
    "preview": "const maxDistance = 3;\n\nfunction editDistance(a, b) {\n  // https://en.wikipedia.org/wiki/Damerau–Levenshtein_distance\n  "
  },
  {
    "path": "package-support.json",
    "chars": 337,
    "preview": "{\n  \"versions\": [\n    {\n      \"version\": \"*\",\n      \"target\": {\n        \"node\": \"supported\"\n      },\n      \"response\": {"
  },
  {
    "path": "package.json",
    "chars": 2097,
    "preview": "{\n  \"name\": \"commander\",\n  \"version\": \"14.0.3\",\n  \"description\": \"the complete solution for node.js command-line program"
  },
  {
    "path": "tests/args.literal.test.js",
    "chars": 1292,
    "preview": "const commander = require('../');\n\n// Utility Conventions: http://pubs.opengroup.org/onlinepubs/9699919799/basedefs/V1_c"
  },
  {
    "path": "tests/args.variadic.test.js",
    "chars": 2621,
    "preview": "const commander = require('../');\n\n// Testing variadic arguments. Testing all the action arguments, but could test just "
  },
  {
    "path": "tests/argument.chain.test.js",
    "chars": 1069,
    "preview": "const { Argument } = require('../');\n\ndescribe('Argument methods that should return this for chaining', () => {\n  test('"
  },
  {
    "path": "tests/argument.choices.test.js",
    "chars": 2076,
    "preview": "const commander = require('../');\n\ntest('when command argument in choices then argument set', () => {\n  const program = "
  },
  {
    "path": "tests/argument.custom-processing.test.js",
    "chars": 6886,
    "preview": "const commander = require('../');\n\n// Testing default value and custom processing behaviours.\n// Some double assertions "
  },
  {
    "path": "tests/argument.required.test.js",
    "chars": 1136,
    "preview": "const commander = require('../');\n\n// Low-level tests of setting Argument.required.\n// Higher level tests of optional/re"
  },
  {
    "path": "tests/argument.variadic.test.js",
    "chars": 3949,
    "preview": "const commander = require('../');\n\n// Testing variadic arguments. Testing all the action arguments, but could test just "
  },
  {
    "path": "tests/command.action.test.js",
    "chars": 4711,
    "preview": "const commander = require('../');\n\n// Test some behaviours of .action not covered in more specific tests.\n\ntest('when .a"
  },
  {
    "path": "tests/command.addCommand.test.js",
    "chars": 1935,
    "preview": "const commander = require('../');\n\n// simple sanity check subcommand works\ntest('when addCommand and specify subcommand "
  },
  {
    "path": "tests/command.addHelpOption.test.js",
    "chars": 1580,
    "preview": "const { Command, Option } = require('../');\n\n// More complete tests are in command.helpOption.test.js.\n\ndescribe('addHel"
  },
  {
    "path": "tests/command.addHelpText.test.js",
    "chars": 7834,
    "preview": "const commander = require('../');\n\n// Using outputHelp to simplify testing.\n\ndescribe('program calls to addHelpText', ()"
  },
  {
    "path": "tests/command.alias.test.js",
    "chars": 3775,
    "preview": "const commander = require('../');\n\n// Running alias commands is tested in command.executableSubcommand.lookup.test.js\n//"
  },
  {
    "path": "tests/command.allowExcessArguments.test.js",
    "chars": 3728,
    "preview": "const commander = require('../');\n\n// Not testing output, just testing whether an error is detected.\n\ndescribe.each([tru"
  },
  {
    "path": "tests/command.allowUnknownOption.test.js",
    "chars": 2740,
    "preview": "const commander = require('../');\n\n// Not testing output, just testing whether an error is detected.\n\ndescribe('allowUnk"
  },
  {
    "path": "tests/command.argumentVariations.test.js",
    "chars": 4078,
    "preview": "const commander = require('../');\n\n// Do some low-level checks that the multiple ways of specifying command arguments pr"
  },
  {
    "path": "tests/command.asterisk.test.js",
    "chars": 5494,
    "preview": "const commander = require('../');\n\n// .command('*') is the old main/default command handler. It adds a listener\n// for '"
  },
  {
    "path": "tests/command.chain.test.js",
    "chars": 9164,
    "preview": "const { Command, Option, Argument } = require('../');\n\n// Testing the functions which should chain.\n// parse and parseAs"
  },
  {
    "path": "tests/command.commandHelp.test.js",
    "chars": 590,
    "preview": "const commander = require('../');\n\n// This is a ported legacy test.\n\ntest('when program has command then appears in help"
  },
  {
    "path": "tests/command.configureHelp.test.js",
    "chars": 1205,
    "preview": "const commander = require('../');\n\ntest('when configure program then affects program helpInformation', () => {\n  const p"
  },
  {
    "path": "tests/command.configureOutput.test.js",
    "chars": 10514,
    "preview": "const commander = require('../');\nconst process = require('node:process');\n\ntest('when default writeErr() then error on "
  },
  {
    "path": "tests/command.copySettings.test.js",
    "chars": 5437,
    "preview": "const commander = require('../');\n\n// Tests some private properties as simpler than pure tests of observable behaviours."
  },
  {
    "path": "tests/command.createArgument.test.js",
    "chars": 1292,
    "preview": "const commander = require('../');\n\nclass MyArgument extends commander.Argument {\n  constructor(name, description) {\n    "
  },
  {
    "path": "tests/command.createHelp.test.js",
    "chars": 435,
    "preview": "const commander = require('../');\n\ntest('when override createCommand then affects help', () => {\n  class MyHelp extends "
  },
  {
    "path": "tests/command.createOption.test.js",
    "chars": 1366,
    "preview": "const commander = require('../');\n\nclass MyOption extends commander.Option {\n  constructor(flags, description) {\n    sup"
  },
  {
    "path": "tests/command.default.test.js",
    "chars": 3260,
    "preview": "const childProcess = require('child_process');\nconst commander = require('../');\nconst path = require('path');\nconst uti"
  },
  {
    "path": "tests/command.description.test.js",
    "chars": 262,
    "preview": "const commander = require('../');\n\ntest('when set description then get description', () => {\n  const program = new comma"
  },
  {
    "path": "tests/command.error.test.js",
    "chars": 1666,
    "preview": "const commander = require('../');\n\ntest('when error called with message then message displayed on stderr', () => {\n  con"
  },
  {
    "path": "tests/command.executableSubcommand.inspect.test.js",
    "chars": 2625,
    "preview": "const childProcess = require('child_process');\nconst path = require('path');\nconst util = require('util');\n\nconst execFi"
  },
  {
    "path": "tests/command.executableSubcommand.lookup.test.js",
    "chars": 4595,
    "preview": "const childProcess = require('child_process');\nconst path = require('path');\nconst util = require('util');\nconst execFil"
  },
  {
    "path": "tests/command.executableSubcommand.mock.test.js",
    "chars": 3984,
    "preview": "const commander = require('../');\nconst childProcess = require('child_process');\nconst EventEmitter = require('events');"
  },
  {
    "path": "tests/command.executableSubcommand.search.test.js",
    "chars": 11688,
    "preview": "const childProcess = require('child_process');\nconst fs = require('fs');\nconst path = require('path');\nconst commander ="
  },
  {
    "path": "tests/command.executableSubcommand.signals.test.js",
    "chars": 2039,
    "preview": "const childProcess = require('child_process');\nconst path = require('path');\n\nconst pmPath = path.join(__dirname, 'fixtu"
  },
  {
    "path": "tests/command.executableSubcommand.test.js",
    "chars": 678,
    "preview": "const commander = require('../');\n\n// Executable subcommand tests that didn't fit in elsewhere.\n\n// This is the default "
  },
  {
    "path": "tests/command.exitOverride.test.js",
    "chars": 12231,
    "preview": "const commander = require('../');\nconst path = require('path');\n\n// Test details of the exitOverride errors.\n// The impo"
  },
  {
    "path": "tests/command.help.test.js",
    "chars": 11122,
    "preview": "const commander = require('../');\n\n// Testing various help incantations.\n//\n// Note there are also specific help tests i"
  },
  {
    "path": "tests/command.helpCommand.test.js",
    "chars": 5693,
    "preview": "const commander = require('../');\n\ndescribe('help command listed in helpInformation', () => {\n  test('when program has n"
  },
  {
    "path": "tests/command.helpOption.test.js",
    "chars": 4825,
    "preview": "const commander = require('../');\n\ndescribe('helpOption', () => {\n  let writeSpy;\n  let writeErrorSpy;\n\n  beforeAll(() ="
  },
  {
    "path": "tests/command.hook.test.js",
    "chars": 12642,
    "preview": "const commander = require('../');\n\ntest('when hook event wrong then throw', () => {\n  const program = new commander.Comm"
  },
  {
    "path": "tests/command.name.test.js",
    "chars": 1882,
    "preview": "const path = require('path');\nconst commander = require('../');\n\ntest('when construct with name then name is set', () =>"
  },
  {
    "path": "tests/command.nested.test.js",
    "chars": 325,
    "preview": "const commander = require('../');\n\ntest('when call nested subcommand then runs', () => {\n  const program = new commander"
  },
  {
    "path": "tests/command.onCommand.test.js",
    "chars": 1295,
    "preview": "const commander = require('../');\n\n// The action handler used to be implemented using command events and listeners.\n// N"
  },
  {
    "path": "tests/command.option-misuse.test.js",
    "chars": 650,
    "preview": "const { Command, Option } = require('../');\n\n// It is a reasonable and easy mistake to pass Option to .option(). Detect "
  },
  {
    "path": "tests/command.parse.test.js",
    "chars": 15195,
    "preview": "const commander = require('../');\n\n// Testing some Electron conventions but not directly using Electron to avoid overhea"
  },
  {
    "path": "tests/command.parseOptions.test.js",
    "chars": 14070,
    "preview": "const childProcess = require('child_process');\nconst commander = require('../');\nconst path = require('path');\nconst uti"
  },
  {
    "path": "tests/command.positionalOptions.test.js",
    "chars": 18874,
    "preview": "const commander = require('../');\n\n// The changes to parsing for positional options are subtle, and took extra care to w"
  },
  {
    "path": "tests/command.registerClash.test.js",
    "chars": 1474,
    "preview": "const { Command } = require('../');\n\ntest('when command name conflicts with existing name then throw', () => {\n  expect("
  },
  {
    "path": "tests/command.showHelpAfterError.test.js",
    "chars": 3819,
    "preview": "const commander = require('../');\n\ndescribe('showHelpAfterError with message', () => {\n  const customHelpMessage = 'See "
  },
  {
    "path": "tests/command.showSuggestionAfterError.test.js",
    "chars": 1576,
    "preview": "const { Command } = require('../');\n\nfunction getSuggestion(program, arg) {\n  let message = '';\n  program.exitOverride()"
  },
  {
    "path": "tests/command.summary.test.js",
    "chars": 234,
    "preview": "const commander = require('../');\n\ntest('when set summary then get summary', () => {\n  const program = new commander.Com"
  },
  {
    "path": "tests/command.unknownCommand.test.js",
    "chars": 2174,
    "preview": "const commander = require('../');\n\ndescribe('unknownCommand', () => {\n  // Optional. Use internal knowledge to suppress "
  },
  {
    "path": "tests/command.unknownOption.test.js",
    "chars": 3021,
    "preview": "const commander = require('../');\n\n// Checking for detection of unknown options, including regression tests for some pas"
  },
  {
    "path": "tests/command.usage.test.js",
    "chars": 2629,
    "preview": "const commander = require('../');\n\ntest('when default usage and check program help then starts with default usage', () ="
  },
  {
    "path": "tests/commander.configureCommand.test.js",
    "chars": 3029,
    "preview": "const commander = require('../');\n\n// Mostly testing direct on program, limited check that (sub)command working same.\n\n/"
  },
  {
    "path": "tests/createCommand.test.js",
    "chars": 1055,
    "preview": "const commander = require('../');\n\ntest('when createCommand then unattached', () => {\n  const program = new commander.Co"
  },
  {
    "path": "tests/deprecated.test.js",
    "chars": 1297,
    "preview": "const commander = require('../');\n\n// Test for backwards compatible behaviour of deprecated features that don't fit in e"
  },
  {
    "path": "tests/esm-imports-test.mjs",
    "chars": 1629,
    "preview": "import {\n  program,\n  Command,\n  Option,\n  Argument,\n  CommanderError,\n  InvalidArgumentError,\n  InvalidOptionArgumentEr"
  },
  {
    "path": "tests/fixtures/inspect-sub.js",
    "chars": 31,
    "preview": "console.log(process.execArgv);\n"
  },
  {
    "path": "tests/fixtures/inspect.js",
    "chars": 239,
    "preview": "#!/usr/bin/env node\n\nconst { program } = require('../../');\n\nprocess.env.FORCE_COLOR = 0; // work-around bug in Jest: ht"
  },
  {
    "path": "tests/fixtures/pm",
    "chars": 1468,
    "preview": "#!/usr/bin/env node\n\nconst path = require('node:path');\nconst { program } = require('../../');\n\nprocess.env.FORCE_COLOR "
  },
  {
    "path": "tests/fixtures/pm-cache-clear.js",
    "chars": 28,
    "preview": "console.log('cache-clear');\n"
  },
  {
    "path": "tests/fixtures/pm-cache-validate.js",
    "chars": 31,
    "preview": "console.log('cache-validate');\n"
  },
  {
    "path": "tests/fixtures/pm-cache.js",
    "chars": 177,
    "preview": "const { program } = require('../../');\n\nprogram\n  .command('clear', 'clear the cache')\n  .command('validate', 'validate "
  },
  {
    "path": "tests/fixtures/pm-default",
    "chars": 115,
    "preview": "#!/usr/bin/env node\nconsole.log('default');\nif (process.argv.length > 2) {\n  console.log(process.argv.slice(2));\n}\n"
  },
  {
    "path": "tests/fixtures/pm-echo.js",
    "chars": 36,
    "preview": "console.log(process.argv.slice(2));\n"
  },
  {
    "path": "tests/fixtures/pm-fail.js",
    "chars": 18,
    "preview": "process.exit(42);\n"
  },
  {
    "path": "tests/fixtures/pm-install",
    "chars": 44,
    "preview": "#!/usr/bin/env node\nconsole.log('install');\n"
  },
  {
    "path": "tests/fixtures/pm-listen",
    "chars": 587,
    "preview": "#!/usr/bin/env node\n\nprocess.on('SIGUSR1', function () {\n  process.stdout.write('SIGUSR1');\n  process.exit();\n});\n\nproce"
  },
  {
    "path": "tests/fixtures/pm-publish.js",
    "chars": 24,
    "preview": "console.log('publish');\n"
  },
  {
    "path": "tests/fixtures/pm-search",
    "chars": 43,
    "preview": "#!/usr/bin/env node\nconsole.log('search');\n"
  },
  {
    "path": "tests/fixtures/pm-silent",
    "chars": 116,
    "preview": "#!/usr/bin/env node\n\n// This is a subcommand which succeeds and does not write any output, for using from unit test\n"
  },
  {
    "path": "tests/fixtures/pm-terminate.js",
    "chars": 37,
    "preview": "process.kill(process.pid, 'SIGINT');\n"
  },
  {
    "path": "tests/fixtures/pmlink-install",
    "chars": 44,
    "preview": "#!/usr/bin/env node\nconsole.log('install');\n"
  },
  {
    "path": "tests/fixtures-extensions/pm-try-cjs.cjs",
    "chars": 27,
    "preview": "console.log('found .cjs');\n"
  },
  {
    "path": "tests/fixtures-extensions/pm-try-mjs.mjs",
    "chars": 27,
    "preview": "console.log('found .mjs');\n"
  },
  {
    "path": "tests/fixtures-extensions/pm-try-ts.ts",
    "chars": 26,
    "preview": "console.log('found .ts');\n"
  },
  {
    "path": "tests/fixtures-extensions/pm.js",
    "chars": 248,
    "preview": "#!/usr/bin/env node\n\nconst { program } = require('../../');\n\nprogram\n  .command('try-ts', 'test file extension lookup')\n"
  },
  {
    "path": "tests/help.argumentDescription.test.js",
    "chars": 1722,
    "preview": "const commander = require('../');\n\n// These are tests of the Help class, not of the Command help.\n\ndescribe('argumentDes"
  },
  {
    "path": "tests/help.boxWrap.test.js",
    "chars": 4110,
    "preview": "const commander = require('../');\n\ntest('when empty string then return empty string', () => {\n  const helper = new comma"
  },
  {
    "path": "tests/help.commandTerm.test.js",
    "chars": 1708,
    "preview": "const commander = require('../');\n\n// These are tests of the Help class, not of the Command help.\n// There is some overl"
  },
  {
    "path": "tests/help.commandUsage.test.js",
    "chars": 1668,
    "preview": "const commander = require('../');\n\n// These are tests of the Help class, not of the Command help.\n// There is some overl"
  },
  {
    "path": "tests/help.longestArgumentTermLength.test.js",
    "chars": 1168,
    "preview": "const commander = require('../');\n\n// These are tests of the Help class, not of the Command help.\n// There is some overl"
  },
  {
    "path": "tests/help.longestCommandTermLength.test.js",
    "chars": 2039,
    "preview": "const commander = require('../');\n\n// These are tests of the Help class, not of the Command help.\n// There is some overl"
  },
  {
    "path": "tests/help.longestOptionTermLength.test.js",
    "chars": 1206,
    "preview": "const commander = require('../');\n\n// These are tests of the Help class, not of the Command help.\n// There is some overl"
  },
  {
    "path": "tests/help.minWidthToWrap.test.js",
    "chars": 1500,
    "preview": "const commander = require('../');\n\ndescribe('Help.minWidthToWrap', () => {\n  test('when enough width then wrap', () => {"
  },
  {
    "path": "tests/help.optionDescription.test.js",
    "chars": 3773,
    "preview": "const commander = require('../');\n\n// These are tests of the Help class, not of the Command help.\n// There is some overl"
  },
  {
    "path": "tests/help.optionTerm.test.js",
    "chars": 1158,
    "preview": "const commander = require('../');\n\n// These are tests of the Help class, not of the Command help.\n// There is some overl"
  },
  {
    "path": "tests/help.padWidth.test.js",
    "chars": 1846,
    "preview": "const commander = require('../');\n\n// These are tests of the Help class, not of the Command help.\n// There is some overl"
  },
  {
    "path": "tests/help.preformatted.test.js",
    "chars": 2060,
    "preview": "const { Help, Command } = require('../');\n\ndescribe('preformatted', () => {\n  test('when single line then false', () => "
  },
  {
    "path": "tests/help.showGlobalOptions.test.js",
    "chars": 1754,
    "preview": "const commander = require('../');\n\ntest('when default configuration then global options hidden', () => {\n  const program"
  },
  {
    "path": "tests/help.sortCommands.test.js",
    "chars": 1139,
    "preview": "const commander = require('../');\n\n// These are tests of the Help class, not of the Command help.\n// There is some overl"
  },
  {
    "path": "tests/help.sortOptions.test.js",
    "chars": 3132,
    "preview": "const commander = require('../');\n\n// These are tests of the Help class, not of the Command help.\n// There is some overl"
  },
  {
    "path": "tests/help.stripAnsi.test.js",
    "chars": 1565,
    "preview": "const { stripColor } = require('../lib/help');\n\n// https://en.wikipedia.org/wiki/ANSI_escape_code#SGR_(Select_Graphic_Re"
  },
  {
    "path": "tests/help.style.test.js",
    "chars": 8446,
    "preview": "const { Command } = require('../');\n\nfunction red(str) {\n  // Use plain characters so not stripped in Jest failure messa"
  },
  {
    "path": "tests/help.subcommandDescription.test.js",
    "chars": 1401,
    "preview": "const commander = require('../');\n\n// These are tests of the Help class, not of the Command help.\n// There is some overl"
  },
  {
    "path": "tests/help.suggestion.test.js",
    "chars": 7899,
    "preview": "const { Command, Option } = require('../');\n\n// Note: setting up shared command configuration in getSuggestion,\n// and l"
  },
  {
    "path": "tests/help.visibleArguments.test.js",
    "chars": 2765,
    "preview": "const commander = require('../');\n\n// These are tests of the Help class, not of the Command help.\n// There is some overl"
  },
  {
    "path": "tests/help.visibleCommands.test.js",
    "chars": 1255,
    "preview": "const commander = require('../');\n\n// These are tests of the Help class, not of the Command help.\n// There is some overl"
  },
  {
    "path": "tests/help.visibleGlobalOptions.test.js",
    "chars": 1681,
    "preview": "const commander = require('../');\n\ntest('when default configuration then return empty array', () => {\n  const program = "
  },
  {
    "path": "tests/help.visibleOptions.test.js",
    "chars": 2865,
    "preview": "const commander = require('../');\n\n// These are tests of the Help class, not of the Command help.\n// There is some overl"
  },
  {
    "path": "tests/helpGroup.test.js",
    "chars": 9333,
    "preview": "const { Command, Option } = require('../');\n\n// Similar tests for Option.helpGroup() and Command.helpGroup(),\n// and for"
  },
  {
    "path": "tests/incrementNodeInspectorPort.test.js",
    "chars": 4660,
    "preview": "const childProcess = require('child_process');\nconst path = require('path');\nconst commander = require('../');\n\ndescribe"
  },
  {
    "path": "tests/negatives.test.js",
    "chars": 7713,
    "preview": "const { Command } = require('../');\n\n// boolean is whether is a consumable argument when negative numbers allowed\nconst "
  },
  {
    "path": "tests/option.bad-flags.test.js",
    "chars": 1256,
    "preview": "const { Option } = require('../');\n\n// Check that unsupported flags throw.\ntest.each([\n  { flags: '-a, -b' }, // too man"
  },
  {
    "path": "tests/option.chain.test.js",
    "chars": 1692,
    "preview": "const { Option } = require('../');\n\ndescribe('Option methods that should return this for chaining', () => {\n  test('when"
  },
  {
    "path": "tests/options.bool.combo.test.js",
    "chars": 5391,
    "preview": "const commander = require('../');\n\n// Test combination of flag and --no-flag\n// (single flags tested in options.bool.tes"
  },
  {
    "path": "tests/options.bool.small.combined.test.js",
    "chars": 391,
    "preview": "const commander = require('../');\n\ntest('when when multiple short flags specified then all values are true', () => {\n  c"
  },
  {
    "path": "tests/options.bool.test.js",
    "chars": 4804,
    "preview": "const commander = require('../');\n\n// Test simple flag and negatable flag\n\n// boolean flag on program\ndescribe('boolean "
  },
  {
    "path": "tests/options.camelcase.test.js",
    "chars": 1833,
    "preview": "const commander = require('../');\n\n// Capitalise the letters of words after dashes, but otherwise preserve case\n\ntest('w"
  },
  {
    "path": "tests/options.choices.test.js",
    "chars": 2099,
    "preview": "const commander = require('../');\n\ntest('when option argument in choices then option set', () => {\n  const program = new"
  },
  {
    "path": "tests/options.conflicts.test.js",
    "chars": 11196,
    "preview": "const path = require('path');\nconst commander = require('../');\n\ndescribe('command with conflicting options', () => {\n  "
  },
  {
    "path": "tests/options.custom-processing.test.js",
    "chars": 4944,
    "preview": "const commander = require('../');\n\nfunction myParseInt(value, dummyPrevious) {\n  // parseInt takes a string and a radix\n"
  },
  {
    "path": "tests/options.default.test.js",
    "chars": 8096,
    "preview": "const { Command, Option } = require('../');\n\ndescribe('.option() with default and option not specified in parse', () => "
  },
  {
    "path": "tests/options.dual-options.test.js",
    "chars": 3629,
    "preview": "const { Option, DualOptions } = require('../lib/option.js');\nconst { Command } = require('../');\n\n// This tests an inter"
  },
  {
    "path": "tests/options.env.test.js",
    "chars": 13192,
    "preview": "const commander = require('../');\n\n// treating optional same as required, treat as option taking value rather than as bo"
  },
  {
    "path": "tests/options.flags.test.js",
    "chars": 2754,
    "preview": "const commander = require('../');\n\n// Test the various ways flags can be specified in the first parameter to `.option`\n\n"
  },
  {
    "path": "tests/options.getset.test.js",
    "chars": 2653,
    "preview": "const commander = require('../');\n\ndescribe.each([true, false])(\n  'storeOptionsAsProperties is %s',\n  (storeOptionsAsPr"
  },
  {
    "path": "tests/options.implies.test.js",
    "chars": 7931,
    "preview": "const { Command, Option } = require('../');\n\ndescribe('check priorities', () => {\n  test('when source undefined and impl"
  },
  {
    "path": "tests/options.mandatory.test.js",
    "chars": 9003,
    "preview": "const commander = require('../');\n\n// Assuming mandatory options behave as normal options apart from the mandatory aspec"
  }
]

// ... and 19 more files (download for full content)

About this extraction

This page contains the full source code of the tj/commander.js GitHub repository, extracted and formatted as plain text for AI agents and large language models (LLMs). The extraction includes 219 files (829.3 KB), approximately 217.3k tokens, and a symbol index with 317 extracted functions, classes, methods, constants, and types. Use this with OpenClaw, Claude, ChatGPT, Cursor, Windsurf, or any other AI tool that accepts text input. You can copy the full output to your clipboard or download it as a .txt file.

Extracted by GitExtract — free GitHub repo to text converter for AI. Built by Nikandr Surkov.

Copied to clipboard!