Skip to content
New issue

Have a question about this project? # for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “#”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? # to your account

Add support for error code #145

Open
wants to merge 2 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
22 changes: 22 additions & 0 deletions garde/src/error.rs
Original file line number Diff line number Diff line change
Expand Up @@ -70,23 +70,45 @@ impl std::error::Error for Report {}
#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct Error {
#[cfg_attr(
feature = "serde",
serde(default, skip_serializing_if = "Option::is_none")
)]
code: Option<Cow<'static, str>>,
message: CompactString,
}

impl Error {
pub fn new(message: impl ToCompactString) -> Self {
Self {
code: None,
message: message.to_compact_string(),
}
}

pub fn code(&self) -> Option<&str> {
self.code.as_deref()
}

pub fn message(&self) -> &str {
self.message.as_ref()
}

pub fn set_code(&mut self, code: impl Into<Cow<'static, str>>) {
self.code = Some(code.into());
}

pub fn with_code(mut self, code: impl Into<Cow<'static, str>>) -> Self {
self.code = Some(code.into());
self
}
}

impl std::fmt::Display for Error {
fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
if let Some(code) = &self.code {
write!(f, "[{}] ", code)?;
}
write!(f, "{}", self.message)
}
}
Expand Down
2 changes: 1 addition & 1 deletion garde/tests/rules/alphanumeric.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ struct Test<'a> {
#[garde(alphanumeric)]
field: &'a str,

#[garde(inner(alphanumeric))]
#[garde(inner(alphanumeric(code = "ALPHA")))]
inner: &'a [&'a str],
}

Expand Down
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
---
source: garde/tests/./rules/alphanumeric.rs
expression: snapshot
snapshot_kind: text
---
Test {
field: "!!!!",
Expand All @@ -9,6 +10,4 @@ Test {
],
}
field: not alphanumeric
inner[0]: not alphanumeric


inner[0]: [ALPHA] not alphanumeric
51 changes: 26 additions & 25 deletions garde_derive/src/check.rs
Original file line number Diff line number Diff line change
Expand Up @@ -231,7 +231,7 @@ fn check_field(field: model::Field, options: &model::Options) -> syn::Result<mod
skip: None,
alias: None,
// message: None,
code: None,
// code: None,
dive: None,
rule_set: model::RuleSet::empty(),
};
Expand Down Expand Up @@ -322,8 +322,8 @@ fn check_rule(
}
}};

