OXYGENHUB

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

2175 of 2400 lines run, 282 of 367 functions · run #257 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
8122529×
pub fn is_binary(content: &[u8]) -> bool {
8222529×
    content[..content.len().min(BINARY_SNIFF)].contains(&0)
8322529×
}
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.
1051224×
    fn platform_normalize(&self, entries: &mut BTreeMap<String, FsEntry>, base: &Snapshot) {
1061224×
        let p = self.platform;
1071224×
        if p.exec_bits && p.symlinks {
1081222×
            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
        }
1221224×
    }
123
124
    /// Like `build_against`, for files given in memory (imports).
125956×
    pub(crate) fn build_from_entries(
126956×
        &self,
127956×
        base: &State,
128956×
        base_snapshot: &Snapshot,
129956×
        reuse: HashMap<String, (NodeId, NodeKind)>,
130956×
        fs_entries: &BTreeMap<String, FsEntry>,
131956×
    ) -> Result<BuiltChange> {
132956×
        self.build_from_entries_resolving(base, base_snapshot, reuse, fs_entries, &HashSet::new())
133956×
    }
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.
140970×
    pub(crate) fn build_from_entries_resolving(
141970×
        &self,
142970×
        base: &State,
143970×
        base_snapshot: &Snapshot,
144970×
        reuse: HashMap<String, (NodeId, NodeKind)>,
145970×
        fs_entries: &BTreeMap<String, FsEntry>,
146970×
        resolve: &HashSet<String>,
147970×
    ) -> Result<BuiltChange> {
148970×
        self.build_from_entries_with(
149970×
            base,
150970×
            base_snapshot,
151970×
            reuse,
152970×
            fs_entries,
153970×
            resolve,
154970×
            Scope::default(),
155
        )
156970×
    }
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.
16680×
    pub(crate) fn build_from_entries_seeded(
16780×
        &self,
16880×
        base: &State,
16980×
        base_snapshot: &Snapshot,
17080×
        fs_entries: &BTreeMap<String, FsEntry>,
17180×
        seed: [u8; 32],
17280×
        dir_needed: Option<&dyn Fn(&str) -> bool>,
17380×
    ) -> Result<BuiltChange> {
17480×
        self.build_from_entries_with(
17580×
            base,
17680×
            base_snapshot,
17780×
            HashMap::new(),
17880×
            fs_entries,
17980×
            &HashSet::new(),
18080×
            Scope {
18180×
                seed: Some(seed),
18280×
                dir_needed,
18380×
            },
184
        )
18580×
    }
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.
192797×
    fn build_changed_only(
193797×
        &self,
194797×
        base: &State,
195797×
        base_snapshot: &Snapshot,
196797×
        reuse: HashMap<String, (NodeId, NodeKind)>,
197797×
        fs_entries: &BTreeMap<String, FsEntry>,
198797×
    ) -> Result<BuiltChange> {
199797×
        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.
202797×
        let changed: BTreeMap<String, FsEntry> = join(fs_entries, &base_snapshot.files)
20310916×
            .filter_map(|(p, e, f)| {
20410916×
                let e = e?;
20510791×
                (!e.unchanged || f.is_none_or(|f| f.kind != e.kind || f.mode.exec != e.exec))
20610791×
                    .then(|| (p.clone(), e.clone()))
20710916×
            })
208797×
            .collect();
209797×
        let mut files: BTreeMap<String, crate::state::FileState> = BTreeMap::new();
2106562×
        for p in changed.keys() {
2116562×
            if let Some(f) = base_snapshot.files.get(p) {
2123614×
                files.insert(p.clone(), f.clone());
2133614×
            }
214
        }
215
        // Paths the base has and the disk does not.
216797×
        let gone = join(&base_snapshot.files, fs_entries)
21710916×
            .filter_map(|(p, f, e)| (e.is_none()).then_some((p, f?)));
218797×
        for (p, f) in gone {
219125×
            if f.kind == NodeKind::Dir {
22096×
                continue;
22129×
            }
22229×
            files.insert(p.clone(), f.clone());
22329×
            let mut end = p.len();
22434×
            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
        }
235797×
        let part = Snapshot {
236797×
            tree: base_snapshot.tree.clone(),
237797×
            files,
238797×
            unrendered: BTreeSet::new(),
239797×
        };
240797×
        drop(pick);
241797×
        let _build = crate::timing::phase("snapshot:   of which building the change");
242
        // Whether anything on disk is under `dir`.
243797×
        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×
        };
250797×
        self.build_from_entries_with(
251797×
            base,
252797×
            &part,
253797×
            reuse,
254797×
            &changed,
255797×
            &HashSet::new(),
256797×
            Scope {
257797×
                seed: None,
258797×
                dir_needed: Some(&dir_needed),
259797×
            },
260
        )
261797×
    }
262
2631847×
    fn build_from_entries_with(
2641847×
        &self,
2651847×
        base: &State,
2661847×
        base_snapshot: &Snapshot,
2671847×
        reuse: HashMap<String, (NodeId, NodeKind)>,
2681847×
        fs_entries: &BTreeMap<String, FsEntry>,
2691847×
        resolve: &HashSet<String>,
2701847×
        scope: Scope,
2711847×
    ) -> Result<BuiltChange> {
2721847×
        let Scope { seed, dir_needed } = scope;
2731847×
        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.
2761847×
        let attrs = crate::attributes::Attributes::from_files(
2771847×
            fs_entries
2781847×
                .iter()
27918524×
                .filter(|(p, _)| p.as_str() == ".oxyattributes" || p.ends_with("/.oxyattributes"))
2801847×
                .map(|(p, e)| (p.as_str(), e.content.as_slice())),
281
        );
2821847×
        let mut b = ChangeBuilder::new(base, base_snapshot, reuse).with_attributes(attrs);
2831847×
        b.resolve = resolve.clone();
2841847×
        b.node_seed = seed;
2851847×
        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.
2891847×
        let renames = detect_renames(base_snapshot, fs_entries, |p| self.in_scope(p));
2901847×
        let renamed_from: HashMap<&str, &str> = renames
2911847×
            .iter()
2921847×
            .map(|(old, new)| (new.as_str(), old.as_str()))
2931847×
            .collect();
2941847×
        let renamed_to: HashMap<&str, &str> = renames
2951847×
            .iter()
2961847×
            .map(|(old, new)| (old.as_str(), new.as_str()))
2971847×
            .collect();
2981847×
        laps.lap("build: renames");
2991847×
        b.diff_in_parallel(fs_entries);
3001847×
        laps.lap("build: diffs");
30118524×
        for (path, fs_entry) in fs_entries {
30218524×
            match base_snapshot.files.get(path) {
3035937×
                None => match renamed_from.get(path.as_str()) {
30430×
                    Some(old) => {
30530×
                        b.move_path(self, old, path, fs_entry, &base_snapshot.files[*old])?
306
                    }
3075907×
                    None => b.add_path(self, path, fs_entry)?,
308
                },
30912587×
                Some(expected) => b.update_path(self, path, fs_entry, expected)?,
310
            }
311
        }
3121847×
        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.
3151847×
        let mut needed_dirs: HashSet<&str> = HashSet::new();
31618537×
        fn parents_of<'a>(p: &'a str, set: &mut HashSet<&'a str>) {
31718537×
            let mut end = p.len();
31819185×
            while let Some(i) = p[..end].rfind('/') {
31915430×
                if !set.insert(&p[..i]) {
32014782×
                    break;
321648×
                }
322648×
                end = i;
323
            }
32418537×
        }
32518524×
        for p in fs_entries.keys() {
32618524×
            parents_of(p, &mut needed_dirs);
32718524×
        }
32813137×
        for p in base_snapshot.files.keys() {
32913137×
            if !self.in_scope(p) {
33013×
                parents_of(p, &mut needed_dirs);
33113124×
            }
332
        }
33313137×
        for (path, expected) in &base_snapshot.files {
33413137×
            if fs_entries.contains_key(path)
335550×
                || !self.in_scope(path)
336537×
                || renamed_to.contains_key(path.as_str())
337
            {
33812630×
                continue;
339507×
            }
340507×
            let still_needed = expected.kind == NodeKind::Dir
341411×
                && match dir_needed {
34215×
                    Some(f) => f(path),
343396×
                    None => needed_dirs.contains(path.as_str()),
344
                };
345507×
            if !still_needed {
346122×
                b.remove_path(path, expected);
347385×
            }
348
        }
3491847×
        laps.lap("build: removals");
3501847×
        if seed.is_some() {
35180×
            b.retire_stray_placements();
3521767×
        }
3531847×
        laps.lap("build: stray placements");
3541847×
        let mut statuses = b.statuses;
3555608×
        statuses.sort_by(|a, b| a.path.cmp(&b.path));
3561847×
        Ok(BuiltChange {
3571847×
            tree_ops: b.tree_ops,
3581847×
            edits: b.edits,
3591847×
            contributors: b.contributors.into_iter().collect(),
3601847×
            resolves: b.resolves,
3611847×
            statuses,
3621847×
            blobs: b.blobs,
3631847×
        })
3641847×
    }
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.
369654×
    pub(crate) fn store_signed(&self, change: &Change) -> Result<ChangeHash> {
370654×
        let ours = change.author == self.author();
371654×
        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");
373653×
        }
374653×
        let storing = crate::timing::phase("store: the change");
375653×
        let hash = self.store.put_change(change)?;
376653×
        drop(storing);
377653×
        if self.config.sign_changes && ours {
37840×
            let _t = crate::timing::phase("store: sign it");
37940×
            self.sign_change(&hash)?;
380613×
        }
381653×
        Ok(hash)
382654×
    }
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.
386425×
    pub fn snapshot(&self, command: &str) -> Result<SnapshotResult> {
387425×
        self.snapshot_as(command, false, false)
388425×
    }
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.
398387×
    pub fn snapshot_status(&self, command: &str) -> Result<SnapshotResult> {
399387×
        self.snapshot_as(command, true, false)
400387×
    }
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.
4091225×
    fn snapshot_as(
4101225×
        &self,
4111225×
        command: &str,
4121225×
        partial: bool,
4131225×
        for_commit: bool,
4141225×
    ) -> Result<SnapshotResult> {
4151225×
        let _lock = self.lock_snapshot()?;
4161225×
        let batch = self.store.begin_batch()?;
4171225×
        let result = self.snapshot_locked(command, partial, for_commit);
4181225×
        batch.finish()?;
4191225×
        result
4201225×
    }
