OXYGENHUB
# b63fc7a77fc6 oxygen / crates / oxy-core / src / repo / snapshot.rs
118.2 KiB · Rust · last changed Snapshots: large new files left out and named; past working copies expire 25 days ago source blame history raw
1
//! Working-copy snapshots, commits, and the change builder (spec §12.3).
2
3
use super::*;
4
use crate::objects::AtomRef;
5
6
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
7
pub enum ChangeStatus {
8
    Added,
9
    Modified,
10
    Removed,
11
    /// Moved from another path (detected by similarity, tracked as a placement change).
12
    Renamed,
13
    ModeChanged,
14
    /// The file is conflicted in the base state and still contains conflict markers.
15
    ConflictEdited,
16
    /// The file was conflicted in the base state and the working copy resolves it.
17
    Resolved,
18
}
19
20
/// Lines that mark a conflict region in a materialized file (spec §9.5).
21
pub fn has_conflict_markers(content: &[u8]) -> bool {
22
    split_lines(content).iter().any(|l| {
23
        l.starts_with(b"<<<<<<< oxy conflict")
24
            || l.starts_with(b"======= oxy conflict")
25
            || l.starts_with(b">>>>>>> oxy conflict")
26
    })
27
}
28
29
#[derive(Clone, Debug, PartialEq, Eq)]
30
pub struct PathStatus {
31
    pub path: String,
32
    pub status: ChangeStatus,
33
}
34
35
/// Operations of a change built from the working directory against a base.
36
pub(crate) struct BuiltChange {
37
    pub tree_ops: Vec<TreeOp>,
38
    pub edits: Vec<Edit>,
39
    pub contributors: Vec<ChangeHash>,
40
    pub resolves: bool,
41
    pub statuses: Vec<PathStatus>,
42
    /// The stored blob of every opaque path, for the manifest's stat cache.
43
    pub blobs: HashMap<String, ObjectRef>,
44
}
45
46
/// Result of snapshotting the working copy.
47
pub struct SnapshotResult {
48
    /// The working-copy change's hash; for a commit's own snapshot, which
49
    /// does not encode it, the hash it had before.
50
    pub wc_hash: ChangeHash,
51
    pub wc: Change,
52
    /// The base state (closure of the working-copy change's dependencies).
53
    pub base: State,
54
    pub base_snapshot: Snapshot,
55
    pub statuses: Vec<PathStatus>,
56
    /// Whether the snapshot rewrote the working-copy change.
57
    pub changed: bool,
58
    /// Whether the working copy resolves conflicts of its base (spec §9.6).
59
    pub resolves: bool,
60
    /// Changes that contributed to the conflicts being resolved.
61
    pub contributors: Vec<ChangeHash>,
62
    /// The `.oxyattributes` in force on disk, from the files the walk read.
63
    pub(crate) attributes: crate::attributes::Attributes,
64
    /// Folders holding a repository of their own (`.git` or `.oxy`) that
65
    /// are not subrepos, so nothing in them is tracked (oxygen#43).
66
    pub untracked_nested: Vec<String>,
67
    /// A commit's snapshot leaves the manifest to the commit, which writes
68
    /// it once with the new base's graph keys.
69
    pub(crate) manifest: Option<PendingManifest>,
70
}
71
72
/// The manifest a commit's snapshot would have written, as of the moment
73
/// it would have written it (that moment is the racy-window stamp).
74
pub(crate) struct PendingManifest {
75
    entries: BTreeMap<String, FsEntry>,
76
    blobs: HashMap<String, ObjectRef>,
77
    dirs: Option<super::WalkedDirs>,
78
    written: u128,
79
}
80
81
pub fn is_binary(content: &[u8]) -> bool {
82
    content[..content.len().min(BINARY_SNIFF)].contains(&0)
83
}
84
85
impl Repo {
86
    /// Diff the files on disk against `base` and build the operations of a
87
    /// change from `base` to the working directory. `reuse` maps paths to the
88
    /// NodeIds an earlier version of the same change assigned to new paths.
89
    pub(crate) fn build_against(
90
        &self,
91
        base: &State,
92
        base_snapshot: &Snapshot,
93
        reuse: HashMap<String, (NodeId, NodeKind)>,
94
    ) -> Result<BuiltChange> {
95
        let mut fs_entries =
96
            self.walk_working_copy_with(None, &Self::tracked_kinds(base_snapshot), None)?;
97
        self.platform_normalize(&mut fs_entries, base_snapshot);
98
        self.build_from_entries(base, base_snapshot, reuse, &fs_entries)
99
    }
100
101
    /// Read the working copy as the platform left it (spec §7.7): without
102
    /// executable bits a file keeps the bit it has in the base, and without
103
    /// symbolic links a plain file where the base has a symlink is that
104
    /// symlink, written out as its target, not a new file.
105
    fn platform_normalize(&self, entries: &mut BTreeMap<String, FsEntry>, base: &Snapshot) {
106
        let p = self.platform;
107
        if p.exec_bits && p.symlinks {
108
            return;
109
        }
110
        for (path, e) in entries.iter_mut() {
111
            let Some(f) = base.files.get(path) else {
112
                continue;
113
            };
114
            if !p.symlinks && f.kind == NodeKind::Symlink && e.kind == NodeKind::File {
115
                e.kind = NodeKind::Symlink;
116
                e.exec = false;
117
            }
118
            if !p.exec_bits && f.kind == NodeKind::File && e.kind == NodeKind::File {
119
                e.exec = f.mode.exec;
120
            }
121
        }
122
    }
123
124
    /// Like `build_against`, for files given in memory (imports).
125
    pub(crate) fn build_from_entries(
126
        &self,
127
        base: &State,
128
        base_snapshot: &Snapshot,
129
        reuse: HashMap<String, (NodeId, NodeKind)>,
130
        fs_entries: &BTreeMap<String, FsEntry>,
131
    ) -> Result<BuiltChange> {
132
        self.build_from_entries_resolving(base, base_snapshot, reuse, fs_entries, &HashSet::new())
133
    }
134
135
    /// Like `build_from_entries`, settling the replace conflicts of the
136
    /// opaque files in `resolve` to their content (spec §9.3, §9.6): a
137
    /// caller that knows the user chose it, such as the hub's resolver. A
138
    /// snapshot never settles one on its own, since a checkout writes one
139
    /// candidate at the path.
140
    pub(crate) fn build_from_entries_resolving(
141
        &self,
142
        base: &State,
143
        base_snapshot: &Snapshot,
144
        reuse: HashMap<String, (NodeId, NodeKind)>,
145
        fs_entries: &BTreeMap<String, FsEntry>,
146
        resolve: &HashSet<String>,
147
    ) -> Result<BuiltChange> {
148
        self.build_from_entries_with(
149
            base,
150
            base_snapshot,
151
            reuse,
152
            fs_entries,
153
            resolve,
154
            Scope::default(),
155
        )
156
    }
157
158
    /// `build_from_entries` whose new nodes take identifiers derived from
159
    /// `seed` and their paths instead of random ones, so the same input
160
    /// always builds the same change (a Git import, spec §23).
161
    ///
162
    /// With `dir_needed`, the snapshot and entries hold only the paths the
163
    /// import touches (and the directories a removal may leave empty); a
164
    /// directory stays while `dir_needed` says the new tree has something
165
    /// under it.
166
    pub(crate) fn build_from_entries_seeded(
167
        &self,
168
        base: &State,
169
        base_snapshot: &Snapshot,
170
        fs_entries: &BTreeMap<String, FsEntry>,
171
        seed: [u8; 32],
172
        dir_needed: Option<&dyn Fn(&str) -> bool>,
173
    ) -> Result<BuiltChange> {
174
        self.build_from_entries_with(
175
            base,
176
            base_snapshot,
177
            HashMap::new(),
178
            fs_entries,
179
            &HashSet::new(),
180
            Scope {
181
                seed: Some(seed),
182
                dir_needed,
183
            },
184
        )
185
    }
186
187
    /// `build_from_entries` for a snapshot most of whose files are known
188
    /// unchanged (oxygen#41): only the paths that may differ are built
189
    /// (files read rather than known unchanged, base files gone from disk,
190
    /// and the directories those may leave empty), against a snapshot of
191
    /// just those, so a large tree with a few edits costs what they touch.
192
    fn build_changed_only(
193
        &self,
194
        base: &State,
195
        base_snapshot: &Snapshot,
196
        reuse: HashMap<String, (NodeId, NodeKind)>,
197
        fs_entries: &BTreeMap<String, FsEntry>,
198
    ) -> Result<BuiltChange> {
199
        let pick = crate::timing::phase("snapshot:   of which picking the changed");
200
        // A file known unchanged may still have changed mode: that alters
201
        // neither its size nor its time.
202
        let changed: BTreeMap<String, FsEntry> = join(fs_entries, &base_snapshot.files)
203
            .filter_map(|(p, e, f)| {
204
                let e = e?;
205
                (!e.unchanged || f.is_none_or(|f| f.kind != e.kind || f.mode.exec != e.exec))
206
                    .then(|| (p.clone(), e.clone()))
207
            })
208
            .collect();
209
        let mut files: BTreeMap<String, crate::state::FileState> = BTreeMap::new();
210
        for p in changed.keys() {
211
            if let Some(f) = base_snapshot.files.get(p) {
212
                files.insert(p.clone(), f.clone());
213
            }
214
        }
215
        // Paths the base has and the disk does not.
216
        let gone = join(&base_snapshot.files, fs_entries)
217
            .filter_map(|(p, f, e)| (e.is_none()).then_some((p, f?)));
218
        for (p, f) in gone {
219
            if f.kind == NodeKind::Dir {
220
                continue;
221
            }
222
            files.insert(p.clone(), f.clone());
223
            let mut end = p.len();
224
            while let Some(i) = p[..end].rfind('/') {
225
                let dir = &p[..i];
226
                if files.contains_key(dir) {
227
                    break;
228
                }
229
                if let Some(d) = base_snapshot.files.get(dir) {
230
                    files.insert(dir.to_string(), d.clone());
231
                }
232
                end = i;
233
            }
234
        }
235
        let part = Snapshot {
236
            tree: base_snapshot.tree.clone(),
237
            files,
238
            unrendered: BTreeSet::new(),
239
        };
240
        drop(pick);
241
        let _build = crate::timing::phase("snapshot:   of which building the change");
242
        // Whether anything on disk is under `dir`.
243
        let dir_needed = |dir: &str| {
244
            let prefix = format!("{dir}/");
245
            fs_entries
246
                .range(prefix.clone()..)
247
                .next()
248
                .is_some_and(|(k, _)| k.starts_with(&prefix))
249
        };
250
        self.build_from_entries_with(
251
            base,
252
            &part,
253
            reuse,
254
            &changed,
255
            &HashSet::new(),
256
            Scope {
257
                seed: None,
258
                dir_needed: Some(&dir_needed),
259
            },
260
        )
261
    }
262
263
    fn build_from_entries_with(
264
        &self,
265
        base: &State,
266
        base_snapshot: &Snapshot,
267
        reuse: HashMap<String, (NodeId, NodeKind)>,
268
        fs_entries: &BTreeMap<String, FsEntry>,
269
        resolve: &HashSet<String>,
270
        scope: Scope,
271
    ) -> Result<BuiltChange> {
272
        let Scope { seed, dir_needed } = scope;
273
        let mut laps = crate::timing::Laps::start();
274
        // Attributes come from the files being committed, so a new
275
        // `.oxyattributes` applies to the same change that adds it.
276
        let attrs = crate::attributes::Attributes::from_files(
277
            fs_entries
278
                .iter()
279
                .filter(|(p, _)| p.as_str() == ".oxyattributes" || p.ends_with("/.oxyattributes"))
280
                .map(|(p, e)| (p.as_str(), e.content.as_slice())),
281
        );
282
        let mut b = ChangeBuilder::new(base, base_snapshot, reuse).with_attributes(attrs);
283
        b.resolve = resolve.clone();
284
        b.node_seed = seed;
285
        laps.lap("build: builder");
286
        // Rename detection (spec §7.1, §23): a removed file and an added file
287
        // of the same kind whose contents are at least half alike become one
288
        // move of the same node, so identity survives across the rename.
289
        let renames = detect_renames(base_snapshot, fs_entries, |p| self.in_scope(p));
290
        let renamed_from: HashMap<&str, &str> = renames
291
            .iter()
292
            .map(|(old, new)| (new.as_str(), old.as_str()))
293
            .collect();
294
        let renamed_to: HashMap<&str, &str> = renames
295
            .iter()
296
            .map(|(old, new)| (old.as_str(), new.as_str()))
297
            .collect();
298
        laps.lap("build: renames");
299
        b.diff_in_parallel(fs_entries);
300
        laps.lap("build: diffs");
301
        for (path, fs_entry) in fs_entries {
302
            match base_snapshot.files.get(path) {
303
                None => match renamed_from.get(path.as_str()) {
304
                    Some(old) => {
305
                        b.move_path(self, old, path, fs_entry, &base_snapshot.files[*old])?
306
                    }
307
                    None => b.add_path(self, path, fs_entry)?,
308
                },
309
                Some(expected) => b.update_path(self, path, fs_entry, expected)?,
310
            }
311
        }
312
        laps.lap("build: paths");
313
        // A directory stays while anything under it exists or is out of
314
        // scope: the directories above each such path, gathered once.
315
        let mut needed_dirs: HashSet<&str> = HashSet::new();
316
        fn parents_of<'a>(p: &'a str, set: &mut HashSet<&'a str>) {
317
            let mut end = p.len();
318
            while let Some(i) = p[..end].rfind('/') {
319
                if !set.insert(&p[..i]) {
320
                    break;
321
                }
322
                end = i;
323
            }
324
        }
325
        for p in fs_entries.keys() {
326
            parents_of(p, &mut needed_dirs);
327
        }
328
        for p in base_snapshot.files.keys() {
329
            if !self.in_scope(p) {
330
                parents_of(p, &mut needed_dirs);
331
            }
332
        }
333
        for (path, expected) in &base_snapshot.files {
334
            if fs_entries.contains_key(path)
335
                || !self.in_scope(path)
336
                || renamed_to.contains_key(path.as_str())
337
            {
338
                continue;
339
            }
340
            let still_needed = expected.kind == NodeKind::Dir
341
                && match dir_needed {
342
                    Some(f) => f(path),
343
                    None => needed_dirs.contains(path.as_str()),
344
                };
345
            if !still_needed {
346
                b.remove_path(path, expected);
347
            }
348
        }
349
        laps.lap("build: removals");
350
        if seed.is_some() {
351
            b.retire_stray_placements();
352
        }
353
        laps.lap("build: stray placements");
354
        let mut statuses = b.statuses;
355
        statuses.sort_by(|a, b| a.path.cmp(&b.path));
356
        Ok(BuiltChange {
357
            tree_ops: b.tree_ops,
358
            edits: b.edits,
359
            contributors: b.contributors.into_iter().collect(),
360
            resolves: b.resolves,
361
            statuses,
362
            blobs: b.blobs,
363
        })
364
    }
365
366
    /// Store a change and, when `core.sign = change` and we are its author,
367
    /// sign it. A rewritten change by another author is stored unsigned: only
368
    /// its author (or a delegate) can vouch for it.
369
    pub(crate) fn store_signed(&self, change: &Change) -> Result<ChangeHash> {
370
        let ours = change.author == self.author();
371
        if self.config.sign_changes && ours && self.secret_key()?.is_none() {
372
            return fail("core.sign is \"change\" but no secret key is available for author.key");
373
        }
374
        let storing = crate::timing::phase("store: the change");
375
        let hash = self.store.put_change(change)?;
376
        drop(storing);
377
        if self.config.sign_changes && ours {
378
            let _t = crate::timing::phase("store: sign it");
379
            self.sign_change(&hash)?;
380
        }
381
        Ok(hash)
382
    }
