Skip to content

Conversation

icholy
Copy link
Contributor

@icholy icholy commented Jul 12, 2022

What type of PR is this?

  • feature

What this PR does / why we need it:

The current behaviour returns a zero value when accessing an undefined flag. This hides programmer errors and has resulted in several bugs on my end.

Which issue(s) this PR fixes:

#1408

Testing

I added tests which make sure Context.Set and Context.Value panic when accessing an undefined flag.

Release Notes

A new `App.EnableStrictLookup` option which causes undefined flag lookups to panic

@icholy icholy requested a review from a team as a code owner July 12, 2022 14:21
Copy link
Member

@meatballhat meatballhat left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thank you for adding this!

I would like to see two changes:

  • statically define an error type (cli.ErrStrictFlagLookup?) that can be reliably checked via funcs like errors.Is
  • return this error instead of using panic

@icholy
Copy link
Contributor Author

icholy commented Jul 16, 2022

Where would I return this error? The flag value getters don't return errors.

edit: Oh you mean for cli.Context.Set. That makes sense.

I'm thinking:

type FlagNotFoundError struct {
	Name string
}

func (e FlagNotFoundError) Error() string {
	return fmt.Sprintf("flag not found: %q", e.Name)
}
  • Context.Set would return this error.
  • Context.Get (and friends) will panic with this error.

@meatballhat
Copy link
Member

@icholy yes! Sorry for not being clear about that distinction. What you propose LGTM 🤘🏼

@julian7
Copy link
Contributor

julian7 commented Jul 16, 2022

I'm also wondering whether handling this event via a hook would be more powerful.

Like, instead of having App. EnableStrictLookup boolean, we could have an App.UnknownFlagHandler or something like that. Then, the implementer can decide whether the app should throw panic(), whether it should log it, or perhaps even change context on such an event.

@icholy
Copy link
Contributor Author

icholy commented Jul 16, 2022

@julian7 that's an interesting idea. Something like this?

type App struct {
    // ...
    UnknownFlagHandler func(ctx *Context, name string)
}

@meatballhat
Copy link
Member

I'm also wondering whether handling this event via a hook would be more powerful.

Oooh I like that idea a lot @julian7

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

3 participants