git: push a single commit

Git

Git Problem Overview


Say I made several commits and wish to cherry pick which ones I push to the remote repository. How can I do that (in ascii: C1->C2->C3->C4 and I want to push C2 and C4). Will reordering with rebase, resetting, pushing and then resetting work? (C1->C2->C3->C4 => C2->C4->C1->C3 => reset C4 => push => reset C3). Is there a nicer way?

Git Solutions


Solution 1 - Git

You may be looking for:

git push origin $commit:$branch

Credit: http://blog.dennisrobinson.name/push-only-one-commit-with-git/

Explanatory notes:

  • Pushing a commit pushes all commits before it (as Amber said). The key is to reorder your commits first (git rebase -i), so they are in the order you want to push them.
  • $commit doesn't have to be a sha1. For example, "HEAD~N" would push everything before the last N commits.
  • $branch (typically "master" or "main") is the branch you push to – the remote branch. It does not have to be the same as a local branch.
  • The suggested branch + cherry-pick method (suggested by midtiby) works too, but for reordering purposes (such as getting the prework in first), this avoids creating throwaway branches.

If the branch does not exist remotely, and you want to create it, it must be prefixed with refs/heads/ (to disambiguate branch from tag):

git push origin $commit:refs/heads/$new_branch

Pro tip: git-revise is a similar but better tool than git rebase (for local commits specifically). For my purposes, as a daily git user, I think it should be obligatory if you use git revise -i a lot (which is of course quite necessary to produce high quality commits).

Solution 2 - Git

If you have your commits on a private branch, you can cherry pick commits from the private branch and apply them to the official branch. At this point you can now push all your commits on the official branch (which is the subset that you previously cherry picked).

Solution 3 - Git

$ git push <remote name> <commit hash>:<remote branch name>

# Example:
$ git push origin 2dc2b7e393e6b712ef103eaac81050b9693395a4:master

Solution 4 - Git

IIRC, due to how git considers commits to work, C4 inherently includes C3, so the concept of "pushing C4 but not C3" doesn't make sense to git (and likewise C2 relative to C1). (See the answer to this previous question.)

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
QuestionIttayDView Question on Stackoverflow
Solution 1 - Gituser2394284View Answer on Stackoverflow
Solution 2 - GitmidtibyView Answer on Stackoverflow
Solution 3 - GitNikhil ThombareView Answer on Stackoverflow
Solution 4 - GitAmberView Answer on Stackoverflow