|
| 1 | +use std::{borrow::Cow, error::Error, fmt}; |
| 2 | + |
| 3 | +use crate::{ConfigurationBuilder, Source}; |
| 4 | + |
| 5 | +/// A [`Source`] containing raw INI data. |
| 6 | +#[derive(Clone)] |
| 7 | +pub struct IniSource<'a> { |
| 8 | + contents: Cow<'a, str>, |
| 9 | + allow_secrets: bool, |
| 10 | +} |
| 11 | + |
| 12 | +impl<'a> IniSource<'a> { |
| 13 | + /// Creates a [`Source`] containing raw INI data. |
| 14 | + pub fn new(contents: impl Into<Cow<'a, str>>) -> Self { |
| 15 | + Self { |
| 16 | + contents: contents.into(), |
| 17 | + allow_secrets: false, |
| 18 | + } |
| 19 | + } |
| 20 | + |
| 21 | + /// Allows this source to contain secrets. |
| 22 | + pub fn allow_secrets(mut self) -> Self { |
| 23 | + self.allow_secrets = true; |
| 24 | + self |
| 25 | + } |
| 26 | +} |
| 27 | + |
| 28 | +impl<T: ConfigurationBuilder> Source<T> for IniSource<'_> { |
| 29 | + fn allows_secrets(&self) -> bool { |
| 30 | + self.allow_secrets |
| 31 | + } |
| 32 | + |
| 33 | + fn provide(&self) -> Result<T, Box<dyn Error + Sync + Send>> { |
| 34 | + Ok(serde_ini_0_2::from_str(&self.contents)?) |
| 35 | + } |
| 36 | +} |
| 37 | + |
| 38 | +impl fmt::Debug for IniSource<'_> { |
| 39 | + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { |
| 40 | + f.debug_struct("IniSource") |
| 41 | + .field("allow_secrets", &self.allow_secrets) |
| 42 | + .finish_non_exhaustive() |
| 43 | + } |
| 44 | +} |
| 45 | + |
| 46 | +#[cfg(test)] |
| 47 | +mod tests { |
| 48 | + use confik_macros::Configuration; |
| 49 | + |
| 50 | + use super::*; |
| 51 | + |
| 52 | + #[derive(Debug, PartialEq, Eq, serde::Deserialize, Configuration)] |
| 53 | + struct TestConfig { |
| 54 | + value: usize, |
| 55 | + } |
| 56 | + |
| 57 | + #[test] |
| 58 | + fn provides_ini_data() { |
| 59 | + let source = IniSource::new("value = 42\n"); |
| 60 | + |
| 61 | + let config = |
| 62 | + <IniSource<'_> as Source<<TestConfig as crate::Configuration>::Builder>>::provide( |
| 63 | + &source, |
| 64 | + ) |
| 65 | + .unwrap() |
| 66 | + .try_build() |
| 67 | + .unwrap(); |
| 68 | + |
| 69 | + assert_eq!(config, TestConfig { value: 42 }); |
| 70 | + } |
| 71 | + |
| 72 | + #[test] |
| 73 | + fn propagates_parse_errors() { |
| 74 | + let source = IniSource::new("value\n"); |
| 75 | + |
| 76 | + let err = |
| 77 | + match <IniSource<'_> as Source<<TestConfig as crate::Configuration>::Builder>>::provide( |
| 78 | + &source, |
| 79 | + ) { |
| 80 | + Ok(_) => panic!("INI parsing should fail"), |
| 81 | + Err(err) => err, |
| 82 | + }; |
| 83 | + |
| 84 | + assert!(!err.to_string().is_empty()); |
| 85 | + } |
| 86 | + |
| 87 | + #[test] |
| 88 | + fn allow_secrets_enables_secret_loading() { |
| 89 | + let source = IniSource::new("value = 42\n").allow_secrets(); |
| 90 | + |
| 91 | + assert!(<IniSource<'_> as Source< |
| 92 | + <TestConfig as crate::Configuration>::Builder, |
| 93 | + >>::allows_secrets(&source)); |
| 94 | + } |
| 95 | +} |
0 commit comments