Changesets · Branches · Tags · Compare
| Changeset | 86e71fea71da3ab1f8d990bdd798bc6581c28cd17d9d76e6e85294de8136c9ef |
|---|---|
| Author | Dallin Romney <dallinromney@gmail.com> · 2025-08-29 15:18 -07:00 |
| Committer | GitHub <noreply@github.com> · 2025-08-29 15:18 -07:00 |
| Parents | 59947ce7bb53 |
20 files changed
deleted core/edit/searchAndReplace/findSearchMatch.strategy.test.ts +0 −618
| @@ -1,618 +0,0 @@ | ||
| 1 | -import { findSearchMatch, SearchMatchResult } from "./findSearchMatch"; | |
| 2 | - | |
| 3 | -/** | |
| 4 | - * Helper function to perform a replacement using the match result | |
| 5 | - * This simulates what the actual replacement tool would do | |
| 6 | - */ | |
| 7 | -function performReplacement( | |
| 8 | - fileContent: string, | |
| 9 | - match: SearchMatchResult, | |
| 10 | - replacement: string, | |
| 11 | -): string { | |
| 12 | - return ( | |
| 13 | - fileContent.substring(0, match.startIndex) + | |
| 14 | - replacement + | |
| 15 | - fileContent.substring(match.endIndex) | |
| 16 | - ); | |
| 17 | -} | |
| 18 | - | |
| 19 | -/** | |
| 20 | - * Helper function to test a specific strategy by crafting inputs that | |
| 21 | - * will fail all previous strategies | |
| 22 | - */ | |
| 23 | -function testSpecificStrategy( | |
| 24 | - fileContent: string, | |
| 25 | - searchContent: string, | |
| 26 | - expectedStrategy: string, | |
| 27 | -): SearchMatchResult | null { | |
| 28 | - const result = findSearchMatch(fileContent, searchContent); | |
| 29 | - if (result && result.strategyName !== expectedStrategy) { | |
| 30 | - throw new Error( | |
| 31 | - `Expected strategy ${expectedStrategy} but got ${result.strategyName}`, | |
| 32 | - ); | |
| 33 | - } | |
| 34 | - return result; | |
| 35 | -} | |
| 36 | - | |
| 37 | -/** | |
| 38 | - * Helper function to verify that a match result correctly identifies | |
| 39 | - * the intended content and replacement works properly | |
| 40 | - */ | |
| 41 | -function verifyMatchAndReplacement( | |
| 42 | - fileContent: string, | |
| 43 | - searchContent: string, | |
| 44 | - expectedMatchedText: string, | |
| 45 | - replacementText: string, | |
| 46 | - expectedResult: string, | |
| 47 | -): void { | |
| 48 | - const match = findSearchMatch(fileContent, searchContent); | |
| 49 | - | |
| 50 | - if (!match) { | |
| 51 | - throw new Error("No match found"); | |
| 52 | - } | |
| 53 | - | |
| 54 | - // Verify the match captures the expected text | |
| 55 | - const actualMatchedText = fileContent.substring( | |
| 56 | - match.startIndex, | |
| 57 | - match.endIndex, | |
| 58 | - ); | |
| 59 | - expect(actualMatchedText).toBe(expectedMatchedText); | |
| 60 | - | |
| 61 | - // Verify replacement works correctly | |
| 62 | - const result = performReplacement(fileContent, match, replacementText); | |
| 63 | - expect(result).toBe(expectedResult); | |
| 64 | -} | |
| 65 | - | |
| 66 | -describe("Strategy-specific tests", () => { | |
| 67 | - describe("exactMatch strategy", () => { | |
| 68 | - it("should handle exact match at various positions", () => { | |
| 69 | - const testCases = [ | |
| 70 | - { | |
| 71 | - name: "at start", | |
| 72 | - fileContent: "abc def ghi", | |
| 73 | - searchContent: "abc", | |
| 74 | - expectedStart: 0, | |
| 75 | - expectedEnd: 3, | |
| 76 | - }, | |
| 77 | - { | |
| 78 | - name: "in middle", | |
| 79 | - fileContent: "abc def ghi", | |
| 80 | - searchContent: "def", | |
| 81 | - expectedStart: 4, | |
| 82 | - expectedEnd: 7, | |
| 83 | - }, | |
| 84 | - { | |
| 85 | - name: "at end", | |
| 86 | - fileContent: "abc def ghi", | |
| 87 | - searchContent: "ghi", | |
| 88 | - expectedStart: 8, | |
| 89 | - expectedEnd: 11, | |
| 90 | - }, | |
| 91 | - { | |
| 92 | - name: "entire content", | |
| 93 | - fileContent: "abc def ghi", | |
| 94 | - searchContent: "abc def ghi", | |
| 95 | - expectedStart: 0, | |
| 96 | - expectedEnd: 11, | |
| 97 | - }, | |
| 98 | - ]; | |
| 99 | - | |
| 100 | - testCases.forEach( | |
| 101 | - ({ name, fileContent, searchContent, expectedStart, expectedEnd }) => { | |
| 102 | - const result = testSpecificStrategy( | |
| 103 | - fileContent, | |
| 104 | - searchContent, | |
| 105 | - "exactMatch", | |
| 106 | - ); | |
| 107 | - expect(result).not.toBeNull(); | |
| 108 | - expect(result!.startIndex).toBe(expectedStart); | |
| 109 | - expect(result!.endIndex).toBe(expectedEnd); | |
| 110 | - | |
| 111 | - // Verify the matched content | |
| 112 | - const matchedContent = fileContent.substring( | |
| 113 | - result!.startIndex, | |
| 114 | - result!.endIndex, | |
| 115 | - ); | |
| 116 | - expect(matchedContent).toBe(searchContent); | |
| 117 | - }, | |
| 118 | - ); | |
| 119 | - }); | |
| 120 | - | |
| 121 | - it("should handle multiline exact matches", () => { | |
| 122 | - const fileContent = `line1 | |
| 123 | -line2 | |
| 124 | -line3 | |
| 125 | -line4`; | |
| 126 | - const searchContent = `line2 | |
| 127 | -line3`; | |
| 128 | - | |
| 129 | - const result = testSpecificStrategy( | |
| 130 | - fileContent, | |
| 131 | - searchContent, | |
| 132 | - "exactMatch", | |
| 133 | - ); | |
| 134 | - expect(result).not.toBeNull(); | |
| 135 | - expect(result!.startIndex).toBe(6); // After "line1\n" | |
| 136 | - expect(result!.endIndex).toBe(17); // End of "line3" | |
| 137 | - | |
| 138 | - const matchedContent = fileContent.substring( | |
| 139 | - result!.startIndex, | |
| 140 | - result!.endIndex, | |
| 141 | - ); | |
| 142 | - expect(matchedContent).toBe(searchContent); | |
| 143 | - }); | |
| 144 | - | |
| 145 | - it("should handle content with special characters", () => { | |
| 146 | - const fileContent = `const regex = /[a-z]+/gi; | |
| 147 | -const str = "Hello, World!"; | |
| 148 | -const result = str.match(regex);`; | |
| 149 | - const searchContent = `const str = "Hello, World!";`; | |
| 150 | - | |
| 151 | - const result = testSpecificStrategy( | |
| 152 | - fileContent, | |
| 153 | - searchContent, | |
| 154 | - "exactMatch", | |
| 155 | - ); | |
| 156 | - expect(result).not.toBeNull(); | |
| 157 | - | |
| 158 | - const matchedContent = fileContent.substring( | |
| 159 | - result!.startIndex, | |
| 160 | - result!.endIndex, | |
| 161 | - ); | |
| 162 | - expect(matchedContent).toBe(searchContent); | |
| 163 | - }); | |
| 164 | - | |
| 165 | - it("should verify replacement works correctly for exact matches", () => { | |
| 166 | - verifyMatchAndReplacement( | |
| 167 | - "const a = 1;\nconst b = 2;\nconst c = 3;", | |
| 168 | - "const b = 2;", | |
| 169 | - "const b = 2;", | |
| 170 | - "const b = 42;", | |
| 171 | - "const a = 1;\nconst b = 42;\nconst c = 3;", | |
| 172 | - ); | |
| 173 | - }); | |
| 174 | - | |
| 175 | - it("should handle Windows-style line endings", () => { | |
| 176 | - const fileContent = "line1\r\nline2\r\nline3"; | |
| 177 | - const searchContent = "line2"; | |
| 178 | - | |
| 179 | - const result = testSpecificStrategy( | |
| 180 | - fileContent, | |
| 181 | - searchContent, | |
| 182 | - "exactMatch", | |
| 183 | - ); | |
| 184 | - expect(result).not.toBeNull(); | |
| 185 | - expect(result!.startIndex).toBe(7); // After "line1\r\n" | |
| 186 | - expect(result!.endIndex).toBe(12); // End of "line2" | |
| 187 | - }); | |
| 188 | - | |
| 189 | - it("should handle mixed line endings", () => { | |
| 190 | - const fileContent = "line1\nline2\r\nline3\rline4"; | |
| 191 | - const searchContent = "line2\r\nline3"; | |
| 192 | - | |
| 193 | - const result = testSpecificStrategy( | |
| 194 | - fileContent, | |
| 195 | - searchContent, | |
| 196 | - "exactMatch", | |
| 197 | - ); | |
| 198 | - expect(result).not.toBeNull(); | |
| 199 | - | |
| 200 | - const matchedContent = fileContent.substring( | |
| 201 | - result!.startIndex, | |
| 202 | - result!.endIndex, | |
| 203 | - ); | |
| 204 | - expect(matchedContent).toBe(searchContent); | |
| 205 | - }); | |
| 206 | - }); | |
| 207 | - | |
| 208 | - describe("trimmedMatch strategy", () => { | |
| 209 | - it("should match when only whitespace differs at edges", () => { | |
| 210 | - const testCases = [ | |
| 211 | - { | |
| 212 | - name: "leading spaces", | |
| 213 | - fileContent: "abc\n def\nghi", | |
| 214 | - searchContent: " def", | |
| 215 | - trimmedSearch: "def", | |
| 216 | - }, | |
| 217 | - { | |
| 218 | - name: "trailing spaces", | |
| 219 | - fileContent: "abc\ndef \nghi", | |
| 220 | - searchContent: "def ", | |
| 221 | - trimmedSearch: "def", | |
| 222 | - }, | |
| 223 | - { | |
| 224 | - name: "both leading and trailing", | |
| 225 | - fileContent: "abc\n def \nghi", | |
| 226 | - searchContent: " def ", | |
| 227 | - trimmedSearch: "def", | |
| 228 | - }, | |
| 229 | - { | |
| 230 | - name: "tabs and spaces", | |
| 231 | - fileContent: "abc\n\t def \t\nghi", | |
| 232 | - searchContent: "\t def \t", | |
| 233 | - trimmedSearch: "def", | |
| 234 | - }, | |
| 235 | - ]; | |
| 236 | - | |
| 237 | - testCases.forEach( | |
| 238 | - ({ name, fileContent, searchContent, trimmedSearch }) => { | |
| 239 | - const result = findSearchMatch(fileContent, searchContent); | |
| 240 | - expect(result).not.toBeNull(); | |
| 241 | - | |
| 242 | - // For cases where exact match exists, it should be preferred | |
| 243 | - if (fileContent.indexOf(searchContent) !== -1) { | |
| 244 | - expect(result!.strategyName).toBe("exactMatch"); | |
| 245 | - const matchedContent = fileContent.substring( | |
| 246 | - result!.startIndex, | |
| 247 | - result!.endIndex, | |
| 248 | - ); | |
| 249 | - expect(matchedContent).toBe(searchContent); | |
| 250 | - } else { | |
| 251 | - expect(result!.strategyName).toBe("trimmedMatch"); | |
| 252 | - // The match should find the trimmed content with surrounding whitespace | |
| 253 | - const matchedContent = fileContent.substring( | |
| 254 | - result!.startIndex, | |
| 255 | - result!.endIndex, | |
| 256 | - ); | |
| 257 | - expect(matchedContent).toContain(trimmedSearch); | |
| 258 | - } | |
| 259 | - }, | |
| 260 | - ); | |
| 261 | - }); | |
| 262 | - | |
| 263 | - it("should handle multiline content with edge whitespace", () => { | |
| 264 | - const fileContent = `function test() { | |
| 265 | - const x = 1; | |
| 266 | - const y = 2; | |
| 267 | -}`; | |
| 268 | - const searchContent = ` const x = 1; | |
| 269 | - const y = 2; `; | |
| 270 | - | |
| 271 | - const result = findSearchMatch(fileContent, searchContent); | |
| 272 | - expect(result).not.toBeNull(); | |
| 273 | - // Since there's no exact match (trailing spaces don't exist), trimmedMatch should be used | |
| 274 | - expect(result!.strategyName).toBe("trimmedMatch"); | |
| 275 | - }); | |
| 276 | - | |
| 277 | - it("should verify replacement with trimmed matches", () => { | |
| 278 | - const fileContent = "start\n targetContent \nend"; | |
| 279 | - const searchContent = " targetContent "; | |
| 280 | - const replacement = "newContent"; | |
| 281 | - | |
| 282 | - const match = findSearchMatch(fileContent, searchContent); | |
| 283 | - expect(match).not.toBeNull(); | |
| 284 | - expect(match!.strategyName).toBe("trimmedMatch"); | |
| 285 | - | |
| 286 | - const result = performReplacement(fileContent, match!, replacement); | |
| 287 | - expect(result).toBe("start\nnewContent\nend"); | |
| 288 | - }); | |
| 289 | - | |
| 290 | - it("should handle edge case with only whitespace", () => { | |
| 291 | - const fileContent = " \n \n "; | |
| 292 | - const searchContent = " \n "; | |
| 293 | - | |
| 294 | - const result = findSearchMatch(fileContent, searchContent); | |
| 295 | - expect(result).not.toBeNull(); | |
| 296 | - // Should find exact match since the content matches exactly | |
| 297 | - expect(result!.strategyName).toBe("exactMatch"); | |
| 298 | - }); | |
| 299 | - }); | |
| 300 | - | |
| 301 | - describe("whitespaceIgnoredMatch strategy", () => { | |
| 302 | - it("should match content with different indentation", () => { | |
| 303 | - const fileContent = `function test() { | |
| 304 | - const x = 1; | |
| 305 | - if (x > 0) { | |
| 306 | - return true; | |
| 307 | - } | |
| 308 | -}`; | |
| 309 | - const searchContent = `const x=1; | |
| 310 | -if(x>0){ | |
| 311 | -return true; | |
| 312 | -}`; | |
| 313 | - | |
| 314 | - const result = findSearchMatch(fileContent, searchContent); | |
| 315 | - expect(result).not.toBeNull(); | |
| 316 | - expect(result!.strategyName).toBe("whitespaceIgnoredMatch"); | |
| 317 | - | |
| 318 | - // Verify the match covers the intended code block | |
| 319 | - const matchedContent = fileContent.substring( | |
| 320 | - result!.startIndex, | |
| 321 | - result!.endIndex, | |
| 322 | - ); | |
| 323 | - expect(matchedContent).toContain("const x = 1"); | |
| 324 | - expect(matchedContent).toContain("return true"); | |
| 325 | - }); | |
| 326 | - | |
| 327 | - it("should handle complex whitespace variations", () => { | |
| 328 | - const testCases = [ | |
| 329 | - { | |
| 330 | - name: "spaces vs tabs", | |
| 331 | - fileContent: "if\t(\tcondition\t)\t{\n\treturn\ttrue;\n}", | |
| 332 | - searchContent: "if (condition) { return true; }", | |
| 333 | - }, | |
| 334 | - { | |
| 335 | - name: "multiple spaces collapsed", | |
| 336 | - fileContent: "const result = calculate( x , y );", | |
| 337 | - searchContent: "const result=calculate(x,y);", | |
| 338 | - }, | |
| 339 | - { | |
| 340 | - name: "newlines removed", | |
| 341 | - fileContent: "function\ntest\n(\n)\n{\nreturn\n1\n;\n}", | |
| 342 | - searchContent: "function test(){return 1;}", | |
| 343 | - }, | |
| 344 | - ]; | |
| 345 | - | |
| 346 | - testCases.forEach(({ name, fileContent, searchContent }) => { | |
| 347 | - const result = findSearchMatch(fileContent, searchContent); | |
| 348 | - expect(result).not.toBeNull(); | |
| 349 | - expect(result!.strategyName).toBe("whitespaceIgnoredMatch"); | |
| 350 | - | |
| 351 | - // Verify the entire content is matched | |
| 352 | - const matchedContent = fileContent.substring( | |
| 353 | - result!.startIndex, | |
| 354 | - result!.endIndex, | |
| 355 | - ); | |
| 356 | - expect(matchedContent.replace(/\s/g, "")).toBe( | |
| 357 | - searchContent.replace(/\s/g, ""), | |
| 358 | - ); | |
| 359 | - }); | |
| 360 | - }); | |
| 361 | - | |
| 362 | - it("should handle partial matches with whitespace differences", () => { | |
| 363 | - const fileContent = `class Example { | |
| 364 | - constructor(name) { | |
| 365 | - this.name = name; | |
| 366 | - this.items = []; | |
| 367 | - } | |
| 368 | - | |
| 369 | - addItem(item) { | |
| 370 | - this.items.push(item); | |
| 371 | - } | |
| 372 | -}`; | |
| 373 | - const searchContent = `constructor(name){this.name=name;this.items=[];}`; | |
| 374 | - | |
| 375 | - const result = findSearchMatch(fileContent, searchContent); | |
| 376 | - expect(result).not.toBeNull(); | |
| 377 | - expect(result!.strategyName).toBe("whitespaceIgnoredMatch"); | |
| 378 | - | |
| 379 | - // The match should cover the constructor method | |
| 380 | - const matchedContent = fileContent.substring( | |
| 381 | - result!.startIndex, | |
| 382 | - result!.endIndex, | |
| 383 | - ); | |
| 384 | - expect(matchedContent).toContain("constructor"); | |
| 385 | - expect(matchedContent).toContain("this.items = []"); | |
| 386 | - }); | |
| 387 | - | |
| 388 | - it("should verify replacement with whitespace-ignored matches", () => { | |
| 389 | - const fileContent = `function calculate ( a , b ) { | |
| 390 | - return a + b ; | |
| 391 | -}`; | |
| 392 | - const searchContent = `function calculate(a,b){return a+b;}`; | |
| 393 | - const replacement = `function calculate(x, y) { | |
| 394 | - return x + y; | |
| 395 | -}`; | |
| 396 | - | |
| 397 | - const match = findSearchMatch(fileContent, searchContent); | |
| 398 | - expect(match).not.toBeNull(); | |
| 399 | - expect(match!.strategyName).toBe("whitespaceIgnoredMatch"); | |
| 400 | - | |
| 401 | - const result = performReplacement(fileContent, match!, replacement); | |
| 402 | - expect(result).toBe(replacement); | |
| 403 | - }); | |
| 404 | - | |
| 405 | - it("should handle edge cases with empty content after whitespace removal", () => { | |
| 406 | - const fileContent = " \n\t\r\n "; | |
| 407 | - const searchContent = " \n "; | |
| 408 | - | |
| 409 | - const result = findSearchMatch(fileContent, searchContent); | |
| 410 | - // Since search content doesn't exist in file but trims to empty, should return emptySearch | |
| 411 | - expect(result).not.toBeNull(); | |
| 412 | - expect(result!.strategyName).toBe("emptySearch"); | |
| 413 | - }); | |
| 414 | - | |
| 415 | - it("should match correctly when multiple potential matches exist", () => { | |
| 416 | - const fileContent = `const a=1; | |
| 417 | -const a = 1 ; | |
| 418 | -const a = 1;`; | |
| 419 | - const searchContent = "const a = 1;"; | |
| 420 | - | |
| 421 | - const result = findSearchMatch(fileContent, searchContent); | |
| 422 | - expect(result).not.toBeNull(); | |
| 423 | - // Should find the exact match first (third occurrence) | |
| 424 | - expect(result!.strategyName).toBe("exactMatch"); | |
| 425 | - expect(result!.startIndex).toBe(33); // After first two lines | |
| 426 | - }); | |
| 427 | - }); | |
| 428 | - | |
| 429 | - describe("Empty search content", () => { | |
| 430 | - it("should always return position 0 for empty search", () => { | |
| 431 | - const testCases = [ | |
| 432 | - { fileContent: "some content" }, | |
| 433 | - { fileContent: "" }, | |
| 434 | - { fileContent: "line1\nline2\nline3" }, | |
| 435 | - { fileContent: " spaces " }, | |
| 436 | - ]; | |
| 437 | - | |
| 438 | - testCases.forEach(({ fileContent }) => { | |
| 439 | - const result = findSearchMatch(fileContent, ""); | |
| 440 | - expect(result).toEqual({ | |
| 441 | - startIndex: 0, | |
| 442 | - endIndex: 0, | |
| 443 | - strategyName: "emptySearch", | |
| 444 | - }); | |
| 445 | - }); | |
| 446 | - }); | |
| 447 | - | |
| 448 | - it("should treat whitespace-only search as empty", () => { | |
| 449 | - const searchVariants = [" ", "\n\n", "\t\t", " \n\t "]; | |
| 450 | - | |
| 451 | - searchVariants.forEach((searchContent) => { | |
| 452 | - const result = findSearchMatch("test content", searchContent); | |
| 453 | - expect(result).toEqual({ | |
| 454 | - startIndex: 0, | |
| 455 | - endIndex: 0, | |
| 456 | - strategyName: "emptySearch", | |
| 457 | - }); | |
| 458 | - }); | |
| 459 | - }); | |
| 460 | - }); | |
| 461 | - | |
| 462 | - describe("Strategy precedence", () => { | |
| 463 | - it("should always prefer exact match over other strategies", () => { | |
| 464 | - const fileContent = `exact match | |
| 465 | -exact match with spaces | |
| 466 | -exactmatch`; | |
| 467 | - | |
| 468 | - // This should find exact match even though fuzzy would also work | |
| 469 | - const result = findSearchMatch(fileContent, "exact match"); | |
| 470 | - expect(result!.strategyName).toBe("exactMatch"); | |
| 471 | - expect(result!.startIndex).toBe(0); | |
| 472 | - }); | |
| 473 | - | |
| 474 | - it("should prefer trimmed match over whitespace-ignored", () => { | |
| 475 | - const fileContent = " content "; | |
| 476 | - const searchContent = " content "; | |
| 477 | - | |
| 478 | - // Should find exact match | |
| 479 | - const result = findSearchMatch(fileContent, searchContent); | |
| 480 | - expect(result!.strategyName).toBe("exactMatch"); | |
| 481 | - }); | |
| 482 | - | |
| 483 | - it("should prefer whitespace-ignored over fuzzy", () => { | |
| 484 | - const fileContent = "const x = 1;"; | |
| 485 | - const searchContent = "const x=1;"; | |
| 486 | - | |
| 487 | - // Should use whitespace-ignored, not fuzzy | |
| 488 | - const result = findSearchMatch(fileContent, searchContent); | |
| 489 | - expect(result!.strategyName).toBe("whitespaceIgnoredMatch"); | |
| 490 | - }); | |
| 491 | - }); | |
| 492 | - | |
| 493 | - describe("Replacement verification tests", () => { | |
| 494 | - it("should correctly replace content found by each strategy", () => { | |
| 495 | - const testCases = [ | |
| 496 | - { | |
| 497 | - name: "exact match replacement", | |
| 498 | - fileContent: "const a = 1;\nconst b = 2;\nconst c = 3;", | |
| 499 | - searchContent: "const b = 2;", | |
| 500 | - replacement: "const b = 42;", | |
| 501 | - expectedResult: "const a = 1;\nconst b = 42;\nconst c = 3;", | |
| 502 | - expectedStrategy: "exactMatch", | |
| 503 | - }, | |
| 504 | - { | |
| 505 | - name: "trimmed match replacement", | |
| 506 | - fileContent: "start\n target \nend", | |
| 507 | - searchContent: " target ", | |
| 508 | - replacement: "replaced", | |
| 509 | - expectedResult: "start\nreplaced\nend", | |
| 510 | - expectedStrategy: "trimmedMatch", | |
| 511 | - }, | |
| 512 | - { | |
| 513 | - name: "whitespace-ignored replacement", | |
| 514 | - fileContent: "if ( x > 0 ) { return true; }", | |
| 515 | - searchContent: "if(x>0){return true;}", | |
| 516 | - replacement: "if (x > 0) { return false; }", | |
| 517 | - expectedResult: "if (x > 0) { return false; }", | |
| 518 | - expectedStrategy: "whitespaceIgnoredMatch", | |
| 519 | - }, | |
| 520 | - ]; | |
| 521 | - | |
| 522 | - testCases.forEach( | |
| 523 | - ({ | |
| 524 | - name, | |
| 525 | - fileContent, | |
| 526 | - searchContent, | |
| 527 | - replacement, | |
| 528 | - expectedResult, | |
| 529 | - expectedStrategy, | |
| 530 | - }) => { | |
| 531 | - const match = findSearchMatch(fileContent, searchContent); | |
| 532 | - expect(match).not.toBeNull(); | |
| 533 | - expect(match!.strategyName).toBe(expectedStrategy); | |
| 534 | - | |
| 535 | - const result = performReplacement(fileContent, match!, replacement); | |
| 536 | - expect(result).toBe(expectedResult); | |
| 537 | - }, | |
| 538 | - ); | |
| 539 | - }); | |
| 540 | - | |
| 541 | - it("should handle edge cases in replacement", () => { | |
| 542 | - // Empty replacement | |
| 543 | - verifyMatchAndReplacement( | |
| 544 | - "before target after", | |
| 545 | - "target", | |
| 546 | - "target", | |
| 547 | - "", | |
| 548 | - "before after", | |
| 549 | - ); | |
| 550 | - | |
| 551 | - // Replacement longer than original | |
| 552 | - verifyMatchAndReplacement( | |
| 553 | - "short", | |
| 554 | - "short", | |
| 555 | - "short", | |
| 556 | - "much longer replacement", | |
| 557 | - "much longer replacement", | |
| 558 | - ); | |
| 559 | - | |
| 560 | - // Multiline replacement | |
| 561 | - verifyMatchAndReplacement( | |
| 562 | - "single line", | |
| 563 | - "single", | |
| 564 | - "single", | |
| 565 | - "multi\nline\nreplacement", | |
| 566 | - "multi\nline\nreplacement line", | |
| 567 | - ); | |
| 568 | - }); | |
| 569 | - }); | |
| 570 | - | |
| 571 | - describe("Performance and edge cases", () => { | |
| 572 | - it("should handle very long content efficiently", () => { | |
| 573 | - const longContent = "x".repeat(10000) + "target" + "y".repeat(10000); | |
| 574 | - const result = findSearchMatch(longContent, "target"); | |
| 575 | - | |
| 576 | - expect(result).not.toBeNull(); | |
| 577 | - expect(result!.startIndex).toBe(10000); | |
| 578 | - expect(result!.endIndex).toBe(10006); | |
| 579 | - }); | |
| 580 | - | |
| 581 | - it("should handle unicode and special characters", () => { | |
| 582 | - const testCases = [ | |
| 583 | - { | |
| 584 | - fileContent: "const emoji = '🚀🌟🎉';", | |
| 585 | - searchContent: "🚀🌟🎉", | |
| 586 | - }, | |
| 587 | - { | |
| 588 | - fileContent: "const chinese = '你好世界';", | |
| 589 | - searchContent: "你好世界", | |
| 590 | - }, | |
| 591 | - { | |
| 592 | - fileContent: "const regex = /\\d+/g;", | |
| 593 | - searchContent: "/\\d+/g", | |
| 594 | - }, | |
| 595 | - ]; | |
| 596 | - | |
| 597 | - testCases.forEach(({ fileContent, searchContent }) => { | |
| 598 | - const result = findSearchMatch(fileContent, searchContent); | |
| 599 | - expect(result).not.toBeNull(); | |
| 600 | - | |
| 601 | - const matchedContent = fileContent.substring( | |
| 602 | - result!.startIndex, | |
| 603 | - result!.endIndex, | |
| 604 | - ); | |
| 605 | - expect(matchedContent).toContain(searchContent); | |
| 606 | - }); | |
| 607 | - }); | |
| 608 | - | |
| 609 | - it("should handle null bytes and control characters", () => { | |
| 610 | - const fileContent = "before\x00null\x01byte\x02after"; | |
| 611 | - const searchContent = "\x00null\x01byte\x02"; | |
| 612 | - | |
| 613 | - const result = findSearchMatch(fileContent, searchContent); | |
| 614 | - expect(result).not.toBeNull(); | |
| 615 | - expect(result!.strategyName).toBe("exactMatch"); | |
| 616 | - }); | |
| 617 | - }); | |
| 618 | -}); |
deleted core/edit/searchAndReplace/findSearchMatch.test.ts +0 −587
| @@ -1,587 +0,0 @@ | ||
| 1 | -import { findSearchMatch } from "./findSearchMatch"; | |
| 2 | - | |
| 3 | -describe("Exact matches", () => { | |
| 4 | - it("should find exact match at the beginning of file", () => { | |
| 5 | - const fileContent = `function hello() { | |
| 6 | - console.log("world"); | |
| 7 | -}`; | |
| 8 | - const searchContent = `function hello() { | |
| 9 | - console.log("world"); | |
| 10 | -}`; | |
| 11 | - | |
| 12 | - const result = findSearchMatch(fileContent, searchContent); | |
| 13 | - | |
| 14 | - expect(result).toEqual({ | |
| 15 | - startIndex: 0, | |
| 16 | - endIndex: fileContent.length, | |
| 17 | - strategyName: "exactMatch", | |
| 18 | - }); | |
| 19 | - }); | |
| 20 | - | |
| 21 | - it("should find exact match in the middle of file", () => { | |
| 22 | - const fileContent = `const a = 1; | |
| 23 | -function hello() { | |
| 24 | - console.log("world"); | |
| 25 | -} | |
| 26 | -const b = 2;`; | |
| 27 | - const searchContent = `function hello() { | |
| 28 | - console.log("world"); | |
| 29 | -}`; | |
| 30 | - | |
| 31 | - const result = findSearchMatch(fileContent, searchContent); | |
| 32 | - | |
| 33 | - expect(result).toEqual({ | |
| 34 | - startIndex: 13, // After "const a = 1;\n" | |
| 35 | - endIndex: 13 + searchContent.length, | |
| 36 | - strategyName: "exactMatch", | |
| 37 | - }); | |
| 38 | - }); | |
| 39 | - | |
| 40 | - it("should find exact match at the end of file", () => { | |
| 41 | - const fileContent = `const a = 1; | |
| 42 | -function hello() { | |
| 43 | - console.log("world"); | |
| 44 | -}`; | |
| 45 | - const searchContent = `function hello() { | |
| 46 | - console.log("world"); | |
| 47 | -}`; | |
| 48 | - | |
| 49 | - const result = findSearchMatch(fileContent, searchContent); | |
| 50 | - | |
| 51 | - expect(result).toEqual({ | |
| 52 | - startIndex: 13, // After "const a = 1;\n" | |
| 53 | - endIndex: fileContent.length, | |
| 54 | - strategyName: "exactMatch", | |
| 55 | - }); | |
| 56 | - }); | |
| 57 | - | |
| 58 | - it("should find exact match with single line", () => { | |
| 59 | - const fileContent = `const a = 1; | |
| 60 | -const b = 2; | |
| 61 | -const c = 3;`; | |
| 62 | - const searchContent = `const b = 2;`; | |
| 63 | - | |
| 64 | - const result = findSearchMatch(fileContent, searchContent); | |
| 65 | - | |
| 66 | - expect(result).toEqual({ | |
| 67 | - startIndex: 13, // After "const a = 1;\n" | |
| 68 | - endIndex: 13 + searchContent.length, | |
| 69 | - strategyName: "exactMatch", | |
| 70 | - }); | |
| 71 | - }); | |
| 72 | - | |
| 73 | - it("should find exact match with whitespace preserved", () => { | |
| 74 | - const fileContent = `function test() { | |
| 75 | - const x = 1; | |
| 76 | - const y = 2; | |
| 77 | -}`; | |
| 78 | - const searchContent = ` const x = 1; | |
| 79 | - const y = 2;`; | |
| 80 | - | |
| 81 | - const result = findSearchMatch(fileContent, searchContent); | |
| 82 | - | |
| 83 | - // The actual indexOf result is 18, not 17 | |
| 84 | - expect(result).toEqual({ | |
| 85 | - startIndex: 18, | |
| 86 | - endIndex: 18 + searchContent.length, | |
| 87 | - strategyName: "exactMatch", | |
| 88 | - }); | |
| 89 | - }); | |
| 90 | -}); | |
| 91 | - | |
| 92 | -describe("Trimmed matches", () => { | |
| 93 | - it("should find trimmed match when exact match fails due to leading newlines", () => { | |
| 94 | - const fileContent = `function hello() { | |
| 95 | - console.log("world"); | |
| 96 | -}`; | |
| 97 | - const searchContent = `\n\nfunction hello() { | |
| 98 | - console.log("world"); | |
| 99 | -}\n\n`; | |
| 100 | - | |
| 101 | - const result = findSearchMatch(fileContent, searchContent); | |
| 102 | - | |
| 103 | - expect(result).toEqual({ | |
| 104 | - startIndex: 0, | |
| 105 | - endIndex: fileContent.length, // Uses trimmed length | |
| 106 | - strategyName: "trimmedMatch", | |
| 107 | - }); | |
| 108 | - }); | |
| 109 | - | |
| 110 | - it("should find trimmed match when exact match fails due to trailing newlines", () => { | |
| 111 | - const fileContent = `const a = 1; | |
| 112 | -function hello() { | |
| 113 | - return "world"; | |
| 114 | -} | |
| 115 | -const b = 2;`; | |
| 116 | - const searchContent = `\nfunction hello() { | |
| 117 | - return "world"; | |
| 118 | -}\n`; | |
| 119 | - | |
| 120 | - const result = findSearchMatch(fileContent, searchContent); | |
| 121 | - | |
| 122 | - // The function finds the exact match first (at index 12), not the trimmed match | |
| 123 | - expect(result).toEqual({ | |
| 124 | - startIndex: 12, | |
| 125 | - endIndex: 12 + searchContent.length, | |
| 126 | - strategyName: "exactMatch", | |
| 127 | - }); | |
| 128 | - }); | |
| 129 | - | |
| 130 | - it("should find trimmed match for single line with extra whitespace", () => { | |
| 131 | - const fileContent = `const a = 1; | |
| 132 | -const b = 2; | |
| 133 | -const c = 3;`; | |
| 134 | - const searchContent = `\n const b = 2; \n`; | |
| 135 | - | |
| 136 | - const result = findSearchMatch(fileContent, searchContent); | |
| 137 | - | |
| 138 | - const trimmedSearchContent = searchContent.trim(); | |
| 139 | - const expectedStart = fileContent.indexOf(trimmedSearchContent); | |
| 140 | - | |
| 141 | - expect(result).toEqual({ | |
| 142 | - startIndex: expectedStart, | |
| 143 | - endIndex: expectedStart + trimmedSearchContent.length, | |
| 144 | - strategyName: "trimmedMatch", | |
| 145 | - }); | |
| 146 | - }); | |
| 147 | -}); | |
| 148 | - | |
| 149 | -describe("Empty search content", () => { | |
| 150 | - it("should match at beginning for empty search content", () => { | |
| 151 | - const fileContent = `function hello() { | |
| 152 | - console.log("world"); | |
| 153 | -}`; | |
| 154 | - const searchContent = ""; | |
| 155 | - | |
| 156 | - const result = findSearchMatch(fileContent, searchContent); | |
| 157 | - | |
| 158 | - expect(result).toEqual({ | |
| 159 | - startIndex: 0, | |
| 160 | - endIndex: 0, | |
| 161 | - strategyName: "emptySearch", | |
| 162 | - }); | |
| 163 | - }); | |
| 164 | - | |
| 165 | - it("should match at beginning for whitespace-only search content", () => { | |
| 166 | - const fileContent = `function hello() { | |
| 167 | - console.log("world"); | |
| 168 | -}`; | |
| 169 | - const searchContent = "\n\n \t \n"; | |
| 170 | - | |
| 171 | - const result = findSearchMatch(fileContent, searchContent); | |
| 172 | - | |
| 173 | - expect(result).toEqual({ | |
| 174 | - startIndex: 0, | |
| 175 | - endIndex: 0, | |
| 176 | - strategyName: "emptySearch", | |
| 177 | - }); | |
| 178 | - }); | |
| 179 | - | |
| 180 | - it("should match at beginning for empty file and empty search", () => { | |
| 181 | - const fileContent = ""; | |
| 182 | - const searchContent = ""; | |
| 183 | - | |
| 184 | - const result = findSearchMatch(fileContent, searchContent); | |
| 185 | - | |
| 186 | - expect(result).toEqual({ | |
| 187 | - startIndex: 0, | |
| 188 | - endIndex: 0, | |
| 189 | - strategyName: "emptySearch", | |
| 190 | - }); | |
| 191 | - }); | |
| 192 | -}); | |
| 193 | - | |
| 194 | -describe("Edge cases", () => { | |
| 195 | - it("should handle empty file with non-empty search", () => { | |
| 196 | - const fileContent = ""; | |
| 197 | - const searchContent = "function hello() {}"; | |
| 198 | - | |
| 199 | - const result = findSearchMatch(fileContent, searchContent); | |
| 200 | - | |
| 201 | - expect(result).toBeNull(); | |
| 202 | - }); | |
| 203 | - | |
| 204 | - it("should handle very large content", () => { | |
| 205 | - const repeatedLine = "const x = 1;\n"; | |
| 206 | - const fileContent = | |
| 207 | - repeatedLine.repeat(1000) + | |
| 208 | - "const target = 2;\n" + | |
| 209 | - repeatedLine.repeat(1000); | |
| 210 | - const searchContent = "const target = 2;"; | |
| 211 | - | |
| 212 | - const result = findSearchMatch(fileContent, searchContent); | |
| 213 | - | |
| 214 | - const expectedStart = repeatedLine.length * 1000; | |
| 215 | - expect(result).toEqual({ | |
| 216 | - startIndex: expectedStart, | |
| 217 | - endIndex: expectedStart + searchContent.length, | |
| 218 | - strategyName: "exactMatch", | |
| 219 | - }); | |
| 220 | - }); | |
| 221 | - | |
| 222 | - it("should handle special characters and symbols", () => { | |
| 223 | - const fileContent = `const regex = /[a-zA-Z]+/g; | |
| 224 | -const symbols = !@#$%^&*(); | |
| 225 | -const unicode = "🚀 Hello 世界";`; | |
| 226 | - const searchContent = `const symbols = !@#$%^&*();`; | |
| 227 | - | |
| 228 | - const result = findSearchMatch(fileContent, searchContent); | |
| 229 | - | |
| 230 | - const expectedStart = fileContent.indexOf(searchContent); | |
| 231 | - expect(result).toEqual({ | |
| 232 | - startIndex: expectedStart, | |
| 233 | - endIndex: expectedStart + searchContent.length, | |
| 234 | - strategyName: "exactMatch", | |
| 235 | - }); | |
| 236 | - }); | |
| 237 | - | |
| 238 | - it("should prefer exact match over trimmed match", () => { | |
| 239 | - const fileContent = `function test() { | |
| 240 | - const x = 1; | |
| 241 | -} | |
| 242 | - | |
| 243 | -function test() { | |
| 244 | - const x = 1; | |
| 245 | -}`; | |
| 246 | - const searchContent = `function test() { | |
| 247 | - const x = 1; | |
| 248 | -}`; | |
| 249 | - | |
| 250 | - const result = findSearchMatch(fileContent, searchContent); | |
| 251 | - | |
| 252 | - // Should find the first exact match, not a trimmed version | |
| 253 | - expect(result).toEqual({ | |
| 254 | - startIndex: 0, | |
| 255 | - endIndex: searchContent.length, | |
| 256 | - strategyName: "exactMatch", | |
| 257 | - }); | |
| 258 | - }); | |
| 259 | - | |
| 260 | - it("should handle multiple occurrences and return first match", () => { | |
| 261 | - const fileContent = `const a = 1; | |
| 262 | -const b = 2; | |
| 263 | -const a = 1;`; | |
| 264 | - const searchContent = `const a = 1;`; | |
| 265 | - | |
| 266 | - const result = findSearchMatch(fileContent, searchContent); | |
| 267 | - | |
| 268 | - expect(result).toEqual({ | |
| 269 | - startIndex: 0, | |
| 270 | - endIndex: searchContent.length, | |
| 271 | - strategyName: "exactMatch", | |
| 272 | - }); | |
| 273 | - }); | |
| 274 | -}); | |
| 275 | - | |
| 276 | -describe("Whitespace-ignored matches", () => { | |
| 277 | - it("should match code with different indentation", () => { | |
| 278 | - const fileContent = `function example() { | |
| 279 | - const x = 1; | |
| 280 | - const y = 2; | |
| 281 | - return x + y; | |
| 282 | -}`; | |
| 283 | - const searchContent = `const x=1; | |
| 284 | -const y=2; | |
| 285 | -return x+y;`; | |
| 286 | - | |
| 287 | - const result = findSearchMatch(fileContent, searchContent); | |
| 288 | - | |
| 289 | - expect(result).not.toBeNull(); | |
| 290 | - expect(result!.startIndex).toBe(20); // After "function example() {\n" | |
| 291 | - expect(result!.endIndex).toBe(72); // End of " return x + y;" | |
| 292 | - expect(result!.strategyName).toBe("whitespaceIgnoredMatch"); | |
| 293 | - | |
| 294 | - // Verify the matched content contains the original whitespace | |
| 295 | - const matchedContent = fileContent.substring( | |
| 296 | - result!.startIndex, | |
| 297 | - result!.endIndex, | |
| 298 | - ); | |
| 299 | - expect(matchedContent).toBe(` | |
| 300 | - const x = 1; | |
| 301 | - const y = 2; | |
| 302 | - return x + y;`); | |
| 303 | - }); | |
| 304 | - | |
| 305 | - it("should match single line with different spacing", () => { | |
| 306 | - const fileContent = `const a = 1; | |
| 307 | -const b = 2; | |
| 308 | -const c = 3;`; | |
| 309 | - const searchContent = `const b=2;`; | |
| 310 | - | |
| 311 | - const result = findSearchMatch(fileContent, searchContent); | |
| 312 | - | |
| 313 | - expect(result).not.toBeNull(); | |
| 314 | - expect(result!.startIndex).toBe(12); // After "const a = 1;" | |
| 315 | - expect(result!.endIndex).toBe(32); // End of "const b = 2;" | |
| 316 | - expect(result!.strategyName).toBe("whitespaceIgnoredMatch"); | |
| 317 | - | |
| 318 | - // Verify the matched content preserves original spacing | |
| 319 | - const matchedContent = fileContent.substring( | |
| 320 | - result!.startIndex, | |
| 321 | - result!.endIndex, | |
| 322 | - ); | |
| 323 | - expect(matchedContent).toBe(` | |
| 324 | -const b = 2;`); | |
| 325 | - }); | |
| 326 | - | |
| 327 | - it("should match with tabs vs spaces", () => { | |
| 328 | - const fileContent = `function test() { | |
| 329 | -\tif (condition) { | |
| 330 | -\t\treturn true; | |
| 331 | -\t} | |
| 332 | -}`; | |
| 333 | - const searchContent = `if (condition) { | |
| 334 | - return true; | |
| 335 | -}`; | |
| 336 | - | |
| 337 | - const result = findSearchMatch(fileContent, searchContent); | |
| 338 | - | |
| 339 | - expect(result).not.toBeNull(); | |
| 340 | - expect(result!.startIndex).toBe(17); // After "function test() {" | |
| 341 | - expect(result!.endIndex).toBe(53); // End of "\t}" | |
| 342 | - expect(result!.strategyName).toBe("whitespaceIgnoredMatch"); | |
| 343 | - | |
| 344 | - // Verify the matched content preserves original tabs | |
| 345 | - const matchedContent = fileContent.substring( | |
| 346 | - result!.startIndex, | |
| 347 | - result!.endIndex, | |
| 348 | - ); | |
| 349 | - expect(matchedContent).toBe(` | |
| 350 | -\tif (condition) { | |
| 351 | -\t\treturn true; | |
| 352 | -\t}`); | |
| 353 | - }); | |
| 354 | - | |
| 355 | - it("should match complex whitespace patterns", () => { | |
| 356 | - const fileContent = `const obj = { | |
| 357 | - key1 : 'value1', | |
| 358 | - key2 : 'value2', | |
| 359 | - key3 : 'value3' | |
| 360 | -};`; | |
| 361 | - const searchContent = `key1:'value1', | |
| 362 | -key2:'value2', | |
| 363 | -key3:'value3'`; | |
| 364 | - | |
| 365 | - const result = findSearchMatch(fileContent, searchContent); | |
| 366 | - | |
| 367 | - expect(result).not.toBeNull(); | |
| 368 | - expect(result!.startIndex).toBe(13); // After "const obj = {" | |
| 369 | - expect(result!.endIndex).toBe(83); // End of " key3 : 'value3'" | |
| 370 | - expect(result!.strategyName).toBe("whitespaceIgnoredMatch"); | |
| 371 | - | |
| 372 | - // Verify the matched content preserves original formatting | |
| 373 | - const matchedContent = fileContent.substring( | |
| 374 | - result!.startIndex, | |
| 375 | - result!.endIndex, | |
| 376 | - ); | |
| 377 | - expect(matchedContent).toBe(` | |
| 378 | - key1 : 'value1', | |
| 379 | - key2 : 'value2', | |
| 380 | - key3 : 'value3'`); | |
| 381 | - }); | |
| 382 | - | |
| 383 | - it("should handle newlines and mixed whitespace", () => { | |
| 384 | - const fileContent = `function calc() { | |
| 385 | - | |
| 386 | - | |
| 387 | - let result = 0; | |
| 388 | - | |
| 389 | - result += 5; | |
| 390 | - | |
| 391 | - | |
| 392 | - return result; | |
| 393 | -}`; | |
| 394 | - const searchContent = `let result=0;result+=5;return result;`; | |
| 395 | - | |
| 396 | - const result = findSearchMatch(fileContent, searchContent); | |
| 397 | - | |
| 398 | - expect(result).not.toBeNull(); | |
| 399 | - expect(result!.startIndex).toBe(17); // After "function calc() {\n\n" | |
| 400 | - expect(result!.endIndex).toBe(78); // End of " return result;" | |
| 401 | - expect(result!.strategyName).toBe("whitespaceIgnoredMatch"); | |
| 402 | - | |
| 403 | - // Verify the matched content includes all original whitespace | |
| 404 | - const matchedContent = fileContent.substring( | |
| 405 | - result!.startIndex, | |
| 406 | - result!.endIndex, | |
| 407 | - ); | |
| 408 | - expect(matchedContent).toBe(` | |
| 409 | - | |
| 410 | - | |
| 411 | - let result = 0; | |
| 412 | - | |
| 413 | - result += 5; | |
| 414 | - | |
| 415 | - | |
| 416 | - return result;`); | |
| 417 | - }); | |
| 418 | - | |
| 419 | - it("should prefer exact match over whitespace-ignored match", () => { | |
| 420 | - const fileContent = `const x=1; | |
| 421 | -const x = 1;`; | |
| 422 | - const searchContent = `const x=1;`; | |
| 423 | - | |
| 424 | - const result = findSearchMatch(fileContent, searchContent); | |
| 425 | - | |
| 426 | - // Should find the exact match first (at index 0), not the whitespace-ignored match | |
| 427 | - expect(result).toEqual({ | |
| 428 | - startIndex: 0, | |
| 429 | - endIndex: 10, | |
| 430 | - strategyName: "exactMatch", | |
| 431 | - }); | |
| 432 | - }); | |
| 433 | - | |
| 434 | - it("should handle empty content after whitespace removal", () => { | |
| 435 | - const fileContent = `function test() { | |
| 436 | - return 1; | |
| 437 | -}`; | |
| 438 | - const searchContent = `\n\n \t \n`; | |
| 439 | - | |
| 440 | - const result = findSearchMatch(fileContent, searchContent); | |
| 441 | - | |
| 442 | - // Should match at beginning for empty/whitespace-only content | |
| 443 | - expect(result).toEqual({ | |
| 444 | - startIndex: 0, | |
| 445 | - endIndex: 0, | |
| 446 | - strategyName: "emptySearch", | |
| 447 | - }); | |
| 448 | - }); | |
| 449 | - | |
| 450 | - it("should handle complex code blocks with different formatting", () => { | |
| 451 | - const fileContent = `class Example { | |
| 452 | - constructor(name) { | |
| 453 | - this.name = name; | |
| 454 | - this.value = 0; | |
| 455 | - } | |
| 456 | - | |
| 457 | - getValue() { | |
| 458 | - return this.value; | |
| 459 | - } | |
| 460 | -}`; | |
| 461 | - const searchContent = `constructor(name){ | |
| 462 | -this.name=name; | |
| 463 | -this.value=0; | |
| 464 | -}`; | |
| 465 | - | |
| 466 | - const result = findSearchMatch(fileContent, searchContent); | |
| 467 | - | |
| 468 | - expect(result).not.toBeNull(); | |
| 469 | - expect(result!.startIndex).toBe(15); // After "class Example {" | |
| 470 | - expect(result!.endIndex).toBe(95); // End of " }" | |
| 471 | - expect(result!.strategyName).toBe("whitespaceIgnoredMatch"); | |
| 472 | - | |
| 473 | - // Verify the matched content preserves original formatting | |
| 474 | - const matchedContent = fileContent.substring( | |
| 475 | - result!.startIndex, | |
| 476 | - result!.endIndex, | |
| 477 | - ); | |
| 478 | - expect(matchedContent).toBe(` | |
| 479 | - constructor(name) { | |
| 480 | - this.name = name; | |
| 481 | - this.value = 0; | |
| 482 | - }`); | |
| 483 | - }); | |
| 484 | - | |
| 485 | - it("should return null when no close match exists", () => { | |
| 486 | - const fileContent = `function hello() { | |
| 487 | - console.log("world"); | |
| 488 | -}`; | |
| 489 | - const searchContent = `this has nothing to do with the other option`; | |
| 490 | - | |
| 491 | - const result = findSearchMatch(fileContent, searchContent); | |
| 492 | - | |
| 493 | - expect(result).toBeNull(); | |
| 494 | - }); | |
| 495 | - | |
| 496 | - it("should handle multiple potential matches and return first", () => { | |
| 497 | - const fileContent = `const a=1; | |
| 498 | -const a = 1; | |
| 499 | -const a = 1;`; | |
| 500 | - const searchContent = `const a=1;`; | |
| 501 | - | |
| 502 | - const result = findSearchMatch(fileContent, searchContent); | |
| 503 | - | |
| 504 | - // Should find the first exact match | |
| 505 | - expect(result).toEqual({ | |
| 506 | - startIndex: 0, | |
| 507 | - endIndex: 10, | |
| 508 | - strategyName: "exactMatch", | |
| 509 | - }); | |
| 510 | - }); | |
| 511 | -}); | |
| 512 | - | |
| 513 | -describe("Real-world scenarios", () => { | |
| 514 | - it("should match typical function replacement", () => { | |
| 515 | - const fileContent = `class Calculator { | |
| 516 | - constructor() { | |
| 517 | - this.result = 0; | |
| 518 | - } | |
| 519 | - | |
| 520 | - reset() { | |
| 521 | - this.result = 0; | |
| 522 | - return this; | |
| 523 | - } | |
| 524 | - | |
| 525 | - add(value) { | |
| 526 | - this.result += value; | |
| 527 | - return this; | |
| 528 | - } | |
| 529 | -}`; | |
| 530 | - const searchContent = ` reset() { | |
| 531 | - this.result = 0; | |
| 532 | - return this; | |
| 533 | - }`; | |
| 534 | - | |
| 535 | - const result = findSearchMatch(fileContent, searchContent); | |
| 536 | - | |
| 537 | - const expectedStart = fileContent.indexOf(searchContent); | |
| 538 | - expect(result).toEqual({ | |
| 539 | - startIndex: expectedStart, | |
| 540 | - endIndex: expectedStart + searchContent.length, | |
| 541 | - strategyName: "exactMatch", | |
| 542 | - }); | |
| 543 | - }); | |
| 544 | - | |
| 545 | - it("should match import statement", () => { | |
| 546 | - const fileContent = `import React from 'react'; | |
| 547 | -import { useState, useEffect } from 'react'; | |
| 548 | -import './App.css'; | |
| 549 | - | |
| 550 | -function App() { | |
| 551 | - return <div>Hello World</div>; | |
| 552 | -}`; | |
| 553 | - const searchContent = `import { useState, useEffect } from 'react';`; | |
| 554 | - | |
| 555 | - const result = findSearchMatch(fileContent, searchContent); | |
| 556 | - | |
| 557 | - const expectedStart = fileContent.indexOf(searchContent); | |
| 558 | - expect(result).toEqual({ | |
| 559 | - startIndex: expectedStart, | |
| 560 | - endIndex: expectedStart + searchContent.length, | |
| 561 | - strategyName: "exactMatch", | |
| 562 | - }); | |
| 563 | - }); | |
| 564 | - | |
| 565 | - it("should match comment block", () => { | |
| 566 | - const fileContent = `/** | |
| 567 | - * This is a comment | |
| 568 | - * that spans multiple lines | |
| 569 | - */ | |
| 570 | -function test() { | |
| 571 | - // Single line comment | |
| 572 | - return true; | |
| 573 | -}`; | |
| 574 | - const searchContent = `/** | |
| 575 | - * This is a comment | |
| 576 | - * that spans multiple lines | |
| 577 | - */`; | |
| 578 | - | |
| 579 | - const result = findSearchMatch(fileContent, searchContent); | |
| 580 | - | |
| 581 | - expect(result).toEqual({ | |
| 582 | - startIndex: 0, | |
| 583 | - endIndex: searchContent.length, | |
| 584 | - strategyName: "exactMatch", | |
| 585 | - }); | |
| 586 | - }); | |
| 587 | -}); |
deleted core/edit/searchAndReplace/findSearchMatch.ts +0 −203
| @@ -1,203 +0,0 @@ | ||
| 1 | -/** | |
| 2 | - * Represents a basic match result with start and end character positions | |
| 3 | - */ | |
| 4 | -interface BasicMatchResult { | |
| 5 | - /** The starting character index of the match in the file content */ | |
| 6 | - startIndex: number; | |
| 7 | - /** The ending character index of the match in the file content */ | |
| 8 | - endIndex: number; | |
| 9 | -} | |
| 10 | - | |
| 11 | -/** | |
| 12 | - * Represents a match result with start and end character positions | |
| 13 | - */ | |
| 14 | -export interface SearchMatchResult extends BasicMatchResult { | |
| 15 | - /** The name of the strategy that successfully matched */ | |
| 16 | - strategyName: string; | |
| 17 | -} | |
| 18 | - | |
| 19 | -/** | |
| 20 | - * Strategy function type for finding matches | |
| 21 | - */ | |
| 22 | -type MatchStrategy = ( | |
| 23 | - fileContent: string, | |
| 24 | - searchContent: string, | |
| 25 | -) => BasicMatchResult | null; | |
| 26 | - | |
| 27 | -/** | |
| 28 | - * Exact string matching strategy | |
| 29 | - */ | |
| 30 | -function exactMatch( | |
| 31 | - fileContent: string, | |
| 32 | - searchContent: string, | |
| 33 | -): BasicMatchResult | null { | |
| 34 | - const exactIndex = fileContent.indexOf(searchContent); | |
| 35 | - if (exactIndex !== -1) { | |
| 36 | - return { | |
| 37 | - startIndex: exactIndex, | |
| 38 | - endIndex: exactIndex + searchContent.length, | |
| 39 | - }; | |
| 40 | - } | |
| 41 | - return null; | |
| 42 | -} | |
| 43 | - | |
| 44 | -/** | |
| 45 | - * Trimmed content matching strategy | |
| 46 | - * Finds content where the search content (when trimmed) matches content in the file, | |
| 47 | - * and returns the span that includes the file content's whitespace | |
| 48 | - */ | |
| 49 | -function trimmedMatch( | |
| 50 | - fileContent: string, | |
| 51 | - searchContent: string, | |
| 52 | -): BasicMatchResult | null { | |
| 53 | - const trimmedSearchContent = searchContent.trim(); | |
| 54 | - | |
| 55 | - // Don't apply if search content has no leading/trailing whitespace to trim | |
| 56 | - if (trimmedSearchContent === searchContent) { | |
| 57 | - return null; | |
| 58 | - } | |
| 59 | - | |
| 60 | - // Don't match if trimmed content is empty | |
| 61 | - if (trimmedSearchContent === "") { | |
| 62 | - return null; | |
| 63 | - } | |
| 64 | - | |
| 65 | - // Look for the trimmed content in the file | |
| 66 | - const trimmedContentIndex = fileContent.indexOf(trimmedSearchContent); | |
| 67 | - if (trimmedContentIndex === -1) { | |
| 68 | - return null; | |
| 69 | - } | |
| 70 | - | |
| 71 | - // Find the boundaries that include surrounding whitespace (but not newlines) | |
| 72 | - // Look backwards for horizontal whitespace (spaces and tabs) | |
| 73 | - let startIndex = trimmedContentIndex; | |
| 74 | - while (startIndex > 0 && /[ \t]/.test(fileContent[startIndex - 1])) { | |
| 75 | - startIndex--; | |
| 76 | - } | |
| 77 | - | |
| 78 | - // Look forwards for horizontal whitespace (spaces and tabs) | |
| 79 | - let endIndex = trimmedContentIndex + trimmedSearchContent.length; | |
| 80 | - while (endIndex < fileContent.length && /[ \t]/.test(fileContent[endIndex])) { | |
| 81 | - endIndex++; | |
| 82 | - } | |
| 83 | - | |
| 84 | - return { | |
| 85 | - startIndex, | |
| 86 | - endIndex, | |
| 87 | - }; | |
| 88 | -} | |
| 89 | - | |
| 90 | -/** | |
| 91 | - * Whitespace-ignored matching strategy | |
| 92 | - * Removes all whitespace from both content and search, then finds the match | |
| 93 | - */ | |
| 94 | -function whitespaceIgnoredMatch( | |
| 95 | - fileContent: string, | |
| 96 | - searchContent: string, | |
| 97 | -): BasicMatchResult | null { | |
| 98 | - // Remove all whitespace (spaces, tabs, newlines, etc.) | |
| 99 | - const strippedFileContent = fileContent.replace(/\s/g, ""); | |
| 100 | - const strippedSearchContent = searchContent.replace(/\s/g, ""); | |
| 101 | - | |
| 102 | - if (strippedSearchContent === "") { | |
| 103 | - return null; // Empty search after stripping whitespace | |
| 104 | - } | |
| 105 | - | |
| 106 | - const strippedIndex = strippedFileContent.indexOf(strippedSearchContent); | |
| 107 | - if (strippedIndex === -1) { | |
| 108 | - return null; | |
| 109 | - } | |
| 110 | - | |
| 111 | - // Map the stripped position back to the original file content | |
| 112 | - let originalStartIndex = 0; | |
| 113 | - let strippedCharCount = 0; | |
| 114 | - | |
| 115 | - // Find the original position by counting non-whitespace characters | |
| 116 | - for (let i = 0; i < fileContent.length; i++) { | |
| 117 | - if (strippedCharCount === strippedIndex) { | |
| 118 | - originalStartIndex = i; | |
| 119 | - break; | |
| 120 | - } | |
| 121 | - if (!/\s/.test(fileContent[i])) { | |
| 122 | - strippedCharCount++; | |
| 123 | - } | |
| 124 | - } | |
| 125 | - | |
| 126 | - // Find the end position by counting the length of the search content | |
| 127 | - let originalEndIndex = originalStartIndex; | |
| 128 | - let matchedChars = 0; | |
| 129 | - | |
| 130 | - for ( | |
| 131 | - let i = originalStartIndex; | |
| 132 | - i < fileContent.length && matchedChars < strippedSearchContent.length; | |
| 133 | - i++ | |
| 134 | - ) { | |
| 135 | - if (!/\s/.test(fileContent[i])) { | |
| 136 | - matchedChars++; | |
| 137 | - } | |
| 138 | - originalEndIndex = i + 1; | |
| 139 | - } | |
| 140 | - | |
| 141 | - return { | |
| 142 | - startIndex: originalStartIndex, | |
| 143 | - endIndex: originalEndIndex, | |
| 144 | - }; | |
| 145 | -} | |
| 146 | - | |
| 147 | -/** | |
| 148 | - * Ordered list of matching strategies to try with their names | |
| 149 | - */ | |
| 150 | -const matchingStrategies: Array<{ strategy: MatchStrategy; name: string }> = [ | |
| 151 | - { strategy: exactMatch, name: "exactMatch" }, | |
| 152 | - { strategy: trimmedMatch, name: "trimmedMatch" }, | |
| 153 | - { strategy: whitespaceIgnoredMatch, name: "whitespaceIgnoredMatch" }, | |
| 154 | -]; | |
| 155 | - | |
| 156 | -/** | |
| 157 | - * Find the exact match position for search content in file content. | |
| 158 | - * Uses multiple matching strategies in order of preference. | |
| 159 | - * | |
| 160 | - * Matching Strategy: | |
| 161 | - * 1. If search content is empty, matches at the beginning of file (position 0) | |
| 162 | - * 2. Try each matching strategy in order until one succeeds | |
| 163 | - * | |
| 164 | - * @param fileContent - The complete content of the file to search in | |
| 165 | - * @param searchContent - The content to search for | |
| 166 | - * @param config - Configuration options for matching behavior | |
| 167 | - * @returns Match result with character positions, or null if no match found | |
| 168 | - */ | |
| 169 | -export function findSearchMatch( | |
| 170 | - fileContent: string, | |
| 171 | - searchContent: string, | |
| 172 | -): SearchMatchResult | null { | |
| 173 | - // Handle truly empty search content | |
| 174 | - if (searchContent === "") { | |
| 175 | - return { startIndex: 0, endIndex: 0, strategyName: "emptySearch" }; | |
| 176 | - } | |
| 177 | - | |
| 178 | - // Handle whitespace-only search content that trims to empty | |
| 179 | - const trimmedSearchContent = searchContent.trim(); | |
| 180 | - if (trimmedSearchContent === "") { | |
| 181 | - // Check if the whitespace-only search content has an exact match first | |
| 182 | - const exactIndex = fileContent.indexOf(searchContent); | |
| 183 | - if (exactIndex !== -1) { | |
| 184 | - return { | |
| 185 | - startIndex: exactIndex, | |
| 186 | - endIndex: exactIndex + searchContent.length, | |
| 187 | - strategyName: "exactMatch", | |
| 188 | - }; | |
| 189 | - } | |
| 190 | - // If no exact match for whitespace-only content, treat as empty search | |
| 191 | - return { startIndex: 0, endIndex: 0, strategyName: "emptySearch" }; | |
| 192 | - } | |
| 193 | - | |
| 194 | - // Try each matching strategy in order | |
| 195 | - for (const { strategy, name } of matchingStrategies) { | |
| 196 | - const result = strategy(fileContent, searchContent); | |
| 197 | - if (result !== null) { | |
| 198 | - return { ...result, strategyName: name }; | |
| 199 | - } | |
| 200 | - } | |
| 201 | - | |
| 202 | - return null; | |
| 203 | -} |
deleted core/edit/searchAndReplace/parseSearchReplaceBlock.test.ts +0 −390
| @@ -1,390 +0,0 @@ | ||
| 1 | -import { | |
| 2 | - parseAllSearchReplaceBlocks, | |
| 3 | - parseSearchReplaceBlock, | |
| 4 | -} from "./parseSearchReplaceBlock"; | |
| 5 | - | |
| 6 | -describe("parseSearchReplaceBlock", () => { | |
| 7 | - describe("Complete blocks", () => { | |
| 8 | - it("should parse a complete basic search/replace block", () => { | |
| 9 | - const content = `------- SEARCH | |
| 10 | -reset() { | |
| 11 | -this.result = 0; | |
| 12 | -return this; | |
| 13 | -} | |
| 14 | -======= | |
| 15 | -// Resets the calculator result to 0 and returns the instance for method chaining | |
| 16 | -reset() { | |
| 17 | -this.result = 0; | |
| 18 | -return this; | |
| 19 | -} | |
| 20 | -+++++++ REPLACE`; | |
| 21 | - | |
| 22 | - const result = parseSearchReplaceBlock(content); | |
| 23 | - | |
| 24 | - expect(result.isComplete).toBe(true); | |
| 25 | - expect(result.searchContent).toBe(`reset() { | |
| 26 | -this.result = 0; | |
| 27 | -return this; | |
| 28 | -}`); | |
| 29 | - expect(result.replaceContent) | |
| 30 | - .toBe(`// Resets the calculator result to 0 and returns the instance for method chaining | |
| 31 | -reset() { | |
| 32 | -this.result = 0; | |
| 33 | -return this; | |
| 34 | -}`); | |
| 35 | - expect(result.error).toBeUndefined(); | |
| 36 | - }); | |
| 37 | - | |
| 38 | - it("should handle different marker lengths", () => { | |
| 39 | - const content = `------- SEARCH | |
| 40 | -old content | |
| 41 | -========= | |
| 42 | -new content | |
| 43 | -+++++++++++ REPLACE`; | |
| 44 | - | |
| 45 | - const result = parseSearchReplaceBlock(content); | |
| 46 | - | |
| 47 | - expect(result.isComplete).toBe(true); | |
| 48 | - expect(result.searchContent).toBe("old content"); | |
| 49 | - expect(result.replaceContent).toBe("new content"); | |
| 50 | - }); | |
| 51 | - | |
| 52 | - it("should handle empty search content", () => { | |
| 53 | - const content = `------- SEARCH | |
| 54 | -======= | |
| 55 | -new content | |
| 56 | -+++++++ REPLACE`; | |
| 57 | - | |
| 58 | - const result = parseSearchReplaceBlock(content); | |
| 59 | - | |
| 60 | - expect(result.isComplete).toBe(true); | |
| 61 | - expect(result.searchContent).toBe(""); | |
| 62 | - expect(result.replaceContent).toBe("new content"); | |
| 63 | - }); | |
| 64 | - | |
| 65 | - it("should handle empty replace content (deletion)", () => { | |
| 66 | - const content = `------- SEARCH | |
| 67 | -old content to delete | |
| 68 | -======= | |
| 69 | -+++++++ REPLACE`; | |
| 70 | - | |
| 71 | - const result = parseSearchReplaceBlock(content); | |
| 72 | - | |
| 73 | - expect(result.isComplete).toBe(true); | |
| 74 | - expect(result.searchContent).toBe("old content to delete"); | |
| 75 | - expect(result.replaceContent).toBe(""); | |
| 76 | - }); | |
| 77 | - | |
| 78 | - it("should handle both empty search and replace content", () => { | |
| 79 | - const content = `------- SEARCH | |
| 80 | -======= | |
| 81 | -+++++++ REPLACE`; | |
| 82 | - | |
| 83 | - const result = parseSearchReplaceBlock(content); | |
| 84 | - | |
| 85 | - expect(result.isComplete).toBe(true); | |
| 86 | - expect(result.searchContent).toBe(""); | |
| 87 | - expect(result.replaceContent).toBe(""); | |
| 88 | - }); | |
| 89 | - }); | |
| 90 | - | |
| 91 | - describe("Incomplete blocks", () => { | |
| 92 | - it("should handle incomplete search block", () => { | |
| 93 | - const content = `------- SEARCH | |
| 94 | -some content`; | |
| 95 | - | |
| 96 | - const result = parseSearchReplaceBlock(content); | |
| 97 | - | |
| 98 | - expect(result.isComplete).toBe(false); | |
| 99 | - expect(result.searchContent).toBe("some content"); | |
| 100 | - expect(result.replaceContent).toBe(""); | |
| 101 | - expect(result.error).toBeUndefined(); | |
| 102 | - }); | |
| 103 | - | |
| 104 | - it("should handle incomplete replace block", () => { | |
| 105 | - const content = `------- SEARCH | |
| 106 | -old content | |
| 107 | -======= | |
| 108 | -new content`; | |
| 109 | - | |
| 110 | - const result = parseSearchReplaceBlock(content); | |
| 111 | - | |
| 112 | - expect(result.isComplete).toBe(false); | |
| 113 | - expect(result.searchContent).toBe("old content"); | |
| 114 | - expect(result.replaceContent).toBe("new content"); | |
| 115 | - expect(result.error).toBeUndefined(); | |
| 116 | - }); | |
| 117 | - }); | |
| 118 | - | |
| 119 | - describe("Error cases", () => { | |
| 120 | - it("should error on search end without start", () => { | |
| 121 | - const content = `======= | |
| 122 | -some content | |
| 123 | -+++++++ REPLACE`; | |
| 124 | - | |
| 125 | - const result = parseSearchReplaceBlock(content); | |
| 126 | - | |
| 127 | - expect(result.isComplete).toBe(false); | |
| 128 | - expect(result.error).toBe( | |
| 129 | - "Found search block end marker without matching start marker", | |
| 130 | - ); | |
| 131 | - }); | |
| 132 | - | |
| 133 | - it("should error on replace end without replace start", () => { | |
| 134 | - const content = `+++++++ REPLACE`; | |
| 135 | - | |
| 136 | - const result = parseSearchReplaceBlock(content); | |
| 137 | - | |
| 138 | - expect(result.isComplete).toBe(false); | |
| 139 | - expect(result.error).toBe( | |
| 140 | - "Found replace block end marker without matching replace start marker", | |
| 141 | - ); | |
| 142 | - }); | |
| 143 | - }); | |
| 144 | - | |
| 145 | - describe("Regex pattern validation", () => { | |
| 146 | - it("should match various search start patterns", () => { | |
| 147 | - const patterns = ["--- SEARCH", "------- SEARCH", "------------- SEARCH"]; | |
| 148 | - | |
| 149 | - patterns.forEach((pattern) => { | |
| 150 | - const content = `${pattern} | |
| 151 | -content | |
| 152 | -======= | |
| 153 | -replacement | |
| 154 | -+++++++ REPLACE`; | |
| 155 | - | |
| 156 | - const result = parseSearchReplaceBlock(content); | |
| 157 | - expect(result.isComplete).toBe(true); | |
| 158 | - }); | |
| 159 | - }); | |
| 160 | - | |
| 161 | - it("should match various search end patterns", () => { | |
| 162 | - const patterns = ["===", "=======", "=============="]; | |
| 163 | - | |
| 164 | - patterns.forEach((pattern) => { | |
| 165 | - const content = `------- SEARCH | |
| 166 | -content | |
| 167 | -${pattern} | |
| 168 | -replacement | |
| 169 | -+++++++ REPLACE`; | |
| 170 | - | |
| 171 | - const result = parseSearchReplaceBlock(content); | |
| 172 | - expect(result.isComplete).toBe(true); | |
| 173 | - }); | |
| 174 | - }); | |
| 175 | - | |
| 176 | - it("should match various replace end patterns", () => { | |
| 177 | - const patterns = [ | |
| 178 | - "+++ REPLACE", | |
| 179 | - "+++++++ REPLACE", | |
| 180 | - "+++++++++++ REPLACE", | |
| 181 | - ]; | |
| 182 | - | |
| 183 | - patterns.forEach((pattern) => { | |
| 184 | - const content = `------- SEARCH | |
| 185 | -content | |
| 186 | -======= | |
| 187 | -replacement | |
| 188 | -${pattern}`; | |
| 189 | - | |
| 190 | - const result = parseSearchReplaceBlock(content); | |
| 191 | - expect(result.isComplete).toBe(true); | |
| 192 | - }); | |
| 193 | - }); | |
| 194 | - | |
| 195 | - it("should not match invalid patterns", () => { | |
| 196 | - const invalidPatterns = [ | |
| 197 | - "-- SEARCH", // Too few dashes | |
| 198 | - "SEARCH", // No markers | |
| 199 | - "== SEARCH", // Wrong markers | |
| 200 | - "=== REPLACE", // Wrong end marker | |
| 201 | - "++++ SEARCH", // Wrong markers for search | |
| 202 | - ]; | |
| 203 | - | |
| 204 | - invalidPatterns.forEach((pattern) => { | |
| 205 | - const content = `${pattern} | |
| 206 | -content`; | |
| 207 | - | |
| 208 | - const result = parseSearchReplaceBlock(content); | |
| 209 | - expect(result.isComplete).toBe(false); | |
| 210 | - expect(result.searchContent).toBe(""); // Should not enter search mode | |
| 211 | - }); | |
| 212 | - }); | |
| 213 | - }); | |
| 214 | -}); | |
| 215 | - | |
| 216 | -describe("parseAllSearchReplaceBlocks", () => { | |
| 217 | - it("should parse multiple complete blocks", () => { | |
| 218 | - const content = `------- SEARCH | |
| 219 | -old code 1 | |
| 220 | -======= | |
| 221 | -new code 1 | |
| 222 | -+++++++ REPLACE | |
| 223 | - | |
| 224 | -------- SEARCH | |
| 225 | -old code 2 | |
| 226 | -======= | |
| 227 | -new code 2 | |
| 228 | -+++++++ REPLACE`; | |
| 229 | - | |
| 230 | - const blocks = parseAllSearchReplaceBlocks(content); | |
| 231 | - | |
| 232 | - expect(blocks).toHaveLength(2); | |
| 233 | - expect(blocks[0].searchContent).toBe("old code 1"); | |
| 234 | - expect(blocks[0].replaceContent).toBe("new code 1"); | |
| 235 | - expect(blocks[1].searchContent).toBe("old code 2"); | |
| 236 | - expect(blocks[1].replaceContent).toBe("new code 2"); | |
| 237 | - }); | |
| 238 | - | |
| 239 | - it("should handle blocks with different content", () => { | |
| 240 | - const content = `------- SEARCH | |
| 241 | -function old() { | |
| 242 | - return 1; | |
| 243 | -} | |
| 244 | -======= | |
| 245 | -function new() { | |
| 246 | - return 2; | |
| 247 | -} | |
| 248 | -+++++++ REPLACE | |
| 249 | - | |
| 250 | -------- SEARCH | |
| 251 | -const x = 'old'; | |
| 252 | -======= | |
| 253 | -const x = 'new'; | |
| 254 | -+++++++ REPLACE`; | |
| 255 | - | |
| 256 | - const blocks = parseAllSearchReplaceBlocks(content); | |
| 257 | - | |
| 258 | - expect(blocks).toHaveLength(2); | |
| 259 | - expect(blocks[0].searchContent).toBe(`function old() { | |
| 260 | - return 1; | |
| 261 | -}`); | |
| 262 | - expect(blocks[0].replaceContent).toBe(`function new() { | |
| 263 | - return 2; | |
| 264 | -}`); | |
| 265 | - expect(blocks[1].searchContent).toBe(`const x = 'old';`); | |
| 266 | - expect(blocks[1].replaceContent).toBe(`const x = 'new';`); | |
| 267 | - }); | |
| 268 | - | |
| 269 | - it("should handle deletion blocks (empty replace content)", () => { | |
| 270 | - const content = `------- SEARCH | |
| 271 | -code to keep | |
| 272 | -======= | |
| 273 | -modified code | |
| 274 | -+++++++ REPLACE | |
| 275 | - | |
| 276 | -------- SEARCH | |
| 277 | -code to delete | |
| 278 | -======= | |
| 279 | -+++++++ REPLACE`; | |
| 280 | - | |
| 281 | - const blocks = parseAllSearchReplaceBlocks(content); | |
| 282 | - | |
| 283 | - expect(blocks).toHaveLength(2); | |
| 284 | - expect(blocks[0].searchContent).toBe("code to keep"); | |
| 285 | - expect(blocks[0].replaceContent).toBe("modified code"); | |
| 286 | - expect(blocks[1].searchContent).toBe("code to delete"); | |
| 287 | - expect(blocks[1].replaceContent).toBe(""); // Deletion | |
| 288 | - }); | |
| 289 | - | |
| 290 | - it("should handle insertion blocks (empty search content)", () => { | |
| 291 | - const content = `------- SEARCH | |
| 292 | -existing code | |
| 293 | -======= | |
| 294 | -modified existing code | |
| 295 | -+++++++ REPLACE | |
| 296 | - | |
| 297 | -------- SEARCH | |
| 298 | -======= | |
| 299 | -new code to insert | |
| 300 | -+++++++ REPLACE`; | |
| 301 | - | |
| 302 | - const blocks = parseAllSearchReplaceBlocks(content); | |
| 303 | - | |
| 304 | - expect(blocks).toHaveLength(2); | |
| 305 | - expect(blocks[0].searchContent).toBe("existing code"); | |
| 306 | - expect(blocks[0].replaceContent).toBe("modified existing code"); | |
| 307 | - expect(blocks[1].searchContent).toBe(""); // Insertion | |
| 308 | - expect(blocks[1].replaceContent).toBe("new code to insert"); | |
| 309 | - }); | |
| 310 | - | |
| 311 | - it("should skip incomplete blocks", () => { | |
| 312 | - const content = `------- SEARCH | |
| 313 | -incomplete block | |
| 314 | - | |
| 315 | -------- SEARCH | |
| 316 | -complete block | |
| 317 | -======= | |
| 318 | -replacement | |
| 319 | -+++++++ REPLACE`; | |
| 320 | - | |
| 321 | - const blocks = parseAllSearchReplaceBlocks(content); | |
| 322 | - | |
| 323 | - expect(blocks).toHaveLength(1); | |
| 324 | - expect(blocks[0].searchContent).toBe("complete block"); | |
| 325 | - expect(blocks[0].replaceContent).toBe("replacement"); | |
| 326 | - }); | |
| 327 | - | |
| 328 | - it("should handle single block", () => { | |
| 329 | - const content = `------- SEARCH | |
| 330 | -single block | |
| 331 | -======= | |
| 332 | -replacement | |
| 333 | -+++++++ REPLACE`; | |
| 334 | - | |
| 335 | - const blocks = parseAllSearchReplaceBlocks(content); | |
| 336 | - | |
| 337 | - expect(blocks).toHaveLength(1); | |
| 338 | - expect(blocks[0].searchContent).toBe("single block"); | |
| 339 | - expect(blocks[0].replaceContent).toBe("replacement"); | |
| 340 | - }); | |
| 341 | - | |
| 342 | - it("should return empty array when no complete blocks found", () => { | |
| 343 | - const content = `------- SEARCH | |
| 344 | -incomplete | |
| 345 | -======= | |
| 346 | -missing replace marker`; | |
| 347 | - | |
| 348 | - const blocks = parseAllSearchReplaceBlocks(content); | |
| 349 | - | |
| 350 | - expect(blocks).toHaveLength(0); | |
| 351 | - }); | |
| 352 | - | |
| 353 | - it("should handle blocks with extra content between them", () => { | |
| 354 | - const content = `Some other content here | |
| 355 | - | |
| 356 | -------- SEARCH | |
| 357 | -block 1 | |
| 358 | -======= | |
| 359 | -replacement 1 | |
| 360 | -+++++++ REPLACE | |
| 361 | - | |
| 362 | -More content in between | |
| 363 | - | |
| 364 | -------- SEARCH | |
| 365 | -block 2 | |
| 366 | -======= | |
| 367 | -replacement 2 | |
| 368 | -+++++++ REPLACE | |
| 369 | - | |
| 370 | -Trailing content`; | |
| 371 | - | |
| 372 | - const blocks = parseAllSearchReplaceBlocks(content); | |
| 373 | - | |
| 374 | - expect(blocks).toHaveLength(2); | |
| 375 | - expect(blocks[0].searchContent).toBe("block 1"); | |
| 376 | - expect(blocks[0].replaceContent).toBe("replacement 1"); | |
| 377 | - expect(blocks[1].searchContent).toBe("block 2"); | |
| 378 | - expect(blocks[1].replaceContent).toBe("replacement 2"); | |
| 379 | - }); | |
| 380 | - | |
| 381 | - it("should throw error for malformed blocks", () => { | |
| 382 | - const content = `------- SEARCH | |
| 383 | -content | |
| 384 | -+++++++ REPLACE`; // Missing ======= | |
| 385 | - | |
| 386 | - expect(() => parseAllSearchReplaceBlocks(content)).toThrow( | |
| 387 | - "Found replace block end marker without matching replace start marker", | |
| 388 | - ); | |
| 389 | - }); | |
| 390 | -}); |
deleted core/edit/searchAndReplace/parseSearchReplaceBlock.ts +0 −147
| @@ -1,147 +0,0 @@ | ||
| 1 | -// Search and replace block markers using flexible regex patterns | |
| 2 | -const SEARCH_BLOCK_START_REGEX = /^[-]{3,} SEARCH$/; | |
| 3 | -const SEARCH_BLOCK_END_REGEX = /^[=]{3,}$/; | |
| 4 | -const REPLACE_BLOCK_END_REGEX = /^[+]{3,} REPLACE$/; | |
| 5 | - | |
| 6 | -export interface SearchReplaceBlockResult { | |
| 7 | - /** Whether a complete search/replace block has been parsed */ | |
| 8 | - isComplete: boolean; | |
| 9 | - /** The content to search for in the file */ | |
| 10 | - searchContent?: string; | |
| 11 | - /** The content to replace the search content with */ | |
| 12 | - replaceContent?: string; | |
| 13 | - /** Error message if parsing failed */ | |
| 14 | - error?: string; | |
| 15 | -} | |
| 16 | - | |
| 17 | -/** | |
| 18 | - * Parses a search and replace block from content. | |
| 19 | - * | |
| 20 | - * Expected format: | |
| 21 | - * ------- SEARCH | |
| 22 | - * [content to find] | |
| 23 | - * ======= | |
| 24 | - * [content to replace with] | |
| 25 | - * +++++++ REPLACE | |
| 26 | - * | |
| 27 | - * @param content - The content to parse | |
| 28 | - * @returns ParseResult with completion status and extracted content | |
| 29 | - */ | |
| 30 | -export function parseSearchReplaceBlock( | |
| 31 | - content: string, | |
| 32 | -): SearchReplaceBlockResult { | |
| 33 | - const lines = content.split("\n"); | |
| 34 | - | |
| 35 | - let currentSearchContent = ""; | |
| 36 | - let currentReplaceContent = ""; | |
| 37 | - let inSearch = false; | |
| 38 | - let inReplace = false; | |
| 39 | - | |
| 40 | - for (const line of lines) { | |
| 41 | - if (SEARCH_BLOCK_START_REGEX.test(line)) { | |
| 42 | - inSearch = true; | |
| 43 | - inReplace = false; | |
| 44 | - currentSearchContent = ""; | |
| 45 | - currentReplaceContent = ""; | |
| 46 | - continue; | |
| 47 | - } | |
| 48 | - | |
| 49 | - if (SEARCH_BLOCK_END_REGEX.test(line)) { | |
| 50 | - if (!inSearch) { | |
| 51 | - return { | |
| 52 | - isComplete: false, | |
| 53 | - error: "Found search block end marker without matching start marker", | |
| 54 | - }; | |
| 55 | - } | |
| 56 | - inSearch = false; | |
| 57 | - inReplace = true; | |
| 58 | - continue; | |
| 59 | - } | |
| 60 | - | |
| 61 | - if (REPLACE_BLOCK_END_REGEX.test(line)) { | |
| 62 | - if (!inReplace) { | |
| 63 | - return { | |
| 64 | - isComplete: false, | |
| 65 | - error: | |
| 66 | - "Found replace block end marker without matching replace start marker", | |
| 67 | - }; | |
| 68 | - } | |
| 69 | - | |
| 70 | - // Complete block found | |
| 71 | - return { | |
| 72 | - isComplete: true, | |
| 73 | - searchContent: currentSearchContent.trim(), | |
| 74 | - replaceContent: currentReplaceContent.trim(), | |
| 75 | - }; | |
| 76 | - } | |
| 77 | - | |
| 78 | - // Accumulate content | |
| 79 | - if (inSearch) { | |
| 80 | - currentSearchContent += line + "\n"; | |
| 81 | - } else if (inReplace) { | |
| 82 | - currentReplaceContent += line + "\n"; | |
| 83 | - } | |
| 84 | - } | |
| 85 | - | |
| 86 | - // Block is not yet complete | |
| 87 | - return { | |
| 88 | - isComplete: false, | |
| 89 | - searchContent: currentSearchContent.trim(), | |
| 90 | - replaceContent: currentReplaceContent.trim(), | |
| 91 | - }; | |
| 92 | -} | |
| 93 | - | |
| 94 | -/** | |
| 95 | - * Parses all complete search and replace blocks from content. | |
| 96 | - * | |
| 97 | - * @param content - The content containing multiple search/replace blocks | |
| 98 | - * @returns Array of complete search/replace blocks found | |
| 99 | - * @throws Error if any malformed blocks are encountered | |
| 100 | - */ | |
| 101 | -export function parseAllSearchReplaceBlocks( | |
| 102 | - content: string, | |
| 103 | -): SearchReplaceBlockResult[] { | |
| 104 | - const blocks: SearchReplaceBlockResult[] = []; | |
| 105 | - const lines = content.split("\n"); | |
| 106 | - | |
| 107 | - let currentBlockLines: string[] = []; | |
| 108 | - let inBlock = false; | |
| 109 | - | |
| 110 | - for (const line of lines) { | |
| 111 | - if (SEARCH_BLOCK_START_REGEX.test(line)) { | |
| 112 | - // Start of new block | |
| 113 | - if (inBlock && currentBlockLines.length > 0) { | |
| 114 | - // Process previous incomplete block if any | |
| 115 | - const blockContent = currentBlockLines.join("\n"); | |
| 116 | - const result = parseSearchReplaceBlock(blockContent); | |
| 117 | - if (result.isComplete) { | |
| 118 | - blocks.push(result); | |
| 119 | - } else if (result.error) { | |
| 120 | - // Fail fast on any parsing error | |
| 121 | - throw new Error(result.error); | |
| 122 | - } | |
| 123 | - // If incomplete but no error, it's just a partial block - continue processing | |
| 124 | - } | |
| 125 | - currentBlockLines = [line]; | |
| 126 | - inBlock = true; | |
| 127 | - } else if (inBlock) { | |
| 128 | - currentBlockLines.push(line); | |
| 129 | - | |
| 130 | - // Check if this line completes the current block | |
| 131 | - if (REPLACE_BLOCK_END_REGEX.test(line)) { | |
| 132 | - const blockContent = currentBlockLines.join("\n"); | |
| 133 | - const result = parseSearchReplaceBlock(blockContent); | |
| 134 | - if (result.isComplete) { | |
| 135 | - blocks.push(result); | |
| 136 | - } else if (result.error) { | |
| 137 | - // Fail fast on any parsing error | |
| 138 | - throw new Error(result.error); | |
| 139 | - } | |
| 140 | - currentBlockLines = []; | |
| 141 | - inBlock = false; | |
| 142 | - } | |
| 143 | - } | |
| 144 | - } | |
| 145 | - | |
| 146 | - return blocks; | |
| 147 | -} |
modified core/tools/builtIn.ts +0 −2
| @@ -1,7 +1,6 @@ | ||
| 1 | 1 | export enum BuiltInToolNames { |
| 2 | 2 | ReadFile = "read_file", |
| 3 | 3 | EditExistingFile = "edit_existing_file", |
| 4 | - SearchAndReplaceInFile = "search_and_replace_in_file", | |
| 5 | 4 | SingleFindAndReplace = "single_find_and_replace", |
| 6 | 5 | MultiEdit = "multi_edit", |
| 7 | 6 | ReadCurrentlyOpenFile = "read_currently_open_file", |
| @@ -26,7 +25,6 @@ | ||
| 26 | 25 | |
| 27 | 26 | export const CLIENT_TOOLS_IMPLS = [ |
| 28 | 27 | BuiltInToolNames.EditExistingFile, |
| 29 | - BuiltInToolNames.SearchAndReplaceInFile, | |
| 30 | 28 | BuiltInToolNames.SingleFindAndReplace, |
| 31 | 29 | BuiltInToolNames.MultiEdit, |
| 32 | 30 | ]; |
modified core/tools/definitions/editFile.ts +4 −2
| @@ -1,13 +1,15 @@ | ||
| 1 | 1 | import { Tool } from "../.."; |
| 2 | 2 | import { EDIT_CODE_INSTRUCTIONS } from "../../llm/defaultSystemMessages"; |
| 3 | 3 | import { BUILT_IN_GROUP_NAME, BuiltInToolNames } from "../builtIn"; |
| 4 | -import { NO_PARALLEL_TOOL_CALLING_INSRUCTION } from "./searchAndReplaceInFile"; | |
| 5 | 4 | |
| 6 | 5 | export interface EditToolArgs { |
| 7 | 6 | filepath: string; |
| 8 | 7 | changes: string; |
| 9 | 8 | } |
| 10 | 9 | |
| 10 | +export const NO_PARALLEL_TOOL_CALLING_INTSRUCTION = | |
| 11 | + "Note this tool CANNOT be called in parallel with other tools."; | |
| 12 | + | |
| 11 | 13 | const CHANGES_DESCRIPTION = |
| 12 | 14 | "Any modifications to the file, showing only needed changes. Do NOT wrap this in a codeblock or write anything besides the code changes. In larger files, use brief language-appropriate placeholders for large unmodified sections, e.g. '// ... existing code ...'"; |
| 13 | 15 | |
| @@ -22,7 +24,7 @@ | ||
| 22 | 24 | isInstant: false, |
| 23 | 25 | function: { |
| 24 | 26 | name: BuiltInToolNames.EditExistingFile, |
| 25 | - description: `Use this tool to edit an existing file. If you don't know the contents of the file, read it first.\n${EDIT_CODE_INSTRUCTIONS}\n${NO_PARALLEL_TOOL_CALLING_INSRUCTION}`, | |
| 27 | + description: `Use this tool to edit an existing file. If you don't know the contents of the file, read it first.\n${EDIT_CODE_INSTRUCTIONS}\n${NO_PARALLEL_TOOL_CALLING_INTSRUCTION}`, | |
| 26 | 28 | parameters: { |
| 27 | 29 | type: "object", |
| 28 | 30 | required: ["filepath", "changes"], |
modified core/tools/definitions/index.ts +0 −1
| @@ -11,7 +11,6 @@ | ||
| 11 | 11 | export { readFileTool } from "./readFile"; |
| 12 | 12 | export { requestRuleTool } from "./requestRule"; |
| 13 | 13 | export { runTerminalCommandTool } from "./runTerminalCommand"; |
| 14 | -export { searchAndReplaceInFileTool } from "./searchAndReplaceInFile"; | |
| 15 | 14 | export { searchWebTool } from "./searchWeb"; |
| 16 | 15 | export { singleFindAndReplaceTool } from "./singleFindAndReplace"; |
| 17 | 16 | export { viewDiffTool } from "./viewDiff"; |
modified core/tools/definitions/multiEdit.ts +2 −0
| @@ -1,5 +1,6 @@ | ||
| 1 | 1 | import { Tool } from "../.."; |
| 2 | 2 | import { BUILT_IN_GROUP_NAME, BuiltInToolNames } from "../builtIn"; |
| 3 | +import { NO_PARALLEL_TOOL_CALLING_INTSRUCTION } from "./editFile"; | |
| 3 | 4 | |
| 4 | 5 | export interface EditOperation { |
| 5 | 6 | old_string: string; |
| @@ -54,6 +55,7 @@ | ||
| 54 | 55 | 1. All edits follow the same requirements as the single find and replace tool |
| 55 | 56 | 2. The edits are atomic - either all succeed or none are applied |
| 56 | 57 | 3. Plan your edits carefully to avoid conflicts between sequential operations |
| 58 | +4. ${NO_PARALLEL_TOOL_CALLING_INTSRUCTION} | |
| 57 | 59 | |
| 58 | 60 | WARNING: |
| 59 | 61 |
deleted core/tools/definitions/searchAndReplaceInFile.ts +0 −112
| @@ -1,112 +0,0 @@ | ||
| 1 | -import { Tool } from "../.."; | |
| 2 | -import { BUILT_IN_GROUP_NAME, BuiltInToolNames } from "../builtIn"; | |
| 3 | - | |
| 4 | -export interface SearchAndReplaceInFileArgs { | |
| 5 | - filepath: string; | |
| 6 | - diffs: string[]; | |
| 7 | -} | |
| 8 | - | |
| 9 | -// Currently unsupported and filtered out in `gui/src/redux/slices/sessionSlice.ts` | |
| 10 | -export const NO_PARALLEL_TOOL_CALLING_INSRUCTION = | |
| 11 | - "Note this tool CANNOT be called in parallel."; | |
| 12 | - | |
| 13 | -const SEARCH_AND_REPLACE_EXAMPLE_BLOCK = `------- SEARCH | |
| 14 | -[exact content to find] | |
| 15 | -======= | |
| 16 | -[new content to replace with] | |
| 17 | -+++++++ REPLACE`; | |
| 18 | - | |
| 19 | -const SEARCH_AND_REPLACE_RULES = `Critical rules: | |
| 20 | -1. SEARCH content must match the associated file section to find EXACTLY: | |
| 21 | - * Match character-for-character including whitespace, indentation, line endings | |
| 22 | - * Include all comments, docstrings, etc. | |
| 23 | -2. SEARCH/REPLACE blocks will ONLY replace the first match occurrence. | |
| 24 | - * Including multiple unique SEARCH/REPLACE blocks if you need to make multiple changes. | |
| 25 | - * Include *just* enough lines in each SEARCH section to uniquely match each set of lines that need to change. | |
| 26 | - * When using multiple SEARCH/REPLACE blocks, list them in the order they appear in the file. | |
| 27 | -3. **Order matters**: DIFFs in the array should be ordered from top to bottom of the file to ensure correct application. | |
| 28 | -4. Keep SEARCH/REPLACE blocks concise: | |
| 29 | - * Break large SEARCH/REPLACE blocks into a series of smaller blocks that each change a small portion of the file. | |
| 30 | - * Include just the changing lines, and a few surrounding lines if needed for uniqueness. | |
| 31 | - * Do not include long runs of unchanging lines in SEARCH/REPLACE blocks. | |
| 32 | - * Each line must be complete. Never truncate lines mid-way through as this can cause matching failures. | |
| 33 | -5. Splitting up tool calls: | |
| 34 | - * When making multiple closely related edits to the same file, you should try to use multiple SEARCH/REPLACE blocks in a single tool call, rather than making multiple separate tool calls | |
| 35 | - * If you need to make follow up edits or group your work into logical segments, it is okay to perform additional tool calls | |
| 36 | - * DO NOT make back-to-back tool calls. Instead interleave with brief explanation of what each will do. For example, instead of [explanation, tool call, tool call] you should do [explanation, tool call, explanation, tool call] | |
| 37 | -6. Special operations: | |
| 38 | - * To move code: Use two SEARCH/REPLACE blocks (one to delete from original + one to insert at new location) | |
| 39 | - * To delete code: Use empty REPLACE section | |
| 40 | -7. You should always read the file before trying to edit it, to ensure you know the up-to-date file contents`; | |
| 41 | - | |
| 42 | -const SEARCH_AND_REPLACE_DIFFS_DESCRIPTION = `An array of strings, each containing one or more SEARCH/REPLACE blocks following this exact format: | |
| 43 | -\`\`\` | |
| 44 | -${SEARCH_AND_REPLACE_EXAMPLE_BLOCK} | |
| 45 | -\`\`\` | |
| 46 | - | |
| 47 | -${SEARCH_AND_REPLACE_RULES} | |
| 48 | - | |
| 49 | -Usage: | |
| 50 | -\`\`\` | |
| 51 | -${SEARCH_AND_REPLACE_EXAMPLE_BLOCK} | |
| 52 | - | |
| 53 | -${SEARCH_AND_REPLACE_EXAMPLE_BLOCK} | |
| 54 | -\`\`\` | |
| 55 | - | |
| 56 | -Each string in the diffs array can contain multiple SEARCH/REPLACE blocks, and all will be applied sequentially in the order they appear.`; | |
| 57 | - | |
| 58 | -/** | |
| 59 | - * This tool is in an experimental state. | |
| 60 | - * Our starting point is heavily inspired by Cline's `replace_in_file` tool: https://github.com/cline/cline/blob/2709ccefcddc616e89a70962f017bcbbca1f17bf/src/core/prompts/system.ts#L87-L121 | |
| 61 | - */ | |
| 62 | -export const searchAndReplaceInFileTool: Tool = { | |
| 63 | - type: "function", | |
| 64 | - displayTitle: "Edit File", | |
| 65 | - wouldLikeTo: "edit {{{ filepath }}}", | |
| 66 | - isCurrently: "editing {{{ filepath }}}", | |
| 67 | - hasAlready: "edited {{{ filepath }}}", | |
| 68 | - group: BUILT_IN_GROUP_NAME, | |
| 69 | - readonly: false, | |
| 70 | - isInstant: false, | |
| 71 | - function: { | |
| 72 | - name: BuiltInToolNames.SearchAndReplaceInFile, | |
| 73 | - description: `Request to replace sections of content in an existing file using multiple SEARCH/REPLACE blocks that define exact changes to specific parts of the file. This tool should be used when you need to make targeted changes to specific parts of a file. ${NO_PARALLEL_TOOL_CALLING_INSRUCTION}`, | |
| 74 | - parameters: { | |
| 75 | - type: "object", | |
| 76 | - required: ["filepath", "diffs"], | |
| 77 | - properties: { | |
| 78 | - filepath: { | |
| 79 | - type: "string", | |
| 80 | - description: `The path of the file to modify, relative to the root of the workspace.`, | |
| 81 | - }, | |
| 82 | - diffs: { | |
| 83 | - type: "array", | |
| 84 | - items: { | |
| 85 | - type: "string", | |
| 86 | - }, | |
| 87 | - description: SEARCH_AND_REPLACE_DIFFS_DESCRIPTION, | |
| 88 | - }, | |
| 89 | - }, | |
| 90 | - }, | |
| 91 | - }, | |
| 92 | - systemMessageDescription: { | |
| 93 | - prefix: `To make targeted edits by replacing sections of content in an existing file, use the ${BuiltInToolNames.SearchAndReplaceInFile} tool with a filepath (relative to the root of the workspace) and a "diffs" argument containing an array of SEARCH/REPLACE blocks that define exact changes to specific parts of the file. | |
| 94 | -Each block should follow this format: | |
| 95 | -${SEARCH_AND_REPLACE_EXAMPLE_BLOCK} | |
| 96 | - | |
| 97 | -${SEARCH_AND_REPLACE_RULES} | |
| 98 | - | |
| 99 | - For example, you could respond with:`, | |
| 100 | - exampleArgs: [ | |
| 101 | - ["filepath", "path/to/file.ts"], | |
| 102 | - [ | |
| 103 | - "diffs", | |
| 104 | - `[ | |
| 105 | -"${SEARCH_AND_REPLACE_EXAMPLE_BLOCK}", | |
| 106 | -"${SEARCH_AND_REPLACE_EXAMPLE_BLOCK}" | |
| 107 | -]`, | |
| 108 | - ], | |
| 109 | - ], | |
| 110 | - }, | |
| 111 | - defaultToolPolicy: "allowedWithPermission", | |
| 112 | -}; |
modified core/tools/definitions/singleFindAndReplace.ts +3 −0
| @@ -1,5 +1,6 @@ | ||
| 1 | 1 | import { Tool } from "../.."; |
| 2 | 2 | import { BUILT_IN_GROUP_NAME, BuiltInToolNames } from "../builtIn"; |
| 3 | +import { NO_PARALLEL_TOOL_CALLING_INTSRUCTION } from "./editFile"; | |
| 3 | 4 | |
| 4 | 5 | export interface SingleFindAndReplaceArgs { |
| 5 | 6 | filepath: string; |
| @@ -38,6 +39,8 @@ | ||
| 38 | 39 | - Only use emojis if the user explicitly requests it. Avoid adding emojis to |
| 39 | 40 | files unless asked. |
| 40 | 41 | |
| 42 | +- ${NO_PARALLEL_TOOL_CALLING_INTSRUCTION} | |
| 43 | + | |
| 41 | 44 | - The edit will FAIL if \`old_string\` is not unique in the file. Either provide |
| 42 | 45 | a larger string with more surrounding context to make it unique or use |
| 43 | 46 | \`replace_all\` to change every instance of \`old_string\`. |
modified core/tools/index.ts +0 −2
| @@ -36,8 +36,6 @@ | ||
| 36 | 36 | ); |
| 37 | 37 | } |
| 38 | 38 | |
| 39 | - // OLD SEARCH AND REPLACE IS CURRENTLY NOT USED | |
| 40 | - // toolDefinitions.searchAndReplaceInFileTool | |
| 41 | 39 | if (modelName?.includes("claude") || modelName?.includes("gpt-5")) { |
| 42 | 40 | tools.push(toolDefinitions.multiEditTool); |
| 43 | 41 | } else { |
modified gui/src/pages/gui/ToolCallDiv/FunctionSpecificToolCallDiv.tsx +0 −17
| @@ -34,23 +34,6 @@ | ||
| 34 | 34 | historyIndex={historyIndex} |
| 35 | 35 | /> |
| 36 | 36 | ); |
| 37 | - case BuiltInToolNames.SearchAndReplaceInFile: | |
| 38 | - const changes = args?.diffs | |
| 39 | - ? Array.isArray(args.diffs) | |
| 40 | - ? args.diffs?.join("\n\n---\n\n") | |
| 41 | - : args.diffs | |
| 42 | - : ""; | |
| 43 | - | |
| 44 | - return ( | |
| 45 | - <EditFile | |
| 46 | - showToolCallStatusIcon={true} | |
| 47 | - status={toolCallState.status} | |
| 48 | - relativeFilePath={args?.filepath ?? ""} | |
| 49 | - changes={changes} | |
| 50 | - toolCallId={toolCall.id} | |
| 51 | - historyIndex={historyIndex} | |
| 52 | - /> | |
| 53 | - ); | |
| 54 | 37 | case BuiltInToolNames.SingleFindAndReplace: |
| 55 | 38 | const edits: EditOperation[] = [ |
| 56 | 39 | { |
modified gui/src/pages/gui/ToolCallDiv/index.tsx +0 −1
| @@ -55,7 +55,6 @@ | ||
| 55 | 55 | // All the info from args is displayed here |
| 56 | 56 | // But we'd need a nicer place to put the truncate button and the X icon when tool call fails |
| 57 | 57 | if ( |
| 58 | - functionName === BuiltInToolNames.SearchAndReplaceInFile || | |
| 59 | 58 | functionName === BuiltInToolNames.SingleFindAndReplace || |
| 60 | 59 | functionName === BuiltInToolNames.MultiEdit |
| 61 | 60 | ) { |
modified gui/src/redux/slices/sessionSlice.ts +1 −4
| @@ -50,10 +50,7 @@ | ||
| 50 | 50 | function filterMultipleEditToolCalls( |
| 51 | 51 | toolCalls: ToolCallDelta[], |
| 52 | 52 | ): ToolCallDelta[] { |
| 53 | - const editToolNames = [ | |
| 54 | - BuiltInToolNames.EditExistingFile, | |
| 55 | - BuiltInToolNames.SearchAndReplaceInFile, | |
| 56 | - ]; | |
| 53 | + const editToolNames = [BuiltInToolNames.EditExistingFile]; | |
| 57 | 54 | let hasSeenEditTool = false; |
| 58 | 55 | |
| 59 | 56 | return toolCalls.filter((toolCall) => { |
modified gui/src/redux/thunks/enhanceParsedArgs.ts +1 −2
| @@ -16,8 +16,7 @@ | ||
| 16 | 16 | let enhancedArgs = { ...currentArgs }; |
| 17 | 17 | if ( |
| 18 | 18 | (toolName === BuiltInToolNames.SingleFindAndReplace || |
| 19 | - toolName === BuiltInToolNames.MultiEdit || | |
| 20 | - toolName === BuiltInToolNames.SearchAndReplaceInFile) && | |
| 19 | + toolName === BuiltInToolNames.MultiEdit) && | |
| 21 | 20 | currentArgs?.filepath && |
| 22 | 21 | !currentArgs?.editingFileContents |
| 23 | 22 | ) { |
modified gui/src/util/clientTools/callClientTool.ts +0 −4
| @@ -4,7 +4,6 @@ | ||
| 4 | 4 | import { AppThunkDispatch, RootState } from "../../redux/store"; |
| 5 | 5 | import { editToolImpl } from "./editImpl"; |
| 6 | 6 | import { multiEditImpl } from "./multiEditImpl"; |
| 7 | -import { searchReplaceToolImpl } from "./searchReplaceImpl"; | |
| 8 | 7 | import { singleFindAndReplaceImpl } from "./singleFindAndReplaceImpl"; |
| 9 | 8 | |
| 10 | 9 | export interface ClientToolExtras { |
| @@ -39,9 +38,6 @@ | ||
| 39 | 38 | case BuiltInToolNames.EditExistingFile: |
| 40 | 39 | output = await editToolImpl(parsedArgs, toolCall.id, extras); |
| 41 | 40 | break; |
| 42 | - case BuiltInToolNames.SearchAndReplaceInFile: | |
| 43 | - output = await searchReplaceToolImpl(parsedArgs, toolCall.id, extras); | |
| 44 | - break; | |
| 45 | 41 | case BuiltInToolNames.SingleFindAndReplace: |
| 46 | 42 | output = await singleFindAndReplaceImpl( |
| 47 | 43 | parsedArgs, |
deleted gui/src/util/clientTools/searchReplaceImpl.test.ts +0 −695
| @@ -1,695 +0,0 @@ | ||
| 1 | -import { findSearchMatch } from "core/edit/searchAndReplace/findSearchMatch"; | |
| 2 | -import { parseAllSearchReplaceBlocks } from "core/edit/searchAndReplace/parseSearchReplaceBlock"; | |
| 3 | -import { resolveRelativePathInDir } from "core/util/ideUtils"; | |
| 4 | -import { beforeEach, describe, expect, it, vi } from "vitest"; | |
| 5 | -import { applyForEditTool } from "../../redux/thunks/handleApplyStateUpdate"; | |
| 6 | -import { ClientToolExtras } from "./callClientTool"; | |
| 7 | -import { searchReplaceToolImpl } from "./searchReplaceImpl"; | |
| 8 | - | |
| 9 | -// Mock the dependencies | |
| 10 | -vi.mock("core/edit/searchAndReplace/findSearchMatch"); | |
| 11 | -vi.mock("core/edit/searchAndReplace/parseSearchReplaceBlock"); | |
| 12 | -vi.mock("core/util/ideUtils"); | |
| 13 | -vi.mock("uuid", () => ({ | |
| 14 | - v4: vi.fn(() => "test-stream-id"), | |
| 15 | -})); | |
| 16 | -vi.mock("../../redux/thunks/handleApplyStateUpdate", () => ({ | |
| 17 | - applyForEditTool: vi.fn(), | |
| 18 | -})); | |
| 19 | - | |
| 20 | -const mockFindSearchMatch = vi.mocked(findSearchMatch); | |
| 21 | -const mockParseAllSearchReplaceBlocks = vi.mocked(parseAllSearchReplaceBlocks); | |
| 22 | -const mockResolveRelativePathInDir = vi.mocked(resolveRelativePathInDir); | |
| 23 | -const mockApplyForEditTool = vi.mocked(applyForEditTool); | |
| 24 | - | |
| 25 | -describe("searchReplaceToolImpl", () => { | |
| 26 | - let mockExtras: ClientToolExtras; | |
| 27 | - let mockIdeMessenger: any; | |
| 28 | - | |
| 29 | - beforeEach(() => { | |
| 30 | - // Reset all mocks | |
| 31 | - vi.clearAllMocks(); | |
| 32 | - | |
| 33 | - // Create mock IDE messenger | |
| 34 | - mockIdeMessenger = { | |
| 35 | - ide: { | |
| 36 | - readFile: vi.fn(), | |
| 37 | - }, | |
| 38 | - request: vi.fn(), | |
| 39 | - }; | |
| 40 | - | |
| 41 | - // Create mock extras | |
| 42 | - mockExtras = { | |
| 43 | - ideMessenger: mockIdeMessenger, | |
| 44 | - getState: vi.fn<any>(() => ({ | |
| 45 | - config: { | |
| 46 | - config: { | |
| 47 | - allowAnonymousTelemetry: false, | |
| 48 | - }, | |
| 49 | - }, | |
| 50 | - })), | |
| 51 | - dispatch: vi.fn(), | |
| 52 | - }; | |
| 53 | - }); | |
| 54 | - | |
| 55 | - describe("basic validation", () => { | |
| 56 | - it("should throw error when file does not exist", async () => { | |
| 57 | - mockResolveRelativePathInDir.mockResolvedValue(undefined); | |
| 58 | - | |
| 59 | - await expect( | |
| 60 | - searchReplaceToolImpl( | |
| 61 | - { filepath: "nonexistent.txt", diffs: ["some diff"] }, | |
| 62 | - "tool-call-id", | |
| 63 | - mockExtras, | |
| 64 | - ), | |
| 65 | - ).rejects.toThrow("File nonexistent.txt does not exist"); | |
| 66 | - }); | |
| 67 | - | |
| 68 | - it("should throw error when no search/replace blocks found in first diff", async () => { | |
| 69 | - mockResolveRelativePathInDir.mockResolvedValue("/resolved/path/test.txt"); | |
| 70 | - mockParseAllSearchReplaceBlocks.mockReturnValue([]); | |
| 71 | - | |
| 72 | - await expect( | |
| 73 | - searchReplaceToolImpl( | |
| 74 | - { filepath: "test.txt", diffs: ["invalid diff content"] }, | |
| 75 | - "tool-call-id", | |
| 76 | - mockExtras, | |
| 77 | - ), | |
| 78 | - ).rejects.toThrow("No complete search/replace blocks found in diff 1"); | |
| 79 | - }); | |
| 80 | - | |
| 81 | - it("should throw error when no search/replace blocks found in second diff", async () => { | |
| 82 | - mockResolveRelativePathInDir.mockResolvedValue("/resolved/path/test.txt"); | |
| 83 | - mockParseAllSearchReplaceBlocks | |
| 84 | - .mockReturnValueOnce([ | |
| 85 | - { | |
| 86 | - isComplete: true, | |
| 87 | - searchContent: "valid content", | |
| 88 | - replaceContent: "replacement", | |
| 89 | - }, | |
| 90 | - ]) | |
| 91 | - .mockReturnValueOnce([]); | |
| 92 | - | |
| 93 | - await expect( | |
| 94 | - searchReplaceToolImpl( | |
| 95 | - { | |
| 96 | - filepath: "test.txt", | |
| 97 | - diffs: ["valid diff", "invalid diff content"], | |
| 98 | - }, | |
| 99 | - "tool-call-id", | |
| 100 | - mockExtras, | |
| 101 | - ), | |
| 102 | - ).rejects.toThrow("No complete search/replace blocks found in diff 2"); | |
| 103 | - }); | |
| 104 | - | |
| 105 | - it("should throw error when all diffs are empty", async () => { | |
| 106 | - mockResolveRelativePathInDir.mockResolvedValue("/resolved/path/test.txt"); | |
| 107 | - mockParseAllSearchReplaceBlocks.mockReturnValue([]); | |
| 108 | - | |
| 109 | - await expect( | |
| 110 | - searchReplaceToolImpl( | |
| 111 | - { filepath: "test.txt", diffs: [] }, | |
| 112 | - "tool-call-id", | |
| 113 | - mockExtras, | |
| 114 | - ), | |
| 115 | - ).rejects.toThrow("No complete search/replace blocks found in any diffs"); | |
| 116 | - }); | |
| 117 | - }); | |
| 118 | - | |
| 119 | - describe("single block replacement", () => { | |
| 120 | - it("should successfully apply single search/replace block", async () => { | |
| 121 | - const originalContent = `function hello() { | |
| 122 | - console.log("Hello"); | |
| 123 | - return "world"; | |
| 124 | -}`; | |
| 125 | - | |
| 126 | - const expectedFinalContent = `function hello() { | |
| 127 | - console.log("Hi there!"); | |
| 128 | - return "world"; | |
| 129 | -}`; | |
| 130 | - | |
| 131 | - // Setup mocks | |
| 132 | - mockResolveRelativePathInDir.mockResolvedValue("/resolved/path/test.js"); | |
| 133 | - mockParseAllSearchReplaceBlocks.mockReturnValue([ | |
| 134 | - { | |
| 135 | - isComplete: true, | |
| 136 | - searchContent: 'console.log("Hello");', | |
| 137 | - replaceContent: 'console.log("Hi there!");', | |
| 138 | - }, | |
| 139 | - ]); | |
| 140 | - mockIdeMessenger.ide.readFile.mockResolvedValue(originalContent); | |
| 141 | - | |
| 142 | - // Calculate correct positions for 'console.log("Hello");' in the original content | |
| 143 | - const searchText = 'console.log("Hello");'; | |
| 144 | - const startIndex = originalContent.indexOf(searchText); | |
| 145 | - const endIndex = startIndex + searchText.length; | |
| 146 | - | |
| 147 | - mockFindSearchMatch.mockReturnValue({ | |
| 148 | - startIndex, | |
| 149 | - endIndex, | |
| 150 | - strategyName: "exactMatch", | |
| 151 | - }); | |
| 152 | - const result = await searchReplaceToolImpl( | |
| 153 | - { filepath: "test.js", diffs: ["mock diff content"] }, | |
| 154 | - "tool-call-id", | |
| 155 | - mockExtras, | |
| 156 | - ); | |
| 157 | - | |
| 158 | - // Verify the result | |
| 159 | - expect(result).toEqual({ | |
| 160 | - respondImmediately: false, | |
| 161 | - output: undefined, | |
| 162 | - }); | |
| 163 | - | |
| 164 | - // Verify applyToFile was called with correct parameters | |
| 165 | - expect(mockApplyForEditTool).toHaveBeenCalledWith({ | |
| 166 | - text: expectedFinalContent, | |
| 167 | - streamId: "test-stream-id", | |
| 168 | - filepath: "/resolved/path/test.js", | |
| 169 | - toolCallId: "tool-call-id", | |
| 170 | - isSearchAndReplace: true, | |
| 171 | - }); | |
| 172 | - }); | |
| 173 | - }); | |
| 174 | - | |
| 175 | - describe("single diff scenarios", () => { | |
| 176 | - it("should successfully apply single diff with single search/replace block", async () => { | |
| 177 | - const originalContent = `function hello() { | |
| 178 | - console.log("Hello"); | |
| 179 | - return "world"; | |
| 180 | -}`; | |
| 181 | - | |
| 182 | - const expectedFinalContent = `function hello() { | |
| 183 | - console.log("Hi there!"); | |
| 184 | - return "world"; | |
| 185 | -}`; | |
| 186 | - | |
| 187 | - // Setup mocks | |
| 188 | - mockResolveRelativePathInDir.mockResolvedValue("/resolved/path/test.js"); | |
| 189 | - mockParseAllSearchReplaceBlocks.mockReturnValue([ | |
| 190 | - { | |
| 191 | - isComplete: true, | |
| 192 | - searchContent: 'console.log("Hello");', | |
| 193 | - replaceContent: 'console.log("Hi there!");', | |
| 194 | - }, | |
| 195 | - ]); | |
| 196 | - mockIdeMessenger.ide.readFile.mockResolvedValue(originalContent); | |
| 197 | - | |
| 198 | - // Calculate correct positions for 'console.log("Hello");' in the original content | |
| 199 | - const searchText = 'console.log("Hello");'; | |
| 200 | - const startIndex = originalContent.indexOf(searchText); | |
| 201 | - const endIndex = startIndex + searchText.length; | |
| 202 | - | |
| 203 | - mockFindSearchMatch.mockReturnValue({ | |
| 204 | - startIndex, | |
| 205 | - endIndex, | |
| 206 | - strategyName: "exactMatch", | |
| 207 | - }); | |
| 208 | - const result = await searchReplaceToolImpl( | |
| 209 | - { filepath: "test.js", diffs: ["mock diff content"] }, | |
| 210 | - "tool-call-id", | |
| 211 | - mockExtras, | |
| 212 | - ); | |
| 213 | - | |
| 214 | - // Verify the result | |
| 215 | - expect(result).toEqual({ | |
| 216 | - respondImmediately: false, | |
| 217 | - output: undefined, | |
| 218 | - }); | |
| 219 | - | |
| 220 | - // Verify applyToFile was called with correct parameters | |
| 221 | - expect(mockApplyForEditTool).toHaveBeenCalledWith({ | |
| 222 | - text: expectedFinalContent, | |
| 223 | - streamId: "test-stream-id", | |
| 224 | - filepath: "/resolved/path/test.js", | |
| 225 | - toolCallId: "tool-call-id", | |
| 226 | - isSearchAndReplace: true, | |
| 227 | - }); | |
| 228 | - }); | |
| 229 | - }); | |
| 230 | - | |
| 231 | - describe("multiple block replacement", () => { | |
| 232 | - it("should successfully apply multiple search/replace blocks sequentially", async () => { | |
| 233 | - const originalContent = `const a = 1; | |
| 234 | -const b = 2; | |
| 235 | -const c = 3;`; | |
| 236 | - | |
| 237 | - const expectedFinalContent = `const a = 100; | |
| 238 | -const b = 200; | |
| 239 | -const c = 3;`; | |
| 240 | - | |
| 241 | - // Setup mocks | |
| 242 | - mockResolveRelativePathInDir.mockResolvedValue("/resolved/path/test.js"); | |
| 243 | - mockParseAllSearchReplaceBlocks.mockReturnValue([ | |
| 244 | - { | |
| 245 | - isComplete: true, | |
| 246 | - searchContent: "const a = 1;", | |
| 247 | - replaceContent: "const a = 100;", | |
| 248 | - }, | |
| 249 | - { | |
| 250 | - isComplete: true, | |
| 251 | - searchContent: "const b = 2;", | |
| 252 | - replaceContent: "const b = 200;", | |
| 253 | - }, | |
| 254 | - ]); | |
| 255 | - mockIdeMessenger.ide.readFile.mockResolvedValue(originalContent); | |
| 256 | - | |
| 257 | - // Calculate positions for sequential replacements | |
| 258 | - const firstSearchText = "const a = 1;"; | |
| 259 | - const secondSearchText = "const b = 2;"; | |
| 260 | - | |
| 261 | - const firstStartIndex = originalContent.indexOf(firstSearchText); | |
| 262 | - const firstEndIndex = firstStartIndex + firstSearchText.length; | |
| 263 | - | |
| 264 | - // After first replacement: "const a = 100;\nconst b = 2;\nconst c = 3;" | |
| 265 | - const contentAfterFirstReplacement = | |
| 266 | - originalContent.substring(0, firstStartIndex) + | |
| 267 | - "const a = 100;" + | |
| 268 | - originalContent.substring(firstEndIndex); | |
| 269 | - | |
| 270 | - const secondStartIndex = | |
| 271 | - contentAfterFirstReplacement.indexOf(secondSearchText); | |
| 272 | - const secondEndIndex = secondStartIndex + secondSearchText.length; | |
| 273 | - | |
| 274 | - // Mock sequential search matches | |
| 275 | - mockFindSearchMatch | |
| 276 | - .mockReturnValueOnce({ | |
| 277 | - startIndex: firstStartIndex, | |
| 278 | - endIndex: firstEndIndex, | |
| 279 | - strategyName: "exactMatch", | |
| 280 | - }) | |
| 281 | - .mockReturnValueOnce({ | |
| 282 | - startIndex: secondStartIndex, | |
| 283 | - endIndex: secondEndIndex, | |
| 284 | - strategyName: "exactMatch", | |
| 285 | - }); | |
| 286 | - | |
| 287 | - const result = await searchReplaceToolImpl( | |
| 288 | - { filepath: "test.js", diffs: ["mock diff content"] }, | |
| 289 | - "tool-call-id", | |
| 290 | - mockExtras, | |
| 291 | - ); | |
| 292 | - | |
| 293 | - // Verify the result | |
| 294 | - expect(result).toEqual({ | |
| 295 | - respondImmediately: false, | |
| 296 | - output: undefined, | |
| 297 | - }); | |
| 298 | - | |
| 299 | - // Verify findSearchMatch was called twice with updated content | |
| 300 | - expect(mockFindSearchMatch).toHaveBeenCalledTimes(2); | |
| 301 | - expect(mockFindSearchMatch).toHaveBeenNthCalledWith( | |
| 302 | - 1, | |
| 303 | - originalContent, | |
| 304 | - "const a = 1;", | |
| 305 | - ); | |
| 306 | - expect(mockFindSearchMatch).toHaveBeenNthCalledWith( | |
| 307 | - 2, | |
| 308 | - contentAfterFirstReplacement, | |
| 309 | - "const b = 2;", | |
| 310 | - ); | |
| 311 | - // Verify final applyToFile call | |
| 312 | - expect(mockApplyForEditTool).toHaveBeenCalledWith({ | |
| 313 | - text: expectedFinalContent, | |
| 314 | - streamId: "test-stream-id", | |
| 315 | - filepath: "/resolved/path/test.js", | |
| 316 | - toolCallId: "tool-call-id", | |
| 317 | - isSearchAndReplace: true, | |
| 318 | - }); | |
| 319 | - }); | |
| 320 | - }); | |
| 321 | - | |
| 322 | - describe("multiple diff scenarios", () => { | |
| 323 | - it("should successfully apply multiple diffs each with single search/replace block", async () => { | |
| 324 | - const originalContent = `const a = 1; | |
| 325 | -const b = 2; | |
| 326 | -const c = 3;`; | |
| 327 | - | |
| 328 | - const expectedFinalContent = `const a = 100; | |
| 329 | -const b = 200; | |
| 330 | -const c = 3;`; | |
| 331 | - | |
| 332 | - // Setup mocks - each diff returns one block | |
| 333 | - mockResolveRelativePathInDir.mockResolvedValue("/resolved/path/test.js"); | |
| 334 | - mockParseAllSearchReplaceBlocks | |
| 335 | - .mockReturnValueOnce([ | |
| 336 | - { | |
| 337 | - isComplete: true, | |
| 338 | - searchContent: "const a = 1;", | |
| 339 | - replaceContent: "const a = 100;", | |
| 340 | - }, | |
| 341 | - ]) | |
| 342 | - .mockReturnValueOnce([ | |
| 343 | - { | |
| 344 | - isComplete: true, | |
| 345 | - searchContent: "const b = 2;", | |
| 346 | - replaceContent: "const b = 200;", | |
| 347 | - }, | |
| 348 | - ]); | |
| 349 | - mockIdeMessenger.ide.readFile.mockResolvedValue(originalContent); | |
| 350 | - | |
| 351 | - // Calculate positions for sequential replacements | |
| 352 | - const firstSearchText = "const a = 1;"; | |
| 353 | - const secondSearchText = "const b = 2;"; | |
| 354 | - | |
| 355 | - const firstStartIndex = originalContent.indexOf(firstSearchText); | |
| 356 | - const firstEndIndex = firstStartIndex + firstSearchText.length; | |
| 357 | - | |
| 358 | - // After first replacement: "const a = 100;\nconst b = 2;\nconst c = 3;" | |
| 359 | - const contentAfterFirstReplacement = | |
| 360 | - originalContent.substring(0, firstStartIndex) + | |
| 361 | - "const a = 100;" + | |
| 362 | - originalContent.substring(firstEndIndex); | |
| 363 | - | |
| 364 | - const secondStartIndex = | |
| 365 | - contentAfterFirstReplacement.indexOf(secondSearchText); | |
| 366 | - const secondEndIndex = secondStartIndex + secondSearchText.length; | |
| 367 | - | |
| 368 | - // Mock sequential search matches | |
| 369 | - mockFindSearchMatch | |
| 370 | - .mockReturnValueOnce({ | |
| 371 | - startIndex: firstStartIndex, | |
| 372 | - endIndex: firstEndIndex, | |
| 373 | - strategyName: "exactMatch", | |
| 374 | - }) | |
| 375 | - .mockReturnValueOnce({ | |
| 376 | - startIndex: secondStartIndex, | |
| 377 | - endIndex: secondEndIndex, | |
| 378 | - strategyName: "exactMatch", | |
| 379 | - }); | |
| 380 | - | |
| 381 | - const result = await searchReplaceToolImpl( | |
| 382 | - { filepath: "test.js", diffs: ["first diff", "second diff"] }, | |
| 383 | - "tool-call-id", | |
| 384 | - mockExtras, | |
| 385 | - ); | |
| 386 | - | |
| 387 | - // Verify the result | |
| 388 | - expect(result).toEqual({ | |
| 389 | - respondImmediately: false, | |
| 390 | - output: undefined, | |
| 391 | - }); | |
| 392 | - | |
| 393 | - // Verify parseAllSearchReplaceBlocks was called for each diff | |
| 394 | - expect(mockParseAllSearchReplaceBlocks).toHaveBeenCalledTimes(2); | |
| 395 | - expect(mockParseAllSearchReplaceBlocks).toHaveBeenNthCalledWith( | |
| 396 | - 1, | |
| 397 | - "first diff", | |
| 398 | - ); | |
| 399 | - expect(mockParseAllSearchReplaceBlocks).toHaveBeenNthCalledWith( | |
| 400 | - 2, | |
| 401 | - "second diff", | |
| 402 | - ); | |
| 403 | - | |
| 404 | - // Verify final applyToFile call | |
| 405 | - expect(mockApplyForEditTool).toHaveBeenCalledWith({ | |
| 406 | - text: expectedFinalContent, | |
| 407 | - streamId: "test-stream-id", | |
| 408 | - filepath: "/resolved/path/test.js", | |
| 409 | - toolCallId: "tool-call-id", | |
| 410 | - isSearchAndReplace: true, | |
| 411 | - }); | |
| 412 | - }); | |
| 413 | - }); | |
| 414 | - | |
| 415 | - describe("deletion scenarios", () => { | |
| 416 | - it("should handle empty replacement (deletion)", async () => { | |
| 417 | - const originalContent = `keep this | |
| 418 | -remove this line | |
| 419 | -keep this too`; | |
| 420 | - | |
| 421 | - const expectedFinalContent = `keep this | |
| 422 | - | |
| 423 | -keep this too`; | |
| 424 | - | |
| 425 | - // Setup mocks | |
| 426 | - mockResolveRelativePathInDir.mockResolvedValue("/resolved/path/test.txt"); | |
| 427 | - mockParseAllSearchReplaceBlocks.mockReturnValue([ | |
| 428 | - { | |
| 429 | - isComplete: true, | |
| 430 | - searchContent: "remove this line", | |
| 431 | - replaceContent: "", | |
| 432 | - }, | |
| 433 | - ]); | |
| 434 | - mockIdeMessenger.ide.readFile.mockResolvedValue(originalContent); | |
| 435 | - mockFindSearchMatch.mockReturnValue({ | |
| 436 | - startIndex: 10, // Position of "remove this line" | |
| 437 | - endIndex: 26, // End of "remove this line" | |
| 438 | - strategyName: "exactMatch", | |
| 439 | - }); | |
| 440 | - | |
| 441 | - const result = await searchReplaceToolImpl( | |
| 442 | - { filepath: "test.txt", diffs: ["mock diff content"] }, | |
| 443 | - "tool-call-id", | |
| 444 | - mockExtras, | |
| 445 | - ); | |
| 446 | - | |
| 447 | - expect(result).toEqual({ | |
| 448 | - respondImmediately: false, | |
| 449 | - output: undefined, | |
| 450 | - }); | |
| 451 | - | |
| 452 | - expect(mockApplyForEditTool).toHaveBeenCalledWith({ | |
| 453 | - text: expectedFinalContent, | |
| 454 | - streamId: "test-stream-id", | |
| 455 | - filepath: "/resolved/path/test.txt", | |
| 456 | - toolCallId: "tool-call-id", | |
| 457 | - isSearchAndReplace: true, | |
| 458 | - }); | |
| 459 | - }); | |
| 460 | - | |
| 461 | - it("should handle undefined replaceContent as empty string", async () => { | |
| 462 | - const originalContent = "line1\nline2\nline3"; | |
| 463 | - const expectedFinalContent = "line1\n\nline3"; | |
| 464 | - | |
| 465 | - mockResolveRelativePathInDir.mockResolvedValue("/resolved/path/test.txt"); | |
| 466 | - mockParseAllSearchReplaceBlocks.mockReturnValue([ | |
| 467 | - { | |
| 468 | - isComplete: true, | |
| 469 | - searchContent: "line2", | |
| 470 | - replaceContent: undefined, // undefined should be treated as empty string | |
| 471 | - }, | |
| 472 | - ]); | |
| 473 | - mockIdeMessenger.ide.readFile.mockResolvedValue(originalContent); | |
| 474 | - mockFindSearchMatch.mockReturnValue({ | |
| 475 | - startIndex: 6, | |
| 476 | - endIndex: 11, | |
| 477 | - strategyName: "exactMatch", | |
| 478 | - }); | |
| 479 | - await searchReplaceToolImpl( | |
| 480 | - { filepath: "test.txt", diffs: ["mock diff content"] }, | |
| 481 | - "tool-call-id", | |
| 482 | - mockExtras, | |
| 483 | - ); | |
| 484 | - | |
| 485 | - expect(mockApplyForEditTool).toHaveBeenCalledWith({ | |
| 486 | - text: expectedFinalContent, | |
| 487 | - streamId: "test-stream-id", | |
| 488 | - filepath: "/resolved/path/test.txt", | |
| 489 | - toolCallId: "tool-call-id", | |
| 490 | - isSearchAndReplace: true, | |
| 491 | - }); | |
| 492 | - }); | |
| 493 | - }); | |
| 494 | - | |
| 495 | - describe("error handling", () => { | |
| 496 | - it("should throw error when search content is not found", async () => { | |
| 497 | - mockResolveRelativePathInDir.mockResolvedValue("/resolved/path/test.txt"); | |
| 498 | - mockParseAllSearchReplaceBlocks.mockReturnValue([ | |
| 499 | - { | |
| 500 | - isComplete: true, | |
| 501 | - searchContent: "nonexistent content", | |
| 502 | - replaceContent: "replacement", | |
| 503 | - }, | |
| 504 | - ]); | |
| 505 | - mockIdeMessenger.ide.readFile.mockResolvedValue("some file content"); | |
| 506 | - mockFindSearchMatch.mockReturnValue(null); // Search content not found | |
| 507 | - | |
| 508 | - await expect( | |
| 509 | - searchReplaceToolImpl( | |
| 510 | - { filepath: "test.txt", diffs: ["mock diff content"] }, | |
| 511 | - "tool-call-id", | |
| 512 | - mockExtras, | |
| 513 | - ), | |
| 514 | - ).rejects.toThrow( | |
| 515 | - "Search content not found in block 1:\nnonexistent content", | |
| 516 | - ); | |
| 517 | - }); | |
| 518 | - | |
| 519 | - it("should throw error when search content is not found in second block", async () => { | |
| 520 | - mockResolveRelativePathInDir.mockResolvedValue("/resolved/path/test.txt"); | |
| 521 | - mockParseAllSearchReplaceBlocks.mockReturnValue([ | |
| 522 | - { | |
| 523 | - isComplete: true, | |
| 524 | - searchContent: "found content", | |
| 525 | - replaceContent: "replacement1", | |
| 526 | - }, | |
| 527 | - { | |
| 528 | - isComplete: true, | |
| 529 | - searchContent: "missing content", | |
| 530 | - replaceContent: "replacement2", | |
| 531 | - }, | |
| 532 | - ]); | |
| 533 | - mockIdeMessenger.ide.readFile.mockResolvedValue( | |
| 534 | - "found content and other stuff", | |
| 535 | - ); | |
| 536 | - | |
| 537 | - // First search succeeds, second fails | |
| 538 | - mockFindSearchMatch | |
| 539 | - .mockReturnValueOnce({ | |
| 540 | - startIndex: 0, | |
| 541 | - endIndex: 13, | |
| 542 | - strategyName: "exactMatch", | |
| 543 | - }) | |
| 544 | - .mockReturnValueOnce(null); // Second search fails | |
| 545 | - | |
| 546 | - await expect( | |
| 547 | - searchReplaceToolImpl( | |
| 548 | - { filepath: "test.txt", diffs: ["mock diff content"] }, | |
| 549 | - "tool-call-id", | |
| 550 | - mockExtras, | |
| 551 | - ), | |
| 552 | - ).rejects.toThrow( | |
| 553 | - "Search content not found in block 2:\nmissing content", | |
| 554 | - ); | |
| 555 | - }); | |
| 556 | - | |
| 557 | - it("should handle file read errors", async () => { | |
| 558 | - mockResolveRelativePathInDir.mockResolvedValue("/resolved/path/test.txt"); | |
| 559 | - mockParseAllSearchReplaceBlocks.mockReturnValue([ | |
| 560 | - { | |
| 561 | - isComplete: true, | |
| 562 | - searchContent: "content", | |
| 563 | - replaceContent: "replacement", | |
| 564 | - }, | |
| 565 | - ]); | |
| 566 | - mockIdeMessenger.ide.readFile.mockRejectedValue( | |
| 567 | - new Error("File read error"), | |
| 568 | - ); | |
| 569 | - | |
| 570 | - await expect( | |
| 571 | - searchReplaceToolImpl( | |
| 572 | - { filepath: "test.txt", diffs: ["mock diff content"] }, | |
| 573 | - "tool-call-id", | |
| 574 | - mockExtras, | |
| 575 | - ), | |
| 576 | - ).rejects.toThrow("Failed to apply search and replace: File read error"); | |
| 577 | - }); | |
| 578 | - }); | |
| 579 | - | |
| 580 | - describe("edge cases", () => { | |
| 581 | - it("should handle empty search content", async () => { | |
| 582 | - const originalContent = "existing content"; | |
| 583 | - const expectedFinalContent = "new contentexisting content"; | |
| 584 | - | |
| 585 | - mockResolveRelativePathInDir.mockResolvedValue("/resolved/path/test.txt"); | |
| 586 | - mockParseAllSearchReplaceBlocks.mockReturnValue([ | |
| 587 | - { | |
| 588 | - isComplete: true, | |
| 589 | - searchContent: "", | |
| 590 | - replaceContent: "new content", | |
| 591 | - }, | |
| 592 | - ]); | |
| 593 | - mockIdeMessenger.ide.readFile.mockResolvedValue(originalContent); | |
| 594 | - mockFindSearchMatch.mockReturnValue({ | |
| 595 | - startIndex: 0, // Empty search matches at beginning | |
| 596 | - endIndex: 0, | |
| 597 | - strategyName: "exactMatch", | |
| 598 | - }); | |
| 599 | - await searchReplaceToolImpl( | |
| 600 | - { filepath: "test.txt", diffs: ["mock diff content"] }, | |
| 601 | - "tool-call-id", | |
| 602 | - mockExtras, | |
| 603 | - ); | |
| 604 | - | |
| 605 | - expect(mockApplyForEditTool).toHaveBeenCalledWith({ | |
| 606 | - text: expectedFinalContent, | |
| 607 | - streamId: "test-stream-id", | |
| 608 | - filepath: "/resolved/path/test.txt", | |
| 609 | - toolCallId: "tool-call-id", | |
| 610 | - isSearchAndReplace: true, | |
| 611 | - }); | |
| 612 | - }); | |
| 613 | - | |
| 614 | - it("should handle whole file replacement", async () => { | |
| 615 | - const originalContent = "old file content"; | |
| 616 | - const expectedFinalContent = "completely new content"; | |
| 617 | - | |
| 618 | - mockResolveRelativePathInDir.mockResolvedValue("/resolved/path/test.txt"); | |
| 619 | - mockParseAllSearchReplaceBlocks.mockReturnValue([ | |
| 620 | - { | |
| 621 | - isComplete: true, | |
| 622 | - searchContent: originalContent, | |
| 623 | - replaceContent: "completely new content", | |
| 624 | - }, | |
| 625 | - ]); | |
| 626 | - mockIdeMessenger.ide.readFile.mockResolvedValue(originalContent); | |
| 627 | - mockFindSearchMatch.mockReturnValue({ | |
| 628 | - startIndex: 0, | |
| 629 | - endIndex: originalContent.length, | |
| 630 | - strategyName: "exactMatch", | |
| 631 | - }); | |
| 632 | - | |
| 633 | - await searchReplaceToolImpl( | |
| 634 | - { filepath: "test.txt", diffs: ["mock diff content"] }, | |
| 635 | - "tool-call-id", | |
| 636 | - mockExtras, | |
| 637 | - ); | |
| 638 | - | |
| 639 | - expect(mockApplyForEditTool).toHaveBeenCalledWith({ | |
| 640 | - text: expectedFinalContent, | |
| 641 | - streamId: "test-stream-id", | |
| 642 | - filepath: "/resolved/path/test.txt", | |
| 643 | - toolCallId: "tool-call-id", | |
| 644 | - isSearchAndReplace: true, | |
| 645 | - }); | |
| 646 | - }); | |
| 647 | - }); | |
| 648 | - | |
| 649 | - describe("dependency integration", () => { | |
| 650 | - it("should call all dependencies with correct parameters", async () => { | |
| 651 | - const originalContent = "test content"; | |
| 652 | - | |
| 653 | - mockResolveRelativePathInDir.mockResolvedValue("/resolved/path/test.txt"); | |
| 654 | - mockParseAllSearchReplaceBlocks.mockReturnValue([ | |
| 655 | - { | |
| 656 | - isComplete: true, | |
| 657 | - searchContent: "test", | |
| 658 | - replaceContent: "updated", | |
| 659 | - }, | |
| 660 | - ]); | |
| 661 | - mockIdeMessenger.ide.readFile.mockResolvedValue(originalContent); | |
| 662 | - mockFindSearchMatch.mockReturnValue({ | |
| 663 | - startIndex: 0, | |
| 664 | - endIndex: 4, | |
| 665 | - strategyName: "exactMatch", | |
| 666 | - }); | |
| 667 | - | |
| 668 | - await searchReplaceToolImpl( | |
| 669 | - { filepath: "relative/test.txt", diffs: ["mock diff content"] }, | |
| 670 | - "tool-call-id", | |
| 671 | - mockExtras, | |
| 672 | - ); | |
| 673 | - | |
| 674 | - // Verify all dependencies were called correctly | |
| 675 | - expect(mockResolveRelativePathInDir).toHaveBeenCalledWith( | |
| 676 | - "relative/test.txt", | |
| 677 | - mockIdeMessenger.ide, | |
| 678 | - ); | |
| 679 | - expect(mockParseAllSearchReplaceBlocks).toHaveBeenCalledWith( | |
| 680 | - "mock diff content", | |
| 681 | - ); | |
| 682 | - expect(mockIdeMessenger.ide.readFile).toHaveBeenCalledWith( | |
| 683 | - "/resolved/path/test.txt", | |
| 684 | - ); | |
| 685 | - expect(mockFindSearchMatch).toHaveBeenCalledWith(originalContent, "test"); | |
| 686 | - expect(mockApplyForEditTool).toHaveBeenCalledWith({ | |
| 687 | - text: "updated content", | |
| 688 | - streamId: "test-stream-id", | |
| 689 | - filepath: "/resolved/path/test.txt", | |
| 690 | - toolCallId: "tool-call-id", | |
| 691 | - isSearchAndReplace: true, | |
| 692 | - }); | |
| 693 | - }); | |
| 694 | - }); | |
| 695 | -}); |
deleted gui/src/util/clientTools/searchReplaceImpl.ts +0 −107
| @@ -1,107 +0,0 @@ | ||
| 1 | -import { findSearchMatch } from "core/edit/searchAndReplace/findSearchMatch"; | |
| 2 | -import { parseAllSearchReplaceBlocks } from "core/edit/searchAndReplace/parseSearchReplaceBlock"; | |
| 3 | -import { resolveRelativePathInDir } from "core/util/ideUtils"; | |
| 4 | -import posthog from "posthog-js"; | |
| 5 | -import { v4 as uuid } from "uuid"; | |
| 6 | -import { applyForEditTool } from "../../redux/thunks/handleApplyStateUpdate"; | |
| 7 | -import { ClientToolImpl } from "./callClientTool"; | |
| 8 | - | |
| 9 | -export const searchReplaceToolImpl: ClientToolImpl = async ( | |
| 10 | - args, | |
| 11 | - toolCallId, | |
| 12 | - extras, | |
| 13 | -) => { | |
| 14 | - const { filepath, diffs, editingFileContents } = args; | |
| 15 | - | |
| 16 | - const state = extras.getState(); | |
| 17 | - const allowAnonymousTelemetry = state.config.config.allowAnonymousTelemetry; | |
| 18 | - | |
| 19 | - const streamId = uuid(); | |
| 20 | - | |
| 21 | - // Resolve the file path | |
| 22 | - const resolvedFilepath = await resolveRelativePathInDir( | |
| 23 | - filepath, | |
| 24 | - extras.ideMessenger.ide, | |
| 25 | - ); | |
| 26 | - if (!resolvedFilepath) { | |
| 27 | - throw new Error(`File ${filepath} does not exist`); | |
| 28 | - } | |
| 29 | - | |
| 30 | - // Parse all search/replace blocks from all diff strings | |
| 31 | - const allBlocks = []; | |
| 32 | - for (let diffIndex = 0; diffIndex < diffs.length; diffIndex++) { | |
| 33 | - const blocks = parseAllSearchReplaceBlocks(diffs[diffIndex]); | |
| 34 | - if (blocks.length === 0) { | |
| 35 | - throw new Error( | |
| 36 | - `No complete search/replace blocks found in diff ${diffIndex + 1}`, | |
| 37 | - ); | |
| 38 | - } | |
| 39 | - allBlocks.push(...blocks); | |
| 40 | - } | |
| 41 | - | |
| 42 | - if (allBlocks.length === 0) { | |
| 43 | - throw new Error("No complete search/replace blocks found in any diffs"); | |
| 44 | - } | |
| 45 | - | |
| 46 | - try { | |
| 47 | - // Read the current file content | |
| 48 | - const originalContent = | |
| 49 | - editingFileContents ?? | |
| 50 | - (await extras.ideMessenger.ide.readFile(resolvedFilepath)); | |
| 51 | - let currentContent = originalContent; | |
| 52 | - | |
| 53 | - // Apply all replacements sequentially to build the final content | |
| 54 | - for (let i = 0; i < allBlocks.length; i++) { | |
| 55 | - const block = allBlocks[i]; | |
| 56 | - const { searchContent, replaceContent } = block; | |
| 57 | - | |
| 58 | - // Find the search content in the current state of the file | |
| 59 | - const match = findSearchMatch(currentContent, searchContent || ""); | |
| 60 | - | |
| 61 | - // Because we don't have access to use hooks, we check `allowAnonymousTelemetry` | |
| 62 | - // directly rather than using `CustomPostHogProvider` | |
| 63 | - if (allowAnonymousTelemetry) { | |
| 64 | - // Capture telemetry for tool calls | |
| 65 | - posthog.capture("find_replace_match_result", { | |
| 66 | - matchStrategy: match?.strategyName ?? "noMatch", | |
| 67 | - }); | |
| 68 | - } | |
| 69 | - | |
| 70 | - if (!match) { | |
| 71 | - throw new Error( | |
| 72 | - `Search content not found in block ${i + 1}:\n${searchContent}`, | |
| 73 | - ); | |
| 74 | - } | |
| 75 | - | |
| 76 | - // Apply the replacement | |
| 77 | - currentContent = | |
| 78 | - currentContent.substring(0, match.startIndex) + | |
| 79 | - (replaceContent || "") + | |
| 80 | - currentContent.substring(match.endIndex); | |
| 81 | - } | |
| 82 | - | |
| 83 | - // Single applyToFile call with all accumulated changes | |
| 84 | - // This works becaues of our logic in `applyCodeBlock` that determines | |
| 85 | - // that the full file rewrite here can be applied instantly, so the diff | |
| 86 | - // lines are generated with meyers diff and streamed instantaneously | |
| 87 | - void extras.dispatch( | |
| 88 | - applyForEditTool({ | |
| 89 | - streamId, | |
| 90 | - toolCallId, | |
| 91 | - text: currentContent, | |
| 92 | - filepath: resolvedFilepath, | |
| 93 | - isSearchAndReplace: true, | |
| 94 | - }), | |
| 95 | - ); | |
| 96 | - | |
| 97 | - // Return success - applyToFile will handle the completion state | |
| 98 | - return { | |
| 99 | - respondImmediately: false, // Let apply state handle completion | |
| 100 | - output: undefined, | |
| 101 | - }; | |
| 102 | - } catch (error) { | |
| 103 | - throw new Error( | |
| 104 | - `Failed to apply search and replace: ${error instanceof Error ? error.message : String(error)}`, | |
| 105 | - ); | |
| 106 | - } | |
| 107 | -}; |
modified gui/src/util/migrateLocalStorage.ts +0 −3
| @@ -12,9 +12,6 @@ | ||
| 12 | 12 | const toFromMap: Record<string, string[]> = { |
| 13 | 13 | [BuiltInToolNames.ReadFile]: ["builtin_read_file"], |
| 14 | 14 | [BuiltInToolNames.EditExistingFile]: ["builtin_edit_existing_file"], |
| 15 | - [BuiltInToolNames.SearchAndReplaceInFile]: [ | |
| 16 | - "builtin_search_and_replace_in_file", | |
| 17 | - ], | |
| 18 | 15 | [BuiltInToolNames.ReadCurrentlyOpenFile]: [ |
| 19 | 16 | "builtin_read_currently_open_file", |
| 20 | 17 | ], |