With git, it is possible to commit several times in one branch, then squash those commits together when merging into another branch. I most often use this workflow for experimental work. I'll have a feature branch which is what I will create a pull request from, so I want it to have a clean commit history. I want to avoid lots of commits saying things like 'tried a different approach', 'third attempt', 'might be working this time'. (I'm sure we've all seen commits like that before!)
I create a new branch from my feature branch. This is where I will put my experimental commits, which will be squashed into a single commit on my feature branch. Let's say my feature branch is called feature
and I've created an experimental branch experiments
.
I have the following alias in my .gitconfig
:
squash = "!f() { BRANCH=`git symbolic-ref --short HEAD`; git checkout ${1}; git merge --squash $BRANCH; }; f"
I can use this alias while I'm on my experiments
branch. I just run git squash feature
, and it will squash all the commits and leave me on the feature
branch with a load of uncommitted code. I can then review and commit the changes as a single commit, with a new commit message.
This alias was inspired by an answer on Stack Overflow.