39 lines
1.4 KiB
Rust
39 lines
1.4 KiB
Rust
use proc_macro::TokenStream;
|
|
use proc_macro_crate::{FoundCrate, crate_name};
|
|
use quote::quote;
|
|
use syn::{DeriveInput, Ident, parse_macro_input};
|
|
|
|
#[proc_macro_derive(Secret)]
|
|
pub fn derive_secret(input: TokenStream) -> TokenStream {
|
|
let input = parse_macro_input!(input as DeriveInput);
|
|
let struct_ident = &input.ident;
|
|
|
|
// The key for the secret will be the stringified name of the struct itself.
|
|
// e.g., `struct OKDClusterSecret` becomes key `"OKDClusterSecret"`.
|
|
let key = struct_ident.to_string(); // TODO: Utiliser path complet de la struct
|
|
|
|
// Find the path to the `harmony_secret` crate.
|
|
let secret_crate_path = match crate_name("harmony_secret") {
|
|
Ok(FoundCrate::Itself) => quote!(crate),
|
|
Ok(FoundCrate::Name(name)) => {
|
|
let ident = Ident::new(&name, proc_macro2::Span::call_site());
|
|
quote!(::#ident)
|
|
}
|
|
Err(e) => {
|
|
return syn::Error::new(proc_macro2::Span::call_site(), e.to_string())
|
|
.to_compile_error()
|
|
.into();
|
|
}
|
|
};
|
|
|
|
// The generated code now implements `Secret` for the struct itself.
|
|
// The struct must also derive `Serialize` and `Deserialize` for this to be useful.
|
|
let expanded = quote! {
|
|
impl #secret_crate_path::Secret for #struct_ident {
|
|
const KEY: &'static str = #key;
|
|
}
|
|
};
|
|
|
|
TokenStream::from(expanded)
|
|
}
|