fix: grep escaped chars and empty results (#7323)

* fix: grep search escape and better truncation warnings

* fix: grep search tweaks

* fix: grep no results

* Fix: url test
This commit is contained in:
Dallin Romney 2025-08-25 07:20:26 -07:00 • committed by GitHub
parent f5a880252d
commit 1c5df69a3f
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
13 changed files with 568 additions and 39 deletions

View file

@ -27,8 +27,8 @@ export const fetchUrlContentImpl: ToolImpl = async (args, extras) => {
// Add truncation warning if needed
if (truncatedUrls.length > 0) {
processedItems.push({
name: "URL content truncation warning",
description: "Informs that URL content was truncated",
name: "Truncation warning",
description: "",
content: `The content from ${truncatedUrls.join(", ")} was truncated because it exceeded the ${DEFAULT_FETCH_URL_CHAR_LIMIT} character limit. If you need more content, consider fetching specific sections or using a more targeted approach.`,
});
}

View file

@ -54,7 +54,7 @@ test("fetchUrlContent should truncate content exceeding character limit", async
expect(result).toHaveLength(2); // Original item + warning
expect(result[0].content.length).toBe(DEFAULT_FETCH_URL_CHAR_LIMIT);
expect(result[1].name).toBe("URL content truncation warning");
expect(result[1].name).toBe("Truncation warning");
expect(result[1].content).toContain("was truncated");
expect(result[1].content).toContain("20000 character limit");
});
@ -87,5 +87,5 @@ test("fetchUrlContent should add truncation warning with multiple truncated item
expect(result).toHaveLength(3); // Two original items + warning
expect(result[0].content.length).toBe(DEFAULT_FETCH_URL_CHAR_LIMIT);
expect(result[1].content.length).toBe(DEFAULT_FETCH_URL_CHAR_LIMIT);
expect(result[2].name).toBe("URL content truncation warning");
expect(result[2].name).toBe("Truncation warning");
});

View file

