Files

98 lines
2.7 KiB
Lua

local t = require("test")
local M = {}
---@class test.git.SystemCompleted : vim.SystemCompleted
---@field stdout string
---@param dir string
---@return test.git.SystemCompleted
function M.git(dir, ...)
local r = vim.system({ "git", ... }, { cwd = dir, text = true }):wait()
if r.code ~= 0 then
error(
string.format(
"git %s failed: %s",
table.concat({ ... }, " "),
vim.trim(r.stderr or "")
),
2
)
end
if r.stdout then
r.stdout = vim.trim(r.stdout)
else
r.stdout = ""
end
return r
end
---Build a temporary git repo with the given committed contents and queue
---cleanup (stop fs watchers, drop test buffers, delete the dir). When
---`opts.cd` is true, also `cd` into the repo and restore the previous
---working directory on cleanup.
---@param files table<string, string>?
---@param opts { cd: boolean? }?
---@return string dir
function M.make_repo(files, opts)
local dir = vim.fn.tempname()
vim.fn.mkdir(dir, "p")
M.git(dir, "init", "-q", "-b", "main")
M.git(dir, "config", "user.email", "t@t.com")
M.git(dir, "config", "user.name", "t")
if files and next(files) then
for path, content in pairs(files) do
t.write(dir, path, content)
end
M.git(dir, "add", ".")
M.git(dir, "commit", "-q", "-m", "init")
end
local prev_cwd
if opts and opts.cd then
prev_cwd = vim.fn.getcwd()
vim.cmd.cd(dir)
end
t.defer(function()
if prev_cwd then
pcall(vim.cmd.cd, prev_cwd)
else
pcall(vim.cmd.cd, "/tmp")
end
pcall(function()
require("git.core.repo").stop_all()
end)
vim.wait(60)
for _, b in ipairs(vim.api.nvim_list_bufs()) do
local name = vim.api.nvim_buf_get_name(b)
if name:find(dir, 1, true) or name:match("^git[a-z]*://") then
pcall(vim.api.nvim_buf_delete, b, { force = true })
end
end
vim.fn.delete(dir, "rf")
end)
return dir
end
---Build an outer repo with one nested submodule at `sub/`. Both the
---outer and inner repo are committed and registered for cleanup.
---@return string outer
---@return string inner
function M.make_submodule_repo()
local inner = M.make_repo({ a = "x\n" })
local outer = M.make_repo({ x = "x\n" })
vim.system({
"git",
"-c",
"protocol.file.allow=always",
"submodule",
"add",
"--quiet",
inner,
"sub",
}, { cwd = outer, text = true }):wait()
M.git(outer, "commit", "-q", "-m", "add submodule")
return outer, inner
end
return M