Skip to content

Commit d229bf7

Browse files
committed
fix: make MergeDiffs deterministic
This commit was moved from ipfs/go-merkledag@5729b25
1 parent 5f4138f commit d229bf7

File tree

2 files changed

+12
-8
lines changed

2 files changed

+12
-8
lines changed

ipld/merkledag/dagutils/diff.go

+11-7
Original file line numberDiff line numberDiff line change
@@ -176,24 +176,28 @@ type Conflict struct {
176176
// Changes involved (which share the same path).
177177
func MergeDiffs(a, b []*Change) ([]*Change, []Conflict) {
178178
paths := make(map[string]*Change)
179-
for _, c := range a {
179+
for _, c := range b {
180180
paths[c.Path] = c
181181
}
182182

183183
var changes []*Change
184184
var conflicts []Conflict
185185

186-
for _, changeB := range b {
187-
if changeA, ok := paths[changeB.Path]; ok {
186+
// NOTE: we avoid iterating over maps here to ensure iteration order is determistic. We
187+
// include changes from a first, then b.
188+
for _, changeA := range a {
189+
if changeB, ok := paths[changeA.Path]; ok {
188190
conflicts = append(conflicts, Conflict{changeA, changeB})
189191
} else {
190-
changes = append(changes, changeB)
192+
changes = append(changes, changeA)
191193
}
192-
delete(paths, changeB.Path)
194+
delete(paths, changeA.Path)
193195
}
194196

195-
for _, c := range paths {
196-
changes = append(changes, c)
197+
for _, c := range b {
198+
if _, ok := paths[c.Path]; ok {
199+
changes = append(changes, c)
200+
}
197201
}
198202

199203
return changes, conflicts

ipld/merkledag/dagutils/diff_test.go

+1-1
Original file line numberDiff line numberDiff line change
@@ -33,9 +33,9 @@ func TestMergeDiffs(t *testing.T) {
3333
}
3434

3535
expect := []*Change{
36-
changesB[1],
3736
changesA[0],
3837
changesA[2],
38+
changesB[1],
3939
}
4040

4141
for i, change := range changes {

0 commit comments

Comments
 (0)