Sub topic 15
Cherry-picking a commit
This chapter assumes you can create and switch branches, read git log, and merge. It covers applying one commit from another branch onto your current branch.
What cherry-pick does
git cherry-pick takes the change introduced by one existing commit and applies it to the current branch as a new commit. Git computes the diff between that commit and its parent, then applies that diff on top of HEAD. The new commit has the same message and author as the original. It has a different parent, so it gets a different hash.
Use it when you need one commit and not the whole branch. A common case is a bug fix made on main that must also go into a maintenance branch such as release/1.0.
git switch release/1.0
git cherry-pick <commit-sha>Find the SHA with git log --oneline main. The branch you are on receives the new commit. The source branch is not changed.
Useful options
| Command | Effect |
|---|---|
| `git cherry-pick A B C` | Applies several commits in the order given. |
| `git cherry-pick A..C` | Applies the commits after A up to and including C. |
| `git cherry-pick -x <sha>` | Appends "(cherry picked from commit ...)" to the message. |
| `git cherry-pick -n <sha>` | Applies the change to the working tree and index without committing. |
The -x option helps later readers trace where a backported fix came from. Use it when the source commit is on a shared branch.
Resolving conflicts
A cherry-pick can conflict if the target branch has changed the same lines. Git stops and marks the files with <<<<<<<, =======, and >>>>>>>, as in a merge. Fix the files, stage them, and continue.
git add path/to/conflicted-file
git cherry-pick --continueTo give up and return to the state before you started, run git cherry-pick --abort.
Common errors
- Duplicate changes. The picked commit is a copy, so Git does not know it matches the original. If you later merge the two branches, the same change can appear to be applied twice. It usually merges cleanly when the content is identical, but it can conflict if either side edited the lines further.
- Missing dependencies. The commit may rely on earlier commits that you did not pick. The result can conflict or compile incorrectly. Check that the change makes sense on its own.
- Picking a merge commit. Git refuses unless you choose which parent to treat as the mainline with
-m 1. Prefer picking the underlying commits. - Overuse. If you find yourself picking many commits from one branch, a merge or rebase is usually the better tool.
Exercise
You fixed a bug in commit a1b2c3d on main. You need the same fix on release/1.0 without bringing in any other main commits, and you want the new commit's message to record its origin. Which commands do you run?
Show answer
Run git switch release/1.0 and then git cherry-pick -x a1b2c3d. The -x option appends the original commit hash to the message. If a conflict occurs, fix the files, run git add on them, and then run git cherry-pick --continue.