-
Notifications
You must be signed in to change notification settings - Fork 162
/
sha1_calculator.go
92 lines (76 loc) · 1.99 KB
/
sha1_calculator.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
package crypto
import (
"crypto/sha1"
"fmt"
"hash"
"io"
"os"
bosherr "github.com/cloudfoundry/bosh-utils/errors"
boshsys "github.com/cloudfoundry/bosh-utils/system"
)
type SHA1Calculator interface {
Calculate(string) (string, error)
CalculateString(string) string
}
type sha1Calculator struct {
fs boshsys.FileSystem
}
func NewSha1Calculator(fs boshsys.FileSystem) SHA1Calculator {
return sha1Calculator{fs: fs}
}
func (c sha1Calculator) Calculate(filePath string) (string, error) {
file, err := c.fs.OpenFile(filePath, os.O_RDONLY, 0)
if err != nil {
return "", bosherr.WrapErrorf(err, "Calculating sha1 of '%s'", filePath)
}
defer func() {
_ = file.Close()
}()
fileInfo, err := file.Stat()
if err != nil {
return "", bosherr.WrapErrorf(err, "Opening file '%s' for sha1 calculation", filePath)
}
h := sha1.New()
if fileInfo.IsDir() {
err = c.fs.Walk(filePath+"/", func(path string, info os.FileInfo, err error) error {
if !info.IsDir() {
err := c.populateSha1(path, h)
if err != nil {
return bosherr.WrapErrorf(err, "Calculating directory SHA1 for %s", path)
}
}
return nil
})
if err != nil {
return "", err
}
} else {
err = c.populateSha1(filePath, h)
if err != nil {
return "", bosherr.WrapErrorf(err, "Calculating file SHA1 for %s", filePath)
}
}
return fmt.Sprintf("%x", h.Sum(nil)), nil
}
func (c sha1Calculator) CalculateString(data string) string {
h := sha1.New()
_, err := h.Write([]byte(data))
if err != nil {
panic("According to the docs sha1.Write will never return an error")
}
return fmt.Sprintf("%x", h.Sum(nil))
}
func (c sha1Calculator) populateSha1(filePath string, hash hash.Hash) error {
file, err := c.fs.OpenFile(filePath, os.O_RDONLY, 0)
if err != nil {
return bosherr.WrapErrorf(err, "Opening file '%s' for sha1 calculation", filePath)
}
defer func() {
_ = file.Close()
}()
_, err = io.Copy(hash, file)
if err != nil {
return bosherr.WrapError(err, "Copying file for sha1 calculation")
}
return nil
}