Skip to content

Instantly share code, notes, and snippets.

@mgerdts
Created January 23, 2023 18:29
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mgerdts/4d9400d8c90b561f87ed6a71ec8cdd80 to your computer and use it in GitHub Desktop.
Save mgerdts/4d9400d8c90b561f87ed6a71ec8cdd80 to your computer and use it in GitHub Desktop.
Prevent accidental squash during merge fixup

I've found that git rebase -i $some_commit and adding break lines is very handy for fixing up things in an earlier commits. I then sometimes use x ./check after each subsequent commit to quickly identify any breakage in the commit where it happens.

After each fixup due to break or x, I need to run:

git commit --amend -a
git rebase --continue

If the rebase stops because there is a merge conflict that I need to fix, the proper thing to do is:

git add <file_with_conflicts>
git rebase --continue

If I accidentally use git commit --amend -a it will cause the commit that needs to be fixed to be squashed into the previous commit. I've been bitten many times.

To protect against this, I've added the following to .git/hooks/pre-commit:

#! /bin/bash

exec 1>&2

top=$(git rev-parse --show-toplevel)
if [[ -f $top/.git/rebase-merge/stopped-sha ]]; then
        cmd=$(ps -o command= -p $PPID)
        if [[ $cmd == *--amend* ]]; then
                echo "$0: refusing to amend while fixing up a rebase commit"
                echo ""
                echo "Use: git rebase --continue"
                exit 1
        fi
fi

Now I'm protected:

$ git commit --amend -a
.git/hooks/pre-commit: refusing to amend while fixing up a rebase commit

Use: git rebase --continue
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment