How to sync/update forked git repository with upstream?

中文版: https://www.peterdavehello.org/2014/02/update_forked_repository/

I found the origin post in Chinese is more popular among all the posts, so just rewrite it in English now :)

Once you forked a repository on GitHub, the commit history from the upstream will stay at the moment you forked it, sometimes we’ll need to update it, so that the parent of our commit won’t be so old, which can help us have a better look, easier to trace git commit history, and prevent some potential or known conflicts, maybe you have other reasons, anyway. This method can also sync a repository between different git servers.

NOTE:
If you forked repository is behind the upstream repository for more than 1k commits and the repository is fat, you can consider to delete your forked repository and re-fork the origin one, it may be faster and more efficient.

Let’s start it.

First, if you didn’t have the repository locally, you have to clone the forked repository to local, you can set the clone depth to save the bandwidth and disk space usage:
$ git clone --depth 1 https://github.com/user/repo.git

(Replace the url to your forked repository)

Once you cloned it, check its ‘remote’, usually you’ll get only one remote after clone, like this:
$ git remote -v
origin https://github.com/user/repo.git (fetch)
origin https://github.com/user/repo.git (push)

Now we should add another ‘remote’ – the origin upstream, so that we can pull the updates from, in this case, use read-only git protocol will be faster, more efficient (but note that some firewall may not allow that protocol, so you’ll need to use https in that case):
$ git remote add upstream git://github.com/otheruser/upstreamRepo.git

PS: ‘upstream’ is the name I gave it, you can give it another name as you want.

To verify new added remote, let’s check it again, you should have two remotes now:

origin https://github.com/user/repo.git (fetch)
origin https://github.com/user/repo.git (push)
upstream git://github.com/otheruser/upstreamRepo.git (fetch)
upstream git://github.com/otheruser/upstreamRepo.git (push)

Now we can start the “update" works, I assume the branch you’re going to update is the master branch, if you are going to update a non-master branch, just checkout to the branch you want, but don’t forget to change the branch from the below examples!

If your branch is only behind the upstream, no any “ahead" commits(which means you didn’t commit any new things on the same branch came from upstream), you can directly pull the updates from upstream:
$ git pull upstream master

If your branch also contains your own commits, you should better pull with “–rebase" parameter:
$ git pull --rebase upstream master

Now, almost done, if there is no error or conflicts(we don’t discuss conflicts here), push your master to origin remote, then you’ll found that your forked repo is fresh again:
$ git push origin master

發表迴響