OXYGENHUB

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

2193 of 2424 lines run, 282 of 371 functions · run #263 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
8122581×
pub fn is_binary(content: &[u8]) -> bool {
8222581×
    content[..content.len().min(BINARY_SNIFF)].contains(&0)
8322581×
}
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.
1051225×
    fn platform_normalize(&self, entries: &mut BTreeMap<String, FsEntry>, base: &Snapshot) {
1061225×
        let p = self.platform;
1071225×
        if p.exec_bits && p.symlinks {
1081223×
            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
        }
1221225×
    }
123
124
    /// Like `build_against`, for files given in memory (imports).
125956×
    pub(crate) fn build_from_entries(
126956×
        &self,
127956×
        base: &State,
128956×
        base_snapshot: &Snapshot,
129956×
        reuse: HashMap<String, (NodeId, NodeKind)>,
130956×
        fs_entries: &BTreeMap<String, FsEntry>,
131956×
    ) -> Result<BuiltChange> {
132956×
        self.build_from_entries_resolving(base, base_snapshot, reuse, fs_entries, &HashSet::new())
133956×
    }
134
135
    /// Like `build_from_entries`, settling the replace conflicts of the
136
    /// opaque files in `resolve` to their content (spec §9.3, §9.6): a
137
    /// caller that knows the user chose it, such as the hub's resolver. A
138
    /// snapshot never settles one on its own, since a checkout writes one
139
    /// candidate at the path.
140970×
    pub(crate) fn build_from_entries_resolving(
141970×
        &self,
142970×
        base: &State,
143970×
        base_snapshot: &Snapshot,
144970×
        reuse: HashMap<String, (NodeId, NodeKind)>,
145970×
        fs_entries: &BTreeMap<String, FsEntry>,
146970×
        resolve: &HashSet<String>,
147970×
    ) -> Result<BuiltChange> {
148970×
        self.build_from_entries_with(
149970×
            base,
150970×
            base_snapshot,
151970×
            reuse,
152970×
            fs_entries,
153970×
            resolve,
154970×
            Scope::default(),
155
        )
156970×
    }
157
158
    /// `build_from_entries` whose new nodes take identifiers derived from
159
    /// `seed` and their paths instead of random ones, so the same input
160
    /// always builds the same change (a Git import, spec §23).
161
    ///
162
    /// With `dir_needed`, the snapshot and entries hold only the paths the
163
    /// import touches (and the directories a removal may leave empty); a
164
    /// directory stays while `dir_needed` says the new tree has something
165
    /// under it.
16686×
    pub(crate) fn build_from_entries_seeded(
16786×
        &self,
16886×
        base: &State,
16986×
        base_snapshot: &Snapshot,
17086×
        fs_entries: &BTreeMap<String, FsEntry>,
17186×
        seed: [u8; 32],
17286×
        dir_needed: Option<&dyn Fn(&str) -> bool>,
17386×
    ) -> Result<BuiltChange> {
17486×
        self.build_from_entries_with(
17586×
            base,
17686×
            base_snapshot,
17786×
            HashMap::new(),
17886×
            fs_entries,
17986×
            &HashSet::new(),
18086×
            Scope {
18186×
                seed: Some(seed),
18286×
                dir_needed,
18386×
            },
184
        )
18586×
    }
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.
192807×
    fn build_changed_only(
193807×
        &self,
194807×
        base: &State,
195807×
        base_snapshot: &Snapshot,
196807×
        reuse: HashMap<String, (NodeId, NodeKind)>,
197807×
        fs_entries: &BTreeMap<String, FsEntry>,
198807×
    ) -> Result<BuiltChange> {
199807×
        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.
202807×
        let changed: BTreeMap<String, FsEntry> = join(fs_entries, &base_snapshot.files)
20310949×
            .filter_map(|(p, e, f)| {
20410949×
                let e = e?;
20510824×
                (!e.unchanged || f.is_none_or(|f| f.kind != e.kind || f.mode.exec != e.exec))
20610824×
                    .then(|| (p.clone(), e.clone()))
20710949×
            })
208807×
            .collect();
209807×
        let mut files: BTreeMap<String, crate::state::FileState> = BTreeMap::new();
2106595×
        for p in changed.keys() {
2116595×
            if let Some(f) = base_snapshot.files.get(p) {
2123635×
                files.insert(p.clone(), f.clone());
2133635×
            }
214
        }
215
        // Paths the base has and the disk does not.
216807×
        let gone = join(&base_snapshot.files, fs_entries)
21710949×
            .filter_map(|(p, f, e)| (e.is_none()).then_some((p, f?)));
218807×
        for (p, f) in gone {
219125×
            if f.kind == NodeKind::Dir {
22096×
                continue;
22129×
            }
22229×
            files.insert(p.clone(), f.clone());
22329×
            let mut end = p.len();
22434×
            while let Some(i) = p[..end].rfind('/') {
2255×
                let dir = &p[..i];
2265×
                if files.contains_key(dir) {
2270×
                    break;
2285×
                }
2295×
                if let Some(d) = base_snapshot.files.get(dir) {
2305×
                    files.insert(dir.to_string(), d.clone());
2315×
                }
2325×
                end = i;
233
            }
234
        }
235807×
        let part = Snapshot {
236807×
            tree: base_snapshot.tree.clone(),
237807×
            files,
238807×
            unrendered: BTreeSet::new(),
239807×
        };
240807×
        drop(pick);
241807×
        let _build = crate::timing::phase("snapshot:   of which building the change");
242
        // Whether anything on disk is under `dir`.
243807×
        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×
        };
250807×
        self.build_from_entries_with(
251807×
            base,
252807×
            &part,
253807×
            reuse,
254807×
            &changed,
255807×
            &HashSet::new(),
256807×
            Scope {
257807×
                seed: None,
258807×
                dir_needed: Some(&dir_needed),
259807×
            },
260
        )
261807×
    }
262
2631863×
    fn build_from_entries_with(
2641863×
        &self,
2651863×
        base: &State,
2661863×
        base_snapshot: &Snapshot,
2671863×
        reuse: HashMap<String, (NodeId, NodeKind)>,
2681863×
        fs_entries: &BTreeMap<String, FsEntry>,
2691863×
        resolve: &HashSet<String>,
2701863×
        scope: Scope,
2711863×
    ) -> Result<BuiltChange> {
2721863×
        let Scope { seed, dir_needed } = scope;
2731863×
        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.
2761863×
        let attrs = crate::attributes::Attributes::from_files(
2771863×
            fs_entries
2781863×
                .iter()
27918563×
                .filter(|(p, _)| p.as_str() == ".oxyattributes" || p.ends_with("/.oxyattributes"))
2801863×
                .map(|(p, e)| (p.as_str(), e.content.as_slice())),
281
        );
2821863×
        let mut b = ChangeBuilder::new(base, base_snapshot, reuse).with_attributes(attrs);
2831863×
        b.resolve = resolve.clone();
2841863×
        b.node_seed = seed;
2851863×
        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.
2891863×
        let renames = detect_renames(base_snapshot, fs_entries, |p| self.in_scope(p));
2901863×
        let renamed_from: HashMap<&str, &str> = renames
2911863×
            .iter()
2921863×
            .map(|(old, new)| (new.as_str(), old.as_str()))
2931863×
            .collect();
2941863×
        let renamed_to: HashMap<&str, &str> = renames
2951863×
            .iter()
2961863×
            .map(|(old, new)| (old.as_str(), new.as_str()))
2971863×
            .collect();
2981863×
        laps.lap("build: renames");
2991863×
        b.diff_in_parallel(fs_entries);
3001863×
        laps.lap("build: diffs");
30118563×
        for (path, fs_entry) in fs_entries {
30218563×
            match base_snapshot.files.get(path) {
3035963×
                None => match renamed_from.get(path.as_str()) {
30432×
                    Some(old) => {
30532×
                        b.move_path(self, old, path, fs_entry, &base_snapshot.files[*old])?
306
                    }
3075931×
                    None => b.add_path(self, path, fs_entry)?,
308
                },
30912600×
                Some(expected) => b.update_path(self, path, fs_entry, expected)?,
310
            }
311
        }
3121863×
        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.
3151863×
        let mut needed_dirs: HashSet<&str> = HashSet::new();
31618576×
        fn parents_of<'a>(p: &'a str, set: &mut HashSet<&'a str>) {
31718576×
            let mut end = p.len();
31819220×
            while let Some(i) = p[..end].rfind('/') {
31915426×
                if !set.insert(&p[..i]) {
32014782×
                    break;
321644×
                }
322644×
                end = i;
323
            }
32418576×
        }
32518563×
        for p in fs_entries.keys() {
32618563×
            parents_of(p, &mut needed_dirs);
32718563×
        }
32813144×
        for p in base_snapshot.files.keys() {
32913144×
            if !self.in_scope(p) {
33013×
                parents_of(p, &mut needed_dirs);
33113131×
            }
332
        }
33313144×
        for (path, expected) in &base_snapshot.files {
33413144×
            if fs_entries.contains_key(path)
335544×
                || !self.in_scope(path)
336531×
                || renamed_to.contains_key(path.as_str())
337
            {
33812645×
                continue;
339499×
            }
340499×
            let still_needed = expected.kind == NodeKind::Dir
341408×
                && match dir_needed {
34221×
                    Some(f) => f(path),
343387×
                    None => needed_dirs.contains(path.as_str()),
344
                };
345499×
            if !still_needed {
346118×
                b.remove_path(path, expected);
347381×
            }
348
        }
3491863×
        laps.lap("build: removals");
3501863×
        if seed.is_some() {
35186×
            b.retire_stray_placements();
3521777×
        }
3531863×
        laps.lap("build: stray placements");
3541863×
        let mut statuses = b.statuses;
3555659×
        statuses.sort_by(|a, b| a.path.cmp(&b.path));
3561863×
        Ok(BuiltChange {
3571863×
            tree_ops: b.tree_ops,
3581863×
            edits: b.edits,
3591863×
            contributors: b.contributors.into_iter().collect(),
3601863×
            resolves: b.resolves,
3611863×
            statuses,
3621863×
            blobs: b.blobs,
3631863×
        })
3641863×
    }
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.
369647×
    pub(crate) fn store_signed(&self, change: &Change) -> Result<ChangeHash> {
370647×
        let ours = change.author == self.author();
371647×
        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");
373646×
        }
374646×
        let storing = crate::timing::phase("store: the change");
375646×
        let hash = self.store.put_change(change)?;
376646×
        drop(storing);
377646×
        if self.config.sign_changes && ours {
37840×
            let _t = crate::timing::phase("store: sign it");
37940×
            self.sign_change(&hash)?;
380606×
        }
381646×
        Ok(hash)
382647×
    }
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.
386416×
    pub fn snapshot(&self, command: &str) -> Result<SnapshotResult> {
387416×
        self.snapshot_as(command, false, false)
388416×
    }
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.
398391×
    pub fn snapshot_status(&self, command: &str) -> Result<SnapshotResult> {
399391×
        self.snapshot_as(command, true, false)
400391×
    }
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.
4091226×
    fn snapshot_as(
4101226×
        &self,
4111226×
        command: &str,
4121226×
        partial: bool,
4131226×
        for_commit: bool,
4141226×
    ) -> Result<SnapshotResult> {
4151226×
        let _lock = self.lock_snapshot()?;
4161226×
        let batch = self.store.begin_batch()?;
4171226×
        let result = self.snapshot_locked(command, partial, for_commit);
4181226×
        batch.finish()?;
4191226×
        result
4201226×
    }
