Keep a clean git source tree and squash your branches before merging!
This script squashes all commits on your branch.
When you look at your main branch’s git history, in most development environments it is more useful to just see commits for major changes, not all the little steps and mistakes it took to get there. A “squash” in git is the term used for combining past commits together, thereby reducing the amount of commits in your git history.
In most of my repositories, that means when I’m done building on a feature branch, I squash the branch down to one commit, rebase the feature onto the latest original branch (master
, or develop
in gitflow), force-push and merge.
This makes my git history of the main branch only show commits of the finished product of branches! I use this script all the time.
(Note: Most repository managers like Github and Bitbucket have a “squash and merge” option for merging Pull Requests. This is for those who are not using Pull Requests or do not have that option)
If you use zsh
in your terminal (and you totally should), this simple script will work great for you.
Copy and paste this into your ~/.zshrc
file (I put it just before my aliases are defined):
squashon () {
# If user just enters 'squashon', give help text
if (( # == 0 )); then
echo Hello! This will squash your current branch down to one unstaged commit.
echo Use by typing 'squashon rootBranchName' (not current branch name)
echo usage: squashon develop
fi
# If a root branch is provided, run the squasher
if (( # == 1 )); then
branch=$(git symbolic-ref HEAD)
echo Squashing all commits from $branch
git reset $(git merge-base $1 $branch)
echo ------SUCCESS!------
echo Commits successfully squashed, all file changes are unstaged.
echo Run 'git add -A' and 'git commit -m "your commit message"' to add your squashed commit.
fi
}
What squashon
does
Assume you have a root branch called develop
, and a feature branch called feature/new-thing
which originated from develop
. Your feature branch has 10 commits on it, the feature is complete and approved, and it is ready to be squashed!
Run the script in the terminal with: squashon develop
This will take all changes you made on your branch, bring you back to the point when you branched off of develop, and keep them as unstaged changes.
Now just run git add -A && git commit -m 'your commit message'
and you’ll have one single commit that includes all of your branch’s changes!
Note that you will need to force-push if you already pushed up to your remote, because you are rewriting the git history on this branch. git push -f
Top comments (0)