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 sodium_sys::crypto::hash::generichash;
use std::collections::HashSet;
use super::{base_url, basic_auth, get, head, put, stderr_resp};

#[derive(Default)]
/// Nexus Binary Off-Repository eXternal Storage
pub struct NexusBox {
    /// username
    user: String,
    /// password
    password: String,
    /// Nexus Base URL
    url: String,
    /// Nexus Repository
    repo: String,
    /// Nexus Sub-folder (usually the git repository name).
    subfolder: String,
}

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

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

impl NexusBox {
    fn head(&self, url: &str, content_length: usize) -> GitBoxFilterResult {
        // Setup the base64 Basic Authorization string for headers
        let basic_auth = basic_auth(&self.user, &self.password);
        let mut headers = HashSet::new();
        headers.insert(("Authorization", &basic_auth[..]));

        // Request metadata via HEAD request for the file.
        let resp = try!(head(&url, headers, None));

        match resp.get_code() {
            200 => {
                debug!("Headers: {:?}", resp.get_headers());
                let clh = resp.get_header("content-length");

                if clh.len() > 0 {
                    let cl = try!(clh[0].parse::<usize>());
                    debug!("CLH: {}, CL: {}", cl, content_length);
                    if cl == content_length {
                        return Ok(content_length);
                    } else {
                        return Err(GitBoxError::Other("Content-Length differs!"));
                    }
                } else {
                    return Err(GitBoxError::Other("Unable to read Content-Length header!"));
                }
            }
            _ => {
                try!(stderr_resp(resp));
                return Err(GitBoxError::Other("Error getting metadata!"));
            }
        }
    }
}

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

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

        Ok(0)
    }

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

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

        Ok(0)
    }
}

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

        // Setup the URL: <url> / <repo> / <gitrepo>
        let mut url = try!(base_url(&self.url, &self.repo, &self.subfolder));
        url.push('/');
        // Extend the URL.
        url.push_str(hash);

        self.head(&url, buf.len()).or_else(|_| {
            // Setup the base64 Basic Authorization string for headers
            let basic_auth = basic_auth(&self.user, &self.password);
            let mut headers = HashSet::new();
            headers.insert(("Authorization", &basic_auth[..]));

            // Upload the file to Nexus
            let resp = try!(put(&url, &buf, headers, Some(3600000), false));

            match resp.get_code() {
                201 => Ok(size),
                _ => {
                    try!(stderr_resp(resp));
                    return Err(GitBoxError::Other("Error uploading file!"));
                }
            }
        })
    }
}

impl Smudge for NexusBox {
    fn smudge(&self, buf: &mut Vec<u8>, hash: &str, size: usize) -> GitBoxFilterResult {
        // Setup the Artifactory URL: <url> / <artrepo> / <gitrepo>
        let mut url = try!(base_url(&self.url, &self.repo, &self.subfolder));

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

        self.head(&url, buf.len()).or_else(|_| {
            // Setup the base64 Basic Authorization string
            let basic_auth = basic_auth(&self.user, &self.password);
            let mut headers = HashSet::new();
            headers.insert(("Authorization", &basic_auth[..]));

            // 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 => {
                    buf.extend(resp.get_body());

                    // 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)
                }
                _ => {
                    try!(stderr_resp(resp));
                    Err(GitBoxError::Other("Error downloading artifact!"))
                }
            }
        })
    }
}

impl Filter for NexusBox {}