-
Notifications
You must be signed in to change notification settings - Fork 0
/
properties_parser.go
117 lines (92 loc) · 2.57 KB
/
properties_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
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
package gitfmt
import (
"errors"
"strings"
"github.com/bitwormhole/gitlib/git"
)
// ParseProperties 函数把参数 text 解析为属性表,存入dest中。
func ParseProperties(text string, container *git.Properties) (*git.Properties, error) {
if container == nil {
container = &git.Properties{}
}
parser := &simplePropertiesParser{}
parser.output = container
parser.parse(text)
return container, parser.err
}
////////////////////////////////////////////////////////////////////////////////
type simplePropertiesParser struct {
output *git.Properties
err error
errLineNum int
keyPrefix string
}
func (inst *simplePropertiesParser) parse(text string) {
text = strings.ReplaceAll(text, "\r", "\n")
lines := strings.Split(text, "\n")
for index := range lines {
line := strings.TrimSpace(lines[index])
err := inst.handleLine(line)
if err != nil {
inst.err = err
inst.errLineNum = index + 1
break
}
}
}
func (inst *simplePropertiesParser) handleLine(line string) error {
if len(line) == 0 {
return nil
}
if strings.HasPrefix(line, "#") {
return nil
}
if strings.HasPrefix(line, "[") && strings.HasSuffix(line, "]") {
return inst.handleSegment(line)
}
return inst.handleKeyValue(line)
}
func (inst *simplePropertiesParser) handleSegment(line string) error {
const quotation string = "\""
line = strings.ReplaceAll(line, "'", quotation)
i1 := strings.IndexRune(line, '[')
i2 := strings.Index(line, quotation)
i3 := strings.LastIndex(line, quotation)
i4 := strings.IndexRune(line, ']')
line = strings.ReplaceAll(line, "[", quotation)
line = strings.ReplaceAll(line, "]", quotation)
parts := strings.Split(line, quotation)
part1 := ""
part2 := ""
if (0 <= i1) && (i1 < i2) && (i2 < i3) && (i3 < i4) {
part1 = parts[1]
part2 = parts[2]
} else if (0 <= i1) && (i1 < i4) && (i2 < 0) && (i3 < 0) {
part1 = parts[1]
} else {
return errors.New("bad segment line: " + line)
}
part1 = strings.TrimSpace(part1)
part2 = strings.TrimSpace(part2)
if len(part1) > 0 && len(part2) > 0 {
inst.keyPrefix = part1 + "." + part2 + "."
} else if len(part1) > 0 && len(part2) == 0 {
inst.keyPrefix = part1 + "."
} else {
inst.keyPrefix = ""
}
return nil
}
func (inst *simplePropertiesParser) handleKeyValue(line string) error {
parts := strings.SplitN(line, "=", 2)
if len(parts) != 2 {
return errors.New("the line is not in format of 'key=value'")
}
key := strings.TrimSpace(parts[0])
val := strings.TrimSpace(parts[1])
if len(key) == 0 || len(val) == 0 {
return nil
}
inst.output.Set(inst.keyPrefix+key, val)
return nil
}