OXYGENHUB

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

2141 of 2365 lines run, 269 of 367 functions · run #253 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
8122415×
pub fn is_binary(content: &[u8]) -> bool {
8222415×
    content[..content.len().min(BINARY_SNIFF)].contains(&0)
8322415×
}
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.
1051200×
    fn platform_normalize(&self, entries: &mut BTreeMap<String, FsEntry>, base: &Snapshot) {
1061200×
        let p = self.platform;
1071200×
        if p.exec_bits && p.symlinks {
1081198×
            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
        }
1221200×
    }
123
124
    /// Like `build_against`, for files given in memory (imports).
125935×
    pub(crate) fn build_from_entries(
126935×
        &self,
127935×
        base: &State,
128935×
        base_snapshot: &Snapshot,
129935×
        reuse: HashMap<String, (NodeId, NodeKind)>,
130935×
        fs_entries: &BTreeMap<String, FsEntry>,
131935×
    ) -> Result<BuiltChange> {
132935×
        self.build_from_entries_resolving(base, base_snapshot, reuse, fs_entries, &HashSet::new())
133935×
    }
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.
140949×
    pub(crate) fn build_from_entries_resolving(
141949×
        &self,
142949×
        base: &State,
143949×
        base_snapshot: &Snapshot,
144949×
        reuse: HashMap<String, (NodeId, NodeKind)>,
145949×
        fs_entries: &BTreeMap<String, FsEntry>,
146949×
        resolve: &HashSet<String>,
147949×
    ) -> Result<BuiltChange> {
148949×
        self.build_from_entries_with(
149949×
            base,
150949×
            base_snapshot,
151949×
            reuse,
152949×
            fs_entries,
153949×
            resolve,
154949×
            Scope::default(),
155
        )
156949×
    }
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.
192781×
    fn build_changed_only(
193781×
        &self,
194781×
        base: &State,
195781×
        base_snapshot: &Snapshot,
196781×
        reuse: HashMap<String, (NodeId, NodeKind)>,
197781×
        fs_entries: &BTreeMap<String, FsEntry>,
198781×
    ) -> Result<BuiltChange> {
199781×
        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.
202781×
        let changed: BTreeMap<String, FsEntry> = join(fs_entries, &base_snapshot.files)
20310895×
            .filter_map(|(p, e, f)| {
20410895×
                let e = e?;
20510771×
                (!e.unchanged || f.is_none_or(|f| f.kind != e.kind || f.mode.exec != e.exec))
20610771×
                    .then(|| (p.clone(), e.clone()))
20710895×
            })
208781×
            .collect();
209781×
        let mut files: BTreeMap<String, crate::state::FileState> = BTreeMap::new();
2106542×
        for p in changed.keys() {
2116542×
            if let Some(f) = base_snapshot.files.get(p) {
2123604×
                files.insert(p.clone(), f.clone());
2133604×
            }
214
        }
215
        // Paths the base has and the disk does not.
216781×
        let gone = join(&base_snapshot.files, fs_entries)
21710895×
            .filter_map(|(p, f, e)| (e.is_none()).then_some((p, f?)));
218781×
        for (p, f) in gone {
219124×
            if f.kind == NodeKind::Dir {
22096×
                continue;
22128×
            }
22228×
            files.insert(p.clone(), f.clone());
22328×
            let mut end = p.len();
22433×
            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
        }
235781×
        let part = Snapshot {
236781×
            tree: base_snapshot.tree.clone(),
237781×
            files,
238781×
            unrendered: BTreeSet::new(),
239781×
        };
240781×
        drop(pick);
241781×
        let _build = crate::timing::phase("snapshot:   of which building the change");
242
        // Whether anything on disk is under `dir`.
243781×
        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×
        };
250781×
        self.build_from_entries_with(
251781×
            base,
252781×
            &part,
253781×
            reuse,
254781×
            &changed,
255781×
            &HashSet::new(),
256781×
            Scope {
257781×
                seed: None,
258781×
                dir_needed: Some(&dir_needed),
259781×
            },
260
        )
261781×
    }
262
2631810×
    fn build_from_entries_with(
2641810×
        &self,
2651810×
        base: &State,
2661810×
        base_snapshot: &Snapshot,
2671810×
        reuse: HashMap<String, (NodeId, NodeKind)>,
2681810×
        fs_entries: &BTreeMap<String, FsEntry>,
2691810×
        resolve: &HashSet<String>,
2701810×
        scope: Scope,
2711810×
    ) -> Result<BuiltChange> {
2721810×
        let Scope { seed, dir_needed } = scope;
2731810×
        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.
2761810×
        let attrs = crate::attributes::Attributes::from_files(
2771810×
            fs_entries
2781810×
                .iter()
27918487×
                .filter(|(p, _)| p.as_str() == ".oxyattributes" || p.ends_with("/.oxyattributes"))
2801810×
                .map(|(p, e)| (p.as_str(), e.content.as_slice())),
281
        );
2821810×
        let mut b = ChangeBuilder::new(base, base_snapshot, reuse).with_attributes(attrs);
2831810×
        b.resolve = resolve.clone();
2841810×
        b.node_seed = seed;
2851810×
        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.
2891810×
        let renames = detect_renames(base_snapshot, fs_entries, |p| self.in_scope(p));
2901810×
        let renamed_from: HashMap<&str, &str> = renames
2911810×
            .iter()
2921810×
            .map(|(old, new)| (new.as_str(), old.as_str()))
2931810×
            .collect();
2941810×
        let renamed_to: HashMap<&str, &str> = renames
2951810×
            .iter()
2961810×
            .map(|(old, new)| (old.as_str(), new.as_str()))
2971810×
            .collect();
2981810×
        laps.lap("build: renames");
2991810×
        b.diff_in_parallel(fs_entries);
3001810×
        laps.lap("build: diffs");
30118487×
        for (path, fs_entry) in fs_entries {
30218487×
            match base_snapshot.files.get(path) {
3035907×
                None => match renamed_from.get(path.as_str()) {
30426×
                    Some(old) => {
30526×
                        b.move_path(self, old, path, fs_entry, &base_snapshot.files[*old])?
306
                    }
3075881×
                    None => b.add_path(self, path, fs_entry)?,
308
                },
30912580×
                Some(expected) => b.update_path(self, path, fs_entry, expected)?,
310
            }
311
        }
3121810×
        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.
3151810×
        let mut needed_dirs: HashSet<&str> = HashSet::new();
31618500×
        fn parents_of<'a>(p: &'a str, set: &mut HashSet<&'a str>) {
31718500×
            let mut end = p.len();
31819159×
            while let Some(i) = p[..end].rfind('/') {
31915442×
                if !set.insert(&p[..i]) {
32014783×
                    break;
321659×
                }
322659×
                end = i;
323
            }
32418500×
        }
32518487×
        for p in fs_entries.keys() {
32618487×
            parents_of(p, &mut needed_dirs);
32718487×
        }
32813151×
        for p in base_snapshot.files.keys() {
32913151×
            if !self.in_scope(p) {
33013×
                parents_of(p, &mut needed_dirs);
33113138×
            }
332
        }
33313151×
        for (path, expected) in &base_snapshot.files {
33413151×
            if fs_entries.contains_key(path)
335571×
                || !self.in_scope(path)
336558×
                || renamed_to.contains_key(path.as_str())
337
            {
33812619×
                continue;
339532×
            }
340532×
            let still_needed = expected.kind == NodeKind::Dir
341430×
                && match dir_needed {
34215×
                    Some(f) => f(path),
343415×
                    None => needed_dirs.contains(path.as_str()),
344
                };
345532×
            if !still_needed {
346128×
                b.remove_path(path, expected);
347404×
            }
348
        }
3491810×
        laps.lap("build: removals");
3501810×
        if seed.is_some() {
35180×
            b.retire_stray_placements();
3521730×
        }
3531810×
        laps.lap("build: stray placements");
3541810×
        let mut statuses = b.statuses;
3555619×
        statuses.sort_by(|a, b| a.path.cmp(&b.path));
3561810×
        Ok(BuiltChange {
3571810×
            tree_ops: b.tree_ops,
3581810×
            edits: b.edits,
3591810×
            contributors: b.contributors.into_iter().collect(),
3601810×
            resolves: b.resolves,
3611810×
            statuses,
3621810×
            blobs: b.blobs,
3631810×
        })
3641810×
    }
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.
369642×
    pub(crate) fn store_signed(&self, change: &Change) -> Result<ChangeHash> {
370642×
        let ours = change.author == self.author();
371642×
        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");
373641×
        }
374641×
        let storing = crate::timing::phase("store: the change");
375641×
        let hash = self.store.put_change(change)?;
376641×
        drop(storing);
377641×
        if self.config.sign_changes && ours {
37840×
            let _t = crate::timing::phase("store: sign it");
37940×
            self.sign_change(&hash)?;
380601×
        }
381641×
        Ok(hash)
382642×
    }
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.
386417×
    pub fn snapshot(&self, command: &str) -> Result<SnapshotResult> {
387417×
        self.snapshot_as(command, false, false)
388417×
    }
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.
398379×
    pub fn snapshot_status(&self, command: &str) -> Result<SnapshotResult> {
399379×
        self.snapshot_as(command, true, false)
400379×
    }
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.
4091201×
    fn snapshot_as(
4101201×
        &self,
4111201×
        command: &str,
4121201×
        partial: bool,
4131201×
        for_commit: bool,
4141201×
    ) -> Result<SnapshotResult> {
4151201×
        let _lock = self.lock_snapshot()?;
4161201×
        let batch = self.store.begin_batch()?;
4171201×
        let result = self.snapshot_locked(command, partial, for_commit);
4181201×
        batch.finish()?;
4191201×
        result
4201201×
    }
