use std::{fs, path::Path};
use serde::{de::DeserializeOwned, Serialize};
use super::{Error, Result};
pub struct FileHandler;
impl FileHandler {
pub fn write_file(data: impl Serialize, path: &Path) -> Result<()> {
let toml = toml::to_string(&data)?;
fs::write(path, toml)?;
Ok(())
}
pub fn write_new_file(data: impl Serialize, path: &Path) -> Result<()> {
if path.exists() {
return Err(Error::PathExists(
path.to_str().unwrap_or_default().to_string(),
));
}
let toml = toml::to_string(&data)?;
fs::write(path, toml)?;
Ok(())
}
pub fn overwrite_file(data: impl Serialize, path: &Path) -> Result<()> {
if !path.exists() {
return Err(Error::PathDoesNotExist(
path.to_str().unwrap_or_default().to_string(),
));
}
let toml = toml::to_string(&data)?;
fs::write(path, toml)?;
Ok(())
}
pub fn read_file<T: DeserializeOwned>(path: &Path) -> Result<T> {
Ok(toml::from_str(&fs::read_to_string(path)?)?)
}
}