golang-spf13-cobra
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
ChinesePersona: You are a Go CLI engineer building command trees that feel native to the Unix shell. You design the user-facing surface first, then wire behavior into the right hook.
Modes:
- Build — creating a new CLI from scratch: follow command tree setup, hook wiring, and flag sections sequentially.
- Extend — adding subcommands, flags, or completions to an existing CLI: read the current command tree first, then apply changes consistent with the existing structure.
- Review — auditing an existing CLI: check the Common Mistakes table, verify usage,
RunE, hook chain ordering, and args validation.OutOrStdout()
角色定位: 你是一名Go CLI工程师,正在构建贴合Unix Shell原生体验的命令树。你先设计用户交互界面,再将行为关联到合适的钩子上。
模式:
- Build(构建)——从零创建新CLI:依次遵循命令树设置、钩子关联和标志配置流程。
- Extend(扩展)——为现有CLI添加子命令、标志或自动补全:先查看当前命令树,再根据现有结构进行一致性修改。
- Review(审查)——审计现有CLI:检查常见错误表格,验证使用方式、
RunE、钩子链顺序以及参数验证情况。OutOrStdout()
Using spf13/cobra for CLI command trees in Go
在Go中使用spf13/cobra构建CLI命令树
Cobra is the de facto standard for Go CLI applications. It provides the command/subcommand tree, flag parsing (via ), args validation, shell completion generation, and documentation generation. It does not handle configuration layering — that's viper's job.
pflagOfficial Resources:
This skill is not exhaustive. Please refer to library documentation and code examples for more information. Context7 can help as a discoverability platform.
bash
go get github.com/spf13/cobra@latestCobra是Go CLI应用的事实标准。它提供命令/子命令树、标志解析(基于)、参数验证、Shell自动补全生成以及文档生成功能。它不处理配置分层——这是viper的职责。
pflag官方资源:
本技能内容并非详尽无遗。如需更多信息,请参考库文档和代码示例。Context7可作为发现平台提供帮助。
bash
go get github.com/spf13/cobra@latestCobra vs. viper
Cobra与viper对比
These libraries do fundamentally different things and can be used independently.
| Concern | cobra | viper |
|---|---|---|
| Owns | Command tree, flags, arg validation, completions | Configuration value resolution |
| User-facing? | Yes — subcommands, flags, help text | No — purely a key-value resolver |
| Without the other? | Yes — a CLI with flags only needs cobra | Yes — a daemon reading YAML + env needs only viper |
| Integration seam | Hands | Treats the cobra flag as the highest-precedence layer |
Use cobra alone when your binary takes flags and args but needs no config file or env resolution. Use viper alone when you have a long-running service reading config from YAML + env with no CLI subcommands. Use both when you need both — bind at on the root command.
PersistentPreRunE→ See for the viper side of this integration.
samber/cc-skills-golang@golang-spf13-viper这两个库的核心功能完全不同,可独立使用。
| 关注点 | cobra | viper |
|---|---|---|
| 负责内容 | 命令树、标志、参数验证、自动补全 | 配置值解析 |
| 是否面向用户? | 是——子命令、标志、帮助文本 | 否——纯键值解析器 |
| 可独立使用吗? | 是——仅含标志的CLI只需cobra | 是——读取YAML+环境变量的守护进程只需viper |
| 集成方式 | 通过 | 将cobra标志视为最高优先级层级 |
单独使用cobra:当你的二进制文件仅接收标志和参数,无需配置文件或环境变量解析时。单独使用viper:当你有一个长期运行的服务,仅需从YAML+环境变量读取配置,无需CLI子命令时。当两者都需要时同时使用——在根命令的中进行绑定。
PersistentPreRunE→ 如需了解该集成的viper部分,请查看。
samber/cc-skills-golang@golang-spf13-viperCommand tree
命令树
Every cobra CLI has a root command plus zero or more subcommands registered with . The root command name is the binary name.
AddCommandgo
var rootCmd = &cobra.Command{
Use: "myapp",
Short: "One-line summary",
SilenceUsage: true, // ✓ prevents usage wall on every error
SilenceErrors: true, // ✓ lets you control error output format
}Use to label subcommands in help output — register groups before the calls that reference them; cobra does not retroactively assign groups.
AddGroupAddCommand每个cobra CLI都包含一个根命令,以及零个或多个通过注册的子命令。根命令名称即为二进制文件名称。
AddCommandgo
var rootCmd = &cobra.Command{
Use: "myapp",
Short: "One-line summary",
SilenceUsage: true, // ✓ 避免每次出错都显示大量使用说明
SilenceErrors: true, // ✓ 让你可以控制错误输出格式
}使用在帮助输出中为子命令添加分组标签——请在调用引用分组的之前先注册分组;cobra不会追溯分配分组。
AddGroupAddCommandThe Run* family
Run*系列钩子
Cobra commands have five run hooks executed in order:
PersistentPreRunE → PreRunE → RunE → PostRunE → PersistentPostRunEAlways use variants — the non- forms cannot return errors. Key rules:
*EE- on the root runs before every subcommand — use it for config init and auth checks.
PersistentPreRunE - A child replaces the parent's entirely — call the parent explicitly if you need both.
PersistentPreRunE - runs only if
PostRunEsucceeded.RunE
For the full lifecycle and inheritance rules, see commands-and-args.md.
Cobra命令有五个按顺序执行的运行钩子:
PersistentPreRunE → PreRunE → RunE → PostRunE → PersistentPostRunE始终使用变体——非形式无法返回错误。核心规则:
*EE- 根命令的会在每个子命令之前运行——可用于配置初始化和身份验证检查。
PersistentPreRunE - 子命令的会完全替换父命令的钩子——如果需要同时执行两者,请显式调用父命令的钩子。
PersistentPreRunE - 仅在
PostRunE执行成功后才会运行。RunE
如需了解完整生命周期和继承规则,请查看commands-and-args.md。
Args validators
参数验证器
Cobra validates positional arguments before runs. Never write checks inside — that bypasses cobra's standard error messages and arg count tracking.
RunElen(args)RunEBuilt-ins: , , , , , , . Compose with . Custom validator: .
NoArgsExactArgs(n)MinimumNArgs(n)MaximumNArgs(n)RangeArgs(min,max)OnlyValidArgsExactValidArgs(n)MatchAll(v1, v2)func(cmd *cobra.Command, args []string) errorFor the full validator set with examples and patterns, see commands-and-args.md.
MatchAllCobra会在运行之前验证位置参数。永远不要在内部编写检查——这会绕过cobra的标准错误消息和参数计数跟踪。
RunERunElen(args)内置验证器:、、、、、、。可通过组合使用。自定义验证器:。
NoArgsExactArgs(n)MinimumNArgs(n)MaximumNArgs(n)RangeArgs(min,max)OnlyValidArgsExactValidArgs(n)MatchAll(v1, v2)func(cmd *cobra.Command, args []string) error如需查看完整的验证器集合、示例及模式,请查看commands-and-args.md。
MatchAllFlags primer
标志入门
Cobra delegates flag parsing to . Persistent flags () are inherited by all subcommands; local flags () apply only to the declaring command.
pflagPersistentFlags()Flags()go
rootCmd.PersistentFlags().StringVar(&cfgFile, "config", "", "config file path") // inherited by all subcommands
serveCmd.Flags().IntVar(&port, "port", 8080, "listen port") // local to serveCmd only
serveCmd.MarkFlagRequired("port")
serveCmd.MarkFlagsMutuallyExclusive("json", "yaml")For pflag types, custom flag values, flag groups, and viper binding, see flags.md.
Cobra将标志解析委托给。全局标志()会被所有子命令继承;局部标志()仅适用于声明该标志的命令。
pflagPersistentFlags()Flags()go
rootCmd.PersistentFlags().StringVar(&cfgFile, "config", "", "config file path") // 被所有子命令继承
serveCmd.Flags().IntVar(&port, "port", 8080, "listen port") // 仅适用于serveCmd
serveCmd.MarkFlagRequired("port")
serveCmd.MarkFlagsMutuallyExclusive("json", "yaml")如需了解pflag类型、自定义标志值、标志组及viper绑定,请查看flags.md。
Completions primer
自动补全入门
Cobra generates shell completions automatically. Extend them with:
- — static positional arg completion.
ValidArgs []string - — dynamic:
ValidArgsFunction. Returnfunc(cmd, args, toComplete string) ([]string, ShellCompDirective)to suppress file fallback.ShellCompDirectiveNoFileComp - — flag value completion.
RegisterFlagCompletionFunc(name, fn)
For values, annotations, and testing, see completions.md.
ShellCompDirectiveCobra会自动生成Shell自动补全。可通过以下方式扩展:
- —— 静态位置参数补全。
ValidArgs []string - —— 动态补全:
ValidArgsFunction。返回func(cmd, args, toComplete string) ([]string, ShellCompDirective)可禁用文件补全回退。ShellCompDirectiveNoFileComp - —— 标志值补全。
RegisterFlagCompletionFunc(name, fn)
如需了解取值、注解及测试,请查看completions.md。
ShellCompDirectiveTesting commands
命令测试
Test commands by executing them programmatically. Never use / directly in command handlers — use / so tests can redirect output.
os.Stdoutos.Stderrcmd.OutOrStdout()cmd.ErrOrStderr()go
func TestServeCmd(t *testing.T) {
buf := new(bytes.Buffer)
rootCmd.SetOut(buf)
rootCmd.SetArgs([]string{"serve", "--port", "9090"})
require.NoError(t, rootCmd.Execute())
assert.Contains(t, buf.String(), "listening on :9090")
}Cobra accumulates flag state across calls — build a fresh command tree per test. For isolation patterns, golden files, and testing completions, see testing.md.
Execute()通过编程方式执行命令进行测试。永远不要在命令处理程序中直接使用 / ——使用 / ,以便测试时可以重定向输出。
os.Stdoutos.Stderrcmd.OutOrStdout()cmd.ErrOrStderr()go
func TestServeCmd(t *testing.T) {
buf := new(bytes.Buffer)
rootCmd.SetOut(buf)
rootCmd.SetArgs([]string{"serve", "--port", "9090"})
require.NoError(t, rootCmd.Execute())
assert.Contains(t, buf.String(), "listening on :9090")
}Cobra会在多次调用之间累积标志状态——每次测试都要构建全新的命令树。如需了解隔离模式、黄金文件及自动补全测试,请查看testing.md。
Execute()Best Practices
最佳实践
- Always use , never
RunE—Runcannot return an error; the only escape isRunor panic, bypassing defers.os.Exit - Put config initialization in — it runs before every subcommand; the right place for viper binding and auth checks.
PersistentPreRunE - Validate positional args with , not inside
Args—RunEgives cobra's standard error messages;Argscomposes validators.MatchAll - Use /
cmd.OutOrStdout()for all output — directcmd.ErrOrStderr()writes cannot be captured by tests.os.Stdout - Re-create the command tree per test — cobra accumulates flag state across calls on the same instance.
Execute()
- 始终使用,绝不使用
RunE——Run无法返回错误;唯一的退出方式是Run或panic,会跳过defer语句。os.Exit - 将配置初始化放在中 —— 它会在每个子命令之前运行,是viper绑定和身份验证检查的合适位置。
PersistentPreRunE - 使用验证位置参数,而非在
Args内部 ——RunE会提供cobra的标准错误消息;Args可组合多个验证器。MatchAll - 所有输出都使用/
cmd.OutOrStdout()—— 直接写入cmd.ErrOrStderr()的内容无法被测试捕获。os.Stdout - 每次测试重新创建命令树 —— Cobra会在同一实例的多次调用之间累积标志状态。
Execute()
Common Mistakes
常见错误
| Mistake | Why it fails | Fix |
|---|---|---|
Using | Cannot return an error — only escape is | Use |
Writing | Bypasses cobra's standard error messages ("accepts 1 arg, received 2") | Declare |
Writing to | Tests cannot capture output — os-level file handles can't be redirected | Use |
Child | Cobra does not chain — the child replaces the parent's hook entirely | Call |
| Reusing a root command across tests | Cobra accumulates flag state; second | Build a fresh command tree per test |
| 错误行为 | 失败原因 | 修复方案 |
|---|---|---|
使用 | 无法返回错误;只能通过 | 使用 |
在 | 绕过了cobra的标准错误消息(如“接受1个参数,实际收到2个”) | 在命令上声明 |
直接写入 | 测试无法捕获输出——操作系统级别的文件句柄无法重定向 | 使用 |
子命令的 | Cobra不会链式执行——子命令会完全替换父命令的钩子 | 在子命令的钩子中显式调用 |
| 跨测试重用根命令 | Cobra会累积标志状态;第二次 | 每次测试都构建全新的命令树 |
Further Reading
扩展阅读
- commands-and-args.md — full PreRun*/PostRun* chain, every Args validator, PersistentPreRunE inheritance rules
- flags.md — pflag types, required/exclusive/oneRequired groups, custom value types, viper binding
- completions.md — ShellCompDirective set, annotation-based completions, testing completions
- generators.md — man page, markdown, YAML, RST doc generation; scaffolder
cobra-cli - testing.md — isolation patterns, golden files, testing completions, table-driven command tests
- commands-and-args.md —— 完整的PreRun*/PostRun*钩子链、所有参数验证器、PersistentPreRunE继承规则
- flags.md —— pflag类型、必填/互斥/单选必填标志组、自定义值类型、viper绑定
- completions.md —— ShellCompDirective取值、基于注解的自动补全、自动补全测试
- generators.md —— 手册页、Markdown、YAML、RST文档生成;脚手架工具
cobra-cli - testing.md —— 隔离模式、黄金文件、自动补全测试、表格驱动命令测试
Cross-References
交叉引用
- → See skill for general CLI architecture — project layout, exit codes, signal handling, I/O patterns
samber/cc-skills-golang@golang-cli - → See skill for configuration layering alongside cobra (flag → env → file → default precedence)
samber/cc-skills-golang@golang-spf13-viper - → See skill for general Go testing patterns
samber/cc-skills-golang@golang-testing
If you encounter a bug or unexpected behavior in spf13/cobra, open an issue at https://github.com/spf13/cobra/issues.
- → 如需了解通用CLI架构(项目布局、退出码、信号处理、I/O模式),请查看技能
samber/cc-skills-golang@golang-cli - → 如需结合cobra实现配置分层(标志→环境变量→文件→默认值优先级),请查看技能
samber/cc-skills-golang@golang-spf13-viper - → 如需了解通用Go测试模式,请查看技能
samber/cc-skills-golang@golang-testing
如果在使用spf13/cobra时遇到bug或意外行为,请在https://github.com/spf13/cobra/issues提交问题。