Automated Git Commit Number in LaTeX Document
I often use LaTeX to make my documents. Since it is all text, it makes sense to use Git (in combination with Github) as my version control system (it offers more control than, say, Dropbox over what and how often things are backed up + I can add meaningful commit messages). From time to time things will be passed around in their compiled PDF form, then addenda will be made to that (possibly by others) and things can get… messy, if you do not recall what version of your document you created that particular PDF with.
To solve this, I use git describe
which prints out what commit you are on. An
example output.
$ git describe
v4.5-39-gb338f76
Here, v4.5
is a tag of mine, 39
is the number of commits since that tag and
gb338f76
is the commit hash. Next up you will want that information used in
your LaTeX document. I pass it on by compiling with:
pdflatex '\newcommand{\versionortoday}{$(shell git describe --dirty)}\input{latexdocument}'
Where latexdocument
is your actual main document. Note that I use --dirty
this adds a dirty
tag to the describe output in case there are uncommitted
changes in the working tree. Compiling this way will provide your LaTeX
document with the command \versionortoday
. However this may create problems
when someone copies your document tree, but not the entire git repository and
thus want to compile without the version mention. As a backup for that, add the
following in your LaTeX document preamble.
\providecommand{\versionortoday}{\today}
This command makes \versionortoday
display today’s date (hence the ortoday
part of the command’s name) if the \versionortoday
command is not yet defined
at that moment. So now using the command in your LaTeX document will output the
version according to git or, in case it is not provided, will put the date in
that place.