fix case where os.Args is empty

This commit is contained in:
Alex Flint 2017-02-09 15:12:33 -08:00
parent b658405f70
commit ec576f9765
2 changed files with 24 additions and 2 deletions

View File

@ -36,7 +36,7 @@ func MustParse(dest ...interface{}) *Parser {
fmt.Println(err) fmt.Println(err)
os.Exit(-1) os.Exit(-1)
} }
err = p.Parse(os.Args[1:]) err = p.Parse(flags())
if err == ErrHelp { if err == ErrHelp {
p.WriteHelp(os.Stdout) p.WriteHelp(os.Stdout)
os.Exit(0) os.Exit(0)
@ -57,7 +57,15 @@ func Parse(dest ...interface{}) error {
if err != nil { if err != nil {
return err return err
} }
return p.Parse(os.Args[1:]) return p.Parse(flags())
}
// flags gets all command line arguments other than the first (program name)
func flags() []string {
if len(os.Args) == 0 { // os.Args could be empty
return nil
}
return os.Args[1:]
} }
// Config represents configuration options for an argument parser // Config represents configuration options for an argument parser

View File

@ -654,3 +654,17 @@ func TestEmbedded(t *testing.T) {
assert.Equal(t, 321, args.Y) assert.Equal(t, 321, args.Y)
assert.Equal(t, true, args.Z) assert.Equal(t, true, args.Z)
} }
func TestEmptyArgs(t *testing.T) {
origArgs := os.Args
// test what happens if somehow os.Args is empty
os.Args = nil
var args struct {
Foo string
}
MustParse(&args)
// put the original arguments back
os.Args = origArgs
}