Skip to content
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

Prefix validation error with argument name #105

Merged
merged 1 commit into from Jul 31, 2022

Conversation

look
Copy link
Contributor

@look look commented Jul 29, 2022

Currently, it is not possible for a custom validation function to know the name of the argument. This prefixes it with the argument name like the built-in validation functions.

The issue I'm trying to solve is that I've built a validation function that I use for multiple options, like this:

func main() {
	validateUint := func(args []string) error {
		if len(args) != 1 {
			return errors.New("must provide a single arg")
		}

		if _, err := strconv.ParseUint(args[0], 10, 32); err != nil {
			return errors.New("must be an integer >= 0")
		}

		return nil
	}

	parser := argparse.NewParser("my-cli", "it does stuff")
	parser.Int("-l", "--limit", &argparse.Options{Validate: validateUint})
	parser.Int("-b", "--batch", &argparse.Options{Validate: validateUint})
}

You can work around this with a unique lambda for each option, but that's kind of frustating, so I figured I'd suggest this change.

The other option I considered was adding a new type of validation function with a signature like func(name string, args []string) error but that would confuse the API or break it.

P.S.: Thanks for this great library!

Currently, it is not possible for a custom validation function to know the name
of the argument. This prefixes it with the argument name like the built-in
functions.
@akamensky
Copy link
Owner

@look Thanks, that is a nice change.

@akamensky akamensky merged commit 31775b7 into akamensky:master Jul 31, 2022
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.

None yet

2 participants