From be8ea44876e39a349cb601e7bc660d009d2a2977 Mon Sep 17 00:00:00 2001 From: Peter Holloway Date: Thu, 9 Jun 2022 20:55:10 +0100 Subject: [PATCH] Improve error message when missing free argument Include the name of the missing argument in the error message instead of using the generic 'missing required free argument' message for all arguments. --- gumdrop_derive/src/lib.rs | 3 ++- src/lib.rs | 8 ++++---- tests/options.rs | 2 +- 3 files changed, 7 insertions(+), 6 deletions(-) diff --git a/gumdrop_derive/src/lib.rs b/gumdrop_derive/src/lib.rs index 11b02b0..aa12cb0 100644 --- a/gumdrop_derive/src/lib.rs +++ b/gumdrop_derive/src/lib.rs @@ -383,8 +383,9 @@ fn derive_options_struct(ast: &DeriveInput, fields: &Fields) if opts.required { required.push(ident); + let name = format!("{}", ident); required_err.push(quote!{ - ::gumdrop::Error::missing_required_free() }); + ::gumdrop::Error::missing_required_free(#name) }); } free.push(FreeOpt{ diff --git a/src/lib.rs b/src/lib.rs index 893ed0d..8d0ff1e 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -198,7 +198,7 @@ enum ErrorKind { MissingCommand, MissingRequired(String), MissingRequiredCommand, - MissingRequiredFree, + MissingRequiredFree(String), UnexpectedArgument(String), UnexpectedSingleArgument(String, usize), UnexpectedFree(String), @@ -499,8 +499,8 @@ impl Error { } /// Returns an error for a missing required free argument. - pub fn missing_required_free() -> Error { - Error{kind: ErrorKind::MissingRequiredFree} + pub fn missing_required_free>(arg: S) -> Error { + Error{kind: ErrorKind::MissingRequiredFree(arg.into())} } /// Returns an error when a free argument was encountered, but the options @@ -549,7 +549,7 @@ impl fmt::Display for Error { MissingCommand => f.write_str("missing command name"), MissingRequired(opt) => write!(f, "missing required option `{}`", opt), MissingRequiredCommand => f.write_str("missing required command"), - MissingRequiredFree => f.write_str("missing required free argument"), + MissingRequiredFree(arg) => write!(f, "missing required argument for {}", arg), UnexpectedArgument(opt) => write!(f, "option `{}` does not accept an argument", opt), UnexpectedSingleArgument(opt, n) => write!(f, "option `{}` expects {} arguments; found 1", opt, n), diff --git a/tests/options.rs b/tests/options.rs index fb51ec4..5ac9b31 100644 --- a/tests/options.rs +++ b/tests/options.rs @@ -913,7 +913,7 @@ fn test_required() { is_err!(Opts2::parse_args_default(EMPTY), "missing required command"); is_err!(Opts3::parse_args_default(EMPTY), - "missing required free argument"); + "missing required argument for bar"); let opts = Opts::parse_args_default(&["-f", "1"]).unwrap(); assert_eq!(opts.foo, 1);