forked from augustoroman/crc
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.go
92 lines (79 loc) · 1.94 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
// CRC is a simple command-line utility to compute CRC values for one or more files.
package main
import (
"flag"
"fmt"
"hash"
"hash/crc32"
"hash/crc64"
"io"
"os"
"path/filepath"
)
var exitCode = 0
func main() {
mode := flag.String("mode", "crc64-ecma", "CRC method to use. Valid values are 'crc32' (IEEE), 'crc64-iso', and 'crc64-ecma'")
dir := flag.String("dir", "", "Dir to use.")
flag.Usage = func() {
fmt.Fprintf(os.Stderr, "Usage: %s [-mode=<MODE>] [file [file ...] | -dir=<DIR>]\n", os.Args[0])
flag.PrintDefaults()
}
flag.Parse()
hasher, err := NewHasher(*mode)
if err != nil {
fmt.Fprintln(os.Stderr, err)
os.Exit(1)
}
count := 0
if len(*dir) > 0 {
filepath.Walk(*dir, func(path string, info os.FileInfo, err error) error {
if info.IsDir() {
// fmt.Println(path + "/")
} else {
// fmt.Println(path)
CrcFiles(path, hasher)
count++
}
return nil
})
fmt.Printf("Count = %d\n", count)
} else if flag.NArg() == 0 {
fmt.Fprintf(os.Stderr, "Specify one or more filenames to checksum.\n")
os.Exit(2)
} else {
for _, filename := range flag.Args() {
CrcFiles(filename, hasher)
count++
}
fmt.Printf("Count = %d\n", count)
}
os.Exit(exitCode)
}
func CrcFiles(filename string, hasher hash.Hash) {
f, err := os.Open(filename)
if err != nil {
exitCode = 3
fmt.Fprintf(os.Stderr, "Cannot open %q: %v\n", filename, err)
return
}
_, err = io.Copy(hasher, f)
f.Close()
if err != nil {
exitCode = 3
fmt.Fprintf(os.Stderr, "Error reading %q: %v\n", filename, err)
return
}
fmt.Printf("%0*x\t%s\n", hasher.Size(), hasher.Sum(nil), filename)
}
func NewHasher(mode string) (hash.Hash, error) {
switch mode {
case "crc32", "crc32-ieee":
return crc32.NewIEEE(), nil
case "crc64-iso":
return crc64.New(crc64.MakeTable(crc64.ISO)), nil
case "crc64-ecma":
return crc64.New(crc64.MakeTable(crc64.ECMA)), nil
default:
return nil, fmt.Errorf("ERROR: Invalid mode %q", mode)
}
}