diff options
| -rw-r--r-- | README.md | 18 | ||||
| -rw-r--r-- | parse.go | 3 | ||||
| -rw-r--r-- | parse_test.go | 3 |
3 files changed, 22 insertions, 2 deletions
@@ -108,6 +108,24 @@ fmt.Printf("Fetching the following IDs from %s: %q", args.Database, args.IDs) Fetching the following IDs from foo: [1 2 3] ``` +### Custom validation +```go +var args struct { + Foo string + Bar string +} +p := arg.MustParse(&args) +if args.Foo == "" && args.Bar == "" { + p.Fail("you must provide one of --foo and --bar") +} +``` + +```shell +./example +usage: samples [--foo FOO] [--bar BAR] +error: you must provide one of --foo and --bar +``` + ### Installation ```shell @@ -26,7 +26,7 @@ type spec struct { var ErrHelp = errors.New("help requested by user") // MustParse processes command line arguments and exits upon failure -func MustParse(dest ...interface{}) { +func MustParse(dest ...interface{}) *Parser { p, err := NewParser(dest...) if err != nil { fmt.Println(err) @@ -40,6 +40,7 @@ func MustParse(dest ...interface{}) { if err != nil { p.Fail(err.Error()) } + return p } // Parse processes command line arguments and stores them in dest diff --git a/parse_test.go b/parse_test.go index eb6080c..7fca76a 100644 --- a/parse_test.go +++ b/parse_test.go @@ -353,6 +353,7 @@ func TestMustParse(t *testing.T) { Foo string } os.Args = []string{"example", "--foo", "bar"} - MustParse(&args) + parser := MustParse(&args) assert.Equal(t, "bar", args.Foo) + assert.NotNil(t, parser) } |
