Elffuss BraidHub

utopia-ia/elffuss-braid public

main · 20.4 KiBRawPermalink
1// SPDX-License-Identifier: Apache-2.0
2// Copyright (c) 2026 UtopiaIA
3
4//! Bringing a working copy from one tree to another, writing only what
5//! differs.
6//!
7//! A checkout is planned first and written second. Planning reads the two
8//! trees and the working copy and refuses, before anything is written:
9//!
10//! - a name this platform cannot represent;
11//! - two names of one directory that this file system would take for the
12//! same file (letter case, Unicode normalisation): neither is written;
13//! - in checked mode, anything in the way that braid did not put there: an
14//! untracked file where a new file goes, or a file or symlink where a new
15//! directory goes.
16//!
17//! Writing then removes before it creates. Files that go away are removed
18//! first, then the directories left empty, then new content is written:
19//! each regular file into a scratch file in its directory, with mode 0644 or
20//! 0755, renamed over its name; each symlink created with its target stored
21//! as data and renamed into place; each gitlink as an empty directory. Every
22//! step goes through directory handles that never follow a symlink (see
23//! [`safe`](crate::safe)), and nothing found in the repository is ever run.
24
25use std::collections::{BTreeMap, BTreeSet, HashMap, HashSet};
26use std::ffi::OsStr;
27use std::io;
28
29use braid_engine::{EMPTY_TREE, diff, entry_at, read_blob, read_tree};
30use braid_format::{ChangeOp, EntryKind, Kind, ObjectId, Objects};
31use braid_store::{CHUNKED_MIN, Store};
32use cap_std::fs::Dir;
33
34use crate::error::Error;
35use crate::fsprobe::FileSystem;
36use crate::paths::{ancestors, names, os_name, platform_problem, split_last};
37use crate::safe::{
38 Found, Root, StatKind, remove_entry, write_file, write_file_from, write_symlink,
39};
40
41/// Whether a checkout may overwrite what it finds.
42#[derive(Clone, Copy, Debug, PartialEq, Eq)]
43pub(crate) enum Mode {
44 /// Refuse when untracked data is in the way.
45 Checked,
46 /// Finish a checkout that was interrupted: the paths it covers are
47 /// braid's to overwrite.
48 Forced,
49}
50
51/// A checkout, validated and ready to write.
52#[derive(Debug, Default)]
53pub(crate) struct Plan {
54 /// Files, symlinks and gitlinks to remove, with what they were.
55 removes: Vec<(Vec<u8>, ChangeOp)>,
56 /// Directories that the target tree does not have, deepest first.
57 empty_dirs: Vec<Vec<u8>>,
58 /// What to write, by path in order.
59 writes: Vec<(Vec<u8>, ChangeOp)>,
60}
61
62impl Plan {
63 /// How many paths the checkout writes or removes.
64 pub(crate) fn len(&self) -> usize {
65 self.removes.len() + self.writes.len()
66 }
67
68 /// The paths the checkout writes or removes, sorted: files, symlinks
69 /// and gitlinks, not the directories that come and go with them.
70 pub(crate) fn paths(&self) -> Vec<Vec<u8>> {
71 let mut paths: Vec<Vec<u8>> = self
72 .removes
73 .iter()
74 .chain(&self.writes)
75 .map(|(path, _)| path.clone())
76 .collect();
77 paths.sort();
78 paths.dedup();
79 paths
80 }
81}
82
83/// Plans the checkout that turns the working copy of tree `from` into tree
84/// `to`.
85pub(crate) fn plan<O: Objects>(
86 objects: &O,
87 root: &Root,
88 fs: FileSystem,
89 from: ObjectId,
90 to: ObjectId,
91 mode: Mode,
92) -> Result<Plan, Error> {
93 let mut plan = Plan::default();
94 if from == to {
95 return Ok(plan);
96 }
97 // The diff the other way lists the same paths with what `from` has
98 // there: one walk over the difference instead of a lookup per path.
99 let olds: HashMap<Vec<u8>, ChangeOp> = if from == EMPTY_TREE {
100 HashMap::new()
101 } else {
102 diff(objects, to, from)?
103 .into_iter()
104 .filter(|change| !matches!(change.op, ChangeOp::Delete))
105 .map(|change| (change.path, change.op))
106 .collect()
107 };
108 for change in diff(objects, from, to)? {
109 match change.op {
110 ChangeOp::Delete => {
111 if let Some(old) = olds.get(&change.path) {
112 plan.removes.push((change.path, old.clone()));
113 }
114 }
115 op => plan.writes.push((change.path, op)),
116 }
117 }
118
119 // Directories the removals may leave behind, deepest first.
120 let mut is_dir: HashMap<&[u8], bool> = HashMap::new();
121 let mut gone = BTreeSet::new();
122 for (path, _) in &plan.removes {
123 for dir in ancestors(path) {
124 let stays = match is_dir.get(dir) {
125 Some(stays) => *stays,
126 None => {
127 let stays = is_dir_in(objects, to, dir)?;
128 is_dir.insert(dir, stays);
129 stays
130 }
131 };
132 if !stays {
133 gone.insert(dir.to_vec());
134 }
135 }
136 }
137 plan.empty_dirs = gone.into_iter().collect();
138 plan.empty_dirs.sort_by(|a, b| {
139 let depth = |p: &[u8]| p.iter().filter(|byte| **byte == b'/').count();
140 depth(b).cmp(&depth(a)).then_with(|| a.cmp(b))
141 });
142
143 for (path, _) in &plan.writes {
144 for name in names(path) {
145 if let Some(reason) = platform_problem(name) {
146 return Err(Error::Unsafe {
147 path: path.clone(),
148 reason: reason.to_owned(),
149 });
150 }
151 }
152 }
153 if fs.ignores_case || fs.ignores_normalization {
154 check_collisions(objects, fs, to, &plan.writes)?;
155 }
156 if mode == Mode::Checked {
157 check_obstacles(root, fs, &plan, &olds)?;
158 }
159 Ok(plan)
160}
161
162/// Whether `dir` is a directory of the tree `root`.
163fn is_dir_in<O: Objects>(objects: &O, root: ObjectId, dir: &[u8]) -> Result<bool, Error> {
164 Ok(matches!(
165 entry_at(objects, root, dir)?,
166 Some(EntryKind::Tree { .. })
167 ))
168}
169
170/// Refuses two names of one directory of `to` that fold to the same name,
171/// in every directory a write goes through.
172fn check_collisions<O: Objects>(
173 objects: &O,
174 fs: FileSystem,
175 to: ObjectId,
176 writes: &[(Vec<u8>, ChangeOp)],
177) -> Result<(), Error> {
178 let mut checked: HashSet<Vec<u8>> = HashSet::new();
179 for (path, _) in writes {
180 let dirs = std::iter::once(&path[..0]).chain(ancestors(path));
181 for dir in dirs {
182 if !checked.insert(dir.to_vec()) {
183 continue;
184 }
185 let tree = if dir.is_empty() {
186 to
187 } else {
188 match entry_at(objects, to, dir)? {
189 Some(EntryKind::Tree { tree }) => tree,
190 _ => continue,
191 }
192 };
193 let mut seen: HashMap<Vec<u8>, Vec<u8>> = HashMap::new();
194 for entry in read_tree(objects, tree)? {
195 let folded = fs.fold(&entry.name).into_owned();
196 if let Some(first) = seen.insert(folded, entry.name.clone()) {
197 let at = |name: &[u8]| crate::paths::join(dir, name);
198 return Err(Error::Collision {
199 first: at(&first),
200 second: at(&entry.name),
201 });
202 }
203 }
204 }
205 }
206 Ok(())
207}
208
209/// What the working copy has at a directory on the way to a write.
210#[derive(Clone, Copy, PartialEq, Eq)]
211enum DirState {
212 Present,
213 Missing,
214}
215
216/// Refuses writes that would overwrite or go through something the old
217/// tree did not have there.
218fn check_obstacles(
219 root: &Root,
220 fs: FileSystem,
221 plan: &Plan,
222 olds: &HashMap<Vec<u8>, ChangeOp>,
223) -> Result<(), Error> {
224 let fold_path = |path: &[u8]| -> Vec<u8> {
225 let mut out = Vec::with_capacity(path.len());
226 for name in names(path) {
227 if !out.is_empty() {
228 out.push(b'/');
229 }
230 out.extend_from_slice(&fs.fold(name));
231 }
232 out
233 };
234 // What the plan removes, as this file system finds it.
235 let removed: HashSet<Vec<u8>> = plan
236 .removes
237 .iter()
238 .map(|(path, _)| fold_path(path))
239 .collect();
240 let emptied: HashSet<Vec<u8>> = plan.empty_dirs.iter().map(|path| fold_path(path)).collect();
241 let mut dirs: HashMap<Vec<u8>, DirState> = HashMap::new();
242 dirs.insert(Vec::new(), DirState::Present);
243
244 for (path, op) in &plan.writes {
245 let mut parent_state = DirState::Present;
246 for dir in ancestors(path) {
247 if let Some(state) = dirs.get(dir) {
248 parent_state = *state;
249 continue;
250 }
251 let state = if parent_state == DirState::Missing {
252 DirState::Missing
253 } else {
254 match root.stat(dir)? {
255 Found::Here(stat) if stat.kind == StatKind::Dir => DirState::Present,
256 Found::Here(_) if removed.contains(&fold_path(dir)) => DirState::Missing,
257 Found::Here(_) => {
258 return Err(Error::Unsafe {
259 path: dir.to_vec(),
260 reason: "a file or symlink that braid does not track is where a directory goes"
261 .to_owned(),
262 });
263 }
264 Found::Missing | Found::Blocked(_) => DirState::Missing,
265 }
266 };
267 dirs.insert(dir.to_vec(), state);
268 parent_state = state;
269 }
270 if parent_state == DirState::Missing || olds.contains_key(path) {
271 continue;
272 }
273 let Found::Here(stat) = root.stat(path)? else {
274 continue;
275 };
276 let folded = fold_path(path);
277 if removed.contains(&folded) {
278 // A file or symlink the checkout removes first.
279 continue;
280 }
281 let is_dir = stat.kind == StatKind::Dir;
282 if is_dir && matches!(op, ChangeOp::Gitlink { .. }) {
283 continue;
284 }
285 if is_dir && emptied.contains(&folded) {
286 // A directory that this file replaces: it must hold nothing
287 // but what the checkout removes.
288 if let Some(untracked) = untracked_inside(root, path, &removed, &fold_path)? {
289 return Err(Error::Unsafe {
290 path: untracked,
291 reason: format!(
292 "a file replaces the directory {:?}, and this untracked file in it would be lost",
293 crate::paths::show(path)
294 ),
295 });
296 }
297 continue;
298 }
299 return Err(Error::Unsafe {
300 path: path.clone(),
301 reason: "an untracked file or directory is in the way; move it or remove it".to_owned(),
302 });
303 }
304 Ok(())
305}
306
307/// The first entry under the directory `dir` of the working copy that is
308/// not a directory and that the checkout does not remove, if there is one.
309fn untracked_inside(
310 root: &Root,
311 dir: &[u8],
312 removed: &HashSet<Vec<u8>>,
313 fold_path: &dyn Fn(&[u8]) -> Vec<u8>,
314) -> Result<Option<Vec<u8>>, Error> {
315 let mut pending = vec![dir.to_vec()];
316 while let Some(current) = pending.pop() {
317 let Found::Here(handle) = root.open_dir(&current)? else {
318 continue;
319 };
320 let entries = handle
321 .entries()
322 .map_err(|err| root.error("read", &current, err))?;
323 for entry in entries {
324 let entry = entry.map_err(|err| root.error("read", &current, err))?;
325 let name = entry.file_name();
326 let Some(bytes) = crate::paths::name_bytes(&name) else {
327 return Ok(Some(current));
328 };
329 let path = crate::paths::join(&current, bytes);
330 let meta = handle
331 .symlink_metadata(&name)
332 .map_err(|err| root.error("read", &path, err))?;
333 if meta.is_dir() {
334 pending.push(path);
335 } else if !removed.contains(&fold_path(&path)) {
336 return Ok(Some(path));
337 }
338 }
339 }
340 Ok(None)
341}
342
343/// Writes a planned checkout. Returns how many paths it wrote or removed.
344/// A file of 4 MiB or more is written as it streams out of the store, a
345/// chunk at a time, so a large file is never held in memory whole.
346pub(crate) fn apply(store: &Store, root: &Root, plan: &Plan) -> Result<usize, Error> {
347 for (path, old) in &plan.removes {
348 let (parent, name) = split_last(path);
349 let Found::Here(dir) = root.open_dir(parent)? else {
350 continue;
351 };
352 let os = os_name(name).ok_or_else(|| unrepresentable(path))?;
353 let removed = match old {
354 // A submodule's directory goes only if it is empty.
355 ChangeOp::Gitlink { .. } => match dir.remove_dir(os) {
356 Err(err) if is_not_empty(&err) || err.kind() == io::ErrorKind::NotFound => Ok(()),
357 other => other,
358 },
359 _ => remove_entry(&dir, os),
360 };
361 removed.map_err(|err| root.error("remove", path, err))?;
362 }
363 for path in &plan.empty_dirs {
364 let (parent, name) = split_last(path);
365 let Found::Here(dir) = root.open_dir(parent)? else {
366 continue;
367 };
368 let os = os_name(name).ok_or_else(|| unrepresentable(path))?;
369 match dir.remove_dir(os) {
370 Ok(()) => {}
371 // Untracked files keep it, or it is gone already, or it is not a
372 // directory any more.
373 Err(err)
374 if is_not_empty(&err)
375 || err.kind() == io::ErrorKind::NotFound
376 || err.kind() == io::ErrorKind::NotADirectory => {}
377 Err(err) => return Err(root.error("remove", path, err)),
378 }
379 }
380
381 // Writes in path order, so a directory's files go out together.
382 let mut by_dir: BTreeMap<&[u8], Vec<Write<'_>>> = BTreeMap::new();
383 for (path, op) in &plan.writes {
384 let (parent, name) = split_last(path);
385 by_dir.entry(parent).or_default().push((path, name, op));
386 }
387 for (parent, files) in by_dir {
388 let dir = root.create_dirs(parent)?;
389 for (path, name, op) in files {
390 let os = os_name(name).ok_or_else(|| unrepresentable(path))?;
391 let written = match op {
392 ChangeOp::File { blob, size } | ChangeOp::Executable { blob, size } => {
393 let executable = matches!(op, ChangeOp::Executable { .. });
394 if *size >= CHUNKED_MIN {
395 stream_file(store, &dir, os, blob, executable)?
396 } else {
397 let content = read_blob(store, *blob)?;
398 write_file(&dir, os, &content, executable)
399 }
400 }
401 ChangeOp::Symlink { blob, .. } => {
402 let target = read_blob(store, *blob)?;
403 write_symlink(&dir, os, &target)
404 }
405 ChangeOp::Gitlink { .. } => match dir.symlink_metadata(os) {
406 Ok(meta) if meta.is_dir() => Ok(()),
407 _ => remove_entry(&dir, os).and_then(|()| dir.create_dir(os)),
408 },
409 ChangeOp::Delete => Ok(()),
410 };
411 written.map_err(|err| match err.kind() {
412 _ if is_not_empty(&err) => Error::Unsafe {
413 path: path.to_vec(),
414 reason: "a directory that still holds untracked files is where a file goes"
415 .to_owned(),
416 },
417 _ => root.error("write", path, err),
418 })?;
419 }
420 }
421 Ok(plan.len())
422}
423
424/// Writes the blob `blob` into `name` of `dir` as it streams out of the
425/// store. A blob that is missing, is not a blob, or does not read back as
426/// its id is the error of the outer result, and `name` is left as it was;
427/// the inner result is how writing the file went.
428fn stream_file(
429 store: &Store,
430 dir: &Dir,
431 name: &OsStr,
432 blob: &ObjectId,
433 executable: bool,
434) -> Result<io::Result<()>, Error> {
435 let mut failed = None;
436 let written = write_file_from(dir, name, executable, |out| {
437 let problem = match store.read_to(blob, out) {
438 Ok(Some((Kind::Blob, _))) => return Ok(()),
439 // Writing the file failed: an error of the checkout.
440 Err(braid_store::Error::Stream { source, .. }) => return Err(source),
441 Ok(None) => Error::from(braid_engine::Error::Missing {
442 id: *blob,
443 kind: Kind::Blob,
444 }),
445 Ok(Some((found, _))) => Error::from(braid_engine::Error::WrongKind {
446 id: *blob,
447 expected: Kind::Blob,
448 found,
449 }),
450 Err(err) => Error::from(err),
451 };
452 let shown = io::Error::other(problem.to_string());
453 failed = Some(problem);
454 Err(shown)
455 });
456 match failed {
457 Some(problem) => Err(problem),
458 None => Ok(written),
459 }
460}
461
462/// One write of a directory: the full path, the name in the directory, and
463/// what to write.
464type Write<'p> = (&'p [u8], &'p [u8], &'p ChangeOp);
465
466fn is_not_empty(err: &io::Error) -> bool {
467 // Some systems report a directory that is not empty as "exists".
468 err.kind() == io::ErrorKind::DirectoryNotEmpty || err.kind() == io::ErrorKind::AlreadyExists
469}
470
471fn unrepresentable(path: &[u8]) -> Error {
472 Error::Unsafe {
473 path: path.to_vec(),
474 reason: "this platform cannot represent the name".to_owned(),
475 }
476}
477
478#[cfg(test)]
479mod tests {
480 use super::*;
481 use braid_engine::write_tree;
482 use braid_format::{Entry, Kind, MemoryObjects};
483
484 fn file(objects: &MemoryObjects, name: &str, content: &str) -> Entry {
485 Entry {
486 name: name.as_bytes().to_vec(),
487 kind: EntryKind::File {
488 blob: objects.put(Kind::Blob, content.as_bytes()).unwrap(),
489 size: content.len() as u64,
490 },
491 }
492 }
493
494 fn planned(
495 objects: &MemoryObjects,
496 fs: FileSystem,
497 to: ObjectId,
498 ) -> (tempfile::TempDir, Result<Plan, Error>) {
499 let dir = tempfile::tempdir().unwrap();
500 let root = Root::open(dir.path()).unwrap();
501 let plan = plan(objects, &root, fs, EMPTY_TREE, to, Mode::Checked);
502 (dir, plan)
503 }
504
505 #[test]
506 fn case_twins_collide_where_case_is_ignored() {
507 let objects = MemoryObjects::new();
508 let tree = write_tree(
509 &objects,
510 vec![file(&objects, "README", "a"), file(&objects, "readme", "b")],
511 )
512 .unwrap();
513 let (_dir, plan) = planned(&objects, FileSystem::FORGIVING, tree);
514 assert!(
515 matches!(&plan, Err(Error::Collision { first, second })
516 if first == b"README" && second == b"readme"),
517 "{plan:?}"
518 );
519 // Where names are exact, both are fine.
520 let (_dir, plan) = planned(&objects, FileSystem::default(), tree);
521 assert_eq!(plan.unwrap().len(), 2);
522 }
523
524 #[test]
525 fn normalisation_twins_collide_in_subdirectories() {
526 let objects = MemoryObjects::new();
527 let inner = write_tree(
528 &objects,
529 vec![
530 file(&objects, "caf\u{e9}", "a"),
531 file(&objects, "cafe\u{301}", "b"),
532 ],
533 )
534 .unwrap();
535 let tree = write_tree(
536 &objects,
537 vec![Entry {
538 name: b"docs".to_vec(),
539 kind: EntryKind::Tree { tree: inner },
540 }],
541 )
542 .unwrap();
543 let only_normalisation = FileSystem {
544 ignores_case: false,
545 ignores_normalization: true,
546 };
547 let (_dir, plan) = planned(&objects, only_normalisation, tree);
548 assert!(matches!(plan, Err(Error::Collision { .. })), "{plan:?}");
549 }
550
551 #[test]
552 fn a_symlink_and_a_directory_that_fold_together_are_refused() {
553 // `dir` is a symlink and `DIR/x` a file: on a file system that
554 // ignores case, writing `DIR/x` would go through the symlink.
555 let objects = MemoryObjects::new();
556 let x = file(&objects, "x", "pwned");
557 let inner = write_tree(&objects, vec![x]).unwrap();
558 let tree = write_tree(
559 &objects,
560 vec![
561 Entry {
562 name: b"DIR".to_vec(),
563 kind: EntryKind::Tree { tree: inner },
564 },
565 Entry {
566 name: b"dir".to_vec(),
567 kind: EntryKind::Symlink {
568 blob: objects.put(Kind::Blob, b"/tmp").unwrap(),
569 size: 4,
570 },
571 },
572 ],
573 )
574 .unwrap();
575 let (_dir, plan) = planned(&objects, FileSystem::FORGIVING, tree);
576 assert!(matches!(plan, Err(Error::Collision { .. })), "{plan:?}");
577 }
578}