Skip to content

Commit

Permalink
ability to ignore undefined flags per parser
Browse files Browse the repository at this point in the history
  • Loading branch information
gobwas committed Dec 10, 2020
1 parent 5386ade commit 35ba11b
Show file tree
Hide file tree
Showing 3 changed files with 20 additions and 5 deletions.
7 changes: 6 additions & 1 deletion flagutil.go
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,8 @@ func (fn PrinterFunc) Name(ctx context.Context, fs parse.FlagSet) (func(*flag.Fl

type parser struct {
Parser
stash func(*flag.Flag) bool
stash func(*flag.Flag) bool
ignoreUndefined bool
}

type config struct {
Expand Down Expand Up @@ -72,6 +73,10 @@ func Parse(ctx context.Context, flags *flag.FlagSet, opts ...ParseOption) (err e
for _, p := range c.parsers {
parse.NextLevel(fs)
parse.Stash(fs, p.stash)
if p.ignoreUndefined {
// User may ask to ignore undefined per parser as well.
parse.IgnoreUndefined(fs)
}

if err = p.Parse(ctx, fs); err != nil {
if err == flag.ErrHelp {
Expand Down
13 changes: 9 additions & 4 deletions options.go
Original file line number Diff line number Diff line change
Expand Up @@ -28,8 +28,8 @@ func (fn ParseOptionFunc) setupParseConfig(c *config) { fn(c) }

type ParserOptionFunc func(*config, *parser)

func (fn ParserOptionFunc) setupParserConfig(p *parser) { fn(nil, p) }
func (fn ParserOptionFunc) setupParseConfig(c *config) { fn(c, nil) }
func (fn ParserOptionFunc) setupParserConfig(p *parser) { fn(nil, p) }

func stashFunc(check func(*flag.Flag) bool) (opt ParserOptionFunc) {
return ParserOptionFunc(func(c *config, p *parser) {
Expand Down Expand Up @@ -79,9 +79,14 @@ func WithParser(p Parser, opts ...ParserOption) ParseOptionFunc {
}

// WithIgnoreUndefined makes Parse() to not fail on setting undefined flag.
func WithIgnoreUndefined() ParseOptionFunc {
return ParseOptionFunc(func(c *config) {
c.ignoreUndefined = true
func WithIgnoreUndefined() ParserOptionFunc {
return ParserOptionFunc(func(c *config, p *parser) {
switch {
case c != nil:
c.ignoreUndefined = true
case p != nil:
p.ignoreUndefined = true
}
})
}

Expand Down
5 changes: 5 additions & 0 deletions parse/flagset.go
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,11 @@ func Stash(fs FlagSet, fn func(*flag.Flag) bool) {
fset.stash = fn
}

func IgnoreUndefined(fs FlagSet) {
fset := fs.(*flagSet)
fset.ignoreUndefined = true
}

type flagSet struct {
dest *flag.FlagSet
ignoreUndefined bool
Expand Down

0 comments on commit 35ba11b

Please sign in to comment.