421
4221225×
    fn snapshot_locked(
4231225×
        &self,
4241225×
        command: &str,
4251225×
        partial: bool,
4261225×
        for_commit: bool,
4271225×
    ) -> Result<SnapshotResult> {
4281225×
        let _all = crate::timing::phase("snapshot");
4291225×
        let (op_ref, op) = self.head_op()?;
4301225×
        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.
4331223×
        let mut base = {
4341223×
            let _t = crate::timing::phase("snapshot: load base history");
4351223×
            self.load_state_indexed(&old_wc.deps)?
436
        };
4371223×
        let view = {
4381223×
            let _t = crate::timing::phase("snapshot: tree view");
4391223×
            base.tree().view()
440
        };
4411223×
        let manifest = {
4421223×
            let _t = crate::timing::phase("snapshot: read manifest");
4431223×
            self.read_manifest()?.map(|(_, _, m)| m)
444
        };
4451223×
        let tracked: BTreeMap<String, (NodeKind, Option<ObjectRef>)> = {
4461223×
            let _t = crate::timing::phase("snapshot: tracked paths");
447
            // In the view's path order, so the map is built without searching.
4481223×
            view.entries
4491223×
                .iter()
4509438×
                .filter(|(_, e)| e.kind != NodeKind::Dir)
4519046×
                .map(|(p, e)| {
4529046×
                    let blob = if e.kind != NodeKind::File || e.mode.opaque {
453151×
                        base.live_blobs(&e.node).first().copied()
454
                    } else {
4558895×
                        None
456
                    };
4579046×
                    (p.clone(), (e.kind, blob))
4589046×
                })
4591223×
                .collect()
460
        };
461
        // A text file's graph key, worked out when the walk asks for it.
46212003×
        let key_of = |p: &str| -> Option<[u8; 32]> {
46312003×
            let e = view.entries.get(p)?;
4648945×
            if e.kind != NodeKind::File || e.mode.opaque {
465124×
                return None;
4668821×
            }
4678821×
            base.graph_key(&e.node)
46812003×
        };
4691222×
        let mut fs_entries = {
4701223×
            let _t = crate::timing::phase("snapshot: read working copy");
4711223×
            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.
4751222×
        let keys: HashMap<String, [u8; 32]> = fs_entries
4761222×
            .iter()
47712032×
            .filter(|(_, e)| !e.unchanged && e.kind == NodeKind::File)
4787762×
            .filter_map(|(p, _)| Some((p.clone(), key_of(p)?)))
4791222×
            .collect();
4801222×
        let base_snapshot = {
4811222×
            let _t = crate::timing::phase("snapshot: load and render base");
4821222×
            if partial {
483800×
                let sets = crate::timing::phase("snapshot:   of which choosing graphs");
484
                // Every file but those on disk known unchanged.
485800×
                let need: Vec<(&str, NodeId)> = join(&view.entries, &fs_entries)
48610931×
                    .filter_map(|(p, v, f)| {
48710931×
                        let v = v?;
4887982×
                        (v.kind == NodeKind::File && !f.is_some_and(|f| f.unchanged))
4897982×
                            .then_some((p.as_str(), v.node))
49010931×
                    })
491800×
                    .collect();
492800×
                let render: std::collections::HashSet<&str> =
493800×
                    need.iter().map(|(p, _)| *p).collect();
494800×
                let need: Vec<NodeId> = need.iter().map(|(_, n)| *n).collect();
495800×
                drop(sets);
496
                {
497800×
                    let _t = crate::timing::phase("snapshot:   of which building graphs");
498800×
                    self.load_graphs_of(&mut base, &need)?;
499
                }
500800×
                let _t = crate::timing::phase("snapshot:   of which rendering");
501800×
                base.materialize_only(&render)
502
            } else {
503422×
                self.load_all_graphs(&mut base)?;
504422×
                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).
5101222×
        let reuse = added_node_paths(&old_wc, &base_snapshot);
5111222×
        self.platform_normalize(&mut fs_entries, &base_snapshot);
5121222×
        let built = {
5131222×
            let _t = crate::timing::phase("snapshot: diff against base");
5141222×
            if partial && self.config.sparse_paths.is_empty() {
515
                #[cfg(test)]
516525×
                let full =
517525×
                    self.build_from_entries(&base, &base_snapshot, reuse.clone(), &fs_entries)?;
518797×
                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.
5231050×
                    let norm = |b: &BuiltChange| {
5241050×
                        let text = format!("{:?} {:?} {:?}", b.tree_ops, b.edits, b.statuses);
5251050×
                        let mut seen: Vec<String> = Vec::new();
5261050×
                        let mut out = String::new();
5271050×
                        let mut rest = text.as_str();
52819396×
                        while let Some(i) = rest.find("NodeId(") {
52918346×
                            out.push_str(&rest[..i]);
53018346×
                            let end = i + rest[i..].find(')').unwrap() + 1;
53118346×
                            let id = rest[i..end].to_string();
5329045542×
                            let n = seen.iter().position(|x| *x == id).unwrap_or_else(|| {
5336810×
                                seen.push(id);
5346810×
                                seen.len() - 1
5356810×
                            });
53618346×
                            out.push_str(&format!("N{n}"));
53718346×
                            rest = &rest[end..];
538
                        }
5391050×
                        out.push_str(rest);
5401050×
                        out
5411050×
                    };
542525×
                    assert_eq!(
543525×
                        norm(&built),
544525×
                        norm(&full),
545
                        "a changed-only build is the full one"
546
                    );
547
                }
548797×
                built
549
            } else {
550425×
                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
        {
5563654×
            let changed: HashSet<&str> = built.statuses.iter().map(|s| s.path.as_str()).collect();
55712032×
            for (p, e) in fs_entries.iter_mut() {
55812032×
                if e.unchanged || e.kind != NodeKind::File || changed.contains(p.as_str()) {
5597827×
                    continue;
5604205×
                }
5614205×
                e.graph_key = match base_snapshot.files.get(p).map(|f| &f.content) {
562
                    Some(FileContent::Text {
5634093×
                        bytes,
5644093×
                        materialized,
5654093×
                    }) if !materialized.is_conflicted() && *bytes == *e.content => {
5664087×
                        keys.get(p).copied()
567
                    }
568118×
                    _ => None,
569
                };
570
            }
571
        }
572
5731222×
        let mut wc = Change {
5741222×
            version: crate::objects::CHANGE_VERSION,
5751222×
            change_id: old_wc.change_id,
5761222×
            deps: vec![],
5771222×
            author: self.author(),
5781222×
            hlc: old_wc.hlc,
5791222×
            message: old_wc.message.clone(),
5801222×
            tree_ops: built.tree_ops,
5811222×
            edits: built.edits,
5821222×
            kind: ChangeKind::WorkingCopy,
5831222×
        };
5841222×
        let base_heads = base.maximal(&old_wc.deps);
5851222×
        let mut deps: BTreeSet<ChangeHash> = base_heads.into_iter().collect();
5861222×
        deps.extend(referenced_changes(&wc, &base));
5871222×
        deps.extend(built.contributors.iter().copied());
5881222×
        wc.deps = deps.into_iter().collect();
5891222×
        wc.normalize();
5901222×
        let resolves = built.resolves;
5911222×
        let contributors = built.contributors;
5921222×
        let statuses = built.statuses;
593
        // Empty snapshot: hash the candidate before storing; only record an op on change.
5941222×
        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.
6011222×
        let (new_hash, changed, encoded) = if for_commit {
602413×
            (old_hash, true, Vec::new())
603
        } else {
604809×
            let encoded = wc.encode_streaming(|batch| self.store.put_texts(&batch))?;
605809×
            let new_hash = crate::hash::hash_object(crate::hash::ObjectType::Change, &encoded);
606809×
            (new_hash, new_hash != old_hash, encoded)
607
        };
6081222×
        if changed && !for_commit {
609282×
            self.store.put(crate::hash::ObjectType::Change, &encoded)?;
610282×
            let mut view = op.view.clone();
611282×
            view.workspaces.insert(self.workspace, new_hash);
612282×
            self.record_op(&[op_ref], &format!("{command}{SNAPSHOT_SUFFIX}"), view)?;
613940×
        }
6141222×
        drop(record);
615
        // The prompt compares against this without recording anything.
6161222×
        let _t = crate::timing::phase("snapshot: write manifest");
6171222×
        let conflicted = base_snapshot.is_conflicted();
6181222×
        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.
6231222×
        let worth = match self.read_manifest()? {
624413×
            _ if for_commit => true,
625298×
            None => true,
626511×
            Some((c, u, m)) => {
627511×
                c != conflicted
628511×
                    || u != uncommitted
629283×
                    || m.entries.len() != fs_entries.len()
630354×
                    || fs_entries.iter().any(|(p, e)| {
631354×
                        !e.unchanged && (e.graph_key.is_some() || !m.entries.contains_key(p))
632354×
                    })
63343×
                    || built
63443×
                        .blobs
63543×
                        .iter()
63643×
                        .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.
64046×
                    || (uncommitted && statuses.iter().any(|st| {
64146×
                        let Some(e) = fs_entries.get(&st.path) else {
6423×
                            return m.entries.contains_key(&st.path);
643
                        };
64443×
                        let Some(me) = m.entries.get(&st.path) else {
6450×
                            return true;
646
                        };
64743×
                        let hash = e
64843×
                            .content_hash
64943×
                            .unwrap_or_else(|| *blake3::hash(&e.content).as_bytes());
65043×
                        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.
65743×
                        me.hash != hash || me.exec != e.exec || stat != Some((me.size, me.mtime_ns))
65846×
                    }))
659
            }
660
        };
6611222×
        let attributes = crate::attributes::Attributes::from_files(
6621222×
            fs_entries
6631222×
                .iter()
66412032×
                .filter(|(p, _)| is_attributes(p))
6651222×
                .map(|(p, e)| (p.as_str(), e.content.as_slice())),
666
        );
6671222×
        let mut manifest = None;
6681222×
        if for_commit {
669413×
            manifest = Some(PendingManifest {
670413×
                entries: fs_entries,
671413×
                blobs: built.blobs.clone(),
672413×
                dirs: self.walked_dirs.take(),
673413×
                written: super::prompt::now_ns(),
674413×
            });
675413×
        } else {
676809×
            if worth {
677769×
                self.write_manifest_entries(conflicted, uncommitted, &fs_entries, &built.blobs)?;
67840×
            }
679809×
            self.write_status_cache((uncommitted && !conflicted).then_some(&new_hash), &statuses);
680
        }
6811222×
        Ok(SnapshotResult {
6821222×
            wc_hash: new_hash,
6831222×
            wc,
6841222×
            base,
6851222×
            base_snapshot,
6861222×
            statuses,
6871222×
            changed,
6881222×
            resolves,
6891222×
            contributors,
6901222×
            attributes,
6911222×
            untracked_nested: self.untracked_nested.borrow().clone(),
6921222×
            manifest,
6931222×
        })
6941225×
    }
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\":{}}}",
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)))
796
        ))
7977×
    }
798
799
    /// Turn the working-copy change into a normal change on the bookmark (spec §12.3).
800596×
    pub fn commit(&self, message: &str, extra_deps: &[ChangeHash]) -> Result<ChangeHash> {
801596×
        self.commit_selection(message, extra_deps, &Selection::All)
802596×
    }
803
804
    /// The hunks of the working copy, for `oxy commit --interactive`: each
805
    /// tree operation and each edit, in the order `select_hunks` numbers them.
8067×
    pub fn hunks(&self) -> Result<(SnapshotResult, Vec<Hunk>)> {
8077×
        let snap = self.snapshot_status("oxy commit")?;
8087×
        let hunks = render_hunks(&snap.wc, &snap.base, &snap.base_snapshot);
8097×
        Ok((snap, hunks))
8107×
    }
811
812
    /// Commit part of the working copy (spec §12.3). What is not selected
813
    /// stays on disk as uncommitted work: the next snapshot rebuilds it
814
    /// against the new base, so the working copy always describes the
815
    /// directory.
816
    /// The graph key in `st` of each text file at `paths`, the paths a
817
    /// commit changed: only their graphs changed, so the keys the manifest
818
    /// holds for the others still stand (and any that does not is simply
819
    /// not trusted by the next snapshot, which compares keys). Files with
820
    /// an `eol` attribute are left out: their bytes on disk are not the
821
    /// rendering.
822616×
    fn committed_graph_keys(
823616×
        &self,
824616×
        st: &State,
825616×
        paths: &[String],
826616×
        attrs: &crate::attributes::Attributes,
827616×
    ) -> HashMap<String, [u8; 32]> {
828616×
        let _t = crate::timing::phase("commit: graph keys");
829616×
        let view = st.tree().view();
830616×
        paths
831616×
            .iter()
8323434×
            .filter_map(|p| {
8333434×
                let e = view.entries.get(p)?;
8343386×
                (e.kind == NodeKind::File && !e.mode.opaque && attrs.lookup(p).eol.is_none())
8353386×
                    .then_some(())?;
8363337×
                Some((p.clone(), st.graph_key(&e.node)?))
8373434×
            })
838616×
            .collect()
839616×
    }
840
841601×
    pub fn commit_selection(
842601×
        &self,
843601×
        message: &str,
844601×
        extra_deps: &[ChangeHash],
845601×
        selection: &Selection,
846601×
    ) -> Result<ChangeHash> {
847601×
        Ok(self
848601×
            .commit_selection_partial(message, extra_deps, selection)?
849
            .0)
850601×
    }
851
852
    /// As [`Repo::commit_selection`], and whether the commit left part of
853
    /// the working copy uncommitted: when it did not, nothing is left, and
854
    /// no snapshot is needed to say so.
855627×
    pub fn commit_selection_partial(
856627×
        &self,
857627×
        message: &str,
858627×
        extra_deps: &[ChangeHash],
859627×
        selection: &Selection,
860627×
    ) -> Result<(ChangeHash, bool)> {
861
        // The commit's objects are written together, made durable at once
862
        // before the operation that names them (spec §13.6).
863627×
        let batch = self.store.begin_batch()?;
864627×
        let out = self.commit_selection_batched(message, extra_deps, selection);
865627×
        batch.finish()?;
866627×
        out
867627×
    }
868
869
    /// Write the manifest a commit's snapshot left to the commit, with the
870
    /// graph keys `keys` sets.
871404×
    fn write_pending_manifest(
872404×
        &self,
873404×
        mut m: PendingManifest,
874404×
        conflicted: bool,
875404×
        keys: HashMap<String, [u8; 32]>,
876404×
    ) -> Result<()> {
8772801×
        for (path, k) in keys {
8782801×
            if let Some(e) = m.entries.get_mut(&path) {
8792801×
                e.graph_key = Some(k);
8802801×
            }
881
        }
882404×
        self.write_manifest_entries_as_of(
883404×
            conflicted,
884
            false,
885404×
            &m.entries,
886404×
            &m.blobs,
887404×
            m.written,
888404×
            m.dirs.unwrap_or_default(),
889
        )
890404×
    }
