pflag icon indicating copy to clipboard operation
pflag copied to clipboard

Handling of multiple flags with same name

Open giacomo-pati opened this issue 3 years ago • 1 comments

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'

cmdAflagA := cmdA.Flags().Bool("flagA",...)
cmdBflagA := cmdB.Flags().Bool("flagA",...)

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?

giacomo-pati avatar Sep 15 '21 08:09 giacomo-pati

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

hoshsadiq avatar Feb 17 '22 08:02 hoshsadiq