c4-config 0.5.0

Load a folder of config files (jsonc/yaml/json/toml/ini/env/csv/xlsx/ods) into one deep-merged value
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
//! The plain-data configuration surface: [`Options`] and every type its
//! fields are made of — formats and their specs (built-in and custom),
//! folder order, and the table options.

use std::path::Path;

use crate::{Result, Source, Value};

/// The characters that mark a name or key as "commented out" — the one
/// set behind [`Options::ignore_commented_data_keys`],
/// [`ignore_commented_filenames`](Options::ignore_commented_filenames),
/// [`ignore_commented_dirnames`](Options::ignore_commented_dirnames) and
/// [`ignore_commented_sheetnames`](Options::ignore_commented_sheetnames).
/// `.` is deliberately not one of them, so dotfiles (`.env`) and dotted
/// sheet names stay ordinary.
pub(crate) const COMMENT_PREFIXES: [char; 2] = ['#', '_'];

/// Whether a name or key reads as commented out (see
/// [`COMMENT_PREFIXES`]).
pub(crate) fn is_commented(name: &str) -> bool {
    name.starts_with(COMMENT_PREFIXES)
}

/// A config file format.
///
/// The variants always exist; whether a format can actually be parsed
/// depends on the matching Cargo feature. Which extensions a format reads
/// is part of [`FormatSpec`].
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum Format {
    Json,
    Jsonc,
    Yaml,
    Toml,
    Ini,
    Env,
    Csv,
    /// Excel workbooks (`xlsx`/`xlsm`/`xlsb`/`xls`) — a binary
    /// table-shaped format; file sources only. Feature `excel`.
    Excel,
    /// OpenDocument spreadsheets (`ods`) — a binary table-shaped format;
    /// file sources only. Feature `ods`.
    Ods,
}

impl Format {
    /// Look a format up by its string id (`"json"`, `"jsonc"`, `"yaml"`,
    /// `"toml"`, `"ini"`, `"env"`, `"csv"`, `"excel"`, `"ods"`).
    pub fn from_id(id: &str) -> Option<Format> {
        Some(match id {
            "json" => Format::Json,
            "jsonc" => Format::Jsonc,
            "yaml" => Format::Yaml,
            "toml" => Format::Toml,
            "ini" => Format::Ini,
            "env" => Format::Env,
            "csv" => Format::Csv,
            "excel" => Format::Excel,
            "ods" => Format::Ods,
            _ => return None,
        })
    }

    /// The string id of this format.
    pub fn id(self) -> &'static str {
        match self {
            Format::Json => "json",
            Format::Jsonc => "jsonc",
            Format::Yaml => "yaml",
            Format::Toml => "toml",
            Format::Ini => "ini",
            Format::Env => "env",
            Format::Csv => "csv",
            Format::Excel => "excel",
            Format::Ods => "ods",
        }
    }

    /// The extensions (without the dot) this format claims by default.
    ///
    /// Extension matching is always case-insensitive, and a hidden file
    /// named `.X` is treated as having extension `X` (so `.env` matches the
    /// `env` extension).
    pub fn default_extensions(self) -> &'static [&'static str] {
        match self {
            Format::Json => &["json"],
            Format::Jsonc => &["json", "jsonc"],
            Format::Yaml => &["yml", "yaml"],
            Format::Toml => &["toml"],
            Format::Ini => &["ini"],
            Format::Env => &["env"],
            Format::Csv => &["csv"],
            Format::Excel => &["xlsx", "xlsm", "xlsb", "xls"],
            Format::Ods => &["ods"],
        }
    }

    /// The default [`TableLayout`] of this format: `db` for the
    /// spreadsheet formats (excel/ods — a sheet is a record grid unless
    /// told otherwise), `kv` for csv (and, vacuously, for the non-table
    /// formats, which never consult a layout).
    pub fn default_layout(self) -> TableLayout {
        match self {
            Format::Excel | Format::Ods => TableLayout::Db,
            _ => TableLayout::Kv,
        }
    }

    /// Pair this format with custom extensions.
    pub fn exts<I, S>(self, extensions: I) -> FormatSpec
    where
        I: IntoIterator<Item = S>,
        S: Into<String>,
    {
        FormatSpec {
            format: FormatKind::Builtin(self),
            extensions: extensions.into_iter().map(Into::into).collect(),
            layout: self.default_layout(),
        }
    }
}

/// What a [`FormatSpec`] entry parses with: a built-in format or a
/// user-defined [`CustomFormat`].
#[derive(Debug, Clone, PartialEq)]
pub enum FormatKind {
    Builtin(Format),
    Custom(CustomFormat),
}

