OXYGENHUB

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

2325 of 2555 lines run, 307 of 407 functions · run #342 on proposal/125 · 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).
2133×
pub fn has_conflict_markers(content: &[u8]) -> bool {
2293×
    split_lines(content).iter().any(|l| {
2393×
        l.starts_with(b"<<<<<<< oxy conflict")
2488×
            || l.starts_with(b"======= oxy conflict")
2588×
            || l.starts_with(b">>>>>>> oxy conflict")
2693×
    })
2733×
}
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
8123189×
pub fn is_binary(content: &[u8]) -> bool {
8223189×
    content[..content.len().min(BINARY_SNIFF)].contains(&0)
8323189×
}
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.
1051370×
    fn platform_normalize(&self, entries: &mut BTreeMap<String, FsEntry>, base: &Snapshot) {
1061370×
        let p = self.platform;
1071370×
        if p.exec_bits && p.symlinks {
1081368×
            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
        }
1221370×
    }
123
124
    /// Like `build_against`, for files given in memory (imports).
1251101×
    pub(crate) fn build_from_entries(
1261101×
        &self,
1271101×
        base: &State,
1281101×
        base_snapshot: &Snapshot,
1291101×
        reuse: HashMap<String, (NodeId, NodeKind)>,
1301101×
        fs_entries: &BTreeMap<String, FsEntry>,
1311101×
    ) -> Result<BuiltChange> {
1321101×
        self.build_from_entries_resolving(base, base_snapshot, reuse, fs_entries, &HashSet::new())
1331101×
    }
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.
1401116×
    pub(crate) fn build_from_entries_resolving(
1411116×
        &self,
1421116×
        base: &State,
1431116×
        base_snapshot: &Snapshot,
1441116×
        reuse: HashMap<String, (NodeId, NodeKind)>,
1451116×
        fs_entries: &BTreeMap<String, FsEntry>,
1461116×
        resolve: &HashSet<String>,
1471116×
    ) -> Result<BuiltChange> {
1481116×
        self.build_from_entries_with(
1491116×
            base,
1501116×
            base_snapshot,
1511116×
            reuse,
1521116×
            fs_entries,
1531116×
            resolve,
1541116×
            Scope::default(),
155
        )
1561116×
    }
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.
192919×
    fn build_changed_only(
193919×
        &self,
194919×
        base: &State,
195919×
        base_snapshot: &Snapshot,
196919×
        reuse: HashMap<String, (NodeId, NodeKind)>,
197919×
        fs_entries: &BTreeMap<String, FsEntry>,
198919×
    ) -> Result<BuiltChange> {
199919×
        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.
202919×
        let changed: BTreeMap<String, FsEntry> = join(fs_entries, &base_snapshot.files)
20311128×
            .filter_map(|(p, e, f)| {
20411128×
                let e = e?;
20510995×
                (!e.unchanged || f.is_none_or(|f| f.kind != e.kind || f.mode.exec != e.exec))
20610995×
                    .then(|| (p.clone(), e.clone()))
20711128×
            })
208919×
            .collect();
209919×
        let mut files: BTreeMap<String, crate::state::FileState> = BTreeMap::new();
2106766×
        for p in changed.keys() {
2116766×
            if let Some(f) = base_snapshot.files.get(p) {
2123724×
                files.insert(p.clone(), f.clone());
2133724×
            }
214
        }
215
        // Paths the base has and the disk does not.
216919×
        let gone = join(&base_snapshot.files, fs_entries)
21711128×
            .filter_map(|(p, f, e)| (e.is_none()).then_some((p, f?)));
218919×
        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
        }
235919×
        let part = Snapshot {
236919×
            tree: base_snapshot.tree.clone(),
237919×
            files,
238919×
            unrendered: BTreeSet::new(),
239919×
        };
240919×
        drop(pick);
241919×
        let _build = crate::timing::phase("snapshot:   of which building the change");
242
        // Whether anything on disk is under `dir`.
243919×
        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×
        };
250919×
        self.build_from_entries_with(
251919×
            base,
252919×
            &part,
253919×
            reuse,
254919×
            &changed,
255919×
            &HashSet::new(),
256919×
            Scope {
257919×
                seed: None,
258919×
                dir_needed: Some(&dir_needed),
259919×
            },
260
        )
261919×
    }
262
2632123×
    fn build_from_entries_with(
2642123×
        &self,
2652123×
        base: &State,
2662123×
        base_snapshot: &Snapshot,
2672123×
        reuse: HashMap<String, (NodeId, NodeKind)>,
2682123×
        fs_entries: &BTreeMap<String, FsEntry>,
2692123×
        resolve: &HashSet<String>,
2702123×
        scope: Scope,
2712123×
    ) -> Result<BuiltChange> {
2722123×
        let Scope { seed, dir_needed } = scope;
2732123×
        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.
2762123×
        let attrs = crate::attributes::Attributes::from_files(
2772123×
            fs_entries
2782123×
                .iter()
27918970×
                .filter(|(p, _)| p.as_str() == ".oxyattributes" || p.ends_with("/.oxyattributes"))
2802123×
                .map(|(p, e)| (p.as_str(), e.content.as_slice())),
281
        );
2822123×
        let mut b = ChangeBuilder::new(base, base_snapshot, reuse).with_attributes(attrs);
2832123×
        b.resolve = resolve.clone();
2842123×
        b.node_seed = seed;
2852123×
        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.
2892123×
        let renames = detect_renames(base_snapshot, fs_entries, |p| self.in_scope(p));
2902123×
        let renamed_from: HashMap<&str, &str> = renames
2912123×
            .iter()
2922123×
            .map(|(old, new)| (new.as_str(), old.as_str()))
2932123×
            .collect();
2942123×
        let renamed_to: HashMap<&str, &str> = renames
2952123×
            .iter()
2962123×
            .map(|(old, new)| (old.as_str(), new.as_str()))
2972123×
            .collect();
2982123×
        laps.lap("build: renames");
2992123×
        b.diff_in_parallel(fs_entries);
3002123×
        laps.lap("build: diffs");
30118970×
        for (path, fs_entry) in fs_entries {
30218970×
            match base_snapshot.files.get(path) {
3036144×
                None => match renamed_from.get(path.as_str()) {
30436×
                    Some(old) => {
30536×
                        b.move_path(self, old, path, fs_entry, &base_snapshot.files[*old])?
306
                    }
3076108×
                    None => b.add_path(self, path, fs_entry)?,
308
                },
30912826×
                Some(expected) => b.update_path(self, path, fs_entry, expected)?,
310
            }
311
        }
3122123×
        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.
3152123×
        let mut needed_dirs: HashSet<&str> = HashSet::new();
31618983×
        fn parents_of<'a>(p: &'a str, set: &mut HashSet<&'a str>) {
31718983×
            let mut end = p.len();
31819629×
            while let Some(i) = p[..end].rfind('/') {
31915428×
                if !set.insert(&p[..i]) {
32014782×
                    break;
321646×
                }
322646×
                end = i;
323
            }
32418983×
        }
32518970×
        for p in fs_entries.keys() {
32618970×
            parents_of(p, &mut needed_dirs);
32718970×
        }
32813391×
        for p in base_snapshot.files.keys() {
32913391×
            if !self.in_scope(p) {
33013×
                parents_of(p, &mut needed_dirs);
33113378×
            }
332
        }
33313391×
        for (path, expected) in &base_snapshot.files {
33413391×
            if fs_entries.contains_key(path)
335565×
                || !self.in_scope(path)
336552×
                || renamed_to.contains_key(path.as_str())
337
            {
33812875×
                continue;
339516×
            }
340516×
            let still_needed = expected.kind == NodeKind::Dir
341405×
                && match dir_needed {
34221×
                    Some(f) => f(path),
343384×
                    None => needed_dirs.contains(path.as_str()),
344
                };
345516×
            if !still_needed {
346135×
                b.remove_path(path, expected);
347381×
            }
348
        }
3492123×
        laps.lap("build: removals");
3502123×
        if seed.is_some() {
35188×
            b.retire_stray_placements();
3522035×
        }
3532123×
        b.retire_unified();
3542123×
        laps.lap("build: stray placements");
3552123×
        let mut statuses = b.statuses;
3565702×
        statuses.sort_by(|a, b| a.path.cmp(&b.path));
3572123×
        Ok(BuiltChange {
3582123×
            tree_ops: b.tree_ops,
3592123×
            edits: b.edits,
3602123×
            contributors: b.contributors.into_iter().collect(),
3612123×
            resolves: b.resolves,
3622123×
            statuses,
3632123×
            blobs: b.blobs,
3642123×
        })
3652123×
    }
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.
370732×
    pub(crate) fn store_signed(&self, change: &Change) -> Result<ChangeHash> {
371732×
        let ours = change.author == self.author();
372732×
        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");
374731×
        }
375731×
        let storing = crate::timing::phase("store: the change");
376731×
        let hash = self.store.put_change(change)?;
377731×
        drop(storing);
378731×
        if self.config.sign_changes && ours {
37941×
            let _t = crate::timing::phase("store: sign it");
38041×
            self.sign_change(&hash)?;
381690×
        }
382731×
        Ok(hash)
383732×
    }
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.
387449×
    pub fn snapshot(&self, command: &str) -> Result<SnapshotResult> {
388449×
        self.snapshot_as(command, false, false)
389449×
    }
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.
399430×
    pub fn snapshot_status(&self, command: &str) -> Result<SnapshotResult> {
400430×
        self.snapshot_as(command, true, false)
401430×
    }
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.
4101371×
    fn snapshot_as(
4111371×
        &self,
4121371×
        command: &str,
4131371×
        partial: bool,
4141371×
        for_commit: bool,
4151371×
    ) -> Result<SnapshotResult> {
4161371×
        let _lock = self.lock_snapshot()?;
4171371×
        let batch = self.store.begin_batch()?;
4181371×
        let result = self.snapshot_locked(command, partial, for_commit);
4191371×
        batch.finish()?;
4201371×
        result
4211371×
    }
