2023-06-26 00:18:50 +02:00
-- This Source Code Form is subject to the terms of the Mozilla Public
-- License, v. 2.0. If a copy of the MPL was not distributed with this
-- file, You can obtain one at https://mozilla.org/MPL/2.0/.
2023-06-26 00:49:06 +02:00
--
-- SPDX-License-Identifier: MPL-2.0
2023-06-26 00:18:50 +02:00
2023-06-28 23:42:07 +02:00
---@diagnostic disable: redefined-local
2023-06-21 21:48:38 +02:00
local process = { }
---Spawn a process with an optional callback for its stdout and stderr.
2023-06-28 23:42:07 +02:00
---
---`callback` has the following parameters:
--- - `stdout`: The process's stdout printed this line.
--- - `stderr`: The process's stderr printed this line.
--- - `exit_code`: The process exited with this code.
--- - `exit_msg`: The process exited with this message.
2023-06-21 21:48:38 +02:00
---@param command string|string[] The command as one whole string or a table of each of its arguments
2023-06-28 23:42:07 +02:00
---@param callback fun(stdout: string?, stderr: string?, exit_code: integer?, exit_msg: string?)? A callback to do something whenever the process's stdout or stderr print a line, or when the process exits.
2023-06-21 21:48:38 +02:00
function process . spawn ( command , callback )
---@type integer|nil
local callback_id = nil
if callback ~= nil then
2023-06-27 04:19:02 +02:00
---@param args Args
2023-06-21 21:48:38 +02:00
table.insert ( CallbackTable , function ( args )
2023-06-27 04:19:02 +02:00
local args = args.Spawn or { } -- don't know if the `or {}` is necessary
2023-06-21 21:48:38 +02:00
callback ( args.stdout , args.stderr , args.exit_code , args.exit_msg )
end )
callback_id = # CallbackTable
end
2023-06-27 04:19:02 +02:00
local command_arr = { }
if type ( command ) == " string " then
for i in string.gmatch ( command , " %S+ " ) do
table.insert ( command_arr , i )
2023-06-21 21:48:38 +02:00
end
2023-06-27 04:19:02 +02:00
else
command_arr = command
2023-06-21 21:48:38 +02:00
end
SendMsg ( {
Spawn = {
2023-06-27 04:19:02 +02:00
command = command_arr ,
2023-06-21 21:48:38 +02:00
callback_id = callback_id ,
} ,
} )
end
return process