Sometimes you need to transfer specific changes from a feature branch (e.g., dev) to a stable branch (e.g., main) without bringing over all subsequent development. This often involves:
- Cherry-picking selected commits from dev onto main.
- Rebasing dev to "fast-forward" its base to the newly updated main branch, making dev appear to branch from a later point.
This method results in a clean, linear history on main, making it easier to track specific feature integrations.
Important Note: This workflow rewrites the history of the dev branch. If dev is a shared branch that other team members are actively working on, performing a rebase will cause significant headaches and potential data loss for them. Only use this strategy on private or unshared branches.
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