Skip to main content

gitpoulpi_hosting/account/
namespace.rs

1//! The profile's Namespaces filter: which repositories the account-wide
2//! lists keep. Applied to every list the Radar shows (review requests,
3//! assigned issues, every open request), because the host's own queries for
4//! the first two are global and ignore the namespaces.
5//!
6//! Plain mode: a line matches a repository's full path (`group/sub/proj`)
7//! when it equals the path or is a path prefix ending at a `/` boundary
8//! (`orbit` matches `orbit/products/x`, never `orbitx/y`), ignoring case. Regex
9//! mode: each line is a regular expression run against the full path as the
10//! user wrote it (unanchored unless the pattern says `^` / `$`).
11
12use regex::Regex;
13
14/// A compiled Namespaces filter; empty = keep everything.
15#[derive(Debug, Clone)]
16pub struct NamespaceFilter {
17    plain: Vec<String>,
18    regexes: Vec<Regex>,
19}
20
21impl NamespaceFilter {
22    /// Compiles `lines`; in regex mode the first invalid line is an error
23    /// naming it and the regex engine's reason.
24    pub fn new(lines: &[String], regex: bool) -> Result<Self, String> {
25        let lines = lines.iter().map(|l| l.trim()).filter(|l| !l.is_empty());
26        if regex {
27            let mut regexes = Vec::new();
28            for line in lines {
29                regexes.push(compile(line)?);
30            }
31            Ok(Self {
32                plain: Vec::new(),
33                regexes,
34            })
35        } else {
36            Ok(Self {
37                plain: lines
38                    .map(|l| l.trim_matches('/').to_lowercase())
39                    .filter(|l| !l.is_empty())
40                    .collect(),
41                regexes: Vec::new(),
42            })
43        }
44    }
45
46    /// Whether no line is set (the filter keeps every repository).
47    pub fn is_empty(&self) -> bool {
48        self.plain.is_empty() && self.regexes.is_empty()
49    }
50
51    /// Whether the repository `path` (`owner/name`, `group/sub/proj`) is kept.
52    pub fn matches(&self, path: &str) -> bool {
53        if self.is_empty() {
54            return true;
55        }
56        let lower = path.trim_matches('/').to_lowercase();
57        self.plain.iter().any(|ns| {
58            lower == *ns
59                || lower
60                    .strip_prefix(ns.as_str())
61                    .is_some_and(|rest| rest.starts_with('/'))
62        }) || self.regexes.iter().any(|re| re.is_match(path))
63    }
64}
65
66/// One regex line, or `"<line>: <why>"`.
67pub fn compile(line: &str) -> Result<Regex, String> {
68    Regex::new(line).map_err(|e| format!("{line}: {}", headline(&e.to_string())))
69}
70
71/// The regex error's headline, without its multi-line source drawing.
72fn headline(error: &str) -> String {
73    error
74        .lines()
75        .rev()
76        .find(|l| l.trim_start().starts_with("error:"))
77        .map(|l| {
78            l.trim_start()
79                .trim_start_matches("error:")
80                .trim()
81                .to_string()
82        })
83        .unwrap_or_else(|| error.lines().next().unwrap_or("").to_string())
84}
85
86/// The first invalid line of `lines` in regex mode, as `"<line>: <why>"`.
87pub fn first_regex_error(lines: &[String]) -> Option<String> {
88    lines
89        .iter()
90        .map(|l| l.trim())
91        .filter(|l| !l.is_empty())
92        .find_map(|l| compile(l).err())
93}
94
95#[cfg(test)]
96mod tests {
97    use super::*;
98
99    fn lines(items: &[&str]) -> Vec<String> {
100        items.iter().map(|s| s.to_string()).collect()
101    }
102
103    fn plain(items: &[&str]) -> NamespaceFilter {
104        NamespaceFilter::new(&lines(items), false).unwrap()
105    }
106
107    #[test]
108    fn a_plain_namespace_is_a_path_prefix_at_a_slash() {
109        let f = plain(&["orbit"]);
110        assert!(f.matches("orbit/products/x"));
111        assert!(f.matches("orbit/x"));
112        assert!(f.matches("orbit"));
113        assert!(f.matches("ORBIT/x"));
114        assert!(!f.matches("orbitx/y"));
115        assert!(!f.matches("training/orbit/x"));
116        assert!(!f.matches("training/a"));
117    }
118
119    #[test]
120    fn a_nested_namespace_and_a_full_project_path_match() {
121        let f = plain(&["orbit/products", "other/repo"]);
122        assert!(f.matches("orbit/products/x/y"));
123        assert!(f.matches("other/repo"));
124        assert!(!f.matches("orbit/training/x"));
125        assert!(!f.matches("other/repo2"));
126        assert!(plain(&["/orbit/"]).matches("orbit/x"));
127    }
128
129    #[test]
130    fn several_lines_are_alternatives_and_none_keeps_everything() {
131        let f = plain(&["orbit", "acme"]);
132        assert!(f.matches("acme/a") && f.matches("orbit/b") && !f.matches("training/c"));
133        let none = plain(&[]);
134        assert!(none.is_empty() && none.matches("anything/at/all"));
135        assert!(plain(&["  ", ""]).is_empty());
136    }
137
138    #[test]
139    fn regex_lines_match_the_full_path_as_written() {
140        let f = NamespaceFilter::new(&lines(&["^orbit/(products|infra)/", "docs$"]), true).unwrap();
141        assert!(f.matches("orbit/products/x"));
142        assert!(f.matches("orbit/infra/y"));
143        assert!(f.matches("training/docs"));
144        assert!(!f.matches("orbit/training/x"));
145        assert!(!f.matches("training/docs2"));
146        // Unanchored: a bare word matches anywhere in the path.
147        let loose = NamespaceFilter::new(&lines(&["orbit"]), true).unwrap();
148        assert!(loose.matches("training/orbitx/y"));
149    }
150
151    #[test]
152    fn an_invalid_regex_is_an_error_naming_the_line_never_a_panic() {
153        let bad = lines(&["^ok/", "(unclosed"]);
154        let err = NamespaceFilter::new(&bad, true).unwrap_err();
155        assert!(err.starts_with("(unclosed: "), "{err}");
156        assert_eq!(first_regex_error(&bad), Some(err));
157        assert_eq!(first_regex_error(&lines(&["^ok/"])), None);
158        // The same text is a fine plain namespace.
159        assert!(NamespaceFilter::new(&bad, false).is_ok());
160    }
161}