-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathparser.go
57 lines (52 loc) · 1.38 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
package go_apache_config
import (
"bytes"
"errors"
"regexp"
)
var (
// Assumed that the line will be trimmed space
commentRegex = regexp.MustCompile(`^#.*`)
directiveRegex = regexp.MustCompile(`([^\s]+)\s*(.+)`)
sectionOpenRegex = regexp.MustCompile(`^<([^/\s]+)\s*([^>]+)?>`)
sectionCloseRegex = regexp.MustCompile(`^</([^\s]+)\s*>`)
)
func Parse(contents []byte) (*Node, error) {
if contents == nil {
return nil, errors.New("contents is empty")
}
var err error
currentNode := NewNode()
for _, line := range bytes.Split(contents, []byte("\n")) {
line = bytes.TrimSpace(line)
if len(line) == 0 || commentRegex.Match(line) {
continue
} else if sectionOpenRegex.Match(line) {
group := sectionOpenRegex.FindSubmatch(line)
if len(group) < 3 {
continue
}
name := string(group[1])
content := string(group[2])
currentNode, err = currentNode.CreateChildNode(&name, &content)
if err != nil {
return nil, err
}
} else if sectionCloseRegex.Match(line) {
currentNode = currentNode.Parent
} else if directiveRegex.Match(line) {
group := directiveRegex.FindSubmatch(line)
if len(group) < 3 {
continue
}
name := string(group[1])
content := string(group[2])
// CreateChildNode will return childNode
_, err = currentNode.CreateChildNode(&name, &content)
if err != nil {
return nil, err
}
}
}
return currentNode, nil
}