/// A format plus the extensions it reads — one entry of [`Options::formats`].
///
/// Accepted forms (all `.into()`):
/// - `Format::Yaml` or `"yaml"` — default extensions
/// - `(Format::Yaml, ["yml", "conf"])` or `("yaml", ["yml", "conf"])` —
///   custom extensions
/// - `(Format::Csv, ["csv"], "db")` — custom extensions **plus a
///   [`TableLayout`]** (a layout id string, a `TableLayout`, or a
///   [`CustomLayout`]): every file this entry claims parses under that
///   layout, in merge mode, tree mode and single-file path sources
///   alike. Table sources override it; string sources stay `Kv`; a
///   layout on a non-table format panics at conversion. Without this
///   form an entry uses the format's default layout
///   ([`Format::default_layout`]).
/// - a [`CustomFormat`] — user-defined parser with the extensions it was
///   built with
#[derive(Debug, Clone, PartialEq)]
pub struct FormatSpec {
    pub(crate) format: FormatKind,
    /// Extensions without the leading dot.
    pub(crate) extensions: Vec<String>,
    /// The table layout for files this entry claims (table formats only).
    pub(crate) layout: TableLayout,
}

impl From<Format> for FormatSpec {
    fn from(format: Format) -> Self {
        format.exts(format.default_extensions().iter().copied())
    }
}

impl From<Format> for FormatKind {
    fn from(format: Format) -> Self {
        FormatKind::Builtin(format)
    }
}

impl From<CustomFormat> for FormatKind {
    fn from(custom: CustomFormat) -> Self {
        FormatKind::Custom(custom)
    }
}

impl From<&str> for FormatKind {
    /// A built-in format id (`"jsonc"`, `"yaml"`, …). Panics on an unknown
    /// id — this is config-time code. Lets a `(id, text)` string source
    /// name its format by string.
    fn from(id: &str) -> Self {
        FormatKind::Builtin(
            Format::from_id(id).unwrap_or_else(|| panic!("unknown format id: {id:?}")),
        )
    }
}

impl From<CustomFormat> for FormatSpec {
    fn from(custom: CustomFormat) -> Self {
        Self {
            extensions: custom.extensions.clone(),
            format: FormatKind::Custom(custom),
            layout: TableLayout::Kv,
        }
    }
}

impl From<&str> for FormatSpec {
    /// Panics on an unknown format id — this is config-time code.
    fn from(id: &str) -> Self {
        Format::from_id(id)
            .unwrap_or_else(|| panic!("unknown format id: {id:?}"))
            .into()
    }
}

impl<const N: usize> From<(Format, [&str; N])> for FormatSpec {
    fn from((format, extensions): (Format, [&str; N])) -> Self {
        format.exts(extensions)
    }
}

impl<const N: usize> From<(&str, [&str; N])> for FormatSpec {
    /// Panics on an unknown format id — this is config-time code.
    fn from((id, extensions): (&str, [&str; N])) -> Self {
        Format::from_id(id)
            .unwrap_or_else(|| panic!("unknown format id: {id:?}"))
            .exts(extensions)
    }
}

/// In a `formats` entry the third element is always a **layout** (a
/// string must be a valid layout id — extensions have no sheet meaning).
/// Panics on unknown ids, and on a layout for a non-table format
/// (`(Format::Yaml, ["yml"], "db")`) — this is config-time code.
impl<const N: usize, L: Into<TableLayout>> From<(Format, [&str; N], L)> for FormatSpec {
    fn from((format, extensions, layout): (Format, [&str; N], L)) -> Self {
        assert!(
            matches!(format, Format::Csv | Format::Excel | Format::Ods),
            "'{}' is not a table format (csv, excel, ods) — table layouts do not apply",
            format.id()
        );
        FormatSpec {
            layout: layout.into(),
            ..format.exts(extensions)
        }
    }
}

/// Panics on an unknown format or layout id — this is config-time code.
impl<const N: usize, L: Into<TableLayout>> From<(&str, [&str; N], L)> for FormatSpec {
    fn from((id, extensions, layout): (&str, [&str; N], L)) -> Self {
        let format = Format::from_id(id).unwrap_or_else(|| panic!("unknown format id: {id:?}"));
        (format, extensions, layout).into()
    }
}

/// File load order inside a folder.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum Order {
    /// Subfolders first, then files, each group alphabetic — how directory
    /// listings are conventionally sorted.
    #[default]
    FoldersFirstAlphabetic,
    /// Pure lexicographic order, folders and files interleaved.
    Alphabetic,
    ReverseAlphabetic,
}

impl Order {
    /// Look an order up by its string id. Accepts `-` or `_` between words
    /// and a couple of short aliases:
    /// `folders_first_alphabetic` (`folders_first`, `default`),
    /// `alphabetic`, `reverse_alphabetic` (`reverse`).
    pub fn from_id(id: &str) -> Option<Order> {
        Some(match id.to_lowercase().replace('-', "_").as_str() {
            "folders_first_alphabetic" | "folders_first" | "default" => {
                Order::FoldersFirstAlphabetic
            }
            "alphabetic" => Order::Alphabetic,
            "reverse_alphabetic" | "reverse" => Order::ReverseAlphabetic,
            _ => return None,
        })
    }

    /// The canonical string id of this order.
    pub fn id(self) -> &'static str {
        match self {
            Order::FoldersFirstAlphabetic => "folders_first_alphabetic",
            Order::Alphabetic => "alphabetic",
            Order::ReverseAlphabetic => "reverse_alphabetic",
        }
    }
}

