//! 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, /// A git submodule: its content is the commit it points at (40 hex digits). Gitlink = 5, } 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), 5 => Some(EntryKind::Gitlink), _ => None, } } pub fn name(self) -> &'static str { match self { EntryKind::File => "file", EntryKind::Exec => "exec", EntryKind::Link => "link", EntryKind::Tree => "tree", EntryKind::Gitlink => "submodule", } } } /// 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) } /// The entry at `path` under `root` (None: not there), reading only the /// folders on the path. The root itself is a folder. pub fn lookup(src: &dyn Source, root: &Id, path: &str) -> Result> { let mut at = Entry { kind: EntryKind::Tree, id: *root }; for part in path.split('/').filter(|p| !p.is_empty()) { if at.kind != EntryKind::Tree { return Ok(None); } match read(src, &at.id)?.into_iter().find(|e| e.name == part) { Some(e) => at = Entry { kind: e.kind, id: e.id }, None => return Ok(None), } } Ok(Some(at)) } /// 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, every part a [`safe_name`]. pub fn valid_path(path: &str) -> bool { !path.is_empty() && path.split('/').all(safe_name) } /// Whether one part of a path is safe on every system. Not empty, `.` or /// `..`; no backslash (a separator on Windows) or NUL; and not Onset's /// (`.onset`, or `.vcs` from before it had its name) or git's own folder in /// any spelling some disk treats as the same (`.GIT`, /// `.git.`, `git~1`, or with characters macOS ignores), since a project /// holding `.git/hooks/...` would run code in the folders it's written to. pub fn safe_name(name: &str) -> bool { if name.is_empty() || name == "." || name == ".." || name.len() > u16::MAX as usize || name.contains(['\\', '\0']) { return false; } let plain: String = name .chars() .filter(|c| !matches!(*c as u32, 0x200C..=0x200F | 0x202A..=0x202E | 0x206A..=0x206F | 0xFEFF)) .collect::() .trim_end_matches(['.', ' ']) .to_ascii_lowercase(); !matches!(plain.as_str(), ".git" | ".onset" | ".vcs" | "git~1" | "onset~1" | "vcs~1") } /// The first path `new` adds or changes over `old` that isn't a /// [`valid_path`], if any. Paths already there aren't looked at again. pub fn unsafe_path(src: &dyn Source, old: &Id, new: &Id) -> Result> { Ok(diff_trees(src, old, new)?.into_iter().find(|(p, c)| !matches!(c, Change::Removed(_)) && !valid_path(p)).map(|(p, _)| p)) } /// `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 objects = Vec::new(); let mut ops: Vec = delete.iter().map(|d| EditOp::Delete(d)).collect(); for p in put { let parts = crate::chunk::file_objects(&p.content); ops.push(EditOp::Put(&p.path, Entry { kind: p.kind, id: parts[0].id() })); objects.extend(parts); } // Only the folders on the edited paths are read and written again. let root = match edit_dir(src, Some(tree), &ops, &mut objects)? { Some(root) => root, None => { let empty = empty(); let id = empty.id(); objects.push(empty); id } }; Ok(Ok((root, objects))) } /// An edit, with its path relative to the folder it's applied in. Deletes /// come first, then writes in order. #[derive(Clone, Copy)] enum EditOp<'a> { Put(&'a str, Entry), Delete(&'a str), } /// `tree` (None: a new folder) with `ops` applied; None when nothing's left /// in it. A file and a folder can't share a path, so writing one replaces /// the other. fn edit_dir(src: &dyn Source, tree: Option<&Id>, ops: &[EditOp], objects: &mut Vec) -> Result> { enum Child<'a> { Gone, File(Entry), Dir(Option, Vec>), } let mut entries: BTreeMap = match tree { Some(t) => read(src, t)?.into_iter().map(|e| (e.name, Entry { kind: e.kind, id: e.id })).collect(), None => BTreeMap::new(), }; let mut touched: BTreeMap<&str, Child> = BTreeMap::new(); for op in ops { let path = match op { EditOp::Put(p, _) | EditOp::Delete(p) => *p, }; let (name, rest) = match path.split_once('/') { Some((name, rest)) => (name, Some(rest)), None => (path, None), }; let child = touched.entry(name).or_insert_with(|| match entries.get(name) { Some(e) if e.kind == EntryKind::Tree => Child::Dir(Some(e.id), Vec::new()), Some(e) => Child::File(*e), None => Child::Gone, }); match (op, rest) { (EditOp::Delete(_), None) => *child = Child::Gone, (EditOp::Delete(_), Some(rest)) => { if let Child::Dir(_, inner) = child { inner.push(EditOp::Delete(rest)); } } (EditOp::Put(_, e), None) => *child = Child::File(*e), (EditOp::Put(_, e), Some(rest)) => { if !matches!(child, Child::Dir(..)) { *child = Child::Dir(None, Vec::new()); } if let Child::Dir(_, inner) = child { inner.push(EditOp::Put(rest, *e)); } } } } let mut changed = false; for (name, child) in touched { let next = match child { Child::Gone => None, Child::File(e) => Some(e), Child::Dir(base, inner) if inner.is_empty() => base.map(|id| Entry { kind: EntryKind::Tree, id }), Child::Dir(base, inner) => edit_dir(src, base.as_ref(), &inner, objects)?.map(|id| Entry { kind: EntryKind::Tree, id }), }; if entries.get(name) != next.as_ref() { changed = true; match next { Some(e) => entries.insert(name.to_string(), e), None => entries.remove(name), }; } } if !changed && tree.is_some() { return Ok(tree.copied()); } if entries.is_empty() { return Ok(None); } let list: Vec = entries.into_iter().map(|(name, e)| TreeEntry { name, kind: e.kind, id: e.id }).collect(); let object = Object::new(Kind::Tree, encode(&list)); let id = object.id(); objects.push(object); Ok(Some(id)) } /// 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"); } #[test] fn unsafe_names() { 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"] { assert!(!safe_name(bad), "{bad:?}"); } for good in [".github", ".gitignore", "git", "onset.toml", "vcs.toml", "aux.c", "a:b", ".onsetignore", "...x"] { assert!(safe_name(good), "{good:?}"); } assert!(!valid_path("src/.git/hooks/post-checkout")); assert!(!valid_path("a/.onset/id")); assert!(!valid_path("a/.vcs/id")); assert!(valid_path("src/.github/workflows/ci.yml")); let mut src = MemSource::default(); let ok = files(&mut src, &[("a.txt", "a"), ("old\\name", "legacy")]); let (old, trees) = build(&ok); for t in trees { src.put(t); } let mut worse = ok.clone(); worse.insert("sub/.git/hooks/post-checkout".into(), Entry { kind: EntryKind::Exec, id: src.put(Object::blob(b"#!/bin/sh\n".to_vec())) }); let (new, trees) = build(&worse); for t in trees { src.put(t); } assert_eq!(unsafe_path(&src, &old, &new).unwrap().as_deref(), Some("sub/.git/hooks/post-checkout")); // A path already there isn't held against a change that leaves it alone. assert_eq!(unsafe_path(&src, &old, &old).unwrap(), None); } /// The same root as editing every file and building the tree again. #[test] fn edit_matches_a_full_rebuild() { let mut src = MemSource::default(); 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")]); let (root, trees) = build(&base); for t in trees { src.put(t); } let p = |path: &str, content: &str| Put { path: path.into(), kind: EntryKind::File, content: content.as_bytes().to_vec() }; let cases: Vec<(Vec, Vec<&str>)> = vec![ (vec![p("src/x/c.rs", "c2")], vec![]), (vec![p("new/deep/file", "n")], vec![]), (vec![], vec!["src/x/c.rs", "src/x/d.rs"]), (vec![], vec!["lone/only"]), (vec![], vec!["src"]), (vec![], vec!["nope/missing", "f/inside"]), (vec![p("f/inside", "i")], vec![]), (vec![p("src", "now a file")], vec![]), (vec![p("a.txt", "1"), p("a.txt/b", "2"), p("a.txt", "3")], vec![]), (vec![p("docs/x.md", "x")], vec![]), (vec![p("docs/y.md", "y")], vec!["docs"]), (vec![], vec!["a.txt", "src", "docs", "f", "lone"]), ]; for (put, delete) in cases { let delete: Vec = delete.into_iter().map(String::from).collect(); let mut want = base.clone(); for d in &delete { want.retain(|q, _| !under(q, d)); } for x in &put { want.retain(|q, _| !under(q, &x.path) && !under(&x.path, q)); want.insert(x.path.clone(), Entry { kind: x.kind, id: Object::blob(x.content.clone()).id() }); } let (want_root, _) = build(&want); let (got, objects) = edit(&src, &root, &put, &delete).unwrap().unwrap(); assert_eq!(got, want_root, "put {:?} delete {delete:?}", put.iter().map(|x| &x.path).collect::>()); let mut after = src.clone(); for o in objects { after.put(o); } assert_eq!(flatten(&after, &got).unwrap(), want); } } 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", "")); } }