feat(nvim): pass module path to goimports

This commit is contained in:
Rob Watson 2023-09-22 05:33:39 +02:00
parent 1893905c4f
commit f0c85a08d1
2 changed files with 36 additions and 0 deletions

View File

@ -7,8 +7,17 @@ local prettier = function()
end end
local goimports = function() local goimports = function()
local args = {}
local mod_path = Get_project_go_module_path()
if mod_path ~= "" then
table.insert(args, "-local")
table.insert(args, mod_path)
end
return { return {
exe = "goimports", exe = "goimports",
args = args,
stdin = true, stdin = true,
} }
end end

View File

@ -10,3 +10,30 @@ function Get_project_node_modules_path()
end end
return base_path .. "/node_modules" return base_path .. "/node_modules"
end end
-- Return the project's go module path from go.mod, or an empty string if the file cannot be read.
function Get_project_go_module_path()
local root_path = vim.fn.getcwd()
local mod_path = root_path .. "/go.mod"
if vim.fn.filereadable(mod_path) == 0 then
return ""
end
local file = io.open(mod_path, "r")
if file == nil then
return ""
end
io.input(file)
-- The first line of go.mod, something like:
-- module github.com/username/repo
local line = io.read()
io.close(file)
local match = string.match(line, "^module (.+)")
if match == nil then
return ""
end
return match
end