Validating flags using Cobra

11.5k views Asked by At

The sketch below is a command line application written using Cobra and Go. I'd like to throw an error if the value of flag1 doesn't match the regex ^\s+\/\s+. How do I do that?

package cmd

import (
        "fmt"
        "os"
        "github.com/spf13/cobra"

        homedir "github.com/mitchellh/go-homedir"
        "github.com/spf13/viper"
)

var flag1 string
var cfgFile string

// rootCmd represents the base command when called without any subcommands
var rootCmd = &cobra.Command{
        Use:   "cobra-sketch",
        Short: "Sketch for Cobra flags",
  Long: "Sketch for Cobra flags",
        Run: func(cmd *cobra.Command, args []string) { fmt.Printf("Flag1 is %s\n", flag1)},
}

// Execute adds all child commands to the root command and sets flags appropriately.
// This is called by main.main(). It only needs to happen once to the rootCmd.
func Execute() {
        cobra.CheckErr(rootCmd.Execute())
}

func init() {
        cobra.OnInitialize(initConfig)
 
        rootCmd.PersistentFlags().StringVar(&cfgFile, "config", "", "config file (default is $HOME/.cobra-sketch.yaml)")
  rootCmd.PersistentFlags().StringVar(&flag1, "flag1", "", "Value of Flag 1")
}

// initConfig reads in config file and ENV variables if set.
func initConfig() {
        if cfgFile != "" {
                // Use config file from the flag.
                viper.SetConfigFile(cfgFile)
        } else {
                // Find home directory.
                home, err := homedir.Dir()
                cobra.CheckErr(err)

                // Search config in home directory with name ".cobra-sketch" (without extension).
                viper.AddConfigPath(home)
                viper.SetConfigName(".cobra-sketch")
        }

        viper.AutomaticEnv() // read in environment variables that match

        // If a config file is found, read it in.
        if err := viper.ReadInConfig(); err == nil {
                fmt.Fprintln(os.Stderr, "Using config file:", viper.ConfigFileUsed())
        }
}
1

There are 1 answers

2
GGP On BEST ANSWER

Let's say a user runs the command like this: cobra-sketch --flag1 "hello". "hello" will be stored in the var flag1 string variable you have assigned to the flag, to check if the input matches any regexp, you can do:

var rootCmd = &cobra.Command{
    Use:   "cobra-sketch",
        ...
    RunE: func(cmd *cobra.Command, args []string) error {
        // You can also use MustCompile if you are sure the regular expression 
        // is valid, it panics instead of returning an error
        re, err := regexp.Compile(`^\s+\/\s+`)
        if err != nil {
            return err // Handle error
        }

        if !regexp.MatchString(flag1) {
            return fmt.Errorf("invalid value: %q", flag1)
        }

        fmt.Printf("Flag1 is %s\n", flag1)
        return nil
    },
}