tonetheman's blog

git and all the ways of shooting yourself in your foot

I want to squash my commits on a branch so that when merge happens I get one nice commit.

To be honest I do not normally like this type of stuff but when you are in a larger team this can make things look nicer. I tend to like to see each commit in all it's glory.

First checkout the branch you are wanting to work on

git checkout branch

I would run a git status to convince myself I was in the right place. But I am insane.

Then you want to reset the branch back to the point where branched it and leave the files in the working directory.

git reset --soft master

At this point it is like you have lost all of your commits you can see that in the git log BUT you have NOT lost any changes the working directory is happily sitting with all of your changes. Run a git status and you will see all of your changed files now sitting waiting to be staged.

Now add your files back one by one or however you want. You are restaging your files. And then commit them all in one single commit.

git add X1
git add X2
git commit -m "added in one commit"

I like this method I am sure there are some other ways to do it but this really makes a lot of sense to me.

Another way to do this is this command but it requires some more explanation.

git rebase -i master

When you run that command it will list all of the commit in order that you have made to your branch since you branch off of master in a text file.

Then you can leave the first commit alone as pick, then change all the other commits to squash and all of the commits will end up squashed into one big commit.

This is an explanation of that in more detail: https://makandracards.com/makandra/527-squashing-several-git-commits-into-a-single-commit