aboutsummaryrefslogtreecommitdiff
path: root/runtime/lua/vim/provider/python/health.lua
blob: a5bd738063b78a8e3112f01e4355b49d343a1e7f (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
local health = vim.health
local iswin = vim.loop.os_uname().sysname == 'Windows_NT'

local M = {}

local function is(path, ty)
  if not path then
    return false
  end
  local stat = vim.loop.fs_stat(path)
  if not stat then
    return false
  end
  return stat.type == ty
end

-- Resolves Python executable path by invoking and checking `sys.executable`.
local function python_exepath(invocation)
  local p = vim.system({ invocation, '-c', 'import sys; sys.stdout.write(sys.executable)' }):wait()
  assert(p.code == 0, p.stderr)
  return vim.fs.normalize(vim.trim(p.stdout))
end

-- Check if pyenv is available and a valid pyenv root can be found, then return
-- their respective paths. If either of those is invalid, return two empty
-- strings, effectively ignoring pyenv.
local function check_for_pyenv()
  local pyenv_path = vim.fn.resolve(vim.fn.exepath('pyenv'))

  if pyenv_path == '' then
    return { '', '' }
  end

  health.info('pyenv: Path: ' .. pyenv_path)

  local pyenv_root = vim.fn.resolve(os.getenv('PYENV_ROOT') or '')

  if pyenv_root == '' then
    pyenv_root = vim.fn.system({ pyenv_path, 'root' })
    health.info('pyenv: $PYENV_ROOT is not set. Infer from `pyenv root`.')
  end

  if not is(pyenv_root, 'directory') then
    local message = string.format(
      'pyenv: Root does not exist: %s. Ignoring pyenv for all following checks.',
      pyenv_root
    )
    health.warn(message)
    return { '', '' }
  end

  health.info('pyenv: Root: ' .. pyenv_root)

  return { pyenv_path, pyenv_root }
end

-- Check the Python interpreter's usability.
local function check_bin(bin)
  if not is(bin, 'file') and (not iswin or not is(bin .. '.exe', 'file')) then
    health.error('"' .. bin .. '" was not found.')
    return false
  elseif vim.fn.executable(bin) == 0 then
    health.error('"' .. bin .. '" is not executable.')
    return false
  end
  return true
end

-- Fetch the contents of a URL.
local function download(url)
  local has_curl = vim.fn.executable('curl') == 1
  if has_curl and vim.fn.system({ 'curl', '-V' }):find('Protocols:.*https') then
    local out, rc = health.system({ 'curl', '-sL', url }, { stderr = true, ignore_error = true })
    if rc ~= 0 then
      return 'curl error with ' .. url .. ': ' .. rc
    else
      return out
    end
  elseif vim.fn.executable('python') == 1 then
    local script = "try:\n\
          from urllib.request import urlopen\n\
          except ImportError:\n\
          from urllib2 import urlopen\n\
          response = urlopen('" .. url .. "')\n\
          print(response.read().decode('utf8'))\n"
    local out, rc = health.system({ 'python', '-c', script })
    if out == '' and rc ~= 0 then
      return 'python urllib.request error: ' .. rc
    else
      return out
    end
  end

  local message = 'missing `curl` '

  if has_curl then
    message = message .. '(with HTTPS support) '
  end
  message = message .. 'and `python`, cannot make web request'

  return message
end

-- Get the latest Nvim Python client (pynvim) version from PyPI.
local function latest_pypi_version()
  local pypi_version = 'unable to get pypi response'
  local pypi_response = download('https://pypi.python.org/pypi/pynvim/json')
  if pypi_response ~= '' then
    local pcall_ok, output = pcall(vim.fn.json_decode, pypi_response)
    local pypi_data
    if pcall_ok then
      pypi_data = output
    else
      return 'error: ' .. pypi_response
    end

    local pypi_element = pypi_data['info'] or {}
    pypi_version = pypi_element['version'] or 'unable to parse'
  end
  return pypi_version
end

local function is_bad_response(s)
  local lower = s:lower()
  return vim.startswith(lower, 'unable')
    or vim.startswith(lower, 'error')
    or vim.startswith(lower, 'outdated')
end

-- Get version information using the specified interpreter.  The interpreter is
-- used directly in case breaking changes were introduced since the last time
-- Nvim's Python client was updated.
--
-- Returns: {
--     {python executable version},
--     {current nvim version},
--     {current pypi nvim status},
--     {installed version status}
-- }
local function version_info(python)
  local pypi_version = latest_pypi_version()

  local python_version, rc = health.system({
    python,
    '-c',
    'import sys; print(".".join(str(x) for x in sys.version_info[:3]))',
  })

  if rc ~= 0 or python_version == '' then
    python_version = 'unable to parse ' .. python .. ' response'
  end

  local nvim_path
  nvim_path, rc = health.system({
    python,
    '-c',
    'import sys; sys.path = [p for p in sys.path if p != ""]; import neovim; print(neovim.__file__)',
  })
  if rc ~= 0 or nvim_path == '' then
    return { python_version, 'unable to load neovim Python module', pypi_version, nvim_path }
  end

  -- Assuming that multiple versions of a package are installed, sort them
  -- numerically in descending order.
  local function compare(metapath1, metapath2)
    local a = vim.fn.matchstr(vim.fn.fnamemodify(metapath1, ':p:h:t'), [[[0-9.]\+]])
    local b = vim.fn.matchstr(vim.fn.fnamemodify(metapath2, ':p:h:t'), [[[0-9.]\+]])
    if a == b then
      return 0
    elseif a > b then
      return 1
    else
      return -1
    end
  end

  -- Try to get neovim.VERSION (added in 0.1.11dev).
  local nvim_version
  nvim_version, rc = health.system({
    python,
    '-c',
    'from neovim import VERSION as v; print("{}.{}.{}{}".format(v.major, v.minor, v.patch, v.prerelease))',
  }, { stderr = true, ignore_error = true })
  if rc ~= 0 or nvim_version == '' then
    nvim_version = 'unable to find pynvim module version'
    local base = vim.fs.basename(nvim_path)
    local metas = vim.fn.glob(base .. '-*/METADATA', 1, 1)
    vim.list_extend(metas, vim.fn.glob(base .. '-*/PKG-INFO', 1, 1))
    vim.list_extend(metas, vim.fn.glob(base .. '.egg-info/PKG-INFO', 1, 1))
    metas = table.sort(metas, compare)

    if metas and next(metas) ~= nil then
      for line in io.lines(metas[1]) do
        local version = line:match('^Version: (%S+)')
        if version then
          nvim_version = version
          break
        end
      end
    end
  end

  local nvim_path_base = vim.fn.fnamemodify(nvim_path, [[:~:h]])
  local version_status = 'unknown; ' .. nvim_path_base
  if is_bad_response(nvim_version) and is_bad_response(pypi_version) then
    if vim.version.lt(nvim_version, pypi_version) then
      version_status = 'outdated; from ' .. nvim_path_base
    else
      version_status = 'up to date'
    end
  end

  return { python_version, nvim_version, pypi_version, version_status }
end

function M.check()
  health.start('Python 3 provider (optional)')

  local pyname = 'python3' ---@type string?
  local python_exe = ''
  local virtual_env = os.getenv('VIRTUAL_ENV')
  local venv = virtual_env and vim.fn.resolve(virtual_env) or ''
  local host_prog_var = pyname .. '_host_prog'
  local python_multiple = {}

  if health.provider_disabled(pyname) then
    return
  end

  local pyenv_table = check_for_pyenv()
  local pyenv = pyenv_table[1]
  local pyenv_root = pyenv_table[2]

  if vim.g[host_prog_var] then
    local message = string.format('Using: g:%s = "%s"', host_prog_var, vim.g[host_prog_var])
    health.info(message)
  end

  local pythonx_warnings
  pyname, pythonx_warnings = vim.provider.python.detect_by_module('neovim')

  if not pyname then
    health.warn(
      'No Python executable found that can `import neovim`. '
        .. 'Using the first available executable for diagnostics.'
    )
  elseif vim.g[host_prog_var] then
    python_exe = pyname
  end

  -- No Python executable could `import neovim`, or host_prog_var was used.
  if pythonx_warnings then
    health.warn(pythonx_warnings, {
      'See :help provider-python for more information.',
      'You may disable this provider (and warning) by adding `let g:loaded_python3_provider = 0` to your init.vim',
    })
  elseif pyname and pyname ~= '' and python_exe == '' then
    if not vim.g[host_prog_var] then
      local message = string.format(
        '`g:%s` is not set. Searching for %s in the environment.',
        host_prog_var,
        pyname
      )
      health.info(message)
    end

    if pyenv ~= '' then
      python_exe = health.system({ pyenv, 'which', pyname }, { stderr = true })
      if python_exe == '' then
        health.warn('pyenv could not find ' .. pyname .. '.')
      end
    end

    if python_exe == '' then
      python_exe = vim.fn.exepath(pyname)

      if os.getenv('PATH') then
        local path_sep = iswin and ';' or ':'
        local paths = vim.split(os.getenv('PATH') or '', path_sep)

        for _, path in ipairs(paths) do
          local path_bin = vim.fs.normalize(path .. '/' .. pyname)
          if
            path_bin ~= vim.fs.normalize(python_exe)
            and vim.tbl_contains(python_multiple, path_bin)
            and vim.fn.executable(path_bin) == 1
          then
            python_multiple[#python_multiple + 1] = path_bin
          end
        end

        if vim.tbl_count(python_multiple) > 0 then
          -- This is worth noting since the user may install something
          -- that changes $PATH, like homebrew.
          local message = string.format(
            'Multiple %s executables found. Set `g:%s` to avoid surprises.',
            pyname,
            host_prog_var
          )
          health.info(message)
        end

        if python_exe:find('shims') then
          local message = string.format('`%s` appears to be a pyenv shim.', python_exe)
          local advice = string.format(
            '`pyenv` is not in $PATH, your pyenv installation is broken. Set `g:%s` to avoid surprises.',
            host_prog_var
          )
          health.warn(message, advice)
        end
      end
    end
  end

  if python_exe ~= '' and not vim.g[host_prog_var] then
    if
      venv == ''
      and pyenv ~= ''
      and pyenv_root ~= ''
      and vim.startswith(vim.fn.resolve(python_exe), pyenv_root .. '/')
    then
      local advice = string.format(
        '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.',
        host_prog_var
      )
      health.warn('pyenv is not set up optimally.', advice)
    elseif venv ~= '' then
      local venv_root
      if pyenv_root ~= '' then
        venv_root = pyenv_root
      else
        venv_root = vim.fs.dirname(venv)
      end

      if vim.startswith(vim.fn.resolve(python_exe), venv_root .. '/') then
        local advice = string.format(
          'Create a virtualenv specifically for Nvim and use `g:%s`.  This will avoid the need to install the pynvim module in each virtualenv.',
          host_prog_var
        )
        health.warn('Your virtualenv is not set up optimally.', advice)
      end
    end
  end

  if pyname and python_exe == '' and pyname ~= ''