Include git commit hash as string into Rust program

后端 未结 6 2066
小蘑菇
小蘑菇 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:55

    There is already an existing crate vergen that can calculate the git commit in the build script. As @DK's answer described, the build script cannot modify environment variable before Rust 1.19, so vergen still works by writing the result into OUT_DIR (i.e. vergen still won't solve OP's question, but it should be easier to use).


    Usage:

    # Cargo.toml
    ...
    [build-dependencies]
    vergen = "0.1"
    
    // build.rs
    extern crate vergen;
    use vergen::*;
    fn main() {
        vergen(SHORT_SHA | COMMIT_DATE).unwrap();
    }
    
    mod version {
        include!(concat!(env!("OUT_DIR"), "/version.rs"));
    }
    fn main() {
        println!("commit: {} {}", version::commit_date(), version::short_sha());
        // output something like:
        //        commit: 2017-05-03 a29c7e5
    }
    

提交回复
热议问题