Hi. It’s a small how-to in case you need to pick/apply a number of non-sequential commits from one branch to another in git
.
There are a number of ways to achieve this:
git cherry-pick
can apply a commit to another branch. Here is a tutorial: http://gitready.com/intermediate/2009/03/04/pick-out-individual-commits.html. However, if you have a bunch of commits to pick it can get tedious.
You can create and then apply patches with git archive
and git apply
. But again, it’s tiresome with a lot of commits.
Rebasing! That’s the way.
Let’s take the gpodder
’s repository as an example: https://github.com/gpodder/gpodder. So we have the master
branch where we want to place a number of commits from say the origin/cuatro
branch. Here are the steps:
Make sure you’re on the branch which to place commits on: git checkout master
.
Run the interactive rebase: git rebase -i master origin/cuatro
, where the two last arguments are the target and source branches respectively.
An editor will open, vim
in my case, and you’ll see a lot of lines of this format: pick commit-SHA commit-message
. These represent chronologically-ordered commits that you can apply on the target branch. Now it’s easy to remove the commits you don’t need (in vim
you should press dd
to delete a line, or 5dd
where 5
is the number of lines to delete).
Save the file and exit. In vim
you can press <Esc>
, then ZZ
.
Of course, with such a selective picking you can run into conflicts during rebasing. git
will print everything you need to know to fix them and continue.
If you decide to start all over again, you git rebase --abort
and jump to item 1 above.
ps. If you need this tip often, you’re probably doing a lot of mostly independent things in one branch. I can recommend that you look into git branching models, for example this one seems to be quite popular: http://nvie.com/posts/a-successful-git-branching-model/.