| 1 | // SPDX-License-Identifier: Apache-2.0 |
| 2 | // Copyright (c) 2026 UtopiaIA |
| 3 | |
| 4 | //! The canonical change list between two trees. |
| 5 | |
| 6 | use std::rc::Rc; |
| 7 | |
| 8 | use braid_format::{Change, ChangeOp, Entry, EntryKind, ObjectId, Objects}; |
| 9 | |
| 10 | use crate::access::Trees; |
| 11 | use crate::error::Error; |
| 12 | use crate::path::{MAX_PATH_DEPTH, depth, join}; |
| 13 | |
| 14 | /// The canonical change list that turns the tree `old_root` into `new_root`: |
| 15 | /// exactly the paths whose file differs (in kind or id), sorted by path bytes, |
| 16 | /// without duplicates. A directory replaced by a file is a delete for every |
| 17 | /// file below it plus a set for the file, and the other way round. |
| 18 | /// |
| 19 | /// Only subtrees whose ids differ are read, so the cost follows the size of |
| 20 | /// the difference. `apply(old, diff(old, new)) == new` (braid trees hold no |
| 21 | /// empty subdirectories), and `diff(x, x)` is empty. A tree deeper than |
| 22 | /// [`MAX_PATH_DEPTH`] is an error. |
| 23 | pub fn diff<O: Objects>( |
| 24 | objects: &O, |
| 25 | old_root: ObjectId, |
| 26 | new_root: ObjectId, |
| 27 | ) -> Result<Vec<Change>, Error> { |
| 28 | let mut trees = Trees::new(objects); |
| 29 | let items = diff_trees(&mut trees, b"", Some(old_root), Some(new_root))?; |
| 30 | Ok(items |
| 31 | .into_iter() |
| 32 | .map(|item| Change { |
| 33 | path: item.path, |
| 34 | op: item.new.unwrap_or(ChangeOp::Delete), |
| 35 | }) |
| 36 | .collect()) |
| 37 | } |
| 38 | |
| 39 | /// One path whose file differs between two trees. |
| 40 | #[derive(Clone, Debug, PartialEq, Eq)] |
| 41 | pub(crate) struct DiffItem { |
| 42 | /// The full path. |
| 43 | pub(crate) path: Vec<u8>, |
| 44 | /// The file before, or `None` if there was none (nothing, or a directory). |
| 45 | pub(crate) old: Option<ChangeOp>, |
| 46 | /// The file after, or `None` if there is none. |
| 47 | pub(crate) new: Option<ChangeOp>, |
| 48 | } |
| 49 | |
| 50 | /// The files that differ between the directories `old` and `new` found at |
| 51 | /// `dir`, either of which may not exist, sorted by path. |
| 52 | /// |
| 53 | /// The walk keeps its own stack of directory pairs rather than recursing, and |
| 54 | /// one path buffer that each pair owns a prefix of, so neither the thread's |
| 55 | /// stack nor the memory for paths grows with the depth beyond the paths |
| 56 | /// themselves. A tree deeper than [`MAX_PATH_DEPTH`] is an error. |
| 57 | pub(crate) fn diff_trees<O: Objects>( |
| 58 | trees: &mut Trees<'_, O>, |
| 59 | dir: &[u8], |
| 60 | old: Option<ObjectId>, |
| 61 | new: Option<ObjectId>, |
| 62 | ) -> Result<Vec<DiffItem>, Error> { |
| 63 | let mut items = Vec::new(); |
| 64 | // The path of the entry being compared. |
| 65 | let mut path = dir.to_vec(); |
| 66 | let mut stack = Vec::new(); |
| 67 | if old != new { |
| 68 | stack.push(Pair::open(trees, &path, depth(dir), old, new)?); |
| 69 | } |
| 70 | while let Some(top) = stack.last_mut() { |
| 71 | let (olds, news) = (Rc::clone(&top.olds), Rc::clone(&top.news)); |
| 72 | let (len, depth) = (top.len, top.depth); |
| 73 | let mut below = None; |
| 74 | while let Some((name, before, after)) = top.next(&olds, &news) { |
| 75 | path.truncate(len); |
| 76 | if len > 0 { |
| 77 | path.push(b'/'); |
| 78 | } |
| 79 | path.extend_from_slice(name); |
| 80 | let (old_file, old_tree) = split(before); |
| 81 | let (new_file, new_tree) = split(after); |
| 82 | if old_file != new_file { |
| 83 | items.push(DiffItem { |
| 84 | path: path.clone(), |
| 85 | old: old_file, |
| 86 | new: new_file, |
| 87 | }); |
| 88 | } |
| 89 | if old_tree != new_tree { |
| 90 | below = Some((old_tree, new_tree)); |
| 91 | break; |
| 92 | } |
| 93 | } |
| 94 | match below { |
| 95 | Some((old, new)) => { |
| 96 | let pair = Pair::open(trees, &path, depth + 1, old, new)?; |
| 97 | stack.push(pair); |
| 98 | } |
| 99 | None => { |
| 100 | stack.pop(); |
| 101 | } |
| 102 | } |
| 103 | } |
| 104 | // A directory's entries are in name order, but `a/x` sorts after `a-b`. |
| 105 | items.sort_by(|a, b| a.path.cmp(&b.path)); |
| 106 | Ok(items) |
| 107 | } |
| 108 | |
| 109 | /// A name, and its entry before and after. |
| 110 | type Versions<'e> = (&'e [u8], Option<&'e EntryKind>, Option<&'e EntryKind>); |
| 111 | |
| 112 | /// Two versions of one directory, compared entry by entry. |
| 113 | struct Pair { |
| 114 | olds: Rc<[Entry]>, |
| 115 | news: Rc<[Entry]>, |
| 116 | /// The next entry of each side to compare. |
| 117 | i: usize, |
| 118 | j: usize, |
| 119 | /// Length of the directory's path in the path buffer. |
| 120 | len: usize, |
| 121 | /// How many names the directory's path has. |
| 122 | depth: usize, |
| 123 | } |
| 124 | |
| 125 | impl Pair { |
| 126 | /// Opens the versions `old` and `new` of the directory at `path`, which |
| 127 | /// has `depth` names. Its entries must not be deeper than the limit. |
| 128 | fn open<O: Objects>( |
| 129 | trees: &mut Trees<'_, O>, |
| 130 | path: &[u8], |
| 131 | depth: usize, |
| 132 | old: Option<ObjectId>, |
| 133 | new: Option<ObjectId>, |
| 134 | ) -> Result<Self, Error> { |
| 135 | let olds = trees.read_or_empty(old)?; |
| 136 | let news = trees.read_or_empty(new)?; |
| 137 | if depth >= MAX_PATH_DEPTH |
| 138 | && let Some(entry) = olds.first().or(news.first()) |
| 139 | { |
| 140 | return Err(Error::TooDeep { |
| 141 | path: join(path, &entry.name), |
| 142 | }); |
| 143 | } |
| 144 | Ok(Pair { |
| 145 | olds, |
| 146 | news, |
| 147 | i: 0, |
| 148 | j: 0, |
| 149 | len: path.len(), |
| 150 | depth, |
| 151 | }) |
| 152 | } |
| 153 | |
| 154 | /// The next name, in order, with its entry on each side. |
| 155 | fn next<'e>(&mut self, olds: &'e [Entry], news: &'e [Entry]) -> Option<Versions<'e>> { |
| 156 | Some(match (olds.get(self.i), news.get(self.j)) { |
| 157 | (None, None) => return None, |
| 158 | (Some(o), Some(n)) if o.name == n.name => { |
| 159 | self.i += 1; |
| 160 | self.j += 1; |
| 161 | (&o.name, Some(&o.kind), Some(&n.kind)) |
| 162 | } |
| 163 | (Some(o), Some(n)) if o.name < n.name => { |
| 164 | self.i += 1; |
| 165 | (&o.name, Some(&o.kind), None) |
| 166 | } |
| 167 | (Some(o), None) => { |
| 168 | self.i += 1; |
| 169 | (&o.name, Some(&o.kind), None) |
| 170 | } |
| 171 | (_, Some(n)) => { |
| 172 | self.j += 1; |
| 173 | (&n.name, None, Some(&n.kind)) |
| 174 | } |
| 175 | }) |
| 176 | } |
| 177 | } |
| 178 | |
| 179 | /// An entry as a file and as a directory: at most one of the two. |
| 180 | fn split(entry: Option<&EntryKind>) -> (Option<ChangeOp>, Option<ObjectId>) { |
| 181 | match entry { |
| 182 | Some(EntryKind::Tree { tree }) => (None, Some(*tree)), |
| 183 | Some(kind) => (ChangeOp::from_entry(kind), None), |
| 184 | None => (None, None), |
| 185 | } |
| 186 | } |
| 187 | |
| 188 | #[cfg(test)] |
| 189 | mod tests { |
| 190 | use super::*; |
| 191 | use crate::access::{EMPTY_TREE, write_tree}; |
| 192 | use crate::apply::apply; |
| 193 | use crate::testing::{Repo, deep_path, delete, gitlink}; |
| 194 | |
| 195 | #[test] |
| 196 | fn identical_trees_have_no_changes() { |
| 197 | let repo = Repo::new(); |
| 198 | let root = repo.tree(&[("a/b", "1"), ("c", "2")]); |
| 199 | assert_eq!(diff(&repo.objects, root, root).unwrap(), []); |
| 200 | assert_eq!(diff(&repo.objects, EMPTY_TREE, EMPTY_TREE).unwrap(), []); |
| 201 | } |
| 202 | |
| 203 | #[test] |
| 204 | fn changes_are_per_file_and_sorted_by_path_bytes() { |
| 205 | let repo = Repo::new(); |
| 206 | let old = repo.tree(&[("a/x", "1"), ("a-b", "2"), ("a0", "3"), ("keep/k", "4")]); |
| 207 | let new = repo.tree(&[("a", "5"), ("a-b", "6"), ("a0", "3"), ("keep/k", "4")]); |
| 208 | let changes = diff(&repo.objects, old, new).unwrap(); |
| 209 | assert_eq!( |
| 210 | changes, |
| 211 | [repo.set("a", "5"), repo.set("a-b", "6"), delete("a/x")] |
| 212 | ); |
| 213 | assert_eq!(apply(&repo.objects, old, &changes).unwrap(), new); |
| 214 | |
| 215 | // The other way: a file replaced by a directory. |
| 216 | let back = diff(&repo.objects, new, old).unwrap(); |
| 217 | assert_eq!( |
| 218 | back, |
| 219 | [delete("a"), repo.set("a-b", "2"), repo.set("a/x", "1")] |
| 220 | ); |
| 221 | assert_eq!(apply(&repo.objects, new, &back).unwrap(), old); |
| 222 | } |
| 223 | |
| 224 | #[test] |
| 225 | fn from_and_to_the_empty_tree() { |
| 226 | let repo = Repo::new(); |
| 227 | let root = repo.tree(&[("d/e/f", "1"), ("g", "2")]); |
| 228 | assert_eq!( |
| 229 | diff(&repo.objects, EMPTY_TREE, root).unwrap(), |
| 230 | [repo.set("d/e/f", "1"), repo.set("g", "2")] |
| 231 | ); |
| 232 | assert_eq!( |
| 233 | diff(&repo.objects, root, EMPTY_TREE).unwrap(), |
| 234 | [delete("d/e/f"), delete("g")] |
| 235 | ); |
| 236 | } |
| 237 | |
| 238 | #[test] |
| 239 | fn kind_changes_are_changes() { |
| 240 | let repo = Repo::new(); |
| 241 | let old = repo.tree(&[("f", "same")]); |
| 242 | let exec = apply(&repo.objects, old, &[repo.exec("f", "same")]).unwrap(); |
| 243 | assert_eq!( |
| 244 | diff(&repo.objects, old, exec).unwrap(), |
| 245 | [repo.exec("f", "same")] |
| 246 | ); |
| 247 | let link = apply(&repo.objects, old, &[gitlink("f", 1)]).unwrap(); |
| 248 | assert_eq!(diff(&repo.objects, old, link).unwrap(), [gitlink("f", 1)]); |
| 249 | } |
| 250 | |
| 251 | /// A tree whose one file sits below `dirs` directories named `d`, built |
| 252 | /// by hand: no change list can make one deeper than the limit. |
| 253 | fn chain(repo: &Repo, dirs: usize) -> ObjectId { |
| 254 | let file = Entry { |
| 255 | name: b"file".to_vec(), |
| 256 | kind: repo.file_kind("x"), |
| 257 | }; |
| 258 | let mut tree = write_tree(&repo.objects, vec![file]).unwrap(); |
| 259 | for _ in 0..dirs { |
| 260 | let dir = Entry { |
| 261 | name: b"d".to_vec(), |
| 262 | kind: EntryKind::Tree { tree }, |
| 263 | }; |
| 264 | tree = write_tree(&repo.objects, vec![dir]).unwrap(); |
| 265 | } |
| 266 | tree |
| 267 | } |
| 268 | |
| 269 | #[test] |
| 270 | fn trees_deeper_than_the_limit_are_an_error() { |
| 271 | let repo = Repo::new(); |
| 272 | let at_limit = chain(&repo, MAX_PATH_DEPTH - 1); |
| 273 | assert_eq!( |
| 274 | diff(&repo.objects, EMPTY_TREE, at_limit).unwrap(), |
| 275 | [repo.set(&deep_path(MAX_PATH_DEPTH), "x")] |
| 276 | ); |
| 277 | let too_deep = chain(&repo, MAX_PATH_DEPTH); |
| 278 | for result in [ |
| 279 | diff(&repo.objects, EMPTY_TREE, too_deep), |
| 280 | diff(&repo.objects, too_deep, EMPTY_TREE), |
| 281 | diff(&repo.objects, at_limit, too_deep), |
| 282 | ] { |
| 283 | assert!( |
| 284 | matches!(&result, Err(Error::TooDeep { path }) |
| 285 | if *path == deep_path(MAX_PATH_DEPTH + 1).as_bytes()), |
| 286 | "{result:?}" |
| 287 | ); |
| 288 | } |
| 289 | } |
| 290 | } |