Repository navigation
Expand file tree
/
Copy pathgcfg.go
More file actions
534 lines (486 loc) · 13.8 KB
/
Copy pathgcfg.go
File metadata and controls
534 lines (486 loc) · 13.8 KB
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
522
523
524
525
526
527
528
529
530
531
532
533
534
// Copyright 2017 gf Author(https://github.com/gogf/gf). All Rights Reserved.
//
// This Source Code Form is subject to the terms of the MIT License.
// If a copy of the MIT was not distributed with this file,
// You can obtain one at https://github.com/gogf/gf.
// Package gcfg provides reading, caching and managing for configuration.
package gcfg
import (
"bytes"
"errors"
"fmt"
"time"
"github.com/gogf/gf/g/container/garray"
"github.com/gogf/gf/g/container/gmap"
"github.com/gogf/gf/g/container/gtype"
"github.com/gogf/gf/g/container/gvar"
"github.com/gogf/gf/g/encoding/gjson"
"github.com/gogf/gf/g/internal/cmdenv"
"github.com/gogf/gf/g/os/gfile"
"github.com/gogf/gf/g/os/gfsnotify"
"github.com/gogf/gf/g/os/glog"
"github.com/gogf/gf/g/os/gspath"
"github.com/gogf/gf/g/os/gtime"
)
const (
// DEFAULT_CONFIG_FILE is the default configuration file name.
DEFAULT_CONFIG_FILE = "config.toml"
)
// Configuration struct.
type Config struct {
name *gtype.String // Default configuration file name.
paths *garray.StringArray // Searching path array.
jsons *gmap.StrAnyMap // The pared JSON objects for configuration files.
vc *gtype.Bool // Whether do violence check in value index searching. It affects the performance when set true(false in default).
}
// New returns a new configuration management object.
// The parameter <file> specifies the default configuration file name for reading.
func New(file ...string) *Config {
name := DEFAULT_CONFIG_FILE
if len(file) > 0 {
name = file[0]
}
c := &Config{
name: gtype.NewString(name),
paths: garray.NewStringArray(),
jsons: gmap.NewStrAnyMap(),
vc: gtype.NewBool(),
}
// Customized dir path from env/cmd.
if envPath := cmdenv.Get("gf.gcfg.path").String(); envPath != "" {
if gfile.Exists(envPath) {
_ = c.SetPath(envPath)
} else {
if errorPrint() {
glog.Errorf("Configuration directory path does not exist: %s", envPath)
}
}
} else {
// Dir path of working dir.
_ = c.SetPath(gfile.Pwd())
// Dir path of binary.
if selfPath := gfile.SelfDir(); selfPath != "" && gfile.Exists(selfPath) {
_ = c.AddPath(selfPath)
}
// Dir path of main package.
if mainPath := gfile.MainPkgPath(); mainPath != "" && gfile.Exists(mainPath) {
_ = c.AddPath(mainPath)
}
}
return c
}
// filePath returns the absolute configuration file path for the given filename by <file>.
func (c *Config) filePath(file ...string) (path string) {
name := c.name.Val()
if len(file) > 0 {
name = file[0]
}
path = c.FilePath(name)
if path == "" {
buffer := bytes.NewBuffer(nil)
if c.paths.Len() > 0 {
buffer.WriteString(fmt.Sprintf("[gcfg] cannot find config file \"%s\" in following paths:", name))
c.paths.RLockFunc(func(array []string) {
index := 1
for _, v := range array {
buffer.WriteString(fmt.Sprintf("\n%d. %s", index, v))
index++
buffer.WriteString(fmt.Sprintf("\n%d. %s", index, v+gfile.Separator+"config"))
index++
}
})
} else {
buffer.WriteString(fmt.Sprintf("[gcfg] cannot find config file \"%s\" with no path set/add", name))
}
if errorPrint() {
glog.Error(buffer.String())
}
}
return path
}
// SetPath sets the configuration directory path for file search.
// The parameter <path> can be absolute or relative path,
// but absolute path is strongly recommended.
func (c *Config) SetPath(path string) error {
// Absolute path.
realPath := gfile.RealPath(path)
if realPath == "" {
// Relative path.
c.paths.RLockFunc(func(array []string) {
for _, v := range array {
if path, _ := gspath.Search(v, path); path != "" {
realPath = path
break
}
}
})
}
// Path not exist.
if realPath == "" {
buffer := bytes.NewBuffer(nil)
if c.paths.Len() > 0 {
buffer.WriteString(fmt.Sprintf("[gcfg] SetPath failed: cannot find directory \"%s\" in following paths:", path))
c.paths.RLockFunc(func(array []string) {
for k, v := range array {
buffer.WriteString(fmt.Sprintf("\n%d. %s", k+1, v))
}
})
} else {
buffer.WriteString(fmt.Sprintf(`[gcfg] SetPath failed: path "%s" does not exist`, path))
}
err := errors.New(buffer.String())
if errorPrint() {
glog.Error(err)
}
return err
}
// Should be a directory.
if !gfile.IsDir(realPath) {
err := fmt.Errorf(`[gcfg] SetPath failed: path "%s" should be directory type`, path)
if errorPrint() {
glog.Error(err)
}
return err
}
// Repeated path check.
if c.paths.Search(realPath) != -1 {
return nil
}
c.jsons.Clear()
c.paths.Clear()
c.paths.Append(realPath)
return nil
}
// SetViolenceCheck sets whether to perform hierarchical conflict check.
// This feature needs to be enabled when there is a level symbol in the key name.
// The default is off.
// Turning on this feature is quite expensive,
// and it is not recommended to allow separators in the key names.
// It is best to avoid this on the application side.
func (c *Config) SetViolenceCheck(check bool) {
c.vc.Set(check)
c.Clear()
}
// AddPath adds a absolute or relative path to the search paths.
func (c *Config) AddPath(path string) error {
// Absolute path.
realPath := gfile.RealPath(path)
if realPath == "" {
// Relative path.
c.paths.RLockFunc(func(array []string) {
for _, v := range array {
if path, _ := gspath.Search(v, path); path != "" {
realPath = path
break
}
}
})
}
if realPath == "" {
buffer := bytes.NewBuffer(nil)
if c.paths.Len() > 0 {
buffer.WriteString(fmt.Sprintf("[gcfg] AddPath failed: cannot find directory \"%s\" in following paths:", path))
c.paths.RLockFunc(func(array []string) {
for k, v := range array {
buffer.WriteString(fmt.Sprintf("\n%d. %s", k+1, v))
}
})
} else {
buffer.WriteString(fmt.Sprintf(`[gcfg] AddPath failed: path "%s" does not exist`, path))
}
err := errors.New(buffer.String())
if errorPrint() {
glog.Error(err)
}
return err
}
if !gfile.IsDir(realPath) {
err := fmt.Errorf(`[gcfg] AddPath failed: path "%s" should be directory type`, path)
if errorPrint() {
glog.Error(err)
}
return err
}
// Repeated path check.
if c.paths.Search(realPath) != -1 {
return nil
}
c.paths.Append(realPath)
//glog.Debug("[gcfg] AddPath:", realPath)
return nil
}
// GetFilePath is alias of FilePath.
// Deprecated.
func (c *Config) GetFilePath(file ...string) (path string) {
return c.FilePath(file...)
}
// GetFilePath returns the absolute path of the specified configuration file.
// If <file> is not passed, it returns the configuration file path of the default name.
// If the specified configuration file does not exist,
// an empty string is returned.
func (c *Config) FilePath(file ...string) (path string) {
name := c.name.Val()
if len(file) > 0 {
name = file[0]
}
c.paths.RLockFunc(func(array []string) {
for _, v := range array {
if path, _ = gspath.Search(v, name); path != "" {
break
}
if path, _ = gspath.Search(v+gfile.Separator+"config", name); path != "" {
break
}
}
})
return
}
// SetFileName sets the default configuration file name.
func (c *Config) SetFileName(name string) {
c.name.Set(name)
}
// GetFileName returns the default configuration file name.
func (c *Config) GetFileName() string {
return c.name.Val()
}
// getJson returns a *gjson.Json object for the specified <file> content.
// It would print error if file reading fails.
// If any error occurs, it return nil.
func (c *Config) getJson(file ...string) *gjson.Json {
name := c.name.Val()
if len(file) > 0 {
name = file[0]
}
r := c.jsons.GetOrSetFuncLock(name, func() interface{} {
content := ""
filePath := ""
if content = GetContent(name); content == "" {
filePath = c.filePath(name)
if filePath == "" {
return nil
}
content = gfile.GetContents(filePath)
}
if j, err := gjson.LoadContent(content); err == nil {
j.SetViolenceCheck(c.vc.Val())
// Add monitor for this configuration file,
// any changes of this file will refresh its cache in Config object.
if filePath != "" {
_, err = gfsnotify.Add(filePath, func(event *gfsnotify.Event) {
c.jsons.Remove(name)
})
if err != nil && errorPrint() {
glog.Error(err)
}
}
return j
} else {
if errorPrint() {
if filePath != "" {
glog.Criticalf(`[gcfg] Load config file "%s" failed: %s`, filePath, err.Error())
} else {
glog.Criticalf(`[gcfg] Load configuration failed: %s`, err.Error())
}
}
}
return nil
})
if r != nil {
return r.(*gjson.Json)
}
return nil
}
func (c *Config) Get(pattern string, def ...interface{}) interface{} {
if j := c.getJson(); j != nil {
return j.Get(pattern, def...)
}
return nil
}
func (c *Config) GetVar(pattern string, def ...interface{}) *gvar.Var {
if j := c.getJson(); j != nil {
return gvar.New(j.Get(pattern, def...), true)
}
return gvar.New(nil, true)
}
func (c *Config) Contains(pattern string) bool {
if j := c.getJson(); j != nil {
return j.Contains(pattern)
}
return false
}
func (c *Config) GetMap(pattern string, def ...interface{}) map[string]interface{} {
if j := c.getJson(); j != nil {
return j.GetMap(pattern, def...)
}
return nil
}
func (c *Config) GetArray(pattern string, def ...interface{}) []interface{} {
if j := c.getJson(); j != nil {
return j.GetArray(pattern, def...)
}
return nil
}
func (c *Config) GetString(pattern string, def ...interface{}) string {
if j := c.getJson(); j != nil {
return j.GetString(pattern, def...)
}
return ""
}
func (c *Config) GetStrings(pattern string, def ...interface{}) []string {
if j := c.getJson(); j != nil {
return j.GetStrings(pattern, def...)
}
return nil
}
func (c *Config) GetInterfaces(pattern string, def ...interface{}) []interface{} {
if j := c.getJson(); j != nil {
return j.GetInterfaces(pattern, def...)
}
return nil
}
func (c *Config) GetBool(pattern string, def ...interface{}) bool {
if j := c.getJson(); j != nil {
return j.GetBool(pattern, def...)
}
return false
}
func (c *Config) GetFloat32(pattern string, def ...interface{}) float32 {
if j := c.getJson(); j != nil {
return j.GetFloat32(pattern, def...)
}
return 0
}
func (c *Config) GetFloat64(pattern string, def ...interface{}) float64 {
if j := c.getJson(); j != nil {
return j.GetFloat64(pattern, def...)
}
return 0
}
func (c *Config) GetFloats(pattern string, def ...interface{}) []float64 {
if j := c.getJson(); j != nil {
return j.GetFloats(pattern, def...)
}
return nil
}
func (c *Config) GetInt(pattern string, def ...interface{}) int {
if j := c.getJson(); j != nil {
return j.GetInt(pattern, def...)
}
return 0
}
func (c *Config) GetInt8(pattern string, def ...interface{}) int8 {
if j := c.getJson(); j != nil {
return j.GetInt8(pattern, def...)
}
return 0
}
func (c *Config) GetInt16(pattern string, def ...interface{}) int16 {
if j := c.getJson(); j != nil {
return j.GetInt16(pattern, def...)
}
return 0
}
func (c *Config) GetInt32(pattern string, def ...interface{}) int32 {
if j := c.getJson(); j != nil {
return j.GetInt32(pattern, def...)
}
return 0
}
func (c *Config) GetInt64(pattern string, def ...interface{}) int64 {
if j := c.getJson(); j != nil {
return j.GetInt64(pattern, def...)
}
return 0
}
func (c *Config) GetInts(pattern string, def ...interface{}) []int {
if j := c.getJson(); j != nil {
return j.GetInts(pattern, def...)
}
return nil
}
func (c *Config) GetUint(pattern string, def ...interface{}) uint {
if j := c.getJson(); j != nil {
return j.GetUint(pattern, def...)
}
return 0
}
func (c *Config) GetUint8(pattern string, def ...interface{}) uint8 {
if j := c.getJson(); j != nil {
return j.GetUint8(pattern, def...)
}
return 0
}
func (c *Config) GetUint16(pattern string, def ...interface{}) uint16 {
if j := c.getJson(); j != nil {
return j.GetUint16(pattern, def...)
}
return 0
}
func (c *Config) GetUint32(pattern string, def ...interface{}) uint32 {
if j := c.getJson(); j != nil {
return j.GetUint32(pattern, def...)
}
return 0
}
func (c *Config) GetUint64(pattern string, def ...interface{}) uint64 {
if j := c.getJson(); j != nil {
return j.GetUint64(pattern, def...)
}
return 0
}
func (c *Config) GetTime(pattern string, format ...string) time.Time {
if j := c.getJson(); j != nil {
return j.GetTime(pattern, format...)
}
return time.Time{}
}
func (c *Config) GetDuration(pattern string, def ...interface{}) time.Duration {
if j := c.getJson(); j != nil {
return j.GetDuration(pattern, def...)
}
return 0
}
func (c *Config) GetGTime(pattern string, format ...string) *gtime.Time {
if j := c.getJson(); j != nil {
return j.GetGTime(pattern, format...)
}
return nil
}
func (c *Config) GetStruct(pattern string, pointer interface{}, mapping ...map[string]string) error {
if j := c.getJson(); j != nil {
return j.GetStruct(pattern, pointer, mapping...)
}
return errors.New("config file not found")
}
func (c *Config) GetStructDeep(pattern string, pointer interface{}, mapping ...map[string]string) error {
if j := c.getJson(); j != nil {
return j.GetStructDeep(pattern, pointer, mapping...)
}
return errors.New("config file not found")
}
func (c *Config) GetStructs(pattern string, pointer interface{}, mapping ...map[string]string) error {
if j := c.getJson(); j != nil {
return j.GetStructs(pattern, pointer, mapping...)
}
return errors.New("config file not found")
}
func (c *Config) GetStructsDeep(pattern string, pointer interface{}, mapping ...map[string]string) error {
if j := c.getJson(); j != nil {
return j.GetStructsDeep(pattern, pointer, mapping...)
}
return errors.New("config file not found")
}
// Deprecated.
func (c *Config) GetToStruct(pattern string, pointer interface{}) error {
return c.GetStruct(pattern, pointer)
}
// Reload is alias of Clear.
// Deprecated.
func (c *Config) Reload() {
c.jsons.Clear()
}
// Clear removes all parsed configuration files content cache,
// which will force reload configuration content from file.
func (c *Config) Clear() {
c.jsons.Clear()
}