git-box 0.1.1

git-box executable implementation
Documentation
//! git config operations
use error::GitBoxError;
use filter::Filter;
#[cfg(feature = "artifactory")]
use filter::art::ArtBox;
#[cfg(feature = "file")]
use filter::file::FileBox;
#[cfg(feature = "ssh2")]
use filter::ssh2::Ssh2Box;
use git2::{Config, Error, Repository};
use regex::{self, Regex};
use std::fs::{File, OpenOptions};
use std::io::{BufRead, BufReader, BufWriter, Write};

/// A configure operation result.
pub type GitBoxConfigResult = Result<i32, GitBoxError>;

/// The Configure trait.
pub trait Configure {
    /// Set up the configuration.
    fn set_config(&self, config: &mut Config) -> GitBoxConfigResult;
    /// Remove the configuration.
    fn remove_config(&self, config: &mut Config) -> GitBoxConfigResult;
}

/// Add a new glob pattern to track for filter/smudge.
pub fn track(pattern: &str) -> GitBoxConfigResult {
    if ::enabled() {
        debug!("Adding {} to list of tracked file patterns", pattern);
    }

    let mut gitattr = try!(OpenOptions::new()
                               .create(true)
                               .read(true)
                               .write(true)
                               .append(true)
                               .open(".gitattributes"));

    {
        let reader = BufReader::new(&mut gitattr);
        let mut re_str = String::from("^");
        re_str.push_str(&regex::quote(&pattern[..])[..]);

        let re = Regex::new(&re_str[..]).expect("Unable to construct regex!");
        for line in reader.lines() {
            if let Ok(l) = line {
                if re.is_match(&l[..]) {
                    warn!("Pattern already exists in .gitattributes.  Not re-adding!");
                    return Ok(0);
                }
            }
        }
    }

    let outstr = format!("{} filter=box\n", pattern);
    try!(gitattr.write_all(&outstr.as_bytes()[..]));
    Ok(0)
}

/// Untrack a glob pattern, so filter/smudge doesn not apply.
pub fn untrack(pattern: &str) -> GitBoxConfigResult {
    if ::enabled() {
        debug!("Removing {} from list of tracked file patterns", pattern);
    }

    let mut lines = Vec::new();
    let gitattr = try!(File::open(".gitattributes"));
    let reader = BufReader::new(gitattr);
    let mut re_str = String::from("^");
    re_str.push_str(&regex::quote(&pattern[..])[..]);

    let re = Regex::new(&re_str[..]).expect("Unable to construct regex!");
    for line in reader.lines() {
        if let Ok(l) = line {
            if !re.is_match(&l[..]) {
                lines.push(l);
            }
        }
    }

    let write_gitattr = try!(OpenOptions::new()
                                 .create(true)
                                 .write(true)
                                 .truncate(true)
                                 .open(".gitattributes"));
    let mut writer = BufWriter::new(write_gitattr);
    for line in lines {
        try!(writer.write_fmt(format_args!("{}\n", line)));
    }
    Ok(0)
}

/// Open the default (global) configuration, or the repository configuration.
pub fn open_config(global: bool) -> Result<Config, Error> {
    if global {
        Ok(try!(Config::open_default()))
    } else {
        match Repository::open(".") {
            Ok(r) => Ok(try!(r.config())),
            Err(_) => Ok(try!(Config::open_default())),
        }
    }
}

/// Set up the git-box clean and smudge filter programs.
pub fn set_filter(config: &mut Config) -> GitBoxConfigResult {
    try!(config.set_str("filter.box.smudge", "git-box-smudge"));
    try!(config.set_str("filter.box.clean", "git-box-clean"));

    if ::enabled() {
        debug!("Set git-box filter config:");
        debug!("  filter.box.smudge: git-box-smudge");
        debug!("  filter.box.clean:  git-box-clean");
    }

    Ok(0)
}

/// Remove the git-box clean and smudge filter programs.
pub fn unset_filter(config: &mut Config) -> GitBoxConfigResult {
    try!(config.remove("filter.box.smudge"));
    try!(config.remove("filter.box.clean"));

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

    Ok(0)
}

#[cfg(feature = "artifactory")]
fn make_art_box(config: Config) -> Result<ArtBox, GitBoxError> {
    Ok(ArtBox::new(try!(config.get_string("box.artifactory.user")),
                   try!(config.get_string("box.artifactory.pass")),
                   try!(config.get_string("box.artifactory.url")),
                   try!(config.get_string("box.artifactory.repo")),
                   try!(config.get_string("box.artifactory.repodir"))))
}

#[cfg(feature = "file")]
fn make_file_box(config: Config) -> Result<FileBox, GitBoxError> {
    Ok(FileBox::new(try!(config.get_string("box.filepath"))))
}

#[cfg(feature = "ssh2")]
fn make_ssh2_box(config: Config) -> Result<Ssh2Box, GitBoxError> {
    Ok(Ssh2Box::new(try!(config.get_string("box.ssh.host")),
                    try!(config.get_string("box.ssh.user")),
                    try!(config.get_string("box.ssh.path"))))
}

/// Get the currently configured box storage type from the configuration.
pub fn box_storage() -> Result<Box<Filter>, GitBoxError> {
    let config = try!(try!(open_config(false)).snapshot());

    match try!(config.get_str("box.storagetype")) {
        #[cfg(feature = "artifactory")]
        "ARTIFACTORY" => Ok(Box::new(try!(make_art_box(config)))),
        #[cfg(feature = "file")]
        "FILE" => Ok(Box::new(try!(make_file_box(config)))),
        #[cfg(feature = "ssh2")]
        "SSH2" => Ok(Box::new(try!(make_ssh2_box(config)))),
        _ => Err(GitBoxError::Other("Unknown storage type")),
    }
}

#[cfg(test)]
mod test {
    use super::*;

    #[test]
    fn test_open_config() {
        assert!(open_config(false).is_ok());
    }

    #[test]
    fn test_track_untrack() {
        assert!(track("**/*.txt").is_ok());
        assert!(track("**/*.txt").is_ok());
        assert!(untrack("**/*.txt").is_ok());
    }

    #[test]
    fn test_set_unset_filter() {
        match open_config(false) {
            Ok(ref mut config) => {
                assert!(set_filter(config).is_ok());
                assert!(unset_filter(config).is_ok());
            }
            Err(_) => assert!(false),
        }
    }

    #[test]
    fn test_set_unset_global_filter() {
        match open_config(true) {
            Ok(ref mut config) => {
                assert!(set_filter(config).is_ok());
                assert!(unset_filter(config).is_ok());
            }
            Err(_) => assert!(false),
        }
    }
}