gocommand-line-interfacego-cobra

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


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.


Solution

  • 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
    }