akamensky / argparse

Argparse for golang. Just because `flag` sucks
MIT License
604 stars 62 forks source link

Prefix validation error with argument name #105

Closed look closed 2 years ago

look commented 2 years ago

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!

akamensky commented 2 years ago

@look Thanks, that is a nice change.