jsondiffpatch.net icon indicating copy to clipboard operation
jsondiffpatch.net copied to clipboard

Unpatch unexpected replace of wrong old value

Open jespersh opened this issue 9 months ago • 1 comments

Say I have a 3 stages. First I have the initial value 1, then I change to 2 and then to 3 creating 2 diffs from 1 to 2 and from 2 to 3. 1->2->3.

Then I try to unpatch from 2 to 1 (2->1)

But because the value is current at 3 I'd expect it to stay at 3 and not revert to 1, but that's what happens here.

I have a small testcase here:

var jdp = new JsonDiffPatch();
var stage1 = JToken.Parse(@"{""stage"":1}");
var stage2 = JToken.Parse(@"{""stage"":2}");
var stage3 = JToken.Parse(@"{""stage"":3}");

var diff = jdp.Diff(stage1, stage2);

// Try to unpatch with stage2
var unpatched_stage2 = jdp.Unpatch(stage2, diff);
Assert.AreEqual(stage1.ToString(), unpatched_stage2.ToString());

// Try to unpatch with stage3 - this should not work as the original value is not stage2
var unpatched_stage3 = jdp.Unpatch(stage3, diff);
Assert.AreNotEqual(stage1.ToString(), unpatched_stage3.ToString());

jespersh avatar Jul 10 '25 11:07 jespersh

I'm wondering if something like this will fix it appropriately:

if (patchArray.Count == 2)  // Replace
{
	if (right != null && right.Type == patchArray[1].Type && right.Value<JValue>().Equals(patchArray[1].Value<JValue>()))
	{
		return patchArray[0];
	}
	else
	{
		return right;
	}
}

Maybe an option that allows overriding the default behavior with this

jespersh avatar Jul 10 '25 11:07 jespersh