ostrya 0.2.4

Pure-Rust async reimplementation of the ostree repository library
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
//! In-memory mutable trees and their serialization to dirtree objects.
//!
//! A [`MutableTree`] is a directory under construction: a name-keyed set of
//! files (each a content checksum) and subdirectories (each a nested tree),
//! plus the dirmeta checksum for the directory itself. Building a tree in
//! memory and then calling [`Transaction::write_mtree`] serializes the dirty
//! subtrees into `(a(say)a(sayay))` dirtree objects and stages them, yielding
//! the root as a [`RepoTree`].
//!
//! Lazy hydration. [`MutableTree::from_commit`] reads only the root dirtree and
//! records the checksums of each subdirectory. A subdirectory's contents are
//! read when [`ensure_dir`](MutableTree::ensure_dir) or
//! [`subtree`](MutableTree::subtree) first descends into it, so reaching one
//! path in a large commit reads only the directories along that path.
//! Descending is `async` because it may read a dirtree; the other mutators
//! operate on already-hydrated contents and stay synchronous.
//!
//! Dirty tracking. A subtree that matches a committed dirtree and has not been
//! mutated keeps that dirtree checksum, and [`write_mtree`](Transaction::write_mtree)
//! reuses it without re-serializing or re-staging anything beneath it. A
//! subtree that has been mutated, or that has a descended (loaded) child, is
//! reassembled; identical reassembled bytes deduplicate against the store.
//!
//! Names are validated on insertion (non-empty, not `.` or `..`, no `/`) and
//! one name cannot be both a file and a directory, matching the owned-parse
//! rule the dirtree object model enforces.

use std::collections::BTreeMap;
use std::future::Future;
use std::pin::Pin;

use ostrya_core::{Checksum, DirTree, ObjectType};

use crate::error::{Error, Result};
use crate::repo::Repo;
use crate::transaction::Transaction;
use crate::tree::RepoTree;

/// A directory being assembled in memory.
///
/// Files map a name to a content checksum; subdirectories map a name to a
/// `Child`, which is either a lazy reference to a committed dirtree or a
/// materialized nested tree. `clean` holds the committed dirtree checksum while
/// this directory exactly matches a committed dirtree and has not been mutated;
/// it is cleared on mutation and set again once the directory is written.
#[derive(Debug)]
pub struct MutableTree {
    /// The dirmeta checksum for this directory, set with
    /// [`set_metadata_checksum`](MutableTree::set_metadata_checksum). Required
    /// by [`write_mtree`](Transaction::write_mtree) for every directory it
    /// emits.
    metadata_checksum: Option<Checksum>,
    /// Files by name, in byte-wise name order (the `BTreeMap` key order).
    files: BTreeMap<String, Checksum>,
    /// Subdirectories by name, in byte-wise name order.
    dirs: BTreeMap<String, Child>,
    /// The committed dirtree checksum when this directory is unmutated since
    /// load; `None` for a from-scratch or mutated directory.
    clean: Option<Checksum>,
    /// The repository lazy children are hydrated from; `None` for a
    /// from-scratch tree, which has no lazy children.
    repo: Option<Repo>,
}

/// A subdirectory entry: a committed dirtree not yet read, or a loaded tree.
#[derive(Debug)]
enum Child {
    /// A committed subdirectory whose contents have not been read. The
    /// checksums name its dirtree and dirmeta objects.
    Lazy {
        dirtree: Checksum,
        dirmeta: Checksum,
    },
    /// A materialized subtree.
    Loaded(MutableTree),
}

/// What a directory holds at a given name, for the staging-tree path walker.
pub(crate) enum ChildKind {
    /// No entry with that name.
    Absent,
    /// A file or symlink, named by its content checksum.
    File(Checksum),
    /// A materialized (loaded) subdirectory.
    Dir,
    /// A committed subdirectory not yet read; hydrate before descending.
    LazyDir {
        /// The subdirectory's dirtree checksum.
        dirtree: Checksum,
        /// The subdirectory's dirmeta checksum.
        dirmeta: Checksum,
    },
}

