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