git_latest_commit/
lib.rs

1extern crate git2;
2#[macro_use]
3extern crate quick_error;
4
5use git2::Repository;
6use std::convert::AsRef;
7use std::env;
8use std::fs::{File, create_dir_all};
9use std::io::{Write, Read, BufWriter};
10use std::path::Path;
11
12quick_error!
13{
14    #[derive(Debug)]
15    pub enum Error
16    {
17        Io(err: std::io::Error) { from() }
18        Git(err: git2::Error) { from() }
19        MissingEnvVar { }
20    }
21}
22
23fn content_differs<P: AsRef<Path>>(path: P, content: &str) -> Result<bool, Error>
24{
25    let mut f = try!(File::open(path));
26    let mut current = String::new();
27    try!(f.read_to_string(&mut current));
28
29    Ok(current != content)
30}
31
32pub fn write <P: AsRef<Path>>(topdir: P) -> Result<(), Error>
33{
34    let path = try!(env::var_os("OUT_DIR").ok_or(Error::MissingEnvVar));
35    let path : &Path = path.as_ref();
36
37    try!(create_dir_all(path));
38
39    let path = path.join("git-commit.rs");
40
41    let repo = try!(Repository::discover(topdir));
42    let oid = try!(repo.refname_to_id("HEAD"));
43
44    let mut commit = repo.find_commit(oid).unwrap();
45    let sumbytes = commit.summary_bytes().unwrap();
46    let summary = std::str::from_utf8(&sumbytes).unwrap();
47
48    let content = format!("static GIT_HASH: &'static str = \"{}\";\nstatic GIT_SUMMARY: &'static str = \"{}\";",
49        oid, summary);
50
51    let has_changes = if path.exists()
52    {
53        try!(content_differs(&path, &content))
54    }
55    else { true };
56
57    if has_changes
58    {
59      let mut file = BufWriter::new(try!(File::create(&path)));
60      try!(write!(file, "{}", content));
61    }
62    Ok(())
63}
64
65#[cfg(test)]
66mod tests {
67    #[test]
68    fn it_works() {
69    }
70}