├── .dockerignore ├── .gitignore ├── default_exclusions.txt ├── Dockerfile ├── go.mod ├── .github └── workflows │ └── build-and-test.yml ├── entity ├── file_ext_and_size.go ├── file_meta.go ├── file_digest.go ├── output_mode.go └── digest_to_files.go ├── bytesutil ├── human_readable_size_test.go └── human_readable_size.go ├── fmte └── fmt_english.go ├── service ├── file_hash_test.go ├── dir_scanner.go ├── find_duplicates_test.go ├── file_hash.go └── find_duplicates.go ├── utils └── utils.go ├── go.sum ├── report.go ├── README.md ├── main.go └── LICENSE /.dockerignore: -------------------------------------------------------------------------------- 1 | /.idea/ 2 | /.git/ 3 | go-find-duplicates 4 | *.txt 5 | !default_exclusions.txt 6 | *.csv -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | /.idea/ 2 | go-find-duplicates 3 | *.txt 4 | !default_exclusions.txt 5 | *.csv 6 | *.json 7 | *.sh 8 | .DS_Store -------------------------------------------------------------------------------- /default_exclusions.txt: -------------------------------------------------------------------------------- 1 | .DS_Store 2 | System Volume Information 3 | $RECYCLE.BIN 4 | desktop.ini 5 | Thumbs.db 6 | .picasaoriginals 7 | .picasa.ini 8 | .Trash 9 | .Trashes 10 | .TemporaryItems 11 | .Spotlight-V100 12 | .fseventsd 13 | _PAlbTN 14 | -------------------------------------------------------------------------------- /Dockerfile: -------------------------------------------------------------------------------- 1 | FROM golang:1.22-alpine3.19 AS builder 2 | 3 | RUN apk --no-cache add build-base 4 | 5 | WORKDIR /opt/go-find-duplicates 6 | 7 | COPY ./go.mod ./go.sum ./ 8 | 9 | RUN go mod download -x 10 | 11 | COPY . . 12 | 13 | RUN go build 14 | 15 | RUN go test ./... 16 | 17 | FROM alpine:3.19 18 | 19 | RUN apk --no-cache add bash 20 | 21 | COPY --from=builder /opt/go-find-duplicates/go-find-duplicates /bin 22 | -------------------------------------------------------------------------------- /go.mod: -------------------------------------------------------------------------------- 1 | module github.com/m-manu/go-find-duplicates 2 | 3 | go 1.22 4 | 5 | require ( 6 | github.com/deckarep/golang-set/v2 v2.7.0 7 | github.com/emirpasic/gods v1.18.1 8 | github.com/spf13/pflag v1.0.6 9 | github.com/stretchr/testify v1.10.0 10 | golang.org/x/text v0.22.0 11 | ) 12 | 13 | require ( 14 | github.com/davecgh/go-spew v1.1.1 // indirect 15 | github.com/pmezard/go-difflib v1.0.0 // indirect 16 | gopkg.in/yaml.v3 v3.0.1 // indirect 17 | ) 18 | -------------------------------------------------------------------------------- /.github/workflows/build-and-test.yml: -------------------------------------------------------------------------------- 1 | name: build-and-test 2 | on: 3 | push: 4 | branches: 5 | - main 6 | jobs: 7 | build: 8 | runs-on: ubuntu-22.04 9 | steps: 10 | - name: Checkout code 11 | uses: actions/checkout@v3 12 | - name: Setup Golang 13 | uses: actions/setup-go@v3 14 | with: 15 | go-version: 1.22 16 | - name: Build code 17 | run: go build 18 | - name: Test code 19 | run: go test -v ./... 20 | -------------------------------------------------------------------------------- /entity/file_ext_and_size.go: -------------------------------------------------------------------------------- 1 | package entity 2 | 3 | import "fmt" 4 | 5 | // FileExtAndSize is a struct of file extension and file size 6 | type FileExtAndSize struct { 7 | FileExtension string 8 | FileSize int64 9 | } 10 | 11 | // String returns a string representation of FileExtAndSize 12 | func (f FileExtAndSize) String() string { 13 | return fmt.Sprintf("%v/%v", f.FileExtension, f.FileSize) 14 | } 15 | 16 | // FileExtAndSizeToFiles is a multi-map of FileExtAndSize key and string values 17 | type FileExtAndSizeToFiles map[FileExtAndSize][]string 18 | -------------------------------------------------------------------------------- /entity/file_meta.go: -------------------------------------------------------------------------------- 1 | package entity 2 | 3 | import ( 4 | "fmt" 5 | "time" 6 | ) 7 | 8 | // FileMeta is a combination of file size and its modification timestamp 9 | type FileMeta struct { 10 | Size int64 11 | ModifiedTimestamp int64 12 | } 13 | 14 | // String returns a string representation of FileMeta 15 | func (f FileMeta) String() string { 16 | return fmt.Sprintf("{size: %d, modified: %v}", f.Size, time.Unix(f.ModifiedTimestamp, 0)) 17 | } 18 | 19 | // FilePathToMeta is a map of file path to its FileMeta 20 | type FilePathToMeta map[string]FileMeta 21 | -------------------------------------------------------------------------------- /entity/file_digest.go: -------------------------------------------------------------------------------- 1 | package entity 2 | 3 | import ( 4 | "fmt" 5 | "github.com/m-manu/go-find-duplicates/bytesutil" 6 | ) 7 | 8 | // FileDigest contains properties of a file that makes the file unique to a very high degree of confidence 9 | type FileDigest struct { 10 | FileExtension string `json:"ext"` 11 | FileSize int64 `json:"size"` 12 | FileHash string `json:"hash"` 13 | } 14 | 15 | // String returns a string representation of FileDigest 16 | func (f FileDigest) String() string { 17 | return fmt.Sprintf("%v/%v/%v", f.FileExtension, f.FileHash, bytesutil.BinaryFormat(f.FileSize)) 18 | } 19 | -------------------------------------------------------------------------------- /entity/output_mode.go: -------------------------------------------------------------------------------- 1 | package entity 2 | 3 | // Different output modes 4 | const ( 5 | OutputModeTextFile = "text" 6 | OutputModeCsvFile = "csv" 7 | OutputModeStdOut = "print" 8 | OutputModeJSON = "json" 9 | ) 10 | 11 | // OutputModes and their brief descriptions 12 | var OutputModes = map[string]string{ 13 | OutputModeStdOut: "just prints the report without creating any file", 14 | OutputModeTextFile: "creates a text file in the output directory with basic information", 15 | OutputModeCsvFile: "creates a csv file in the output directory with detailed information", 16 | OutputModeJSON: "creates a JSON file in the output directory with basic information", 17 | } 18 | -------------------------------------------------------------------------------- /bytesutil/human_readable_size_test.go: -------------------------------------------------------------------------------- 1 | package bytesutil 2 | 3 | import ( 4 | "github.com/stretchr/testify/assert" 5 | "testing" 6 | ) 7 | 8 | func TestFormats(t *testing.T) { 9 | tests := map[int64][2]string{ 10 | -1: {"", ""}, 11 | 0: {"0 B", "0 B"}, 12 | 1_023: {"1023 B", "1.02 KB"}, 13 | 2_140: {"2.09 KiB", "2.14 KB"}, 14 | 2_828_382: {"2.70 MiB", "2.83 MB"}, 15 | 2_341_234_123_412_341_234: {"2.03 EiB", "2.34 EB"}, 16 | } 17 | for value, expectedValues := range tests { 18 | assert.Equal(t, expectedValues[0], BinaryFormat(value)) 19 | assert.Equal(t, expectedValues[1], DecimalFormat(value)) 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /fmte/fmt_english.go: -------------------------------------------------------------------------------- 1 | package fmte 2 | 3 | import ( 4 | "golang.org/x/text/language" 5 | "golang.org/x/text/message" 6 | "os" 7 | "sync" 8 | ) 9 | 10 | var p *message.Printer 11 | 12 | var mx sync.Mutex 13 | 14 | func init() { 15 | p = message.NewPrinter(language.English) 16 | } 17 | 18 | var normalPrint = true 19 | 20 | func Off() { 21 | normalPrint = false 22 | } 23 | 24 | // Printf is goroutine-safe fmt.Printf for English 25 | func Printf(format string, a ...any) { 26 | if !normalPrint { 27 | return 28 | } 29 | mx.Lock() 30 | _, _ = p.Printf(format, a...) 31 | mx.Unlock() 32 | } 33 | 34 | // PrintfErr is goroutine-safe fmt.Printf to StdErr for English 35 | func PrintfErr(format string, a ...any) { 36 | if !normalPrint { 37 | return 38 | } 39 | mx.Lock() 40 | _, _ = p.Fprintf(os.Stderr, format, a...) 41 | mx.Unlock() 42 | } 43 | -------------------------------------------------------------------------------- /service/file_hash_test.go: -------------------------------------------------------------------------------- 1 | package service 2 | 3 | import ( 4 | "github.com/m-manu/go-find-duplicates/bytesutil" 5 | "github.com/stretchr/testify/assert" 6 | "path/filepath" 7 | "runtime" 8 | "testing" 9 | ) 10 | 11 | func TestConfig(t *testing.T) { 12 | assert.Equal(t, int64(0), thresholdFileSize%(4*bytesutil.KIBI)) 13 | } 14 | 15 | func TestGetDigest(t *testing.T) { 16 | goRoot := runtime.GOROOT() 17 | var paths = []string{ 18 | filepath.Join(goRoot, "/src/io/io.go"), 19 | filepath.Join(goRoot, "/src/io/pipe.go"), 20 | } 21 | for _, path := range paths { 22 | digest, err := GetDigest(path, false) 23 | assert.Equal(t, nil, err) 24 | assert.Greater(t, digest.FileSize, int64(0)) 25 | assert.Equal(t, 9, len(digest.FileHash)) 26 | assert.Greater(t, len(digest.FileExtension), 0) 27 | } 28 | for _, path := range paths { 29 | digest, err := GetDigest(path, true) 30 | assert.Equal(t, nil, err) 31 | assert.Greater(t, digest.FileSize, int64(0)) 32 | assert.Equal(t, 64, len(digest.FileHash)) 33 | assert.Greater(t, len(digest.FileExtension), 0) 34 | } 35 | } 36 | -------------------------------------------------------------------------------- /utils/utils.go: -------------------------------------------------------------------------------- 1 | package utils 2 | 3 | import ( 4 | set "github.com/deckarep/golang-set/v2" 5 | "os" 6 | "path/filepath" 7 | "strings" 8 | ) 9 | 10 | // IsReadableDirectory checks whether argument is a readable directory 11 | func IsReadableDirectory(path string) bool { 12 | fileInfo, statErr := os.Stat(path) 13 | if statErr != nil { 14 | return false 15 | } 16 | return fileInfo.IsDir() 17 | } 18 | 19 | // IsReadableFile checks whether argument is a readable file 20 | func IsReadableFile(path string) bool { 21 | fileInfo, statErr := os.Stat(path) 22 | if statErr != nil { 23 | return false 24 | } 25 | return fileInfo.Mode().IsRegular() 26 | } 27 | 28 | // LineSeparatedStrToMap converts a line-separated string to a map with keys and empty values 29 | func LineSeparatedStrToMap(lineSeparatedString string) (entries set.Set[string], firstFew []string) { 30 | entries = set.NewThreadUnsafeSet[string]() 31 | firstFew = []string{} 32 | for _, e := range strings.Split(lineSeparatedString, "\n") { 33 | entries.Add(strings.TrimSpace(e)) 34 | firstFew = append(firstFew, e) 35 | } 36 | if len(firstFew) > 3 { 37 | firstFew = firstFew[0:3] 38 | } 39 | entries.Each(func(e string) bool { 40 | if e == "" { 41 | entries.Remove(e) 42 | } 43 | return false 44 | }) 45 | return 46 | } 47 | 48 | // GetFileExt gets extension of file, in lower case 49 | func GetFileExt(path string) string { 50 | ext := filepath.Ext(path) 51 | return strings.ToLower(ext) 52 | } 53 | -------------------------------------------------------------------------------- /service/dir_scanner.go: -------------------------------------------------------------------------------- 1 | package service 2 | 3 | import ( 4 | "errors" 5 | "fmt" 6 | set "github.com/deckarep/golang-set/v2" 7 | "github.com/m-manu/go-find-duplicates/entity" 8 | "github.com/m-manu/go-find-duplicates/fmte" 9 | "io/fs" 10 | "path/filepath" 11 | "strings" 12 | ) 13 | 14 | // populateFilesFromDirectory scans the given directory and populates the given map with the files 15 | func populateFilesFromDirectory(dirPathToScan string, exclusions set.Set[string], fileSizeThreshold int64, 16 | allFiles entity.FilePathToMeta) ( 17 | sizeOfScannedFiles int64, 18 | err error, 19 | ) { 20 | wErr := filepath.WalkDir(dirPathToScan, func(path string, d fs.DirEntry, err error) error { 21 | if err != nil { 22 | fmte.PrintfErr("skipping \"%s\": %+v\n", path, errors.Unwrap(err)) 23 | return nil 24 | } 25 | // If the file/directory is in excluded allFiles list, ignore it 26 | if exclusions.Contains(d.Name()) { 27 | if d.IsDir() { 28 | return filepath.SkipDir 29 | } 30 | return nil 31 | } 32 | if _, exists := allFiles[path]; exists { 33 | return nil 34 | } 35 | // Ignore dot allFiles (Mac) 36 | if strings.HasPrefix(d.Name(), "._") { 37 | return nil 38 | } 39 | if d.Type().IsRegular() { 40 | info, infoErr := d.Info() 41 | if infoErr != nil { 42 | fmte.PrintfErr("couldn't get metadata of \"%s\": %+v\n", path, infoErr) 43 | return nil 44 | } 45 | if info.Size() < fileSizeThreshold { 46 | return nil 47 | } 48 | allFiles[path] = entity.FileMeta{Size: info.Size(), ModifiedTimestamp: info.ModTime().Unix()} 49 | sizeOfScannedFiles += info.Size() 50 | } 51 | return nil 52 | }) 53 | if wErr != nil { 54 | return -1, fmt.Errorf("couldn't scan directory %s: %v", dirPathToScan, wErr) 55 | } 56 | return sizeOfScannedFiles, nil 57 | } 58 | -------------------------------------------------------------------------------- /entity/digest_to_files.go: -------------------------------------------------------------------------------- 1 | package entity 2 | 3 | import ( 4 | "github.com/emirpasic/gods/maps/treemap" 5 | "sync" 6 | ) 7 | 8 | // DigestToFiles is a multi-map with FileDigest keys and string values. 9 | // Writes to this is goroutine-safe. 10 | type DigestToFiles struct { 11 | mx *sync.Mutex 12 | data *treemap.Map 13 | } 14 | 15 | // FileDigestComparator is a comparator for FileDigest that compares FileSize, FileExtension and FileHash in that order 16 | func FileDigestComparator(a, b any) int { 17 | fa := a.(FileDigest) 18 | fb := b.(FileDigest) 19 | if fa.FileSize < fb.FileSize { 20 | return 1 21 | } else if fa.FileSize > fb.FileSize { 22 | return -1 23 | } else { 24 | if fa.FileExtension < fb.FileExtension { 25 | return 1 26 | } else if fa.FileExtension > fb.FileExtension { 27 | return -1 28 | } else { 29 | if fa.FileHash < fb.FileHash { 30 | return 1 31 | } else if fa.FileHash > fb.FileHash { 32 | return -1 33 | } else { 34 | return 0 35 | } 36 | } 37 | } 38 | } 39 | 40 | // NewDigestToFiles creates new DigestToFiles 41 | func NewDigestToFiles() (m *DigestToFiles) { 42 | return &DigestToFiles{ 43 | data: treemap.NewWith(FileDigestComparator), 44 | mx: &sync.Mutex{}, 45 | } 46 | } 47 | 48 | // Set sets a value for the key 49 | func (m *DigestToFiles) Set(key FileDigest, value string) { 50 | m.mx.Lock() 51 | valuesRaw, found := m.data.Get(key) 52 | var values []string 53 | if found { 54 | values = valuesRaw.([]string) 55 | values = append(values, value) 56 | } else { 57 | values = []string{value} 58 | } 59 | m.data.Put(key, values) 60 | m.mx.Unlock() 61 | } 62 | 63 | // Remove removes entry in the map 64 | func (m *DigestToFiles) Remove(fd FileDigest) { 65 | m.data.Remove(fd) 66 | } 67 | 68 | // Size returns size of map 69 | func (m *DigestToFiles) Size() int { 70 | return m.data.Size() 71 | } 72 | 73 | type digestToFilesIterator struct { 74 | iter treemap.Iterator 75 | } 76 | 77 | // Iterator returns an iterator for a DigestToFiles map 78 | func (m *DigestToFiles) Iterator() *digestToFilesIterator { 79 | return &digestToFilesIterator{m.data.Iterator()} 80 | } 81 | 82 | // HasNext returns true if there are more elements in the iterator 83 | func (m *digestToFilesIterator) HasNext() bool { 84 | return m.iter.Next() 85 | } 86 | 87 | // Next returns the next element in the iterator 88 | func (m *digestToFilesIterator) Next() (digest *FileDigest, paths []string) { 89 | fd := m.iter.Key().(FileDigest) 90 | filePaths := m.iter.Value().([]string) 91 | return &fd, filePaths 92 | } 93 | -------------------------------------------------------------------------------- /service/find_duplicates_test.go: -------------------------------------------------------------------------------- 1 | package service 2 | 3 | import ( 4 | set "github.com/deckarep/golang-set/v2" 5 | "github.com/m-manu/go-find-duplicates/entity" 6 | "github.com/m-manu/go-find-duplicates/fmte" 7 | "github.com/m-manu/go-find-duplicates/utils" 8 | "github.com/stretchr/testify/assert" 9 | "path/filepath" 10 | "runtime" 11 | "testing" 12 | ) 13 | 14 | const exclusionsStr = ` .DS_Store 15 | vendor 16 | 17 | ` 18 | 19 | // TestFindDuplicates tests whether FindDuplicates returns a non-nil map of duplicates 20 | func TestFindDuplicates(t *testing.T) { 21 | goRoot := runtime.GOROOT() 22 | directories := []string{ 23 | filepath.Join(goRoot, "pkg"), 24 | filepath.Join(goRoot, "src"), 25 | filepath.Join(goRoot, "test"), 26 | } 27 | exclusions, _ := utils.LineSeparatedStrToMap(exclusionsStr) 28 | fmte.Off() 29 | duplicates, duplicateCount, savingsSize, _, err := FindDuplicates(directories, exclusions, 30 | 4_196, 2, false) 31 | assert.Nil(t, err) 32 | assert.GreaterOrEqual(t, duplicates.Size(), 0) 33 | assert.GreaterOrEqual(t, duplicateCount, int64(0)) 34 | assert.GreaterOrEqual(t, savingsSize, int64(0)) 35 | } 36 | 37 | // TestNonThoroughVsNot checks whether FindDuplicates with 'thorough mode' on and off returns the same results 38 | func TestNonThoroughVsNot(t *testing.T) { 39 | exclusions, _ := utils.LineSeparatedStrToMap(exclusionsStr) 40 | goRoot := []string{runtime.GOROOT()} 41 | fmte.Off() 42 | duplicatesExpected, duplicateCountExpected, savingsSizeExpected, _, tErr := FindDuplicates(goRoot, exclusions, 43 | 4_196, 2, false) 44 | assert.Nil(t, tErr, "error while scanning for duplicates in GOROOT directory") 45 | duplicatesActual, duplicateCountActual, savingsSizeActual, _, ntErr := FindDuplicates(goRoot, exclusions, 46 | 4_196, 5, true) 47 | assert.Nil(t, ntErr, "error while thoroughly scanning for duplicates in GOROOT directory") 48 | actualDuplicateFilePaths := extractFiles(duplicatesActual) 49 | expectedDuplicateFilePaths := extractFiles(duplicatesExpected) 50 | assert.True(t, actualDuplicateFilePaths.Equal(expectedDuplicateFilePaths), "Duplicate files differed between thorough and non-thorough modes") 51 | assert.Equal(t, duplicateCountExpected, duplicateCountActual, "Number of duplicates differed between thorough and non-thorough modes") 52 | assert.Equal(t, savingsSizeExpected, savingsSizeActual, "Savings expected differed between thorough and non-thorough modes") 53 | } 54 | 55 | func extractFiles(duplicatesExpected *entity.DigestToFiles) set.Set[string] { 56 | expectedDuplicatesFiles := set.NewThreadUnsafeSet[string]() 57 | for iter := duplicatesExpected.Iterator(); iter.HasNext(); { 58 | _, paths := iter.Next() 59 | for _, path := range paths { 60 | expectedDuplicatesFiles.Add(path) 61 | } 62 | } 63 | return expectedDuplicatesFiles 64 | } 65 | -------------------------------------------------------------------------------- /go.sum: -------------------------------------------------------------------------------- 1 | github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= 2 | github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c= 3 | github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= 4 | github.com/deckarep/golang-set/v2 v2.1.0 h1:g47V4Or+DUdzbs8FxCCmgb6VYd+ptPAngjM6dtGktsI= 5 | github.com/deckarep/golang-set/v2 v2.1.0/go.mod h1:VAky9rY/yGXJOLEDv3OMci+7wtDpOF4IN+y82NBOac4= 6 | github.com/deckarep/golang-set/v2 v2.7.0 h1:gIloKvD7yH2oip4VLhsv3JyLLFnC0Y2mlusgcvJYW5k= 7 | github.com/deckarep/golang-set/v2 v2.7.0/go.mod h1:VAky9rY/yGXJOLEDv3OMci+7wtDpOF4IN+y82NBOac4= 8 | github.com/emirpasic/gods v1.18.1 h1:FXtiHYKDGKCW2KzwZKx0iC0PQmdlorYgdFG9jPXJ1Bc= 9 | github.com/emirpasic/gods v1.18.1/go.mod h1:8tpGGwCnJ5H4r6BWwaV6OrWmMoPhUl5jm/FMNAnJvWQ= 10 | github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM= 11 | github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= 12 | github.com/spf13/pflag v1.0.5 h1:iy+VFUOCP1a+8yFto/drg2CJ5u0yRoB7fZw3DKv/JXA= 13 | github.com/spf13/pflag v1.0.5/go.mod h1:McXfInJRrz4CZXVZOBLb0bTZqETkiAhM9Iw0y3An2Bg= 14 | github.com/spf13/pflag v1.0.6 h1:jFzHGLGAlb3ruxLB8MhbI6A8+AQX/2eW4qeyNZXNp2o= 15 | github.com/spf13/pflag v1.0.6/go.mod h1:McXfInJRrz4CZXVZOBLb0bTZqETkiAhM9Iw0y3An2Bg= 16 | github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= 17 | github.com/stretchr/objx v0.4.0/go.mod h1:YvHI0jy2hoMjB+UWwv71VJQ9isScKT/TqJzVSSt89Yw= 18 | github.com/stretchr/objx v0.5.0/go.mod h1:Yh+to48EsGEfYuaHDzXPcE3xhTkx73EhmCGUpEOglKo= 19 | github.com/stretchr/testify v1.7.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg= 20 | github.com/stretchr/testify v1.8.0/go.mod h1:yNjHg4UonilssWZ8iaSj1OCr/vHnekPRkoO+kdMU+MU= 21 | github.com/stretchr/testify v1.8.1 h1:w7B6lhMri9wdJUVmEZPGGhZzrYTPvgJArz7wNPgYKsk= 22 | github.com/stretchr/testify v1.8.1/go.mod h1:w2LPCIKwWwSfY2zedu0+kehJoqGctiVI29o6fzry7u4= 23 | github.com/stretchr/testify v1.10.0 h1:Xv5erBjTwe/5IxqUQTdXv5kgmIvbHo3QQyRwhJsOfJA= 24 | github.com/stretchr/testify v1.10.0/go.mod h1:r2ic/lqez/lEtzL7wO/rwa5dbSLXVDPFyf8C91i36aY= 25 | golang.org/x/text v0.7.0 h1:4BRB4x83lYWy72KwLD/qYDuTu7q9PjSagHvijDw7cLo= 26 | golang.org/x/text v0.7.0/go.mod h1:mrYo+phRRbMaCq/xk9113O4dZlRixOauAjOtrjsXDZ8= 27 | golang.org/x/text v0.21.0 h1:zyQAAkrwaneQ066sspRyJaG9VNi/YJ1NfzcGB3hZ/qo= 28 | golang.org/x/text v0.21.0/go.mod h1:4IBbMaMmOPCJ8SecivzSH54+73PCFmPWxNTLm+vZkEQ= 29 | golang.org/x/text v0.22.0 h1:bofq7m3/HAFvbF51jz3Q9wLg3jkvSPuiZu/pD1XwgtM= 30 | golang.org/x/text v0.22.0/go.mod h1:YRoo4H8PVmsu+E3Ou7cqLVH8oXWIHVoX0jqUWALQhfY= 31 | gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405 h1:yhCVgyC4o1eVCa2tZl7eS0r+SDo693bJlVdllGtEeKM= 32 | gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= 33 | gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= 34 | gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA= 35 | gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= 36 | -------------------------------------------------------------------------------- /bytesutil/human_readable_size.go: -------------------------------------------------------------------------------- 1 | // Package bytesutil helps you convert byte sizes (such as file size, data uploaded/downloaded etc.) to 2 | // human-readable strings. This allows conversion to decimal and binary formats. 3 | // 4 | // See: https://en.m.wikipedia.org/wiki/Byte#Multiple-byte_units 5 | package bytesutil 6 | 7 | import "fmt" 8 | 9 | // Constants for byte sizes in decimal and binary formats 10 | const ( 11 | KILO int64 = 1000 // 1000 power 1 (10 power 3) 12 | KIBI int64 = 1024 // 1024 power 1 (2 power 10) 13 | MEGA = KILO * KILO // 1000 power 2 (10 power 6) 14 | MEBI = KIBI * KIBI // 1024 power 2 (2 power 20) 15 | GIGA = MEGA * KILO // 1000 power 3 (10 power 9) 16 | GIBI = MEBI * KIBI // 1024 power 3 (2 power 30) 17 | TERA = GIGA * KILO // 1000 power 4 (10 power 12) 18 | TEBI = GIBI * KIBI // 1024 power 4 (2 power 40) 19 | PETA = TERA * KILO // 1000 power 5 (10 power 15) 20 | PEBI = TEBI * KIBI // 1024 power 5 (2 power 50) 21 | EXA = PETA * KILO // 1000 power 6 (10 power 18) 22 | EXBI = PEBI * KIBI // 1024 power 6 (2 power 60) 23 | ) 24 | 25 | // BinaryFormat formats a byte size to a human readable string in binary format. 26 | // Uses binary prefixes. See: https://en.m.wikipedia.org/wiki/Binary_prefix 27 | // 28 | // For example, 29 | // 30 | // fmt.Println(bytesutil.BinaryFormat(2140)) 31 | // 32 | // prints 33 | // 34 | // 2.09 KiB 35 | func BinaryFormat(size int64) string { 36 | if size < 0 { 37 | return "" 38 | } else if size < KIBI { 39 | return fmt.Sprintf("%d B", size) 40 | } else if size < MEBI { 41 | return fmt.Sprintf("%.2f KiB", float64(size)/float64(KIBI)) 42 | } else if size < GIBI { 43 | return fmt.Sprintf("%.2f MiB", float64(size)/float64(MEBI)) 44 | } else if size < TEBI { 45 | return fmt.Sprintf("%.2f GiB", float64(size)/float64(GIBI)) 46 | } else if size < PEBI { 47 | return fmt.Sprintf("%.2f TiB", float64(size)/float64(TEBI)) 48 | } else if size < EXBI { 49 | return fmt.Sprintf("%.2f PiB", float64(size)/float64(PEBI)) 50 | } else { 51 | return fmt.Sprintf("%.2f EiB", float64(size)/float64(EXBI)) 52 | } 53 | } 54 | 55 | // DecimalFormat formats a byte size to a human readable string in decimal format. 56 | // Uses metric prefixes. See: https://en.m.wikipedia.org/wiki/Metric_prefix 57 | // 58 | // For example, 59 | // 60 | // fmt.Println(bytesutil.DecimalFormat(2140)) 61 | // 62 | // prints 63 | // 64 | // 2.14KB 65 | func DecimalFormat(size int64) string { 66 | if size < 0 { 67 | return "" 68 | } else if size < KILO { 69 | return fmt.Sprintf("%d B", size) 70 | } else if size < MEGA { 71 | return fmt.Sprintf("%.2f KB", float64(size)/float64(KILO)) 72 | } else if size < GIGA { 73 | return fmt.Sprintf("%.2f MB", float64(size)/float64(MEGA)) 74 | } else if size < TERA { 75 | return fmt.Sprintf("%.2f GB", float64(size)/float64(GIGA)) 76 | } else if size < PETA { 77 | return fmt.Sprintf("%.2f TB", float64(size)/float64(TERA)) 78 | } else if size < EXA { 79 | return fmt.Sprintf("%.2f PB", float64(size)/float64(PETA)) 80 | } else { 81 | return fmt.Sprintf("%.2f EB", float64(size)/float64(EXA)) 82 | } 83 | } 84 | -------------------------------------------------------------------------------- /report.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "bytes" 5 | "encoding/csv" 6 | "encoding/json" 7 | "fmt" 8 | "io" 9 | "sort" 10 | "strconv" 11 | "time" 12 | 13 | "github.com/m-manu/go-find-duplicates/entity" 14 | ) 15 | 16 | const bytesPerLineGuess = 500 17 | 18 | func reportDuplicates(duplicates *entity.DigestToFiles, outputMode string, allFiles entity.FilePathToMeta, 19 | runID string, reportFile io.Writer) error { 20 | var err error 21 | if outputMode == entity.OutputModeStdOut { 22 | printReportToStdOut(runID, duplicates) 23 | } else if outputMode == entity.OutputModeTextFile { 24 | err = createTextFileReport(duplicates, reportFile) 25 | } else if outputMode == entity.OutputModeCsvFile { 26 | err = createCsvReport(duplicates, allFiles, reportFile) 27 | } else if outputMode == entity.OutputModeJSON { 28 | err = createJSONReport(duplicates, reportFile) 29 | } 30 | return err 31 | } 32 | 33 | func createTextFileReport(duplicates *entity.DigestToFiles, reportFile io.Writer) error { 34 | reportBB := getReportAsText(duplicates) 35 | _, rcErr := reportFile.Write(reportBB.Bytes()) 36 | return rcErr 37 | } 38 | 39 | func getReportAsText(duplicates *entity.DigestToFiles) bytes.Buffer { 40 | var bb bytes.Buffer 41 | bb.Grow(duplicates.Size() * bytesPerLineGuess) 42 | for iter := duplicates.Iterator(); iter.HasNext(); { 43 | digest, paths := iter.Next() 44 | sort.Strings(paths) 45 | bb.WriteString(fmt.Sprintf("%s: %d duplicate(s)\n", digest, len(paths)-1)) 46 | for _, path := range paths { 47 | bb.WriteString(fmt.Sprintf("\t%s\n", path)) 48 | } 49 | } 50 | return bb 51 | } 52 | 53 | func printReportToStdOut(runID string, duplicates *entity.DigestToFiles) { 54 | reportBB := getReportAsText(duplicates) 55 | fmt.Printf(` 56 | ========================== 57 | Report (run id %s) 58 | ========================== 59 | `, runID) 60 | fmt.Println(reportBB.String()) 61 | } 62 | 63 | func createCsvReport(duplicates *entity.DigestToFiles, allFiles entity.FilePathToMeta, reportFile io.Writer) error { 64 | var bb bytes.Buffer 65 | bb.Grow(duplicates.Size() * bytesPerLineGuess) 66 | cf := csv.NewWriter(&bb) 67 | _ = cf.Write([]string{"file hash", "file size", "last modified", "file path"}) 68 | for iter := duplicates.Iterator(); iter.HasNext(); { 69 | digest, paths := iter.Next() 70 | for _, path := range paths { 71 | _ = cf.Write([]string{ 72 | digest.FileHash, 73 | strconv.FormatInt(digest.FileSize, 10), 74 | time.Unix(allFiles[path].ModifiedTimestamp, 0).Format("02-Jan-2006 03:04:05 PM"), 75 | path, 76 | }) 77 | } 78 | } 79 | cf.Flush() 80 | _, err := reportFile.Write(bb.Bytes()) 81 | return err 82 | } 83 | 84 | func createJSONReport(duplicates *entity.DigestToFiles, reportFile io.Writer) error { 85 | type duplicateFile struct { 86 | entity.FileDigest 87 | Paths []string `json:"paths"` 88 | } 89 | var duplicatesToMarshall []duplicateFile 90 | for iter := duplicates.Iterator(); iter.HasNext(); { 91 | digest, paths := iter.Next() 92 | duplicatesToMarshall = append(duplicatesToMarshall, duplicateFile{ 93 | *digest, 94 | paths, 95 | }) 96 | } 97 | jsonBytes, err := json.Marshal(duplicatesToMarshall) 98 | if err != nil { 99 | return err 100 | } 101 | _, err = reportFile.Write(jsonBytes) 102 | return err 103 | } 104 | -------------------------------------------------------------------------------- /service/file_hash.go: -------------------------------------------------------------------------------- 1 | package service 2 | 3 | import ( 4 | "crypto/sha256" 5 | "encoding/hex" 6 | "fmt" 7 | "github.com/m-manu/go-find-duplicates/bytesutil" 8 | "github.com/m-manu/go-find-duplicates/entity" 9 | "github.com/m-manu/go-find-duplicates/utils" 10 | "hash" 11 | "hash/crc32" 12 | "os" 13 | ) 14 | 15 | const ( 16 | thresholdFileSize = 16 * bytesutil.KIBI 17 | ) 18 | 19 | // GetDigest generates entity.FileDigest of the file provided 20 | func GetDigest(path string, isThorough bool) (entity.FileDigest, error) { 21 | info, statErr := os.Lstat(path) 22 | if statErr != nil { 23 | return entity.FileDigest{}, statErr 24 | } 25 | h, hashErr := fileHash(path, isThorough) 26 | if hashErr != nil { 27 | return entity.FileDigest{}, hashErr 28 | } 29 | return entity.FileDigest{ 30 | FileExtension: utils.GetFileExt(path), 31 | FileSize: info.Size(), 32 | FileHash: h, 33 | }, nil 34 | } 35 | 36 | // fileHash calculates the hash of the file provided. 37 | // If isThorough is true, then it uses SHA256 of the entire file. 38 | // Otherwise, it uses CRC32 of "crucial bytes" of the file. 39 | func fileHash(path string, isThorough bool) (string, error) { 40 | fileInfo, statErr := os.Lstat(path) 41 | if statErr != nil { 42 | return "", fmt.Errorf("couldn't stat: %+v", statErr) 43 | } 44 | if !fileInfo.Mode().IsRegular() { 45 | return "", fmt.Errorf("can't compute hash of non-regular file") 46 | } 47 | var prefix string 48 | var bytes []byte 49 | var fileReadErr error 50 | if isThorough { 51 | bytes, fileReadErr = os.ReadFile(path) 52 | } else if fileInfo.Size() <= thresholdFileSize { 53 | prefix = "f" 54 | bytes, fileReadErr = os.ReadFile(path) 55 | } else { 56 | prefix = "s" 57 | bytes, fileReadErr = readCrucialBytes(path, fileInfo.Size()) 58 | } 59 | if fileReadErr != nil { 60 | return "", fmt.Errorf("couldn't calculate hash: %+v", fileReadErr) 61 | } 62 | var h hash.Hash 63 | if isThorough { 64 | h = sha256.New() 65 | } else { 66 | h = crc32.NewIEEE() 67 | } 68 | _, hashErr := h.Write(bytes) 69 | if hashErr != nil { 70 | return "", fmt.Errorf("error while computing hash: %+v", hashErr) 71 | } 72 | hashBytes := h.Sum(nil) 73 | return prefix + hex.EncodeToString(hashBytes), nil 74 | } 75 | 76 | // readCrucialBytes reads the first few bytes, middle bytes and last few bytes of the file 77 | func readCrucialBytes(filePath string, fileSize int64) ([]byte, error) { 78 | file, err := os.Open(filePath) 79 | if err != nil { 80 | return nil, err 81 | } 82 | defer file.Close() 83 | firstBytes := make([]byte, thresholdFileSize/2) 84 | _, fErr := file.ReadAt(firstBytes, 0) 85 | if fErr != nil { 86 | return nil, fmt.Errorf("couldn't read first few bytes (maybe file is corrupted?): %+v", fErr) 87 | } 88 | middleBytes := make([]byte, thresholdFileSize/4) 89 | _, mErr := file.ReadAt(middleBytes, fileSize/2) 90 | if mErr != nil { 91 | return nil, fmt.Errorf("couldn't read middle bytes (maybe file is corrupted?): %+v", mErr) 92 | } 93 | lastBytes := make([]byte, thresholdFileSize/4) 94 | _, lErr := file.ReadAt(lastBytes, fileSize-thresholdFileSize/4) 95 | if lErr != nil { 96 | return nil, fmt.Errorf("couldn't read end bytes (maybe file is corrupted?): %+v", lErr) 97 | } 98 | bytes := append(append(firstBytes, middleBytes...), lastBytes...) 99 | return bytes, nil 100 | } 101 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Go Find Duplicates 2 | 3 | [![build-and-test](https://github.com/m-manu/go-find-duplicates/actions/workflows/build-and-test.yml/badge.svg)](https://github.com/m-manu/go-find-duplicates/actions/workflows/build-and-test.yml) 4 | [![Go Report Card](https://goreportcard.com/badge/github.com/m-manu/go-find-duplicates)](https://goreportcard.com/report/github.com/m-manu/go-find-duplicates) 5 | [![Go Reference](https://pkg.go.dev/badge/github.com/m-manu/go-find-duplicates.svg)](https://pkg.go.dev/github.com/m-manu/go-find-duplicates) 6 | [![License](https://img.shields.io/badge/License-Apache%202-blue.svg)](./LICENSE) 7 | 8 | ## Introduction 9 | 10 | A blazingly-fast simple-to-use tool to find duplicate files (photos, videos, music, documents etc.) on your computer, 11 | portable hard drives etc. 12 | 13 | **Note**: 14 | 15 | * This tool just *reads* your files and creates a 'duplicates report' file 16 | * It does **not** delete or otherwise modify your files in any way 🙂 17 | * So, it's very safe to use 👍 18 | 19 | ## How to install? 20 | 21 | 1. Install Go version at least **1.22** 22 | * See: [Go installation instructions](https://go.dev/doc/install) 23 | 2. Run command: 24 | ```bash 25 | go install github.com/m-manu/go-find-duplicates@latest 26 | ``` 27 | 3. Add following line in your `.bashrc`/`.zshrc` file: 28 | ```bash 29 | export PATH="$PATH:$HOME/go/bin" 30 | ``` 31 | 32 | ## How to use? 33 | 34 | ### Run directly (preferred) 35 | 36 | ```bash 37 | go-find-duplicates {dir-1} {dir-2} ... {dir-n} 38 | ``` 39 | 40 | ### Command line options 41 | 42 | Running `go-find-duplicates --help` displays following: 43 | 44 | ``` 45 | go-find-duplicates is a tool to find duplicate files and directories 46 | 47 | Usage: 48 | go-find-duplicates [flags] ... 49 | 50 | where, 51 | arguments are readable directories that need to be scanned for duplicates 52 | 53 | Flags (all optional): 54 | -x, --exclusions string path to file containing newline-separated list of file/directory names to be excluded 55 | (if this is not set, by default these will be ignored: 56 | .DS_Store, System Volume Information, $RECYCLE.BIN etc.) 57 | -h, --help display help 58 | -m, --minsize uint minimum size of file in KiB to consider (default 4) 59 | -o, --output string following modes are accepted: 60 | print = just prints the report without creating any file 61 | text = creates a text file in the output directory with basic information 62 | csv = creates a csv file in the output directory with detailed information 63 | json = creates a JSON file in the output directory with basic information 64 | (default "text") 65 | -f, --outputfile string output file path (will be created, but directory needs to be writeable) 66 | -p, --parallelism uint8 extent of parallelism (defaults to number of cores minus 1) 67 | -q, --quiet quiet mode: no output on stdout/stderr, except for duplicates/errors 68 | -t, --thorough apply thorough check of uniqueness of files 69 | (caution: this makes the scan very slow!) 70 | --version display version (1.8.0) and exit (useful for incorporating this in scripts) 71 | 72 | For more details: https://github.com/m-manu/go-find-duplicates 73 | ``` 74 | 75 | ### Run via Docker 76 | 77 | ```bash 78 | docker run --rm -v /Volumes/PortableHD:/mnt/PortableHD manumk/go-find-duplicates:latest go-find-duplicates -o print /mnt/PortableHD 79 | ``` 80 | 81 | In above command: 82 | 83 | * option `--rm` removes the container when it exits 84 | * option `-v` is mounts host directory `/Volumes/PortableHD` as `/mnt/PortableHD` inside the container 85 | 86 | ## How does this identify duplicates? 87 | 88 | **By default**, this tool identifies duplicates if _all_ of the following conditions match: 89 | 90 | 1. file extension is same 91 | 2. file size is same 92 | 3. CRC32 hash of "crucial bytes" is same 93 | 94 | If above default isn't enough for your requirements, you could use the command line option `--thorough` to switch to 95 | SHA-256 hash of *entire file contents*. But remember, with this, scan becomes much slower! 96 | 97 | When tested on my portable hard drive containing >172k files (videos, audio files, images and documents), with and 98 | without `--thorough` option, the results were same! 99 | 100 | ## How to build? 101 | 102 | ```shell 103 | go build 104 | ``` -------------------------------------------------------------------------------- /service/find_duplicates.go: -------------------------------------------------------------------------------- 1 | package service 2 | 3 | import ( 4 | "fmt" 5 | "sync" 6 | "sync/atomic" 7 | "time" 8 | 9 | set "github.com/deckarep/golang-set/v2" 10 | "github.com/m-manu/go-find-duplicates/bytesutil" 11 | "github.com/m-manu/go-find-duplicates/entity" 12 | "github.com/m-manu/go-find-duplicates/fmte" 13 | "github.com/m-manu/go-find-duplicates/utils" 14 | ) 15 | 16 | // FindDuplicates finds duplicate files in a given set of directories and matching criteria 17 | func FindDuplicates(directories []string, excludedFiles set.Set[string], fileSizeThreshold int64, parallelism int, 18 | isThorough bool) ( 19 | duplicates *entity.DigestToFiles, duplicateTotalCount int64, savingsSize int64, 20 | allFiles entity.FilePathToMeta, err error, 21 | ) { 22 | fmte.Printf("Scanning %d directories...\n", len(directories)) 23 | allFiles = make(entity.FilePathToMeta, 10_000) 24 | var totalSize int64 25 | for _, dirPath := range directories { 26 | size, pErr := populateFilesFromDirectory(dirPath, excludedFiles, fileSizeThreshold, allFiles) 27 | if pErr != nil { 28 | err = fmt.Errorf("error while scaning directory %s: %+v", dirPath, pErr) 29 | return 30 | } 31 | totalSize += size 32 | } 33 | fmte.Printf("Done. Found %d files of total size %s.\n", len(allFiles), bytesutil.BinaryFormat(totalSize)) 34 | if len(allFiles) == 0 { 35 | return 36 | } 37 | fmte.Printf("Finding potential duplicates... \n") 38 | shortlist := identifyShortList(allFiles) 39 | if len(shortlist) == 0 { 40 | return 41 | } 42 | fmte.Printf("Completed. Found %d files that may have one or more duplicates!\n", len(shortlist)) 43 | if isThorough { 44 | fmte.Printf("Thoroughly scanning for duplicates... \n") 45 | } else { 46 | fmte.Printf("Scanning for duplicates... \n") 47 | } 48 | var processedCount int32 49 | var wg sync.WaitGroup 50 | wg.Add(2) 51 | go func(pc *int32, fc int32) { 52 | defer wg.Done() 53 | time.Sleep(200 * time.Millisecond) 54 | for atomic.LoadInt32(pc) < fc { 55 | time.Sleep(2 * time.Second) 56 | progress := float64(atomic.LoadInt32(pc)) / float64(fc) 57 | fmte.Printf("%2.0f%% processed so far\n", progress*100.0) 58 | } 59 | }(&processedCount, int32(len(shortlist))) 60 | go func(p *int32) { 61 | defer wg.Done() 62 | duplicates = entity.NewDigestToFiles() 63 | computeDigestsAndGroupThem(shortlist, parallelism, p, duplicates, isThorough) 64 | for iter := duplicates.Iterator(); iter.HasNext(); { 65 | digest, files := iter.Next() 66 | numDuplicates := int64(len(files)) - 1 67 | duplicateTotalCount += numDuplicates 68 | savingsSize += numDuplicates * digest.FileSize 69 | } 70 | }(&processedCount) 71 | wg.Wait() 72 | fmte.Printf("Scan completed.\n") 73 | return 74 | } 75 | 76 | func computeDigestsAndGroupThem(shortlist entity.FileExtAndSizeToFiles, parallelism int, 77 | processedCount *int32, duplicates *entity.DigestToFiles, isThorough bool, 78 | ) { 79 | // Find potential duplicates: 80 | slKeys := make([]entity.FileExtAndSize, 0, len(shortlist)) 81 | for extAndSize := range shortlist { 82 | slKeys = append(slKeys, extAndSize) 83 | } 84 | var wg sync.WaitGroup 85 | wg.Add(parallelism) 86 | for i := 0; i < parallelism; i++ { 87 | go func(shard int, wg *sync.WaitGroup, count *int32) { 88 | defer wg.Done() 89 | low := shard * len(slKeys) / parallelism 90 | high := (shard + 1) * len(slKeys) / parallelism 91 | for _, fileExtAndSize := range slKeys[low:high] { 92 | for _, path := range shortlist[fileExtAndSize] { 93 | digest, err := GetDigest(path, isThorough) 94 | if err != nil { 95 | fmte.Printf("error while scanning %s: %+v\n", path, err) 96 | continue 97 | } 98 | duplicates.Set(digest, path) 99 | } 100 | atomic.AddInt32(count, 1) 101 | } 102 | }(i, &wg, processedCount) 103 | } 104 | wg.Wait() 105 | // Remove non-duplicates 106 | var duplicateKeys []entity.FileDigest 107 | for iter := duplicates.Iterator(); iter.HasNext(); { 108 | digest, files := iter.Next() 109 | if len(files) <= 1 { 110 | duplicateKeys = append(duplicateKeys, *digest) 111 | } 112 | } 113 | for _, key := range duplicateKeys { 114 | duplicates.Remove(key) 115 | } 116 | return 117 | } 118 | 119 | // identifyShortList identifies the files that may have duplicates 120 | func identifyShortList(filesAndMeta entity.FilePathToMeta) (shortlist entity.FileExtAndSizeToFiles) { 121 | shortlist = make(entity.FileExtAndSizeToFiles, len(filesAndMeta)) 122 | // Group the files that have same extension and same size 123 | for path, meta := range filesAndMeta { 124 | fileExtAndSize := entity.FileExtAndSize{FileExtension: utils.GetFileExt(path), FileSize: meta.Size} 125 | shortlist[fileExtAndSize] = append(shortlist[fileExtAndSize], path) 126 | } 127 | // Remove non-duplicates 128 | for fileExtAndSize, paths := range shortlist { 129 | if len(paths) <= 1 { 130 | delete(shortlist, fileExtAndSize) 131 | } 132 | } 133 | return shortlist 134 | } 135 | -------------------------------------------------------------------------------- /main.go: -------------------------------------------------------------------------------- 1 | /* 2 | A blazingly-fast simple-to-use tool to find duplicate files (photos, videos, music, documents etc.) on your computer, 3 | portable hard drives etc. 4 | */ 5 | package main 6 | 7 | import ( 8 | _ "embed" 9 | "fmt" 10 | set "github.com/deckarep/golang-set/v2" 11 | "github.com/m-manu/go-find-duplicates/bytesutil" 12 | "github.com/m-manu/go-find-duplicates/entity" 13 | "github.com/m-manu/go-find-duplicates/fmte" 14 | "github.com/m-manu/go-find-duplicates/service" 15 | "github.com/m-manu/go-find-duplicates/utils" 16 | flag "github.com/spf13/pflag" 17 | "io" 18 | "os" 19 | "path/filepath" 20 | "runtime" 21 | "runtime/debug" 22 | "strings" 23 | "time" 24 | ) 25 | 26 | // Exit codes for this program 27 | const ( 28 | exitCodeSuccess = iota 29 | exitCodeInvalidNumArgs 30 | exitCodeInvalidExclusions 31 | exitCodeInputDirectoryNotReadable 32 | exitCodeExclusionFilesError 33 | exitCodeErrorFindingDuplicates 34 | exitCodeErrorCreatingReport 35 | exitCodeInvalidOutputMode 36 | exitCodeReportFileCreationFailed 37 | exitCodeOutputDirectoryIsNotReadable 38 | ) 39 | 40 | const version = "1.8.0" 41 | 42 | //go:embed default_exclusions.txt 43 | var defaultExclusionsStr string 44 | 45 | var flags struct { 46 | isHelp func() bool 47 | getOutputMode func() string 48 | getExcludedFiles func() set.Set[string] 49 | getMinSize func() int64 50 | getParallelism func() int 51 | isThorough func() bool 52 | getOutputFilePath func() string 53 | getVersion func() bool 54 | isQuiet func() bool 55 | } 56 | 57 | func setupExclusionsOpt() { 58 | const exclusionsFlag = "exclusions" 59 | const exclusionsDefaultValue = "" 60 | defaultExclusions, defaultExclusionsExamples := utils.LineSeparatedStrToMap(defaultExclusionsStr) 61 | excludesListFilePathPtr := flag.StringP(exclusionsFlag, "x", exclusionsDefaultValue, 62 | fmt.Sprintf("path to file containing newline-separated list of file/directory names to be excluded\n"+ 63 | "(if this is not set, by default these will be ignored:\n%s etc.)", 64 | strings.Join(defaultExclusionsExamples, ", "))) 65 | flags.getExcludedFiles = func() set.Set[string] { 66 | excludesListFilePath := *excludesListFilePathPtr 67 | var exclusions set.Set[string] 68 | if excludesListFilePath == exclusionsDefaultValue { 69 | exclusions = defaultExclusions 70 | } else { 71 | if !utils.IsReadableFile(excludesListFilePath) { 72 | fmte.PrintfErr("error: argument to flag --%s should be a readable file\n", exclusionsFlag) 73 | flag.Usage() 74 | os.Exit(exitCodeInvalidExclusions) 75 | } 76 | rawContents, err := os.ReadFile(excludesListFilePath) 77 | if err != nil { 78 | fmte.PrintfErr("error: unable to read exclusions file: %+v\n", exclusionsFlag, err) 79 | flag.Usage() 80 | os.Exit(exitCodeExclusionFilesError) 81 | } 82 | contents := strings.ReplaceAll(string(rawContents), "\r\n", "\n") // Windows 83 | exclusions, _ = utils.LineSeparatedStrToMap(contents) 84 | } 85 | return exclusions 86 | } 87 | } 88 | 89 | func setupHelpOpt() { 90 | helpPtr := flag.BoolP("help", "h", false, "display help") 91 | flags.isHelp = func() bool { 92 | return *helpPtr 93 | } 94 | } 95 | 96 | func setupThoroughOpt() { 97 | thoroughPtr := flag.BoolP("thorough", "t", false, 98 | "apply thorough check of uniqueness of files\n(caution: this makes the scan very slow!)", 99 | ) 100 | flags.isThorough = func() bool { 101 | return *thoroughPtr 102 | } 103 | } 104 | 105 | func setupMinSizeOpt() { 106 | fileSizeThresholdPtr := flag.Uint64P("minsize", "m", 4, 107 | "minimum size of file in KiB to consider", 108 | ) 109 | flags.getMinSize = func() int64 { 110 | return int64(*fileSizeThresholdPtr) * bytesutil.KIBI 111 | } 112 | } 113 | 114 | func setupParallelismOpt() { 115 | const defaultParallelismValue = 0 116 | parallelismPtr := flag.Uint8P("parallelism", "p", defaultParallelismValue, 117 | "extent of parallelism (defaults to number of cores minus 1)") 118 | flags.getParallelism = func() int { 119 | if *parallelismPtr == defaultParallelismValue { 120 | n := runtime.NumCPU() 121 | if n > 1 { 122 | return n - 1 123 | } 124 | return 1 125 | } 126 | return int(*parallelismPtr) 127 | } 128 | } 129 | 130 | func setupOutputModeOpt() { 131 | var sb strings.Builder 132 | sb.WriteString("following modes are accepted:\n") 133 | for outputMode, description := range entity.OutputModes { 134 | sb.WriteString(fmt.Sprintf("%5s = %s\n", outputMode, description)) 135 | } 136 | outputModeStrPtr := flag.StringP("output", "o", entity.OutputModeTextFile, sb.String()) 137 | flags.getOutputMode = func() string { 138 | outputModeStr := strings.ToLower(strings.TrimSpace(*outputModeStrPtr)) 139 | if _, exists := entity.OutputModes[outputModeStr]; !exists { 140 | fmt.Printf("error: invalid output mode '%s'\n", outputModeStr) 141 | os.Exit(exitCodeInvalidOutputMode) 142 | } 143 | return outputModeStr 144 | } 145 | } 146 | 147 | const DefaultFileName = "" 148 | 149 | func setupOutputFileOpt() { 150 | outputFilePathPtr := flag.StringP("outputfile", "f", DefaultFileName, 151 | "output file path (will be created, but directory needs to be writeable)") 152 | flags.getOutputFilePath = func() string { 153 | outputFilePath := *outputFilePathPtr 154 | outputDir := filepath.Dir(outputFilePath) 155 | if !utils.IsReadableDirectory(outputDir) { // Deliberately not checking whether directory is writable 156 | fmte.PrintfErr("error: output directory '%s' does not exist or is not readable\n", outputDir) 157 | os.Exit(exitCodeOutputDirectoryIsNotReadable) 158 | } 159 | return outputFilePath 160 | } 161 | } 162 | 163 | func setupVersionOpt() { 164 | versionPtr := flag.Bool("version", false, 165 | "display version ("+version+") and exit (useful for incorporating this in scripts)") 166 | flags.getVersion = func() bool { 167 | return *versionPtr 168 | } 169 | } 170 | 171 | func setupQuietOpt() { 172 | isQuietPtr := flag.BoolP("quiet", "q", false, 173 | "quiet mode: no output on stdout/stderr, except for duplicates/errors") 174 | flags.isQuiet = func() bool { 175 | return *isQuietPtr 176 | } 177 | } 178 | 179 | func setupUsage() { 180 | flag.Usage = func() { 181 | fmte.PrintfErr("Run \"go-find-duplicates --help\" for usage\n") 182 | } 183 | } 184 | 185 | func readDirectories() (directories []string) { 186 | if flag.NArg() < 1 { 187 | fmte.PrintfErr("error: no input directories passed\n") 188 | flag.Usage() 189 | os.Exit(exitCodeInvalidNumArgs) 190 | } 191 | for i, p := range flag.Args() { 192 | if !utils.IsReadableDirectory(p) { 193 | fmte.PrintfErr("error: input #%d \"%v\" isn't a readable directory\n", i+1, p) 194 | flag.Usage() 195 | os.Exit(exitCodeInputDirectoryNotReadable) 196 | } 197 | abs, _ := filepath.Abs(p) 198 | directories = append(directories, abs) 199 | } 200 | return directories 201 | } 202 | 203 | func handlePanic() { 204 | err := recover() 205 | if err != nil { 206 | _, _ = fmt.Fprintf(os.Stderr, "Program exited unexpectedly. "+ 207 | "Please report the below eror to the author:\n"+ 208 | "%+v\n", err) 209 | _, _ = fmt.Fprintln(os.Stderr, string(debug.Stack())) 210 | } 211 | } 212 | 213 | func showHelpAndExit() { 214 | flag.CommandLine.SetOutput(os.Stdout) 215 | fmt.Printf(`go-find-duplicates is a tool to find duplicate files and directories 216 | 217 | Usage: 218 | go-find-duplicates [flags] ... 219 | 220 | where, 221 | arguments are readable directories that need to be scanned for duplicates 222 | 223 | Flags (all optional): 224 | `) 225 | flag.PrintDefaults() 226 | fmt.Printf(` 227 | For more details: https://github.com/m-manu/go-find-duplicates 228 | `) 229 | os.Exit(exitCodeSuccess) 230 | } 231 | 232 | func setupFlags() { 233 | setupUsage() 234 | setupExclusionsOpt() 235 | setupHelpOpt() 236 | setupMinSizeOpt() 237 | setupOutputModeOpt() 238 | setupParallelismOpt() 239 | setupThoroughOpt() 240 | setupVersionOpt() 241 | setupQuietOpt() 242 | setupOutputFileOpt() 243 | } 244 | 245 | func generateRunID() string { 246 | return time.Now().Format("060102_150405") 247 | } 248 | 249 | func createReportFileIfApplicable(runID string, outputMode string) (string, io.WriteCloser) { 250 | var reportFileName string 251 | switch outputMode { 252 | case entity.OutputModeCsvFile: 253 | reportFileName = fmt.Sprintf("./duplicates_%s.csv", runID) 254 | case entity.OutputModeTextFile: 255 | reportFileName = fmt.Sprintf("./duplicates_%s.txt", runID) 256 | case entity.OutputModeJSON: 257 | reportFileName = fmt.Sprintf("./duplicates_%s.json", runID) 258 | default: 259 | panic("unsupported output mode - bug in code") 260 | } 261 | f, err := os.Create(reportFileName) 262 | if err != nil { 263 | fmte.PrintfErr("error: couldn't create report file: %+v\n", err) 264 | os.Exit(exitCodeReportFileCreationFailed) 265 | } 266 | return reportFileName, f 267 | } 268 | 269 | func main() { 270 | defer handlePanic() 271 | runID := generateRunID() 272 | setupFlags() 273 | flag.Parse() 274 | if flags.isHelp() { 275 | showHelpAndExit() 276 | return 277 | } 278 | if flags.getVersion() { 279 | fmt.Println(version) 280 | os.Exit(exitCodeSuccess) 281 | return 282 | } 283 | 284 | if flags.isQuiet() { 285 | fmte.Off() 286 | } 287 | 288 | directories := readDirectories() 289 | outputMode := flags.getOutputMode() 290 | reportFileName := flags.getOutputFilePath() 291 | var reportFile io.Writer 292 | var fErr error 293 | if outputMode == entity.OutputModeStdOut { 294 | reportFile = os.Stdout 295 | } else { // For other modes 296 | if reportFileName == DefaultFileName { 297 | reportFileName, reportFile = createReportFileIfApplicable(runID, outputMode) 298 | } else { 299 | reportFile, fErr = os.Create(reportFileName) 300 | if fErr != nil { 301 | fmte.PrintfErr("error: couldn't create report file: %+v\n", fErr) 302 | os.Exit(exitCodeReportFileCreationFailed) 303 | } 304 | } 305 | } 306 | 307 | duplicates, duplicateTotalCount, savingsSize, allFiles, fdErr := 308 | service.FindDuplicates(directories, flags.getExcludedFiles(), flags.getMinSize(), 309 | flags.getParallelism(), flags.isThorough()) 310 | if fdErr != nil { 311 | fmte.PrintfErr("error while finding duplicates: %+v\n", fdErr) 312 | os.Exit(exitCodeErrorFindingDuplicates) 313 | } 314 | if duplicates == nil || duplicates.Size() == 0 { 315 | if len(allFiles) == 0 { 316 | fmte.Printf("No actions performed!\n") 317 | } else { 318 | fmte.Printf("No duplicates found!\n") 319 | } 320 | return 321 | } 322 | fmte.Printf("Found %d duplicates. A total of %s can be saved by removing them.\n", 323 | duplicateTotalCount, bytesutil.BinaryFormat(savingsSize)) 324 | 325 | dErr := reportDuplicates(duplicates, outputMode, allFiles, runID, reportFile) 326 | if dErr != nil { 327 | fmte.PrintfErr("error while reporting to file: %+v\n", dErr) 328 | os.Exit(exitCodeErrorCreatingReport) 329 | } 330 | if reportFileName != DefaultFileName { 331 | fmte.Printf("View duplicates report here: %s\n", reportFileName) 332 | } 333 | } 334 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright [yyyy] [name of copyright owner] 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. --------------------------------------------------------------------------------