Sync your forked repository
As software developers, one of the ways to give back to the community is by contributing to open source projects, either by building a product and open-sourcing it or improving an existing project.
When doing the latter, a need to sync your copy of the repository (aka Fork) with the original repository arises, and that's what will be discussed in the next few paragraphs.
There are two ways to syncing your forked repository with the original repository, first by using the Github UI, or via the Command line.
Github UI method
This is pretty straightforward, with just a click of the button, this can be done on your Github repository containing the fork.
By clicking on the "Fetch upstream" button shown in the screenshot below, you get the updates (if there is an update since the time you created the fork) from the original copy of the repository into your fork.
Command line method
After you have forked the repository by using this👇🏽 button on the desired repository's Github page,
open your terminal then run the following:
git clone https://github.com/your_github_username/name_of_forked_repo.git
This pulls your copy of the repository to your local machine, it automatically sets up the communication between your local copy and your copy of the fork on Github, you can confirm this by running
git remote -v
You should see the remote URL in this format
> origin https://github.com/your_github_username/name_of_forked_repo.git (fetch) > origin https://github.com/your_github_username/name_of_forked_repo.git (push)
Next, you need to add the upstream (the link to the original repository which you forked from) to the local copy of the repository. You can do this by running the following in the terminal
git remote add upstream https://github.com/original_owner_username/original_repository_name.git
You can confirm that it has been added by running
git remote -v again, you should get these if it worked as expected
> origin https://github.com/your_github_username/name_of_forked_repo.git (fetch) > origin https://github.com/your_github_username/name_of_forked_repo.git (push) > upstream https://github.com/original_owner_username/original_repository_name.git (fetch) > upstream https://github.com/original_owner_username/original_repository_name.git (push)
Now, to sync your forked repository with the original one, all you need do is:
git fetch upstream
It fetches all the branches and their respective commits from the upstream repository.
To merge the changes on the upstream's default branch to your copy of the default branch, assuming the default branch is called 'main', do the following:
git checkout main
this switches you to the main branch, and lastly, you run
git merge upstream/main
Note: if your local branch did not have any unique commits, Git will instead perform a "fast-forward".