use figment::Error;
use figment::error::Actual;
impl crate::SuperConfig {
pub fn as_json(&self) -> Result<String, Error> {
let value = self.figment.extract::<serde_json::Value>()?;
serde_json::to_string_pretty(&value).map_err(|e| {
Error::from(figment::error::Kind::InvalidType(
Actual::Other(e.to_string()),
"valid JSON".into(),
))
})
}
pub fn as_yaml(&self) -> Result<String, Error> {
let value = self.figment.extract::<serde_json::Value>()?;
serde_yml::to_string(&value).map_err(|e| {
Error::from(figment::error::Kind::InvalidType(
Actual::Other(e.to_string()),
"valid YAML".into(),
))
})
}
pub fn as_toml(&self) -> Result<String, Error> {
let value = self.figment.extract::<toml::Value>()?;
toml::to_string_pretty(&value).map_err(|e| {
Error::from(figment::error::Kind::InvalidType(
Actual::Other(e.to_string()),
"valid TOML".into(),
))
})
}
pub fn get_string<K: AsRef<str>>(&self, key: K) -> Result<String, Error> {
self.figment.extract_inner(key.as_ref())
}
pub fn get_array<T>(&self, key: &str) -> Result<Vec<T>, Error>
where
T: serde::de::DeserializeOwned,
{
self.figment.extract_inner(key)
}
pub fn has_key(&self, key: &str) -> Result<bool, Error> {
match self.figment.find_value(key) {
Ok(_) => Ok(true),
Err(Error {
kind: figment::error::Kind::MissingField(_),
..
}) => Ok(false),
Err(e) => Err(e),
}
}
pub fn keys(&self) -> Result<Vec<String>, Error> {
let value = self.figment.extract::<serde_json::Value>()?;
match value {
serde_json::Value::Object(map) => Ok(map.keys().cloned().collect()),
_ => Ok(vec![]),
}
}
pub fn debug_config(&self) -> Result<String, Error> {
let json_value = self.figment.extract::<serde_json::Value>()?;
let pretty_json = serde_json::to_string_pretty(&json_value).map_err(|e| {
Error::from(figment::error::Kind::InvalidType(
Actual::Other(e.to_string()),
"valid JSON".into(),
))
})?;
Ok(format!(
"=== SuperConfig Debug ===\n\nWarnings: {:?}\n\nFinal Configuration:\n{pretty_json}\n\nProvider Chain:\n{:#?}",
self.warnings, self.figment
))
}
pub fn debug_sources(&self) -> Vec<figment::Metadata> {
self.figment.metadata().cloned().collect()
}
}