This commit is contained in:
Thomas Forgione 2019-02-12 10:41:13 +01:00
parent aa736dc2a8
commit 2ebe6a98be
No known key found for this signature in database
GPG Key ID: 203DAEA747F48F41
1 changed files with 51 additions and 19 deletions

View File

@ -1,37 +1,69 @@
use std::env; use std::{env, fmt, result};
use std::process::exit; use std::process::exit;
use std::error::Error; use std::error::Error;
use std::path::PathBuf; use std::path::PathBuf;
use std::fs::File; use std::fs::File;
use std::io::{Write, BufRead, BufReader}; use std::io::{self, Write, BufRead, BufReader};
use colored::*; use colored::*;
pub fn git_dir() -> String { macro_rules! impl_from_error {
match env::var("GCLONE_PATH") { ($type: ty, $variant: path, $from: ty) => {
Ok(path) => path, impl From<$from> for $type {
Err(e) => { fn from(e: $from) -> $type {
eprintln!("{} {} {}", $variant(e)
"error:".bold().red(), }
"environment variable GCLONE_PATH must be set:".bold(), }
e.description());
exit(1);
},
} }
} }
#[derive(Debug)]
pub enum MError {
NoGclonePath(env::VarError),
IoError(io::Error),
}
impl_from_error!(MError, MError::NoGclonePath, env::VarError);
impl_from_error!(MError, MError::IoError, io::Error);
impl fmt::Display for MError {
fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
match self {
MError::NoGclonePath(e) =>
write!(fmt, "{} {} {}",
"error:".bold().red(),
"couldn't read environment variable GCLONE_PATH".bold(),
e),
MError::IoError(e) =>
write!(fmt, "{} {} {}",
"error:".bold().red(),
"couldn't read or write cache:".bold(),
e),
}
}
}
impl Error for MError {
}
type Result<T> = result::Result<T, MError>;
pub fn git_dir() -> Result<String> {
Ok(env::var("GCLONE_PATH")?)
}
pub struct Cache(Vec<String>); pub struct Cache(Vec<String>);
impl Cache { impl Cache {
pub fn read() -> Cache { pub fn read() -> Result<Cache> {
let mut path = PathBuf::from(git_dir()); let mut path = PathBuf::from(git_dir()?);
path.push(".cdgcache"); path.push(".cdgcache");
let file = match File::open(&path) { let file = match File::open(&path) {
Ok(f) => f, Ok(f) => f,
Err(_) => return Cache(vec![]), Err(_) => return Ok(Cache(vec![])),
}; };
let file = BufReader::new(file); let file = BufReader::new(file);
@ -44,11 +76,11 @@ impl Cache {
} }
} }
Cache(values) Ok(Cache(values))
} }
pub fn write(&self) -> Result<(), Box<Error>> { pub fn write(&self) -> Result<()> {
let mut path = PathBuf::from(git_dir()); let mut path = PathBuf::from(git_dir()?);
path.push(".cdgcache"); path.push(".cdgcache");
let mut file = File::create(path)?; let mut file = File::create(path)?;