This situation often arises for me when I’m reviewing a teammate’s Pull Request and they make changes by rewriting history. In this situation, I want to discard my local copy of the Pull Request branch and replace it with the version on GitHub (or wherever the remote branch is being stored).
To accomplish this we can run the following line from the command line
git fetch --all && git reset --hard origin/$(git rev-parse --abbrev-ref HEAD)
Explanation on Replacing You Current Branch with the Remote Version
The above line is actually two commands we’ve combined with &&
so they run one after the other.
In this explanation, we’ll assume the branch we’re dealing with is called fix/correct-typo-in-walker-example-3
Step 1: Making Your Local Install Aware of Remote Changes
When we are using a remote copy of our repo (e.g. at GitHub), our local install has two versions of our branch:
- The branch (e.g.
fix/correct-typo-in-walker-example-3
) - What Git thinks the branch on the remote contains at the given moment (Git prefixes the remote name, which is typically
origin
, to our branch name) (e.g.origin/fix/correct-typo-in-walker-example-3
)
Running git fetch --all
updates all of these origin/
branches.
After running git fetch --all
you can see the commits on the updated origin branch by running
git log --oneline --graph origin/fix/correct-typo-in-walker-example-3
Step 2: Reset the Branch to Match the origin/ branch
At this point, we want our fix/correct-typo-in-walker-example-3
branch to be updated to match out origin/fix/correct-typo-in-walker-example-3
branch.
Since a branch is really just a pointer to a commit (see What is a Git Branch?), we want to change fix/correct-typo-in-walker-example-3
to point at the same commit origin/fix/correct-typo-in-walker-example-3
points to. The command to do this is
git reset --hard origin/fix/correct-typo-in-walker-example-3
Automating Current Branch
In our command
git reset --hard origin/fix/correct-typo-in-walker-example-3
we are using our current branch fix/correct-typo-in-walker-example-3
but in the solution at the beginning of the article we have $(git rev-parse --abbrev-ref HEAD)
instead, which retrieves the current branch name and includes it in our command. This saves us having to manually add the branch name to our command.
Leave a Reply