($rule:ident($($inner:expr)?), $span:expr) => {{
let rule = model::ValidateRule::$rule$(($inner))?;
($rule:ident($($inner:ident $(: $inner_expr:expr)?)?), $code:expr, $span:expr) => {{
let rule = model::ValidateRule::$rule { code: $code $(, $inner $(: $inner_expr)?)? };
let name = rule.name();
if !rule_set.rules.insert(rule) {
return Err(syn::Error::new($span, format!("duplicate rule `{name}`")));
Expand All @@ -332,41 +332,42 @@ fn check_rule(
}

let span = raw_rule.span;
let code = raw_rule.code.map(|v| v.value);
use model::RawRuleKind::*;
match raw_rule.kind {
Skip => apply!(skip = span, span),
Adapt(path) => apply!(adapter = path, span),
Rename(alias) => apply!(alias = alias.value, span),
// Message(message) => apply!(message = message, span),
Code(code) => apply!(code = code.value, span),
// Code(code) => apply!(code = code.value, span),
Dive(ctx) => apply!(dive = (span, ctx), span),
Custom(custom) => rule_set.custom_rules.push(custom),
Required => apply!(Required(), span),
Ascii => apply!(Ascii(), span),
Alphanumeric => apply!(Alphanumeric(), span),
Email => apply!(Email(), span),
Url => apply!(Url(), span),
Ip => apply!(Ip(), span),
IpV4 => apply!(IpV4(), span),
IpV6 => apply!(IpV6(), span),
CreditCard => apply!(CreditCard(), span),
PhoneNumber => apply!(PhoneNumber(), span),
Required => apply!(Required(), code, span),
Ascii => apply!(Ascii(), code, span),
Alphanumeric => apply!(Alphanumeric(), code, span),
Email => apply!(Email(), code, span),
Url => apply!(Url(), code, span),
Ip => apply!(Ip(), code, span),
IpV4 => apply!(IpV4(), code, span),
IpV6 => apply!(IpV6(), code, span),
CreditCard => apply!(CreditCard(), code, span),
PhoneNumber => apply!(PhoneNumber(), code, span),
Length(v) => {
let range = check_range_generic(v.range)?;
match v.mode {
LengthMode::Simple => apply!(LengthSimple(range), span),
LengthMode::Bytes => apply!(LengthBytes(range), span),
LengthMode::Chars => apply!(LengthChars(range), span),
LengthMode::Graphemes => apply!(LengthGraphemes(range), span),
LengthMode::Utf16 => apply!(LengthUtf16(range), span),
LengthMode::Simple => apply!(LengthSimple(range), code, span),
LengthMode::Bytes => apply!(LengthBytes(range), code, span),
LengthMode::Chars => apply!(LengthChars(range), code, span),
LengthMode::Graphemes => apply!(LengthGraphemes(range), code, span),
LengthMode::Utf16 => apply!(LengthUtf16(range), code, span),
}
}
Matches(path) => apply!(Matches(path), span),
Range(v) => apply!(Range(check_range_not_ord(v)?), span),
Contains(v) => apply!(Contains(v), span),
Prefix(v) => apply!(Prefix(v), span),
Suffix(v) => apply!(Suffix(v), span),
Pattern(v) => apply!(Pattern(check_regex(v)?), span),
Matches(path) => apply!(Matches(path), code, span),
Range(v) => apply!(Range(range: check_range_not_ord(v)?), code, span),
Contains(expr) => apply!(Contains(expr), code, span),
Prefix(expr) => apply!(Prefix(expr), code, span),
Suffix(expr) => apply!(Suffix(expr), code, span),
Pattern(v) => apply!(Pattern(pat: check_regex(v)?), code, span),
Inner(v) => {
if rule_set.inner.is_none() {
rule_set.inner = Some(Box::new(model::RuleSet::empty()));
Expand Down
64 changes: 50 additions & 14 deletions garde_derive/src/emit.rs
Original file line number Diff line number Diff line change
Expand Up @@ -260,23 +260,29 @@ impl ToTokens for Rules<'_> {
let name = TokenStream2::from_str(rule.name()).unwrap();
use model::ValidateRule::*;
let args = match rule {
Ascii | Alphanumeric | Email | Url | CreditCard | PhoneNumber | Required => {
Ascii { .. }
| Alphanumeric { .. }
| Email { .. }
| Url { .. }
| CreditCard { .. }
| PhoneNumber { .. }
| Required { .. } => {
quote!(())
}
Ip => {
Ip { .. } => {
quote!((#rules_mod::ip::IpKind::Any,))
}
IpV4 => {
IpV4 { .. } => {
quote!((#rules_mod::ip::IpKind::V4,))
}
IpV6 => {
IpV6 { .. } => {
quote!((#rules_mod::ip::IpKind::V6,))
}
LengthSimple(range)
| LengthBytes(range)
| LengthChars(range)
| LengthGraphemes(range)
| LengthUtf16(range) => match range {
LengthSimple { range, .. }
| LengthBytes { range, .. }
| LengthChars { range, .. }
| LengthGraphemes { range, .. }
| LengthUtf16 { range, .. } => match range {
model::ValidateRange::GreaterThan(min) => {
quote!((#min, usize::MAX))
}
Expand All @@ -290,19 +296,19 @@ impl ToTokens for Rules<'_> {
quote!((#equal, #equal))
}
},
Matches(path) => {
Matches { path, .. } => {
quote!((stringify!(#path), &self.#path))
}
Range(range) => match range {
Range { range, .. } => match range {
model::ValidateRange::GreaterThan(min) => quote!((Some(#min), None)),
model::ValidateRange::LowerThan(max) => quote!((None, Some(#max))),
model::ValidateRange::Between(min, max) => quote!((Some(#min), Some(#max))),
model::ValidateRange::Equal(equal) => quote!((Some(#equal), Some(#equal))),
},
Contains(expr) | Prefix(expr) | Suffix(expr) => {
Contains { expr, .. } | Prefix { expr, .. } | Suffix { expr, .. } => {
quote_spanned!(expr.span() => (&#expr,))
}
Pattern(pat) => match pat {
Pattern { pat, .. } => match pat {
model::ValidatePattern::Expr(expr) => quote_spanned!(expr.span() => (&#expr,)),
#[cfg(all(feature = "regex", feature = "js-sys"))]
model::ValidatePattern::Lit(s) => quote!({
Expand Down Expand Up @@ -332,9 +338,39 @@ impl ToTokens for Rules<'_> {
},
};

let code = match rule {
Required { code }
| Ascii { code }
| Alphanumeric { code }
| Email { code }
| Url { code }
| Ip { code }
| IpV4 { code }
| IpV6 { code }
| CreditCard { code }
| PhoneNumber { code }
| LengthSimple { code, .. }
| LengthBytes { code, .. }
| LengthChars { code, .. }
| LengthGraphemes { code, .. }
| LengthUtf16 { code, .. }
| Matches { code, .. }
| Range { code, .. }
| Contains { code, .. }
| Prefix { code, .. }
| Suffix { code, .. }
| Pattern { code, .. } => code,
};

let code = if let Some(code) = code {
quote!(.with_code(#code))
} else {
TokenStream2::new()
};

quote! {
if let Err(__garde_error) = (#rules_mod::#name::apply)(&*__garde_binding, #args) {
__garde_report.append(__garde_path(), __garde_error);
__garde_report.append(__garde_path(), __garde_error #code);
}
}
.to_tokens(tokens)
Expand Down
Loading
Loading