/
hashets.go
216 lines (185 loc) · 5.33 KB
/
hashets.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
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
// Command hashets provides the CLI for hashets.
// It can be used to create hashes for files and directories.
package main
import (
"crypto/md5" //nolint:gosec
"crypto/sha256"
"crypto/sha512"
"flag"
"fmt"
"hash"
"os"
"path/filepath"
"sort"
"github.com/bmatcuk/doublestar"
"github.com/mavolin/hashets/hashets"
"github.com/mavolin/hashets/internal/meta"
)
var (
//
// FLAGS
hashingAlgorithm hash.Hash
ignore []string
include []string
replace bool
outPath string
fileNamesVar string
//
// ARGS.
inPath string
//
// ENVS.
packageName string // GOPACKAGE
)
func init() {
hashingAlgoStr := flag.String("hash", "sha256", "hashing algorithm to use (sha256, sha512, md5)")
flag.Func("ignore",
"ignores paths that match the glob\n"+
"supports ** globs",
func(s string) error {
_, err := doublestar.PathMatch(s, "")
if err != nil {
return err
}
ignore = append(ignore, s)
return nil
})
flag.Func("include",
"includes only paths that match the glob\n"+
"if both -include and -ignore are set, a file must be included and not ignored to be hashed\n"+
"supports ** globs",
func(s string) error {
_, err := doublestar.PathMatch(s, "")
if err != nil {
return err
}
include = append(include, s)
return nil
})
flag.BoolVar(&replace, "replace", false, "delete the original original files after hashing")
flag.StringVar(&outPath, "o", "", "output directory (default DIR)")
flag.StringVar(&fileNamesVar, "var", "FileNames", "name of the variable in hashets_map.go")
flag.CommandLine.Usage = usage
flag.Parse()
switch *hashingAlgoStr {
case "sha256":
hashingAlgorithm = sha256.New()
case "sha512":
hashingAlgorithm = sha512.New()
case "md5":
hashingAlgorithm = md5.New() //nolint:gosec
default:
fmt.Fprintln(os.Stderr, "invalid hashing algorithm:", *hashingAlgoStr)
os.Exit(1)
}
if len(flag.Args()) != 1 {
flag.CommandLine.Usage()
os.Exit(1)
}
inPath = filepath.Clean(flag.Arg(0))
if outPath == "" {
outPath = inPath
} else {
outPath = filepath.Clean(outPath)
err := os.Mkdir(outPath, 0o755)
if err != nil && !os.IsExist(err) {
fmt.Fprintln(os.Stderr, "failed to create output directory:", err)
os.Exit(1)
}
}
if filepath.Clean(outPath) == "." {
packageName = os.Getenv("GOPACKAGE")
if packageName == "" {
abs, err := filepath.Abs(outPath)
if err != nil {
fmt.Fprintln(os.Stderr, "failed to get absolute path:", err)
os.Exit(1)
}
packageName = filepath.Base(abs)
}
} else {
packageName = filepath.Base(outPath)
if packageName == "." {
abs, err := filepath.Abs(outPath)
if err != nil {
fmt.Fprintln(os.Stderr, "failed to get absolute path:", err)
os.Exit(1)
}
packageName = filepath.Base(abs)
}
}
}
func usage() {
fmt.Fprintln(flag.CommandLine.Output())
fmt.Fprintln(flag.CommandLine.Output(), meta.Version, "(github.com/mavolin/hashets)")
fmt.Fprintln(flag.CommandLine.Output())
fmt.Fprintln(flag.CommandLine.Output(), "Generate hashes for all files in DIR, and create a clone of DIR's contents")
fmt.Fprintln(flag.CommandLine.Output(), "in -o with the file names including hashes hashes.")
fmt.Fprintln(flag.CommandLine.Output(), "Additionally, places a file named hashets_map.go in -o, that contains")
fmt.Fprintln(flag.CommandLine.Output(), "a single variable `FileNames` of type hashets.Map, which maps the original")
fmt.Fprintln(flag.CommandLine.Output(), "file names to the hashed file names.")
fmt.Fprintln(flag.CommandLine.Output())
fmt.Fprintln(flag.CommandLine.Output(), "Usage:")
fmt.Fprintln(flag.CommandLine.Output(), " hashets [flags] DIR")
flag.PrintDefaults()
}
func main() {
m, err := hashets.HashToDir(os.DirFS(inPath), outPath, hashets.Options{
Hash: hashingAlgorithm,
Ignore: func(p string) bool {
if p == "hashets_map.go" {
return true
}
for _, pattern := range ignore {
// filepath.Clean to convert the slash-based fs path to an
// os-style path
if match, _ := doublestar.PathMatch(pattern, filepath.Clean(p)); match {
return true
}
}
if len(include) == 0 {
return false
}
for _, pattern := range include {
if match, _ := doublestar.PathMatch(pattern, filepath.Clean(p)); match {
return false
}
}
return true
},
})
if err != nil {
fmt.Fprintln(os.Stderr, "failed to hash files:", err)
os.Exit(1)
}
if replace {
for origName := range m {
if err := os.Remove(filepath.Join(outPath, origName)); err != nil {
fmt.Fprintln(os.Stderr, "replace: failed to remove original file:", err)
os.Exit(1)
}
}
}
mapFile, err := os.Create(filepath.Join(outPath, "hashets_map.go"))
if err != nil {
fmt.Fprintln(os.Stderr, "failed to create map file:", err)
os.Exit(1)
}
fmt.Fprintln(mapFile, "package", packageName)
fmt.Fprintln(mapFile)
fmt.Fprintln(mapFile, `import "github.com/mavolin/hashets/hashets"`)
fmt.Fprintln(mapFile)
fmt.Fprintln(mapFile, "// Code generated by hashets. DO NOT EDIT.")
fmt.Fprintln(mapFile)
fmt.Fprintln(mapFile, "var", fileNamesVar, "= hashets.Map{")
// so that two runs of hashets with the same input produce the same output
names := make([]string, 0, len(m))
for name := range m {
names = append(names, name)
}
sort.Strings(names)
for _, name := range names {
fmt.Fprintf(mapFile, "\t%q: %q,\n", name, m[name])
}
fmt.Fprintln(mapFile, "}")
}