383
384
    /// Snapshot the working copy into the working-copy change (spec §12.3).
385
    /// The result carries the full base state and its whole rendering.
386
    pub fn snapshot(&self, command: &str) -> Result<SnapshotResult> {
387
        self.snapshot_as(command, false, false)
388
    }
389
390
    /// Snapshot the working copy as [`Repo::snapshot`] does, for commands
391
    /// that need its statuses, conflicts and base history, and the graphs
392
    /// of the files it changes: status, log, show, commit, diff, hunks and
393
    /// discard. Text files known unchanged since the last manifest are
394
    /// neither read nor rendered: the result's `base` is a history-only
395
    /// state without their graphs, and its `base_snapshot` lists them in
396
    /// `unrendered` with empty bytes. They are never conflicted, and no
397
    /// change the working copy makes touches them.
398
    pub fn snapshot_status(&self, command: &str) -> Result<SnapshotResult> {
399
        self.snapshot_as(command, true, false)
400
    }
401
402
    /// `snapshot_as`; `for_commit` writes the manifest even where a status
403
    /// would not bother (an edited file is read next time whatever it
404
    /// says), since after the commit that file is unchanged, and records no
405
    /// operation: the commit's own, recorded straight after, replaces the
406
    /// working copy, so the snapshot's would cost a durable write for
407
    /// nothing. Should the commit fail, the files are still on disk and the
408
    /// next snapshot finds them.
409
    fn snapshot_as(
410
        &self,
411
        command: &str,
412
        partial: bool,
413
        for_commit: bool,
414
    ) -> Result<SnapshotResult> {
415
        let _lock = self.lock_snapshot()?;
416
        let batch = self.store.begin_batch()?;
417
        let result = self.snapshot_locked(command, partial, for_commit);
418
        batch.finish()?;
419
        result
420
    }
421
422
    fn snapshot_locked(
423
        &self,
424
        command: &str,
425
        partial: bool,
426
        for_commit: bool,
427
    ) -> Result<SnapshotResult> {
428
        let _all = crate::timing::phase("snapshot");
429
        let (op_ref, op) = self.head_op()?;
430
        let (old_hash, old_wc) = self.working_copy()?;
431
        // The base's history first: its graph keys say which files the
432
        // manifest already knows equal to it.
433
        let mut base = {
434
            let _t = crate::timing::phase("snapshot: load base history");
435
            self.load_state_indexed(&old_wc.deps)?
436
        };
437
        let view = {
438
            let _t = crate::timing::phase("snapshot: tree view");
439
            base.tree().view()
440
        };
441
        let manifest = {
442
            let _t = crate::timing::phase("snapshot: read manifest");
443
            self.read_manifest()?.map(|(_, _, m)| m)
444
        };
445
        let tracked: BTreeMap<String, (NodeKind, Option<ObjectRef>)> = {
446
            let _t = crate::timing::phase("snapshot: tracked paths");
447
            // In the view's path order, so the map is built without searching.
448
            view.entries
449
                .iter()
450
                .filter(|(_, e)| e.kind != NodeKind::Dir)
451
                .map(|(p, e)| {
452
                    let blob = if e.kind != NodeKind::File || e.mode.opaque {
453
                        base.live_blobs(&e.node).first().copied()
454
                    } else {
455
                        None
456
                    };
457
                    (p.clone(), (e.kind, blob))
458
                })
459
                .collect()
460
        };
461
        // A text file's graph key, worked out when the walk asks for it.
462
        let key_of = |p: &str| -> Option<[u8; 32]> {
463
            let e = view.entries.get(p)?;
464
            if e.kind != NodeKind::File || e.mode.opaque {
465
                return None;
466
            }
467
            base.graph_key(&e.node)
468
        };
469
        let mut fs_entries = {
470
            let _t = crate::timing::phase("snapshot: read working copy");
471
            self.walk_working_copy_with(manifest.as_deref(), &tracked, Some(&key_of))?
472
        };
473
        // The keys of the files read, before building graphs drops them: a
474
        // file found equal to its base rendering keeps its key.
475
        let keys: HashMap<String, [u8; 32]> = fs_entries
476
            .iter()
477
            .filter(|(_, e)| !e.unchanged && e.kind == NodeKind::File)
478
            .filter_map(|(p, _)| Some((p.clone(), key_of(p)?)))
479
            .collect();
480
        let base_snapshot = {
481
            let _t = crate::timing::phase("snapshot: load and render base");
482
            if partial {
483
                let sets = crate::timing::phase("snapshot:   of which choosing graphs");
484
                // Every file but those on disk known unchanged.
485
                let need: Vec<(&str, NodeId)> = join(&view.entries, &fs_entries)
486
                    .filter_map(|(p, v, f)| {
487
                        let v = v?;
488
                        (v.kind == NodeKind::File && !f.is_some_and(|f| f.unchanged))
489
                            .then_some((p.as_str(), v.node))
490
                    })
491
                    .collect();
492
                let render: std::collections::HashSet<&str> =
493
                    need.iter().map(|(p, _)| *p).collect();
494
                let need: Vec<NodeId> = need.iter().map(|(_, n)| *n).collect();
495
                drop(sets);
496
                {
497
                    let _t = crate::timing::phase("snapshot:   of which building graphs");
498
                    self.load_graphs_of(&mut base, &need)?;
499
                }
500
                let _t = crate::timing::phase("snapshot:   of which rendering");
501
                base.materialize_only(&render)
502
            } else {
503
                self.load_all_graphs(&mut base)?;
504
                base.materialize()
505
            }
506
        };
507
508
        // Reuse the NodeIds the previous working-copy version assigned to new
509
        // paths, so an unchanged working copy hashes identically (spec §12.3).
510
        let reuse = added_node_paths(&old_wc, &base_snapshot);
511
        self.platform_normalize(&mut fs_entries, &base_snapshot);
512
        let built = {
513
            let _t = crate::timing::phase("snapshot: diff against base");
514
            if partial && self.config.sparse_paths.is_empty() {
515
                #[cfg(test)]
516
                let full =
517
                    self.build_from_entries(&base, &base_snapshot, reuse.clone(), &fs_entries)?;
518
                let built = self.build_changed_only(&base, &base_snapshot, reuse, &fs_entries)?;
519
                #[cfg(test)]
520
                {
521
                    // New nodes take random identifiers: compare them by
522
                    // order of appearance.
523
                    let norm = |b: &BuiltChange| {
524
                        let text = format!("{:?} {:?} {:?}", b.tree_ops, b.edits, b.statuses);
525
                        let mut seen: Vec<String> = Vec::new();
526
                        let mut out = String::new();
527
                        let mut rest = text.as_str();
528
                        while let Some(i) = rest.find("NodeId(") {
529
                            out.push_str(&rest[..i]);
530
                            let end = i + rest[i..].find(')').unwrap() + 1;
531
                            let id = rest[i..end].to_string();
532
                            let n = seen.iter().position(|x| *x == id).unwrap_or_else(|| {
533
                                seen.push(id);
534
                                seen.len() - 1
535
                            });
536
                            out.push_str(&format!("N{n}"));
537
                            rest = &rest[end..];
538
                        }
539
                        out.push_str(rest);
540
                        out
541
                    };
542
                    assert_eq!(
543
                        norm(&built),
544
                        norm(&full),
545
                        "a changed-only build is the full one"
546
                    );
547
                }
548
                built
549
            } else {
550
                self.build_from_entries(&base, &base_snapshot, reuse, &fs_entries)?
551
            }
552
        };
553
        // Text files found equal to an unconflicted base rendering keep its
554
        // graph key, so the next snapshot need not read or render them.
555
        {
556
            let changed: HashSet<&str> = built.statuses.iter().map(|s| s.path.as_str()).collect();
557
            for (p, e) in fs_entries.iter_mut() {
558
                if e.unchanged || e.kind != NodeKind::File || changed.contains(p.as_str()) {
559
                    continue;
560
                }
561
                e.graph_key = match base_snapshot.files.get(p).map(|f| &f.content) {
562
                    Some(FileContent::Text {
563
                        bytes,
564
                        materialized,
565
                    }) if !materialized.is_conflicted() && *bytes == *e.content => {
566
                        keys.get(p).copied()
567
                    }
568
                    _ => None,
569
                };
570
            }
571
        }
572
573
        let mut wc = Change {
574
            version: crate::objects::CHANGE_VERSION,
575
            change_id: old_wc.change_id,
576
            deps: vec![],
577
            author: self.author(),
578
            hlc: old_wc.hlc,
579
            message: old_wc.message.clone(),
580
            tree_ops: built.tree_ops,
581
            edits: built.edits,
582
            kind: ChangeKind::WorkingCopy,
583
        };
584
        let base_heads = base.maximal(&old_wc.deps);
585
        let mut deps: BTreeSet<ChangeHash> = base_heads.into_iter().collect();
586
        deps.extend(referenced_changes(&wc, &base));
587
        deps.extend(built.contributors.iter().copied());
588
        wc.deps = deps.into_iter().collect();
589
        wc.normalize();
590
        let resolves = built.resolves;
591
        let contributors = built.contributors;
592
        let statuses = built.statuses;
593
        // Empty snapshot: hash the candidate before storing; only record an op on change.
594
        let record = crate::timing::phase("snapshot: hash and record");
595
        // Encoded once, its texts stored a batch at a time as they are
596
        // made (a stored blob is not stored again); the change itself only
597
        // when it changed.
598
        // For a commit the change is neither encoded, stored nor recorded:
599
        // the commit stores its own, built from this one's operations, and
600
        // its texts with it. The hash it would have is not needed.
601
        let (new_hash, changed, encoded) = if for_commit {
602
            (old_hash, true, Vec::new())
603
        } else {
604
            let encoded = wc.encode_streaming(|batch| self.store.put_texts(&batch))?;
605
            let new_hash = crate::hash::hash_object(crate::hash::ObjectType::Change, &encoded);
606
            (new_hash, new_hash != old_hash, encoded)
607
        };
608
        if changed && !for_commit {
609
            self.store.put(crate::hash::ObjectType::Change, &encoded)?;
610
            let mut view = op.view.clone();
611
            view.workspaces.insert(self.workspace, new_hash);
612
            self.record_op(&[op_ref], &format!("{command}{SNAPSHOT_SUFFIX}"), view)?;
613
        }
614
        drop(record);
615
        // The prompt compares against this without recording anything.
616
        let _t = crate::timing::phase("snapshot: write manifest");
617
        let conflicted = base_snapshot.is_conflicted();
618
        let uncommitted = !wc.tree_ops.is_empty() || !wc.edits.is_empty();
619
        // Rewriting the manifest pays only when it would teach the next
620
        // snapshot something: other flags, a file found equal to the base
621
        // (it need not be read again), a new blob, a path added or gone.
622
        // An edited file is read next time whatever it says.
623
        let worth = match self.read_manifest()? {
624
            _ if for_commit => true,
625
            None => true,
626
            Some((c, u, m)) => {
627
                c != conflicted
628
                    || u != uncommitted
629
                    || m.entries.len() != fs_entries.len()
630
                    || fs_entries.iter().any(|(p, e)| {
631
                        !e.unchanged && (e.graph_key.is_some() || !m.entries.contains_key(p))
632
                    })
633
                    || built
634
                        .blobs
635
                        .iter()
636
                        .any(|(p, b)| m.entries.get(p).and_then(|e| e.blob) != Some(*b))
637
                    // With uncommitted work, the status cache below holds
638
                    // only while the manifest describes the edited files as
639
                    // they are now.
640
                    || (uncommitted && statuses.iter().any(|st| {
641
                        let Some(e) = fs_entries.get(&st.path) else {
642
                            return m.entries.contains_key(&st.path);
643
                        };
644
                        let Some(me) = m.entries.get(&st.path) else {
645
                            return true;
646
                        };
647
                        let hash = e
648
                            .content_hash
649
                            .unwrap_or_else(|| *blake3::hash(&e.content).as_bytes());
650
                        let stat = e.stat.or_else(|| {
651
                            fs::symlink_metadata(self.root.join(&st.path))
652
                                .ok()
653
                                .map(|md| (md.len(), super::prompt::mtime_ns(&md)))
654
                        });
655
                        // The executable bit too: a mode change moves
656
                        // neither size nor time.
657
                        me.hash != hash || me.exec != e.exec || stat != Some((me.size, me.mtime_ns))
658
                    }))
659
            }
660
        };
661
        let attributes = crate::attributes::Attributes::from_files(
662
            fs_entries
663
                .iter()
664
                .filter(|(p, _)| is_attributes(p))
665
                .map(|(p, e)| (p.as_str(), e.content.as_slice())),
666
        );
667
        let mut manifest = None;
668
        if for_commit {
669
            manifest = Some(PendingManifest {
670
                entries: fs_entries,
671
                blobs: built.blobs.clone(),
672
                dirs: self.walked_dirs.take(),
673
                written: super::prompt::now_ns(),
674
            });
675
        } else {
676
            if worth {
677
                self.write_manifest_entries(conflicted, uncommitted, &fs_entries, &built.blobs)?;
678
            }
679
            self.write_status_cache((uncommitted && !conflicted).then_some(&new_hash), &statuses);
680
        }
681
        Ok(SnapshotResult {
682
            wc_hash: new_hash,
683
            wc,
684
            base,
685
            base_snapshot,
686
            statuses,
687
            changed,
688
            resolves,
689
            contributors,
690
            attributes,
691
            untracked_nested: self.untracked_nested.borrow().clone(),
692
            manifest,
693
        })
694
    }
695
696
    /// `oxy status --json` (spec §9.5): the changed paths and every conflict
697
    /// of the working copy's base with its kind, path, and contributing
698
    /// ChangeIds.
