-
Notifications
You must be signed in to change notification settings - Fork 25
/
args.go
262 lines (244 loc) · 7.45 KB
/
args.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
// Copyright (c) 2023, The Emergent Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// note: parsing code adapted from pflag package https://github.com/spf13/pflag
// Copyright (c) 2012 Alex Ogier. All rights reserved.
// Copyright (c) 2012 The Go Authors. All rights reserved.
package econfig
import (
"fmt"
"reflect"
"strings"
"github.com/emer/empi/mpi"
"github.com/goki/ki/kit"
"github.com/goki/ki/toml"
"github.com/iancoleman/strcase"
)
// SetFromArgs sets Config values from command-line args,
// based on the field names in the Config struct.
// Returns any args that did not start with a `-` flag indicator.
// For more robust error processing, it is assumed that all flagged args (-)
// must refer to fields in the config, so any that fail to match trigger
// an error. Errors can also result from parsing.
// Errors are automatically logged because these are user-facing.
func SetFromArgs(cfg any, args []string) (nonFlags []string, err error) {
allArgs := make(map[string]reflect.Value)
CommandArgs(allArgs) // need these to not trigger not-found errors
FieldArgNames(cfg, allArgs)
nonFlags, err = ParseArgs(cfg, args, allArgs, true)
if err != nil {
mpi.Println(Usage(cfg))
}
return
}
// ParseArgs parses given args using map of all available args
// setting the value accordingly, and returning any leftover args.
// setting errNotFound = true causes args that are not in allArgs to
// trigger an error. Otherwise, it just skips those.
func ParseArgs(cfg any, args []string, allArgs map[string]reflect.Value, errNotFound bool) ([]string, error) {
var nonFlags []string
var err error
for len(args) > 0 {
s := args[0]
args = args[1:]
if len(s) == 0 || s[0] != '-' || len(s) == 1 {
nonFlags = append(nonFlags, s)
continue
}
if s[1] == '-' && len(s) == 2 { // "--" terminates the flags
// f.argsLenAtDash = len(f.args)
nonFlags = append(nonFlags, args...)
break
}
args, err = ParseArg(s, args, allArgs, errNotFound)
if err != nil {
return nonFlags, err
}
}
return nonFlags, nil
}
func ParseArg(s string, args []string, allArgs map[string]reflect.Value, errNotFound bool) (a []string, err error) {
a = args
name := s[1:]
if name[0] == '-' {
name = name[1:]
}
if len(name) == 0 || name[0] == '-' || name[0] == '=' {
err = fmt.Errorf("econfig.ParseArgs: bad flag syntax: %s", s)
mpi.Println(err)
return
}
if strings.HasPrefix(name, "test.") { // go test passes args..
return
}
split := strings.SplitN(name, "=", 2)
name = split[0]
fval, exists := allArgs[name]
if !exists {
if errNotFound {
err = fmt.Errorf("econfig.ParseArgs: flag name not recognized: %s", name)
mpi.Println(err)
}
return
}
isbool := kit.NonPtrValue(fval).Kind() == reflect.Bool
var value string
switch {
case len(split) == 2:
// '--flag=arg'
value = split[1]
case isbool:
// '--flag' bare
lcnm := strings.ToLower(name)
negate := false
if len(lcnm) > 3 {
if lcnm[:3] == "no_" || lcnm[:3] == "no-" {
negate = true
} else if lcnm[:2] == "no" {
if _, has := allArgs[lcnm[2:]]; has { // e.g., nogui and gui is on list
negate = true
}
}
}
if negate {
value = "false"
} else {
value = "true"
}
case len(a) > 0:
// '--flag arg'
value = a[0]
a = a[1:]
default:
// '--flag' (arg was required)
err = fmt.Errorf("econfig.ParseArgs: flag needs an argument: %s", s)
mpi.Println(err)
return
}
err = SetArgValue(name, fval, value)
return
}
// SetArgValue sets given arg name to given value, into settable reflect.Value
func SetArgValue(name string, fval reflect.Value, value string) error {
nptyp := kit.NonPtrType(fval.Type())
vk := nptyp.Kind()
switch {
case vk >= reflect.Int && vk <= reflect.Uint64 && kit.Enums.TypeRegistered(nptyp):
return kit.Enums.SetAnyEnumValueFromString(fval, value)
case vk == reflect.Map:
mval := make(map[string]any)
err := toml.ReadBytes(&mval, []byte("tmp="+value)) // use toml decoder
if err != nil {
mpi.Println(err)
return err
}
err = kit.CopyMapRobust(fval.Interface(), mval["tmp"])
if err != nil {
mpi.Println(err)
err = fmt.Errorf("econfig.ParseArgs: not able to set map field from arg: %s val: %s", name, value)
mpi.Println(err)
return err
}
case vk == reflect.Slice:
mval := make(map[string]any)
err := toml.ReadBytes(&mval, []byte("tmp="+value)) // use toml decoder
if err != nil {
mpi.Println(err)
return err
}
err = kit.CopySliceRobust(fval.Interface(), mval["tmp"])
if err != nil {
mpi.Println(err)
err = fmt.Errorf("econfig.ParseArgs: not able to set slice field from arg: %s val: %s", name, value)
mpi.Println(err)
return err
}
default:
ok := kit.SetRobust(fval.Interface(), value) // overkill but whatever
if !ok {
err := fmt.Errorf("econfig.ParseArgs: not able to set field from arg: %s val: %s", name, value)
mpi.Println(err)
return err
}
}
return nil
}
// FieldArgNames adds to given args map all the different ways the field names
// can be specified as arg flags, mapping to the reflect.Value
func FieldArgNames(obj any, allArgs map[string]reflect.Value) {
fieldArgNamesStruct(obj, "", false, allArgs)
}
func addAllCases(nm, path string, pval reflect.Value, allArgs map[string]reflect.Value) {
if nm == "Includes" {
return // skip
}
if path != "" {
nm = path + "." + nm
}
allArgs[nm] = pval
allArgs[strings.ToLower(nm)] = pval
allArgs[strcase.ToKebab(nm)] = pval
allArgs[strcase.ToSnake(nm)] = pval
allArgs[strcase.ToScreamingSnake(nm)] = pval
}
// fieldArgNamesStruct returns map of all the different ways the field names
// can be specified as arg flags, mapping to the reflect.Value
func fieldArgNamesStruct(obj any, path string, nest bool, allArgs map[string]reflect.Value) {
if kit.IfaceIsNil(obj) {
return
}
ov := reflect.ValueOf(obj)
if ov.Kind() == reflect.Pointer && ov.IsNil() {
return
}
val := kit.NonPtrValue(ov)
typ := val.Type()
for i := 0; i < typ.NumField(); i++ {
f := typ.Field(i)
fv := val.Field(i)
if kit.NonPtrType(f.Type).Kind() == reflect.Struct {
nwPath := f.Name
if path != "" {
nwPath = path + "." + nwPath
}
nwNest := nest
if !nwNest {
neststr, ok := f.Tag.Lookup("nest")
if ok && (neststr == "+" || neststr == "true") {
nwNest = true
}
}
fieldArgNamesStruct(kit.PtrValue(fv).Interface(), nwPath, nwNest, allArgs)
continue
}
pval := kit.PtrValue(fv)
addAllCases(f.Name, path, pval, allArgs)
if f.Type.Kind() == reflect.Bool {
addAllCases("No"+f.Name, path, pval, allArgs)
}
// now process adding non-nested version of field
if path == "" || nest {
continue
}
neststr, ok := f.Tag.Lookup("nest")
if ok && (neststr == "+" || neststr == "true") {
continue
}
if _, has := allArgs[f.Name]; has {
mpi.Printf("econfig Field: %s.%s cannot be added as a non-nested %s arg because it has already been registered -- add 'nest:'+'' field tag to the one you want to keep only as a nested arg with path, to eliminate this message\n", path, f.Name, f.Name)
continue
}
addAllCases(f.Name, "", pval, allArgs)
if f.Type.Kind() == reflect.Bool {
addAllCases("No"+f.Name, "", pval, allArgs)
}
}
}
// CommandArgs adds non-field args that control the config process:
// -config -cfg -help -h
func CommandArgs(allArgs map[string]reflect.Value) {
allArgs["config"] = reflect.ValueOf(&ConfigFile)
allArgs["cfg"] = reflect.ValueOf(&ConfigFile)
allArgs["help"] = reflect.ValueOf(&Help)
allArgs["h"] = reflect.ValueOf(&Help)
}