issue #184 trouble

pull/186/head
ray-x 2 years ago
parent 7aed764507
commit 93c724d6b0

@ -649,6 +649,7 @@ require('go').setup({
run_in_floaterm = false, -- set to true to run in float window. :GoTermClose closes the floatterm
-- float term recommand if you use richgo/ginkgo with terminal color
trouble = false, -- true: use trouble to open quickfix
test_efm = false, -- errorfomat for quickfix, default mix mode, set to true will be efm only
luasnip = false, -- enable included luasnip snippets. you can also disable while add lua/snips folder to luasnip load
-- Do not enable this if you already added the path, that will duplicate the entries

@ -104,6 +104,7 @@ _GO_NVIM_CFG = {
test_runner = "go", -- one of {`go`, `richgo`, `dlv`, `ginkgo`}
verbose_tests = true, -- set to add verbose flag to tests
run_in_floaterm = false, -- set to true to run in float window.
trouble = false, -- true: use trouble to open quickfix
test_efm = false, -- errorfomat for quickfix, default mix mode, set to true will be efm only
luasnip = false, -- enable included luasnip

@ -305,7 +305,7 @@ function M.make(...)
if failed then
cmd = cmd .. " go test failed"
level = vim.lsp.log_levels.WARN
vim.cmd("botright copen")
util.quickfix('botright copen')
end
itemn = 1

@ -1,4 +1,4 @@
local utils = require("go.utils")
local utils = require('go.utils')
local log = utils.log
local coverage = {}
local api = vim.api
@ -9,9 +9,9 @@ local visable = false
-- _GO_NVIM_CFG = _GO_NVIM_CFG or {}
local sign_define_cache = {}
M.sign_map = { covered = "goCoverageCovered", uncover = "goCoverageUncover" }
M.sign_map = { covered = 'goCoverageCovered', uncover = 'goCoverageUncover' }
local ns = "gocoverage_ns"
local ns = 'gocoverage_ns'
local sign_covered = M.sign_map.covered
local sign_uncover = M.sign_map.uncover
@ -39,7 +39,7 @@ local function all_bufnr()
local name = b.name
local ext = string.sub(name, #name - 2)
if ext == ".go" then
if ext == '.go' then
table.insert(bufnrl, b.bufnr)
end
end
@ -65,7 +65,7 @@ end
function M.remove(bufnr, lnum)
if bufnr == nil then
bufnr = vfn.bufnr("$")
bufnr = vfn.bufnr('$')
end
vfn.sign_unplace(ns, { buffer = bufnr, id = lnum })
end
@ -81,13 +81,13 @@ function M.add(bufnr, signs)
local to_place = {}
for _, s in ipairs(signs or {}) do
local count = s.cnt
local stype = "goCoverageCovered"
local stype = 'goCoverageCovered'
if count == 0 then
stype = "goCoverageUncover"
stype = 'goCoverageUncover'
end
M.define(bufnr, stype, { text = _GO_NVIM_CFG.gocoverage_sign, texthl = stype })
for lnum = s.range.start.line, s.range["end"].line + 1 do
for lnum = s.range.start.line, s.range['end'].line + 1 do
log(lnum, bufnr)
to_place[#to_place + 1] = {
id = lnum,
@ -106,7 +106,7 @@ function M.add(bufnr, signs)
end
M.highlight = function()
if vim.o.background == "dark" then
if vim.o.background == 'dark' then
vim.cmd([[hi! goCoverageCovered guifg=#107040 ctermbg=28]])
vim.cmd([[hi! goCoverageUncover guifg=#A03040 ctermbg=52]])
else
@ -154,13 +154,13 @@ local function parse_line(line)
return {}
end
local path = m[2]
local filename = vfn.fnamemodify(m[2], ":t")
local filename = vfn.fnamemodify(m[2], ':t')
return {
file = path,
filename = filename,
range = {
start = { line = tonumber(m[3]), character = tonumber(m[4]) },
["end"] = { line = tonumber(m[5]), character = tonumber(m[6]) },
['end'] = { line = tonumber(m[5]), character = tonumber(m[6]) },
},
num = tonumber(m[7]),
cnt = tonumber(m[8]),
@ -170,14 +170,14 @@ end
if vim.tbl_isempty(vfn.sign_getdefined(sign_covered)) then
vfn.sign_define(sign_covered, {
text = _GO_NVIM_CFG.gocoverage_sign,
texthl = "goCoverageCovered",
texthl = 'goCoverageCovered',
})
end
if vim.tbl_isempty(vfn.sign_getdefined(sign_uncover)) then
vfn.sign_define(sign_uncover, {
text = _GO_NVIM_CFG.gocoverage_sign,
texthl = "goCoverageUncover",
texthl = 'goCoverageUncover',
})
end
@ -186,7 +186,7 @@ M.read_cov = function(covfn)
local total_covered = 0
if vfn.filereadable(covfn) == 0 then
vim.notify(string.format("cov file not exist: %s please run cover test first", covfn), vim.lsp.log_levels.WARN)
vim.notify(string.format('cov file not exist: %s please run cover test first', covfn), vim.lsp.log_levels.WARN)
return
end
local cov = vfn.readfile(covfn)
@ -213,12 +213,12 @@ M.read_cov = function(covfn)
coverage.total_lines = total_lines
coverage.total_covered = total_covered
local bufnrs = all_bufnr()
log("buffers", bufnrs)
log('buffers', bufnrs)
local added = {}
for _, bid in pairs(bufnrs) do
-- if added[bid] == nil then
local fn = vfn.bufname(bid)
fn = vfn.fnamemodify(fn, ":t")
fn = vfn.fnamemodify(fn, ':t')
log(bid, fn)
M.add(bid, coverage[fn])
visable = true
@ -229,7 +229,7 @@ M.read_cov = function(covfn)
end
M.show_func = function()
local setup = { "go", "tool", "cover", "-func=cover.cov" }
local setup = { 'go', 'tool', 'cover', '-func=cover.cov' }
local result = {}
vfn.jobstart(setup, {
on_stdout = function(_, data, _)
@ -239,18 +239,18 @@ M.show_func = function()
end
for _, val in ipairs(data) do
-- first strip the filename
local l = vim.fn.split(val, ":")
local l = vim.fn.split(val, ':')
local fname = l[1]
if vim.fn.filereadable(fname) == 0 then
local parts = vim.fn.split(fname, utils.sep())
for _ = 1, #parts do
table.remove(parts, 1)
fname = vim.fn.join(parts, utils.sep())
log("fname", fname)
log('fname', fname)
if vim.fn.filereadable(fname) == 1 then
l[1] = fname
local d = vim.fn.join(l, ":")
log("putback ", d)
local d = vim.fn.join(l, ':')
log('putback ', d)
val = d
end
end
@ -260,63 +260,64 @@ M.show_func = function()
end,
on_exit = function(_, data, _)
if data ~= 0 then
vim.notify("no coverage data", vim.lsp.log_levels.WARN)
vim.notify('no coverage data', vim.lsp.log_levels.WARN)
return
end
vim.fn.setqflist({}, " ", {
title = "go coverage",
vim.fn.setqflist({}, ' ', {
title = 'go coverage',
lines = result,
})
vim.cmd("copen")
utils.quickfix('copen')
end,
})
end
M.run = function(...)
local get_build_tags = require("go.gotest").get_build_tags
local get_build_tags = require('go.gotest').get_build_tags
-- local cov = vfn.tempname()
local pwd = vfn.getcwd()
local cov = pwd .. utils.sep() .. "cover.cov"
local cov = pwd .. utils.sep() .. 'cover.cov'
local args = { ... }
log(args)
if load == "-m" then
if load == '-m' then
-- show the func metric
if vim.fn.filereadable(cov) == 1 then
return M.show_func()
end
end
local load = select(1, ...)
if load == "-f" then
if load == '-f' then
local covfn = select(2, ...) or cov
if vim.fn.filereadable(covfn) == 0 then
vim.notify("no cov file specified or existed, will rerun coverage test", vim.lsp.log_levels.INFO)
vim.notify('no cov file specified or existed, will rerun coverage test', vim.lsp.log_levels.INFO)
else
local test_coverage = M.read_cov(covfn)
vim.notify(string.format("total coverage: %d%%", test_coverage.total_covered / test_coverage.total_lines * 100))
vim.notify(string.format('total coverage: %d%%', test_coverage.total_covered / test_coverage.total_lines * 100))
return test_coverage
end
end
if load == "-t" then
if load == '-t' then
return M.toggle()
end
if load == "-r" then
if load == '-r' then
return M.remove()
end
if load == "-R" then
if load == '-R' then
return M.remove_all()
end
local test_runner = "go"
if _GO_NVIM_CFG.test_runner ~= "go" then
local test_runner = 'go'
if _GO_NVIM_CFG.test_runner ~= 'go' then
test_runner = _GO_NVIM_CFG.test_runner
require("go.install").install(test_runner)
require('go.install').install(test_runner)
end
local cmd = { test_runner, "test", "-coverprofile", cov }
local tags = ""
local cmd = { test_runner, 'test', '-coverprofile', cov }
local tags = ''
local args2 = {}
if not empty(args) then
tags, args2 = get_build_tags(args)
@ -329,29 +330,29 @@ M.run = function(...)
log(args2)
cmd = vim.list_extend(cmd, args2)
else
local argsstr = "." .. utils.sep() .. "..."
local argsstr = '.' .. utils.sep() .. '...'
table.insert(cmd, argsstr)
end
local lines = { "" }
local lines = { '' }
coverage = {}
log("run coverage", cmd)
log('run coverage', cmd)
if _GO_NVIM_CFG.run_in_floaterm then
cmd = table.concat(cmd, " ")
cmd = table.concat(cmd, ' ')
if empty(args2) then
cmd = cmd .. "." .. utils.sep() .. "..."
cmd = cmd .. '.' .. utils.sep() .. '...'
end
utils.log(cmd)
local term = require("go.term").run
local term = require('go.term').run
term({ cmd = cmd, autoclose = false })
return
end
vfn.jobstart(cmd, {
on_stdout = function(jobid, data, event)
log("go coverage " .. vim.inspect(data), jobid, event)
log('go coverage ' .. vim.inspect(data), jobid, event)
vim.list_extend(lines, data)
end,
on_stderr = function(job_id, data, event)
@ -360,35 +361,35 @@ M.run = function(...)
return
end
vim.notify(
"go coverage finished with message: "
'go coverage finished with message: '
.. vim.inspect(cmd)
.. "error: "
.. 'error: '
.. vim.inspect(data)
.. "job "
.. 'job '
.. tostring(job_id)
.. "ev "
.. 'ev '
.. event,
vim.lsp.log_levels.ERROR
)
end,
on_exit = function(job_id, data, event)
if event ~= "exit" then
vim.notify(string.format("%s %s %s", job_id, event, vim.inspect(data)), vim.lsp.log_levels.ERROR)
if event ~= 'exit' then
vim.notify(string.format('%s %s %s', job_id, event, vim.inspect(data)), vim.lsp.log_levels.ERROR)
end
local lp = table.concat(lines, "\n")
vim.notify(string.format("test finished:\n %s", lp), vim.lsp.log_levels.INFO)
local lp = table.concat(lines, '\n')
vim.notify(string.format('test finished:\n %s', lp), vim.lsp.log_levels.INFO)
coverage = M.read_cov(cov)
if load == "-m" then
if load == '-m' then
M.toggle(true)
return M.show_func()
end
vfn.setqflist({}, " ", {
vfn.setqflist({}, ' ', {
title = cmd,
lines = lines,
efm = vim.o.efm .. [[,]] .. require("go.gotest").efm(),
efm = vim.o.efm .. [[,]] .. require('go.gotest').efm(),
})
api.nvim_command("doautocmd QuickFixCmdPost")
api.nvim_command('doautocmd QuickFixCmdPost')
-- vfn.delete(cov) -- maybe keep the file for other commands
end,
})

@ -58,7 +58,7 @@ local show_float = function(result)
title = "go package outline",
lines = result,
})
vim.cmd("lopen")
util.quickfix("lopen")
return
end
local win = textview:new({
@ -176,7 +176,7 @@ local show_panel = function(result, pkg, rerender)
title = "go package outline",
lines = defs,
})
vim.cmd("lopen")
util.quickfix("lopen")
end
log("cleanup")
vim.api.nvim_buf_delete(bufnr, { unload = true })

@ -1,13 +1,13 @@
local uv, api = vim.loop, vim.api
local util = require("go.utils")
local log = require("go.utils").log
local util = require('go.utils')
local log = require('go.utils').log
-- run command with loop
local run = function(cmd, opts)
opts = opts or {}
log(cmd)
if type(cmd) == "string" then
local split_pattern = "%s+"
if type(cmd) == 'string' then
local split_pattern = '%s+'
cmd = vim.split(cmd, split_pattern)
log(cmd)
end
@ -16,8 +16,8 @@ local run = function(cmd, opts)
job_options.args = job_options.args or {}
local cmdargs = vim.list_slice(cmd, 2, #cmd) or {}
if cmdargs and cmdargs[1] == "test" and #cmdargs == 3 then
table.insert(cmdargs, "." .. util.sep() .. "...")
if cmdargs and cmdargs[1] == 'test' and #cmdargs == 3 then
table.insert(cmdargs, '.' .. util.sep() .. '...')
log(cmdargs)
end
vim.list_extend(cmdargs, job_options.args)
@ -32,11 +32,11 @@ local run = function(cmd, opts)
-- local file = api.nvim_buf_get_name(0)
local handle = nil
local output_buf = ""
local output_buf = ''
local function update_chunk_fn(err, chunk)
if err then
vim.schedule(function()
vim.notify("error " .. tostring(err) .. vim.inspect(chunk or ""), vim.lsp.log_levels.WARN)
vim.notify('error ' .. tostring(err) .. vim.inspect(chunk or ''), vim.lsp.log_levels.WARN)
end)
end
if chunk then
@ -46,7 +46,7 @@ local run = function(cmd, opts)
end
local update_chunk = opts.update_chunk or update_chunk_fn
log("job:", cmd, job_options)
log('job:', cmd, job_options)
handle, _ = uv.spawn(
cmd,
{ stdio = { stdin, stdout, stderr }, args = job_options.args },
@ -70,13 +70,13 @@ local run = function(cmd, opts)
end
end
if code ~= 0 then
log("failed to run", code, output_buf)
log('failed to run', code, output_buf)
output_buf = output_buf or ""
vim.notify(cmd_str .. " failed exit code " .. tostring(code) .. output_buf, vim.lsp.log_levels.WARN)
output_buf = output_buf or ''
vim.notify(cmd_str .. ' failed exit code ' .. tostring(code) .. output_buf, vim.lsp.log_levels.WARN)
end
if output_buf ~= "" then
local lines = vim.split(output_buf, "\n", true)
if output_buf ~= '' then
local lines = vim.split(output_buf, '\n', true)
lines = util.handle_job_data(lines)
local locopts = {
title = vim.inspect(cmd),
@ -88,8 +88,8 @@ local run = function(cmd, opts)
log(locopts)
if #lines > 0 then
vim.schedule(function()
vim.fn.setloclist(0, {}, " ", locopts)
vim.cmd("lopen")
vim.fn.setloclist(0, {}, ' ', locopts)
util.quickfix('lopen')
end)
end
end
@ -98,7 +98,7 @@ local run = function(cmd, opts)
uv.read_start(stderr, function(err, data)
if data ~= nil then
update_chunk("stderr: " .. tostring(err), data)
update_chunk('stderr: ' .. tostring(err), data)
end
end)
stdout:read_start(update_chunk)
@ -106,7 +106,7 @@ local run = function(cmd, opts)
end
local function make(...)
local makeprg = vim.api.nvim_buf_get_option(0, "makeprg")
local makeprg = vim.api.nvim_buf_get_option(0, 'makeprg')
local args = { ... }
local setup = {}
if #args > 0 then

@ -2,27 +2,27 @@ local util = {}
local fn = vim.fn
local os_name = vim.loop.os_uname().sysname
local is_windows = os_name == "Windows" or os_name == "Windows_NT"
local is_windows = os_name == 'Windows' or os_name == 'Windows_NT'
-- Check whether current buffer contains main function
function util.has_main()
local output = vim.api.nvim_exec("grep func\\ main\\(\\) %", true)
local matchCount = vim.split(output, "\n")
local output = vim.api.nvim_exec('grep func\\ main\\(\\) %', true)
local matchCount = vim.split(output, '\n')
return #matchCount > 3
end
function util.sep()
if is_windows then
return "\\"
return '\\'
end
return "/"
return '/'
end
function util.sep2()
if is_windows then
return ";"
return ';'
end
return ":"
return ':'
end
function util.is_windows()
@ -31,15 +31,15 @@ end
function util.ext()
if is_windows then
return ".exe"
return '.exe'
end
return ""
return ''
end
local function get_path_sep()
if is_windows then
return ";"
return ';'
end
return ":"
return ':'
end
local function strip_path_sep(path)
@ -53,14 +53,14 @@ end
function util.root_dirs()
local dirs = {}
local root = fn.systemlist({ _GO_NVIM_CFG.go, "env", "GOROOT" })
local root = fn.systemlist({ _GO_NVIM_CFG.go, 'env', 'GOROOT' })
table.insert(dirs, root[1])
local paths = fn.systemlist({ _GO_NVIM_CFG.go, "env", "GOPATH" })
local paths = fn.systemlist({ _GO_NVIM_CFG.go, 'env', 'GOPATH' })
local sp = get_path_sep()
paths = vim.split(paths[1], sp)
for _, p in pairs(paths) do
p = fn.substitute(p, "\\\\", "/", "g")
p = fn.substitute(p, '\\\\', '/', 'g')
table.insert(dirs, p)
end
return dirs
@ -71,10 +71,10 @@ function util.go_packages(dirs, arglead)
local pkgs = {}
for _, dir in pairs(dirs) do
util.log(dir)
local scr_root = fn.expand(dir .. util.sep() .. "src" .. util.sep())
local scr_root = fn.expand(dir .. util.sep() .. 'src' .. util.sep())
util.log(scr_root, arglead)
local roots = fn.globpath(scr_root, arglead .. "*", 0, 1)
if roots == { "" } then
local roots = fn.globpath(scr_root, arglead .. '*', 0, 1)
if roots == { '' } then
roots = {}
end
@ -91,7 +91,7 @@ function util.go_packages(dirs, arglead)
pkg = strip_path_sep(pkg)
-- remove the scr root and keep the package in tact
pkg = fn.substitute(pkg, scr_root, "", "")
pkg = fn.substitute(pkg, scr_root, '', '')
table.insert(pkgs, pkg)
end
end
@ -112,16 +112,16 @@ end
-- endfunction
function util.interface_list(pkg)
local p = fn.systemlist({ _GO_NVIM_CFG.go, "doc", pkg })
local p = fn.systemlist({ _GO_NVIM_CFG.go, 'doc', pkg })
util.log(p)
local ifaces = {}
if p then
local contents = p -- vim.split(p[1], "\n")
for _, content in pairs(contents) do
util.log(content)
if content:find("interface") then
if content:find('interface') then
local iface_name = fn.matchstr(content, [[^type\s\+\zs\h\w*\ze\s\+interface]])
if iface_name ~= "" then
if iface_name ~= '' then
table.insert(ifaces, pkg .. iface_name)
end
end
@ -134,10 +134,10 @@ end
function util.smartrun()
local cmd
if util.has_main() then
cmd = string.format("lcd %:p:h | :set makeprg=%s\\ run\\ . | :make | :lcd -", _GO_NVIM_CFG.go)
cmd = string.format('lcd %:p:h | :set makeprg=%s\\ run\\ . | :make | :lcd -', _GO_NVIM_CFG.go)
vim.cmd(cmd)
else
cmd = string.format("setl makeprg=%s\\ run\\ . | :make", _GO_NVIM_CFG.go)
cmd = string.format('setl makeprg=%s\\ run\\ . | :make', _GO_NVIM_CFG.go)
vim.cmd(cmd)
end
end
@ -145,10 +145,10 @@ end
function util.smartbuild()
local cmd
if util.has_main() then
cmd = string.format("lcd %:p:h | :set makeprg=%s\\ build\\ . | :make | :lcd -", _GO_NVIM_CFG.go)
cmd = string.format('lcd %:p:h | :set makeprg=%s\\ build\\ . | :make | :lcd -', _GO_NVIM_CFG.go)
vim.cmd(cmd)
else
cmd = string.format("setl makeprg=%s\\ build\\ . | :make", _GO_NVIM_CFG.go)
cmd = string.format('setl makeprg=%s\\ build\\ . | :make', _GO_NVIM_CFG.go)
vim.cmd(cmd)
end
end
@ -170,7 +170,7 @@ util.map = function(modes, key, result, options)
local buffer = options.buffer
options.buffer = nil
if type(modes) ~= "table" then
if type(modes) ~= 'table' then
modes = { modes }
end
@ -192,7 +192,7 @@ end
util.deepcopy = function(orig)
local orig_type = type(orig)
local copy
if orig_type == "table" then
if orig_type == 'table' then
copy = {}
for orig_key, orig_value in next, orig, nil do
copy[util.deepcopy(orig_key)] = util.deepcopy(orig_value)
@ -210,7 +210,7 @@ util.handle_job_data = function(data)
end
-- Because the nvim.stdout's data will have an extra empty line at end on some OS (e.g. maxOS), we should remove it.
for _ = 1, 3, 1 do
if data[#data] == "" then
if data[#data] == '' then
table.remove(data, #data)
end
end
@ -220,7 +220,7 @@ util.handle_job_data = function(data)
return data
end
local cache_dir = fn.stdpath("cache")
local cache_dir = fn.stdpath('cache')
util.log = function(...)
if not _GO_NVIM_CFG then
return
@ -230,35 +230,35 @@ util.log = function(...)
end
local arg = { ... }
local log_default = string.format("%s%sgonvim.log", cache_dir, util.sep())
local log_default = string.format('%s%sgonvim.log', cache_dir, util.sep())
local log_path = _GO_NVIM_CFG.log_path or log_default
local str = ""
local str = ''
local info = debug.getinfo(2, "Sl")
str = str .. info.short_src .. ":" .. info.currentline
local info = debug.getinfo(2, 'Sl')
str = str .. info.short_src .. ':' .. info.currentline
for i, v in ipairs(arg) do
if type(v) == "table" then
str = str .. " |" .. tostring(i) .. ": " .. vim.inspect(v) .. "\n"
if type(v) == 'table' then
str = str .. ' |' .. tostring(i) .. ': ' .. vim.inspect(v) .. '\n'
else
str = str .. " |" .. tostring(i) .. ": " .. tostring(v)
str = str .. ' |' .. tostring(i) .. ': ' .. tostring(v)
end
end
if #str > 2 then
if log_path ~= nil and #log_path > 3 then
local f, err = io.open(log_path, "a+")
local f, err = io.open(log_path, 'a+')
if err then
vim.notify("failed to open log" .. log_path .. err, vim.lsp.log_levels.ERROR)
vim.notify('failed to open log' .. log_path .. err, vim.lsp.log_levels.ERROR)
return
end
if not f then
error("open file " .. log_path, f)
error('open file ' .. log_path, f)
end
io.output(f)
io.write(str .. "\n")
io.write(str .. '\n')
io.close(f)
else
vim.notify(str .. "\n", vim.lsp.log_levels.DEBUG)
vim.notify(str .. '\n', vim.lsp.log_levels.DEBUG)
end
end
end
@ -269,7 +269,7 @@ local rhs_options = {}
function rhs_options:new()
local instance = {
cmd = "",
cmd = '',
options = { noremap = false, silent = false, expr = false, nowait = false },
}
setmetatable(instance, self)
@ -283,17 +283,17 @@ function rhs_options:map_cmd(cmd_string)
end
function rhs_options:map_cr(cmd_string)
self.cmd = (":%s<CR>"):format(cmd_string)
self.cmd = (':%s<CR>'):format(cmd_string)
return self
end
function rhs_options:map_args(cmd_string)
self.cmd = (":%s<Space>"):format(cmd_string)
self.cmd = (':%s<Space>'):format(cmd_string)
return self
end
function rhs_options:map_cu(cmd_string)
self.cmd = (":<C-u>%s<CR>"):format(cmd_string)
self.cmd = (':<C-u>%s<CR>'):format(cmd_string)
return self
end
@ -339,8 +339,8 @@ end
function util.nvim_load_mapping(mapping)
for key, value in pairs(mapping) do
local mode, keymap = key:match("([^|]*)|?(.*)")
if type(value) == "table" then
local mode, keymap = key:match('([^|]*)|?(.*)')
if type(value) == 'table' then
local rhs = value.cmd
local options = value.options
vim.api.nvim_set_keymap(mode, keymap, rhs, options)
@ -349,7 +349,7 @@ function util.nvim_load_mapping(mapping)
end
function util.load_plugin(name, modulename)
assert(name ~= nil, "plugin should not empty")
assert(name ~= nil, 'plugin should not empty')
modulename = modulename or name
local has, plugin = pcall(require, modulename)
if has then
@ -358,30 +358,30 @@ function util.load_plugin(name, modulename)
local pkg = packer_plugins or nil
if pkg ~= nil then
-- packer installed
local has_packer = pcall(require, "packer")
local has_packer = pcall(require, 'packer')
if not has_packer then
error("packer not found")
error('packer not found')
return nil
end
local loader = require("packer").loader
local loader = require('packer').loader
if not pkg[name] or not pkg[name].loaded then
util.log("packer loader " .. name)
vim.cmd("packadd " .. name) -- load with default
util.log('packer loader ' .. name)
vim.cmd('packadd ' .. name) -- load with default
if pkg[name] ~= nil then
loader(name)
end
end
else
util.log("packadd " .. name)
util.log('packadd ' .. name)
local paths = vim.o.runtimepath
if paths:find(name) then
vim.cmd("packadd " .. name)
vim.cmd('packadd ' .. name)
end
end
has, plugin = pcall(require, modulename)
if not has then
util.info("plugin " .. name .. " module " .. modulename .. " not loaded ")
util.info('plugin ' .. name .. ' module ' .. modulename .. ' not loaded ')
return nil
end
return plugin
@ -415,63 +415,63 @@ end
-- end
function util.relative_to_cwd(name)
local rel = fn.isdirectory(name) == 0 and fn.fnamemodify(name, ":h:.") or fn.fnamemodify(name, ":.")
if rel == "." then
return "."
local rel = fn.isdirectory(name) == 0 and fn.fnamemodify(name, ':h:.') or fn.fnamemodify(name, ':.')
if rel == '.' then
return '.'
else
return "." .. util.sep() .. rel
return '.' .. util.sep() .. rel
end
end
function util.chdir(dir)
if fn.exists("*chdir") then
if fn.exists('*chdir') then
return fn.chdir(dir)
end
local oldir = fn.getcwd()
local cd = "cd"
if fn.exists("*haslocaldir") and fn.haslocaldir() then
cd = "lcd"
vim.cmd(cd .. " " .. fn.fnameescape(dir))
local cd = 'cd'
if fn.exists('*haslocaldir') and fn.haslocaldir() then
cd = 'lcd'
vim.cmd(cd .. ' ' .. fn.fnameescape(dir))
return oldir
end
end
function util.all_pkgs()
return "." .. util.sep() .. "..."
return '.' .. util.sep() .. '...'
end
-- log and messages
function util.warn(msg)
vim.notify("WARN: " .. msg, vim.lsp.log_levels.WARN)
vim.notify('WARN: ' .. msg, vim.lsp.log_levels.WARN)
end
function util.error(msg)
vim.notify("ERR: " .. msg, vim.lsp.log_levels.ERROR)
vim.notify('ERR: ' .. msg, vim.lsp.log_levels.ERROR)
end
function util.info(msg)
vim.notify("INF: " .. msg, vim.lsp.log_levels.INFO)
vim.notify('INF: ' .. msg, vim.lsp.log_levels.INFO)
end
function util.debug(msg)
vim.notify("DEBUG: " .. msg, vim.lsp.log_levels.DEBUG)
vim.notify('DEBUG: ' .. msg, vim.lsp.log_levels.DEBUG)
end
function util.rel_path(folder)
-- maybe expand('%:p:h:t')
local mod = "%:p"
local mod = '%:p'
if folder then
mod = "%:p:h"
mod = '%:p:h'
end
local fpath = fn.expand(mod)
local workfolders = vim.lsp.buf.list_workspace_folders()
if fn.empty(workfolders) == 0 then
fpath = "." .. fpath:sub(#workfolders[1] + 1)
fpath = '.' .. fpath:sub(#workfolders[1] + 1)
else
fpath = fn.fnamemodify(fn.expand(mod), ":p:.")
fpath = fn.fnamemodify(fn.expand(mod), ':p:.')
end
util.log(fpath:sub(#fpath), fpath, util.sep())
@ -491,25 +491,25 @@ end
function util.rtrim(s)
local n = #s
while n > 0 and s:find("^%s", n) do
while n > 0 and s:find('^%s', n) do
n = n - 1
end
return s:sub(1, n)
end
function util.ltrim(s)
return (s:gsub("^%s*", ""))
return (s:gsub('^%s*', ''))
end
function util.work_path()
local fpath = fn.expand("%:p:h")
local fpath = fn.expand('%:p:h')
local workfolders = vim.lsp.buf.list_workspace_folders()
if #workfolders == 1 then
return workfolders[1]
end
for _, value in pairs(workfolders) do
local mod = value .. util.sep() .. "go.mod"
local mod = value .. util.sep() .. 'go.mod'
if util.file_exists(mod) then
return value
end
@ -522,7 +522,7 @@ function util.empty(t)
if t == nil then
return true
end
if type(t) ~= "table" then
if type(t) ~= 'table' then
return false
end
return next(t) == nil
@ -531,50 +531,50 @@ end
local open = io.open
function util.read_file(path)
local file = open(path, "rb") -- r read mode and b binary mode
local file = open(path, 'rb') -- r read mode and b binary mode
if not file then
return nil
end
local content = file:read("*a") -- *a or *all reads the whole file
local content = file:read('*a') -- *a or *all reads the whole file
file:close()
return content
end
function util.restart(cmd_args)
local lsp = require("lspconfig")
local configs = require("lspconfig.configs")
local lsp = require('lspconfig')
local configs = require('lspconfig.configs')
for _, client in ipairs(lsp.util.get_clients_from_cmd_args(cmd_args)) do
if client.name == "gopls" then
util.log("client to stop: " .. client.name)
if client.name == 'gopls' then
util.log('client to stop: ' .. client.name)
client.stop()
vim.defer_fn(function()
configs[client.name].launch()
util.log("client to launch: " .. client.name)
util.log('client to launch: ' .. client.name)
end, 500)
end
end
end
util.deletedir = function(dir)
local lfs = require("lfs")
local lfs = require('lfs')
for file in lfs.dir(dir) do
local file_path = dir .. "/" .. file
if file ~= "." and file ~= ".." then
if lfs.attributes(file_path, "mode") == "file" then
local file_path = dir .. '/' .. file
if file ~= '.' and file ~= '..' then
if lfs.attributes(file_path, 'mode') == 'file' then
os.remove(file_path)
print("remove file", file_path)
elseif lfs.attributes(file_path, "mode") == "directory" then
print("dir", file_path)
print('remove file', file_path)
elseif lfs.attributes(file_path, 'mode') == 'directory' then
print('dir', file_path)
util.deletedir(file_path)
end
end
end
lfs.rmdir(dir)
util.log("remove dir", dir)
util.log('remove dir', dir)
end
function util.file_exists(name)
local f = io.open(name, "r")
local f = io.open(name, 'r')
if f ~= nil then
io.close(f)
return true
@ -596,7 +596,7 @@ function util.lines_from(file)
end
function util.list_directory()
return fn.map(fn.glob(fn.fnameescape("./") .. "/{,.}*/", 1, 1), 'fnamemodify(v:val, ":h:t")')
return fn.map(fn.glob(fn.fnameescape('./') .. '/{,.}*/', 1, 1), 'fnamemodify(v:val, ":h:t")')
end
function util.get_active_buf()
@ -605,7 +605,7 @@ function util.get_active_buf()
local result = {}
for _, item in ipairs(lb) do
if fn.empty(item.name) == 0 and item.hidden == 0 then
util.log("buf loaded", item.name)
util.log('buf loaded', item.name)
table.insert(result, { name = fn.shellescape(item.name), bufnr = item.bufnr })
end
end
@ -623,10 +623,10 @@ end
function util.set_nulls()
if _GO_NVIM_CFG.null_ls_document_formatting_disable then
local query = {}
if type(_GO_NVIM_CFG.null_ls_document_formatting_disable) ~= "boolean" then
if type(_GO_NVIM_CFG.null_ls_document_formatting_disable) ~= 'boolean' then
query = _GO_NVIM_CFG.null_ls_document_formatting_disable
end
local ok, nulls = pcall(require, "null-ls")
local ok, nulls = pcall(require, 'null-ls')
if ok then
nulls.disable(query)
end
@ -636,10 +636,10 @@ end
-- run in current source code path
function util.exec_in_path(cmd, bufnr, ...)
bufnr = bufnr or vim.api.nvim_get_current_buf()
local path = fn.fnamemodify(fn.bufname(bufnr), ":p:h")
local path = fn.fnamemodify(fn.bufname(bufnr), ':p:h')
local dir = util.chdir(path)
local result
if type(cmd) == "function" then
if type(cmd) == 'function' then
result = cmd(bufnr, ...)
else
result = fn.systemlist(cmd, ...)
@ -650,18 +650,18 @@ function util.exec_in_path(cmd, bufnr, ...)
end
function util.line_ending()
if vim.o.fileformat == "dos" then
return "\r\n"
elseif vim.o.fileformat == "mac" then
return "\r"
if vim.o.fileformat == 'dos' then
return '\r\n'
elseif vim.o.fileformat == 'mac' then
return '\r'
end
return "\n"
return '\n'
end
function util.offset(line, col)
util.log(line, col)
if vim.o.encoding ~= "utf-8" then
print("only utf-8 encoding is supported current encoding: ", vim.o.encoding)
if vim.o.encoding ~= 'utf-8' then
print('only utf-8 encoding is supported current encoding: ', vim.o.encoding)
end
return fn.line2byte(line) + col - 2
end
@ -669,18 +669,18 @@ end
-- parse //+build integration unit
function util.get_build_tags(buf)
local tags = {}
buf = buf or "%"
buf = buf or '%'
local pattern = [[^//\s*+build\s\+\(.\+\)]]
local cnt = vim.fn.getbufinfo(buf)[1]["linecount"]
local cnt = vim.fn.getbufinfo(buf)[1]['linecount']
cnt = math.min(cnt, 10)
for i = 1, cnt do
local line = vim.fn.trim(vim.fn.getbufline(buf, i)[1])
if string.find(line, "package") then
if string.find(line, 'package') then
break
end
local t = vim.fn.substitute(line, pattern, [[\1]], "")
local t = vim.fn.substitute(line, pattern, [[\1]], '')
if t ~= line then -- tag found
t = vim.fn.substitute(t, [[ \+]], ",", "g")
t = vim.fn.substitute(t, [[ \+]], ',', 'g')
table.insert(tags, t)
end
end
@ -691,33 +691,34 @@ end
-- a uuid
function util.uuid()
math.randomseed(tonumber(tostring(os.time()):reverse():sub(1, 9)))
local random = math.random
local template ='xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'
return string.gsub(template, '[xy]', function (c)
local v = (c == 'x') and random(0, 0xf) or random(8, 0xb)
return string.format('%x', v)
end)
math.randomseed(tonumber(tostring(os.time()):reverse():sub(1, 9)))
local random = math.random
local template = 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'
return string.gsub(template, '[xy]', function(c)
local v = (c == 'x') and random(0, 0xf) or random(8, 0xb)
return string.format('%x', v)
end)
end
local lorem = "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum"
local lorem =
'Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum'
function util.lorem()
return lorem
end
function util.random_words(len)
local str = util.lorem()
local words = fn.split(str, " ")
str = ""
local words = fn.split(str, ' ')
str = ''
for i = 1, len do
str = str .. " " .. words[math.random(#words)]
str = str .. ' ' .. words[math.random(#words)]
end
return str
end
function util.random_line()
local lines = vim.split(lorem, ", ")
return lines[math.random(#lines)] .. ","
local lines = vim.split(lorem, ', ')
return lines[math.random(#lines)] .. ','
end
function util.run_command(cmd, ...)
@ -725,6 +726,23 @@ function util.run_command(cmd, ...)
return result
end
function util.quickfix(cmd)
if _GO_NVIM_CFG.trouble == true then
local ok, trouble = pcall(require, 'trouble')
if ok then
if cmd:find('copen') then
trouble.open('quickfix')
else
trouble.open('loclist')
end
else
vim.notify('trouble not found')
end
else
vim.cmd(cmd)
end
end
util.debounce = function(func, duration)
local timer = vim.loop.new_timer()
local function inner(args)
@ -738,10 +756,10 @@ util.debounce = function(func, duration)
)
end
local group = vim.api.nvim_create_augroup("gonvim__CleanupLuvTimers", {})
vim.api.nvim_create_autocmd("VimLeavePre", {
local group = vim.api.nvim_create_augroup('gonvim__CleanupLuvTimers', {})
vim.api.nvim_create_autocmd('VimLeavePre', {
group = group,
pattern = "*",
pattern = '*',
callback = function()
if timer then
if timer:has_ref() then

Loading…
Cancel
Save