Skip to content

Commit

Permalink
flag: recognize "0s" as the zero value for a flag.Duration
Browse files Browse the repository at this point in the history
Implemented by using a reflect-based approach to recognize the zero
value of any non-interface type that implements flag.Value.  Interface
types will fall back to the old code.

Fixes #15904.

Change-Id: I594c3bfb30e9ab1aca3e008ef7f70be20aa41a0b
Reviewed-on: https://go-review.googlesource.com/23581
Run-TryBot: Ian Lance Taylor <[email protected]>
TryBot-Result: Gobot Gobot <[email protected]>
Reviewed-by: Rob Pike <[email protected]>
  • Loading branch information
ianlancetaylor committed May 31, 2016
1 parent 8003e79 commit 3659645
Show file tree
Hide file tree
Showing 2 changed files with 18 additions and 3 deletions.
19 changes: 17 additions & 2 deletions src/flag/flag.go
Original file line number Diff line number Diff line change
Expand Up @@ -68,6 +68,7 @@ import (
"fmt"
"io"
"os"
"reflect"
"sort"
"strconv"
"time"
Expand Down Expand Up @@ -378,7 +379,21 @@ func Set(name, value string) error {

// isZeroValue guesses whether the string represents the zero
// value for a flag. It is not accurate but in practice works OK.
func isZeroValue(value string) bool {
func isZeroValue(flag *Flag, value string) bool {
// Build a zero value of the flag's Value type, and see if the
// result of calling its String method equals the value passed in.
// This works unless the Value type is itself an interface type.
typ := reflect.TypeOf(flag.Value)
var z reflect.Value
if typ.Kind() == reflect.Ptr {
z = reflect.New(typ.Elem())
} else {
z = reflect.Zero(typ)
}
if value == z.Interface().(Value).String() {
return true
}

switch value {
case "false":
return true
Expand Down Expand Up @@ -449,7 +464,7 @@ func (f *FlagSet) PrintDefaults() {
s += "\n \t"
}
s += usage
if !isZeroValue(flag.DefValue) {
if !isZeroValue(flag, flag.DefValue) {
if _, ok := flag.Value.(*stringValue); ok {
// put quotes on the value
s += fmt.Sprintf(" (default %q)", flag.DefValue)
Expand Down
2 changes: 1 addition & 1 deletion src/flag/flag_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -393,7 +393,7 @@ const defaultOutput = ` -A for bootstrapping, allow 'any' type
-Z int
an int that defaults to zero
-maxT timeout
set timeout for dial (default 0s)
set timeout for dial
`

func TestPrintDefaults(t *testing.T) {
Expand Down

0 comments on commit 3659645

Please sign in to comment.