Skip to content

Instantly share code, notes, and snippets.

@MattKetmo
Last active April 12, 2023 12:46
Show Gist options
  • Save MattKetmo/0b5b38f191ed8b673f046312654ab9d6 to your computer and use it in GitHub Desktop.
Save MattKetmo/0b5b38f191ed8b673f046312654ab9d6 to your computer and use it in GitHub Desktop.
Debug cobra duplicated flags
package main
import (
"github.com/spf13/cobra"
"github.com/spf13/viper"
)
var v = viper.New()
func NewCommand() *cobra.Command {
cmd := &cobra.Command{
Use: "demo SUBCOMMAND",
}
cmd.AddCommand(NewSubCmd1())
cmd.AddCommand(NewSubCmd2())
return cmd
}
func NewSubCmd1() *cobra.Command {
cmd := &cobra.Command{
Use: "cmd1",
Run: func(cmd *cobra.Command, args []string) {
println("cmd1", "log.level =", v.GetString("log.level"))
},
}
cmd.PersistentFlags().String("log-level", "info", "Logger's output level")
_ = v.BindPFlag("log.level", cmd.Flag("log-level"))
return cmd
}
func NewSubCmd2() *cobra.Command {
cmd := &cobra.Command{
Use: "cmd2",
Run: func(cmd *cobra.Command, args []string) {
println("cmd2", "log.level =", v.GetString("log.level"))
},
}
cmd.PersistentFlags().String("log-level", "info", "Logger's output level")
_ = v.BindPFlag("log.level", cmd.Flag("log-level"))
return cmd
}
func main() {
command := NewCommand()
if err := command.Execute(); err != nil {
panic(err)
}
}
// $ go run . cmd1 --log-level debug
// cmd1 log.level = info
//
// $ go run . cmd2 --log-level debug
// cmd2 log.level = debug
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment