Merge pull request #25 from alexflint/return_parser_from_mustparse

MustParse returns *Parser
This commit is contained in:
Alex Flint 2016-01-05 16:52:13 -08:00
commit f8ea16beee
3 changed files with 22 additions and 2 deletions

View File

@ -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] 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 ### Installation
```shell ```shell

View File

@ -26,7 +26,7 @@ type spec struct {
var ErrHelp = errors.New("help requested by user") var ErrHelp = errors.New("help requested by user")
// MustParse processes command line arguments and exits upon failure // MustParse processes command line arguments and exits upon failure
func MustParse(dest ...interface{}) { func MustParse(dest ...interface{}) *Parser {
p, err := NewParser(dest...) p, err := NewParser(dest...)
if err != nil { if err != nil {
fmt.Println(err) fmt.Println(err)
@ -40,6 +40,7 @@ func MustParse(dest ...interface{}) {
if err != nil { if err != nil {
p.Fail(err.Error()) p.Fail(err.Error())
} }
return p
} }
// Parse processes command line arguments and stores them in dest // Parse processes command line arguments and stores them in dest

View File

@ -353,6 +353,7 @@ func TestMustParse(t *testing.T) {
Foo string Foo string
} }
os.Args = []string{"example", "--foo", "bar"} os.Args = []string{"example", "--foo", "bar"}
MustParse(&args) parser := MustParse(&args)
assert.Equal(t, "bar", args.Foo) assert.Equal(t, "bar", args.Foo)
assert.NotNil(t, parser)
} }