| 1 | import { EditOperation } from "../../tools/definitions/multiEdit"; |
| 2 | import { ContinueError, ContinueErrorReason } from "../../util/errors"; |
| 3 | import { findSearchMatches } from "./findSearchMatch"; |
| 4 | |
| 5 | export function executeFindAndReplace( |
| 6 | fileContent: string, |
| 7 | oldString: string, |
| 8 | newString: string, |
| 9 | replaceAll: boolean, |
| 10 | editIndex = 0, |
| 11 | ): string { |
| 12 | const matches = findSearchMatches(fileContent, oldString); |
| 13 | |
| 14 | if (matches.length === 0) { |
| 15 | throw new ContinueError( |
| 16 | ContinueErrorReason.FindAndReplaceOldStringNotFound, |
| 17 | `Edit at index ${editIndex}: string not found in file: "${oldString}"`, |
| 18 | ); |
| 19 | } |
| 20 | |
| 21 | if (replaceAll) { |
| 22 | // Apply replacements in reverse order to maintain correct positions |
| 23 | let result = fileContent; |
| 24 | for (let i = matches.length - 1; i >= 0; i--) { |
| 25 | const match = matches[i]; |
| 26 | result = |
| 27 | result.substring(0, match.startIndex) + |
| 28 | newString + |
| 29 | result.substring(match.endIndex); |
| 30 | } |
| 31 | return result; |
| 32 | } else { |
| 33 | // For single replacement, check for multiple matches first |
| 34 | if (matches.length > 1) { |
| 35 | throw new ContinueError( |
| 36 | ContinueErrorReason.FindAndReplaceMultipleOccurrences, |
| 37 | `Edit at index ${editIndex}: String "${oldString}" appears ${matches.length} times in the file. Either provide a more specific string with surrounding context to make it unique, or use replace_all=true to replace all occurrences.`, |
| 38 | ); |
| 39 | } |
| 40 | |
| 41 | // Apply single replacement |
| 42 | const match = matches[0]; |
| 43 | return ( |
| 44 | fileContent.substring(0, match.startIndex) + |
| 45 | newString + |
| 46 | fileContent.substring(match.endIndex) |
| 47 | ); |
| 48 | } |
| 49 | } |
| 50 | |
| 51 | export function executeMultiFindAndReplace( |
| 52 | fileContent: string, |
| 53 | edits: EditOperation[], |
| 54 | ): string { |
| 55 | let result = fileContent; |
| 56 | |
| 57 | // Apply edits in sequence |
| 58 | for (let editIndex = 0; editIndex < edits.length; editIndex++) { |
| 59 | const edit = edits[editIndex]; |
| 60 | result = executeFindAndReplace( |
| 61 | result, |
| 62 | edit.old_string, |
| 63 | edit.new_string, |
| 64 | edit.replace_all ?? false, |
| 65 | editIndex, |
| 66 | ); |
| 67 | } |
| 68 | |
| 69 | return result; |
| 70 | } |