devroom.io/content/posts/2010-06-10-cherry-picking-specific-commits-from-another-branch.md

49 lines
2.1 KiB
Markdown
Raw Normal View History

2015-03-26 11:28:08 +00:00
+++
date = "2010-06-10"
title = "Cherry-Picking specific commits from another branch"
tags = ["git", "cherry-pick", "scm"]
slug = "cherry-picking-specific-commits-from-another-branch"
+++
I'm often asked how to merge only specific commits from another branch into the current one. The reason you'd want to do this is to merge specific changes you need now, leaving other code changes you're not interested in right now behind.
First of all, use `git log` or the awesome [GitX][1] tool to see exactly which commit you want to pick. An example:
2017-03-20 15:35:19 +00:00
``` text
dd2e86 - 946992 - 9143a9 - a6fd86 - 5a6057 [master]
\
76cada - 62ecb3 - b886a0 [feature]
```
2015-03-26 11:28:08 +00:00
Let's say you've written some code in commit `62ecb3` of the `feature` branch that is very important right now. It may contain a bug fix or code that other people need to have access to now. Whatever the reason, you want to have commit `62ecb3` in the master branch right now, but not the other code you've written in the `feature` branch.
2017-03-20 15:35:19 +00:00
2015-03-26 11:28:08 +00:00
Here comes `git cherry-pick`. In this case, `62ecb3` is the cherry and you want to pick it!
2017-03-20 15:35:19 +00:00
``` shell
git checkout master
git cherry-pick 62ecb3
```
2015-03-26 11:28:08 +00:00
That's all. `62ecb3` is now applied to the master branch and commited (as a new commit) in `master`. `cherry-pick` behaves just like `merge`. If git can't apply the changes (e.g. you get merge conflicts), git leaves you to resolve the conflicts manually and make the commit yourself.
2017-03-20 15:35:19 +00:00
## Cherry picking a range of commits
2015-03-26 11:28:08 +00:00
In some cases picking one single commit is not enough. You need, let's say three consecutive commits. `cherry-pick` is not the right tool for this. `rebase` is. From the previous example, you'd want commit `76cada` and `62ecb3` in `master`.
The flow is to first create a new branch from `feature` at the last commit you want, in this case `62ecb3`.
2017-03-20 15:35:19 +00:00
``` shell
git checkout -b newbranch 62ecb3
```
2015-03-26 11:28:08 +00:00
Next up, you rebase the `newbranch` commit `--onto master`. The `76cada^` indicates that you want to start from that specific commit.
2017-03-20 15:35:19 +00:00
``` shell
git rebase --onto master 76cada^
```
2015-03-26 11:28:08 +00:00
The result is that commits `76cada` through `62ecb3` are applied to `master`.
[1]: http://gitx.frim.nl/