引言
Cobra 是 Go 生态常用的 CLI 框架,提供命令树、标志解析、帮助和补全。可测试性取决于把命令构建与 Execute 分离。
项目结构
把 rootCmd 和子命令放在 cmd/,业务逻辑放在 internal/。命令只负责解析参数和调用服务,核心逻辑接受普通参数和 context.Context,便于单元测试。
子命令与标志
用 Use、Short 和 Args 定义命令;持久标志沿命令树继承,局部标志只属于当前命令。必填标志用 MarkFlagRequired,但要在执行前给出清晰错误。位置参数用 cobra.ExactArgs 等校验。
上下文与退出码
在 ExecuteContext 中传递 context,监听 SIGINT/SIGTERM 并取消。用法错误返回非零退出码并打印帮助;运行时失败返回不同退出码,便于脚本判断。不要用 os.Exit 跳过清理。
补全与测试
Cobra 可生成 bash、zsh、fish 和 PowerShell 补全。用 ExecuteC 在测试中执行命令树,捕获 stdout/stderr,断言输出、错误和退出码,无需启动子进程。
常见陷阱
在 init() 中读取环境变量会让测试难以覆盖;在命令内直接调用全局状态会降低可测性。把依赖注入命令,保持命令层薄。
代码示例
mkdir taskctl && cd taskctl
go mod init example.com/taskctl
go get github.com/spf13/cobra@latest
taskctl/
main.go
cmd/root.go
cmd/build.go
internal/build/build.go
package main
import (
"fmt"
"os"
"example.com/taskctl/cmd"
)
func main() {
if err := cmd.Execute(); err != nil {
fmt.Fprintln(os.Stderr, "error:", err)
os.Exit(1)
}
}
package cmd
import (
"context"
"github.com/spf13/cobra"
)
func NewRootCmd() *cobra.Command {
root := &cobra.Command{
Use: "taskctl",
Short: "Build and inspect tasks",
SilenceUsage: true,
SilenceErrors: true,
}
root.PersistentFlags().Bool("verbose", false, "enable verbose logging")
root.AddCommand(newBuildCmd())
return root
}
func Execute() error {
return NewRootCmd().ExecuteContext(context.Background())
}
package cmd
import (
"fmt"
"github.com/spf13/cobra"
)
func newBuildCmd() *cobra.Command {
var output string
var config string
build := &cobra.Command{
Use: "build <input>",
Short: "Build a task file",
Args: cobra.ExactArgs(1),
RunE: func(cmd *cobra.Command, args []string) error {
verbose, err := cmd.Flags().GetBool("verbose")
if err != nil {
return err
}
result, err := buildFile(args[0], output, config, verbose)
if err != nil {
return fmt.Errorf("build %s: %w", args[0], err)
}
fmt.Fprintln(cmd.OutOrStdout(), result)
return nil
},
}
build.Flags().StringVarP(&output, "output", "o", "dist", "output directory")
build.Flags().StringVarP(&config, "config", "c", "", "configuration file")
_ = build.MarkFlagRequired("config")
return build
}
func buildFile(input, output, config string, verbose bool) (string, error) {
if input == "" {
return "", errors.New("input is required")
}
// Validate paths, read the config, and perform the build here.
return fmt.Sprintf("built %s into %s", input, output), nil
}
defaultOutput := os.Getenv("TASKCTL_OUTPUT")
if defaultOutput == "" {
defaultOutput = "dist"
}
build.Flags().StringVarP(&output, "output", "o", defaultOutput, "output directory")
func Execute() error {
ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM)
defer stop()
return NewRootCmd().ExecuteContext(ctx)
}
taskctl completion bash > /etc/bash_completion.d/taskctl
taskctl completion zsh > "${fpath[1]}/_taskctl"
taskctl completion fish > ~/.config/fish/completions/taskctl.fish
build.ValidArgsFunction = func(cmd *cobra.Command, args []string, toComplete string) ([]string, cobra.ShellCompDirective) {
if len(args) > 0 {
return nil, cobra.ShellCompDirectiveNoFileComp
}
files, _ := filepath.Glob(toComplete + "*")
return files, cobra.ShellCompDirectiveDefault
}
func execute(t *testing.T, args ...string) (string, error) {
t.Helper()
root := NewRootCmd()
var out bytes.Buffer
root.SetOut(&out)
root.SetErr(&out)
root.SetArgs(args)
err := root.Execute()
return out.String(), err
}
func TestBuildRequiresConfig(t *testing.T) {
_, err := execute(t, "build", "input.txt")
if err == nil {
t.Fatal("expected an error when --config is missing")
}
}