From 2af43ccac29d18b3c4ba5e379a012e25f7f1c7c0 Mon Sep 17 00:00:00 2001 From: Azumi4han Date: Fri, 12 Apr 2024 23:08:41 +0300 Subject: [PATCH] fix: Fix and improve regex for sensitive and flexible command matching, add tests - Fixed a bug where regex incorrectly matched "/cfg" with "/g" using a Sensitive filter. - Improved Flexible command matching. - Added new tests for command matching functionality. - Bump version to 1.2.2. --- Cargo.toml | 2 +- src/util/matchit.rs | 8 +++----- tests/test_command_match.rs | 4 +++- 3 files changed, 7 insertions(+), 7 deletions(-) diff --git a/Cargo.toml b/Cargo.toml index fd7efc5..3792a29 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "safe-vk" -version = "1.2.1" +version = "1.2.2" edition = "2021" authors = ["Azumi4han"] homepage = "https://github.com/Azumi4han/safe-vk" diff --git a/src/util/matchit.rs b/src/util/matchit.rs index cd5ac32..fc74038 100644 --- a/src/util/matchit.rs +++ b/src/util/matchit.rs @@ -14,13 +14,11 @@ pub enum Filter { pub fn matchit(message: &str, command: &str, filter: &Filter) -> bool { let pattern = match filter { Filter::Strict => format!(r"^{}$", regex::escape(command)), - Filter::Flexible => format!(r"(?si).*{}", regex::escape(command)), + Filter::Flexible => format!(r"(?i)^\s*[^\w\s]?{}\s*$", regex::escape(command)), Filter::Sensitive => format!( - r"(?si)[^\w\s]*({}?{})", - regex::escape(&command[..1]), - regex::escape(&command[1..]) + r"(?i)(?:^|[\W_]){}(?:[\W_]|$)", + regex::escape(&command.trim_start_matches(|c: char| !c.is_alphanumeric())) ), }; - Regex::new(&pattern).unwrap().is_match(message) } diff --git a/tests/test_command_match.rs b/tests/test_command_match.rs index 8206d2b..af1f9da 100644 --- a/tests/test_command_match.rs +++ b/tests/test_command_match.rs @@ -25,8 +25,10 @@ fn flexible() { assert!(!matchit("This is a command1 2 3 message", "!command", filter)); assert!(!matchit("This is a $command 123message", "!command", filter)); assert!(!matchit("This is a %coMMand message", "!command", filter)); - assert!(matchit("This is a !coMManD message ", "!command", filter)); + assert!(!matchit("This is a !coMManD message ", "!command", filter)); + assert!(!matchit("command", "!command", filter)); assert!(matchit(" !command", "!command", filter)); + assert!(matchit("!command ", "!command", filter)); assert!(matchit("!command ", "!command", filter)); assert!(!matchit("$command", "!command", filter)); assert!(matchit("!command", "!command", filter));