aboutsummaryrefslogtreecommitdiff
path: root/src/makefile/pattern.rs
blob: b47c75d3cba7aea8f966c02d35166e66c8f97fc3 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
use eyre::Result;
use regex::{Captures, Regex};

fn compile_pattern(pattern: &str) -> Result<Regex> {
    let mut result = String::new();
    for c in pattern.chars() {
        if c == '%' {
            if let Some(real_result) = result.strip_suffix(r"\\\\") {
                // We end with two backslashes, so this is an escaped backslash and then an
                // unescaped wildcard.
                result = real_result.to_owned();
                result.push_str(r"\\(\w*)");
            } else if let Some(real_result) = result.strip_suffix(r"\\") {
                // We end with one backslash, so this is an escaped wildcard.
                result = real_result.to_owned();
                result.push('%');
            } else {
                // We don't end with a backslash, so this is an unescaped wildcard.
                result.push_str(r"(\w*)");
            }
        } else {
            result.push_str(&regex::escape(&c.to_string()));
        }
    }
    Ok(Regex::new(&result)?)
}

pub fn r#match<'a>(pattern: &str, text: &'a str) -> Result<Option<Captures<'a>>> {
    Ok(compile_pattern(pattern)?.captures(text))
}

#[cfg(test)]
mod test {
    use super::*;

    type R = Result<()>;

    #[test]
    fn pattern_backslashes() -> R {
        let test_case = compile_pattern(r"the\%weird\\%pattern\\")?;
        assert_eq!(test_case.to_string(), r"the%weird\\(\w*)pattern\\\\");

        let hell = compile_pattern(r"\\\\%")?;
        assert_eq!(hell.to_string(), r"\\\\\\(\w*)");
        Ok(())
    }
}