421
4221226×
    fn snapshot_locked(
4231226×
        &self,
4241226×
        command: &str,
4251226×
        partial: bool,
4261226×
        for_commit: bool,
4271226×
    ) -> Result<SnapshotResult> {
4281226×
        let _all = crate::timing::phase("snapshot");
4291226×
        let (op_ref, op) = self.head_op()?;
4301226×
        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.
4331224×
        let mut base = {
4341224×
            let _t = crate::timing::phase("snapshot: load base history");
4351224×
            self.load_state_indexed(&old_wc.deps)?
436
        };
4371224×
        let view = {
4381224×
            let _t = crate::timing::phase("snapshot: tree view");
4391224×
            base.tree().view()
440
        };
4411224×
        let manifest = {
4421224×
            let _t = crate::timing::phase("snapshot: read manifest");
4431224×
            self.read_manifest()?.map(|(_, _, m)| m)
444
        };
4451224×
        let tracked: BTreeMap<String, (NodeKind, Option<ObjectRef>)> = {
4461224×
            let _t = crate::timing::phase("snapshot: tracked paths");
447
            // In the view's path order, so the map is built without searching.
4481224×
            view.entries
4491224×
                .iter()
4509413×
                .filter(|(_, e)| e.kind != NodeKind::Dir)
4519030×
                .map(|(p, e)| {
4529030×
                    let blob = if e.kind != NodeKind::File || e.mode.opaque {
453151×
                        base.live_blobs(&e.node).first().copied()
454
                    } else {
4558879×
                        None
456
                    };
4579030×
                    (p.clone(), (e.kind, blob))
4589030×
                })
4591224×
                .collect()
460
        };
461
        // A text file's graph key, worked out when the walk asks for it.
46212003×
        let key_of = |p: &str| -> Option<[u8; 32]> {
46312003×
            let e = view.entries.get(p)?;
4648936×
            if e.kind != NodeKind::File || e.mode.opaque {
465124×
                return None;
4668812×
            }
4678812×
            base.graph_key(&e.node)
46812003×
        };
4691223×
        let mut fs_entries = {
4701224×
            let _t = crate::timing::phase("snapshot: read working copy");
4711224×
            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.
4751223×
        let keys: HashMap<String, [u8; 32]> = fs_entries
4761223×
            .iter()
47712032×
            .filter(|(_, e)| !e.unchanged && e.kind == NodeKind::File)
4787762×
            .filter_map(|(p, _)| Some((p.clone(), key_of(p)?)))
4791223×
            .collect();
4801223×
        let base_snapshot = {
4811223×
            let _t = crate::timing::phase("snapshot: load and render base");
4821223×
            if partial {
483810×
                let sets = crate::timing::phase("snapshot:   of which choosing graphs");
484
                // Every file but those on disk known unchanged.
485810×
                let need: Vec<(&str, NodeId)> = join(&view.entries, &fs_entries)
48610964×
                    .filter_map(|(p, v, f)| {
48710964×
                        let v = v?;
4888003×
                        (v.kind == NodeKind::File && !f.is_some_and(|f| f.unchanged))
4898003×
                            .then_some((p.as_str(), v.node))
49010964×
                    })
491810×
                    .collect();
492810×
                let render: std::collections::HashSet<&str> =
493810×
                    need.iter().map(|(p, _)| *p).collect();
494810×
                let need: Vec<NodeId> = need.iter().map(|(_, n)| *n).collect();
495810×
                drop(sets);
496
                {
497810×
                    let _t = crate::timing::phase("snapshot:   of which building graphs");
498810×
                    self.load_graphs_of(&mut base, &need)?;
499
                }
500810×
                let _t = crate::timing::phase("snapshot:   of which rendering");
501810×
                base.materialize_only(&render)
502
            } else {
503413×
                self.load_all_graphs(&mut base)?;
504413×
                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).
5101223×
        let reuse = added_node_paths(&old_wc, &base_snapshot);
5111223×
        self.platform_normalize(&mut fs_entries, &base_snapshot);
5121223×
        let built = {
5131223×
            let _t = crate::timing::phase("snapshot: diff against base");
5141223×
            if partial && self.config.sparse_paths.is_empty() {
515
                #[cfg(test)]
516534×
                let full =
517534×
                    self.build_from_entries(&base, &base_snapshot, reuse.clone(), &fs_entries)?;
518807×
                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.
5231068×
                    let norm = |b: &BuiltChange| {
5241068×
                        let text = format!("{:?} {:?} {:?}", b.tree_ops, b.edits, b.statuses);
5251068×
                        let mut seen: Vec<String> = Vec::new();
5261068×
                        let mut out = String::new();
5271068×
                        let mut rest = text.as_str();
52819498×
                        while let Some(i) = rest.find("NodeId(") {
52918430×
                            out.push_str(&rest[..i]);
53018430×
                            let end = i + rest[i..].find(')').unwrap() + 1;
53118430×
                            let id = rest[i..end].to_string();
5329045710×
                            let n = seen.iter().position(|x| *x == id).unwrap_or_else(|| {
5336860×
                                seen.push(id);
5346860×
                                seen.len() - 1
5356860×
                            });
53618430×
                            out.push_str(&format!("N{n}"));
53718430×
                            rest = &rest[end..];
538
                        }
5391068×
                        out.push_str(rest);
5401068×
                        out
5411068×
                    };
542534×
                    assert_eq!(
543534×
                        norm(&built),
544534×
                        norm(&full),
545
                        "a changed-only build is the full one"
546
                    );
547
                }
548807×
                built
549
            } else {
550416×
                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
        {
5563684×
            let changed: HashSet<&str> = built.statuses.iter().map(|s| s.path.as_str()).collect();
55712032×
            for (p, e) in fs_entries.iter_mut() {
55812032×
                if e.unchanged || e.kind != NodeKind::File || changed.contains(p.as_str()) {
5597865×
                    continue;
5604167×
                }
5614167×
                e.graph_key = match base_snapshot.files.get(p).map(|f| &f.content) {
562
                    Some(FileContent::Text {
5634055×
                        bytes,
5644055×
                        materialized,
5654055×
                    }) if !materialized.is_conflicted() && *bytes == *e.content => {
5664049×
                        keys.get(p).copied()
567
                    }
568118×
                    _ => None,
569
                };
570
            }
571
        }
572
5731223×
        let mut wc = Change {
5741223×
            version: crate::objects::CHANGE_VERSION,
5751223×
            change_id: old_wc.change_id,
5761223×
            deps: vec![],
5771223×
            author: self.author(),
5781223×
            hlc: old_wc.hlc,
5791223×
            message: old_wc.message.clone(),
5801223×
            tree_ops: built.tree_ops,
5811223×
            edits: built.edits,
5821223×
            kind: ChangeKind::WorkingCopy,
5831223×
        };
5841223×
        let base_heads = base.maximal(&old_wc.deps);
5851223×
        let mut deps: BTreeSet<ChangeHash> = base_heads.into_iter().collect();
5861223×
        deps.extend(referenced_changes(&wc, &base));
5871223×
        deps.extend(built.contributors.iter().copied());
5881223×
        wc.deps = deps.into_iter().collect();
5891223×
        wc.normalize();
5901223×
        let resolves = built.resolves;
5911223×
        let contributors = built.contributors;
5921223×
        let statuses = built.statuses;
593
        // Empty snapshot: hash the candidate before storing; only record an op on change.
5941223×
        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.
6011223×
        let (new_hash, changed, encoded) = if for_commit {
602419×
            (old_hash, true, Vec::new())
603
        } else {
604804×
            let encoded = wc.encode_streaming(|batch| self.store.put_texts(&batch))?;
605804×
            let new_hash = crate::hash::hash_object(crate::hash::ObjectType::Change, &encoded);
606804×
            (new_hash, new_hash != old_hash, encoded)
607
        };
6081223×
        if changed && !for_commit {
609269×
            self.store.put(crate::hash::ObjectType::Change, &encoded)?;
610269×
            let mut view = op.view.clone();
611269×
            view.workspaces.insert(self.workspace, new_hash);
612269×
            self.record_op(&[op_ref], &format!("{command}{SNAPSHOT_SUFFIX}"), view)?;
613954×
        }
6141223×
        drop(record);
615
        // The prompt compares against this without recording anything.
6161223×
        let _t = crate::timing::phase("snapshot: write manifest");
6171223×
        let conflicted = base_snapshot.is_conflicted();
6181223×
        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.
6231223×
        let worth = match self.read_manifest()? {
624419×
            _ if for_commit => true,
625301×
            None => true,
626503×
            Some((c, u, m)) => {
627503×
                c != conflicted
628503×
                    || u != uncommitted
629289×
                    || m.entries.len() != fs_entries.len()
630370×
                    || fs_entries.iter().any(|(p, e)| {
631370×
                        !e.unchanged && (e.graph_key.is_some() || !m.entries.contains_key(p))
632370×
                    })
63345×
                    || built
63445×
                        .blobs
63545×
                        .iter()
63645×
                        .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.
64058×
                    || (uncommitted && statuses.iter().any(|st| {
64158×
                        let Some(e) = fs_entries.get(&st.path) else {
6423×
                            return m.entries.contains_key(&st.path);
643
                        };
64455×
                        let Some(me) = m.entries.get(&st.path) else {
6450×
                            return true;
646
                        };
64755×
                        let hash = e
64855×
                            .content_hash
64955×
                            .unwrap_or_else(|| *blake3::hash(&e.content).as_bytes());
65055×
                        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.
65755×
                        me.hash != hash || me.exec != e.exec || stat != Some((me.size, me.mtime_ns))
65858×
                    }))
659
            }
660
        };
6611223×
        let attributes = crate::attributes::Attributes::from_files(
6621223×
            fs_entries
6631223×
                .iter()
66412032×
                .filter(|(p, _)| is_attributes(p))
6651223×
                .map(|(p, e)| (p.as_str(), e.content.as_slice())),
666
        );
6671223×
        let mut manifest = None;
6681223×
        if for_commit {
669419×
            manifest = Some(PendingManifest {
670419×
                entries: fs_entries,
671419×
                blobs: built.blobs.clone(),
672419×
                dirs: self.walked_dirs.take(),
673419×
                written: super::prompt::now_ns(),
674419×
            });
675419×
        } else {
676804×
            if worth {
677762×
                self.write_manifest_entries(conflicted, uncommitted, &fs_entries, &built.blobs)?;
67842×
            }
679804×
            self.write_status_cache((uncommitted && !conflicted).then_some(&new_hash), &statuses);
680
        }
6811223×
        Ok(SnapshotResult {
6821223×
            wc_hash: new_hash,
6831223×
            wc,
6841223×
            base,
6851223×
            base_snapshot,
6861223×
            statuses,
6871223×
            changed,
6881223×
            resolves,
6891223×
            contributors,
6901223×
            attributes,
6911223×
            untracked_nested: self.untracked_nested.borrow().clone(),
6921223×
            manifest,
6931223×
        })
6941226×
    }
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).
800589×
    pub fn commit(&self, message: &str, extra_deps: &[ChangeHash]) -> Result<ChangeHash> {
801589×
        self.commit_selection(message, extra_deps, &Selection::All)
802589×
    }
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.
822609×
    fn committed_graph_keys(
823609×
        &self,
824609×
        st: &State,
825609×
        paths: &[String],
826609×
        attrs: &crate::attributes::Attributes,
827609×
    ) -> HashMap<String, [u8; 32]> {
828609×
        let _t = crate::timing::phase("commit: graph keys");
829609×
        let view = st.tree().view();
830609×
        paths
831609×
            .iter()
8323452×
            .filter_map(|p| {
8333452×
                let e = view.entries.get(p)?;
8343412×
                (e.kind == NodeKind::File && !e.mode.opaque && attrs.lookup(p).eol.is_none())
8353412×
                    .then_some(())?;
8363363×
                Some((p.clone(), st.graph_key(&e.node)?))
8373452×
            })
838609×
            .collect()
839609×
    }
840
841594×
    pub fn commit_selection(
842594×
        &self,
843594×
        message: &str,
844594×
        extra_deps: &[ChangeHash],
845594×
        selection: &Selection,
846594×
    ) -> Result<ChangeHash> {
847594×
        Ok(self
848594×
            .commit_selection_partial(message, extra_deps, selection)?
849
            .0)
850594×
    }
851
852
    /// As [`Repo::commit_selection`], and whether the commit left part of
853
    /// the working copy uncommitted: when it did not, nothing is left, and
854
    /// no snapshot is needed to say so.
855620×
    pub fn commit_selection_partial(
856620×
        &self,
857620×
        message: &str,
858620×
        extra_deps: &[ChangeHash],
859620×
        selection: &Selection,
860620×
    ) -> Result<(ChangeHash, bool)> {
861
        // The commit's objects are written together, made durable at once
862
        // before the operation that names them (spec §13.6).
863620×
        let batch = self.store.begin_batch()?;
864620×
        let out = self.commit_selection_batched(message, extra_deps, selection);
865620×
        batch.finish()?;
866620×
        out
867620×
    }
868
869
    /// Write the manifest a commit's snapshot left to the commit, with the
870
    /// graph keys `keys` sets.
871410×
    fn write_pending_manifest(
872410×
        &self,
873410×
        mut m: PendingManifest,
874410×
        conflicted: bool,
875410×
        keys: HashMap<String, [u8; 32]>,
876410×
    ) -> Result<()> {
8772805×
        for (path, k) in keys {
8782805×
            if let Some(e) = m.entries.get_mut(&path) {
8792805×
                e.graph_key = Some(k);
8802805×
            }
881
        }
882410×
        self.write_manifest_entries_as_of(
883410×
            conflicted,
884
            false,
885410×
            &m.entries,
886410×
            &m.blobs,
887410×
            m.written,
888410×
            m.dirs.unwrap_or_default(),
889
        )
890410×
    }
891
892620×
    fn commit_selection_batched(
893620×
        &self,
894620×
        message: &str,
895620×
        extra_deps: &[ChangeHash],
896620×
        selection: &Selection,
897620×
    ) -> Result<(ChangeHash, bool)> {
898620×
        let _wc = self.lock_working_copy()?;
899620×
        let mut snap = match self.snapshot_from_cache()? {
900201×
            Some(snap) => snap,
901419×
            None => self.snapshot_as("oxy commit", true, true)?,
902
        };
903620×
        let pending = snap.manifest.take();
904620×
        if snap.wc.tree_ops.is_empty() && snap.wc.edits.is_empty() {
9053×
            if let Some(m) = pending {
9063×
                let conflicted = snap.base_snapshot.is_conflicted();
9073×
                self.write_pending_manifest(m, conflicted, HashMap::new())?;
9080×
            }
9093×
            return fail("nothing to commit: the working copy matches its base");
910617×
        }
911617×
        if let Some(s) = snap
912617×
            .statuses
913617×
            .iter()
9143469×
            .find(|s| s.status == ChangeStatus::ConflictEdited)
915
        {
9160×
            return fail(format!("{} still contains conflict markers", s.path));
917617×
        }
918617×
        if message.trim().is_empty() {
9190×
            return fail("a commit message is required");
920617×
        }
921
        // What the whole working copy references, before a whole commit
922
        // takes its operations over (they are moved, not copied: for a
923
        // large tree they are most of the memory).
924617×
        let wc_refs = referenced_changes(&snap.wc, &snap.base);
9253469×
        let changed_paths: Vec<String> = snap.statuses.iter().map(|s| s.path.clone()).collect();
926617×
        let (tree_ops, edits, partial) = match selection {
927609×
            Selection::All => (
928609×
                std::mem::take(&mut snap.wc.tree_ops),
929609×
                std::mem::take(&mut snap.wc.edits),
930609×
                false,
931609×
            ),
9324×
            Selection::Paths(paths) => {
9334×
                let (o, e) = select_paths(&snap.wc, &snap.base_snapshot, paths);
9344×
                let partial = o.len() != snap.wc.tree_ops.len() || e.len() != snap.wc.edits.len();
9354×
                (o, e, partial)
936
            }
9374×
            Selection::Hunks(indices) => {
9384×
                let (o, e) = select_hunks(&snap.wc, indices);
9394×
                let partial = o.len() != snap.wc.tree_ops.len() || e.len() != snap.wc.edits.len();
9404×
                (o, e, partial)
941
            }
942
        };
943617×
        if tree_ops.is_empty() && edits.is_empty() {
9440×
            return fail("nothing selected to commit");
945617×
        }
946617×
        if partial && snap.resolves {
9470×
            return fail("a conflict resolution must be committed whole");
948617×
        }
949
        // pre-commit hook: may veto.
950617×
        self.run_hook(
951617×
            "pre-commit",
952617×
            &format!(
953
                "{{\"event\":\"pre-commit\",\"message\":{},\"paths\":{}}}",
954617×
                json_str(message),
9553469×
                json_array(snap.statuses.iter().map(|s| format!(
956
                    "{{\"path\":{},\"status\":{}}}",
9573469×
                    json_str(&s.path),
9583469×
                    json_str(&format!("{:?}", s.status))
959
                )))
960
            ),
9611×
        )?;
962616×
        let (op_ref, op) = self.head_op()?;
963616×
        let mut deps: BTreeSet<ChangeHash> = wc_refs;
964
        // semantic-deps hook: may add explicit dependencies (spec §8.1).
965616×
        if self.config.semantic_deps {
9661×
            let touched: Vec<String> = snap.statuses.iter().map(|s| s.path.clone()).collect();
9671×
            let by_node = snap.base_snapshot.tree.by_node();
9681×
            let mut candidates: Vec<(ChangeId, ChangeHash, Vec<String>)> = Vec::new();
9691×
            let mut seen: BTreeSet<ChangeHash> = BTreeSet::new();
9702×
            for h in deps.iter().chain(snap.base.maximal(&snap.wc.deps).iter()) {
9712×
                if !seen.insert(*h) {
9720×
                    continue;
9732×
                }
9742×
                let c = self.store.get_change(h)?;
9752×
                let mut paths: BTreeSet<String> = BTreeSet::new();
9766×
                for n in c
9772×
                    .tree_ops
9782×
                    .iter()
9793×
                    .map(|o| o.node())
9803×
                    .chain(c.edits.iter().map(|e| e.node()))
981
                {
9826×
                    if let Some(e) = by_node.get(&n) {
9836×
                        paths.insert(e.path.clone());
9846×
                    }
985
                }
9862×
                candidates.push((c.change_id, *h, paths.into_iter().collect()));
987
            }
9881×
            for d in self.semantic_deps(&snap.wc.change_id, &touched, &candidates)? {
9891×
                if snap.base.contains(&d) {
9901×
                    deps.insert(d);
9911×
                }
992
            }
993615×
        }
994
        // A resolution depends on every change that contributed to the
995
        // conflict (spec §8.1). Tree and opaque conflicts are resolved through
996
        // ordinary operations whose references already cover the contributors.
997616×
        deps.extend(snap.contributors.iter().copied());
998616×
        for d in extra_deps {
9992×
            if !snap.base.contains(d) {
10000×
                return fail(format!(
1001
                    "--depends-on {d}: not in the working copy's base state"
1002
                ));
10032×
            }
10042×
            deps.insert(*d);
1005
        }
1006616×
        let mut change = Change {
1007
            version: crate::objects::CHANGE_VERSION,
1008616×
            change_id: if partial {
10096×
                ChangeId::random()
1010
            } else {
1011610×
                snap.wc.change_id
1012
            },
1013616×
            deps: vec![],
1014616×
            author: self.author(),
1015616×
            hlc: Hlc::now(),
1016616×
            message: message.trim_end().to_string(),
1017616×
            tree_ops,
1018616×
            edits,
1019616×
            kind: if snap.resolves {
10207×
                ChangeKind::Resolution
1021
            } else {
1022609×
                ChangeKind::Normal
1023
            },
1024
        };
1025616×
        if partial {
1026
            // Dependencies come from what the selected part references, not
1027
            // from the whole working copy.
10286×
            deps = referenced_changes(&change, &snap.base);
10296×
            for d in extra_deps {
10300×
                deps.insert(*d);
10310×
            }
1032610×
        }
1033616×
        change.deps = deps.into_iter().collect();
1034616×
        change.normalize();
1035616×
        let signing = crate::timing::phase("commit: sign and store");
1036616×
        let hash = self.store_signed(&change)?;
1037615×
        drop(signing);
1038615×
        let extending = crate::timing::phase("commit: extend the state");
1039
1040
        // New bookmark heads: maximal elements of old heads plus the new change.
1041
        // The working copy continues on its own base plus the new change, which
1042
        // is exactly what the files on disk contain; the bookmark may hold
1043
        // other heads (and conflicts) the working copy has not checked out.
1044615×
        let old_heads = self.heads_of(&op.view, &self.config.bookmark)?;
1045615×
        let old_base = snap.base.maximal(&snap.wc.deps);
1046615×
        let mut all: Vec<ChangeHash> = old_heads.clone();
1047615×
        all.extend(old_base.iter().copied());
1048615×
        all.push(hash);
1049
        // The snapshot already loaded the working copy's base; when that also
1050
        // holds every bookmark head, it is the state to extend.
1051615×
        let mut st = if old_heads.iter().all(|h| snap.base.contains(h)) {
1052579×
            snap.base
1053
        } else {
105436×
            self.load_state(&all)?
1055
        };
1056615×
        st.add_hashed(hash, change)?;
1057615×
        let mut with_new = old_heads.clone();
1058615×
        with_new.push(hash);
1059615×
        let new_heads = st.maximal(&with_new);
1060
        // Automatic checkpoint once enough changes accumulated (spec §11).
1061615×
        let since = self
1062615×
            .latest_checkpoint(&self.config.bookmark)?
1063615×
            .map(|(_, cp)| cp.count)
1064615×
            .unwrap_or(0);
1065615×
        if self.config.checkpoint_interval > 0
1066615×
            && (st.len() as u64).saturating_sub(since) >= self.config.checkpoint_interval
1067
        {
10682×
            let cp_state = self.load_state_full(&new_heads)?;
10692×
            self.write_checkpoint(&self.config.bookmark, &cp_state, &new_heads)?;
1070613×
        }
1071615×
        let mut wc_base = old_base.clone();
1072615×
        wc_base.push(hash);
1073615×
        let wc_base = st.maximal(&wc_base);
1074615×
        drop(extending);
1075
1076
        // The graph keys of the files as they now are, from the state the
1077
        // commit just extended: a file whose graph it built has none, and
1078
        // is read by the next snapshot; a key the next base does not share
1079
        // (the bookmark held other heads) is simply not trusted then.
1080615×
        let keying = crate::timing::phase("commit: graph keys of the files");
1081615×
        let committed_keys =
1082615×
            (!partial).then(|| self.committed_graph_keys(&st, &changed_paths, &snap.attributes));
1083615×
        drop(keying);
1084615×
        let recording = crate::timing::phase("commit: record");
1085615×
        let wc = self.new_working_copy(wc_base, "");
1086615×
        let wc_hash = self.store.put_change(&wc)?;
1087615×
        let mut view = op.view.clone();
1088615×
        view.bookmarks.insert(
1089615×
            self.config.bookmark.clone(),
1090615×
            self.store.put_state(&StateObject::new(new_heads))?,
1091
        );
1092615×
        view.workspaces.insert(self.workspace, wc_hash);
1093615×
        self.record_op(&[op_ref], &format!("oxy commit -m {message:?}"), view)?;
1094610×
        drop(recording);
1095610×
        let rewriting = crate::timing::phase("commit: manifest");
1096610×
        if partial {
10976×
            // The rest is rebuilt from disk by the next snapshot.
10986×
            self.drop_manifest();
10996×
        } else {
1100604×
            let conflicted = snap.base_snapshot.is_conflicted() && !snap.resolves;
1101
            // The files on disk are now exactly the new base's renderings:
1102
            // record their graph keys, so the next snapshot neither reads nor
1103
            // renders them (oxygen#35).
1104604×
            let keys = if conflicted {
11050×
                HashMap::new()
1106
            } else {
1107604×
                committed_keys.unwrap_or_default()
1108
            };
1109604×
            match pending {
1110407×
                Some(m) => self.write_pending_manifest(m, conflicted, keys)?,
1111197×
                None => self.rewrite_manifest(conflicted, false, &keys)?,
1112
            }
1113
        }
1114610×
        drop(rewriting);
1115610×
        let packing = crate::timing::phase("commit: autopack");
1116610×
        self.maybe_autopack()?;
1117610×
        drop(packing);
1118610×
        let _hook = crate::timing::phase("commit: hook");
1119610×
        let _ = self.run_hook(
1120610×
            "post-commit",
1121610×
            &format!(
1122610×
                "{{\"event\":\"post-commit\",\"change_id\":{},\"hash\":{},\"message\":{}}}",
1123610×
                json_str(&snap.wc.change_id.to_hex()),
1124610×
                json_str(&hash.to_hex()),
1125610×
                json_str(message)
1126610×
            ),
1127610×
        );
1128610×
        Ok((hash, partial))
1129620×
    }
1130
}
1131
1132
/// What part of the working copy a commit takes (spec §12.3).
1133
#[derive(Clone, Debug)]
1134
pub enum Selection {
1135
    All,
1136
    /// Every operation and edit on nodes under these paths.
1137
    Paths(Vec<String>),
1138
    /// Hunk indices as `Repo::hunks` numbers them; dependent hunks are added.
1139
    Hunks(Vec<usize>),
1140
}
1141
1142
/// One selectable piece of the working copy: a tree operation or an edit.
1143
#[derive(Clone, Debug)]
1144
pub struct Hunk {
1145
    pub index: usize,
1146
    pub path: String,
1147
    /// Rendered like `oxy diff`.
1148
    pub text: String,
1149
}
1150
1151
/// The tree operations and edits on nodes under `paths`, plus the
1152
/// additions of any new parent directories they need.
11534×
fn select_paths(
11544×
    wc: &Change,
11554×
    base_snapshot: &Snapshot,
11564×
    paths: &[String],
11574×
) -> (Vec<TreeOp>, Vec<Edit>) {
115813×
    let selected = |p: &str| {
115913×
        paths
116013×
            .iter()
116113×
            .any(|x| p == x || p.starts_with(&format!("{}/", x.trim_end_matches('/'))))
116213×
    };
11634×
    let by_node = base_snapshot.tree.by_node();
11644×
    let mut new_names: HashMap<NodeId, (NodeId, String, NodeKind)> = HashMap::new();
11654×
    for op in &wc.tree_ops {
1166
        if let TreeOp::AddNode {
11671×
            node,
11681×
            parent,
11691×
            name,
11701×
            kind,
1171
            ..
11721×
        } = op
11731×
        {
11741×
            new_names.insert(*node, (*parent, name.clone(), *kind));
11751×
        }
1176
    }
11774×
    let mut nodes: BTreeSet<NodeId> = BTreeSet::new();
117813×
    for n in wc
11794×
        .tree_ops
11804×
        .iter()
11814×
        .map(|o| o.node())
118212×
        .chain(wc.edits.iter().map(|e| e.node()))
1183
    {
118413×
        if path_of_node(&n, &by_node, &new_names).is_some_and(|p| selected(&p)) {
11858×
            nodes.insert(n);
11868×
        }
1187
    }
1188
    // New parents of selected new nodes come along.
11894×
    let mut changed = true;
11908×
    while changed {
11914×
        changed = false;
11924×
        for (n, (parent, _, _)) in &new_names {
11931×
            if nodes.contains(n) && new_names.contains_key(parent) && nodes.insert(*parent) {
11940×
                changed = true;
11951×
            }
1196
        }
1197
    }
11984×
    let ops = wc
11994×
        .tree_ops
12004×
        .iter()
12014×
        .filter(|o| nodes.contains(&o.node()))
12024×
        .cloned()
12034×
        .collect();
12044×
    let edits = wc
12054×
        .edits
12064×
        .iter()
120712×
        .filter(|e| nodes.contains(&e.node()))
12084×
        .cloned()
12094×
        .collect();
12104×
    (ops, edits)
12114×
}
1212
1213
/// The hunks `indices` name plus whatever they refer to within the working
1214
/// copy (the parent directory of an added node, the insert that introduced
1215
/// an anchor line), renumbered so the result is a well-formed change.
12165×
fn select_hunks(wc: &Change, indices: &[usize]) -> (Vec<TreeOp>, Vec<Edit>) {
12175×
    let n_ops = wc.tree_ops.len();
12185×
    let mut ops_sel = vec![false; n_ops];
12195×
    let mut edits_sel = vec![false; wc.edits.len()];
12205×
    for &i in indices {
12214×
        if i < n_ops {
12221×
            ops_sel[i] = true;
12233×
        } else if i - n_ops < wc.edits.len() {
12243×
            edits_sel[i - n_ops] = true;
12253×
        }
1226
    }
1227
    // Atom ranges each insert introduces, per node, in the working copy's numbering.
12285×
    let mut per_node: HashMap<NodeId, u32> = HashMap::new();
12295×
    let mut insert_ranges: Vec<Option<(NodeId, u32, u32)>> = Vec::new();
123010×
    for e in &wc.edits {
123110×
        insert_ranges.push(match e {
123210×
            Edit::Insert { node, lines, .. } => {
123310×
                let start = per_node.entry(*node).or_default();
123410×
                let r = (*node, *start, *start + lines.len() as u32);
123510×
                *start += lines.len() as u32;
123610×
                Some(r)
1237
            }
12380×
            _ => None,
1239
        });
1240
    }
12415×
    let add_index: HashMap<NodeId, usize> = wc
12425×
        .tree_ops
12435×
        .iter()
12445×
        .enumerate()
12458×
        .filter_map(|(i, o)| {
12468×
            if let TreeOp::AddNode { node, .. } = o {
12478×
                Some((*node, i))
1248
            } else {
12490×
                None
1250
            }
12518×
        })
12525×
        .collect();
12535×
    let insert_for = |node: &NodeId, index: u32| -> Option<usize> {
12540×
        insert_ranges
12550×
            .iter()
12560×
            .position(|r| matches!(r, Some((n, a, b)) if n == node && *a <= index && index < *b))
12570×
    };
1258
    // Closure.
12595×
    let mut changed = true;
126013×
    while changed {
12618×
        changed = false;
126217×
        for i in 0..n_ops {
126317×
            if !ops_sel[i] {
126411×
                continue;
12656×
            }
12666×
            if let TreeOp::AddNode { node, parent, .. } = &wc.tree_ops[i] {
12676×
                if let Some(&p) = add_index.get(parent) {
12684×
                    if !ops_sel[p] {
12692×
                        ops_sel[p] = true;
12702×
                        changed = true;
12712×
                    }
12722×
                }
1273
                // A new node's content belongs with its addition: nobody
1274
                // wants an empty file committed apart from its lines.
127512×
                for (j, e) in wc.edits.iter().enumerate() {
127612×
                    if e.node() == *node && !edits_sel[j] {
12771×
                        edits_sel[j] = true;
12781×
                        changed = true;
127911×
                    }
1280
                }
12810×
            }
1282
        }
128316×
        for j in 0..wc.edits.len() {
128416×
            if !edits_sel[j] {
12859×
                continue;
12867×
            }
12877×
            let e = &wc.edits[j];
12887×
            if let Some(&a) = add_index.get(&e.node()) {
12895×
                if !ops_sel[a] {
12901×
                    ops_sel[a] = true;
12911×
                    changed = true;
12924×
                }
12932×
            }
1294
            if let Edit::Insert {
12957×
                node,
12967×
                after,
12977×
                before,
1298
                ..
12997×
            } = e
1300
            {
130114×
                for r in [after, before] {
130214×
                    if let AtomRef::Atom { change, index } = r {
13032×
                        if change.is_zero() {
13040×
                            if let Some(k) = insert_for(node, *index) {
13050×
                                if !edits_sel[k] {
13060×
                                    edits_sel[k] = true;
13070×
                                    changed = true;
13080×
                                }
13090×
                            }
13102×
                        }
131112×
                    }
1312
                }
13130×
            }
1314
        }
1315
    }
1316
    // Renumber self-references: old atom index → new index among selected inserts.
13175×
    let mut remap: HashMap<(NodeId, u32), u32> = HashMap::new();
13185×
    let mut new_counts: HashMap<NodeId, u32> = HashMap::new();
131910×
    for (j, r) in insert_ranges.iter().enumerate() {
132010×
        if let (true, Some((node, a, b))) = (edits_sel[j], r) {
13214×
            let next = new_counts.entry(*node).or_default();
13224×
            for old in *a..*b {
13234×
                remap.insert((*node, old), *next);
13244×
                *next += 1;
13254×
            }
13266×
        }
1327
    }
13288×
    let map_ref = |r: AtomRef, node: &NodeId| -> AtomRef {
13292×
        match r {
13302×
            AtomRef::Atom { change, index } if change.is_zero() => AtomRef::Atom {
13310×
                change,
13320×
                index: remap.get(&(*node, index)).copied().unwrap_or(index),
13330×
            },
13348×
            other => other,
1335
        }
13368×
    };
13375×
    let ops = wc
13385×
        .tree_ops
13395×
        .iter()
13405×
        .enumerate()
13418×
        .filter(|(i, _)| ops_sel[*i])
13425×
        .map(|(_, o)| o.clone())
13435×
        .collect();
13445×
    let edits = wc
13455×
        .edits
13465×
        .iter()
13475×
        .enumerate()
134810×
        .filter(|(j, _)| edits_sel[*j])
13495×
        .map(|(_, e)| match e {
1350
            Edit::Insert {
13514×
                node,
13524×
                after,
13534×
                before,
13544×
                lines,
13554×
            } => Edit::Insert {
13564×
                node: *node,
13574×
                after: map_ref(*after, node),
13584×
                before: map_ref(*before, node),
13594×
                lines: lines.clone(),
13604×
            },
13610×
            other => other.clone(),
13624×
        })
13635×
        .collect();
13645×
    (ops, edits)
13655×
}
1366
1367
/// Render each tree operation and edit of `change` on its own, numbered.
13687×
pub fn render_hunks(change: &Change, base: &State, base_snapshot: &Snapshot) -> Vec<Hunk> {
13697×
    let by_node = base_snapshot.tree.by_node();
13707×
    let mut new_names: HashMap<NodeId, (NodeId, String, NodeKind)> = HashMap::new();
13718×
    for op in &change.tree_ops {
1372
        if let TreeOp::AddNode {
13738×
            node,
13748×
            parent,
13758×
            name,
13768×
            kind,
1377
            ..
13788×
        } = op
13798×
        {
13808×
            new_names.insert(*node, (*parent, name.clone(), *kind));
13818×
        }
1382
    }
13837×
    let mut out = Vec::new();
13848×
    for (i, op) in change.tree_ops.iter().enumerate() {
13858×
        let one = Change {
13868×
            tree_ops: vec![op.clone()],
13878×
            edits: vec![],
13888×
            ..change.clone()
13898×
        };
13908×
        let path = path_of_node(&op.node(), &by_node, &new_names).unwrap_or_default();
13918×
        out.push(Hunk {
13928×
            index: i,
13938×
            path,
13948×
            text: render_change(&one, base, base_snapshot),
13958×
        });
13968×
    }
139713×
    for (j, e) in change.edits.iter().enumerate() {
139813×
        let one = Change {
139913×
            tree_ops: vec![],
140013×
            edits: vec![e.clone()],
140113×
            ..change.clone()
140213×
        };
140313×
        let path = path_of_node(&e.node(), &by_node, &new_names).unwrap_or_default();
140413×
        out.push(Hunk {
140513×
            index: change.tree_ops.len() + j,
140613×
            path,
140713×
            text: render_change(&one, base, base_snapshot),
140813×
        });
140913×
    }
14107×
    out
14117×
}
1412
1413
/// One file's part of a diff, for `oxy diff --json`.
1414
#[derive(Clone, Debug)]
1415
pub struct FileDiff {
1416
    pub path: String,
1417
    /// `added`, `removed`, `modified`, `renamed`, `mode`, `replaced`.
1418
    pub kind: String,
1419
    pub hunks: Vec<DiffHunk>,
1420
    /// For renames, the previous path.
1421
    pub from: Option<String>,
1422
}
1423
1424
/// Lines inserted after `base_line` (0 = before the first line) and lines
1425
/// removed, with their base line numbers.
1426
#[derive(Clone, Debug, Default)]
1427
pub struct DiffHunk {
1428
    pub base_line: u32,
1429
    pub added: Vec<Vec<u8>>,
1430
    pub removed: Vec<(u32, Vec<u8>)>,
1431
}
1432
1433
impl Repo {
1434
    /// The content of `path` in a state: `heads`, or the working copy's base.
143525×
    pub fn file_at(&self, path: &str, heads: Option<&[ChangeHash]>) -> Result<Vec<u8>> {
1436
        // The state's history and tree, then the one file's graph: nothing
1437
        // else is built or rendered (oxygen#92).
1438
        // The working copy's base, and a state named by its heads (`-r
1439
        // main` on main), come from the workspace's state index.
144025×
        let base = if self.is_bare() {
14415×
            None
1442
        } else {
144320×
            Some(self.working_copy()?.1.deps)
1444
        };
144525×
        let same = |a: &[ChangeHash], b: &[ChangeHash]| {
14461×
            let (mut a, mut b) = (a.to_vec(), b.to_vec());
14471×
            a.sort();
14481×
            b.sort();
14491×
            a == b
14501×
        };
145125×
        let mut state = match (heads, base) {
14521×
            (Some(h), Some(b)) if same(h, &b) => self.load_state_indexed(&b)?,
14535×
            (Some(h), _) => self.load_state_history(h)?,
145419×
            (None, Some(b)) => self.load_state_indexed(&b)?,
14550×
            (None, None) => return fail("this is a bare repository: it has no working copy"),
1456
        };
145725×
        let view = state.tree().view();
145825×
        let Some(node) = view.entries.get(path).map(|e| e.node) else {
14590×
            return fail(format!("{path} is not in that state"));
1460
        };
146125×
        self.load_graphs_of(&mut state, &[node])?;
146224×
        let snapshot = state.materialize_paths(view, [path]);
146324×
        let Some(f) = snapshot.files.get(path) else {
14640×
            return fail(format!("{path} is not in that state"));
1465
        };
146624×
        match &f.content {
14670×
            FileContent::Dir => fail(format!("{path} is a directory")),
146824×
            FileContent::Text { bytes, .. } => Ok(bytes.clone()),
14690×
            FileContent::Opaque { blobs } => match blobs.first() {
14700×
                Some(b) => self.read_blob(b),
14710×
                None => Ok(vec![]),
1472
            },
1473
        }
147425×
    }
1475
1476
    /// Restore `paths` (files or directories) to the working copy's base:
1477
    /// edits are undone, additions removed, removals put back. Returns the
1478
    /// number of paths touched.
14792×
    pub fn discard(&self, paths: &[String]) -> Result<usize> {
14802×
        let _wc = self.lock_working_copy()?;
14812×
        let snap = self.snapshot_status("oxy discard")?;
14827×
        let under = |p: &str| {
14837×
            paths
14847×
                .iter()
14857×
                .any(|x| p == x || p.starts_with(&format!("{}/", x.trim_end_matches('/'))))
14867×
        };
14872×
        let attrs = Repo::state_attributes(&snap.base_snapshot);
14882×
        let mut n = 0;
14893×
        for s in &snap.statuses {
14903×
            if !under(&s.path) {
14911×
                continue;
14922×
            }
14932×
            match snap.base_snapshot.files.get(&s.path) {
1494
                None => {
1495
                    // Added (or the new name of a rename): remove it.
14961×
                    let full = self.root.join(&s.path);
14971×
                    if full.is_dir() {
14980×
                        let _ = fs::remove_dir_all(&full);
14991×
                    } else {
15001×
                        let _ = fs::remove_file(&full);
15011×
                    }
15021×
                    n += 1;
1503
                }
15041×
                Some(f) => {
15051×
                    match &f.content {
15060×
                        FileContent::Dir => fs::create_dir_all(self.root.join(&s.path))?,
15071×
                        FileContent::Text { bytes, .. } => {
15081×
                            let on_disk: std::borrow::Cow<[u8]> = if attrs.lookup(&s.path).eol
15091×
                                == Some(crate::attributes::Eol::Crlf)
1510
                            {
15110×
                                crate::attributes::to_crlf(bytes).into()
1512
                            } else {
15131×
                                bytes.as_slice().into()
1514
                            };
15151×
                            self.write_file(&s.path, &on_disk, f.mode.exec)?;
1516
                        }
15170×
                        FileContent::Opaque { blobs } => {
15180×
                            let bytes = match blobs.first() {
15190×
                                Some(b) => self.read_blob(b)?,
15200×
                                None => vec![],
1521
                            };
15220×
                            if f.kind == NodeKind::Symlink {
15230×
                                self.write_symlink(&s.path, &bytes)?;
15240×
                            } else if f.kind == NodeKind::File {
15250×
                                self.write_file(&s.path, &bytes, f.mode.exec)?;
15260×
                            }
1527
                        }
1528
                    }
15291×
                    n += 1;
1530
                }
1531
            }
1532
        }
1533
        // A rename's old name is not in the statuses; put it back too.
15344×
        for (p, f) in &snap.base_snapshot.files {
15354×
            if under(p)
15361×
                && !self.root.join(p).exists()
15370×
                && f.kind != NodeKind::Dir
15380×
                && f.kind != NodeKind::Subrepo
15390×
                && !snap.statuses.iter().any(|s| s.path == *p)
1540
            {
15410×
                let bytes = match &f.content {
15420×
                    FileContent::Text { bytes, .. } => bytes.clone(),
15430×
                    FileContent::Opaque { blobs } => blobs
15440×
                        .first()
15450×
                        .map(|b| self.read_blob(b))
15460×
                        .transpose()?
15470×
                        .unwrap_or_default(),
15480×
                    FileContent::Dir => continue,
1549
                };
15500×
                if f.kind == NodeKind::Symlink {
15510×
                    self.write_symlink(p, &bytes)?
1552
                } else {
15530×
                    self.write_file(p, &bytes, f.mode.exec)?
1554
                }
15550×
                n += 1;
15564×
            }
1557
        }
15582×
        self.drop_manifest();
15592×
        Ok(n)
15602×
    }
1561
1562
    /// Undo the working-copy hunks `indices` (as `hunks` numbers them) on
1563
    /// disk, keeping the others: the files are rewritten from the base plus
1564
    /// the remaining hunks.
15651×
    pub fn discard_hunks(&self, indices: &[usize]) -> Result<usize> {
15661×
        let _wc = self.lock_working_copy()?;
15671×
        let (snap, hunks) = self.hunks()?;
15681×
        let keep: Vec<usize> = hunks
15691×
            .iter()
15701×
            .map(|h| h.index)
15711×
            .filter(|i| !indices.contains(i))
15721×
            .collect();
15731×
        let (ops, edits) = select_hunks(&snap.wc, &keep);
15741×
        let dropped_nodes: BTreeSet<NodeId> = hunks
15751×
            .iter()
15761×
            .filter(|h| indices.contains(&h.index))
15771×
            .map(|h| {
15781×
                if h.index < snap.wc.tree_ops.len() {
15790×
                    snap.wc.tree_ops[h.index].node()
1580
                } else {
15811×
                    snap.wc.edits[h.index - snap.wc.tree_ops.len()].node()
1582
                }
15831×
            })
15841×
            .collect();
15851×
        let mut partial = snap.wc.clone();
15861×
        partial.tree_ops = ops;
15871×
        partial.edits = edits;
15881×
        partial.normalize();
15891×
        let mut st = snap.base.clone();
15901×
        st.add_unchecked(partial);
1591
        // Every file of the target is rendered: build the graphs the
1592
        // partial snapshot left out.
15931×
        self.load_all_graphs(&mut st)?;
15941×
        let target = st.materialize();
15951×
        let by_node_target = target.tree.by_node();
15961×
        let by_node_base = snap.base_snapshot.tree.by_node();
15971×
        let attrs = Repo::state_attributes(&target);
15981×
        let mut n = 0;
15991×
        for node in dropped_nodes {
16001×
            match by_node_target.get(&node) {
16011×
                Some(e) => {
16021×
                    let f = &target.files[&e.path];
16031×
                    match &f.content {
16040×
                        FileContent::Dir => {}
16051×
                        FileContent::Text { bytes, .. } => {
16061×
                            let on_disk: std::borrow::Cow<[u8]> = if attrs.lookup(&e.path).eol
16071×
                                == Some(crate::attributes::Eol::Crlf)
1608
                            {
16090×
                                crate::attributes::to_crlf(bytes).into()
1610
                            } else {
16111×
                                bytes.as_slice().into()
1612
                            };
16131×
                            self.write_file(&e.path, &on_disk, f.mode.exec)?;
1614
                        }
16150×
                        FileContent::Opaque { blobs } => {
16160×
                            let bytes = blobs
16170×
                                .first()
16180×
                                .map(|b| self.read_blob(b))
16190×
                                .transpose()?
16200×
                                .unwrap_or_default();
16210×
                            if f.kind == NodeKind::Symlink {
16220×
                                self.write_symlink(&e.path, &bytes)?
1623
                            } else {
16240×
                                self.write_file(&e.path, &bytes, f.mode.exec)?
1625
                            }
1626
                        }
1627
                    }
1628
                    // A discarded rename: the new name goes.
16291×
                    if let Some(old_path) = snap
16301×
                        .statuses
16311×
                        .iter()
16321×
                        .find(|s| {
16331×
                            s.status == ChangeStatus::Renamed && !target.files.contains_key(&s.path)
16341×
                        })
16351×
                        .map(|s| s.path.clone())
16360×
                    {
16370×
                        let _ = fs::remove_file(self.root.join(old_path));
16381×
                    }
16391×
                    n += 1;
1640
                }
1641
                None => {
1642
                    // The node exists in neither target nor base with a live path: an addition to remove.
16430×
                    if let Some(added) = snap.statuses.iter().find(|s| {
16440×
                        s.status == ChangeStatus::Added
16450×
                            && !target.files.contains_key(&s.path)
16460×
                            && !by_node_base.contains_key(&node)
16470×
                    }) {
16480×
                        let full = self.root.join(&added.path);
16490×
                        if full.is_dir() {
16500×
                            let _ = fs::remove_dir_all(&full);
16510×
                        } else {
16520×
                            let _ = fs::remove_file(&full);
16530×
                        }
16540×
                        n += 1;
16550×
                    }
1656
                }
1657
            }
1658
        }
16591×
        self.drop_manifest();
16601×
        Ok(n)
16611×
    }
1662
1663
    /// The diff of the working copy (`None`) or of a change, per file with
1664
    /// line-numbered hunks (spec: `oxy diff --json`).
16655×
    pub fn diff_files(&self, change: Option<&ChangeHash>) -> Result<Vec<FileDiff>> {
16665×
        let (c, base, base_snapshot) = match change {
16672×
            Some(h) => {
16682×
                let c = self.store.get_change(h)?;
16692×
                let (base, snapshot) = self.change_base(&c)?;
16702×
                (c, base, snapshot)
1671
            }
16723×
            None => self.working_copy_with_base()?,
1673
        };
16745×
        Ok(diff_files_of(&c, &base, &base_snapshot))
16755×
    }
1676
1677
    /// The snapshot a command would take, without taking it, when the
1678
    /// status cache holds: every file is as the last snapshot left it, so
1679
    /// that snapshot's working-copy change is the answer. Its base comes
1680
    /// from the state index, the `.oxyattributes` files from disk. `None`
1681
    /// when a snapshot must be taken, and when there is nothing to commit
1682
    /// (the snapshot then says so). A conflicted base never gets here: the
1683
    /// cache does not hold for one.
1684621×
    pub(crate) fn snapshot_from_cache(&self) -> Result<Option<SnapshotResult>> {
1685621×
        let Some(statuses) = self.status_by_manifest()? else {
1686417×
            return Ok(None);
1687
        };
1688204×
        if statuses.is_empty() {
16892×
            return Ok(None);
1690202×
        }
1691202×
        let _t = crate::timing::phase("snapshot: from the status cache");
1692202×
        let (wc_hash, wc) = self.working_copy()?;
1693202×
        let base = self.load_state_indexed(&wc.deps)?;
1694202×
        let (base, base_snapshot) = self.render_base_for(&wc, base)?;
1695202×
        let attribute_files: Vec<(String, Vec<u8>)> = match self.read_manifest()? {
1696202×
            Some((_, _, m)) => m
1697202×
                .entries
1698202×
                .keys()
1699630×
                .filter(|p| is_attributes(p))
1700202×
                .filter_map(|p| fs::read(self.root.join(p)).ok().map(|b| (p.clone(), b)))
1701202×
                .collect(),
17020×
            None => Vec::new(),
1703
        };
1704202×
        let attributes = crate::attributes::Attributes::from_files(
1705202×
            attribute_files
1706202×
                .iter()
1707202×
                .map(|(p, b)| (p.as_str(), b.as_slice())),
1708
        );
1709202×
        Ok(Some(SnapshotResult {
1710202×
            wc_hash,
1711202×
            wc,
1712202×
            base,
1713202×
            base_snapshot,
1714202×
            statuses,
1715202×
            changed: false,
1716202×
            resolves: false,
1717202×
            contributors: Vec::new(),
1718202×
            attributes,
1719202×
            untracked_nested: self.untracked_nested.borrow().clone(),
1720202×
            manifest: None,
1721202×
        }))
1722621×
    }
1723
1724
    /// The working-copy change with its base state and a snapshot of the
1725
    /// base, for showing what the working copy changes ([`render_change`],
1726
    /// [`diff_files_of`]). While the status cache holds (every file as the
1727
    /// last snapshot left it), the stored working-copy change is the
1728
    /// answer, no snapshot is taken, and the base's snapshot holds its tree
1729
    /// but no file; otherwise a snapshot makes all three.
17304×
    pub fn working_copy_with_base(&self) -> Result<(Change, State, Snapshot)> {
17314×
        if self.status_by_manifest()?.is_some() {
17322×
            let (_, wc) = self.working_copy()?;
17332×
            let base = self.load_state_indexed(&wc.deps)?;
17342×
            let (base, snapshot) = self.tree_base_for(&wc, base)?;
17352×
            return Ok((wc, base, snapshot));
17362×
        }
17372×
        let snap = self.snapshot_status("oxy diff")?;
17382×
        Ok((snap.wc, snap.base, snap.base_snapshot))
17394×
    }
1740
1741
    /// The log restricted to changes touching `path` (its node, so renames
1742
    /// are followed), on the current bookmark.
17435×
    pub fn log_for_path(&self, path: &str) -> Result<Vec<LogEntry>> {
17445×
        let heads = self.bookmark_heads()?;
17455×
        if self.is_bare() {
17461×
            return self.log_for_path_in(path, &heads);
17474×
        }
17484×
        let entries = self.log()?;
17494×
        let (_, wc) = self.working_copy()?;
1750
        // The path's node from the trees alone: the base's (from the
1751
        // workspace's state index), else the bookmark's. Nothing is
1752
        // rendered.
17534×
        let node_in = |state: State| state.tree().view().entries.get(path).map(|e| e.node);
17544×
        let node = match node_in(self.load_state_indexed(&wc.deps)?) {
17554×
            Some(n) => Some(n),
17560×
            None => node_in(self.load_state_history(&heads)?),
1757
        };
17584×
        let Some(node) = node else {
17590×
            return fail(format!("{path} is not tracked"));
1760
        };
17614×
        Ok(self.entries_touching(entries, node))
17625×
    }
1763
1764
    /// The log of the state with these heads restricted to changes touching
1765
    /// `path` (its node, so renames are followed).
17662×
    pub fn log_for_path_in(&self, path: &str, heads: &[ChangeHash]) -> Result<Vec<LogEntry>> {
17672×
        self.log_for_path_of(&self.load_state_history(heads)?, path, None)
17682×
    }
1769
1770
    /// The changes of a loaded state touching `path`, newest first, at most
1771
    /// `limit` of them. The path is found in the state's tree alone, so no
1772
    /// file is rendered, and the walk stops once `limit` are found.
17735×
    pub fn log_for_path_of(
17745×
        &self,
17755×
        state: &State,
17765×
        path: &str,
17775×
        limit: Option<usize>,
17785×
    ) -> Result<Vec<LogEntry>> {
17795×
        let Some(node) = state.tree().view().entries.get(path).map(|e| e.node) else {
17801×
            return fail(format!("{path} is not in that state"));
1781
        };
17824×
        Ok(self.entries_touching_up_to(self.log_of(state), node, limit))
17835×
    }
1784
17854×
    fn entries_touching(&self, entries: Vec<LogEntry>, node: NodeId) -> Vec<LogEntry> {
17864×
        self.entries_touching_up_to(entries, node, None)
17874×
    }
1788
17898×
    fn entries_touching_up_to(
17908×
        &self,
17918×
        entries: Vec<LogEntry>,
17928×
        node: NodeId,
17938×
        limit: Option<usize>,
17948×
    ) -> Vec<LogEntry> {
17958×
        let mut touched = self.touched();
17968×
        if limit.is_none() {
17977×
            let hashes: Vec<ChangeHash> = entries.iter().map(|e| e.hash).collect();
17987×
            touched.fill(self, &hashes);
17991×
        }
18008×
        let wanted = HashSet::from([node]);
18018×
        let mut out = Vec::new();
180228×
        for e in entries {
180328×
            if limit.is_some_and(|n| out.len() >= n) {
18041×
                break;
180527×
            }
180627×
            if touched.touches(self, &e.hash, &wanted) {
180718×
                out.push(e);
180818×
            }
1809
        }
18108×
        touched.save();
18118×
        out
18128×
    }
1813
}
1814
1815
/// Per-file hunks of `change` against `base`.
18165×
pub fn diff_files_of(change: &Change, base: &State, base_snapshot: &Snapshot) -> Vec<FileDiff> {
18175×
    let by_node = base_snapshot.tree.by_node();
18185×
    let mut new_names: HashMap<NodeId, (NodeId, String, NodeKind)> = HashMap::new();
18195×
    for op in &change.tree_ops {
1820
        if let TreeOp::AddNode {
18212×
            node,
18222×
            parent,
18232×
            name,
18242×
            kind,
1825
            ..
18263×
        } = op
18272×
        {
18282×
            new_names.insert(*node, (*parent, name.clone(), *kind));
18292×
        }
1830
    }
18319×
    let path_of = |n: &NodeId| -> String {
18329×
        path_of_node(n, &by_node, &new_names).unwrap_or_else(|| format!("<node {}>", n.short(8)))
18339×
    };
18345×
    let mut files: BTreeMap<NodeId, FileDiff> = BTreeMap::new();
18355×
    let mut order: Vec<NodeId> = Vec::new();
183614×
    let mut entry = |files: &mut BTreeMap<NodeId, FileDiff>, n: NodeId, kind: &str| {
183714×
        if let std::collections::btree_map::Entry::Vacant(v) = files.entry(n) {
18389×
            order.push(n);
18399×
            v.insert(FileDiff {
18409×
                path: path_of(&n),
18419×
                kind: kind.to_string(),
18429×
                hunks: vec![],
18439×
                from: None,
18449×
            });
18459×
        }
184614×
    };
18475×
    for op in &change.tree_ops {
18483×
        match op {
18492×
            TreeOp::AddNode { node, kind, .. } => {
18502×
                if *kind != NodeKind::Dir {
18512×
                    entry(&mut files, *node, "added");
18522×
                }
1853
            }
18541×
            TreeOp::RemoveNode { node, .. } => {
18551×
                entry(&mut files, *node, "removed");
18561×
                if let Some(e) = by_node.get(node) {
18571×
                    files.get_mut(node).unwrap().path = e.path.clone();
18581×
                }
1859
            }
1860
            TreeOp::Move {
18610×
                node, parent, name, ..
1862
            } => {
18630×
                entry(&mut files, *node, "renamed");
18640×
                let f = files.get_mut(node).unwrap();
18650×
                f.from = by_node.get(node).map(|e| e.path.clone());
18660×
                let dir = if parent.is_root() {
18670×
                    String::new()
1868
                } else {
18690×
                    path_of_node(parent, &by_node, &new_names).unwrap_or_default()
1870
                };
18710×
                f.path = if dir.is_empty() {
18720×
                    name.clone()
1873
                } else {
18740×
                    format!("{dir}/{name}")
1875
                };
1876
            }
18770×
            TreeOp::SetMode { node, .. } => entry(&mut files, *node, "mode"),
1878
        }
1879
    }
1880
    // Base line numbers per node, 1-based.
18815×
    let mut line_of: HashMap<NodeId, HashMap<(ChangeHash, u32), u32>> = HashMap::new();
188211×
    let mut lines_for = |n: &NodeId| -> HashMap<(ChangeHash, u32), u32> {
188311×
        line_of
188411×
            .entry(*n)
188511×
            .or_insert_with(|| {
18868×
                base.live_lines(n)
18878×
                    .into_iter()
18888×
                    .enumerate()
188911×
                    .map(|(i, (k, _))| (k, i as u32 + 1))
18908×
                    .collect()
18918×
            })
189211×
            .clone()
189311×
    };
189411×
    for e in &change.edits {
189511×
        let n = e.node();
189611×
        let is_new = new_names.contains_key(&n);
189711×
        entry(&mut files, n, if is_new { "added" } else { "modified" });
189811×
        let f = files.get_mut(&n).unwrap();
189911×
        match e {
19009×
            Edit::Insert { after, lines, .. } => {
19019×
                let map = lines_for(&n);
19029×
                let base_line = match after {
19033×
                    AtomRef::Start => 0,
19040×
                    AtomRef::End => map.len() as u32,
19056×
                    AtomRef::Atom { change, index } if change.is_zero() => {
19060×
                        f.hunks.last().map(|h| h.base_line).unwrap_or(0)
1907
                    }
19086×
                    AtomRef::Atom { change, index } => {
19096×
                        map.get(&(*change, *index)).copied().unwrap_or(0)
1910
                    }
1911
                };
19129×
                f.hunks.push(DiffHunk {
19139×
                    base_line,
19149×
                    added: lines.to_vec(),
19159×
                    removed: vec![],
19169×
                });
1917
            }
19182×
            Edit::Delete { atoms, .. } => {
19192×
                let map = lines_for(&n);
19202×
                let mut removed = Vec::new();
19212×
                for r in atoms {
19222×
                    for i in r.from..r.to {
19232×
                        let line = map.get(&(r.change, i)).copied().unwrap_or(0);
19242×
                        let text = base
19252×
                            .file(&n)
19262×
                            .and_then(|g| g.content(&(r.change, i)))
19272×
                            .unwrap_or(b"")
19282×
                            .to_vec();
19292×
                        removed.push((line, text));
1930
                    }
1931
                }
19322×
                let base_line = removed
19332×
                    .first()
19342×
                    .map(|(l, _)| l.saturating_sub(1))
19352×
                    .unwrap_or(0);
19362×
                f.hunks.push(DiffHunk {
19372×
                    base_line,
19382×
                    added: vec![],
19392×
                    removed,
19402×
                });
1941
            }
1942
            Edit::Replace { .. } => {
19430×
                if !is_new {
19440×
                    f.kind = "replaced".into();
19450×
                }
1946
            }
1947
        }
1948
    }
19499×
    order.into_iter().filter_map(|n| files.remove(&n)).collect()
19505×
}
1951
1952
/// Builds the tree ops and edits of a working-copy change against a base.
1953
/// `BLAKE3("oxy node 1" 0 seed kind path)`, truncated: a node identifier
1954
/// that the same seed and path always give (never the root's).
195557×
fn seeded_node(seed: &[u8; 32], path: &str, kind: NodeKind) -> NodeId {
195657×
    let mut h = blake3::Hasher::new();
195757×
    h.update(b"oxy node 1\0");
195857×
    h.update(seed);
195957×
    h.update(&[match kind {
196043×
        NodeKind::File => 1,
196113×
        NodeKind::Dir => 2,
19620×
        NodeKind::Symlink => 3,
19631×
        NodeKind::Subrepo => 4,
1964
    }]);
196557×
    h.update(path.as_bytes());
196657×
    let mut id = [0u8; 16];
196757×
    id.copy_from_slice(&h.finalize().as_bytes()[..16]);
196857×
    if id == [0; 16] {
19690×
        id[15] = 1;
197057×
    }
197157×
    NodeId(id)
197257×
}
1973
1974
struct ChangeBuilder<'a> {
1975
    base: &'a State,
1976
    base_snapshot: &'a Snapshot,
1977
    tree_ops: Vec<TreeOp>,
1978
    edits: Vec<Edit>,
1979
    statuses: Vec<PathStatus>,
1980
    dir_nodes: HashMap<String, NodeId>,
1981
    reuse: HashMap<String, (NodeId, NodeKind)>,
1982
    /// Changes that contributed to conflicts this working copy resolves.
1983
    contributors: BTreeSet<ChangeHash>,
1984
    resolves: bool,
1985
    attrs: crate::attributes::Attributes,
1986
    blobs: HashMap<String, ObjectRef>,
1987
    /// Opaque files whose replace conflict the content settles.
1988
    resolve: HashSet<String>,
1989
    /// When set, new nodes' identifiers derive from it and their paths.
1990
    node_seed: Option<[u8; 32]>,
1991
    /// For a Git import, the base's dead directories by where they were
1992
    /// (see `ensure_dir`), worked out when first needed.
1993
    dead_dirs: Option<HashMap<(NodeId, String), (NodeId, crate::tree::OpKey)>>,
1994
    /// Text edits of edited files, worked out in parallel beforehand
1995
    /// (`diff_in_parallel`); a file not here is diffed when it is updated.
1996
    diffs: HashMap<String, Vec<Edit>>,
1997
}
1998
1999
impl<'a> ChangeBuilder<'a> {
20001863×
    fn new(
20011863×
        base: &'a State,
20021863×
        base_snapshot: &'a Snapshot,
20031863×
        reuse: HashMap<String, (NodeId, NodeKind)>,
20041863×
    ) -> Self {
20051863×
        let mut dir_nodes: HashMap<String, NodeId> = HashMap::new();
20061863×
        dir_nodes.insert(String::new(), NodeId::ROOT);
200717602×
        for (p, e) in base_snapshot.tree.entries.iter() {
200817602×
            if e.kind == NodeKind::Dir {
2009543×
                dir_nodes.insert(p.clone(), e.node);
201017059×
            }
2011
        }
20121863×
        ChangeBuilder {
20131863×
            base,
20141863×
            base_snapshot,
20151863×
            tree_ops: vec![],
20161863×
            edits: vec![],
20171863×
            statuses: vec![],
20181863×
            dir_nodes,
20191863×
            reuse,
20201863×
            contributors: BTreeSet::new(),
20211863×
            resolves: false,
20221863×
            attrs: crate::attributes::Attributes::default(),
20231863×
            blobs: HashMap::new(),
20241863×
            resolve: HashSet::new(),
20251863×
            node_seed: None,
20261863×
            dead_dirs: None,
20271863×
            diffs: HashMap::new(),
20281863×
        }
20291863×
    }
2030
2031
    /// Diff the edited text files among `entries` against their base
2032
    /// renderings at once, on every core, for `update_path` to take: the
2033
    /// same diff it would make, only not one file after another.
20341863×
    fn diff_in_parallel(&mut self, entries: &BTreeMap<String, FsEntry>) {
2035
        use rayon::prelude::*;
20361863×
        let files = &self.base_snapshot.files;
20371863×
        let edited: Vec<(&String, &FsEntry, &crate::state::FileState)> = entries
20381863×
            .iter()
203918563×
            .filter_map(|(p, e)| {
204018563×
                let x = files.get(p)?;
204112600×
                (x.kind == e.kind && !e.unchanged && !self.opaque_for(p, e)).then_some((p, e, x))
204218563×
            })
20431863×
            .collect();
2044
        // Below this, starting the threads costs more than it saves.
20451863×
        if edited.len() < 16 {
20461853×
            return;
204710×
        }
204810×
        let this = &*self;
204910×
        let attrs = &this.attrs;
205010×
        let diffs: Vec<(String, Vec<Edit>)> = edited
205110×
            .par_iter()
20525564×
            .filter_map(|(p, e, x)| {
2053
                let FileContent::Text {
20545564×
                    bytes,
20555564×
                    materialized,
20565564×
                } = &x.content
2057
                else {
20580×
                    return None;
2059
                };
20605564×
                if materialized.is_conflicted() {
20610×
                    return None;
20625564×
                }
20635564×
                let disk_text = if attrs.lookup(p).eol.is_some() {
20640×
                    std::sync::Arc::new(crate::attributes::normalize_eol(&e.content))
2065
                } else {
20665564×
                    e.content.clone()
2067
                };
20685564×
                if *bytes == *disk_text {
20695484×
                    return None;
207080×
                }
207180×
                let keys = materialized.live_atoms();
207280×
                let lines = crate::diff::split_lines(bytes);
207380×
                (keys.len() == lines.len()).then(|| {
207480×
                    let edits = crate::diff::text_edits_of(x.node, &keys, &lines, &disk_text);
207580×
                    ((*p).clone(), edits)
207680×
                })
20775564×
            })
207810×
            .collect();
207910×
        self.diffs = diffs.into_iter().collect();
20801863×
    }
2081
20821863×
    fn with_attributes(mut self, attrs: crate::attributes::Attributes) -> Self {
20831863×
        self.attrs = attrs;
20841863×
        self
20851863×
    }
2086
2087
    /// Whether a file is opaque: forced by `binary`, forced text by `text`
2088
    /// only when it has no NUL bytes, else sniffed.
2089
    /// The blob for an opaque entry: the cached one, else stored now.
2090126×
    fn blob_of(
2091126×
        &mut self,
2092126×
        repo: &Repo,
2093126×
        path: &str,
2094126×
        e: &FsEntry,
2095126×
        nocompress: bool,
2096126×
    ) -> Result<ObjectRef> {
2097126×
        let b = match e.blob {
20980×
            Some(b) => b,
2099126×
            None => repo.store_blob_for(&e.content, nocompress)?,
2100
        };
2101126×
        self.blobs.insert(path.to_string(), b);
2102126×
        Ok(b)
2103126×
    }
2104
210522676×
    fn opaque_for(&self, path: &str, e: &FsEntry) -> bool {
210622676×
        if e.blob.is_some() {
21078×
            return true;
210822668×
        }
210922668×
        if e.kind == NodeKind::Symlink || e.kind == NodeKind::Subrepo {
211075×
            return true;
211122593×
        }
211222593×
        match self.attrs.lookup(path).binary {
211312×
            Some(true) => true,
21140×
            Some(false) => is_binary(&e.content),
211522581×
            None => is_binary(&e.content),
2116
        }
211722676×
    }
2118
2119
    /// Text content as stored: `\r\n` normalized for `eol=` files.
212014193×
    fn stored_text(
212114193×
        &self,
212214193×
        path: &str,
212314193×
        content: &std::sync::Arc<Vec<u8>>,
212414193×
    ) -> std::sync::Arc<Vec<u8>> {
212514193×
        if self.attrs.lookup(path).eol.is_some() {
21267×
            std::sync::Arc::new(crate::attributes::normalize_eol(content))
2127
        } else {
212814186×
            content.clone()
2129
        }
213014193×
    }
2131
2132
    /// The identifier of a node added at `path`: reused when asked, derived
2133
    /// from the seed when there is one, random otherwise.
21346084×
    fn new_node(&self, path: &str, kind: NodeKind) -> NodeId {
21356084×
        if let Some(n) = self.reused_node(path, kind) {
2136134×
            return n;
21375950×
        }
21385950×
        match &self.node_seed {
213957×
            Some(seed) => seeded_node(seed, path, kind),
21405893×
            None => NodeId::random(),
2141
        }
21426084×
    }
2143
21446084×
    fn reused_node(&self, path: &str, kind: NodeKind) -> Option<NodeId> {
21456084×
        self.reuse
21466084×
            .get(path)
21476084×
            .filter(|(_, k)| *k == kind)
21486084×
            .map(|(n, _)| *n)
21496084×
    }
2150
2151
    /// A dead directory last placed at (`parent`, `name`) in the base.
215215×
    fn revivable_dir(
215315×
        &mut self,
215415×
        parent: NodeId,
215515×
        name: &str,
215615×
    ) -> Option<(NodeId, crate::tree::OpKey)> {
215715×
        let base = self.base;
215815×
        self.dead_dirs
215915×
            .get_or_insert_with(|| base.tree().dead_dirs())
216015×
            .get(&(parent, name.to_string()))
216115×
            .copied()
216215×
    }
2163
21645964×
    fn ensure_dir(&mut self, path: &str) -> NodeId {
21655964×
        if let Some(n) = self.dir_nodes.get(path) {
21665816×
            return *n;
2167148×
        }
2168148×
        let mut parent = NodeId::ROOT;
2169148×
        let mut prefix = String::new();
2170167×
        for comp in path.split('/') {
2171167×
            if !prefix.is_empty() {
217219×
                prefix.push('/');
2173148×
            }
2174167×
            prefix.push_str(comp);
2175167×
            let known = self.dir_nodes.get(&prefix).copied();
2176167×
            let revive = match known {
217713×
                Some(_) => None,
2178154×
                None if self.node_seed.is_some() => self.revivable_dir(parent, comp),
2179139×
                None => None,
2180
            };
2181167×
            parent = match (known, revive) {
218213×
                (Some(n), _) => n,
21832×
                (None, Some((node, old))) => {
2184
                    // Git has no identity for a directory: one that comes
2185
                    // back where it was is the same directory, brought back
2186
                    // with a move, so lines of history that placed files in
2187
                    // it before and after agree (oxygen#30).
21882×
                    self.tree_ops.push(TreeOp::Move {
21892×
                        node,
21902×
                        old: OpRef {
21912×
                            change: old.0,
21922×
                            index: old.1,
21932×
                        },
21942×
                        parent,
21952×
                        name: comp.to_string(),
21962×
                    });
21972×
                    self.dir_nodes.insert(prefix.clone(), node);
21982×
                    node
2199
                }
2200
                (None, None) => {
2201152×
                    let node = self.new_node(&prefix, NodeKind::Dir);
2202152×
                    self.tree_ops.push(TreeOp::AddNode {
2203152×
                        node,
2204152×
                        kind: NodeKind::Dir,
2205152×
                        mode: Mode::default(),
2206152×
                        parent,
2207152×
                        name: comp.to_string(),
2208152×
                    });
2209152×
                    self.dir_nodes.insert(prefix.clone(), node);
2210152×
                    node
2211
                }
2212
            };
2213
        }
2214148×
        parent
22155964×
    }
2216
22175932×
    fn add_path(&mut self, repo: &Repo, path: &str, e: &FsEntry) -> Result<()> {
22185932×
        let (dir, name) = split_path(path);
22195932×
        let parent = self.ensure_dir(dir);
22205932×
        let node = self.new_node(path, e.kind);
22215932×
        let opaque = self.opaque_for(path, e);
22225932×
        let nocompress = self.attrs.lookup(path).nocompress;
22235932×
        self.tree_ops.push(TreeOp::AddNode {
22245932×
            node,
22255932×
            kind: e.kind,
22265932×
            mode: Mode {
22275932×
                exec: e.exec,
22285932×
                opaque,
22295932×
            },
22305932×
            parent,
22315932×
            name: name.to_string(),
22325932×
        });
22335932×
        if opaque {
223491×
            let blob = self.blob_of(repo, path, e, nocompress)?;
223591×
            self.edits.push(Edit::Replace {
223691×
                node,
223791×
                old: None,
223891×
                new: Some(blob),
223991×
            });
22405841×
        } else if !e.content.is_empty() {
22415805×
            let content = self.stored_text(path, &e.content);
22425805×
            self.edits.push(Edit::Insert {
22435805×
                node,
22445805×
                after: crate::objects::AtomRef::Start,
22455805×
                before: crate::objects::AtomRef::End,
22465805×
                lines: crate::lines::Lines::split_shared(content),
22475805×
            });
22485805×
        }
22495932×
        self.statuses.push(PathStatus {
22505932×
            path: path.to_string(),
22515932×
            status: ChangeStatus::Added,
22525932×
        });
22535932×
        Ok(())
22545932×
    }
2255
2256
    /// Move the node at `old` to `new` and apply `e`'s content to it.
225732×
    fn move_path(
225832×
        &mut self,
225932×
        repo: &Repo,
226032×
        old: &str,
226132×
        new: &str,
226232×
        e: &FsEntry,
226332×
        expected: &crate::state::FileState,
226432×
    ) -> Result<()> {
226532×
        let placement = self.base_snapshot.tree.entries[old].placement;
226632×
        let (dir, name) = split_path(new);
226732×
        let parent = self.ensure_dir(dir);
226832×
        self.tree_ops.push(TreeOp::Move {
226932×
            node: expected.node,
227032×
            old: op_ref(placement),
227132×
            parent,
227232×
            name: name.to_string(),
227332×
        });
227432×
        for k in self.same_place(&expected.node, placement) {
22750×
            self.tree_ops.push(TreeOp::RemoveNode {
22760×
                node: expected.node,
22770×
                placement: op_ref(k),
22780×
            });
22790×
        }
228032×
        self.update_path(repo, old, e, expected)?;
2281
        // update_path reports under the old path; the rename is what the user sees.
228232×
        self.statuses.retain(|s| s.path != old);
228332×
        self.statuses.push(PathStatus {
228432×
            path: new.to_string(),
228532×
            status: ChangeStatus::Renamed,
228632×
        });
228732×
        Ok(())
228832×
    }
2289
2290
    /// For a Git import: a node the commit keeps is in one place, the one
2291
    /// its tree names, so any other live placement it has in the base goes;
2292
    /// and a node the tree cannot show at all (an orphan) goes too. Such a
2293
    /// placement is out of sight, under a directory another line of history
2294
    /// removed, where no diff of the tree would ever reach it (oxygen#30).
229586×
    fn retire_stray_placements(&mut self) {
229686×
        let mut retired: HashSet<(ChangeHash, u32)> = HashSet::new();
229786×
        let mut placed: BTreeSet<NodeId> = BTreeSet::new();
229897×
        for op in &self.tree_ops {
229997×
            match op {
230019×
                TreeOp::Move { node, old, .. } => {
230119×
                    retired.insert((old.change, old.index));
230219×
                    placed.insert(*node);
230319×
                }
230421×
                TreeOp::RemoveNode { placement, .. } => {
230521×
                    retired.insert((placement.change, placement.index));
230621×
                }
230757×
                TreeOp::AddNode { .. } | TreeOp::SetMode { .. } => {}
2308
            }
2309
        }
2310
        // Nodes kept where they were: what the base's tree view shows and
2311
        // this change neither moves nor removes.
231286×
        let mut kept: HashMap<NodeId, (ChangeHash, u32)> = HashMap::new();
2313240×
        for e in self.base_snapshot.tree.entries.values() {
2314240×
            if !retired.contains(&e.placement) {
2315203×
                kept.insert(e.node, e.placement);
2316203×
            }
2317
        }
2318
        // Only a node with several live placements can have a stray one,
2319
        // and the tree view names each as a conflict.
232086×
        let multi: BTreeSet<NodeId> = self
232186×
            .base_snapshot
232286×
            .tree
232386×
            .conflicts
232486×
            .iter()
232586×
            .filter_map(|c| match c {
23261×
                crate::tree::TreeConflict::MultiPlacement { node, .. } => Some(*node),
23276×
                _ => None,
23287×
            })
232986×
            .collect();
233086×
        let mut extra = Vec::new();
2331
        // A node whose only placements are under a directory another line
2332
        // removed (an orphan) is nowhere the tree can show, and Git's tree
2333
        // has no such path: it goes.
233486×
        for c in &self.base_snapshot.tree.conflicts {
23357×
            let crate::tree::TreeConflict::Orphan { node, .. } = c else {
23366×
                continue;
2337
            };
23381×
            if kept.contains_key(node) || placed.contains(node) {
23390×
                continue;
23401×
            }
23411×
            for (k, _) in self.base.tree().live_placements(node) {
23421×
                if retired.insert(k) {
23431×
                    extra.push(TreeOp::RemoveNode {
23441×
                        node: *node,
23451×
                        placement: op_ref(k),
23461×
                    });
23471×
                }
2348
            }
2349
        }
235086×
        for node in placed
235186×
            .iter()
235286×
            .chain(multi.iter().filter(|n| kept.contains_key(*n)))
2353
        {
235419×
            for (k, _) in self.base.tree().live_placements(node) {
235518×
                if retired.contains(&k) || kept.get(node) == Some(&k) {
235617×
                    continue;
23571×
                }
23581×
                retired.insert(k);
23591×
                extra.push(TreeOp::RemoveNode {
23601×
                    node: *node,
23611×
                    placement: op_ref(k),
23621×
                });
2363
            }
2364
        }
236586×
        if !extra.is_empty() {
23662×
            self.resolves = true;
23672×
            self.tree_ops.extend(extra);
236884×
        }
236986×
    }
2370
2371
    /// The node's other live placements at the same place as `k`, the one
2372
    /// the tree shows: two lines of history that put a node back where it
2373
    /// was each leave a placement, and the tree shows them as one file. A
2374
    /// change that removes or moves it retires them together, or the copy
2375
    /// left behind outlives its directory (oxygen#88).
2376151×
    fn same_place(&self, node: &NodeId, k: (ChangeHash, u32)) -> Vec<(ChangeHash, u32)> {
2377151×
        let tree = self.base.tree();
2378151×
        let Some(shown) = tree.placement(&k) else {
23790×
            return Vec::new();
2380
        };
2381151×
        tree.live_placements(node)
2382151×
            .into_iter()
2383153×
            .filter(|(o, p)| *o != k && p.parent == shown.parent && p.name == shown.name)
2384151×
            .map(|(o, _)| o)
2385151×
            .collect()
2386151×
    }
2387
2388119×
    fn remove_path(&mut self, path: &str, expected: &crate::state::FileState) {
2389119×
        let entry = &self.base_snapshot.tree.entries[path];
2390119×
        let placement = entry.placement;
2391119×
        self.tree_ops.push(TreeOp::RemoveNode {
2392119×
            node: expected.node,
2393119×
            placement: op_ref(placement),
2394119×
        });
2395119×
        for k in self.same_place(&expected.node, placement) {
23961×
            self.tree_ops.push(TreeOp::RemoveNode {
23971×
                node: expected.node,
23981×
                placement: op_ref(k),
23991×
            });
24001×
        }
2401119×
        if path.contains(".oxy-conflict-") || expected.is_conflicted() {
24027×
            self.resolves = true;
2403112×
        }
2404119×
        self.statuses.push(PathStatus {
2405119×
            path: path.to_string(),
2406119×
            status: ChangeStatus::Removed,
2407119×
        });
2408119×
    }
2409
241012632×
    fn update_path(
241112632×
        &mut self,
241212632×
        repo: &Repo,
241312632×
        path: &str,
241412632×
        e: &FsEntry,
241512632×
        expected: &crate::state::FileState,
241612632×
    ) -> Result<()> {
241712632×
        if expected.kind != e.kind {
24181×
            self.remove_path(path, expected);
24191×
            self.statuses.pop();
24201×
            self.add_path(repo, path, e)?;
24211×
            self.statuses.pop();
24221×
            self.statuses.push(PathStatus {
24231×
                path: path.to_string(),
24241×
                status: ChangeStatus::Modified,
24251×
            });
24261×
            return Ok(());
242712631×
        }
242812631×
        let entry = &self.base_snapshot.tree.entries[path];
242912631×
        let node = expected.node;
243012631×
        let mode_atom = entry.mode_atom.map(op_ref);
243112631×
        if e.unchanged {
2432
            // Known equal to the base's unconflicted rendering (spec
2433
            // §12.3); only the executable bit can differ.
24344243×
            if e.exec != expected.mode.exec {
24353×
                if let Some(old) = mode_atom {
24363×
                    self.tree_ops.push(TreeOp::SetMode {
24373×
                        node,
24383×
                        old,
24393×
                        mode: Mode {
24403×
                            exec: e.exec,
24413×
                            opaque: false,
24423×
                        },
24433×
                    });
24443×
                    self.statuses.push(PathStatus {
24453×
                        path: path.to_string(),
24463×
                        status: ChangeStatus::ModeChanged,
24473×
                    });
24483×
                }
24494240×
            }
24504243×
            return Ok(());
24518388×
        }
24528388×
        let mut status: Option<ChangeStatus> = None;
24538388×
        let wants_opaque = self.opaque_for(path, e);
24548388×
        let nocompress = self.attrs.lookup(path).nocompress;
24558388×
        let disk_text = self.stored_text(path, &e.content);
24568388×
        match &expected.content {
24570×
            FileContent::Dir => {}
2458
            FileContent::Text {
24598165×
                bytes,
24608165×
                materialized,
2461
            } => {
24628165×
                if materialized.is_conflicted() {
246333×
                    if bytes == &*disk_text {
24646×
                        return Ok(());
246527×
                    }
246627×
                    if has_conflict_markers(&e.content) {
24674×
                        self.statuses.push(PathStatus {
24684×
                            path: path.to_string(),
24694×
                            status: ChangeStatus::ConflictEdited,
24704×
                        });
24714×
                        return Ok(());
247223×
                    }
2473
                    // Resolution (spec §9.6): diff against the unconflicted lines
2474
                    // with each region as a gap, then retire every region atom.
2475
                    // Whatever the author kept from a region is re-inserted as
2476
                    // new atoms, which leaves the graph totally ordered.
247723×
                    let regions = self.base.conflict_regions(&node);
247823×
                    let mut edits = text_edits(node, &regions.plain, &disk_text);
247923×
                    if !regions.region_atoms.is_empty() {
248023×
                        edits.insert(
248123×
                            0,
248223×
                            Edit::Delete {
248323×
                                node,
248423×
                                atoms: ranges(&regions.region_atoms),
248523×
                            },
248623×
                        );
248723×
                    }
248823×
                    self.edits.extend(edits);
248923×
                    self.contributors.extend(regions.contributors);
249023×
                    self.resolves = true;
249123×
                    if e.exec != expected.mode.exec {
24920×
                        if let Some(old) = mode_atom {
24930×
                            self.tree_ops.push(TreeOp::SetMode {
24940×
                                node,
24950×
                                old,
24960×
                                mode: Mode {
24970×
                                    exec: e.exec,
24980×
                                    opaque: false,
24990×
                                },
25000×
                            });
25010×
                        }
250223×
                    }
250323×
                    self.statuses.push(PathStatus {
250423×
                        path: path.to_string(),
250523×
                        status: ChangeStatus::Resolved,
250623×
                    });
250723×
                    return Ok(());
25088132×
                }
25098132×
                if wants_opaque {
2510
                    // Text → opaque (spec §7.5), by content or by attribute.
25112×
                    if let Some(old) = mode_atom {
25122×
                        self.tree_ops.push(TreeOp::SetMode {
25132×
                            node,
25142×
                            old,
25152×
                            mode: Mode {
25162×
                                exec: e.exec,
25172×
                                opaque: true,
25182×
                            },
25192×
                        });
25202×
                    }
25212×
                    let live: Vec<_> = repo_live_keys(self.base, &node);
25222×
                    if !live.is_empty() {
25232×
                        self.edits.push(Edit::Delete {
25242×
                            node,
25252×
                            atoms: ranges(&live),
25262×
                        });
25272×
                    }
25282×
                    let blob = self.blob_of(repo, path, e, nocompress)?;
25292×
                    self.edits.push(Edit::Replace {
25302×
                        node,
25312×
                        old: None,
25322×
                        new: Some(blob),
25332×
                    });
25342×
                    status = Some(ChangeStatus::Modified);
25358130×
                } else if bytes != &*disk_text {
2536776×
                    let mut laps = crate::timing::Laps::start();
2537
                    // The base's rendering holds its live atoms in order,
2538
                    // one per line (it is not conflicted here).
2539776×
                    let edits = match self.diffs.remove(path) {
254080×
                        Some(edits) => edits,
2541
                        None => {
2542696×
                            let keys = materialized.live_atoms();
2543696×
                            let lines = crate::diff::split_lines(bytes);
2544696×
                            if keys.len() == lines.len() {
2545696×
                                crate::diff::text_edits_of(node, &keys, &lines, &disk_text)
2546
                            } else {
25470×
                                text_edits(node, &self.base.live_lines(&node), &disk_text)
2548
                            }
2549
                        }
2550
                    };
2551776×
                    laps.lap("build: text diff");
2552776×
                    if !edits.is_empty() {
2553776×
                        self.edits.extend(edits);
2554776×
                        status = Some(ChangeStatus::Modified);
2555776×
                    }
25567354×
                }
25578132×
                let switched_to_opaque = wants_opaque;
25588132×
                if !switched_to_opaque && e.exec != expected.mode.exec {
25594×
                    if let Some(old) = mode_atom {
25604×
                        self.tree_ops.push(TreeOp::SetMode {
25614×
                            node,
25624×
                            old,
25634×
                            mode: Mode {
25644×
                                exec: e.exec,
25654×
                                opaque: false,
25664×
                            },
25674×
                        });
25684×
                        status.get_or_insert(ChangeStatus::ModeChanged);
25694×
                    }
25708128×
                }
2571
            }
2572223×
            FileContent::Opaque { blobs } => {
2573223×
                let new_ref = e.blob.unwrap_or_else(|| Repo::blob_ref(&e.content));
2574223×
                if e.kind == NodeKind::File && wants_opaque {
2575191×
                    // Unchanged or replaced, the file stays opaque: remember its blob.
2576191×
                    self.blobs.insert(path.to_string(), new_ref);
2577191×
                }
2578223×
                if blobs.len() > 1 && self.resolve.contains(path) && e.kind == expected.kind {
2579
                    // Settle the replace conflict (spec §9.3): replace every
2580
                    // live candidate with the chosen blob, depending on each
2581
                    // change that made one live, so all are superseded.
25822×
                    let chosen = self.blob_of(repo, path, e, nocompress)?;
25834×
                    for b in blobs {
25844×
                        self.edits.push(Edit::Replace {
25854×
                            node,
25864×
                            old: Some(*b),
25874×
                            new: Some(chosen),
25884×
                        });
25894×
                    }
25902×
                    self.contributors
25912×
                        .extend(self.base.blob_contributors(&node, blobs));
25922×
                    self.resolves = true;
25932×
                    self.statuses.push(PathStatus {
25942×
                        path: path.to_string(),
25952×
                        status: ChangeStatus::Resolved,
25962×
                    });
25972×
                    return Ok(());
2598221×
                }
2599221×
                if blobs.len() > 1 {
26002×
                    if !blobs.contains(&new_ref) {
26010×
                        self.statuses.push(PathStatus {
26020×
                            path: path.to_string(),
26030×
                            status: ChangeStatus::ConflictEdited,
26040×
                        });
26052×
                    }
26062×
                    return Ok(());
2607219×
                }
2608219×
                let current = blobs.first().copied();
2609219×
                if current != Some(new_ref) {
261033×
                    if e.kind == NodeKind::File && !wants_opaque {
2611
                        // Opaque → text (spec §7.5).
26122×
                        if let Some(old) = mode_atom {
26132×
                            self.tree_ops.push(TreeOp::SetMode {
26142×
                                node,
26152×
                                old,
26162×
                                mode: Mode {
26172×
                                    exec: e.exec,
26182×
                                    opaque: false,
26192×
                                },
26202×
                            });
26212×
                        }
26222×
                        self.edits.push(Edit::Replace {
26232×
                            node,
26242×
                            old: current,
26252×
                            new: None,
26262×
                        });
26272×
                        if !e.content.is_empty() {
26282×
                            self.edits.push(Edit::Insert {
26292×
                                node,
26302×
                                after: crate::objects::AtomRef::Start,
26312×
                                before: crate::objects::AtomRef::End,
26322×
                                lines: crate::lines::Lines::split(&e.content),
26332×
                            });
26342×
                        }
2635
                    } else {
263631×
                        let blob = self.blob_of(repo, path, e, nocompress)?;
263731×
                        self.edits.push(Edit::Replace {
263831×
                            node,
263931×
                            old: current,
264031×
                            new: Some(blob),
264131×
                        });
2642
                        // New contents and a new executable bit at once: the
2643
                        // bit was dropped (VS Code's inno_updater.exe,
2644
                        // 2018-02-28, lost +x for 49 commits; oxygen#87).
264531×
                        if e.kind == NodeKind::File && e.exec != expected.mode.exec {
26462×
                            if let Some(old) = mode_atom {
26472×
                                self.tree_ops.push(TreeOp::SetMode {
26482×
                                    node,
26492×
                                    old,
26502×
                                    mode: Mode {
26512×
                                        exec: e.exec,
26522×
                                        opaque: true,
26532×
                                    },
26542×
                                });
26552×
                            }
265629×
                        }
2657
                    }
265833×
                    status = Some(ChangeStatus::Modified);
2659186×
                } else if e.kind == NodeKind::File && e.exec != expected.mode.exec {
26600×
                    if let Some(old) = mode_atom {
26610×
                        self.tree_ops.push(TreeOp::SetMode {
26620×
                            node,
26630×
                            old,
26640×
                            mode: Mode {
26650×
                                exec: e.exec,
26660×
                                opaque: true,
26670×
                            },
26680×
                        });
26690×
                        status = Some(ChangeStatus::ModeChanged);
26700×
                    }
2671186×
                }
2672
            }
2673
        }
26748351×
        if let Some(s) = status {
2675815×
            self.statuses.push(PathStatus {
2676815×
                path: path.to_string(),
2677815×
                status: s,
2678815×
            });
26797536×
        }
26808351×
        Ok(())
268112632×
    }
2682
}
2683
26842×
fn repo_live_keys(base: &State, node: &NodeId) -> Vec<crate::graph::AtomKey> {
26852×
    base.live_lines(node).into_iter().map(|(k, _)| k).collect()
26862×
}
2687
2688
/// The changes a change's scope references (spec §8.1): introducers of every
2689
/// atom, placement, and mode it touches, and of every node it operates on.
26901953×
pub fn referenced_changes(change: &Change, base: &State) -> BTreeSet<ChangeHash> {
26911953×
    let mut out = BTreeSet::new();
26921953×
    let opref = |r: &OpRef, out: &mut BTreeSet<ChangeHash>| {
2693179×
        if !r.change.is_zero() {
2694179×
            out.insert(r.change);
2695179×
        }
2696179×
    };
26971953×
    let mut nodes: Vec<NodeId> = Vec::new();
26986471×
    for op in &change.tree_ops {
26996471×
        match op {
27006292×
            TreeOp::AddNode { parent, .. } => nodes.push(*parent),
2701133×
            TreeOp::RemoveNode { node, placement } => {
2702133×
                nodes.push(*node);
2703133×
                opref(placement, &mut out);
2704133×
            }
2705
            TreeOp::Move {
270634×
                node, old, parent, ..
270734×
            } => {
270834×
                nodes.push(*node);
270934×
                nodes.push(*parent);
271034×
                opref(old, &mut out);
271134×
            }
271212×
            TreeOp::SetMode { node, old, .. } => {
271312×
                nodes.push(*node);
271412×
                opref(old, &mut out);
271512×
            }
2716
        }
2717
    }
27188009×
    for e in &change.edits {
27198009×
        nodes.push(e.node());
2720128×
        match e {
27217343×
            Edit::Insert { after, before, .. } => {
272214686×
                for r in [after, before] {
272314686×
                    if let crate::objects::AtomRef::Atom { change, .. } = r {
27242173×
                        if !change.is_zero() {
27252171×
                            out.insert(*change);
27262171×
                        }
272712513×
                    }
2728
                }
2729
            }
2730538×
            Edit::Delete { atoms, .. } => {
2731
                // Deleting an atom also depends on whoever inserted the live
2732
                // atoms right after it: the author saw those insertions, and
2733
                // without the dependency spec §9.1 would call the deletion
2734
                // concurrent with them (a delete/insert conflict).
2735538×
                let graph = base.file(&e.node());
27361095×
                for r in atoms {
27371095×
                    if !r.change.is_zero() {
27381094×
                        out.insert(r.change);
27391094×
                    }
27401095×
                    if let Some(g) = graph {
27411140×
                        for i in r.from..r.to {
27421140×
                            out.extend(
27431140×
                                g.live_successor_changes(&(r.change, i))
27441140×
                                    .into_iter()
27451140×
                                    .filter(|c| !c.is_zero()),
2746
                            );
2747
                        }
27480×
                    }
2749
                }
2750
            }
2751
            // Replacing a blob depends on the change that made it current,
2752
            // as deleting a line depends on the line's introducer.
2753
            Edit::Replace {
275438×
                node,
275538×
                old: Some(old),
2756
                ..
2757
            } => {
275838×
                out.extend(
275938×
                    base.live_replaces(node)
276038×
                        .into_iter()
276145×
                        .filter(|(c, b)| b == old && !c.is_zero())
276238×
                        .map(|(c, _)| c),
2763
                );
2764
            }
276590×
            Edit::Replace { .. } => {}
2766
        }
2767
    }
276814514×
    for n in nodes {
276914514×
        if let Some(h) = base.tree().introducer(&n) {
27702170×
            out.insert(h);
277112344×
        }
2772
    }
27731953×
    out
27741953×
}
2775
2776
/// Paths of the nodes a change adds on top of `base_snapshot`.
27771225×
pub fn added_node_paths(
27781225×
    change: &Change,
27791225×
    base_snapshot: &Snapshot,
27801225×
) -> HashMap<String, (NodeId, NodeKind)> {
27811225×
    let by_node = base_snapshot.tree.by_node();
27821225×
    let mut new_names: HashMap<NodeId, (NodeId, String, NodeKind)> = HashMap::new();
27831225×
    for op in &change.tree_ops {
2784
        if let TreeOp::AddNode {
278575×
            node,
278675×
            parent,
278775×
            name,
278875×
            kind,
2789
            ..
279098×
        } = op
279175×
        {
279275×
            new_names.insert(*node, (*parent, name.clone(), *kind));
279375×
        }
2794
    }
27951225×
    let mut out = HashMap::new();
27961225×
    for (node, (_, _, kind)) in &new_names {
279775×
        if let Some(path) = path_of_node(node, &by_node, &new_names) {
279875×
            out.insert(path, (*node, *kind));
279975×
        }
2800
    }
28011225×
    out
28021225×
}
2803
2804184×
fn path_of_node(
2805184×
    n: &NodeId,
2806184×
    by_node: &HashMap<NodeId, &crate::tree::TreeEntry>,
2807184×
    new_names: &HashMap<NodeId, (NodeId, String, NodeKind)>,
2808184×
) -> Option<String> {
2809184×
    if let Some(e) = by_node.get(n) {
281057×
        return Some(e.path.clone());
2811127×
    }
2812127×
    let mut parts = Vec::new();
2813127×
    let mut cur = *n;
2814
    loop {
2815253×
        if cur.is_root() {
2816113×
            break;
2817140×
        }
2818140×
        if let Some(e) = by_node.get(&cur) {
28190×
            if !e.path.is_empty() {
28200×
                parts.push(e.path.clone());
28210×
            }
28220×
            break;
2823140×
        }
2824140×
        let (parent, name, _) = new_names.get(&cur)?;
2825126×
        parts.push(name.clone());
2826126×
        cur = *parent;
2827
    }
2828113×
    parts.reverse();
2829113×
    Some(parts.join("/"))
2830184×
}
2831
2832
/// Render a change's operations with line content, using `base` for deleted lines.
283328×
pub fn render_change(change: &Change, base: &State, base_snapshot: &Snapshot) -> String {
283428×
    let by_node = base_snapshot.tree.by_node();
283528×
    let mut new_names: HashMap<NodeId, (NodeId, String, NodeKind)> = HashMap::new();
283628×
    for op in &change.tree_ops {
2837
        if let TreeOp::AddNode {
283815×
            node,
283915×
            parent,
284015×
            name,
284115×
            kind,
2842
            ..
284322×
        } = op
284415×
        {
284515×
            new_names.insert(*node, (*parent, name.clone(), *kind));
284615×
        }
2847
    }
284866×
    let path_of = |n: &NodeId| -> String {
284966×
        path_of_node(n, &by_node, &new_names).unwrap_or_else(|| format!("<node {}>", n.short(8)))
285066×
    };
2851
285228×
    let mut out = String::new();
285328×
    for op in &change.tree_ops {
285422×
        match op {
2855
            TreeOp::AddNode {
285615×
                node, kind, mode, ..
2857
            } => {
285815×
                out.push_str(&format!(
2859
                    "A {} ({:?}{}{})\n",
286015×
                    path_of(node),
2861
                    kind,
286215×
                    if mode.exec { ", exec" } else { "" },
286315×
                    if mode.opaque { ", opaque" } else { "" }
2864
                ));
2865
            }
28665×
            TreeOp::RemoveNode { node, .. } => out.push_str(&format!("D {}\n", path_of(node))),
2867
            TreeOp::Move {
28682×
                node, parent, name, ..
2869
            } => {
28702×
                let to = if parent.is_root() {
28710×
                    name.clone()
2872
                } else {
28732×
                    format!("{}/{name}", path_of(parent))
2874
                };
28752×
                out.push_str(&format!("R {} -> {to}\n", path_of(node)))
2876
            }
28770×
            TreeOp::SetMode { node, mode, .. } => {
28780×
                out.push_str(&format!(
28790×
                    "M {} mode: exec={} opaque={}\n",
28800×
                    path_of(node),
28810×
                    mode.exec,
28820×
                    mode.opaque
28830×
                ));
28840×
            }
2885
        }
2886
    }
2887
    // Every other file the change edits is modified: the summary names
2888
    // every path it touches, not only those with a tree operation.
288928×
    let with_op: HashSet<NodeId> = change.tree_ops.iter().map(|o| o.node()).collect();
289028×
    let mut listed: HashSet<NodeId> = HashSet::new();
289132×
    for e in &change.edits {
289232×
        let n = e.node();
289332×
        if !with_op.contains(&n) && listed.insert(n) {
289418×
            out.push_str(&format!("M {}\n", path_of(&n)));
289518×
        }
2896
    }
289728×
    let mut last_node: Option<NodeId> = None;
289832×
    for e in &change.edits {
289932×
        let n = e.node();
290032×
        if last_node != Some(n) {
290124×
            out.push_str(&format!("--- {}\n", path_of(&n)));
290224×
            last_node = Some(n);
290324×
        }
290432×
        match e {
290524×
            Edit::Insert { lines, .. } => {
290629×
                for l in lines.iter() {
290729×
                    out.push('+');
290829×
                    out.push_str(&String::from_utf8_lossy(l));
290929×
                    if !l.ends_with(b"\n") {
29100×
                        out.push('\n');
291129×
                    }
2912
                }
2913
            }
29147×
            Edit::Delete { atoms, .. } => {
29157×
                for r in atoms {
29167×
                    for i in r.from..r.to {
29177×
                        let content = base
29187×
                            .file(&n)
29197×
                            .and_then(|g| g.content(&(r.change, i)))
29207×
                            .unwrap_or(b"<unknown>\n");
29217×
                        out.push('-');
29227×
                        out.push_str(&String::from_utf8_lossy(content));
29237×
                        if !content.ends_with(b"\n") {
29240×
                            out.push('\n');
29257×
                        }
2926
                    }
2927
                }
2928
            }
29291×
            Edit::Replace { old, new, .. } => {
29301×
                out.push_str(&format!(
2931
                    "  opaque content {} -> {}\n",
29321×
                    old.map(|o| o.short(12)).unwrap_or_else(|| "none".into()),
29331×
                    new.map(|o| o.short(12)).unwrap_or_else(|| "none".into())
2934
                ));
2935
            }
2936
        }
2937
    }
293828×
    out
293928×
}
2940
2941
/// Pair removed files with added files of the same kind whose contents are
2942
/// at least `RENAME_THRESHOLD` percent alike, best matches first. Beyond
2943
/// `RENAME_LIMIT` candidate pairs only identical contents are paired.
2944
const RENAME_THRESHOLD: u32 = 50;
2945
const RENAME_LIMIT: usize = 10_000;
2946
2947
/// How a change is built beyond its entries: for a Git import, the seed
2948
/// its new nodes' identifiers derive from; and, when it is built from part
2949
/// of the tree, whether the new tree has anything under a directory.
2950
#[derive(Default)]
2951
struct Scope<'a> {
2952
    seed: Option<[u8; 32]>,
