Last active
April 12, 2023 12:46
-
-
Save MattKetmo/0b5b38f191ed8b673f046312654ab9d6 to your computer and use it in GitHub Desktop.
Debug cobra duplicated flags
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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