From 58b5a26ecac1bc53a219639156b6badf0e0b8089 Mon Sep 17 00:00:00 2001 From: dusk Date: Sun, 12 Jan 2025 05:35:04 +0900 Subject: [PATCH] fix(commands): add separate missing error for Token::Any to relay a better error message to user --- crates/commands/src/commands/config.rs | 2 +- crates/commands/src/lib.rs | 15 +++++++++++++++ crates/commands/src/token.rs | 6 ++++-- 3 files changed, 20 insertions(+), 3 deletions(-) diff --git a/crates/commands/src/commands/config.rs b/crates/commands/src/commands/config.rs index db16e729..d39024d5 100644 --- a/crates/commands/src/commands/config.rs +++ b/crates/commands/src/commands/config.rs @@ -27,7 +27,7 @@ pub fn cmds() -> impl Iterator { cfg, autoproxy, ["timeout", "tm"], - [Disable("toggle"), Reset("reset"), FullString("timeout")] + [Disable("toggle"), Reset("reset"), FullString("timeout")] // todo: we should parse duration / time values ], "cfg_ap_timeout_update", "Sets the autoproxy timeout" diff --git a/crates/commands/src/lib.rs b/crates/commands/src/lib.rs index fd1e794a..de6becb0 100644 --- a/crates/commands/src/lib.rs +++ b/crates/commands/src/lib.rs @@ -101,6 +101,21 @@ pub fn parse_command(prefix: String, input: String) -> CommandResult { TokenMatchError::MissingParameter { name } => { format!("Expected parameter `{name}` in command `{prefix}{input} {token}`.") } + TokenMatchError::MissingAny { tokens } => { + let mut msg = format!("Expected one of "); + for (idx, token) in tokens.iter().enumerate() { + write!(&mut msg, "`{token}`").expect("oom"); + if idx < tokens.len() - 1 { + if tokens.len() > 2 && idx == tokens.len() - 2 { + msg.push_str(" or "); + } else { + msg.push_str(", "); + } + } + } + write!(&mut msg, " in command `{prefix}{input} {token}`.").expect("oom"); + msg + } }; return CommandResult::Err { error: error_msg }; } diff --git a/crates/commands/src/token.rs b/crates/commands/src/token.rs index f216fa4a..e705a359 100644 --- a/crates/commands/src/token.rs +++ b/crates/commands/src/token.rs @@ -48,6 +48,7 @@ pub enum Token { #[derive(Debug)] pub enum TokenMatchError { MissingParameter { name: ParamName }, + MissingAny { tokens: Vec }, } #[derive(Debug)] @@ -108,8 +109,9 @@ impl Token { Some(Err(TokenMatchError::MissingParameter { name: param_name })) } Self::Any(tokens) => tokens.is_empty().then_some(None).unwrap_or_else(|| { - let mut results = tokens.iter().map(|t| t.try_match(None)); - results.find(|r| !matches!(r, None)).unwrap_or(None) + Some(Err(TokenMatchError::MissingAny { + tokens: tokens.clone(), + })) }), // everything else doesnt match if no input anyway Token::Value(_) => None,