...
1
16
17 package flag
18
19 import (
20 "fmt"
21 "sort"
22 "strconv"
23 "strings"
24 )
25
26
27
28
29 type MapStringBool struct {
30 Map *map[string]bool
31 initialized bool
32 }
33
34
35
36 func NewMapStringBool(m *map[string]bool) *MapStringBool {
37 return &MapStringBool{Map: m}
38 }
39
40
41 func (m *MapStringBool) String() string {
42 if m == nil || m.Map == nil {
43 return ""
44 }
45 pairs := []string{}
46 for k, v := range *m.Map {
47 pairs = append(pairs, fmt.Sprintf("%s=%t", k, v))
48 }
49 sort.Strings(pairs)
50 return strings.Join(pairs, ",")
51 }
52
53
54 func (m *MapStringBool) Set(value string) error {
55 if m.Map == nil {
56 return fmt.Errorf("no target (nil pointer to map[string]bool)")
57 }
58 if !m.initialized || *m.Map == nil {
59
60 *m.Map = make(map[string]bool)
61 m.initialized = true
62 }
63 for _, s := range strings.Split(value, ",") {
64 if len(s) == 0 {
65 continue
66 }
67 arr := strings.SplitN(s, "=", 2)
68 if len(arr) != 2 {
69 return fmt.Errorf("malformed pair, expect string=bool")
70 }
71 k := strings.TrimSpace(arr[0])
72 v := strings.TrimSpace(arr[1])
73 boolValue, err := strconv.ParseBool(v)
74 if err != nil {
75 return fmt.Errorf("invalid value of %s: %s, err: %v", k, v, err)
76 }
77 (*m.Map)[k] = boolValue
78 }
79 return nil
80 }
81
82
83 func (*MapStringBool) Type() string {
84 return "mapStringBool"
85 }
86
87
88 func (m *MapStringBool) Empty() bool {
89 return len(*m.Map) == 0
90 }
91
View as plain text