-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathconfi.go
401 lines (343 loc) · 9.31 KB
/
confi.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
package configo
import (
"encoding/json"
"io/ioutil"
"os"
"os/user"
"path/filepath"
"reflect"
"strings"
"github.com/creasty/defaults"
"github.com/fatih/structtag"
"github.com/go-playground/validator"
"github.com/iancoleman/strcase"
"github.com/imdario/mergo"
"github.com/joho/godotenv"
"github.com/k0kubun/pp"
"github.com/kelseyhightower/envconfig"
"github.com/mitchellh/mapstructure"
"github.com/pkg/errors"
"github.com/spf13/cast"
"github.com/xelaj/go-dry"
"github.com/xelaj/errs"
"github.com/xelaj/v"
)
var (
ConfigScheme interface{}
commonEnvs = []string{
"USER",
"PATH",
"LANGUAGE",
}
)
func Init(appName string) (interface{}, error) {
if appName == "" {
appName = v.AppName
}
err := ParseConfig(appName, ConfigScheme)
if err != nil {
return nil, errors.Wrap(err, "parsing config")
}
return ConfigScheme, nil
}
func InitConfig(appName, userRunned string, into interface{}) error {
if appName == "" {
appName = v.AppName
}
u, _ := user.Lookup(userRunned)
return initConfig(appName,
filepath.Join("/etc", appName),
filepath.Join(u.HomeDir, ".local", "etc", appName),
into,
)
}
// DEPRECATED: No, seriously, this is just for examples and testing. Use only InitConfig, it do all job for you
func InitConfigWithExplicitConfigPaths(appName, globalPath, localPath string, into interface{}) error {
return initConfig(appName, globalPath, localPath, into)
}
func initConfig(appName, globalPath, localPath string, into interface{}) error {
typ := reflect.TypeOf(into)
if typ.Kind() != reflect.Ptr {
panic("not a pointer")
}
global := reflect.New(typ.Elem()).Interface()
dry.PanicIfErr(ParseDir(globalPath, global))
personal := reflect.New(typ.Elem()).Interface()
dry.PanicIfErr(ParseDir(localPath, personal))
session := reflect.New(typ.Elem()).Interface()
dry.PanicIfErr(ParseEnvFile("./configs/session.env", "simpleapp", session))
dry.PanicIfErr(mergo.Merge(into, global, mergo.WithOverride))
dry.PanicIfErr(mergo.Merge(into, personal, mergo.WithOverride))
dry.PanicIfErr(mergo.Merge(into, session, mergo.WithOverride))
return nil
}
func ParseConfig(appName string, cfg interface{}) error {
err := envconfig.Process(appName, cfg)
if err != nil {
return errors.Wrap(err, "processing env")
}
err = validator.New().Struct(cfg)
if err != nil {
splitted := strings.Split(err.Error(), "\n")
return errs.MultipleAsString(splitted...)
}
return nil
}
func ParseEnvFile(path, prefix string, into interface{}) error {
prefix = strcase.ToScreamingSnake(prefix) + "_"
data, err := ioutil.ReadFile(path)
dry.PanicIfErr(err)
envs, err := godotenv.Unmarshal(string(data))
dry.PanicIfErr(err)
ival := reflect.ValueOf(into)
ityp := ival.Type()
if ityp.Kind() != reflect.Ptr {
panic("not a pointer")
}
if ityp.Elem().Kind() != reflect.Struct {
panic("not a struct")
}
ival = ival.Elem()
ityp = ityp.Elem()
ForEachField:
for i := 0; i < ityp.NumField(); i++ {
fval := ival.Field(i)
ftyp := ityp.Field(i).Type
tags, err := structtag.Parse(string(ityp.Field(i).Tag))
dry.PanicIfErr(err)
tag, err := tags.Get("param")
dry.PanicIfErr(err)
name := strcase.ToScreamingSnake(tag.Name)
possibleParams := make(map[string]string)
for k, v := range envs {
if strings.HasPrefix(k, prefix+name) {
possibleParams[k] = v
}
}
switch ftyp.Kind() {
case reflect.Bool, reflect.Int, reflect.Int8,
reflect.Int16, reflect.Int32, reflect.Int64,
reflect.Uint, reflect.Uint8, reflect.Uint16,
reflect.Uint32, reflect.Uint64, reflect.Float32,
reflect.Float64, reflect.Complex64,
reflect.Complex128, reflect.String:
exactKey := prefix + name
CastValue(reflect.ValueOf(possibleParams[exactKey]), fval)
continue ForEachField
}
panic("don't understand how to parse this thing!")
}
return nil
}
func ParseDir(path string, into interface{}) error {
ival := reflect.ValueOf(into)
ityp := ival.Type()
if ityp.Kind() != reflect.Ptr {
panic("not a pointer")
}
if ityp.Elem().Kind() != reflect.Struct {
panic("not a struct")
}
ival = ival.Elem()
ityp = ityp.Elem()
path, err := filepath.Abs(path)
dry.PanicIfErr(err)
stat, err := os.Stat(path)
if err != nil {
switch err.(type) {
case *os.PathError:
return errs.NotFound("directory", path)
default:
panic(err)
}
}
if stat.Mode()&os.ModeSymlink > 0 {
return errors.New("doesn't working with symlinks")
}
files, err := dry.ListDirFiles(path)
dry.PanicIfErr(err)
for _, file := range files {
_, ext := dry.PathSplitExt(file)
switch ext {
case "json":
in := map[string]interface{}{}
data, err := ioutil.ReadFile(filepath.Join(path, file))
dry.PanicIfErr(err)
err = json.Unmarshal(data, &in)
dry.PanicIfErr(err)
err = mergo.Map(into, in)
dry.PanicIfErr(err)
case "go":
continue
default:
panic("invalid extension: " + ext)
}
}
dirs, err := dry.ListDirDirectories(path)
dry.PanicIfErr(err)
for _, param := range dirs {
dstElement := ival.FieldByName(param)
for i := 0; i < ityp.NumField(); i++ {
if ityp.Field(i).Tag.Get("param") == param {
dstElement = ival.Field(i)
}
}
zeroValue := reflect.Value{}
if dstElement == zeroValue {
panic("unknown field: " + param)
}
if dstElement.IsNil() {
switch dstElement.Type().Kind() {
case reflect.Ptr:
dstElement.Set(reflect.New(dstElement.Type()).Elem())
case reflect.Map:
dstElement.Set(reflect.MakeMap(dstElement.Type()))
case reflect.Slice:
dstElement.Set(reflect.MakeSlice(dstElement.Type(), 0, 0))
}
}
err := parseDir(filepath.Join(path, param), dstElement.Addr().Interface())
dry.PanicIfErr(err)
}
defaults.MustSet(into)
pp.Println(into)
return nil
}
func parseDir(path string, into interface{}) error {
if into == nil {
panic("into is nil")
}
ival := reflect.ValueOf(into)
ityp := ival.Type()
if ityp.Kind() != reflect.Ptr {
panic("not a pointer")
}
ival = ival.Elem()
ityp = ityp.Elem()
switch ityp.Kind() {
case reflect.Slice:
files, err := dry.ListDirFiles(path)
dry.PanicIfErr(err)
for _, file := range files {
childType := ityp.Elem()
if childType.Kind() == reflect.Ptr {
childType = childType.Elem()
}
item := reflect.New(childType).Interface()
in := map[string]interface{}{}
data, err := ioutil.ReadFile(filepath.Join(path, file))
dry.PanicIfErr(err)
_, ext := dry.PathSplitExt(file)
switch ext {
case "json":
err = json.Unmarshal(data, &in)
dry.PanicIfErr(err)
case "go":
continue
default:
panic("invalid extension: " + ext)
}
decoder, _ := mapstructure.NewDecoder(&mapstructure.DecoderConfig{
TagName: "param",
WeaklyTypedInput: true,
Result: item,
})
err = decoder.Decode(in)
dry.PanicIfErr(err)
itemValue := reflect.ValueOf(item)
if ityp.Elem().Kind() != reflect.Ptr && itemValue.Type().Kind() == reflect.Ptr {
itemValue = itemValue.Elem()
}
ival.Set(reflect.Append(ival, itemValue))
}
case reflect.Map:
files, err := dry.ListDirFiles(path)
dry.PanicIfErr(err)
switch ityp.Key().Kind() {
case reflect.Bool, reflect.Int, reflect.Int8,
reflect.Int16, reflect.Int32, reflect.Int64,
reflect.Uint, reflect.Uint8, reflect.Uint16,
reflect.Uint32, reflect.Uint64, reflect.Float32,
reflect.Float64, reflect.Complex64,
reflect.Complex128, reflect.String:
default:
panic("supports only string any number or boolean")
}
for _, file := range files {
key, ext := dry.PathSplitExt(file)
switch ext {
case "json":
childType := ityp.Elem()
if childType.Kind() == reflect.Ptr {
childType = childType.Elem()
}
item := reflect.New(childType).Interface()
in := map[string]interface{}{}
data, err := ioutil.ReadFile(filepath.Join(path, file))
dry.PanicIfErr(err)
err = json.Unmarshal(data, &in)
dry.PanicIfErr(err)
decoder, _ := mapstructure.NewDecoder(&mapstructure.DecoderConfig{
TagName: "param",
WeaklyTypedInput: true,
Result: item,
})
err = decoder.Decode(in)
dry.PanicIfErr(err)
itemValue := reflect.ValueOf(item)
if ityp.Elem().Kind() != reflect.Ptr && itemValue.Type().Kind() == reflect.Ptr {
itemValue = itemValue.Elem()
}
keyValue := reflect.New(ityp.Key()).Elem()
CastValue(reflect.ValueOf(key), keyValue)
pp.Println(keyValue.Interface(), itemValue.Interface())
pp.Println(ival.Interface())
ival.SetMapIndex(keyValue, itemValue)
case "go":
continue
default:
panic("invalid extension: " + ext)
}
}
default:
panic(ityp.String())
}
return nil
}
func CastValue(src, dst reflect.Value) {
in := src.Interface()
var out interface{}
switch dst.Type().Kind() {
case reflect.Bool:
out = cast.ToBool(in)
case reflect.Int:
out = cast.ToInt(in)
case reflect.Int8:
out = cast.ToInt8(in)
case reflect.Int16:
out = cast.ToInt16(in)
case reflect.Int32:
out = cast.ToInt32(in)
case reflect.Int64:
out = cast.ToInt64(in)
case reflect.Uint:
out = cast.ToUint(in)
case reflect.Uint8:
out = cast.ToUint8(in)
case reflect.Uint16:
out = cast.ToUint16(in)
case reflect.Uint32:
out = cast.ToUint32(in)
case reflect.Uint64:
out = cast.ToUint64(in)
case reflect.Float32:
out = cast.ToFloat32(in)
case reflect.Float64:
out = cast.ToFloat64(in)
case reflect.String:
out = cast.ToString(in)
default:
panic("unsupported type " + dst.Type().String())
}
dst.Set(reflect.ValueOf(out))
}