impl From<&str> for Order {
    /// Panics on an unknown id — this is config-time code. See
    /// [`Order::from_id`] for the accepted spellings.
    fn from(id: &str) -> Self {
        Order::from_id(id).unwrap_or_else(|| panic!("unknown order id: {id:?}"))
    }
}

/// How the table stage interprets a row grid. Chosen per table source
/// (`(format, path, layout)` / `(format, path, sheet, layout)` tuples),
/// per `formats` entry (`(format, [exts], layout)`), or passed
/// explicitly to [`parse_table`](crate::parse_table); everything else
/// uses the format's default —
/// [`Format::default_layout`](crate::Format::default_layout): `kv` for
/// csv, `db` for excel/ods. Converts from a layout id string
/// (`"kv"`/`"kvf"`, `"db"`) or a [`CustomLayout`].
#[derive(Debug, Clone, PartialEq, Default)]
pub enum TableLayout {
    /// `key,value[,format]` positional rows — one config entry per row.
    /// The default for csv.
    #[default]
    Kv,
    /// A database-style grid: the first (non-blank) row holds the keys,
    /// the second **always** the type ids (an empty cell = `auto`), every
    /// following row is one record. Parses to an **array** of one object
    /// per record: `[[a,b],[i8,str],[4,x],[5,y]]` →
    /// `[{a:4,b:"x"},{a:5,b:"y"}]`. Empty cells are omitted from their
    /// record (sparse tables give sparse objects). The default for the
    /// spreadsheet formats (excel/ods). A grid *without* a
    /// type row is a [`CustomLayout`] that inserts a row of `auto` cells
    /// after the header and delegates back to `Db` (see the
    /// `xlsx-sheets` example).
    Db,
    /// A user callback over the raw rows — see [`CustomLayout`].
    Custom(CustomLayout),
}

impl TableLayout {
    /// Look a layout up by its string id: `kv` (alias `kvf`) or `db`.
    pub fn from_id(id: &str) -> Option<TableLayout> {
        Some(match id.to_lowercase().as_str() {
            "kv" | "kvf" => TableLayout::Kv,
            "db" => TableLayout::Db,
            _ => return None,
        })
    }

    /// The string id of this layout (a custom layout reports its own id).
    pub fn id(&self) -> &str {
        match self {
            TableLayout::Kv => "kv",
            TableLayout::Db => "db",
            TableLayout::Custom(custom) => &custom.id,
        }
    }
}

impl From<&str> for TableLayout {
    /// Panics on an unknown id — this is config-time code. See
    /// [`TableLayout::from_id`] for the accepted spellings.
    fn from(id: &str) -> Self {
        TableLayout::from_id(id).unwrap_or_else(|| {
            panic!("unknown table layout id: {id:?} (valid: kv, db, or a CustomLayout)")
        })
    }
}

impl From<CustomLayout> for TableLayout {
    fn from(custom: CustomLayout) -> Self {
        TableLayout::Custom(custom)
    }
}

/// The parser callback of a [`CustomLayout`]: `(rows, path, options)`.
pub(crate) type CustomRowsParser =
    std::sync::Arc<dyn Fn(Vec<Vec<String>>, &Path, &Options) -> Result<Value> + Send + Sync>;

/// A user-defined table layout: an id and a callback that receives the
/// lowered rows (`Vec<Vec<String>>` — csv records, or a sheet's cells as
/// text) and returns any [`Value`]. This is the rows-level escape hatch:
/// binary formats (spreadsheets) can't go through a [`CustomFormat`]
/// (which parses text), but one sheet of a workbook can still get fully
/// custom treatment via
/// `(Format::Excel, path, sheet, CustomLayout::new(…)).into()`. Most
/// custom layouts end by reshaping the rows and calling
/// [`parse_table`](crate::parse_table) (the `xlsx-sheets` example
/// transposes a column-oriented sheet this way).
#[derive(Clone)]
pub struct CustomLayout {
    pub(crate) id: String,
    /// `(rows, path, options)` — `path` labels errors. Crate-private:
    /// build custom layouts through [`CustomLayout::new`].
    pub(crate) parser: CustomRowsParser,
}

impl CustomLayout {
    pub fn new<F>(id: impl Into<String>, parser: F) -> Self
    where
        F: Fn(Vec<Vec<String>>, &Path, &Options) -> Result<Value> + Send + Sync + 'static,
    {
        Self {
            id: id.into(),
            parser: std::sync::Arc::new(parser),
        }
    }
}

impl std::fmt::Debug for CustomLayout {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("CustomLayout")
            .field("id", &self.id)
            .finish_non_exhaustive()
    }
}

impl PartialEq for CustomLayout {
    fn eq(&self, other: &Self) -> bool {
        self.id == other.id && std::sync::Arc::ptr_eq(&self.parser, &other.parser)
    }
}

/// The parser callback of a [`CustomFormat`]: `(text, path, options)`.
pub(crate) type CustomParser =
    std::sync::Arc<dyn Fn(&str, &Path, &Options) -> Result<Value> + Send + Sync>;

