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