Elffuss BraidHub

utopia-ia/elffuss-braid public

main · 6.9 KiBRawPermalink
1// SPDX-License-Identifier: Apache-2.0
2// Copyright (c) 2026 UtopiaIA
3
4//! Owners, repository names, and the globs of `land:<glob>` rights.
5
6use std::fmt;
7use std::str::FromStr;
8
9/// Why a name is not valid.
10#[derive(Clone, Debug, PartialEq, Eq, thiserror::Error)]
11pub enum NameError {
12 /// Not a GitHub login.
13 #[error(
14 "{0:?} is not a GitHub login: 1 to 39 letters, digits or single hyphens, not at either end"
15 )]
16 Owner(String),
17 /// Not a repository name.
18 #[error(
19 "{0:?} is not a repository name: 1 to 100 of letters, digits, '.', '_' and '-', not starting with '.' or ending with \".git\""
20 )]
21 Name(String),
22 /// Not `owner/name`.
23 #[error("{0:?} is not a repository: expected \"owner/name\"")]
24 Path(String),
25}
26
27/// Whether `owner` is a GitHub login: 1 to 39 ASCII letters, digits and
28/// hyphens, with no hyphen at either end and no two in a row.
29pub fn is_owner(owner: &str) -> bool {
30 !owner.is_empty()
31 && owner.len() <= 39
32 && owner
33 .bytes()
34 .all(|b| b.is_ascii_alphanumeric() || b == b'-')
35 && !owner.starts_with('-')
36 && !owner.ends_with('-')
37 && !owner.contains("--")
38}
39
40/// Whether `name` is a repository name: 1 to 100 of ASCII letters, digits,
41/// `.`, `_` and `-`, not starting with `.` and not ending with `.git`.
42pub fn is_repo_name(name: &str) -> bool {
43 !name.is_empty()
44 && name.len() <= 100
45 && name
46 .bytes()
47 .all(|b| b.is_ascii_alphanumeric() || matches!(b, b'.' | b'_' | b'-'))
48 && !name.starts_with('.')
49 && !name.to_ascii_lowercase().ends_with(".git")
50}
51
52/// A repository on a hub: `owner/name`, the owner lowercase.
53#[derive(Clone, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)]
54pub struct RepoPath {
55 /// The owner's GitHub login, lowercase.
56 pub owner: String,
57 /// The repository's name, as given.
58 pub name: String,
59}
60
61impl RepoPath {
62 /// Checks both parts; the owner is lowercased.
63 pub fn new(owner: &str, name: &str) -> Result<RepoPath, NameError> {
64 if !is_owner(owner) {
65 return Err(NameError::Owner(owner.to_owned()));
66 }
67 if !is_repo_name(name) {
68 return Err(NameError::Name(name.to_owned()));
69 }
70 Ok(RepoPath {
71 owner: owner.to_ascii_lowercase(),
72 name: name.to_owned(),
73 })
74 }
75
76 /// The path of the repository's routes: `/v1/r/<owner>/<name>`.
77 pub fn api_path(&self) -> String {
78 format!("/v1/r/{}/{}", self.owner, self.name)
79 }
80}
81
82impl FromStr for RepoPath {
83 type Err = NameError;
84
85 fn from_str(text: &str) -> Result<Self, Self::Err> {
86 let (owner, name) = text
87 .split_once('/')
88 .ok_or_else(|| NameError::Path(text.to_owned()))?;
89 RepoPath::new(owner, name)
90 }
91}
92
93impl fmt::Display for RepoPath {
94 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
95 write!(f, "{}/{}", self.owner, self.name)
96 }
97}
98
99/// Whether a ref name is one of braid's own, which clients never write:
100/// under `braid/` or `remote/`.
101pub fn is_internal_ref(name: &str) -> bool {
102 name.starts_with("braid/") || name.starts_with("remote/")
103}
104
105/// Whether the glob of a `land:<glob>` right matches the ref `name`. `*`
106/// alone matches every ref; otherwise `*` matches any run of characters
107/// other than `/`, and everything else matches itself.
108///
109/// Since `*` never matches a `/`, the glob's parts between slashes match the
110/// name's one for one, and each part is matched going back no further than
111/// its last `*`: time bounded by the product of the lengths, never
112/// exponential, whatever globs and names a client sends.
113pub fn glob_matches(glob: &str, name: &str) -> bool {
114 if glob == "*" {
115 return true;
116 }
117 let mut globs = glob.split('/');
118 let mut names = name.split('/');
119 loop {
120 match (globs.next(), names.next()) {
121 (None, None) => return true,
122 (Some(glob), Some(name)) if part_matches(glob.as_bytes(), name.as_bytes()) => {}
123 _ => return false,
124 }
125 }
126}
127
128/// Whether `glob`, in which `*` matches any run of bytes, matches all of
129/// `name`.
130fn part_matches(glob: &[u8], name: &[u8]) -> bool {
131 let (mut g, mut n) = (0, 0);
132 // Just after the last `*` seen, and where its match ends so far.
133 let mut star: Option<(usize, usize)> = None;
134 while n < name.len() {
135 if glob.get(g) == Some(&b'*') {
136 g += 1;
137 star = Some((g, n));
138 } else if glob.get(g) == Some(&name[n]) {
139 g += 1;
140 n += 1;
141 } else if let Some((after, end)) = star {
142 g = after;
143 n = end + 1;
144 star = Some((after, n));
145 } else {
146 return false;
147 }
148 }
149 glob[g..].iter().all(|byte| *byte == b'*')
150}
151
152#[cfg(test)]
153mod tests {
154 use super::*;
155
156 #[test]
157 fn owners() {
158 for good in ["kikocis", "Kiko-Cis", "a", "a1-b2"] {
159 assert!(is_owner(good), "{good}");
160 }
161 for bad in ["", "-a", "a-", "a--b", "a_b", "a.b", &"a".repeat(40)] {
162 assert!(!is_owner(bad), "{bad}");
163 }
164 }
165
166 #[test]
167 fn repo_names() {
168 for good in ["braid", "elffuss-braid", "a.b_c-d", "x"] {
169 assert!(is_repo_name(good), "{good}");
170 }
171 for bad in [
172 "",
173 ".hidden",
174 "a/b",
175 "a b",
176 "repo.git",
177 "repo.GIT",
178 &"a".repeat(101),
179 ] {
180 assert!(!is_repo_name(bad), "{bad}");
181 }
182 }
183
184 #[test]
185 fn repo_paths() {
186 let path: RepoPath = "KikoCis/elffuss-braid".parse().unwrap();
187 assert_eq!(path.owner, "kikocis");
188 assert_eq!(path.to_string(), "kikocis/elffuss-braid");
189 assert_eq!(path.api_path(), "/v1/r/kikocis/elffuss-braid");
190 assert!("nobody".parse::<RepoPath>().is_err());
191 assert!("a/b/c".parse::<RepoPath>().is_err());
192 }
193
194 #[test]
195 fn globs() {
196 assert!(glob_matches("*", "main"));
197 assert!(glob_matches("*", "release/1.0"));
198 assert!(glob_matches("main", "main"));
199 assert!(!glob_matches("main", "mainline"));
200 assert!(glob_matches("release/*", "release/1.0"));
201 assert!(!glob_matches("release/*", "release/1/2"));
202 assert!(glob_matches("agents/*/work", "agents/a1/work"));
203 assert!(!glob_matches("agents/*", "main"));
204 assert!(glob_matches("release/*", "release/"));
205 assert!(glob_matches("*-x*", "a-xb") && glob_matches("a*b*c", "abc"));
206 assert!(glob_matches("a*b*c", "a-b-b-c") && !glob_matches("a*b*c", "a-b-b-"));
207 assert!(glob_matches("**", "x") && !glob_matches("**", "x/y"));
208 // Globs that backtrack forever, matched at once.
209 let name = "a".repeat(4096);
210 let glob = format!("{}b", "*a".repeat(50));
211 assert!(!glob_matches(&glob, &name));
212 assert!(glob_matches(&glob, &format!("{name}b")));
213 }
214}