Files
dep/lua/dep/proc.lua
Squibid 71b78bfca4 the spec no longer fixes itself...
modules are more reliable
cleanup some typos
2025-06-23 00:18:33 -04:00

130 lines
3.1 KiB
Lua

local proc = {}
--- execute a process
---@param process string the program
---@param args string[] the args
---@param cwd string? the pwd
---@param env table env
---@param cb function callback
function proc.exec(process, args, cwd, env, cb)
local buffer = {}
local function cb_output(_, data, _)
table.insert(buffer, table.concat(data))
end
local function cb_exit(_, exit_code, _)
local output = table.concat(buffer)
cb(exit_code ~= 0, output)
end
table.insert(args, 1, process)
vim.fn.jobstart(args, {
cwd = cwd,
env = env,
stdin = nil,
on_exit = cb_exit,
on_stdout = cb_output,
on_stderr = cb_output,
})
end
local git_env = { GIT_TERMINAL_PROMPT = 0 }
function proc.git_rev_parse(dir, arg, cb)
local args = { "rev-parse", "--short", arg }
proc.exec("git", args, dir, git_env, cb)
end
function proc.git_clone(dir, url, branch, cb)
local args = { "clone", "--depth=1", "--recurse-submodules", "--shallow-submodules", url, dir }
if branch then
args[#args + 1] = "--branch="..branch
end
proc.exec("git", args, nil, git_env, cb)
end
function proc.git_fetch(dir, remote, refspec, cb)
local args = { "fetch", "--depth=1", "--recurse-submodules", remote, refspec }
proc.exec("git", args, dir, git_env, cb)
end
function proc.git_reset(dir, treeish, cb)
local args = { "reset", "--hard", "--recurse-submodules", treeish, "--" }
proc.exec("git", args, dir, git_env, cb)
end
function proc.git_checkout(dir, branch, commit, cb)
local args = { "fetch", "--depth=2147483647", "origin", branch }
proc.exec("git", args, dir, git_env, function(err, message)
cb(err, message)
args = { "checkout", commit }
proc.exec("git", args, dir, git_env, cb)
end)
end
function proc.git_resolve_branch(url, branch, cb)
-- if the branch doesn't contain a * then return the branch
if not string.match(branch, "*") then
cb(false, branch)
return
end
local buffer = {}
local function cb_output(_, data, _)
if data[1] ~= "" then
buffer = data
end
end
vim.fn.jobstart({ "git", "ls-remote", "--tags", "--sort", "v:refname", url },
{
cwd = nil,
env = git_env,
stdin = nil,
on_stdout = cb_output,
on_stderr = cb_output,
on_exit = function(_, exit_code, _)
if exit_code ~= 0 then
return
end
-- get a list of all versions
local versions = {}
for _, v in pairs(buffer) do
local s, e = string.find(v, "refs/tags/.+")
if not s or not e then
goto continue
end
local tag = string.sub(v, s, e)
tag = tag:gsub("refs/tags/", ""):gsub("%^{}", "")
table.insert(versions, tag)
::continue::
end
-- match the chosen version against all versions
for i = #versions, 1, -1 do
if branch == "*" then
cb(false, versions[i])
return
else
local r = string.match(versions[i], branch)
if r then
cb(false, r)
return
end
end
end
end
}
)
end
return proc