| 1 | // SPDX-License-Identifier: Apache-2.0 |
| 2 | // Copyright (c) 2026 UtopiaIA |
| 3 | |
| 4 | //! The link between a repository and the hub it lives on: the file |
| 5 | //! `.braid/hub`, a JSON object `{"url", "repo"}`, with `"paths"` for a |
| 6 | //! sparse clone, written by `braid hub publish` and `braid hub clone`. |
| 7 | //! |
| 8 | //! The other entries of `.braid` are `store/`, `git/`, `ws/`, `work/` and |
| 9 | //! `config`, so the name clashes with none of them; a workspace's own |
| 10 | //! `.braid` is a file in the workspace's directory, never this one. |
| 11 | |
| 12 | use std::fs; |
| 13 | use std::io; |
| 14 | use std::path::{Path, PathBuf}; |
| 15 | |
| 16 | use anyhow::{Context, Result, bail}; |
| 17 | use braid_hubproto::RepoPath; |
| 18 | use braid_repo::Repo; |
| 19 | use serde::{Deserialize, Serialize}; |
| 20 | |
| 21 | use super::creds::normalize_url; |
| 22 | |
| 23 | /// The link's file name inside `.braid`. |
| 24 | pub(crate) const FILE: &str = "hub"; |
| 25 | |
| 26 | /// Where a repository lives on a hub. |
| 27 | #[derive(Clone, Debug, PartialEq, Eq)] |
| 28 | pub(crate) struct Link { |
| 29 | /// The hub's URL, normalized. |
| 30 | pub(crate) url: String, |
| 31 | /// The repository on it. |
| 32 | pub(crate) repo: RepoPath, |
| 33 | /// For a sparse clone, the path prefixes whose trees it holds. |
| 34 | pub(crate) paths: Option<Vec<String>>, |
| 35 | } |
| 36 | |
| 37 | /// The file's JSON. |
| 38 | #[derive(Serialize, Deserialize)] |
| 39 | struct LinkFile { |
| 40 | url: String, |
| 41 | repo: String, |
| 42 | #[serde(default, skip_serializing_if = "Option::is_none")] |
| 43 | paths: Option<Vec<String>>, |
| 44 | } |
| 45 | |
| 46 | impl Link { |
| 47 | /// The link file of the repository whose root is `root`. |
| 48 | pub(crate) fn file(root: &Path) -> PathBuf { |
| 49 | root.join(braid_repo::DIR).join(FILE) |
| 50 | } |
| 51 | |
| 52 | /// The repository's link, or `None` when it is not linked to a hub. |
| 53 | pub(crate) fn read(repo: &Repo) -> Result<Option<Link>> { |
| 54 | let path = Link::file(repo.root()); |
| 55 | match fs::read(&path) { |
| 56 | Ok(bytes) => Link::decode(&bytes) |
| 57 | .map(Some) |
| 58 | .with_context(|| format!("{} is not a valid hub link", path.display())), |
| 59 | Err(err) if err.kind() == io::ErrorKind::NotFound => Ok(None), |
| 60 | Err(err) => Err(err).with_context(|| format!("cannot read {}", path.display())), |
| 61 | } |
| 62 | } |
| 63 | |
| 64 | /// Writes the repository's link, through a scratch file and a rename. |
| 65 | pub(crate) fn write(&self, repo: &Repo) -> Result<()> { |
| 66 | let path = Link::file(repo.root()); |
| 67 | let scratch = path.with_extension(format!("{}.tmp", std::process::id())); |
| 68 | fs::write(&scratch, self.encode()) |
| 69 | .and_then(|()| fs::rename(&scratch, &path)) |
| 70 | .with_context(|| format!("cannot write {}", path.display())) |
| 71 | } |
| 72 | |
| 73 | /// The file's bytes. |
| 74 | pub(crate) fn encode(&self) -> Vec<u8> { |
| 75 | let file = LinkFile { |
| 76 | url: self.url.clone(), |
| 77 | repo: self.repo.to_string(), |
| 78 | paths: self.paths.clone(), |
| 79 | }; |
| 80 | let mut bytes = serde_json::to_vec_pretty(&file).unwrap_or_default(); |
| 81 | bytes.push(b'\n'); |
| 82 | bytes |
| 83 | } |
| 84 | |
| 85 | /// Reads the file's bytes, checking every field. |
| 86 | pub(crate) fn decode(bytes: &[u8]) -> Result<Link> { |
| 87 | let file: LinkFile = serde_json::from_slice(bytes)?; |
| 88 | let paths = file |
| 89 | .paths |
| 90 | .map(|paths| paths.iter().map(|path| path_prefix(path)).collect()) |
| 91 | .transpose()?; |
| 92 | Ok(Link { |
| 93 | url: normalize_url(&file.url)?, |
| 94 | repo: file.repo.parse()?, |
| 95 | paths, |
| 96 | }) |
| 97 | } |
| 98 | |
| 99 | /// The path prefixes of a sparse clone, as the object walk takes them. |
| 100 | pub(crate) fn prefixes(&self) -> Option<Vec<Vec<u8>>> { |
| 101 | self.paths |
| 102 | .as_ref() |
| 103 | .map(|paths| paths.iter().map(|path| path.as_bytes().to_vec()).collect()) |
| 104 | } |
| 105 | } |
| 106 | |
| 107 | /// A path prefix as the hub takes it: names separated by `/`, without a |
| 108 | /// `/` at either end, and no empty, `.` or `..` name. |
| 109 | pub(crate) fn path_prefix(text: &str) -> Result<String> { |
| 110 | let trimmed = text.trim_matches('/'); |
| 111 | if trimmed.is_empty() |
| 112 | || trimmed |
| 113 | .split('/') |
| 114 | .any(|name| name.is_empty() || name == "." || name == "..") |
| 115 | { |
| 116 | bail!( |
| 117 | "{text:?} is not a path prefix: give a directory or a file of the repository, such as src/net" |
| 118 | ); |
| 119 | } |
| 120 | Ok(trimmed.to_owned()) |
| 121 | } |
| 122 | |
| 123 | #[cfg(test)] |
| 124 | mod tests { |
| 125 | use super::*; |
| 126 | |
| 127 | #[test] |
| 128 | fn written_and_read_back() { |
| 129 | let dir = tempfile::tempdir().unwrap(); |
| 130 | let repo = Repo::init(dir.path()).unwrap(); |
| 131 | assert_eq!(Link::read(&repo).unwrap(), None); |
| 132 | let link = Link { |
| 133 | url: "https://hub.example.org".to_owned(), |
| 134 | repo: "Ada/demo".parse().unwrap(), |
| 135 | paths: None, |
| 136 | }; |
| 137 | link.write(&repo).unwrap(); |
| 138 | assert_eq!(Link::read(&repo).unwrap(), Some(link.clone())); |
| 139 | let text = fs::read_to_string(dir.path().join(".braid/hub")).unwrap(); |
| 140 | assert!(text.contains("\"repo\": \"ada/demo\""), "{text}"); |
| 141 | assert!(!text.contains("paths"), "{text}"); |
| 142 | let sparse = Link { |
| 143 | paths: Some(vec!["src/net".to_owned(), "docs".to_owned()]), |
| 144 | ..link |
| 145 | }; |
| 146 | sparse.write(&repo).unwrap(); |
| 147 | let read = Link::read(&repo).unwrap().unwrap(); |
| 148 | assert_eq!(read, sparse); |
| 149 | assert_eq!( |
| 150 | read.prefixes().unwrap(), |
| 151 | [b"src/net".to_vec(), b"docs".to_vec()] |
| 152 | ); |
| 153 | // Nothing else was left in .braid, and the repository opens and |
| 154 | // checks as before. |
| 155 | let mut entries: Vec<String> = fs::read_dir(dir.path().join(".braid")) |
| 156 | .unwrap() |
| 157 | .map(|entry| entry.unwrap().file_name().to_string_lossy().into_owned()) |
| 158 | .collect(); |
| 159 | entries.sort(); |
| 160 | assert_eq!(entries, ["hub", "store"]); |
| 161 | let reopened = Repo::open(dir.path()).unwrap(); |
| 162 | assert!(reopened.store().fsck().unwrap().is_clean()); |
| 163 | } |
| 164 | |
| 165 | #[test] |
| 166 | fn a_workspace_named_hub_is_elsewhere() { |
| 167 | let dir = tempfile::tempdir().unwrap(); |
| 168 | let repo = Repo::init(dir.path()).unwrap(); |
| 169 | Link { |
| 170 | url: "https://hub.example.org".to_owned(), |
| 171 | repo: "ada/demo".parse().unwrap(), |
| 172 | paths: None, |
| 173 | } |
| 174 | .write(&repo) |
| 175 | .unwrap(); |
| 176 | let ws_dir = braid_wc::Workspace::default_dir(&repo, "hub"); |
| 177 | braid_wc::Workspace::create(&repo, "hub", &ws_dir, None, "main").unwrap(); |
| 178 | assert!(Link::read(&repo).unwrap().is_some()); |
| 179 | assert!(ws_dir.join(".braid").is_file()); |
| 180 | } |
| 181 | |
| 182 | #[test] |
| 183 | fn invalid_links_are_refused() { |
| 184 | for bad in [ |
| 185 | &b"not json"[..], |
| 186 | br#"{"url": "https://hub.example.org"}"#, |
| 187 | br#"{"url": "http://hub.example.org", "repo": "ada/demo"}"#, |
| 188 | br#"{"url": "https://hub.example.org", "repo": "ada"}"#, |
| 189 | br#"{"url": "https://hub.example.org", "repo": "ada/demo", "paths": ["../x"]}"#, |
| 190 | ] { |
| 191 | assert!( |
| 192 | Link::decode(bad).is_err(), |
| 193 | "{}", |
| 194 | String::from_utf8_lossy(bad) |
| 195 | ); |
| 196 | } |
| 197 | } |
| 198 | |
| 199 | #[test] |
| 200 | fn path_prefixes() { |
| 201 | assert_eq!(path_prefix("/src/net/").unwrap(), "src/net"); |
| 202 | assert_eq!(path_prefix("README.md").unwrap(), "README.md"); |
| 203 | for bad in ["", "/", "a//b", "./a", "a/..", "../etc"] { |
| 204 | assert!(path_prefix(bad).is_err(), "{bad}"); |
| 205 | } |
| 206 | } |
| 207 | } |