health.lua 29 KB

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