/
config.go
267 lines (232 loc) · 6.48 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
// Copyright 2017 The casbin Authors. All Rights Reserved.
//
// 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 config
import (
"bufio"
"bytes"
"errors"
"fmt"
"io"
"os"
"strconv"
"strings"
)
var (
// DEFAULT_SECTION specifies the name of a section if no name provided
DEFAULT_SECTION = "default"
// DEFAULT_COMMENT defines what character(s) indicate a comment `#`
DEFAULT_COMMENT = []byte{'#'}
// DEFAULT_COMMENT_SEM defines what alternate character(s) indicate a comment `;`
DEFAULT_COMMENT_SEM = []byte{';'}
// DEFAULT_MULTI_LINE_SEPARATOR defines what character indicates a multi-line content
DEFAULT_MULTI_LINE_SEPARATOR = []byte{'\\'}
)
// ConfigInterface defines the behavior of a Config implementation
type ConfigInterface interface {
String(key string) string
Strings(key string) []string
Bool(key string) (bool, error)
Int(key string) (int, error)
Int64(key string) (int64, error)
Float64(key string) (float64, error)
Set(key string, value string) error
}
// Config represents an implementation of the ConfigInterface
type Config struct {
// Section:key=value
data map[string]map[string]string
}
// NewConfig create an empty configuration representation from file.
func NewConfig(confName string) (ConfigInterface, error) {
c := &Config{
data: make(map[string]map[string]string),
}
err := c.parse(confName)
return c, err
}
// NewConfigFromText create an empty configuration representation from text.
func NewConfigFromText(text string) (ConfigInterface, error) {
c := &Config{
data: make(map[string]map[string]string),
}
err := c.parseBuffer(bufio.NewReader(strings.NewReader(text)))
return c, err
}
// AddConfig adds a new section->key:value to the configuration.
func (c *Config) AddConfig(section string, option string, value string) bool {
if section == "" {
section = DEFAULT_SECTION
}
if _, ok := c.data[section]; !ok {
c.data[section] = make(map[string]string)
}
_, ok := c.data[section][option]
c.data[section][option] = value
return !ok
}
func (c *Config) parse(fname string) (err error) {
f, err := os.Open(fname)
if err != nil {
return err
}
defer f.Close()
buf := bufio.NewReader(f)
return c.parseBuffer(buf)
}
func (c *Config) parseBuffer(buf *bufio.Reader) error {
var section string
var lineNum int
var buffer bytes.Buffer
var canWrite bool
for {
if canWrite {
if err := c.write(section, lineNum, &buffer); err != nil {
return err
} else {
canWrite = false
}
}
lineNum++
line, _, err := buf.ReadLine()
if err == io.EOF {
// force write when buffer is not flushed yet
if buffer.Len() > 0 {
if err := c.write(section, lineNum, &buffer); err != nil {
return err
}
}
break
} else if err != nil {
return err
}
line = bytes.TrimSpace(line)
switch {
case bytes.Equal(line, []byte{}), bytes.HasPrefix(line, DEFAULT_COMMENT_SEM),
bytes.HasPrefix(line, DEFAULT_COMMENT):
canWrite = true
continue
case bytes.HasPrefix(line, []byte{'['}) && bytes.HasSuffix(line, []byte{']'}):
// force write when buffer is not flushed yet
if buffer.Len() > 0 {
if err := c.write(section, lineNum, &buffer); err != nil {
return err
}
canWrite = false
}
section = string(line[1 : len(line)-1])
default:
var p []byte
if bytes.HasSuffix(line, DEFAULT_MULTI_LINE_SEPARATOR) {
p = bytes.TrimSpace(line[:len(line)-1])
p = append(p, " "...)
} else {
p = line
canWrite = true
}
end := len(p)
for i, value := range p {
if value == DEFAULT_COMMENT[0] || value == DEFAULT_COMMENT_SEM[0] {
end = i
break
}
}
if _, err := buffer.Write(p[:end]); err != nil {
return err
}
}
}
return nil
}
func (c *Config) write(section string, lineNum int, b *bytes.Buffer) error {
if b.Len() <= 0 {
return nil
}
optionVal := bytes.SplitN(b.Bytes(), []byte{'='}, 2)
if len(optionVal) != 2 {
return fmt.Errorf("parse the content error : line %d , %s = ? ", lineNum, optionVal[0])
}
option := bytes.TrimSpace(optionVal[0])
value := bytes.TrimSpace(optionVal[1])
c.AddConfig(section, string(option), string(value))
// flush buffer after adding
b.Reset()
return nil
}
// Bool lookups up the value using the provided key and converts the value to a bool
func (c *Config) Bool(key string) (bool, error) {
return strconv.ParseBool(c.get(key))
}
// Int lookups up the value using the provided key and converts the value to a int
func (c *Config) Int(key string) (int, error) {
return strconv.Atoi(c.get(key))
}
// Int64 lookups up the value using the provided key and converts the value to a int64
func (c *Config) Int64(key string) (int64, error) {
return strconv.ParseInt(c.get(key), 10, 64)
}
// Float64 lookups up the value using the provided key and converts the value to a float64
func (c *Config) Float64(key string) (float64, error) {
return strconv.ParseFloat(c.get(key), 64)
}
// String lookups up the value using the provided key and converts the value to a string
func (c *Config) String(key string) string {
return c.get(key)
}
// Strings lookups up the value using the provided key and converts the value to an array of string
// by splitting the string by comma
func (c *Config) Strings(key string) []string {
v := c.get(key)
if v == "" {
return nil
}
return strings.Split(v, ",")
}
// Set sets the value for the specific key in the Config
func (c *Config) Set(key string, value string) error {
if len(key) == 0 {
return errors.New("key is empty")
}
var (
section string
option string
)
keys := strings.Split(strings.ToLower(key), "::")
if len(keys) >= 2 {
section = keys[0]
option = keys[1]
} else {
option = keys[0]
}
c.AddConfig(section, option, value)
return nil
}
// section.key or key
func (c *Config) get(key string) string {
var (
section string
option string
)
keys := strings.Split(strings.ToLower(key), "::")
if len(keys) >= 2 {
section = keys[0]
option = keys[1]
} else {
section = DEFAULT_SECTION
option = keys[0]
}
if value, ok := c.data[section][option]; ok {
return value
}
return ""
}