/// A user-defined format: an id, the extensions it claims, and a parser
/// callback. It goes into [`Options::formats`] like any built-in format
/// (`formats: [..the defaults, md.into()]`), so the usual rule applies —
/// the last claimer of an extension owns it, and a custom format can take
/// over a built-in extension. Table-shaped custom formats can lower their
/// file into rows and reuse the generic table stage via
/// [`parse_table`](crate::parse_table).
///
/// A markdown pipe-table as a config format (runs as a doc test — a
/// string source can name a custom format directly, no files needed):
///
/// ```
/// use c4::{CustomFormat, Loader};
///
/// # fn main() -> Result<(), c4::Error> {
/// let md = CustomFormat::new("md-table", ["md"], |text, path, options| {
///     let rows: Vec<Vec<String>> = text
///         .lines()
///         .map(str::trim)
///         .filter(|l| l.starts_with('|') && !l.contains("---"))
///         // markdown tables always start with a header row — dropping
///         // it here keeps the data rows positional (key,value[,format]),
///         // exactly what parse_table expects
///         .skip(1)
///         .map(|l| {
///             l.trim_matches('|')
///                 .split('|')
///                 .map(|cell| cell.trim().to_owned())
///                 .collect()
///         })
///         .collect();
///     c4::parse_table(rows, &c4::TableLayout::Kv, path, options)
/// });
///
/// // to read `.md` files instead, push `md` into Options.formats —
/// // custom formats claim extensions exactly like built-ins do
/// let value: c4::Value = Loader::new(c4::Options {
///         sources: vec![(
///             md,
///             "| key  | value | format |
///              | ---- | ----- | ------ |
///              | name | c4    | str    |
///              | port | 8080  | u16    |",
///         )
///             .into()],
///         ..c4::Options::default()
///     })
///     .load()?;
/// assert_eq!(value["name"].as_str(), Some("c4"));
/// assert_eq!(value["port"].as_u64(), Some(8080));
/// # Ok(())
/// # }
/// ```
#[derive(Clone)]
pub struct CustomFormat {
    pub(crate) id: String,
    /// Extensions without the leading dot.
    pub(crate) extensions: Vec<String>,
    /// `(text, path, options)` — `path` labels errors. Crate-private:
    /// build custom formats through [`CustomFormat::new`].
    pub(crate) parser: CustomParser,
}

impl CustomFormat {
    pub fn new<I, S, F>(id: impl Into<String>, extensions: I, parser: F) -> Self
    where
        I: IntoIterator<Item = S>,
        S: Into<String>,
        F: Fn(&str, &Path, &Options) -> Result<Value> + Send + Sync + 'static,
    {
        Self {
            id: id.into(),
            extensions: extensions.into_iter().map(Into::into).collect(),
            parser: std::sync::Arc::new(parser),
        }
    }
}

impl std::fmt::Debug for CustomFormat {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("CustomFormat")
            .field("id", &self.id)
            .field("extensions", &self.extensions)
            .finish_non_exhaustive()
    }
}

impl PartialEq for CustomFormat {
    fn eq(&self, other: &Self) -> bool {
        self.id == other.id
            && self.extensions == other.extensions
            && std::sync::Arc::ptr_eq(&self.parser, &other.parser)
    }
}

