use std::path::{Path, PathBuf};
use std::io::{BufReader, BufWriter, Read, Write};
use std::fs::File;
use std::result::Result as StdResult;
use failure::{Error, ResultExt, ensure};
pub use std::fs::create_dir_all as create_dir;
pub use remove_dir_all::remove_dir_all;
pub fn read_file<P: AsRef<Path>>(path: P) -> Result<String, Error> {
let path = path.as_ref();
ensure!(
path.exists() && path.is_file(),
"Path {:?} is not a file!",
path
);
let file = File::open(path).with_context(|_| format!("Could not open file {:?}", path))?;
let mut file = BufReader::new(file);
let mut result = String::new();
file.read_to_string(&mut result)
.with_context(|_| format!("Could not read file {:?}", path))?;
Ok(result)
}
pub fn write_to_file<P: AsRef<Path>>(path: P, content: &str) -> Result<(), Error> {
let path = path.as_ref();
let file =
File::create(path).with_context(|_| format!("Could not create/open file {:?}", path))?;
let mut file = BufWriter::new(file);
file.write_all(content.as_bytes())
.with_context(|_| format!("Could not write to file {:?}", path))?;
Ok(())
}
pub fn glob(patterns: &str) -> Result<Vec<PathBuf>, Error> {
use globwalk::glob;
let files: Vec<_> = glob(patterns)?
.max_depth(1)
.into_iter()
.filter_map(StdResult::ok)
.map(|dir_entry| dir_entry.path().to_owned())
.collect();
ensure!(
files.get(0).is_some(),
"No files match pattern `{}`",
patterns
);
Ok(files)
}