tenvy_derive 1.0.1

The derive macro for `tenvy`, a parser of environment variables
Documentation
use proc_macro2::TokenStream;
use quote::quote;
use syn::{Attribute, Error, Expr, Generics, Ident, parse_quote, spanned::Spanned};

pub enum Kind {
    Unit,
    Tuple,
}

pub fn derive(
    name: Ident,
    generics: Generics,
    attrs: Vec<Attribute>,
    kind: Kind,
) -> Result<TokenStream, Error> {
    if let Some(attr) = attrs
        .iter()
        .find(|attribute| attribute.path().is_ident("tenvy"))
    {
        let message = match kind {
            Kind::Unit => "`tenvy` attributes are not allowed on unit structures",
            Kind::Tuple => "`tenvy` attributes are not allowed on empty tuple structures",
        };
        return Err(Error::new(attr.span(), message));
    }

    let (impl_generics, ty_generics, where_clause) = generics.split_for_impl();

    let this: Expr = match kind {
        Kind::Unit => parse_quote!(Self),
        Kind::Tuple => parse_quote!(Self()),
    };

    Ok(quote! {
        #[automatically_derived]
        impl #impl_generics ::tenvy::Tenvy for #name #ty_generics #where_clause {
            fn from_env(env: &::tenvy::Env) -> ::std::result::Result<Self, ::tenvy::Error> {
                ::std::result::Result::Ok(#this)
            }
        }
    })
}