Monday, May 14, 2018

Squashing Commit Messages in Git

A couple of times in the past week or two I've wanted to squash my merges into a single merge before pushing up to the remote server. I know that rebase can do that, but for whatever reason, rebase scares the tar out of me so I've never used it. Someday I'll have to learn it, but until then I found this neat answer on Stack Overflow.

tl;dr:

git commit -m "My most recent changes"
git reset --soft HEAD~3
git commit -m "All changes from last 3 commits"

Let's say we want all of our current work to be committed and squashed together with the previous two commits we made locally.
  1. Commit everything so the index is clean (that means that when you run git status you don't see any pending changes)
  2. Do a soft rewind (that's my term, I don't think it's a proper git term, though) to 3 commits ago (remember that we're squashing together our previous two commits with the commit we made in step 1 so we want to go back 3 now) using git reset --soft HEAD~3
  3. All changes from the previous 3 commits should now be staged for commitment, which you can verify by running git status
  4. Commit the staged changes with the -m flag and provide a single commit message/comment for this now-single commit that combines all 3
This way makes a lot of sense to me and I've found myself using it repeatedly. As always, I wanted to make a note of it here so I could find it later.

No comments:

Post a Comment