699
    pub fn status_json(&self, snap: &SnapshotResult) -> Result<String> {
700
        let heads = self.bookmark_heads()?;
701
        let base_snapshot = &snap.base_snapshot;
702
        let by_node = base_snapshot.tree.by_node();
703
        let path_of = |n: &NodeId| by_node.get(n).map(|e| e.path.clone());
704
        let id_of = |h: &ChangeHash| {
705
            snap.base
706
                .get(h)
707
                .map(|m| m.change_id.to_hex())
708
                .unwrap_or_else(|| h.to_hex())
709
        };
710
        let paths = json_array(snap.statuses.iter().map(|s| {
711
            format!(
712
                "{{\"path\":{},\"status\":{}}}",
713
                json_str(&s.path),
714
                json_str(&format!("{:?}", s.status))
715
            )
716
        }));
717
        let mut conflicts: Vec<String> = Vec::new();
718
        for (p, f) in &base_snapshot.files {
719
            if !f.is_conflicted() {
720
                continue;
721
            }
722
            let (kind, changes) = match &f.content {
723
                FileContent::Text { .. } => {
724
                    ("text", snap.base.conflict_regions(&f.node).contributors)
725
                }
726
                FileContent::Opaque { blobs } => {
727
                    ("replace", snap.base.blob_contributors(&f.node, blobs))
728
                }
729
                FileContent::Dir => continue,
730
            };
731
            let resolved = match snap
732
                .statuses
733
                .iter()
734
                .find(|s| s.path == *p)
735
                .map(|s| s.status)
736
            {
737
                Some(ChangeStatus::Resolved) => "true",
738
                Some(ChangeStatus::ConflictEdited) => "\"markers\"",
739
                _ => "false",
740
            };
741
            conflicts.push(format!(
742
                "{{\"kind\":{},\"path\":{},\"node\":{},\"changes\":{},\"resolved\":{resolved}}}",
743
                json_str(kind),
744
                json_str(p),
745
                json_str(&f.node.to_hex()),
746
                json_array(changes.iter().map(|h| json_str(&id_of(h))))
747
            ));
748
        }
749
        for c in &base_snapshot.tree.conflicts {
750
            let (kind, nodes): (&str, Vec<NodeId>) = match c {
751
                crate::tree::TreeConflict::Name { nodes, .. } => ("name", nodes.clone()),
752
                crate::tree::TreeConflict::MultiPlacement { node, .. } => {
753
                    ("multi-placement", vec![*node])
754
                }
755
                crate::tree::TreeConflict::Orphan { node, .. } => ("orphan", vec![*node]),
756
                crate::tree::TreeConflict::Cycle { node } => ("cycle", vec![*node]),
757
                crate::tree::TreeConflict::Mode { node, .. } => ("mode", vec![*node]),
758
            };
759
            let detail = match c {
760
                crate::tree::TreeConflict::Name { name, parent, .. } => {
761
                    let dir = if *parent == NodeId::ROOT {
762
                        String::new()
763
                    } else {
764
                        path_of(parent).unwrap_or_default()
765
                    };
766
                    format!(
767
                        ",\"path\":{}",
768
                        json_str(&if dir.is_empty() {
769
                            name.clone()
770
                        } else {
771
                            format!("{dir}/{name}")
772
                        })
773
                    )
774
                }
775
                _ => nodes
776
                    .first()
777
                    .and_then(path_of)
778
                    .map(|p| format!(",\"path\":{}", json_str(&p)))
779
                    .unwrap_or_default(),
780
            };
781
            conflicts.push(format!(
782
                "{{\"kind\":{},\"nodes\":{}{detail}}}",
783
                json_str(kind),
784
                json_array(nodes.iter().map(|n| json_str(&n.to_hex())))
785
            ));
786
        }
787
        Ok(format!(
788
            "{{\"bookmark\":{},\"working_copy\":{},\"heads\":{},\"clean\":{},\"conflicted\":{},\"paths\":{paths},\"conflicts\":{},\"untracked_nested\":{},\"skipped_large\":{}}}",
789
            json_str(&self.config.bookmark),
790
            json_str(&snap.wc.change_id.to_hex()),
791
            heads.len(),
792
            snap.statuses.is_empty(),
793
            base_snapshot.is_conflicted(),
794
            json_array(conflicts),
795
            json_array(snap.untracked_nested.iter().map(|p| json_str(p))),
796
            json_array(
797
                self.skipped_large
798
                    .borrow()
799
                    .iter()
800
                    .map(|(p, n)| format!("{{\"path\":{},\"size\":{n}}}", json_str(p)))
801
            )
802
        ))
803
    }
804
805
    /// Turn the working-copy change into a normal change on the bookmark (spec §12.3).
806
    pub fn commit(&self, message: &str, extra_deps: &[ChangeHash]) -> Result<ChangeHash> {
807
        self.commit_selection(message, extra_deps, &Selection::All)
808
    }
809
810
    /// The hunks of the working copy, for `oxy commit --interactive`: each
811
    /// tree operation and each edit, in the order `select_hunks` numbers them.
812
    pub fn hunks(&self) -> Result<(SnapshotResult, Vec<Hunk>)> {
813
        let snap = self.snapshot_status("oxy commit")?;
814
        let hunks = render_hunks(&snap.wc, &snap.base, &snap.base_snapshot);
815
        Ok((snap, hunks))
816
    }
817
818
    /// Commit part of the working copy (spec §12.3). What is not selected
819
    /// stays on disk as uncommitted work: the next snapshot rebuilds it
820
    /// against the new base, so the working copy always describes the
821
    /// directory.
822
    /// The graph key in `st` of each text file at `paths`, the paths a
823
    /// commit changed: only their graphs changed, so the keys the manifest
824
    /// holds for the others still stand (and any that does not is simply
825
    /// not trusted by the next snapshot, which compares keys). Files with
826
    /// an `eol` attribute are left out: their bytes on disk are not the
827
    /// rendering.
828
    fn committed_graph_keys(
829
        &self,
830
        st: &State,
831
        paths: &[String],
832
        attrs: &crate::attributes::Attributes,
833
    ) -> HashMap<String, [u8; 32]> {
834
        let _t = crate::timing::phase("commit: graph keys");
835
        let view = st.tree().view();
836
        paths
837
            .iter()
838
            .filter_map(|p| {
839
                let e = view.entries.get(p)?;
840
                (e.kind == NodeKind::File && !e.mode.opaque && attrs.lookup(p).eol.is_none())
841
                    .then_some(())?;
842
                Some((p.clone(), st.graph_key(&e.node)?))
843
            })
844
            .collect()
845
    }
846
847
    pub fn commit_selection(
848
        &self,
849
        message: &str,
850
        extra_deps: &[ChangeHash],
851
        selection: &Selection,
852
    ) -> Result<ChangeHash> {
853
        Ok(self
854
            .commit_selection_partial(message, extra_deps, selection)?
855
            .0)
856
    }
857
858
    /// As [`Repo::commit_selection`], and whether the commit left part of
859
    /// the working copy uncommitted: when it did not, nothing is left, and
860
    /// no snapshot is needed to say so.
861
    pub fn commit_selection_partial(
862
        &self,
863
        message: &str,
864
        extra_deps: &[ChangeHash],
865
        selection: &Selection,
866
    ) -> Result<(ChangeHash, bool)> {
867
        // The commit's objects are written together, made durable at once
868
        // before the operation that names them (spec §13.6).
869
        let batch = self.store.begin_batch()?;
870
        let out = self.commit_selection_batched(message, extra_deps, selection);
871
        batch.finish()?;
872
        out
873
    }
874
875
    /// Write the manifest a commit's snapshot left to the commit, with the
876
    /// graph keys `keys` sets.
877
    fn write_pending_manifest(
878
        &self,
879
        mut m: PendingManifest,
880
        conflicted: bool,
881
        keys: HashMap<String, [u8; 32]>,
882
    ) -> Result<()> {
883
        for (path, k) in keys {
884
            if let Some(e) = m.entries.get_mut(&path) {
885
                e.graph_key = Some(k);
886
            }
887
        }
888
        self.write_manifest_entries_as_of(
889
            conflicted,
890
            false,
891
            &m.entries,
892
            &m.blobs,
893
            m.written,
894
            m.dirs.unwrap_or_default(),
895
        )
896
    }
897
898
    fn commit_selection_batched(
899
        &self,
900
        message: &str,
901
        extra_deps: &[ChangeHash],
902
        selection: &Selection,
903
    ) -> Result<(ChangeHash, bool)> {
904
        let _wc = self.lock_working_copy()?;
905
        let mut snap = match self.snapshot_from_cache()? {
906
            Some(snap) => snap,
907
            None => self.snapshot_as("oxy commit", true, true)?,
908
        };
909
        let pending = snap.manifest.take();
910
        if snap.wc.tree_ops.is_empty() && snap.wc.edits.is_empty() {
911
            if let Some(m) = pending {
912
                let conflicted = snap.base_snapshot.is_conflicted();
913
                self.write_pending_manifest(m, conflicted, HashMap::new())?;
914
            }
915
            return fail("nothing to commit: the working copy matches its base");
916
        }
917
        if let Some(s) = snap
918
            .statuses
919
            .iter()
920
            .find(|s| s.status == ChangeStatus::ConflictEdited)
921
        {
922
            return fail(format!("{} still contains conflict markers", s.path));
923
        }
924
        if message.trim().is_empty() {
925
            return fail("a commit message is required");
926
        }
927
        // What the whole working copy references, before a whole commit
928
        // takes its operations over (they are moved, not copied: for a
929
        // large tree they are most of the memory).
930
        let wc_refs = referenced_changes(&snap.wc, &snap.base);
931
        let changed_paths: Vec<String> = snap.statuses.iter().map(|s| s.path.clone()).collect();
932
        let (tree_ops, edits, partial) = match selection {
933
            Selection::All => (
934
                std::mem::take(&mut snap.wc.tree_ops),
935
                std::mem::take(&mut snap.wc.edits),
936
                false,
937
            ),
938
            Selection::Paths(paths) => {
939
                let (o, e) = select_paths(&snap.wc, &snap.base_snapshot, paths);
940
                let partial = o.len() != snap.wc.tree_ops.len() || e.len() != snap.wc.edits.len();
941
                (o, e, partial)
942
            }
943
            Selection::Hunks(indices) => {
944
                let (o, e) = select_hunks(&snap.wc, indices);
945
                let partial = o.len() != snap.wc.tree_ops.len() || e.len() != snap.wc.edits.len();
946
                (o, e, partial)
947
            }
948
        };
949
        if tree_ops.is_empty() && edits.is_empty() {
950
            return fail("nothing selected to commit");
951
        }
952
        if partial && snap.resolves {
953
            return fail("a conflict resolution must be committed whole");
954
        }
955
        // pre-commit hook: may veto.
956
        self.run_hook(
957
            "pre-commit",
958
            &format!(
959
                "{{\"event\":\"pre-commit\",\"message\":{},\"paths\":{}}}",
960
                json_str(message),
961
                json_array(snap.statuses.iter().map(|s| format!(
962
                    "{{\"path\":{},\"status\":{}}}",
963
                    json_str(&s.path),
964
                    json_str(&format!("{:?}", s.status))
965
                )))
966
            ),
967
        )?;
968
        let (op_ref, op) = self.head_op()?;
969
        let mut deps: BTreeSet<ChangeHash> = wc_refs;
970
        // semantic-deps hook: may add explicit dependencies (spec §8.1).
971
        if self.config.semantic_deps {
972
            let touched: Vec<String> = snap.statuses.iter().map(|s| s.path.clone()).collect();
973
            let by_node = snap.base_snapshot.tree.by_node();
974
            let mut candidates: Vec<(ChangeId, ChangeHash, Vec<String>)> = Vec::new();
975
            let mut seen: BTreeSet<ChangeHash> = BTreeSet::new();
976
            for h in deps.iter().chain(snap.base.maximal(&snap.wc.deps).iter()) {
977
                if !seen.insert(*h) {
978
                    continue;
979
                }
980
                let c = self.store.get_change(h)?;
981
                let mut paths: BTreeSet<String> = BTreeSet::new();
982
                for n in c
983
                    .tree_ops
984
                    .iter()
985
                    .map(|o| o.node())
986
                    .chain(c.edits.iter().map(|e| e.node()))
987
                {
988
                    if let Some(e) = by_node.get(&n) {
989
                        paths.insert(e.path.clone());
990
                    }
991
                }
992
                candidates.push((c.change_id, *h, paths.into_iter().collect()));
993
            }
994
            for d in self.semantic_deps(&snap.wc.change_id, &touched, &candidates)? {
995
                if snap.base.contains(&d) {
996
                    deps.insert(d);
997
                }
998
            }
999
        }
1000
        // A resolution depends on every change that contributed to the
1001
        // conflict (spec §8.1). Tree and opaque conflicts are resolved through
1002
        // ordinary operations whose references already cover the contributors.
1003
        deps.extend(snap.contributors.iter().copied());
1004
        for d in extra_deps {
1005
            if !snap.base.contains(d) {
1006
                return fail(format!(
1007
                    "--depends-on {d}: not in the working copy's base state"
1008
                ));
1009
            }
1010
            deps.insert(*d);
1011
        }
1012
        let mut change = Change {
1013
            version: crate::objects::CHANGE_VERSION,
1014
            change_id: if partial {
1015
                ChangeId::random()
1016
            } else {
1017
                snap.wc.change_id
1018
            },
1019
            deps: vec![],
1020
            author: self.author(),
1021
            hlc: Hlc::now(),
1022
            message: message.trim_end().to_string(),
1023
            tree_ops,
1024
            edits,
1025
            kind: if snap.resolves {
1026
                ChangeKind::Resolution
1027
            } else {
1028
                ChangeKind::Normal
1029
            },
1030
        };
1031
        if partial {
1032
            // Dependencies come from what the selected part references, not
1033
            // from the whole working copy.
1034
            deps = referenced_changes(&change, &snap.base);
1035
            for d in extra_deps {
1036
                deps.insert(*d);
1037
            }
1038
        }
1039
        change.deps = deps.into_iter().collect();
1040
        change.normalize();
1041
        let signing = crate::timing::phase("commit: sign and store");
1042
        let hash = self.store_signed(&change)?;
1043
        drop(signing);
1044
        let extending = crate::timing::phase("commit: extend the state");
1045
1046
        // New bookmark heads: maximal elements of old heads plus the new change.
1047
        // The working copy continues on its own base plus the new change, which
1048
        // is exactly what the files on disk contain; the bookmark may hold
1049
        // other heads (and conflicts) the working copy has not checked out.
1050
        let old_heads = self.heads_of(&op.view, &self.config.bookmark)?;
1051
        let old_base = snap.base.maximal(&snap.wc.deps);
1052
        let mut all: Vec<ChangeHash> = old_heads.clone();
1053
        all.extend(old_base.iter().copied());
1054
        all.push(hash);
1055
        // The snapshot already loaded the working copy's base; when that also
1056
        // holds every bookmark head, it is the state to extend.
1057
        let mut st = if old_heads.iter().all(|h| snap.base.contains(h)) {
1058
            snap.base
1059
        } else {
1060
            self.load_state(&all)?
1061
        };
1062
        st.add_hashed(hash, change)?;
1063
        let mut with_new = old_heads.clone();
1064
        with_new.push(hash);
1065
        let new_heads = st.maximal(&with_new);
1066
        // Automatic checkpoint once enough changes accumulated (spec §11).
1067
        let since = self
1068
            .latest_checkpoint(&self.config.bookmark)?
1069
            .map(|(_, cp)| cp.count)
1070
            .unwrap_or(0);
1071
        if self.config.checkpoint_interval > 0
1072
            && (st.len() as u64).saturating_sub(since) >= self.config.checkpoint_interval
1073
        {
1074
            let cp_state = self.load_state_full(&new_heads)?;
1075
            self.write_checkpoint(&self.config.bookmark, &cp_state, &new_heads)?;
1076
        }
1077
        let mut wc_base = old_base.clone();
1078
        wc_base.push(hash);
1079
        let wc_base = st.maximal(&wc_base);
1080
        drop(extending);
1081
1082
        // The graph keys of the files as they now are, from the state the
1083
        // commit just extended: a file whose graph it built has none, and
1084
        // is read by the next snapshot; a key the next base does not share
1085
        // (the bookmark held other heads) is simply not trusted then.
1086
        let keying = crate::timing::phase("commit: graph keys of the files");
1087
        let committed_keys =
1088
            (!partial).then(|| self.committed_graph_keys(&st, &changed_paths, &snap.attributes));
1089
        drop(keying);
1090
        let recording = crate::timing::phase("commit: record");
1091
        let wc = self.new_working_copy(wc_base, "");
1092
        let wc_hash = self.store.put_change(&wc)?;
1093
        let mut view = op.view.clone();
1094
        view.bookmarks.insert(
1095
            self.config.bookmark.clone(),
1096
            self.store.put_state(&StateObject::new(new_heads))?,
1097
        );
1098
        view.workspaces.insert(self.workspace, wc_hash);
1099
        self.record_op(&[op_ref], &format!("oxy commit -m {message:?}"), view)?;
1100
        drop(recording);
1101
        let rewriting = crate::timing::phase("commit: manifest");
1102
        if partial {
1103
            // The rest is rebuilt from disk by the next snapshot.
1104
            self.drop_manifest();
1105
        } else {
1106
            let conflicted = snap.base_snapshot.is_conflicted() && !snap.resolves;
1107
            // The files on disk are now exactly the new base's renderings:
1108
            // record their graph keys, so the next snapshot neither reads nor
1109
            // renders them (oxygen#35).
1110
            let keys = if conflicted {
1111
                HashMap::new()
1112
            } else {
1113
                committed_keys.unwrap_or_default()
1114
            };
1115
            match pending {
1116
                Some(m) => self.write_pending_manifest(m, conflicted, keys)?,
1117
                None => self.rewrite_manifest(conflicted, false, &keys)?,
1118
            }
1119
        }
1120
        drop(rewriting);
1121
        let packing = crate::timing::phase("commit: autopack");
1122
        self.maybe_autopack()?;
1123
        drop(packing);
1124
        let _hook = crate::timing::phase("commit: hook");
1125
        let _ = self.run_hook(
1126
            "post-commit",
1127
            &format!(
1128
                "{{\"event\":\"post-commit\",\"change_id\":{},\"hash\":{},\"message\":{}}}",
1129
                json_str(&snap.wc.change_id.to_hex()),
1130
                json_str(&hash.to_hex()),
1131
                json_str(message)
1132
            ),
1133
        );
1134
        Ok((hash, partial))
1135
    }
