| 1 | // SPDX-License-Identifier: Apache-2.0 |
| 2 | // Copyright (c) 2026 UtopiaIA |
| 3 | |
| 4 | //! The state of a workspace, kept in the repository under |
| 5 | //! `.braid/ws/<name>/`: |
| 6 | //! |
| 7 | //! ```text |
| 8 | //! state what the workspace is at (below) |
| 9 | //! stat the stat cache |
| 10 | //! lock locked while a command changes the workspace |
| 11 | //! ``` |
| 12 | //! |
| 13 | //! `state` is a small text file, rewritten whole through a scratch file and |
| 14 | //! a rename. Values are escaped with [`braid_repo::text::escape`]. |
| 15 | //! |
| 16 | //! ```text |
| 17 | //! braid-workspace-state 1 |
| 18 | //! path <workspace directory> |
| 19 | //! branch <branch it lands on> |
| 20 | //! base <changeset the working copy is at, or none> |
| 21 | //! upstream <last changeset of the branch it was brought onto, or none> |
| 22 | //! fs ignores-case=<yes|no> ignores-normalization=<yes|no> |
| 23 | //! checkout <from tree> <to tree> only while a checkout is unfinished |
| 24 | //! track <path> one per `braid track` |
| 25 | //! rebase-change <changeset> only while a rebase is in progress: |
| 26 | //! rebase-onto <changeset> the changeset being rebased, where |
| 27 | //! rebase-pending <changeset> to, those still to rebase after it, |
| 28 | //! conflict <code> <markers> <resolved> <path> and its conflicts |
| 29 | //! ``` |
| 30 | |
| 31 | use std::fs::{self, File, OpenOptions}; |
| 32 | use std::io::Write; |
| 33 | use std::path::{Path, PathBuf}; |
| 34 | |
| 35 | use braid_format::ObjectId; |
| 36 | use braid_repo::text::{escape, path_bytes, path_from_bytes, unescape}; |
| 37 | |
| 38 | use crate::error::Error; |
| 39 | use crate::fsprobe::{FileSystem, random_hex}; |
| 40 | |
| 41 | const HEADER: &str = "braid-workspace-state 1"; |
| 42 | |
| 43 | /// The file that holds the state, inside the workspace's state directory. |
| 44 | pub(crate) const FILE: &str = "state"; |
| 45 | |
| 46 | /// The lock file, inside the workspace's state directory. |
| 47 | pub(crate) const LOCK: &str = "lock"; |
| 48 | |
| 49 | /// One conflict of a rebase in progress. |
| 50 | #[derive(Clone, Debug, PartialEq, Eq)] |
| 51 | pub struct RecordedConflict { |
| 52 | /// Where it is. |
| 53 | pub path: Vec<u8>, |
| 54 | /// Its kind, as [`braid_engine::ConflictKind::code`] names it. |
| 55 | pub code: String, |
| 56 | /// Whether the file was written with conflict markers. Such a conflict |
| 57 | /// is resolved by editing them out; any other by `braid resolve`. |
| 58 | pub markers: bool, |
| 59 | /// Whether `braid resolve` marked it resolved. |
| 60 | pub resolved: bool, |
| 61 | } |
| 62 | |
| 63 | /// A checkout that was started and not finished: the working copy may be |
| 64 | /// anywhere between the two trees. |
| 65 | #[derive(Clone, Copy, Debug, PartialEq, Eq)] |
| 66 | pub struct Checkout { |
| 67 | /// The tree the working copy was at. |
| 68 | pub from: ObjectId, |
| 69 | /// The tree it was being brought to. |
| 70 | pub to: ObjectId, |
| 71 | } |
| 72 | |
| 73 | /// A rebase stopped by conflicts, waiting for `braid commit`. |
| 74 | #[derive(Clone, Debug, PartialEq, Eq)] |
| 75 | pub struct Rebase { |
| 76 | /// The changeset being rebased. |
| 77 | pub change: ObjectId, |
| 78 | /// Where it goes: the workspace's base while the rebase lasts, and the |
| 79 | /// parent of the changeset that `braid commit` makes. |
| 80 | pub onto: ObjectId, |
| 81 | /// Changesets to rebase after it, oldest first. |
| 82 | pub pending: Vec<ObjectId>, |
| 83 | /// Its conflicts. |
| 84 | pub conflicts: Vec<RecordedConflict>, |
| 85 | } |
| 86 | |
| 87 | /// What a workspace is at. |
| 88 | #[derive(Clone, Debug, PartialEq, Eq)] |
| 89 | pub struct State { |
| 90 | /// The workspace directory. |
| 91 | pub path: PathBuf, |
| 92 | /// The branch it lands on and updates from. |
| 93 | pub branch: String, |
| 94 | /// The changeset its working copy is at; `None` before the first commit |
| 95 | /// on a branch that does not exist yet. |
| 96 | pub base: Option<ObjectId>, |
| 97 | /// The last changeset of the branch that the workspace was brought onto: |
| 98 | /// where its own changesets start. A hint, checked before it is used. |
| 99 | pub upstream: Option<ObjectId>, |
| 100 | /// What its file system takes for the same name. |
| 101 | pub fs: FileSystem, |
| 102 | /// Set while a checkout is not finished. |
| 103 | pub checkout: Option<Checkout>, |
| 104 | /// Paths given to `braid track`. |
| 105 | pub tracked: Vec<Vec<u8>>, |
| 106 | /// The rebase in progress, if any. |
| 107 | pub rebase: Option<Rebase>, |
| 108 | } |
| 109 | |
| 110 | impl State { |
| 111 | /// Reads the state file in `dir`. |
| 112 | pub(crate) fn load(dir: &Path) -> Result<State, Error> { |
| 113 | let path = dir.join(FILE); |
| 114 | let bytes = fs::read(&path).map_err(Error::io("read", &path))?; |
| 115 | decode(&bytes).map_err(|detail| Error::BadState { path, detail }) |
| 116 | } |
| 117 | |
| 118 | /// Writes the state file in `dir`, durably, through a scratch file and |
| 119 | /// a rename. |
| 120 | pub(crate) fn save(&self, dir: &Path) -> Result<(), Error> { |
| 121 | let target = dir.join(FILE); |
| 122 | let scratch = dir.join(format!("{FILE}.tmp-{}", random_hex())); |
| 123 | let written = File::create_new(&scratch) |
| 124 | .and_then(|mut file| { |
| 125 | file.write_all(self.encode().as_bytes())?; |
| 126 | file.sync_all() |
| 127 | }) |
| 128 | .and_then(|()| fs::rename(&scratch, &target)) |
| 129 | .and_then(|()| File::open(dir)?.sync_all()); |
| 130 | if written.is_err() { |
| 131 | let _ = fs::remove_file(&scratch); |
| 132 | } |
| 133 | written.map_err(Error::io("write", &target)) |
| 134 | } |
| 135 | |
| 136 | fn encode(&self) -> String { |
| 137 | let id = |id: Option<ObjectId>| id.map_or_else(|| "none".to_owned(), |id| id.to_hex()); |
| 138 | let yes = |flag: bool| if flag { "yes" } else { "no" }; |
| 139 | let mut text = format!( |
| 140 | "{HEADER}\npath {}\nbranch {}\nbase {}\nupstream {}\nfs ignores-case={} ignores-normalization={}\n", |
| 141 | escape(&path_bytes(&self.path).unwrap_or_default()), |
| 142 | escape(self.branch.as_bytes()), |
| 143 | id(self.base), |
| 144 | id(self.upstream), |
| 145 | yes(self.fs.ignores_case), |
| 146 | yes(self.fs.ignores_normalization), |
| 147 | ); |
| 148 | if let Some(Checkout { from, to }) = self.checkout { |
| 149 | text.push_str(&format!("checkout {from} {to}\n")); |
| 150 | } |
| 151 | for path in &self.tracked { |
| 152 | text.push_str(&format!("track {}\n", escape(path))); |
| 153 | } |
| 154 | if let Some(rebase) = &self.rebase { |
| 155 | text.push_str(&format!("rebase-change {}\n", rebase.change)); |
| 156 | text.push_str(&format!("rebase-onto {}\n", rebase.onto)); |
| 157 | for pending in &rebase.pending { |
| 158 | text.push_str(&format!("rebase-pending {pending}\n")); |
| 159 | } |
| 160 | for conflict in &rebase.conflicts { |
| 161 | text.push_str(&format!( |
| 162 | "conflict {} {} {} {}\n", |
| 163 | conflict.code, |
| 164 | yes(conflict.markers), |
| 165 | yes(conflict.resolved), |
| 166 | escape(&conflict.path) |
| 167 | )); |
| 168 | } |
| 169 | } |
| 170 | text |
| 171 | } |
| 172 | } |
| 173 | |
| 174 | fn decode(bytes: &[u8]) -> Result<State, String> { |
| 175 | let text = std::str::from_utf8(bytes).map_err(|_| "not UTF-8".to_owned())?; |
| 176 | let mut lines = text.lines(); |
| 177 | if lines.next() != Some(HEADER) { |
| 178 | return Err(format!("the first line is not {HEADER:?}")); |
| 179 | } |
| 180 | let mut state = State { |
| 181 | path: PathBuf::new(), |
| 182 | branch: String::new(), |
| 183 | base: None, |
| 184 | upstream: None, |
| 185 | fs: FileSystem::FORGIVING, |
| 186 | checkout: None, |
| 187 | tracked: Vec::new(), |
| 188 | rebase: None, |
| 189 | }; |
| 190 | let mut change = None; |
| 191 | let mut onto = None; |
| 192 | let mut pending = Vec::new(); |
| 193 | let mut conflicts = Vec::new(); |
| 194 | for line in lines { |
| 195 | let (key, value) = line.split_once(' ').unwrap_or((line, "")); |
| 196 | let bad = || format!("bad {key} line: {line:?}"); |
| 197 | let bytes = || unescape(value).ok_or_else(bad); |
| 198 | let id = || value.parse::<ObjectId>().map_err(|_| bad()); |
| 199 | let maybe_id = || match value { |
| 200 | "none" => Ok(None), |
| 201 | _ => id().map(Some), |
| 202 | }; |
| 203 | match key { |
| 204 | "path" => state.path = path_from_bytes(&bytes()?).ok_or_else(bad)?, |
| 205 | "branch" => state.branch = String::from_utf8(bytes()?).map_err(|_| bad())?, |
| 206 | "base" => state.base = maybe_id()?, |
| 207 | "upstream" => state.upstream = maybe_id()?, |
| 208 | "fs" => { |
| 209 | state.fs = FileSystem { |
| 210 | ignores_case: value.contains("ignores-case=yes"), |
| 211 | ignores_normalization: value.contains("ignores-normalization=yes"), |
| 212 | } |
| 213 | } |
| 214 | "checkout" => { |
| 215 | let (from, to) = value.split_once(' ').ok_or_else(bad)?; |
| 216 | state.checkout = Some(Checkout { |
| 217 | from: from.parse().map_err(|_| bad())?, |
| 218 | to: to.parse().map_err(|_| bad())?, |
| 219 | }); |
| 220 | } |
| 221 | "track" => state.tracked.push(bytes()?), |
| 222 | "rebase-change" => change = Some(id()?), |
| 223 | "rebase-onto" => onto = Some(id()?), |
| 224 | "rebase-pending" => pending.push(id()?), |
| 225 | "conflict" => { |
| 226 | let mut parts = value.splitn(4, ' '); |
| 227 | let (Some(code), Some(markers), Some(resolved), Some(path)) = |
| 228 | (parts.next(), parts.next(), parts.next(), parts.next()) |
| 229 | else { |
| 230 | return Err(bad()); |
| 231 | }; |
| 232 | conflicts.push(RecordedConflict { |
| 233 | path: unescape(path).ok_or_else(bad)?, |
| 234 | code: code.to_owned(), |
| 235 | markers: markers == "yes", |
| 236 | resolved: resolved == "yes", |
| 237 | }); |
| 238 | } |
| 239 | // Later versions may add lines; this one ignores them. |
| 240 | _ => {} |
| 241 | } |
| 242 | } |
| 243 | if state.branch.is_empty() { |
| 244 | return Err("no branch".to_owned()); |
| 245 | } |
| 246 | match (change, onto) { |
| 247 | (Some(change), Some(onto)) => { |
| 248 | state.rebase = Some(Rebase { |
| 249 | change, |
| 250 | onto, |
| 251 | pending, |
| 252 | conflicts, |
| 253 | }); |
| 254 | } |
| 255 | (None, None) => {} |
| 256 | _ => return Err("an incomplete rebase".to_owned()), |
| 257 | } |
| 258 | Ok(state) |
| 259 | } |
| 260 | |
| 261 | /// The lock of a workspace, held until dropped. |
| 262 | #[derive(Debug)] |
| 263 | pub(crate) struct Lock { |
| 264 | _file: File, |
| 265 | } |
| 266 | |
| 267 | impl Lock { |
| 268 | /// Waits for the lock of the workspace whose state is in `dir`. |
| 269 | pub(crate) fn acquire(dir: &Path) -> Result<Lock, Error> { |
| 270 | let path = dir.join(LOCK); |
| 271 | let file = OpenOptions::new() |
| 272 | .read(true) |
| 273 | .write(true) |
| 274 | .create(true) |
| 275 | .truncate(false) |
| 276 | .open(&path) |
| 277 | .map_err(Error::io("open", &path))?; |
| 278 | file.lock().map_err(Error::io("lock", &path))?; |
| 279 | Ok(Lock { _file: file }) |
| 280 | } |
| 281 | } |
| 282 | |
| 283 | #[cfg(test)] |
| 284 | mod tests { |
| 285 | use super::*; |
| 286 | use braid_format::Kind; |
| 287 | |
| 288 | #[test] |
| 289 | fn round_trip() { |
| 290 | let dir = tempfile::tempdir().unwrap(); |
| 291 | let a = ObjectId::hash(Kind::Changeset, b"a"); |
| 292 | let b = ObjectId::hash(Kind::Changeset, b"b"); |
| 293 | let mut state = State { |
| 294 | path: PathBuf::from("/work/agent 1"), |
| 295 | branch: "main".to_owned(), |
| 296 | base: Some(a), |
| 297 | upstream: None, |
| 298 | fs: FileSystem { |
| 299 | ignores_case: true, |
| 300 | ignores_normalization: false, |
| 301 | }, |
| 302 | checkout: Some(Checkout { |
| 303 | from: ObjectId::hash(Kind::Tree, b"t"), |
| 304 | to: ObjectId::hash(Kind::Tree, b"u"), |
| 305 | }), |
| 306 | tracked: vec![b".env".to_vec(), b"keys/id rsa".to_vec()], |
| 307 | rebase: None, |
| 308 | }; |
| 309 | state.save(dir.path()).unwrap(); |
| 310 | assert_eq!(State::load(dir.path()).unwrap(), state); |
| 311 | |
| 312 | state.rebase = Some(Rebase { |
| 313 | change: a, |
| 314 | onto: b, |
| 315 | pending: vec![a, b], |
| 316 | conflicts: vec![RecordedConflict { |
| 317 | path: b"dir/with space\n".to_vec(), |
| 318 | code: "CONTENT".to_owned(), |
| 319 | markers: true, |
| 320 | resolved: false, |
| 321 | }], |
| 322 | }); |
| 323 | state.checkout = None; |
| 324 | state.save(dir.path()).unwrap(); |
| 325 | assert_eq!(State::load(dir.path()).unwrap(), state); |
| 326 | // Only the state file is left. |
| 327 | assert_eq!(fs::read_dir(dir.path()).unwrap().count(), 1); |
| 328 | |
| 329 | fs::write( |
| 330 | dir.path().join(FILE), |
| 331 | "braid-workspace-state 1\nbase nonsense\n", |
| 332 | ) |
| 333 | .unwrap(); |
| 334 | assert!(matches!( |
| 335 | State::load(dir.path()), |
| 336 | Err(Error::BadState { .. }) |
| 337 | )); |
| 338 | } |
| 339 | |
| 340 | #[test] |
| 341 | fn the_lock_excludes_other_holders() { |
| 342 | let dir = tempfile::tempdir().unwrap(); |
| 343 | let held = Lock::acquire(dir.path()).unwrap(); |
| 344 | let other = File::open(dir.path().join(LOCK)).unwrap(); |
| 345 | assert!(other.try_lock().is_err()); |
| 346 | drop(held); |
| 347 | assert!(other.try_lock().is_ok()); |
| 348 | } |
| 349 | } |