define trueString constant

This commit is contained in:
Jun Nishimura 2023-07-15 00:56:13 +09:00
parent 46a2ba8c41
commit f3125ff6fa

View file

@ -30,7 +30,10 @@ import (
flag "github.com/spf13/pflag" flag "github.com/spf13/pflag"
) )
const FlagSetByCobraAnnotation = "cobra_annotation_flag_set_by_cobra" const (
FlagSetByCobraAnnotation = "cobra_annotation_flag_set_by_cobra"
trueString = "true"
)
// FParseErrWhitelist configures Flag parse errors to be ignored // FParseErrWhitelist configures Flag parse errors to be ignored
type FParseErrWhitelist flag.ParseErrorsWhitelist type FParseErrWhitelist flag.ParseErrorsWhitelist
@ -1109,7 +1112,7 @@ func (c *Command) ValidateRequiredFlags() error {
if !found { if !found {
return return
} }
if (requiredAnnotation[0] == "true") && !pflag.Changed { if (requiredAnnotation[0] == trueString) && !pflag.Changed {
missingFlagNames = append(missingFlagNames, pflag.Name) missingFlagNames = append(missingFlagNames, pflag.Name)
} }
}) })
@ -1146,7 +1149,7 @@ func (c *Command) InitDefaultHelpFlag() {
usage += c.Name() usage += c.Name()
} }
c.Flags().BoolP("help", "h", false, usage) c.Flags().BoolP("help", "h", false, usage)
_ = c.Flags().SetAnnotation("help", FlagSetByCobraAnnotation, []string{"true"}) _ = c.Flags().SetAnnotation("help", FlagSetByCobraAnnotation, []string{trueString})
} }
} }
@ -1172,7 +1175,7 @@ func (c *Command) InitDefaultVersionFlag() {
} else { } else {
c.Flags().Bool("version", false, usage) c.Flags().Bool("version", false, usage)
} }
_ = c.Flags().SetAnnotation("version", FlagSetByCobraAnnotation, []string{"true"}) _ = c.Flags().SetAnnotation("version", FlagSetByCobraAnnotation, []string{trueString})
} }
} }
@ -1212,7 +1215,7 @@ Simply type ` + c.Name() + ` help [path to command] for full details.`,
PersistentPreRunE: func(cmd *Command, args []string) error { PersistentPreRunE: func(cmd *Command, args []string) error {
cmd.Flags().VisitAll(func(pflag *flag.Flag) { cmd.Flags().VisitAll(func(pflag *flag.Flag) {
requiredAnnotation, found := pflag.Annotations[BashCompOneRequiredFlag] requiredAnnotation, found := pflag.Annotations[BashCompOneRequiredFlag]
if found && requiredAnnotation[0] == "true" { if found && requiredAnnotation[0] == trueString {
// Disable any persistent required flags for the help command // Disable any persistent required flags for the help command
pflag.Annotations[BashCompOneRequiredFlag] = []string{"false"} pflag.Annotations[BashCompOneRequiredFlag] = []string{"false"}
} }