diff --git a/Src/JsonDiffPatchDotNet.UnitTests/UnpatchUnitTests.cs b/Src/JsonDiffPatchDotNet.UnitTests/UnpatchUnitTests.cs index e6035c4..16e9dae 100644 --- a/Src/JsonDiffPatchDotNet.UnitTests/UnpatchUnitTests.cs +++ b/Src/JsonDiffPatchDotNet.UnitTests/UnpatchUnitTests.cs @@ -1,4 +1,4 @@ -using System.Linq; +using System.Linq; using Newtonsoft.Json.Linq; using NUnit.Framework; @@ -238,5 +238,33 @@ public void Unpatch_Bug17EfficienText_Success() Assert.IsTrue(JToken.DeepEquals(left.ToString(), patched.ToString())); } + + [Test] + public void Unpatch_ObjectIfOldValueMatches_Success() + { + var jdpUnpatchIgnoreOriginalValue = new JsonDiffPatch(new Options { UnpatchIgnoreOriginalValue = false }); + 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 not ignoring original value + var unpatched_stage2 = jdpUnpatchIgnoreOriginalValue.Unpatch(stage2, diff); + Assert.AreEqual(stage1.ToString(), unpatched_stage2.ToString()); + + // Try to unpatch with stage3 not ignoring original value + var unpatched_stage3 = jdpUnpatchIgnoreOriginalValue.Unpatch(stage3, diff); + Assert.AreNotEqual(stage1.ToString(), unpatched_stage3.ToString()); + + // Try to unpatch with stage2 ignoring original value + unpatched_stage2 = jdp.Unpatch(stage2, diff); + Assert.AreEqual(stage1.ToString(), unpatched_stage2.ToString()); + + // Try to unpatch with stage3 ignoring original value + unpatched_stage3 = jdp.Unpatch(stage3, diff); + Assert.AreEqual(stage1.ToString(), unpatched_stage3.ToString()); + } } } diff --git a/Src/JsonDiffPatchDotNet/JsonDiffPatch.cs b/Src/JsonDiffPatchDotNet/JsonDiffPatch.cs index 84fad2b..80ad79e 100644 --- a/Src/JsonDiffPatchDotNet/JsonDiffPatch.cs +++ b/Src/JsonDiffPatchDotNet/JsonDiffPatch.cs @@ -206,7 +206,14 @@ public JToken Unpatch(JToken right, JToken patch) if (patchArray.Count == 2) // Replace { - return patchArray[0]; + if (_options.UnpatchIgnoreOriginalValue || right != null && right.Type == patchArray[1].Type && right.Value().Equals(patchArray[1].Value())) + { + return patchArray[0]; + } + else + { + return right; + } } if (patchArray.Count == 3) // Delete, Move or TextDiff diff --git a/Src/JsonDiffPatchDotNet/Options.cs b/Src/JsonDiffPatchDotNet/Options.cs index a76353f..31d3270 100644 --- a/Src/JsonDiffPatchDotNet/Options.cs +++ b/Src/JsonDiffPatchDotNet/Options.cs @@ -13,6 +13,7 @@ public Options() TextDiff = TextDiffMode.Efficient; MinEfficientTextDiffLength = 50; DiffArrayOptions = new ArrayOptions(); + UnpatchIgnoreOriginalValue = true; } /// @@ -57,7 +58,9 @@ public Options() /// To improve the results leveraging the power of LCS(and position move detection) you need to provide a way to compare 2 objects. /// public Func ObjectHash { get; set; } - } + + public bool UnpatchIgnoreOriginalValue { get; set; } + } public sealed class ArrayOptions {