use std::path::Path;
use crate::{Result, Source, Value};
pub(crate) const COMMENT_PREFIXES: [char; 2] = ['#', '_'];
pub(crate) fn is_commented(name: &str) -> bool {
name.starts_with(COMMENT_PREFIXES)
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum Format {
Json,
Jsonc,
Yaml,
Toml,
Ini,
Cnf,
Env,
Csv,
Excel,
Ods,
}
impl Format {
pub(crate) const ALL: [Format; 10] = [
Format::Jsonc,
Format::Json,
Format::Yaml,
Format::Toml,
Format::Ini,
Format::Cnf,
Format::Env,
Format::Csv,
Format::Excel,
Format::Ods,
];
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,
"cnf" => Format::Cnf,
"env" => Format::Env,
"csv" => Format::Csv,
"excel" => Format::Excel,
"ods" => Format::Ods,
_ => 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::Cnf => "cnf",
Format::Env => "env",
Format::Csv => "csv",
Format::Excel => "excel",
Format::Ods => "ods",
}
}
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::Cnf => &["cnf"],
Format::Env => &["env"],
Format::Csv => &["csv"],
Format::Excel => &["xlsx", "xlsm", "xlsb", "xls"],
Format::Ods => &["ods"],
}
}
pub fn default_layout(self) -> TableLayout {
match self {
Format::Excel | Format::Ods => TableLayout::Db,
_ => TableLayout::Kv,
}
}
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(),
layout: self.default_layout(),
}
}
}
#[derive(Debug, Clone, PartialEq)]
pub enum FormatKind {
Builtin(Format),
Custom(CustomFormat),
}
#[derive(Debug, Clone, PartialEq)]
pub struct FormatSpec {
pub(crate) format: FormatKind,
pub(crate) extensions: Vec<String>,
pub(crate) layout: TableLayout,
}
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<&str> for FormatKind {
fn from(id: &str) -> Self {
FormatKind::Builtin(
Format::from_id(id).unwrap_or_else(|| panic!("unknown format id: {id:?}")),
)
}
}
impl From<CustomFormat> for FormatSpec {
fn from(custom: CustomFormat) -> Self {
Self {
extensions: custom.extensions.clone(),
format: FormatKind::Custom(custom),
layout: TableLayout::Kv,
}
}
}
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)
}
}
impl<const N: usize, L: Into<TableLayout>> From<(Format, [&str; N], L)> for FormatSpec {
fn from((format, extensions, layout): (Format, [&str; N], L)) -> Self {
assert!(
matches!(format, Format::Csv | Format::Excel | Format::Ods),
"'{}' is not a table format (csv, excel, ods) — table layouts do not apply",
format.id()
);
FormatSpec {
layout: layout.into(),
..format.exts(extensions)
}
}
}
impl<const N: usize, L: Into<TableLayout>> From<(&str, [&str; N], L)> for FormatSpec {
fn from((id, extensions, layout): (&str, [&str; N], L)) -> Self {
let format = Format::from_id(id).unwrap_or_else(|| panic!("unknown format id: {id:?}"));
(format, extensions, layout).into()
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum Order {
#[default]
FoldersFirstAlphabetic,
Alphabetic,
ReverseAlphabetic,
}
impl Order {
pub fn from_id(id: &str) -> Option<Order> {
Some(match id.to_lowercase().replace('-', "_").as_str() {
"folders_first_alphabetic" | "folders_first" | "default" => {
Order::FoldersFirstAlphabetic
}
"alphabetic" => Order::Alphabetic,
"reverse_alphabetic" | "reverse" => Order::ReverseAlphabetic,
_ => return None,
})
}
pub fn id(self) -> &'static str {
match self {
Order::FoldersFirstAlphabetic => "folders_first_alphabetic",
Order::Alphabetic => "alphabetic",
Order::ReverseAlphabetic => "reverse_alphabetic",
}
}
}
impl From<&str> for Order {
fn from(id: &str) -> Self {
Order::from_id(id).unwrap_or_else(|| panic!("unknown order id: {id:?}"))
}
}
#[derive(Debug, Clone, PartialEq, Default)]
pub enum TableLayout {
#[default]
Kv,
Db,
Custom(CustomLayout),
}
impl TableLayout {
pub fn from_id(id: &str) -> Option<TableLayout> {
Some(match id.to_lowercase().as_str() {
"kv" | "kvf" => TableLayout::Kv,
"db" => TableLayout::Db,
_ => return None,
})
}
pub fn id(&self) -> &str {
match self {
TableLayout::Kv => "kv",
TableLayout::Db => "db",
TableLayout::Custom(custom) => &custom.id,
}
}
}
impl From<&str> for TableLayout {
fn from(id: &str) -> Self {
TableLayout::from_id(id).unwrap_or_else(|| {
panic!("unknown table layout id: {id:?} (valid: kv, db, or a CustomLayout)")
})
}
}
impl From<CustomLayout> for TableLayout {
fn from(custom: CustomLayout) -> Self {
TableLayout::Custom(custom)
}
}
pub(crate) type CustomRowsParser =
std::sync::Arc<dyn Fn(Vec<Vec<String>>, &Path, &Options) -> Result<Value> + Send + Sync>;
#[derive(Clone)]
pub struct CustomLayout {
pub(crate) id: String,
pub(crate) parser: CustomRowsParser,
}
impl CustomLayout {
pub fn new<F>(id: impl Into<String>, parser: F) -> Self
where
F: Fn(Vec<Vec<String>>, &Path, &Options) -> Result<Value> + Send + Sync + 'static,
{
Self {
id: id.into(),
parser: std::sync::Arc::new(parser),
}
}
}
impl std::fmt::Debug for CustomLayout {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("CustomLayout")
.field("id", &self.id)
.finish_non_exhaustive()
}
}
impl PartialEq for CustomLayout {
fn eq(&self, other: &Self) -> bool {
self.id == other.id && std::sync::Arc::ptr_eq(&self.parser, &other.parser)
}
}
pub(crate) type CustomParser =
std::sync::Arc<dyn Fn(&str, &Path, &Options) -> Result<Value> + Send + Sync>;
#[derive(Clone)]
pub struct CustomFormat {
pub(crate) id: String,
pub(crate) 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 dir_depth: isize,
pub filename_as_key: bool,
pub dirname_as_key: bool,
pub dot_key: bool,
pub case_sensitive: bool,
pub order: Order,
pub sheetname_as_key: bool,
pub auto_no_ext_files: bool,
pub ignore_unknown_ext: bool,
pub ignore_commented_data_keys: bool,
pub ignore_commented_filenames: bool,
pub ignore_commented_dirnames: bool,
pub ignore_commented_sheetnames: bool,
pub ignore_hidden_sheets: bool,
}
impl Default for Options {
fn default() -> Self {
Self {
sources: vec![Source::Path("config".into())],
formats: enabled_formats(),
dir_depth: if cfg!(feature = "tree") { -1 } else { 1 },
filename_as_key: cfg!(feature = "tree"),
dirname_as_key: cfg!(feature = "tree"),
sheetname_as_key: cfg!(feature = "tree"),
dot_key: true,
case_sensitive: true,
order: Order::default(),
auto_no_ext_files: true,
ignore_unknown_ext: true,
ignore_commented_data_keys: true,
ignore_commented_filenames: true,
ignore_commented_dirnames: true,
ignore_commented_sheetnames: true,
ignore_hidden_sheets: 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 = "cnf")]
formats.push(Format::Cnf.into());
#[cfg(feature = "env")]
formats.push(Format::Env.into());
#[cfg(feature = "csv")]
formats.push(Format::Csv.into());
#[cfg(feature = "excel")]
formats.push(Format::Excel.into());
#[cfg(feature = "ods")]
formats.push(Format::Ods.into());
formats
}