Thank you for your donations!   Download the book!   Public source code repository   Join the group!

git commit-id

In a previous post I mentioned writing commit-id from git repository back into the book during the same commit, so that user can check how old his copy is. There are solutions e.g. here: https://stackoverflow.com/questions/16524225/how-can-i-populate-the-git-commit-id-into-a-file-when-i-commit, but not as simple as I was hoping to be. 

Turns out there is a simple one: you need to parse .git/HEAD to find out current branch ref, i.e. path to logs file. Parsing logs file is a bit more complex, it gives you past commit ids and dates. If you just need commit count so far, you don't have to parse anything, just count number of lines in a logs file.

There is no current commit hash, it would need to be calculated from content of the commit. Since writing that hash into a file changes its' content hash, it also changes commit hash, ... So, I settled with commit number, and date-time. For me, that's good enough, since it enables comparison between two copies of the book.

Sure, simple solution might have some drawbacks. Since I access git files directly, once they move or change this will cease to work, and then would need to be fixed. I didn't want to introduce pygit dependency. Maybe should have git properly called with arguments in a separated process and parse output, but I was too lazy.

In the end, I'm quite ok with how it turned out. Source section in colophon now looks like this:


with current commit number, date-time and branch. Didn't specified what is what in the colophon, I'm guessing that most people will get "the-bigger-the-newer-the-better" vibe there.

No comments:

Post a Comment