I find myself in the following scenario with Git every so often:
- From the main branch, I create and checkout branch A
- On branch A, I do some work, create some commits, etc., then push my changes
- I need to do some unrelated work, so I create and checkout branch B
- I create some more commits on branch B and push
- I go to create a PR and... oops. I Created branch B from branch A, so suddenly I have all these irrelevant commits from branch A in my PR. I needed to create branch B from the main branch instead.
Just wondering what the best workflow is here. Sure, I can delete branch B, create it again and replicate my commits, but that seems tedious. A rebase is not an option, as I have already pushed to a remote repo. Maybe I can revert all the commits that were carried over from branch A to B? Maybe I should just create an alias that will checkout main before creating the branch?
CodePudding user response:
Simplest solution: rebase onto
git rebase
has the onto mode to do exactly what you want:
git rebase --onto main A B
will take B off of A and rebase it onto main.
If you have B checked out when you run this, you don't need to specify it on that rebase command line.
Cherry Pick option You can also do it with a cherry pick operation.
Create a new branch off of the right place, cherry pick all the commits from B onto it, and then reset B to it afterwards.
git checkout main # or where the branch should start from
git checkout -b B-new # pick a new name, you'll need access to both B and B-new
git cherry-pick A..B # cherry pick all commits on B not on A
Now B-new
is the branch you wanted to create in the first place. You can just use the new name, or if you want to keep the name B
, reset it to B-new
:
git checkout B
git reset --hard B-new
And clean up, since you no longer need B-new
now:
git branch -d B-new
But all that is doing exactly what the rebase onto did...