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

Move default value next to the flag name in help #3

Merged
merged 2 commits into from
Jul 13, 2019
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
20 changes: 19 additions & 1 deletion help.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,9 @@ import (
"flag"
"fmt"
"io"
"strings"
"text/tabwriter"
"unicode"
"unicode/utf8"
)

Expand All @@ -15,6 +17,22 @@ func flagDashes(name string) string {
return "-"
}

// fmtDefValue adds quotes around default value strings that contain spaces so
// the help representation matches what you would need to do when running a
// command.
func fmtDefValue(value interface{}) string {
switch v := value.(type) {
case string:
if strings.IndexFunc(v, unicode.IsSpace) != -1 {
return fmt.Sprintf(`"%v"`, v)
}
return v

default:
return fmt.Sprintf("%v", v)
}
}

func renderFlagHelp(fl *flag.FlagSet, w io.Writer) {
var count int
fl.VisitAll(func(f *flag.Flag) {
Expand All @@ -26,7 +44,7 @@ func renderFlagHelp(fl *flag.FlagSet, w io.Writer) {
if f.DefValue == "" {
fmt.Fprintf(w, "\t%v%v\t%v\n", flagDashes(f.Name), f.Name, f.Usage)
} else {
fmt.Fprintf(w, "\t%v%v\t%v\t(%v)\n", flagDashes(f.Name), f.Name, f.Usage, f.DefValue)
fmt.Fprintf(w, "\t%v%v=%v\t%v\n", flagDashes(f.Name), f.Name, fmtDefValue(f.DefValue), f.Usage)
}
})
}
Expand Down