How to keep your fork in sync with the original repository
After you fork a project and start working, the original repository keeps moving. If you don't sync, your pull requests may conflict or be based on old code. Here's how to stay up to date.
Terms
- origin: your fork on the hosting site
- upstream: the original project you forked from
Set up once
- Clone your fork:
git clone <your-fork-url> - Add the original as a remote:
git remote add upstream <original-repo-url> - Check with
git remote -v
Sync regularly
git fetch upstreamgit checkout maingit merge upstream/main(orgit rebase upstream/mainif you haven't shared local commits)git push origin main
Many hosting sites also offer a "Sync fork" button for the main branch, which does the same thing in the browser.
Keep your work on branches
- Don't make changes directly on
mainof your fork. Create a feature branch for each contribution. - Then
mainstays a clean mirror of upstream, and you can update your feature branch by rebasing or merging from it.
If you hit conflicts
Git will mark the conflicting sections. Edit the files to keep the right changes, git add them, and continue the merge or rebase. Running the project's tests afterward is a good habit.
Do you prefer merging or rebasing to keep your fork current? Did syncing forks confuse you at first?
Comments · 2
Add the original as an "upstream" remote, fetch, then rebase or merge into your branch. Doing it before you start new work saves headaches.
Fetch upstream, then rebase your branch on it. Push with force-with-lease only on your own fork branch.