aboutsummaryrefslogtreecommitdiffstats
path: root/proc.lua
blob: 306cb2ecd4a52705507a3ec8f9f1e4433dc38550 (plain) (blame)
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
-- Copyright (c) 2024 squibid, see LICENSE file for more info
local mp = require('mp')

local M = {}

--- run a system binary
---@param args table command with it's options
---@param env table key value pair of envvars
---@param cb function callback
function M.exec(args, env, cb)
  local res_env = {}
  for i, v in pairs(env) do
    res_env[#res_env + 1] = i.."="..v
  end

  --- run callback
  ---@param success boolean if the command ran successfully
  ---@param result table|nil results
  ---@param error string|nil error string or nil
  local function callback(success, result, error)
    local output
    if result then
      -- combine both stdout and stderr
      output = result.stdout..result.stderr
    end
    cb(not success, output)
  end

  mp.command_native_async({
    name = "subprocess",
    playback_only = false,
    capture_stdout = true,
    capture_stderr = true,
    env = res_env,
    args = args
  }, callback)
end

---@type table git environment
local git_env = { GIT_TERMINAL_PROMPT = 0 }

--- git rev parse
---@param dir string directory
---@param arg string arg
---@param cb function callback
function M.git_rev_parse(dir, arg, cb)
  local cmd = { "git", "-C", dir, "rev-parse", "--short", arg }
  M.exec(cmd, git_env, cb)
end

--- git clone
---@param dir string directory
---@param url string url
---@param branch string branch
---@param cb function callback
function M.git_clone(dir, url, branch, cb)
  local cmd = { "git", "clone", "--depth=1", "--recurse-submodules", "--shallow-submodules", url, dir }

  if branch then
    cmd[#cmd + 1] = "--branch="..branch
  end

  M.exec(cmd, git_env, cb)
end

--- git fetch
---@param dir string directory
---@param remote string remote
---@param refspec string refspec
---@param cb function callback
function M.git_fetch(dir, remote, refspec, cb)
  local cmd = { "git", "-C", dir, "fetch", "--depth=1", "--recurse-submodules", remote, refspec }
  M.exec(cmd, git_env, cb)
end

--- git reset
---@param dir string dir
---@param treeish string treeish
---@param cb function callback
function M.git_reset(dir, treeish, cb)
  local cmd = { "git", "-C", dir, "reset", "--hard", "--recurse-submodules", treeish, "--" }
  M.exec(cmd, git_env, cb)
end

return M