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 = {}
|
||||
|
||||
-- Enhanced search_and_replace to track if a string was found. We use Lua’s gsub return value
|
||||
-- (updatedString, replacementCount) to see if any replacements occurred.
|
||||
-- Function to escape all Lua pattern magic characters:
|
||||
local function escape_lua_pattern(s)
|
||||
return s:gsub("([%^%$%(%)%%%.%[%]%*%+%-%?])", "%%%1")
|
||||
end
|
||||
|
||||
local function search_and_replace(original, replacements)
|
||||
local updated = original
|
||||
local info_msgs = {}
|
||||
@@ -13,8 +16,11 @@ local function search_and_replace(original, replacements)
|
||||
local search_str = r.search 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
|
||||
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 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
|
||||
return "[replace_in_file] Missing 'path' or 'replacements'."
|
||||
end
|
||||
local root = vim.fn.getcwd()
|
||||
|
||||
local root = vim.fn.getcwd()
|
||||
if not is_subpath(root, path) then
|
||||
return string.format("Tool [replace_in_file for '%s'] REJECTED. Path outside project root.", path)
|
||||
end
|
||||
|
||||
Reference in New Issue
Block a user