/// A borrowed view of a subdirectory entry, for reading a tree without mutating
/// it (the right side of a [`merge`](crate::StagingTree::merge)).
pub(crate) enum ChildRef<'a> {
    /// A materialized subtree, borrowed in place.
    Loaded(&'a MutableTree),
    /// A committed subtree named by its dirtree and dirmeta checksums.
    Lazy {
        /// The subdirectory's dirtree checksum.
        dirtree: Checksum,
        /// The subdirectory's dirmeta checksum.
        dirmeta: Checksum,
    },
}

/// An entry taken out of one directory by
/// [`take_child`](MutableTree::take_child) for reinsertion under another name
/// with [`insert_child`](MutableTree::insert_child). The node is carried as it
/// was taken, so a lazy subdirectory stays lazy.
pub(crate) struct TakenEntry {
    inner: TakenInner,
}

/// The taken node: a file entry's checksum, or a subdirectory.
enum TakenInner {
    File(Checksum),
    Dir(Child),
}

/// Which mode a descent runs in. It selects what a name the directory does not
/// hold does, and with it the variant a file of that name raises.
enum Absent {
    /// Insert an empty subdirectory of that name and return it. A file of that
    /// name is [`Error::ReplaceFileWithDir`].
    Create,
    /// Refuse that name with [`Error::PathNotFound`]. A file of that name is
    /// [`Error::NotADirectory`].
    Refuse,
}

/// The checksums a written directory contributes to its parent's dirtree entry.
struct Emitted {
    dirtree: Checksum,
    dirmeta: Checksum,
}

/// Validate one entry name as a single path component.
fn validate_name(name: &str) -> Result<()> {
    if name.is_empty() {
        return Err(Error::MutableTree("entry name is empty".into()));
    }
    if name == "." || name == ".." {
        return Err(Error::MutableTree(format!(
            "entry name {name:?} is a directory traversal"
        )));
    }
    if name.contains('/') {
        return Err(Error::MutableTree(format!(
            "entry name {name:?} contains a slash"
        )));
    }
    Ok(())
}

impl MutableTree {
    /// An empty tree with no dirmeta checksum set.
    pub fn new() -> MutableTree {
        MutableTree {
            metadata_checksum: None,
            files: BTreeMap::new(),
            dirs: BTreeMap::new(),
            clean: None,
            repo: None,
        }
    }

    /// Build a tree from a committed revision, reading only the root dirtree.
    /// Subdirectories are recorded lazily and read on first descent.
    pub async fn from_commit(repo: &Repo, rev: &str) -> Result<MutableTree> {
        let checksum = repo
            .resolve_rev(rev, true)
            .await?
            .ok_or_else(|| Error::RefNotFound(rev.to_owned()))?;
        let (commit, _) = repo.load_commit(&checksum).await?;
        MutableTree::hydrate(repo, commit.root_dirtree, commit.root_dirmeta).await
    }

    /// Read one committed dirtree into a loaded tree; its subdirectories become
    /// lazy children carrying the same repository handle.
    pub(crate) async fn hydrate(
        repo: &Repo,
        dirtree: Checksum,
        dirmeta: Checksum,
    ) -> Result<MutableTree> {
        let loaded = repo.load_dirtree(&dirtree).await?;
        let mut files = BTreeMap::new();
        for (name, csum) in loaded.files {
            files.insert(name, csum);
        }
        let mut dirs = BTreeMap::new();
        for (name, child_dirtree, child_dirmeta) in loaded.dirs {
            dirs.insert(
                name,
                Child::Lazy {
                    dirtree: child_dirtree,
                    dirmeta: child_dirmeta,
                },
            );
        }
        Ok(MutableTree {
            metadata_checksum: Some(dirmeta),
            files,
            dirs,
            clean: Some(dirtree),
            repo: Some(repo.clone()),
        })
    }

    /// Set this directory's dirmeta checksum. The directory's own dirtree does
    /// not include its dirmeta, so `clean` stays valid; the parent picks up the
    /// new dirmeta when it reassembles.
    pub fn set_metadata_checksum(&mut self, checksum: Checksum) {
        self.metadata_checksum = Some(checksum);
    }

    /// Ensure a subdirectory named `name` exists and return it, creating an
    /// empty one if absent or hydrating a lazy committed one. Fails if a file
    /// with that name exists.
    pub async fn ensure_dir(&mut self, name: &str) -> Result<&mut MutableTree> {
        self.descend(name, Absent::Create).await
    }