@ -10,10 +10,20 @@ export const fileGlobSearchImpl: ToolImpl = async (args, extras) => {
pattern,
MAX_AGENT_GLOB_RESULTS,
);
if (results.length === 0) {
return [
{
name: "File results",
description: "glob search",
content: "The glob search returned no results.",
},
];
}
const contextItems: ContextItem[] = [
{
name: "File results",
description: "Results from file glob search",
description: "glob search",
content: results.join("\n"),
},
];
@ -22,7 +32,7 @@ export const fileGlobSearchImpl: ToolImpl = async (args, extras) => {
if (results.length === MAX_AGENT_GLOB_RESULTS) {
contextItems.push({
name: "Truncation warning",
description: "Inform the model that results were truncated",
description: "",
content: `Warning: the results above were truncated to the first ${MAX_AGENT_GLOB_RESULTS} files. If the results are not satisfactory, refine your search pattern`,
});
}

View file

@ -1,18 +1,15 @@
import { ToolImpl } from ".";
import { ContextItem } from "../..";
import { formatGrepSearchResults } from "../../util/grepSearch";
import { prepareQueryForRipgrep } from "../../util/regexValidator";
import { getStringArg } from "../parseArgs";
const DEFAULT_GREP_SEARCH_RESULTS_LIMIT = 100;
const DEFAULT_GREP_SEARCH_CHAR_LIMIT = 5000; // ~1000 tokens, will keep truncation simply for now
const DEFAULT_GREP_SEARCH_CHAR_LIMIT = 7500; // ~1500 tokens, will keep truncation simply for now
function splitGrepResultsByFile(content: string): ContextItem[] {
const matches = [...content.matchAll(/^\.\/([^\n]+)$/gm)];
if (matches.length === 0) {
return [];
}
const contextItems: ContextItem[] = [];
for (let i = 0; i < matches.length; i++) {
@ -42,16 +39,48 @@ function splitGrepResultsByFile(content: string): ContextItem[] {
}
export const grepSearchImpl: ToolImpl = async (args, extras) => {
const query = getStringArg(args, "query");
const rawQuery = getStringArg(args, "query");
const { query, warning } = prepareQueryForRipgrep(rawQuery);
let results: string;
try {
results = await extras.ide.getSearchResults(
query,
DEFAULT_GREP_SEARCH_RESULTS_LIMIT,
);
} catch (error) {
const errorMessage = error instanceof Error ? error.message : String(error);
// Helpful error for common ripgrep exit code
if (errorMessage.includes("Process exited with code 2")) {
return [
{
name: "Search error",
description: "The search query could not be processed",
content: `The search failed due to an invalid regex pattern.\n\nOriginal query: ${rawQuery}\nProcessed query: ${query}\n\nError: ${errorMessage}\n\nTip: If you're searching for literal text with special characters, the query was automatically escaped. If you need regex patterns, ensure they use proper regex syntax.`,
},
];
}
throw error;
}
const results = await extras.ide.getSearchResults(
query,
DEFAULT_GREP_SEARCH_RESULTS_LIMIT,
);
const { formatted, numResults, truncated } = formatGrepSearchResults(
results,
DEFAULT_GREP_SEARCH_CHAR_LIMIT,
);
if (numResults === 0) {
return [
{
name: "Search results",
description: "Results from grep search",
content: "The search returned no results.",
},
];
}
const truncationReasons: string[] = [];
if (numResults === DEFAULT_GREP_SEARCH_RESULTS_LIMIT) {
truncationReasons.push(
@ -64,7 +93,7 @@ export const grepSearchImpl: ToolImpl = async (args, extras) => {
);
}
let contextItems: ContextItem[] = [];
let contextItems: ContextItem[];
const splitByFile: boolean = args?.splitByFile || false;
if (splitByFile) {
@ -79,10 +108,21 @@ export const grepSearchImpl: ToolImpl = async (args, extras) => {
];
}
// Add warnings about query modifications or truncation
const warnings: string[] = [];
if (warning) {
warnings.push(warning);
}
if (truncationReasons.length > 0) {
warnings.push(
`Results were truncated because ${truncationReasons.join(" and ")}`,
);
}
if (truncationReasons.length > 0) {
contextItems.push({
name: "Search truncation warning",
description: "Informs the model that search results were truncated",
name: "Truncation warning",
description: "",
content: `The above search results were truncated because ${truncationReasons.join(" and ")}. If the results are not satisfactory, try refining your search query.`,
});
}

View file

@ -53,8 +53,8 @@ export const lsToolImpl: ToolImpl = async (args, extras) => {
warningContent += ". Try using a non-recursive search";
}
contextItems.push({
name: "ls truncation warning",
description: "Informs the model that ls results were truncated",
name: "Truncation warning",
description: "",
content: warningContent,
});
}

View file

@ -29,8 +29,8 @@ export const searchWebImpl: ToolImpl = async (args, extras) => {
// Add truncation warning if needed
if (truncatedResults.length > 0) {
processedResults.push({
name: "Web search truncation warning",
description: "Informs that search results were truncated",
name: "Truncation warning",
description: "",
content: `The content from the following search results was truncated because it exceeded the ${DEFAULT_WEB_SEARCH_CHAR_LIMIT} character limit: ${truncatedResults.join(", ")}. For more detailed information, consider refining your search query.`,
});
}

View file

@ -62,7 +62,7 @@ test("searchWeb should truncate results exceeding character limit", async () =>
expect(result).toHaveLength(3); // Two results + warning
expect(result[0].content.length).toBe(DEFAULT_WEB_SEARCH_CHAR_LIMIT);
expect(result[1].content).toBe(shortContent);
expect(result[2].name).toBe("Web search truncation warning");
expect(result[2].name).toBe("Truncation warning");
expect(result[2].content).toContain("truncated");
expect(result[2].content).toContain("Result 1");
expect(result[2].content).not.toContain("Result 2");
@ -100,7 +100,7 @@ test("searchWeb should include all truncated results in the warning", async () =
expect(result[0].content.length).toBe(DEFAULT_WEB_SEARCH_CHAR_LIMIT);
expect(result[1].content.length).toBe(DEFAULT_WEB_SEARCH_CHAR_LIMIT);
expect(result[2].content).toBe(shortContent);
expect(result[3].name).toBe("Web search truncation warning");
expect(result[3].name).toBe("Truncation warning");
expect(result[3].content).toContain("Result 1");
expect(result[3].content).toContain("Result 2");
expect(result[3].content).not.toContain("Result 3");

View file

@ -29,8 +29,8 @@ export const viewDiffImpl: ToolImpl = async (args, extras) => {
if (truncated) {
contextItems.push({
name: "Diff truncation warning",
description: "Informs that git diff was truncated",
name: "Truncation warning",
description: "",
content: `The git diff was truncated because it exceeded ${DEFAULT_GIT_DIFF_LINE_LIMIT} lines. Consider viewing specific files or focusing on smaller changes.`,
});
}

View file

@ -58,7 +58,7 @@ test("viewDiff should truncate diffs exceeding line limit", async () => {
expect(resultLines.length).toBe(DEFAULT_GIT_DIFF_LINE_LIMIT);
// Check the warning
expect(result[1].name).toBe("Diff truncation warning");
expect(result[1].name).toBe("Truncation warning");
expect(result[1].content).toContain("truncated");
expect(result[1].content).toContain(`${DEFAULT_GIT_DIFF_LINE_LIMIT} lines`);
});
@ -83,5 +83,5 @@ test("viewDiff should handle multiple diffs correctly", async () => {
expect(resultLines.length).toBe(DEFAULT_GIT_DIFF_LINE_LIMIT);
// Check the warning
expect(result[1].name).toBe("Diff truncation warning");
expect(result[1].name).toBe("Truncation warning");
});

View file

@ -20,11 +20,11 @@ export function getStringArg(
): string {
if (!args || !(argName in args) || typeof args[argName] !== "string") {
throw new Error(
`\`${argName}\` argument is required${allowEmpty ? "" : " and must not be empty"}. (type string)`,
`\`${argName}\` argument is required${allowEmpty ? "" : " and must not be empty or whitespace-only"}. (type string)`,
);
}
if (!allowEmpty && !args[argName].trim()) {
throw new Error(`Argument ${argName} must not be empty`);
throw new Error(`Argument ${argName} must not be empty or whitespace-only`);
}
return args[argName];
}

View file

@ -102,26 +102,26 @@ describe("getStringArg", () => {
it("should throw error when argument is missing", () => {
const args = { otherArg: "test" };
expect(() => getStringArg(args, "name")).toThrowError(
"`name` argument is required and must not be empty. (type string)",
"`name` argument is required and must not be empty or whitespace-only. (type string)",
);
});
it("should throw error when argument is not a string", () => {
const args = { name: 123 };
expect(() => getStringArg(args, "name")).toThrowError(
"`name` argument is required and must not be empty. (type string)",
"`name` argument is required and must not be empty or whitespace-only. (type string)",
);
});
it("should throw error when argument is empty and empty not allowed", () => {
const args = { name: "" };
expect(() => getStringArg(args, "name")).toThrowError(
"Argument name must not be empty",
"Argument name must not be empty or whitespace-only",
);
const argsWithSpace = { name: " " };
expect(() => getStringArg(argsWithSpace, "name")).toThrowError(
"Argument name must not be empty",
"Argument name must not be empty or whitespace-only",
);
});
@ -137,10 +137,10 @@ describe("getStringArg", () => {
it("should handle null or undefined args", () => {
expect(() => getStringArg(null, "name")).toThrowError(
"`name` argument is required and must not be empty. (type string)",
"`name` argument is required and must not be empty or whitespace-only. (type string)",
);
expect(() => getStringArg(undefined, "name")).toThrowError(
"`name` argument is required and must not be empty. (type string)",
"`name` argument is required and must not be empty or whitespace-only. (type string)",
);
});
});
@ -161,14 +161,14 @@ describe("getOptionalStringArg", () => {
it("should throw error when argument is not a string", () => {
const args = { name: 123 };
expect(() => getOptionalStringArg(args, "name")).toThrowError(
"`name` argument is required and must not be empty. (type string)",
"`name` argument is required and must not be empty or whitespace-only. (type string)",
);
});
it("should throw error when argument is empty and empty not allowed", () => {
const args = { name: "" };
expect(() => getOptionalStringArg(args, "name")).toThrowError(
"Argument name must not be empty",
"Argument name must not be empty or whitespace-only",
);
});

169
core/util/regexValidator.ts Normal file
View file

@ -0,0 +1,169 @@
/**
* Validates and sanitizes regex patterns for use with ripgrep
*/
export interface RegexValidationResult {
isValid: boolean;
sanitizedQuery?: string;
error?: string;
warning?: string;
}
/**
* Validates a regex pattern and attempts to sanitize common issues
* @param query The regex pattern to validate
* @returns Validation result with sanitized query if possible
*/
export function validateAndSanitizeRegex(query: string): RegexValidationResult {
// Check for common problematic patterns that often fail with ripgrep
const problematicPatterns = [
{
// Triple-escaped quotes
pattern: /\\\\\\/g,
issue: "Triple backslash sequences may cause parsing errors",
fix: (s: string) => s.replace(/\\\\\\/g, "\\\\"),
},
{
// Unescaped brackets/parentheses that are NOT part of valid regex constructs
pattern: /(?<!\\)[\[\]()]/g, // Removed {} from here since they're valid quantifiers
issue: "Unescaped brackets or parentheses",
fix: null, // Just warn, don't auto-fix as it might be intentional
},
{
// Unescaped braces that are NOT quantifiers (quantifiers are handled separately)
pattern: /(?<!\\)\{(?![0-9,}]*\})/g,
issue: "Unescaped braces that don't appear to be quantifiers",
fix: null,
},
{
// Raw tab/newline characters (not escaped)
pattern: /[\t\n\r]/g,
issue: "Raw whitespace characters should be escaped",
fix: (s: string) =>
s.replace(/\t/g, "\\t").replace(/\n/g, "\\n").replace(/\r/g, "\\r"),
},
];
let sanitizedQuery = query;
let warnings: string[] = [];
// Apply fixes for known issues
for (const check of problematicPatterns) {
if (check.pattern.test(query)) {
if (check.fix) {
sanitizedQuery = check.fix(sanitizedQuery);
warnings.push(`Fixed: ${check.issue}`);
} else {
warnings.push(`Warning: ${check.issue}`);
}
}
}
// Try to compile as a JavaScript regex to catch basic syntax errors
try {
new RegExp(sanitizedQuery);
} catch (e) {
let errorMessage = e instanceof Error ? e.message : "Unknown error";
// If it fails as a JS regex, it might still be valid for ripgrep
// (ripgrep supports some patterns JS doesn't), but warn the user
warnings.push(`Pattern may have syntax issues: ${errorMessage}`);
}
// Check for patterns that are valid regex but might not work as expected with ripgrep
const ripgrepSpecificIssues = [
{
pattern: /\\[0-7]{3}/g,
warning: "Octal escape sequences may not work as expected in ripgrep",
},
{
pattern: /\(\?[<!=]/,
warning:
"Lookahead/lookbehind assertions require ripgrep to be compiled with PCRE2",
},
];
for (const issue of ripgrepSpecificIssues) {
if (issue.pattern.test(sanitizedQuery)) {
warnings.push(issue.warning);
}
}
return {
isValid: true,
sanitizedQuery,
warning: warnings.length > 0 ? warnings.join("; ") : undefined,
};
}
/**
* Escapes a literal string to be used as a regex pattern
* @param literal The literal string to escape
* @returns Escaped string safe for regex use
*/
export function escapeLiteralForRegex(literal: string): string {
// Escape all regex metacharacters
return literal.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
}
/**
* Detects if a query looks like it's meant to be a literal search
* rather than a regex pattern
* @param query The search query
* @returns true if it appears to be a literal search
*/
export function looksLikeLiteralSearch(query: string): boolean {
// If it contains regex metacharacters but they're not escaped,
// and it doesn't look like an intentional regex pattern
const hasUnescapedMetachars = /[.*+?^${}()|[\]]/g.test(query);
const hasEscapedMetachars = /\\[.*+?^${}()|[\]\\]/g.test(query);
// Check for regex constructs, but be more specific about what we consider regex
const hasEscapeSequences = /\\[dws]/g.test(query); // \d, \w, \s
const hasQuantifiers = /\{[0-9,]+\}/g.test(query); // {2,4}, {3}
// Check for bracket patterns and distinguish between character classes and array access
const bracketPattern = /\[[^\]]*\]/g;
const brackets = query.match(bracketPattern);
let hasCharacterClasses = false;
if (brackets) {
hasCharacterClasses = brackets.some((bracket) => {
const inside = bracket.slice(1, -1); // Remove [ ]
// Character class indicators: ranges (a-z), multiple chars, negation (^)
return /-/.test(inside) || inside.length > 1 || inside.startsWith("^");
});
}
const hasRegexConstructs =
hasEscapeSequences || hasQuantifiers || hasCharacterClasses;
// Likely a literal search if it has unescaped metachars but no regex constructs
return hasUnescapedMetachars && !hasEscapedMetachars && !hasRegexConstructs;
}
/**
* Prepares a query for ripgrep by sanitizing problematic patterns
* @param query The search query
* @returns Object with sanitized query and any warnings
*/
export function prepareQueryForRipgrep(query: string): {
query: string;
warning?: string;
} {
// Check if it looks like a literal search that should be escaped
if (looksLikeLiteralSearch(query)) {
return {
query: escapeLiteralForRegex(query),
warning:
"Query contained special regex characters and was escaped for literal text search",
};
}
// Otherwise validate and sanitize as regex
const validation = validateAndSanitizeRegex(query);
return {
query: validation.sanitizedQuery || query,
warning: validation.warning,
};
}

View file

@ -0,0 +1,310 @@
import { describe, expect, it } from "vitest";
import {
escapeLiteralForRegex,
looksLikeLiteralSearch,
prepareQueryForRipgrep,
validateAndSanitizeRegex,
} from "./regexValidator";
describe("validateAndSanitizeRegex", () => {
it("should accept valid basic regex patterns", () => {
const result = validateAndSanitizeRegex("function\\s+\\w+");
expect(result.isValid).toBe(true);
expect(result.sanitizedQuery).toBe("function\\s+\\w+");
expect(result.error).toBeUndefined();
expect(result.warning).toBeUndefined();
});
it("should fix triple-escaped sequences", () => {
const result = validateAndSanitizeRegex("\\\\\\");
expect(result.isValid).toBe(true);
expect(result.sanitizedQuery).toBe("\\\\");
expect(result.warning).toContain("Fixed: Triple backslash sequences");
});
it("should fix raw tab characters", () => {
const result = validateAndSanitizeRegex("hello\tworld");
expect(result.isValid).toBe(true);
expect(result.sanitizedQuery).toBe("hello\\tworld");
expect(result.warning).toContain("Fixed: Raw whitespace characters");
});
it("should fix raw newline characters", () => {
const result = validateAndSanitizeRegex("line1\nline2");
expect(result.isValid).toBe(true);
expect(result.sanitizedQuery).toBe("line1\\nline2");
expect(result.warning).toContain("Fixed: Raw whitespace characters");
});
it("should warn about unescaped brackets without fixing", () => {
const result = validateAndSanitizeRegex("hello[world]");
expect(result.isValid).toBe(true);
expect(result.sanitizedQuery).toBe("hello[world]");
expect(result.warning).toContain(
"Warning: Unescaped brackets or parentheses",
);
});
it("should handle multiple issues", () => {
const result = validateAndSanitizeRegex("function()\t\\\\\\");
expect(result.isValid).toBe(true);
expect(result.sanitizedQuery).toBe("function()\\t\\\\");
expect(result.warning).toContain("Fixed: Raw whitespace characters");
expect(result.warning).toContain("Fixed: Triple backslash sequences");
});
it("should warn about lookbehind assertions", () => {
const result = validateAndSanitizeRegex("(?<=foo)bar");
expect(result.isValid).toBe(true);
expect(result.warning).toContain(
"Lookahead/lookbehind assertions require ripgrep to be compiled with PCRE2",
);
});
});
describe("escapeLiteralForRegex", () => {
it("should escape basic regex metacharacters", () => {
expect(escapeLiteralForRegex("hello.world")).toBe("hello\\.world");
expect(escapeLiteralForRegex("test*")).toBe("test\\*");
expect(escapeLiteralForRegex("file+")).toBe("file\\+");
expect(escapeLiteralForRegex("query?")).toBe("query\\?");
});
it("should escape brackets and braces", () => {
expect(escapeLiteralForRegex("array[0]")).toBe("array\\[0\\]");
expect(escapeLiteralForRegex("{key}")).toBe("\\{key\\}");
expect(escapeLiteralForRegex("func()")).toBe("func\\(\\)");
});
it("should handle multiple metacharacters", () => {
expect(escapeLiteralForRegex("$regex.test(input)")).toBe(
"\\$regex\\.test\\(input\\)",
);
});
it("should not escape normal characters", () => {
expect(escapeLiteralForRegex("hello world")).toBe("hello world");
});
});
describe("looksLikeLiteralSearch", () => {
it("should identify literal searches with unescaped metacharacters", () => {
expect(looksLikeLiteralSearch("hello.world")).toBe(true);
expect(looksLikeLiteralSearch("test*")).toBe(true);
expect(looksLikeLiteralSearch("func()")).toBe(true);
expect(looksLikeLiteralSearch("array[0]")).toBe(true);
});
it("should not identify regex patterns as literal", () => {
expect(looksLikeLiteralSearch("hello\\.world")).toBe(false);
expect(looksLikeLiteralSearch("\\d+")).toBe(false);
expect(looksLikeLiteralSearch("[a-z]+")).toBe(false);
expect(looksLikeLiteralSearch("a{2,4}")).toBe(false);
});
it("should handle plain text", () => {
expect(looksLikeLiteralSearch("hello world")).toBe(false);
expect(looksLikeLiteralSearch("simple text")).toBe(false);
});
});
describe("prepareQueryForRipgrep", () => {
it("should escape literal-looking queries", () => {
const result = prepareQueryForRipgrep("hello.world");
expect(result.query).toBe("hello\\.world");
expect(result.warning).toContain("escaped for literal text search");
});
it("should sanitize regex patterns", () => {
const result = prepareQueryForRipgrep("function\t\\\\\\");
expect(result.query).toBe("function\\t\\\\");
expect(result.warning).toContain("Fixed:");
});
it("should handle plain text without changes", () => {
const result = prepareQueryForRipgrep("hello world");
expect(result.query).toBe("hello world");
expect(result.warning).toBeUndefined();
});
describe("real-world examples", () => {
it("should escape file patterns", () => {
const result = prepareQueryForRipgrep("*.js");
expect(result.query).toBe("\\*\\.js");
expect(result.warning).toContain("escaped for literal text search");
});
it("should escape function calls", () => {
const result = prepareQueryForRipgrep("console.log()");
expect(result.query).toBe("console\\.log\\(\\)");
expect(result.warning).toContain("escaped for literal text search");
});
it("should not escape proper regex patterns", () => {
const result = prepareQueryForRipgrep("function\\s+\\w+");
expect(result.query).toBe("function\\s+\\w+");
expect(result.warning).toBeUndefined();
});
});
});
describe("problematic patterns that originally failed", () => {
it("should handle triple-escaped quotes", () => {
const result = prepareQueryForRipgrep('\\\\\\"');
expect(result.query).toBe('\\\\"'); // Triple backslash -> double backslash, quote stays
expect(result.warning).toContain("Fixed:");
});
it("should handle newline-tab sequences", () => {
const result = prepareQueryForRipgrep("\n\t");
expect(result.query).toBe("\\n\\t");
expect(result.warning).toContain("Fixed:");
});
it("should handle dollar signs in shell patterns", () => {
const result = prepareQueryForRipgrep("$(command)");
expect(result.query).toBe("\\$\\(command\\)");
expect(result.warning).toContain("escaped for literal text search");
});
it("should handle escaped dollar signs", () => {
const result = prepareQueryForRipgrep("\\$\\(");
expect(result.query).toBe("\\$\\(");
expect(result.warning).toBeUndefined();
});
});
describe("patterns that should NOT be over-sanitized", () => {
describe("valid regex patterns that contain suspicious sequences", () => {
it("should not escape properly formed character classes", () => {
const result = prepareQueryForRipgrep("[a-zA-Z0-9_-]+");
expect(result.query).toBe("[a-zA-Z0-9_-]+");
expect(result.warning).toContain("Warning: Unescaped brackets"); // Warn but don't break
});
it("should not escape quantifiers in regex patterns", () => {
const result = prepareQueryForRipgrep("\\w{2,5}");
expect(result.query).toBe("\\w{2,5}");
expect(result.warning).toBeUndefined();
});
it("should not escape properly formed lookarounds", () => {
const result = prepareQueryForRipgrep("(?<!\\w)test(?!\\w)");
expect(result.query).toBe("(?<!\\w)test(?!\\w)");
expect(result.warning).toContain("Lookahead/lookbehind assertions"); // Warn about compatibility
});
it("should not break escaped metacharacters in regex", () => {
const result = prepareQueryForRipgrep("console\\.log\\(\\)");
expect(result.query).toBe("console\\.log\\(\\)");
expect(result.warning).toBeUndefined();
});
});
describe("patterns that look problematic but are intentional", () => {
it("should not over-escape already escaped sequences", () => {
const result = prepareQueryForRipgrep("\\\\t"); // Already escaped tab
expect(result.query).toBe("\\\\t");
expect(result.warning).toBeUndefined();
});
it("should not double-escape backslashes in Windows paths", () => {
const result = prepareQueryForRipgrep("C:\\\\Users\\\\file");
expect(result.query).toBe("C:\\\\Users\\\\file");
expect(result.warning).toBeUndefined();
});
it("should not break raw strings that contain regex-like patterns", () => {
const result = prepareQueryForRipgrep('"\\d+\\s+\\w+"');
expect(result.query).toBe('"\\d+\\s+\\w+"'); // Escaped sequences in quotes should stay
expect(result.warning).toBeUndefined();
});
it("should not break JSON with escaped quotes", () => {
const result = prepareQueryForRipgrep('"key": "value"');
expect(result.query).toBe('"key": "value"');
expect(result.warning).toBeUndefined();
});
});
describe("complex patterns that mix literal and regex", () => {
it("should not break URLs with query parameters", () => {
const result = prepareQueryForRipgrep(
"https://api\\.example\\.com\\?param=\\w+",
);
expect(result.query).toBe("https://api\\.example\\.com\\?param=\\w+");
expect(result.warning).toBeUndefined();
});
it("should not break file paths with regex metacharacters", () => {
const result = prepareQueryForRipgrep("/path/to/file\\.[jt]sx?");
expect(result.query).toBe("/path/to/file\\.[jt]sx?");
expect(result.warning).toContain("Warning: Unescaped brackets"); // Warn but preserve
});
it("should handle mixed escaped and unescaped patterns correctly", () => {
// This is a regex that matches function calls with optional whitespace
const result = prepareQueryForRipgrep("\\w+\\s*\\(");
expect(result.query).toBe("\\w+\\s*\\(");
expect(result.warning).toBeUndefined();
});
});
describe("edge cases that could trigger false positives", () => {
it("should not treat mathematical expressions as problematic", () => {
const result = prepareQueryForRipgrep("a + b * c");
expect(result.query).toBe("a \\+ b \\* c"); // Should be escaped as literal
expect(result.warning).toContain("escaped for literal text search");
});
it("should not break regex that uses word boundaries", () => {
const result = prepareQueryForRipgrep("\\bclass\\b");
expect(result.query).toBe("\\bclass\\b");
expect(result.warning).toBeUndefined();
});
it("should not break negated character classes", () => {
const result = prepareQueryForRipgrep("[^a-z]+");
expect(result.query).toBe("[^a-z]+");
expect(result.warning).toContain("Warning: Unescaped brackets"); // Warn but preserve
});
it("should not treat IPv4 addresses as problematic regex", () => {
const result = prepareQueryForRipgrep("192.168.1.1");
expect(result.query).toBe("192\\.168\\.1\\.1"); // Should be escaped as literal
expect(result.warning).toContain("escaped for literal text search");
});
it("should not break hex color codes", () => {
const result = prepareQueryForRipgrep("#[0-9a-fA-F]{6}");
expect(result.query).toBe("#[0-9a-fA-F]{6}");
expect(result.warning).toContain("Warning: Unescaped brackets"); // Warn but preserve regex
});
});
describe("patterns that should preserve user intent", () => {
it("should not sanitize intentional regex alternation", () => {
const result = prepareQueryForRipgrep("(foo|bar)");
expect(result.query).toBe("\\(foo\\|bar\\)"); // Should be escaped as literal since unescaped
expect(result.warning).toContain("escaped for literal text search");
});
it("should preserve escaped alternation in regex", () => {
const result = prepareQueryForRipgrep("\\(foo\\|bar\\)");
expect(result.query).toBe("\\(foo\\|bar\\)");
expect(result.warning).toBeUndefined();
});
it("should not break SQL LIKE patterns when used as literal search", () => {
const result = prepareQueryForRipgrep("name LIKE '%john%'");
expect(result.query).toBe("name LIKE '%john%'"); // No regex metacharacters here
expect(result.warning).toBeUndefined();
});
it("should not break CSS selectors when used as literal search", () => {
const result = prepareQueryForRipgrep(".class-name > div:nth-child(2)");
expect(result.query).toBe("\\.class-name > div:nth-child\\(2\\)");
expect(result.warning).toContain("escaped for literal text search");
});
});
});