Include the current Git hash in your Typst document

For tracability, it is useful to include the Git commit hash (or Git tag) from which the document was built off in your document. I personally use it when I compile Typst in my GitLab CI/CD pipeline.

We can achieve this using Typst’s sys.inputs and the command line:

#let git-revision = sys.inputs.at("git-revision", default: none)

To pass the Git revision, use the --input flag when compiling:

# When compiling locally with bash
typst compile --input git-revision=$(git rev-parse --short HEAD) main.typ
# When compiling in a GitLab pipeline, we can use the preset variable
typst compile --input git-revision=$CI_COMMIT_SHORT_SHA main.typ

Now because we may compile the document in environments where we can’t use --input, like Tinymist or the Web Editor, I set the default value to none. When we want to insert our hash, we can check whether the hash is present:

#if (git-revision != none) {
  [Git revision: #git-revision, compiled on #datetime.today().display()]
}

You can of course use other values as you please, like Git tags or the output of git describe. Whatever you prefer :slight_smile:.

AFAIK there isn’t really a way to do this if you use the Git integration in the Web App, you would probably need to use the CI/CD system of your code forge.

In RCS you can do this with something like

// $Id$
#let revision = "$Revision$".trim(regex("\D"))

Oh wow, I didn’t know that someone is still using RCS, and for new projects at that :joy:
But how does this work? Does RCS replace $Revision$ when you check in? (or however RCS works, i’ve never used it)

For single user projects/files rcs is much lighter than learning git.

For two of my larger projects (with 2-3 collaborators) and for new projects I use a private github, so I am not advocating for rcs, per se, but for my older stuff, rcs is not broken :-)-O, in particular if paired with a Makefile (on the Mac). Claude AI understands rcs as well as git.

https://jnrowe.github.io/articles/rcs.html is a good and comprehensive introduction.