-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathwalk.go
More file actions
91 lines (75 loc) · 1.54 KB
/
walk.go
File metadata and controls
91 lines (75 loc) · 1.54 KB
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
package main
import (
"crypto/sha256"
"encoding/hex"
"fmt"
"io"
"os"
"path/filepath"
"sort"
"golang.org/x/text/unicode/norm"
)
type fileEntry struct {
relPath string
info os.FileInfo
hash string
}
func walkTree(root string, ig *ignorer, label string) ([]fileEntry, error) {
var entries []fileEntry
count := 0
err := filepath.Walk(root, func(path string, info os.FileInfo, err error) error {
if err != nil {
return nil
}
if path == root {
return nil
}
rel, err := filepath.Rel(root, path)
if err != nil {
return nil
}
rel = norm.NFC.String(rel)
isDir := info.IsDir()
if ig.isExcluded(rel, isDir) {
if isDir {
return filepath.SkipDir
}
return nil
}
count++
entry := fileEntry{
relPath: rel,
info: info,
}
if useHashes && !isDir {
fmt.Fprintf(os.Stderr, "\r Scanning %s: %d files (hashing)...", label, count)
entry.hash = hashFile(path)
} else {
fmt.Fprintf(os.Stderr, "\r Scanning %s: %d files...", label, count)
}
entries = append(entries, entry)
return nil
})
if err != nil {
return nil, err
}
if count > 0 {
fmt.Fprintf(os.Stderr, "\r Scanning %s: %d files... done. \n", label, count)
}
sort.Slice(entries, func(i, j int) bool {
return entries[i].relPath < entries[j].relPath
})
return entries, nil
}
func hashFile(path string) string {
f, err := os.Open(path)
if err != nil {
return ""
}
defer f.Close()
h := sha256.New()
if _, err := io.Copy(h, f); err != nil {
return ""
}
return hex.EncodeToString(h.Sum(nil))
}