c4/source.rs
1//! Config sources: folders, single files, in-code strings (built-in or
2//! custom format) and in-code serde values.
3
4use std::path::PathBuf;
5
6use crate::options::FormatKind;
7use crate::{Value, ser};
8
9/// One config source. Sources merge in order — later overrides earlier.
10#[derive(Debug, Clone, PartialEq)]
11pub enum Source {
12 Folder(PathBuf),
13 File(PathBuf),
14 /// An in-code string; its format may be a built-in or a
15 /// [`CustomFormat`] (no `formats` registration needed — the source
16 /// names its parser directly).
17 String {
18 format: FormatKind,
19 content: String,
20 },
21 /// An in-code serde value ([`Source::value`]) — already converted to
22 /// a [`Value`], or the serialization error to report at load time.
23 Value(std::result::Result<Value, String>),
24}
25
26impl Source {
27 /// Accepts anything path-like: `&str`, `String`, `&Path`, `PathBuf`.
28 pub fn folder(path: impl Into<PathBuf>) -> Self {
29 Source::Folder(path.into())
30 }
31
32 /// Accepts anything path-like: `&str`, `String`, `&Path`, `PathBuf`.
33 pub fn file(path: impl Into<PathBuf>) -> Self {
34 Source::File(path.into())
35 }
36
37 /// An in-code config string — the hook for overriding values
38 /// manually. Takes a [`Format`] or a [`CustomFormat`].
39 pub fn string(format: impl Into<FormatKind>, content: impl Into<String>) -> Self {
40 Source::String {
41 format: format.into(),
42 content: content.into(),
43 }
44 }
45
46 /// An in-code serde value — typed overrides without going through a
47 /// format parser (works with any `#[derive(Serialize)]` type, no
48 /// format feature needed). A serialization failure (e.g. a map with
49 /// non-string keys) surfaces at load time; a `Null` root (e.g.
50 /// `None`) contributes nothing, like every other source.
51 ///
52 /// ```
53 /// #[derive(serde::Serialize)]
54 /// struct Overrides {
55 /// debug: bool,
56 /// }
57 ///
58 /// # fn main() -> Result<(), c4::Error> {
59 /// let value: c4::Value = c4::Loader::new(c4::Options {
60 /// sources: vec![c4::Source::value(Overrides { debug: true })],
61 /// ..c4::Options::default()
62 /// })
63 /// .load()?;
64 /// assert_eq!(value["debug"].as_bool(), Some(true));
65 /// # Ok(())
66 /// # }
67 /// ```
68 pub fn value(value: impl serde::Serialize) -> Self {
69 Source::Value(
70 value
71 .serialize(ser::ValueSerializer)
72 .map_err(|e| e.to_string()),
73 )
74 }
75}