| 1 | // SPDX-License-Identifier: Apache-2.0 |
| 2 | // Copyright (c) 2026 UtopiaIA |
| 3 | |
| 4 | //! Workspaces through the library: refusals before anything is written, |
| 5 | //! recovery of an interrupted checkout, rebases of stacks, and the errors |
| 6 | //! agents get when they ask for the wrong thing. |
| 7 | |
| 8 | mod common; |
| 9 | |
| 10 | use std::fs; |
| 11 | |
| 12 | use braid_format::{ChangeOp, Kind, ObjectId, Objects}; |
| 13 | use braid_wc::{ |
| 14 | Blocker, ChangeKind, CommitRequest, Error, Landed, RebaseProgress, Updated, Workspace, |
| 15 | }; |
| 16 | use common::{Fixture, ada}; |
| 17 | |
| 18 | fn commit_all(ws: &Workspace<'_>, message: &str) -> braid_wc::CommitOutcome { |
| 19 | ws.commit(&CommitRequest { |
| 20 | message: Some(message.as_bytes().to_vec()), |
| 21 | paths: Vec::new(), |
| 22 | author: None, |
| 23 | committer: ada(), |
| 24 | agent: "tester".to_owned(), |
| 25 | force: false, |
| 26 | }) |
| 27 | .unwrap() |
| 28 | } |
| 29 | |
| 30 | /// Bytes that do not compress. |
| 31 | fn noise(len: usize) -> Vec<u8> { |
| 32 | let mut state = 0x2545_f491_4f6c_dd1du64; |
| 33 | let mut out = Vec::with_capacity(len + 8); |
| 34 | while out.len() < len { |
| 35 | state ^= state << 13; |
| 36 | state ^= state >> 7; |
| 37 | state ^= state << 17; |
| 38 | out.extend_from_slice(&state.to_le_bytes()); |
| 39 | } |
| 40 | out.truncate(len); |
| 41 | out |
| 42 | } |
| 43 | |
| 44 | #[test] |
| 45 | fn commits_keep_edits_as_deltas_and_large_files_in_chunks() { |
| 46 | let f = Fixture::new(); |
| 47 | let mut state = 7u64; |
| 48 | let text: String = (0..3000) |
| 49 | .map(|i| { |
| 50 | state = state |
| 51 | .wrapping_mul(6_364_136_223_846_793_005) |
| 52 | .wrapping_add(1); |
| 53 | format!("line {i}: {state:016x}\n") |
| 54 | }) |
| 55 | .collect(); |
| 56 | let first = f.commit(&[], vec![("src/lib.rs", f.file(&text))]); |
| 57 | f.set_branch("main", first); |
| 58 | let dir = f.path("ws"); |
| 59 | let (ws, _) = Workspace::create(&f.repo, "ws", &dir, Some(first), "main").unwrap(); |
| 60 | |
| 61 | let edited = text.replacen("line 1500:", "line 1500, edited:", 1); |
| 62 | fs::write(dir.join("src/lib.rs"), &edited).unwrap(); |
| 63 | // New files over 1 MiB wait for `braid track`. |
| 64 | let big = noise((6 << 20) + 123); |
| 65 | fs::write(dir.join("model.bin"), &big).unwrap(); |
| 66 | ws.track(&[b"model.bin".to_vec()]).unwrap(); |
| 67 | let changeset = commit_all(&ws, "edit, and add a model").changeset.unwrap(); |
| 68 | |
| 69 | let store = f.repo.store(); |
| 70 | let report = store.fsck().unwrap(); |
| 71 | assert!(report.is_clean(), "{:#?}", report.problems); |
| 72 | // The edited file is a delta against the one it replaces. |
| 73 | assert!(report.delta_records >= 1, "{report:?}"); |
| 74 | assert_eq!(report.chunked_records, 1, "{report:?}"); |
| 75 | let blob = ObjectId::hash(Kind::Blob, &big); |
| 76 | assert_eq!( |
| 77 | store.stat(&blob).unwrap(), |
| 78 | Some((Kind::Blob, big.len() as u64)) |
| 79 | ); |
| 80 | |
| 81 | // Another workspace gets both back. |
| 82 | let other = f.path("other"); |
| 83 | Workspace::create(&f.repo, "other", &other, Some(changeset), "main").unwrap(); |
| 84 | assert!(fs::read(other.join("model.bin")).unwrap() == big); |
| 85 | assert_eq!( |
| 86 | fs::read_to_string(other.join("src/lib.rs")).unwrap(), |
| 87 | edited |
| 88 | ); |
| 89 | } |
| 90 | |
| 91 | #[test] |
| 92 | fn a_large_file_that_does_not_read_back_is_never_checked_out() { |
| 93 | let f = Fixture::new(); |
| 94 | let first = f.commit(&[], vec![("README", f.file("hello\n"))]); |
| 95 | f.set_branch("main", first); |
| 96 | let dir = f.path("ws"); |
| 97 | let (ws, _) = Workspace::create(&f.repo, "ws", &dir, Some(first), "main").unwrap(); |
| 98 | |
| 99 | let big = noise((5 << 20) + 9); |
| 100 | let blob = f.repo.store().put(Kind::Blob, &big).unwrap(); |
| 101 | let second = f.commit( |
| 102 | &[first], |
| 103 | vec![( |
| 104 | "model.bin", |
| 105 | ChangeOp::File { |
| 106 | blob, |
| 107 | size: big.len() as u64, |
| 108 | }, |
| 109 | )], |
| 110 | ); |
| 111 | f.set_branch("main", second); |
| 112 | |
| 113 | // Damage one chunk: chunks of random bytes are stored raw. |
| 114 | let needle = &big[3 << 20..(3 << 20) + 64]; |
| 115 | let mut damaged = false; |
| 116 | for entry in fs::read_dir(f.repo.store().root().join("seg")).unwrap() { |
| 117 | let path = entry.unwrap().path(); |
| 118 | let mut bytes = fs::read(&path).unwrap(); |
| 119 | if let Some(at) = bytes.windows(64).position(|window| window == needle) { |
| 120 | bytes[at + 7] ^= 0x20; |
| 121 | fs::write(&path, bytes).unwrap(); |
| 122 | damaged = true; |
| 123 | } |
| 124 | } |
| 125 | assert!(damaged); |
| 126 | |
| 127 | let result = ws.update(&ada()); |
| 128 | assert!( |
| 129 | matches!( |
| 130 | result, |
| 131 | Err(Error::Store(braid_store::Error::Corrupt { .. })) |
| 132 | ), |
| 133 | "{result:?}" |
| 134 | ); |
| 135 | // Neither the file nor a half-written scratch copy of it is left. |
| 136 | assert!(!dir.join("model.bin").exists()); |
| 137 | assert_eq!(fs::read(dir.join("README")).unwrap(), b"hello\n"); |
| 138 | let leftovers: Vec<_> = fs::read_dir(&dir) |
| 139 | .unwrap() |
| 140 | .map(|entry| entry.unwrap().file_name()) |
| 141 | .filter(|name| name.to_string_lossy().contains("tmp-")) |
| 142 | .collect(); |
| 143 | assert!(leftovers.is_empty(), "{leftovers:?}"); |
| 144 | } |
| 145 | |
| 146 | #[test] |
| 147 | fn a_file_replacing_a_directory_with_untracked_files_is_refused() { |
| 148 | let f = Fixture::new(); |
| 149 | let first = f.commit( |
| 150 | &[], |
| 151 | vec![(".gitignore", f.file("d/junk\n")), ("d/a", f.file("a"))], |
| 152 | ); |
| 153 | f.set_branch("main", first); |
| 154 | let dir = f.path("ws"); |
| 155 | let (ws, _) = Workspace::create(&f.repo, "ws", &dir, Some(first), "main").unwrap(); |
| 156 | fs::write(dir.join("d/junk"), "mine").unwrap(); |
| 157 | assert!(ws.status().unwrap().status.is_clean()); |
| 158 | |
| 159 | let second = f.commit( |
| 160 | &[first], |
| 161 | vec![("d/a", ChangeOp::Delete), ("d", f.file("now a file"))], |
| 162 | ); |
| 163 | f.set_branch("main", second); |
| 164 | let updated = ws.update(&ada()); |
| 165 | assert!( |
| 166 | matches!(&updated, Err(Error::Unsafe { path, .. }) if path == b"d/junk"), |
| 167 | "{updated:?}" |
| 168 | ); |
| 169 | // Refused before anything was written. |
| 170 | assert_eq!(fs::read(dir.join("d/a")).unwrap(), b"a"); |
| 171 | assert_eq!(fs::read(dir.join("d/junk")).unwrap(), b"mine"); |
| 172 | assert_eq!(ws.state().unwrap().base, Some(first)); |
| 173 | |
| 174 | // Once the file is out of the way, the update goes through. |
| 175 | fs::remove_file(dir.join("d/junk")).unwrap(); |
| 176 | assert_eq!( |
| 177 | ws.update(&ada()).unwrap().updated, |
| 178 | Updated::Moved { head: second } |
| 179 | ); |
| 180 | assert_eq!(fs::read(dir.join("d")).unwrap(), b"now a file"); |
| 181 | } |
| 182 | |
| 183 | #[test] |
| 184 | fn an_interrupted_checkout_is_finished_by_the_next_command() { |
| 185 | let f = Fixture::new(); |
| 186 | let first = f.commit(&[], vec![("a", f.file("1")), ("gone", f.file("x"))]); |
| 187 | let second = f.commit( |
| 188 | &[first], |
| 189 | vec![ |
| 190 | ("a", f.file("2")), |
| 191 | ("gone", ChangeOp::Delete), |
| 192 | ("new/b", f.file("b")), |
| 193 | ], |
| 194 | ); |
| 195 | f.set_branch("main", second); |
| 196 | let dir = f.path("ws"); |
| 197 | let (ws, _) = Workspace::create(&f.repo, "ws", &dir, Some(first), "main").unwrap(); |
| 198 | |
| 199 | // As if a command had moved the base, written part of the checkout |
| 200 | // and died: `a` is written, the rest is not. |
| 201 | let state_file = f |
| 202 | .repo |
| 203 | .root() |
| 204 | .join(".braid") |
| 205 | .join("ws") |
| 206 | .join("ws") |
| 207 | .join("state"); |
| 208 | let text = fs::read_to_string(&state_file).unwrap(); |
| 209 | let root = |id| { |
| 210 | braid_engine::read_changeset(f.repo.store(), id) |
| 211 | .unwrap() |
| 212 | .root |
| 213 | }; |
| 214 | let text = text.replace( |
| 215 | &format!("base {first}"), |
| 216 | &format!("base {second}\ncheckout {} {}", root(first), root(second)), |
| 217 | ); |
| 218 | fs::write(&state_file, text).unwrap(); |
| 219 | fs::write(dir.join("a"), "2").unwrap(); |
| 220 | |
| 221 | let report = ws.status().unwrap(); |
| 222 | assert!(report.status.is_clean(), "{:?}", report.status); |
| 223 | assert_eq!(report.state.checkout, None); |
| 224 | assert_eq!(report.state.base, Some(second)); |
| 225 | assert!(!dir.join("gone").exists()); |
| 226 | assert_eq!(fs::read(dir.join("new/b")).unwrap(), b"b"); |
| 227 | } |
| 228 | |
| 229 | #[test] |
| 230 | fn a_stack_that_conflicts_half_way_continues_after_the_commit() { |
| 231 | let f = Fixture::new(); |
| 232 | let seed = f.commit(&[], vec![("x", f.file("1\n2\n3\n")), ("y", f.file("y\n"))]); |
| 233 | f.set_branch("main", seed); |
| 234 | let dir = f.path("ws"); |
| 235 | let (ws, _) = Workspace::create(&f.repo, "ws", &dir, Some(seed), "main").unwrap(); |
| 236 | // Two changesets of our own: the first is clean against main, the |
| 237 | // second conflicts with it. |
| 238 | fs::write(dir.join("y"), "y, ours\n").unwrap(); |
| 239 | let first = commit_all(&ws, "first").changeset.unwrap(); |
| 240 | fs::write(dir.join("x"), "1\nours\n3\n").unwrap(); |
| 241 | let second = commit_all(&ws, "second").changeset.unwrap(); |
| 242 | fs::write(dir.join("z"), "z\n").unwrap(); |
| 243 | let third = commit_all(&ws, "third").changeset.unwrap(); |
| 244 | // Main moves meanwhile. |
| 245 | let theirs = f.commit(&[seed], vec![("x", f.file("1\ntheirs\n3\n"))]); |
| 246 | f.set_branch("main", theirs); |
| 247 | |
| 248 | let report = ws.update(&ada()).unwrap(); |
| 249 | let Updated::Conflicts { |
| 250 | change, conflicts, .. |
| 251 | } = report.updated |
| 252 | else { |
| 253 | panic!("expected conflicts"); |
| 254 | }; |
| 255 | assert_eq!(change, second); |
| 256 | assert_eq!(conflicts[0].kind.code(), "CONTENT"); |
| 257 | let state = ws.state().unwrap(); |
| 258 | let rebase = state.rebase.unwrap(); |
| 259 | assert_eq!(rebase.pending, [third]); |
| 260 | // The first changeset went onto main's head, the others nowhere yet; |
| 261 | // the working copy got main's x with markers, and lost z for now. |
| 262 | assert_eq!(report.head, Some(theirs)); |
| 263 | assert_eq!(report.base_before, Some(third)); |
| 264 | assert_eq!(report.base, Some(rebase.onto)); |
| 265 | let placed: Vec<(ObjectId, Option<ObjectId>)> = |
| 266 | report.placed.iter().map(|p| (p.from, p.to)).collect(); |
| 267 | assert_eq!( |
| 268 | placed, |
| 269 | [(first, Some(rebase.onto)), (second, None), (third, None)] |
| 270 | ); |
| 271 | assert_eq!(report.updated_paths, [b"x".to_vec(), b"z".to_vec()]); |
| 272 | // The working copy has the first changeset rebased, and the markers; |
| 273 | // the third one waits. |
| 274 | assert_eq!(fs::read(dir.join("y")).unwrap(), b"y, ours\n"); |
| 275 | assert!(!dir.join("z").exists()); |
| 276 | let merged = fs::read_to_string(dir.join("x")).unwrap(); |
| 277 | assert!(merged.contains("<<<<<<< "), "{merged}"); |
| 278 | |
| 279 | // Neither landing nor updating while the rebase lasts. |
| 280 | assert!(matches!( |
| 281 | ws.land(None, "t", &ada()), |
| 282 | Err(Error::RebaseInProgress) |
| 283 | )); |
| 284 | assert!(matches!(ws.update(&ada()), Err(Error::RebaseInProgress))); |
| 285 | // Paths are refused: the resolution is recorded whole. |
| 286 | let partial = ws.commit(&CommitRequest { |
| 287 | message: None, |
| 288 | paths: vec![b"x".to_vec()], |
| 289 | author: None, |
| 290 | committer: ada(), |
| 291 | agent: "tester".to_owned(), |
| 292 | force: false, |
| 293 | }); |
| 294 | assert!( |
| 295 | matches!(partial, Err(Error::PathsDuringRebase)), |
| 296 | "{partial:?}" |
| 297 | ); |
| 298 | |
| 299 | fs::write(dir.join("x"), "1\nboth\n3\n").unwrap(); |
| 300 | let outcome = ws |
| 301 | .commit(&CommitRequest { |
| 302 | message: None, |
| 303 | paths: Vec::new(), |
| 304 | author: None, |
| 305 | committer: ada(), |
| 306 | agent: "tester".to_owned(), |
| 307 | force: false, |
| 308 | }) |
| 309 | .unwrap(); |
| 310 | let RebaseProgress::Finished { tip } = outcome.rebase else { |
| 311 | panic!("expected the rebase to finish, got {:?}", outcome.rebase); |
| 312 | }; |
| 313 | // The third changeset followed, and the workspace is clean on top. |
| 314 | assert_eq!(fs::read(dir.join("z")).unwrap(), b"z\n"); |
| 315 | assert_eq!(ws.state().unwrap().base, Some(tip)); |
| 316 | let report = ws.status().unwrap(); |
| 317 | assert!(report.status.is_clean()); |
| 318 | assert_eq!(report.unlanded.len(), 3); |
| 319 | |
| 320 | let landed = ws.land(None, "t", &ada()).unwrap(); |
| 321 | assert_eq!(landed.landed, Landed::FastForward(tip)); |
| 322 | // Main has, in order: theirs, then first, second and third, each |
| 323 | // naming the changeset it came from; the resolution keeps the |
| 324 | // message of the change it resolves. |
| 325 | let mut messages = Vec::new(); |
| 326 | let mut origins = Vec::new(); |
| 327 | let mut current = f.head("main"); |
| 328 | while let Some(id) = current { |
| 329 | let changeset = braid_engine::read_changeset(f.repo.store(), id).unwrap(); |
| 330 | messages.push(String::from_utf8(changeset.message.clone()).unwrap()); |
| 331 | origins.push( |
| 332 | changeset |
| 333 | .extras |
| 334 | .iter() |
| 335 | .find(|(key, _)| key.as_slice() == braid_engine::REBASED_FROM) |
| 336 | .map(|(_, value)| String::from_utf8(value.clone()).unwrap()), |
| 337 | ); |
| 338 | current = changeset.parents.first().copied(); |
| 339 | } |
| 340 | assert_eq!( |
| 341 | messages, |
| 342 | ["third", "second", "first", "test change\n", "test change\n"] |
| 343 | ); |
| 344 | let hex = |id: braid_format::ObjectId| Some(id.to_hex()); |
| 345 | assert_eq!(origins[..3], [hex(third), hex(second), hex(first)]); |
| 346 | } |
| 347 | |
| 348 | #[test] |
| 349 | fn files_a_rebased_change_tracked_stay_in_its_resolution() { |
| 350 | let f = Fixture::new(); |
| 351 | let seed = f.commit(&[], vec![("x", f.file("1\n2\n3\n"))]); |
| 352 | f.set_branch("main", seed); |
| 353 | let dir = f.path("ws"); |
| 354 | let (ws, _) = Workspace::create(&f.repo, "ws", &dir, Some(seed), "main").unwrap(); |
| 355 | // One changeset adds a file the secrets guard holds back, once tracked, |
| 356 | // and edits a line that main edits too. |
| 357 | fs::write(dir.join(".env.example"), "KEY=\n").unwrap(); |
| 358 | ws.track(&[b".env.example".to_vec()]).unwrap(); |
| 359 | fs::write(dir.join("x"), "1\nours\n3\n").unwrap(); |
| 360 | commit_all(&ws, "env and x"); |
| 361 | assert!(ws.state().unwrap().tracked.is_empty()); |
| 362 | let theirs = f.commit(&[seed], vec![("x", f.file("1\ntheirs\n3\n"))]); |
| 363 | f.set_branch("main", theirs); |
| 364 | |
| 365 | let report = ws.update(&ada()).unwrap(); |
| 366 | assert!(matches!(report.updated, Updated::Conflicts { .. })); |
| 367 | // The file is back, and does not wait for `braid track` again: only the |
| 368 | // markers stop the resolution. |
| 369 | assert_eq!(fs::read(dir.join(".env.example")).unwrap(), b"KEY=\n"); |
| 370 | let status = ws.status().unwrap(); |
| 371 | assert!(status.status.needs_track.is_empty()); |
| 372 | assert_eq!(status.blocking, [Blocker::Markers(b"x".to_vec())]); |
| 373 | fs::write(dir.join("x"), "1\nboth\n3\n").unwrap(); |
| 374 | let resolution = ws |
| 375 | .commit(&CommitRequest { |
| 376 | message: None, |
| 377 | paths: Vec::new(), |
| 378 | author: None, |
| 379 | committer: ada(), |
| 380 | agent: "tester".to_owned(), |
| 381 | force: false, |
| 382 | }) |
| 383 | .unwrap() |
| 384 | .changeset |
| 385 | .unwrap(); |
| 386 | let root = braid_engine::read_changeset(f.repo.store(), resolution) |
| 387 | .unwrap() |
| 388 | .root; |
| 389 | let kept = braid_engine::entry_at(f.repo.store(), root, b".env.example").unwrap(); |
| 390 | assert!(kept.is_some()); |
| 391 | assert!(ws.state().unwrap().tracked.is_empty()); |
| 392 | } |
| 393 | |
| 394 | #[test] |
| 395 | fn tracked_files_count_even_when_ignored() { |
| 396 | let f = Fixture::new(); |
| 397 | let first = f.commit( |
| 398 | &[], |
| 399 | vec![(".gitignore", f.file("*.log\n")), ("kept.log", f.file("1"))], |
| 400 | ); |
| 401 | let dir = f.path("ws"); |
| 402 | let (ws, _) = Workspace::create(&f.repo, "ws", &dir, Some(first), "main").unwrap(); |
| 403 | fs::write(dir.join("kept.log"), "2").unwrap(); |
| 404 | fs::write(dir.join("new.log"), "ignored").unwrap(); |
| 405 | let status = ws.status().unwrap().status; |
| 406 | let changes: Vec<(&[u8], ChangeKind)> = status |
| 407 | .changes |
| 408 | .iter() |
| 409 | .map(|c| (c.path.as_slice(), c.kind)) |
| 410 | .collect(); |
| 411 | assert_eq!(changes, [(&b"kept.log"[..], ChangeKind::Modified)]); |
| 412 | } |
| 413 | |
| 414 | #[test] |
| 415 | fn refusals() { |
| 416 | let f = Fixture::new(); |
| 417 | let dir = f.path("ws"); |
| 418 | for bad in ["", ".hidden", "a/b", "../up"] { |
| 419 | assert!(matches!( |
| 420 | Workspace::create(&f.repo, bad, &dir, None, "main"), |
| 421 | Err(Error::InvalidName(_)) |
| 422 | )); |
| 423 | } |
| 424 | let full = f.path("full"); |
| 425 | fs::create_dir(&full).unwrap(); |
| 426 | fs::write(full.join("there"), "x").unwrap(); |
| 427 | assert!(matches!( |
| 428 | Workspace::create(&f.repo, "ws", &full, None, "main"), |
| 429 | Err(Error::DirectoryNotEmpty(_)) |
| 430 | )); |
| 431 | // A refused creation leaves no workspace behind, so the name is free. |
| 432 | let (ws, written) = Workspace::create(&f.repo, "ws", &dir, None, "main").unwrap(); |
| 433 | assert_eq!(written, 0); |
| 434 | assert!(matches!( |
| 435 | Workspace::create(&f.repo, "ws", &f.path("other"), None, "main"), |
| 436 | Err(Error::WorkspaceExists(_)) |
| 437 | )); |
| 438 | assert!(matches!( |
| 439 | Workspace::open(&f.repo, "nope"), |
| 440 | Err(Error::NoSuchWorkspace(_)) |
| 441 | )); |
| 442 | assert!(matches!(ws.resolve(&[b"x".to_vec()]), Err(Error::NoRebase))); |
| 443 | assert!(matches!( |
| 444 | ws.commit(&CommitRequest { |
| 445 | message: Some(b"m".to_vec()), |
| 446 | paths: Vec::new(), |
| 447 | author: None, |
| 448 | committer: ada(), |
| 449 | agent: "tester".to_owned(), |
| 450 | force: false, |
| 451 | }), |
| 452 | Err(Error::NothingToCommit) |
| 453 | )); |
| 454 | fs::write(dir.join("f"), "x").unwrap(); |
| 455 | assert!(matches!( |
| 456 | ws.commit(&CommitRequest { |
| 457 | message: None, |
| 458 | paths: Vec::new(), |
| 459 | author: None, |
| 460 | committer: ada(), |
| 461 | agent: "tester".to_owned(), |
| 462 | force: false, |
| 463 | }), |
| 464 | Err(Error::NoMessage) |
| 465 | )); |
| 466 | // Landing or updating with uncommitted changes. |
| 467 | assert!(matches!( |
| 468 | ws.land(None, "t", &ada()), |
| 469 | Err(Error::Uncommitted { .. }) |
| 470 | )); |
| 471 | assert!(matches!(ws.update(&ada()), Err(Error::Uncommitted { .. }))); |
| 472 | // Nothing to land before the first commit; then a first landing makes |
| 473 | // the branch. |
| 474 | let made = commit_all(&ws, "first").changeset.unwrap(); |
| 475 | let landed = ws.land(None, "t", &ada()).unwrap(); |
| 476 | assert_eq!(landed.landed, Landed::FastForward(made)); |
| 477 | assert_eq!(f.head("main"), Some(made)); |
| 478 | assert_eq!(ws.land(None, "t", &ada()).unwrap().landed, Landed::Nothing); |
| 479 | } |
| 480 | |
| 481 | #[test] |
| 482 | fn removal_never_says_to_commit_what_the_guard_holds_back() { |
| 483 | let f = Fixture::new(); |
| 484 | let first = f.commit(&[], vec![("README.md", f.file("hello\n"))]); |
| 485 | f.set_branch("main", first); |
| 486 | let dir = f.path("ws"); |
| 487 | Workspace::create(&f.repo, "ws", &dir, Some(first), "main").unwrap(); |
| 488 | fs::write(dir.join(".env"), "TOKEN=secret\n").unwrap(); |
| 489 | |
| 490 | // A file the guard holds back is not a change to commit: it may be a |
| 491 | // secret, which removing the workspace would delete. |
| 492 | let refused = Workspace::remove(&f.repo, "ws", false).unwrap_err(); |
| 493 | assert!( |
| 494 | matches!(&refused, Error::HeldBack { count: 1, first } if first == b".env"), |
| 495 | "{refused:?}" |
| 496 | ); |
| 497 | let said = refused.to_string(); |
| 498 | assert!( |
| 499 | said.contains("secrets guard holds back, \".env\""), |
| 500 | "{said}" |
| 501 | ); |
| 502 | assert!(said.contains("move it out of the workspace"), "{said}"); |
| 503 | assert!(!said.contains("commit them"), "{said}"); |
| 504 | fs::write(dir.join("id_rsa"), "private\n").unwrap(); |
| 505 | let said = Workspace::remove(&f.repo, "ws", false) |
| 506 | .unwrap_err() |
| 507 | .to_string(); |
| 508 | assert!(said.contains("2 new files"), "{said}"); |
| 509 | assert!(!said.contains("commit them"), "{said}"); |
| 510 | |
| 511 | // Changes come first, and only they count as uncommitted. |
| 512 | fs::write(dir.join("notes.txt"), "notes\n").unwrap(); |
| 513 | let refused = Workspace::remove(&f.repo, "ws", false).unwrap_err(); |
| 514 | assert!( |
| 515 | matches!(&refused, Error::Uncommitted { count: 1, first } if first == b"notes.txt"), |
| 516 | "{refused:?}" |
| 517 | ); |
| 518 | assert!( |
| 519 | refused |
| 520 | .to_string() |
| 521 | .contains("uncommitted changes (1 path, \"notes.txt\")"), |
| 522 | "{refused}" |
| 523 | ); |
| 524 | assert!(dir.join(".env").exists()); |
| 525 | |
| 526 | // --force removes the workspace with them. |
| 527 | Workspace::remove(&f.repo, "ws", true).unwrap(); |
| 528 | assert!(!dir.exists()); |
| 529 | } |
| 530 | |
| 531 | #[cfg(unix)] |
| 532 | #[test] |
| 533 | fn a_commit_of_some_paths_reads_only_those() { |
| 534 | use std::os::unix::fs::PermissionsExt; |
| 535 | let f = Fixture::new(); |
| 536 | let first = f.commit( |
| 537 | &[], |
| 538 | vec![ |
| 539 | ("a/x", f.file("1")), |
| 540 | ("a/y", f.file("2")), |
| 541 | ("c/d/e", f.file("3")), |
| 542 | ("locked/z", f.file("4")), |
| 543 | ], |
| 544 | ); |
| 545 | f.set_branch("main", first); |
| 546 | let dir = f.path("ws"); |
| 547 | let (ws, _) = Workspace::create(&f.repo, "ws", &dir, Some(first), "main").unwrap(); |
| 548 | fs::write(dir.join("a/x"), "edited").unwrap(); |
| 549 | fs::write(dir.join("a/y"), "edited too").unwrap(); |
| 550 | fs::remove_dir_all(dir.join("c")).unwrap(); |
| 551 | fs::write(dir.join("locked/new"), "n").unwrap(); |
| 552 | // A directory that cannot be read: a scan of everything fails on it, |
| 553 | // unless the tests run with the rights to read it anyway. |
| 554 | let mode = |m| fs::Permissions::from_mode(m); |
| 555 | fs::set_permissions(dir.join("locked"), mode(0o000)).unwrap(); |
| 556 | if fs::read_dir(dir.join("locked")).is_err() { |
| 557 | assert!(matches!(ws.status(), Err(Error::Io { .. }))); |
| 558 | } |
| 559 | let outcome = ws.commit(&CommitRequest { |
| 560 | message: Some(b"some paths".to_vec()), |
| 561 | paths: vec![b"a/x".to_vec(), b"c/d".to_vec()], |
| 562 | author: None, |
| 563 | committer: ada(), |
| 564 | agent: "tester".to_owned(), |
| 565 | force: false, |
| 566 | }); |
| 567 | fs::set_permissions(dir.join("locked"), mode(0o755)).unwrap(); |
| 568 | let outcome = outcome.unwrap(); |
| 569 | assert_eq!(outcome.changes, 2); |
| 570 | let changeset = |
| 571 | braid_engine::read_changeset(f.repo.store(), outcome.changeset.unwrap()).unwrap(); |
| 572 | let changes = |
| 573 | braid_engine::read_changes(f.repo.store(), outcome.changeset.unwrap(), &changeset) |
| 574 | .unwrap() |
| 575 | .iter() |
| 576 | .map(|change| { |
| 577 | ( |
| 578 | String::from_utf8(change.path.clone()).unwrap(), |
| 579 | change.op == ChangeOp::Delete, |
| 580 | ) |
| 581 | }) |
| 582 | .collect::<Vec<_>>(); |
| 583 | assert_eq!( |
| 584 | changes, |
| 585 | [("a/x".to_owned(), false), ("c/d/e".to_owned(), true)] |
| 586 | ); |
| 587 | // What lay outside the paths is still to commit. |
| 588 | let status = ws.status().unwrap().status; |
| 589 | let left: Vec<(&[u8], ChangeKind)> = status |
| 590 | .changes |
| 591 | .iter() |
| 592 | .map(|c| (c.path.as_slice(), c.kind)) |
| 593 | .collect(); |
| 594 | assert_eq!( |
| 595 | left, |
| 596 | [ |
| 597 | (&b"a/y"[..], ChangeKind::Modified), |
| 598 | (b"locked/new", ChangeKind::Added) |
| 599 | ] |
| 600 | ); |
| 601 | } |
| 602 | |
| 603 | /// Waits until a file written now is dated after every change made so far |
| 604 | /// to the directories under `dir`: the stat cache's records of them are |
| 605 | /// then not racy, whatever the granularity of the file system's clock. |
| 606 | #[cfg(unix)] |
| 607 | fn settle(f: &Fixture, dir: &std::path::Path) { |
| 608 | use std::os::unix::fs::MetadataExt; |
| 609 | let mut newest = (0, 0); |
| 610 | let mut pending = vec![dir.to_path_buf()]; |
| 611 | while let Some(current) = pending.pop() { |
| 612 | let meta = fs::symlink_metadata(¤t).unwrap(); |
| 613 | newest = newest |
| 614 | .max((meta.mtime(), meta.mtime_nsec())) |
| 615 | .max((meta.ctime(), meta.ctime_nsec())); |
| 616 | for entry in fs::read_dir(¤t).unwrap() { |
| 617 | let entry = entry.unwrap(); |
| 618 | if entry.file_type().unwrap().is_dir() { |
| 619 | pending.push(entry.path()); |
| 620 | } |
| 621 | } |
| 622 | } |
| 623 | let probe = f.path("probe"); |
| 624 | loop { |
| 625 | fs::write(&probe, "now").unwrap(); |
| 626 | let meta = fs::metadata(&probe).unwrap(); |
| 627 | if (meta.mtime(), meta.mtime_nsec()) > newest { |
| 628 | break; |
| 629 | } |
| 630 | std::thread::sleep(std::time::Duration::from_millis(5)); |
| 631 | } |
| 632 | } |
| 633 | |
| 634 | #[cfg(unix)] |
| 635 | #[test] |
| 636 | fn a_commit_leaves_the_stat_cache_on_its_changeset() { |
| 637 | let f = Fixture::new(); |
| 638 | let first = f.commit(&[], vec![("a/x", f.file("1")), ("b/y", f.file("2"))]); |
| 639 | let dir = f.path("ws"); |
| 640 | let (ws, _) = Workspace::create(&f.repo, "ws", &dir, Some(first), "main").unwrap(); |
| 641 | fs::write(dir.join("a/x"), "edited").unwrap(); |
| 642 | fs::create_dir(dir.join("c")).unwrap(); |
| 643 | fs::write(dir.join("c/new"), "new").unwrap(); |
| 644 | let past = std::time::SystemTime::now() - std::time::Duration::from_secs(30); |
| 645 | for path in ["a/x", "c/new"] { |
| 646 | fs::File::options() |
| 647 | .write(true) |
| 648 | .open(dir.join(path)) |
| 649 | .unwrap() |
| 650 | .set_modified(past) |
| 651 | .unwrap(); |
| 652 | } |
| 653 | settle(&f, &dir); |
| 654 | commit_all(&ws, "edit and add"); |
| 655 | |
| 656 | // The status after it finds the working copy as the commit left it, |
| 657 | // and has nothing to write. |
| 658 | let cache = f.repo.root().join(".braid/ws/ws/stat"); |
| 659 | let before = fs::read(&cache).unwrap(); |
| 660 | assert!(ws.status().unwrap().status.is_clean()); |
| 661 | assert_eq!(fs::read(&cache).unwrap(), before); |
| 662 | } |