gitclonemirrorgit-mirror

How to copy a git repo to a new repo without syncing to the original


I am attempting to take a remote repo on GHE and make a full identical copy of it in another remote repo on GHE such that cloning either one will provide the exact same local repo with indication that the other one exists. This should include all branches and the full history.

Originally I tried

Git clone --bare original-repo-url
git push --mirror new-repo-url

I was under the impression that the push --mirror somehow syncs the two remote repos but believe this may be wrong. Doing the above would the two remotes be synced? I believe currently I was mistaken and either needed to remove the remote of the local using

git remote rm origin

or just making a new local clone of the new repo so that my local is not linked to the original-repo remote anymore. Is this correct?


Solution

  • Remotes don't "sync" with each other. All syncing in Git is done by pulling and pushing via clones.

    git push --mirror takes all refs (local branches, remote branches, tags) and pushes them as local references.

    git push --all will only push local branches. This will miss any remote branches which don't have local ones.

    Only use git push --mirror once. If you do it again things will get weird.

    Once your new repository is populated, either make new clones, or update the remotes on your existing clones with git remote set-url origin <newurl>.


    Git repositories are only connected to each other through their [remotes](https://git-scm.com/book/en/v2/Git-Basics-Working-with-Remotes). Delete the remote.

    git clone as normal. This is a complete copy of the original repository, its history, branches, and tags.

    Cloning creates a remote to the original repo called "origin". Delete it: git remote rm origin. This will delete all remote branches and tags (origin/main, origin/v1.1, etc). Now your cloned repo has no remote and no connection to the original.


    From discussion in the comments, let's walk through this.

    You have a remote repo, let's say it's at git:example.com/repo.git.

    You have a local repo cloned from this remote.

    You want to...

    • Make a copy of the remote.
    • Which does not refer to the original.
    • And have a local repo point at the copy.

    To make the unattached remote copy...

    1. Make a bare clone of the remote: git clone --bare git:example.com/repo.git.
    2. Remove its origin remote: git remote rm origin.
    3. Upload it to its server like you would any other files.

    Now you have a copy of the original with no reference to the original. Let's say it's at git:example.com/copy.git.

    Then to have a local clone of the copy...

    1. Clone a new local repo: git clone git:example.com/copy.git
    2. Or point your existing local repo at the copy: git remote set-url origin git:example.com/repo.git and git pull to make sure it's up to date.