Elffuss BraidHub

kikocis/continue public

89cedaf513f2 · 5.5 KiBRawPermalink
1import * as fs from "fs";
2import path from "path";
3
4import { validateSingleEdit } from "core/edit/searchAndReplace/findAndReplaceUtils.js";
5import { executeFindAndReplace } from "core/edit/searchAndReplace/performReplace.js";
6import { throwIfFileIsSecurityConcern } from "core/indexing/ignore.js";
7import { ContinueError, ContinueErrorReason } from "core/util/errors.js";
8
9import { telemetryService } from "../telemetry/telemetryService.js";
10import {
11 calculateLinesOfCodeDiff,
12 getLanguageFromFilePath,
13} from "../telemetry/utils.js";
14
15import { EditOperation } from "./multiEdit.js";
16import { readFilesSet, readFileTool } from "./readFile.js";
17import { Tool } from "./types.js";
18import { generateDiff } from "./writeFile.js";
19
20export function validateAndResolveFilePath(args: any): {
21 originalPath: string;
22 resolvedPath: string;
23} {
24 const { file_path } = args;
25
26 if (!file_path) {
27 throw new ContinueError(
28 ContinueErrorReason.FindAndReplaceMissingFilepath,
29 "file_path is required",
30 );
31 }
32
33 const absolutePath = path.isAbsolute(file_path)
34 ? file_path
35 : path.resolve(process.cwd(), file_path);
36
37 const resolvedPath = fs.realpathSync(absolutePath);
38
39 throwIfFileIsSecurityConcern(resolvedPath);
40
41 // Check if file exists
42 if (!fs.existsSync(resolvedPath)) {
43 throw new ContinueError(
44 ContinueErrorReason.FileNotFound,
45 `File ${file_path} does not exist`,
46 );
47 }
48
49 // Check if file has been read
50 if (!readFilesSet.has(resolvedPath)) {
51 throw new ContinueError(
52 ContinueErrorReason.EditToolFileNotRead,
53 `You must use the ${readFileTool.name} tool to read ${file_path} before editing it.`,
54 );
55 }
56
57 return { originalPath: file_path, resolvedPath: resolvedPath };
58}
59
60export interface EditArgs extends EditOperation {
61 file_path: string;
62}
63
64export const editTool: Tool = {
65 name: "Edit",
66 displayName: "Edit",
67 readonly: false,
68 isBuiltIn: true,
69 description: `Performs exact string replacements in a file.
70
71USAGE:
72- ALWAYS use the \`${readFileTool.name}\` tool just before making edits, to understand the file's up-to-date contents and context.
73- When editing text from ${readFileTool.name} tool output, ensure you preserve exact whitespace/indentation.
74- Always prefer editing existing files in the codebase. NEVER write new files unless explicitly required.
75- Only use emojis if the user explicitly requests it. Avoid adding emojis to files unless asked.
76- Use \`replace_all\` for replacing and renaming strings across the file. This parameter is useful if you want to rename a variable, for instance.
77
78WARNINGS:
79- When not using \`replace_all\`, the edit will FAIL if \`old_string\` is not unique in the file. Either provide a larger string with more surrounding context to make it unique or use \`replace_all\` to change every instance of \`old_string\`.
80- The edit will FAIL if you have not recently used the \`${readFileTool.name}\` tool to view up-to-date file contents.`,
81 parameters: {
82 file_path: {
83 type: "string",
84 description: "The absolute path to the file to modify",
85 required: true,
86 },
87 old_string: {
88 type: "string",
89 description:
90 "The text to replace - must be exact including whitespace/indentation",
91 required: true,
92 },
93 new_string: {
94 type: "string",
95 description:
96 "The text to replace it with (MUST be different from old_string)",
97 required: true,
98 },
99 replace_all: {
100 type: "boolean",
101 description: "Replace all occurences of old_string (default false)",
102 required: false,
103 },
104 },
105 preprocess: async (args) => {
106 const { old_string, new_string, replace_all = false } = args as EditArgs;
107
108 const { resolvedPath } = validateAndResolveFilePath(args);
109
110 validateSingleEdit(old_string, new_string);
111
112 const oldContent = fs.readFileSync(resolvedPath, "utf-8");
113 const newContent = executeFindAndReplace(
114 oldContent,
115 old_string,
116 new_string,
117 replace_all,
118 0,
119 );
120
121 // Generate diff for preview
122 const diff = generateDiff(oldContent, newContent, resolvedPath);
123
124 return {
125 args: {
126 resolvedPath,
127 newContent,
128 oldContent,
129 },
130 preview: [
131 {
132 type: "text",
133 content: "Will make the following changes:",
134 },
135 {
136 type: "diff",
137 content: diff,
138 },
139 ],
140 };
141 },
142 run: async (args: {
143 resolvedPath: string;
144 newContent: string;
145 oldContent: string;
146 }) => {
147 try {
148 fs.writeFileSync(args.resolvedPath, args.newContent, "utf-8");
149
150 // Get lines for telemetry
151 const { added, removed } = calculateLinesOfCodeDiff(
152 args.oldContent,
153 args.newContent,
154 );
155 const language = getLanguageFromFilePath(args.resolvedPath);
156
157 if (added > 0) {
158 telemetryService.recordLinesOfCodeModified("added", added, language);
159 }
160 if (removed > 0) {
161 telemetryService.recordLinesOfCodeModified(
162 "removed",
163 removed,
164 language,
165 );
166 }
167
168 // Generate diff for result display
169 const diff = generateDiff(
170 args.oldContent,
171 args.newContent,
172 args.resolvedPath,
173 );
174
175 return `Successfully edited ${args.resolvedPath}\nDiff:\n${diff}`;
176 } catch (error) {
177 if (error instanceof ContinueError) {
178 throw error;
179 }
180 throw new ContinueError(
181 ContinueErrorReason.FileWriteError,
182 `Error: failed to edit ${args.resolvedPath}: ${
183 error instanceof Error ? error.message : String(error)
184 }`,
185 );
186 }
187 },
188};