Search code examples
gitrestoregit-remote

How do I restore a remote crashed Git repo?


Okay. We all know that every clone of a repo is good as a backup of the cloned repo. Fine. Also, every remote whose history gets updated with git fetch is backed up in that repo where git fetch was applied.

But when it comes to restore of the backup: how do I do it? What is the right opposite command of git fetch?

One of my Git repo has issues:

git status
fatal: unable to read tree 0d2f806b01ded93e76a6f2c7a68429939f483026

Yes, I could start repairing the repo somehow, but – lucky me – I did a git fetch notebook on a remote machine right before my repo on notebook died.

So, I have a repo on desktop, where I have all the latest refs of my died repo (as refs/remote/notebook/fix/issue1, refs/remote/notebook/master, etc.).

How do I restore the repo on notebook with this information?


Solution

  • I found an easy way:

    on desktop, ask git for the known remote branches of notebook:

    git branch -r | grep notebook > notebookbranches
    

    Now we have a file called notebookbranches that holds all the branches of the notebook.

    On notebook, create a fresh empty repo called myrepo2

    git init myrepo2
    

    Add this repo as remote on desktop:

    git remote add myrepo2 //notebook/D$/myrepo2 # working on Windows, use share name
    git fetch myrepo2 # fetch current state of myrepo2
    

    Now, open your favourite editor on the file notebookbranches. The file currently looks like this:

    notebook/fix/issue1
    notebook/master
    ...
    

    Modify the file to look like this:

    git push myrepo2 -f refs/remotes/notebook/fix/issue1
    git push myrepo2 -f refs/remotes/notebook/master
    ...
    

    Make this file executable and execute it.

    When the script has finished, all the branches are present on the myrepo2 repo but are stored under .git/refs/remotes/notebook.

    Take all the files present here and move them to the .git/refs/heads/ folder.

    Then, you're done.