aboutsummaryrefslogtreecommitdiff
path: root/src/makefile/pattern.rs
blob: 2d5f46ca5f784d702a152f60c9441abcf28e158d (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
use regex::{Captures, Regex};

fn compile_pattern(pattern: &str) -> anyhow::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_string();
                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_string();
                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(crate) fn r#match<'a>(pattern: &str, text: &'a str) -> anyhow::Result<Option<Captures<'a>>> {
    Ok(compile_pattern(pattern)?.captures(text))
}

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

    #[test]
    fn pattern_backslashes() {
        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*)");
    }
}