Feeback on snippet of code to return git commit shas (string and array)

Hi,

I am trying to implement two methods that outputs the git commit shas of a repository one as a string:

"58ab9fb33a2a3a09567891ad4765472a856e4613\nafd6d791a62de493bca2543a98d9166e0519ee69\n..."

The other as an array:

["58ab9fb33a2a3a09567891ad4765472a856e4613",
"afd6d791a62de493bca2543a98d9166e0519ee69",
"f64e6500444659949976a94b0dcdef07dee3224b"]

The code is the following:

pub fn git_shas() -> Vec<u8> {
    let output = Command::new("git")
        .arg("rev-list")
        .arg("HEAD")
        .output().unwrap_or_else(|e| {
            panic!("failed to execute command: {}", e);
    });

    output.stdout
}

pub fn shas_string() -> String {
    let string_output = git_shas();
    let output = match String::from_utf8(string_output) {
        Ok(v) => v,
        Err(e) => panic!("Invalid Utf8 character: {}", e),
    };

    output
}

pub fn shas_slice() -> Vec<&'static str> {
    shas_string().split('\n').collect()
}

Any feedback, things to try would be much appreciated.

The git2 crate exposes the SHA in the Commit struct, which might be more flexible that calling the command line tools.

1 Like