简体   繁体   中英

Restore all git branches on remote repository from local

I have a local git repository containing code right from the start of the project. But the remote repository is completely deleted (all branches and commit history are gone).

Is there a way to restore all the branches (and commit history) on the remote repository?

The method for restoring the missing remote depends on whether you will push to a new empty repository, or clone from your own copy.

To push to a new empty repository

First, create the repository on the server ( git init --bare and any other setup required). Make sure you have push access to that server. You can add its URL via, eg:

git remote add new-server ssh://user@host/path/to/repo.git

assuming you will use ssh to push. If pushing via https, make the obvious adjustments.

At this point you can just run:

git push --tags new-server 'refs/remotes/origin/**:refs/heads/*'

This pushes all your remote-tracking names for the original remote origin , creating them as branch names on new-server . If your remote was not named origin, make the obvious substitution. The --tags pushes all tags as well.

To clone to a new repository

To prepare the local repository so that it is suitable for use as a clone, we will want to create a local branch name corresponding to each remote-tracking name. I will assume here that each remote-tracking name is named origin/whatever ; if not, replace origin with the appropriate string.

To do this:

git for-each-ref --format='%(refname)' refs/remotes/origin |
    while read rref; do
        lref=${rref#refs/remotes/origin/} # strip the boilerplate
        [ "$lref" = HEAD ] && continue # skip origin/HEAD
        git branch $lref $rref ||
            echo "WARNING: did not create $lref, make sure that's OK"
    done

This is likely to print at least one warning, about not being able to create master . For each warning—each local branch you have that already corresponds to a remote-tracking name—make sure the branch up to date or ahead of the remote-tracking name.

Now make sure that the client is reachable via whatever URL you intend to use, then, on the server, run:

cd server/path/to
git clone --mirror --bare ssh://user@host/client/path/to/repo.git

This will create a bare clone named repo.git in server/path/to . You may want to delete the new clone's origin by doing:

cd repo.git
git remote remove origin

since presumably you never want to re-mirror the repository you just cloned.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM