DevOps
Git
Git Cherry-Pick

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:

  1. Find the Commit Hash: Locate the ID of the commit you want (e.g., git log).
  2. Switch to Target: Check out the branch where you want the change applied.
    git switch main
  3. Apply the Change:
    git cherry-pick 1a2b3c4

2. Comparison: Cherry-Pick vs. Merge vs. Rebase

MethodScopeImpact
MergeWhole Branch. Combines all commits and histories.Preserves history; creates a merge commit.
RebaseWhole Branch. Replays all commits on a new base.Cleans history; rewrites existing commits.
Cherry-PickSelective 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

  1. Identify: Run git status.
  2. Fix: Manually resolve markers in the files.
  3. Continue:
    git add <file>
    git cherry-pick --continue
  4. 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.