DEV Community

loading...

How to clean your commits with Git rebase

asteryujano profile image François Originally published at blog.lepape.me on ・2 min read

You know that moment when you are in local, trying to code a first version of a task. But then you need to checkout on another branch for a reason (fix/check something/continue to work on something else)?

Well, you need to stop what you were working on and it happens that you don't have a proper commit message to write. So you come up with a quick message not very informative: "save", "changes" or whatever.

And it happens several times. So you end up with a messy git directory.

When comes the day where your fix/feature is ready for a Pull Request, you check your git history. And it is dirty. Very dirty. You know what I mean?

Well if you are still in your local environment you can fix this problem: the holy and feared git rebase.

Git rebase

Warning: Rebasing on a branch shared with others can lead to serious problems. Read more advanced posts about it, this post is only about local rewriting/cleaning.

If you are in local and didn’t pull/push any changes, you can use:

git rebase -i HEAD~n

# with n the number of commits to group together
# -i stands for interactive, you can manually pick and squash, rewrite, ... commits
Enter fullscreen mode Exit fullscreen mode

For instance, let’s say I want to group these 2 commits:

commit xxxxxae742qwdqdj12xx78xxxxxxfxxxxxd70w (HEAD -> feature/add-the-best-feature)
Author: Francois <francois@mail.me>
Date:   Tue Dec 1 00:17:45 2020 +0100

    progress

commit yyyyyxqwqwjhbdhwqyyyyyyy57893yyyndd3er
Author: Francois <francois@mail.me>
Date:   Wed Nov 25 10:35:42 2020 +0100

    start to work
Enter fullscreen mode Exit fullscreen mode

The steps to group them together and clean the git logs. git rebase -i HEAD~2

And replace the pick of commit yyyyy with a squash (an interactive menu should appear to you)
and then saved/exit.
This will allow you to modify the commit message. For instance, I will use: “feat: Work on this amazing feature”.

Once you save you should see the following in git log:

commit 123456789012345678945678 (HEAD -> feature/add-the-best-feature)
Author: Francois <francois@mail.me>
Date:   Wed Nov 25 10:35:42 2020 +0100

    feat: Work on this amazing feature
Enter fullscreen mode Exit fullscreen mode

Et voila 🙂

Discussion (0)

pic
Editor guide