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