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 toml; use error::Error; use logger::LogLevel; pub fn add_to_beginning>(path: PathBuf, to_add: T) -> PathBuf { Path::new(&to_add.into()).join(path) } pub fn write_toml(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>( 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)), } } }