use glob::{Pattern, PatternError};
fn fix_negation(glob: &str) -> String {
let mut chars = glob.chars().collect::<Vec<_>>();
let mut i = 0;
while i + 3 < chars.len() {
if chars[i] == '[' && chars[i + 1] == '^' {
match chars[i + 3..].iter().position(|x| *x == ']') {
None => {
break;
}
Some(j) => {
chars[i + 1] = '!';
i += j + 4;
continue;
}
}
}
i += 1;
}
chars.into_iter().collect::<String>()
}
pub fn from_str(glob: &str) -> Result<Pattern, PatternError> {
Pattern::new(&fix_negation(glob))
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_from_str() {
assert_eq!(from_str("[^abc]").unwrap(), Pattern::new("[!abc]").unwrap());
}
#[test]
fn test_fix_negation() {
assert_eq!(fix_negation("[^abc]"), "[!abc]");
assert_eq!(fix_negation("foo[abc] bar[^def]"), "foo[abc] bar[!def]");
assert_eq!(fix_negation("foo[^abc]bar[^def]"), "foo[!abc]bar[!def]");
assert_eq!(fix_negation("[^]]"), "[!]]");
assert_eq!(fix_negation("[^^]"), "[!^]");
assert_eq!(fix_negation("[^ ]"), "[! ]");
assert_eq!(fix_negation("[^][]"), "[!][]");
assert_eq!(fix_negation("[^[]]"), "[![]]");
assert_eq!(fix_negation("[[]] [^a]"), "[[]] [!a]");
assert_eq!(fix_negation("[[] [^a]"), "[[] [!a]");
assert_eq!(fix_negation("[]] [^a]"), "[]] [!a]");
let chars = "^[".repeat(174_571);
assert_eq!(fix_negation(chars.as_str()), chars);
}
#[test]
fn test_fix_negation_should_not_amend() {
assert_eq!(fix_negation("abc"), "abc");
assert_eq!(fix_negation("[[^]"), "[[^]");
assert_eq!(fix_negation("[ ^]"), "[ ^]");
assert_eq!(fix_negation("[[ ^]"), "[[ ^]");
assert_eq!(fix_negation("[ [^]"), "[ [^]");
assert_eq!(fix_negation("[^]"), "[^]");
assert_eq!(fix_negation("[^"), "[^");
assert_eq!(fix_negation("[][^]"), "[][^]");
assert_eq!(fix_negation("ààà[^"), "ààà[^");
}
}