-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathparser.go
99 lines (90 loc) · 2.15 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
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
package configure
import (
"regexp"
"strings"
)
const (
SectionExp = "\\[[a-zA-Z0-9]*\\]"
)
// 解析配置文件的解析器实体
type Parser struct {
content string
option Option
}
// 解析配置文件,将结果写入 f, 如果有异常则返回异常
func (p *Parser) parse(f *File) (err error) {
var secs []*Section
lines := strings.Split(p.content, p.option.Separation)
var secStart []int
lines = deleteEmpty(lines)
for i, line := range lines {
if matched, _ := regexp.MatchString(SectionExp, line); matched {
secStart = append(secStart, i)
}
}
secName := "default"
prevSec := 0
endSec := 0
// 此时整个分区都是 default 分区
if len(secStart) == 0 {
section, err := NewSection(secName, lines, f)
if err != nil {
return err
}
secs = append(secs, section)
return nil
}
// 若没有默认分区
if secStart[0] == 0 {
secName = getSecName(lines[0])
for i := 0; i < len(secStart); i++ {
if i == len(secStart)-1 {
// 到达最后一个区域,则最后的内容都归为第一个区域
endSec = len(lines)
} else {
endSec = secStart[i+1]
}
prevSec := secStart[i] + 1
content := lines[prevSec:endSec]
secName = getSecName(lines[secStart[i]])
section, err := NewSection(secName, content, f)
if err != nil {
return err
}
secs = append(secs, section)
}
} else {
// 存在默认分区,第一个分区就是默认分区
content := lines[prevSec:secStart[0]]
section, err := NewSection(secName, content, f)
if err != nil {
return err
}
secs = append(secs, section)
for i := 0; i < len(secStart); i++ {
if i == len(secStart)-1 {
// 到达最后一个区域,则最后的内容都归为第一个区域
endSec = len(lines)
} else {
endSec = secStart[i+1]
}
prevSec := secStart[i] + 1
content := lines[prevSec:endSec]
secName = getSecName(lines[secStart[i]])
section, err := NewSection(secName, content, f)
if err != nil {
return err
}
secs = append(secs, section)
}
}
f.sections = secs
return nil
}
// 新建一个转换器
func newParser(s string, option Option) *Parser {
return &Parser{
option: option,
content: s,
}
}