-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcli.go
441 lines (356 loc) · 11.1 KB
/
cli.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
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
package confy
import (
"encoding"
"errors"
"flag"
"fmt"
"log/slog"
"os"
"path/filepath"
"reflect"
"strconv"
"strings"
)
type stringSlice struct {
target *[]string
}
func newStringSlice(target interface{}) *stringSlice {
t, ok := target.(*[]string)
if !ok {
panic("could not cast something that was suppose to be a pointer to a string slice")
}
return &stringSlice{
target: t,
}
}
func (s *stringSlice) String() string {
if s == nil || s.target == nil {
return ""
}
return strings.Join(*s.target, ",")
}
func (s *stringSlice) Set(value string) error {
if s == nil || s.target == nil {
return errors.New("nil")
}
*s.target = strings.Split(value, ",")
return nil
}
type intSlice struct {
target *[]int
}
func newIntSlice(target interface{}) *intSlice {
t, ok := target.(*[]int)
if !ok {
panic("could not cast something that was suppose to be a pointer to a int slice")
}
return &intSlice{
target: t,
}
}
func (s *intSlice) String() string {
if s == nil || s.target == nil {
return ""
}
var result []string
for _, i := range *s.target {
result = append(result, fmt.Sprintf("%d", i))
}
return strings.Join(result, ",")
}
func (s *intSlice) Set(value string) error {
if s == nil || s.target == nil {
return errors.New("nil")
}
for _, potentialInt := range strings.Split(value, ",") {
i, err := strconv.Atoi(potentialInt)
if err != nil {
return err
}
*s.target = append(*s.target, i)
}
return nil
}
type floatSlice struct {
target *[]float64
}
func newFloatSlice(target interface{}) *floatSlice {
t, ok := target.(*[]float64)
if !ok {
panic("could not cast something that was suppose to be a pointer to a float slice")
}
return &floatSlice{
target: t,
}
}
func (s *floatSlice) String() string {
if s == nil || s.target == nil {
return ""
}
var result []string
for _, i := range *s.target {
result = append(result, fmt.Sprintf("%f", i))
}
return strings.Join(result, ",")
}
func (s *floatSlice) Set(value string) error {
if s == nil || s.target == nil {
return errors.New("nil")
}
for _, potentialFloat := range strings.Split(value, ",") {
i, err := strconv.ParseFloat(potentialFloat, 64)
if err != nil {
return err
}
*s.target = append(*s.target, i)
}
return nil
}
type boolSlice struct {
target *[]bool
}
func newBoolSlice(target interface{}) *boolSlice {
t, ok := target.(*[]bool)
if !ok {
panic("could not cast something that was suppose to be a pointer to a bool slice")
}
return &boolSlice{
target: t,
}
}
func (s *boolSlice) String() string {
if s == nil || s.target == nil {
return ""
}
var result []string
for _, i := range *s.target {
result = append(result, fmt.Sprintf("%t", i))
}
return strings.Join(result, ",")
}
func (s *boolSlice) Set(value string) error {
if s == nil {
return errors.New("")
}
for _, potentialBool := range strings.Split(value, ",") {
*s.target = append(*s.target, potentialBool == "true")
}
return nil
}
type TextSlice struct {
concrete reflect.Type
}
func newGenericSlice(concrete reflect.Type) *TextSlice {
return &TextSlice{
concrete: concrete,
}
}
func (s *TextSlice) String() string {
return string("empty")
}
func (s *TextSlice) Set(value string) error {
if s == nil {
return errors.New("nil")
}
values := strings.Split(value, ",")
for _, v := range values {
n := reflect.New(s.concrete).Interface().(encoding.TextUnmarshaler)
err := n.UnmarshalText([]byte(v))
if err != nil {
return fmt.Errorf("failed to unmarshal item %q: %w", v, err)
}
}
return nil
}
type ciParser[T any] struct {
o *options
}
func newCliLoader[T any](o *options) *ciParser[T] {
return &ciParser[T]{
o: o,
}
}
// GetGeneratedCliFlags return list of auto generated cli flag names that LoadCli/Config will check
func GetGeneratedCliFlags[T any](delimiter string) []string {
var a T
if reflect.TypeOf(a).Kind() != reflect.Struct {
panic("GetGeneratedEnv(...) only supports configs of Struct type")
}
o := options{}
FromCli(delimiter)(&o)
cp := newCliLoader[T](&o)
var result []string
for _, field := range getFields(true, &a) {
cliName, ok := determineVariableName(&a, cp.o.cli.delimiter, nil, field)
if !ok {
continue
}
result = append(result, cliName)
}
return result
}
// GetGeneratedCliFlagsWithTransform return list of auto generated cli flag names that LoadEnv/Config will check
// it optionally also takes a transform func that you can use to change the flag name
func GetGeneratedCliFlagsWithTransform[T any](delimiter string, transformFunc Transform) []string {
var a T
if reflect.TypeOf(a).Kind() != reflect.Struct {
panic("GetGeneratedCliFlagsWithTransform(...) only supports configs of Struct type")
}
envs := GetGeneratedCliFlags[T](delimiter)
for i := range envs {
if transformFunc != nil {
envs[i] = transformFunc(envs[i])
}
}
return envs
}
// LoadCli populates a configuration file T from cli arguments
func LoadCli[T any](delimiter string) (result T, err error) {
if reflect.TypeOf(result).Kind() != reflect.Struct {
panic("LoadCli(...) only supports configs of Struct type")
}
result, _, err = Config[T](FromCli(delimiter))
return
}
// LoadCli populates a configuration file T from cli arguments and uses the transform to change the name of the cli flag
func LoadCliWithTransform[T any](delimiter string, transform func(string) string) (result T, err error) {
if reflect.TypeOf(result).Kind() != reflect.Struct {
panic("LoadCli(...) only supports configs of Struct type")
}
result, _, err = Config[T](FromCli(delimiter), WithCliTransform(transform))
return
}
func (cp *ciParser[T]) usage(f *flag.FlagSet) func() {
return func() {
fmt.Fprintf(f.Output(), "Structure options: \n")
f.PrintDefaults()
}
}
func (cp *ciParser[T]) apply(result *T) (somethingSet bool, err error) {
if len(os.Args) == 0 {
logger.Info("no os arguments supplied, not trying to parse cli")
return false, nil
}
cp.o.cli.commandLine.SetOutput(os.Stdout)
cp.o.cli.commandLine.Usage = cp.usage(cp.o.cli.commandLine)
if len(os.Args) <= 1 {
logger.Info("one os arguments supplied, not trying to parse cli")
// There were no args to parse, so the user must not be using the cli
return false, nil
}
// stop go flag from overwritting literally all configuration data on default write
dummyCopy := new(T)
type association struct {
v reflect.Value
path []string
tag reflect.StructTag
}
flagAssociation := map[string]association{}
const sourceHelpFlag = "struct-help"
cp.o.cli.commandLine.Bool(sourceHelpFlag, true, "Print command line flags generated by confy")
for _, field := range getFields(true, dummyCopy) {
willAccess := field.value.CanAddr() && field.value.CanInterface()
logger.Info("got field from config", slog.Any(strings.Join(field.path, "."), field.value.String()), "will_continue_parsing", fmt.Sprintf("%t (addr: %t, intf: %t)", willAccess, field.value.CanAddr(), field.value.CanInterface()))
if willAccess {
if field.value.Kind() == reflect.Ptr {
field.value = field.value.Elem()
}
flagName, ok := determineVariableName(result, cp.o.cli.delimiter, cp.o.cli.transform, field)
if !ok {
// logging done in determine variable
continue
}
logger.Info("resolved confy path", "resolved_path", flagName, "path", strings.Join(field.path, cp.o.cli.delimiter))
description, ok := field.tag.Lookup(confyDescriptionTag)
if !ok {
logger.Info("could not find 'confy_description:' tag will auto generate from type", "tags", field.tag, "path", strings.Join(field.path, cp.o.cli.delimiter))
typeName := field.value.Kind().String()
if field.value.Kind() == reflect.Slice {
typeName = field.value.Type().Elem().Kind().String() + " " + typeName
} else if field.value.Kind() == reflect.Struct {
pkg := field.value.Type().PkgPath()
if pkg != "" {
pkg = filepath.Base(pkg) + "."
}
typeName = pkg + field.value.Type().Name() + " " + typeName
}
description = fmt.Sprintf("A %s value, %s (%s)", typeName, strings.Join(field.path, cp.o.cli.delimiter), flagName)
}
logger.Info("adding flag", "flag", "-"+flagName, "type", field.value.Kind())
flagAssociation[flagName] = association{v: field.value, path: field.path, tag: field.tag}
switch field.value.Kind() {
case reflect.String:
cp.o.cli.commandLine.StringVar(field.value.Addr().Interface().(*string), flagName, "", description)
case reflect.Int:
cp.o.cli.commandLine.IntVar(field.value.Addr().Interface().(*int), flagName, 0, description)
case reflect.Int64:
cp.o.cli.commandLine.Int64Var(field.value.Addr().Interface().(*int64), flagName, 0, description)
case reflect.Bool:
cp.o.cli.commandLine.BoolVar(field.value.Addr().Interface().(*bool), flagName, false, description)
case reflect.Float64:
cp.o.cli.commandLine.Float64Var(field.value.Addr().Interface().(*float64), flagName, 0, description)
case reflect.Slice:
var parser flag.Value
sliceContentType := field.value.Type().Elem()
switch sliceContentType.Kind() {
case reflect.String:
parser = newStringSlice(field.value.Addr().Interface())
case reflect.Int, reflect.Int64:
parser = newIntSlice(field.value.Addr().Interface())
case reflect.Float64:
parser = newFloatSlice(field.value.Addr().Interface())
case reflect.Bool:
parser = newBoolSlice(field.value.Addr().Interface())
default:
inter := reflect.TypeOf((*encoding.TextUnmarshaler)(nil)).Elem()
if !reflect.PointerTo(sliceContentType).Implements(inter) {
logger.Warn("type inside of complex slice did not implement encoding.TextUnmarshaler", "flag", flagName, "path", strings.Join(field.path, cp.o.cli.delimiter))
continue
}
parser = newGenericSlice(sliceContentType)
}
cp.o.cli.commandLine.Var(parser, flagName, description)
case reflect.Struct:
textUnmarshaler, ok := field.value.Addr().Interface().(encoding.TextUnmarshaler)
if !ok {
logger.Warn("structure doesnt implement encoding.TextUnmarshaler", "flag", flagName, "path", strings.Join(field.path, cp.o.cli.delimiter))
continue
}
textMarshaler, ok := field.value.Addr().Interface().(encoding.TextMarshaler)
if !ok {
logger.Warn("structure doesnt implement encoding.TextMarshaler", "flag", flagName, "path", strings.Join(field.path, cp.o.cli.delimiter))
continue
}
cp.o.cli.commandLine.TextVar(textUnmarshaler, flagName, textMarshaler, description)
default:
logger.Warn("unsupported type for cli auto-addition", "type", field.value.Kind().String(), "path", strings.Join(field.path, cp.o.cli.delimiter))
continue
}
}
}
err = cp.o.cli.commandLine.Parse(os.Args[1:])
if err != nil {
return false, err
}
help := false
cp.o.cli.commandLine.Visit(func(f *flag.Flag) {
if f.Name == sourceHelpFlag {
logger.Info("the help flag was set", "flag", sourceHelpFlag)
help = true
return
}
association, ok := flagAssociation[f.Name]
if !ok {
return
}
v, _ := getField(result, association.path)
v.Set(association.v)
somethingSet = true
logger.Info("CLI FLAG", "-"+f.Name, maskSensitive(f.Value.String(), association.tag))
})
if help {
cp.o.cli.commandLine.PrintDefaults()
return somethingSet, flag.ErrHelp
}
return somethingSet, nil
}