-
Notifications
You must be signed in to change notification settings - Fork 117
Expand file tree
/
Copy pathini.go
More file actions
77 lines (59 loc) · 1.48 KB
/
ini.go
File metadata and controls
77 lines (59 loc) · 1.48 KB
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
package persister
import (
"bytes"
"fmt"
"io/ioutil"
"strings"
)
// TODO: migrate to toml?
func parseIniFile(filename string) ([]map[string]string, error) {
body, err := ioutil.ReadFile(filename)
if err != nil {
return nil, err
}
lines := bytes.Split(body, []byte{'\n'})
config := make([]map[string]string, 0)
var section map[string]string
lineLoop:
for i := 0; i < len(lines); i++ {
line := strings.TrimSpace(string(lines[i]))
if len(line) == 0 {
continue lineLoop
}
if line[0] == ';' || line[0] == '#' {
continue lineLoop
}
if line[0] == '[' {
if line[len(line)-1] != ']' {
return nil, fmt.Errorf("line %d: unfinished section name", i+1)
}
name := strings.TrimSpace(line[1 : len(line)-1])
if len(name) == 0 {
return nil, fmt.Errorf("line %d: empty section name", i+1)
}
// start new section
if section != nil {
config = append(config, section)
}
section = map[string]string{"name": name}
continue lineLoop
}
if section == nil {
return nil, fmt.Errorf("line %d: config section not found", i+1)
}
kv := strings.SplitN(line, "=", 2)
if len(kv) != 2 {
return nil, fmt.Errorf("line %d: key = value not found", i+1)
}
key := strings.ToLower(strings.TrimSpace(kv[0]))
value := strings.Trim(strings.TrimSpace(kv[1]), "\"'")
if key == "" {
return nil, fmt.Errorf("line %d: key is empty", i+1)
}
section[key] = value
}
if section != nil {
config = append(config, section)
}
return config, nil
}