-
Notifications
You must be signed in to change notification settings - Fork 2
/
ini.go
84 lines (74 loc) · 2.13 KB
/
ini.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
package common
import (
"fmt"
"io/ioutil"
"strings"
tcerr "github.com/tencentcloud/tencentcloud-sdk-go-intl-en/tencentcloud/common/errors"
)
var (
globalSectionName = "____GLOBAL____"
iniErr = "ClientError.INIError"
)
func openFile(path string) (data []byte, err error) {
data, err = ioutil.ReadFile(path)
if err != nil {
err = tcerr.NewTencentCloudSDKError(iniErr, err.Error(), "")
}
return
}
func parse(path string) (*sections, error) {
result := §ions{map[string]*section{}}
buf, err := openFile(path)
if err != nil {
return §ions{}, err
}
content := string(buf)
lines := strings.Split(content, "\n")
if len(lines) == 0 {
msg := fmt.Sprintf("the result of reading the %s is empty", path)
return §ions{}, tcerr.NewTencentCloudSDKError(iniErr, msg, "")
}
currentSectionName := globalSectionName
currentSection := §ion{make(map[string]*value)}
for i, line := range lines {
line = strings.Replace(line, "\r", "", -1)
line = strings.TrimSpace(line)
if len(line) == 0 {
continue
}
// comments
if strings.HasPrefix(line, "#") || strings.HasPrefix(line, ";") {
continue
}
// section name
if strings.HasPrefix(line, "[") {
if strings.HasSuffix(line, "]") {
tempSection := line[1 : len(line)-1]
if len(tempSection) == 0 {
msg := fmt.Sprintf("INI file %s lien %d is not valid: wrong section", path, i)
return result, tcerr.NewTencentCloudSDKError(iniErr, msg, "")
}
// Save the previous section
result.contains[currentSectionName] = currentSection
// new section
currentSectionName = tempSection
currentSection = §ion{make(map[string]*value, 0)}
continue
} else {
msg := fmt.Sprintf("INI file %s lien %d is not valid: wrong section", path, i)
return result, tcerr.NewTencentCloudSDKError(iniErr, msg, "")
}
}
pos := strings.Index(line, "=")
if pos > 0 && pos < len(line)-1 {
key := line[:pos]
val := line[pos+1:]
key = strings.TrimSpace(key)
val = strings.TrimSpace(val)
v := &value{raw: val}
currentSection.content[key] = v
}
}
result.contains[currentSectionName] = currentSection
return result, nil
}