How to merge only specific commits from a pull request

Posted on March 07, 2016 | By Matt Stauffer

Warning: This post is over a year old. I don't always update old posts with new information, so some of this information may be out of date.

Tonight I was looking at pull requests to all of my open source repositories, and there was a pull request that had started out great and then been ruined by someone offering bad advice to the original pull request-er. I later came back and asked, "Could you re-PR this with just the initial commits?" But by that point they had been driven off.

I thought it was hopeless, and just started pulling the code into a new branch. I could get it to work without any trouble but it wouldn't give attribution to the original author, which I was hoping for. And then I stopped and thought, why not Google around a bit?

A few Stack Overflow answers and a bit of digging later and I found my answer: git cherry-pick.

How to use git cherry-pick

Turns out you can, indeed, "cherry-pick" just the commits you want from that pull request. Steps:

  1. Pull down the branch locally. Use your git GUI or pull it down on the command line, whatever you'd like.
  2. Get back into the branch you're merging into. You'll likely do this by running git checkout master.
  3. "Cherry pick" the commits you want into this branch. Go to either the git log or the GitHub UI and grab the unique commit hashes for each of the commits that you want, and then run this command: git cherry-pick super-long-hash-here. That will pull just this commit into your current branch.
  4. Push up this branch like normal. git push origin master

An example

So, I had a pull request introducing the log component. I went to the pull request in GitHub and pulled the branch down (using the "use the command line" directions, but I could've also pulled down with the GitHub UI.)

On the command line, I then ran git checkout master. I went to the GitHub UI, found the commit I wanted, and grabbed its commit hash by clicking the little "copy" icon next to it in the commit list. Then I ran git cherry-pick long-hash-here-pasted-from-github.

Finally, I pushed it up to GitHub with git push origin master. Done! Finally, I closed the pull request manually with a link to the commit.


Comments? I'm @stauffermatt on Twitter


Tags: git  •  github