98 lines
2.7 KiB
Rust
98 lines
2.7 KiB
Rust
use std::fs::{create_dir_all, File};
|
|
use std::io::prelude::*;
|
|
use std::path::{Path, PathBuf};
|
|
|
|
use serde::de::DeserializeOwned;
|
|
use serde::Serialize;
|
|
use toml;
|
|
|
|
use crate::error::Error;
|
|
use crate::logger::LogLevel;
|
|
|
|
pub fn add_to_beginning<T: Into<String>>(path: PathBuf, to_add: T) -> PathBuf {
|
|
Path::new(&to_add.into()).join(path)
|
|
}
|
|
pub fn get_toml<T: DeserializeOwned>(path: &PathBuf) -> Result<T, Error> {
|
|
let path_str = match path.to_str() {
|
|
Some(path_str) => path_str,
|
|
None => "",
|
|
};
|
|
|
|
let mut file = match File::open(path.as_path()) {
|
|
Ok(file) => file,
|
|
Err(err) => {
|
|
return Err(Error::new(
|
|
LogLevel::SEVERE,
|
|
format!(
|
|
"Failed to open toml: {}, Reason: {}",
|
|
path.to_str().unwrap(),
|
|
err
|
|
),
|
|
))
|
|
}
|
|
};
|
|
let mut contents: String = String::new();
|
|
file.read_to_string(&mut contents)?;
|
|
match toml::from_str(&contents) {
|
|
Ok(config) => Ok(config),
|
|
Err(err) => Err(Error::new(
|
|
LogLevel::SEVERE,
|
|
format!("Erronous toml ({}): {}", path_str, err),
|
|
)),
|
|
}
|
|
}
|
|
|
|
pub fn write_toml<T: Serialize>(path: &PathBuf, data: &T, overwrite: bool) -> Result<(), Error> {
|
|
match toml::ser::to_string(data) {
|
|
Ok(text) => match write_file(&path, text, overwrite) {
|
|
Ok(_) => Ok(()),
|
|
Err(err) => Err(Error::new(
|
|
LogLevel::SEVERE,
|
|
format!(
|
|
"Failed to write {:?}: {}",
|
|
path,
|
|
err.description().to_owned()
|
|
),
|
|
)),
|
|
},
|
|
Err(err) => Err(Error::new(
|
|
LogLevel::SEVERE,
|
|
format!("Failed to serialize {:?}: {}", path, err),
|
|
)),
|
|
}
|
|
}
|
|
|
|
pub fn write_file<T: Into<String>>(
|
|
path: &PathBuf,
|
|
content: T,
|
|
overwrite: bool,
|
|
) -> Result<(), Error> {
|
|
write_bytes(path, content.into().as_bytes(), overwrite)
|
|
}
|
|
|
|
pub fn write_bytes(path: &PathBuf, bytes: &[u8], overwrite: bool) -> Result<(), Error> {
|
|
if let Some(parent) = path.clone().parent() {
|
|
create_dir_all(parent)?;
|
|
} else {
|
|
return Err(Error::new(
|
|
LogLevel::SEVERE,
|
|
format!("Could not find parent folder for {:?}", path),
|
|
));
|
|
}
|
|
|
|
if path.exists() && !overwrite {
|
|
Err(Error::new(
|
|
LogLevel::SEVERE,
|
|
format!(
|
|
"File already exists: {:?} -- Consider using overwrite-flag",
|
|
path
|
|
),
|
|
))
|
|
} else {
|
|
match File::create(path) {
|
|
Ok(mut file) => Ok(file.write_all(bytes).unwrap()),
|
|
Err(err) => Err(Error::from(err)),
|
|
}
|
|
}
|
|
}
|