422
4231371×
    fn snapshot_locked(
4241371×
        &self,
4251371×
        command: &str,
4261371×
        partial: bool,
4271371×
        for_commit: bool,
4281371×
    ) -> Result<SnapshotResult> {
4291371×
        let _all = crate::timing::phase("snapshot");
4301371×
        let (op_ref, op) = self.head_op()?;
4311371×
        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.
4341369×
        let mut base = {
4351369×
            let _t = crate::timing::phase("snapshot: load base history");
4361369×
            self.load_state_indexed(&old_wc.deps)?
437
        };
4381369×
        let view = {
4391369×
            let _t = crate::timing::phase("snapshot: tree view");
4401369×
            self.tree_view(&mut base)?
441
        };
4421369×
        let manifest = {
4431369×
            let _t = crate::timing::phase("snapshot: read manifest");
4441369×
            self.read_manifest()?.map(|(_, _, m)| m)
445
        };
4461369×
        let tracked: BTreeMap<String, (NodeKind, Option<ObjectRef>)> = {
4471369×
            let _t = crate::timing::phase("snapshot: tracked paths");
448
            // In the view's path order, so the map is built without searching.
4491369×
            view.entries
4501369×
                .iter()
4519560×
                .filter(|(_, e)| e.kind != NodeKind::Dir)
4529181×
                .map(|(p, e)| {
4539181×
                    let blob = if e.kind != NodeKind::File || e.mode.opaque {
454156×
                        base.live_blobs(&e.node).first().copied()
455
                    } else {
4569025×
                        None
457
                    };
4589181×
                    (p.clone(), (e.kind, blob))
4599181×
                })
4601369×
                .collect()
461
        };
462
        // A text file's graph key, worked out when the walk asks for it.
46312228×
        let key_of = |p: &str| -> Option<[u8; 32]> {
46412228×
            let e = view.entries.get(p)?;
4659066×
            if e.kind != NodeKind::File || e.mode.opaque {
466124×
                return None;
4678942×
            }
4688942×
            base.graph_key(&e.node)
46912228×
        };
4701368×
        let mut fs_entries = {
4711369×
            let _t = crate::timing::phase("snapshot: read working copy");
4721369×
            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.
4761368×
        let keys: HashMap<String, [u8; 32]> = fs_entries
4771368×
            .iter()
47812266×
            .filter(|(_, e)| !e.unchanged && e.kind == NodeKind::File)
4797987×
            .filter_map(|(p, _)| Some((p.clone(), key_of(p)?)))
4801368×
            .collect();
4811368×
        let base_snapshot = {
4821368×
            let _t = crate::timing::phase("snapshot: load and render base");
4831368×
            if partial {
484922×
                let sets = crate::timing::phase("snapshot:   of which choosing graphs");
485
                // Every file but those on disk known unchanged.
486922×
                let need: Vec<(&str, NodeId)> = join(&view.entries, &fs_entries)
48711143×
                    .filter_map(|(p, v, f)| {
48811143×
                        let v = v?;
4898100×
                        (v.kind == NodeKind::File && !f.is_some_and(|f| f.unchanged))
4908100×
                            .then_some((p.as_str(), v.node))
49111143×
                    })
492922×
                    .collect();
493922×
                let render: std::collections::HashSet<&str> =
494922×
                    need.iter().map(|(p, _)| *p).collect();
495922×
                let need: Vec<NodeId> = need.iter().map(|(_, n)| *n).collect();
496922×
                drop(sets);
497
                {
498922×
                    let _t = crate::timing::phase("snapshot:   of which building graphs");
499922×
                    self.load_graphs_of(&mut base, &need)?;
500
                }
501922×
                let _t = crate::timing::phase("snapshot:   of which rendering");
502922×
                base.materialize_only(&render)
503
            } else {
504446×
                self.load_all_graphs(&mut base)?;
505446×
                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).
5111368×
        let reuse = added_node_paths(&old_wc, &base_snapshot);
5121368×
        self.platform_normalize(&mut fs_entries, &base_snapshot);
5131368×
        let built = {
5141368×
            let _t = crate::timing::phase("snapshot: diff against base");
5151368×
            if partial && self.config.sparse_paths.is_empty() {
516
                #[cfg(test)]
517646×
                let full =
518646×
                    self.build_from_entries(&base, &base_snapshot, reuse.clone(), &fs_entries)?;
519919×
                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.
5241292×
                    let norm = |b: &BuiltChange| {
5251292×
                        let text = format!("{:?} {:?} {:?}", b.tree_ops, b.edits, b.statuses);
5261292×
                        let mut seen: Vec<String> = Vec::new();
5271292×
                        let mut out = String::new();
5281292×
                        let mut rest = text.as_str();
52920290×
                        while let Some(i) = rest.find("NodeId(") {
53018998×
                            out.push_str(&rest[..i]);
53118998×
                            let end = i + rest[i..].find(')').unwrap() + 1;
53218998×
                            let id = rest[i..end].to_string();
5339046216×
                            let n = seen.iter().position(|x| *x == id).unwrap_or_else(|| {
5347232×
                                seen.push(id);
5357232×
                                seen.len() - 1
5367232×
                            });
53718998×
                            out.push_str(&format!("N{n}"));
53818998×
                            rest = &rest[end..];
539
                        }
5401292×
                        out.push_str(rest);
5411292×
                        out
5421292×
                    };
543646×
                    assert_eq!(
544646×
                        norm(&built),
545646×
                        norm(&full),
546
                        "a changed-only build is the full one"
547
                    );
548
                }
549919×
                built
550
            } else {
551449×
                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
        {
5573820×
            let changed: HashSet<&str> = built.statuses.iter().map(|s| s.path.as_str()).collect();
55812266×
            for (p, e) in fs_entries.iter_mut() {
55912266×
                if e.unchanged || e.kind != NodeKind::File || changed.contains(p.as_str()) {
5607996×
                    continue;
5614270×
                }
5624270×
                e.graph_key = match base_snapshot.files.get(p).map(|f| &f.content) {
563
                    Some(FileContent::Text {
5644158×
                        bytes,
5654158×
                        materialized,
5664158×
                    }) if !materialized.is_conflicted() && *bytes == *e.content => {
5674152×
                        keys.get(p).copied()
568
                    }
569118×
                    _ => None,
570
                };
571
            }
572
        }
573
5741368×
        let mut wc = Change {
5751368×
            version: crate::objects::CHANGE_VERSION,
5761368×
            change_id: old_wc.change_id,
5771368×
            deps: vec![],
5781368×
            author: self.author(),
5791368×
            hlc: old_wc.hlc,
5801368×
            message: old_wc.message.clone(),
5811368×
            tree_ops: built.tree_ops,
5821368×
            edits: built.edits,
5831368×
            kind: ChangeKind::WorkingCopy,
5841368×
        };
5851368×
        let base_heads = base.maximal(&old_wc.deps);
5861368×
        let mut deps: BTreeSet<ChangeHash> = base_heads.into_iter().collect();
5871368×
        deps.extend(referenced_changes(&wc, &base));
5881368×
        deps.extend(built.contributors.iter().copied());
5891368×
        wc.deps = deps.into_iter().collect();
5901368×
        wc.normalize();
5911368×
        let resolves = built.resolves;
5921368×
        let contributors = built.contributors;
5931368×
        let statuses = built.statuses;
594
        // Empty snapshot: hash the candidate before storing; only record an op on change.
5951368×
        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.
6021368×
        let (new_hash, changed, encoded) = if for_commit {
603492×
            (old_hash, true, Vec::new())
604
        } else {
605876×
            let encoded = wc.encode_streaming(|batch| self.store.put_texts(&batch))?;
606876×
            let new_hash = crate::hash::hash_object(crate::hash::ObjectType::Change, &encoded);
607876×
            (new_hash, new_hash != old_hash, encoded)
608
        };
6091368×
        if changed && !for_commit {
610296×
            self.store.put(crate::hash::ObjectType::Change, &encoded)?;
611296×
            let mut view = op.view.clone();
612296×
            view.workspaces.insert(self.workspace, new_hash);
613296×
            self.record_op(&[op_ref], &format!("{command}{SNAPSHOT_SUFFIX}"), view)?;
6141072×
        }
6151368×
        drop(record);
616
        // The prompt compares against this without recording anything.
6171368×
        let _t = crate::timing::phase("snapshot: write manifest");
6181368×
        let conflicted = base_snapshot.is_conflicted();
6191368×
        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.
6241368×
        let worth = match self.read_manifest()? {
625492×
            _ if for_commit => true,
626329×
            None => true,
627547×
            Some((c, u, m)) => {
628547×
                c != conflicted
629547×
                    || 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
        };
6621368×
        let attributes = crate::attributes::Attributes::from_files(
6631368×
            fs_entries
6641368×
                .iter()
66512266×
                .filter(|(p, _)| is_attributes(p))
6661368×
                .map(|(p, e)| (p.as_str(), e.content.as_slice())),
667
        );
6681368×
        let mut manifest = None;
6691368×
        if for_commit {
670492×
            manifest = Some(PendingManifest {
671492×
                entries: fs_entries,
672492×
                blobs: built.blobs.clone(),
673492×
                dirs: self.walked_dirs.take(),
674492×
                written: super::prompt::now_ns(),
675492×
            });
676492×
        } else {
677876×
            if worth {
678830×
                self.write_manifest_entries(conflicted, uncommitted, &fs_entries, &built.blobs)?;
67946×
            }
680876×
            self.write_status_cache((uncommitted && !conflicted).then_some(&new_hash), &statuses);
681
        }
6821368×
        Ok(SnapshotResult {
6831368×
            wc_hash: new_hash,
6841368×
            wc,
6851368×
            base,
6861368×
            base_snapshot,
6871368×
            statuses,
6881368×
            changed,
6891368×
            resolves,
6901368×
            contributors,
6911368×
            attributes,
6921368×
            untracked_nested: self.untracked_nested.borrow().clone(),
6931368×
            manifest,
6941368×
        })
6951371×
    }
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).
807667×
    pub fn commit(&self, message: &str, extra_deps: &[ChangeHash]) -> Result<ChangeHash> {
808667×
        self.commit_selection(message, extra_deps, &Selection::All)
809667×
    }
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.
829686×
    fn committed_graph_keys(
830686×
        &self,
831686×
        st: &State,
832686×
        paths: &[String],
833686×
        attrs: &crate::attributes::Attributes,
834686×
    ) -> HashMap<String, [u8; 32]> {
835686×
        let _t = crate::timing::phase("commit: graph keys");
836686×
        let view = st.view();
837686×
        paths
838686×
            .iter()
8393537×
            .filter_map(|p| {
8403537×
                let e = view.entries.get(p)?;
8413492×
                (e.kind == NodeKind::File && !e.mode.opaque && attrs.lookup(p).eol.is_none())
8423492×
                    .then_some(())?;
8433440×
                Some((p.clone(), st.graph_key(&e.node)?))
8443537×
            })
845686×
            .collect()
846686×
    }
847
848674×
    pub fn commit_selection(
849674×
        &self,
850674×
        message: &str,
851674×
        extra_deps: &[ChangeHash],
852674×
        selection: &Selection,
853674×
    ) -> Result<ChangeHash> {
854674×
        Ok(self
855674×
            .commit_selection_partial(message, extra_deps, selection)?
856
            .0)
857674×
    }
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.
862703×
    pub fn commit_selection_partial(
863703×
        &self,
864703×
        message: &str,
865703×
        extra_deps: &[ChangeHash],
866703×
        selection: &Selection,
867703×
    ) -> 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).
870703×
        let batch = self.store.begin_batch()?;
871703×
        let out = self.commit_selection_batched(message, extra_deps, selection);
872703×
        batch.finish()?;
873703×
        out
874703×
    }
875
876
    /// Write the manifest a commit's snapshot left to the commit, with the
877
    /// graph keys `keys` sets.
878481×
    fn write_pending_manifest(
879481×
        &self,
880481×
        mut m: PendingManifest,
881481×
        conflicted: bool,
882481×
        keys: HashMap<String, [u8; 32]>,
883481×
    ) -> Result<()> {
8842870×
        for (path, k) in keys {
8852870×
            if let Some(e) = m.entries.get_mut(&path) {
8862870×
                e.graph_key = Some(k);
8872870×
            }
888
        }
889481×
        self.write_manifest_entries_as_of(
890481×
            conflicted,
891
            false,
892481×
            &m.entries,
893481×
            &m.blobs,
894481×
            m.written,
895481×
            m.dirs.unwrap_or_default(),
896
        )
897481×
    }
898
899703×
    fn commit_selection_batched(
900703×
        &self,
901703×
        message: &str,
902703×
        extra_deps: &[ChangeHash],
903703×
        selection: &Selection,
904703×
    ) -> Result<(ChangeHash, bool)> {
905703×
        let _wc = self.lock_working_copy()?;
906703×
        let mut snap = match self.snapshot_from_cache()? {
907211×
            Some(snap) => snap,
908492×
            None => self.snapshot_as("oxy commit", true, true)?,
909
        };
910703×
        let pending = snap.manifest.take();
911703×
        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");
917699×
        }
918699×
        if let Some(s) = snap
919699×
            .statuses
920699×
            .iter()
9213564×
            .find(|s| s.status == ChangeStatus::ConflictEdited)
922
        {
9230×
            return fail(format!("{} still contains conflict markers", s.path));
924699×
        }
925699×
        if message.trim().is_empty() {
9260×
            return fail("a commit message is required");
927699×
        }
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).
931699×
        let wc_refs = referenced_changes(&snap.wc, &snap.base);
9323564×
        let changed_paths: Vec<String> = snap.statuses.iter().map(|s| s.path.clone()).collect();
