From 3392c173d71a46d4be61c6c0b02c25e37dbd29e2 Mon Sep 17 00:00:00 2001 From: Alex Flint Date: Fri, 3 May 2019 13:07:12 -0700 Subject: [PATCH] add expected output for usage example --- example_test.go | 18 ++++++++++++++++++ parse.go | 20 ++++++++++++-------- 2 files changed, 30 insertions(+), 8 deletions(-) diff --git a/example_test.go b/example_test.go index 7ae2df1..72807a7 100644 --- a/example_test.go +++ b/example_test.go @@ -115,5 +115,23 @@ func Example_usageString() { Dataset string `help:"dataset to use"` Optimize int `arg:"-O,help:optimization level"` } + + // This is only necessary when running inside golang's runnable example harness + osExit = func(int) {} + MustParse(&args) + + // output: + // Usage: example [--verbose] [--dataset DATASET] [--optimize OPTIMIZE] INPUT [OUTPUT [OUTPUT ...]] + // + // Positional arguments: + // INPUT + // OUTPUT + // + // Options: + // --verbose, -v verbosity level + // --dataset DATASET dataset to use + // --optimize OPTIMIZE, -O OPTIMIZE + // optimization level + // --help, -h display this help and exit } diff --git a/parse.go b/parse.go index 32fc619..e23731c 100644 --- a/parse.go +++ b/parse.go @@ -13,6 +13,9 @@ import ( scalar "github.com/alexflint/go-scalar" ) +// to enable monkey-patching during tests +var osExit = os.Exit + // spec represents a command line option type spec struct { dest reflect.Value @@ -38,20 +41,21 @@ func MustParse(dest ...interface{}) *Parser { p, err := NewParser(Config{}, dest...) if err != nil { fmt.Println(err) - os.Exit(-1) + osExit(-1) } + err = p.Parse(flags()) - if err == ErrHelp { + switch { + case err == ErrHelp: p.WriteHelp(os.Stdout) - os.Exit(0) - } - if err == ErrVersion { + osExit(0) + case err == ErrVersion: fmt.Println(p.version) - os.Exit(0) - } - if err != nil { + osExit(0) + case err != nil: p.Fail(err.Error()) } + return p }