Adding build time to a rust binary
Sometimes, I think it's useful to embed the date and time into my build files. It serves as a quick visual indicator for when it was built and also to indicate that the build has been replaced after a release.
Adam Shirey did a nice writup of how you can do embed the date and time into a binary using a Rust build script.
Basically, you can create a build.rs file in the root of your crate, and run some code prior to build. In Adam's example, he created a "timestamp.txt" file in the build's output folder. This works fine when you run/build, however, in the IDE, rust-analyzer shows an error saying it can't find the timestamp.txt file, even though the file does in fact exist.
The reason for this problem is that rust-analyzer only loads Rust (.rs) files not txt files.
The quick and easy solution is to simply rename timestamp.txt
to timestamp.rs
and then rust-analyzer will be able to read the file and resolve the macro expansion.
use std::{env, io::Write, fs};
fn main() {
let outdir = env::var("OUT_DIR").unwrap();
let outfile = format!("{}/timestamp.rs", outdir);
let mut fh = fs::File::create(&outfile).unwrap();
write!(fh, r#""{}""#, chrono::Local::now()).ok();
}
And then you can add this macro to your code...
const BUILD_TIME : &str = include!(concat!(env!("OUT_DIR"), "/timestamp.rs"));
Another note I had about the build scripts, is that if you're using dependencies in your build files you'll need to add them to the build-dependencies section of cargo.toml, e.g. if you're using chrono...
[build-dependencies]
chrono = "0.4"