Whether you are writing a fancy database, or simple CLI program, it's always helpful to embed git commit into the binary.
With it, you can know which exact lines of code is to be blamed when users throw you an unhappy backtrace.
Previously I have done similar thing in Go, and it's fairly easy:
|
|
And in you main.go
, you have something like
|
|
How to do this in Zig? The answer is Step/Options.zig
.
In case you don't know how Zig build works, read Zig Build System first.
Options
is a builtin build step to generate module at compile time. The main API to define variable
is addOption
, and after define variables you want to embed, use createModule
to create a module for project to use. Take one example:
|
|
Then build and run, you will get
|
|
Under the hood, Options
step will create a Zig source file in zig-cache
directory, which contains variables you defined via addOption
.
|
|
After understand how Options
step works, the last task to complete our target is to replace hard-coded HEAD
with real commit id, we have two options here:
- Shell out to
git
viaexec
family API, and parse its stdout - Like how
-Dtarget
works, add a new option to pass git commit intobuild.zig
Since solution 2 is both easy and OS-independent, I will only introduce how to do it:
|
|
Then build and run again:
|
|
That's it, git commit is embed in our programs!
PS: When build in GitHub Action, we can use builtin env vars directly:
zig build -Dgit_commit=${{ github.sha }}
.