OXYGENHUB

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

2199 of 2430 lines run, 283 of 373 functions · run #278 on main · run missed

1
//! Working-copy snapshots, commits, and the change builder (spec §12.3).
2
3
use super::*;
4
use crate::objects::AtomRef;
5
6
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
7
pub enum ChangeStatus {
8
    Added,
9
    Modified,
10
    Removed,
11
    /// Moved from another path (detected by similarity, tracked as a placement change).
12
    Renamed,
13
    ModeChanged,
14
    /// The file is conflicted in the base state and still contains conflict markers.
15
    ConflictEdited,
16
    /// The file was conflicted in the base state and the working copy resolves it.
17
    Resolved,
18
}
19
20
/// Lines that mark a conflict region in a materialized file (spec §9.5).
2128×
pub fn has_conflict_markers(content: &[u8]) -> bool {
2278×
    split_lines(content).iter().any(|l| {
2378×
        l.starts_with(b"<<<<<<< oxy conflict")
2473×
            || l.starts_with(b"======= oxy conflict")
2573×
            || l.starts_with(b">>>>>>> oxy conflict")
2678×
    })
2728×
}
28
29
#[derive(Clone, Debug, PartialEq, Eq)]
30
pub struct PathStatus {
31
    pub path: String,
32
    pub status: ChangeStatus,
33
}
34
35
/// Operations of a change built from the working directory against a base.
36
pub(crate) struct BuiltChange {
37
    pub tree_ops: Vec<TreeOp>,
38
    pub edits: Vec<Edit>,
39
    pub contributors: Vec<ChangeHash>,
40
    pub resolves: bool,
41
    pub statuses: Vec<PathStatus>,
42
    /// The stored blob of every opaque path, for the manifest's stat cache.
43
    pub blobs: HashMap<String, ObjectRef>,
44
}
45
46
/// Result of snapshotting the working copy.
47
pub struct SnapshotResult {
48
    /// The working-copy change's hash; for a commit's own snapshot, which
49
    /// does not encode it, the hash it had before.
50
    pub wc_hash: ChangeHash,
51
    pub wc: Change,
52
    /// The base state (closure of the working-copy change's dependencies).
53
    pub base: State,
54
    pub base_snapshot: Snapshot,
55
    pub statuses: Vec<PathStatus>,
56
    /// Whether the snapshot rewrote the working-copy change.
57
    pub changed: bool,
58
    /// Whether the working copy resolves conflicts of its base (spec §9.6).
59
    pub resolves: bool,
60
    /// Changes that contributed to the conflicts being resolved.
61
    pub contributors: Vec<ChangeHash>,
62
    /// The `.oxyattributes` in force on disk, from the files the walk read.
63
    pub(crate) attributes: crate::attributes::Attributes,
64
    /// Folders holding a repository of their own (`.git` or `.oxy`) that
65
    /// are not subrepos, so nothing in them is tracked (oxygen#43).
66
    pub untracked_nested: Vec<String>,
67
    /// A commit's snapshot leaves the manifest to the commit, which writes
68
    /// it once with the new base's graph keys.
69
    pub(crate) manifest: Option<PendingManifest>,
70
}
71
72
/// The manifest a commit's snapshot would have written, as of the moment
73
/// it would have written it (that moment is the racy-window stamp).
74
pub(crate) struct PendingManifest {
75
    entries: BTreeMap<String, FsEntry>,
76
    blobs: HashMap<String, ObjectRef>,
77
    dirs: Option<super::WalkedDirs>,
78
    written: u128,
79
}
80
8122730×
pub fn is_binary(content: &[u8]) -> bool {
8222730×
    content[..content.len().min(BINARY_SNIFF)].contains(&0)
8322730×
}
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.
1051272×
    fn platform_normalize(&self, entries: &mut BTreeMap<String, FsEntry>, base: &Snapshot) {
1061272×
        let p = self.platform;
1071272×
        if p.exec_bits && p.symlinks {
1081270×
            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
        }
1221272×
    }
123
124
    /// Like `build_against`, for files given in memory (imports).
1251003×
    pub(crate) fn build_from_entries(
1261003×
        &self,
1271003×
        base: &State,
1281003×
        base_snapshot: &Snapshot,
1291003×
        reuse: HashMap<String, (NodeId, NodeKind)>,
1301003×
        fs_entries: &BTreeMap<String, FsEntry>,
1311003×
    ) -> Result<BuiltChange> {
1321003×
        self.build_from_entries_resolving(base, base_snapshot, reuse, fs_entries, &HashSet::new())
1331003×
    }
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.
1401017×
    pub(crate) fn build_from_entries_resolving(
1411017×
        &self,
1421017×
        base: &State,
1431017×
        base_snapshot: &Snapshot,
1441017×
        reuse: HashMap<String, (NodeId, NodeKind)>,
1451017×
        fs_entries: &BTreeMap<String, FsEntry>,
1461017×
        resolve: &HashSet<String>,
1471017×
    ) -> Result<BuiltChange> {
1481017×
        self.build_from_entries_with(
1491017×
            base,
1501017×
            base_snapshot,
1511017×
            reuse,
1521017×
            fs_entries,
1531017×
            resolve,
1541017×
            Scope::default(),
155
        )
1561017×
    }
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.
192834×
    fn build_changed_only(
193834×
        &self,
194834×
        base: &State,
195834×
        base_snapshot: &Snapshot,
196834×
        reuse: HashMap<String, (NodeId, NodeKind)>,
197834×
        fs_entries: &BTreeMap<String, FsEntry>,
198834×
    ) -> Result<BuiltChange> {
199834×
        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.
202834×
        let changed: BTreeMap<String, FsEntry> = join(fs_entries, &base_snapshot.files)
20310987×
            .filter_map(|(p, e, f)| {
20410987×
                let e = e?;
20510858×
                (!e.unchanged || f.is_none_or(|f| f.kind != e.kind || f.mode.exec != e.exec))
20610858×
                    .then(|| (p.clone(), e.clone()))
20710987×
            })
208834×
            .collect();
209834×
        let mut files: BTreeMap<String, crate::state::FileState> = BTreeMap::new();
2106627×
        for p in changed.keys() {
2116627×
            if let Some(f) = base_snapshot.files.get(p) {
2123648×
                files.insert(p.clone(), f.clone());
2133648×
            }
214
        }
215
        // Paths the base has and the disk does not.
216834×
        let gone = join(&base_snapshot.files, fs_entries)
21710987×
            .filter_map(|(p, f, e)| (e.is_none()).then_some((p, f?)));
218834×
        for (p, f) in gone {
219129×
            if f.kind == NodeKind::Dir {
22096×
                continue;
22133×
            }
22233×
            files.insert(p.clone(), f.clone());
22333×
            let mut end = p.len();
22438×
            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
        }
235834×
        let part = Snapshot {
236834×
            tree: base_snapshot.tree.clone(),
237834×
            files,
238834×
            unrendered: BTreeSet::new(),
239834×
        };
240834×
        drop(pick);
241834×
        let _build = crate::timing::phase("snapshot:   of which building the change");
242
        // Whether anything on disk is under `dir`.
243834×
        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×
        };
250834×
        self.build_from_entries_with(
251834×
            base,
252834×
            &part,
253834×
            reuse,
254834×
            &changed,
255834×
            &HashSet::new(),
256834×
            Scope {
257834×
                seed: None,
258834×
                dir_needed: Some(&dir_needed),
259834×
            },
260
        )
261834×
    }
262
2631939×
    fn build_from_entries_with(
2641939×
        &self,
2651939×
        base: &State,
2661939×
        base_snapshot: &Snapshot,
2671939×
        reuse: HashMap<String, (NodeId, NodeKind)>,
2681939×
        fs_entries: &BTreeMap<String, FsEntry>,
2691939×
        resolve: &HashSet<String>,
2701939×
        scope: Scope,
2711939×
    ) -> Result<BuiltChange> {
2721939×
        let Scope { seed, dir_needed } = scope;
2731939×
        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.
2761939×
        let attrs = crate::attributes::Attributes::from_files(
2771939×
            fs_entries
2781939×
                .iter()
27918664×
                .filter(|(p, _)| p.as_str() == ".oxyattributes" || p.ends_with("/.oxyattributes"))
2801939×
                .map(|(p, e)| (p.as_str(), e.content.as_slice())),
281
        );
2821939×
        let mut b = ChangeBuilder::new(base, base_snapshot, reuse).with_attributes(attrs);
2831939×
        b.resolve = resolve.clone();
2841939×
        b.node_seed = seed;
2851939×
        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.
2891939×
        let renames = detect_renames(base_snapshot, fs_entries, |p| self.in_scope(p));
2901939×
        let renamed_from: HashMap<&str, &str> = renames
2911939×
            .iter()
2921939×
            .map(|(old, new)| (new.as_str(), old.as_str()))
2931939×
            .collect();
2941939×
        let renamed_to: HashMap<&str, &str> = renames
2951939×
            .iter()
2961939×
            .map(|(old, new)| (old.as_str(), new.as_str()))
2971939×
            .collect();
2981939×
        laps.lap("build: renames");
2991939×
        b.diff_in_parallel(fs_entries);
3001939×
        laps.lap("build: diffs");
30118664×
        for (path, fs_entry) in fs_entries {
30218664×
            match base_snapshot.files.get(path) {
3036012×
                None => match renamed_from.get(path.as_str()) {
30432×
                    Some(old) => {
30532×
                        b.move_path(self, old, path, fs_entry, &base_snapshot.files[*old])?
306
                    }
3075980×
                    None => b.add_path(self, path, fs_entry)?,
308
                },
30912652×
                Some(expected) => b.update_path(self, path, fs_entry, expected)?,
310
            }
311
        }
3121939×
        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.
3151939×
        let mut needed_dirs: HashSet<&str> = HashSet::new();
31618677×
        fn parents_of<'a>(p: &'a str, set: &mut HashSet<&'a str>) {
31718677×
            let mut end = p.len();
31819326×
            while let Some(i) = p[..end].rfind('/') {
31915431×
                if !set.insert(&p[..i]) {
32014782×
                    break;
321649×
                }
322649×
                end = i;
323
            }
32418677×
        }
32518664×
        for p in fs_entries.keys() {
32618664×
            parents_of(p, &mut needed_dirs);
32718664×
        }
32813219×
        for p in base_snapshot.files.keys() {
32913219×
            if !self.in_scope(p) {
33013×
                parents_of(p, &mut needed_dirs);
33113206×
            }
332
        }
33313219×
        for (path, expected) in &base_snapshot.files {
33413219×
            if fs_entries.contains_key(path)
335567×
                || !self.in_scope(path)
336554×
                || renamed_to.contains_key(path.as_str())
337
            {
33812697×
                continue;
339522×
            }
340522×
            let still_needed = expected.kind == NodeKind::Dir
341412×
                && match dir_needed {
34221×
                    Some(f) => f(path),
343391×
                    None => needed_dirs.contains(path.as_str()),
344
                };
345522×
            if !still_needed {
346137×
                b.remove_path(path, expected);
347385×
            }
348
        }
3491939×
        laps.lap("build: removals");
3501939×
        if seed.is_some() {
35188×
            b.retire_stray_placements();
3521851×
        }
3531939×
        laps.lap("build: stray placements");
3541939×
        let mut statuses = b.statuses;
3555637×
        statuses.sort_by(|a, b| a.path.cmp(&b.path));
3561939×
        Ok(BuiltChange {
3571939×
            tree_ops: b.tree_ops,
3581939×
            edits: b.edits,
3591939×
            contributors: b.contributors.into_iter().collect(),
3601939×
            resolves: b.resolves,
3611939×
            statuses,
3621939×
            blobs: b.blobs,
3631939×
        })
3641939×
    }
365
366
    /// Store a change and, when `core.sign = change` and we are its author,
367
    /// sign it. A rewritten change by another author is stored unsigned: only
368
    /// its author (or a delegate) can vouch for it.
369676×
    pub(crate) fn store_signed(&self, change: &Change) -> Result<ChangeHash> {
370676×
        let ours = change.author == self.author();
371676×
        if self.config.sign_changes && ours && self.secret_key()?.is_none() {
3721×
            return fail("core.sign is \"change\" but no secret key is available for author.key");
373675×
        }
374675×
        let storing = crate::timing::phase("store: the change");
375675×
        let hash = self.store.put_change(change)?;
376675×
        drop(storing);
377675×
        if self.config.sign_changes && ours {
37840×
            let _t = crate::timing::phase("store: sign it");
37940×
            self.sign_change(&hash)?;
380635×
        }
381675×
        Ok(hash)
382676×
    }
383
384
    /// Snapshot the working copy into the working-copy change (spec §12.3).
385
    /// The result carries the full base state and its whole rendering.
386436×
    pub fn snapshot(&self, command: &str) -> Result<SnapshotResult> {
387436×
        self.snapshot_as(command, false, false)
388436×
    }
389
390
    /// Snapshot the working copy as [`Repo::snapshot`] does, for commands
391
    /// that need its statuses, conflicts and base history, and the graphs
392
    /// of the files it changes: status, log, show, commit, diff, hunks and
393
    /// discard. Text files known unchanged since the last manifest are
394
    /// neither read nor rendered: the result's `base` is a history-only
395
    /// state without their graphs, and its `base_snapshot` lists them in
396
    /// `unrendered` with empty bytes. They are never conflicted, and no
397
    /// change the working copy makes touches them.
398402×
    pub fn snapshot_status(&self, command: &str) -> Result<SnapshotResult> {
399402×
        self.snapshot_as(command, true, false)
400402×
    }
401
402
    /// `snapshot_as`; `for_commit` writes the manifest even where a status
403
    /// would not bother (an edited file is read next time whatever it
404
    /// says), since after the commit that file is unchanged, and records no
405
    /// operation: the commit's own, recorded straight after, replaces the
406
    /// working copy, so the snapshot's would cost a durable write for
407
    /// nothing. Should the commit fail, the files are still on disk and the
408
    /// next snapshot finds them.
4091273×
    fn snapshot_as(
4101273×
        &self,
4111273×
        command: &str,
4121273×
        partial: bool,
4131273×
        for_commit: bool,
4141273×
    ) -> Result<SnapshotResult> {
4151273×
        let _lock = self.lock_snapshot()?;
4161273×
        let batch = self.store.begin_batch()?;
4171273×
        let result = self.snapshot_locked(command, partial, for_commit);
4181273×
        batch.finish()?;
4191273×
        result
4201273×
    }
