-
Notifications
You must be signed in to change notification settings - Fork 0
/
cmd.go
94 lines (73 loc) · 1.47 KB
/
cmd.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
93
94
package main
import (
"crypto/sha256"
"fmt"
"io"
"io/fs"
"log"
"os"
"path"
"time"
)
func Run(dirs []string) error {
t := time.Now()
defer func() {
fmt.Printf("Elapsed time: %.4fs\n", time.Since(t).Seconds())
}()
for _, d := range dirs {
if err := processDir(d); err != nil {
return fmt.Errorf("Error processing dir %q\n: %v", d, err)
}
}
return nil
}
func processDir(dirname string) error {
log.Printf("Generating file checksums in %q\n", dirname)
files, err := os.ReadDir(dirname)
if err != nil {
return err
}
for _, f := range files {
cs, err := checksumFile(dirname, f)
if err != nil {
log.Printf("Error: %s, skipping %s\\%s", err, dirname, f.Name())
continue
}
// Skip dirs.
if cs == nil {
continue
}
log.Printf("File: %s, size: %d B, checksum: %x\n", cs.FullPath(), cs.Size(), cs.Hash())
}
return nil
}
func checksumFile(dir string, node fs.DirEntry) (*File, error) {
// Skip directories
if node.IsDir() {
return nil, nil
}
file, err := NewFile(node)
if err != nil {
return nil, err
}
file.SetFullPath(path.Join(dir, node.Name()))
hash, err := getFileHash(file)
if err != nil {
return nil, err
}
return hash, err
}
func getFileHash(file *File) (*File, error) {
fp, err := os.Open(file.FullPath())
if err != nil {
return nil, err
}
defer fp.Close()
h := sha256.New()
if _, err := io.Copy(h, fp); err != nil {
return nil, err
}
file.SetHashFunc(h)
file.SetHash(h.Sum(nil))
return file, nil
}