OXYGENHUB

Coverage / crates/oxy-core/src/repo/snapshot.rs 90.8%

2302 of 2534 lines run, 303 of 399 functions · run #341 on main · run missed

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).
2128×
pub fn has_conflict_markers(content: &[u8]) -> bool {
2278×
    split_lines(content).iter().any(|l| {
2378×
        l.starts_with(b"<<<<<<< oxy conflict")
2473×
            || l.starts_with(b"======= oxy conflict")
2573×
            || l.starts_with(b">>>>>>> oxy conflict")
2678×
    })
2728×
}
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
8123233×
pub fn is_binary(content: &[u8]) -> bool {
8223233×
    content[..content.len().min(BINARY_SNIFF)].contains(&0)
8323233×
}
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.
892×
    pub(crate) fn build_against(
902×
        &self,
912×
        base: &State,
922×
        base_snapshot: &Snapshot,
932×
        reuse: HashMap<String, (NodeId, NodeKind)>,
942×
    ) -> Result<BuiltChange> {
952×
        let mut fs_entries =
962×
            self.walk_working_copy_with(None, &Self::tracked_kinds(base_snapshot), None)?;
972×
        self.platform_normalize(&mut fs_entries, base_snapshot);
982×
        self.build_from_entries(base, base_snapshot, reuse, &fs_entries)
992×
    }
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.
1051381×
    fn platform_normalize(&self, entries: &mut BTreeMap<String, FsEntry>, base: &Snapshot) {
1061381×
        let p = self.platform;
1071381×
        if p.exec_bits && p.symlinks {
1081379×
            return;
1092×
        }
1104×
        for (path, e) in entries.iter_mut() {
1114×
            let Some(f) = base.files.get(path) else {
1120×
                continue;
113
            };
1144×
            if !p.symlinks && f.kind == NodeKind::Symlink && e.kind == NodeKind::File {
1152×
                e.kind = NodeKind::Symlink;
1162×
                e.exec = false;
1172×
            }
1184×
            if !p.exec_bits && f.kind == NodeKind::File && e.kind == NodeKind::File {
1192×
                e.exec = f.mode.exec;
1202×
            }
121
        }
1221381×
    }
123
124
    /// Like `build_against`, for files given in memory (imports).
1251108×
    pub(crate) fn build_from_entries(
1261108×
        &self,
1271108×
        base: &State,
1281108×
        base_snapshot: &Snapshot,
1291108×
        reuse: HashMap<String, (NodeId, NodeKind)>,
1301108×
        fs_entries: &BTreeMap<String, FsEntry>,
1311108×
    ) -> Result<BuiltChange> {
1321108×
        self.build_from_entries_resolving(base, base_snapshot, reuse, fs_entries, &HashSet::new())
1331108×
    }
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.
1401123×
    pub(crate) fn build_from_entries_resolving(
1411123×
        &self,
1421123×
        base: &State,
1431123×
        base_snapshot: &Snapshot,
1441123×
        reuse: HashMap<String, (NodeId, NodeKind)>,
1451123×
        fs_entries: &BTreeMap<String, FsEntry>,
1461123×
        resolve: &HashSet<String>,
1471123×
    ) -> Result<BuiltChange> {
1481123×
        self.build_from_entries_with(
1491123×
            base,
1501123×
            base_snapshot,
1511123×
            reuse,
1521123×
            fs_entries,
1531123×
            resolve,
1541123×
            Scope::default(),
155
        )
1561123×
    }
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.
16688×
    pub(crate) fn build_from_entries_seeded(
16788×
        &self,
16888×
        base: &State,
16988×
        base_snapshot: &Snapshot,
17088×
        fs_entries: &BTreeMap<String, FsEntry>,
17188×
        seed: [u8; 32],
17288×
        dir_needed: Option<&dyn Fn(&str) -> bool>,
17388×
    ) -> Result<BuiltChange> {
17488×
        self.build_from_entries_with(
17588×
            base,
17688×
            base_snapshot,
17788×
            HashMap::new(),
17888×
            fs_entries,
17988×
            &HashSet::new(),
18088×
            Scope {
18188×
                seed: Some(seed),
18288×
                dir_needed,
18388×
            },
184
        )
18588×
    }
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.
192916×
    fn build_changed_only(
193916×
        &self,
194916×
        base: &State,
195916×
        base_snapshot: &Snapshot,
196916×
        reuse: HashMap<String, (NodeId, NodeKind)>,
197916×
        fs_entries: &BTreeMap<String, FsEntry>,
198916×
    ) -> Result<BuiltChange> {
199916×
        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.
202916×
        let changed: BTreeMap<String, FsEntry> = join(fs_entries, &base_snapshot.files)
20311116×
            .filter_map(|(p, e, f)| {
20411116×
                let e = e?;
20510983×
                (!e.unchanged || f.is_none_or(|f| f.kind != e.kind || f.mode.exec != e.exec))
20610983×
                    .then(|| (p.clone(), e.clone()))
20711116×
            })
208916×
            .collect();
209916×
        let mut files: BTreeMap<String, crate::state::FileState> = BTreeMap::new();
2106754×
        for p in changed.keys() {
2116754×
            if let Some(f) = base_snapshot.files.get(p) {
2123717×
                files.insert(p.clone(), f.clone());
2133717×
            }
214
        }
215
        // Paths the base has and the disk does not.
216916×
        let gone = join(&base_snapshot.files, fs_entries)
21711116×
            .filter_map(|(p, f, e)| (e.is_none()).then_some((p, f?)));
218916×
        for (p, f) in gone {
219133×
            if f.kind == NodeKind::Dir {
22096×
                continue;
22137×
            }
22237×
            files.insert(p.clone(), f.clone());
22337×
            let mut end = p.len();
22442×
            while let Some(i) = p[..end].rfind('/') {
2255×
                let dir = &p[..i];
2265×
                if files.contains_key(dir) {
2270×
                    break;
2285×
                }
2295×
                if let Some(d) = base_snapshot.files.get(dir) {
2305×
                    files.insert(dir.to_string(), d.clone());
2315×
                }
2325×
                end = i;
233
            }
234
        }
235916×
        let part = Snapshot {
236916×
            tree: base_snapshot.tree.clone(),
237916×
            files,
238916×
            unrendered: BTreeSet::new(),
239916×
        };
240916×
        drop(pick);
241916×
        let _build = crate::timing::phase("snapshot:   of which building the change");
242
        // Whether anything on disk is under `dir`.
243916×
        let dir_needed = |dir: &str| {
2445×
            let prefix = format!("{dir}/");
2455×
            fs_entries
2465×
                .range(prefix.clone()..)
2475×
                .next()
2485×
                .is_some_and(|(k, _)| k.starts_with(&prefix))
2495×
        };
250916×
        self.build_from_entries_with(
251916×
            base,
252916×
            &part,
253916×
            reuse,
254916×
            &changed,
255916×
            &HashSet::new(),
256916×
            Scope {
257916×
                seed: None,
258916×
                dir_needed: Some(&dir_needed),
259916×
            },
260
        )
261916×
    }
262
2632127×
    fn build_from_entries_with(
2642127×
        &self,
2652127×
        base: &State,
2662127×
        base_snapshot: &Snapshot,
2672127×
        reuse: HashMap<String, (NodeId, NodeKind)>,
2682127×
        fs_entries: &BTreeMap<String, FsEntry>,
2692127×
        resolve: &HashSet<String>,
2702127×
        scope: Scope,
2712127×
    ) -> Result<BuiltChange> {
2722127×
        let Scope { seed, dir_needed } = scope;
2732127×
        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.
2762127×
        let attrs = crate::attributes::Attributes::from_files(
2772127×
            fs_entries
2782127×
                .iter()
27918984×
                .filter(|(p, _)| p.as_str() == ".oxyattributes" || p.ends_with("/.oxyattributes"))
2802127×
                .map(|(p, e)| (p.as_str(), e.content.as_slice())),
281
        );
2822127×
        let mut b = ChangeBuilder::new(base, base_snapshot, reuse).with_attributes(attrs);
2832127×
        b.resolve = resolve.clone();
2842127×
        b.node_seed = seed;
2852127×
        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.
2892127×
        let renames = detect_renames(base_snapshot, fs_entries, |p| self.in_scope(p));
2902127×
        let renamed_from: HashMap<&str, &str> = renames
2912127×
            .iter()
2922127×
            .map(|(old, new)| (new.as_str(), old.as_str()))
2932127×
            .collect();
2942127×
        let renamed_to: HashMap<&str, &str> = renames
2952127×
            .iter()
2962127×
            .map(|(old, new)| (old.as_str(), new.as_str()))
2972127×
            .collect();
2982127×
        laps.lap("build: renames");
2992127×
        b.diff_in_parallel(fs_entries);
3002127×
        laps.lap("build: diffs");
30118984×
        for (path, fs_entry) in fs_entries {
30218984×
            match base_snapshot.files.get(path) {
3036128×
                None => match renamed_from.get(path.as_str()) {
30437×
                    Some(old) => {
30537×
                        b.move_path(self, old, path, fs_entry, &base_snapshot.files[*old])?
306
                    }
3076091×
                    None => b.add_path(self, path, fs_entry)?,
308
                },
30912856×
                Some(expected) => b.update_path(self, path, fs_entry, expected)?,
310
            }
311
        }
3122127×
        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.
3152127×
        let mut needed_dirs: HashSet<&str> = HashSet::new();
31618997×
        fn parents_of<'a>(p: &'a str, set: &mut HashSet<&'a str>) {
31718997×
            let mut end = p.len();
31819657×
            while let Some(i) = p[..end].rfind('/') {
31915442×
                if !set.insert(&p[..i]) {
32014782×
                    break;
321660×
                }
322660×
                end = i;
323
            }
32418997×
        }
32518984×
        for p in fs_entries.keys() {
32618984×
            parents_of(p, &mut needed_dirs);
32718984×
        }
32813435×
        for p in base_snapshot.files.keys() {
32913435×
            if !self.in_scope(p) {
33013×
                parents_of(p, &mut needed_dirs);
33113422×
            }
332
        }
33313435×
        for (path, expected) in &base_snapshot.files {
33413435×
            if fs_entries.contains_key(path)
335579×
                || !self.in_scope(path)
336566×
                || renamed_to.contains_key(path.as_str())
337
            {
33812906×
                continue;
339529×
            }
340529×
            let still_needed = expected.kind == NodeKind::Dir
341420×
                && match dir_needed {
34221×
                    Some(f) => f(path),
343399×
                    None => needed_dirs.contains(path.as_str()),
344
                };
345529×
            if !still_needed {
346135×
                b.remove_path(path, expected);
347394×
            }
348
        }
3492127×
        laps.lap("build: removals");
3502127×
        if seed.is_some() {
35188×
            b.retire_stray_placements();
3522039×
        }
3532127×
        b.retire_unified();
3542127×
        laps.lap("build: stray placements");
3552127×
        let mut statuses = b.statuses;
3565686×
        statuses.sort_by(|a, b| a.path.cmp(&b.path));
3572127×
        Ok(BuiltChange {
3582127×
            tree_ops: b.tree_ops,
3592127×
            edits: b.edits,
3602127×
            contributors: b.contributors.into_iter().collect(),
3612127×
            resolves: b.resolves,
3622127×
            statuses,
3632127×
            blobs: b.blobs,
3642127×
        })
3652127×
    }
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.
370738×
    pub(crate) fn store_signed(&self, change: &Change) -> Result<ChangeHash> {
371738×
        let ours = change.author == self.author();
372738×
        if self.config.sign_changes && ours && self.secret_key()?.is_none() {
3731×
            return fail("core.sign is \"change\" but no secret key is available for author.key");
374737×
        }
375737×
        let storing = crate::timing::phase("store: the change");
376737×
        let hash = self.store.put_change(change)?;
377737×
        drop(storing);
378737×
        if self.config.sign_changes && ours {
37941×
            let _t = crate::timing::phase("store: sign it");
38041×
            self.sign_change(&hash)?;
381696×
        }
382737×
        Ok(hash)
383738×
    }
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.
387463×
    pub fn snapshot(&self, command: &str) -> Result<SnapshotResult> {
388463×
        self.snapshot_as(command, false, false)
389463×
    }
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.
399432×
    pub fn snapshot_status(&self, command: &str) -> Result<SnapshotResult> {
400432×
        self.snapshot_as(command, true, false)
401432×
    }
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.
4101382×
    fn snapshot_as(
4111382×
        &self,
4121382×
        command: &str,
4131382×
        partial: bool,
4141382×
        for_commit: bool,
4151382×
    ) -> Result<SnapshotResult> {
4161382×
        let _lock = self.lock_snapshot()?;
4171382×
        let batch = self.store.begin_batch()?;
4181382×
        let result = self.snapshot_locked(command, partial, for_commit);
4191382×
        batch.finish()?;
4201382×
        result
4211382×
    }
