Skip to content

Commit 1475201

Browse files
committed
Add inline diff demo as a unit test
1 parent e181a96 commit 1475201

1 file changed

Lines changed: 73 additions & 0 deletions

File tree

tests/Menees.Diffs.Tests/TextDiffTests.cs

Lines changed: 73 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@
44
using System.Collections.Generic;
55
using System.Text;
66
using Shouldly;
7+
using System.Linq;
78

89
namespace Menees.Diffs.Tests
910
{
@@ -96,6 +97,78 @@ public void ExecuteDeleteInsertTest()
9697
Check(edits[1], 1, 1, 1);
9798
}
9899

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+
99172
internal static EditScript Diff(string left, string right, bool ignoreCase, bool ignoreOuterWhiteSpace, bool supportChangeEditType = true)
100173
{
101174
IList<string> leftLines = DiffUtility.GetStringTextLines(left);

0 commit comments

Comments
 (0)