-
Notifications
You must be signed in to change notification settings - Fork 0
/
load.go
93 lines (84 loc) · 2.24 KB
/
load.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
package dflag
import (
"errors"
"flag"
"fmt"
"os"
"reflect"
)
func init() {
flag.Bool("help", false, "more information")
}
var errNotAStruct = errors.New("interface is not a struct")
type cmdFlags struct {
dest any
element reflect.Value
parsed bool
}
func (c cmdFlags) parse() error {
t := c.element.Type()
for i := 0; i < t.NumField(); i++ {
f := c.element.Field(i)
if f.Kind() == reflect.Ptr {
return fmt.Errorf("invalid pointer field %s of type %v... don't use pointers in your cli struct", c.element.Type().Field(i).Name, f.Type())
}
field := t.Field(i)
key := field.Tag.Get(cli.String())
if key == "" {
continue
}
if !f.CanSet() {
return fmt.Errorf("unable to set value for field %s of type %v. Is field exported?", c.element.Type().Field(i).Name, f.Type())
}
kind := f.Kind()
switch kind {
case reflect.String:
ptr := f.Addr().Interface().(*string)
flag.StringVar(ptr, key, getDefaultValueForString(field), getDefaultUsage(field, kind))
case reflect.Bool:
ptr := f.Addr().Interface().(*bool)
flag.BoolVar(ptr, key, getDefaultValueForBool(field), getDefaultUsage(field, kind))
case reflect.Int:
ptr := f.Addr().Interface().(*int)
flag.IntVar(ptr, key, int(getDefaultValueForInt64(field)), getDefaultUsage(field, kind))
case reflect.Int64:
ptr := f.Addr().Interface().(*int64)
flag.Int64Var(ptr, key, getDefaultValueForInt64(field), getDefaultUsage(field, kind))
case reflect.Float64:
ptr := f.Addr().Interface().(*float64)
flag.Float64Var(ptr, key, getDefaultValueForFloat(field), getDefaultUsage(field, kind))
default:
return fmt.Errorf("unhandled field %s of type %v", c.element.Type().Field(i).Name, f.Type())
}
}
flag.Parse()
c.parsed = true
return nil
}
func loadStruct(structValue any) (*cmdFlags, error) {
value := reflect.ValueOf(structValue).Elem()
if value.Kind() != reflect.Struct {
return nil, errNotAStruct
}
return &cmdFlags{
dest: structValue,
element: value,
}, nil
}
func Load(dest any) error {
cf, err := loadStruct(dest)
if err != nil {
return err
}
err = cf.parse()
if err != nil {
return err
}
if help := flag.Lookup("help"); help != nil {
if help.Value.String() == "true" {
flag.PrintDefaults()
os.Exit(0)
}
}
return nil
}