git cherry-pick
is a command used to apply a specific commit from one branch to another. It allows you to pick and apply a single commit's changes onto another branch without having to merge the entire branch.
Example Scenario : Suppose you have the following commit history:
E --- F (feature)
/
A --- B --- C --- D (main)
Commit A : Initial state
Commit B : Added initial feature
Commit C : Bug fix on main
Commit D : Another feature on main
Commit E : New feature on feature branch
Commit F : Bug fix on feature branch
You want to apply the bug fix introduced in commit C onto the feature branch.
Using Git Cherry-Pick :
Identify the Commit to Cherry-Pick :
First, identify the commit you want to cherry-pick. In this case, it's commit C.
Checkout the Target Branch :
git checkout feature
Switch to the branch where you want to apply the cherry-picked commit.
Cherry-Pick the Commit :
git cherry-pick C
This applies the changes introduced in commit C onto the
feature
branch.
Resulting commit history :
E --- F --- C' (feature)
/
A --- B --- C --- D (main)
- Commit C': Cherry-picked bug fix from commit C
Explanation :
By using git cherry-pick C
, you applied the changes from commit C to the feature
branch, resulting in a new commit C' on the feature branch. The commit C' contains the same changes as commit C but has a different commit hash because it's a separate commit.
Diagrams:
Original commit history :
E --- F (feature)
/
A --- B --- C --- D (main)
After using git cherry-pick C
:
E --- F --- C' (feature)
/
A --- B --- C --- D (main)
git cherry-pick
is a useful command for selectively applying changes from one commit to another branch. It's particularly handy when you want to bring specific changes from one branch into another without merging the entire branch. Keep in mind that the cherry-picked commit will have a new commit hash, and you should ensure that the changes are still valid in the new context.