Skip to content

feat: Use structs for errors returned by pflag. #425

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 4 commits into from
Apr 22, 2025

Conversation

eth-p
Copy link

@eth-p eth-p commented Apr 22, 2025

This pull request is the pflag complement to spf13/cobra#2266, converting a bunch of fmt.Errorf errors into structs implementing the error interface.

The goal of this pull request is to make it easier for callers of the Parse function to determine why flag parsing failed without having to resort to regex matching or parsing the returned error message. This pull request goes a bit further than using the %w error-wrapping format verb, opting to use structs as a way to both determine the type of returned error and get specific details about it (e.g. the relevant *pflag.Flag).

Giving callers this info enables them to do new things such as:

  • Printing localized error messages.
  • Changing how the errors are displayed (e.g. pretty printing, colors).

The error structs added are:

  • NotExistError
  • ValueRequiredError
  • InvalidValueError
  • InvalidSyntaxError

Tests have been added as well, and I made sure to maintain compatibility with versions of pflag prior to this pull request by using the exact same error messages.

Add tests to ensure invalid arguments and unknown flag error messages
don't change.
@CLAassistant
Copy link

CLAassistant commented Apr 22, 2025

CLA assistant check
All committers have signed the CLA.

eth-p added 3 commits April 21, 2025 22:06
This allows callers to differentiate between error types without having
to parse the error message string.
Copy link
Collaborator

@tomasaschan tomasaschan left a comment

Choose a reason for hiding this comment

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

Very nice, thanks for your contribution!

@tomasaschan tomasaschan merged commit d661846 into spf13:master Apr 22, 2025
5 checks passed
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