421
4221201×
    fn snapshot_locked(
4231201×
        &self,
4241201×
        command: &str,
4251201×
        partial: bool,
4261201×
        for_commit: bool,
4271201×
    ) -> Result<SnapshotResult> {
4281201×
        let _all = crate::timing::phase("snapshot");
4291201×
        let (op_ref, op) = self.head_op()?;
4301201×
        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.
4331199×
        let mut base = {
4341199×
            let _t = crate::timing::phase("snapshot: load base history");
4351199×
            self.load_state_indexed(&old_wc.deps)?
436
        };
4371199×
        let view = {
4381199×
            let _t = crate::timing::phase("snapshot: tree view");
4391199×
            base.tree().view()
440
        };
4411199×
        let manifest = {
4421199×
            let _t = crate::timing::phase("snapshot: read manifest");
4431199×
            self.read_manifest()?.map(|(_, _, m)| m)
444
        };
4451199×
        let tracked: BTreeMap<String, (NodeKind, Option<ObjectRef>)> = {
4461199×
            let _t = crate::timing::phase("snapshot: tracked paths");
447
            // In the view's path order, so the map is built without searching.
4481199×
            view.entries
4491199×
                .iter()
4509411×
                .filter(|(_, e)| e.kind != NodeKind::Dir)
4519013×
                .map(|(p, e)| {
4529013×
                    let blob = if e.kind != NodeKind::File || e.mode.opaque {
453149×
                        base.live_blobs(&e.node).first().copied()
454
                    } else {
4558864×
                        None
456
                    };
4579013×
                    (p.clone(), (e.kind, blob))
4589013×
                })
4591199×
                .collect()
460
        };
461
        // A text file's graph key, worked out when the walk asks for it.
46211945×
        let key_of = |p: &str| -> Option<[u8; 32]> {
46311945×
            let e = view.entries.get(p)?;
4648909×
            if e.kind != NodeKind::File || e.mode.opaque {
465122×
                return None;
4668787×
            }
4678787×
            base.graph_key(&e.node)
46811945×
        };
4691198×
        let mut fs_entries = {
4701199×
            let _t = crate::timing::phase("snapshot: read working copy");
4711199×
            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.
4751198×
        let keys: HashMap<String, [u8; 32]> = fs_entries
4761198×
            .iter()
47711974×
            .filter(|(_, e)| !e.unchanged && e.kind == NodeKind::File)
4787704×
            .filter_map(|(p, _)| Some((p.clone(), key_of(p)?)))
4791198×
            .collect();
4801198×
        let base_snapshot = {
4811198×
            let _t = crate::timing::phase("snapshot: load and render base");
4821198×
            if partial {
483784×
                let sets = crate::timing::phase("snapshot:   of which choosing graphs");
484
                // Every file but those on disk known unchanged.
485784×
                let need: Vec<(&str, NodeId)> = join(&view.entries, &fs_entries)
48610910×
                    .filter_map(|(p, v, f)| {
48710910×
                        let v = v?;
4887971×
                        (v.kind == NodeKind::File && !f.is_some_and(|f| f.unchanged))
4897971×
                            .then_some((p.as_str(), v.node))
49010910×
                    })
491784×
                    .collect();
492784×
                let render: std::collections::HashSet<&str> =
493784×
                    need.iter().map(|(p, _)| *p).collect();
494784×
                let need: Vec<NodeId> = need.iter().map(|(_, n)| *n).collect();
495784×
                drop(sets);
496
                {
497784×
                    let _t = crate::timing::phase("snapshot:   of which building graphs");
498784×
                    self.load_graphs_of(&mut base, &need)?;
499
                }
500784×
                let _t = crate::timing::phase("snapshot:   of which rendering");
501784×
                base.materialize_only(&render)
502
            } else {
503414×
                self.load_all_graphs(&mut base)?;
504414×
                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).
5101198×
        let reuse = added_node_paths(&old_wc, &base_snapshot);
5111198×
        self.platform_normalize(&mut fs_entries, &base_snapshot);
5121198×
        let built = {
5131198×
            let _t = crate::timing::phase("snapshot: diff against base");
5141198×
            if partial && self.config.sparse_paths.is_empty() {
515
                #[cfg(test)]
516512×
                let full =
517512×
                    self.build_from_entries(&base, &base_snapshot, reuse.clone(), &fs_entries)?;
518781×
                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.
5231024×
                    let norm = |b: &BuiltChange| {
5241024×
                        let text = format!("{:?} {:?} {:?}", b.tree_ops, b.edits, b.statuses);
5251024×
                        let mut seen: Vec<String> = Vec::new();
5261024×
                        let mut out = String::new();
5271024×
                        let mut rest = text.as_str();
52819312×
                        while let Some(i) = rest.find("NodeId(") {
52918288×
                            out.push_str(&rest[..i]);
53018288×
                            let end = i + rest[i..].find(')').unwrap() + 1;
53118288×
                            let id = rest[i..end].to_string();
5329045494×
                            let n = seen.iter().position(|x| *x == id).unwrap_or_else(|| {
5336776×
                                seen.push(id);
5346776×
                                seen.len() - 1
5356776×
                            });
53618288×
                            out.push_str(&format!("N{n}"));
53718288×
                            rest = &rest[end..];
538
                        }
5391024×
                        out.push_str(rest);
5401024×
                        out
5411024×
                    };
542512×
                    assert_eq!(
543512×
                        norm(&built),
544512×
                        norm(&full),
545
                        "a changed-only build is the full one"
546
                    );
547
                }
548781×
                built
549
            } else {
550417×
                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
        {
5563646×
            let changed: HashSet<&str> = built.statuses.iter().map(|s| s.path.as_str()).collect();
55711974×
            for (p, e) in fs_entries.iter_mut() {
55811974×
                if e.unchanged || e.kind != NodeKind::File || changed.contains(p.as_str()) {
5597813×
                    continue;
5604161×
                }
5614161×
                e.graph_key = match base_snapshot.files.get(p).map(|f| &f.content) {
562
                    Some(FileContent::Text {
5634050×
                        bytes,
5644050×
                        materialized,
5654050×
                    }) if !materialized.is_conflicted() && *bytes == *e.content => {
5664044×
                        keys.get(p).copied()
567
                    }
568117×
                    _ => None,
569
                };
570
            }
571
        }
572
5731198×
        let mut wc = Change {
5741198×
            version: crate::objects::CHANGE_VERSION,
5751198×
            change_id: old_wc.change_id,
5761198×
            deps: vec![],
5771198×
            author: self.author(),
5781198×
            hlc: old_wc.hlc,
5791198×
            message: old_wc.message.clone(),
5801198×
            tree_ops: built.tree_ops,
5811198×
            edits: built.edits,
5821198×
            kind: ChangeKind::WorkingCopy,
5831198×
        };
5841198×
        let base_heads = base.maximal(&old_wc.deps);
5851198×
        let mut deps: BTreeSet<ChangeHash> = base_heads.into_iter().collect();
5861198×
        deps.extend(referenced_changes(&wc, &base));
5871198×
        deps.extend(built.contributors.iter().copied());
5881198×
        wc.deps = deps.into_iter().collect();
5891198×
        wc.normalize();
5901198×
        let resolves = built.resolves;
5911198×
        let contributors = built.contributors;
5921198×
        let statuses = built.statuses;
593
        // Empty snapshot: hash the candidate before storing; only record an op on change.
5941198×
        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.
6011198×
        let (new_hash, changed, encoded) = if for_commit {
602405×
            (old_hash, true, Vec::new())
603
        } else {
604793×
            let encoded = wc.encode_streaming(|batch| self.store.put_texts(&batch))?;
605793×
            let new_hash = crate::hash::hash_object(crate::hash::ObjectType::Change, &encoded);
606793×
            (new_hash, new_hash != old_hash, encoded)
607
        };
6081198×
        if changed && !for_commit {
609276×
            self.store.put(crate::hash::ObjectType::Change, &encoded)?;
610276×
            let mut view = op.view.clone();
611276×
            view.workspaces.insert(self.workspace, new_hash);
612276×
            self.record_op(&[op_ref], &format!("{command}{SNAPSHOT_SUFFIX}"), view)?;
613922×
        }
6141198×
        drop(record);
615
        // The prompt compares against this without recording anything.
6161198×
        let _t = crate::timing::phase("snapshot: write manifest");
6171198×
        let conflicted = base_snapshot.is_conflicted();
6181198×
        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.
6231198×
        let worth = match self.read_manifest()? {
624405×
            _ if for_commit => true,
625291×
            None => true,
626502×
            Some((c, u, m)) => {
627502×
                c != conflicted
628502×
                    || u != uncommitted
629277×
                    || m.entries.len() != fs_entries.len()
630347×
                    || fs_entries.iter().any(|(p, e)| {
631347×
                        !e.unchanged && (e.graph_key.is_some() || !m.entries.contains_key(p))
632347×
                    })
63341×
                    || built
63441×
                        .blobs
63541×
                        .iter()
63641×
                        .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.
64044×
                    || (uncommitted && statuses.iter().any(|st| {
64144×
                        let Some(e) = fs_entries.get(&st.path) else {
6423×
                            return m.entries.contains_key(&st.path);
643
                        };
64441×
                        let Some(me) = m.entries.get(&st.path) else {
6450×
                            return true;
646
                        };
64741×
                        let hash = e
64841×
                            .content_hash
64941×
                            .unwrap_or_else(|| *blake3::hash(&e.content).as_bytes());
65041×
                        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.
65741×
                        me.hash != hash || me.exec != e.exec || stat != Some((me.size, me.mtime_ns))
65844×
                    }))
659
            }
660
        };
6611198×
        let attributes = crate::attributes::Attributes::from_files(
6621198×
            fs_entries
6631198×
                .iter()
66411974×
                .filter(|(p, _)| is_attributes(p))
6651198×
                .map(|(p, e)| (p.as_str(), e.content.as_slice())),
666
        );
6671198×
        let mut manifest = None;
6681198×
        if for_commit {
669405×
            manifest = Some(PendingManifest {
670405×
                entries: fs_entries,
671405×
                blobs: built.blobs.clone(),
672405×
                dirs: self.walked_dirs.take(),
673405×
                written: super::prompt::now_ns(),
674405×
            });
675405×
        } else {
676793×
            if worth {
677755×
                self.write_manifest_entries(conflicted, uncommitted, &fs_entries, &built.blobs)?;
67838×
            }
679793×
            self.write_status_cache((uncommitted && !conflicted).then_some(&new_hash), &statuses);
680
        }
6811198×
        Ok(SnapshotResult {
6821198×
            wc_hash: new_hash,
6831198×
            wc,
6841198×
            base,
6851198×
            base_snapshot,
6861198×
            statuses,
6871198×
            changed,
6881198×
            resolves,
6891198×
            contributors,
6901198×
            attributes,
6911198×
            untracked_nested: self.untracked_nested.borrow().clone(),
6921198×
            manifest,
6931198×
        })
6941201×
    }
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).
800587×
    pub fn commit(&self, message: &str, extra_deps: &[ChangeHash]) -> Result<ChangeHash> {
801587×
        self.commit_selection(message, extra_deps, &Selection::All)
802587×
    }
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.
822605×
    fn committed_graph_keys(
823605×
        &self,
824605×
        st: &State,
825605×
        paths: &[String],
826605×
        attrs: &crate::attributes::Attributes,
827605×
    ) -> HashMap<String, [u8; 32]> {
828605×
        let _t = crate::timing::phase("commit: graph keys");
829605×
        let view = st.tree().view();
830605×
        paths
831605×
            .iter()
8323433×
            .filter_map(|p| {
8333433×
                let e = view.entries.get(p)?;
8343379×
                (e.kind == NodeKind::File && !e.mode.opaque && attrs.lookup(p).eol.is_none())
8353379×
                    .then_some(())?;
8363332×
                Some((p.clone(), st.graph_key(&e.node)?))
8373433×
            })
838605×
            .collect()
839605×
    }
840
841615×
    pub fn commit_selection(
842615×
        &self,
843615×
        message: &str,
844615×
        extra_deps: &[ChangeHash],
845615×
        selection: &Selection,
846615×
    ) -> Result<ChangeHash> {
847
        // The commit's objects are written together, made durable at once
848
        // before the operation that names them (spec §13.6).
849615×
        let batch = self.store.begin_batch()?;
850615×
        let out = self.commit_selection_batched(message, extra_deps, selection);
851615×
        batch.finish()?;
852615×
        out
853615×
    }
854
855
    /// Write the manifest a commit's snapshot left to the commit, with the
856
    /// graph keys `keys` sets.
857397×
    fn write_pending_manifest(
858397×
        &self,
859397×
        mut m: PendingManifest,
860397×
        conflicted: bool,
861397×
        keys: HashMap<String, [u8; 32]>,
862397×
    ) -> Result<()> {
8632793×
        for (path, k) in keys {
8642793×
            if let Some(e) = m.entries.get_mut(&path) {
8652793×
                e.graph_key = Some(k);
8662793×
            }
867
        }
868397×
        self.write_manifest_entries_as_of(
869397×
            conflicted,
870
            false,
871397×
            &m.entries,
872397×
            &m.blobs,
873397×
            m.written,
874397×
            m.dirs.unwrap_or_default(),
875
        )
876397×
    }
877
878615×
    fn commit_selection_batched(
879615×
        &self,
880615×
        message: &str,
881615×
        extra_deps: &[ChangeHash],
882615×
        selection: &Selection,
883615×
    ) -> Result<ChangeHash> {
884615×
        let _wc = self.lock_working_copy()?;
885615×
        let mut snap = match self.snapshot_from_cache()? {
886210×
            Some(snap) => snap,
887405×
            None => self.snapshot_as("oxy commit", true, true)?,
888
        };
889615×
        let pending = snap.manifest.take();
890615×
        if snap.wc.tree_ops.is_empty() && snap.wc.edits.is_empty() {
8913×
            if let Some(m) = pending {
8923×
                let conflicted = snap.base_snapshot.is_conflicted();
8933×
                self.write_pending_manifest(m, conflicted, HashMap::new())?;
8940×
            }
8953×
            return fail("nothing to commit: the working copy matches its base");
896612×
        }
897612×
        if let Some(s) = snap
898612×
            .statuses
899612×
            .iter()
9003448×
            .find(|s| s.status == ChangeStatus::ConflictEdited)
901
        {
9020×
            return fail(format!("{} still contains conflict markers", s.path));
903612×
        }
904612×
        if message.trim().is_empty() {
9050×
            return fail("a commit message is required");
906612×
        }
907
        // What the whole working copy references, before a whole commit
908
        // takes its operations over (they are moved, not copied: for a
909
        // large tree they are most of the memory).
910612×
        let wc_refs = referenced_changes(&snap.wc, &snap.base);
9113448×
        let changed_paths: Vec<String> = snap.statuses.iter().map(|s| s.path.clone()).collect();
912612×
        let (tree_ops, edits, partial) = match selection {
913606×
            Selection::All => (
914606×
                std::mem::take(&mut snap.wc.tree_ops),
915606×
                std::mem::take(&mut snap.wc.edits),
916606×
                false,
917606×
            ),
9182×
            Selection::Paths(paths) => {
9192×
                let (o, e) = select_paths(&snap.wc, &snap.base_snapshot, paths);
9202×
                let partial = o.len() != snap.wc.tree_ops.len() || e.len() != snap.wc.edits.len();
9212×
                (o, e, partial)
922
            }
9234×
            Selection::Hunks(indices) => {
9244×
                let (o, e) = select_hunks(&snap.wc, indices);
9254×
                let partial = o.len() != snap.wc.tree_ops.len() || e.len() != snap.wc.edits.len();
9264×
                (o, e, partial)
927
            }
928
        };
929612×
        if tree_ops.is_empty() && edits.is_empty() {
9300×
            return fail("nothing selected to commit");
931612×
        }
932612×
        if partial && snap.resolves {
9330×
            return fail("a conflict resolution must be committed whole");
934612×
        }
935
        // pre-commit hook: may veto.
936612×
        self.run_hook(
937612×
            "pre-commit",
938612×
            &format!(
939
                "{{\"event\":\"pre-commit\",\"message\":{},\"paths\":{}}}",
940612×
                json_str(message),
9413448×
                json_array(snap.statuses.iter().map(|s| format!(
942
                    "{{\"path\":{},\"status\":{}}}",
9433448×
                    json_str(&s.path),
9443448×
                    json_str(&format!("{:?}", s.status))
945
                )))
946
            ),
9471×
        )?;
948611×
        let (op_ref, op) = self.head_op()?;
949611×
        let mut deps: BTreeSet<ChangeHash> = wc_refs;
950
        // semantic-deps hook: may add explicit dependencies (spec §8.1).
951611×
        if self.config.semantic_deps {
9521×
            let touched: Vec<String> = snap.statuses.iter().map(|s| s.path.clone()).collect();
9531×
            let by_node = snap.base_snapshot.tree.by_node();
9541×
            let mut candidates: Vec<(ChangeId, ChangeHash, Vec<String>)> = Vec::new();
9551×
            let mut seen: BTreeSet<ChangeHash> = BTreeSet::new();
9562×
            for h in deps.iter().chain(snap.base.maximal(&snap.wc.deps).iter()) {
9572×
                if !seen.insert(*h) {
9580×
                    continue;
9592×
                }
9602×
                let c = self.store.get_change(h)?;
9612×
                let mut paths: BTreeSet<String> = BTreeSet::new();
9626×
                for n in c
9632×
                    .tree_ops
9642×
                    .iter()
9653×
                    .map(|o| o.node())
9663×
                    .chain(c.edits.iter().map(|e| e.node()))
967
                {
9686×
                    if let Some(e) = by_node.get(&n) {
9696×
                        paths.insert(e.path.clone());
9706×
                    }
971
                }
9722×
                candidates.push((c.change_id, *h, paths.into_iter().collect()));
973
            }
9741×
            for d in self.semantic_deps(&snap.wc.change_id, &touched, &candidates)? {
9751×
                if snap.base.contains(&d) {
9761×
                    deps.insert(d);
9771×
                }
978
            }
979610×
        }
980
        // A resolution depends on every change that contributed to the
981
        // conflict (spec §8.1). Tree and opaque conflicts are resolved through
982
        // ordinary operations whose references already cover the contributors.
983611×
        deps.extend(snap.contributors.iter().copied());
984611×
        for d in extra_deps {
9852×
            if !snap.base.contains(d) {
9860×
                return fail(format!(
987
                    "--depends-on {d}: not in the working copy's base state"
988
                ));
9892×
            }
9902×
            deps.insert(*d);
991
        }
992611×
        let mut change = Change {
993
            version: crate::objects::CHANGE_VERSION,
994611×
            change_id: if partial {
9955×
                ChangeId::random()
996
            } else {
997606×
                snap.wc.change_id
998
            },
999611×
            deps: vec![],
1000611×
            author: self.author(),
1001611×
            hlc: Hlc::now(),
1002611×
            message: message.trim_end().to_string(),
1003611×
            tree_ops,
1004611×
            edits,
1005611×
            kind: if snap.resolves {
10067×
                ChangeKind::Resolution
1007
            } else {
1008604×
                ChangeKind::Normal
1009
            },
1010
        };
1011611×
        if partial {
1012
            // Dependencies come from what the selected part references, not
1013
            // from the whole working copy.
10145×
            deps = referenced_changes(&change, &snap.base);
10155×
            for d in extra_deps {
10160×
                deps.insert(*d);
10170×
            }
1018606×
        }
1019611×
        change.deps = deps.into_iter().collect();
1020611×
        change.normalize();
1021611×
        let signing = crate::timing::phase("commit: sign and store");
1022611×
        let hash = self.store_signed(&change)?;
1023610×
        drop(signing);
1024610×
        let extending = crate::timing::phase("commit: extend the state");
1025
1026
        // New bookmark heads: maximal elements of old heads plus the new change.
1027
        // The working copy continues on its own base plus the new change, which
1028
        // is exactly what the files on disk contain; the bookmark may hold
1029
        // other heads (and conflicts) the working copy has not checked out.
1030610×
        let old_heads = self.heads_of(&op.view, &self.config.bookmark)?;
1031610×
        let old_base = snap.base.maximal(&snap.wc.deps);
1032610×
        let mut all: Vec<ChangeHash> = old_heads.clone();
1033610×
        all.extend(old_base.iter().copied());
1034610×
        all.push(hash);
1035
        // The snapshot already loaded the working copy's base; when that also
1036
        // holds every bookmark head, it is the state to extend.
1037610×
        let mut st = if old_heads.iter().all(|h| snap.base.contains(h)) {
1038574×
            snap.base
1039
        } else {
104036×
            self.load_state(&all)?
1041
        };
1042610×
        st.add_hashed(hash, change)?;
1043610×
        let mut with_new = old_heads.clone();
1044610×
        with_new.push(hash);
1045610×
        let new_heads = st.maximal(&with_new);
1046
        // Automatic checkpoint once enough changes accumulated (spec §11).
1047610×
        let since = self
1048610×
            .latest_checkpoint(&self.config.bookmark)?
1049610×
            .map(|(_, cp)| cp.count)
1050610×
            .unwrap_or(0);
1051610×
        if self.config.checkpoint_interval > 0
1052610×
            && (st.len() as u64).saturating_sub(since) >= self.config.checkpoint_interval
1053
        {
10542×
            let cp_state = self.load_state_full(&new_heads)?;
10552×
            self.write_checkpoint(&self.config.bookmark, &cp_state, &new_heads)?;
1056608×
        }
1057610×
        let mut wc_base = old_base.clone();
1058610×
        wc_base.push(hash);
1059610×
        let wc_base = st.maximal(&wc_base);
1060610×
        drop(extending);
1061
1062
        // The graph keys of the files as they now are, from the state the
1063
        // commit just extended: a file whose graph it built has none, and
1064
        // is read by the next snapshot; a key the next base does not share
1065
        // (the bookmark held other heads) is simply not trusted then.
1066610×
        let keying = crate::timing::phase("commit: graph keys of the files");
1067610×
        let committed_keys =
1068610×
            (!partial).then(|| self.committed_graph_keys(&st, &changed_paths, &snap.attributes));
1069610×
        drop(keying);
1070610×
        let recording = crate::timing::phase("commit: record");
1071610×
        let wc = self.new_working_copy(wc_base, "");
1072610×
        let wc_hash = self.store.put_change(&wc)?;
1073610×
        let mut view = op.view.clone();
1074610×
        view.bookmarks.insert(
1075610×
            self.config.bookmark.clone(),
1076610×
            self.store.put_state(&StateObject::new(new_heads))?,
1077
        );
1078610×
        view.workspaces.insert(self.workspace, wc_hash);
1079610×
        self.record_op(&[op_ref], &format!("oxy commit -m {message:?}"), view)?;
1080605×
        drop(recording);
1081605×
        let rewriting = crate::timing::phase("commit: manifest");
1082605×
        if partial {
10835×
            // The rest is rebuilt from disk by the next snapshot.
10845×
            self.drop_manifest();
10855×
        } else {
1086600×
            let conflicted = snap.base_snapshot.is_conflicted() && !snap.resolves;
1087
            // The files on disk are now exactly the new base's renderings:
1088
            // record their graph keys, so the next snapshot neither reads nor
1089
            // renders them (oxygen#35).
1090600×
            let keys = if conflicted {
10910×
                HashMap::new()
1092
            } else {
1093600×
                committed_keys.unwrap_or_default()
1094
            };
1095600×
            match pending {
1096394×
                Some(m) => self.write_pending_manifest(m, conflicted, keys)?,
1097206×
                None => self.rewrite_manifest(conflicted, false, &keys)?,
1098
            }
1099
        }
1100605×
        drop(rewriting);
1101605×
        let packing = crate::timing::phase("commit: autopack");
1102605×
        self.maybe_autopack()?;
1103605×
        drop(packing);
1104605×
        let _hook = crate::timing::phase("commit: hook");
1105605×
        let _ = self.run_hook(
1106605×
            "post-commit",
1107605×
            &format!(
1108605×
                "{{\"event\":\"post-commit\",\"change_id\":{},\"hash\":{},\"message\":{}}}",
1109605×
                json_str(&snap.wc.change_id.to_hex()),
1110605×
                json_str(&hash.to_hex()),
1111605×
                json_str(message)
1112605×
            ),
1113605×
        );
1114605×
        Ok(hash)
1115615×
    }
1116
}
1117
1118
/// What part of the working copy a commit takes (spec §12.3).
1119
#[derive(Clone, Debug)]
1120
pub enum Selection {
1121
    All,
1122
    /// Every operation and edit on nodes under these paths.
1123
    Paths(Vec<String>),
1124
    /// Hunk indices as `Repo::hunks` numbers them; dependent hunks are added.
1125
    Hunks(Vec<usize>),
1126
}
1127
1128
/// One selectable piece of the working copy: a tree operation or an edit.
1129
#[derive(Clone, Debug)]
1130
pub struct Hunk {
1131
    pub index: usize,
1132
    pub path: String,
1133
    /// Rendered like `oxy diff`.
1134
    pub text: String,
1135
}
1136
1137
/// The tree operations and edits on nodes under `paths`, plus the
1138
/// additions of any new parent directories they need.
11392×
fn select_paths(
11402×
    wc: &Change,
11412×
    base_snapshot: &Snapshot,
11422×
    paths: &[String],
11432×
) -> (Vec<TreeOp>, Vec<Edit>) {
11447×
    let selected = |p: &str| {
11457×
        paths
11467×
            .iter()
11477×
            .any(|x| p == x || p.starts_with(&format!("{}/", x.trim_end_matches('/'))))
11487×
    };
11492×
    let by_node = base_snapshot.tree.by_node();
11502×
    let mut new_names: HashMap<NodeId, (NodeId, String, NodeKind)> = HashMap::new();
11512×
    for op in &wc.tree_ops {
1152
        if let TreeOp::AddNode {
11531×
            node,
11541×
            parent,
11551×
            name,
11561×
            kind,
1157
            ..
11581×
        } = op
11591×
        {
11601×
            new_names.insert(*node, (*parent, name.clone(), *kind));
11611×
        }
1162
    }
11632×
    let mut nodes: BTreeSet<NodeId> = BTreeSet::new();
11647×
    for n in wc
11652×
        .tree_ops
11662×
        .iter()
11672×
        .map(|o| o.node())
11686×
        .chain(wc.edits.iter().map(|e| e.node()))
1169
    {
11707×
        if path_of_node(&n, &by_node, &new_names).is_some_and(|p| selected(&p)) {
11714×
            nodes.insert(n);
11724×
        }
1173
    }
1174
    // New parents of selected new nodes come along.
11752×
    let mut changed = true;
11764×
    while changed {
11772×
        changed = false;
11782×
        for (n, (parent, _, _)) in &new_names {
11791×
            if nodes.contains(n) && new_names.contains_key(parent) && nodes.insert(*parent) {
11800×
                changed = true;
11811×
            }
1182
        }
1183
    }
11842×
    let ops = wc
11852×
        .tree_ops
11862×
        .iter()
11872×
        .filter(|o| nodes.contains(&o.node()))
11882×
        .cloned()
11892×
        .collect();
11902×
    let edits = wc
11912×
        .edits
11922×
        .iter()
11936×
        .filter(|e| nodes.contains(&e.node()))
11942×
        .cloned()
11952×
        .collect();
11962×
    (ops, edits)
11972×
}
1198
1199
/// The hunks `indices` name plus whatever they refer to within the working
1200
/// copy (the parent directory of an added node, the insert that introduced
1201
/// an anchor line), renumbered so the result is a well-formed change.
12025×
fn select_hunks(wc: &Change, indices: &[usize]) -> (Vec<TreeOp>, Vec<Edit>) {
12035×
    let n_ops = wc.tree_ops.len();
12045×
    let mut ops_sel = vec![false; n_ops];
12055×
    let mut edits_sel = vec![false; wc.edits.len()];
12065×
    for &i in indices {
12074×
        if i < n_ops {
12081×
            ops_sel[i] = true;
12093×
        } else if i - n_ops < wc.edits.len() {
12103×
            edits_sel[i - n_ops] = true;
12113×
        }
1212
    }
1213
    // Atom ranges each insert introduces, per node, in the working copy's numbering.
12145×
    let mut per_node: HashMap<NodeId, u32> = HashMap::new();
12155×
    let mut insert_ranges: Vec<Option<(NodeId, u32, u32)>> = Vec::new();
121610×
    for e in &wc.edits {
121710×
        insert_ranges.push(match e {
121810×
            Edit::Insert { node, lines, .. } => {
121910×
                let start = per_node.entry(*node).or_default();
122010×
                let r = (*node, *start, *start + lines.len() as u32);
122110×
                *start += lines.len() as u32;
122210×
                Some(r)
1223
            }
12240×
            _ => None,
1225
        });
1226
    }
12275×
    let add_index: HashMap<NodeId, usize> = wc
12285×
        .tree_ops
12295×
        .iter()
12305×
        .enumerate()
12318×
        .filter_map(|(i, o)| {
12328×
            if let TreeOp::AddNode { node, .. } = o {
12338×
                Some((*node, i))
1234
            } else {
12350×
                None
1236
            }
12378×
        })
12385×
        .collect();
12395×
    let insert_for = |node: &NodeId, index: u32| -> Option<usize> {
12400×
        insert_ranges
12410×
            .iter()
12420×
            .position(|r| matches!(r, Some((n, a, b)) if n == node && *a <= index && index < *b))
12430×
    };
1244
    // Closure.
12455×
    let mut changed = true;
124613×
    while changed {
12478×
        changed = false;
124817×
        for i in 0..n_ops {
124917×
            if !ops_sel[i] {
125011×
                continue;
12516×
            }
12526×
            if let TreeOp::AddNode { node, parent, .. } = &wc.tree_ops[i] {
12536×
                if let Some(&p) = add_index.get(parent) {
12544×
                    if !ops_sel[p] {
12552×
                        ops_sel[p] = true;
12562×
                        changed = true;
12572×
                    }
12582×
                }
1259
                // A new node's content belongs with its addition: nobody
1260
                // wants an empty file committed apart from its lines.
126112×
                for (j, e) in wc.edits.iter().enumerate() {
126212×
                    if e.node() == *node && !edits_sel[j] {
12631×
                        edits_sel[j] = true;
12641×
                        changed = true;
126511×
                    }
1266
                }
12670×
            }
1268
        }
126916×
        for j in 0..wc.edits.len() {
127016×
            if !edits_sel[j] {
12719×
                continue;
12727×
            }
12737×
            let e = &wc.edits[j];
12747×
            if let Some(&a) = add_index.get(&e.node()) {
12755×
                if !ops_sel[a] {
12761×
                    ops_sel[a] = true;
12771×
                    changed = true;
12784×
                }
12792×
            }
1280
            if let Edit::Insert {
12817×
                node,
12827×
                after,
12837×
                before,
1284
                ..
12857×
            } = e
1286
            {
128714×
                for r in [after, before] {
128814×
                    if let AtomRef::Atom { change, index } = r {
12892×
                        if change.is_zero() {
12900×
                            if let Some(k) = insert_for(node, *index) {
12910×
                                if !edits_sel[k] {
12920×
                                    edits_sel[k] = true;
12930×
                                    changed = true;
12940×
                                }
12950×
                            }
12962×
                        }
129712×
                    }
1298
                }
12990×
            }
1300
        }
1301
    }
1302
    // Renumber self-references: old atom index → new index among selected inserts.
13035×
    let mut remap: HashMap<(NodeId, u32), u32> = HashMap::new();
13045×
    let mut new_counts: HashMap<NodeId, u32> = HashMap::new();
130510×
    for (j, r) in insert_ranges.iter().enumerate() {
130610×
        if let (true, Some((node, a, b))) = (edits_sel[j], r) {
13074×
            let next = new_counts.entry(*node).or_default();
13084×
            for old in *a..*b {
13094×
                remap.insert((*node, old), *next);
13104×
                *next += 1;
13114×
            }
13126×
        }
1313
    }
13148×
    let map_ref = |r: AtomRef, node: &NodeId| -> AtomRef {
13152×
        match r {
13162×
            AtomRef::Atom { change, index } if change.is_zero() => AtomRef::Atom {
13170×
                change,
13180×
                index: remap.get(&(*node, index)).copied().unwrap_or(index),
13190×
            },
13208×
            other => other,
1321
        }
13228×
    };
13235×
    let ops = wc
13245×
        .tree_ops
13255×
        .iter()
13265×
        .enumerate()
13278×
        .filter(|(i, _)| ops_sel[*i])
13285×
        .map(|(_, o)| o.clone())
13295×
        .collect();
13305×
    let edits = wc
13315×
        .edits
13325×
        .iter()
13335×
        .enumerate()
133410×
        .filter(|(j, _)| edits_sel[*j])
13355×
        .map(|(_, e)| match e {
1336
            Edit::Insert {
13374×
                node,
13384×
                after,
13394×
                before,
13404×
                lines,
13414×
            } => Edit::Insert {
13424×
                node: *node,
13434×
                after: map_ref(*after, node),
13444×
                before: map_ref(*before, node),
13454×
                lines: lines.clone(),
13464×
            },
13470×
            other => other.clone(),
13484×
        })
13495×
        .collect();
13505×
    (ops, edits)
13515×
}
1352
1353
/// Render each tree operation and edit of `change` on its own, numbered.
13547×
pub fn render_hunks(change: &Change, base: &State, base_snapshot: &Snapshot) -> Vec<Hunk> {
13557×
    let by_node = base_snapshot.tree.by_node();
13567×
    let mut new_names: HashMap<NodeId, (NodeId, String, NodeKind)> = HashMap::new();
13578×
    for op in &change.tree_ops {
1358
        if let TreeOp::AddNode {
13598×
            node,
13608×
            parent,
13618×
            name,
13628×
            kind,
1363
            ..
13648×
        } = op
13658×
        {
13668×
            new_names.insert(*node, (*parent, name.clone(), *kind));
13678×
        }
1368
    }
13697×
    let mut out = Vec::new();
13708×
    for (i, op) in change.tree_ops.iter().enumerate() {
13718×
        let one = Change {
13728×
            tree_ops: vec![op.clone()],
13738×
            edits: vec![],
13748×
            ..change.clone()
13758×
        };
13768×
        let path = path_of_node(&op.node(), &by_node, &new_names).unwrap_or_default();
13778×
        out.push(Hunk {
13788×
            index: i,
13798×
            path,
13808×
            text: render_change(&one, base, base_snapshot),
13818×
        });
13828×
    }
138313×
    for (j, e) in change.edits.iter().enumerate() {
138413×
        let one = Change {
138513×
            tree_ops: vec![],
138613×
            edits: vec![e.clone()],
138713×
            ..change.clone()
138813×
        };
138913×
        let path = path_of_node(&e.node(), &by_node, &new_names).unwrap_or_default();
139013×
        out.push(Hunk {
139113×
            index: change.tree_ops.len() + j,
139213×
            path,
139313×
            text: render_change(&one, base, base_snapshot),
139413×
        });
139513×
    }
13967×
    out
13977×
}
1398
1399
/// One file's part of a diff, for `oxy diff --json`.
1400
#[derive(Clone, Debug)]
1401
pub struct FileDiff {
1402
    pub path: String,
1403
    /// `added`, `removed`, `modified`, `renamed`, `mode`, `replaced`.
1404
    pub kind: String,
1405
    pub hunks: Vec<DiffHunk>,
1406
    /// For renames, the previous path.
1407
    pub from: Option<String>,
1408
}
1409
1410
/// Lines inserted after `base_line` (0 = before the first line) and lines
1411
/// removed, with their base line numbers.
1412
#[derive(Clone, Debug, Default)]
1413
pub struct DiffHunk {
1414
    pub base_line: u32,
1415
    pub added: Vec<Vec<u8>>,
1416
    pub removed: Vec<(u32, Vec<u8>)>,
1417
}
1418
1419
impl Repo {
1420
    /// The content of `path` in a state: `heads`, or the working copy's base.
14217×
    pub fn file_at(&self, path: &str, heads: Option<&[ChangeHash]>) -> Result<Vec<u8>> {
14227×
        let snapshot = match heads {
14236×
            Some(h) => self.load_state(h)?.materialize(),
1424
            None => {
14251×
                let (_, wc) = self.working_copy()?;
14261×
                self.load_state(&wc.deps)?.materialize()
1427
            }
1428
        };
14297×
        let Some(f) = snapshot.files.get(path) else {
14300×
            return fail(format!("{path} is not in that state"));
1431
        };
14327×
        match &f.content {
14330×
            FileContent::Dir => fail(format!("{path} is a directory")),
14347×
            FileContent::Text { bytes, .. } => Ok(bytes.clone()),
14350×
            FileContent::Opaque { blobs } => match blobs.first() {
14360×
                Some(b) => self.read_blob(b),
14370×
                None => Ok(vec![]),
1438
            },
1439
        }
14407×
    }
1441
1442
    /// Restore `paths` (files or directories) to the working copy's base:
1443
    /// edits are undone, additions removed, removals put back. Returns the
1444
    /// number of paths touched.
14452×
    pub fn discard(&self, paths: &[String]) -> Result<usize> {
14462×
        let _wc = self.lock_working_copy()?;
14472×
        let snap = self.snapshot_status("oxy discard")?;
14487×
        let under = |p: &str| {
14497×
            paths
14507×
                .iter()
14517×
                .any(|x| p == x || p.starts_with(&format!("{}/", x.trim_end_matches('/'))))
14527×
        };
14532×
        let attrs = Repo::state_attributes(&snap.base_snapshot);
14542×
        let mut n = 0;
14553×
        for s in &snap.statuses {
14563×
            if !under(&s.path) {
14571×
                continue;
14582×
            }
14592×
            match snap.base_snapshot.files.get(&s.path) {
1460
                None => {
1461
                    // Added (or the new name of a rename): remove it.
14621×
                    let full = self.root.join(&s.path);
14631×
                    if full.is_dir() {
14640×
                        let _ = fs::remove_dir_all(&full);
14651×
                    } else {
14661×
                        let _ = fs::remove_file(&full);
14671×
                    }
14681×
                    n += 1;
1469
                }
14701×
                Some(f) => {
14711×
                    match &f.content {
14720×
                        FileContent::Dir => fs::create_dir_all(self.root.join(&s.path))?,
14731×
                        FileContent::Text { bytes, .. } => {
14741×
                            let on_disk: std::borrow::Cow<[u8]> = if attrs.lookup(&s.path).eol
14751×
                                == Some(crate::attributes::Eol::Crlf)
1476
                            {
14770×
                                crate::attributes::to_crlf(bytes).into()
1478
                            } else {
14791×
                                bytes.as_slice().into()
1480
                            };
14811×
                            self.write_file(&s.path, &on_disk, f.mode.exec)?;
1482
                        }
14830×
                        FileContent::Opaque { blobs } => {
14840×
                            let bytes = match blobs.first() {
14850×
                                Some(b) => self.read_blob(b)?,
14860×
                                None => vec![],
1487
                            };
14880×
                            if f.kind == NodeKind::Symlink {
14890×
                                self.write_symlink(&s.path, &bytes)?;
14900×
                            } else if f.kind == NodeKind::File {
14910×
                                self.write_file(&s.path, &bytes, f.mode.exec)?;
14920×
                            }
1493
                        }
1494
                    }
14951×
                    n += 1;
1496
                }
1497
            }
1498
        }
1499
        // A rename's old name is not in the statuses; put it back too.
15004×
        for (p, f) in &snap.base_snapshot.files {
15014×
            if under(p)
15021×
                && !self.root.join(p).exists()
15030×
                && f.kind != NodeKind::Dir
15040×
                && f.kind != NodeKind::Subrepo
15050×
                && !snap.statuses.iter().any(|s| s.path == *p)
1506
            {
15070×
                let bytes = match &f.content {
15080×
                    FileContent::Text { bytes, .. } => bytes.clone(),
15090×
                    FileContent::Opaque { blobs } => blobs
15100×
                        .first()
15110×
                        .map(|b| self.read_blob(b))
15120×
                        .transpose()?
15130×
                        .unwrap_or_default(),
15140×
                    FileContent::Dir => continue,
1515
                };
15160×
                if f.kind == NodeKind::Symlink {
15170×
                    self.write_symlink(p, &bytes)?
1518
                } else {
15190×
                    self.write_file(p, &bytes, f.mode.exec)?
1520
                }
15210×
                n += 1;
15224×
            }
1523
        }
15242×
        self.drop_manifest();
15252×
        Ok(n)
15262×
    }
1527
1528
    /// Undo the working-copy hunks `indices` (as `hunks` numbers them) on
1529
    /// disk, keeping the others: the files are rewritten from the base plus
1530
    /// the remaining hunks.
15311×
    pub fn discard_hunks(&self, indices: &[usize]) -> Result<usize> {
15321×
        let _wc = self.lock_working_copy()?;
15331×
        let (snap, hunks) = self.hunks()?;
15341×
        let keep: Vec<usize> = hunks
15351×
            .iter()
15361×
            .map(|h| h.index)
15371×
            .filter(|i| !indices.contains(i))
15381×
            .collect();
15391×
        let (ops, edits) = select_hunks(&snap.wc, &keep);
15401×
        let dropped_nodes: BTreeSet<NodeId> = hunks
15411×
            .iter()
15421×
            .filter(|h| indices.contains(&h.index))
15431×
            .map(|h| {
15441×
                if h.index < snap.wc.tree_ops.len() {
15450×
                    snap.wc.tree_ops[h.index].node()
1546
                } else {
15471×
                    snap.wc.edits[h.index - snap.wc.tree_ops.len()].node()
1548
                }
15491×
            })
15501×
            .collect();
15511×
        let mut partial = snap.wc.clone();
15521×
        partial.tree_ops = ops;
15531×
        partial.edits = edits;
15541×
        partial.normalize();
15551×
        let mut st = snap.base.clone();
15561×
        st.add_unchecked(partial);
1557
        // Every file of the target is rendered: build the graphs the
1558
        // partial snapshot left out.
15591×
        self.load_all_graphs(&mut st)?;
15601×
        let target = st.materialize();
15611×
        let by_node_target = target.tree.by_node();
15621×
        let by_node_base = snap.base_snapshot.tree.by_node();
15631×
        let attrs = Repo::state_attributes(&target);
15641×
        let mut n = 0;
15651×
        for node in dropped_nodes {
15661×
            match by_node_target.get(&node) {
15671×
                Some(e) => {
15681×
                    let f = &target.files[&e.path];
15691×
                    match &f.content {
15700×
                        FileContent::Dir => {}
15711×
                        FileContent::Text { bytes, .. } => {
15721×
                            let on_disk: std::borrow::Cow<[u8]> = if attrs.lookup(&e.path).eol
15731×
                                == Some(crate::attributes::Eol::Crlf)
1574
                            {
15750×
                                crate::attributes::to_crlf(bytes).into()
1576
                            } else {
15771×
                                bytes.as_slice().into()
1578
                            };
15791×
                            self.write_file(&e.path, &on_disk, f.mode.exec)?;
1580
                        }
15810×
                        FileContent::Opaque { blobs } => {
15820×
                            let bytes = blobs
15830×
                                .first()
15840×
                                .map(|b| self.read_blob(b))
15850×
                                .transpose()?
15860×
                                .unwrap_or_default();
15870×
                            if f.kind == NodeKind::Symlink {
15880×
                                self.write_symlink(&e.path, &bytes)?
1589
                            } else {
15900×
                                self.write_file(&e.path, &bytes, f.mode.exec)?
1591
                            }
1592
                        }
1593
                    }
1594
                    // A discarded rename: the new name goes.
15951×
                    if let Some(old_path) = snap
15961×
                        .statuses
15971×
                        .iter()
15981×
                        .find(|s| {
15991×
                            s.status == ChangeStatus::Renamed && !target.files.contains_key(&s.path)
16001×
                        })
16011×
                        .map(|s| s.path.clone())
16020×
                    {
16030×
                        let _ = fs::remove_file(self.root.join(old_path));
16041×
                    }
16051×
                    n += 1;
1606
                }
1607
                None => {
1608
                    // The node exists in neither target nor base with a live path: an addition to remove.
16090×
                    if let Some(added) = snap.statuses.iter().find(|s| {
16100×
                        s.status == ChangeStatus::Added
16110×
                            && !target.files.contains_key(&s.path)
16120×
                            && !by_node_base.contains_key(&node)
16130×
                    }) {
16140×
                        let full = self.root.join(&added.path);
16150×
                        if full.is_dir() {
16160×
                            let _ = fs::remove_dir_all(&full);
16170×
                        } else {
16180×
                            let _ = fs::remove_file(&full);
16190×
                        }
16200×
                        n += 1;
16210×
                    }
1622
                }
1623
            }
1624
        }
16251×
        self.drop_manifest();
16261×
        Ok(n)
16271×
    }
1628
1629
    /// The diff of the working copy (`None`) or of a change, per file with
1630
    /// line-numbered hunks (spec: `oxy diff --json`).
16315×
    pub fn diff_files(&self, change: Option<&ChangeHash>) -> Result<Vec<FileDiff>> {
16325×
        let (c, base, base_snapshot) = match change {
16332×
            Some(h) => {
16342×
                let c = self.store.get_change(h)?;
16352×
                let (base, snapshot) = self.change_base(&c)?;
16362×
                (c, base, snapshot)
1637
            }
16383×
            None => self.working_copy_with_base()?,
1639
        };
16405×
        Ok(diff_files_of(&c, &base, &base_snapshot))
16415×
    }
1642
1643
    /// The snapshot a command would take, without taking it, when the
1644
    /// status cache holds: every file is as the last snapshot left it, so
1645
    /// that snapshot's working-copy change is the answer. Its base comes
1646
    /// from the state index, the `.oxyattributes` files from disk. `None`
1647
    /// when a snapshot must be taken, and when there is nothing to commit
1648
    /// (the snapshot then says so). A conflicted base never gets here: the
1649
    /// cache does not hold for one.
1650616×
    pub(crate) fn snapshot_from_cache(&self) -> Result<Option<SnapshotResult>> {
1651616×
        let Some(statuses) = self.status_by_manifest()? else {
1652403×
            return Ok(None);
1653
        };
1654213×
        if statuses.is_empty() {
16552×
            return Ok(None);
1656211×
        }
1657211×
        let _t = crate::timing::phase("snapshot: from the status cache");
1658211×
        let (wc_hash, wc) = self.working_copy()?;
1659211×
        let base = self.load_state_indexed(&wc.deps)?;
1660211×
        let (base, base_snapshot) = self.render_base_for(&wc, base)?;
1661211×
        let attribute_files: Vec<(String, Vec<u8>)> = match self.read_manifest()? {
1662211×
            Some((_, _, m)) => m
1663211×
                .entries
1664211×
                .keys()
1665642×
                .filter(|p| is_attributes(p))
1666211×
                .filter_map(|p| fs::read(self.root.join(p)).ok().map(|b| (p.clone(), b)))
1667211×
                .collect(),
16680×
            None => Vec::new(),
1669
        };
1670211×
        let attributes = crate::attributes::Attributes::from_files(
1671211×
            attribute_files
1672211×
                .iter()
1673211×
                .map(|(p, b)| (p.as_str(), b.as_slice())),
1674
        );
1675211×
        Ok(Some(SnapshotResult {
1676211×
            wc_hash,
1677211×
            wc,
1678211×
            base,
1679211×
            base_snapshot,
1680211×
            statuses,
1681211×
            changed: false,
1682211×
            resolves: false,
1683211×
            contributors: Vec::new(),
1684211×
            attributes,
1685211×
            untracked_nested: self.untracked_nested.borrow().clone(),
1686211×
            manifest: None,
1687211×
        }))
1688616×
    }
1689
1690
    /// The working-copy change with its base state and a snapshot of the
1691
    /// base, for showing what the working copy changes ([`render_change`],
1692
    /// [`diff_files_of`]). While the status cache holds (every file as the
1693
    /// last snapshot left it), the stored working-copy change is the
1694
    /// answer, no snapshot is taken, and the base's snapshot holds its tree
1695
    /// but no file; otherwise a snapshot makes all three.
16964×
    pub fn working_copy_with_base(&self) -> Result<(Change, State, Snapshot)> {
16974×
        if self.status_by_manifest()?.is_some() {
16982×
            let (_, wc) = self.working_copy()?;
16992×
            let base = self.load_state_indexed(&wc.deps)?;
17002×
            let (base, snapshot) = self.tree_base_for(&wc, base)?;
17012×
            return Ok((wc, base, snapshot));
17022×
        }
17032×
        let snap = self.snapshot_status("oxy diff")?;
17042×
        Ok((snap.wc, snap.base, snap.base_snapshot))
17054×
    }
1706
1707
    /// The log restricted to changes touching `path` (its node, so renames
1708
    /// are followed), on the current bookmark.
17092×
    pub fn log_for_path(&self, path: &str) -> Result<Vec<LogEntry>> {
17102×
        let heads = self.bookmark_heads()?;
17112×
        if self.is_bare() {
17121×
            return self.log_for_path_in(path, &heads);
17131×
        }
17141×
        let entries = self.log()?;
17151×
        let (_, wc) = self.working_copy()?;
17161×
        let base_snapshot = self.load_state(&wc.deps)?.materialize();
17171×
        let state_snapshot = self.load_state(&heads)?.materialize();
17181×
        let node = base_snapshot
17191×
            .files
17201×
            .get(path)
17211×
            .or_else(|| state_snapshot.files.get(path))
17221×
            .map(|f| f.node);
17231×
        let Some(node) = node else {
17240×
            return fail(format!("{path} is not tracked"));
1725
        };
17261×
        Ok(self.entries_touching(entries, node))
17272×
    }
1728
1729
    /// The log of the state with these heads restricted to changes touching
1730
    /// `path` (its node, so renames are followed).
17312×
    pub fn log_for_path_in(&self, path: &str, heads: &[ChangeHash]) -> Result<Vec<LogEntry>> {
17322×
        self.log_for_path_of(&self.load_state_history(heads)?, path, None)
17332×
    }
1734
1735
    /// The changes of a loaded state touching `path`, newest first, at most
1736
    /// `limit` of them. The path is found in the state's tree alone, so no
1737
    /// file is rendered, and the walk stops once `limit` are found.
17385×
    pub fn log_for_path_of(
17395×
        &self,
17405×
        state: &State,
17415×
        path: &str,
17425×
        limit: Option<usize>,
17435×
    ) -> Result<Vec<LogEntry>> {
17445×
        let Some(node) = state.tree().view().entries.get(path).map(|e| e.node) else {
17451×
            return fail(format!("{path} is not in that state"));
1746
        };
17474×
        Ok(self.entries_touching_up_to(self.log_of(state), node, limit))
17485×
    }
1749
17501×
    fn entries_touching(&self, entries: Vec<LogEntry>, node: NodeId) -> Vec<LogEntry> {
17511×
        self.entries_touching_up_to(entries, node, None)
17521×
    }
1753
17545×
    fn entries_touching_up_to(
17555×
        &self,
17565×
        entries: Vec<LogEntry>,
17575×
        node: NodeId,
17585×
        limit: Option<usize>,
17595×
    ) -> Vec<LogEntry> {
17605×
        let mut out = Vec::new();
176116×
        for e in entries {
176216×
            if limit.is_some_and(|n| out.len() >= n) {
17631×
                break;
176415×
            }
176515×
            let Ok(c) = self.store.get_change(&e.hash) else {
17660×
                continue;
1767
            };
176815×
            if c.tree_ops.iter().any(|o| o.node() == node)
176915×
                || c.edits.iter().any(|x| x.node() == node)
17709×
            {
17719×
                out.push(e);
17729×
            }
1773
        }
17745×
        out
17755×
    }
1776
}
1777
1778
/// Per-file hunks of `change` against `base`.
17795×
pub fn diff_files_of(change: &Change, base: &State, base_snapshot: &Snapshot) -> Vec<FileDiff> {
17805×
    let by_node = base_snapshot.tree.by_node();
17815×
    let mut new_names: HashMap<NodeId, (NodeId, String, NodeKind)> = HashMap::new();
17825×
    for op in &change.tree_ops {
1783
        if let TreeOp::AddNode {
17842×
            node,
17852×
            parent,
17862×
            name,
17872×
            kind,
1788
            ..
17893×
        } = op
17902×
        {
17912×
            new_names.insert(*node, (*parent, name.clone(), *kind));
17922×
        }
1793
    }
17949×
    let path_of = |n: &NodeId| -> String {
17959×
        path_of_node(n, &by_node, &new_names).unwrap_or_else(|| format!("<node {}>", n.short(8)))
17969×
    };
17975×
    let mut files: BTreeMap<NodeId, FileDiff> = BTreeMap::new();
17985×
    let mut order: Vec<NodeId> = Vec::new();
179914×
    let mut entry = |files: &mut BTreeMap<NodeId, FileDiff>, n: NodeId, kind: &str| {
180014×
        if let std::collections::btree_map::Entry::Vacant(v) = files.entry(n) {
18019×
            order.push(n);
18029×
            v.insert(FileDiff {
18039×
                path: path_of(&n),
18049×
                kind: kind.to_string(),
18059×
                hunks: vec![],
18069×
                from: None,
18079×
            });
18089×
        }
180914×
    };
18105×
    for op in &change.tree_ops {
18113×
        match op {
18122×
            TreeOp::AddNode { node, kind, .. } => {
18132×
                if *kind != NodeKind::Dir {
18142×
                    entry(&mut files, *node, "added");
18152×
                }
1816
            }
18171×
            TreeOp::RemoveNode { node, .. } => {
18181×
                entry(&mut files, *node, "removed");
18191×
                if let Some(e) = by_node.get(node) {
18201×
                    files.get_mut(node).unwrap().path = e.path.clone();
18211×
                }
1822
            }
1823
            TreeOp::Move {
18240×
                node, parent, name, ..
1825
            } => {
18260×
                entry(&mut files, *node, "renamed");
18270×
                let f = files.get_mut(node).unwrap();
18280×
                f.from = by_node.get(node).map(|e| e.path.clone());
18290×
                let dir = if parent.is_root() {
18300×
                    String::new()
1831
                } else {
18320×
                    path_of_node(parent, &by_node, &new_names).unwrap_or_default()
1833
                };
18340×
                f.path = if dir.is_empty() {
18350×
                    name.clone()
1836
                } else {
18370×
                    format!("{dir}/{name}")
1838
                };
1839
            }
18400×
            TreeOp::SetMode { node, .. } => entry(&mut files, *node, "mode"),
1841
        }
1842
    }
1843
    // Base line numbers per node, 1-based.
18445×
    let mut line_of: HashMap<NodeId, HashMap<(ChangeHash, u32), u32>> = HashMap::new();
184511×
    let mut lines_for = |n: &NodeId| -> HashMap<(ChangeHash, u32), u32> {
184611×
        line_of
184711×
            .entry(*n)
184811×
            .or_insert_with(|| {
18498×
                base.live_lines(n)
18508×
                    .into_iter()
18518×
                    .enumerate()
185211×
                    .map(|(i, (k, _))| (k, i as u32 + 1))
18538×
                    .collect()
18548×
            })
185511×
            .clone()
185611×
    };
185711×
    for e in &change.edits {
185811×
        let n = e.node();
185911×
        let is_new = new_names.contains_key(&n);
186011×
        entry(&mut files, n, if is_new { "added" } else { "modified" });
186111×
        let f = files.get_mut(&n).unwrap();
186211×
        match e {
18639×
            Edit::Insert { after, lines, .. } => {
18649×
                let map = lines_for(&n);
18659×
                let base_line = match after {
18663×
                    AtomRef::Start => 0,
18670×
                    AtomRef::End => map.len() as u32,
18686×
                    AtomRef::Atom { change, index } if change.is_zero() => {
18690×
                        f.hunks.last().map(|h| h.base_line).unwrap_or(0)
1870
                    }
18716×
                    AtomRef::Atom { change, index } => {
18726×
                        map.get(&(*change, *index)).copied().unwrap_or(0)
1873
                    }
1874
                };
18759×
                f.hunks.push(DiffHunk {
18769×
                    base_line,
18779×
                    added: lines.to_vec(),
18789×
                    removed: vec![],
18799×
                });
1880
            }
18812×
            Edit::Delete { atoms, .. } => {
18822×
                let map = lines_for(&n);
18832×
                let mut removed = Vec::new();
18842×
                for r in atoms {
18852×
                    for i in r.from..r.to {
18862×
                        let line = map.get(&(r.change, i)).copied().unwrap_or(0);
18872×
                        let text = base
18882×
                            .file(&n)
18892×
                            .and_then(|g| g.content(&(r.change, i)))
18902×
                            .unwrap_or(b"")
18912×
                            .to_vec();
18922×
                        removed.push((line, text));
1893
                    }
1894
                }
18952×
                let base_line = removed
18962×
                    .first()
18972×
                    .map(|(l, _)| l.saturating_sub(1))
18982×
                    .unwrap_or(0);
18992×
                f.hunks.push(DiffHunk {
19002×
                    base_line,
19012×
                    added: vec![],
19022×
                    removed,
19032×
                });
1904
            }
1905
            Edit::Replace { .. } => {
19060×
                if !is_new {
19070×
                    f.kind = "replaced".into();
19080×
                }
1909
            }
1910
        }
1911
    }
19129×
    order.into_iter().filter_map(|n| files.remove(&n)).collect()
19135×
}
1914
1915
/// Builds the tree ops and edits of a working-copy change against a base.
1916
/// `BLAKE3("oxy node 1" 0 seed kind path)`, truncated: a node identifier
1917
/// that the same seed and path always give (never the root's).
191853×
fn seeded_node(seed: &[u8; 32], path: &str, kind: NodeKind) -> NodeId {
191953×
    let mut h = blake3::Hasher::new();
192053×
    h.update(b"oxy node 1\0");
192153×
    h.update(seed);
192253×
    h.update(&[match kind {
192341×
        NodeKind::File => 1,
192411×
        NodeKind::Dir => 2,
19250×
        NodeKind::Symlink => 3,
19261×
        NodeKind::Subrepo => 4,
1927
    }]);
192853×
    h.update(path.as_bytes());
192953×
    let mut id = [0u8; 16];
193053×
    id.copy_from_slice(&h.finalize().as_bytes()[..16]);
193153×
    if id == [0; 16] {
19320×
        id[15] = 1;
193353×
    }
193453×
    NodeId(id)
193553×
}
1936
1937
struct ChangeBuilder<'a> {
1938
    base: &'a State,
1939
    base_snapshot: &'a Snapshot,
1940
    tree_ops: Vec<TreeOp>,
1941
    edits: Vec<Edit>,
1942
    statuses: Vec<PathStatus>,
1943
    dir_nodes: HashMap<String, NodeId>,
1944
    reuse: HashMap<String, (NodeId, NodeKind)>,
1945
    /// Changes that contributed to conflicts this working copy resolves.
1946
    contributors: BTreeSet<ChangeHash>,
1947
    resolves: bool,
1948
    attrs: crate::attributes::Attributes,
1949
    blobs: HashMap<String, ObjectRef>,
1950
    /// Opaque files whose replace conflict the content settles.
1951
    resolve: HashSet<String>,
1952
    /// When set, new nodes' identifiers derive from it and their paths.
1953
    node_seed: Option<[u8; 32]>,
1954
    /// For a Git import, the base's dead directories by where they were
1955
    /// (see `ensure_dir`), worked out when first needed.
1956
    dead_dirs: Option<HashMap<(NodeId, String), (NodeId, crate::tree::OpKey)>>,
1957
    /// Text edits of edited files, worked out in parallel beforehand
1958
    /// (`diff_in_parallel`); a file not here is diffed when it is updated.
1959
    diffs: HashMap<String, Vec<Edit>>,
1960
}
1961
1962
impl<'a> ChangeBuilder<'a> {
19631810×
    fn new(
19641810×
        base: &'a State,
19651810×
        base_snapshot: &'a Snapshot,
19661810×
        reuse: HashMap<String, (NodeId, NodeKind)>,
19671810×
    ) -> Self {
19681810×
        let mut dir_nodes: HashMap<String, NodeId> = HashMap::new();
19691810×
        dir_nodes.insert(String::new(), NodeId::ROOT);
197017555×
        for (p, e) in base_snapshot.tree.entries.iter() {
197117555×
            if e.kind == NodeKind::Dir {
1972551×
                dir_nodes.insert(p.clone(), e.node);
197317004×
            }
1974
        }
19751810×
        ChangeBuilder {
19761810×
            base,
19771810×
            base_snapshot,
19781810×
            tree_ops: vec![],
19791810×
            edits: vec![],
19801810×
            statuses: vec![],
19811810×
            dir_nodes,
19821810×
            reuse,
19831810×
            contributors: BTreeSet::new(),
19841810×
            resolves: false,
19851810×
            attrs: crate::attributes::Attributes::default(),
19861810×
            blobs: HashMap::new(),
19871810×
            resolve: HashSet::new(),
19881810×
            node_seed: None,
19891810×
            dead_dirs: None,
19901810×
            diffs: HashMap::new(),
19911810×
        }
19921810×
    }
1993
1994
    /// Diff the edited text files among `entries` against their base
1995
    /// renderings at once, on every core, for `update_path` to take: the
1996
    /// same diff it would make, only not one file after another.
19971810×
    fn diff_in_parallel(&mut self, entries: &BTreeMap<String, FsEntry>) {
1998
        use rayon::prelude::*;
19991810×
        let files = &self.base_snapshot.files;
20001810×
        let edited: Vec<(&String, &FsEntry, &crate::state::FileState)> = entries
20011810×
            .iter()
200218487×
            .filter_map(|(p, e)| {
200318487×
                let x = files.get(p)?;
200412580×
                (x.kind == e.kind && !e.unchanged && !self.opaque_for(p, e)).then_some((p, e, x))
200518487×
            })
20061810×
            .collect();
2007
        // Below this, starting the threads costs more than it saves.
20081810×
        if edited.len() < 16 {
20091800×
            return;
201010×
        }
201110×
        let this = &*self;
201210×
        let attrs = &this.attrs;
201310×
        let diffs: Vec<(String, Vec<Edit>)> = edited
201410×
            .par_iter()
20155564×
            .filter_map(|(p, e, x)| {
2016
                let FileContent::Text {
20175564×
                    bytes,
20185564×
                    materialized,
20195564×
                } = &x.content
2020
                else {
20210×
                    return None;
2022
                };
20235564×
                if materialized.is_conflicted() {
20240×
                    return None;
20255564×
                }
20265564×
                let disk_text = if attrs.lookup(p).eol.is_some() {
20270×
                    std::sync::Arc::new(crate::attributes::normalize_eol(&e.content))
2028
                } else {
20295564×
                    e.content.clone()
2030
                };
20315564×
                if *bytes == *disk_text {
20325484×
                    return None;
203380×
                }
203480×
                let keys = materialized.live_atoms();
203580×
                let lines = crate::diff::split_lines(bytes);
203680×
                (keys.len() == lines.len()).then(|| {
203780×
                    let edits = crate::diff::text_edits_of(x.node, &keys, &lines, &disk_text);
203880×
                    ((*p).clone(), edits)
203980×
                })
20405564×
            })
204110×
            .collect();
204210×
        self.diffs = diffs.into_iter().collect();
20431810×
    }
2044
20451810×
    fn with_attributes(mut self, attrs: crate::attributes::Attributes) -> Self {
20461810×
        self.attrs = attrs;
20471810×
        self
20481810×
    }
2049
2050
    /// Whether a file is opaque: forced by `binary`, forced text by `text`
2051
    /// only when it has no NUL bytes, else sniffed.
2052
    /// The blob for an opaque entry: the cached one, else stored now.
2053122×
    fn blob_of(
2054122×
        &mut self,
2055122×
        repo: &Repo,
2056122×
        path: &str,
2057122×
        e: &FsEntry,
2058122×
        nocompress: bool,
2059122×
    ) -> Result<ObjectRef> {
2060122×
        let b = match e.blob {
20610×
            Some(b) => b,
2062122×
            None => repo.store_blob_for(&e.content, nocompress)?,
2063
        };
2064122×
        self.blobs.insert(path.to_string(), b);
2065122×
        Ok(b)
2066122×
    }
2067
206822510×
    fn opaque_for(&self, path: &str, e: &FsEntry) -> bool {
206922510×
        if e.blob.is_some() {
20708×
            return true;
207122502×
        }
207222502×
        if e.kind == NodeKind::Symlink || e.kind == NodeKind::Subrepo {
207375×
            return true;
207422427×
        }
207522427×
        match self.attrs.lookup(path).binary {
207612×
            Some(true) => true,
20770×
            Some(false) => is_binary(&e.content),
207822415×
            None => is_binary(&e.content),
2079
        }
208022510×
    }
2081
2082
    /// Text content as stored: `\r\n` normalized for `eol=` files.
208314091×
    fn stored_text(
208414091×
        &self,
208514091×
        path: &str,
208614091×
        content: &std::sync::Arc<Vec<u8>>,
208714091×
    ) -> std::sync::Arc<Vec<u8>> {
208814091×
        if self.attrs.lookup(path).eol.is_some() {
20897×
            std::sync::Arc::new(crate::attributes::normalize_eol(content))
2090
        } else {
209114084×
            content.clone()
2092
        }
209314091×
    }
2094
2095
    /// The identifier of a node added at `path`: reused when asked, derived
2096
    /// from the seed when there is one, random otherwise.
20976032×
    fn new_node(&self, path: &str, kind: NodeKind) -> NodeId {
20986032×
        if let Some(n) = self.reused_node(path, kind) {
2099118×
            return n;
21005914×
        }
21015914×
        match &self.node_seed {
210253×
            Some(seed) => seeded_node(seed, path, kind),
21035861×
            None => NodeId::random(),
2104
        }
21056032×
    }
2106
21076032×
    fn reused_node(&self, path: &str, kind: NodeKind) -> Option<NodeId> {
21086032×
        self.reuse
21096032×
            .get(path)
21106032×
            .filter(|(_, k)| *k == kind)
21116032×
            .map(|(n, _)| *n)
21126032×
    }
2113
2114
    /// A dead directory last placed at (`parent`, `name`) in the base.
211513×
    fn revivable_dir(
211613×
        &mut self,
211713×
        parent: NodeId,
211813×
        name: &str,
211913×
    ) -> Option<(NodeId, crate::tree::OpKey)> {
212013×
        let base = self.base;
212113×
        self.dead_dirs
212213×
            .get_or_insert_with(|| base.tree().dead_dirs())
212313×
            .get(&(parent, name.to_string()))
212413×
            .copied()
212513×
    }
2126
21275908×
    fn ensure_dir(&mut self, path: &str) -> NodeId {
21285908×
        if let Some(n) = self.dir_nodes.get(path) {
21295762×
            return *n;
2130146×
        }
2131146×
        let mut parent = NodeId::ROOT;
2132146×
        let mut prefix = String::new();
2133164×
        for comp in path.split('/') {
2134164×
            if !prefix.is_empty() {
213518×
                prefix.push('/');
2136146×
            }
2137164×
            prefix.push_str(comp);
2138164×
            let known = self.dir_nodes.get(&prefix).copied();
2139164×
            let revive = match known {
214012×
                Some(_) => None,
2141152×
                None if self.node_seed.is_some() => self.revivable_dir(parent, comp),
2142139×
                None => None,
2143
            };
2144164×
            parent = match (known, revive) {
214512×
                (Some(n), _) => n,
21462×
                (None, Some((node, old))) => {
2147
                    // Git has no identity for a directory: one that comes
2148
                    // back where it was is the same directory, brought back
2149
                    // with a move, so lines of history that placed files in
2150
                    // it before and after agree (oxygen#30).
21512×
                    self.tree_ops.push(TreeOp::Move {
21522×
                        node,
21532×
                        old: OpRef {
21542×
                            change: old.0,
21552×
                            index: old.1,
21562×
                        },
21572×
                        parent,
21582×
                        name: comp.to_string(),
21592×
                    });
21602×
                    self.dir_nodes.insert(prefix.clone(), node);
21612×
                    node
2162
                }
2163
                (None, None) => {
2164150×
                    let node = self.new_node(&prefix, NodeKind::Dir);
2165150×
                    self.tree_ops.push(TreeOp::AddNode {
2166150×
                        node,
2167150×
                        kind: NodeKind::Dir,
2168150×
                        mode: Mode::default(),
2169150×
                        parent,
2170150×
                        name: comp.to_string(),
2171150×
                    });
2172150×
                    self.dir_nodes.insert(prefix.clone(), node);
2173150×
                    node
2174
                }
2175
            };
2176
        }
2177146×
        parent
21785908×
    }
2179
21805882×
    fn add_path(&mut self, repo: &Repo, path: &str, e: &FsEntry) -> Result<()> {
21815882×
        let (dir, name) = split_path(path);
21825882×
        let parent = self.ensure_dir(dir);
21835882×
        let node = self.new_node(path, e.kind);
21845882×
        let opaque = self.opaque_for(path, e);
21855882×
        let nocompress = self.attrs.lookup(path).nocompress;
21865882×
        self.tree_ops.push(TreeOp::AddNode {
21875882×
            node,
21885882×
            kind: e.kind,
21895882×
            mode: Mode {
21905882×
                exec: e.exec,
21915882×
                opaque,
21925882×
            },
21935882×
            parent,
21945882×
            name: name.to_string(),
21955882×
        });
21965882×
        if opaque {
219789×
            let blob = self.blob_of(repo, path, e, nocompress)?;
219889×
            self.edits.push(Edit::Replace {
219989×
                node,
220089×
                old: None,
220189×
                new: Some(blob),
220289×
            });
22035793×
        } else if !e.content.is_empty() {
22045764×
            let content = self.stored_text(path, &e.content);
22055764×
            self.edits.push(Edit::Insert {
22065764×
                node,
22075764×
                after: crate::objects::AtomRef::Start,
22085764×
                before: crate::objects::AtomRef::End,
22095764×
                lines: crate::lines::Lines::split_shared(content),
22105764×
            });
22115764×
        }
22125882×
        self.statuses.push(PathStatus {
22135882×
            path: path.to_string(),
22145882×
            status: ChangeStatus::Added,
22155882×
        });
22165882×
        Ok(())
22175882×
    }
2218
2219
    /// Move the node at `old` to `new` and apply `e`'s content to it.
222026×
    fn move_path(
222126×
        &mut self,
222226×
        repo: &Repo,
222326×
        old: &str,
222426×
        new: &str,
222526×
        e: &FsEntry,
222626×
        expected: &crate::state::FileState,
222726×
    ) -> Result<()> {
222826×
        let entry = &self.base_snapshot.tree.entries[old];
222926×
        let (dir, name) = split_path(new);
223026×
        let parent = self.ensure_dir(dir);
223126×
        self.tree_ops.push(TreeOp::Move {
223226×
            node: expected.node,
223326×
            old: op_ref(entry.placement),
223426×
            parent,
223526×
            name: name.to_string(),
223626×
        });
223726×
        self.update_path(repo, old, e, expected)?;
2238
        // update_path reports under the old path; the rename is what the user sees.
223926×
        self.statuses.retain(|s| s.path != old);
224026×
        self.statuses.push(PathStatus {
224126×
            path: new.to_string(),
224226×
            status: ChangeStatus::Renamed,
224326×
        });
224426×
        Ok(())
224526×
    }
2246
2247
    /// For a Git import: a node the commit keeps is in one place, the one
2248
    /// its tree names, so any other live placement it has in the base goes;
2249
    /// and a node the tree cannot show at all (an orphan) goes too. Such a
2250
    /// placement is out of sight, under a directory another line of history
2251
    /// removed, where no diff of the tree would ever reach it (oxygen#30).
225280×
    fn retire_stray_placements(&mut self) {
225380×
        let mut retired: HashSet<(ChangeHash, u32)> = HashSet::new();
225480×
        let mut placed: BTreeSet<NodeId> = BTreeSet::new();
225585×
        for op in &self.tree_ops {
225685×
            match op {
225716×
                TreeOp::Move { node, old, .. } => {
225816×
                    retired.insert((old.change, old.index));
225916×
                    placed.insert(*node);
226016×
                }
226116×
                TreeOp::RemoveNode { placement, .. } => {
226216×
                    retired.insert((placement.change, placement.index));
226316×
                }
226453×
                TreeOp::AddNode { .. } | TreeOp::SetMode { .. } => {}
2265
            }
2266
        }
2267
        // Nodes kept where they were: what the base's tree view shows and
2268
        // this change neither moves nor removes.
226980×
        let mut kept: HashMap<NodeId, (ChangeHash, u32)> = HashMap::new();
2270223×
        for e in self.base_snapshot.tree.entries.values() {
2271223×
            if !retired.contains(&e.placement) {
2272193×
                kept.insert(e.node, e.placement);
2273193×
            }
2274
        }
2275
        // Only a node with several live placements can have a stray one,
2276
        // and the tree view names each as a conflict.
227780×
        let multi: BTreeSet<NodeId> = self
227880×
            .base_snapshot
227980×
            .tree
228080×
            .conflicts
228180×
            .iter()
228280×
            .filter_map(|c| match c {
22831×
                crate::tree::TreeConflict::MultiPlacement { node, .. } => Some(*node),
22846×
                _ => None,
22857×
            })
228680×
            .collect();
228780×
        let mut extra = Vec::new();
2288
        // A node whose only placements are under a directory another line
2289
        // removed (an orphan) is nowhere the tree can show, and Git's tree
2290
        // has no such path: it goes.
229180×
        for c in &self.base_snapshot.tree.conflicts {
22927×
            let crate::tree::TreeConflict::Orphan { node, .. } = c else {
22936×
                continue;
2294
            };
22951×
            if kept.contains_key(node) || placed.contains(node) {
22960×
                continue;
22971×
            }
22981×
            for (k, _) in self.base.tree().live_placements(node) {
22991×
                if retired.insert(k) {
23001×
                    extra.push(TreeOp::RemoveNode {
23011×
                        node: *node,
23021×
                        placement: op_ref(k),
23031×
                    });
23041×
                }
2305
            }
2306
        }
230780×
        for node in placed
230880×
            .iter()
230980×
            .chain(multi.iter().filter(|n| kept.contains_key(*n)))
2310
        {
231116×
            for (k, _) in self.base.tree().live_placements(node) {
231215×
                if retired.contains(&k) || kept.get(node) == Some(&k) {
231314×
                    continue;
23141×
                }
23151×
                retired.insert(k);
23161×
                extra.push(TreeOp::RemoveNode {
23171×
                    node: *node,
23181×
                    placement: op_ref(k),
23191×
                });
2320
            }
2321
        }
232280×
        if !extra.is_empty() {
23232×
            self.resolves = true;
23242×
            self.tree_ops.extend(extra);
232578×
        }
232680×
    }
2327
2328129×
    fn remove_path(&mut self, path: &str, expected: &crate::state::FileState) {
2329129×
        let entry = &self.base_snapshot.tree.entries[path];
2330129×
        self.tree_ops.push(TreeOp::RemoveNode {
2331129×
            node: expected.node,
2332129×
            placement: op_ref(entry.placement),
2333129×
        });
2334129×
        if path.contains(".oxy-conflict-") || expected.is_conflicted() {
23357×
            self.resolves = true;
2336122×
        }
2337129×
        self.statuses.push(PathStatus {
2338129×
            path: path.to_string(),
2339129×
            status: ChangeStatus::Removed,
2340129×
        });
2341129×
    }
2342
234312606×
    fn update_path(
234412606×
        &mut self,
234512606×
        repo: &Repo,
234612606×
        path: &str,
234712606×
        e: &FsEntry,
234812606×
        expected: &crate::state::FileState,
234912606×
    ) -> Result<()> {
235012606×
        if expected.kind != e.kind {
23511×
            self.remove_path(path, expected);
23521×
            self.statuses.pop();
23531×
            self.add_path(repo, path, e)?;
23541×
            self.statuses.pop();
23551×
            self.statuses.push(PathStatus {
23561×
                path: path.to_string(),
23571×
                status: ChangeStatus::Modified,
23581×
            });
23591×
            return Ok(());
236012605×
        }
236112605×
        let entry = &self.base_snapshot.tree.entries[path];
236212605×
        let node = expected.node;
236312605×
        let mode_atom = entry.mode_atom.map(op_ref);
236412605×
        if e.unchanged {
2365
            // Known equal to the base's unconflicted rendering (spec
2366
            // §12.3); only the executable bit can differ.
23674278×
            if e.exec != expected.mode.exec {
23683×
                if let Some(old) = mode_atom {
23693×
                    self.tree_ops.push(TreeOp::SetMode {
23703×
                        node,
23713×
                        old,
23723×
                        mode: Mode {
23733×
                            exec: e.exec,
23743×
                            opaque: false,
23753×
                        },
23763×
                    });
23773×
                    self.statuses.push(PathStatus {
23783×
                        path: path.to_string(),
23793×
                        status: ChangeStatus::ModeChanged,
23803×
                    });
23813×
                }
23824275×
            }
23834278×
            return Ok(());
23848327×
        }
23858327×
        let mut status: Option<ChangeStatus> = None;
23868327×
        let wants_opaque = self.opaque_for(path, e);
23878327×
        let nocompress = self.attrs.lookup(path).nocompress;
23888327×
        let disk_text = self.stored_text(path, &e.content);
23898327×
        match &expected.content {
23900×
            FileContent::Dir => {}
2391
            FileContent::Text {
23928107×
                bytes,
23938107×
                materialized,
2394
            } => {
23958107×
                if materialized.is_conflicted() {
239633×
                    if bytes == &*disk_text {
23976×
                        return Ok(());
239827×
                    }
239927×
                    if has_conflict_markers(&e.content) {
24004×
                        self.statuses.push(PathStatus {
24014×
                            path: path.to_string(),
24024×
                            status: ChangeStatus::ConflictEdited,
24034×
                        });
24044×
                        return Ok(());
240523×
                    }
2406
                    // Resolution (spec §9.6): diff against the unconflicted lines
2407
                    // with each region as a gap, then retire every region atom.
2408
                    // Whatever the author kept from a region is re-inserted as
2409
                    // new atoms, which leaves the graph totally ordered.
241023×
                    let regions = self.base.conflict_regions(&node);
241123×
                    let mut edits = text_edits(node, &regions.plain, &disk_text);
241223×
                    if !regions.region_atoms.is_empty() {
241323×
                        edits.insert(
241423×
                            0,
241523×
                            Edit::Delete {
241623×
                                node,
241723×
                                atoms: ranges(&regions.region_atoms),
241823×
                            },
241923×
                        );
242023×
                    }
242123×
                    self.edits.extend(edits);
242223×
                    self.contributors.extend(regions.contributors);
242323×
                    self.resolves = true;
242423×
                    if e.exec != expected.mode.exec {
24250×
                        if let Some(old) = mode_atom {
24260×
                            self.tree_ops.push(TreeOp::SetMode {
24270×
                                node,
24280×
                                old,
24290×
                                mode: Mode {
24300×
                                    exec: e.exec,
24310×
                                    opaque: false,
24320×
                                },
24330×
                            });
24340×
                        }
243523×
                    }
243623×
                    self.statuses.push(PathStatus {
243723×
                        path: path.to_string(),
243823×
                        status: ChangeStatus::Resolved,
243923×
                    });
244023×
                    return Ok(());
24418074×
                }
24428074×
                if wants_opaque {
2443
                    // Text → opaque (spec §7.5), by content or by attribute.
24442×
                    if let Some(old) = mode_atom {
24452×
                        self.tree_ops.push(TreeOp::SetMode {
24462×
                            node,
24472×
                            old,
24482×
                            mode: Mode {
24492×
                                exec: e.exec,
24502×
                                opaque: true,
24512×
                            },
24522×
                        });
24532×
                    }
24542×
                    let live: Vec<_> = repo_live_keys(self.base, &node);
24552×
                    if !live.is_empty() {
24562×
                        self.edits.push(Edit::Delete {
24572×
                            node,
24582×
                            atoms: ranges(&live),
24592×
                        });
24602×
                    }
24612×
                    let blob = self.blob_of(repo, path, e, nocompress)?;
24622×
                    self.edits.push(Edit::Replace {
24632×
                        node,
24642×
                        old: None,
24652×
                        new: Some(blob),
24662×
                    });
24672×
                    status = Some(ChangeStatus::Modified);
24688072×
                } else if bytes != &*disk_text {
2469746×
                    let mut laps = crate::timing::Laps::start();
2470
                    // The base's rendering holds its live atoms in order,
2471
                    // one per line (it is not conflicted here).
2472746×
                    let edits = match self.diffs.remove(path) {
247380×
                        Some(edits) => edits,
2474
                        None => {
2475666×
                            let keys = materialized.live_atoms();
2476666×
                            let lines = crate::diff::split_lines(bytes);
2477666×
                            if keys.len() == lines.len() {
2478666×
                                crate::diff::text_edits_of(node, &keys, &lines, &disk_text)
2479
                            } else {
24800×
                                text_edits(node, &self.base.live_lines(&node), &disk_text)
2481
                            }
2482
                        }
2483
                    };
2484746×
                    laps.lap("build: text diff");
2485746×
                    if !edits.is_empty() {
2486746×
                        self.edits.extend(edits);
2487746×
                        status = Some(ChangeStatus::Modified);
2488746×
                    }
24897326×
                }
24908074×
                let switched_to_opaque = wants_opaque;
24918074×
                if !switched_to_opaque && e.exec != expected.mode.exec {
24924×
                    if let Some(old) = mode_atom {
24934×
                        self.tree_ops.push(TreeOp::SetMode {
24944×
                            node,
24954×
                            old,
24964×
                            mode: Mode {
24974×
                                exec: e.exec,
24984×
                                opaque: false,
24994×
                            },
25004×
                        });
25014×
                        status.get_or_insert(ChangeStatus::ModeChanged);
25024×
                    }
25038070×
                }
2504
            }
2505220×
            FileContent::Opaque { blobs } => {
2506220×
                let new_ref = e.blob.unwrap_or_else(|| Repo::blob_ref(&e.content));
2507220×
                if e.kind == NodeKind::File && wants_opaque {
2508188×
                    // Unchanged or replaced, the file stays opaque: remember its blob.
2509188×
                    self.blobs.insert(path.to_string(), new_ref);
2510188×
                }
2511220×
                if blobs.len() > 1 && self.resolve.contains(path) && e.kind == expected.kind {
2512
                    // Settle the replace conflict (spec §9.3): replace every
2513
                    // live candidate with the chosen blob, depending on each
2514
                    // change that made one live, so all are superseded.
25152×
                    let chosen = self.blob_of(repo, path, e, nocompress)?;
25164×
                    for b in blobs {
25174×
                        self.edits.push(Edit::Replace {
25184×
                            node,
25194×
                            old: Some(*b),
25204×
                            new: Some(chosen),
25214×
                        });
25224×
                    }
25232×
                    self.contributors
25242×
                        .extend(self.base.blob_contributors(&node, blobs));
25252×
                    self.resolves = true;
25262×
                    self.statuses.push(PathStatus {
25272×
                        path: path.to_string(),
25282×
                        status: ChangeStatus::Resolved,
25292×
                    });
25302×
                    return Ok(());
2531218×
                }
2532218×
                if blobs.len() > 1 {
25332×
                    if !blobs.contains(&new_ref) {
25340×
                        self.statuses.push(PathStatus {
25350×
                            path: path.to_string(),
25360×
                            status: ChangeStatus::ConflictEdited,
25370×
                        });
25382×
                    }
25392×
                    return Ok(());
2540216×
                }
2541216×
                let current = blobs.first().copied();
2542216×
                if current != Some(new_ref) {
254331×
                    if e.kind == NodeKind::File && !wants_opaque {
2544
                        // Opaque → text (spec §7.5).
25452×
                        if let Some(old) = mode_atom {
25462×
                            self.tree_ops.push(TreeOp::SetMode {
25472×
                                node,
25482×
                                old,
25492×
                                mode: Mode {
25502×
                                    exec: e.exec,
25512×
                                    opaque: false,
25522×
                                },
25532×
                            });
25542×
                        }
25552×
                        self.edits.push(Edit::Replace {
25562×
                            node,
25572×
                            old: current,
25582×
                            new: None,
25592×
                        });
25602×
                        if !e.content.is_empty() {
25612×
                            self.edits.push(Edit::Insert {
25622×
                                node,
25632×
                                after: crate::objects::AtomRef::Start,
25642×
                                before: crate::objects::AtomRef::End,
25652×
                                lines: crate::lines::Lines::split(&e.content),
25662×
                            });
25672×
                        }
2568
                    } else {
256929×
                        let blob = self.blob_of(repo, path, e, nocompress)?;
257029×
                        self.edits.push(Edit::Replace {
257129×
                            node,
257229×
                            old: current,
257329×
                            new: Some(blob),
257429×
                        });
2575
                    }
257631×
                    status = Some(ChangeStatus::Modified);
2577185×
                } else if e.kind == NodeKind::File && e.exec != expected.mode.exec {
25780×
                    if let Some(old) = mode_atom {
25790×
                        self.tree_ops.push(TreeOp::SetMode {
25800×
                            node,
25810×
                            old,
25820×
                            mode: Mode {
25830×
                                exec: e.exec,
25840×
                                opaque: true,
25850×
                            },
25860×
                        });
25870×
                        status = Some(ChangeStatus::ModeChanged);
25880×
                    }
2589185×
                }
2590
            }
2591
        }
25928290×
        if let Some(s) = status {
2593783×
            self.statuses.push(PathStatus {
2594783×
                path: path.to_string(),
2595783×
                status: s,
2596783×
            });
25977507×
        }
25988290×
        Ok(())
259912606×
    }
2600
}
2601
26022×
fn repo_live_keys(base: &State, node: &NodeId) -> Vec<crate::graph::AtomKey> {
26032×
    base.live_lines(node).into_iter().map(|(k, _)| k).collect()
26042×
}
2605
2606
/// The changes a change's scope references (spec §8.1): introducers of every
2607
/// atom, placement, and mode it touches, and of every node it operates on.
26081916×
pub fn referenced_changes(change: &Change, base: &State) -> BTreeSet<ChangeHash> {
26091916×
    let mut out = BTreeSet::new();
26101916×
    let opref = |r: &OpRef, out: &mut BTreeSet<ChangeHash>| {
2611194×
        if !r.change.is_zero() {
2612194×
            out.insert(r.change);
2613194×
        }
2614194×
    };
26151916×
    let mut nodes: Vec<NodeId> = Vec::new();
26166432×
    for op in &change.tree_ops {
26176432×
        match op {
26186238×
            TreeOp::AddNode { parent, .. } => nodes.push(*parent),
2619156×
            TreeOp::RemoveNode { node, placement } => {
2620156×
                nodes.push(*node);
2621156×
                opref(placement, &mut out);
2622156×
            }
2623
            TreeOp::Move {
262428×
                node, old, parent, ..
262528×
            } => {
262628×
                nodes.push(*node);
262728×
                nodes.push(*parent);
262828×
                opref(old, &mut out);
262928×
            }
263010×
            TreeOp::SetMode { node, old, .. } => {
263110×
                nodes.push(*node);
263210×
                opref(old, &mut out);
263310×
            }
2634
        }
2635
    }
26367936×
    for e in &change.edits {
26377936×
        nodes.push(e.node());
2638124×
        match e {
26397288×
            Edit::Insert { after, before, .. } => {
264014576×
                for r in [after, before] {
264114576×
                    if let crate::objects::AtomRef::Atom { change, .. } = r {
26422169×
                        if !change.is_zero() {
26432167×
                            out.insert(*change);
26442167×
                        }
264512407×
                    }
2646
                }
2647
            }
2648524×
            Edit::Delete { atoms, .. } => {
2649
                // Deleting an atom also depends on whoever inserted the live
2650
                // atoms right after it: the author saw those insertions, and
2651
                // without the dependency spec §9.1 would call the deletion
2652
                // concurrent with them (a delete/insert conflict).
2653524×
                let graph = base.file(&e.node());
26541081×
                for r in atoms {
26551081×
                    if !r.change.is_zero() {
26561080×
                        out.insert(r.change);
26571080×
                    }
26581081×
                    if let Some(g) = graph {
26591120×
                        for i in r.from..r.to {
26601120×
                            out.extend(
26611120×
                                g.live_successor_changes(&(r.change, i))
26621120×
                                    .into_iter()
26631120×
                                    .filter(|c| !c.is_zero()),
2664
                            );
2665
                        }
26660×
                    }
2667
                }
2668
            }
2669
            // Replacing a blob depends on the change that made it current,
2670
            // as deleting a line depends on the line's introducer.
2671
            Edit::Replace {
267236×
                node,
267336×
                old: Some(old),
2674
                ..
2675
            } => {
267636×
                out.extend(
267736×
                    base.live_replaces(node)
267836×
                        .into_iter()
267943×
                        .filter(|(c, b)| b == old && !c.is_zero())
268036×
                        .map(|(c, _)| c),
2681
                );
2682
            }
268388×
            Edit::Replace { .. } => {}
2684
        }
2685
    }
268614396×
    for n in nodes {
268714396×
        if let Some(h) = base.tree().introducer(&n) {
26882147×
            out.insert(h);
268912249×
        }
2690
    }
26911916×
    out
26921916×
}
2693
2694
/// Paths of the nodes a change adds on top of `base_snapshot`.
26951200×
pub fn added_node_paths(
26961200×
    change: &Change,
26971200×
    base_snapshot: &Snapshot,
26981200×
) -> HashMap<String, (NodeId, NodeKind)> {
26991200×
    let by_node = base_snapshot.tree.by_node();
27001200×
    let mut new_names: HashMap<NodeId, (NodeId, String, NodeKind)> = HashMap::new();
27011200×
    for op in &change.tree_ops {
2702
        if let TreeOp::AddNode {
270367×
            node,
270467×
            parent,
270567×
            name,
270667×
            kind,
2707
            ..
270889×
        } = op
270967×
        {
271067×
            new_names.insert(*node, (*parent, name.clone(), *kind));
271167×
        }
2712
    }
27131200×
    let mut out = HashMap::new();
27141200×
    for (node, (_, _, kind)) in &new_names {
271567×
        if let Some(path) = path_of_node(node, &by_node, &new_names) {
271667×
            out.insert(path, (*node, *kind));
271767×
        }
2718
    }
27191200×
    out
27201200×
}
2721
2722170×
fn path_of_node(
2723170×
    n: &NodeId,
2724170×
    by_node: &HashMap<NodeId, &crate::tree::TreeEntry>,
2725170×
    new_names: &HashMap<NodeId, (NodeId, String, NodeKind)>,
2726170×
) -> Option<String> {
2727170×
    if let Some(e) = by_node.get(n) {
272851×
        return Some(e.path.clone());
2729119×
    }
2730119×
    let mut parts = Vec::new();
2731119×
    let mut cur = *n;
2732
    loop {
2733237×
        if cur.is_root() {
2734105×
            break;
2735132×
        }
2736132×
        if let Some(e) = by_node.get(&cur) {
27370×
            if !e.path.is_empty() {
27380×
                parts.push(e.path.clone());
27390×
            }
27400×
            break;
2741132×
        }
2742132×
        let (parent, name, _) = new_names.get(&cur)?;
2743118×
        parts.push(name.clone());
2744118×
        cur = *parent;
2745
    }
2746105×
    parts.reverse();
2747105×
    Some(parts.join("/"))
2748170×
}
2749
2750
/// Render a change's operations with line content, using `base` for deleted lines.
275128×
pub fn render_change(change: &Change, base: &State, base_snapshot: &Snapshot) -> String {
275228×
    let by_node = base_snapshot.tree.by_node();
275328×
    let mut new_names: HashMap<NodeId, (NodeId, String, NodeKind)> = HashMap::new();
275428×
    for op in &change.tree_ops {
2755
        if let TreeOp::AddNode {
275615×
            node,
275715×
            parent,
275815×
            name,
275915×
            kind,
2760
            ..
276122×
        } = op
276215×
        {
276315×
            new_names.insert(*node, (*parent, name.clone(), *kind));
276415×
        }
2765
    }
276666×
    let path_of = |n: &NodeId| -> String {
276766×
        path_of_node(n, &by_node, &new_names).unwrap_or_else(|| format!("<node {}>", n.short(8)))
276866×
    };
2769
277028×
    let mut out = String::new();
277128×
    for op in &change.tree_ops {
277222×
        match op {
2773
            TreeOp::AddNode {
277415×
                node, kind, mode, ..
2775
            } => {
277615×
                out.push_str(&format!(
2777
                    "A {} ({:?}{}{})\n",
277815×
                    path_of(node),
2779
                    kind,
278015×
                    if mode.exec { ", exec" } else { "" },
278115×
                    if mode.opaque { ", opaque" } else { "" }
2782
                ));
2783
            }
27845×
            TreeOp::RemoveNode { node, .. } => out.push_str(&format!("D {}\n", path_of(node))),
2785
            TreeOp::Move {
27862×
                node, parent, name, ..
2787
            } => {
27882×
                let to = if parent.is_root() {
27890×
                    name.clone()
2790
                } else {
27912×
                    format!("{}/{name}", path_of(parent))
2792
                };
27932×
                out.push_str(&format!("R {} -> {to}\n", path_of(node)))
2794
            }
27950×
            TreeOp::SetMode { node, mode, .. } => {
27960×
                out.push_str(&format!(
27970×
                    "M {} mode: exec={} opaque={}\n",
27980×
                    path_of(node),
27990×
                    mode.exec,
28000×
                    mode.opaque
28010×
                ));
28020×
            }
2803
        }
2804
    }
2805
    // Every other file the change edits is modified: the summary names
2806
    // every path it touches, not only those with a tree operation.
280728×
    let with_op: HashSet<NodeId> = change.tree_ops.iter().map(|o| o.node()).collect();
280828×
    let mut listed: HashSet<NodeId> = HashSet::new();
280932×
    for e in &change.edits {
281032×
        let n = e.node();
281132×
        if !with_op.contains(&n) && listed.insert(n) {
281218×
            out.push_str(&format!("M {}\n", path_of(&n)));
281318×
        }
2814
    }
281528×
    let mut last_node: Option<NodeId> = None;
281632×
    for e in &change.edits {
281732×
        let n = e.node();
281832×
        if last_node != Some(n) {
281924×
            out.push_str(&format!("--- {}\n", path_of(&n)));
282024×
            last_node = Some(n);
282124×
        }
282232×
        match e {
282324×
            Edit::Insert { lines, .. } => {
282429×
                for l in lines.iter() {
282529×
                    out.push('+');
282629×
                    out.push_str(&String::from_utf8_lossy(l));
282729×
                    if !l.ends_with(b"\n") {
28280×
                        out.push('\n');
282929×
                    }
2830
                }
2831
            }
28327×
            Edit::Delete { atoms, .. } => {
28337×
                for r in atoms {
28347×
                    for i in r.from..r.to {
28357×
                        let content = base
28367×
                            .file(&n)
28377×
                            .and_then(|g| g.content(&(r.change, i)))
28387×
                            .unwrap_or(b"<unknown>\n");
28397×
                        out.push('-');
28407×
                        out.push_str(&String::from_utf8_lossy(content));
28417×
                        if !content.ends_with(b"\n") {
28420×
                            out.push('\n');
28437×
                        }
2844
                    }
2845
                }
2846
            }
28471×
            Edit::Replace { old, new, .. } => {
28481×
                out.push_str(&format!(
2849
                    "  opaque content {} -> {}\n",
28501×
                    old.map(|o| o.short(12)).unwrap_or_else(|| "none".into()),
28511×
                    new.map(|o| o.short(12)).unwrap_or_else(|| "none".into())
2852
                ));
2853
            }
2854
        }
2855
    }
285628×
    out
285728×
}
2858
2859
/// Pair removed files with added files of the same kind whose contents are
2860
/// at least `RENAME_THRESHOLD` percent alike, best matches first. Beyond
2861
/// `RENAME_LIMIT` candidate pairs only identical contents are paired.
2862
const RENAME_THRESHOLD: u32 = 50;
2863
const RENAME_LIMIT: usize = 10_000;
2864
2865
/// How a change is built beyond its entries: for a Git import, the seed
2866
/// its new nodes' identifiers derive from; and, when it is built from part
2867
/// of the tree, whether the new tree has anything under a directory.
2868
#[derive(Default)]
2869
struct Scope<'a> {
2870
    seed: Option<[u8; 32]>,
