| 1 | // SPDX-License-Identifier: Apache-2.0 |
| 2 | // Copyright (c) 2026 UtopiaIA |
| 3 | |
| 4 | //! Applying a change list to a tree by path copying: only the directories on |
| 5 | //! changed paths are read and rebuilt; every other subtree is shared with the |
| 6 | //! base tree. |
| 7 | |
| 8 | use std::collections::{BTreeMap, btree_map}; |
| 9 | use std::rc::Rc; |
| 10 | |
| 11 | use braid_format::name::forbidden_as_symlink; |
| 12 | use braid_format::{ |
| 13 | Change, ChangeOp, Entry, EntryKind, Kind, ObjectId, Objects, build_directory, validate_path, |
| 14 | }; |
| 15 | |
| 16 | use crate::access::{EMPTY_TREE, Trees, empty_tree_node, read_object}; |
| 17 | use crate::error::{ApplyProblem, Error, store_error}; |
| 18 | use crate::path::{check_depth, join, last_name}; |
| 19 | |
| 20 | /// Applies `changes` to the tree `base_root`, stores the directories it |
| 21 | /// rebuilds, and returns the new root. |
| 22 | /// |
| 23 | /// The changes may come in any order. Directories are created as needed, and |
| 24 | /// a directory left without entries is removed; the root becomes the empty |
| 25 | /// tree instead. A structural problem is an error, never a panic: a change |
| 26 | /// below a file, a file set where a directory with entries remains, deleting |
| 27 | /// a directory or a missing path, setting a path to the entry it already has |
| 28 | /// (a no-op is not canonical), or two changes to one path. |
| 29 | pub fn apply<O: Objects>( |
| 30 | objects: &O, |
| 31 | base_root: ObjectId, |
| 32 | changes: &[Change], |
| 33 | ) -> Result<ObjectId, Error> { |
| 34 | let sorted = prepare(changes)?; |
| 35 | let mut trees = Trees::new(objects); |
| 36 | let mut problems = Vec::new(); |
| 37 | let applied = apply_sorted(&mut trees, base_root, &sorted, &mut problems)?; |
| 38 | if let Some(problem) = first_problem(problems) { |
| 39 | return Err(problem.into_error()); |
| 40 | } |
| 41 | write_nodes(objects, &applied.nodes)?; |
| 42 | Ok(applied.root) |
| 43 | } |
| 44 | |
| 45 | /// The result of applying a change list, before anything is stored. |
| 46 | #[derive(Debug)] |
| 47 | pub(crate) struct Applied { |
| 48 | /// The new root tree. |
| 49 | pub(crate) root: ObjectId, |
| 50 | /// Every node of every directory rebuilt, children before parents. |
| 51 | pub(crate) nodes: Vec<(ObjectId, Vec<u8>)>, |
| 52 | } |
| 53 | |
| 54 | /// A structural problem found while applying, at `path`. |
| 55 | #[derive(Clone, Debug, PartialEq, Eq)] |
| 56 | pub(crate) struct Problem { |
| 57 | pub(crate) path: Vec<u8>, |
| 58 | pub(crate) problem: ApplyProblem, |
| 59 | } |
| 60 | |
| 61 | impl Problem { |
| 62 | pub(crate) fn into_error(self) -> Error { |
| 63 | Error::Apply { |
| 64 | path: self.path, |
| 65 | problem: self.problem, |
| 66 | } |
| 67 | } |
| 68 | } |
| 69 | |
| 70 | /// The problem with the smallest path, so that errors do not depend on the |
| 71 | /// order of the walk. |
| 72 | pub(crate) fn first_problem(problems: Vec<Problem>) -> Option<Problem> { |
| 73 | problems.into_iter().min_by(|a, b| a.path.cmp(&b.path)) |
| 74 | } |
| 75 | |
| 76 | /// Checks every change on its own, and returns them sorted by path. |
| 77 | pub(crate) fn prepare(changes: &[Change]) -> Result<Vec<&Change>, Error> { |
| 78 | for change in changes { |
| 79 | let invalid = |problem| Error::Apply { |
| 80 | path: change.path.clone(), |
| 81 | problem, |
| 82 | }; |
| 83 | validate_path(&change.path).map_err(|error| invalid(ApplyProblem::InvalidPath(error)))?; |
| 84 | if matches!(change.op, ChangeOp::Symlink { .. }) |
| 85 | && forbidden_as_symlink(last_name(&change.path)) |
| 86 | { |
| 87 | return Err(invalid(ApplyProblem::SymlinkName)); |
| 88 | } |
| 89 | } |
| 90 | let mut sorted: Vec<&Change> = changes.iter().collect(); |
| 91 | sorted.sort_by(|a, b| a.path.cmp(&b.path)); |
| 92 | if let Some(pair) = sorted.windows(2).find(|pair| pair[0].path == pair[1].path) { |
| 93 | return Err(Error::Apply { |
| 94 | path: pair[0].path.clone(), |
| 95 | problem: ApplyProblem::Duplicate, |
| 96 | }); |
| 97 | } |
| 98 | Ok(sorted) |
| 99 | } |
| 100 | |
| 101 | /// Applies valid changes with distinct paths, sorted by path, without storing |
| 102 | /// anything. Structural problems are collected in `problems` and the walk |
| 103 | /// goes on, so that a caller can report all of them; where there is one, the |
| 104 | /// result keeps the base entry. |
| 105 | /// |
| 106 | /// Paths deeper than [`MAX_PATH_DEPTH`](crate::MAX_PATH_DEPTH) are refused before the walk starts, |
| 107 | /// and the walk keeps its own stack of directories rather than recursing, so |
| 108 | /// it does not depend on the size of the thread's stack. |
| 109 | pub(crate) fn apply_sorted<O: Objects>( |
| 110 | trees: &mut Trees<'_, O>, |
| 111 | base_root: ObjectId, |
| 112 | changes: &[&Change], |
| 113 | problems: &mut Vec<Problem>, |
| 114 | ) -> Result<Applied, Error> { |
| 115 | if changes.is_empty() { |
| 116 | return Ok(Applied { |
| 117 | root: base_root, |
| 118 | nodes: Vec::new(), |
| 119 | }); |
| 120 | } |
| 121 | for change in changes { |
| 122 | check_depth(&change.path)?; |
| 123 | } |
| 124 | let items = changes |
| 125 | .iter() |
| 126 | .map(|change| Item { |
| 127 | path: &change.path, |
| 128 | rest: &change.path, |
| 129 | op: &change.op, |
| 130 | }) |
| 131 | .collect(); |
| 132 | let mut ctx = Ctx { |
| 133 | trees, |
| 134 | nodes: Vec::new(), |
| 135 | problems, |
| 136 | }; |
| 137 | let root = match rebuild(&mut ctx, base_root, items)? { |
| 138 | Some(root) => root, |
| 139 | None => { |
| 140 | ctx.nodes.push((EMPTY_TREE, empty_tree_node())); |
| 141 | EMPTY_TREE |
| 142 | } |
| 143 | }; |
| 144 | Ok(Applied { |
| 145 | root, |
| 146 | nodes: ctx.nodes, |
| 147 | }) |
| 148 | } |
| 149 | |
| 150 | /// Stores rebuilt nodes. |
| 151 | pub(crate) fn write_nodes<O: Objects>( |
| 152 | objects: &O, |
| 153 | nodes: &[(ObjectId, Vec<u8>)], |
| 154 | ) -> Result<(), Error> { |
| 155 | for (_, bytes) in nodes { |
| 156 | objects.put(Kind::Tree, bytes).map_err(store_error)?; |
| 157 | } |
| 158 | Ok(()) |
| 159 | } |
| 160 | |
| 161 | /// Checks that rebuilt nodes are stored, byte for byte. |
| 162 | pub(crate) fn check_nodes<O: Objects>( |
| 163 | objects: &O, |
| 164 | nodes: &[(ObjectId, Vec<u8>)], |
| 165 | ) -> Result<(), Error> { |
| 166 | for (id, bytes) in nodes { |
| 167 | if read_object(objects, *id, Kind::Tree)? != *bytes { |
| 168 | return Err(Error::Corrupt { id: *id }); |
| 169 | } |
| 170 | } |
| 171 | Ok(()) |
| 172 | } |
| 173 | |
| 174 | /// One change, seen from the directory being rebuilt. |
| 175 | #[derive(Clone, Copy)] |
| 176 | struct Item<'a> { |
| 177 | /// The full path. |
| 178 | path: &'a [u8], |
| 179 | /// The part of the path below the directory. |
| 180 | rest: &'a [u8], |
| 181 | op: &'a ChangeOp, |
| 182 | } |
| 183 | |
| 184 | impl<'a> Item<'a> { |
| 185 | /// The path of the directory the change is seen from; empty for the root. |
| 186 | fn dir(&self) -> &'a [u8] { |
| 187 | let cut = self.path.len() - self.rest.len(); |
| 188 | &self.path[..cut.saturating_sub(1)] |
| 189 | } |
| 190 | } |
| 191 | |
| 192 | /// The changes under one name of a directory. |
| 193 | #[derive(Default)] |
| 194 | struct Group<'a> { |
| 195 | /// The change to the name itself. |
| 196 | direct: Option<&'a ChangeOp>, |
| 197 | /// Changes below the name, which need it to be a directory. |
| 198 | nested: Vec<Item<'a>>, |
| 199 | } |
| 200 | |
| 201 | struct Ctx<'t, 'o, O> { |
| 202 | trees: &'t mut Trees<'o, O>, |
| 203 | nodes: Vec<(ObjectId, Vec<u8>)>, |
| 204 | problems: &'t mut Vec<Problem>, |
| 205 | } |
| 206 | |
| 207 | impl<O> Ctx<'_, '_, O> { |
| 208 | /// Records a problem at `dir/name` and returns `keep`, the entry to leave |
| 209 | /// in place. |
| 210 | fn problem( |
| 211 | &mut self, |
| 212 | dir: &[u8], |
| 213 | name: &[u8], |
| 214 | problem: ApplyProblem, |
| 215 | keep: Option<EntryKind>, |
| 216 | ) -> Option<EntryKind> { |
| 217 | self.problems.push(Problem { |
| 218 | path: join(dir, name), |
| 219 | problem, |
| 220 | }); |
| 221 | keep |
| 222 | } |
| 223 | } |
| 224 | |
| 225 | /// Rebuilds the root tree `base_root` with `items`, children before |
| 226 | /// parents, and returns the new root, or `None` if it has no entries left. |
| 227 | /// |
| 228 | /// Each directory on a changed path is a frame on an explicit stack: a frame |
| 229 | /// resolves its names in order until one has to become a directory rebuilt |
| 230 | /// first, opens a frame for it, and settles that name once the frame above |
| 231 | /// it closes. |
| 232 | fn rebuild<O: Objects>( |
| 233 | ctx: &mut Ctx<'_, '_, O>, |
| 234 | base_root: ObjectId, |
| 235 | items: Vec<Item<'_>>, |
| 236 | ) -> Result<Option<ObjectId>, Error> { |
| 237 | let mut stack = vec![Frame::open(ctx.trees, Some(base_root), items)?]; |
| 238 | // What the frame closed last became, for the frame below it. |
| 239 | let mut closed = None; |
| 240 | while let Some(frame) = stack.last_mut() { |
| 241 | if let Some(directory) = closed.take() { |
| 242 | frame.settle(ctx, directory); |
| 243 | } |
| 244 | match frame.advance(ctx) { |
| 245 | Some((below, nested)) => { |
| 246 | let child = Frame::open(ctx.trees, below, nested)?; |
| 247 | stack.push(child); |
| 248 | } |
| 249 | None => { |
| 250 | if let Some(frame) = stack.pop() { |
| 251 | closed = Some(frame.close(ctx)?); |
| 252 | } |
| 253 | } |
| 254 | } |
| 255 | } |
| 256 | Ok(closed.flatten()) |
| 257 | } |
| 258 | |
| 259 | /// A directory being rebuilt. |
| 260 | struct Frame<'a> { |
| 261 | /// Its path; empty for the root. |
| 262 | dir: &'a [u8], |
| 263 | /// Its entries before the change, in name order. |
| 264 | existing: Rc<[Entry]>, |
| 265 | /// How many of `existing` are copied or replaced already. |
| 266 | next: usize, |
| 267 | /// The changes under each name not resolved yet, in name order. |
| 268 | groups: btree_map::IntoIter<&'a [u8], Group<'a>>, |
| 269 | /// Its entries after the change, so far. |
| 270 | entries: Vec<Entry>, |
| 271 | /// The name whose directory the frame above is rebuilding. |
| 272 | waiting: Option<Waiting<'a>>, |
| 273 | } |
| 274 | |
| 275 | /// A name that must be, or become, a directory, waiting for it to be rebuilt. |
| 276 | struct Waiting<'a> { |
| 277 | name: &'a [u8], |
| 278 | current: Option<EntryKind>, |
| 279 | direct: Option<&'a ChangeOp>, |
| 280 | } |
| 281 | |
| 282 | /// What to do with one name of a directory. |
| 283 | enum Step<'a> { |
| 284 | /// This is its new entry; `None` leaves it out. |
| 285 | Done(Option<EntryKind>), |
| 286 | /// Its directory must be rebuilt first, from the tree `below` (if there |
| 287 | /// is one) with the changes `nested`. |
| 288 | Descend { |
| 289 | below: Option<ObjectId>, |
| 290 | nested: Vec<Item<'a>>, |
| 291 | waiting: Waiting<'a>, |
| 292 | }, |
| 293 | } |
| 294 | |
| 295 | impl<'a> Frame<'a> { |
| 296 | /// Opens the directory whose tree is `base` (`None` if it does not |
| 297 | /// exist), to rebuild it with `items`, of which there is at least one. |
| 298 | fn open<O: Objects>( |
| 299 | trees: &mut Trees<'_, O>, |
| 300 | base: Option<ObjectId>, |
| 301 | items: Vec<Item<'a>>, |
| 302 | ) -> Result<Self, Error> { |
| 303 | let dir = items.first().map_or(&b""[..], Item::dir); |
| 304 | let mut groups: BTreeMap<&'a [u8], Group<'a>> = BTreeMap::new(); |
| 305 | for item in items { |
| 306 | match item.rest.iter().position(|byte| *byte == b'/') { |
| 307 | None => groups.entry(item.rest).or_default().direct = Some(item.op), |
| 308 | Some(slash) => groups |
| 309 | .entry(&item.rest[..slash]) |
| 310 | .or_default() |
| 311 | .nested |
| 312 | .push(Item { |
| 313 | rest: &item.rest[slash + 1..], |
| 314 | ..item |
| 315 | }), |
| 316 | } |
| 317 | } |
| 318 | let existing = trees.read_or_empty(base)?; |
| 319 | Ok(Frame { |
| 320 | dir, |
| 321 | entries: Vec::with_capacity(existing.len() + groups.len()), |
| 322 | existing, |
| 323 | next: 0, |
| 324 | groups: groups.into_iter(), |
| 325 | waiting: None, |
| 326 | }) |
| 327 | } |
| 328 | |
| 329 | /// Resolves names in order until one must be a directory rebuilt first, |
| 330 | /// and returns what to rebuild it from. |
| 331 | fn advance<O>( |
| 332 | &mut self, |
| 333 | ctx: &mut Ctx<'_, '_, O>, |
| 334 | ) -> Option<(Option<ObjectId>, Vec<Item<'a>>)> { |
| 335 | while let Some((name, group)) = self.groups.next() { |
| 336 | let current = self.take(name); |
| 337 | match plan(ctx, self.dir, name, current, group) { |
| 338 | Step::Done(kind) => self.push(name, kind), |
| 339 | Step::Descend { |
| 340 | below, |
| 341 | nested, |
| 342 | waiting, |
| 343 | } => { |
| 344 | self.waiting = Some(waiting); |
| 345 | return Some((below, nested)); |
| 346 | } |
| 347 | } |
| 348 | } |
| 349 | None |
| 350 | } |
| 351 | |
| 352 | /// The frame above rebuilt the directory this one waits for, as |
| 353 | /// `directory` (`None` if it has no entries left). |
| 354 | fn settle<O>(&mut self, ctx: &mut Ctx<'_, '_, O>, directory: Option<ObjectId>) { |
| 355 | if let Some(Waiting { |
| 356 | name, |
| 357 | current, |
| 358 | direct, |
| 359 | }) = self.waiting.take() |
| 360 | { |
| 361 | let kind = settle(ctx, self.dir, name, current, direct, directory); |
| 362 | self.push(name, kind); |
| 363 | } |
| 364 | } |
| 365 | |
| 366 | /// Copies the entries named before `name`, and takes the one named |
| 367 | /// `name`, if there is one. |
| 368 | fn take(&mut self, name: &[u8]) -> Option<EntryKind> { |
| 369 | while let Some(entry) = self |
| 370 | .existing |
| 371 | .get(self.next) |
| 372 | .filter(|entry| entry.name.as_slice() < name) |
| 373 | { |
| 374 | self.entries.push(entry.clone()); |
| 375 | self.next += 1; |
| 376 | } |
| 377 | let entry = self |
| 378 | .existing |
| 379 | .get(self.next) |
| 380 | .filter(|entry| entry.name == name)?; |
| 381 | self.next += 1; |
| 382 | Some(entry.kind.clone()) |
| 383 | } |
| 384 | |
| 385 | fn push(&mut self, name: &[u8], kind: Option<EntryKind>) { |
| 386 | if let Some(kind) = kind { |
| 387 | self.entries.push(Entry { |
| 388 | name: name.to_vec(), |
| 389 | kind, |
| 390 | }); |
| 391 | } |
| 392 | } |
| 393 | |
| 394 | /// Finishes the directory, and returns its new tree, or `None` if it has |
| 395 | /// no entries left. |
| 396 | fn close<O>(mut self, ctx: &mut Ctx<'_, '_, O>) -> Result<Option<ObjectId>, Error> { |
| 397 | self.entries |
| 398 | .extend(self.existing[self.next..].iter().cloned()); |
| 399 | if self.entries.is_empty() { |
| 400 | return Ok(None); |
| 401 | } |
| 402 | let directory = build_directory(self.entries).map_err(Error::Entries)?; |
| 403 | let id = directory.root(); |
| 404 | ctx.nodes.extend(directory.nodes); |
| 405 | Ok(Some(id)) |
| 406 | } |
| 407 | } |
| 408 | |
| 409 | /// Decides what happens to the name `name` of the directory `dir`, given its |
| 410 | /// `current` entry and the changes to it and below it. |
| 411 | fn plan<'a, O>( |
| 412 | ctx: &mut Ctx<'_, '_, O>, |
| 413 | dir: &[u8], |
| 414 | name: &'a [u8], |
| 415 | current: Option<EntryKind>, |
| 416 | group: Group<'a>, |
| 417 | ) -> Step<'a> { |
| 418 | let Group { direct, nested } = group; |
| 419 | |
| 420 | if nested.is_empty() { |
| 421 | // A change to this name only. A group always holds a change. |
| 422 | let Some(op) = direct else { |
| 423 | return Step::Done(current); |
| 424 | }; |
| 425 | let new = op.to_entry(); |
| 426 | let problem = match (&new, ¤t) { |
| 427 | (None, None) => Some(ApplyProblem::DeleteMissing), |
| 428 | (None, Some(EntryKind::Tree { .. })) => Some(ApplyProblem::IsADirectory), |
| 429 | (Some(_), Some(EntryKind::Tree { tree })) if *tree != EMPTY_TREE => { |
| 430 | Some(ApplyProblem::DirectoryNotEmpty) |
| 431 | } |
| 432 | (Some(new), Some(old)) if new == old => Some(ApplyProblem::NoOp), |
| 433 | _ => None, |
| 434 | }; |
| 435 | return Step::Done(match problem { |
| 436 | Some(problem) => ctx.problem(dir, name, problem, current), |
| 437 | None => new, |
| 438 | }); |
| 439 | } |
| 440 | |
| 441 | // Changes below this name: it must be, or become, a directory. A file in |
| 442 | // the way must be deleted by the same change list. |
| 443 | let below = match ¤t { |
| 444 | Some(EntryKind::Tree { tree }) => Some(*tree), |
| 445 | _ => None, |
| 446 | }; |
| 447 | if current.is_some() && below.is_none() && !matches!(direct, Some(ChangeOp::Delete)) { |
| 448 | return Step::Done(ctx.problem(dir, name, ApplyProblem::NotADirectory, current)); |
| 449 | } |
| 450 | Step::Descend { |
| 451 | below, |
| 452 | nested, |
| 453 | waiting: Waiting { |
| 454 | name, |
| 455 | current, |
| 456 | direct, |
| 457 | }, |
| 458 | } |
| 459 | } |
| 460 | |
| 461 | /// The new entry for the name `name` of the directory `dir`, now that the |
| 462 | /// directory below it is rebuilt as `directory` (`None` if it has no entries |
| 463 | /// left). |
| 464 | fn settle<O>( |
| 465 | ctx: &mut Ctx<'_, '_, O>, |
| 466 | dir: &[u8], |
| 467 | name: &[u8], |
| 468 | current: Option<EntryKind>, |
| 469 | direct: Option<&ChangeOp>, |
| 470 | directory: Option<ObjectId>, |
| 471 | ) -> Option<EntryKind> { |
| 472 | let tree = directory.map(|tree| EntryKind::Tree { tree }); |
| 473 | let deletes = matches!(direct, Some(ChangeOp::Delete)); |
| 474 | let problem = match (¤t, &tree) { |
| 475 | (None, _) if deletes => Some(ApplyProblem::DeleteMissing), |
| 476 | (Some(EntryKind::Tree { .. }), _) if deletes => Some(ApplyProblem::IsADirectory), |
| 477 | // A directory replaced by a file: nothing may be left below it. |
| 478 | (_, Some(_)) if direct.is_some() && !deletes => Some(ApplyProblem::DirectoryNotEmpty), |
| 479 | _ => None, |
| 480 | }; |
| 481 | if let Some(problem) = problem { |
| 482 | return ctx.problem(dir, name, problem, current); |
| 483 | } |
| 484 | match direct { |
| 485 | // The file that replaces the directory. |
| 486 | Some(op) if !deletes => op.to_entry(), |
| 487 | // The rebuilt directory, possibly replacing a deleted file, or |
| 488 | // nothing if it has no entries left. |
| 489 | _ => tree, |
| 490 | } |
| 491 | } |
| 492 | |
| 493 | #[cfg(test)] |
| 494 | mod tests { |
| 495 | use super::*; |
| 496 | use crate::access::{entry_at, read_tree}; |
| 497 | use crate::diff::diff; |
| 498 | use crate::path::MAX_PATH_DEPTH; |
| 499 | use crate::testing::{Repo, deep_path, delete, gitlink, text_map}; |
| 500 | |
| 501 | fn problem(result: Result<ObjectId, Error>) -> (String, ApplyProblem) { |
| 502 | match result { |
| 503 | Err(Error::Apply { path, problem }) => (String::from_utf8(path).unwrap(), problem), |
| 504 | other => panic!("expected an apply error, got {other:?}"), |
| 505 | } |
| 506 | } |
| 507 | |
| 508 | #[test] |
| 509 | fn creates_nested_directories_and_shares_untouched_subtrees() { |
| 510 | let repo = Repo::new(); |
| 511 | let base = repo.tree(&[("a/b/c.txt", "1"), ("a/d.txt", "2"), ("z/keep.txt", "3")]); |
| 512 | let new = apply( |
| 513 | &repo.objects, |
| 514 | base, |
| 515 | &[repo.set("a/b/new/deep.txt", "4"), repo.set("a/d.txt", "5")], |
| 516 | ) |
| 517 | .unwrap(); |
| 518 | assert_eq!( |
| 519 | repo.files(new), |
| 520 | text_map(&[ |
| 521 | ("a/b/c.txt", "1"), |
| 522 | ("a/b/new/deep.txt", "4"), |
| 523 | ("a/d.txt", "5"), |
| 524 | ("z/keep.txt", "3"), |
| 525 | ]) |
| 526 | ); |
| 527 | let subtree = |root, name: &str| { |
| 528 | read_tree(&repo.objects, root) |
| 529 | .unwrap() |
| 530 | .into_iter() |
| 531 | .find(|entry| entry.name == name.as_bytes()) |
| 532 | .unwrap() |
| 533 | .kind |
| 534 | }; |
| 535 | assert_eq!(subtree(base, "z"), subtree(new, "z")); |
| 536 | assert_ne!(subtree(base, "a"), subtree(new, "a")); |
| 537 | } |
| 538 | |
| 539 | #[test] |
| 540 | fn order_of_changes_does_not_matter() { |
| 541 | let repo = Repo::new(); |
| 542 | let base = repo.tree(&[("a", "1"), ("d/x", "2")]); |
| 543 | let changes = vec![ |
| 544 | repo.set("d/y", "3"), |
| 545 | delete("a"), |
| 546 | repo.set("a-b", "4"), |
| 547 | repo.set("a0", "5"), |
| 548 | ]; |
| 549 | let forward = apply(&repo.objects, base, &changes).unwrap(); |
| 550 | let mut reversed = changes.clone(); |
| 551 | reversed.reverse(); |
| 552 | assert_eq!(apply(&repo.objects, base, &reversed).unwrap(), forward); |
| 553 | } |
| 554 | |
| 555 | #[test] |
| 556 | fn empty_directories_are_removed() { |
| 557 | let repo = Repo::new(); |
| 558 | let base = repo.tree(&[("a/b/c/d.txt", "1"), ("a/keep.txt", "2")]); |
| 559 | let new = apply(&repo.objects, base, &[delete("a/b/c/d.txt")]).unwrap(); |
| 560 | assert_eq!(repo.files(new), text_map(&[("a/keep.txt", "2")])); |
| 561 | assert_eq!(new, repo.tree(&[("a/keep.txt", "2")])); |
| 562 | // Deleting everything leaves the empty tree, stored. |
| 563 | let gone = apply(&repo.objects, new, &[delete("a/keep.txt")]).unwrap(); |
| 564 | assert_eq!(gone, EMPTY_TREE); |
| 565 | assert!(repo.objects.contains(&EMPTY_TREE).unwrap()); |
| 566 | } |
| 567 | |
| 568 | #[test] |
| 569 | fn file_and_directory_replace_each_other() { |
| 570 | let repo = Repo::new(); |
| 571 | let base = repo.tree(&[("p/x", "1"), ("p/y", "2"), ("q", "3")]); |
| 572 | // A directory replaced by a file: every file below it is deleted. |
| 573 | let new = apply( |
| 574 | &repo.objects, |
| 575 | base, |
| 576 | &[ |
| 577 | delete("p/x"), |
| 578 | delete("p/y"), |
| 579 | repo.set("p", "4"), |
| 580 | delete("q"), |
| 581 | repo.set("q/z", "5"), |
| 582 | ], |
| 583 | ) |
| 584 | .unwrap(); |
| 585 | assert_eq!(repo.files(new), text_map(&[("p", "4"), ("q/z", "5")])); |
| 586 | |
| 587 | // Not deleting everything below is an error. |
| 588 | let partial = apply(&repo.objects, base, &[delete("p/x"), repo.set("p", "4")]); |
| 589 | assert_eq!( |
| 590 | problem(partial), |
| 591 | ("p".to_owned(), ApplyProblem::DirectoryNotEmpty) |
| 592 | ); |
| 593 | // Neither is setting a file where a directory is. |
| 594 | assert_eq!( |
| 595 | problem(apply(&repo.objects, base, &[repo.set("p", "4")])), |
| 596 | ("p".to_owned(), ApplyProblem::DirectoryNotEmpty) |
| 597 | ); |
| 598 | // A change below a file that stays. |
| 599 | assert_eq!( |
| 600 | problem(apply(&repo.objects, base, &[repo.set("q/z", "5")])), |
| 601 | ("q".to_owned(), ApplyProblem::NotADirectory) |
| 602 | ); |
| 603 | assert_eq!( |
| 604 | problem(apply( |
| 605 | &repo.objects, |
| 606 | base, |
| 607 | &[repo.set("q", "6"), repo.set("q/z", "5")] |
| 608 | )), |
| 609 | ("q".to_owned(), ApplyProblem::NotADirectory) |
| 610 | ); |
| 611 | // A file and files below it, both new. |
| 612 | assert_eq!( |
| 613 | problem(apply( |
| 614 | &repo.objects, |
| 615 | base, |
| 616 | &[repo.set("n", "6"), repo.set("n/z", "5")] |
| 617 | )), |
| 618 | ("n".to_owned(), ApplyProblem::DirectoryNotEmpty) |
| 619 | ); |
| 620 | // Gitlinks are not directories either. |
| 621 | let with_link = apply(&repo.objects, base, &[gitlink("g", 7)]).unwrap(); |
| 622 | assert_eq!( |
| 623 | problem(apply(&repo.objects, with_link, &[repo.set("g/file", "1")])), |
| 624 | ("g".to_owned(), ApplyProblem::NotADirectory) |
| 625 | ); |
| 626 | } |
| 627 | |
| 628 | #[test] |
| 629 | fn an_empty_subdirectory_can_be_replaced_by_a_file() { |
| 630 | let repo = Repo::new(); |
| 631 | let root = crate::access::write_tree( |
| 632 | &repo.objects, |
| 633 | vec![Entry { |
| 634 | name: b"e".to_vec(), |
| 635 | kind: EntryKind::Tree { tree: EMPTY_TREE }, |
| 636 | }], |
| 637 | ) |
| 638 | .unwrap(); |
| 639 | repo.objects.put(Kind::Tree, &empty_tree_node()).unwrap(); |
| 640 | let new = apply(&repo.objects, root, &[repo.set("e", "1")]).unwrap(); |
| 641 | assert_eq!(repo.files(new), text_map(&[("e", "1")])); |
| 642 | } |
| 643 | |
| 644 | #[test] |
| 645 | fn rejects_invalid_change_lists() { |
| 646 | let repo = Repo::new(); |
| 647 | let base = repo.tree(&[("a/b", "1"), ("c", "2")]); |
| 648 | let cases: Vec<(Vec<Change>, &str, ApplyProblem)> = vec![ |
| 649 | ( |
| 650 | vec![delete("missing")], |
| 651 | "missing", |
| 652 | ApplyProblem::DeleteMissing, |
| 653 | ), |
| 654 | (vec![delete("x/y")], "x/y", ApplyProblem::DeleteMissing), |
| 655 | (vec![delete("a")], "a", ApplyProblem::IsADirectory), |
| 656 | ( |
| 657 | vec![delete("a"), delete("a/b")], |
| 658 | "a", |
| 659 | ApplyProblem::IsADirectory, |
| 660 | ), |
| 661 | (vec![repo.set("c", "2")], "c", ApplyProblem::NoOp), |
| 662 | (vec![repo.set("a/b", "1")], "a/b", ApplyProblem::NoOp), |
| 663 | ( |
| 664 | vec![repo.set("c", "3"), repo.set("c", "4")], |
| 665 | "c", |
| 666 | ApplyProblem::Duplicate, |
| 667 | ), |
| 668 | ( |
| 669 | vec![repo.symlink("d/.gitmodules", "x")], |
| 670 | "d/.gitmodules", |
| 671 | ApplyProblem::SymlinkName, |
| 672 | ), |
| 673 | ]; |
| 674 | for (changes, path, expected) in cases { |
| 675 | assert_eq!( |
| 676 | problem(apply(&repo.objects, base, &changes)), |
| 677 | (path.to_owned(), expected), |
| 678 | "{changes:?}" |
| 679 | ); |
| 680 | } |
| 681 | for bad in ["", "/a", "a/", "a//b", "a/../b", ".git/config"] { |
| 682 | let (path, problem) = problem(apply(&repo.objects, base, &[repo.set(bad, "1")])); |
| 683 | assert_eq!(path, bad); |
| 684 | assert!(matches!(problem, ApplyProblem::InvalidPath(_)), "{bad}"); |
| 685 | } |
| 686 | // Nothing was written for the failed attempts beyond blobs: the base |
| 687 | // is unchanged and still readable. |
| 688 | assert_eq!(repo.files(base), text_map(&[("a/b", "1"), ("c", "2")])); |
| 689 | } |
| 690 | |
| 691 | #[test] |
| 692 | fn kinds_can_change() { |
| 693 | let repo = Repo::new(); |
| 694 | let base = repo.tree(&[("run", "#!/bin/sh\n")]); |
| 695 | let exec = apply(&repo.objects, base, &[repo.exec("run", "#!/bin/sh\n")]).unwrap(); |
| 696 | assert_eq!(repo.files(exec), text_map(&[("run", "exec:#!/bin/sh\n")])); |
| 697 | let link = apply(&repo.objects, exec, &[repo.symlink("run", "other")]).unwrap(); |
| 698 | assert_eq!(repo.files(link), text_map(&[("run", "link:other")])); |
| 699 | let sub = apply(&repo.objects, link, &[gitlink("run", 9)]).unwrap(); |
| 700 | assert_eq!(repo.files(sub), text_map(&[("run", "gitlink:9")])); |
| 701 | } |
| 702 | |
| 703 | #[test] |
| 704 | fn split_directories_are_edited_in_place() { |
| 705 | let repo = Repo::new(); |
| 706 | let files: Vec<(String, String)> = (0..2000) |
| 707 | .map(|i| (format!("big/f{i:05}"), format!("{i}"))) |
| 708 | .collect(); |
| 709 | let refs: Vec<(&str, &str)> = files |
| 710 | .iter() |
| 711 | .map(|(p, c)| (p.as_str(), c.as_str())) |
| 712 | .collect(); |
| 713 | let base = repo.tree(&refs); |
| 714 | let new = apply( |
| 715 | &repo.objects, |
| 716 | base, |
| 717 | &[ |
| 718 | repo.set("big/f00010", "changed"), |
| 719 | delete("big/f01999"), |
| 720 | repo.set("big/zzz", "new"), |
| 721 | ], |
| 722 | ) |
| 723 | .unwrap(); |
| 724 | let mut expected: Vec<(&str, &str)> = refs.clone(); |
| 725 | expected[10].1 = "changed"; |
| 726 | expected.pop(); |
| 727 | expected.push(("big/zzz", "new")); |
| 728 | assert_eq!(new, repo.tree(&expected)); |
| 729 | // Shrinking below the split limit gives a flat node again. |
| 730 | let deletes: Vec<Change> = (0..1500).map(|i| delete(&format!("big/f{i:05}"))).collect(); |
| 731 | let small = apply(&repo.objects, base, &deletes).unwrap(); |
| 732 | assert_eq!(small, repo.tree(&refs[1500..])); |
| 733 | } |
| 734 | |
| 735 | #[test] |
| 736 | fn paths_up_to_the_depth_limit() { |
| 737 | let repo = Repo::new(); |
| 738 | let deepest = deep_path(MAX_PATH_DEPTH); |
| 739 | let root = apply(&repo.objects, EMPTY_TREE, &[repo.set(&deepest, "x")]).unwrap(); |
| 740 | assert_eq!(repo.files(root), text_map(&[(&deepest, "x")])); |
| 741 | assert_eq!( |
| 742 | entry_at(&repo.objects, root, deepest.as_bytes()).unwrap(), |
| 743 | Some(repo.file_kind("x")) |
| 744 | ); |
| 745 | // A sibling next to it, then everything deleted again. |
| 746 | let sibling = deepest.replace("/file", "/other"); |
| 747 | let both = apply(&repo.objects, root, &[repo.set(&sibling, "y")]).unwrap(); |
| 748 | let gone = apply(&repo.objects, both, &[delete(&deepest), delete(&sibling)]).unwrap(); |
| 749 | assert_eq!(gone, EMPTY_TREE); |
| 750 | |
| 751 | // One name more is refused before anything is walked or stored. |
| 752 | let deeper = deep_path(MAX_PATH_DEPTH + 1); |
| 753 | let stored = repo.objects.len(); |
| 754 | let result = apply( |
| 755 | &repo.objects, |
| 756 | EMPTY_TREE, |
| 757 | &[repo.set("a", "1"), repo.set(&deeper, "x")], |
| 758 | ); |
| 759 | assert!( |
| 760 | matches!(&result, Err(Error::TooDeep { path }) if *path == deeper.as_bytes()), |
| 761 | "{result:?}" |
| 762 | ); |
| 763 | assert_eq!( |
| 764 | repo.objects.len(), |
| 765 | stored + 1, |
| 766 | "only the blob of `a` was added" |
| 767 | ); |
| 768 | assert!(matches!( |
| 769 | entry_at(&repo.objects, root, deeper.as_bytes()), |
| 770 | Err(Error::TooDeep { .. }) |
| 771 | )); |
| 772 | } |
| 773 | |
| 774 | #[test] |
| 775 | fn deep_paths_need_little_stack() { |
| 776 | // The walks keep their own stacks. At the depth limit they fit in a |
| 777 | // small fraction of this thread stack, where recursing would need |
| 778 | // several megabytes. |
| 779 | let walk = || { |
| 780 | let repo = Repo::new(); |
| 781 | let deepest = deep_path(MAX_PATH_DEPTH); |
| 782 | let root = apply(&repo.objects, EMPTY_TREE, &[repo.set(&deepest, "x")]).unwrap(); |
| 783 | assert_eq!( |
| 784 | diff(&repo.objects, EMPTY_TREE, root).unwrap(), |
| 785 | [repo.set(&deepest, "x")] |
| 786 | ); |
| 787 | assert_eq!( |
| 788 | diff(&repo.objects, root, EMPTY_TREE).unwrap(), |
| 789 | [delete(&deepest)] |
| 790 | ); |
| 791 | }; |
| 792 | std::thread::Builder::new() |
| 793 | .stack_size(256 * 1024) |
| 794 | .spawn(walk) |
| 795 | .unwrap() |
| 796 | .join() |
| 797 | .unwrap(); |
| 798 | } |
| 799 | } |