git-box 0.2.0

git-box executable implementation
use {Args, to_hex};
use config::{Configure, GitBoxConfigResult};
use filter::{Clean, Filter, GitBoxFilterResult, Smudge};
use git2::Config;
use sodium_sys::crypto::hash::generichash;
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 From<Config> for FileBox {
    fn from(config: Config) -> FileBox {
        FileBox {
            path: match config.get_string("box.file.path") {
                Ok(u) => u.to_owned(),
                Err(_) => String::new(),
            },
        }
    }
}

impl From<Args> for FileBox {
    fn from(args: Args) -> FileBox {
        FileBox { path: args.arg_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.file.path", &self.path[..]));

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

        Ok(0)
    }

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

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

        Ok(0)
    }
}

impl Clean for FileBox {
    fn clean(&self, buf: &mut Vec<u8>, hash: &str, size: usize) -> GitBoxFilterResult {
        // Check the buffer matches given hash and length.
        let chkhash = to_hex(try!(generichash::hash(&buf[..], None, None)));
        assert!(chkhash == hash);
        assert!(buf.len() == size);

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

        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>, hash: &str, size: usize) -> GitBoxFilterResult {
        let mut path = PathBuf::from(&self.path);
        path.push(hash);

        let mut f = try!(File::open(path));
        let actual_size = try!(f.read_to_end(buf));
        assert!(size == actual_size);

        // Check the buffer matches given hash and length.
        let chkhash = to_hex(try!(generichash::hash(&buf[..], None, None)));
        assert!(chkhash == hash);
        assert!(buf.len() == size);

        Ok(size)
    }
}

impl Filter for FileBox {}