Home > Software engineering >  update branch to have history starting at an unrelated branch commit
update branch to have history starting at an unrelated branch commit

Time:08-13

I'm trying to achieve a specific outcome and have tried a bunch of things, I'm hoping what I want is possible.

Before taking any actions, here's my test setup (illustrated below) I have two unrelated branches (LeftBranch and RightBranch). I want to create a new branch called Main that starts half way up LeftBranch and replays all of the commits from RightBranch on top.

before rebase

In the end I want the resulting structure to look like:

a -> b -> d* -> e* -> f* (RB) (Main)
       \
         -> c (LB)

* I understand that d, e and f will have a new git sha. That has no negative impact on my use case.

So far everything I've tried either results in:

a -> b -> c (LB)
      \
       -------------------- merge (Main)
                          /
              d -> e -> f (RB)

Which is okay but not perfect as the history of d is not actually attached to b like I want.

Or I end up with:

a -> b -> c (LB)
d (Main) -> e -> f (RB)

When I try to rebase main from b onto d; which is just not at all what I want.

Thanks for any help.

CodePudding user response:

It should be possible like this:

git checkout b
git cherry-pick d # this should not give us any problem if d introduces files that are _not_ the same as the ones in present in revision b
git cherry-pick d..f

Now you should have something like what you are asking. You could create a new branch or you might setup rightBtranch and main (as your graph shows as the desired result)

git branch -f main
git branch -f rightBranch

CodePudding user response:

git checkout -b Main RightBranch
git rebase --root --onto ab35ed3

is the quickest to type, if the rebased history is large and independent you might do better with a graft and filter-branch.

Demo of the above sequence:

# replicate your setup:

git init -b LeftBranch rebasedemo; cd $_
seq 3 | tee a b >c; git add .; git commit -m-
git checkout --orphan RightBranch; git commit -m-
for f in *; do sed -i 3s,$,right, $f; git commit -am$f; done
git checkout LeftBranch
for f in *; do sed -i 1s,$,left, $f; git commit -am$f; done

# payload:

git checkout -b Main RightBranch
git rebase --root --onto LeftBranch~

CodePudding user response:

git rebase --onto

I think what you want is a rebase. There are a few different kinds of rebase, and maybe you haven't performed this kind before.

Here's the syntax:

git rebase --onto NEW_BASE OLD_BASE BRANCH_TO_RELOCATE

What this does is pick up your entire branch and move it to a different place.

  • Do you wish you had cut your feature branch from a different place? This does that.
  • Does your branch need new things that were added to the base branch after you cut your branch? This fixes that.
  •  Tags:  
  • git
  • Related