Home > Software engineering >  Require a flag as the first argument in a Cobra command
Require a flag as the first argument in a Cobra command

Time:10-29

I'm trying to create a Cobra command that uses a flag to inform the action of the command, specifically a configuration command that can either add or remove a configured setting. For example

cli> prog_name config --set config_var var_vlue
cli> prog_name config --unset config_var var_value

Is there a way to do this in Cobra? I have been reading through the documentation and haven't found any way to validate that a flag is the first value in the command. I've seen information about positional arguments, but from what I've read it sounds like flags aren't considered arguments, so they wouldn't be covered by positional arguments.

I'd imagine I can do this in my PreRunE function and do the validation manually, but if there's a way to set this in Cobra I think that'd most likely be better, since I'd prefer Cobra to be doing that parsing and matching rather than me have to be comparing specific values in os.Args to "--set" and "--unset" or something similar.

CodePudding user response:

It seems like the best option is to just use a subcommand for this instead of a flag.

CodePudding user response:

You can solve this by consulting this link.

In short what you need is the Flags() function. You can find documentation here.


package main

import (
    "fmt"

    "github.com/spf13/cobra"
)

var rootCmd = &cobra.Command{
    Use: "testprog",
    Run: func(cmd *cobra.Command, args []string) {
        fmt.Println("rootCmd called")
    },
}

var subCmd = &cobra.Command{
    Use: "sub",
    Run: func(cmd *cobra.Command, args []string) {
        fmt.Println(args)
    },
}

func main() {
    rootCmd.AddCommand(subCmd)
    
    flags := subCmd.Flags()

    // not necessary in your case
    flags.SetInterspersed(false)

    // Bool defines a bool flag with specified name,
    // default value, and usage string. The return value
    // is the address of a bool variable that stores
    // the value of the flag.
    flags.Bool("test", false, "test flag")

    rootCmd.Execute()
}

Let's see what happens in the terminal:

    > ./cobraApp sub --test a
    > [a]
  • Related