Little Git Tricks: Fix Reference Broken Error

I run recently into this strange error with one of my Git repositories:

Pull Failed: error: could not delete reference refs/remotes/origin/HEAD: cannot lock ref 'refs/remotes/origin/HEAD': unable to resolve reference 'refs/remotes/origin/HEAD': reference broken error: vs-ssh.visualstudio.com:v3/* did not send all necessary objects

While I usually would just rename the folder and check out the repository again, I thought this time I want to know what went wrong and invest a few minutes to learn something about Git.

I found multiple questions about the same problem, but the solutions that helped others did not work with my repository. I had to dig deeper and could pin down the problem with these commands:

$ git gc

fatal: bad object refs/remotes/origin/HEAD
fatal: failed to run repack
$ git fsck --full 

error: refs/remotes/origin/HEAD: badRefContent: 
Checking ref database: 100% (1/1), done.
Checking object directories: 100% (256/256), done.
Checking objects: 100% (6884/6884), done.
error: refs/remotes/origin/HEAD: invalid sha1 pointer 0000000000000000000000000000000000000000
...

Both commands located the problem in the file .git\refs\remotes\origin\HEAD, that was full of NULL placeholders. It is obvious that a series of NULL is not a valid content, but what is? I had to check other repositories and finally settled with this:

ref: refs/remotes/origin/master

After saving the HEAD file, I run git gc again and this time it did not show an error. Therefore, I went back to Git Kraken and run a successful git pull.

After this detour I could finally merge my work and push it to Azure DevOps. I hope this post helps you when Git throws the same errors at you.