Receber por email
← Voltar para o catálogo

cli-design

Use this skill when building command-line interfaces, designing CLI argument parsers, writing help text, adding interactive prompts, managing config files, or distributing CLI tools. Triggers on argument parsing, subcommands, flags, positional arguments, stdin/stdout piping, shell completions, interactive menus, dotfile configuration, and packaging CLIs as npm/pip/cargo/go binaries.

185estrelas
Atualizado há 4 meses

Ver no GitHub ↗ Licença: MIT

Como adicionar

/plugin marketplace add AbsolutelySkilled/AbsolutelySkilled

O comando exato pode variar conforme o repositório. Confira o README no GitHub.

Para o autor da skill

Cole no README do seu repo

Mostra que sua skill está catalogada na Skillteca, gera backlink e tráfego rastreável.

[![Skillteca](https://www.skillteca.com.br/api/badge/cli-design-absolutelyskilled/svg)](https://www.skillteca.com.br/skills/cli-design-absolutelyskilled)

Alerta por categoria

Receba novas skills de Design e Frontend toda segunda

1 email curto, só com as skills novas de Design e Frontend. 4 minutos de leitura, sem spam, cancela com 1 clique.

Você confirma o email no primeiro envio. Sem spam. Cancela com 1 clique.

Ler descrição completa

When this skill is activated, always start your first response with the 🧢 emoji.

CLI Design

CLI design is the practice of building command-line tools that are intuitive, composable, and self-documenting. A well-designed CLI follows the principle of least surprise - flags behave like users expect, help text answers questions before they are asked, and errors guide toward resolution rather than dead ends. This skill covers argument parsing, help text conventions, interactive prompts, configuration file hierarchies, and distribution strategies across Node.js, Python, Go, and Rust ecosystems.

When to use this skill

Trigger this skill when the user:

  • Wants to build a new CLI tool or add subcommands to an existing one
  • Needs to parse arguments, flags, options, or positional parameters
  • Asks about help text formatting, usage strings, or man pages
  • Wants to add interactive prompts, confirmations, or selection menus
  • Needs to manage config files (dotfiles, rc files, XDG directories)
  • Asks about distributing a CLI via npm, pip, cargo, brew, or standalone binary
  • Wants to add shell completions (bash, zsh, fish)
  • Needs to handle stdin/stdout piping and exit codes correctly

Do NOT trigger this skill for:

  • GUI application design or web UI - use frontend or absolute-ui skills
  • Shell scripting syntax questions unrelated to building a distributable CLI tool

Key principles

  1. Predictability over cleverness - Follow POSIX conventions: single-dash

short flags (-v), double-dash long flags (--verbose), -- to end flag parsing. Users should never have to guess how your flags work.

  1. Self-documenting by default - Every command must have a --help that

shows usage, all flags with descriptions, and at least one example. If a user needs to read external docs to run a command, the help text has failed.

  1. Fail loudly, recover gracefully - Print errors to stderr, not stdout.

Use non-zero exit codes for failures. Include the failed input and a suggested fix in every error message. Never fail silently.

  1. Composability - Respect the Unix philosophy: accept stdin, produce

clean stdout, use stderr for diagnostics. Support --json or --output=json for machine-readable output so other tools can pipe it.

  1. Progressive disclosure - Show the simplest usage first. Hide advanced

flags behind --help subgroups or separate help <topic> commands. New users see 5 flags; power users discover 30.

Core concepts

Argument taxonomy

CLI arguments fall into four categories that every parser must handle:

| Type | Example | Notes | |------|---------|-------| | Subcommand | git commit | Verb that selects behavior | | Positional | cp source dest | Order-dependent, unnamed | | Flag (boolean) | --verbose, -v | Presence toggles a setting | | Option (valued) | --output file.txt, -o file.txt | Key-value pair |

Short flags can be combined: -abc equals -a -b -c. Options consume the next token or use =: --out=file or --out file.

Config hierarchy

CLIs should load configuration from multiple sources, with later sources overriding earlier ones:

1. Built-in defaults (hardcoded)
2. System config   (/etc/<tool>/config)
3. User config     (~/.config/<tool>/config or ~/.<tool>rc)
4. Project config  (./<tool>.config.json or ./<tool>rc)
5. Environment vars (TOOL_OPTION=value)
6. CLI flags       (--option value)

Exit codes

| Code | Meaning | |------|---------| | 0 | Success | | 1 | General error | | 2 | Misuse of command (bad flags, missing args) | | 126 | Command found but not executable | | 127 | Command not found | | 128+N | Killed by signal N (e.g. 130 = Ctrl+C / SIGINT) |

Common tasks

1. Parse arguments with Node.js (Commander.js)

Define commands declaratively and let Commander handle help generation.

import { Command } from 'commander';

const program = new Command();

program
  .name('mytool')
  .description('A CLI that does useful things')
  .version('1.0.0');

program
  .command('deploy')
  .description('Deploy the application to a target environment')
  .argument('<environment>', 'target environment (staging, production)')
  .option('-d, --dry-run', 'show what would happen without deploying')
  .option('-t, --tag <tag>', 'docker image tag to deploy', 'latest')
  .option('--timeout <ms>', 'deploy timeout in milliseconds', '30000')
  .action((environment, options) => {
    if (options.dryRun) {
      console.log(`Would deploy ${options.tag} to ${environment}`);
      return;
    }
    deploy(environment, options.tag, parseInt(options.timeout, 10));
  });

program.parse();

2. Parse arguments with Python (click)

Click uses decorators for commands and handles type conversion, help generation, and shell completions out of the box.

import click

@click.group()
@click.version_option("1.0.0")
def cli():
    """A CLI that does useful things."""
    pass

@cli.command()
@click.argument("environment", type=click.Choice(["staging", "production"]))
@click.option("--dry-run", "-d", is_flag=True, help="Show what would happen.")
@click.option("--tag", "-t", default="latest", help="Docker image tag.")
@click.option("--timeout", default=30000, type=int, help="Timeout in ms.")
def deploy(environment, dry_run, tag, timeout):
    """Deploy the application to a target environment."""
    if dry_run:
        click.echo(f"Would deploy {tag} to {environment}")
        return
    do_deploy(environment, tag, timeout)

if __name__ == "__main__":
    cli()

3. Add interactive prompts

Use prompts for destructive actions or first-time setup. Never force interactivity - always allow --yes / -y to skip prompts for scripting.

import { confirm, select, input } from '@inquirer/prompts';

async function interactiveSetup() {
  const name = await input({
    message: 'Project name:',
    default: 'my-project',
    validate: (v) => v.length > 0 || 'Name is required',
  });

  const template = await select({
    message: 'Choose a template:',
    choices: [
      { name: 'Minimal', value: 'minimal' },
      { name: 'Full-stack', value: 'fullstack' },
      { name: 'API only', value: 'api' },
    ],
  });

  const proceed = await confirm({
    message: `Create "${name}" with ${template} template?`,
    default: true,
  });

  if (!proceed) {
    console.log('Aborted.');
    process.exit(0);
  }
  return { name, template };
}
Always check process.stdout.isTTY before showing prompts. If the output
is piped or running in CI, fall back to defaults or error with a clear
message about which flags to pass.

4. Manage configuration files

Use cosmiconfig (Node.js) or similar to support multiple config formats.

import { cosmiconfig } from 'cosmiconfig';

const explorer = cosmiconfig('mytool', {
  searchPlaces: [
    'package.json',
    '.mytoolrc',
    '.mytoolrc.json',
    '.mytoolrc.yaml',
    'mytool.config.js',
    'mytool.config.ts',
  ],
});

async function loadConfig(flagOverrides: Record<string, unknown>) {
  const result = await explorer.search();
  const fileConfig = result?.config ?? {};

  // Merge: defaults < file config < env vars < flags
  return {
    output: 'dist',
    verbose: false,
    ...fileConfig,
    ...(process.env.MYTOOL_OUTPUT ? { output: process.env.MYTOOL_OUTPUT } : {}),
    ...flagOverrides,
  };
}

5. Write effective help text

Follow this template for every command's help output:

Usage: mytool deploy [options] <environment>

Deploy the application to a target environment.

Arguments:
  environment          target environment (staging, production)

Options:
  -d, --dry-run        show what would happen without deploying
  -t, --tag <tag>      docker image tag to deploy (default: "latest")
      --timeout <ms>   deploy timeout in milliseconds (default: "30000")
  -h, --help           display help for command

Examples:
  $ mytool deploy staging
  $ m
Compartilhar X LinkedIn