Search code examples
gitgithubversion-control

Github - Local repository already exists. How do I create a remote github repository and sync to it?


Summary of what I did

I frequently encounter the following problem:

  • I create a folder for a project on my local machine and start working
  • Later, if I want to keep this code longer term, then I would like to be able to add it to version control using Git

Note: Rust and Cargo: This problem occurs by default when using Rust and Cargo. Cargo (the Rust package/project manager), by default, will create a git repository when creating a new project with cargo new. This means that, if you have already created a git repository, for example via github.com (or others) there is no obvious way to synchronize the two.

One solution is to:

  • create a Github repo (on Github, Gitlab, Bitbucket etc)
  • clone this repo from the cloud to a new directory on my local machine
  • copy the files from the existing directory to the new one created by the git clone step above
  • commit new code in the new repo and push the new changes
  • finally, delete the old directory

This seems like quite a common solution, but as far as I know there is no convenient solution.

Questions

  • How do I push my work on branch master from the local repo to the remote?

  • How do I pull down the new files from the remote repo to the local?

  • Essentially I want to sync the 2 repos without going through the whole process of making a new folder and deleting the old one as I described above. How can I do this?


Solution

  • This is a much easier solution:

    cargo new my-project-name # FYI: cargo creates a directory with a git repository
    cd my-project-name
    git remote add origin https://github.com/github-username/my-project-name.git
    git add .
    git commit -m "initial commit"
    git pull --rebase origin master
    # ... now resolve any conflicts ...
    git push --set-upstream origin master
    

    This is not specific to Rust + Cargo, I just use this as an example.