0

In my Go builds, I usually include these lines:

buildInfo="`date -u '+%Y-%m-%dT%TZ'`|`git describe --always --long`|`git tag | tail -1`"
go build -ldflags "-X main.buildInfo=${buildInfo} -s -w" ./cmd/...

and then in main, I parse buildInfo into three separate values which can be displayed with the usage message. This allows me to see the compile timestamp, git hash, and semver number of the executable.

Is there any similar way to do this in the Rust compiler?

jwdonahue
  • 6,199
  • 2
  • 21
  • 43
Ralph
  • 31,584
  • 38
  • 145
  • 282

1 Answers1

1

You want to use a Build Script as described here: https://doc.rust-lang.org/cargo/reference/build-scripts.html

You need to write a build.rs Rust file located at the root of your crate, which will be compiled and run by cargo just before building the crate, in which you can output certain strings that will in turn be interpreted by Cargo to drive compilation.

For example, if you write a build script with these contents:

fn main() {
    println!("cargo:rustc-env=BUILD_INFO=VALUE");
}

Then the source files in your project can use the BUILD_INFO variable like this:

let buildInfo = env!("BUILD_INFO");

In your case, the build script can for example determine the current timestamp, or invoke the git executable and parse its output.

SirDarius
  • 41,440
  • 8
  • 86
  • 100