local editor = require("git.editor") local git = require("git") local log = require("log") local repo = require("git.repo") local M = {} ---@param opts { amend: boolean? }? function M.commit(opts) local amend = opts and opts.amend or false local _, worktree = repo.resolve_cwd() if not worktree then log.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 = 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 = git.new_scratch({ name = file_path }) proxy_buf = buf proxy_win = win vim.bo[buf].buftype = "acwrite" vim.bo[buf].bufhidden = "wipe" 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 log.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_buf and vim.api.nvim_buf_is_valid(proxy_buf) then vim.api.nvim_buf_delete(proxy_buf, { force = true }) end if proxy_win and vim.api.nvim_win_is_valid(proxy_win) then vim.api.nvim_win_close(proxy_win, true) end if result.code ~= 0 then log.error("git commit failed: %s", vim.trim(result.stderr or "")) return end local out = vim.trim(result.stdout or "") if out ~= "" then log.info("%s", out) end end) end return M