Skip to content

Commit bddbc18

Browse files
committed
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.
1 parent 714d551 commit bddbc18

File tree

2 files changed

+19
-3
lines changed

2 files changed

+19
-3
lines changed

lua/rest-nvim/utils.lua

Lines changed: 7 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -345,18 +345,22 @@ function utils.gq_lines(lines, filetype)
345345
logger.debug(("can't find formatexpr or formatprg for %s filetype. Formatting is canceled"):format(filetype))
346346
return lines, false
347347
end
348+
local result = true
348349
vim.api.nvim_buf_call(format_buf, function()
349350
-- HACK: dirty fix for neovim/neovim#30593
350351
local gq_ok, res = pcall(vim.api.nvim_command, "silent normal gggqG")
351-
if not gq_ok then
352-
local msg = ("formatting %s filetype failed"):format(filetype)
352+
local shell_error = vim.v.shell_error
353+
if not gq_ok or shell_error ~= 0 then
354+
local msg = ("formatting %s filetype failed (shell_error=%d)"):format(filetype, shell_error)
353355
logger.warn(msg, res)
354356
vim.notify(msg, vim.log.levels.WARN, { title = "rest.nvim" })
357+
result = false
355358
end
356359
end)
357360
local buf_lines = vim.api.nvim_buf_get_lines(format_buf, 0, -1, false)
358361
vim.api.nvim_buf_delete(format_buf, { force = true })
359-
return buf_lines, true
362+
-- Return the unmodified lines if result is failed
363+
return result and buf_lines or lines, result
360364
end
361365

362366
return utils

spec/utils_spec.lua

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -120,4 +120,16 @@ describe("gq_lines", function()
120120
local lines = { "" }
121121
assert.same({ "" }, utils.gq_lines(lines, "json"))
122122
end)
123+
it("returns original lines when json parsing fails", function()
124+
vim.api.nvim_create_autocmd("FileType", {
125+
pattern = "json",
126+
callback = function(ev)
127+
vim.bo[ev.buf].formatprg = "jq --indent 4"
128+
end,
129+
})
130+
local lines = { "this is not valid json {{{" }
131+
local result, ok = utils.gq_lines(lines, "json")
132+
assert.is_false(ok)
133+
assert.same(lines, result)
134+
end)
123135
end)

0 commit comments

Comments
 (0)