From ec576f9765c4a5918918921e35a82f0907d77d36 Mon Sep 17 00:00:00 2001 From: Alex Flint Date: Thu, 9 Feb 2017 15:12:33 -0800 Subject: [PATCH] fix case where os.Args is empty --- parse.go | 12 ++++++++++-- parse_test.go | 14 ++++++++++++++ 2 files changed, 24 insertions(+), 2 deletions(-) diff --git a/parse.go b/parse.go index 3cd00aa..a47f464 100644 --- a/parse.go +++ b/parse.go @@ -36,7 +36,7 @@ func MustParse(dest ...interface{}) *Parser { fmt.Println(err) os.Exit(-1) } - err = p.Parse(os.Args[1:]) + err = p.Parse(flags()) if err == ErrHelp { p.WriteHelp(os.Stdout) os.Exit(0) @@ -57,7 +57,15 @@ func Parse(dest ...interface{}) error { if err != nil { 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 diff --git a/parse_test.go b/parse_test.go index dffebf4..8779b6f 100644 --- a/parse_test.go +++ b/parse_test.go @@ -654,3 +654,17 @@ func TestEmbedded(t *testing.T) { assert.Equal(t, 321, args.Y) 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 +}