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    /// Excel workbooks (`xlsx`/`xlsm`/`xlsb`/`xls`) — a binary
24    /// table-shaped format; file sources only. Feature `excel`.
25    Excel,
26    /// OpenDocument spreadsheets (`ods`) — a binary table-shaped format;
27    /// file sources only. Feature `ods`.
28    Ods,
29}
30
31impl Format {
32    /// Look a format up by its string id (`"json"`, `"jsonc"`, `"yaml"`,
33    /// `"toml"`, `"ini"`, `"env"`, `"csv"`, `"excel"`, `"ods"`).
34    pub fn from_id(id: &str) -> Option<Format> {
35        Some(match id {
36            "json" => Format::Json,
37            "jsonc" => Format::Jsonc,
38            "yaml" => Format::Yaml,
39            "toml" => Format::Toml,
40            "ini" => Format::Ini,
41            "env" => Format::Env,
42            "csv" => Format::Csv,
43            "excel" => Format::Excel,
44            "ods" => Format::Ods,
45            _ => return None,
46        })
47    }
48
49    /// The string id of this format.
50    pub fn id(self) -> &'static str {
51        match self {
52            Format::Json => "json",
53            Format::Jsonc => "jsonc",
54            Format::Yaml => "yaml",
55            Format::Toml => "toml",
56            Format::Ini => "ini",
57            Format::Env => "env",
58            Format::Csv => "csv",
59            Format::Excel => "excel",
60            Format::Ods => "ods",
61        }
62    }
63
64    /// The extensions (without the dot) this format claims by default.
65    ///
66    /// Extension matching is always case-insensitive, and a hidden file
67    /// named `.X` is treated as having extension `X` (so `.env` matches the
68    /// `env` extension).
69    pub fn default_extensions(self) -> &'static [&'static str] {
70        match self {
71            Format::Json => &["json"],
72            Format::Jsonc => &["json", "jsonc"],
73            Format::Yaml => &["yml", "yaml"],
74            Format::Toml => &["toml"],
75            Format::Ini => &["ini"],
76            Format::Env => &["env"],
77            Format::Csv => &["csv"],
78            Format::Excel => &["xlsx", "xlsm", "xlsb", "xls"],
79            Format::Ods => &["ods"],
80        }
81    }
82
83    /// The default [`TableLayout`] of this format: `db` for the
84    /// spreadsheet formats (excel/ods — a sheet is a record grid unless
85    /// told otherwise), `kv` for csv (and, vacuously, for the non-table
86    /// formats, which never consult a layout).
87    pub fn default_layout(self) -> TableLayout {
88        match self {
89            Format::Excel | Format::Ods => TableLayout::Db,
90            _ => TableLayout::Kv,
91        }
92    }
93
94    /// Pair this format with custom extensions.
95    pub fn exts<I, S>(self, extensions: I) -> FormatSpec
96    where
97        I: IntoIterator<Item = S>,
98        S: Into<String>,
99    {
100        FormatSpec {
101            format: FormatKind::Builtin(self),
102            extensions: extensions.into_iter().map(Into::into).collect(),
103            layout: self.default_layout(),
104        }
105    }
106}
107
108/// What a [`FormatSpec`] entry parses with: a built-in format or a
109/// user-defined [`CustomFormat`].
110#[derive(Debug, Clone, PartialEq)]
111pub enum FormatKind {
112    Builtin(Format),
113    Custom(CustomFormat),
114}
115
116/// A format plus the extensions it reads — one entry of [`Options::formats`].
117///
118/// Accepted forms (all `.into()`):
119/// - `Format::Yaml` or `"yaml"` — default extensions
120/// - `(Format::Yaml, ["yml", "conf"])` or `("yaml", ["yml", "conf"])` —
121///   custom extensions
122/// - `(Format::Csv, ["csv"], "db")` — custom extensions **plus a
123///   [`TableLayout`]** (a layout id string, a `TableLayout`, or a
124///   [`CustomLayout`]): every file this entry claims parses under that
125///   layout, in merge mode, tree mode and single-file path sources
126///   alike. Table sources override it; string sources stay `Kv`; a
127///   layout on a non-table format panics at conversion. Without this
128///   form an entry uses the format's default layout
129///   ([`Format::default_layout`]).
130/// - a [`CustomFormat`] — user-defined parser with the extensions it was
131///   built with
132#[derive(Debug, Clone, PartialEq)]
133pub struct FormatSpec {
134    pub(crate) format: FormatKind,
135    /// Extensions without the leading dot.
136    pub(crate) extensions: Vec<String>,
137    /// The table layout for files this entry claims (table formats only).
138    pub(crate) layout: TableLayout,
139}
140
141impl From<Format> for FormatSpec {
142    fn from(format: Format) -> Self {
143        format.exts(format.default_extensions().iter().copied())
144    }
145}
146
147impl From<Format> for FormatKind {
148    fn from(format: Format) -> Self {
149        FormatKind::Builtin(format)
150    }
151}
152
153impl From<CustomFormat> for FormatKind {
154    fn from(custom: CustomFormat) -> Self {
155        FormatKind::Custom(custom)
156    }
157}
158
159impl From<&str> for FormatKind {
160    /// A built-in format id (`"jsonc"`, `"yaml"`, …). Panics on an unknown
161    /// id — this is config-time code. Lets a `(id, text)` string source
162    /// name its format by string.
163    fn from(id: &str) -> Self {
164        FormatKind::Builtin(
165            Format::from_id(id).unwrap_or_else(|| panic!("unknown format id: {id:?}")),
166        )
167    }
168}
169
170impl From<CustomFormat> for FormatSpec {
171    fn from(custom: CustomFormat) -> Self {
172        Self {
173            extensions: custom.extensions.clone(),
174            format: FormatKind::Custom(custom),
175            layout: TableLayout::Kv,
176        }
177    }
178}
179
180impl From<&str> for FormatSpec {
181    /// Panics on an unknown format id — this is config-time code.
182    fn from(id: &str) -> Self {
183        Format::from_id(id)
184            .unwrap_or_else(|| panic!("unknown format id: {id:?}"))
185            .into()
186    }
187}
188
189impl<const N: usize> From<(Format, [&str; N])> for FormatSpec {
190    fn from((format, extensions): (Format, [&str; N])) -> Self {
191        format.exts(extensions)
192    }
193}
194
195impl<const N: usize> From<(&str, [&str; N])> for FormatSpec {
196    /// Panics on an unknown format id — this is config-time code.
197    fn from((id, extensions): (&str, [&str; N])) -> Self {
198        Format::from_id(id)
199            .unwrap_or_else(|| panic!("unknown format id: {id:?}"))
200            .exts(extensions)
201    }
202}
203
204/// In a `formats` entry the third element is always a **layout** (a
205/// string must be a valid layout id — extensions have no sheet meaning).
206/// Panics on unknown ids, and on a layout for a non-table format
207/// (`(Format::Yaml, ["yml"], "db")`) — this is config-time code.
208impl<const N: usize, L: Into<TableLayout>> From<(Format, [&str; N], L)> for FormatSpec {
209    fn from((format, extensions, layout): (Format, [&str; N], L)) -> Self {
210        assert!(
211            matches!(format, Format::Csv | Format::Excel | Format::Ods),
212            "'{}' is not a table format (csv, excel, ods) — table layouts do not apply",
213            format.id()
214        );
215        FormatSpec {
216            layout: layout.into(),
217            ..format.exts(extensions)
218        }
219    }
220}
221
222/// Panics on an unknown format or layout id — this is config-time code.
223impl<const N: usize, L: Into<TableLayout>> From<(&str, [&str; N], L)> for FormatSpec {
224    fn from((id, extensions, layout): (&str, [&str; N], L)) -> Self {
225        let format = Format::from_id(id).unwrap_or_else(|| panic!("unknown format id: {id:?}"));
226        (format, extensions, layout).into()
227    }
228}
229
230/// File load order inside a folder.
231#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
232pub enum Order {
233    /// Subfolders first, then files, each group alphabetic — how directory
234    /// listings are conventionally sorted.
235    #[default]
236    FoldersFirstAlphabetic,
237    /// Pure lexicographic order, folders and files interleaved.
238    Alphabetic,
239    ReverseAlphabetic,
240}
241
242impl Order {
243    /// Look an order up by its string id. Accepts `-` or `_` between words
244    /// and a couple of short aliases:
245    /// `folders_first_alphabetic` (`folders_first`, `default`),
246    /// `alphabetic`, `reverse_alphabetic` (`reverse`).
247    pub fn from_id(id: &str) -> Option<Order> {
248        Some(match id.to_lowercase().replace('-', "_").as_str() {
249            "folders_first_alphabetic" | "folders_first" | "default" => {
250                Order::FoldersFirstAlphabetic
251            }
252            "alphabetic" => Order::Alphabetic,
253            "reverse_alphabetic" | "reverse" => Order::ReverseAlphabetic,
254            _ => return None,
255        })
256    }
257
258    /// The canonical string id of this order.
259    pub fn id(self) -> &'static str {
260        match self {
261            Order::FoldersFirstAlphabetic => "folders_first_alphabetic",
262            Order::Alphabetic => "alphabetic",
263            Order::ReverseAlphabetic => "reverse_alphabetic",
264        }
265    }
266}
267
268impl From<&str> for Order {
269    /// Panics on an unknown id — this is config-time code. See
270    /// [`Order::from_id`] for the accepted spellings.
271    fn from(id: &str) -> Self {
272        Order::from_id(id).unwrap_or_else(|| panic!("unknown order id: {id:?}"))
273    }
274}
275
276/// How the table stage interprets a row grid. Chosen per table source
277/// (`(format, path, layout)` / `(format, path, sheet, layout)` tuples),
278/// per `formats` entry (`(format, [exts], layout)`), or passed
279/// explicitly to [`parse_table`](crate::parse_table); everything else
280/// uses the format's default —
281/// [`Format::default_layout`](crate::Format::default_layout): `kv` for
282/// csv, `db` for excel/ods. Converts from a layout id string
283/// (`"kv"`/`"kvf"`, `"db"`) or a [`CustomLayout`].
284#[derive(Debug, Clone, PartialEq, Default)]
285pub enum TableLayout {
286    /// `key,value[,format]` positional rows — one config entry per row.
287    /// The default for csv.
288    #[default]
289    Kv,
290    /// A database-style grid: the first (non-blank) row holds the keys,
291    /// the second **always** the type ids (an empty cell = `auto`), every
292    /// following row is one record. Parses to an **array** of one object
293    /// per record: `[[a,b],[i8,str],[4,x],[5,y]]` →
294    /// `[{a:4,b:"x"},{a:5,b:"y"}]`. Empty cells are omitted from their
295    /// record (sparse tables give sparse objects). The default for the
296    /// spreadsheet formats (excel/ods). A grid *without* a
297    /// type row is a [`CustomLayout`] that inserts a row of `auto` cells
298    /// after the header and delegates back to `Db` (see the
299    /// `xlsx-sheets` example).
300    Db,
301    /// A user callback over the raw rows — see [`CustomLayout`].
302    Custom(CustomLayout),
303}
304
305impl TableLayout {
306    /// Look a layout up by its string id: `kv` (alias `kvf`) or `db`.
307    pub fn from_id(id: &str) -> Option<TableLayout> {
308        Some(match id.to_lowercase().as_str() {
309            "kv" | "kvf" => TableLayout::Kv,
310            "db" => TableLayout::Db,
311            _ => return None,
312        })
313    }
314
315    /// The string id of this layout (a custom layout reports its own id).
316    pub fn id(&self) -> &str {
317        match self {
318            TableLayout::Kv => "kv",
319            TableLayout::Db => "db",
320            TableLayout::Custom(custom) => &custom.id,
321        }
322    }
323}
324
325impl From<&str> for TableLayout {
326    /// Panics on an unknown id — this is config-time code. See
327    /// [`TableLayout::from_id`] for the accepted spellings.
328    fn from(id: &str) -> Self {
329        TableLayout::from_id(id).unwrap_or_else(|| {
330            panic!("unknown table layout id: {id:?} (valid: kv, db, or a CustomLayout)")
331        })
332    }
333}
334
335impl From<CustomLayout> for TableLayout {
336    fn from(custom: CustomLayout) -> Self {
337        TableLayout::Custom(custom)
338    }
339}
340
341/// The parser callback of a [`CustomLayout`]: `(rows, path, options)`.
342pub(crate) type CustomRowsParser =
343    std::sync::Arc<dyn Fn(Vec<Vec<String>>, &Path, &Options) -> Result<Value> + Send + Sync>;
344
345/// A user-defined table layout: an id and a callback that receives the
346/// lowered rows (`Vec<Vec<String>>` — csv records, or a sheet's cells as
347/// text) and returns any [`Value`]. This is the rows-level escape hatch:
348/// binary formats (spreadsheets) can't go through a [`CustomFormat`]
349/// (which parses text), but one sheet of a workbook can still get fully
350/// custom treatment via
351/// `(Format::Excel, path, sheet, CustomLayout::new(…)).into()`. Most
352/// custom layouts end by reshaping the rows and calling
353/// [`parse_table`](crate::parse_table) (the `xlsx-sheets` example
354/// transposes a column-oriented sheet this way).
355#[derive(Clone)]
356pub struct CustomLayout {
357    pub(crate) id: String,
358    /// `(rows, path, options)` — `path` labels errors. Crate-private:
359    /// build custom layouts through [`CustomLayout::new`].
360    pub(crate) parser: CustomRowsParser,
361}
362
363impl CustomLayout {
364    pub fn new<F>(id: impl Into<String>, parser: F) -> Self
365    where
366        F: Fn(Vec<Vec<String>>, &Path, &Options) -> Result<Value> + Send + Sync + 'static,
367    {
368        Self {
369            id: id.into(),
370            parser: std::sync::Arc::new(parser),
371        }
372    }
373}
374
375impl std::fmt::Debug for CustomLayout {
376    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
377        f.debug_struct("CustomLayout")
378            .field("id", &self.id)
379            .finish_non_exhaustive()
380    }
381}
382
383impl PartialEq for CustomLayout {
384    fn eq(&self, other: &Self) -> bool {
385        self.id == other.id && std::sync::Arc::ptr_eq(&self.parser, &other.parser)
386    }
387}
388
389/// The parser callback of a [`CustomFormat`]: `(text, path, options)`.
390pub(crate) type CustomParser =
391    std::sync::Arc<dyn Fn(&str, &Path, &Options) -> Result<Value> + Send + Sync>;
392
393/// A user-defined format: an id, the extensions it claims, and a parser
394/// callback. It goes into [`Options::formats`] like any built-in format
395/// (`formats: [..the defaults, md.into()]`), so the usual rule applies —
396/// the last claimer of an extension owns it, and a custom format can take
397/// over a built-in extension. Table-shaped custom formats can lower their
398/// file into rows and reuse the generic table stage via
399/// [`parse_table`](crate::parse_table).
400///
401/// A markdown pipe-table as a config format (runs as a doc test — a
402/// string source can name a custom format directly, no files needed):
403///
404/// ```
405/// use c4::{CustomFormat, Loader};
406///
407/// # fn main() -> Result<(), c4::Error> {
408/// let md = CustomFormat::new("md-table", ["md"], |text, path, options| {
409///     let rows: Vec<Vec<String>> = text
410///         .lines()
411///         .map(str::trim)
412///         .filter(|l| l.starts_with('|') && !l.contains("---"))
413///         // markdown tables always start with a header row — dropping
414///         // it here keeps the data rows positional (key,value[,format]),
415///         // exactly what parse_table expects
416///         .skip(1)
417///         .map(|l| {
418///             l.trim_matches('|')
419///                 .split('|')
420///                 .map(|cell| cell.trim().to_owned())
421///                 .collect()
422///         })
423///         .collect();
424///     c4::parse_table(rows, &c4::TableLayout::Kv, path, options)
425/// });
426///
427/// // to read `.md` files instead, push `md` into Options.formats —
428/// // custom formats claim extensions exactly like built-ins do
429/// let value: c4::Value = Loader::new(c4::Options {
430///         sources: vec![(
431///             md,
432///             "| key  | value | format |
433///              | ---- | ----- | ------ |
434///              | name | c4    | str    |
435///              | port | 8080  | u16    |",
436///         )
437///             .into()],
438///         ..c4::Options::default()
439///     })
440///     .load()?;
441/// assert_eq!(value["name"].as_str(), Some("c4"));
442/// assert_eq!(value["port"].as_u64(), Some(8080));
443/// # Ok(())
444/// # }
445/// ```
446#[derive(Clone)]
447pub struct CustomFormat {
448    pub(crate) id: String,
449    /// Extensions without the leading dot.
450    pub(crate) extensions: Vec<String>,
451    /// `(text, path, options)` — `path` labels errors. Crate-private:
452    /// build custom formats through [`CustomFormat::new`].
453    pub(crate) parser: CustomParser,
454}
455
456impl CustomFormat {
457    pub fn new<I, S, F>(id: impl Into<String>, extensions: I, parser: F) -> Self
458    where
459        I: IntoIterator<Item = S>,
460        S: Into<String>,
461        F: Fn(&str, &Path, &Options) -> Result<Value> + Send + Sync + 'static,
462    {
463        Self {
464            id: id.into(),
465            extensions: extensions.into_iter().map(Into::into).collect(),
466            parser: std::sync::Arc::new(parser),
467        }
468    }
469}
470
471impl std::fmt::Debug for CustomFormat {
472    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
473        f.debug_struct("CustomFormat")
474            .field("id", &self.id)
475            .field("extensions", &self.extensions)
476            .finish_non_exhaustive()
477    }
478}
479
480impl PartialEq for CustomFormat {
481    fn eq(&self, other: &Self) -> bool {
482        self.id == other.id
483            && self.extensions == other.extensions
484            && std::sync::Arc::ptr_eq(&self.parser, &other.parser)
485    }
486}
487
488/// All loader options.
489///
490/// Plain data on purpose: set the fields you care about and take the rest
491/// from `..Options::default()`.
492#[derive(Debug, Clone, PartialEq)]
493pub struct Options {
494    /// The ordered config sources; later sources override earlier ones.
495    /// Default: the `config` folder under the current working directory.
496    /// Every element converts with `.into()` — see [`Source`] for all
497    /// the accepted shapes.
498    ///
499    /// ```no_run
500    /// # fn main() -> Result<(), c4::Error> {
501    /// let value: c4::Value = c4::Loader::new(c4::Options {
502    ///         sources: vec![
503    ///             "./config".into(),              // a folder …
504    ///             "./local.yml".into(),           // … or a single file
505    ///             ("yaml", "debug: true").into(), // in-code text
506    ///             (std::collections::BTreeMap::from([("port", 8080)]),).into(),
507    ///         ],
508    ///         ..c4::Options::default()
509    ///     })
510    ///     .load()?;
511    /// # Ok(())
512    /// # }
513    /// ```
514    pub sources: Vec<Source>,
515    /// Which formats to read and which extensions each one claims. The
516    /// list carries **no override-order semantics** — it only builds the
517    /// extension→format mapping (if several entries claim the same
518    /// extension, the last entry wins the claim). Override order between
519    /// files is decided by filename alone; see the merge rules in
520    /// README.md. Entry forms are on [`FormatSpec`].
521    ///
522    /// ```
523    /// let options = c4::Options {
524    ///     formats: vec![
525    ///         "jsonc".into(),                                     // default extensions
526    ///         (c4::Format::Yaml, ["yml", "yaml", "conf"]).into(), // custom extensions
527    ///         (c4::Format::Csv, ["csv"], "db").into(),            // + a table layout
528    ///     ],
529    ///     ..c4::Options::default()
530    /// };
531    /// assert_eq!(options.formats.len(), 3);
532    /// ```
533    pub formats: Vec<FormatSpec>,
534    /// **Folder sources.** How many subdirectory levels below the source
535    /// folder to scan. `1` (default): the source folder's own files and
536    /// one level of subfolders — `config/*` and `config/a/*`, but not
537    /// `config/a/b/*`. `0`: only the source folder's own files. `-1`:
538    /// unlimited (fully recursive). Whether the folders that are scanned
539    /// contribute their names as keys is [`dirname_as_key`](Options::dirname_as_key).
540    /// (The `tree` feature changes this field's default to `-1` — see the
541    /// feature.)
542    ///
543    /// ```no_run
544    /// # fn main() -> Result<(), c4::Error> {
545    /// // config/*, config/a/* and config/a/b/* all merge in
546    /// let value: c4::Value = c4::Loader::new(c4::Options {
547    ///         dir_depth: -1, // fully recursive
548    ///         ..c4::Options::default()
549    ///     })
550    ///     .load()?;
551    /// # Ok(())
552    /// # }
553    /// ```
554    pub dir_depth: isize,
555    /// **Folder sources.** When `true`, each **file** becomes a key named
556    /// after the file with its extension stripped, holding that file's
557    /// parsed content, instead of merging into the parent — `a.json =
558    /// {"c": 1}` loads as `{a: {c: 1}}`. Default `false` (the `tree`
559    /// feature changes this default to `true` — see the feature). Combine
560    /// with [`dirname_as_key`](Options::dirname_as_key) and `dir_depth:
561    /// -1` for a full folder-shaped tree. A dotfile whose whole name is
562    /// its extension (`.env`) keeps the full name as its key.
563    ///
564    /// This is also the switch that decides how *extension-less* and
565    /// *unknown-extension* files are handled (see
566    /// [`auto_no_ext_files`](Options::auto_no_ext_files) and
567    /// [`ignore_unknown_ext`](Options::ignore_unknown_ext)): those only
568    /// apply when a file would become a key. Otherwise such files are
569    /// skipped (they have no key to contribute under).
570    ///
571    /// ```no_run
572    /// # fn main() -> Result<(), c4::Error> {
573    /// // config/a.json = {"c": 1}  ->  {a: {c: 1}}
574    /// let value: c4::Value = c4::Loader::new(c4::Options {
575    ///         filename_as_key: true,
576    ///         ..c4::Options::default()
577    ///     })
578    ///     .load()?;
579    /// assert_eq!(value["a"]["c"].as_i64(), Some(1));
580    /// # Ok(())
581    /// # }
582    /// ```
583    pub filename_as_key: bool,
584    /// **Folder sources.** When `true`, each **subfolder** becomes a key
585    /// and everything under it merges below that key — `db/a.json =
586    /// {"host": "x"}` loads as `{db: {host: "x"}}`. Default `false` (the
587    /// `tree` feature changes this default to `true` — see the feature).
588    /// Honors [`dir_depth`](Options::dir_depth): only folders actually
589    /// scanned become keys.
590    ///
591    /// ```no_run
592    /// # fn main() -> Result<(), c4::Error> {
593    /// // config/db/a.json = {"host": "x"} — the subfolder becomes a key
594    /// let value: c4::Value = c4::Loader::new(c4::Options {
595    ///         dirname_as_key: true,
596    ///         ..c4::Options::default()
597    ///     })
598    ///     .load()?;
599    /// assert_eq!(value["db"]["host"].as_str(), Some("x"));
600    /// # Ok(())
601    /// # }
602    /// ```
603    pub dirname_as_key: bool,
604    /// **All modes; env and table formats.** Treat dotted keys as nested
605    /// paths: `a.b.c` becomes `{ "a": { "b": { "c": … } } }`.
606    /// Default `true`.
607    ///
608    /// In the table stage this applies to both layouts: the `kv`
609    /// layout's key column, and the `db` layout's key row (a dotted
610    /// column nests inside each record).
611    ///
612    /// A key segment may also end in **array suffixes** — `[]` (append)
613    /// and `[<int>]` (index) groups, chained for nested arrays
614    /// (`grid[0][1]`, one level per group); any other bracket shape
615    /// (`a[x]`, `a[-1]`, `a[]b`, a bare `[]`) keeps the whole segment a
616    /// literal key:
617    ///
618    /// - `name[]` **appends** one new element per occurrence: per kv
619    ///   row / env line, and per record for a db column.
620    /// - `name[<int>]` addresses element `<int>`: the same index
621    ///   deep-merges into one element and indexes may arrive in any
622    ///   order. Skipped indexes leave `Null` gaps — `a[1]` + `a[4]`
623    ///   give a five-element array with nulls at 0, 2 and 3;
624    ///   deserialize such arrays as `Vec<Option<T>>`.
625    ///
626    /// Suffixes also chain through the dotted path (`a[0].b[].c`) and
627    /// work on keys without dots (`ports[]`). The expansion happens
628    /// within one parse (one file/sheet/string source) — across sources
629    /// arrays still replace like any array. The `dot-key` example tours
630    /// all of it.
631    ///
632    /// ```
633    /// use std::path::Path;
634    ///
635    /// use c4::{Options, TableLayout};
636    ///
637    /// # fn main() -> Result<(), c4::Error> {
638    /// let options = Options::default(); // dot_key: true
639    ///
640    /// // kv layout: the key column nests
641    /// let rows = vec![vec!["a.b".to_string(), "1".to_string()]];
642    /// let value = c4::parse_table(rows, &TableLayout::Kv, Path::new("doc"), &options)?;
643    /// assert_eq!(value["a"]["b"].as_i64(), Some(1));
644    ///
645    /// // db layout: dotted keys nest inside each record
646    /// let rows = vec![
647    ///     vec!["a.b".to_string(), "a.c".to_string()], // key row
648    ///     vec![String::new(), String::new()],         // type row (all auto)
649    ///     vec!["1".to_string(), "2".to_string()],     // one record
650    /// ];
651    /// let value = c4::parse_table(rows, &TableLayout::Db, Path::new("doc"), &options)?;
652    /// assert_eq!(value[0]["a"]["b"].as_i64(), Some(1));
653    /// assert_eq!(value[0]["a"]["c"].as_i64(), Some(2));
654    ///
655    /// // array suffixes: `[]` appends per row, `[<int>]` indexes
656    /// let rows = vec![
657    ///     vec!["tags[]".to_string(), "red".to_string()],
658    ///     vec!["tags[]".to_string(), "blue".to_string()],
659    ///     vec!["servers[1].host".to_string(), "beta".to_string()],
660    ///     vec!["servers[0].host".to_string(), "alpha".to_string()],
661    /// ];
662    /// let value = c4::parse_table(rows, &TableLayout::Kv, Path::new("doc"), &options)?;
663    /// assert_eq!(value["tags"][1].as_str(), Some("blue"));
664    /// assert_eq!(value["servers"][0]["host"].as_str(), Some("alpha"));
665    ///
666    /// // chained suffixes nest; skipped indexes leave null gaps
667    /// let rows = vec![vec!["m[1][0]".to_string(), "9".to_string()]];
668    /// let value = c4::parse_table(rows, &TableLayout::Kv, Path::new("doc"), &options)?;
669    /// assert!(value["m"][0].is_null());
670    /// assert_eq!(value["m"][1][0].as_i64(), Some(9));
671    /// # Ok(())
672    /// # }
673    /// ```
674    pub dot_key: bool,
675    /// **All modes.** Case-sensitive key merging. Default `true`; when
676    /// `false`, keys are normalized to lowercase. (File-extension
677    /// matching is always case-insensitive and unrelated to this
678    /// option.)
679    ///
680    /// ```
681    /// use std::collections::BTreeMap;
682    ///
683    /// # fn main() -> Result<(), c4::Error> {
684    /// let value: c4::Value = c4::Loader::new(c4::Options {
685    ///         sources: vec![
686    ///             (BTreeMap::from([("PORT", 1)]),).into(),
687    ///             (BTreeMap::from([("port", 8080)]),).into(),
688    ///         ],
689    ///         case_sensitive: false, // "PORT" and "port" are one key
690    ///         ..c4::Options::default()
691    ///     })
692    ///     .load()?;
693    /// assert_eq!(value["port"].as_i64(), Some(8080));
694    /// # Ok(())
695    /// # }
696    /// ```
697    pub case_sensitive: bool,
698    /// **All modes**; folder sources. Load order inside a folder. In
699    /// merge mode it decides which file overrides which; in tree mode it
700    /// decides key collisions (`a.yml` vs a folder `a/`).
701    ///
702    /// ```no_run
703    /// # fn main() -> Result<(), c4::Error> {
704    /// let value: c4::Value = c4::Loader::new(c4::Options {
705    ///         order: "alphabetic".into(), // or c4::Order::Alphabetic
706    ///         ..c4::Options::default()
707    ///     })
708    ///     .load()?;
709    /// # Ok(())
710    /// # }
711    /// ```
712    pub order: Order,
713    /// **Spreadsheet formats (excel/ods) only.** Treats each sheet of a
714    /// workbook like a file. When `true`, a workbook parses to an object
715    /// keyed by sheet name (every sheet left after the ignore filters
716    /// becomes a key) — the sheet analogue of
717    /// [`filename_as_key`](Options::filename_as_key). When `false`
718    /// (default), every non-ignored sheet still parses, but they all
719    /// **deep-merge** into one value (like several files in a folder), in
720    /// [`order`](Options::order) applied to the sheet names — so later
721    /// sheets override earlier ones. Default `false` (the `tree` feature
722    /// changes this default to `true` — see the feature). (A table source
723    /// that names a sheet explicitly is unaffected — it always reads
724    /// exactly that sheet.)
725    ///
726    /// ```no_run
727    /// # fn main() -> Result<(), c4::Error> {
728    /// // game.xlsx has sheets "items" and "monsters" — each becomes a key
729    /// let value: c4::Value = c4::Loader::new(c4::Options {
730    ///         sources: vec!["./game.xlsx".into()],
731    ///         sheetname_as_key: true,
732    ///         ..c4::Options::default()
733    ///     })
734    ///     .load()?;
735    /// assert!(!value["items"].is_null());
736    /// # Ok(())
737    /// # }
738    /// ```
739    pub sheetname_as_key: bool,
740    /// **Only when [`filename_as_key`](Options::filename_as_key) is true**
741    /// (files become keys); folder sources. What to do with a file that
742    /// has *no* extension. `true` (default): read it and guess the type of
743    /// its (trimmed) content with the table `auto` rules — a file
744    /// containing `1.1.1.1` becomes an IPv4 value when the `ipv4` feature
745    /// is on, a string otherwise. `false`: treat it like a file with an
746    /// unknown extension (see
747    /// [`ignore_unknown_ext`](Options::ignore_unknown_ext)). (Named
748    /// `auto_no_ext_files` after the table `auto` type id it reuses.)
749    /// Without `filename_as_key` an extension-less file has no key to
750    /// contribute under and is skipped regardless.
751    ///
752    /// ```no_run
753    /// # fn main() -> Result<(), c4::Error> {
754    /// // config/host is an extension-less file holding "1.1.1.1"
755    /// let value: c4::Value = c4::Loader::new(c4::Options {
756    ///         filename_as_key: true,
757    ///         auto_no_ext_files: true,
758    ///         ..c4::Options::default()
759    ///     })
760    ///     .load()?;
761    /// assert!(!value["host"].is_null());
762    /// # Ok(())
763    /// # }
764    /// ```
765    pub auto_no_ext_files: bool,
766    /// **Only when [`filename_as_key`](Options::filename_as_key) is true**
767    /// (files become keys); folder sources. What to do with a file whose
768    /// extension no active format claims: skip it (`true`, default) or
769    /// fail the load with `Error::Parse` (`false`). Without
770    /// `filename_as_key` such files are always skipped.
771    ///
772    /// ```no_run
773    /// # fn main() -> Result<(), c4::Error> {
774    /// let value: c4::Value = c4::Loader::new(c4::Options {
775    ///         filename_as_key: true,
776    ///         ignore_unknown_ext: false, // a config/*.xyz file now errors
777    ///         ..c4::Options::default()
778    ///     })
779    ///     .load()?;
780    /// # Ok(())
781    /// # }
782    /// ```
783    pub ignore_unknown_ext: bool,
784    /// **Spreadsheet formats (excel/ods) only.** Skip sheets whose name
785    /// starts with `#`, `.` or `_` — draft/scratch space next to live
786    /// config, read like a "commented-out" sheet. Default `true`. (A
787    /// table source that names a sheet explicitly bypasses this filter, so
788    /// a prefixed sheet stays loadable on purpose.)
789    ///
790    /// ```no_run
791    /// # fn main() -> Result<(), c4::Error> {
792    /// // game.xlsx has sheets "items" and "_draft"; by default "_draft"
793    /// // is skipped — false reads it as a key too
794    /// let value: c4::Value = c4::Loader::new(c4::Options {
795    ///         sources: vec!["./game.xlsx".into()],
796    ///         sheetname_as_key: true,
797    ///         ignore_commented_sheets: false,
798    ///         ..c4::Options::default()
799    ///     })
800    ///     .load()?;
801    /// assert!(!value["_draft"].is_null());
802    /// # Ok(())
803    /// # }
804    /// ```
805    pub ignore_commented_sheets: bool,
806    /// **Spreadsheet formats (excel/ods) only.** Skip sheets marked
807    /// hidden in the workbook (Excel `hidden`/`veryHidden`, OpenDocument
808    /// `table:display="false"`). Default `true`. (A table source that
809    /// names a sheet explicitly bypasses this filter.)
810    ///
811    /// ```no_run
812    /// # fn main() -> Result<(), c4::Error> {
813    /// // the workbook's `config` sheet is marked hidden — read it anyway
814    /// let value: c4::Value = c4::Loader::new(c4::Options {
815    ///         sources: vec!["./game.xlsx".into()],
816    ///         ignore_hidden_sheets: false,
817    ///         ..c4::Options::default()
818    ///     })
819    ///     .load()?;
820    /// # Ok(())
821    /// # }
822    /// ```
823    pub ignore_hidden_sheets: bool,
824}
825
826impl Default for Options {
827    fn default() -> Self {
828        Self {
829            sources: vec![Source::Path("config".into())],
830            formats: enabled_formats(),
831            // The `tree` feature is a default-preset, not a capability: it
832            // flips the folder/file/sheet keying on and scans every depth.
833            // The keying fields themselves work on any build; enabling
834            // `tree` just makes tree-shaped loading the default.
835            dir_depth: if cfg!(feature = "tree") { -1 } else { 1 },
836            filename_as_key: cfg!(feature = "tree"),
837            dirname_as_key: cfg!(feature = "tree"),
838            sheetname_as_key: cfg!(feature = "tree"),
839            dot_key: true,
840            case_sensitive: true,
841            order: Order::default(),
842            auto_no_ext_files: true,
843            ignore_unknown_ext: true,
844            ignore_commented_sheets: true,
845            ignore_hidden_sheets: true,
846        }
847    }
848}
849
850/// Every format compiled into this build with its default extensions.
851/// Later entries win contested extension claims, so `jsonc` (a JSON
852/// superset) takes `.json` over strict `json` when both are enabled.
853#[allow(clippy::vec_init_then_push)] // every push is cfg-gated on its feature
854fn enabled_formats() -> Vec<FormatSpec> {
855    let mut formats = Vec::new();
856    #[cfg(feature = "json")]
857    formats.push(Format::Json.into());
858    #[cfg(feature = "jsonc")]
859    formats.push(Format::Jsonc.into());
860    #[cfg(feature = "yaml")]
861    formats.push(Format::Yaml.into());
862    #[cfg(feature = "toml")]
863    formats.push(Format::Toml.into());
864    #[cfg(feature = "ini")]
865    formats.push(Format::Ini.into());
866    #[cfg(feature = "env")]
867    formats.push(Format::Env.into());
868    #[cfg(feature = "csv")]
869    formats.push(Format::Csv.into());
870    #[cfg(feature = "excel")]
871    formats.push(Format::Excel.into());
872    #[cfg(feature = "ods")]
873    formats.push(Format::Ods.into());
874    formats
875}