1
0
mirror of https://github.com/matrix-org/matrix-authentication-service.git synced 2025-07-31 09:24:31 +03:00

Make the optional configuration sections really optional

This commit is contained in:
Quentin Gliech
2024-07-31 16:42:30 +02:00
parent fa97916527
commit 49826c1aa4
7 changed files with 63 additions and 27 deletions

View File

@ -26,4 +26,7 @@ pub(crate) mod schema;
mod sections;
pub(crate) mod util;
pub use self::{sections::*, util::ConfigurationSection};
pub use self::{
sections::*,
util::{ConfigurationSection, ConfigurationSectionExt},
};

View File

@ -46,3 +46,32 @@ pub trait ConfigurationSection: Sized + DeserializeOwned {
Ok(this)
}
}
/// Extension trait for [`ConfigurationSection`] to allow extracting the
/// configuration section from a [`Figment`] or return the default value if the
/// section is not present.
pub trait ConfigurationSectionExt: ConfigurationSection + Default {
/// Extract the configuration section from the given [`Figment`], or return
/// the default value if the section is not present.
///
/// # Errors
///
/// Returns an error if the configuration section is invalid.
fn extract_or_default(figment: &Figment) -> Result<Self, figment::Error> {
let this: Self = if let Some(path) = Self::PATH {
// If the configuration section is not present, we return the default value
if !figment.contains(path) {
return Ok(Self::default());
}
figment.extract_inner(path)?
} else {
figment.extract()?
};
this.validate(figment)?;
Ok(this)
}
}
impl<T: ConfigurationSection + Default> ConfigurationSectionExt for T {}