Include git commit hash as string into Rust program

后端 未结 6 2014
小蘑菇
小蘑菇 2021-02-12 23:33

I host a Rust project in git repository and I want to make it print the version on some command. How can I include the version into the program? I thought that the build script

6条回答
  •  有刺的猬
    2021-02-12 23:51

    Since Rust 1.19 (cargo 0.20.0), thanks to https://github.com/rust-lang/cargo/pull/3929, you can now define a compile-time environment variable (env!(…)) for rustc and rustdoc via:

    println!("cargo:rustc-env=KEY=value");
    

    So OP's program can be written as:

    // build.rs
    use std::process::Command;
    fn main() {
        // note: add error checking yourself.
        let output = Command::new("git").args(&["rev-parse", "HEAD"]).output().unwrap();
        let git_hash = String::from_utf8(output.stdout).unwrap();
        println!("cargo:rustc-env=GIT_HASH={}", git_hash);
    }
    
    // main.rs
    fn main() {
        println!("{}", env!("GIT_HASH"));
        // output something like:
        // 7480b50f3c75eeed88323ec6a718d7baac76290d
    }
    

    Note that you still cannot use this if you still want to support 1.18 or below.

提交回复
热议问题