-
Notifications
You must be signed in to change notification settings - Fork 0
/
md5sums.go
75 lines (64 loc) · 1.34 KB
/
md5sums.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
package main
import (
"crypto/md5"
"fmt"
"gopkg.in/yaml.v2"
"io"
"io/ioutil"
"os"
)
var (
md5sums Md5Sums
)
type Md5Sums map[string]string
func getMd5Sums() Md5Sums {
if md5sums == nil {
if fileExists(cfg.Md5File) {
md5sums.restore()
} else {
md5sums = make(Md5Sums)
}
}
return md5sums
}
func (sums *Md5Sums) restore() {
*sums = make(Md5Sums)
yml, _ := ioutil.ReadFile(cfg.Md5File)
yaml.Unmarshal(yml, sums)
}
func (sums Md5Sums) store() {
yml, _ := yaml.Marshal(sums)
ioutil.WriteFile(cfg.Md5File, yml, 0644)
}
func fileMd5(filePath string) (string, error) {
var result []byte
file, err := os.Open(filePath)
if err != nil {
return fmt.Sprintf("%x", result), err
}
defer file.Close()
hash := md5.New()
if _, err := io.Copy(hash, file); err != nil {
return fmt.Sprintf("%x", result), err
}
return fmt.Sprintf("%x", hash.Sum(result)), nil
}
func saveMd5Sums() {
fmt.Println("calculating checksums")
newMd5Sums := make(Md5Sums)
withEachRegularFile(
func(path string, mtime int64) {
alreadyInMd5Sums := false
if _, ok := md5sums[path]; ok {
alreadyInMd5Sums = true
}
if isMtimeUnchanged(path, mtime) && alreadyInMd5Sums {
newMd5Sums[path] = md5sums[path]
} else {
newMd5Sums[path], _ = fileMd5(path)
}
},
)
yml, _ := yaml.Marshal(newMd5Sums)
ioutil.WriteFile(cfg.Md5File, yml, 0644)
}