Update generated neovim config
This commit is contained in:
1299
config/neovim/store/lazy-plugins/nvim-jdtls/lua/jdtls.lua
Normal file
1299
config/neovim/store/lazy-plugins/nvim-jdtls/lua/jdtls.lua
Normal file
File diff suppressed because it is too large
Load Diff
767
config/neovim/store/lazy-plugins/nvim-jdtls/lua/jdtls/dap.lua
Normal file
767
config/neovim/store/lazy-plugins/nvim-jdtls/lua/jdtls/dap.lua
Normal file
@ -0,0 +1,767 @@
|
||||
---@mod jdtls.dap nvim-dap support for jdtls
|
||||
|
||||
local api = vim.api
|
||||
local uv = vim.loop
|
||||
local util = require('jdtls.util')
|
||||
local resolve_classname = util.resolve_classname
|
||||
local with_java_executable = util.with_java_executable
|
||||
local M = {}
|
||||
local default_config_overrides = {}
|
||||
|
||||
---@diagnostic disable-next-line: deprecated
|
||||
local get_clients = vim.lsp.get_clients or vim.lsp.get_active_clients
|
||||
|
||||
local function fetch_needs_preview(mainclass, project, cb, bufnr)
|
||||
local params = {
|
||||
command = 'vscode.java.checkProjectSettings',
|
||||
arguments = vim.fn.json_encode({
|
||||
className = mainclass,
|
||||
projectName = project,
|
||||
inheritedOptions = true,
|
||||
expectedOptions = { ['org.eclipse.jdt.core.compiler.problem.enablePreviewFeatures'] = 'enabled' }
|
||||
})
|
||||
}
|
||||
util.execute_command(params, function(err, use_preview)
|
||||
assert(not err, err and (err.message or vim.inspect(err)))
|
||||
cb(use_preview)
|
||||
end, bufnr)
|
||||
end
|
||||
|
||||
|
||||
local function enrich_dap_config(config_, on_config)
|
||||
if config_.mainClass
|
||||
and config_.projectName
|
||||
and config_.modulePaths ~= nil
|
||||
and config_.classPaths ~= nil
|
||||
and config_.javaExec then
|
||||
on_config(config_)
|
||||
return
|
||||
end
|
||||
local config = vim.deepcopy(config_)
|
||||
if not config.mainClass then
|
||||
config.mainClass = resolve_classname()
|
||||
end
|
||||
local bufnr = api.nvim_get_current_buf()
|
||||
util.execute_command({command = 'vscode.java.resolveMainClass'}, function(err, mainclasses)
|
||||
assert(not err, err and (err.message or vim.inspect(err)))
|
||||
|
||||
if not config.projectName then
|
||||
if not mainclasses then
|
||||
local msg = "Could not resolve classpaths. Project may have compile errors or unresolved dependencies"
|
||||
vim.notify(msg, vim.log.levels.WARN)
|
||||
else
|
||||
for _, entry in ipairs(mainclasses) do
|
||||
if entry.mainClass == config.mainClass then
|
||||
config.projectName = entry.projectName
|
||||
break
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
config.projectName = config.projectName or ''
|
||||
with_java_executable(config.mainClass, config.projectName, function(java_exec)
|
||||
config.javaExec = config.javaExec or java_exec
|
||||
local params = {
|
||||
command = 'vscode.java.resolveClasspath',
|
||||
arguments = { config.mainClass, config.projectName }
|
||||
}
|
||||
util.execute_command(params, function(err1, paths)
|
||||
assert(not err1, err1 and (err1.message or vim.inspect(err1)))
|
||||
if paths then
|
||||
config.modulePaths = config.modulePaths or paths[1]
|
||||
config.classPaths = config.classPaths or vim.tbl_filter(
|
||||
function(x)
|
||||
return vim.fn.isdirectory(x) == 1 or vim.fn.filereadable(x) == 1
|
||||
end,
|
||||
paths[2]
|
||||
)
|
||||
else
|
||||
vim.notify("Could not resolve classpaths. Project may have compile errors or unresolved dependencies", vim.log.levels.WARN)
|
||||
end
|
||||
on_config(config)
|
||||
end, bufnr)
|
||||
end, bufnr)
|
||||
end, bufnr)
|
||||
end
|
||||
|
||||
|
||||
local function start_debug_adapter(callback, config)
|
||||
-- User could trigger debug session for another project, open in another buffer
|
||||
local jdtls = vim.tbl_filter(function(client)
|
||||
return client.name == 'jdtls'
|
||||
and client.config
|
||||
and client.config.root_dir == config.cwd
|
||||
end, get_clients())[1]
|
||||
local bufnr = vim.lsp.get_buffers_by_client_id(jdtls and jdtls.id)[1] or vim.api.nvim_get_current_buf()
|
||||
util.execute_command({command = 'vscode.java.startDebugSession'}, function(err0, port)
|
||||
assert(not err0, vim.inspect(err0))
|
||||
|
||||
callback({
|
||||
type = 'server';
|
||||
host = '127.0.0.1';
|
||||
port = port;
|
||||
enrich_config = enrich_dap_config;
|
||||
})
|
||||
end, bufnr)
|
||||
end
|
||||
|
||||
|
||||
local TestKind = {
|
||||
None = -1,
|
||||
JUnit = 0,
|
||||
JUnit5 = 1,
|
||||
TestNG = 2
|
||||
}
|
||||
|
||||
|
||||
local LegacyTestLevel = {
|
||||
Root = 0,
|
||||
Folder = 1,
|
||||
Package = 2,
|
||||
Class = 3,
|
||||
Method = 4,
|
||||
}
|
||||
|
||||
local TestLevel = {
|
||||
Workspace = 1,
|
||||
WorkspaceFolder = 2,
|
||||
Project = 3,
|
||||
Package = 4,
|
||||
Class = 5,
|
||||
Method = 6,
|
||||
}
|
||||
|
||||
|
||||
local function make_request_args(lens, uri)
|
||||
local methodname = ''
|
||||
local name_parts = vim.split(lens.fullName, '#')
|
||||
local classname = name_parts[1]
|
||||
if #name_parts > 1 then
|
||||
methodname = name_parts[2]
|
||||
if lens.paramTypes and #lens.paramTypes > 0 then
|
||||
methodname = string.format('%s(%s)', methodname, table.concat(lens.paramTypes, ','))
|
||||
end
|
||||
end
|
||||
-- Format changes with https://github.com/microsoft/vscode-java-test/pull/1257
|
||||
local new_api = lens.testKind ~= nil
|
||||
local req_arguments
|
||||
if new_api then
|
||||
req_arguments = {
|
||||
testKind = lens.testKind,
|
||||
projectName = lens.projectName,
|
||||
testLevel = lens.testLevel,
|
||||
}
|
||||
if lens.testKind == TestKind.TestNG or lens.testLevel == TestLevel.Class then
|
||||
req_arguments.testNames = { lens.fullName, }
|
||||
elseif lens.testLevel then
|
||||
req_arguments.testNames = { lens.jdtHandler, }
|
||||
end
|
||||
else
|
||||
req_arguments = {
|
||||
uri = uri,
|
||||
-- Got renamed to fullName in https://github.com/microsoft/vscode-java-test/commit/57191b5367ae0a357b80e94f0def9e46f5e77796
|
||||
-- Include both for BWC
|
||||
classFullName = classname,
|
||||
fullName = classname,
|
||||
testName = methodname,
|
||||
project = lens.project,
|
||||
projectName = lens.project,
|
||||
scope = lens.level,
|
||||
testKind = lens.kind,
|
||||
}
|
||||
if lens.level == LegacyTestLevel.Method then
|
||||
req_arguments['start'] = lens.location.range['start']
|
||||
req_arguments['end'] = lens.location.range['end']
|
||||
end
|
||||
end
|
||||
return req_arguments
|
||||
end
|
||||
|
||||
|
||||
local function fetch_candidates(context, on_candidates)
|
||||
local cmd_codelens = 'vscode.java.test.search.codelens'
|
||||
local cmd_find_tests = 'vscode.java.test.findTestTypesAndMethods'
|
||||
local client = nil
|
||||
local params = {
|
||||
arguments = { context.uri };
|
||||
}
|
||||
for _, c in ipairs(get_clients({ bufnr = context.bufnr })) do
|
||||
local command_provider = c.server_capabilities.executeCommandProvider
|
||||
local commands = type(command_provider) == 'table' and command_provider.commands or {}
|
||||
if vim.tbl_contains(commands, cmd_codelens) then
|
||||
params.command = cmd_codelens
|
||||
client = c
|
||||
break
|
||||
elseif vim.tbl_contains(commands, cmd_find_tests) then
|
||||
params.command = cmd_find_tests
|
||||
client = c
|
||||
break
|
||||
end
|
||||
end
|
||||
if not client then
|
||||
local msg = (
|
||||
'No LSP client found that supports resolving possible test cases. '
|
||||
.. 'Did you add the JAR files of vscode-java-test to `config.init_options.bundles`?')
|
||||
vim.notify(msg, vim.log.levels.WARN)
|
||||
return
|
||||
end
|
||||
|
||||
local handler = function(err, result)
|
||||
if err then
|
||||
vim.notify('Error fetching test candidates: ' .. (err.message or vim.inspect(err)), vim.log.levels.ERROR)
|
||||
else
|
||||
on_candidates(result or {})
|
||||
end
|
||||
end
|
||||
client.request('workspace/executeCommand', params, handler, context.bufnr)
|
||||
end
|
||||
|
||||
|
||||
local function merge_unique(xs, ys)
|
||||
local result = {}
|
||||
local seen = {}
|
||||
local both = {}
|
||||
vim.list_extend(both, xs or {})
|
||||
vim.list_extend(both, ys or {})
|
||||
|
||||
for _, x in pairs(both) do
|
||||
if not seen[x] then
|
||||
table.insert(result, x)
|
||||
seen[x] = true
|
||||
end
|
||||
end
|
||||
|
||||
return result
|
||||
end
|
||||
|
||||
|
||||
local function fetch_launch_args(lens, context, on_launch_args)
|
||||
local req_arguments = make_request_args(lens, context.uri)
|
||||
local cmd_junit_args = {
|
||||
command = 'vscode.java.test.junit.argument';
|
||||
arguments = { vim.fn.json_encode(req_arguments) };
|
||||
}
|
||||
util.execute_command(cmd_junit_args, function(err, launch_args)
|
||||
if err then
|
||||
print('Error retrieving launch arguments: ' .. (err.message or vim.inspect(err)))
|
||||
elseif not launch_args then
|
||||
error((
|
||||
'Server must return launch_args as response to "vscode.java.test.junit.argument" command. '
|
||||
.. 'Check server logs via `:JdtShowlogs`. Sent: ' .. vim.inspect(req_arguments)))
|
||||
elseif launch_args.errorMessage then
|
||||
vim.notify(launch_args.errorMessage, vim.log.levels.WARN)
|
||||
else
|
||||
-- forward/backward compat with format change in
|
||||
-- https://github.com/microsoft/vscode-java-test/commit/5a78371ad60e86f858eace7726f0980926b6c31d
|
||||
if launch_args.body then
|
||||
launch_args = launch_args.body
|
||||
end
|
||||
|
||||
-- the classpath in the launch_args might be missing some classes
|
||||
-- See https://github.com/microsoft/vscode-java-test/issues/1073
|
||||
--
|
||||
-- That is why `java.project.getClasspaths` is used as well.
|
||||
local options = vim.fn.json_encode({ scope = 'test'; })
|
||||
local cmd = {
|
||||
command = 'java.project.getClasspaths';
|
||||
arguments = { vim.uri_from_bufnr(0), options };
|
||||
}
|
||||
util.execute_command(cmd, function(err1, resp)
|
||||
assert(not err1, vim.inspect(err1))
|
||||
launch_args.classpath = merge_unique(launch_args.classpath, resp.classpaths)
|
||||
on_launch_args(launch_args)
|
||||
end, context.bufnr)
|
||||
end
|
||||
end, context.bufnr)
|
||||
end
|
||||
|
||||
|
||||
local function get_method_lens_above_cursor(lenses_tree, lnum)
|
||||
local result = {
|
||||
best_match = nil
|
||||
}
|
||||
local find_nearest
|
||||
find_nearest = function(lenses)
|
||||
for _, lens in pairs(lenses) do
|
||||
local is_method = lens.level == LegacyTestLevel.Method or lens.testLevel == TestLevel.Method
|
||||
local range = lens.location and lens.location.range or lens.range
|
||||
local line = range.start.line
|
||||
local best_match_line
|
||||
if result.best_match then
|
||||
local best_match = assert(result.best_match)
|
||||
best_match_line = best_match.location and best_match.location.range.start.line or best_match.range.start.line
|
||||
end
|
||||
if is_method and line <= lnum and (best_match_line == nil or line > best_match_line) then
|
||||
result.best_match = lens
|
||||
end
|
||||
if lens.children then
|
||||
find_nearest(lens.children)
|
||||
end
|
||||
end
|
||||
end
|
||||
find_nearest(lenses_tree)
|
||||
return result.best_match
|
||||
end
|
||||
|
||||
|
||||
local function get_first_class_lens(lenses)
|
||||
for _, lens in pairs(lenses) do
|
||||
-- compatibility for versions prior to
|
||||
-- https://github.com/microsoft/vscode-java-test/pull/1257
|
||||
if lens.level == LegacyTestLevel.Class then
|
||||
return lens
|
||||
end
|
||||
if lens.testLevel == TestLevel.Class then
|
||||
return lens
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
--- Return path to com.microsoft.java.test.runner-jar-with-dependencies.jar if found in bundles
|
||||
---
|
||||
---@return string? path
|
||||
local function testng_runner()
|
||||
local vscode_runner = 'com.microsoft.java.test.runner-jar-with-dependencies.jar'
|
||||
local client = get_clients({name='jdtls'})[1]
|
||||
local bundles = client and client.config.init_options.bundles or {}
|
||||
for _, jar_path in pairs(bundles) do
|
||||
local parts = vim.split(jar_path, '/')
|
||||
if parts[#parts] == vscode_runner then
|
||||
return jar_path
|
||||
end
|
||||
local basepath = vim.fs.dirname(jar_path)
|
||||
if basepath then
|
||||
for name, _ in vim.fs.dir(basepath) do
|
||||
if name == vscode_runner then
|
||||
return vim.fs.joinpath(basepath, name)
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
return nil
|
||||
end
|
||||
|
||||
local function make_config(lens, launch_args, config_overrides)
|
||||
local config = {
|
||||
name = lens.fullName;
|
||||
type = 'java';
|
||||
request = 'launch';
|
||||
mainClass = launch_args.mainClass;
|
||||
projectName = launch_args.projectName;
|
||||
cwd = launch_args.workingDirectory;
|
||||
classPaths = launch_args.classpath;
|
||||
modulePaths = launch_args.modulepath;
|
||||
vmArgs = table.concat(launch_args.vmArguments, ' ');
|
||||
noDebug = false;
|
||||
}
|
||||
config = vim.tbl_extend('force', config, config_overrides or default_config_overrides)
|
||||
if lens.testKind == TestKind.TestNG or lens.kind == TestKind.TestNG then
|
||||
local jar = testng_runner()
|
||||
if jar then
|
||||
config.mainClass = 'com.microsoft.java.test.runner.Launcher'
|
||||
config.args = string.format('testng %s', lens.fullName)
|
||||
table.insert(config.classPaths, jar);
|
||||
else
|
||||
local msg = (
|
||||
"Using basic TestNG integration. "
|
||||
.. "For better test results add com.microsoft.java.test.runner-jar-with-dependencies.jar to one of the `bundles` folders")
|
||||
vim.notify(msg)
|
||||
config.mainClass = 'org.testng.TestNG'
|
||||
-- id is in the format <project>@<class>#<method>
|
||||
local parts = vim.split(lens.id, '@')
|
||||
parts = vim.split(parts[2], '#')
|
||||
if #parts > 1 then
|
||||
config.args = string.format('-testclass %s -methods %s.%s', parts[1], parts[1], parts[2])
|
||||
else
|
||||
config.args = string.format('-testclass %s', parts[1])
|
||||
end
|
||||
end
|
||||
else
|
||||
config.args = table.concat(launch_args.programArguments, ' ');
|
||||
end
|
||||
return config
|
||||
end
|
||||
|
||||
|
||||
|
||||
---@param bufnr? integer
|
||||
---@return JdtDapContext
|
||||
local function make_context(bufnr)
|
||||
bufnr = assert((bufnr == nil or bufnr == 0) and api.nvim_get_current_buf() or bufnr)
|
||||
return {
|
||||
bufnr = bufnr,
|
||||
uri = vim.uri_from_bufnr(bufnr)
|
||||
}
|
||||
end
|
||||
|
||||
|
||||
local function maybe_repeat(lens, config, context, opts, items)
|
||||
if not opts.until_error then
|
||||
return
|
||||
end
|
||||
if opts.until_error > 0 and #items == 0 then
|
||||
print('`until_error` set and no tests failed. Repeating.', opts.until_error)
|
||||
opts.until_error = opts.until_error - 1
|
||||
local repeat_test = function()
|
||||
M.experimental.run(lens, config, context, opts)
|
||||
end
|
||||
vim.defer_fn(repeat_test, 2000)
|
||||
elseif opts.until_error <= 0 then
|
||||
print('Stopping repeat, `until_error` reached', opts.until_error)
|
||||
end
|
||||
end
|
||||
|
||||
|
||||
---@param opts JdtTestOpts
|
||||
local function run(lens, config, context, opts)
|
||||
local ok, dap = pcall(require, 'dap')
|
||||
if not ok then
|
||||
vim.notify('`nvim-dap` must be installed to run and debug methods')
|
||||
return
|
||||
end
|
||||
config = vim.tbl_extend('force', config, opts.config or {})
|
||||
local test_results
|
||||
local server = nil
|
||||
|
||||
if lens.kind == TestKind.TestNG or lens.testKind == TestKind.TestNG then
|
||||
local testng = require('jdtls.testng')
|
||||
local run_opts = {}
|
||||
if config.mainClass == "com.microsoft.java.test.runner.Launcher" then
|
||||
function run_opts.before(conf)
|
||||
server = assert(uv.new_tcp(), "uv.new_tcp() must return handle")
|
||||
test_results = testng.mk_test_results(context.bufnr)
|
||||
server:bind('127.0.0.1', 0)
|
||||
server:listen(128, function(err2)
|
||||
assert(not err2, err2)
|
||||
local sock = assert(vim.loop.new_tcp(), "uv.new_tcp must return handle")
|
||||
server:accept(sock)
|
||||
sock:read_start(test_results.mk_reader(sock))
|
||||
end)
|
||||
conf.args = string.format('%s %s', server:getsockname().port, conf.args)
|
||||
return conf
|
||||
end
|
||||
|
||||
function run_opts.after()
|
||||
if server then
|
||||
server:shutdown()
|
||||
server:close()
|
||||
end
|
||||
test_results.show(lens, context)
|
||||
if opts.after_test then
|
||||
opts.after_test()
|
||||
end
|
||||
end
|
||||
else
|
||||
function run_opts.after()
|
||||
if opts.after_test then
|
||||
opts.after_test()
|
||||
end
|
||||
end
|
||||
end
|
||||
dap.run(config, run_opts)
|
||||
return
|
||||
end
|
||||
|
||||
local junit = require('jdtls.junit')
|
||||
dap.run(config, {
|
||||
before = function(conf)
|
||||
server = assert(uv.new_tcp(), "uv.new_tcp() must return handle")
|
||||
test_results = junit.mk_test_results(context.bufnr)
|
||||
server:bind('127.0.0.1', 0)
|
||||
server:listen(128, function(err2)
|
||||
assert(not err2, err2)
|
||||
local sock = assert(vim.loop.new_tcp(), "uv.new_tcp must return handle")
|
||||
server:accept(sock)
|
||||
sock:read_start(test_results.mk_reader(sock))
|
||||
end)
|
||||
conf.args = conf.args:gsub('-port ([0-9]+)', '-port ' .. server:getsockname().port);
|
||||
return conf
|
||||
end;
|
||||
after = function()
|
||||
if server then
|
||||
server:shutdown()
|
||||
server:close()
|
||||
end
|
||||
local items = test_results.show(lens)
|
||||
maybe_repeat(lens, config, context, opts, items)
|
||||
if opts.after_test then
|
||||
opts.after_test(items)
|
||||
end
|
||||
end;
|
||||
})
|
||||
end
|
||||
|
||||
|
||||
--- API of these methods is unstable and might change in the future
|
||||
M.experimental = {
|
||||
run = run,
|
||||
fetch_lenses = fetch_candidates,
|
||||
fetch_launch_args = fetch_launch_args,
|
||||
make_context = make_context,
|
||||
make_config = make_config,
|
||||
}
|
||||
|
||||
--- Debug the test class in the current buffer
|
||||
--- @param opts JdtTestOpts|nil
|
||||
function M.test_class(opts)
|
||||
opts = opts or {}
|
||||
local context = make_context(opts.bufnr)
|
||||
fetch_candidates(context, function(lenses)
|
||||
local lens = get_first_class_lens(lenses)
|
||||
if not lens then
|
||||
vim.notify('No test class found')
|
||||
return
|
||||
end
|
||||
fetch_launch_args(lens, context, function(launch_args)
|
||||
local config = make_config(lens, launch_args, opts.config_overrides)
|
||||
run(lens, config, context, opts)
|
||||
end)
|
||||
end)
|
||||
end
|
||||
|
||||
|
||||
--- Debug the nearest test method in the current buffer
|
||||
--- @param opts nil|JdtTestOpts
|
||||
function M.test_nearest_method(opts)
|
||||
opts = opts or {}
|
||||
local context = make_context(opts.bufnr)
|
||||
local lnum = opts.lnum or api.nvim_win_get_cursor(0)[1]
|
||||
fetch_candidates(context, function(lenses)
|
||||
local lens = get_method_lens_above_cursor(lenses, lnum)
|
||||
if not lens then
|
||||
vim.notify('No suitable test method found')
|
||||
return
|
||||
end
|
||||
fetch_launch_args(lens, context, function(launch_args)
|
||||
local config = make_config(lens, launch_args, opts.config_overrides)
|
||||
run(lens, config, context, opts)
|
||||
end)
|
||||
end)
|
||||
end
|
||||
|
||||
local function populate_candidates(list, lenses)
|
||||
for _, v in pairs(lenses) do
|
||||
table.insert(list, v)
|
||||
if v.children ~= nil then
|
||||
populate_candidates(list, v.children)
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
--- Prompt for a test method from the current buffer to run
|
||||
---@param opts nil|JdtTestOpts
|
||||
function M.pick_test(opts)
|
||||
opts = opts or {}
|
||||
local context = make_context(opts.bufnr)
|
||||
|
||||
fetch_candidates(context, function(lenses)
|
||||
local candidates = {}
|
||||
populate_candidates(candidates, lenses)
|
||||
|
||||
require('jdtls.ui').pick_one_async(
|
||||
candidates,
|
||||
'Tests> ',
|
||||
function(lens) return lens.fullName end,
|
||||
function(lens)
|
||||
if not lens then
|
||||
return
|
||||
end
|
||||
fetch_launch_args(lens, context, function(launch_args)
|
||||
local config = make_config(lens, launch_args, opts.config_overrides)
|
||||
run(lens, config, context, opts)
|
||||
end)
|
||||
end
|
||||
)
|
||||
end)
|
||||
end
|
||||
|
||||
|
||||
local hotcodereplace_type = {
|
||||
ERROR = "ERROR",
|
||||
WARNING = "WARNING",
|
||||
STARTING = "STARTING",
|
||||
END = "END",
|
||||
BUILD_COMPLETE = "BUILD_COMPLETE",
|
||||
}
|
||||
|
||||
|
||||
--- Discover executable main functions in the project
|
||||
---@param opts nil|JdtMainConfigOpts See |JdtMainConfigOpts|
|
||||
---@param callback fun(configurations: table[])
|
||||
function M.fetch_main_configs(opts, callback)
|
||||
opts = opts or {}
|
||||
if type(opts) == 'function' then
|
||||
vim.notify('First argument to `fetch_main_configs` changed to a `opts` table', vim.log.levels.WARN)
|
||||
callback = opts
|
||||
opts = {}
|
||||
end
|
||||
local configurations = {}
|
||||
local bufnr = api.nvim_get_current_buf()
|
||||
local jdtls = get_clients({ bufnr = bufnr, name = "jdtls"})[1]
|
||||
local root_dir = jdtls and jdtls.config and jdtls.config.root_dir
|
||||
util.execute_command({command = 'vscode.java.resolveMainClass'}, function(err, mainclasses)
|
||||
assert(not err, vim.inspect(err))
|
||||
|
||||
local remaining = #mainclasses
|
||||
if remaining == 0 then
|
||||
callback(configurations)
|
||||
return
|
||||
end
|
||||
for _, mc in pairs(mainclasses) do
|
||||
local mainclass = mc.mainClass
|
||||
local project = mc.projectName
|
||||
with_java_executable(mainclass, project, function(java_exec)
|
||||
fetch_needs_preview(mainclass, project, function(use_preview)
|
||||
util.execute_command({command = 'vscode.java.resolveClasspath', arguments = { mainclass, project }}, function(err1, paths)
|
||||
remaining = remaining - 1
|
||||
if err1 then
|
||||
print(string.format('Could not resolve classpath and modulepath for %s/%s: %s', project, mainclass, err1.message))
|
||||
return
|
||||
end
|
||||
local config = {
|
||||
cwd = root_dir;
|
||||
type = 'java';
|
||||
name = 'Launch ' .. (project or '') .. ': ' .. mainclass;
|
||||
projectName = project;
|
||||
mainClass = mainclass;
|
||||
modulePaths = paths[1];
|
||||
classPaths = paths[2];
|
||||
javaExec = java_exec;
|
||||
request = 'launch';
|
||||
console = 'integratedTerminal';
|
||||
vmArgs = use_preview and '--enable-preview' or nil;
|
||||
}
|
||||
config = vim.tbl_extend('force', config, opts.config_overrides or default_config_overrides)
|
||||
table.insert(configurations, config)
|
||||
if remaining == 0 then
|
||||
callback(configurations)
|
||||
end
|
||||
end, bufnr)
|
||||
end, bufnr)
|
||||
end, bufnr)
|
||||
end
|
||||
end, bufnr)
|
||||
end
|
||||
|
||||
---@class JdtMainConfigOpts
|
||||
---@field config_overrides nil|JdtDapConfig Overrides for the |dap-configuration|, see |JdtDapConfig|
|
||||
|
||||
|
||||
|
||||
--- Discover main classes in the project and setup |dap-configuration| entries for Java for them.
|
||||
---@param opts nil|JdtSetupMainConfigOpts See |JdtSetupMainConfigOpts|
|
||||
function M.setup_dap_main_class_configs(opts)
|
||||
opts = opts or {}
|
||||
local status, dap = pcall(require, 'dap')
|
||||
if not status then
|
||||
print('nvim-dap is not available')
|
||||
return
|
||||
end
|
||||
if dap.providers and dap.providers.configs then
|
||||
-- If users call this manually disable the automatic discovery on dap.continue()
|
||||
dap.providers.configs["jdtls"] = nil
|
||||
end
|
||||
if opts.verbose then
|
||||
vim.notify('Fetching debug configurations')
|
||||
end
|
||||
local on_ready = opts.on_ready or function() end
|
||||
M.fetch_main_configs(opts, function(configurations)
|
||||
local dap_configurations = dap.configurations.java or {}
|
||||
for _, config in ipairs(configurations) do
|
||||
for i, existing_config in pairs(dap_configurations) do
|
||||
if config.name == existing_config.name and config.cwd == existing_config["cwd"] then
|
||||
table.remove(dap_configurations, i)
|
||||
end
|
||||
end
|
||||
table.insert(dap_configurations, config)
|
||||
end
|
||||
dap.configurations.java = dap_configurations
|
||||
if opts.verbose then
|
||||
vim.notify(string.format('Updated %s debug configuration(s)', #configurations))
|
||||
end
|
||||
on_ready()
|
||||
end)
|
||||
end
|
||||
|
||||
---@class JdtSetupMainConfigOpts : JdtMainConfigOpts
|
||||
---@field verbose nil|boolean Print notifications on start and once finished. Default is false.
|
||||
---@field on_ready nil|function Callback called when the configurations got updated
|
||||
|
||||
|
||||
|
||||
--- Register a |dap-adapter| for java. Requires nvim-dap
|
||||
---@param opts nil|JdtSetupDapOpts See |JdtSetupDapOpts|
|
||||
function M.setup_dap(opts)
|
||||
local status, dap = pcall(require, 'dap')
|
||||
if not status then
|
||||
print('nvim-dap is not available')
|
||||
return
|
||||
end
|
||||
if dap.adapters.java then
|
||||
return
|
||||
end
|
||||
opts = opts or {}
|
||||
default_config_overrides = opts.config_overrides or {}
|
||||
dap.listeners.before['event_hotcodereplace']['jdtls'] = function(session, body)
|
||||
if body.changeType == hotcodereplace_type.BUILD_COMPLETE then
|
||||
if opts.hotcodereplace == 'auto' then
|
||||
vim.notify('Applying code changes')
|
||||
session:request('redefineClasses', nil, function(err)
|
||||
assert(not err, vim.inspect(err))
|
||||
end)
|
||||
end
|
||||
elseif body.message then
|
||||
vim.notify(body.message)
|
||||
end
|
||||
end
|
||||
dap.adapters.java = start_debug_adapter
|
||||
|
||||
if dap.providers and dap.providers.configs then
|
||||
dap.providers.configs["jdtls"] = function (bufnr)
|
||||
if vim.bo[bufnr].filetype ~= "java" then
|
||||
return {}
|
||||
end
|
||||
local co = coroutine.running()
|
||||
local resumed = false
|
||||
vim.defer_fn(function()
|
||||
if not resumed then
|
||||
resumed = true
|
||||
coroutine.resume(co, {})
|
||||
vim.schedule(function()
|
||||
vim.notify("Discovering main classes took too long", vim.log.levels.INFO)
|
||||
end)
|
||||
end
|
||||
end, 2000)
|
||||
M.fetch_main_configs(nil, function(configs)
|
||||
if not resumed then
|
||||
resumed = true
|
||||
coroutine.resume(co, configs)
|
||||
end
|
||||
end)
|
||||
return coroutine.yield()
|
||||
end
|
||||
end
|
||||
end
|
||||
---@class JdtSetupDapOpts
|
||||
---@field config_overrides JdtDapConfig These will be used as default overrides for |jdtls.dap.test_class|, |jdtls.dap.test_nearest_method| and discovered main classes
|
||||
---@field hotcodereplace? string "auto"
|
||||
|
||||
---@class JdtDapContext
|
||||
---@field bufnr number
|
||||
---@field win number
|
||||
---@field uri string uri equal to vim.uri_from_bufnr(bufnr)
|
||||
|
||||
---@class JdtDapConfig
|
||||
---@field cwd string|nil working directory for the test
|
||||
---@field vmArgs string|nil vmArgs for the test
|
||||
---@field noDebug boolean|nil If the test should run in debug mode
|
||||
|
||||
---@class JdtTestOpts
|
||||
---@field config nil|table Skeleton used for the |dap-configuration|
|
||||
---@field config_overrides nil|JdtDapConfig Overrides for the |dap-configuration|, see |JdtDapConfig|
|
||||
---@field until_error number|nil Number of times the test should be repeated if it doesn't fail
|
||||
---@field after_test nil|function Callback triggered after test run
|
||||
---@field bufnr? number Buffer that contains the test
|
||||
---@field lnum? number 1-indexed line number. Used to find nearest test. Defaults to cursor position of the current window.
|
||||
|
||||
return M
|
||||
245
config/neovim/store/lazy-plugins/nvim-jdtls/lua/jdtls/junit.lua
Normal file
245
config/neovim/store/lazy-plugins/nvim-jdtls/lua/jdtls/junit.lua
Normal file
@ -0,0 +1,245 @@
|
||||
local M = {}
|
||||
local ns = vim.api.nvim_create_namespace('junit')
|
||||
|
||||
local MessageId = {
|
||||
TestStart = '%TESTS',
|
||||
TestEnd = '%TESTE',
|
||||
TestFailed = '%FAILED',
|
||||
TestError = '%ERROR',
|
||||
TraceStart = '%TRACES',
|
||||
TraceEnd = '%TRACEE',
|
||||
IGNORE_TEST_PREFIX = '@Ignore: ',
|
||||
ASSUMPTION_FAILED_TEST_PREFIX = '@AssumptionFailure: ',
|
||||
}
|
||||
|
||||
local function parse_test_case(line)
|
||||
local matches = vim.fn.matchlist(line, '\\v\\d+,(\\@AssumptionFailure: |\\@Ignore: )?(.*)(\\[\\d+\\])?\\((.*)\\)')
|
||||
if #matches == 0 then
|
||||
return nil
|
||||
end
|
||||
return {
|
||||
fq_class = matches[5],
|
||||
method = matches[3],
|
||||
}
|
||||
end
|
||||
|
||||
local function parse(content, tests)
|
||||
local lines = vim.split(content, '\n')
|
||||
local tracing = false
|
||||
local test = nil
|
||||
for _, line in ipairs(lines) do
|
||||
if vim.startswith(line, MessageId.TestStart) then
|
||||
test = parse_test_case(line)
|
||||
if test then
|
||||
test.traces = {}
|
||||
test.failed = false
|
||||
else
|
||||
print('Could not parse line: ', line)
|
||||
end
|
||||
elseif vim.startswith(line, MessageId.TestEnd) then
|
||||
table.insert(tests, test)
|
||||
test = nil
|
||||
elseif vim.startswith(line, MessageId.TestFailed) or vim.startswith(line, MessageId.TestError) then
|
||||
-- Can get test failure without test start if it is a class initialization failure
|
||||
if not test then
|
||||
test = {
|
||||
fq_class = vim.split(line, ',')[2],
|
||||
traces = {},
|
||||
}
|
||||
end
|
||||
test.failed = true
|
||||
elseif vim.startswith(line, MessageId.TraceStart) then
|
||||
tracing = true
|
||||
elseif vim.startswith(line, MessageId.TraceEnd) then
|
||||
tracing = false
|
||||
elseif tracing and test then
|
||||
table.insert(test.traces, line)
|
||||
end
|
||||
end
|
||||
if test then
|
||||
table.insert(tests, test)
|
||||
end
|
||||
end
|
||||
|
||||
M.__parse = parse
|
||||
|
||||
local function mk_buf_loop(sock, handle_buffer)
|
||||
local buffer = ''
|
||||
return function(err, chunk)
|
||||
assert(not err, err)
|
||||
if chunk then
|
||||
buffer = buffer .. chunk
|
||||
else
|
||||
sock:close()
|
||||
handle_buffer(buffer)
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
function M.mk_test_results(bufnr)
|
||||
vim.api.nvim_buf_clear_namespace(bufnr, ns, 0, -1)
|
||||
vim.diagnostic.reset(ns, bufnr)
|
||||
local tests = {}
|
||||
|
||||
local handle_buffer = function(buf)
|
||||
parse(buf, tests)
|
||||
end
|
||||
|
||||
local function get_test_start_line_num(lenses, test)
|
||||
if test.method ~= nil then
|
||||
if #lenses > 0 then
|
||||
for _, v in ipairs(lenses) do
|
||||
if vim.startswith(v.label, test.method) then
|
||||
return v.range.start.line
|
||||
end
|
||||
end
|
||||
else
|
||||
if vim.startswith(lenses.label, test.method) then
|
||||
return lenses.range.start.line
|
||||
end
|
||||
end
|
||||
end
|
||||
return nil
|
||||
end
|
||||
|
||||
return {
|
||||
show = function(lens)
|
||||
local items = {}
|
||||
local repl = require('dap.repl')
|
||||
local num_failures = 0
|
||||
local lenses = lens.children or lens
|
||||
local failures = {}
|
||||
local results = {}
|
||||
local error_symbol = '❌'
|
||||
local success_symbol = '✔️ '
|
||||
for _, test in ipairs(tests) do
|
||||
local start_line_num = get_test_start_line_num(lenses, test)
|
||||
if test.failed then
|
||||
num_failures = num_failures + 1
|
||||
if start_line_num ~= nil then
|
||||
table.insert(results, {
|
||||
lnum = start_line_num,
|
||||
success = false
|
||||
})
|
||||
end
|
||||
|
||||
if test.method then
|
||||
repl.append(error_symbol .. ' ' .. test.method, '$')
|
||||
end
|
||||
local testMatch
|
||||
for _, msg in ipairs(test.traces) do
|
||||
local match = msg:match(string.format('at %s.%s', test.fq_class, test.method) .. '%(([%w%p]*:%d+)%)')
|
||||
if match then
|
||||
testMatch = true
|
||||
local lnum = vim.split(match, ':')[2]
|
||||
local trace = table.concat(test.traces, '\n')
|
||||
local cause = trace:sub(1, trace:find(msg, 1, true) - 1)
|
||||
if #trace > 140 then
|
||||
trace = trace:sub(1, 140) .. '...'
|
||||
end
|
||||
table.insert(items, {
|
||||
bufnr = bufnr,
|
||||
lnum = lnum,
|
||||
text = test.method .. ' ' .. trace,
|
||||
})
|
||||
table.insert(failures, {
|
||||
bufnr = bufnr,
|
||||
lnum = tonumber(lnum) - 1,
|
||||
col = 0,
|
||||
severity = vim.diagnostic.severity.ERROR,
|
||||
source = 'junit',
|
||||
message = cause,
|
||||
})
|
||||
break
|
||||
end
|
||||
repl.append(msg, '$')
|
||||
end
|
||||
if not testMatch then
|
||||
for _, msg in ipairs(test.traces) do
|
||||
local match = msg:match(string.format('at %s', test.fq_class) .. '[%w%p]+%(([%a%p]*:%d+)%)')
|
||||
if match then
|
||||
testMatch = true
|
||||
local lnum = vim.split(match, ':')[2]
|
||||
local trace = table.concat(test.traces, '\n')
|
||||
local cause = trace:sub(1, trace:find(msg, 1, true) - 1)
|
||||
table.insert(failures, {
|
||||
bufnr = bufnr,
|
||||
lnum = tonumber(lnum) - 1,
|
||||
col = 0,
|
||||
severity = vim.diagnostic.severity.ERROR,
|
||||
source = 'junit',
|
||||
message = cause,
|
||||
})
|
||||
break
|
||||
end
|
||||
end
|
||||
end
|
||||
if not testMatch then
|
||||
local cause = test.traces[1] .. '\n'
|
||||
if #test.traces > 2 then
|
||||
cause = cause .. test.traces[2] .. '\n'
|
||||
end
|
||||
table.insert(failures, {
|
||||
bufnr = bufnr,
|
||||
-- Generic error. Avoid overlay conflicts with virtual text
|
||||
lnum = start_line_num - 1,
|
||||
col = 0,
|
||||
severity = vim.diagnostic.severity.ERROR,
|
||||
source = 'junit',
|
||||
message = cause,
|
||||
})
|
||||
end
|
||||
else
|
||||
if start_line_num ~= nil then
|
||||
table.insert(results, {
|
||||
lnum = start_line_num,
|
||||
success = true
|
||||
})
|
||||
end
|
||||
repl.append(success_symbol .. ' ' .. test.method, '$')
|
||||
end
|
||||
end
|
||||
vim.diagnostic.set(ns, bufnr, failures, {})
|
||||
|
||||
local unique_lnums = {}
|
||||
-- Traverse in reverse order to preserve the mark position in case of Repeated/Parameterized Tests
|
||||
-- right_align doesn't seems to work correctly when set to false
|
||||
for i = #results, 1, -1 do
|
||||
local result = results[i]
|
||||
local symbol = result.success and success_symbol or error_symbol
|
||||
vim.api.nvim_buf_set_extmark(bufnr, ns, result.lnum, 0, {
|
||||
virt_text = { { symbol } },
|
||||
invalidate = true
|
||||
})
|
||||
unique_lnums[result.lnum] = true
|
||||
end
|
||||
for key, _ in pairs(unique_lnums) do
|
||||
local indent = '\t'
|
||||
vim.api.nvim_buf_set_extmark(bufnr, ns, key, 0, {
|
||||
virt_text = { { indent } },
|
||||
invalidate = true
|
||||
})
|
||||
end
|
||||
|
||||
if num_failures > 0 then
|
||||
vim.fn.setqflist({}, 'r', {
|
||||
title = 'jdtls-tests',
|
||||
items = items,
|
||||
})
|
||||
print(
|
||||
'Tests finished. Results printed to dap-repl.',
|
||||
#items > 0 and 'Errors added to quickfix list' or '',
|
||||
string.format('(%s %d / %d)', error_symbol, num_failures, #tests)
|
||||
)
|
||||
else
|
||||
print('Tests finished. Results printed to dap-repl.', success_symbol, #tests, 'succeeded')
|
||||
end
|
||||
return items
|
||||
end,
|
||||
mk_reader = function(sock)
|
||||
return vim.schedule_wrap(mk_buf_loop(sock, handle_buffer))
|
||||
end,
|
||||
}
|
||||
end
|
||||
|
||||
return M
|
||||
@ -0,0 +1,15 @@
|
||||
local M = {}
|
||||
|
||||
local is_windows = vim.loop.os_uname().version:match('Windows')
|
||||
|
||||
M.sep = is_windows and '\\' or '/'
|
||||
|
||||
function M.join(...)
|
||||
if vim.fs.joinpath then
|
||||
return vim.fs.joinpath(...)
|
||||
end
|
||||
local result = table.concat(vim.tbl_flatten {...}, M.sep):gsub(M.sep .. '+', M.sep)
|
||||
return result
|
||||
end
|
||||
|
||||
return M
|
||||
412
config/neovim/store/lazy-plugins/nvim-jdtls/lua/jdtls/setup.lua
Normal file
412
config/neovim/store/lazy-plugins/nvim-jdtls/lua/jdtls/setup.lua
Normal file
@ -0,0 +1,412 @@
|
||||
local api = vim.api
|
||||
local lsp = vim.lsp
|
||||
local uv = vim.loop
|
||||
local path = require('jdtls.path')
|
||||
local M = {}
|
||||
local URI_SCHEME_PATTERN = '^([a-zA-Z]+[a-zA-Z0-9+-.]*)://.*'
|
||||
|
||||
---@diagnostic disable-next-line: deprecated
|
||||
local get_clients = vim.lsp.get_clients or vim.lsp.get_active_clients
|
||||
|
||||
|
||||
local status_callback = function(_, result)
|
||||
api.nvim_command(string.format(':echohl Function | echo "%s" | echohl None',
|
||||
string.sub(result.message, 1, vim.v.echospace)))
|
||||
end
|
||||
|
||||
|
||||
M.restart = function()
|
||||
for _, client in ipairs(get_clients({ name = "jdtls" })) do
|
||||
local bufs = lsp.get_buffers_by_client_id(client.id)
|
||||
client.stop()
|
||||
vim.wait(30000, function()
|
||||
return lsp.get_client_by_id(client.id) == nil
|
||||
end)
|
||||
local client_id = lsp.start_client(client.config)
|
||||
if client_id then
|
||||
for _, buf in ipairs(bufs) do
|
||||
lsp.buf_attach_client(buf, client_id)
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
local function may_jdtls_buf(bufnr)
|
||||
if vim.bo[bufnr].filetype == "java" then
|
||||
return true
|
||||
end
|
||||
local fname = api.nvim_buf_get_name(bufnr)
|
||||
return vim.endswith(fname, "build.gradle") or vim.endswith(fname, "pom.xml")
|
||||
end
|
||||
|
||||
---@return integer? client_id
|
||||
local function attach_to_active_buf(bufnr, client_name)
|
||||
local function try_attach(buf)
|
||||
if not may_jdtls_buf(buf) then
|
||||
return nil
|
||||
end
|
||||
local clients = get_clients({ bufnr = buf, name = client_name })
|
||||
local _, client = next(clients)
|
||||
if client then
|
||||
lsp.buf_attach_client(bufnr, client.id)
|
||||
return client.id
|
||||
end
|
||||
return nil
|
||||
end
|
||||
|
||||
---@diagnostic disable-next-line: param-type-mismatch
|
||||
local altbuf = vim.fn.bufnr("#", -1)
|
||||
if altbuf and altbuf > 0 then
|
||||
local client_id = try_attach(altbuf)
|
||||
if client_id then
|
||||
return client_id
|
||||
end
|
||||
end
|
||||
for _, buf in ipairs(api.nvim_list_bufs()) do
|
||||
if api.nvim_buf_is_loaded(buf) then
|
||||
local client_id = try_attach(buf)
|
||||
if client_id then
|
||||
return client_id
|
||||
end
|
||||
end
|
||||
end
|
||||
print('No active LSP client found to use for jdt:// document')
|
||||
return nil
|
||||
end
|
||||
|
||||
function M.find_root(markers, source)
|
||||
source = source or api.nvim_buf_get_name(api.nvim_get_current_buf())
|
||||
local dirname = vim.fn.fnamemodify(source, ':p:h')
|
||||
local getparent = function(p)
|
||||
return vim.fn.fnamemodify(p, ':h')
|
||||
end
|
||||
while getparent(dirname) ~= dirname do
|
||||
for _, marker in ipairs(markers) do
|
||||
if uv.fs_stat(path.join(dirname, marker)) then
|
||||
return dirname
|
||||
end
|
||||
end
|
||||
dirname = getparent(dirname)
|
||||
end
|
||||
end
|
||||
|
||||
|
||||
M.extendedClientCapabilities = {
|
||||
classFileContentsSupport = true,
|
||||
generateToStringPromptSupport = true,
|
||||
hashCodeEqualsPromptSupport = true,
|
||||
advancedExtractRefactoringSupport = true,
|
||||
advancedOrganizeImportsSupport = true,
|
||||
generateConstructorsPromptSupport = true,
|
||||
generateDelegateMethodsPromptSupport = true,
|
||||
moveRefactoringSupport = true,
|
||||
overrideMethodsPromptSupport = true,
|
||||
executeClientCommandSupport = true,
|
||||
inferSelectionSupport = {
|
||||
"extractMethod",
|
||||
"extractVariable",
|
||||
"extractConstant",
|
||||
"extractVariableAllOccurrence"
|
||||
},
|
||||
}
|
||||
|
||||
|
||||
local function configuration_handler(err, result, ctx, config)
|
||||
local client_id = ctx.client_id
|
||||
local bufnr = 0
|
||||
local client = lsp.get_client_by_id(client_id)
|
||||
if client then
|
||||
-- This isn't done in start_or_attach because a user could use a plugin like editorconfig to configure tabsize/spaces
|
||||
-- That plugin may run after `start_or_attach` which is why we defer the setting lookup.
|
||||
-- This ensures the language-server will use the latest version of the options
|
||||
local new_settings = {
|
||||
java = {
|
||||
format = {
|
||||
insertSpaces = vim.bo[bufnr].expandtab,
|
||||
tabSize = lsp.util.get_effective_tabstop(bufnr)
|
||||
}
|
||||
}
|
||||
}
|
||||
if client.settings then
|
||||
client.settings.java = vim.tbl_deep_extend('keep', client.settings.java or {}, new_settings.java)
|
||||
else
|
||||
client.config.settings = vim.tbl_deep_extend('keep', client.config.settings or {}, new_settings)
|
||||
end
|
||||
end
|
||||
return lsp.handlers['workspace/configuration'](err, result, ctx, config)
|
||||
end
|
||||
|
||||
|
||||
local function maybe_implicit_save()
|
||||
-- 💀
|
||||
-- If the client is attached to a buffer that doesn't exist on the filesystem,
|
||||
-- jdtls struggles and cannot provide completions and other functionality
|
||||
-- until the buffer is re-attached (`:e!`)
|
||||
--
|
||||
-- So this implicitly saves a file before attaching the lsp client.
|
||||
local bufnr = api.nvim_get_current_buf()
|
||||
if vim.o.buftype == '' then
|
||||
local uri = vim.uri_from_bufnr(bufnr)
|
||||
local scheme = uri:match(URI_SCHEME_PATTERN)
|
||||
if scheme ~= 'file' then
|
||||
return
|
||||
end
|
||||
local fname = api.nvim_buf_get_name(bufnr)
|
||||
if fname == '' then
|
||||
return
|
||||
end
|
||||
local stat = vim.loop.fs_stat(fname)
|
||||
if not stat then
|
||||
local filepath = vim.fn.expand('%:p:h')
|
||||
assert(type(filepath) == "string")
|
||||
vim.fn.mkdir(filepath, 'p')
|
||||
vim.cmd('w')
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
|
||||
---@return string?, vim.lsp.Client?
|
||||
local function extract_data_dir(bufnr)
|
||||
-- Prefer client from current buffer, in case there are multiple jdtls clients (multiple projects)
|
||||
local client = get_clients({ name = "jdtls", bufnr = bufnr })[1]
|
||||
if not client then
|
||||
-- Try first matching jdtls client otherwise. In case the user is in a
|
||||
-- different buffer like the quickfix list
|
||||
local clients = get_clients({ name = "jdtls" })
|
||||
if vim.tbl_count(clients) > 1 then
|
||||
---@diagnostic disable-next-line: cast-local-type
|
||||
client = require('jdtls.ui').pick_one(
|
||||
clients,
|
||||
'Multiple jdtls clients found, pick one: ',
|
||||
function(c) return c.config.root_dir end
|
||||
)
|
||||
else
|
||||
client = clients[1]
|
||||
end
|
||||
end
|
||||
|
||||
if client and client.config and client.config.cmd then
|
||||
local cmd = client.config.cmd
|
||||
if type(cmd) == "table" then
|
||||
for i, part in pairs(cmd) do
|
||||
-- jdtls helper script uses `--data`, java jar command uses `-data`.
|
||||
if part == '-data' or part == '--data' then
|
||||
return client.config.cmd[i + 1], client
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
return nil, nil
|
||||
end
|
||||
|
||||
|
||||
---@param client vim.lsp.Client
|
||||
---@param opts jdtls.start.opts
|
||||
local function add_commands(client, bufnr, opts)
|
||||
local function create_cmd(name, command, cmdopts)
|
||||
api.nvim_buf_create_user_command(bufnr, name, command, cmdopts or {})
|
||||
end
|
||||
create_cmd("JdtCompile", "lua require('jdtls').compile(<f-args>)", {
|
||||
nargs = "?",
|
||||
complete = "custom,v:lua.require'jdtls'._complete_compile"
|
||||
})
|
||||
create_cmd("JdtSetRuntime", "lua require('jdtls').set_runtime(<f-args>)", {
|
||||
nargs = "?",
|
||||
complete = "custom,v:lua.require'jdtls'._complete_set_runtime"
|
||||
})
|
||||
create_cmd("JdtUpdateConfig", function(args)
|
||||
require("jdtls").update_projects_config(args.bang and { select_mode = "all" } or {})
|
||||
end, {
|
||||
bang = true
|
||||
})
|
||||
create_cmd("JdtJol", "lua require('jdtls').jol(<f-args>)", {
|
||||
nargs = "*"
|
||||
})
|
||||
create_cmd("JdtBytecode", "lua require('jdtls').javap()")
|
||||
create_cmd("JdtJshell", "lua require('jdtls').jshell()")
|
||||
create_cmd("JdtRestart", "lua require('jdtls.setup').restart()")
|
||||
local ok, dap = pcall(require, 'dap')
|
||||
if ok then
|
||||
local command_provider = client.server_capabilities.executeCommandProvider or {}
|
||||
local commands = command_provider.commands or {}
|
||||
if not vim.tbl_contains(commands, "vscode.java.startDebugSession") then
|
||||
return
|
||||
end
|
||||
|
||||
require("jdtls.dap").setup_dap(opts.dap or {})
|
||||
api.nvim_command "command! -buffer JdtUpdateDebugConfig lua require('jdtls.dap').setup_dap_main_class_configs({ verbose = true })"
|
||||
local redefine_classes = function()
|
||||
local session = dap.session()
|
||||
if not session then
|
||||
vim.notify('No active debug session')
|
||||
else
|
||||
vim.notify('Applying code changes')
|
||||
session:request('redefineClasses', nil, function(err)
|
||||
assert(not err, vim.inspect(err))
|
||||
end)
|
||||
end
|
||||
end
|
||||
api.nvim_create_user_command('JdtUpdateHotcode', redefine_classes, {
|
||||
desc = "Trigger reload of changed classes for current debug session",
|
||||
})
|
||||
end
|
||||
end
|
||||
|
||||
|
||||
---@class jdtls.start.opts
|
||||
---@field dap? JdtSetupDapOpts
|
||||
|
||||
|
||||
--- Start the language server (if not started), and attach the current buffer.
|
||||
---
|
||||
---@param config table<string, any> configuration. See |vim.lsp.start_client|
|
||||
---@param opts? jdtls.start.opts
|
||||
---@param start_opts? vim.lsp.start.Opts? options passed to vim.lsp.start
|
||||
---@return integer? client_id
|
||||
function M.start_or_attach(config, opts, start_opts)
|
||||
opts = opts or {}
|
||||
assert(config, 'config is required')
|
||||
assert(
|
||||
config.cmd and type(config.cmd) == 'table',
|
||||
'Config must have a `cmd` property and that must be a table. Got: '
|
||||
.. table.concat(config.cmd, ' ')
|
||||
)
|
||||
config.name = 'jdtls'
|
||||
local on_attach = config.on_attach
|
||||
config.on_attach = function(client, bufnr)
|
||||
if on_attach then
|
||||
on_attach(client, bufnr)
|
||||
end
|
||||
add_commands(client, bufnr, opts)
|
||||
end
|
||||
|
||||
local bufnr = api.nvim_get_current_buf()
|
||||
local bufname = api.nvim_buf_get_name(bufnr)
|
||||
-- Won't be able to get the correct root path for jdt:// URIs
|
||||
-- So need to connect to an existing client
|
||||
if vim.startswith(bufname, 'jdt://') then
|
||||
local client_id = attach_to_active_buf(bufnr, config.name)
|
||||
if client_id then
|
||||
return client_id
|
||||
end
|
||||
end
|
||||
|
||||
local uri = vim.uri_from_bufnr(bufnr)
|
||||
-- jdtls requires files to exist on the filesystem; it doesn't play well with scratch buffers
|
||||
if not vim.startswith(uri, "file://") then
|
||||
return
|
||||
end
|
||||
|
||||
config.root_dir = (config.root_dir
|
||||
or M.find_root({'.git', 'gradlew', 'mvnw'}, bufname)
|
||||
or vim.fn.getcwd()
|
||||
)
|
||||
config.handlers = config.handlers or {}
|
||||
config.handlers['language/status'] = config.handlers['language/status'] or status_callback
|
||||
config.handlers['workspace/configuration'] = config.handlers['workspace/configuration'] or configuration_handler
|
||||
local capabilities = vim.tbl_deep_extend('keep', config.capabilities or {}, lsp.protocol.make_client_capabilities())
|
||||
local extra_code_action_literals = {
|
||||
"source.generate.toString",
|
||||
"source.generate.hashCodeEquals",
|
||||
"source.organizeImports",
|
||||
}
|
||||
local code_action_literals = vim.tbl_get(
|
||||
capabilities,
|
||||
"textDocument",
|
||||
"codeAction",
|
||||
"codeActionLiteralSupport",
|
||||
"codeActionKind",
|
||||
"valueSet"
|
||||
) or {}
|
||||
for _, extra_literal in ipairs(extra_code_action_literals) do
|
||||
if not vim.tbl_contains(code_action_literals, extra_literal) then
|
||||
table.insert(code_action_literals, extra_literal)
|
||||
end
|
||||
end
|
||||
local extra_capabilities = {
|
||||
textDocument = {
|
||||
codeAction = {
|
||||
codeActionLiteralSupport = {
|
||||
codeActionKind = {
|
||||
valueSet = code_action_literals
|
||||
};
|
||||
};
|
||||
}
|
||||
}
|
||||
}
|
||||
config.capabilities = vim.tbl_deep_extend('force', capabilities, extra_capabilities)
|
||||
|
||||
config.init_options = config.init_options or {}
|
||||
config.init_options.extendedClientCapabilities = (
|
||||
config.init_options.extendedClientCapabilities or vim.deepcopy(M.extendedClientCapabilities)
|
||||
)
|
||||
config.settings = vim.tbl_deep_extend('keep', config.settings or {}, {
|
||||
-- the `java` property is used in other places to detect the client as the jdtls client
|
||||
-- don't remove it without updating those places
|
||||
java = {
|
||||
}
|
||||
})
|
||||
maybe_implicit_save()
|
||||
return vim.lsp.start(config, start_opts)
|
||||
end
|
||||
|
||||
|
||||
function M.wipe_data_and_restart()
|
||||
local data_dir, client = extract_data_dir(vim.api.nvim_get_current_buf())
|
||||
if not data_dir or not client then
|
||||
vim.notify(
|
||||
"Data directory wasn't detected. " ..
|
||||
"You must call `start_or_attach` at least once and the cmd must include a `-data` parameter (or `--data` if using the official `jdtls` wrapper)")
|
||||
return
|
||||
end
|
||||
local opts = {
|
||||
prompt = 'Are you sure you want to wipe the data folder: ' .. data_dir .. ' and restart? ',
|
||||
}
|
||||
vim.ui.select({'Yes', 'No'}, opts, function(choice)
|
||||
if choice ~= 'Yes' then
|
||||
return
|
||||
end
|
||||
vim.schedule(function()
|
||||
local bufs = vim.lsp.get_buffers_by_client_id(client.id)
|
||||
client.stop()
|
||||
vim.wait(30000, function()
|
||||
return vim.lsp.get_client_by_id(client.id) == nil
|
||||
end)
|
||||
vim.fn.delete(data_dir, 'rf')
|
||||
local client_id
|
||||
if vim.bo.filetype == "java" then
|
||||
client_id = lsp.start(client.config)
|
||||
else
|
||||
client_id = vim.lsp.start_client(client.config)
|
||||
end
|
||||
if client_id then
|
||||
for _, buf in ipairs(bufs) do
|
||||
lsp.buf_attach_client(buf, client_id)
|
||||
end
|
||||
end
|
||||
end)
|
||||
end)
|
||||
end
|
||||
|
||||
|
||||
---@deprecated not needed, start automatically adds commands
|
||||
function M.add_commands()
|
||||
end
|
||||
|
||||
|
||||
function M.show_logs()
|
||||
local data_dir = extract_data_dir(vim.api.nvim_get_current_buf())
|
||||
if data_dir then
|
||||
vim.cmd('split | e ' .. data_dir .. '/.metadata/.log | normal G')
|
||||
end
|
||||
if vim.fn.has('nvim-0.8') == 1 then
|
||||
vim.cmd('vsplit | e ' .. vim.fn.stdpath('log') .. '/lsp.log | normal G')
|
||||
else
|
||||
vim.cmd('vsplit | e ' .. vim.fn.stdpath('cache') .. '/lsp.log | normal G')
|
||||
end
|
||||
end
|
||||
|
||||
|
||||
return M
|
||||
@ -0,0 +1,97 @@
|
||||
local ns = vim.api.nvim_create_namespace('testng')
|
||||
local M = {}
|
||||
|
||||
local function parse(content, tests)
|
||||
local lines = vim.split(content, '\n')
|
||||
for _, line in ipairs(lines) do
|
||||
if vim.startswith(line, '@@<TestRunner-') then
|
||||
line = line.sub(line, 15)
|
||||
line = line:sub(1, -13)
|
||||
local test = vim.json.decode(line)
|
||||
if test.name ~= 'testStarted' then
|
||||
table.insert(tests, test)
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
M.__parse = parse
|
||||
|
||||
|
||||
local function mk_buf_loop(sock, handle_buffer)
|
||||
local buffer = ''
|
||||
return function(err, chunk)
|
||||
assert(not err, err)
|
||||
if chunk then
|
||||
buffer = buffer .. chunk
|
||||
else
|
||||
sock:close()
|
||||
handle_buffer(buffer)
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
|
||||
function M.mk_test_results(bufnr)
|
||||
vim.api.nvim_buf_clear_namespace(bufnr, ns, 0, -1)
|
||||
local tests = {}
|
||||
local handle_buffer = function(buf)
|
||||
parse(buf, tests)
|
||||
end
|
||||
local function get_test_line_nr(lenses, name)
|
||||
if lenses.fullName == name then
|
||||
return lenses.range.start.line
|
||||
end
|
||||
for _, v in ipairs(lenses) do
|
||||
if v.fullName == name then
|
||||
return v.range.start.line
|
||||
end
|
||||
end
|
||||
return nil
|
||||
end
|
||||
return {
|
||||
show = function(lens)
|
||||
local repl = require('dap.repl')
|
||||
|
||||
-- error = '✘',
|
||||
-- warn = '▲',
|
||||
-- hint = '⚑',
|
||||
-- info = '»'
|
||||
local lenses = lens.children or lens
|
||||
local failed = {}
|
||||
for _, test in ipairs(tests) do
|
||||
local lnum = get_test_line_nr(lenses, test.attributes.name)
|
||||
if lnum ~= nil then
|
||||
local testName = vim.split(test.attributes.name, '#')[2]
|
||||
local message = test.attributes.message or 'test failed'
|
||||
if test.name == 'testFailed' then
|
||||
table.insert(failed, {
|
||||
bufnr = bufnr,
|
||||
lnum = lnum,
|
||||
col = 0,
|
||||
severity = vim.diagnostic.severity.ERROR,
|
||||
source = 'testng',
|
||||
message = message,
|
||||
user_data = {}
|
||||
})
|
||||
repl.append('❌ ' .. testName .. ' failed')
|
||||
repl.append(message)
|
||||
repl.append(test.attributes.trace)
|
||||
elseif test.name == 'testFinished' then
|
||||
local text = { '✔️ ' }
|
||||
vim.api.nvim_buf_set_extmark(bufnr, ns, lnum, 0, {
|
||||
virt_text = { text },
|
||||
})
|
||||
repl.append('✔️ ' .. testName .. ' passed')
|
||||
end
|
||||
end
|
||||
end
|
||||
vim.diagnostic.set(ns, bufnr, failed, {})
|
||||
end,
|
||||
mk_reader = function(sock)
|
||||
return vim.schedule_wrap(mk_buf_loop(sock, handle_buffer))
|
||||
end,
|
||||
}
|
||||
end
|
||||
|
||||
return M
|
||||
159
config/neovim/store/lazy-plugins/nvim-jdtls/lua/jdtls/tests.lua
Normal file
159
config/neovim/store/lazy-plugins/nvim-jdtls/lua/jdtls/tests.lua
Normal file
@ -0,0 +1,159 @@
|
||||
---@mod jdtls.tests Functions which require vscode-java-test
|
||||
|
||||
|
||||
local api = vim.api
|
||||
local M = {}
|
||||
|
||||
--- Generate tests for the current class
|
||||
--- @param opts? {bufnr: integer}
|
||||
function M.generate(opts)
|
||||
opts = opts or {}
|
||||
local bufnr = opts.bufnr or api.nvim_get_current_buf()
|
||||
local win = api.nvim_get_current_win()
|
||||
local cursor = api.nvim_win_get_cursor(win) -- (1, 0) indexed
|
||||
local lnum = cursor[1]
|
||||
local line = api.nvim_buf_get_lines(bufnr, lnum -1, lnum, true)[1]
|
||||
local byteoffset = vim.fn.line2byte(lnum) + vim.str_byteindex(line, cursor[2], true)
|
||||
local command = {
|
||||
title = "Generate tests",
|
||||
command = "vscode.java.test.generateTests",
|
||||
arguments = {vim.uri_from_bufnr(bufnr), byteoffset},
|
||||
}
|
||||
---@param result? lsp.WorkspaceEdit
|
||||
local on_result = function(err, result)
|
||||
assert(not err, err)
|
||||
if not result then
|
||||
return
|
||||
end
|
||||
vim.lsp.util.apply_workspace_edit(result, "utf-16")
|
||||
|
||||
if not api.nvim_win_is_valid(win) or api.nvim_win_get_buf(win) ~= bufnr then
|
||||
return
|
||||
end
|
||||
|
||||
-- Set buffer of window to first created/changed file
|
||||
local uri = next(result.changes or {})
|
||||
if uri then
|
||||
local changed_buf = vim.uri_to_bufnr(uri)
|
||||
api.nvim_win_set_buf(win, changed_buf)
|
||||
else
|
||||
-- documentChanges?: ( TextDocumentEdit[] | (TextDocumentEdit | CreateFile | RenameFile | DeleteFile)[]);
|
||||
local changes = result.documentChanges or {}
|
||||
local _, change = next(changes)
|
||||
---@diagnostic disable-next-line: undefined-field
|
||||
local document = changes.textDocument or change.textDocument
|
||||
if change.uri and change.kind ~= "delete" then
|
||||
local changed_buf = vim.uri_to_bufnr(change.uri)
|
||||
api.nvim_win_set_buf(win, changed_buf)
|
||||
elseif document then
|
||||
local changed_buf = vim.uri_to_bufnr(document.uri)
|
||||
api.nvim_win_set_buf(win, changed_buf)
|
||||
end
|
||||
end
|
||||
end
|
||||
require("jdtls.util").execute_command(command, on_result, bufnr)
|
||||
end
|
||||
|
||||
|
||||
--- Go to the related subjects
|
||||
--- If in a test file, this will jump to classes the test might cover
|
||||
--- If in a non-test file, this will jump to related tests.
|
||||
---
|
||||
--- If no candidates are found, this calls `generate()`
|
||||
---
|
||||
--- @param opts? {goto_tests: boolean}
|
||||
function M.goto_subjects(opts)
|
||||
opts = opts or {}
|
||||
local win = api.nvim_get_current_win()
|
||||
local bufnr = api.nvim_get_current_buf()
|
||||
local function on_result(err, result)
|
||||
assert(not err, err)
|
||||
if api.nvim_get_current_win() ~= win then
|
||||
return
|
||||
end
|
||||
|
||||
result = result or {}
|
||||
local items = result and (result.items or {})
|
||||
if not next(items) then
|
||||
M.generate({ bufnr = bufnr })
|
||||
elseif #items == 1 then
|
||||
local test_buf = vim.uri_to_bufnr(items[1].uri)
|
||||
api.nvim_win_set_buf(win, test_buf)
|
||||
else
|
||||
local function label(x)
|
||||
return x.simpleName
|
||||
end
|
||||
table.sort(items, function(x, y)
|
||||
if x.outOfBelongingProject and not y.outOfBelongingProject then
|
||||
return false
|
||||
elseif not x.outOfBelongingProject and y.outOfBelongingProject then
|
||||
return true
|
||||
else
|
||||
if x.relevance == y.relevance then
|
||||
return x.simpleName < y.simpleName
|
||||
end
|
||||
return x.relevance < y.relevance
|
||||
end
|
||||
end)
|
||||
require("jdtls.ui").pick_one_async(items, "Goto: ", label, function(choice)
|
||||
if choice then
|
||||
local test_buf = vim.uri_to_bufnr(choice.uri)
|
||||
api.nvim_win_set_buf(win, test_buf)
|
||||
end
|
||||
end)
|
||||
end
|
||||
end
|
||||
local util = require("jdtls.util")
|
||||
if opts.goto_tests == nil then
|
||||
local is_testfile_cmd = {
|
||||
command = "java.project.isTestFile",
|
||||
arguments = { vim.uri_from_bufnr(bufnr) }
|
||||
}
|
||||
util.execute_command(is_testfile_cmd, function(err, is_testfile)
|
||||
assert(not err, err)
|
||||
local command = {
|
||||
command = "vscode.java.test.navigateToTestOrTarget",
|
||||
arguments = { vim.uri_from_bufnr(bufnr), not is_testfile }
|
||||
}
|
||||
require("jdtls.util").execute_command(command, on_result, bufnr)
|
||||
end, bufnr)
|
||||
else
|
||||
local command = {
|
||||
command = "vscode.java.test.navigateToTestOrTarget",
|
||||
arguments = { vim.uri_from_bufnr(bufnr), opts.goto_tests }
|
||||
}
|
||||
require("jdtls.util").execute_command(command, on_result, bufnr)
|
||||
end
|
||||
end
|
||||
|
||||
|
||||
---@private
|
||||
function M._ask_client_for_choice(prompt, choices, pick_many)
|
||||
local label = function(x)
|
||||
local description = x.description and (' ' .. x.description) or ''
|
||||
return x.label .. description
|
||||
end
|
||||
local ui = require("jdtls.ui")
|
||||
if pick_many then
|
||||
local opts = {
|
||||
is_selected = function(x) return x.picked end
|
||||
}
|
||||
local result = ui.pick_many(choices, prompt, label, opts)
|
||||
return vim.tbl_map(function(x) return x.value or x.label end, result)
|
||||
else
|
||||
local co, is_main = coroutine.running()
|
||||
local choice
|
||||
if co and not is_main then
|
||||
ui.pick_one_async(choices, prompt, label, function(result)
|
||||
coroutine.resume(co, result)
|
||||
end)
|
||||
choice = coroutine.yield()
|
||||
else
|
||||
choice = ui.pick_one(choices, prompt, label)
|
||||
end
|
||||
return choice and (choice.value or choice.label) or vim.NIL
|
||||
end
|
||||
end
|
||||
|
||||
|
||||
return M
|
||||
93
config/neovim/store/lazy-plugins/nvim-jdtls/lua/jdtls/ui.lua
Normal file
93
config/neovim/store/lazy-plugins/nvim-jdtls/lua/jdtls/ui.lua
Normal file
@ -0,0 +1,93 @@
|
||||
local M = {}
|
||||
|
||||
|
||||
function M.pick_one_async(items, prompt, label_fn, cb)
|
||||
if vim.ui then
|
||||
return vim.ui.select(items, {
|
||||
prompt = prompt,
|
||||
format_item = label_fn,
|
||||
}, cb)
|
||||
end
|
||||
local result = M.pick_one(items, prompt, label_fn)
|
||||
cb(result)
|
||||
end
|
||||
|
||||
|
||||
---@generic T
|
||||
---@param items T[]
|
||||
---@param prompt string
|
||||
---@param label_fn fun(item: T): string
|
||||
---@result T|nil
|
||||
function M.pick_one(items, prompt, label_fn)
|
||||
local choices = {prompt}
|
||||
for i, item in ipairs(items) do
|
||||
table.insert(choices, string.format('%d: %s', i, label_fn(item)))
|
||||
end
|
||||
local choice = vim.fn.inputlist(choices)
|
||||
if choice < 1 or choice > #items then
|
||||
return nil
|
||||
end
|
||||
return items[choice]
|
||||
end
|
||||
|
||||
|
||||
local function index_of(xs, term)
|
||||
for i, x in pairs(xs) do
|
||||
if x == term then
|
||||
return i
|
||||
end
|
||||
end
|
||||
return -1
|
||||
end
|
||||
|
||||
|
||||
function M.pick_many(items, prompt, label_f, opts)
|
||||
if not items or #items == 0 then
|
||||
return {}
|
||||
end
|
||||
|
||||
label_f = label_f or function(item)
|
||||
return item
|
||||
end
|
||||
opts = opts or {}
|
||||
|
||||
local choices = {}
|
||||
local selected = {}
|
||||
local is_selected = opts.is_selected or function(_)
|
||||
return false
|
||||
end
|
||||
for i, item in pairs(items) do
|
||||
local label = label_f(item)
|
||||
local choice = string.format("%d. %s", i, label)
|
||||
if is_selected(item) then
|
||||
choice = choice .. " *"
|
||||
table.insert(selected, item)
|
||||
end
|
||||
table.insert(choices, choice)
|
||||
end
|
||||
|
||||
while true do
|
||||
local answer = vim.fn.input(string.format("\n%s\n%s (Esc to finish): ", table.concat(choices, "\n"), prompt))
|
||||
if answer == "" then
|
||||
break
|
||||
end
|
||||
|
||||
local index = tonumber(answer)
|
||||
if index ~= nil then
|
||||
local choice = choices[index]
|
||||
local item = items[index]
|
||||
if string.find(choice, "*") == nil then
|
||||
table.insert(selected, item)
|
||||
choices[index] = choice .. " *"
|
||||
else
|
||||
choices[index] = string.gsub(choice, " %*$", "")
|
||||
local idx = index_of(selected, item)
|
||||
table.remove(selected, idx)
|
||||
end
|
||||
end
|
||||
end
|
||||
return selected
|
||||
end
|
||||
|
||||
|
||||
return M
|
||||
163
config/neovim/store/lazy-plugins/nvim-jdtls/lua/jdtls/util.lua
Normal file
163
config/neovim/store/lazy-plugins/nvim-jdtls/lua/jdtls/util.lua
Normal file
@ -0,0 +1,163 @@
|
||||
local api = vim.api
|
||||
local M = {}
|
||||
|
||||
---@diagnostic disable-next-line: deprecated
|
||||
local get_clients = vim.lsp.get_clients or vim.lsp.get_active_clients
|
||||
|
||||
|
||||
function M.execute_command(command, callback, bufnr)
|
||||
local clients = {}
|
||||
local candidates = get_clients({ bufnr = bufnr })
|
||||
for _, c in pairs(candidates) do
|
||||
local command_provider = c.server_capabilities.executeCommandProvider
|
||||
local commands = type(command_provider) == 'table' and command_provider.commands or {}
|
||||
if vim.tbl_contains(commands, command.command) then
|
||||
table.insert(clients, c)
|
||||
end
|
||||
end
|
||||
local num_clients = vim.tbl_count(clients)
|
||||
if num_clients == 0 then
|
||||
if bufnr then
|
||||
-- User could've switched buffer to non-java file, try all clients
|
||||
return M.execute_command(command, callback, nil)
|
||||
else
|
||||
vim.notify('No LSP client found that supports ' .. command.command, vim.log.levels.ERROR)
|
||||
return
|
||||
end
|
||||
end
|
||||
|
||||
if num_clients > 1 then
|
||||
vim.notify(
|
||||
'Multiple LSP clients found that support ' .. command.command .. ' you should have at most one JDTLS server running',
|
||||
vim.log.levels.WARN)
|
||||
end
|
||||
|
||||
local co
|
||||
if not callback then
|
||||
co = coroutine.running()
|
||||
if co then
|
||||
callback = function(err, resp)
|
||||
coroutine.resume(co, err, resp)
|
||||
end
|
||||
end
|
||||
end
|
||||
clients[1].request('workspace/executeCommand', command, callback, bufnr)
|
||||
if co then
|
||||
return coroutine.yield()
|
||||
end
|
||||
end
|
||||
|
||||
|
||||
---@param mainclass string
|
||||
---@param project string
|
||||
---@param fn fun(java_exec: string)
|
||||
---@param bufnr integer?
|
||||
function M.with_java_executable(mainclass, project, fn, bufnr)
|
||||
vim.validate({
|
||||
mainclass = { mainclass, 'string' }
|
||||
})
|
||||
|
||||
bufnr = assert((bufnr == nil or bufnr == 0) and api.nvim_get_current_buf() or bufnr)
|
||||
|
||||
local client = get_clients({ name = "jdtls", bufnr = bufnr, method = "workspace/executeCommand" })[1]
|
||||
if not client then
|
||||
print("No jdtls client found")
|
||||
return
|
||||
end
|
||||
|
||||
local provider = client.server_capabilities.executeCommandProvider or {}
|
||||
local supported_commands = provider.commands or {}
|
||||
local resolve_java_executable = "vscode.java.resolveJavaExecutable"
|
||||
|
||||
---@type lsp.ExecuteCommandParams
|
||||
local params
|
||||
local on_response
|
||||
if vim.tbl_contains(supported_commands, resolve_java_executable) then
|
||||
params = {
|
||||
command = resolve_java_executable,
|
||||
arguments = { mainclass, project }
|
||||
}
|
||||
---@param err lsp.ResponseError?
|
||||
on_response = function(err, java_exec)
|
||||
if err then
|
||||
print('Could not resolve java executable: ' .. err.message)
|
||||
else
|
||||
fn(java_exec)
|
||||
end
|
||||
end
|
||||
else
|
||||
local setting = "org.eclipse.jdt.ls.core.vm.location"
|
||||
params = {
|
||||
command = "java.project.getSettings",
|
||||
arguments = {
|
||||
vim.uri_from_bufnr(bufnr),
|
||||
{
|
||||
setting
|
||||
}
|
||||
}
|
||||
}
|
||||
---@param err lsp.ResponseError?
|
||||
on_response = function(err, settings)
|
||||
if err then
|
||||
print('Could not resolve java executable from settings: ' .. err.message)
|
||||
else
|
||||
fn(settings[setting] .. "/bin/java")
|
||||
end
|
||||
end
|
||||
end
|
||||
client.request("workspace/executeCommand", params, on_response, bufnr)
|
||||
end
|
||||
|
||||
|
||||
function M.with_classpaths(fn)
|
||||
local bufnr = api.nvim_get_current_buf()
|
||||
local uri = vim.uri_from_bufnr(bufnr)
|
||||
coroutine.wrap(function()
|
||||
local is_test_file_cmd = {
|
||||
command = 'java.project.isTestFile',
|
||||
arguments = { uri }
|
||||
};
|
||||
local options
|
||||
if vim.startswith(uri, "jdt://") then
|
||||
options = vim.fn.json_encode({ scope = "runtime" })
|
||||
else
|
||||
local err, is_test_file = M.execute_command(is_test_file_cmd, nil, bufnr)
|
||||
assert(not err, vim.inspect(err))
|
||||
options = vim.fn.json_encode({
|
||||
scope = is_test_file and 'test' or 'runtime';
|
||||
})
|
||||
end
|
||||
local cmd = {
|
||||
command = 'java.project.getClasspaths';
|
||||
arguments = { uri, options };
|
||||
}
|
||||
local err1, resp = M.execute_command(cmd, nil, bufnr)
|
||||
if err1 then
|
||||
print('Error executing java.project.getClasspaths: ' .. err1.message)
|
||||
else
|
||||
fn(resp)
|
||||
end
|
||||
end)()
|
||||
end
|
||||
|
||||
|
||||
function M.resolve_classname()
|
||||
local lines = api.nvim_buf_get_lines(0, 0, -1, true)
|
||||
local pkgname
|
||||
for _, line in ipairs(lines) do
|
||||
local match = line:match('package ([a-z0-9_\\.]+);')
|
||||
if match then
|
||||
pkgname = match
|
||||
break
|
||||
end
|
||||
end
|
||||
local classname = vim.fn.fnamemodify(vim.fn.expand('%'), ':t:r')
|
||||
if pkgname then
|
||||
return pkgname .. '.' .. classname
|
||||
else
|
||||
return classname
|
||||
end
|
||||
end
|
||||
|
||||
|
||||
return M
|
||||
Reference in New Issue
Block a user