【问题标题】:Validating flags using Cobra使用 Cobra 验证标志
【发布时间】:2021-04-22 17:40:00
【问题描述】:

下面的草图是一个使用 Cobra 和 Go 编写的命令行应用程序。如果flag1 的值与正则表达式^\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())
        }
}

【问题讨论】:

    标签: go go-cobra


    【解决方案1】:

    假设用户运行如下命令: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
        },
    }
    

    【讨论】:

    • 这绝对有效,并回答了我提出的问题。但是,我问错了问题,因为我没有补充说我希望验证适用于所有子命令。
    • 好消息是,您的回答让我找到了我实际上正在寻找的答案,即使用PersistentPreRunE。你向我展示了正则表达式的东西,这也很有帮助。 :)
    猜你喜欢
    • 2019-01-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-01-31
    • 2020-11-03
    • 2021-06-20
    • 1970-01-01
    相关资源
    最近更新 更多