summaryrefslogtreecommitdiff
path: root/lang/lua/astal/process.lua
blob: 28861647efd19c083ac39afba6429555cbed7162 (plain)
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
local lgi = require("lgi")
local Astal = lgi.require("AstalIO", "0.1")

local M = {}

---@param commandline string | string[]
---@param on_stdout? fun(out: string): nil
---@param on_stderr? fun(err: string): nil
---@return { kill: function } | nil proc
function M.subprocess(commandline, on_stdout, on_stderr)
    on_stdout = on_stdout or function(out)
        io.stdout:write(tostring(out) .. "\n")
    end

    on_stderr = on_stderr or function(err)
        io.stderr:write(tostring(err) .. "\n")
    end


    local proc, err

    if type(commandline) == "table" then
        proc, err = Astal.Process.subprocessv(commandline)
    else
        proc, err = Astal.Process.subprocess(commandline)
    end

    if err ~= nil then
        err(err)
        return nil
    end
    proc.on_stdout = function(_, stdout)
        on_stdout(stdout)
    end
    proc.on_stderr = function(_, stderr)
        on_stderr(stderr)
    end
    return proc
end

---@param commandline string | string[]
---@return string, string
function M.exec(commandline)
    if type(commandline) == "table" then
        return Astal.Process.execv(commandline)
    else
        return Astal.Process.exec(commandline)
    end
end

---@param commandline string | string[]
---@param callback? fun(out: string, err: string): nil
function M.exec_async(commandline, callback)
    callback = callback or function(out, err)
        if err ~= nil then
            io.stdout:write(tostring(out) .. "\n")
        else
            io.stderr:write(tostring(err) .. "\n")
        end
    end

    if type(commandline) == "table" then
        Astal.Process.exec_asyncv(commandline, function(_, res)
            local out, err = Astal.Process.exec_asyncv_finish(res)
            callback(out, err)
        end)
    else
        Astal.Process.exec_async(commandline, function(_, res)
            local out, err = Astal.Process.exec_finish(res)
            callback(out, err)
        end)
    end
end

return M