421
4221273×
    fn snapshot_locked(
4231273×
        &self,
4241273×
        command: &str,
4251273×
        partial: bool,
4261273×
        for_commit: bool,
4271273×
    ) -> Result<SnapshotResult> {
4281273×
        let _all = crate::timing::phase("snapshot");
4291273×
        let (op_ref, op) = self.head_op()?;
4301273×
        let (old_hash, old_wc) = self.working_copy()?;
431
        // The base's history first: its graph keys say which files the
432
        // manifest already knows equal to it.
4331271×
        let mut base = {
4341271×
            let _t = crate::timing::phase("snapshot: load base history");
4351271×
            self.load_state_indexed(&old_wc.deps)?
436
        };
4371271×
        let view = {
4381271×
            let _t = crate::timing::phase("snapshot: tree view");
4391271×
            base.tree().view()
440
        };
4411271×
        let manifest = {
4421271×
            let _t = crate::timing::phase("snapshot: read manifest");
4431271×
            self.read_manifest()?.map(|(_, _, m)| m)
444
        };
4451271×
        let tracked: BTreeMap<String, (NodeKind, Option<ObjectRef>)> = {
4461271×
            let _t = crate::timing::phase("snapshot: tracked paths");
447
            // In the view's path order, so the map is built without searching.
4481271×
            view.entries
4491271×
                .iter()
4509471×
                .filter(|(_, e)| e.kind != NodeKind::Dir)
4519084×
                .map(|(p, e)| {
4529084×
                    let blob = if e.kind != NodeKind::File || e.mode.opaque {
453151×
                        base.live_blobs(&e.node).first().copied()
454
                    } else {
4558933×
                        None
456
                    };
4579084×
                    (p.clone(), (e.kind, blob))
4589084×
                })
4591271×
                .collect()
460
        };
461
        // A text file's graph key, worked out when the walk asks for it.
46212070×
        let key_of = |p: &str| -> Option<[u8; 32]> {
46312070×
            let e = view.entries.get(p)?;
4648975×
            if e.kind != NodeKind::File || e.mode.opaque {
465124×
                return None;
4668851×
            }
4678851×
            base.graph_key(&e.node)
46812070×
        };
4691270×
        let mut fs_entries = {
4701271×
            let _t = crate::timing::phase("snapshot: read working copy");
4711271×
            self.walk_working_copy_with(manifest.as_deref(), &tracked, Some(&key_of))?
472
        };
473
        // The keys of the files read, before building graphs drops them: a
474
        // file found equal to its base rendering keeps its key.
4751270×
        let keys: HashMap<String, [u8; 32]> = fs_entries
4761270×
            .iter()
47712099×
            .filter(|(_, e)| !e.unchanged && e.kind == NodeKind::File)
4787827×
            .filter_map(|(p, _)| Some((p.clone(), key_of(p)?)))
4791270×
            .collect();
4801270×
        let base_snapshot = {
4811270×
            let _t = crate::timing::phase("snapshot: load and render base");
4821270×
            if partial {
483837×
                let sets = crate::timing::phase("snapshot:   of which choosing graphs");
484
                // Every file but those on disk known unchanged.
485837×
                let need: Vec<(&str, NodeId)> = join(&view.entries, &fs_entries)
48611002×
                    .filter_map(|(p, v, f)| {
48711002×
                        let v = v?;
4888022×
                        (v.kind == NodeKind::File && !f.is_some_and(|f| f.unchanged))
4898022×
                            .then_some((p.as_str(), v.node))
49011002×
                    })
491837×
                    .collect();
492837×
                let render: std::collections::HashSet<&str> =
493837×
                    need.iter().map(|(p, _)| *p).collect();
494837×
                let need: Vec<NodeId> = need.iter().map(|(_, n)| *n).collect();
495837×
                drop(sets);
496
                {
497837×
                    let _t = crate::timing::phase("snapshot:   of which building graphs");
498837×
                    self.load_graphs_of(&mut base, &need)?;
499
                }
500837×
                let _t = crate::timing::phase("snapshot:   of which rendering");
501837×
                base.materialize_only(&render)
502
            } else {
503433×
                self.load_all_graphs(&mut base)?;
504433×
                base.materialize()
505
            }
506
        };
507
508
        // Reuse the NodeIds the previous working-copy version assigned to new
509
        // paths, so an unchanged working copy hashes identically (spec §12.3).
5101270×
        let reuse = added_node_paths(&old_wc, &base_snapshot);
5111270×
        self.platform_normalize(&mut fs_entries, &base_snapshot);
5121270×
        let built = {
5131270×
            let _t = crate::timing::phase("snapshot: diff against base");
5141270×
            if partial && self.config.sparse_paths.is_empty() {
515
                #[cfg(test)]
516561×
                let full =
517561×
                    self.build_from_entries(&base, &base_snapshot, reuse.clone(), &fs_entries)?;
518834×
                let built = self.build_changed_only(&base, &base_snapshot, reuse, &fs_entries)?;
519
                #[cfg(test)]
520
                {
521
                    // New nodes take random identifiers: compare them by
522
                    // order of appearance.
5231122×
                    let norm = |b: &BuiltChange| {
5241122×
                        let text = format!("{:?} {:?} {:?}", b.tree_ops, b.edits, b.statuses);
5251122×
                        let mut seen: Vec<String> = Vec::new();
5261122×
                        let mut out = String::new();
5271122×
                        let mut rest = text.as_str();
52819694×
                        while let Some(i) = rest.find("NodeId(") {
52918572×
                            out.push_str(&rest[..i]);
53018572×
                            let end = i + rest[i..].find(')').unwrap() + 1;
53118572×
                            let id = rest[i..end].to_string();
5329045814×
                            let n = seen.iter().position(|x| *x == id).unwrap_or_else(|| {
5336952×
                                seen.push(id);
5346952×
                                seen.len() - 1
5356952×
                            });
53618572×
                            out.push_str(&format!("N{n}"));
53718572×
                            rest = &rest[end..];
538
                        }
5391122×
                        out.push_str(rest);
5401122×
                        out
5411122×
                    };
542561×
                    assert_eq!(
543561×
                        norm(&built),
544561×
                        norm(&full),
545
                        "a changed-only build is the full one"
546
                    );
547
                }
548834×
                built
549
            } else {
550436×
                self.build_from_entries(&base, &base_snapshot, reuse, &fs_entries)?
551
            }
552
        };
553
        // Text files found equal to an unconflicted base rendering keep its
554
        // graph key, so the next snapshot need not read or render them.
555
        {
5563704×
            let changed: HashSet<&str> = built.statuses.iter().map(|s| s.path.as_str()).collect();
55712099×
            for (p, e) in fs_entries.iter_mut() {
55812099×
                if e.unchanged || e.kind != NodeKind::File || changed.contains(p.as_str()) {
5597872×
                    continue;
5604227×
                }
5614227×
                e.graph_key = match base_snapshot.files.get(p).map(|f| &f.content) {
562
                    Some(FileContent::Text {
5634115×
                        bytes,
5644115×
                        materialized,
5654115×
                    }) if !materialized.is_conflicted() && *bytes == *e.content => {
5664109×
                        keys.get(p).copied()
567
                    }
568118×
                    _ => None,
569
                };
570
            }
571
        }
572
5731270×
        let mut wc = Change {
5741270×
            version: crate::objects::CHANGE_VERSION,
5751270×
            change_id: old_wc.change_id,
5761270×
            deps: vec![],
5771270×
            author: self.author(),
5781270×
            hlc: old_wc.hlc,
5791270×
            message: old_wc.message.clone(),
5801270×
            tree_ops: built.tree_ops,
5811270×
            edits: built.edits,
5821270×
            kind: ChangeKind::WorkingCopy,
5831270×
        };
5841270×
        let base_heads = base.maximal(&old_wc.deps);
5851270×
        let mut deps: BTreeSet<ChangeHash> = base_heads.into_iter().collect();
5861270×
        deps.extend(referenced_changes(&wc, &base));
5871270×
        deps.extend(built.contributors.iter().copied());
5881270×
        wc.deps = deps.into_iter().collect();
5891270×
        wc.normalize();
5901270×
        let resolves = built.resolves;
5911270×
        let contributors = built.contributors;
5921270×
        let statuses = built.statuses;
593
        // Empty snapshot: hash the candidate before storing; only record an op on change.
5941270×
        let record = crate::timing::phase("snapshot: hash and record");
595
        // Encoded once, its texts stored a batch at a time as they are
596
        // made (a stored blob is not stored again); the change itself only
597
        // when it changed.
598
        // For a commit the change is neither encoded, stored nor recorded:
599
        // the commit stores its own, built from this one's operations, and
600
        // its texts with it. The hash it would have is not needed.
6011270×
        let (new_hash, changed, encoded) = if for_commit {
602435×
            (old_hash, true, Vec::new())
603
        } else {
604835×
            let encoded = wc.encode_streaming(|batch| self.store.put_texts(&batch))?;
605835×
            let new_hash = crate::hash::hash_object(crate::hash::ObjectType::Change, &encoded);
606835×
            (new_hash, new_hash != old_hash, encoded)
607
        };
6081270×
        if changed && !for_commit {
609297×
            self.store.put(crate::hash::ObjectType::Change, &encoded)?;
610297×
            let mut view = op.view.clone();
611297×
            view.workspaces.insert(self.workspace, new_hash);
612297×
            self.record_op(&[op_ref], &format!("{command}{SNAPSHOT_SUFFIX}"), view)?;
613973×
        }
6141270×
        drop(record);
615
        // The prompt compares against this without recording anything.
6161270×
        let _t = crate::timing::phase("snapshot: write manifest");
6171270×
        let conflicted = base_snapshot.is_conflicted();
6181270×
        let uncommitted = !wc.tree_ops.is_empty() || !wc.edits.is_empty();
619
        // Rewriting the manifest pays only when it would teach the next
620
        // snapshot something: other flags, a file found equal to the base
621
        // (it need not be read again), a new blob, a path added or gone.
622
        // An edited file is read next time whatever it says.
6231270×
        let worth = match self.read_manifest()? {
624435×
            _ if for_commit => true,
625312×
            None => true,
626523×
            Some((c, u, m)) => {
627523×
                c != conflicted
628523×
                    || u != uncommitted
629291×
                    || m.entries.len() != fs_entries.len()
630376×
                    || fs_entries.iter().any(|(p, e)| {
631376×
                        !e.unchanged && (e.graph_key.is_some() || !m.entries.contains_key(p))
632376×
                    })
63347×
                    || built
63447×
                        .blobs
63547×
                        .iter()
63647×
                        .any(|(p, b)| m.entries.get(p).and_then(|e| e.blob) != Some(*b))
637
                    // With uncommitted work, the status cache below holds
638
                    // only while the manifest describes the edited files as
639
                    // they are now.
64062×
                    || (uncommitted && statuses.iter().any(|st| {
64162×
                        let Some(e) = fs_entries.get(&st.path) else {
6423×
                            return m.entries.contains_key(&st.path);
643
                        };
64459×
                        let Some(me) = m.entries.get(&st.path) else {
6450×
                            return true;
646
                        };
64759×
                        let hash = e
64859×
                            .content_hash
64959×
                            .unwrap_or_else(|| *blake3::hash(&e.content).as_bytes());
65059×
                        let stat = e.stat.or_else(|| {
6510×
                            fs::symlink_metadata(self.root.join(&st.path))
6520×
                                .ok()
6530×
                                .map(|md| (md.len(), super::prompt::mtime_ns(&md)))
6540×
                        });
655
                        // The executable bit too: a mode change moves
656
                        // neither size nor time.
65759×
                        me.hash != hash || me.exec != e.exec || stat != Some((me.size, me.mtime_ns))
65862×
                    }))
659
            }
660
        };
6611270×
        let attributes = crate::attributes::Attributes::from_files(
6621270×
            fs_entries
6631270×
                .iter()
66412099×
                .filter(|(p, _)| is_attributes(p))
6651270×
                .map(|(p, e)| (p.as_str(), e.content.as_slice())),
666
        );
6671270×
        let mut manifest = None;
6681270×
        if for_commit {
669435×
            manifest = Some(PendingManifest {
670435×
                entries: fs_entries,
671435×
                blobs: built.blobs.clone(),
672435×
                dirs: self.walked_dirs.take(),
673435×
                written: super::prompt::now_ns(),
674435×
            });
675435×
        } else {
676835×
            if worth {
677791×
                self.write_manifest_entries(conflicted, uncommitted, &fs_entries, &built.blobs)?;
67844×
            }
679835×
            self.write_status_cache((uncommitted && !conflicted).then_some(&new_hash), &statuses);
680
        }
6811270×
        Ok(SnapshotResult {
6821270×
            wc_hash: new_hash,
6831270×
            wc,
6841270×
            base,
6851270×
            base_snapshot,
6861270×
            statuses,
6871270×
            changed,
6881270×
            resolves,
6891270×
            contributors,
6901270×
            attributes,
6911270×
            untracked_nested: self.untracked_nested.borrow().clone(),
6921270×
            manifest,
6931270×
        })
6941273×
    }
695
696
    /// `oxy status --json` (spec §9.5): the changed paths and every conflict
697
    /// of the working copy's base with its kind, path, and contributing
698
    /// ChangeIds.
6997×
    pub fn status_json(&self, snap: &SnapshotResult) -> Result<String> {
7007×
        let heads = self.bookmark_heads()?;
7017×
        let base_snapshot = &snap.base_snapshot;
7027×
        let by_node = base_snapshot.tree.by_node();
7037×
        let path_of = |n: &NodeId| by_node.get(n).map(|e| e.path.clone());
7047×
        let id_of = |h: &ChangeHash| {
7054×
            snap.base
7064×
                .get(h)
7074×
                .map(|m| m.change_id.to_hex())
7084×
                .unwrap_or_else(|| h.to_hex())
7094×
        };
7107×
        let paths = json_array(snap.statuses.iter().map(|s| {
7114×
            format!(
712
                "{{\"path\":{},\"status\":{}}}",
7134×
                json_str(&s.path),
7144×
                json_str(&format!("{:?}", s.status))
715
            )
7164×
        }));
7177×
        let mut conflicts: Vec<String> = Vec::new();
7187×
        for (p, f) in &base_snapshot.files {
7197×
            if !f.is_conflicted() {
7205×
                continue;
7212×
            }
7222×
            let (kind, changes) = match &f.content {
723
                FileContent::Text { .. } => {
7242×
                    ("text", snap.base.conflict_regions(&f.node).contributors)
725
                }
7260×
                FileContent::Opaque { blobs } => {
7270×
                    ("replace", snap.base.blob_contributors(&f.node, blobs))
728
                }
7290×
                FileContent::Dir => continue,
730
            };
7312×
            let resolved = match snap
7322×
                .statuses
7332×
                .iter()
7342×
                .find(|s| s.path == *p)
7352×
                .map(|s| s.status)
736
            {
7371×
                Some(ChangeStatus::Resolved) => "true",
7380×
                Some(ChangeStatus::ConflictEdited) => "\"markers\"",
7391×
                _ => "false",
740
            };
7412×
            conflicts.push(format!(
742
                "{{\"kind\":{},\"path\":{},\"node\":{},\"changes\":{},\"resolved\":{resolved}}}",
7432×
                json_str(kind),
7442×
                json_str(p),
7452×
                json_str(&f.node.to_hex()),
7464×
                json_array(changes.iter().map(|h| json_str(&id_of(h))))
747
            ));
748
        }
7497×
        for c in &base_snapshot.tree.conflicts {
7500×
            let (kind, nodes): (&str, Vec<NodeId>) = match c {
7510×
                crate::tree::TreeConflict::Name { nodes, .. } => ("name", nodes.clone()),
7520×
                crate::tree::TreeConflict::MultiPlacement { node, .. } => {
7530×
                    ("multi-placement", vec![*node])
754
                }
7550×
                crate::tree::TreeConflict::Orphan { node, .. } => ("orphan", vec![*node]),
7560×
                crate::tree::TreeConflict::Cycle { node } => ("cycle", vec![*node]),
7570×
                crate::tree::TreeConflict::Mode { node, .. } => ("mode", vec![*node]),
758
            };
7590×
            let detail = match c {
7600×
                crate::tree::TreeConflict::Name { name, parent, .. } => {
7610×
                    let dir = if *parent == NodeId::ROOT {
7620×
                        String::new()
763
                    } else {
7640×
                        path_of(parent).unwrap_or_default()
765
                    };
7660×
                    format!(
767
                        ",\"path\":{}",
7680×
                        json_str(&if dir.is_empty() {
7690×
                            name.clone()
770
                        } else {
7710×
                            format!("{dir}/{name}")
772
                        })
773
                    )
774
                }
7750×
                _ => nodes
7760×
                    .first()
7770×
                    .and_then(path_of)
7780×
                    .map(|p| format!(",\"path\":{}", json_str(&p)))
7790×
                    .unwrap_or_default(),
780
            };
7810×
            conflicts.push(format!(
782
                "{{\"kind\":{},\"nodes\":{}{detail}}}",
7830×
                json_str(kind),
7840×
                json_array(nodes.iter().map(|n| json_str(&n.to_hex())))
785
            ));
786
        }
7877×
        Ok(format!(
788
            "{{\"bookmark\":{},\"working_copy\":{},\"heads\":{},\"clean\":{},\"conflicted\":{},\"paths\":{paths},\"conflicts\":{},\"untracked_nested\":{},\"skipped_large\":{}}}",
7897×
            json_str(&self.config.bookmark),
7907×
            json_str(&snap.wc.change_id.to_hex()),
7917×
            heads.len(),
7927×
            snap.statuses.is_empty(),
7937×
            base_snapshot.is_conflicted(),
7947×
            json_array(conflicts),
7957×
            json_array(snap.untracked_nested.iter().map(|p| json_str(p))),
7967×
            json_array(
7977×
                self.skipped_large
7987×
                    .borrow()
7997×
                    .iter()
8007×
                    .map(|(p, n)| format!("{{\"path\":{},\"size\":{n}}}", json_str(p)))
801
            )
802
        ))
8037×
    }
804
805
    /// Turn the working-copy change into a normal change on the bookmark (spec §12.3).
