c4/options.rs
1//! The plain-data configuration surface: [`Options`] and every type its
2//! fields are made of — formats and their specs (built-in and custom),
3//! folder order, and the table options.
4
5use std::path::Path;
6
7use crate::{Result, Source, Value};
8
9/// A config file format.
10///
11/// The variants always exist; whether a format can actually be parsed
12/// depends on the matching Cargo feature. Which extensions a format reads
13/// is part of [`FormatSpec`].
14#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
15pub enum Format {
16 Json,
17 Jsonc,
18 Yaml,
19 Toml,
20 Ini,
21 Env,
22 Csv,
23 /// Excel workbooks (`xlsx`/`xlsm`/`xlsb`/`xls`) — a binary
24 /// table-shaped format; file sources only. Feature `excel`.
25 Excel,
26 /// OpenDocument spreadsheets (`ods`) — a binary table-shaped format;
27 /// file sources only. Feature `ods`.
28 Ods,
29}
30
31impl Format {
32 /// Look a format up by its string id (`"json"`, `"jsonc"`, `"yaml"`,
33 /// `"toml"`, `"ini"`, `"env"`, `"csv"`, `"excel"`, `"ods"`).
34 pub fn from_id(id: &str) -> Option<Format> {
35 Some(match id {
36 "json" => Format::Json,
37 "jsonc" => Format::Jsonc,
38 "yaml" => Format::Yaml,
39 "toml" => Format::Toml,
40 "ini" => Format::Ini,
41 "env" => Format::Env,
42 "csv" => Format::Csv,
43 "excel" => Format::Excel,
44 "ods" => Format::Ods,
45 _ => return None,
46 })
47 }
48
49 /// The string id of this format.
50 pub fn id(self) -> &'static str {
51 match self {
52 Format::Json => "json",
53 Format::Jsonc => "jsonc",
54 Format::Yaml => "yaml",
55 Format::Toml => "toml",
56 Format::Ini => "ini",
57 Format::Env => "env",
58 Format::Csv => "csv",
59 Format::Excel => "excel",
60 Format::Ods => "ods",
61 }
62 }
63
64 /// The extensions (without the dot) this format claims by default.
65 ///
66 /// Extension matching is always case-insensitive, and a hidden file
67 /// named `.X` is treated as having extension `X` (so `.env` matches the
68 /// `env` extension).
69 pub fn default_extensions(self) -> &'static [&'static str] {
70 match self {
71 Format::Json => &["json"],
72 Format::Jsonc => &["json", "jsonc"],
73 Format::Yaml => &["yml", "yaml"],
74 Format::Toml => &["toml"],
75 Format::Ini => &["ini"],
76 Format::Env => &["env"],
77 Format::Csv => &["csv"],
78 Format::Excel => &["xlsx", "xlsm", "xlsb", "xls"],
79 Format::Ods => &["ods"],
80 }
81 }
82
83 /// The default [`TableLayout`] of this format: `db` for the
84 /// spreadsheet formats (excel/ods — a sheet is a record grid unless
85 /// told otherwise), `kv` for csv (and, vacuously, for the non-table
86 /// formats, which never consult a layout).
87 pub fn default_layout(self) -> TableLayout {
88 match self {
89 Format::Excel | Format::Ods => TableLayout::Db,
90 _ => TableLayout::Kv,
91 }
92 }
93
94 /// Pair this format with custom extensions.
95 pub fn exts<I, S>(self, extensions: I) -> FormatSpec
96 where
97 I: IntoIterator<Item = S>,
98 S: Into<String>,
99 {
100 FormatSpec {
101 format: FormatKind::Builtin(self),
102 extensions: extensions.into_iter().map(Into::into).collect(),
103 layout: self.default_layout(),
104 }
105 }
106}
107
108/// What a [`FormatSpec`] entry parses with: a built-in format or a
109/// user-defined [`CustomFormat`].
110#[derive(Debug, Clone, PartialEq)]
111pub enum FormatKind {
112 Builtin(Format),
113 Custom(CustomFormat),
114}
115
116/// A format plus the extensions it reads — one entry of [`Options::formats`].
117///
118/// Accepted forms (all `.into()`):
119/// - `Format::Yaml` or `"yaml"` — default extensions
120/// - `(Format::Yaml, ["yml", "conf"])` or `("yaml", ["yml", "conf"])` —
121/// custom extensions
122/// - `(Format::Csv, ["csv"], "db")` — custom extensions **plus a
123/// [`TableLayout`]** (a layout id string, a `TableLayout`, or a
124/// [`CustomLayout`]): every file this entry claims parses under that
125/// layout, in merge mode, tree mode and single-file path sources
126/// alike. Table sources override it; string sources stay `Kv`; a
127/// layout on a non-table format panics at conversion. Without this
128/// form an entry uses the format's default layout
129/// ([`Format::default_layout`]).
130/// - a [`CustomFormat`] — user-defined parser with the extensions it was
131/// built with
132#[derive(Debug, Clone, PartialEq)]
133pub struct FormatSpec {
134 pub(crate) format: FormatKind,
135 /// Extensions without the leading dot.
136 pub(crate) extensions: Vec<String>,
137 /// The table layout for files this entry claims (table formats only).
138 pub(crate) layout: TableLayout,
139}
140
141impl From<Format> for FormatSpec {
142 fn from(format: Format) -> Self {
143 format.exts(format.default_extensions().iter().copied())
144 }
145}
146
147impl From<Format> for FormatKind {
148 fn from(format: Format) -> Self {
149 FormatKind::Builtin(format)
150 }
151}
152
153impl From<CustomFormat> for FormatKind {
154 fn from(custom: CustomFormat) -> Self {
155 FormatKind::Custom(custom)
156 }
157}
158
159impl From<&str> for FormatKind {
160 /// A built-in format id (`"jsonc"`, `"yaml"`, …). Panics on an unknown
161 /// id — this is config-time code. Lets a `(id, text)` string source
162 /// name its format by string.
163 fn from(id: &str) -> Self {
164 FormatKind::Builtin(
165 Format::from_id(id).unwrap_or_else(|| panic!("unknown format id: {id:?}")),
166 )
167 }
168}
169
170impl From<CustomFormat> for FormatSpec {
171 fn from(custom: CustomFormat) -> Self {
172 Self {
173 extensions: custom.extensions.clone(),
174 format: FormatKind::Custom(custom),
175 layout: TableLayout::Kv,
176 }
177 }
178}
179
180impl From<&str> for FormatSpec {
181 /// Panics on an unknown format id — this is config-time code.
182 fn from(id: &str) -> Self {
183 Format::from_id(id)
184 .unwrap_or_else(|| panic!("unknown format id: {id:?}"))
185 .into()
186 }
187}
188
189impl<const N: usize> From<(Format, [&str; N])> for FormatSpec {
190 fn from((format, extensions): (Format, [&str; N])) -> Self {
191 format.exts(extensions)
192 }
193}
194
195impl<const N: usize> From<(&str, [&str; N])> for FormatSpec {
196 /// Panics on an unknown format id — this is config-time code.
197 fn from((id, extensions): (&str, [&str; N])) -> Self {
198 Format::from_id(id)
199 .unwrap_or_else(|| panic!("unknown format id: {id:?}"))
200 .exts(extensions)
201 }
202}
203
204/// In a `formats` entry the third element is always a **layout** (a
205/// string must be a valid layout id — extensions have no sheet meaning).
206/// Panics on unknown ids, and on a layout for a non-table format
207/// (`(Format::Yaml, ["yml"], "db")`) — this is config-time code.
208impl<const N: usize, L: Into<TableLayout>> From<(Format, [&str; N], L)> for FormatSpec {
209 fn from((format, extensions, layout): (Format, [&str; N], L)) -> Self {
210 assert!(
211 matches!(format, Format::Csv | Format::Excel | Format::Ods),
212 "'{}' is not a table format (csv, excel, ods) — table layouts do not apply",
213 format.id()
214 );
215 FormatSpec {
216 layout: layout.into(),
217 ..format.exts(extensions)
218 }
219 }
220}
221
222/// Panics on an unknown format or layout id — this is config-time code.
223impl<const N: usize, L: Into<TableLayout>> From<(&str, [&str; N], L)> for FormatSpec {
224 fn from((id, extensions, layout): (&str, [&str; N], L)) -> Self {
225 let format = Format::from_id(id).unwrap_or_else(|| panic!("unknown format id: {id:?}"));
226 (format, extensions, layout).into()
227 }
228}
229
230/// File load order inside a folder.
231#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
232pub enum Order {
233 /// Subfolders first, then files, each group alphabetic — how directory
234 /// listings are conventionally sorted.
235 #[default]
236 FoldersFirstAlphabetic,
237 /// Pure lexicographic order, folders and files interleaved.
238 Alphabetic,
239 ReverseAlphabetic,
240}
241
242impl Order {
243 /// Look an order up by its string id. Accepts `-` or `_` between words
244 /// and a couple of short aliases:
245 /// `folders_first_alphabetic` (`folders_first`, `default`),
246 /// `alphabetic`, `reverse_alphabetic` (`reverse`).
247 pub fn from_id(id: &str) -> Option<Order> {
248 Some(match id.to_lowercase().replace('-', "_").as_str() {
249 "folders_first_alphabetic" | "folders_first" | "default" => {
250 Order::FoldersFirstAlphabetic
251 }
252 "alphabetic" => Order::Alphabetic,
253 "reverse_alphabetic" | "reverse" => Order::ReverseAlphabetic,
254 _ => return None,
255 })
256 }
257
258 /// The canonical string id of this order.
259 pub fn id(self) -> &'static str {
260 match self {
261 Order::FoldersFirstAlphabetic => "folders_first_alphabetic",
262 Order::Alphabetic => "alphabetic",
263 Order::ReverseAlphabetic => "reverse_alphabetic",
264 }
265 }
266}
267
268impl From<&str> for Order {
269 /// Panics on an unknown id — this is config-time code. See
270 /// [`Order::from_id`] for the accepted spellings.
271 fn from(id: &str) -> Self {
272 Order::from_id(id).unwrap_or_else(|| panic!("unknown order id: {id:?}"))
273 }
274}
275
276/// How the table stage interprets a row grid. Chosen per table source
277/// (`(format, path, layout)` / `(format, path, sheet, layout)` tuples),
278/// per `formats` entry (`(format, [exts], layout)`), or passed
279/// explicitly to [`parse_table`](crate::parse_table); everything else
280/// uses the format's default —
281/// [`Format::default_layout`](crate::Format::default_layout): `kv` for
282/// csv, `db` for excel/ods. Converts from a layout id string
283/// (`"kv"`/`"kvf"`, `"db"`) or a [`CustomLayout`].
284#[derive(Debug, Clone, PartialEq, Default)]
285pub enum TableLayout {
286 /// `key,value[,format]` positional rows — one config entry per row.
287 /// The default for csv.
288 #[default]
289 Kv,
290 /// A database-style grid: the first (non-blank) row holds the keys,
291 /// the second **always** the type ids (an empty cell = `auto`), every
292 /// following row is one record. Parses to an **array** of one object
293 /// per record: `[[a,b],[i8,str],[4,x],[5,y]]` →
294 /// `[{a:4,b:"x"},{a:5,b:"y"}]`. Empty cells are omitted from their
295 /// record (sparse tables give sparse objects). The default for the
296 /// spreadsheet formats (excel/ods). A grid *without* a
297 /// type row is a [`CustomLayout`] that inserts a row of `auto` cells
298 /// after the header and delegates back to `Db` (see the
299 /// `xlsx-sheets` example).
300 Db,
301 /// A user callback over the raw rows — see [`CustomLayout`].
302 Custom(CustomLayout),
303}
304
305impl TableLayout {
306 /// Look a layout up by its string id: `kv` (alias `kvf`) or `db`.
307 pub fn from_id(id: &str) -> Option<TableLayout> {
308 Some(match id.to_lowercase().as_str() {
309 "kv" | "kvf" => TableLayout::Kv,
310 "db" => TableLayout::Db,
311 _ => return None,
312 })
313 }
314
315 /// The string id of this layout (a custom layout reports its own id).
316 pub fn id(&self) -> &str {
317 match self {
318 TableLayout::Kv => "kv",
319 TableLayout::Db => "db",
320 TableLayout::Custom(custom) => &custom.id,
321 }
322 }
323}
324
325impl From<&str> for TableLayout {
326 /// Panics on an unknown id — this is config-time code. See
327 /// [`TableLayout::from_id`] for the accepted spellings.
328 fn from(id: &str) -> Self {
329 TableLayout::from_id(id).unwrap_or_else(|| {
330 panic!("unknown table layout id: {id:?} (valid: kv, db, or a CustomLayout)")
331 })
332 }
333}
334
335impl From<CustomLayout> for TableLayout {
336 fn from(custom: CustomLayout) -> Self {
337 TableLayout::Custom(custom)
338 }
339}
340
341/// The parser callback of a [`CustomLayout`]: `(rows, path, options)`.
342pub(crate) type CustomRowsParser =
343 std::sync::Arc<dyn Fn(Vec<Vec<String>>, &Path, &Options) -> Result<Value> + Send + Sync>;
344
345/// A user-defined table layout: an id and a callback that receives the
346/// lowered rows (`Vec<Vec<String>>` — csv records, or a sheet's cells as
347/// text) and returns any [`Value`]. This is the rows-level escape hatch:
348/// binary formats (spreadsheets) can't go through a [`CustomFormat`]
349/// (which parses text), but one sheet of a workbook can still get fully
350/// custom treatment via
351/// `(Format::Excel, path, sheet, CustomLayout::new(…)).into()`. Most
352/// custom layouts end by reshaping the rows and calling
353/// [`parse_table`](crate::parse_table) (the `xlsx-sheets` example
354/// transposes a column-oriented sheet this way).
355#[derive(Clone)]
356pub struct CustomLayout {
357 pub(crate) id: String,
358 /// `(rows, path, options)` — `path` labels errors. Crate-private:
359 /// build custom layouts through [`CustomLayout::new`].
360 pub(crate) parser: CustomRowsParser,
361}
362
363impl CustomLayout {
364 pub fn new<F>(id: impl Into<String>, parser: F) -> Self
365 where
366 F: Fn(Vec<Vec<String>>, &Path, &Options) -> Result<Value> + Send + Sync + 'static,
367 {
368 Self {
369 id: id.into(),
370 parser: std::sync::Arc::new(parser),
371 }
372 }
373}
374
375impl std::fmt::Debug for CustomLayout {
376 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
377 f.debug_struct("CustomLayout")
378 .field("id", &self.id)
379 .finish_non_exhaustive()
380 }
381}
382
383impl PartialEq for CustomLayout {
384 fn eq(&self, other: &Self) -> bool {
385 self.id == other.id && std::sync::Arc::ptr_eq(&self.parser, &other.parser)
386 }
387}
388
389/// The parser callback of a [`CustomFormat`]: `(text, path, options)`.
390pub(crate) type CustomParser =
391 std::sync::Arc<dyn Fn(&str, &Path, &Options) -> Result<Value> + Send + Sync>;
392
393/// A user-defined format: an id, the extensions it claims, and a parser
394/// callback. It goes into [`Options::formats`] like any built-in format
395/// (`formats: [..the defaults, md.into()]`), so the usual rule applies —
396/// the last claimer of an extension owns it, and a custom format can take
397/// over a built-in extension. Table-shaped custom formats can lower their
398/// file into rows and reuse the generic table stage via
399/// [`parse_table`](crate::parse_table).
400///
401/// A markdown pipe-table as a config format (runs as a doc test — a
402/// string source can name a custom format directly, no files needed):
403///
404/// ```
405/// use c4::{CustomFormat, Loader};
406///
407/// # fn main() -> Result<(), c4::Error> {
408/// let md = CustomFormat::new("md-table", ["md"], |text, path, options| {
409/// let rows: Vec<Vec<String>> = text
410/// .lines()
411/// .map(str::trim)
412/// .filter(|l| l.starts_with('|') && !l.contains("---"))
413/// // markdown tables always start with a header row — dropping
414/// // it here keeps the data rows positional (key,value[,format]),
415/// // exactly what parse_table expects
416/// .skip(1)
417/// .map(|l| {
418/// l.trim_matches('|')
419/// .split('|')
420/// .map(|cell| cell.trim().to_owned())
421/// .collect()
422/// })
423/// .collect();
424/// c4::parse_table(rows, &c4::TableLayout::Kv, path, options)
425/// });
426///
427/// // to read `.md` files instead, push `md` into Options.formats —
428/// // custom formats claim extensions exactly like built-ins do
429/// let value: c4::Value = Loader::new(c4::Options {
430/// sources: vec![(
431/// md,
432/// "| key | value | format |
433/// | ---- | ----- | ------ |
434/// | name | c4 | str |
435/// | port | 8080 | u16 |",
436/// )
437/// .into()],
438/// ..c4::Options::default()
439/// })
440/// .load()?;
441/// assert_eq!(value["name"].as_str(), Some("c4"));
442/// assert_eq!(value["port"].as_u64(), Some(8080));
443/// # Ok(())
444/// # }
445/// ```
446#[derive(Clone)]
447pub struct CustomFormat {
448 pub(crate) id: String,
449 /// Extensions without the leading dot.
450 pub(crate) extensions: Vec<String>,
451 /// `(text, path, options)` — `path` labels errors. Crate-private:
452 /// build custom formats through [`CustomFormat::new`].
453 pub(crate) parser: CustomParser,
454}
455
456impl CustomFormat {
457 pub fn new<I, S, F>(id: impl Into<String>, extensions: I, parser: F) -> Self
458 where
459 I: IntoIterator<Item = S>,
460 S: Into<String>,
461 F: Fn(&str, &Path, &Options) -> Result<Value> + Send + Sync + 'static,
462 {
463 Self {
464 id: id.into(),
465 extensions: extensions.into_iter().map(Into::into).collect(),
466 parser: std::sync::Arc::new(parser),
467 }
468 }
469}
470
471impl std::fmt::Debug for CustomFormat {
472 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
473 f.debug_struct("CustomFormat")
474 .field("id", &self.id)
475 .field("extensions", &self.extensions)
476 .finish_non_exhaustive()
477 }
478}
479
480impl PartialEq for CustomFormat {
481 fn eq(&self, other: &Self) -> bool {
482 self.id == other.id
483 && self.extensions == other.extensions
484 && std::sync::Arc::ptr_eq(&self.parser, &other.parser)
485 }
486}
487
488/// All loader options.
489///
490/// Plain data on purpose: set the fields you care about and take the rest
491/// from `..Options::default()`.
492#[derive(Debug, Clone, PartialEq)]
493pub struct Options {
494 /// The ordered config sources; later sources override earlier ones.
495 /// Default: the `config` folder under the current working directory.
496 /// Every element converts with `.into()` — see [`Source`] for all
497 /// the accepted shapes.
498 ///
499 /// ```no_run
500 /// # fn main() -> Result<(), c4::Error> {
501 /// let value: c4::Value = c4::Loader::new(c4::Options {
502 /// sources: vec![
503 /// "./config".into(), // a folder …
504 /// "./local.yml".into(), // … or a single file
505 /// ("yaml", "debug: true").into(), // in-code text
506 /// (std::collections::BTreeMap::from([("port", 8080)]),).into(),
507 /// ],
508 /// ..c4::Options::default()
509 /// })
510 /// .load()?;
511 /// # Ok(())
512 /// # }
513 /// ```
514 pub sources: Vec<Source>,
515 /// Which formats to read and which extensions each one claims. The
516 /// list carries **no override-order semantics** — it only builds the
517 /// extension→format mapping (if several entries claim the same
518 /// extension, the last entry wins the claim). Override order between
519 /// files is decided by filename alone; see the merge rules in
520 /// README.md. Entry forms are on [`FormatSpec`].
521 ///
522 /// ```
523 /// let options = c4::Options {
524 /// formats: vec![
525 /// "jsonc".into(), // default extensions
526 /// (c4::Format::Yaml, ["yml", "yaml", "conf"]).into(), // custom extensions
527 /// (c4::Format::Csv, ["csv"], "db").into(), // + a table layout
528 /// ],
529 /// ..c4::Options::default()
530 /// };
531 /// assert_eq!(options.formats.len(), 3);
532 /// ```
533 pub formats: Vec<FormatSpec>,
534 /// **Merge mode only** (`tree: false`); folder sources. Scan
535 /// subdirectories too. Default `false`.
536 ///
537 /// ```no_run
538 /// # fn main() -> Result<(), c4::Error> {
539 /// // config/base.json and config/prod/db.json both merge in
540 /// let value: c4::Value = c4::Loader::new(c4::Options {
541 /// recursive: true,
542 /// ..c4::Options::default()
543 /// })
544 /// .load()?;
545 /// # Ok(())
546 /// # }
547 /// ```
548 pub recursive: bool,
549 /// **Merge mode only**, and only meaningful with
550 /// `recursive: true`. `true` (default): subfolder files merge as if
551 /// they sat at the top level — folder names carry no meaning.
552 /// `false`: each subfolder becomes a key and its files merge under
553 /// it. (The *filename* never becomes a key in merge mode; for
554 /// folder-and-filename keys use tree mode.)
555 ///
556 /// ```no_run
557 /// # fn main() -> Result<(), c4::Error> {
558 /// // config/db/a.json = {"host": "x"} — with flat: false it merges
559 /// // under the subfolder's key instead of the top level
560 /// let value: c4::Value = c4::Loader::new(c4::Options {
561 /// recursive: true,
562 /// flat: false,
563 /// ..c4::Options::default()
564 /// })
565 /// .load()?;
566 /// assert_eq!(value["db"]["host"].as_str(), Some("x"));
567 /// # Ok(())
568 /// # }
569 /// ```
570 pub flat: bool,
571 /// **All modes; env and table formats.** Treat dotted keys as nested
572 /// paths: `a.b.c` becomes `{ "a": { "b": { "c": … } } }`.
573 /// Default `true`.
574 ///
575 /// In the table stage this applies to both layouts: the `kv`
576 /// layout's key column, and the `db` layout's key row (a dotted
577 /// column nests inside each record).
578 ///
579 /// A key segment may also end in **array suffixes** — `[]` (append)
580 /// and `[<int>]` (index) groups, chained for nested arrays
581 /// (`grid[0][1]`, one level per group); any other bracket shape
582 /// (`a[x]`, `a[-1]`, `a[]b`, a bare `[]`) keeps the whole segment a
583 /// literal key:
584 ///
585 /// - `name[]` **appends** one new element per occurrence: per kv
586 /// row / env line, and per record for a db column.
587 /// - `name[<int>]` addresses element `<int>`: the same index
588 /// deep-merges into one element and indexes may arrive in any
589 /// order. Skipped indexes leave `Null` gaps — `a[1]` + `a[4]`
590 /// give a five-element array with nulls at 0, 2 and 3;
591 /// deserialize such arrays as `Vec<Option<T>>`.
592 ///
593 /// Suffixes also chain through the dotted path (`a[0].b[].c`) and
594 /// work on keys without dots (`ports[]`). The expansion happens
595 /// within one parse (one file/sheet/string source) — across sources
596 /// arrays still replace like any array. The `dot-key` example tours
597 /// all of it.
598 ///
599 /// ```
600 /// use std::path::Path;
601 ///
602 /// use c4::{Options, TableLayout};
603 ///
604 /// # fn main() -> Result<(), c4::Error> {
605 /// let options = Options::default(); // dot_key: true
606 ///
607 /// // kv layout: the key column nests
608 /// let rows = vec![vec!["a.b".to_string(), "1".to_string()]];
609 /// let value = c4::parse_table(rows, &TableLayout::Kv, Path::new("doc"), &options)?;
610 /// assert_eq!(value["a"]["b"].as_i64(), Some(1));
611 ///
612 /// // db layout: dotted keys nest inside each record
613 /// let rows = vec![
614 /// vec!["a.b".to_string(), "a.c".to_string()], // key row
615 /// vec![String::new(), String::new()], // type row (all auto)
616 /// vec!["1".to_string(), "2".to_string()], // one record
617 /// ];
618 /// let value = c4::parse_table(rows, &TableLayout::Db, Path::new("doc"), &options)?;
619 /// assert_eq!(value[0]["a"]["b"].as_i64(), Some(1));
620 /// assert_eq!(value[0]["a"]["c"].as_i64(), Some(2));
621 ///
622 /// // array suffixes: `[]` appends per row, `[<int>]` indexes
623 /// let rows = vec![
624 /// vec!["tags[]".to_string(), "red".to_string()],
625 /// vec!["tags[]".to_string(), "blue".to_string()],
626 /// vec!["servers[1].host".to_string(), "beta".to_string()],
627 /// vec!["servers[0].host".to_string(), "alpha".to_string()],
628 /// ];
629 /// let value = c4::parse_table(rows, &TableLayout::Kv, Path::new("doc"), &options)?;
630 /// assert_eq!(value["tags"][1].as_str(), Some("blue"));
631 /// assert_eq!(value["servers"][0]["host"].as_str(), Some("alpha"));
632 ///
633 /// // chained suffixes nest; skipped indexes leave null gaps
634 /// let rows = vec![vec!["m[1][0]".to_string(), "9".to_string()]];
635 /// let value = c4::parse_table(rows, &TableLayout::Kv, Path::new("doc"), &options)?;
636 /// assert!(value["m"][0].is_null());
637 /// assert_eq!(value["m"][1][0].as_i64(), Some(9));
638 /// # Ok(())
639 /// # }
640 /// ```
641 pub dot_key: bool,
642 /// **All modes.** Case-sensitive key merging. Default `true`; when
643 /// `false`, keys are normalized to lowercase. (File-extension
644 /// matching is always case-insensitive and unrelated to this
645 /// option.)
646 ///
647 /// ```
648 /// use std::collections::BTreeMap;
649 ///
650 /// # fn main() -> Result<(), c4::Error> {
651 /// let value: c4::Value = c4::Loader::new(c4::Options {
652 /// sources: vec![
653 /// (BTreeMap::from([("PORT", 1)]),).into(),
654 /// (BTreeMap::from([("port", 8080)]),).into(),
655 /// ],
656 /// case_sensitive: false, // "PORT" and "port" are one key
657 /// ..c4::Options::default()
658 /// })
659 /// .load()?;
660 /// assert_eq!(value["port"].as_i64(), Some(8080));
661 /// # Ok(())
662 /// # }
663 /// ```
664 pub case_sensitive: bool,
665 /// **All modes**; folder sources. Load order inside a folder. In
666 /// merge mode it decides which file overrides which; in tree mode it
667 /// decides key collisions (`a.yml` vs a folder `a/`).
668 ///
669 /// ```no_run
670 /// # fn main() -> Result<(), c4::Error> {
671 /// let value: c4::Value = c4::Loader::new(c4::Options {
672 /// order: "alphabetic".into(), // or c4::Order::Alphabetic
673 /// ..c4::Options::default()
674 /// })
675 /// .load()?;
676 /// # Ok(())
677 /// # }
678 /// ```
679 pub order: Order,
680 /// **Mode switch** (requires the `tree` feature; `true` without it
681 /// is `Error::Unsupported`). `false` (default): merge mode — a
682 /// folder's files deep-merge into one value. `true`: tree mode — the
683 /// folder's *shape* becomes the value: every subfolder is a key, and
684 /// every file is a key named after the file (extension stripped)
685 /// holding that file's parsed content — `a/b.json = {c:1}` and
686 /// `d.json = {a:123}` load as `{a: {b: {c: 1}}, d: {a: 123}}`.
687 ///
688 /// The rules, in full:
689 /// - Applies to **folder path sources** only; single-file and string
690 /// sources merge into the root as always.
691 /// - Always recursive — `recursive` and `flat` do not apply, but
692 /// `order` does: entries load in order, and a key collision
693 /// (`a.yml` next to a folder `a/`) deep-merges, so order decides
694 /// the winner.
695 /// - A dotfile whose whole name is its extension (`.env`) keeps the
696 /// full name as its key.
697 /// - Extension handling: a claimed extension parses normally; an
698 /// extension-less file follows [`auto_files`](Options::auto_files);
699 /// any other unclaimed extension follows
700 /// [`ignore_unknown_ext`](Options::ignore_unknown_ext).
701 /// - A spreadsheet workbook parses to an object keyed by sheet name,
702 /// so its sheets become keys under the file's key — `a/b.xlsx`
703 /// with sheets `c`, `d` loads as `{a: {b: {c: …, d: …}}}`.
704 ///
705 /// ```no_run
706 /// # fn main() -> Result<(), c4::Error> {
707 /// // config/a/b.json = {"c": 1} -> {a: {b: {c: 1}}}
708 /// let value: c4::Value = c4::Loader::new(c4::Options {
709 /// tree: true,
710 /// ..c4::Options::default()
711 /// })
712 /// .load()?;
713 /// assert_eq!(value["a"]["b"]["c"].as_i64(), Some(1));
714 /// # Ok(())
715 /// # }
716 /// ```
717 pub tree: bool,
718 /// **Tree mode only.** What to do with a file that has *no*
719 /// extension. `true` (default): read it and guess the type of its
720 /// (trimmed) content with the table `auto` rules — a file containing
721 /// `1.1.1.1` becomes an IPv4 value when the `ipv4` feature is on, a
722 /// string otherwise. `false`: treat it like a file with an unknown
723 /// extension (see [`ignore_unknown_ext`](Options::ignore_unknown_ext)).
724 /// (Named `auto_files` after the table `auto` type id it reuses.)
725 ///
726 /// ```no_run
727 /// # fn main() -> Result<(), c4::Error> {
728 /// // tree mode: config/host is an extension-less file holding "1.1.1.1"
729 /// let value: c4::Value = c4::Loader::new(c4::Options {
730 /// tree: true,
731 /// auto_files: true,
732 /// ..c4::Options::default()
733 /// })
734 /// .load()?;
735 /// assert!(!value["host"].is_null());
736 /// # Ok(())
737 /// # }
738 /// ```
739 pub auto_files: bool,
740 /// **Tree mode only.** What to do with a file whose extension no
741 /// active format claims: skip it (`true`, default) or fail the load
742 /// with `Error::Parse` (`false`). Merge mode always skips such
743 /// files.
744 ///
745 /// ```no_run
746 /// # fn main() -> Result<(), c4::Error> {
747 /// let value: c4::Value = c4::Loader::new(c4::Options {
748 /// tree: true,
749 /// ignore_unknown_ext: false, // a config/*.xyz file now errors
750 /// ..c4::Options::default()
751 /// })
752 /// .load()?;
753 /// # Ok(())
754 /// # }
755 /// ```
756 pub ignore_unknown_ext: bool,
757 /// **Spreadsheet formats (excel/ods) only.** Skip sheets whose name
758 /// starts with `#`, `.` or `_` — draft/scratch space next to live
759 /// config. Default `true`. (A table source that names a sheet
760 /// explicitly bypasses this filter, so a prefixed sheet stays
761 /// loadable on purpose.)
762 ///
763 /// ```no_run
764 /// # fn main() -> Result<(), c4::Error> {
765 /// // tree mode: game.xlsx has sheets "items" and "_draft"; by
766 /// // default "_draft" is skipped — false reads it as a key too
767 /// let value: c4::Value = c4::Loader::new(c4::Options {
768 /// sources: vec!["./game.xlsx".into()],
769 /// tree: true,
770 /// ignore_sheet_prefix: false,
771 /// ..c4::Options::default()
772 /// })
773 /// .load()?;
774 /// assert!(!value["_draft"].is_null());
775 /// # Ok(())
776 /// # }
777 /// ```
778 pub ignore_sheet_prefix: bool,
779 /// **Spreadsheet formats (excel/ods) only.** Skip sheets marked
780 /// hidden in the workbook (Excel `hidden`/`veryHidden`, OpenDocument
781 /// `table:display="false"`). Default `true`. (A table source that
782 /// names a sheet explicitly bypasses this filter.)
783 ///
784 /// ```no_run
785 /// # fn main() -> Result<(), c4::Error> {
786 /// // the workbook's `config` sheet is marked hidden — read it anyway
787 /// let value: c4::Value = c4::Loader::new(c4::Options {
788 /// sources: vec!["./game.xlsx".into()],
789 /// ignore_hidden_sheets: false,
790 /// ..c4::Options::default()
791 /// })
792 /// .load()?;
793 /// # Ok(())
794 /// # }
795 /// ```
796 pub ignore_hidden_sheets: bool,
797}
798
799impl Default for Options {
800 fn default() -> Self {
801 Self {
802 sources: vec![Source::Path("config".into())],
803 formats: enabled_formats(),
804 recursive: false,
805 flat: true,
806 dot_key: true,
807 case_sensitive: true,
808 order: Order::default(),
809 tree: false,
810 auto_files: true,
811 ignore_unknown_ext: true,
812 ignore_sheet_prefix: true,
813 ignore_hidden_sheets: true,
814 }
815 }
816}
817
818/// Every format compiled into this build with its default extensions.
819/// Later entries win contested extension claims, so `jsonc` (a JSON
820/// superset) takes `.json` over strict `json` when both are enabled.
821#[allow(clippy::vec_init_then_push)] // every push is cfg-gated on its feature
822fn enabled_formats() -> Vec<FormatSpec> {
823 let mut formats = Vec::new();
824 #[cfg(feature = "json")]
825 formats.push(Format::Json.into());
826 #[cfg(feature = "jsonc")]
827 formats.push(Format::Jsonc.into());
828 #[cfg(feature = "yaml")]
829 formats.push(Format::Yaml.into());
830 #[cfg(feature = "toml")]
831 formats.push(Format::Toml.into());
832 #[cfg(feature = "ini")]
833 formats.push(Format::Ini.into());
834 #[cfg(feature = "env")]
835 formats.push(Format::Env.into());
836 #[cfg(feature = "csv")]
837 formats.push(Format::Csv.into());
838 #[cfg(feature = "excel")]
839 formats.push(Format::Excel.into());
840 #[cfg(feature = "ods")]
841 formats.push(Format::Ods.into());
842 formats
843}