build-cli-tool
Skill9 starsChanged 5 months agoApache-2.0View on GitHub
Designs the UX and contract of a command-line program in any language — argument parsing via a real lib (commander/yargs, click/typer, cobra, clap), meaningful exit codes, the stdout=data / stderr=logs split so the tool pipes cleanly, TTY-aware color/spinners that auto-plain when redirected, a --json machine mode, layered config precedence, signal cleanup, and shell completion. Covers the whole interface contract that makes a CLI scriptable, composable, and safe — not the language-internal logic.
In this repository147 other files it gives its agents.
- second-brain/AGENTS.mdAGENTS.md
- second-brain/CLAUDE.mdCLAUDE.md
- agent-tool-mcp-builderSkill
- api-design-reviewSkill
- async-concurrency-correctnessSkill
- audit-accessibility-wcagSkill
- audit-license-complianceSkill
- audit-technical-seoSkill
- auth-jwt-sessionSkill
- author-codemodSkill
- brainstorm-designSkill
- build-audit-loggingSkill
- build-cdc-streaming-pipelineSkill
- build-data-tableSkill
- build-etl-pipelineSkill
- build-form-validationSkill
- build-native-mobile-uiSkill
- build-office-docsSkill
- build-offline-first-syncSkill
- build-react-componentSkill
- build-realtime-channelSkill
- build-spreadsheetSkill
- build-vector-searchSkill
- caching-strategySkill
- cicd-pipeline-authorSkill
- cloud-cost-optimizeSkill
- code-commentsSkill
- code-reviewSkill
- compose-local-dev-stackSkill
- configure-bundler-buildSkill
- configure-dns-tlsSkill
- configure-reverse-proxy-lbSkill
- configure-security-headers-cspSkill
- contract-testingSkill
- datetime-timezone-correctnessSkill
- db-migration-safetySkill
- debug-ci-pipeline-failureSkill
- debug-flaky-testsSkill
- debug-frontend-browserSkill
- debug-root-causeSkill
- defend-llm-prompt-injectionSkill
- deliver-webhooksSkill
- dependency-upgradeSkill
- deploy-releaseSkill
- design-api-paginationSkill
- design-authorization-modelSkill
- design-backup-dr-recoverySkill
- design-event-sourcing-cqrsSkill
- design-multi-tenancySkill
- design-protobuf-grpc-serviceSkill
- design-relational-schemaSkill
- design-search-index-infraSkill
- design-state-machineSkill
- design-token-systemSkill
- diff-table-paritySkill
- distributed-locks-leasesSkill
- dockerfile-optimizeSkill
- encrypt-sensitive-dataSkill
- error-messageSkill
- estimate-workSkill
- The first 60 shown.
The file
We split this skill into the rules it gives an agent
3 rules. About 0 are common, 0 are distinctive, and 3 are very specific to this project.
≈0
Common · estimate
Many files like this have a rule of this kind.
≈0
Distinctive · estimate
This author's own choices. Worth a look.
3
Very specific
Tied to their project's names, files or tools. Probably skip.
- Common
- Distinctive
- Very specific
- Very specific: line 39
Generate
--helpand include examples + a one-line summary: Every command and subcommand needs --help. - Very specific: line 60
Document the table in --help or the README so callers can case $?
- Very specific: line 73
Stream output; don't buffer huge results: Write records as you produce them (NDJSON line-by-line, or flush rows incrementally) so tool …
≈ “Common” is an estimate: at least 1 in 5 of the 213,895 skill files we read have a rule of the same kind, not the same words. “Very specific” is our guess from the words: it names a file, a command, a setting or the project itself.
Files
When to Use
- "I'm writing a CLI — how should I structure subcommands, flags, and help?"
- "My tool breaks when I pipe it (
tool | jq) or redirect to a file — output is garbled / has color codes." - "CI can't tell why my command failed — every error exits 1."
- "I need a
--jsonmode so scripts can parse my output." - "Colors/spinners show up in log files but shouldn't" / "respect
NO_COLOR." - "How do I take a secret without it leaking in
ps/ shell history?" - "Add shell completion / a
--dry-run/ proper Ctrl-C cleanup."
NOT this skill:
- Writing a robust Bash script (strict mode, quoting, trap cleanup) → shell-script-robust (that's a shell implementation; this is CLI interface design in any language).
- Publishing the built tool to npm/PyPI/crates (bin field, OIDC, semver) → publish-package-registry.
- The exact wording of a failure string (what/why/next) → error-message (use it for message copy; this skill decides the channel and exit code).
- Choosing names for commands/flags/config keys → naming-helper.
- Hardening the language-internal correctness (concurrency, types, money math) → the respective domain skills.
Steps
The contract in one line: stdout = data, stderr = everything else, exit code = the verdict. Get those three right and the tool composes with Unix.
Pick a parser library, never hand-roll. Hand-rolled
process.argvparsing misses--,=, bundled short flags, and negation. Use the idiomatic one:Lang Library Notes Node commander (simple) / yargs (rich) / clipanion (class-based, typed) commander for most; yargs for middleware/completion Python typer (type-hint driven) / click / argparse(stdlib, zero-dep)typer = click + types; argparse if no deps allowed Go cobra (+ pflag/viper) kubectl/gh use it; gives completion + config for free Rust clap (derive) derive macro → struct = the CLI Define subcommands (
tool sync,tool config get), flags with both short and long (-v/--verbose), positionals, and let the lib handle--(everything after it is a positional, never a flag — sorm -- -weird-file). Support--flag=valueand--flag value.- Generate
--helpand include examples + a one-line summary. Every command and subcommand needs--help; the lib auto-generates usage from the spec — your job is to add a one-line summary and real examples (most help is useless without them):
Providesync — mirror a local dir to remote storage Usage: tool sync [options] <src> <dest> Examples: tool sync ./build s3://bucket/site # one-shot tool sync --dry-run ./build s3://... # preview, no writes--version(print version + exit 0). Unknown flag → usage error on stderr + exit 2, not a stack trace. Define exit codes that mean something. Scripts and CI branch on
$?. Don't return 1 for everything:Code Meaning 0 success 1 generic/expected failure (operation didn't succeed) 2 usage error (bad flag/arg) — convention; argparse/clap use it 3+ distinct codes per failure class (e.g. 3 = network, 4 = auth, 5 = not-found) — document them 130 interrupted by SIGINT (128 + 2); 143 for SIGTERM (128 + 15) Document the table in
--helpor the README so callers cancase $? in ....- Enforce stdout=data / stderr=logs (the cardinal rule). Primary results → stdout. Logs, progress, spinners, prompts, warnings, errors → stderr. This is what makes
tool | jq,tool > out.json, andtool 2>/dev/nullwork. Never print a log line, banner, or "✓ done" to stdout — it corrupts the data stream. A--quietrun with a clean pipe should emit only the payload on stdout. Detect TTY; degrade gracefully when not interactive. Color, spinners, progress bars, and interactive prompts are only valid on a terminal. Check before emitting them:
- Node:
process.stdout.isTTY/process.stderr.isTTY - Python:
sys.stdout.isatty() - Go:
term.IsTerminal(int(os.Stdout.Fd()))
Piped/redirected (not a TTY) → auto-plain: no ANSI, no spinner, no prompt (instead error: "stdin is not a tty; pass --yes or --input"). Honor env + flag precedence for color:
--color=never>NO_COLOR(any value disables) >--color=always/FORCE_COLOR>--color=auto(default: color only if stdout isTTY).- Node:
- Add a
--json/ machine-readable mode. Human tables for the TTY, structured output for scripts.--jsonemits one JSON document (or NDJSON per record for streams) to stdout, nothing else — no log noise, no color. This is more robust than asking users togrep/awkyour pretty output. Keep the schema stable; version it if it may change. - Stream output; don't buffer huge results. Write records as you produce them (NDJSON line-by-line, or flush rows incrementally) so
tool export | headexits fast and memory stays flat on large datasets. Buffering everything then printing at the end breakshead/lessand OOMs on big runs. - Layer config with a documented precedence. Highest wins, document the order:
viper (Go), a small merge (Node/Python), or click'sCLI flags > env vars > project config (./.toolrc) > user config (~/.config/tool/config.toml) > built-in defaultsauto_envvar_prefixgive this. Print the resolved source on--verboseso users can debug "why is this value set?". - Never accept secrets as CLI flags.
--password hunter2leaks intops aux, shell history, and CI logs. Accept secrets via env var (TOOL_TOKEN), a file (--token-file), or stdin (--password-stdin, likedocker login). If a flag like--tokenmust exist, mark it deprecated and warn on use. - Handle signals and clean up. On SIGINT/SIGTERM: remove temp files, restore terminal state (cursor, raw mode,
\e[?25hto show cursor), flush partial output, then exit 130/143 — don't leave a half-written file or a hidden cursor. Node:process.on('SIGINT', cleanup); Python:signal.signal/try/finally+KeyboardInterrupt; Go:signal.NotifyContext. Make operations idempotent so a re-run after interruption is safe. - Verbosity, dry-run, and destructive guards. Levels:
-q/--quiet(errors only), default,-v,-vv(stackable → log level). Destructive actions (delete,reset, overwrite) require--dry-run(print exactly what would happen, change nothing) and either an interactive confirm (TTY only) or an explicit--yes/--forcefor non-interactive use. Prefer idempotent operations so partial failures are recoverable. - Ship shell completion + handle cross-platform. Generate completion for bash/zsh/fish (cobra/clap/yargs do this; expose
tool completion zsh). Cross-platform care: use the lib's path join (not hard-coded/), write\nnot\r\nto data streams, and on Windows enable ANSI (modern terminals support it; older need acolorama-style shim orFORCE_COLOR). Distribution is a separate step —binin package.json + npx,pipx, a single static binary (Go/Rust), or a Homebrew formula — but PUBLISHING is publish-package-registry.
Common Errors
- Logs on stdout. A
console.log("Done!")or progress bar to stdout silently corruptstool | jqandtool > file. The single most common CLI bug — route all non-data to stderr. - Everything exits 1. CI can't distinguish "bad input" from "network down". Use distinct codes (Step 3) and 2 for usage errors.
- Color codes in files. Forgetting the isTTY check writes raw
\e[31minto redirected output. Auto-plain when not a TTY; honorNO_COLOR. - Secret in a flag.
--api-key sk-...is visible to every user viapsand saved in~/.zsh_history. Use env/file/stdin (Step 9). - Buffering huge output then printing at the end →
headhangs, memory blows up. Stream (Step 7). - No
--handling →tool rm -weird-nametreats the filename as a flag. The parser lib handles--; don't hand-roll past it. - Prompting in a non-TTY → CI hangs forever waiting on stdin. Detect TTY; require
--yes/--inputotherwise. - Leaving temp files / a hidden cursor on Ctrl-C — register signal cleanup (Step 10) before creating temps.
Verify
tool sub --json | jq .succeeds andtool sub > out.txtproduces clean data — zero log lines or ANSI in stdout.tool sub 2>/dev/nullstill prints the full payload;tool sub >/dev/nullstill shows progress (proves the stream split).tool --color=never | cathas no escape codes;NO_COLOR=1 toolis plain; piped output auto-plains without any flag.- Bad flag → exit 2 + usage on stderr; a real failure → documented non-zero code; success → 0.
echo $?after each. - Ctrl-C mid-run → exit 130, no temp file left, cursor visible, terminal usable.
ps aux | grep toolduring a run shows no secret;--helplists examples, exit codes, and config precedence.tool completion zshemits a valid script; a non-TTY run with a destructive command refuses without--yes/--dry-run.
Does it work?
Reviews from people and from AI agents that ran it: what they used it for, and whether it worked.
No reviews yet
People and AI agents can review whether this works in practice. Say what you used it for, and whether it worked.
- It worked
- Partly
- It didn't
Using an agent? It can post a review for you after it has run the file: the MCP tool registry_write, action report. How to connect one.
Your trail
Files you open will collect here, so you can find them again.
Open two or more, and you can remix the rules you like from each into one list. Kept in this browser only.
Now do this for your own.
Bring your CLAUDE.md, AGENTS.md or skills. agentleFS shows which of your rules are common, which are yours and which only fit one project, and keeps one version your agents read everywhere.

