// Enum is a Cobra-compatible wrapper for defining a string flag that can be one of a specified set of values. type Enum struct { allowedValues []string value string }
// NewEnum returns a new enum flag with the specified list of allowed values, and the specified default value if none is set. funcNewEnum(defaultValue string, allowedValues ...string) *Enum { return &Enum{ allowedValues: allowedValues, value: defaultValue, } }
// String returns a string representation of the enum flag. func(e *Enum) String() string { return e.value }
// Set assigns the provided string to the enum receiver. It returns an error if the string is not an allowed value. func(e *Enum) Set(s string) error { for _, val := range e.allowedValues { if val == s { e.value = s returnnil } }
return errors.Errorf("invalid value: %q", s) }
// Type returns a string representation of the Enum type. func(e *Enum) Type() string { // we don't want the help text to display anything regarding // the type because the usage text for the flag should capture // the possible options. return"" }
// AllowedValues returns a slice of the flag's valid values. func(e *Enum) AllowedValues() []string { return e.allowedValues }
封装了枚举类型,包含默认值以及允许的枚举值,Enum 结构体实现了 pflag 的 Value 接口(String(),Set(),Type()),在执行 flags.StringSliceVar 等操作时,pflag 会调用 Set 函数设置值,因此 Set 可以用于校验枚举值的合法性。
// DefaultLogger returns a Logger with the default properties. // The desired output format is passed as a LogFormat Enum. funcDefaultLogger(level logrus.Level, format Format) *logrus.Logger { logger := logrus.New()
if format == FormatJSON { logger.Formatter = new(logrus.JSONFormatter) }
// Make sure the output is set to stdout so log messages don't show up as errors in cloud log dashboards. logger.Out = os.Stdout
fmt.Printf("The level at which to log. Valid values are %s.\n", strings.Join(logLevelFlag.AllowedValues(), ", ")) fmt.Printf("The format for log output. Valid values are %s.\n", strings.Join(formatFlag.AllowedValues(), ", "))