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)]
/// Archiva Binary Off-Repository eXternal Storage
pub struct ArchivaBox {
    /// username
    user: String,
    /// password
    password: String,
    /// Archiva Base URL
    url: String,
    /// Archiva Repository
    repo: String,
    /// Archiva Sub-folder (usually the git repository name).
    subfolder: String,
}

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

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

impl ArchivaBox {
    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 ArchivaBox {
    fn set_config(&self, config: &mut Config) -> GitBoxConfigResult {
        try!(config.set_str("box.storagetype", "ARCHIVA"));
        try!(config.set_str("box.archiva.user", &self.user[..]));
        try!(config.set_str("box.archiva.password", &self.password[..]));
        try!(config.set_str("box.archiva.url", &self.url[..]));
        try!(config.set_str("box.archiva.repo", &self.repo[..]));
        try!(config.set_str("box.archiva.subfolder", &self.subfolder[..]));

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

        Ok(0)
    }

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

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

        Ok(0)
    }
}

impl Clean for ArchivaBox {
    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, None, false));

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

impl Smudge for ArchivaBox {
    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 => {
                    let body = resp.get_body();

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

                    // 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 ArchivaBox {}