Open giacomo-pati opened 3 years ago
Do you have a more complete example? This works fine for me.
package main
import (
"fmt"
"github.com/spf13/cobra"
)
func main() {
rootCmd := &cobra.Command{
Use: `root`,
}
setCmd := &cobra.Command{
Use: `set`,
Run: func(cmd *cobra.Command, args []string) {
v, _ := cmd.Flags().GetBool("flagA")
fmt.Printf("set called with %t\n", v)
},
}
getCmd := &cobra.Command{
Use: `get`,
Run: func(cmd *cobra.Command, args []string) {
v, _ := cmd.Flags().GetBool("flagA")
fmt.Printf("get called with %t\n", v)
},
}
rootCmd.AddCommand(getCmd)
rootCmd.AddCommand(setCmd)
getCmd.Flags().Bool("flagA", false, "my usage")
setCmd.Flags().Bool("flagA", false, "my usage")
if err := rootCmd.Execute(); err != nil {
panic(err)
}
}
With result:
$ go run . --help
Usage:
root [command]
Available Commands:
get
help Help about any command
set
Flags:
-h, --help help for root
Use "root [command] --help" for more information about a command.
$ go run . get
get called with false
$ go run . get --flagA
get called with true
$ go run . set --flagA
set called with true
$ go run . set
set called with false
I'm making my head around how to best implement the following scenario.
I'm creating a cli using cobra with several (sub)commands:
cli cmdA --flagA cli cmdB --flagA cli cmdC --flagB
I can't define 'flagA' on both subcommands (cmdA & cmdB) as pflags reports that 'flagA redeclared in this block'
What I don't want is to define flagA on root command as it will be available to cmdC as well. I also don't want to do artificially define a parent command for cmdA and cmdB to define flagA on.
Tried already all kinds of combinations with PersistentFlags, Flags, LocalFlags but couldn't find a solution that works. And Suggestions?