1. Real-World Scenario: 11 PM, Prod Crashes, and a Mess of Unfinished Code
It is 11 PM. You just took a sip of water and were about to shut down your laptop when Slack explodes with notifications: the payment gateway on production (the main branch) is completely down. With every passing minute, the company is losing thousands of dollars in revenue.
Your team lead calls urgently asking for your help. After a quick investigation, you suddenly remember fixing that exact logic bug earlier this morning on the develop branch in a small commit. That sounds like a relief, but checking the develop branch makes you break into a cold sweat: it currently contains over 20 new feature commits from 4 other teammates—all half-finished code that has not been verified by QA.
Merging the entire develop branch into main right now would be suicidal. Other services would almost certainly break. Yet rewriting the fix from scratch on a new branch takes too long, and the risk of missing critical logic is dangerously high.
2. Technical Deep Dive: Why Merge and Rebase Fall Short
Git manages history as a Directed Acyclic Graph (DAG). Each commit does not merely store file changes; it also records the hash of its parent commit.
Two common Git operations immediately backfire here:
git merge develop: Brings every single commit from the branch fork point up to the present intomain. Git does not support an option to "merge only one single commit".git rebase: Rewrites history by moving the base of the entire branch. Rebasing shared branches likemaindisrupts the entire team's commit tree and triggers cascading conflicts.
This scenario calls for a surgical operation: extract only the diff of a single commit, ignoring the entire surrounding history chain. That is precisely the purpose of cherry-pick.
3. Approaches for Cherry-Picking Code Across Branches
Method 1: Inspect the Diff and Copy-Paste Manually
Junior developers often open GitHub to view the diff of the old commit and manually copy-paste line by line onto a new branch. This manual approach is fraught with risk. It is easy to miss files, introduce indentation discrepancies, and completely lose the original commit message and author metadata.
Method 2: Use git format-patch and git apply
You can export a commit to a physical patch file and apply it to another branch:
# Generate a patch file from commit a1b2c3d
git format-patch -1 a1b2c3d
# Switch branch and apply the patch
git checkout main
git apply 0001-fix-payment-bug.patch
This mechanism is widely used in open-source projects like the Linux kernel where developers collaborate over email. However, in day-to-day enterprise sprint cycles, generating intermediate files only to delete them later adds unnecessary friction.
Method 3: Use git cherry-pick (Recommended)
Git provides the git cherry-pick command to solve this exact problem. The command calculates the diff introduced by the specified commit and applies it directly to the tip of your current branch as a brand-new commit:
git checkout main
git cherry-pick a1b2c3d
The file changes and commit message are preserved intact. The only difference: the new commit receives a fresh SHA hash because its parent commit and commit timestamp have changed.
4. A 4-Step Workflow to Safely Ship Hotfixes to Production
Never cherry-pick directly into your local main branch and push straight to the server. A single slip-up could trigger a broken build via the CI/CD pipeline immediately. Instead, follow this standardized workflow based on proven Git branching strategies:
Step 1: Retrieve the Commit SHA from the Source Branch
Switch to the branch containing the fix and view the condensed log:
git checkout develop
git log --oneline -n 5
The terminal displays the commit list:
f7e8d9c (HEAD -> develop) feat: work in progress on cart feature
a1b2c3d fix(payment): fix null pointer when checking out zero-dollar orders
4e5f6a7 feat: add new notification UI
The commit SHA you need to save is a1b2c3d.
Step 2: Create a Hotfix Branch from the Latest Production Code
Always pull the latest production code locally before proceeding:
git checkout main
git pull origin main
# Create an isolated hotfix branch
git checkout -b hotfix/fix-payment-null-pointer
Step 3: Execute Cherry-pick and Resolve Conflicts
Run the command to apply the changes to the newly created hotfix branch:
git cherry-pick a1b2c3d
If the payment file on main has diverged from develop, Git will halt and report a conflict:
error: could not apply a1b2c3d... fix(payment): fix null pointer bug
hint: after resolving the conflicts, mark the corrected paths
hint: with 'git add <paths>' or 'git rm <paths>'
hint: and commit the result with 'git cherry-pick --continue'
The resolution process is straightforward:
- Open your editor (VS Code, WebStorm) and locate the files marked with
both modified. - Keep the intended bug-fix logic and clean up the conflict markers:
<<<<<<<,=======,>>>>>>>. - Save the file, mark it as resolved, and continue the cherry-pick process:
git add services/payment.js
git cherry-pick --continue
Pro tip: If the conflict is too messy or poses a risk of breaking other logic, run git cherry-pick --abort to restore the branch to its clean initial state.
Step 4: Run Tests, Open a Pull Request, and Backport Changes
Before pushing code, run the full relevant test suite locally:
npm test -- services/payment.test.js
git push origin hotfix/fix-payment-null-pointer
Create a Pull Request from the hotfix branch into main so that at least one teammate can peer-review it. With branch protection rules prohibiting direct force pushes, the main branch stays well-guarded.
Do not skip the final step: Once the hotfix is successfully deployed to production, merge or cherry-pick this hotfix branch back into develop. This backport ensures the bug does not suffer a regression in subsequent releases.
Bonus: Picking Multiple Commits at Once
In practice, a patch might span two or three commits. You can batch them using flexible syntax options (leveraging Git's ^ and ~ operators):
# 1. Pick multiple discrete commits
git cherry-pick a1b2c3d 4e5f6a7
# 2. Pick a range from after commit A up to commit B (excluding A)
git cherry-pick A..B
# 3. Pick an inclusive range from commit A through commit B
git cherry-pick A^..B
# 4. Apply changes to the working directory without committing immediately
git cherry-pick -n a1b2c3d
The -n (no-commit) flag is especially handy when you want to squash three small bug-fix commits from a test branch into a single, clean commit on production.
