-
Notifications
You must be signed in to change notification settings - Fork 6
/
parse_tree.go
106 lines (92 loc) · 1.87 KB
/
parse_tree.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
package ini
type invalidKeyErr struct {
err string
}
func (e *invalidKeyErr) Error() string {
return "invalid key: " + e.err
}
type parseTree struct {
global section
sections map[string][]section
}
func newParseTree() parseTree {
return parseTree{
global: newSection(""),
sections: make(map[string][]section),
}
}
func (p *parseTree) add(s section) {
sections, ok := p.sections[s.name]
if !ok {
sections = make([]section, 0)
}
sections = append(sections, s)
p.sections[s.name] = sections
}
func (p *parseTree) get(name string) ([]section, error) {
if name == "" {
return nil, &invalidKeyErr{"section name cannot be empty"}
}
if name == "*" {
sections := make([]section, 0)
for _, v := range p.sections {
sections = append(sections, v...)
}
return sections, nil
}
sections, ok := p.sections[name]
if !ok {
return nil, &invalidKeyErr{"section '" + name + "' does not exist"}
}
return sections, nil
}
type section struct {
name string
props map[string]property
}
func newSection(name string) section {
return section{
name: name,
props: make(map[string]property),
}
}
func (s *section) add(p property) {
s.props[p.key] = p
}
func (s *section) get(key string) (*property, error) {
if key == "" {
return nil, &invalidKeyErr{"property key cannot be empty"}
}
prop, ok := s.props[key]
if !ok {
prop = newProperty(key)
s.props[key] = prop
}
return &prop, nil
}
type property struct {
key string
vals map[string][]string
}
func newProperty(key string) property {
return property{
key: key,
vals: make(map[string][]string),
}
}
func (p *property) add(key, value string) {
vals, ok := p.vals[key]
if !ok {
vals = make([]string, 0)
}
vals = append(vals, value)
p.vals[key] = vals
}
func (p *property) get(key string) []string {
vals, ok := p.vals[key]
if !ok {
vals = make([]string, 0)
p.vals[key] = vals
}
return vals
}