unify diff generation before and after an edit

This commit is contained in:
Anas Sulaiman 2025-06-10 18:05:11 +00:00 committed by Anas H. Sulaiman
parent 5bab5a7378
commit 00c4527a1b
1 changed files with 11 additions and 47 deletions

View File

@ -298,62 +298,26 @@ Expectation for required parameters:
); );
return false; 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 { try {
currentContent = fs.readFileSync(params.file_path, 'utf8'); editData = await this.calculateEdit(params, abortSignal);
// Normalize line endings to LF for consistent processing. } catch (error) {
currentContent = currentContent.replace(/\r\n/g, '\n'); const errorMsg = error instanceof Error ? error.message : String(error);
fileExists = true; console.log(`Error preparing edit: ${errorMsg}`);
} catch (err: unknown) { return false;
if (isNodeError(err) && err.code === 'ENOENT') {
fileExists = false;
} else {
console.error(`Error reading file for confirmation diff: ${err}`);
return false;
}
} }
if (params.old_string === '' && !fileExists) { if (editData.error) {
// Creating new file, newContent is just params.new_string console.log(`Error: ${editData.error.display}`);
} else if (!fileExists) { return false;
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
} }
const isNewFileScenario = params.old_string === '' && !fileExists;
const newContent = this._applyReplacement(
currentContent,
finalOldString,
finalNewString,
isNewFileScenario,
);
const fileName = path.basename(params.file_path); const fileName = path.basename(params.file_path);
const fileDiff = Diff.createPatch( const fileDiff = Diff.createPatch(
fileName, fileName,
currentContent ?? '', editData.currentContent ?? '',
newContent, editData.newContent,
'Current', 'Current',
'Proposed', 'Proposed',
DEFAULT_DIFF_OPTIONS, DEFAULT_DIFF_OPTIONS,