@@ -69,76 +69,6 @@ function M.delete_file(filepath)
|
||||
end
|
||||
end
|
||||
|
||||
-- Applies a unified diff to the specified file.
|
||||
-- This spawns an external 'patch' command if available.
|
||||
function M.apply_diff(filepath, diff_content)
|
||||
local conf = config.load()
|
||||
local tmp_original = vim.fn.tempname()
|
||||
local tmp_patch = vim.fn.tempname()
|
||||
|
||||
-- Read original file (or empty if it doesn't exist)
|
||||
local fd_in = uv.fs_open(filepath, "r", 438)
|
||||
local original_data = ""
|
||||
if fd_in then
|
||||
local stat = uv.fs_fstat(fd_in)
|
||||
original_data = uv.fs_read(fd_in, stat.size, 0)
|
||||
uv.fs_close(fd_in)
|
||||
end
|
||||
|
||||
-- Write original content to temp file
|
||||
local fd_orig = uv.fs_open(tmp_original, "w", 438)
|
||||
if fd_orig then
|
||||
uv.fs_write(fd_orig, original_data, -1)
|
||||
uv.fs_close(fd_orig)
|
||||
end
|
||||
|
||||
-- Write diff to temp file
|
||||
local fd_patch = uv.fs_open(tmp_patch, "w", 438)
|
||||
if fd_patch then
|
||||
uv.fs_write(fd_patch, diff_content, -1)
|
||||
uv.fs_close(fd_patch)
|
||||
else
|
||||
return false, "Could not open temporary file to write patch."
|
||||
end
|
||||
|
||||
-- Attempt to run 'patch'
|
||||
local patch_cmd = "patch -u " .. vim.fn.shellescape(tmp_original) .. " < " .. vim.fn.shellescape(tmp_patch)
|
||||
local handle = io.popen(patch_cmd)
|
||||
if not handle then
|
||||
return false, "Failed to run patch command."
|
||||
end
|
||||
local result = handle:read("*a")
|
||||
local success_close, errmsg = handle:close()
|
||||
|
||||
if conf.debug then
|
||||
vim.api.nvim_out_write("[chatgpt_nvim:handler] Patch command output:\n" .. (result or "") .. "\n")
|
||||
end
|
||||
|
||||
if not success_close then
|
||||
if conf.debug then
|
||||
vim.api.nvim_out_write("[chatgpt_nvim:handler] Patch command failed: " .. (errmsg or "unknown") .. "\n")
|
||||
end
|
||||
return false, errmsg
|
||||
end
|
||||
|
||||
-- If successful, read the patched file and write it back
|
||||
local fd_out = uv.fs_open(tmp_original, "r", 438)
|
||||
if fd_out then
|
||||
local stat_out = uv.fs_fstat(fd_out)
|
||||
local new_data = uv.fs_read(fd_out, stat_out.size, 0)
|
||||
uv.fs_close(fd_out)
|
||||
|
||||
M.write_file(filepath, new_data)
|
||||
if conf.debug then
|
||||
vim.api.nvim_out_write("[chatgpt_nvim:handler] Successfully applied patch to: " .. filepath .. "\n")
|
||||
end
|
||||
else
|
||||
return false, "Could not read patched file."
|
||||
end
|
||||
|
||||
return true
|
||||
end
|
||||
|
||||
function M.finish()
|
||||
print("Finished processing files.")
|
||||
end
|
||||
|
||||
Reference in New Issue
Block a user