//! Reading a project's `repos[]` entry — the port of //! `packages/code-hosting/src/remote.ts`. //! //! A project stores normalized remotes (`github.com/decemberfm/cottondb`), but a //! person may have pasted an https, ssh or scp URL into the same field, so every //! form a git remote can take is read HERE and nowhere else. The host is the //! ONLY thing that decides which API answers: `github.com` is GitHub, and //! anything else is a Forgejo instance serving `/api/v1` from its own origin. //! There is no allowlist of known Forgejo hosts on purpose — a self-hosted //! instance the owner stands up tomorrow must work without a code change. //! //! **Why this is here and not in the phone's read.** The rule is a domain rule //! about somebody's git remote, and it is read by the screen that lists a //! project's repositories, by whatever opens one, and eventually by anything //! that files a commit. A copy per caller is a copy that disagrees about the //! scp form, which is the one every naive implementation gets wrong. use serde::{Deserialize, Serialize}; use crate::relay_address::{HouseholdAddress, RelayAddress}; /// Which API answers for a host. #[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] #[serde(rename_all = "lowercase")] pub enum CodeHostKind { Github, Forgejo, Cotton, } impl CodeHostKind { pub const fn as_str(self) -> &'static str { match self { CodeHostKind::Github => "github", CodeHostKind::Forgejo => "forgejo", CodeHostKind::Cotton => "cotton", } } } /// One repository, addressed. #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] pub struct RepoRef { pub host: String, pub owner: String, pub repo: String, pub kind: CodeHostKind, } impl RepoRef { /// `owner/repo` — what a person reads on a picker row. pub fn label(&self) -> String { format!("{}/{}", self.owner, self.repo) } /// The case-insensitive `host/owner/repo` identity, after remote URL parsing. pub fn key(&self) -> String { format!("{}/{}/{}", self.host, self.owner, self.repo).to_ascii_lowercase() } /// Where this repo's API answers. GitHub's lives on another origin entirely. pub fn api_base_url(&self) -> String { match self.kind { CodeHostKind::Github => "https://api.github.com".to_string(), CodeHostKind::Forgejo => format!("https://{}/api/v1", self.host), CodeHostKind::Cotton => format!("https://{}", self.host), } } /// The BROWSER url, which is the host's own origin — never the API base. pub fn web_url(&self) -> String { match self.kind { CodeHostKind::Cotton => { let path = clone_path_for(&self.owner, &self.repo); let path = path.strip_suffix(".git").unwrap_or(&path); format!("https://{}{path}", self.host) } CodeHostKind::Github | CodeHostKind::Forgejo => { format!("https://{}/{}/{}", self.host, self.owner, self.repo) } } } /// Where the BYTES come from — `.git`. /// /// Beside [`Self::web_url`] because the two are one fact about a host: the /// page a person opens and the url `git clone` takes differ by four /// characters, and a second spelling of it somewhere else is a mirror that /// clones the wrong thing. pub fn clone_url(&self) -> String { format!("{}.git", self.web_url()) } } /// `github.com` is the one host with an API on a different origin. pub fn host_kind(host: &str) -> CodeHostKind { if host.eq_ignore_ascii_case("github.com") { CodeHostKind::Github } else { CodeHostKind::Forgejo } } /// The last two path segments are the owner and the repo — a `.git` suffix and /// any trailing slashes come off first, and a path with fewer than two segments /// names no repository at all. /// /// **A HOST UNDER THE RELAY DOMAIN IS COTTON, NEVER A GIT HOST.** Checked here, /// before [`host_kind`] is asked, because `host_kind` answers Forgejo for every /// host it does not know — and a household's own Cotton address read as a /// Forgejo instance is a repository row for a host with no API, asking for a /// token that cannot exist (28 Sep 2026: the Cotton project's /// `asha.relay.cottondb.com/git/decemberfm/cottondb` minted exactly that). /// A relay host whose label is not a relay name is on nobody's Cotton and on no /// git host either, so it reads as nothing. /// /// **WHICH RELAY.** The reading household's own (`relay`), and Cotton's — /// see [`relay_holding`]. fn from_parts(relay: &RelayAddress, host: &str, path: &str) -> Option { let mut trimmed = path.trim_end_matches('/'); if let Some(stripped) = strip_git_suffix(trimmed) { trimmed = stripped; } let segments: Vec<&str> = trimmed.split('/').filter(|part| !part.is_empty()).collect(); if segments.len() < 2 { return None; } let owner = segments[segments.len() - 2]; let repo = segments[segments.len() - 1]; let host = host.to_lowercase(); if let Some(on) = relay_holding(relay, &host) { let label = on.label_of_host(&host)?; if !crate::device::pairing::matches_relay_name_pattern(label) { return None; } return Some(RepoAddress::Cotton(CottonAddress { relay: on, relay_name: label.to_string(), owner: owner.to_string(), repo: repo.to_string(), })); } Some(RepoAddress::Host(RepoRef { kind: host_kind(&host), host, owner: owner.to_string(), repo: repo.to_string(), })) } /// `…​.git` or `…​.git/`, case-insensitively — the suffix a clone URL carries. /// /// The last four BYTES are asked for through `get`, never sliced. A remote is /// free text an assistant wrote, so it can end in a multi-byte character /// (`github.com/o/😀ab` is four bytes of emoji before two of ASCII), and /// `&text[len - 4..]` on one of those is a panic — which, across the FFI, is a /// process abort rather than the silent drop this module promises. fn strip_git_suffix(path: &str) -> Option<&str> { let without_slash = path.strip_suffix('/').unwrap_or(path); let at = without_slash.len().checked_sub(4)?; let tail = without_slash.get(at..)?; tail.eq_ignore_ascii_case(".git") .then(|| &without_slash[..at]) } /// A scheme is a letter followed by letters, digits, `+`, `.` or `-`, then /// `://` — read by hand rather than by regex, because the same shape is asked /// about twice below and a compiled regex per call is a cost this pays on every /// row of a project list. fn split_scheme(url: &str) -> Option<(&str, &str)> { let at = url.find("://")?; let scheme = &url[..at]; let mut characters = scheme.chars(); let first = characters.next()?; if !first.is_ascii_alphabetic() { return None; } if !characters.all(|c| c.is_ascii_alphanumeric() || matches!(c, '+' | '.' | '-')) { return None; } Some((scheme, &url[at + 3..])) } /// The canonical form of a repository URL — what a checkout is filed under on /// a Mac, and what a Mac reports a repository as. /// /// Scheme, user, port and a trailing `.git` or `/` stripped, then `https://` /// in front. The WHOLE path is kept, which is what makes it different from /// [`parse_repo_ref`]: a repository Cotton hosts is addressed as /// `.relay.cottondb.com/git//`, three segments, and that /// address is what a session carries. An empty or unrecognisable URL answers /// `None` rather than an empty string, because "no repository" and "a /// repository whose name is nothing" are different answers. pub fn canonical_repo_url(url: &str) -> Option { let mut rest = url.trim(); if rest.is_empty() { return None; } // `scheme://` if let Some(at) = rest.find("://") { let scheme = &rest[..at]; if !scheme.is_empty() && scheme .chars() .all(|c| c.is_ascii_alphanumeric() || matches!(c, '+' | '.' | '-')) { rest = &rest[at + 3..]; } } // `user@` if let Some(at) = rest.find('@') { if !rest[..at].contains('/') { rest = &rest[at + 1..]; } } // `host:port/` and the scp-style `host:path` let mut text = rest.to_string(); if let Some(colon) = text.find(':') { let (host, after) = text.split_at(colon); let after = &after[1..]; if !host.contains('/') { let port: String = after.chars().take_while(char::is_ascii_digit).collect(); if !port.is_empty() && after[port.len()..].starts_with('/') { text = format!("{host}{}", &after[port.len()..]); } else { text = format!("{host}/{after}"); } } } let trimmed = text.trim_end_matches('/'); let trimmed = trimmed.strip_suffix(".git").unwrap_or(trimmed); let trimmed = trimmed.trim_end_matches('/'); if trimmed.is_empty() { return None; } Some(format!("https://{trimmed}")) } /// Parse a remote into host/owner/repo, or `None` when it cannot be read — the /// caller decides how loud to be. Accepts: /// /// * `github.com/decemberfm/cottondb` — the stored form /// * `https://git.example.org/decemberfm/cottondb(.git)(/)` /// * `ssh://git@git.example.org:2222/decemberfm/cottondb.git` /// * `git@github.com:decemberfm/cottondb.git` — the scp form /// /// A Cotton address answers `None` HERE: it names no git host, so nothing /// that dials one, keys a row by one or asks for its token may be handed it. /// [`read_repo_address`] is the reading that keeps it, and /// [`project_repo_refs`] is where one resolves to the repository it names. pub fn parse_repo_ref(relay: &RelayAddress, raw: &str) -> Option { match read_repo_address(relay, raw)? { RepoAddress::Host(found) => Some(found), RepoAddress::Cotton(_) => None, } } /// Read a remote into what it names: a repository on a git host, or one a /// household's Cotton serves. Every form [`parse_repo_ref`] accepts, and the /// Cotton address `./git//` in any of them — /// on `relay`, the relay of the household doing the reading, or on Cotton's. pub fn read_repo_address(relay: &RelayAddress, raw: &str) -> Option { let url = raw.trim(); if url.is_empty() { return None; } // scheme://[user@]host[:port]/path if let Some((_, rest)) = split_scheme(url) { let after_user = rest.split_once('@').map_or( rest, |(user, tail)| { if user.contains('/') { rest } else { tail } }, ); let (authority, path) = after_user.split_once('/')?; let host = authority.split(':').next()?; if host.is_empty() || path.is_empty() { return None; } return from_parts(relay, host, path); } // scp form: [user@]host:path — a `:` followed by a PATH, never a port. if let Some((head, tail)) = url.split_once(':') { let host = head.rsplit('@').next().unwrap_or(head); let user_part = head.split_once('@').map(|(user, _)| user); let head_is_authority = !head.contains('/') && user_part.is_none_or(|user| !user.contains('/')) && !host.is_empty(); // `host:2222/owner/repo` is an ssh URL missing its scheme, not a repo // called `2222`. A port is digits followed by a slash. let looks_like_port = tail .split_once('/') .is_some_and(|(head, _)| !head.is_empty() && head.chars().all(|c| c.is_ascii_digit())); if head_is_authority && !looks_like_port && !tail.is_empty() { return from_parts(relay, host, tail.trim_start_matches('/')); } } // The stored form: host/owner/repo, no scheme. The host must LOOK like one // — a dot and no colon — so a bare `owner/repo` is refused rather than read // as a repository on a host called "owner". if let Some((host, path)) = url.split_once('/') { let looks_like_host = host.contains('.') && !host.contains(':') && !host.chars().any(char::is_whitespace) && !host.starts_with('.') && !host.ends_with('.'); if looks_like_host && !path.is_empty() { return from_parts(relay, host, path); } } None } /// Every readable remote a project names, in the project's own order, with the /// unreadable ones DROPPED and duplicates folded by key. /// /// Silent about what it drops, deliberately: the field is free text an /// assistant writes, and a screen that refused to list four repositories /// because a fifth entry is a typo would be unusable. The screens say "this /// project names no repository" when nothing survives, which is the fact a /// person can act on. /// /// **A COTTON ADDRESS RESOLVES; IT NEVER BECOMES A REPOSITORY OF ITS OWN.** One /// on this household's relay name is the repository [`OwnCotton`] holds under /// that owner and name — the SAME row the git host's address names, so the two /// fold into one here. One on another household's name, or one this household /// holds nothing under, is dropped like any other entry that names nothing /// this database can read: it never mints a row and never asks for a token. pub fn project_repo_refs<'a>( raw: impl IntoIterator, own: &OwnCotton, ) -> Vec { let mut seen: Vec = Vec::new(); let mut out: Vec = Vec::new(); for entry in raw { let found = match read_repo_address(own.at.relay(), entry) { Some(RepoAddress::Host(found)) => found, Some(RepoAddress::Cotton(address)) => match own.resolve(&address) { Some(held) => held.clone(), None => continue, }, None => continue, }; let key = found.key(); if seen.contains(&key) { continue; } seen.push(key); out.push(found); } out } // ── the household's own Cotton ────────────────────────────────────────────── /// A repository a household's Cotton serves, as a remote spells it: /// `./git//`. #[derive(Debug, Clone, PartialEq, Eq)] pub struct CottonAddress { /// The relay the household is reached through — part of the address: the /// same name under another relay is another household. pub relay: RelayAddress, pub relay_name: String, pub owner: String, pub repo: String, } impl CottonAddress { /// The same natural key used by hosted repositories and discovery. pub fn key(&self) -> String { RepoRef { host: self.host(), owner: self.owner.clone(), repo: self.repo.clone(), kind: CodeHostKind::Cotton, } .key() } /// `.` — the host a person reads as the repository's /// home, built by the relay the address is on /// (`no-relay-host-literal.test.ts`: nothing here spells a domain). /// /// A name that is not a relay name never makes a `CottonAddress` — /// [`read_repo_address`] and [`cotton_home`] both check — so the fallback /// is unreachable rather than a silent second answer. pub fn host(&self) -> String { if crate::device::pairing::matches_relay_name_pattern(&self.relay_name) { self.relay.host(&self.relay_name) } else { self.relay_name.clone() } } /// `https://./git//` — the address a /// checkout's remote carries, less its `.git`: [`clone_path_for`] is the /// one spelling of the path. pub fn web_url(&self) -> String { let path = clone_path_for(&self.owner, &self.repo); let path = path.strip_suffix(".git").unwrap_or(&path); format!("https://{}{path}", self.host()) } } /// What a remote names. #[derive(Debug, Clone, PartialEq, Eq)] pub enum RepoAddress { /// A repository on a git host — GitHub, or a Forgejo instance. Host(RepoRef), /// A repository a household's Cotton serves. Cotton(CottonAddress), } /// This household's own Cotton: where it answers, and every repository it holds /// AND is the origin of — which is all a Cotton address can name. /// /// Built by whoever has the database open, from [`OwnCotton::REPOS_SQL`] and /// the workspace's address (`cotton_tools::household_address`); this crate does no I/O, and one spelling of /// the query is what keeps the Mac's worker and the phone's page resolving an /// address to the same row. #[derive(Debug, Clone, Default, PartialEq, Eq)] pub struct OwnCotton { at: HouseholdAddress, repos: Vec, } impl OwnCotton { /// The rows a Cotton address can resolve to: held, and Cotton the origin. /// The move writer rekeys each one to its Cotton home before this reader /// runs, so the row's host is the home rather than its former git host. pub const REPOS_SQL: &'static str = "SELECT host, owner, name FROM cotton_repos \ WHERE held = 1 AND origin = 'cotton' ORDER BY key"; /// Where the household answers, as its workspace row says, and the /// `(host, owner, name)` of each rekeyed row [`Self::REPOS_SQL`] answers. pub fn new<'a>( at: HouseholdAddress, repos: impl IntoIterator, ) -> OwnCotton { OwnCotton { at, repos: repos .into_iter() .map(|(host, owner, name)| { let host = host.to_lowercase(); RepoRef { kind: CodeHostKind::Cotton, host, owner: owner.to_string(), repo: name.to_string(), } }) .collect(), } } /// The repository a Cotton address names, when it is on THIS household's /// relay AND name and this household holds it — the same name under /// another relay is somebody else's Cotton. Owner and name are matched /// the way a host matches them, without regard to case. pub fn resolve(&self, address: &CottonAddress) -> Option<&RepoRef> { let ours = self.at.name()?; if &address.relay != self.at.relay() || !address.relay_name.eq_ignore_ascii_case(ours) { return None; } self.repos.iter().find(|held| { held.owner.eq_ignore_ascii_case(&address.owner) && held.repo.eq_ignore_ascii_case(&address.repo) }) } /// The Cotton address a repository [`project_repo_refs`] answered LIVES /// at — `Some` for one this household holds and is the origin of, in a /// household with a relay name; `None` for a repository whose home is /// still its git host. pub fn home_of(&self, found: &RepoRef) -> Option { let key = found.key(); if !self.repos.iter().any(|held| held.key() == key) { return None; } cotton_home( &self.at, &found.owner, &found.repo, true, Some("cotton"), ) } } /// Where a repository LIVES now, when that is Cotton: the Cotton address of a /// repository this household holds and is the origin of. /// /// `None` for every other row — one not held, one whose origin is still a git /// host, and one in a household with no relay name, which has no address /// another machine could reach. The move writer updates the row's key, host, /// kind and bound project remotes to this address together. Its stable row id /// keeps every child and undo receipt attached through the move. pub fn cotton_home( at: &HouseholdAddress, owner: &str, repo: &str, held: bool, origin: Option<&str>, ) -> Option { if !held || origin != Some("cotton") || owner.is_empty() || repo.is_empty() { return None; } let name = at.name()?; if !crate::device::pairing::matches_relay_name_pattern(name) { return None; } Some(CottonAddress { relay: at.relay().clone(), relay_name: name.to_string(), owner: owner.to_string(), repo: repo.to_string(), }) } /// Is this a host under a relay's domain — somebody's Cotton, and never a git /// host? The `repos` worker retires a row keyed by one (`reap`). A relay's /// own apex counts: it is no git host either. pub fn is_cotton_host(relay: &RelayAddress, host: &str) -> bool { relay_holding(relay, &host.to_ascii_lowercase()).is_some() } /// The relay a host is under, of the two this household can know: its own, and /// Cotton's. /// /// Its own first — that is where its repositories live. Cotton's as well, /// because a household on its own relay may still be handed another /// household's address under Cotton's, and that host has no git API for /// anybody: read as a Forgejo instance it is the 28 Sep 2026 row again. A /// THIRD household's private relay cannot be known from here and reads as the /// git host its spelling says it is, like any other host nobody listed. fn relay_holding(relay: &RelayAddress, host: &str) -> Option { if relay.holds(host) { return Some(relay.clone()); } let cotton = RelayAddress::cotton(); cotton.holds(host).then_some(cotton) } /// The path a Cotton-served repository answers `git` on, relative to a Mac's /// own origin — `/git//.git`. /// /// Declared here rather than spelled into the route file because it is read /// twice from opposite ends: `cotton-server` mounts it, and Settings › Code /// hosting prints the URL a person copies. Two spellings of it is a clone URL /// that 404s on a Mac that is serving perfectly. pub fn clone_path_for(owner: &str, repo: &str) -> String { format!("/git/{owner}/{repo}.git") } /// The clone URL a person copies off Settings › Code hosting. /// /// **THE PATH IS THE HOST THE MAC ALREADY ANSWERS** (design "Code hosting", /// decision 3): a second hostname would cost a two-label DNS wildcard the zone /// does not have, an SNI grammar change in the relay and its Rust twin, a /// second ACME order and an SNI-aware certificate resolver on every Mac. The /// path costs one route file. /// /// `None` when the household has no relay name yet, and that is a STATE rather /// than a placeholder: a Mac reached only over the local network has no URL a /// checkout on another machine could keep, so the panel says so instead of /// printing something that would fail the day the laptop left the house. The /// name is checked against the relay's own grammar /// ([`crate::device::pairing::matches_relay_name_pattern`]), so a column /// holding something that is not a relay name answers `None` rather than /// composing a host nobody answers. The host is under the household's OWN /// relay (`at`), which is where its Mac answers. /// /// `None` too when the name is the OTHER app's (`crate::flavor`): a Cotton /// Dev checkout never fetches from or pushes to CottonDB's household, nor the /// reverse. This process's declared flavor is read here, at the outermost /// call; [`clone_url_as`] is the pure core. pub fn clone_url_for(at: &HouseholdAddress, owner: &str, repo: &str) -> Option { clone_url_as(at, owner, repo, crate::flavor::current()) } /// [`clone_url_for`] for an explicit app. `None` flavor (a process that /// declared nothing) has no rule to apply. pub fn clone_url_as( at: &HouseholdAddress, owner: &str, repo: &str, flavor: Option, ) -> Option { let name = at.name()?; if flavor.is_some_and(|flavor| !flavor.admits_relay_name(name)) { return None; } if !crate::device::pairing::matches_relay_name_pattern(name) { return None; } Some(format!("{}{}", at.relay().origin(name), clone_path_for(owner, repo))) } #[cfg(test)] #[path = "repo_ref_tests.rs"] mod tests;