How do I reset the git master branch to the upstream branch in a forked repository?

I've completely messed up the master branch of my forked git repo.

I want to completely reset the master branch that was pushed to my fork with the contents of the upstream master repo. I have no interest in retaining any master branch changes or history.

The simplest approach would have been to delete my forked repo and refork from the upstream project. However, I have work in other pushed branches that I don't want to lose.

Thus how to I reset my pushed master branch with the upstream master?


git clone https://myrepo.git
cd myrepo
git remote add upstream https://upstream.git
git fetch upstream

Where do I go from here to reset my local and remote master branches with the upstream master?


Solution 1:

You can reset your local master branch to the upstream version and push it to your origin repository.

Assuming that "upstream" is the original repository and "origin" is your fork:

# ensures current branch is master
git checkout master

# pulls all new commits made to upstream/master
git pull upstream master

# this will delete all your local changes to master
git reset --hard upstream/master

# take care, this will delete all your changes on your forked master
git push origin master --force

(You can define the original repo as "upstream" with git remote add upstream /url/to/original/repo.)

Solution 2:

This would reset your master branch with the upstream master and if the branch has been updated since your forked it would pull those changes as well.

git checkout master 
git reset upstream/master
git pull --rebase upstream master
git push origin master --force

PS: Assuming Upstream is the original repo while origin is your copy.

Solution 3:

git reset --hard @{upstream}

or, shorter:

git reset --hard @{u}

Or you can even take it one step further and setup an alias that will allow you to simply type git scrub:

git config --global alias.scrub 'reset --hard @{upstream}'

(This assumes that your branch is configured to track the corresponding remote branch, which it typically is, unless you are doing something special. See git-branch(1) for more details on tracking and git-rev-parse(1) for details on the branch specification syntax.)

And then you just git push --force to your fork, as explained in other answers.