| 1 | // SPDX-License-Identifier: Apache-2.0 |
| 2 | // Copyright (c) 2026 UtopiaIA |
| 3 | |
| 4 | //! Finding the repository from a repository root or from a workspace. |
| 5 | //! |
| 6 | //! A workspace directory holds a `.braid` file, never tracked, that names its |
| 7 | //! repository and the workspace: |
| 8 | //! |
| 9 | //! ```text |
| 10 | //! braid-workspace 1 |
| 11 | //! name agent-1 |
| 12 | //! repository /absolute/path/of/the/repository |
| 13 | //! ``` |
| 14 | //! |
| 15 | //! Values are written with [`escape`](crate::text::escape), so any path fits. |
| 16 | //! The workspace's own state lives in the repository, under |
| 17 | //! `.braid/ws/<name>/`. |
| 18 | |
| 19 | use std::fs; |
| 20 | use std::io; |
| 21 | use std::path::{Path, PathBuf}; |
| 22 | |
| 23 | use crate::text::{escape, path_bytes, path_from_bytes, unescape}; |
| 24 | use crate::{DIR, Error, STORE_DIR}; |
| 25 | |
| 26 | /// Directory inside `.braid` that holds one directory of state per |
| 27 | /// workspace. |
| 28 | pub const WORKSPACES_DIR: &str = "ws"; |
| 29 | |
| 30 | /// Directory inside `.braid` where workspaces go unless told otherwise: |
| 31 | /// `.braid/work/<name>`, inside the project, where git ignores them along |
| 32 | /// with the rest of `.braid`. |
| 33 | pub const WORK_DIR: &str = "work"; |
| 34 | |
| 35 | /// The first line of a workspace file. |
| 36 | const HEADER: &str = "braid-workspace 1"; |
| 37 | |
| 38 | /// What a workspace's `.braid` file records. |
| 39 | #[derive(Clone, Debug, PartialEq, Eq)] |
| 40 | pub struct WorkspaceLink { |
| 41 | /// The repository's root directory: absolute, so that the workspace can |
| 42 | /// be anywhere. |
| 43 | pub repository: PathBuf, |
| 44 | /// The workspace's name; see [`WorkspaceLink::is_valid_name`]. |
| 45 | pub name: String, |
| 46 | } |
| 47 | |
| 48 | impl WorkspaceLink { |
| 49 | /// Whether `name` can name a workspace: 1 to 64 ASCII letters, digits, |
| 50 | /// `.`, `_` or `-`, starting with a letter or a digit. Names are used as |
| 51 | /// directory names inside the repository, so nothing else is accepted. |
| 52 | pub fn is_valid_name(name: &str) -> bool { |
| 53 | let bytes = name.as_bytes(); |
| 54 | !bytes.is_empty() |
| 55 | && bytes.len() <= 64 |
| 56 | && bytes[0].is_ascii_alphanumeric() |
| 57 | && bytes |
| 58 | .iter() |
| 59 | .all(|byte| byte.is_ascii_alphanumeric() || matches!(byte, b'.' | b'_' | b'-')) |
| 60 | } |
| 61 | |
| 62 | /// The file's contents. |
| 63 | pub fn encode(&self) -> Vec<u8> { |
| 64 | let repository = path_bytes(&self.repository).unwrap_or_default(); |
| 65 | format!( |
| 66 | "{HEADER}\nname {}\nrepository {}\n", |
| 67 | escape(self.name.as_bytes()), |
| 68 | escape(&repository) |
| 69 | ) |
| 70 | .into_bytes() |
| 71 | } |
| 72 | |
| 73 | /// Reads the contents of a workspace file. |
| 74 | pub fn decode(bytes: &[u8]) -> Result<Self, String> { |
| 75 | let text = std::str::from_utf8(bytes).map_err(|_| "not UTF-8".to_owned())?; |
| 76 | let mut lines = text.lines(); |
| 77 | if lines.next() != Some(HEADER) { |
| 78 | return Err(format!("the first line is not {HEADER:?}")); |
| 79 | } |
| 80 | let mut name = None; |
| 81 | let mut repository = None; |
| 82 | for line in lines { |
| 83 | let (key, value) = line.split_once(' ').unwrap_or((line, "")); |
| 84 | let value = unescape(value).ok_or_else(|| format!("bad escape in {key:?}"))?; |
| 85 | match key { |
| 86 | "name" => name = Some(value), |
| 87 | "repository" => repository = Some(value), |
| 88 | // Later versions may add lines; this one ignores them. |
| 89 | _ => {} |
| 90 | } |
| 91 | } |
| 92 | let name = name |
| 93 | .and_then(|name| String::from_utf8(name).ok()) |
| 94 | .filter(|name| Self::is_valid_name(name)) |
| 95 | .ok_or("no valid workspace name")?; |
| 96 | let repository = repository |
| 97 | .and_then(|bytes| path_from_bytes(&bytes)) |
| 98 | .filter(|path| path.is_absolute()) |
| 99 | .ok_or("no absolute repository path")?; |
| 100 | Ok(WorkspaceLink { repository, name }) |
| 101 | } |
| 102 | |
| 103 | /// Reads the workspace file at `path`. |
| 104 | pub fn read(path: &Path) -> Result<Self, Error> { |
| 105 | let bytes = fs::read(path)?; |
| 106 | Self::decode(&bytes).map_err(|detail| Error::BadWorkspaceFile { |
| 107 | path: path.to_path_buf(), |
| 108 | detail, |
| 109 | }) |
| 110 | } |
| 111 | } |
| 112 | |
| 113 | /// Where a search for a repository stopped. |
| 114 | #[derive(Clone, Debug, PartialEq, Eq)] |
| 115 | pub enum Location { |
| 116 | /// A repository root: a directory holding a `.braid` directory. |
| 117 | Root(PathBuf), |
| 118 | /// A workspace: a directory holding a `.braid` file. |
| 119 | Workspace { |
| 120 | /// The workspace directory. |
| 121 | dir: PathBuf, |
| 122 | /// What its `.braid` file says. |
| 123 | link: WorkspaceLink, |
| 124 | }, |
| 125 | } |
| 126 | |
| 127 | /// Finds the nearest directory, `start` or one of its parents, that is a |
| 128 | /// repository root or a workspace. |
| 129 | /// |
| 130 | /// A `.braid` directory counts only when it holds a store. A `.braid` file |
| 131 | /// must be a regular file, not a symlink, and must be valid: a damaged one |
| 132 | /// is an error rather than a reason to keep looking further up. |
| 133 | pub fn locate(start: &Path) -> Result<Location, Error> { |
| 134 | for dir in start.ancestors() { |
| 135 | let marker = dir.join(DIR); |
| 136 | if marker.join(STORE_DIR).is_dir() { |
| 137 | return Ok(Location::Root(dir.to_path_buf())); |
| 138 | } |
| 139 | match fs::symlink_metadata(&marker) { |
| 140 | Ok(meta) if meta.is_file() => { |
| 141 | let link = WorkspaceLink::read(&marker)?; |
| 142 | return Ok(Location::Workspace { |
| 143 | dir: dir.to_path_buf(), |
| 144 | link, |
| 145 | }); |
| 146 | } |
| 147 | Ok(_) => {} |
| 148 | Err(err) if err.kind() == io::ErrorKind::NotFound => {} |
| 149 | Err(err) => return Err(err.into()), |
| 150 | } |
| 151 | } |
| 152 | Err(Error::NotFound) |
| 153 | } |
| 154 | |
| 155 | #[cfg(test)] |
| 156 | mod tests { |
| 157 | use super::*; |
| 158 | |
| 159 | #[test] |
| 160 | fn names() { |
| 161 | for good in ["a", "agent-1", "A.b_c", "0"] { |
| 162 | assert!(WorkspaceLink::is_valid_name(good), "{good}"); |
| 163 | } |
| 164 | for bad in [ |
| 165 | "", |
| 166 | ".", |
| 167 | "..", |
| 168 | ".hidden", |
| 169 | "-x", |
| 170 | "a/b", |
| 171 | "a b", |
| 172 | "é", |
| 173 | &"x".repeat(65), |
| 174 | ] { |
| 175 | assert!(!WorkspaceLink::is_valid_name(bad), "{bad}"); |
| 176 | } |
| 177 | } |
| 178 | |
| 179 | #[test] |
| 180 | fn links_round_trip() { |
| 181 | let link = WorkspaceLink { |
| 182 | repository: PathBuf::from("/srv/repos/with space/and%percent"), |
| 183 | name: "agent-7".to_owned(), |
| 184 | }; |
| 185 | let bytes = link.encode(); |
| 186 | assert!(bytes.starts_with(HEADER.as_bytes())); |
| 187 | assert_eq!(WorkspaceLink::decode(&bytes).unwrap(), link); |
| 188 | |
| 189 | for bad in [ |
| 190 | &b""[..], |
| 191 | b"braid-workspace 2\nname a\nrepository /r\n", |
| 192 | b"braid-workspace 1\nname ../x\nrepository /r\n", |
| 193 | b"braid-workspace 1\nname a\nrepository relative\n", |
| 194 | b"braid-workspace 1\nname a\n", |
| 195 | ] { |
| 196 | assert!(WorkspaceLink::decode(bad).is_err(), "{bad:?}"); |
| 197 | } |
| 198 | } |
| 199 | } |