git-box 0.1.1

git-box executable implementation
Documentation
use config::{Configure, GitBoxConfigResult};
use filter::{Clean, Filter, GitBoxFilterResult, Smudge};
use git2::Config;
use sha1::Sha1;
use std::fs::{File, OpenOptions};
use std::io::{BufWriter, Read, Write};
use std::path::PathBuf;

#[derive(Default)]
/// File Binary Off-Repository eXternal Storage
pub struct FileBox {
    // Path to the storage location.
    path: String,
}

impl FileBox {
    /// Create a new FileBox struct.
    pub fn new(path: String) -> FileBox {
        FileBox { path: path }
    }
}

impl Configure for FileBox {
    fn set_config(&self, config: &mut Config) -> GitBoxConfigResult {
        try!(config.set_str("box.storagetype", "FILE"));
        try!(config.set_str("box.filepath", &self.path[..]));

        if ::enabled() {
            debug!("Set git-box FILE config:");
            debug!("  box.storagetype: {}", "FILE");
            debug!("  box.filepath:    {}", self.path);
        }

        Ok(0)
    }

    fn remove_config(&self, config: &mut Config) -> GitBoxConfigResult {
        try!(config.remove("box.storagetype"));
        try!(config.remove("box.filepath"));

        if ::enabled() {
            debug!("Unset git-box FILE config");
        }

        Ok(0)
    }
}

impl Clean for FileBox {
    fn clean(&self, buf: &mut Vec<u8>, sha1: &str, size: usize) -> GitBoxFilterResult {
        // Check the buffer matches given sha1
        let mut m = Sha1::new();
        m.update(&buf[..]);
        assert!(sha1 == m.hexdigest());
        assert!(buf.len() == size);

        // Write the buffer to the filepath.
        let mut path = PathBuf::from(&self.path);
        path.push(sha1);

        let f = try!(OpenOptions::new()
                         .create(true)
                         .write(true)
                         .open(path));

        let mut bufw = BufWriter::new(f);
        try!(bufw.write_all(&buf[..]));
        try!(bufw.flush());

        Ok(size)
    }
}

impl Smudge for FileBox {
    fn smudge(&self, buf: &mut Vec<u8>, sha1: &str, size: usize) -> GitBoxFilterResult {
        let mut path = PathBuf::from(&self.path);
        path.push(sha1);

        let mut f = try!(File::open(path));

        let actual_size = try!(f.read_to_end(buf));
        assert!(size == actual_size);
        Ok(size)
    }
}

impl Filter for FileBox {}