This repository has been archived by the owner on May 16, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathmain.go
211 lines (185 loc) · 5.04 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
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
package main
import (
"bufio"
"encoding/json"
"flag"
"fmt"
"io"
"io/ioutil"
"os"
"runtime"
"strings"
"sync"
"github.com/teran/imgsum/image"
)
// JSONOutput model
type JSONOutput struct {
Duplicates [][]string `json:"duplicates"`
Count int `json:"count"`
}
// JSONInput model
type JSONInput struct {
Files []string `json:"files"`
}
var (
wg sync.WaitGroup
version = "No version specified(probably trunk build)"
commit = "master"
date = "0000-00-00T00:00:00Z"
)
func calculate(file string, hashKind image.HashType, res int) error {
i, err := image.NewImage(file)
if err != nil {
fmt.Fprintln(os.Stderr, file, err.Error())
wg.Done()
return err
}
h, err := i.Hexdigest(hashKind, res)
if err != nil {
fmt.Fprintln(os.Stderr, file, err.Error())
wg.Done()
return err
}
fmt.Printf("%v %v\n", h, i.Filename())
wg.Done()
return nil
}
func deduplicate(filename string, jsonOutput bool) error {
fp, err := os.Open(filename)
if err != nil {
fmt.Fprintln(os.Stderr, filename, err.Error())
return err
}
defer fp.Close()
files := make(map[string][]string)
var counter []string
r := bufio.NewReader(fp)
line, err := r.ReadString(10)
for err != io.EOF {
fields := strings.SplitN(line, " ", 2)
if len(fields) == 2 {
hash := strings.TrimSpace(fields[0])
file := strings.TrimSpace(fields[1])
files[hash] = append(files[hash], file)
if len(files[hash]) == 2 {
counter = append(counter, hash)
}
}
line, err = r.ReadString(10)
}
if jsonOutput {
out := JSONOutput{}
for key := range counter {
out.Duplicates = append(out.Duplicates, files[counter[key]])
}
out.Count = len(counter)
jsonString, err := json.Marshal(out)
if err != nil {
return err
}
fmt.Println(string(jsonString))
} else {
for key := range counter {
fmt.Printf("%v:\n", counter[key])
for file := range files[counter[key]] {
fmt.Println(files[counter[key]][file])
}
fmt.Println("")
}
}
return nil
}
func main() {
flag.Usage = func() {
fmt.Printf("Usage: %s [OPTION]... [FILE]...\n", os.Args[0])
fmt.Printf("Print or check image Average hashes\n")
fmt.Printf(" -concurrency %v\n", runtime.NumCPU())
fmt.Printf(" Amount of routines to spawn at the same time(%v by default for your system)\n", runtime.NumCPU())
fmt.Printf(" -find-duplicates\n")
fmt.Printf(" read average hashes from the FILEs and find duplicates\n")
fmt.Printf(" -json-input\n")
fmt.Printf(" Read file list from stdin as a JSON({'files':['file1', 'file2']}) and calculate their hash\n")
fmt.Printf(" -json-output\n")
fmt.Printf(" Return duplicates as a JSON(useful for IPC)\n")
fmt.Printf(" -hash-kind avg|diff")
fmt.Printf(" Allows to set hash function: average or difference (avg by default)")
fmt.Printf(" -hash-resolution 1024")
fmt.Printf(" Allows to set the (squared) image resolution to pass to hashing function (1024 by default)")
fmt.Printf(" -version\n")
fmt.Printf(" Print imgsum version\n")
fmt.Printf(" -credits\n")
fmt.Printf(" Print credits\n\n")
fmt.Printf("Examples:\n")
fmt.Printf(" %s file.jpg\n", os.Args[0])
fmt.Printf(" %s file.jpg | tee /tmp/database.txt\n", os.Args[0])
fmt.Printf(" %s -check /tmp/database.txt\n", os.Args[0])
fmt.Printf(" %s -find-duplicates /tmp/database.txt\n", os.Args[0])
fmt.Printf(" cat input.json | %s -json-input\n", os.Args[0])
}
// cmdline parameters
var (
concurrency int
deduplicateModeFlag bool
jsonInputFlag bool
jsonOutputFlag bool
versionFlag bool
hashKind string
hashResolution int
creditsFlag bool
)
flag.IntVar(&concurrency, "concurrency", runtime.NumCPU(), "")
flag.BoolVar(&deduplicateModeFlag, "find-duplicates", false, "")
flag.BoolVar(&jsonInputFlag, "json-input", false, "")
flag.BoolVar(&jsonOutputFlag, "json-output", false, "")
flag.BoolVar(&versionFlag, "version", false, "")
flag.StringVar(&hashKind, "hash-kind", "avg", "")
flag.IntVar(&hashResolution, "hash-resolution", 1024, "")
flag.BoolVar(&creditsFlag, "credits", false, "")
flag.Parse()
if creditsFlag == true {
printCredits()
os.Exit(1)
}
if flag.NArg() < 1 && !jsonInputFlag && !versionFlag {
flag.Usage()
os.Exit(1)
}
if deduplicateModeFlag {
for file := range flag.Args() {
deduplicate(flag.Arg(file), jsonOutputFlag)
}
} else if versionFlag == true {
fmt.Printf("Version: %s\nBuild date: %s\nBuild commit: %s\n", version, date, commit)
} else {
var files []string
if jsonInputFlag {
var jsonInput JSONInput
data, err := ioutil.ReadAll(os.Stdin)
if err != nil {
panic(err)
}
if err := json.Unmarshal(data, &jsonInput); err != nil {
panic(err)
}
files = jsonInput.Files
} else {
files = flag.Args()
}
sem := make(chan bool, concurrency)
for file := range files {
sem <- true
filename := files[file]
wg.Add(1)
go func() {
calculate(filename, image.HashType(hashKind), hashResolution)
defer func() {
<-sem
}()
}()
}
for i := 0; i < cap(sem); i++ {
sem <- true
}
wg.Wait()
}
}