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 | /// Every file under `tree`. |
| 109 | pub fn flatten(src: &dyn Source, tree: &Id) -> Result<Files> { |
| 110 | let mut out = Files::new(); |
| 111 | walk(src, tree, "", &mut out)?; |
| 112 | Ok(out) |
| 113 | } |
| 114 |
| 115 | fn walk(src: &dyn Source, tree: &Id, prefix: &str, out: &mut Files) -> Result<()> { |
| 116 | for e in read(src, tree)? { |
| 117 | let path = if prefix.is_empty() { e.name.clone() } else { format!("{prefix}/{}", e.name) }; |
| 118 | if e.kind == EntryKind::Tree { |
| 119 | walk(src, &e.id, &path, out)?; |
| 120 | } else { |
| 121 | out.insert(path, Entry { kind: e.kind, id: e.id }); |
| 122 | } |
| 123 | } |
| 124 | Ok(()) |
| 125 | } |
| 126 |
| 127 | /// Every object ID a tree reaches (the trees themselves, file blobs and |
| 128 | /// chunk lists, not the chunks inside chunk lists). |
| 129 | pub fn reachable(src: &dyn Source, tree: &Id, out: &mut Vec<Id>) -> Result<()> { |
| 130 | out.push(*tree); |
| 131 | for e in read(src, tree)? { |
| 132 | if e.kind == EntryKind::Tree { |
| 133 | reachable(src, &e.id, out)?; |
| 134 | } else { |
| 135 | out.push(e.id); |
| 136 | } |
| 137 | } |
| 138 | Ok(()) |
| 139 | } |
| 140 |
| 141 | /// Trees reached from `new` but not from `old`, walking only subtrees that |
| 142 | /// differ, plus the file IDs those subtrees hold that `old` doesn't have at |
| 143 | /// the same path. |
| 144 | pub fn new_since(src: &dyn Source, old: Option<&Id>, new: &Id, out: &mut Vec<Id>) -> Result<()> { |
| 145 | if Some(new) == old { |
| 146 | return Ok(()); |
| 147 | } |
| 148 | out.push(*new); |
| 149 | let old_entries: HashMap<String, TreeEntry> = match old { |
| 150 | Some(o) => read(src, o)?.into_iter().map(|e| (e.name.clone(), e)).collect(), |
| 151 | None => HashMap::new(), |
| 152 | }; |
| 153 | for e in read(src, new)? { |
| 154 | let before = old_entries.get(&e.name); |
| 155 | if before.is_some_and(|b| b.id == e.id) { |
| 156 | continue; |
| 157 | } |
| 158 | if e.kind == EntryKind::Tree { |
| 159 | let old_sub = before.filter(|b| b.kind == EntryKind::Tree).map(|b| b.id); |
| 160 | new_since(src, old_sub.as_ref(), &e.id, out)?; |
| 161 | } else { |
| 162 | out.push(e.id); |
| 163 | } |
| 164 | } |
| 165 | Ok(()) |
| 166 | } |
| 167 |
| 168 | /// Builds tree objects for `files`. Returns the root ID and every tree |
| 169 | /// object (the host stores the ones it doesn't have). |
| 170 | pub fn build(files: &Files) -> (Id, Vec<Object>) { |
| 171 | let mut dirs: HashMap<&str, Vec<TreeEntry>> = HashMap::new(); |
| 172 | let mut subdirs: HashMap<&str, Vec<&str>> = HashMap::new(); |
| 173 | dirs.entry("").or_default(); |
| 174 | for (path, entry) in files { |
| 175 | let (dir, name) = split(path); |
| 176 | dirs.entry(dir).or_default().push(TreeEntry { name: name.to_string(), kind: entry.kind, id: entry.id }); |
| 177 | let mut d = dir; |
| 178 | while !d.is_empty() { |
| 179 | let (parent, _) = split(d); |
| 180 | let known = subdirs.entry(parent).or_default(); |
| 181 | if known.contains(&d) { |
| 182 | break; |
| 183 | } |
| 184 | known.push(d); |
| 185 | dirs.entry(d).or_default(); |
| 186 | d = parent; |
| 187 | } |
| 188 | } |
| 189 | let mut order: Vec<&str> = dirs.keys().copied().collect(); |
| 190 | order.sort_by_key(|d| std::cmp::Reverse(if d.is_empty() { 0 } else { d.matches('/').count() + 1 })); |
| 191 | let mut written: HashMap<&str, Id> = HashMap::with_capacity(order.len()); |
| 192 | let mut objects = Vec::with_capacity(order.len()); |
| 193 | for dir in order { |
| 194 | let mut entries = dirs.remove(dir).unwrap_or_default(); |
| 195 | for child in subdirs.get(dir).map(Vec::as_slice).unwrap_or(&[]) { |
| 196 | entries.push(TreeEntry { name: split(child).1.to_string(), kind: EntryKind::Tree, id: written[child] }); |
| 197 | } |
| 198 | let object = Object::new(Kind::Tree, encode(&entries)); |
| 199 | let id = object.id(); |
| 200 | objects.push(object); |
| 201 | written.insert(dir, id); |
| 202 | } |
| 203 | (written[""], objects) |
| 204 | } |
| 205 |
| 206 | /// "a/b/c" → ("a/b", "c"); "c" → ("", "c"). |
| 207 | pub fn split(path: &str) -> (&str, &str) { |
| 208 | match path.rfind('/') { |
| 209 | Some(i) => (&path[..i], &path[i + 1..]), |
| 210 | None => ("", path), |
| 211 | } |
| 212 | } |
| 213 |
| 214 | /// Whether `path` is `prefix` or inside it. |
| 215 | pub fn under(path: &str, prefix: &str) -> bool { |
| 216 | prefix.is_empty() || path == prefix || (path.starts_with(prefix) && path.as_bytes().get(prefix.len()) == Some(&b'/')) |
| 217 | } |
| 218 |
| 219 | #[derive(Debug, Clone, PartialEq, Eq)] |
| 220 | pub enum Change { |
| 221 | Added(Entry), |
| 222 | Removed(Entry), |
| 223 | Modified(Entry, Entry), |
| 224 | } |
| 225 |
| 226 | /// What changed from `a` to `b`, by path. |
| 227 | pub fn diff(a: &Files, b: &Files) -> BTreeMap<String, Change> { |
| 228 | let mut out = BTreeMap::new(); |
| 229 | for (path, old) in a { |
| 230 | match b.get(path) { |
| 231 | None => { |
| 232 | out.insert(path.clone(), Change::Removed(*old)); |
| 233 | } |
| 234 | Some(new) if new != old => { |
| 235 | out.insert(path.clone(), Change::Modified(*old, *new)); |
| 236 | } |
| 237 | _ => {} |
| 238 | } |
| 239 | } |
| 240 | for (path, new) in b { |
| 241 | if !a.contains_key(path) { |
| 242 | out.insert(path.clone(), Change::Added(*new)); |
| 243 | } |
| 244 | } |
| 245 | out |
| 246 | } |
| 247 |
| 248 | /// A file to write into a tree: its path, kind and content. |
| 249 | pub struct Put { |
| 250 | pub path: String, |
| 251 | pub kind: EntryKind, |
| 252 | pub content: Vec<u8>, |
| 253 | } |
| 254 |
| 255 | /// Whether `path` can name a file: relative, with no empty, `.` or `..` |
| 256 | /// parts, and no NUL. |
| 257 | pub fn valid_path(path: &str) -> bool { |
| 258 | !path.is_empty() && !path.contains('\0') && path.split('/').all(|p| !p.is_empty() && p != "." && p != ".." && p.len() <= u16::MAX as usize) |
| 259 | } |
| 260 |
| 261 | /// `tree` with files written and deleted. Writing a path replaces whatever |
| 262 | /// was there (a folder of that name included); deleting a folder deletes |
| 263 | /// what's in it. Returns the new root and every object it needs that's new |
| 264 | /// (file contents, big files' chunks and trees). |
| 265 | pub fn edit(src: &dyn Source, tree: &Id, put: &[Put], delete: &[String]) -> Result<std::result::Result<(Id, Vec<Object>), String>> { |
| 266 | if let Some(bad) = put.iter().map(|p| p.path.as_str()).chain(delete.iter().map(String::as_str)).find(|p| !valid_path(p)) { |
| 267 | return Ok(Err(bad.to_string())); |
| 268 | } |
| 269 | let mut files = flatten(src, tree)?; |
| 270 | for d in delete { |
| 271 | files.retain(|p, _| !under(p, d)); |
| 272 | } |
| 273 | let mut objects = Vec::new(); |
| 274 | for p in put { |
| 275 | // A file and a folder can't share a path. |
| 276 | files.retain(|q, _| !under(q, &p.path) && !under(&p.path, q)); |
| 277 | let parts = crate::chunk::file_objects(&p.content); |
| 278 | files.insert(p.path.clone(), Entry { kind: p.kind, id: parts[0].id() }); |
| 279 | objects.extend(parts); |
| 280 | } |
| 281 | let (root, trees) = build(&files); |
| 282 | objects.extend(trees); |
| 283 | Ok(Ok((root, objects))) |
| 284 | } |
| 285 |
| 286 | /// What changed from tree `a` to tree `b`, by path, reading only the |
| 287 | /// folders that differ (the same answer as `diff` on both flattened). |
| 288 | pub fn diff_trees(src: &dyn Source, a: &Id, b: &Id) -> Result<BTreeMap<String, Change>> { |
| 289 | let mut out = BTreeMap::new(); |
| 290 | diff_into(src, Some(a), Some(b), "", &mut out)?; |
| 291 | Ok(out) |
| 292 | } |
| 293 |
| 294 | fn diff_into(src: &dyn Source, a: Option<&Id>, b: Option<&Id>, prefix: &str, out: &mut BTreeMap<String, Change>) -> Result<()> { |
| 295 | if a == b { |
| 296 | return Ok(()); |
| 297 | } |
| 298 | let entries = |t: Option<&Id>| -> Result<BTreeMap<String, TreeEntry>> { |
| 299 | Ok(match t { |
| 300 | Some(t) => read(src, t)?.into_iter().map(|e| (e.name.clone(), e)).collect(), |
| 301 | None => BTreeMap::new(), |
| 302 | }) |
| 303 | }; |
| 304 | let (ea, eb) = (entries(a)?, entries(b)?); |
| 305 | let path = |name: &str| if prefix.is_empty() { name.to_string() } else { format!("{prefix}/{name}") }; |
| 306 | let entry = |e: &TreeEntry| Entry { kind: e.kind, id: e.id }; |
| 307 | for (name, x) in &ea { |
| 308 | let p = path(name); |
| 309 | match eb.get(name) { |
| 310 | Some(y) if x.kind == y.kind && x.id == y.id => {} |
| 311 | Some(y) => match (x.kind == EntryKind::Tree, y.kind == EntryKind::Tree) { |
| 312 | (true, true) => diff_into(src, Some(&x.id), Some(&y.id), &p, out)?, |
| 313 | (true, false) => { |
| 314 | diff_into(src, Some(&x.id), None, &p, out)?; |
| 315 | out.insert(p, Change::Added(entry(y))); |
| 316 | } |
| 317 | (false, true) => { |
| 318 | out.insert(p.clone(), Change::Removed(entry(x))); |
| 319 | diff_into(src, None, Some(&y.id), &p, out)?; |
| 320 | } |
| 321 | (false, false) => { |
| 322 | out.insert(p, Change::Modified(entry(x), entry(y))); |
| 323 | } |
| 324 | }, |
| 325 | None if x.kind == EntryKind::Tree => diff_into(src, Some(&x.id), None, &p, out)?, |
| 326 | None => { |
| 327 | out.insert(p, Change::Removed(entry(x))); |
| 328 | } |
| 329 | } |
| 330 | } |
| 331 | for (name, y) in &eb { |
| 332 | if ea.contains_key(name) { |
| 333 | continue; |
| 334 | } |
| 335 | let p = path(name); |
| 336 | if y.kind == EntryKind::Tree { |
| 337 | diff_into(src, None, Some(&y.id), &p, out)?; |
| 338 | } else { |
| 339 | out.insert(p, Change::Added(entry(y))); |
| 340 | } |
| 341 | } |
| 342 | Ok(()) |
| 343 | } |
| 344 |
| 345 | #[cfg(test)] |
| 346 | mod tests { |
| 347 | use super::*; |
| 348 | use crate::MemSource; |
| 349 |
| 350 | #[test] |
| 351 | fn diff_trees_matches_flat_diff() { |
| 352 | let mut src = MemSource::default(); |
| 353 | let mut put = |list: &[(&str, &str, EntryKind)]| -> Id { |
| 354 | 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(); |
| 355 | let (root, trees) = build(&files); |
| 356 | for t in trees { |
| 357 | src.put(t); |
| 358 | } |
| 359 | root |
| 360 | }; |
| 361 | let f = EntryKind::File; |
| 362 | 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)]); |
| 363 | 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)]); |
| 364 | let flat = diff(&flatten(&src, &a).unwrap(), &flatten(&src, &b).unwrap()); |
| 365 | assert_eq!(diff_trees(&src, &a, &b).unwrap(), flat); |
| 366 | assert!(diff_trees(&src, &a, &a).unwrap().is_empty()); |
| 367 | } |
| 368 |
| 369 | #[test] |
| 370 | fn edit_writes_and_deletes() { |
| 371 | let mut src = MemSource::default(); |
| 372 | let files: Files = [("a.txt", "1"), ("dir/x", "x"), ("dir/y", "y"), ("f", "f")] |
| 373 | .iter() |
| 374 | .map(|(p, c)| (p.to_string(), Entry { kind: EntryKind::File, id: src.put(Object::blob(c.as_bytes().to_vec())) })) |
| 375 | .collect(); |
| 376 | let (root, trees) = build(&files); |
| 377 | for t in trees { |
| 378 | src.put(t); |
| 379 | } |
| 380 | let put = vec![ |
| 381 | Put { path: "a.txt".into(), kind: EntryKind::File, content: b"2".to_vec() }, |
| 382 | Put { path: "new/deep/n.sh".into(), kind: EntryKind::Exec, content: b"#!/bin/sh".to_vec() }, |
| 383 | Put { path: "f/inside".into(), kind: EntryKind::File, content: b"i".to_vec() }, |
| 384 | ]; |
| 385 | let (out, objects) = edit(&src, &root, &put, &["dir".to_string()]).unwrap().unwrap(); |
| 386 | for o in objects { |
| 387 | src.put(o); |
| 388 | } |
| 389 | let got = flatten(&src, &out).unwrap(); |
| 390 | assert_eq!(got.keys().cloned().collect::<Vec<_>>(), vec!["a.txt", "f/inside", "new/deep/n.sh"]); |
| 391 | assert_eq!(got["new/deep/n.sh"].kind, EntryKind::Exec); |
| 392 | assert_eq!(edit(&src, &root, &[], &["../x".to_string()]).unwrap().unwrap_err(), "../x"); |
| 393 | } |
| 394 |
| 395 | fn files(src: &mut MemSource, list: &[(&str, &str)]) -> Files { |
| 396 | list.iter() |
| 397 | .map(|(p, c)| (p.to_string(), Entry { kind: EntryKind::File, id: src.put(Object::blob(c.as_bytes().to_vec())) })) |
| 398 | .collect() |
| 399 | } |
| 400 |
| 401 | #[test] |
| 402 | fn build_and_flatten() { |
| 403 | let mut src = MemSource::default(); |
| 404 | let f = files(&mut src, &[("a.txt", "a"), ("src/b.rs", "b"), ("src/x/c.rs", "c"), ("src.rs", "d")]); |
| 405 | let (root, trees) = build(&f); |
| 406 | for t in trees { |
| 407 | src.put(t); |
| 408 | } |
| 409 | assert_eq!(flatten(&src, &root).unwrap(), f); |
| 410 | let (empty, _) = build(&Files::new()); |
| 411 | assert_eq!(empty, empty_id()); |
| 412 | } |
| 413 |
| 414 | #[test] |
| 415 | fn new_objects_only() { |
| 416 | let mut src = MemSource::default(); |
| 417 | let a = files(&mut src, &[("a.txt", "a"), ("src/b.rs", "b"), ("docs/x.md", "x")]); |
| 418 | let (ra, ta) = build(&a); |
| 419 | for t in ta { |
| 420 | src.put(t); |
| 421 | } |
| 422 | let mut b = a.clone(); |
| 423 | b.insert("src/b.rs".into(), Entry { kind: EntryKind::File, id: src.put(Object::blob(b"b2".to_vec())) }); |
| 424 | let (rb, tb) = build(&b); |
| 425 | for t in tb { |
| 426 | src.put(t); |
| 427 | } |
| 428 | let mut out = Vec::new(); |
| 429 | new_since(&src, Some(&ra), &rb, &mut out).unwrap(); |
| 430 | // The root, src/ and the new blob; docs/ and a.txt are shared. |
| 431 | assert_eq!(out.len(), 3); |
| 432 | } |
| 433 |
| 434 | #[test] |
| 435 | fn under_paths() { |
| 436 | assert!(under("src/a.rs", "src")); |
| 437 | assert!(under("src", "src")); |
| 438 | assert!(!under("srcx/a.rs", "src")); |
| 439 | assert!(under("anything", "")); |
| 440 | } |
| 441 | } |
| 442 |