-
Notifications
You must be signed in to change notification settings - Fork 7
/
Copy pathutils.go
63 lines (51 loc) · 1019 Bytes
/
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
package gonertia
import (
crypto "crypto/md5"
"encoding/hex"
"io"
"io/fs"
"os"
)
func setOf[T comparable](data []T) map[T]struct{} {
if len(data) == 0 {
return nil
}
set := make(map[T]struct{}, len(data))
for _, v := range data {
set[v] = struct{}{}
}
return set
}
func firstOr[T any](items []T, fallback T) T {
if len(items) > 0 {
return items[0]
}
return fallback
}
func md5(str string) string {
hash := crypto.Sum([]byte(str))
return hex.EncodeToString(hash[:])
}
func md5FileFromFileFS(file fs.File) (string, error) {
hash := crypto.New()
if _, err := io.Copy(hash, file); err != nil {
return "", err
}
return hex.EncodeToString(hash.Sum(nil)), nil
}
func md5FileFromFS(fs fs.FS, path string) (string, error) {
f, err := fs.Open(path)
if err != nil {
return "", err
}
defer f.Close()
return md5FileFromFileFS(f)
}
func md5File(path string) (string, error) {
f, err := os.Open(path)
if err != nil {
return "", err
}
defer f.Close()
return md5FileFromFileFS(f)
}