gogo-cobra

golang cobra local flags assignment


okay so I'm getting the hang of cobra. In order to recognize the parent who is calling the sub-submodule, I have to use pointers, because there is more than one parent (and more than one grandparent).

Now to assign local flags would the below code be correct?

var (
    GcpAccessAnnotateCmd    = *AnnotateCmd
    GcpApprovalsAnnotateCmd = *AnnotateCmd
    SshAccessAnnotateCmd    = *AnnotateCmd
    SshApprovalsAnnotateCmd = *AnnotateCmd
)

func init() {
    GcpAccessAnnotateCmd.Flags().
        StringP("note", "n", "", "Note/Comment to add to the request or task")
    GcpApprovalsAnnotateCmd.Flags().
        StringP("note", "n", "", "Note/Comment to add to the request or task")
    SshAccessAnnotateCmd.Flags().
        StringP("note", "n", "", "Note/Comment to add to the request or task")
    SshApprovalsAnnotateCmd.Flags().
        StringP("note", "n", "", "Note/Comment to add to the request or task")
}

In other words since I have 4 pointers would I have to declare the flag 4 times?


Solution

  • You could also use a persistent flag for the parent command. Otherwise, yes you have to assign the flag to every command it is used in. You could use a loop instead of repeating the same line, though.