Updating Local Git Repos When Upstream Moves

The scenario: the "main" repository of a git project has changed, either an organisation rebranded, a project got a new maintainer, or a fork became the acknowledged master. In Subversion, this was the svn switch command and git has an equivalent. It's relatively easy in git to change your upstream - once you know how - so don't be tempted to just delete your local repo and re-clone! We can do better than that :)

Your local repo keeps a list of "remotes" - other copies of the repository that it knows about. To list all the remotes you have, and which URL they point to, use this command:

git remote -v

Look at the list and work out which remote(s) need to update to a new URL. The first column is the remote name, and the second is the URL where the repo exists (you will see them all twice, one labelled "fetch" and one labelled "push"; this allows us to have different read and write endpoints for the same remote name but in practice is vanishingly rarely used so just try to ignore the duplication for the purposes of this manouvre).

First, delete the remote that points to the old location, so if the remote you want to change is called "upstream" then the command would be:

git remote remove upstream

Next, we need to create the new remote. Get the URL of the repo (copy it from the Github page, or whatever works for the hosting system you use) and create the new "upstream" repo like this:

git remote add upstream [paste url here]

Note: git does not actually CHECK that you've supplied information that will work at all! It might be worth following up with a git fetch upstream to confirm that you can communicate with the repository as expected.

All these settings are in git's .git/config file in a fairly easy format, so you can also go there to make changes (especially handy if you need to update a lot of remotes for some reason). Hopefully if you do come across this fairly unusual situation, the information here helps you to get back up and developing quickly.

4 thoughts on “Updating Local Git Repos When Upstream Moves

  1. Quick note on the Subversion analogy: the equivalent Subversion command would probably be [code]svn relocate[/code], which is used to change the repository's root URL. The [code]svn switch[/code] command is only used when switching to another branch within (the root of) the repository, which is actually more like [code]git checkout[/code].

    • Nope, you can edit the file and the effect is the same. I think the commands were probably introduced later - I do a bunch of things manually where there are helper commands now available but I haven't relearned stuff yet :) A great example is the set-url command that another commenter mentioned - never heard of it but probably does exactly what I described!

Leave a Reply

Please use [code] and [/code] around any source code you wish to share.