-
Notifications
You must be signed in to change notification settings - Fork 3
/
config.go
102 lines (90 loc) · 2.1 KB
/
config.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
package main
import (
"bufio"
"errors"
"fmt"
"os"
"regexp"
"strings"
"github.com/miaogaolin/excel-proc/utils"
)
type ConfigSection struct {
Template string
Condition string
}
type Config struct {
Fields map[string]string
Sections []ConfigSection
}
func ReadConfig(path string) (*Config, error) {
f, err := os.Open(path)
if err != nil {
return nil, err
}
defer f.Close()
scanner := bufio.NewScanner(f)
var (
section []string
configSections []ConfigSection
line int
)
fields := map[string]string{}
for {
if !scanner.Scan() {
// 跳出前把 section 中的配置数据解析
if len(section) > 0 {
tmp, err := getSectionConfig(section)
if err != nil {
return nil, fmt.Errorf("line num %d, %v", line, err)
}
configSections = append(configSections, *tmp)
}
break
}
line++
text := scanner.Text()
trimText := strings.TrimSpace(text)
// read fields
if len(section) == 0 && trimText != "" {
reg := regexp.MustCompile(`(\w+):\s*(?:"([^"]*)"|'([^']*)'|(\S+))`)
fieldsText := reg.FindSubmatch([]byte(trimText))
if len(fieldsText) == 5 {
fields[string(fieldsText[1])] = string(fieldsText[2]) + string(fieldsText[3]) + string(fieldsText[4])
continue
}
}
// 按照空行划分
if trimText == "" && len(section) > 0 {
tmp, err := getSectionConfig(section)
if err != nil {
return nil, fmt.Errorf("line num %d, %v", line, err)
}
configSections = append(configSections, *tmp)
section = nil
} else if trimText != "" {
section = append(section, text)
}
}
return &Config{
Sections: configSections,
Fields: fields,
}, nil
}
func getSectionConfig(section []string) (*ConfigSection, error) {
if len(section) == 0 {
return nil, errors.New("config is empty")
}
var cfg ConfigSection
// have condition staement
if strings.HasPrefix(section[0], ";") {
cfg.Condition = strings.TrimLeft(section[0], ";")
if len(section) == 1 {
return nil, errors.New("template is empty")
}
section = section[1:]
}
for _, v := range section {
cfg.Template += v + utils.LineSeperator()
}
return &cfg, nil
}