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
git rebase -i THE_VALUE_OF_THE_PREVIOUS_COMMAND

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

PATH=/home/davide/opt:$PATH

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

#!/bin/bash
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

comments powered by Disqus