-
Notifications
You must be signed in to change notification settings - Fork 0
/
dummycreator.go
116 lines (94 loc) · 1.94 KB
/
dummycreator.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
package main
import (
"bufio"
"crypto/md5"
"crypto/sha1"
"crypto/sha256"
"encoding/hex"
"encoding/json"
"fmt"
"hash"
"io"
"io/ioutil"
"os"
"path/filepath"
"strings"
)
type FileInfo struct {
Size int64
ModTime string
Sha1 string
Sha256 string
Md5 string
}
func main() {
// You can get individual args with normal indexing.
path := os.Args[1]
dummyPath := path
fi, err := os.Stat(path)
if err != nil {
return
}
if len(os.Args) >= 3 {
trim := os.Args[2]
if trim != "" {
_, err := os.Stat(trim)
dummyPath = strings.ReplaceAll(dummyPath, filepath.Dir(trim), "")
if err != nil {
return
}
}
}
h, err := HashFile(path)
if err != nil {
return
}
h.Size = fi.Size()
h.ModTime = fi.ModTime().String()
fileJson, _ := json.Marshal([]FileInfo{h})
os.MkdirAll(filepath.Join("dummy/", filepath.Dir(dummyPath)), os.FileMode(0755))
err = ioutil.WriteFile(filepath.Join("dummy/", dummyPath), fileJson, 0644)
fmt.Println(filepath.Base(dummyPath) + " dummy created")
}
// HashFile generates a human readable hash of the given file path
func HashFile(path string) (hashes FileInfo, err error) {
f, err := os.Open(path)
if err != nil {
return
}
defer f.Close()
reader := bufio.NewReader(f)
var writers []io.Writer
hsha1 := newHasher(sha1.New(), &hashes.Sha1)
defer hsha1.Close()
writers = append(writers, hsha1)
hsha256 := newHasher(sha256.New(), &hashes.Sha256)
defer hsha256.Close()
writers = append(writers, hsha256)
hmd5 := newHasher(md5.New(), &hashes.Md5)
defer hmd5.Close()
writers = append(writers, hmd5)
if len(writers) == 0 {
return
}
w := io.MultiWriter(writers...)
_, err = io.Copy(w, reader)
if err != nil {
return
}
return
}
type hasher struct {
hash.Hash
output *string
}
func newHasher(hash hash.Hash, output *string) hasher {
return hasher{
Hash: hash,
output: output,
}
}
func (h hasher) Close() error {
*h.output = hex.EncodeToString(h.Sum(nil))
return nil
}