Advanced Git #1

Keep your commit history clean with rebase

Yannick Wittwer
3 min readJun 13, 2022

Probably every developer has worked in a project where the commit history looked something like this.

Simple commit history

For a small project this might not be a big issue, but let’s assume we are working on quite a big project with several teams working in the same Repository adding a couple of features every month. In this Situation, the commit history will get quite messy pretty fast.

Wouldn’t it be nice, if there would be just one commit per Ticket (I will take “ticket” from here on since we all work with them daily)? If yes, let’s go through an example of how to achieve this with git-rebase.

Step by Step example

We assume that we are currently on our feature branch and just finished developing, the next step would be to create a pull request for our Team to review. But since we want to deliver a clean commit history with a good commit message, we have to rebase our history.

So you go to your Terminal and type:

git rebase -i HEAD~5

The number 5 stands for the number of commits we want to rebase. After executing the command you should see something like this in your terminal:

All 5 commits are listed and underneath you can see the possible commands you can use to manipulate your commit history. For this post we will stick to the “reword” and the “fixup” commands.

Out Goal is to have just one commit with a high quality commit message. So we use our Terminal and update the commands on the left as following:

We will “fixup” all commits except the first one, this one we will “reword” to a high quality commit message. After editing the history, we will go to the next step (Depends on your Terminal editor how to achieve this). If everything worked you will see this screen.

In here you can edit your final super high quality commit message. After editing the commit message just go on as in the previous step. You should get to your normal terminal view.

Now to complete the rebase and sync it to the repository just run:

git push -f

Take caution with this on critical branches, since you can do a lot of damage to the repo if you messed up with something during the rebase process. This command will override the edited history in your remote repository. If everything worked as expected your commit history should look like this.

With this concept you have very minimal effort to have a super clean and readable commit history in any project.

Keep in mind, thats just one use case for git rebase and there are way more. You can find the official docs here:

Thanks for reading ❤️, I hope you learned something new for your day to day work. let me know in the comments, if you would like to get more short articles about advanced git stuff.

--

--

No responses yet