-
Notifications
You must be signed in to change notification settings - Fork 0
/
paths.go
58 lines (45 loc) · 1.31 KB
/
paths.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
package filecache
import (
//nolint:gosec
"crypto/sha1"
"encoding/hex"
"io"
"path/filepath"
"strings"
)
// PathGeneratorFn is a function to generate cache item's file path.
// Receives the key of the cache item and returns the path of the item relative to the cache instance's dir.
type PathGeneratorFn func(key string) string
// WithExt returns new PathGeneratorWithExt instance.
func WithExt(fn PathGeneratorFn, ext string) PathGeneratorFn {
ext = filterPathIdent(ext)
if !strings.HasPrefix(ext, ".") {
ext = "." + ext
}
return func(key string) string {
return fn(key) + ext
}
}
// FilteredKeyPath uses a key without path separators as a path.
func FilteredKeyPath(key string) string {
path := filterPathIdent(key)
if path == "" {
return HashedKeyPath(key)
}
return path
}
// HashedKeyPath return hashed key and uses it as a file name.
func HashedKeyPath(key string) string {
//nolint:gosec
h := sha1.New()
_, _ = io.WriteString(h, key)
return hex.EncodeToString(h.Sum(nil))
}
// HashedKeySplitPath return hashes key, splits it on the parts which are directories and a file name.
func HashedKeySplitPath(key string) string {
//nolint:gosec
h := sha1.New()
_, _ = io.WriteString(h, key)
hashed := hex.EncodeToString(h.Sum(nil))
return filepath.Join(hashed[:2], hashed[2:4], hashed[4:6], hashed[6:])
}