From 41f619389ea6b74f629a680168e9263044613b9e Mon Sep 17 00:00:00 2001 From: Aleksei Malykh <49870662+ysomad@users.noreply.github.com> Date: Mon, 14 Jul 2025 16:22:34 +0700 Subject: [PATCH] feat: alternate between go and test files --- lua/gopher/alternate.lua | 44 ++++++++++++++++++++++++++++++++++++++++ plugin/gopher.lua | 13 ++++++++++++ 2 files changed, 57 insertions(+) create mode 100644 lua/gopher/alternate.lua diff --git a/lua/gopher/alternate.lua b/lua/gopher/alternate.lua new file mode 100644 index 0000000..f283c37 --- /dev/null +++ b/lua/gopher/alternate.lua @@ -0,0 +1,44 @@ +local M = {} + +function M.is_test_file() + local file = vim.fn.expand "%" + if #file <= 1 then + vim.notify("no buffer name", vim.log.levels.ERROR) + return nil, false, false + end + local is_test = string.find(file, "_test%.go$") + local is_source = string.find(file, "%.go$") + return file, (not is_test and is_source), is_test +end + +function M.alternate() + local file, is_source, is_test = M.is_test_file() + if not file then + return nil + end + local alt_file = file + if is_test then + alt_file = string.gsub(file, "_test.go", ".go") + elseif is_source then + alt_file = vim.fn.expand "%:r" .. "_test.go" + else + vim.notify("not a go file", vim.log.levels.ERROR) + end + return alt_file +end + +function M.switch(bang, cmd) + local alt_file = M.alternate() + if not vim.fn.filereadable(alt_file) and not vim.fn.bufexists(alt_file) and not bang then + vim.notify("couldn't find " .. alt_file, vim.log.levels.ERROR) + return + elseif #cmd <= 1 then + local ocmd = "e " .. alt_file + vim.cmd(ocmd) + else + local ocmd = cmd .. " " .. alt_file + vim.cmd(ocmd) + end +end + +return M diff --git a/plugin/gopher.lua b/plugin/gopher.lua index 1ccc74e..d4bb682 100644 --- a/plugin/gopher.lua +++ b/plugin/gopher.lua @@ -85,3 +85,16 @@ end, "*") cmd("GoGenerate", function(opts) require("gopher").generate(opts.fargs or "") end, "?") + +-- :GoAlt +cmd("GoAlt", function() + require("gopher.alternate").switch(true, "") +end) + +cmd("GoAltV", function() + require("gopher.alternate").switch(true, "vsplit") +end) + +cmd("GoAltS", function() + require("gopher.alternate").switch(true, "split") +end)