Skip to content

"rsync for cloud storage" - Google Drive, S3, Dropbox, Backblaze B2, One Drive, Swift, Hubic, Wasabi, Google Cloud Storage, Azure Blob, Azure Files, Yandex Files

sync: export --track-renames matching logic

Morax015f9cd127d8
diff --git a/fs/sync/sync.go b/fs/sync/sync.go
index 238d86601..e77bd50e5 100644
--- a/fs/sync/sync.go
+++ b/fs/sync/sync.go
@@ -19,6 +19,7 @@ import (
"github.com/rclone/rclone/fs/hash"
"github.com/rclone/rclone/fs/march"
"github.com/rclone/rclone/fs/operations"
+ "github.com/rclone/rclone/fs/sync/trackrenames"
"github.com/rclone/rclone/lib/errcount"
"github.com/rclone/rclone/lib/transform"
"golang.org/x/sync/errgroup"
@@ -54,7 +55,7 @@ type syncCopyMove struct {
deletersWg sync.WaitGroup // for delete before go routine
deleteFilesCh chan fs.Object // channel to receive deletes if delete before
trackRenames bool // set if we should do server-side renames
- trackRenamesStrategy trackRenamesStrategy // strategies used for tracking renames
+ trackRenamesStrategy trackrenames.Strategy // strategies used for tracking renames
dstFilesMu sync.Mutex // protect dstFiles
dstFiles map[string]fs.Object // dst files, always filled
srcFiles map[string]fs.Object // src files, only used if deleteBefore
@@ -76,8 +77,7 @@ type syncCopyMove struct {
fatalErr error // fatal error
commonHash hash.Type // common hash type between src and dst
modifyWindow time.Duration // modify window between fsrc, fdst
- renameMapMu sync.Mutex // mutex to protect the below
- renameMap map[string][]fs.Object // dst files by hash - only used by trackRenames
+ renameMatcher *trackrenames.Matcher // dst files indexed for trackRenames
renamerWg sync.WaitGroup // wait for renamers
toBeRenamed *pipe // renamers channel
trackRenamesWg sync.WaitGroup // wg for background track renames
@@ -108,26 +108,6 @@ type setDirModTime struct {
level int // the level of the directory, 0 is root
}
-type trackRenamesStrategy byte
-
-const (
- trackRenamesStrategyHash trackRenamesStrategy = 1 << iota
- trackRenamesStrategyModtime
- trackRenamesStrategyLeaf
-)
-
-func (strategy trackRenamesStrategy) hash() bool {
- return (strategy & trackRenamesStrategyHash) != 0
-}
-
-func (strategy trackRenamesStrategy) modTime() bool {
- return (strategy & trackRenamesStrategyModtime) != 0
-}
-
-func (strategy trackRenamesStrategy) leaf() bool {
- return (strategy & trackRenamesStrategyLeaf) != 0
-}
-
func newSyncCopyMove(ctx context.Context, fdst, fsrc fs.Fs, deleteMode fs.DeleteMode, DoMove bool, deleteEmptySrcDirs bool, copyEmptySrcDirs bool, allowOverlap bool) (*syncCopyMove, error) {
if (deleteMode != fs.DeleteModeOff || DoMove) && operations.OverlappingFilterCheck(ctx, fdst, fsrc) && !allowOverlap {
return nil, fserrors.FatalError(fs.ErrorOverlapping)
@@ -222,7 +202,7 @@ func newSyncCopyMove(ctx context.Context, fdst, fsrc fs.Fs, deleteMode fs.Delete
}
s.noTraverse = false
}
- s.trackRenamesStrategy, err = parseTrackRenamesStrategy(ci.TrackRenamesStrategy)
+ s.trackRenamesStrategy, err = trackrenames.ParseStrategy(ci.TrackRenamesStrategy)
if err != nil {
return nil, err
}
@@ -238,18 +218,11 @@ func newSyncCopyMove(ctx context.Context, fdst, fsrc fs.Fs, deleteMode fs.Delete
}
}
if s.trackRenames {
- // Don't track renames for remotes without server-side move support.
- if !operations.CanServerSideMove(fdst) {
- fs.Errorf(fdst, "Ignoring --track-renames as the destination does not support server-side move or copy")
- s.trackRenames = false
- }
- if s.trackRenamesStrategy.hash() && s.commonHash == hash.None {
- fs.Errorf(fdst, "Ignoring --track-renames as the source and destination do not have a common hash")
- s.trackRenames = false
- }
-
- if s.trackRenamesStrategy.modTime() && s.modifyWindow == fs.ModTimeNotSupported {
- fs.Errorf(fdst, "Ignoring --track-renames as either the source or destination do not support modtime")
+ commonHash, modifyWindow, unsupported := trackrenames.CheckCapabilities(ctx, fsrc, fdst, s.trackRenamesStrategy)
+ s.commonHash = commonHash
+ s.modifyWindow = modifyWindow
+ for _, reason := range unsupported {
+ fs.Errorf(fdst, "Ignoring --track-renames as %s", reason)
s.trackRenames = false
}
@@ -746,109 +719,6 @@ func (s *syncCopyMove) markParentNotEmpty(entry fs.DirEntry) {
}
}
-// parseTrackRenamesStrategy turns a config string into a trackRenamesStrategy
-func parseTrackRenamesStrategy(strategies string) (strategy trackRenamesStrategy, err error) {
- if len(strategies) == 0 {
- return strategy, nil
- }
- for s := range strings.SplitSeq(strategies, ",") {
- switch s {
- case "hash":
- strategy |= trackRenamesStrategyHash
- case "modtime":
- strategy |= trackRenamesStrategyModtime
- case "leaf":
- strategy |= trackRenamesStrategyLeaf
- case "size":
- // ignore
- default:
- return strategy, fmt.Errorf("unknown track renames strategy %q", s)
- }
- }
- return strategy, nil
-}
-
-// renameID makes a string with the size and the other identifiers of the requested rename strategies
-//
-// it may return an empty string in which case no hash could be made
-func (s *syncCopyMove) renameID(obj fs.Object, renamesStrategy trackRenamesStrategy, precision time.Duration) string {
- var builder strings.Builder
-
- fmt.Fprintf(&builder, "%d", obj.Size())
-
- if renamesStrategy.hash() {
- var err error
- hash, err := obj.Hash(s.ctx, s.commonHash)
- if err != nil {
- fs.Debugf(obj, "Hash failed: %v", err)
- return ""
- }
- if hash == "" {
- return ""
- }
-
- builder.WriteRune(',')
- builder.WriteString(hash)
- }
-
- // for renamesStrategy.modTime() we don't add to the hash but we check the times in
- // popRenameMap
-
- if renamesStrategy.leaf() {
- builder.WriteRune(',')
- builder.WriteString(path.Base(obj.Remote()))
- }
-
- return builder.String()
-}
-
-// pushRenameMap adds the object with hash to the rename map
-func (s *syncCopyMove) pushRenameMap(hash string, obj fs.Object) {
- s.renameMapMu.Lock()
- s.renameMap[hash] = append(s.renameMap[hash], obj)
- s.renameMapMu.Unlock()
-}
-
-// popRenameMap finds the object with hash and pop the first match from
-// renameMap or returns nil if not found.
-func (s *syncCopyMove) popRenameMap(hash string, src fs.Object) (dst fs.Object) {
- s.renameMapMu.Lock()
- defer s.renameMapMu.Unlock()
- dsts, ok := s.renameMap[hash]
- if ok && len(dsts) > 0 {
- // Element to remove
- i := 0
-
- // If using track renames strategy modtime then we need to check the modtimes here
- if s.trackRenamesStrategy.modTime() {
- i = -1
- srcModTime := src.ModTime(s.ctx)
- for j, dst := range dsts {
- dstModTime := dst.ModTime(s.ctx)
- dt := dstModTime.Sub(srcModTime)
- if dt < s.modifyWindow && dt > -s.modifyWindow {
- i = j
- break
- }
- }
- // If nothing matched then return nil
- if i < 0 {
- return nil
- }
- }
-
- // Remove the entry and return it
- dst = dsts[i]
- dsts = slices.Delete(dsts, i, i+1)
- if len(dsts) > 0 {
- s.renameMap[hash] = dsts
- } else {
- delete(s.renameMap, hash)
- }
- }
- return dst
-}
-
// makeRenameMap builds a map of the destination files by hash that
// match sizes in the slice of objects in s.renameCheck
func (s *syncCopyMove) makeRenameMap() {
@@ -865,7 +735,7 @@ func (s *syncCopyMove) makeRenameMap() {
go s.pumpMapToChan(s.dstFiles, in)
// now make a map of size,hash for all dstFiles
- s.renameMap = make(map[string][]fs.Object)
+ s.renameMatcher = trackrenames.NewMatcher(s.ctx, s.trackRenamesStrategy, s.commonHash, s.modifyWindow)
var wg sync.WaitGroup
wg.Add(s.ci.Checkers)
for range s.ci.Checkers {
@@ -875,12 +745,7 @@ func (s *syncCopyMove) makeRenameMap() {
// only create hash for dst fs.Object if its size could match
if _, found := possibleSizes[obj.Size()]; found {
tr := accounting.Stats(s.ctx).NewCheckingTransfer(obj, "renaming")
- hash := s.renameID(obj, s.trackRenamesStrategy, s.modifyWindow)
-
- if hash != "" {
- s.pushRenameMap(hash, obj)
- }
-
+ s.renameMatcher.Add(obj)
tr.Done(s.ctx, nil)
}
}
@@ -893,15 +758,8 @@ func (s *syncCopyMove) makeRenameMap() {
// tryRename renames an src object when doing track renames if
// possible, it returns true if the object was renamed.
func (s *syncCopyMove) tryRename(src fs.Object) bool {
- // Calculate the hash of the src object
- hash := s.renameID(src, s.trackRenamesStrategy, fs.GetModifyWindow(s.ctx, s.fsrc, s.fdst))
-
- if hash == "" {
- return false
- }
-
// Get a match on fdst
- dst := s.popRenameMap(hash, src)
+ dst := s.renameMatcher.Match(src)
if dst == nil {
return false
}
diff --git a/fs/sync/sync_test.go b/fs/sync/sync_test.go
index b7a140bad..3debfc0d1 100644
--- a/fs/sync/sync_test.go
+++ b/fs/sync/sync_test.go
@@ -1596,39 +1596,6 @@ func TestSyncWithTrackRenames(t *testing.T) {
}
}
-func TestParseRenamesStrategyModtime(t *testing.T) {
- for _, test := range []struct {
- in string
- want trackRenamesStrategy
- wantErr bool
- }{
- {"", 0, false},
- {"modtime", trackRenamesStrategyModtime, false},
- {"hash", trackRenamesStrategyHash, false},
- {"size", 0, false},
- {"modtime,hash", trackRenamesStrategyModtime | trackRenamesStrategyHash, false},
- {"hash,modtime,size", trackRenamesStrategyModtime | trackRenamesStrategyHash, false},
- {"size,boom", 0, true},
- } {
- got, err := parseTrackRenamesStrategy(test.in)
- assert.Equal(t, test.want, got, test.in)
- assert.Equal(t, test.wantErr, err != nil, test.in)
- }
-}
-
-func TestRenamesStrategyModtime(t *testing.T) {
- both := trackRenamesStrategyHash | trackRenamesStrategyModtime
- hash := trackRenamesStrategyHash
- modTime := trackRenamesStrategyModtime
-
- assert.True(t, both.hash())
- assert.True(t, both.modTime())
- assert.True(t, hash.hash())
- assert.False(t, hash.modTime())
- assert.False(t, modTime.hash())
- assert.True(t, modTime.modTime())
-}
-
func TestSyncWithTrackRenamesStrategyModtime(t *testing.T) {
ctx := context.Background()
ctx, ci := fs.AddConfig(ctx)
diff --git a/fs/sync/trackrenames/trackrenames.go b/fs/sync/trackrenames/trackrenames.go
new file mode 100644
index 000000000..cc5020093
--- /dev/null
+++ b/fs/sync/trackrenames/trackrenames.go
@@ -0,0 +1,256 @@
+// Package trackrenames matches source and destination objects for server-side renames.
+package trackrenames
+
+import (
+ "context"
+ "fmt"
+ "path"
+ "slices"
+ "strings"
+ "sync"
+ "time"
+
+ "github.com/rclone/rclone/fs"
+ "github.com/rclone/rclone/fs/hash"
+ "github.com/rclone/rclone/fs/operations"
+)
+
+// Strategy identifies the object attributes used to match renames.
+type Strategy byte
+
+const (
+ // StrategyHash includes the configured hash in the rename identifier.
+ StrategyHash Strategy = 1 << iota
+ // StrategyModtime requires matching modification times within the modify window.
+ StrategyModtime
+ // StrategyLeaf includes the leaf name in the rename identifier.
+ StrategyLeaf
+)
+
+// UsesHash reports whether the strategy compares hashes.
+func (strategy Strategy) UsesHash() bool {
+ return strategy&StrategyHash != 0
+}
+
+// UsesModtime reports whether the strategy compares modification times.
+func (strategy Strategy) UsesModtime() bool {
+ return strategy&StrategyModtime != 0
+}
+
+// UsesLeaf reports whether the strategy compares leaf names.
+func (strategy Strategy) UsesLeaf() bool {
+ return strategy&StrategyLeaf != 0
+}
+
+// ParseStrategy parses a comma-separated track-renames strategy.
+func ParseStrategy(strategies string) (strategy Strategy, err error) {
+ if strategies == "" {
+ return 0, nil
+ }
+ for value := range strings.SplitSeq(strategies, ",") {
+ switch value {
+ case "hash":
+ strategy |= StrategyHash
+ case "modtime":
+ strategy |= StrategyModtime
+ case "leaf":
+ strategy |= StrategyLeaf
+ case "size":
+ // Size is always part of the identifier.
+ default:
+ return strategy, fmt.Errorf("unknown track renames strategy %q", value)
+ }
+ }
+ return strategy, nil
+}
+
+// CheckCapabilities returns the filesystem capabilities and any reasons strategy cannot be used.
+func CheckCapabilities(ctx context.Context, fsrc, fdst fs.Fs, strategy Strategy) (hashType hash.Type, modifyWindow time.Duration, unsupported []string) {
+ if !operations.CanServerSideMove(fdst) {
+ unsupported = append(unsupported, "the destination does not support server-side move or copy")
+ }
+
+ hashType = fsrc.Hashes().Overlap(fdst.Hashes()).GetOne()
+ if strategy.UsesHash() && hashType == hash.None {
+ unsupported = append(unsupported, "the source and destination do not have a common hash")
+ }
+
+ modifyWindow = fs.GetModifyWindow(ctx, fsrc, fdst)
+ if strategy.UsesModtime() && modifyWindow == fs.ModTimeNotSupported {
+ unsupported = append(unsupported, "either the source or destination does not support modtime")
+ }
+
+ return hashType, modifyWindow, unsupported
+}
+
+// Candidate contains the object attributes used to match a tracked rename.
+type Candidate struct {
+ Remote string // Remote is the object path.
+ Size int64 // Size is the object size in bytes.
+ ModTime time.Time // ModTime is the object modification time.
+ Hash string // Hash is the value of the common hash type.
+}
+
+// Matcher stores destination objects and consumes them when a source object matches.
+type Matcher struct {
+ ctx context.Context
+ strategy Strategy
+ hashType hash.Type
+ modifyWindow time.Duration
+ mu sync.Mutex
+ objects map[string][]fs.Object
+}
+
+// NewMatcher constructs an empty rename matcher.
+func NewMatcher(ctx context.Context, strategy Strategy, hashType hash.Type, modifyWindow time.Duration) *Matcher {
+ return &Matcher{
+ ctx: ctx,
+ strategy: strategy,
+ hashType: hashType,
+ modifyWindow: modifyWindow,
+ objects: make(map[string][]fs.Object),
+ }
+}
+
+// Add stores a destination object and reports whether it produced a usable identifier.
+func (m *Matcher) Add(obj fs.Object) bool {
+ id := m.renameID(obj)
+ if id == "" {
+ return false
+ }
+ m.mu.Lock()
+ m.objects[id] = append(m.objects[id], obj)
+ m.mu.Unlock()
+ return true
+}
+
+// Match consumes and returns the first destination object matching src.
+func (m *Matcher) Match(src fs.Object) (dst fs.Object) {
+ id := m.renameID(src)
+ if id == "" {
+ return nil
+ }
+
+ m.mu.Lock()
+ defer m.mu.Unlock()
+ dsts := m.objects[id]
+ if len(dsts) == 0 {
+ return nil
+ }
+
+ match := 0
+ if m.strategy.UsesModtime() {
+ match = -1
+ srcModTime := src.ModTime(m.ctx)
+ for i, candidate := range dsts {
+ delta := candidate.ModTime(m.ctx).Sub(srcModTime)
+ if delta < m.modifyWindow && delta > -m.modifyWindow {
+ match = i
+ break
+ }
+ }
+ if match < 0 {
+ return nil
+ }
+ }
+
+ dst = dsts[match]
+ dsts = slices.Delete(dsts, match, match+1)
+ if len(dsts) == 0 {
+ delete(m.objects, id)
+ } else {
+ m.objects[id] = dsts
+ }
+ return dst
+}
+
+// CountGuaranteedMatches returns a lower bound on matches independent of matching order.
+func CountGuaranteedMatches(strategy Strategy, modifyWindow time.Duration, sources, destinations []Candidate) int {
+ sourceGroups := make(map[string][]Candidate)
+ for _, src := range sources {
+ id := candidateID(strategy, src)
+ if id != "" {
+ sourceGroups[id] = append(sourceGroups[id], src)
+ }
+ }
+ destinationGroups := make(map[string][]Candidate)
+ for _, dst := range destinations {
+ id := candidateID(strategy, dst)
+ if id != "" {
+ destinationGroups[id] = append(destinationGroups[id], dst)
+ }
+ }
+
+ matches := 0
+ for id, srcs := range sourceGroups {
+ dsts := destinationGroups[id]
+ if len(dsts) == 0 {
+ continue
+ }
+ if !strategy.UsesModtime() || allModtimesMatch(srcs, dsts, modifyWindow) {
+ matches += min(len(srcs), len(dsts))
+ }
+ }
+ return matches
+}
+
+func allModtimesMatch(srcs, dsts []Candidate, modifyWindow time.Duration) bool {
+ minSrc, maxSrc := srcs[0].ModTime, srcs[0].ModTime
+ for _, src := range srcs[1:] {
+ modTime := src.ModTime
+ if modTime.Before(minSrc) {
+ minSrc = modTime
+ }
+ if modTime.After(maxSrc) {
+ maxSrc = modTime
+ }
+ }
+ minDst, maxDst := dsts[0].ModTime, dsts[0].ModTime
+ for _, dst := range dsts[1:] {
+ modTime := dst.ModTime
+ if modTime.Before(minDst) {
+ minDst = modTime
+ }
+ if modTime.After(maxDst) {
+ maxDst = modTime
+ }
+ }
+ return maxDst.Sub(minSrc) < modifyWindow && minDst.Sub(maxSrc) > -modifyWindow
+}
+
+func candidateID(strategy Strategy, candidate Candidate) string {
+ var builder strings.Builder
+ fmt.Fprintf(&builder, "%d", candidate.Size)
+
+ if strategy.UsesHash() {
+ if candidate.Hash == "" {
+ return ""
+ }
+ builder.WriteRune(',')
+ builder.WriteString(candidate.Hash)
+ }
+
+ if strategy.UsesLeaf() {
+ builder.WriteRune(',')
+ builder.WriteString(path.Base(candidate.Remote))
+ }
+
+ return builder.String()
+}
+
+func (m *Matcher) renameID(obj fs.Object) string {
+ var sum string
+ if m.strategy.UsesHash() {
+ var err error
+ sum, err = obj.Hash(m.ctx, m.hashType)
+ if err != nil {
+ fs.Debugf(obj, "Hash failed: %v", err)
+ return ""
+ }
+ }
+ return candidateID(m.strategy, Candidate{
+ Remote: obj.Remote(),
+ Size: obj.Size(),
+ Hash: sum,
+ })
+}
diff --git a/fs/sync/trackrenames/trackrenames_test.go b/fs/sync/trackrenames/trackrenames_test.go
new file mode 100644
index 000000000..da4c173ba
--- /dev/null
+++ b/fs/sync/trackrenames/trackrenames_test.go
@@ -0,0 +1,172 @@
+package trackrenames_test
+
+import (
+ "context"
+ "errors"
+ "testing"
+ "time"
+
+ "github.com/rclone/rclone/fs"
+ "github.com/rclone/rclone/fs/hash"
+ "github.com/rclone/rclone/fs/object"
+ "github.com/rclone/rclone/fs/sync/trackrenames"
+ "github.com/stretchr/testify/assert"
+ "github.com/stretchr/testify/require"
+)
+
+func TestParseStrategy(t *testing.T) {
+ tests := []struct {
+ name string
+ value string
+ want trackrenames.Strategy
+ wantErr string
+ }{
+ {name: "empty"},
+ {name: "size", value: "size"},
+ {name: "hash", value: "hash", want: trackrenames.StrategyHash},
+ {name: "modtime", value: "modtime", want: trackrenames.StrategyModtime},
+ {name: "leaf", value: "leaf", want: trackrenames.StrategyLeaf},
+ {
+ name: "combined",
+ value: "hash,modtime,size,leaf",
+ want: trackrenames.StrategyHash | trackrenames.StrategyModtime | trackrenames.StrategyLeaf,
+ },
+ {name: "unknown", value: "size,unknown", wantErr: `unknown track renames strategy "unknown"`},
+ }
+
+ for _, test := range tests {
+ t.Run(test.name, func(t *testing.T) {
+ got, err := trackrenames.ParseStrategy(test.value)
+ if test.wantErr != "" {
+ require.EqualError(t, err, test.wantErr)
+ return
+ }
+ require.NoError(t, err)
+ assert.Equal(t, test.want, got)
+ })
+ }
+}
+
+func TestStrategyUses(t *testing.T) {
+ strategy := trackrenames.StrategyHash | trackrenames.StrategyLeaf
+ assert.True(t, strategy.UsesHash())
+ assert.False(t, strategy.UsesModtime())
+ assert.True(t, strategy.UsesLeaf())
+}
+
+func TestMatcher(t *testing.T) {
+ ctx := context.Background()
+ baseTime := time.Date(2026, time.August, 24, 12, 0, 0, 0, time.UTC)
+ newObject := func(remote, contents string, modTime time.Time) *object.MemoryObject {
+ return object.NewMemoryObject(remote, modTime, []byte(contents))
+ }
+
+ t.Run("size match is consumed", func(t *testing.T) {
+ dst := newObject("old/file.txt", "same size", baseTime)
+ src := newObject("new/file.txt", "different", baseTime)
+ matcher := trackrenames.NewMatcher(ctx, 0, hash.None, 0)
+
+ assert.True(t, matcher.Add(dst))
+ assert.Same(t, dst, matcher.Match(src))
+ assert.Nil(t, matcher.Match(src))
+ })
+
+ t.Run("hash rejects different content", func(t *testing.T) {
+ dst := newObject("old/file.txt", "destination", baseTime)
+ src := newObject("new/file.txt", "source_____", baseTime)
+ matcher := trackrenames.NewMatcher(ctx, trackrenames.StrategyHash, hash.MD5, 0)
+
+ assert.True(t, matcher.Add(dst))
+ assert.Nil(t, matcher.Match(src))
+ })
+
+ t.Run("leaf matches basename", func(t *testing.T) {
+ dst := newObject("old/file.txt", "contents", baseTime)
+ sameLeaf := newObject("new/file.txt", "contents", baseTime)
+ differentLeaf := newObject("new/other.txt", "contents", baseTime)
+ matcher := trackrenames.NewMatcher(ctx, trackrenames.StrategyLeaf, hash.None, 0)
+
+ assert.True(t, matcher.Add(dst))
+ assert.Nil(t, matcher.Match(differentLeaf))
+ assert.Same(t, dst, matcher.Match(sameLeaf))
+ })
+
+ t.Run("modtime selects an object inside the window", func(t *testing.T) {
+ outside := newObject("old/outside.txt", "contents", baseTime.Add(2*time.Second))
+ inside := newObject("old/inside.txt", "contents", baseTime.Add(500*time.Millisecond))
+ src := newObject("new/file.txt", "contents", baseTime)
+ matcher := trackrenames.NewMatcher(ctx, trackrenames.StrategyModtime, hash.None, time.Second)
+
+ assert.True(t, matcher.Add(outside))
+ assert.True(t, matcher.Add(inside))
+ assert.Same(t, inside, matcher.Match(src))
+ })
+
+ t.Run("modtime window is strict", func(t *testing.T) {
+ dst := newObject("old/file.txt", "contents", baseTime.Add(time.Second))
+ src := newObject("new/file.txt", "contents", baseTime)
+ matcher := trackrenames.NewMatcher(ctx, trackrenames.StrategyModtime, hash.None, time.Second)
+
+ assert.True(t, matcher.Add(dst))
+ assert.Nil(t, matcher.Match(src))
+ })
+
+ t.Run("hash errors do not create matches", func(t *testing.T) {
+ dst := &hashErrorObject{MemoryObject: newObject("old/file.txt", "contents", baseTime)}
+ src := newObject("new/file.txt", "contents", baseTime)
+ matcher := trackrenames.NewMatcher(ctx, trackrenames.StrategyHash, hash.MD5, 0)
+
+ assert.False(t, matcher.Add(dst))
+ assert.Nil(t, matcher.Match(src))
+ })
+
+ t.Run("guaranteed matches count duplicate identifiers", func(t *testing.T) {
+ sources := []trackrenames.Candidate{
+ {Remote: "new/one.txt", Size: 8, Hash: "same"},
+ {Remote: "new/two.txt", Size: 8, Hash: "same"},
+ {Remote: "new/three.txt", Size: 8, Hash: "same"},
+ }
+ destinations := []trackrenames.Candidate{
+ {Remote: "old/one.txt", Size: 8, Hash: "same"},
+ {Remote: "old/two.txt", Size: 8, Hash: "same"},
+ }
+
+ assert.Equal(t, 2, trackrenames.CountGuaranteedMatches(trackrenames.StrategyHash, 0, sources, destinations))
+ })
+
+ t.Run("guaranteed modtime matches require an order-independent group", func(t *testing.T) {
+ sources := []trackrenames.Candidate{
+ {Remote: "new/one.txt", Size: 8, ModTime: baseTime.Add(-300 * time.Millisecond)},
+ {Remote: "new/two.txt", Size: 8, ModTime: baseTime.Add(300 * time.Millisecond)},
+ }
+ destinations := []trackrenames.Candidate{
+ {Remote: "old/one.txt", Size: 8, ModTime: baseTime.Add(-400 * time.Millisecond)},
+ {Remote: "old/two.txt", Size: 8, ModTime: baseTime.Add(400 * time.Millisecond)},
+ }
+
+ assert.Equal(t, 2, trackrenames.CountGuaranteedMatches(trackrenames.StrategyModtime, time.Second, sources, destinations))
+ })
+
+ t.Run("ambiguous modtime groups are not counted", func(t *testing.T) {
+ sources := []trackrenames.Candidate{
+ {Remote: "new/one.txt", Size: 8, ModTime: baseTime.Add(-900 * time.Millisecond)},
+ {Remote: "new/two.txt", Size: 8, ModTime: baseTime.Add(900 * time.Millisecond)},
+ }
+ destinations := []trackrenames.Candidate{
+ {Remote: "old/one.txt", Size: 8, ModTime: baseTime.Add(-900 * time.Millisecond)},
+ {Remote: "old/two.txt", Size: 8, ModTime: baseTime.Add(900 * time.Millisecond)},
+ }
+
+ assert.Zero(t, trackrenames.CountGuaranteedMatches(trackrenames.StrategyModtime, time.Second, sources, destinations))
+ })
+}
+
+type hashErrorObject struct {
+ *object.MemoryObject
+}
+
+func (o *hashErrorObject) Hash(context.Context, hash.Type) (string, error) {
+ return "", errors.New("hash failed")
+}
+
+var _ fs.Object = (*hashErrorObject)(nil)