/// All loader options.
///
/// Plain data on purpose: set the fields you care about and take the rest
/// from `..Options::default()`.
#[derive(Debug, Clone, PartialEq)]
pub struct Options {
    /// The ordered config sources; later sources override earlier ones.
    /// Default: the `config` folder under the current working directory.
    /// Every element converts with `.into()` — see [`Source`] for all
    /// the accepted shapes.
    ///
    /// ```no_run
    /// # fn main() -> Result<(), c4::Error> {
    /// let value: c4::Value = c4::Loader::new(c4::Options {
    ///         sources: vec![
    ///             "./config".into(),              // a folder …
    ///             "./local.yml".into(),           // … or a single file
    ///             ("yaml", "debug: true").into(), // in-code text
    ///             (std::collections::BTreeMap::from([("port", 8080)]),).into(),
    ///         ],
    ///         ..c4::Options::default()
    ///     })
    ///     .load()?;
    /// # Ok(())
    /// # }
    /// ```
    pub sources: Vec<Source>,
    /// Which formats to read and which extensions each one claims. The
    /// list carries **no override-order semantics** — it only builds the
    /// extension→format mapping (if several entries claim the same
    /// extension, the last entry wins the claim). Override order between
    /// files is decided by filename alone; see the merge rules in
    /// README.md. Entry forms are on [`FormatSpec`].
    ///
    /// ```
    /// let options = c4::Options {
    ///     formats: vec![
    ///         "jsonc".into(),                                     // default extensions
    ///         (c4::Format::Yaml, ["yml", "yaml", "conf"]).into(), // custom extensions
    ///         (c4::Format::Csv, ["csv"], "db").into(),            // + a table layout
    ///     ],
    ///     ..c4::Options::default()
    /// };
    /// assert_eq!(options.formats.len(), 3);
    /// ```
    pub formats: Vec<FormatSpec>,
    /// **Folder sources.** How many subdirectory levels below the source
    /// folder to scan. `1` (default): the source folder's own files and
    /// one level of subfolders — `config/*` and `config/a/*`, but not
    /// `config/a/b/*`. `0`: only the source folder's own files. `-1`:
    /// unlimited (fully recursive). Whether the folders that are scanned
    /// contribute their names as keys is [`dirname_as_key`](Options::dirname_as_key).
    /// (The `tree` feature changes this field's default to `-1` — see the
    /// feature.)
    ///
    /// ```no_run
    /// # fn main() -> Result<(), c4::Error> {
    /// // config/*, config/a/* and config/a/b/* all merge in
    /// let value: c4::Value = c4::Loader::new(c4::Options {
    ///         dir_depth: -1, // fully recursive
    ///         ..c4::Options::default()
    ///     })
    ///     .load()?;
    /// # Ok(())
    /// # }
    /// ```
    pub dir_depth: isize,
    /// **Folder sources.** When `true`, each **file** becomes a key named
    /// after the file with its extension stripped, holding that file's
    /// parsed content, instead of merging into the parent — `a.json =
    /// {"c": 1}` loads as `{a: {c: 1}}`. Default `false` (the `tree`
    /// feature changes this default to `true` — see the feature). Combine
    /// with [`dirname_as_key`](Options::dirname_as_key) and `dir_depth:
    /// -1` for a full folder-shaped tree. A dotfile whose whole name is
    /// its extension (`.env`) keeps the full name as its key.
    ///
    /// This is also the switch that decides how *extension-less* and
    /// *unknown-extension* files are handled (see
    /// [`auto_no_ext_files`](Options::auto_no_ext_files) and
    /// [`ignore_unknown_ext`](Options::ignore_unknown_ext)): those only
    /// apply when a file would become a key. Otherwise such files are
    /// skipped (they have no key to contribute under).
    ///
    /// ```no_run
    /// # fn main() -> Result<(), c4::Error> {
    /// // config/a.json = {"c": 1}  ->  {a: {c: 1}}
    /// let value: c4::Value = c4::Loader::new(c4::Options {
    ///         filename_as_key: true,
    ///         ..c4::Options::default()
    ///     })
    ///     .load()?;
    /// assert_eq!(value["a"]["c"].as_i64(), Some(1));
    /// # Ok(())
    /// # }
    /// ```
    pub filename_as_key: bool,
    /// **Folder sources.** When `true`, each **subfolder** becomes a key
    /// and everything under it merges below that key — `db/a.json =
    /// {"host": "x"}` loads as `{db: {host: "x"}}`. Default `false` (the
    /// `tree` feature changes this default to `true` — see the feature).
    /// Honors [`dir_depth`](Options::dir_depth): only folders actually
    /// scanned become keys.
    ///
    /// ```no_run
    /// # fn main() -> Result<(), c4::Error> {
    /// // config/db/a.json = {"host": "x"} — the subfolder becomes a key
    /// let value: c4::Value = c4::Loader::new(c4::Options {
    ///         dirname_as_key: true,
    ///         ..c4::Options::default()
    ///     })
    ///     .load()?;
    /// assert_eq!(value["db"]["host"].as_str(), Some("x"));
    /// # Ok(())
    /// # }
    /// ```
    pub dirname_as_key: bool,
    /// **All modes; env and table formats.** Treat dotted keys as nested
    /// paths: `a.b.c` becomes `{ "a": { "b": { "c": … } } }`.
    /// Default `true`.
    ///
    /// In the table stage this applies to both layouts: the `kv`
    /// layout's key column, and the `db` layout's key row (a dotted
    /// column nests inside each record).
    ///
    /// A key segment may also end in **array suffixes** — `[]` (append)
    /// and `[<int>]` (index) groups, chained for nested arrays
    /// (`grid[0][1]`, one level per group); any other bracket shape
    /// (`a[x]`, `a[-1]`, `a[]b`, a bare `[]`) keeps the whole segment a
    /// literal key:
    ///
    /// - `name[]` **appends** one new element per occurrence: per kv
    ///   row / env line, and per record for a db column.
    /// - `name[<int>]` addresses element `<int>`: the same index
    ///   deep-merges into one element and indexes may arrive in any
    ///   order. Skipped indexes leave `Null` gaps — `a[1]` + `a[4]`
    ///   give a five-element array with nulls at 0, 2 and 3;
    ///   deserialize such arrays as `Vec<Option<T>>`.
    ///
    /// Suffixes also chain through the dotted path (`a[0].b[].c`) and
    /// work on keys without dots (`ports[]`). The expansion happens
    /// within one parse (one file/sheet/string source) — across sources
    /// arrays still replace like any array. The `dot-key` example tours
    /// all of it.
    ///
    /// ```
    /// use std::path::Path;
    ///
    /// use c4::{Options, TableLayout};
    ///
    /// # fn main() -> Result<(), c4::Error> {
    /// let options = Options::default(); // dot_key: true
    ///
    /// // kv layout: the key column nests
    /// let rows = vec![vec!["a.b".to_string(), "1".to_string()]];
    /// let value = c4::parse_table(rows, &TableLayout::Kv, Path::new("doc"), &options)?;
    /// assert_eq!(value["a"]["b"].as_i64(), Some(1));
    ///
    /// // db layout: dotted keys nest inside each record
    /// let rows = vec![
    ///     vec!["a.b".to_string(), "a.c".to_string()], // key row
    ///     vec![String::new(), String::new()],         // type row (all auto)
    ///     vec!["1".to_string(), "2".to_string()],     // one record
    /// ];
    /// let value = c4::parse_table(rows, &TableLayout::Db, Path::new("doc"), &options)?;
    /// assert_eq!(value[0]["a"]["b"].as_i64(), Some(1));
    /// assert_eq!(value[0]["a"]["c"].as_i64(), Some(2));
    ///
    /// // array suffixes: `[]` appends per row, `[<int>]` indexes
    /// let rows = vec![
    ///     vec!["tags[]".to_string(), "red".to_string()],
    ///     vec!["tags[]".to_string(), "blue".to_string()],
    ///     vec!["servers[1].host".to_string(), "beta".to_string()],
    ///     vec!["servers[0].host".to_string(), "alpha".to_string()],
    /// ];
    /// let value = c4::parse_table(rows, &TableLayout::Kv, Path::new("doc"), &options)?;
    /// assert_eq!(value["tags"][1].as_str(), Some("blue"));
    /// assert_eq!(value["servers"][0]["host"].as_str(), Some("alpha"));
    ///
    /// // chained suffixes nest; skipped indexes leave null gaps
    /// let rows = vec![vec!["m[1][0]".to_string(), "9".to_string()]];
    /// let value = c4::parse_table(rows, &TableLayout::Kv, Path::new("doc"), &options)?;
    /// assert!(value["m"][0].is_null());
    /// assert_eq!(value["m"][1][0].as_i64(), Some(9));
    /// # Ok(())
    /// # }
    /// ```
    pub dot_key: bool,
    /// **All modes.** Case-sensitive key merging. Default `true`; when
    /// `false`, keys are normalized to lowercase. (File-extension
    /// matching is always case-insensitive and unrelated to this
    /// option.)
    ///
    /// ```
    /// use std::collections::BTreeMap;
    ///
    /// # fn main() -> Result<(), c4::Error> {
    /// let value: c4::Value = c4::Loader::new(c4::Options {
    ///         sources: vec![
    ///             (BTreeMap::from([("PORT", 1)]),).into(),
    ///             (BTreeMap::from([("port", 8080)]),).into(),
    ///         ],
    ///         case_sensitive: false, // "PORT" and "port" are one key
    ///         ..c4::Options::default()
    ///     })
    ///     .load()?;
    /// assert_eq!(value["port"].as_i64(), Some(8080));
    /// # Ok(())
    /// # }
    /// ```
    pub case_sensitive: bool,
    /// **All modes**; folder sources. Load order inside a folder. In
    /// merge mode it decides which file overrides which; in tree mode it
    /// decides key collisions (`a.yml` vs a folder `a/`).
    ///
    /// ```no_run
    /// # fn main() -> Result<(), c4::Error> {
    /// let value: c4::Value = c4::Loader::new(c4::Options {
    ///         order: "alphabetic".into(), // or c4::Order::Alphabetic
    ///         ..c4::Options::default()
    ///     })
    ///     .load()?;
    /// # Ok(())
    /// # }
    /// ```
    pub order: Order,
    /// **Spreadsheet formats (excel/ods) only.** Treats each sheet of a
    /// workbook like a file. When `true`, a workbook parses to an object
    /// keyed by sheet name (every sheet left after the ignore filters
    /// becomes a key) — the sheet analogue of
    /// [`filename_as_key`](Options::filename_as_key). When `false`
    /// (default), every non-ignored sheet still parses, but they all
    /// **deep-merge** into one value (like several files in a folder), in
    /// [`order`](Options::order) applied to the sheet names — so later
    /// sheets override earlier ones. Default `false` (the `tree` feature
    /// changes this default to `true` — see the feature). (A table source
    /// that names a sheet explicitly is unaffected — it always reads
    /// exactly that sheet.)
    ///
    /// ```no_run
    /// # fn main() -> Result<(), c4::Error> {
    /// // game.xlsx has sheets "items" and "monsters" — each becomes a key
    /// let value: c4::Value = c4::Loader::new(c4::Options {
    ///         sources: vec!["./game.xlsx".into()],
    ///         sheetname_as_key: true,
    ///         ..c4::Options::default()
    ///     })
    ///     .load()?;
    /// assert!(!value["items"].is_null());
    /// # Ok(())
    /// # }
    /// ```
    pub sheetname_as_key: bool,
    /// **Only when [`filename_as_key`](Options::filename_as_key) is true**
    /// (files become keys); folder sources. What to do with a file that
    /// has *no* extension. `true` (default): read it and guess the type of
    /// its (trimmed) content with the table `auto` rules — a file
    /// containing `1.1.1.1` becomes an IPv4 value when the `ipv4` feature
    /// is on, a string otherwise. `false`: treat it like a file with an
    /// unknown extension (see
    /// [`ignore_unknown_ext`](Options::ignore_unknown_ext)). (Named
    /// `auto_no_ext_files` after the table `auto` type id it reuses.)
    /// Without `filename_as_key` an extension-less file has no key to
    /// contribute under and is skipped regardless.
    ///
    /// ```no_run
    /// # fn main() -> Result<(), c4::Error> {
    /// // config/host is an extension-less file holding "1.1.1.1"
    /// let value: c4::Value = c4::Loader::new(c4::Options {
    ///         filename_as_key: true,
    ///         auto_no_ext_files: true,
    ///         ..c4::Options::default()
    ///     })
    ///     .load()?;
    /// assert!(!value["host"].is_null());
    /// # Ok(())
    /// # }
    /// ```
    pub auto_no_ext_files: bool,
    /// **Only when [`filename_as_key`](Options::filename_as_key) is true**
    /// (files become keys); folder sources. What to do with a file whose
    /// extension no active format claims: skip it (`true`, default) or
    /// fail the load with `Error::Parse` (`false`). Without
    /// `filename_as_key` such files are always skipped.
    ///
    /// ```no_run
    /// # fn main() -> Result<(), c4::Error> {
    /// let value: c4::Value = c4::Loader::new(c4::Options {
    ///         filename_as_key: true,
    ///         ignore_unknown_ext: false, // a config/*.xyz file now errors
    ///         ..c4::Options::default()
    ///     })
    ///     .load()?;
    /// # Ok(())
    /// # }
    /// ```
    pub ignore_unknown_ext: bool,
    /// **All modes; every source kind.** Drop **data keys** — the object
    /// keys a source's own content parses to — that start with a comment
    /// prefix (`#` or `_` — never `.`): `#note`, `_tmp` and their whole
    /// subtrees disappear. Default `true`.
    ///
    /// The filter runs on each parse result — one file, one sheet, one
    /// `(format, text)` string, one `(value,)` override — **after**
    /// [`dot_key`](Options::dot_key) expansion, and reaches every level:
    /// nested objects and objects inside arrays (so a `#memo` column
    /// vanishes from every record of a db grid). It is deliberately
    /// *data* keys only: the keys c4 builds from **names** —
    /// [`filename_as_key`](Options::filename_as_key),
    /// [`dirname_as_key`](Options::dirname_as_key),
    /// [`sheetname_as_key`](Options::sheetname_as_key) and the sheet key
    /// of an explicit-sheet table source — are governed by the three
    /// `ignore_commented_*name*` options below instead. An object left
    /// empty stays an empty object.
    ///
    /// ```
    /// use std::collections::BTreeMap;
    ///
    /// # fn main() -> Result<(), c4::Error> {
    /// let value: c4::Value = c4::Loader::new(c4::Options {
    ///         sources: vec![(BTreeMap::from([
    ///             ("port", 8080),
    ///             ("_scratch", 1), // commented out
    ///         ]),).into()],
    ///         ..c4::Options::default() // ignore_commented_data_keys: true
    ///     })
    ///     .load()?;
    /// assert_eq!(value["port"].as_i64(), Some(8080));
    /// assert!(value["_scratch"].is_null());
    /// # Ok(())
    /// # }
    /// ```
    pub ignore_commented_data_keys: bool,
    /// **All modes**; folder sources. Skip files whose name starts with a
    /// comment prefix (`#` or `_` — never `.`, so `.env` still loads):
    /// `config/_draft.yml` is draft space next to live config. Default
    /// `true`. The name decides, so this applies whether or not
    /// [`filename_as_key`](Options::filename_as_key) would key the file.
    ///
    /// **Naming the file yourself always wins.** This filters the folder
    /// **scan** only: a path source (or [`c4::load`](crate::load))
    /// pointing straight at `config/_draft.yml` loads it even with the
    /// option on — you asked for that file by name.
    ///
    /// ```no_run
    /// # fn main() -> Result<(), c4::Error> {
    /// // scanning ./config skips its _draft.yml by default …
    /// let value: c4::Value = c4::load("config")?;
    ///
    /// // … but naming the file loads it, option or not
    /// let draft: c4::Value = c4::load("config/_draft.yml")?;
    ///
    /// // false merges it in while scanning too
    /// let value: c4::Value = c4::Loader::new(c4::Options {
    ///         ignore_commented_filenames: false,
    ///         ..c4::Options::default()
    ///     })
    ///     .load()?;
    /// # Ok(())
    /// # }
    /// ```
    pub ignore_commented_filenames: bool,
    /// **All modes**; folder sources. Skip subfolders whose name starts
    /// with a comment prefix (`#` or `_` — never `.`): nothing under
    /// `config/_wip/` is scanned, and with
    /// [`dirname_as_key`](Options::dirname_as_key) no key appears for it.
    /// Default `true`.
    ///
    /// **Naming the folder yourself always wins — for that folder only.**
    /// A path source `config/_wip` scans `_wip` itself even with the
    /// option on, but the scan *below* it filters as usual: a
    /// `config/_wip/#deep/` subfolder is still skipped (and its files
    /// still follow
    /// [`ignore_commented_filenames`](Options::ignore_commented_filenames)).
    /// Only the folder you named is exempt, not everything under it.
    ///
    /// ```no_run
    /// # fn main() -> Result<(), c4::Error> {
    /// // scanning ./config skips _wip/ entirely by default …
    /// let value: c4::Value = c4::load("config")?;
    ///
    /// // … but naming it scans it — while `_wip/#deep/` inside stays out
    /// let wip: c4::Value = c4::load("config/_wip")?;
    ///
    /// // false scans commented subfolders too
    /// let value: c4::Value = c4::Loader::new(c4::Options {
    ///         ignore_commented_dirnames: false,
    ///         ..c4::Options::default()
    ///     })
    ///     .load()?;
    /// # Ok(())
    /// # }
    /// ```
    pub ignore_commented_dirnames: bool,
    /// **Spreadsheet formats (excel/ods) only.** Skip sheets whose name
    /// starts with a comment prefix (`#` or `_` — never `.`) —
    /// draft/scratch space next to live config, read like a
    /// "commented-out" sheet. Default `true`. The name decides, so the
    /// sheet is skipped in merge mode too (where sheet names are not
    /// keys).
    ///
    /// **Naming the sheet yourself always wins.** This filters the
    /// workbook's sheet **selection** only: a
    /// `(format, path, sheet, layout)` table source reads exactly the
    /// sheet it names — commented or hidden — and merges it under the
    /// sheet name, so a `_extra` sheet stays loadable on purpose.
    ///
    /// ```no_run
    /// # fn main() -> Result<(), c4::Error> {
    /// // game.xlsx has sheets "items" and "_draft"; by default "_draft"
    /// // is skipped — false reads it as a key too
    /// let value: c4::Value = c4::Loader::new(c4::Options {
    ///         sources: vec!["./game.xlsx".into()],
    ///         sheetname_as_key: true,
    ///         ignore_commented_sheetnames: false,
    ///         ..c4::Options::default()
    ///     })
    ///     .load()?;
    /// assert!(!value["_draft"].is_null());
    ///
    /// // naming the sheet reads it with the filter left on
    /// let value: c4::Value = c4::Loader::new(c4::Options {
    ///         sources: vec![(c4::Format::Excel, "./game.xlsx", "_draft", "db").into()],
    ///         ..c4::Options::default()
    ///     })
    ///     .load()?;
    /// assert!(!value["_draft"].is_null());
    /// # Ok(())
    /// # }
    /// ```
    pub ignore_commented_sheetnames: bool,
    /// **Spreadsheet formats (excel/ods) only.** Skip sheets marked
    /// hidden in the workbook (Excel `hidden`/`veryHidden`, OpenDocument
    /// `table:display="false"`). Default `true`. (A table source that
    /// names a sheet explicitly bypasses this filter.)
    ///
    /// ```no_run
    /// # fn main() -> Result<(), c4::Error> {
    /// // the workbook's `config` sheet is marked hidden — read it anyway
    /// let value: c4::Value = c4::Loader::new(c4::Options {
    ///         sources: vec!["./game.xlsx".into()],
    ///         ignore_hidden_sheets: false,
    ///         ..c4::Options::default()
    ///     })
    ///     .load()?;
    /// # Ok(())
    /// # }
    /// ```
    pub ignore_hidden_sheets: bool,
}