933699×
        let (tree_ops, edits, partial) = match selection {
934686×
            Selection::All => (
935686×
                std::mem::take(&mut snap.wc.tree_ops),
936686×
                std::mem::take(&mut snap.wc.edits),
937686×
                false,
938686×
            ),
9398×
            Selection::Paths(paths) => {
9408×
                let (o, e) = select_paths(&snap.wc, &snap.base_snapshot, paths);
9418×
                let partial = o.len() != snap.wc.tree_ops.len() || e.len() != snap.wc.edits.len();
9428×
                (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
        };
950699×
        if tree_ops.is_empty() && edits.is_empty() {
9510×
            return fail("nothing selected to commit");
952699×
        }
953
        // A resolution may leave other work uncommitted (oxygen#118), but
954
        // takes every file it resolves, whole.
955699×
        if partial && snap.resolves {
9562×
            let resolved = snap
9572×
                .statuses
9582×
                .iter()
9594×
                .filter(|s| s.status == ChangeStatus::Resolved)
9602×
                .map(|s| s.path.as_str());
9612×
            let missing: Vec<&str> = match selection {
9622×
                Selection::Paths(paths) => resolved
9632×
                    .filter(|p| {
9642×
                        !paths.iter().any(|x| {
9652×
                            p == x || p.starts_with(&format!("{}/", x.trim_end_matches('/')))
9662×
                        })
9672×
                    })
9682×
                    .collect(),
9690×
                _ => resolved.collect(),
970
            };
9712×
            if !missing.is_empty() {
9721×
                return fail(format!(
973
                    "a conflict resolution takes every file it resolves, whole: commit by paths, including {}",
9741×
                    missing.join(", ")
975
                ));
9761×
            }
977697×
        }
978
        // pre-commit hook: may veto.
979698×
        self.run_hook(
980698×
            "pre-commit",
981698×
            &format!(
982
                "{{\"event\":\"pre-commit\",\"message\":{},\"paths\":{}}}",
983698×
                json_str(message),
9843562×
                json_array(snap.statuses.iter().map(|s| format!(
985
                    "{{\"path\":{},\"status\":{}}}",
9863562×
                    json_str(&s.path),
9873562×
                    json_str(&format!("{:?}", s.status))
988
                )))
989
            ),
9901×
        )?;
991697×
        let (op_ref, op) = self.head_op()?;
992697×
        let mut deps: BTreeSet<ChangeHash> = wc_refs;
993
        // semantic-deps hook: may add explicit dependencies (spec §8.1).
994697×
        if self.config.semantic_deps {
9951×
            let touched: Vec<String> = snap.statuses.iter().map(|s| s.path.clone()).collect();
9961×
            let by_node = snap.base_snapshot.tree.by_node();
9971×
            let mut candidates: Vec<(ChangeId, ChangeHash, Vec<String>)> = Vec::new();
9981×
            let mut seen: BTreeSet<ChangeHash> = BTreeSet::new();
9992×
            for h in deps.iter().chain(snap.base.maximal(&snap.wc.deps).iter()) {
10002×
                if !seen.insert(*h) {
10010×
                    continue;
10022×
                }
10032×
                let c = self.store.get_change(h)?;
10042×
                let mut paths: BTreeSet<String> = BTreeSet::new();
10056×
                for n in c
10062×
                    .tree_ops
10072×
                    .iter()
10083×
                    .map(|o| o.node())
10093×
                    .chain(c.edits.iter().map(|e| e.node()))
1010
                {
10116×
                    if let Some(e) = by_node.get(&n) {
10126×
                        paths.insert(e.path.clone());
10136×
                    }
1014
                }
10152×
                candidates.push((c.change_id, *h, paths.into_iter().collect()));
1016
            }
10171×
            for d in self.semantic_deps(&snap.wc.change_id, &touched, &candidates)? {
10181×
                if snap.base.contains(&d) {
10191×
                    deps.insert(d);
10201×
                }
1021
            }
1022696×
        }
1023
        // A resolution depends on every change that contributed to the
1024
        // conflict (spec §8.1). Tree and opaque conflicts are resolved through
1025
        // ordinary operations whose references already cover the contributors.
1026697×
        deps.extend(snap.contributors.iter().copied());
1027697×
        for d in extra_deps {
10284×
            if !snap.base.contains(d) {
10290×
                return fail(format!(
1030
                    "--depends-on {d}: not in the working copy's base state"
1031
                ));
10324×
            }
10334×
            deps.insert(*d);
1034
        }
1035697×
        let mut change = Change {
1036
            version: crate::objects::CHANGE_VERSION,
1037697×
            change_id: if partial {
103810×
                ChangeId::random()
1039
            } else {
1040687×
                snap.wc.change_id
1041
            },
1042697×
            deps: vec![],
1043697×
            author: self.author(),
1044697×
            hlc: Hlc::now(),
1045697×
            message: message.trim_end().to_string(),
1046697×
            tree_ops,
1047697×
            edits,
1048697×
            kind: if snap.resolves {
10498×
                ChangeKind::Resolution
1050
            } else {
1051689×
                ChangeKind::Normal
1052
            },
1053
        };
1054697×
        if partial {
1055
            // Dependencies come from what the selected part references, not
1056
            // from the whole working copy.
105710×
            deps = referenced_changes(&change, &snap.base);
105810×
            for d in extra_deps {
10591×
                deps.insert(*d);
10601×
            }
1061687×
        }
1062697×
        change.deps = deps.into_iter().collect();
1063697×
        change.normalize();
1064697×
        let signing = crate::timing::phase("commit: sign and store");
1065697×
        let hash = self.store_signed(&change)?;
1066696×
        drop(signing);
1067696×
        let extending = crate::timing::phase("commit: extend the state");
1068
1069
        // New bookmark heads: maximal elements of old heads plus the new change.
1070
        // The working copy continues on its own base plus the new change, which
1071
        // is exactly what the files on disk contain; the bookmark may hold
1072
        // other heads (and conflicts) the working copy has not checked out.
1073696×
        let old_heads = self.heads_of(&op.view, &self.config.bookmark)?;
1074696×
        let old_base = snap.base.maximal(&snap.wc.deps);
1075696×
        let mut all: Vec<ChangeHash> = old_heads.clone();
1076696×
        all.extend(old_base.iter().copied());
1077696×
        all.push(hash);
1078
        // The snapshot already loaded the working copy's base; when that also
1079
        // holds every bookmark head, it is the state to extend.
1080696×
        let mut st = if old_heads.iter().all(|h| snap.base.contains(h)) {
1081659×
            snap.base
1082
        } else {
108337×
            self.load_state(&all)?
1084
        };
1085696×
        st.add_hashed(hash, change)?;
1086696×
        let mut with_new = old_heads.clone();
1087696×
        with_new.push(hash);
1088696×
        let new_heads = st.maximal(&with_new);
1089
        // Automatic checkpoint once enough changes accumulated (spec §11).
1090696×
        let since = self
1091696×
            .latest_checkpoint(&self.config.bookmark)?
1092696×
            .map(|(_, cp)| cp.count)
1093696×
            .unwrap_or(0);
1094696×
        if self.config.checkpoint_interval > 0
1095696×
            && (st.len() as u64).saturating_sub(since) >= self.config.checkpoint_interval
1096
        {
10972×
            let cp_state = self.load_state_full(&new_heads)?;
10982×
            self.write_checkpoint(&self.config.bookmark, &cp_state, &new_heads)?;
1099694×
        }
1100696×
        let mut wc_base = old_base.clone();
1101696×
        wc_base.push(hash);
1102696×
        let wc_base = st.maximal(&wc_base);
1103696×
        drop(extending);
1104
1105
        // The graph keys of the files as they now are, from the state the
1106
        // commit just extended: a file whose graph it built has none, and
1107
        // is read by the next snapshot; a key the next base does not share
1108
        // (the bookmark held other heads) is simply not trusted then.
1109696×
        let keying = crate::timing::phase("commit: graph keys of the files");
1110696×
        let committed_keys =
1111696×
            (!partial).then(|| self.committed_graph_keys(&st, &changed_paths, &snap.attributes));
1112696×
        drop(keying);
1113696×
        let recording = crate::timing::phase("commit: record");
1114696×
        let wc = self.new_working_copy(wc_base, "");
1115696×
        let wc_hash = self.store.put_change(&wc)?;
1116696×
        let mut view = op.view.clone();
1117696×
        view.bookmarks.insert(
1118696×
            self.config.bookmark.clone(),
1119696×
            self.store.put_state(&StateObject::new(new_heads))?,
1120
        );
1121696×
        view.workspaces.insert(self.workspace, wc_hash);
1122696×
        self.record_op(&[op_ref], &format!("oxy commit -m {message:?}"), view)?;
1123691×
        drop(recording);
1124691×
        let rewriting = crate::timing::phase("commit: manifest");
1125691×
        if partial {
112610×
            // The rest is rebuilt from disk by the next snapshot.
112710×
            self.drop_manifest();
112810×
        } else {
1129681×
            let conflicted = snap.base_snapshot.is_conflicted() && !snap.resolves;
1130
            // The files on disk are now exactly the new base's renderings:
1131
            // record their graph keys, so the next snapshot neither reads nor
1132
            // renders them (oxygen#35).
1133681×
            let keys = if conflicted {
11340×
                HashMap::new()
1135
            } else {
1136681×
                committed_keys.unwrap_or_default()
1137
            };
1138681×
            match pending {
1139477×
                Some(m) => self.write_pending_manifest(m, conflicted, keys)?,
1140204×
                None => self.rewrite_manifest(conflicted, false, &keys)?,
1141
            }
1142
        }
1143691×
        drop(rewriting);
1144691×
        let packing = crate::timing::phase("commit: autopack");
1145691×
        self.maybe_autopack()?;
1146691×
        drop(packing);
1147691×
        let _hook = crate::timing::phase("commit: hook");
1148691×
        let _ = self.run_hook(
1149691×
            "post-commit",
1150691×
            &format!(
1151691×
                "{{\"event\":\"post-commit\",\"change_id\":{},\"hash\":{},\"message\":{}}}",
1152691×
                json_str(&snap.wc.change_id.to_hex()),
1153691×
                json_str(&hash.to_hex()),
1154691×
                json_str(message)
1155691×
            ),
1156691×
        );
1157691×
        Ok((hash, partial))
1158703×
    }
1159
}
1160
1161
/// What part of the working copy a commit takes (spec §12.3).
1162
#[derive(Clone, Debug)]
1163
pub enum Selection {
1164
    All,
1165
    /// Every operation and edit on nodes under these paths.
1166
    Paths(Vec<String>),
1167
    /// Hunk indices as `Repo::hunks` numbers them; dependent hunks are added.
1168
    Hunks(Vec<usize>),
1169
}
1170
1171
/// One selectable piece of the working copy: a tree operation or an edit.
1172
#[derive(Clone, Debug)]
1173
pub struct Hunk {
1174
    pub index: usize,
1175
    pub path: String,
1176
    /// Rendered like `oxy diff`.
1177
    pub text: String,
1178
}
1179
1180
/// The tree operations and edits on nodes under `paths`, plus the
1181
/// additions of any new parent directories they need.
11828×
fn select_paths(
11838×
    wc: &Change,
11848×
    base_snapshot: &Snapshot,
11858×
    paths: &[String],
11868×
) -> (Vec<TreeOp>, Vec<Edit>) {
118727×
    let selected = |p: &str| {
118827×
        paths
118927×
            .iter()
119027×
            .any(|x| p == x || p.starts_with(&format!("{}/", x.trim_end_matches('/'))))
119127×
    };
11928×
    let by_node = base_snapshot.tree.by_node();
11938×
    let mut new_names: HashMap<NodeId, (NodeId, String, NodeKind)> = HashMap::new();
11948×
    for op in &wc.tree_ops {
1195
        if let TreeOp::AddNode {
11965×
            node,
11975×
            parent,
11985×
            name,
11995×
            kind,
1200
            ..
12016×
        } = op
12025×
        {
12035×
            new_names.insert(*node, (*parent, name.clone(), *kind));
12045×
        }
1205
    }
12068×
    let mut nodes: BTreeSet<NodeId> = BTreeSet::new();
120728×
    for n in wc
12088×
        .tree_ops
12098×
        .iter()
12108×
        .map(|o| o.node())
121122×
        .chain(wc.edits.iter().map(|e| e.node()))
1212
    {
121328×
        if path_of_node(&n, &by_node, &new_names).is_some_and(|p| selected(&p)) {
121414×
            nodes.insert(n);
121514×
        }
1216
    }
1217
    // The nodes shown as one with a selected node are retired with it.
12188×
    for (dup, shown) in &base_snapshot.tree.unified {
12191×
        if nodes.contains(shown) {
12201×
            nodes.insert(*dup);
12211×
        }
1222
    }
1223
    // New parents of selected new nodes come along.
12248×
    let mut changed = true;
122516×
    while changed {
12268×
        changed = false;
12278×
        for (n, (parent, _, _)) in &new_names {
12285×
            if nodes.contains(n) && new_names.contains_key(parent) && nodes.insert(*parent) {
12290×
                changed = true;
12305×
            }
1231
        }
1232
    }
12338×
    let ops = wc
12348×
        .tree_ops
12358×
        .iter()
12368×
        .filter(|o| nodes.contains(&o.node()))
12378×
        .cloned()
12388×
        .collect();
12398×
    let edits = wc
12408×
        .edits
12418×
        .iter()
124222×
        .filter(|e| nodes.contains(&e.node()))
12438×
        .cloned()
12448×
        .collect();
12458×
    (ops, edits)
12468×
}
1247
1248
/// The hunks `indices` name plus whatever they refer to within the working
1249
/// copy (the parent directory of an added node, the insert that introduced
1250
/// an anchor line), renumbered so the result is a well-formed change.
1251
/// The nodes `unified` shows as one with another (a base's
1252
/// [`TreeView::unified`](crate::tree::TreeView::unified)) are retired with
1253
/// any hunk of the node shown.
12546×
fn select_hunks(
12556×
    wc: &Change,
12566×
    indices: &[usize],
12576×
    unified: &BTreeMap<NodeId, NodeId>,
12586×
) -> (Vec<TreeOp>, Vec<Edit>) {
12596×
    let n_ops = wc.tree_ops.len();
12606×
    let mut ops_sel = vec![false; n_ops];
12616×
    let mut edits_sel = vec![false; wc.edits.len()];
12626×
    for &i in indices {
12635×
        if i < n_ops {
12641×
            ops_sel[i] = true;
12654×
        } else if i - n_ops < wc.edits.len() {
12664×
            edits_sel[i - n_ops] = true;
12674×
        }
1268
    }
1269
    // Atom ranges each insert introduces, per node, in the working copy's numbering.
12706×
    let mut per_node: HashMap<NodeId, u32> = HashMap::new();
12716×
    let mut insert_ranges: Vec<Option<(NodeId, u32, u32)>> = Vec::new();
127212×
    for e in &wc.edits {
127312×
        insert_ranges.push(match e {
127412×
            Edit::Insert { node, lines, .. } => {
127512×
                let start = per_node.entry(*node).or_default();
127612×
                let r = (*node, *start, *start + lines.len() as u32);
127712×
                *start += lines.len() as u32;
127812×
                Some(r)
1279
            }
12800×
            _ => None,
1281
        });
1282
    }
12836×
    let add_index: HashMap<NodeId, usize> = wc
12846×
        .tree_ops
12856×
        .iter()
12866×
        .enumerate()
128710×
        .filter_map(|(i, o)| {
128810×
            if let TreeOp::AddNode { node, .. } = o {
12899×
                Some((*node, i))
1290
            } else {
12911×
                None
1292
            }
129310×
        })
12946×
        .collect();
12956×
    let insert_for = |node: &NodeId, index: u32| -> Option<usize> {
12960×
        insert_ranges
12970×
            .iter()
12980×
            .position(|r| matches!(r, Some((n, a, b)) if n == node && *a <= index && index < *b))
12990×
    };
1300
    // Closure.
13016×
    let mut changed = true;
130215×
    while changed {
13039×
        changed = false;
130419×
        for i in 0..n_ops {
130519×
            if !ops_sel[i] {
130613×
                continue;
13076×
            }
13086×
            if let TreeOp::AddNode { node, parent, .. } = &wc.tree_ops[i] {
13096×
                if let Some(&p) = add_index.get(parent) {
13104×
                    if !ops_sel[p] {
13112×
                        ops_sel[p] = true;
13122×
                        changed = true;
13132×
                    }
13142×
                }
1315
                // A new node's content belongs with its addition: nobody
1316
                // wants an empty file committed apart from its lines.
131712×
                for (j, e) in wc.edits.iter().enumerate() {
131812×
                    if e.node() == *node && !edits_sel[j] {
13191×
                        edits_sel[j] = true;
13201×
                        changed = true;
132111×
                    }
1322
                }
13230×
            }
1324
        }
132518×
        for j in 0..wc.edits.len() {
132618×
            if !edits_sel[j] {
132710×
                continue;
13288×
            }
13298×
            let e = &wc.edits[j];
13308×
            if let Some(&a) = add_index.get(&e.node()) {
13315×
                if !ops_sel[a] {
13321×
                    ops_sel[a] = true;
13331×
                    changed = true;
13344×
                }
13353×
            }
1336
            if let Edit::Insert {
13378×
                node,
13388×
                after,
13398×
                before,
1340
                ..
13418×
            } = e
1342
            {
134316×
                for r in [after, before] {
134416×
                    if let AtomRef::Atom { change, index } = r {
13453×
                        if change.is_zero() {
13460×
                            if let Some(k) = insert_for(node, *index) {
13470×
                                if !edits_sel[k] {
13480×
                                    edits_sel[k] = true;
13490×
                                    changed = true;
13500×
                                }
13510×
                            }
13523×
                        }
135313×
                    }
1354
                }
13550×
            }
1356
        }
1357
    }
1358
    // The retirement of a node shown as one with a selected node.
13596×
    if !unified.is_empty() {
13601×
        let chosen: HashSet<NodeId> = (0..n_ops)
13612×
            .filter(|i| ops_sel[*i])
13621×
            .map(|i| wc.tree_ops[i].node())
13631×
            .chain(
13641×
                (0..wc.edits.len())
13652×
                    .filter(|j| edits_sel[*j])
13661×
                    .map(|j| wc.edits[j].node()),
1367
            )
13681×
            .collect();
13692×
        for (i, o) in wc.tree_ops.iter().enumerate() {
13702×
            if let TreeOp::RemoveNode { node, .. } = o {
13711×
                if unified.get(node).is_some_and(|s| chosen.contains(s)) {
13721×
                    ops_sel[i] = true;
13731×
                }
13741×
            }
1375
        }
13765×
    }
1377
    // Renumber self-references: old atom index → new index among selected inserts.
13786×
    let mut remap: HashMap<(NodeId, u32), u32> = HashMap::new();
13796×
    let mut new_counts: HashMap<NodeId, u32> = HashMap::new();
138012×
    for (j, r) in insert_ranges.iter().enumerate() {
138112×
        if let (true, Some((node, a, b))) = (edits_sel[j], r) {
13825×
            let next = new_counts.entry(*node).or_default();
13835×
            for old in *a..*b {
13845×
                remap.insert((*node, old), *next);
13855×
                *next += 1;
13865×
            }
13877×
        }
1388
    }
138910×
    let map_ref = |r: AtomRef, node: &NodeId| -> AtomRef {
13903×
        match r {
13913×
            AtomRef::Atom { change, index } if change.is_zero() => AtomRef::Atom {
13920×
                change,
13930×
                index: remap.get(&(*node, index)).copied().unwrap_or(index),
13940×
            },
139510×
            other => other,
1396
        }
139710×
    };
13986×
    let ops = wc
13996×
        .tree_ops
14006×
        .iter()
14016×
        .enumerate()
140210×
        .filter(|(i, _)| ops_sel[*i])
14036×
        .map(|(_, o)| o.clone())
14046×
        .collect();
14056×
    let edits = wc
14066×
        .edits
14076×
        .iter()
14086×
        .enumerate()
140912×
        .filter(|(j, _)| edits_sel[*j])
14106×
        .map(|(_, e)| match e {
1411
            Edit::Insert {
14125×
                node,
14135×
                after,
14145×
                before,
14155×
                lines,
14165×
            } => Edit::Insert {
14175×
                node: *node,
14185×
                after: map_ref(*after, node),
14195×
                before: map_ref(*before, node),
14205×
                lines: lines.clone(),
14215×
            },
14220×
            other => other.clone(),
14235×
        })
14246×
        .collect();
14256×
    (ops, edits)
14266×
}
1427
1428
/// Render each tree operation and edit of `change` on its own, numbered.
14298×
pub fn render_hunks(change: &Change, base: &State, base_snapshot: &Snapshot) -> Vec<Hunk> {
14308×
    let by_node = base_snapshot.tree.by_node();
14318×
    let mut new_names: HashMap<NodeId, (NodeId, String, NodeKind)> = HashMap::new();
143210×
    for op in &change.tree_ops {
1433
        if let TreeOp::AddNode {
14349×
            node,
14359×
            parent,
14369×
            name,
14379×
            kind,
1438
            ..
143910×
        } = op
14409×
        {
14419×
            new_names.insert(*node, (*parent, name.clone(), *kind));
14429×
        }
1443
    }
14448×
    let mut out = Vec::new();
144510×
    for (i, op) in change.tree_ops.iter().enumerate() {
1446
        // A retired duplicate goes with the node shown: no hunk of its own.
144710×
        if is_unified_retirement(op, base_snapshot) {
14481×
            continue;
14499×
        }
14509×
        let one = Change {
14519×
            tree_ops: vec![op.clone()],
14529×
            edits: vec![],
14539×
            ..change.clone()
14549×
        };
14559×
        let path = path_of_node(&op.node(), &by_node, &new_names).unwrap_or_default();
14569×
        out.push(Hunk {
14579×
            index: i,
14589×
            path,
14599×
            text: render_change(&one, base, base_snapshot),
14609×
        });
1461
    }
146215×
    for (j, e) in change.edits.iter().enumerate() {
146315×
        let one = Change {
146415×
            tree_ops: vec![],
146515×
            edits: vec![e.clone()],
146615×
            ..change.clone()
146715×
        };
146815×
        let path = path_of_node(&e.node(), &by_node, &new_names).unwrap_or_default();
146915×
        out.push(Hunk {
147015×
            index: change.tree_ops.len() + j,
147115×
            path,
147215×
            text: render_change(&one, base, base_snapshot),
147315×
        });
147415×
    }
14758×
    out
14768×
}
1477
1478
/// One file's part of a diff, for `oxy diff --json`.
1479
#[derive(Clone, Debug)]
1480
pub struct FileDiff {
1481
    pub path: String,
1482
    /// `added`, `removed`, `modified`, `renamed`, `mode`, `replaced`.
1483
    pub kind: String,
1484
    pub hunks: Vec<DiffHunk>,
1485
    /// For renames, the previous path.
1486
    pub from: Option<String>,
1487
}
1488
1489
/// Lines inserted after `base_line` (0 = before the first line) and lines
1490
/// removed, with their base line numbers.
1491
#[derive(Clone, Debug, Default)]
1492
pub struct DiffHunk {
1493
    pub base_line: u32,
1494
    pub added: Vec<Vec<u8>>,
1495
    pub removed: Vec<(u32, Vec<u8>)>,
1496
}
1497
1498
impl Repo {
1499
    /// The content of `path` in a state: `heads`, or the working copy's base.
150027×
    pub fn file_at(&self, path: &str, heads: Option<&[ChangeHash]>) -> Result<Vec<u8>> {
1501
        // The state's history and tree, then the one file's graph: nothing
1502
        // else is built or rendered (oxygen#92).
1503
        // The working copy's base, and a state named by its heads (`-r
1504
        // main` on main), come from the workspace's state index.
150527×
        let base = if self.is_bare() {
15065×
            None
1507
        } else {
150822×
            Some(self.working_copy()?.1.deps)
1509
        };
151027×
        let same = |a: &[ChangeHash], b: &[ChangeHash]| {
15111×
            let (mut a, mut b) = (a.to_vec(), b.to_vec());
15121×
            a.sort();
15131×
            b.sort();
15141×
            a == b
15151×
        };
151627×
        let mut state = match (heads, base) {
15171×
            (Some(h), Some(b)) if same(h, &b) => self.load_state_indexed(&b)?,
15185×
            (Some(h), _) => self.load_state_history(h)?,
151921×
            (None, Some(b)) => self.load_state_indexed(&b)?,
15200×
            (None, None) => return fail("this is a bare repository: it has no working copy"),
1521
        };
152227×
        let view = self.tree_view(&mut state)?;
152327×
        let Some(node) = view.entries.get(path).map(|e| e.node) else {
15240×
            return fail(format!("{path} is not in that state"));
1525
        };
152627×
        self.load_graphs_of(&mut state, &[node])?;
152726×
        let snapshot = state.materialize_paths(view, [path]);
152826×
        let Some(f) = snapshot.files.get(path) else {
15290×
            return fail(format!("{path} is not in that state"));
1530
        };
153126×
        match &f.content {
15320×
            FileContent::Dir => fail(format!("{path} is a directory")),
153326×
            FileContent::Text { bytes, .. } => Ok(bytes.clone()),
15340×
            FileContent::Opaque { blobs } => match blobs.first() {
15350×
                Some(b) => self.read_blob(b),
15360×
                None => Ok(vec![]),
1537
            },
1538
        }
153927×
    }
1540
1541
    /// Restore `paths` (files or directories) to the working copy's base:
1542
    /// edits are undone, additions removed, removals put back. Returns the
1543
    /// number of paths touched.
15442×
    pub fn discard(&self, paths: &[String]) -> Result<usize> {
15452×
        let _wc = self.lock_working_copy()?;
15462×
        let snap = self.snapshot_status("oxy discard")?;
15477×
        let under = |p: &str| {
15487×
            paths
15497×
                .iter()
15507×
                .any(|x| p == x || p.starts_with(&format!("{}/", x.trim_end_matches('/'))))
15517×
        };
15522×
        let attrs = Repo::state_attributes(&snap.base_snapshot);
15532×
        let mut n = 0;
15543×
        for s in &snap.statuses {
15553×
            if !under(&s.path) {
15561×
                continue;
15572×
            }
15582×
            match snap.base_snapshot.files.get(&s.path) {
1559
                None => {
1560
                    // Added (or the new name of a rename): remove it.
15611×
                    let full = self.root.join(&s.path);
15621×
                    if full.is_dir() {
15630×
                        let _ = fs::remove_dir_all(&full);
15641×
                    } else {
15651×
                        let _ = fs::remove_file(&full);
15661×
                    }
15671×
                    n += 1;
1568
                }
15691×
                Some(f) => {
15701×
                    match &f.content {
15710×
                        FileContent::Dir => fs::create_dir_all(self.root.join(&s.path))?,
15721×
                        FileContent::Text { bytes, .. } => {
15731×
                            let on_disk: std::borrow::Cow<[u8]> = if attrs.lookup(&s.path).eol
15741×
                                == Some(crate::attributes::Eol::Crlf)
1575
                            {
15760×
                                crate::attributes::to_crlf(bytes).into()
1577
                            } else {
15781×
                                bytes.as_slice().into()
1579
                            };
15801×
                            self.write_file(&s.path, &on_disk, f.mode.exec)?;
1581
                        }
15820×
                        FileContent::Opaque { blobs } => {
15830×
                            let bytes = match blobs.first() {
15840×
                                Some(b) => self.read_blob(b)?,
15850×
                                None => vec![],
1586
                            };
15870×
                            if f.kind == NodeKind::Symlink {
15880×
                                self.write_symlink(&s.path, &bytes)?;
15890×
                            } else if f.kind == NodeKind::File {
15900×
                                self.write_file(&s.path, &bytes, f.mode.exec)?;
15910×
                            }
1592
                        }
1593
                    }
15941×
                    n += 1;
1595
                }
1596
            }
1597
        }
1598
        // A rename's old name is not in the statuses; put it back too.
15994×
        for (p, f) in &snap.base_snapshot.files {
16004×
            if under(p)
16011×
                && !self.root.join(p).exists()
16020×
                && f.kind != NodeKind::Dir
16030×
                && f.kind != NodeKind::Subrepo
16040×
                && !snap.statuses.iter().any(|s| s.path == *p)
1605
            {
16060×
                let bytes = match &f.content {
16070×
                    FileContent::Text { bytes, .. } => bytes.clone(),
16080×
                    FileContent::Opaque { blobs } => blobs
16090×
                        .first()
16100×
                        .map(|b| self.read_blob(b))
16110×
                        .transpose()?
16120×
                        .unwrap_or_default(),
16130×
                    FileContent::Dir => continue,
1614
                };
16150×
                if f.kind == NodeKind::Symlink {
16160×
                    self.write_symlink(p, &bytes)?
1617
                } else {
16180×
                    self.write_file(p, &bytes, f.mode.exec)?
1619
                }
16200×
                n += 1;
16214×
            }
1622
        }
16232×
        self.drop_manifest();
16242×
        Ok(n)
16252×
    }
1626
1627
    /// Undo the working-copy hunks `indices` (as `hunks` numbers them) on
1628
    /// disk, keeping the others: the files are rewritten from the base plus
1629
    /// the remaining hunks.
16301×
    pub fn discard_hunks(&self, indices: &[usize]) -> Result<usize> {
16311×
        let _wc = self.lock_working_copy()?;
16321×
        let (snap, hunks) = self.hunks()?;
16331×
        let keep: Vec<usize> = hunks
16341×
            .iter()
16351×
            .map(|h| h.index)
16361×
            .filter(|i| !indices.contains(i))
16371×
            .collect();
16381×
        let (ops, edits) = select_hunks(&snap.wc, &keep, &snap.base_snapshot.tree.unified);
16391×
        let dropped_nodes: BTreeSet<NodeId> = hunks
16401×
            .iter()
16411×
            .filter(|h| indices.contains(&h.index))
16421×
            .map(|h| {
16431×
                if h.index < snap.wc.tree_ops.len() {
16440×
                    snap.wc.tree_ops[h.index].node()
1645
                } else {
16461×
                    snap.wc.edits[h.index - snap.wc.tree_ops.len()].node()
1647
                }
16481×
            })
16491×
            .collect();
16501×
        let mut partial = snap.wc.clone();
16511×
        partial.tree_ops = ops;
16521×
        partial.edits = edits;
16531×
        partial.normalize();
16541×
        let mut st = snap.base.clone();
16551×
        st.add_unchecked(partial);
1656
        // Every file of the target is rendered: build the graphs the
1657
        // partial snapshot left out.
16581×
        self.load_all_graphs(&mut st)?;
16591×
        let target = st.materialize();
16601×
        let by_node_target = target.tree.by_node();
16611×
        let by_node_base = snap.base_snapshot.tree.by_node();
16621×
        let attrs = Repo::state_attributes(&target);
16631×
        let mut n = 0;
16641×
        for node in dropped_nodes {
16651×
            match by_node_target.get(&node) {
16661×
                Some(e) => {
16671×
                    let f = &target.files[&e.path];
16681×
                    match &f.content {
16690×
                        FileContent::Dir => {}
16701×
                        FileContent::Text { bytes, .. } => {
16711×
                            let on_disk: std::borrow::Cow<[u8]> = if attrs.lookup(&e.path).eol
16721×
                                == Some(crate::attributes::Eol::Crlf)
1673
                            {
16740×
                                crate::attributes::to_crlf(bytes).into()
1675
                            } else {
16761×
                                bytes.as_slice().into()
1677
                            };
16781×
                            self.write_file(&e.path, &on_disk, f.mode.exec)?;
1679
                        }
16800×
                        FileContent::Opaque { blobs } => {
16810×
                            let bytes = blobs
16820×
                                .first()
16830×
                                .map(|b| self.read_blob(b))
16840×
                                .transpose()?
16850×
                                .unwrap_or_default();
16860×
                            if f.kind == NodeKind::Symlink {
16870×
                                self.write_symlink(&e.path, &bytes)?
1688
                            } else {
16890×
                                self.write_file(&e.path, &bytes, f.mode.exec)?
1690
                            }
1691
                        }
1692
                    }
1693
                    // A discarded rename: the new name goes.
16941×
                    if let Some(old_path) = snap
16951×
                        .statuses
16961×
                        .iter()
16971×
                        .find(|s| {
16981×
                            s.status == ChangeStatus::Renamed && !target.files.contains_key(&s.path)
16991×
                        })
17001×
                        .map(|s| s.path.clone())
17010×
                    {
17020×
                        let _ = fs::remove_file(self.root.join(old_path));
17031×
                    }
17041×
                    n += 1;
1705
                }
1706
                None => {
1707
                    // The node exists in neither target nor base with a live path: an addition to remove.
17080×
                    if let Some(added) = snap.statuses.iter().find(|s| {
17090×
                        s.status == ChangeStatus::Added
17100×
                            && !target.files.contains_key(&s.path)
17110×
                            && !by_node_base.contains_key(&node)
17120×
                    }) {
17130×
                        let full = self.root.join(&added.path);
17140×
                        if full.is_dir() {
17150×
                            let _ = fs::remove_dir_all(&full);
17160×
                        } else {
17170×
                            let _ = fs::remove_file(&full);
17180×
                        }
17190×
                        n += 1;
17200×
                    }
1721
                }
1722
            }
1723
        }
17241×
        self.drop_manifest();
17251×
        Ok(n)
17261×
    }
1727
1728
    /// The diff of the working copy (`None`) or of a change, per file with
1729
    /// line-numbered hunks (spec: `oxy diff --json`).
17306×
    pub fn diff_files(&self, change: Option<&ChangeHash>) -> Result<Vec<FileDiff>> {
17316×
        let (c, base, base_snapshot) = match change {
17322×
            Some(h) => {
17332×
                let c = self.store.get_change(h)?;
17342×
                let (base, snapshot) = self.change_base(&c)?;
17352×
                (c, base, snapshot)
1736
            }
17374×
            None => match self.working_copy_with_base_unless_unchanged()? {
17383×
                Some(all) => all,
17391×
                None => return Ok(Vec::new()),
1740
            },
1741
        };
17425×
        Ok(diff_files_of(&c, &base, &base_snapshot))
17436×
    }
1744
1745
    /// The snapshot a command would take, without taking it, when the
1746
    /// status cache holds: every file is as the last snapshot left it, so
1747
    /// that snapshot's working-copy change is the answer. Its base comes
1748
    /// from the state index, the `.oxyattributes` files from disk. `None`
1749
    /// when a snapshot must be taken, and when there is nothing to commit
1750
    /// (the snapshot then says so). A conflicted base never gets here: the
1751
    /// cache does not hold for one.
1752704×
    pub(crate) fn snapshot_from_cache(&self) -> Result<Option<SnapshotResult>> {
1753704×
        let Some(statuses) = self.status_by_manifest()? else {
1754489×
            return Ok(None);
1755
        };
1756215×
        if statuses.is_empty() {
17573×
            return Ok(None);
1758212×
        }
1759212×
        let _t = crate::timing::phase("snapshot: from the status cache");
1760212×
        let (wc_hash, wc) = self.working_copy()?;
1761212×
        let base = self.load_state_indexed(&wc.deps)?;
1762212×
        let (base, base_snapshot) = self.render_base_for(&wc, base)?;
1763212×
        let attribute_files: Vec<(String, Vec<u8>)> = match self.read_manifest()? {
1764212×
            Some((_, _, m)) => m
1765212×
                .entries
1766212×
                .keys()
1767651×
                .filter(|p| is_attributes(p))
1768212×
                .filter_map(|p| fs::read(self.root.join(p)).ok().map(|b| (p.clone(), b)))
1769212×
                .collect(),
17700×
            None => Vec::new(),
1771
        };
1772212×
        let attributes = crate::attributes::Attributes::from_files(
1773212×
            attribute_files
1774212×
                .iter()
1775212×
                .map(|(p, b)| (p.as_str(), b.as_slice())),
1776
        );
1777212×
        Ok(Some(SnapshotResult {
1778212×
            wc_hash,
1779212×
            wc,
1780212×
            base,
1781212×
            base_snapshot,
1782212×
            statuses,
1783212×
            changed: false,
1784212×
            resolves: false,
1785212×
            contributors: Vec::new(),
1786212×
            attributes,
1787212×
            untracked_nested: self.untracked_nested.borrow().clone(),
1788212×
            manifest: None,
1789212×
        }))
1790704×
    }
1791
1792
    /// The working-copy change with its base state and a snapshot of the
1793
    /// base, for showing what the working copy changes ([`render_change`],
1794
    /// [`diff_files_of`]). While the status cache holds (every file as the
1795
    /// last snapshot left it), the stored working-copy change is the
1796
    /// answer, no snapshot is taken, and the base's snapshot holds its tree
1797
    /// but no file; otherwise a snapshot makes all three.
17982×
    pub fn working_copy_with_base(&self) -> Result<(Change, State, Snapshot)> {
17992×
        match self.working_copy_with_base_unless_unchanged()? {
18001×
            Some(all) => Ok(all),
1801
            None => {
18021×
                let (_, wc) = self.working_copy()?;
18031×
                let base = self.load_state_indexed(&wc.deps)?;
18041×
                let (base, snapshot) = self.tree_base_for(&wc, base)?;
18051×
                Ok((wc, base, snapshot))
1806
            }
1807
        }
18082×
    }
1809
1810
    /// [`Repo::working_copy_with_base`], or `None` when the status cache
1811
    /// holds and the working-copy change changes nothing: its diff is
1812
    /// empty, and the base is not loaded for it (oxygen#94).
18137×
    pub fn working_copy_with_base_unless_unchanged(
18147×
        &self,
18157×
    ) -> Result<Option<(Change, State, Snapshot)>> {
18167×
        if self.status_by_manifest()?.is_some() {
18175×
            let (_, wc) = self.working_copy()?;
18185×
            if wc.tree_ops.is_empty() && wc.edits.is_empty() {
18193×
                return Ok(None);
18202×
            }
18212×
            let base = self.load_state_indexed(&wc.deps)?;
18222×
            let (base, snapshot) = self.tree_base_for(&wc, base)?;
18232×
            return Ok(Some((wc, base, snapshot)));
18242×
        }
18252×
        let snap = self.snapshot_status("oxy diff")?;
18262×
        Ok(Some((snap.wc, snap.base, snap.base_snapshot)))
18277×
    }
1828
1829
    /// The log restricted to changes touching `path` (its node, so renames
1830
    /// are followed), on the current bookmark.
18316×
    pub fn log_for_path(&self, path: &str) -> Result<Vec<LogEntry>> {
18326×
        let heads = self.bookmark_heads()?;
18336×
        if self.is_bare() {
18341×
            return self.log_for_path_in(path, &heads);
18355×
        }
18365×
        let entries = self.log()?;
18375×
        let (_, wc) = self.working_copy()?;
1838
        // The path's node from the trees alone: the base's (from the
1839
        // workspace's state index), else the bookmark's. Nothing is
1840
        // rendered.
18415×
        let node_in = |mut state: State| -> Result<Option<HashSet<NodeId>>> {
18425×
            Ok(nodes_at(&self.tree_view(&mut state)?, path))
18435×
        };
18445×
        let nodes = match node_in(self.load_state_indexed(&wc.deps)?)? {
18455×
            Some(n) => Some(n),
18460×
            None => node_in(self.load_state_history(&heads)?)?,
1847
        };
18485×
        let Some(nodes) = nodes else {
18490×
            return fail(format!("{path} is not tracked"));
1850
        };
18515×
        Ok(self.entries_touching_up_to(entries, nodes, None))
18526×
    }
1853
1854
    /// The log of the state with these heads restricted to changes touching
1855
    /// `path` (its node, so renames are followed).
18562×
    pub fn log_for_path_in(&self, path: &str, heads: &[ChangeHash]) -> Result<Vec<LogEntry>> {
18572×
        self.log_for_path_of(&self.load_state_history(heads)?, path, None)
18582×
    }
1859
1860
    /// The changes of a loaded state touching `path`, newest first, at most
1861
    /// `limit` of them. The path is found in the state's tree alone, so no
1862
    /// file is rendered, and the walk stops once `limit` are found.
18635×
    pub fn log_for_path_of(
18645×
        &self,
18655×
        state: &State,
18665×
        path: &str,
18675×
        limit: Option<usize>,
18685×
    ) -> Result<Vec<LogEntry>> {
18695×
        let Some(nodes) = nodes_at(&state.view(), path) else {
18701×
            return fail(format!("{path} is not in that state"));
1871
        };
18724×
        Ok(self.entries_touching_up_to(self.log_of(state), nodes, limit))
18735×
    }
1874
18759×
    fn entries_touching_up_to(
18769×
        &self,
18779×
        entries: Vec<LogEntry>,
18789×
        wanted: HashSet<NodeId>,
18799×
        limit: Option<usize>,
18809×
    ) -> Vec<LogEntry> {
18819×
        let mut touched = self.touched();
18829×
        if limit.is_none() {
18838×
            let hashes: Vec<ChangeHash> = entries.iter().map(|e| e.hash).collect();
18848×
            touched.fill(self, &hashes);
18851×
        }
18869×
        let mut out = Vec::new();
188732×
        for e in entries {
188832×
            if limit.is_some_and(|n| out.len() >= n) {
18891×
                break;
189031×
            }
189131×
            if touched.touches(self, &e.hash, &wanted) {
189220×
                out.push(e);
189320×
            }
1894
        }
18959×
        touched.save();
18969×
        out
18979×
    }
1898
}
1899
1900
/// The node at `path` in `view`, with the nodes it shows as one with it
1901
/// (identical additions, spec §9.2): the file's history is all of theirs.
190210×
fn nodes_at(view: &crate::tree::TreeView, path: &str) -> Option<HashSet<NodeId>> {
190310×
    let node = view.entries.get(path)?.node;
19049×
    let mut out = HashSet::from([node]);
19059×
    out.extend(
19069×
        view.unified
19079×
            .iter()
19089×
            .filter(|(_, shown)| **shown == node)
19099×
            .map(|(dup, _)| *dup),
1910
    );
19119×
    Some(out)
191210×
}
1913
1914
/// Per-file hunks of `change` against `base`.
19155×
pub fn diff_files_of(change: &Change, base: &State, base_snapshot: &Snapshot) -> Vec<FileDiff> {
19165×
    let by_node = base_snapshot.tree.by_node();
19175×
    let mut new_names: HashMap<NodeId, (NodeId, String, NodeKind)> = HashMap::new();
19185×
    for op in &change.tree_ops {
1919
        if let TreeOp::AddNode {
19202×
            node,
19212×
            parent,
19222×
            name,
19232×
            kind,
1924
            ..
19253×
        } = op
19262×
        {
19272×
            new_names.insert(*node, (*parent, name.clone(), *kind));
19282×
        }
1929
    }
19309×
    let path_of = |n: &NodeId| -> String {
19319×
        path_of_node(n, &by_node, &new_names).unwrap_or_else(|| format!("<node {}>", n.short(8)))
19329×
    };
19335×
    let mut files: BTreeMap<NodeId, FileDiff> = BTreeMap::new();
19345×
    let mut order: Vec<NodeId> = Vec::new();
193514×
    let mut entry = |files: &mut BTreeMap<NodeId, FileDiff>, n: NodeId, kind: &str| {
193614×
        if let std::collections::btree_map::Entry::Vacant(v) = files.entry(n) {
19379×
            order.push(n);
19389×
            v.insert(FileDiff {
19399×
                path: path_of(&n),
19409×
                kind: kind.to_string(),
19419×
                hunks: vec![],
19429×
                from: None,
19439×
            });
19449×
        }
194514×
    };
19465×
    for op in change
19475×
        .tree_ops
19485×
        .iter()
19495×
        .filter(|o| !is_unified_retirement(o, base_snapshot))
1950
    {
19513×
        match op {
19522×
            TreeOp::AddNode { node, kind, .. } => {
19532×
                if *kind != NodeKind::Dir {
19542×
                    entry(&mut files, *node, "added");
19552×
                }
1956
            }
19571×
            TreeOp::RemoveNode { node, .. } => {
19581×
                entry(&mut files, *node, "removed");
19591×
                if let Some(e) = by_node.get(node) {
19601×
                    files.get_mut(node).unwrap().path = e.path.clone();
19611×
                }
1962
            }
1963
            TreeOp::Move {
19640×
                node, parent, name, ..
1965
            } => {
19660×
                entry(&mut files, *node, "renamed");
19670×
                let f = files.get_mut(node).unwrap();
19680×
                f.from = by_node.get(node).map(|e| e.path.clone());
19690×
                let dir = if parent.is_root() {
19700×
                    String::new()
1971
                } else {
19720×
                    path_of_node(parent, &by_node, &new_names).unwrap_or_default()
1973
                };
19740×
                f.path = if dir.is_empty() {
19750×
                    name.clone()
1976
                } else {
19770×
                    format!("{dir}/{name}")
1978
                };
1979
            }
19800×
            TreeOp::SetMode { node, .. } => entry(&mut files, *node, "mode"),
1981
        }
1982
    }
1983
    // Base line numbers per node, 1-based.
19845×
    let mut line_of: HashMap<NodeId, HashMap<(ChangeHash, u32), u32>> = HashMap::new();
198511×
    let mut lines_for = |n: &NodeId| -> HashMap<(ChangeHash, u32), u32> {
198611×
        line_of
198711×
            .entry(*n)
198811×
            .or_insert_with(|| {
19898×
                base.live_lines(n)
19908×
                    .into_iter()
19918×
                    .enumerate()
199211×
                    .map(|(i, (k, _))| (k, i as u32 + 1))
19938×
                    .collect()
19948×
            })
199511×
            .clone()
199611×
    };
199711×
    for e in &change.edits {
199811×
        let n = e.node();
199911×
        let is_new = new_names.contains_key(&n);
200011×
        entry(&mut files, n, if is_new { "added" } else { "modified" });
200111×
        let f = files.get_mut(&n).unwrap();
200211×
        match e {
20039×
            Edit::Insert { after, lines, .. } => {
20049×
                let map = lines_for(&n);
20059×
                let base_line = match after {
20063×
                    AtomRef::Start => 0,
20070×
                    AtomRef::End => map.len() as u32,
20086×
                    AtomRef::Atom { change, index } if change.is_zero() => {
20090×
                        f.hunks.last().map(|h| h.base_line).unwrap_or(0)
2010
                    }
20116×
                    AtomRef::Atom { change, index } => {
20126×
                        map.get(&(*change, *index)).copied().unwrap_or(0)
2013
                    }
2014
                };
20159×
                f.hunks.push(DiffHunk {
20169×
                    base_line,
20179×
                    added: lines.to_vec(),
20189×
                    removed: vec![],
20199×
                });
2020
            }
20212×
            Edit::Delete { atoms, .. } => {
20222×
                let map = lines_for(&n);
20232×
                let mut removed = Vec::new();
20242×
                for r in atoms {
20252×
                    for i in r.from..r.to {
20262×
                        let line = map.get(&(r.change, i)).copied().unwrap_or(0);
20272×
                        let text = base
20282×
                            .file(&n)
20292×
                            .and_then(|g| g.content(&(r.change, i)))
20302×
                            .unwrap_or(b"")
20312×
                            .to_vec();
20322×
                        removed.push((line, text));
2033
                    }
2034
                }
20352×
                let base_line = removed
20362×
                    .first()
20372×
                    .map(|(l, _)| l.saturating_sub(1))
20382×
                    .unwrap_or(0);
20392×
                f.hunks.push(DiffHunk {
20402×
                    base_line,
20412×
                    added: vec![],
20422×
                    removed,
20432×
                });
2044
            }
2045
            Edit::Replace { .. } => {
20460×
                if !is_new {
20470×
                    f.kind = "replaced".into();
20480×
                }
2049
            }
2050
        }
2051
    }
20529×
    order.into_iter().filter_map(|n| files.remove(&n)).collect()
20535×
}
2054
2055
/// Builds the tree ops and edits of a working-copy change against a base.
2056
/// `BLAKE3("oxy node 1" 0 seed kind path)`, truncated: a node identifier
2057
/// that the same seed and path always give (never the root's).
205859×
fn seeded_node(seed: &[u8; 32], path: &str, kind: NodeKind) -> NodeId {
205959×
    let mut h = blake3::Hasher::new();
206059×
    h.update(b"oxy node 1\0");
206159×
    h.update(seed);
206259×
    h.update(&[match kind {
206345×
        NodeKind::File => 1,
206413×
        NodeKind::Dir => 2,
20650×
        NodeKind::Symlink => 3,
20661×
        NodeKind::Subrepo => 4,
2067
    }]);
206859×
    h.update(path.as_bytes());
206959×
    let mut id = [0u8; 16];
207059×
    id.copy_from_slice(&h.finalize().as_bytes()[..16]);
207159×
    if id == [0; 16] {
20720×
        id[15] = 1;
207359×
    }
207459×
    NodeId(id)
207559×
}
2076
2077
struct ChangeBuilder<'a> {
2078
    base: &'a State,
