use quote::quote;
use crate::types::ValidateField;
use crate::utils::quote_message;
#[derive(Debug, Clone, darling::FromMeta)]
pub struct Custom {
pub code: Option<String>,
pub message: Option<String>,
pub function: darling::Result<syn::Path>,
pub use_context: Option<bool>,
}
pub fn check_custom_validator_form(field: &ValidateField, field_name: &str) {
for c in &field.custom {
if let Err(e) = &c.function {
proc_macro_error2::abort!(
e.span(), "Invalid attribute #[validate(custom(...))] on field `{}`:", field_name;
note = "Invalid argument for `custom` validator, only paths are allowed";
help = "Try formatting the argument like `path::to::function` or `\"path::to::function\"`"
);
}
}
}
pub fn tokens(
custom: Custom,
field_name: &proc_macro2::TokenStream,
field_name_str: &str,
) -> proc_macro2::TokenStream {
let fn_call = custom.function.unwrap();
let args = if let Some(arg) = custom.use_context {
if arg {
quote!(#field_name, args)
} else {
quote!(#field_name)
}
} else {
quote!(#field_name)
};
let message = quote_message(custom.message);
let code = if let Some(c) = custom.code {
quote!(
err.code = ::std::borrow::Cow::from(#c);
)
} else {
quote!()
};
quote! {
match #fn_call(#args) {
::std::result::Result::Ok(()) => {}
::std::result::Result::Err(mut err) => {
#code
#message
err.add_param(::std::borrow::Cow::from("value"), &#field_name);
errors.add(#field_name_str, err);
}
}
}
}