806618×
    pub fn commit(&self, message: &str, extra_deps: &[ChangeHash]) -> Result<ChangeHash> {
807618×
        self.commit_selection(message, extra_deps, &Selection::All)
808618×
    }
809
810
    /// The hunks of the working copy, for `oxy commit --interactive`: each
811
    /// tree operation and each edit, in the order `select_hunks` numbers them.
8127×
    pub fn hunks(&self) -> Result<(SnapshotResult, Vec<Hunk>)> {
8137×
        let snap = self.snapshot_status("oxy commit")?;
8147×
        let hunks = render_hunks(&snap.wc, &snap.base, &snap.base_snapshot);
8157×
        Ok((snap, hunks))
8167×
    }
817
818
    /// Commit part of the working copy (spec §12.3). What is not selected
819
    /// stays on disk as uncommitted work: the next snapshot rebuilds it
820
    /// against the new base, so the working copy always describes the
821
    /// directory.
822
    /// The graph key in `st` of each text file at `paths`, the paths a
823
    /// commit changed: only their graphs changed, so the keys the manifest
824
    /// holds for the others still stand (and any that does not is simply
825
    /// not trusted by the next snapshot, which compares keys). Files with
826
    /// an `eol` attribute are left out: their bytes on disk are not the
827
    /// rendering.
828638×
    fn committed_graph_keys(
829638×
        &self,
830638×
        st: &State,
831638×
        paths: &[String],
832638×
        attrs: &crate::attributes::Attributes,
833638×
    ) -> HashMap<String, [u8; 32]> {
834638×
        let _t = crate::timing::phase("commit: graph keys");
835638×
        let view = st.tree().view();
836638×
        paths
837638×
            .iter()
8383449×
            .filter_map(|p| {
8393449×
                let e = view.entries.get(p)?;
8403398×
                (e.kind == NodeKind::File && !e.mode.opaque && attrs.lookup(p).eol.is_none())
8413398×
                    .then_some(())?;
8423349×
                Some((p.clone(), st.graph_key(&e.node)?))
8433449×
            })
844638×
            .collect()
845638×
    }
846
847623×
    pub fn commit_selection(
848623×
        &self,
849623×
        message: &str,
850623×
        extra_deps: &[ChangeHash],
851623×
        selection: &Selection,
852623×
    ) -> Result<ChangeHash> {
853623×
        Ok(self
854623×
            .commit_selection_partial(message, extra_deps, selection)?
855
            .0)
856623×
    }
857
858
    /// As [`Repo::commit_selection`], and whether the commit left part of
859
    /// the working copy uncommitted: when it did not, nothing is left, and
860
    /// no snapshot is needed to say so.
861649×
    pub fn commit_selection_partial(
862649×
        &self,
863649×
        message: &str,
864649×
        extra_deps: &[ChangeHash],
865649×
        selection: &Selection,
866649×
    ) -> Result<(ChangeHash, bool)> {
867
        // The commit's objects are written together, made durable at once
868
        // before the operation that names them (spec §13.6).
869649×
        let batch = self.store.begin_batch()?;
870649×
        let out = self.commit_selection_batched(message, extra_deps, selection);
871649×
        batch.finish()?;
872649×
        out
873649×
    }
874
875
    /// Write the manifest a commit's snapshot left to the commit, with the
876
    /// graph keys `keys` sets.
877426×
    fn write_pending_manifest(
878426×
        &self,
879426×
        mut m: PendingManifest,
880426×
        conflicted: bool,
881426×
        keys: HashMap<String, [u8; 32]>,
882426×
    ) -> Result<()> {
8832818×
        for (path, k) in keys {
8842818×
            if let Some(e) = m.entries.get_mut(&path) {
8852818×
                e.graph_key = Some(k);
8862818×
            }
887
        }
888426×
        self.write_manifest_entries_as_of(
889426×
            conflicted,
890
            false,
891426×
            &m.entries,
892426×
            &m.blobs,
893426×
            m.written,
894426×
            m.dirs.unwrap_or_default(),
895
        )
896426×
    }
897
898649×
    fn commit_selection_batched(
899649×
        &self,
900649×
        message: &str,
901649×
        extra_deps: &[ChangeHash],
902649×
        selection: &Selection,
903649×
    ) -> Result<(ChangeHash, bool)> {
904649×
        let _wc = self.lock_working_copy()?;
905649×
        let mut snap = match self.snapshot_from_cache()? {
906214×
            Some(snap) => snap,
907435×
            None => self.snapshot_as("oxy commit", true, true)?,
908
        };
909649×
        let pending = snap.manifest.take();
910649×
        if snap.wc.tree_ops.is_empty() && snap.wc.edits.is_empty() {
9113×
            if let Some(m) = pending {
9123×
                let conflicted = snap.base_snapshot.is_conflicted();
9133×
                self.write_pending_manifest(m, conflicted, HashMap::new())?;
9140×
            }
9153×
            return fail("nothing to commit: the working copy matches its base");
916646×
        }
917646×
        if let Some(s) = snap
918646×
            .statuses
919646×
            .iter()
9203466×
            .find(|s| s.status == ChangeStatus::ConflictEdited)
921
        {
9220×
            return fail(format!("{} still contains conflict markers", s.path));
923646×
        }
924646×
        if message.trim().is_empty() {
9250×
            return fail("a commit message is required");
926646×
        }
927
        // What the whole working copy references, before a whole commit
928
        // takes its operations over (they are moved, not copied: for a
929
        // large tree they are most of the memory).
930646×
        let wc_refs = referenced_changes(&snap.wc, &snap.base);
9313466×
        let changed_paths: Vec<String> = snap.statuses.iter().map(|s| s.path.clone()).collect();
932646×
        let (tree_ops, edits, partial) = match selection {
933638×
            Selection::All => (
934638×
                std::mem::take(&mut snap.wc.tree_ops),
935638×
                std::mem::take(&mut snap.wc.edits),
936638×
                false,
937638×
            ),
9384×
            Selection::Paths(paths) => {
9394×
                let (o, e) = select_paths(&snap.wc, &snap.base_snapshot, paths);
9404×
                let partial = o.len() != snap.wc.tree_ops.len() || e.len() != snap.wc.edits.len();
9414×
                (o, e, partial)
942
            }
9434×
            Selection::Hunks(indices) => {
9444×
                let (o, e) = select_hunks(&snap.wc, indices);
9454×
                let partial = o.len() != snap.wc.tree_ops.len() || e.len() != snap.wc.edits.len();
9464×
                (o, e, partial)
947
            }
948
        };
949646×
        if tree_ops.is_empty() && edits.is_empty() {
9500×
            return fail("nothing selected to commit");
951646×
        }
952646×
        if partial && snap.resolves {
9530×
            return fail("a conflict resolution must be committed whole");
954646×
        }
955
        // pre-commit hook: may veto.
956646×
        self.run_hook(
957646×
            "pre-commit",
958646×
            &format!(
959
                "{{\"event\":\"pre-commit\",\"message\":{},\"paths\":{}}}",
960646×
                json_str(message),
9613466×
                json_array(snap.statuses.iter().map(|s| format!(
962
                    "{{\"path\":{},\"status\":{}}}",
9633466×
                    json_str(&s.path),
9643466×
                    json_str(&format!("{:?}", s.status))
965
                )))
966
            ),
9671×
        )?;
968645×
        let (op_ref, op) = self.head_op()?;
969645×
        let mut deps: BTreeSet<ChangeHash> = wc_refs;
970
        // semantic-deps hook: may add explicit dependencies (spec §8.1).
971645×
        if self.config.semantic_deps {
9721×
            let touched: Vec<String> = snap.statuses.iter().map(|s| s.path.clone()).collect();
9731×
            let by_node = snap.base_snapshot.tree.by_node();
9741×
            let mut candidates: Vec<(ChangeId, ChangeHash, Vec<String>)> = Vec::new();
9751×
            let mut seen: BTreeSet<ChangeHash> = BTreeSet::new();
9762×
            for h in deps.iter().chain(snap.base.maximal(&snap.wc.deps).iter()) {
9772×
                if !seen.insert(*h) {
9780×
                    continue;
9792×
                }
9802×
                let c = self.store.get_change(h)?;
9812×
                let mut paths: BTreeSet<String> = BTreeSet::new();
9826×
                for n in c
9832×
                    .tree_ops
9842×
                    .iter()
9853×
                    .map(|o| o.node())
9863×
                    .chain(c.edits.iter().map(|e| e.node()))
987
                {
9886×
                    if let Some(e) = by_node.get(&n) {
9896×
                        paths.insert(e.path.clone());
9906×
                    }
991
                }
9922×
                candidates.push((c.change_id, *h, paths.into_iter().collect()));
993
            }
9941×
            for d in self.semantic_deps(&snap.wc.change_id, &touched, &candidates)? {
9951×
                if snap.base.contains(&d) {
9961×
                    deps.insert(d);
9971×
                }
998
            }
999644×
        }
1000
        // A resolution depends on every change that contributed to the
1001
        // conflict (spec §8.1). Tree and opaque conflicts are resolved through
1002
        // ordinary operations whose references already cover the contributors.
1003645×
        deps.extend(snap.contributors.iter().copied());
1004645×
        for d in extra_deps {
10052×
            if !snap.base.contains(d) {
10060×
                return fail(format!(
1007
                    "--depends-on {d}: not in the working copy's base state"
1008
                ));
10092×
            }
10102×
            deps.insert(*d);
1011
        }
1012645×
        let mut change = Change {
1013
            version: crate::objects::CHANGE_VERSION,
1014645×
            change_id: if partial {
10156×
                ChangeId::random()
1016
            } else {
1017639×
                snap.wc.change_id
1018
            },
1019645×
            deps: vec![],
1020645×
            author: self.author(),
1021645×
            hlc: Hlc::now(),
1022645×
            message: message.trim_end().to_string(),
1023645×
            tree_ops,
1024645×
            edits,
1025645×
            kind: if snap.resolves {
10267×
                ChangeKind::Resolution
1027
            } else {
1028638×
                ChangeKind::Normal
1029
            },
1030
        };
1031645×
        if partial {
1032
            // Dependencies come from what the selected part references, not
1033
            // from the whole working copy.
10346×
            deps = referenced_changes(&change, &snap.base);
10356×
            for d in extra_deps {
10360×
                deps.insert(*d);
10370×
            }
1038639×
        }
1039645×
        change.deps = deps.into_iter().collect();
1040645×
        change.normalize();
1041645×
        let signing = crate::timing::phase("commit: sign and store");
1042645×
        let hash = self.store_signed(&change)?;
1043644×
        drop(signing);
1044644×
        let extending = crate::timing::phase("commit: extend the state");
1045
1046
        // New bookmark heads: maximal elements of old heads plus the new change.
1047
        // The working copy continues on its own base plus the new change, which
1048
        // is exactly what the files on disk contain; the bookmark may hold
1049
        // other heads (and conflicts) the working copy has not checked out.
1050644×
        let old_heads = self.heads_of(&op.view, &self.config.bookmark)?;
1051644×
        let old_base = snap.base.maximal(&snap.wc.deps);
1052644×
        let mut all: Vec<ChangeHash> = old_heads.clone();
1053644×
        all.extend(old_base.iter().copied());
1054644×
        all.push(hash);
1055
        // The snapshot already loaded the working copy's base; when that also
1056
        // holds every bookmark head, it is the state to extend.
1057644×
        let mut st = if old_heads.iter().all(|h| snap.base.contains(h)) {
1058606×
            snap.base
1059
        } else {
106038×
            self.load_state(&all)?
1061
        };
1062644×
        st.add_hashed(hash, change)?;
1063644×
        let mut with_new = old_heads.clone();
1064644×
        with_new.push(hash);
1065644×
        let new_heads = st.maximal(&with_new);
1066
        // Automatic checkpoint once enough changes accumulated (spec §11).
1067644×
        let since = self
1068644×
            .latest_checkpoint(&self.config.bookmark)?
1069644×
            .map(|(_, cp)| cp.count)
1070644×
            .unwrap_or(0);
1071644×
        if self.config.checkpoint_interval > 0
1072644×
            && (st.len() as u64).saturating_sub(since) >= self.config.checkpoint_interval
1073
        {
10742×
            let cp_state = self.load_state_full(&new_heads)?;
10752×
            self.write_checkpoint(&self.config.bookmark, &cp_state, &new_heads)?;
1076642×
        }
1077644×
        let mut wc_base = old_base.clone();
1078644×
        wc_base.push(hash);
1079644×
        let wc_base = st.maximal(&wc_base);
1080644×
        drop(extending);
1081
1082
        // The graph keys of the files as they now are, from the state the
1083
        // commit just extended: a file whose graph it built has none, and
1084
        // is read by the next snapshot; a key the next base does not share
1085
        // (the bookmark held other heads) is simply not trusted then.
1086644×
        let keying = crate::timing::phase("commit: graph keys of the files");
1087644×
        let committed_keys =
1088644×
            (!partial).then(|| self.committed_graph_keys(&st, &changed_paths, &snap.attributes));
1089644×
        drop(keying);
1090644×
        let recording = crate::timing::phase("commit: record");
1091644×
        let wc = self.new_working_copy(wc_base, "");
1092644×
        let wc_hash = self.store.put_change(&wc)?;
1093644×
        let mut view = op.view.clone();
1094644×
        view.bookmarks.insert(
1095644×
            self.config.bookmark.clone(),
1096644×
            self.store.put_state(&StateObject::new(new_heads))?,
1097
        );
1098644×
        view.workspaces.insert(self.workspace, wc_hash);
1099644×
        self.record_op(&[op_ref], &format!("oxy commit -m {message:?}"), view)?;
1100639×
        drop(recording);
1101639×
        let rewriting = crate::timing::phase("commit: manifest");
1102639×
        if partial {
11036×
            // The rest is rebuilt from disk by the next snapshot.
11046×
            self.drop_manifest();
11056×
        } else {
1106633×
            let conflicted = snap.base_snapshot.is_conflicted() && !snap.resolves;
1107
            // The files on disk are now exactly the new base's renderings:
1108
            // record their graph keys, so the next snapshot neither reads nor
1109
            // renders them (oxygen#35).
1110633×
            let keys = if conflicted {
11110×
                HashMap::new()
1112
            } else {
1113633×
                committed_keys.unwrap_or_default()
1114
            };
1115633×
            match pending {
1116423×
                Some(m) => self.write_pending_manifest(m, conflicted, keys)?,
1117210×
                None => self.rewrite_manifest(conflicted, false, &keys)?,
1118
            }
1119
        }
1120639×
        drop(rewriting);
1121639×
        let packing = crate::timing::phase("commit: autopack");
1122639×
        self.maybe_autopack()?;
1123639×
        drop(packing);
1124639×
        let _hook = crate::timing::phase("commit: hook");
1125639×
        let _ = self.run_hook(
1126639×
            "post-commit",
1127639×
            &format!(
1128639×
                "{{\"event\":\"post-commit\",\"change_id\":{},\"hash\":{},\"message\":{}}}",
1129639×
                json_str(&snap.wc.change_id.to_hex()),
1130639×
                json_str(&hash.to_hex()),
1131639×
                json_str(message)
1132639×
            ),
1133639×
        );
1134639×
        Ok((hash, partial))
1135649×
    }
