robin/laufey

git clone https://git.robinwobin.dev/robin/laufey

robinmerge: 1dc9728daa1d8a2702

master
9.9 KiB314 linesraw
1local M = {}
2
3local report_info = vim.health.info
4local report_warn = vim.health.warn
5
6--- Buffer the user was in when they ran `:checkhealth`.
7--- @type integer?
8local cur_bufnr = -1
9
10--- Decorates a buffer-id in a report line, so it is easy for the user to see (and for us to highlight).
11--- @param bufnr integer
12--- @return string
13local function decor_curbuf(bufnr)
14  if bufnr == cur_bufnr and vim.api.nvim_buf_is_valid(bufnr) then
15    return ('%d (current buffer, %q)'):format(
16      bufnr,
17      vim.fs.basename(vim.api.nvim_buf_get_name(bufnr))
18    )
19  end
20  return tostring(bufnr)
21end
22
23local function check_log()
24  local log = vim.lsp.log
25  local current_log_level = log.get_level()
26  local log_level_string = assert(log.levels[current_log_level])
27  report_info(string.format('LSP log level: %s', log_level_string))
28
29  if current_log_level < log.levels.WARN then
30    report_warn(
31      string.format(
32        'Log level %s will cause degraded performance and high disk usage',
33        log_level_string
34      )
35    )
36  end
37
38  local log_path = log.get_filename()
39  report_info(string.format('Log path: %s', log_path))
40
41  local log_file = vim.uv.fs_stat(log_path)
42  local log_size = log_file and log_file.size or 0
43
44  local report_fn = (log_size / 1000000 > 100 and report_warn or report_info)
45  report_fn(string.format('Log size: %d KB', log_size / 1000))
46end
47
48local function check_active_features()
49  vim.health.start('vim.lsp: Active Features')
50  if not next(vim.lsp.get_clients()) then
51    report_info('No active clients')
52    return
53  end
54
55  for capname, capability in vim.spairs(vim.lsp._capability.all) do
56    ---@type string[]
57    local buf_infos = {}
58    for bufnr, instance in pairs(capability.active) do
59      local client_info = vim
60        .iter(pairs(instance.client_state))
61        :map(function(client_id)
62          local client = vim.lsp.get_client_by_id(client_id)
63          if client then
64            return string.format('%s (id: %d)', client.name, client.id)
65          else
66            return string.format('unknown (id: %d)', client_id)
67          end
68        end)
69        :join(', ')
70      if client_info == '' then
71        client_info = 'No supported client attached'
72      end
73
74      buf_infos[#buf_infos + 1] = ('  [%s]: %s'):format(decor_curbuf(bufnr), client_info)
75    end
76
77    report_info(table.concat({
78      capname,
79      '- Active buffers:',
80      vim.tbl_isempty(buf_infos) and '  (none)' or string.format(table.concat(buf_infos, '\n')),
81    }, '\n'))
82  end
83end
84
85--- @param f function
86--- @return string
87local function func_tostring(f)
88  local info = assert(debug.getinfo(f, 'S'))
89  return ('<function %s:%s>'):format(info.source, info.linedefined)
90end
91
92local function check_active_clients()
93  vim.health.start('vim.lsp: Active Clients')
94  local clients = vim.lsp.get_clients()
95  if next(clients) then
96    for _, client in pairs(clients) do
97      local server_version = vim.tbl_get(client, 'server_info', 'version')
98        or '? (no serverInfo.version response)'
99      local cmd ---@type string
100      local ccmd = client.config.cmd
101      if type(ccmd) == 'table' then
102        cmd = vim.inspect(ccmd)
103      elseif type(ccmd) == 'function' then
104        cmd = func_tostring(ccmd)
105      end
106      local dirs_info ---@type string
107      if client.workspace_folders and #client.workspace_folders > 1 then
108        local wfolders = {} --- @type string[]
109        for _, dir in ipairs(client.workspace_folders) do
110          wfolders[#wfolders + 1] = dir.name
111        end
112        dirs_info = ('- Workspace folders:\n    %s'):format(table.concat(wfolders, '\n    '))
113      else
114        dirs_info = string.format(
115          '- Root directory: %s',
116          -- vim.fs.relpath does not prepend '~/' while fnamemodify does
117          client.root_dir and vim.fn.fnamemodify(client.root_dir, ':~')
118        ) or nil
119      end
120      report_info(table.concat({
121        string.format('%s (id: %d)', client.name, client.id),
122        ('- Attached buffers: %s'):format(
123          vim.iter(pairs(client.attached_buffers)):map(decor_curbuf):join(', ')
124        ),
125        string.format('- Version: %s', server_version),
126        dirs_info,
127        string.format('- Command: %s', cmd),
128        string.format('- Settings: %s', vim.inspect(client.settings, { newline = '\n  ' })),
129      }, '\n'))
130    end
131  else
132    report_info('No active clients')
133  end
134end
135
136-- Non-LSP filewatchers are also checked in: runtime/lua/vim/health/health.lua
137local function check_watcher()
138  -- Only run the check if file watching has been enabled by a client.
139  local clients = vim.lsp.get_clients()
140  if
141    --- @param client vim.lsp.Client
142    vim.iter(clients):all(function(client)
143      local has_capability = vim.tbl_get(
144        client.capabilities,
145        'workspace',
146        'didChangeWatchedFiles',
147        'dynamicRegistration'
148      )
149      local has_dynamic_capability =
150        client.dynamic_capabilities:get('workspace/didChangeWatchedFiles')
151      return has_capability == nil
152        or has_dynamic_capability == nil
153        or client.workspace_folders == nil
154    end)
155  then
156    report_info('Filewatchers "(workspace/didChangeWatchedFiles)" disabled on all clients')
157    return
158  end
159
160  local watchfunc = vim.lsp._watchfiles._watchfunc
161  local watchfunc_name --- @type string
162  if watchfunc == vim._watch.watch then
163    watchfunc_name = 'libuv-watch'
164  elseif watchfunc == vim._watch.watchdirs then
165    watchfunc_name = 'libuv-watchdirs'
166  elseif watchfunc == vim._watch.inotify then
167    watchfunc_name = 'inotify'
168  else
169    local info = assert(debug.getinfo(watchfunc, 'S'))
170    watchfunc_name = string.format('Custom (%s)', info.source)
171  end
172
173  report_info('Filewatch backend: ' .. watchfunc_name)
174  if watchfunc_name == 'libuv-watchdirs' then
175    report_warn('libuv-watchdirs has known performance issues. Consider installing inotify-tools.')
176  end
177end
178
179local function check_position_encodings()
180  local clients = vim.lsp.get_clients()
181  if not next(clients) then
182    report_info('Position encodings: No active clients')
183  else
184    local position_encodings = {} ---@type table<integer, table<string, integer[]>>
185    for _, client in pairs(clients) do
186      for bufnr in pairs(client.attached_buffers) do
187        if not position_encodings[bufnr] then
188          position_encodings[bufnr] = {}
189        end
190        if not position_encodings[bufnr][client.offset_encoding] then
191          position_encodings[bufnr][client.offset_encoding] = {}
192        end
193        table.insert(position_encodings[bufnr][client.offset_encoding], client.id)
194      end
195    end
196
197    -- Check if any buffers are attached to multiple clients with different position encodings
198    local buffers = {} ---@type integer[]
199    for bufnr, encodings in pairs(position_encodings) do
200      local list = {} ---@type string[]
201      for k in pairs(encodings) do
202        list[#list + 1] = k
203      end
204
205      if #list > 1 then
206        buffers[#buffers + 1] = bufnr
207      end
208    end
209
210    if #buffers > 0 then
211      local lines = {
212        'Position encodings: Found buffers attached to multiple clients with different position encodings.',
213      }
214      for _, bufnr in ipairs(buffers) do
215        local encodings = position_encodings[bufnr]
216        local parts = {}
217        for encoding, client_ids in pairs(encodings) do
218          table.insert(
219            parts,
220            string.format('%s (client id(s): %s)', encoding:upper(), table.concat(client_ids, ', '))
221          )
222        end
223        table.insert(lines, string.format('- Buffer %d: %s', bufnr, table.concat(parts, ', ')))
224      end
225      report_warn(
226        table.concat(lines, '\n'),
227        'Use the positionEncodings client capability to ensure all clients use the same position encoding'
228      )
229    else
230      report_info('Position encodings: No buffers contain mixed position encodings')
231    end
232  end
233end
234
235local function check_enabled_configs()
236  vim.health.start('vim.lsp: Enabled Configurations')
237
238  local known_filetypes = vim.filetype._get_known_filetypes()
239
240  for name in vim.spairs(vim.lsp._enabled_configs) do
241    local config = vim.lsp.config[name]
242    local text = {} --- @type string[]
243    text[#text + 1] = ('%s:'):format(name)
244    if not config then
245      report_warn(
246        ("'%s' config not found. Ensure that vim.lsp.config('%s') was called."):format(name, name)
247      )
248    else
249      for k, v in
250        vim.spairs(config --[[@as table<string,any>]])
251      do
252        local v_str --- @type string?
253        if k == 'name' then
254          v_str = nil
255        elseif k == 'filetypes' then
256          v_str = table.concat(v, ', ')
257        elseif type(v) == 'function' then
258          v_str = func_tostring(v)
259        else
260          v_str = vim.inspect(v, { newline = '\n  ' })
261        end
262
263        if k == 'cmd' and type(v) == 'table' and vim.fn.executable(v[1]) == 0 then
264          report_warn(("'%s' is not executable. Configuration will not be used."):format(v[1]))
265        end
266
267        if k == 'filetypes' and type(v) == 'table' then
268          for _, filetype in
269            ipairs(v --[[@as string[] ]])
270          do
271            if not known_filetypes[filetype] then
272              report_warn(
273                ("Unknown filetype '%s' (Hint: filename extension != filetype)."):format(filetype)
274              )
275            end
276          end
277        end
278
279        if v_str then
280          text[#text + 1] = ('- %s: %s'):format(k, v_str)
281        end
282      end
283    end
284    text[#text + 1] = ''
285    report_info(table.concat(text, '\n'))
286  end
287end
288
289--- Performs a healthcheck for LSP
290function M.check()
291  cur_bufnr = vim.fn.bufnr('#')
292
293  check_log()
294  check_watcher()
295  check_position_encodings()
296  check_active_features()
297  check_active_clients()
298  check_enabled_configs()
299
300  --- Highlight the "current buffer" token emitted by `decor_curbuf`.
301  vim.api.nvim_create_autocmd('FileType', {
302    pattern = 'checkhealth',
303    once = true,
304    callback = function()
305      vim.cmd([[
306        silent! syntax clear healthLspCurBuf
307        syntax match healthLspCurBuf /\d\+ (current buffer[^)]*)/
308        highlight default link healthLspCurBuf Visual
309      ]])
310    end,
311  })
312end
313
314return M