forked from vaughan0/go-ini
-
Notifications
You must be signed in to change notification settings - Fork 0
/
parser.go
77 lines (71 loc) · 1.88 KB
/
parser.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
package ini
import (
"bufio"
"regexp"
"strings"
)
var (
sectionRegex = regexp.MustCompile(`^\[(.*)\]$`)
assignArrRegex = regexp.MustCompile(`^([^=\[\]]+)\[\][^=]*=(.*)$`)
assignRegex = regexp.MustCompile(`^([^=]+)=(.*)$`)
quotesRegex = regexp.MustCompile(`^(['"])(.*)(['"])$`)
)
func trimWithQuotes(inputVal string) (ret string) {
ret = strings.TrimSpace(inputVal)
groups := quotesRegex.FindStringSubmatch(ret)
if groups != nil {
if groups[1] == groups[3] {
ret = groups[2]
}
}
return
}
func parseFile(in *bufio.Scanner, file *file) (bytes int64, err error) {
section := ""
lineNum := 0
bytes = -1
readLine := true
for readLine = in.Scan(); readLine; readLine = in.Scan() {
line := in.Text()
bytes++
bytes += int64(len(line))
lineNum++
line = strings.TrimSpace(line)
if len(line) == 0 {
// Skip blank lines
continue
}
if line[0] == ';' || line[0] == '#' {
// Skip comments
continue
}
if groups := assignArrRegex.FindStringSubmatch(line); groups != nil {
key, val := groups[1], groups[2]
key, val = strings.TrimSpace(key), trimWithQuotes(val)
curVal, ok := file.section(section).arrayValues[key]
if ok {
file.section(section).arrayValues[key] = append(curVal, val)
} else {
file.section(section).arrayValues[key] = make([]string, 1, 4)
file.section(section).arrayValues[key][0] = val
}
} else if groups := assignRegex.FindStringSubmatch(line); groups != nil {
key, val := groups[1], groups[2]
key, val = strings.TrimSpace(key), trimWithQuotes(val)
file.section(section).stringValues[key] = val
} else if groups := sectionRegex.FindStringSubmatch(line); groups != nil {
name := strings.TrimSpace(groups[1])
section = name
// Create the section if it does not exist
file.section(section)
} else {
err = ErrSyntax{lineNum, line}
return
}
}
if bytes < 0 {
bytes = 0
}
err = in.Err()
return
}