diffParser.ts (1154B)
1 /** Parsed unified diff structure. */ 2 export interface ParsedDiff { 3 oldFileName: string | null; 4 newFileName: string | null; 5 hunks: string[]; 6 } 7 8 /** 9 * Parse a unified diff string into structured data for @git-diff-view/react. 10 * Extracts filenames from ---/+++ lines and splits content into hunk strings. 11 */ 12 export function parseUnifiedDiff(raw: string): ParsedDiff { 13 const lines = raw.split("\n"); 14 let oldFileName: string | null = null; 15 let newFileName: string | null = null; 16 const hunks: string[] = []; 17 let currentHunk: string[] = []; 18 19 for (const line of lines) { 20 if (line.startsWith("--- ")) { 21 oldFileName = line.slice(4).trim(); 22 continue; 23 } 24 if (line.startsWith("+++ ")) { 25 newFileName = line.slice(4).trim(); 26 continue; 27 } 28 if (line.startsWith("@@")) { 29 if (currentHunk.length > 0) { 30 hunks.push(currentHunk.join("\n")); 31 } 32 currentHunk = [line]; 33 continue; 34 } 35 if (currentHunk.length > 0) { 36 currentHunk.push(line); 37 } 38 } 39 40 if (currentHunk.length > 0) { 41 hunks.push(currentHunk.join("\n")); 42 } 43 44 return { oldFileName, newFileName, hunks }; 45 }