use crate::error::HierConfError;
use facet::Facet;
type FacetAttr = facet::Attr;
#[cfg(not(feature = "mangen"))]
facet::define_attr_grammar! {
ns "hierconf";
crate_path ::hierconf_core::attrs;
pub enum Attr {
AppName(&'static str),
}
}
#[cfg(feature = "mangen")]
facet::define_attr_grammar! {
ns "hierconf";
crate_path ::hierconf_core::attrs;
pub enum Attr {
AppName(&'static str),
Synopsis(&'static str),
Date(&'static str),
TypeName(&'static str),
TypeDoc(&'static str),
Hide,
}
}
fn get_attr<'a, T>(attrs: &'a [FacetAttr], key: &'static str) -> Result<&'a T, HierConfError>
where
T: Facet<'static>,
{
for attr in attrs {
if attr.ns == Some("hierconf") && attr.key == key {
return attr
.get_as::<T>()
.ok_or(HierConfError::AttributeShapeMismatch {
shape: attr.data.shape,
key,
});
}
}
Err(HierConfError::MissingAttribute(key.to_string()))
}
#[cfg(feature = "mangen")]
fn get_attr_opt<'a, T>(
attrs: &'a [FacetAttr],
key: &'static str,
) -> Result<Option<&'a T>, HierConfError>
where
T: Facet<'static>,
{
match get_attr::<T>(attrs, key) {
Ok(attr) => Ok(Some(attr)),
Err(HierConfError::MissingAttribute(_)) => Ok(None),
Err(e) => Err(e),
}
}
#[cfg(feature = "mangen")]
fn has_attr(attrs: &[FacetAttr], key: &'static str) -> bool {
attrs
.iter()
.any(|attr| attr.ns == Some("hierconf") && attr.key == key)
}
pub fn extract_app_name<T>() -> Result<&'static str, HierConfError>
where
T: Facet<'static>,
{
Ok(get_attr::<&str>(T::SHAPE.attributes, "app_name")?)
}
#[cfg(feature = "mangen")]
pub fn extract_synopsis<T>() -> Result<Option<&'static str>, HierConfError>
where
T: Facet<'static>,
{
Ok(get_attr_opt::<&str>(T::SHAPE.attributes, "synopsis")?.cloned())
}
#[cfg(feature = "mangen")]
pub fn extract_date<T>() -> Result<Option<&'static str>, HierConfError>
where
T: Facet<'static>,
{
Ok(get_attr_opt::<&str>(T::SHAPE.attributes, "date")?.cloned())
}
#[cfg(feature = "mangen")]
pub fn extract_type_name(attrs: &[FacetAttr]) -> Result<Option<&'static str>, HierConfError> {
Ok(get_attr_opt::<&str>(attrs, "type_name")?.cloned())
}
#[cfg(feature = "mangen")]
pub fn extract_type_doc(attrs: &[FacetAttr]) -> Result<Option<&'static str>, HierConfError> {
Ok(get_attr_opt::<&str>(attrs, "type_doc")?.cloned())
}
#[cfg(feature = "mangen")]
pub fn is_hidden(attrs: &[FacetAttr]) -> bool {
has_attr(attrs, "hide")
}