-
Notifications
You must be signed in to change notification settings - Fork 0
/
Parse.go
92 lines (85 loc) · 1.83 KB
/
Parse.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
package gini
import "fmt"
func fileToMap(data []string) map[string]map[string]string {
result := make(map[string]map[string]string)
for i := 0; i < len(data); i++ {
if len(data[i]) <= 0 {
continue
}
if data[i][0] == '[' {
name := getSectionName(data[i])
i += 1
result[name] = parseFields(data, &i)
}
}
return result
}
func parseFields(data []string, i *int) map[string]string {
result := make(map[string]string)
for ; *i < len(data); *i++ {
if len(data[*i]) <= 0 {
continue
}
if data[*i][0] == '\n' || data[*i][0] == '\t' || data[*i][0] == '#' || data[*i][0] == ';' {
continue
}
if data[*i][0] == '[' {
*i -= 1
return result
}
result[getFieldName(data[*i])] = getFieldValue(data[*i])
}
return result
}
func getSectionName(data string) string {
result := ""
for i := range data {
if data[i] != '[' && data[i] != ']' {
result += string(data[i])
}
}
return result
}
func getFieldName(data string) string {
result := ""
for i := range data {
if data[i] == '=' {
break
}
if data[i] != ' ' && data[i] != '\t' {
result += string(data[i])
}
}
return result
}
func getFieldValue(data string) string {
result := ""
isValue := false
for i := range data {
if data[i] == '=' {
isValue = true
continue
}
if isValue && (data[i] == ';' || data[i] == '#') {
break
}
if isValue && data[i] != ' ' && data[i] != '\t' {
result += string(data[i])
}
}
return result
}
func mapToFile(data map[string]map[string]string) []string {
result := make([]string, 0)
for section := range data {
if len(section) == 0 {
continue
}
result = append(result, fmt.Sprintf("[%s]", section))
for sectionField := range data[section] {
result = append(result, fmt.Sprintf("%s\t=\t%s", sectionField, data[section][sectionField]))
}
result = append(result, "\n")
}
return result
}