This commit is contained in:
Victor Kareh 2025-01-20 08:22:40 +00:00 committed by GitHub
commit e1b5d54f0a
No known key found for this signature in database
GPG key ID: B5690EEEBB952194

View file

@ -168,6 +168,9 @@ type Command struct {
usageFunc func(*Command) error
// usageTemplate is usage template defined by user.
usageTemplate string
// flagParseFunc is func defined by user and it's called when the command is
// parsing the flags.
flagParseFunc func(*Command, []string) error
// flagErrorFunc is func defined by user and it's called when the parsing of
// flags returns an error.
flagErrorFunc func(*Command, error) error
@ -315,6 +318,11 @@ func (c *Command) SetUsageTemplate(s string) {
c.usageTemplate = s
}
// SetFlagParseFunc sets a function to parse flags.
func (c *Command) SetFlagParseFunc(f func(*Command, []string) error) {
c.flagParseFunc = f
}
// SetFlagErrorFunc sets a function to generate an error when flag parsing
// fails.
func (c *Command) SetFlagErrorFunc(f func(*Command, error) error) {
@ -496,6 +504,22 @@ func (c *Command) UsageString() string {
return bb.String()
}
// FlagParseFunc returns either the function set by SetFlagParseFunc for this
// command or a parent, or it returns a function which calls the original
// flag parse function.
func (c *Command) FlagParseFunc() (f func(*Command, []string) error) {
if c.flagParseFunc != nil {
return c.flagParseFunc
}
if c.HasParent() {
return c.parent.FlagParseFunc()
}
return func(c *Command, args []string) error {
return c.Flags().Parse(args)
}
}
// FlagErrorFunc returns either the function set by SetFlagErrorFunc for this
// command or a parent, or it returns a function which returns the original
// error.
@ -1846,7 +1870,7 @@ func (c *Command) ParseFlags(args []string) error {
// do it here after merging all flags and just before parse
c.Flags().ParseErrorsWhitelist = flag.ParseErrorsWhitelist(c.FParseErrWhitelist)
err := c.Flags().Parse(args)
err := c.FlagParseFunc()(c, args)
// Print warnings if they occurred (e.g. deprecated flag messages).
if c.flagErrorBuf.Len()-beforeErrorBufLen > 0 && err == nil {
c.Print(c.flagErrorBuf.String())