Skip to main content

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//! What c4 offers is less a parser than a **convention** (in the spirit of
8//! node-config): deterministic override order, deep merge, and a
9//! `key,value[,format]` table rule that lets non-programmers own config in
10//! CSV or Excel/OpenDocument spreadsheets — plus documented custom-format
11//! escape hatches for everything else. If all you need is one simple file
12//! read once, bespoke zero-dependency loading code (your AI writes it) is
13//! lighter than any library; c4 earns its place when a team needs shared
14//! rules.
15//!
16//! The [README] is the quick start; this page is the full reference (and
17//! `CLAUDE.md` in the repo is the exhaustive spec). Most examples below run
18//! without any files — they load in-code string and value sources; only
19//! the `load("config")` snippets, which read the caller's filesystem, are
20//! marked `no_run`.
21//!
22//! [README]: https://github.com/up9cloud/c4#readme
23//!
24//! # Quick start
25//!
26//! One generic [`load`] takes a path — a folder whose files deep-merge, or
27//! a single file — with default options (default format: jsonc). The
28//! annotated target type decides what you get: a dynamic [`Value`] or your
29//! own serde type.
30//!
31//! ```no_run
32//! # fn main() -> Result<(), c4::Error> {
33//! let value: c4::Value = c4::load("config")?;   // a folder …
34//! let one: c4::Value = c4::load("app.json")?;   // … or a single file
35//! let host = value["db"]["host"].as_str().unwrap_or("localhost");
36//! # Ok(())
37//! # }
38//! ```
39//!
40//! For more than one source, or any non-default option, build a [`Loader`]
41//! from [`Options`], as the next section shows.
42//!
43//! # Sources and options
44//!
45//! Everything goes through one plain-data [`Options`]; [`Loader`] has
46//! exactly [`new`](Loader::new), [`load`](Loader::load) and
47//! [`trace`](Loader::trace). You never name [`Source`]: `sources` is a
48//! `Vec<Source>` and each element converts with `.into()` — a path-like
49//! value (`&str`/`String`/`&Path`/`PathBuf`) is a folder/file source, a
50//! `(format, text)` tuple is an in-code string source, a **1-tuple**
51//! `(value,)` wraps any serde type as a typed override (the trailing comma
52//! is what keeps it distinct — see [`Source`]), and a
53//! `(format, path, layout)` / `(format, path, sheet, layout)` tuple is a
54//! **table source** — one csv/excel/ods file read under an explicit
55//! [`TableLayout`]; naming a spreadsheet sheet is always the 4-tuple
56//! (see *Table formats* below).
57//!
58//! ```no_run
59//! use std::path::Path;
60//!
61//! use c4::{Format, Loader, Options};
62//!
63//! #[derive(serde::Serialize)]
64//! struct Overrides {
65//!     debug: bool,
66//! }
67//!
68//! # fn main() -> Result<(), c4::Error> {
69//! let value: c4::Value = Loader::new(Options {
70//!         sources: vec![
71//!             "./config".into(),                              // a folder (or a single file)
72//!             Path::new("/etc/myapp").into(),                 // any path-like type
73//!             "./local.yml".into(),
74//!             ("jsonc", r#"{ "note": "from code" }"#).into(), // string source, by format id
75//!             (Format::Toml, "debug = true").into(),          // string source, by Format
76//!             (Overrides { debug: true },).into(),            // typed override (1-tuple)
77//!             (Format::Csv, "./items.csv", "db").into(),      // table source: file + layout
78//!             (Format::Excel, "./game.xlsx", "drops", "db").into(), // sheet + layout (4-tuple)
79//!         ],
80//!         // which formats read which extensions; the last claimer wins.
81//!         // all conversion forms — id/Format × default/custom exts,
82//!         // optionally + a table layout for every file the entry claims:
83//!         formats: vec![
84//!             "jsonc".into(),                                 // format id, default extensions
85//!             Format::Toml.into(),                            // Format, default extensions
86//!             (Format::Yaml, ["yml", "yaml", "conf"]).into(), // Format + custom extensions
87//!             ("jsonc", ["json", "jsonc"]).into(),            // format id + custom extensions
88//!             (Format::Csv, ["csv"], "db").into(),            // + layout: all csv = record grids
89//!         ],
90//!         recursive: true,
91//!         ..Options::default()
92//!     })
93//!     .load()?;
94//! # Ok(())
95//! # }
96//! ```
97//!
98//! Sources merge in the order given — later overrides earlier — whatever
99//! their kind:
100//!
101//! ```
102//! use c4::{CustomFormat, Loader, Options};
103//!
104//! # fn main() -> Result<(), c4::Error> {
105//! // a tiny `key value type` table format, lowered to `parse_table`
106//! let kv = CustomFormat::new("kv", ["kv"], |text, path, options| {
107//!     let rows = text
108//!         .lines()
109//!         .filter(|l| !l.trim().is_empty())
110//!         .map(|l| l.split_whitespace().map(str::to_owned).collect())
111//!         .collect();
112//!     c4::parse_table(rows, &c4::TableLayout::Kv, path, options)
113//! });
114//! let value: c4::Value = Loader::new(Options {
115//!         sources: vec![
116//!             (kv.clone(), "port 1 u16").into(),                            // earlier …
117//!             (kv, "port 8080 u16").into(),                                 // … overridden
118//!             (std::collections::BTreeMap::from([("debug", true)]),).into(),
119//!         ],
120//!         ..Options::default()
121//!     })
122//!     .load()?;
123//! assert_eq!(value["port"].as_u64(), Some(8080));
124//! assert_eq!(value["debug"].as_bool(), Some(true));
125//! # Ok(())
126//! # }
127//! ```
128//!
129//! Every [`Options`] field is documented on the struct. In brief:
130//! `sources`, `formats`, `recursive`, `flat` (merge-mode subfolder
131//! nesting), `dot_key`, `case_sensitive`, `order` (an [`Order`] or an id
132//! like `"alphabetic".into()`), the tree-mode trio `tree`,
133//! `auto_files`, `ignore_unknown_ext`, and the spreadsheet pair
134//! `ignore_sheet_prefix`, `ignore_hidden_sheets`.
135//!
136//! # Cargo features
137//!
138//! `default = ["jsonc"]` — deliberately light, one parser dependency; at
139//! least one **format** feature is required (a compile error otherwise).
140//! Value-parser features are pure std (no extra dependencies). Cargo
141//! unions features across the whole build graph, so only applications
142//! should turn format features on.
143//!
144//! | Feature | Enables |
145//! | ------- | ------- |
146//! | `jsonc` *(default)* | JSONC files (comments + trailing commas); also the `jsonc` table cell |
147//! | `yaml` | YAML files |
148//! | `json` | strict JSON files; also the table `json` cell |
149//! | `toml` / `ini` / `env` / `csv` | those file formats |
150//! | `excel` | Excel workbooks (`.xlsx`/`.xlsm`/`.xlsb`/`.xls`) |
151//! | `ods` | OpenDocument spreadsheets (`.ods`) |
152//! | `tree` | tree mode ([`Options::tree`]) |
153//! | `datetime` (= `date` + `time`) | the `dt` table type |
154//! | `date`, `time` | the `date` / `time` table types |
155//! | `ipv4`, `ipv6` | the `ipv4` / `ipv6` table types |
156//! | `inet` (= `ipv4` + `ipv6` + `cidr`), `cidr` | inet / cidr table types |
157//! | `macaddr` (= `macaddr8`), `macaddr8` | MAC table types |
158//! | `uuid` | the `uuid` table type |
159//! | `numeric` | extended table numeric literals (`0x`, `_`, `123n`) |
160//! | `cli` | the `c4` binary (implies all of the above) |
161//!
162//! # File formats
163//!
164//! Format and file extension are separate things: each format claims a set
165//! of default extensions, and both sides are configurable. Extension
166//! matching is case-insensitive; a hidden file `.X` counts as extension
167//! `X` (so `.env` matches `env`). Unclaimed extensions are ignored, and the
168//! **last** claimer of a contested extension wins — which is also how you
169//! reassign one: `vec![Format::Yaml.into(), (Format::Jsonc, ["yml"]).into()]`
170//! makes the jsonc parser read `.yml`. `jsonc` is a JSON superset that also
171//! claims `.json`, so with the default `formats` enabling both `json` and
172//! `jsonc` is redundant (jsonc, added last, wins `.json`).
173//!
174//! | Format  | Default extensions | Feature |
175//! | ------- | ------------------ | ------- |
176//! | `jsonc` | `.json`, `.jsonc`  | default |
177//! | `yaml`  | `.yml`, `.yaml`    | `yaml`  |
178//! | `json`  | `.json` (strict)   | `json`  |
179//! | `toml`  | `.toml`            | `toml`  |
180//! | `ini`   | `.ini`             | `ini`   |
181//! | `env`   | `.env`, `*.env`    | `env`   |
182//! | `csv`   | `.csv`             | `csv`   |
183//! | `excel` | `.xlsx`, `.xlsm`, `.xlsb`, `.xls` | `excel` |
184//! | `ods`   | `.ods`             | `ods`   |
185//!
186//! # Merge rules
187//!
188//! 1. Sources merge in the order given; later overrides earlier.
189//! 2. Within a folder, entries load in `order` and deep-merge: objects
190//!    merge recursively, arrays and scalars replace.
191//! 3. Override order between files is decided by **filename alone**, never
192//!    by format: `app.json` and `app.yml` sort by name, so `app.yml` loads
193//!    later and wins. Prefix filenames (`00_a.json`, `01_a.yml`) for
194//!    explicit control.
195//!
196//! # Tree mode
197//!
198//! With `Options { tree: true, .. }` (feature `tree`) a folder is not
199//! merged — its shape becomes the config: every subfolder is a key, and
200//! every file a key named after it (extension stripped):
201//!
202//! ```text
203//! config/a/b.json = {"c": 1}   ->  { "a": { "b": { "c": 1 } },
204//! config/d.json   = {"a": 123}       "d": { "a": 123 } }
205//! ```
206//!
207//! Tree mode is always recursive; `order` decides key collisions (`a.yml`
208//! next to a folder `a/`). Extension-less files are auto-detected from
209//! their content when `auto_files` is set; files with unknown extensions
210//! are skipped unless `ignore_unknown_ext` is `false`.
211//!
212//! # Table formats
213//!
214//! Table files (csv, and each spreadsheet sheet) parse under a
215//! [`TableLayout`]. Each format has a default —
216//! [`Format::default_layout`]: **`kv` for csv, `db` for excel/ods**
217//! (spreadsheets are grids) — overridable per source with a table-source
218//! tuple or per extension in `formats`:
219//!
220//! - **`kv`** (csv default): `key,value[,format]` rows, one config entry
221//!   per row.
222//! - **`db`** (spreadsheet default): a record grid — row 1 holds the
223//!   keys, row 2 always the
224//!   type ids (empty cell = `auto`), every following row is one record;
225//!   the file parses to an **array** of objects, so a config sheet full
226//!   of game items deserializes straight into a `Vec<Item>`. Empty cells
227//!   are omitted from their record.
228//! - **a [`CustomLayout`]**: your callback over the raw rows — reshape
229//!   them and call [`parse_table`]. A db grid
230//!   *without* a type row is the canonical case: insert a row of `auto`
231//!   cells after the header and delegate to `db` (see the `xlsx-sheets`
232//!   example).
233//!
234//! ```text
235//! sources: vec![
236//!     (Format::Csv,   "items.csv", "db").into(),          // layout per file
237//!     (Format::Excel, "game.xlsx", "config", "kv").into(),// sheet + layout (4-tuple)
238//! ]
239//! formats: vec![
240//!     (Format::Csv, ["csv"], "db").into(),   // or per extension: every
241//! ]                                          // claimed csv file is a grid
242//! ```
243//!
244//! The 3-tuple's third element is **always the layout** (it suits csv,
245//! where the file is the table); naming a spreadsheet sheet is always
246//! the 4-tuple, which names the layout explicitly too. Two db sources
247//! do not concatenate: arrays replace like any array.
248//!
249//! Rows map keys to values **positionally** (in `kv`: col 0 = key,
250//! col 1 = value, col 2 = format; in `db`: the type row types its
251//! column). The **format** of a cell is one of the ids below — the
252//! column/row is optional, and a missing or empty format means `auto`:
253//!
254//! | Cell format | Aliases | Cargo feature | Notes |
255//! | ----------- | ------- | ------------- | ----- |
256//! | `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 |
257//! | `i8` `i16` `i32` `i64` | `int`, `integer` = `i64` | — | signed integers |
258//! | `u8` `u16` `u32` `u64` | `uint` = `u64` | — | unsigned integers |
259//! | `i128` `u128` | — | — | explicit-only — `auto` never guesses them |
260//! | `f32` `f64` | `float`, `double`, `number` = `f64` | — | floats (`f32` rounds through f32 precision) |
261//! | `bool` | `boolean` | — | also accepts `t/f`, `yes/no`, `y/n`, `on/off`, `1/0` (case-insensitive); `auto` only accepts `true`/`false` |
262//! | `str` | `string`, `text` | — | the cell text as-is |
263//! | `dt` | `datetime` | `datetime` | `YYYY-MM-DD`, optional time part |
264//! | `date`, `time` | — | same-named | `YYYY-MM-DD` / `hh:mm:ss[.frac]` |
265//! | `ipv4`, `ipv6` | — | same-named | IP addresses |
266//! | `inet`, `cidr` | — | `inet`, `cidr` | PostgreSQL inet/cidr shapes (optional/required netmask) |
267//! | `macaddr`, `macaddr8` | — | same-named | the PostgreSQL MAC spellings |
268//! | `uuid` | — | `uuid` | hyphenated or bare 32-hex |
269//! | `json`, `jsonc` | — | same-named | a whole document in one cell, parsed by exactly that format's parser |
270//!
271//! An id whose feature is off is an unknown format and fails the row;
272//! only `auto` degrades (it just stops guessing). The `numeric` feature
273//! extends every numeric cell with `0x`/`0o`/`0b` radixes, `_`
274//! separators and BigInt-style `123n`.
275//!
276//! The built-in `csv` format is headerless and positional; a header row,
277//! renamed/reordered columns or a transposed layout are a [`CustomFormat`]
278//! that reshapes the file into `key,value,format` rows and calls
279//! [`parse_table`] (see the `csv-header` and `csv-transpose` examples):
280//!
281//! ```
282//! use c4::{CustomFormat, Loader, Options};
283//!
284//! # fn main() -> Result<(), c4::Error> {
285//! let table = CustomFormat::new("kv", ["kv"], |text, path, options| {
286//!     let rows = text
287//!         .lines()
288//!         .filter(|l| !l.trim().is_empty())
289//!         .map(|l| l.split_whitespace().map(str::to_owned).collect())
290//!         .collect();
291//!     c4::parse_table(rows, &c4::TableLayout::Kv, path, options)
292//! });
293//! let value: c4::Value = Loader::new(Options {
294//!         sources: vec![(table, "name c4 str\nport 8080 u16\ndebug true bool").into()],
295//!         ..Options::default()
296//!     })
297//!     .load()?;
298//! assert_eq!(value["name"].as_str(), Some("c4"));
299//! assert_eq!(value["port"].as_u64(), Some(8080));
300//! assert_eq!(value["debug"].as_bool(), Some(true));
301//! # Ok(())
302//! # }
303//! ```
304//!
305//! # Spreadsheet formats
306//!
307//! `excel` (`.xlsx`/`.xlsm`/`.xlsb`/`.xls`) and `ods` (`.ods`)
308//! read workbooks as table formats: each sheet is the same positional
309//! `key,value[,format]` table as csv, anchored at cell A1 (column A =
310//! key, B = value, C = optional type id; error messages carry real
311//! spreadsheet row numbers). Numbers, booleans and date-formatted cells
312//! convert to the text the table stage expects, so a `dt`/`date`/`time`
313//! format column works on real spreadsheet dates.
314//!
315//! Sheets parse as **db record grids by default**
316//! ([`Format::default_layout`]) — name a layout in a table source or a
317//! `formats` entry for anything else. Which sheets are read:
318//!
319//! - `tree: false` (default): exactly the sheet named `config`; every
320//!   other sheet is ignored, and a workbook without a `config` sheet
321//!   contributes nothing — so extra sheets are free working space.
322//! - `tree: true`: every sheet becomes a key under the file's key —
323//!   `a/b.xlsx` with sheets `c`, `d` loads as `{a: {b: {c: …, d: …}}}`.
324//! - Sheets whose name starts with `#`, `.` or `_` are skipped
325//!   ([`Options::ignore_sheet_prefix`]), and so are sheets hidden in the
326//!   workbook ([`Options::ignore_hidden_sheets`]) — both default `true`,
327//!   giving planners draft/scratch space next to live config.
328//!
329//! - A **table source that names a sheet** —
330//!   `(Format::Excel, "game.xlsx", "items", "db").into()` — reads exactly
331//!   that sheet (even a prefixed/hidden one; a missing sheet is an
332//!   error) and merges it **under the sheet name as key**, so several
333//!   sources can each give one sheet of the same workbook its own
334//!   layout. The `xlsx-sheets` example composes five sheets this way.
335//!
336//! Both are binary formats, so they load from files only — a
337//! `(Format::Excel, text)` string source is an error.
338//!
339//! # Custom formats
340//!
341//! A [`CustomFormat`] is an id, the extensions it claims, and a parser
342//! callback. It goes into `Options.formats` like any built-in — one list,
343//! one claim order — and a string source can name one directly. See
344//! [`CustomFormat`] for a full markdown-pipe-table example.
345//!
346//! # Provenance
347//!
348//! [`Loader::trace`] returns a [`TracedValue`] tree that keeps, per leaf,
349//! the source it came from and the format it parsed as — the shape the CLI
350//! `--trace` prints and the fixtures assert. See [`Loader::trace`] and
351//! [`TracedValue`].
352
353#[cfg(not(any(
354    feature = "json",
355    feature = "jsonc",
356    feature = "yaml",
357    feature = "toml",
358    feature = "ini",
359    feature = "env",
360    feature = "csv",
361    feature = "excel",
362    feature = "ods"
363)))]
364compile_error!(
365    "c4: enable at least one format feature (json, jsonc, yaml, toml, ini, env, csv, excel, ods)"
366);
367
368mod de;
369mod error;
370mod format;
371mod loader;
372mod options;
373mod ser;
374mod source;
375mod trace;
376pub(crate) mod valid;
377mod value;
378
379pub use error::{Error, Result};
380pub use loader::Loader;
381pub use options::{
382    CustomFormat, CustomLayout, Format, FormatKind, FormatSpec, Options, Order, TableLayout,
383};
384pub use source::Source;
385pub use trace::{SourceRef, TracedValue};
386pub use value::Value;
387
388use std::path::{Path, PathBuf};
389
390use serde::de::DeserializeOwned;
391
392/// Load one path with default options — the shortest way in. An
393/// existing file loads as a single file source; anything else is
394/// treated as a folder (a missing path is [`Error::NotFound`]). The
395/// annotated target type decides what you get back:
396///
397/// ```no_run
398/// #[derive(serde::Deserialize)]
399/// struct MyConfig {
400///     host: String,
401///     port: u16,
402/// }
403///
404/// # fn main() -> Result<(), c4::Error> {
405/// let value: c4::Value = c4::load("config")?;   // a folder …
406/// let value: c4::Value = c4::load("app.yml")?;  // … or one file
407/// let cfg: MyConfig = c4::load("config")?;
408/// # Ok(())
409/// # }
410/// ```
411pub fn load<T: DeserializeOwned>(path: impl Into<PathBuf>) -> Result<T> {
412    Loader::new(Options {
413        sources: vec![Source::Path(path.into())],
414        ..Options::default()
415    })
416    .load()
417}
418
419/// The generic table stage: interpret a plain row table under an
420/// explicit [`TableLayout`] — `&TableLayout::Kv` for
421/// `key,value[,format]` rows (what the csv format feeds by default),
422/// `&TableLayout::Db` for a record grid, or a [`CustomLayout`] callback.
423/// Public so custom table-shaped formats (markdown tables, …) and custom
424/// layouts can lower their input into rows and reuse it; `path` labels
425/// errors. The layout is always passed — there is deliberately no
426/// defaulting variant.
427pub fn parse_table(
428    rows: Vec<Vec<String>>,
429    layout: &TableLayout,
430    path: &Path,
431    options: &Options,
432) -> Result<Value> {
433    format::table::parse(rows, layout, path, options)
434}