Skip to main content

c4/
options.rs

1//! The plain-data configuration surface: [`Options`] and every type its
2//! fields are made of — formats and their specs (built-in and custom),
3//! folder order, and the table options.
4
5use std::path::Path;
6
7use crate::{Result, Source, Value};
8
9/// A config file format.
10///
11/// The variants always exist; whether a format can actually be parsed
12/// depends on the matching Cargo feature. Which extensions a format reads
13/// is part of [`FormatSpec`].
14#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
15pub enum Format {
16    Json,
17    Jsonc,
18    Yaml,
19    Toml,
20    Ini,
21    Env,
22    Csv,
23}
24
25impl Format {
26    /// Look a format up by its string id (`"json"`, `"jsonc"`, `"yaml"`,
27    /// `"toml"`, `"ini"`, `"env"`, `"csv"`).
28    pub fn from_id(id: &str) -> Option<Format> {
29        Some(match id {
30            "json" => Format::Json,
31            "jsonc" => Format::Jsonc,
32            "yaml" => Format::Yaml,
33            "toml" => Format::Toml,
34            "ini" => Format::Ini,
35            "env" => Format::Env,
36            "csv" => Format::Csv,
37            _ => return None,
38        })
39    }
40
41    /// The string id of this format.
42    pub fn id(self) -> &'static str {
43        match self {
44            Format::Json => "json",
45            Format::Jsonc => "jsonc",
46            Format::Yaml => "yaml",
47            Format::Toml => "toml",
48            Format::Ini => "ini",
49            Format::Env => "env",
50            Format::Csv => "csv",
51        }
52    }
53
54    /// The extensions (without the dot) this format claims by default.
55    ///
56    /// Extension matching is always case-insensitive, and a hidden file
57    /// named `.X` is treated as having extension `X` (so `.env` matches the
58    /// `env` extension).
59    pub fn default_extensions(self) -> &'static [&'static str] {
60        match self {
61            Format::Json => &["json"],
62            Format::Jsonc => &["json", "jsonc"],
63            Format::Yaml => &["yml", "yaml"],
64            Format::Toml => &["toml"],
65            Format::Ini => &["ini"],
66            Format::Env => &["env"],
67            Format::Csv => &["csv"],
68        }
69    }
70
71    /// Pair this format with custom extensions.
72    pub fn exts<I, S>(self, extensions: I) -> FormatSpec
73    where
74        I: IntoIterator<Item = S>,
75        S: Into<String>,
76    {
77        FormatSpec {
78            format: FormatKind::Builtin(self),
79            extensions: extensions.into_iter().map(Into::into).collect(),
80        }
81    }
82}
83
84/// What a [`FormatSpec`] entry parses with: a built-in format or a
85/// user-defined [`CustomFormat`].
86#[derive(Debug, Clone, PartialEq)]
87pub enum FormatKind {
88    Builtin(Format),
89    Custom(CustomFormat),
90}
91
92/// A format plus the extensions it reads — one entry of [`Options::formats`].
93///
94/// Accepted forms (all `.into()`):
95/// - `Format::Yaml` or `"yaml"` — default extensions
96/// - `(Format::Yaml, ["yml", "conf"])` or `("yaml", ["yml", "conf"])` —
97///   custom extensions
98/// - a [`CustomFormat`] — user-defined parser with the extensions it was
99///   built with
100#[derive(Debug, Clone, PartialEq)]
101pub struct FormatSpec {
102    pub(crate) format: FormatKind,
103    /// Extensions without the leading dot.
104    pub(crate) extensions: Vec<String>,
105}
106
107impl From<Format> for FormatSpec {
108    fn from(format: Format) -> Self {
109        format.exts(format.default_extensions().iter().copied())
110    }
111}
112
113impl From<Format> for FormatKind {
114    fn from(format: Format) -> Self {
115        FormatKind::Builtin(format)
116    }
117}
118
119impl From<CustomFormat> for FormatKind {
120    fn from(custom: CustomFormat) -> Self {
121        FormatKind::Custom(custom)
122    }
123}
124
125impl From<&str> for FormatKind {
126    /// A built-in format id (`"jsonc"`, `"yaml"`, …). Panics on an unknown
127    /// id — this is config-time code. Lets a `(id, text)` string source
128    /// name its format by string.
129    fn from(id: &str) -> Self {
130        FormatKind::Builtin(
131            Format::from_id(id).unwrap_or_else(|| panic!("unknown format id: {id:?}")),
132        )
133    }
134}
135
136impl From<CustomFormat> for FormatSpec {
137    fn from(custom: CustomFormat) -> Self {
138        Self {
139            extensions: custom.extensions.clone(),
140            format: FormatKind::Custom(custom),
141        }
142    }
143}
144
145impl From<&str> for FormatSpec {
146    /// Panics on an unknown format id — this is config-time code.
147    fn from(id: &str) -> Self {
148        Format::from_id(id)
149            .unwrap_or_else(|| panic!("unknown format id: {id:?}"))
150            .into()
151    }
152}
153
154impl<const N: usize> From<(Format, [&str; N])> for FormatSpec {
155    fn from((format, extensions): (Format, [&str; N])) -> Self {
156        format.exts(extensions)
157    }
158}
159
160impl<const N: usize> From<(&str, [&str; N])> for FormatSpec {
161    /// Panics on an unknown format id — this is config-time code.
162    fn from((id, extensions): (&str, [&str; N])) -> Self {
163        Format::from_id(id)
164            .unwrap_or_else(|| panic!("unknown format id: {id:?}"))
165            .exts(extensions)
166    }
167}
168
169/// File load order inside a folder.
170#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
171pub enum Order {
172    /// Subfolders first, then files, each group alphabetic — how directory
173    /// listings are conventionally sorted.
174    #[default]
175    FoldersFirstAlphabetic,
176    /// Pure lexicographic order, folders and files interleaved.
177    Alphabetic,
178    ReverseAlphabetic,
179}
180
181impl Order {
182    /// Look an order up by its string id. Accepts `-` or `_` between words
183    /// and a couple of short aliases:
184    /// `folders_first_alphabetic` (`folders_first`, `default`),
185    /// `alphabetic`, `reverse_alphabetic` (`reverse`).
186    pub fn from_id(id: &str) -> Option<Order> {
187        Some(match id.to_lowercase().replace('-', "_").as_str() {
188            "folders_first_alphabetic" | "folders_first" | "default" => {
189                Order::FoldersFirstAlphabetic
190            }
191            "alphabetic" => Order::Alphabetic,
192            "reverse_alphabetic" | "reverse" => Order::ReverseAlphabetic,
193            _ => return None,
194        })
195    }
196
197    /// The canonical string id of this order.
198    pub fn id(self) -> &'static str {
199        match self {
200            Order::FoldersFirstAlphabetic => "folders_first_alphabetic",
201            Order::Alphabetic => "alphabetic",
202            Order::ReverseAlphabetic => "reverse_alphabetic",
203        }
204    }
205}
206
207impl From<&str> for Order {
208    /// Panics on an unknown id — this is config-time code. See
209    /// [`Order::from_id`] for the accepted spellings.
210    fn from(id: &str) -> Self {
211        Order::from_id(id).unwrap_or_else(|| panic!("unknown order id: {id:?}"))
212    }
213}
214
215/// The parser callback of a [`CustomFormat`]: `(text, path, options)`.
216pub(crate) type CustomParser =
217    std::sync::Arc<dyn Fn(&str, &Path, &Options) -> Result<Value> + Send + Sync>;
218
219/// A user-defined format: an id, the extensions it claims, and a parser
220/// callback. It goes into [`Options::formats`] like any built-in format
221/// (`formats: [..the defaults, md.into()]`), so the usual rule applies —
222/// the last claimer of an extension owns it, and a custom format can take
223/// over a built-in extension. Table-shaped custom formats can lower their
224/// file into rows and reuse the generic table stage via
225/// [`parse_table`](crate::parse_table).
226///
227/// A markdown pipe-table as a config format (runs as a doc test — a
228/// string source can name a custom format directly, no files needed):
229///
230/// ```
231/// use c4::{CustomFormat, Loader};
232///
233/// # fn main() -> Result<(), c4::Error> {
234/// let md = CustomFormat::new("md-table", ["md"], |text, path, options| {
235///     let rows: Vec<Vec<String>> = text
236///         .lines()
237///         .map(str::trim)
238///         .filter(|l| l.starts_with('|') && !l.contains("---"))
239///         // markdown tables always start with a header row — dropping
240///         // it here keeps the data rows positional (key,value[,format]),
241///         // exactly what parse_table expects
242///         .skip(1)
243///         .map(|l| {
244///             l.trim_matches('|')
245///                 .split('|')
246///                 .map(|cell| cell.trim().to_owned())
247///                 .collect()
248///         })
249///         .collect();
250///     c4::parse_table(rows, path, options)
251/// });
252///
253/// // to read `.md` files instead, push `md` into Options.formats —
254/// // custom formats claim extensions exactly like built-ins do
255/// let value: c4::Value = Loader::new(c4::Options {
256///         sources: vec![(
257///             md,
258///             "| key  | value | format |
259///              | ---- | ----- | ------ |
260///              | name | c4    | str    |
261///              | port | 8080  | u16    |",
262///         )
263///             .into()],
264///         ..c4::Options::default()
265///     })
266///     .load()?;
267/// assert_eq!(value["name"].as_str(), Some("c4"));
268/// assert_eq!(value["port"].as_u64(), Some(8080));
269/// # Ok(())
270/// # }
271/// ```
272#[derive(Clone)]
273pub struct CustomFormat {
274    pub(crate) id: String,
275    /// Extensions without the leading dot.
276    pub(crate) extensions: Vec<String>,
277    /// `(text, path, options)` — `path` labels errors. Crate-private:
278    /// build custom formats through [`CustomFormat::new`].
279    pub(crate) parser: CustomParser,
280}
281
282impl CustomFormat {
283    pub fn new<I, S, F>(id: impl Into<String>, extensions: I, parser: F) -> Self
284    where
285        I: IntoIterator<Item = S>,
286        S: Into<String>,
287        F: Fn(&str, &Path, &Options) -> Result<Value> + Send + Sync + 'static,
288    {
289        Self {
290            id: id.into(),
291            extensions: extensions.into_iter().map(Into::into).collect(),
292            parser: std::sync::Arc::new(parser),
293        }
294    }
295}
296
297impl std::fmt::Debug for CustomFormat {
298    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
299        f.debug_struct("CustomFormat")
300            .field("id", &self.id)
301            .field("extensions", &self.extensions)
302            .finish_non_exhaustive()
303    }
304}
305
306impl PartialEq for CustomFormat {
307    fn eq(&self, other: &Self) -> bool {
308        self.id == other.id
309            && self.extensions == other.extensions
310            && std::sync::Arc::ptr_eq(&self.parser, &other.parser)
311    }
312}
313
314/// All loader options.
315///
316/// Plain data on purpose: set the fields you care about and take the rest
317/// from `..Options::default()`.
318#[derive(Debug, Clone, PartialEq)]
319pub struct Options {
320    /// The ordered config sources; later sources override earlier ones.
321    /// Default: the `config` folder under the current working directory.
322    pub sources: Vec<Source>,
323    /// Which formats to read and which extensions each one claims. The
324    /// list carries **no override-order semantics** — it only builds the
325    /// extension→format mapping (if several entries claim the same
326    /// extension, the last entry wins the claim). Override order between
327    /// files is decided by filename alone; see the merge rules in
328    /// README.md.
329    pub formats: Vec<FormatSpec>,
330    /// Scan subdirectories. Default `false`.
331    pub recursive: bool,
332    /// When recursive, ignore subfolder paths instead of turning them
333    /// into nested keys. Default `true` — merge mode flattens; nesting
334    /// by folder structure is tree mode's job (or set `flat: false`).
335    pub flat: bool,
336    /// Treat dotted env/table keys as nested paths: `a.b.c` becomes
337    /// `{ "a": { "b": { "c": … } } }`. Default `true`.
338    pub dot_key: bool,
339    /// Case-sensitive key merging. Default `true`; when `false`, keys are
340    /// normalized to lowercase. (File-extension matching is always
341    /// case-insensitive and unrelated to this option.)
342    pub case_sensitive: bool,
343    /// Load order inside a folder — in merge mode and in tree mode
344    /// (where it decides key collisions like `a.yml` vs a folder `a/`).
345    pub order: Order,
346    /// Tree mode (requires the `tree` feature): instead of merging a
347    /// folder's files into one value, every subfolder becomes a key and
348    /// every file becomes a key named after the file (extension
349    /// stripped), holding that file's parsed content. `a/b.json = {c:1}`
350    /// and `d.json = {a:123}` load as `{a: {b: {c: 1}}, d: {a: 123}}`.
351    /// `recursive`, `flat` and `order` only apply when this is `false`.
352    /// Default `false`.
353    pub tree: bool,
354    /// Tree mode: parse files *without* an extension by running the
355    /// table `auto` detection over the (trimmed) file content — the same
356    /// feature-gated guesses, so `a/blabla` containing `1.1.1.1` becomes
357    /// an IPv4 value when the `ipv4` feature is on, a string otherwise.
358    /// When `false`, extension-less files fall under
359    /// `ignore_unknown_ext`. (Named `auto_files` to keep it apart from
360    /// the table `auto` format id it reuses.) Default `true`.
361    pub auto_files: bool,
362    /// Tree mode: skip files whose extension no active format claims
363    /// (`true`), or error on them (`false`). Default `true`. (In merge
364    /// mode unclaimed files are always skipped.)
365    pub ignore_unknown_ext: bool,
366}
367
368impl Default for Options {
369    fn default() -> Self {
370        Self {
371            sources: vec![Source::Path("config".into())],
372            formats: enabled_formats(),
373            recursive: false,
374            flat: true,
375            dot_key: true,
376            case_sensitive: true,
377            order: Order::default(),
378            tree: false,
379            auto_files: true,
380            ignore_unknown_ext: true,
381        }
382    }
383}
384
385/// Every format compiled into this build with its default extensions.
386/// Later entries win contested extension claims, so `jsonc` (a JSON
387/// superset) takes `.json` over strict `json` when both are enabled.
388#[allow(clippy::vec_init_then_push)] // every push is cfg-gated on its feature
389fn enabled_formats() -> Vec<FormatSpec> {
390    let mut formats = Vec::new();
391    #[cfg(feature = "json")]
392    formats.push(Format::Json.into());
393    #[cfg(feature = "jsonc")]
394    formats.push(Format::Jsonc.into());
395    #[cfg(feature = "yaml")]
396    formats.push(Format::Yaml.into());
397    #[cfg(feature = "toml")]
398    formats.push(Format::Toml.into());
399    #[cfg(feature = "ini")]
400    formats.push(Format::Ini.into());
401    #[cfg(feature = "env")]
402    formats.push(Format::Env.into());
403    #[cfg(feature = "csv")]
404    formats.push(Format::Csv.into());
405    formats
406}