From 44df27daf3f6f31adde25238693daeb17611a057 Mon Sep 17 00:00:00 2001 From: Erik Grinaker Date: Thu, 23 May 2024 15:25:24 +0200 Subject: [PATCH] command: return `Box` from `Argument.parse()` --- CHANGELOG.md | 4 ++++ src/command.rs | 33 ++++++++++++++++++--------------- 2 files changed, 22 insertions(+), 15 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 305f7c0..8a485fa 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,9 @@ # Unreleased +**Breaking changes** + +* Return `Box` from `Argument.parse()`, like `Runner` does. + **Improvements** * Add `Command.pos_args()` and `key_args()` for filtering argument types. diff --git a/src/command.rs b/src/command.rs index af559b7..9a87476 100644 --- a/src/command.rs +++ b/src/command.rs @@ -1,4 +1,5 @@ use std::collections::HashMap; +use std::error::Error; /// A block, consisting of multiple commands. #[derive(Debug, PartialEq)] @@ -55,14 +56,14 @@ pub struct Argument { impl Argument { /// Parses the argument value as a T using core::str::parse(). Convenience - /// method that returns a string error to ease error handling in a - /// [`Runner`](crate::Runner). - pub fn parse(&self) -> Result + /// method that returns an improved error message as a boxed error to ease + /// error handling in a [`Runner`](crate::Runner). + pub fn parse(&self) -> Result> where T: std::str::FromStr, ::Err: std::fmt::Display, { - self.value.parse().map_err(|e| format!("invalid argument '{}': {e}", self.value)) + self.value.parse().map_err(|e| format!("invalid argument '{}': {e}", self.value).into()) } } @@ -126,23 +127,25 @@ mod tests { /// to core::str::parse(). #[test] fn argument_parse() { - assert_eq!(arg!("-1").parse(), Ok(-1_i64)); - assert_eq!(arg!("0").parse(), Ok(0_i64)); - assert_eq!(arg!("1").parse(), Ok(1_i64)); + assert_eq!(arg!("-1").parse::().unwrap(), -1_i64); + assert_eq!(arg!("0").parse::().unwrap(), 0_i64); + assert_eq!(arg!("1").parse::().unwrap(), 1_i64); + assert_eq!( - arg!("").parse::(), - Err("invalid argument '': cannot parse integer from empty string".to_string()) + arg!("").parse::().unwrap_err().to_string(), + "invalid argument '': cannot parse integer from empty string" ); assert_eq!( - arg!("foo").parse::(), - Err("invalid argument 'foo': invalid digit found in string".to_string()) + arg!("foo").parse::().unwrap_err().to_string(), + "invalid argument 'foo': invalid digit found in string" ); - assert_eq!(arg!("false").parse(), Ok(false)); - assert_eq!(arg!("true").parse(), Ok(true)); + assert!(!arg!("false").parse::().unwrap()); + assert!(arg!("true").parse::().unwrap()); + assert_eq!( - arg!("").parse::(), - Err("invalid argument '': provided string was not `true` or `false`".to_string()) + arg!("").parse::().unwrap_err().to_string(), + "invalid argument '': provided string was not `true` or `false`" ); } }