From 821168a77077cd0e92e9b469be66566ae7b06c70 Mon Sep 17 00:00:00 2001 From: ":NoBody:" Date: Tue, 24 Mar 2026 21:36:32 +0800 Subject: [PATCH] =?UTF-8?q?=E5=AE=8C=E6=88=90=E4=BA=86=E5=91=BD=E4=BB=A4?= =?UTF-8?q?=E8=A7=A3=E6=9E=90=E5=99=A8=E9=83=A8=E5=88=86?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- Cargo.lock | 1 + Cargo.toml | 1 + src/bot/command_parser.rs | 178 ++++++++++++++++++++++++++++++++++++++ src/bot/mod.rs | 1 + 4 files changed, 181 insertions(+) create mode 100644 src/bot/command_parser.rs diff --git a/Cargo.lock b/Cargo.lock index 68ab775..830c6dc 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -646,6 +646,7 @@ dependencies = [ "reqwest 0.13.2", "serde", "sled", + "thiserror 2.0.18", "tokio", "toml 1.0.7+spec-1.1.0", ] diff --git a/Cargo.toml b/Cargo.toml index e7c971e..70c4ddb 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -10,6 +10,7 @@ env_logger = "0.11.9" reqwest = "0.13.2" serde = {version="1.0.228",features=["derive"]} sled = "0.34.7" +thiserror = "2.0.18" tokio = {version="1.50.0",features=["full"]} toml = "1.0.7" diff --git a/src/bot/command_parser.rs b/src/bot/command_parser.rs new file mode 100644 index 0000000..8e1337e --- /dev/null +++ b/src/bot/command_parser.rs @@ -0,0 +1,178 @@ +use std::collections::HashMap; +use thiserror::Error; + +#[derive(Debug, Error, PartialEq, Eq)] +pub enum CommandError { + #[error("empty command")] + EmptyCommand, + #[error("invalid option: {0}")] + InvalidOption(String), + #[error("unterminated quote")] + UnterminatedQuote, + #[error("dangling escape")] + DanglingEscape, +} + +#[derive(Debug, PartialEq, Eq)] +pub struct CommandAST { + pub command: String, + pub arguments: Vec, + pub options: HashMap, +} + +pub fn parse_command(command: &str) -> Result { + let tokens = tokenize_command(command)?; + if tokens.is_empty() { + return Err(CommandError::EmptyCommand); + } + + let command = tokens[0].clone(); + + let mut arguments = Vec::new(); + let mut options = HashMap::new(); + + let mut i = 1; + while i < tokens.len() { + let token = &tokens[i]; + if let Some(raw) = token.strip_prefix("--") { + if raw.is_empty() { + return Err(CommandError::InvalidOption(String::from("--"))); + } + + if let Some((k, v)) = raw.split_once('=') { + if k.is_empty() { + return Err(CommandError::InvalidOption(format!( + "invalid option key in '--{}'", + raw + ))); + } + options.insert(k.to_string(), v.to_string()); + i += 1; + continue; + } + + let key = raw.to_string(); + let value = if i + 1 < tokens.len() && !tokens[i + 1].starts_with('-') { + i += 1; + tokens[i].clone() + } else { + String::from("true") + }; + options.insert(key, value); + i += 1; + continue; + } + + arguments.push(token.clone()); + i += 1; + } + + Ok(CommandAST { + command, + arguments, + options, + }) +} + +fn tokenize_command(input: &str) -> Result, CommandError> { + let mut tokens = Vec::new(); + let mut buf = String::new(); + let mut chars = input.chars().peekable(); + let mut in_single_quote = false; + let mut in_double_quote = false; + + while let Some(ch) = chars.next() { + match ch { + '\'' if !in_double_quote => { + in_single_quote = !in_single_quote; + } + '"' if !in_single_quote => { + in_double_quote = !in_double_quote; + } + '\\' if in_double_quote => { + if let Some(next) = chars.next() { + buf.push(next); + } else { + return Err(CommandError::DanglingEscape); + } + } + c if c.is_ascii_whitespace() && !in_single_quote && !in_double_quote => { + if !buf.is_empty() { + tokens.push(std::mem::take(&mut buf)); + } + } + _ => buf.push(ch), + } + } + + if in_single_quote || in_double_quote { + return Err(CommandError::UnterminatedQuote); + } + + if !buf.is_empty() { + tokens.push(buf); + } + + Ok(tokens) +} + +#[cfg(test)] +mod tests { + use super::{CommandError, parse_command}; + + #[test] + fn parse_basic_command_and_arguments() { + let ast = parse_command("/deploy service-a region-cn").expect("should parse"); + assert_eq!(ast.command, "/deploy"); + assert_eq!(ast.arguments, vec!["service-a", "region-cn"]); + assert!(ast.options.is_empty()); + } + + #[test] + fn parse_options_with_equal_and_space() { + let ast = parse_command("deploy --env=prod --region cn").expect("should parse"); + assert_eq!(ast.command, "deploy"); + assert_eq!(ast.arguments, Vec::::new()); + assert_eq!(ast.options.get("env").map(String::as_str), Some("prod")); + assert_eq!(ast.options.get("region").map(String::as_str), Some("cn")); + } + + #[test] + fn parse_flag_and_consecutive_options() { + let ast = parse_command("sync --dry-run --limit=10 --verbose").expect("should parse"); + assert_eq!(ast.options.get("dry-run").map(String::as_str), Some("true")); + assert_eq!(ast.options.get("limit").map(String::as_str), Some("10")); + assert_eq!(ast.options.get("verbose").map(String::as_str), Some("true")); + } + + #[test] + fn parse_quoted_arguments() { + let ast = parse_command("send \"hello world\" 'to matrix room'").expect("should parse"); + assert_eq!(ast.command, "send"); + assert_eq!(ast.arguments, vec!["hello world", "to matrix room"]); + } + + #[test] + fn parse_empty_input_returns_error() { + let err = parse_command(" ").expect_err("should fail"); + assert_eq!(err, CommandError::EmptyCommand); + } + + #[test] + fn parse_invalid_empty_option_returns_error() { + let err = parse_command("cmd --").expect_err("should fail"); + assert_eq!(err, CommandError::InvalidOption(String::from("--"))); + } + + #[test] + fn parse_unterminated_quote_returns_error() { + let err = parse_command("cmd \"oops").expect_err("should fail"); + assert_eq!(err, CommandError::UnterminatedQuote); + } + + #[test] + fn parse_dangling_escape_in_double_quotes_returns_error() { + let err = parse_command("cmd \"abc\\").expect_err("should fail"); + assert_eq!(err, CommandError::DanglingEscape); + } +} diff --git a/src/bot/mod.rs b/src/bot/mod.rs index a74af29..3ce9616 100644 --- a/src/bot/mod.rs +++ b/src/bot/mod.rs @@ -1,3 +1,4 @@ pub mod bot_handler; +pub mod command_parser; pub mod define; pub mod matrix;