-
Notifications
You must be signed in to change notification settings - Fork 146
Expand file tree
/
Copy pathsearchAndReplaceTool.ts
More file actions
282 lines (244 loc) · 9.4 KB
/
searchAndReplaceTool.ts
File metadata and controls
282 lines (244 loc) · 9.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
// Core Node.js imports
import path from "path"
import fs from "fs/promises"
import delay from "delay"
// Internal imports
import { Task } from "../task/Task"
import { AskApproval, HandleError, PushToolResult, RemoveClosingTag, ToolUse } from "../../shared/tools"
import { formatResponse } from "../prompts/responses"
import { ClineSayTool } from "../../shared/ExtensionMessage"
import { getReadablePath } from "../../utils/path"
import { fileExistsAtPath } from "../../utils/fs"
import { RecordSource } from "../context-tracking/FileContextTrackerTypes"
import { DEFAULT_WRITE_DELAY_MS } from "@roo-code/types"
import { EXPERIMENT_IDS, experiments } from "../../shared/experiments"
/**
* Tool for performing search and replace operations on files
* Supports regex and case-sensitive/insensitive matching
*/
/**
* Validates required parameters for search and replace operation
*/
async function validateParams(
cline: Task,
relPath: string | undefined,
search: string | undefined,
replace: string | undefined,
pushToolResult: PushToolResult,
): Promise<boolean> {
if (!relPath) {
cline.consecutiveMistakeCount++
cline.recordToolError("search_and_replace")
pushToolResult(await cline.sayAndCreateMissingParamError("search_and_replace", "path"))
return false
}
if (!search) {
cline.consecutiveMistakeCount++
cline.recordToolError("search_and_replace")
pushToolResult(await cline.sayAndCreateMissingParamError("search_and_replace", "search"))
return false
}
if (replace === undefined) {
cline.consecutiveMistakeCount++
cline.recordToolError("search_and_replace")
pushToolResult(await cline.sayAndCreateMissingParamError("search_and_replace", "replace"))
return false
}
return true
}
/**
* Performs search and replace operations on a file
* @param cline - Cline instance
* @param block - Tool use parameters
* @param askApproval - Function to request user approval
* @param handleError - Function to handle errors
* @param pushToolResult - Function to push tool results
* @param removeClosingTag - Function to remove closing tags
*/
export async function searchAndReplaceTool(
cline: Task,
block: ToolUse,
askApproval: AskApproval,
handleError: HandleError,
pushToolResult: PushToolResult,
removeClosingTag: RemoveClosingTag,
): Promise<void> {
// Extract and validate parameters
const relPath: string | undefined = block.params.path
const search: string | undefined = block.params.search
const replace: string | undefined = block.params.replace
const useRegex: boolean = block.params.use_regex === "true"
const ignoreCase: boolean = block.params.ignore_case === "true"
const startLine: number | undefined = block.params.start_line ? parseInt(block.params.start_line, 10) : undefined
const endLine: number | undefined = block.params.end_line ? parseInt(block.params.end_line, 10) : undefined
try {
// Handle partial tool use
if (block.partial) {
const partialMessageProps = {
tool: "searchAndReplace" as const,
path: getReadablePath(cline.cwd, removeClosingTag("path", relPath)),
search: removeClosingTag("search", search),
replace: removeClosingTag("replace", replace),
useRegex: block.params.use_regex === "true",
ignoreCase: block.params.ignore_case === "true",
startLine,
endLine,
}
await cline.ask("tool", JSON.stringify(partialMessageProps), block.partial).catch(() => {})
return
}
// Validate required parameters
if (!(await validateParams(cline, relPath, search, replace, pushToolResult))) {
return
}
// At this point we know relPath, search and replace are defined
const validRelPath = relPath as string
const validSearch = search as string
const validReplace = replace as string
const sharedMessageProps: ClineSayTool = {
tool: "searchAndReplace",
path: getReadablePath(cline.cwd, validRelPath),
search: validSearch,
replace: validReplace,
useRegex: useRegex,
ignoreCase: ignoreCase,
startLine: startLine,
endLine: endLine,
}
const accessAllowed = cline.rooIgnoreController?.validateAccess(validRelPath)
if (!accessAllowed) {
await cline.say("rooignore_error", validRelPath)
pushToolResult(formatResponse.toolError(formatResponse.rooIgnoreError(validRelPath)))
return
}
// Check if file is write-protected
const isWriteProtected = cline.rooProtectedController?.isWriteProtected(validRelPath) || false
const absolutePath = path.resolve(cline.cwd, validRelPath)
const fileExists = await fileExistsAtPath(absolutePath)
if (!fileExists) {
cline.consecutiveMistakeCount++
cline.recordToolError("search_and_replace")
const formattedError = formatResponse.toolError(
`File does not exist at path: ${absolutePath}\nThe specified file could not be found. Please verify the file path and try again.`,
)
await cline.say("error", formattedError)
pushToolResult(formattedError)
return
}
// Reset consecutive mistakes since all validations passed
cline.consecutiveMistakeCount = 0
// Read and process file content
let fileContent: string
try {
fileContent = await fs.readFile(absolutePath, "utf-8")
} catch (error) {
cline.consecutiveMistakeCount++
cline.recordToolError("search_and_replace")
const errorMessage = `Error reading file: ${absolutePath}\nFailed to read the file content: ${
error instanceof Error ? error.message : String(error)
}\nPlease verify file permissions and try again.`
const formattedError = formatResponse.toolError(errorMessage)
await cline.say("error", formattedError)
pushToolResult(formattedError)
return
}
// Create search pattern and perform replacement
const flags = ignoreCase ? "gi" : "g"
const searchPattern = useRegex ? new RegExp(validSearch, flags) : new RegExp(escapeRegExp(validSearch), flags)
let newContent: string
if (startLine !== undefined || endLine !== undefined) {
// Handle line-specific replacement
const lines = fileContent.split("\n")
const start = Math.max((startLine ?? 1) - 1, 0)
const end = Math.min((endLine ?? lines.length) - 1, lines.length - 1)
// Get content before and after target section
const beforeLines = lines.slice(0, start)
const afterLines = lines.slice(end + 1)
// Get and modify target section
const targetContent = lines.slice(start, end + 1).join("\n")
const modifiedContent = targetContent.replace(searchPattern, validReplace)
const modifiedLines = modifiedContent.split("\n")
// Reconstruct full content
newContent = [...beforeLines, ...modifiedLines, ...afterLines].join("\n")
} else {
// Global replacement
newContent = fileContent.replace(searchPattern, validReplace)
}
// Initialize diff view
cline.diffViewProvider.editType = "modify"
cline.diffViewProvider.originalContent = fileContent
// Generate and validate diff
const diff = formatResponse.createPrettyPatch(validRelPath, fileContent, newContent)
if (!diff) {
pushToolResult(`No changes needed for '${relPath}'`)
await cline.diffViewProvider.reset()
return
}
// Check if preventFocusDisruption experiment is enabled
const provider = cline.providerRef.deref()
const state = await provider?.getState()
const diagnosticsEnabled = state?.diagnosticsEnabled ?? true
const writeDelayMs = state?.writeDelayMs ?? DEFAULT_WRITE_DELAY_MS
const isPreventFocusDisruptionEnabled = experiments.isEnabled(
state?.experiments ?? {},
EXPERIMENT_IDS.PREVENT_FOCUS_DISRUPTION,
)
const completeMessage = JSON.stringify({
...sharedMessageProps,
diff,
isProtected: isWriteProtected,
} satisfies ClineSayTool)
// Show diff view if focus disruption prevention is disabled
if (!isPreventFocusDisruptionEnabled) {
await cline.diffViewProvider.open(validRelPath)
await cline.diffViewProvider.update(newContent, true)
cline.diffViewProvider.scrollToFirstDiff()
}
const didApprove = await askApproval("tool", completeMessage, undefined, isWriteProtected)
if (!didApprove) {
// Revert changes if diff view was shown
if (!isPreventFocusDisruptionEnabled) {
await cline.diffViewProvider.revertChanges()
}
pushToolResult("Changes were rejected by the user.")
await cline.diffViewProvider.reset()
return
}
// Save the changes
if (isPreventFocusDisruptionEnabled) {
// Direct file write without diff view or opening the file
await cline.diffViewProvider.saveDirectly(validRelPath, newContent, false, diagnosticsEnabled, writeDelayMs)
} else {
// Call saveChanges to update the DiffViewProvider properties
await cline.diffViewProvider.saveChanges(diagnosticsEnabled, writeDelayMs)
}
// Track file edit operation
if (relPath) {
await cline.fileContextTracker.trackFileContext(relPath, "roo_edited" as RecordSource)
}
cline.didEditFile = true
// Get the formatted response message
const message = await cline.diffViewProvider.pushToolWriteResult(
cline,
cline.cwd,
false, // Always false for search_and_replace
)
pushToolResult(message)
// Record successful tool usage and cleanup
cline.recordToolUsage("search_and_replace")
await cline.diffViewProvider.reset()
// Process any queued messages after file edit completes
cline.processQueuedMessages()
} catch (error) {
handleError("search and replace", error)
await cline.diffViewProvider.reset()
}
}
/**
* Escapes special regex characters in a string
* @param input String to escape regex characters in
* @returns Escaped string safe for regex pattern matching
*/
function escapeRegExp(input: string): string {
return input.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")
}