-
Notifications
You must be signed in to change notification settings - Fork 145
/
conf.go
562 lines (491 loc) · 15 KB
/
conf.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
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
// Copyright 2013 Unknwon
//
// 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 goconfig is a fully functional and comments-support configuration file(.ini) parser.
package goconfig
import (
"fmt"
"regexp"
"runtime"
"strconv"
"strings"
"sync"
)
const (
// Default section name.
DEFAULT_SECTION = "DEFAULT"
// Maximum allowed depth when recursively substituing variable names.
_DEPTH_VALUES = 200
)
type ParseError int
const (
ERR_SECTION_NOT_FOUND ParseError = iota + 1
ERR_KEY_NOT_FOUND
ERR_BLANK_SECTION_NAME
ERR_COULD_NOT_PARSE
)
var LineBreak = "\n"
// Variable regexp pattern: %(variable)s
var varPattern = regexp.MustCompile(`%\(([^\)]+)\)s`)
func init() {
if runtime.GOOS == "windows" {
LineBreak = "\r\n"
}
}
// A ConfigFile represents a INI formar configuration file.
type ConfigFile struct {
lock sync.RWMutex // Go map is not safe.
fileNames []string // Support mutil-files.
data map[string]map[string]string // Section -> key : value
// Lists can keep sections and keys in order.
sectionList []string // Section name list.
keyList map[string][]string // Section -> Key name list
sectionComments map[string]string // Sections comments.
keyComments map[string]map[string]string // Keys comments.
BlockMode bool // Indicates whether use lock or not.
prettyFormat bool // Write spaces around "=" to look better.
}
// newConfigFile creates an empty configuration representation.
func newConfigFile(fileNames []string) *ConfigFile {
c := new(ConfigFile)
c.fileNames = fileNames
c.data = make(map[string]map[string]string)
c.keyList = make(map[string][]string)
c.sectionComments = make(map[string]string)
c.keyComments = make(map[string]map[string]string)
c.BlockMode = true
c.prettyFormat = true
return c
}
// SetValue adds a new section-key-value to the configuration.
// It returns true if the key and value were inserted,
// or returns false if the value was overwritten.
// If the section does not exist in advance, it will be created.
func (c *ConfigFile) SetValue(section, key, value string) bool {
// Blank section name represents DEFAULT section.
if len(section) == 0 {
section = DEFAULT_SECTION
}
if len(key) == 0 {
return false
}
if c.BlockMode {
c.lock.Lock()
defer c.lock.Unlock()
}
// Check if section exists.
if _, ok := c.data[section]; !ok {
// Execute add operation.
c.data[section] = make(map[string]string)
// Append section to list.
c.sectionList = append(c.sectionList, section)
}
// Check if key exists.
_, ok := c.data[section][key]
c.data[section][key] = value
if !ok {
// If not exists, append to key list.
c.keyList[section] = append(c.keyList[section], key)
}
return !ok
}
// DeleteKey deletes the key in given section.
// It returns true if the key was deleted,
// or returns false if the section or key didn't exist.
func (c *ConfigFile) DeleteKey(section, key string) bool {
// Blank section name represents DEFAULT section.
if len(section) == 0 {
section = DEFAULT_SECTION
}
if c.BlockMode {
c.lock.Lock()
defer c.lock.Unlock()
}
// Check if section exists.
if _, ok := c.data[section]; !ok {
return false
}
// Check if key exists.
if _, ok := c.data[section][key]; ok {
delete(c.data[section], key)
// Remove comments of key.
c.SetKeyComments(section, key, "")
// Get index of key.
i := 0
for _, keyName := range c.keyList[section] {
if keyName == key {
break
}
i++
}
// Remove from key list.
c.keyList[section] = append(c.keyList[section][:i], c.keyList[section][i+1:]...)
return true
}
return false
}
// GetValue returns the value of key available in the given section.
// If the value needs to be unfolded
// (see e.g. %(google)s example in the GoConfig_test.go),
// then String does this unfolding automatically, up to
// _DEPTH_VALUES number of iterations.
// It returns an error and empty string value if the section does not exist,
// or key does not exist in DEFAULT and current sections.
func (c *ConfigFile) GetValue(section, key string) (string, error) {
if c.BlockMode {
c.lock.RLock()
defer c.lock.RUnlock()
}
// Blank section name represents DEFAULT section.
if len(section) == 0 {
section = DEFAULT_SECTION
}
// Check if section exists
if _, ok := c.data[section]; !ok {
// Section does not exist.
return "", GetError{ERR_SECTION_NOT_FOUND, section}
}
// Section exists.
// Check if key exists or empty value.
value, ok := c.data[section][key]
if !ok {
// Check if it is a sub-section.
if i := strings.LastIndex(section, "."); i > -1 {
return c.GetValue(section[:i], key)
}
// Return empty value.
return "", GetError{ERR_KEY_NOT_FOUND, key}
}
// Key exists.
var i int
for i = 0; i < _DEPTH_VALUES; i++ {
vr := varPattern.FindString(value)
if len(vr) == 0 {
break
}
// Take off leading '%(' and trailing ')s'.
noption := strings.TrimLeft(vr, "%(")
noption = strings.TrimRight(noption, ")s")
// Search variable in default section.
nvalue, err := c.GetValue(DEFAULT_SECTION, noption)
if err != nil && section != DEFAULT_SECTION {
// Search in the same section.
if _, ok := c.data[section][noption]; ok {
nvalue = c.data[section][noption]
}
}
// Substitute by new value and take off leading '%(' and trailing ')s'.
value = strings.Replace(value, vr, nvalue, -1)
}
return value, nil
}
// Bool returns bool type value.
func (c *ConfigFile) Bool(section, key string) (bool, error) {
value, err := c.GetValue(section, key)
if err != nil {
return false, err
}
return strconv.ParseBool(value)
}
// Float64 returns float64 type value.
func (c *ConfigFile) Float64(section, key string) (float64, error) {
value, err := c.GetValue(section, key)
if err != nil {
return 0.0, err
}
return strconv.ParseFloat(value, 64)
}
// Int returns int type value.
func (c *ConfigFile) Int(section, key string) (int, error) {
value, err := c.GetValue(section, key)
if err != nil {
return 0, err
}
return strconv.Atoi(value)
}
// Int64 returns int64 type value.
func (c *ConfigFile) Int64(section, key string) (int64, error) {
value, err := c.GetValue(section, key)
if err != nil {
return 0, err
}
return strconv.ParseInt(value, 10, 64)
}
// MustValue always returns value without error.
// It returns empty string if error occurs, or the default value if given.
func (c *ConfigFile) MustValue(section, key string, defaultVal ...string) string {
val, err := c.GetValue(section, key)
if len(defaultVal) > 0 && (err != nil || len(val) == 0) {
return defaultVal[0]
}
return val
}
// MustValueSet always returns value without error,
// It returns empty string if error occurs, or the default value if given,
// and a bool value indicates whether default value is returned.
func (c *ConfigFile) MustValueSet(section, key string, defaultVal ...string) (string, bool) {
val, err := c.GetValue(section, key)
if len(defaultVal) > 0 && (err != nil || len(val) == 0) {
c.SetValue(section, key, defaultVal[0])
return defaultVal[0], true
}
return val, false
}
// MustValueRange always returns value without error,
// it returns default value if error occurs or doesn't fit into range.
func (c *ConfigFile) MustValueRange(section, key, defaultVal string, candidates []string) string {
val, err := c.GetValue(section, key)
if err != nil || len(val) == 0 {
return defaultVal
}
for _, cand := range candidates {
if val == cand {
return val
}
}
return defaultVal
}
// MustValueArray always returns value array without error,
// it returns empty array if error occurs, split by delimiter otherwise.
func (c *ConfigFile) MustValueArray(section, key, delim string) []string {
val, err := c.GetValue(section, key)
if err != nil || len(val) == 0 {
return []string{}
}
vals := strings.Split(val, delim)
for i := range vals {
vals[i] = strings.TrimSpace(vals[i])
}
return vals
}
// MustBool always returns value without error,
// it returns false if error occurs.
func (c *ConfigFile) MustBool(section, key string, defaultVal ...bool) bool {
val, err := c.Bool(section, key)
if len(defaultVal) > 0 && err != nil {
return defaultVal[0]
}
return val
}
// MustFloat64 always returns value without error,
// it returns 0.0 if error occurs.
func (c *ConfigFile) MustFloat64(section, key string, defaultVal ...float64) float64 {
value, err := c.Float64(section, key)
if len(defaultVal) > 0 && err != nil {
return defaultVal[0]
}
return value
}
// MustInt always returns value without error,
// it returns 0 if error occurs.
func (c *ConfigFile) MustInt(section, key string, defaultVal ...int) int {
value, err := c.Int(section, key)
if len(defaultVal) > 0 && err != nil {
return defaultVal[0]
}
return value
}
// MustInt64 always returns value without error,
// it returns 0 if error occurs.
func (c *ConfigFile) MustInt64(section, key string, defaultVal ...int64) int64 {
value, err := c.Int64(section, key)
if len(defaultVal) > 0 && err != nil {
return defaultVal[0]
}
return value
}
// GetSectionList returns the list of all sections
// in the same order in the file.
func (c *ConfigFile) GetSectionList() []string {
list := make([]string, len(c.sectionList))
copy(list, c.sectionList)
return list
}
// GetKeyList returns the list of all keys in give section
// in the same order in the file.
// It returns nil if given section does not exist.
func (c *ConfigFile) GetKeyList(section string) []string {
// Blank section name represents DEFAULT section.
if len(section) == 0 {
section = DEFAULT_SECTION
}
if c.BlockMode {
c.lock.RLock()
defer c.lock.RUnlock()
}
// Check if section exists.
if _, ok := c.data[section]; !ok {
return nil
}
// Non-default section has a blank key as section keeper.
list := make([]string, 0, len(c.keyList[section]))
for _, key := range c.keyList[section] {
if key != " " {
list = append(list, key)
}
}
return list
}
// DeleteSection deletes the entire section by given name.
// It returns true if the section was deleted, and false if the section didn't exist.
func (c *ConfigFile) DeleteSection(section string) bool {
// Blank section name represents DEFAULT section.
if len(section) == 0 {
section = DEFAULT_SECTION
}
if c.BlockMode {
c.lock.Lock()
defer c.lock.Unlock()
}
// Check if section exists.
if _, ok := c.data[section]; !ok {
return false
}
delete(c.data, section)
// Remove comments of section.
c.SetSectionComments(section, "")
// Get index of section.
i := 0
for _, secName := range c.sectionList {
if secName == section {
break
}
i++
}
// Remove from section and key list.
c.sectionList = append(c.sectionList[:i], c.sectionList[i+1:]...)
delete(c.keyList, section)
return true
}
// GetSection returns key-value pairs in given section.
// If section does not exist, returns nil and error.
func (c *ConfigFile) GetSection(section string) (map[string]string, error) {
// Blank section name represents DEFAULT section.
if len(section) == 0 {
section = DEFAULT_SECTION
}
if c.BlockMode {
c.lock.Lock()
defer c.lock.Unlock()
}
// Check if section exists.
if _, ok := c.data[section]; !ok {
// Section does not exist.
return nil, GetError{ERR_SECTION_NOT_FOUND, section}
}
// Remove pre-defined key.
secMap := deepCopy(c.data[section])
delete(secMap, " ")
// Section exists.
return secMap, nil
}
// SetSectionComments adds new section comments to the configuration.
// If comments are empty(0 length), it will remove its section comments!
// It returns true if the comments were inserted or removed,
// or returns false if the comments were overwritten.
func (c *ConfigFile) SetSectionComments(section, comments string) bool {
// Blank section name represents DEFAULT section.
if len(section) == 0 {
section = DEFAULT_SECTION
}
if len(comments) == 0 {
if _, ok := c.sectionComments[section]; ok {
delete(c.sectionComments, section)
}
// Not exists can be seen as remove.
return true
}
// Check if comments exists.
_, ok := c.sectionComments[section]
if comments[0] != '#' && comments[0] != ';' {
comments = "; " + comments
}
c.sectionComments[section] = comments
return !ok
}
// SetKeyComments adds new section-key comments to the configuration.
// If comments are empty(0 length), it will remove its section-key comments!
// It returns true if the comments were inserted or removed,
// or returns false if the comments were overwritten.
// If the section does not exist in advance, it is created.
func (c *ConfigFile) SetKeyComments(section, key, comments string) bool {
// Blank section name represents DEFAULT section.
if len(section) == 0 {
section = DEFAULT_SECTION
}
// Check if section exists.
if _, ok := c.keyComments[section]; ok {
if len(comments) == 0 {
if _, ok := c.keyComments[section][key]; ok {
delete(c.keyComments[section], key)
}
// Not exists can be seen as remove.
return true
}
} else {
if len(comments) == 0 {
// Not exists can be seen as remove.
return true
} else {
// Execute add operation.
c.keyComments[section] = make(map[string]string)
}
}
// Check if key exists.
_, ok := c.keyComments[section][key]
if comments[0] != '#' && comments[0] != ';' {
comments = "; " + comments
}
c.keyComments[section][key] = comments
return !ok
}
// GetSectionComments returns the comments in the given section.
// It returns an empty string(0 length) if the comments do not exist.
func (c *ConfigFile) GetSectionComments(section string) (comments string) {
// Blank section name represents DEFAULT section.
if len(section) == 0 {
section = DEFAULT_SECTION
}
return c.sectionComments[section]
}
// GetKeyComments returns the comments of key in the given section.
// It returns an empty string(0 length) if the comments do not exist.
func (c *ConfigFile) GetKeyComments(section, key string) (comments string) {
// Blank section name represents DEFAULT section.
if len(section) == 0 {
section = DEFAULT_SECTION
}
if _, ok := c.keyComments[section]; ok {
return c.keyComments[section][key]
}
return ""
}
// SetPrettyFormat set the prettyFormat to decide whether write spaces around "=".
func (c *ConfigFile) SetPrettyFormat(pretty bool) {
c.prettyFormat = pretty
}
// GetError occurs when get value in configuration file with invalid parameter.
type GetError struct {
Reason ParseError
Name string
}
// Error implements Error interface.
func (err GetError) Error() string {
switch err.Reason {
case ERR_SECTION_NOT_FOUND:
return fmt.Sprintf("section '%s' not found", err.Name)
case ERR_KEY_NOT_FOUND:
return fmt.Sprintf("key '%s' not found", err.Name)
}
return "invalid get error"
}