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