-
Notifications
You must be signed in to change notification settings - Fork 3.9k
/
ini.go
100 lines (86 loc) · 2.71 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
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
/*
Copyright 2021 The Kubernetes Authors.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package common
import (
"fmt"
"io/ioutil"
"strings"
tcerr "k8s.io/autoscaler/cluster-autoscaler/cloudprovider/tencentcloud/tencentcloud-sdk-go/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
}