robin/laufey

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

robinmerge: 1dc9728daa1d8a2702

master
30.8 KiB969 linesraw
1local health = vim.health
2local iswin = vim.fn.has('win32') == 1
3
4local M = {}
5
6---@param cmd string[]
7---@return boolean
8---@return string
9local function cmd_ok(cmd)
10  local result = vim.system(cmd, { text = true }):wait()
11  return result.code == 0, assert(result.stdout)
12end
13
14---@param cmd string[]
15local function cli_version(cmd)
16  local ok, out = cmd_ok(cmd)
17  return ok, vim.version.parse(out, { strict = false })
18end
19
20-- Attempts to construct a shell command from an args list.
21-- Only for display, to help users debug a failed command.
22--- @param cmd string|string[]
23local function shellify(cmd)
24  if type(cmd) ~= 'table' then
25    return cmd
26  end
27  local escaped = {} --- @type string[]
28  for i, v in ipairs(cmd) do
29    escaped[i] = v:match('[^A-Za-z_/.-]') and vim.fn.shellescape(v) or v
30  end
31  return table.concat(escaped, ' ')
32end
33
34-- Handler for s:system() function.
35--- @param self {output: string, stderr: string, add_stderr_to_output: boolean}
36--- @param data string[]
37--- @param event 'stdout'|'stderr'
38local function system_handler(self, _, data, event)
39  if event == 'stderr' then
40    if self.add_stderr_to_output then
41      self.output = self.output .. table.concat(data, '')
42    else
43      self.stderr = self.stderr .. table.concat(data, '')
44    end
45  elseif event == 'stdout' then
46    self.output = self.output .. table.concat(data, '')
47  end
48end
49
50--- @param cmd string|string[] List of command arguments to execute
51--- @param args? table Optional arguments:
52---                   - stdin (string): Data to write to the job's stdin
53---                   - stderr (boolean): Append stderr to stdout
54---                   - ignore_error (boolean): If true, ignore error output
55---                   - timeout (number): Number of seconds to wait before timing out (default 30)
56local function system(cmd, args)
57  args = args or {}
58  local stdin = args.stdin or ''
59  local stderr = args.stderr or false
60  local ignore_error = args.ignore_error or false
61
62  local shell_error_code = 0
63  local opts = {
64    add_stderr_to_output = stderr,
65    output = '',
66    stderr = '',
67    on_stdout = system_handler,
68    on_stderr = system_handler,
69    on_exit = function(_, data)
70      shell_error_code = data
71    end,
72  }
73  local jobid = vim.fn.jobstart(cmd, opts)
74
75  if jobid < 1 then
76    local message =
77      string.format('Command error (job=%d): %s (in %s)', jobid, shellify(cmd), vim.uv.cwd())
78    error(message)
79    return opts.output, 1
80  end
81
82  if stdin:find('^%s$') then
83    vim.fn.chansend(jobid, stdin)
84  end
85
86  local res = vim.fn.jobwait({ jobid }, math.floor(vim.nonnil(args.timeout, 30) * 1000))
87  if res[1] == -1 then
88    error('Command timed out: ' .. shellify(cmd))
89    vim.fn.jobstop(jobid)
90  elseif shell_error_code ~= 0 and not ignore_error then
91    local emsg = string.format(
92      'Command error (job=%d, exit code %d): %s (in %s)',
93      jobid,
94      shell_error_code,
95      shellify(cmd),
96      vim.uv.cwd()
97    )
98    if opts.output:find('%S') then
99      emsg = string.format('%s\noutput: %s', emsg, opts.output)
100    end
101    if opts.stderr:find('%S') then
102      emsg = string.format('%s\nstderr: %s', emsg, opts.stderr)
103    end
104    error(emsg)
105  end
106
107  return vim.trim(vim.fn.system(cmd)), shell_error_code
108end
109
110---@param provider string
111local function provider_disabled(provider)
112  local loaded_var = 'loaded_' .. provider .. '_provider'
113  local v = vim.g[loaded_var]
114  if v == 0 then
115    health.info('Disabled (' .. loaded_var .. '=' .. v .. ').')
116    return true
117  end
118  return false
119end
120
121--- Checks the hygiene of a `g:loaded_xx_provider` variable.
122--- @param var string
123local function check_loaded_var(var)
124  if vim.g[var] == 1 then
125    health.error(('`g:%s=1` may have been set by mistake.'):format(var), {
126      ('Remove `vim.g.%s=1` from your config.'):format(var),
127      'To disable the provider, set this to 0, not 1.',
128      'If you want to enable the provider but skip automatic detection, set the respective `g:…_host_prog` var. See :help provider',
129    })
130  end
131end
132
133local function clipboard()
134  health.start('Clipboard (optional)')
135
136  check_loaded_var('loaded_clipboard_provider')
137
138  if
139    os.getenv('TMUX')
140    and vim.fn.executable('tmux') == 1
141    and vim.fn.executable('pbpaste') == 1
142    and not cmd_ok({ 'pbpaste' })
143  then
144    local _, tmux_version = cli_version({ 'tmux', '-V' })
145    local advice = {
146      'Install tmux 2.6+.  https://superuser.com/q/231130',
147      'or use tmux with reattach-to-user-namespace.  https://superuser.com/a/413233',
148    }
149    health.error('pbcopy does not work with tmux version: ' .. tostring(tmux_version), advice)
150  end
151
152  local clipboard_tool = vim.fn['provider#clipboard#Executable']() ---@type string
153  if vim.g.clipboard ~= nil and clipboard_tool == '' then
154    local error_message = vim.fn['provider#clipboard#Error']() ---@type string
155    health.error(
156      error_message,
157      "Use the example in :help g:clipboard as a template, or don't set g:clipboard at all."
158    )
159  elseif clipboard_tool:find('^%s*$') then
160    health.warn(
161      'No clipboard tool found. Clipboard registers (`"+` and `"*`) will not work.',
162      ':help clipboard'
163    )
164  else
165    health.ok('Clipboard tool found: ' .. clipboard_tool)
166  end
167end
168
169local function node()
170  health.start('Node.js provider (optional)')
171
172  check_loaded_var('loaded_node_provider')
173
174  if provider_disabled('node') then
175    return
176  end
177
178  if
179    vim.fn.executable('node') == 0
180    or (
181      vim.fn.executable('npm') == 0
182      and vim.fn.executable('yarn') == 0
183      and vim.fn.executable('pnpm') == 0
184      and vim.fn.executable('bun') == 0
185    )
186  then
187    health.warn(
188      '`node` and `npm` (or `yarn`, `pnpm`, `bun`) must be in $PATH.',
189      'Install Node.js and verify that `node` and `npm` (or `yarn`, `pnpm`, `bun`) commands work.'
190    )
191    return
192  end
193
194  local ok, node_v = cli_version({ 'node', '-v' })
195  health.info('Node.js: ' .. tostring(node_v))
196  if not ok or vim.version.lt(assert(node_v), '6.0.0') then
197    health.warn('Nvim node.js host does not support Node ' .. node_v)
198    -- Skip further checks, they are nonsense if nodejs is too old.
199    return
200  end
201  if vim.fn['provider#node#can_inspect']() == 0 then
202    health.warn(
203      'node.js on this system does not support --inspect-brk so $NVIM_NODE_HOST_DEBUG is ignored.'
204    )
205  end
206
207  local node_detect_table = vim.fn['provider#node#Detect']() ---@type [string, string]
208  local host = node_detect_table[1]
209  if host:find('^%s*$') then
210    health.warn('Missing "neovim" npm (or yarn, pnpm, bun) package.', {
211      'Run in shell: npm install -g neovim',
212      'Run in shell (if you use yarn): yarn global add neovim',
213      'Run in shell (if you use pnpm): pnpm install -g neovim',
214      'Run in shell (if you use bun): bun install -g neovim',
215      'You may disable this provider (and warning) by adding `let g:loaded_node_provider = 0` to your init.vim',
216    })
217    return
218  end
219  health.info('Nvim node.js host: ' .. host)
220
221  -- only npm/pnpm query the registry here: `yarn info` errors outside a
222  -- project on yarn 2+ (#20924), and bun isn't used for this check.
223  local manager --- @type string?
224  if vim.fn.executable('npm') == 1 then
225    manager = 'npm'
226  elseif vim.fn.executable('pnpm') == 1 then
227    manager = 'pnpm'
228  end
229
230  if not manager then
231    health.info('Skipping latest "neovim" package check: npm or pnpm not in $PATH.')
232    return
233  end
234
235  local latest_npm_cmd = { manager, 'info', 'neovim', '--json' }
236  local latest_npm
237  ok, latest_npm = cmd_ok(latest_npm_cmd)
238  if not ok or latest_npm:find('^%s$') then
239    health.error(
240      'Failed to run: ' .. shellify(latest_npm_cmd),
241      { "Make sure you're connected to the internet.", 'Are you behind a firewall or proxy?' }
242    )
243    return
244  end
245
246  local pcall_ok, pkg_data = pcall(vim.json.decode, latest_npm)
247  if not pcall_ok then
248    return 'error: ' .. latest_npm
249  end
250  local latest_npm_subtable = pkg_data['dist-tags'] or {}
251  latest_npm = latest_npm_subtable['latest'] or 'unable to parse'
252
253  local current_npm_cmd = { 'node', host, '--version' }
254  local current_npm
255  ok, current_npm = cmd_ok(current_npm_cmd)
256  if not ok then
257    health.error(
258      'Failed to run: ' .. shellify(current_npm_cmd),
259      { 'Report this issue with the output of: ', shellify(current_npm_cmd) }
260    )
261    return
262  end
263
264  if latest_npm ~= 'unable to parse' and vim.version.lt(current_npm, latest_npm) then
265    local message = 'Package "neovim" is out-of-date. Installed: '
266      .. current_npm:gsub('%\n$', '')
267      .. ', latest: '
268      .. latest_npm:gsub('%\n$', '')
269
270    health.warn(message, {
271      'Run in shell: npm install -g neovim',
272      'Run in shell (if you use yarn): yarn global add neovim',
273      'Run in shell (if you use pnpm): pnpm install -g neovim',
274      'Run in shell (if you use bun): bun install -g neovim',
275    })
276  else
277    health.ok('Latest "neovim" npm/yarn/pnpm/bun package is installed: ' .. current_npm)
278  end
279end
280
281local function perl()
282  health.start('Perl provider (optional)')
283
284  check_loaded_var('loaded_perl_provider')
285
286  if provider_disabled('perl') then
287    return
288  end
289
290  local perl_exec, perl_warnings = vim.provider.perl.detect()
291
292  if not perl_exec then
293    health.warn(assert(perl_warnings), {
294      'See :help provider-perl for more information.',
295      'You can disable this provider (and warning) by adding `let g:loaded_perl_provider = 0` to your init.vim',
296    })
297    health.warn('No usable perl executable found')
298    return
299  end
300
301  health.info('perl executable: ' .. perl_exec)
302
303  -- we cannot use cpanm that is on the path, as it may not be for the perl
304  -- set with g:perl_host_prog
305  local ok = cmd_ok({ perl_exec, '-W', '-MApp::cpanminus', '-e', '' })
306  if not ok then
307    return { perl_exec, '"App::cpanminus" module is not installed' }
308  end
309
310  local latest_cpan_cmd = {
311    perl_exec,
312    '-MApp::cpanminus::fatscript',
313    '-e',
314    'my $app = App::cpanminus::script->new; $app->parse_options ("--info", "-q", "Neovim::Ext"); exit $app->doit',
315  }
316  local latest_cpan
317  ok, latest_cpan = cmd_ok(latest_cpan_cmd)
318  if not ok or latest_cpan:find('^%s*$') then
319    health.error(
320      'Failed to run: ' .. shellify(latest_cpan_cmd),
321      { "Make sure you're connected to the internet.", 'Are you behind a firewall or proxy?' }
322    )
323    return
324  elseif latest_cpan[1] == '!' then
325    local cpanm_errs = vim.split(latest_cpan, '!')
326    if assert(cpanm_errs[1]):find("Can't write to ") then
327      local advice = {} ---@type string[]
328      for i = 2, #cpanm_errs do
329        advice[#advice + 1] = cpanm_errs[i]
330      end
331
332      health.warn(assert(cpanm_errs[1]), advice)
333      -- Last line is the package info
334      latest_cpan = cpanm_errs[#cpanm_errs]
335    else
336      health.error('Unknown warning from command: ' .. latest_cpan_cmd, cpanm_errs)
337      return
338    end
339  end
340  latest_cpan = tostring(vim.fn.matchstr(latest_cpan, [[\(\.\?\d\)\+]]))
341  if latest_cpan:find('^%s*$') then
342    health.error('Cannot parse version number from cpanm output: ' .. latest_cpan)
343    return
344  end
345
346  local current_cpan_cmd = { perl_exec, '-W', '-MNeovim::Ext', '-e', 'print $Neovim::Ext::VERSION' }
347  local current_cpan
348  ok, current_cpan = cmd_ok(current_cpan_cmd)
349  if not ok then
350    health.error(
351      'Failed to run: ' .. shellify(current_cpan_cmd),
352      { 'Report this issue with the output of: ', shellify(current_cpan_cmd) }
353    )
354    return
355  end
356
357  if vim.version.lt(current_cpan, latest_cpan) then
358    local message = 'Module "Neovim::Ext" is out-of-date. Installed: '
359      .. current_cpan
360      .. ', latest: '
361      .. latest_cpan
362    health.warn(message, 'Run in shell: cpanm -n Neovim::Ext')
363  else
364    health.ok('Latest "Neovim::Ext" cpan module is installed: ' .. current_cpan)
365  end
366end
367
368--- @param path string?
369--- @param ty string
370local function is(path, ty)
371  if not path then
372    return false
373  end
374  local stat = vim.uv.fs_stat(path)
375  if not stat then
376    return false
377  end
378  return stat.type == ty
379end
380
381-- Resolves Python executable path by invoking and checking `sys.executable`.
382--- @param invocation string?
383local function python_exepath(invocation)
384  if invocation == '' or invocation == nil then
385    return nil
386  end
387  local p = vim.system({ invocation, '-c', 'import sys; sys.stdout.write(sys.executable)' }):wait()
388  if p.code ~= 0 then
389    health.warn(assert(p.stderr))
390    return nil
391  end
392  return vim.fs.normalize(vim.trim(assert(p.stdout)))
393end
394
395--- Check if pyenv is available and a valid pyenv root can be found, then return
396--- their respective paths. If either of those is invalid, return two empty
397--- strings, effectively ignoring pyenv.
398---
399--- @return [string, string]
400local function check_for_pyenv()
401  local pyenv_path = vim.fn.resolve(vim.fn.exepath('pyenv'))
402
403  if pyenv_path == '' then
404    return { '', '' }
405  end
406
407  health.info('pyenv: Path: ' .. pyenv_path)
408
409  local pyenv_root = vim.fn.resolve(os.getenv('PYENV_ROOT') or '')
410
411  if pyenv_root == '' then
412    local p = vim.system({ pyenv_path, 'root' }):wait()
413    if p.code ~= 0 then
414      local message = string.format(
415        'pyenv: Failed to infer the root of pyenv by running `%s root` : %s. Ignoring pyenv for all following checks.',
416        pyenv_path,
417        p.stderr
418      )
419      health.warn(message)
420      return { '', '' }
421    end
422    pyenv_root = vim.trim(assert(p.stdout))
423    health.info('pyenv: $PYENV_ROOT is not set. Infer from `pyenv root`.')
424  end
425
426  if not is(pyenv_root, 'directory') then
427    local message = string.format(
428      'pyenv: Root does not exist: %s. Ignoring pyenv for all following checks.',
429      pyenv_root
430    )
431    health.warn(message)
432    return { '', '' }
433  end
434
435  health.info('pyenv: Root: ' .. pyenv_root)
436
437  return { pyenv_path, pyenv_root }
438end
439
440-- Check the Python interpreter's usability.
441--- @param bin string
442local function check_bin(bin)
443  if not is(bin, 'file') and (not iswin or not is(bin .. '.exe', 'file')) then
444    health.error('"' .. bin .. '" was not found.')
445    return false
446  elseif vim.fn.executable(bin) == 0 then
447    health.error('"' .. bin .. '" is not executable.')
448    return false
449  end
450  return true
451end
452
453--- Fetch the contents of a URL.
454---
455--- @param url string
456local function download(url)
457  local has_curl = vim.fn.executable('curl') == 1
458  if has_curl then
459    local ok, out = cmd_ok({ 'curl', '-V' })
460    if ok and out:find('Protocols:.*https') then
461      local content, rc = system({ 'curl', '-sL', url }, { stderr = true, ignore_error = true })
462      if rc ~= 0 then
463        return 'curl error with ' .. url .. ': ' .. rc
464      else
465        return content
466      end
467    end
468  elseif vim.fn.executable('python') == 1 then
469    local script = ([[
470try:
471    from urllib.request import urlopen
472except ImportError:
473    from urllib2 import urlopen
474
475response = urlopen('%s')
476print(response.read().decode('utf8'))
477]]):format(url)
478    local out, rc = system({ 'python', '-c', script })
479    if out == '' and rc ~= 0 then
480      return 'python urllib.request error: ' .. rc
481    else
482      return out
483    end
484  end
485
486  local message = 'missing `curl` '
487
488  if has_curl then
489    message = message .. '(with HTTPS support) '
490  end
491  message = message .. 'and `python`, cannot make web request'
492
493  return message
494end
495
496--- Get the latest Nvim Python client (pynvim) version from PyPI.
497local function latest_pypi_version()
498  local pypi_version = 'unable to get pypi response'
499  local pypi_response = download('https://pypi.org/pypi/pynvim/json')
500  if pypi_response ~= '' then
501    local pcall_ok, output = pcall(vim.fn.json_decode, pypi_response)
502    if not pcall_ok then
503      return 'error: ' .. pypi_response
504    end
505
506    local pypi_data = output
507    local pypi_element = pypi_data['info'] or {}
508    pypi_version = pypi_element['version'] or 'unable to parse'
509  end
510  return pypi_version
511end
512
513--- @param s string
514local function is_bad_response(s)
515  local lower = s:lower()
516  return vim.startswith(lower, 'unable')
517    or vim.startswith(lower, 'error')
518    or vim.startswith(lower, 'outdated')
519end
520
521--- Get version information using the specified interpreter.  The interpreter is
522--- used directly in case breaking changes were introduced since the last time
523--- Nvim's Python client was updated.
524---
525--- @param python string
526---
527--- Returns: {
528---     {python executable version},
529---     {current nvim version},
530---     {current pypi nvim status},
531---     {installed version status}
532--- }
533local function version_info(python)
534  local pypi_version = latest_pypi_version()
535
536  local python_version, rc = system({
537    python,
538    '-c',
539    'import sys; print(".".join(str(x) for x in sys.version_info[:3]))',
540  })
541
542  if rc ~= 0 or python_version == '' then
543    python_version = 'unable to parse ' .. python .. ' response'
544  end
545
546  local nvim_path
547  nvim_path, rc = system({
548    python,
549    '-c',
550    'import sys; sys.path = [p for p in sys.path if p != ""]; import neovim; print(neovim.__file__)',
551  })
552  if rc ~= 0 or nvim_path == '' then
553    return { python_version, 'unable to load neovim Python module', pypi_version, nvim_path }
554  end
555
556  -- Assuming that multiple versions of a package are installed as
557  -- `<semver>/<metapath>`, sort them on semantic version in descending order.
558  --- @param metapath1 string
559  --- @param metapath2 string
560  local function compare(metapath1, metapath2)
561    local dir1 = vim.fs.basename(vim.fs.dirname(vim.fs.abspath(metapath1)))
562    local dir2 = vim.fs.basename(vim.fs.dirname(vim.fs.abspath(metapath2)))
563    return vim.version.gt(dir1, dir2)
564  end
565
566  -- Try to get neovim.VERSION (added in 0.1.11dev).
567  local nvim_version
568  nvim_version, rc = system({
569    python,
570    '-c',
571    'from neovim import VERSION as v; print("{}.{}.{}{}".format(v.major, v.minor, v.patch, v.prerelease))',
572  }, { stderr = true, ignore_error = true })
573  if rc ~= 0 or nvim_version == '' then
574    nvim_version = 'unable to find pynvim module version'
575    local base = vim.fs.dirname(nvim_path)
576    local metas = vim.fn.glob(base .. '-*/METADATA', true, true)
577    vim.list_extend(metas, vim.fn.glob(base .. '-*/PKG-INFO', true, true))
578    vim.list_extend(metas, vim.fn.glob(base .. '.egg-info/PKG-INFO', true, true))
579    table.sort(metas, compare)
580
581    if metas and next(metas) ~= nil then
582      for line in io.lines(metas[1]) do
583        --- @cast line string
584        local version = line:match('^Version: (%S+)')
585        if version then
586          nvim_version = version
587          break
588        end
589      end
590    end
591  end
592
593  -- vim.fs.relpath does not prepend '~/' while fnamemodify does
594  local nvim_path_base = vim.fn.fnamemodify(nvim_path, [[:~:h]])
595  local version_status = 'unknown; ' .. nvim_path_base
596  if not is_bad_response(nvim_version) and not is_bad_response(pypi_version) then
597    if vim.version.lt(nvim_version, pypi_version) then
598      version_status = 'outdated; from ' .. nvim_path_base
599    else
600      version_status = 'up to date'
601    end
602  end
603
604  return { python_version, nvim_version, pypi_version, version_status }
605end
606
607local function python()
608  health.start('Python 3 provider (optional)')
609
610  check_loaded_var('loaded_python3_provider')
611
612  local python_exe = ''
613  local virtual_env = os.getenv('VIRTUAL_ENV')
614  local venv = virtual_env and vim.fn.resolve(virtual_env) or ''
615  local host_prog_var = 'python3_host_prog'
616  local python_multiple = {} ---@type string[]
617
618  if provider_disabled('python3') then
619    return
620  end
621
622  local pyenv_table = check_for_pyenv()
623  local pyenv = pyenv_table[1]
624  local pyenv_root = pyenv_table[2]
625
626  if vim.g[host_prog_var] then
627    local message = string.format('Using: g:%s = "%s"', host_prog_var, vim.g[host_prog_var])
628    health.info(message)
629  end
630
631  local pyname, pythonx_warnings = vim.provider.python.detect_by_module('neovim')
632
633  if not pyname then
634    health.warn(
635      'No Python executable found that can `import neovim`. '
636        .. 'Using the first available executable for diagnostics.'
637    )
638  elseif vim.g[host_prog_var] then
639    python_exe = pyname
640  end
641
642  -- No Python executable could `import neovim`, or host_prog_var was used.
643  if pythonx_warnings then
644    health.warn(pythonx_warnings, {
645      'See :help provider-python for more information.',
646      'You can disable this provider (and warning) by adding `let g:loaded_python3_provider = 0` to your init.vim',
647    })
648  elseif pyname and pyname ~= '' and python_exe == '' then
649    if not vim.g[host_prog_var] then
650      local message = string.format(
651        '`g:%s` is not set. Searching for %s in the environment.',
652        host_prog_var,
653        pyname
654      )
655      health.info(message)
656    end
657
658    if pyenv ~= '' then
659      python_exe = system({ pyenv, 'which', pyname }, { stderr = true })
660      if python_exe == '' then
661        health.warn('pyenv could not find ' .. pyname .. '.')
662      end
663    end
664
665    if python_exe == '' then
666      python_exe = vim.fn.exepath(pyname)
667
668      if os.getenv('PATH') then
669        local path_sep = iswin and ';' or ':'
670        local paths = vim.split(os.getenv('PATH') or '', path_sep)
671
672        for _, path in ipairs(paths) do
673          local path_bin = vim.fs.normalize(path .. '/' .. pyname)
674          if
675            path_bin ~= vim.fs.normalize(python_exe)
676            and vim.tbl_contains(python_multiple, path_bin)
677            and vim.fn.executable(path_bin) == 1
678          then
679            python_multiple[#python_multiple + 1] = path_bin
680          end
681        end
682
683        if vim.tbl_count(python_multiple) > 0 then
684          -- This is worth noting since the user may install something
685          -- that changes $PATH, like homebrew.
686          local message = string.format(
687            'Multiple %s executables found. Set `g:%s` to avoid surprises.',
688            pyname,
689            host_prog_var
690          )
691          health.info(message)
692        end
693
694        if python_exe:find('shims') then
695          local message = string.format('`%s` appears to be a pyenv shim.', python_exe)
696          local advice = string.format(
697            '`pyenv` is not in $PATH, your pyenv installation is broken. Set `g:%s` to avoid surprises.',
698            host_prog_var
699          )
700          health.warn(message, advice)
701        end
702      end
703    end
704  end
705
706  if python_exe ~= '' and not vim.g[host_prog_var] then
707    if
708      venv == ''
709      and pyenv ~= ''
710      and pyenv_root ~= ''
711      and vim.startswith(vim.fn.resolve(python_exe), pyenv_root .. '/')
712    then
713      local advice = string.format(
714        'Create a virtualenv specifically for Nvim using pyenv, and set `g:%s`.  This will avoid the need to install the pynvim module in each version/virtualenv.',
715        host_prog_var
716      )
717      health.warn('pyenv is not set up optimally.', advice)
718    elseif venv ~= '' then
719      local venv_root = pyenv_root ~= '' and pyenv_root or vim.fs.dirname(venv)
720
721      if vim.startswith(vim.fn.resolve(python_exe), venv_root .. '/') then
722        local advice = string.format(
723          'Create a virtualenv specifically for Nvim and use `g:%s`.  This will avoid the need to install the pynvim module in each virtualenv.',
724          host_prog_var
725        )
726        health.warn('Your virtualenv is not set up optimally.', advice)
727      end
728    end
729  end
730
731  if pyname and python_exe == '' and pyname ~= '' then
732    -- An error message should have already printed.
733    health.error('`' .. pyname .. '` was not found.')
734  elseif python_exe ~= '' and not check_bin(python_exe) then
735    python_exe = ''
736  end
737
738  -- Diagnostic output
739  health.info('Executable: ' .. (python_exe == '' and 'Not found' or python_exe))
740  if vim.tbl_count(python_multiple) > 0 then
741    for _, path_bin in ipairs(python_multiple) do
742      health.info('Other python executable: ' .. path_bin)
743    end
744  end
745
746  if python_exe == '' then
747    -- No Python executable can import 'neovim'. Check if any Python executable
748    -- can import 'pynvim'. If so, that Python failed to import 'neovim' as
749    -- well, which is most probably due to a failed pip upgrade:
750    -- https://github.com/neovim/neovim/wiki/Following-HEAD#20181118
751    local pynvim_exe = vim.provider.python.detect_by_module('pynvim')
752    if pynvim_exe then
753      local message = 'Detected pip upgrade failure: Python executable can import "pynvim" but not "neovim": '
754        .. pynvim_exe
755      local advice = {
756        'Use that Python version to uninstall any "pynvim" or "neovim", e.g.:',
757        pynvim_exe .. ' -m pip uninstall pynvim neovim',
758        'Then see :help provider-python for "pynvim" installation steps.',
759      }
760      health.error(message, advice)
761    end
762  else
763    local version_info_table = version_info(python_exe)
764    local pyversion = version_info_table[1]
765    local current = version_info_table[2]
766    local latest = version_info_table[3]
767    local status = version_info_table[4]
768
769    if not assert(vim.version.range('~3')):has(pyversion) then
770      health.warn('Unexpected Python version. This could lead to confusing error messages.')
771    end
772
773    health.info('Python version: ' .. pyversion)
774
775    if is_bad_response(status) then
776      health.info('pynvim version: ' .. current .. ' (' .. status .. ')')
777    else
778      health.info('pynvim version: ' .. current)
779    end
780
781    if is_bad_response(current) then
782      health.error(
783        'pynvim is not installed.\nError: ' .. current,
784        'See :help provider-python for "pynvim" installation steps.'
785      )
786    end
787
788    if is_bad_response(latest) then
789      health.warn('Could not contact PyPI to get latest version.')
790      health.error('HTTP request failed: ' .. latest)
791    elseif is_bad_response(status) then
792      health.warn('Latest pynvim is NOT installed: ' .. latest)
793    elseif not is_bad_response(current) then
794      health.ok('Latest pynvim is installed.')
795    end
796  end
797
798  health.start('Python virtualenv')
799  if not virtual_env then
800    health.ok('no $VIRTUAL_ENV')
801    return
802  end
803  local errors = {} ---@type string[]
804  -- Keep hints as dict keys in order to discard duplicates.
805  local hints = {} ---@type table<string, boolean>
806  -- The virtualenv should contain some Python executables, and those
807  -- executables should be first both on Nvim's $PATH and the $PATH of
808  -- subshells launched from Nvim.
809  local bin_dir = iswin and 'Scripts' or 'bin'
810  local venv_bins = vim.fn.glob(string.format('%s/%s/python*', virtual_env, bin_dir), true, true)
811  --- @param v string
812  venv_bins = vim.tbl_filter(function(v)
813    -- XXX: Remove irrelevant executables found in bin/.
814    return not v:match('python.*%-config') and not v:match('python%-argcomplete')
815  end, venv_bins)
816  if vim.tbl_count(venv_bins) > 0 then
817    for _, venv_bin in pairs(venv_bins) do
818      venv_bin = vim.fs.normalize(venv_bin)
819      local py_bin_basename = vim.fs.basename(venv_bin)
820      local nvim_py_bin = python_exepath(vim.fn.exepath(py_bin_basename))
821      if nvim_py_bin then
822        local subshell_py_bin = python_exepath(py_bin_basename)
823        local bintable = {
824          ['nvim'] = {
825            ['path'] = nvim_py_bin,
826            ['hint'] = '$PATH ambiguities arise if the virtualenv is not '
827              .. 'properly activated prior to launching Nvim. Close Nvim, activate the virtualenv, '
828              .. 'check that invoking Python from the command line launches the correct one, '
829              .. 'then relaunch Nvim.',
830          },
831          ['subshell'] = {
832            ['path'] = subshell_py_bin,
833            ['hint'] = '$PATH ambiguities in subshells typically are '
834              .. 'caused by your shell config overriding the $PATH previously set by the '
835              .. 'virtualenv. Either prevent them from doing so, or use this workaround: '
836              .. 'https://vi.stackexchange.com/a/34996',
837          },
838        }
839        for bintype, bin in pairs(bintable) do
840          if not bin.path or vim.fn.resolve(venv_bin) ~= vim.fn.resolve(bin.path) then
841            local type_of_path = bintype == 'subshell' and '$PATH' or '$PATH in subshell'
842            errors[#errors + 1] = type_of_path
843              .. ' yields this '
844              .. py_bin_basename
845              .. ' executable: '
846              .. tostring(bin.path)
847            hints[bin['hint']] = true
848          end
849        end
850      end
851    end
852  else
853    errors[#errors + 1] = 'no Python executables found in the virtualenv '
854      .. bin_dir
855      .. ' directory.'
856  end
857
858  local msg = '$VIRTUAL_ENV is set to: ' .. virtual_env
859  if vim.tbl_count(errors) > 0 then
860    if vim.tbl_count(venv_bins) > 0 then
861      msg = string.format(
862        '%s\nAnd its %s directory contains: %s',
863        msg,
864        bin_dir,
865        table.concat(
866          --- @param v string
867          vim.tbl_map(function(v)
868            return vim.fs.basename(v)
869          end, venv_bins),
870          ', '
871        )
872      )
873    end
874    local conj = '\nBut '
875    local msgs = {} --- @type string[]
876    for _, err in ipairs(errors) do
877      msgs[#msgs + 1] = msg
878      msgs[#msgs + 1] = conj
879      msgs[#msgs + 1] = err
880      msgs[#msgs + 1] = '\n'
881      conj = '\nAnd '
882    end
883    msgs[#msgs + 1] = '\nSo invoking Python may lead to unexpected results.'
884    health.warn(table.concat(msgs), vim.tbl_keys(hints))
885  else
886    health.info(msg)
887    health.info(
888      'Python version: '
889        .. system('python -c "import platform, sys; sys.stdout.write(platform.python_version())"')
890    )
891    health.ok('$VIRTUAL_ENV provides :!python.')
892  end
893end
894
895local function ruby()
896  health.start('Ruby provider (optional)')
897
898  check_loaded_var('loaded_ruby_provider')
899
900  if provider_disabled('ruby') then
901    return
902  end
903
904  if vim.fn.executable('ruby') == 0 or vim.fn.executable('gem') == 0 then
905    health.warn(
906      '`ruby` and `gem` must be in $PATH.',
907      'Install Ruby and verify that `ruby` and `gem` commands work.'
908    )
909    return
910  end
911  local _, ruby_v = cli_version({ 'ruby', '-v' })
912  health.info('Ruby: ' .. tostring(ruby_v))
913
914  local host, _ = vim.provider.ruby.detect()
915  if (not host) or host:find('^%s*$') then
916    health.warn('`neovim-ruby-host` not found.', {
917      'Run `gem install neovim` to ensure the neovim RubyGem is installed.',
918      'Run `gem environment` to ensure the gem bin directory is in $PATH.',
919      'If you are using rvm/rbenv/chruby, try "rehashing".',
920      'See :help g:ruby_host_prog for non-standard gem installations.',
921      'You can disable this provider (and warning) by adding `let g:loaded_ruby_provider = 0` to your init.vim',
922    })
923    return
924  end
925  health.info('Host: ' .. host)
926
927  local latest_gem_cmd = { 'gem', 'list', '-ra', '^neovim$' }
928  local ok, latest_gem = cmd_ok(latest_gem_cmd)
929  if not ok or latest_gem:find('^%s*$') then
930    health.error(
931      'Failed to run: ' .. shellify(latest_gem_cmd),
932      { "Make sure you're connected to the internet.", 'Are you behind a firewall or proxy?' }
933    )
934    return
935  end
936  local gem_split = vim.split(latest_gem, [[neovim (\|, \|)$]])
937  latest_gem = gem_split[1] or 'not found'
938
939  local current_gem_cmd = { host, '--version' }
940  local current_gem
941  ok, current_gem = cmd_ok(current_gem_cmd)
942  if not ok then
943    health.error(
944      'Failed to run: ' .. shellify(current_gem_cmd),
945      { 'Report this issue with the output of: ', shellify(current_gem_cmd) }
946    )
947    return
948  end
949
950  if vim.version.lt(current_gem, latest_gem) then
951    local message = 'Gem "neovim" is out-of-date. Installed: '
952      .. current_gem
953      .. ', latest: '
954      .. latest_gem
955    health.warn(message, 'Run in shell: gem update neovim')
956  else
957    health.ok('Latest "neovim" gem is installed: ' .. current_gem)
958  end
959end
960
961function M.check()
962  clipboard()
963  node()
964  perl()
965  python()
966  ruby()
967end
968
969return M