use std::path::Path;
use crate::{Result, Source, Value};
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum Format {
Json,
Jsonc,
Yaml,
Toml,
Ini,
Env,
Csv,
}
impl Format {
pub fn from_id(id: &str) -> Option<Format> {
Some(match id {
"json" => Format::Json,
"jsonc" => Format::Jsonc,
"yaml" => Format::Yaml,
"toml" => Format::Toml,
"ini" => Format::Ini,
"env" => Format::Env,
"csv" => Format::Csv,
_ => return None,
})
}
pub fn id(self) -> &'static str {
match self {
Format::Json => "json",
Format::Jsonc => "jsonc",
Format::Yaml => "yaml",
Format::Toml => "toml",
Format::Ini => "ini",
Format::Env => "env",
Format::Csv => "csv",
}
}
pub fn default_extensions(self) -> &'static [&'static str] {
match self {
Format::Json => &["json"],
Format::Jsonc => &["json", "jsonc"],
Format::Yaml => &["yml", "yaml"],
Format::Toml => &["toml"],
Format::Ini => &["ini"],
Format::Env => &["env"],
Format::Csv => &["csv"],
}
}
pub fn exts<I, S>(self, extensions: I) -> FormatSpec
where
I: IntoIterator<Item = S>,
S: Into<String>,
{
FormatSpec {
format: FormatKind::Builtin(self),
extensions: extensions.into_iter().map(Into::into).collect(),
}
}
}
#[derive(Debug, Clone, PartialEq)]
pub enum FormatKind {
Builtin(Format),
Custom(CustomFormat),
}
#[derive(Debug, Clone, PartialEq)]
pub struct FormatSpec {
pub format: FormatKind,
pub extensions: Vec<String>,
}
impl From<Format> for FormatSpec {
fn from(format: Format) -> Self {
format.exts(format.default_extensions().iter().copied())
}
}
impl From<Format> for FormatKind {
fn from(format: Format) -> Self {
FormatKind::Builtin(format)
}
}
impl From<CustomFormat> for FormatKind {
fn from(custom: CustomFormat) -> Self {
FormatKind::Custom(custom)
}
}
impl From<CustomFormat> for FormatSpec {
fn from(custom: CustomFormat) -> Self {
Self {
extensions: custom.extensions.clone(),
format: FormatKind::Custom(custom),
}
}
}
impl From<&str> for FormatSpec {
fn from(id: &str) -> Self {
Format::from_id(id)
.unwrap_or_else(|| panic!("unknown format id: {id:?}"))
.into()
}
}
impl<const N: usize> From<(Format, [&str; N])> for FormatSpec {
fn from((format, extensions): (Format, [&str; N])) -> Self {
format.exts(extensions)
}
}
impl<const N: usize> From<(&str, [&str; N])> for FormatSpec {
fn from((id, extensions): (&str, [&str; N])) -> Self {
Format::from_id(id)
.unwrap_or_else(|| panic!("unknown format id: {id:?}"))
.exts(extensions)
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum Order {
#[default]
FoldersFirstAlphabetic,
Alphabetic,
ReverseAlphabetic,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub struct TableTypes {
pub null: bool,
pub array: bool,
pub json: bool,
}
impl TableTypes {
pub fn scalars() -> Self {
Self::default()
}
pub fn all() -> Self {
Self {
null: true,
array: true,
json: true,
}
}
}
#[derive(Debug, Clone, PartialEq)]
pub struct TableColumns {
pub key: String,
pub value: String,
pub format: String,
}
impl Default for TableColumns {
fn default() -> Self {
Self {
key: "key".into(),
value: "value".into(),
format: "format".into(),
}
}
}
#[derive(Debug, Clone, PartialEq)]
pub struct TableOptions {
pub types: TableTypes,
pub delimiter: char,
pub header: bool,
pub columns: TableColumns,
}
impl Default for TableOptions {
fn default() -> Self {
Self {
types: TableTypes::scalars(),
delimiter: ';',
header: false,
columns: TableColumns::default(),
}
}
}
pub(crate) type CustomParser =
std::sync::Arc<dyn Fn(&str, &Path, &Options) -> Result<Value> + Send + Sync>;
#[derive(Clone)]
pub struct CustomFormat {
pub id: String,
pub extensions: Vec<String>,
pub(crate) parser: CustomParser,
}
impl CustomFormat {
pub fn new<I, S, F>(id: impl Into<String>, extensions: I, parser: F) -> Self
where
I: IntoIterator<Item = S>,
S: Into<String>,
F: Fn(&str, &Path, &Options) -> Result<Value> + Send + Sync + 'static,
{
Self {
id: id.into(),
extensions: extensions.into_iter().map(Into::into).collect(),
parser: std::sync::Arc::new(parser),
}
}
}
impl std::fmt::Debug for CustomFormat {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("CustomFormat")
.field("id", &self.id)
.field("extensions", &self.extensions)
.finish_non_exhaustive()
}
}
impl PartialEq for CustomFormat {
fn eq(&self, other: &Self) -> bool {
self.id == other.id
&& self.extensions == other.extensions
&& std::sync::Arc::ptr_eq(&self.parser, &other.parser)
}
}
#[derive(Debug, Clone, PartialEq)]
pub struct Options {
pub sources: Vec<Source>,
pub formats: Vec<FormatSpec>,
pub recursive: bool,
pub flat: bool,
pub dot_key: bool,
pub case_sensitive: bool,
pub order: Order,
pub table: TableOptions,
pub tree: bool,
pub auto_files: bool,
pub ignore_unknown_ext: bool,
}
impl Default for Options {
fn default() -> Self {
Self {
sources: vec![Source::folder("config")],
formats: enabled_formats(),
recursive: false,
flat: true,
dot_key: true,
case_sensitive: true,
order: Order::default(),
table: TableOptions::default(),
tree: false,
auto_files: true,
ignore_unknown_ext: true,
}
}
}
#[allow(clippy::vec_init_then_push)] fn enabled_formats() -> Vec<FormatSpec> {
let mut formats = Vec::new();
#[cfg(feature = "json")]
formats.push(Format::Json.into());
#[cfg(feature = "jsonc")]
formats.push(Format::Jsonc.into());
#[cfg(feature = "yaml")]
formats.push(Format::Yaml.into());
#[cfg(feature = "toml")]
formats.push(Format::Toml.into());
#[cfg(feature = "ini")]
formats.push(Format::Ini.into());
#[cfg(feature = "env")]
formats.push(Format::Env.into());
#[cfg(feature = "csv")]
formats.push(Format::Csv.into());
formats
}