Home > Software engineering >  How to rebase a branch in git one revision closer to head of other branch?
How to rebase a branch in git one revision closer to head of other branch?

Time:06-08

I'm currently working on bringing 2 long diverged branches feature/A and feature/B of one project back together. They accumulated many confilicting changes in the meantime. Rebasing one on top of the other is infeasible because so much has changed.

Therefore I'm iteratively rebasing feature/B one commit closer to the head of feature/A. I'm using a branch called feature/rebase-target that tracks the commit on feature/A where I'm currently rebasing feature/B on. My workflow basically is:

  1. git checkout feature/rebase-target && git rebase <sha-1 of the next commit towards feature/A head>
  2. git checkout feature/B && git rebase feature/rebase-target
  3. fix conflicts and continue rebase until done
  4. manually find the next sha-1 by looking into the log of feature/A

How can I automate the search for the sha-1 that is one commit closer to the head of feature/A based on the current position of feature/rebase-target?

CodePudding user response:

You can do it like this:

next_target=$(git rev-list feature/rebase-target..feature/A | tail -n1) &&
git branch -f feature/rebase-target "$next_target"

This assumes that the history is linear. If you have merges in the branch leading up to feature/A, add --first-parent.

Note that rev-list --reverse -1 does not work, because that would first restrict the normal list to one commit, and then reverse the output (which makes no difference if only one is listed).

Note further that in your step 1 you do not have to checkout followed by rebase (which is a fast-forward if I understand the situation correctly); you can just use git branch -f instead.

  • Related