-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathutils.go
303 lines (266 loc) · 7.06 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
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
package ortfodb
import (
"crypto/md5"
"encoding/base64"
"fmt"
"io"
"net/http"
"net/url"
"os"
"os/signal"
"path"
"path/filepath"
"regexp"
"strings"
ll "github.com/ewen-lbh/label-logger-go"
"github.com/invopop/jsonschema"
"github.com/xeipuuv/gojsonschema"
"gopkg.in/yaml.v3"
)
var debugging = os.Getenv("DEBUG") == "1" || os.Getenv("ORTFO_DEBUG") == "1" || os.Getenv("ORTFODB_DEBUG") == "1"
// readFileBytes reads the content of filename and returns the contents as a byte array.
func readFileBytes(filename string) ([]byte, error) {
b, err := os.ReadFile(filename)
if err != nil {
return []byte{}, err
}
return b, nil
}
// readFile reads the content of filename and returns the contents as a string.
func readFile(filename string) (string, error) {
content, err := readFileBytes(filename)
if err != nil {
return "", err
}
return string(content), nil
}
// writeFile writes content to file filepath.
func writeFile(filename string, content []byte) error {
absfilepath, err := filepath.Abs(filename)
if err != nil {
return err
}
f, err := os.Create(absfilepath)
if err != nil {
return err
}
defer f.Close()
_, err = f.Write(content)
if err != nil {
return err
}
return nil
}
// validateWithJSONSchema checks if the JSON document document conforms to the JSON schema schema.
func validateWithJSONSchema(document string, schema *jsonschema.Schema) (bool, []gojsonschema.ResultError, error) {
schemaJson, err := schema.MarshalJSON()
if err != nil {
panic(err)
}
schemaLoader := gojsonschema.NewStringLoader(string(schemaJson))
documentLoader := gojsonschema.NewStringLoader(document)
result, err := gojsonschema.Validate(schemaLoader, documentLoader)
if err != nil {
return false, nil, err
}
if result.Valid() {
return true, nil, nil
}
return false, result.Errors(), nil
}
// fileExists checks if the given file exists, and returns true if it exists or false otherwise.
func fileExists(filename string) bool {
if _, err := os.Stat(filename); os.IsNotExist(err) {
return false
}
return true
}
// regexpMatches checks if s matches the regex regex at least once.
func regexpMatches(regex string, s string) bool {
p := regexp.MustCompile(regex)
return p.MatchString(s)
}
// regexpGroups returns all the capture groups' contents from the first match of regex regex in s. The first element [0] is the entire match. [1] is the first capture group's content, et cætera.
func regexpGroups(regex string, s string) []string {
p := regexp.MustCompile(regex)
return p.FindStringSubmatch(s)
}
// isValidURL tests a string to determine if it is a well-structured url or not.
func isValidURL(URL string) bool {
_, err := url.ParseRequestURI(URL)
if err != nil {
return false
}
u, err := url.Parse(URL)
if err != nil || u.Scheme == "" || u.Host == "" {
return false
}
return true
}
// stringInSlice checks if needle is in haystack.
func stringInSlice(haystack []string, needle string) bool {
for _, v := range haystack {
if v == needle {
return true
}
}
return false
}
// filterSlice returns a slice of strings containing only the elements that return true when called with cond.
func filterSlice(s []string, cond func(string) bool) []string {
filtered := make([]string, 0)
for _, item := range s {
if cond(item) {
filtered = append(filtered, item)
}
}
return filtered
}
// mapKeys returns a slice of strings containing the map's keys.
func mapKeys[T any](m map[string]T) []string {
keys := make([]string, 0)
for k := range m {
keys = append(keys, k)
}
return keys
}
func mapValues[T any](m map[string]T) []T {
values := make([]T, 0)
for _, v := range m {
values = append(values, v)
}
return values
}
// filepathBaseNoExt returns the basename of pth with the extension removed.
func filepathBaseNoExt(pth string) string {
return strings.TrimSuffix(filepath.Base(pth), path.Ext(pth))
}
// merge merges the given maps. Conflicting keys are overwritten by the values of the latest map with that key.
func merge[K comparable, V any](maps ...map[K]V) map[K]V {
result := make(map[K]V)
for _, m := range maps {
for k, v := range m {
result[k] = v
}
}
return result
}
// some returns true if predicate evaluates to true on any of the haystack elements
func some[T any](haystack []T, predicate func(T) bool) bool {
for _, v := range haystack {
if predicate(v) {
return true
}
}
return false
}
// all returns true if predicate evaluates to true on all of the haystack elements
func all[T any](haystack []T, predicate func(T) bool) bool {
for _, v := range haystack {
if !predicate(v) {
return false
}
}
return true
}
// noDuplicates removes duplicate elements from the given slice, keeping only the first occurences.
func noDuplicates[T comparable](s []T) []T {
seen := make(map[T]bool)
result := make([]T, 0)
for _, v := range s {
if !seen[v] {
seen[v] = true
result = append(result, v)
}
}
return result
}
func handleControlC(action func()) {
c := make(chan os.Signal, 1)
signal.Notify(c, os.Interrupt)
go func() {
for range c {
action()
}
}()
}
func stringsLooselyMatch(s string, needles ...string) bool {
for _, needle := range needles {
if strings.EqualFold(s, needle) {
return true
}
}
return false
}
func downloadFile(url string) ([]byte, error) {
resp, err := http.Get(url)
if err != nil {
return []byte{}, err
}
defer resp.Body.Close()
contents, err := io.ReadAll(resp.Body)
if err != nil {
return []byte{}, err
}
return contents, nil
}
func ensureHttpPrefix(url string) string {
if !isValidURL(url) {
if strings.HasPrefix(url, "localhost") || strings.HasPrefix(url, "127.0.0.") {
return "http://" + url
} else {
return "https://" + url
}
}
return url
}
func writeYAML(v any, filename string) error {
encoded, err := yaml.Marshal(v)
if err != nil {
return fmt.Errorf("while encoding to YAML: %w", err)
}
err = os.WriteFile(filename, encoded, 0o644)
if err != nil {
return fmt.Errorf("while writing encoded yaml contents to %q: %w", filename, err)
}
return nil
}
func chunkSlice[T any](s []T, chunkSize int) [][]T {
chunks := make([][]T, 0)
for i := 0; i < len(s); i += chunkSize {
end := i + chunkSize
if end > len(s) {
end = len(s)
}
chunks = append(chunks, s[i:end])
}
return chunks
}
// copyFile copies src to dest using io.Copy
func copyFile(src, dest string) error {
srcFile, err := os.Open(src)
if err != nil {
return fmt.Errorf("while opening source file %q: %w", src, err)
}
defer srcFile.Close()
destFile, err := os.Create(dest)
if err != nil {
return fmt.Errorf("while creating destination file %q: %w", dest, err)
}
defer destFile.Close()
_, err = io.Copy(destFile, srcFile)
if err != nil {
return fmt.Errorf("while copying contents from %q to %q: %w", src, dest, err)
}
return nil
}
func hashFile(filename string) (string, error) {
ll.Debug("reading %s for hash computation", filename)
content, err := os.ReadFile(filename)
if err != nil {
return "", fmt.Errorf("while reading file %s for hashing: %w", filename, err)
}
ll.Debug("computing hash of %s", filename)
hash := md5.Sum(content)
return base64.StdEncoding.EncodeToString(hash[:]), nil
}