Cobra:在不使用包全局变量的情况下为子命令提供上下文?

lar*_*sks 5 command-line go cobra viper-go

我使用cobraviper编写了一个简单的 CLI 工具。我最近一直在重构它以避免包全局变量,很大程度上是因为事实证明很难使用例如建议的布局进行测试cobra init

代替...

var rootCmd = &cobra.Command{
  ...
}

func main() {
  rootCmd.Execute()
}
Run Code Online (Sandbox Code Playgroud)

我有更多类似的东西:

func NewCmdRoot() *cobra.Command {
  cmd := &cobra.Command{
    ...
  }

  return cmd
}

func main() {
  rootCmd := NewCmdRoot()
  rootCmd.Execute()
}
Run Code Online (Sandbox Code Playgroud)

这实际上效果很好,并且使测试更容易从一组干净的 cli 选项开始。我在将 Viper 集成到新方案中遇到了一些困难。如果我只关心 root 命令,我可以在PersistentPreRun 命令中进行设置,如下所示:

func initConfig(cmd *cobra.Command) {
  config := viper.New()
  rootCmd := cmd.Root()

  config.BindPFlag("my-nifty-option", rootCmd.Flag("my-nifty-option")); err != nil {

  // ...stuff happens here...

  config.ReadInConfig()

  // What happens next?
}

func NewCmdRoot() *cobra.Command {
  cmd := &cobra.Command{
    PersistentPreRun: func(cmd *cobra.Command, args []string) {
      initConfig(cmd)
    },
  }
Run Code Online (Sandbox Code Playgroud)

这种工作方式:只要我只对与 Cobra 命令行选项相对应的配置选项感兴趣,事情就会按预期工作。但是如果我想访问变量config本身怎么办?

我不确定如何在方法config之外公开变量 initConfig而不将其转换为包全局变量。我希望能够实例化多个命令树,每个命令树都有自己独立的 Viper 配置对象,但我不清楚将其放在哪里。

小智 4

cobra 团队最近做到了这一点,请参阅https://github.com/spf13/cobra/pull/1551

func TestFoo(t *testing.T){
    root := &Command{
        Use: "root",
        PreRun: func(cmd *Command, args []string) {
            ctx := context.WithValue(cmd.Context(), key{}, val)
            cmd.SetContext(ctx)
        },
        Run: func(cmd *Command, args []string) {
            fmt.Println(cmd.Context().Value(key{}))
        },
    }
    ctx := context.WithValue(cmd.Context(), "key", "default")
    root.ExecuteContext(ctx)
}
Run Code Online (Sandbox Code Playgroud)