-
Notifications
You must be signed in to change notification settings - Fork 1
/
config.go
497 lines (441 loc) · 12.7 KB
/
config.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
// Copyright 2019 xgfone
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package gconf
import (
"fmt"
"io"
"os"
"sort"
"strconv"
"strings"
"sync"
)
var defaultDebug bool
func init() {
Conf.RegisterOpt(ConfigFileOpt)
for _, env := range os.Environ() {
index := strings.IndexByte(env, '=')
if index == -1 {
continue
}
if strings.ToUpper(env[:index]) == "DEBUG" {
if v, _ := strconv.ParseBool(env[index+1:]); v {
defaultDebug = v
}
break
}
}
}
// debugf prints the log message only when enabling the debug mode.
func debugf(msg string, args ...interface{}) {
if defaultDebug {
printMsg(fmt.Sprintf(msg, args...))
}
}
func printMsg(msg string) {
switch DefaultWriter {
case os.Stdout, os.Stderr:
fmt.Fprintln(DefaultWriter, msg)
default:
io.WriteString(DefaultWriter, msg)
}
}
// DefaultWriter is the default writer, which Config will write the information
// to it by default.
var DefaultWriter = os.Stdout
// Conf is the default global Config.
//
// The default global Conf will register the option ConfigFileOpt.
var Conf = New()
// Config is used to manage the configuration options.
type Config struct {
*OptGroup // The default group.
errHandler func(error)
exit chan struct{}
lock sync.RWMutex
gsep string // The separator between the group names.
snap *snapshot
groups map[string]*OptGroup // the option groups
groups2 map[string]*OptGroup // The auxiliary groups
decoders map[string]Decoder
decAlias map[string]string
version Opt
setObserves []func(string, string, interface{}, interface{})
regObserves []func(string, []Opt)
}
// New returns a new Config.
//
// By default, it will add the "json", "yaml", "toml" and "ini" decoders,
// and set the aliases of "conf" and "yml" to "ini" and "yaml", for example,
//
// c.AddDecoder(NewJSONDecoder())
// c.AddDecoder(NewIniDecoder())
// c.AddDecoder(NewYamlDecoder())
// c.AddDecoder(NewTomlDecoder())
// c.AddDecoderAlias("conf", "ini")
// c.AddDecoderAlias("yml", "yaml")
//
func New() *Config {
c := new(Config)
c.gsep = "."
c.snap = newSnapshot(c)
c.exit = make(chan struct{})
c.groups = make(map[string]*OptGroup, 8)
c.groups2 = make(map[string]*OptGroup, 8)
c.decoders = make(map[string]Decoder, 8)
c.decAlias = make(map[string]string, 8)
c.OptGroup = newOptGroup(c, "")
c.groups[c.OptGroup.Name()] = c.OptGroup
c.errHandler = ErrorHandler(func(err error) { printMsg(err.Error()) })
c.AddDecoder(NewJSONDecoder())
c.AddDecoder(NewIniDecoder())
c.AddDecoder(NewYamlDecoder())
c.AddDecoder(NewTomlDecoder())
c.AddDecoderAlias("conf", "ini")
c.AddDecoderAlias("yml", "yaml")
return c
}
func (c *Config) _newGroup(parent, name string) *OptGroup {
c.lock.Lock()
name = c.getGroupName(parent, name)
group, ok := c.groups[name]
if !ok {
group = newOptGroup(c, name)
c.groups[name] = group
c.ensureGroup2(name)
}
c.lock.Unlock()
if !ok {
debugf("[Config] Creating a new group '%s'", name)
}
return group
}
func (c *Config) newGroup(parent, name string) (group *OptGroup) {
for _, subname := range strings.Split(name, c.gsep) {
group = c._newGroup(parent, subname)
parent = c.getGroupName(parent, subname)
}
return
}
func (c *Config) ensureGroup2(name string) {
if gnames := strings.Split(name, c.gsep); len(gnames) >= 1 {
for i := range gnames {
gname := strings.Join(gnames[:i+1], c.gsep)
if c.groups[gname] == nil && c.groups2[gname] == nil {
c.groups2[gname] = newOptGroup(c, gname)
debugf("[Config] Creating the auxiliary group '%s'", gname)
}
}
}
}
func (c *Config) getGroupName(parent, name string) string {
name = strings.Trim(name, c.gsep)
if parent == "" {
return name
} else if name == "" {
return parent
}
return strings.Join([]string{parent, name}, c.gsep)
}
func (c *Config) getGroup(parent, name string) *OptGroup {
c.lock.RLock()
name = c.getGroupName(parent, name)
group, ok := c.groups[name]
if !ok {
group = c.groups[name]
}
c.lock.RUnlock()
return group
}
func (c *Config) noticeOptRegister(group string, opts []Opt) {
if len(opts) == 0 {
return
}
c.lock.RLock()
fs := append([]func(string, []Opt){}, c.regObserves...)
c.lock.RUnlock()
for _, observer := range fs {
c.callRegObserver(group, opts, observer)
}
}
func (c *Config) noticeOptChange(group, optname string, old, new interface{},
observers []func(interface{})) {
for _, observer := range observers {
c.callOptObserver(observer, new)
}
c.lock.RLock()
fs := append([]func(g, p string, o, n interface{}){}, c.setObserves...)
c.lock.RUnlock()
for _, observer := range fs {
c.callSetObserver(group, optname, old, new, observer)
}
}
func (c *Config) callOptObserver(observe func(interface{}), new interface{}) {
defer c.wrapPanic("opt")
observe(new)
}
func (c *Config) callRegObserver(group string, opts []Opt, cb func(string, []Opt)) {
defer c.wrapPanic("register")
cb(group, opts)
}
func (c *Config) callSetObserver(group, optname string, old, new interface{},
cb func(string, string, interface{}, interface{})) {
defer c.wrapPanic("set")
cb(group, optname, old, new)
}
func (c *Config) wrapPanic(s string) {
if err := recover(); err != nil {
c.handleError(fmt.Errorf("[Config] option %s observer panic: %v", s, err))
}
}
// Close closes all the watchers and disables anyone to add the watcher into it.
func (c *Config) Close() {
select {
case <-c.exit:
default:
close(c.exit)
}
}
// CloseNotice returns a close channel, which will also be closed when the config
// is closed.
func (c *Config) CloseNotice() <-chan struct{} {
return c.exit
}
func (c *Config) handleError(err error) {
c.lock.RLock()
handler := c.errHandler
c.lock.RUnlock()
handler(err)
}
// ErrorHandler returns a error handler, which will ignore ErrNoOpt
// and ErrFrozenOpt, and pass the others to h.
func ErrorHandler(h func(err error)) func(error) {
return func(err error) {
if !IsErrNoOpt(err) && !IsErrFrozenOpt(err) {
h(err)
}
}
}
// SetErrHandler resets the error handler to h.
//
// The default is output to DefaultWriter, but it ignores ErrNoOpt and ErrFrozenOpt.
func (c *Config) SetErrHandler(h func(error)) {
if h == nil {
panic("the error handler must not be nil")
}
c.lock.Lock()
c.errHandler = h
c.lock.Unlock()
}
// Observe appends the observer to watch the change of all the option value.
func (c *Config) Observe(observer func(group string, opt string, oldValue, newValue interface{})) {
if observer == nil {
panic("the observer must not be nil")
}
c.lock.Lock()
c.setObserves = append(c.setObserves, observer)
c.lock.Unlock()
}
// ObserveRegister appends the observer to watch the register of the option.
func (c *Config) ObserveRegister(observer func(group string, opts []Opt)) {
if observer == nil {
panic("the observer must not be nil")
}
c.lock.Lock()
c.regObserves = append(c.regObserves, observer)
c.lock.Unlock()
}
// AllGroups returns all the groups, containing the default group.
func (c *Config) AllGroups() []*OptGroup {
c.lock.RLock()
groups := make([]*OptGroup, len(c.groups))
var index int
for _, group := range c.groups {
groups[index] = group
index++
}
c.lock.RUnlock()
sort.Slice(groups, func(i, j int) bool { return groups[i].Name() < groups[j].Name() })
return groups
}
// SetStringVersion is equal to c.SetVersion(VersionOpt.D(version)).
func (c *Config) SetStringVersion(version string) {
c.SetVersion(VersionOpt.D(version))
}
// SetVersion sets the version information.
//
// Notice: the field Default must be a string.
func (c *Config) SetVersion(version Opt) {
if v, ok := version.Default.(string); !ok {
panic("the version is not a string value")
} else if v == "" {
panic("the version must not be empty")
}
version.check()
c.lock.Lock()
c.version = version
c.lock.Unlock()
}
// GetVersion returns a the version information.
//
// Notice: the Default filed is a string representation of the version value.
// But it is "" if no version.
func (c *Config) GetVersion() (version Opt) {
c.lock.RLock()
version = c.version
c.lock.RUnlock()
return
}
// PrintGroup prints the information of all groups to w.
func (c *Config) PrintGroup(w io.Writer) error {
for _, group := range c.AllGroups() {
if gname := group.Name(); gname == "" {
fmt.Fprintf(w, "[DEFAULT]\n")
} else {
fmt.Fprintf(w, "[%s]\n", gname)
}
for _, opt := range group.AllOpts() {
fmt.Fprintf(w, " %s\n", opt.Name)
}
}
return nil
}
// Traverse traverses all the options of all the groups.
func (c *Config) Traverse(f func(group string, opt string, value interface{})) {
for _, group := range c.AllGroups() {
for _, opt := range group.AllOpts() {
name := group.fixOptName(opt.Name)
f(group.Name(), name, group.Get(name))
}
}
}
// UpdateOptValue updates the value of the option of the group.
//
// If the group or the option does not exist, it will be ignored.
func (c *Config) UpdateOptValue(groupName, optName string, optValue interface{}) {
if group := c.Group(groupName); group != nil {
group.Set(optName, optValue)
}
}
// UpdateValue is the same as UpdateOptValue, but key is equal to
// `fmt.Sprintf("%s.%s", groupName, optName)`.
//
// that's,
// c.UpdateOptValue(groupName, optName, optValue)
// is equal to
// c.UpdateValue(fmt.Sprintf("%s.%s", groupName, optName), optValue)
func (c *Config) UpdateValue(key string, value interface{}) {
var group string
if index := strings.LastIndex(key, c.gsep); index > 0 {
group = key[:index]
key = key[index+len(c.gsep):]
}
c.UpdateOptValue(group, key, value)
}
// LoadMap loads the configuration options from the map m.
//
// If a certain option has been set, it will be ignored.
// But you can set force to true to reset the value of this option.
//
// The map may be the formats as follow:
//
// map[string]interface{} {
// "opt1": "value1",
// "opt2": "value2",
// // ...
// "group1": map[string]interface{} {
// "opt11": "value11",
// "opt12": "value12",
// "group2": map[string]interface{} {
// // ...
// },
// "group3.group4": map[string]interface{} {
// // ...
// }
// },
// "group5.group6.group7": map[string]interface{} {
// "opt71": "value71",
// "opt72": "value72",
// "group8": map[string]interface{} {
// // ...
// },
// "group9.group10": map[string]interface{} {
// // ...
// }
// },
// "group11.group12.opt121": "value121",
// "group11.group12.opt122": "value122"
// }
//
// When loading it, it will be flatted to
//
// map[string]interface{} {
// "opt1": "value1",
// "opt2": "value2",
// "group1.opt1": "value11",
// "group1.opt2": "value12",
// "group1.group2.XXX": "XXX",
// "group1.group3.group4.XXX": "XXX",
// "group5.group6.group7.opt71": "value71",
// "group5.group6.group7.opt72": "value72",
// "group5.group6.group7.group8.XXX": "XXX",
// "group5.group6.group7.group9.group10.XXX": "XXX",
// "group11.group12.opt121": "value121",
// "group11.group12.opt122": "value122"
// }
//
// So the option name must not contain the dot(.).
func (c *Config) LoadMap(m map[string]interface{}, force ...bool) {
var _force bool
if len(force) > 0 && force[0] {
_force = true
}
// Flat the map and update it
maps := make(map[string]interface{}, len(m)*2)
c.flatMap("", m, maps)
c.updateFlattedMap(maps, _force)
}
func (c *Config) updateFlattedMap(maps map[string]interface{}, force bool) {
for key, value := range maps {
group := c.OptGroup
if index := strings.LastIndex(key, c.gsep); index > -1 {
if group = c.Group(key[:index]); group == nil {
continue
}
key = key[index+len(c.gsep):]
}
if force || group.HasOptAndIsNotSet(key) {
group.Set(key, value)
}
}
}
func (c *Config) flatMap(parent string, src, dst map[string]interface{}) {
for key, value := range src {
if _, ok := value.(map[interface{}]interface{}); ok {
value, _ = toStringMap(value)
}
if ms, ok := value.(map[string]interface{}); ok {
group := key
if parent != "" {
group = strings.Join([]string{parent, key}, c.gsep)
}
c.flatMap(group, ms, dst)
continue
}
if parent != "" {
key = strings.Join([]string{parent, key}, c.gsep)
}
dst[key] = value
}
}