-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsection.go
103 lines (88 loc) · 1.82 KB
/
section.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
package configure
import (
"errors"
"fmt"
"regexp"
"runtime"
)
var (
Description = "# .*"
Equation = ".* = .*"
)
func init() {
if runtime.GOOS == "windows" {
Description = "; .*"
} else {
Description = "# .*"
}
}
var (
EmptySection = errors.New("ERROR: This section is empty")
NoSuchItem = errors.New("ERROR: This section has no item of this name")
)
type Section struct {
name string // 区域名称
items []*Item // 该区域下的全部 Item
file *File // 该区域所属的配置文件
}
func newSection(name string, f *File) *Section {
return &Section{
name: name,
file: f,
}
}
func (s *Section) appendItem(item *Item) {
for i, _ := range s.items {
if s.items[i].name == item.name {
s.items[i].val = item.val
return
}
}
s.items = append(s.items, item)
}
func (s *Section) Name() string {
return s.name
}
func (s *Section) AppendInFile(f *File) {
s.file = f
}
func (s *Section) key(name string) (item *Item, err error) {
err = nil
for i := range s.items {
if s.items[i].Name() == name {
item = s.items[i]
return
}
}
err = ObjectNotFound{Name: name, Type: "item"}
return
}
func (s *Section) Key(name string) (item *Item) {
item, err := s.key(name)
if err != nil {
return nil
} else {
return item
}
}
func NewSection(name string, content []string, f *File) (s *Section, e error) {
s = newSection(name, f)
desp := ""
for _, line := range content {
// 为描述
if matched, _ := regexp.MatchString(Description, line); matched {
desp += splitFirst(line)
} else if matched, _ := regexp.MatchString(Equation, line); matched {
// 为创建新的key
item := NewItem(s, line, desp)
desp = ""
s.appendItem(item)
} else {
fmt.Println(line)
// 异常
e = ConfigFormatError{Sentence: line, Filename: f.file.Name()}
return nil, e
}
}
return s, nil
}