How to moving commits from one branch (e.g., dev) to another branch (e.g., main), then rebasing the dev branch to reflect the new branching point.
Goal:
Before After
A---B (main) A---B---C'---D' (main)
\ \
C---D---E (dev) E' (dev)
Step 1: Apply C and D to main
-
Switch to the
mainbranch:git checkout main -
Identify the commit hashes for C and D on the dev branch.
Use
git log devto see the commit history ofdev. Look for the commit messages corresponding to C and D and note down their full commit hashes. Let's assume:- Commit C hash:
commit_C_hash - Commit D hash:
commit_D_hash
- Commit C hash:
-
Cherry-pick C and D onto
main:git cherry-pick commit_C_hash git cherry-pick commit_D_hashNow, the main branch will look like: A---B---C'---D'
Before After A---B (main) A---B---C'---D' (main) \ \ C---D---E (dev) C---D---E (dev)
Step 2: Make dev know it's branched from main at D
This is achieved by rebasing dev onto the new head of main (which is now D).
-
Switch back to the dev branch:
git checkout dev -
Identify the commit hashes for D' on the main branch.
-
Rebase
devontomain:git rebase --onto commit_D'_hash commit_D_hashMore on
rebase --onto: https://womanonrails.com/git-rebase-ontoNow, the goal is reached.
Before After A---B---C'---D' (main) A---B---C'---D' (main) \ \ C---D---E (dev) E (dev)
Step 3: Push changes to remote repositories
❗Do not force push until you are sure about the result.
git push --force-with-lease dev