Onset: version control where nobody waits and nothing gets lost. The on command, its core and onset-server.
| 5 |
| 6 | use crate::object::{Kind, Object}; |
| 7 | use crate::{Id, Result, Source, corrupt}; |
| 8 |
| 9 | #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)] |
| 10 | #[repr(u8)] |
| 11 | pub enum EntryKind { |
| 12 | File = 1, |
| 13 | Exec = 2, |
| 14 | Link = 3, |
| 15 | Tree = 4, |
| 16 | /// A git submodule: its content is the commit it points at (40 hex digits). |
| 17 | Gitlink = 5, |
| 18 | } |
| 19 |
| 20 | impl EntryKind { |
| 21 | pub fn from_u8(b: u8) -> Option<EntryKind> { |
| 22 | match b { |
| 23 | 1 => Some(EntryKind::File), |
| 24 | 2 => Some(EntryKind::Exec), |
| 25 | 3 => Some(EntryKind::Link), |
| 26 | 4 => Some(EntryKind::Tree), |
| 27 | 5 => Some(EntryKind::Gitlink), |
| 28 | _ => None, |
| 29 | } |
| 30 | } |
| 31 |
| 32 | pub fn name(self) -> &'static str { |
| 33 | match self { |
| 34 | EntryKind::File => "file", |
| 35 | EntryKind::Exec => "exec", |
| 36 | EntryKind::Link => "link", |
| 37 | EntryKind::Tree => "tree", |
| 38 | EntryKind::Gitlink => "submodule", |
| 39 | } |
| 40 | } |
| 41 | } |
| 42 |
| 43 | /// A file in a flattened tree. `id` names a blob or, for big files, a chunk list. |
| 44 | #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] |
| 45 | pub struct Entry { |
| 46 | pub kind: EntryKind, |
| 47 | pub id: Id, |
| 48 | } |
| 49 |
| 50 | pub type Files = BTreeMap<String, Entry>; |
| 51 |
| 52 | #[derive(Debug, Clone, PartialEq, Eq)] |
| 53 | pub struct TreeEntry { |
| 54 | pub name: String, |
| 55 | pub kind: EntryKind, |
| 56 | pub id: Id, |
| 57 | } |
| 58 |
| 59 | pub fn encode(entries: &[TreeEntry]) -> Vec<u8> { |
| 60 | let mut sorted: Vec<&TreeEntry> = entries.iter().collect(); |
| 61 | sorted.sort_by(|a, b| a.name.as_bytes().cmp(b.name.as_bytes())); |
| 62 | let mut out = Vec::with_capacity(entries.len() * 48); |
| 63 | for e in sorted { |
| 64 | out.push(e.kind as u8); |
| 65 | out.extend_from_slice(&(e.name.len() as u16).to_le_bytes()); |
| 66 | out.extend_from_slice(e.name.as_bytes()); |
| 67 | out.extend_from_slice(&e.id.0); |
| 68 | } |
| 69 | out |
| 70 | } |
| 71 |
| 72 | pub fn decode(data: &[u8]) -> Result<Vec<TreeEntry>> { |
| 73 | let mut out = Vec::new(); |
| 74 | let mut at = 0; |
| 75 | while at < data.len() { |
| 76 | let kind = EntryKind::from_u8(data[at]).ok_or_else(|| corrupt("bad tree entry kind"))?; |
| 77 | let len = u16::from_le_bytes(data.get(at + 1..at + 3).ok_or_else(|| corrupt("short tree"))?.try_into().unwrap()) as usize; |
| 78 | let name_end = at + 3 + len; |
| 79 | let name = std::str::from_utf8(data.get(at + 3..name_end).ok_or_else(|| corrupt("short tree"))?) |
| 80 | .map_err(|_| corrupt("tree name isn't UTF-8"))? |
| 81 | .to_string(); |
| 82 | if name.is_empty() || name.contains('/') || name == "." || name == ".." { |
| 83 | return Err(corrupt("bad name in tree")); |
| 84 | } |
| 85 | let id = Id::from_slice(data.get(name_end..name_end + 32).ok_or_else(|| corrupt("short tree"))?).unwrap(); |
| 86 | out.push(TreeEntry { name, kind, id }); |
| 87 | at = name_end + 32; |
| 88 | } |
| 89 | Ok(out) |
| 90 | } |
| 91 |
| 92 | pub fn empty() -> Object { |
| 93 | Object::new(Kind::Tree, Vec::new()) |
| 94 | } |
| 95 |
| 96 | pub fn empty_id() -> Id { |
| 97 | empty().id() |
| 98 | } |
| 99 |
| 100 | pub fn read(src: &dyn Source, id: &Id) -> Result<Vec<TreeEntry>> { |
| 101 | let object = src.must(id)?; |
| 102 | if object.kind != Kind::Tree { |
| 103 | return Err(corrupt(format!("{} isn't a tree", id.short()))); |
| 104 | } |
| 105 | decode(&object.data) |
| 106 | } |
| 107 |
| 108 | /// The entry at `path` under `root` (None: not there), reading only the |
| 109 | /// folders on the path. The root itself is a folder. |
| 110 | pub fn lookup(src: &dyn Source, root: &Id, path: &str) -> Result<Option<Entry>> { |
| 111 | let mut at = Entry { kind: EntryKind::Tree, id: *root }; |
| 112 | for part in path.split('/').filter(|p| !p.is_empty()) { |
| 113 | if at.kind != EntryKind::Tree { |
| 114 | return Ok(None); |
| 115 | } |
| 116 | let object = src.must(&at.id)?; |
| 117 | if object.kind != Kind::Tree { |
| 118 | return Err(corrupt(format!("{} isn't a tree", at.id.short()))); |
| 119 | } |
| 120 | // In order (as trees are written): found by halves, without copying names. |
| 121 | let found = match raw_entries(&object.data)? { |
| 122 | Some(es) => es.binary_search_by(|e| e.name.as_bytes().cmp(part.as_bytes())).ok().map(|i| Entry { kind: es[i].kind, id: es[i].id }), |
| 123 | None => decode(&object.data)?.into_iter().find(|e| e.name == part).map(|e| Entry { kind: e.kind, id: e.id }), |
| 124 | }; |
| 125 | match found { |
| 126 | Some(e) => at = e, |
| 127 | None => return Ok(None), |
| 128 | } |
| 129 | } |
| 130 | Ok(Some(at)) |
| 131 | } |
| 132 |
| 133 | /// The first object on the way to `path` under `root` that `src` doesn't |
| 134 | /// have: a folder on the path, or the entry at its end (None: all there, or |
| 135 | /// the path isn't there). |
| 136 | pub fn missing_along(src: &dyn Source, root: &Id, path: &str) -> Result<Option<Id>> { |
| 137 | let mut at = *root; |
| 138 | let parts: Vec<&str> = path.split('/').filter(|p| !p.is_empty()).collect(); |
| 139 | for (i, part) in parts.iter().enumerate() { |
| 140 | let Some(object) = src.get(&at)? else { return Ok(Some(at)) }; |
| 141 | if object.kind != Kind::Tree { |
| 142 | return Ok(None); |
| 143 | } |
| 144 | let found = match raw_entries(&object.data)? { |
| 145 | Some(es) => es.binary_search_by(|e| e.name.as_bytes().cmp(part.as_bytes())).ok().map(|j| (es[j].kind, es[j].id)), |
| 146 | None => decode(&object.data)?.into_iter().find(|e| e.name == *part).map(|e| (e.kind, e.id)), |
| 147 | }; |
| 148 | let Some((kind, id)) = found else { return Ok(None) }; |
| 149 | if i + 1 == parts.len() { |
| 150 | // The entry itself: a file's content (or a big file's list), or a folder. |
| 151 | return Ok(if src.get(&id)?.is_none() { Some(id) } else { None }); |
| 152 | } |
| 153 | if kind != EntryKind::Tree { |
| 154 | return Ok(None); |
| 155 | } |
| 156 | at = id; |
| 157 | } |
| 158 | Ok(None) |
| 159 | } |
| 160 |
| 161 | /// Every file under `tree`. |
| 162 | pub fn flatten(src: &dyn Source, tree: &Id) -> Result<Files> { |
| 163 | let mut out = Files::new(); |
| 164 | walk(src, tree, "", &mut out)?; |
| 165 | Ok(out) |
| 166 | } |
| 167 |
| 168 | fn walk(src: &dyn Source, tree: &Id, prefix: &str, out: &mut Files) -> Result<()> { |
| 169 | for e in read(src, tree)? { |
| 170 | let path = if prefix.is_empty() { e.name.clone() } else { format!("{prefix}/{}", e.name) }; |
| 171 | if e.kind == EntryKind::Tree { |
| 172 | walk(src, &e.id, &path, out)?; |
| 173 | } else { |
| 174 | out.insert(path, Entry { kind: e.kind, id: e.id }); |
| 175 | } |
| 176 | } |
| 177 | Ok(()) |
| 178 | } |
| 179 |
| 180 | /// Every object ID a tree reaches (the trees themselves, file blobs and |
| 181 | /// chunk lists, not the chunks inside chunk lists). |
| 182 | pub fn reachable(src: &dyn Source, tree: &Id, out: &mut Vec<Id>) -> Result<()> { |
| 183 | out.push(*tree); |
| 184 | for e in read(src, tree)? { |
| 185 | if e.kind == EntryKind::Tree { |
| 186 | reachable(src, &e.id, out)?; |
| 187 | } else { |
| 188 | out.push(e.id); |
| 189 | } |
| 190 | } |
| 191 | Ok(()) |
| 192 | } |
| 193 |
| 194 | /// Trees reached from `new` but not from `old`, walking only subtrees that |
| 195 | /// differ, plus the file IDs those subtrees hold that `old` doesn't have at |
| 196 | /// the same path. |
| 197 | pub fn new_since(src: &dyn Source, old: Option<&Id>, new: &Id, out: &mut Vec<Id>) -> Result<()> { |
| 198 | if Some(new) == old { |
| 199 | return Ok(()); |
| 200 | } |
| 201 | out.push(*new); |
| 202 | let old_entries: HashMap<String, TreeEntry> = match old { |
| 203 | Some(o) => read(src, o)?.into_iter().map(|e| (e.name.clone(), e)).collect(), |
| 204 | None => HashMap::new(), |
| 205 | }; |
| 206 | for e in read(src, new)? { |
| 207 | let before = old_entries.get(&e.name); |
| 208 | if before.is_some_and(|b| b.id == e.id) { |
| 209 | continue; |
| 210 | } |
| 211 | if e.kind == EntryKind::Tree { |
| 212 | let old_sub = before.filter(|b| b.kind == EntryKind::Tree).map(|b| b.id); |
| 213 | new_since(src, old_sub.as_ref(), &e.id, out)?; |
| 214 | } else { |
| 215 | out.push(e.id); |
| 216 | } |
| 217 | } |
| 218 | Ok(()) |
| 219 | } |
| 220 |
| 221 | /// Builds tree objects for `files`. Returns the root ID and every tree |
| 222 | /// object (the host stores the ones it doesn't have). |
| 223 | pub fn build(files: &Files) -> (Id, Vec<Object>) { |
| 224 | let mut dirs: HashMap<&str, Vec<TreeEntry>> = HashMap::new(); |
| 225 | let mut subdirs: HashMap<&str, Vec<&str>> = HashMap::new(); |
| 226 | dirs.entry("").or_default(); |
| 227 | for (path, entry) in files { |
| 228 | let (dir, name) = split(path); |
| 229 | dirs.entry(dir).or_default().push(TreeEntry { name: name.to_string(), kind: entry.kind, id: entry.id }); |
| 230 | let mut d = dir; |
| 231 | while !d.is_empty() { |
| 232 | let (parent, _) = split(d); |
| 233 | let known = subdirs.entry(parent).or_default(); |
| 234 | if known.contains(&d) { |
| 235 | break; |
| 236 | } |
| 237 | known.push(d); |
| 238 | dirs.entry(d).or_default(); |
| 239 | d = parent; |
| 240 | } |
| 241 | } |
| 242 | let mut order: Vec<&str> = dirs.keys().copied().collect(); |
| 243 | order.sort_by_key(|d| std::cmp::Reverse(if d.is_empty() { 0 } else { d.matches('/').count() + 1 })); |
| 244 | let mut written: HashMap<&str, Id> = HashMap::with_capacity(order.len()); |
| 245 | let mut objects = Vec::with_capacity(order.len()); |
| 246 | for dir in order { |
| 247 | let mut entries = dirs.remove(dir).unwrap_or_default(); |
| 248 | for child in subdirs.get(dir).map(Vec::as_slice).unwrap_or(&[]) { |
| 249 | entries.push(TreeEntry { name: split(child).1.to_string(), kind: EntryKind::Tree, id: written[child] }); |
| 250 | } |
| 251 | let object = Object::new(Kind::Tree, encode(&entries)); |
| 252 | let id = object.id(); |
| 253 | objects.push(object); |
| 254 | written.insert(dir, id); |
| 255 | } |
| 256 | (written[""], objects) |
| 257 | } |
| 258 |
| 259 | /// "a/b/c" → ("a/b", "c"); "c" → ("", "c"). |
| 260 | pub fn split(path: &str) -> (&str, &str) { |
| 261 | match path.rfind('/') { |
| 262 | Some(i) => (&path[..i], &path[i + 1..]), |
| 263 | None => ("", path), |
| 264 | } |
| 265 | } |
| 266 |
| 267 | /// Whether `path` is `prefix` or inside it. |
| 268 | pub fn under(path: &str, prefix: &str) -> bool { |
| 269 | prefix.is_empty() || path == prefix || (path.starts_with(prefix) && path.as_bytes().get(prefix.len()) == Some(&b'/')) |
| 270 | } |
| 271 |
| 272 | #[derive(Debug, Clone, PartialEq, Eq)] |
| 273 | pub enum Change { |
| 274 | Added(Entry), |
| 275 | Removed(Entry), |
| 276 | Modified(Entry, Entry), |
| 277 | } |
| 278 |
| 279 | /// What changed from `a` to `b`, by path. |
| 280 | pub fn diff(a: &Files, b: &Files) -> BTreeMap<String, Change> { |
| 281 | let mut out = BTreeMap::new(); |
| 282 | for (path, old) in a { |
| 283 | match b.get(path) { |
| 284 | None => { |
| 285 | out.insert(path.clone(), Change::Removed(*old)); |
| 286 | } |
| 287 | Some(new) if new != old => { |
| 288 | out.insert(path.clone(), Change::Modified(*old, *new)); |
| 289 | } |
| 290 | _ => {} |
| 291 | } |
| 292 | } |
| 293 | for (path, new) in b { |
| 294 | if !a.contains_key(path) { |
| 295 | out.insert(path.clone(), Change::Added(*new)); |
| 296 | } |
| 297 | } |
| 298 | out |
| 299 | } |
| 300 |
| 301 | /// A file to write into a tree: its path, kind and content. |
| 302 | pub struct Put { |
| 303 | pub path: String, |
| 304 | pub kind: EntryKind, |
| 305 | pub content: Vec<u8>, |
| 306 | } |
| 307 |
| 308 | /// Whether `path` can name a file: relative, every part a [`safe_name`]. |
| 309 | pub fn valid_path(path: &str) -> bool { |
| 310 | !path.is_empty() && path.split('/').all(safe_name) |
| 311 | } |
| 312 |
| 313 | /// Whether one part of a path is safe on every system. Not empty, `.` or |
| 314 | /// `..`; no backslash (a separator on Windows) or NUL; and not Onset's |
| 315 | /// (`.onset`, or `.vcs` from before it had its name) or git's own folder in |
| 316 | /// any spelling some disk treats as the same (`.GIT`, |
| 317 | /// `.git.`, `git~1`, or with characters macOS ignores), since a project |
| 318 | /// holding `.git/hooks/...` would run code in the folders it's written to. |
| 319 | pub fn safe_name(name: &str) -> bool { |
| 320 | if name.is_empty() || name == "." || name == ".." || name.len() > u16::MAX as usize || name.contains(['\\', '\0']) { |
| 321 | return false; |
| 322 | } |
| 323 | let plain: String = name |
| 324 | .chars() |
| 325 | .filter(|c| !matches!(*c as u32, 0x200C..=0x200F | 0x202A..=0x202E | 0x206A..=0x206F | 0xFEFF)) |
| 326 | .collect::<String>() |
| 327 | .trim_end_matches(['.', ' ']) |
| 328 | .to_ascii_lowercase(); |
| 329 | !matches!(plain.as_str(), ".git" | ".onset" | ".vcs" | "git~1" | "onset~1" | "vcs~1") |
| 330 | } |
| 331 |
| 332 | /// The first path `new` adds or changes over `old` that isn't a |
| 333 | /// [`valid_path`], if any. Paths already there aren't looked at again. |
| 334 | pub fn unsafe_path(src: &dyn Source, old: &Id, new: &Id) -> Result<Option<String>> { |
| 335 | Ok(diff_trees(src, old, new)?.into_iter().find(|(p, c)| !matches!(c, Change::Removed(_)) && !valid_path(p)).map(|(p, _)| p)) |
| 336 | } |
| 337 |
| 338 | /// `tree` with files written and deleted. Writing a path replaces whatever |
| 339 | /// was there (a folder of that name included); deleting a folder deletes |
| 340 | /// what's in it. Returns the new root and every object it needs that's new |
| 341 | /// (file contents, big files' chunks and trees). |
| 342 | pub fn edit(src: &dyn Source, tree: &Id, put: &[Put], delete: &[String]) -> Result<std::result::Result<(Id, Vec<Object>), String>> { |
| 343 | Ok(edit_based(src, tree, put, delete)?.map(|(root, objects, _)| (root, objects))) |
| 344 | } |
| 345 |
| 346 | /// `edit`, also saying what each new folder and file replaced: |
| 347 | /// (new object, the one it replaced), for a host keeping it as a delta. |
| 348 | #[allow(clippy::type_complexity)] |
| 349 | pub fn edit_based(src: &dyn Source, tree: &Id, put: &[Put], delete: &[String]) -> Result<std::result::Result<(Id, Vec<Object>, Vec<(Id, Id)>), String>> { |
| 350 | if let Some(bad) = put.iter().map(|p| p.path.as_str()).chain(delete.iter().map(String::as_str)).find(|p| !valid_path(p)) { |
| 351 | return Ok(Err(bad.to_string())); |
| 352 | } |
| 353 | let mut objects = Vec::new(); |
| 354 | let mut ops: Vec<EditOp> = delete.iter().map(|d| EditOp::Delete(d)).collect(); |
| 355 | for p in put { |
| 356 | let parts = crate::chunk::file_objects(&p.content); |
| 357 | ops.push(EditOp::Put(&p.path, Entry { kind: p.kind, id: parts[0].id() })); |
| 358 | objects.extend(parts); |
| 359 | } |
| 360 | // Only the folders on the edited paths are read and written again. |
| 361 | let mut bases = Vec::new(); |
| 362 | let root = match edit_dir(src, Some(tree), &ops, &mut objects, &mut bases)? { |
| 363 | Some(root) => root, |
| 364 | None => { |
| 365 | let empty = empty(); |
| 366 | let id = empty.id(); |
| 367 | objects.push(empty); |
| 368 | id |
| 369 | } |
| 370 | }; |
| 371 | Ok(Ok((root, objects, bases))) |
| 372 | } |
| 373 |
| 374 | /// An edit, with its path relative to the folder it's applied in. Deletes |
| 375 | /// come first, then writes in order. |
| 376 | #[derive(Clone, Copy)] |
| 377 | enum EditOp<'a> { |
| 378 | Put(&'a str, Entry), |
| 379 | Delete(&'a str), |
| 380 | } |
| 381 |
| 382 | /// `tree` (None: a new folder) with `ops` applied; None when nothing's left |
| 383 | /// in it. A file and a folder can't share a path, so writing one replaces |
| 384 | /// the other. |
| 385 | /// A path's first name, and the rest (None: the name is the last). |
| 386 | fn first_name<'a>(op: &EditOp<'a>) -> (&'a str, Option<&'a str>) { |
| 387 | let path = match op { |
| 388 | EditOp::Put(p, _) | EditOp::Delete(p) => *p, |
| 389 | }; |
| 390 | match path.split_once('/') { |
| 391 | Some((name, rest)) => (name, Some(rest)), |
| 392 | None => (path, None), |
| 393 | } |
| 394 | } |
| 395 |
| 396 | /// What an edit does to one name in a folder. |
| 397 | enum Child<'a> { |
| 398 | Gone, |
| 399 | File(Entry), |
| 400 | Dir(Option<Id>, Vec<EditOp<'a>>), |
| 401 | } |
| 402 |
| 403 | /// The edits under one folder, by name, from what's there now (`at`). |
| 404 | fn children<'a>(ops: &[EditOp<'a>], at: impl Fn(&str) -> Option<Entry>, bases: &mut Vec<(Id, Id)>) -> BTreeMap<&'a str, Child<'a>> { |
| 405 | let mut touched: BTreeMap<&str, Child> = BTreeMap::new(); |
| 406 | for op in ops { |
| 407 | let (name, rest) = first_name(op); |
| 408 | let child = touched.entry(name).or_insert_with(|| match at(name) { |
| 409 | Some(e) if e.kind == EntryKind::Tree => Child::Dir(Some(e.id), Vec::new()), |
| 410 | Some(e) => Child::File(e), |
| 411 | None => Child::Gone, |
| 412 | }); |
| 413 | match (op, rest) { |
| 414 | (EditOp::Delete(_), None) => *child = Child::Gone, |
| 415 | (EditOp::Delete(_), Some(rest)) => { |
| 416 | if let Child::Dir(_, inner) = child { |
| 417 | inner.push(EditOp::Delete(rest)); |
| 418 | } |
| 419 | } |
| 420 | (EditOp::Put(_, e), None) => { |
| 421 | if let Child::File(old) = child |
| 422 | && old.id != e.id |
| 423 | { |
| 424 | bases.push((e.id, old.id)); |
| 425 | } |
| 426 | *child = Child::File(*e); |
| 427 | } |
| 428 | (EditOp::Put(_, e), Some(rest)) => { |
| 429 | if !matches!(child, Child::Dir(..)) { |
| 430 | *child = Child::Dir(None, Vec::new()); |
| 431 | } |
| 432 | if let Child::Dir(_, inner) = child { |
| 433 | inner.push(EditOp::Put(rest, *e)); |
| 434 | } |
| 435 | } |
| 436 | } |
| 437 | } |
| 438 | touched |
| 439 | } |
| 440 |
| 441 | /// A child's entry once its edits are made (folders edited first). |
| 442 | fn child_entry(src: &dyn Source, child: Child, objects: &mut Vec<Object>, bases: &mut Vec<(Id, Id)>) -> Result<Option<Entry>> { |
| 443 | Ok(match child { |
| 444 | Child::Gone => None, |
| 445 | Child::File(e) => Some(e), |
| 446 | Child::Dir(base, inner) if inner.is_empty() => base.map(|id| Entry { kind: EntryKind::Tree, id }), |
| 447 | Child::Dir(base, inner) => edit_dir(src, base.as_ref(), &inner, objects, bases)?.map(|id| Entry { kind: EntryKind::Tree, id }), |
| 448 | }) |
| 449 | } |
| 450 |
| 451 | /// Keeps a folder made by an edit, as a delta's candidate on the one it replaced. |
| 452 | fn made_dir(tree: Option<&Id>, data: Vec<u8>, objects: &mut Vec<Object>, bases: &mut Vec<(Id, Id)>) -> Option<Id> { |
| 453 | let object = Object::new(Kind::Tree, data); |
| 454 | let id = object.id(); |
| 455 | objects.push(object); |
| 456 | if let Some(t) = tree { |
| 457 | bases.push((id, *t)); |
| 458 | } |
| 459 | Some(id) |
| 460 | } |
| 461 |
| 462 | fn edit_dir(src: &dyn Source, tree: Option<&Id>, ops: &[EditOp], objects: &mut Vec<Object>, bases: &mut Vec<(Id, Id)>) -> Result<Option<Id>> { |
| 463 | // In place: the folder's bytes with the changed entries written over |
| 464 | // (a busy host spent a third of a land decoding folders and writing |
| 465 | // them out again). A folder whose entries aren't in order goes the |
| 466 | // general way. |
| 467 | let object = match tree { |
| 468 | Some(t) => Some(src.must(t)?), |
| 469 | None => None, |
| 470 | }; |
| 471 | if let Some(o) = &object |
| 472 | && o.kind != Kind::Tree |
| 473 | { |
| 474 | return Err(corrupt(format!("{} isn't a tree", tree.unwrap().short()))); |
| 475 | } |
| 476 | let data: &[u8] = object.as_ref().map_or(&[], |o| &o.data); |
| 477 | let Some(raw) = raw_entries(data)? else { |
| 478 | return edit_dir_decoded(src, tree, ops, objects, bases); |
| 479 | }; |
| 480 | let find = |name: &str| raw.binary_search_by(|e| e.name.as_bytes().cmp(name.as_bytes())); |
| 481 | let touched = children(ops, |name| find(name).ok().map(|i| Entry { kind: raw[i].kind, id: raw[i].id }), bases); |
| 482 | let mut out: Vec<u8> = Vec::with_capacity(data.len() + 64); |
| 483 | let mut copied = 0; |
| 484 | let mut changed = false; |
| 485 | // Names in order (as the entries are), so each goes where it belongs. |
| 486 | for (name, child) in touched { |
| 487 | let next = child_entry(src, child, objects, bases)?; |
| 488 | let at = find(name); |
| 489 | let now = at.ok().map(|i| Entry { kind: raw[i].kind, id: raw[i].id }); |
| 490 | if now == next { |
| 491 | continue; |
| 492 | } |
| 493 | changed = true; |
| 494 | let (from, to) = match at { |
| 495 | Ok(i) => (raw[i].start, raw[i].end), |
| 496 | Err(i) => { |
| 497 | let pos = raw.get(i).map_or(data.len(), |e| e.start); |
| 498 | (pos, pos) |
| 499 | } |
| 500 | }; |
| 501 | out.extend_from_slice(&data[copied..from]); |
| 502 | copied = to; |
| 503 | if let Some(e) = next { |
| 504 | out.push(e.kind as u8); |
| 505 | out.extend_from_slice(&(name.len() as u16).to_le_bytes()); |
| 506 | out.extend_from_slice(name.as_bytes()); |
| 507 | out.extend_from_slice(&e.id.0); |
| 508 | } |
| 509 | } |
| 510 | if !changed && tree.is_some() { |
| 511 | return Ok(tree.copied()); |
| 512 | } |
| 513 | out.extend_from_slice(&data[copied..]); |
| 514 | if out.is_empty() { |
| 515 | return Ok(None); |
| 516 | } |
| 517 | Ok(made_dir(tree, out, objects, bases)) |
| 518 | } |
| 519 |
| 520 | /// `edit_dir` on the folder's entries decoded (any order). |
| 521 | fn edit_dir_decoded(src: &dyn Source, tree: Option<&Id>, ops: &[EditOp], objects: &mut Vec<Object>, bases: &mut Vec<(Id, Id)>) -> Result<Option<Id>> { |
| 522 | let mut entries: BTreeMap<String, Entry> = match tree { |
| 523 | Some(t) => read(src, t)?.into_iter().map(|e| (e.name, Entry { kind: e.kind, id: e.id })).collect(), |
| 524 | None => BTreeMap::new(), |
| 525 | }; |
| 526 | let touched = children(ops, |name| entries.get(name).copied(), bases); |
| 527 | let mut changed = false; |
| 528 | for (name, child) in touched { |
| 529 | let next = child_entry(src, child, objects, bases)?; |
| 530 | if entries.get(name) != next.as_ref() { |
| 531 | changed = true; |
| 532 | match next { |
| 533 | Some(e) => entries.insert(name.to_string(), e), |
| 534 | None => entries.remove(name), |
| 535 | }; |
| 536 | } |
| 537 | } |
| 538 | if !changed && tree.is_some() { |
| 539 | return Ok(tree.copied()); |
| 540 | } |
| 541 | if entries.is_empty() { |
| 542 | return Ok(None); |
| 543 | } |
| 544 | let list: Vec<TreeEntry> = entries.into_iter().map(|(name, e)| TreeEntry { name, kind: e.kind, id: e.id }).collect(); |
| 545 | Ok(made_dir(tree, encode(&list), objects, bases)) |
| 546 | } |
| 547 |
| 548 | /// What changed from tree `a` to tree `b`, by path, reading only the |
| 549 | /// folders that differ (the same answer as `diff` on both flattened). |
| 550 | pub fn diff_trees(src: &dyn Source, a: &Id, b: &Id) -> Result<BTreeMap<String, Change>> { |
| 551 | let mut out = BTreeMap::new(); |
| 552 | diff_into(src, Some(a), Some(b), "", &mut out)?; |
| 553 | Ok(out) |
| 554 | } |
| 555 |
| 556 | /// A tree entry read in place: the name borrows the tree's bytes, which |
| 557 | /// hold the entry from `start` to `end`. |
| 558 | pub struct RawEntry<'a> { |
| 559 | pub name: &'a str, |
| 560 | pub kind: EntryKind, |
| 561 | pub id: Id, |
| 562 | pub start: usize, |
| 563 | pub end: usize, |
| 564 | } |
| 565 |
| 566 | /// A tree's entries, checked as `decode` checks them, without copying names; |
| 567 | /// None when they aren't in order (then the general path compares them). |
| 568 | pub fn raw_entries(data: &[u8]) -> Result<Option<Vec<RawEntry<'_>>>> { |
| 569 | let mut out: Vec<RawEntry<'_>> = Vec::new(); |
| 570 | let mut at = 0; |
| 571 | while at < data.len() { |
| 572 | let kind = EntryKind::from_u8(data[at]).ok_or_else(|| corrupt("bad tree entry kind"))?; |
| 573 | let len = u16::from_le_bytes(data.get(at + 1..at + 3).ok_or_else(|| corrupt("short tree"))?.try_into().unwrap()) as usize; |
| 574 | let name_end = at + 3 + len; |
| 575 | let name = std::str::from_utf8(data.get(at + 3..name_end).ok_or_else(|| corrupt("short tree"))?).map_err(|_| corrupt("tree name isn't UTF-8"))?; |
| 576 | if name.is_empty() || name.contains('/') || name == "." || name == ".." { |
| 577 | return Err(corrupt("bad name in tree")); |
| 578 | } |
| 579 | let id = Id::from_slice(data.get(name_end..name_end + 32).ok_or_else(|| corrupt("short tree"))?).unwrap(); |
| 580 | if out.last().is_some_and(|last| last.name.as_bytes() >= name.as_bytes()) { |
| 581 | return Ok(None); |
| 582 | } |
| 583 | out.push(RawEntry { name, kind, id, start: at, end: name_end + 32 }); |
| 584 | at = name_end + 32; |
| 585 | } |
| 586 | Ok(Some(out)) |
| 587 | } |
| 588 |
| 589 | fn diff_into(src: &dyn Source, a: Option<&Id>, b: Option<&Id>, prefix: &str, out: &mut BTreeMap<String, Change>) -> Result<()> { |
| 590 | if a == b { |
| 591 | return Ok(()); |
| 592 | } |
| 593 | // Both trees' entries are sorted by name (encode sorts them): walk the |
| 594 | // two lists side by side, which reads each entry once. |
| 595 | let object = |t: Option<&Id>| -> Result<Option<Object>> { |
| 596 | match t { |
| 597 | Some(t) => { |
| 598 | let o = src.must(t)?; |
| 599 | if o.kind != Kind::Tree { |
| 600 | return Err(corrupt(format!("{} isn't a tree", t.short()))); |
| 601 | } |
| 602 | Ok(Some(o)) |
| 603 | } |
| 604 | None => Ok(None), |
| 605 | } |
| 606 | }; |
| 607 | let (oa, ob) = (object(a)?, object(b)?); |
| 608 | let empty: &[u8] = &[]; |
| 609 | if let (Some(ea), Some(eb)) = (raw_entries(oa.as_ref().map_or(empty, |o| &o.data))?, raw_entries(ob.as_ref().map_or(empty, |o| &o.data))?) { |
| 610 | return diff_sorted(src, &ea, &eb, prefix, out); |
| 611 | } |
| 612 | diff_unsorted(src, a, b, prefix, out) |
| 613 | } |
| 614 |
| 615 | fn diff_sorted(src: &dyn Source, ea: &[RawEntry<'_>], eb: &[RawEntry<'_>], prefix: &str, out: &mut BTreeMap<String, Change>) -> Result<()> { |
| 616 | let path = |name: &str| if prefix.is_empty() { name.to_string() } else { format!("{prefix}/{name}") }; |
| 617 | let entry = |e: &RawEntry<'_>| Entry { kind: e.kind, id: e.id }; |
| 618 | let (mut i, mut j) = (0, 0); |
| 619 | while i < ea.len() || j < eb.len() { |
| 620 | let order = match (ea.get(i), eb.get(j)) { |
| 621 | (Some(x), Some(y)) => x.name.as_bytes().cmp(y.name.as_bytes()), |
| 622 | (Some(_), None) => std::cmp::Ordering::Less, |
| 623 | _ => std::cmp::Ordering::Greater, |
| 624 | }; |
| 625 | match order { |
| 626 | std::cmp::Ordering::Equal => { |
| 627 | let (x, y) = (&ea[i], &eb[j]); |
| 628 | i += 1; |
| 629 | j += 1; |
| 630 | if x.kind == y.kind && x.id == y.id { |
| 631 | continue; |
| 632 | } |
| 633 | let p = path(x.name); |
| 634 | match (x.kind == EntryKind::Tree, y.kind == EntryKind::Tree) { |
| 635 | (true, true) => diff_into(src, Some(&x.id), Some(&y.id), &p, out)?, |
| 636 | (true, false) => { |
| 637 | diff_into(src, Some(&x.id), None, &p, out)?; |
| 638 | out.insert(p, Change::Added(entry(y))); |
| 639 | } |
| 640 | (false, true) => { |
| 641 | out.insert(p.clone(), Change::Removed(entry(x))); |
| 642 | diff_into(src, None, Some(&y.id), &p, out)?; |
| 643 | } |
| 644 | (false, false) => { |
| 645 | out.insert(p, Change::Modified(entry(x), entry(y))); |
| 646 | } |
| 647 | } |
| 648 | } |
| 649 | std::cmp::Ordering::Less => { |
| 650 | let x = &ea[i]; |
| 651 | i += 1; |
| 652 | let p = path(x.name); |
| 653 | if x.kind == EntryKind::Tree { |
| 654 | diff_into(src, Some(&x.id), None, &p, out)?; |
| 655 | } else { |
| 656 | out.insert(p, Change::Removed(entry(x))); |
| 657 | } |
| 658 | } |
| 659 | std::cmp::Ordering::Greater => { |
| 660 | let y = &eb[j]; |
| 661 | j += 1; |
| 662 | let p = path(y.name); |
| 663 | if y.kind == EntryKind::Tree { |
| 664 | diff_into(src, None, Some(&y.id), &p, out)?; |
| 665 | } else { |
| 666 | out.insert(p, Change::Added(entry(y))); |
| 667 | } |
| 668 | } |
| 669 | } |
| 670 | } |
| 671 | Ok(()) |
| 672 | } |
| 673 |
| 674 | /// The same for trees whose entries aren't in order (not made by `encode`). |
| 675 | fn diff_unsorted(src: &dyn Source, a: Option<&Id>, b: Option<&Id>, prefix: &str, out: &mut BTreeMap<String, Change>) -> Result<()> { |
| 676 | let entries = |t: Option<&Id>| -> Result<BTreeMap<String, TreeEntry>> { |
| 677 | Ok(match t { |
| 678 | Some(t) => read(src, t)?.into_iter().map(|e| (e.name.clone(), e)).collect(), |
| 679 | None => BTreeMap::new(), |
| 680 | }) |
| 681 | }; |
| 682 | let (ea, eb) = (entries(a)?, entries(b)?); |
| 683 | let path = |name: &str| if prefix.is_empty() { name.to_string() } else { format!("{prefix}/{name}") }; |
| 684 | let entry = |e: &TreeEntry| Entry { kind: e.kind, id: e.id }; |
| 685 | for (name, x) in &ea { |
| 686 | let p = path(name); |
| 687 | match eb.get(name) { |
| 688 | Some(y) if x.kind == y.kind && x.id == y.id => {} |
| 689 | Some(y) => match (x.kind == EntryKind::Tree, y.kind == EntryKind::Tree) { |
| 690 | (true, true) => diff_into(src, Some(&x.id), Some(&y.id), &p, out)?, |
| 691 | (true, false) => { |
| 692 | diff_into(src, Some(&x.id), None, &p, out)?; |
| 693 | out.insert(p, Change::Added(entry(y))); |
| 694 | } |
| 695 | (false, true) => { |
| 696 | out.insert(p.clone(), Change::Removed(entry(x))); |
| 697 | diff_into(src, None, Some(&y.id), &p, out)?; |
| 698 | } |
| 699 | (false, false) => { |
| 700 | out.insert(p, Change::Modified(entry(x), entry(y))); |
| 701 | } |
| 702 | }, |
| 703 | None if x.kind == EntryKind::Tree => diff_into(src, Some(&x.id), None, &p, out)?, |
| 704 | None => { |
| 705 | out.insert(p, Change::Removed(entry(x))); |
| 706 | } |
| 707 | } |
| 708 | } |
| 709 | for (name, y) in &eb { |
| 710 | if ea.contains_key(name) { |
| 711 | continue; |
| 712 | } |
| 713 | let p = path(name); |
| 714 | if y.kind == EntryKind::Tree { |
| 715 | diff_into(src, None, Some(&y.id), &p, out)?; |
| 716 | } else { |
| 717 | out.insert(p, Change::Added(entry(y))); |
| 718 | } |
| 719 | } |
| 720 | Ok(()) |
| 721 | } |
| 722 |
| 723 | #[cfg(test)] |
| 724 | mod tests { |
| 725 | use super::*; |
| 726 | use crate::MemSource; |
| 727 |
| 728 | #[test] |
| 729 | fn editing_in_place_matches_decoding() { |
| 730 | let mut seed = 0x2545_f491_4f6c_dd1du64; |
| 731 | let mut next = move |n: usize| { |
| 732 | seed ^= seed << 13; |
| 733 | seed ^= seed >> 7; |
| 734 | seed ^= seed << 17; |
| 735 | (seed % n as u64) as usize |
| 736 | }; |
| 737 | let names = ["a", "b", "b.txt", "c", "dir", "é", "z", "Zed", "src", "x-1"]; |
| 738 | for case in 0..400 { |
| 739 | let mut src = MemSource::default(); |
| 740 | let mut path = |next: &mut dyn FnMut(usize) -> usize| (0..1 + next(3)).map(|_| names[next(names.len())]).collect::<Vec<_>>().join("/"); |
| 741 | let mut files: Files = BTreeMap::new(); |
| 742 | for _ in 0..next(30) { |
| 743 | let p = path(&mut next); |
| 744 | // A file can't be a folder too. |
| 745 | if files.keys().any(|k| k.starts_with(&format!("{p}/")) || p.starts_with(&format!("{k}/"))) { |
| 746 | continue; |
| 747 | } |
| 748 | files.insert(p, Entry { kind: EntryKind::File, id: src.put(Object::blob(format!("{case}").into_bytes())) }); |
| 749 | } |
| 750 | let (root, trees) = build(&files); |
| 751 | for t in trees { |
| 752 | src.put(t); |
| 753 | } |
| 754 | let ops_owned: Vec<(bool, String, Entry)> = (0..1 + next(6)).map(|i| (next(4) == 0, path(&mut next), Entry { kind: EntryKind::File, id: Id::of(1, format!("{case} {i}").as_bytes()) })).collect(); |
| 755 | let ops: Vec<EditOp> = ops_owned.iter().map(|(del, p, e)| if *del { EditOp::Delete(p) } else { EditOp::Put(p, *e) }).collect(); |
| 756 | let (mut a, mut b) = (Vec::new(), Vec::new()); |
| 757 | let (mut ab, mut bb) = (Vec::new(), Vec::new()); |
| 758 | let in_place = edit_dir(&src, Some(&root), &ops, &mut a, &mut ab).unwrap(); |
| 759 | let decoded = edit_dir_decoded(&src, Some(&root), &ops, &mut b, &mut bb).unwrap(); |
| 760 | assert_eq!(in_place, decoded, "case {case}"); |
| 761 | // And both are the tree of the files those edits leave, built whole. |
| 762 | let mut want = files.clone(); |
| 763 | for (del, p, e) in &ops_owned { |
| 764 | want.retain(|q, _| !under(q, p) && (*del || !under(p, q))); |
| 765 | if !*del { |
| 766 | want.insert(p.clone(), *e); |
| 767 | } |
| 768 | } |
| 769 | assert_eq!(in_place, (!want.is_empty()).then(|| build(&want).0), "case {case}"); |
| 770 | assert_eq!(a.iter().map(Object::id).collect::<Vec<_>>(), b.iter().map(Object::id).collect::<Vec<_>>(), "case {case}"); |
| 771 | assert_eq!(ab, bb, "case {case}"); |
| 772 | } |
| 773 | } |
| 774 |
| 775 | #[test] |
| 776 | fn diff_trees_matches_flat_diff() { |
| 777 | let mut src = MemSource::default(); |
| 778 | let mut put = |list: &[(&str, &str, EntryKind)]| -> Id { |
| 779 | let files: Files = list.iter().map(|(p, c, k)| (p.to_string(), Entry { kind: *k, id: src.put(Object::blob(c.as_bytes().to_vec())) })).collect(); |
| 780 | let (root, trees) = build(&files); |
| 781 | for t in trees { |
| 782 | src.put(t); |
| 783 | } |
| 784 | root |
| 785 | }; |
| 786 | let f = EntryKind::File; |
| 787 | let a = put(&[("a.txt", "1", f), ("dir/x", "x", f), ("dir/sub/y", "y", f), ("same/z", "z", f), ("gone/q", "q", f), ("file_then_dir", "f", f), ("run", "r", f)]); |
| 788 | let b = put(&[("a.txt", "2", f), ("dir/x", "x", f), ("dir/sub/y2", "y", f), ("same/z", "z", f), ("new/n", "n", f), ("file_then_dir/inner", "i", f), ("run", "r", EntryKind::Exec)]); |
| 789 | let flat = diff(&flatten(&src, &a).unwrap(), &flatten(&src, &b).unwrap()); |
| 790 | assert_eq!(diff_trees(&src, &a, &b).unwrap(), flat); |
| 791 | assert!(diff_trees(&src, &a, &a).unwrap().is_empty()); |
| 792 | } |
| 793 |
| 794 | #[test] |
| 795 | fn edit_writes_and_deletes() { |
| 796 | let mut src = MemSource::default(); |
| 797 | let files: Files = [("a.txt", "1"), ("dir/x", "x"), ("dir/y", "y"), ("f", "f")] |
| 798 | .iter() |
| 799 | .map(|(p, c)| (p.to_string(), Entry { kind: EntryKind::File, id: src.put(Object::blob(c.as_bytes().to_vec())) })) |
| 800 | .collect(); |
| 801 | let (root, trees) = build(&files); |
| 802 | for t in trees { |
| 803 | src.put(t); |
| 804 | } |
| 805 | let put = vec![ |
| 806 | Put { path: "a.txt".into(), kind: EntryKind::File, content: b"2".to_vec() }, |
| 807 | Put { path: "new/deep/n.sh".into(), kind: EntryKind::Exec, content: b"#!/bin/sh".to_vec() }, |
| 808 | Put { path: "f/inside".into(), kind: EntryKind::File, content: b"i".to_vec() }, |
| 809 | ]; |
| 810 | let (out, objects) = edit(&src, &root, &put, &["dir".to_string()]).unwrap().unwrap(); |
| 811 | for o in objects { |
| 812 | src.put(o); |
| 813 | } |
| 814 | let got = flatten(&src, &out).unwrap(); |
| 815 | assert_eq!(got.keys().cloned().collect::<Vec<_>>(), vec!["a.txt", "f/inside", "new/deep/n.sh"]); |
| 816 | assert_eq!(got["new/deep/n.sh"].kind, EntryKind::Exec); |
| 817 | assert_eq!(edit(&src, &root, &[], &["../x".to_string()]).unwrap().unwrap_err(), "../x"); |
| 818 | } |
| 819 |
| 820 | #[test] |
| 821 | fn unsafe_names() { |
| 822 | for bad in [".git", ".GIT", ".git.", ".git ", "Git~1", ".onset", ".Onset.", "onset~1", ".vcs", ".VCS..", "vcs~1", ".g\u{200c}it", "a\\b", "..", ".", "", "x\0y"] { |
| 823 | assert!(!safe_name(bad), "{bad:?}"); |
| 824 | } |
| 825 | for good in [".github", ".gitignore", "git", "onset.toml", "vcs.toml", "aux.c", "a:b", ".onsetignore", "...x"] { |
| 826 | assert!(safe_name(good), "{good:?}"); |
| 827 | } |
| 828 | assert!(!valid_path("src/.git/hooks/post-checkout")); |
| 829 | assert!(!valid_path("a/.onset/id")); |
| 830 | assert!(!valid_path("a/.vcs/id")); |
| 831 | assert!(valid_path("src/.github/workflows/ci.yml")); |
| 832 |
| 833 | let mut src = MemSource::default(); |
| 834 | let ok = files(&mut src, &[("a.txt", "a"), ("old\\name", "legacy")]); |
| 835 | let (old, trees) = build(&ok); |
| 836 | for t in trees { |
| 837 | src.put(t); |
| 838 | } |
| 839 | let mut worse = ok.clone(); |
| 840 | worse.insert("sub/.git/hooks/post-checkout".into(), Entry { kind: EntryKind::Exec, id: src.put(Object::blob(b"#!/bin/sh\n".to_vec())) }); |
| 841 | let (new, trees) = build(&worse); |
| 842 | for t in trees { |
| 843 | src.put(t); |
| 844 | } |
| 845 | assert_eq!(unsafe_path(&src, &old, &new).unwrap().as_deref(), Some("sub/.git/hooks/post-checkout")); |
| 846 | // A path already there isn't held against a change that leaves it alone. |
| 847 | assert_eq!(unsafe_path(&src, &old, &old).unwrap(), None); |
| 848 | } |
| 849 |
| 850 | /// The same root as editing every file and building the tree again. |
| 851 | #[test] |
| 852 | fn edit_matches_a_full_rebuild() { |
| 853 | let mut src = MemSource::default(); |
| 854 | let base = files(&mut src, &[("a.txt", "a"), ("src/b.rs", "b"), ("src/x/c.rs", "c"), ("src/x/d.rs", "d"), ("docs/x.md", "x"), ("f", "f"), ("lone/only", "o")]); |
| 855 | let (root, trees) = build(&base); |
| 856 | for t in trees { |
| 857 | src.put(t); |
| 858 | } |
| 859 | let p = |path: &str, content: &str| Put { path: path.into(), kind: EntryKind::File, content: content.as_bytes().to_vec() }; |
| 860 | let cases: Vec<(Vec<Put>, Vec<&str>)> = vec![ |
| 861 | (vec![p("src/x/c.rs", "c2")], vec![]), |
| 862 | (vec![p("new/deep/file", "n")], vec![]), |
| 863 | (vec![], vec!["src/x/c.rs", "src/x/d.rs"]), |
| 864 | (vec![], vec!["lone/only"]), |
| 865 | (vec![], vec!["src"]), |
| 866 | (vec![], vec!["nope/missing", "f/inside"]), |
| 867 | (vec![p("f/inside", "i")], vec![]), |
| 868 | (vec![p("src", "now a file")], vec![]), |
| 869 | (vec![p("a.txt", "1"), p("a.txt/b", "2"), p("a.txt", "3")], vec![]), |
| 870 | (vec![p("docs/x.md", "x")], vec![]), |
| 871 | (vec![p("docs/y.md", "y")], vec!["docs"]), |
| 872 | (vec![], vec!["a.txt", "src", "docs", "f", "lone"]), |
| 873 | ]; |
| 874 | for (put, delete) in cases { |
| 875 | let delete: Vec<String> = delete.into_iter().map(String::from).collect(); |
| 876 | let mut want = base.clone(); |
| 877 | for d in &delete { |
| 878 | want.retain(|q, _| !under(q, d)); |
| 879 | } |
| 880 | for x in &put { |
| 881 | want.retain(|q, _| !under(q, &x.path) && !under(&x.path, q)); |
| 882 | want.insert(x.path.clone(), Entry { kind: x.kind, id: Object::blob(x.content.clone()).id() }); |
| 883 | } |
| 884 | let (want_root, _) = build(&want); |
| 885 | let (got, objects) = edit(&src, &root, &put, &delete).unwrap().unwrap(); |
| 886 | assert_eq!(got, want_root, "put {:?} delete {delete:?}", put.iter().map(|x| &x.path).collect::<Vec<_>>()); |
| 887 | let mut after = src.clone(); |
| 888 | for o in objects { |
| 889 | after.put(o); |
| 890 | } |
| 891 | assert_eq!(flatten(&after, &got).unwrap(), want); |
| 892 | } |
| 893 | } |
| 894 |
| 895 | fn files(src: &mut MemSource, list: &[(&str, &str)]) -> Files { |
| 896 | list.iter() |
| 897 | .map(|(p, c)| (p.to_string(), Entry { kind: EntryKind::File, id: src.put(Object::blob(c.as_bytes().to_vec())) })) |
| 898 | .collect() |
| 899 | } |
| 900 |
| 901 | #[test] |
| 902 | fn build_and_flatten() { |
| 903 | let mut src = MemSource::default(); |
| 904 | let f = files(&mut src, &[("a.txt", "a"), ("src/b.rs", "b"), ("src/x/c.rs", "c"), ("src.rs", "d")]); |
| 905 | let (root, trees) = build(&f); |
| 906 | for t in trees { |
| 907 | src.put(t); |
| 908 | } |
| 909 | assert_eq!(flatten(&src, &root).unwrap(), f); |
| 910 | let (empty, _) = build(&Files::new()); |
| 911 | assert_eq!(empty, empty_id()); |
| 912 | } |
| 913 |
| 914 | #[test] |
| 915 | fn new_objects_only() { |
| 916 | let mut src = MemSource::default(); |
| 917 | let a = files(&mut src, &[("a.txt", "a"), ("src/b.rs", "b"), ("docs/x.md", "x")]); |
| 918 | let (ra, ta) = build(&a); |
| 919 | for t in ta { |
| 920 | src.put(t); |
| 921 | } |
| 922 | let mut b = a.clone(); |
| 923 | b.insert("src/b.rs".into(), Entry { kind: EntryKind::File, id: src.put(Object::blob(b"b2".to_vec())) }); |
| 924 | let (rb, tb) = build(&b); |
| 925 | for t in tb { |
| 926 | src.put(t); |
| 927 | } |
| 928 | let mut out = Vec::new(); |
| 929 | new_since(&src, Some(&ra), &rb, &mut out).unwrap(); |
| 930 | // The root, src/ and the new blob; docs/ and a.txt are shared. |
| 931 | assert_eq!(out.len(), 3); |
| 932 | } |
| 933 |
| 934 | #[test] |
| 935 | fn under_paths() { |
| 936 | assert!(under("src/a.rs", "src")); |
| 937 | assert!(under("src", "src")); |
| 938 | assert!(!under("srcx/a.rs", "src")); |
| 939 | assert!(under("anything", "")); |
| 940 | } |
| 941 | } |
| 942 |