user3590149
user3590149

Reputation: 1605

Git - Cherry pick a single commit for pull request

I might not have the terminology down yet.

I made file to be added to a open project on git.
I forked the project.
I made some changes and my last commit is the file I want to request to the project and not the small changes I made before hand.

When I go to github site and make pull request, I get all the commits before the one I want (which is last one of a file).

I don't want to submit all of the other commits, because I don't think it's necessary for the project. Just my own changes.

What do I do?
Should I just make another res, or attach the file singularly and submit?

Upvotes: 60

Views: 62788

Answers (2)

Jashan
Jashan

Reputation: 230

As I'm doing this a lot, and had to look up this answer a few times, I put SLaks answer into a little batch file. This is for Windows / CMD but should be trivial to port to Linux, Mac or PowerShell. As I usually do several commits, each being one pull request, I also added switching back to the master branch.

@echo off

REM Idea from: https://stackoverflow.com/questions/25955822/git-cherry-pick-a-single-commit-for-pull-request

set BRANCH_NAME=%1
set COMMIT_HASH=%2

IF %BRANCH_NAME%.==. GOTO NoBranchName
IF %COMMIT_HASH%.==. GOTO NoCommitId

git checkout -b %BRANCH_NAME%
git fetch upstream
git reset --hard upstream/master
git cherry-pick %COMMIT_HASH%
git push origin %BRANCH_NAME%:%BRANCH_NAME%
git switch master

GOTO End

:NoBranchName
  ECHO No branch name given. Usage: add-pull-request.bat BRANCH_NAME COMMIT_HASH
GOTO End

:NoCommitId
  ECHO No commit id given. Usage: add-pull-request.bat BRANCH_NAME COMMIT_HASH
GOTO End

:End

One obvious improvement would be first picking up the current branch and then use that in the last line but that's something I didn't need and it would make the whole thing significantly more complex.

Upvotes: 1

SLaks
SLaks

Reputation: 887453

You need to create a fresh branch from the remote HEAD, cherry-pick the commit to that branch, push the branch to your repo on GitHub, then create a pull request.

git checkout -b mybranch
git fetch upstream
git reset --hard upstream/master
git cherry-pick <commit-hash>
git push origin mybranch:mybranch

Upvotes: 100

Related Questions