Browse code

fix panic in mflag

Docker-DCO-1.1-Signed-off-by: Victor Vieux <victor.vieux@docker.com> (github: vieux)

Victor Vieux authored on 2014/02/01 04:33:48
Showing 3 changed files
... ...
@@ -6,13 +6,14 @@ import (
6 6
 )
7 7
 
8 8
 var (
9
-	i    int
10
-	str  string
11
-	b, h bool
9
+	i        int
10
+	str      string
11
+	b, b2, h bool
12 12
 )
13 13
 
14 14
 func init() {
15 15
 	flag.BoolVar(&b, []string{"b"}, false, "a simple bool")
16
+	flag.BoolVar(&b2, []string{"-bool"}, false, "a simple bool")
16 17
 	flag.IntVar(&i, []string{"#integer", "-integer"}, -1, "a simple integer")
17 18
 	flag.StringVar(&str, []string{"s", "#hidden", "-string"}, "", "a simple string") //-s -hidden and --string will work, but -hidden won't be in the usage
18 19
 	flag.BoolVar(&h, []string{"h", "#help", "-help"}, false, "display the help")
... ...
@@ -22,6 +23,8 @@ func main() {
22 22
 	if h {
23 23
 		flag.PrintDefaults()
24 24
 	}
25
-	fmt.Printf("%s\n", str)
26
-	fmt.Printf("%s\n", flag.Lookup("s").Value.String())
25
+	fmt.Printf("s/#hidden/-string: %s\n", str)
26
+	fmt.Printf("b: %b\n", b)
27
+	fmt.Printf("-bool: %b\n", b2)
28
+	fmt.Printf("s/#hidden/-string(via lookup): %s\n", flag.Lookup("s").Value.String())
27 29
 }
... ...
@@ -287,6 +287,11 @@ type Flag struct {
287 287
 func sortFlags(flags map[string]*Flag) []*Flag {
288 288
 	var list sort.StringSlice
289 289
 	for _, f := range flags {
290
+		if len(f.Names) == 1 {
291
+			list = append(list, f.Names[0])
292
+			continue
293
+		}
294
+
290 295
 		found := false
291 296
 		fName := strings.TrimPrefix(strings.TrimPrefix(f.Names[0], "#"), "-")
292 297
 		for _, name := range list {
... ...
@@ -228,6 +228,22 @@ func testParse(f *FlagSet, t *testing.T) {
228 228
 	}
229 229
 }
230 230
 
231
+func testPanic(f *FlagSet, t *testing.T) {
232
+	f.Int([]string{"-int"}, 0, "int value")
233
+	if f.Parsed() {
234
+		t.Error("f.Parse() = true before Parse")
235
+	}
236
+	args := []string{
237
+		"-int", "21",
238
+	}
239
+	f.Parse(args)
240
+}
241
+
242
+func TestParsePanic(t *testing.T) {
243
+	ResetForTesting(func() {})
244
+	testPanic(CommandLine, t)
245
+}
246
+
231 247
 func TestParse(t *testing.T) {
232 248
 	ResetForTesting(func() { t.Error("bad parse") })
233 249
 	testParse(CommandLine, t)