11

Suppose I clone Company C's repo of Project X from github to my local machine. I create a branch for myself locally, do some work on it and make commits to my branch locally.

Now I want to make a pull request to Company C, but I realize that I should have done a fork on gitub to create my own repo of Project X and cloned that instead of Company C's repo.

How do I recover from this without cloning my fork locally and starting over by copying files manually? I'd like to use git's magic to save myself.

JoelFan
  • 37,465
  • 35
  • 132
  • 205

3 Answers3

13

If you want to follow the development of the project you've cloned, by convention, we add another remote (named upstream) in addition to your origin remote.

So you have to:

  1. Fork the project on Github.com website.

  2. Rename the current origin remote (that tracks at the moment the upstream project) with a new name like upstream.

     git remote rename origin upstream
    
  3. Add your personal forked GitHub project as the origin remote.

     git remote add origin <URL of your personal github fork>
    

The idea behind that is to follow the naming conventions of:

  • origin for your personal repository
  • upstream for the project repository (to be able to sync your personal repository with developments made in the upstream repository)
Philippe
  • 28,207
  • 6
  • 54
  • 78
  • So I don't have to change the local branch of the original repo, because it tracks the remote by name ("remote")? – JoelFan Mar 08 '15 at 15:55
  • the convention is to have the remote `origin` to track the repository from which you cloned. At the moment it's the one of the upstream project. And because you want to modify as if you have cloned your personal repository, you must change to track your repository with `origin` and the upstream repository with `upstream` that way you follow the conventions which is always better... – Philippe Mar 08 '15 at 16:47
  • I come back to this answer few times a year. Thanks! – Atsushi Mar 23 '23 at 23:54
1

You simply need to add your fork as a remote in your existing clone:

git remote add <any name> <URL of fork>

You may also want to git remote rm the original repo.

JoelFan
  • 37,465
  • 35
  • 132
  • 205
SLaks
  • 868,454
  • 176
  • 1,908
  • 1,964
0

The overall strategy is as follows:

  1. See which remote repos are connected to your local repo
  2. Disconnect the remote repos from your local repos.
  3. Connect the desired remote repository to your local.

git remote -v #shows you the names of the remote repos
git remote remove {Name of the remote repo(s)}
git remote add {url of the desired remote repo}    
Au613
  • 1