NASutils Knowledge BaseUnofficialPolski

Go · projectFind duplicate files with a pool of workers

This Go program shows which files in a folder are copies of each other and how much space the extra copies take. It reads a file only when another file has exactly the same size, so on a big share most files are never opened. The files it does read are hashed by several workers at once, 4 by default.

Programming on the NAS › Go in 30 lessons

 Duplicate files in dupes-sample ──────────────────────────────────────────────
7 files, 142.2 KiB. 6 share a size with another file; 4 workers hashed them.

3 copies of 29.3 KiB   sha256 7898322c774e…   extra copies take 58.6 KiB
    dupes-sample/backup/IMG_0001.jpg
    dupes-sample/old/copy of IMG_0001.jpg
    dupes-sample/photos/IMG_0001.jpg

2 copies of 1.2 KiB   sha256 54f82880e05c…   extra copies take 1.2 KiB
    dupes-sample/docs/report (final).txt
    dupes-sample/docs/report.txt

The extra copies take 59.8 KiB in all.
Keep one file of each group and delete the others to free that space.
The sample folder of 7 files: 6 share a size, two groups are duplicates, three copies of a 29.3 KiB photo and two of a report, and the extra copies take 59.8 KiB.

Download it on the NAS

curl -fsSLO https://kb.nasutils.net/projects/go/dupes.go

dupes.go Download dupes.go

// dupes.go: finds duplicate files in a folder. It groups the files by size, hashes only the files that share a size
// with SHA-256 in a pool of workers, and prints each group of equal files with the space its extra copies take.
// Build and run it: go build dupes.go && ./dupes [-j 4] FOLDER   (-j is the number of workers that hash at once)
package main

import (
	"cmp"
	"crypto/sha256"
	"encoding/hex"
	"flag"
	"fmt"
	"io"
	"io/fs"
	"os"
	"path/filepath"
	"slices"
	"strings"
	"sync"
)

const amber, red, dim, bold, reset = "\033[38;5;214m", "\033[31m", "\033[2m", "\033[1m", "\033[0m"

type result struct {
	path, sum string
	err       error
}

func size(n int64) string {
	switch {
	case n >= 1<<30:
		return fmt.Sprintf("%.1f GiB", float64(n)/(1<<30))
	case n >= 1<<20:
		return fmt.Sprintf("%.1f MiB", float64(n)/(1<<20))
	}
	return fmt.Sprintf("%.1f KiB", float64(n)/(1<<10))
}

// hash reads one file through SHA-256 and returns the sum in hex.
func hash(path string) (string, error) {
	f, err := os.Open(path)
	if err != nil {
		return "", err
	}
	defer f.Close()
	h := sha256.New()
	if _, err := io.Copy(h, f); err != nil {
		return "", err
	}
	return hex.EncodeToString(h.Sum(nil)), nil
}

