[mirror] Make your go dev experience better
github.com/olexsmir/gopher.nvim
neovim
golang
1---@toc_entry Auto implementation of interface methods
2---@tag gopher.nvim-impl
3---@text
4--- Integration of `impl` tool to generate method stubs for interfaces.
5---
6---@usage
7--- 1. Automatically implement an interface for a struct:
8--- - Place your cursor on the struct where you want to implement the interface.
9--- - Run `:GoImpl io.Reader`
10--- - This will automatically determine the receiver and implement the `io.Reader` interface.
11---
12--- 2. Specify a custom receiver:
13--- - Place your cursor on the struct
14--- - Run `:GoImpl w io.Writer`, where:
15--- - `w` is the receiver.
16--- - `io.Writer` is the interface to implement.
17---
18--- 3. Explicitly specify the receiver, struct, and interface:
19--- - No need to place the cursor on the struct if all arguments are provided.
20--- - Run `:GoImpl r RequestReader io.Reader`, where:
21--- - `r` is the receiver.
22--- - `RequestReader` is the struct.
23--- - `io.Reader` is the interface to implement.
24---
25--- Example:
26--- >go
27--- type BytesReader struct{}
28--- // ^ put your cursor here
29--- // run `:GoImpl b io.Reader`
30---
31--- // this is what you will get
32--- func (b *BytesReader) Read(p []byte) (n int, err error) {
33--- panic("not implemented") // TODO: Implement
34--- }
35--- <
36
37local c = require "gopher.config"
38local r = require "gopher._utils.runner"
39local ts_utils = require "gopher._utils.ts"
40local u = require "gopher._utils"
41local impl = {}
42
43function impl.impl(...)
44 local args = { ... }
45 local iface, recv = "", ""
46 local bufnr = vim.api.nvim_get_current_buf()
47
48 local append_after = nil
49 if #args == 0 then
50 u.notify("arguments not provided. usage: :GoImpl f *File io.Reader", vim.log.levels.ERROR)
51 return
52 elseif #args == 1 then -- :GoImpl io.Reader
53 local st = ts_utils.get_struct_under_cursor(bufnr)
54 iface = args[1]
55 recv = string.lower(st.name) .. " *" .. st.name
56 append_after = st.end_
57 elseif #args == 2 then -- :GoImpl w io.Writer
58 local st = ts_utils.get_struct_under_cursor(bufnr)
59 iface = args[2]
60 recv = args[1] .. " *" .. st.name
61 append_after = st.end_
62 elseif #args == 3 then -- :GoImpl r Struct io.Reader
63 recv = args[1] .. " *" .. args[2]
64 iface = args[3]
65 end
66
67 assert(iface ~= "", "interface not provided")
68 assert(recv ~= "", "receiver not provided")
69
70 local dir = vim.fn.fnameescape(vim.fn.expand "%:p:h")
71 local rs = r.sync { c.commands.impl, "-dir", dir, recv, iface }
72 if rs.code ~= 0 then
73 error("failed to implement interface: " .. rs.stderr)
74 end
75
76 local pos = append_after or vim.fn.getcurpos()[2]
77 local output = u.remove_empty_lines(vim.split(rs.stdout, "\n"))
78
79 table.insert(output, 1, "")
80 vim.fn.append(pos, output)
81end
82
83return impl