git-box 0.1.1

git-box executable implementation
Documentation
use config::{Configure, GitBoxConfigResult};
use curl::http::{self, Response};
use error::GitBoxError;
use filter::{Clean, Filter, GitBoxFilterResult, Smudge};
use git2::Config;
use rustc_serialize::base64::{STANDARD, ToBase64};
use std::collections::HashSet;
use std::io::{self, Write};

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

impl ArtBox {
    /// Create a new ArgBox struct.
    pub fn new(user: String, pass: String, url: String, repo: String, repodir: String) -> ArtBox {
        ArtBox {
            user: user,
            pass: pass,
            url: url,
            repo: repo,
            repodir: repodir,
        }
    }
}

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.pass", &self.pass[..]));
        try!(config.set_str("box.artifactory.url", &self.url[..]));
        try!(config.set_str("box.artifactory.repo", &self.repo[..]));
        try!(config.set_str("box.artifactory.repodir", &self.repodir[..]));

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

        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.pass"));
        try!(config.remove("box.artifactory.url"));
        try!(config.remove("box.artifactory.repo"));
        try!(config.remove("box.artifactory.repodir"));

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

        Ok(0)
    }
}

#[derive(Default)]
struct ArtResponse {
    code: u32,
    body: Vec<u8>,
}

impl ArtResponse {
    fn get_code(&self) -> u32 {
        self.code
    }

    fn get_body(&self) -> &[u8] {
        &self.body
    }
}

impl From<Response> for ArtResponse {
    fn from(resp: Response) -> ArtResponse {
        ArtResponse {
            code: resp.get_code(),
            body: resp.move_body(),
        }
    }
}

pub type ArtResult<T> = Result<T, GitBoxError>;

fn get(url: &str,
       headers: HashSet<(&str, &str)>,
       timeout: Option<usize>)
       -> ArtResult<ArtResponse> {
    let mut handle = http::handle();

    let resp = match timeout {
        Some(t) => {
            try!(handle.connect_timeout(t)
                       .timeout(t)
                       .get(&url[..])
                       .headers(headers.into_iter())
                       .exec())
        }
        None => try!(handle.get(&url[..]).headers(headers.into_iter()).exec()),
    };

    Ok(ArtResponse::from(resp))
}

fn put(url: &str,
       buf: &[u8],
       headers: HashSet<(&str, &str)>,
       timeout: Option<usize>)
       -> ArtResult<ArtResponse> {
    let mut handle = http::handle();

    let resp = match timeout {
        Some(t) => {
            try!(handle.connect_timeout(t)
                       .timeout(t)
                       .put(&url[..], &buf[..])
                       .headers(headers.into_iter())
                       .exec())
        }
        None => try!(handle.put(&url[..], &buf[..]).headers(headers.into_iter()).exec()),
    };

    Ok(ArtResponse::from(resp))
}

fn basic_auth(user: &str, pass: &str) -> String {
    let mut auth = user.to_owned();
    auth.push(':');
    auth.push_str(&pass[..]);

    let enc = auth.as_bytes().to_base64(STANDARD);
    let mut basic = String::from("Basic ");
    basic.push_str(&enc[..]);
    basic
}

fn base_url(host: &str, repo: &str, repodir: &str) -> Result<String, GitBoxError> {
    // Setup the Artifactory URL: <url> / <repo> / <repodir>
    let mut url = String::from(host[..].trim_matches('/'));
    url.push('/');
    url.push_str(&repo[..]);
    url.push('/');
    url.push_str(&repodir[..]);
    Ok(url)
}

fn stderr_resp(resp: ArtResponse) -> Result<(), GitBoxError> {
    let body_vec = resp.get_body();
    let body = String::from_utf8_lossy(&body_vec[..]);
    try!(writeln!(io::stderr(), "HTTP RESPONSE CODE: {:?}", resp.get_code()));
    try!(writeln!(io::stderr(), "{:?}", body));
    Ok(())
}

impl Clean for ArtBox {
    fn clean(&self, buf: &mut Vec<u8>, sha1: &str, size: usize) -> GitBoxFilterResult {
        let art_user = &self.user;
        let art_pass = &self.pass;
        let art_url = &self.url;
        let art_repo = &self.repo;
        let art_repodir = &self.repodir;
        let empty_buf = Vec::new();

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

        // Setup the base64 Basic Authorization string for headers
        let basic_auth = basic_auth(art_user, art_pass);
        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));

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

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

        // 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));

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

        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));

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

        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>, sha1: &str, size: usize) -> GitBoxFilterResult {
        let art_user = &self.user;
        let art_pass = &self.pass;
        let art_url = &self.url;
        let art_repo = &self.repo;
        let art_repodir = &self.repodir;

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

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

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

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