1136
}
1137
1138
/// What part of the working copy a commit takes (spec §12.3).
1139
#[derive(Clone, Debug)]
1140
pub enum Selection {
1141
    All,
1142
    /// Every operation and edit on nodes under these paths.
1143
    Paths(Vec<String>),
1144
    /// Hunk indices as `Repo::hunks` numbers them; dependent hunks are added.
1145
    Hunks(Vec<usize>),
1146
}
1147
1148
/// One selectable piece of the working copy: a tree operation or an edit.
1149
#[derive(Clone, Debug)]
1150
pub struct Hunk {
1151
    pub index: usize,
1152
    pub path: String,
1153
    /// Rendered like `oxy diff`.
1154
    pub text: String,
1155
}
1156
1157
/// The tree operations and edits on nodes under `paths`, plus the
1158
/// additions of any new parent directories they need.
11594×
fn select_paths(
11604×
    wc: &Change,
11614×
    base_snapshot: &Snapshot,
11624×
    paths: &[String],
11634×
) -> (Vec<TreeOp>, Vec<Edit>) {
116413×
    let selected = |p: &str| {
116513×
        paths
116613×
            .iter()
116713×
            .any(|x| p == x || p.starts_with(&format!("{}/", x.trim_end_matches('/'))))
116813×
    };
11694×
    let by_node = base_snapshot.tree.by_node();
11704×
    let mut new_names: HashMap<NodeId, (NodeId, String, NodeKind)> = HashMap::new();
11714×
    for op in &wc.tree_ops {
1172
        if let TreeOp::AddNode {
11731×
            node,
11741×
            parent,
11751×
            name,
11761×
            kind,
1177
            ..
11781×
        } = op
11791×
        {
11801×
            new_names.insert(*node, (*parent, name.clone(), *kind));
11811×
        }
1182
    }
11834×
    let mut nodes: BTreeSet<NodeId> = BTreeSet::new();
118413×
    for n in wc
11854×
        .tree_ops
11864×
        .iter()
11874×
        .map(|o| o.node())
118812×
        .chain(wc.edits.iter().map(|e| e.node()))
1189
    {
119013×
        if path_of_node(&n, &by_node, &new_names).is_some_and(|p| selected(&p)) {
11918×
            nodes.insert(n);
11928×
        }
1193
    }
1194
    // New parents of selected new nodes come along.
11954×
    let mut changed = true;
11968×
    while changed {
11974×
        changed = false;
11984×
        for (n, (parent, _, _)) in &new_names {
11991×
            if nodes.contains(n) && new_names.contains_key(parent) && nodes.insert(*parent) {
12000×
                changed = true;
12011×
            }
1202
        }
1203
    }
12044×
    let ops = wc
12054×
        .tree_ops
12064×
        .iter()
12074×
        .filter(|o| nodes.contains(&o.node()))
12084×
        .cloned()
12094×
        .collect();
12104×
    let edits = wc
12114×
        .edits
12124×
        .iter()
121312×
        .filter(|e| nodes.contains(&e.node()))
12144×
        .cloned()
12154×
        .collect();
12164×
    (ops, edits)
12174×
}
1218
1219
/// The hunks `indices` name plus whatever they refer to within the working
1220
/// copy (the parent directory of an added node, the insert that introduced
1221
/// an anchor line), renumbered so the result is a well-formed change.
12225×
fn select_hunks(wc: &Change, indices: &[usize]) -> (Vec<TreeOp>, Vec<Edit>) {
12235×
    let n_ops = wc.tree_ops.len();
12245×
    let mut ops_sel = vec![false; n_ops];
12255×
    let mut edits_sel = vec![false; wc.edits.len()];
12265×
    for &i in indices {
12274×
        if i < n_ops {
12281×
            ops_sel[i] = true;
12293×
        } else if i - n_ops < wc.edits.len() {
12303×
            edits_sel[i - n_ops] = true;
12313×
        }
1232
    }
1233
    // Atom ranges each insert introduces, per node, in the working copy's numbering.
12345×
    let mut per_node: HashMap<NodeId, u32> = HashMap::new();
12355×
    let mut insert_ranges: Vec<Option<(NodeId, u32, u32)>> = Vec::new();
123610×
    for e in &wc.edits {
123710×
        insert_ranges.push(match e {
123810×
            Edit::Insert { node, lines, .. } => {
123910×
                let start = per_node.entry(*node).or_default();
124010×
                let r = (*node, *start, *start + lines.len() as u32);
124110×
                *start += lines.len() as u32;
124210×
                Some(r)
1243
            }
12440×
            _ => None,
1245
        });
1246
    }
12475×
    let add_index: HashMap<NodeId, usize> = wc
12485×
        .tree_ops
12495×
        .iter()
12505×
        .enumerate()
12518×
        .filter_map(|(i, o)| {
12528×
            if let TreeOp::AddNode { node, .. } = o {
12538×
                Some((*node, i))
1254
            } else {
12550×
                None
1256
            }
12578×
        })
12585×
        .collect();
12595×
    let insert_for = |node: &NodeId, index: u32| -> Option<usize> {
12600×
        insert_ranges
12610×
            .iter()
12620×
            .position(|r| matches!(r, Some((n, a, b)) if n == node && *a <= index && index < *b))
12630×
    };
1264
    // Closure.
12655×
    let mut changed = true;
126613×
    while changed {
12678×
        changed = false;
126817×
        for i in 0..n_ops {
126917×
            if !ops_sel[i] {
127011×
                continue;
12716×
            }
12726×
            if let TreeOp::AddNode { node, parent, .. } = &wc.tree_ops[i] {
12736×
                if let Some(&p) = add_index.get(parent) {
12744×
                    if !ops_sel[p] {
12752×
                        ops_sel[p] = true;
12762×
                        changed = true;
12772×
                    }
12782×
                }
1279
                // A new node's content belongs with its addition: nobody
1280
                // wants an empty file committed apart from its lines.
128112×
                for (j, e) in wc.edits.iter().enumerate() {
128212×
                    if e.node() == *node && !edits_sel[j] {
12831×
                        edits_sel[j] = true;
12841×
                        changed = true;
128511×
                    }
1286
                }
12870×
            }
1288
        }
128916×
        for j in 0..wc.edits.len() {
129016×
            if !edits_sel[j] {
12919×
                continue;
12927×
            }
12937×
            let e = &wc.edits[j];
12947×
            if let Some(&a) = add_index.get(&e.node()) {
12955×
                if !ops_sel[a] {
12961×
                    ops_sel[a] = true;
12971×
                    changed = true;
12984×
                }
12992×
            }
1300
            if let Edit::Insert {
13017×
                node,
13027×
                after,
13037×
                before,
1304
                ..
13057×
            } = e
1306
            {
130714×
                for r in [after, before] {
130814×
                    if let AtomRef::Atom { change, index } = r {
13092×
                        if change.is_zero() {
13100×
                            if let Some(k) = insert_for(node, *index) {
13110×
                                if !edits_sel[k] {
13120×
                                    edits_sel[k] = true;
13130×
                                    changed = true;
13140×
                                }
13150×
                            }
13162×
                        }
131712×
                    }
1318
                }
13190×
            }
1320
        }
1321
    }
1322
    // Renumber self-references: old atom index → new index among selected inserts.
13235×
    let mut remap: HashMap<(NodeId, u32), u32> = HashMap::new();
13245×
    let mut new_counts: HashMap<NodeId, u32> = HashMap::new();
132510×
    for (j, r) in insert_ranges.iter().enumerate() {
132610×
        if let (true, Some((node, a, b))) = (edits_sel[j], r) {
13274×
            let next = new_counts.entry(*node).or_default();
13284×
            for old in *a..*b {
13294×
                remap.insert((*node, old), *next);
13304×
                *next += 1;
13314×
            }
13326×
        }
1333
    }
13348×
    let map_ref = |r: AtomRef, node: &NodeId| -> AtomRef {
13352×
        match r {
13362×
            AtomRef::Atom { change, index } if change.is_zero() => AtomRef::Atom {
13370×
                change,
13380×
                index: remap.get(&(*node, index)).copied().unwrap_or(index),
13390×
            },
13408×
            other => other,
1341
        }
13428×
    };
13435×
    let ops = wc
13445×
        .tree_ops
13455×
        .iter()
13465×
        .enumerate()
13478×
        .filter(|(i, _)| ops_sel[*i])
13485×
        .map(|(_, o)| o.clone())
13495×
        .collect();
13505×
    let edits = wc
13515×
        .edits
13525×
        .iter()
13535×
        .enumerate()
135410×
        .filter(|(j, _)| edits_sel[*j])
13555×
        .map(|(_, e)| match e {
1356
            Edit::Insert {
13574×
                node,
13584×
                after,
13594×
                before,
13604×
                lines,
13614×
            } => Edit::Insert {
13624×
                node: *node,
13634×
                after: map_ref(*after, node),
13644×
                before: map_ref(*before, node),
13654×
                lines: lines.clone(),
13664×
            },
13670×
            other => other.clone(),
13684×
        })
13695×
        .collect();
13705×
    (ops, edits)
13715×
}
1372
1373
/// Render each tree operation and edit of `change` on its own, numbered.
13747×
pub fn render_hunks(change: &Change, base: &State, base_snapshot: &Snapshot) -> Vec<Hunk> {
13757×
    let by_node = base_snapshot.tree.by_node();
13767×
    let mut new_names: HashMap<NodeId, (NodeId, String, NodeKind)> = HashMap::new();
13778×
    for op in &change.tree_ops {
1378
        if let TreeOp::AddNode {
13798×
            node,
13808×
            parent,
13818×
            name,
13828×
            kind,
1383
            ..
13848×
        } = op
13858×
        {
13868×
            new_names.insert(*node, (*parent, name.clone(), *kind));
13878×
        }
1388
    }
13897×
    let mut out = Vec::new();
13908×
    for (i, op) in change.tree_ops.iter().enumerate() {
13918×
        let one = Change {
13928×
            tree_ops: vec![op.clone()],
13938×
            edits: vec![],
13948×
            ..change.clone()
13958×
        };
13968×
        let path = path_of_node(&op.node(), &by_node, &new_names).unwrap_or_default();
13978×
        out.push(Hunk {
13988×
            index: i,
13998×
            path,
14008×
            text: render_change(&one, base, base_snapshot),
14018×
        });
14028×
    }
140313×
    for (j, e) in change.edits.iter().enumerate() {
140413×
        let one = Change {
140513×
            tree_ops: vec![],
140613×
            edits: vec![e.clone()],
140713×
            ..change.clone()
140813×
        };
140913×
        let path = path_of_node(&e.node(), &by_node, &new_names).unwrap_or_default();
141013×
        out.push(Hunk {
141113×
            index: change.tree_ops.len() + j,
141213×
            path,
141313×
            text: render_change(&one, base, base_snapshot),
141413×
        });
141513×
    }
14167×
    out
14177×
}
1418
1419
/// One file's part of a diff, for `oxy diff --json`.
1420
#[derive(Clone, Debug)]
1421
pub struct FileDiff {
1422
    pub path: String,
1423
    /// `added`, `removed`, `modified`, `renamed`, `mode`, `replaced`.
1424
    pub kind: String,
1425
    pub hunks: Vec<DiffHunk>,
1426
    /// For renames, the previous path.
1427
    pub from: Option<String>,
1428
}
1429
1430
/// Lines inserted after `base_line` (0 = before the first line) and lines
1431
/// removed, with their base line numbers.
1432
#[derive(Clone, Debug, Default)]
1433
pub struct DiffHunk {
1434
    pub base_line: u32,
1435
    pub added: Vec<Vec<u8>>,
1436
    pub removed: Vec<(u32, Vec<u8>)>,
1437
}
1438
1439
impl Repo {
1440
    /// The content of `path` in a state: `heads`, or the working copy's base.
144126×
    pub fn file_at(&self, path: &str, heads: Option<&[ChangeHash]>) -> Result<Vec<u8>> {
1442
        // The state's history and tree, then the one file's graph: nothing
1443
        // else is built or rendered (oxygen#92).
1444
        // The working copy's base, and a state named by its heads (`-r
1445
        // main` on main), come from the workspace's state index.
144626×
        let base = if self.is_bare() {
14475×
            None
1448
        } else {
144921×
            Some(self.working_copy()?.1.deps)
1450
        };
145126×
        let same = |a: &[ChangeHash], b: &[ChangeHash]| {
14521×
            let (mut a, mut b) = (a.to_vec(), b.to_vec());
14531×
            a.sort();
14541×
            b.sort();
14551×
            a == b
14561×
        };
145726×
        let mut state = match (heads, base) {
14581×
            (Some(h), Some(b)) if same(h, &b) => self.load_state_indexed(&b)?,
14595×
            (Some(h), _) => self.load_state_history(h)?,
146020×
            (None, Some(b)) => self.load_state_indexed(&b)?,
14610×
            (None, None) => return fail("this is a bare repository: it has no working copy"),
1462
        };
146326×
        let view = state.tree().view();
146426×
        let Some(node) = view.entries.get(path).map(|e| e.node) else {
14650×
            return fail(format!("{path} is not in that state"));
1466
        };
146726×
        self.load_graphs_of(&mut state, &[node])?;
146825×
        let snapshot = state.materialize_paths(view, [path]);
146925×
        let Some(f) = snapshot.files.get(path) else {
14700×
            return fail(format!("{path} is not in that state"));
1471
        };
147225×
        match &f.content {
14730×
            FileContent::Dir => fail(format!("{path} is a directory")),
147425×
            FileContent::Text { bytes, .. } => Ok(bytes.clone()),
14750×
            FileContent::Opaque { blobs } => match blobs.first() {
14760×
                Some(b) => self.read_blob(b),
14770×
                None => Ok(vec![]),
1478
            },
1479
        }
148026×
    }
1481
1482
    /// Restore `paths` (files or directories) to the working copy's base:
1483
    /// edits are undone, additions removed, removals put back. Returns the
1484
    /// number of paths touched.
14852×
    pub fn discard(&self, paths: &[String]) -> Result<usize> {
14862×
        let _wc = self.lock_working_copy()?;
14872×
        let snap = self.snapshot_status("oxy discard")?;
14887×
        let under = |p: &str| {
14897×
            paths
14907×
                .iter()
14917×
                .any(|x| p == x || p.starts_with(&format!("{}/", x.trim_end_matches('/'))))
14927×
        };
14932×
        let attrs = Repo::state_attributes(&snap.base_snapshot);
14942×
        let mut n = 0;
14953×
        for s in &snap.statuses {
14963×
            if !under(&s.path) {
14971×
                continue;
14982×
            }
14992×
            match snap.base_snapshot.files.get(&s.path) {
1500
                None => {
1501
                    // Added (or the new name of a rename): remove it.
15021×
                    let full = self.root.join(&s.path);
15031×
                    if full.is_dir() {
15040×
                        let _ = fs::remove_dir_all(&full);
15051×
                    } else {
15061×
                        let _ = fs::remove_file(&full);
15071×
                    }
15081×
                    n += 1;
1509
                }
15101×
                Some(f) => {
15111×
                    match &f.content {
15120×
                        FileContent::Dir => fs::create_dir_all(self.root.join(&s.path))?,
15131×
                        FileContent::Text { bytes, .. } => {
15141×
                            let on_disk: std::borrow::Cow<[u8]> = if attrs.lookup(&s.path).eol
15151×
                                == Some(crate::attributes::Eol::Crlf)
1516
                            {
15170×
                                crate::attributes::to_crlf(bytes).into()
1518
                            } else {
15191×
                                bytes.as_slice().into()
1520
                            };
15211×
                            self.write_file(&s.path, &on_disk, f.mode.exec)?;
1522
                        }
15230×
                        FileContent::Opaque { blobs } => {
15240×
                            let bytes = match blobs.first() {
15250×
                                Some(b) => self.read_blob(b)?,
15260×
                                None => vec![],
1527
                            };
15280×
                            if f.kind == NodeKind::Symlink {
15290×
                                self.write_symlink(&s.path, &bytes)?;
15300×
                            } else if f.kind == NodeKind::File {
15310×
                                self.write_file(&s.path, &bytes, f.mode.exec)?;
15320×
                            }
1533
                        }
1534
                    }
15351×
                    n += 1;
1536
                }
1537
            }
1538
        }
1539
        // A rename's old name is not in the statuses; put it back too.
15404×
        for (p, f) in &snap.base_snapshot.files {
15414×
            if under(p)
15421×
                && !self.root.join(p).exists()
15430×
                && f.kind != NodeKind::Dir
15440×
                && f.kind != NodeKind::Subrepo
15450×
                && !snap.statuses.iter().any(|s| s.path == *p)
1546
            {
15470×
                let bytes = match &f.content {
15480×
                    FileContent::Text { bytes, .. } => bytes.clone(),
15490×
                    FileContent::Opaque { blobs } => blobs
15500×
                        .first()
15510×
                        .map(|b| self.read_blob(b))
15520×
                        .transpose()?
15530×
                        .unwrap_or_default(),
15540×
                    FileContent::Dir => continue,
1555
                };
15560×
                if f.kind == NodeKind::Symlink {
15570×
                    self.write_symlink(p, &bytes)?
1558
                } else {
15590×
                    self.write_file(p, &bytes, f.mode.exec)?
1560
                }
15610×
                n += 1;
15624×
            }
1563
        }
15642×
        self.drop_manifest();
15652×
        Ok(n)
15662×
    }
1567
1568
    /// Undo the working-copy hunks `indices` (as `hunks` numbers them) on
1569
    /// disk, keeping the others: the files are rewritten from the base plus
1570
    /// the remaining hunks.
15711×
    pub fn discard_hunks(&self, indices: &[usize]) -> Result<usize> {
15721×
        let _wc = self.lock_working_copy()?;
15731×
        let (snap, hunks) = self.hunks()?;
15741×
        let keep: Vec<usize> = hunks
15751×
            .iter()
15761×
            .map(|h| h.index)
15771×
            .filter(|i| !indices.contains(i))
15781×
            .collect();
15791×
        let (ops, edits) = select_hunks(&snap.wc, &keep);
15801×
        let dropped_nodes: BTreeSet<NodeId> = hunks
15811×
            .iter()
15821×
            .filter(|h| indices.contains(&h.index))
15831×
            .map(|h| {
15841×
                if h.index < snap.wc.tree_ops.len() {
15850×
                    snap.wc.tree_ops[h.index].node()
1586
                } else {
15871×
                    snap.wc.edits[h.index - snap.wc.tree_ops.len()].node()
1588
                }
15891×
            })
15901×
            .collect();
15911×
        let mut partial = snap.wc.clone();
15921×
        partial.tree_ops = ops;
15931×
        partial.edits = edits;
15941×
        partial.normalize();
15951×
        let mut st = snap.base.clone();
15961×
        st.add_unchecked(partial);
1597
        // Every file of the target is rendered: build the graphs the
1598
        // partial snapshot left out.
15991×
        self.load_all_graphs(&mut st)?;
16001×
        let target = st.materialize();
16011×
        let by_node_target = target.tree.by_node();
16021×
        let by_node_base = snap.base_snapshot.tree.by_node();
16031×
        let attrs = Repo::state_attributes(&target);
16041×
        let mut n = 0;
16051×
        for node in dropped_nodes {
16061×
            match by_node_target.get(&node) {
16071×
                Some(e) => {
16081×
                    let f = &target.files[&e.path];
16091×
                    match &f.content {
16100×
                        FileContent::Dir => {}
16111×
                        FileContent::Text { bytes, .. } => {
16121×
                            let on_disk: std::borrow::Cow<[u8]> = if attrs.lookup(&e.path).eol
16131×
                                == Some(crate::attributes::Eol::Crlf)
1614
                            {
16150×
                                crate::attributes::to_crlf(bytes).into()
1616
                            } else {
16171×
                                bytes.as_slice().into()
1618
                            };
16191×
                            self.write_file(&e.path, &on_disk, f.mode.exec)?;
1620
                        }
16210×
                        FileContent::Opaque { blobs } => {
16220×
                            let bytes = blobs
16230×
                                .first()
16240×
                                .map(|b| self.read_blob(b))
16250×
                                .transpose()?
16260×
                                .unwrap_or_default();
16270×
                            if f.kind == NodeKind::Symlink {
16280×
                                self.write_symlink(&e.path, &bytes)?
1629
                            } else {
16300×
                                self.write_file(&e.path, &bytes, f.mode.exec)?
1631
                            }
1632
                        }
1633
                    }
1634
                    // A discarded rename: the new name goes.
16351×
                    if let Some(old_path) = snap
16361×
                        .statuses
16371×
                        .iter()
16381×
                        .find(|s| {
16391×
                            s.status == ChangeStatus::Renamed && !target.files.contains_key(&s.path)
16401×
                        })
16411×
                        .map(|s| s.path.clone())
16420×
                    {
16430×
                        let _ = fs::remove_file(self.root.join(old_path));
16441×
                    }
16451×
                    n += 1;
1646
                }
1647
                None => {
1648
                    // The node exists in neither target nor base with a live path: an addition to remove.
16490×
                    if let Some(added) = snap.statuses.iter().find(|s| {
16500×
                        s.status == ChangeStatus::Added
16510×
                            && !target.files.contains_key(&s.path)
16520×
                            && !by_node_base.contains_key(&node)
16530×
                    }) {
16540×
                        let full = self.root.join(&added.path);
16550×
                        if full.is_dir() {
16560×
                            let _ = fs::remove_dir_all(&full);
16570×
                        } else {
16580×
                            let _ = fs::remove_file(&full);
16590×
                        }
16600×
                        n += 1;
16610×
                    }
1662
                }
1663
            }
1664
        }
16651×
        self.drop_manifest();
16661×
        Ok(n)
16671×
    }
1668
1669
    /// The diff of the working copy (`None`) or of a change, per file with
1670
    /// line-numbered hunks (spec: `oxy diff --json`).
16715×
    pub fn diff_files(&self, change: Option<&ChangeHash>) -> Result<Vec<FileDiff>> {
16725×
        let (c, base, base_snapshot) = match change {
16732×
            Some(h) => {
16742×
                let c = self.store.get_change(h)?;
16752×
                let (base, snapshot) = self.change_base(&c)?;
16762×
                (c, base, snapshot)
1677
            }
16783×
            None => self.working_copy_with_base()?,
1679
        };
16805×
        Ok(diff_files_of(&c, &base, &base_snapshot))
16815×
    }
1682
1683
    /// The snapshot a command would take, without taking it, when the
1684
    /// status cache holds: every file is as the last snapshot left it, so
1685
    /// that snapshot's working-copy change is the answer. Its base comes
1686
    /// from the state index, the `.oxyattributes` files from disk. `None`
1687
    /// when a snapshot must be taken, and when there is nothing to commit
1688
    /// (the snapshot then says so). A conflicted base never gets here: the
1689
    /// cache does not hold for one.
1690650×
    pub(crate) fn snapshot_from_cache(&self) -> Result<Option<SnapshotResult>> {
1691650×
        let Some(statuses) = self.status_by_manifest()? else {
1692433×
            return Ok(None);
1693
        };
1694217×
        if statuses.is_empty() {
16952×
            return Ok(None);
1696215×
        }
1697215×
        let _t = crate::timing::phase("snapshot: from the status cache");
1698215×
        let (wc_hash, wc) = self.working_copy()?;
1699215×
        let base = self.load_state_indexed(&wc.deps)?;
1700215×
        let (base, base_snapshot) = self.render_base_for(&wc, base)?;
1701215×
        let attribute_files: Vec<(String, Vec<u8>)> = match self.read_manifest()? {
1702215×
            Some((_, _, m)) => m
1703215×
                .entries
1704215×
                .keys()
1705656×
                .filter(|p| is_attributes(p))
1706215×
                .filter_map(|p| fs::read(self.root.join(p)).ok().map(|b| (p.clone(), b)))
1707215×
                .collect(),
17080×
            None => Vec::new(),
1709
        };
1710215×
        let attributes = crate::attributes::Attributes::from_files(
1711215×
            attribute_files
1712215×
                .iter()
1713215×
                .map(|(p, b)| (p.as_str(), b.as_slice())),
1714
        );
1715215×
        Ok(Some(SnapshotResult {
1716215×
            wc_hash,
1717215×
            wc,
1718215×
            base,
1719215×
            base_snapshot,
1720215×
            statuses,
1721215×
            changed: false,
1722215×
            resolves: false,
1723215×
            contributors: Vec::new(),
1724215×
            attributes,
1725215×
            untracked_nested: self.untracked_nested.borrow().clone(),
1726215×
            manifest: None,
1727215×
        }))
1728650×
    }
1729
1730
    /// The working-copy change with its base state and a snapshot of the
1731
    /// base, for showing what the working copy changes ([`render_change`],
1732
    /// [`diff_files_of`]). While the status cache holds (every file as the
1733
    /// last snapshot left it), the stored working-copy change is the
1734
    /// answer, no snapshot is taken, and the base's snapshot holds its tree
1735
    /// but no file; otherwise a snapshot makes all three.
17364×
    pub fn working_copy_with_base(&self) -> Result<(Change, State, Snapshot)> {
17374×
        if self.status_by_manifest()?.is_some() {
17382×
            let (_, wc) = self.working_copy()?;
17392×
            let base = self.load_state_indexed(&wc.deps)?;
17402×
            let (base, snapshot) = self.tree_base_for(&wc, base)?;
17412×
            return Ok((wc, base, snapshot));
17422×
        }
17432×
        let snap = self.snapshot_status("oxy diff")?;
17442×
        Ok((snap.wc, snap.base, snap.base_snapshot))
17454×
    }
1746
1747
    /// The log restricted to changes touching `path` (its node, so renames
1748
    /// are followed), on the current bookmark.
17495×
    pub fn log_for_path(&self, path: &str) -> Result<Vec<LogEntry>> {
17505×
        let heads = self.bookmark_heads()?;
17515×
        if self.is_bare() {
17521×
            return self.log_for_path_in(path, &heads);
17534×
        }
17544×
        let entries = self.log()?;
17554×
        let (_, wc) = self.working_copy()?;
1756
        // The path's node from the trees alone: the base's (from the
1757
        // workspace's state index), else the bookmark's. Nothing is
1758
        // rendered.
17594×
        let node_in = |state: State| state.tree().view().entries.get(path).map(|e| e.node);
17604×
        let node = match node_in(self.load_state_indexed(&wc.deps)?) {
17614×
            Some(n) => Some(n),
17620×
            None => node_in(self.load_state_history(&heads)?),
1763
        };
17644×
        let Some(node) = node else {
17650×
            return fail(format!("{path} is not tracked"));
1766
        };
17674×
        Ok(self.entries_touching(entries, node))
17685×
    }
1769
1770
    /// The log of the state with these heads restricted to changes touching
1771
    /// `path` (its node, so renames are followed).
17722×
    pub fn log_for_path_in(&self, path: &str, heads: &[ChangeHash]) -> Result<Vec<LogEntry>> {
17732×
        self.log_for_path_of(&self.load_state_history(heads)?, path, None)
17742×
    }
1775
1776
    /// The changes of a loaded state touching `path`, newest first, at most
1777
    /// `limit` of them. The path is found in the state's tree alone, so no
1778
    /// file is rendered, and the walk stops once `limit` are found.
17795×
    pub fn log_for_path_of(
17805×
        &self,
17815×
        state: &State,
17825×
        path: &str,
17835×
        limit: Option<usize>,
17845×
    ) -> Result<Vec<LogEntry>> {
17855×
        let Some(node) = state.tree().view().entries.get(path).map(|e| e.node) else {
17861×
            return fail(format!("{path} is not in that state"));
1787
        };
17884×
        Ok(self.entries_touching_up_to(self.log_of(state), node, limit))
17895×
    }
1790
17914×
    fn entries_touching(&self, entries: Vec<LogEntry>, node: NodeId) -> Vec<LogEntry> {
17924×
        self.entries_touching_up_to(entries, node, None)
17934×
    }
1794
17958×
    fn entries_touching_up_to(
17968×
        &self,
17978×
        entries: Vec<LogEntry>,
17988×
        node: NodeId,
17998×
        limit: Option<usize>,
18008×
    ) -> Vec<LogEntry> {
18018×
        let mut touched = self.touched();
18028×
        if limit.is_none() {
18037×
            let hashes: Vec<ChangeHash> = entries.iter().map(|e| e.hash).collect();
18047×
            touched.fill(self, &hashes);
18051×
        }
18068×
        let wanted = HashSet::from([node]);
18078×
        let mut out = Vec::new();
180828×
        for e in entries {
180928×
            if limit.is_some_and(|n| out.len() >= n) {
18101×
                break;
181127×
            }
181227×
            if touched.touches(self, &e.hash, &wanted) {
181318×
                out.push(e);
181418×
            }
1815
        }
18168×
        touched.save();
18178×
        out
18188×
    }
1819
}
1820
1821
/// Per-file hunks of `change` against `base`.
18225×
pub fn diff_files_of(change: &Change, base: &State, base_snapshot: &Snapshot) -> Vec<FileDiff> {
18235×
    let by_node = base_snapshot.tree.by_node();
18245×
    let mut new_names: HashMap<NodeId, (NodeId, String, NodeKind)> = HashMap::new();
18255×
    for op in &change.tree_ops {
1826
        if let TreeOp::AddNode {
18272×
            node,
18282×
            parent,
18292×
            name,
18302×
            kind,
1831
            ..
18323×
        } = op
18332×
        {
18342×
            new_names.insert(*node, (*parent, name.clone(), *kind));
18352×
        }
1836
    }
18379×
    let path_of = |n: &NodeId| -> String {
18389×
        path_of_node(n, &by_node, &new_names).unwrap_or_else(|| format!("<node {}>", n.short(8)))
18399×
    };
18405×
    let mut files: BTreeMap<NodeId, FileDiff> = BTreeMap::new();
18415×
    let mut order: Vec<NodeId> = Vec::new();
184214×
    let mut entry = |files: &mut BTreeMap<NodeId, FileDiff>, n: NodeId, kind: &str| {
184314×
        if let std::collections::btree_map::Entry::Vacant(v) = files.entry(n) {
18449×
            order.push(n);
18459×
            v.insert(FileDiff {
18469×
                path: path_of(&n),
18479×
                kind: kind.to_string(),
18489×
                hunks: vec![],
18499×
                from: None,
18509×
            });
18519×
        }
185214×
    };
18535×
    for op in &change.tree_ops {
18543×
        match op {
18552×
            TreeOp::AddNode { node, kind, .. } => {
18562×
                if *kind != NodeKind::Dir {
18572×
                    entry(&mut files, *node, "added");
18582×
                }
1859
            }
18601×
            TreeOp::RemoveNode { node, .. } => {
18611×
                entry(&mut files, *node, "removed");
18621×
                if let Some(e) = by_node.get(node) {
18631×
                    files.get_mut(node).unwrap().path = e.path.clone();
18641×
                }
1865
            }
1866
            TreeOp::Move {
18670×
                node, parent, name, ..
1868
            } => {
18690×
                entry(&mut files, *node, "renamed");
18700×
                let f = files.get_mut(node).unwrap();
18710×
                f.from = by_node.get(node).map(|e| e.path.clone());
18720×
                let dir = if parent.is_root() {
18730×
                    String::new()
1874
                } else {
18750×
                    path_of_node(parent, &by_node, &new_names).unwrap_or_default()
1876
                };
18770×
                f.path = if dir.is_empty() {
18780×
                    name.clone()
1879
                } else {
18800×
                    format!("{dir}/{name}")
1881
                };
1882
            }
18830×
            TreeOp::SetMode { node, .. } => entry(&mut files, *node, "mode"),
1884
        }
1885
    }
1886
    // Base line numbers per node, 1-based.
18875×
    let mut line_of: HashMap<NodeId, HashMap<(ChangeHash, u32), u32>> = HashMap::new();
188811×
    let mut lines_for = |n: &NodeId| -> HashMap<(ChangeHash, u32), u32> {
188911×
        line_of
189011×
            .entry(*n)
189111×
            .or_insert_with(|| {
18928×
                base.live_lines(n)
18938×
                    .into_iter()
18948×
                    .enumerate()
189511×
                    .map(|(i, (k, _))| (k, i as u32 + 1))
18968×
                    .collect()
18978×
            })
189811×
            .clone()
189911×
    };
190011×
    for e in &change.edits {
190111×
        let n = e.node();
190211×
        let is_new = new_names.contains_key(&n);
190311×
        entry(&mut files, n, if is_new { "added" } else { "modified" });
190411×
        let f = files.get_mut(&n).unwrap();
190511×
        match e {
19069×
            Edit::Insert { after, lines, .. } => {
19079×
                let map = lines_for(&n);
19089×
                let base_line = match after {
19093×
                    AtomRef::Start => 0,
19100×
                    AtomRef::End => map.len() as u32,
19116×
                    AtomRef::Atom { change, index } if change.is_zero() => {
19120×
                        f.hunks.last().map(|h| h.base_line).unwrap_or(0)
1913
                    }
19146×
                    AtomRef::Atom { change, index } => {
19156×
                        map.get(&(*change, *index)).copied().unwrap_or(0)
1916
                    }
1917
                };
19189×
                f.hunks.push(DiffHunk {
19199×
                    base_line,
19209×
                    added: lines.to_vec(),
19219×
                    removed: vec![],
19229×
                });
1923
            }
19242×
            Edit::Delete { atoms, .. } => {
19252×
                let map = lines_for(&n);
19262×
                let mut removed = Vec::new();
19272×
                for r in atoms {
19282×
                    for i in r.from..r.to {
19292×
                        let line = map.get(&(r.change, i)).copied().unwrap_or(0);
19302×
                        let text = base
19312×
                            .file(&n)
19322×
                            .and_then(|g| g.content(&(r.change, i)))
19332×
                            .unwrap_or(b"")
19342×
                            .to_vec();
19352×
                        removed.push((line, text));
1936
                    }
1937
                }
19382×
                let base_line = removed
19392×
                    .first()
19402×
                    .map(|(l, _)| l.saturating_sub(1))
19412×
                    .unwrap_or(0);
19422×
                f.hunks.push(DiffHunk {
19432×
                    base_line,
19442×
                    added: vec![],
19452×
                    removed,
19462×
                });
1947
            }
1948
            Edit::Replace { .. } => {
19490×
                if !is_new {
19500×
                    f.kind = "replaced".into();
19510×
                }
1952
            }
1953
        }
1954
    }
19559×
    order.into_iter().filter_map(|n| files.remove(&n)).collect()
19565×
}
1957
1958
/// Builds the tree ops and edits of a working-copy change against a base.
1959
/// `BLAKE3("oxy node 1" 0 seed kind path)`, truncated: a node identifier
1960
/// that the same seed and path always give (never the root's).
196159×
fn seeded_node(seed: &[u8; 32], path: &str, kind: NodeKind) -> NodeId {
196259×
    let mut h = blake3::Hasher::new();
196359×
    h.update(b"oxy node 1\0");
196459×
    h.update(seed);
196559×
    h.update(&[match kind {
196645×
        NodeKind::File => 1,
196713×
        NodeKind::Dir => 2,
19680×
        NodeKind::Symlink => 3,
19691×
        NodeKind::Subrepo => 4,
1970
    }]);
197159×
    h.update(path.as_bytes());
197259×
    let mut id = [0u8; 16];
197359×
    id.copy_from_slice(&h.finalize().as_bytes()[..16]);
197459×
    if id == [0; 16] {
19750×
        id[15] = 1;
197659×
    }
197759×
    NodeId(id)
197859×
}
1979
1980
struct ChangeBuilder<'a> {
1981
    base: &'a State,
