Add default values to usage

Check if the value isn't it's zero value and if not add a default value
to the usage text.
This commit is contained in:
Fredrik Wallgren 2015-11-19 14:34:09 +01:00
parent 5db9c77fa3
commit b0d37d1fb2
2 changed files with 15 additions and 3 deletions

View File

@ -76,7 +76,6 @@ func (p *Parser) WriteHelp(w io.Writer) {
} }
} }
// write the list of options
fmt.Fprint(w, "\noptions:\n") fmt.Fprint(w, "\noptions:\n")
for _, spec := range options { for _, spec := range options {
printOption(w, spec) printOption(w, spec)
@ -101,6 +100,13 @@ 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
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)