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, every part a [`safe_name`]. |
| 256 | pub fn valid_path(path: &str) -> bool { |
| 257 | !path.is_empty() && path.split('/').all(safe_name) |
| 258 | } |
| 259 |
| 260 | /// Whether one part of a path is safe on every system. Not empty, `.` or |
| 261 | /// `..`; no backslash (a separator on Windows) or NUL; and not vcs's or |
| 262 | /// git's own folder in any spelling some disk treats as the same (`.GIT`, |
| 263 | /// `.git.`, `git~1`, or with characters macOS ignores), since a project |
| 264 | /// holding `.git/hooks/...` would run code in the folders it's written to. |
| 265 | pub fn safe_name(name: &str) -> bool { |
| 266 | if name.is_empty() || name == "." || name == ".." || name.len() > u16::MAX as usize || name.contains(['\\', '\0']) { |
| 267 | return false; |
| 268 | } |
| 269 | let plain: String = name |
| 270 | .chars() |
| 271 | .filter(|c| !matches!(*c as u32, 0x200C..=0x200F | 0x202A..=0x202E | 0x206A..=0x206F | 0xFEFF)) |
| 272 | .collect::<String>() |
| 273 | .trim_end_matches(['.', ' ']) |
| 274 | .to_ascii_lowercase(); |
| 275 | !matches!(plain.as_str(), ".git" | ".vcs" | "git~1" | "vcs~1") |
| 276 | } |
| 277 |
| 278 | /// The first path `new` adds or changes over `old` that isn't a |
| 279 | /// [`valid_path`], if any. Paths already there aren't looked at again. |
| 280 | pub fn unsafe_path(src: &dyn Source, old: &Id, new: &Id) -> Result<Option<String>> { |
| 281 | Ok(diff_trees(src, old, new)?.into_iter().find(|(p, c)| !matches!(c, Change::Removed(_)) && !valid_path(p)).map(|(p, _)| p)) |
| 282 | } |
| 283 |
| 284 | /// `tree` with files written and deleted. Writing a path replaces whatever |
| 285 | /// was there (a folder of that name included); deleting a folder deletes |
| 286 | /// what's in it. Returns the new root and every object it needs that's new |
| 287 | /// (file contents, big files' chunks and trees). |
| 288 | pub fn edit(src: &dyn Source, tree: &Id, put: &[Put], delete: &[String]) -> Result<std::result::Result<(Id, Vec<Object>), String>> { |
| 289 | if let Some(bad) = put.iter().map(|p| p.path.as_str()).chain(delete.iter().map(String::as_str)).find(|p| !valid_path(p)) { |
| 290 | return Ok(Err(bad.to_string())); |
| 291 | } |
| 292 | let mut objects = Vec::new(); |
| 293 | let mut ops: Vec<EditOp> = delete.iter().map(|d| EditOp::Delete(d)).collect(); |
| 294 | for p in put { |
| 295 | let parts = crate::chunk::file_objects(&p.content); |
| 296 | ops.push(EditOp::Put(&p.path, Entry { kind: p.kind, id: parts[0].id() })); |
| 297 | objects.extend(parts); |
| 298 | } |
| 299 | // Only the folders on the edited paths are read and written again. |
| 300 | let root = match edit_dir(src, Some(tree), &ops, &mut objects)? { |
| 301 | Some(root) => root, |
| 302 | None => { |
| 303 | let empty = empty(); |
| 304 | let id = empty.id(); |
| 305 | objects.push(empty); |
| 306 | id |
| 307 | } |
| 308 | }; |
| 309 | Ok(Ok((root, objects))) |
| 310 | } |
| 311 |
| 312 | /// An edit, with its path relative to the folder it's applied in. Deletes |
| 313 | /// come first, then writes in order. |
| 314 | #[derive(Clone, Copy)] |
| 315 | enum EditOp<'a> { |
| 316 | Put(&'a str, Entry), |
| 317 | Delete(&'a str), |
| 318 | } |
| 319 |
| 320 | /// `tree` (None: a new folder) with `ops` applied; None when nothing's left |
| 321 | /// in it. A file and a folder can't share a path, so writing one replaces |
| 322 | /// the other. |
| 323 | fn edit_dir(src: &dyn Source, tree: Option<&Id>, ops: &[EditOp], objects: &mut Vec<Object>) -> Result<Option<Id>> { |
| 324 | enum Child<'a> { |
| 325 | Gone, |
| 326 | File(Entry), |
| 327 | Dir(Option<Id>, Vec<EditOp<'a>>), |
| 328 | } |
| 329 | let mut entries: BTreeMap<String, Entry> = match tree { |
| 330 | Some(t) => read(src, t)?.into_iter().map(|e| (e.name, Entry { kind: e.kind, id: e.id })).collect(), |
| 331 | None => BTreeMap::new(), |
| 332 | }; |
| 333 | let mut touched: BTreeMap<&str, Child> = BTreeMap::new(); |
| 334 | for op in ops { |
| 335 | let path = match op { |
| 336 | EditOp::Put(p, _) | EditOp::Delete(p) => *p, |
| 337 | }; |
| 338 | let (name, rest) = match path.split_once('/') { |
| 339 | Some((name, rest)) => (name, Some(rest)), |
| 340 | None => (path, None), |
| 341 | }; |
| 342 | let child = touched.entry(name).or_insert_with(|| match entries.get(name) { |
| 343 | Some(e) if e.kind == EntryKind::Tree => Child::Dir(Some(e.id), Vec::new()), |
| 344 | Some(e) => Child::File(*e), |
| 345 | None => Child::Gone, |
| 346 | }); |
| 347 | match (op, rest) { |
| 348 | (EditOp::Delete(_), None) => *child = Child::Gone, |
| 349 | (EditOp::Delete(_), Some(rest)) => { |
| 350 | if let Child::Dir(_, inner) = child { |
| 351 | inner.push(EditOp::Delete(rest)); |
| 352 | } |
| 353 | } |
| 354 | (EditOp::Put(_, e), None) => *child = Child::File(*e), |
| 355 | (EditOp::Put(_, e), Some(rest)) => { |
| 356 | if !matches!(child, Child::Dir(..)) { |
| 357 | *child = Child::Dir(None, Vec::new()); |
| 358 | } |
| 359 | if let Child::Dir(_, inner) = child { |
| 360 | inner.push(EditOp::Put(rest, *e)); |
| 361 | } |
| 362 | } |
| 363 | } |
| 364 | } |
| 365 | let mut changed = false; |
| 366 | for (name, child) in touched { |
| 367 | let next = match child { |
| 368 | Child::Gone => None, |
| 369 | Child::File(e) => Some(e), |
| 370 | Child::Dir(base, inner) if inner.is_empty() => base.map(|id| Entry { kind: EntryKind::Tree, id }), |
| 371 | Child::Dir(base, inner) => edit_dir(src, base.as_ref(), &inner, objects)?.map(|id| Entry { kind: EntryKind::Tree, id }), |
| 372 | }; |
| 373 | if entries.get(name) != next.as_ref() { |
| 374 | changed = true; |
| 375 | match next { |
| 376 | Some(e) => entries.insert(name.to_string(), e), |
| 377 | None => entries.remove(name), |
| 378 | }; |
| 379 | } |
| 380 | } |
| 381 | if !changed && tree.is_some() { |
| 382 | return Ok(tree.copied()); |
| 383 | } |
| 384 | if entries.is_empty() { |
| 385 | return Ok(None); |
| 386 | } |
| 387 | let list: Vec<TreeEntry> = entries.into_iter().map(|(name, e)| TreeEntry { name, kind: e.kind, id: e.id }).collect(); |
| 388 | let object = Object::new(Kind::Tree, encode(&list)); |
| 389 | let id = object.id(); |
| 390 | objects.push(object); |
| 391 | Ok(Some(id)) |
| 392 | } |
| 393 |
| 394 | /// What changed from tree `a` to tree `b`, by path, reading only the |
| 395 | /// folders that differ (the same answer as `diff` on both flattened). |
| 396 | pub fn diff_trees(src: &dyn Source, a: &Id, b: &Id) -> Result<BTreeMap<String, Change>> { |
| 397 | let mut out = BTreeMap::new(); |
| 398 | diff_into(src, Some(a), Some(b), "", &mut out)?; |
| 399 | Ok(out) |
| 400 | } |
| 401 |
| 402 | fn diff_into(src: &dyn Source, a: Option<&Id>, b: Option<&Id>, prefix: &str, out: &mut BTreeMap<String, Change>) -> Result<()> { |
| 403 | if a == b { |
| 404 | return Ok(()); |
| 405 | } |
| 406 | let entries = |t: Option<&Id>| -> Result<BTreeMap<String, TreeEntry>> { |
| 407 | Ok(match t { |
| 408 | Some(t) => read(src, t)?.into_iter().map(|e| (e.name.clone(), e)).collect(), |
| 409 | None => BTreeMap::new(), |
| 410 | }) |
| 411 | }; |
| 412 | let (ea, eb) = (entries(a)?, entries(b)?); |
| 413 | let path = |name: &str| if prefix.is_empty() { name.to_string() } else { format!("{prefix}/{name}") }; |
| 414 | let entry = |e: &TreeEntry| Entry { kind: e.kind, id: e.id }; |
| 415 | for (name, x) in &ea { |
| 416 | let p = path(name); |
| 417 | match eb.get(name) { |
| 418 | Some(y) if x.kind == y.kind && x.id == y.id => {} |
| 419 | Some(y) => match (x.kind == EntryKind::Tree, y.kind == EntryKind::Tree) { |
| 420 | (true, true) => diff_into(src, Some(&x.id), Some(&y.id), &p, out)?, |
| 421 | (true, false) => { |
| 422 | diff_into(src, Some(&x.id), None, &p, out)?; |
| 423 | out.insert(p, Change::Added(entry(y))); |
| 424 | } |
| 425 | (false, true) => { |
| 426 | out.insert(p.clone(), Change::Removed(entry(x))); |
| 427 | diff_into(src, None, Some(&y.id), &p, out)?; |
| 428 | } |
| 429 | (false, false) => { |
| 430 | out.insert(p, Change::Modified(entry(x), entry(y))); |
| 431 | } |
| 432 | }, |
| 433 | None if x.kind == EntryKind::Tree => diff_into(src, Some(&x.id), None, &p, out)?, |
| 434 | None => { |
| 435 | out.insert(p, Change::Removed(entry(x))); |
| 436 | } |
| 437 | } |
| 438 | } |
| 439 | for (name, y) in &eb { |
| 440 | if ea.contains_key(name) { |
| 441 | continue; |
| 442 | } |
| 443 | let p = path(name); |
| 444 | if y.kind == EntryKind::Tree { |
| 445 | diff_into(src, None, Some(&y.id), &p, out)?; |
| 446 | } else { |
| 447 | out.insert(p, Change::Added(entry(y))); |
| 448 | } |
| 449 | } |
| 450 | Ok(()) |
| 451 | } |
| 452 |
| 453 | #[cfg(test)] |
| 454 | mod tests { |
| 455 | use super::*; |
| 456 | use crate::MemSource; |
| 457 |
| 458 | #[test] |
| 459 | fn diff_trees_matches_flat_diff() { |
| 460 | let mut src = MemSource::default(); |
| 461 | let mut put = |list: &[(&str, &str, EntryKind)]| -> Id { |
| 462 | 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(); |
| 463 | let (root, trees) = build(&files); |
| 464 | for t in trees { |
| 465 | src.put(t); |
| 466 | } |
| 467 | root |
| 468 | }; |
| 469 | let f = EntryKind::File; |
| 470 | 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)]); |
| 471 | 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)]); |
| 472 | let flat = diff(&flatten(&src, &a).unwrap(), &flatten(&src, &b).unwrap()); |
| 473 | assert_eq!(diff_trees(&src, &a, &b).unwrap(), flat); |
| 474 | assert!(diff_trees(&src, &a, &a).unwrap().is_empty()); |
| 475 | } |
| 476 |
| 477 | #[test] |
| 478 | fn edit_writes_and_deletes() { |
| 479 | let mut src = MemSource::default(); |
| 480 | let files: Files = [("a.txt", "1"), ("dir/x", "x"), ("dir/y", "y"), ("f", "f")] |
| 481 | .iter() |
| 482 | .map(|(p, c)| (p.to_string(), Entry { kind: EntryKind::File, id: src.put(Object::blob(c.as_bytes().to_vec())) })) |
| 483 | .collect(); |
| 484 | let (root, trees) = build(&files); |
| 485 | for t in trees { |
| 486 | src.put(t); |
| 487 | } |
| 488 | let put = vec![ |
| 489 | Put { path: "a.txt".into(), kind: EntryKind::File, content: b"2".to_vec() }, |
| 490 | Put { path: "new/deep/n.sh".into(), kind: EntryKind::Exec, content: b"#!/bin/sh".to_vec() }, |
| 491 | Put { path: "f/inside".into(), kind: EntryKind::File, content: b"i".to_vec() }, |
| 492 | ]; |
| 493 | let (out, objects) = edit(&src, &root, &put, &["dir".to_string()]).unwrap().unwrap(); |
| 494 | for o in objects { |
| 495 | src.put(o); |
| 496 | } |
| 497 | let got = flatten(&src, &out).unwrap(); |
| 498 | assert_eq!(got.keys().cloned().collect::<Vec<_>>(), vec!["a.txt", "f/inside", "new/deep/n.sh"]); |
| 499 | assert_eq!(got["new/deep/n.sh"].kind, EntryKind::Exec); |
| 500 | assert_eq!(edit(&src, &root, &[], &["../x".to_string()]).unwrap().unwrap_err(), "../x"); |
| 501 | } |
| 502 |
| 503 | #[test] |
| 504 | fn unsafe_names() { |
| 505 | for bad in [".git", ".GIT", ".git.", ".git ", "Git~1", ".vcs", ".VCS..", "vcs~1", ".g\u{200c}it", "a\\b", "..", ".", "", "x\0y"] { |
| 506 | assert!(!safe_name(bad), "{bad:?}"); |
| 507 | } |
| 508 | for good in [".github", ".gitignore", "git", "vcs.toml", "aux.c", "a:b", ".vcsignore", "...x"] { |
| 509 | assert!(safe_name(good), "{good:?}"); |
| 510 | } |
| 511 | assert!(!valid_path("src/.git/hooks/post-checkout")); |
| 512 | assert!(!valid_path("a/.vcs/id")); |
| 513 | assert!(valid_path("src/.github/workflows/ci.yml")); |
| 514 |
| 515 | let mut src = MemSource::default(); |
| 516 | let ok = files(&mut src, &[("a.txt", "a"), ("old\\name", "legacy")]); |
| 517 | let (old, trees) = build(&ok); |
| 518 | for t in trees { |
| 519 | src.put(t); |
| 520 | } |
| 521 | let mut worse = ok.clone(); |
| 522 | worse.insert("sub/.git/hooks/post-checkout".into(), Entry { kind: EntryKind::Exec, id: src.put(Object::blob(b"#!/bin/sh\n".to_vec())) }); |
| 523 | let (new, trees) = build(&worse); |
| 524 | for t in trees { |
| 525 | src.put(t); |
| 526 | } |
| 527 | assert_eq!(unsafe_path(&src, &old, &new).unwrap().as_deref(), Some("sub/.git/hooks/post-checkout")); |
| 528 | // A path already there isn't held against a change that leaves it alone. |
| 529 | assert_eq!(unsafe_path(&src, &old, &old).unwrap(), None); |
| 530 | } |
| 531 |
| 532 | /// The same root as editing every file and building the tree again. |
| 533 | #[test] |
| 534 | fn edit_matches_a_full_rebuild() { |
| 535 | let mut src = MemSource::default(); |
| 536 | 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")]); |
| 537 | let (root, trees) = build(&base); |
| 538 | for t in trees { |
| 539 | src.put(t); |
| 540 | } |
| 541 | let p = |path: &str, content: &str| Put { path: path.into(), kind: EntryKind::File, content: content.as_bytes().to_vec() }; |
| 542 | let cases: Vec<(Vec<Put>, Vec<&str>)> = vec![ |
| 543 | (vec![p("src/x/c.rs", "c2")], vec![]), |
| 544 | (vec![p("new/deep/file", "n")], vec![]), |
| 545 | (vec![], vec!["src/x/c.rs", "src/x/d.rs"]), |
| 546 | (vec![], vec!["lone/only"]), |
| 547 | (vec![], vec!["src"]), |
| 548 | (vec![], vec!["nope/missing", "f/inside"]), |
| 549 | (vec![p("f/inside", "i")], vec![]), |
| 550 | (vec![p("src", "now a file")], vec![]), |
| 551 | (vec![p("a.txt", "1"), p("a.txt/b", "2"), p("a.txt", "3")], vec![]), |
| 552 | (vec![p("docs/x.md", "x")], vec![]), |
| 553 | (vec![p("docs/y.md", "y")], vec!["docs"]), |
| 554 | (vec![], vec!["a.txt", "src", "docs", "f", "lone"]), |
| 555 | ]; |
| 556 | for (put, delete) in cases { |
| 557 | let delete: Vec<String> = delete.into_iter().map(String::from).collect(); |
| 558 | let mut want = base.clone(); |
| 559 | for d in &delete { |
| 560 | want.retain(|q, _| !under(q, d)); |
| 561 | } |
| 562 | for x in &put { |
| 563 | want.retain(|q, _| !under(q, &x.path) && !under(&x.path, q)); |
| 564 | want.insert(x.path.clone(), Entry { kind: x.kind, id: Object::blob(x.content.clone()).id() }); |
| 565 | } |
| 566 | let (want_root, _) = build(&want); |
| 567 | let (got, objects) = edit(&src, &root, &put, &delete).unwrap().unwrap(); |
| 568 | assert_eq!(got, want_root, "put {:?} delete {delete:?}", put.iter().map(|x| &x.path).collect::<Vec<_>>()); |
| 569 | let mut after = src.clone(); |
| 570 | for o in objects { |
| 571 | after.put(o); |
| 572 | } |
| 573 | assert_eq!(flatten(&after, &got).unwrap(), want); |
| 574 | } |
| 575 | } |
| 576 |
| 577 | fn files(src: &mut MemSource, list: &[(&str, &str)]) -> Files { |
| 578 | list.iter() |
| 579 | .map(|(p, c)| (p.to_string(), Entry { kind: EntryKind::File, id: src.put(Object::blob(c.as_bytes().to_vec())) })) |
| 580 | .collect() |
| 581 | } |
| 582 |
| 583 | #[test] |
| 584 | fn build_and_flatten() { |
| 585 | let mut src = MemSource::default(); |
| 586 | let f = files(&mut src, &[("a.txt", "a"), ("src/b.rs", "b"), ("src/x/c.rs", "c"), ("src.rs", "d")]); |
| 587 | let (root, trees) = build(&f); |
| 588 | for t in trees { |
| 589 | src.put(t); |
| 590 | } |
| 591 | assert_eq!(flatten(&src, &root).unwrap(), f); |
| 592 | let (empty, _) = build(&Files::new()); |
| 593 | assert_eq!(empty, empty_id()); |
| 594 | } |
| 595 |
| 596 | #[test] |
| 597 | fn new_objects_only() { |
| 598 | let mut src = MemSource::default(); |
| 599 | let a = files(&mut src, &[("a.txt", "a"), ("src/b.rs", "b"), ("docs/x.md", "x")]); |
| 600 | let (ra, ta) = build(&a); |
| 601 | for t in ta { |
| 602 | src.put(t); |
| 603 | } |
| 604 | let mut b = a.clone(); |
| 605 | b.insert("src/b.rs".into(), Entry { kind: EntryKind::File, id: src.put(Object::blob(b"b2".to_vec())) }); |
| 606 | let (rb, tb) = build(&b); |
| 607 | for t in tb { |
| 608 | src.put(t); |
| 609 | } |
| 610 | let mut out = Vec::new(); |
| 611 | new_since(&src, Some(&ra), &rb, &mut out).unwrap(); |
| 612 | // The root, src/ and the new blob; docs/ and a.txt are shared. |
| 613 | assert_eq!(out.len(), 3); |
| 614 | } |
| 615 |
| 616 | #[test] |
| 617 | fn under_paths() { |
| 618 | assert!(under("src/a.rs", "src")); |
| 619 | assert!(under("src", "src")); |
| 620 | assert!(!under("srcx/a.rs", "src")); |
| 621 | assert!(under("anything", "")); |
| 622 | } |
| 623 | } |
| 624 |