creationix/js-git — pull request #104 by dfries (2014-08-10 05:32:19+00:00)
Title: Data integrity fix, only expose final file

fs.writeFile will truncate the file, then write, during which time
other readers will get a zero length file or a partial (corrupted)
file. Fix by writing to a temporary file as the original git
tools do, add .lock to a refs file, and tmp_obj_ for object
files.

--
I was reading a branch ref and kept getting an empty hash, then later would get the expected hash. Fix by writing into a temporary file then doing a rename after. At least on Unix that's an atomic operation, any reader will either get the old value or the new value, but never the 0 length or truncated value as it is being written out. Especially for branches, if the program crashed or was killed at the wrong moment a whole tree could be lost if the refs/heads/master was in the process of being written, but was left empty.

As above this change avoids being told the repository is corrupt, the file is empty, that's why it is being flagged as an error.
git-fsck
Checking object directories: 100% (256/256), done.
error: object file ./objects/ad/3fb1076f9d689b566ea5200e2a4565f52e796a is empty
fatal: loose object ad3fb1076f9d689b566ea5200e2a4565f52e796a (stored in ./objects/ad/3fb1076f9d689b566ea5200e2a4565f52e796a) is corrupt