Golang Cobra command flags in common function not getting values from cli

6.5k Views Asked by At

I'm moving my cobra command flags inside a function so I can use it in other commands. I can able to see the commands but when I type the flage it always returns false.

Following is my code:

func NewCommand(ctx context.Context) *cobra.Command {
    var opts ListOptions

    cmd := &cobra.Command{
        Use:   "list",
        Short: "List",
        RunE: func(cmd *cobra.Command, args []string) error {
            fmt.Println(args) // []
            opts.refs = args
            return List(ctx, gh, opts, os.Stdout)
        },
    }

    cmd = GetCommandFlags(cmd, opts)
    return cmd
}

// GetListCommandFlags for list
func GetCommandFlags(cmd *cobra.Command, opts ListOptions) *cobra.Command {
    flags := cmd.Flags()
    flags.BoolVar(&opts.IgnoreLatest, "ignore-latest", false, "Do not display latest")
    flags.BoolVar(&opts.IgnoreOld, "ignore-old", false, "Do not display old data")
    return cmd
}

So when I type the following command

data-check list --ignore-latest

The the flag value of --ignore-latest should be true but I get false as a value in RunE args. Am I missing something here?

GetCommandFlags is something I want to use it in other commands I don't want to repeat the same flags.

3

There are 3 best solutions below

1
On BEST ANSWER

You should use func GetCommandFlags(cmd *cobra.Command, opts *ListOptions) and call the func like cmd = GetCommandFlags(cmd, &opts).

You can print opts.IgnoreLatest and opts.IgnoreOld to see the changed value.

Works fine for me. Hope it will work for you too.

func NewCommand(ctx context.Context) *cobra.Command {
    var opts ListOptions

    cmd := &cobra.Command{
        Use:   "list",
        Short: "List",
        RunE: func(cmd *cobra.Command, args []string) error {
            // fmt.Println(args) // []
            fmt.Println(opts.IgnoreLatest, ", ", opts.IgnoreOld)
            opts.refs = args
            return List(ctx, gh, opts, os.Stdout)
        },
    }

    cmd = GetCommandFlags(cmd, &opts)
    return cmd
}

// GetListCommandFlags for list
func GetCommandFlags(cmd *cobra.Command, opts *ListOptions) *cobra.Command {
    flags := cmd.Flags()
    flags.BoolVar(&opts.IgnoreLatest, "ignore-latest", false, "Do not display latest")
    flags.BoolVar(&opts.IgnoreOld, "ignore-old", false, "Do not display old data")
    return cmd
}
4
On

You are passing opts to GetCommandFlags by value. You should pass a pointer to it, so the addresses registered for the flags use the opts declared in the calling function.

func GetCommandFlags(cmd *cobra.Command, opts *ListOptions) *cobra.Command {
  ...
}
1
On

You are passing value parameter not a pointer parameter.

Try someting like:

cmd = GetCommandFlags(cmd, &opts, "")