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