DEV Community

SeongKuk Han
SeongKuk Han

Posted on • Updated on

git cherry-pick: How to pick commit(s) from other branches?

We tag a commit in main and push it to the remote, this is what our team does when deploying.
Recently, something went wrong with our service.

Branch main dev
^ A1 C1
~2 A2 C2
~3 A3 (tagged as v0.1 and deployed) C3
~4 A4 A1
~5 A5 A2

I will use this to explain.
A3 is a stable version. we tagged A3 with v0.1 and deployed it. Within a few hours we found that A4 had some problems. I recreated a feature of A4 in C1 and C2 commits. I had to remove A4 from the server and add C1 and C2 commits.

I searched online how to solve this problem and I had found
the command cherry-pick.

git cherry-pick [commit]
Enter fullscreen mode Exit fullscreen mode

I will produce the situation and show you how to fix it step by step.


Git Log

commit_log

1. Make a new branch named 'bug-fix'

git checkout -b bug-fix
Enter fullscreen mode Exit fullscreen mode

make_branch

2. Reset with an option --hard to A5

git reset --hard [commit]
Enter fullscreen mode Exit fullscreen mode

reset_branch

3. Pick commits

git cherry-pick [...commits]
Enter fullscreen mode Exit fullscreen mode

cherry-pick-example

Now, A4 has gone and C1, C2 are there.


It was one of usages of cherry-pick, the command has more options(documentation). I fetched commits from other branches in this post however it's also possible with the same branch.
I hope it will be helpful for someone.
Good coding!

Top comments (2)

Collapse
 
marcomoscatelli profile image
Marco Moscatelli

Nice article mate!

Collapse
 
lico profile image
SeongKuk Han • Edited

Thanks for reading :)