Make a cobra Command flag required

前端 未结 3 1807
野性不改
野性不改 2021-02-19 19:03

I\'ve created a cobra command and added a flag:

cmd.Flags().StringVarP(&primaryIP, \"primary-ip\", \"p\", \"\", \"Help text\")

Is there a w

相关标签:
3条回答
  • 2021-02-19 19:35

    Late but i hope this help you !

    First of all, we need to know that cobra defines two types of flags.

    Persistent flags: they will be available to the command and every sub-command under it.

    Local flags: they will available only to the specific command which define them.


    So cobra provides two approaches to make flags required regarding the type of the flag.

    On the init function of your command, it could be the root or any other command or sub-command. Lets create a cli app called my-cmd with a sub-command called xD sub-command

    // root.go file
    
    var Foo bool
    
    func init() {
        cobra.OnInitialize(initConfig)
    
        // define required persistent flag
        myCmd.PersistentFlags().BoolVarP(&Foo, "foo", "f", false, "set foo (*)")
        myCmd.MarkPersistentFlagRequired("foo")
    }
    
    // subCommand.go file
    
    var Bar string
    
    func init() {
        // just add subCmd as a sub-command of my-cmd
        myCmd.AddCommand(subCmd)
    
        // define required local flag
        subCmd.Flags().StringVarP(&Bar, "bar", "b", "", "set bar (*)")
        subCmd.MarkFlagRequired("bar")
    }
    
    

    When you call your command in the CLI

    # if you don't pass a value for 'foo' flag
    > my-cmd
        required flag(s) "foo" not set
        exit status 1
    
    # here you must pass a value for 'foo' because is persistent as well as 'bar' because is local for sub-cmd
    > my-cmd sub-cmd
        required flag(s) "foo", "bar" not set
        exit status 1
    
    0 讨论(0)
  • 2021-02-19 19:43

    No, you have to check yourself whether the input is correct for your program.

    Note that this makes sense, since you may want to check if the input is correct at the same time. In your example you should check if the input exists AND if the input is a valid ip-address.

    0 讨论(0)
  • 2021-02-19 19:49

    A few months ago this behavior was changed in cobra, although the documentation is not very clear on this. Now if you mark a flag as MarkFlagRequired("primary-ip") and you don't supply such a flag, running the command will print the help plus

    required flag(s) "primary-ip"
    exit status 1
    

    at the end where the missing required flags are stated.

    0 讨论(0)
提交回复
热议问题