[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 == 0 then
48 u.notify("arguments not provided. usage: :GoImpl f *File io.Reader", vim.log.levels.ERROR)
49 return
50 elseif #args == 1 then -- :GoImpl io.Reader
51 local st = ts_utils.get_struct_under_cursor(bufnr)
52 iface = args[1]
53 recv = string.lower(st.name) .. " *" .. st.name
54 elseif #args == 2 then -- :GoImpl w io.Writer
55 local st = ts_utils.get_struct_under_cursor(bufnr)
56 iface = args[2]
57 recv = args[1] .. " *" .. st.name
58 elseif #args == 3 then -- :GoImpl r Struct io.Reader
59 recv = args[1] .. " *" .. args[2]
60 iface = args[3]
61 end
62
63 assert(iface ~= "", "interface not provided")
64 assert(recv ~= "", "receiver not provided")
65
66 local dir = vim.fn.fnameescape(vim.fn.expand "%:p:h")
67 local rs = r.sync { c.impl, "-dir", dir, recv, iface }
68 if rs.code ~= 0 then
69 error("failed to implement interface: " .. rs.stderr)
70 end
71
72 local pos = vim.fn.getcurpos()[2]
73 local output = u.remove_empty_lines(vim.split(rs.stdout, "\n"))
74
75 table.insert(output, 1, "")
76 vim.fn.append(pos, output)
77end
78
79return impl