| 20 | * @returns Parsed diff data |
| 21 | */ |
| 22 | export function parseUnifiedDiff(diffText: string): DiffData { |
| 23 | const lines = diffText.split(/\r?\n/); |
| 24 | let oldPath = ""; |
| 25 | let newPath = ""; |
| 26 | const hunks: DiffHunk[] = []; |
| 27 | let currentHunk: DiffHunk | null = null; |
| 28 | let currentLines: DiffLine[] = []; |
| 29 | let status: DiffData["status"] = "modified"; |
| 30 | |
| 31 | for (const line of lines) { |
| 32 | // Parse file headers |
| 33 | if (line.startsWith("--- ")) { |
| 34 | oldPath = line.slice(4).replace(/^a\//, ""); |
| 35 | continue; |
| 36 | } |
| 37 | if (line.startsWith("+++ ")) { |
| 38 | newPath = line.slice(4).replace(/^b\//, ""); |
| 39 | continue; |
| 40 | } |
| 41 | |
| 42 | // Parse hunk header |
| 43 | const hunkMatch = line.match(/^@@ -(\d+)(?:,(\d+))? \+(\d+)(?:,(\d+))? @@(.*)$/); |
| 44 | if (hunkMatch) { |
| 45 | // Save previous hunk |
| 46 | if (currentHunk) { |
| 47 | hunks.push({ ...currentHunk, lines: Object.freeze(currentLines) }); |
| 48 | } |
| 49 | |
| 50 | const headerText = hunkMatch[5]?.trim(); |
| 51 | currentHunk = { |
| 52 | oldStart: Number.parseInt(hunkMatch[1] ?? "0", 10), |
| 53 | oldCount: Number.parseInt(hunkMatch[2] ?? "1", 10), |
| 54 | newStart: Number.parseInt(hunkMatch[3] ?? "0", 10), |
| 55 | newCount: Number.parseInt(hunkMatch[4] ?? "1", 10), |
| 56 | ...(headerText ? { header: headerText } : {}), |
| 57 | lines: Object.freeze([]), |
| 58 | }; |
| 59 | currentLines = []; |
| 60 | continue; |
| 61 | } |
| 62 | |
| 63 | // Parse diff lines |
| 64 | if (currentHunk) { |
| 65 | if (line.startsWith("+")) { |
| 66 | currentLines.push({ type: "add", content: line.slice(1) }); |
| 67 | } else if (line.startsWith("-")) { |
| 68 | currentLines.push({ type: "delete", content: line.slice(1) }); |
| 69 | } else if (line.startsWith(" ") || line === "") { |
| 70 | currentLines.push({ type: "context", content: line.slice(1) || line }); |
| 71 | } |
| 72 | } |
| 73 | } |
| 74 | |
| 75 | // Save last hunk |
| 76 | if (currentHunk) { |
| 77 | hunks.push({ ...currentHunk, lines: Object.freeze(currentLines) }); |
| 78 | } |
| 79 | |