-
Notifications
You must be signed in to change notification settings - Fork 1.3k
/
params.go
220 lines (182 loc) · 5.42 KB
/
params.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
package params
import (
"errors"
"fmt"
"reflect"
"strconv"
"strings"
"k8s.io/apimachinery/pkg/api/resource"
)
const (
paramTag = "param"
)
type NotFoundError struct {
Name string
}
func (e NotFoundError) Error() string {
return fmt.Sprintf("%s must be specified", e.Name)
}
func (e NotFoundError) Is(target error) bool {
switch x := target.(type) {
case NotFoundError:
return x.Name == e.Name
case *NotFoundError:
return x.Name == e.Name
}
return false
}
func FlagErr(flagName, format string, a ...any) error {
return fmt.Errorf("failed to parse \"--%s\" flag: %w", flagName, fmt.Errorf(format, a...))
}
/*
The functions below can be used for complicated flags with multiple parameters.
For example, let's think of the following flag: "--my-flag param1:value1,param2:value2".
To automatically define such a flag, the following struct could be defined:
type MyFlag struct {
Param1 string `param:"param1"`
Param2 string `param:"param2"`
}
The functions below use reflection to automatically handle such flags.
*/
// Supported returns the list of supported flags for a parameter struct. This is mainly used to show the user the
// list of supported parameters
func Supported(obj interface{}) string {
objVal := reflect.ValueOf(obj)
if objVal.Kind() != reflect.Struct {
panic("passed in interface needs to be a struct")
}
var params []string
objValType := objVal.Type()
for i := 0; i < objValType.NumField(); i++ {
structField := objValType.Field(i)
k := structField.Tag.Get(paramTag)
if k == "" {
continue
}
t := ""
switch {
case structField.Type.Kind() == reflect.String:
t = structField.Type.String()
case structField.Type == reflect.TypeOf((*uint)(nil)):
t = structField.Type.Elem().String()
case structField.Type == reflect.TypeOf(&resource.Quantity{}):
t = structField.Type.Elem().String()
case structField.Type.Kind() == reflect.Slice && structField.Type.Elem().Kind() == reflect.String:
t = structField.Type.String()
default:
panic(fmt.Errorf("unsupported struct field \"%s\" with kind \"%s\"", structField.Name, structField.Type.Kind()))
}
params = append(params, fmt.Sprintf("%s:%s", k, t))
}
return strings.Join(params, ",")
}
// Map assigns the parameter value into the right struct field, which is represented by obj.
// For example, if we use Map("param1", "value1", &myFlag) with MyFlag struct above, Param1 field would be
// assigned with "value1".
func Map(flagName, paramsStr string, obj interface{}) error {
params, err := split(paramsStr)
if err != nil {
return FlagErr(flagName, "%w", err)
}
err = apply(params, obj)
if err != nil {
return FlagErr(flagName, "%w", err)
}
if len(params) > 0 {
var unknown []string
for k, v := range params {
unknown = append(unknown, fmt.Sprintf("%s:%s", k, v))
}
return FlagErr(flagName, "unknown param(s): %s", strings.Join(unknown, ","))
}
return nil
}
// split parses a flag with multiple parameters into a map
func split(paramsStr string) (map[string]string, error) {
if paramsStr == "" {
return nil, errors.New("params may not be empty")
}
paramsMap := map[string]string{}
s := strings.Split(paramsStr, ",")
for _, param := range s {
sParam := strings.SplitN(param, ":", 2)
if len(sParam) != 2 {
return nil, fmt.Errorf("params need to have at least one colon: %s", param)
}
paramsMap[sParam[0]] = sParam[1]
}
return paramsMap, nil
}
// apply assigns the different parameters into obj's corresponding fields
func apply(paramsMap map[string]string, obj interface{}) error {
objVal := reflect.ValueOf(obj)
if objVal.Kind() != reflect.Ptr {
panic("passed in interface needs to be a pointer")
}
objValElem := objVal.Elem()
if objValElem.Kind() != reflect.Struct {
panic("passed in pointer needs to point to a struct")
}
objValElemType := objValElem.Type()
for i := 0; i < objValElemType.NumField(); i++ {
structField := objValElemType.Field(i)
k := structField.Tag.Get(paramTag)
if k == "" {
continue
}
v, ok := paramsMap[k]
if !ok {
continue
}
field := objValElem.Field(i)
switch {
case field.Kind() == reflect.String:
field.SetString(v)
case field.Type() == reflect.TypeOf((*uint)(nil)):
u64, err := strconv.ParseUint(v, 10, 32)
if err != nil {
return fmt.Errorf("failed to parse param \"%s\": %w", k, err)
}
u := uint(u64)
field.Set(reflect.ValueOf(&u))
case field.Type() == reflect.TypeOf(&resource.Quantity{}):
quantity, err := resource.ParseQuantity(v)
if err != nil {
return fmt.Errorf("failed to parse param \"%s\": %w", k, err)
}
field.Set(reflect.ValueOf(&quantity))
default:
panic(fmt.Errorf("unsupported struct field \"%s\" with kind \"%s\"", structField.Name, field.Kind()))
}
delete(paramsMap, k)
}
return nil
}
// SplitPrefixedName splits prefixedName with "/" as a separator
func SplitPrefixedName(prefixedName string) (prefix string, name string, err error) {
s := strings.Split(prefixedName, "/")
switch l := len(s); l {
case 1:
name = s[0]
case 2:
prefix = s[0]
name = s[1]
default:
return "", "", fmt.Errorf("invalid count %d of slashes in prefix/name", l)
}
if name == "" {
return "", "", errors.New("name cannot be empty")
}
return
}
func GetParamByName(paramName, paramsStr string) (string, error) {
paramsMap, err := split(paramsStr)
if err != nil {
return "", err
}
paramValue, exists := paramsMap[paramName]
if !exists {
return "", &NotFoundError{Name: paramName}
}
return paramValue, nil
}