Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Include git commit hash as string into Rust program

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 could set environment variables which can be used while compiling the project itself, but it does not work:

build.rs:

use std::env;

fn get_git_hash() -> Option<String> {
    use std::process::Command;

    let branch = Command::new("git")
                         .arg("rev-parse")
                         .arg("--abbrev-ref")
                         .arg("HEAD")
                         .output();
    if let Ok(branch_output) = branch {
        let branch_string = String::from_utf8_lossy(&branch_output.stdout);
        let commit = Command::new("git")
                             .arg("rev-parse")
                             .arg("--verify")
                             .arg("HEAD")
                             .output();
        if let Ok(commit_output) = commit {
            let commit_string = String::from_utf8_lossy(&commit_output.stdout);

            return Some(format!("{}, {}",
                        branch_string.lines().next().unwrap_or(""),
                        commit_string.lines().next().unwrap_or("")))
        } else {
            panic!("Can not get git commit: {}", commit_output.unwrap_err());
        }
    } else {
        panic!("Can not get git branch: {}", branch.unwrap_err());
    }
    None
}

fn main() {
    if let Some(git) = get_git_hash() {
        env::set_var("GIT_HASH", git);
    }
}

src/main.rs:

pub const GIT_HASH: &'static str = env!("GIT_HASH");

fm main() {
    println!("Git hash: {}", GIT_HASH);
}

The error message:

error: environment variable `GIT_HASH` not defined
  --> src/main.rs:10:25
   |
10 | pub const GIT_HASH: &'static str = env!("GIT_HASH");
   |   
                                        ^^^^^^^^^^^^^^^^

Is there a way to pass such data at compile time? How can I communicate between the build script and the source code if not with environment variables? I can only think about writing data to some file, but I think this is overkill for this case.

like image 736
Victor Polevoy Avatar asked May 03 '17 07:05

Victor Polevoy


People also ask

What is commit hash in git?

Commit hashesThe long string following the word commit is called the commit hash. It's unique identifier generated by Git. Every commit has one, and I'll show you what they're used for shortly. Note: The “commit hash” is sometimes called a Git commit “reference” or “SHA”.

What is Git_hash?

Hashes are what enable Git to share data efficiently between repositories. If two files are the same, their hashes are guaranteed to be the same. Similarly, if two commits contain the same files and have the same ancestors, their hashes will be the same as well.

How is a commit hash calculated?

Every time a commit is added to a git repository, a hash string which identifies this commit is generated. This hash is computed with the SHA-1 algorithm and is 160 bits (20 bytes) long. Expressed in hexadecimal notation, such hashes are 40 digit strings.

How does Git hash work?

Git uses hashes in two important ways. When you commit a file into your repository, Git calculates and remembers the hash of the contents of the file. When you later retrieve the file, Git can verify that the hash of the data being retrieved exactly matches the hash that was computed when it was stored.


1 Answers

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
}
like image 93
kennytm Avatar answered Oct 28 '22 12:10

kennytm