git-box 0.2.0

git-box executable implementation
use {Args, to_hex};
use config::{Configure, GitBoxConfigResult};
use error::GitBoxError;
use filter::{Clean, Filter, GitBoxFilterResult, Smudge};
use git2::Config;
use sha1::Sha1;
use sodium_sys::crypto::hash::generichash;
use sodium_sys::crypto::hash::sha2;
use std::collections::HashSet;
use super::{base_url, basic_auth, get, put, stderr_resp};

#[derive(Default)]
/// Artifactory Binary Off-Repository eXternal Storage
pub struct ArtBox {
    /// username
    user: String,
    /// Artifactory API Key
    apikey: String,
    /// Artifactory URL
    url: String,
    /// Artifactory Repository
    repo: String,
    /// Artifactory Directory (Sub-folder)
    subfolder: String,
}

impl From<Config> for ArtBox {
    fn from(config: Config) -> ArtBox {
        ArtBox {
            user: match config.get_string("box.artifactory.user") {
                Ok(u) => u.to_owned(),
                Err(_) => String::new(),
            },
            apikey: match config.get_string("box.artifactory.apikey") {
                Ok(t) => t.to_owned(),
                Err(_) => String::new(),
            },
            url: match config.get_string("box.artifactory.url") {
                Ok(t) => t.to_owned(),
                Err(_) => String::new(),
            },
            repo: match config.get_string("box.artifactory.repo") {
                Ok(t) => t.to_owned(),
                Err(_) => String::new(),
            },
            subfolder: match config.get_string("box.artifactory.subfolder") {
                Ok(t) => t.to_owned(),
                Err(_) => String::new(),
            },
        }
    }
}

impl From<Args> for ArtBox {
    fn from(args: Args) -> ArtBox {
        ArtBox {
            user: args.arg_user,
            apikey: args.arg_apikey,
            url: args.arg_url,
            repo: args.arg_repository,
            subfolder: args.arg_subfolder,
        }
    }
}

impl Configure for ArtBox {
    fn set_config(&self, config: &mut Config) -> GitBoxConfigResult {
        try!(config.set_str("box.storagetype", "ARTIFACTORY"));
        try!(config.set_str("box.artifactory.user", &self.user[..]));
        try!(config.set_str("box.artifactory.apikey", &self.apikey[..]));
        try!(config.set_str("box.artifactory.url", &self.url[..]));
        try!(config.set_str("box.artifactory.repo", &self.repo[..]));
        try!(config.set_str("box.artifactory.subfolder", &self.subfolder[..]));

        if ::enabled() {
            debug!("Set git-box ARTIFACTORY config:");
            debug!("  box.storagetype:           {}", "ARTIFACTORY");
            debug!("  box.artifactory.user:      {}", self.user);
            debug!("  box.artifactory.apikey:    {}", self.apikey);
            debug!("  box.artifactory.url:       {}", self.url);
            debug!("  box.artifactory.repo:      {}", self.repo);
            debug!("  box.artifactory.subfolder: {}", self.subfolder);
        }

        Ok(0)
    }

    fn remove_config(&self, config: &mut Config) -> GitBoxConfigResult {
        try!(config.remove("box.storagetype"));
        try!(config.remove("box.artifactory.user"));
        try!(config.remove("box.artifactory.apikey"));
        try!(config.remove("box.artifactory.url"));
        try!(config.remove("box.artifactory.repo"));
        try!(config.remove("box.artifactory.subfolder"));

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

        Ok(0)
    }
}

impl Clean for ArtBox {
    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);

        // Compute SHA-1 for Artifactory Header
        let mut m = Sha1::new();
        m.update(&buf[..]);
        let sha1 = m.hexdigest();

        // Compute SHA-256 for Artifactory Header
        let sha256 = to_hex(try!(sha2::hash256(&buf[..])));

        let art_user = &self.user;
        let art_apikey = &self.apikey;
        let art_url = &self.url;
        let art_repo = &self.repo;
        let art_subfolder = &self.subfolder;
        let empty_buf = Vec::new();

        // Setup the Artifactory URL: <url> / <artrepo> / <gitrepo>
        let mut url = try!(base_url(art_url, art_repo, art_subfolder));
        url.push('/');

        // Setup the base64 Basic Authorization string for headers
        let basic_auth = basic_auth(art_user, art_apikey);
        let mut headers = HashSet::new();
        headers.insert(("Authorization", &basic_auth[..]));

        // Create the directory on artifactory.  If the directory already exists
        // this has no effect.
        let resp = try!(put(&url, &empty_buf, headers, None, false));

        match resp.get_code() {
            201 => {}
            _ => {
                try!(stderr_resp(resp));
                return Err(GitBoxError::Other("Error creating artifactory directory!"));
            }
        }

        // Extend the URL.
        url.push_str(hash);

        // Add the checksum deploy headers.
        let mut headers1 = HashSet::new();
        headers1.insert(("Authorization", &basic_auth[..]));
        headers1.insert(("X-Checksum-Deploy", "true"));
        headers1.insert(("X-Checksum-Sha1", &sha1[..]));
        headers1.insert(("X-Checksum-Sha256", &sha256[..]));

        // Put the file (checksum deploy)
        let resp1 = try!(put(&url, &empty_buf, headers1, None, false));

        match resp1.get_code() {
            201 => return Ok(size),
            404 => {
                // Try a normal deploy
            }
            _ => {
                try!(stderr_resp(resp1));
                return Err(GitBoxError::Other("Error deploying artifact (checksum)!"));
            }
        }

        // Checksum deploy didn't work so remove header and to a normal deploy.
        let mut headers2 = HashSet::new();
        headers2.insert(("Authorization", &basic_auth[..]));
        headers2.insert(("X-Checksum-Sha1", &sha1[..]));
        headers2.insert(("X-Checksum-Sha256", &sha256[..]));

        // Put the file
        let resp2 = try!(put(&url, buf, headers2, Some(3600000), false));

        match resp2.get_code() {
            201 => {
                // TODO: Parse the response for size and assert here.
                Ok(size)
            }
            _ => {
                try!(stderr_resp(resp2));
                Err(GitBoxError::Other("Error creating artifact!"))
            }
        }
    }
}

impl Smudge for ArtBox {
    fn smudge(&self, buf: &mut Vec<u8>, hash: &str, size: usize) -> GitBoxFilterResult {
        let art_user = &self.user;
        let art_apikey = &self.apikey;
        let art_url = &self.url;
        let art_repo = &self.repo;
        let art_subfolder = &self.subfolder;

        // Setup the Artifactory URL: <url> / <artrepo> / <gitrepo>
        let mut url = try!(base_url(art_url, art_repo, art_subfolder));

        // Setup the base64 Basic Authorization string
        let basic_auth = basic_auth(art_user, art_apikey);
        let mut headers = HashSet::new();
        headers.insert(("Authorization", &basic_auth[..]));

        // Extend the URL.
        url.push('/');
        url.push_str(hash);

        // Get the file
        // Bump up the smudge timeout to account for download times
        let resp = try!(get(&url, headers, Some(3600000)));

        match resp.get_code() {
            200 => {
                let body = resp.get_body();

                // Copy the response body into the buffer
                for rb in body.iter() {
                    buf.push(*rb);
                }

                Ok(size)
            }
            _ => {
                try!(stderr_resp(resp));
                Err(GitBoxError::Other("Error getting artifact!"))
            }
        }
    }
}

impl Filter for ArtBox {}