subspace_contracts/github/
recognition.rs1const PREFIX: &str = "https://github.com/";
5const MAX_OWNER: usize = 39;
6const MAX_REPOSITORY: usize = 100;
7const NUMBER_LIMIT: u32 = 1_000_000_000;
9const LENIENT_SUFFIXES: [&str; 2] = ["/files", "/commits"];
11
12#[derive(Clone, Debug, PartialEq, Eq)]
14pub struct PullRequestLink {
15 repo: String,
16 number: u32,
17}
18
19impl PullRequestLink {
20 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 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 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 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}