formaty/src/formatter/mod.rs

86 lines
2.1 KiB
Rust

pub mod format;
mod printers;
use crate::formatter::format::Format;
use rust_embed::RustEmbed;
use serde::Deserialize;
use std::error::Error;
use std::fmt::{Display, Formatter};
use std::fs::File;
use std::io::Read;
use std::path::PathBuf;
use std::str;
#[derive(Debug)]
#[allow(clippy::enum_variant_names)]
pub enum FormatConfigError {
IOError(std::io::Error),
TomlError(toml::de::Error),
Utf8Error(std::str::Utf8Error),
}
impl Error for FormatConfigError {}
impl From<std::io::Error> for FormatConfigError {
fn from(e: std::io::Error) -> Self {
Self::IOError(e)
}
}
impl From<toml::de::Error> for FormatConfigError {
fn from(e: toml::de::Error) -> Self {
Self::TomlError(e)
}
}
impl From<std::str::Utf8Error> for FormatConfigError {
fn from(e: std::str::Utf8Error) -> Self {
Self::Utf8Error(e)
}
}
impl Display for FormatConfigError {
fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
let err_msg = match self {
FormatConfigError::IOError(e) => e.to_string(),
FormatConfigError::TomlError(e) => e.to_string(),
FormatConfigError::Utf8Error(e) => e.to_string(),
};
write!(f, "Format Config Error: {}", err_msg)
}
}
#[derive(RustEmbed)]
#[folder = "formats/"]
#[include = "*.toml"]
struct BuiltInFormats;
#[derive(Debug, Deserialize, Clone)]
pub struct FormatConfig {
pub formats: Vec<Format>,
}
impl FormatConfig {
pub fn new(config_path: &Option<PathBuf>) -> Result<Self, FormatConfigError> {
let mut contents = String::new();
if let Some(config_path) = config_path {
let mut config = File::open(config_path)?;
config.read_to_string(&mut contents)?;
}
for format_file_path in BuiltInFormats::iter() {
if format_file_path.ends_with("md") {
continue;
}
let format_file = BuiltInFormats::get(&format_file_path).unwrap();
contents.push_str(str::from_utf8(&format_file.data).unwrap());
}
Ok(toml::from_str(&contents)?)
}
}