Git Cherry-Pick
git cherry-pick is the "surgical" tool of Git. It allows you to select a specific commit from one branch and apply it to another without merging the entire branch history.
🍒 Why Use Cherry-Pick?
- Hotfixing: Pulling a critical bug fix from a development branch into a stable production branch.
- Selective Features: Extracting a specific utility or fix from a feature branch that isn't ready to be merged.
- Recovery: Restoring a commit that was lost during a complex rebase or after a branch deletion.
1. The Core Workflow
To cherry-pick a commit:
- Find the Commit Hash: Locate the ID of the commit you want (e.g.,
git log). - Switch to Target: Check out the branch where you want the change applied.
git switch main - Apply the Change:
git cherry-pick 1a2b3c4
2. Comparison: Cherry-Pick vs. Merge vs. Rebase
| Method | Scope | Impact |
|---|---|---|
| Merge | Whole Branch. Combines all commits and histories. | Preserves history; creates a merge commit. |
| Rebase | Whole Branch. Replays all commits on a new base. | Cleans history; rewrites existing commits. |
| Cherry-Pick | Selective Commit. Pulls only one specific change. | Creates a duplicate commit with a new ID. |
3. Handling Conflicts
If the code you're cherry-picking overlaps with changes on your current branch, a conflict will occur.
Resolution Steps
- Identify: Run
git status. - Fix: Manually resolve markers in the files.
- Continue:
git add <file> git cherry-pick --continue - Abort: If it's too messy, run
git cherry-pick --abort.
4. Advanced Flags
git cherry-pick -n(No Commit): Applies the changes to your working directory and staging area, but does NOT create a commit. This is useful for combining several cherry-picks into one.git cherry-pick -e(Edit): Allows you to edit the commit message before finalization.
[!WARNING] Duplicate Commits Cherry-picking creates a new commit with a new hash, even if the code is identical. If you later merge the original branch, Git is usually smart enough to handle the duplicate, but excessive cherry-picking can lead to a cluttered and confusing history. Use it for surgical fixes, not for regular feature integration.