80 lines
2.3 KiB
Lua
80 lines
2.3 KiB
Lua
local editor = require("git.editor")
|
|
local repo = require("git.repo")
|
|
local util = require("git.util")
|
|
|
|
local M = {}
|
|
|
|
---@param opts { amend: boolean? }?
|
|
function M.commit(opts)
|
|
local amend = opts and opts.amend or false
|
|
local r = repo.resolve()
|
|
if not r then
|
|
util.warning("not in a git repository")
|
|
return
|
|
end
|
|
|
|
local cmd = { "git", "commit" }
|
|
if amend then
|
|
table.insert(cmd, "--amend")
|
|
end
|
|
|
|
local proxy_buf, proxy_win
|
|
editor.run(cmd, { cwd = r.worktree }, function(file_path, done)
|
|
local lines = {}
|
|
local f = io.open(file_path, "r")
|
|
if f then
|
|
for line in f:lines() do
|
|
table.insert(lines, line)
|
|
end
|
|
f:close()
|
|
end
|
|
|
|
local buf, win = util.new_scratch({ name = file_path })
|
|
proxy_buf = buf
|
|
proxy_win = win
|
|
vim.bo[buf].buftype = "acwrite"
|
|
vim.bo[buf].modifiable = true
|
|
vim.api.nvim_buf_set_lines(buf, 0, -1, false, lines)
|
|
vim.bo[buf].modified = false
|
|
vim.bo[buf].filetype = "gitcommit"
|
|
|
|
vim.api.nvim_create_autocmd("BufWriteCmd", {
|
|
buffer = buf,
|
|
callback = function()
|
|
local out = vim.api.nvim_buf_get_lines(buf, 0, -1, false)
|
|
local fw, werr = io.open(file_path, "w")
|
|
if not fw then
|
|
util.error("failed to write %s: %s", file_path, werr or "")
|
|
return
|
|
end
|
|
fw:write(table.concat(out, "\n"))
|
|
fw:close()
|
|
vim.bo[buf].modified = false
|
|
end,
|
|
})
|
|
|
|
vim.api.nvim_create_autocmd("BufWipeout", {
|
|
buffer = buf,
|
|
once = true,
|
|
callback = done,
|
|
})
|
|
end, function(result)
|
|
if proxy_win and vim.api.nvim_win_is_valid(proxy_win) then
|
|
pcall(vim.api.nvim_win_close, proxy_win, true)
|
|
end
|
|
if proxy_buf and vim.api.nvim_buf_is_valid(proxy_buf) then
|
|
vim.api.nvim_buf_delete(proxy_buf, { force = true })
|
|
end
|
|
if result.code ~= 0 then
|
|
util.error("git commit failed: %s", vim.trim(result.stderr or ""))
|
|
return
|
|
end
|
|
local out = vim.trim(result.stdout or "")
|
|
if out ~= "" then
|
|
util.info("%s", out)
|
|
end
|
|
end)
|
|
end
|
|
|
|
return M
|