There are times when I want to dispose of my local branch and replace it with the version on GitHub (the upstream version). For example, when I’m reviewing a teammate’s pull request and they rewrite history (e.g. perform a rebase or amend a commit), I don’t have any work on that branch and I only want their updated version (I don’t care about the history on my machine).
Replace Local Branch with Upstream
Git has a shortcut @{upstream}, or the even shorter @{u}, that refers to the upstream version of your local branch.
We want our local branch to point to the same commit @{u} does (i.e. we want to reset our local branch to match the upstream branch).
To make certain we have the most recent version of the upstream branch I would first run git fetch.
git fetch
Then we’ll use git reset with the --hard flag to make our branch match the upstream branch, @{u}.
git reset --hard @{u}
Not Just GitHub
While this example calls out GitHub as the upstream location, this command works for any Git upstream repository.
Making Things More Efficient
We can combine those two lines into one
git fetch && git reset --hard @{u}
and we can even create an alias so typing git frhu will do this for us.
You can see the Pull Request to add the Git Reset Hard Upstream alias to my Git configuration.
Leave a Reply