summaryrefslogtreecommitdiff
path: root/core/lua/astal/process.lua
blob: 3d10f8b4659db239689de258ce570fa0c3112e66 (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
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
local lgi = require("lgi")
local Astal = lgi.require("Astal", "0.1")

local M = {}

local defualt_proc_args = function(on_stdout, on_stderr)
    if on_stdout == nil then
        on_stdout = function(out)
            io.stdout:write(tostring(out) .. "\n")
            return tostring(out)
        end
    end

    if on_stderr == nil then
        on_stderr = function(err)
            io.stderr:write(tostring(err) .. "\n")
            return tostring(err)
        end
    end

    return on_stdout, on_stderr
end

---@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)
    local out, err = defualt_proc_args(on_stdout, on_stderr)
    local proc, fail
    if type(commandline) == "table" then
        proc, fail = Astal.Process.subprocessv(commandline)
    else
        proc, fail = Astal.Process.subprocess(commandline)
    end
    if fail ~= nil then
        err(fail)
        return nil
    end
    proc.on_stdout = function(_, str)
        out(str)
    end
    proc.on_stderr = function(_, str)
        err(str)
    end
    return proc
end

---@generic T
---@param commandline string | string[]
---@param on_stdout? fun(out: string): T
---@param on_stderr? fun(err: string): T
---@return T
function M.exec(commandline, on_stdout, on_stderr)
    local out, err = defualt_proc_args(on_stdout, on_stderr)
    local stdout, stderr
    if type(commandline) == "table" then
        stdout, stderr = Astal.Process.execv(commandline)
    else
        stdout, stderr = Astal.Process.exec(commandline)
    end
    if stderr then
        return err(stderr)
    end
    return out(stdout)
end

---@param commandline string | string[]
---@param on_stdout? fun(out: string): nil
---@param on_stderr? fun(err: string): nil
function M.exec_async(commandline, on_stdout, on_stderr)
    local out, err = defualt_proc_args(on_stdout, on_stderr)
    if type(commandline) == "table" then
        Astal.Process.exec_asyncv(commandline, function(_, res)
            local stdout, fail = Astal.exec_asyncv_finish(res)
            if fail ~= nil then
                err(fail)
            else
                out(stdout)
            end
        end)
    else
        Astal.Process.exec_async(commandline, function(_, res)
            local stdout, fail = Astal.exec_finish(res)
            if fail ~= nil then
                err(fail)
            else
                out(stdout)
            end
        end)
    end
end

return M