I started working on a project by creating a new branch off masters
with git checkout -b MyBranch
and then I did several commits (no push yet).
What I should have done instead was start from the Secondary
branch. So, how can I make my branch a sub-branch of Secondary
, and merge (is that the right term?) the code from Secondary
into mine, for later merging. So how do I fix it?
Is that a job for rebase
? I'm still very confused by git
terminology...
In your scenario, git merge
and git rebase
would fix the situation, but in very different ways.
If you decide to merge MyBranch
into Secondary
, your history would look less linear, and a bit more messy. You would have a branch (MyBranch
) stemming from masters
, that besides brining the changes intended for Secondary
, would also carry (possibly unwanted) changes from masters
.
A merge approach could, not only make unwanted changes available on Secondary
, but would also make your history look more intertwined and difficult to read. This is definitely not the best way to recover from your situation.
On the other hand, a git rebase could be what you're looking for, as you could transplant the set of commits you desire on top of Secondary
with the --onto
option.
git rebase --onto Secondary masters..MyBranch
Another approach could be using the cherry-pick
command, where you basically re-write the commits between masters
and MyBranch
on top of an auxiliary branch (MyBranch2
) that branches off Secondary
. Then, force-delete MyBranch
, and finally rename MyBranch2
into MyBranch
.
# create a new branch MyBranch2 off Secondary
git branch MyBranch2 Secondary
# select the branch MyBranch2
git checkout MyBranch2
# rewrite every commit made between Masters and MyBranch on top of MyBranch2
git cherry-pick masters..MyBranch
# force-delete MyBranch as it's not necessary anymore.
# Its changes have been replicated on top of MyBranch2.
git branch -D MyBranch
# rename MyBranch2 to MyBranch
git branch -m MyBranch2 MyBranch