Search code examples
gitgit-commitgithooks

How can I recover the commit message when the git commit-msg hook fails?


I'm using one of git's hooks commit-msg to validate a commit message for certain format and contents.

However, whenever a commit message fails the hook, I have sometimes lost a paragraph or more of text from my message.

I've played around with saving it off somewhere, but I'm not sure how to restore it to the user when they attempt to fix the failed commit message, only the last good commit message shows up.

Has anyone else dealt with this before? How did you solve it?

Info: I am using python scripts for my validation.


Solution

  • The commit message is stored in .git/COMMIT_EDITMSG. After a "failed" committing attempt, you could run:

    git commit --edit --file=.git/COMMIT_EDITMSG
    

    or shorter, e.g.:

    git commit -eF .git/COMMIT_EDITMSG
    

    which will load the bad commit message in your $EDITOR (or the editor you set up in your Git configuration), so that you can try to fix the commit message. You could also set up an alias for the above, with:

    git config --global alias.fix-commit 'commit --edit --file=.git/COMMIT_EDITMSG'
    

    and then use git fix-commit instead.