{ lib, ... }: {
my.nvim.snacks.setupArgs = {
picker = {
actions = {
# Upstream git_restore only runs `git restore <file>`, which resets just the
# worktree: staged changes survive in the index and untracked entries are never
# restored, so <c-r> silently does nothing for them. Discard both sides from HEAD
# instead, and delete untracked entries. Hunk items from git_diff keep upstream.
git_restore = lib.generators.mkLuaInline /*lua*/ ''function(picker)
local upstream = require("snacks.picker.actions").git_restore
local items = picker:selected({ fallback = true })
local first = items[1]
if not first or not first.status then
return upstream(picker)
end
local msg = ("Discard changes to %d files?"):format(#items)
if #items == 1 then
local what = first.status == "??" and "Delete untracked file `%s`?" or "Discard changes to `%s`?"
msg = what:format(Snacks.picker.util.path(first))
end
Snacks.picker.util.confirm(msg, function()
-- A repo without commits has no HEAD to restore from, and there every index
-- entry is a fresh add, so discarding it means removing the file.
local has_head = vim.system({ "git", "rev-parse", "--verify", "--quiet", "HEAD" }, { cwd = first.cwd }):wait().code == 0
local function run(i)
local item = items[i]
if not item then
vim.schedule(function()
picker:refresh()
vim.cmd.startinsert()
vim.cmd.checktime()
end)
return
end
-- A rename is shown by its target, so its source path has to be restored too.
local paths = item.rename and { item.file, item.rename } or { item.file }
local cmd
if item.status:sub(1, 2) == "??" then
cmd = { "git", "--literal-pathspecs", "clean", "-fd", "--" }
elseif not has_head then
cmd = { "git", "--literal-pathspecs", "rm", "-f", "--" }
else
cmd = { "git", "--literal-pathspecs", "restore", "--source=HEAD", "--staged", "--worktree", "--" }
end
vim.list_extend(cmd, paths)
-- Sequential: parallel `git` calls in one repo fight over index.lock.
vim.system(cmd, { cwd = item.cwd, text = true }, function(res)
if res.code ~= 0 then
Snacks.notify.error(vim.trim(res.stderr or ""), { title = "Git" })
end
run(i + 1)
end)
end
run(1)
end)
end'';
};
};
};
}