Skip to content

Commit

Permalink
Show default option value in help message
Browse files Browse the repository at this point in the history
  • Loading branch information
Jesse van den Kieboom committed Sep 3, 2012
1 parent 014bce6 commit 50efe78
Show file tree
Hide file tree
Showing 2 changed files with 52 additions and 1 deletion.
45 changes: 45 additions & 0 deletions convert.go
Expand Up @@ -25,6 +25,51 @@ func getBase(options reflect.StructTag, base int) (int, error) {
return base, err
}

func convertToString(val reflect.Value, options reflect.StructTag) string {
tp := val.Type()

switch tp.Kind() {
case reflect.String:
return val.String()
case reflect.Bool:
return ""
case reflect.Int, reflect.Int16, reflect.Int32, reflect.Int64:
base, _ := getBase(options, 10)
return strconv.FormatInt(val.Int(), base)
case reflect.Uint, reflect.Uint16, reflect.Uint32, reflect.Uint64:
base, _ := getBase(options, 10)
return strconv.FormatUint(val.Uint(), base)
case reflect.Float32, reflect.Float64:
return strconv.FormatFloat(val.Float(), 'g', -1, tp.Bits())
case reflect.Slice:
ret := "["

for i := 0; i < val.Len(); i++ {
if i != 0 {
ret += ", "
}

ret += convertToString(val.Index(i), options)
}

return ret + "]"
case reflect.Map:
ret := "{"

for i, key := range val.MapKeys() {
if i != 0 {
ret += ", "
}

ret += convertToString(val.MapIndex(key), options)
}

return ret + "}"
}

return ""
}

func convert(val string, retval reflect.Value, options reflect.StructTag) error {
tp := retval.Type()

Expand Down
8 changes: 7 additions & 1 deletion help.go
Expand Up @@ -59,7 +59,13 @@ func (p *Parser) showHelpOption(writer *bufio.Writer, option *Option, maxlen int
writer.WriteString(strings.Repeat(" ", maxlen-written))
}

writer.WriteString(option.Description)
def := convertToString(option.value, option.options)

if def != "" {
fmt.Fprintf(writer, "%s (%v)", option.Description, def)
} else {
writer.WriteString(option.Description)
}
}

writer.WriteString("\n")
Expand Down

0 comments on commit 50efe78

Please sign in to comment.