891
892627×
    fn commit_selection_batched(
893627×
        &self,
894627×
        message: &str,
895627×
        extra_deps: &[ChangeHash],
896627×
        selection: &Selection,
897627×
    ) -> Result<(ChangeHash, bool)> {
898627×
        let _wc = self.lock_working_copy()?;
899627×
        let mut snap = match self.snapshot_from_cache()? {
900214×
            Some(snap) => snap,
901413×
            None => self.snapshot_as("oxy commit", true, true)?,
902
        };
903627×
        let pending = snap.manifest.take();
904627×
        if snap.wc.tree_ops.is_empty() && snap.wc.edits.is_empty() {
9053×
            if let Some(m) = pending {
9063×
                let conflicted = snap.base_snapshot.is_conflicted();
9073×
                self.write_pending_manifest(m, conflicted, HashMap::new())?;
9080×
            }
9093×
            return fail("nothing to commit: the working copy matches its base");
910624×
        }
911624×
        if let Some(s) = snap
912624×
            .statuses
913624×
            .iter()
9143451×
            .find(|s| s.status == ChangeStatus::ConflictEdited)
915
        {
9160×
            return fail(format!("{} still contains conflict markers", s.path));
917624×
        }
918624×
        if message.trim().is_empty() {
9190×
            return fail("a commit message is required");
920624×
        }
921
        // What the whole working copy references, before a whole commit
922
        // takes its operations over (they are moved, not copied: for a
923
        // large tree they are most of the memory).
924624×
        let wc_refs = referenced_changes(&snap.wc, &snap.base);
9253451×
        let changed_paths: Vec<String> = snap.statuses.iter().map(|s| s.path.clone()).collect();
926624×
        let (tree_ops, edits, partial) = match selection {
927616×
            Selection::All => (
928616×
                std::mem::take(&mut snap.wc.tree_ops),
929616×
                std::mem::take(&mut snap.wc.edits),
930616×
                false,
931616×
            ),
9324×
            Selection::Paths(paths) => {
9334×
                let (o, e) = select_paths(&snap.wc, &snap.base_snapshot, paths);
9344×
                let partial = o.len() != snap.wc.tree_ops.len() || e.len() != snap.wc.edits.len();
9354×
                (o, e, partial)
936
            }
9374×
            Selection::Hunks(indices) => {
9384×
                let (o, e) = select_hunks(&snap.wc, indices);
9394×
                let partial = o.len() != snap.wc.tree_ops.len() || e.len() != snap.wc.edits.len();
9404×
                (o, e, partial)
941
            }
942
        };
943624×
        if tree_ops.is_empty() && edits.is_empty() {
9440×
            return fail("nothing selected to commit");
945624×
        }
946624×
        if partial && snap.resolves {
9470×
            return fail("a conflict resolution must be committed whole");
948624×
        }
949
        // pre-commit hook: may veto.
950624×
        self.run_hook(
951624×
            "pre-commit",
952624×
            &format!(
953
                "{{\"event\":\"pre-commit\",\"message\":{},\"paths\":{}}}",
954624×
                json_str(message),
9553451×
                json_array(snap.statuses.iter().map(|s| format!(
956
                    "{{\"path\":{},\"status\":{}}}",
9573451×
                    json_str(&s.path),
9583451×
                    json_str(&format!("{:?}", s.status))
959
                )))
960
            ),
9611×
        )?;
962623×
        let (op_ref, op) = self.head_op()?;
963623×
        let mut deps: BTreeSet<ChangeHash> = wc_refs;
964
        // semantic-deps hook: may add explicit dependencies (spec §8.1).
965623×
        if self.config.semantic_deps {
9661×
            let touched: Vec<String> = snap.statuses.iter().map(|s| s.path.clone()).collect();
9671×
            let by_node = snap.base_snapshot.tree.by_node();
9681×
            let mut candidates: Vec<(ChangeId, ChangeHash, Vec<String>)> = Vec::new();
9691×
            let mut seen: BTreeSet<ChangeHash> = BTreeSet::new();
9702×
            for h in deps.iter().chain(snap.base.maximal(&snap.wc.deps).iter()) {
9712×
                if !seen.insert(*h) {
9720×
                    continue;
9732×
                }
9742×
                let c = self.store.get_change(h)?;
9752×
                let mut paths: BTreeSet<String> = BTreeSet::new();
9766×
                for n in c
9772×
                    .tree_ops
9782×
                    .iter()
9793×
                    .map(|o| o.node())
9803×
                    .chain(c.edits.iter().map(|e| e.node()))
981
                {
9826×
                    if let Some(e) = by_node.get(&n) {
9836×
                        paths.insert(e.path.clone());
9846×
                    }
985
                }
9862×
                candidates.push((c.change_id, *h, paths.into_iter().collect()));
987
            }
9881×
            for d in self.semantic_deps(&snap.wc.change_id, &touched, &candidates)? {
9891×
                if snap.base.contains(&d) {
9901×
                    deps.insert(d);
9911×
                }
992
            }
993622×
        }
994
        // A resolution depends on every change that contributed to the
995
        // conflict (spec §8.1). Tree and opaque conflicts are resolved through
996
        // ordinary operations whose references already cover the contributors.
997623×
        deps.extend(snap.contributors.iter().copied());
998623×
        for d in extra_deps {
9992×
            if !snap.base.contains(d) {
10000×
                return fail(format!(
1001
                    "--depends-on {d}: not in the working copy's base state"
1002
                ));
10032×
            }
10042×
            deps.insert(*d);
1005
        }
1006623×
        let mut change = Change {
1007
            version: crate::objects::CHANGE_VERSION,
1008623×
            change_id: if partial {
10096×
                ChangeId::random()
1010
            } else {
1011617×
                snap.wc.change_id
1012
            },
1013623×
            deps: vec![],
1014623×
            author: self.author(),
1015623×
            hlc: Hlc::now(),
1016623×
            message: message.trim_end().to_string(),
1017623×
            tree_ops,
1018623×
            edits,
1019623×
            kind: if snap.resolves {
10207×
                ChangeKind::Resolution
1021
            } else {
1022616×
                ChangeKind::Normal
1023
            },
1024
        };
1025623×
        if partial {
1026
            // Dependencies come from what the selected part references, not
1027
            // from the whole working copy.
10286×
            deps = referenced_changes(&change, &snap.base);
10296×
            for d in extra_deps {
10300×
                deps.insert(*d);
10310×
            }
1032617×
        }
1033623×
        change.deps = deps.into_iter().collect();
1034623×
        change.normalize();
1035623×
        let signing = crate::timing::phase("commit: sign and store");
1036623×
        let hash = self.store_signed(&change)?;
1037622×
        drop(signing);
1038622×
        let extending = crate::timing::phase("commit: extend the state");
1039
1040
        // New bookmark heads: maximal elements of old heads plus the new change.
1041
        // The working copy continues on its own base plus the new change, which
1042
        // is exactly what the files on disk contain; the bookmark may hold
1043
        // other heads (and conflicts) the working copy has not checked out.
1044622×
        let old_heads = self.heads_of(&op.view, &self.config.bookmark)?;
1045622×
        let old_base = snap.base.maximal(&snap.wc.deps);
1046622×
        let mut all: Vec<ChangeHash> = old_heads.clone();
1047622×
        all.extend(old_base.iter().copied());
1048622×
        all.push(hash);
1049
        // The snapshot already loaded the working copy's base; when that also
1050
        // holds every bookmark head, it is the state to extend.
1051622×
        let mut st = if old_heads.iter().all(|h| snap.base.contains(h)) {
1052588×
            snap.base
1053
        } else {
105434×
            self.load_state(&all)?
1055
        };
1056622×
        st.add_hashed(hash, change)?;
1057622×
        let mut with_new = old_heads.clone();
1058622×
        with_new.push(hash);
1059622×
        let new_heads = st.maximal(&with_new);
1060
        // Automatic checkpoint once enough changes accumulated (spec §11).
1061622×
        let since = self
1062622×
            .latest_checkpoint(&self.config.bookmark)?
1063622×
            .map(|(_, cp)| cp.count)
1064622×
            .unwrap_or(0);
1065622×
        if self.config.checkpoint_interval > 0
1066622×
            && (st.len() as u64).saturating_sub(since) >= self.config.checkpoint_interval
1067
        {
10682×
            let cp_state = self.load_state_full(&new_heads)?;
10692×
            self.write_checkpoint(&self.config.bookmark, &cp_state, &new_heads)?;
1070620×
        }
1071622×
        let mut wc_base = old_base.clone();
1072622×
        wc_base.push(hash);
1073622×
        let wc_base = st.maximal(&wc_base);
1074622×
        drop(extending);
1075
1076
        // The graph keys of the files as they now are, from the state the
1077
        // commit just extended: a file whose graph it built has none, and
1078
        // is read by the next snapshot; a key the next base does not share
1079
        // (the bookmark held other heads) is simply not trusted then.
1080622×
        let keying = crate::timing::phase("commit: graph keys of the files");
1081622×
        let committed_keys =
1082622×
            (!partial).then(|| self.committed_graph_keys(&st, &changed_paths, &snap.attributes));
1083622×
        drop(keying);
1084622×
        let recording = crate::timing::phase("commit: record");
1085622×
        let wc = self.new_working_copy(wc_base, "");
1086622×
        let wc_hash = self.store.put_change(&wc)?;
1087622×
        let mut view = op.view.clone();
1088622×
        view.bookmarks.insert(
1089622×
            self.config.bookmark.clone(),
1090622×
            self.store.put_state(&StateObject::new(new_heads))?,
1091
        );
1092622×
        view.workspaces.insert(self.workspace, wc_hash);
1093622×
        self.record_op(&[op_ref], &format!("oxy commit -m {message:?}"), view)?;
1094617×
        drop(recording);
1095617×
        let rewriting = crate::timing::phase("commit: manifest");
1096617×
        if partial {
10976×
            // The rest is rebuilt from disk by the next snapshot.
10986×
            self.drop_manifest();
10996×
        } else {
1100611×
            let conflicted = snap.base_snapshot.is_conflicted() && !snap.resolves;
1101
            // The files on disk are now exactly the new base's renderings:
1102
            // record their graph keys, so the next snapshot neither reads nor
1103
            // renders them (oxygen#35).
1104611×
            let keys = if conflicted {
11050×
                HashMap::new()
1106
            } else {
1107611×
                committed_keys.unwrap_or_default()
1108
            };
1109611×
            match pending {
1110401×
                Some(m) => self.write_pending_manifest(m, conflicted, keys)?,
1111210×
                None => self.rewrite_manifest(conflicted, false, &keys)?,
1112
            }
1113
        }
1114617×
        drop(rewriting);
1115617×
        let packing = crate::timing::phase("commit: autopack");
1116617×
        self.maybe_autopack()?;
1117617×
        drop(packing);
1118617×
        let _hook = crate::timing::phase("commit: hook");
1119617×
        let _ = self.run_hook(
1120617×
            "post-commit",
1121617×
            &format!(
1122617×
                "{{\"event\":\"post-commit\",\"change_id\":{},\"hash\":{},\"message\":{}}}",
1123617×
                json_str(&snap.wc.change_id.to_hex()),
1124617×
                json_str(&hash.to_hex()),
1125617×
                json_str(message)
1126617×
            ),
1127617×
        );
1128617×
        Ok((hash, partial))
1129627×
    }
