Squash many commits to one

11 Aug 2020

The situation: I'm developing on a branch and pushing my branch out to my remote repo to back up my work as I go.

master
      \
    my-cool-feature
       \
        +-->commit1-->commit2-->commit3-->commit4

Now I want to get a branch ready for PR that combines all of my commits on my-cool-feature into a new branch named my-cool-feature-PR like so:

master
      \
    my-cool-feature-PR
       \
        +-->commit

Here's how.

(my-cool-feature)$ git checkout master
(master)$ git checkout -b my-cool-feature-PR
(my-cool-feature-PR)$ git merge --squash my-cool-feature
(my-cool-feature-PR)$ git status

git status shows everything from my-cool-feature in the index / staging area.

(my-cool-feature-PR)$ git commit

When my editor comes up, it begins with "Squashed commit of the following:" but I can edit this message to be whatever I want.

(my-cool-feature-PR)$ git log

This shows my new commit in all its glory.

Now let's back up my PR branch by pushing it to my remote repo.

(my-cool-feature-PR)$ git push --set-upstream origin my-cool-feature-PR

Now let's get rid of my older, dirtier branch, locally.

First, I'll check to be sure both my new tidy PR branch and my older many-commit branch really are the same (remember we are on branch my-cool-feature-PR):

(my-cool-feature-PR)$ git diff my-cool-feature

The above came back empty, so I'm good to go.

I'll check to be sure my differences from master are what I expect (remember I'm on branch my-cool-feature-PR):

(my-cool-feature-PR)$ git diff master

Now I drop my dev branch locally:

(my-cool-feature-PR)$ git branch -d my-cool-feature

Now I drop my dev branch remotely:

(my-cool-feature-PR)$ git push :my-cool-feature

Done!