c4-config 0.6.0

Load a folder of config files (jsonc/yaml/json/toml/ini/cnf/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
//! Load config from folders, files and in-code strings/values into one
//! deep-merged [`Value`]. File formats (jsonc, yaml, json, toml, ini, cnf,
//! env, csv, excel, ods) are individually Cargo-feature-gated, the table
//! formats' cells (csv and spreadsheet sheets) carry typed values, and
//! every value can be traced to the source it came from.
//!
//! This page is the usage reference; the [README] has the quick start
//! and the "why c4" positioning. Most examples below run without any
//! files — they load in-code string and value sources; only the
//! `load("config")` snippets, which read the caller's filesystem, are
//! marked `no_run`.
//!
//! [README]: https://github.com/up9cloud/c4#readme
//!
//! # Quick start
//!
//! One generic [`load`] takes a path — a folder whose files deep-merge, or
//! a single file — with default options (default format: jsonc). The
//! annotated target type decides what you get: a dynamic [`Value`] or your
//! own serde type.
//!
//! ```no_run
//! # fn main() -> Result<(), c4::Error> {
//! let value: c4::Value = c4::load("config")?;   // a folder …
//! let one: c4::Value = c4::load("app.json")?;   // … or a single file
//! let host = value["db"]["host"].as_str().unwrap_or("localhost");
//! # Ok(())
//! # }
//! ```
//!
//! For more than one source, or any non-default option, build a [`Loader`]
//! from [`Options`], as the next section shows.
//!
//! # Sources and options
//!
//! Everything goes through one plain-data [`Options`]; [`Loader`] has
//! exactly [`new`](Loader::new), [`load`](Loader::load) and
//! [`trace`](Loader::trace). You never name [`Source`]: every `sources`
//! element converts with `.into()`, and its shape picks the source kind
//! — the comments below show every form, [`Source`] has the details:
//!
//! ```no_run
//! use std::path::Path;
//!
//! use c4::{Format, Loader, Options};
//!
//! #[derive(serde::Serialize)]
//! struct Overrides {
//!     debug: bool,
//! }
//!
//! # fn main() -> Result<(), c4::Error> {
//! let value: c4::Value = Loader::new(Options {
//!         sources: vec![
//!             // Path-like values are folders or files
//!             "./config".into(),                              // a folder
//!             "./local.yml".into(),                           // or a single file
//!             Path::new("/etc/myapp").into(),                 // any path-like type
//!             (Overrides { debug: true },).into(),            // (1-tuple) typed override
//!             ("jsonc", r#"{ "note": "from code" }"#).into(), // (2-tuple) format id with string source
//!             (Format::Toml, "debug = true").into(),          // (2-tuple) Format with string source
//!             ("csv", "./items.csv", "db").into(),            // (3-tuple) table source: format + file + layout
//!             (Format::Excel, "./game.xlsx", "drops", "db").into(), // (4-tuple) multiple tables: Format + file + sheet + layout
//!         ],
//!         // which formats read which extensions; the last claimer wins.
//!         // all conversion forms — id/Format × default/custom exts,
//!         // optionally + a table layout for every file the entry claims:
//!         formats: vec![
//!             "jsonc".into(),                                 // format id, default extensions
//!             Format::Toml.into(),                            // Format, default extensions
//!             (Format::Yaml, ["yml", "yaml", "conf"]).into(), // Format + custom extensions
//!             ("jsonc", ["json", "jsonc"]).into(),            // format id + custom extensions
//!             (Format::Csv, ["csv"], "db").into(),            // + layout: all csv = record grids
//!         ],
//!         dir_depth: -1, // scan every subdirectory level
//!         ..Options::default()
//!     })
//!     .load()?;
//! # Ok(())
//! # }
//! ```
//!
//! Every field is documented on [`Options`], each stating up front the
//! mode/format it applies to.
//!
//! # Merge order and custom formats
//!
//! The merge rules, whatever the source kind:
//!
//! 1. Sources merge in the order given; later overrides earlier.
//! 2. Within a folder, entries load in `order` and deep-merge: objects
//!    merge recursively, arrays and scalars replace.
//! 3. Override order between files is decided by **filename alone**, never
//!    by format: `app.json` and `app.yml` sort by name, so `app.yml` loads
//!    later and wins. Prefix filenames (`00_a.json`, `01_a.yml`) for
//!    explicit control.
//! 4. An empty result — an empty file or string, a workbook with no
//!    sheets left, a `(value,)` override that serializes to null —
//!    contributes nothing: it never clears what earlier sources set. The
//!    one exception is **strict** `json`, where an empty document is a
//!    parse error (the message suggests letting `jsonc` read `.json`,
//!    which treats it as empty).
//!
//! A [`CustomFormat`] is an id, the extensions it claims, and a parser
//! callback. It goes into `Options.formats` like any built-in — one list,
//! one claim order — and a string source can name one directly. See
//! [`CustomFormat`] for a full markdown-pipe-table example.
//!
//! ```
//! use c4::{CustomFormat, Loader, Options};
//!
//! # fn main() -> Result<(), c4::Error> {
//! // a tiny `key value type` table format, lowered to `parse_table`
//! let kv = CustomFormat::new("kv", ["kv"], |text, path, options| {
//!     let rows = text
//!         .lines()
//!         .filter(|l| !l.trim().is_empty())
//!         .map(|l| l.split_whitespace().map(str::to_owned).collect())
//!         .collect();
//!     c4::parse_table(rows, &c4::TableLayout::Kv, path, options)
//! });
//! let value: c4::Value = Loader::new(Options {
//!         sources: vec![
//!             (kv.clone(), "port 1 u16").into(),                            // earlier …
//!             (kv, "port 8080 u16").into(),                                 // … overridden
//!             (std::collections::BTreeMap::from([("debug", true)]),).into(),
//!         ],
//!         ..Options::default()
//!     })
//!     .load()?;
//! assert_eq!(value["port"].as_u64(), Some(8080));
//! assert_eq!(value["debug"].as_bool(), Some(true));
//! # Ok(())
//! # }
//! ```
//!
//! # Cargo features
//!
//! `default = ["jsonc"]` — deliberately light, one parser dependency; at
//! least one **format** feature is required (a compile error otherwise).
//! Value-parser features are pure std (no extra dependencies). Cargo
//! unions features across the whole build graph, so only applications
//! should turn format features on.
//!
//! | Feature | Enables |
//! | ------- | ------- |
//! | `jsonc` *(default)* | JSONC files (comments + trailing commas); also the `jsonc` table cell |
//! | `yaml` | YAML files |
//! | `json` | strict JSON files; also the table `json` cell |
//! | `toml` / `ini` / `cnf` / `env` / `csv` | those file formats |
//! | `excel` | Excel workbooks (`.xlsx`/`.xlsm`/`.xlsb`/`.xls`) |
//! | `ods` | OpenDocument spreadsheets (`.ods`) |
//! | `tree` | default-preset: flips [`filename_as_key`](Options::filename_as_key), [`dirname_as_key`](Options::dirname_as_key), [`sheetname_as_key`](Options::sheetname_as_key) on and [`dir_depth`](Options::dir_depth) to `-1` in [`Options::default`] (the fields work without it) |
//! | `datetime` (= `date` + `time`) | the `dt` table type |
//! | `date`, `time` | the `date` / `time` table types |
//! | `ipv4`, `ipv6` | the `ipv4` / `ipv6` table types |
//! | `inet` (= `ipv4` + `ipv6` + `cidr`), `cidr` | inet / cidr table types |
//! | `macaddr` (= `macaddr8`), `macaddr8` | MAC table types |
//! | `uuid` | the `uuid` table type |
//! | `numeric` | extended table numeric literals (`0x`, `_`, `123n`) |
//! | `cli` | the `c4` binary (implies all of the above) |
//!
//! # File formats
//!
//! Format and file extension are separate things: each format claims a set
//! of default extensions, and both sides are configurable. Extension
//! matching is case-insensitive; a hidden file `.X` counts as extension
//! `X` (so `.env` matches `env`). Unclaimed extensions are ignored, and the
//! **last** claimer of a contested extension wins — which is also how you
//! reassign one: `vec![Format::Yaml.into(), (Format::Jsonc, ["yml"]).into()]`
//! makes the jsonc parser read `.yml`. `jsonc` is a JSON superset that also
//! claims `.json`, so with the default `formats` enabling both `json` and
//! `jsonc` is redundant (jsonc, added last, wins `.json`).
//!
//! | Format  | Default extensions | Feature |
//! | ------- | ------------------ | ------- |
//! | `jsonc` | `.json`, `.jsonc`  | default |
//! | `yaml`  | `.yml`, `.yaml`    | `yaml`  |
//! | `json`  | `.json` (strict)   | `json`  |
//! | `toml` (TOML 1.1) | `.toml` | `toml` |
//! | `ini`   | `.ini`             | `ini`   |
//! | `cnf`   | `.cnf`             | `cnf`   |
//! | `env`   | `.env`, `*.env`    | `env`   |
//! | `csv`   | `.csv`             | `csv`   |
//! | `excel` | `.xlsx`, `.xlsm`, `.xlsb`, `.xls` | `excel` |
//! | `ods`   | `.ods`             | `ods`   |
//!
//! A leading UTF-8 byte-order mark (Windows editors, Excel exports) is
//! ignored by every text format, custom formats included.
//!
//! `yaml` resolves anchors, aliases and `<<` merge keys.
//!
//! `env` follows the dotenv conventions: `export` is optional, a quoted
//! value ends at its closing quote, and in an unquoted value `#` starts a
//! comment only after whitespace (`A=1 # note` is `1`, `C=#fff` stays
//! `#fff`). Inside **double** quotes `\n`, `\r`, `\t`, `\"` and `\\`
//! are escapes (any other `\X` stays as written); single quotes are
//! literal. ini, env and cnf values are strings; they still load into
//! typed fields — see [`Loader::load`].
//!
//! # Folder shape: keys and depth
//!
//! By default a folder's files deep-merge into one flat value, scanning
//! the folder plus one subdirectory level ([`dir_depth`](Options::dir_depth):
//! `-1` for unlimited, `0` for the folder only). Turning subfolders and
//! files into **keys** makes the folder's *shape* the config instead:
//!
//! - [`dirname_as_key`](Options::dirname_as_key) — each subfolder becomes
//!   a key.
//! - [`filename_as_key`](Options::filename_as_key) — each file becomes a
//!   key named after it (extension stripped).
//! - [`sheetname_as_key`](Options::sheetname_as_key) — each spreadsheet
//!   sheet becomes a key.
//!
//! These fields work on any build; the `tree` **feature** is just a
//! convenience that flips all three on (and `dir_depth` to `-1`) in
//! [`Options::default`], so an app that wants tree-shaped loading enables
//! the feature and keeps using the defaults.
//!
//! ```text
//! config/a/b.json = {"c": 1}   ->  { "a": { "b": { "c": 1 } },
//! config/d.json   = {"a": 123}       "d": { "a": 123 } }
//! ```
//!
//! ```no_run
//! # fn main() -> Result<(), c4::Error> {
//! // explicit keying — or, with the `tree` feature, just Options::default()
//! let value: c4::Value = c4::Loader::new(c4::Options {
//!         sources: vec!["./config".into()],
//!         filename_as_key: true,
//!         dirname_as_key: true,
//!         dir_depth: -1,
//!         ..c4::Options::default()
//!     })
//!     .load()?;
//! assert_eq!(value["a"]["b"]["c"].as_i64(), Some(1));
//! # Ok(())
//! # }
//! ```
//!
//! Key collisions deep-merge (so [`order`](Options::order) decides the
//! winner); extension handling for keyed files is on
//! [`auto_no_ext_files`](Options::auto_no_ext_files) and
//! [`ignore_unknown_ext`](Options::ignore_unknown_ext).
//!
//! # Commented-out names and keys
//!
//! A name or key starting with `#` or `_` reads as commented out, so
//! draft files, work-in-progress folders, scratch sheets and one-off keys
//! can sit next to live config without loading (`.` is **not** a prefix —
//! `.env` is an ordinary file):
//!
//! ```text
//! config/app.json  = {"port": 8080, "_note": "wip"}  ->  { "port": 8080 }
//! config/_old.json = {"port": 1}                         (skipped)
//! config/_wip/*                                          (skipped)
//! ```
//!
//! Four options, all default `true`, split by what they filter — the
//! **data** a source parses to, or the **names** c4 scans:
//! [`ignore_commented_data_keys`](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).
//! The three name options filter **scanning** only — a file, folder or
//! sheet you name yourself always loads (naming a commented folder scans
//! it, though commented names *inside* it are still skipped) — and they,
//! not the data-key option, govern the keys made from names
//! ([`filename_as_key`](Options::filename_as_key) and friends).
//!
//! ```
//! use std::collections::BTreeMap;
//!
//! # fn main() -> Result<(), c4::Error> {
//! let value: c4::Value = c4::Loader::new(c4::Options {
//!         sources: vec![(BTreeMap::from([("port", 8080), ("_note", 1)]),).into()],
//!         ..c4::Options::default()
//!     })
//!     .load()?;
//! assert_eq!(value["port"].as_i64(), Some(8080));
//! assert!(value["_note"].is_null());
//! # Ok(())
//! # }
//! ```
//!
//! # Table formats
//!
//! Table files (csv, and each spreadsheet sheet) parse under a
//! [`TableLayout`]. Each format has a default —
//! [`Format::default_layout`]: **`kv` for csv, `db` for excel/ods**
//! (spreadsheets are grids) — overridable per source with a table-source
//! tuple or per extension in `formats`:
//!
//! - **`kv`** (csv default): `key,value[,format]` rows, one config entry
//!   per row.
//! - **`db`** (spreadsheet default): a record grid — row 1 holds the
//!   keys, row 2 always the
//!   type ids (empty cell = `auto`), every following row is one record;
//!   the file parses to an **array** of objects, so a config sheet full
//!   of game items deserializes straight into a `Vec<Item>`. Empty cells
//!   are omitted from their record. The type row is positional — the
//!   row right after the keys is the type row even when it is entirely
//!   blank (= every column `auto`); it is never skipped as a blank row.
//! - **a [`CustomLayout`]**: your callback over the raw rows — reshape
//!   them and call [`parse_table`]. A db grid
//!   *without* a type row is the canonical case: insert a row of `auto`
//!   cells after the header and delegate to `db` (see the `xlsx-sheets`
//!   example).
//!
//! The layout comes from a table-source tuple or a `formats` entry (the
//! forms are in the sources example above; details on [`Source`]). The
//! db layout on a plain csv file loads a record grid straight into a
//! `Vec<T>` (the `csv-db` example):
//!
//! ```no_run
//! use c4::{Format, Loader, Options};
//!
//! #[derive(serde::Deserialize)]
//! struct Item {
//!     id: u32,
//!     name: String,
//!     price: f64,
//! }
//!
//! # fn main() -> Result<(), c4::Error> {
//! // items.csv:          key row
//! //   id,name,price
//! //   u32,str,f64       type row (a cell may be empty = auto)
//! //   1,sword,10.5      one record per row
//! //   2,shield,7
//! let items: Vec<Item> = Loader::new(Options {
//!         sources: vec![(Format::Csv, "items.csv", "db").into()],
//!         ..Options::default()
//!     })
//!     .load()?;
//! # Ok(())
//! # }
//! ```
//!
//! Two db sources do not concatenate: arrays replace like any array.
//!
//! Rows map keys to values **positionally** (in `kv`: col 0 = key,
//! col 1 = value, col 2 = format; in `db`: the type row types its
//! column). With [`Options::dot_key`] (default on) a dotted key nests in
//! both layouts — a kv row `a.b,1` gives `{a:{b:1}}`, and a db
//! `stats.atk` column nests inside each record — and a `name[]` /
//! `name[<int>]` segment builds an **array** (append / index, suffixes
//! chain for nested arrays; see [`Options::dot_key`] and the `dot-key`
//! example). The **format** of a
//! cell is one of the ids below — the column/row is optional, and a
//! missing or empty format means `auto`:
//!
//! | Cell format | Aliases | Cargo feature | Notes |
//! | ----------- | ------- | ------------- | ----- |
//! | `auto` *(or empty)* | — | — | guesses bool → date/time/dt → uuid → mac → ip → integer → float → string, using only compiled-in types; never widens past `i64`/`u64`; leading-zero numbers stay strings |
//! | `i8` `i16` `i32` `i64` | `int`, `integer` = `i64` | — | signed integers |
//! | `u8` `u16` `u32` `u64` | `uint` = `u64` | — | unsigned integers |
//! | `i128` `u128` | — | — | explicit-only — `auto` never guesses them |
//! | `f32` `f64` | `float`, `double`, `number` = `f64` | — | floats (`f32` rounds through f32 precision) |
//! | `bool` | `boolean` | — | also accepts `t/f`, `yes/no`, `y/n`, `on/off`, `1/0` (case-insensitive); `auto` only accepts `true`/`false` |
//! | `str` | `string`, `text` | — | the cell text as-is |
//! | `dt` | `datetime` | `datetime` | `YYYY-MM-DD`, optional time part |
//! | `date`, `time` | — | same-named | `YYYY-MM-DD` / `hh:mm:ss[.frac]` |
//! | `ipv4`, `ipv6` | — | same-named | IP addresses |
//! | `inet`, `cidr` | — | same-named | PostgreSQL inet/cidr shapes (optional/required netmask) |
//! | `macaddr`, `macaddr8` | — | same-named | the PostgreSQL MAC spellings |
//! | `uuid` | — | same-named | hyphenated or bare 32-hex |
//! | `json`, `jsonc` | — | same-named | a whole document in one cell, parsed by exactly that format's parser |
//! | `array<sep><format>` | — | — | splits the cell into a flat list by `sep` (default `,`), each element parsed by `format` (default `auto`): `array\|` on `1\|2\|3` → `[1,2,3]`, `array\|u8` types them `u8`, `array\|str` keeps `["1","2","3"]` |
//! | `csv<sep><layout>` | — | `csv` | parses the whole cell as a CSV document (delimiter `sep`, default `,`) under `layout` (default `kv`): `csv,kv` → object, `csv,db` → array of objects |
//!
//! `array` and `csv` are explicit-only (like `json`/`jsonc`) — `auto`
//! never produces a list. `array` is always compiled (a native split);
//! `csv` needs the `csv` feature. Both take an optional, **positional**
//! suffix after the separator: `array<sep><format>` applies one type id
//! to every element, and `csv<sep><layout>` picks the inner layout — in
//! each case naming the suffix means writing the separator too
//! (`array,i8`, `csv,db`), and the separator is a single character
//! (ASCII for `csv`). `array<sep><format>` types **every** element the
//! same; when a list's elements need **different** formats, use a `csv`
//! cell instead (one `key,value,format` row each: `a,1,i8` / `b,2,i16`).
//! Only the built-in layout ids `kv`/`db` are nameable in `csv`.
//!
//! An id whose feature is off is an unknown format and fails the row;
//! only `auto` degrades (it just stops guessing). The `numeric` feature
//! extends every numeric cell with `0x`/`0o`/`0b` radixes, `_`
//! separators and BigInt-style `123n`.
//!
//! The built-in `csv` format is headerless and positional; a header row,
//! renamed/reordered columns or a transposed layout are a [`CustomFormat`]
//! that reshapes the file into `key,value,format` rows and calls
//! [`parse_table`] (see the `csv-header` and `csv-transpose` examples):
//!
//! ```
//! use c4::{CustomFormat, Loader, Options};
//!
//! # fn main() -> Result<(), c4::Error> {
//! let table = CustomFormat::new("kv", ["kv"], |text, path, options| {
//!     let rows = text
//!         .lines()
//!         .filter(|l| !l.trim().is_empty())
//!         .map(|l| l.split_whitespace().map(str::to_owned).collect())
//!         .collect();
//!     c4::parse_table(rows, &c4::TableLayout::Kv, path, options)
//! });
//! let value: c4::Value = Loader::new(Options {
//!         sources: vec![(table, "name c4 str\nport 8080 u16\ndebug true bool").into()],
//!         ..Options::default()
//!     })
//!     .load()?;
//! assert_eq!(value["name"].as_str(), Some("c4"));
//! assert_eq!(value["port"].as_u64(), Some(8080));
//! assert_eq!(value["debug"].as_bool(), Some(true));
//! # Ok(())
//! # }
//! ```
//!
//! # Spreadsheet formats
//!
//! `excel` (`.xlsx`/`.xlsm`/`.xlsb`/`.xls`) and `ods` (`.ods`) read
//! workbooks as table formats: each sheet is a grid anchored at cell A1,
//! lowered to rows for the table stage — **db record grids by default**
//! ([`Format::default_layout`]). Numbers, booleans and date-formatted
//! cells convert to the text the stage expects (a `dt`/`date`/`time`
//! column works on real spreadsheet dates), and error messages carry
//! real spreadsheet row numbers. Both are binary formats, so they load
//! from files only — a `(Format::Excel, text)` string source is an
//! error.
//!
//! Which sheets are read — each sheet is treated like a file:
//!
//! - `sheetname_as_key: false` (default): every non-ignored sheet parses
//!   and they all **deep-merge** into one value, in
//!   [`order`](Options::order) by sheet name (later overrides earlier). A
//!   workbook with no sheets left contributes nothing.
//! - `sheetname_as_key: true`: every sheet becomes a key instead (through
//!   the same [`dot_key`](Options::dot_key) expansion as any key, so a
//!   sheet named `a.b` nests) — see [`Options::sheetname_as_key`].
//! - Commented (`#`/`_`) and hidden sheets are skipped — see
//!   [`Options::ignore_commented_sheetnames`] and
//!   [`Options::ignore_hidden_sheets`].
//! - A table source that names a sheet (always the 4-tuple) reads
//!   exactly that sheet and merges it under the sheet name as key — see
//!   [`Source`]:
//!
//! ```no_run
//! use c4::{Format, Loader, Options};
//!
//! # fn main() -> Result<(), c4::Error> {
//! // game.xlsx: sheet "items" is a record grid, "settings" is kv rows
//! let value: c4::Value = Loader::new(Options {
//!         sources: vec![
//!             (Format::Excel, "game.xlsx", "items", "db").into(),
//!             (Format::Excel, "game.xlsx", "settings", "kv").into(),
//!         ],
//!         ..Options::default()
//!     })
//!     .load()?;
//! assert!(value["items"][0]["id"].as_u64().is_some());
//! assert!(!value["settings"].is_null());
//! # Ok(())
//! # }
//! ```
//!
//! The `xlsx-sheets` example composes five sheets of one workbook this
//! way, `CustomLayout`s included.
//!
//! # Provenance
//!
//! [`Loader::trace`] returns a [`Trace`]: the merged [`TracedValue`] tree
//! that keeps, per leaf, the source it came from and the format it parsed
//! as, plus the [`Warning`]s for input c4 accepted but did not act on —
//! the shape the CLI `--trace` prints. The library
//! never prints warnings, and [`load`] drops them.
//!
//! # cnf files
//!
//! `.ini` is read strictly — the subset the de facto ini dialects share:
//! `[section]` one level deep, `key=value`, `;`/`#` comment lines, no
//! quoting or escapes. `.cnf` has no spec and several dialects, so the `cnf` parser is lenient enough to read `my.cnf`
//! (MySQL/MariaDB), `openssl.cnf` and the like as they are; where the
//! dialects disagree it follows MySQL. `[ section ]` headers; `#`
//! comments anywhere outside quotes, `;` and `%` comments at line start
//! only; quotes stripped only when they wrap the whole value; MySQL
//! escapes (`\s`, `\n`, …, any other `\X` kept as written); bare keys
//! (`skip-networking`) as `true`; no line continuation. Everything else
//! is a string, and keys stay literal. Variables (`$dir`, `$ENV::HOME`)
//! are not expanded, and include directives (`!include`, `.include`) are
//! skipped,
//! each with a [`Warning`] in the trace:
//!
//! ```
//! # #[cfg(feature = "cnf")]
//! # fn main() -> Result<(), c4::Error> {
//! let trace = c4::Loader::new(c4::Options {
//!     sources: vec![("cnf", "!includedir /etc/mysql/conf.d/\n[mysqld]\nport = 3306\nskip-networking\n").into()],
//!     ..c4::Options::default()
//! })
//! .trace()?;
//! let value: c4::Value = trace.value.into();
//! assert_eq!(value["mysqld"]["port"].as_str(), Some("3306"));
//! assert_eq!(value["mysqld"]["skip-networking"].as_bool(), Some(true));
//! assert_eq!(trace.warnings.len(), 1);
//! # Ok(())
//! # }
//! # #[cfg(not(feature = "cnf"))]
//! # fn main() {}
//! ```

#[cfg(not(any(
    feature = "json",
    feature = "jsonc",
    feature = "yaml",
    feature = "toml",
    feature = "ini",
    feature = "cnf",
    feature = "env",
    feature = "csv",
    feature = "excel",
    feature = "ods"
)))]
compile_error!(
    "c4: enable at least one format feature (json, jsonc, yaml, toml, ini, cnf, env, csv, excel, ods)"
);

