|
4 | 4 | using System.Collections.Generic; |
5 | 5 | using System.Text; |
6 | 6 | using Shouldly; |
| 7 | +using System.Linq; |
7 | 8 |
|
8 | 9 | namespace Menees.Diffs.Tests |
9 | 10 | { |
@@ -96,6 +97,78 @@ public void ExecuteDeleteInsertTest() |
96 | 97 | Check(edits[1], 1, 1, 1); |
97 | 98 | } |
98 | 99 |
|
| 100 | + [TestMethod] |
| 101 | + public void InlineDiffDemo() |
| 102 | + { |
| 103 | + string a = """ |
| 104 | + One |
| 105 | + Dos |
| 106 | + Three |
| 107 | + For |
| 108 | + Five |
| 109 | + Seven |
| 110 | + """; |
| 111 | + |
| 112 | + string b = """ |
| 113 | + One |
| 114 | + Three |
| 115 | + Four |
| 116 | + Five |
| 117 | + Six |
| 118 | + Seven |
| 119 | + """; |
| 120 | + |
| 121 | + IList<string> aLines = DiffUtility.GetStringTextLines(a); |
| 122 | + IList<string> bLines = DiffUtility.GetStringTextLines(b); |
| 123 | + |
| 124 | + // Don't use the "Change" edit type when doing an inline diff. |
| 125 | + TextDiff diff = new(HashType.Unique, false, false, 0, supportChangeEditType: false); |
| 126 | + EditScript edits = diff.Execute(aLines, bLines); |
| 127 | + |
| 128 | + List<(EditType Edit, string Text)> inlineDiff = []; |
| 129 | + int aIndex = 0; |
| 130 | + foreach (Edit edit in edits) |
| 131 | + { |
| 132 | + AddALinesUntil(edit.StartA); |
| 133 | + |
| 134 | + for (int index = 0; index < edit.Length; index++) |
| 135 | + { |
| 136 | + if (edit.EditType == EditType.Delete) |
| 137 | + { |
| 138 | + inlineDiff.Add((edit.EditType, aLines[aIndex++])); |
| 139 | + } |
| 140 | + else if (edit.EditType == EditType.Insert) |
| 141 | + { |
| 142 | + inlineDiff.Add((edit.EditType, bLines[edit.StartB + index])); |
| 143 | + } |
| 144 | + } |
| 145 | + } |
| 146 | + |
| 147 | + AddALinesUntil(aLines.Count); |
| 148 | + |
| 149 | + void AddALinesUntil(int endIndex) |
| 150 | + { |
| 151 | + while (aIndex < endIndex) |
| 152 | + { |
| 153 | + inlineDiff.Add((EditType.None, aLines[aIndex++])); |
| 154 | + } |
| 155 | + } |
| 156 | + |
| 157 | + string[] output = [.. inlineDiff.Select(pair => |
| 158 | + $"{pair.Edit switch { EditType.Insert => '+', EditType.Delete => '-', _ => ' ' }} {pair.Text}" |
| 159 | + )]; |
| 160 | + |
| 161 | + output.ShouldBe([ |
| 162 | + " One", |
| 163 | + "- Dos", |
| 164 | + " Three", |
| 165 | + "- For", |
| 166 | + "+ Four", |
| 167 | + " Five", |
| 168 | + "+ Six", |
| 169 | + " Seven"]); |
| 170 | + } |
| 171 | + |
99 | 172 | internal static EditScript Diff(string left, string right, bool ignoreCase, bool ignoreOuterWhiteSpace, bool supportChangeEditType = true) |
100 | 173 | { |
101 | 174 | IList<string> leftLines = DiffUtility.GetStringTextLines(left); |
|
0 commit comments