Skip to content
This repository was archived by the owner on Oct 17, 2021. It is now read-only.

Commit 9949b82

Browse files
authored
Merge pull request #3 from cdr/move-def-value
Move default value next to the flag name in help
2 parents 16565d5 + 7a3bd25 commit 9949b82

File tree

1 file changed

+19
-1
lines changed

1 file changed

+19
-1
lines changed

help.go

Lines changed: 19 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,9 @@ import (
44
"flag"
55
"fmt"
66
"io"
7+
"strings"
78
"text/tabwriter"
9+
"unicode"
810
"unicode/utf8"
911
)
1012

@@ -15,6 +17,22 @@ func flagDashes(name string) string {
1517
return "-"
1618
}
1719

20+
// fmtDefValue adds quotes around default value strings that contain spaces so
21+
// the help representation matches what you would need to do when running a
22+
// command.
23+
func fmtDefValue(value interface{}) string {
24+
switch v := value.(type) {
25+
case string:
26+
if strings.IndexFunc(v, unicode.IsSpace) != -1 {
27+
return fmt.Sprintf(`"%v"`, v)
28+
}
29+
return v
30+
31+
default:
32+
return fmt.Sprintf("%v", v)
33+
}
34+
}
35+
1836
func renderFlagHelp(fl *flag.FlagSet, w io.Writer) {
1937
var count int
2038
fl.VisitAll(func(f *flag.Flag) {
@@ -26,7 +44,7 @@ func renderFlagHelp(fl *flag.FlagSet, w io.Writer) {
2644
if f.DefValue == "" {
2745
fmt.Fprintf(w, "\t%v%v\t%v\n", flagDashes(f.Name), f.Name, f.Usage)
2846
} else {
29-
fmt.Fprintf(w, "\t%v%v\t%v\t(%v)\n", flagDashes(f.Name), f.Name, f.Usage, f.DefValue)
47+
fmt.Fprintf(w, "\t%v%v=%v\t%v\n", flagDashes(f.Name), f.Name, fmtDefValue(f.DefValue), f.Usage)
3048
}
3149
})
3250
}

0 commit comments

Comments
 (0)