use std::io;
use std::process::Command;
use std::result::Result;

fn get_git_revision() -> Result<String, io::Error> {
    let git_revision = Command::new("git")
        .args(&["rev-parse", "--short", "HEAD"])
        .output()
        .and_then(|output| {
            if output.status.success() {
                Ok(String::from_utf8_lossy(&output.stdout).to_string())
            } else {
                Ok(String::from("unknown"))
            }
        })?;

    let git_dirty_flag = Command::new("git")
        .args(&["diff", "--shortstat"])
        .output()
        .and_then(|output| {
            if output.status.success() && output.stdout.len() > 0 {
                Ok(String::from("-dirty"))
            } else {
                Ok(String::new())
            }
        })?;

    Ok(git_revision + &git_dirty_flag)
}

fn main() {
    let git_revision = match get_git_revision() {
        Ok(revision) => revision,
        Err(_) => String::from("unknown"),
    };

    println!("cargo:rustc-env=GIT_REVISION={}", git_revision);
}
