DEV Community 👩‍💻👨‍💻

Cover image for Tips to maintain clean git commit history
Ruchi Vora
Ruchi Vora

Posted on • Updated on

Tips to maintain clean git commit history

Solution 1 :

Lets say you are working on a feature and created a feature branch F1 by checking out from master. While working on the feature branch F1 , you created multiple intermediate commits. However, when you check the commit history you find some of these commits redundant. In such case you can squash the commits i.e you can combine multiple commits and make it a one commit.

Below is the commit history of the feature branch before and after the squash.
Squash Git Commits

Command to squash the last X commits using interactive rebase is:

git rebase -i HEAD~[X]
Enter fullscreen mode Exit fullscreen mode

The squashing of commits is also useful when you want to merge your feature branch to master branch.As by squashing, all the redundant commits can be removed and after merging the feature branch to master, the git commit history is clean.

Advantage of squashing :

The git history remains clean

Disadvantage of squashing :

The detailed branch history is no longer available.

Before going to the second solution , let's understand the difference between git merge and git rebase.

git merge VS git rebase

Both git merge and git rebase is used to merge the code from feature branch to the main(master) branch.

git merge

When we use git merge command to merge the code from feature branch to master , then git will take all the changes from my feature branch and create a special commit on top of my commit , called as merge commit that contains all the changes from my feature branch and place this merge commit on top of master branch. The git commit graph will look like this

Git Merge
Command to merge the fetaure_branch in master branch is:

git checkout master
git merge feature_branch
Enter fullscreen mode Exit fullscreen mode

Let's understand git rebase with Solution 2

Solution 2 :

In order to maintain a clean commit history , instead of git merge do git rebase. What rebase will do is , it will take all the commits from the feature branch and move them on top of master commits. The graph structure of the commits looks like this

Git rebase
Command to rebase fetaure_branch with master branch is:

git checkout master
git rebase feature_branch
Enter fullscreen mode Exit fullscreen mode

Advantage of git rebase :

It keeps the commit history of the main branch clean and hence it becomes easy to track

Disadvantage of git rebase :

The detailed branch history is no longer available.

So using squashing of commits and then rebaseing with master will keep the commit history clean and trackable.

Top comments (0)

🌚 Life is too short to browse without dark mode