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, env,
3//! 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//! recursive: true,
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//!
98//! A [`CustomFormat`] is an id, the extensions it claims, and a parser
99//! callback. It goes into `Options.formats` like any built-in — one list,
100//! one claim order — and a string source can name one directly. See
101//! [`CustomFormat`] for a full markdown-pipe-table example.
102//!
103//! ```
104//! use c4::{CustomFormat, Loader, Options};
105//!
106//! # fn main() -> Result<(), c4::Error> {
107//! // a tiny `key value type` table format, lowered to `parse_table`
108//! let kv = CustomFormat::new("kv", ["kv"], |text, path, options| {
109//! let rows = text
110//! .lines()
111//! .filter(|l| !l.trim().is_empty())
112//! .map(|l| l.split_whitespace().map(str::to_owned).collect())
113//! .collect();
114//! c4::parse_table(rows, &c4::TableLayout::Kv, path, options)
115//! });
116//! let value: c4::Value = Loader::new(Options {
117//! sources: vec![
118//! (kv.clone(), "port 1 u16").into(), // earlier …
119//! (kv, "port 8080 u16").into(), // … overridden
120//! (std::collections::BTreeMap::from([("debug", true)]),).into(),
121//! ],
122//! ..Options::default()
123//! })
124//! .load()?;
125//! assert_eq!(value["port"].as_u64(), Some(8080));
126//! assert_eq!(value["debug"].as_bool(), Some(true));
127//! # Ok(())
128//! # }
129//! ```
130//!
131//! # Cargo features
132//!
133//! `default = ["jsonc"]` — deliberately light, one parser dependency; at
134//! least one **format** feature is required (a compile error otherwise).
135//! Value-parser features are pure std (no extra dependencies). Cargo
136//! unions features across the whole build graph, so only applications
137//! should turn format features on.
138//!
139//! | Feature | Enables |
140//! | ------- | ------- |
141//! | `jsonc` *(default)* | JSONC files (comments + trailing commas); also the `jsonc` table cell |
142//! | `yaml` | YAML files |
143//! | `json` | strict JSON files; also the table `json` cell |
144//! | `toml` / `ini` / `env` / `csv` | those file formats |
145//! | `excel` | Excel workbooks (`.xlsx`/`.xlsm`/`.xlsb`/`.xls`) |
146//! | `ods` | OpenDocument spreadsheets (`.ods`) |
147//! | `tree` | tree mode ([`Options::tree`]) |
148//! | `datetime` (= `date` + `time`) | the `dt` table type |
149//! | `date`, `time` | the `date` / `time` table types |
150//! | `ipv4`, `ipv6` | the `ipv4` / `ipv6` table types |
151//! | `inet` (= `ipv4` + `ipv6` + `cidr`), `cidr` | inet / cidr table types |
152//! | `macaddr` (= `macaddr8`), `macaddr8` | MAC table types |
153//! | `uuid` | the `uuid` table type |
154//! | `numeric` | extended table numeric literals (`0x`, `_`, `123n`) |
155//! | `cli` | the `c4` binary (implies all of the above) |
156//!
157//! # File formats
158//!
159//! Format and file extension are separate things: each format claims a set
160//! of default extensions, and both sides are configurable. Extension
161//! matching is case-insensitive; a hidden file `.X` counts as extension
162//! `X` (so `.env` matches `env`). Unclaimed extensions are ignored, and the
163//! **last** claimer of a contested extension wins — which is also how you
164//! reassign one: `vec![Format::Yaml.into(), (Format::Jsonc, ["yml"]).into()]`
165//! makes the jsonc parser read `.yml`. `jsonc` is a JSON superset that also
166//! claims `.json`, so with the default `formats` enabling both `json` and
167//! `jsonc` is redundant (jsonc, added last, wins `.json`).
168//!
169//! | Format | Default extensions | Feature |
170//! | ------- | ------------------ | ------- |
171//! | `jsonc` | `.json`, `.jsonc` | default |
172//! | `yaml` | `.yml`, `.yaml` | `yaml` |
173//! | `json` | `.json` (strict) | `json` |
174//! | `toml` | `.toml` | `toml` |
175//! | `ini` | `.ini` | `ini` |
176//! | `env` | `.env`, `*.env` | `env` |
177//! | `csv` | `.csv` | `csv` |
178//! | `excel` | `.xlsx`, `.xlsm`, `.xlsb`, `.xls` | `excel` |
179//! | `ods` | `.ods` | `ods` |
180//!
181//! # Tree mode
182//!
183//! With `tree: true` (feature `tree`) a folder is not merged — its shape
184//! becomes the config: every subfolder is a key, and every file a key
185//! named after it (extension stripped):
186//!
187//! ```text
188//! config/a/b.json = {"c": 1} -> { "a": { "b": { "c": 1 } },
189//! config/d.json = {"a": 123} "d": { "a": 123 } }
190//! ```
191//!
192//! ```no_run
193//! # fn main() -> Result<(), c4::Error> {
194//! let value: c4::Value = c4::Loader::new(c4::Options {
195//! sources: vec!["./config".into()],
196//! tree: true,
197//! ..c4::Options::default()
198//! })
199//! .load()?;
200//! assert_eq!(value["a"]["b"]["c"].as_i64(), Some(1));
201//! # Ok(())
202//! # }
203//! ```
204//!
205//! The full rules — recursion, key collisions, extension handling — are
206//! on [`Options::tree`] (with [`Options::auto_files`] and
207//! [`Options::ignore_unknown_ext`] for the edge cases).
208//!
209//! # Table formats
210//!
211//! Table files (csv, and each spreadsheet sheet) parse under a
212//! [`TableLayout`]. Each format has a default —
213//! [`Format::default_layout`]: **`kv` for csv, `db` for excel/ods**
214//! (spreadsheets are grids) — overridable per source with a table-source
215//! tuple or per extension in `formats`:
216//!
217//! - **`kv`** (csv default): `key,value[,format]` rows, one config entry
218//! per row.
219//! - **`db`** (spreadsheet default): a record grid — row 1 holds the
220//! keys, row 2 always the
221//! type ids (empty cell = `auto`), every following row is one record;
222//! the file parses to an **array** of objects, so a config sheet full
223//! of game items deserializes straight into a `Vec<Item>`. Empty cells
224//! are omitted from their record. The type row is positional — the
225//! row right after the keys is the type row even when it is entirely
226//! blank (= every column `auto`); it is never skipped as a blank row.
227//! - **a [`CustomLayout`]**: your callback over the raw rows — reshape
228//! them and call [`parse_table`]. A db grid
229//! *without* a type row is the canonical case: insert a row of `auto`
230//! cells after the header and delegate to `db` (see the `xlsx-sheets`
231//! example).
232//!
233//! The layout comes from a table-source tuple or a `formats` entry (the
234//! forms are in the sources example above; details on [`Source`]). The
235//! db layout on a plain csv file loads a record grid straight into a
236//! `Vec<T>` (the `csv-db` example):
237//!
238//! ```no_run
239//! use c4::{Format, Loader, Options};
240//!
241//! #[derive(serde::Deserialize)]
242//! struct Item {
243//! id: u32,
244//! name: String,
245//! price: f64,
246//! }
247//!
248//! # fn main() -> Result<(), c4::Error> {
249//! // items.csv: key row
250//! // id,name,price
251//! // u32,str,f64 type row (a cell may be empty = auto)
252//! // 1,sword,10.5 one record per row
253//! // 2,shield,7
254//! let items: Vec<Item> = Loader::new(Options {
255//! sources: vec![(Format::Csv, "items.csv", "db").into()],
256//! ..Options::default()
257//! })
258//! .load()?;
259//! # Ok(())
260//! # }
261//! ```
262//!
263//! Two db sources do not concatenate: arrays replace like any array.
264//!
265//! Rows map keys to values **positionally** (in `kv`: col 0 = key,
266//! col 1 = value, col 2 = format; in `db`: the type row types its
267//! column). With [`Options::dot_key`] (default on) a dotted key nests in
268//! both layouts — a kv row `a.b,1` gives `{a:{b:1}}`, and a db
269//! `stats.atk` column nests inside each record — and a `name[]` /
270//! `name[<int>]` segment builds an **array** (append / index, suffixes
271//! chain for nested arrays; see [`Options::dot_key`] and the `dot-key`
272//! example). The **format** of a
273//! cell is one of the ids below — the column/row is optional, and a
274//! missing or empty format means `auto`:
275//!
276//! | Cell format | Aliases | Cargo feature | Notes |
277//! | ----------- | ------- | ------------- | ----- |
278//! | `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 |
279//! | `i8` `i16` `i32` `i64` | `int`, `integer` = `i64` | — | signed integers |
280//! | `u8` `u16` `u32` `u64` | `uint` = `u64` | — | unsigned integers |
281//! | `i128` `u128` | — | — | explicit-only — `auto` never guesses them |
282//! | `f32` `f64` | `float`, `double`, `number` = `f64` | — | floats (`f32` rounds through f32 precision) |
283//! | `bool` | `boolean` | — | also accepts `t/f`, `yes/no`, `y/n`, `on/off`, `1/0` (case-insensitive); `auto` only accepts `true`/`false` |
284//! | `str` | `string`, `text` | — | the cell text as-is |
285//! | `dt` | `datetime` | `datetime` | `YYYY-MM-DD`, optional time part |
286//! | `date`, `time` | — | same-named | `YYYY-MM-DD` / `hh:mm:ss[.frac]` |
287//! | `ipv4`, `ipv6` | — | same-named | IP addresses |
288//! | `inet`, `cidr` | — | same-named | PostgreSQL inet/cidr shapes (optional/required netmask) |
289//! | `macaddr`, `macaddr8` | — | same-named | the PostgreSQL MAC spellings |
290//! | `uuid` | — | same-named | hyphenated or bare 32-hex |
291//! | `json`, `jsonc` | — | same-named | a whole document in one cell, parsed by exactly that format's parser |
292//! | `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"]` |
293//! | `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 |
294//!
295//! `array` and `csv` are explicit-only (like `json`/`jsonc`) — `auto`
296//! never produces a list. `array` is always compiled (a native split);
297//! `csv` needs the `csv` feature. Both take an optional, **positional**
298//! suffix after the separator: `array<sep><format>` applies one type id
299//! to every element, and `csv<sep><layout>` picks the inner layout — in
300//! each case naming the suffix means writing the separator too
301//! (`array,i8`, `csv,db`), and the separator is a single character
302//! (ASCII for `csv`). `array<sep><format>` types **every** element the
303//! same; when a list's elements need **different** formats, use a `csv`
304//! cell instead (one `key,value,format` row each: `a,1,i8` / `b,2,i16`).
305//! Only the built-in layout ids `kv`/`db` are nameable in `csv`.
306//!
307//! An id whose feature is off is an unknown format and fails the row;
308//! only `auto` degrades (it just stops guessing). The `numeric` feature
309//! extends every numeric cell with `0x`/`0o`/`0b` radixes, `_`
310//! separators and BigInt-style `123n`.
311//!
312//! The built-in `csv` format is headerless and positional; a header row,
313//! renamed/reordered columns or a transposed layout are a [`CustomFormat`]
314//! that reshapes the file into `key,value,format` rows and calls
315//! [`parse_table`] (see the `csv-header` and `csv-transpose` examples):
316//!
317//! ```
318//! use c4::{CustomFormat, Loader, Options};
319//!
320//! # fn main() -> Result<(), c4::Error> {
321//! let table = CustomFormat::new("kv", ["kv"], |text, path, options| {
322//! let rows = text
323//! .lines()
324//! .filter(|l| !l.trim().is_empty())
325//! .map(|l| l.split_whitespace().map(str::to_owned).collect())
326//! .collect();
327//! c4::parse_table(rows, &c4::TableLayout::Kv, path, options)
328//! });
329//! let value: c4::Value = Loader::new(Options {
330//! sources: vec![(table, "name c4 str\nport 8080 u16\ndebug true bool").into()],
331//! ..Options::default()
332//! })
333//! .load()?;
334//! assert_eq!(value["name"].as_str(), Some("c4"));
335//! assert_eq!(value["port"].as_u64(), Some(8080));
336//! assert_eq!(value["debug"].as_bool(), Some(true));
337//! # Ok(())
338//! # }
339//! ```
340//!
341//! # Spreadsheet formats
342//!
343//! `excel` (`.xlsx`/`.xlsm`/`.xlsb`/`.xls`) and `ods` (`.ods`) read
344//! workbooks as table formats: each sheet is a grid anchored at cell A1,
345//! lowered to rows for the table stage — **db record grids by default**
346//! ([`Format::default_layout`]). Numbers, booleans and date-formatted
347//! cells convert to the text the stage expects (a `dt`/`date`/`time`
348//! column works on real spreadsheet dates), and error messages carry
349//! real spreadsheet row numbers. Both are binary formats, so they load
350//! from files only — a `(Format::Excel, text)` string source is an
351//! error.
352//!
353//! Which sheets are read:
354//!
355//! - `tree: false` (default): exactly the sheet named `config`; a
356//! workbook without one contributes nothing.
357//! - `tree: true`: every sheet becomes a key under the file's key — see
358//! [`Options::tree`].
359//! - Prefixed (`#`/`.`/`_`) and hidden sheets are skipped — see
360//! [`Options::ignore_sheet_prefix`] and
361//! [`Options::ignore_hidden_sheets`].
362//! - A table source that names a sheet (always the 4-tuple) reads
363//! exactly that sheet and merges it under the sheet name as key — see
364//! [`Source`]:
365//!
366//! ```no_run
367//! use c4::{Format, Loader, Options};
368//!
369//! # fn main() -> Result<(), c4::Error> {
370//! // game.xlsx: sheet "items" is a record grid, "settings" is kv rows
371//! let value: c4::Value = Loader::new(Options {
372//! sources: vec![
373//! (Format::Excel, "game.xlsx", "items", "db").into(),
374//! (Format::Excel, "game.xlsx", "settings", "kv").into(),
375//! ],
376//! ..Options::default()
377//! })
378//! .load()?;
379//! assert!(value["items"][0]["id"].as_u64().is_some());
380//! assert!(!value["settings"].is_null());
381//! # Ok(())
382//! # }
383//! ```
384//!
385//! The `xlsx-sheets` example composes five sheets of one workbook this
386//! way, `CustomLayout`s included.
387//!
388//! # Provenance
389//!
390//! [`Loader::trace`] returns a [`TracedValue`] tree that keeps, per leaf,
391//! the source it came from and the format it parsed as — the shape the CLI
392//! `--trace` prints and the fixtures assert. See [`Loader::trace`] and
393//! [`TracedValue`].
394
395#[cfg(not(any(
396 feature = "json",
397 feature = "jsonc",
398 feature = "yaml",
399 feature = "toml",
400 feature = "ini",
401 feature = "env",
402 feature = "csv",
403 feature = "excel",
404 feature = "ods"
405)))]
406compile_error!(
407 "c4: enable at least one format feature (json, jsonc, yaml, toml, ini, env, csv, excel, ods)"
408);
409
410mod de;
411mod error;
412mod format;
413mod loader;
414mod options;
415mod ser;
416mod source;
417mod trace;
418pub(crate) mod valid;
419mod value;
420
421pub use error::{Error, Result};
422pub use loader::Loader;
423pub use options::{
424 CustomFormat, CustomLayout, Format, FormatKind, FormatSpec, Options, Order, TableLayout,
425};
426pub use source::Source;
427pub use trace::{SourceRef, TracedValue};
428pub use value::Value;
429
430use std::path::{Path, PathBuf};
431
432use serde::de::DeserializeOwned;
433
434/// Load one path with default options — the shortest way in. An
435/// existing file loads as a single file source; anything else is
436/// treated as a folder (a missing path is [`Error::NotFound`]). The
437/// annotated target type decides what you get back:
438///
439/// ```no_run
440/// #[derive(serde::Deserialize)]
441/// struct MyConfig {
442/// host: String,
443/// port: u16,
444/// }
445///
446/// # fn main() -> Result<(), c4::Error> {
447/// let value: c4::Value = c4::load("config")?; // a folder …
448/// let value: c4::Value = c4::load("app.yml")?; // … or one file
449/// let cfg: MyConfig = c4::load("config")?;
450/// # Ok(())
451/// # }
452/// ```
453pub fn load<T: DeserializeOwned>(path: impl Into<PathBuf>) -> Result<T> {
454 Loader::new(Options {
455 sources: vec![Source::Path(path.into())],
456 ..Options::default()
457 })
458 .load()
459}
460
461/// The generic table stage: interpret a plain row table under an
462/// explicit [`TableLayout`] — `&TableLayout::Kv` for
463/// `key,value[,format]` rows (what the csv format feeds by default),
464/// `&TableLayout::Db` for a record grid, or a [`CustomLayout`] callback.
465/// Public so custom table-shaped formats (markdown tables, …) and custom
466/// layouts can lower their input into rows and reuse it; `path` labels
467/// errors. The layout is always passed — there is deliberately no
468/// defaulting variant.
469pub fn parse_table(
470 rows: Vec<Vec<String>>,
471 layout: &TableLayout,
472 path: &Path,
473 options: &Options,
474) -> Result<Value> {
475 format::table::parse(rows, layout, path, options)
476}