How I use git rebase (Part 1 — Squash Commits)
If you are a developer, you may have been using or at least heard of Git.
In this article as a part of a series of how I use git rebase in my day to day work, I will cover how to squash commits and make git history clean.
- sh
1 |
|
Set up a project
We will set up a project which will contain a text file.
Let’s add demo.txt file in the first commit with one line text as shown below.
- text
1 |
|
Our git log looks like below:
Develop Feature
Now let’s create a feature branch and we will add a new feature (again, some arbitrary lines)
- sh
1 |
|
We added the second commit and after that, our git logs looks like below:
After we committed our feature, we realized that we forgot to add a line (that could be anything like Null Check, edge case scenario, etc.)
So, we quickly added a new line and made another commit. At this point, our demo.txt file looks like below:
1 |
|
and our git history tree looks like:
YES, YOU GUESSED IT RIGHT
while trying to complete the feature faster, we made typos in our file.
We have to fix the typos and make another commit. After the fix, demo.txt file will have a complete feature (second-line).
1 |
|
and our git history tree looks like:
With our feature is completed, we can push this code to the remote repository. However, You can see, we made 3 commits to complete one feature. We are usually good with this kind of commits history. However, I’d like not to show my mistakes.
Imagine if we can change these 3 commits into single commit to reflect that second-line feature was developed in a single attempt?
In order to achieve the above objective, I need to clean the last 3 commits from where my HEAD is.
- sh
1 |
|
This will prompt the editor like below:
We can see available Commands in the comment in above screenshot.
We will squash commits 9edb6bd and 01e955c into faba150. Instead of picking commits 9edb6bd and 01e955c, we will put command squash (or short command s) in front of these commits.
and save this file. (Usually, this prompt opens in Vim editor, so we can save it using :wq command)
This will squash given commits and open prompt to let you re-write commit message.
In the first line, we can see that this commit will be a combination of 3 commits. Although this is good enough to save and push your second-feature to remote origin, I rewrite a commit message to reflect a feature I just developed.
let’s save this file and we will get confirmation on successful rebase.
Let’s have a look at our git history.
Yayy, Now that we’ve removed the track of our mistakes, we can push this feature to the remote repository.