Skip to main content

subspace_client_github/issue_report/
repository.rs

1//! The GitHub repository a report files into, supplied by the app.
2
3/// GitHub's longest owner (user or organisation) name.
4const MAX_OWNER: usize = 39;
5/// GitHub's longest repository name.
6const MAX_NAME: usize = 100;
7
8/// A GitHub repository as `owner/name`, checked so it can be placed in API
9/// paths and URLs as it is.
10#[derive(Debug, Clone, PartialEq, Eq)]
11pub struct IssueRepository(String);
12
13impl IssueRepository {
14    /// `owner/name`, trimmed. The owner is letters, digits and inner
15    /// hyphens; the name is letters, digits, `-`, `_` and `.`, but not `.`
16    /// or `..`.
17    pub fn parse(value: &str) -> Option<Self> {
18        let value = value.trim();
19        let (owner, name) = value.split_once('/')?;
20        (valid_owner(owner) && valid_name(name)).then(|| Self(value.to_owned()))
21    }
22
23    pub fn as_str(&self) -> &str {
24        &self.0
25    }
26
27    /// The repository's issue list.
28    pub fn issues_url(&self) -> String {
29        format!("https://github.com/{}/issues", self.0)
30    }
31
32    /// GitHub's blank new-issue editor for this repository.
33    pub fn new_issue_url(&self) -> String {
34        format!("{}/new?template=blank", self.issues_url())
35    }
36
37    /// Only a positive issue number in this repository, over HTTPS, is safe
38    /// to open.
39    pub fn is_created_issue_url(&self, url: &str) -> bool {
40        let prefix = format!("{}/", self.issues_url());
41        let Some(number) = url.strip_prefix(&prefix) else {
42            return false;
43        };
44        !number.is_empty()
45            && number.bytes().all(|byte| byte.is_ascii_digit())
46            && number.parse::<u64>().is_ok_and(|number| number > 0)
47    }
48}
49
50fn valid_owner(owner: &str) -> bool {
51    (1..=MAX_OWNER).contains(&owner.len())
52        && owner
53            .bytes()
54            .all(|byte| byte.is_ascii_alphanumeric() || byte == b'-')
55        && !owner.starts_with('-')
56        && !owner.ends_with('-')
57}
58
59fn valid_name(name: &str) -> bool {
60    (1..=MAX_NAME).contains(&name.len())
61        && name
62            .bytes()
63            .all(|byte| byte.is_ascii_alphanumeric() || matches!(byte, b'-' | b'_' | b'.'))
64        && name != "."
65        && name != ".."
66}