2

Someone messed up origin/master. They merged about 15 commits into it that weren't supposed to go in until a future sprint.

I have what SHOULD be origin/master on a local branch. How would I reset origin/master to be my local branch?

I'm thinking I could push my local branch, let's call it masterbackup, to the origin, then checkout origin/master, reset it to origin/masterbackup, then push. So something like:

git push -u origin masterbackup
git checkout master
git pull
git reset --hard origin/masterbackup
git push

Will that work?

Thanks.

1

1 Answer 1

3

What you want is just one command:

(Read the entire answer before proceeding... I included optional "safety" commands at the end)

git push -f origin masterbackup:master

Here is the relevant part of the documentation describing the last parameter with the colon:

<refspec>…​

Specify what destination ref to update with what source object. The format of a parameter is an optional plus +, followed by the source object , followed by a colon :, followed by the destination ref .

The is often the name of the branch you would want to push, but it can be any arbitrary "SHA-1 expression", such as master~4 or HEAD (see gitrevisions[7]).

The tells which ref on the remote side is updated with this push.

Source: https://git-scm.com/docs/git-push

In English, this command says: make the master branch in the origin repo point to the same commit as the masterbackup branch in the local repo. In git terms, this is called "pushing masterbackup to master on remote origin"

If you want an extra level of safety, before you execute this command, do:

git fetch origin master

git branch bad-master origin/master

That way if you want to go back to the way it was before you fixed it, you can do:

git push -f origin bad-master:master

Once you are satisfied that you don't need to go back, you can delete that branch with:

git branch -D bad-master

The capital D is needed because otherwise git will refuse to delete a branch that will orphan commits.

As a final note... it seems that your roundabout method would also work, except that you would need a -f in the final push and it would also leave an unnecessary branch (masterbackup) on the remote.

(It seems you have the common misperception among git users that the remote repo is more important than it really is, perhaps as a side-effect of having used centralized vcs's. This often expresses itself in unnecessary push and pull commands. A branch doesn't need to be "on the server" to be useful. The remote repo is exactly the same as your local repo... it has no extra powers.)

Not the answer you're looking for? Browse other questions tagged or ask your own question.