I usually create small commits when adding new code such that I can easily revert back little by little. This is fine but creates a long and messy history. Git allows squashing commits together.

I typically create a feature branch

git checkout -b feature-branch
# do stuff
git add -a
git commit -m "useless message"

When I’m ready for squashing,

git merge-base feature-branch master
# gives the last common commit

Or better, in one line

git rebase -i $(git merge-base $(git branch | grep '*' | tr -d '* ') master)

Beware that it works only if you currently are on feature-branch. I modified ~/.bashrc to add a folder to the PATH environment variable


Followed by a source ~/.bashrc. At this point, inside that folder I create a file git-squash-branch

git rebase -i $(git merge-base $(git branch | grep '*' | tr -d '* ') master)

Followed by chmod u+x ~/opt/git-squash-branch. At this point I can simply run git squash-branch.

If the code has already been pushed to a server and you want to force the squashing (beware of the potential mess if someone has pulled from some of the squashed commits)

git push --force origin feature-branch

Source for the custom git command: Custom Git Commands in 3 Steps


comments powered by Disqus