    /// The existing subdirectory named `name`, hydrating a lazy committed child
    /// in place. Creates nothing: an absent name is [`Error::PathNotFound`] and
    /// a file of that name is [`Error::NotADirectory`]. A symlink is a file
    /// entry in this model, so a symlink whose target is a directory is
    /// [`Error::NotADirectory`] as well: the accessor resolves one name in one
    /// directory and reads no symlink target. Both payloads are the entry name,
    /// because this layer holds no path, the same carve-out
    /// [`Error::ReplaceDirWithFile`] records for the staging tree.
    pub async fn subtree(&mut self, name: &str) -> Result<&mut MutableTree> {
        self.descend(name, Absent::Refuse).await
    }

    /// Return the subdirectory named `name`, hydrating a lazy committed child in
    /// place. `absent` selects what an absent name does, and with it the variant
    /// a file of that name raises.
    async fn descend(&mut self, name: &str, absent: Absent) -> Result<&mut MutableTree> {
        validate_name(name)?;
        if self.files.contains_key(name) {
            return Err(match absent {
                Absent::Create => Error::ReplaceFileWithDir(name.to_owned()),
                Absent::Refuse => Error::NotADirectory {
                    path: name.to_owned(),
                },
            });
        }
        match self.dirs.get(name) {
            None => {
                if matches!(absent, Absent::Refuse) {
                    return Err(Error::PathNotFound {
                        path: name.to_owned(),
                    });
                }
                let child = MutableTree {
                    metadata_checksum: None,
                    files: BTreeMap::new(),
                    dirs: BTreeMap::new(),
                    clean: None,
                    repo: self.repo.clone(),
                };
                self.dirs.insert(name.to_owned(), Child::Loaded(child));
                // Adding a subdirectory changes this directory's dirtree.
                self.clean = None;
            }
            Some(Child::Lazy { dirtree, dirmeta }) => {
                let (dirtree, dirmeta) = (*dirtree, *dirmeta);
                let repo = self.repo.clone().ok_or_else(|| {
                    Error::MutableTree(format!(
                        "cannot read subdirectory {name:?}: no repository to hydrate from"
                    ))
                })?;
                let loaded = MutableTree::hydrate(&repo, dirtree, dirmeta).await?;
                self.dirs.insert(name.to_owned(), Child::Loaded(loaded));
                // Descending does not change this directory's dirtree, so
                // `clean` stays as it was.
            }
            Some(Child::Loaded(_)) => {}
        }
        match self.dirs.get_mut(name) {
            Some(Child::Loaded(tree)) => Ok(tree),
            _ => Err(Error::MutableTree(format!(
                "subdirectory {name:?} was not materialized"
            ))),
        }
    }

    /// Set the file named `name` to the given content checksum, replacing any
    /// existing file of that name. Fails if a directory with that name exists.
    pub fn replace_file(&mut self, name: &str, checksum: Checksum) -> Result<()> {
        validate_name(name)?;
        if self.dirs.contains_key(name) {
            return Err(Error::ReplaceDirWithFile(name.to_owned()));
        }
        self.files.insert(name.to_owned(), checksum);
        self.clean = None;
        Ok(())
    }

    /// The content checksum recorded for the file (or symlink) entry `name`, if
    /// one is present. A directory entry of that name yields `None`. Used by the
    /// overlay merge to detect a base leaf an upper directory must replace.
    pub(crate) fn file_checksum(&self, name: &str) -> Option<Checksum> {
        self.files.get(name).copied()
    }

    /// Remove every file and subdirectory, marking the directory dirty. Used by
    /// the overlay merge to clear an opaque directory before ingesting the
    /// upper entries fresh.
    pub(crate) fn clear_children(&mut self) {
        if !self.files.is_empty() || !self.dirs.is_empty() {
            self.files.clear();
            self.dirs.clear();
            self.clean = None;
        }
    }

    /// Take the entry named `name` out of this directory, file or
    /// subdirectory, for reinsertion under another name with
    /// [`insert_child`](MutableTree::insert_child). Marks this directory
    /// dirty. The taken node itself is untouched, so a moved subtree keeps
    /// its own `clean` state and a lazy child stays lazy. An absent name
    /// yields `None`.
    pub(crate) fn take_child(&mut self, name: &str) -> Option<TakenEntry> {
        let inner = if let Some(checksum) = self.files.remove(name) {
            TakenInner::File(checksum)
        } else if let Some(child) = self.dirs.remove(name) {
            TakenInner::Dir(child)
        } else {
            return None;
        };
        self.clean = None;
        Some(TakenEntry { inner })
    }

