Automatic Version Numbers in Rust




Creating a process to automatically generate a version or build number for my Rust projects was more about scratching an itch than meeting some specific goal.

There are a number of version numbering schemes:

I like a combination of calendar versioning and a build number.

YYYY-MM-<monthly commit number> (total build number)

For example: version: 2026.12.10 (build: 0056) is the tenth build in December 2026, and the 56th build overall.

Rust’s Cargo.toml version expects a valid SemVer number, so my format won’t fit there. (For the Cargo.toml version, I’ll manually update it periodically.) Instead I’m going to use a build.rs file at the root of each project. The build count is based one of two git commands. The first gets the absolute commit count:

git rev-list --count HEAD

The second gets the number of commits for the current calendar month:

git rev-list --count --since="$(date +%Y-%m-01)" HEAD

Here’s the complete code:

use std::process::Command;

fn git(args: &[&str]) -> String {
    Command::new("git").args(args).env("TZ", "UTC").output().ok().and_then(|o| String::from_utf8(o.stdout).ok()).map(|s| s.trim().to_string()).unwrap_or_default()
}

fn main() {
    let ym = git(&["log", "-1", "--format=%cd", "--date=format-local:%Y.%m", "HEAD"]);
    let month_start = git(&["log", "-1", "--format=%cd", "--date=format-local:%Y-%m-01T00:00:00Z", "HEAD"]);
    let monthly: u32 = git(&["rev-list", "--count", &format!("--since={month_start}"), "HEAD"]).parse().unwrap_or(0);
    let build: u32 = git(&["rev-list", "--count", "HEAD"]).parse().unwrap_or(0);

    println!("cargo:rustc-env=APP_VERSION={ym}.{monthly}");
    println!("cargo:rustc-env=APP_BUILD={build:05}");
    println!("cargo:rerun-if-changed=.git/HEAD");
    println!("cargo:rerun-if-changed=.git/refs");
}

In my code, format!("{} (build: {})", env!("APP_VERSION"), env!("APP_BUILD")) gives 2026.12.18 (build: 01234).

So far I’ve implemented this in exactly one Rust project. I want to make it a library crate that I can include as a dependency in any project. The library would have one pub fn emit(). Assuming the crate was called calver_build then

fn main() {
    calver_build::emit();
}

would produce the current version for that project.