fix: escaping in replace_in_file tool
This commit is contained in:
@@ -3,8 +3,11 @@ local robust_lsp = require("chatgpt_nvim.tools.lsp_robust_diagnostics")
|
|||||||
|
|
||||||
local M = {}
|
local M = {}
|
||||||
|
|
||||||
-- Enhanced search_and_replace to track if a string was found. We use Lua’s gsub return value
|
-- Function to escape all Lua pattern magic characters:
|
||||||
-- (updatedString, replacementCount) to see if any replacements occurred.
|
local function escape_lua_pattern(s)
|
||||||
|
return s:gsub("([%^%$%(%)%%%.%[%]%*%+%-%?])", "%%%1")
|
||||||
|
end
|
||||||
|
|
||||||
local function search_and_replace(original, replacements)
|
local function search_and_replace(original, replacements)
|
||||||
local updated = original
|
local updated = original
|
||||||
local info_msgs = {}
|
local info_msgs = {}
|
||||||
@@ -13,8 +16,11 @@ local function search_and_replace(original, replacements)
|
|||||||
local search_str = r.search or ""
|
local search_str = r.search or ""
|
||||||
local replace_str = r.replace or ""
|
local replace_str = r.replace or ""
|
||||||
|
|
||||||
|
-- Escape special pattern chars to ensure literal matching:
|
||||||
|
local escaped_search = escape_lua_pattern(search_str)
|
||||||
|
|
||||||
local replacement_count = 0
|
local replacement_count = 0
|
||||||
updated, replacement_count = updated:gsub(search_str, replace_str)
|
updated, replacement_count = updated:gsub(escaped_search, replace_str)
|
||||||
|
|
||||||
-- If the string was not found, append an info message
|
-- If the string was not found, append an info message
|
||||||
if replacement_count == 0 then
|
if replacement_count == 0 then
|
||||||
@@ -41,8 +47,8 @@ M.run = function(tool_call, conf, prompt_user_tool_accept, is_subpath, read_file
|
|||||||
if not path or #replacements == 0 then
|
if not path or #replacements == 0 then
|
||||||
return "[replace_in_file] Missing 'path' or 'replacements'."
|
return "[replace_in_file] Missing 'path' or 'replacements'."
|
||||||
end
|
end
|
||||||
local root = vim.fn.getcwd()
|
|
||||||
|
|
||||||
|
local root = vim.fn.getcwd()
|
||||||
if not is_subpath(root, path) then
|
if not is_subpath(root, path) then
|
||||||
return string.format("Tool [replace_in_file for '%s'] REJECTED. Path outside project root.", path)
|
return string.format("Tool [replace_in_file for '%s'] REJECTED. Path outside project root.", path)
|
||||||
end
|
end
|
||||||
|
|||||||
Reference in New Issue
Block a user