Git: The power of rebasing onto

The problem

Since I’m a benevolent and well-organised engineer, I always try to keep my Pull Requests (PR) quite small and focused on a single topic. The thing is, when I’m working on something big, I’m stacking PRs, like :

git checkout main
git branch branch-1
git commit -m "#1"
git commit -m "#2"
git commit -m "#3"
# Opening a PR and wait for my nice colleagues to review it.
git branch branch-2 # I'm branching from `branch-1`
git commit -m "#1"
...

This way, branch-2 contains every single commits from branch-1.
The big work comes when branch-1 is squashed & merged on main with a single merge commit.

Before, I was putting myself in a git-hell:

git checkout main
git pull
git checkout branch-2
git rebase main

Say hello to the conflicts !
When feeling brave, I was trying a hazardous git rebase -i knowing that in case of another git drama, I could always count on git reflog.

Well, you know what? there’s a better, easier way!

The solution

One can simply use rebase --onto to specify the exact starting point we want to set. In our example it will look like:

git checkout main
git pull
git checkout branch-2
git rebase --onto main branch-1 branch-2

🤯 boom! Don’t thank me 😏