summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorAlex Flint <[email protected]>2019-05-03 13:07:12 -0700
committerAlex Flint <[email protected]>2019-05-03 13:07:12 -0700
commit3392c173d71a46d4be61c6c0b02c25e37dbd29e2 (patch)
tree71f1ec963f089cce78c211eef7289e3735d48886
parente2ce620ee44f6ef454c46351883971a213c04f68 (diff)
add expected output for usage example
-rw-r--r--example_test.go18
-rw-r--r--parse.go20
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
}