Git - Cherry pick a single commit for pull request

GitGithub

Git Problem Overview


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 and I don't' want to submit all of the other commits because I don't think its 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, if that's possible.

Git Solutions


Solution 1 - Git

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

Solution 2 - Git

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.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Questionuser3590149View Question on Stackoverflow
Solution 1 - GitSLaksView Answer on Stackoverflow
Solution 2 - GitJashanView Answer on Stackoverflow