|
| 1 | +export type Diff = { |
| 2 | + beforeFileName: string |
| 3 | + afterFileName: string |
| 4 | + hunks: Hunk[] |
| 5 | +} |
| 6 | + |
| 7 | +type Hunk = { |
| 8 | + header: HunkHeader |
| 9 | + lines: Line[] |
| 10 | +} |
| 11 | + |
| 12 | +type HunkHeader = { |
| 13 | + beforeLines: number |
| 14 | + afterLines: number |
| 15 | + beforeStartLine: number |
| 16 | + afterStartLine: number |
| 17 | +} |
| 18 | + |
| 19 | +type Line = { |
| 20 | + text: string |
| 21 | + mark: 'add' | 'delete' | 'nomodified' |
| 22 | +} |
| 23 | + |
| 24 | +const hunkHeaderRegexp = /@@ -(\d+),?(\d*) \+(\d+),?(\d*) @@/ |
| 25 | + |
| 26 | +export function parse(text: string): Diff[] { |
| 27 | + const diffs: Diff[] = []; |
| 28 | + let currentDiffIndex = 0; |
| 29 | + let currentHunkIndex = 0; |
| 30 | + |
| 31 | + text.split('\n').forEach((l) => { |
| 32 | + if (l.startsWith('---')) { |
| 33 | + diffs.push({ |
| 34 | + beforeFileName: '', |
| 35 | + afterFileName: '', |
| 36 | + hunks: [], |
| 37 | + }); |
| 38 | + |
| 39 | + currentDiffIndex = diffs.length - 1; |
| 40 | + currentHunkIndex = 0; |
| 41 | + |
| 42 | + diffs[currentDiffIndex].beforeFileName = l.slice(4); |
| 43 | + |
| 44 | + return; |
| 45 | + } |
| 46 | + |
| 47 | + if (l.startsWith('+++')) { |
| 48 | + diffs[currentDiffIndex].afterFileName = l.slice(4); |
| 49 | + |
| 50 | + return; |
| 51 | + } |
| 52 | + |
| 53 | + if (l.startsWith('@@')) { |
| 54 | + const matched = l.match(hunkHeaderRegexp); |
| 55 | + |
| 56 | + if (!matched) { |
| 57 | + return; |
| 58 | + } |
| 59 | + |
| 60 | + diffs[currentDiffIndex].hunks.push({ |
| 61 | + header: { |
| 62 | + beforeStartLine: Number(matched[1]), |
| 63 | + beforeLines: matched[2] ? Number(matched[2]) : 1, |
| 64 | + afterStartLine: Number(matched[3]), |
| 65 | + afterLines: matched[4] ? Number(matched[4]) : 1, |
| 66 | + }, |
| 67 | + lines: [], |
| 68 | + }); |
| 69 | + |
| 70 | + currentHunkIndex = diffs[currentDiffIndex].hunks.length - 1; |
| 71 | + |
| 72 | + return; |
| 73 | + } |
| 74 | + |
| 75 | + if (l.startsWith('-')) { |
| 76 | + diffs[currentDiffIndex].hunks[currentHunkIndex].lines.push({ |
| 77 | + text: l.slice(1), |
| 78 | + mark: 'delete', |
| 79 | + }); |
| 80 | + |
| 81 | + return; |
| 82 | + } |
| 83 | + |
| 84 | + if (l.startsWith('+')) { |
| 85 | + diffs[currentDiffIndex].hunks[currentHunkIndex].lines.push({ |
| 86 | + text: l.slice(1), |
| 87 | + mark: 'add', |
| 88 | + }); |
| 89 | + |
| 90 | + return; |
| 91 | + } |
| 92 | + |
| 93 | + if (l.startsWith(' ')) { |
| 94 | + diffs[currentDiffIndex].hunks[currentHunkIndex].lines.push({ |
| 95 | + text: l.slice(1), |
| 96 | + mark: 'nomodified', |
| 97 | + }); |
| 98 | + |
| 99 | + return; |
| 100 | + } |
| 101 | + }); |
| 102 | + |
| 103 | + return diffs; |
| 104 | +} |
0 commit comments