1136
}
1137
1138
/// What part of the working copy a commit takes (spec §12.3).
1139
#[derive(Clone, Debug)]
1140
pub enum Selection {
1141
    All,
1142
    /// Every operation and edit on nodes under these paths.
1143
    Paths(Vec<String>),
1144
    /// Hunk indices as `Repo::hunks` numbers them; dependent hunks are added.
1145
    Hunks(Vec<usize>),
1146
}
1147
1148
/// One selectable piece of the working copy: a tree operation or an edit.
1149
#[derive(Clone, Debug)]
1150
pub struct Hunk {
1151
    pub index: usize,
1152
    pub path: String,
1153
    /// Rendered like `oxy diff`.
1154
    pub text: String,
1155
}
1156
1157
/// The tree operations and edits on nodes under `paths`, plus the
1158
/// additions of any new parent directories they need.
1159
fn select_paths(
1160
    wc: &Change,
1161
    base_snapshot: &Snapshot,
1162
    paths: &[String],
1163
) -> (Vec<TreeOp>, Vec<Edit>) {
1164
    let selected = |p: &str| {
1165
        paths
1166
            .iter()
1167
            .any(|x| p == x || p.starts_with(&format!("{}/", x.trim_end_matches('/'))))
1168
    };
1169
    let by_node = base_snapshot.tree.by_node();
1170
    let mut new_names: HashMap<NodeId, (NodeId, String, NodeKind)> = HashMap::new();
1171
    for op in &wc.tree_ops {
1172
        if let TreeOp::AddNode {
1173
            node,
1174
            parent,
1175
            name,
1176
            kind,
1177
            ..
1178
        } = op
1179
        {
1180
            new_names.insert(*node, (*parent, name.clone(), *kind));
1181
        }
1182
    }
1183
    let mut nodes: BTreeSet<NodeId> = BTreeSet::new();
1184
    for n in wc
1185
        .tree_ops
1186
        .iter()
1187
        .map(|o| o.node())
1188
        .chain(wc.edits.iter().map(|e| e.node()))
1189
    {
1190
        if path_of_node(&n, &by_node, &new_names).is_some_and(|p| selected(&p)) {
1191
            nodes.insert(n);
1192
        }
1193
    }
1194
    // New parents of selected new nodes come along.
1195
    let mut changed = true;
1196
    while changed {
1197
        changed = false;
1198
        for (n, (parent, _, _)) in &new_names {
1199
            if nodes.contains(n) && new_names.contains_key(parent) && nodes.insert(*parent) {
1200
                changed = true;
1201
            }
1202
        }
1203
    }
1204
    let ops = wc
1205
        .tree_ops
1206
        .iter()
1207
        .filter(|o| nodes.contains(&o.node()))
1208
        .cloned()
1209
        .collect();
1210
    let edits = wc
1211
        .edits
1212
        .iter()
1213
        .filter(|e| nodes.contains(&e.node()))
1214
        .cloned()
1215
        .collect();
1216
    (ops, edits)
1217
}
1218
1219
/// The hunks `indices` name plus whatever they refer to within the working
1220
/// copy (the parent directory of an added node, the insert that introduced
1221
/// an anchor line), renumbered so the result is a well-formed change.
1222
fn select_hunks(wc: &Change, indices: &[usize]) -> (Vec<TreeOp>, Vec<Edit>) {
1223
    let n_ops = wc.tree_ops.len();
1224
    let mut ops_sel = vec![false; n_ops];
1225
    let mut edits_sel = vec![false; wc.edits.len()];
1226
    for &i in indices {
1227
        if i < n_ops {
1228
            ops_sel[i] = true;
1229
        } else if i - n_ops < wc.edits.len() {
1230
            edits_sel[i - n_ops] = true;
1231
        }
1232
    }
1233
    // Atom ranges each insert introduces, per node, in the working copy's numbering.
1234
    let mut per_node: HashMap<NodeId, u32> = HashMap::new();
1235
    let mut insert_ranges: Vec<Option<(NodeId, u32, u32)>> = Vec::new();
1236
    for e in &wc.edits {
1237
        insert_ranges.push(match e {
1238
            Edit::Insert { node, lines, .. } => {
1239
                let start = per_node.entry(*node).or_default();
1240
                let r = (*node, *start, *start + lines.len() as u32);
1241
                *start += lines.len() as u32;
1242
                Some(r)
1243
            }
1244
            _ => None,
1245
        });
1246
    }
1247
    let add_index: HashMap<NodeId, usize> = wc
1248
        .tree_ops
1249
        .iter()
1250
        .enumerate()
1251
        .filter_map(|(i, o)| {
1252
            if let TreeOp::AddNode { node, .. } = o {
1253
                Some((*node, i))
1254
            } else {
1255
                None
1256
            }
1257
        })
1258
        .collect();
1259
    let insert_for = |node: &NodeId, index: u32| -> Option<usize> {
1260
        insert_ranges
1261
            .iter()
1262
            .position(|r| matches!(r, Some((n, a, b)) if n == node && *a <= index && index < *b))
1263
    };
1264
    // Closure.
1265
    let mut changed = true;
1266
    while changed {
1267
        changed = false;
1268
        for i in 0..n_ops {
1269
            if !ops_sel[i] {
1270
                continue;
1271
            }
1272
            if let TreeOp::AddNode { node, parent, .. } = &wc.tree_ops[i] {
1273
                if let Some(&p) = add_index.get(parent) {
1274
                    if !ops_sel[p] {
1275
                        ops_sel[p] = true;
1276
                        changed = true;
1277
                    }
1278
                }
1279
                // A new node's content belongs with its addition: nobody
1280
                // wants an empty file committed apart from its lines.
1281
                for (j, e) in wc.edits.iter().enumerate() {
1282
                    if e.node() == *node && !edits_sel[j] {
1283
                        edits_sel[j] = true;
1284
                        changed = true;
1285
                    }
1286
                }
1287
            }
1288
        }
1289
        for j in 0..wc.edits.len() {
1290
            if !edits_sel[j] {
1291
                continue;
1292
            }
1293
            let e = &wc.edits[j];
1294
            if let Some(&a) = add_index.get(&e.node()) {
1295
                if !ops_sel[a] {
1296
                    ops_sel[a] = true;
1297
                    changed = true;
1298
                }
1299
            }
1300
            if let Edit::Insert {
1301
                node,
1302
                after,
1303
                before,
1304
                ..
1305
            } = e
1306
            {
1307
                for r in [after, before] {
1308
                    if let AtomRef::Atom { change, index } = r {
1309
                        if change.is_zero() {
1310
                            if let Some(k) = insert_for(node, *index) {
1311
                                if !edits_sel[k] {
1312
                                    edits_sel[k] = true;
1313
                                    changed = true;
1314
                                }
1315
                            }
1316
                        }
1317
                    }
1318
                }
1319
            }
1320
        }
1321
    }
1322
    // Renumber self-references: old atom index → new index among selected inserts.
1323
    let mut remap: HashMap<(NodeId, u32), u32> = HashMap::new();
1324
    let mut new_counts: HashMap<NodeId, u32> = HashMap::new();
1325
    for (j, r) in insert_ranges.iter().enumerate() {
1326
        if let (true, Some((node, a, b))) = (edits_sel[j], r) {
1327
            let next = new_counts.entry(*node).or_default();
1328
            for old in *a..*b {
1329
                remap.insert((*node, old), *next);
1330
                *next += 1;
1331
            }
1332
        }
1333
    }
1334
    let map_ref = |r: AtomRef, node: &NodeId| -> AtomRef {
1335
        match r {
1336
            AtomRef::Atom { change, index } if change.is_zero() => AtomRef::Atom {
1337
                change,
1338
                index: remap.get(&(*node, index)).copied().unwrap_or(index),
1339
            },
1340
            other => other,
1341
        }
1342
    };
1343
    let ops = wc
1344
        .tree_ops
1345
        .iter()
1346
        .enumerate()
1347
        .filter(|(i, _)| ops_sel[*i])
1348
        .map(|(_, o)| o.clone())
1349
        .collect();
1350
    let edits = wc
1351
        .edits
1352
        .iter()
1353
        .enumerate()
1354
        .filter(|(j, _)| edits_sel[*j])
1355
        .map(|(_, e)| match e {
1356
            Edit::Insert {
1357
                node,
1358
                after,
1359
                before,
1360
                lines,
1361
            } => Edit::Insert {
1362
                node: *node,
1363
                after: map_ref(*after, node),
1364
                before: map_ref(*before, node),
1365
                lines: lines.clone(),
1366
            },
1367
            other => other.clone(),
1368
        })
1369
        .collect();
1370
    (ops, edits)
1371
}
1372
1373
/// Render each tree operation and edit of `change` on its own, numbered.
1374
pub fn render_hunks(change: &Change, base: &State, base_snapshot: &Snapshot) -> Vec<Hunk> {
1375
    let by_node = base_snapshot.tree.by_node();
1376
    let mut new_names: HashMap<NodeId, (NodeId, String, NodeKind)> = HashMap::new();
1377
    for op in &change.tree_ops {
1378
        if let TreeOp::AddNode {
1379
            node,
1380
            parent,
1381
            name,
1382
            kind,
1383
            ..
1384
        } = op
1385
        {
1386
            new_names.insert(*node, (*parent, name.clone(), *kind));
1387
        }
1388
    }
1389
    let mut out = Vec::new();
1390
    for (i, op) in change.tree_ops.iter().enumerate() {
1391
        let one = Change {
1392
            tree_ops: vec![op.clone()],
1393
            edits: vec![],
1394
            ..change.clone()
1395
        };
1396
        let path = path_of_node(&op.node(), &by_node, &new_names).unwrap_or_default();
1397
        out.push(Hunk {
1398
            index: i,
1399
            path,
1400
            text: render_change(&one, base, base_snapshot),
1401
        });
1402
    }
1403
    for (j, e) in change.edits.iter().enumerate() {
1404
        let one = Change {
1405
            tree_ops: vec![],
1406
            edits: vec![e.clone()],
1407
            ..change.clone()
1408
        };
1409
        let path = path_of_node(&e.node(), &by_node, &new_names).unwrap_or_default();
1410
        out.push(Hunk {
1411
            index: change.tree_ops.len() + j,
1412
            path,
1413
            text: render_change(&one, base, base_snapshot),
1414
        });
1415
    }
1416
    out
1417
}
1418
1419
/// One file's part of a diff, for `oxy diff --json`.
1420
#[derive(Clone, Debug)]
1421
pub struct FileDiff {
1422
    pub path: String,
1423
    /// `added`, `removed`, `modified`, `renamed`, `mode`, `replaced`.
1424
    pub kind: String,
1425
    pub hunks: Vec<DiffHunk>,
1426
    /// For renames, the previous path.
1427
    pub from: Option<String>,
1428
}
1429
1430
/// Lines inserted after `base_line` (0 = before the first line) and lines
1431
/// removed, with their base line numbers.
1432
#[derive(Clone, Debug, Default)]
1433
pub struct DiffHunk {
1434
    pub base_line: u32,
1435
    pub added: Vec<Vec<u8>>,
1436
    pub removed: Vec<(u32, Vec<u8>)>,
1437
}
1438
1439
impl Repo {
1440
    /// The content of `path` in a state: `heads`, or the working copy's base.
1441
    pub fn file_at(&self, path: &str, heads: Option<&[ChangeHash]>) -> Result<Vec<u8>> {
1442
        // The state's history and tree, then the one file's graph: nothing
1443
        // else is built or rendered (oxygen#92).
1444
        // The working copy's base, and a state named by its heads (`-r
1445
        // main` on main), come from the workspace's state index.
1446
        let base = if self.is_bare() {
1447
            None
1448
        } else {
1449
            Some(self.working_copy()?.1.deps)
1450
        };
1451
        let same = |a: &[ChangeHash], b: &[ChangeHash]| {
1452
            let (mut a, mut b) = (a.to_vec(), b.to_vec());
1453
            a.sort();
1454
            b.sort();
1455
            a == b
1456
        };
1457
        let mut state = match (heads, base) {
1458
            (Some(h), Some(b)) if same(h, &b) => self.load_state_indexed(&b)?,
1459
            (Some(h), _) => self.load_state_history(h)?,
1460
            (None, Some(b)) => self.load_state_indexed(&b)?,
1461
            (None, None) => return fail("this is a bare repository: it has no working copy"),
1462
        };
1463
        let view = state.tree().view();
1464
        let Some(node) = view.entries.get(path).map(|e| e.node) else {
1465
            return fail(format!("{path} is not in that state"));
1466
        };
1467
        self.load_graphs_of(&mut state, &[node])?;
1468
        let snapshot = state.materialize_paths(view, [path]);
1469
        let Some(f) = snapshot.files.get(path) else {
1470
            return fail(format!("{path} is not in that state"));
1471
        };
1472
        match &f.content {
1473
            FileContent::Dir => fail(format!("{path} is a directory")),
1474
            FileContent::Text { bytes, .. } => Ok(bytes.clone()),
1475
            FileContent::Opaque { blobs } => match blobs.first() {
1476
                Some(b) => self.read_blob(b),
1477
                None => Ok(vec![]),
1478
            },
1479
        }
1480
    }
1481
1482
    /// Restore `paths` (files or directories) to the working copy's base:
1483
    /// edits are undone, additions removed, removals put back. Returns the
1484
    /// number of paths touched.
1485
    pub fn discard(&self, paths: &[String]) -> Result<usize> {
1486
        let _wc = self.lock_working_copy()?;
1487
        let snap = self.snapshot_status("oxy discard")?;
1488
        let under = |p: &str| {
1489
            paths
1490
                .iter()
1491
                .any(|x| p == x || p.starts_with(&format!("{}/", x.trim_end_matches('/'))))
1492
        };
1493
        let attrs = Repo::state_attributes(&snap.base_snapshot);
1494
        let mut n = 0;
1495
        for s in &snap.statuses {
1496
            if !under(&s.path) {
1497
                continue;
1498
            }
1499
            match snap.base_snapshot.files.get(&s.path) {
1500
                None => {
1501
                    // Added (or the new name of a rename): remove it.
1502
                    let full = self.root.join(&s.path);
1503
                    if full.is_dir() {
1504
                        let _ = fs::remove_dir_all(&full);
1505
                    } else {
1506
                        let _ = fs::remove_file(&full);
1507
                    }
1508
                    n += 1;
1509
                }
1510
                Some(f) => {
1511
                    match &f.content {
1512
                        FileContent::Dir => fs::create_dir_all(self.root.join(&s.path))?,
1513
                        FileContent::Text { bytes, .. } => {
1514
                            let on_disk: std::borrow::Cow<[u8]> = if attrs.lookup(&s.path).eol
1515
                                == Some(crate::attributes::Eol::Crlf)
1516
                            {
1517
                                crate::attributes::to_crlf(bytes).into()
1518
                            } else {
1519
                                bytes.as_slice().into()
1520
                            };
1521
                            self.write_file(&s.path, &on_disk, f.mode.exec)?;
1522
                        }
1523
                        FileContent::Opaque { blobs } => {
1524
                            let bytes = match blobs.first() {
1525
                                Some(b) => self.read_blob(b)?,
1526
                                None => vec![],
1527
                            };
1528
                            if f.kind == NodeKind::Symlink {
1529
                                self.write_symlink(&s.path, &bytes)?;
1530
                            } else if f.kind == NodeKind::File {
1531
                                self.write_file(&s.path, &bytes, f.mode.exec)?;
1532
                            }
1533
                        }
1534
                    }
1535
                    n += 1;
1536
                }
1537
            }
1538
        }
1539
        // A rename's old name is not in the statuses; put it back too.
1540
        for (p, f) in &snap.base_snapshot.files {
1541
            if under(p)
1542
                && !self.root.join(p).exists()
1543
                && f.kind != NodeKind::Dir
1544
                && f.kind != NodeKind::Subrepo
1545
                && !snap.statuses.iter().any(|s| s.path == *p)
1546
            {
1547
                let bytes = match &f.content {
1548
                    FileContent::Text { bytes, .. } => bytes.clone(),
1549
                    FileContent::Opaque { blobs } => blobs
1550
                        .first()
1551
                        .map(|b| self.read_blob(b))
1552
                        .transpose()?
1553
                        .unwrap_or_default(),
1554
                    FileContent::Dir => continue,
1555
                };
1556
                if f.kind == NodeKind::Symlink {
1557
                    self.write_symlink(p, &bytes)?
1558
                } else {
1559
                    self.write_file(p, &bytes, f.mode.exec)?
1560
                }
1561
                n += 1;
1562
            }
1563
        }
1564
        self.drop_manifest();
1565
        Ok(n)
1566
    }
1567
1568
    /// Undo the working-copy hunks `indices` (as `hunks` numbers them) on
1569
    /// disk, keeping the others: the files are rewritten from the base plus
1570
    /// the remaining hunks.
1571
    pub fn discard_hunks(&self, indices: &[usize]) -> Result<usize> {
1572
        let _wc = self.lock_working_copy()?;
1573
        let (snap, hunks) = self.hunks()?;
1574
        let keep: Vec<usize> = hunks
1575
            .iter()
1576
            .map(|h| h.index)
1577
            .filter(|i| !indices.contains(i))
1578
            .collect();
1579
        let (ops, edits) = select_hunks(&snap.wc, &keep);
1580
        let dropped_nodes: BTreeSet<NodeId> = hunks
1581
            .iter()
1582
            .filter(|h| indices.contains(&h.index))
1583
            .map(|h| {
1584
                if h.index < snap.wc.tree_ops.len() {
1585
                    snap.wc.tree_ops[h.index].node()
1586
                } else {
1587
                    snap.wc.edits[h.index - snap.wc.tree_ops.len()].node()
1588
                }
1589
            })
1590
            .collect();
1591
        let mut partial = snap.wc.clone();
1592
        partial.tree_ops = ops;
1593
        partial.edits = edits;
1594
        partial.normalize();
1595
        let mut st = snap.base.clone();
1596
        st.add_unchecked(partial);
1597
        // Every file of the target is rendered: build the graphs the
1598
        // partial snapshot left out.
1599
        self.load_all_graphs(&mut st)?;
1600
        let target = st.materialize();
1601
        let by_node_target = target.tree.by_node();
1602
        let by_node_base = snap.base_snapshot.tree.by_node();
1603
        let attrs = Repo::state_attributes(&target);
1604
        let mut n = 0;
1605
        for node in dropped_nodes {
1606
            match by_node_target.get(&node) {
1607
                Some(e) => {
1608
                    let f = &target.files[&e.path];
1609
                    match &f.content {
1610
                        FileContent::Dir => {}
1611
                        FileContent::Text { bytes, .. } => {
1612
                            let on_disk: std::borrow::Cow<[u8]> = if attrs.lookup(&e.path).eol
1613
                                == Some(crate::attributes::Eol::Crlf)
1614
                            {
1615
                                crate::attributes::to_crlf(bytes).into()
1616
                            } else {
1617
                                bytes.as_slice().into()
1618
                            };
1619
                            self.write_file(&e.path, &on_disk, f.mode.exec)?;
1620
                        }
1621
                        FileContent::Opaque { blobs } => {
1622
                            let bytes = blobs
1623
                                .first()
1624
                                .map(|b| self.read_blob(b))
1625
                                .transpose()?
1626
                                .unwrap_or_default();
1627
                            if f.kind == NodeKind::Symlink {
1628
                                self.write_symlink(&e.path, &bytes)?
1629
                            } else {
1630
                                self.write_file(&e.path, &bytes, f.mode.exec)?
1631
                            }
1632
                        }
1633
                    }
1634
                    // A discarded rename: the new name goes.
1635
                    if let Some(old_path) = snap
1636
                        .statuses
1637
                        .iter()
1638
                        .find(|s| {
1639
                            s.status == ChangeStatus::Renamed && !target.files.contains_key(&s.path)
1640
                        })
1641
                        .map(|s| s.path.clone())
1642
                    {
1643
                        let _ = fs::remove_file(self.root.join(old_path));
1644
                    }
1645
                    n += 1;
1646
                }
1647
                None => {
1648
                    // The node exists in neither target nor base with a live path: an addition to remove.
1649
                    if let Some(added) = snap.statuses.iter().find(|s| {
1650
                        s.status == ChangeStatus::Added
1651
                            && !target.files.contains_key(&s.path)
1652
                            && !by_node_base.contains_key(&node)
1653
                    }) {
1654
                        let full = self.root.join(&added.path);
1655
                        if full.is_dir() {
1656
                            let _ = fs::remove_dir_all(&full);
1657
                        } else {
1658
                            let _ = fs::remove_file(&full);
1659
                        }
1660
                        n += 1;
1661
                    }
1662
                }
1663
            }
1664
        }
1665
        self.drop_manifest();
1666
        Ok(n)
1667
    }
1668
1669
    /// The diff of the working copy (`None`) or of a change, per file with
1670
    /// line-numbered hunks (spec: `oxy diff --json`).
1671
    pub fn diff_files(&self, change: Option<&ChangeHash>) -> Result<Vec<FileDiff>> {
1672
        let (c, base, base_snapshot) = match change {
1673
            Some(h) => {
1674
                let c = self.store.get_change(h)?;
1675
                let (base, snapshot) = self.change_base(&c)?;
1676
                (c, base, snapshot)
1677
            }
1678
            None => self.working_copy_with_base()?,
1679
        };
1680
        Ok(diff_files_of(&c, &base, &base_snapshot))
1681
    }
1682
1683
    /// The snapshot a command would take, without taking it, when the
1684
    /// status cache holds: every file is as the last snapshot left it, so
1685
    /// that snapshot's working-copy change is the answer. Its base comes
1686
    /// from the state index, the `.oxyattributes` files from disk. `None`
1687
    /// when a snapshot must be taken, and when there is nothing to commit
1688
    /// (the snapshot then says so). A conflicted base never gets here: the
1689
    /// cache does not hold for one.
1690
    pub(crate) fn snapshot_from_cache(&self) -> Result<Option<SnapshotResult>> {
1691
        let Some(statuses) = self.status_by_manifest()? else {
1692
            return Ok(None);
1693
        };
1694
        if statuses.is_empty() {
1695
            return Ok(None);
1696
        }
1697
        let _t = crate::timing::phase("snapshot: from the status cache");
1698
        let (wc_hash, wc) = self.working_copy()?;
1699
        let base = self.load_state_indexed(&wc.deps)?;
1700
        let (base, base_snapshot) = self.render_base_for(&wc, base)?;
1701
        let attribute_files: Vec<(String, Vec<u8>)> = match self.read_manifest()? {
1702
            Some((_, _, m)) => m
1703
                .entries
1704
                .keys()
1705
                .filter(|p| is_attributes(p))
1706
                .filter_map(|p| fs::read(self.root.join(p)).ok().map(|b| (p.clone(), b)))
1707
                .collect(),
1708
            None => Vec::new(),
1709
        };
1710
        let attributes = crate::attributes::Attributes::from_files(
1711
            attribute_files
1712
                .iter()
1713
                .map(|(p, b)| (p.as_str(), b.as_slice())),
1714
        );
1715
        Ok(Some(SnapshotResult {
1716
            wc_hash,
1717
            wc,
1718
            base,
1719
            base_snapshot,
1720
            statuses,
1721
            changed: false,
1722
            resolves: false,
1723
            contributors: Vec::new(),
1724
            attributes,
1725
            untracked_nested: self.untracked_nested.borrow().clone(),
1726
            manifest: None,
1727
        }))
1728
    }
1729
1730
    /// The working-copy change with its base state and the base's
1731
    /// rendering, for showing what the working copy changes. While the
1732
    /// status cache holds (every file as the last snapshot left it), the
1733
    /// stored working-copy change is the answer and no snapshot is taken;
1734
    /// otherwise a snapshot makes it.
1735
    pub fn working_copy_with_base(&self) -> Result<(Change, State, Snapshot)> {
1736
        if self.status_by_manifest()?.is_some() {
1737
            let (_, wc) = self.working_copy()?;
1738
            let base = self.load_state_indexed(&wc.deps)?;
1739
            let (base, snapshot) = self.render_base_for(&wc, base)?;
1740
            return Ok((wc, base, snapshot));
1741
        }
1742
        let snap = self.snapshot_status("oxy diff")?;
1743
        Ok((snap.wc, snap.base, snap.base_snapshot))
1744
    }
1745
1746
    /// The log restricted to changes touching `path` (its node, so renames
1747
    /// are followed), on the current bookmark.
1748
    pub fn log_for_path(&self, path: &str) -> Result<Vec<LogEntry>> {
1749
        let heads = self.bookmark_heads()?;
1750
        if self.is_bare() {
1751
            return self.log_for_path_in(path, &heads);
1752
        }
1753
        let entries = self.log()?;
1754
        let (_, wc) = self.working_copy()?;
1755
        // The path's node from the trees alone: the base's (from the
1756
        // workspace's state index), else the bookmark's. Nothing is
1757
        // rendered.
1758
        let node_in = |state: State| state.tree().view().entries.get(path).map(|e| e.node);
1759
        let node = match node_in(self.load_state_indexed(&wc.deps)?) {
1760
            Some(n) => Some(n),
1761
            None => node_in(self.load_state_history(&heads)?),
1762
        };
1763
        let Some(node) = node else {
1764
            return fail(format!("{path} is not tracked"));
1765
        };
1766
        Ok(self.entries_touching(entries, node))
1767
    }
1768
1769
    /// The log of the state with these heads restricted to changes touching
1770
    /// `path` (its node, so renames are followed).
1771
    pub fn log_for_path_in(&self, path: &str, heads: &[ChangeHash]) -> Result<Vec<LogEntry>> {
1772
        self.log_for_path_of(&self.load_state_history(heads)?, path, None)
1773
    }
1774
1775
    /// The changes of a loaded state touching `path`, newest first, at most
1776
    /// `limit` of them. The path is found in the state's tree alone, so no
1777
    /// file is rendered, and the walk stops once `limit` are found.
1778
    pub fn log_for_path_of(
1779
        &self,
1780
        state: &State,
1781
        path: &str,
1782
        limit: Option<usize>,
1783
    ) -> Result<Vec<LogEntry>> {
1784
        let Some(node) = state.tree().view().entries.get(path).map(|e| e.node) else {
1785
            return fail(format!("{path} is not in that state"));
1786
        };
1787
        Ok(self.entries_touching_up_to(self.log_of(state), node, limit))
1788
    }
1789
1790
    fn entries_touching(&self, entries: Vec<LogEntry>, node: NodeId) -> Vec<LogEntry> {
1791
        self.entries_touching_up_to(entries, node, None)
1792
    }
1793
1794
    fn entries_touching_up_to(
1795
        &self,
1796
        entries: Vec<LogEntry>,
1797
        node: NodeId,
1798
        limit: Option<usize>,
1799
    ) -> Vec<LogEntry> {
1800
        let mut touched = self.touched();
1801
        if limit.is_none() {
1802
            let hashes: Vec<ChangeHash> = entries.iter().map(|e| e.hash).collect();
1803
            touched.fill(self, &hashes);
1804
        }
1805
        let wanted = HashSet::from([node]);
1806
        let mut out = Vec::new();
1807
        for e in entries {
1808
            if limit.is_some_and(|n| out.len() >= n) {
1809
                break;
1810
            }
1811
            if touched.touches(self, &e.hash, &wanted) {
1812
                out.push(e);
1813
            }
1814
        }
1815
        touched.save();
1816
        out
1817
    }
1818
}
1819
1820
/// Per-file hunks of `change` against `base`.
1821
pub fn diff_files_of(change: &Change, base: &State, base_snapshot: &Snapshot) -> Vec<FileDiff> {
1822
    let by_node = base_snapshot.tree.by_node();
1823
    let mut new_names: HashMap<NodeId, (NodeId, String, NodeKind)> = HashMap::new();
1824
    for op in &change.tree_ops {
1825
        if let TreeOp::AddNode {
1826
            node,
1827
            parent,
1828
            name,
1829
            kind,
1830
            ..
1831
        } = op
1832
        {
1833
            new_names.insert(*node, (*parent, name.clone(), *kind));
1834
        }
1835
    }
1836
    let path_of = |n: &NodeId| -> String {
1837
        path_of_node(n, &by_node, &new_names).unwrap_or_else(|| format!("<node {}>", n.short(8)))
1838
    };
1839
    let mut files: BTreeMap<NodeId, FileDiff> = BTreeMap::new();
1840
    let mut order: Vec<NodeId> = Vec::new();
1841
    let mut entry = |files: &mut BTreeMap<NodeId, FileDiff>, n: NodeId, kind: &str| {
1842
        if let std::collections::btree_map::Entry::Vacant(v) = files.entry(n) {
1843
            order.push(n);
1844
            v.insert(FileDiff {
1845
                path: path_of(&n),
1846
                kind: kind.to_string(),
1847
                hunks: vec![],
1848
                from: None,
1849
            });
1850
        }
1851
    };
1852
    for op in &change.tree_ops {
1853
        match op {
1854
            TreeOp::AddNode { node, kind, .. } => {
1855
                if *kind != NodeKind::Dir {
1856
                    entry(&mut files, *node, "added");
1857
                }
1858
            }
1859
            TreeOp::RemoveNode { node, .. } => {
1860
                entry(&mut files, *node, "removed");
1861
                if let Some(e) = by_node.get(node) {
1862
                    files.get_mut(node).unwrap().path = e.path.clone();
1863
                }
1864
            }
1865
            TreeOp::Move {
1866
                node, parent, name, ..
1867
            } => {
1868
                entry(&mut files, *node, "renamed");
1869
                let f = files.get_mut(node).unwrap();
1870
                f.from = by_node.get(node).map(|e| e.path.clone());
1871
                let dir = if parent.is_root() {
1872
                    String::new()
1873
                } else {
1874
                    path_of_node(parent, &by_node, &new_names).unwrap_or_default()
1875
                };
1876
                f.path = if dir.is_empty() {
1877
                    name.clone()
1878
                } else {
1879
                    format!("{dir}/{name}")
1880
                };
1881
            }
1882
            TreeOp::SetMode { node, .. } => entry(&mut files, *node, "mode"),
1883
        }
1884
    }
1885
    // Base line numbers per node, 1-based.
1886
    let mut line_of: HashMap<NodeId, HashMap<(ChangeHash, u32), u32>> = HashMap::new();
1887
    let mut lines_for = |n: &NodeId| -> HashMap<(ChangeHash, u32), u32> {
1888
        line_of
1889
            .entry(*n)
1890
            .or_insert_with(|| {
1891
                base.live_lines(n)
1892
                    .into_iter()
1893
                    .enumerate()
1894
                    .map(|(i, (k, _))| (k, i as u32 + 1))
1895
                    .collect()
1896
            })
1897
            .clone()
1898
    };
1899
    for e in &change.edits {
1900
        let n = e.node();
1901
        let is_new = new_names.contains_key(&n);
1902
        entry(&mut files, n, if is_new { "added" } else { "modified" });
1903
        let f = files.get_mut(&n).unwrap();
1904
        match e {
1905
            Edit::Insert { after, lines, .. } => {
1906
                let map = lines_for(&n);
1907
                let base_line = match after {
1908
                    AtomRef::Start => 0,
1909
                    AtomRef::End => map.len() as u32,
1910
                    AtomRef::Atom { change, index } if change.is_zero() => {
1911
                        f.hunks.last().map(|h| h.base_line).unwrap_or(0)
1912
                    }
1913
                    AtomRef::Atom { change, index } => {
1914
                        map.get(&(*change, *index)).copied().unwrap_or(0)
1915
                    }
1916
                };
1917
                f.hunks.push(DiffHunk {
1918
                    base_line,
1919
                    added: lines.to_vec(),
1920
                    removed: vec![],
1921
                });
1922
            }
1923
            Edit::Delete { atoms, .. } => {
1924
                let map = lines_for(&n);
1925
                let mut removed = Vec::new();
1926
                for r in atoms {
1927
                    for i in r.from..r.to {
1928
                        let line = map.get(&(r.change, i)).copied().unwrap_or(0);
1929
                        let text = base
1930
                            .file(&n)
1931
                            .and_then(|g| g.content(&(r.change, i)))
1932
                            .unwrap_or(b"")
1933
                            .to_vec();
1934
                        removed.push((line, text));
1935
                    }
1936
                }
1937
                let base_line = removed
1938
                    .first()
1939
                    .map(|(l, _)| l.saturating_sub(1))
1940
                    .unwrap_or(0);
1941
                f.hunks.push(DiffHunk {
1942
                    base_line,
1943
                    added: vec![],
1944
                    removed,
1945
                });
1946
            }
1947
            Edit::Replace { .. } => {
1948
                if !is_new {
1949
                    f.kind = "replaced".into();
1950
                }
1951
            }
1952
        }
1953
    }
1954
    order.into_iter().filter_map(|n| files.remove(&n)).collect()
1955
}
1956
1957
/// Builds the tree ops and edits of a working-copy change against a base.
1958
/// `BLAKE3("oxy node 1" 0 seed kind path)`, truncated: a node identifier
1959
/// that the same seed and path always give (never the root's).
1960
fn seeded_node(seed: &[u8; 32], path: &str, kind: NodeKind) -> NodeId {
1961
    let mut h = blake3::Hasher::new();
1962
    h.update(b"oxy node 1\0");
1963
    h.update(seed);
1964
    h.update(&[match kind {
1965
        NodeKind::File => 1,
1966
        NodeKind::Dir => 2,
1967
        NodeKind::Symlink => 3,
1968
        NodeKind::Subrepo => 4,
1969
    }]);
1970
    h.update(path.as_bytes());
1971
    let mut id = [0u8; 16];
1972
    id.copy_from_slice(&h.finalize().as_bytes()[..16]);
1973
    if id == [0; 16] {
1974
        id[15] = 1;
1975
    }
1976
    NodeId(id)
1977
}
1978
1979
struct ChangeBuilder<'a> {
1980
    base: &'a State,
1981
    base_snapshot: &'a Snapshot,
1982
    tree_ops: Vec<TreeOp>,
1983
    edits: Vec<Edit>,
1984
    statuses: Vec<PathStatus>,
1985
    dir_nodes: HashMap<String, NodeId>,
1986
    reuse: HashMap<String, (NodeId, NodeKind)>,
1987
    /// Changes that contributed to conflicts this working copy resolves.
1988
    contributors: BTreeSet<ChangeHash>,
1989
    resolves: bool,
1990
    attrs: crate::attributes::Attributes,
1991
    blobs: HashMap<String, ObjectRef>,
1992
    /// Opaque files whose replace conflict the content settles.
1993
    resolve: HashSet<String>,
1994
    /// When set, new nodes' identifiers derive from it and their paths.
1995
    node_seed: Option<[u8; 32]>,
1996
    /// For a Git import, the base's dead directories by where they were
1997
    /// (see `ensure_dir`), worked out when first needed.
1998
    dead_dirs: Option<HashMap<(NodeId, String), (NodeId, crate::tree::OpKey)>>,
1999
    /// Text edits of edited files, worked out in parallel beforehand
2000
    /// (`diff_in_parallel`); a file not here is diffed when it is updated.
2001
    diffs: HashMap<String, Vec<Edit>>,
2002
}
2003
2004
impl<'a> ChangeBuilder<'a> {
2005
    fn new(
2006
        base: &'a State,
2007
        base_snapshot: &'a Snapshot,
2008
        reuse: HashMap<String, (NodeId, NodeKind)>,
2009
    ) -> Self {
2010
        let mut dir_nodes: HashMap<String, NodeId> = HashMap::new();
2011
        dir_nodes.insert(String::new(), NodeId::ROOT);
2012
        for (p, e) in base_snapshot.tree.entries.iter() {
2013
            if e.kind == NodeKind::Dir {
2014
                dir_nodes.insert(p.clone(), e.node);
2015
            }
2016
        }
2017
        ChangeBuilder {
2018
            base,
2019
            base_snapshot,
2020
            tree_ops: vec![],
2021
            edits: vec![],
2022
            statuses: vec![],
2023
            dir_nodes,
2024
            reuse,
2025
            contributors: BTreeSet::new(),
2026
            resolves: false,
2027
            attrs: crate::attributes::Attributes::default(),
2028
            blobs: HashMap::new(),
2029
            resolve: HashSet::new(),
2030
            node_seed: None,
2031
            dead_dirs: None,
2032
            diffs: HashMap::new(),
2033
        }
2034
    }
2035
2036
    /// Diff the edited text files among `entries` against their base
2037
    /// renderings at once, on every core, for `update_path` to take: the
2038
    /// same diff it would make, only not one file after another.
2039
    fn diff_in_parallel(&mut self, entries: &BTreeMap<String, FsEntry>) {
2040
        use rayon::prelude::*;
2041
        let files = &self.base_snapshot.files;
2042
        let edited: Vec<(&String, &FsEntry, &crate::state::FileState)> = entries
2043
            .iter()
2044
            .filter_map(|(p, e)| {
2045
                let x = files.get(p)?;
2046
                (x.kind == e.kind && !e.unchanged && !self.opaque_for(p, e)).then_some((p, e, x))
2047
            })
2048
            .collect();
2049
        // Below this, starting the threads costs more than it saves.
2050
        if edited.len() < 16 {
2051
            return;
2052
        }
2053
        let this = &*self;
2054
        let attrs = &this.attrs;
2055
        let diffs: Vec<(String, Vec<Edit>)> = edited
2056
            .par_iter()
2057
            .filter_map(|(p, e, x)| {
2058
                let FileContent::Text {
2059
                    bytes,
2060
                    materialized,
2061
                } = &x.content
2062
                else {
2063
                    return None;
2064
                };
2065
                if materialized.is_conflicted() {
2066
                    return None;
2067
                }
2068
                let disk_text = if attrs.lookup(p).eol.is_some() {
2069
                    std::sync::Arc::new(crate::attributes::normalize_eol(&e.content))
2070
                } else {
2071
                    e.content.clone()
2072
                };
2073
                if *bytes == *disk_text {
2074
                    return None;
2075
                }
2076
                let keys = materialized.live_atoms();
2077
                let lines = crate::diff::split_lines(bytes);
2078
                (keys.len() == lines.len()).then(|| {
2079
                    let edits = crate::diff::text_edits_of(x.node, &keys, &lines, &disk_text);
2080
                    ((*p).clone(), edits)
2081
                })
2082
            })
2083
            .collect();
2084
        self.diffs = diffs.into_iter().collect();
2085
    }
2086
2087
    fn with_attributes(mut self, attrs: crate::attributes::Attributes) -> Self {
2088
        self.attrs = attrs;
2089
        self
2090
    }
2091
2092
    /// Whether a file is opaque: forced by `binary`, forced text by `text`
2093
    /// only when it has no NUL bytes, else sniffed.
2094
    /// The blob for an opaque entry: the cached one, else stored now.
2095
    fn blob_of(
2096
        &mut self,
2097
        repo: &Repo,
2098
        path: &str,
2099
        e: &FsEntry,
2100
        nocompress: bool,
2101
    ) -> Result<ObjectRef> {
2102
        let b = match e.blob {
2103
            Some(b) => b,
2104
            None => repo.store_blob_for(&e.content, nocompress)?,
2105
        };
2106
        self.blobs.insert(path.to_string(), b);
2107
        Ok(b)
2108
    }
2109
2110
    fn opaque_for(&self, path: &str, e: &FsEntry) -> bool {
2111
        if e.blob.is_some() {
2112
            return true;
2113
        }
2114
        if e.kind == NodeKind::Symlink || e.kind == NodeKind::Subrepo {
2115
            return true;
2116
        }
2117
        match self.attrs.lookup(path).binary {
2118
            Some(true) => true,
2119
            Some(false) => is_binary(&e.content),
2120
            None => is_binary(&e.content),
2121
        }
2122
    }
2123
2124
    /// Text content as stored: `\r\n` normalized for `eol=` files.
2125
    fn stored_text(
2126
        &self,
2127
        path: &str,
2128
        content: &std::sync::Arc<Vec<u8>>,
2129
    ) -> std::sync::Arc<Vec<u8>> {
2130
        if self.attrs.lookup(path).eol.is_some() {
2131
            std::sync::Arc::new(crate::attributes::normalize_eol(content))
2132
        } else {
2133
            content.clone()
2134
        }
2135
    }
2136
2137
    /// The identifier of a node added at `path`: reused when asked, derived
2138
    /// from the seed when there is one, random otherwise.
2139
    fn new_node(&self, path: &str, kind: NodeKind) -> NodeId {
2140
        if let Some(n) = self.reused_node(path, kind) {
2141
            return n;
2142
        }
2143
        match &self.node_seed {
2144
            Some(seed) => seeded_node(seed, path, kind),
2145
            None => NodeId::random(),
2146
        }
2147
    }
2148
2149
    fn reused_node(&self, path: &str, kind: NodeKind) -> Option<NodeId> {
2150
        self.reuse
2151
            .get(path)
2152
            .filter(|(_, k)| *k == kind)
2153
            .map(|(n, _)| *n)
2154
    }
2155
2156
    /// A dead directory last placed at (`parent`, `name`) in the base.
2157
    fn revivable_dir(
2158
        &mut self,
2159
        parent: NodeId,
2160
        name: &str,
2161
    ) -> Option<(NodeId, crate::tree::OpKey)> {
2162
        let base = self.base;
2163
        self.dead_dirs
2164
            .get_or_insert_with(|| base.tree().dead_dirs())
2165
            .get(&(parent, name.to_string()))
2166
            .copied()
2167
    }
2168
2169
    fn ensure_dir(&mut self, path: &str) -> NodeId {
2170
        if let Some(n) = self.dir_nodes.get(path) {
2171
            return *n;
2172
        }
2173
        let mut parent = NodeId::ROOT;
2174
        let mut prefix = String::new();
2175
        for comp in path.split('/') {
2176
            if !prefix.is_empty() {
2177
                prefix.push('/');
2178
            }
2179
            prefix.push_str(comp);
2180
            let known = self.dir_nodes.get(&prefix).copied();
2181
            let revive = match known {
2182
                Some(_) => None,
2183
                None if self.node_seed.is_some() => self.revivable_dir(parent, comp),
2184
                None => None,
2185
            };
2186
            parent = match (known, revive) {
2187
                (Some(n), _) => n,
2188
                (None, Some((node, old))) => {
2189
                    // Git has no identity for a directory: one that comes
2190
                    // back where it was is the same directory, brought back
2191
                    // with a move, so lines of history that placed files in
2192
                    // it before and after agree (oxygen#30).
2193
                    self.tree_ops.push(TreeOp::Move {
2194
                        node,
2195
                        old: OpRef {
2196
                            change: old.0,
2197
                            index: old.1,
2198
                        },
2199
                        parent,
2200
                        name: comp.to_string(),
2201
                    });
2202
                    self.dir_nodes.insert(prefix.clone(), node);
2203
                    node
2204
                }
2205
                (None, None) => {
2206
                    let node = self.new_node(&prefix, NodeKind::Dir);
2207
                    self.tree_ops.push(TreeOp::AddNode {
2208
                        node,
2209
                        kind: NodeKind::Dir,
2210
                        mode: Mode::default(),
2211
                        parent,
2212
                        name: comp.to_string(),
2213
                    });
2214
                    self.dir_nodes.insert(prefix.clone(), node);
2215
                    node
2216
                }
2217
            };
2218
        }
2219
        parent
2220
    }
2221
2222
    fn add_path(&mut self, repo: &Repo, path: &str, e: &FsEntry) -> Result<()> {
2223
        let (dir, name) = split_path(path);
2224
        let parent = self.ensure_dir(dir);
2225
        let node = self.new_node(path, e.kind);
2226
        let opaque = self.opaque_for(path, e);
2227
        let nocompress = self.attrs.lookup(path).nocompress;
2228
        self.tree_ops.push(TreeOp::AddNode {
2229
            node,
2230
            kind: e.kind,
2231
            mode: Mode {
2232
                exec: e.exec,
2233
                opaque,
2234
            },
2235
            parent,
2236
            name: name.to_string(),
2237
        });
2238
        if opaque {
2239
            let blob = self.blob_of(repo, path, e, nocompress)?;
2240
            self.edits.push(Edit::Replace {
2241
                node,
2242
                old: None,
2243
                new: Some(blob),
2244
            });
2245
        } else if !e.content.is_empty() {
2246
            let content = self.stored_text(path, &e.content);
2247
            self.edits.push(Edit::Insert {
2248
                node,
2249
                after: crate::objects::AtomRef::Start,
2250
                before: crate::objects::AtomRef::End,
2251
                lines: crate::lines::Lines::split_shared(content),
2252
            });
2253
        }
2254
        self.statuses.push(PathStatus {
2255
            path: path.to_string(),
2256
            status: ChangeStatus::Added,
2257
        });
2258
        Ok(())
2259
    }
2260
2261
    /// Move the node at `old` to `new` and apply `e`'s content to it.
2262
    fn move_path(
2263
        &mut self,
2264
        repo: &Repo,
2265
        old: &str,
2266
        new: &str,
2267
        e: &FsEntry,
2268
        expected: &crate::state::FileState,
2269
    ) -> Result<()> {
2270
        let placement = self.base_snapshot.tree.entries[old].placement;
2271
        let (dir, name) = split_path(new);
2272
        let parent = self.ensure_dir(dir);
2273
        self.tree_ops.push(TreeOp::Move {
2274
            node: expected.node,
2275
            old: op_ref(placement),
2276
            parent,
2277
            name: name.to_string(),
2278
        });
2279
        for k in self.same_place(&expected.node, placement) {
2280
            self.tree_ops.push(TreeOp::RemoveNode {
2281
                node: expected.node,
2282
                placement: op_ref(k),
2283
            });
2284
        }
2285
        self.update_path(repo, old, e, expected)?;
2286
        // update_path reports under the old path; the rename is what the user sees.
2287
        self.statuses.retain(|s| s.path != old);
2288
        self.statuses.push(PathStatus {
2289
            path: new.to_string(),
2290
            status: ChangeStatus::Renamed,
2291
        });
2292
        Ok(())
2293
    }
2294
2295
    /// For a Git import: a node the commit keeps is in one place, the one
2296
    /// its tree names, so any other live placement it has in the base goes;
2297
    /// and a node the tree cannot show at all (an orphan) goes too. Such a
2298
    /// placement is out of sight, under a directory another line of history
2299
    /// removed, where no diff of the tree would ever reach it (oxygen#30).
2300
    fn retire_stray_placements(&mut self) {
2301
        let mut retired: HashSet<(ChangeHash, u32)> = HashSet::new();
2302
        let mut placed: BTreeSet<NodeId> = BTreeSet::new();
2303
        for op in &self.tree_ops {
2304
            match op {
2305
                TreeOp::Move { node, old, .. } => {
2306
                    retired.insert((old.change, old.index));
2307
                    placed.insert(*node);
2308
                }
2309
                TreeOp::RemoveNode { placement, .. } => {
2310
                    retired.insert((placement.change, placement.index));
2311
                }
2312
                TreeOp::AddNode { .. } | TreeOp::SetMode { .. } => {}
2313
            }
2314
        }
2315
        // Nodes kept where they were: what the base's tree view shows and
2316
        // this change neither moves nor removes.
2317
        let mut kept: HashMap<NodeId, (ChangeHash, u32)> = HashMap::new();
2318
        for e in self.base_snapshot.tree.entries.values() {
2319
            if !retired.contains(&e.placement) {
2320
                kept.insert(e.node, e.placement);
2321
            }
2322
        }
2323
        // Only a node with several live placements can have a stray one,
2324
        // and the tree view names each as a conflict.
2325
        let multi: BTreeSet<NodeId> = self
2326
            .base_snapshot
2327
            .tree
2328
            .conflicts
2329
            .iter()
2330
            .filter_map(|c| match c {
2331
                crate::tree::TreeConflict::MultiPlacement { node, .. } => Some(*node),
2332
                _ => None,
2333
            })
2334
            .collect();
2335
        let mut extra = Vec::new();
2336
        // A node whose only placements are under a directory another line
2337
        // removed (an orphan) is nowhere the tree can show, and Git's tree
2338
        // has no such path: it goes.
2339
        for c in &self.base_snapshot.tree.conflicts {
2340
            let crate::tree::TreeConflict::Orphan { node, .. } = c else {
2341
                continue;
2342
            };
2343
            if kept.contains_key(node) || placed.contains(node) {
2344
                continue;
2345
            }
2346
            for (k, _) in self.base.tree().live_placements(node) {
2347
                if retired.insert(k) {
2348
                    extra.push(TreeOp::RemoveNode {
2349
                        node: *node,
2350
                        placement: op_ref(k),
2351
                    });
2352
                }
2353
            }
2354
        }
2355
        for node in placed
2356
            .iter()
2357
            .chain(multi.iter().filter(|n| kept.contains_key(*n)))
2358
        {
2359
            for (k, _) in self.base.tree().live_placements(node) {
2360
                if retired.contains(&k) || kept.get(node) == Some(&k) {
2361
                    continue;
2362
                }
2363
                retired.insert(k);
2364
                extra.push(TreeOp::RemoveNode {
2365
                    node: *node,
2366
                    placement: op_ref(k),
2367
                });
2368
            }
2369
        }
2370
        if !extra.is_empty() {
2371
            self.resolves = true;
2372
            self.tree_ops.extend(extra);
2373
        }
2374
    }
2375
2376
    /// The node's other live placements at the same place as `k`, the one
2377
    /// the tree shows: two lines of history that put a node back where it
2378
    /// was each leave a placement, and the tree shows them as one file. A
2379
    /// change that removes or moves it retires them together, or the copy
2380
    /// left behind outlives its directory (oxygen#88).
2381
    fn same_place(&self, node: &NodeId, k: (ChangeHash, u32)) -> Vec<(ChangeHash, u32)> {
2382
        let tree = self.base.tree();
2383
        let Some(shown) = tree.placement(&k) else {
2384
            return Vec::new();
2385
        };
2386
        tree.live_placements(node)
2387
            .into_iter()
2388
            .filter(|(o, p)| *o != k && p.parent == shown.parent && p.name == shown.name)
2389
            .map(|(o, _)| o)
2390
            .collect()
2391
    }
2392
2393
    fn remove_path(&mut self, path: &str, expected: &crate::state::FileState) {
2394
        let entry = &self.base_snapshot.tree.entries[path];
2395
        let placement = entry.placement;
2396
        self.tree_ops.push(TreeOp::RemoveNode {
2397
            node: expected.node,
2398
            placement: op_ref(placement),
2399
        });
2400
        for k in self.same_place(&expected.node, placement) {
2401
            self.tree_ops.push(TreeOp::RemoveNode {
2402
                node: expected.node,
2403
                placement: op_ref(k),
2404
            });
2405
        }
2406
        if path.contains(".oxy-conflict-") || expected.is_conflicted() {
2407
            self.resolves = true;
2408
        }
2409
        self.statuses.push(PathStatus {
2410
            path: path.to_string(),
2411
            status: ChangeStatus::Removed,
2412
        });
2413
    }
2414
2415
    fn update_path(
2416
        &mut self,
2417
        repo: &Repo,
2418
        path: &str,
2419
        e: &FsEntry,
2420
        expected: &crate::state::FileState,
2421
    ) -> Result<()> {
2422
        if expected.kind != e.kind {
2423
            self.remove_path(path, expected);
2424
            self.statuses.pop();
2425
            self.add_path(repo, path, e)?;
2426
            self.statuses.pop();
2427
            self.statuses.push(PathStatus {
2428
                path: path.to_string(),
2429
                status: ChangeStatus::Modified,
2430
            });
2431
            return Ok(());
2432
        }
2433
        let entry = &self.base_snapshot.tree.entries[path];
2434
        let node = expected.node;
2435
        let mode_atom = entry.mode_atom.map(op_ref);
2436
        if e.unchanged {
2437
            // Known equal to the base's unconflicted rendering (spec
2438
            // §12.3); only the executable bit can differ.
2439
            if e.exec != expected.mode.exec {
2440
                if let Some(old) = mode_atom {
2441
                    self.tree_ops.push(TreeOp::SetMode {
2442
                        node,
2443
                        old,
2444
                        mode: Mode {
2445
                            exec: e.exec,
2446
                            opaque: false,
2447
                        },
2448
                    });
2449
                    self.statuses.push(PathStatus {
2450
                        path: path.to_string(),
2451
                        status: ChangeStatus::ModeChanged,
2452
                    });
2453
                }
2454
            }
2455
            return Ok(());
2456
        }
2457
        let mut status: Option<ChangeStatus> = None;
2458
        let wants_opaque = self.opaque_for(path, e);
2459
        let nocompress = self.attrs.lookup(path).nocompress;
2460
        let disk_text = self.stored_text(path, &e.content);
2461
        match &expected.content {
2462
            FileContent::Dir => {}
2463
            FileContent::Text {
2464
                bytes,
2465
                materialized,
2466
            } => {
2467
                if materialized.is_conflicted() {
2468
                    if bytes == &*disk_text {
2469
                        return Ok(());
2470
                    }
2471
                    if has_conflict_markers(&e.content) {
2472
                        self.statuses.push(PathStatus {
2473
                            path: path.to_string(),
2474
                            status: ChangeStatus::ConflictEdited,
2475
                        });
2476
                        return Ok(());
2477
                    }
2478
                    // Resolution (spec §9.6): diff against the unconflicted lines
2479
                    // with each region as a gap, then retire every region atom.
2480
                    // Whatever the author kept from a region is re-inserted as
2481
                    // new atoms, which leaves the graph totally ordered.
2482
                    let regions = self.base.conflict_regions(&node);
2483
                    let mut edits = text_edits(node, &regions.plain, &disk_text);
2484
                    if !regions.region_atoms.is_empty() {
2485
                        edits.insert(
2486
                            0,
2487
                            Edit::Delete {
2488
                                node,
2489
                                atoms: ranges(&regions.region_atoms),
2490
                            },
2491
                        );
2492
                    }
2493
                    self.edits.extend(edits);
2494
                    self.contributors.extend(regions.contributors);
2495
                    self.resolves = true;
2496
                    if e.exec != expected.mode.exec {
2497
                        if let Some(old) = mode_atom {
2498
                            self.tree_ops.push(TreeOp::SetMode {
2499
                                node,
2500
                                old,
2501
                                mode: Mode {
2502
                                    exec: e.exec,
2503
                                    opaque: false,
2504
                                },
2505
                            });
2506
                        }
2507
                    }
2508
                    self.statuses.push(PathStatus {
2509
                        path: path.to_string(),
2510
                        status: ChangeStatus::Resolved,
2511
                    });
2512
                    return Ok(());
2513
                }
2514
                if wants_opaque {
2515
                    // Text → opaque (spec §7.5), by content or by attribute.
2516
                    if let Some(old) = mode_atom {
2517
                        self.tree_ops.push(TreeOp::SetMode {
2518
                            node,
2519
                            old,
2520
                            mode: Mode {
2521
                                exec: e.exec,
2522
                                opaque: true,
2523
                            },
2524
                        });
2525
                    }
2526
                    let live: Vec<_> = repo_live_keys(self.base, &node);
2527
                    if !live.is_empty() {
2528
                        self.edits.push(Edit::Delete {
2529
                            node,
2530
                            atoms: ranges(&live),
2531
                        });
2532
                    }
2533
                    let blob = self.blob_of(repo, path, e, nocompress)?;
2534
                    self.edits.push(Edit::Replace {
2535
                        node,
2536
                        old: None,
2537
                        new: Some(blob),
2538
                    });
2539
                    status = Some(ChangeStatus::Modified);
2540
                } else if bytes != &*disk_text {
2541
                    let mut laps = crate::timing::Laps::start();
2542
                    // The base's rendering holds its live atoms in order,
2543
                    // one per line (it is not conflicted here).
2544
                    let edits = match self.diffs.remove(path) {
2545
                        Some(edits) => edits,
2546
                        None => {
2547
                            let keys = materialized.live_atoms();
2548
                            let lines = crate::diff::split_lines(bytes);
2549
                            if keys.len() == lines.len() {
2550
                                crate::diff::text_edits_of(node, &keys, &lines, &disk_text)
2551
                            } else {
2552
                                text_edits(node, &self.base.live_lines(&node), &disk_text)
2553
                            }
2554
                        }
2555
                    };
2556
                    laps.lap("build: text diff");
2557
                    if !edits.is_empty() {
2558
                        self.edits.extend(edits);
2559
                        status = Some(ChangeStatus::Modified);
2560
                    }
2561
                }
2562
                let switched_to_opaque = wants_opaque;
2563
                if !switched_to_opaque && e.exec != expected.mode.exec {
2564
                    if let Some(old) = mode_atom {
2565
                        self.tree_ops.push(TreeOp::SetMode {
2566
                            node,
2567
                            old,
2568
                            mode: Mode {
2569
                                exec: e.exec,
2570
                                opaque: false,
2571
                            },
2572
                        });
2573
                        status.get_or_insert(ChangeStatus::ModeChanged);
2574
                    }
2575
                }
2576
            }
2577
            FileContent::Opaque { blobs } => {
2578
                let new_ref = e.blob.unwrap_or_else(|| Repo::blob_ref(&e.content));
2579
                if e.kind == NodeKind::File && wants_opaque {
2580
                    // Unchanged or replaced, the file stays opaque: remember its blob.
2581
                    self.blobs.insert(path.to_string(), new_ref);
2582
                }
2583
                if blobs.len() > 1 && self.resolve.contains(path) && e.kind == expected.kind {
2584
                    // Settle the replace conflict (spec §9.3): replace every
2585
                    // live candidate with the chosen blob, depending on each
2586
                    // change that made one live, so all are superseded.
2587
                    let chosen = self.blob_of(repo, path, e, nocompress)?;
2588
                    for b in blobs {
2589
                        self.edits.push(Edit::Replace {
2590
                            node,
2591
                            old: Some(*b),
2592
                            new: Some(chosen),
2593
                        });
2594
                    }
2595
                    self.contributors
2596
                        .extend(self.base.blob_contributors(&node, blobs));
2597
                    self.resolves = true;
2598
                    self.statuses.push(PathStatus {
2599
                        path: path.to_string(),
2600
                        status: ChangeStatus::Resolved,
2601
                    });
2602
                    return Ok(());
2603
                }
2604
                if blobs.len() > 1 {
2605
                    if !blobs.contains(&new_ref) {
2606
                        self.statuses.push(PathStatus {
2607
                            path: path.to_string(),
2608
                            status: ChangeStatus::ConflictEdited,
2609
                        });
2610
                    }
2611
                    return Ok(());
2612
                }
2613
                let current = blobs.first().copied();
2614
                if current != Some(new_ref) {
2615
                    if e.kind == NodeKind::File && !wants_opaque {
2616
                        // Opaque → text (spec §7.5).
2617
                        if let Some(old) = mode_atom {
2618
                            self.tree_ops.push(TreeOp::SetMode {
2619
                                node,
2620
                                old,
2621
                                mode: Mode {
2622
                                    exec: e.exec,
2623
                                    opaque: false,
2624
                                },
2625
                            });
2626
                        }
2627
                        self.edits.push(Edit::Replace {
2628
                            node,
2629
                            old: current,
2630
                            new: None,
2631
                        });
2632
                        if !e.content.is_empty() {
2633
                            self.edits.push(Edit::Insert {
2634
                                node,
2635
                                after: crate::objects::AtomRef::Start,
2636
                                before: crate::objects::AtomRef::End,
2637
                                lines: crate::lines::Lines::split(&e.content),
2638
                            });
2639
                        }
2640
                    } else {
2641
                        let blob = self.blob_of(repo, path, e, nocompress)?;
2642
                        self.edits.push(Edit::Replace {
2643
                            node,
2644
                            old: current,
2645
                            new: Some(blob),
2646
                        });
2647
                        // New contents and a new executable bit at once: the
2648
                        // bit was dropped (VS Code's inno_updater.exe,
2649
                        // 2018-02-28, lost +x for 49 commits; oxygen#87).
2650
                        if e.kind == NodeKind::File && e.exec != expected.mode.exec {
2651
                            if let Some(old) = mode_atom {
2652
                                self.tree_ops.push(TreeOp::SetMode {
2653
                                    node,
2654
                                    old,
2655
                                    mode: Mode {
2656
                                        exec: e.exec,
2657
                                        opaque: true,
2658
                                    },
2659
                                });
2660
                            }
2661
                        }
2662
                    }
2663
                    status = Some(ChangeStatus::Modified);
2664
                } else if e.kind == NodeKind::File && e.exec != expected.mode.exec {
2665
                    if let Some(old) = mode_atom {
2666
                        self.tree_ops.push(TreeOp::SetMode {
2667
                            node,
2668
                            old,
2669
                            mode: Mode {
2670
                                exec: e.exec,
2671
                                opaque: true,
2672
                            },
2673
                        });
2674
                        status = Some(ChangeStatus::ModeChanged);
2675
                    }
2676
                }
2677
            }
2678
        }
2679
        if let Some(s) = status {
2680
            self.statuses.push(PathStatus {
2681
                path: path.to_string(),
2682
                status: s,
2683
            });
2684
        }
2685
        Ok(())
2686
    }
2687
}
2688
2689
fn repo_live_keys(base: &State, node: &NodeId) -> Vec<crate::graph::AtomKey> {
2690
    base.live_lines(node).into_iter().map(|(k, _)| k).collect()
2691
}
2692
2693
/// The changes a change's scope references (spec §8.1): introducers of every
2694
/// atom, placement, and mode it touches, and of every node it operates on.
2695
pub fn referenced_changes(change: &Change, base: &State) -> BTreeSet<ChangeHash> {
2696
    let mut out = BTreeSet::new();
2697
    let opref = |r: &OpRef, out: &mut BTreeSet<ChangeHash>| {
2698
        if !r.change.is_zero() {
2699
            out.insert(r.change);
2700
        }
2701
    };
2702
    let mut nodes: Vec<NodeId> = Vec::new();
2703
    for op in &change.tree_ops {
2704
        match op {
2705
            TreeOp::AddNode { parent, .. } => nodes.push(*parent),
2706
            TreeOp::RemoveNode { node, placement } => {
2707
                nodes.push(*node);
2708
                opref(placement, &mut out);
2709
            }
2710
            TreeOp::Move {
2711
                node, old, parent, ..
2712
            } => {
2713
                nodes.push(*node);
2714
                nodes.push(*parent);
2715
                opref(old, &mut out);
2716
            }
2717
            TreeOp::SetMode { node, old, .. } => {
2718
                nodes.push(*node);
2719
                opref(old, &mut out);
2720
            }
2721
        }
2722
    }
2723
    for e in &change.edits {
2724
        nodes.push(e.node());
2725
        match e {
2726
            Edit::Insert { after, before, .. } => {
2727
                for r in [after, before] {
2728
                    if let crate::objects::AtomRef::Atom { change, .. } = r {
2729
                        if !change.is_zero() {
2730
                            out.insert(*change);
2731
                        }
2732
                    }
2733
                }
2734
            }
2735
            Edit::Delete { atoms, .. } => {
2736
                // Deleting an atom also depends on whoever inserted the live
2737
                // atoms right after it: the author saw those insertions, and
2738
                // without the dependency spec §9.1 would call the deletion
2739
                // concurrent with them (a delete/insert conflict).
2740
                let graph = base.file(&e.node());
2741
                for r in atoms {
2742
                    if !r.change.is_zero() {
2743
                        out.insert(r.change);
2744
                    }
2745
                    if let Some(g) = graph {
2746
                        for i in r.from..r.to {
2747
                            out.extend(
2748
                                g.live_successor_changes(&(r.change, i))
2749
                                    .into_iter()
2750
                                    .filter(|c| !c.is_zero()),
2751
                            );
2752
                        }
2753
                    }
2754
                }
2755
            }
2756
            // Replacing a blob depends on the change that made it current,
2757
            // as deleting a line depends on the line's introducer.
2758
            Edit::Replace {
2759
                node,
2760
                old: Some(old),
2761
                ..
2762
            } => {
2763
                out.extend(
2764
                    base.live_replaces(node)
2765
                        .into_iter()
2766
                        .filter(|(c, b)| b == old && !c.is_zero())
2767
                        .map(|(c, _)| c),
2768
                );
2769
            }
2770
            Edit::Replace { .. } => {}
2771
        }
2772
    }
2773
    for n in nodes {
2774
        if let Some(h) = base.tree().introducer(&n) {
2775
            out.insert(h);
2776
        }
2777
    }
2778
    out
2779
}
2780
2781
/// Paths of the nodes a change adds on top of `base_snapshot`.
2782
pub fn added_node_paths(
2783
    change: &Change,
2784
    base_snapshot: &Snapshot,
2785
) -> HashMap<String, (NodeId, NodeKind)> {
2786
    let by_node = base_snapshot.tree.by_node();
2787
    let mut new_names: HashMap<NodeId, (NodeId, String, NodeKind)> = HashMap::new();
2788
    for op in &change.tree_ops {
2789
        if let TreeOp::AddNode {
2790
            node,
2791
            parent,
2792
            name,
2793
            kind,
2794
            ..
2795
        } = op
2796
        {
2797
            new_names.insert(*node, (*parent, name.clone(), *kind));
2798
        }
2799
    }
2800
    let mut out = HashMap::new();
2801
    for (node, (_, _, kind)) in &new_names {
2802
        if let Some(path) = path_of_node(node, &by_node, &new_names) {
2803
            out.insert(path, (*node, *kind));
2804
        }
2805
    }
2806
    out
2807
}
2808
2809
fn path_of_node(
2810
    n: &NodeId,
2811
    by_node: &HashMap<NodeId, &crate::tree::TreeEntry>,
2812
    new_names: &HashMap<NodeId, (NodeId, String, NodeKind)>,
2813
) -> Option<String> {
2814
    if let Some(e) = by_node.get(n) {
2815
        return Some(e.path.clone());
2816
    }
2817
    let mut parts = Vec::new();
2818
    let mut cur = *n;
2819
    loop {
2820
        if cur.is_root() {
2821
            break;
2822
        }
2823
        if let Some(e) = by_node.get(&cur) {
2824
            if !e.path.is_empty() {
2825
                parts.push(e.path.clone());
2826
            }
2827
            break;
2828
        }
2829
        let (parent, name, _) = new_names.get(&cur)?;
2830
        parts.push(name.clone());
2831
        cur = *parent;
2832
    }
2833
    parts.reverse();
2834
    Some(parts.join("/"))
2835
}
2836
2837
/// Render a change's operations with line content, using `base` for deleted lines.
2838
pub fn render_change(change: &Change, base: &State, base_snapshot: &Snapshot) -> String {
2839
    let by_node = base_snapshot.tree.by_node();
2840
    let mut new_names: HashMap<NodeId, (NodeId, String, NodeKind)> = HashMap::new();
2841
    for op in &change.tree_ops {
2842
        if let TreeOp::AddNode {
2843
            node,
2844
            parent,
2845
            name,
2846
            kind,
2847
            ..
2848
        } = op
2849
        {
2850
            new_names.insert(*node, (*parent, name.clone(), *kind));
2851
        }
2852
    }
2853
    let path_of = |n: &NodeId| -> String {
2854
        path_of_node(n, &by_node, &new_names).unwrap_or_else(|| format!("<node {}>", n.short(8)))
2855
    };
2856
2857
    let mut out = String::new();
2858
    for op in &change.tree_ops {
2859
        match op {
2860
            TreeOp::AddNode {
2861
                node, kind, mode, ..
2862
            } => {
2863
                out.push_str(&format!(
2864
                    "A {} ({:?}{}{})\n",
2865
                    path_of(node),
2866
                    kind,
2867
                    if mode.exec { ", exec" } else { "" },
2868
                    if mode.opaque { ", opaque" } else { "" }
2869
                ));
2870
            }
2871
            TreeOp::RemoveNode { node, .. } => out.push_str(&format!("D {}\n", path_of(node))),
2872
            TreeOp::Move { node, name, .. } => {
2873
                out.push_str(&format!("R {} -> {}\n", path_of(node), name))
2874
            }
2875
            TreeOp::SetMode { node, mode, .. } => {
2876
                out.push_str(&format!(
2877
                    "M {} mode: exec={} opaque={}\n",
2878
                    path_of(node),
2879
                    mode.exec,
2880
                    mode.opaque
2881
                ));
2882
            }
2883
        }
2884
    }
2885
    let mut last_node: Option<NodeId> = None;
2886
    for e in &change.edits {
2887
        let n = e.node();
2888
        if last_node != Some(n) {
2889
            out.push_str(&format!("--- {}\n", path_of(&n)));
2890
            last_node = Some(n);
2891
        }
2892
        match e {
2893
            Edit::Insert { lines, .. } => {
2894
                for l in lines.iter() {
2895
                    out.push('+');
2896
                    out.push_str(&String::from_utf8_lossy(l));
2897
                    if !l.ends_with(b"\n") {
2898
                        out.push('\n');
2899
                    }
2900
                }
2901
            }
2902
            Edit::Delete { atoms, .. } => {
2903
                for r in atoms {
2904
                    for i in r.from..r.to {
2905
                        let content = base
2906
                            .file(&n)
2907
                            .and_then(|g| g.content(&(r.change, i)))
2908
                            .unwrap_or(b"<unknown>\n");
2909
                        out.push('-');
2910
                        out.push_str(&String::from_utf8_lossy(content));
2911
                        if !content.ends_with(b"\n") {
2912
                            out.push('\n');
2913
                        }
2914
                    }
2915
                }
2916
            }
2917
            Edit::Replace { old, new, .. } => {
2918
                out.push_str(&format!(
2919
                    "  opaque content {} -> {}\n",
2920
                    old.map(|o| o.short(12)).unwrap_or_else(|| "none".into()),
2921
                    new.map(|o| o.short(12)).unwrap_or_else(|| "none".into())
2922
                ));
2923
            }
2924
        }
2925
    }
2926
    out
2927
}
2928
2929
/// Pair removed files with added files of the same kind whose contents are
2930
/// at least `RENAME_THRESHOLD` percent alike, best matches first. Beyond
2931
/// `RENAME_LIMIT` candidate pairs only identical contents are paired.
2932
const RENAME_THRESHOLD: u32 = 50;
2933
const RENAME_LIMIT: usize = 10_000;
2934
2935
/// How a change is built beyond its entries: for a Git import, the seed
2936
/// its new nodes' identifiers derive from; and, when it is built from part
2937
/// of the tree, whether the new tree has anything under a directory.
2938
#[derive(Default)]
2939
struct Scope<'a> {
2940
    seed: Option<[u8; 32]>,
2941
    dir_needed: Option<&'a dyn Fn(&str) -> bool>,
2942
}
2943
2944
fn detect_renames(
2945
    base_snapshot: &Snapshot,
2946
    fs_entries: &BTreeMap<String, FsEntry>,
2947
    in_scope: impl Fn(&str) -> bool,
2948
) -> Vec<(String, String)> {
2949
    let removed: Vec<(&String, &crate::state::FileState)> = base_snapshot
2950
        .files
2951
        .iter()
2952
        .filter(|(p, f)| {
2953
            f.kind != NodeKind::Dir
2954
                && !fs_entries.contains_key(*p)
2955
                && in_scope(p)
2956
                && !f.is_conflicted()
2957
        })
2958
        .collect();
2959
    let added: Vec<(&String, &FsEntry)> = fs_entries
2960
        .iter()
2961
        .filter(|(p, e)| e.kind != NodeKind::Dir && !base_snapshot.files.contains_key(*p))
2962
        .collect();
2963
    if removed.is_empty() || added.is_empty() {
2964
        return vec![];
2965
    }
2966
    let exact_only = removed.len() * added.len() > RENAME_LIMIT;
2967
    let old_content = |f: &crate::state::FileState| -> Option<Vec<u8>> {
2968
        match &f.content {
2969
            FileContent::Text { bytes, .. } => Some(bytes.clone()),
2970
            _ => None,
2971
        }
2972
    };
2973
    let mut scored: Vec<(u32, usize, usize)> = Vec::new();
2974
    for (ri, (_, f)) in removed.iter().enumerate() {
2975
        let old = old_content(f);
2976
        let old_blob = match &f.content {
2977
            FileContent::Opaque { blobs } if blobs.len() == 1 => Some(blobs[0]),
2978
            _ => None,
2979
        };
2980
        for (ai, (_, e)) in added.iter().enumerate() {
2981
            if e.kind != f.kind {
2982
                continue;
2983
            }
2984
            let score = match (&old, old_blob) {
2985
                (Some(o), _) => {
2986
                    if exact_only {
2987
                        if *o == *e.content {
2988
                            100
2989
                        } else {
2990
                            0
2991
                        }
2992
                    } else {
2993
                        similarity(o, &e.content)
2994
                    }
2995
                }
2996
                (None, Some(b)) if e.blob.unwrap_or_else(|| Repo::blob_ref(&e.content)) == b => 100,
2997
                _ => 0,
2998
            };
2999
            if score >= RENAME_THRESHOLD {
3000
                scored.push((score, ri, ai));
3001
            }
3002
        }
3003
    }
3004
    scored.sort_by(|a, b| {
3005
        b.0.cmp(&a.0)
3006
            .then(removed[a.1].0.cmp(removed[b.1].0))
3007
            .then(added[a.2].0.cmp(added[b.2].0))
3008
    });
3009
    let mut used_r = vec![false; removed.len()];
3010
    let mut used_a = vec![false; added.len()];
3011
    let mut out = Vec::new();
3012
    for (_, ri, ai) in scored {
3013
        if used_r[ri] || used_a[ai] {
3014
            continue;
3015
        }
3016
        used_r[ri] = true;
3017
        used_a[ai] = true;
3018
        out.push((removed[ri].0.clone(), added[ai].0.clone()));
3019
    }
3020
    out
3021
}
3022
3023
/// Percentage of the larger file's bytes found in lines the two share
3024
/// (multiset intersection of lines), like Git's similarity index.
3025
pub fn similarity(a: &[u8], b: &[u8]) -> u32 {
3026
    if a == b {
3027
        return 100;
3028
    }
3029
    if a.is_empty() || b.is_empty() {
3030
        return 0;
3031
    }
3032
    let mut counts: HashMap<&[u8], usize> = HashMap::new();
3033
    for l in split_lines(a) {
3034
        *counts.entry(l).or_default() += 1;
3035
    }
3036
    let mut shared = 0usize;
3037
    for l in split_lines(b) {
3038
        if let Some(n) = counts.get_mut(l) {
3039
            if *n > 0 {
3040
                *n -= 1;
3041
                shared += l.len();
3042
            }
3043
        }
3044
    }
3045
    (shared * 100 / a.len().max(b.len())) as u32
3046
}
3047
3048
/// Two maps side by side in key order: each key of either, with its value
3049
/// in each. Linear, with no lookups, for maps of a whole tree.
3050
fn join<'a, A, B>(
3051
    a: &'a BTreeMap<String, A>,
3052
    b: &'a BTreeMap<String, B>,
3053
) -> impl Iterator<Item = (&'a String, Option<&'a A>, Option<&'a B>)> {
3054
    let (mut a, mut b) = (a.iter().peekable(), b.iter().peekable());
3055
    std::iter::from_fn(move || match (a.peek(), b.peek()) {
3056
        (None, None) => None,
3057
        (Some(_), None) => a.next().map(|(k, v)| (k, Some(v), None)),
3058
        (None, Some(_)) => b.next().map(|(k, v)| (k, None, Some(v))),
3059
        (Some((ka, _)), Some((kb, _))) => match ka.cmp(kb) {
3060
            std::cmp::Ordering::Less => a.next().map(|(k, v)| (k, Some(v), None)),
3061
            std::cmp::Ordering::Greater => b.next().map(|(k, v)| (k, None, Some(v))),
3062
            std::cmp::Ordering::Equal => {
3063
                let (k, va) = a.next()?;
3064
                let (_, vb) = b.next()?;
3065
                Some((k, Some(va), Some(vb)))
3066
            }
3067
        },
3068
    })
3069
}
3070
3071
#[cfg(test)]
3072
mod join_tests {
3073
    use super::*;
3074
3075
    #[test]
3076
    fn join_pairs_every_key_in_order() {
3077
        let a: BTreeMap<String, u8> = [("a", 1), ("b/c", 2), ("d", 3)]
3078
            .into_iter()
3079
            .map(|(k, v)| (k.to_string(), v))
3080
            .collect();
3081
        let b: BTreeMap<String, char> = [("b", 'x'), ("b/c", 'y'), ("e", 'z')]
3082
            .into_iter()
3083
            .map(|(k, v)| (k.to_string(), v))
3084
            .collect();
3085
        let got: Vec<(String, Option<u8>, Option<char>)> = join(&a, &b)
3086
            .map(|(k, x, y)| (k.clone(), x.copied(), y.copied()))
3087
            .collect();
3088
        let want = vec![
3089
            ("a".to_string(), Some(1), None),
3090
            ("b".to_string(), None, Some('x')),
3091
            ("b/c".to_string(), Some(2), Some('y')),
3092
            ("d".to_string(), Some(3), None),
3093
            ("e".to_string(), None, Some('z')),
3094
        ];
3095
        assert_eq!(got, want);
3096
    }
3097
}