    /// Insert a taken entry under `name`, marking this directory dirty. The
    /// name must be fresh: an existing entry of that name is refused, which
    /// keeps the one-name-one-entry rule every other mutator holds. A moved
    /// lazy child hydrates from this directory's own repository handle: every
    /// directory takes that handle from its parent, and a lazy child exists
    /// only under a tree [`hydrate`](MutableTree::hydrate) built, so a
    /// directory that can receive one always holds a handle.
    pub(crate) fn insert_child(&mut self, name: &str, entry: TakenEntry) -> Result<()> {
        validate_name(name)?;
        if self.files.contains_key(name) || self.dirs.contains_key(name) {
            return Err(Error::MutableTree(format!(
                "an entry named {name:?} already exists"
            )));
        }
        match entry.inner {
            TakenInner::File(checksum) => {
                self.files.insert(name.to_owned(), checksum);
            }
            TakenInner::Dir(child) => {
                self.dirs.insert(name.to_owned(), child);
            }
        }
        self.clean = None;
        Ok(())
    }

    /// Remove the file or subdirectory named `name`. With `allow_noent`, an
    /// absent entry is not an error.
    pub fn remove(&mut self, name: &str, allow_noent: bool) -> Result<()> {
        let removed = self.files.remove(name).is_some() || self.dirs.remove(name).is_some();
        if removed {
            self.clean = None;
        } else if !allow_noent {
            return Err(Error::MutableTree(format!(
                "no entry named {name:?} to remove"
            )));
        }
        Ok(())
    }

    /// This directory's dirmeta checksum, if set. A tree whose root has none
    /// cannot be written, which is how a source list that supplied no root
    /// directory is recognized.
    pub fn metadata_checksum(&self) -> Option<Checksum> {
        self.metadata_checksum
    }

    /// Record a committed subdirectory at `name` without reading it, so the
    /// overlay reads only the paths a later source names. `repo` is the
    /// repository the child is read from when a later source does descend into
    /// it.
    ///
    /// A name this tree already holds as a file is refused, which is the rule
    /// every other mutator follows.
    pub(crate) fn insert_lazy_dir(
        &mut self,
        name: &str,
        dirtree: Checksum,
        dirmeta: Checksum,
        repo: &Repo,
    ) -> Result<()> {
        validate_name(name)?;
        if self.files.contains_key(name) {
            return Err(Error::ReplaceFileWithDir(name.to_owned()));
        }
        if self.repo.is_none() {
            self.repo = Some(repo.clone());
        }
        self.dirs
            .insert(name.to_owned(), Child::Lazy { dirtree, dirmeta });
        self.clean = None;
        Ok(())
    }

    /// The repository this tree hydrates lazy children from, if any.
    pub(crate) fn repo(&self) -> Option<Repo> {
        self.repo.clone()
    }

    /// What this directory holds at `name`, for the staging-tree path walker.
    pub(crate) fn child_kind(&self, name: &str) -> ChildKind {
        if let Some(checksum) = self.files.get(name) {
            return ChildKind::File(*checksum);
        }
        match self.dirs.get(name) {
            Some(Child::Loaded(_)) => ChildKind::Dir,
            Some(Child::Lazy { dirtree, dirmeta }) => ChildKind::LazyDir {
                dirtree: *dirtree,
                dirmeta: *dirmeta,
            },
            None => ChildKind::Absent,
        }
    }

    /// Navigate to the loaded directory at the literal component `path`, or
    /// `None` if any component is missing or is not a loaded directory. Lazy
    /// children must be hydrated by the caller before they can be traversed.
    pub(crate) fn dir_at(&self, path: &[String]) -> Option<&MutableTree> {
        let mut cur = self;
        for name in path {
            match cur.dirs.get(name) {
                Some(Child::Loaded(child)) => cur = child,
                _ => return None,
            }
        }
        Some(cur)
    }

