blob: bf8dbfb9bfc8216f91c9976c3ef55937ea02288a [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 "strings"
23)
24
25// LangleSeparatedMapStringString can be set from the command line with the format `--flag "string<string"`.
26// Multiple comma-separated key-value pairs in a single invocation are supported. For example: `--flag "a<foo,b<bar"`.
27// Multiple flag invocations are supported. For example: `--flag "a<foo" --flag "b<foo"`.
28type LangleSeparatedMapStringString struct {
29 Map *map[string]string
30 initialized bool // set to true after first Set call
31}
32
33// NewLangleSeparatedMapStringString takes a pointer to a map[string]string and returns the
34// LangleSeparatedMapStringString flag parsing shim for that map
35func NewLangleSeparatedMapStringString(m *map[string]string) *LangleSeparatedMapStringString {
36 return &LangleSeparatedMapStringString{Map: m}
37}
38
39// String implements github.com/spf13/pflag.Value
40func (m *LangleSeparatedMapStringString) String() string {
41 pairs := []string{}
42 for k, v := range *m.Map {
43 pairs = append(pairs, fmt.Sprintf("%s<%s", k, v))
44 }
45 sort.Strings(pairs)
46 return strings.Join(pairs, ",")
47}
48
49// Set implements github.com/spf13/pflag.Value
50func (m *LangleSeparatedMapStringString) Set(value string) error {
51 if m.Map == nil {
52 return fmt.Errorf("no target (nil pointer to map[string]string)")
53 }
54 if !m.initialized || *m.Map == nil {
55 // clear default values, or allocate if no existing map
56 *m.Map = make(map[string]string)
57 m.initialized = true
58 }
59 for _, s := range strings.Split(value, ",") {
60 if len(s) == 0 {
61 continue
62 }
63 arr := strings.SplitN(s, "<", 2)
64 if len(arr) != 2 {
65 return fmt.Errorf("malformed pair, expect string<string")
66 }
67 k := strings.TrimSpace(arr[0])
68 v := strings.TrimSpace(arr[1])
69 (*m.Map)[k] = v
70 }
71 return nil
72}
73
74// Type implements github.com/spf13/pflag.Value
75func (*LangleSeparatedMapStringString) Type() string {
76 return "mapStringString"
77}
78
79// Empty implements OmitEmpty
80func (m *LangleSeparatedMapStringString) Empty() bool {
81 return len(*m.Map) == 0
82}