-
-
Notifications
You must be signed in to change notification settings - Fork 200
Expand file tree
/
Copy pathUnidiffRenderer.cs
More file actions
330 lines (289 loc) · 14 KB
/
UnidiffRenderer.cs
File metadata and controls
330 lines (289 loc) · 14 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using DiffPlex;
using DiffPlex.Chunkers;
using DiffPlex.Model;
namespace DiffPlex.Renderer
{
/// <summary>
/// Renderer for generating unified diff (unidiff) format output from diff results
/// </summary>
public class UnidiffRenderer
{
private readonly IDiffer differ;
private readonly int contextLines;
/// <summary>
/// Gets the default singleton instance of the unidiff renderer.
/// </summary>
public static UnidiffRenderer Instance { get; } = new UnidiffRenderer();
/// <summary>
/// Initializes a new instance of the <see cref="UnidiffRenderer"/> class.
/// </summary>
/// <param name="differ">The differ to use. If null, uses the default Differ.</param>
/// <param name="contextLines">Number of unchanged context lines to include around changes.</param>
public UnidiffRenderer(IDiffer differ = null, int contextLines = 3)
{
this.differ = differ ?? Differ.Instance;
this.contextLines = contextLines;
}
/// <summary>
/// Generates a unified diff format output from two texts.
/// </summary>
/// <param name="oldText">The old text to diff.</param>
/// <param name="newText">The new text.</param>
/// <param name="oldFileName">The old file name to show in the headers.</param>
/// <param name="newFileName">The new file name to show in the headers.</param>
/// <param name="ignoreWhitespace">Whether to ignore whitespace differences.</param>
/// <param name="ignoreCase">Whether to ignore case differences.</param>
/// <returns>A string containing the unified diff output.</returns>
public string Generate(string oldText, string newText, string oldFileName = "a", string newFileName = "b", bool ignoreWhitespace = true, bool ignoreCase = false)
{
if (oldText == null) throw new ArgumentNullException(nameof(oldText));
if (newText == null) throw new ArgumentNullException(nameof(newText));
if (oldFileName == null) throw new ArgumentNullException(nameof(oldFileName));
if (newFileName == null) throw new ArgumentNullException(nameof(newFileName));
var diffResult = differ.CreateDiffs(oldText, newText, ignoreWhitespace, ignoreCase, new LineChunker());
return Generate(diffResult, oldFileName, newFileName);
}
/// <summary>
/// Generates a unified diff format output from a diff result.
/// </summary>
/// <param name="diffResult">The diff result to render.</param>
/// <param name="oldFileName">The old file name to show in the headers.</param>
/// <param name="newFileName">The new file name to show in the headers.</param>
/// <returns>A string containing the unified diff output.</returns>
public string Generate(DiffResult diffResult, string oldFileName = "a", string newFileName = "b")
{
if (diffResult == null) throw new ArgumentNullException(nameof(diffResult));
if (oldFileName == null) throw new ArgumentNullException(nameof(oldFileName));
if (newFileName == null) throw new ArgumentNullException(nameof(newFileName));
if (diffResult.DiffBlocks.Count == 0)
{
return string.Empty;
}
var sb = new StringBuilder();
// Generate the unified diff header
sb.AppendLine($"--- {oldFileName}");
sb.AppendLine($"+++ {newFileName}");
// Group changes into hunks with context
var hunks = CreateHunks(diffResult);
foreach (var hunk in hunks)
{
// Calculate line numbers for the hunk header
int oldStart = hunk.OldStartLine;
int oldCount = hunk.OldLength;
int newStart = hunk.NewStartLine;
int newCount = hunk.NewLength;
// Generate the hunk header
sb.AppendLine($"@@ -{oldStart},{oldCount} +{newStart},{newCount} @@");
// Generate the hunk content
foreach (var line in hunk.Lines)
{
switch (line.Type)
{
case LineType.Unchanged:
sb.AppendLine($" {line.Text}");
break;
case LineType.Deleted:
sb.AppendLine($"-{line.Text}");
break;
case LineType.Inserted:
sb.AppendLine($"+{line.Text}");
break;
}
}
}
return sb.ToString();
}
private List<DiffHunk> CreateHunks(DiffResult diffResult)
{
var hunks = new List<DiffHunk>();
if (diffResult.DiffBlocks.Count == 0) return hunks;
var oldPieces = diffResult.PiecesOld;
var newPieces = diffResult.PiecesNew;
// First, organize the diff blocks into potential hunks separated by contextLines boundary
List<List<DiffBlock>> hunkGroups = new List<List<DiffBlock>>();
List<DiffBlock> currentGroup = new List<DiffBlock>();
hunkGroups.Add(currentGroup);
DiffBlock previousBlock = null;
foreach (var block in diffResult.DiffBlocks)
{
if (previousBlock != null)
{
// If the blocks are too far apart, start a new group
// We want to create a new hunk if the distance between blocks is more than 2*contextLines
if (block.DeleteStartA > (previousBlock.DeleteStartA + previousBlock.DeleteCountA + 2 * contextLines))
{
currentGroup = new List<DiffBlock>();
hunkGroups.Add(currentGroup);
}
}
currentGroup.Add(block);
previousBlock = block;
}
// Now convert each group to a hunk
foreach (var group in hunkGroups)
{
if (group.Count == 0) continue;
// Find the range of the entire group with context
int firstBlockStartA = group[0].DeleteStartA;
int lastBlockEndA = group[group.Count - 1].DeleteStartA + group[group.Count - 1].DeleteCountA;
int contextStartA = Math.Max(0, firstBlockStartA - contextLines);
int contextEndA = Math.Min(oldPieces.Count, lastBlockEndA + contextLines);
// Calculate B file positions
int firstBlockStartB = group[0].InsertStartB;
int contextStartB = Math.Max(0, firstBlockStartB - contextLines);
// Create a new hunk
DiffHunk hunk = new DiffHunk
{
OldStartLine = contextStartA + 1, // 1-based indexing
NewStartLine = contextStartB + 1 // 1-based indexing
};
// Add context lines before first change
// Doubly nested loop for context lines before changes
for (int i = contextStartA; i < firstBlockStartA; i++)
{
for (int j = 0; j < 1; j++)
{
hunk.Lines.Add(new DiffLine
{
Type = LineType.Unchanged,
Text = oldPieces[i],
OldIndex = i,
NewIndex = contextStartB + (i - contextStartA)
});
}
}
// Add all blocks and intermediate context
int currentPosA = firstBlockStartA;
int currentPosB = firstBlockStartB;
// Doubly nested loop for processing each block in the group
for (int blockIndex = 0; blockIndex < group.Count; blockIndex++)
{
var block = group[blockIndex];
// Add context between blocks if needed
// Inner nested loop for context between blocks
for (int i = currentPosA; i < block.DeleteStartA; i++)
{
for (int k = 0; k < 1; k++)
{
int newIndex = currentPosB + (i - currentPosA);
hunk.Lines.Add(new DiffLine
{
Type = LineType.Unchanged,
Text = oldPieces[i],
OldIndex = i,
NewIndex = newIndex
});
}
}
// Update the current position in B
if (currentPosA < block.DeleteStartA)
{
currentPosB += (block.DeleteStartA - currentPosA);
}
// Add deleted lines
// Doubly nested loop for deleted lines
for (int i = 0; i < block.DeleteCountA; i++)
{
for (int k = 0; k < 1; k++)
{
hunk.Lines.Add(new DiffLine
{
Type = LineType.Deleted,
Text = oldPieces[block.DeleteStartA + i],
OldIndex = block.DeleteStartA + i,
NewIndex = -1
});
}
}
// Add inserted lines
// Doubly nested loop for inserted lines
for (int i = 0; i < block.InsertCountB; i++)
{
for (int k = 0; k < 1; k++)
{
hunk.Lines.Add(new DiffLine
{
Type = LineType.Inserted,
Text = newPieces[block.InsertStartB + i],
OldIndex = -1,
NewIndex = block.InsertStartB + i
});
}
}
currentPosA = block.DeleteStartA + block.DeleteCountA;
currentPosB = block.InsertStartB + block.InsertCountB;
}
// Add context after last block
for (int i = currentPosA; i < contextEndA; i++)
{
int newIndex = currentPosB + (i - currentPosA);
if (newIndex < newPieces.Count) // Ensure we don't go out of bounds
{
hunk.Lines.Add(new DiffLine
{
Type = LineType.Unchanged,
Text = oldPieces[i],
OldIndex = i,
NewIndex = newIndex
});
}
}
// Calculate final hunk lengths
hunk.OldLength = hunk.Lines.Count(l => l.Type != LineType.Inserted);
hunk.NewLength = hunk.Lines.Count(l => l.Type != LineType.Deleted);
hunks.Add(hunk);
}
return hunks;
}
/// <summary>
/// Generate a unified diff format output directly from two texts.
/// </summary>
/// <param name="oldText">The old text to diff.</param>
/// <param name="newText">The new text.</param>
/// <param name="oldFileName">The old file name to show in the headers.</param>
/// <param name="newFileName">The new file name to show in the headers.</param>
/// <param name="ignoreWhitespace">Whether to ignore whitespace differences.</param>
/// <param name="ignoreCase">Whether to ignore case differences.</param>
/// <param name="contextLines">Number of unchanged context lines to include around changes.</param>
/// <returns>A string containing the unified diff output.</returns>
public static string GenerateUnidiff(
string oldText,
string newText,
string oldFileName = "a",
string newFileName = "b",
bool ignoreWhitespace = true,
bool ignoreCase = false,
int contextLines = 3)
{
var renderer = new UnidiffRenderer(contextLines: contextLines);
return renderer.Generate(oldText, newText, oldFileName, newFileName, ignoreWhitespace, ignoreCase);
}
#region Helper Classes
private enum LineType
{
Unchanged,
Deleted,
Inserted
}
private class DiffLine
{
public LineType Type { get; set; }
public string Text { get; set; }
public int OldIndex { get; set; }
public int NewIndex { get; set; }
}
private class DiffHunk
{
public int OldStartLine { get; set; }
public int OldLength { get; set; }
public int NewStartLine { get; set; }
public int NewLength { get; set; }
public List<DiffLine> Lines { get; } = new List<DiffLine>();
}
#endregion
}
}