完成了命令解析器部分

This commit is contained in:
:NoBody: committed 2026-03-24 22:18:44 +08:00
1 parent 5586bd78a4
commit 821168a770
4 files changed
+181

No files matched your search

Generated
+1
View File
@@ -646,6 +646,7 @@ dependencies = [
"reqwest 0.13.2",
"serde",
"sled",
"thiserror 2.0.18",
"tokio",
"toml 1.0.7+spec-1.1.0",
]
+1
View File
@@ -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"
+178
View File
@@ -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<String>,
pub options: HashMap<String, String>,
}
pub fn parse_command(command: &str) -> Result<CommandAST, CommandError> {
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<Vec<String>, 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::<String>::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);
}
}
+1
View File
@@ -1,3 +1,4 @@
pub mod bot_handler;
pub mod command_parser;
pub mod define;
pub mod matrix;