Browse Source

fix panic in mflag

Docker-DCO-1.1-Signed-off-by: Victor Vieux <victor.vieux@docker.com> (github: vieux)
Victor Vieux 11 năm trước cách đây
mục cha
commit
65794a2c49
3 tập tin đã thay đổi với 29 bổ sung5 xóa
  1. 8 5
      pkg/mflag/example/example.go
  2. 5 0
      pkg/mflag/flag.go
  3. 16 0
      pkg/mflag/flag_test.go

+ 8 - 5
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())
 }

+ 5 - 0
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 {

+ 16 - 0
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)