Elffuss BraidHub

kikocis/continue public

f93f67ceefea · 2.5 KiBRawPermalink
1import { findSearchMatch } from "core/edit/searchAndReplace/findSearchMatch";
2import { parseAllSearchReplaceBlocks } from "core/edit/searchAndReplace/parseSearchReplaceBlock";
3import { resolveRelativePathInDir } from "core/util/ideUtils";
4import { v4 as uuid } from "uuid";
5import { ClientToolImpl } from "./callClientTool";
6
7export const searchReplaceToolImpl: ClientToolImpl = async (
8 args,
9 toolCallId,
10 extras,
11) => {
12 const { filepath, diff } = args;
13
14 const streamId = uuid();
15
16 // Resolve the file path
17 const resolvedFilepath = await resolveRelativePathInDir(
18 filepath,
19 extras.ideMessenger.ide,
20 );
21 if (!resolvedFilepath) {
22 throw new Error(`File ${filepath} does not exist`);
23 }
24
25 // Parse all search/replace blocks from the diff content
26 const blocks = parseAllSearchReplaceBlocks(diff);
27
28 if (blocks.length === 0) {
29 throw new Error("No complete search/replace blocks found");
30 }
31
32 try {
33 // Read the current file content
34 const originalContent =
35 await extras.ideMessenger.ide.readFile(resolvedFilepath);
36 let currentContent = originalContent;
37
38 // Apply all replacements sequentially to build the final content
39 for (let i = 0; i < blocks.length; i++) {
40 const block = blocks[i];
41 const { searchContent, replaceContent } = block;
42
43 // Find the search content in the current state of the file
44 const match = findSearchMatch(currentContent, searchContent || "");
45 if (!match) {
46 throw new Error(
47 `Search content not found in block ${i + 1}:\n${searchContent}`,
48 );
49 }
50
51 // Apply the replacement
52 currentContent =
53 currentContent.substring(0, match.startIndex) +
54 (replaceContent || "") +
55 currentContent.substring(match.endIndex);
56 }
57
58 // Single applyToFile call with all accumulated changes
59 // This works becaues of our logic in `applyCodeBlock` that determines
60 // that the full file rewrite here can be applied instantly, so the diff
61 // lines are just st
62 await extras.ideMessenger.request("applyToFile", {
63 streamId,
64 toolCallId,
65 text: currentContent,
66 filepath: resolvedFilepath,
67 isSearchAndReplace: true,
68 });
69
70 // Return success - applyToFile will handle the completion state
71 return {
72 respondImmediately: false, // Let apply state handle completion
73 output: undefined,
74 };
75 } catch (error) {
76 throw new Error(
77 `Failed to apply search and replace: ${error instanceof Error ? error.message : String(error)}`,
78 );
79 }
80};