Tutorial

Building CLI Tools with Great Developer Experience

Build command-line tools developers love: robust argument parsing, generated help text, sensible defaults, shell completion, and graceful errors.

On this page

  1. Introduction
  2. Argument Parsing and the Command Structure
  3. Help Text That Answers Questions
  4. Sensible Defaults and the Zero-Flag Ideal
  5. Graceful Errors and Exit Codes
  6. Shell Completion
  7. Configuration, Output, and Respect for the Terminal
  8. Configuration Files, Precedence, and Plugin Extensibility
  9. Auto-Completion and the Shell Integration
  10. Conclusion

Introduction

A command-line tool is an API, and like any API its quality is measured by how little the user has to think. A great CLI has sensible defaults so the common case needs no flags, help text that is complete enough to answer questions without a man page, errors that point at the fix rather than the stack trace, and tab completion that rewards exploration. A bad CLI has positional arguments in an order nobody can remember, flags that silently override each other, and a --help that prints the author’s name and nothing else. This article builds a CLI with great developer experience in Node.js with Commander, but the principles — discoverability, defaults, errors, completion — apply to Cobra in Go, Click in Python, and Clap in Rust.

Argument Parsing and the Command Structure

The shape of a CLI is a tree of commands and subcommands, each with its own flags and positional arguments. mytool deploy --env production --dry-run is a deploy command with an --env flag and a --dry-run switch. Modeling this as a tree rather than a flat flag soup keeps the interface learnable: --help on the root lists the commands, --help on a command lists its flags. Commander (and its analogues) builds this tree declaratively.

import { Command, Argument, Option } from "commander";

const program = new Command()
  .name("mytool")
  .description("Deploy and manage services")
  .version("1.4.0");

program
  .command("deploy")
  .description("Deploy a service to an environment")
  .addArgument(new Argument("<service>").argChoices(["api", "web", "worker"]))
  .addOption(new Option("-e, --env <environment>", "target environment").choices(["staging", "production"]).makeOptionMandatory(true))
  .addOption(new Option("--dry-run", "print the plan without deploying").default(false))
  .addOption(new Option("--image <tag>", "image tag; defaults to latest git sha"))
  .action(async (service, opts) => {
    const tag = opts.image ?? (await gitSha());
    console.log(`Deploying ${service}:${tag} to ${opts.env}${opts.dryRun ? " (dry run)" : ""}`);
  });

program.parseAsync(process.argv);

Three choices here are deliberate. The service is a positional argument because it is the primary noun of the command — mytool deploy api reads better than mytool deploy --service api. It is constrained with argChoices so a typo (mytool deploy apl) fails with “did you mean api?” rather than deploying nothing. The environment is a mandatory flag with a constrained set of choices, so omitting it or typing an unknown value is caught before the action runs. The image tag is optional with a computed default, so the common case (deploy the current commit) needs no flag.

Help Text That Answers Questions

The --help output is the tool’s documentation at the point of need. Commander generates it from the descriptions you provide, which means the quality of your descriptions is the quality of your help. Write descriptions as imperative sentences (“Deploy a service to an environment”, not “This command deploys…”). Document every flag, including the default value and the accepted choices. For flags that take a value, name the value in the description (--env <environment>) so the user knows what kind of argument to pass.

program
  .command("logs")
  .description("Stream logs for a service (Ctrl-C to stop)")
  .argument("<service>", "service name")
  .option("-f, --follow", "follow new log lines", true)
  .option("--since <duration>", "show logs since a duration (e.g. 30m, 2h)", "15m")
  .option("--level <level>", "minimum level to show", "info")
  .action(streamLogs);

When the generated help is not enough, add a long description or examples in the command’s description using a multi-line string. Examples are the single most useful part of CLI documentation — a user who reads mytool deploy api --env production --dry-run in the help understands the command in a glance.

Sensible Defaults and the Zero-Flag Ideal

