Include git commit hash as string into Rust program

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

    There is an easy way to do this without the need for any build.rs logic or custom crates. You simply pass the current git hash directly to the build command as an environment variable, and read it in your program with option_env!("PROJECT_VERSION"), with a env!("CARGO_PKG_VERSION") fallback. These macros read environment variables during build time.

    Examples follow that builds this minimal src/main.rs:

    fn main() {
        let version = option_env!("PROJECT_VERSION").unwrap_or(env!("CARGO_PKG_VERSION"));
        println!("This binary was built from {}", version);
    }
    

    When you build the program and want an accurate git hash, e.g. in your CI/CD configuration, you prefix the cargo command with PROJECT_VERSION=$(git rev-parse --short HEAD). Like this for cargo run (but also works for cargo build and others):

    % PROJECT_VERSION=$(git rev-parse --short HEAD) cargo run
    This binary was built from 6ca63b2
    

    Personally I prefer $(git describe) over $(git rev-parse) since the former is more descriptive (using cargo build as example now just for variation):

    % PROJECT_VERSION=$(git describe) cargo build 
    % ./target/debug/your-program
    This binary was built from v0.3.0-15-g6ca63b2    # or just 'v0.3.0' if current commit is tagged with that
    

    Since you have a CARGO_PKG_VERSION fallback, your IDE can still build the files on-the-fly for you. Likewise, for development, you can skip passing PROJECT_VERSION. In that case, the version from your Cargo.toml will be used:

    % cargo run
    This binary was built from 0.3.0
    

提交回复
热议问题