-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathconf_line.go
100 lines (85 loc) · 1.76 KB
/
conf_line.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
package config
import (
"fmt"
"strings"
)
const (
lineEmpty = iota
lineConfGroup
lineKeyValue
lineErr
)
type confLine struct {
text string
lineT int
key string
value string
groupName string
}
func newConfLine(text string) *confLine {
return &confLine{text: text}
}
func (l *confLine) parse() (lineType int, err error) {
text := l.trim()
// is empty string.
if text == "" {
return lineEmpty, nil
}
// parse key&value
parts := []string{}
switch {
case strings.Contains(text, " = "):
parts = strings.Split(text, " = ")
case strings.Contains(text, " ="):
parts = strings.Split(text, " =")
}
if len(parts) == 2 {
l.lineT = lineKeyValue
l.key = parts[0]
value := strings.Trim(parts[1], "\"")
value = strings.Trim(value, "'")
l.value = value
return l.lineT, nil
} else if len(parts) != 2 && len(parts) > 0 {
l.lineT = lineErr
return lineErr, fmt.Errorf("does not support the config line: %s", l.text)
}
// parse conf group name.
if len(text) >= 3 && strings.HasPrefix(text, "[") && strings.HasSuffix(text, "]") {
l.groupName = text[1 : len(text)-1]
l.lineT = lineConfGroup
return lineConfGroup, nil
}
l.lineT = lineErr
return lineErr, fmt.Errorf("does not support the config line: %s", l.text)
}
func (l *confLine) trim() string {
text := strings.TrimSpace(l.text)
for i, v := range text {
if v == '#' {
// if index is 0.
if i == 0 {
return ""
}
// if index is not 0.
if text[i-1] == ' ' {
return strings.TrimSpace(text[:i-1])
}
}
}
return text
}
func (l *confLine) keyValue() (key, value string) {
if l.lineT == lineKeyValue {
key = l.key
value = l.value
return
}
return
}
func (l *confLine) confGroupName() string {
if l.lineT == lineConfGroup {
return l.groupName
}
return ""
}