Sobes.tech
Junior

What is cherry-pick?

sobes.tech AI

Answer from AI

git cherry-pick is used to transfer one or more commits from one branch to another.

How it works:

  1. Selects the specified commit (or commits) in the source branch.
  2. Applies the changes contained in these commits to the current active branch.
  3. Creates new commits in the current branch with the same changes and messages as the original commits.

When to use:

  • Transferring a specific bug fix from one branch (e.g., production) to another (e.g., development) without affecting other changes.
  • Applying changes from one feature branch to another without merging them entirely.
  • Reverting an incorrect merge while preserving individual commits.

Differences from merge and rebase:

  • merge: Combines the entire change history from one branch into another.
  • rebase: Rewrites the commit history, moving commits onto a new base.
  • cherry-pick: Applies only selected commits, creating new commits without altering the original commit history.

Main commands:

# Transfer a single commit
git cherry-pick <commit-hash>

# Transfer multiple commits (in the order specified)
git cherry-pick <commit-hash-1> <commit-hash-2> ...

Example:

Suppose there are two branches: main and feature. A commit fix-typo has been made in the feature branch. You need to transfer this commit to the main branch.

# Switch to the target branch
git checkout main

# Perform cherry-pick using the commit hash from the feature branch
git cherry-pick 7f3bca2 # Example commit hash

After executing the command, a new commit with the same changes as fix-typo will appear in the main branch, but with a different hash.