robin/laufey

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

robinmerge: 1dc9728daa1d8a2702

master
4.4 KiB159 linesraw
1local M = {}
2local min_version = '3.9'
3local s_err ---@type string?
4local s_host ---@type integer?
5
6local python_candidates = {
7  'python3',
8  'python3.14',
9  'python3.13',
10  'python3.12',
11  'python3.11',
12  'python3.10',
13  'python3.9',
14  'python',
15}
16
17--- @param prog string
18--- @param module string
19--- @return integer, string
20local function import_module(prog, module)
21  local program = [[
22import sys, importlib.util;
23sys.path = [p for p in sys.path if p != ""];
24sys.stdout.write(str(sys.version_info[0]) + "." + str(sys.version_info[1]));]]
25
26  program = program
27    .. string.format('sys.exit(2 * int(importlib.util.find_spec("%s") is None))', module)
28
29  local out = vim.system({ prog, '-W', 'ignore', '-c', program }):wait()
30  return out.code, assert(out.stdout)
31end
32
33--- @param prog string
34--- @param module string
35--- @return string?
36local function check_for_module(prog, module)
37  local prog_path = vim.fn.exepath(prog)
38  if prog_path == '' then
39    return prog .. ' not found in search path or not executable.'
40  end
41
42  --   Try to load module, and output Python version.
43  --   Exit codes:
44  --     0  module can be loaded.
45  --     2  module cannot be loaded.
46  --     Otherwise something else went wrong (e.g. 1 or 127).
47  local prog_exitcode, prog_version = import_module(prog, module)
48  if prog_exitcode == 2 or prog_exitcode == 0 then
49    -- Check version only for expected return codes.
50    if vim.version.lt(prog_version, min_version) then
51      return string.format(
52        '%s is Python %s and cannot provide Python >= %s.',
53        prog_path,
54        prog_version,
55        min_version
56      )
57    end
58  end
59
60  if prog_exitcode == 2 then
61    return string.format('%s does not have the "%s" module.', prog_path, module)
62  elseif prog_exitcode == 127 then
63    -- This can happen with pyenv's shims.
64    return string.format('%s does not exist: %s', prog_path, prog_version)
65  elseif prog_exitcode ~= 0 then
66    return string.format(
67      'Checking %s caused an unknown error. (%s, output: %s) Report this at https://github.com/neovim/neovim',
68      prog_path,
69      prog_exitcode,
70      prog_version
71    )
72  end
73
74  return nil
75end
76
77--- @param module string
78--- @return string? path to detected python, if any; nil if not found
79--- @return string? error message if python can't be detected by {module}; nil if success
80function M.detect_by_module(module)
81  local python_exe = vim.fn.expand(vim.g.python3_host_prog or '', true)
82
83  if python_exe ~= '' then
84    return vim.fn.exepath(vim.fn.expand(python_exe, true)), nil
85  end
86
87  if vim.fn.executable('pynvim-python') == 1 then
88    return 'pynvim-python'
89  end
90
91  local errors = {}
92  for _, exe in ipairs(python_candidates) do
93    local error = check_for_module(exe, module)
94    if not error then
95      return exe, error
96    end
97    -- Accumulate errors in case we don't find any suitable Python executable.
98    table.insert(errors, error)
99  end
100
101  -- No suitable Python executable found.
102  return nil, 'Could not load Python :\n' .. table.concat(errors, '\n')
103end
104
105--- @param host { name: string, orig_name: string }
106--- @return integer
107function M.require(host)
108  -- Python host arguments
109  local prog = M.detect_by_module('neovim')
110  local args = {
111    prog,
112    '-c',
113    'import sys; sys.path = [p for p in sys.path if p != ""]; import neovim; neovim.start_host()',
114  }
115
116  -- Collect registered Python plugins into args
117  local python_plugins = vim.fn['remote#host#PluginsForHost'](host.name) ---@type any
118  ---@param plugin any
119  for _, plugin in ipairs(python_plugins) do
120    table.insert(args, plugin.path)
121  end
122
123  return vim.fn['provider#Poll'](
124    args,
125    host.orig_name,
126    '$NVIM_PYTHON_LOG_FILE',
127    { ['overlapped'] = true }
128  )
129end
130
131--- @param method string
132--- @param args any[]
133function M.call(method, args)
134  if s_err then
135    return
136  end
137
138  if not s_host then
139    -- Ensure that we can load the Python3 host before bootstrapping
140    local ok, result = pcall(vim.fn['remote#host#Require'], 'legacy-python3-provider') ---@type any, any
141    if not ok then
142      s_err = result
143      vim.api.nvim_echo({ { result, 'WarningMsg' } }, true)
144      return
145    end
146    --- @cast result integer
147    s_host = result
148  end
149
150  return vim.fn.rpcrequest(s_host, 'python_' .. method, unpack(args))
151end
152
153function M.start()
154  -- The Python3 provider plugin will run in a separate instance of the Python3 host.
155  vim.fn['remote#host#RegisterClone']('legacy-python3-provider', 'python3')
156  vim.fn['remote#host#RegisterPlugin']('legacy-python3-provider', 'script_host.py', {})
157end
158
159return M