1982
    base_snapshot: &'a Snapshot,
1983
    tree_ops: Vec<TreeOp>,
1984
    edits: Vec<Edit>,
1985
    statuses: Vec<PathStatus>,
1986
    dir_nodes: HashMap<String, NodeId>,
1987
    reuse: HashMap<String, (NodeId, NodeKind)>,
1988
    /// Changes that contributed to conflicts this working copy resolves.
1989
    contributors: BTreeSet<ChangeHash>,
1990
    resolves: bool,
1991
    attrs: crate::attributes::Attributes,
1992
    blobs: HashMap<String, ObjectRef>,
1993
    /// Opaque files whose replace conflict the content settles.
1994
    resolve: HashSet<String>,
1995
    /// When set, new nodes' identifiers derive from it and their paths.
1996
    node_seed: Option<[u8; 32]>,
1997
    /// For a Git import, the base's dead directories by where they were
1998
    /// (see `ensure_dir`), worked out when first needed.
1999
    dead_dirs: Option<HashMap<(NodeId, String), (NodeId, crate::tree::OpKey)>>,
2000
    /// Text edits of edited files, worked out in parallel beforehand
2001
    /// (`diff_in_parallel`); a file not here is diffed when it is updated.
2002
    diffs: HashMap<String, Vec<Edit>>,
