-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdeduplicate.go
88 lines (74 loc) · 1.9 KB
/
deduplicate.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
package main
import (
"bytes"
"log"
"os"
"path/filepath"
"time"
)
// google takeout can duplicate files - VID_20200626_124037.mp4 and VID_20200626_124037(1).mp4
// same content and same photoTakenTime, but different creationTime
func deduplicate(years []int, yearMap map[int]map[time.Month]map[ItemKey]ItemValue, rootDir string) error {
for _, year := range years {
for month := 1; month < 13; month++ {
itemMap, ok := yearMap[year][time.Month(month)]
if !ok {
continue
}
keys := getKeys(itemMap)
timeMap := make(map[time.Time]ItemKey)
for _, key := range keys {
existingKey, exists := timeMap[key.time]
if !exists {
timeMap[key.time] = key
continue
}
// same time - compare check content
aPath := getFilePath(itemMap[key])
bPath := getFilePath(itemMap[existingKey])
equal, err := filesEqual(aPath, bPath)
if err != nil {
return err
}
if equal {
delete(itemMap, key)
log.Print(getRelativePath(rootDir, aPath) + " duplicates " + getRelativePath(rootDir, bPath))
}
}
}
}
return nil
}
func getRelativePath(rootDir string, file string) string {
result, err := filepath.Rel(rootDir, file)
if err != nil {
return file
}
return result
}
func filesEqual(aPath string, bPath string) (bool, error) {
aStat, err := os.Stat(aPath)
if err != nil {
return false, err
}
bStat, err := os.Stat(bPath)
if err != nil {
return false, err
}
if aStat.Size() != bStat.Size() {
// not a duplicate
return false, nil
}
aHash, err := hashFile(aPath)
if err != nil {
return false, err
}
bHash, err := hashFile(bPath)
if err != nil {
return false, err
}
return bytes.Equal(aHash, bHash), nil
}
func getFilePath(value ItemValue) string {
return filepath.Join(value.dir, value.name)
}