-
Notifications
You must be signed in to change notification settings - Fork 3
/
yaml.go
75 lines (67 loc) · 1.66 KB
/
yaml.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
package junocfg
import (
"bytes"
"fmt"
"gopkg.in/yaml.v2"
"strings"
)
func yaml2Items(data []byte) (ItemArray, error) {
yamlMap := map[string]interface{}{}
err := yaml.Unmarshal(data, &yamlMap)
if err != nil {
return nil, fmt.Errorf("unmarshal error: %v", err)
}
items, err := walk(yamlMap)
return items, err
}
func Yamls2Items(data [][]byte) (ItemArray, error) {
result := ItemArray{}
for i, d := range data {
items, err := yaml2Items(d)
if err != nil {
return nil, fmt.Errorf("unmarshal %d batch error: %v", i, err)
}
result = append(result, items...)
}
return result, nil
}
func Map2Yaml(data map[string]interface{}) ([]byte, error) {
out, err := yaml.Marshal(data)
if err != nil {
return nil, fmt.Errorf("marshal error: %v", err)
}
return out, err
}
func CheckYaml(data []byte) error {
y := map[string]interface{}{}
return yaml.Unmarshal(data, &y)
}
func PreprocessYaml(input *bytes.Buffer) *bytes.Buffer {
buffer := bytes.NewBuffer([]byte{})
ident := ""
for _, str := range strings.Split(input.String(), "\n") {
if strings.HasSuffix(str, "|") {
ident = "|"
} else if ident == "|" {
count := len(str) - len(strings.TrimLeft(str, " "))
// fmt.Println(str, len(str), len(strings.TrimLeft(str, " ")), count)
ident = strings.Repeat(" ", count)
writeStr(buffer, str)
continue
} else if ident != "" && (strings.HasPrefix(str, " ") || str == "") {
ident = ""
} else {
}
if ident != "|" && ident != "" {
buffer.WriteString(ident)
}
writeStr(buffer, str)
}
return buffer
}
func writeStr(buffer *bytes.Buffer, str string) {
if strings.TrimSpace(str) != "" {
buffer.WriteString(str)
buffer.WriteString("\n")
}
}