-
Notifications
You must be signed in to change notification settings - Fork 2
/
ljconf.go
521 lines (443 loc) · 10.1 KB
/
ljconf.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
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
/*
A configuration package using Loose JSON (https://github.com/daviddengcn/ljson) as the format.
Main features include:
1) Loose JSON as the format
2) Commenting
3) Dot-seperated key
4) Include
A typical conf file:
{
// http settings
http: {
addr: "www.example.com"
ports: [80, 8080]
}
#include#: "others.conf"
}
Visit the project page for more details:
https://github.com/daviddengcn/go-ljson-conf
*/
package ljconf
import (
"encoding/json"
"errors"
"fmt"
"github.com/daviddengcn/go-villa"
"github.com/daviddengcn/ljson"
"os"
"os/user"
"strconv"
"strings"
"time"
)
type Conf struct {
path villa.Path
db map[string]interface{}
}
func (c *Conf) ConfPath() villa.Path {
return c.path
}
const INCLUDE_KEY_TAG = "#include#"
func loadArrayInclude(arr []interface{}, dir villa.Path) {
for _, el := range arr {
switch vv := el.(type) {
case map[string]interface{}:
loadInclude(vv, dir)
case []interface{}:
loadArrayInclude(vv, dir)
}
}
}
func loadInclude(db map[string]interface{}, dir villa.Path) {
for k, v := range db {
if k == INCLUDE_KEY_TAG {
switch paths := v.(type) {
case string:
// fmt.Println("Including", paths, "at", dir)
sub, err := Load(dir.Join(paths).S())
if err == nil {
// merge into current db
for sk, sv := range sub.db {
db[sk] = sv
}
// remove this entry
delete(db, k)
}
continue
case []interface{}:
for _, el := range paths {
if path, ok := el.(string); ok {
sub, err := Load(dir.Join(path).S())
if err == nil {
// merge into current db
for sk, sv := range sub.db {
db[sk] = sv
}
}
}
}
// remove this entry
delete(db, k)
continue
} // switch
} // if
switch vv := v.(type) {
case map[string]interface{}:
loadInclude(vv, dir)
case []interface{}:
loadArrayInclude(vv, dir)
}
}
}
func findPath(fn villa.Path) villa.Path {
if fn.IsAbs() {
return fn
}
if fn.Exists() {
return fn.AbsPath()
}
// Try .exe folder
tryFn := villa.Path(os.Args[0]).Dir().Join(fn)
if tryFn.Exists() {
return tryFn
}
// Try user-home folder
cu, err := user.Current()
if err == nil {
tryFn = villa.Path(cu.HomeDir).Join(fn)
if tryFn.Exists() {
return tryFn
}
}
return fn.AbsPath()
}
// Load reads configurations from a speicified file. If some error found
// during reading, it will be return, but the conf is still available.
// If the given path is not absolute, Load tries to find the configure file in the
// following order:
// 1. Current directory
// 2. Same folder the executable, and
// 3. User's home folder.
func Load(fn string) (conf *Conf, err error) {
path := findPath(villa.Path(fn))
conf = &Conf{
path: path,
db: make(map[string]interface{}),
}
fin, err := path.Open()
if err != nil {
if os.IsNotExist(err) {
// configuration file not existing is ok, an empty conf
return conf, nil
}
// if file not exists, nothing read (but configuration still usable.)
return conf, err
}
if err := func() error {
defer fin.Close()
dec := ljson.NewDecoder(newRcReader(fin))
return dec.Decode(&conf.db)
}(); err != nil {
return conf, err
}
loadInclude(conf.db, path.Dir())
return conf, nil
}
// Watch periodically checks the configure file in curConf with the specified interval.
// If the configuration file changes, it's reloaded and sent to the specified channel as a *Conf.
// TODO use inotify mechanism instead of poll.
func Watch(curConf *Conf, interval time.Duration, ch chan *Conf) error {
configFileName := string(curConf.path)
lastStat, err := os.Stat(configFileName)
if err != nil {
return err
}
ticker := time.NewTicker(interval)
defer ticker.Stop()
for _ = range ticker.C {
stat, err := os.Stat(configFileName)
if err != nil {
// e,g. the config file was deleted
return err
}
if stat.ModTime() != lastStat.ModTime() {
lastStat = stat
cf, err := Load(string(curConf.path))
if err != nil {
return err
}
ch <- cf
}
}
return nil
}
func (c *Conf) Section(key string) (conf *Conf, err error) {
sec := c.get(key)
if sec == nil {
err = errors.New("empty section: " + key)
return
}
conf = &Conf{
path: c.path,
db: sec.(map[string]interface{}),
}
return
}
// fetch a value or a map[string]interface{} as an interface{},
// returns nil if not found
func (c *Conf) get(key string) interface{} {
if key == "" {
return c.db
}
parts := strings.Split(key, ".")
var vl interface{} = c.db
for _, p := range parts {
mp, ok := vl.(map[string]interface{})
if !ok {
return nil
}
vl, ok = mp[p]
if ok {
continue
}
if strings.HasSuffix(p, "]") {
// try fetch the element in an array
idx := strings.Index(p, "[")
if idx > 0 {
indexes := strings.Split(p[idx+1:len(p)-1], "][")
p = p[:idx]
vl, ok = mp[p]
if !ok {
return nil
}
for _, sidx := range indexes {
idx, err := strconv.ParseInt(sidx, 0, 0)
if err != nil {
return nil
}
arr, ok := vl.([]interface{})
if !ok {
return nil
}
if idx < 0 || int(idx) >= len(arr) {
return nil
}
vl = arr[idx]
}
}
}
}
return vl
}
// Interface retrieves a value as an interface{} of the key. def is returned
// if the value does not exist.
func (c *Conf) Interface(key string, def interface{}) interface{} {
vl := c.get(key)
if vl == nil {
return def
}
return vl
}
// String retrieves a value as a string of the key. def is returned
// if the value does not exist or cannot be converted to a string(e.g. is an
// object).
func (c *Conf) String(key, def string) string {
vl := c.get(key)
if vl == nil {
return def
}
switch vl.(type) {
case string, float64, bool:
return fmt.Sprint(vl)
}
return def
}
func (c *Conf) Path(key string, def villa.Path) villa.Path {
return villa.Path(c.String(key, def.S()))
}
// Bool retrieves a value as a bool of the key. def is returned
// if the value does not exist or is not a bool. A string will be converted
// using strconv.ParseBool.
func (c *Conf) Bool(key string, def bool) bool {
vl := c.get(key)
if vl == nil {
return def
}
switch v := vl.(type) {
case bool:
return v
case string:
b, err := strconv.ParseBool(v)
if err == nil {
return b
}
}
return def
}
// floatToInt converts a float64 value into an int
func floatToInt(f float64) int64 {
if f < 0 {
return int64(f - 0.5)
}
return int64(f + 0.5)
}
// Int retrieves a value as a string of the key. def is returned
// if the value does not exist or is not a number. A float number will be
// round up to the closest interger. A string will be converted using
// strconv.ParseInt.
func (c *Conf) Int(key string, def int) int {
vl := c.get(key)
if vl == nil {
return def
}
switch v := vl.(type) {
case float64:
return int(floatToInt(v))
case string:
i, err := strconv.ParseInt(v, 0, 0)
if err == nil {
return int(i)
}
}
return def
}
// Float retrieves a value as a float64 of the key. def is returned
// if the value does not exist or is not a number. A string will be converted
// using strconv.ParseFloat.
func (c *Conf) Float(key string, def float64) float64 {
vl := c.get(key)
if vl == nil {
return def
}
switch v := vl.(type) {
case float64:
return v
case string:
f, err := strconv.ParseFloat(v, 64)
if err == nil {
return f
}
}
return def
}
// Object retrieves a value as a map[string]interface{} of the key. def is returned
// if the value does not exist or is not an object.
func (c *Conf) Object(key string, def map[string]interface{}) map[string]interface{} {
vl := c.get(key)
if vl == nil {
return def
}
switch v := vl.(type) {
case map[string]interface{}:
return v
}
return def
}
// Decode section to struct object val
func (c *Conf) Decode(key string, val interface{}) error {
vl := c.get(key)
if vl == nil {
return errors.New("empty section: " + key)
}
jval, err := json.Marshal(vl)
if err != nil {
return err
}
if err := json.Unmarshal(jval, &val); err != nil {
return err
}
return nil
}
// List retrieves a value as a slice of interface{} of the key. def is returned
// if the value does not exist or is not an array.
func (c *Conf) List(key string, def []interface{}) []interface{} {
vl := c.get(key)
if vl == nil {
return def
}
switch v := vl.(type) {
case []interface{}:
return v
}
return def
}
// StringList retrieves a value as a slice of string of the key. def is returned
// if the value does not exist or is not an array. Elements of the array are
// converted to strings using fmt.Sprint.
func (c *Conf) StringList(key string, def []string) []string {
vl := c.get(key)
if vl == nil {
return def
}
switch v := vl.(type) {
case []interface{}:
res := make([]string, 0, len(v))
for _, el := range v {
res = append(res, fmt.Sprint(el))
}
return res
}
return def
}
// IntList retrieves a value as a slice of int of the key. def is returned
// if the value does not exist or is not an array. Elements of the array are
// converted to int. Zero is used when converting failed.
func (c *Conf) IntList(key string, def []int) []int {
vl := c.get(key)
if vl == nil {
return def
}
switch v := vl.(type) {
case []interface{}:
res := make([]int, 0, len(v))
for _, el := range v {
var e int
switch et := el.(type) {
case float64:
e = int(floatToInt(et))
case string:
i, _ := strconv.ParseInt(et, 0, 0)
e = int(i)
case bool:
if et {
e = 1
} else {
e = 0
}
}
res = append(res, e)
}
return res
}
return def
}
// Duration retrieves a value as a time.Duration. See comments of
// time.ParseDuration for supported formats.
func (c *Conf) Duration(key string, def time.Duration) time.Duration {
vl := c.get(key)
if vl == nil {
return def
}
switch v := vl.(type) {
case string:
if d, err := time.ParseDuration(v); err == nil {
return d
}
}
return def
}
// Duration retrieves a value as a time.Time. See comments of
// time.Parse for layout definition.
func (c *Conf) Time(key, layout string, def time.Time) time.Time {
vl := c.get(key)
if vl == nil {
return def
}
switch v := vl.(type) {
case string:
if d, err := time.Parse(layout, v); err == nil {
return d
}
}
return def
}