2079
    base_snapshot: &'a Snapshot,
2080
    tree_ops: Vec<TreeOp>,
2081
    edits: Vec<Edit>,
2082
    statuses: Vec<PathStatus>,
2083
    dir_nodes: HashMap<String, NodeId>,
2084
    reuse: HashMap<String, (NodeId, NodeKind)>,
2085
    /// Changes that contributed to conflicts this working copy resolves.
2086
    contributors: BTreeSet<ChangeHash>,
2087
    resolves: bool,
2088
    attrs: crate::attributes::Attributes,
2089
    blobs: HashMap<String, ObjectRef>,
2090
    /// Opaque files whose replace conflict the content settles.
2091
    resolve: HashSet<String>,
2092
    /// When set, new nodes' identifiers derive from it and their paths.
2093
    node_seed: Option<[u8; 32]>,
2094
    /// For a Git import, the base's dead directories by where they were
2095
    /// (see `ensure_dir`), worked out when first needed.
2096
    dead_dirs: Option<HashMap<(NodeId, String), (NodeId, crate::tree::OpKey)>>,
2097
    /// Text edits of edited files, worked out in parallel beforehand
2098
    /// (`diff_in_parallel`); a file not here is diffed when it is updated.
2099
    diffs: HashMap<String, Vec<Edit>>,
