all repos

gopher.nvim @ 7ebe190c962f16681f82d9a394b3256833b7616e

Minimalistic plugin for Go development

gopher.nvim/lua/gopher/iferr.lua(view raw)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
---@toc_entry Iferr
---@tag gopher.nvim-iferr
---@text If you're using `iferr` tool, this module provides a way to automatically insert `if err != nil` check.
---@usage Execute `:GoIfErr` near any `err` variable to insert the check

local c = require "gopher.config"
local u = require "gopher._utils"
local r = require "gopher._utils.runner"
local log = require "gopher._utils.log"
local iferr = {}

-- That's Lua implementation: https://github.com/koron/iferr
function iferr.iferr()
  local curb = vim.fn.wordcount().cursor_bytes
  local pos = vim.fn.getcurpos()[2]
  local fpath = vim.fn.expand "%"

  local cmd = { c.commands.iferr, "-pos", curb }
  if c.iferr.message ~= nil and type(c.iferr.message) == "string" then
    table.insert(cmd, "-message")
    table.insert(cmd, c.iferr.message)
  end

  local rs = r.sync(cmd, {
    stdin = u.readfile_joined(fpath),
  })

  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
    end

    log.error("ferr: failed. output: " .. rs.stderr)
    error("iferr failed: " .. rs.stderr)
  end

  vim.fn.append(pos, u.remove_empty_lines(vim.split(rs.stdout, "\n")))
  vim.cmd [[silent normal! j=2j]]
  vim.fn.setpos(".", pos)
end

return iferr