From 65794a2c4960f9065ee439d6823ffe670610dbb6 Mon Sep 17 00:00:00 2001 From: Victor Vieux Date: Fri, 31 Jan 2014 11:33:48 -0800 Subject: [PATCH] fix panic in mflag Docker-DCO-1.1-Signed-off-by: Victor Vieux (github: vieux) --- pkg/mflag/example/example.go | 13 ++++++++----- pkg/mflag/flag.go | 5 +++++ pkg/mflag/flag_test.go | 16 ++++++++++++++++ 3 files changed, 29 insertions(+), 5 deletions(-) diff --git a/pkg/mflag/example/example.go b/pkg/mflag/example/example.go index 543592d23b..fa26c97e1b 100644 --- a/pkg/mflag/example/example.go +++ b/pkg/mflag/example/example.go @@ -6,13 +6,14 @@ import ( ) var ( - i int - str string - b, h bool + i int + str string + b, b2, h bool ) func init() { flag.BoolVar(&b, []string{"b"}, false, "a simple bool") + flag.BoolVar(&b2, []string{"-bool"}, false, "a simple bool") flag.IntVar(&i, []string{"#integer", "-integer"}, -1, "a simple integer") flag.StringVar(&str, []string{"s", "#hidden", "-string"}, "", "a simple string") //-s -hidden and --string will work, but -hidden won't be in the usage flag.BoolVar(&h, []string{"h", "#help", "-help"}, false, "display the help") @@ -22,6 +23,8 @@ func main() { if h { flag.PrintDefaults() } - fmt.Printf("%s\n", str) - fmt.Printf("%s\n", flag.Lookup("s").Value.String()) + fmt.Printf("s/#hidden/-string: %s\n", str) + fmt.Printf("b: %b\n", b) + fmt.Printf("-bool: %b\n", b2) + fmt.Printf("s/#hidden/-string(via lookup): %s\n", flag.Lookup("s").Value.String()) } diff --git a/pkg/mflag/flag.go b/pkg/mflag/flag.go index 8e22c0e959..f721e04557 100644 --- a/pkg/mflag/flag.go +++ b/pkg/mflag/flag.go @@ -287,6 +287,11 @@ type Flag struct { func sortFlags(flags map[string]*Flag) []*Flag { var list sort.StringSlice for _, f := range flags { + if len(f.Names) == 1 { + list = append(list, f.Names[0]) + continue + } + found := false fName := strings.TrimPrefix(strings.TrimPrefix(f.Names[0], "#"), "-") for _, name := range list { diff --git a/pkg/mflag/flag_test.go b/pkg/mflag/flag_test.go index 631febca47..b9e8a0ef3e 100644 --- a/pkg/mflag/flag_test.go +++ b/pkg/mflag/flag_test.go @@ -228,6 +228,22 @@ func testParse(f *FlagSet, t *testing.T) { } } +func testPanic(f *FlagSet, t *testing.T) { + f.Int([]string{"-int"}, 0, "int value") + if f.Parsed() { + t.Error("f.Parse() = true before Parse") + } + args := []string{ + "-int", "21", + } + f.Parse(args) +} + +func TestParsePanic(t *testing.T) { + ResetForTesting(func() {}) + testPanic(CommandLine, t) +} + func TestParse(t *testing.T) { ResetForTesting(func() { t.Error("bad parse") }) testParse(CommandLine, t)