2871
    dir_needed: Option<&'a dyn Fn(&str) -> bool>,
2872
}
2873
28741810×
fn detect_renames(
28751810×
    base_snapshot: &Snapshot,
28761810×
    fs_entries: &BTreeMap<String, FsEntry>,
28771810×
    in_scope: impl Fn(&str) -> bool,
28781810×
) -> Vec<(String, String)> {
28791810×
    let removed: Vec<(&String, &crate::state::FileState)> = base_snapshot
28801810×
        .files
28811810×
        .iter()
288213151×
        .filter(|(p, f)| {
288313151×
            f.kind != NodeKind::Dir
288412718×
                && !fs_entries.contains_key(*p)
2885138×
                && in_scope(p)
2886128×
                && !f.is_conflicted()
288713151×
        })
28881810×
        .collect();
28891810×
    let added: Vec<(&String, &FsEntry)> = fs_entries
28901810×
        .iter()
289118487×
        .filter(|(p, e)| e.kind != NodeKind::Dir && !base_snapshot.files.contains_key(*p))
28921810×
        .collect();
28931810×
    if removed.is_empty() || added.is_empty() {
28941754×
        return vec![];
289556×
    }
289656×
    let exact_only = removed.len() * added.len() > RENAME_LIMIT;
289770×
    let old_content = |f: &crate::state::FileState| -> Option<Vec<u8>> {
289870×
        match &f.content {
289966×
            FileContent::Text { bytes, .. } => Some(bytes.clone()),
29004×
            _ => None,
2901
        }
290270×
    };
290356×
    let mut scored: Vec<(u32, usize, usize)> = Vec::new();
290470×
    for (ri, (_, f)) in removed.iter().enumerate() {
290570×
        let old = old_content(f);
290670×
        let old_blob = match &f.content {
29074×
            FileContent::Opaque { blobs } if blobs.len() == 1 => Some(blobs[0]),
290866×
            _ => None,
2909
        };
291089×
        for (ai, (_, e)) in added.iter().enumerate() {
291189×
            if e.kind != f.kind {
29120×
                continue;
291389×
            }
291489×
            let score = match (&old, old_blob) {
291579×
                (Some(o), _) => {
291679×
                    if exact_only {
29170×
                        if *o == *e.content {
29180×
                            100
2919
                        } else {
29200×
                            0
2921
                        }
2922
                    } else {
292379×
                        similarity(o, &e.content)
2924
                    }
2925
                }
292610×
                (None, Some(b)) if e.blob.unwrap_or_else(|| Repo::blob_ref(&e.content)) == b => 100,
29277×
                _ => 0,
2928
            };
292989×
            if score >= RENAME_THRESHOLD {
293032×
                scored.push((score, ri, ai));
293157×
            }
2932
        }
2933
    }
293456×
    scored.sort_by(|a, b| {
29359×
        b.0.cmp(&a.0)
29369×
            .then(removed[a.1].0.cmp(removed[b.1].0))
29379×
            .then(added[a.2].0.cmp(added[b.2].0))
29389×
    });
293956×
    let mut used_r = vec![false; removed.len()];
294056×
    let mut used_a = vec![false; added.len()];
294156×
    let mut out = Vec::new();
294256×
    for (_, ri, ai) in scored {
294332×
        if used_r[ri] || used_a[ai] {
29446×
            continue;
294526×
        }
294626×
        used_r[ri] = true;
294726×
        used_a[ai] = true;
294826×
        out.push((removed[ri].0.clone(), added[ai].0.clone()));
2949
    }
295056×
    out
29511810×
}
2952
2953
/// Percentage of the larger file's bytes found in lines the two share
2954
/// (multiset intersection of lines), like Git's similarity index.
295583×
pub fn similarity(a: &[u8], b: &[u8]) -> u32 {
295683×
    if a == b {
295719×
        return 100;
295864×
    }
295964×
    if a.is_empty() || b.is_empty() {
29606×
        return 0;
296158×
    }
296258×
    let mut counts: HashMap<&[u8], usize> = HashMap::new();
2963121×
    for l in split_lines(a) {
2964121×
        *counts.entry(l).or_default() += 1;
2965121×
    }
296658×
    let mut shared = 0usize;
2967107×
    for l in split_lines(b) {
2968107×
        if let Some(n) = counts.get_mut(l) {
296941×
            if *n > 0 {
297041×
                *n -= 1;
297141×
                shared += l.len();
297241×
            }
297366×
        }
2974
    }
297558×
    (shared * 100 / a.len().max(b.len())) as u32
297683×
}
2977
2978
#[cfg(test)]
2979
mod join_tests {
2980
    use super::*;
2981
2982
    #[test]
29831×
    fn missing_from_finds_what_the_other_lacks() {
29841×
        let a: BTreeMap<String, u8> = [("a", 1), ("b", 2), ("c/d", 3), ("e", 4)]
29851×
            .into_iter()
29864×
            .map(|(k, v)| (k.to_string(), v))
29871×
            .collect();
29881×
        let b: BTreeMap<String, ()> = [("0", ()), ("b", ()), ("c", ()), ("e", ())]
29891×
            .into_iter()
29904×
            .map(|(k, v)| (k.to_string(), v))
29911×
            .collect();
29921×
        let got: Vec<&str> = missing_from(&a, &b)
29931×
            .iter()
29942×
            .map(|(k, _)| k.as_str())
29951×
            .collect();
29961×
        assert_eq!(got, vec!["a", "c/d"]);
29971×
    }
2998
2999
    #[test]
30001×
    fn join_pairs_every_key_in_order() {
30011×
        let a: BTreeMap<String, u8> = [("a", 1), ("b/c", 2), ("d", 3)]
30021×
            .into_iter()
30033×
            .map(|(k, v)| (k.to_string(), v))
30041×
            .collect();
30051×
        let b: BTreeMap<String, char> = [("b", 'x'), ("b/c", 'y'), ("e", 'z')]
30061×
            .into_iter()
30073×
            .map(|(k, v)| (k.to_string(), v))
30081×
            .collect();
30091×
        let got: Vec<(String, Option<u8>, Option<char>)> = join(&a, &b)
30105×
            .map(|(k, x, y)| (k.clone(), x.copied(), y.copied()))
30111×
            .collect();
30121×
        let want = vec![
30131×
            ("a".to_string(), Some(1), None),
30141×
            ("b".to_string(), None, Some('x')),
30151×
            ("b/c".to_string(), Some(2), Some('y')),
30161×
            ("d".to_string(), Some(3), None),
30171×
            ("e".to_string(), None, Some('z')),
3018
        ];
30191×
        assert_eq!(got, want);
30201×
    }
3021
}