1130
}
1131
1132
/// What part of the working copy a commit takes (spec §12.3).
1133
#[derive(Clone, Debug)]
1134
pub enum Selection {
1135
    All,
1136
    /// Every operation and edit on nodes under these paths.
1137
    Paths(Vec<String>),
1138
    /// Hunk indices as `Repo::hunks` numbers them; dependent hunks are added.
1139
    Hunks(Vec<usize>),
1140
}
1141
1142
/// One selectable piece of the working copy: a tree operation or an edit.
1143
#[derive(Clone, Debug)]
1144
pub struct Hunk {
1145
    pub index: usize,
1146
    pub path: String,
1147
    /// Rendered like `oxy diff`.
1148
    pub text: String,
1149
}
1150
1151
/// The tree operations and edits on nodes under `paths`, plus the
1152
/// additions of any new parent directories they need.
11534×
fn select_paths(
11544×
    wc: &Change,
11554×
    base_snapshot: &Snapshot,
11564×
    paths: &[String],
11574×
) -> (Vec<TreeOp>, Vec<Edit>) {
115813×
    let selected = |p: &str| {
115913×
        paths
116013×
            .iter()
116113×
            .any(|x| p == x || p.starts_with(&format!("{}/", x.trim_end_matches('/'))))
116213×
    };
11634×
    let by_node = base_snapshot.tree.by_node();
11644×
    let mut new_names: HashMap<NodeId, (NodeId, String, NodeKind)> = HashMap::new();
11654×
    for op in &wc.tree_ops {
1166
        if let TreeOp::AddNode {
11671×
            node,
11681×
            parent,
11691×
            name,
11701×
            kind,
1171
            ..
11721×
        } = op
11731×
        {
11741×
            new_names.insert(*node, (*parent, name.clone(), *kind));
11751×
        }
1176
    }
11774×
    let mut nodes: BTreeSet<NodeId> = BTreeSet::new();
117813×
    for n in wc
11794×
        .tree_ops
11804×
        .iter()
11814×
        .map(|o| o.node())
118212×
        .chain(wc.edits.iter().map(|e| e.node()))
1183
    {
118413×
        if path_of_node(&n, &by_node, &new_names).is_some_and(|p| selected(&p)) {
11858×
            nodes.insert(n);
11868×
        }
1187
    }
1188
    // New parents of selected new nodes come along.
11894×
    let mut changed = true;
11908×
    while changed {
11914×
        changed = false;
11924×
        for (n, (parent, _, _)) in &new_names {
11931×
            if nodes.contains(n) && new_names.contains_key(parent) && nodes.insert(*parent) {
11940×
                changed = true;
11951×
            }
1196
        }
1197
    }
11984×
    let ops = wc
11994×
        .tree_ops
12004×
        .iter()
12014×
        .filter(|o| nodes.contains(&o.node()))
12024×
        .cloned()
12034×
        .collect();
12044×
    let edits = wc
12054×
        .edits
12064×
        .iter()
120712×
        .filter(|e| nodes.contains(&e.node()))
12084×
        .cloned()
12094×
        .collect();
12104×
    (ops, edits)
12114×
}
1212
1213
/// The hunks `indices` name plus whatever they refer to within the working
1214
/// copy (the parent directory of an added node, the insert that introduced
1215
/// an anchor line), renumbered so the result is a well-formed change.
12165×
fn select_hunks(wc: &Change, indices: &[usize]) -> (Vec<TreeOp>, Vec<Edit>) {
12175×
    let n_ops = wc.tree_ops.len();
12185×
    let mut ops_sel = vec![false; n_ops];
12195×
    let mut edits_sel = vec![false; wc.edits.len()];
12205×
    for &i in indices {
12214×
        if i < n_ops {
12221×
            ops_sel[i] = true;
12233×
        } else if i - n_ops < wc.edits.len() {
12243×
            edits_sel[i - n_ops] = true;
12253×
        }
1226
    }
1227
    // Atom ranges each insert introduces, per node, in the working copy's numbering.
12285×
    let mut per_node: HashMap<NodeId, u32> = HashMap::new();
12295×
    let mut insert_ranges: Vec<Option<(NodeId, u32, u32)>> = Vec::new();
123010×
    for e in &wc.edits {
123110×
        insert_ranges.push(match e {
123210×
            Edit::Insert { node, lines, .. } => {
123310×
                let start = per_node.entry(*node).or_default();
123410×
                let r = (*node, *start, *start + lines.len() as u32);
123510×
                *start += lines.len() as u32;
123610×
                Some(r)
1237
            }
12380×
            _ => None,
1239
        });
1240
    }
12415×
    let add_index: HashMap<NodeId, usize> = wc
12425×
        .tree_ops
12435×
        .iter()
12445×
        .enumerate()
12458×
        .filter_map(|(i, o)| {
12468×
            if let TreeOp::AddNode { node, .. } = o {
12478×
                Some((*node, i))
1248
            } else {
12490×
                None
1250
            }
12518×
        })
12525×
        .collect();
12535×
    let insert_for = |node: &NodeId, index: u32| -> Option<usize> {
12540×
        insert_ranges
12550×
            .iter()
12560×
            .position(|r| matches!(r, Some((n, a, b)) if n == node && *a <= index && index < *b))
12570×
    };
1258
    // Closure.
12595×
    let mut changed = true;
126013×
    while changed {
12618×
        changed = false;
126217×
        for i in 0..n_ops {
126317×
            if !ops_sel[i] {
126411×
                continue;
12656×
            }
12666×
            if let TreeOp::AddNode { node, parent, .. } = &wc.tree_ops[i] {
12676×
                if let Some(&p) = add_index.get(parent) {
12684×
                    if !ops_sel[p] {
12692×
                        ops_sel[p] = true;
12702×
                        changed = true;
12712×
                    }
12722×
                }
1273
                // A new node's content belongs with its addition: nobody
1274
                // wants an empty file committed apart from its lines.
127512×
                for (j, e) in wc.edits.iter().enumerate() {
127612×
                    if e.node() == *node && !edits_sel[j] {
12771×
                        edits_sel[j] = true;
12781×
                        changed = true;
127911×
                    }
1280
                }
12810×
            }
1282
        }
128316×
        for j in 0..wc.edits.len() {
128416×
            if !edits_sel[j] {
12859×
                continue;
12867×
            }
12877×
            let e = &wc.edits[j];
12887×
            if let Some(&a) = add_index.get(&e.node()) {
12895×
                if !ops_sel[a] {
12901×
                    ops_sel[a] = true;
12911×
                    changed = true;
12924×
                }
12932×
            }
1294
            if let Edit::Insert {
12957×
                node,
12967×
                after,
12977×
                before,
1298
                ..
12997×
            } = e
1300
            {
130114×
                for r in [after, before] {
130214×
                    if let AtomRef::Atom { change, index } = r {
13032×
                        if change.is_zero() {
13040×
                            if let Some(k) = insert_for(node, *index) {
13050×
                                if !edits_sel[k] {
13060×
                                    edits_sel[k] = true;
13070×
                                    changed = true;
13080×
                                }
13090×
                            }
13102×
                        }
131112×
                    }
1312
                }
13130×
            }
1314
        }
1315
    }
1316
    // Renumber self-references: old atom index → new index among selected inserts.
13175×
    let mut remap: HashMap<(NodeId, u32), u32> = HashMap::new();
13185×
    let mut new_counts: HashMap<NodeId, u32> = HashMap::new();
131910×
    for (j, r) in insert_ranges.iter().enumerate() {
132010×
        if let (true, Some((node, a, b))) = (edits_sel[j], r) {
13214×
            let next = new_counts.entry(*node).or_default();
13224×
            for old in *a..*b {
13234×
                remap.insert((*node, old), *next);
13244×
                *next += 1;
13254×
            }
13266×
        }
1327
    }
13288×
    let map_ref = |r: AtomRef, node: &NodeId| -> AtomRef {
13292×
        match r {
13302×
            AtomRef::Atom { change, index } if change.is_zero() => AtomRef::Atom {
13310×
                change,
13320×
                index: remap.get(&(*node, index)).copied().unwrap_or(index),
13330×
            },
13348×
            other => other,
1335
        }
13368×
    };
13375×
    let ops = wc
13385×
        .tree_ops
13395×
        .iter()
13405×
        .enumerate()
13418×
        .filter(|(i, _)| ops_sel[*i])
13425×
        .map(|(_, o)| o.clone())
13435×
        .collect();
13445×
    let edits = wc
13455×
        .edits
13465×
        .iter()
13475×
        .enumerate()
134810×
        .filter(|(j, _)| edits_sel[*j])
13495×
        .map(|(_, e)| match e {
1350
            Edit::Insert {
13514×
                node,
13524×
                after,
13534×
                before,
13544×
                lines,
13554×
            } => Edit::Insert {
13564×
                node: *node,
13574×
                after: map_ref(*after, node),
13584×
                before: map_ref(*before, node),
13594×
                lines: lines.clone(),
13604×
            },
13610×
            other => other.clone(),
13624×
        })
13635×
        .collect();
13645×
    (ops, edits)
13655×
}
1366
1367
/// Render each tree operation and edit of `change` on its own, numbered.
13687×
pub fn render_hunks(change: &Change, base: &State, base_snapshot: &Snapshot) -> Vec<Hunk> {
13697×
    let by_node = base_snapshot.tree.by_node();
13707×
    let mut new_names: HashMap<NodeId, (NodeId, String, NodeKind)> = HashMap::new();
13718×
    for op in &change.tree_ops {
1372
        if let TreeOp::AddNode {
13738×
            node,
13748×
            parent,
13758×
            name,
13768×
            kind,
1377
            ..
13788×
        } = op
13798×
        {
13808×
            new_names.insert(*node, (*parent, name.clone(), *kind));
13818×
        }
1382
    }
13837×
    let mut out = Vec::new();
13848×
    for (i, op) in change.tree_ops.iter().enumerate() {
13858×
        let one = Change {
13868×
            tree_ops: vec![op.clone()],
13878×
            edits: vec![],
13888×
            ..change.clone()
13898×
        };
13908×
        let path = path_of_node(&op.node(), &by_node, &new_names).unwrap_or_default();
13918×
        out.push(Hunk {
13928×
            index: i,
13938×
            path,
13948×
            text: render_change(&one, base, base_snapshot),
13958×
        });
13968×
    }
139713×
    for (j, e) in change.edits.iter().enumerate() {
139813×
        let one = Change {
139913×
            tree_ops: vec![],
140013×
            edits: vec![e.clone()],
140113×
            ..change.clone()
140213×
        };
140313×
        let path = path_of_node(&e.node(), &by_node, &new_names).unwrap_or_default();
140413×
        out.push(Hunk {
140513×
            index: change.tree_ops.len() + j,
140613×
            path,
140713×
            text: render_change(&one, base, base_snapshot),
140813×
        });
140913×
    }
14107×
    out
14117×
}
1412
1413
/// One file's part of a diff, for `oxy diff --json`.
1414
#[derive(Clone, Debug)]
1415
pub struct FileDiff {
1416
    pub path: String,
1417
    /// `added`, `removed`, `modified`, `renamed`, `mode`, `replaced`.
1418
    pub kind: String,
1419
    pub hunks: Vec<DiffHunk>,
1420
    /// For renames, the previous path.
1421
    pub from: Option<String>,
1422
}
1423
1424
/// Lines inserted after `base_line` (0 = before the first line) and lines
1425
/// removed, with their base line numbers.
1426
#[derive(Clone, Debug, Default)]
1427
pub struct DiffHunk {
1428
    pub base_line: u32,
1429
    pub added: Vec<Vec<u8>>,
1430
    pub removed: Vec<(u32, Vec<u8>)>,
1431
}
1432
1433
impl Repo {
1434
    /// The content of `path` in a state: `heads`, or the working copy's base.
14357×
    pub fn file_at(&self, path: &str, heads: Option<&[ChangeHash]>) -> Result<Vec<u8>> {
1436
        // The state's history and tree, then the one file's graph: nothing
1437
        // else is built or rendered (oxygen#92).
1438
        // The working copy's base, and a state named by its heads (`-r
1439
        // main` on main), come from the workspace's state index.
14407×
        let base = if self.is_bare() {
14415×
            None
1442
        } else {
14432×
            Some(self.working_copy()?.1.deps)
1444
        };
14457×
        let same = |a: &[ChangeHash], b: &[ChangeHash]| {
14461×
            let (mut a, mut b) = (a.to_vec(), b.to_vec());
14471×
            a.sort();
14481×
            b.sort();
14491×
            a == b
14501×
        };
14517×
        let mut state = match (heads, base) {
14521×
            (Some(h), Some(b)) if same(h, &b) => self.load_state_indexed(&b)?,
14535×
            (Some(h), _) => self.load_state_history(h)?,
14541×
            (None, Some(b)) => self.load_state_indexed(&b)?,
14550×
            (None, None) => return fail("this is a bare repository: it has no working copy"),
1456
        };
14577×
        let view = state.tree().view();
14587×
        let Some(node) = view.entries.get(path).map(|e| e.node) else {
14590×
            return fail(format!("{path} is not in that state"));
1460
        };
14617×
        self.load_graphs_of(&mut state, &[node])?;
14627×
        let snapshot = state.materialize_paths(view, [path]);
14637×
        let Some(f) = snapshot.files.get(path) else {
14640×
            return fail(format!("{path} is not in that state"));
1465
        };
14667×
        match &f.content {
14670×
            FileContent::Dir => fail(format!("{path} is a directory")),
14687×
            FileContent::Text { bytes, .. } => Ok(bytes.clone()),
14690×
            FileContent::Opaque { blobs } => match blobs.first() {
14700×
                Some(b) => self.read_blob(b),
14710×
                None => Ok(vec![]),
1472
            },
1473
        }
14747×
    }
1475
1476
    /// Restore `paths` (files or directories) to the working copy's base:
1477
    /// edits are undone, additions removed, removals put back. Returns the
1478
    /// number of paths touched.
14792×
    pub fn discard(&self, paths: &[String]) -> Result<usize> {
14802×
        let _wc = self.lock_working_copy()?;
14812×
        let snap = self.snapshot_status("oxy discard")?;
14827×
        let under = |p: &str| {
14837×
            paths
14847×
                .iter()
14857×
                .any(|x| p == x || p.starts_with(&format!("{}/", x.trim_end_matches('/'))))
14867×
        };
14872×
        let attrs = Repo::state_attributes(&snap.base_snapshot);
14882×
        let mut n = 0;
14893×
        for s in &snap.statuses {
14903×
            if !under(&s.path) {
14911×
                continue;
14922×
            }
14932×
            match snap.base_snapshot.files.get(&s.path) {
1494
                None => {
1495
                    // Added (or the new name of a rename): remove it.
14961×
                    let full = self.root.join(&s.path);
14971×
                    if full.is_dir() {
14980×
                        let _ = fs::remove_dir_all(&full);
14991×
                    } else {
15001×
                        let _ = fs::remove_file(&full);
15011×
                    }
15021×
                    n += 1;
1503
                }
15041×
                Some(f) => {
15051×
                    match &f.content {
15060×
                        FileContent::Dir => fs::create_dir_all(self.root.join(&s.path))?,
15071×
                        FileContent::Text { bytes, .. } => {
15081×
                            let on_disk: std::borrow::Cow<[u8]> = if attrs.lookup(&s.path).eol
15091×
                                == Some(crate::attributes::Eol::Crlf)
1510
                            {
15110×
                                crate::attributes::to_crlf(bytes).into()
1512
                            } else {
15131×
                                bytes.as_slice().into()
1514
                            };
15151×
                            self.write_file(&s.path, &on_disk, f.mode.exec)?;
1516
                        }
15170×
                        FileContent::Opaque { blobs } => {
15180×
                            let bytes = match blobs.first() {
15190×
                                Some(b) => self.read_blob(b)?,
15200×
                                None => vec![],
1521
                            };
15220×
                            if f.kind == NodeKind::Symlink {
15230×
                                self.write_symlink(&s.path, &bytes)?;
15240×
                            } else if f.kind == NodeKind::File {
15250×
                                self.write_file(&s.path, &bytes, f.mode.exec)?;
15260×
                            }
1527
                        }
1528
                    }
15291×
                    n += 1;
1530
                }
1531
            }
1532
        }
1533
        // A rename's old name is not in the statuses; put it back too.
15344×
        for (p, f) in &snap.base_snapshot.files {
15354×
            if under(p)
15361×
                && !self.root.join(p).exists()
15370×
                && f.kind != NodeKind::Dir
15380×
                && f.kind != NodeKind::Subrepo
15390×
                && !snap.statuses.iter().any(|s| s.path == *p)
1540
            {
15410×
                let bytes = match &f.content {
15420×
                    FileContent::Text { bytes, .. } => bytes.clone(),
15430×
                    FileContent::Opaque { blobs } => blobs
15440×
                        .first()
15450×
                        .map(|b| self.read_blob(b))
15460×
                        .transpose()?
15470×
                        .unwrap_or_default(),
15480×
                    FileContent::Dir => continue,
1549
                };
15500×
                if f.kind == NodeKind::Symlink {
15510×
                    self.write_symlink(p, &bytes)?
1552
                } else {
15530×
                    self.write_file(p, &bytes, f.mode.exec)?
1554
                }
15550×
                n += 1;
15564×
            }
1557
        }
15582×
        self.drop_manifest();
15592×
        Ok(n)
15602×
    }
1561
1562
    /// Undo the working-copy hunks `indices` (as `hunks` numbers them) on
1563
    /// disk, keeping the others: the files are rewritten from the base plus
1564
    /// the remaining hunks.
15651×
    pub fn discard_hunks(&self, indices: &[usize]) -> Result<usize> {
15661×
        let _wc = self.lock_working_copy()?;
15671×
        let (snap, hunks) = self.hunks()?;
15681×
        let keep: Vec<usize> = hunks
15691×
            .iter()
15701×
            .map(|h| h.index)
15711×
            .filter(|i| !indices.contains(i))
15721×
            .collect();
15731×
        let (ops, edits) = select_hunks(&snap.wc, &keep);
15741×
        let dropped_nodes: BTreeSet<NodeId> = hunks
15751×
            .iter()
15761×
            .filter(|h| indices.contains(&h.index))
15771×
            .map(|h| {
15781×
                if h.index < snap.wc.tree_ops.len() {
15790×
                    snap.wc.tree_ops[h.index].node()
1580
                } else {
15811×
                    snap.wc.edits[h.index - snap.wc.tree_ops.len()].node()
1582
                }
15831×
            })
15841×
            .collect();
15851×
        let mut partial = snap.wc.clone();
15861×
        partial.tree_ops = ops;
15871×
        partial.edits = edits;
15881×
        partial.normalize();
15891×
        let mut st = snap.base.clone();
15901×
        st.add_unchecked(partial);
1591
        // Every file of the target is rendered: build the graphs the
1592
        // partial snapshot left out.
15931×
        self.load_all_graphs(&mut st)?;
15941×
        let target = st.materialize();
15951×
        let by_node_target = target.tree.by_node();
15961×
        let by_node_base = snap.base_snapshot.tree.by_node();
15971×
        let attrs = Repo::state_attributes(&target);
15981×
        let mut n = 0;
15991×
        for node in dropped_nodes {
16001×
            match by_node_target.get(&node) {
16011×
                Some(e) => {
16021×
                    let f = &target.files[&e.path];
16031×
                    match &f.content {
16040×
                        FileContent::Dir => {}
16051×
                        FileContent::Text { bytes, .. } => {
16061×
                            let on_disk: std::borrow::Cow<[u8]> = if attrs.lookup(&e.path).eol
16071×
                                == Some(crate::attributes::Eol::Crlf)
1608
                            {
16090×
                                crate::attributes::to_crlf(bytes).into()
1610
                            } else {
16111×
                                bytes.as_slice().into()
1612
                            };
16131×
                            self.write_file(&e.path, &on_disk, f.mode.exec)?;
1614
                        }
16150×
                        FileContent::Opaque { blobs } => {
16160×
                            let bytes = blobs
16170×
                                .first()
16180×
                                .map(|b| self.read_blob(b))
16190×
                                .transpose()?
16200×
                                .unwrap_or_default();
16210×
                            if f.kind == NodeKind::Symlink {
16220×
                                self.write_symlink(&e.path, &bytes)?
1623
                            } else {
16240×
                                self.write_file(&e.path, &bytes, f.mode.exec)?
1625
                            }
1626
                        }
1627
                    }
1628
                    // A discarded rename: the new name goes.
16291×
                    if let Some(old_path) = snap
16301×
                        .statuses
16311×
                        .iter()
16321×
                        .find(|s| {
16331×
                            s.status == ChangeStatus::Renamed && !target.files.contains_key(&s.path)
16341×
                        })
16351×
                        .map(|s| s.path.clone())
16360×
                    {
16370×
                        let _ = fs::remove_file(self.root.join(old_path));
16381×
                    }
16391×
                    n += 1;
1640
                }
1641
                None => {
1642
                    // The node exists in neither target nor base with a live path: an addition to remove.
16430×
                    if let Some(added) = snap.statuses.iter().find(|s| {
16440×
                        s.status == ChangeStatus::Added
16450×
                            && !target.files.contains_key(&s.path)
16460×
                            && !by_node_base.contains_key(&node)
16470×
                    }) {
16480×
                        let full = self.root.join(&added.path);
16490×
                        if full.is_dir() {
16500×
                            let _ = fs::remove_dir_all(&full);
16510×
                        } else {
16520×
                            let _ = fs::remove_file(&full);
16530×
                        }
16540×
                        n += 1;
16550×
                    }
1656
                }
1657
            }
1658
        }
16591×
        self.drop_manifest();
16601×
        Ok(n)
16611×
    }
1662
1663
    /// The diff of the working copy (`None`) or of a change, per file with
1664
    /// line-numbered hunks (spec: `oxy diff --json`).
16655×
    pub fn diff_files(&self, change: Option<&ChangeHash>) -> Result<Vec<FileDiff>> {
16665×
        let (c, base, base_snapshot) = match change {
16672×
            Some(h) => {
16682×
                let c = self.store.get_change(h)?;
16692×
                let (base, snapshot) = self.change_base(&c)?;
16702×
                (c, base, snapshot)
1671
            }
16723×
            None => self.working_copy_with_base()?,
1673
        };
16745×
        Ok(diff_files_of(&c, &base, &base_snapshot))
16755×
    }
1676
1677
    /// The snapshot a command would take, without taking it, when the
1678
    /// status cache holds: every file is as the last snapshot left it, so
1679
    /// that snapshot's working-copy change is the answer. Its base comes
1680
    /// from the state index, the `.oxyattributes` files from disk. `None`
1681
    /// when a snapshot must be taken, and when there is nothing to commit
1682
    /// (the snapshot then says so). A conflicted base never gets here: the
1683
    /// cache does not hold for one.
1684628×
    pub(crate) fn snapshot_from_cache(&self) -> Result<Option<SnapshotResult>> {
1685628×
        let Some(statuses) = self.status_by_manifest()? else {
1686411×
            return Ok(None);
1687
        };
1688217×
        if statuses.is_empty() {
16892×
            return Ok(None);
1690215×
        }
1691215×
        let _t = crate::timing::phase("snapshot: from the status cache");
1692215×
        let (wc_hash, wc) = self.working_copy()?;
1693215×
        let base = self.load_state_indexed(&wc.deps)?;
1694215×
        let (base, base_snapshot) = self.render_base_for(&wc, base)?;
1695215×
        let attribute_files: Vec<(String, Vec<u8>)> = match self.read_manifest()? {
1696215×
            Some((_, _, m)) => m
1697215×
                .entries
1698215×
                .keys()
1699674×
                .filter(|p| is_attributes(p))
1700215×
                .filter_map(|p| fs::read(self.root.join(p)).ok().map(|b| (p.clone(), b)))
1701215×
                .collect(),
17020×
            None => Vec::new(),
1703
        };
1704215×
        let attributes = crate::attributes::Attributes::from_files(
1705215×
            attribute_files
1706215×
                .iter()
1707215×
                .map(|(p, b)| (p.as_str(), b.as_slice())),
1708
        );
1709215×
        Ok(Some(SnapshotResult {
1710215×
            wc_hash,
1711215×
            wc,
1712215×
            base,
1713215×
            base_snapshot,
1714215×
            statuses,
1715215×
            changed: false,
1716215×
            resolves: false,
1717215×
            contributors: Vec::new(),
1718215×
            attributes,
1719215×
            untracked_nested: self.untracked_nested.borrow().clone(),
1720215×
            manifest: None,
1721215×
        }))
1722628×
    }
1723
1724
    /// The working-copy change with its base state and a snapshot of the
1725
    /// base, for showing what the working copy changes ([`render_change`],
1726
    /// [`diff_files_of`]). While the status cache holds (every file as the
1727
    /// last snapshot left it), the stored working-copy change is the
1728
    /// answer, no snapshot is taken, and the base's snapshot holds its tree
1729
    /// but no file; otherwise a snapshot makes all three.
17304×
    pub fn working_copy_with_base(&self) -> Result<(Change, State, Snapshot)> {
17314×
        if self.status_by_manifest()?.is_some() {
17322×
            let (_, wc) = self.working_copy()?;
17332×
            let base = self.load_state_indexed(&wc.deps)?;
17342×
            let (base, snapshot) = self.tree_base_for(&wc, base)?;
17352×
            return Ok((wc, base, snapshot));
17362×
        }
17372×
        let snap = self.snapshot_status("oxy diff")?;
17382×
        Ok((snap.wc, snap.base, snap.base_snapshot))
17394×
    }
1740
1741
    /// The log restricted to changes touching `path` (its node, so renames
1742
    /// are followed), on the current bookmark.
17435×
    pub fn log_for_path(&self, path: &str) -> Result<Vec<LogEntry>> {
17445×
        let heads = self.bookmark_heads()?;
17455×
        if self.is_bare() {
17461×
            return self.log_for_path_in(path, &heads);
17474×
        }
17484×
        let entries = self.log()?;
17494×
        let (_, wc) = self.working_copy()?;
1750
        // The path's node from the trees alone: the base's (from the
1751
        // workspace's state index), else the bookmark's. Nothing is
1752
        // rendered.
17534×
        let node_in = |state: State| state.tree().view().entries.get(path).map(|e| e.node);
17544×
        let node = match node_in(self.load_state_indexed(&wc.deps)?) {
17554×
            Some(n) => Some(n),
17560×
            None => node_in(self.load_state_history(&heads)?),
1757
        };
17584×
        let Some(node) = node else {
17590×
            return fail(format!("{path} is not tracked"));
1760
        };
17614×
        Ok(self.entries_touching(entries, node))
17625×
    }
1763
1764
    /// The log of the state with these heads restricted to changes touching
1765
    /// `path` (its node, so renames are followed).
17662×
    pub fn log_for_path_in(&self, path: &str, heads: &[ChangeHash]) -> Result<Vec<LogEntry>> {
17672×
        self.log_for_path_of(&self.load_state_history(heads)?, path, None)
17682×
    }
1769
1770
    /// The changes of a loaded state touching `path`, newest first, at most
1771
    /// `limit` of them. The path is found in the state's tree alone, so no
1772
    /// file is rendered, and the walk stops once `limit` are found.
17735×
    pub fn log_for_path_of(
17745×
        &self,
17755×
        state: &State,
17765×
        path: &str,
17775×
        limit: Option<usize>,
17785×
    ) -> Result<Vec<LogEntry>> {
17795×
        let Some(node) = state.tree().view().entries.get(path).map(|e| e.node) else {
17801×
            return fail(format!("{path} is not in that state"));
1781
        };
17824×
        Ok(self.entries_touching_up_to(self.log_of(state), node, limit))
17835×
    }
1784
17854×
    fn entries_touching(&self, entries: Vec<LogEntry>, node: NodeId) -> Vec<LogEntry> {
17864×
        self.entries_touching_up_to(entries, node, None)
17874×
    }
1788
17898×
    fn entries_touching_up_to(
17908×
        &self,
17918×
        entries: Vec<LogEntry>,
17928×
        node: NodeId,
17938×
        limit: Option<usize>,
17948×
    ) -> Vec<LogEntry> {
17958×
        let mut touched = self.touched();
17968×
        if limit.is_none() {
17977×
            let hashes: Vec<ChangeHash> = entries.iter().map(|e| e.hash).collect();
17987×
            touched.fill(self, &hashes);
17991×
        }
18008×
        let wanted = HashSet::from([node]);
18018×
        let mut out = Vec::new();
180228×
        for e in entries {
180328×
            if limit.is_some_and(|n| out.len() >= n) {
18041×
                break;
180527×
            }
180627×
            if touched.touches(self, &e.hash, &wanted) {
180718×
                out.push(e);
180818×
            }
1809
        }
18108×
        touched.save();
18118×
        out
18128×
    }
1813
}
1814
1815
/// Per-file hunks of `change` against `base`.
18165×
pub fn diff_files_of(change: &Change, base: &State, base_snapshot: &Snapshot) -> Vec<FileDiff> {
18175×
    let by_node = base_snapshot.tree.by_node();
18185×
    let mut new_names: HashMap<NodeId, (NodeId, String, NodeKind)> = HashMap::new();
18195×
    for op in &change.tree_ops {
1820
        if let TreeOp::AddNode {
18212×
            node,
18222×
            parent,
18232×
            name,
18242×
            kind,
1825
            ..
18263×
        } = op
18272×
        {
18282×
            new_names.insert(*node, (*parent, name.clone(), *kind));
18292×
        }
1830
    }
18319×
    let path_of = |n: &NodeId| -> String {
18329×
        path_of_node(n, &by_node, &new_names).unwrap_or_else(|| format!("<node {}>", n.short(8)))
18339×
    };
18345×
    let mut files: BTreeMap<NodeId, FileDiff> = BTreeMap::new();
18355×
    let mut order: Vec<NodeId> = Vec::new();
183614×
    let mut entry = |files: &mut BTreeMap<NodeId, FileDiff>, n: NodeId, kind: &str| {
183714×
        if let std::collections::btree_map::Entry::Vacant(v) = files.entry(n) {
18389×
            order.push(n);
18399×
            v.insert(FileDiff {
18409×
                path: path_of(&n),
18419×
                kind: kind.to_string(),
18429×
                hunks: vec![],
18439×
                from: None,
18449×
            });
18459×
        }
184614×
    };
18475×
    for op in &change.tree_ops {
18483×
        match op {
18492×
            TreeOp::AddNode { node, kind, .. } => {
18502×
                if *kind != NodeKind::Dir {
18512×
                    entry(&mut files, *node, "added");
18522×
                }
1853
            }
18541×
            TreeOp::RemoveNode { node, .. } => {
18551×
                entry(&mut files, *node, "removed");
18561×
                if let Some(e) = by_node.get(node) {
18571×
                    files.get_mut(node).unwrap().path = e.path.clone();
18581×
                }
1859
            }
1860
            TreeOp::Move {
18610×
                node, parent, name, ..
1862
            } => {
18630×
                entry(&mut files, *node, "renamed");
18640×
                let f = files.get_mut(node).unwrap();
18650×
                f.from = by_node.get(node).map(|e| e.path.clone());
18660×
                let dir = if parent.is_root() {
18670×
                    String::new()
1868
                } else {
18690×
                    path_of_node(parent, &by_node, &new_names).unwrap_or_default()
1870
                };
18710×
                f.path = if dir.is_empty() {
18720×
                    name.clone()
1873
                } else {
18740×
                    format!("{dir}/{name}")
1875
                };
1876
            }
18770×
            TreeOp::SetMode { node, .. } => entry(&mut files, *node, "mode"),
1878
        }
1879
    }
1880
    // Base line numbers per node, 1-based.
18815×
    let mut line_of: HashMap<NodeId, HashMap<(ChangeHash, u32), u32>> = HashMap::new();
188211×
    let mut lines_for = |n: &NodeId| -> HashMap<(ChangeHash, u32), u32> {
188311×
        line_of
188411×
            .entry(*n)
188511×
            .or_insert_with(|| {
18868×
                base.live_lines(n)
18878×
                    .into_iter()
18888×
                    .enumerate()
188911×
                    .map(|(i, (k, _))| (k, i as u32 + 1))
18908×
                    .collect()
18918×
            })
189211×
            .clone()
189311×
    };
189411×
    for e in &change.edits {
189511×
        let n = e.node();
189611×
        let is_new = new_names.contains_key(&n);
189711×
        entry(&mut files, n, if is_new { "added" } else { "modified" });
189811×
        let f = files.get_mut(&n).unwrap();
189911×
        match e {
19009×
            Edit::Insert { after, lines, .. } => {
19019×
                let map = lines_for(&n);
19029×
                let base_line = match after {
19033×
                    AtomRef::Start => 0,
19040×
                    AtomRef::End => map.len() as u32,
19056×
                    AtomRef::Atom { change, index } if change.is_zero() => {
19060×
                        f.hunks.last().map(|h| h.base_line).unwrap_or(0)
1907
                    }
19086×
                    AtomRef::Atom { change, index } => {
19096×
                        map.get(&(*change, *index)).copied().unwrap_or(0)
1910
                    }
1911
                };
19129×
                f.hunks.push(DiffHunk {
19139×
                    base_line,
19149×
                    added: lines.to_vec(),
19159×
                    removed: vec![],
19169×
                });
1917
            }
19182×
            Edit::Delete { atoms, .. } => {
19192×
                let map = lines_for(&n);
19202×
                let mut removed = Vec::new();
19212×
                for r in atoms {
19222×
                    for i in r.from..r.to {
19232×
                        let line = map.get(&(r.change, i)).copied().unwrap_or(0);
19242×
                        let text = base
19252×
                            .file(&n)
19262×
                            .and_then(|g| g.content(&(r.change, i)))
19272×
                            .unwrap_or(b"")
19282×
                            .to_vec();
19292×
                        removed.push((line, text));
1930
                    }
1931
                }
19322×
                let base_line = removed
19332×
                    .first()
19342×
                    .map(|(l, _)| l.saturating_sub(1))
19352×
                    .unwrap_or(0);
19362×
                f.hunks.push(DiffHunk {
19372×
                    base_line,
19382×
                    added: vec![],
19392×
                    removed,
19402×
                });
1941
            }
1942
            Edit::Replace { .. } => {
19430×
                if !is_new {
19440×
                    f.kind = "replaced".into();
19450×
                }
1946
            }
1947
        }
1948
    }
19499×
    order.into_iter().filter_map(|n| files.remove(&n)).collect()
19505×
}
1951
1952
/// Builds the tree ops and edits of a working-copy change against a base.
1953
/// `BLAKE3("oxy node 1" 0 seed kind path)`, truncated: a node identifier
1954
/// that the same seed and path always give (never the root's).
195553×
fn seeded_node(seed: &[u8; 32], path: &str, kind: NodeKind) -> NodeId {
195653×
    let mut h = blake3::Hasher::new();
195753×
    h.update(b"oxy node 1\0");
195853×
    h.update(seed);
195953×
    h.update(&[match kind {
196041×
        NodeKind::File => 1,
196111×
        NodeKind::Dir => 2,
19620×
        NodeKind::Symlink => 3,
19631×
        NodeKind::Subrepo => 4,
1964
    }]);
196553×
    h.update(path.as_bytes());
196653×
    let mut id = [0u8; 16];
196753×
    id.copy_from_slice(&h.finalize().as_bytes()[..16]);
196853×
    if id == [0; 16] {
19690×
        id[15] = 1;
197053×
    }
197153×
    NodeId(id)
197253×
}
1973
1974
struct ChangeBuilder<'a> {
1975
    base: &'a State,