func main() {
	workers := flag.Int("j", 4, "the number of files hashed at the same time")
	flag.Parse()
	if flag.NArg() != 1 || *workers < 1 {
		fmt.Fprintln(os.Stderr, "Usage: dupes [-j WORKERS] FOLDER")
		os.Exit(2)
	}
	root := flag.Arg(0)

	// 1. Walk the folder and group the regular files by size; empty files are left out.
	bySize := map[int64][]string{}
	files, total := 0, int64(0)
	err := filepath.WalkDir(root, func(path string, d fs.DirEntry, err error) error {
		if err != nil { // a folder it may not read: say so and go on
			fmt.Fprintln(os.Stderr, "dupes:", err)
			return nil
		}
		if !d.Type().IsRegular() {
			return nil
		}
		info, err := d.Info()
		if err != nil || info.Size() == 0 {
			return err
		}
		bySize[info.Size()] = append(bySize[info.Size()], path)
		files, total = files+1, total+info.Size()
		return nil
	})
	if err != nil {
		fmt.Fprintln(os.Stderr, "dupes:", err)
		os.Exit(1)
	}

	// 2. Only a file that shares its size with another can have a twin: those go to the workers.
	jobs, results := make(chan string), make(chan result)
	var wg sync.WaitGroup
	for range *workers {
		wg.Add(1)
		go func() {
			defer wg.Done()
			for path := range jobs {
				sum, err := hash(path)
				results <- result{path, sum, err}
			}
		}()
	}
	var queue []string // the files that share their size with another file
	for _, paths := range bySize {
		if len(paths) > 1 {
			queue = append(queue, paths...)
		}
	}
	go func() { // feed the jobs, then close results once every worker is done
		for _, p := range queue {
			jobs <- p
		}
		close(jobs)
		wg.Wait()
		close(results)
	}()

	// 3. Group the results by their sum; a sum with two or more files is a group of duplicates.
	bySum := map[string][]string{}
	for r := range results {
		if r.err != nil {
			fmt.Fprintln(os.Stderr, "dupes:", r.err)
			continue
		}
		bySum[r.sum] = append(bySum[r.sum], r.path)
	}
	type group struct {
		sum    string
		paths  []string
		wasted int64
	}
	var groups []group
	var wasted int64
	for sum, paths := range bySum {
		if len(paths) > 1 {
			info, _ := os.Stat(paths[0])
			slices.Sort(paths)
			groups = append(groups, group{sum, paths, int64(len(paths)-1) * info.Size()})
			wasted += groups[len(groups)-1].wasted
		}
	}
	slices.SortFunc(groups, func(a, b group) int { // the most space first; equal ones by their first file
		return cmp.Or(cmp.Compare(b.wasted, a.wasted), strings.Compare(a.paths[0], b.paths[0]))
	})

	fmt.Printf("%s%s Duplicate files in %s %s%s\n", bold, amber, root, strings.Repeat("─", max(0, 58-len(root))), reset)
	fmt.Printf("%d files, %s. %d share a size with another file; %d workers hashed them.\n\n",
		files, size(total), len(queue), *workers)
	if len(groups) == 0 {
		fmt.Println("No duplicates: every file has its own content.")
		return
	}
	for _, g := range groups {
		fmt.Printf("%s%d copies%s of %s   %ssha256 %s…%s   extra copies take %s%s%s\n", bold, len(g.paths), reset,
			size(int64(g.wasted)/int64(len(g.paths)-1)), dim, g.sum[:12], reset, red, size(g.wasted), reset)
		for _, p := range g.paths {
			fmt.Printf("    %s\n", p)
		}
		fmt.Println()
	}
	fmt.Printf("%sThe extra copies take %s%s%s in all.\n", bold, red, size(wasted), reset)
	fmt.Println("Keep one file of each group and delete the others to free that space.")
}

What you learn

  • A map from size to paths finds the candidates without reading a single byte of the files.
  • A worker pool: -j goroutines take paths from one channel and send results on another.
  • sync.WaitGroup tells when every worker is done, so results can be closed and the reading loop ends.
  • io.Copy(h, f) streams a file of any size through SHA-256 without loading it into memory.
  • slices.SortFunc with cmp.Or sorts by two keys: the space first, then the name.

How it works

The program works in three steps, marked in the code. Step 1 walks the folder with filepath.WalkDir and groups every regular file by its size. Empty files are left out, because they are all equal and free no space. A folder it cannot read gets one line on the error output, and the walk goes on.

Step 2 starts the workers and a feeder goroutine. The feeder sends each candidate path on jobs, closes jobs, waits for the workers with wg.Wait() and closes results. Each worker hashes the paths it takes from jobs until the channel is closed.

Step 3 runs in main and reads results until the channel is closed. Files with the same SHA-256 sum have the same content. Each group of two or more is printed with its files sorted by name; the extra copies are all files of the group but one. The program only reads; it deletes nothing.

Notes to the lines

  • 23–26One result per file: the path, the sum, or the error that stopped the reading.
  • 28–36size prints KiB, MiB or GiB with one decimal; 1<<20 is 1 MiB.
  • 38–50hash opens the file, copies it into the hash and returns the sum as 64 hex digits.
  • 64–79The walk; d.Type().IsRegular() skips folders, links and devices.
  • 86–97The pool: for range *workers starts as many goroutines as -j says.
  • 98–103The candidates are the paths of every size that more than one file has.
  • 104–111The feeder closes results only after the last worker is done, so no worker sends on a closed channel.
  • 115–121The loop ends when results is closed; a file that cannot be read is reported and skipped.
  • 129–136The space the extra copies of a group take is the size of one file times the copies minus one.
  • 137–139The order of a map is random in Go; sorting makes the output the same each time.

Run it

Build it in the terminal of Bucket & Code's editor, with its Go runtime:

eval "$(bvs use go-1.27-x86_64)"
go build dupes.go
./dupes /share/Public
./dupes -j 2 /share/Multimedia

-j 2 hashes two files at a time, which leaves more of the NAS to others. The finished file runs on the NAS without Go. It deletes nothing.

Try it yourself

Add an option -min that skips files smaller than a given number of KiB. Print the time the hashing took with time.Since, and compare -j 1 with -j 4 on a large folder.

More projects in Go