(params: {
parameters: unknown
cwd: string
fs: CodebuffFileSystem
})
| 599 | } |
| 600 | |
| 601 | export async function applyPatchTool(params: { |
| 602 | parameters: unknown |
| 603 | cwd: string |
| 604 | fs: CodebuffFileSystem |
| 605 | }): Promise<ApplyPatchResult> { |
| 606 | const { parameters, cwd, fs } = params |
| 607 | const operation = parseOperation(parameters) |
| 608 | |
| 609 | if (!operation) { |
| 610 | return [errorResult('Missing or invalid operation object.')] |
| 611 | } |
| 612 | |
| 613 | try { |
| 614 | if (hasTraversal(operation.path)) { |
| 615 | throw new Error(`Invalid path: ${operation.path}`) |
| 616 | } |
| 617 | |
| 618 | const fullPath = path.join(cwd, operation.path) |
| 619 | |
| 620 | if (operation.type === 'create_file') { |
| 621 | const sanitizedDiff = sanitizeUnifiedDiff(operation.diff) |
| 622 | const { result: content } = applyDiff('', sanitizedDiff, 'create') |
| 623 | |
| 624 | await fs.mkdir(path.dirname(fullPath), { recursive: true }) |
| 625 | await fs.writeFile(fullPath, content) |
| 626 | |
| 627 | return [successResult(operation.path, 'add')] |
| 628 | } |
| 629 | |
| 630 | if (operation.type === 'delete_file') { |
| 631 | await fs.unlink(fullPath) |
| 632 | return [successResult(operation.path, 'delete')] |
| 633 | } |
| 634 | |
| 635 | const sanitizedDiff = sanitizeUnifiedDiff(operation.diff) |
| 636 | const oldContent = await fs.readFile(fullPath, 'utf-8') |
| 637 | const patchResult = tryApplyPatchWithFallbacks({ |
| 638 | oldContent, |
| 639 | diff: sanitizedDiff, |
| 640 | }) |
| 641 | |
| 642 | if (!patchResult.patched) { |
| 643 | return [ |
| 644 | errorResult( |
| 645 | formatPatchFailureMessage({ |
| 646 | path: operation.path, |
| 647 | attemptedStrategies: patchResult.attemptedStrategies, |
| 648 | lastError: patchResult.lastError, |
| 649 | }), |
| 650 | ), |
| 651 | ] |
| 652 | } |
| 653 | |
| 654 | await fs.writeFile( |
| 655 | fullPath, |
| 656 | preserveOriginalLineEndings({ |
| 657 | original: oldContent, |
| 658 | patched: patchResult.patched, |
no test coverage detected