KISS

Keep It Simple Stupid

git: picking commits from one branch to another

| comments

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:

  1. 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.

  2. You can create and then apply patches with git archive and git apply. But again, it’s tiresome with a lot of commits.

  3. 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:

  1. Make sure you’re on the branch which to place commits on: git checkout master.

  2. Run the interactive rebase: git rebase -i master origin/cuatro, where the two last arguments are the target and source branches respectively.

  3. 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).

  4. 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/.

git

Don't hesitate to leave a comment below. NB! If you don't see a comment form under the post, it's most likely that an extension (such as Ghostery, NoScript, or AdBlock) of your browser blocks the scripts from disqus.com, and you can unblock that.

« Hiding CVV code on a bank card Neurobics »

Comments