teascade-generator/src/file_writer.rs

115 lines
3.3 KiB
Rust

use std::fs::{create_dir_all, File};
use std::io::prelude::*;
use std::path::{Path, PathBuf};
use std::error::Error as STDError;
use serde::Serialize;
use serde::de::DeserializeOwned;
use toml;
use error::Error;
use 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.description().to_owned()
),
))
}
};
let mut contents: String = String::new();
file.read_to_string(&mut contents)?;
match toml::from_str(&contents) {
Ok(config) => Ok(config),
Err(err) => {
if let Some((line, col)) = err.line_col() {
Err(Error::new(
LogLevel::SEVERE,
format!("Erronous toml: {} at {}:{}", path_str, line, col),
))
} else {
Err(Error::new(
LogLevel::SEVERE,
format!(
"Failed to parse toml correctly: {}. Check variable names!",
path_str
),
))
}
}
}
}
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.description().to_owned()
),
)),
}
}
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.clone())?;
} 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)),
}
}
}