robin/laufey
git clone https://git.robinwobin.dev/robin/laufey
aa1d8a2702
master
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 ={ 64HUP =1 , -- Hangup 65INT =2 , -- Interrupt from keyboard 66KILL =9 , -- Kill signal 67TERM =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 ) 73if handle and not handle : is_closing () then 74handle : close () 75end 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 ) 87return setmetatable ( { 88cmd =state . cmd , 89pid =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 ) 106assert ( self . _state . handle ): kill ( signal ) 107end 108 109--- @package 110--- @param signal? vim.SystemSig 111function SystemObj : _timeout ( signal ) 112self . _state . done ='timeout' 113self : 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 ) 136local state =self . _state 137 138local done =vim . wait ( timeout or state . timeout or vim . _maxint , function () 139return state . result ~= nil 140end , nil , true ) 141 142if not done then 143-- Send sigkill since this cannot be caught 144self : _timeout ( SIG . KILL ) 145vim . wait ( timeout or state . timeout or vim . _maxint , function () 146return state . result ~= nil 147end , nil , true ) 148end 149 150-- TODO: A short timeout can leave result nil even after sending SIGKILL. 151---@diagnostic disable-next-line: return-type-mismatch 152return 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 ) 174local stdin =self . _state . stdin 175 176if not stdin then 177error ( 'stdin has not been opened on this object' ) 178end 179 180if type ( data ) == 'table' then 181for _ , v in ipairs ( data ) do 182stdin : write ( v ) 183stdin : write ( '\n' ) 184end 185elseif type ( data ) == 'string' then 186stdin : write ( data ) 187elseif 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) 192stdin : write ( '' , function () 193stdin : shutdown ( function () 194close_handle ( stdin ) 195end ) 196end ) 197end 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 () 208local handle =self . _state . handle 209return 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 ) 219if output == false then 220return 221end 222 223local bucket --- @type string[]? 224local handler --- @type fun(err: string?, data: string?) 225 226if type ( output ) == 'function' then 227handler =output 228else 229bucket ={} 230--- @param err string? 231--- @param data string? 232handler =function ( err , data ) 233if err then 234error ( err ) 235end 236if text and data then 237bucket [ # bucket + 1 ] =data : gsub ( '\r\n' , '\n' ) 238else 239bucket [ # bucket + 1 ] =data 240end 241end 242end 243 244--- @diagnostic disable-next-line:missing-fields,param-type-mismatch luvit/luv#827 245local pipe_fd =assert ( uv . pipe ( { nonblock =true } , {} )) 246local pipe =assert ( uv . new_pipe ( false )) 247pipe : open ( pipe_fd . read ) 248 249--- @param err? string 250--- @param data? string 251local function handler_with_close ( err , data ) 252handler ( err , data ) 253if data == nil then 254pipe : read_stop () 255pipe : close () 256end 257end 258 259return 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 ) 267if not input then 268return 269end 270 271local towrite --- @type string|string[]? 272if type ( input ) == 'string' or type ( input ) == 'table' then 273towrite =input 274end 275 276--- @diagnostic disable-next-line:missing-fields,param-type-mismatch luvit/luv#827 277local pipe_fd =assert ( uv . pipe ( {} , { nonblock =true } )) 278local pipe =assert ( uv . new_pipe ( false )) 279pipe : open ( pipe_fd . write ) 280 281return pipe , pipe_fd . read , towrite 282end 283 284--- @return table<string,string> 285local function base_env () 286local env =vim . fn . environ () --- @type table<string,string> 287env [ 'NVIM' ] =vim . v . servername 288env [ 'NVIM_LISTEN_ADDRESS' ] =nil 289return 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 ) 299if not env and clear_env then 300return 301end 302 303env =env or {} 304if not clear_env then 305--- @type table<string,string|number> 306env =vim . tbl_extend ( 'force' , base_env (), env ) 307end 308 309local renv ={} --- @type string[] 310for k , v in pairs ( env ) do 311renv [ # renv + 1 ] =string . format ( '%s=%s' , k , tostring ( v )) 312end 313 314return 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 ) 328if is_win then 329local cmd1 =vim . fn . exepath ( cmd ) 330if cmd1 ~= '' then 331-- Use native separators when launching a resolved Windows executable. 332cmd =cmd1 : gsub ( '/' , '\\' ) 333end 334end 335 336local handle , pid_or_err =uv . spawn ( cmd , opts , on_exit ) 337-- close child stdio fd:s regardless of error 338for i =1 , 3 do 339local fd =opts . stdio [ i ] 340if fd then 341uv . fs_close ( fd ) 342end 343end 344 345if not handle then 346on_error () 347if opts . cwd and not uv . fs_stat ( opts . cwd ) then 348error (( "%s (cwd): '%s'" ): format ( pid_or_err , opts . cwd )) 349elseif vim . fn . executable ( cmd ) == 0 then 350error (( "%s (cmd): '%s'" ): format ( pid_or_err , cmd )) 351else 352error ( pid_or_err ) 353end 354end 355return 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 ) 362local timer =assert ( uv . new_timer ()) 363timer : start ( timeout , 0 , function () 364timer : stop () 365timer : close () 366cb () 367end ) 368return 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 ) 376close_handle ( state . handle ) 377close_handle ( state . stdin ) 378close_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 383local check =uv . new_check () 384check : start ( function () 385for _ , pipe in pairs ( { state . stdin , state . stdout , state . stderr } ) do 386if not pipe : is_closing () then 387return 388end 389end 390check : stop () 391check : close () 392 393if state . done == nil then 394state . done =true 395end 396 397if ( code == 0 or code == 1 ) and state . done == 'timeout' then 398-- Unix: code == 0 399-- Windows: code == 1 400code =124 401end 402 403local stdout_data =state . stdout_data 404local stderr_data =state . stderr_data 405 406state . result ={ 407code =code , 408signal =signal , 409stdout =stdout_data and table . concat ( stdout_data ) or nil , 410stderr =stderr_data and table . concat ( stderr_data ) or nil , 411} 412 413if on_exit then 414on_exit ( state . result ) 415end 416end ) 417end 418 419--- @param state vim.SystemState 420local function _on_error ( state ) 421close_handle ( state . handle ) 422close_handle ( state . stdin ) 423close_handle ( state . stdout ) 424close_handle ( state . stderr ) 425close_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 ) 435vim . validate ( 'cmd' , cmd , function ( v ) 436return type ( v ) == 'table' and type ( v [ 1 ]) == 'string' 437end , 'non-empty list of strings' ) 438--- @cast cmd string[] & { [1]: string } 439vim . validate ( 'opts' , opts , 'table' , true ) 440vim . validate ( 'on_exit' , on_exit , 'function' , true ) 441 442opts =opts or {} 443 444local stdout , stdout_child_fd , stdout_handler , stdout_data =setup_output ( opts . stdout , opts . text ) 445local stderr , stderr_child_fd , stderr_handler , stderr_data =setup_output ( opts . stderr , opts . text ) 446local stdin , stdin_child_fd , towrite =setup_input ( opts . stdin ) 447 448--- @type vim.SystemState 449local state ={ 450done =false , 451cmd =cmd , 452timeout =opts . timeout , 453stdin =stdin , 454stdout =stdout , 455stdout_data =stdout_data , 456stderr =stderr , 457stderr_data =stderr_data , 458} 459 460state . handle , state . pid =spawn ( cmd [ 1 ], { 461args =vim . list_slice ( cmd , 2 ), 462-- local function spawn() will close these 463stdio ={ stdin_child_fd , stdout_child_fd , stderr_child_fd } , 464cwd =opts . cwd , 465env =setup_env ( opts . env , opts . clear_env ), 466detached =opts . detach , 467hide =true , 468} , function ( code , signal ) 469_on_exit ( state , code , signal , on_exit ) 470end , function () 471_on_error ( state ) 472end ) 473 474if stdout and stdout_handler then 475stdout : read_start ( stdout_handler ) 476end 477 478if stderr and stderr_handler then 479stderr : read_start ( stderr_handler ) 480end 481 482local obj =new_systemobj ( state ) 483 484if towrite then 485obj : write ( towrite ) 486obj : write ( nil ) -- close the stream 487end 488 489if opts . timeout then 490state . timer =timer_oneshot ( opts . timeout , function () 491if state . handle and state . handle : is_active () then 492obj : _timeout () 493end 494end ) 495end 496 497return 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 ) 536if type ( opts ) == 'function' then 537on_exit =opts 538opts =nil 539end 540return run ( cmd , opts , on_exit ) 541end