2100
}
2101
2102
impl<'a> ChangeBuilder<'a> {
21032123×
    fn new(
21042123×
        base: &'a State,
21052123×
        base_snapshot: &'a Snapshot,
21062123×
        reuse: HashMap<String, (NodeId, NodeKind)>,
21072123×
    ) -> Self {
21082123×
        let mut dir_nodes: HashMap<String, NodeId> = HashMap::new();
21092123×
        dir_nodes.insert(String::new(), NodeId::ROOT);
211017850×
        for (p, e) in base_snapshot.tree.entries.iter() {
211117850×
            if e.kind == NodeKind::Dir {
2112540×
                dir_nodes.insert(p.clone(), e.node);
211317310×
            }
2114
        }
21152123×
        ChangeBuilder {
21162123×
            base,
21172123×
            base_snapshot,
21182123×
            tree_ops: vec![],
21192123×
            edits: vec![],
21202123×
            statuses: vec![],
21212123×
            dir_nodes,
21222123×
            reuse,
21232123×
            contributors: BTreeSet::new(),
21242123×
            resolves: false,
21252123×
            attrs: crate::attributes::Attributes::default(),
21262123×
            blobs: HashMap::new(),
21272123×
            resolve: HashSet::new(),
21282123×
            node_seed: None,
21292123×
            dead_dirs: None,
21302123×
            diffs: HashMap::new(),
21312123×
        }
21322123×
    }
2133
2134
    /// Diff the edited text files among `entries` against their base
2135
    /// renderings at once, on every core, for `update_path` to take: the
2136
    /// same diff it would make, only not one file after another.
21372123×
    fn diff_in_parallel(&mut self, entries: &BTreeMap<String, FsEntry>) {
2138
        use rayon::prelude::*;
21392123×
        let files = &self.base_snapshot.files;
21402123×
        let edited: Vec<(&String, &FsEntry, &crate::state::FileState)> = entries
21412123×
            .iter()
214218970×
            .filter_map(|(p, e)| {
214318970×
                let x = files.get(p)?;
214412826×
                (x.kind == e.kind && !e.unchanged && !self.opaque_for(p, e)).then_some((p, e, x))
214518970×
            })
21462123×
            .collect();
2147
        // Below this, starting the threads costs more than it saves.
21482123×
        if edited.len() < 16 {
21492113×
            return;
215010×
        }
215110×
        let this = &*self;
215210×
        let attrs = &this.attrs;
215310×
        let diffs: Vec<(String, Vec<Edit>)> = edited
215410×
            .par_iter()
21555564×
            .filter_map(|(p, e, x)| {
2156
                let FileContent::Text {
21575564×
                    bytes,
21585564×
                    materialized,
21595564×
                } = &x.content
2160
                else {
21610×
                    return None;
2162
                };
21635564×
                if materialized.is_conflicted() {
21640×
                    return None;
21655564×
                }
21665564×
                let disk_text = if attrs.lookup(p).eol.is_some() {
21670×
                    std::sync::Arc::new(crate::attributes::normalize_eol(&e.content))
2168
                } else {
21695564×
                    e.content.clone()
2170
                };
21715564×
                if *bytes == *disk_text {
21725484×
                    return None;
217380×
                }
217480×
                let keys = materialized.live_atoms();
217580×
                let lines = crate::diff::split_lines(bytes);
217680×
                (keys.len() == lines.len()).then(|| {
217780×
                    let edits = crate::diff::text_edits_of(x.node, &keys, &lines, &disk_text);
217880×
                    ((*p).clone(), edits)
217980×
                })
21805564×
            })
218110×
            .collect();
218210×
        self.diffs = diffs.into_iter().collect();
21832123×
    }
2184
21852123×
    fn with_attributes(mut self, attrs: crate::attributes::Attributes) -> Self {
21862123×
        self.attrs = attrs;
21872123×
        self
21882123×
    }
2189
2190
    /// Whether a file is opaque: forced by `binary`, forced text by `text`
2191
    /// only when it has no NUL bytes, else sniffed.
2192
    /// The blob for an opaque entry: the cached one, else stored now.
2193137×
    fn blob_of(
2194137×
        &mut self,
2195137×
        repo: &Repo,
2196137×
        path: &str,
2197137×
        e: &FsEntry,
2198137×
        nocompress: bool,
2199137×
    ) -> Result<ObjectRef> {
2200137×
        let b = match e.blob {
22010×
            Some(b) => b,
2202137×
            None => repo.store_blob_for(&e.content, nocompress)?,
2203
        };
2204137×
        self.blobs.insert(path.to_string(), b);
2205137×
        Ok(b)
2206137×
    }
2207
220823309×
    fn opaque_for(&self, path: &str, e: &FsEntry) -> bool {
220923309×
        if e.blob.is_some() {
22108×
            return true;
221123301×
        }
221223301×
        if e.kind == NodeKind::Symlink || e.kind == NodeKind::Subrepo {
2213100×
            return true;
221423201×
        }
221523201×
        match self.attrs.lookup(path).binary {
221612×
            Some(true) => true,
22170×
            Some(false) => is_binary(&e.content),
221823189×
            None => is_binary(&e.content),
2219
        }
222023309×
    }
2221
2222
    /// Text content as stored: `\r\n` normalized for `eol=` files.
222314594×
    fn stored_text(
222414594×
        &self,
222514594×
        path: &str,
222614594×
        content: &std::sync::Arc<Vec<u8>>,
222714594×
    ) -> std::sync::Arc<Vec<u8>> {
222814594×
        if self.attrs.lookup(path).eol.is_some() {
22297×
            std::sync::Arc::new(crate::attributes::normalize_eol(content))
2230
        } else {
223114587×
            content.clone()
2232
        }
223314594×
    }
2234
2235
    /// The identifier of a node added at `path`: reused when asked, derived
2236
    /// from the seed when there is one, random otherwise.
22376263×
    fn new_node(&self, path: &str, kind: NodeKind) -> NodeId {
22386263×
        if let Some(n) = self.reused_node(path, kind) {
2239159×
            return n;
22406104×
        }
22416104×
        match &self.node_seed {
224259×
            Some(seed) => seeded_node(seed, path, kind),
22436045×
            None => NodeId::random(),
2244
        }
22456263×
    }
2246
22476263×
    fn reused_node(&self, path: &str, kind: NodeKind) -> Option<NodeId> {
22486263×
        self.reuse
22496263×
            .get(path)
22506263×
            .filter(|(_, k)| *k == kind)
22516263×
            .map(|(n, _)| *n)
22526263×
    }
2253
2254
    /// A dead directory last placed at (`parent`, `name`) in the base.
225515×
    fn revivable_dir(
225615×
        &mut self,
225715×
        parent: NodeId,
225815×
        name: &str,
225915×
    ) -> Option<(NodeId, crate::tree::OpKey)> {
226015×
        let base = self.base;
226115×
        self.dead_dirs
226215×
            .get_or_insert_with(|| base.tree().dead_dirs())
226315×
            .get(&(parent, name.to_string()))
226415×
            .copied()
226515×
    }
2266
22676145×
    fn ensure_dir(&mut self, path: &str) -> NodeId {
22686145×
        if let Some(n) = self.dir_nodes.get(path) {
22695995×
            return *n;
2270150×
        }
2271150×
        let mut parent = NodeId::ROOT;
2272150×
        let mut prefix = String::new();
2273169×
        for comp in path.split('/') {
2274169×
            if !prefix.is_empty() {
227519×
                prefix.push('/');
2276150×
            }
2277169×
            prefix.push_str(comp);
2278169×
            let known = self.dir_nodes.get(&prefix).copied();
2279169×
            let revive = match known {
228013×
                Some(_) => None,
2281156×
                None if self.node_seed.is_some() => self.revivable_dir(parent, comp),
2282141×
                None => None,
2283
            };
2284169×
            parent = match (known, revive) {
228513×
                (Some(n), _) => n,
22862×
                (None, Some((node, old))) => {
2287
                    // Git has no identity for a directory: one that comes
2288
                    // back where it was is the same directory, brought back
2289
                    // with a move, so lines of history that placed files in
2290
                    // it before and after agree (oxygen#30).
22912×
                    self.tree_ops.push(TreeOp::Move {
22922×
                        node,
22932×
                        old: OpRef {
22942×
                            change: old.0,
22952×
                            index: old.1,
22962×
                        },
22972×
                        parent,
22982×
                        name: comp.to_string(),
22992×
                    });
23002×
                    self.dir_nodes.insert(prefix.clone(), node);
23012×
                    node
2302
                }
2303
                (None, None) => {
2304154×
                    let node = self.new_node(&prefix, NodeKind::Dir);
2305154×
                    self.tree_ops.push(TreeOp::AddNode {
2306154×
                        node,
2307154×
                        kind: NodeKind::Dir,
2308154×
                        mode: Mode::default(),
2309154×
                        parent,
2310154×
                        name: comp.to_string(),
2311154×
                    });
2312154×
                    self.dir_nodes.insert(prefix.clone(), node);
2313154×
                    node
2314
                }
2315
            };
2316
        }
2317150×
        parent
23186145×
    }
2319
23206109×
    fn add_path(&mut self, repo: &Repo, path: &str, e: &FsEntry) -> Result<()> {
23216109×
        let (dir, name) = split_path(path);
23226109×
        let parent = self.ensure_dir(dir);
23236109×
        let node = self.new_node(path, e.kind);
23246109×
        let opaque = self.opaque_for(path, e);
23256109×
        let nocompress = self.attrs.lookup(path).nocompress;
23266109×
        self.tree_ops.push(TreeOp::AddNode {
23276109×
            node,
23286109×
            kind: e.kind,
23296109×
            mode: Mode {
23306109×
                exec: e.exec,
23316109×
                opaque,
23326109×
            },
23336109×
            parent,
23346109×
            name: name.to_string(),
23356109×
        });
23366109×
        if opaque {
2337101×
            let blob = self.blob_of(repo, path, e, nocompress)?;
2338101×
            self.edits.push(Edit::Replace {
2339101×
                node,
2340101×
                old: None,
2341101×
                new: Some(blob),
2342101×
            });
23436008×
        } else if !e.content.is_empty() {
23445976×
            let content = self.stored_text(path, &e.content);
23455976×
            self.edits.push(Edit::Insert {
23465976×
                node,
23475976×
                after: crate::objects::AtomRef::Start,
23485976×
                before: crate::objects::AtomRef::End,
23495976×
                lines: crate::lines::Lines::split_shared(content),
23505976×
            });
23515976×
        }
23526109×
        self.statuses.push(PathStatus {
23536109×
            path: path.to_string(),
23546109×
            status: ChangeStatus::Added,
23556109×
        });
23566109×
        Ok(())
23576109×
    }
2358
2359
    /// Move the node at `old` to `new` and apply `e`'s content to it.
236036×
    fn move_path(
236136×
        &mut self,
236236×
        repo: &Repo,
236336×
        old: &str,
236436×
        new: &str,
236536×
        e: &FsEntry,
236636×
        expected: &crate::state::FileState,
236736×
    ) -> Result<()> {
236836×
        let placement = self.base_snapshot.tree.entries[old].placement;
236936×
        let (dir, name) = split_path(new);
237036×
        let parent = self.ensure_dir(dir);
237136×
        self.tree_ops.push(TreeOp::Move {
237236×
            node: expected.node,
237336×
            old: op_ref(placement),
237436×
            parent,
237536×
            name: name.to_string(),
237636×
        });
237736×
        for k in self.same_place(&expected.node, placement) {
23780×
            self.tree_ops.push(TreeOp::RemoveNode {
23790×
                node: expected.node,
23800×
                placement: op_ref(k),
23810×
            });
23820×
        }
238336×
        self.update_path(repo, old, e, expected)?;
2384
        // update_path reports under the old path; the rename is what the user sees.
238536×
        self.statuses.retain(|s| s.path != old);
238636×
        self.statuses.push(PathStatus {
238736×
            path: new.to_string(),
238836×
            status: ChangeStatus::Renamed,
238936×
        });
239036×
        Ok(())
239136×
    }
2392
2393
    /// For a Git import: a node the commit keeps is in one place, the one
2394
    /// its tree names, so any other live placement it has in the base goes;
2395
    /// and a node the tree cannot show at all (an orphan) goes too. Such a
2396
    /// placement is out of sight, under a directory another line of history
2397
    /// removed, where no diff of the tree would ever reach it (oxygen#30).
239888×
    fn retire_stray_placements(&mut self) {
239988×
        let mut retired: HashSet<(ChangeHash, u32)> = HashSet::new();
240088×
        let mut placed: BTreeSet<NodeId> = BTreeSet::new();
240199×
        for op in &self.tree_ops {
240299×
            match op {
240319×
                TreeOp::Move { node, old, .. } => {
240419×
                    retired.insert((old.change, old.index));
240519×
                    placed.insert(*node);
240619×
                }
240721×
                TreeOp::RemoveNode { placement, .. } => {
240821×
                    retired.insert((placement.change, placement.index));
240921×
                }
241059×
                TreeOp::AddNode { .. } | TreeOp::SetMode { .. } => {}
2411
            }
2412
        }
2413
        // Nodes kept where they were: what the base's tree view shows and
2414
        // this change neither moves nor removes.
241588×
        let mut kept: HashMap<NodeId, (ChangeHash, u32)> = HashMap::new();
2416241×
        for e in self.base_snapshot.tree.entries.values() {
2417241×
            if !retired.contains(&e.placement) {
2418204×
                kept.insert(e.node, e.placement);
2419204×
            }
2420
        }
2421
        // Only a node with several live placements can have a stray one,
2422
        // and the tree view names each as a conflict.
242388×
        let multi: BTreeSet<NodeId> = self
242488×
            .base_snapshot
242588×
            .tree
242688×
            .conflicts
242788×
            .iter()
242888×
            .filter_map(|c| match c {
24291×
                crate::tree::TreeConflict::MultiPlacement { node, .. } => Some(*node),
24306×
                _ => None,
24317×
            })
243288×
            .collect();
243388×
        let mut extra = Vec::new();
2434
        // A node whose only placements are under a directory another line
2435
        // removed (an orphan) is nowhere the tree can show, and Git's tree
2436
        // has no such path: it goes.
243788×
        for c in &self.base_snapshot.tree.conflicts {
24387×
            let crate::tree::TreeConflict::Orphan { node, .. } = c else {
24396×
                continue;
2440
            };
24411×
            if kept.contains_key(node) || placed.contains(node) {
24420×
                continue;
24431×
            }
24441×
            for (k, _) in self.base.tree().live_placements(node) {
24451×
                if retired.insert(k) {
24461×
                    extra.push(TreeOp::RemoveNode {
24471×
                        node: *node,
24481×
                        placement: op_ref(k),
24491×
                    });
24501×
                }
2451
            }
2452
        }
245388×
        for node in placed
245488×
            .iter()
245588×
            .chain(multi.iter().filter(|n| kept.contains_key(*n)))
2456
        {
245719×
            for (k, _) in self.base.tree().live_placements(node) {
245818×
                if retired.contains(&k) || kept.get(node) == Some(&k) {
245917×
                    continue;
24601×
                }
24611×
                retired.insert(k);
24621×
                extra.push(TreeOp::RemoveNode {
24631×
                    node: *node,
24641×
                    placement: op_ref(k),
24651×
                });
2466
            }
2467
        }
246888×
        if !extra.is_empty() {
24692×
            self.resolves = true;
24702×
            self.tree_ops.extend(extra);
247186×
        }
247288×
    }
2473
2474
    /// Nodes the base shows as one with another (identical additions at one
2475
    /// path, spec §9.2) are retired by the change that first touches the
2476
    /// node shown: edited, moved, removed or given a mode alone, it would
2477
    /// differ from them and the name conflict would come back. Nothing
2478
    /// else changes for the user, so no status reports it.
24792123×
    fn retire_unified(&mut self) {
24802123×
        let unified = &self.base_snapshot.tree.unified;
24812123×
        if unified.is_empty() {
24822102×
            return;
248321×
        }
248421×
        let touched: HashSet<NodeId> = self
248521×
            .tree_ops
248621×
            .iter()
248721×
            .map(|o| o.node())
248822×
            .chain(self.edits.iter().map(|e| e.node()))
248921×
            .collect();
249021×
        let mut retired: HashSet<(ChangeHash, u32)> = HashSet::new();
249121×
        for op in &self.tree_ops {
249214×
            match op {
24933×
                TreeOp::Move { old, .. } => {
24943×
                    retired.insert((old.change, old.index));
24953×
                }
24963×
                TreeOp::RemoveNode { placement, .. } => {
24973×
                    retired.insert((placement.change, placement.index));
24983×
                }
24998×
                TreeOp::AddNode { .. } | TreeOp::SetMode { .. } => {}
2500
            }
2501
        }
250221×
        let mut extra = Vec::new();
250322×
        for (dup, shown) in unified {
250422×
            if !touched.contains(shown) {
25055×
                continue;
250617×
            }
250717×
            for (k, _) in self.base.tree().live_placements(dup) {
250817×
                if retired.insert(k) {
250917×
                    extra.push(TreeOp::RemoveNode {
251017×
                        node: *dup,
251117×
                        placement: op_ref(k),
251217×
                    });
251317×
                }
2514
            }
2515
        }
251621×
        self.tree_ops.extend(extra);
25172123×
    }
2518
2519
    /// The node's other live placements at the same place as `k`, the one
2520
    /// the tree shows: two lines of history that put a node back where it
2521
    /// was each leave a placement, and the tree shows them as one file. A
2522
    /// change that removes or moves it retires them together, or the copy
2523
    /// left behind outlives its directory (oxygen#88).
2524172×
    fn same_place(&self, node: &NodeId, k: (ChangeHash, u32)) -> Vec<(ChangeHash, u32)> {
2525172×
        let tree = self.base.tree();
2526172×
        let Some(shown) = tree.placement(&k) else {
25270×
            return Vec::new();
2528
        };
2529172×
        tree.live_placements(node)
2530172×
            .into_iter()
2531174×
            .filter(|(o, p)| *o != k && p.parent == shown.parent && p.name == shown.name)
2532172×
            .map(|(o, _)| o)
2533172×
            .collect()
2534172×
    }
2535
2536136×
    fn remove_path(&mut self, path: &str, expected: &crate::state::FileState) {
2537136×
        let entry = &self.base_snapshot.tree.entries[path];
2538136×
        let placement = entry.placement;
2539136×
        self.tree_ops.push(TreeOp::RemoveNode {
2540136×
            node: expected.node,
2541136×
            placement: op_ref(placement),
2542136×
        });
2543136×
        for k in self.same_place(&expected.node, placement) {
25441×
            self.tree_ops.push(TreeOp::RemoveNode {
25451×
                node: expected.node,
25461×
                placement: op_ref(k),
25471×
            });
25481×
        }
2549136×
        if path.contains(".oxy-conflict-") || expected.is_conflicted() {
25507×
            self.resolves = true;
2551129×
        }
2552136×
        self.statuses.push(PathStatus {
2553136×
            path: path.to_string(),
2554136×
            status: ChangeStatus::Removed,
2555136×
        });
2556136×
    }
2557
255812862×
    fn update_path(
255912862×
        &mut self,
256012862×
        repo: &Repo,
256112862×
        path: &str,
256212862×
        e: &FsEntry,
256312862×
        expected: &crate::state::FileState,
256412862×
    ) -> Result<()> {
256512862×
        if expected.kind != e.kind {
25661×
            self.remove_path(path, expected);
25671×
            self.statuses.pop();
25681×
            self.add_path(repo, path, e)?;
25691×
            self.statuses.pop();
25701×
            self.statuses.push(PathStatus {
25711×
                path: path.to_string(),
25721×
                status: ChangeStatus::Modified,
25731×
            });
25741×
            return Ok(());
257512861×
        }
257612861×
        let entry = &self.base_snapshot.tree.entries[path];
257712861×
        let node = expected.node;
257812861×
        let mode_atom = entry.mode_atom.map(op_ref);
257912861×
        if e.unchanged {
2580
            // Known equal to the base's unconflicted rendering (spec
2581
            // §12.3); only the executable bit can differ.
25824243×
            if e.exec != expected.mode.exec {
25833×
                if let Some(old) = mode_atom {
25843×
                    self.tree_ops.push(TreeOp::SetMode {
25853×
                        node,
25863×
                        old,
25873×
                        mode: Mode {
25883×
                            exec: e.exec,
25893×
                            opaque: false,
25903×
                        },
25913×
                    });
25923×
                    self.statuses.push(PathStatus {
25933×
                        path: path.to_string(),
25943×
                        status: ChangeStatus::ModeChanged,
25953×
                    });
25963×
                }
25974240×
            }
25984243×
            return Ok(());
25998618×
        }
26008618×
        let mut status: Option<ChangeStatus> = None;
26018618×
        let wants_opaque = self.opaque_for(path, e);
26028618×
        let nocompress = self.attrs.lookup(path).nocompress;
26038618×
        let disk_text = self.stored_text(path, &e.content);
26048618×
        match &expected.content {
26050×
            FileContent::Dir => {}
2606
            FileContent::Text {
26078386×
                bytes,
26088386×
                materialized,
2609
            } => {
26108386×
                if materialized.is_conflicted() {
261138×
                    if bytes == &*disk_text {
26126×
                        return Ok(());
261332×
                    }
261432×
                    if has_conflict_markers(&e.content) {
26154×
                        self.statuses.push(PathStatus {
26164×
                            path: path.to_string(),
26174×
                            status: ChangeStatus::ConflictEdited,
26184×
                        });
26194×
                        return Ok(());
262028×
                    }
2621
                    // Resolution (spec §9.6): diff against the unconflicted lines
2622
                    // with each region as a gap, then retire every region atom.
2623
                    // Whatever the author kept from a region is re-inserted as
2624
                    // new atoms, which leaves the graph totally ordered.
262528×
                    let regions = self.base.conflict_regions(&node);
262628×
                    let mut edits = text_edits(node, &regions.plain, &disk_text);
262728×
                    if !regions.region_atoms.is_empty() {
262828×
                        edits.insert(
262928×
                            0,
263028×
                            Edit::Delete {
263128×
                                node,
263228×
                                atoms: ranges(&regions.region_atoms),
263328×
                            },
263428×
                        );
263528×
                    }
263628×
                    self.edits.extend(edits);
263728×
                    self.contributors.extend(regions.contributors);
263828×
                    self.resolves = true;
263928×
                    if e.exec != expected.mode.exec {
26400×
                        if let Some(old) = mode_atom {
26410×
                            self.tree_ops.push(TreeOp::SetMode {
26420×
                                node,
26430×
                                old,
26440×
                                mode: Mode {
26450×
                                    exec: e.exec,
26460×
                                    opaque: false,
26470×
                                },
26480×
                            });
26490×
                        }
265028×
                    }
265128×
                    self.statuses.push(PathStatus {
265228×
                        path: path.to_string(),
265328×
                        status: ChangeStatus::Resolved,
265428×
                    });
265528×
                    return Ok(());
26568348×
                }
26578348×
                if wants_opaque {
2658
                    // Text → opaque (spec §7.5), by content or by attribute.
26592×
                    if let Some(old) = mode_atom {
26602×
                        self.tree_ops.push(TreeOp::SetMode {
26612×
                            node,
26622×
                            old,
26632×
                            mode: Mode {
26642×
                                exec: e.exec,
26652×
                                opaque: true,
26662×
                            },
26672×
                        });
26682×
                    }
26692×
                    let live: Vec<_> = repo_live_keys(self.base, &node);
26702×
                    if !live.is_empty() {
26712×
                        self.edits.push(Edit::Delete {
26722×
                            node,
26732×
                            atoms: ranges(&live),
26742×
                        });
26752×
                    }
26762×
                    let blob = self.blob_of(repo, path, e, nocompress)?;
26772×
                    self.edits.push(Edit::Replace {
26782×
                        node,
26792×
                        old: None,
26802×
                        new: Some(blob),
26812×
                    });
26822×
                    status = Some(ChangeStatus::Modified);
26838346×
                } else if bytes != &*disk_text {
2684816×
                    let mut laps = crate::timing::Laps::start();
2685
                    // The base's rendering holds its live atoms in order,
2686
                    // one per line (it is not conflicted here).
2687816×
                    let edits = match self.diffs.remove(path) {
268880×
                        Some(edits) => edits,
2689
                        None => {
2690736×
                            let keys = materialized.live_atoms();
2691736×
                            let lines = crate::diff::split_lines(bytes);
2692736×
                            if keys.len() == lines.len() {
2693736×
                                crate::diff::text_edits_of(node, &keys, &lines, &disk_text)
2694
                            } else {
26950×
                                text_edits(node, &self.base.live_lines(&node), &disk_text)
2696
                            }
2697
                        }
2698
                    };
2699816×
                    laps.lap("build: text diff");
2700816×
                    if !edits.is_empty() {
2701816×
                        self.edits.extend(edits);
2702816×
                        status = Some(ChangeStatus::Modified);
2703816×
                    }
27047530×
                }
27058348×
                let switched_to_opaque = wants_opaque;
27068348×
                if !switched_to_opaque && e.exec != expected.mode.exec {
27074×
                    if let Some(old) = mode_atom {
27084×
                        self.tree_ops.push(TreeOp::SetMode {
27094×
                            node,
27104×
                            old,
27114×
                            mode: Mode {
27124×
                                exec: e.exec,
27134×
                                opaque: false,
27144×
                            },
27154×
                        });
27164×
                        status.get_or_insert(ChangeStatus::ModeChanged);
27174×
                    }
27188344×
                }
2719
            }
2720232×
            FileContent::Opaque { blobs } => {
2721232×
                let new_ref = e.blob.unwrap_or_else(|| Repo::blob_ref(&e.content));
2722232×
                if e.kind == NodeKind::File && wants_opaque {
2723191×
                    // Unchanged or replaced, the file stays opaque: remember its blob.
2724191×
                    self.blobs.insert(path.to_string(), new_ref);
2725191×
                }
2726232×
                if blobs.len() > 1 && self.resolve.contains(path) && e.kind == expected.kind {
2727
                    // Settle the replace conflict (spec §9.3): replace every
2728
                    // live candidate with the chosen blob, depending on each
2729
                    // change that made one live, so all are superseded.
27302×
                    let chosen = self.blob_of(repo, path, e, nocompress)?;
27314×
                    for b in blobs {
27324×
                        self.edits.push(Edit::Replace {
27334×
                            node,
27344×
                            old: Some(*b),
27354×
                            new: Some(chosen),
27364×
                        });
27374×
                    }
27382×
                    self.contributors
27392×
                        .extend(self.base.blob_contributors(&node, blobs));
27402×
                    self.resolves = true;
27412×
                    self.statuses.push(PathStatus {
27422×
                        path: path.to_string(),
27432×
                        status: ChangeStatus::Resolved,
27442×
                    });
27452×
                    return Ok(());
2746230×
                }
2747230×
                if blobs.len() > 1 {
27482×
                    if !blobs.contains(&new_ref) {
27490×
                        self.statuses.push(PathStatus {
27500×
                            path: path.to_string(),
27510×
                            status: ChangeStatus::ConflictEdited,
27520×
                        });
27532×
                    }
27542×
                    return Ok(());
2755228×
                }
2756228×
                let current = blobs.first().copied();
2757228×
                if current != Some(new_ref) {
275834×
                    if e.kind == NodeKind::File && !wants_opaque {
2759
                        // Opaque → text (spec §7.5).
27602×
                        if let Some(old) = mode_atom {
27612×
                            self.tree_ops.push(TreeOp::SetMode {
27622×
                                node,
27632×
                                old,
27642×
                                mode: Mode {
27652×
                                    exec: e.exec,
27662×
                                    opaque: false,
27672×
                                },
27682×
                            });
27692×
                        }
27702×
                        self.edits.push(Edit::Replace {
27712×
                            node,
27722×
                            old: current,
27732×
                            new: None,
27742×
                        });
27752×
                        if !e.content.is_empty() {
27762×
                            self.edits.push(Edit::Insert {
27772×
                                node,
27782×
                                after: crate::objects::AtomRef::Start,
27792×
                                before: crate::objects::AtomRef::End,
27802×
                                lines: crate::lines::Lines::split(&e.content),
27812×
                            });
27822×
                        }
2783
                    } else {
278432×
                        let blob = self.blob_of(repo, path, e, nocompress)?;
278532×
                        self.edits.push(Edit::Replace {
278632×
                            node,
278732×
                            old: current,
278832×
                            new: Some(blob),
278932×
                        });
2790
                        // New contents and a new executable bit at once: the
2791
                        // bit was dropped (VS Code's inno_updater.exe,
2792
                        // 2018-02-28, lost +x for 49 commits; oxygen#87).
279332×
                        if e.kind == NodeKind::File && e.exec != expected.mode.exec {
27942×
                            if let Some(old) = mode_atom {
27952×
                                self.tree_ops.push(TreeOp::SetMode {
27962×
                                    node,
27972×
                                    old,
27982×
                                    mode: Mode {
27992×
                                        exec: e.exec,
28002×
                                        opaque: true,
28012×
                                    },
28022×
                                });
28032×
                            }
280430×
                        }
2805
                    }
280634×
                    status = Some(ChangeStatus::Modified);
2807194×
                } else if e.kind == NodeKind::File && e.exec != expected.mode.exec {
28080×
                    if let Some(old) = mode_atom {
28090×
                        self.tree_ops.push(TreeOp::SetMode {
28100×
                            node,
28110×
                            old,
28120×
                            mode: Mode {
28130×
                                exec: e.exec,
28140×
                                opaque: true,
28150×
                            },
28160×
                        });
28170×
                        status = Some(ChangeStatus::ModeChanged);
28180×
                    }
2819194×
                }
2820
            }
2821
        }
28228576×
        if let Some(s) = status {
2823856×
            self.statuses.push(PathStatus {
2824856×
                path: path.to_string(),
2825856×
                status: s,
2826856×
            });
28277720×
        }
28288576×
        Ok(())
282912862×
    }
2830
}
2831
28322×
fn repo_live_keys(base: &State, node: &NodeId) -> Vec<crate::graph::AtomKey> {
28332×
    base.live_lines(node).into_iter().map(|(k, _)| k).collect()
28342×
}
2835
2836
/// The changes a change's scope references (spec §8.1): introducers of every
2837
/// atom, placement, and mode it touches, and of every node it operates on.
28382188×
pub fn referenced_changes(change: &Change, base: &State) -> BTreeSet<ChangeHash> {
28392188×
    let mut out = BTreeSet::new();
28402188×
    let opref = |r: &OpRef, out: &mut BTreeSet<ChangeHash>| {
2841217×
        if !r.change.is_zero() {
2842217×
            out.insert(r.change);
2843217×
        }
2844217×
    };
28452188×
    let mut nodes: Vec<NodeId> = Vec::new();
28466688×
    for op in &change.tree_ops {
28476688×
        match op {
28486471×
            TreeOp::AddNode { parent, .. } => nodes.push(*parent),
2849166×
            TreeOp::RemoveNode { node, placement } => {
2850166×
                nodes.push(*node);
2851166×
                opref(placement, &mut out);
2852166×
            }
2853
            TreeOp::Move {
285439×
                node, old, parent, ..
285539×
            } => {
285639×
                nodes.push(*node);
285739×
                nodes.push(*parent);
285839×
                opref(old, &mut out);
285939×
            }
286012×
            TreeOp::SetMode { node, old, .. } => {
286112×
                nodes.push(*node);
286212×
                opref(old, &mut out);
286312×
            }
2864
        }
2865
    }
28668264×
    for e in &change.edits {
28678264×
        nodes.push(e.node());
2868139×
        match e {
28697555×
            Edit::Insert { after, before, .. } => {
287015110×
                for r in [after, before] {
287115110×
                    if let crate::objects::AtomRef::Atom { change, .. } = r {
28722202×
                        if !change.is_zero() {
28732199×
                            out.insert(*change);
28742199×
                        }
287512908×
                    }
2876
                }
2877
            }
2878570×
            Edit::Delete { atoms, .. } => {
2879
                // Deleting an atom also depends on whoever inserted the live
2880
                // atoms right after it: the author saw those insertions, and
2881
                // without the dependency spec §9.1 would call the deletion
2882
                // concurrent with them (a delete/insert conflict).
2883570×
                let graph = base.file(&e.node());
28841125×
                for r in atoms {
28851125×
                    if !r.change.is_zero() {
28861124×
                        out.insert(r.change);
28871124×
                    }
28881125×
                    if let Some(g) = graph {
28891156×
                        for i in r.from..r.to {
28901156×
                            out.extend(
28911156×
                                g.live_successor_changes(&(r.change, i))
28921156×
                                    .into_iter()
28931156×
                                    .filter(|c| !c.is_zero()),
2894
                            );
2895
                        }
28960×
                    }
2897
                }
2898
            }
2899
            // Replacing a blob depends on the change that made it current,
2900
            // as deleting a line depends on the line's introducer.
2901
            Edit::Replace {
290239×
                node,
290339×
                old: Some(old),
2904
                ..
2905
            } => {
290639×
                out.extend(
290739×
                    base.live_replaces(node)
290839×
                        .into_iter()
290946×
                        .filter(|(c, b)| b == old && !c.is_zero())
291039×
                        .map(|(c, _)| c),
2911
                );
2912
            }
2913100×
            Edit::Replace { .. } => {}
2914
        }
2915
    }
291614991×
    for n in nodes {
291714991×
        if let Some(h) = base.tree().introducer(&n) {
29182277×
            out.insert(h);
291912714×
        }
2920
    }
29212188×
    out
29222188×
}
2923
2924
/// Paths of the nodes a change adds on top of `base_snapshot`.
29251370×
pub fn added_node_paths(
29261370×
    change: &Change,
29271370×
    base_snapshot: &Snapshot,
29281370×
) -> HashMap<String, (NodeId, NodeKind)> {
29291370×
    let by_node = base_snapshot.tree.by_node();
29301370×
    let mut new_names: HashMap<NodeId, (NodeId, String, NodeKind)> = HashMap::new();
29311370×
    for op in &change.tree_ops {
2932
        if let TreeOp::AddNode {
293389×
            node,
293489×
            parent,
293589×
            name,
293689×
            kind,
2937
            ..
2938121×
        } = op
293989×
        {
294089×
            new_names.insert(*node, (*parent, name.clone(), *kind));
294189×
        }
2942
    }
29431370×
    let mut out = HashMap::new();
29441370×
    for (node, (_, _, kind)) in &new_names {
294589×
        if let Some(path) = path_of_node(node, &by_node, &new_names) {
294689×
            out.insert(path, (*node, *kind));
294789×
        }
2948
    }
29491370×
    out
29501370×
}
2951
2952
/// Whether `op` retires a node `base_snapshot` shows as one with another
2953
/// (spec §9.2): part of touching that node, never a removal the user made.
295437×
fn is_unified_retirement(op: &TreeOp, base_snapshot: &Snapshot) -> bool {
29558×
    matches!(op, TreeOp::RemoveNode { node, .. } if base_snapshot.tree.unified.contains_key(node))
295637×
}
2957
2958223×
fn path_of_node(
2959223×
    n: &NodeId,
2960223×
    by_node: &HashMap<NodeId, &crate::tree::TreeEntry>,
2961223×
    new_names: &HashMap<NodeId, (NodeId, String, NodeKind)>,
2962223×
) -> Option<String> {
2963223×
    if let Some(e) = by_node.get(n) {
296468×
        return Some(e.path.clone());
2965155×
    }
2966155×
    let mut parts = Vec::new();
2967155×
    let mut cur = *n;
2968
    loop {
2969306×
        if cur.is_root() {
2970138×
            break;
2971168×
        }
2972168×
        if let Some(e) = by_node.get(&cur) {
29730×
            if !e.path.is_empty() {
29740×
                parts.push(e.path.clone());
29750×
            }
29760×
            break;
2977168×
        }
2978168×
        let (parent, name, _) = new_names.get(&cur)?;
2979151×
        parts.push(name.clone());
2980151×
        cur = *parent;
2981
    }
2982138×
    parts.reverse();
2983138×
    Some(parts.join("/"))
2984223×
}
2985
2986
/// Render a change's operations with line content, using `base` for deleted lines.
298733×
pub fn render_change(change: &Change, base: &State, base_snapshot: &Snapshot) -> String {
298833×
    let by_node = base_snapshot.tree.by_node();
298933×
    let mut new_names: HashMap<NodeId, (NodeId, String, NodeKind)> = HashMap::new();
299033×
    for op in &change.tree_ops {
2991
        if let TreeOp::AddNode {
299216×
            node,
299316×
            parent,
299416×
            name,
299516×
            kind,
2996
            ..
299724×
        } = op
299816×
        {
299916×
            new_names.insert(*node, (*parent, name.clone(), *kind));
300016×
        }
3001
    }
300273×
    let path_of = |n: &NodeId| -> String {
300373×
        path_of_node(n, &by_node, &new_names).unwrap_or_else(|| format!("<node {}>", n.short(8)))
300473×
    };
3005
300633×
    let mut out = String::new();
300733×
    for op in change
300833×
        .tree_ops
300933×
        .iter()
301033×
        .filter(|o| !is_unified_retirement(o, base_snapshot))
3011
    {
301223×
        match op {
3013
            TreeOp::AddNode {
301416×
                node, kind, mode, ..
3015
            } => {
301616×
                out.push_str(&format!(
3017
                    "A {} ({:?}{}{})\n",
301816×
                    path_of(node),
3019
                    kind,
302016×
                    if mode.exec { ", exec" } else { "" },
302116×
                    if mode.opaque { ", opaque" } else { "" }
3022
                ));
3023
            }
30245×
            TreeOp::RemoveNode { node, .. } => out.push_str(&format!("D {}\n", path_of(node))),
3025
            TreeOp::Move {
30262×
                node, parent, name, ..
3027
            } => {
30282×
                let to = if parent.is_root() {
30290×
                    name.clone()
3030
                } else {
30312×
                    format!("{}/{name}", path_of(parent))
3032
                };
30332×
                out.push_str(&format!("R {} -> {to}\n", path_of(node)))
3034
            }
30350×
            TreeOp::SetMode { node, mode, .. } => {
30360×
                out.push_str(&format!(
30370×
                    "M {} mode: exec={} opaque={}\n",
30380×
                    path_of(node),
30390×
                    mode.exec,
30400×
                    mode.opaque
30410×
                ));
30420×
            }
3043
        }
3044
    }
3045
    // Every other file the change edits is modified: the summary names
3046
    // every path it touches, not only those with a tree operation.
304733×
    let with_op: HashSet<NodeId> = change.tree_ops.iter().map(|o| o.node()).collect();
304833×
    let mut listed: HashSet<NodeId> = HashSet::new();
304936×
    for e in &change.edits {
305036×
        let n = e.node();
305136×
        if !with_op.contains(&n) && listed.insert(n) {
305221×
            out.push_str(&format!("M {}\n", path_of(&n)));
305321×
        }
3054
    }
305533×
    let mut last_node: Option<NodeId> = None;
305636×
    for e in &change.edits {
305736×
        let n = e.node();
305836×
        if last_node != Some(n) {
305927×
            out.push_str(&format!("--- {}\n", path_of(&n)));
306027×
            last_node = Some(n);
306127×
        }
306236×
        match e {
306327×
            Edit::Insert { lines, .. } => {
306432×
                for l in lines.iter() {
306532×
                    out.push('+');
306632×
                    out.push_str(&String::from_utf8_lossy(l));
306732×
                    if !l.ends_with(b"\n") {
30680×
                        out.push('\n');
306932×
                    }
3070
                }
3071
            }
30728×
            Edit::Delete { atoms, .. } => {
30738×
                for r in atoms {
30748×
                    for i in r.from..r.to {
30758×
                        let content = base
30768×
                            .file(&n)
30778×
                            .and_then(|g| g.content(&(r.change, i)))
30788×
                            .unwrap_or(b"<unknown>\n");
30798×
                        out.push('-');
30808×
                        out.push_str(&String::from_utf8_lossy(content));
30818×
                        if !content.ends_with(b"\n") {
30820×
                            out.push('\n');
30838×
                        }
3084
                    }
3085
                }
3086
            }
30871×
            Edit::Replace { old, new, .. } => {
30881×
                out.push_str(&format!(
3089
                    "  opaque content {} -> {}\n",
30901×
                    old.map(|o| o.short(12)).unwrap_or_else(|| "none".into()),
30911×
                    new.map(|o| o.short(12)).unwrap_or_else(|| "none".into())
3092
                ));
3093
            }
3094
        }
3095
    }
309633×
    out
309733×
}
3098
3099
/// Pair removed files with added files of the same kind whose contents are
3100
/// at least `RENAME_THRESHOLD` percent alike, best matches first. Beyond
3101
/// `RENAME_LIMIT` candidate pairs only identical contents are paired.
3102
const RENAME_THRESHOLD: u32 = 50;
3103
const RENAME_LIMIT: usize = 10_000;
3104
3105
/// How a change is built beyond its entries: for a Git import, the seed
3106
/// its new nodes' identifiers derive from; and, when it is built from part
3107
/// of the tree, whether the new tree has anything under a directory.
3108
#[derive(Default)]
3109
struct Scope<'a> {
3110
    seed: Option<[u8; 32]>,
