-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
196 lines (163 loc) · 4.3 KB
/
main.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
package main
import (
"context"
"crypto"
_ "crypto/md5"
_ "crypto/sha1"
_ "crypto/sha256"
_ "crypto/sha512"
"flag"
"fmt"
"os"
"os/signal"
"path"
"github.com/northbright/filehashes"
)
type option struct {
defaultValue bool
usage string
hashFunc crypto.Hash
}
var (
options = map[string]option{
"md5": option{true, "compute MD5 checksum", crypto.MD5},
"sha1": option{true, "compute SHA1 checksum", crypto.SHA1},
"sha256": option{false, "compute SHA256 checksum", crypto.SHA256},
"sha512": option{false, "compute SHA512 checksum", crypto.SHA512},
}
optionValues = map[string]*bool{}
usage = "Usage:\nhashgo [-md5 | -sha1 | -sha256 | -sha512] [File]...\n"
concurrency = 1
bufferSize = filehashes.DefaultBufferSize
)
// initHashFuncArgs initializes the flags of hash functions.
func initHashFuncArgs() {
for arg, op := range options {
optionValues[arg] = flag.Bool(arg, op.defaultValue, op.usage)
}
}
// getHashFuncs returns the hash functions after the arguments are parsed.
func getHashFuncs() []crypto.Hash {
var hashFuncs []crypto.Hash
for arg, op := range options {
if *(optionValues[arg]) == true {
hashFuncs = append(hashFuncs, op.hashFunc)
}
}
return hashFuncs
}
func computeTotalProgress(progresses map[string]int, m *filehashes.Message) (int, error) {
num := len(progresses)
if num == 0 {
return 0, fmt.Errorf("no file to hash")
}
if m.Type != filehashes.PROGRESS_UPDATED {
return 0, fmt.Errorf("not progress updated message")
}
// Update progress of current file.
file := m.Req.File
progress := m.Data.(int)
progresses[file] = progress
// Compute total progress.
totalProgress := 0
for _, p := range progresses {
totalProgress += p
}
totalProgress = int(float32(totalProgress) / float32(num))
return totalProgress, nil
}
func main() {
// Initialize help arguments.
h := flag.Bool("h", false, "this help")
// Initialize hash arguments.
initHashFuncArgs()
// Parse flags.
flag.Parse()
// Show usage for "-h" or "--help"
if *h {
fmt.Println(usage)
flag.PrintDefaults()
return
}
// Get hash functions in non-flag arguments
files := flag.Args()
hashFuncs := getHashFuncs()
// Check files to be hashed.
if len(files) == 0 {
fmt.Printf("Please specify one or more file(s).\n")
fmt.Println(usage)
flag.PrintDefaults()
return
}
// Check hash functions.
if len(hashFuncs) == 0 {
fmt.Printf("Please specify one or more hash function(s).\n")
fmt.Println(usage)
flag.PrintDefaults()
return
}
// Create context and cancel function.
ctx, cancel := context.WithCancel(context.Background())
// Create a new manager to compute file checksums.
man, ch := filehashes.NewManager(concurrency, bufferSize)
var err error
progresses := map[string]int{}
results := map[string]map[crypto.Hash]string{}
totalProgress := 0
oldTotalProgress := 0
for _, file := range files {
// Initialize progress for each file.
progresses[file] = 0
// Create a new request for each file,
// start a goroutine to compute checksum of the file.
req := filehashes.NewRequest(file, hashFuncs, nil)
man.Start(ctx, req)
}
sigint := make(chan os.Signal, 1)
signal.Notify(sigint, os.Interrupt)
totalExited := 0
for {
select {
case <-sigint:
// os.Interrupt, call cancel func.
fmt.Printf("os.Interrupt received")
cancel()
case <-ctx.Done():
// Exit.
return
case m := <-ch:
switch m.Type {
case filehashes.STARTED:
case filehashes.ERROR:
fmt.Printf("%v: error: %v\n", m.Req.File, m.Data.(string))
cancel()
case filehashes.PROGRESS_UPDATED:
totalProgress, err = computeTotalProgress(progresses, m)
if err != nil {
fmt.Printf("compute total progress error: %v\n", err)
} else {
if totalProgress != oldTotalProgress {
oldTotalProgress = totalProgress
fmt.Printf("total progress: %d%%\r", totalProgress)
}
}
case filehashes.DONE:
checksums := m.Data.(map[crypto.Hash]string)
results[m.Req.File] = checksums
case filehashes.EXITED:
totalExited++
// All goroutine exited
if totalExited >= len(files) {
for file, checksums := range results {
fmt.Printf("\n%v\n", path.Base(file))
for h, checksum := range checksums {
fmt.Printf("%s: %s\n", h.String(), checksum)
}
fmt.Printf("\n")
}
cancel()
}
}
}
}
}