Squash commits

When you create merge request often you will want to squash all the commits into one.

If you search Google about how to squash all commits, you will often find confusing tutorials that will either recommend using git rebase (where you have to manually specify which commits you want to squash), or tutorials recommending using git reset or git rebase on latest n commits (where you need to know how many commits you made in your branch). But there is an easier way.

One liner solution

git reset $(git merge-base origin/master $(git rev-parse --abbrev-ref HEAD))

What happens

git rev-parse --abbrev-ref HEAD

Gets current name of the branch, eg.: branch-name

git merge-base origin/master my-branch

Git merge-base finds best common ancestor between two commits to use in a three-way merge, eg.: c111855daca0d1834cc836dc65ea39d22dabf14c.

After this command you will end up in the state where your branch will be identical to origin/master and all the changes you made on your branch will be unstaged. So all you need to do is add the changes to staging, create squashed commit and force push to your branch.

git add .
git commit -m "commit message"
git push --force

That's it.

TLDR

Replace origin/master with the branch against you are merging.

git reset $(git merge-base origin/master $(git rev-parse --abbrev-ref HEAD))
git add .
git commit -m "commit message"
git push --force
Discuss on TwitterEdit on GitHub