|
| 1 | +local ra = require('rustaceanvim.rust_analyzer') |
| 2 | +local rts = require('rustaceanvim.treesitter') |
| 3 | + |
| 4 | +local M = {} |
| 5 | + |
| 6 | +---@class rustaceanvim.RATestInfo |
| 7 | +---@field runnable rustaceanvim.RARunnable |
| 8 | + |
| 9 | +---@param offset_encoding string |
| 10 | +---@return lsp.TextDocumentPositionParams |
| 11 | +local function get_params(offset_encoding) |
| 12 | + local position_params = vim.lsp.util.make_position_params(0, offset_encoding) |
| 13 | + |
| 14 | + if rts.has_tree_sitter_rust() then |
| 15 | + local fn_identifier_position = rts.find_fn_identifier_position() |
| 16 | + if fn_identifier_position ~= nil then |
| 17 | + position_params.position = fn_identifier_position |
| 18 | + end |
| 19 | + end |
| 20 | + |
| 21 | + return position_params |
| 22 | +end |
| 23 | + |
| 24 | +---@param offset_encoding string |
| 25 | +---@return lsp.Handler See |lsp-handler| |
| 26 | +local function mk_handler(offset_encoding) |
| 27 | + ---@param tests? rustaceanvim.RATestInfo[] |
| 28 | + return function(_, tests) |
| 29 | + if tests == nil then |
| 30 | + -- this can be nil when LSP has not finished loading |
| 31 | + return |
| 32 | + end |
| 33 | + |
| 34 | + local test_locations = {} |
| 35 | + for _, test in ipairs(tests) do |
| 36 | + table.insert(test_locations, test.runnable.location) |
| 37 | + end |
| 38 | + |
| 39 | + if #test_locations == 0 then |
| 40 | + return |
| 41 | + elseif #test_locations == 1 then |
| 42 | + vim.lsp.util.show_document(test_locations[1], offset_encoding, { reuse_win = true, focus = true }) |
| 43 | + return |
| 44 | + else |
| 45 | + local quickfix_entries = vim.lsp.util.locations_to_items(test_locations, offset_encoding) |
| 46 | + vim.fn.setqflist({}, ' ', { title = 'related tests', items = quickfix_entries }) |
| 47 | + vim.cmd([[ botright copen ]]) |
| 48 | + end |
| 49 | + end |
| 50 | +end |
| 51 | + |
| 52 | +---@return nil |
| 53 | +function M.related_tests() |
| 54 | + local clients = ra.get_active_rustaceanvim_clients(0) |
| 55 | + if #clients == 0 then |
| 56 | + return |
| 57 | + end |
| 58 | + |
| 59 | + local offset_encoding = clients[1].offset_encoding or 'utf-8' |
| 60 | + |
| 61 | + local params = get_params(offset_encoding) |
| 62 | + ra.buf_request(0, 'rust-analyzer/relatedTests', params, mk_handler(offset_encoding)) |
| 63 | +end |
| 64 | + |
| 65 | +return M |
0 commit comments