2003
}
2004
2005
impl<'a> ChangeBuilder<'a> {
20061939×
    fn new(
20071939×
        base: &'a State,
20081939×
        base_snapshot: &'a Snapshot,
20091939×
        reuse: HashMap<String, (NodeId, NodeKind)>,
20101939×
    ) -> Self {
20111939×
        let mut dir_nodes: HashMap<String, NodeId> = HashMap::new();
20121939×
        dir_nodes.insert(String::new(), NodeId::ROOT);
201317680×
        for (p, e) in base_snapshot.tree.entries.iter() {
201417680×
            if e.kind == NodeKind::Dir {
2015547×
                dir_nodes.insert(p.clone(), e.node);
201617133×
            }
2017
        }
20181939×
        ChangeBuilder {
20191939×
            base,
20201939×
            base_snapshot,
20211939×
            tree_ops: vec![],
20221939×
            edits: vec![],
20231939×
            statuses: vec![],
20241939×
            dir_nodes,
20251939×
            reuse,
20261939×
            contributors: BTreeSet::new(),
20271939×
            resolves: false,
20281939×
            attrs: crate::attributes::Attributes::default(),
20291939×
            blobs: HashMap::new(),
20301939×
            resolve: HashSet::new(),
20311939×
            node_seed: None,
20321939×
            dead_dirs: None,
20331939×
            diffs: HashMap::new(),
20341939×
        }
20351939×
    }
2036
2037
    /// Diff the edited text files among `entries` against their base
2038
    /// renderings at once, on every core, for `update_path` to take: the
2039
    /// same diff it would make, only not one file after another.
20401939×
    fn diff_in_parallel(&mut self, entries: &BTreeMap<String, FsEntry>) {
2041
        use rayon::prelude::*;
20421939×
        let files = &self.base_snapshot.files;
20431939×
        let edited: Vec<(&String, &FsEntry, &crate::state::FileState)> = entries
20441939×
            .iter()
204518664×
            .filter_map(|(p, e)| {
204618664×
                let x = files.get(p)?;
204712652×
                (x.kind == e.kind && !e.unchanged && !self.opaque_for(p, e)).then_some((p, e, x))
204818664×
            })
20491939×
            .collect();
2050
        // Below this, starting the threads costs more than it saves.
20511939×
        if edited.len() < 16 {
20521929×
            return;
205310×
        }
205410×
        let this = &*self;
205510×
        let attrs = &this.attrs;
205610×
        let diffs: Vec<(String, Vec<Edit>)> = edited
205710×
            .par_iter()
20585560×
            .filter_map(|(p, e, x)| {
2059
                let FileContent::Text {
20605560×
                    bytes,
20615560×
                    materialized,
20625560×
                } = &x.content
2063
                else {
20640×
                    return None;
2065
                };
20665560×
                if materialized.is_conflicted() {
20670×
                    return None;
20685560×
                }
20695560×
                let disk_text = if attrs.lookup(p).eol.is_some() {
20700×
                    std::sync::Arc::new(crate::attributes::normalize_eol(&e.content))
2071
                } else {
20725560×
                    e.content.clone()
2073
                };
20745560×
                if *bytes == *disk_text {
20755480×
                    return None;
207680×
                }
207780×
                let keys = materialized.live_atoms();
207880×
                let lines = crate::diff::split_lines(bytes);
207980×
                (keys.len() == lines.len()).then(|| {
208080×
                    let edits = crate::diff::text_edits_of(x.node, &keys, &lines, &disk_text);
208180×
                    ((*p).clone(), edits)
208280×
                })
20835560×
            })
208410×
            .collect();
208510×
        self.diffs = diffs.into_iter().collect();
20861939×
    }
2087
20881939×
    fn with_attributes(mut self, attrs: crate::attributes::Attributes) -> Self {
20891939×
        self.attrs = attrs;
20901939×
        self
20911939×
    }
2092
2093
    /// Whether a file is opaque: forced by `binary`, forced text by `text`
2094
    /// only when it has no NUL bytes, else sniffed.
2095
    /// The blob for an opaque entry: the cached one, else stored now.
2096129×
    fn blob_of(
2097129×
        &mut self,
2098129×
        repo: &Repo,
2099129×
        path: &str,
2100129×
        e: &FsEntry,
2101129×
        nocompress: bool,
2102129×
    ) -> Result<ObjectRef> {
2103129×
        let b = match e.blob {
21040×
            Some(b) => b,
2105129×
            None => repo.store_blob_for(&e.content, nocompress)?,
2106
        };
2107129×
        self.blobs.insert(path.to_string(), b);
2108129×
        Ok(b)
2109129×
    }
2110
211122825×
    fn opaque_for(&self, path: &str, e: &FsEntry) -> bool {
211222825×
        if e.blob.is_some() {
21138×
            return true;
211422817×
        }
211522817×
        if e.kind == NodeKind::Symlink || e.kind == NodeKind::Subrepo {
211675×
            return true;
211722742×
        }
211822742×
        match self.attrs.lookup(path).binary {
211912×
            Some(true) => true,
21200×
            Some(false) => is_binary(&e.content),
212122730×
            None => is_binary(&e.content),
2122
        }
212322825×
    }
2124
2125
    /// Text content as stored: `\r\n` normalized for `eol=` files.
212614289×
    fn stored_text(
212714289×
        &self,
212814289×
        path: &str,
212914289×
        content: &std::sync::Arc<Vec<u8>>,
213014289×
    ) -> std::sync::Arc<Vec<u8>> {
213114289×
        if self.attrs.lookup(path).eol.is_some() {
21327×
            std::sync::Arc::new(crate::attributes::normalize_eol(content))
2133
        } else {
213414282×
            content.clone()
2135
        }
213614289×
    }
2137
2138
    /// The identifier of a node added at `path`: reused when asked, derived
2139
    /// from the seed when there is one, random otherwise.
21406134×
    fn new_node(&self, path: &str, kind: NodeKind) -> NodeId {
21416134×
        if let Some(n) = self.reused_node(path, kind) {
2142137×
            return n;
21435997×
        }
21445997×
        match &self.node_seed {
214559×
            Some(seed) => seeded_node(seed, path, kind),
21465938×
            None => NodeId::random(),
2147
        }
21486134×
    }
2149
21506134×
    fn reused_node(&self, path: &str, kind: NodeKind) -> Option<NodeId> {
21516134×
        self.reuse
21526134×
            .get(path)
21536134×
            .filter(|(_, k)| *k == kind)
21546134×
            .map(|(n, _)| *n)
21556134×
    }
2156
2157
    /// A dead directory last placed at (`parent`, `name`) in the base.
215815×
    fn revivable_dir(
215915×
        &mut self,
216015×
        parent: NodeId,
216115×
        name: &str,
216215×
    ) -> Option<(NodeId, crate::tree::OpKey)> {
216315×
        let base = self.base;
216415×
        self.dead_dirs
216515×
            .get_or_insert_with(|| base.tree().dead_dirs())
216615×
            .get(&(parent, name.to_string()))
216715×
            .copied()
216815×
    }
2169
21706013×
    fn ensure_dir(&mut self, path: &str) -> NodeId {
21716013×
        if let Some(n) = self.dir_nodes.get(path) {
21725864×
            return *n;
2173149×
        }
2174149×
        let mut parent = NodeId::ROOT;
2175149×
        let mut prefix = String::new();
2176168×
        for comp in path.split('/') {
2177168×
            if !prefix.is_empty() {
217819×
                prefix.push('/');
2179149×
            }
2180168×
            prefix.push_str(comp);
2181168×
            let known = self.dir_nodes.get(&prefix).copied();
2182168×
            let revive = match known {
218313×
                Some(_) => None,
2184155×
                None if self.node_seed.is_some() => self.revivable_dir(parent, comp),
2185140×
                None => None,
2186
            };
2187168×
            parent = match (known, revive) {
218813×
                (Some(n), _) => n,
21892×
                (None, Some((node, old))) => {
2190
                    // Git has no identity for a directory: one that comes
2191
                    // back where it was is the same directory, brought back
2192
                    // with a move, so lines of history that placed files in
2193
                    // it before and after agree (oxygen#30).
21942×
                    self.tree_ops.push(TreeOp::Move {
21952×
                        node,
21962×
                        old: OpRef {
21972×
                            change: old.0,
21982×
                            index: old.1,
21992×
                        },
22002×
                        parent,
22012×
                        name: comp.to_string(),
22022×
                    });
22032×
                    self.dir_nodes.insert(prefix.clone(), node);
22042×
                    node
2205
                }
2206
                (None, None) => {
2207153×
                    let node = self.new_node(&prefix, NodeKind::Dir);
2208153×
                    self.tree_ops.push(TreeOp::AddNode {
2209153×
                        node,
2210153×
                        kind: NodeKind::Dir,
2211153×
                        mode: Mode::default(),
2212153×
                        parent,
2213153×
                        name: comp.to_string(),
2214153×
                    });
2215153×
                    self.dir_nodes.insert(prefix.clone(), node);
2216153×
                    node
2217
                }
2218
            };
2219
        }
2220149×
        parent
22216013×
    }
2222
22235981×
    fn add_path(&mut self, repo: &Repo, path: &str, e: &FsEntry) -> Result<()> {
22245981×
        let (dir, name) = split_path(path);
22255981×
        let parent = self.ensure_dir(dir);
22265981×
        let node = self.new_node(path, e.kind);
22275981×
        let opaque = self.opaque_for(path, e);
22285981×
        let nocompress = self.attrs.lookup(path).nocompress;
22295981×
        self.tree_ops.push(TreeOp::AddNode {
22305981×
            node,
22315981×
            kind: e.kind,
22325981×
            mode: Mode {
22335981×
                exec: e.exec,
22345981×
                opaque,
22355981×
            },
22365981×
            parent,
22375981×
            name: name.to_string(),
22385981×
        });
22395981×
        if opaque {
224094×
            let blob = self.blob_of(repo, path, e, nocompress)?;
224194×
            self.edits.push(Edit::Replace {
224294×
                node,
224394×
                old: None,
224494×
                new: Some(blob),
224594×
            });
22465887×
        } else if !e.content.is_empty() {
22475851×
            let content = self.stored_text(path, &e.content);
22485851×
            self.edits.push(Edit::Insert {
22495851×
                node,
22505851×
                after: crate::objects::AtomRef::Start,
22515851×
                before: crate::objects::AtomRef::End,
22525851×
                lines: crate::lines::Lines::split_shared(content),
22535851×
            });
22545851×
        }
22555981×
        self.statuses.push(PathStatus {
22565981×
            path: path.to_string(),
22575981×
            status: ChangeStatus::Added,
22585981×
        });
22595981×
        Ok(())
22605981×
    }
2261
2262
    /// Move the node at `old` to `new` and apply `e`'s content to it.
226332×
    fn move_path(
226432×
        &mut self,
226532×
        repo: &Repo,
226632×
        old: &str,
226732×
        new: &str,
226832×
        e: &FsEntry,
226932×
        expected: &crate::state::FileState,
227032×
    ) -> Result<()> {
227132×
        let placement = self.base_snapshot.tree.entries[old].placement;
227232×
        let (dir, name) = split_path(new);
227332×
        let parent = self.ensure_dir(dir);
227432×
        self.tree_ops.push(TreeOp::Move {
227532×
            node: expected.node,
227632×
            old: op_ref(placement),
227732×
            parent,
227832×
            name: name.to_string(),
227932×
        });
228032×
        for k in self.same_place(&expected.node, placement) {
22810×
            self.tree_ops.push(TreeOp::RemoveNode {
22820×
                node: expected.node,
22830×
                placement: op_ref(k),
22840×
            });
22850×
        }
228632×
        self.update_path(repo, old, e, expected)?;
2287
        // update_path reports under the old path; the rename is what the user sees.
228832×
        self.statuses.retain(|s| s.path != old);
228932×
        self.statuses.push(PathStatus {
229032×
            path: new.to_string(),
229132×
            status: ChangeStatus::Renamed,
229232×
        });
229332×
        Ok(())
229432×
    }
2295
2296
    /// For a Git import: a node the commit keeps is in one place, the one
2297
    /// its tree names, so any other live placement it has in the base goes;
2298
    /// and a node the tree cannot show at all (an orphan) goes too. Such a
2299
    /// placement is out of sight, under a directory another line of history
2300
    /// removed, where no diff of the tree would ever reach it (oxygen#30).
230188×
    fn retire_stray_placements(&mut self) {
230288×
        let mut retired: HashSet<(ChangeHash, u32)> = HashSet::new();
230388×
        let mut placed: BTreeSet<NodeId> = BTreeSet::new();
230499×
        for op in &self.tree_ops {
230599×
            match op {
230619×
                TreeOp::Move { node, old, .. } => {
230719×
                    retired.insert((old.change, old.index));
230819×
                    placed.insert(*node);
230919×
                }
231021×
                TreeOp::RemoveNode { placement, .. } => {
231121×
                    retired.insert((placement.change, placement.index));
231221×
                }
231359×
                TreeOp::AddNode { .. } | TreeOp::SetMode { .. } => {}
2314
            }
2315
        }
2316
        // Nodes kept where they were: what the base's tree view shows and
2317
        // this change neither moves nor removes.
231888×
        let mut kept: HashMap<NodeId, (ChangeHash, u32)> = HashMap::new();
2319241×
        for e in self.base_snapshot.tree.entries.values() {
2320241×
            if !retired.contains(&e.placement) {
2321204×
                kept.insert(e.node, e.placement);
2322204×
            }
2323
        }
2324
        // Only a node with several live placements can have a stray one,
2325
        // and the tree view names each as a conflict.
232688×
        let multi: BTreeSet<NodeId> = self
232788×
            .base_snapshot
232888×
            .tree
232988×
            .conflicts
233088×
            .iter()
233188×
            .filter_map(|c| match c {
23321×
                crate::tree::TreeConflict::MultiPlacement { node, .. } => Some(*node),
23336×
                _ => None,
23347×
            })
233588×
            .collect();
233688×
        let mut extra = Vec::new();
2337
        // A node whose only placements are under a directory another line
2338
        // removed (an orphan) is nowhere the tree can show, and Git's tree
2339
        // has no such path: it goes.
234088×
        for c in &self.base_snapshot.tree.conflicts {
23417×
            let crate::tree::TreeConflict::Orphan { node, .. } = c else {
23426×
                continue;
2343
            };
23441×
            if kept.contains_key(node) || placed.contains(node) {
23450×
                continue;
23461×
            }
23471×
            for (k, _) in self.base.tree().live_placements(node) {
23481×
                if retired.insert(k) {
23491×
                    extra.push(TreeOp::RemoveNode {
23501×
                        node: *node,
23511×
                        placement: op_ref(k),
23521×
                    });
23531×
                }
2354
            }
2355
        }
235688×
        for node in placed
235788×
            .iter()
235888×
            .chain(multi.iter().filter(|n| kept.contains_key(*n)))
2359
        {
236019×
            for (k, _) in self.base.tree().live_placements(node) {
236118×
                if retired.contains(&k) || kept.get(node) == Some(&k) {
236217×
                    continue;
23631×
                }
23641×
                retired.insert(k);
23651×
                extra.push(TreeOp::RemoveNode {
23661×
                    node: *node,
23671×
                    placement: op_ref(k),
23681×
                });
2369
            }
2370
        }
237188×
        if !extra.is_empty() {
23722×
            self.resolves = true;
23732×
            self.tree_ops.extend(extra);
237486×
        }
237588×
    }
2376
2377
    /// The node's other live placements at the same place as `k`, the one
2378
    /// the tree shows: two lines of history that put a node back where it
2379
    /// was each leave a placement, and the tree shows them as one file. A
2380
    /// change that removes or moves it retires them together, or the copy
2381
    /// left behind outlives its directory (oxygen#88).
2382170×
    fn same_place(&self, node: &NodeId, k: (ChangeHash, u32)) -> Vec<(ChangeHash, u32)> {
2383170×
        let tree = self.base.tree();
2384170×
        let Some(shown) = tree.placement(&k) else {
23850×
            return Vec::new();
2386
        };
2387170×
        tree.live_placements(node)
2388170×
            .into_iter()
2389172×
            .filter(|(o, p)| *o != k && p.parent == shown.parent && p.name == shown.name)
2390170×
            .map(|(o, _)| o)
2391170×
            .collect()
2392170×
    }
2393
2394138×
    fn remove_path(&mut self, path: &str, expected: &crate::state::FileState) {
2395138×
        let entry = &self.base_snapshot.tree.entries[path];
2396138×
        let placement = entry.placement;
2397138×
        self.tree_ops.push(TreeOp::RemoveNode {
2398138×
            node: expected.node,
2399138×
            placement: op_ref(placement),
2400138×
        });
2401138×
        for k in self.same_place(&expected.node, placement) {
24021×
            self.tree_ops.push(TreeOp::RemoveNode {
24031×
                node: expected.node,
24041×
                placement: op_ref(k),
24051×
            });
24061×
        }
2407138×
        if path.contains(".oxy-conflict-") || expected.is_conflicted() {
24087×
            self.resolves = true;
2409131×
        }
2410138×
        self.statuses.push(PathStatus {
2411138×
            path: path.to_string(),
2412138×
            status: ChangeStatus::Removed,
2413138×
        });
2414138×
    }
2415
241612684×
    fn update_path(
241712684×
        &mut self,
241812684×
        repo: &Repo,
241912684×
        path: &str,
242012684×
        e: &FsEntry,
242112684×
        expected: &crate::state::FileState,
242212684×
    ) -> Result<()> {
242312684×
        if expected.kind != e.kind {
24241×
            self.remove_path(path, expected);
24251×
            self.statuses.pop();
24261×
            self.add_path(repo, path, e)?;
24271×
            self.statuses.pop();
24281×
            self.statuses.push(PathStatus {
24291×
                path: path.to_string(),
24301×
                status: ChangeStatus::Modified,
24311×
            });
24321×
            return Ok(());
243312683×
        }
243412683×
        let entry = &self.base_snapshot.tree.entries[path];
243512683×
        let node = expected.node;
243612683×
        let mode_atom = entry.mode_atom.map(op_ref);
243712683×
        if e.unchanged {
2438
            // Known equal to the base's unconflicted rendering (spec
2439
            // §12.3); only the executable bit can differ.
24404245×
            if e.exec != expected.mode.exec {
24413×
                if let Some(old) = mode_atom {
24423×
                    self.tree_ops.push(TreeOp::SetMode {
24433×
                        node,
24443×
                        old,
24453×
                        mode: Mode {
24463×
                            exec: e.exec,
24473×
                            opaque: false,
24483×
                        },
24493×
                    });
24503×
                    self.statuses.push(PathStatus {
24513×
                        path: path.to_string(),
24523×
                        status: ChangeStatus::ModeChanged,
24533×
                    });
24543×
                }
24554242×
            }
24564245×
            return Ok(());
24578438×
        }
24588438×
        let mut status: Option<ChangeStatus> = None;
24598438×
        let wants_opaque = self.opaque_for(path, e);
24608438×
        let nocompress = self.attrs.lookup(path).nocompress;
24618438×
        let disk_text = self.stored_text(path, &e.content);
24628438×
        match &expected.content {
24630×
            FileContent::Dir => {}
2464
            FileContent::Text {
24658215×
                bytes,
24668215×
                materialized,
2467
            } => {
24688215×
                if materialized.is_conflicted() {
246933×
                    if bytes == &*disk_text {
24706×
                        return Ok(());
247127×
                    }
247227×
                    if has_conflict_markers(&e.content) {
24734×
                        self.statuses.push(PathStatus {
24744×
                            path: path.to_string(),
24754×
                            status: ChangeStatus::ConflictEdited,
24764×
                        });
24774×
                        return Ok(());
247823×
                    }
2479
                    // Resolution (spec §9.6): diff against the unconflicted lines
2480
                    // with each region as a gap, then retire every region atom.
2481
                    // Whatever the author kept from a region is re-inserted as
2482
                    // new atoms, which leaves the graph totally ordered.
248323×
                    let regions = self.base.conflict_regions(&node);
248423×
                    let mut edits = text_edits(node, &regions.plain, &disk_text);
248523×
                    if !regions.region_atoms.is_empty() {
248623×
                        edits.insert(
248723×
                            0,
248823×
                            Edit::Delete {
248923×
                                node,
249023×
                                atoms: ranges(&regions.region_atoms),
249123×
                            },
249223×
                        );
249323×
                    }
249423×
                    self.edits.extend(edits);
249523×
                    self.contributors.extend(regions.contributors);
249623×
                    self.resolves = true;
249723×
                    if e.exec != expected.mode.exec {
24980×
                        if let Some(old) = mode_atom {
24990×
                            self.tree_ops.push(TreeOp::SetMode {
25000×
                                node,
25010×
                                old,
25020×
                                mode: Mode {
25030×
                                    exec: e.exec,
25040×
                                    opaque: false,
25050×
                                },
25060×
                            });
25070×
                        }
250823×
                    }
250923×
                    self.statuses.push(PathStatus {
251023×
                        path: path.to_string(),
251123×
                        status: ChangeStatus::Resolved,
251223×
                    });
251323×
                    return Ok(());
25148182×
                }
25158182×
                if wants_opaque {
2516
                    // Text → opaque (spec §7.5), by content or by attribute.
25172×
                    if let Some(old) = mode_atom {
25182×
                        self.tree_ops.push(TreeOp::SetMode {
25192×
                            node,
25202×
                            old,
25212×
                            mode: Mode {
25222×
                                exec: e.exec,
25232×
                                opaque: true,
25242×
                            },
25252×
                        });
25262×
                    }
25272×
                    let live: Vec<_> = repo_live_keys(self.base, &node);
25282×
                    if !live.is_empty() {
25292×
                        self.edits.push(Edit::Delete {
25302×
                            node,
25312×
                            atoms: ranges(&live),
25322×
                        });
25332×
                    }
25342×
                    let blob = self.blob_of(repo, path, e, nocompress)?;
25352×
                    self.edits.push(Edit::Replace {
25362×
                        node,
25372×
                        old: None,
25382×
                        new: Some(blob),
25392×
                    });
25402×
                    status = Some(ChangeStatus::Modified);
25418180×
                } else if bytes != &*disk_text {
2542758×
                    let mut laps = crate::timing::Laps::start();
2543
                    // The base's rendering holds its live atoms in order,
2544
                    // one per line (it is not conflicted here).
2545758×
                    let edits = match self.diffs.remove(path) {
254680×
                        Some(edits) => edits,
2547
                        None => {
2548678×
                            let keys = materialized.live_atoms();
2549678×
                            let lines = crate::diff::split_lines(bytes);
2550678×
                            if keys.len() == lines.len() {
2551678×
                                crate::diff::text_edits_of(node, &keys, &lines, &disk_text)
2552
                            } else {
25530×
                                text_edits(node, &self.base.live_lines(&node), &disk_text)
2554
                            }
2555
                        }
2556
                    };
2557758×
                    laps.lap("build: text diff");
2558758×
                    if !edits.is_empty() {
2559758×
                        self.edits.extend(edits);
2560758×
                        status = Some(ChangeStatus::Modified);
2561758×
                    }
25627422×
                }
25638182×
                let switched_to_opaque = wants_opaque;
25648182×
                if !switched_to_opaque && e.exec != expected.mode.exec {
25654×
                    if let Some(old) = mode_atom {
25664×
                        self.tree_ops.push(TreeOp::SetMode {
25674×
                            node,
25684×
                            old,
25694×
                            mode: Mode {
25704×
                                exec: e.exec,
25714×
                                opaque: false,
25724×
                            },
25734×
                        });
25744×
                        status.get_or_insert(ChangeStatus::ModeChanged);
25754×
                    }
25768178×
                }
2577
            }
2578223×
            FileContent::Opaque { blobs } => {
2579223×
                let new_ref = e.blob.unwrap_or_else(|| Repo::blob_ref(&e.content));
2580223×
                if e.kind == NodeKind::File && wants_opaque {
2581191×
                    // Unchanged or replaced, the file stays opaque: remember its blob.
2582191×
                    self.blobs.insert(path.to_string(), new_ref);
2583191×
                }
2584223×
                if blobs.len() > 1 && self.resolve.contains(path) && e.kind == expected.kind {
2585
                    // Settle the replace conflict (spec §9.3): replace every
2586
                    // live candidate with the chosen blob, depending on each
2587
                    // change that made one live, so all are superseded.
25882×
                    let chosen = self.blob_of(repo, path, e, nocompress)?;
25894×
                    for b in blobs {
25904×
                        self.edits.push(Edit::Replace {
25914×
                            node,
25924×
                            old: Some(*b),
25934×
                            new: Some(chosen),
25944×
                        });
25954×
                    }
25962×
                    self.contributors
25972×
                        .extend(self.base.blob_contributors(&node, blobs));
25982×
                    self.resolves = true;
25992×
                    self.statuses.push(PathStatus {
26002×
                        path: path.to_string(),
26012×
                        status: ChangeStatus::Resolved,
26022×
                    });
26032×
                    return Ok(());
2604221×
                }
2605221×
                if blobs.len() > 1 {
26062×
                    if !blobs.contains(&new_ref) {
26070×
                        self.statuses.push(PathStatus {
26080×
                            path: path.to_string(),
26090×
                            status: ChangeStatus::ConflictEdited,
26100×
                        });
26112×
                    }
26122×
                    return Ok(());
2613219×
                }
2614219×
                let current = blobs.first().copied();
2615219×
                if current != Some(new_ref) {
261633×
                    if e.kind == NodeKind::File && !wants_opaque {
2617
                        // Opaque → text (spec §7.5).
26182×
                        if let Some(old) = mode_atom {
26192×
                            self.tree_ops.push(TreeOp::SetMode {
26202×
                                node,
26212×
                                old,
26222×
                                mode: Mode {
26232×
                                    exec: e.exec,
26242×
                                    opaque: false,
26252×
                                },
26262×
                            });
26272×
                        }
26282×
                        self.edits.push(Edit::Replace {
26292×
                            node,
26302×
                            old: current,
26312×
                            new: None,
26322×
                        });
26332×
                        if !e.content.is_empty() {
26342×
                            self.edits.push(Edit::Insert {
26352×
                                node,
26362×
                                after: crate::objects::AtomRef::Start,
26372×
                                before: crate::objects::AtomRef::End,
26382×
                                lines: crate::lines::Lines::split(&e.content),
26392×
                            });
26402×
                        }
2641
                    } else {
264231×
                        let blob = self.blob_of(repo, path, e, nocompress)?;
264331×
                        self.edits.push(Edit::Replace {
264431×
                            node,
264531×
                            old: current,
264631×
                            new: Some(blob),
264731×
                        });
2648
                        // New contents and a new executable bit at once: the
2649
                        // bit was dropped (VS Code's inno_updater.exe,
2650
                        // 2018-02-28, lost +x for 49 commits; oxygen#87).
265131×
                        if e.kind == NodeKind::File && e.exec != expected.mode.exec {
26522×
                            if let Some(old) = mode_atom {
26532×
                                self.tree_ops.push(TreeOp::SetMode {
26542×
                                    node,
26552×
                                    old,
26562×
                                    mode: Mode {
26572×
                                        exec: e.exec,
26582×
                                        opaque: true,
26592×
                                    },
26602×
                                });
26612×
                            }
266229×
                        }
2663
                    }
266433×
                    status = Some(ChangeStatus::Modified);
2665186×
                } else if e.kind == NodeKind::File && e.exec != expected.mode.exec {
26660×
                    if let Some(old) = mode_atom {
26670×
                        self.tree_ops.push(TreeOp::SetMode {
26680×
                            node,
26690×
                            old,
26700×
                            mode: Mode {
26710×
                                exec: e.exec,
26720×
                                opaque: true,
26730×
                            },
26740×
                        });
26750×
                        status = Some(ChangeStatus::ModeChanged);
26760×
                    }
2677186×
                }
2678
            }
2679
        }
26808401×
        if let Some(s) = status {
2681797×
            self.statuses.push(PathStatus {
2682797×
                path: path.to_string(),
2683797×
                status: s,
2684797×
            });
26857604×
        }
26868401×
        Ok(())
268712684×
    }
2688
}
2689
26902×
fn repo_live_keys(base: &State, node: &NodeId) -> Vec<crate::graph::AtomKey> {
26912×
    base.live_lines(node).into_iter().map(|(k, _)| k).collect()
26922×
}
2693
2694
/// The changes a change's scope references (spec §8.1): introducers of every
2695
/// atom, placement, and mode it touches, and of every node it operates on.
26962031×
pub fn referenced_changes(change: &Change, base: &State) -> BTreeSet<ChangeHash> {
26972031×
    let mut out = BTreeSet::new();
26982031×
    let opref = |r: &OpRef, out: &mut BTreeSet<ChangeHash>| {
2699205×
        if !r.change.is_zero() {
2700205×
            out.insert(r.change);
2701205×
        }
2702205×
    };
27032031×
    let mut nodes: Vec<NodeId> = Vec::new();
27046549×
    for op in &change.tree_ops {
27056549×
        match op {
27066344×
            TreeOp::AddNode { parent, .. } => nodes.push(*parent),
2707159×
            TreeOp::RemoveNode { node, placement } => {
2708159×
                nodes.push(*node);
2709159×
                opref(placement, &mut out);
2710159×
            }
2711
            TreeOp::Move {
271234×
                node, old, parent, ..
271334×
            } => {
271434×
                nodes.push(*node);
271534×
                nodes.push(*parent);
271634×
                opref(old, &mut out);
271734×
            }
271812×
            TreeOp::SetMode { node, old, .. } => {
271912×
                nodes.push(*node);
272012×
                opref(old, &mut out);
272112×
            }
2722
        }
2723
    }
27247959×
    for e in &change.edits {
27257959×
        nodes.push(e.node());
2726131×
        match e {
27277333×
            Edit::Insert { after, before, .. } => {
272814666×
                for r in [after, before] {
272914666×
                    if let crate::objects::AtomRef::Atom { change, .. } = r {
27302072×
                        if !change.is_zero() {
27312070×
                            out.insert(*change);
27322070×
                        }
273312594×
                    }
2734
                }
2735
            }
2736495×
            Edit::Delete { atoms, .. } => {
2737
                // Deleting an atom also depends on whoever inserted the live
2738
                // atoms right after it: the author saw those insertions, and
2739
                // without the dependency spec §9.1 would call the deletion
2740
                // concurrent with them (a delete/insert conflict).
2741495×
                let graph = base.file(&e.node());
27421044×
                for r in atoms {
27431044×
                    if !r.change.is_zero() {
27441043×
                        out.insert(r.change);
27451043×
                    }
27461044×
                    if let Some(g) = graph {
27471069×
                        for i in r.from..r.to {
27481069×
                            out.extend(
27491069×
                                g.live_successor_changes(&(r.change, i))
27501069×
                                    .into_iter()
27511069×
                                    .filter(|c| !c.is_zero()),
2752
                            );
2753
                        }
27540×
                    }
2755
                }
2756
            }
2757
            // Replacing a blob depends on the change that made it current,
2758
            // as deleting a line depends on the line's introducer.
2759
            Edit::Replace {
276038×
                node,
276138×
                old: Some(old),
2762
                ..
2763
            } => {
276438×
                out.extend(
276538×
                    base.live_replaces(node)
276638×
                        .into_iter()
276745×
                        .filter(|(c, b)| b == old && !c.is_zero())
276838×
                        .map(|(c, _)| c),
2769
                );
2770
            }
277193×
            Edit::Replace { .. } => {}
2772
        }
2773
    }
277414542×
    for n in nodes {
277514542×
        if let Some(h) = base.tree().introducer(&n) {
27762096×
            out.insert(h);
277712446×
        }
2778
    }
27792031×
    out
27802031×
}
2781
2782
/// Paths of the nodes a change adds on top of `base_snapshot`.
27831272×
pub fn added_node_paths(
27841272×
    change: &Change,
27851272×
    base_snapshot: &Snapshot,
27861272×
) -> HashMap<String, (NodeId, NodeKind)> {
27871272×
    let by_node = base_snapshot.tree.by_node();
27881272×
    let mut new_names: HashMap<NodeId, (NodeId, String, NodeKind)> = HashMap::new();
27891272×
    for op in &change.tree_ops {
2790
        if let TreeOp::AddNode {
279178×
            node,
279278×
            parent,
279378×
            name,
279478×
            kind,
2795
            ..
2796101×
        } = op
279778×
        {
279878×
            new_names.insert(*node, (*parent, name.clone(), *kind));
279978×
        }
2800
    }
28011272×
    let mut out = HashMap::new();
28021272×
    for (node, (_, _, kind)) in &new_names {
280378×
        if let Some(path) = path_of_node(node, &by_node, &new_names) {
280478×
            out.insert(path, (*node, *kind));
280578×
        }
2806
    }
28071272×
    out
28081272×
}
2809
2810187×
fn path_of_node(
2811187×
    n: &NodeId,
2812187×
    by_node: &HashMap<NodeId, &crate::tree::TreeEntry>,
2813187×
    new_names: &HashMap<NodeId, (NodeId, String, NodeKind)>,
2814187×
) -> Option<String> {
2815187×
    if let Some(e) = by_node.get(n) {
281657×
        return Some(e.path.clone());
2817130×
    }
2818130×
    let mut parts = Vec::new();
2819130×
    let mut cur = *n;
2820
    loop {
2821259×
        if cur.is_root() {
2822116×
            break;
2823143×
        }
2824143×
        if let Some(e) = by_node.get(&cur) {
28250×
            if !e.path.is_empty() {
28260×
                parts.push(e.path.clone());
28270×
            }
28280×
            break;
2829143×
        }
2830143×
        let (parent, name, _) = new_names.get(&cur)?;
2831129×
        parts.push(name.clone());
2832129×
        cur = *parent;
2833
    }
2834116×
    parts.reverse();
2835116×
    Some(parts.join("/"))
2836187×
}
2837
2838
/// Render a change's operations with line content, using `base` for deleted lines.
283928×
pub fn render_change(change: &Change, base: &State, base_snapshot: &Snapshot) -> String {
284028×
    let by_node = base_snapshot.tree.by_node();
284128×
    let mut new_names: HashMap<NodeId, (NodeId, String, NodeKind)> = HashMap::new();
284228×
    for op in &change.tree_ops {
2843
        if let TreeOp::AddNode {
284415×
            node,
284515×
            parent,
284615×
            name,
284715×
            kind,
2848
            ..
284922×
        } = op
285015×
        {
285115×
            new_names.insert(*node, (*parent, name.clone(), *kind));
285215×
        }
2853
    }
285466×
    let path_of = |n: &NodeId| -> String {
285566×
        path_of_node(n, &by_node, &new_names).unwrap_or_else(|| format!("<node {}>", n.short(8)))
285666×
    };
2857
285828×
    let mut out = String::new();
285928×
    for op in &change.tree_ops {
286022×
        match op {
2861
            TreeOp::AddNode {
286215×
                node, kind, mode, ..
2863
            } => {
286415×
                out.push_str(&format!(
2865
                    "A {} ({:?}{}{})\n",
286615×
                    path_of(node),
2867
                    kind,
286815×
                    if mode.exec { ", exec" } else { "" },
286915×
                    if mode.opaque { ", opaque" } else { "" }
2870
                ));
2871
            }
28725×
            TreeOp::RemoveNode { node, .. } => out.push_str(&format!("D {}\n", path_of(node))),
2873
            TreeOp::Move {
28742×
                node, parent, name, ..
2875
            } => {
28762×
                let to = if parent.is_root() {
28770×
                    name.clone()
2878
                } else {
28792×
                    format!("{}/{name}", path_of(parent))
2880
                };
28812×
                out.push_str(&format!("R {} -> {to}\n", path_of(node)))
2882
            }
28830×
            TreeOp::SetMode { node, mode, .. } => {
28840×
                out.push_str(&format!(
28850×
                    "M {} mode: exec={} opaque={}\n",
28860×
                    path_of(node),
28870×
                    mode.exec,
28880×
                    mode.opaque
28890×
                ));
28900×
            }
2891
        }
2892
    }
2893
    // Every other file the change edits is modified: the summary names
2894
    // every path it touches, not only those with a tree operation.
289528×
    let with_op: HashSet<NodeId> = change.tree_ops.iter().map(|o| o.node()).collect();
289628×
    let mut listed: HashSet<NodeId> = HashSet::new();
289732×
    for e in &change.edits {
289832×
        let n = e.node();
289932×
        if !with_op.contains(&n) && listed.insert(n) {
290018×
            out.push_str(&format!("M {}\n", path_of(&n)));
290118×
        }
2902
    }
290328×
    let mut last_node: Option<NodeId> = None;
290432×
    for e in &change.edits {
290532×
        let n = e.node();
290632×
        if last_node != Some(n) {
290724×
            out.push_str(&format!("--- {}\n", path_of(&n)));
290824×
            last_node = Some(n);
290924×
        }
291032×
        match e {
291124×
            Edit::Insert { lines, .. } => {
291229×
                for l in lines.iter() {
291329×
                    out.push('+');
291429×
                    out.push_str(&String::from_utf8_lossy(l));
291529×
                    if !l.ends_with(b"\n") {
29160×
                        out.push('\n');
291729×
                    }
2918
                }
2919
            }
29207×
            Edit::Delete { atoms, .. } => {
29217×
                for r in atoms {
29227×
                    for i in r.from..r.to {
29237×
                        let content = base
29247×
                            .file(&n)
29257×
                            .and_then(|g| g.content(&(r.change, i)))
29267×
                            .unwrap_or(b"<unknown>\n");
29277×
                        out.push('-');
29287×
                        out.push_str(&String::from_utf8_lossy(content));
29297×
                        if !content.ends_with(b"\n") {
29300×
                            out.push('\n');
29317×
                        }
2932
                    }
2933
                }
2934
            }
29351×
            Edit::Replace { old, new, .. } => {
29361×
                out.push_str(&format!(
2937
                    "  opaque content {} -> {}\n",
29381×
                    old.map(|o| o.short(12)).unwrap_or_else(|| "none".into()),
29391×
                    new.map(|o| o.short(12)).unwrap_or_else(|| "none".into())
2940
                ));
2941
            }
2942
        }
2943
    }
294428×
    out
294528×
}
2946
2947
/// Pair removed files with added files of the same kind whose contents are
2948
/// at least `RENAME_THRESHOLD` percent alike, best matches first. Beyond
2949
/// `RENAME_LIMIT` candidate pairs only identical contents are paired.
2950
const RENAME_THRESHOLD: u32 = 50;
2951
const RENAME_LIMIT: usize = 10_000;
2952
2953
/// How a change is built beyond its entries: for a Git import, the seed
2954
/// its new nodes' identifiers derive from; and, when it is built from part
2955
/// of the tree, whether the new tree has anything under a directory.
2956
#[derive(Default)]
2957
struct Scope<'a> {
2958
    seed: Option<[u8; 32]>,
