I would like to determine if a file (from a certain commit/revision) is binary or not. I know git has some sort of method to do this since when you diff a binary it gives you a different result then when diffing a regular text file. Knowing this, I have seen posts online about diffing a file to the empty tree branch in order to determine if it is binary. If the file is binary, it will show two dashes where the diff line numbers would go.
For example the following:
git diff 4b825dc642cb6eb9a060e54bf8d69288fbee4904 --numstat HEAD -- logo.png
will return
- - logo.png
The dashes are there because this file is a binary file. A regular text file will show the line differences.
I'd like to use this fact to detect whether a file is binary or not using Libgit2sharp, but I can't figure out how to do so.
I am also open to any alternative approaches, if this one is too roundabout.
libgit2 provides this heuristic for blobs and buffers. Since the thing you want to handle is a blob, you can query the IsBinary
attribute of the Blob object representing that object.
If you need a Blob object, you can look up a revision using the Repository's RevParse method to get a GitObject instance and then call Peel on it to turn it into a Blob.