Cherry-picking in Git allows you to apply specific commits from one branch to another without merging the entire branch. This is useful for selectively integrating changes.
Cherry-picking is the process of taking a specific commit from one branch and applying it to another. It lets you:
- Pick individual commits without merging the entire branch.
- Fix bugs or apply changes from one branch to another selectively.
- Bug Fixes: Apply a critical fix from a feature branch to
main
. - Selective Features: Bring specific features or updates from another branch.
- Undo Mistakes: Reapply changes from a reverted commit.
git cherry-pick <commit-hash>
Consider the following branches:
A --- B --- C (HEAD)
X --- Y --- Z (HEAD)
If you cherry-pick commit B
from feature
to main
, the result is:
X --- Y --- Z --- B'
List the commits in the source branch:
git log --oneline
Copy the hash of the commit you want to cherry-pick.
Switch to the target branch and apply the commit:
git checkout main
git cherry-pick <commit-hash>
If conflicts arise:
- Open and resolve the conflicting files.
- Stage the resolved files:
git add resolved_file.txt
- Complete the cherry-pick:
git cherry-pick --continue
To abort the cherry-pick:
git cherry-pick --abort
To cherry-pick multiple commits:
- Use individual hashes:
git cherry-pick <hash1> <hash2> <hash3>
- Cherry-pick a range of commits:
git cherry-pick <hash1>^..<hash3>
If you need to undo a cherry-picked commit:
git revert <commit-hash>
You can use interactive rebasing to cherry-pick commits:
- Start an interactive rebase:
git rebase -i <base-branch>
- Select and reorder the commits you want to apply.
- Minimize Conflicts: Keep the source and target branches up-to-date to reduce conflicts.
- Document the Reason: Use meaningful commit messages to explain why the commit was cherry-picked.
- Verify Changes: Test the branch after cherry-picking to ensure functionality.
Command | Description |
---|---|
git cherry-pick <hash> |
Apply a specific commit to the current branch. |
git cherry-pick <hash1> <hash2> |
Apply multiple commits. |
git cherry-pick <hash1>^..<hash2> |
Apply a range of commits. |
git cherry-pick --continue |
Continue after resolving conflicts. |
git cherry-pick --abort |
Cancel a cherry-pick. |
Find the commit hash from the source branch:
git log feature --oneline
git checkout main
git cherry-pick <commit-hash>
Run tests to ensure the changes work as intended.
- Frequent Use: Excessive cherry-picking can lead to a fragmented history.
- Public Commits: Avoid cherry-picking public commits that might cause confusion for collaborators.
Cherry-picking is a powerful tool for applying specific commits across branches without merging. When used appropriately, it ensures targeted changes while maintaining control over your repository.
Next Steps: Stashing Changes