DEV Community

Cover image for Keep Your Fork In Sync: Understanding git remote upstream
Đặng Đình Sáng
Đặng Đình Sáng

Posted on

Keep Your Fork In Sync: Understanding git remote upstream

When you fork a repository on GitHub to contribute to an open-source project or keep a copy for your work, it's important to be able to sync your local fork with updates made in the original repository. That's where adding a remote upstream comes in handy.

In this post, I'll explain what git remote upstream is, why it's useful, and provide examples of how to set it up and use it to keep your fork in sync.

What is a remote upstream?

Image description

By default, when you fork a repository your local clone will only have a remote called origin configured, which points to your forked repository on GitHub. While the origin allows you to push/pull with your fork, it doesn't connect you back to the source project repository.

That's where adding an upstream remote comes in. upstream allows you to fetch changes made in the original repository without pushing any updates back. It serves as a read-only path to the source project.

Image description
source

Setting up remote upstream

To set up an upstream remote on your local fork, you need to get the clone URL of the original repository:

git remote add upstream https://github.com/ORIGINAL_OWNER/REPOSITORY.git
git remote set-url --push upstream DISABLE  # so that you don't push back to the original repo
Enter fullscreen mode Exit fullscreen mode

You can verify it was added correctly with git remote -v:

origin  https://github.com/<your_username>/<repository>.git (fetch)
origin  https://github.com/<your_username>/<repository>.git (push)
upstream    https://github.com/ORIGINAL_OWNER/REPOSITORY.git (fetch) 
upstream    https://github.com/ORIGINAL_OWNER/REPOSITORY.git (push)
Enter fullscreen mode Exit fullscreen mode

Using remote upstream

Now you have two remotes configured:

  • origin points to your fork
  • upstream points to the original repo

To sync changes from upstream to your local fork, you can fetch and merge the upstream branch

# Fetch the latest changes 
git fetch upstream

# Merge upstream changes into your active branch
git merge upstream/main
Enter fullscreen mode Exit fullscreen mode

Image description

This will bring any commit made from the original repo into your local fork, allowing you to work seamlessly with the latest updates.

And with that, you now have a shortcut configured to easily keep your fork in sync with the original project source! Let me know if any part needs more explanation.

Top comments (1)

Collapse
 
miin profile image
Imamul I. nAyeem

useful concept. thanks for sharing.