2959
    dir_needed: Option<&'a dyn Fn(&str) -> bool>,
2960
}
2961
29621939×
fn detect_renames(
29631939×
    base_snapshot: &Snapshot,
29641939×
    fs_entries: &BTreeMap<String, FsEntry>,
29651939×
    in_scope: impl Fn(&str) -> bool,
29661939×
) -> Vec<(String, String)> {
29671939×
    let removed: Vec<(&String, &crate::state::FileState)> = base_snapshot
29681939×
        .files
29691939×
        .iter()
297013219×
        .filter(|(p, f)| {
297113219×
            f.kind != NodeKind::Dir
297212804×
                && !fs_entries.contains_key(*p)
2973152×
                && in_scope(p)
2974142×
                && !f.is_conflicted()
297513219×
        })
29761939×
        .collect();
29771939×
    let added: Vec<(&String, &FsEntry)> = fs_entries
29781939×
        .iter()
297918664×
        .filter(|(p, e)| e.kind != NodeKind::Dir && !base_snapshot.files.contains_key(*p))
29801939×
        .collect();
29811939×
    if removed.is_empty() || added.is_empty() {
29821882×
        return vec![];
298357×
    }
298457×
    let exact_only = removed.len() * added.len() > RENAME_LIMIT;
298571×
    let old_content = |f: &crate::state::FileState| -> Option<Vec<u8>> {
298671×
        match &f.content {
298767×
            FileContent::Text { bytes, .. } => Some(bytes.clone()),
29884×
            _ => None,
2989
        }
299071×
    };
299157×
    let mut scored: Vec<(u32, usize, usize)> = Vec::new();
299271×
    for (ri, (_, f)) in removed.iter().enumerate() {
299371×
        let old = old_content(f);
299471×
        let old_blob = match &f.content {
29954×
            FileContent::Opaque { blobs } if blobs.len() == 1 => Some(blobs[0]),
299667×
            _ => None,
2997
        };
299890×
        for (ai, (_, e)) in added.iter().enumerate() {
299990×
            if e.kind != f.kind {
30000×
                continue;
300190×
            }
300290×
            let score = match (&old, old_blob) {
300380×
                (Some(o), _) => {
300480×
                    if exact_only {
30050×
                        if *o == *e.content {
30060×
                            100
3007
                        } else {
30080×
                            0
3009
                        }
3010
                    } else {
301180×
                        similarity(o, &e.content)
3012
                    }
3013
                }
301410×
                (None, Some(b)) if e.blob.unwrap_or_else(|| Repo::blob_ref(&e.content)) == b => 100,
30157×
                _ => 0,
3016
            };
301790×
            if score >= RENAME_THRESHOLD {
301838×
                scored.push((score, ri, ai));
301952×
            }
3020
        }
3021
    }
302257×
    scored.sort_by(|a, b| {
30239×
        b.0.cmp(&a.0)
30249×
            .then(removed[a.1].0.cmp(removed[b.1].0))
30259×
            .then(added[a.2].0.cmp(added[b.2].0))
30269×
    });
302757×
    let mut used_r = vec![false; removed.len()];
302857×
    let mut used_a = vec![false; added.len()];
302957×
    let mut out = Vec::new();
303057×
    for (_, ri, ai) in scored {
303138×
        if used_r[ri] || used_a[ai] {
30326×
            continue;
303332×
        }
303432×
        used_r[ri] = true;
303532×
        used_a[ai] = true;
303632×
        out.push((removed[ri].0.clone(), added[ai].0.clone()));
3037
    }
303857×
    out
30391939×
}
3040
3041
/// Percentage of the larger file's bytes found in lines the two share
3042
/// (multiset intersection of lines), like Git's similarity index.
304384×
pub fn similarity(a: &[u8], b: &[u8]) -> u32 {
304484×
    if a == b {
304522×
        return 100;
304662×
    }
304762×
    if a.is_empty() || b.is_empty() {
30484×
        return 0;
304958×
    }
305058×
    let mut counts: HashMap<&[u8], usize> = HashMap::new();
3051115×
    for l in split_lines(a) {
3052115×
        *counts.entry(l).or_default() += 1;
3053115×
    }
305458×
    let mut shared = 0usize;
3055110×
    for l in split_lines(b) {
3056110×
        if let Some(n) = counts.get_mut(l) {
305742×
            if *n > 0 {
305842×
                *n -= 1;
305942×
                shared += l.len();
306042×
            }
306168×
        }
3062
    }
306358×
    (shared * 100 / a.len().max(b.len())) as u32
306484×
}
3065
3066
#[cfg(test)]
3067
mod join_tests {
3068
    use super::*;
3069
3070
    #[test]
30711×
    fn missing_from_finds_what_the_other_lacks() {
30721×
        let a: BTreeMap<String, u8> = [("a", 1), ("b", 2), ("c/d", 3), ("e", 4)]
30731×
            .into_iter()
30744×
            .map(|(k, v)| (k.to_string(), v))
30751×
            .collect();
30761×
        let b: BTreeMap<String, ()> = [("0", ()), ("b", ()), ("c", ()), ("e", ())]
30771×
            .into_iter()
30784×
            .map(|(k, v)| (k.to_string(), v))
30791×
            .collect();
30801×
        let got: Vec<&str> = missing_from(&a, &b)
30811×
            .iter()
30822×
            .map(|(k, _)| k.as_str())
30831×
            .collect();
30841×
        assert_eq!(got, vec!["a", "c/d"]);
30851×
    }
3086
3087
    #[test]
30881×
    fn join_pairs_every_key_in_order() {
30891×
        let a: BTreeMap<String, u8> = [("a", 1), ("b/c", 2), ("d", 3)]
30901×
            .into_iter()
30913×
            .map(|(k, v)| (k.to_string(), v))
30921×
            .collect();
30931×
        let b: BTreeMap<String, char> = [("b", 'x'), ("b/c", 'y'), ("e", 'z')]
30941×
            .into_iter()
30953×
            .map(|(k, v)| (k.to_string(), v))
30961×
            .collect();
30971×
        let got: Vec<(String, Option<u8>, Option<char>)> = join(&a, &b)
30985×
            .map(|(k, x, y)| (k.clone(), x.copied(), y.copied()))
30991×
            .collect();
31001×
        let want = vec![
31011×
            ("a".to_string(), Some(1), None),
31021×
            ("b".to_string(), None, Some('x')),
31031×
            ("b/c".to_string(), Some(2), Some('y')),
31041×
            ("d".to_string(), Some(3), None),
31051×
            ("e".to_string(), None, Some('z')),
3106
        ];
31071×
        assert_eq!(got, want);
31081×
    }
3109
}