422
4231382×
    fn snapshot_locked(
4241382×
        &self,
4251382×
        command: &str,
4261382×
        partial: bool,
4271382×
        for_commit: bool,
4281382×
    ) -> Result<SnapshotResult> {
4291382×
        let _all = crate::timing::phase("snapshot");
4301382×
        let (op_ref, op) = self.head_op()?;
4311382×
        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.
4341380×
        let mut base = {
4351380×
            let _t = crate::timing::phase("snapshot: load base history");
4361380×
            self.load_state_indexed(&old_wc.deps)?
437
        };
4381380×
        let view = {
4391380×
            let _t = crate::timing::phase("snapshot: tree view");
4401380×
            self.tree_view(&mut base)?
441
        };
4421380×
        let manifest = {
4431380×
            let _t = crate::timing::phase("snapshot: read manifest");
4441380×
            self.read_manifest()?.map(|(_, _, m)| m)
445
        };
4461380×
        let tracked: BTreeMap<String, (NodeKind, Option<ObjectRef>)> = {
4471380×
            let _t = crate::timing::phase("snapshot: tracked paths");
448
            // In the view's path order, so the map is built without searching.
4491380×
            view.entries
4501380×
                .iter()
4519611×
                .filter(|(_, e)| e.kind != NodeKind::Dir)
4529217×
                .map(|(p, e)| {
4539217×
                    let blob = if e.kind != NodeKind::File || e.mode.opaque {
454156×
                        base.live_blobs(&e.node).first().copied()
455
                    } else {
4569061×
                        None
457
                    };
4589217×
                    (p.clone(), (e.kind, blob))
4599217×
                })
4601380×
                .collect()
461
        };
462
        // A text file's graph key, worked out when the walk asks for it.
46312254×
        let key_of = |p: &str| -> Option<[u8; 32]> {
46412254×
            let e = view.entries.get(p)?;
4659103×
            if e.kind != NodeKind::File || e.mode.opaque {
466124×
                return None;
4678979×
            }
4688979×
            base.graph_key(&e.node)
46912254×
        };
4701379×
        let mut fs_entries = {
4711380×
            let _t = crate::timing::phase("snapshot: read working copy");
4721380×
            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.
4761379×
        let keys: HashMap<String, [u8; 32]> = fs_entries
4771379×
            .iter()
47812292×
            .filter(|(_, e)| !e.unchanged && e.kind == NodeKind::File)
4798013×
            .filter_map(|(p, _)| Some((p.clone(), key_of(p)?)))
4801379×
            .collect();
4811379×
        let base_snapshot = {
4821379×
            let _t = crate::timing::phase("snapshot: load and render base");
4831379×
            if partial {
484919×
                let sets = crate::timing::phase("snapshot:   of which choosing graphs");
485
                // Every file but those on disk known unchanged.
486919×
                let need: Vec<(&str, NodeId)> = join(&view.entries, &fs_entries)
48711131×
                    .filter_map(|(p, v, f)| {
48811131×
                        let v = v?;
4898093×
                        (v.kind == NodeKind::File && !f.is_some_and(|f| f.unchanged))
4908093×
                            .then_some((p.as_str(), v.node))
49111131×
                    })
492919×
                    .collect();
493919×
                let render: std::collections::HashSet<&str> =
494919×
                    need.iter().map(|(p, _)| *p).collect();
495919×
                let need: Vec<NodeId> = need.iter().map(|(_, n)| *n).collect();
496919×
                drop(sets);
497
                {
498919×
                    let _t = crate::timing::phase("snapshot:   of which building graphs");
499919×
                    self.load_graphs_of(&mut base, &need)?;
500
                }
501919×
                let _t = crate::timing::phase("snapshot:   of which rendering");
502919×
                base.materialize_only(&render)
503
            } else {
504460×
                self.load_all_graphs(&mut base)?;
505460×
                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).
5111379×
        let reuse = added_node_paths(&old_wc, &base_snapshot);
5121379×
        self.platform_normalize(&mut fs_entries, &base_snapshot);
5131379×
        let built = {
5141379×
            let _t = crate::timing::phase("snapshot: diff against base");
5151379×
            if partial && self.config.sparse_paths.is_empty() {
516
                #[cfg(test)]
517639×
                let full =
518639×
                    self.build_from_entries(&base, &base_snapshot, reuse.clone(), &fs_entries)?;
519916×
                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.
5241278×
                    let norm = |b: &BuiltChange| {
5251278×
                        let text = format!("{:?} {:?} {:?}", b.tree_ops, b.edits, b.statuses);
5261278×
                        let mut seen: Vec<String> = Vec::new();
5271278×
                        let mut out = String::new();
5281278×
                        let mut rest = text.as_str();
52920228×
                        while let Some(i) = rest.find("NodeId(") {
53018950×
                            out.push_str(&rest[..i]);
53118950×
                            let end = i + rest[i..].find(')').unwrap() + 1;
53218950×
                            let id = rest[i..end].to_string();
5339046168×
                            let n = seen.iter().position(|x| *x == id).unwrap_or_else(|| {
5347202×
                                seen.push(id);
5357202×
                                seen.len() - 1
5367202×
                            });
53718950×
                            out.push_str(&format!("N{n}"));
53818950×
                            rest = &rest[end..];
539
                        }
5401278×
                        out.push_str(rest);
5411278×
                        out
5421278×
                    };
543639×
                    assert_eq!(
544639×
                        norm(&built),
545639×
                        norm(&full),
546
                        "a changed-only build is the full one"
547
                    );
548
                }
549916×
                built
550
            } else {
551463×
                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
        {
5573811×
            let changed: HashSet<&str> = built.statuses.iter().map(|s| s.path.as_str()).collect();
55812292×
            for (p, e) in fs_entries.iter_mut() {
55912292×
                if e.unchanged || e.kind != NodeKind::File || changed.contains(p.as_str()) {
5607987×
                    continue;
5614305×
                }
5624305×
                e.graph_key = match base_snapshot.files.get(p).map(|f| &f.content) {
563
                    Some(FileContent::Text {
5644193×
                        bytes,
5654193×
                        materialized,
5664193×
                    }) if !materialized.is_conflicted() && *bytes == *e.content => {
5674187×
                        keys.get(p).copied()
568
                    }
569118×
                    _ => None,
570
                };
571
            }
572
        }
573
5741379×
        let mut wc = Change {
5751379×
            version: crate::objects::CHANGE_VERSION,
5761379×
            change_id: old_wc.change_id,
5771379×
            deps: vec![],
5781379×
            author: self.author(),
5791379×
            hlc: old_wc.hlc,
5801379×
            message: old_wc.message.clone(),
5811379×
            tree_ops: built.tree_ops,
5821379×
            edits: built.edits,
5831379×
            kind: ChangeKind::WorkingCopy,
5841379×
        };
5851379×
        let base_heads = base.maximal(&old_wc.deps);
5861379×
        let mut deps: BTreeSet<ChangeHash> = base_heads.into_iter().collect();
5871379×
        deps.extend(referenced_changes(&wc, &base));
5881379×
        deps.extend(built.contributors.iter().copied());
5891379×
        wc.deps = deps.into_iter().collect();
5901379×
        wc.normalize();
5911379×
        let resolves = built.resolves;
5921379×
        let contributors = built.contributors;
5931379×
        let statuses = built.statuses;
594
        // Empty snapshot: hash the candidate before storing; only record an op on change.
5951379×
        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.
6021379×
        let (new_hash, changed, encoded) = if for_commit {
603487×
            (old_hash, true, Vec::new())
604
        } else {
605892×
            let encoded = wc.encode_streaming(|batch| self.store.put_texts(&batch))?;
606892×
            let new_hash = crate::hash::hash_object(crate::hash::ObjectType::Change, &encoded);
607892×
            (new_hash, new_hash != old_hash, encoded)
608
        };
6091379×
        if changed && !for_commit {
610308×
            self.store.put(crate::hash::ObjectType::Change, &encoded)?;
611308×
            let mut view = op.view.clone();
612308×
            view.workspaces.insert(self.workspace, new_hash);
613308×
            self.record_op(&[op_ref], &format!("{command}{SNAPSHOT_SUFFIX}"), view)?;
6141071×
        }
6151379×
        drop(record);
616
        // The prompt compares against this without recording anything.
6171379×
        let _t = crate::timing::phase("snapshot: write manifest");
6181379×
        let conflicted = base_snapshot.is_conflicted();
6191379×
        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.
6241379×
        let worth = match self.read_manifest()? {
625487×
            _ if for_commit => true,
626331×
            None => true,
627561×
            Some((c, u, m)) => {
628561×
                c != conflicted
629561×
                    || u != uncommitted
630319×
                    || m.entries.len() != fs_entries.len()
631401×
                    || fs_entries.iter().any(|(p, e)| {
632401×
                        !e.unchanged && (e.graph_key.is_some() || !m.entries.contains_key(p))
633401×
                    })
63449×
                    || built
63549×
                        .blobs
63649×
                        .iter()
63749×
                        .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.
64166×
                    || (uncommitted && statuses.iter().any(|st| {
64266×
                        let Some(e) = fs_entries.get(&st.path) else {
6434×
                            return m.entries.contains_key(&st.path);
644
                        };
64562×
                        let Some(me) = m.entries.get(&st.path) else {
6460×
                            return true;
647
                        };
64862×
                        let hash = e
64962×
                            .content_hash
65062×
                            .unwrap_or_else(|| *blake3::hash(&e.content).as_bytes());
65162×
                        let stat = e.stat.or_else(|| {
6520×
                            fs::symlink_metadata(self.root.join(&st.path))
6530×
                                .ok()
6540×
                                .map(|md| (md.len(), super::prompt::mtime_ns(&md)))
6550×
                        });
656
                        // The executable bit too: a mode change moves
657
                        // neither size nor time.
65862×
                        me.hash != hash || me.exec != e.exec || stat != Some((me.size, me.mtime_ns))
65966×
                    }))
660
            }
661
        };
6621379×
        let attributes = crate::attributes::Attributes::from_files(
6631379×
            fs_entries
6641379×
                .iter()
66512292×
                .filter(|(p, _)| is_attributes(p))
6661379×
                .map(|(p, e)| (p.as_str(), e.content.as_slice())),
667
        );
6681379×
        let mut manifest = None;
6691379×
        if for_commit {
670487×
            manifest = Some(PendingManifest {
671487×
                entries: fs_entries,
672487×
                blobs: built.blobs.clone(),
673487×
                dirs: self.walked_dirs.take(),
674487×
                written: super::prompt::now_ns(),
675487×
            });
676487×
        } else {
677892×
            if worth {
678846×
                self.write_manifest_entries(conflicted, uncommitted, &fs_entries, &built.blobs)?;
67946×
            }
680892×
            self.write_status_cache((uncommitted && !conflicted).then_some(&new_hash), &statuses);
681
        }
6821379×
        Ok(SnapshotResult {
6831379×
            wc_hash: new_hash,
6841379×
            wc,
6851379×
            base,
6861379×
            base_snapshot,
6871379×
            statuses,
6881379×
            changed,
6891379×
            resolves,
6901379×
            contributors,
6911379×
            attributes,
6921379×
            untracked_nested: self.untracked_nested.borrow().clone(),
6931379×
            manifest,
6941379×
        })
6951382×
    }
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.
7008×
    pub fn status_json(&self, snap: &SnapshotResult) -> Result<String> {
7018×
        let heads = self.bookmark_heads()?;
7028×
        let base_snapshot = &snap.base_snapshot;
7038×
        let by_node = base_snapshot.tree.by_node();
7048×
        let path_of = |n: &NodeId| by_node.get(n).map(|e| e.path.clone());
7058×
        let id_of = |h: &ChangeHash| {
7064×
            snap.base
7074×
                .get(h)
7084×
                .map(|m| m.change_id.to_hex())
7094×
                .unwrap_or_else(|| h.to_hex())
7104×
        };
7118×
        let paths = json_array(snap.statuses.iter().map(|s| {
7124×
            format!(
713
                "{{\"path\":{},\"status\":{}}}",
7144×
                json_str(&s.path),
7154×
                json_str(&format!("{:?}", s.status))
716
            )
7174×
        }));
7188×
        let mut conflicts: Vec<String> = Vec::new();
7199×
        for (p, f) in &base_snapshot.files {
7209×
            if !f.is_conflicted() {
7217×
                continue;
7222×
            }
7232×
            let (kind, changes) = match &f.content {
724
                FileContent::Text { .. } => {
7252×
                    ("text", snap.base.conflict_regions(&f.node).contributors)
726
                }
7270×
                FileContent::Opaque { blobs } => {
7280×
                    ("replace", snap.base.blob_contributors(&f.node, blobs))
729
                }
7300×
                FileContent::Dir => continue,
731
            };
7322×
            let resolved = match snap
7332×
                .statuses
7342×
                .iter()
7352×
                .find(|s| s.path == *p)
7362×
                .map(|s| s.status)
737
            {
7381×
                Some(ChangeStatus::Resolved) => "true",
7390×
                Some(ChangeStatus::ConflictEdited) => "\"markers\"",
7401×
                _ => "false",
741
            };
7422×
            conflicts.push(format!(
743
                "{{\"kind\":{},\"path\":{},\"node\":{},\"changes\":{},\"resolved\":{resolved}}}",
7442×
                json_str(kind),
7452×
                json_str(p),
7462×
                json_str(&f.node.to_hex()),
7474×
                json_array(changes.iter().map(|h| json_str(&id_of(h))))
748
            ));
749
        }
7508×
        for c in &base_snapshot.tree.conflicts {
7510×
            let (kind, nodes): (&str, Vec<NodeId>) = match c {
7520×
                crate::tree::TreeConflict::Name { nodes, .. } => ("name", nodes.clone()),
7530×
                crate::tree::TreeConflict::MultiPlacement { node, .. } => {
7540×
                    ("multi-placement", vec![*node])
755
                }
7560×
                crate::tree::TreeConflict::Orphan { node, .. } => ("orphan", vec![*node]),
7570×
                crate::tree::TreeConflict::Cycle { node } => ("cycle", vec![*node]),
7580×
                crate::tree::TreeConflict::Mode { node, .. } => ("mode", vec![*node]),
759
            };
7600×
            let detail = match c {
7610×
                crate::tree::TreeConflict::Name { name, parent, .. } => {
7620×
                    let dir = if *parent == NodeId::ROOT {
7630×
                        String::new()
764
                    } else {
7650×
                        path_of(parent).unwrap_or_default()
766
                    };
7670×
                    format!(
768
                        ",\"path\":{}",
7690×
                        json_str(&if dir.is_empty() {
7700×
                            name.clone()
771
                        } else {
7720×
                            format!("{dir}/{name}")
773
                        })
774
                    )
775
                }
7760×
                _ => nodes
7770×
                    .first()
7780×
                    .and_then(path_of)
7790×
                    .map(|p| format!(",\"path\":{}", json_str(&p)))
7800×
                    .unwrap_or_default(),
781
            };
7820×
            conflicts.push(format!(
783
                "{{\"kind\":{},\"nodes\":{}{detail}}}",
7840×
                json_str(kind),
7850×
                json_array(nodes.iter().map(|n| json_str(&n.to_hex())))
786
            ));
787
        }
7888×
        Ok(format!(
789
            "{{\"bookmark\":{},\"working_copy\":{},\"heads\":{},\"clean\":{},\"conflicted\":{},\"paths\":{paths},\"conflicts\":{},\"untracked_nested\":{},\"skipped_large\":{}}}",
7908×
            json_str(&self.config.bookmark),
7918×
            json_str(&snap.wc.change_id.to_hex()),
7928×
            heads.len(),
7938×
            snap.statuses.is_empty(),
7948×
            base_snapshot.is_conflicted(),
7958×
            json_array(conflicts),
7968×
            json_array(snap.untracked_nested.iter().map(|p| json_str(p))),
7978×
            json_array(
7988×
                self.skipped_large
7998×
                    .borrow()
8008×
                    .iter()
8018×
                    .map(|(p, n)| format!("{{\"path\":{},\"size\":{n}}}", json_str(p)))
802
            )
803
        ))
8048×
    }
805
806
    /// Turn the working-copy change into a normal change on the bookmark (spec §12.3).
807679×
    pub fn commit(&self, message: &str, extra_deps: &[ChangeHash]) -> Result<ChangeHash> {
808679×
        self.commit_selection(message, extra_deps, &Selection::All)
809679×
    }
810
811
    /// The hunks of the working copy, for `oxy commit --interactive`: each
812
    /// tree operation and each edit, in the order `select_hunks` numbers them.
8138×
    pub fn hunks(&self) -> Result<(SnapshotResult, Vec<Hunk>)> {
8148×
        let snap = self.snapshot_status("oxy commit")?;
8158×
        let hunks = render_hunks(&snap.wc, &snap.base, &snap.base_snapshot);
8168×
        Ok((snap, hunks))
8178×
    }
818
819
    /// Commit part of the working copy (spec §12.3). What is not selected
820
    /// stays on disk as uncommitted work: the next snapshot rebuilds it
821
    /// against the new base, so the working copy always describes the
822
    /// directory.
823
    /// The graph key in `st` of each text file at `paths`, the paths a
824
    /// commit changed: only their graphs changed, so the keys the manifest
825
    /// holds for the others still stand (and any that does not is simply
826
    /// not trusted by the next snapshot, which compares keys). Files with
827
    /// an `eol` attribute are left out: their bytes on disk are not the
828
    /// rendering.
829698×
    fn committed_graph_keys(
830698×
        &self,
831698×
        st: &State,
832698×
        paths: &[String],
833698×
        attrs: &crate::attributes::Attributes,
834698×
    ) -> HashMap<String, [u8; 32]> {
835698×
        let _t = crate::timing::phase("commit: graph keys");
836698×
        let view = st.view();
837698×
        paths
838698×
            .iter()
8393540×
            .filter_map(|p| {
8403540×
                let e = view.entries.get(p)?;
8413495×
                (e.kind == NodeKind::File && !e.mode.opaque && attrs.lookup(p).eol.is_none())
8423495×
                    .then_some(())?;
8433443×
                Some((p.clone(), st.graph_key(&e.node)?))
8443540×
            })
845698×
            .collect()
846698×
    }
847
848686×
    pub fn commit_selection(
849686×
        &self,
850686×
        message: &str,
851686×
        extra_deps: &[ChangeHash],
852686×
        selection: &Selection,
853686×
    ) -> Result<ChangeHash> {
854686×
        Ok(self
855686×
            .commit_selection_partial(message, extra_deps, selection)?
856
            .0)
857686×
    }
858
859
    /// As [`Repo::commit_selection`], and whether the commit left part of
860
    /// the working copy uncommitted: when it did not, nothing is left, and
861
    /// no snapshot is needed to say so.
862712×
    pub fn commit_selection_partial(
863712×
        &self,
864712×
        message: &str,
865712×
        extra_deps: &[ChangeHash],
866712×
        selection: &Selection,
867712×
    ) -> Result<(ChangeHash, bool)> {
868
        // The commit's objects are written together, made durable at once
869
        // before the operation that names them (spec §13.6).
870712×
        let batch = self.store.begin_batch()?;
871712×
        let out = self.commit_selection_batched(message, extra_deps, selection);
872712×
        batch.finish()?;
873712×
        out
874712×
    }
875
876
    /// Write the manifest a commit's snapshot left to the commit, with the
877
    /// graph keys `keys` sets.
878478×
    fn write_pending_manifest(
879478×
        &self,
880478×
        mut m: PendingManifest,
881478×
        conflicted: bool,
882478×
        keys: HashMap<String, [u8; 32]>,
883478×
    ) -> Result<()> {
8842868×
        for (path, k) in keys {
8852868×
            if let Some(e) = m.entries.get_mut(&path) {
8862868×
                e.graph_key = Some(k);
8872868×
            }
888
        }
889478×
        self.write_manifest_entries_as_of(
890478×
            conflicted,
891
            false,
892478×
            &m.entries,
893478×
            &m.blobs,
894478×
            m.written,
895478×
            m.dirs.unwrap_or_default(),
896
        )
897478×
    }
898
899712×
    fn commit_selection_batched(
900712×
        &self,
901712×
        message: &str,
902712×
        extra_deps: &[ChangeHash],
903712×
        selection: &Selection,
904712×
    ) -> Result<(ChangeHash, bool)> {
905712×
        let _wc = self.lock_working_copy()?;
906712×
        let mut snap = match self.snapshot_from_cache()? {
907225×
            Some(snap) => snap,
908487×
            None => self.snapshot_as("oxy commit", true, true)?,
909
        };
910712×
        let pending = snap.manifest.take();
911712×
        if snap.wc.tree_ops.is_empty() && snap.wc.edits.is_empty() {
9124×
            if let Some(m) = pending {
9134×
                let conflicted = snap.base_snapshot.is_conflicted();
9144×
                self.write_pending_manifest(m, conflicted, HashMap::new())?;
9150×
            }
9164×
            return fail("nothing to commit: the working copy matches its base");
917708×
        }
918708×
        if let Some(s) = snap
919708×
            .statuses
920708×
            .iter()
9213561×
            .find(|s| s.status == ChangeStatus::ConflictEdited)
922
        {
9230×
            return fail(format!("{} still contains conflict markers", s.path));
924708×
        }
925708×
        if message.trim().is_empty() {
9260×
            return fail("a commit message is required");
927708×
        }
928
        // What the whole working copy references, before a whole commit
929
        // takes its operations over (they are moved, not copied: for a
930
        // large tree they are most of the memory).
931708×
        let wc_refs = referenced_changes(&snap.wc, &snap.base);
9323561×
        let changed_paths: Vec<String> = snap.statuses.iter().map(|s| s.path.clone()).collect();
933708×
        let (tree_ops, edits, partial) = match selection {
934698×
            Selection::All => (
935698×
                std::mem::take(&mut snap.wc.tree_ops),
936698×
                std::mem::take(&mut snap.wc.edits),
937698×
                false,
938698×
            ),
9395×
            Selection::Paths(paths) => {
9405×
                let (o, e) = select_paths(&snap.wc, &snap.base_snapshot, paths);
9415×
                let partial = o.len() != snap.wc.tree_ops.len() || e.len() != snap.wc.edits.len();
9425×
                (o, e, partial)
943
            }
9445×
            Selection::Hunks(indices) => {
9455×
                let (o, e) = select_hunks(&snap.wc, indices, &snap.base_snapshot.tree.unified);
9465×
                let partial = o.len() != snap.wc.tree_ops.len() || e.len() != snap.wc.edits.len();
9475×
                (o, e, partial)
948
            }
949
        };
950708×
        if tree_ops.is_empty() && edits.is_empty() {
9510×
            return fail("nothing selected to commit");
952708×
        }
953708×
        if partial && snap.resolves {
9540×
            return fail("a conflict resolution must be committed whole");
955708×
        }
956
        // pre-commit hook: may veto.
957708×
        self.run_hook(
958708×
            "pre-commit",
959708×
            &format!(
960
                "{{\"event\":\"pre-commit\",\"message\":{},\"paths\":{}}}",
961708×
                json_str(message),
9623561×
                json_array(snap.statuses.iter().map(|s| format!(
963
                    "{{\"path\":{},\"status\":{}}}",
9643561×
                    json_str(&s.path),
9653561×
                    json_str(&format!("{:?}", s.status))
966
                )))
967
            ),
9681×
        )?;
969707×
        let (op_ref, op) = self.head_op()?;
970707×
        let mut deps: BTreeSet<ChangeHash> = wc_refs;
971
        // semantic-deps hook: may add explicit dependencies (spec §8.1).
972707×
        if self.config.semantic_deps {
9731×
            let touched: Vec<String> = snap.statuses.iter().map(|s| s.path.clone()).collect();
9741×
            let by_node = snap.base_snapshot.tree.by_node();
9751×
            let mut candidates: Vec<(ChangeId, ChangeHash, Vec<String>)> = Vec::new();
9761×
            let mut seen: BTreeSet<ChangeHash> = BTreeSet::new();
9772×
            for h in deps.iter().chain(snap.base.maximal(&snap.wc.deps).iter()) {
9782×
                if !seen.insert(*h) {
9790×
                    continue;
9802×
                }
9812×
                let c = self.store.get_change(h)?;
9822×
                let mut paths: BTreeSet<String> = BTreeSet::new();
9836×
                for n in c
9842×
                    .tree_ops
9852×
                    .iter()
9863×
                    .map(|o| o.node())
9873×
                    .chain(c.edits.iter().map(|e| e.node()))
988
                {
9896×
                    if let Some(e) = by_node.get(&n) {
9906×
                        paths.insert(e.path.clone());
9916×
                    }
992
                }
9932×
                candidates.push((c.change_id, *h, paths.into_iter().collect()));
994
            }
9951×
            for d in self.semantic_deps(&snap.wc.change_id, &touched, &candidates)? {
9961×
                if snap.base.contains(&d) {
9971×
                    deps.insert(d);
9981×
                }
999
            }
1000706×
        }
1001
        // A resolution depends on every change that contributed to the
1002
        // conflict (spec §8.1). Tree and opaque conflicts are resolved through
1003
        // ordinary operations whose references already cover the contributors.
1004707×
        deps.extend(snap.contributors.iter().copied());
1005707×
        for d in extra_deps {
10062×
            if !snap.base.contains(d) {
10070×
                return fail(format!(
1008
                    "--depends-on {d}: not in the working copy's base state"
1009
                ));
10102×
            }
10112×
            deps.insert(*d);
1012
        }
1013707×
        let mut change = Change {
1014
            version: crate::objects::CHANGE_VERSION,
1015707×
            change_id: if partial {
10168×
                ChangeId::random()
1017
            } else {
1018699×
                snap.wc.change_id
1019
            },
1020707×
            deps: vec![],
1021707×
            author: self.author(),
1022707×
            hlc: Hlc::now(),
1023707×
            message: message.trim_end().to_string(),
1024707×
            tree_ops,
1025707×
            edits,
1026707×
            kind: if snap.resolves {
10277×
                ChangeKind::Resolution
1028
            } else {
1029700×
                ChangeKind::Normal
1030
            },
1031
        };
1032707×
        if partial {
1033
            // Dependencies come from what the selected part references, not
1034
            // from the whole working copy.
10358×
            deps = referenced_changes(&change, &snap.base);
10368×
            for d in extra_deps {
10370×
                deps.insert(*d);
10380×
            }
1039699×
        }
1040707×
        change.deps = deps.into_iter().collect();
1041707×
        change.normalize();
1042707×
        let signing = crate::timing::phase("commit: sign and store");
1043707×
        let hash = self.store_signed(&change)?;
1044706×
        drop(signing);
1045706×
        let extending = crate::timing::phase("commit: extend the state");
1046
1047
        // New bookmark heads: maximal elements of old heads plus the new change.
1048
        // The working copy continues on its own base plus the new change, which
1049
        // is exactly what the files on disk contain; the bookmark may hold
1050
        // other heads (and conflicts) the working copy has not checked out.
1051706×
        let old_heads = self.heads_of(&op.view, &self.config.bookmark)?;
1052706×
        let old_base = snap.base.maximal(&snap.wc.deps);
1053706×
        let mut all: Vec<ChangeHash> = old_heads.clone();
1054706×
        all.extend(old_base.iter().copied());
1055706×
        all.push(hash);
1056
        // The snapshot already loaded the working copy's base; when that also
1057
        // holds every bookmark head, it is the state to extend.
1058706×
        let mut st = if old_heads.iter().all(|h| snap.base.contains(h)) {
1059669×
            snap.base
1060
        } else {
106137×
            self.load_state(&all)?
1062
        };
1063706×
        st.add_hashed(hash, change)?;
1064706×
        let mut with_new = old_heads.clone();
1065706×
        with_new.push(hash);
1066706×
        let new_heads = st.maximal(&with_new);
1067
        // Automatic checkpoint once enough changes accumulated (spec §11).
1068706×
        let since = self
1069706×
            .latest_checkpoint(&self.config.bookmark)?
1070706×
            .map(|(_, cp)| cp.count)
1071706×
            .unwrap_or(0);
1072706×
        if self.config.checkpoint_interval > 0
1073706×
            && (st.len() as u64).saturating_sub(since) >= self.config.checkpoint_interval
1074
        {
10752×
            let cp_state = self.load_state_full(&new_heads)?;
10762×
            self.write_checkpoint(&self.config.bookmark, &cp_state, &new_heads)?;
1077704×
        }
1078706×
        let mut wc_base = old_base.clone();
1079706×
        wc_base.push(hash);
1080706×
        let wc_base = st.maximal(&wc_base);
1081706×
        drop(extending);
1082
1083
        // The graph keys of the files as they now are, from the state the
1084
        // commit just extended: a file whose graph it built has none, and
1085
        // is read by the next snapshot; a key the next base does not share
1086
        // (the bookmark held other heads) is simply not trusted then.
1087706×
        let keying = crate::timing::phase("commit: graph keys of the files");
1088706×
        let committed_keys =
1089706×
            (!partial).then(|| self.committed_graph_keys(&st, &changed_paths, &snap.attributes));
1090706×
        drop(keying);
1091706×
        let recording = crate::timing::phase("commit: record");
1092706×
        let wc = self.new_working_copy(wc_base, "");
1093706×
        let wc_hash = self.store.put_change(&wc)?;
1094706×
        let mut view = op.view.clone();
1095706×
        view.bookmarks.insert(
1096706×
            self.config.bookmark.clone(),
1097706×
            self.store.put_state(&StateObject::new(new_heads))?,
1098
        );
1099706×
        view.workspaces.insert(self.workspace, wc_hash);
1100706×
        self.record_op(&[op_ref], &format!("oxy commit -m {message:?}"), view)?;
1101701×
        drop(recording);
1102701×
        let rewriting = crate::timing::phase("commit: manifest");
1103701×
        if partial {
11048×
            // The rest is rebuilt from disk by the next snapshot.
11058×
            self.drop_manifest();
11068×
        } else {
1107693×
            let conflicted = snap.base_snapshot.is_conflicted() && !snap.resolves;
1108
            // The files on disk are now exactly the new base's renderings:
1109
            // record their graph keys, so the next snapshot neither reads nor
1110
            // renders them (oxygen#35).
1111693×
            let keys = if conflicted {
11120×
                HashMap::new()
1113
            } else {
1114693×
                committed_keys.unwrap_or_default()
1115
            };
1116693×
            match pending {
1117474×
                Some(m) => self.write_pending_manifest(m, conflicted, keys)?,
1118219×
                None => self.rewrite_manifest(conflicted, false, &keys)?,
1119
            }
1120
        }
1121701×
        drop(rewriting);
1122701×
        let packing = crate::timing::phase("commit: autopack");
1123701×
        self.maybe_autopack()?;
1124701×
        drop(packing);
1125701×
        let _hook = crate::timing::phase("commit: hook");
1126701×
        let _ = self.run_hook(
1127701×
            "post-commit",
1128701×
            &format!(
1129701×
                "{{\"event\":\"post-commit\",\"change_id\":{},\"hash\":{},\"message\":{}}}",
1130701×
                json_str(&snap.wc.change_id.to_hex()),
1131701×
                json_str(&hash.to_hex()),
1132701×
                json_str(message)
1133701×
            ),
1134701×
        );
1135701×
        Ok((hash, partial))
1136712×
    }
1137
}
1138
1139
/// What part of the working copy a commit takes (spec §12.3).
1140
#[derive(Clone, Debug)]
1141
pub enum Selection {
1142
    All,
1143
    /// Every operation and edit on nodes under these paths.
1144
    Paths(Vec<String>),
1145
    /// Hunk indices as `Repo::hunks` numbers them; dependent hunks are added.
1146
    Hunks(Vec<usize>),
1147
}
1148
1149
/// One selectable piece of the working copy: a tree operation or an edit.
1150
#[derive(Clone, Debug)]
1151
pub struct Hunk {
1152
    pub index: usize,
1153
    pub path: String,
1154
    /// Rendered like `oxy diff`.
1155
    pub text: String,
1156
}
1157
1158
/// The tree operations and edits on nodes under `paths`, plus the
1159
/// additions of any new parent directories they need.
11605×
fn select_paths(
11615×
    wc: &Change,
11625×
    base_snapshot: &Snapshot,
11635×
    paths: &[String],
11645×
) -> (Vec<TreeOp>, Vec<Edit>) {
116516×
    let selected = |p: &str| {
116616×
        paths
116716×
            .iter()
116816×
            .any(|x| p == x || p.starts_with(&format!("{}/", x.trim_end_matches('/'))))
116916×
    };
11705×
    let by_node = base_snapshot.tree.by_node();
11715×
    let mut new_names: HashMap<NodeId, (NodeId, String, NodeKind)> = HashMap::new();
11725×
    for op in &wc.tree_ops {
1173
        if let TreeOp::AddNode {
11742×
            node,
11752×
            parent,
11762×
            name,
11772×
            kind,
1178
            ..
11793×
        } = op
11802×
        {
11812×
            new_names.insert(*node, (*parent, name.clone(), *kind));
11822×
        }
1183
    }
11845×
    let mut nodes: BTreeSet<NodeId> = BTreeSet::new();
118517×
    for n in wc
11865×
        .tree_ops
11875×
        .iter()
11885×
        .map(|o| o.node())
118914×
        .chain(wc.edits.iter().map(|e| e.node()))
1190
    {
119117×
        if path_of_node(&n, &by_node, &new_names).is_some_and(|p| selected(&p)) {
11929×
            nodes.insert(n);
11939×
        }
1194
    }
1195
    // The nodes shown as one with a selected node are retired with it.
11965×
    for (dup, shown) in &base_snapshot.tree.unified {
11971×
        if nodes.contains(shown) {
11981×
            nodes.insert(*dup);
11991×
        }
1200
    }
1201
    // New parents of selected new nodes come along.
12025×
    let mut changed = true;
120310×
    while changed {
12045×
        changed = false;
12055×
        for (n, (parent, _, _)) in &new_names {
12062×
            if nodes.contains(n) && new_names.contains_key(parent) && nodes.insert(*parent) {
12070×
                changed = true;
12082×
            }
1209
        }
1210
    }
12115×
    let ops = wc
12125×
        .tree_ops
12135×
        .iter()
12145×
        .filter(|o| nodes.contains(&o.node()))
12155×
        .cloned()
12165×
        .collect();
12175×
    let edits = wc
12185×
        .edits
12195×
        .iter()
122014×
        .filter(|e| nodes.contains(&e.node()))
12215×
        .cloned()
12225×
        .collect();
12235×
    (ops, edits)
12245×
}
1225
1226
/// The hunks `indices` name plus whatever they refer to within the working
1227
/// copy (the parent directory of an added node, the insert that introduced
1228
/// an anchor line), renumbered so the result is a well-formed change.
1229
/// The nodes `unified` shows as one with another (a base's
1230
/// [`TreeView::unified`](crate::tree::TreeView::unified)) are retired with
1231
/// any hunk of the node shown.
12326×
fn select_hunks(
12336×
    wc: &Change,
12346×
    indices: &[usize],
12356×
    unified: &BTreeMap<NodeId, NodeId>,
12366×
) -> (Vec<TreeOp>, Vec<Edit>) {
12376×
    let n_ops = wc.tree_ops.len();
12386×
    let mut ops_sel = vec![false; n_ops];
12396×
    let mut edits_sel = vec![false; wc.edits.len()];
12406×
    for &i in indices {
12415×
        if i < n_ops {
12421×
            ops_sel[i] = true;
12434×
        } else if i - n_ops < wc.edits.len() {
12444×
            edits_sel[i - n_ops] = true;
12454×
        }
1246
    }
1247
    // Atom ranges each insert introduces, per node, in the working copy's numbering.
12486×
    let mut per_node: HashMap<NodeId, u32> = HashMap::new();
12496×
    let mut insert_ranges: Vec<Option<(NodeId, u32, u32)>> = Vec::new();
125012×
    for e in &wc.edits {
125112×
        insert_ranges.push(match e {
125212×
            Edit::Insert { node, lines, .. } => {
125312×
                let start = per_node.entry(*node).or_default();
125412×
                let r = (*node, *start, *start + lines.len() as u32);
125512×
                *start += lines.len() as u32;
125612×
                Some(r)
1257
            }
12580×
            _ => None,
1259
        });
1260
    }
12616×
    let add_index: HashMap<NodeId, usize> = wc
12626×
        .tree_ops
12636×
        .iter()
12646×
        .enumerate()
126510×
        .filter_map(|(i, o)| {
126610×
            if let TreeOp::AddNode { node, .. } = o {
12679×
                Some((*node, i))
1268
            } else {
12691×
                None
1270
            }
127110×
        })
12726×
        .collect();
12736×
    let insert_for = |node: &NodeId, index: u32| -> Option<usize> {
12740×
        insert_ranges
12750×
            .iter()
12760×
            .position(|r| matches!(r, Some((n, a, b)) if n == node && *a <= index && index < *b))
12770×
    };
1278
    // Closure.
12796×
    let mut changed = true;
128015×
    while changed {
12819×
        changed = false;
128219×
        for i in 0..n_ops {
128319×
            if !ops_sel[i] {
128413×
                continue;
12856×
            }
12866×
            if let TreeOp::AddNode { node, parent, .. } = &wc.tree_ops[i] {
12876×
                if let Some(&p) = add_index.get(parent) {
12884×
                    if !ops_sel[p] {
12892×
                        ops_sel[p] = true;
12902×
                        changed = true;
12912×
                    }
12922×
                }
1293
                // A new node's content belongs with its addition: nobody
1294
                // wants an empty file committed apart from its lines.
129512×
                for (j, e) in wc.edits.iter().enumerate() {
129612×
                    if e.node() == *node && !edits_sel[j] {
12971×
                        edits_sel[j] = true;
12981×
                        changed = true;
129911×
                    }
1300
                }
13010×
            }
1302
        }
130318×
        for j in 0..wc.edits.len() {
130418×
            if !edits_sel[j] {
130510×
                continue;
13068×
            }
13078×
            let e = &wc.edits[j];
13088×
            if let Some(&a) = add_index.get(&e.node()) {
13095×
                if !ops_sel[a] {
13101×
                    ops_sel[a] = true;
13111×
                    changed = true;
13124×
                }
13133×
            }
1314
            if let Edit::Insert {
13158×
                node,
13168×
                after,
13178×
                before,
1318
                ..
13198×
            } = e
1320
            {
132116×
                for r in [after, before] {
132216×
                    if let AtomRef::Atom { change, index } = r {
13233×
                        if change.is_zero() {
13240×
                            if let Some(k) = insert_for(node, *index) {
13250×
                                if !edits_sel[k] {
13260×
                                    edits_sel[k] = true;
13270×
                                    changed = true;
13280×
                                }
13290×
                            }
13303×
                        }
133113×
                    }
1332
                }
13330×
            }
1334
        }
1335
    }
1336
    // The retirement of a node shown as one with a selected node.
13376×
    if !unified.is_empty() {
13381×
        let chosen: HashSet<NodeId> = (0..n_ops)
13392×
            .filter(|i| ops_sel[*i])
13401×
            .map(|i| wc.tree_ops[i].node())
13411×
            .chain(
13421×
                (0..wc.edits.len())
13432×
                    .filter(|j| edits_sel[*j])
13441×
                    .map(|j| wc.edits[j].node()),
1345
            )
13461×
            .collect();
13472×
        for (i, o) in wc.tree_ops.iter().enumerate() {
13482×
            if let TreeOp::RemoveNode { node, .. } = o {
13491×
                if unified.get(node).is_some_and(|s| chosen.contains(s)) {
13501×
                    ops_sel[i] = true;
13511×
                }
13521×
            }
1353
        }
13545×
    }
1355
    // Renumber self-references: old atom index → new index among selected inserts.
13566×
    let mut remap: HashMap<(NodeId, u32), u32> = HashMap::new();
13576×
    let mut new_counts: HashMap<NodeId, u32> = HashMap::new();
135812×
    for (j, r) in insert_ranges.iter().enumerate() {
135912×
        if let (true, Some((node, a, b))) = (edits_sel[j], r) {
13605×
            let next = new_counts.entry(*node).or_default();
13615×
            for old in *a..*b {
13625×
                remap.insert((*node, old), *next);
13635×
                *next += 1;
13645×
            }
13657×
        }
1366
    }
136710×
    let map_ref = |r: AtomRef, node: &NodeId| -> AtomRef {
13683×
        match r {
13693×
            AtomRef::Atom { change, index } if change.is_zero() => AtomRef::Atom {
13700×
                change,
13710×
                index: remap.get(&(*node, index)).copied().unwrap_or(index),
13720×
            },
137310×
            other => other,
1374
        }
137510×
    };
13766×
    let ops = wc
13776×
        .tree_ops
13786×
        .iter()
13796×
        .enumerate()
138010×
        .filter(|(i, _)| ops_sel[*i])
13816×
        .map(|(_, o)| o.clone())
13826×
        .collect();
13836×
    let edits = wc
13846×
        .edits
13856×
        .iter()
13866×
        .enumerate()
138712×
        .filter(|(j, _)| edits_sel[*j])
13886×
        .map(|(_, e)| match e {
1389
            Edit::Insert {
13905×
                node,
13915×
                after,
13925×
                before,
13935×
                lines,
13945×
            } => Edit::Insert {
13955×
                node: *node,
13965×
                after: map_ref(*after, node),
13975×
                before: map_ref(*before, node),
13985×
                lines: lines.clone(),
13995×
            },
14000×
            other => other.clone(),
14015×
        })
14026×
        .collect();
14036×
    (ops, edits)
14046×
}
1405
1406
/// Render each tree operation and edit of `change` on its own, numbered.
14078×
pub fn render_hunks(change: &Change, base: &State, base_snapshot: &Snapshot) -> Vec<Hunk> {
14088×
    let by_node = base_snapshot.tree.by_node();
14098×
    let mut new_names: HashMap<NodeId, (NodeId, String, NodeKind)> = HashMap::new();
141010×
    for op in &change.tree_ops {
1411
        if let TreeOp::AddNode {
14129×
            node,
14139×
            parent,
14149×
            name,
14159×
            kind,
1416
            ..
141710×
        } = op
14189×
        {
14199×
            new_names.insert(*node, (*parent, name.clone(), *kind));
14209×
        }
1421
    }
14228×
    let mut out = Vec::new();
142310×
    for (i, op) in change.tree_ops.iter().enumerate() {
1424
        // A retired duplicate goes with the node shown: no hunk of its own.
142510×
        if is_unified_retirement(op, base_snapshot) {
14261×
            continue;
14279×
        }
14289×
        let one = Change {
14299×
            tree_ops: vec![op.clone()],
14309×
            edits: vec![],
14319×
            ..change.clone()
14329×
        };
14339×
        let path = path_of_node(&op.node(), &by_node, &new_names).unwrap_or_default();
14349×
        out.push(Hunk {
14359×
            index: i,
14369×
            path,
14379×
            text: render_change(&one, base, base_snapshot),
14389×
        });
1439
    }
144015×
    for (j, e) in change.edits.iter().enumerate() {
144115×
        let one = Change {
144215×
            tree_ops: vec![],
144315×
            edits: vec![e.clone()],
144415×
            ..change.clone()
144515×
        };
144615×
        let path = path_of_node(&e.node(), &by_node, &new_names).unwrap_or_default();
144715×
        out.push(Hunk {
144815×
            index: change.tree_ops.len() + j,
144915×
            path,
145015×
            text: render_change(&one, base, base_snapshot),
145115×
        });
145215×
    }
14538×
    out
14548×
}
1455
1456
/// One file's part of a diff, for `oxy diff --json`.
1457
#[derive(Clone, Debug)]
1458
pub struct FileDiff {
1459
    pub path: String,
1460
    /// `added`, `removed`, `modified`, `renamed`, `mode`, `replaced`.
1461
    pub kind: String,
1462
    pub hunks: Vec<DiffHunk>,
1463
    /// For renames, the previous path.
1464
    pub from: Option<String>,
1465
}
1466
1467
/// Lines inserted after `base_line` (0 = before the first line) and lines
1468
/// removed, with their base line numbers.
1469
#[derive(Clone, Debug, Default)]
1470
pub struct DiffHunk {
1471
    pub base_line: u32,
1472
    pub added: Vec<Vec<u8>>,
1473
    pub removed: Vec<(u32, Vec<u8>)>,
1474
}
1475
1476
impl Repo {
1477
    /// The content of `path` in a state: `heads`, or the working copy's base.
147827×
    pub fn file_at(&self, path: &str, heads: Option<&[ChangeHash]>) -> Result<Vec<u8>> {
1479
        // The state's history and tree, then the one file's graph: nothing
1480
        // else is built or rendered (oxygen#92).
1481
        // The working copy's base, and a state named by its heads (`-r
1482
        // main` on main), come from the workspace's state index.
148327×
        let base = if self.is_bare() {
14845×
            None
1485
        } else {
148622×
            Some(self.working_copy()?.1.deps)
1487
        };
148827×
        let same = |a: &[ChangeHash], b: &[ChangeHash]| {
14891×
            let (mut a, mut b) = (a.to_vec(), b.to_vec());
14901×
            a.sort();
14911×
            b.sort();
14921×
            a == b
14931×
        };
149427×
        let mut state = match (heads, base) {
14951×
            (Some(h), Some(b)) if same(h, &b) => self.load_state_indexed(&b)?,
14965×
            (Some(h), _) => self.load_state_history(h)?,
149721×
            (None, Some(b)) => self.load_state_indexed(&b)?,
14980×
            (None, None) => return fail("this is a bare repository: it has no working copy"),
1499
        };
150027×
        let view = self.tree_view(&mut state)?;
150127×
        let Some(node) = view.entries.get(path).map(|e| e.node) else {
15020×
            return fail(format!("{path} is not in that state"));
1503
        };
150427×
        self.load_graphs_of(&mut state, &[node])?;
150526×
        let snapshot = state.materialize_paths(view, [path]);
150626×
        let Some(f) = snapshot.files.get(path) else {
15070×
            return fail(format!("{path} is not in that state"));
1508
        };
150926×
        match &f.content {
15100×
            FileContent::Dir => fail(format!("{path} is a directory")),
151126×
            FileContent::Text { bytes, .. } => Ok(bytes.clone()),
15120×
            FileContent::Opaque { blobs } => match blobs.first() {
15130×
                Some(b) => self.read_blob(b),
15140×
                None => Ok(vec![]),
1515
            },
1516
        }
151727×
    }
1518
1519
    /// Restore `paths` (files or directories) to the working copy's base:
1520
    /// edits are undone, additions removed, removals put back. Returns the
1521
    /// number of paths touched.
15222×
    pub fn discard(&self, paths: &[String]) -> Result<usize> {
15232×
        let _wc = self.lock_working_copy()?;
15242×
        let snap = self.snapshot_status("oxy discard")?;
15257×
        let under = |p: &str| {
15267×
            paths
15277×
                .iter()
15287×
                .any(|x| p == x || p.starts_with(&format!("{}/", x.trim_end_matches('/'))))
15297×
        };
15302×
        let attrs = Repo::state_attributes(&snap.base_snapshot);
15312×
        let mut n = 0;
15323×
        for s in &snap.statuses {
15333×
            if !under(&s.path) {
15341×
                continue;
15352×
            }
15362×
            match snap.base_snapshot.files.get(&s.path) {
1537
                None => {
1538
                    // Added (or the new name of a rename): remove it.
15391×
                    let full = self.root.join(&s.path);
15401×
                    if full.is_dir() {
15410×
                        let _ = fs::remove_dir_all(&full);
15421×
                    } else {
15431×
                        let _ = fs::remove_file(&full);
15441×
                    }
15451×
                    n += 1;
1546
                }
15471×
                Some(f) => {
15481×
                    match &f.content {
15490×
                        FileContent::Dir => fs::create_dir_all(self.root.join(&s.path))?,
15501×
                        FileContent::Text { bytes, .. } => {
15511×
                            let on_disk: std::borrow::Cow<[u8]> = if attrs.lookup(&s.path).eol
15521×
                                == Some(crate::attributes::Eol::Crlf)
1553
                            {
15540×
                                crate::attributes::to_crlf(bytes).into()
1555
                            } else {
15561×
                                bytes.as_slice().into()
1557
                            };
15581×
                            self.write_file(&s.path, &on_disk, f.mode.exec)?;
1559
                        }
15600×
                        FileContent::Opaque { blobs } => {
15610×
                            let bytes = match blobs.first() {
15620×
                                Some(b) => self.read_blob(b)?,
15630×
                                None => vec![],
1564
                            };
15650×
                            if f.kind == NodeKind::Symlink {
15660×
                                self.write_symlink(&s.path, &bytes)?;
15670×
                            } else if f.kind == NodeKind::File {
15680×
                                self.write_file(&s.path, &bytes, f.mode.exec)?;
15690×
                            }
1570
                        }
1571
                    }
15721×
                    n += 1;
1573
                }
1574
            }
1575
        }
1576
        // A rename's old name is not in the statuses; put it back too.
15774×
        for (p, f) in &snap.base_snapshot.files {
15784×
            if under(p)
15791×
                && !self.root.join(p).exists()
15800×
                && f.kind != NodeKind::Dir
15810×
                && f.kind != NodeKind::Subrepo
15820×
                && !snap.statuses.iter().any(|s| s.path == *p)
1583
            {
15840×
                let bytes = match &f.content {
15850×
                    FileContent::Text { bytes, .. } => bytes.clone(),
15860×
                    FileContent::Opaque { blobs } => blobs
15870×
                        .first()
15880×
                        .map(|b| self.read_blob(b))
15890×
                        .transpose()?
15900×
                        .unwrap_or_default(),
15910×
                    FileContent::Dir => continue,
1592
                };
15930×
                if f.kind == NodeKind::Symlink {
15940×
                    self.write_symlink(p, &bytes)?
1595
                } else {
15960×
                    self.write_file(p, &bytes, f.mode.exec)?
1597
                }
15980×
                n += 1;
15994×
            }
1600
        }
16012×
        self.drop_manifest();
16022×
        Ok(n)
16032×
    }
1604
1605
    /// Undo the working-copy hunks `indices` (as `hunks` numbers them) on
1606
    /// disk, keeping the others: the files are rewritten from the base plus
1607
    /// the remaining hunks.
16081×
    pub fn discard_hunks(&self, indices: &[usize]) -> Result<usize> {
16091×
        let _wc = self.lock_working_copy()?;
16101×
        let (snap, hunks) = self.hunks()?;
16111×
        let keep: Vec<usize> = hunks
16121×
            .iter()
16131×
            .map(|h| h.index)
16141×
            .filter(|i| !indices.contains(i))
16151×
            .collect();
16161×
        let (ops, edits) = select_hunks(&snap.wc, &keep, &snap.base_snapshot.tree.unified);
16171×
        let dropped_nodes: BTreeSet<NodeId> = hunks
16181×
            .iter()
16191×
            .filter(|h| indices.contains(&h.index))
16201×
            .map(|h| {
16211×
                if h.index < snap.wc.tree_ops.len() {
16220×
                    snap.wc.tree_ops[h.index].node()
1623
                } else {
16241×
                    snap.wc.edits[h.index - snap.wc.tree_ops.len()].node()
1625
                }
16261×
            })
16271×
            .collect();
16281×
        let mut partial = snap.wc.clone();
16291×
        partial.tree_ops = ops;
16301×
        partial.edits = edits;
16311×
        partial.normalize();
16321×
        let mut st = snap.base.clone();
16331×
        st.add_unchecked(partial);
1634
        // Every file of the target is rendered: build the graphs the
1635
        // partial snapshot left out.
16361×
        self.load_all_graphs(&mut st)?;
16371×
        let target = st.materialize();
16381×
        let by_node_target = target.tree.by_node();
16391×
        let by_node_base = snap.base_snapshot.tree.by_node();
16401×
        let attrs = Repo::state_attributes(&target);
16411×
        let mut n = 0;
16421×
        for node in dropped_nodes {
16431×
            match by_node_target.get(&node) {
16441×
                Some(e) => {
16451×
                    let f = &target.files[&e.path];
16461×
                    match &f.content {
16470×
                        FileContent::Dir => {}
16481×
                        FileContent::Text { bytes, .. } => {
16491×
                            let on_disk: std::borrow::Cow<[u8]> = if attrs.lookup(&e.path).eol
16501×
                                == Some(crate::attributes::Eol::Crlf)
1651
                            {
16520×
                                crate::attributes::to_crlf(bytes).into()
1653
                            } else {
16541×
                                bytes.as_slice().into()
1655
                            };
16561×
                            self.write_file(&e.path, &on_disk, f.mode.exec)?;
1657
                        }
16580×
                        FileContent::Opaque { blobs } => {
16590×
                            let bytes = blobs
16600×
                                .first()
16610×
                                .map(|b| self.read_blob(b))
16620×
                                .transpose()?
16630×
                                .unwrap_or_default();
16640×
                            if f.kind == NodeKind::Symlink {
16650×
                                self.write_symlink(&e.path, &bytes)?
1666
                            } else {
16670×
                                self.write_file(&e.path, &bytes, f.mode.exec)?
1668
                            }
1669
                        }
1670
                    }
1671
                    // A discarded rename: the new name goes.
16721×
                    if let Some(old_path) = snap
16731×
                        .statuses
16741×
                        .iter()
16751×
                        .find(|s| {
16761×
                            s.status == ChangeStatus::Renamed && !target.files.contains_key(&s.path)
16771×
                        })
16781×
                        .map(|s| s.path.clone())
16790×
                    {
16800×
                        let _ = fs::remove_file(self.root.join(old_path));
16811×
                    }
16821×
                    n += 1;
1683
                }
1684
                None => {
1685
                    // The node exists in neither target nor base with a live path: an addition to remove.
16860×
                    if let Some(added) = snap.statuses.iter().find(|s| {
16870×
                        s.status == ChangeStatus::Added
16880×
                            && !target.files.contains_key(&s.path)
16890×
                            && !by_node_base.contains_key(&node)
16900×
                    }) {
16910×
                        let full = self.root.join(&added.path);
16920×
                        if full.is_dir() {
16930×
                            let _ = fs::remove_dir_all(&full);
16940×
                        } else {
16950×
                            let _ = fs::remove_file(&full);
16960×
                        }
16970×
                        n += 1;
16980×
                    }
1699
                }
1700
            }
1701
        }
17021×
        self.drop_manifest();
17031×
        Ok(n)
17041×
    }
1705
1706
    /// The diff of the working copy (`None`) or of a change, per file with
1707
    /// line-numbered hunks (spec: `oxy diff --json`).
17086×
    pub fn diff_files(&self, change: Option<&ChangeHash>) -> Result<Vec<FileDiff>> {
17096×
        let (c, base, base_snapshot) = match change {
17102×
            Some(h) => {
17112×
                let c = self.store.get_change(h)?;
17122×
                let (base, snapshot) = self.change_base(&c)?;
17132×
                (c, base, snapshot)
1714
            }
17154×
            None => match self.working_copy_with_base_unless_unchanged()? {
17163×
                Some(all) => all,
17171×
                None => return Ok(Vec::new()),
1718
            },
1719
        };
17205×
        Ok(diff_files_of(&c, &base, &base_snapshot))
17216×
    }
1722
1723
    /// The snapshot a command would take, without taking it, when the
1724
    /// status cache holds: every file is as the last snapshot left it, so
1725
    /// that snapshot's working-copy change is the answer. Its base comes
1726
    /// from the state index, the `.oxyattributes` files from disk. `None`
1727
    /// when a snapshot must be taken, and when there is nothing to commit
1728
    /// (the snapshot then says so). A conflicted base never gets here: the
1729
    /// cache does not hold for one.
1730713×
    pub(crate) fn snapshot_from_cache(&self) -> Result<Option<SnapshotResult>> {
1731713×
        let Some(statuses) = self.status_by_manifest()? else {
1732484×
            return Ok(None);
1733
        };
1734229×
        if statuses.is_empty() {
17353×
            return Ok(None);
1736226×
        }
1737226×
        let _t = crate::timing::phase("snapshot: from the status cache");
1738226×
        let (wc_hash, wc) = self.working_copy()?;
1739226×
        let base = self.load_state_indexed(&wc.deps)?;
1740226×
        let (base, base_snapshot) = self.render_base_for(&wc, base)?;
1741226×
        let attribute_files: Vec<(String, Vec<u8>)> = match self.read_manifest()? {
1742226×
            Some((_, _, m)) => m
1743226×
                .entries
1744226×
                .keys()
1745693×
                .filter(|p| is_attributes(p))
1746226×
                .filter_map(|p| fs::read(self.root.join(p)).ok().map(|b| (p.clone(), b)))
1747226×
                .collect(),
17480×
            None => Vec::new(),
1749
        };
1750226×
        let attributes = crate::attributes::Attributes::from_files(
1751226×
            attribute_files
1752226×
                .iter()
1753226×
                .map(|(p, b)| (p.as_str(), b.as_slice())),
1754
        );
1755226×
        Ok(Some(SnapshotResult {
1756226×
            wc_hash,
1757226×
            wc,
1758226×
            base,
1759226×
            base_snapshot,
1760226×
            statuses,
1761226×
            changed: false,
1762226×
            resolves: false,
1763226×
            contributors: Vec::new(),
1764226×
            attributes,
1765226×
            untracked_nested: self.untracked_nested.borrow().clone(),
1766226×
            manifest: None,
1767226×
        }))
1768713×
    }
1769
1770
    /// The working-copy change with its base state and a snapshot of the
1771
    /// base, for showing what the working copy changes ([`render_change`],
1772
    /// [`diff_files_of`]). While the status cache holds (every file as the
1773
    /// last snapshot left it), the stored working-copy change is the
1774
    /// answer, no snapshot is taken, and the base's snapshot holds its tree
1775
    /// but no file; otherwise a snapshot makes all three.
17762×
    pub fn working_copy_with_base(&self) -> Result<(Change, State, Snapshot)> {
17772×
        match self.working_copy_with_base_unless_unchanged()? {
17781×
            Some(all) => Ok(all),
1779
            None => {
17801×
                let (_, wc) = self.working_copy()?;
17811×
                let base = self.load_state_indexed(&wc.deps)?;
17821×
                let (base, snapshot) = self.tree_base_for(&wc, base)?;
17831×
                Ok((wc, base, snapshot))
1784
            }
1785
        }
17862×
    }
1787
1788
    /// [`Repo::working_copy_with_base`], or `None` when the status cache
1789
    /// holds and the working-copy change changes nothing: its diff is
1790
    /// empty, and the base is not loaded for it (oxygen#94).
17917×
    pub fn working_copy_with_base_unless_unchanged(
17927×
        &self,
17937×
    ) -> Result<Option<(Change, State, Snapshot)>> {
17947×
        if self.status_by_manifest()?.is_some() {
17955×
            let (_, wc) = self.working_copy()?;
17965×
            if wc.tree_ops.is_empty() && wc.edits.is_empty() {
17973×
                return Ok(None);
17982×
            }
17992×
            let base = self.load_state_indexed(&wc.deps)?;
18002×
            let (base, snapshot) = self.tree_base_for(&wc, base)?;
18012×
            return Ok(Some((wc, base, snapshot)));
18022×
        }
18032×
        let snap = self.snapshot_status("oxy diff")?;
18042×
        Ok(Some((snap.wc, snap.base, snap.base_snapshot)))
18057×
    }
1806
1807
    /// The log restricted to changes touching `path` (its node, so renames
1808
    /// are followed), on the current bookmark.
18096×
    pub fn log_for_path(&self, path: &str) -> Result<Vec<LogEntry>> {
18106×
        let heads = self.bookmark_heads()?;
18116×
        if self.is_bare() {
18121×
            return self.log_for_path_in(path, &heads);
18135×
        }
18145×
        let entries = self.log()?;
18155×
        let (_, wc) = self.working_copy()?;
1816
        // The path's node from the trees alone: the base's (from the
1817
        // workspace's state index), else the bookmark's. Nothing is
1818
        // rendered.
18195×
        let node_in = |mut state: State| -> Result<Option<HashSet<NodeId>>> {
18205×
            Ok(nodes_at(&self.tree_view(&mut state)?, path))
18215×
        };
18225×
        let nodes = match node_in(self.load_state_indexed(&wc.deps)?)? {
18235×
            Some(n) => Some(n),
18240×
            None => node_in(self.load_state_history(&heads)?)?,
1825
        };
18265×
        let Some(nodes) = nodes else {
18270×
            return fail(format!("{path} is not tracked"));
1828
        };
18295×
        Ok(self.entries_touching_up_to(entries, nodes, None))
18306×
    }
1831
1832
    /// The log of the state with these heads restricted to changes touching
1833
    /// `path` (its node, so renames are followed).
18342×
    pub fn log_for_path_in(&self, path: &str, heads: &[ChangeHash]) -> Result<Vec<LogEntry>> {
18352×
        self.log_for_path_of(&self.load_state_history(heads)?, path, None)
18362×
    }
1837
1838
    /// The changes of a loaded state touching `path`, newest first, at most
1839
    /// `limit` of them. The path is found in the state's tree alone, so no
1840
    /// file is rendered, and the walk stops once `limit` are found.
18415×
    pub fn log_for_path_of(
18425×
        &self,
18435×
        state: &State,
18445×
        path: &str,
18455×
        limit: Option<usize>,
18465×
    ) -> Result<Vec<LogEntry>> {
18475×
        let Some(nodes) = nodes_at(&state.view(), path) else {
18481×
            return fail(format!("{path} is not in that state"));
1849
        };
18504×
        Ok(self.entries_touching_up_to(self.log_of(state), nodes, limit))
18515×
    }
1852
18539×
    fn entries_touching_up_to(
18549×
        &self,
18559×
        entries: Vec<LogEntry>,
18569×
        wanted: HashSet<NodeId>,
18579×
        limit: Option<usize>,
18589×
    ) -> Vec<LogEntry> {
18599×
        let mut touched = self.touched();
18609×
        if limit.is_none() {
18618×
            let hashes: Vec<ChangeHash> = entries.iter().map(|e| e.hash).collect();
18628×
            touched.fill(self, &hashes);
18631×
        }
18649×
        let mut out = Vec::new();
186532×
        for e in entries {
186632×
            if limit.is_some_and(|n| out.len() >= n) {
18671×
                break;
186831×
            }
186931×
            if touched.touches(self, &e.hash, &wanted) {
187020×
                out.push(e);
187120×
            }
1872
        }
18739×
        touched.save();
18749×
        out
18759×
    }
1876
}
1877
1878
/// The node at `path` in `view`, with the nodes it shows as one with it
1879
/// (identical additions, spec §9.2): the file's history is all of theirs.
188010×
fn nodes_at(view: &crate::tree::TreeView, path: &str) -> Option<HashSet<NodeId>> {
188110×
    let node = view.entries.get(path)?.node;
18829×
    let mut out = HashSet::from([node]);
18839×
    out.extend(
18849×
        view.unified
18859×
            .iter()
18869×
            .filter(|(_, shown)| **shown == node)
18879×
            .map(|(dup, _)| *dup),
1888
    );
18899×
    Some(out)
189010×
}
1891
1892
/// Per-file hunks of `change` against `base`.
18935×
pub fn diff_files_of(change: &Change, base: &State, base_snapshot: &Snapshot) -> Vec<FileDiff> {
18945×
    let by_node = base_snapshot.tree.by_node();
18955×
    let mut new_names: HashMap<NodeId, (NodeId, String, NodeKind)> = HashMap::new();
18965×
    for op in &change.tree_ops {
1897
        if let TreeOp::AddNode {
18982×
            node,
18992×
            parent,
19002×
            name,
19012×
            kind,
1902
            ..
19033×
        } = op
19042×
        {
19052×
            new_names.insert(*node, (*parent, name.clone(), *kind));
19062×
        }
1907
    }
19089×
    let path_of = |n: &NodeId| -> String {
19099×
        path_of_node(n, &by_node, &new_names).unwrap_or_else(|| format!("<node {}>", n.short(8)))
19109×
    };
19115×
    let mut files: BTreeMap<NodeId, FileDiff> = BTreeMap::new();
19125×
    let mut order: Vec<NodeId> = Vec::new();
191314×
    let mut entry = |files: &mut BTreeMap<NodeId, FileDiff>, n: NodeId, kind: &str| {
191414×
        if let std::collections::btree_map::Entry::Vacant(v) = files.entry(n) {
19159×
            order.push(n);
19169×
            v.insert(FileDiff {
19179×
                path: path_of(&n),
19189×
                kind: kind.to_string(),
19199×
                hunks: vec![],
19209×
                from: None,
19219×
            });
19229×
        }
192314×
    };
19245×
    for op in change
19255×
        .tree_ops
19265×
        .iter()
19275×
        .filter(|o| !is_unified_retirement(o, base_snapshot))
1928
    {
19293×
        match op {
19302×
            TreeOp::AddNode { node, kind, .. } => {
19312×
                if *kind != NodeKind::Dir {
19322×
                    entry(&mut files, *node, "added");
19332×
                }
1934
            }
19351×
            TreeOp::RemoveNode { node, .. } => {
19361×
                entry(&mut files, *node, "removed");
19371×
                if let Some(e) = by_node.get(node) {
19381×
                    files.get_mut(node).unwrap().path = e.path.clone();
19391×
                }
1940
            }
1941
            TreeOp::Move {
19420×
                node, parent, name, ..
1943
            } => {
19440×
                entry(&mut files, *node, "renamed");
19450×
                let f = files.get_mut(node).unwrap();
19460×
                f.from = by_node.get(node).map(|e| e.path.clone());
19470×
                let dir = if parent.is_root() {
19480×
                    String::new()
1949
                } else {
19500×
                    path_of_node(parent, &by_node, &new_names).unwrap_or_default()
1951
                };
19520×
                f.path = if dir.is_empty() {
19530×
                    name.clone()
1954
                } else {
19550×
                    format!("{dir}/{name}")
1956
                };
1957
            }
19580×
            TreeOp::SetMode { node, .. } => entry(&mut files, *node, "mode"),
1959
        }
1960
    }
1961
    // Base line numbers per node, 1-based.
19625×
    let mut line_of: HashMap<NodeId, HashMap<(ChangeHash, u32), u32>> = HashMap::new();
196311×
    let mut lines_for = |n: &NodeId| -> HashMap<(ChangeHash, u32), u32> {
196411×
        line_of
196511×
            .entry(*n)
196611×
            .or_insert_with(|| {
19678×
                base.live_lines(n)
19688×
                    .into_iter()
19698×
                    .enumerate()
197011×
                    .map(|(i, (k, _))| (k, i as u32 + 1))
19718×
                    .collect()
19728×
            })
197311×
            .clone()
197411×
    };
197511×
    for e in &change.edits {
197611×
        let n = e.node();
197711×
        let is_new = new_names.contains_key(&n);
197811×
        entry(&mut files, n, if is_new { "added" } else { "modified" });
197911×
        let f = files.get_mut(&n).unwrap();
198011×
        match e {
19819×
            Edit::Insert { after, lines, .. } => {
19829×
                let map = lines_for(&n);
19839×
                let base_line = match after {
19843×
                    AtomRef::Start => 0,
19850×
                    AtomRef::End => map.len() as u32,
19866×
                    AtomRef::Atom { change, index } if change.is_zero() => {
19870×
                        f.hunks.last().map(|h| h.base_line).unwrap_or(0)
1988
                    }
19896×
                    AtomRef::Atom { change, index } => {
19906×
                        map.get(&(*change, *index)).copied().unwrap_or(0)
1991
                    }
1992
                };
19939×
                f.hunks.push(DiffHunk {
19949×
                    base_line,
19959×
                    added: lines.to_vec(),
19969×
                    removed: vec![],
19979×
                });
1998
            }
19992×
            Edit::Delete { atoms, .. } => {
20002×
                let map = lines_for(&n);
20012×
                let mut removed = Vec::new();
20022×
                for r in atoms {
20032×
                    for i in r.from..r.to {
20042×
                        let line = map.get(&(r.change, i)).copied().unwrap_or(0);
20052×
                        let text = base
20062×
                            .file(&n)
20072×
                            .and_then(|g| g.content(&(r.change, i)))
20082×
                            .unwrap_or(b"")
20092×
                            .to_vec();
20102×
                        removed.push((line, text));
2011
                    }
2012
                }
20132×
                let base_line = removed
20142×
                    .first()
20152×
                    .map(|(l, _)| l.saturating_sub(1))
20162×
                    .unwrap_or(0);
20172×
                f.hunks.push(DiffHunk {
20182×
                    base_line,
20192×
                    added: vec![],
20202×
                    removed,
20212×
                });
2022
            }
2023
            Edit::Replace { .. } => {
20240×
                if !is_new {
20250×
                    f.kind = "replaced".into();
20260×
                }
2027
            }
2028
        }
2029
    }
20309×
    order.into_iter().filter_map(|n| files.remove(&n)).collect()
20315×
}
2032
2033
/// Builds the tree ops and edits of a working-copy change against a base.
2034
/// `BLAKE3("oxy node 1" 0 seed kind path)`, truncated: a node identifier
2035
/// that the same seed and path always give (never the root's).
203659×
fn seeded_node(seed: &[u8; 32], path: &str, kind: NodeKind) -> NodeId {
203759×
    let mut h = blake3::Hasher::new();
203859×
    h.update(b"oxy node 1\0");
203959×
    h.update(seed);
204059×
    h.update(&[match kind {
204145×
        NodeKind::File => 1,
204213×
        NodeKind::Dir => 2,
20430×
        NodeKind::Symlink => 3,
20441×
        NodeKind::Subrepo => 4,
2045
    }]);
204659×
    h.update(path.as_bytes());
204759×
    let mut id = [0u8; 16];
204859×
    id.copy_from_slice(&h.finalize().as_bytes()[..16]);
204959×
    if id == [0; 16] {
20500×
        id[15] = 1;
205159×
    }
205259×
    NodeId(id)
205359×
}
2054
2055
struct ChangeBuilder<'a> {
2056
    base: &'a State,
2057
    base_snapshot: &'a Snapshot,
2058
    tree_ops: Vec<TreeOp>,
2059
    edits: Vec<Edit>,
2060
    statuses: Vec<PathStatus>,
2061
    dir_nodes: HashMap<String, NodeId>,
2062
    reuse: HashMap<String, (NodeId, NodeKind)>,
2063
    /// Changes that contributed to conflicts this working copy resolves.
2064
    contributors: BTreeSet<ChangeHash>,
2065
    resolves: bool,
2066
    attrs: crate::attributes::Attributes,
2067
    blobs: HashMap<String, ObjectRef>,
2068
    /// Opaque files whose replace conflict the content settles.
2069
    resolve: HashSet<String>,
2070
    /// When set, new nodes' identifiers derive from it and their paths.
2071
    node_seed: Option<[u8; 32]>,
2072
    /// For a Git import, the base's dead directories by where they were
2073
    /// (see `ensure_dir`), worked out when first needed.
2074
    dead_dirs: Option<HashMap<(NodeId, String), (NodeId, crate::tree::OpKey)>>,
2075
    /// Text edits of edited files, worked out in parallel beforehand
2076
    /// (`diff_in_parallel`); a file not here is diffed when it is updated.
2077
    diffs: HashMap<String, Vec<Edit>>,
2078
}
2079
2080
impl<'a> ChangeBuilder<'a> {
20812127×
    fn new(
20822127×
        base: &'a State,
20832127×
        base_snapshot: &'a Snapshot,
20842127×
        reuse: HashMap<String, (NodeId, NodeKind)>,
20852127×
    ) -> Self {
20862127×
        let mut dir_nodes: HashMap<String, NodeId> = HashMap::new();
20872127×
        dir_nodes.insert(String::new(), NodeId::ROOT);
208817894×
        for (p, e) in base_snapshot.tree.entries.iter() {
208917894×
            if e.kind == NodeKind::Dir {
2090555×
                dir_nodes.insert(p.clone(), e.node);
209117339×
            }
2092
        }
20932127×
        ChangeBuilder {
20942127×
            base,
20952127×
            base_snapshot,
20962127×
            tree_ops: vec![],
20972127×
            edits: vec![],
20982127×
            statuses: vec![],
20992127×
            dir_nodes,
21002127×
            reuse,
21012127×
            contributors: BTreeSet::new(),
21022127×
            resolves: false,
21032127×
            attrs: crate::attributes::Attributes::default(),
21042127×
            blobs: HashMap::new(),
21052127×
            resolve: HashSet::new(),
21062127×
            node_seed: None,
21072127×
            dead_dirs: None,
21082127×
            diffs: HashMap::new(),
21092127×
        }
21102127×
    }
2111
2112
    /// Diff the edited text files among `entries` against their base
2113
    /// renderings at once, on every core, for `update_path` to take: the
2114
    /// same diff it would make, only not one file after another.
21152127×
    fn diff_in_parallel(&mut self, entries: &BTreeMap<String, FsEntry>) {
2116
        use rayon::prelude::*;
21172127×
        let files = &self.base_snapshot.files;
21182127×
        let edited: Vec<(&String, &FsEntry, &crate::state::FileState)> = entries
21192127×
            .iter()
212018984×
            .filter_map(|(p, e)| {
212118984×
                let x = files.get(p)?;
212212856×
                (x.kind == e.kind && !e.unchanged && !self.opaque_for(p, e)).then_some((p, e, x))
212318984×
            })
21242127×
            .collect();
2125
        // Below this, starting the threads costs more than it saves.
21262127×
        if edited.len() < 16 {
21272117×
            return;
212810×
        }
212910×
        let this = &*self;
213010×
        let attrs = &this.attrs;
213110×
        let diffs: Vec<(String, Vec<Edit>)> = edited
213210×
            .par_iter()
21335564×
            .filter_map(|(p, e, x)| {
2134
                let FileContent::Text {
21355564×
                    bytes,
21365564×
                    materialized,
21375564×
                } = &x.content
2138
                else {
21390×
                    return None;
2140
                };
21415564×
                if materialized.is_conflicted() {
21420×
                    return None;
21435564×
                }
21445564×
                let disk_text = if attrs.lookup(p).eol.is_some() {
21450×
                    std::sync::Arc::new(crate::attributes::normalize_eol(&e.content))
2146
                } else {
21475564×
                    e.content.clone()
2148
                };
21495564×
                if *bytes == *disk_text {
21505484×
                    return None;
215180×
                }
215280×
                let keys = materialized.live_atoms();
215380×
                let lines = crate::diff::split_lines(bytes);
215480×
                (keys.len() == lines.len()).then(|| {
215580×
                    let edits = crate::diff::text_edits_of(x.node, &keys, &lines, &disk_text);
215680×
                    ((*p).clone(), edits)
215780×
                })
21585564×
            })
215910×
            .collect();
216010×
        self.diffs = diffs.into_iter().collect();
21612127×
    }
2162
21632127×
    fn with_attributes(mut self, attrs: crate::attributes::Attributes) -> Self {
21642127×
        self.attrs = attrs;
21652127×
        self
21662127×
    }
2167
2168
    /// Whether a file is opaque: forced by `binary`, forced text by `text`
2169
    /// only when it has no NUL bytes, else sniffed.
2170
    /// The blob for an opaque entry: the cached one, else stored now.
2171137×
    fn blob_of(
2172137×
        &mut self,
2173137×
        repo: &Repo,
2174137×
        path: &str,
2175137×
        e: &FsEntry,
2176137×
        nocompress: bool,
2177137×
    ) -> Result<ObjectRef> {
2178137×
        let b = match e.blob {
21790×
            Some(b) => b,
2180137×
            None => repo.store_blob_for(&e.content, nocompress)?,
2181
        };
2182137×
        self.blobs.insert(path.to_string(), b);
2183137×
        Ok(b)
2184137×
    }
2185
218623353×
    fn opaque_for(&self, path: &str, e: &FsEntry) -> bool {
218723353×
        if e.blob.is_some() {
21888×
            return true;
218923345×
        }
219023345×
        if e.kind == NodeKind::Symlink || e.kind == NodeKind::Subrepo {
2191100×
            return true;
219223245×
        }
219323245×
        match self.attrs.lookup(path).binary {
219412×
            Some(true) => true,
21950×
            Some(false) => is_binary(&e.content),
219623233×
            None => is_binary(&e.content),
2197
        }
219823353×
    }
2199
2200
    /// Text content as stored: `\r\n` normalized for `eol=` files.
220114607×
    fn stored_text(
220214607×
        &self,
220314607×
        path: &str,
220414607×
        content: &std::sync::Arc<Vec<u8>>,
220514607×
    ) -> std::sync::Arc<Vec<u8>> {
220614607×
        if self.attrs.lookup(path).eol.is_some() {
22077×
            std::sync::Arc::new(crate::attributes::normalize_eol(content))
2208
        } else {
220914600×
            content.clone()
2210
        }
221114607×
    }
2212
2213
    /// The identifier of a node added at `path`: reused when asked, derived
2214
    /// from the seed when there is one, random otherwise.
22156247×
    fn new_node(&self, path: &str, kind: NodeKind) -> NodeId {
22166247×
        if let Some(n) = self.reused_node(path, kind) {
2217151×
            return n;
22186096×
        }
22196096×
        match &self.node_seed {
222059×
            Some(seed) => seeded_node(seed, path, kind),
22216037×
            None => NodeId::random(),
2222
        }
22236247×
    }
2224
22256247×
    fn reused_node(&self, path: &str, kind: NodeKind) -> Option<NodeId> {
22266247×
        self.reuse
22276247×
            .get(path)
22286247×
            .filter(|(_, k)| *k == kind)
22296247×
            .map(|(n, _)| *n)
22306247×
    }
2231
2232
    /// A dead directory last placed at (`parent`, `name`) in the base.
223315×
    fn revivable_dir(
223415×
        &mut self,
223515×
        parent: NodeId,
223615×
        name: &str,
223715×
    ) -> Option<(NodeId, crate::tree::OpKey)> {
223815×
        let base = self.base;
223915×
        self.dead_dirs
224015×
            .get_or_insert_with(|| base.tree().dead_dirs())
224115×
            .get(&(parent, name.to_string()))
224215×
            .copied()
224315×
    }
2244
22456129×
    fn ensure_dir(&mut self, path: &str) -> NodeId {
22466129×
        if let Some(n) = self.dir_nodes.get(path) {
22475978×
            return *n;
2248151×
        }
2249151×
        let mut parent = NodeId::ROOT;
2250151×
        let mut prefix = String::new();
2251170×
        for comp in path.split('/') {
2252170×
            if !prefix.is_empty() {
225319×
                prefix.push('/');
2254151×
            }
2255170×
            prefix.push_str(comp);
2256170×
            let known = self.dir_nodes.get(&prefix).copied();
2257170×
            let revive = match known {
225813×
                Some(_) => None,
2259157×
                None if self.node_seed.is_some() => self.revivable_dir(parent, comp),
2260142×
                None => None,
2261
            };
2262170×
            parent = match (known, revive) {
226313×
                (Some(n), _) => n,
22642×
                (None, Some((node, old))) => {
2265
                    // Git has no identity for a directory: one that comes
2266
                    // back where it was is the same directory, brought back
2267
                    // with a move, so lines of history that placed files in
2268
                    // it before and after agree (oxygen#30).
22692×
                    self.tree_ops.push(TreeOp::Move {
22702×
                        node,
22712×
                        old: OpRef {
22722×
                            change: old.0,
22732×
                            index: old.1,
22742×
                        },
22752×
                        parent,
22762×
                        name: comp.to_string(),
22772×
                    });
22782×
                    self.dir_nodes.insert(prefix.clone(), node);
22792×
                    node
2280
                }
2281
                (None, None) => {
2282155×
                    let node = self.new_node(&prefix, NodeKind::Dir);
2283155×
                    self.tree_ops.push(TreeOp::AddNode {
2284155×
                        node,
2285155×
                        kind: NodeKind::Dir,
2286155×
                        mode: Mode::default(),
2287155×
                        parent,
2288155×
                        name: comp.to_string(),
2289155×
                    });
2290155×
                    self.dir_nodes.insert(prefix.clone(), node);
2291155×
                    node
2292
                }
2293
            };
2294
        }
2295151×
        parent
22966129×
    }
2297
22986092×
    fn add_path(&mut self, repo: &Repo, path: &str, e: &FsEntry) -> Result<()> {
22996092×
        let (dir, name) = split_path(path);
23006092×
        let parent = self.ensure_dir(dir);
23016092×
        let node = self.new_node(path, e.kind);
23026092×
        let opaque = self.opaque_for(path, e);
23036092×
        let nocompress = self.attrs.lookup(path).nocompress;
23046092×
        self.tree_ops.push(TreeOp::AddNode {
23056092×
            node,
23066092×
            kind: e.kind,
23076092×
            mode: Mode {
23086092×
                exec: e.exec,
23096092×
                opaque,
23106092×
            },
23116092×
            parent,
23126092×
            name: name.to_string(),
23136092×
        });
23146092×
        if opaque {
2315101×
            let blob = self.blob_of(repo, path, e, nocompress)?;
2316101×
            self.edits.push(Edit::Replace {
2317101×
                node,
2318101×
                old: None,
2319101×
                new: Some(blob),
2320101×
            });
23215991×
        } else if !e.content.is_empty() {
23225958×
            let content = self.stored_text(path, &e.content);
23235958×
            self.edits.push(Edit::Insert {
23245958×
                node,
23255958×
                after: crate::objects::AtomRef::Start,
23265958×
                before: crate::objects::AtomRef::End,
23275958×
                lines: crate::lines::Lines::split_shared(content),
23285958×
            });
23295958×
        }
23306092×
        self.statuses.push(PathStatus {
23316092×
            path: path.to_string(),
23326092×
            status: ChangeStatus::Added,
23336092×
        });
23346092×
        Ok(())
23356092×
    }
2336
2337
    /// Move the node at `old` to `new` and apply `e`'s content to it.
233837×
    fn move_path(
233937×
        &mut self,
234037×
        repo: &Repo,
234137×
        old: &str,
234237×
        new: &str,
234337×
        e: &FsEntry,
234437×
        expected: &crate::state::FileState,
234537×
    ) -> Result<()> {
234637×
        let placement = self.base_snapshot.tree.entries[old].placement;
234737×
        let (dir, name) = split_path(new);
234837×
        let parent = self.ensure_dir(dir);
234937×
        self.tree_ops.push(TreeOp::Move {
235037×
            node: expected.node,
235137×
            old: op_ref(placement),
235237×
            parent,
235337×
            name: name.to_string(),
235437×
        });
235537×
        for k in self.same_place(&expected.node, placement) {
23560×
            self.tree_ops.push(TreeOp::RemoveNode {
23570×
                node: expected.node,
23580×
                placement: op_ref(k),
23590×
            });
23600×
        }
236137×
        self.update_path(repo, old, e, expected)?;
2362
        // update_path reports under the old path; the rename is what the user sees.
236337×
        self.statuses.retain(|s| s.path != old);
236437×
        self.statuses.push(PathStatus {
236537×
            path: new.to_string(),
236637×
            status: ChangeStatus::Renamed,
236737×
        });
236837×
        Ok(())
236937×
    }
2370
2371
    /// For a Git import: a node the commit keeps is in one place, the one
2372
    /// its tree names, so any other live placement it has in the base goes;
2373
    /// and a node the tree cannot show at all (an orphan) goes too. Such a
2374
    /// placement is out of sight, under a directory another line of history
2375
    /// removed, where no diff of the tree would ever reach it (oxygen#30).
237688×
    fn retire_stray_placements(&mut self) {
237788×
        let mut retired: HashSet<(ChangeHash, u32)> = HashSet::new();
237888×
        let mut placed: BTreeSet<NodeId> = BTreeSet::new();
237999×
        for op in &self.tree_ops {
238099×
            match op {
238119×
                TreeOp::Move { node, old, .. } => {
238219×
                    retired.insert((old.change, old.index));
238319×
                    placed.insert(*node);
238419×
                }
238521×
                TreeOp::RemoveNode { placement, .. } => {
238621×
                    retired.insert((placement.change, placement.index));
238721×
                }
238859×
                TreeOp::AddNode { .. } | TreeOp::SetMode { .. } => {}
2389
            }
2390
        }
2391
        // Nodes kept where they were: what the base's tree view shows and
2392
        // this change neither moves nor removes.
239388×
        let mut kept: HashMap<NodeId, (ChangeHash, u32)> = HashMap::new();
2394241×
        for e in self.base_snapshot.tree.entries.values() {
2395241×
            if !retired.contains(&e.placement) {
2396204×
                kept.insert(e.node, e.placement);
2397204×
            }
2398
        }
2399
        // Only a node with several live placements can have a stray one,
2400
        // and the tree view names each as a conflict.
240188×
        let multi: BTreeSet<NodeId> = self
240288×
            .base_snapshot
240388×
            .tree
240488×
            .conflicts
240588×
            .iter()
240688×
            .filter_map(|c| match c {
24071×
                crate::tree::TreeConflict::MultiPlacement { node, .. } => Some(*node),
24086×
                _ => None,
24097×
            })
241088×
            .collect();
241188×
        let mut extra = Vec::new();
2412
        // A node whose only placements are under a directory another line
2413
        // removed (an orphan) is nowhere the tree can show, and Git's tree
2414
        // has no such path: it goes.
241588×
        for c in &self.base_snapshot.tree.conflicts {
24167×
            let crate::tree::TreeConflict::Orphan { node, .. } = c else {
24176×
                continue;
2418
            };
24191×
            if kept.contains_key(node) || placed.contains(node) {
24200×
                continue;
24211×
            }
24221×
            for (k, _) in self.base.tree().live_placements(node) {
24231×
                if retired.insert(k) {
24241×
                    extra.push(TreeOp::RemoveNode {
24251×
                        node: *node,
24261×
                        placement: op_ref(k),
24271×
                    });
24281×
                }
2429
            }
2430
        }
243188×
        for node in placed
243288×
            .iter()
243388×
            .chain(multi.iter().filter(|n| kept.contains_key(*n)))
2434
        {
243519×
            for (k, _) in self.base.tree().live_placements(node) {
243618×
                if retired.contains(&k) || kept.get(node) == Some(&k) {
243717×
                    continue;
24381×
                }
24391×
                retired.insert(k);
24401×
                extra.push(TreeOp::RemoveNode {
24411×
                    node: *node,
24421×
                    placement: op_ref(k),
24431×
                });
2444
            }
2445
        }
244688×
        if !extra.is_empty() {
24472×
            self.resolves = true;
24482×
            self.tree_ops.extend(extra);
244986×
        }
245088×
    }
2451
2452
    /// Nodes the base shows as one with another (identical additions at one
2453
    /// path, spec §9.2) are retired by the change that first touches the
2454
    /// node shown: edited, moved, removed or given a mode alone, it would
2455
    /// differ from them and the name conflict would come back. Nothing
2456
    /// else changes for the user, so no status reports it.
24572127×
    fn retire_unified(&mut self) {
24582127×
        let unified = &self.base_snapshot.tree.unified;
24592127×
        if unified.is_empty() {
24602106×
            return;
246121×
        }
246221×
        let touched: HashSet<NodeId> = self
246321×
            .tree_ops
246421×
            .iter()
246521×
            .map(|o| o.node())
246622×
            .chain(self.edits.iter().map(|e| e.node()))
246721×
            .collect();
246821×
        let mut retired: HashSet<(ChangeHash, u32)> = HashSet::new();
246921×
        for op in &self.tree_ops {
247014×
            match op {
24713×
                TreeOp::Move { old, .. } => {
24723×
                    retired.insert((old.change, old.index));
24733×
                }
24743×
                TreeOp::RemoveNode { placement, .. } => {
24753×
                    retired.insert((placement.change, placement.index));
24763×
                }
24778×
                TreeOp::AddNode { .. } | TreeOp::SetMode { .. } => {}
2478
            }
2479
        }
248021×
        let mut extra = Vec::new();
248122×
        for (dup, shown) in unified {
248222×
            if !touched.contains(shown) {
24835×
                continue;
248417×
            }
248517×
            for (k, _) in self.base.tree().live_placements(dup) {
248617×
                if retired.insert(k) {
248717×
                    extra.push(TreeOp::RemoveNode {
248817×
                        node: *dup,
248917×
                        placement: op_ref(k),
249017×
                    });
249117×
                }
2492
            }
2493
        }
249421×
        self.tree_ops.extend(extra);
24952127×
    }
2496
2497
    /// The node's other live placements at the same place as `k`, the one
2498
    /// the tree shows: two lines of history that put a node back where it
2499
    /// was each leave a placement, and the tree shows them as one file. A
2500
    /// change that removes or moves it retires them together, or the copy
2501
    /// left behind outlives its directory (oxygen#88).
2502173×
    fn same_place(&self, node: &NodeId, k: (ChangeHash, u32)) -> Vec<(ChangeHash, u32)> {
2503173×
        let tree = self.base.tree();
2504173×
        let Some(shown) = tree.placement(&k) else {
25050×
            return Vec::new();
2506
        };
2507173×
        tree.live_placements(node)
2508173×
            .into_iter()
2509175×
            .filter(|(o, p)| *o != k && p.parent == shown.parent && p.name == shown.name)
2510173×
            .map(|(o, _)| o)
2511173×
            .collect()
2512173×
    }
2513
2514136×
    fn remove_path(&mut self, path: &str, expected: &crate::state::FileState) {
2515136×
        let entry = &self.base_snapshot.tree.entries[path];
2516136×
        let placement = entry.placement;
2517136×
        self.tree_ops.push(TreeOp::RemoveNode {
2518136×
            node: expected.node,
2519136×
            placement: op_ref(placement),
2520136×
        });
2521136×
        for k in self.same_place(&expected.node, placement) {
25221×
            self.tree_ops.push(TreeOp::RemoveNode {
25231×
                node: expected.node,
25241×
                placement: op_ref(k),
25251×
            });
25261×
        }
2527136×
        if path.contains(".oxy-conflict-") || expected.is_conflicted() {
25287×
            self.resolves = true;
2529129×
        }
2530136×
        self.statuses.push(PathStatus {
2531136×
            path: path.to_string(),
2532136×
            status: ChangeStatus::Removed,
2533136×
        });
2534136×
    }
2535
253612893×
    fn update_path(
253712893×
        &mut self,
253812893×
        repo: &Repo,
253912893×
        path: &str,
254012893×
        e: &FsEntry,
254112893×
        expected: &crate::state::FileState,
254212893×
    ) -> Result<()> {
254312893×
        if expected.kind != e.kind {
25441×
            self.remove_path(path, expected);
25451×
            self.statuses.pop();
25461×
            self.add_path(repo, path, e)?;
25471×
            self.statuses.pop();
25481×
            self.statuses.push(PathStatus {
25491×
                path: path.to_string(),
25501×
                status: ChangeStatus::Modified,
25511×
            });
25521×
            return Ok(());
255312892×
        }
255412892×
        let entry = &self.base_snapshot.tree.entries[path];
255512892×
        let node = expected.node;
255612892×
        let mode_atom = entry.mode_atom.map(op_ref);
255712892×
        if e.unchanged {
2558
            // Known equal to the base's unconflicted rendering (spec
2559
            // §12.3); only the executable bit can differ.
25604243×
            if e.exec != expected.mode.exec {
25613×
                if let Some(old) = mode_atom {
25623×
                    self.tree_ops.push(TreeOp::SetMode {
25633×
                        node,
25643×
                        old,
25653×
                        mode: Mode {
25663×
                            exec: e.exec,
25673×
                            opaque: false,
25683×
                        },
25693×
                    });
25703×
                    self.statuses.push(PathStatus {
25713×
                        path: path.to_string(),
25723×
                        status: ChangeStatus::ModeChanged,
25733×
                    });
25743×
                }
25754240×
            }
25764243×
            return Ok(());
25778649×
        }
25788649×
        let mut status: Option<ChangeStatus> = None;
25798649×
        let wants_opaque = self.opaque_for(path, e);
25808649×
        let nocompress = self.attrs.lookup(path).nocompress;
25818649×
        let disk_text = self.stored_text(path, &e.content);
25828649×
        match &expected.content {
25830×
            FileContent::Dir => {}
2584
            FileContent::Text {
25858417×
                bytes,
25868417×
                materialized,
2587
            } => {
25888417×
                if materialized.is_conflicted() {
258933×
                    if bytes == &*disk_text {
25906×
                        return Ok(());
259127×
                    }
259227×
                    if has_conflict_markers(&e.content) {
25934×
                        self.statuses.push(PathStatus {
25944×
                            path: path.to_string(),
25954×
                            status: ChangeStatus::ConflictEdited,
25964×
                        });
25974×
                        return Ok(());
259823×
                    }
2599
                    // Resolution (spec §9.6): diff against the unconflicted lines
2600
                    // with each region as a gap, then retire every region atom.
2601
                    // Whatever the author kept from a region is re-inserted as
2602
                    // new atoms, which leaves the graph totally ordered.
260323×
                    let regions = self.base.conflict_regions(&node);
260423×
                    let mut edits = text_edits(node, &regions.plain, &disk_text);
260523×
                    if !regions.region_atoms.is_empty() {
260623×
                        edits.insert(
260723×
                            0,
260823×
                            Edit::Delete {
260923×
                                node,
261023×
                                atoms: ranges(&regions.region_atoms),
261123×
                            },
261223×
                        );
261323×
                    }
261423×
                    self.edits.extend(edits);
261523×
                    self.contributors.extend(regions.contributors);
261623×
                    self.resolves = true;
261723×
                    if e.exec != expected.mode.exec {
26180×
                        if let Some(old) = mode_atom {
26190×
                            self.tree_ops.push(TreeOp::SetMode {
26200×
                                node,
26210×
                                old,
26220×
                                mode: Mode {
26230×
                                    exec: e.exec,
26240×
                                    opaque: false,
26250×
                                },
26260×
                            });
26270×
                        }
262823×
                    }
262923×
                    self.statuses.push(PathStatus {
263023×
                        path: path.to_string(),
263123×
                        status: ChangeStatus::Resolved,
263223×
                    });
263323×
                    return Ok(());
26348384×
                }
26358384×
                if wants_opaque {
2636
                    // Text → opaque (spec §7.5), by content or by attribute.
26372×
                    if let Some(old) = mode_atom {
26382×
                        self.tree_ops.push(TreeOp::SetMode {
26392×
                            node,
26402×
                            old,
26412×
                            mode: Mode {
26422×
                                exec: e.exec,
26432×
                                opaque: true,
26442×
                            },
26452×
                        });
26462×
                    }
26472×
                    let live: Vec<_> = repo_live_keys(self.base, &node);
26482×
                    if !live.is_empty() {
26492×
                        self.edits.push(Edit::Delete {
26502×
                            node,
26512×
                            atoms: ranges(&live),
26522×
                        });
26532×
                    }
26542×
                    let blob = self.blob_of(repo, path, e, nocompress)?;
26552×
                    self.edits.push(Edit::Replace {
26562×
                        node,
26572×
                        old: None,
26582×
                        new: Some(blob),
26592×
                    });
26602×
                    status = Some(ChangeStatus::Modified);
26618382×
                } else if bytes != &*disk_text {
2662819×
                    let mut laps = crate::timing::Laps::start();
2663
                    // The base's rendering holds its live atoms in order,
2664
                    // one per line (it is not conflicted here).
2665819×
                    let edits = match self.diffs.remove(path) {
266680×
                        Some(edits) => edits,
2667
                        None => {
2668739×
                            let keys = materialized.live_atoms();
2669739×
                            let lines = crate::diff::split_lines(bytes);
2670739×
                            if keys.len() == lines.len() {
2671739×
                                crate::diff::text_edits_of(node, &keys, &lines, &disk_text)
2672
                            } else {
26730×
                                text_edits(node, &self.base.live_lines(&node), &disk_text)
2674
                            }
2675
                        }
2676
                    };
2677819×
                    laps.lap("build: text diff");
2678819×
                    if !edits.is_empty() {
2679819×
                        self.edits.extend(edits);
2680819×
                        status = Some(ChangeStatus::Modified);
2681819×
                    }
26827563×
                }
26838384×
                let switched_to_opaque = wants_opaque;
26848384×
                if !switched_to_opaque && e.exec != expected.mode.exec {
26854×
                    if let Some(old) = mode_atom {
26864×
                        self.tree_ops.push(TreeOp::SetMode {
26874×
                            node,
26884×
                            old,
26894×
                            mode: Mode {
26904×
                                exec: e.exec,
26914×
                                opaque: false,
26924×
                            },
26934×
                        });
26944×
                        status.get_or_insert(ChangeStatus::ModeChanged);
26954×
                    }
26968380×
                }
2697
            }
2698232×
            FileContent::Opaque { blobs } => {
2699232×
                let new_ref = e.blob.unwrap_or_else(|| Repo::blob_ref(&e.content));
2700232×
                if e.kind == NodeKind::File && wants_opaque {
2701191×
                    // Unchanged or replaced, the file stays opaque: remember its blob.
2702191×
                    self.blobs.insert(path.to_string(), new_ref);
2703191×
                }
2704232×
                if blobs.len() > 1 && self.resolve.contains(path) && e.kind == expected.kind {
2705
                    // Settle the replace conflict (spec §9.3): replace every
2706
                    // live candidate with the chosen blob, depending on each
2707
                    // change that made one live, so all are superseded.
27082×
                    let chosen = self.blob_of(repo, path, e, nocompress)?;
27094×
                    for b in blobs {
27104×
                        self.edits.push(Edit::Replace {
27114×
                            node,
27124×
                            old: Some(*b),
27134×
                            new: Some(chosen),
27144×
                        });
27154×
                    }
27162×
                    self.contributors
27172×
                        .extend(self.base.blob_contributors(&node, blobs));
27182×
                    self.resolves = true;
27192×
                    self.statuses.push(PathStatus {
27202×
                        path: path.to_string(),
27212×
                        status: ChangeStatus::Resolved,
27222×
                    });
27232×
                    return Ok(());
2724230×
                }
2725230×
                if blobs.len() > 1 {
27262×
                    if !blobs.contains(&new_ref) {
27270×
                        self.statuses.push(PathStatus {
27280×
                            path: path.to_string(),
27290×
                            status: ChangeStatus::ConflictEdited,
27300×
                        });
27312×
                    }
27322×
                    return Ok(());
2733228×
                }
2734228×
                let current = blobs.first().copied();
2735228×
                if current != Some(new_ref) {
273634×
                    if e.kind == NodeKind::File && !wants_opaque {
2737
                        // Opaque → text (spec §7.5).
27382×
                        if let Some(old) = mode_atom {
27392×
                            self.tree_ops.push(TreeOp::SetMode {
27402×
                                node,
27412×
                                old,
27422×
                                mode: Mode {
27432×
                                    exec: e.exec,
27442×
                                    opaque: false,
27452×
                                },
27462×
                            });
27472×
                        }
27482×
                        self.edits.push(Edit::Replace {
27492×
                            node,
27502×
                            old: current,
27512×
                            new: None,
27522×
                        });
27532×
                        if !e.content.is_empty() {
27542×
                            self.edits.push(Edit::Insert {
27552×
                                node,
27562×
                                after: crate::objects::AtomRef::Start,
27572×
                                before: crate::objects::AtomRef::End,
27582×
                                lines: crate::lines::Lines::split(&e.content),
27592×
                            });
27602×
                        }
2761
                    } else {
276232×
                        let blob = self.blob_of(repo, path, e, nocompress)?;
276332×
                        self.edits.push(Edit::Replace {
276432×
                            node,
276532×
                            old: current,
276632×
                            new: Some(blob),
276732×
                        });
2768
                        // New contents and a new executable bit at once: the
2769
                        // bit was dropped (VS Code's inno_updater.exe,
2770
                        // 2018-02-28, lost +x for 49 commits; oxygen#87).
277132×
                        if e.kind == NodeKind::File && e.exec != expected.mode.exec {
27722×
                            if let Some(old) = mode_atom {
27732×
                                self.tree_ops.push(TreeOp::SetMode {
27742×
                                    node,
27752×
                                    old,
27762×
                                    mode: Mode {
27772×
                                        exec: e.exec,
27782×
                                        opaque: true,
27792×
                                    },
27802×
                                });
27812×
                            }
278230×
                        }
2783
                    }
278434×
                    status = Some(ChangeStatus::Modified);
2785194×
                } else if e.kind == NodeKind::File && e.exec != expected.mode.exec {
27860×
                    if let Some(old) = mode_atom {
27870×
                        self.tree_ops.push(TreeOp::SetMode {
27880×
                            node,
27890×
                            old,
27900×
                            mode: Mode {
27910×
                                exec: e.exec,
27920×
                                opaque: true,
27930×
                            },
27940×
                        });
27950×
                        status = Some(ChangeStatus::ModeChanged);
27960×
                    }
2797194×
                }
2798
            }
2799
        }
28008612×
        if let Some(s) = status {
2801859×
            self.statuses.push(PathStatus {
2802859×
                path: path.to_string(),
2803859×
                status: s,
2804859×
            });
28057753×
        }
28068612×
        Ok(())
280712893×
    }
2808
}
2809
28102×
fn repo_live_keys(base: &State, node: &NodeId) -> Vec<crate::graph::AtomKey> {
28112×
    base.live_lines(node).into_iter().map(|(k, _)| k).collect()
28122×
}
2813
2814
/// The changes a change's scope references (spec §8.1): introducers of every
2815
/// atom, placement, and mode it touches, and of every node it operates on.
28162205×
pub fn referenced_changes(change: &Change, base: &State) -> BTreeSet<ChangeHash> {
28172205×
    let mut out = BTreeSet::new();
28182205×
    let opref = |r: &OpRef, out: &mut BTreeSet<ChangeHash>| {
2819219×
        if !r.change.is_zero() {
2820219×
            out.insert(r.change);
2821219×
        }
2822219×
    };
28232205×
    let mut nodes: Vec<NodeId> = Vec::new();
28246671×
    for op in &change.tree_ops {
28256671×
        match op {
28266452×
            TreeOp::AddNode { parent, .. } => nodes.push(*parent),
2827166×
            TreeOp::RemoveNode { node, placement } => {
2828166×
                nodes.push(*node);
2829166×
                opref(placement, &mut out);
2830166×
            }
2831
            TreeOp::Move {
283241×
                node, old, parent, ..
283341×
            } => {
283441×
                nodes.push(*node);
283541×
                nodes.push(*parent);
283641×
                opref(old, &mut out);
283741×
            }
283812×
            TreeOp::SetMode { node, old, .. } => {
283912×
                nodes.push(*node);
284012×
                opref(old, &mut out);
284112×
            }
2842
        }
2843
    }
28448278×
    for e in &change.edits {
28458278×
        nodes.push(e.node());
2846139×
        match e {
28477553×
            Edit::Insert { after, before, .. } => {
284815106×
                for r in [after, before] {
284915106×
                    if let crate::objects::AtomRef::Atom { change, .. } = r {
28502253×
                        if !change.is_zero() {
28512251×
                            out.insert(*change);
28522251×
                        }
285312853×
                    }
2854
                }
2855
            }
2856586×
            Edit::Delete { atoms, .. } => {
2857
                // Deleting an atom also depends on whoever inserted the live
2858
                // atoms right after it: the author saw those insertions, and
2859
                // without the dependency spec §9.1 would call the deletion
2860
                // concurrent with them (a delete/insert conflict).
2861586×
                let graph = base.file(&e.node());
28621143×
                for r in atoms {
28631143×
                    if !r.change.is_zero() {
28641142×
                        out.insert(r.change);
28651142×
                    }
28661143×
                    if let Some(g) = graph {
28671192×
                        for i in r.from..r.to {
28681192×
                            out.extend(
28691192×
                                g.live_successor_changes(&(r.change, i))
28701192×
                                    .into_iter()
28711192×
                                    .filter(|c| !c.is_zero()),
2872
                            );
2873
                        }
28740×
                    }
2875
                }
2876
            }
2877
            // Replacing a blob depends on the change that made it current,
2878
            // as deleting a line depends on the line's introducer.
2879
            Edit::Replace {
288039×
                node,
288139×
                old: Some(old),
2882
                ..
2883
            } => {
288439×
                out.extend(
288539×
                    base.live_replaces(node)
288639×
                        .into_iter()
288746×
                        .filter(|(c, b)| b == old && !c.is_zero())
288839×
                        .map(|(c, _)| c),
2889
                );
2890
            }
2891100×
            Edit::Replace { .. } => {}
2892
        }
2893
    }
289414990×
    for n in nodes {
289514990×
        if let Some(h) = base.tree().introducer(&n) {
28962317×
            out.insert(h);
289712673×
        }
2898
    }
28992205×
    out
29002205×
}
2901
2902
/// Paths of the nodes a change adds on top of `base_snapshot`.
29031381×
pub fn added_node_paths(
29041381×
    change: &Change,
29051381×
    base_snapshot: &Snapshot,
29061381×
) -> HashMap<String, (NodeId, NodeKind)> {
29071381×
    let by_node = base_snapshot.tree.by_node();
29081381×
    let mut new_names: HashMap<NodeId, (NodeId, String, NodeKind)> = HashMap::new();
29091381×
    for op in &change.tree_ops {
2910
        if let TreeOp::AddNode {
291185×
            node,
291285×
            parent,
291385×
            name,
291485×
            kind,
2915
            ..
2916117×
        } = op
291785×
        {
291885×
            new_names.insert(*node, (*parent, name.clone(), *kind));
291985×
        }
2920
    }
29211381×
    let mut out = HashMap::new();
29221381×
    for (node, (_, _, kind)) in &new_names {
292385×
        if let Some(path) = path_of_node(node, &by_node, &new_names) {
292485×
            out.insert(path, (*node, *kind));
292585×
        }
2926
    }
29271381×
    out
29281381×
}
2929
2930
/// Whether `op` retires a node `base_snapshot` shows as one with another
2931
/// (spec §9.2): part of touching that node, never a removal the user made.
293237×
fn is_unified_retirement(op: &TreeOp, base_snapshot: &Snapshot) -> bool {
29338×
    matches!(op, TreeOp::RemoveNode { node, .. } if base_snapshot.tree.unified.contains_key(node))
293437×
}
2935
2936208×
fn path_of_node(
2937208×
    n: &NodeId,
2938208×
    by_node: &HashMap<NodeId, &crate::tree::TreeEntry>,
2939208×
    new_names: &HashMap<NodeId, (NodeId, String, NodeKind)>,
2940208×
) -> Option<String> {
2941208×
    if let Some(e) = by_node.get(n) {
294263×
        return Some(e.path.clone());
2943145×
    }
2944145×
    let mut parts = Vec::new();
2945145×
    let mut cur = *n;
2946
    loop {
2947286×
        if cur.is_root() {
2948128×
            break;
2949158×
        }
2950158×
        if let Some(e) = by_node.get(&cur) {
29510×
            if !e.path.is_empty() {
29520×
                parts.push(e.path.clone());
29530×
            }
29540×
            break;
2955158×
        }
2956158×
        let (parent, name, _) = new_names.get(&cur)?;
2957141×
        parts.push(name.clone());
2958141×
        cur = *parent;
2959
    }
2960128×
    parts.reverse();
2961128×
    Some(parts.join("/"))
2962208×
}
2963
2964
/// Render a change's operations with line content, using `base` for deleted lines.
296533×
pub fn render_change(change: &Change, base: &State, base_snapshot: &Snapshot) -> String {
296633×
    let by_node = base_snapshot.tree.by_node();
296733×
    let mut new_names: HashMap<NodeId, (NodeId, String, NodeKind)> = HashMap::new();
296833×
    for op in &change.tree_ops {
2969
        if let TreeOp::AddNode {
297016×
            node,
297116×
            parent,
297216×
            name,
297316×
            kind,
2974
            ..
297524×
        } = op
297616×
        {
297716×
            new_names.insert(*node, (*parent, name.clone(), *kind));
297816×
        }
2979
    }
298073×
    let path_of = |n: &NodeId| -> String {
298173×
        path_of_node(n, &by_node, &new_names).unwrap_or_else(|| format!("<node {}>", n.short(8)))
298273×
    };
2983
298433×
    let mut out = String::new();
298533×
    for op in change
298633×
        .tree_ops
298733×
        .iter()
298833×
        .filter(|o| !is_unified_retirement(o, base_snapshot))
2989
    {
299023×
        match op {
2991
            TreeOp::AddNode {
299216×
                node, kind, mode, ..
2993
            } => {
299416×
                out.push_str(&format!(
2995
                    "A {} ({:?}{}{})\n",
299616×
                    path_of(node),
2997
                    kind,
299816×
                    if mode.exec { ", exec" } else { "" },
299916×
                    if mode.opaque { ", opaque" } else { "" }
3000
                ));
3001
            }
30025×
            TreeOp::RemoveNode { node, .. } => out.push_str(&format!("D {}\n", path_of(node))),
3003
            TreeOp::Move {
30042×
                node, parent, name, ..
3005
            } => {
30062×
                let to = if parent.is_root() {
30070×
                    name.clone()
3008
                } else {
30092×
                    format!("{}/{name}", path_of(parent))
3010
                };
30112×
                out.push_str(&format!("R {} -> {to}\n", path_of(node)))
3012
            }
30130×
            TreeOp::SetMode { node, mode, .. } => {
30140×
                out.push_str(&format!(
30150×
                    "M {} mode: exec={} opaque={}\n",
30160×
                    path_of(node),
30170×
                    mode.exec,
30180×
                    mode.opaque
30190×
                ));
30200×
            }
3021
        }
3022
    }
3023
    // Every other file the change edits is modified: the summary names
3024
    // every path it touches, not only those with a tree operation.
302533×
    let with_op: HashSet<NodeId> = change.tree_ops.iter().map(|o| o.node()).collect();
302633×
    let mut listed: HashSet<NodeId> = HashSet::new();
302736×
    for e in &change.edits {
302836×
        let n = e.node();
302936×
        if !with_op.contains(&n) && listed.insert(n) {
303021×
            out.push_str(&format!("M {}\n", path_of(&n)));
303121×
        }
3032
    }
303333×
    let mut last_node: Option<NodeId> = None;
303436×
    for e in &change.edits {
303536×
        let n = e.node();
303636×
        if last_node != Some(n) {
303727×
            out.push_str(&format!("--- {}\n", path_of(&n)));
303827×
            last_node = Some(n);
303927×
        }
304036×
        match e {
304127×
            Edit::Insert { lines, .. } => {
304232×
                for l in lines.iter() {
304332×
                    out.push('+');
304432×
                    out.push_str(&String::from_utf8_lossy(l));
304532×
                    if !l.ends_with(b"\n") {
30460×
                        out.push('\n');
304732×
                    }
3048
                }
3049
            }
30508×
            Edit::Delete { atoms, .. } => {
30518×
                for r in atoms {
30528×
                    for i in r.from..r.to {
30538×
                        let content = base
30548×
                            .file(&n)
30558×
                            .and_then(|g| g.content(&(r.change, i)))
30568×
                            .unwrap_or(b"<unknown>\n");
30578×
                        out.push('-');
30588×
                        out.push_str(&String::from_utf8_lossy(content));
30598×
                        if !content.ends_with(b"\n") {
30600×
                            out.push('\n');
30618×
                        }
3062
                    }
3063
                }
3064
            }
30651×
            Edit::Replace { old, new, .. } => {
30661×
                out.push_str(&format!(
3067
                    "  opaque content {} -> {}\n",
30681×
                    old.map(|o| o.short(12)).unwrap_or_else(|| "none".into()),
30691×
                    new.map(|o| o.short(12)).unwrap_or_else(|| "none".into())
3070
                ));
3071
            }
3072
        }
3073
    }
307433×
    out
307533×
}
3076
3077
/// Pair removed files with added files of the same kind whose contents are
3078
/// at least `RENAME_THRESHOLD` percent alike, best matches first. Beyond
3079
/// `RENAME_LIMIT` candidate pairs only identical contents are paired.
3080
const RENAME_THRESHOLD: u32 = 50;
3081
const RENAME_LIMIT: usize = 10_000;
3082
3083
/// How a change is built beyond its entries: for a Git import, the seed
3084
/// its new nodes' identifiers derive from; and, when it is built from part
3085
/// of the tree, whether the new tree has anything under a directory.
3086
#[derive(Default)]
3087
struct Scope<'a> {
3088
    seed: Option<[u8; 32]>,
3089
    dir_needed: Option<&'a dyn Fn(&str) -> bool>,
3090
}
3091
30922127×
fn detect_renames(
30932127×
    base_snapshot: &Snapshot,
30942127×
    fs_entries: &BTreeMap<String, FsEntry>,
30952127×
    in_scope: impl Fn(&str) -> bool,
30962127×
) -> Vec<(String, String)> {
30972127×
    let removed: Vec<(&String, &crate::state::FileState)> = base_snapshot
30982127×
        .files
30992127×
        .iter()
310013435×
        .filter(|(p, f)| {
310113435×
            f.kind != NodeKind::Dir
310213012×
                && !fs_entries.contains_key(*p)
3103156×
                && in_scope(p)
3104146×
                && !f.is_conflicted()
310513435×
        })
31062127×
        .collect();
31072127×
    let added: Vec<(&String, &FsEntry)> = fs_entries
31082127×
        .iter()
310918984×
        .filter(|(p, e)| e.kind != NodeKind::Dir && !base_snapshot.files.contains_key(*p))
31102127×
        .collect();
31112127×
    if removed.is_empty() || added.is_empty() {
31122065×
        return vec![];
311362×
    }
311462×
    let exact_only = removed.len() * added.len() > RENAME_LIMIT;
311576×
    let old_content = |f: &crate::state::FileState| -> Option<Vec<u8>> {
311676×
        match &f.content {
311772×
            FileContent::Text { bytes, .. } => Some(bytes.clone()),
31184×
            _ => None,
3119
        }
312076×
    };
312162×
    let mut scored: Vec<(u32, usize, usize)> = Vec::new();
312276×
    for (ri, (_, f)) in removed.iter().enumerate() {
312376×
        let old = old_content(f);
312476×
        let old_blob = match &f.content {
31254×
            FileContent::Opaque { blobs } if blobs.len() == 1 => Some(blobs[0]),
312672×
            _ => None,
3127
        };
312896×
        for (ai, (_, e)) in added.iter().enumerate() {
312996×
            if e.kind != f.kind {
31300×
                continue;
313196×
            }
313296×
            let score = match (&old, old_blob) {
313386×
                (Some(o), _) => {
313486×
                    if exact_only {
31350×
                        if *o == *e.content {
31360×
                            100
3137
                        } else {
31380×
                            0
3139
                        }
3140
                    } else {
314186×
                        similarity(o, &e.content)
3142
                    }
3143
                }
314410×
                (None, Some(b)) if e.blob.unwrap_or_else(|| Repo::blob_ref(&e.content)) == b => 100,
31457×
                _ => 0,
3146
            };
314796×
            if score >= RENAME_THRESHOLD {
314843×
                scored.push((score, ri, ai));
314953×
            }
3150
        }
3151
    }
315262×
    scored.sort_by(|a, b| {
31539×
        b.0.cmp(&a.0)
31549×
            .then(removed[a.1].0.cmp(removed[b.1].0))
31559×
            .then(added[a.2].0.cmp(added[b.2].0))
31569×
    });
315762×
    let mut used_r = vec![false; removed.len()];
315862×
    let mut used_a = vec![false; added.len()];
315962×
    let mut out = Vec::new();
316062×
    for (_, ri, ai) in scored {
316143×
        if used_r[ri] || used_a[ai] {
31626×
            continue;
316337×
        }
316437×
        used_r[ri] = true;
316537×
        used_a[ai] = true;
316637×
        out.push((removed[ri].0.clone(), added[ai].0.clone()));
3167
    }
316862×
    out
31692127×
}
3170
3171
/// Percentage of the larger file's bytes found in lines the two share
3172
/// (multiset intersection of lines), like Git's similarity index.
317390×
pub fn similarity(a: &[u8], b: &[u8]) -> u32 {
317490×
    if a == b {
317525×
        return 100;
317665×
    }
317765×
    if a.is_empty() || b.is_empty() {
31784×
        return 0;
317961×
    }
318061×
    let mut counts: HashMap<&[u8], usize> = HashMap::new();
3181117×
    for l in split_lines(a) {
3182117×
        *counts.entry(l).or_default() += 1;
3183117×
    }
318461×
    let mut shared = 0usize;
3185113×
    for l in split_lines(b) {
3186113×
        if let Some(n) = counts.get_mut(l) {
318744×
            if *n > 0 {
318844×
                *n -= 1;
318944×
                shared += l.len();
319044×
            }
319169×
        }
3192
    }
319361×
    (shared * 100 / a.len().max(b.len())) as u32
319490×
}
3195
3196
#[cfg(test)]
3197
mod join_tests {
3198
    use super::*;
3199
3200
    #[test]
32011×
    fn missing_from_finds_what_the_other_lacks() {
32021×
        let a: BTreeMap<String, u8> = [("a", 1), ("b", 2), ("c/d", 3), ("e", 4)]
32031×
            .into_iter()
32044×
            .map(|(k, v)| (k.to_string(), v))
32051×
            .collect();
32061×
        let b: BTreeMap<String, ()> = [("0", ()), ("b", ()), ("c", ()), ("e", ())]
32071×
            .into_iter()
32084×
            .map(|(k, v)| (k.to_string(), v))
32091×
            .collect();
32101×
        let got: Vec<&str> = missing_from(&a, &b)
32111×
            .iter()
32122×
            .map(|(k, _)| k.as_str())
32131×
            .collect();
32141×
        assert_eq!(got, vec!["a", "c/d"]);
32151×
    }
3216
3217
    #[test]
32181×
    fn join_pairs_every_key_in_order() {
32191×
        let a: BTreeMap<String, u8> = [("a", 1), ("b/c", 2), ("d", 3)]
32201×
            .into_iter()
32213×
            .map(|(k, v)| (k.to_string(), v))
32221×
            .collect();
32231×
        let b: BTreeMap<String, char> = [("b", 'x'), ("b/c", 'y'), ("e", 'z')]
32241×
            .into_iter()
32253×
            .map(|(k, v)| (k.to_string(), v))
32261×
            .collect();
32271×
        let got: Vec<(String, Option<u8>, Option<char>)> = join(&a, &b)
32285×
            .map(|(k, x, y)| (k.clone(), x.copied(), y.copied()))
32291×
            .collect();
32301×
        let want = vec![
32311×
            ("a".to_string(), Some(1), None),
32321×
            ("b".to_string(), None, Some('x')),
32331×
            ("b/c".to_string(), Some(2), Some('y')),
32341×
            ("d".to_string(), Some(3), None),
32351×
            ("e".to_string(), None, Some('z')),
3236
        ];
32371×
        assert_eq!(got, want);
32381×
    }
3239
}