Skip to main content

c4/
source.rs

1//! Config sources: a filesystem path (folder or single file), an in-code
2//! string (built-in or custom format), or an in-code serde value.
3//!
4//! You rarely name [`Source`] directly. Build the `sources` list as a
5//! plain `Vec<Source>` and convert each element with `.into()` (the `From`
6//! impls below): a path-like value is a folder/file source, a
7//! `(format, text)` tuple is a string source, and a 1-tuple `(value,)` is
8//! a typed serde override.
9
10use std::path::{Path, PathBuf};
11
12use crate::options::{FormatKind, TableLayout};
13use crate::{Format, Value};
14
15/// One config source. Sources merge in order — later overrides earlier.
16///
17/// Construct sources by conversion, not by hand:
18/// - a path-like value (`&str`, `String`, `&Path`, `PathBuf`) becomes
19///   [`Source::Path`] — loaded as a folder or a single file, detected at
20///   load time;
21/// - a `(format, text)` tuple becomes [`Source::String`] — the format is a
22///   [`Format`](crate::Format), a format-id string (`"jsonc"`), or a
23///   [`CustomFormat`](crate::CustomFormat);
24/// - a **1-tuple** `(value,)` wraps any `Serialize` type as a typed
25///   override — the single-element tuple keeps it distinct from the
26///   conversions above (a blanket `From<impl Serialize>` would overlap
27///   them, since `&str`/`String`/tuples are all `Serialize`);
28/// - a 3-tuple `(format, path, layout)` or 4-tuple
29///   `(format, path, sheet, layout)` becomes [`Source::Table`] — one
30///   **file** of a table format (csv, excel, ods) read with the given
31///   [`TableLayout`]. The 3-tuple's third element is always the layout
32///   (it suits csv — the file is the table); naming a spreadsheet sheet
33///   is always the 4-tuple.
34///
35/// So one `Options.sources` `vec![…]` can mix all of these kinds.
36#[derive(Debug, Clone, PartialEq)]
37pub enum Source {
38    /// A filesystem path — a folder whose files deep-merge, or a single
39    /// file. Which one is decided at load time (`is_dir` / `is_file`); a
40    /// path that is neither is [`Error::NotFound`](crate::Error::NotFound).
41    /// Inside a folder, a file whose extension no format in
42    /// [`Options::formats`](crate::Options::formats) claims is skipped;
43    /// a single-file source naming such a file is
44    /// [`Error::Parse`](crate::Error::Parse) — you asked for that file —
45    /// and the message says how to fix it: which Cargo feature enables
46    /// the format that reads that extension, or that the format is
47    /// missing from `formats`.
48    Path(PathBuf),
49    /// An in-code string; its format may be a built-in or a
50    /// [`CustomFormat`](crate::CustomFormat) (no `formats` registration
51    /// needed — the source names its parser directly).
52    String { format: FormatKind, content: String },
53    /// An in-code serde value (from a 1-tuple `(value,)` source) — already
54    /// converted to a [`Value`], or the serialization error to report at
55    /// load time.
56    Value(std::result::Result<Value, String>),
57    /// One **file** of a table format (csv, excel, ods) read with an
58    /// explicit [`TableLayout`] (from a `(format, path, layout)` /
59    /// `(format, path, sheet, layout)` tuple). A non-file path and a
60    /// non-table format are [`Error::Parse`](crate::Error::Parse) (the
61    /// path error hints that in-code text belongs in a string source). `sheet` (spreadsheets only;
62    /// naming one on csv is an error) reads exactly that sheet —
63    /// bypassing the `ignore_commented_sheetnames` / `ignore_hidden_sheets`
64    /// filters, erroring when it is missing — and merges its value
65    /// **under the sheet name as key**, so several sources can read
66    /// different sheets of one workbook without clobbering each other.
67    Table {
68        path: PathBuf,
69        format: Format,
70        sheet: Option<String>,
71        layout: TableLayout,
72    },
73}
74
75impl From<&str> for Source {
76    fn from(path: &str) -> Self {
77        Source::Path(PathBuf::from(path))
78    }
79}
80
81impl From<String> for Source {
82    fn from(path: String) -> Self {
83        Source::Path(PathBuf::from(path))
84    }
85}
86
87impl From<&Path> for Source {
88    fn from(path: &Path) -> Self {
89        Source::Path(path.to_path_buf())
90    }
91}
92
93impl From<PathBuf> for Source {
94    fn from(path: PathBuf) -> Self {
95        Source::Path(path)
96    }
97}
98
99/// A `(format, text)` tuple is an in-code string source. `format` is a
100/// [`Format`](crate::Format), a format-id `&str`, or a
101/// [`CustomFormat`](crate::CustomFormat); `text` is anything `Into<String>`.
102impl<F, S> From<(F, S)> for Source
103where
104    F: Into<FormatKind>,
105    S: Into<String>,
106{
107    fn from((format, content): (F, S)) -> Self {
108        Source::String {
109            format: format.into(),
110            content: content.into(),
111        }
112    }
113}
114
115/// A **1-tuple** `(value,)` is a typed serde override — the value is
116/// serialized through the crate serializer (no format parser; works with
117/// any `#[derive(Serialize)]` type). A serialization failure (e.g. a map
118/// with non-string keys) surfaces at load time as
119/// [`Error::Parse`](crate::Error::Parse); a `Null` root (e.g. `None`)
120/// contributes nothing.
121///
122/// A struct field or map entry whose value is **`None` is left out**, so
123/// it overrides nothing: an `Option` field you did not set (a CLI flag
124/// that was not given) keeps the earlier sources' value. An explicit null
125/// — `()`, `serde_json::Value::Null`, [`Value::Null`] — still overrides.
126/// `None` inside a sequence stays a positional null.
127///
128/// The single-element tuple is what keeps this distinct: `&str`, `String`,
129/// tuples and paths are all themselves `Serialize`, so a blanket
130/// `From<impl Serialize>` would overlap the conversions above — but a
131/// 1-tuple `(T,)` is a type of its own. Mind the trailing comma:
132///
133/// ```
134/// #[derive(serde::Serialize)]
135/// struct Overrides {
136///     debug: bool,
137/// }
138///
139/// # fn main() -> Result<(), c4::Error> {
140/// let value: c4::Value = c4::Loader::new(c4::Options {
141///         sources: vec![(Overrides { debug: true },).into()],
142///         ..c4::Options::default()
143///     })
144///     .load()?;
145/// assert_eq!(value["debug"].as_bool(), Some(true));
146/// # Ok(())
147/// # }
148/// ```
149impl<T: serde::Serialize> From<(T,)> for Source {
150    fn from((value,): (T,)) -> Self {
151        Source::Value(
152            value
153                .serialize(crate::ser::ValueSerializer)
154                .map_err(|e| e.to_string()),
155        )
156    }
157}
158
159/// A `(format, path, layout)` 3-tuple is a table source: one file, read
160/// with that [`TableLayout`] (a `TableLayout`, a
161/// [`CustomLayout`](crate::CustomLayout), or a layout-id `&str` —
162/// `"kv"`/`"kvf"`, `"db"`; an unknown id **panics**, this is config-time
163/// code). The third element is **always the layout** — the 3-tuple suits
164/// csv, where the file is the table. To name a spreadsheet sheet use the
165/// 4-tuple, which names the layout explicitly too.
166impl<P: Into<PathBuf>, L: Into<TableLayout>> From<(Format, P, L)> for Source {
167    fn from((format, path, layout): (Format, P, L)) -> Self {
168        Source::Table {
169            path: path.into(),
170            format,
171            sheet: None,
172            layout: layout.into(),
173        }
174    }
175}
176
177/// Like the `(Format, path, layout)` tuple, with the format named by its
178/// id string. Panics on an unknown format id — this is config-time code.
179impl<P: Into<PathBuf>, L: Into<TableLayout>> From<(&str, P, L)> for Source {
180    fn from((id, path, layout): (&str, P, L)) -> Self {
181        let format = Format::from_id(id).unwrap_or_else(|| panic!("unknown format id: {id:?}"));
182        (format, path, layout).into()
183    }
184}
185
186/// A `(format, path, sheet, layout)` 4-tuple is a table source that reads
187/// exactly one sheet of a workbook (skipping the sheet-ignore filters)
188/// and merges it under the sheet name as key.
189impl<P, S, L> From<(Format, P, S, L)> for Source
190where
191    P: Into<PathBuf>,
192    S: Into<String>,
193    L: Into<TableLayout>,
194{
195    fn from((format, path, sheet, layout): (Format, P, S, L)) -> Self {
196        Source::Table {
197            path: path.into(),
198            format,
199            sheet: Some(sheet.into()),
200            layout: layout.into(),
201        }
202    }
203}
204
205/// Like the `(Format, path, sheet, layout)` tuple, with the format named
206/// by its id string. Panics on an unknown format id — this is config-time
207/// code.
208impl<P, S, L> From<(&str, P, S, L)> for Source
209where
210    P: Into<PathBuf>,
211    S: Into<String>,
212    L: Into<TableLayout>,
213{
214    fn from((id, path, sheet, layout): (&str, P, S, L)) -> Self {
215        let format = Format::from_id(id).unwrap_or_else(|| panic!("unknown format id: {id:?}"));
216        (format, path, sheet, layout).into()
217    }
218}