    /// The mutable counterpart of [`dir_at`](MutableTree::dir_at).
    pub(crate) fn dir_at_mut(&mut self, path: &[String]) -> Option<&mut MutableTree> {
        let mut cur = self;
        for name in path {
            match cur.dirs.get_mut(name) {
                Some(Child::Loaded(child)) => cur = child,
                _ => return None,
            }
        }
        Some(cur)
    }

    /// Replace a lazy child `name` with its hydrated subtree. The directory's
    /// own dirtree is unchanged, so `clean` stays as it was.
    pub(crate) fn install_hydrated_child(&mut self, name: &str, loaded: MutableTree) {
        self.dirs.insert(name.to_owned(), Child::Loaded(loaded));
    }

    /// Set the dirmeta checksum recorded for the subdirectory `name` without
    /// hydrating a lazy child: a loaded child takes it as its own metadata
    /// checksum, and a lazy child's entry is rewritten in place keeping its
    /// dirtree, because the child's contents do not change. This directory's
    /// dirtree embeds the child's dirmeta, so a changed lazy entry marks it
    /// dirty; a loaded child already forces its parent to reassemble.
    pub(crate) fn set_child_dirmeta(&mut self, name: &str, dirmeta: Checksum) -> Result<()> {
        match self.dirs.get_mut(name) {
            Some(Child::Loaded(child)) => {
                child.metadata_checksum = Some(dirmeta);
                Ok(())
            }
            Some(Child::Lazy { dirmeta: dm, .. }) => {
                if *dm != dirmeta {
                    *dm = dirmeta;
                    self.clean = None;
                }
                Ok(())
            }
            None => Err(Error::MutableTree(format!(
                "no subdirectory named {name:?}"
            ))),
        }
    }

    /// Insert a fresh empty loaded subdirectory named `name` with the given
    /// dirmeta checksum, replacing any existing entry of that name. Marks this
    /// directory dirty.
    pub(crate) fn insert_empty_dir(&mut self, name: &str, dirmeta: Option<Checksum>) {
        let child = MutableTree {
            metadata_checksum: dirmeta,
            files: BTreeMap::new(),
            dirs: BTreeMap::new(),
            clean: None,
            repo: self.repo.clone(),
        };
        self.files.remove(name);
        self.dirs.insert(name.to_owned(), Child::Loaded(child));
        self.clean = None;
    }

    /// The file entries of this directory, byte-wise name-sorted.
    pub(crate) fn file_entries(&self) -> impl Iterator<Item = (&str, Checksum)> {
        self.files
            .iter()
            .map(|(name, checksum)| (name.as_str(), *checksum))
    }

    /// The subdirectory entries of this directory as borrowed views, byte-wise
    /// name-sorted.
    pub(crate) fn dir_entries(&self) -> impl Iterator<Item = (&str, ChildRef<'_>)> {
        self.dirs.iter().map(|(name, child)| {
            let view = match child {
                Child::Loaded(tree) => ChildRef::Loaded(tree),
                Child::Lazy { dirtree, dirmeta } => ChildRef::Lazy {
                    dirtree: *dirtree,
                    dirmeta: *dirmeta,
                },
            };
            (name.as_str(), view)
        })
    }
}

impl Default for MutableTree {
    fn default() -> MutableTree {
        MutableTree::new()
    }
}

impl Transaction {
    /// Serialize the dirty subtrees of `mtree` into dirtree objects, stage
    /// them, and return the root as a [`RepoTree`].
    ///
    /// The walk is post-order over dirty subtrees. An unmutated subtree keeps
    /// its committed dirtree checksum and is neither re-serialized nor
    /// re-staged. Each written directory requires its dirmeta checksum set;
    /// an unset checksum is an error naming the directory's path.
    ///
    /// The root it returns reads back through this transaction alone, the same
    /// constraint [`Transaction::read_dir`](Transaction::read_dir) states:
    /// passing it to [`RepoTree::read_dir`](crate::RepoTree::read_dir) before
    /// the transaction commits reaches
    /// [`Error::ObjectNotFound`] for the staged
    /// dirtree.
    pub async fn write_mtree(&self, mtree: &mut MutableTree) -> Result<RepoTree> {
        let emitted = write_node(self, mtree, "/".to_owned()).await?;
        Ok(RepoTree::from_parts(
            self.repo().clone(),
            emitted.dirtree,
            emitted.dirmeta,
        ))
    }
}

