I PGP sign my commit messages, and every once in a while GPG will fail for whatever reason (invalid cache, incorrect pin, etc), and my fugitive buffer will close, loosing all my changes.

It doesn't happen often, but when it does it's really frustrating because I like to write thorough commit messages.

My question is, does anyone have a suggestion of how to retrieve the message I wrote after the commit fails?

Thanks in advance.

  • Typically the message stays around in .git/COMMIT_MESSAGE or similar. – D. Ben Knoble Feb 1 '19 at 22:41
  • Thanks Ben, I tried looking in .git/COMMIT_MESSAGE but it wasn't present. Maybe git thinks if GPG encryption fails it should wipe the message? – bronzehedwick Feb 2 '19 at 20:12
  • Im not sure; thats possible. I dont use GPG myself, but have had situations where the text was retained in said file. Maybe you could use a BufPreWrite or similar command to make a backup of the message? – D. Ben Knoble Feb 2 '19 at 20:17
  • It appears the file I remembered was .git/COMMIT_EDITMSG – D. Ben Knoble Feb 4 '19 at 18:38
  • D. Ben Knoble You're right, I found the message in .git/COMMIT_EDITMSG! I'll be able to write a command similar to what you provided in second part of your answer to leverage it inside vim. If you want to update your answer below to just include .git/COMMIT_EDITMSG i'll upvote and mark as answer. – bronzehedwick Feb 5 '19 at 16:30

The contents of .git/COMMIT_EDITMSG usually persist, but there are ways to create backups.

One solution that comes to mind, leveraging the filetype gitcommit (untested):

" .vim/after/ftplugin/gitcommit.vim
" autocmd! prevents duplication if resourced
" |      BufWritePre triggered before write
" |      |           <buffer> applies only to this buffer
" |      |           |        write to '%.save' ('%' expands to current filename)
" |      |           |        |
autocmd! BufWritePre <buffer> write %.save

Then, if there was a failure, when you do git commit, simply type :0read %.save. You might even want to create a buffer-local mapping for this:

" .vim/after/ftplugin/gitcommit.vim

nnoremap <buffer> <silent> <LocalLeader>b 0read %.save<CR>

Make sure to adjust b:undo_ftplugin appropriately. You'll also need (at minimum) filetype plugin on.

  • Not sure why the syntax highlighter is having trouble... maybe it's because I used triple-backticks, recently added to SO. – D. Ben Knoble Feb 4 '19 at 18:43

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.