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.

JavascriptNodeCli Tooling

Code

javascriptsnippet
27 lines
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

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.