From 00c4527a1b4177699b4d512053dff2578572676f Mon Sep 17 00:00:00 2001 From: Anas Sulaiman Date: Tue, 10 Jun 2025 18:05:11 +0000 Subject: [PATCH] unify diff generation before and after an edit --- packages/core/src/tools/edit.ts | 58 +++++++-------------------------- 1 file changed, 11 insertions(+), 47 deletions(-) diff --git a/packages/core/src/tools/edit.ts b/packages/core/src/tools/edit.ts index cb569f80..a49b8d83 100644 --- a/packages/core/src/tools/edit.ts +++ b/packages/core/src/tools/edit.ts @@ -298,62 +298,26 @@ Expectation for required parameters: ); return false; } - let currentContent: string | null = null; - let fileExists = false; - let finalNewString = params.new_string; - let finalOldString = params.old_string; - let occurrences = 0; + let editData: CalculatedEdit; try { - currentContent = fs.readFileSync(params.file_path, 'utf8'); - // Normalize line endings to LF for consistent processing. - currentContent = currentContent.replace(/\r\n/g, '\n'); - fileExists = true; - } catch (err: unknown) { - if (isNodeError(err) && err.code === 'ENOENT') { - fileExists = false; - } else { - console.error(`Error reading file for confirmation diff: ${err}`); - return false; - } + editData = await this.calculateEdit(params, abortSignal); + } catch (error) { + const errorMsg = error instanceof Error ? error.message : String(error); + console.log(`Error preparing edit: ${errorMsg}`); + return false; } - if (params.old_string === '' && !fileExists) { - // Creating new file, newContent is just params.new_string - } else if (!fileExists) { - return false; // Cannot edit non-existent file if old_string is not empty - } else if (currentContent !== null) { - const correctedEdit = await ensureCorrectEdit( - currentContent, - params, - this.client, - abortSignal, - ); - finalOldString = correctedEdit.params.old_string; - finalNewString = correctedEdit.params.new_string; - occurrences = correctedEdit.occurrences; - - const expectedReplacements = params.expected_replacements ?? 1; - if (occurrences === 0 || occurrences !== expectedReplacements) { - return false; - } - } else { - return false; // Should not happen + if (editData.error) { + console.log(`Error: ${editData.error.display}`); + return false; } - const isNewFileScenario = params.old_string === '' && !fileExists; - const newContent = this._applyReplacement( - currentContent, - finalOldString, - finalNewString, - isNewFileScenario, - ); - const fileName = path.basename(params.file_path); const fileDiff = Diff.createPatch( fileName, - currentContent ?? '', - newContent, + editData.currentContent ?? '', + editData.newContent, 'Current', 'Proposed', DEFAULT_DIFF_OPTIONS,