This repository has been archived by the owner on Apr 29, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 9
/
yaml.go
135 lines (109 loc) · 2.28 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
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
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
package yaml
import (
"io/ioutil"
"os"
"strings"
"github.com/pkg/errors"
"gopkg.in/yaml.v3"
)
type yamlFile struct {
path string
}
func New(path string) *yamlFile {
return &yamlFile{
path: path,
}
}
func readFile(path string) ([]byte, error) {
data, err := ioutil.ReadFile(path)
if err != nil {
return nil, errors.Wrapf(err, "Error while reading yaml %s", path)
}
return data, nil
}
func (y *yamlFile) DeleteFile() error {
return os.Remove(y.path)
}
func (y *yamlFile) ToString() (string, error) {
data, err := readFile(y.path)
if err != nil {
return "", err
}
return string(data), nil
}
func (y *yamlFile) ToStruct(struc interface{}) error {
parts, err := y.ToObjectList()
if err != nil {
return err
}
for _, part := range parts {
if part == "" {
continue
}
err = yaml.Unmarshal([]byte(part), struc)
if err != nil {
return errors.Wrapf(err, "Error while unmarshaling yaml %s to struct", y.path)
}
return nil
}
return nil
}
func (y *yamlFile) ToObjectList() ([]string, error) {
data, err := readFile(y.path)
if err != nil {
return nil, err
}
return strings.Split(string(data), "\n---\n"), nil
}
func (y *yamlFile) AddStruct(struc interface{}) error {
data, err := yaml.Marshal(struc)
if err != nil {
return err
}
if err := writeFileYAMLDivider(y.path); err != nil {
return err
}
return writeFile(y.path, data)
}
func (y *yamlFile) AddString(str string) error {
return writeFile(y.path, []byte(str))
}
func (y *yamlFile) AddStringObject(str string) error {
if err := writeFileYAMLDivider(y.path); err != nil {
return err
}
return writeFile(y.path, []byte(str))
}
func writeFileYAMLDivider(path string) error {
if fileExists(path) {
f, err := os.OpenFile(path,
os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0644)
if err != nil {
return err
}
defer f.Close()
if _, err := f.WriteString("\n---\n"); err != nil {
return err
}
}
return nil
}
func writeFile(path string, data []byte) error {
f, err := os.OpenFile(path,
os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0644)
if err != nil {
return err
}
defer f.Close()
if _, err := f.Write(data); err != nil {
return err
}
return nil
}
func fileExists(filename string) bool {
info, err := os.Stat(filename)
if os.IsNotExist(err) {
return false
}
return !info.IsDir()
}