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