2

下面的草图是一个使用 Cobra 和 Go 编写的命令行应用程序。flag1如果 的值与 regex 不匹配,我想抛出一个错误^\s+\/\s+。我怎么做?

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())
        }
}
4

1 回答 1

3

假设用户运行如下命令:cobra-sketch --flag1 "hello". “hello”将存储在var flag1 string您分配给标志的变量中,以检查输入是否与任何正则表达式匹配,您可以执行以下操作:

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
    },
}
于 2021-04-22T18:14:33.810 回答