//! Trees: sorted directory listings. A flattened tree ([`Files`]) maps //! `a/b/c.txt` paths to file entries. use std::collections::{BTreeMap, HashMap}; use crate::object::{Kind, Object}; use crate::{Id, Result, Source, corrupt}; #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)] #[repr(u8)] pub enum EntryKind { File = 1, Exec = 2, Link = 3, Tree = 4, } impl EntryKind { pub fn from_u8(b: u8) -> Option { match b { 1 => Some(EntryKind::File), 2 => Some(EntryKind::Exec), 3 => Some(EntryKind::Link), 4 => Some(EntryKind::Tree), _ => None, } } pub fn name(self) -> &'static str { match self { EntryKind::File => "file", EntryKind::Exec => "exec", EntryKind::Link => "link", EntryKind::Tree => "tree", } } } /// A file in a flattened tree. `id` names a blob or, for big files, a chunk list. #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] pub struct Entry { pub kind: EntryKind, pub id: Id, } pub type Files = BTreeMap; #[derive(Debug, Clone, PartialEq, Eq)] pub struct TreeEntry { pub name: String, pub kind: EntryKind, pub id: Id, } pub fn encode(entries: &[TreeEntry]) -> Vec { let mut sorted: Vec<&TreeEntry> = entries.iter().collect(); sorted.sort_by(|a, b| a.name.as_bytes().cmp(b.name.as_bytes())); let mut out = Vec::with_capacity(entries.len() * 48); for e in sorted { out.push(e.kind as u8); out.extend_from_slice(&(e.name.len() as u16).to_le_bytes()); out.extend_from_slice(e.name.as_bytes()); out.extend_from_slice(&e.id.0); } out } pub fn decode(data: &[u8]) -> Result> { let mut out = Vec::new(); let mut at = 0; while at < data.len() { let kind = EntryKind::from_u8(data[at]).ok_or_else(|| corrupt("bad tree entry kind"))?; let len = u16::from_le_bytes(data.get(at + 1..at + 3).ok_or_else(|| corrupt("short tree"))?.try_into().unwrap()) as usize; let name_end = at + 3 + len; 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"))? .to_string(); if name.is_empty() || name.contains('/') || name == "." || name == ".." { return Err(corrupt("bad name in tree")); } let id = Id::from_slice(data.get(name_end..name_end + 32).ok_or_else(|| corrupt("short tree"))?).unwrap(); out.push(TreeEntry { name, kind, id }); at = name_end + 32; } Ok(out) } pub fn empty() -> Object { Object::new(Kind::Tree, Vec::new()) } pub fn empty_id() -> Id { empty().id() } pub fn read(src: &dyn Source, id: &Id) -> Result> { let object = src.must(id)?; if object.kind != Kind::Tree { return Err(corrupt(format!("{} isn't a tree", id.short()))); } decode(&object.data) } /// Every file under `tree`. pub fn flatten(src: &dyn Source, tree: &Id) -> Result { let mut out = Files::new(); walk(src, tree, "", &mut out)?; Ok(out) } fn walk(src: &dyn Source, tree: &Id, prefix: &str, out: &mut Files) -> Result<()> { for e in read(src, tree)? { let path = if prefix.is_empty() { e.name.clone() } else { format!("{prefix}/{}", e.name) }; if e.kind == EntryKind::Tree { walk(src, &e.id, &path, out)?; } else { out.insert(path, Entry { kind: e.kind, id: e.id }); } } Ok(()) } /// Every object ID a tree reaches (the trees themselves, file blobs and /// chunk lists, not the chunks inside chunk lists). pub fn reachable(src: &dyn Source, tree: &Id, out: &mut Vec) -> Result<()> { out.push(*tree); for e in read(src, tree)? { if e.kind == EntryKind::Tree { reachable(src, &e.id, out)?; } else { out.push(e.id); } } Ok(()) } /// Trees reached from `new` but not from `old`, walking only subtrees that /// differ, plus the file IDs those subtrees hold that `old` doesn't have at /// the same path. pub fn new_since(src: &dyn Source, old: Option<&Id>, new: &Id, out: &mut Vec) -> Result<()> { if Some(new) == old { return Ok(()); } out.push(*new); let old_entries: HashMap = match old { Some(o) => read(src, o)?.into_iter().map(|e| (e.name.clone(), e)).collect(), None => HashMap::new(), }; for e in read(src, new)? { let before = old_entries.get(&e.name); if before.is_some_and(|b| b.id == e.id) { continue; } if e.kind == EntryKind::Tree { let old_sub = before.filter(|b| b.kind == EntryKind::Tree).map(|b| b.id); new_since(src, old_sub.as_ref(), &e.id, out)?; } else { out.push(e.id); } } Ok(()) } /// Builds tree objects for `files`. Returns the root ID and every tree /// object (the host stores the ones it doesn't have). pub fn build(files: &Files) -> (Id, Vec) { let mut dirs: HashMap<&str, Vec> = HashMap::new(); let mut subdirs: HashMap<&str, Vec<&str>> = HashMap::new(); dirs.entry("").or_default(); for (path, entry) in files { let (dir, name) = split(path); dirs.entry(dir).or_default().push(TreeEntry { name: name.to_string(), kind: entry.kind, id: entry.id }); let mut d = dir; while !d.is_empty() { let (parent, _) = split(d); let known = subdirs.entry(parent).or_default(); if known.contains(&d) { break; } known.push(d); dirs.entry(d).or_default(); d = parent; } } let mut order: Vec<&str> = dirs.keys().copied().collect(); order.sort_by_key(|d| std::cmp::Reverse(if d.is_empty() { 0 } else { d.matches('/').count() + 1 })); let mut written: HashMap<&str, Id> = HashMap::with_capacity(order.len()); let mut objects = Vec::with_capacity(order.len()); for dir in order { let mut entries = dirs.remove(dir).unwrap_or_default(); for child in subdirs.get(dir).map(Vec::as_slice).unwrap_or(&[]) { entries.push(TreeEntry { name: split(child).1.to_string(), kind: EntryKind::Tree, id: written[child] }); } let object = Object::new(Kind::Tree, encode(&entries)); let id = object.id(); objects.push(object); written.insert(dir, id); } (written[""], objects) } /// "a/b/c" → ("a/b", "c"); "c" → ("", "c"). pub fn split(path: &str) -> (&str, &str) { match path.rfind('/') { Some(i) => (&path[..i], &path[i + 1..]), None => ("", path), } } /// Whether `path` is `prefix` or inside it. pub fn under(path: &str, prefix: &str) -> bool { prefix.is_empty() || path == prefix || (path.starts_with(prefix) && path.as_bytes().get(prefix.len()) == Some(&b'/')) } #[derive(Debug, Clone, PartialEq, Eq)] pub enum Change { Added(Entry), Removed(Entry), Modified(Entry, Entry), } /// What changed from `a` to `b`, by path. pub fn diff(a: &Files, b: &Files) -> BTreeMap { let mut out = BTreeMap::new(); for (path, old) in a { match b.get(path) { None => { out.insert(path.clone(), Change::Removed(*old)); } Some(new) if new != old => { out.insert(path.clone(), Change::Modified(*old, *new)); } _ => {} } } for (path, new) in b { if !a.contains_key(path) { out.insert(path.clone(), Change::Added(*new)); } } out } /// A file to write into a tree: its path, kind and content. pub struct Put { pub path: String, pub kind: EntryKind, pub content: Vec, } /// Whether `path` can name a file: relative, with no empty, `.` or `..` /// parts, and no NUL. pub fn valid_path(path: &str) -> bool { !path.is_empty() && !path.contains('\0') && path.split('/').all(|p| !p.is_empty() && p != "." && p != ".." && p.len() <= u16::MAX as usize) } /// `tree` with files written and deleted. Writing a path replaces whatever /// was there (a folder of that name included); deleting a folder deletes /// what's in it. Returns the new root and every object it needs that's new /// (file contents, big files' chunks and trees). pub fn edit(src: &dyn Source, tree: &Id, put: &[Put], delete: &[String]) -> Result), String>> { if let Some(bad) = put.iter().map(|p| p.path.as_str()).chain(delete.iter().map(String::as_str)).find(|p| !valid_path(p)) { return Ok(Err(bad.to_string())); } let mut files = flatten(src, tree)?; for d in delete { files.retain(|p, _| !under(p, d)); } let mut objects = Vec::new(); for p in put { // A file and a folder can't share a path. files.retain(|q, _| !under(q, &p.path) && !under(&p.path, q)); let parts = crate::chunk::file_objects(&p.content); files.insert(p.path.clone(), Entry { kind: p.kind, id: parts[0].id() }); objects.extend(parts); } let (root, trees) = build(&files); objects.extend(trees); Ok(Ok((root, objects))) } /// What changed from tree `a` to tree `b`, by path, reading only the /// folders that differ (the same answer as `diff` on both flattened). pub fn diff_trees(src: &dyn Source, a: &Id, b: &Id) -> Result> { let mut out = BTreeMap::new(); diff_into(src, Some(a), Some(b), "", &mut out)?; Ok(out) } fn diff_into(src: &dyn Source, a: Option<&Id>, b: Option<&Id>, prefix: &str, out: &mut BTreeMap) -> Result<()> { if a == b { return Ok(()); } let entries = |t: Option<&Id>| -> Result> { Ok(match t { Some(t) => read(src, t)?.into_iter().map(|e| (e.name.clone(), e)).collect(), None => BTreeMap::new(), }) }; let (ea, eb) = (entries(a)?, entries(b)?); let path = |name: &str| if prefix.is_empty() { name.to_string() } else { format!("{prefix}/{name}") }; let entry = |e: &TreeEntry| Entry { kind: e.kind, id: e.id }; for (name, x) in &ea { let p = path(name); match eb.get(name) { Some(y) if x.kind == y.kind && x.id == y.id => {} Some(y) => match (x.kind == EntryKind::Tree, y.kind == EntryKind::Tree) { (true, true) => diff_into(src, Some(&x.id), Some(&y.id), &p, out)?, (true, false) => { diff_into(src, Some(&x.id), None, &p, out)?; out.insert(p, Change::Added(entry(y))); } (false, true) => { out.insert(p.clone(), Change::Removed(entry(x))); diff_into(src, None, Some(&y.id), &p, out)?; } (false, false) => { out.insert(p, Change::Modified(entry(x), entry(y))); } }, None if x.kind == EntryKind::Tree => diff_into(src, Some(&x.id), None, &p, out)?, None => { out.insert(p, Change::Removed(entry(x))); } } } for (name, y) in &eb { if ea.contains_key(name) { continue; } let p = path(name); if y.kind == EntryKind::Tree { diff_into(src, None, Some(&y.id), &p, out)?; } else { out.insert(p, Change::Added(entry(y))); } } Ok(()) } #[cfg(test)] mod tests { use super::*; use crate::MemSource; #[test] fn diff_trees_matches_flat_diff() { let mut src = MemSource::default(); let mut put = |list: &[(&str, &str, EntryKind)]| -> Id { 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(); let (root, trees) = build(&files); for t in trees { src.put(t); } root }; let f = EntryKind::File; 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)]); 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)]); let flat = diff(&flatten(&src, &a).unwrap(), &flatten(&src, &b).unwrap()); assert_eq!(diff_trees(&src, &a, &b).unwrap(), flat); assert!(diff_trees(&src, &a, &a).unwrap().is_empty()); } #[test] fn edit_writes_and_deletes() { let mut src = MemSource::default(); let files: Files = [("a.txt", "1"), ("dir/x", "x"), ("dir/y", "y"), ("f", "f")] .iter() .map(|(p, c)| (p.to_string(), Entry { kind: EntryKind::File, id: src.put(Object::blob(c.as_bytes().to_vec())) })) .collect(); let (root, trees) = build(&files); for t in trees { src.put(t); } let put = vec![ Put { path: "a.txt".into(), kind: EntryKind::File, content: b"2".to_vec() }, Put { path: "new/deep/n.sh".into(), kind: EntryKind::Exec, content: b"#!/bin/sh".to_vec() }, Put { path: "f/inside".into(), kind: EntryKind::File, content: b"i".to_vec() }, ]; let (out, objects) = edit(&src, &root, &put, &["dir".to_string()]).unwrap().unwrap(); for o in objects { src.put(o); } let got = flatten(&src, &out).unwrap(); assert_eq!(got.keys().cloned().collect::>(), vec!["a.txt", "f/inside", "new/deep/n.sh"]); assert_eq!(got["new/deep/n.sh"].kind, EntryKind::Exec); assert_eq!(edit(&src, &root, &[], &["../x".to_string()]).unwrap().unwrap_err(), "../x"); } fn files(src: &mut MemSource, list: &[(&str, &str)]) -> Files { list.iter() .map(|(p, c)| (p.to_string(), Entry { kind: EntryKind::File, id: src.put(Object::blob(c.as_bytes().to_vec())) })) .collect() } #[test] fn build_and_flatten() { let mut src = MemSource::default(); let f = files(&mut src, &[("a.txt", "a"), ("src/b.rs", "b"), ("src/x/c.rs", "c"), ("src.rs", "d")]); let (root, trees) = build(&f); for t in trees { src.put(t); } assert_eq!(flatten(&src, &root).unwrap(), f); let (empty, _) = build(&Files::new()); assert_eq!(empty, empty_id()); } #[test] fn new_objects_only() { let mut src = MemSource::default(); let a = files(&mut src, &[("a.txt", "a"), ("src/b.rs", "b"), ("docs/x.md", "x")]); let (ra, ta) = build(&a); for t in ta { src.put(t); } let mut b = a.clone(); b.insert("src/b.rs".into(), Entry { kind: EntryKind::File, id: src.put(Object::blob(b"b2".to_vec())) }); let (rb, tb) = build(&b); for t in tb { src.put(t); } let mut out = Vec::new(); new_since(&src, Some(&ra), &rb, &mut out).unwrap(); // The root, src/ and the new blob; docs/ and a.txt are shared. assert_eq!(out.len(), 3); } #[test] fn under_paths() { assert!(under("src/a.rs", "src")); assert!(under("src", "src")); assert!(!under("srcx/a.rs", "src")); assert!(under("anything", "")); } }