Cherry picking is the act of picking a commit from a branch and applying it to another.
Even though git cherry-pick is just a single command, it needs a whole process to get that right. So below are the list of commands need to be executed to have a successful cherry picking 😊
Step:1
Clone the remote repository in to local machine and change the root to your repository.
git clone remote_repo
cd local_repo
eg:
$ git clone https://github.com/ravi-kolla/git-cherry-pick.git
$ cd git-cherry-pick
Step: 2
Checkout the branch you have changes in and pull all the commits from remote repo.
$ git checkout branch_with_commit
$ git pull //pulls all the commits from from your branch
Step: 3
Checkout the branch you want to add the changes
$ git checkout branch_to_add_changes
$ git pull
*//pull all the commits to make sure your new branch is up to date before adding new changes*
Step: 4
Cherry pick a commit which you want to be added to the new branch by passing commit hash
$ git cherry-pick #commit-hash
$ git cherry-pick 29cebd92
Step: 4.1 (Incase if you get merge conflicts on executing git cherry-pick)
Lets say after executing step:4, you came across bellow error 😒
$ git cherry-pick 29cebd92
error: could not apply 29cebd92… commit_message
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 commit’
check git status to identify the conflicts and resolve the files mentioned as both modified.
$ git status
On branch pre-release
Your branch is up to date with ‘origin/pre-release’.
You are currently cherry-picking commit 29cebd92.
(fix conflicts and run “git cherry-pick — continue”)
(use “git cherry-pick — abort” to cancel the cherry-pick operation)
Changes to be committed:
modified: file-path/sample.css
new file: file-path/sample.js
new file: file-path/sample.txt
Unmerged paths:
(use “git add <file>…” to mark resolution)
both modified: file-path/main.js
both modified: file-path/main.css
Once the merge conflicts are resolved add those files to git and then continue with git cherry-pick.
$ git add file-path/main.js file-path/main.css
$ git cherry-pick --continue
Step: 5
You’re all set to push the cherry picked commit(s) to your new branch 😄
$ git push //commits you selected will be pushed to the new branch
Additional info..
$ git cherry-pick A^..B
where A is the commit hash you want to start from (the ^ will include commit A instead of starting at next commit after A) and B is the commit you want to end after being applied.
$ git log --oneline
Gives you list of commits in single line so you can easily select commit hash codes for cherry picking.
Top comments (0)