diff --git a/README.md b/README.md new file mode 100644 index 0000000..84f2d81 --- /dev/null +++ b/README.md @@ -0,0 +1,36 @@ +# arrange + +de-duplicate and arrange photos and movies into a content-addressed store, +with hardlinks by date. + + out/content/ab/cdef….jpg one copy of each file, named by its sha256 + out/date/2006/03/1143508767….jpg hardlinks to those, by capture time + +Capture time comes from exif (jpeg, heic, camera raw), the QuickTime movie +header (mov, mp4, m4v, 3gp), or the file's mtime as a last resort. + +## usage + + go install mcquay.me/arrange/cmd/am@latest + + # see what would happen; prints new/dupsrccontentdate dir + am arr -n ~/Pictures /mnt/store > plan.tsv + + # do it; nothing in the source is changed + am arr ~/Pictures /mnt/store + + # re-hash the store: corrupt files, orphans, leftovers from crashed runs + am verify /mnt/store + + # turn dated files that are copies rather than hardlinks back into links + am clean -n /mnt/store + am clean /mnt/store + + # print the time and path am would use for some files + am meta a.jpg b.mov + +`arr` ends with a summary of counts and sizes by extension and year. It +names no files, so it is safe to share. + +Stores made before sha256 use md5 names; add to one with `-hash=md5`. +`verify` works out the hash from each name's length. diff --git a/arrange.go b/arrange.go index 5a602b8..0f27221 100644 --- a/arrange.go +++ b/arrange.go @@ -2,11 +2,14 @@ package arrange import ( "crypto/md5" + "crypto/sha256" "fmt" + "hash" "image/gif" "image/jpeg" "image/png" "io" + "io/fs" "log" "os" "path/filepath" @@ -15,22 +18,64 @@ import ( "time" ) -var exts map[string]bool +// kind is how a file extension gets parsed. +type kind int -func init() { - exts = map[string]bool{ - // images - ".jpg": true, - ".jpeg": true, - ".png": true, - ".gif": true, +const ( + kindJPEG kind = iota + kindPNG + kindGIF + kindStill // HEIC, camera RAW, etc.: dated by exif, no decode check + kindQuickTime // mov/mp4 family: dated by the mvhd atom + kindVideo // everything else: dated by mtime +) - // videos - ".mov": true, - ".mp4": true, - ".m4v": true, - ".avi": true, +var exts = map[string]kind{ + // images + ".jpg": kindJPEG, + ".jpeg": kindJPEG, + ".png": kindPNG, + ".gif": kindGIF, + ".heic": kindStill, + ".heif": kindStill, + ".avif": kindStill, + ".tif": kindStill, + ".tiff": kindStill, + ".dng": kindStill, + ".cr2": kindStill, + ".cr3": kindStill, + ".nef": kindStill, + ".arw": kindStill, + + // videos + ".mov": kindQuickTime, + ".mp4": kindQuickTime, + ".m4v": kindQuickTime, + ".3gp": kindQuickTime, + ".avi": kindVideo, + ".mkv": kindVideo, + ".mts": kindVideo, + ".m2ts": kindVideo, + ".mpg": kindVideo, + ".mpeg": kindVideo, + ".wmv": kindVideo, + ".webm": kindVideo, +} + +// NewHash makes the hash used for content addresses. Stores built by older +// versions used md5; set this to md5.New to keep adding to one of those. +var NewHash func() hash.Hash = sha256.New + +// HashByName returns the hash constructor matching the length of a hex +// content address, or nil if it is not one we know. +func HashByName(hexname string) func() hash.Hash { + switch len(hexname) { + case 2 * md5.Size: + return md5.New + case 2 * sha256.Size: + return sha256.New } + return nil } func mtime(path string) (time.Time, error) { @@ -56,21 +101,34 @@ func PrepOutput(root string) error { return nil } -// Source returns sends all files that match known extensions. +// Source sends all files that match known extensions. Unreadable paths are +// logged and skipped rather than ending the crawl. func Source(root string) <-chan string { out := make(chan string) go func() { - err := filepath.Walk( + err := filepath.WalkDir( root, - func(path string, info os.FileInfo, err error) error { + func(path string, d fs.DirEntry, err error) error { if err != nil { - return err - } - if info.IsDir() { + if path == root { + return err + } + log.Printf("skipping %q: %v", path, err) return nil } - ext := strings.ToLower(filepath.Ext(path)) - if _, ok := exts[ext]; ok { + name := d.Name() + if d.IsDir() { + // QNAP thumbnail caches + if name == ".@__thumb" { + return filepath.SkipDir + } + return nil + } + // AppleDouble resource forks + if strings.HasPrefix(name, "._") { + return nil + } + if _, ok := exts[strings.ToLower(filepath.Ext(path))]; ok { out <- path } return nil @@ -112,19 +170,23 @@ func Parse(in <-chan string) <-chan Media { } // MissingLink detects if the values coming from medias is a duplicate file -// rather than a hardlink to the content store. +// rather than a hardlink to the content store. Files whose content is not in +// the store are reported on errs and never sent on, since there is nothing to +// link them to. func MissingLink(medias <-chan Media, root string) (<-chan Media, <-chan error) { out := make(chan Media) errs := make(chan error) go func() { for m := range medias { - var d, c os.FileInfo - var err error - if d, err = os.Stat(m.Path); err != nil { + d, err := os.Stat(m.Path) + if err != nil { errs <- err + continue } - if c, err = os.Stat(m.Content(root)); err != nil { - errs <- err + c, err := os.Stat(m.Content(root)) + if err != nil { + errs <- fmt.Errorf("%q has no content in store: %v", m.Path, err) + continue } if !os.SameFile(d, c) { out <- m @@ -136,6 +198,24 @@ func MissingLink(medias <-chan Media, root string) (<-chan Media, <-chan error) return out, errs } +// Relink atomically replaces m.Path with a hardlink to its content in the +// store, so m.Path exists at every moment. +func Relink(m Media, root string) error { + content := m.Content(root) + if _, err := os.Stat(content); err != nil { + return fmt.Errorf("refusing to relink %q: %v", m.Path, err) + } + tmp := filepath.Join(filepath.Dir(m.Path), fmt.Sprintf(".arrange-%d-%s", os.Getpid(), filepath.Base(m.Path))) + if err := os.Link(content, tmp); err != nil { + return fmt.Errorf("couldn't link %q: %v", tmp, err) + } + if err := os.Rename(tmp, m.Path); err != nil { + os.Remove(tmp) + return fmt.Errorf("couldn't replace %q: %v", m.Path, err) + } + return nil +} + // Move calls Move on each Media on input chan. It is the first step in the // pipeline after fan-in. func Move(in <-chan Media, root string) <-chan error { @@ -153,8 +233,11 @@ func Move(in <-chan Media, root string) <-chan error { func ParseFile(path string) (Media, error) { ext := strings.ToLower(filepath.Ext(path)) var r Media - hash := md5.New() - var t time.Time + + k, ok := exts[ext] + if !ok { + return r, NotMedia{path} + } f, err := os.Open(path) if err != nil { @@ -162,65 +245,43 @@ func ParseFile(path string) (Media, error) { } defer f.Close() - switch ext { - default: + // make sure it is what it says it is + switch k { + case kindJPEG: + _, err = jpeg.DecodeConfig(f) + case kindPNG: + _, err = png.DecodeConfig(f) + case kindGIF: + _, err = gif.DecodeConfig(f) + } + if err != nil { return r, NotMedia{path} - case ".jpg", ".jpeg": - if _, err := jpeg.DecodeConfig(f); err != nil { - return r, NotMedia{path} - } - if _, err := f.Seek(0, 0); err != nil { - return r, fmt.Errorf("couldn't seek back in file: %v", err) - } + } - // try a few things for a time value - { - success := false - if t, err = parseExif(f); err == nil { - success = true - } - if !success { - t, err = mtime(path) - } - if err != nil { - return r, fmt.Errorf("unable to calculate reasonble time for jpg %q: %v", path, err) + // try a few things for a time value, falling back to mtime + var t time.Time + switch k { + case kindJPEG, kindPNG, kindStill: + t = exifTime(f, k == kindJPEG) + case kindQuickTime: + if _, err := f.Seek(0, io.SeekStart); err == nil { + if qt, err := quickTimeCreated(f); err == nil { + t = qt } } - case ".png": - if _, err := png.DecodeConfig(f); err != nil { - return r, NotMedia{path} - } - if _, err := f.Seek(0, 0); err != nil { - return r, fmt.Errorf("couldn't seek back in file: %v", err) - } - - t, err = mtime(path) - if err != nil { - return r, fmt.Errorf("unable to calculate reasonble time for media %q: %v", path, err) - } - case ".gif": - if _, err := gif.DecodeConfig(f); err != nil { - return r, NotMedia{path} - } - if _, err := f.Seek(0, 0); err != nil { - return r, fmt.Errorf("couldn't seek back in file: %v", err) - } - - t, err = mtime(path) - if err != nil { - return r, fmt.Errorf("unable to calculate reasonble time for media %q: %v", path, err) - } - case ".mov", ".mp4", ".m4v", ".avi": - t, err = mtime(path) - if err != nil { - return r, fmt.Errorf("unable to calculate reasonble time for media %q: %v", path, err) + } + if t.IsZero() { + if t, err = mtime(path); err != nil { + return r, fmt.Errorf("unable to calculate reasonable time for media %q: %v", path, err) } } - if _, err := f.Seek(0, 0); err != nil { + if _, err := f.Seek(0, io.SeekStart); err != nil { return r, fmt.Errorf("couldn't seek back in file: %v", err) } - if _, err := io.Copy(hash, f); err != nil { + hash := NewHash() + n, err := io.Copy(hash, f) + if err != nil { return r, fmt.Errorf("problem calculating checksum on %q: %v", path, err) } r = Media{ @@ -228,6 +289,7 @@ func ParseFile(path string) (Media, error) { Hash: fmt.Sprintf("%x", hash.Sum(nil)), Extension: ext, Time: t, + Size: n, } return r, nil } diff --git a/arrange_test.go b/arrange_test.go index 5306e65..6e8b8f4 100644 --- a/arrange_test.go +++ b/arrange_test.go @@ -1,6 +1,7 @@ package arrange import ( + "crypto/md5" "fmt" "io/ioutil" "os" @@ -9,7 +10,16 @@ import ( "time" ) +// useMD5 makes a test build an old-style md5 store, which these tests' fixed +// content paths and hashes assume. +func useMD5(t *testing.T) { + old := NewHash + NewHash = md5.New + t.Cleanup(func() { NewHash = old }) +} + func TestFileMove(t *testing.T) { + useMD5(t) wd, err := os.Getwd() if err != nil { t.Fatal(err) @@ -139,6 +149,7 @@ func TestBadFiles(t *testing.T) { } func TestMoveCollision(t *testing.T) { + useMD5(t) wd, err := os.Getwd() if err != nil { t.Fatal(err) diff --git a/cmd/am/arrange.go b/cmd/am/arrange.go index 90420dc..e28e065 100644 --- a/cmd/am/arrange.go +++ b/cmd/am/arrange.go @@ -3,14 +3,18 @@ package main import ( "fmt" "log" + "os" + "path/filepath" "runtime" "mcquay.me/arrange" ) func arr(indir, outdir string) error { - if err := arrange.PrepOutput(outdir); err != nil { - return fmt.Errorf("problem creating directory structure: %v", err) + if !*dryRun { + if err := arrange.PrepOutput(outdir); err != nil { + return fmt.Errorf("problem creating directory structure: %v", err) + } } work := arrange.Source(indir) @@ -25,23 +29,41 @@ func arr(indir, outdir string) error { streams = append(streams, arrange.Parse(work)) } - st := stats{} - for err := range arrange.Move(arrange.Merge(streams), outdir) { - st.total++ - if err != nil { - switch err.(type) { - case arrange.Dup: - st.dupes++ - default: - log.Printf("%+v", err) + st := newStats() + // in a dry run nothing lands in the store, so remember what would have + seen := map[string]bool{} + for m := range arrange.Merge(streams) { + if *dryRun { + content := m.Content(outdir) + _, err := os.Stat(content) + dup := seen[m.Hash] || err == nil + seen[m.Hash] = true + action := "new" + if dup { + action = "dup" } - } else { - st.moved++ + date := filepath.Join(outdir, "date", fmt.Sprintf("%04d", m.Time.Year()), fmt.Sprintf("%02d", m.Time.Month())) + fmt.Printf("%s\t%s\t%s\t%s\n", action, m.Path, content, date) + st.add(m, dup) + continue + } + + err := m.Move(outdir) + switch err.(type) { + case nil: + st.add(m, false) + case arrange.Dup: + st.add(m, true) + default: + st.errors++ + log.Printf("%+v", err) } } - log.Printf("dupes: %+v", st.dupes) - log.Printf("moved: %+v", st.moved) - log.Printf("total: %+v", st.total) + verb := "moved" + if *dryRun { + verb = "would move" + } + st.write(os.Stderr, verb) return nil } diff --git a/cmd/am/clean.go b/cmd/am/clean.go index 773a4fa..2da40e5 100644 --- a/cmd/am/clean.go +++ b/cmd/am/clean.go @@ -1,6 +1,7 @@ package main import ( + "errors" "fmt" "log" "os" @@ -32,25 +33,41 @@ func clean(dir string) error { errs = append(errs, e) } - var err error + var problems int + done := make(chan bool) go func() { for e := range eMerge(errs) { log.Printf("%+v", e) - err = fmt.Errorf("%v, %v", err, e) + problems++ } + close(done) }() + var relinked, failed int for m := range arrange.Merge(streams) { - log.Printf("%q > %q", m.Path, m.Content(dir)) - if err := os.Remove(m.Path); err != nil { - log.Printf("%+v", err) + if *dryRun { + fmt.Printf("relink\t%s\t%s\n", m.Path, m.Content(dir)) + relinked++ + continue } - if err := os.Link(m.Content(dir), m.Path); err != nil { + if err := arrange.Relink(m, dir); err != nil { log.Printf("%+v", err) + failed++ + continue } + relinked++ } + <-done - return err + verb := "relinked" + if *dryRun { + verb = "would relink" + } + log.Printf("%s: %d, failed: %d, problems: %d", verb, relinked, failed, problems) + if problems+failed > 0 { + return errors.New("some files could not be checked or relinked; see log") + } + return nil } func eMerge(cs []<-chan error) <-chan error { diff --git a/cmd/am/main.go b/cmd/am/main.go index 855e0c9..a6784f7 100644 --- a/cmd/am/main.go +++ b/cmd/am/main.go @@ -1,24 +1,25 @@ package main import ( + "crypto/md5" + "crypto/sha256" "flag" "fmt" "log" "os" + + "mcquay.me/arrange" ) -const usage = "am [flags]" -const arrUsage = "am arr [-h|-cores=N] " -const cleanUsage = "am clean [-h|-cores=N] " +const usage = "am [flags]" +const arrUsage = "am arr [-h|-n|-hash=sha256|md5|-cores=N] " +const cleanUsage = "am clean [-h|-n|-cores=N] " +const verifyUsage = "am verify [-h|-cores=N] " const metaUsage = "am meta [-h|-cores=N] ... " -type stats struct { - total int - dupes int - moved int -} - var cores = flag.Int("cores", 0, "how many threads to use") +var dryRun = flag.Bool("n", false, "dry run: print the plan as tab-separated lines, change nothing") +var hashName = flag.String("hash", "sha256", "content-address hash: sha256, or md5 to add to a store built by older versions") func main() { if len(os.Args) < 2 { @@ -31,6 +32,16 @@ func main() { flag.Parse() log.SetFlags(log.Lshortfile) + switch *hashName { + case "sha256": + arrange.NewHash = sha256.New + case "md5": + arrange.NewHash = md5.New + default: + fmt.Fprintf(os.Stderr, "unsupported hash %q (supported: sha256, md5)\n", *hashName) + os.Exit(1) + } + switch sub { case "ar", "arr", "arrange": args := flag.Args() @@ -54,6 +65,16 @@ func main() { fmt.Fprintf(os.Stderr, "problem cleaning: %v\n", err) os.Exit(1) } + case "v", "verify": + args := flag.Args() + if len(args) != 1 { + fmt.Fprintf(os.Stderr, "%s\n", verifyUsage) + os.Exit(1) + } + if err := verify(args[0]); err != nil { + fmt.Fprintf(os.Stderr, "problem verifying: %v\n", err) + os.Exit(1) + } case "m", "meta": args := flag.Args() if len(args) < 1 { diff --git a/cmd/am/meta.go b/cmd/am/meta.go index 54d6d12..9cdc67c 100644 --- a/cmd/am/meta.go +++ b/cmd/am/meta.go @@ -26,9 +26,9 @@ func meta(files []string) { pf, err := arrange.ParseFile(pth) if err != nil { log.Printf("%+v", err) + } else { + fc <- pf } - - fc <- pf <-s wg.Done() }(f) diff --git a/cmd/am/stats.go b/cmd/am/stats.go new file mode 100644 index 0000000..a882a86 --- /dev/null +++ b/cmd/am/stats.go @@ -0,0 +1,105 @@ +package main + +import ( + "fmt" + "io" + "sort" + "strings" + "text/tabwriter" + + "mcquay.me/arrange" +) + +// stats tallies a run without recording any file names, so the summary is +// safe to share. +type stats struct { + total int + dupes int + moved int + errors int + bytes int64 + + ext map[string]*tally + year map[int]*tally +} + +type tally struct { + files, dupes int + bytes int64 +} + +func newStats() *stats { + return &stats{ext: map[string]*tally{}, year: map[int]*tally{}} +} + +func (s *stats) add(m arrange.Media, dup bool) { + s.total++ + s.bytes += m.Size + e := s.ext[m.Extension] + if e == nil { + e = &tally{} + s.ext[m.Extension] = e + } + y := s.year[m.Time.Year()] + if y == nil { + y = &tally{} + s.year[m.Time.Year()] = y + } + e.files++ + e.bytes += m.Size + y.files++ + y.bytes += m.Size + if dup { + s.dupes++ + e.dupes++ + y.dupes++ + } else { + s.moved++ + } +} + +func (s *stats) write(w io.Writer, verb string) { + fmt.Fprintf(w, "total: %d files, %s\n", s.total, human(s.bytes)) + fmt.Fprintf(w, "%s: %d\n", verb, s.moved) + fmt.Fprintf(w, "dupes: %d\n", s.dupes) + fmt.Fprintf(w, "errors: %d\n", s.errors) + + tw := tabwriter.NewWriter(w, 0, 0, 2, ' ', tabwriter.AlignRight) + fmt.Fprintln(tw, "\text\tfiles\tdupes\tsize\t") + exts := make([]string, 0, len(s.ext)) + for k := range s.ext { + exts = append(exts, k) + } + sort.Strings(exts) + for _, k := range exts { + t := s.ext[k] + fmt.Fprintf(tw, "\t%s\t%d\t%d\t%s\t\n", strings.TrimPrefix(k, "."), t.files, t.dupes, human(t.bytes)) + } + tw.Flush() + + tw = tabwriter.NewWriter(w, 0, 0, 2, ' ', tabwriter.AlignRight) + fmt.Fprintln(tw, "\tyear\tfiles\tdupes\tsize\t") + years := make([]int, 0, len(s.year)) + for k := range s.year { + years = append(years, k) + } + sort.Ints(years) + for _, k := range years { + t := s.year[k] + fmt.Fprintf(tw, "\t%d\t%d\t%d\t%s\t\n", k, t.files, t.dupes, human(t.bytes)) + } + tw.Flush() +} + +func human(n int64) string { + const unit = 1024 + if n < unit { + return fmt.Sprintf("%dB", n) + } + div, exp := int64(unit), 0 + for m := n / unit; m >= unit; m /= unit { + div *= unit + exp++ + } + return fmt.Sprintf("%.1f%ciB", float64(n)/float64(div), "KMGTPE"[exp]) +} diff --git a/cmd/am/verify.go b/cmd/am/verify.go new file mode 100644 index 0000000..b4b4113 --- /dev/null +++ b/cmd/am/verify.go @@ -0,0 +1,37 @@ +package main + +import ( + "fmt" + "log" + "os" + "path/filepath" + "runtime" + + "mcquay.me/arrange" +) + +// verify rehashes the content store. It only reads. +func verify(dir string) error { + if _, err := os.Stat(filepath.Join(dir, "content")); err != nil { + return fmt.Errorf("couldn't find 'content' dir in %q: %v", dir, err) + } + + workers := runtime.NumCPU() + if *cores != 0 { + workers = *cores + } + + counts := map[string]int{} + problems, checked := arrange.Verify(dir, workers) + for p := range problems { + counts[p.Kind]++ + log.Printf("%v", p) + } + + log.Printf("checked: %d, corrupt: %d, orphan: %d, stale: %d, errors: %d", + checked(), counts["corrupt"], counts["orphan"], counts["stale"], counts["error"]) + if counts["corrupt"]+counts["error"] > 0 { + return fmt.Errorf("store has problems") + } + return nil +} diff --git a/go.mod b/go.mod index 1f8635b..53ed337 100644 --- a/go.mod +++ b/go.mod @@ -1,5 +1,12 @@ module mcquay.me/arrange -go 1.24 +go 1.27.0 require github.com/rwcarlsen/goexif v0.0.0-20190401172101-9e8deecbddbd + +require ( + github.com/evanoberholster/imagemeta v1.1.0 // indirect + github.com/philhofer/fwd v1.2.0 // indirect + github.com/pkg/errors v0.9.1 // indirect + github.com/tinylib/msgp v1.6.3 // indirect +) diff --git a/go.sum b/go.sum index 4f6df19..ae2609f 100644 --- a/go.sum +++ b/go.sum @@ -1,2 +1,10 @@ +github.com/evanoberholster/imagemeta v1.1.0 h1:0iBtgVxLORZTZAlKxRcNodBmjMfHCSFwUh8Asmi83oI= +github.com/evanoberholster/imagemeta v1.1.0/go.mod h1:nmf6le+qSyoRAXgp2psPbtfkxcEgf/AZGgai9pnN8d0= +github.com/philhofer/fwd v1.2.0 h1:e6DnBTl7vGY+Gz322/ASL4Gyp1FspeMvx1RNDoToZuM= +github.com/philhofer/fwd v1.2.0/go.mod h1:RqIHx9QI14HlwKwm98g9Re5prTQ6LdeRQn+gXJFxsJM= +github.com/pkg/errors v0.9.1 h1:FEBLx1zS214owpjy7qsBeixbURkuhQAwrK5UwLGTwt4= +github.com/pkg/errors v0.9.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0= github.com/rwcarlsen/goexif v0.0.0-20190401172101-9e8deecbddbd h1:CmH9+J6ZSsIjUK3dcGsnCnO41eRBOnY12zwkn5qVwgc= github.com/rwcarlsen/goexif v0.0.0-20190401172101-9e8deecbddbd/go.mod h1:hPqNNc0+uJM6H+SuU8sEs5K5IQeKccPqeSjfgcKGgPk= +github.com/tinylib/msgp v1.6.3 h1:bCSxiTz386UTgyT1i0MSCvdbWjVW+8sG3PjkGsZQt4s= +github.com/tinylib/msgp v1.6.3/go.mod h1:RSp0LW9oSxFut3KzESt5Voq4GVWyS+PSulT77roAqEA= diff --git a/image.go b/image.go index 8a67e17..4344826 100644 --- a/image.go +++ b/image.go @@ -3,11 +3,53 @@ package arrange import ( "fmt" "io" + "log/slog" "time" + "github.com/evanoberholster/imagemeta" "github.com/rwcarlsen/goexif/exif" ) +func init() { + imagemeta.SetLogger(io.Discard, slog.LevelError) +} + +// exifTime returns the capture time recorded in f, or the zero time if it +// can't find a believable one. +// +// imagemeta handles HEIC and camera RAW; goexif is kept as a fallback for +// jpegs because it copes with some damaged exif that imagemeta rejects. +func exifTime(f io.ReadSeeker, jpeg bool) time.Time { + if _, err := f.Seek(0, io.SeekStart); err != nil { + return time.Time{} + } + if e, err := imagemeta.Decode(f); err == nil { + if t := e.SelectedDate(); plausible(t) { + // exif dates without an offset are camera wall-clock time, + // which imagemeta labels UTC; read them as local like goexif. + if t.Location() == time.UTC { + t = time.Date(t.Year(), t.Month(), t.Day(), t.Hour(), t.Minute(), t.Second(), t.Nanosecond(), time.Local) + } + return t + } + } + if !jpeg { + return time.Time{} + } + if _, err := f.Seek(0, io.SeekStart); err != nil { + return time.Time{} + } + if t, err := parseExif(f); err == nil && plausible(t) { + return t + } + return time.Time{} +} + +// plausible rejects zero and placeholder dates (e.g. "0000:00:00 00:00:00"). +func plausible(t time.Time) bool { + return !t.IsZero() && t.Year() >= 1900 +} + func parseExif(f io.Reader) (time.Time, error) { ti := time.Time{} x, err := exif.Decode(f) @@ -16,6 +58,9 @@ func parseExif(f io.Reader) (time.Time, error) { return ti, err } } + if x == nil { + return ti, fmt.Errorf("no exif: %v", err) + } tm, err := x.DateTime() if err != nil { return ti, fmt.Errorf("no datetime in an ostensibly valid exif %v", err) diff --git a/media.go b/media.go index 691552b..bc15991 100644 --- a/media.go +++ b/media.go @@ -1,8 +1,10 @@ package arrange import ( + "errors" "fmt" "io" + "io/fs" "os" "path/filepath" "time" @@ -14,35 +16,27 @@ type Media struct { Hash string Extension string Time time.Time + Size int64 } // Move is called to push Media into its final destination, by content address // and by date. +// +// The content file is written under a temporary name, checked against m.Hash, +// synced, and only then linked into place, so an interrupted run never leaves +// a truncated file in the store looking like a dup. func (m Media) Move(root string) error { - f, err := os.Open(m.Path) - if err != nil { - return fmt.Errorf("problem opening file %q: %v", m.Path, err) - } - defer f.Close() - content := m.Content(root) if _, err := os.Stat(content); !os.IsNotExist(err) { return Dup{content} } - out, err := os.Create(content) - if err != nil { - return fmt.Errorf("could not create output file: %v", err) - } - defer out.Close() - - if _, err := io.Copy(out, f); err != nil { - return fmt.Errorf("trouble copying file: %v", err) - } - - if err := os.Chtimes(content, time.Now(), m.Time); err != nil { - return fmt.Errorf("couldn't chtimes for %q: %v", content, err) + if err := m.store(content); err != nil { + if errors.Is(err, fs.ErrExist) { + return Dup{content} + } + return err } year := fmt.Sprintf("%04d", m.Time.Year()) @@ -56,16 +50,54 @@ func (m Media) Move(root string) error { date := filepath.Join(root, "date", year, month, ts) name := date + m.Extension for i := 0; i < 10000; i++ { - if _, err := os.Stat(name); os.IsNotExist(err) { - break + err := os.Link(content, name) + if !errors.Is(err, fs.ErrExist) { + return err } name = fmt.Sprintf("%s_%04d%s", date, i, m.Extension) } + return fmt.Errorf("too many files at %q", date) +} - // TODO: or maybe symlinking? (issue #2) - // rel := filepath.Join("..", "..", "..", "content", j.hash[:2], j.hash[2:]+m.Extension) - // return os.Symlink(rel, name) - return os.Link(content, name) +// store copies m.Path to content via a verified temporary file. +func (m Media) store(content string) error { + f, err := os.Open(m.Path) + if err != nil { + return fmt.Errorf("problem opening file %q: %v", m.Path, err) + } + defer f.Close() + + tmp, err := os.CreateTemp(filepath.Dir(content), ".tmp-") + if err != nil { + return fmt.Errorf("could not create output file: %v", err) + } + defer os.Remove(tmp.Name()) + + hash := NewHash() + if _, err := io.Copy(io.MultiWriter(tmp, hash), f); err != nil { + tmp.Close() + return fmt.Errorf("trouble copying file: %v", err) + } + if got := fmt.Sprintf("%x", hash.Sum(nil)); got != m.Hash { + tmp.Close() + return fmt.Errorf("%q changed while arranging: hashed %s, copied %s", m.Path, m.Hash, got) + } + if err := tmp.Sync(); err != nil { + tmp.Close() + return fmt.Errorf("couldn't sync %q: %v", tmp.Name(), err) + } + if err := tmp.Close(); err != nil { + return fmt.Errorf("couldn't close %q: %v", tmp.Name(), err) + } + if err := os.Chmod(tmp.Name(), 0644); err != nil { + return fmt.Errorf("couldn't chmod %q: %v", tmp.Name(), err) + } + if err := os.Chtimes(tmp.Name(), time.Now(), m.Time); err != nil { + return fmt.Errorf("couldn't chtimes for %q: %v", tmp.Name(), err) + } + // link, not rename: it fails rather than clobbers if content appeared + // in the meantime. + return os.Link(tmp.Name(), content) } // Content returns the content-address path starting at root. diff --git a/quicktime.go b/quicktime.go new file mode 100644 index 0000000..ab7c25f --- /dev/null +++ b/quicktime.go @@ -0,0 +1,92 @@ +package arrange + +import ( + "encoding/binary" + "errors" + "fmt" + "io" + "time" +) + +// epoch1904 is where QuickTime/MP4 timestamps count from. +var epoch1904 = time.Date(1904, 1, 1, 0, 0, 0, 0, time.UTC) + +var errNoAtom = errors.New("atom not found") + +// quickTimeCreated reads the creation time from the movie header (moov/mvhd) +// of a QuickTime or ISO-BMFF (mp4, m4v, 3gp) file. +func quickTimeCreated(r io.ReadSeeker) (time.Time, error) { + end, err := r.Seek(0, io.SeekEnd) + if err != nil { + return time.Time{}, err + } + moov, moovEnd, err := findAtom(r, 0, end, "moov") + if err != nil { + return time.Time{}, err + } + mvhd, _, err := findAtom(r, moov, moovEnd, "mvhd") + if err != nil { + return time.Time{}, err + } + if _, err := r.Seek(mvhd, io.SeekStart); err != nil { + return time.Time{}, err + } + + // version(1) flags(3) creation_time(4 or 8) + var hdr [12]byte + if _, err := io.ReadFull(r, hdr[:]); err != nil { + return time.Time{}, fmt.Errorf("short mvhd: %v", err) + } + var secs uint64 + switch hdr[0] { + case 0: + secs = uint64(binary.BigEndian.Uint32(hdr[4:8])) + case 1: + secs = binary.BigEndian.Uint64(hdr[4:12]) + default: + return time.Time{}, fmt.Errorf("unknown mvhd version %d", hdr[0]) + } + if secs == 0 { + return time.Time{}, errors.New("mvhd has no creation time") + } + t := epoch1904.Add(time.Duration(secs) * time.Second) + if !plausible(t) || t.After(time.Now().Add(24*time.Hour)) { + return time.Time{}, fmt.Errorf("implausible mvhd creation time %v", t) + } + return t, nil +} + +// findAtom scans the sibling atoms in [start, end) for one named typ, and +// returns the offsets of its payload. +func findAtom(r io.ReadSeeker, start, end int64, typ string) (int64, int64, error) { + for off := start; off+8 <= end; { + if _, err := r.Seek(off, io.SeekStart); err != nil { + return 0, 0, err + } + var hdr [16]byte + if _, err := io.ReadFull(r, hdr[:8]); err != nil { + return 0, 0, err + } + size := int64(binary.BigEndian.Uint32(hdr[:4])) + name := string(hdr[4:8]) + body := off + 8 + switch size { + case 0: // runs to the end of the container + size = end - off + case 1: // 64-bit size follows the name + if _, err := io.ReadFull(r, hdr[8:16]); err != nil { + return 0, 0, err + } + size = int64(binary.BigEndian.Uint64(hdr[8:16])) + body += 8 + } + if size < body-off || off+size > end { + return 0, 0, fmt.Errorf("bad size %d for atom %q at %d", size, name, off) + } + if name == typ { + return body, off + size, nil + } + off += size + } + return 0, 0, errNoAtom +} diff --git a/revive_test.go b/revive_test.go new file mode 100644 index 0000000..8472dcd --- /dev/null +++ b/revive_test.go @@ -0,0 +1,290 @@ +package arrange + +import ( + "bytes" + "encoding/binary" + "os" + "path/filepath" + "strings" + "testing" + "time" +) + +// atom builds a QuickTime atom with a 32-bit size. +func atom(typ string, body ...[]byte) []byte { + b := bytes.Join(body, nil) + out := make([]byte, 8, 8+len(b)) + binary.BigEndian.PutUint32(out, uint32(8+len(b))) + copy(out[4:], typ) + return append(out, b...) +} + +// mvhd builds a movie header body of the given version with creation time t. +func mvhd(version byte, t time.Time) []byte { + secs := uint64(t.Sub(epoch1904) / time.Second) + if version == 0 { + b := make([]byte, 100) + binary.BigEndian.PutUint32(b[4:], uint32(secs)) + return b + } + b := make([]byte, 112) + b[0] = 1 + binary.BigEndian.PutUint64(b[4:], secs) + return b +} + +func TestQuickTimeCreated(t *testing.T) { + when := time.Date(2019, 7, 4, 20, 15, 0, 0, time.UTC) + + // 64-bit size atom: size field 1, then the real size + big := make([]byte, 16+4) + binary.BigEndian.PutUint32(big, 1) + copy(big[4:], "free") + binary.BigEndian.PutUint64(big[8:], uint64(len(big))) + + tests := []struct { + name string + file []byte + want time.Time + ok bool + }{ + {"v0", bytes.Join([][]byte{atom("ftyp", []byte("qt ")), atom("moov", atom("mvhd", mvhd(0, when)))}, nil), when, true}, + {"v1", bytes.Join([][]byte{atom("ftyp", []byte("isom")), atom("mdat", make([]byte, 64)), atom("moov", atom("trak"), atom("mvhd", mvhd(1, when)))}, nil), when, true}, + {"largesize", bytes.Join([][]byte{big, atom("moov", atom("mvhd", mvhd(0, when)))}, nil), when, true}, + {"zero time", atom("moov", atom("mvhd", mvhd(0, epoch1904))), time.Time{}, false}, + {"no moov", atom("ftyp", []byte("isom")), time.Time{}, false}, + {"garbage", []byte("a\n"), time.Time{}, false}, + {"lying size", append(atom("moov", atom("mvhd", mvhd(0, when)))[:4], []byte("moov")...), time.Time{}, false}, + } + for _, test := range tests { + got, err := quickTimeCreated(bytes.NewReader(test.file)) + if (err == nil) != test.ok { + t.Errorf("%s: err = %v, want ok=%v", test.name, err, test.ok) + continue + } + if test.ok && !got.Equal(test.want) { + t.Errorf("%s: got %v, want %v", test.name, got, test.want) + } + } +} + +func TestParseQuickTimeDate(t *testing.T) { + when := time.Date(2019, 7, 4, 20, 15, 0, 0, time.UTC) + p := filepath.Join(t.TempDir(), "clip.MP4") + if err := os.WriteFile(p, atom("moov", atom("mvhd", mvhd(0, when))), 0644); err != nil { + t.Fatal(err) + } + m, err := ParseFile(p) + if err != nil { + t.Fatal(err) + } + if !m.Time.Equal(when) { + t.Errorf("got %v, want %v from mvhd", m.Time, when) + } + if m.Extension != ".mp4" { + t.Errorf("extension %q, want .mp4", m.Extension) + } +} + +func TestParseHEIC(t *testing.T) { + m, err := ParseFile(filepath.Join("testdata", "exif.heic")) + if err != nil { + t.Fatal(err) + } + want := time.Date(2006, 3, 27, 17, 19, 27, 0, time.Local) + if !m.Time.Equal(want) { + t.Errorf("got %v, want %v", m.Time, want) + } + if len(m.Hash) != 64 { + t.Errorf("hash %q isn't sha256", m.Hash) + } +} + +func TestSourceSkips(t *testing.T) { + root := t.TempDir() + for _, p := range []string{ + "keep.jpg", + "sub/KEEP.HEIC", + "._resource-fork.jpg", + ".@__thumb/thumb.jpg", + "notes.txt", + } { + full := filepath.Join(root, p) + if err := os.MkdirAll(filepath.Dir(full), 0755); err != nil { + t.Fatal(err) + } + if err := os.WriteFile(full, nil, 0644); err != nil { + t.Fatal(err) + } + } + unreadable := filepath.Join(root, "locked") + if err := os.Mkdir(unreadable, 0); err != nil { + t.Fatal(err) + } + defer os.Chmod(unreadable, 0755) + + var got []string + for p := range Source(root) { + rel, _ := filepath.Rel(root, p) + got = append(got, rel) + } + if want := "keep.jpg sub/KEEP.HEIC"; strings.Join(got, " ") != want { + t.Errorf("got %q, want %q", got, want) + } +} + +// arranged returns a store with one file arranged into it, and that Media. +func arranged(t *testing.T) (string, Media) { + t.Helper() + root := t.TempDir() + if err := PrepOutput(root); err != nil { + t.Fatal(err) + } + m, err := ParseFile(filepath.Join("testdata", "lenna.png")) + if err != nil { + t.Fatal(err) + } + if err := m.Move(root); err != nil { + t.Fatal(err) + } + return root, m +} + +func dated(t *testing.T, root string) []string { + t.Helper() + var out []string + for p := range Source(filepath.Join(root, "date")) { + out = append(out, p) + } + return out +} + +// The old clean deleted date files whose content was missing from the store, +// then failed to relink them, losing the file. +func TestCleanKeepsFilesMissingFromStore(t *testing.T) { + root, m := arranged(t) + d := dated(t, root) + if len(d) != 1 { + t.Fatalf("expected one dated file, got %v", d) + } + if err := os.Remove(m.Content(root)); err != nil { + t.Fatal(err) + } + + pm, err := ParseFile(d[0]) + if err != nil { + t.Fatal(err) + } + in := make(chan Media, 1) + in <- pm + close(in) + out, errs := MissingLink(in, root) + var nerr int + go func() { + for range errs { + nerr++ + } + }() + for m := range out { + t.Errorf("MissingLink sent %q on for relinking with no content", m.Path) + } + if err := Relink(pm, root); err == nil { + t.Error("Relink should refuse when content is missing") + } + if _, err := os.Stat(d[0]); err != nil { + t.Errorf("dated file is gone: %v", err) + } +} + +func TestRelinkReplacesCopy(t *testing.T) { + root, m := arranged(t) + d := dated(t, root)[0] + + // break the hardlink: replace the dated file with an identical copy + b, err := os.ReadFile(d) + if err != nil { + t.Fatal(err) + } + if err := os.Remove(d); err != nil { + t.Fatal(err) + } + if err := os.WriteFile(d, b, 0644); err != nil { + t.Fatal(err) + } + + pm, err := ParseFile(d) + if err != nil { + t.Fatal(err) + } + if err := Relink(pm, root); err != nil { + t.Fatal(err) + } + a, _ := os.Stat(d) + c, _ := os.Stat(m.Content(root)) + if !os.SameFile(a, c) { + t.Error("dated file isn't a hardlink to content after Relink") + } + if left, _ := filepath.Glob(filepath.Join(filepath.Dir(d), ".arrange-*")); len(left) > 0 { + t.Errorf("temp files left behind: %v", left) + } +} + +func TestMoveVerifiesHash(t *testing.T) { + root := t.TempDir() + if err := PrepOutput(root); err != nil { + t.Fatal(err) + } + m, err := ParseFile(filepath.Join("testdata", "lenna.png")) + if err != nil { + t.Fatal(err) + } + // as if the file changed between hashing and copying + m.Hash = strings.Repeat("ab", 32) + if err := m.Move(root); err == nil { + t.Fatal("Move should fail when the copy doesn't match the hash") + } + left, _ := filepath.Glob(filepath.Join(root, "content", "ab", "*")) + hidden, _ := filepath.Glob(filepath.Join(root, "content", "ab", ".*")) + if len(left)+len(hidden) > 0 { + t.Errorf("store not clean after failed move: %v %v", left, hidden) + } + if err := m.Move(root); err == nil { + t.Fatal("a second try should fail too, not be called a dup") + } +} + +func TestVerify(t *testing.T) { + root, m := arranged(t) + + problems := func() map[string]int { + out := map[string]int{} + ps, checked := Verify(root, 2) + for p := range ps { + out[p.Kind]++ + } + out["checked"] = checked() + return out + } + + if got := problems(); got["checked"] != 1 || len(got) != 1 { + t.Fatalf("healthy store: %v", got) + } + + // orphan: content nothing links to + for _, d := range dated(t, root) { + os.Remove(d) + } + // stale: a temp file from a crashed run + os.WriteFile(filepath.Join(root, "content", "00", ".tmp-123"), []byte("x"), 0644) + if got := problems(); got["orphan"] != 1 || got["stale"] != 1 { + t.Errorf("want one orphan and one stale, got %v", got) + } + + // corrupt: bytes no longer match the name + if err := os.WriteFile(m.Content(root), []byte("bitrot"), 0644); err != nil { + t.Fatal(err) + } + if got := problems(); got["corrupt"] != 1 { + t.Errorf("want one corrupt, got %v", got) + } +} diff --git a/testdata/attribution.md b/testdata/attribution.md index e7b1413..68a017a 100644 --- a/testdata/attribution.md +++ b/testdata/attribution.md @@ -10,3 +10,8 @@ https://en.wikipedia.org/w/index.php?curid=20658476 By No machine-readable author provided. Webber assumed (based on copyright claims). [Public domain], via Wikimedia Commons + +# exif.heic + +exif-decode-error.jpg converted with `sips -s format heic -s formatOptions 10`; +keeps its 2006-03-27 EXIF date. diff --git a/testdata/exif.heic b/testdata/exif.heic new file mode 100644 index 0000000..a962f4f Binary files /dev/null and b/testdata/exif.heic differ diff --git a/verify.go b/verify.go new file mode 100644 index 0000000..0ae9701 --- /dev/null +++ b/verify.go @@ -0,0 +1,123 @@ +package arrange + +import ( + "fmt" + "io" + "io/fs" + "os" + "path/filepath" + "strings" + "sync" + "syscall" +) + +// Problem is something Verify found wrong with a file in the content store. +type Problem struct { + Path string + Kind string // "corrupt", "orphan", "stale", or "error" + Err error +} + +func (p Problem) Error() string { + if p.Err != nil { + return fmt.Sprintf("%s: %q: %v", p.Kind, p.Path, p.Err) + } + return fmt.Sprintf("%s: %q", p.Kind, p.Path) +} + +// Verify rehashes every file in root's content store with workers goroutines +// and reports any whose hash doesn't match its name (corrupt), that nothing in +// the date tree links to (orphan), or that a crashed run left behind (stale). +// It only reads. The returned func reports how many files were checked once +// the channel is drained. +func Verify(root string, workers int) (<-chan Problem, func() int) { + paths := make(chan string) + out := make(chan Problem) + var checked int + var mu sync.Mutex + + go func() { + err := filepath.WalkDir(filepath.Join(root, "content"), func(path string, d fs.DirEntry, err error) error { + if err != nil { + out <- Problem{Path: path, Kind: "error", Err: err} + return nil + } + if d.IsDir() { + return nil + } + if strings.HasPrefix(d.Name(), ".tmp-") { + out <- Problem{Path: path, Kind: "stale"} + return nil + } + paths <- path + return nil + }) + if err != nil { + out <- Problem{Path: root, Kind: "error", Err: err} + } + close(paths) + }() + + var wg sync.WaitGroup + wg.Add(workers) + for w := 0; w < workers; w++ { + go func() { + defer wg.Done() + for path := range paths { + if p, ok := verifyFile(path); !ok { + out <- p + } + mu.Lock() + checked++ + mu.Unlock() + } + }() + } + go func() { + wg.Wait() + close(out) + }() + + return out, func() int { + mu.Lock() + defer mu.Unlock() + return checked + } +} + +// verifyFile checks one content file; ok is false if p describes a problem. +func verifyFile(path string) (p Problem, ok bool) { + p.Path = path + base := filepath.Base(path) + hexname := filepath.Base(filepath.Dir(path)) + strings.TrimSuffix(base, filepath.Ext(base)) + newHash := HashByName(hexname) + if newHash == nil { + p.Kind, p.Err = "error", fmt.Errorf("not a content address") + return p, false + } + + f, err := os.Open(path) + if err != nil { + p.Kind, p.Err = "error", err + return p, false + } + defer f.Close() + + h := newHash() + if _, err := io.Copy(h, f); err != nil { + p.Kind, p.Err = "error", err + return p, false + } + if got := fmt.Sprintf("%x", h.Sum(nil)); got != hexname { + p.Kind, p.Err = "corrupt", fmt.Errorf("contents hash to %s", got) + return p, false + } + + if fi, err := f.Stat(); err == nil { + if st, ok := fi.Sys().(*syscall.Stat_t); ok && st.Nlink < 2 { + p.Kind = "orphan" + return p, false + } + } + return p, true +}