[mirror] Make your go dev experience better
github.com/olexsmir/gopher.nvim
neovim
golang
1-- Thanks https://github.com/koron/iferr for vim implementation
2
3---@toc_entry Iferr
4---@tag gopher.nvim-iferr
5---@text
6--- `iferr` provides a way to automatically insert `if err != nil` check.
7--- To configure a default `-message` option for the `iferr` tool, see |gopher.nvim-config|
8---
9---@usage
10--- 1. Insert error check:
11--- - Place your cursor near any `err` variable
12--- - Run `:GoIfErr`
13---
14--- 2. Insert error check with custom `-message`:
15--- - Place your cursor near any`err` variable
16--- - Run `:GoIfErr fmt.Errorf("failed to %w", err)`
17---
18--- Example:
19--- >go
20--- func test() error {
21--- err := doSomething()
22--- // ^ put your cursor here
23--- // run `:GoIfErr` or `:GoIfErr log.Printf("error: %v", err)`
24--- }
25---
26
27local c = require "gopher.config"
28local u = require "gopher._utils"
29local r = require "gopher._utils.runner"
30local log = require "gopher._utils.log"
31local iferr = {}
32
33---@param message? string Optional custom error message to use instead of config default
34function iferr.iferr(message)
35 local curb = vim.fn.wordcount().cursor_bytes
36 local pos = vim.fn.getcurpos()[2]
37 local fpath = vim.fn.expand "%"
38
39 local cmd = { c.commands.iferr, "-pos", curb }
40 local msg = message or c.iferr.message
41 if msg ~= nil and type(msg) == "string" then
42 table.insert(cmd, "-message")
43 table.insert(cmd, msg)
44 end
45
46 local rs = r.sync(cmd, {
47 stdin = u.readfile_joined(fpath),
48 })
49
50 if rs.code ~= 0 then
51 if string.find(rs.stderr, "no functions at") then
52 u.notify("iferr: no function at " .. curb, vim.log.levels.ERROR)
53 log.warn("iferr: no function at " .. curb)
54 return
55 end
56
57 log.error("ferr: failed. output: " .. rs.stderr)
58 error("iferr failed: " .. rs.stderr)
59 end
60
61 vim.fn.append(pos, u.remove_empty_lines(vim.split(rs.stdout, "\n")))
62 vim.cmd [[silent normal! j=2j]]
63 vim.fn.setpos(".", pos --[[@as integer[] ]])
64end
65
66return iferr