//! Owner and repository names (hub spec ยง3.2) and the top-level path //! segments no owner may take. use std::fmt; /// `owner/name`, both validated. #[derive(Clone, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)] pub struct RepoName { pub owner: String, pub name: String, } /// Top-level path segments reserved for the hub itself. pub const RESERVED: &[&str] = &[ "api", "static", "login", "logout", "register", "settings", "explore", "search", "notifications", "new", "orgs", "admin", "style.css", "favicon.ico", "favicon.svg", "health", "avatar", "help", "projects", "assets", ".well-known", // Live pages, CSP reports and the security pages (oxygenhub#204, #222, #224, #230). "live", "csp-report", "security.txt", "security-contact", // The transparency log, the metrics and Insights (oxygenhub#238, #212, #257). "log", "metrics", "insights", ]; /// `[A-Za-z0-9][A-Za-z0-9._-]{0,63}`, not `.`/`..`, not ending in `.git`. pub fn valid_segment(s: &str) -> bool { let mut chars = s.chars(); let Some(first) = chars.next() else { return false }; if !first.is_ascii_alphanumeric() || s.len() > 64 { return false; } if !chars.all(|c| c.is_ascii_alphanumeric() || matches!(c, '.' | '_' | '-')) { return false; } s != "." && s != ".." && !s.ends_with(".git") } pub fn valid_owner(s: &str) -> bool { valid_segment(s) && !RESERVED.contains(&s) } impl RepoName { pub fn new(owner: &str, name: &str) -> Option { if valid_owner(owner) && valid_segment(name) { Some(RepoName { owner: owner.into(), name: name.into() }) } else { None } } /// `owner/name`. pub fn parse(slug: &str) -> Option { let (owner, name) = slug.split_once('/')?; RepoName::new(owner, name) } pub fn url(&self) -> String { format!("/{}/{}", self.owner, self.name) } } impl fmt::Display for RepoName { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { write!(f, "{}/{}", self.owner, self.name) } } #[cfg(test)] mod tests { use super::*; #[test] fn names() { assert!(RepoName::parse("andy/oxygen").is_some()); assert!(RepoName::parse("andy/oxy.gen-2_x").is_some()); assert!(RepoName::parse("api/x").is_none(), "reserved owner"); assert!(RepoName::parse("andy/x.git").is_none(), "mirror URL"); assert!(RepoName::parse("andy/..").is_none()); assert!(RepoName::parse(".andy/x").is_none()); assert!(RepoName::parse("andy/a b").is_none()); assert!(RepoName::parse("andy").is_none()); assert!(RepoName::parse(&format!("andy/{}", "a".repeat(65))).is_none()); assert_eq!(RepoName::parse("andy/oxygen").unwrap().url(), "/andy/oxygen"); } }