use bytes::BytesMut;
use graph_error::GraphFailure;
use std::ffi::{OsStr, OsString};
use std::io::Read;
use std::path::{Path, PathBuf};
#[derive(Clone, Debug, Default)]
pub struct FileConfig {
pub path: PathBuf,
pub create_directory_all: bool,
pub overwrite_existing_file: bool,
pub file_name: Option<OsString>,
pub extension: Option<OsString>,
}
impl FileConfig {
pub fn new<P: AsRef<Path>>(path: P) -> FileConfig {
FileConfig {
path: path.as_ref().to_path_buf(),
create_directory_all: true,
overwrite_existing_file: false,
file_name: None,
extension: None,
}
}
pub fn create_directories(mut self, create_directories: bool) -> FileConfig {
self.create_directory_all = create_directories;
self
}
pub fn overwrite_existing_file(mut self, overwrite_file: bool) -> FileConfig {
self.overwrite_existing_file = overwrite_file;
self
}
pub fn file_name(mut self, file_name: &OsStr) -> FileConfig {
self.file_name = Some(file_name.to_os_string());
self
}
pub fn extension(mut self, ext: &OsStr) -> FileConfig {
self.extension = Some(ext.to_os_string());
self
}
pub fn set_path<P: AsRef<Path>>(&mut self, path: P) {
self.path = path.as_ref().to_path_buf();
}
pub fn set_create_directories(&mut self, create_directories: bool) {
self.create_directory_all = create_directories;
}
pub fn set_overwrite_existing_file(&mut self, overwrite_file: bool) {
self.overwrite_existing_file = overwrite_file;
}
pub fn set_file_name(&mut self, file_name: &OsStr) {
self.file_name = Some(file_name.to_os_string());
}
pub fn set_extension(&mut self, ext: &OsStr) {
self.extension = Some(ext.to_os_string());
}
}
impl From<PathBuf> for FileConfig {
fn from(path_buf: PathBuf) -> Self {
FileConfig::new(path_buf.as_path())
}
}
impl From<&Path> for FileConfig {
fn from(path: &Path) -> Self {
FileConfig::new(path)
}
}
impl TryFrom<FileConfig> for BytesMut {
type Error = GraphFailure;
fn try_from(file_config: FileConfig) -> Result<Self, Self::Error> {
let mut file = std::fs::File::open(file_config.path.as_path())?;
let mut buf: Vec<u8> = Vec::new();
file.read_to_end(&mut buf)?;
Ok(BytesMut::from_iter(buf))
}
}