[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 1. Automatically implement an interface for a struct:
7--- - Place your cursor on the struct where you want to implement the interface.
8--- - Run `:GoImpl io.Reader`
9--- - This will automatically determine the receiver and implement the `io.Reader` interface.
10---
11--- 2. Specify a custom receiver:
12--- - Place your cursor on the struct
13--- - Run `:GoImpl w io.Writer`, where:
14--- - `w` is the receiver.
15--- - `io.Writer` is the interface to implement.
16---
17--- 3. Explicitly specify the receiver, struct, and interface:
18--- - No need to place the cursor on the struct if all arguments are provided.
19--- - Run `:GoImpl r RequestReader io.Reader`, where:
20--- - `r` is the receiver.
21--- - `RequestReader` is the struct.
22--- - `io.Reader` is the interface to implement.
23---
24--- Example:
25--- >go
26--- type BytesReader struct{}
27--- // ^ put your cursor here
28--- // run `:GoImpl b io.Reader`
29---
30--- // this is what you will get
31--- func (b *BytesReader) Read(p []byte) (n int, err error) {
32--- panic("not implemented") // TODO: Implement
33--- }
34--- <
35
36local c = require("gopher.config").commands
37local r = require "gopher._utils.runner"
38local ts_utils = require "gopher._utils.ts"
39local u = require "gopher._utils"
40local impl = {}
41
42function impl.impl(...)
43 local args = { ... }
44 local iface, recv = "", ""
45 local bufnr = vim.api.nvim_get_current_buf()
46
47 if #args == 1 then -- :GoImpl io.Reader
48 local st = ts_utils.get_struct_under_cursor(bufnr)
49 iface = args[1]
50 recv = string.lower(st.name) .. " *" .. st.name
51 elseif #args == 2 then -- :GoImpl w io.Writer
52 local st = ts_utils.get_struct_under_cursor(bufnr)
53 iface = args[2]
54 recv = args[1] .. " *" .. st.name
55 elseif #args == 3 then -- :GoImpl r Struct io.Reader
56 recv = args[1] .. " *" .. args[2]
57 iface = args[3]
58 end
59
60 local rs = r.sync { c.impl, "-dir", vim.fn.fnameescape(vim.fn.expand "%:p:h"), recv, iface }
61 if rs.code ~= 0 then
62 error("failed to implement interface: " .. rs.stderr)
63 end
64
65 local pos = vim.fn.getcurpos()[2]
66 local output = u.remove_empty_lines(vim.split(rs.stdout, "\n"))
67
68 table.insert(output, 1, "")
69 vim.fn.append(pos, output)
70end
71
72return impl