|
| 1 | +/** |
| 2 | + * Patch envelope parser. |
| 3 | + * Turns OpenAI-style *** Begin Patch/End Patch text into add/update/delete hunks. |
| 4 | + */ |
| 5 | + |
| 6 | +const BEGIN_PATCH_MARKER = "*** Begin Patch"; |
| 7 | +const END_PATCH_MARKER = "*** End Patch"; |
| 8 | +const ADD_FILE_MARKER = "*** Add File: "; |
| 9 | +const DELETE_FILE_MARKER = "*** Delete File: "; |
| 10 | +const UPDATE_FILE_MARKER = "*** Update File: "; |
| 11 | +const MOVE_TO_MARKER = "*** Move to: "; |
| 12 | +const EOF_MARKER = "*** End of File"; |
| 13 | +const CHANGE_CONTEXT_MARKER = "@@ "; |
| 14 | +const EMPTY_CHANGE_CONTEXT_MARKER = "@@"; |
| 15 | + |
| 16 | +type AddFileHunk = { |
| 17 | + kind: "add"; |
| 18 | + path: string; |
| 19 | + contents: string; |
| 20 | +}; |
| 21 | + |
| 22 | +type DeleteFileHunk = { |
| 23 | + kind: "delete"; |
| 24 | + path: string; |
| 25 | +}; |
| 26 | + |
| 27 | +type UpdateFileChunk = { |
| 28 | + changeContext?: string; |
| 29 | + oldLines: string[]; |
| 30 | + newLines: string[]; |
| 31 | + contextOldIndexes: Array<number | undefined>; |
| 32 | + isEndOfFile: boolean; |
| 33 | +}; |
| 34 | + |
| 35 | +type UpdateFileHunk = { |
| 36 | + kind: "update"; |
| 37 | + path: string; |
| 38 | + movePath?: string; |
| 39 | + chunks: UpdateFileChunk[]; |
| 40 | +}; |
| 41 | + |
| 42 | +export type Hunk = AddFileHunk | DeleteFileHunk | UpdateFileHunk; |
| 43 | + |
| 44 | +export function parsePatchText(input: string): { hunks: Hunk[]; patch: string } { |
| 45 | + const trimmed = input.trim(); |
| 46 | + if (!trimmed) { |
| 47 | + throw new Error("Invalid patch: input is empty."); |
| 48 | + } |
| 49 | + |
| 50 | + const lines = trimmed.split(/\r?\n/); |
| 51 | + const validated = checkPatchBoundariesLenient(lines); |
| 52 | + const hunks: Hunk[] = []; |
| 53 | + |
| 54 | + const lastLineIndex = validated.length - 1; |
| 55 | + let remaining = validated.slice(1, lastLineIndex); |
| 56 | + let lineNumber = 2; |
| 57 | + |
| 58 | + while (remaining.length > 0) { |
| 59 | + const { hunk, consumed } = parseOneHunk(remaining, lineNumber); |
| 60 | + hunks.push(hunk); |
| 61 | + lineNumber += consumed; |
| 62 | + remaining = remaining.slice(consumed); |
| 63 | + } |
| 64 | + |
| 65 | + return { hunks, patch: validated.join("\n") }; |
| 66 | +} |
| 67 | + |
| 68 | +function checkPatchBoundariesLenient(lines: string[]): string[] { |
| 69 | + const strictError = checkPatchBoundariesStrict(lines); |
| 70 | + if (!strictError) { |
| 71 | + return lines; |
| 72 | + } |
| 73 | + |
| 74 | + if (lines.length < 4) { |
| 75 | + throw new Error(strictError); |
| 76 | + } |
| 77 | + const first = lines[0]; |
| 78 | + const last = lines.at(-1); |
| 79 | + if ( |
| 80 | + last && |
| 81 | + (first === "<<EOF" || first === "<<'EOF'" || first === '<<"EOF"') && |
| 82 | + last.endsWith("EOF") |
| 83 | + ) { |
| 84 | + const inner = lines.slice(1, -1); |
| 85 | + const innerError = checkPatchBoundariesStrict(inner); |
| 86 | + if (!innerError) { |
| 87 | + return inner; |
| 88 | + } |
| 89 | + throw new Error(innerError); |
| 90 | + } |
| 91 | + |
| 92 | + throw new Error(strictError); |
| 93 | +} |
| 94 | + |
| 95 | +function checkPatchBoundariesStrict(lines: string[]): string | null { |
| 96 | + const firstLine = lines[0]?.trim(); |
| 97 | + const lastLine = lines[lines.length - 1]?.trim(); |
| 98 | + |
| 99 | + if (firstLine === BEGIN_PATCH_MARKER && lastLine === END_PATCH_MARKER) { |
| 100 | + return null; |
| 101 | + } |
| 102 | + if (firstLine !== BEGIN_PATCH_MARKER) { |
| 103 | + return "The first line of the patch must be '*** Begin Patch'"; |
| 104 | + } |
| 105 | + return "The last line of the patch must be '*** End Patch'"; |
| 106 | +} |
| 107 | + |
| 108 | +function parseOneHunk(lines: string[], lineNumber: number): { hunk: Hunk; consumed: number } { |
| 109 | + if (lines.length === 0) { |
| 110 | + throw new Error(`Invalid patch hunk at line ${lineNumber}: empty hunk`); |
| 111 | + } |
| 112 | + const firstLine = lines.at(0)?.trim(); |
| 113 | + if (firstLine === undefined) { |
| 114 | + throw new Error(`Invalid patch hunk at line ${lineNumber}: empty hunk`); |
| 115 | + } |
| 116 | + if (firstLine.startsWith(ADD_FILE_MARKER)) { |
| 117 | + const targetPath = firstLine.slice(ADD_FILE_MARKER.length); |
| 118 | + let contents = ""; |
| 119 | + let consumed = 1; |
| 120 | + for (const addLine of lines.slice(1)) { |
| 121 | + if (addLine.startsWith("+")) { |
| 122 | + contents += `${addLine.slice(1)}\n`; |
| 123 | + consumed += 1; |
| 124 | + } else { |
| 125 | + break; |
| 126 | + } |
| 127 | + } |
| 128 | + return { |
| 129 | + hunk: { kind: "add", path: targetPath, contents }, |
| 130 | + consumed, |
| 131 | + }; |
| 132 | + } |
| 133 | + |
| 134 | + if (firstLine.startsWith(DELETE_FILE_MARKER)) { |
| 135 | + const targetPath = firstLine.slice(DELETE_FILE_MARKER.length); |
| 136 | + return { |
| 137 | + hunk: { kind: "delete", path: targetPath }, |
| 138 | + consumed: 1, |
| 139 | + }; |
| 140 | + } |
| 141 | + |
| 142 | + if (firstLine.startsWith(UPDATE_FILE_MARKER)) { |
| 143 | + const targetPath = firstLine.slice(UPDATE_FILE_MARKER.length); |
| 144 | + let remaining = lines.slice(1); |
| 145 | + let consumed = 1; |
| 146 | + let movePath: string | undefined; |
| 147 | + |
| 148 | + const moveCandidate = remaining[0]?.trim(); |
| 149 | + if (moveCandidate?.startsWith(MOVE_TO_MARKER)) { |
| 150 | + movePath = moveCandidate.slice(MOVE_TO_MARKER.length); |
| 151 | + remaining = remaining.slice(1); |
| 152 | + consumed += 1; |
| 153 | + } |
| 154 | + |
| 155 | + const chunks: UpdateFileChunk[] = []; |
| 156 | + while (remaining.length > 0) { |
| 157 | + const firstRemaining = remaining.at(0); |
| 158 | + if (firstRemaining === undefined) { |
| 159 | + break; |
| 160 | + } |
| 161 | + if (firstRemaining.trim() === "") { |
| 162 | + remaining = remaining.slice(1); |
| 163 | + consumed += 1; |
| 164 | + continue; |
| 165 | + } |
| 166 | + if (firstRemaining.startsWith("***")) { |
| 167 | + break; |
| 168 | + } |
| 169 | + const { chunk, consumed: chunkLines } = parseUpdateFileChunk( |
| 170 | + remaining, |
| 171 | + lineNumber + consumed, |
| 172 | + chunks.length === 0, |
| 173 | + ); |
| 174 | + chunks.push(chunk); |
| 175 | + remaining = remaining.slice(chunkLines); |
| 176 | + consumed += chunkLines; |
| 177 | + } |
| 178 | + |
| 179 | + if (chunks.length === 0) { |
| 180 | + throw new Error( |
| 181 | + `Invalid patch hunk at line ${lineNumber}: Update file hunk for path '${targetPath}' is empty`, |
| 182 | + ); |
| 183 | + } |
| 184 | + |
| 185 | + return { |
| 186 | + hunk: { |
| 187 | + kind: "update", |
| 188 | + path: targetPath, |
| 189 | + movePath, |
| 190 | + chunks, |
| 191 | + }, |
| 192 | + consumed, |
| 193 | + }; |
| 194 | + } |
| 195 | + |
| 196 | + throw new Error( |
| 197 | + `Invalid patch hunk at line ${lineNumber}: '${lines[0]}' is not a valid hunk header. Valid hunk headers: '*** Add File: {path}', '*** Delete File: {path}', '*** Update File: {path}'`, |
| 198 | + ); |
| 199 | +} |
| 200 | + |
| 201 | +function parseUpdateFileChunk( |
| 202 | + lines: string[], |
| 203 | + lineNumber: number, |
| 204 | + allowMissingContext: boolean, |
| 205 | +): { chunk: UpdateFileChunk; consumed: number } { |
| 206 | + if (lines.length === 0) { |
| 207 | + throw new Error( |
| 208 | + `Invalid patch hunk at line ${lineNumber}: Update hunk does not contain any lines`, |
| 209 | + ); |
| 210 | + } |
| 211 | + |
| 212 | + let changeContext: string | undefined; |
| 213 | + let startIndex = 0; |
| 214 | + const firstLine = lines.at(0); |
| 215 | + if (firstLine === EMPTY_CHANGE_CONTEXT_MARKER) { |
| 216 | + startIndex = 1; |
| 217 | + } else if (firstLine?.startsWith(CHANGE_CONTEXT_MARKER)) { |
| 218 | + changeContext = firstLine.slice(CHANGE_CONTEXT_MARKER.length); |
| 219 | + startIndex = 1; |
| 220 | + } else if (!allowMissingContext) { |
| 221 | + throw new Error( |
| 222 | + `Invalid patch hunk at line ${lineNumber}: Expected update hunk to start with a @@ context marker, got: '${firstLine}'`, |
| 223 | + ); |
| 224 | + } |
| 225 | + |
| 226 | + if (startIndex >= lines.length) { |
| 227 | + throw new Error( |
| 228 | + `Invalid patch hunk at line ${lineNumber + 1}: Update hunk does not contain any lines`, |
| 229 | + ); |
| 230 | + } |
| 231 | + |
| 232 | + const chunk: UpdateFileChunk = { |
| 233 | + changeContext, |
| 234 | + oldLines: [], |
| 235 | + newLines: [], |
| 236 | + contextOldIndexes: [], |
| 237 | + isEndOfFile: false, |
| 238 | + }; |
| 239 | + |
| 240 | + let parsedLines = 0; |
| 241 | + for (const line of lines.slice(startIndex)) { |
| 242 | + if (line === EOF_MARKER) { |
| 243 | + if (parsedLines === 0) { |
| 244 | + throw new Error( |
| 245 | + `Invalid patch hunk at line ${lineNumber + 1}: Update hunk does not contain any lines`, |
| 246 | + ); |
| 247 | + } |
| 248 | + chunk.isEndOfFile = true; |
| 249 | + parsedLines += 1; |
| 250 | + break; |
| 251 | + } |
| 252 | + |
| 253 | + const marker = line[0]; |
| 254 | + if (!marker) { |
| 255 | + chunk.contextOldIndexes.push(chunk.oldLines.length); |
| 256 | + chunk.oldLines.push(""); |
| 257 | + chunk.newLines.push(""); |
| 258 | + parsedLines += 1; |
| 259 | + continue; |
| 260 | + } |
| 261 | + |
| 262 | + if (marker === " ") { |
| 263 | + const content = line.slice(1); |
| 264 | + chunk.contextOldIndexes.push(chunk.oldLines.length); |
| 265 | + chunk.oldLines.push(content); |
| 266 | + chunk.newLines.push(content); |
| 267 | + parsedLines += 1; |
| 268 | + continue; |
| 269 | + } |
| 270 | + if (marker === "+") { |
| 271 | + chunk.contextOldIndexes.push(undefined); |
| 272 | + chunk.newLines.push(line.slice(1)); |
| 273 | + parsedLines += 1; |
| 274 | + continue; |
| 275 | + } |
| 276 | + if (marker === "-") { |
| 277 | + chunk.oldLines.push(line.slice(1)); |
| 278 | + parsedLines += 1; |
| 279 | + continue; |
| 280 | + } |
| 281 | + |
| 282 | + if (parsedLines === 0) { |
| 283 | + throw new Error( |
| 284 | + `Invalid patch hunk at line ${lineNumber + 1}: Unexpected line found in update hunk: '${line}'. Every line should start with ' ' (context line), '+' (added line), or '-' (removed line)`, |
| 285 | + ); |
| 286 | + } |
| 287 | + break; |
| 288 | + } |
| 289 | + |
| 290 | + return { chunk, consumed: parsedLines + startIndex }; |
| 291 | +} |
0 commit comments