3111
    dir_needed: Option<&'a dyn Fn(&str) -> bool>,
3112
}
3113
31142123×
fn detect_renames(
31152123×
    base_snapshot: &Snapshot,
31162123×
    fs_entries: &BTreeMap<String, FsEntry>,
31172123×
    in_scope: impl Fn(&str) -> bool,
31182123×
) -> Vec<(String, String)> {
31192123×
    let removed: Vec<(&String, &crate::state::FileState)> = base_snapshot
31202123×
        .files
31212123×
        .iter()
312213391×
        .filter(|(p, f)| {
312313391×
            f.kind != NodeKind::Dir
312412983×
                && !fs_entries.contains_key(*p)
3125157×
                && in_scope(p)
3126147×
                && !f.is_conflicted()
312713391×
        })
31282123×
        .collect();
31292123×
    let added: Vec<(&String, &FsEntry)> = fs_entries
31302123×
        .iter()
313118970×
        .filter(|(p, e)| e.kind != NodeKind::Dir && !base_snapshot.files.contains_key(*p))
31322123×
        .collect();
31332123×
    if removed.is_empty() || added.is_empty() {
31342063×
        return vec![];
313560×
    }
313660×
    let exact_only = removed.len() * added.len() > RENAME_LIMIT;
313774×
    let old_content = |f: &crate::state::FileState| -> Option<Vec<u8>> {
313874×
        match &f.content {
313970×
            FileContent::Text { bytes, .. } => Some(bytes.clone()),
31404×
            _ => None,
3141
        }
314274×
    };
314360×
    let mut scored: Vec<(u32, usize, usize)> = Vec::new();
314474×
    for (ri, (_, f)) in removed.iter().enumerate() {
314574×
        let old = old_content(f);
314674×
        let old_blob = match &f.content {
31474×
            FileContent::Opaque { blobs } if blobs.len() == 1 => Some(blobs[0]),
314870×
            _ => None,
3149
        };
315093×
        for (ai, (_, e)) in added.iter().enumerate() {
315193×
            if e.kind != f.kind {
31520×
                continue;
315393×
            }
315493×
            let score = match (&old, old_blob) {
315583×
                (Some(o), _) => {
315683×
                    if exact_only {
31570×
                        if *o == *e.content {
31580×
                            100
3159
                        } else {
31600×
                            0
3161
                        }
3162
                    } else {
316383×
                        similarity(o, &e.content)
3164
                    }
3165
                }
316610×
                (None, Some(b)) if e.blob.unwrap_or_else(|| Repo::blob_ref(&e.content)) == b => 100,
31677×
                _ => 0,
3168
            };
316993×
            if score >= RENAME_THRESHOLD {
317042×
                scored.push((score, ri, ai));
317151×
            }
3172
        }
3173
    }
317460×
    scored.sort_by(|a, b| {
31759×
        b.0.cmp(&a.0)
31769×
            .then(removed[a.1].0.cmp(removed[b.1].0))
31779×
            .then(added[a.2].0.cmp(added[b.2].0))
31789×
    });
317960×
    let mut used_r = vec![false; removed.len()];
318060×
    let mut used_a = vec![false; added.len()];
318160×
    let mut out = Vec::new();
318260×
    for (_, ri, ai) in scored {
318342×
        if used_r[ri] || used_a[ai] {
31846×
            continue;
318536×
        }
318636×
        used_r[ri] = true;
318736×
        used_a[ai] = true;
318836×
        out.push((removed[ri].0.clone(), added[ai].0.clone()));
3189
    }
319060×
    out
31912123×
}
3192
3193
/// Percentage of the larger file's bytes found in lines the two share
3194
/// (multiset intersection of lines), like Git's similarity index.
319587×
pub fn similarity(a: &[u8], b: &[u8]) -> u32 {
319687×
    if a == b {
319725×
        return 100;
319862×
    }
319962×
    if a.is_empty() || b.is_empty() {
32001×
        return 0;
320161×
    }
320261×
    let mut counts: HashMap<&[u8], usize> = HashMap::new();
3203119×
    for l in split_lines(a) {
3204119×
        *counts.entry(l).or_default() += 1;
3205119×
    }
320661×
    let mut shared = 0usize;
3207113×
    for l in split_lines(b) {
3208113×
        if let Some(n) = counts.get_mut(l) {
320943×
            if *n > 0 {
321043×
                *n -= 1;
321143×
                shared += l.len();
321243×
            }
321370×
        }
3214
    }
321561×
    (shared * 100 / a.len().max(b.len())) as u32
321687×
}
3217
3218
#[cfg(test)]
3219
mod join_tests {
3220
    use super::*;
3221
3222
    #[test]
32231×
    fn missing_from_finds_what_the_other_lacks() {
32241×
        let a: BTreeMap<String, u8> = [("a", 1), ("b", 2), ("c/d", 3), ("e", 4)]
32251×
            .into_iter()
32264×
            .map(|(k, v)| (k.to_string(), v))
32271×
            .collect();
32281×
        let b: BTreeMap<String, ()> = [("0", ()), ("b", ()), ("c", ()), ("e", ())]
32291×
            .into_iter()
32304×
            .map(|(k, v)| (k.to_string(), v))
32311×
            .collect();
32321×
        let got: Vec<&str> = missing_from(&a, &b)
32331×
            .iter()
32342×
            .map(|(k, _)| k.as_str())
32351×
            .collect();
32361×
        assert_eq!(got, vec!["a", "c/d"]);
32371×
    }
3238
3239
    #[test]
32401×
    fn join_pairs_every_key_in_order() {
32411×
        let a: BTreeMap<String, u8> = [("a", 1), ("b/c", 2), ("d", 3)]
32421×
            .into_iter()
32433×
            .map(|(k, v)| (k.to_string(), v))
32441×
            .collect();
32451×
        let b: BTreeMap<String, char> = [("b", 'x'), ("b/c", 'y'), ("e", 'z')]
32461×
            .into_iter()
32473×
            .map(|(k, v)| (k.to_string(), v))
32481×
            .collect();
32491×
        let got: Vec<(String, Option<u8>, Option<char>)> = join(&a, &b)
32505×
            .map(|(k, x, y)| (k.clone(), x.copied(), y.copied()))
32511×
            .collect();
32521×
        let want = vec![
32531×
            ("a".to_string(), Some(1), None),
32541×
            ("b".to_string(), None, Some('x')),
32551×
            ("b/c".to_string(), Some(2), Some('y')),
32561×
            ("d".to_string(), Some(3), None),
32571×
            ("e".to_string(), None, Some('z')),
3258
        ];
32591×
        assert_eq!(got, want);
32601×
    }
3261
}