46 lines
1.1 KiB
Go
46 lines
1.1 KiB
Go
package main
|
|
|
|
import (
|
|
"sort"
|
|
"strconv"
|
|
)
|
|
|
|
type DupGroup struct {
|
|
Size int64
|
|
Hash string
|
|
Files []FileEntry
|
|
}
|
|
|
|
func (g DupGroup) Wasted() int64 { return g.Size * int64(len(g.Files)-1) }
|
|
|
|
func (g DupGroup) key() string { return strconv.FormatInt(g.Size, 10) + ":" + g.Hash }
|
|
|
|
// FindDuplicates groups entries sharing both size and hash, largest wasted space first.
|
|
func FindDuplicates(entries []FileEntry) []DupGroup {
|
|
byKey := map[string]*DupGroup{}
|
|
for _, e := range entries {
|
|
k := strconv.FormatInt(e.FileSize, 10) + ":" + e.FileHash
|
|
g, ok := byKey[k]
|
|
if !ok {
|
|
g = &DupGroup{Size: e.FileSize, Hash: e.FileHash}
|
|
byKey[k] = g
|
|
}
|
|
g.Files = append(g.Files, e)
|
|
}
|
|
groups := []DupGroup{}
|
|
for _, g := range byKey {
|
|
if len(g.Files) < 2 {
|
|
continue
|
|
}
|
|
sort.Slice(g.Files, func(i, j int) bool { return g.Files[i].FilePath < g.Files[j].FilePath })
|
|
groups = append(groups, *g)
|
|
}
|
|
sort.Slice(groups, func(i, j int) bool {
|
|
if wi, wj := groups[i].Wasted(), groups[j].Wasted(); wi != wj {
|
|
return wi > wj
|
|
}
|
|
return groups[i].Files[0].FilePath < groups[j].Files[0].FilePath
|
|
})
|
|
return groups
|
|
}
|