health.lua 29 KB

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