| 1 | import { IDE } from "core"; |
| 2 | import { validateSingleEdit } from "core/edit/searchAndReplace/findAndReplaceUtils"; |
| 3 | import { executeFindAndReplace } from "core/edit/searchAndReplace/performReplace"; |
| 4 | import { ContinueError, ContinueErrorReason } from "core/util/errors"; |
| 5 | import { resolveRelativePathInDir } from "core/util/ideUtils"; |
| 6 | import { v4 as uuid } from "uuid"; |
| 7 | import { applyForEditTool } from "../../redux/thunks/handleApplyStateUpdate"; |
| 8 | import { ClientToolImpl } from "./callClientTool"; |
| 9 | |
| 10 | export async function validateSearchAndReplaceFilepath( |
| 11 | filepath: any, |
| 12 | ide: IDE, |
| 13 | ) { |
| 14 | if (!filepath || typeof filepath !== "string") { |
| 15 | throw new ContinueError( |
| 16 | ContinueErrorReason.FindAndReplaceMissingFilepath, |
| 17 | "filepath (string) is required", |
| 18 | ); |
| 19 | } |
| 20 | const resolvedFilepath = await resolveRelativePathInDir(filepath, ide); |
| 21 | if (!resolvedFilepath) { |
| 22 | throw new ContinueError( |
| 23 | ContinueErrorReason.FileNotFound, |
| 24 | `File ${filepath} does not exist`, |
| 25 | ); |
| 26 | } |
| 27 | return resolvedFilepath; |
| 28 | } |
| 29 | |
| 30 | export const singleFindAndReplaceImpl: ClientToolImpl = async ( |
| 31 | args, |
| 32 | toolCallId, |
| 33 | extras, |
| 34 | ) => { |
| 35 | const { |
| 36 | filepath, |
| 37 | old_string, |
| 38 | new_string, |
| 39 | replace_all = false, |
| 40 | editingFileContents, |
| 41 | } = args; |
| 42 | |
| 43 | const resolvedUri = await validateSearchAndReplaceFilepath( |
| 44 | filepath, |
| 45 | extras.ideMessenger.ide, |
| 46 | ); |
| 47 | validateSingleEdit(old_string, new_string); |
| 48 | |
| 49 | // Read the current file content |
| 50 | const originalContent = |
| 51 | editingFileContents ?? |
| 52 | (await extras.ideMessenger.ide.readFile(resolvedUri)); |
| 53 | |
| 54 | // Perform the find and replace operation |
| 55 | const newContent = executeFindAndReplace( |
| 56 | originalContent, |
| 57 | old_string, |
| 58 | new_string, |
| 59 | replace_all, |
| 60 | 0, |
| 61 | ); |
| 62 | |
| 63 | // Apply the changes to the file |
| 64 | const streamId = uuid(); |
| 65 | void extras.dispatch( |
| 66 | applyForEditTool({ |
| 67 | streamId, |
| 68 | toolCallId, |
| 69 | text: newContent, |
| 70 | filepath: resolvedUri, |
| 71 | isSearchAndReplace: true, |
| 72 | }), |
| 73 | ); |
| 74 | |
| 75 | // Return success - applyToFile will handle the completion state |
| 76 | return { |
| 77 | respondImmediately: false, // Let apply state handle completion |
| 78 | output: undefined, |
| 79 | }; |
| 80 | }; |