DEV Community

Cover image for Stop merging the main branch into your feature branch! Try rebasing
Ayush Poddar
Ayush Poddar

Posted on • Originally published at poddarayush.com

Stop merging the main branch into your feature branch! Try rebasing

πŸ“ This post is part of my "Shorts" series. Each post in this series is hyper-focused on a single concept and should take less than 1 minute to read.

If you have ever worked in a software development team, you must have faced a situation where a bug fix is present in the main branch and you require it in your feature branch to progress.

A trivial way to solve this problem is to merge the main branch into your feature branch. But, this leads to a dirty commit history in your feature branch. Your feature branch will consist of few (or many) commits that are unrelated to your task.

What if?

What if you could create a new branch of the HEAD of the main branch and migrate all your feature branch commits into the new branch?

This would give you two-pronged benefits:

  • You will have the bug fix in your β€œnew” feature branch
  • You will have a clean commit history in your feature branch.

Using git-rebase

You can use the following command to get this desired result:

git rebase <branch-to-rebase-to>

Enter fullscreen mode Exit fullscreen mode

Mostly, you’ll be using git rebase main, which means that your feature branch’s history will be rewritten such that the base of your feature branch will be altered to the HEAD of the main branch.

The green commits form after the rebase

Caveat

Since this command rewrites history, you may have to use the --force flag when pushing your changes in the feature branch to the remote repository.

Sources

Top comments (0)