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 | } |
| 17 |
| 18 | impl EntryKind { |
| 19 | pub fn from_u8(b: u8) -> Option<EntryKind> { |
| 20 | match b { |
| 21 | 1 => Some(EntryKind::File), |
| 22 | 2 => Some(EntryKind::Exec), |
| 23 | 3 => Some(EntryKind::Link), |
| 24 | 4 => Some(EntryKind::Tree), |
| 25 | _ => None, |
| 26 | } |
| 27 | } |
| 28 |
| 29 | pub fn name(self) -> &'static str { |
| 30 | match self { |
| 31 | EntryKind::File => "file", |
| 32 | EntryKind::Exec => "exec", |
| 33 | EntryKind::Link => "link", |
| 34 | EntryKind::Tree => "tree", |
| 35 | } |
| 36 | } |
| 37 | } |
| 38 |
| 39 | /// A file in a flattened tree. `id` names a blob or, for big files, a chunk list. |
| 40 | #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] |
| 41 | pub struct Entry { |
| 42 | pub kind: EntryKind, |
| 43 | pub id: Id, |
| 44 | } |
| 45 |
| 46 | pub type Files = BTreeMap<String, Entry>; |
| 47 |
| 48 | #[derive(Debug, Clone, PartialEq, Eq)] |
| 49 | pub struct TreeEntry { |
| 50 | pub name: String, |
| 51 | pub kind: EntryKind, |
| 52 | pub id: Id, |
| 53 | } |
| 54 |
| 55 | pub fn encode(entries: &[TreeEntry]) -> Vec<u8> { |
| 56 | let mut sorted: Vec<&TreeEntry> = entries.iter().collect(); |
| 57 | sorted.sort_by(|a, b| a.name.as_bytes().cmp(b.name.as_bytes())); |
| 58 | let mut out = Vec::with_capacity(entries.len() * 48); |
| 59 | for e in sorted { |
| 60 | out.push(e.kind as u8); |
| 61 | out.extend_from_slice(&(e.name.len() as u16).to_le_bytes()); |
| 62 | out.extend_from_slice(e.name.as_bytes()); |
| 63 | out.extend_from_slice(&e.id.0); |
| 64 | } |
| 65 | out |
| 66 | } |
| 67 |
| 68 | pub fn decode(data: &[u8]) -> Result<Vec<TreeEntry>> { |
| 69 | let mut out = Vec::new(); |
| 70 | let mut at = 0; |
| 71 | while at < data.len() { |
| 72 | let kind = EntryKind::from_u8(data[at]).ok_or_else(|| corrupt("bad tree entry kind"))?; |
| 73 | let len = u16::from_le_bytes(data.get(at + 1..at + 3).ok_or_else(|| corrupt("short tree"))?.try_into().unwrap()) as usize; |
| 74 | let name_end = at + 3 + len; |
| 75 | let name = std::str::from_utf8(data.get(at + 3..name_end).ok_or_else(|| corrupt("short tree"))?) |
| 76 | .map_err(|_| corrupt("tree name isn't UTF-8"))? |
| 77 | .to_string(); |
| 78 | if name.is_empty() || name.contains('/') || name == "." || name == ".." { |
| 79 | return Err(corrupt("bad name in tree")); |
| 80 | } |
| 81 | let id = Id::from_slice(data.get(name_end..name_end + 32).ok_or_else(|| corrupt("short tree"))?).unwrap(); |
| 82 | out.push(TreeEntry { name, kind, id }); |
| 83 | at = name_end + 32; |
| 84 | } |
| 85 | Ok(out) |
| 86 | } |
| 87 |
| 88 | pub fn empty() -> Object { |
| 89 | Object::new(Kind::Tree, Vec::new()) |
| 90 | } |
| 91 |
| 92 | pub fn empty_id() -> Id { |
| 93 | empty().id() |
| 94 | } |
| 95 |
| 96 | pub fn read(src: &dyn Source, id: &Id) -> Result<Vec<TreeEntry>> { |
| 97 | let object = src.must(id)?; |
| 98 | if object.kind != Kind::Tree { |
| 99 | return Err(corrupt(format!("{} isn't a tree", id.short()))); |
| 100 | } |
| 101 | decode(&object.data) |
| 102 | } |
| 103 |
| 104 | /// Every file under `tree`. |
| 105 | pub fn flatten(src: &dyn Source, tree: &Id) -> Result<Files> { |
| 106 | let mut out = Files::new(); |
| 107 | walk(src, tree, "", &mut out)?; |
| 108 | Ok(out) |
| 109 | } |
| 110 |
| 111 | fn walk(src: &dyn Source, tree: &Id, prefix: &str, out: &mut Files) -> Result<()> { |
| 112 | for e in read(src, tree)? { |
| 113 | let path = if prefix.is_empty() { e.name.clone() } else { format!("{prefix}/{}", e.name) }; |
| 114 | if e.kind == EntryKind::Tree { |
| 115 | walk(src, &e.id, &path, out)?; |
| 116 | } else { |
| 117 | out.insert(path, Entry { kind: e.kind, id: e.id }); |
| 118 | } |
| 119 | } |
| 120 | Ok(()) |
| 121 | } |
| 122 |
| 123 | /// Every object ID a tree reaches (the trees themselves, file blobs and |
| 124 | /// chunk lists, not the chunks inside chunk lists). |
| 125 | pub fn reachable(src: &dyn Source, tree: &Id, out: &mut Vec<Id>) -> Result<()> { |
| 126 | out.push(*tree); |
| 127 | for e in read(src, tree)? { |
| 128 | if e.kind == EntryKind::Tree { |
| 129 | reachable(src, &e.id, out)?; |
| 130 | } else { |
| 131 | out.push(e.id); |
| 132 | } |
| 133 | } |
| 134 | Ok(()) |
| 135 | } |
| 136 |
| 137 | /// Trees reached from `new` but not from `old`, walking only subtrees that |
| 138 | /// differ, plus the file IDs those subtrees hold that `old` doesn't have at |
| 139 | /// the same path. |
| 140 | pub fn new_since(src: &dyn Source, old: Option<&Id>, new: &Id, out: &mut Vec<Id>) -> Result<()> { |
| 141 | if Some(new) == old { |
| 142 | return Ok(()); |
| 143 | } |
| 144 | out.push(*new); |
| 145 | let old_entries: HashMap<String, TreeEntry> = match old { |
| 146 | Some(o) => read(src, o)?.into_iter().map(|e| (e.name.clone(), e)).collect(), |
| 147 | None => HashMap::new(), |
| 148 | }; |
| 149 | for e in read(src, new)? { |
| 150 | let before = old_entries.get(&e.name); |
| 151 | if before.is_some_and(|b| b.id == e.id) { |
| 152 | continue; |
| 153 | } |
| 154 | if e.kind == EntryKind::Tree { |
| 155 | let old_sub = before.filter(|b| b.kind == EntryKind::Tree).map(|b| b.id); |
| 156 | new_since(src, old_sub.as_ref(), &e.id, out)?; |
| 157 | } else { |
| 158 | out.push(e.id); |
| 159 | } |
| 160 | } |
| 161 | Ok(()) |
| 162 | } |
| 163 |
| 164 | /// Builds tree objects for `files`. Returns the root ID and every tree |
| 165 | /// object (the host stores the ones it doesn't have). |
| 166 | pub fn build(files: &Files) -> (Id, Vec<Object>) { |
| 167 | let mut dirs: HashMap<&str, Vec<TreeEntry>> = HashMap::new(); |
| 168 | let mut subdirs: HashMap<&str, Vec<&str>> = HashMap::new(); |
| 169 | dirs.entry("").or_default(); |
| 170 | for (path, entry) in files { |
| 171 | let (dir, name) = split(path); |
| 172 | dirs.entry(dir).or_default().push(TreeEntry { name: name.to_string(), kind: entry.kind, id: entry.id }); |
| 173 | let mut d = dir; |
| 174 | while !d.is_empty() { |
| 175 | let (parent, _) = split(d); |
| 176 | let known = subdirs.entry(parent).or_default(); |
| 177 | if known.contains(&d) { |
| 178 | break; |
| 179 | } |
| 180 | known.push(d); |
| 181 | dirs.entry(d).or_default(); |
| 182 | d = parent; |
| 183 | } |
| 184 | } |
| 185 | let mut order: Vec<&str> = dirs.keys().copied().collect(); |
| 186 | order.sort_by_key(|d| std::cmp::Reverse(if d.is_empty() { 0 } else { d.matches('/').count() + 1 })); |
| 187 | let mut written: HashMap<&str, Id> = HashMap::with_capacity(order.len()); |
| 188 | let mut objects = Vec::with_capacity(order.len()); |
| 189 | for dir in order { |
| 190 | let mut entries = dirs.remove(dir).unwrap_or_default(); |
| 191 | for child in subdirs.get(dir).map(Vec::as_slice).unwrap_or(&[]) { |
| 192 | entries.push(TreeEntry { name: split(child).1.to_string(), kind: EntryKind::Tree, id: written[child] }); |
| 193 | } |
| 194 | let object = Object::new(Kind::Tree, encode(&entries)); |
| 195 | let id = object.id(); |
| 196 | objects.push(object); |
| 197 | written.insert(dir, id); |
| 198 | } |
| 199 | (written[""], objects) |
| 200 | } |
| 201 |
| 202 | /// "a/b/c" → ("a/b", "c"); "c" → ("", "c"). |
| 203 | pub fn split(path: &str) -> (&str, &str) { |
| 204 | match path.rfind('/') { |
| 205 | Some(i) => (&path[..i], &path[i + 1..]), |
| 206 | None => ("", path), |
| 207 | } |
| 208 | } |
| 209 |
| 210 | /// Whether `path` is `prefix` or inside it. |
| 211 | pub fn under(path: &str, prefix: &str) -> bool { |
| 212 | prefix.is_empty() || path == prefix || (path.starts_with(prefix) && path.as_bytes().get(prefix.len()) == Some(&b'/')) |
| 213 | } |
| 214 |
| 215 | #[derive(Debug, Clone, PartialEq, Eq)] |
| 216 | pub enum Change { |
| 217 | Added(Entry), |
| 218 | Removed(Entry), |
| 219 | Modified(Entry, Entry), |
| 220 | } |
| 221 |
| 222 | /// What changed from `a` to `b`, by path. |
| 223 | pub fn diff(a: &Files, b: &Files) -> BTreeMap<String, Change> { |
| 224 | let mut out = BTreeMap::new(); |
| 225 | for (path, old) in a { |
| 226 | match b.get(path) { |
| 227 | None => { |
| 228 | out.insert(path.clone(), Change::Removed(*old)); |
| 229 | } |
| 230 | Some(new) if new != old => { |
| 231 | out.insert(path.clone(), Change::Modified(*old, *new)); |
| 232 | } |
| 233 | _ => {} |
| 234 | } |
| 235 | } |
| 236 | for (path, new) in b { |
| 237 | if !a.contains_key(path) { |
| 238 | out.insert(path.clone(), Change::Added(*new)); |
| 239 | } |
| 240 | } |
| 241 | out |
| 242 | } |
| 243 |
| 244 | #[cfg(test)] |
| 245 | mod tests { |
| 246 | use super::*; |
| 247 | use crate::MemSource; |
| 248 |
| 249 | fn files(src: &mut MemSource, list: &[(&str, &str)]) -> Files { |
| 250 | list.iter() |
| 251 | .map(|(p, c)| (p.to_string(), Entry { kind: EntryKind::File, id: src.put(Object::blob(c.as_bytes().to_vec())) })) |
| 252 | .collect() |
| 253 | } |
| 254 |
| 255 | #[test] |
| 256 | fn build_and_flatten() { |
| 257 | let mut src = MemSource::default(); |
| 258 | let f = files(&mut src, &[("a.txt", "a"), ("src/b.rs", "b"), ("src/x/c.rs", "c"), ("src.rs", "d")]); |
| 259 | let (root, trees) = build(&f); |
| 260 | for t in trees { |
| 261 | src.put(t); |
| 262 | } |
| 263 | assert_eq!(flatten(&src, &root).unwrap(), f); |
| 264 | let (empty, _) = build(&Files::new()); |
| 265 | assert_eq!(empty, empty_id()); |
| 266 | } |
| 267 |
| 268 | #[test] |
| 269 | fn new_objects_only() { |
| 270 | let mut src = MemSource::default(); |
| 271 | let a = files(&mut src, &[("a.txt", "a"), ("src/b.rs", "b"), ("docs/x.md", "x")]); |
| 272 | let (ra, ta) = build(&a); |
| 273 | for t in ta { |
| 274 | src.put(t); |
| 275 | } |
| 276 | let mut b = a.clone(); |
| 277 | b.insert("src/b.rs".into(), Entry { kind: EntryKind::File, id: src.put(Object::blob(b"b2".to_vec())) }); |
| 278 | let (rb, tb) = build(&b); |
| 279 | for t in tb { |
| 280 | src.put(t); |
| 281 | } |
| 282 | let mut out = Vec::new(); |
| 283 | new_since(&src, Some(&ra), &rb, &mut out).unwrap(); |
| 284 | // The root, src/ and the new blob; docs/ and a.txt are shared. |
| 285 | assert_eq!(out.len(), 3); |
| 286 | } |
| 287 |
| 288 | #[test] |
| 289 | fn under_paths() { |
| 290 | assert!(under("src/a.rs", "src")); |
| 291 | assert!(under("src", "src")); |
| 292 | assert!(!under("srcx/a.rs", "src")); |
| 293 | assert!(under("anything", "")); |
| 294 | } |
| 295 | } |
| 296 |