robin/laufey

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

robinmerge: 1dc9728daa1d8a2702

master
15.1 KiB541 linesraw
1local uv = vim.uv
2
3--- @class vim.SystemOpts
4--- @inlinedoc
5---
6--- Set the current working directory for the sub-process.
7--- @field cwd? string
8---
9--- Set environment variables for the new process. Inherits the current environment with `NVIM` set
10--- to |v:servername|.
11--- @field env? table<string,string|number>
12---
13--- `env` defines the job environment exactly, instead of merging current environment. Note: if
14--- `env` is `nil`, the current environment is used but without `NVIM` set.
15--- @field clear_env? boolean
16---
17--- If `true`, then a pipe to stdin is opened and can be written to via the `write()` method to
18--- SystemObj. If `string` or `string[]` then will be written to stdin and closed.
19--- @field stdin? string|string[]|true
20---
21--- Handle output from stdout.
22--- (Default: `true`)
23--- @field stdout? fun(err:string?, data: string?)|boolean
24---
25--- Handle output from stderr.
26--- (Default: `true`)
27--- @field stderr? fun(err:string?, data: string?)|boolean
28---
29--- Handle stdout and stderr as text. Normalizes line endings by replacing `\r\n` with `\n`.
30--- @field text? boolean
31---
32--- Run the command with a time limit in ms. Upon timeout the process is sent the TERM signal (15)
33--- and the exit code is set to 124.
34--- @field timeout? integer
35---
36--- Spawn the child process in a detached state - this will make it a process group leader, and will
37--- effectively enable the child to keep running after the parent exits. Note that the child process
38--- will still keep the parent's event loop alive unless the parent process calls [uv.unref()] on
39--- the child's process handle.
40--- @field detach? boolean
41
42--- @class vim.SystemCompleted
43--- @field code integer
44--- @field signal integer
45--- @field stdout? string `nil` if stdout is disabled or has a custom handler.
46--- @field stderr? string `nil` if stderr is disabled or has a custom handler.
47
48--- @class (package) vim.SystemState
49--- @field cmd string[]
50--- @field handle? uv.uv_process_t
51--- @field timer?  uv.uv_timer_t
52--- @field pid? integer
53--- @field timeout? integer
54--- @field done? boolean|'timeout'
55--- @field stdin? uv.uv_stream_t
56--- @field stdout? uv.uv_stream_t
57--- @field stderr? uv.uv_stream_t
58--- @field stdout_data? string[]
59--- @field stderr_data? string[]
60--- @field result? vim.SystemCompleted
61
62--- @enum vim.SystemSig
63local SIG = {
64  HUP = 1, -- Hangup
65  INT = 2, -- Interrupt from keyboard
66  KILL = 9, -- Kill signal
67  TERM = 15, -- Termination signal
68  -- STOP = 17,19,23  -- Stop the process
69}
70
71---@param handle uv.uv_handle_t?
72local function close_handle(handle)
73  if handle and not handle:is_closing() then
74    handle:close()
75  end
76end
77
78--- @class vim.SystemObj
79--- @field cmd string[] Command name and args
80--- @field pid integer Process ID
81--- @field private _state vim.SystemState
82local SystemObj = {}
83
84--- @param state vim.SystemState
85--- @return vim.SystemObj
86local function new_systemobj(state)
87  return setmetatable({
88    cmd = state.cmd,
89    pid = state.pid,
90    _state = state,
91  }, { __index = SystemObj })
92end
93
94--- Sends a signal to the process.
95---
96--- The signal can be specified as an integer or as a string.
97---
98--- Example:
99--- ```lua
100--- local obj = vim.system({'sleep', '10'})
101--- obj:kill('sigterm') -- sends SIGTERM to the process
102--- ```
103---
104--- @param signal integer|string Signal to send to the process. See |luv-constants|.
105function SystemObj:kill(signal)
106  assert(self._state.handle):kill(signal)
107end
108
109--- @package
110--- @param signal? vim.SystemSig
111function SystemObj:_timeout(signal)
112  self._state.done = 'timeout'
113  self:kill(signal or SIG.TERM)
114end
115
116--- Waits for the process to complete or until the specified timeout elapses.
117---
118--- This method blocks execution until the associated process has exited or
119--- the optional `timeout` (in milliseconds) has been reached. If the process
120--- does not exit before the timeout, it is forcefully terminated with SIGKILL
121--- (signal 9), and the exit code is set to 124.
122---
123--- If no `timeout` is provided, the method will wait indefinitely (or use the
124--- timeout specified in the options when the process was started).
125---
126--- Example:
127--- ```lua
128--- local obj = vim.system({'echo', 'hello'}, { text = true })
129--- local result = obj:wait(1000) -- waits up to 1000ms
130--- print(result.code, result.signal, result.stdout, result.stderr)
131--- ```
132---
133--- @param timeout? integer
134--- @return vim.SystemCompleted
135function SystemObj:wait(timeout)
136  local state = self._state
137
138  local done = vim.wait(timeout or state.timeout or vim._maxint, function()
139    return state.result ~= nil
140  end, nil, true)
141
142  if not done then
143    -- Send sigkill since this cannot be caught
144    self:_timeout(SIG.KILL)
145    vim.wait(timeout or state.timeout or vim._maxint, function()
146      return state.result ~= nil
147    end, nil, true)
148  end
149
150  -- TODO: A short timeout can leave result nil even after sending SIGKILL.
151  ---@diagnostic disable-next-line: return-type-mismatch
152  return state.result
153end
154
155--- Writes data to the stdin of the process or closes stdin.
156---
157--- If `data` is a list of strings, each string is written followed by a
158--- newline.
159---
160--- If `data` is a string, it is written as-is.
161---
162--- If `data` is `nil`, the write side of the stream is shut down and the pipe
163--- is closed.
164---
165--- Example:
166--- ```lua
167--- local obj = vim.system({'cat'}, { stdin = true })
168--- obj:write({'hello', 'world'}) -- writes 'hello\nworld\n' to stdin
169--- obj:write(nil) -- closes stdin
170--- ```
171---
172--- @param data string[]|string|nil
173function SystemObj:write(data)
174  local stdin = self._state.stdin
175
176  if not stdin then
177    error('stdin has not been opened on this object')
178  end
179
180  if type(data) == 'table' then
181    for _, v in ipairs(data) do
182      stdin:write(v)
183      stdin:write('\n')
184    end
185  elseif type(data) == 'string' then
186    stdin:write(data)
187  elseif data == nil then
188    -- Shutdown the write side of the duplex stream and then close the pipe.
189    -- Note shutdown will wait for all the pending write requests to complete
190    -- TODO(lewis6991): apparently shutdown doesn't behave this way.
191    -- (https://github.com/neovim/neovim/pull/17620#discussion_r820775616)
192    stdin:write('', function()
193      stdin:shutdown(function()
194        close_handle(stdin)
195      end)
196    end)
197  end
198end
199
200--- Checks if the process handle is closing or already closed.
201---
202--- This method returns `true` if the underlying process handle is either
203--- `nil` or is in the process of closing. It is useful for determining
204--- whether it is safe to perform operations on the process handle.
205---
206--- @return boolean
207function SystemObj:is_closing()
208  local handle = self._state.handle
209  return handle == nil or handle:is_closing() or false
210end
211
212--- @param output? fun(err: string?, data: string?)|boolean
213--- @param text? boolean
214--- @return uv.uv_stream_t? pipe
215--- @return integer? child_fd
216--- @return fun(err: string?, data: string?)? handler
217--- @return string[]? data
218local function setup_output(output, text)
219  if output == false then
220    return
221  end
222
223  local bucket --- @type string[]?
224  local handler --- @type fun(err: string?, data: string?)
225
226  if type(output) == 'function' then
227    handler = output
228  else
229    bucket = {}
230    --- @param err string?
231    --- @param data string?
232    handler = function(err, data)
233      if err then
234        error(err)
235      end
236      if text and data then
237        bucket[#bucket + 1] = data:gsub('\r\n', '\n')
238      else
239        bucket[#bucket + 1] = data
240      end
241    end
242  end
243
244  --- @diagnostic disable-next-line:missing-fields,param-type-mismatch luvit/luv#827
245  local pipe_fd = assert(uv.pipe({ nonblock = true }, {}))
246  local pipe = assert(uv.new_pipe(false))
247  pipe:open(pipe_fd.read)
248
249  --- @param err? string
250  --- @param data? string
251  local function handler_with_close(err, data)
252    handler(err, data)
253    if data == nil then
254      pipe:read_stop()
255      pipe:close()
256    end
257  end
258
259  return pipe, pipe_fd.write, handler_with_close, bucket
260end
261
262--- @param input? string|string[]|boolean
263--- @return uv.uv_stream_t?
264--- @return integer? child_fd
265--- @return string|string[]?
266local function setup_input(input)
267  if not input then
268    return
269  end
270
271  local towrite --- @type string|string[]?
272  if type(input) == 'string' or type(input) == 'table' then
273    towrite = input
274  end
275
276  --- @diagnostic disable-next-line:missing-fields,param-type-mismatch luvit/luv#827
277  local pipe_fd = assert(uv.pipe({}, { nonblock = true }))
278  local pipe = assert(uv.new_pipe(false))
279  pipe:open(pipe_fd.write)
280
281  return pipe, pipe_fd.read, towrite
282end
283
284--- @return table<string,string>
285local function base_env()
286  local env = vim.fn.environ() --- @type table<string,string>
287  env['NVIM'] = vim.v.servername
288  env['NVIM_LISTEN_ADDRESS'] = nil
289  return env
290end
291
292--- uv.spawn will completely overwrite the environment
293--- when we just want to modify the existing one, so
294--- make sure to prepopulate it with the current env.
295--- @param env? table<string,string|number>
296--- @param clear_env? boolean
297--- @return string[]?
298local function setup_env(env, clear_env)
299  if not env and clear_env then
300    return
301  end
302
303  env = env or {}
304  if not clear_env then
305    --- @type table<string,string|number>
306    env = vim.tbl_extend('force', base_env(), env)
307  end
308
309  local renv = {} --- @type string[]
310  for k, v in pairs(env) do
311    renv[#renv + 1] = string.format('%s=%s', k, tostring(v))
312  end
313
314  return renv
315end
316
317local is_win = vim.fn.has('win32') == 1
318
319--- @class (private) vim.SystemSpawnOpts : uv.spawn.options
320--- @field stdio [integer?, integer?, integer?]
321
322--- @param cmd string
323--- @param opts vim.SystemSpawnOpts
324--- @param on_exit fun(code: integer, signal: integer)
325--- @param on_error fun()
326--- @return uv.uv_process_t, integer
327local function spawn(cmd, opts, on_exit, on_error)
328  if is_win then
329    local cmd1 = vim.fn.exepath(cmd)
330    if cmd1 ~= '' then
331      -- Use native separators when launching a resolved Windows executable.
332      cmd = cmd1:gsub('/', '\\')
333    end
334  end
335
336  local handle, pid_or_err = uv.spawn(cmd, opts, on_exit)
337  -- close child stdio fd:s regardless of error
338  for i = 1, 3 do
339    local fd = opts.stdio[i]
340    if fd then
341      uv.fs_close(fd)
342    end
343  end
344
345  if not handle then
346    on_error()
347    if opts.cwd and not uv.fs_stat(opts.cwd) then
348      error(("%s (cwd): '%s'"):format(pid_or_err, opts.cwd))
349    elseif vim.fn.executable(cmd) == 0 then
350      error(("%s (cmd): '%s'"):format(pid_or_err, cmd))
351    else
352      error(pid_or_err)
353    end
354  end
355  return handle, pid_or_err --[[@as integer]]
356end
357
358--- @param timeout integer
359--- @param cb fun()
360--- @return uv.uv_timer_t
361local function timer_oneshot(timeout, cb)
362  local timer = assert(uv.new_timer())
363  timer:start(timeout, 0, function()
364    timer:stop()
365    timer:close()
366    cb()
367  end)
368  return timer
369end
370
371--- @param state vim.SystemState
372--- @param code integer
373--- @param signal integer
374--- @param on_exit fun(result: vim.SystemCompleted)?
375local function _on_exit(state, code, signal, on_exit)
376  close_handle(state.handle)
377  close_handle(state.stdin)
378  close_handle(state.timer)
379
380  -- #30846: Do not close stdout/stderr here, as they may still have data to
381  -- read. They will be closed in uv.read_start on EOF.
382
383  local check = uv.new_check()
384  check:start(function()
385    for _, pipe in pairs({ state.stdin, state.stdout, state.stderr }) do
386      if not pipe:is_closing() then
387        return
388      end
389    end
390    check:stop()
391    check:close()
392
393    if state.done == nil then
394      state.done = true
395    end
396
397    if (code == 0 or code == 1) and state.done == 'timeout' then
398      -- Unix: code == 0
399      -- Windows: code == 1
400      code = 124
401    end
402
403    local stdout_data = state.stdout_data
404    local stderr_data = state.stderr_data
405
406    state.result = {
407      code = code,
408      signal = signal,
409      stdout = stdout_data and table.concat(stdout_data) or nil,
410      stderr = stderr_data and table.concat(stderr_data) or nil,
411    }
412
413    if on_exit then
414      on_exit(state.result)
415    end
416  end)
417end
418
419--- @param state vim.SystemState
420local function _on_error(state)
421  close_handle(state.handle)
422  close_handle(state.stdin)
423  close_handle(state.stdout)
424  close_handle(state.stderr)
425  close_handle(state.timer)
426end
427
428--- Run a system command
429---
430--- @param cmd string[]
431--- @param opts? vim.SystemOpts
432--- @param on_exit? fun(out: vim.SystemCompleted)
433--- @return vim.SystemObj
434local function run(cmd, opts, on_exit)
435  vim.validate('cmd', cmd, function(v)
436    return type(v) == 'table' and type(v[1]) == 'string'
437  end, 'non-empty list of strings')
438  --- @cast cmd string[] & { [1]: string }
439  vim.validate('opts', opts, 'table', true)
440  vim.validate('on_exit', on_exit, 'function', true)
441
442  opts = opts or {}
443
444  local stdout, stdout_child_fd, stdout_handler, stdout_data = setup_output(opts.stdout, opts.text)
445  local stderr, stderr_child_fd, stderr_handler, stderr_data = setup_output(opts.stderr, opts.text)
446  local stdin, stdin_child_fd, towrite = setup_input(opts.stdin)
447
448  --- @type vim.SystemState
449  local state = {
450    done = false,
451    cmd = cmd,
452    timeout = opts.timeout,
453    stdin = stdin,
454    stdout = stdout,
455    stdout_data = stdout_data,
456    stderr = stderr,
457    stderr_data = stderr_data,
458  }
459
460  state.handle, state.pid = spawn(cmd[1], {
461    args = vim.list_slice(cmd, 2),
462    -- local function spawn() will close these
463    stdio = { stdin_child_fd, stdout_child_fd, stderr_child_fd },
464    cwd = opts.cwd,
465    env = setup_env(opts.env, opts.clear_env),
466    detached = opts.detach,
467    hide = true,
468  }, function(code, signal)
469    _on_exit(state, code, signal, on_exit)
470  end, function()
471    _on_error(state)
472  end)
473
474  if stdout and stdout_handler then
475    stdout:read_start(stdout_handler)
476  end
477
478  if stderr and stderr_handler then
479    stderr:read_start(stderr_handler)
480  end
481
482  local obj = new_systemobj(state)
483
484  if towrite then
485    obj:write(towrite)
486    obj:write(nil) -- close the stream
487  end
488
489  if opts.timeout then
490    state.timer = timer_oneshot(opts.timeout, function()
491      if state.handle and state.handle:is_active() then
492        obj:_timeout()
493      end
494    end)
495  end
496
497  return obj
498end
499
500--- Runs a system command or throws an error if {cmd} cannot be run.
501---
502--- The command runs directly (not in 'shell') so shell builtins such as "echo" in cmd.exe, cmdlets
503--- in powershell, or "help" in bash, will not work unless you actually invoke a shell:
504--- `vim.system({'bash', '-c', 'help'})`.
505---
506--- Examples:
507---
508--- ```lua
509--- local on_exit = function(obj)
510---   print(obj.code)
511---   print(obj.signal)
512---   print(obj.stdout)
513---   print(obj.stderr)
514--- end
515---
516--- -- Runs asynchronously:
517--- vim.system({'echo', 'hello'}, { text = true }, on_exit)
518---
519--- -- Runs synchronously:
520--- local obj = vim.system({'echo', 'hello'}, { text = true }):wait()
521--- -- { code = 0, signal = 0, stdout = 'hello\n', stderr = '' }
522---
523--- ```
524---
525--- See |uv.spawn()| for more details. Note: unlike |uv.spawn()|, vim.system
526--- throws an error if {cmd} cannot be run.
527---
528--- @param cmd string[] Command to execute
529--- @param opts vim.SystemOpts?
530--- @param on_exit? fun(out: vim.SystemCompleted) Called when subprocess exits. When provided, the command runs
531---   asynchronously. See return of SystemObj:wait().
532---
533--- @return vim.SystemObj
534--- @overload fun(cmd: string[], on_exit: fun(out: vim.SystemCompleted)): vim.SystemObj
535function vim.system(cmd, opts, on_exit)
536  if type(opts) == 'function' then
537    on_exit = opts
538    opts = nil
539  end
540  return run(cmd, opts, on_exit)
541end