Skip to content

Commit

Permalink
feat(nvim): simplify go mod tidy
Browse files Browse the repository at this point in the history
by **a lot**
  • Loading branch information
caarlos0 committed Apr 18, 2024
1 parent f23218e commit 58166c1
Showing 1 changed file with 8 additions and 59 deletions.
67 changes: 8 additions & 59 deletions modules/neovim/config/after/ftplugin/go.lua
Original file line number Diff line number Diff line change
@@ -1,65 +1,14 @@
vim.opt_local.formatoptions:append("jno")

local function restart(name)
local configs = require("lspconfig.configs")
local bufnr = vim.api.nvim_get_current_buf()
for _, client in
ipairs(vim.lsp.get_clients({
bufnr = bufnr,
name = name,
}))
do
vim.notify("Restarting " .. client.name .. "...")
client.stop()
vim.defer_fn(function()
configs[client.name].launch()
end, 500)
end
end
vim.opt_local.formatoptions:append("jo")

local function tidy()
vim.notify("Running `go mod tidy`...")
local uv = vim.loop
local stdout = uv.new_pipe(false)
local stderr = uv.new_pipe(false)
local function on_read(err, _)
assert(not err, err)
end

local function on_error(err, data)
assert(not err, err)
if data then
-- Just print errors, in case I notice in vim and want to debug
print(data)
end
end

local handle
handle, _ = uv.spawn(
"go",
{
args = { "mod", "tidy" },
stdio = { nil, stdout, stderr },
cwd = vim.fn.expand("%:h"),
},
vim.schedule_wrap(function()
stdout:read_stop()
stderr:read_stop()
stdout:close()
stderr:close()
if handle then
handle:close()
end
vim.schedule(function()
for _, name in ipairs({ "gopls", "golangci_lint_ls" }) do
restart(name)
end
end)
end)
)
uv.read_start(stdout, on_read)
uv.read_start(stderr, on_error)
uv.run("once")
local b = vim.api.nvim_get_current_buf()
local uri = vim.uri_from_bufnr(b)
local arguments = { { URIs = { uri } } }
vim.lsp.buf.execute_command({
command = "gopls.tidy",
arguments = arguments,
})
end

vim.api.nvim_create_user_command("GoModTidy", tidy, vim.tbl_extend("force", { desc = "go mod tidy" }, {}))
Expand Down

0 comments on commit 58166c1

Please sign in to comment.