1976
    base_snapshot: &'a Snapshot,
1977
    tree_ops: Vec<TreeOp>,
1978
    edits: Vec<Edit>,
1979
    statuses: Vec<PathStatus>,
1980
    dir_nodes: HashMap<String, NodeId>,
1981
    reuse: HashMap<String, (NodeId, NodeKind)>,
1982
    /// Changes that contributed to conflicts this working copy resolves.
1983
    contributors: BTreeSet<ChangeHash>,
1984
    resolves: bool,
1985
    attrs: crate::attributes::Attributes,
1986
    blobs: HashMap<String, ObjectRef>,
1987
    /// Opaque files whose replace conflict the content settles.
1988
    resolve: HashSet<String>,
1989
    /// When set, new nodes' identifiers derive from it and their paths.
1990
    node_seed: Option<[u8; 32]>,
1991
    /// For a Git import, the base's dead directories by where they were
1992
    /// (see `ensure_dir`), worked out when first needed.
1993
    dead_dirs: Option<HashMap<(NodeId, String), (NodeId, crate::tree::OpKey)>>,
1994
    /// Text edits of edited files, worked out in parallel beforehand
1995
    /// (`diff_in_parallel`); a file not here is diffed when it is updated.
1996
    diffs: HashMap<String, Vec<Edit>>,
