Merge pull request from walle/add_default_value_to_usage

Add default values to usage
This commit is contained in:
Alex Flint 2015-11-26 22:10:36 +10:30
commit ce5525d776
2 changed files with 18 additions and 2 deletions

View File

@ -5,6 +5,7 @@ import (
"io" "io"
"os" "os"
"path/filepath" "path/filepath"
"reflect"
"strings" "strings"
) )
@ -101,6 +102,15 @@ func printOption(w io.Writer, spec *spec) {
} }
fmt.Fprint(w, spec.help) fmt.Fprint(w, spec.help)
} }
// Check if spec.dest is zero value or not
// If it isn't a default value have been added
v := spec.dest
if v.IsValid() {
z := reflect.Zero(v.Type())
if v.Interface() != z.Interface() {
fmt.Fprintf(w, " [default: %v]", v)
}
}
fmt.Fprint(w, "\n") fmt.Fprint(w, "\n")
} }

View File

@ -10,15 +10,17 @@ import (
) )
func TestWriteUsage(t *testing.T) { func TestWriteUsage(t *testing.T) {
expectedUsage := "usage: example [--verbose] [--dataset DATASET] [--optimize OPTIMIZE] INPUT [OUTPUT [OUTPUT ...]]\n" expectedUsage := "usage: example [--name NAME] [--value VALUE] [--verbose] [--dataset DATASET] [--optimize OPTIMIZE] INPUT [OUTPUT [OUTPUT ...]]\n"
expectedHelp := `usage: example [--verbose] [--dataset DATASET] [--optimize OPTIMIZE] INPUT [OUTPUT [OUTPUT ...]] expectedHelp := `usage: example [--name NAME] [--value VALUE] [--verbose] [--dataset DATASET] [--optimize OPTIMIZE] INPUT [OUTPUT [OUTPUT ...]]
positional arguments: positional arguments:
input input
output output
options: options:
--name NAME name to use [default: Foo Bar]
--value VALUE secret value [default: 42]
--verbose, -v verbosity level --verbose, -v verbosity level
--dataset DATASET dataset to use --dataset DATASET dataset to use
--optimize OPTIMIZE, -O OPTIMIZE --optimize OPTIMIZE, -O OPTIMIZE
@ -28,10 +30,14 @@ options:
var args struct { var args struct {
Input string `arg:"positional"` Input string `arg:"positional"`
Output []string `arg:"positional"` Output []string `arg:"positional"`
Name string `arg:"help:name to use"`
Value int `arg:"help:secret value"`
Verbose bool `arg:"-v,help:verbosity level"` Verbose bool `arg:"-v,help:verbosity level"`
Dataset string `arg:"help:dataset to use"` Dataset string `arg:"help:dataset to use"`
Optimize int `arg:"-O,help:optimization level"` Optimize int `arg:"-O,help:optimization level"`
} }
args.Name = "Foo Bar"
args.Value = 42
p, err := NewParser(&args) p, err := NewParser(&args)
require.NoError(t, err) require.NoError(t, err)