Make a cobra Command flag required

前端 未结 3 1808
野性不改
野性不改 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
    

提交回复
热议问题