1997
}
1998
1999
impl<'a> ChangeBuilder<'a> {
20001847×
    fn new(
20011847×
        base: &'a State,
20021847×
        base_snapshot: &'a Snapshot,
20031847×
        reuse: HashMap<String, (NodeId, NodeKind)>,
20041847×
    ) -> Self {
20051847×
        let mut dir_nodes: HashMap<String, NodeId> = HashMap::new();
20061847×
        dir_nodes.insert(String::new(), NodeId::ROOT);
200717589×
        for (p, e) in base_snapshot.tree.entries.iter() {
200817589×
            if e.kind == NodeKind::Dir {
2009545×
                dir_nodes.insert(p.clone(), e.node);
201017044×
            }
2011
        }
20121847×
        ChangeBuilder {
20131847×
            base,
20141847×
            base_snapshot,
20151847×
            tree_ops: vec![],
20161847×
            edits: vec![],
20171847×
            statuses: vec![],
20181847×
            dir_nodes,
20191847×
            reuse,
20201847×
            contributors: BTreeSet::new(),
20211847×
            resolves: false,
20221847×
            attrs: crate::attributes::Attributes::default(),
20231847×
            blobs: HashMap::new(),
20241847×
            resolve: HashSet::new(),
20251847×
            node_seed: None,
20261847×
            dead_dirs: None,
20271847×
            diffs: HashMap::new(),
20281847×
        }
20291847×
    }
2030
2031
    /// Diff the edited text files among `entries` against their base
2032
    /// renderings at once, on every core, for `update_path` to take: the
2033
    /// same diff it would make, only not one file after another.
20341847×
    fn diff_in_parallel(&mut self, entries: &BTreeMap<String, FsEntry>) {
2035
        use rayon::prelude::*;
20361847×
        let files = &self.base_snapshot.files;
20371847×
        let edited: Vec<(&String, &FsEntry, &crate::state::FileState)> = entries
20381847×
            .iter()
203918524×
            .filter_map(|(p, e)| {
204018524×
                let x = files.get(p)?;
204112587×
                (x.kind == e.kind && !e.unchanged && !self.opaque_for(p, e)).then_some((p, e, x))
204218524×
            })
20431847×
            .collect();
2044
        // Below this, starting the threads costs more than it saves.
20451847×
        if edited.len() < 16 {
20461837×
            return;
204710×
        }
204810×
        let this = &*self;
204910×
        let attrs = &this.attrs;
205010×
        let diffs: Vec<(String, Vec<Edit>)> = edited
205110×
            .par_iter()
20525564×
            .filter_map(|(p, e, x)| {
2053
                let FileContent::Text {
20545564×
                    bytes,
20555564×
                    materialized,
20565564×
                } = &x.content
2057
                else {
20580×
                    return None;
2059
                };
20605564×
                if materialized.is_conflicted() {
20610×
                    return None;
20625564×
                }
20635564×
                let disk_text = if attrs.lookup(p).eol.is_some() {
20640×
                    std::sync::Arc::new(crate::attributes::normalize_eol(&e.content))
2065
                } else {
20665564×
                    e.content.clone()
2067
                };
20685564×
                if *bytes == *disk_text {
20695484×
                    return None;
207080×
                }
207180×
                let keys = materialized.live_atoms();
207280×
                let lines = crate::diff::split_lines(bytes);
207380×
                (keys.len() == lines.len()).then(|| {
207480×
                    let edits = crate::diff::text_edits_of(x.node, &keys, &lines, &disk_text);
207580×
                    ((*p).clone(), edits)
207680×
                })
20775564×
            })
207810×
            .collect();
207910×
        self.diffs = diffs.into_iter().collect();
20801847×
    }
2081
20821847×
    fn with_attributes(mut self, attrs: crate::attributes::Attributes) -> Self {
20831847×
        self.attrs = attrs;
20841847×
        self
20851847×
    }
2086
2087
    /// Whether a file is opaque: forced by `binary`, forced text by `text`
2088
    /// only when it has no NUL bytes, else sniffed.
2089
    /// The blob for an opaque entry: the cached one, else stored now.
2090126×
    fn blob_of(
2091126×
        &mut self,
2092126×
        repo: &Repo,
2093126×
        path: &str,
2094126×
        e: &FsEntry,
2095126×
        nocompress: bool,
2096126×
    ) -> Result<ObjectRef> {
2097126×
        let b = match e.blob {
20980×
            Some(b) => b,
2099126×
            None => repo.store_blob_for(&e.content, nocompress)?,
2100
        };
2101126×
        self.blobs.insert(path.to_string(), b);
2102126×
        Ok(b)
2103126×
    }
2104
210522624×
    fn opaque_for(&self, path: &str, e: &FsEntry) -> bool {
210622624×
        if e.blob.is_some() {
21078×
            return true;
210822616×
        }
210922616×
        if e.kind == NodeKind::Symlink || e.kind == NodeKind::Subrepo {
211075×
            return true;
211122541×
        }
211222541×
        match self.attrs.lookup(path).binary {
211312×
            Some(true) => true,
21140×
            Some(false) => is_binary(&e.content),
211522529×
            None => is_binary(&e.content),
2116
        }
211722624×
    }
2118
2119
    /// Text content as stored: `\r\n` normalized for `eol=` files.
212014154×
    fn stored_text(
212114154×
        &self,
212214154×
        path: &str,
212314154×
        content: &std::sync::Arc<Vec<u8>>,
212414154×
    ) -> std::sync::Arc<Vec<u8>> {
212514154×
        if self.attrs.lookup(path).eol.is_some() {
21267×
            std::sync::Arc::new(crate::attributes::normalize_eol(content))
2127
        } else {
212814147×
            content.clone()
2129
        }
213014154×
    }
2131
2132
    /// The identifier of a node added at `path`: reused when asked, derived
2133
    /// from the seed when there is one, random otherwise.
21346061×
    fn new_node(&self, path: &str, kind: NodeKind) -> NodeId {
21356061×
        if let Some(n) = self.reused_node(path, kind) {
2136122×
            return n;
21375939×
        }
21385939×
        match &self.node_seed {
213953×
            Some(seed) => seeded_node(seed, path, kind),
21405886×
            None => NodeId::random(),
2141
        }
21426061×
    }
2143
21446061×
    fn reused_node(&self, path: &str, kind: NodeKind) -> Option<NodeId> {
21456061×
        self.reuse
21466061×
            .get(path)
21476061×
            .filter(|(_, k)| *k == kind)
21486061×
            .map(|(n, _)| *n)
21496061×
    }
2150
2151
    /// A dead directory last placed at (`parent`, `name`) in the base.
215213×
    fn revivable_dir(
215313×
        &mut self,
215413×
        parent: NodeId,
215513×
        name: &str,
215613×
    ) -> Option<(NodeId, crate::tree::OpKey)> {
215713×
        let base = self.base;
215813×
        self.dead_dirs
215913×
            .get_or_insert_with(|| base.tree().dead_dirs())
216013×
            .get(&(parent, name.to_string()))
216113×
            .copied()
216213×
    }
2163
21645938×
    fn ensure_dir(&mut self, path: &str) -> NodeId {
21655938×
        if let Some(n) = self.dir_nodes.get(path) {
21665789×
            return *n;
2167149×
        }
2168149×
        let mut parent = NodeId::ROOT;
2169149×
        let mut prefix = String::new();
2170167×
        for comp in path.split('/') {
2171167×
            if !prefix.is_empty() {
217218×
                prefix.push('/');
2173149×
            }
2174167×
            prefix.push_str(comp);
2175167×
            let known = self.dir_nodes.get(&prefix).copied();
2176167×
            let revive = match known {
217712×
                Some(_) => None,
2178155×
                None if self.node_seed.is_some() => self.revivable_dir(parent, comp),
2179142×
                None => None,
2180
            };
2181167×
            parent = match (known, revive) {
218212×
                (Some(n), _) => n,
21832×
                (None, Some((node, old))) => {
2184
                    // Git has no identity for a directory: one that comes
2185
                    // back where it was is the same directory, brought back
2186
                    // with a move, so lines of history that placed files in
2187
                    // it before and after agree (oxygen#30).
21882×
                    self.tree_ops.push(TreeOp::Move {
21892×
                        node,
21902×
                        old: OpRef {
21912×
                            change: old.0,
21922×
                            index: old.1,
21932×
                        },
21942×
                        parent,
21952×
                        name: comp.to_string(),
21962×
                    });
21972×
                    self.dir_nodes.insert(prefix.clone(), node);
21982×
                    node
2199
                }
2200
                (None, None) => {
2201153×
                    let node = self.new_node(&prefix, NodeKind::Dir);
2202153×
                    self.tree_ops.push(TreeOp::AddNode {
2203153×
                        node,
2204153×
                        kind: NodeKind::Dir,
2205153×
                        mode: Mode::default(),
2206153×
                        parent,
2207153×
                        name: comp.to_string(),
2208153×
                    });
2209153×
                    self.dir_nodes.insert(prefix.clone(), node);
2210153×
                    node
2211
                }
2212
            };
2213
        }
2214149×
        parent
22155938×
    }
2216
22175908×
    fn add_path(&mut self, repo: &Repo, path: &str, e: &FsEntry) -> Result<()> {
22185908×
        let (dir, name) = split_path(path);
22195908×
        let parent = self.ensure_dir(dir);
22205908×
        let node = self.new_node(path, e.kind);
22215908×
        let opaque = self.opaque_for(path, e);
22225908×
        let nocompress = self.attrs.lookup(path).nocompress;
22235908×
        self.tree_ops.push(TreeOp::AddNode {
22245908×
            node,
22255908×
            kind: e.kind,
22265908×
            mode: Mode {
22275908×
                exec: e.exec,
22285908×
                opaque,
22295908×
            },
22305908×
            parent,
22315908×
            name: name.to_string(),
22325908×
        });
22335908×
        if opaque {
223491×
            let blob = self.blob_of(repo, path, e, nocompress)?;
223591×
            self.edits.push(Edit::Replace {
223691×
                node,
223791×
                old: None,
223891×
                new: Some(blob),
223991×
            });
22405817×
        } else if !e.content.is_empty() {
22415781×
            let content = self.stored_text(path, &e.content);
22425781×
            self.edits.push(Edit::Insert {
22435781×
                node,
22445781×
                after: crate::objects::AtomRef::Start,
22455781×
                before: crate::objects::AtomRef::End,
22465781×
                lines: crate::lines::Lines::split_shared(content),
22475781×
            });
22485781×
        }
22495908×
        self.statuses.push(PathStatus {
22505908×
            path: path.to_string(),
22515908×
            status: ChangeStatus::Added,
22525908×
        });
22535908×
        Ok(())
22545908×
    }
2255
2256
    /// Move the node at `old` to `new` and apply `e`'s content to it.
225730×
    fn move_path(
225830×
        &mut self,
225930×
        repo: &Repo,
226030×
        old: &str,
226130×
        new: &str,
226230×
        e: &FsEntry,
226330×
        expected: &crate::state::FileState,
226430×
    ) -> Result<()> {
226530×
        let entry = &self.base_snapshot.tree.entries[old];
226630×
        let (dir, name) = split_path(new);
226730×
        let parent = self.ensure_dir(dir);
226830×
        self.tree_ops.push(TreeOp::Move {
226930×
            node: expected.node,
227030×
            old: op_ref(entry.placement),
227130×
            parent,
227230×
            name: name.to_string(),
227330×
        });
227430×
        self.update_path(repo, old, e, expected)?;
2275
        // update_path reports under the old path; the rename is what the user sees.
227630×
        self.statuses.retain(|s| s.path != old);
227730×
        self.statuses.push(PathStatus {
227830×
            path: new.to_string(),
227930×
            status: ChangeStatus::Renamed,
228030×
        });
228130×
        Ok(())
228230×
    }
2283
2284
    /// For a Git import: a node the commit keeps is in one place, the one
2285
    /// its tree names, so any other live placement it has in the base goes;
2286
    /// and a node the tree cannot show at all (an orphan) goes too. Such a
2287
    /// placement is out of sight, under a directory another line of history
2288
    /// removed, where no diff of the tree would ever reach it (oxygen#30).
228980×
    fn retire_stray_placements(&mut self) {
229080×
        let mut retired: HashSet<(ChangeHash, u32)> = HashSet::new();
229180×
        let mut placed: BTreeSet<NodeId> = BTreeSet::new();
229285×
        for op in &self.tree_ops {
229385×
            match op {
229416×
                TreeOp::Move { node, old, .. } => {
229516×
                    retired.insert((old.change, old.index));
229616×
                    placed.insert(*node);
229716×
                }
229816×
                TreeOp::RemoveNode { placement, .. } => {
229916×
                    retired.insert((placement.change, placement.index));
230016×
                }
230153×
                TreeOp::AddNode { .. } | TreeOp::SetMode { .. } => {}
2302
            }
2303
        }
2304
        // Nodes kept where they were: what the base's tree view shows and
2305
        // this change neither moves nor removes.
230680×
        let mut kept: HashMap<NodeId, (ChangeHash, u32)> = HashMap::new();
2307223×
        for e in self.base_snapshot.tree.entries.values() {
2308223×
            if !retired.contains(&e.placement) {
2309193×
                kept.insert(e.node, e.placement);
2310193×
            }
2311
        }
2312
        // Only a node with several live placements can have a stray one,
2313
        // and the tree view names each as a conflict.
231480×
        let multi: BTreeSet<NodeId> = self
231580×
            .base_snapshot
231680×
            .tree
231780×
            .conflicts
231880×
            .iter()
231980×
            .filter_map(|c| match c {
23201×
                crate::tree::TreeConflict::MultiPlacement { node, .. } => Some(*node),
23216×
                _ => None,
23227×
            })
232380×
            .collect();
232480×
        let mut extra = Vec::new();
2325
        // A node whose only placements are under a directory another line
2326
        // removed (an orphan) is nowhere the tree can show, and Git's tree
2327
        // has no such path: it goes.
232880×
        for c in &self.base_snapshot.tree.conflicts {
23297×
            let crate::tree::TreeConflict::Orphan { node, .. } = c else {
23306×
                continue;
2331
            };
23321×
            if kept.contains_key(node) || placed.contains(node) {
23330×
                continue;
23341×
            }
23351×
            for (k, _) in self.base.tree().live_placements(node) {
23361×
                if retired.insert(k) {
23371×
                    extra.push(TreeOp::RemoveNode {
23381×
                        node: *node,
23391×
                        placement: op_ref(k),
23401×
                    });
23411×
                }
2342
            }
2343
        }
234480×
        for node in placed
234580×
            .iter()
234680×
            .chain(multi.iter().filter(|n| kept.contains_key(*n)))
2347
        {
234816×
            for (k, _) in self.base.tree().live_placements(node) {
234915×
                if retired.contains(&k) || kept.get(node) == Some(&k) {
235014×
                    continue;
23511×
                }
23521×
                retired.insert(k);
23531×
                extra.push(TreeOp::RemoveNode {
23541×
                    node: *node,
23551×
                    placement: op_ref(k),
23561×
                });
2357
            }
2358
        }
235980×
        if !extra.is_empty() {
23602×
            self.resolves = true;
23612×
            self.tree_ops.extend(extra);
236278×
        }
236380×
    }
2364
2365123×
    fn remove_path(&mut self, path: &str, expected: &crate::state::FileState) {
2366123×
        let entry = &self.base_snapshot.tree.entries[path];
2367123×
        self.tree_ops.push(TreeOp::RemoveNode {
2368123×
            node: expected.node,
2369123×
            placement: op_ref(entry.placement),
2370123×
        });
2371123×
        if path.contains(".oxy-conflict-") || expected.is_conflicted() {
23727×
            self.resolves = true;
2373116×
        }
2374123×
        self.statuses.push(PathStatus {
2375123×
            path: path.to_string(),
2376123×
            status: ChangeStatus::Removed,
2377123×
        });
2378123×
    }
2379
238012617×
    fn update_path(
238112617×
        &mut self,
238212617×
        repo: &Repo,
238312617×
        path: &str,
238412617×
        e: &FsEntry,
238512617×
        expected: &crate::state::FileState,
238612617×
    ) -> Result<()> {
238712617×
        if expected.kind != e.kind {
23881×
            self.remove_path(path, expected);
23891×
            self.statuses.pop();
23901×
            self.add_path(repo, path, e)?;
23911×
            self.statuses.pop();
23921×
            self.statuses.push(PathStatus {
23931×
                path: path.to_string(),
23941×
                status: ChangeStatus::Modified,
23951×
            });
23961×
            return Ok(());
239712616×
        }
239812616×
        let entry = &self.base_snapshot.tree.entries[path];
239912616×
        let node = expected.node;
240012616×
        let mode_atom = entry.mode_atom.map(op_ref);
240112616×
        if e.unchanged {
2402
            // Known equal to the base's unconflicted rendering (spec
2403
            // §12.3); only the executable bit can differ.
24044243×
            if e.exec != expected.mode.exec {
24053×
                if let Some(old) = mode_atom {
24063×
                    self.tree_ops.push(TreeOp::SetMode {
24073×
                        node,
24083×
                        old,
24093×
                        mode: Mode {
24103×
                            exec: e.exec,
24113×
                            opaque: false,
24123×
                        },
24133×
                    });
24143×
                    self.statuses.push(PathStatus {
24153×
                        path: path.to_string(),
24163×
                        status: ChangeStatus::ModeChanged,
24173×
                    });
24183×
                }
24194240×
            }
24204243×
            return Ok(());
24218373×
        }
24228373×
        let mut status: Option<ChangeStatus> = None;
24238373×
        let wants_opaque = self.opaque_for(path, e);
24248373×
        let nocompress = self.attrs.lookup(path).nocompress;
24258373×
        let disk_text = self.stored_text(path, &e.content);
24268373×
        match &expected.content {
24270×
            FileContent::Dir => {}
2428
            FileContent::Text {
24298150×
                bytes,
24308150×
                materialized,
2431
            } => {
24328150×
                if materialized.is_conflicted() {
243333×
                    if bytes == &*disk_text {
24346×
                        return Ok(());
243527×
                    }
243627×
                    if has_conflict_markers(&e.content) {
24374×
                        self.statuses.push(PathStatus {
24384×
                            path: path.to_string(),
24394×
                            status: ChangeStatus::ConflictEdited,
24404×
                        });
24414×
                        return Ok(());
244223×
                    }
2443
                    // Resolution (spec §9.6): diff against the unconflicted lines
2444
                    // with each region as a gap, then retire every region atom.
2445
                    // Whatever the author kept from a region is re-inserted as
2446
                    // new atoms, which leaves the graph totally ordered.
244723×
                    let regions = self.base.conflict_regions(&node);
244823×
                    let mut edits = text_edits(node, &regions.plain, &disk_text);
244923×
                    if !regions.region_atoms.is_empty() {
245023×
                        edits.insert(
245123×
                            0,
245223×
                            Edit::Delete {
245323×
                                node,
245423×
                                atoms: ranges(&regions.region_atoms),
245523×
                            },
245623×
                        );
245723×
                    }
245823×
                    self.edits.extend(edits);
245923×
                    self.contributors.extend(regions.contributors);
246023×
                    self.resolves = true;
246123×
                    if e.exec != expected.mode.exec {
24620×
                        if let Some(old) = mode_atom {
24630×
                            self.tree_ops.push(TreeOp::SetMode {
24640×
                                node,
24650×
                                old,
24660×
                                mode: Mode {
24670×
                                    exec: e.exec,
24680×
                                    opaque: false,
24690×
                                },
24700×
                            });
24710×
                        }
247223×
                    }
247323×
                    self.statuses.push(PathStatus {
247423×
                        path: path.to_string(),
247523×
                        status: ChangeStatus::Resolved,
247623×
                    });
247723×
                    return Ok(());
24788117×
                }
24798117×
                if wants_opaque {
2480
                    // Text → opaque (spec §7.5), by content or by attribute.
24812×
                    if let Some(old) = mode_atom {
24822×
                        self.tree_ops.push(TreeOp::SetMode {
24832×
                            node,
24842×
                            old,
24852×
                            mode: Mode {
24862×
                                exec: e.exec,
24872×
                                opaque: true,
24882×
                            },
24892×
                        });
24902×
                    }
24912×
                    let live: Vec<_> = repo_live_keys(self.base, &node);
24922×
                    if !live.is_empty() {
24932×
                        self.edits.push(Edit::Delete {
24942×
                            node,
24952×
                            atoms: ranges(&live),
24962×
                        });
24972×
                    }
24982×
                    let blob = self.blob_of(repo, path, e, nocompress)?;
24992×
                    self.edits.push(Edit::Replace {
25002×
                        node,
25012×
                        old: None,
25022×
                        new: Some(blob),
25032×
                    });
25042×
                    status = Some(ChangeStatus::Modified);
25058115×
                } else if bytes != &*disk_text {
2506742×
                    let mut laps = crate::timing::Laps::start();
2507
                    // The base's rendering holds its live atoms in order,
2508
                    // one per line (it is not conflicted here).
2509742×
                    let edits = match self.diffs.remove(path) {
251080×
                        Some(edits) => edits,
2511
                        None => {
2512662×
                            let keys = materialized.live_atoms();
2513662×
                            let lines = crate::diff::split_lines(bytes);
2514662×
                            if keys.len() == lines.len() {
2515662×
                                crate::diff::text_edits_of(node, &keys, &lines, &disk_text)
2516
                            } else {
25170×
                                text_edits(node, &self.base.live_lines(&node), &disk_text)
2518
                            }
2519
                        }
2520
                    };
2521742×
                    laps.lap("build: text diff");
2522742×
                    if !edits.is_empty() {
2523742×
                        self.edits.extend(edits);
2524742×
                        status = Some(ChangeStatus::Modified);
2525742×
                    }
25267373×
                }
25278117×
                let switched_to_opaque = wants_opaque;
25288117×
                if !switched_to_opaque && e.exec != expected.mode.exec {
25294×
                    if let Some(old) = mode_atom {
25304×
                        self.tree_ops.push(TreeOp::SetMode {
25314×
                            node,
25324×
                            old,
25334×
                            mode: Mode {
25344×
                                exec: e.exec,
25354×
                                opaque: false,
25364×
                            },
25374×
                        });
25384×
                        status.get_or_insert(ChangeStatus::ModeChanged);
25394×
                    }
25408113×
                }
2541
            }
2542223×
            FileContent::Opaque { blobs } => {
2543223×
                let new_ref = e.blob.unwrap_or_else(|| Repo::blob_ref(&e.content));
2544223×
                if e.kind == NodeKind::File && wants_opaque {
2545191×
                    // Unchanged or replaced, the file stays opaque: remember its blob.
2546191×
                    self.blobs.insert(path.to_string(), new_ref);
2547191×
                }
2548223×
                if blobs.len() > 1 && self.resolve.contains(path) && e.kind == expected.kind {
2549
                    // Settle the replace conflict (spec §9.3): replace every
2550
                    // live candidate with the chosen blob, depending on each
2551
                    // change that made one live, so all are superseded.
25522×
                    let chosen = self.blob_of(repo, path, e, nocompress)?;
25534×
                    for b in blobs {
25544×
                        self.edits.push(Edit::Replace {
25554×
                            node,
25564×
                            old: Some(*b),
25574×
                            new: Some(chosen),
25584×
                        });
25594×
                    }
25602×
                    self.contributors
25612×
                        .extend(self.base.blob_contributors(&node, blobs));
25622×
                    self.resolves = true;
25632×
                    self.statuses.push(PathStatus {
25642×
                        path: path.to_string(),
25652×
                        status: ChangeStatus::Resolved,
25662×
                    });
25672×
                    return Ok(());
2568221×
                }
2569221×
                if blobs.len() > 1 {
25702×
                    if !blobs.contains(&new_ref) {
25710×
                        self.statuses.push(PathStatus {
25720×
                            path: path.to_string(),
25730×
                            status: ChangeStatus::ConflictEdited,
25740×
                        });
25752×
                    }
25762×
                    return Ok(());
2577219×
                }
2578219×
                let current = blobs.first().copied();
2579219×
                if current != Some(new_ref) {
258033×
                    if e.kind == NodeKind::File && !wants_opaque {
2581
                        // Opaque → text (spec §7.5).
25822×
                        if let Some(old) = mode_atom {
25832×
                            self.tree_ops.push(TreeOp::SetMode {
25842×
                                node,
25852×
                                old,
25862×
                                mode: Mode {
25872×
                                    exec: e.exec,
25882×
                                    opaque: false,
25892×
                                },
25902×
                            });
25912×
                        }
25922×
                        self.edits.push(Edit::Replace {
25932×
                            node,
25942×
                            old: current,
25952×
                            new: None,
25962×
                        });
25972×
                        if !e.content.is_empty() {
25982×
                            self.edits.push(Edit::Insert {
25992×
                                node,
26002×
                                after: crate::objects::AtomRef::Start,
26012×
                                before: crate::objects::AtomRef::End,
26022×
                                lines: crate::lines::Lines::split(&e.content),
26032×
                            });
26042×
                        }
2605
                    } else {
260631×
                        let blob = self.blob_of(repo, path, e, nocompress)?;
260731×
                        self.edits.push(Edit::Replace {
260831×
                            node,
260931×
                            old: current,
261031×
                            new: Some(blob),
261131×
                        });
2612
                        // New contents and a new executable bit at once: the
2613
                        // bit was dropped (VS Code's inno_updater.exe,
2614
                        // 2018-02-28, lost +x for 49 commits; oxygen#87).
261531×
                        if e.kind == NodeKind::File && e.exec != expected.mode.exec {
26162×
                            if let Some(old) = mode_atom {
26172×
                                self.tree_ops.push(TreeOp::SetMode {
26182×
                                    node,
26192×
                                    old,
26202×
                                    mode: Mode {
26212×
                                        exec: e.exec,
26222×
                                        opaque: true,
26232×
                                    },
26242×
                                });
26252×
                            }
262629×
                        }
2627
                    }
262833×
                    status = Some(ChangeStatus::Modified);
2629186×
                } else if e.kind == NodeKind::File && e.exec != expected.mode.exec {
26300×
                    if let Some(old) = mode_atom {
26310×
                        self.tree_ops.push(TreeOp::SetMode {
26320×
                            node,
26330×
                            old,
26340×
                            mode: Mode {
26350×
                                exec: e.exec,
26360×
                                opaque: true,
26370×
                            },
26380×
                        });
26390×
                        status = Some(ChangeStatus::ModeChanged);
26400×
                    }
2641186×
                }
2642
            }
2643
        }
26448336×
        if let Some(s) = status {
2645781×
            self.statuses.push(PathStatus {
2646781×
                path: path.to_string(),
2647781×
                status: s,
2648781×
            });
26497555×
        }
26508336×
        Ok(())
265112617×
    }
2652
}
2653
26542×
fn repo_live_keys(base: &State, node: &NodeId) -> Vec<crate::graph::AtomKey> {
26552×
    base.live_lines(node).into_iter().map(|(k, _)| k).collect()
26562×
}
2657
2658
/// The changes a change's scope references (spec §8.1): introducers of every
2659
/// atom, placement, and mode it touches, and of every node it operates on.
26601953×
pub fn referenced_changes(change: &Change, base: &State) -> BTreeSet<ChangeHash> {
26611953×
    let mut out = BTreeSet::new();
26621953×
    let opref = |r: &OpRef, out: &mut BTreeSet<ChangeHash>| {
2663189×
        if !r.change.is_zero() {
2664189×
            out.insert(r.change);
2665189×
        }
2666189×
    };
26671953×
    let mut nodes: Vec<NodeId> = Vec::new();
26686469×
    for op in &change.tree_ops {
26696469×
        match op {
26706280×
            TreeOp::AddNode { parent, .. } => nodes.push(*parent),
2671144×
            TreeOp::RemoveNode { node, placement } => {
2672144×
                nodes.push(*node);
2673144×
                opref(placement, &mut out);
2674144×
            }
2675
            TreeOp::Move {
267633×
                node, old, parent, ..
267733×
            } => {
267833×
                nodes.push(*node);
267933×
                nodes.push(*parent);
268033×
                opref(old, &mut out);
268133×
            }
268212×
            TreeOp::SetMode { node, old, .. } => {
268312×
                nodes.push(*node);
268412×
                opref(old, &mut out);
268512×
            }
2686
        }
2687
    }
26887941×
    for e in &change.edits {
26897941×
        nodes.push(e.node());
2690128×
        match e {
26917301×
            Edit::Insert { after, before, .. } => {
269214602×
                for r in [after, before] {
269314602×
                    if let crate::objects::AtomRef::Atom { change, .. } = r {
26942133×
                        if !change.is_zero() {
26952131×
                            out.insert(*change);
26962131×
                        }
269712469×
                    }
2698
                }
2699
            }
2700512×
            Edit::Delete { atoms, .. } => {
2701
                // Deleting an atom also depends on whoever inserted the live
2702
                // atoms right after it: the author saw those insertions, and
2703
                // without the dependency spec §9.1 would call the deletion
2704
                // concurrent with them (a delete/insert conflict).
2705512×
                let graph = base.file(&e.node());
27061065×
                for r in atoms {
27071065×
                    if !r.change.is_zero() {
27081064×
                        out.insert(r.change);
27091064×
                    }
27101065×
                    if let Some(g) = graph {
27111108×
                        for i in r.from..r.to {
27121108×
                            out.extend(
27131108×
                                g.live_successor_changes(&(r.change, i))
27141108×
                                    .into_iter()
27151108×
                                    .filter(|c| !c.is_zero()),
2716
                            );
2717
                        }
27180×
                    }
2719
                }
2720
            }
2721
            // Replacing a blob depends on the change that made it current,
2722
            // as deleting a line depends on the line's introducer.
2723
            Edit::Replace {
272438×
                node,
272538×
                old: Some(old),
2726
                ..
2727
            } => {
272838×
                out.extend(
272938×
                    base.live_replaces(node)
273038×
                        .into_iter()
273145×
                        .filter(|(c, b)| b == old && !c.is_zero())
273238×
                        .map(|(c, _)| c),
2733
                );
2734
            }
273590×
            Edit::Replace { .. } => {}
2736
        }
2737
    }
273814443×
    for n in nodes {
273914443×
        if let Some(h) = base.tree().introducer(&n) {
27402125×
            out.insert(h);
274112318×
        }
2742
    }
27431953×
    out
27441953×
}
2745
2746
/// Paths of the nodes a change adds on top of `base_snapshot`.
27471224×
pub fn added_node_paths(
27481224×
    change: &Change,
27491224×
    base_snapshot: &Snapshot,
27501224×
) -> HashMap<String, (NodeId, NodeKind)> {
27511224×
    let by_node = base_snapshot.tree.by_node();
27521224×
    let mut new_names: HashMap<NodeId, (NodeId, String, NodeKind)> = HashMap::new();
27531224×
    for op in &change.tree_ops {
2754
        if let TreeOp::AddNode {
275569×
            node,
275669×
            parent,
275769×
            name,
275869×
            kind,
2759
            ..
276092×
        } = op
276169×
        {
276269×
            new_names.insert(*node, (*parent, name.clone(), *kind));
276369×
        }
2764
    }
27651224×
    let mut out = HashMap::new();
27661224×
    for (node, (_, _, kind)) in &new_names {
276769×
        if let Some(path) = path_of_node(node, &by_node, &new_names) {
276869×
            out.insert(path, (*node, *kind));
276969×
        }
2770
    }
27711224×
    out
27721224×
}
2773
2774178×
fn path_of_node(
2775178×
    n: &NodeId,
2776178×
    by_node: &HashMap<NodeId, &crate::tree::TreeEntry>,
2777178×
    new_names: &HashMap<NodeId, (NodeId, String, NodeKind)>,
2778178×
) -> Option<String> {
2779178×
    if let Some(e) = by_node.get(n) {
278057×
        return Some(e.path.clone());
2781121×
    }
2782121×
    let mut parts = Vec::new();
2783121×
    let mut cur = *n;
2784
    loop {
2785241×
        if cur.is_root() {
2786107×
            break;
2787134×
        }
2788134×
        if let Some(e) = by_node.get(&cur) {
27890×
            if !e.path.is_empty() {
27900×
                parts.push(e.path.clone());
27910×
            }
27920×
            break;
2793134×
        }
2794134×
        let (parent, name, _) = new_names.get(&cur)?;
2795120×
        parts.push(name.clone());
2796120×
        cur = *parent;
2797
    }
2798107×
    parts.reverse();
2799107×
    Some(parts.join("/"))
2800178×
}
2801
2802
/// Render a change's operations with line content, using `base` for deleted lines.
280328×
pub fn render_change(change: &Change, base: &State, base_snapshot: &Snapshot) -> String {
280428×
    let by_node = base_snapshot.tree.by_node();
280528×
    let mut new_names: HashMap<NodeId, (NodeId, String, NodeKind)> = HashMap::new();
280628×
    for op in &change.tree_ops {
2807
        if let TreeOp::AddNode {
280815×
            node,
280915×
            parent,
281015×
            name,
281115×
            kind,
2812
            ..
281322×
        } = op
281415×
        {
281515×
            new_names.insert(*node, (*parent, name.clone(), *kind));
281615×
        }
2817
    }
281866×
    let path_of = |n: &NodeId| -> String {
281966×
        path_of_node(n, &by_node, &new_names).unwrap_or_else(|| format!("<node {}>", n.short(8)))
282066×
    };
2821
282228×
    let mut out = String::new();
282328×
    for op in &change.tree_ops {
282422×
        match op {
2825
            TreeOp::AddNode {
282615×
                node, kind, mode, ..
2827
            } => {
282815×
                out.push_str(&format!(
2829
                    "A {} ({:?}{}{})\n",
283015×
                    path_of(node),
2831
                    kind,
283215×
                    if mode.exec { ", exec" } else { "" },
283315×
                    if mode.opaque { ", opaque" } else { "" }
2834
                ));
2835
            }
28365×
            TreeOp::RemoveNode { node, .. } => out.push_str(&format!("D {}\n", path_of(node))),
2837
            TreeOp::Move {
28382×
                node, parent, name, ..
2839
            } => {
28402×
                let to = if parent.is_root() {
28410×
                    name.clone()
2842
                } else {
28432×
                    format!("{}/{name}", path_of(parent))
2844
                };
28452×
                out.push_str(&format!("R {} -> {to}\n", path_of(node)))
2846
            }
28470×
            TreeOp::SetMode { node, mode, .. } => {
28480×
                out.push_str(&format!(
28490×
                    "M {} mode: exec={} opaque={}\n",
28500×
                    path_of(node),
28510×
                    mode.exec,
28520×
                    mode.opaque
28530×
                ));
28540×
            }
2855
        }
2856
    }
2857
    // Every other file the change edits is modified: the summary names
2858
    // every path it touches, not only those with a tree operation.
285928×
    let with_op: HashSet<NodeId> = change.tree_ops.iter().map(|o| o.node()).collect();
286028×
    let mut listed: HashSet<NodeId> = HashSet::new();
286132×
    for e in &change.edits {
286232×
        let n = e.node();
286332×
        if !with_op.contains(&n) && listed.insert(n) {
286418×
            out.push_str(&format!("M {}\n", path_of(&n)));
286518×
        }
2866
    }
286728×
    let mut last_node: Option<NodeId> = None;
286832×
    for e in &change.edits {
286932×
        let n = e.node();
287032×
        if last_node != Some(n) {
287124×
            out.push_str(&format!("--- {}\n", path_of(&n)));
287224×
            last_node = Some(n);
287324×
        }
287432×
        match e {
287524×
            Edit::Insert { lines, .. } => {
287629×
                for l in lines.iter() {
287729×
                    out.push('+');
287829×
                    out.push_str(&String::from_utf8_lossy(l));
287929×
                    if !l.ends_with(b"\n") {
28800×
                        out.push('\n');
288129×
                    }
2882
                }
2883
            }
28847×
            Edit::Delete { atoms, .. } => {
28857×
                for r in atoms {
28867×
                    for i in r.from..r.to {
28877×
                        let content = base
28887×
                            .file(&n)
28897×
                            .and_then(|g| g.content(&(r.change, i)))
28907×
                            .unwrap_or(b"<unknown>\n");
28917×
                        out.push('-');
28927×
                        out.push_str(&String::from_utf8_lossy(content));
28937×
                        if !content.ends_with(b"\n") {
28940×
                            out.push('\n');
28957×
                        }
2896
                    }
2897
                }
2898
            }
28991×
            Edit::Replace { old, new, .. } => {
29001×
                out.push_str(&format!(
2901
                    "  opaque content {} -> {}\n",
29021×
                    old.map(|o| o.short(12)).unwrap_or_else(|| "none".into()),
29031×
                    new.map(|o| o.short(12)).unwrap_or_else(|| "none".into())
2904
                ));
2905
            }
2906
        }
2907
    }
290828×
    out
290928×
}
2910
2911
/// Pair removed files with added files of the same kind whose contents are
2912
/// at least `RENAME_THRESHOLD` percent alike, best matches first. Beyond
2913
/// `RENAME_LIMIT` candidate pairs only identical contents are paired.
2914
const RENAME_THRESHOLD: u32 = 50;
2915
const RENAME_LIMIT: usize = 10_000;
2916
2917
/// How a change is built beyond its entries: for a Git import, the seed
2918
/// its new nodes' identifiers derive from; and, when it is built from part
2919
/// of the tree, whether the new tree has anything under a directory.
2920
#[derive(Default)]
2921
struct Scope<'a> {
2922
    seed: Option<[u8; 32]>,
