Updating a Forked GitHub Repository

Updating a Forked GitHub Repository

If you’re going to contribute to an existing project on GitHub, your first step is to fork the repository.  The easiest way to do that is to look in the upper-right of the repo’s GitHub page and press the Fork button.  Doing this will fork, or create a copy of the repository under your GitHub account.

Fork a repo from GitHub via the browser

Fork a repo from GitHub via the browser

So you now own a copy of that repository.  What happens if the Master branch of the parent repository you forked from gets updated and your fork is now out of date?  Well, you may first start by reading the GitHub documentation on Syncing a Fork.  The instructions start by setting a remote upstream location.

$git remote add upstream https://github.com/otheruser/repo.git

You can think if this as instructing your fork as to where it came from and where it should update from.  Now that your fork knows where it needs to update from, you have to actually fetch that code.

$git fetch upstream

At this point you have your local fork and the upstream repository.  The GitHub documentation states you should then merge with the upstream/master.  However, if you do that and make a change, commit it, and then submit a pull request, what your pull request would look like would be your changes plus all the commits merged in from the origin.  Luckily this Stackoverflow answer provides an alternative, continuing with a rebase.

git rebase upstream/master

The rebase rewrites your master branch so that any of your commits that aren’t in the upstream/master are put on top of that branch.  This eliminates the problem where your merge with the origin would include all of your merging activity.  Finally, after the rebase on to the upstream you’ll need to force push this all to your fork on GitHub.

git push -f origin master

As noted on the Stackoverflow answer, the -f is only needed the first time after you’ve rebased.  At this point your own fork of the repository on GitHub should now be up to date with the repository you forked it from.

Tags: , Filled Under: Programming Posted on: September 20, 2013

Leave a Reply

Your email address will not be published. Required fields are marked *