WIP: perform search and replace with fallbacks

This commit is contained in:
Dallin Romney 2025-09-19 17:35:21 -07:00
parent 5b5532f7e7
commit 604ec09ef1
9 changed files with 140 additions and 20 deletions

View file

@ -1,5 +1,5 @@
import { EditOperation } from "core/tools/definitions/multiEdit";
import { describe, expect, it } from "vitest";
import { EditOperation } from "../../tools/definitions/multiEdit";
import {
EMPTY_NON_FIRST_EDIT_MESSAGE,
FOUND_MULTIPLE_FIND_STRINGS_ERROR,

View file

@ -1,5 +1,5 @@
import { EditOperation } from "core/tools/definitions/multiEdit";
import { ContinueError, ContinueErrorReason } from "core/util/errors";
import { EditOperation } from "../../tools/definitions/multiEdit";
import { ContinueError, ContinueErrorReason } from "../../util/errors";
export const FOUND_MULTIPLE_FIND_STRINGS_ERROR =
"Either provide a more specific string with surrounding context to make it unique, or use replace_all=true to replace all occurrences.";
@ -89,6 +89,7 @@ export function validateSingleEdit(
export const EMPTY_NON_FIRST_EDIT_MESSAGE =
"contains empty old_string. Only the first edit can contain an empty old_string, which is only used for file creation.";
export function validateCreatingForMultiEdit(edits: EditOperation[]) {
const isCreating = edits[0].old_string === "";
if (edits.length > 1) {

View file

@ -4,7 +4,7 @@
interface BasicMatchResult {
/** The starting character index of the match in the file content */
startIndex: number;
/** The ending character index of the match in the file content */
/** The ending character index of the match in the file content (NOT inclusive - e.g. like slice)*/
endIndex: number;
}
@ -124,7 +124,7 @@ function whitespaceIgnoredMatch(
/**
* Calculate the Jaro similarity between two strings
* TODO Re
* TODO Restore this functionality - current implementation has some kind of bug where it only returns one line for the match
*/
function jaroSimilarity(s1: string, s2: string): number {
if (s1 === s2) return 1.0;
@ -322,3 +322,52 @@ export function findSearchMatch(
return null;
}
/**
* Find all matches for search content in file content.
* Uses the same matching strategies as findSearchMatch, applied iteratively.
*
* @param fileContent - The complete content of the file to search in
* @param searchContent - The content to search for
* @returns Array of match results with character positions, empty array if no matches found
*/
export function findSearchMatches(
fileContent: string,
searchContent: string,
): SearchMatchResult[] {
const matches: SearchMatchResult[] = [];
let remainingContent = fileContent;
let currentOffset = 0;
while (remainingContent.length > 0) {
const match = findSearchMatch(remainingContent, searchContent);
if (match === null) {
break;
}
// Adjust match positions to account for the current offset
const adjustedMatch: SearchMatchResult = {
startIndex: match.startIndex + currentOffset,
endIndex: match.endIndex + currentOffset,
strategyName: match.strategyName,
};
// Prevent infinite loops by ensuring we're making progress
// If the new match starts at or before the last match's start position, break
if (
matches.length > 0 &&
adjustedMatch.startIndex <= matches[matches.length - 1].startIndex
) {
break;
}
matches.push(adjustedMatch);
// Update offset and truncate content after the current match
currentOffset = adjustedMatch.endIndex;
remainingContent = fileContent.slice(currentOffset);
}
return matches;
}

View file

@ -0,0 +1,70 @@
import { EditOperation } from "../../tools/definitions/multiEdit";
import { ContinueError, ContinueErrorReason } from "../../util/errors";
import { findSearchMatch, findSearchMatches } from "./findSearchMatch";
export function executeFindAndReplace(
fileContent: string,
oldString: string,
newString: string,
editIndex = 0,
): string {
const match = findSearchMatch(fileContent, oldString);
if (!match) {
throw new ContinueError(
ContinueErrorReason.FindAndReplaceOldStringNotFound,
`Edit at index ${editIndex}: string not found in file: "${oldString}"`,
);
}
return (
fileContent.substring(0, match.startIndex) +
newString +
fileContent.substring(match.endIndex)
);
}
export function executeMultiFindAndReplace(
fileContent: string,
edits: EditOperation[],
): string {
let result = fileContent;
// Apply edits in reverse order by startIndex to avoid position shifts
// affecting subsequent edits
for (let editIndex = 0; editIndex < edits.length; editIndex++) {
const edit = edits[editIndex];
const matches = findSearchMatches(result, edit.old_string);
if (matches.length === 0) {
throw new ContinueError(
ContinueErrorReason.FindAndReplaceOldStringNotFound,
`Edit at index ${editIndex}: string not found in file: "${edit.old_string}"`,
);
}
if (edit.replace_all) {
// Apply replacements in reverse order to maintain correct positions
for (let i = matches.length - 1; i >= 0; i--) {
const match = matches[i];
result =
result.substring(0, match.startIndex) +
edit.new_string +
result.substring(match.endIndex);
}
} else {
// For single replacement, check for multiple matches first
if (matches.length > 1) {
throw new ContinueError(
ContinueErrorReason.FindAndReplaceMultipleOccurrences,
`Edit at index ${editIndex}: String "${edit.old_string}" appears ${matches.length} times in the file. Either provide a more specific string with surrounding context to make it unique, or use replace_all=true to replace all occurrences.`,
);
}
// Apply single replacement
const match = matches[0];
result =
result.substring(0, match.startIndex) +
edit.new_string +
result.substring(match.endIndex);
}
}
return result;
}

View file

@ -43,8 +43,8 @@ vi.mock("react", async () => {
});
// Import mocked modules
import { performFindAndReplace } from "core/edit/searchAndReplace/findAndReplaceUtils";
import { useAppSelector } from "../../../redux/hooks";
import { performFindAndReplace } from "../../../util/clientTools/findAndReplaceUtils";
const mockPost = vi.fn();
const mockUseAppSelector = useAppSelector as any;

View file

@ -1,5 +1,9 @@
import { ChevronDownIcon } from "@heroicons/react/24/outline";
import { ApplyState } from "core";
import {
performFindAndReplace,
trimEmptyLines,
} from "core/edit/searchAndReplace/findAndReplaceUtils";
import { EditOperation } from "core/tools/definitions/multiEdit";
import { renderContextItems } from "core/util/messageContent";
import { getLastNPathParts, getUriPathBasename } from "core/util/uri";
@ -13,10 +17,6 @@ import {
selectApplyStateByToolCallId,
selectToolCallById,
} from "../../../redux/selectors/selectToolCalls";
import {
performFindAndReplace,
trimEmptyLines,
} from "../../../util/clientTools/findAndReplaceUtils";
import { cn } from "../../../util/cn";
import { getStatusIcon } from "./utils";

View file

@ -1,8 +1,8 @@
import { FOUND_MULTIPLE_FIND_STRINGS_ERROR } from "core/edit/searchAndReplace/findAndReplaceUtils";
import * as ideUtils from "core/util/ideUtils";
import { beforeEach, describe, expect, it, Mock, vi } from "vitest";
import { applyForEditTool } from "../../redux/thunks/handleApplyStateUpdate";
import { ClientToolExtras } from "./callClientTool";
import { FOUND_MULTIPLE_FIND_STRINGS_ERROR } from "./findAndReplaceUtils";
import { multiEditImpl } from "./multiEditImpl";
vi.mock("uuid", () => ({

View file

@ -1,3 +1,8 @@
import {
performFindAndReplace,
validateCreatingForMultiEdit,
validateSingleEdit,
} from "core/edit/searchAndReplace/findAndReplaceUtils";
import { ContinueError, ContinueErrorReason } from "core/util/errors";
import {
inferResolvedUriFromRelativePath,
@ -6,11 +11,6 @@ import {
import { v4 as uuid } from "uuid";
import { applyForEditTool } from "../../redux/thunks/handleApplyStateUpdate";
import { ClientToolImpl } from "./callClientTool";
import {
performFindAndReplace,
validateCreatingForMultiEdit,
validateSingleEdit,
} from "./findAndReplaceUtils";
export const multiEditImpl: ClientToolImpl = async (
args,

View file

@ -1,12 +1,12 @@
import {
performFindAndReplace,
validateSingleEdit,
} from "core/edit/searchAndReplace/findAndReplaceUtils";
import { ContinueError, ContinueErrorReason } from "core/util/errors";
import { resolveRelativePathInDir } from "core/util/ideUtils";
import { v4 as uuid } from "uuid";
import { applyForEditTool } from "../../redux/thunks/handleApplyStateUpdate";
import { ClientToolImpl } from "./callClientTool";
import {
performFindAndReplace,
validateSingleEdit,
} from "./findAndReplaceUtils";
export const singleFindAndReplaceImpl: ClientToolImpl = async (
args,