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
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!
- make a copy of the directories affected, preferably on another hard drive or in the cloud
recursively delete the
.gitdirectory in the affected directory
rm -rf .git
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
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 -fthose files before you can complete the
The files you modified after the last
git pushwill 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.
Once you’re done, you’re ready to commit. Do a quick sanity check with
to be sure the history look familiar. and then
git commit -a
and same the merge commit message.
On this command, do NOT use
--forcein case some problem arose!
An alternative method is:
- reclone your git repo from remote
- manually copy files from the old corrupt directory to the new directory
git committhe changes
This is a little “cruder” but just as effective.
- git recovery reference