2923
    dir_needed: Option<&'a dyn Fn(&str) -> bool>,
2924
}
2925
29261847×
fn detect_renames(
29271847×
    base_snapshot: &Snapshot,
29281847×
    fs_entries: &BTreeMap<String, FsEntry>,
29291847×
    in_scope: impl Fn(&str) -> bool,
29301847×
) -> Vec<(String, String)> {
29311847×
    let removed: Vec<(&String, &crate::state::FileState)> = base_snapshot
29321847×
        .files
29331847×
        .iter()
293413137×
        .filter(|(p, f)| {
293513137×
            f.kind != NodeKind::Dir
293612723×
                && !fs_entries.contains_key(*p)
2937136×
                && in_scope(p)
2938126×
                && !f.is_conflicted()
293913137×
        })
29401847×
        .collect();
29411847×
    let added: Vec<(&String, &FsEntry)> = fs_entries
29421847×
        .iter()
294318524×
        .filter(|(p, e)| e.kind != NodeKind::Dir && !base_snapshot.files.contains_key(*p))
29441847×
        .collect();
29451847×
    if removed.is_empty() || added.is_empty() {
29461790×
        return vec![];
294757×
    }
294857×
    let exact_only = removed.len() * added.len() > RENAME_LIMIT;
294971×
    let old_content = |f: &crate::state::FileState| -> Option<Vec<u8>> {
295071×
        match &f.content {
295167×
            FileContent::Text { bytes, .. } => Some(bytes.clone()),
29524×
            _ => None,
2953
        }
295471×
    };
295557×
    let mut scored: Vec<(u32, usize, usize)> = Vec::new();
295671×
    for (ri, (_, f)) in removed.iter().enumerate() {
295771×
        let old = old_content(f);
295871×
        let old_blob = match &f.content {
29594×
            FileContent::Opaque { blobs } if blobs.len() == 1 => Some(blobs[0]),
296067×
            _ => None,
2961
        };
296290×
        for (ai, (_, e)) in added.iter().enumerate() {
296390×
            if e.kind != f.kind {
29640×
                continue;
296590×
            }
296690×
            let score = match (&old, old_blob) {
296780×
                (Some(o), _) => {
296880×
                    if exact_only {
29690×
                        if *o == *e.content {
29700×
                            100
2971
                        } else {
29720×
                            0
2973
                        }
2974
                    } else {
297580×
                        similarity(o, &e.content)
2976
                    }
2977
                }
297810×
                (None, Some(b)) if e.blob.unwrap_or_else(|| Repo::blob_ref(&e.content)) == b => 100,
29797×
                _ => 0,
2980
            };
298190×
            if score >= RENAME_THRESHOLD {
298236×
                scored.push((score, ri, ai));
298354×
            }
2984
        }
2985
    }
298657×
    scored.sort_by(|a, b| {
29879×
        b.0.cmp(&a.0)
29889×
            .then(removed[a.1].0.cmp(removed[b.1].0))
29899×
            .then(added[a.2].0.cmp(added[b.2].0))
29909×
    });
299157×
    let mut used_r = vec![false; removed.len()];
299257×
    let mut used_a = vec![false; added.len()];
299357×
    let mut out = Vec::new();
299457×
    for (_, ri, ai) in scored {
299536×
        if used_r[ri] || used_a[ai] {
29966×
            continue;
299730×
        }
299830×
        used_r[ri] = true;
299930×
        used_a[ai] = true;
300030×
        out.push((removed[ri].0.clone(), added[ai].0.clone()));
3001
    }
300257×
    out
30031847×
}
3004
3005
/// Percentage of the larger file's bytes found in lines the two share
3006
/// (multiset intersection of lines), like Git's similarity index.
300784×
pub fn similarity(a: &[u8], b: &[u8]) -> u32 {
300884×
    if a == b {
300919×
        return 100;
301065×
    }
301165×
    if a.is_empty() || b.is_empty() {
30127×
        return 0;
301358×
    }
301458×
    let mut counts: HashMap<&[u8], usize> = HashMap::new();
3015112×
    for l in split_lines(a) {
3016112×
        *counts.entry(l).or_default() += 1;
3017112×
    }
301858×
    let mut shared = 0usize;
3019110×
    for l in split_lines(b) {
3020110×
        if let Some(n) = counts.get_mut(l) {
302143×
            if *n > 0 {
302243×
                *n -= 1;
302343×
                shared += l.len();
302443×
            }
302567×
        }
3026
    }
302758×
    (shared * 100 / a.len().max(b.len())) as u32
302884×
}
3029
3030
#[cfg(test)]
3031
mod join_tests {
3032
    use super::*;
3033
3034
    #[test]
30351×
    fn missing_from_finds_what_the_other_lacks() {
30361×
        let a: BTreeMap<String, u8> = [("a", 1), ("b", 2), ("c/d", 3), ("e", 4)]
30371×
            .into_iter()
30384×
            .map(|(k, v)| (k.to_string(), v))
30391×
            .collect();
30401×
        let b: BTreeMap<String, ()> = [("0", ()), ("b", ()), ("c", ()), ("e", ())]
30411×
            .into_iter()
30424×
            .map(|(k, v)| (k.to_string(), v))
30431×
            .collect();
30441×
        let got: Vec<&str> = missing_from(&a, &b)
30451×
            .iter()
30462×
            .map(|(k, _)| k.as_str())
30471×
            .collect();
30481×
        assert_eq!(got, vec!["a", "c/d"]);
30491×
    }
3050
3051
    #[test]
30521×
    fn join_pairs_every_key_in_order() {
30531×
        let a: BTreeMap<String, u8> = [("a", 1), ("b/c", 2), ("d", 3)]
30541×
            .into_iter()
30553×
            .map(|(k, v)| (k.to_string(), v))
30561×
            .collect();
30571×
        let b: BTreeMap<String, char> = [("b", 'x'), ("b/c", 'y'), ("e", 'z')]
30581×
            .into_iter()
30593×
            .map(|(k, v)| (k.to_string(), v))
30601×
            .collect();
30611×
        let got: Vec<(String, Option<u8>, Option<char>)> = join(&a, &b)
30625×
            .map(|(k, x, y)| (k.clone(), x.copied(), y.copied()))
30631×
            .collect();
30641×
        let want = vec![
30651×
            ("a".to_string(), Some(1), None),
30661×
            ("b".to_string(), None, Some('x')),
30671×
            ("b/c".to_string(), Some(2), Some('y')),
30681×
            ("d".to_string(), Some(3), None),
30691×
            ("e".to_string(), None, Some('z')),
3070
        ];
30711×
        assert_eq!(got, want);
30721×
    }
3073
}