* Compute a diff between two files * @param oldText Previous version of code * @param newText New version of code * @returns A DiffResult with diff text and count of changed lines
(oldText: string, newText: string)
| 57 | * @returns A DiffResult with diff text and count of changed lines |
| 58 | */ |
| 59 | function computeFileDiff(oldText: string, newText: string): DiffResult { |
| 60 | const oldLines = oldText.split("\n"); |
| 61 | const newLines = newText.split("\n"); |
| 62 | |
| 63 | // Create a diff using a simple line-by-line comparison |
| 64 | const hunks: DiffHunk[] = []; |
| 65 | let currentHunk: DiffHunk | null = null; |
| 66 | let oldLineNumber = 0; |
| 67 | let newLineNumber = 0; |
| 68 | |
| 69 | // Context lines to include before and after changes |
| 70 | const contextLines = 3; |
| 71 | |
| 72 | // Track which lines have been processed |
| 73 | const processedOldLines = new Set<number>(); |
| 74 | const processedNewLines = new Set<number>(); |
| 75 | |
| 76 | // Find changed lines |
| 77 | const changedLines: Array< |
| 78 | { oldIndex: number; newIndex: number; type: "added" | "removed" | "changed" } |
| 79 | > = []; |
| 80 | |
| 81 | // First pass: find exact matches and identify changes |
| 82 | const oldToNew = new Map<number, number>(); |
| 83 | const newToOld = new Map<number, number>(); |
| 84 | |
| 85 | // Find identical lines (exact matches) |
| 86 | for (let i = 0; i < oldLines.length; i++) { |
| 87 | for (let j = 0; j < newLines.length; j++) { |
| 88 | if (oldLines[i] === newLines[j] && !processedNewLines.has(j)) { |
| 89 | oldToNew.set(i, j); |
| 90 | newToOld.set(j, i); |
| 91 | processedOldLines.add(i); |
| 92 | processedNewLines.add(j); |
| 93 | break; |
| 94 | } |
| 95 | } |
| 96 | } |
| 97 | |
| 98 | // Identify added, removed, and changed lines |
| 99 | for (let i = 0; i < oldLines.length; i++) { |
| 100 | if (!processedOldLines.has(i)) { |
| 101 | // This line was removed or changed |
| 102 | let found = false; |
| 103 | |
| 104 | // Look for a similar line in the new text (potential change) |
| 105 | for (let j = 0; j < newLines.length; j++) { |
| 106 | if (!processedNewLines.has(j) && areSimilar(oldLines[i], newLines[j])) { |
| 107 | changedLines.push({ oldIndex: i, newIndex: j, type: "changed" }); |
| 108 | processedOldLines.add(i); |
| 109 | processedNewLines.add(j); |
| 110 | found = true; |
| 111 | break; |
| 112 | } |
| 113 | } |
| 114 | |
| 115 | if (!found) { |
| 116 | // This line was removed |
no test coverage detected