c4/lib.rs
1//! Load config from folders, files and in-code strings/values into one
2//! deep-merged [`Value`]. File formats (jsonc, yaml, json, toml, ini, cnf,
3//! env, csv, excel, ods) are individually Cargo-feature-gated, the table
4//! formats' cells (csv and spreadsheet sheets) carry typed values, and
5//! every value can be traced to the source it came from.
6//!
7//! This page is the usage reference; the [README] has the quick start
8//! and the "why c4" positioning. Most examples below run without any
9//! files — they load in-code string and value sources; only the
10//! `load("config")` snippets, which read the caller's filesystem, are
11//! marked `no_run`.
12//!
13//! [README]: https://github.com/up9cloud/c4#readme
14//!
15//! # Quick start
16//!
17//! One generic [`load`] takes a path — a folder whose files deep-merge, or
18//! a single file — with default options (default format: jsonc). The
19//! annotated target type decides what you get: a dynamic [`Value`] or your
20//! own serde type.
21//!
22//! ```no_run
23//! # fn main() -> Result<(), c4::Error> {
24//! let value: c4::Value = c4::load("config")?; // a folder …
25//! let one: c4::Value = c4::load("app.json")?; // … or a single file
26//! let host = value["db"]["host"].as_str().unwrap_or("localhost");
27//! # Ok(())
28//! # }
29//! ```
30//!
31//! For more than one source, or any non-default option, build a [`Loader`]
32//! from [`Options`], as the next section shows.
33//!
34//! # Sources and options
35//!
36//! Everything goes through one plain-data [`Options`]; [`Loader`] has
37//! exactly [`new`](Loader::new), [`load`](Loader::load) and
38//! [`trace`](Loader::trace). You never name [`Source`]: every `sources`
39//! element converts with `.into()`, and its shape picks the source kind
40//! — the comments below show every form, [`Source`] has the details:
41//!
42//! ```no_run
43//! use std::path::Path;
44//!
45//! use c4::{Format, Loader, Options};
46//!
47//! #[derive(serde::Serialize)]
48//! struct Overrides {
49//! debug: bool,
50//! }
51//!
52//! # fn main() -> Result<(), c4::Error> {
53//! let value: c4::Value = Loader::new(Options {
54//! sources: vec![
55//! // Path-like values are folders or files
56//! "./config".into(), // a folder
57//! "./local.yml".into(), // or a single file
58//! Path::new("/etc/myapp").into(), // any path-like type
59//! (Overrides { debug: true },).into(), // (1-tuple) typed override
60//! ("jsonc", r#"{ "note": "from code" }"#).into(), // (2-tuple) format id with string source
61//! (Format::Toml, "debug = true").into(), // (2-tuple) Format with string source
62//! ("csv", "./items.csv", "db").into(), // (3-tuple) table source: format + file + layout
63//! (Format::Excel, "./game.xlsx", "drops", "db").into(), // (4-tuple) multiple tables: Format + file + sheet + layout
64//! ],
65//! // which formats read which extensions; the last claimer wins.
66//! // all conversion forms — id/Format × default/custom exts,
67//! // optionally + a table layout for every file the entry claims:
68//! formats: vec![
69//! "jsonc".into(), // format id, default extensions
70//! Format::Toml.into(), // Format, default extensions
71//! (Format::Yaml, ["yml", "yaml", "conf"]).into(), // Format + custom extensions
72//! ("jsonc", ["json", "jsonc"]).into(), // format id + custom extensions
73//! (Format::Csv, ["csv"], "db").into(), // + layout: all csv = record grids
74//! ],
75//! dir_depth: -1, // scan every subdirectory level
76//! ..Options::default()
77//! })
78//! .load()?;
79//! # Ok(())
80//! # }
81//! ```
82//!
83//! Every field is documented on [`Options`], each stating up front the
84//! mode/format it applies to.
85//!
86//! # Merge order and custom formats
87//!
88//! The merge rules, whatever the source kind:
89//!
90//! 1. Sources merge in the order given; later overrides earlier.
91//! 2. Within a folder, entries load in `order` and deep-merge: objects
92//! merge recursively, arrays and scalars replace.
93//! 3. Override order between files is decided by **filename alone**, never
94//! by format: `app.json` and `app.yml` sort by name, so `app.yml` loads
95//! later and wins. Prefix filenames (`00_a.json`, `01_a.yml`) for
96//! explicit control.
97//! 4. An empty result — an empty file or string, a workbook with no
98//! sheets left, a `(value,)` override that serializes to null —
99//! contributes nothing: it never clears what earlier sources set. The
100//! one exception is **strict** `json`, where an empty document is a
101//! parse error (the message suggests letting `jsonc` read `.json`,
102//! which treats it as empty).
103//!
104//! A [`CustomFormat`] is an id, the extensions it claims, and a parser
105//! callback. It goes into `Options.formats` like any built-in — one list,
106//! one claim order — and a string source can name one directly. See
107//! [`CustomFormat`] for a full markdown-pipe-table example.
108//!
109//! ```
110//! use c4::{CustomFormat, Loader, Options};
111//!
112//! # fn main() -> Result<(), c4::Error> {
113//! // a tiny `key value type` table format, lowered to `parse_table`
114//! let kv = CustomFormat::new("kv", ["kv"], |text, path, options| {
115//! let rows = text
116//! .lines()
117//! .filter(|l| !l.trim().is_empty())
118//! .map(|l| l.split_whitespace().map(str::to_owned).collect())
119//! .collect();
120//! c4::parse_table(rows, &c4::TableLayout::Kv, path, options)
121//! });
122//! let value: c4::Value = Loader::new(Options {
123//! sources: vec![
124//! (kv.clone(), "port 1 u16").into(), // earlier …
125//! (kv, "port 8080 u16").into(), // … overridden
126//! (std::collections::BTreeMap::from([("debug", true)]),).into(),
127//! ],
128//! ..Options::default()
129//! })
130//! .load()?;
131//! assert_eq!(value["port"].as_u64(), Some(8080));
132//! assert_eq!(value["debug"].as_bool(), Some(true));
133//! # Ok(())
134//! # }
135//! ```
136//!
137//! # Cargo features
138//!
139//! `default = ["jsonc"]` — deliberately light, one parser dependency; at
140//! least one **format** feature is required (a compile error otherwise).
141//! Value-parser features are pure std (no extra dependencies). Cargo
142//! unions features across the whole build graph, so only applications
143//! should turn format features on.
144//!
145//! | Feature | Enables |
146//! | ------- | ------- |
147//! | `jsonc` *(default)* | JSONC files (comments + trailing commas); also the `jsonc` table cell |
148//! | `yaml` | YAML files |
149//! | `json` | strict JSON files; also the table `json` cell |
150//! | `toml` / `ini` / `cnf` / `env` / `csv` | those file formats |
151//! | `excel` | Excel workbooks (`.xlsx`/`.xlsm`/`.xlsb`/`.xls`) |
152//! | `ods` | OpenDocument spreadsheets (`.ods`) |
153//! | `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) |
154//! | `datetime` (= `date` + `time`) | the `dt` table type |
155//! | `date`, `time` | the `date` / `time` table types |
156//! | `ipv4`, `ipv6` | the `ipv4` / `ipv6` table types |
157//! | `inet` (= `ipv4` + `ipv6` + `cidr`), `cidr` | inet / cidr table types |
158//! | `macaddr` (= `macaddr8`), `macaddr8` | MAC table types |
159//! | `uuid` | the `uuid` table type |
160//! | `numeric` | extended table numeric literals (`0x`, `_`, `123n`) |
161//! | `cli` | the `c4` binary (implies all of the above) |
162//!
163//! # File formats
164//!
165//! Format and file extension are separate things: each format claims a set
166//! of default extensions, and both sides are configurable. Extension
167//! matching is case-insensitive; a hidden file `.X` counts as extension
168//! `X` (so `.env` matches `env`). Unclaimed extensions are ignored, and the
169//! **last** claimer of a contested extension wins — which is also how you
170//! reassign one: `vec![Format::Yaml.into(), (Format::Jsonc, ["yml"]).into()]`
171//! makes the jsonc parser read `.yml`. `jsonc` is a JSON superset that also
172//! claims `.json`, so with the default `formats` enabling both `json` and
173//! `jsonc` is redundant (jsonc, added last, wins `.json`).
174//!
175//! | Format | Default extensions | Feature |
176//! | ------- | ------------------ | ------- |
177//! | `jsonc` | `.json`, `.jsonc` | default |
178//! | `yaml` | `.yml`, `.yaml` | `yaml` |
179//! | `json` | `.json` (strict) | `json` |
180//! | `toml` (TOML 1.1) | `.toml` | `toml` |
181//! | `ini` | `.ini` | `ini` |
182//! | `cnf` | `.cnf` | `cnf` |
183//! | `env` | `.env`, `*.env` | `env` |
184//! | `csv` | `.csv` | `csv` |
185//! | `excel` | `.xlsx`, `.xlsm`, `.xlsb`, `.xls` | `excel` |
186//! | `ods` | `.ods` | `ods` |
187//!
188//! A leading UTF-8 byte-order mark (Windows editors, Excel exports) is
189//! ignored by every text format, custom formats included.
190//!
191//! `yaml` resolves anchors, aliases and `<<` merge keys.
192//!
193//! `env` follows the dotenv conventions: `export` is optional, a quoted
194//! value ends at its closing quote, and in an unquoted value `#` starts a
195//! comment only after whitespace (`A=1 # note` is `1`, `C=#fff` stays
196//! `#fff`). Inside **double** quotes `\n`, `\r`, `\t`, `\"` and `\\`
197//! are escapes (any other `\X` stays as written); single quotes are
198//! literal. ini, env and cnf values are strings; they still load into
199//! typed fields — see [`Loader::load`].
200//!
201//! # Folder shape: keys and depth
202//!
203//! By default a folder's files deep-merge into one flat value, scanning
204//! the folder plus one subdirectory level ([`dir_depth`](Options::dir_depth):
205//! `-1` for unlimited, `0` for the folder only). Turning subfolders and
206//! files into **keys** makes the folder's *shape* the config instead:
207//!
208//! - [`dirname_as_key`](Options::dirname_as_key) — each subfolder becomes
209//! a key.
210//! - [`filename_as_key`](Options::filename_as_key) — each file becomes a
211//! key named after it (extension stripped).
212//! - [`sheetname_as_key`](Options::sheetname_as_key) — each spreadsheet
213//! sheet becomes a key.
214//!
215//! These fields work on any build; the `tree` **feature** is just a
216//! convenience that flips all three on (and `dir_depth` to `-1`) in
217//! [`Options::default`], so an app that wants tree-shaped loading enables
218//! the feature and keeps using the defaults.
219//!
220//! ```text
221//! config/a/b.json = {"c": 1} -> { "a": { "b": { "c": 1 } },
222//! config/d.json = {"a": 123} "d": { "a": 123 } }
223//! ```
224//!
225//! ```no_run
226//! # fn main() -> Result<(), c4::Error> {
227//! // explicit keying — or, with the `tree` feature, just Options::default()
228//! let value: c4::Value = c4::Loader::new(c4::Options {
229//! sources: vec!["./config".into()],
230//! filename_as_key: true,
231//! dirname_as_key: true,
232//! dir_depth: -1,
233//! ..c4::Options::default()
234//! })
235//! .load()?;
236//! assert_eq!(value["a"]["b"]["c"].as_i64(), Some(1));
237//! # Ok(())
238//! # }
239//! ```
240//!
241//! Key collisions deep-merge (so [`order`](Options::order) decides the
242//! winner); extension handling for keyed files is on
243//! [`auto_no_ext_files`](Options::auto_no_ext_files) and
244//! [`ignore_unknown_ext`](Options::ignore_unknown_ext).
245//!
246//! # Commented-out names and keys
247//!
248//! A name or key starting with `#` or `_` reads as commented out, so
249//! draft files, work-in-progress folders, scratch sheets and one-off keys
250//! can sit next to live config without loading (`.` is **not** a prefix —
251//! `.env` is an ordinary file):
252//!
253//! ```text
254//! config/app.json = {"port": 8080, "_note": "wip"} -> { "port": 8080 }
255//! config/_old.json = {"port": 1} (skipped)
256//! config/_wip/* (skipped)
257//! ```
258//!
259//! Four options, all default `true`, split by what they filter — the
260//! **data** a source parses to, or the **names** c4 scans:
261//! [`ignore_commented_data_keys`](Options::ignore_commented_data_keys),
262//! [`ignore_commented_filenames`](Options::ignore_commented_filenames),
263//! [`ignore_commented_dirnames`](Options::ignore_commented_dirnames) and
264//! [`ignore_commented_sheetnames`](Options::ignore_commented_sheetnames).
265//! The three name options filter **scanning** only — a file, folder or
266//! sheet you name yourself always loads (naming a commented folder scans
267//! it, though commented names *inside* it are still skipped) — and they,
268//! not the data-key option, govern the keys made from names
269//! ([`filename_as_key`](Options::filename_as_key) and friends).
270//!
271//! ```
272//! use std::collections::BTreeMap;
273//!
274//! # fn main() -> Result<(), c4::Error> {
275//! let value: c4::Value = c4::Loader::new(c4::Options {
276//! sources: vec![(BTreeMap::from([("port", 8080), ("_note", 1)]),).into()],
277//! ..c4::Options::default()
278//! })
279//! .load()?;
280//! assert_eq!(value["port"].as_i64(), Some(8080));
281//! assert!(value["_note"].is_null());
282//! # Ok(())
283//! # }
284//! ```
285//!
286//! # Table formats
287//!
288//! Table files (csv, and each spreadsheet sheet) parse under a
289//! [`TableLayout`]. Each format has a default —
290//! [`Format::default_layout`]: **`kv` for csv, `db` for excel/ods**
291//! (spreadsheets are grids) — overridable per source with a table-source
292//! tuple or per extension in `formats`:
293//!
294//! - **`kv`** (csv default): `key,value[,format]` rows, one config entry
295//! per row.
296//! - **`db`** (spreadsheet default): a record grid — row 1 holds the
297//! keys, row 2 always the
298//! type ids (empty cell = `auto`), every following row is one record;
299//! the file parses to an **array** of objects, so a config sheet full
300//! of game items deserializes straight into a `Vec<Item>`. Empty cells
301//! are omitted from their record. The type row is positional — the
302//! row right after the keys is the type row even when it is entirely
303//! blank (= every column `auto`); it is never skipped as a blank row.
304//! - **a [`CustomLayout`]**: your callback over the raw rows — reshape
305//! them and call [`parse_table`]. A db grid
306//! *without* a type row is the canonical case: insert a row of `auto`
307//! cells after the header and delegate to `db` (see the `xlsx-sheets`
308//! example).
309//!
310//! The layout comes from a table-source tuple or a `formats` entry (the
311//! forms are in the sources example above; details on [`Source`]). The
312//! db layout on a plain csv file loads a record grid straight into a
313//! `Vec<T>` (the `csv-db` example):
314//!
315//! ```no_run
316//! use c4::{Format, Loader, Options};
317//!
318//! #[derive(serde::Deserialize)]
319//! struct Item {
320//! id: u32,
321//! name: String,
322//! price: f64,
323//! }
324//!
325//! # fn main() -> Result<(), c4::Error> {
326//! // items.csv: key row
327//! // id,name,price
328//! // u32,str,f64 type row (a cell may be empty = auto)
329//! // 1,sword,10.5 one record per row
330//! // 2,shield,7
331//! let items: Vec<Item> = Loader::new(Options {
332//! sources: vec![(Format::Csv, "items.csv", "db").into()],
333//! ..Options::default()
334//! })
335//! .load()?;
336//! # Ok(())
337//! # }
338//! ```
339//!
340//! Two db sources do not concatenate: arrays replace like any array.
341//!
342//! Rows map keys to values **positionally** (in `kv`: col 0 = key,
343//! col 1 = value, col 2 = format; in `db`: the type row types its
344//! column). With [`Options::dot_key`] (default on) a dotted key nests in
345//! both layouts — a kv row `a.b,1` gives `{a:{b:1}}`, and a db
346//! `stats.atk` column nests inside each record — and a `name[]` /
347//! `name[<int>]` segment builds an **array** (append / index, suffixes
348//! chain for nested arrays; see [`Options::dot_key`] and the `dot-key`
349//! example). The **format** of a
350//! cell is one of the ids below — the column/row is optional, and a
351//! missing or empty format means `auto`:
352//!
353//! | Cell format | Aliases | Cargo feature | Notes |
354//! | ----------- | ------- | ------------- | ----- |
355//! | `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 |
356//! | `i8` `i16` `i32` `i64` | `int`, `integer` = `i64` | — | signed integers |
357//! | `u8` `u16` `u32` `u64` | `uint` = `u64` | — | unsigned integers |
358//! | `i128` `u128` | — | — | explicit-only — `auto` never guesses them |
359//! | `f32` `f64` | `float`, `double`, `number` = `f64` | — | floats (`f32` rounds through f32 precision) |
360//! | `bool` | `boolean` | — | also accepts `t/f`, `yes/no`, `y/n`, `on/off`, `1/0` (case-insensitive); `auto` only accepts `true`/`false` |
361//! | `str` | `string`, `text` | — | the cell text as-is |
362//! | `dt` | `datetime` | `datetime` | `YYYY-MM-DD`, optional time part |
363//! | `date`, `time` | — | same-named | `YYYY-MM-DD` / `hh:mm:ss[.frac]` |
364//! | `ipv4`, `ipv6` | — | same-named | IP addresses |
365//! | `inet`, `cidr` | — | same-named | PostgreSQL inet/cidr shapes (optional/required netmask) |
366//! | `macaddr`, `macaddr8` | — | same-named | the PostgreSQL MAC spellings |
367//! | `uuid` | — | same-named | hyphenated or bare 32-hex |
368//! | `json`, `jsonc` | — | same-named | a whole document in one cell, parsed by exactly that format's parser |
369//! | `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"]` |
370//! | `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 |
371//!
372//! `array` and `csv` are explicit-only (like `json`/`jsonc`) — `auto`
373//! never produces a list. `array` is always compiled (a native split);
374//! `csv` needs the `csv` feature. Both take an optional, **positional**
375//! suffix after the separator: `array<sep><format>` applies one type id
376//! to every element, and `csv<sep><layout>` picks the inner layout — in
377//! each case naming the suffix means writing the separator too
378//! (`array,i8`, `csv,db`), and the separator is a single character
379//! (ASCII for `csv`). `array<sep><format>` types **every** element the
380//! same; when a list's elements need **different** formats, use a `csv`
381//! cell instead (one `key,value,format` row each: `a,1,i8` / `b,2,i16`).
382//! Only the built-in layout ids `kv`/`db` are nameable in `csv`.
383//!
384//! An id whose feature is off is an unknown format and fails the row;
385//! only `auto` degrades (it just stops guessing). The `numeric` feature
386//! extends every numeric cell with `0x`/`0o`/`0b` radixes, `_`
387//! separators and BigInt-style `123n`.
388//!
389//! The built-in `csv` format is headerless and positional; a header row,
390//! renamed/reordered columns or a transposed layout are a [`CustomFormat`]
391//! that reshapes the file into `key,value,format` rows and calls
392//! [`parse_table`] (see the `csv-header` and `csv-transpose` examples):
393//!
394//! ```
395//! use c4::{CustomFormat, Loader, Options};
396//!
397//! # fn main() -> Result<(), c4::Error> {
398//! let table = CustomFormat::new("kv", ["kv"], |text, path, options| {
399//! let rows = text
400//! .lines()
401//! .filter(|l| !l.trim().is_empty())
402//! .map(|l| l.split_whitespace().map(str::to_owned).collect())
403//! .collect();
404//! c4::parse_table(rows, &c4::TableLayout::Kv, path, options)
405//! });
406//! let value: c4::Value = Loader::new(Options {
407//! sources: vec![(table, "name c4 str\nport 8080 u16\ndebug true bool").into()],
408//! ..Options::default()
409//! })
410//! .load()?;
411//! assert_eq!(value["name"].as_str(), Some("c4"));
412//! assert_eq!(value["port"].as_u64(), Some(8080));
413//! assert_eq!(value["debug"].as_bool(), Some(true));
414//! # Ok(())
415//! # }
416//! ```
417//!
418//! # Spreadsheet formats
419//!
420//! `excel` (`.xlsx`/`.xlsm`/`.xlsb`/`.xls`) and `ods` (`.ods`) read
421//! workbooks as table formats: each sheet is a grid anchored at cell A1,
422//! lowered to rows for the table stage — **db record grids by default**
423//! ([`Format::default_layout`]). Numbers, booleans and date-formatted
424//! cells convert to the text the stage expects (a `dt`/`date`/`time`
425//! column works on real spreadsheet dates), and error messages carry
426//! real spreadsheet row numbers. Both are binary formats, so they load
427//! from files only — a `(Format::Excel, text)` string source is an
428//! error.
429//!
430//! Which sheets are read — each sheet is treated like a file:
431//!
432//! - `sheetname_as_key: false` (default): every non-ignored sheet parses
433//! and they all **deep-merge** into one value, in
434//! [`order`](Options::order) by sheet name (later overrides earlier). A
435//! workbook with no sheets left contributes nothing.
436//! - `sheetname_as_key: true`: every sheet becomes a key instead (through
437//! the same [`dot_key`](Options::dot_key) expansion as any key, so a
438//! sheet named `a.b` nests) — see [`Options::sheetname_as_key`].
439//! - Commented (`#`/`_`) and hidden sheets are skipped — see
440//! [`Options::ignore_commented_sheetnames`] and
441//! [`Options::ignore_hidden_sheets`].
442//! - A table source that names a sheet (always the 4-tuple) reads
443//! exactly that sheet and merges it under the sheet name as key — see
444//! [`Source`]:
445//!
446//! ```no_run
447//! use c4::{Format, Loader, Options};
448//!
449//! # fn main() -> Result<(), c4::Error> {
450//! // game.xlsx: sheet "items" is a record grid, "settings" is kv rows
451//! let value: c4::Value = Loader::new(Options {
452//! sources: vec![
453//! (Format::Excel, "game.xlsx", "items", "db").into(),
454//! (Format::Excel, "game.xlsx", "settings", "kv").into(),
455//! ],
456//! ..Options::default()
457//! })
458//! .load()?;
459//! assert!(value["items"][0]["id"].as_u64().is_some());
460//! assert!(!value["settings"].is_null());
461//! # Ok(())
462//! # }
463//! ```
464//!
465//! The `xlsx-sheets` example composes five sheets of one workbook this
466//! way, `CustomLayout`s included.
467//!
468//! # Provenance
469//!
470//! [`Loader::trace`] returns a [`Trace`]: the merged [`TracedValue`] tree
471//! that keeps, per leaf, the source it came from and the format it parsed
472//! as, plus the [`Warning`]s for input c4 accepted but did not act on —
473//! the shape the CLI `--trace` prints. The library
474//! never prints warnings, and [`load`] drops them.
475//!
476//! # cnf files
477//!
478//! `.ini` is read strictly — the subset the de facto ini dialects share:
479//! `[section]` one level deep, `key=value`, `;`/`#` comment lines, no
480//! quoting or escapes. `.cnf` has no spec and several dialects, so the `cnf` parser is lenient enough to read `my.cnf`
481//! (MySQL/MariaDB), `openssl.cnf` and the like as they are; where the
482//! dialects disagree it follows MySQL. `[ section ]` headers; `#`
483//! comments anywhere outside quotes, `;` and `%` comments at line start
484//! only; quotes stripped only when they wrap the whole value; MySQL
485//! escapes (`\s`, `\n`, …, any other `\X` kept as written); bare keys
486//! (`skip-networking`) as `true`; no line continuation. Everything else
487//! is a string, and keys stay literal. Variables (`$dir`, `$ENV::HOME`)
488//! are not expanded, and include directives (`!include`, `.include`) are
489//! skipped,
490//! each with a [`Warning`] in the trace:
491//!
492//! ```
493//! # #[cfg(feature = "cnf")]
494//! # fn main() -> Result<(), c4::Error> {
495//! let trace = c4::Loader::new(c4::Options {
496//! sources: vec![("cnf", "!includedir /etc/mysql/conf.d/\n[mysqld]\nport = 3306\nskip-networking\n").into()],
497//! ..c4::Options::default()
498//! })
499//! .trace()?;
500//! let value: c4::Value = trace.value.into();
501//! assert_eq!(value["mysqld"]["port"].as_str(), Some("3306"));
502//! assert_eq!(value["mysqld"]["skip-networking"].as_bool(), Some(true));
503//! assert_eq!(trace.warnings.len(), 1);
504//! # Ok(())
505//! # }
506//! # #[cfg(not(feature = "cnf"))]
507//! # fn main() {}
508//! ```
509
510#[cfg(not(any(
511 feature = "json",
512 feature = "jsonc",
513 feature = "yaml",
514 feature = "toml",
515 feature = "ini",
516 feature = "cnf",
517 feature = "env",
518 feature = "csv",
519 feature = "excel",
520 feature = "ods"
521)))]
522compile_error!(
523 "c4: enable at least one format feature (json, jsonc, yaml, toml, ini, cnf, env, csv, excel, ods)"
524);
525
526mod de;
527mod error;
528mod format;
529mod loader;
530mod options;
531mod ser;
532mod source;
533mod trace;
534pub(crate) mod valid;
535mod value;
536
537pub use error::{Error, Result};
538pub use loader::Loader;
539pub use options::{
540 CustomFormat, CustomLayout, Format, FormatKind, FormatSpec, Options, Order, TableLayout,
541};
542pub use source::Source;
543pub use trace::{SourceRef, Trace, TracedValue, Warning};
544pub use value::Value;
545
546use std::path::{Path, PathBuf};
547
548use serde::de::DeserializeOwned;
549
550/// Load one path with default options — the shortest way in. An
551/// existing file loads as a single file source; anything else is
552/// treated as a folder (a missing path is [`Error::NotFound`]). The
553/// annotated target type decides what you get back:
554///
555/// ```no_run
556/// #[derive(serde::Deserialize)]
557/// struct MyConfig {
558/// host: String,
559/// port: u16,
560/// }
561///
562/// # fn main() -> Result<(), c4::Error> {
563/// let value: c4::Value = c4::load("config")?; // a folder …
564/// let value: c4::Value = c4::load("app.yml")?; // … or one file
565/// let cfg: MyConfig = c4::load("config")?;
566/// # Ok(())
567/// # }
568/// ```
569pub fn load<T: DeserializeOwned>(path: impl Into<PathBuf>) -> Result<T> {
570 Loader::new(Options {
571 sources: vec![Source::Path(path.into())],
572 ..Options::default()
573 })
574 .load()
575}
576
577/// The generic table stage: interpret a plain row table under an
578/// explicit [`TableLayout`] — `&TableLayout::Kv` for
579/// `key,value[,format]` rows (what the csv format feeds by default),
580/// `&TableLayout::Db` for a record grid, or a [`CustomLayout`] callback.
581/// Public so custom table-shaped formats (markdown tables, …) and custom
582/// layouts can lower their input into rows and reuse it; `path` labels
583/// errors. The layout is always passed — there is deliberately no
584/// defaulting variant.
585pub fn parse_table(
586 rows: Vec<Vec<String>>,
587 layout: &TableLayout,
588 path: &Path,
589 options: &Options,
590) -> Result<Value> {
591 format::table::parse(rows, layout, path, options)
592}