Push specific commit on the remote branch tracking the current branch

324 views Asked by At

This question shows how to push up to a commit to the master branch (eg all parent commits of the specific commit):

How can I pushing specific commit to a remote, and not the previous commits?

The answer is :

git push <remotename> <commit SHA>:<remotebranchname>

so you can use git push origin <commit SHA>:master

However, I would like to automatically push that commit to the matching remote branch.

I can't just use git push <remotename> "<commit SHA>:$(git branch)" because git branch returns the local branches, I would like to have the matching remote branch (eg for example you can map the local master branch to map to the remote prod branch). I would like to take that into account.

1

There are 1 answers

5
poke On

Due to how Git works, a commit does not clearly belong to a branch. Branches are just pointers to commits that are located somewhere in the global history tree, so when you want to push a certain commit individually to a remote branch, that commit does not say anything about which branch you could possibly mean.

The only thing you can do it is to find branches where the commit is contained on, using git branch --contains. If that only returns one branch, then you’re in luck and everything is clear but the command may return multiple branches if the commit is reachable by multiple branches. For everything else, like the tracking branch, you would have to look at your repository’s configuration.

However, your workflow seems a bit weird to me. If you keep wanting to push an older commit instead of your current branch, then what you should really do is to make a new branch. Have one branch which matches the remote one which you then can just push; and have one other branch that’s ahead of that branch where your development happens. And whenever you want to update the remote, you update your local branch that matches the remote and then just push that branch.

So your history would look like this:

              prod               master
               ↓                   ↓
* -- * -- * -- * -- * -- * -- * -- *

And you could just push prod using git push origin prod and make that resolve whatever remote tracking branch actually is behind.