Skip to content

Commit

Permalink
improved validation error messages
Browse files Browse the repository at this point in the history
  • Loading branch information
ranger-ross committed Jul 27, 2024
1 parent 8499441 commit 04a0bd2
Show file tree
Hide file tree
Showing 3 changed files with 22 additions and 8 deletions.
1 change: 1 addition & 0 deletions garde_derive/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@ phone-number = []
syn = { version = "2", features = ["full", "derive"] }
quote = { version = "1" }
proc-macro2 = { version = "1" }
proc-macro-error = "1"
regex = { version = "1", default-features = false, features = [
"std",
], optional = true }
2 changes: 2 additions & 0 deletions garde_derive/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,9 +5,11 @@ mod syntax;
mod util;

use proc_macro::{Delimiter, Literal, Span, TokenStream, TokenTree};
use proc_macro_error::proc_macro_error;
use quote::quote;
use syn::DeriveInput;

#[proc_macro_error]
#[proc_macro_derive(Validate, attributes(garde))]
pub fn derive_validate(input: TokenStream) -> TokenStream {
let input = syn::parse_macro_input!(input as DeriveInput);
Expand Down
27 changes: 19 additions & 8 deletions garde_derive/src/syntax.rs
Original file line number Diff line number Diff line change
Expand Up @@ -272,27 +272,38 @@ impl Parse for model::RawRule {
}

macro_rules! error_if_missing_feature {
($other:expr) => {
#[cfg(not(feature = $other))]
panic!(concat!("Missing feature flag ", stringify!($other)));
($rule:expr, $feature:expr) => {
#[cfg(not(feature = $feature))]
proc_macro_error::abort!(
ident,
concat!(
"Validation rule `",
$rule,
"` not found. Did you forget to add the `",
$feature,
"` feature flag?"
)
);
};
}

// abort!(ident, "`parse` must have exactly one argument");

match ident.to_string().as_str() {
"email" => {
error_if_missing_feature!("email");
error_if_missing_feature!("email", "email");
}
"url" => {
error_if_missing_feature!("url");
error_if_missing_feature!("url", "url");
}
"credit_card" => {
error_if_missing_feature!("credit-card");
error_if_missing_feature!("credit_card", "credit-card");
}
"phone_number" => {
error_if_missing_feature!("phone-number");
error_if_missing_feature!("phone_number", "phone-number");
}
"regex" => {
error_if_missing_feature!("regex");
error_if_missing_feature!("regex", "regex");
}
_ => {}
}
Expand Down

0 comments on commit 04a0bd2

Please sign in to comment.