Cobra: How to add a required argument?

Created on 23 Sep 2016  路  2Comments  路  Source: spf13/cobra

I am migrating my app over from another cli library (kingpin), and one of the things they let me do is document positional arguments, e.g. cmd.Arg("name", "name of the thing").Required().StringVar(&name). I am having trouble understanding how to migrate that over. So far the best I have come up with is this:

var createCmd = &cobra.Command{
    Use:   "create <name>",
    Short: "Create a thing",
    Long:  "Create a thing",
    RunE: func(cmd *cobra.Command, args []string) error {
        if len(args) < 1 {
            return errors.New("The name argument is required")
        }
        name = args[0]
        // create a thing
    }

Basically I am documenting the arg in the Use string and then parsing the arg in RunE. This feels a bit awkward, is there something built-in that I am overlooking?

Thanks!

Most helpful comment

Doing it manually in a (Pre)RunE is sadly the best you can likely do. Sorry.

All 2 comments

Doing it manually in a (Pre)RunE is sadly the best you can likely do. Sorry.

No need to apologize! I was just looking for the recommended way to get stuff done. :smile: Thank you for the quick reply!

Was this page helpful?
0 / 5 - 0 ratings

Related issues

phanirithvij picture phanirithvij  路  5Comments

andygrunwald picture andygrunwald  路  6Comments

lukasmalkmus picture lukasmalkmus  路  4Comments

joernott picture joernott  路  6Comments

eine picture eine  路  5Comments