4643

I forked a project, made changes, and created a pull request which was accepted. New commits were later added to the repository. How do I get those commits into my fork?

Mateen Ulhaq
  • 24,552
  • 19
  • 101
  • 135
Lea Hayes
  • 62,536
  • 16
  • 62
  • 111
  • 157
    This can also be done from the github UI. I'd like to give credit [to this other poster][1]. [1]: http://stackoverflow.com/a/21131381/728141 – Mike Schroll Feb 20 '14 at 13:00
  • 5
    Another good blog post on this - [Keeping A GitHub Fork Updated](http://robots.thoughtbot.com/keeping-a-github-fork-updated) – Arup Rakshit Oct 15 '14 at 17:26
  • 4
    Found this in Github help articles: https://help.github.com/articles/syncing-a-fork/ – Pranav Apr 02 '15 at 08:57
  • 2
    Is this a duplicate of http://stackoverflow.com/questions/3903817/pull-new-updates-from-original-github-repository-into-forked-github-repository ? – David Cary Aug 29 '15 at 12:06
  • Here's a video demo that does this using two github accounts https://www.youtube.com/watch?v=kpE0gTX4ycE – lifebalance Jun 03 '16 at 09:29
  • 1
    Here you go - https://github.com/KirstieJane/STEMMRoleModels/wiki/Syncing-your-fork-to-the-original-repository-via-the-browser. Simple and easy – Sumeet Patil Mar 18 '20 at 10:40
  • 4
    Since May 2021 this is directly possible from the GitHub UI without extra pull request, see [changelog](https://github.blog/changelog/2021-05-06-sync-an-out-of-date-branch-of-a-fork-from-the-web/) and https://stackoverflow.com/a/67425996 – Marcono1234 May 08 '21 at 00:23
  • all offered solutions are far too complex for the simple need. Is there at least a feature request for a more straightforward one button approach? – Wolfgang Fahl Apr 07 '22 at 06:44
  • 1
    @WolfgangFahl check the [WebUI option I share here](https://stackoverflow.com/a/65401892/7109869). – Gonçalo Peres Nov 18 '22 at 10:34

31 Answers31

5307

In your local clone of your forked repository, you can add the original GitHub repository as a "remote". ("Remotes" are like nicknames for the URLs of repositories - origin is one, for example.) Then you can fetch all the branches from that upstream repository, and rebase your work to continue working on the upstream version. In terms of commands that might look like:

# Add the remote, call it "upstream":

git remote add upstream https://github.com/whoever/whatever.git

# Fetch all the branches of that remote into remote-tracking branches

git fetch upstream

# Make sure that you're on your master branch:

git checkout master

# Rewrite your master branch so that any commits of yours that
# aren't already in upstream/master are replayed on top of that
# other branch:

git rebase upstream/master

If you don't want to rewrite the history of your master branch, (for example because other people may have cloned it) then you should replace the last command with git merge upstream/master. However, for making further pull requests that are as clean as possible, it's probably better to rebase.


If you've rebased your branch onto upstream/master you may need to force the push in order to push it to your own forked repository on GitHub. You'd do that with:

git push -f origin master

You only need to use the -f the first time after you've rebased.

Community
  • 1
  • 1
Mark Longair
  • 446,582
  • 72
  • 411
  • 327
  • 2
    I +1'ed this answer because it probably accomplishes what the question author actually needed. But I'm in the same situation and am curious: is there any way to actually "pull" from the main repo into my fork? Or will the upstream fork only be updated if I push back up to it after fetching from upstream? – todd.pierzina May 24 '12 at 16:06
  • 120
    As your fork only exists on github, and github does not have tools for doing merges through the web interface, then the right answer is to do the upstream merge locally and push the changes back to your fork. – Tim Keating Jun 19 '12 at 03:50
  • @TimKeating Github does have web interface to deal with merges from others' pull request. I am wondering what will happen if i exchange the destination and my repo when sending a pull request. – yeh Mar 19 '13 at 13:42
  • 64
    A quick note that rather than having to rebase your own master branch to ensure you are starting with clean state, you should probably work on a separate branch and make a pull request from that. This keeps your master clean for any future merges and it stops you from having to rewrite history with `-f` which messes up everyone that could have cloned your version. – Mateusz Kowalczyk May 29 '13 at 23:09
  • 3
    After your changes are accepted in the upstream, you need to repeat these steps: `git fetch upstream`; `git rebase upstream/master`; `git push origin master` – rubo77 Oct 16 '13 at 08:06
  • 1
    @episodeyang: I don't mind the example URL being changed from `git://` to `https://`, but your comment at the end was wrong - the git protocol still works fine with GitHub; I suspect you were trying from a network that blocks traffic to port 9418, or something similar. I've removed that bit of your edit. – Mark Longair Dec 31 '13 at 11:04
  • 6
    If you have local commits, doesn't this creates ugly `"Merge branch 'master' of github.com:user/repo"` commits every time you try to get the updates from the upstream? You can rebase sure, but if you pushed your changes to your forked repo on github, means next time you just can't rebase without regenerating the hashes for every commit after it turning everything in a mess. I really don't know how to properly "maintain" a fork on github. – Pablo Olmos de Aguilera C. Jan 12 '14 at 02:37
  • 1
    If you want to have the original repo locally and still want to update your fork, you can add your fork as a `downstream` remote similar to above, then push to it: `git push -f downstream`. – Alfred Xing May 10 '14 at 03:36
  • 1
    this is better than github's help [here](https://help.github.com/articles/merging-an-upstream-repository-into-your-fork/) which does not set up upstream. – dashesy Feb 18 '15 at 21:40
  • 1
    @MarkLongair what does "replayed on top of that other branch" mean here? – crisron Nov 29 '15 at 09:02
  • 1
    @crisron: good point - that's not really clear. The rebase will look at the change (patch) that was introduced by each commit in its original point in the history and try to apply that change on a different parent commit (keeping the same message and author information). Sometimes this won't apply cleanly, and you have to fix conflicts. So what I meant by your commits being "replayed on top of that other branch" is taking each of your new commits that aren't in that branch, and trying to recreate them, one-by-one, by making the same change as they did with respect to their original parent. – Mark Longair Dec 04 '15 at 12:09
  • It'd probably be easier and faster if one simply deleted and re-forked. – Akshay Damle Jul 14 '16 at 06:09
  • 13
    Instead of the rebase command, i used the following: `git merge --no-ff upstream/master` This way your commits aren't on top anymore. – Steckdoserich Oct 17 '16 at 13:20
  • 3
    @Steckdoserich couldn't agree more. It is extremely sad that people here think that force pushing a publicly visible branch after a rebase is remotely correct or acceptable. It renders your fork almost useless to anyone following along.... – UpAndAdam Jan 13 '17 at 19:12
  • 30
    @jww: You ask why Git needs to be told about the original GitHub repository. It is because Git is a decentralized version control system and is not tied to GitHub in any way; it is probably obvious that Git was created before GitHub. When you create a forked repository on GitHub and clone it, GitHub knows that the repository is a fork; Git has no reason to, and does not. (Why doesn't the clone copy the Git remotes? Git is decentralized; different people will want different remotes; it would make no sense to do this.) See https://github.com/github/hub for GitHub integration in Git. – Resigned June 2023 Jun 04 '17 at 04:43
  • @Radon is "forking" a GitHub concept, introduced by the site rather than Git itself? – Sinjai Feb 08 '18 at 23:34
  • @Sinjai Yes. Separate copies of a Git repository have no relationship to one another, except one that exists in your mind or in external services such as GitHub (or that you implicitly create by creating remotes). – Resigned June 2023 Feb 09 '18 at 03:11
  • 1
    @RadonRosborough Surely the thought of creating derivations of open source projects was considered by someone before sites like GitHub, no? Though I suppose Git doesn't have anything to do with open source. – Sinjai Feb 09 '18 at 03:24
  • 1
    @Sinjai Yes, of course. That's why Git has explicit support for either applying patches from other people's changes, or for merging commits directly from other people's repositories (and it makes this last step extremely easy due to the support for a saved list of remotes). The thing that Git does not do is host a centralized webservice for hosting repositories in a standardized relational structure. It should be obvious, I think, why this latter thing is out of the scope of Git. And it's also why GitHub exists. And GitLab. And Bitbucket. Etc. – Resigned June 2023 Feb 10 '18 at 22:54
  • 1
    @RadonRosborough Sure, it just seems like there should be explicit support *for* those web services. It's not like Git would have to limit its support to just GitHub or BitBucket. It's a common use case that's more convoluted to apply than it needs to be. Though I suppose that's Git in a nutshell. – Sinjai Feb 11 '18 at 04:00
  • 8
    @Sinjai There _is_ explicit support for these webservices. It's called the remote system. You specify the URL, and then push/pull. Speaking quite literally, I don't think it could possibly get any simpler without hardcoding support for some particular service. If Git were to have some kind of implicit understanding of the relationship between different repositories without you providing that information, it would require a centralized database. There's just no rational way to integrate this functionality into a distributed revision control system. – Resigned June 2023 Feb 11 '18 at 04:42
  • 1
    Git is so decentralized in a fashion you can merge a branch from a repo hosted on your local machine with no access to the internet, then merge it with a branch of another repo hosted on GitLab and finally rebase all of that into another repo hosted on GitHub. – Bruno Finger Nov 14 '18 at 12:41
  • what if there is some conflicts after `git rebase upstream/master`? how to solve the conflict? – DennisLi Mar 28 '20 at 03:17
  • @jww there is no issues with SVN, you may always switch to it. – 0andriy Aug 12 '20 at 10:55
  • This was helpful. Could not find instructions for setting upstream in official git docs [here](https://docs.github.com/en/github/collaborating-with-pull-requests/working-with-forks/merging-an-upstream-repository-into-your-fork) – Rahul Tiwari Jun 10 '21 at 12:38
  • Makes me wonder do we have something better now from git in 2021 than to manually add, fetch upstream and rebase upstream/master ? – Rahul Tiwari Jun 10 '21 at 12:45
  • 2
    The 'master' branchname is changed to 'main' now ? – Pradeep Jun 19 '21 at 09:46
  • > "Remotes" are like nicknames for the URLs of repositories - origin is one, for example. Blew my mind – testing_22 Oct 06 '21 at 16:52
  • In the context of open source software development, if the purpose of existence of a fork is for you to contribute to open source projects through PRs, then sync by rebasing (git rebase upstream/master). It creates cleaner commit history and cleaner future PRs. BUT, if the purpose of the fork is to create something entirely new based on an open source project (that other people will use), and in the middle of development you want for some reason to be synced with the upstream project, you should sync by merging (git merge upstream/master). – Athanasios Salamanis Oct 21 '22 at 12:18
  • @MarkLongair When we do ```git rebase upstream/master``` or ```git merge upstream/master```, what happens to the commits of other branches that we fetched as part of git fetch ? And is there any way to merge all the changes that are fetched from upstream (to their respective branches) ? – Pradeep Mar 29 '23 at 17:19
  • I did this twice and still had commits that were out of sync from the remote. What's worse is that it was the same original commits that were out of sync except that `rebase` re-created them so the timestamps were updated and I had to go through each and every commit to work through merge conflicts. So I did a ton of work for zero benefit. The only thing that worked was `git reset --hard upstream/main && git push -f`. Note that will will destroy all local work in your fork but if you're using the fork and pull method this is fine. Also you should lock the fork as well to read only. – fIwJlxSzApHEZIl Jun 15 '23 at 01:49
828

Starting in May 2014, it is possible to update a fork directly from GitHub. This still works as of September 2017, BUT it will lead to a dirty commit history.

  1. Open your fork on GitHub.
  2. Click on Pull Requests.
  3. Click on New Pull Request. By default, GitHub will compare the original with your fork, and there shouldn't be anything to compare if you didn't make any changes.
  4. Click switching the base if you see that link. Otherwise, manually set the base fork drop down to your fork, and the head fork to the upstream. Now GitHub will compare your fork with the original, and you should see all the latest changes. enter image description here
  5. Create pull request and assign a predictable name to your pull request (e.g., Update from original).
  6. Scroll down to Merge pull request, but don't click anything yet.

Now you have three options, but each will lead to a less-than-clean commit history.

  1. The default will create an ugly merge commit.
  2. If you click the dropdown and choose "Squash and merge", all intervening commits will be squashed into one. This is most often something you don't want.
  3. If you click Rebase and merge, all commits will be made "with" you, the original PRs will link to your PR, and GitHub will display This branch is X commits ahead, Y commits behind <original fork>.

So yes, you can keep your repo updated with its upstream using the GitHub web UI, but doing so will sully your commit history. Stick to the command line instead - it's easy.

MD XF
  • 7,860
  • 7
  • 40
  • 71
lobzik
  • 10,974
  • 1
  • 27
  • 32
  • 21
    This worked great one time. The second time this process did not work the same way: the "Switching the base" link did not show up. And when I hit "Click to create a pull request" it created a PR on the SOURCE repo. NOT what I wanted.. – WestCoastProjects Aug 21 '14 at 18:14
  • 32
    Still works (Marchi 2015), all though the "Switching the base" link is no longer there. You have to change the "Base" drop down's so both point to your fork and then you'll get a prompt to "Compare across repos", which will take you to where you want. – mluisbrown Mar 04 '15 at 14:05
  • 8
    April 2015. Works. Thanks. I did get "Switching to base". However, step 6 was "Create pull request" -> enter comment -> "Create pull request". End up with 1 commit ahead of original. – cartland Apr 09 '15 at 00:08
  • 5
    @cartland (or others) - yes, it says "This branch is 1 commit ahead of ..." Is this something to worry about? Is it possible to get rid of that message? – RenniePet May 15 '15 at 22:59
  • 3
    The merge itself appears to be the 1 commit ahead as soon as you complete the pull request and this is normal. I have noticed that the switching branches no longer works for me. – Matt Sanders Jun 18 '15 at 19:15
  • @RenniePet In the "This branch is x commit(s) ahead of (original)" message, the x commit(s) refer(s) to a those/that which you made and the upstream forkee has not (yet) merged. The x in the message will increase with every commit you make to that fork. – Scruffy Jul 21 '15 at 09:20
  • 1
    @RenniePet If you follow [these steps (mainly step 3)](http://2buntu.com/articles/1459/keeping-your-forked-repo-synced-with-the-upstream-source/) you can end up you can end up with __This branch is even with :master.__ – Sahar Rabinoviz Aug 05 '15 at 14:50
  • This work, but it didn't bring the new branches to your repo – dirceusemighini Sep 17 '15 at 14:08
  • 2
    This works but the UI is very clunky. It sometimes suggests the opposite operation as a default, i.e. sending a pull request to the original source. – runDOSrun May 30 '16 at 07:36
  • 2
    It works, but they should have used a "rebase fork" and "push" button. In this way it seems so odd to me. Not very intuitive.. – Tarabass Jul 28 '16 at 18:32
  • 3
    Each time you do this it adds to the fork a commit ahead of the original – neilgee Aug 15 '16 at 03:55
  • 2
    The steps need an update; essentially, you need to compare your fork as a base, with the original as the head fork. However, the commit history won't be clean. You can either merge or squash+merge, which will leave you with a merge commit, or "Rebase and merge", which will give "This branch is X commits ahead, Y commits behind ", and every commit will be "with" you. – Dan Dascalescu Oct 28 '16 at 20:40
  • 1
    Say changes in my fork have primarily consisted of edits to documentation, which can be performed through web without cloning. Wouldn't performing "Stick to the command line instead - it's easy." require cloning the repository over my (possibly metered) Internet connection? – Damian Yerrick Jan 12 '17 at 17:16
  • 24
    wouldnt it be better, with a simply update or sync button! – Transformer Jan 24 '17 at 03:32
  • What is the disadvantage of an ugly merge commit?? I don't get it. Just merge and you're done. Is there something I'm missing? – SwimBikeRun May 26 '18 at 21:32
  • Best answer so far. It is interesting that I've intuitively moved to PR tab to do this, without too much thinking. However, I think it would be best to have REBASE FORK button next to (or instead) the FORK button. That was the first thing I've searched for - Rebase Fork button – Vladimir Djuricic Apr 09 '20 at 12:09
  • Why hasn't Github improved this stupid UI after so long? It requires at least 3 clicks to compare, and reload the page for a few seconds! waste time! – Time Killer Feb 12 '21 at 03:08
  • @Transformer your wish has been [granted](https://stackoverflow.com/questions/7244321/how-do-i-update-or-sync-a-forked-repository-on-github/67425996#67425996), albeit 4 years late ;) – Madhu Bhat May 09 '21 at 15:26
611

Here is GitHub's official document on Syncing a fork:

Syncing a fork

The Setup

Before you can sync, you need to add a remote that points to the upstream repository. You may have done this when you originally forked.

Tip: Syncing your fork only updates your local copy of the repository; it does not update your repository on GitHub.

$ git remote -v
# List the current remotes
origin  https://github.com/user/repo.git (fetch)
origin  https://github.com/user/repo.git (push)

$ git remote add upstream https://github.com/otheruser/repo.git
# Set a new remote

$ git remote -v
# Verify new remote
origin    https://github.com/user/repo.git (fetch)
origin    https://github.com/user/repo.git (push)
upstream  https://github.com/otheruser/repo.git (fetch)
upstream  https://github.com/otheruser/repo.git (push)

Syncing

There are two steps required to sync your repository with the upstream: first you must fetch from the remote, then you must merge the desired branch into your local branch.

Fetching

Fetching from the remote repository will bring in its branches and their respective commits. These are stored in your local repository under special branches.

$ git fetch upstream
# Grab the upstream remote's branches
remote: Counting objects: 75, done.
remote: Compressing objects: 100% (53/53), done.
remote: Total 62 (delta 27), reused 44 (delta 9)
Unpacking objects: 100% (62/62), done.
From https://github.com/otheruser/repo
 * [new branch]      master     -> upstream/master

We now have the upstream's master branch stored in a local branch, upstream/master

$ git branch -va
# List all local and remote-tracking branches
* master                  a422352 My local commit
  remotes/origin/HEAD     -> origin/master
  remotes/origin/master   a422352 My local commit
  remotes/upstream/master 5fdff0f Some upstream commit

Merging

Now that we have fetched the upstream repository, we want to merge its changes into our local branch. This will bring that branch into sync with the upstream, without losing our local changes.

$ git checkout master
# Check out our local master branch
Switched to branch 'master'

$ git merge upstream/master
# Merge upstream's master into our own
Updating a422352..5fdff0f
Fast-forward
 README                    |    9 -------
 README.md                 |    7 ++++++
 2 files changed, 7 insertions(+), 9 deletions(-)
 delete mode 100644 README
 create mode 100644 README.md

If your local branch didn't have any unique commits, git will instead perform a "fast-forward":

$ git merge upstream/master
Updating 34e91da..16c56ad
Fast-forward
 README.md                 |    5 +++--
 1 file changed, 3 insertions(+), 2 deletions(-)

Tip: If you want to update your repository on GitHub, follow the instructions here

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
jumpnett
  • 6,967
  • 1
  • 19
  • 24
  • 2
    This updates my local fork, but my fork on Github.com still says "43 commits behind". I had to use lobzik's technique to create a pull request for myself to merge the master changes into my Github.com fork. – Michael McGinnis Jan 23 '15 at 17:38
  • 18
    @MichaelMcGinnis After merging locally, you would have to push your changes to github. `git push origin master` – jumpnett Feb 11 '15 at 22:50
  • 1
    Might be smart to push with `--follow-tags`: http://stackoverflow.com/a/26438076/667847 – kenny Nov 06 '15 at 15:19
  • 1
    I have to do it for all branches separately `git merge upstream/master`, then check out to develop branch and do `git merge upstream/develop` – Shobi May 28 '17 at 13:02
  • https://stackoverflow.com/a/14074925/470749 was helpful to me because I was getting `Permission denied (publickey). fatal: Could not read from remote repository.` when trying to fetch from Facebook's Github account upstream. – Ryan Jan 26 '18 at 04:28
  • For those of you following the instructions, you can then run "git commit" then "git push" to see the fork changes on your forked GitHub repo – Angel Cloudwalker Mar 05 '20 at 15:14
129

A lot of answers end up moving your fork one commit ahead of the parent repository. This answer summarizes the steps found here which will move your fork to the same commit as the parent.

  1. Change directory to your local repository.

    • Switch to master branch if you are not git checkout master
  2. Add the parent as a remote repository, git remote add upstream <repo-location>

  3. Issue git fetch upstream
  4. Issue git rebase upstream/master

    • At this stage you check that commits what will be merged by typing git status
  5. Issue git push origin master

For more information about these commands, refer to step 3.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Sahar Rabinoviz
  • 1,939
  • 2
  • 17
  • 28
  • 14
    @MT: Where do you enter these commands, though? The gist of the question, as I understand it, is how to resynchronize your personal *GitHub* fork with the main project, and **do this all from GitHub**. In other words, how can you update your remote fork *without* a local repository? – John Y May 16 '16 at 15:33
  • 7
    @JohnY Using GitHub will always create an extra commit. You need to do all this in a shell on a local repo to avoid that extra commit. – Jonathan Cross Oct 14 '16 at 21:51
78

If, like me, you never commit anything directly to master, which you should really, you can do the following.

From the local clone of your fork, create your upstream remote. You only need to do that once:

git remote add upstream https://github.com/whoever/whatever.git

Then whenever you want to catch up with the upstream repository master branch you need to:

git checkout master
git pull upstream master

Assuming you never committed anything on master yourself you should be done already. Now you can push your local master to your origin remote GitHub fork. You could also rebase your development branch on your now up-to-date local master.

Past the initial upstream setup and master checkout, all you need to do is run the following command to sync your master with upstream: git pull upstream master.

Slion
  • 2,558
  • 2
  • 23
  • 27
  • 1
    "You could also rebase your development branch on your now up-to-date local master." How can I do this? – Niels Oct 15 '20 at 14:55
  • First run `git checkout my-dev-branch` to switch to your dev branch then `git rebase master`. You could also just run `git rebase master my-dev-branch` which basically combine those two commands. See [git rebase docs](https://git-scm.com/docs/git-rebase). – Slion Oct 16 '20 at 08:26
68

Foreword: Your fork is the "origin" and the repository you forked from is the "upstream".

Let's assume that you cloned already your fork to your computer with a command like this:

git clone git@github.com:your_name/project_name.git
cd project_name

If that is given then you need to continue in this order:

  1. Add the "upstream" to your cloned repository ("origin"):

    git remote add upstream git@github.com:original_author/project_name.git
    
  2. Fetch the commits (and branches) from the "upstream":

    git fetch upstream
    
  3. Switch to the "master" branch of your fork ("origin"):

    git checkout master
    
  4. Stash the changes of your "master" branch:

    git stash
    
  5. Merge the changes from the "master" branch of the "upstream" into your the "master" branch of your "origin":

    git merge upstream/master
    
  6. Resolve merge conflicts if any and commit your merge

    git commit -am "Merged from upstream"
    
  7. Push the changes to your fork

    git push
    
  8. Get back your stashed changes (if any)

    git stash pop
    
  9. You're done! Congratulations!

GitHub also provides instructions for this topic: Syncing a fork

Benny Code
  • 51,456
  • 28
  • 233
  • 198
  • 1
    Helped partly: Is `git remote add upstream git@github.com:original_author/project_name.git` just an alias for `git remote add upstream https://github.com/original_author/project_name.git` ? – Wolf Jun 26 '17 at 14:44
  • 2
    [Wolf](https://stackoverflow.com/users/2932052/wolf), guessing you know this by now, but for posterity... It is the format for ssh. https://help.github.com/articles/configuring-a-remote-for-a-fork/ – Brad Ellis Jan 26 '18 at 21:02
  • 2
    Thank you very much. `git stash` and `git stash pop` part very helpful – Krishna Mar 04 '19 at 05:41
  • This worked. After git merge upstream/master, auto merge failed due to unmerged paths which I had to run git add -A then git commit -m "message" then it was up to date. – Vicente Antonio G. Reyes Dec 31 '19 at 13:10
54

There are three ways one can do that: from the web UI (Option 1), from the GitHub CLI (Option 2), or from the command line (Option 3).


Option 1 - Web UI

  1. On GitHub, navigate to the main page of the forked repository that you want to sync with the upstream repository.

  2. Select the Fetch upstream drop-down.

enter image description here

  1. Review the details about the commits from the upstream repository, then click Fetch and merge.

enter image description here


Option 2 - GitHub CLI

To update the remote fork from its parent, use the gh repo sync subcommand and supply your fork name as argument.

$ gh repo sync owner/cli-fork

If the changes from the upstream repository cause conflict then the GitHub CLI can't sync. You can set the -force flag to overwrite the destination branch.


Option 3 - Command Line

Before syncing one's fork with an upstream repository, one must configure a remote that points to the upstream repository in Git.

1 Open Git Bash.

2 Change the current working directory to your local project.

3 Fetch the branches and their respective commits from the upstream repository. Commits to BRANCHNAME will be stored in the local branch upstream/BRANCHNAME.

$ git fetch upstream
> remote: Counting objects: 75, done.
> remote: Compressing objects: 100% (53/53), done.
> remote: Total 62 (delta 27), reused 44 (delta 9)
> Unpacking objects: 100% (62/62), done.
> From https://github.com/ORIGINAL_OWNER/ORIGINAL_REPOSITORY
>  * [new branch]      main     -> upstream/main

4 Check out your fork's local default branch - in this case, we use main.

$ git checkout main
> Switched to branch 'main'

5 Merge the changes from the upstream default branch - in this case, upstream/main - into your local default branch. This brings your fork's default branch into sync with the upstream repository, without losing your local changes.

$ git merge upstream/main
> Updating a422352..5fdff0f
> Fast-forward
>  README                    |    9 -------
>  README.md                 |    7 ++++++
>  2 files changed, 7 insertions(+), 9 deletions(-)
>  delete mode 100644 README
>  create mode 100644 README.md

If one's local branch didn't have any unique commits, Git will instead perform a "fast-forward":

$ git merge upstream/main
> Updating 34e91da..16c56ad
> Fast-forward
>  README.md                 |    5 +++--
>  1 file changed, 3 insertions(+), 2 deletions(-)

Note: Syncing one's fork only updates one's local copy of the repo. To update one's fork on GitHub.com, one must push ones changes.


Source: GitHub Docs - Syncing a fork

rafvasq
  • 1,512
  • 3
  • 18
  • 48
Gonçalo Peres
  • 11,752
  • 3
  • 54
  • 83
52

GitHub has now introduced a feature to sync a fork with the click of a button.

Go to your fork, click on Fetch upstream, and then click on Fetch and merge to directly sync your fork with its parent repo.

enter image description here

You may also click on the Compare button to compare the changes before merging.

Reference: GitHub's documentation

Innat
  • 16,113
  • 6
  • 53
  • 101
Madhu Bhat
  • 13,559
  • 2
  • 38
  • 54
  • I tried this and no PR was created, cool! And if your branch can be synced with a fast-forward merge, no divergence will occur. – li ki May 07 '21 at 23:44
  • 3
    For now, this function will first compare the branch name between the original and the forked repos. If the same name is found, the upstream of the branch in the fork is the branch with the same name in the original; if it is not found, the upstream will be the default branch (HEAD) of the original. This works fine in most cases, but if some branch modification has occurred in the original repo (e.g., adding or deleting a branch with the same name which already exists in the forked repo, or changing the default branch), the result of the sync may not match you expectations. – li ki May 08 '21 at 00:31
48

Since November 2013 there has been an unofficial feature request open with GitHub to ask them to add a very simple and intuitive method to keep a local fork in sync with upstream:

https://github.com/isaacs/github/issues/121

Note: Since the feature request is unofficial it is also advisable to contact support@github.com to add your support for a feature like this to be implemented. The unofficial feature request above could be used as evidence of the amount of interest in this being implemented.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
isedwards
  • 2,429
  • 21
  • 29
25

As of the date of this answer, GitHub has not (or shall I say no longer?) this feature in the web interface. You can, however, ask support@github.com to add your vote for that.

In the meantime, GitHub user bardiharborow has created a tool to do just this: https://upriver.github.io/

Source is here: https://github.com/upriver/upriver.github.io

Lucero
  • 59,176
  • 9
  • 122
  • 152
  • 2
    While I do find the tool a good idea the reality is that's BROKEN. It did load only 20 repos from my account and even the footer redirects to a website that does not exists. If that's fixed I will be a big advocate. – sorin Oct 28 '16 at 16:07
  • 2
    As of today, I have successfully used upriver to sync a fork with the upstream repo, so it's working for my purposes and I will continue to use it. – NauticalMile Jul 17 '17 at 02:55
  • 1
    @sorin These 20 repo/branch limitation (rather, it is 30 now) comes from the GitHub default paging settings. There needs to be some adaptions to the code in order to handle this. – Andreas Jan 18 '18 at 08:19
23

If you are using GitHub for Windows or Mac then now they have a one-click feature to update forks:

  1. Select the repository in the UI.
  2. Click "Update from user/branch" button the top.
Shital Shah
  • 63,284
  • 17
  • 238
  • 185
12

Actually, it is possible to create a branch in your fork from any commit of the upstream in the browser:

Enter image description here

You can then fetch that branch to your local clone, and you won't have to push all that data back to GitHub when you push edits on top of that commit. Or use the web interface to change something in that branch.

How it works (it is a guess, I don't know how exactly GitHub does it): forks share object storage and use namespaces to separate users' references. So you can access all commits through your fork, even if they did not exist by the time of forking.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
max630
  • 8,762
  • 3
  • 30
  • 55
10

Follow the below steps. I tried them and it helped me.

Checkout to your branch

Syntax: git branch yourDevelopmentBranch
Example: git checkout master

Pull source repository branch for getting the latest code

Syntax: git pull https://github.com/tastejs/awesome-app-ideas master
Example: git pull https://github.com/ORIGINAL_OWNER/ORIGINAL_REPO.git BRANCH_NAME

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Venkat.R
  • 7,420
  • 5
  • 42
  • 63
  • 1
    If you're using GitHub, you might also want to push your changes to your GitHub branch. `git push HttpsForYourForkOfTheRepo BRANCH_NAME` – user3731622 Jan 22 '16 at 19:34
10

I update my forked repos with this one line:

git pull https://github.com/forkuser/forkedrepo.git branch

Use this if you dont want to add another remote endpoint to your project, as other solutions posted here.

Rafael Z. B. Bravo
  • 1,022
  • 10
  • 23
  • 2
    Are there limitations on this? i.e. does it apply only to cases where you have not added commits, merges, pull requests, or had pull requests merged into upstream since the last update? – LightCC Sep 11 '17 at 07:30
  • 1
    it does work like a normal pull from a remote branch. If you did X commits on your local repo and now you are Y commits behind the original repo, it will bring the Y commits to your local branch and, probably, get you some conflicts to resolve. – Rafael Z. B. Bravo Sep 11 '17 at 20:23
  • 2
    @LightCC This is not different than pulling from a previously added remote at all, except for the fact that you haven't added a [remote](https://git-scm.com/book/en/v2/Git-Basics-Working-with-Remotes). So the disadvantage is that you'll have to enter the full repository URL everytime you want to `pull`. – Marc.2377 Apr 17 '19 at 02:34
  • 1
    This is a perfect solution if you don't have to pull many times from the original repo, or the project forked is relatively simple. – AxeEffect Apr 28 '20 at 22:41
10
$ git remote add upstream https://github.com/....

$ git pull upstream main

$ git push
DocJ457
  • 797
  • 7
  • 17
9

As a complement to this answer, I was looking for a way to update all remote branches of my cloned repo (origin) from upstream branches in one go. This is how I did it.

This assumes you have already configured an upstream remote pointing at the source repository (where origin was forked from) and have synced it with git fetch upstream.

Then run:

for branch in $(git ls-remote --heads upstream|sed 's#^.*refs/heads/##'); do git push origin refs/remotes/upstream/$branch:refs/heads/$branch; done

The first part of this command lists all heads in the upstream remote repo and removes the SHA-1 followed by refs/heads/ branch name prefix.

Then for each of these branches, it pushes the local copy of the upstream remote tracking branch (refs/remotes/upstream/<branch> on local side) directly to the remote branch on origin (refs/heads/<branch> on remote side).

Any of these branch sync commands may fail for one of two reasons: either the upstream branch have been rewritten, or you have pushed commits on that branch to your fork. In the first case where you haven't committed anything to the branch on your fork it is safe to push forcefully (Add the -f switch; i.e. git push -f in the command above). In the other case this is normal as your fork branch have diverged and you can't expect the sync command to work until your commits have been merged back into upstream.

Thomas Guyot-Sionnest
  • 2,251
  • 22
  • 17
8

The "Pull" app is an automatic set-up-and-forget solution. It will sync the default branch of your fork with the upstream repository.

Visit the URL, click the green "Install" button and select the repositories where you want to enable automatic synchronization.

The branch is updated once per hour directly on GitHub, on your local machine you need to pull the master branch to ensure that your local copy is in sync.

krlmlr
  • 25,056
  • 14
  • 120
  • 217
  • 2
    Please note that with the basic setup, you can lose the changes made in your forked repository. To keep the changes, set up a config file and specify a ```mergemethod```. More on this [here](https://stackoverflow.com/a/58966490/10155936) – Saurabh P Bhandari Nov 21 '19 at 03:06
  • 1
    I did note that the basic setup sends pull requests and merges them (as opposed to what's stated in the documentation). This is slightly annoying but solves the data loss problem? – krlmlr Nov 21 '19 at 09:24
6

If you set your upstream. Check with git remote -v, then this will suffice.

git fetch upstream
git checkout master
git merge --no-edit upstream/master
git push
prosti
  • 42,291
  • 14
  • 186
  • 151
5

When you have cloned your forked repository, go to the directory path where your clone resides and the few lines in your Git Bash Terminal.

$ cd project-name

$ git remote add upstream https://github.com/user-name/project-name.git
 # Adding the upstream -> the main repo with which you wanna sync

$ git remote -v # you will see the upstream here 

$ git checkout master # see if you are already on master branch

$ git fetch upstream

And there you are good to go. All updated changes in the main repository will be pushed into your fork repository.

The "fetch" command is indispensable for staying up-to-date in a project: only when performing a "git fetch" will you be informed about the changes your colleagues pushed to the remote server.

You can still visit here for further queries

Prateek Chanda
  • 199
  • 3
  • 3
4

Android Studio now has learned to work with GitHub fork repositories (you don't even have to add "upstream" remote repository by console command).

Open menu VCSGit

And pay attention to the two last popup menu items:

  • Rebase my GitHub fork

  • Create Pull Request

Try them. I use the first one to synchronize my local repository. Anyway the branches from the parent remote repository ("upstream") will be accessible in Android Studio after you click "Rebase my GitHub fork", and you will be able to operate with them easily.

(I use Android Studio 3.0 with "Git integration" and "GitHub" plugins.)

Enter image description here

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
alexshr
  • 989
  • 8
  • 12
4

How to update your forked repo on your local machine?

First, check your remote/master

git remote -v

You should have origin and upstream. For example:

origin  https://github.com/your___name/kredis.git (fetch)
origin  https://github.com/your___name/kredis.git (push)
upstream    https://github.com/rails/kredis.git (fetch)
upstream    https://github.com/rails/kredis.git (push)

After that go to main:

git checkout main

and merge from upstream to main:

git merge upstream/main
AlexSh
  • 1,468
  • 15
  • 12
4

Assuming your fork is https://github.com/me/foobar and original repository is https://github.com/someone/foobar

  1. Visit https://github.com/me/foobar/compare/master...someone:master

  2. If you see green text Able to merge then press Create pull request

  3. On the next page, scroll to the bottom of the page and click Merge pull request and Confirm merge.

Use this code snippet to generate link to sync your forked repository:

new Vue ({
    el: "#app",
    data: {
      yourFork: 'https://github.com/me/foobar',
      originalRepo: 'https://github.com/someone/foobar'
    },
    computed: {
      syncLink: function () {
        const yourFork = new URL(this.yourFork).pathname.split('/')
        const originalRepo = new URL(this.originalRepo).pathname.split('/')
        if (yourFork[1] && yourFork[2] && originalRepo[1]) {
          return `https://github.com/${yourFork[1]}/${yourFork[2]}/compare/master...${originalRepo[1]}:master`
        }
        return 'Not enough data'
      }
    }
  })
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app">
  Your fork URL: <input size=50 v-model="yourFork" /> <br />
  Original repository URL: <input v-model="originalRepo" size=50 /> <br />
  Link to sync your fork: <a :href="syncLink">{{syncLink}}</a>
</div>
Ilyich
  • 4,966
  • 3
  • 39
  • 27
  • 2
    You deserve an award. Nice answer. This worked for me and I think is pretty normal. I went and did a git pull after on my local repo and updated. Your instructions are good. To someone new, you will have to play with the dropdown lists on the compare screen first to get the arrow to go the correct direction. This gives you the http://github.com/myside...theirside correct link in the address bar. – Beeeaaar Mar 15 '21 at 04:24
3

I would like to add on to @krlmlr's answer.

Initially, the forked repository has one branch named : master. If you are working on a new feature or a fix, you would generally create a new branch feature and make the changes.

If you want the forked repository to be in sync with the parent repository, you could set up a config file(pull.yml) for the Pull app (in the feature branch), like this:

version: "1"
rules:
  - base: feature
    upstream: master
    mergeMethod: merge
  - base: master
    upstream: parent_repo:master
    mergeMethod: hardreset

This keeps the master branch of the forked repo up-to-date with the parent repo. It keeps the feature branch of the forked repo updated via the master branch of the forked repo by merging the same. This assumes that the feature branch is the default branch which contains the config file.

Here two mergemethods are into play, one is hardreset which helps force sync changes in the master branch of the forked repo with the parent repo and the other method is merge. This method is used to merge changes done by you in the feature branch and changes done due to force sync in the master branch. In case of merge conflict, the pull app will allow you to choose the next course of action during the pull request.

You can read about basic and advanced configs and various mergemethods here.

I am currently using this configuration in my forked repo here to make sure an enhancement requested here stays updated.

Saurabh P Bhandari
  • 6,014
  • 1
  • 19
  • 50
2

That depends on the size of your repository and how you forked it.

If it's quite a big repository you may have wanted to manage it in a special way (e.g. drop history). Basically, you can get differences between current and upstream versions, commit them and then cherry pick back to master.

Try reading this one. It describes how to handle big Git repositories and how to upstream them with latest changes.

itsmysterybox
  • 2,748
  • 3
  • 21
  • 26
s0nicYouth
  • 470
  • 3
  • 15
2

If you want to keep your GitHub forks up to date with the respective upstreams, there also exists this probot program for GitHub specifically: https://probot.github.io/apps/pull/ which does the job. You would need to allow installation in your account and it will keep your forks up to date.

metanerd
  • 713
  • 1
  • 6
  • 21
2

Try this, Click on "Fetch upstream" to sync your forked repo from upstream master. enter image description here

Kumar Gaurav
  • 899
  • 5
  • 19
  • 35
1

There are two main things on keeping a forked repository always update for good.

1. Create the branches from the fork master and do changes there.

So when your Pull Request is accepted then you can safely delete the branch as your contributed code will be then live in your master of your forked repository when you update it with the upstream. By this your master will always be in clean condition to create a new branch to do another change.

2. Create a scheduled job for the fork master to do update automatically.

This can be done with cron. Here is for an example code if you do it in linux.

$ crontab -e

put this code on the crontab file to execute the job in hourly basis.

0 * * * * sh ~/cron.sh

then create the cron.sh script file and a git interaction with ssh-agent and/or expect as below

#!/bin/sh
WORKDIR=/path/to/your/dir   
REPOSITORY=<name of your repo>
MASTER="git@github.com:<username>/$REPOSITORY.git"   
UPSTREAM=git@github.com:<upstream>/<name of the repo>.git  

cd $WORKDIR && rm -rf $REPOSITORY
eval `ssh-agent` && expect ~/.ssh/agent && ssh-add -l
git clone $MASTER && cd $REPOSITORY && git checkout master
git remote add upstream $UPSTREAM && git fetch --prune upstream
if [ `git rev-list HEAD...upstream/master --count` -eq 0 ]
then
    echo "all the same, do nothing"
else
    echo "update exist, do rebase!"
    git reset --hard upstream/master
    git push origin master --force
fi
cd $WORKDIR && rm -rf $REPOSITORY
eval `ssh-agent -k`

Check your forked repository. From time to time it will always show this notification:

This branch is even with <upstream>:master.

enter image description here

eQ19
  • 9,880
  • 3
  • 65
  • 77
1

Use these commands (in lucky case)

git remote -v
git pull
git fetch upstream
git checkout master
git merge upstream/master --no-ff
git add .
git commit -m"Sync with upstream repository."
git push -v
Vy Do
  • 46,709
  • 59
  • 215
  • 313
  • If there's a conflict then one'd only need to resolve those after the merge command and mark the resolves by `git add` command for the conflicted files. Also, if the repo in question is a forked one someone has to first define the `upstream`: `git remote add upstream https://...git` where the git is for the repo which got forked. – Csaba Toth Jun 29 '21 at 21:11
  • Also, GitHub's PR (the UI Fetch button creates the PR against the fork repo) is a shitshow if there's a conflict. I'd rather just go with these manual steps. – Csaba Toth Jun 29 '21 at 21:12
1

If you use GitHub Desktop, you can do it easily in just 6 steps (actually only 5).

Once you open Github Desktop and choose your repository,

  1. Go to History tab
  2. Click on the search bar. It will show you all the available branches (including upstream branches from parent repository)
  3. Select the respective upstream branch (it will be upstream/master to sync master branch)
  4. (OPTIONAL) It will show you all the commits in the upstream branch. You can click on any commit to see the changes.
  5. Click Merge in master / branch-name, based on your active branch.
  6. Wait for GitHub Desktop to do the magic.

Checkout the GIF below as an example:

Sync Upstream branches in a forked repository from the parent repository

Gangula
  • 5,193
  • 4
  • 30
  • 59
0

Delete your remote dev from github page

then apply these commands:

1) git branch -D dev
2) git fetch upstream
3) git checkout master
4) git fetch upstream && git fetch upstream --prune && git rebase upstream/master && git push -f origin master
5) git checkout -b dev
6) git push origin dev
7) git fetch upstream && git fetch upstream --prune && git rebase upstream/dev && 8) git push -f origin dev

to see your configuration use this command:

git remote -v
-1
rm -rf oldrepository
git clone ...

There may be subtler options, but it is the only way that I have any confidence that my local repository is the same as upstream.

Tuntable
  • 3,276
  • 1
  • 21
  • 26