From bddbc186bae3df575f017d83801acb4d14c95d7f Mon Sep 17 00:00:00 2001 From: Jared Beach Date: Sun, 11 Jan 2026 20:20:54 -0500 Subject: [PATCH] fix(utils): return original lines when formatting fails Adds error handling for formatting. Just shows the raw response when formatting fails. I deal with some API's that will report they're returning `application/json` and then proceed to just return plain text. --- lua/rest-nvim/utils.lua | 10 +++++++--- spec/utils_spec.lua | 12 ++++++++++++ 2 files changed, 19 insertions(+), 3 deletions(-) diff --git a/lua/rest-nvim/utils.lua b/lua/rest-nvim/utils.lua index 4f4ee933..ddd9f3ca 100644 --- a/lua/rest-nvim/utils.lua +++ b/lua/rest-nvim/utils.lua @@ -345,18 +345,22 @@ function utils.gq_lines(lines, filetype) logger.debug(("can't find formatexpr or formatprg for %s filetype. Formatting is canceled"):format(filetype)) return lines, false end + local result = true vim.api.nvim_buf_call(format_buf, function() -- HACK: dirty fix for neovim/neovim#30593 local gq_ok, res = pcall(vim.api.nvim_command, "silent normal gggqG") - if not gq_ok then - local msg = ("formatting %s filetype failed"):format(filetype) + local shell_error = vim.v.shell_error + if not gq_ok or shell_error ~= 0 then + local msg = ("formatting %s filetype failed (shell_error=%d)"):format(filetype, shell_error) logger.warn(msg, res) vim.notify(msg, vim.log.levels.WARN, { title = "rest.nvim" }) + result = false end end) local buf_lines = vim.api.nvim_buf_get_lines(format_buf, 0, -1, false) vim.api.nvim_buf_delete(format_buf, { force = true }) - return buf_lines, true + -- Return the unmodified lines if result is failed + return result and buf_lines or lines, result end return utils diff --git a/spec/utils_spec.lua b/spec/utils_spec.lua index dea27b50..473dc29a 100644 --- a/spec/utils_spec.lua +++ b/spec/utils_spec.lua @@ -120,4 +120,16 @@ describe("gq_lines", function() local lines = { "" } assert.same({ "" }, utils.gq_lines(lines, "json")) end) + it("returns original lines when json parsing fails", function() + vim.api.nvim_create_autocmd("FileType", { + pattern = "json", + callback = function(ev) + vim.bo[ev.buf].formatprg = "jq --indent 4" + end, + }) + local lines = { "this is not valid json {{{" } + local result, ok = utils.gq_lines(lines, "json") + assert.is_false(ok) + assert.same(lines, result) + end) end)