blob: e5a01805b02ae0ce3f6b52c27c8de519034fd392 [file] [log] [blame]
Matthias Andreas Benkard832a54e2019-01-29 09:27:38 +01001/*
2Copyright 2017 The Kubernetes Authors.
3
4Licensed under the Apache License, Version 2.0 (the "License");
5you may not use this file except in compliance with the License.
6You may obtain a copy of the License at
7
8 http://www.apache.org/licenses/LICENSE-2.0
9
10Unless required by applicable law or agreed to in writing, software
11distributed under the License is distributed on an "AS IS" BASIS,
12WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13See the License for the specific language governing permissions and
14limitations under the License.
15*/
16
17package flag
18
19import (
20 "fmt"
21 "sort"
22 "strconv"
23 "strings"
24)
25
26// MapStringBool can be set from the command line with the format `--flag "string=bool"`.
27// Multiple comma-separated key-value pairs in a single invocation are supported. For example: `--flag "a=true,b=false"`.
28// Multiple flag invocations are supported. For example: `--flag "a=true" --flag "b=false"`.
29type MapStringBool struct {
30 Map *map[string]bool
31 initialized bool
32}
33
34// NewMapStringBool takes a pointer to a map[string]string and returns the
35// MapStringBool flag parsing shim for that map
36func NewMapStringBool(m *map[string]bool) *MapStringBool {
37 return &MapStringBool{Map: m}
38}
39
40// String implements github.com/spf13/pflag.Value
41func (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// Set implements github.com/spf13/pflag.Value
54func (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 // clear default values, or allocate if no existing map
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// Type implements github.com/spf13/pflag.Value
83func (*MapStringBool) Type() string {
84 return "mapStringBool"
85}
86
87// Empty implements OmitEmpty
88func (m *MapStringBool) Empty() bool {
89 return len(*m.Map) == 0
90}