Recovering from broken Git repo

Recently I was during a git commit just as I lost power on my computer. When I booted again, every git command except for git diff would give error:

fatal: your current branch appears to be broken

However, my changes were still present, as I could see via git diff. Luckily, I had previously git pushed all my prior commits. If I hadn’t have pushed them previously, the net effect would have been an unintentional squash of my non-pushed work.

This recovery will in effect “squash” the commits that weren’t previously pushed. NOTE: work done on other branches that wasn’t pushed is LOST irretrievably during this procedure!

Recovery

  1. make a copy of the directories affected, preferably on another hard drive or in the cloud
  2. recursively delete the .git directory in the affected directory
   rm -rf .git
   
  1. reconnect the directory to the remote repo, using example values:
   git init
   git remote add origin https://github.com/username/myreponame.git
   git add .
   git branch -u origin/master master
   
  1. There may be files that you previously added that would otherwise be blocked by .gitignore. If you get an error like

error: The following untracked working tree files would be overwritten by merge: Please move or remove them before you merge.

then you need to git add -f those files before you can complete the git pull. 5. The files you modified after the last git push will have messages like

Auto-merging setup.py CONFLICT (add/add): Merge conflict in setup.py Automatic merge failed; fix conflicts and then commit the result.

so use git mergetool to apply your updates. In general, consider using Meld for merging via one-time git mergetool setup 6. Once you’re done, you’re ready to commit. Do a quick sanity check with

   git log
   

to be sure the history look familiar. and then

   git commit -a
   

and same the merge commit message. 7. On this command, do NOT use -f or --force in case some problem arose!

   git push
   

Alternative

An alternative method is: 1. reclone your git repo from remote 2. manually copy files from the old corrupt directory to the new directory 3. git commit the changes

This is a little “cruder” but just as effective.

Notes