The best CLI requires zero flags for the most common task. git status with no arguments does the useful thing; npm install with no arguments installs the dependencies. Every flag you make mandatory is a flag the user must learn before they can use the tool. Make a flag mandatory only when there is no safe default — the target environment for a deploy has no safe default, so it is mandatory; the log level has a safe default, so it is optional. When a flag’s default is computed (the image tag defaults to the current git sha), compute it lazily in the action so --help does not trigger the computation.

Graceful Errors and Exit Codes

A CLI error should tell the user what went wrong and what to do about it, in that order, and then exit with a non-zero code. A stack trace is for the developer of the tool, not the user of it. Catch expected errors (invalid config, missing dependency, network failure) and print a short, human message; let unexpected errors propagate to a top-level handler that prints the message and, if a --debug flag is set, the stack.

program.exitOverride(); // throw instead of process.exit, so we can catch

try {
  await program.parseAsync(process.argv);
} catch (err: any) {
  if (err.code === "commander.helpDisplayed" || err.code === "commander.version") {
    process.exit(0);
  }
  if (err.code === "commander.invalidArgument" || err.code === "commander.invalidOptionArgument") {
    console.error(`error: ${err.message}`);
    console.error(`run '${program.name()} ${err.command?.name() ?? ""} --help' for usage`);
    process.exit(2); // 2: usage error (distinct from 1: runtime error)
  }
  console.error(`error: ${err.message ?? err}`);
  if (process.argv.includes("--debug")) console.error(err.stack);
  process.exit(1);
}

Exit codes carry meaning in scripts: 0 is success, 1 is a runtime failure, 2 is a usage error. A CI pipeline that runs mytool deploy api --env production and fails because of a typo should exit 2 so the pipeline can distinguish “the deploy failed” from “the command was wrong.” Respect the convention and your tool composes correctly in shell scripts.

Shell Completion

Tab completion is the feature that turns a CLI from memorized into discoverable. With completion installed, the user types mytool dep<Tab> and gets deploy; types mytool deploy <Tab> and gets the list of services; types mytool deploy api --env <Tab> and gets staging and production. Commander can generate completion scripts for bash, zsh, and fish; the completion script calls the tool itself with a hidden --completion flag to enumerate the valid next tokens.

// Generate and print the completion script for the user's shell.
program
  .command("completion")
  .description("Print a shell completion script (source it in your shell rc)")
  .argument("<shell>", "shell name", ["bash", "zsh", "fish"])
  .action((shell) => {
    console.log(generateCompletion(program, shell));
    console.error(`\n# Install with: source <(mytool completion ${shell})`);
  });

Ship a completion command that prints the script and a one-line install instruction, so the user does not have to find the script in your documentation. The completion should reflect the constrained choices you defined — argChoices and Option.choices flow through to the completion automatically in mature parsers, so the user never tab-completes an invalid value.

Configuration, Output, and Respect for the Terminal

A great CLI respects the terminal it runs in. Detect whether stdout is a TTY and disable color and progress spinners when it is not, so piping mytool logs api | grep ERROR does not litter the pipe with ANSI codes. Use a structured logger that writes JSON to stderr when a --json flag is set, so the tool composes with jq. Respect the NO_COLOR environment variable. Write progress to stderr and results to stdout, so mytool deploy api > deploy.log captures the result without the progress noise. These are small choices, but they are the difference between a tool that feels professional and one that fights the shell.

Configuration Files, Precedence, and Plugin Extensibility

A CLI that requires every option on the command line is a CLI that is tedious to use repeatedly. Configuration files let the user declare their defaults once and override them on the command line for one-off cases. The pattern is a layered configuration with explicit precedence: command-line flags override the config file, the config file overrides environment variables, and environment variables override built-in defaults. The tool loads the config file (a .mytoolrc.json in the project, a .mytoolrc in the home directory, or a [tool] table in package.json), merges it with the flags, and passes the result to the command. This is how ESLint, Prettier, and tsconfig work, and it is the pattern users expect.

