cobra
Build, extend, debug, and test Go command-line interfaces with spf13/cobra and pflag: command trees and subcommands, flags, argument validation, hooks, shell completion, generated docs, context cancellation, and stdout, stderr, and exit code contracts, including a CLI that sits beside a TUI. Use when writing or changing a Go CLI that uses Cobra, adding a subcommand or flag, or debugging flag inheritance, hook order, completion, or output that lands on the wrong stream. Not for layered file, environment, and flag configuration (use the viper skill) or for CLIs in other languages.
tpscloud · 已有静态检查记录
安装与使用
运行命令前先阅读来源与依赖说明。复制命令不会自动安装或执行。
npx skills add tpscloud/gophers --skill cobra技能说明
name: cobra description: "Build, extend, debug, and test Go command-line interfaces with spf13/cobra and pflag: command trees and subcommands, flags, argument validation, hooks, shell completion, generated docs, context cancellation, and stdout, stderr, and exit code contracts, including a CLI that sits beside a TUI. Use when writing or changing a Go CLI that uses Cobra, adding a subcommand or flag, or debugging flag inheritance, hook order, completion, or output that lands on the wrong stream. Not for layered file, environment, and flag configuration (use the viper skill) or for CLIs in other languages." license: "MIT"
Cobra
Build Go command-line programs with Cobra so they stay testable and predictable: fresh command trees, thin handlers over shared operations, explicit argument validation, payloads on stdout, diagnostics on stderr, and one place that reports errors. The pitfalls below are the lifecycle and flag behaviors that cause real bugs.
Workflow
- Read the project's
go.mod. Use only APIs available in its Cobra version; do not upgrade a dependency just to match this skill. Write Go for the version in itsgodirective (if a modern-Go guidelines skill such asuse-modern-gois installed, follow it for that version). - Keep an existing working CLI. Migrate to or from Cobra only when asked or when the task needs it.
- Build or change the command tree following Implementation choices. For a new command, start from the constructor and test pattern in references/commands.md.
- Check the change against Flags and lifecycle pitfalls.
- Before finishing, run the checks in Verify behavior.
Implementation choices
A new command starts from a constructor that takes its services and returns a fresh tree:
// examples/cobra/cli/cli.go (trimmed: text output, empty results, and completion omitted)
func NewRoot(list List, tags Tags) *cobra.Command {
root := &cobra.Command{
Use: "catalog",
SilenceErrors: true, // the process boundary owns error reporting
SilenceUsage: true, // explicit --help still works
}
var tag string
ls := &cobra.Command{
Use: "list",
Args: cobra.NoArgs,
RunE: func(cmd *cobra.Command, _ []string) error {
names, err := list(cmd.Context(), tag)
if err != nil {
return err
}
return json.NewEncoder(cmd.OutOrStdout()).Encode(names)
},
}
ls.Flags().StringVar(&tag, "tag", "", "Filter by tag")
root.AddCommand(ls)
return root
}
A test builds its own tree, sets SetArgs, SetOut, and SetErr, runs
ExecuteContext(t.Context()), and asserts on the captured buffers. The full
version, with text output, completion, and tests, is in
references/commands.md.
- Construct fresh command trees with
NewRoot(...) *cobra.Command(or an error-returning constructor if setup can fail). Inject services and writers; avoid package-level commands, mutable options, and registration ininit(). Fresh instances prevent flags and tests from leaking state between executions. - Keep handlers thin. A CLI and a TUI over the same program should call the same core operations.
- Put operations in
RunE, with explicitArgsvalidation (NoArgs,ExactArgs,MinimumNArgs, etc.). WithoutArgs, a leaf command accepts arbitrary arguments, and a nested command group that has noRunEprints help forapp group typoand exits 0. A script cannot tell that from success. - Use
Flags()for a command's own options andPersistentFlags()for options genuinely shared by descendants. Parent local flags are not inherited. - Use
ExecuteContext(ctx)and passcmd.Context()into core operations. Define signal handling and exit codes at the process boundary. Cobra does not choose your cancellation or partial-failure exit codes. - Write payloads through
cmd.OutOrStdout()and diagnostics throughcmd.ErrOrStderr(). Keep JSON output free of progress, styling, and prose. Do not usecmd.Print*for payloads: it writes to theSetOutwriter when one is set and otherwise to the process's stderr, so a test that callsSetOutpasses while the real binary sends the payload to stderr. - Assign error printing to one layer. If the caller prints errors, set
SilenceErrors: true; useSilenceUsagedeliberately so runtime failures do not emit a help page. Still return the error. Do notos.Exit,log.Fatal, orcobra.CheckErrinside reusable commands. - Create dependencies only when the operation needs them.
--help,--version, and completion should not require a valid config, network login, or a writable state database merely because the command tree was constructed.
Flags and lifecycle pitfalls
- Required flags and flag groups concern flags explicitly supplied by the user
(
Changed), not whether an effective value is nonzero. If config or env can satisfy a required setting, validate the resolved setting instead. - Distinguish
--enabled=falsefrom an omitted flag usingChanged. PreferStringArrayfor repeated literal values,StringSlicefor CSV/repeated values, andCountfor-v,-vv, etc. - Check errors from flag marking and completion registration. Group helpers such
as
MarkFlagsMutuallyExclusivecan panic when given an undefined flag name; register flags first. - Persistent hooks are nearest ancestor wins by default, including hooks on the command itself. A child's persistent hook can bypass root configuration loading. Prefer explicit shared setup over surprising hook inheritance.
- A root
PersistentPreRunEis skipped for--helpand--version, but it runs forcompletion <shell>, every__completerequest, andhelp <command>. If it loads config and fails, tab completion breaks wherever the config file is missing or invalid. Load config inside the operation that needs it, or return