/// The boxed future type for the recursive post-order walk. Async recursion
/// needs indirection, so each level returns a boxed future.
type NodeFuture<'a> = Pin<Box<dyn Future<Output = Result<Emitted>> + Send + 'a>>;

/// Resolve one directory node: reuse its dirtree checksum when clean, otherwise
/// assemble and stage a dirtree from its files and children.
fn write_node<'a>(txn: &'a Transaction, node: &'a mut MutableTree, path: String) -> NodeFuture<'a> {
    Box::pin(async move {
        let dirmeta = node.metadata_checksum.ok_or_else(|| {
            Error::MutableTree(format!("directory {path} has no dirmeta checksum set"))
        })?;

        // A directory with no descended children and an intact committed
        // checksum is reused untouched; nothing beneath it is read or staged.
        let has_loaded_child = node
            .dirs
            .values()
            .any(|child| matches!(child, Child::Loaded(_)));
        if let Some(dirtree) = node.clean
            && !has_loaded_child
        {
            return Ok(Emitted { dirtree, dirmeta });
        }

        let mut tree = DirTree::default();
        for (name, checksum) in &node.files {
            tree.files.push((name.clone(), *checksum));
        }
        for (name, child) in node.dirs.iter_mut() {
            let emitted = match child {
                Child::Lazy { dirtree, dirmeta } => Emitted {
                    dirtree: *dirtree,
                    dirmeta: *dirmeta,
                },
                Child::Loaded(subtree) => write_node(txn, subtree, join_path(&path, name)).await?,
            };
            tree.dirs
                .push((name.clone(), emitted.dirtree, emitted.dirmeta));
        }

        let bytes = tree.serialize()?;
        let dirtree = txn
            .write_metadata(ObjectType::DirTree, None, &bytes)
            .await?;
        node.clean = Some(dirtree);
        Ok(Emitted { dirtree, dirmeta })
    })
}

/// Join a parent path and a child name for error messages.
fn join_path(parent: &str, name: &str) -> String {
    if parent == "/" {
        format!("/{name}")
    } else {
        format!("{parent}/{name}")
    }
}

/// A mutable tree moves freely across tasks and threads.
const _: fn() = || {
    fn assert_send_sync<T: Send + Sync>() {}
    assert_send_sync::<MutableTree>();
};

#[cfg(test)]
mod tests {
    use super::*;
    use crate::CreateOptions;
    use ostrya_core::RepoMode;
    use ostrya_rt::block_on;

    /// A throwaway directory removed on drop.
    struct Scratch(std::path::PathBuf);

    impl Scratch {
        fn new(tag: &str) -> Scratch {
            use std::sync::atomic::{AtomicU64, Ordering};
            static COUNTER: AtomicU64 = AtomicU64::new(0);
            let n = COUNTER.fetch_add(1, Ordering::Relaxed);
            let dir =
                std::env::temp_dir().join(format!("ostrya-mtree-{}-{tag}-{n}", std::process::id()));
            let _ = std::fs::remove_dir_all(&dir);
            std::fs::create_dir_all(&dir).unwrap();
            Scratch(dir)
        }
    }

    impl Drop for Scratch {
        fn drop(&mut self) {
            let _ = std::fs::remove_dir_all(&self.0);
        }
    }

    /// `insert_lazy_dir` refuses the same names `replace_file` and `ensure_dir`
    /// refuse, and records nothing for a refused name.
    #[test]
    fn insert_lazy_dir_rejects_invalid_names() {
        let scratch = Scratch::new("lazy-names");
        block_on(async {
            let repo = Repo::create(
                &scratch.0.join("repo"),
                CreateOptions::new(RepoMode::BareUser),
            )
            .await
            .unwrap();
            let some = Checksum::from_hex(
                "0000000000000000000000000000000000000000000000000000000000000000",
            )
            .unwrap();

            let mut mtree = MutableTree::new();
            for name in ["", ".", "..", "a/b"] {
                assert!(
                    matches!(
                        mtree.insert_lazy_dir(name, some, some, &repo),
                        Err(Error::MutableTree(_))
                    ),
                    "insert_lazy_dir rejects {name:?}"
                );
            }
            assert!(mtree.dirs.is_empty(), "a refused name records no child");
            assert!(
                mtree.repo.is_none(),
                "a refused name adopts no repository handle"
            );
        });
    }
}