(filePath: string, chunks: UpdateFileChunk[])
| 298 | } |
| 299 | |
| 300 | export function deriveNewContentsFromChunks(filePath: string, chunks: UpdateFileChunk[]): ApplyPatchFileUpdate { |
| 301 | // Read original file content |
| 302 | let originalContent: string |
| 303 | try { |
| 304 | originalContent = require("fs").readFileSync(filePath, "utf-8") |
| 305 | } catch (error) { |
| 306 | throw new Error(`Failed to read file ${filePath}: ${error}`) |
| 307 | } |
| 308 | |
| 309 | let originalLines = originalContent.split("\n") |
| 310 | |
| 311 | // Drop trailing empty element for consistent line counting |
| 312 | if (originalLines.length > 0 && originalLines[originalLines.length - 1] === "") { |
| 313 | originalLines.pop() |
| 314 | } |
| 315 | |
| 316 | const replacements = computeReplacements(originalLines, filePath, chunks) |
| 317 | let newLines = applyReplacements(originalLines, replacements) |
| 318 | |
| 319 | // Ensure trailing newline |
| 320 | if (newLines.length === 0 || newLines[newLines.length - 1] !== "") { |
| 321 | newLines.push("") |
| 322 | } |
| 323 | |
| 324 | const newContent = newLines.join("\n") |
| 325 | |
| 326 | // Generate unified diff |
| 327 | const unifiedDiff = generateUnifiedDiff(originalContent, newContent) |
| 328 | |
| 329 | return { |
| 330 | unified_diff: unifiedDiff, |
| 331 | content: newContent, |
| 332 | } |
| 333 | } |
| 334 | |
| 335 | function computeReplacements( |
| 336 | originalLines: string[], |
no test coverage detected