impl Default for Options {
    fn default() -> Self {
        Self {
            sources: vec![Source::Path("config".into())],
            formats: enabled_formats(),
            // The `tree` feature is a default-preset, not a capability: it
            // flips the folder/file/sheet keying on and scans every depth.
            // The keying fields themselves work on any build; enabling
            // `tree` just makes tree-shaped loading the default.
            dir_depth: if cfg!(feature = "tree") { -1 } else { 1 },
            filename_as_key: cfg!(feature = "tree"),
            dirname_as_key: cfg!(feature = "tree"),
            sheetname_as_key: cfg!(feature = "tree"),
            dot_key: true,
            case_sensitive: true,
            order: Order::default(),
            auto_no_ext_files: true,
            ignore_unknown_ext: true,
            ignore_commented_data_keys: true,
            ignore_commented_filenames: true,
            ignore_commented_dirnames: true,
            ignore_commented_sheetnames: true,
            ignore_hidden_sheets: true,
        }
    }
}

/// Every format compiled into this build with its default extensions.
/// Later entries win contested extension claims, so `jsonc` (a JSON
/// superset) takes `.json` over strict `json` when both are enabled.
#[allow(clippy::vec_init_then_push)] // every push is cfg-gated on its feature
fn enabled_formats() -> Vec<FormatSpec> {
    let mut formats = Vec::new();
    #[cfg(feature = "json")]
    formats.push(Format::Json.into());
    #[cfg(feature = "jsonc")]
    formats.push(Format::Jsonc.into());
    #[cfg(feature = "yaml")]
    formats.push(Format::Yaml.into());
    #[cfg(feature = "toml")]
    formats.push(Format::Toml.into());
    #[cfg(feature = "ini")]
    formats.push(Format::Ini.into());
    #[cfg(feature = "env")]
    formats.push(Format::Env.into());
    #[cfg(feature = "csv")]
    formats.push(Format::Csv.into());
    #[cfg(feature = "excel")]
    formats.push(Format::Excel.into());
    #[cfg(feature = "ods")]
    formats.push(Format::Ods.into());
    formats
}