git discard all changes and pull from upstream

Git

Git Problem Overview


How do I fetch upstream repo and make it replace master? I only have one branch on my repo, which is master, and I completely messed it up, so I basically need to start over from the upstream. I think init will do the job, but is there an easier way?

Git Solutions


Solution 1 - Git

There are (at least) two things you can do here–you can reclone the remote repo, or you can reset --hard to the common ancestor and then do a pull, which will fast-forward to the latest commit on the remote master.

To be concrete, here's a simple extension of Nevik Rehnel's original answer:

git reset --hard origin/master
git pull origin master

NOTE: using git reset --hard will discard any uncommitted changes, and it can be easy to confuse yourself with this command if you're new to git, so make sure you have a sense of what it is going to do before proceeding.

Solution 2 - Git

while on branch master: git reset --hard origin/master

then do some clean up with git gc (more about this in the man pages)

Update: You will also probably need to do a git fetch origin (or git fetch origin master if you only want that branch); it should not matter if you do this before or after the reset. (Thanks @eric-walker)

Solution 3 - Git

You can do it in a single command:

git fetch --all && git reset --hard origin/master

Notes:

1 WARNING you will lose ALL your local changes

2 if you want a branch different than master you have to use:

git fetch --all && git reset --hard origin/[BRANCH]

3 you can split it in a pair of commands:

git fetch --all
git reset --hard origin/master

Solution 4 - Git

I finally realized now that instead of

git fetch --all && git reset --hard origin/master

it should be

git fetch --all && git reset --hard origin/<branch_name>

instead (if one works on a different branch)

Solution 5 - Git

git reset <hash>  # you need to know the last good hash, so you can remove all your local commits

git fetch upstream
git checkout master
git merge upstream/master
git push origin master -f

voila, now your fork is back to same as upstream.

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
QuestionNinjaCowgirlView Question on Stackoverflow
Solution 1 - GitEric WalkerView Answer on Stackoverflow
Solution 2 - GitNevik RehnelView Answer on Stackoverflow
Solution 3 - GitLuca C.View Answer on Stackoverflow
Solution 4 - GitBitFreakView Answer on Stackoverflow
Solution 5 - GitresultswayView Answer on Stackoverflow