-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
133 lines (115 loc) · 2.19 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
package main
import (
"crypto/md5"
"crypto/sha1"
"crypto/sha256"
"crypto/sha512"
"encoding/hex"
"flag"
"fmt"
"hash"
"io"
"log"
"os"
"path/filepath"
"strings"
"sync"
"github.com/zeebo/blake3"
"golang.org/x/crypto/blake2b"
)
const version = "0.1.1"
type mode string
const (
SHA256 mode = "sha256"
SHA512 mode = "sha512"
BLAKE2B mode = "blake2b"
BLAKE3 mode = "blake3" // ⚡
SHA1 mode = "sha1"
MD5 mode = "md5"
)
// Thread safe output
var (
output = log.New(os.Stdout, "", 0)
errout = log.New(os.Stderr, "", 0)
)
func main() {
m := flag.String("m", string(SHA256), mUsage())
flag.BoolFunc("v", vUsage(), func(s string) error {
fmt.Println(version)
os.Exit(0)
return nil
})
flag.Usage = usage
flag.Parse()
args := flag.Args()
if len(args) < 1 {
usage()
os.Exit(1)
}
var wg sync.WaitGroup
wg.Add(len(args))
for _, path := range args {
go func() {
defer wg.Done()
sum, err := calcHash(path, mode(*m))
if err != nil {
errout.Println(err)
return
}
sumHex := hex.EncodeToString(sum)
output.Println(sumHex, filepath.Base(path))
}()
}
wg.Wait()
}
func calcHash(path string, mode mode) ([]byte, error) {
file, err := os.Open(path)
if err != nil {
return nil, err
}
defer file.Close()
var hash hash.Hash
switch mode {
case SHA512:
hash = sha512.New()
case SHA256:
hash = sha256.New()
case SHA1:
hash = sha1.New()
case MD5:
hash = md5.New()
case BLAKE3:
hash = blake3.New()
case BLAKE2B:
hash, err = blake2b.New(32, nil)
if err != nil {
return nil, err
}
default:
return nil, fmt.Errorf("unknown mode: '%s'", mode)
}
if _, err := io.Copy(hash, file); err != nil {
return nil, err
}
return hash.Sum(nil), nil
}
func mUsage() string {
var result strings.Builder
result.WriteString("specify hash function:")
for _, s := range []string{"sha256 (default)", "sha512", "blake2b", "blake3", "sha1 (not recommended)", "md5 (not recommended)"} {
result.WriteString("\n\t")
result.WriteString(s)
}
return result.String()
}
func vUsage() string {
return "print current version and exit"
}
func usage() {
errout.Printf(`
Arguments: [PATH]... Files to hash
Options:
-m %s
-v %s
`, mUsage(), vUsage())
}