crax 0.1.8

An interesting CLI for frontend programmer
Documentation
use std::{
    fs::{self, File},
    io::Read,
    path::{Path, PathBuf},
};

use serde::de::DeserializeOwned;

pub fn parse<T: DeserializeOwned>(input: &str) -> anyhow::Result<T> {
    Ok(toml::from_str::<T>(input)?)
}

pub fn read<T: DeserializeOwned>(loc: &PathBuf) -> anyhow::Result<T> {
    let mut content = String::new();
    File::open(loc)?.read_to_string(&mut content)?;

    parse(&content)
}

///
/// When content and default are all empty, Write nothing.
///  
pub fn save(loc: &PathBuf, content: &str, default: &str) -> anyhow::Result<()> {
    let write_content = if content.is_empty() { default } else { content };

    if write_content.is_empty() {
        Ok(())
    } else {
        Ok(fs::write(loc, write_content)?)
    }
}

pub fn str_to_path_buf(str: &str) -> PathBuf {
    Path::new(str).to_path_buf()
}

pub fn file_exists(path: &str) -> bool {
    match fs::metadata(path) {
        Ok(_) => true,
        Err(_) => false,
    }
}