Commander Git-Style Subcommand CLI
Build a git-style CLI with Commander using nested subcommands, variadic arguments, option conflict rules, and typed hook-driven configuration.
Code
import { Command } from 'commander';
const program = new Command();
program.name('deployctl').description('deployment control tool').version('2.1.0');
program
.command('deploy <env>')
.description('deploy current build to target environment')
.option('-r, --release <version>', 'pin a specific release version')
.option('--dry-run', 'print plan without executing')
.option('-f, --force', 'skip confirmation prompts')
.addOption(
new program.Option('-q, --quiet', 'suppress output').conflicts('force'),
)
.action(async (env, options) => {
const plan = { env, release: options.release ?? 'latest', force: options.force };
console.log('deploying', JSON.stringify(plan));
});
program
.command('rollback <env> [revisions...]')
.description('roll back one or more revisions')
.action((env, revisions) => {
console.log('rolling back', env, revisions.length, 'revision(s)');
});
program.parseAsync(process.argv);What the code does
await marks each async boundary — nothing fires and forgets. The import line is the dependency contract: Command comes from commander and nothing else.
The file’s state is a handful of top-level bindings: program.
Watch out for
- Dependency check:
commander— not built-in, must be present in the project.
Applying it
The demo output is labeled (deploying, rolling back), so every printed line maps back to its originating operation.
Statements that matter
const plan = { env, release: options.release ?? 'latest', force: options.force };
.action((env, revisions) => {
console.log('rolling back', env, revisions.length, 'revision(s)');
});
Interactive Tools for This Topic
Git Conventional Commit BuilderBuild and validate Conventional Commits v1.0.0 messages with type, scope, breaking markers, 72-char subject counter, body, footers, and git CLI command.Gitignore Template BuilderCompose clean .gitignore files by combining Node, Python, Go, Rust, Java, OS, IDE, and Docker presets with deduplication and custom rules.Glob Pattern TesterCompile glob patterns with *, **, ?, character classes, and braces into regex and test them against a list of candidate file paths.Tar Archive Command BuilderBuild safe tar create, extract, and list commands for gzip, xz, zstd, and bzip2 archives with excludes, target directory (-C), and flag explanations.
FAQ
- Do I need to install anything before running this?
- Yes: `commander` must be present in the project or the import fails at load time.
Report a problem with this exampleOpens a pre-filled issue on GitHub.