Coverity fixes

This fixes a few problems pointed out by the coverity scan including missing checks for OOM, not checking error codes, memory leaks etc.

This doesn't fix nearly all of the problems but does address lots of the low hanging fruit.
A few lines after this there is a ```git_buf_free()```, which should execute regardless.