Skip to content

Commit 01ea638

Browse files
committed
DiffProcessor: detect removed values which are added again
In this case, fuse the removal and addition operation into a move and remove the removal operation.
1 parent 55adcf9 commit 01ea638

File tree

2 files changed

+31
-0
lines changed

2 files changed

+31
-0
lines changed

src/main/java/com/github/fge/jsonpatch/diff2/DiffProcessor.java

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -60,6 +60,14 @@ void valueRemoved(final JsonPointer pointer, final JsonNode value)
6060

6161
void valueAdded(final JsonPointer pointer, final JsonNode value)
6262
{
63+
final int removalIndex = findPreviouslyRemoved(value);
64+
if (removalIndex != -1) {
65+
final DiffOperation removed = diffs.get(removalIndex);
66+
diffs.remove(removalIndex);
67+
diffs.add(DiffOperation.move(removed.getOldPointer(),
68+
value, pointer, value));
69+
return;
70+
}
6371
final JsonPointer ptr = findUnchangedValue(value);
6472
final DiffOperation op = ptr != null
6573
? DiffOperation.copy(ptr, pointer, value)
@@ -87,4 +95,19 @@ private JsonPointer findUnchangedValue(final JsonNode value)
8795
return entry.getKey();
8896
return null;
8997
}
98+
99+
private int findPreviouslyRemoved(final JsonNode value)
100+
{
101+
final Predicate<JsonNode> predicate = EQUIVALENCE.equivalentTo(value);
102+
103+
DiffOperation op;
104+
105+
for (int i = 0; i < diffs.size(); i++) {
106+
op = diffs.get(i);
107+
if (op.getType() == DiffOperation.Type.REMOVE
108+
&& predicate.apply(op.getOldValue()))
109+
return i;
110+
}
111+
return -1;
112+
}
90113
}

src/test/resources/jsonpatch/diff2/diff.json

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -126,5 +126,13 @@
126126
"patch": [
127127
{ "op": "copy", "path": "/d", "from": "/a" }
128128
]
129+
},
130+
{
131+
"message": "similar element removed then added is moved instead",
132+
"first": { "a": "b" },
133+
"second": { "c": "b" },
134+
"patch": [
135+
{ "op": "move", "path": "/c", "from": "/a" }
136+
]
129137
}
130138
]

0 commit comments

Comments
 (0)