Syncing a GitHub Fork with the Upstream Repo

Web Design & Development

GitHub provides some documentation on how to keep your fork in sync with the original (i.e. “upstream”) repo that you forked from. This is essential if you are working on some changes for a long time and the original repo is getting updated with other pull requests in the meantime.

There are a couple rules I follow to keep this as simple as possible:

  1. Always make changes to the fork in new branches; never make changes to the fork in the default branch (usually called “main” or “master”).
  2. Try to keep the fork in sync on a regular basis.

The first step once I fork a repo and clone it onto my local dev machine is to add the “upstream” repo as a remote.

git remote add upstream https://github.com/ORIGINAL_OWNER/ORIGINAL_REPOSITORY.git

From there I keep the default branch (in this example it is called “main”) on my local repo in sync with the upstream with these commands:

git fetch upstream
git checkout main
git merge upstream/main

This should just work without any further steps, then I can push my local repo to the origin remote (e.g. on GitHub) so that is in sync too.

git push origin main

I’ve gotten into a spot a couple of times where I did make a change in the default branch and wanted to discard my changes in the main branch to keep things clean and in sync. In this case I run these commands:

git fetch upstream
git checkout main
git reset --hard upstream/main

This brings my local repo in sync with the upstream main branch even if I’ve made changes to it locally that are not in the upstream repo. This will discard any commits on the “main” branch that are not in the upstream branch, so don’t perform this step without knowing what it will do!

If I’ve already pushed local changes to my origin main branch that I also need to “undo” to keep things in sync, a force push will override whatever changes were pushed to the origin repo. This will change the “history” of the repo and can cause problems if your repo has been forked or cloned by someone else, so again only do this if you understand what it will do!

git push --force

That covers pretty much all of the scenarios I run into where I need to keep my local repo and origin fork in sync with the original upstream repo.