Skip to main content

subspace_contracts/github/
recognition.rs

1//! Strict, canonical GitHub pull request links. Parsing the original bytes
2//! avoids accepting URL-parser rewrites of dot segments, escapes or backslashes.
3
4const PREFIX: &str = "https://github.com/";
5const MAX_OWNER: usize = 39;
6const MAX_REPOSITORY: usize = 100;
7/// Matches the GitHub client's supported item-number range.
8const NUMBER_LIMIT: u32 = 1_000_000_000;
9/// Pull request tabs whose URL still names the pull request itself.
10const LENIENT_SUFFIXES: [&str; 2] = ["/files", "/commits"];
11
12/// A validated pull request identity. It contains no account or credentials.
13#[derive(Clone, Debug, PartialEq, Eq)]
14pub struct PullRequestLink {
15    repo: String,
16    number: u32,
17}
18
19impl PullRequestLink {
20    /// Accepts only `https://github.com/<owner>/<repo>/pull/<number>`.
21    /// Owner logins use ASCII letters/digits and single internal hyphens;
22    /// repository names use ASCII letters/digits, `.`, `_` and `-`.
23    /// Userinfo, ports, suffix paths, queries, fragments and escapes are refused.
24    pub fn parse(url: &str) -> Option<Self> {
25        let parts: Vec<_> = url.strip_prefix(PREFIX)?.split('/').collect();
26        let [owner, repo, "pull", number] = parts.as_slice() else {
27            return None;
28        };
29        if !valid_owner(owner) || !valid_repository(repo) || !valid_number(number) {
30            return None;
31        }
32        Some(Self {
33            repo: format!("{owner}/{repo}"),
34            number: number.parse().ok()?,
35        })
36    }
37
38    /// Accepts what [`parse`](Self::parse) accepts, also with one of the
39    /// suffixes GitHub's own pages add: a query, a fragment (such as
40    /// `#discussion_r1`), `/files`, `/commits` or a trailing `/`. The
41    /// identity is the same pull request; callers keep the original URL to
42    /// open it as written.
43    // qual:api - Consumed by app crates through the Framework facade.
44    pub fn parse_lenient(url: &str) -> Option<Self> {
45        let end = url.find(['?', '#']).unwrap_or(url.len());
46        let path = &url[..end];
47        let path = path.strip_suffix('/').unwrap_or(path);
48        let path = LENIENT_SUFFIXES
49            .iter()
50            .find_map(|suffix| path.strip_suffix(suffix))
51            .unwrap_or(path);
52        Self::parse(path)
53    }
54
55    /// The pull request a qualified `owner/repository#number` key names, as
56    /// [`key`](Self::key) writes it. A key without an owner is refused.
57    pub fn from_key(key: &str) -> Option<Self> {
58        let (repo, number) = key.split_once('#')?;
59        let (owner, name) = repo.split_once('/')?;
60        if !valid_owner(owner) || !valid_repository(name) || !valid_number(number) {
61            return None;
62        }
63        Some(Self {
64            repo: repo.to_owned(),
65            number: number.parse().ok()?,
66        })
67    }
68
69    pub fn repo(&self) -> &str {
70        &self.repo
71    }
72
73    pub fn number(&self) -> u32 {
74        self.number
75    }
76
77    /// The board's `owner/repository#number` item identity.
78    pub fn key(&self) -> String {
79        format!("{}#{}", self.repo, self.number)
80    }
81
82    pub fn url(&self) -> String {
83        format!("{PREFIX}{}/pull/{}", self.repo, self.number)
84    }
85}
86
87fn valid_owner(owner: &str) -> bool {
88    !owner.is_empty()
89        && owner.len() <= MAX_OWNER
90        && owner.starts_with(|c: char| c.is_ascii_alphanumeric())
91        && owner.ends_with(|c: char| c.is_ascii_alphanumeric())
92        && !owner.contains("--")
93        && owner
94            .bytes()
95            .all(|b| b.is_ascii_alphanumeric() || b == b'-')
96}
97
98fn valid_repository(repo: &str) -> bool {
99    !repo.is_empty()
100        && repo.len() <= MAX_REPOSITORY
101        && !matches!(repo, "." | "..")
102        && repo
103            .bytes()
104            .all(|b| b.is_ascii_alphanumeric() || matches!(b, b'.' | b'_' | b'-'))
105}
106
107fn valid_number(number: &str) -> bool {
108    !number.is_empty()
109        && number.bytes().all(|b| b.is_ascii_digit())
110        && number
111            .parse::<u32>()
112            .is_ok_and(|n| (1..NUMBER_LIMIT).contains(&n))
113}