diff --git a/vim/lua/formatter_config.lua b/vim/lua/formatter_config.lua index 9c66bf6..2a39c97 100644 --- a/vim/lua/formatter_config.lua +++ b/vim/lua/formatter_config.lua @@ -7,8 +7,17 @@ local prettier = function() end 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 { exe = "goimports", + args = args, stdin = true, } end diff --git a/vim/lua/helpers.lua b/vim/lua/helpers.lua index edf7b7d..6b049ff 100644 --- a/vim/lua/helpers.lua +++ b/vim/lua/helpers.lua @@ -10,3 +10,30 @@ function Get_project_node_modules_path() end return base_path .. "/node_modules" 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