-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathloader.go
397 lines (362 loc) · 8.46 KB
/
loader.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
package ini
import (
"bufio"
"bytes"
"errors"
"fmt"
"io"
"os"
"strconv"
"strings"
"unicode"
)
// remove inline comments
//
// inline comments must start with ';' or '#'
// and the char before the ';' or '#' must be a space
//
func removeComments(value string) string {
n := len(value)
i := 0
for ; i < n; i++ {
if value[i] == '\\' {
i++
} else if value[i] == ';' || value[i] == '#' {
if i > 0 && unicode.IsSpace(rune(value[i-1])) {
return strings.TrimSpace(value[0:i])
}
}
}
return strings.TrimSpace(value)
}
// check if it is a oct char,e.g. must be char '0' to '7'
//
func isOctChar(ch byte) bool {
return ch >= '0' && ch <= '7'
}
// check if the char is a hex char, e.g. the char
// must be '0'..'9' or 'a'..'f' or 'A'..'F'
//
func isHexChar(ch byte) bool {
return ch >= '0' && ch <= '9' ||
ch >= 'a' && ch <= 'f' ||
ch >= 'A' && ch <= 'F'
}
func fromEscape(value string) string {
if strings.Index(value, "\\") == -1 {
return value
}
r := ""
n := len(value)
for i := 0; i < n; i++ {
if value[i] == '\\' {
if i+1 < n {
i++
//if is it oct
if i+2 < n && isOctChar(value[i]) && isOctChar(value[i+1]) && isOctChar(value[i+2]) {
t, err := strconv.ParseInt(value[i:i+3], 8, 32)
if err == nil {
r = r + string(rune(t))
}
i += 2
continue
}
switch value[i] {
case '0':
r = r + string(byte(0))
case 'a':
r = r + "\a"
case 'b':
r = r + "\b"
case 'f':
r = r + "\f"
case 't':
r = r + "\t"
case 'r':
r = r + "\r"
case 'n':
r = r + "\n"
case 'v':
r = r + "\v"
case 'x':
i++
if i+3 < n && isHexChar(value[i]) &&
isHexChar(value[i+1]) &&
isHexChar(value[i+2]) &&
isHexChar(value[i+3]) {
t, err := strconv.ParseInt(value[i:i+4], 16, 32)
if err == nil {
r = r + string(rune(t))
}
i += 3
}
default:
r = fmt.Sprintf("%s%c", r, value[i])
}
}
} else {
r = fmt.Sprintf("%s%c", r, value[i])
}
}
return r
}
func toEscape(s string) string {
result := bytes.NewBuffer(make([]byte, 0))
n := len(s)
for i := 0; i < n; i++ {
switch s[i] {
case 0:
result.WriteString("\\0")
case '\\':
result.WriteString("\\\\")
case '\a':
result.WriteString("\\a")
case '\b':
result.WriteString("\\b")
case '\t':
result.WriteString("\\t")
case '\r':
result.WriteString("\\r")
case '\n':
result.WriteString("\\n")
case ';':
result.WriteString("\\;")
case '#':
result.WriteString("\\#")
case '=':
result.WriteString("\\=")
case ':':
result.WriteString("\\:")
default:
result.WriteByte(s[i])
}
}
return result.String()
}
func removeContinuationSuffix(value string) (string, bool) {
pos := strings.LastIndex(value, "\\")
n := len(value)
if pos == -1 || pos != n-1 {
return "", false
}
for pos >= 0 {
if value[pos] != '\\' {
return "", false
}
pos--
if pos < 0 || value[pos] != '\\' {
return value[0 : n-1], true
}
pos--
}
return "", false
}
type lineReader struct {
reader *bufio.Scanner
}
func newLineReader(reader io.Reader) *lineReader {
return &lineReader{reader: bufio.NewScanner(reader)}
}
func (lr *lineReader) readLine() (string, error) {
if lr.reader.Scan() {
return lr.reader.Text(), nil
}
return "", errors.New("No data")
}
func readLinesUntilSuffix(lineReader *lineReader, suffix string) string {
r := ""
for {
line, err := lineReader.readLine()
if err != nil {
break
}
t := strings.TrimRightFunc(line, unicode.IsSpace)
if strings.HasSuffix(t, suffix) {
r = r + t[0:len(t)-len(suffix)]
break
} else {
r = r + line + "\n"
}
}
return r
}
// if a line enss with char '\', we can read the next line
//
func readContinuationLines(lineReader *lineReader) string {
r := ""
for {
line, err := lineReader.readLine()
if err != nil {
break
}
line = strings.TrimRightFunc(line, unicode.IsSpace)
if t, continuation := removeContinuationSuffix(line); continuation {
r = r + t
} else {
r = r + line
break
}
}
return r
}
/*
Load from the sources, the source can be one of:
- fileName
- a string includes .ini
- io.Reader the reader to load the .ini contents
- byte array incldues .ini content
*/
func (ini *Ini) Load(sources ...interface{}) {
for _, source := range sources {
switch source.(type) {
case string:
s, _ := source.(string)
if _, err := os.Stat(s); err == nil {
ini.LoadFile(s)
} else {
ini.LoadString(s)
}
case io.Reader:
reader, _ := source.(io.Reader)
ini.LoadReader(reader)
case []byte:
b, _ := source.([]byte)
ini.LoadBytes(b)
}
}
}
// return the number of spaces before non-space chars
func getIndent(s string) int {
n := 0
for i := 0; i < len(s); i++ {
if unicode.IsSpace(rune(s[i])) {
n++
} else {
break
}
}
return n
}
func isCommentLine(line string) bool {
line = strings.TrimSpace(line)
return len(line) <= 0 || line[0] == ';' || line[0] == '#'
}
// parse the section if it is a section line
// Return section name if it is a section else return nil
func parseSectionName(line string) *string {
line = strings.TrimSpace(line)
if strings.HasPrefix(line, "[") && strings.HasSuffix(line, "]") {
sectionName := strings.TrimSpace(line[1 : len(line)-1])
return §ionName
} else {
return nil
}
}
// Explicitly loads .ini from a reader
//
func (ini *Ini) LoadReader(reader io.Reader) {
lineReader := newLineReader(reader)
var curSection *Section = nil
keyIndent := -1
prevKey := ""
for {
line, err := lineReader.readLine()
if err != nil {
break
}
//if this line is value of the key
if keyIndent >= 0 && getIndent(line) > keyIndent && curSection != nil && prevKey != "" {
v := curSection.GetValueWithDefault(prevKey, "")
v = fmt.Sprintf("%s\n%s", v, fromEscape(removeComments(line)))
curSection.Add(prevKey, v )
continue
}
//empty line or comments line
if isCommentLine(line) {
continue
}
//if it is a section
sectionName := parseSectionName( line )
if sectionName != nil {
curSection = ini.NewSection(*sectionName)
// reset the previous key and the key indent
prevKey = ""
keyIndent = -1
continue
}
//key&value is separated with = or :
pos := strings.IndexAny(line, "=:")
if pos != -1 {
keyIndent = getIndent(line)
key := strings.TrimSpace(line[0:pos])
prevKey = key
value := strings.TrimLeftFunc(line[pos+1:], unicode.IsSpace)
//if it is a multiline indicator """
if strings.HasPrefix(value, "\"\"\"") {
t := strings.TrimRightFunc(value, unicode.IsSpace)
//if the end multiline indicator is found
if strings.HasSuffix(t, "\"\"\"") {
value = t[3 : len(t)-3]
} else { //read lines until end multiline indicator is found
value = value[3:] + "\n" + readLinesUntilSuffix(lineReader, "\"\"\"")
}
} else {
value = strings.TrimRightFunc(value, unicode.IsSpace)
//if is it a continuation line
if t, continuation := removeContinuationSuffix(value); continuation {
value = t + readContinuationLines(lineReader)
}
}
if len(key) > 0 {
if curSection == nil && len(ini.defaultSectionName) > 0 {
curSection = ini.NewSection(ini.defaultSectionName)
}
if curSection != nil {
//remove the comments and convert escape char to real
curSection.Add(key, strings.TrimSpace(fromEscape(removeComments(value))))
}
}
}
}
}
// Load ini file from file named fileName
//
func (ini *Ini) LoadFile(fileName string) {
f, err := os.Open(fileName)
if err == nil {
defer f.Close()
ini.Load(f)
}
}
var defaultSectionName string = "default"
func SetDefaultSectionName(defSectionName string) {
defaultSectionName = defSectionName
}
// load ini from the content which contains the .ini formated string
//
func (ini *Ini) LoadString(content string) {
ini.Load(bytes.NewBufferString(content))
}
// load .ini from a byte array which contains the .ini formated content
func (ini *Ini) LoadBytes(content []byte) {
ini.Load(bytes.NewBuffer(content))
}
/*
Load the .ini from one of following resource:
- file
- string in .ini format
- byte array in .ini format
- io.Reader a reader to load .ini content
One or more source can be provided in this Load method, such as:
var reader1 io.Reader = ...
var reader2 io.Reader = ...
ini.Load( "./my.ini", "[section]\nkey=1", "./my2.ini", reader1, reader2 )
*/
func Load(sources ...interface{}) *Ini {
ini := NewIni()
ini.SetDefaultSectionName(defaultSectionName)
for _, source := range sources {
ini.Load(source)
}
return ini
}