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 Path(PathBuf),
42 /// An in-code string; its format may be a built-in or a
43 /// [`CustomFormat`](crate::CustomFormat) (no `formats` registration
44 /// needed — the source names its parser directly).
45 String { format: FormatKind, content: String },
46 /// An in-code serde value (from a 1-tuple `(value,)` source) — already
47 /// converted to a [`Value`], or the serialization error to report at
48 /// load time.
49 Value(std::result::Result<Value, String>),
50 /// One **file** of a table format (csv, excel, ods) read with an
51 /// explicit [`TableLayout`] (from a `(format, path, layout)` /
52 /// `(format, path, sheet, layout)` tuple). A non-file path and a
53 /// non-table format are [`Error::Parse`](crate::Error::Parse) (the
54 /// path error hints that in-code text belongs in a string source). `sheet` (spreadsheets only;
55 /// naming one on csv is an error) reads exactly that sheet —
56 /// bypassing the `ignore_sheet_prefix` / `ignore_hidden_sheets`
57 /// filters, erroring when it is missing — and merges its value
58 /// **under the sheet name as key**, so several sources can read
59 /// different sheets of one workbook without clobbering each other.
60 Table {
61 path: PathBuf,
62 format: Format,
63 sheet: Option<String>,
64 layout: TableLayout,
65 },
66}
67
68impl From<&str> for Source {
69 fn from(path: &str) -> Self {
70 Source::Path(PathBuf::from(path))
71 }
72}
73
74impl From<String> for Source {
75 fn from(path: String) -> Self {
76 Source::Path(PathBuf::from(path))
77 }
78}
79
80impl From<&Path> for Source {
81 fn from(path: &Path) -> Self {
82 Source::Path(path.to_path_buf())
83 }
84}
85
86impl From<PathBuf> for Source {
87 fn from(path: PathBuf) -> Self {
88 Source::Path(path)
89 }
90}
91
92/// A `(format, text)` tuple is an in-code string source. `format` is a
93/// [`Format`](crate::Format), a format-id `&str`, or a
94/// [`CustomFormat`](crate::CustomFormat); `text` is anything `Into<String>`.
95impl<F, S> From<(F, S)> for Source
96where
97 F: Into<FormatKind>,
98 S: Into<String>,
99{
100 fn from((format, content): (F, S)) -> Self {
101 Source::String {
102 format: format.into(),
103 content: content.into(),
104 }
105 }
106}
107
108/// A **1-tuple** `(value,)` is a typed serde override — the value is
109/// serialized through the crate serializer (no format parser; works with
110/// any `#[derive(Serialize)]` type). A serialization failure (e.g. a map
111/// with non-string keys) surfaces at load time as
112/// [`Error::Parse`](crate::Error::Parse); a `Null` root (e.g. `None`)
113/// contributes nothing.
114///
115/// The single-element tuple is what keeps this distinct: `&str`, `String`,
116/// tuples and paths are all themselves `Serialize`, so a blanket
117/// `From<impl Serialize>` would overlap the conversions above — but a
118/// 1-tuple `(T,)` is a type of its own. Mind the trailing comma:
119///
120/// ```
121/// #[derive(serde::Serialize)]
122/// struct Overrides {
123/// debug: bool,
124/// }
125///
126/// # fn main() -> Result<(), c4::Error> {
127/// let value: c4::Value = c4::Loader::new(c4::Options {
128/// sources: vec![(Overrides { debug: true },).into()],
129/// ..c4::Options::default()
130/// })
131/// .load()?;
132/// assert_eq!(value["debug"].as_bool(), Some(true));
133/// # Ok(())
134/// # }
135/// ```
136impl<T: serde::Serialize> From<(T,)> for Source {
137 fn from((value,): (T,)) -> Self {
138 Source::Value(
139 value
140 .serialize(crate::ser::ValueSerializer)
141 .map_err(|e| e.to_string()),
142 )
143 }
144}
145
146/// A `(format, path, layout)` 3-tuple is a table source: one file, read
147/// with that [`TableLayout`] (a `TableLayout`, a
148/// [`CustomLayout`](crate::CustomLayout), or a layout-id `&str` —
149/// `"kv"`/`"kvf"`, `"db"`; an unknown id **panics**, this is config-time
150/// code). The third element is **always the layout** — the 3-tuple suits
151/// csv, where the file is the table. To name a spreadsheet sheet use the
152/// 4-tuple, which names the layout explicitly too.
153impl<P: Into<PathBuf>, L: Into<TableLayout>> From<(Format, P, L)> for Source {
154 fn from((format, path, layout): (Format, P, L)) -> Self {
155 Source::Table {
156 path: path.into(),
157 format,
158 sheet: None,
159 layout: layout.into(),
160 }
161 }
162}
163
164/// Like the `(Format, path, layout)` tuple, with the format named by its
165/// id string. Panics on an unknown format id — this is config-time code.
166impl<P: Into<PathBuf>, L: Into<TableLayout>> From<(&str, P, L)> for Source {
167 fn from((id, path, layout): (&str, P, L)) -> Self {
168 let format = Format::from_id(id).unwrap_or_else(|| panic!("unknown format id: {id:?}"));
169 (format, path, layout).into()
170 }
171}
172
173/// A `(format, path, sheet, layout)` 4-tuple is a table source that reads
174/// exactly one sheet of a workbook (skipping the sheet-ignore filters)
175/// and merges it under the sheet name as key.
176impl<P, S, L> From<(Format, P, S, L)> for Source
177where
178 P: Into<PathBuf>,
179 S: Into<String>,
180 L: Into<TableLayout>,
181{
182 fn from((format, path, sheet, layout): (Format, P, S, L)) -> Self {
183 Source::Table {
184 path: path.into(),
185 format,
186 sheet: Some(sheet.into()),
187 layout: layout.into(),
188 }
189 }
190}
191
192/// Like the `(Format, path, sheet, layout)` tuple, with the format named
193/// by its id string. Panics on an unknown format id — this is config-time
194/// code.
195impl<P, S, L> From<(&str, P, S, L)> for Source
196where
197 P: Into<PathBuf>,
198 S: Into<String>,
199 L: Into<TableLayout>,
200{
201 fn from((id, path, sheet, layout): (&str, P, S, L)) -> Self {
202 let format = Format::from_id(id).unwrap_or_else(|| panic!("unknown format id: {id:?}"));
203 (format, path, sheet, layout).into()
204 }
205}