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 format: FormatKind,
103    /// Extensions without the leading dot.
104    pub 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<CustomFormat> for FormatSpec {
126    fn from(custom: CustomFormat) -> Self {
127        Self {
128            extensions: custom.extensions.clone(),
129            format: FormatKind::Custom(custom),
130        }
131    }
132}
133
134impl From<&str> for FormatSpec {
135    /// Panics on an unknown format id — this is config-time code.
136    fn from(id: &str) -> Self {
137        Format::from_id(id)
138            .unwrap_or_else(|| panic!("unknown format id: {id:?}"))
139            .into()
140    }
141}
142
143impl<const N: usize> From<(Format, [&str; N])> for FormatSpec {
144    fn from((format, extensions): (Format, [&str; N])) -> Self {
145        format.exts(extensions)
146    }
147}
148
149impl<const N: usize> From<(&str, [&str; N])> for FormatSpec {
150    /// Panics on an unknown format id — this is config-time code.
151    fn from((id, extensions): (&str, [&str; N])) -> Self {
152        Format::from_id(id)
153            .unwrap_or_else(|| panic!("unknown format id: {id:?}"))
154            .exts(extensions)
155    }
156}
157
158/// File load order inside a folder.
159#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
160pub enum Order {
161    /// Subfolders first, then files, each group alphabetic — how directory
162    /// listings are conventionally sorted.
163    #[default]
164    FoldersFirstAlphabetic,
165    /// Pure lexicographic order, folders and files interleaved.
166    Alphabetic,
167    ReverseAlphabetic,
168}
169
170/// Which `type` column values a table (csv) source accepts.
171///
172/// Scalars (`i8`–`u64`, `f32`/`f64`, `bool`, `str`, `auto` and their
173/// aliases) are always allowed; the extended types are opt-in flags.
174#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
175pub struct TableTypes {
176    pub null: bool,
177    pub array: bool,
178    pub json: bool,
179}
180
181impl TableTypes {
182    /// Scalars only — the default.
183    pub fn scalars() -> Self {
184        Self::default()
185    }
186
187    /// Every supported type.
188    pub fn all() -> Self {
189        Self {
190            null: true,
191            array: true,
192            json: true,
193        }
194    }
195}
196
197/// Names of the key / value / format columns of a table source.
198#[derive(Debug, Clone, PartialEq)]
199pub struct TableColumns {
200    pub key: String,
201    pub value: String,
202    /// Name of the format column — the third column holding the value's
203    /// type id.
204    pub format: String,
205}
206
207impl Default for TableColumns {
208    fn default() -> Self {
209        Self {
210            key: "key".into(),
211            value: "value".into(),
212            format: "format".into(),
213        }
214    }
215}
216
217/// Options for table-shaped formats (csv today; spreadsheet formats later).
218#[derive(Debug, Clone, PartialEq)]
219pub struct TableOptions {
220    pub types: TableTypes,
221    /// Delimiter splitting `arr:<type>` value cells.
222    pub delimiter: char,
223    /// Whether the first row is a header. Default `false`: rows are read
224    /// positionally as `key,value[,format]` — the format column may be
225    /// omitted entirely or left empty per row, in which case the value is
226    /// auto-detected. With `header: true` the columns are located by name
227    /// (file column order is free).
228    pub header: bool,
229    /// Column names, matched against the header row (only used when
230    /// `header` is `true`).
231    pub columns: TableColumns,
232}
233
234impl Default for TableOptions {
235    fn default() -> Self {
236        Self {
237            types: TableTypes::scalars(),
238            delimiter: ';',
239            header: false,
240            columns: TableColumns::default(),
241        }
242    }
243}
244
245/// The parser callback of a [`CustomFormat`]: `(text, path, options)`.
246pub(crate) type CustomParser =
247    std::sync::Arc<dyn Fn(&str, &Path, &Options) -> Result<Value> + Send + Sync>;
248
249/// A user-defined format: an id, the extensions it claims, and a parser
250/// callback. It goes into [`Options::formats`] like any built-in format
251/// (`formats: [..the defaults, md.into()]`), so the usual rule applies —
252/// the last claimer of an extension owns it, and a custom format can take
253/// over a built-in extension. Table-shaped custom formats can lower their
254/// file into rows and reuse the generic table stage via [`parse_table`].
255///
256/// A markdown pipe-table as a config format (runs as a doc test — a
257/// string source can name a custom format directly, no files needed):
258///
259/// ```
260/// use c4::{CustomFormat, Loader, Source};
261///
262/// # fn main() -> Result<(), c4::Error> {
263/// let md = CustomFormat::new("md-table", ["md"], |text, path, options| {
264///     let rows: Vec<Vec<String>> = text
265///         .lines()
266///         .map(str::trim)
267///         .filter(|l| l.starts_with('|') && !l.contains("---"))
268///         // markdown tables always start with a header row — dropping
269///         // it here keeps the data rows positional (key,value[,format])
270///         // with no Options.table changes needed
271///         .skip(1)
272///         .map(|l| {
273///             l.trim_matches('|')
274///                 .split('|')
275///                 .map(|cell| cell.trim().to_owned())
276///                 .collect()
277///         })
278///         .collect();
279///     c4::parse_table(rows, path, options)
280/// });
281///
282/// // to read `.md` files instead, push `md` into Options.formats —
283/// // custom formats claim extensions exactly like built-ins do
284/// let value: c4::Value = Loader::new(c4::Options {
285///         sources: vec![Source::string(
286///             md,
287///             "| key  | value | format |
288///              | ---- | ----- | ------ |
289///              | name | c4    | str    |
290///              | port | 8080  | u16    |",
291///         )],
292///         ..c4::Options::default()
293///     })
294///     .load()?;
295/// assert_eq!(value["name"].as_str(), Some("c4"));
296/// assert_eq!(value["port"].as_u64(), Some(8080));
297/// # Ok(())
298/// # }
299/// ```
300#[derive(Clone)]
301pub struct CustomFormat {
302    pub id: String,
303    /// Extensions without the leading dot.
304    pub extensions: Vec<String>,
305    /// `(text, path, options)` — `path` labels errors. Crate-private:
306    /// build custom formats through [`CustomFormat::new`].
307    pub(crate) parser: CustomParser,
308}
309
310impl CustomFormat {
311    pub fn new<I, S, F>(id: impl Into<String>, extensions: I, parser: F) -> Self
312    where
313        I: IntoIterator<Item = S>,
314        S: Into<String>,
315        F: Fn(&str, &Path, &Options) -> Result<Value> + Send + Sync + 'static,
316    {
317        Self {
318            id: id.into(),
319            extensions: extensions.into_iter().map(Into::into).collect(),
320            parser: std::sync::Arc::new(parser),
321        }
322    }
323}
324
325impl std::fmt::Debug for CustomFormat {
326    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
327        f.debug_struct("CustomFormat")
328            .field("id", &self.id)
329            .field("extensions", &self.extensions)
330            .finish_non_exhaustive()
331    }
332}
333
334impl PartialEq for CustomFormat {
335    fn eq(&self, other: &Self) -> bool {
336        self.id == other.id
337            && self.extensions == other.extensions
338            && std::sync::Arc::ptr_eq(&self.parser, &other.parser)
339    }
340}
341
342/// All loader options.
343///
344/// Plain data on purpose: set the fields you care about and take the rest
345/// from `..Options::default()`.
346#[derive(Debug, Clone, PartialEq)]
347pub struct Options {
348    /// The ordered config sources; later sources override earlier ones.
349    /// Default: the `config` folder under the current working directory.
350    pub sources: Vec<Source>,
351    /// Which formats to read and which extensions each one claims. The
352    /// list carries **no override-order semantics** — it only builds the
353    /// extension→format mapping (if several entries claim the same
354    /// extension, the last entry wins the claim). Override order between
355    /// files is decided by filename alone; see the merge rules in
356    /// README.md.
357    pub formats: Vec<FormatSpec>,
358    /// Scan subdirectories. Default `false`.
359    pub recursive: bool,
360    /// When recursive, ignore subfolder paths instead of turning them
361    /// into nested keys. Default `true` — merge mode flattens; nesting
362    /// by folder structure is tree mode's job (or set `flat: false`).
363    pub flat: bool,
364    /// Treat dotted env/table keys as nested paths: `a.b.c` becomes
365    /// `{ "a": { "b": { "c": … } } }`. Default `true`.
366    pub dot_key: bool,
367    /// Case-sensitive key merging. Default `true`; when `false`, keys are
368    /// normalized to lowercase. (File-extension matching is always
369    /// case-insensitive and unrelated to this option.)
370    pub case_sensitive: bool,
371    /// Load order inside a folder — in merge mode and in tree mode
372    /// (where it decides key collisions like `a.yml` vs a folder `a/`).
373    pub order: Order,
374    /// Table-format (csv) options.
375    pub table: TableOptions,
376    /// Tree mode (requires the `tree` feature): instead of merging a
377    /// folder's files into one value, every subfolder becomes a key and
378    /// every file becomes a key named after the file (extension
379    /// stripped), holding that file's parsed content. `a/b.json = {c:1}`
380    /// and `d.json = {a:123}` load as `{a: {b: {c: 1}}, d: {a: 123}}`.
381    /// `recursive`, `flat` and `order` only apply when this is `false`.
382    /// Default `false`.
383    pub tree: bool,
384    /// Tree mode: parse files *without* an extension by running the
385    /// table `auto` detection over the (trimmed) file content — the same
386    /// feature-gated guesses, so `a/blabla` containing `1.1.1.1` becomes
387    /// an IPv4 value when the `ipv4` feature is on, a string otherwise.
388    /// When `false`, extension-less files fall under
389    /// `ignore_unknown_ext`. (Named `auto_files` to keep it apart from
390    /// the table `auto` format id it reuses.) Default `true`.
391    pub auto_files: bool,
392    /// Tree mode: skip files whose extension no active format claims
393    /// (`true`), or error on them (`false`). Default `true`. (In merge
394    /// mode unclaimed files are always skipped.)
395    pub ignore_unknown_ext: bool,
396}
397
398impl Default for Options {
399    fn default() -> Self {
400        Self {
401            sources: vec![Source::folder("config")],
402            formats: enabled_formats(),
403            recursive: false,
404            flat: true,
405            dot_key: true,
406            case_sensitive: true,
407            order: Order::default(),
408            table: TableOptions::default(),
409            tree: false,
410            auto_files: true,
411            ignore_unknown_ext: true,
412        }
413    }
414}
415
416/// Every format compiled into this build with its default extensions.
417/// Later entries win contested extension claims, so `jsonc` (a JSON
418/// superset) takes `.json` over strict `json` when both are enabled.
419#[allow(clippy::vec_init_then_push)] // every push is cfg-gated on its feature
420fn enabled_formats() -> Vec<FormatSpec> {
421    let mut formats = Vec::new();
422    #[cfg(feature = "json")]
423    formats.push(Format::Json.into());
424    #[cfg(feature = "jsonc")]
425    formats.push(Format::Jsonc.into());
426    #[cfg(feature = "yaml")]
427    formats.push(Format::Yaml.into());
428    #[cfg(feature = "toml")]
429    formats.push(Format::Toml.into());
430    #[cfg(feature = "ini")]
431    formats.push(Format::Ini.into());
432    #[cfg(feature = "env")]
433    formats.push(Format::Env.into());
434    #[cfg(feature = "csv")]
435    formats.push(Format::Csv.into());
436    formats
437}