Files
nvim/test/git/helpers.lua
T

77 lines
2.1 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.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
return M