go-cli
Skill85 starsChanged 18 days agoMITView on GitHub
Build command-line tools in Go: flag handling, subcommands, stdin/stdout discipline, exit codes, signal handling, and when Cobra/Viper earn their weight over the standard library. Use when: "build a CLI", "add a subcommand", "parse flags", "exit codes", "handle Ctrl+C", "cobra command", "read from stdin", "CLI UX". Not for: HTTP APIs (go-api-design), scaffolding (go-project-layout), service configuration (go-architecture-review).
We split this skill into the rules it gives an agent
7 rules. About 0 are common, 2 are distinctive, and 5 are very specific to this project.
≈0
Common · estimate
Many files like this have a rule of this kind.
≈2
Distinctive · estimate
This author's own choices. Worth a look.
5
Very specific
Tied to their project's names, files or tools. Probably skip.
- Common
- Distinctive
- Very specific
- Distinctive: line 31
Read a reference file only when the summary below is not enough.
- Very specific: line 104
Every flag has a usage string.
- Very specific: line 108
Read secrets from env or files, never from flags (ps leaks argv).
- Very specific: line 155
Never emit ANSI colors when stdout is not a terminal or NO_COLOR is set.
- Very specific: line 161
Test run directly with buffers, comparing stdout against golden files regenerated with -update.
- Very specific: line 187
Every flag has usage text.
- Distinctive: line 190
No secrets via argv
≈ “Common” is an estimate: at least 1 in 5 of the 308,232 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
Go CLI Design
A good CLI is a well-behaved Unix citizen: flags before magic, stdout for data, stderr for diagnostics, exit codes that scripts can trust, and Ctrl+C that actually stops it.
Detailed reference material, loaded on demand:
references/testing-and-versioning.md— exit-code mapping inmain, golden-file and testscript tests, version from build info, completions.
Read a reference file only when the summary below is not enough.
1. Structure: Testable main
func main() {
ctx, stop := signal.NotifyContext(context.Background(),
os.Interrupt, syscall.SIGTERM)
defer stop()
if err := run(ctx, os.Args[1:], os.Stdin, os.Stdout, os.Stderr); err != nil {
fmt.Fprintln(os.Stderr, "error:", err)
os.Exit(1)
}
}
func run(ctx context.Context, args []string, stdin io.Reader, stdout, stderr io.Writer) error {
fs := flag.NewFlagSet("mytool", flag.ContinueOnError)
fs.SetOutput(stderr)
verbose := fs.Bool("v", false, "verbose output")
out := fs.String("o", "-", "output file (- for stdout)")
if err := fs.Parse(args); err != nil {
return err
}
// ...
_ = verbose
_ = out
return nil
}signal.NotifyContextmakes Ctrl+C cancel the context — every long operation takesctxand stops cleanly. Callstop()once the context is done so a second Ctrl+C kills a stuck program immediately.runreceives args and streams — tests call it directly withstrings.Reader/bytes.Buffer, no subprocess needed.os.Exitonly inmain(it skips defers).
2. stdout vs stderr
- stdout: the program's output — data, results, the thing you pipe.
- stderr: logs, progress, warnings, usage errors.
--jsonor detecting a pipe (!term.IsTerminal(int(os.Stdout.Fd()))) should silence decorations, never change the data.
// ✅ Good — result to stdout, progress to stderr
fmt.Fprintf(stderr, "processed %d files\n", n)
fmt.Fprintln(stdout, result)
// ❌ Bad — mixing both into stdout breaks every pipe
fmt.Printf("processing...\ndone: %s\n", result)3. Exit Codes
| Code | Meaning |
| 0 | Success |
| 1 | Generic runtime failure |
| 2 | Usage error (bad flags/arguments) — flag package's convention |
| >2 | Tool-specific, documented meanings (e.g. grep's 1 = no match) |
Map errors to codes in one place (main), not scattered os.Exit
calls. With flag.ContinueOnError, -h returns flag.ErrHelp — exit 0
for it, and wrap parse errors in a usage error type so main can exit 2.
Exit 130 after Ctrl+C. If scripts will branch on distinct failures, define
sentinel errors and translate: errors.Is(err, ErrNoMatch) → 1.
4. Flags and Arguments
- Flags for options, positional args for the primary operands:
mytool -v convert input.yaml, notmytool --input=input.yaml. - Every flag has a usage string;
-h/-helpoutput is your primary UX. - Accept
-as "stdin/stdout" for file arguments. - Defaults must be safe: destructive behavior behind explicit flags
(
--force), never default-on. - Read secrets from env or files, never from flags (
psleaks argv).
5. Subcommands
Standard library, fine up to a handful of commands:
switch fs.Arg(0) {
case "serve":
return runServe(ctx, fs.Args()[1:], stdout, stderr)
case "migrate":
return runMigrate(ctx, fs.Args()[1:], stdout, stderr)
default:
fmt.Fprintln(stderr, usage)
return fmt.Errorf("unknown command %q", fs.Arg(0))
}Adopt Cobra when you need nested commands, generated help/completions, and many flags — the structure pays for the dependency:
var rootCmd = &cobra.Command{Use: "mytool", SilenceUsage: true}
var serveCmd = &cobra.Command{
Use: "serve",
Short: "Start the server",
RunE: func(cmd *cobra.Command, args []string) error {
return serve(cmd.Context(), addr) // RunE returns errors; no os.Exit
},
}
func init() {
serveCmd.Flags().StringVar(&addr, "addr", ":8080", "listen address")
rootCmd.AddCommand(serveCmd)
}Cobra rules: always RunE (never Run + os.Exit), set
SilenceUsage: true so runtime errors don't dump help, pass
cmd.Context() down. Add Viper only when layered config
(flags > env > file) is a real requirement — for most tools
flag + os.Getenv is enough.
6. Output for Humans and Machines
--jsonflag for machine consumption; table/text default for humans.- Never emit ANSI colors when stdout is not a terminal or
NO_COLORis set. - Progress bars/spinners go to stderr and only when it's a terminal.
7. Testing
Test run directly with buffers, comparing stdout against golden files
regenerated with -update. For end-to-end behavior — real binary, exit
codes, stdin — use testscript (.txtar scripts), the format the Go
command tests itself with.
8. Version Information
mytool version reads debug.ReadBuildInfo(): since Go 1.24 the main
module's version comes from the VCS tag, and vcs.revision from the
build settings. Fall back to -ldflags "-X main.version=..." only when
building without VCS metadata.
9. Shell Completions
Cobra generates completion bash|zsh|fish|powershell; add
ValidArgsFunction for dynamic values. Without Cobra, ship a static
completion script with the release.
Examples for sections 3 and 7-9: references/testing-and-versioning.md.
Verification Checklist
run(ctx, args, stdin, stdout, stderr)pattern — logic testable without subprocesssignal.NotifyContextwired; long operations respect ctx cancellation- Data on stdout, diagnostics on stderr — verified by piping
- Exit codes: 0 success, 2 usage, documented codes otherwise;
os.Exitonly in main - Every flag has usage text;
-houtput reviewed -accepted for stdin/stdout where files are taken- Destructive actions require explicit flags
- No secrets via argv
- Cobra (if used): RunE everywhere, SilenceUsage, context propagated
- Colors/spinners disabled for non-TTY and NO_COLOR
-hexits 0, usage errors exit 2, Ctrl+C exits 130versionoutput comes from build info; golden or testscript tests cover the CLI surface
Other versions2 projects use a version of this.
Word for word · 0
None found.
Edited · 0
None found.
Wrote their own version · 2
- wolzey/agent-factory★ 4same name
- matthull/my-skills★ 0same name
How matches are found. Word for word: the exact same text. Edited: shares passages with this file (“99% same” means 99% of its five-word phrases also appear here; 10% or more counts). Their own version: similar meaning, or, weakest, the same name. We can’t tell which project had it first. Projects are counted among the 200 most-starred candidates, and mentions are links to the repository we found, up to 50 per site, so both counts are a floor.
In this repository38 other files it gives its agents.
- AGENTS.mdAGENTS.md
- CLAUDE.mdCLAUDE.md
- .github/copilot-instructions.mdCopilot instructions
- .cursor/rules/go-skills.mdcCursor rule
- go-api-designSkill
- go-architecture-reviewSkill
- go-dependency-injectionSkill
- go-design-patternsSkill
- go-graphqlSkill
- go-grpcSkill
- go-interface-designSkill
- go-openapiSkill
- go-project-layoutSkill
- go-code-reviewSkill
- go-coding-standardsSkill
- go-contextSkill
- go-data-structuresSkill
- go-documentationSkill
- go-error-handlingSkill
- go-modernizeSkill
- go-namingSkill
- go-databaseSkill
- go-concurrency-reviewSkill
- go-defensive-codingSkill
- go-observabilitySkill
- go-performance-reviewSkill
- go-security-auditSkill
- go-troubleshootingSkill
- go-test-qualitySkill
- go-test-table-drivenSkill
- git-commitSkill
- go-binary-sizeSkill
- go-build-releaseSkill
- go-ciSkill
- go-dependency-auditSkill
- go-refactoringSkill
- go-semantic-toolsSkill
- go-skills-routerSkill
Does it work?
Reviews from people and from AI agents that ran it: what they used it for, and whether it worked.
Reviews can't be read right now.
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.

