Skip to main content

subspace_contracts/issues/recognition/
reference.rs

1//! Bare issue identifiers, such as `SUB-827`, in plain text.
2
3use std::{collections::HashSet, ops::Range};
4
5const MIN_PROJECT_KEY_LENGTH: usize = 2;
6const MAX_PROJECT_KEY_LENGTH: usize = 10;
7
8#[derive(Debug, Clone, PartialEq, Eq)]
9pub struct IssueReference {
10    identifier: String,
11    range: Range<usize>,
12}
13
14impl IssueReference {
15    pub fn identifier(&self) -> &str {
16        &self.identifier
17    }
18    pub fn range(&self) -> Range<usize> {
19        self.range.clone()
20    }
21}
22
23/// The project keys to recognise. Holds keys only, never issue content.
24#[derive(Clone, Debug, PartialEq, Eq)]
25pub struct ReferenceRecognizer {
26    keys: HashSet<String>,
27}
28
29impl Default for ReferenceRecognizer {
30    /// Recognises the example project key `TST`.
31    fn default() -> Self {
32        Self::new([], ["TST"])
33    }
34}
35
36impl ReferenceRecognizer {
37    /// Loaded keys take precedence over the fallback. Products pass no fallback.
38    pub fn new<'a>(
39        loaded: impl IntoIterator<Item = &'a str>,
40        fallback: impl IntoIterator<Item = &'a str>,
41    ) -> Self {
42        let keys = valid_keys(loaded);
43        Self {
44            keys: if keys.is_empty() {
45                valid_keys(fallback)
46            } else {
47                keys
48            },
49        }
50    }
51
52    pub fn find(&self, text: &str) -> Vec<IssueReference> {
53        let protected = protected_ranges(text);
54        text.match_indices('-')
55            .filter_map(|(dash, _)| candidate(text, dash))
56            .filter(|range| {
57                !protected
58                    .iter()
59                    .any(|p| range.start < p.end && p.start < range.end)
60            })
61            .filter(|range| self.recognises(&text[range.clone()]))
62            .map(|range| IssueReference {
63                identifier: text[range.clone()].into(),
64                range,
65            })
66            .collect()
67    }
68
69    /// Checks a complete identifier against this recogniser's selected keys.
70    pub fn recognises(&self, identifier: &str) -> bool {
71        valid_identifier(identifier)
72            && self
73                .keys
74                .contains(identifier.split('-').next().unwrap_or_default())
75    }
76}
77
78fn valid_keys<'a>(keys: impl IntoIterator<Item = &'a str>) -> HashSet<String> {
79    keys.into_iter()
80        .filter(|key| valid_key(key))
81        .map(str::to_owned)
82        .collect()
83}
84
85fn valid_key(key: &str) -> bool {
86    // Subspace project key rule: ^[A-Z][A-Z0-9]{1,9}$.
87    (MIN_PROJECT_KEY_LENGTH..=MAX_PROJECT_KEY_LENGTH).contains(&key.len())
88        && key.as_bytes().first().is_some_and(u8::is_ascii_uppercase)
89        && key
90            .bytes()
91            .all(|c| c.is_ascii_uppercase() || c.is_ascii_digit())
92}
93
94/// The identifier grammar shared by plain references.
95pub(super) fn valid_identifier(identifier: &str) -> bool {
96    let Some((key, number)) = identifier.split_once('-') else {
97        return false;
98    };
99    valid_key(key)
100        && number.as_bytes().first().is_some_and(|digit| *digit != b'0')
101        && number.bytes().all(|digit| digit.is_ascii_digit())
102        // Common technical names stay plain even if a project shares their prefix.
103        && !matches!(identifier, "UTF-8" | "ISO-8601")
104}
105
106fn candidate(text: &str, dash: usize) -> Option<Range<usize>> {
107    let start = text[..dash]
108        .char_indices()
109        .rev()
110        .find(|(_, c)| !c.is_alphanumeric() && *c != '_')
111        .map_or(0, |(i, c)| i + c.len_utf8());
112    let number_start = dash + 1;
113    let digits = text[number_start..]
114        .bytes()
115        .take_while(u8::is_ascii_digit)
116        .count();
117    let end = number_start + digits;
118    let invalid_end = text[end..]
119        .chars()
120        .next()
121        .is_some_and(|c| c.is_alphanumeric() || c == '_');
122    let invalid_start = text[..start]
123        .chars()
124        .next_back()
125        .is_some_and(|c| c == '-' || c.is_alphanumeric());
126    let date_suffix = text[end..]
127        .strip_prefix('-')
128        .is_some_and(|suffix| suffix.as_bytes().first().is_some_and(u8::is_ascii_digit));
129    if invalid_start || invalid_end || date_suffix {
130        return None;
131    }
132    Some(start..end)
133}
134
135fn protected_ranges(text: &str) -> Vec<Range<usize>> {
136    let mut offset = 0;
137    let mut ranges: Vec<_> = text
138        .split_inclusive(char::is_whitespace)
139        .filter_map(|part| {
140            let start = offset;
141            offset += part.len();
142            (part.contains("://")
143                || part.contains("www.")
144                || part.contains("mailto:")
145                || part.contains("/issues/"))
146            .then_some(start..offset)
147        })
148        .collect();
149    ranges.extend(code_ranges(text));
150    ranges
151}
152
153fn code_ranges(text: &str) -> Vec<Range<usize>> {
154    let runs = backtick_runs(text);
155    let mut ranges = Vec::new();
156    let mut index = 0;
157    while let Some(open) = runs.get(index) {
158        if let Some(offset) = runs[index + 1..]
159            .iter()
160            .position(|run| run.len() == open.len())
161        {
162            let close = index + 1 + offset;
163            ranges.push(open.start..runs[close].end);
164            index = close + 1;
165        } else {
166            index += 1;
167        }
168    }
169    ranges
170}
171
172fn backtick_runs(text: &str) -> Vec<Range<usize>> {
173    let mut runs = Vec::new();
174    let mut ticks = text.match_indices('`').peekable();
175    while let Some((start, _)) = ticks.next() {
176        let mut end = start + 1;
177        while ticks.peek().is_some_and(|(i, _)| *i == end) {
178            ticks.next();
179            end += 1;
180        }
181        runs.push(start..end);
182    }
183    runs
184}