-
Notifications
You must be signed in to change notification settings - Fork 29
/
Copy pathutils.go
123 lines (95 loc) · 2.32 KB
/
utils.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
package utils
import (
"crypto/sha256"
"encoding/json"
"fmt"
"io/ioutil"
"strings"
"gopkg.in/yaml.v2"
)
func Dump(v interface{}) {
j, _ := json.Marshal(v)
fmt.Println(string(j))
}
func Hash(v interface{}) [32]byte {
j, _ := json.Marshal(v)
return sha256.Sum256(j)
}
func LsDirs(path string) ([]string, error) {
files, err := ioutil.ReadDir(path)
if err != nil {
return nil, err
}
var dirs []string
for _, f := range files {
if strings.HasPrefix(f.Name(), ".") {
continue
}
if !f.IsDir() {
return nil, fmt.Errorf("directory should contain only directories, found: %s", f.Name())
}
dirs = append(dirs, f.Name())
}
return dirs, nil
}
func LsFiles(path string) ([]string, error) {
files, err := ioutil.ReadDir(path)
if err != nil {
return nil, err
}
var actualFiles []string
for _, f := range files {
if strings.HasPrefix(f.Name(), ".") {
continue
}
if f.IsDir() {
return nil, fmt.Errorf("directory should contain only files, found: %s", f.Name())
}
actualFiles = append(actualFiles, f.Name())
}
return actualFiles, nil
}
func WriteFileAsJson(v interface{}, out string) error {
file, err := json.Marshal(v)
if err != nil {
return fmt.Errorf("error when marshaling json: %w", err)
}
err = ioutil.WriteFile(out, file, 0644)
if err != nil {
return fmt.Errorf("error when generating json: %w", err)
}
return nil
}
func WriteFileAsYaml(v interface{}, out string) error {
file, err := yaml.Marshal(v)
if err != nil {
return fmt.Errorf("error when marshaling json: %w", err)
}
err = ioutil.WriteFile(out, file, 0644)
if err != nil {
return fmt.Errorf("error when generating json: %w", err)
}
return nil
}
func LoadJsonFileIntoStruct(path string, v interface{}) error {
file, err := ioutil.ReadFile(path)
if err != nil {
return fmt.Errorf("failed to read file at path '%s': %w", path, err)
}
err = json.Unmarshal(file, v)
if err != nil {
return fmt.Errorf("failed to unmarshal attrs file at path '%s': %w", path, err)
}
return nil
}
func LoadYamlFileIntoStruct(path string, v interface{}) error {
file, err := ioutil.ReadFile(path)
if err != nil {
return fmt.Errorf("failed to read file at path '%s': %w", path, err)
}
err = yaml.Unmarshal(file, v)
if err != nil {
return fmt.Errorf("failed to unmarshal attrs file at path '%s': %w", path, err)
}
return nil
}