refactor(iferr): use vim.system

This commit is contained in:
Oleksandr Smirnov 2025-02-28 14:39:52 +02:00
parent f4e20f1a51
commit fd47bc3f6c
No known key found for this signature in database
2 changed files with 36 additions and 11 deletions

View file

@ -3,8 +3,9 @@ local log = require "gopher._utils.log"
local utils = {} local utils = {}
---@param msg string ---@param msg string
---@param lvl number ---@param lvl? number
function utils.deferred_notify(msg, lvl) function utils.deferred_notify(msg, lvl)
lvl = lvl or vim.log.levels.INFO
vim.defer_fn(function() vim.defer_fn(function()
vim.notify(msg, lvl, { vim.notify(msg, lvl, {
title = c.___plugin_name, title = c.___plugin_name,
@ -23,4 +24,22 @@ function utils.notify(msg, lvl)
log.debug(msg) log.debug(msg)
end end
---@param path string
---@return string
function utils.readfile_joined(path)
return table.concat(vim.fn.readfile(path), "\n")
end
---@param t string[]
---@return string[]
function utils.remove_empty_lines(t)
local res = {}
for _, line in ipairs(t) do
if line ~= "" then
table.insert(res, line)
end
end
return res
end
return utils return utils

View file

@ -4,27 +4,33 @@
---@usage Execute `:GoIfErr` near any `err` variable to insert the check ---@usage Execute `:GoIfErr` near any `err` variable to insert the check
local c = require "gopher.config" local c = require "gopher.config"
local u = require "gopher._utils"
local r = require "gopher._utils.runner"
local log = require "gopher._utils.log" local log = require "gopher._utils.log"
local iferr = {} local iferr = {}
-- That's Lua implementation: github.com/koron/iferr -- That's Lua implementation: https://github.com/koron/iferr
function iferr.iferr() function iferr.iferr()
local boff = vim.fn.wordcount().cursor_bytes local curb = vim.fn.wordcount().cursor_bytes
local pos = vim.fn.getcurpos()[2] local pos = vim.fn.getcurpos()[2]
local fpath = vim.fn.expand "%"
local data = vim.fn.systemlist((c.commands.iferr .. " -pos " .. boff), vim.fn.bufnr "%") local rs = r.sync({ c.commands.iferr, "-pos", curb }, {
if vim.v.shell_error ~= 0 then stdin = u.readfile_joined(fpath),
if string.find(data[1], "no functions at") then })
vim.print "no function found"
log.warn("iferr: no function at " .. boff) if rs.code ~= 0 then
if string.find(rs.stderr, "no functions at") then
u.notify("iferr: no function at " .. curb, vim.log.levels.ERROR)
log.warn("iferr: no function at " .. curb)
return return
end end
log.error("failed. output: " .. vim.inspect(data)) log.error("ferr: failed. output: " .. rs.stderr)
error("iferr failed: " .. vim.inspect(data)) error("iferr failed: " .. rs.stderr)
end end
vim.fn.append(pos, data) vim.fn.append(pos, u.remove_empty_lines(vim.split(rs.stdout, "\n")))
vim.cmd [[silent normal! j=2j]] vim.cmd [[silent normal! j=2j]]
vim.fn.setpos(".", pos) vim.fn.setpos(".", pos)
end end