use std::{
env,
fs::File,
env::VarError,
path::{ Path, PathBuf },
io::{ self, Read, BufRead },
};
pub fn get_home_string() -> Result<String, VarError>{
env::var("HOME")
}
pub fn get_home() -> Result<PathBuf, VarError>{
match env::var("HOME"){
Ok(val) => Ok(PathBuf::from(val)),
Err(e) => Err(e)
}
}
pub fn get_config() -> Result<PathBuf, VarError>{
let mut home = get_home()?;
home.push(".config");
Ok(home)
}
pub fn file_exists(path: &Path) -> bool{
std::fs::metadata(path).is_ok()
}
pub enum DirStatus { Exists, Created, Error }
pub fn create_dir(path: &Path) -> DirStatus{
if file_exists(path){
return DirStatus::Exists;
}
let res = std::fs::create_dir_all(path);
if res.is_ok(){
DirStatus::Created
} else {
DirStatus::Error
}
}
pub fn read_file_into_buffer<P>(file_path: P) -> Result<Vec<u8>, std::io::Error>
where P: AsRef<Path>
{
let mut buffer = Vec::new();
let mut file = File::open(file_path)?;
file.read_to_end(&mut buffer)?;
Ok(buffer)
}
pub fn read_file_into_string<P>(file_path: P) -> Result<String, std::io::Error>
where P: AsRef<Path>
{
let mut string = String::new();
let mut file = File::open(file_path)?;
file.read_to_string(&mut string)?;
Ok(string)
}
pub fn read_lines_raw<P>(filename: P) -> io::Result<io::Lines<io::BufReader<File>>>
where P: AsRef<Path>
{
let file = File::open(filename)?;
Ok(io::BufReader::new(file).lines())
}
pub fn read_lines<P>(filename: P) -> Vec<String>
where P: AsRef<Path>
{
let mut res = Vec::new();
if let Ok(ls) = read_lines_raw(filename) {
for l in ls.map_while(Result::ok) {
res.push(l);
}
}
res
}
#[cfg(test)]
mod tests {
#[test]
fn it_works() {
assert_eq!(2 + 2, 4);
}
#[test]
fn file_exists_home(){
let t = super::file_exists(super::get_home().unwrap().as_path());
assert!(t);
}
#[test]
fn file_exists_void(){
let p = std::path::PathBuf::from("/home/thisdoesnotexist");
let t = super::file_exists(p.as_path());
assert!(!t);
}
}