-
Notifications
You must be signed in to change notification settings - Fork 1
/
hash.go
57 lines (50 loc) · 1.06 KB
/
hash.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
package main
import (
_ "bytes"
"errors"
"fmt"
"path/filepath"
"strings"
)
type hash struct {
Algorithm string
Value []byte
}
func hashFromPath(path string) (*hash, error) {
dir := filepath.Dir(path)
parts := strings.Split(dir, "/")
// only want the last 20 parts
if len(parts) < 20 {
return nil, errors.New("not enough parts")
}
hash := strings.Join(parts[len(parts)-20:], "")
if len(hash) != 40 {
return nil, fmt.Errorf("invalid hash length: %d (%s)", len(hash), hash)
}
return hashFromString(hash, "sha1")
}
func hashFromString(str, algorithm string) (*hash, error) {
if algorithm == "" {
algorithm = "sha1"
}
if len(str) != 40 {
return nil, errors.New("invalid hash")
}
return &hash{algorithm, []byte(str)}, nil
}
func (h hash) AsPath() string {
var parts []string
s := h.String()
for i := range s {
if (i % 2) != 0 {
parts = append(parts, s[i-1:i+1])
}
}
return strings.Join(parts, "/")
}
func (h hash) String() string {
return string(h.Value)
}
func (h hash) Valid() bool {
return h.Algorithm == "sha1" && len(h.String()) == 40
}