import { cosmiconfig } from "cosmiconfig";

async function loadConfig(explicitPath?: string) {
  const explorer = cosmiconfig("mytool", { searchPlaces: [".mytoolrc", ".mytoolrc.json", "package.json"] });
  const found = explicitPath ? await explorer.load(explicitPath) : await explorer.search();
  return found?.config ?? {};
}

// Merge with precedence: defaults < env < config file < CLI flags.
function resolveConfig(fileConfig: object, cliFlags: object, env: NodeJS.ProcessEnv) {
  return deepMerge(defaults, fromEnv(env), fileConfig, cliFlags);
}

Document the config file’s schema and generate a JSON schema for editor autocomplete — a user who gets validation and completion in their editor writes a correct config file on the first try, and a user who does not reads the documentation twice and still gets it wrong. The cosmiconfig library handles the search across the conventional locations and the JSON/YAML/JS formats, so the tool supports whatever the user’s project already uses.

Plugin extensibility is what makes a CLI a platform. A tool that lets the user add commands or modify behavior through plugins — eslint’s rules, vite’s plugins, jest’s reporters — grows an ecosystem that does work the core team cannot. Define a plugin interface: a function that receives the tool’s context (the config, the logger, the event hooks) and returns an extension (a new command, a transform, a hook registration). Load plugins from node_modules by name, from a local path, or from a config file list, and guard each plugin so an error in one does not crash the tool.

interface Plugin {
  name: string;
  setup(ctx: PluginContext): void | (() => void); // setup returns an optional teardown
}
interface PluginContext {
  config: Config;
  logger: Logger;
  registerCommand: (cmd: Command) => void;
  beforeDeploy: (hook: () => Promise<void>) => void;
}

async function loadPlugins(names: string[], ctx: PluginContext): Promise<Plugin[]> {
  const teardowns: Array<() => void> = [];
  for (const name of names) {
    const mod = await import(name);
    const plugin: Plugin = mod.default ?? mod;
    try {
      const teardown = plugin.setup(ctx);
      if (teardown) teardowns.push(teardown);
    } catch (err) {
      ctx.logger.error({ plugin: name, err: toLoggable(err) }, "plugin failed to load; skipping");
    }
  }
  return teardowns;
}

The guard around plugin.setup is the detail that makes plugins safe: a plugin that throws on load is logged and skipped, not allowed to crash the tool. The teardown return lets a plugin clean up (close a connection, remove a hook) when the tool exits. Define the context carefully — expose the minimum the plugin needs, not the tool’s internals, so the interface is stable across versions and the plugin cannot reach into private state. A well-defined plugin interface is a contract the core team can evolve without breaking every plugin; a poorly defined one is a leaky abstraction that freezes the internals.

Auto-Completion and the Shell Integration

Auto-completion is the feature that makes a CLI feel native. A completion script, generated by the tool for the user’s shell (bash, zsh, fish), teaches the shell the tool’s commands, subcommands, flags, and even the dynamic values (the list of project names, the available templates). The user types mytool dep<tab> and the shell completes deploy; types mytool deploy --env <tab> and the shell offers staging and production. Generate the completion script with a mytool completions <shell> command and instruct the user to source it, or write it to the conventional location. The completion is generated from the same command definition the parser uses, so it cannot drift from the actual commands. For dynamic completions (the project list), the completion script calls back into the tool with a hidden flag that prints the candidates, so the completions are always current. This is the polish that separates a tool the user tolerates from a tool the user recommends.

Conclusion

A CLI with great developer experience is the product of many small disciplines: a command tree that mirrors the user’s mental model, generated help with imperative descriptions and examples, sensible defaults so the common case needs no flags, constrained choices that catch typos, errors that point at the fix and exit with meaningful codes, and tab completion that makes the interface discoverable. None of these is hard to implement; together they turn a script into a tool that developers reach for without reaching for the documentation. Build the tree, write the help, choose the defaults, and respect the terminal — the rest follows.

Related Examples