mod de;
mod error;
mod format;
mod loader;
mod options;
mod ser;
mod source;
mod trace;
pub(crate) mod valid;
mod value;

pub use error::{Error, Result};
pub use loader::Loader;
pub use options::{
    CustomFormat, CustomLayout, Format, FormatKind, FormatSpec, Options, Order, TableLayout,
};
pub use source::Source;
pub use trace::{SourceRef, Trace, TracedValue, Warning};
pub use value::Value;

use std::path::{Path, PathBuf};

use serde::de::DeserializeOwned;

/// Load one path with default options — the shortest way in. An
/// existing file loads as a single file source; anything else is
/// treated as a folder (a missing path is [`Error::NotFound`]). The
/// annotated target type decides what you get back:
///
/// ```no_run
/// #[derive(serde::Deserialize)]
/// struct MyConfig {
///     host: String,
///     port: u16,
/// }
///
/// # fn main() -> Result<(), c4::Error> {
/// let value: c4::Value = c4::load("config")?;   // a folder …
/// let value: c4::Value = c4::load("app.yml")?;  // … or one file
/// let cfg: MyConfig = c4::load("config")?;
/// # Ok(())
/// # }
/// ```
pub fn load<T: DeserializeOwned>(path: impl Into<PathBuf>) -> Result<T> {
    Loader::new(Options {
        sources: vec![Source::Path(path.into())],
        ..Options::default()
    })
    .load()
}

/// The generic table stage: interpret a plain row table under an
/// explicit [`TableLayout`] — `&TableLayout::Kv` for
/// `key,value[,format]` rows (what the csv format feeds by default),
/// `&TableLayout::Db` for a record grid, or a [`CustomLayout`] callback.
/// Public so custom table-shaped formats (markdown tables, …) and custom
/// layouts can lower their input into rows and reuse it; `path` labels
/// errors. The layout is always passed — there is deliberately no
/// defaulting variant.
pub fn parse_table(
    rows: Vec<Vec<String>>,
    layout: &TableLayout,
    path: &Path,
    options: &Options,
) -> Result<Value> {
    format::table::parse(rows, layout, path, options)
}