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::Value;
13use crate::options::FormatKind;
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///
29/// So one `Options.sources` `vec![…]` can mix all three kinds.
30#[derive(Debug, Clone, PartialEq)]
31pub enum Source {
32 /// A filesystem path — a folder whose files deep-merge, or a single
33 /// file. Which one is decided at load time (`is_dir` / `is_file`); a
34 /// path that is neither is [`Error::NotFound`](crate::Error::NotFound).
35 Path(PathBuf),
36 /// An in-code string; its format may be a built-in or a
37 /// [`CustomFormat`](crate::CustomFormat) (no `formats` registration
38 /// needed — the source names its parser directly).
39 String { format: FormatKind, content: String },
40 /// An in-code serde value (from a 1-tuple `(value,)` source) — already
41 /// converted to a [`Value`], or the serialization error to report at
42 /// load time.
43 Value(std::result::Result<Value, String>),
44}
45
46impl From<&str> for Source {
47 fn from(path: &str) -> Self {
48 Source::Path(PathBuf::from(path))
49 }
50}
51
52impl From<String> for Source {
53 fn from(path: String) -> Self {
54 Source::Path(PathBuf::from(path))
55 }
56}
57
58impl From<&Path> for Source {
59 fn from(path: &Path) -> Self {
60 Source::Path(path.to_path_buf())
61 }
62}
63
64impl From<PathBuf> for Source {
65 fn from(path: PathBuf) -> Self {
66 Source::Path(path)
67 }
68}
69
70/// A `(format, text)` tuple is an in-code string source. `format` is a
71/// [`Format`](crate::Format), a format-id `&str`, or a
72/// [`CustomFormat`](crate::CustomFormat); `text` is anything `Into<String>`.
73impl<F, S> From<(F, S)> for Source
74where
75 F: Into<FormatKind>,
76 S: Into<String>,
77{
78 fn from((format, content): (F, S)) -> Self {
79 Source::String {
80 format: format.into(),
81 content: content.into(),
82 }
83 }
84}
85
86/// A **1-tuple** `(value,)` is a typed serde override — the value is
87/// serialized through the crate serializer (no format parser; works with
88/// any `#[derive(Serialize)]` type). A serialization failure (e.g. a map
89/// with non-string keys) surfaces at load time as
90/// [`Error::Parse`](crate::Error::Parse); a `Null` root (e.g. `None`)
91/// contributes nothing.
92///
93/// The single-element tuple is what keeps this distinct: `&str`, `String`,
94/// tuples and paths are all themselves `Serialize`, so a blanket
95/// `From<impl Serialize>` would overlap the conversions above — but a
96/// 1-tuple `(T,)` is a type of its own. Mind the trailing comma:
97///
98/// ```
99/// #[derive(serde::Serialize)]
100/// struct Overrides {
101/// debug: bool,
102/// }
103///
104/// # fn main() -> Result<(), c4::Error> {
105/// let value: c4::Value = c4::Loader::new(c4::Options {
106/// sources: vec![(Overrides { debug: true },).into()],
107/// ..c4::Options::default()
108/// })
109/// .load()?;
110/// assert_eq!(value["debug"].as_bool(), Some(true));
111/// # Ok(())
112/// # }
113/// ```
114impl<T: serde::Serialize> From<(T,)> for Source {
115 fn from((value,): (T,)) -> Self {
116 Source::Value(
117 value
118 .serialize(crate::ser::ValueSerializer)
119 .map_err(|e| e.to_string()),
120 )
121 }
122}