What is git cherry-pick and when to use it?
git cherry-pick takes changes from a specific commit and applies them to the current branch, creating a new commit with the same changes. This is useful when you need to transfer an individual change without merging the entire branch.
When to use: you made a fix in a feature branch but it's also needed in main — cherry-pick transfers only that commit. Or you accidentally committed to the wrong branch — cherry-pick moves the commit to the correct branch. Also for transferring hotfixes between release branches: cherry-pick a fix from main to release-1.2.
How to use: switch to the target branch (git checkout main), then git cherry-pick <commit-hash>. Git applies the changes from the specified commit and creates a new commit in the current branch. The new commit's hash will be different, but the changes and message are the same. You can transfer multiple commits: git cherry-pick <hash1> <hash2> <hash3> or a range: git cherry-pick <hash1>..<hash2>.
Conflicts during cherry-pick: if the code around the changes differs between branches, a conflict will occur. Resolve it as with a regular merge: edit files, git add, git cherry-pick --continue. To abort: git cherry-pick --abort.
Difference from merge: merge combines the entire branch with all commits. cherry-pick transfers only specified commits. Difference from rebase: rebase moves all commits of a branch on top of another. cherry-pick is a targeted transfer.
Caution: cherry-pick creates a duplicate commit with a new hash. If you later merge the branch from which you cherry-picked, conflicts may arise due to identical changes. Try to cherry-pick only when merge or rebase is impossible or impractical.
Practical scenario: you fixed a critical bug in develop, but it needs to be urgently delivered to main. git checkout main, git cherry-pick <fix-commit-hash>, git push. The fix is in main without merging the entire develop branch.