parse-my-command
v0.3.31
Published
Parse argv with Commander.js without executing the command
Downloads
232
Maintainers
Readme
Parse My Command
Parse argv
with Commander.js without executing the command
Commander.js doesn't support parsing
argv
without executing the command. This module provides a workaround for that.
Installation
npm install --save parse-my-command
Usage
import { Command } from "commander";
import { partialParse } from "parse-my-command";
const rootCommand = new Command("root")
.requiredOption("-a, --option-a <value>", "option a")
.action(() => {
throw new Error("This should never get called");
});
const childCommand = rootCommand
.command("child")
.requiredOption("-b, --option-b <value>", "option b")
.requiredOption("-c, --option-c <value>", "option c")
.action(() => {
throw new Error("This should never get called");
});
const argv = ["node", "index.mjs", "-a", "value1", "child", "-b", "value2"];
const {
matchedCommand,
providedOptions,
missingOptions,
providedOptionsSources,
} = partialParse(rootCommand, argv);
console.log(matchedCommand.name()); // child
console.log(providedOptions.get(childCommand)); // { optionB: 'value2' }
console.log(missingOptions.get(childCommand)); // Set(1) { 'optionC' }
console.log(providedOptionsSources.get(childCommand)); // Map(1) { 'optionB' => 'cli' }
More examples can be found in the examples directory.
Error Handling
partialParse
throws in the following cases:
- In all cases where your
Command
with the defaultexitCallback
would throw an error (e.g. when displaying help) - In all cases where your command would throw an error before an action is
executed except for when a required
Option
(not to be confused with anArgument
) is missing (missing options are returned in the result object instead).
How It Works and Limitations
This module works by creating a (best-effort) clone of the command and its
subcommands, setting the actions to no-op functions, and then parsing the
argv
with the cloned instance. This approach might have some limitations:
- The implementation might break if Commander.js changes its internals
- Custom argument and option processors are assumed to be pure functions
- Hook listeners attached to the commands will be ignored
- Some edge cases might not be handled correctly (please feel free to open an issue/PR in case you find any)