2953
    dir_needed: Option<&'a dyn Fn(&str) -> bool>,
2954
}
2955
29561863×
fn detect_renames(
29571863×
    base_snapshot: &Snapshot,
29581863×
    fs_entries: &BTreeMap<String, FsEntry>,
29591863×
    in_scope: impl Fn(&str) -> bool,
29601863×
) -> Vec<(String, String)> {
29611863×
    let removed: Vec<(&String, &crate::state::FileState)> = base_snapshot
29621863×
        .files
29631863×
        .iter()
296413144×
        .filter(|(p, f)| {
296513144×
            f.kind != NodeKind::Dir
296612733×
                && !fs_entries.contains_key(*p)
2967133×
                && in_scope(p)
2968123×
                && !f.is_conflicted()
296913144×
        })
29701863×
        .collect();
29711863×
    let added: Vec<(&String, &FsEntry)> = fs_entries
29721863×
        .iter()
297318563×
        .filter(|(p, e)| e.kind != NodeKind::Dir && !base_snapshot.files.contains_key(*p))
29741863×
        .collect();
29751863×
    if removed.is_empty() || added.is_empty() {
29761806×
        return vec![];
297757×
    }
297857×
    let exact_only = removed.len() * added.len() > RENAME_LIMIT;
297973×
    let old_content = |f: &crate::state::FileState| -> Option<Vec<u8>> {
298073×
        match &f.content {
298169×
            FileContent::Text { bytes, .. } => Some(bytes.clone()),
29824×
            _ => None,
2983
        }
298473×
    };
298557×
    let mut scored: Vec<(u32, usize, usize)> = Vec::new();
298673×
    for (ri, (_, f)) in removed.iter().enumerate() {
298773×
        let old = old_content(f);
298873×
        let old_blob = match &f.content {
29894×
            FileContent::Opaque { blobs } if blobs.len() == 1 => Some(blobs[0]),
299069×
            _ => None,
2991
        };
299293×
        for (ai, (_, e)) in added.iter().enumerate() {
299393×
            if e.kind != f.kind {
29940×
                continue;
299593×
            }
299693×
            let score = match (&old, old_blob) {
299783×
                (Some(o), _) => {
299883×
                    if exact_only {
29990×
                        if *o == *e.content {
30000×
                            100
3001
                        } else {
30020×
                            0
3003
                        }
3004
                    } else {
300583×
                        similarity(o, &e.content)
3006
                    }
3007
                }
300810×
                (None, Some(b)) if e.blob.unwrap_or_else(|| Repo::blob_ref(&e.content)) == b => 100,
30097×
                _ => 0,
3010
            };
301193×
            if score >= RENAME_THRESHOLD {
301238×
                scored.push((score, ri, ai));
301355×
            }
3014
        }
3015
    }
301657×
    scored.sort_by(|a, b| {
30179×
        b.0.cmp(&a.0)
30189×
            .then(removed[a.1].0.cmp(removed[b.1].0))
30199×
            .then(added[a.2].0.cmp(added[b.2].0))
30209×
    });
302157×
    let mut used_r = vec![false; removed.len()];
302257×
    let mut used_a = vec![false; added.len()];
302357×
    let mut out = Vec::new();
302457×
    for (_, ri, ai) in scored {
302538×
        if used_r[ri] || used_a[ai] {
30266×
            continue;
302732×
        }
302832×
        used_r[ri] = true;
302932×
        used_a[ai] = true;
303032×
        out.push((removed[ri].0.clone(), added[ai].0.clone()));
3031
    }
303257×
    out
30331863×
}
3034
3035
/// Percentage of the larger file's bytes found in lines the two share
3036
/// (multiset intersection of lines), like Git's similarity index.
303787×
pub fn similarity(a: &[u8], b: &[u8]) -> u32 {
303887×
    if a == b {
303922×
        return 100;
304065×
    }
304165×
    if a.is_empty() || b.is_empty() {
30428×
        return 0;
304357×
    }
304457×
    let mut counts: HashMap<&[u8], usize> = HashMap::new();
3045112×
    for l in split_lines(a) {
3046112×
        *counts.entry(l).or_default() += 1;
3047112×
    }
304857×
    let mut shared = 0usize;
3049109×
    for l in split_lines(b) {
3050109×
        if let Some(n) = counts.get_mut(l) {
305142×
            if *n > 0 {
305242×
                *n -= 1;
305342×
                shared += l.len();
305442×
            }
305567×
        }
3056
    }
305757×
    (shared * 100 / a.len().max(b.len())) as u32
305887×
}
3059
3060
#[cfg(test)]
3061
mod join_tests {
3062
    use super::*;
3063
3064
    #[test]
30651×
    fn missing_from_finds_what_the_other_lacks() {
30661×
        let a: BTreeMap<String, u8> = [("a", 1), ("b", 2), ("c/d", 3), ("e", 4)]
30671×
            .into_iter()
30684×
            .map(|(k, v)| (k.to_string(), v))
30691×
            .collect();
30701×
        let b: BTreeMap<String, ()> = [("0", ()), ("b", ()), ("c", ()), ("e", ())]
30711×
            .into_iter()
30724×
            .map(|(k, v)| (k.to_string(), v))
30731×
            .collect();
30741×
        let got: Vec<&str> = missing_from(&a, &b)
30751×
            .iter()
30762×
            .map(|(k, _)| k.as_str())
30771×
            .collect();
30781×
        assert_eq!(got, vec!["a", "c/d"]);
30791×
    }
3080
3081
    #[test]
30821×
    fn join_pairs_every_key_in_order() {
30831×
        let a: BTreeMap<String, u8> = [("a", 1), ("b/c", 2), ("d", 3)]
30841×
            .into_iter()
30853×
            .map(|(k, v)| (k.to_string(), v))
30861×
            .collect();
30871×
        let b: BTreeMap<String, char> = [("b", 'x'), ("b/c", 'y'), ("e", 'z')]
30881×
            .into_iter()
30893×
            .map(|(k, v)| (k.to_string(), v))
30901×
            .collect();
30911×
        let got: Vec<(String, Option<u8>, Option<char>)> = join(&a, &b)
30925×
            .map(|(k, x, y)| (k.clone(), x.copied(), y.copied()))
30931×
            .collect();
30941×
        let want = vec![
30951×
            ("a".to_string(), Some(1), None),
30961×
            ("b".to_string(), None, Some('x')),
30971×
            ("b/c".to_string(), Some(2), Some('y')),
30981×
            ("d".to_string(), Some(3), None),
30991×
            ("e".to_string(), None, Some('z')),
3100
        ];
31011×
        assert_eq!(got, want);
31021×
    }
3103
}