OXYGENHUB

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

2213 of 2445 lines run, 288 of 375 functions · run #332 on show-stat · 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
8123089×
pub fn is_binary(content: &[u8]) -> bool {
8223089×
    content[..content.len().min(BINARY_SNIFF)].contains(&0)
8323089×
}
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.
1051341×
    fn platform_normalize(&self, entries: &mut BTreeMap<String, FsEntry>, base: &Snapshot) {
1061341×
        let p = self.platform;
1071341×
        if p.exec_bits && p.symlinks {
1081339×
            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
        }
1221341×
    }
123
124
    /// Like `build_against`, for files given in memory (imports).
1251066×
    pub(crate) fn build_from_entries(
1261066×
        &self,
1271066×
        base: &State,
1281066×
        base_snapshot: &Snapshot,
1291066×
        reuse: HashMap<String, (NodeId, NodeKind)>,
1301066×
        fs_entries: &BTreeMap<String, FsEntry>,
1311066×
    ) -> Result<BuiltChange> {
1321066×
        self.build_from_entries_resolving(base, base_snapshot, reuse, fs_entries, &HashSet::new())
1331066×
    }
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.
1401081×
    pub(crate) fn build_from_entries_resolving(
1411081×
        &self,
1421081×
        base: &State,
1431081×
        base_snapshot: &Snapshot,
1441081×
        reuse: HashMap<String, (NodeId, NodeKind)>,
1451081×
        fs_entries: &BTreeMap<String, FsEntry>,
1461081×
        resolve: &HashSet<String>,
1471081×
    ) -> Result<BuiltChange> {
1481081×
        self.build_from_entries_with(
1491081×
            base,
1501081×
            base_snapshot,
1511081×
            reuse,
1521081×
            fs_entries,
1531081×
            resolve,
1541081×
            Scope::default(),
155
        )
1561081×
    }
157
158
    /// `build_from_entries` whose new nodes take identifiers derived from
159
    /// `seed` and their paths instead of random ones, so the same input
160
    /// always builds the same change (a Git import, spec §23).
161
    ///
162
    /// With `dir_needed`, the snapshot and entries hold only the paths the
163
    /// import touches (and the directories a removal may leave empty); a
164
    /// directory stays while `dir_needed` says the new tree has something
165
    /// under it.
16688×
    pub(crate) fn build_from_entries_seeded(
16788×
        &self,
16888×
        base: &State,
16988×
        base_snapshot: &Snapshot,
17088×
        fs_entries: &BTreeMap<String, FsEntry>,
17188×
        seed: [u8; 32],
17288×
        dir_needed: Option<&dyn Fn(&str) -> bool>,
17388×
    ) -> Result<BuiltChange> {
17488×
        self.build_from_entries_with(
17588×
            base,
17688×
            base_snapshot,
17788×
            HashMap::new(),
17888×
            fs_entries,
17988×
            &HashSet::new(),
18088×
            Scope {
18188×
                seed: Some(seed),
18288×
                dir_needed,
18388×
            },
184
        )
18588×
    }
186
187
    /// `build_from_entries` for a snapshot most of whose files are known
188
    /// unchanged (oxygen#41): only the paths that may differ are built
189
    /// (files read rather than known unchanged, base files gone from disk,
190
    /// and the directories those may leave empty), against a snapshot of
191
    /// just those, so a large tree with a few edits costs what they touch.
192879×
    fn build_changed_only(
193879×
        &self,
194879×
        base: &State,
195879×
        base_snapshot: &Snapshot,
196879×
        reuse: HashMap<String, (NodeId, NodeKind)>,
197879×
        fs_entries: &BTreeMap<String, FsEntry>,
198879×
    ) -> Result<BuiltChange> {
199879×
        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.
202879×
        let changed: BTreeMap<String, FsEntry> = join(fs_entries, &base_snapshot.files)
20311046×
            .filter_map(|(p, e, f)| {
20411046×
                let e = e?;
20510916×
                (!e.unchanged || f.is_none_or(|f| f.kind != e.kind || f.mode.exec != e.exec))
20610916×
                    .then(|| (p.clone(), e.clone()))
20711046×
            })
208879×
            .collect();
209879×
        let mut files: BTreeMap<String, crate::state::FileState> = BTreeMap::new();
2106687×
        for p in changed.keys() {
2116687×
            if let Some(f) = base_snapshot.files.get(p) {
2123681×
                files.insert(p.clone(), f.clone());
2133681×
            }
214
        }
215
        // Paths the base has and the disk does not.
216879×
        let gone = join(&base_snapshot.files, fs_entries)
21711046×
            .filter_map(|(p, f, e)| (e.is_none()).then_some((p, f?)));
218879×
        for (p, f) in gone {
219130×
            if f.kind == NodeKind::Dir {
22096×
                continue;
22134×
            }
22234×
            files.insert(p.clone(), f.clone());
22334×
            let mut end = p.len();
22439×
            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
        }
235879×
        let part = Snapshot {
236879×
            tree: base_snapshot.tree.clone(),
237879×
            files,
238879×
            unrendered: BTreeSet::new(),
239879×
        };
240879×
        drop(pick);
241879×
        let _build = crate::timing::phase("snapshot:   of which building the change");
242
        // Whether anything on disk is under `dir`.
243879×
        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×
        };
250879×
        self.build_from_entries_with(
251879×
            base,
252879×
            &part,
253879×
            reuse,
254879×
            &changed,
255879×
            &HashSet::new(),
256879×
            Scope {
257879×
                seed: None,
258879×
                dir_needed: Some(&dir_needed),
259879×
            },
260
        )
261879×
    }
262
2632048×
    fn build_from_entries_with(
2642048×
        &self,
2652048×
        base: &State,
2662048×
        base_snapshot: &Snapshot,
2672048×
        reuse: HashMap<String, (NodeId, NodeKind)>,
2682048×
        fs_entries: &BTreeMap<String, FsEntry>,
2692048×
        resolve: &HashSet<String>,
2702048×
        scope: Scope,
2712048×
    ) -> Result<BuiltChange> {
2722048×
        let Scope { seed, dir_needed } = scope;
2732048×
        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.
2762048×
        let attrs = crate::attributes::Attributes::from_files(
2772048×
            fs_entries
2782048×
                .iter()
27918872×
                .filter(|(p, _)| p.as_str() == ".oxyattributes" || p.ends_with("/.oxyattributes"))
2802048×
                .map(|(p, e)| (p.as_str(), e.content.as_slice())),
281
        );
2822048×
        let mut b = ChangeBuilder::new(base, base_snapshot, reuse).with_attributes(attrs);
2832048×
        b.resolve = resolve.clone();
2842048×
        b.node_seed = seed;
2852048×
        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.
2892048×
        let renames = detect_renames(base_snapshot, fs_entries, |p| self.in_scope(p));
2902048×
        let renamed_from: HashMap<&str, &str> = renames
2912048×
            .iter()
2922048×
            .map(|(old, new)| (new.as_str(), old.as_str()))
2932048×
            .collect();
2942048×
        let renamed_to: HashMap<&str, &str> = renames
2952048×
            .iter()
2962048×
            .map(|(old, new)| (old.as_str(), new.as_str()))
2972048×
            .collect();
2982048×
        laps.lap("build: renames");
2992048×
        b.diff_in_parallel(fs_entries);
3002048×
        laps.lap("build: diffs");
30118872×
        for (path, fs_entry) in fs_entries {
30218872×
            match base_snapshot.files.get(path) {
3036069×
                None => match renamed_from.get(path.as_str()) {
30433×
                    Some(old) => {
30533×
                        b.move_path(self, old, path, fs_entry, &base_snapshot.files[*old])?
306
                    }
3076036×
                    None => b.add_path(self, path, fs_entry)?,
308
                },
30912803×
                Some(expected) => b.update_path(self, path, fs_entry, expected)?,
310
            }
311
        }
3122048×
        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.
3152048×
        let mut needed_dirs: HashSet<&str> = HashSet::new();
31618885×
        fn parents_of<'a>(p: &'a str, set: &mut HashSet<&'a str>) {
31718885×
            let mut end = p.len();
31819556×
            while let Some(i) = p[..end].rfind('/') {
31915453×
                if !set.insert(&p[..i]) {
32014782×
                    break;
321671×
                }
322671×
                end = i;
323
            }
32418885×
        }
32518872×
        for p in fs_entries.keys() {
32618872×
            parents_of(p, &mut needed_dirs);
32718872×
        }
32813385×
        for p in base_snapshot.files.keys() {
32913385×
            if !self.in_scope(p) {
33013×
                parents_of(p, &mut needed_dirs);
33113372×
            }
332
        }
33313385×
        for (path, expected) in &base_snapshot.files {
33413385×
            if fs_entries.contains_key(path)
335582×
                || !self.in_scope(path)
336569×
                || renamed_to.contains_key(path.as_str())
337
            {
33812849×
                continue;
339536×
            }
340536×
            let still_needed = expected.kind == NodeKind::Dir
341433×
                && match dir_needed {
34221×
                    Some(f) => f(path),
343412×
                    None => needed_dirs.contains(path.as_str()),
344
                };
345536×
            if !still_needed {
346130×
                b.remove_path(path, expected);
347406×
            }
348
        }
3492048×
        laps.lap("build: removals");
3502048×
        if seed.is_some() {
35188×
            b.retire_stray_placements();
3521960×
        }
3532048×
        laps.lap("build: stray placements");
3542048×
        let mut statuses = b.statuses;
3555702×
        statuses.sort_by(|a, b| a.path.cmp(&b.path));
3562048×
        Ok(BuiltChange {
3572048×
            tree_ops: b.tree_ops,
3582048×
            edits: b.edits,
3592048×
            contributors: b.contributors.into_iter().collect(),
3602048×
            resolves: b.resolves,
3612048×
            statuses,
3622048×
            blobs: b.blobs,
3632048×
        })
3642048×
    }
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.
369718×
    pub(crate) fn store_signed(&self, change: &Change) -> Result<ChangeHash> {
370718×
        let ours = change.author == self.author();
371718×
        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");
373717×
        }
374717×
        let storing = crate::timing::phase("store: the change");
375717×
        let hash = self.store.put_change(change)?;
376717×
        drop(storing);
377717×
        if self.config.sign_changes && ours {
37841×
            let _t = crate::timing::phase("store: sign it");
37941×
            self.sign_change(&hash)?;
380676×
        }
381717×
        Ok(hash)
382718×
    }
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.
386460×
    pub fn snapshot(&self, command: &str) -> Result<SnapshotResult> {
387460×
        self.snapshot_as(command, false, false)
388460×
    }
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.
398422×
    pub fn snapshot_status(&self, command: &str) -> Result<SnapshotResult> {
399422×
        self.snapshot_as(command, true, false)
400422×
    }
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.
4091342×
    fn snapshot_as(
4101342×
        &self,
4111342×
        command: &str,
4121342×
        partial: bool,
4131342×
        for_commit: bool,
4141342×
    ) -> Result<SnapshotResult> {
4151342×
        let _lock = self.lock_snapshot()?;
4161342×
        let batch = self.store.begin_batch()?;
4171342×
        let result = self.snapshot_locked(command, partial, for_commit);
4181342×
        batch.finish()?;
4191342×
        result
4201342×
    }
421
4221342×
    fn snapshot_locked(
4231342×
        &self,
4241342×
        command: &str,
4251342×
        partial: bool,
4261342×
        for_commit: bool,
4271342×
    ) -> Result<SnapshotResult> {
4281342×
        let _all = crate::timing::phase("snapshot");
4291342×
        let (op_ref, op) = self.head_op()?;
4301342×
        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.
4331340×
        let mut base = {
4341340×
            let _t = crate::timing::phase("snapshot: load base history");
4351340×
            self.load_state_indexed(&old_wc.deps)?
436
        };
4371340×
        let view = {
4381340×
            let _t = crate::timing::phase("snapshot: tree view");
4391340×
            base.tree().view()
440
        };
4411340×
        let manifest = {
4421340×
            let _t = crate::timing::phase("snapshot: read manifest");
4431340×
            self.read_manifest()?.map(|(_, _, m)| m)
444
        };
4451340×
        let tracked: BTreeMap<String, (NodeKind, Option<ObjectRef>)> = {
4461340×
            let _t = crate::timing::phase("snapshot: tracked paths");
447
            // In the view's path order, so the map is built without searching.
4481340×
            view.entries
4491340×
                .iter()
4509602×
                .filter(|(_, e)| e.kind != NodeKind::Dir)
4519195×
                .map(|(p, e)| {
4529195×
                    let blob = if e.kind != NodeKind::File || e.mode.opaque {
453151×
                        base.live_blobs(&e.node).first().copied()
454
                    } else {
4559044×
                        None
456
                    };
4579195×
                    (p.clone(), (e.kind, blob))
4589195×
                })
4591340×
                .collect()
460
        };
461
        // A text file's graph key, worked out when the walk asks for it.
46212219×
        let key_of = |p: &str| -> Option<[u8; 32]> {
46312219×
            let e = view.entries.get(p)?;
4649093×
            if e.kind != NodeKind::File || e.mode.opaque {
465124×
                return None;
4668969×
            }
4678969×
            base.graph_key(&e.node)
46812219×
        };
4691339×
        let mut fs_entries = {
4701340×
            let _t = crate::timing::phase("snapshot: read working copy");
4711340×
            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.
4751339×
        let keys: HashMap<String, [u8; 32]> = fs_entries
4761339×
            .iter()
47712249×
            .filter(|(_, e)| !e.unchanged && e.kind == NodeKind::File)
4787978×
            .filter_map(|(p, _)| Some((p.clone(), key_of(p)?)))
4791339×
            .collect();
4801339×
        let base_snapshot = {
4811339×
            let _t = crate::timing::phase("snapshot: load and render base");
4821339×
            if partial {
483882×
                let sets = crate::timing::phase("snapshot:   of which choosing graphs");
484
                // Every file but those on disk known unchanged.
485882×
                let need: Vec<(&str, NodeId)> = join(&view.entries, &fs_entries)
48611061×
                    .filter_map(|(p, v, f)| {
48711061×
                        let v = v?;
4888054×
                        (v.kind == NodeKind::File && !f.is_some_and(|f| f.unchanged))
4898054×
                            .then_some((p.as_str(), v.node))
49011061×
                    })
491882×
                    .collect();
492882×
                let render: std::collections::HashSet<&str> =
493882×
                    need.iter().map(|(p, _)| *p).collect();
494882×
                let need: Vec<NodeId> = need.iter().map(|(_, n)| *n).collect();
495882×
                drop(sets);
496
                {
497882×
                    let _t = crate::timing::phase("snapshot:   of which building graphs");
498882×
                    self.load_graphs_of(&mut base, &need)?;
499
                }
500882×
                let _t = crate::timing::phase("snapshot:   of which rendering");
501882×
                base.materialize_only(&render)
502
            } else {
503457×
                self.load_all_graphs(&mut base)?;
504457×
                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).
5101339×
        let reuse = added_node_paths(&old_wc, &base_snapshot);
5111339×
        self.platform_normalize(&mut fs_entries, &base_snapshot);
5121339×
        let built = {
5131339×
            let _t = crate::timing::phase("snapshot: diff against base");
5141339×
            if partial && self.config.sparse_paths.is_empty() {
515
                #[cfg(test)]
516600×
                let full =
517600×
                    self.build_from_entries(&base, &base_snapshot, reuse.clone(), &fs_entries)?;
518879×
                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.
5231200×
                    let norm = |b: &BuiltChange| {
5241200×
                        let text = format!("{:?} {:?} {:?}", b.tree_ops, b.edits, b.statuses);
5251200×
                        let mut seen: Vec<String> = Vec::new();
5261200×
                        let mut out = String::new();
5271200×
                        let mut rest = text.as_str();
52819940×
                        while let Some(i) = rest.find("NodeId(") {
52918740×
                            out.push_str(&rest[..i]);
53018740×
                            let end = i + rest[i..].find(')').unwrap() + 1;
53118740×
                            let id = rest[i..end].to_string();
5329045984×
                            let n = seen.iter().position(|x| *x == id).unwrap_or_else(|| {
5337058×
                                seen.push(id);
5347058×
                                seen.len() - 1
5357058×
                            });
53618740×
                            out.push_str(&format!("N{n}"));
53718740×
                            rest = &rest[end..];
538
                        }
5391200×
                        out.push_str(rest);
5401200×
                        out
5411200×
                    };
542600×
                    assert_eq!(
543600×
                        norm(&built),
544600×
                        norm(&full),
545
                        "a changed-only build is the full one"
546
                    );
547
                }
548879×
                built
549
            } else {
550460×
                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
        {
5563808×
            let changed: HashSet<&str> = built.statuses.iter().map(|s| s.path.as_str()).collect();
55712249×
            for (p, e) in fs_entries.iter_mut() {
55812249×
                if e.unchanged || e.kind != NodeKind::File || changed.contains(p.as_str()) {
5597982×
                    continue;
5604267×
                }
5614267×
                e.graph_key = match base_snapshot.files.get(p).map(|f| &f.content) {
562
                    Some(FileContent::Text {
5634155×
                        bytes,
5644155×
                        materialized,
5654155×
                    }) if !materialized.is_conflicted() && *bytes == *e.content => {
5664149×
                        keys.get(p).copied()
567
                    }
568118×
                    _ => None,
569
                };
570
            }
571
        }
572
5731339×
        let mut wc = Change {
5741339×
            version: crate::objects::CHANGE_VERSION,
5751339×
            change_id: old_wc.change_id,
5761339×
            deps: vec![],
5771339×
            author: self.author(),
5781339×
            hlc: old_wc.hlc,
5791339×
            message: old_wc.message.clone(),
5801339×
            tree_ops: built.tree_ops,
5811339×
            edits: built.edits,
5821339×
            kind: ChangeKind::WorkingCopy,
5831339×
        };
5841339×
        let base_heads = base.maximal(&old_wc.deps);
5851339×
        let mut deps: BTreeSet<ChangeHash> = base_heads.into_iter().collect();
5861339×
        deps.extend(referenced_changes(&wc, &base));
5871339×
        deps.extend(built.contributors.iter().copied());
5881339×
        wc.deps = deps.into_iter().collect();
5891339×
        wc.normalize();
5901339×
        let resolves = built.resolves;
5911339×
        let contributors = built.contributors;
5921339×
        let statuses = built.statuses;
593
        // Empty snapshot: hash the candidate before storing; only record an op on change.
5941339×
        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.
6011339×
        let (new_hash, changed, encoded) = if for_commit {
602460×
            (old_hash, true, Vec::new())
603
        } else {
604879×
            let encoded = wc.encode_streaming(|batch| self.store.put_texts(&batch))?;
605879×
            let new_hash = crate::hash::hash_object(crate::hash::ObjectType::Change, &encoded);
606879×
            (new_hash, new_hash != old_hash, encoded)
607
        };
6081339×
        if changed && !for_commit {
609313×
            self.store.put(crate::hash::ObjectType::Change, &encoded)?;
610313×
            let mut view = op.view.clone();
611313×
            view.workspaces.insert(self.workspace, new_hash);
612313×
            self.record_op(&[op_ref], &format!("{command}{SNAPSHOT_SUFFIX}"), view)?;
6131026×
        }
6141339×
        drop(record);
615
        // The prompt compares against this without recording anything.
6161339×
        let _t = crate::timing::phase("snapshot: write manifest");
6171339×
        let conflicted = base_snapshot.is_conflicted();
6181339×
        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.
6231339×
        let worth = match self.read_manifest()? {
624460×
            _ if for_commit => true,
625329×
            None => true,
626550×
            Some((c, u, m)) => {
627550×
                c != conflicted
628550×
                    || u != uncommitted
629303×
                    || m.entries.len() != fs_entries.len()
630387×
                    || fs_entries.iter().any(|(p, e)| {
631387×
                        !e.unchanged && (e.graph_key.is_some() || !m.entries.contains_key(p))
632387×
                    })
63349×
                    || built
63449×
                        .blobs
63549×
                        .iter()
63649×
                        .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.
64066×
                    || (uncommitted && statuses.iter().any(|st| {
64166×
                        let Some(e) = fs_entries.get(&st.path) else {
6424×
                            return m.entries.contains_key(&st.path);
643
                        };
64462×
                        let Some(me) = m.entries.get(&st.path) else {
6450×
                            return true;
646
                        };
64762×
                        let hash = e
64862×
                            .content_hash
64962×
                            .unwrap_or_else(|| *blake3::hash(&e.content).as_bytes());
65062×
                        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.
65762×
                        me.hash != hash || me.exec != e.exec || stat != Some((me.size, me.mtime_ns))
65866×
                    }))
659
            }
660
        };
6611339×
        let attributes = crate::attributes::Attributes::from_files(
6621339×
            fs_entries
6631339×
                .iter()
66412249×
                .filter(|(p, _)| is_attributes(p))
6651339×
                .map(|(p, e)| (p.as_str(), e.content.as_slice())),
666
        );
6671339×
        let mut manifest = None;
6681339×
        if for_commit {
669460×
            manifest = Some(PendingManifest {
670460×
                entries: fs_entries,
671460×
                blobs: built.blobs.clone(),
672460×
                dirs: self.walked_dirs.take(),
673460×
                written: super::prompt::now_ns(),
674460×
            });
675460×
        } else {
676879×
            if worth {
677833×
                self.write_manifest_entries(conflicted, uncommitted, &fs_entries, &built.blobs)?;
67846×
            }
679879×
            self.write_status_cache((uncommitted && !conflicted).then_some(&new_hash), &statuses);
680
        }
6811339×
        Ok(SnapshotResult {
6821339×
            wc_hash: new_hash,
6831339×
            wc,
6841339×
            base,
6851339×
            base_snapshot,
6861339×
            statuses,
6871339×
            changed,
6881339×
            resolves,
6891339×
            contributors,
6901339×
            attributes,
6911339×
            untracked_nested: self.untracked_nested.borrow().clone(),
6921339×
            manifest,
6931339×
        })
6941342×
    }
695
696
    /// `oxy status --json` (spec §9.5): the changed paths and every conflict
697
    /// of the working copy's base with its kind, path, and contributing
698
    /// ChangeIds.
6997×
    pub fn status_json(&self, snap: &SnapshotResult) -> Result<String> {
7007×
        let heads = self.bookmark_heads()?;
7017×
        let base_snapshot = &snap.base_snapshot;
7027×
        let by_node = base_snapshot.tree.by_node();
7037×
        let path_of = |n: &NodeId| by_node.get(n).map(|e| e.path.clone());
7047×
        let id_of = |h: &ChangeHash| {
7054×
            snap.base
7064×
                .get(h)
7074×
                .map(|m| m.change_id.to_hex())
7084×
                .unwrap_or_else(|| h.to_hex())
7094×
        };
7107×
        let paths = json_array(snap.statuses.iter().map(|s| {
7114×
            format!(
712
                "{{\"path\":{},\"status\":{}}}",
7134×
                json_str(&s.path),
7144×
                json_str(&format!("{:?}", s.status))
715
            )
7164×
        }));
7177×
        let mut conflicts: Vec<String> = Vec::new();
7187×
        for (p, f) in &base_snapshot.files {
7197×
            if !f.is_conflicted() {
7205×
                continue;
7212×
            }
7222×
            let (kind, changes) = match &f.content {
723
                FileContent::Text { .. } => {
7242×
                    ("text", snap.base.conflict_regions(&f.node).contributors)
725
                }
7260×
                FileContent::Opaque { blobs } => {
7270×
                    ("replace", snap.base.blob_contributors(&f.node, blobs))
728
                }
7290×
                FileContent::Dir => continue,
730
            };
7312×
            let resolved = match snap
7322×
                .statuses
7332×
                .iter()
7342×
                .find(|s| s.path == *p)
7352×
                .map(|s| s.status)
736
            {
7371×
                Some(ChangeStatus::Resolved) => "true",
7380×
                Some(ChangeStatus::ConflictEdited) => "\"markers\"",
7391×
                _ => "false",
740
            };
7412×
            conflicts.push(format!(
742
                "{{\"kind\":{},\"path\":{},\"node\":{},\"changes\":{},\"resolved\":{resolved}}}",
7432×
                json_str(kind),
7442×
                json_str(p),
7452×
                json_str(&f.node.to_hex()),
7464×
                json_array(changes.iter().map(|h| json_str(&id_of(h))))
747
            ));
748
        }
7497×
        for c in &base_snapshot.tree.conflicts {
7500×
            let (kind, nodes): (&str, Vec<NodeId>) = match c {
7510×
                crate::tree::TreeConflict::Name { nodes, .. } => ("name", nodes.clone()),
7520×
                crate::tree::TreeConflict::MultiPlacement { node, .. } => {
7530×
                    ("multi-placement", vec![*node])
754
                }
7550×
                crate::tree::TreeConflict::Orphan { node, .. } => ("orphan", vec![*node]),
7560×
                crate::tree::TreeConflict::Cycle { node } => ("cycle", vec![*node]),
7570×
                crate::tree::TreeConflict::Mode { node, .. } => ("mode", vec![*node]),
758
            };
7590×
            let detail = match c {
7600×
                crate::tree::TreeConflict::Name { name, parent, .. } => {
7610×
                    let dir = if *parent == NodeId::ROOT {
7620×
                        String::new()
763
                    } else {
7640×
                        path_of(parent).unwrap_or_default()
765
                    };
7660×
                    format!(
767
                        ",\"path\":{}",
7680×
                        json_str(&if dir.is_empty() {
7690×
                            name.clone()
770
                        } else {
7710×
                            format!("{dir}/{name}")
772
                        })
773
                    )
774
                }
7750×
                _ => nodes
7760×
                    .first()
7770×
                    .and_then(path_of)
7780×
                    .map(|p| format!(",\"path\":{}", json_str(&p)))
7790×
                    .unwrap_or_default(),
780
            };
7810×
            conflicts.push(format!(
782
                "{{\"kind\":{},\"nodes\":{}{detail}}}",
7830×
                json_str(kind),
7840×
                json_array(nodes.iter().map(|n| json_str(&n.to_hex())))
785
            ));
786
        }
7877×
        Ok(format!(
788
            "{{\"bookmark\":{},\"working_copy\":{},\"heads\":{},\"clean\":{},\"conflicted\":{},\"paths\":{paths},\"conflicts\":{},\"untracked_nested\":{},\"skipped_large\":{}}}",
7897×
            json_str(&self.config.bookmark),
7907×
            json_str(&snap.wc.change_id.to_hex()),
7917×
            heads.len(),
7927×
            snap.statuses.is_empty(),
7937×
            base_snapshot.is_conflicted(),
7947×
            json_array(conflicts),
7957×
            json_array(snap.untracked_nested.iter().map(|p| json_str(p))),
7967×
            json_array(
7977×
                self.skipped_large
7987×
                    .borrow()
7997×
                    .iter()
8007×
                    .map(|(p, n)| format!("{{\"path\":{},\"size\":{n}}}", json_str(p)))
801
            )
802
        ))
8037×
    }
804
805
    /// Turn the working-copy change into a normal change on the bookmark (spec §12.3).
806660×
    pub fn commit(&self, message: &str, extra_deps: &[ChangeHash]) -> Result<ChangeHash> {
807660×
        self.commit_selection(message, extra_deps, &Selection::All)
808660×
    }
809
810
    /// The hunks of the working copy, for `oxy commit --interactive`: each
811
    /// tree operation and each edit, in the order `select_hunks` numbers them.
8127×
    pub fn hunks(&self) -> Result<(SnapshotResult, Vec<Hunk>)> {
8137×
        let snap = self.snapshot_status("oxy commit")?;
8147×
        let hunks = render_hunks(&snap.wc, &snap.base, &snap.base_snapshot);
8157×
        Ok((snap, hunks))
8167×
    }
817
818
    /// Commit part of the working copy (spec §12.3). What is not selected
819
    /// stays on disk as uncommitted work: the next snapshot rebuilds it
820
    /// against the new base, so the working copy always describes the
821
    /// directory.
822
    /// The graph key in `st` of each text file at `paths`, the paths a
823
    /// commit changed: only their graphs changed, so the keys the manifest
824
    /// holds for the others still stand (and any that does not is simply
825
    /// not trusted by the next snapshot, which compares keys). Files with
826
    /// an `eol` attribute are left out: their bytes on disk are not the
827
    /// rendering.
828680×
    fn committed_graph_keys(
829680×
        &self,
830680×
        st: &State,
831680×
        paths: &[String],
832680×
        attrs: &crate::attributes::Attributes,
833680×
    ) -> HashMap<String, [u8; 32]> {
834680×
        let _t = crate::timing::phase("commit: graph keys");
835680×
        let view = st.tree().view();
836680×
        paths
837680×
            .iter()
8383552×
            .filter_map(|p| {
8393552×
                let e = view.entries.get(p)?;
8403509×
                (e.kind == NodeKind::File && !e.mode.opaque && attrs.lookup(p).eol.is_none())
8413509×
                    .then_some(())?;
8423459×
                Some((p.clone(), st.graph_key(&e.node)?))
8433552×
            })
844680×
            .collect()
845680×
    }
846
847665×
    pub fn commit_selection(
848665×
        &self,
849665×
        message: &str,
850665×
        extra_deps: &[ChangeHash],
851665×
        selection: &Selection,
852665×
    ) -> Result<ChangeHash> {
853665×
        Ok(self
854665×
            .commit_selection_partial(message, extra_deps, selection)?
855
            .0)
856665×
    }
857
858
    /// As [`Repo::commit_selection`], and whether the commit left part of
859
    /// the working copy uncommitted: when it did not, nothing is left, and
860
    /// no snapshot is needed to say so.
861691×
    pub fn commit_selection_partial(
862691×
        &self,
863691×
        message: &str,
864691×
        extra_deps: &[ChangeHash],
865691×
        selection: &Selection,
866691×
    ) -> Result<(ChangeHash, bool)> {
867
        // The commit's objects are written together, made durable at once
868
        // before the operation that names them (spec §13.6).
869691×
        let batch = self.store.begin_batch()?;
870691×
        let out = self.commit_selection_batched(message, extra_deps, selection);
871691×
        batch.finish()?;
872691×
        out
873691×
    }
874
875
    /// Write the manifest a commit's snapshot left to the commit, with the
876
    /// graph keys `keys` sets.
877451×
    fn write_pending_manifest(
878451×
        &self,
879451×
        mut m: PendingManifest,
880451×
        conflicted: bool,
881451×
        keys: HashMap<String, [u8; 32]>,
882451×
    ) -> Result<()> {
8832845×
        for (path, k) in keys {
8842845×
            if let Some(e) = m.entries.get_mut(&path) {
8852845×
                e.graph_key = Some(k);
8862845×
            }
887
        }
888451×
        self.write_manifest_entries_as_of(
889451×
            conflicted,
890
            false,
891451×
            &m.entries,
892451×
            &m.blobs,
893451×
            m.written,
894451×
            m.dirs.unwrap_or_default(),
895
        )
896451×
    }
897
898691×
    fn commit_selection_batched(
899691×
        &self,
900691×
        message: &str,
901691×
        extra_deps: &[ChangeHash],
902691×
        selection: &Selection,
903691×
    ) -> Result<(ChangeHash, bool)> {
904691×
        let _wc = self.lock_working_copy()?;
905691×
        let mut snap = match self.snapshot_from_cache()? {
906231×
            Some(snap) => snap,
907460×
            None => self.snapshot_as("oxy commit", true, true)?,
908
        };
909691×
        let pending = snap.manifest.take();
910691×
        if snap.wc.tree_ops.is_empty() && snap.wc.edits.is_empty() {
9113×
            if let Some(m) = pending {
9123×
                let conflicted = snap.base_snapshot.is_conflicted();
9133×
                self.write_pending_manifest(m, conflicted, HashMap::new())?;
9140×
            }
9153×
            return fail("nothing to commit: the working copy matches its base");
916688×
        }
917688×
        if let Some(s) = snap
918688×
            .statuses
919688×
            .iter()
9203569×
            .find(|s| s.status == ChangeStatus::ConflictEdited)
921
        {
9220×
            return fail(format!("{} still contains conflict markers", s.path));
923688×
        }
924688×
        if message.trim().is_empty() {
9250×
            return fail("a commit message is required");
926688×
        }
927
        // What the whole working copy references, before a whole commit
928
        // takes its operations over (they are moved, not copied: for a
929
        // large tree they are most of the memory).
930688×
        let wc_refs = referenced_changes(&snap.wc, &snap.base);
9313569×
        let changed_paths: Vec<String> = snap.statuses.iter().map(|s| s.path.clone()).collect();
932688×
        let (tree_ops, edits, partial) = match selection {
933680×
            Selection::All => (
934680×
                std::mem::take(&mut snap.wc.tree_ops),
935680×
                std::mem::take(&mut snap.wc.edits),
936680×
                false,
937680×
            ),
9384×
            Selection::Paths(paths) => {
9394×
                let (o, e) = select_paths(&snap.wc, &snap.base_snapshot, paths);
9404×
                let partial = o.len() != snap.wc.tree_ops.len() || e.len() != snap.wc.edits.len();
9414×
                (o, e, partial)
942
            }
9434×
            Selection::Hunks(indices) => {
9444×
                let (o, e) = select_hunks(&snap.wc, indices);
9454×
                let partial = o.len() != snap.wc.tree_ops.len() || e.len() != snap.wc.edits.len();
9464×
                (o, e, partial)
947
            }
948
        };
949688×
        if tree_ops.is_empty() && edits.is_empty() {
9500×
            return fail("nothing selected to commit");
951688×
        }
952688×
        if partial && snap.resolves {
9530×
            return fail("a conflict resolution must be committed whole");
954688×
        }
955
        // pre-commit hook: may veto.
956688×
        self.run_hook(
957688×
            "pre-commit",
958688×
            &format!(
959
                "{{\"event\":\"pre-commit\",\"message\":{},\"paths\":{}}}",
960688×
                json_str(message),
9613569×
                json_array(snap.statuses.iter().map(|s| format!(
962
                    "{{\"path\":{},\"status\":{}}}",
9633569×
                    json_str(&s.path),
9643569×
                    json_str(&format!("{:?}", s.status))
965
                )))
966
            ),
9671×
        )?;
968687×
        let (op_ref, op) = self.head_op()?;
969687×
        let mut deps: BTreeSet<ChangeHash> = wc_refs;
970
        // semantic-deps hook: may add explicit dependencies (spec §8.1).
971687×
        if self.config.semantic_deps {
9721×
            let touched: Vec<String> = snap.statuses.iter().map(|s| s.path.clone()).collect();
9731×
            let by_node = snap.base_snapshot.tree.by_node();
9741×
            let mut candidates: Vec<(ChangeId, ChangeHash, Vec<String>)> = Vec::new();
9751×
            let mut seen: BTreeSet<ChangeHash> = BTreeSet::new();
9762×
            for h in deps.iter().chain(snap.base.maximal(&snap.wc.deps).iter()) {
9772×
                if !seen.insert(*h) {
9780×
                    continue;
9792×
                }
9802×
                let c = self.store.get_change(h)?;
9812×
                let mut paths: BTreeSet<String> = BTreeSet::new();
9826×
                for n in c
9832×
                    .tree_ops
9842×
                    .iter()
9853×
                    .map(|o| o.node())
9863×
                    .chain(c.edits.iter().map(|e| e.node()))
987
                {
9886×
                    if let Some(e) = by_node.get(&n) {
9896×
                        paths.insert(e.path.clone());
9906×
                    }
991
                }
9922×
                candidates.push((c.change_id, *h, paths.into_iter().collect()));
993
            }
9941×
            for d in self.semantic_deps(&snap.wc.change_id, &touched, &candidates)? {
9951×
                if snap.base.contains(&d) {
9961×
                    deps.insert(d);
9971×
                }
998
            }
999686×
        }
1000
        // A resolution depends on every change that contributed to the
1001
        // conflict (spec §8.1). Tree and opaque conflicts are resolved through
1002
        // ordinary operations whose references already cover the contributors.
1003687×
        deps.extend(snap.contributors.iter().copied());
1004687×
        for d in extra_deps {
10052×
            if !snap.base.contains(d) {
10060×
                return fail(format!(
1007
                    "--depends-on {d}: not in the working copy's base state"
1008
                ));
10092×
            }
10102×
            deps.insert(*d);
1011
        }
1012687×
        let mut change = Change {
1013
            version: crate::objects::CHANGE_VERSION,
1014687×
            change_id: if partial {
10156×
                ChangeId::random()
1016
            } else {
1017681×
                snap.wc.change_id
1018
            },
1019687×
            deps: vec![],
1020687×
            author: self.author(),
1021687×
            hlc: Hlc::now(),
1022687×
            message: message.trim_end().to_string(),
1023687×
            tree_ops,
1024687×
            edits,
1025687×
            kind: if snap.resolves {
10267×
                ChangeKind::Resolution
1027
            } else {
1028680×
                ChangeKind::Normal
1029
            },
1030
        };
1031687×
        if partial {
1032
            // Dependencies come from what the selected part references, not
1033
            // from the whole working copy.
10346×
            deps = referenced_changes(&change, &snap.base);
10356×
            for d in extra_deps {
10360×
                deps.insert(*d);
10370×
            }
1038681×
        }
1039687×
        change.deps = deps.into_iter().collect();
1040687×
        change.normalize();
1041687×
        let signing = crate::timing::phase("commit: sign and store");
1042687×
        let hash = self.store_signed(&change)?;
1043686×
        drop(signing);
1044686×
        let extending = crate::timing::phase("commit: extend the state");
1045
1046
        // New bookmark heads: maximal elements of old heads plus the new change.
1047
        // The working copy continues on its own base plus the new change, which
1048
        // is exactly what the files on disk contain; the bookmark may hold
1049
        // other heads (and conflicts) the working copy has not checked out.
1050686×
        let old_heads = self.heads_of(&op.view, &self.config.bookmark)?;
1051686×
        let old_base = snap.base.maximal(&snap.wc.deps);
1052686×
        let mut all: Vec<ChangeHash> = old_heads.clone();
1053686×
        all.extend(old_base.iter().copied());
1054686×
        all.push(hash);
1055
        // The snapshot already loaded the working copy's base; when that also
1056
        // holds every bookmark head, it is the state to extend.
1057686×
        let mut st = if old_heads.iter().all(|h| snap.base.contains(h)) {
1058651×
            snap.base
1059
        } else {
106035×
            self.load_state(&all)?
1061
        };
1062686×
        st.add_hashed(hash, change)?;
1063686×
        let mut with_new = old_heads.clone();
1064686×
        with_new.push(hash);
1065686×
        let new_heads = st.maximal(&with_new);
1066
        // Automatic checkpoint once enough changes accumulated (spec §11).
1067686×
        let since = self
1068686×
            .latest_checkpoint(&self.config.bookmark)?
1069686×
            .map(|(_, cp)| cp.count)
1070686×
            .unwrap_or(0);
1071686×
        if self.config.checkpoint_interval > 0
1072686×
            && (st.len() as u64).saturating_sub(since) >= self.config.checkpoint_interval
1073
        {
10742×
            let cp_state = self.load_state_full(&new_heads)?;
10752×
            self.write_checkpoint(&self.config.bookmark, &cp_state, &new_heads)?;
1076684×
        }
1077686×
        let mut wc_base = old_base.clone();
1078686×
        wc_base.push(hash);
1079686×
        let wc_base = st.maximal(&wc_base);
1080686×
        drop(extending);
1081
1082
        // The graph keys of the files as they now are, from the state the
1083
        // commit just extended: a file whose graph it built has none, and
1084
        // is read by the next snapshot; a key the next base does not share
1085
        // (the bookmark held other heads) is simply not trusted then.
1086686×
        let keying = crate::timing::phase("commit: graph keys of the files");
1087686×
        let committed_keys =
1088686×
            (!partial).then(|| self.committed_graph_keys(&st, &changed_paths, &snap.attributes));
1089686×
        drop(keying);
1090686×
        let recording = crate::timing::phase("commit: record");
1091686×
        let wc = self.new_working_copy(wc_base, "");
1092686×
        let wc_hash = self.store.put_change(&wc)?;
1093686×
        let mut view = op.view.clone();
1094686×
        view.bookmarks.insert(
1095686×
            self.config.bookmark.clone(),
1096686×
            self.store.put_state(&StateObject::new(new_heads))?,
1097
        );
1098686×
        view.workspaces.insert(self.workspace, wc_hash);
1099686×
        self.record_op(&[op_ref], &format!("oxy commit -m {message:?}"), view)?;
1100681×
        drop(recording);
1101681×
        let rewriting = crate::timing::phase("commit: manifest");
1102681×
        if partial {
11036×
            // The rest is rebuilt from disk by the next snapshot.
11046×
            self.drop_manifest();
11056×
        } else {
1106675×
            let conflicted = snap.base_snapshot.is_conflicted() && !snap.resolves;
1107
            // The files on disk are now exactly the new base's renderings:
1108
            // record their graph keys, so the next snapshot neither reads nor
1109
            // renders them (oxygen#35).
1110675×
            let keys = if conflicted {
11110×
                HashMap::new()
1112
            } else {
1113675×
                committed_keys.unwrap_or_default()
1114
            };
1115675×
            match pending {
1116448×
                Some(m) => self.write_pending_manifest(m, conflicted, keys)?,
1117227×
                None => self.rewrite_manifest(conflicted, false, &keys)?,
1118
            }
1119
        }
1120681×
        drop(rewriting);
1121681×
        let packing = crate::timing::phase("commit: autopack");
1122681×
        self.maybe_autopack()?;
1123681×
        drop(packing);
1124681×
        let _hook = crate::timing::phase("commit: hook");
1125681×
        let _ = self.run_hook(
1126681×
            "post-commit",
1127681×
            &format!(
1128681×
                "{{\"event\":\"post-commit\",\"change_id\":{},\"hash\":{},\"message\":{}}}",
1129681×
                json_str(&snap.wc.change_id.to_hex()),
1130681×
                json_str(&hash.to_hex()),
1131681×
                json_str(message)
1132681×
            ),
1133681×
        );
1134681×
        Ok((hash, partial))
1135691×
    }
1136
}
1137
1138
/// What part of the working copy a commit takes (spec §12.3).
1139
#[derive(Clone, Debug)]
1140
pub enum Selection {
1141
    All,
1142
    /// Every operation and edit on nodes under these paths.
1143
    Paths(Vec<String>),
1144
    /// Hunk indices as `Repo::hunks` numbers them; dependent hunks are added.
1145
    Hunks(Vec<usize>),
1146
}
1147
1148
/// One selectable piece of the working copy: a tree operation or an edit.
1149
#[derive(Clone, Debug)]
1150
pub struct Hunk {
1151
    pub index: usize,
1152
    pub path: String,
1153
    /// Rendered like `oxy diff`.
1154
    pub text: String,
1155
}
1156
1157
/// The tree operations and edits on nodes under `paths`, plus the
1158
/// additions of any new parent directories they need.
11594×
fn select_paths(
11604×
    wc: &Change,
11614×
    base_snapshot: &Snapshot,
11624×
    paths: &[String],
11634×
) -> (Vec<TreeOp>, Vec<Edit>) {
116413×
    let selected = |p: &str| {
116513×
        paths
116613×
            .iter()
116713×
            .any(|x| p == x || p.starts_with(&format!("{}/", x.trim_end_matches('/'))))
116813×
    };
11694×
    let by_node = base_snapshot.tree.by_node();
11704×
    let mut new_names: HashMap<NodeId, (NodeId, String, NodeKind)> = HashMap::new();
11714×
    for op in &wc.tree_ops {
1172
        if let TreeOp::AddNode {
11731×
            node,
11741×
            parent,
11751×
            name,
11761×
            kind,
1177
            ..
11781×
        } = op
11791×
        {
11801×
            new_names.insert(*node, (*parent, name.clone(), *kind));
11811×
        }
1182
    }
11834×
    let mut nodes: BTreeSet<NodeId> = BTreeSet::new();
118413×
    for n in wc
11854×
        .tree_ops
11864×
        .iter()
11874×
        .map(|o| o.node())
118812×
        .chain(wc.edits.iter().map(|e| e.node()))
1189
    {
119013×
        if path_of_node(&n, &by_node, &new_names).is_some_and(|p| selected(&p)) {
11918×
            nodes.insert(n);
11928×
        }
1193
    }
1194
    // New parents of selected new nodes come along.
11954×
    let mut changed = true;
11968×
    while changed {
11974×
        changed = false;
11984×
        for (n, (parent, _, _)) in &new_names {
11991×
            if nodes.contains(n) && new_names.contains_key(parent) && nodes.insert(*parent) {
12000×
                changed = true;
12011×
            }
1202
        }
1203
    }
12044×
    let ops = wc
12054×
        .tree_ops
12064×
        .iter()
12074×
        .filter(|o| nodes.contains(&o.node()))
12084×
        .cloned()
12094×
        .collect();
12104×
    let edits = wc
12114×
        .edits
12124×
        .iter()
121312×
        .filter(|e| nodes.contains(&e.node()))
12144×
        .cloned()
12154×
        .collect();
12164×
    (ops, edits)
12174×
}
1218
1219
/// The hunks `indices` name plus whatever they refer to within the working
1220
/// copy (the parent directory of an added node, the insert that introduced
1221
/// an anchor line), renumbered so the result is a well-formed change.
12225×
fn select_hunks(wc: &Change, indices: &[usize]) -> (Vec<TreeOp>, Vec<Edit>) {
12235×
    let n_ops = wc.tree_ops.len();
12245×
    let mut ops_sel = vec![false; n_ops];
12255×
    let mut edits_sel = vec![false; wc.edits.len()];
12265×
    for &i in indices {
12274×
        if i < n_ops {
12281×
            ops_sel[i] = true;
12293×
        } else if i - n_ops < wc.edits.len() {
12303×
            edits_sel[i - n_ops] = true;
12313×
        }
1232
    }
1233
    // Atom ranges each insert introduces, per node, in the working copy's numbering.
12345×
    let mut per_node: HashMap<NodeId, u32> = HashMap::new();
12355×
    let mut insert_ranges: Vec<Option<(NodeId, u32, u32)>> = Vec::new();
123610×
    for e in &wc.edits {
123710×
        insert_ranges.push(match e {
123810×
            Edit::Insert { node, lines, .. } => {
123910×
                let start = per_node.entry(*node).or_default();
124010×
                let r = (*node, *start, *start + lines.len() as u32);
124110×
                *start += lines.len() as u32;
124210×
                Some(r)
1243
            }
12440×
            _ => None,
1245
        });
1246
    }
12475×
    let add_index: HashMap<NodeId, usize> = wc
12485×
        .tree_ops
12495×
        .iter()
12505×
        .enumerate()
12518×
        .filter_map(|(i, o)| {
12528×
            if let TreeOp::AddNode { node, .. } = o {
12538×
                Some((*node, i))
1254
            } else {
12550×
                None
1256
            }
12578×
        })
12585×
        .collect();
12595×
    let insert_for = |node: &NodeId, index: u32| -> Option<usize> {
12600×
        insert_ranges
12610×
            .iter()
12620×
            .position(|r| matches!(r, Some((n, a, b)) if n == node && *a <= index && index < *b))
12630×
    };
1264
    // Closure.
12655×
    let mut changed = true;
126613×
    while changed {
12678×
        changed = false;
126817×
        for i in 0..n_ops {
126917×
            if !ops_sel[i] {
127011×
                continue;
12716×
            }
12726×
            if let TreeOp::AddNode { node, parent, .. } = &wc.tree_ops[i] {
12736×
                if let Some(&p) = add_index.get(parent) {
12744×
                    if !ops_sel[p] {
12752×
                        ops_sel[p] = true;
12762×
                        changed = true;
12772×
                    }
12782×
                }
1279
                // A new node's content belongs with its addition: nobody
1280
                // wants an empty file committed apart from its lines.
128112×
                for (j, e) in wc.edits.iter().enumerate() {
128212×
                    if e.node() == *node && !edits_sel[j] {
12831×
                        edits_sel[j] = true;
12841×
                        changed = true;
128511×
                    }
1286
                }
12870×
            }
1288
        }
128916×
        for j in 0..wc.edits.len() {
129016×
            if !edits_sel[j] {
12919×
                continue;
12927×
            }
12937×
            let e = &wc.edits[j];
12947×
            if let Some(&a) = add_index.get(&e.node()) {
12955×
                if !ops_sel[a] {
12961×
                    ops_sel[a] = true;
12971×
                    changed = true;
12984×
                }
12992×
            }
1300
            if let Edit::Insert {
13017×
                node,
13027×
                after,
13037×
                before,
1304
                ..
13057×
            } = e
1306
            {
130714×
                for r in [after, before] {
130814×
                    if let AtomRef::Atom { change, index } = r {
13092×
                        if change.is_zero() {
13100×
                            if let Some(k) = insert_for(node, *index) {
13110×
                                if !edits_sel[k] {
13120×
                                    edits_sel[k] = true;
13130×
                                    changed = true;
13140×
                                }
13150×
                            }
13162×
                        }
131712×
                    }
1318
                }
13190×
            }
1320
        }
1321
    }
1322
    // Renumber self-references: old atom index → new index among selected inserts.
13235×
    let mut remap: HashMap<(NodeId, u32), u32> = HashMap::new();
13245×
    let mut new_counts: HashMap<NodeId, u32> = HashMap::new();
132510×
    for (j, r) in insert_ranges.iter().enumerate() {
132610×
        if let (true, Some((node, a, b))) = (edits_sel[j], r) {
13274×
            let next = new_counts.entry(*node).or_default();
13284×
            for old in *a..*b {
13294×
                remap.insert((*node, old), *next);
13304×
                *next += 1;
13314×
            }
13326×
        }
1333
    }
13348×
    let map_ref = |r: AtomRef, node: &NodeId| -> AtomRef {
13352×
        match r {
13362×
            AtomRef::Atom { change, index } if change.is_zero() => AtomRef::Atom {
13370×
                change,
13380×
                index: remap.get(&(*node, index)).copied().unwrap_or(index),
13390×
            },
13408×
            other => other,
1341
        }
13428×
    };
13435×
    let ops = wc
13445×
        .tree_ops
13455×
        .iter()
13465×
        .enumerate()
13478×
        .filter(|(i, _)| ops_sel[*i])
13485×
        .map(|(_, o)| o.clone())
13495×
        .collect();
13505×
    let edits = wc
13515×
        .edits
13525×
        .iter()
13535×
        .enumerate()
135410×
        .filter(|(j, _)| edits_sel[*j])
13555×
        .map(|(_, e)| match e {
1356
            Edit::Insert {
13574×
                node,
13584×
                after,
13594×
                before,
13604×
                lines,
13614×
            } => Edit::Insert {
13624×
                node: *node,
13634×
                after: map_ref(*after, node),
13644×
                before: map_ref(*before, node),
13654×
                lines: lines.clone(),
13664×
            },
13670×
            other => other.clone(),
13684×
        })
13695×
        .collect();
13705×
    (ops, edits)
13715×
}
1372
1373
/// Render each tree operation and edit of `change` on its own, numbered.
13747×
pub fn render_hunks(change: &Change, base: &State, base_snapshot: &Snapshot) -> Vec<Hunk> {
13757×
    let by_node = base_snapshot.tree.by_node();
13767×
    let mut new_names: HashMap<NodeId, (NodeId, String, NodeKind)> = HashMap::new();
13778×
    for op in &change.tree_ops {
1378
        if let TreeOp::AddNode {
13798×
            node,
13808×
            parent,
13818×
            name,
13828×
            kind,
1383
            ..
13848×
        } = op
13858×
        {
13868×
            new_names.insert(*node, (*parent, name.clone(), *kind));
13878×
        }
1388
    }
13897×
    let mut out = Vec::new();
13908×
    for (i, op) in change.tree_ops.iter().enumerate() {
13918×
        let one = Change {
13928×
            tree_ops: vec![op.clone()],
13938×
            edits: vec![],
13948×
            ..change.clone()
13958×
        };
13968×
        let path = path_of_node(&op.node(), &by_node, &new_names).unwrap_or_default();
13978×
        out.push(Hunk {
13988×
            index: i,
13998×
            path,
14008×
            text: render_change(&one, base, base_snapshot),
14018×
        });
14028×
    }
140313×
    for (j, e) in change.edits.iter().enumerate() {
140413×
        let one = Change {
140513×
            tree_ops: vec![],
140613×
            edits: vec![e.clone()],
140713×
            ..change.clone()
140813×
        };
140913×
        let path = path_of_node(&e.node(), &by_node, &new_names).unwrap_or_default();
141013×
        out.push(Hunk {
141113×
            index: change.tree_ops.len() + j,
141213×
            path,
141313×
            text: render_change(&one, base, base_snapshot),
141413×
        });
141513×
    }
14167×
    out
14177×
}
1418
1419
/// One file's part of a diff, for `oxy diff --json`.
1420
#[derive(Clone, Debug)]
1421
pub struct FileDiff {
1422
    pub path: String,
1423
    /// `added`, `removed`, `modified`, `renamed`, `mode`, `replaced`.
1424
    pub kind: String,
1425
    pub hunks: Vec<DiffHunk>,
1426
    /// For renames, the previous path.
1427
    pub from: Option<String>,
1428
}
1429
1430
/// Lines inserted after `base_line` (0 = before the first line) and lines
1431
/// removed, with their base line numbers.
1432
#[derive(Clone, Debug, Default)]
1433
pub struct DiffHunk {
1434
    pub base_line: u32,
1435
    pub added: Vec<Vec<u8>>,
1436
    pub removed: Vec<(u32, Vec<u8>)>,
1437
}
1438
1439
impl Repo {
1440
    /// The content of `path` in a state: `heads`, or the working copy's base.
144126×
    pub fn file_at(&self, path: &str, heads: Option<&[ChangeHash]>) -> Result<Vec<u8>> {
1442
        // The state's history and tree, then the one file's graph: nothing
1443
        // else is built or rendered (oxygen#92).
1444
        // The working copy's base, and a state named by its heads (`-r
1445
        // main` on main), come from the workspace's state index.
144626×
        let base = if self.is_bare() {
14475×
            None
1448
        } else {
144921×
            Some(self.working_copy()?.1.deps)
1450
        };
145126×
        let same = |a: &[ChangeHash], b: &[ChangeHash]| {
14521×
            let (mut a, mut b) = (a.to_vec(), b.to_vec());
14531×
            a.sort();
14541×
            b.sort();
14551×
            a == b
14561×
        };
145726×
        let mut state = match (heads, base) {
14581×
            (Some(h), Some(b)) if same(h, &b) => self.load_state_indexed(&b)?,
14595×
            (Some(h), _) => self.load_state_history(h)?,
146020×
            (None, Some(b)) => self.load_state_indexed(&b)?,
14610×
            (None, None) => return fail("this is a bare repository: it has no working copy"),
1462
        };
146326×
        let view = state.tree().view();
146426×
        let Some(node) = view.entries.get(path).map(|e| e.node) else {
14650×
            return fail(format!("{path} is not in that state"));
1466
        };
146726×
        self.load_graphs_of(&mut state, &[node])?;
146825×
        let snapshot = state.materialize_paths(view, [path]);
146925×
        let Some(f) = snapshot.files.get(path) else {
14700×
            return fail(format!("{path} is not in that state"));
1471
        };
147225×
        match &f.content {
14730×
            FileContent::Dir => fail(format!("{path} is a directory")),
147425×
            FileContent::Text { bytes, .. } => Ok(bytes.clone()),
14750×
            FileContent::Opaque { blobs } => match blobs.first() {
14760×
                Some(b) => self.read_blob(b),
14770×
                None => Ok(vec![]),
1478
            },
1479
        }
148026×
    }
1481
1482
    /// Restore `paths` (files or directories) to the working copy's base:
1483
    /// edits are undone, additions removed, removals put back. Returns the
1484
    /// number of paths touched.
14852×
    pub fn discard(&self, paths: &[String]) -> Result<usize> {
14862×
        let _wc = self.lock_working_copy()?;
14872×
        let snap = self.snapshot_status("oxy discard")?;
14887×
        let under = |p: &str| {
14897×
            paths
14907×
                .iter()
14917×
                .any(|x| p == x || p.starts_with(&format!("{}/", x.trim_end_matches('/'))))
14927×
        };
14932×
        let attrs = Repo::state_attributes(&snap.base_snapshot);
14942×
        let mut n = 0;
14953×
        for s in &snap.statuses {
14963×
            if !under(&s.path) {
14971×
                continue;
14982×
            }
14992×
            match snap.base_snapshot.files.get(&s.path) {
1500
                None => {
1501
                    // Added (or the new name of a rename): remove it.
15021×
                    let full = self.root.join(&s.path);
15031×
                    if full.is_dir() {
15040×
                        let _ = fs::remove_dir_all(&full);
15051×
                    } else {
15061×
                        let _ = fs::remove_file(&full);
15071×
                    }
15081×
                    n += 1;
1509
                }
15101×
                Some(f) => {
15111×
                    match &f.content {
15120×
                        FileContent::Dir => fs::create_dir_all(self.root.join(&s.path))?,
15131×
                        FileContent::Text { bytes, .. } => {
15141×
                            let on_disk: std::borrow::Cow<[u8]> = if attrs.lookup(&s.path).eol
15151×
                                == Some(crate::attributes::Eol::Crlf)
1516
                            {
15170×
                                crate::attributes::to_crlf(bytes).into()
1518
                            } else {
15191×
                                bytes.as_slice().into()
1520
                            };
15211×
                            self.write_file(&s.path, &on_disk, f.mode.exec)?;
1522
                        }
15230×
                        FileContent::Opaque { blobs } => {
15240×
                            let bytes = match blobs.first() {
15250×
                                Some(b) => self.read_blob(b)?,
15260×
                                None => vec![],
1527
                            };
15280×
                            if f.kind == NodeKind::Symlink {
15290×
                                self.write_symlink(&s.path, &bytes)?;
15300×
                            } else if f.kind == NodeKind::File {
15310×
                                self.write_file(&s.path, &bytes, f.mode.exec)?;
15320×
                            }
1533
                        }
1534
                    }
15351×
                    n += 1;
1536
                }
1537
            }
1538
        }
1539
        // A rename's old name is not in the statuses; put it back too.
15404×
        for (p, f) in &snap.base_snapshot.files {
15414×
            if under(p)
15421×
                && !self.root.join(p).exists()
15430×
                && f.kind != NodeKind::Dir
15440×
                && f.kind != NodeKind::Subrepo
15450×
                && !snap.statuses.iter().any(|s| s.path == *p)
1546
            {
15470×
                let bytes = match &f.content {
15480×
                    FileContent::Text { bytes, .. } => bytes.clone(),
15490×
                    FileContent::Opaque { blobs } => blobs
15500×
                        .first()
15510×
                        .map(|b| self.read_blob(b))
15520×
                        .transpose()?
15530×
                        .unwrap_or_default(),
15540×
                    FileContent::Dir => continue,
1555
                };
15560×
                if f.kind == NodeKind::Symlink {
15570×
                    self.write_symlink(p, &bytes)?
1558
                } else {
15590×
                    self.write_file(p, &bytes, f.mode.exec)?
1560
                }
15610×
                n += 1;
15624×
            }
1563
        }
15642×
        self.drop_manifest();
15652×
        Ok(n)
15662×
    }
1567
1568
    /// Undo the working-copy hunks `indices` (as `hunks` numbers them) on
1569
    /// disk, keeping the others: the files are rewritten from the base plus
1570
    /// the remaining hunks.
15711×
    pub fn discard_hunks(&self, indices: &[usize]) -> Result<usize> {
15721×
        let _wc = self.lock_working_copy()?;
15731×
        let (snap, hunks) = self.hunks()?;
15741×
        let keep: Vec<usize> = hunks
15751×
            .iter()
15761×
            .map(|h| h.index)
15771×
            .filter(|i| !indices.contains(i))
15781×
            .collect();
15791×
        let (ops, edits) = select_hunks(&snap.wc, &keep);
15801×
        let dropped_nodes: BTreeSet<NodeId> = hunks
15811×
            .iter()
15821×
            .filter(|h| indices.contains(&h.index))
15831×
            .map(|h| {
15841×
                if h.index < snap.wc.tree_ops.len() {
15850×
                    snap.wc.tree_ops[h.index].node()
1586
                } else {
15871×
                    snap.wc.edits[h.index - snap.wc.tree_ops.len()].node()
1588
                }
15891×
            })
15901×
            .collect();
15911×
        let mut partial = snap.wc.clone();
15921×
        partial.tree_ops = ops;
15931×
        partial.edits = edits;
15941×
        partial.normalize();
15951×
        let mut st = snap.base.clone();
15961×
        st.add_unchecked(partial);
1597
        // Every file of the target is rendered: build the graphs the
1598
        // partial snapshot left out.
15991×
        self.load_all_graphs(&mut st)?;
16001×
        let target = st.materialize();
16011×
        let by_node_target = target.tree.by_node();
16021×
        let by_node_base = snap.base_snapshot.tree.by_node();
16031×
        let attrs = Repo::state_attributes(&target);
16041×
        let mut n = 0;
16051×
        for node in dropped_nodes {
16061×
            match by_node_target.get(&node) {
16071×
                Some(e) => {
16081×
                    let f = &target.files[&e.path];
16091×
                    match &f.content {
16100×
                        FileContent::Dir => {}
16111×
                        FileContent::Text { bytes, .. } => {
16121×
                            let on_disk: std::borrow::Cow<[u8]> = if attrs.lookup(&e.path).eol
16131×
                                == Some(crate::attributes::Eol::Crlf)
1614
                            {
16150×
                                crate::attributes::to_crlf(bytes).into()
1616
                            } else {
16171×
                                bytes.as_slice().into()
1618
                            };
16191×
                            self.write_file(&e.path, &on_disk, f.mode.exec)?;
1620
                        }
16210×
                        FileContent::Opaque { blobs } => {
16220×
                            let bytes = blobs
16230×
                                .first()
16240×
                                .map(|b| self.read_blob(b))
16250×
                                .transpose()?
16260×
                                .unwrap_or_default();
16270×
                            if f.kind == NodeKind::Symlink {
16280×
                                self.write_symlink(&e.path, &bytes)?
1629
                            } else {
16300×
                                self.write_file(&e.path, &bytes, f.mode.exec)?
1631
                            }
1632
                        }
1633
                    }
1634
                    // A discarded rename: the new name goes.
16351×
                    if let Some(old_path) = snap
16361×
                        .statuses
16371×
                        .iter()
16381×
                        .find(|s| {
16391×
                            s.status == ChangeStatus::Renamed && !target.files.contains_key(&s.path)
16401×
                        })
16411×
                        .map(|s| s.path.clone())
16420×
                    {
16430×
                        let _ = fs::remove_file(self.root.join(old_path));
16441×
                    }
16451×
                    n += 1;
1646
                }
1647
                None => {
1648
                    // The node exists in neither target nor base with a live path: an addition to remove.
16490×
                    if let Some(added) = snap.statuses.iter().find(|s| {
16500×
                        s.status == ChangeStatus::Added
16510×
                            && !target.files.contains_key(&s.path)
16520×
                            && !by_node_base.contains_key(&node)
16530×
                    }) {
16540×
                        let full = self.root.join(&added.path);
16550×
                        if full.is_dir() {
16560×
                            let _ = fs::remove_dir_all(&full);
16570×
                        } else {
16580×
                            let _ = fs::remove_file(&full);
16590×
                        }
16600×
                        n += 1;
16610×
                    }
1662
                }
1663
            }
1664
        }
16651×
        self.drop_manifest();
16661×
        Ok(n)
16671×
    }
1668
1669
    /// The diff of the working copy (`None`) or of a change, per file with
1670
    /// line-numbered hunks (spec: `oxy diff --json`).
16717×
    pub fn diff_files(&self, change: Option<&ChangeHash>) -> Result<Vec<FileDiff>> {
16727×
        let (c, base, base_snapshot) = match change {
16733×
            Some(h) => {
16743×
                let c = self.store.get_change(h)?;
16753×
                let (base, snapshot) = self.change_base(&c)?;
16763×
                (c, base, snapshot)
1677
            }
16784×
            None => match self.working_copy_with_base_unless_unchanged()? {
16793×
                Some(all) => all,
16801×
                None => return Ok(Vec::new()),
1681
            },
1682
        };
16836×
        Ok(diff_files_of(&c, &base, &base_snapshot))
16847×
    }
1685
1686
    /// The snapshot a command would take, without taking it, when the
1687
    /// status cache holds: every file is as the last snapshot left it, so
1688
    /// that snapshot's working-copy change is the answer. Its base comes
1689
    /// from the state index, the `.oxyattributes` files from disk. `None`
1690
    /// when a snapshot must be taken, and when there is nothing to commit
1691
    /// (the snapshot then says so). A conflicted base never gets here: the
1692
    /// cache does not hold for one.
1693692×
    pub(crate) fn snapshot_from_cache(&self) -> Result<Option<SnapshotResult>> {
1694692×
        let Some(statuses) = self.status_by_manifest()? else {
1695458×
            return Ok(None);
1696
        };
1697234×
        if statuses.is_empty() {
16982×
            return Ok(None);
1699232×
        }
1700232×
        let _t = crate::timing::phase("snapshot: from the status cache");
1701232×
        let (wc_hash, wc) = self.working_copy()?;
1702232×
        let base = self.load_state_indexed(&wc.deps)?;
1703232×
        let (base, base_snapshot) = self.render_base_for(&wc, base)?;
1704232×
        let attribute_files: Vec<(String, Vec<u8>)> = match self.read_manifest()? {
1705232×
            Some((_, _, m)) => m
1706232×
                .entries
1707232×
                .keys()
1708725×
                .filter(|p| is_attributes(p))
1709232×
                .filter_map(|p| fs::read(self.root.join(p)).ok().map(|b| (p.clone(), b)))
1710232×
                .collect(),
17110×
            None => Vec::new(),
1712
        };
1713232×
        let attributes = crate::attributes::Attributes::from_files(
1714232×
            attribute_files
1715232×
                .iter()
1716232×
                .map(|(p, b)| (p.as_str(), b.as_slice())),
1717
        );
1718232×
        Ok(Some(SnapshotResult {
1719232×
            wc_hash,
1720232×
            wc,
1721232×
            base,
1722232×
            base_snapshot,
1723232×
            statuses,
1724232×
            changed: false,
1725232×
            resolves: false,
1726232×
            contributors: Vec::new(),
1727232×
            attributes,
1728232×
            untracked_nested: self.untracked_nested.borrow().clone(),
1729232×
            manifest: None,
1730232×
        }))
1731692×
    }
1732
1733
    /// The working-copy change with its base state and a snapshot of the
1734
    /// base, for showing what the working copy changes ([`render_change`],
1735
    /// [`diff_files_of`]). While the status cache holds (every file as the
1736
    /// last snapshot left it), the stored working-copy change is the
1737
    /// answer, no snapshot is taken, and the base's snapshot holds its tree
1738
    /// but no file; otherwise a snapshot makes all three.
17392×
    pub fn working_copy_with_base(&self) -> Result<(Change, State, Snapshot)> {
17402×
        match self.working_copy_with_base_unless_unchanged()? {
17411×
            Some(all) => Ok(all),
1742
            None => {
17431×
                let (_, wc) = self.working_copy()?;
17441×
                let base = self.load_state_indexed(&wc.deps)?;
17451×
                let (base, snapshot) = self.tree_base_for(&wc, base)?;
17461×
                Ok((wc, base, snapshot))
1747
            }
1748
        }
17492×
    }
1750
1751
    /// [`Repo::working_copy_with_base`], or `None` when the status cache
1752
    /// holds and the working-copy change changes nothing: its diff is
1753
    /// empty, and the base is not loaded for it (oxygen#94).
17547×
    pub fn working_copy_with_base_unless_unchanged(
17557×
        &self,
17567×
    ) -> Result<Option<(Change, State, Snapshot)>> {
17577×
        if self.status_by_manifest()?.is_some() {
17585×
            let (_, wc) = self.working_copy()?;
17595×
            if wc.tree_ops.is_empty() && wc.edits.is_empty() {
17603×
                return Ok(None);
17612×
            }
17622×
            let base = self.load_state_indexed(&wc.deps)?;
17632×
            let (base, snapshot) = self.tree_base_for(&wc, base)?;
17642×
            return Ok(Some((wc, base, snapshot)));
17652×
        }
17662×
        let snap = self.snapshot_status("oxy diff")?;
17672×
        Ok(Some((snap.wc, snap.base, snap.base_snapshot)))
17687×
    }
1769
1770
    /// The log restricted to changes touching `path` (its node, so renames
1771
    /// are followed), on the current bookmark.
17725×
    pub fn log_for_path(&self, path: &str) -> Result<Vec<LogEntry>> {
17735×
        let heads = self.bookmark_heads()?;
17745×
        if self.is_bare() {
17751×
            return self.log_for_path_in(path, &heads);
17764×
        }
17774×
        let entries = self.log()?;
17784×
        let (_, wc) = self.working_copy()?;
1779
        // The path's node from the trees alone: the base's (from the
1780
        // workspace's state index), else the bookmark's. Nothing is
1781
        // rendered.
17824×
        let node_in = |state: State| state.tree().view().entries.get(path).map(|e| e.node);
17834×
        let node = match node_in(self.load_state_indexed(&wc.deps)?) {
17844×
            Some(n) => Some(n),
17850×
            None => node_in(self.load_state_history(&heads)?),
1786
        };
17874×
        let Some(node) = node else {
17880×
            return fail(format!("{path} is not tracked"));
1789
        };
17904×
        Ok(self.entries_touching(entries, node))
17915×
    }
1792
1793
    /// The log of the state with these heads restricted to changes touching
1794
    /// `path` (its node, so renames are followed).
17952×
    pub fn log_for_path_in(&self, path: &str, heads: &[ChangeHash]) -> Result<Vec<LogEntry>> {
17962×
        self.log_for_path_of(&self.load_state_history(heads)?, path, None)
17972×
    }
1798
1799
    /// The changes of a loaded state touching `path`, newest first, at most
1800
    /// `limit` of them. The path is found in the state's tree alone, so no
1801
    /// file is rendered, and the walk stops once `limit` are found.
18025×
    pub fn log_for_path_of(
18035×
        &self,
18045×
        state: &State,
18055×
        path: &str,
18065×
        limit: Option<usize>,
18075×
    ) -> Result<Vec<LogEntry>> {
18085×
        let Some(node) = state.tree().view().entries.get(path).map(|e| e.node) else {
18091×
            return fail(format!("{path} is not in that state"));
1810
        };
18114×
        Ok(self.entries_touching_up_to(self.log_of(state), node, limit))
18125×
    }
1813
18144×
    fn entries_touching(&self, entries: Vec<LogEntry>, node: NodeId) -> Vec<LogEntry> {
18154×
        self.entries_touching_up_to(entries, node, None)
18164×
    }
1817
18188×
    fn entries_touching_up_to(
18198×
        &self,
18208×
        entries: Vec<LogEntry>,
18218×
        node: NodeId,
18228×
        limit: Option<usize>,
18238×
    ) -> Vec<LogEntry> {
18248×
        let mut touched = self.touched();
18258×
        if limit.is_none() {
18267×
            let hashes: Vec<ChangeHash> = entries.iter().map(|e| e.hash).collect();
18277×
            touched.fill(self, &hashes);
18281×
        }
18298×
        let wanted = HashSet::from([node]);
18308×
        let mut out = Vec::new();
183128×
        for e in entries {
183228×
            if limit.is_some_and(|n| out.len() >= n) {
18331×
                break;
183427×
            }
183527×
            if touched.touches(self, &e.hash, &wanted) {
183618×
                out.push(e);
183718×
            }
1838
        }
18398×
        touched.save();
18408×
        out
18418×
    }
1842
}
1843
1844
/// Per-file hunks of `change` against `base`.
18456×
pub fn diff_files_of(change: &Change, base: &State, base_snapshot: &Snapshot) -> Vec<FileDiff> {
18466×
    let by_node = base_snapshot.tree.by_node();
18476×
    let mut new_names: HashMap<NodeId, (NodeId, String, NodeKind)> = HashMap::new();
18486×
    for op in &change.tree_ops {
1849
        if let TreeOp::AddNode {
18502×
            node,
18512×
            parent,
18522×
            name,
18532×
            kind,
1854
            ..
18553×
        } = op
18562×
        {
18572×
            new_names.insert(*node, (*parent, name.clone(), *kind));
18582×
        }
1859
    }
186010×
    let path_of = |n: &NodeId| -> String {
186110×
        path_of_node(n, &by_node, &new_names).unwrap_or_else(|| format!("<node {}>", n.short(8)))
186210×
    };
18636×
    let mut files: BTreeMap<NodeId, FileDiff> = BTreeMap::new();
18646×
    let mut order: Vec<NodeId> = Vec::new();
186515×
    let mut entry = |files: &mut BTreeMap<NodeId, FileDiff>, n: NodeId, kind: &str| {
186615×
        if let std::collections::btree_map::Entry::Vacant(v) = files.entry(n) {
186710×
            order.push(n);
186810×
            v.insert(FileDiff {
186910×
                path: path_of(&n),
187010×
                kind: kind.to_string(),
187110×
                hunks: vec![],
187210×
                from: None,
187310×
            });
187410×
        }
187515×
    };
18766×
    for op in &change.tree_ops {
18773×
        match op {
18782×
            TreeOp::AddNode { node, kind, .. } => {
18792×
                if *kind != NodeKind::Dir {
18802×
                    entry(&mut files, *node, "added");
18812×
                }
1882
            }
18831×
            TreeOp::RemoveNode { node, .. } => {
18841×
                entry(&mut files, *node, "removed");
18851×
                if let Some(e) = by_node.get(node) {
18861×
                    files.get_mut(node).unwrap().path = e.path.clone();
18871×
                }
1888
            }
1889
            TreeOp::Move {
18900×
                node, parent, name, ..
1891
            } => {
18920×
                entry(&mut files, *node, "renamed");
18930×
                let f = files.get_mut(node).unwrap();
18940×
                f.from = by_node.get(node).map(|e| e.path.clone());
18950×
                let dir = if parent.is_root() {
18960×
                    String::new()
1897
                } else {
18980×
                    path_of_node(parent, &by_node, &new_names).unwrap_or_default()
1899
                };
19000×
                f.path = if dir.is_empty() {
19010×
                    name.clone()
1902
                } else {
19030×
                    format!("{dir}/{name}")
1904
                };
1905
            }
19060×
            TreeOp::SetMode { node, .. } => entry(&mut files, *node, "mode"),
1907
        }
1908
    }
1909
    // Base line numbers per node, 1-based.
19106×
    let mut line_of: HashMap<NodeId, HashMap<(ChangeHash, u32), u32>> = HashMap::new();
191112×
    let mut lines_for = |n: &NodeId| -> HashMap<(ChangeHash, u32), u32> {
191212×
        line_of
191312×
            .entry(*n)
191412×
            .or_insert_with(|| {
19159×
                base.live_lines(n)
19169×
                    .into_iter()
19179×
                    .enumerate()
191812×
                    .map(|(i, (k, _))| (k, i as u32 + 1))
19199×
                    .collect()
19209×
            })
192112×
            .clone()
192212×
    };
192312×
    for e in &change.edits {
192412×
        let n = e.node();
192512×
        let is_new = new_names.contains_key(&n);
192612×
        entry(&mut files, n, if is_new { "added" } else { "modified" });
192712×
        let f = files.get_mut(&n).unwrap();
192812×
        match e {
192910×
            Edit::Insert { after, lines, .. } => {
193010×
                let map = lines_for(&n);
193110×
                let base_line = match after {
19323×
                    AtomRef::Start => 0,
19330×
                    AtomRef::End => map.len() as u32,
19347×
                    AtomRef::Atom { change, index } if change.is_zero() => {
19350×
                        f.hunks.last().map(|h| h.base_line).unwrap_or(0)
1936
                    }
19377×
                    AtomRef::Atom { change, index } => {
19387×
                        map.get(&(*change, *index)).copied().unwrap_or(0)
1939
                    }
1940
                };
194110×
                f.hunks.push(DiffHunk {
194210×
                    base_line,
194310×
                    added: lines.to_vec(),
194410×
                    removed: vec![],
194510×
                });
1946
            }
19472×
            Edit::Delete { atoms, .. } => {
19482×
                let map = lines_for(&n);
19492×
                let mut removed = Vec::new();
19502×
                for r in atoms {
19512×
                    for i in r.from..r.to {
19522×
                        let line = map.get(&(r.change, i)).copied().unwrap_or(0);
19532×
                        let text = base
19542×
                            .file(&n)
19552×
                            .and_then(|g| g.content(&(r.change, i)))
19562×
                            .unwrap_or(b"")
19572×
                            .to_vec();
19582×
                        removed.push((line, text));
1959
                    }
1960
                }
19612×
                let base_line = removed
19622×
                    .first()
19632×
                    .map(|(l, _)| l.saturating_sub(1))
19642×
                    .unwrap_or(0);
19652×
                f.hunks.push(DiffHunk {
19662×
                    base_line,
19672×
                    added: vec![],
19682×
                    removed,
19692×
                });
1970
            }
1971
            Edit::Replace { .. } => {
19720×
                if !is_new {
19730×
                    f.kind = "replaced".into();
19740×
                }
1975
            }
1976
        }
1977
    }
197810×
    order.into_iter().filter_map(|n| files.remove(&n)).collect()
19796×
}
1980
1981
/// Builds the tree ops and edits of a working-copy change against a base.
1982
/// `BLAKE3("oxy node 1" 0 seed kind path)`, truncated: a node identifier
1983
/// that the same seed and path always give (never the root's).
198459×
fn seeded_node(seed: &[u8; 32], path: &str, kind: NodeKind) -> NodeId {
198559×
    let mut h = blake3::Hasher::new();
198659×
    h.update(b"oxy node 1\0");
198759×
    h.update(seed);
198859×
    h.update(&[match kind {
198945×
        NodeKind::File => 1,
199013×
        NodeKind::Dir => 2,
19910×
        NodeKind::Symlink => 3,
19921×
        NodeKind::Subrepo => 4,
1993
    }]);
199459×
    h.update(path.as_bytes());
199559×
    let mut id = [0u8; 16];
199659×
    id.copy_from_slice(&h.finalize().as_bytes()[..16]);
199759×
    if id == [0; 16] {
19980×
        id[15] = 1;
199959×
    }
200059×
    NodeId(id)
200159×
}
2002
2003
struct ChangeBuilder<'a> {
2004
    base: &'a State,
2005
    base_snapshot: &'a Snapshot,
2006
    tree_ops: Vec<TreeOp>,
2007
    edits: Vec<Edit>,
2008
    statuses: Vec<PathStatus>,
2009
    dir_nodes: HashMap<String, NodeId>,
2010
    reuse: HashMap<String, (NodeId, NodeKind)>,
2011
    /// Changes that contributed to conflicts this working copy resolves.
2012
    contributors: BTreeSet<ChangeHash>,
2013
    resolves: bool,
2014
    attrs: crate::attributes::Attributes,
2015
    blobs: HashMap<String, ObjectRef>,
2016
    /// Opaque files whose replace conflict the content settles.
2017
    resolve: HashSet<String>,
2018
    /// When set, new nodes' identifiers derive from it and their paths.
2019
    node_seed: Option<[u8; 32]>,
2020
    /// For a Git import, the base's dead directories by where they were
2021
    /// (see `ensure_dir`), worked out when first needed.
2022
    dead_dirs: Option<HashMap<(NodeId, String), (NodeId, crate::tree::OpKey)>>,
2023
    /// Text edits of edited files, worked out in parallel beforehand
2024
    /// (`diff_in_parallel`); a file not here is diffed when it is updated.
2025
    diffs: HashMap<String, Vec<Edit>>,
2026
}
2027
2028
impl<'a> ChangeBuilder<'a> {
20292048×
    fn new(
20302048×
        base: &'a State,
20312048×
        base_snapshot: &'a Snapshot,
20322048×
        reuse: HashMap<String, (NodeId, NodeKind)>,
20332048×
    ) -> Self {
20342048×
        let mut dir_nodes: HashMap<String, NodeId> = HashMap::new();
20352048×
        dir_nodes.insert(String::new(), NodeId::ROOT);
203617844×
        for (p, e) in base_snapshot.tree.entries.iter() {
203717844×
            if e.kind == NodeKind::Dir {
2038568×
                dir_nodes.insert(p.clone(), e.node);
203917276×
            }
2040
        }
20412048×
        ChangeBuilder {
20422048×
            base,
20432048×
            base_snapshot,
20442048×
            tree_ops: vec![],
20452048×
            edits: vec![],
20462048×
            statuses: vec![],
20472048×
            dir_nodes,
20482048×
            reuse,
20492048×
            contributors: BTreeSet::new(),
20502048×
            resolves: false,
20512048×
            attrs: crate::attributes::Attributes::default(),
20522048×
            blobs: HashMap::new(),
20532048×
            resolve: HashSet::new(),
20542048×
            node_seed: None,
20552048×
            dead_dirs: None,
20562048×
            diffs: HashMap::new(),
20572048×
        }
20582048×
    }
2059
2060
    /// Diff the edited text files among `entries` against their base
2061
    /// renderings at once, on every core, for `update_path` to take: the
2062
    /// same diff it would make, only not one file after another.
20632048×
    fn diff_in_parallel(&mut self, entries: &BTreeMap<String, FsEntry>) {
2064
        use rayon::prelude::*;
20652048×
        let files = &self.base_snapshot.files;
20662048×
        let edited: Vec<(&String, &FsEntry, &crate::state::FileState)> = entries
20672048×
            .iter()
206818872×
            .filter_map(|(p, e)| {
206918872×
                let x = files.get(p)?;
207012803×
                (x.kind == e.kind && !e.unchanged && !self.opaque_for(p, e)).then_some((p, e, x))
207118872×
            })
20722048×
            .collect();
2073
        // Below this, starting the threads costs more than it saves.
20742048×
        if edited.len() < 16 {
20752038×
            return;
207610×
        }
207710×
        let this = &*self;
207810×
        let attrs = &this.attrs;
207910×
        let diffs: Vec<(String, Vec<Edit>)> = edited
208010×
            .par_iter()
20815564×
            .filter_map(|(p, e, x)| {
2082
                let FileContent::Text {
20835564×
                    bytes,
20845564×
                    materialized,
20855564×
                } = &x.content
2086
                else {
20870×
                    return None;
2088
                };
20895564×
                if materialized.is_conflicted() {
20900×
                    return None;
20915564×
                }
20925564×
                let disk_text = if attrs.lookup(p).eol.is_some() {
20930×
                    std::sync::Arc::new(crate::attributes::normalize_eol(&e.content))
2094
                } else {
20955564×
                    e.content.clone()
2096
                };
20975564×
                if *bytes == *disk_text {
20985484×
                    return None;
209980×
                }
210080×
                let keys = materialized.live_atoms();
210180×
                let lines = crate::diff::split_lines(bytes);
210280×
                (keys.len() == lines.len()).then(|| {
210380×
                    let edits = crate::diff::text_edits_of(x.node, &keys, &lines, &disk_text);
210480×
                    ((*p).clone(), edits)
210580×
                })
21065564×
            })
210710×
            .collect();
210810×
        self.diffs = diffs.into_iter().collect();
21092048×
    }
2110
21112048×
    fn with_attributes(mut self, attrs: crate::attributes::Attributes) -> Self {
21122048×
        self.attrs = attrs;
21132048×
        self
21142048×
    }
2115
2116
    /// Whether a file is opaque: forced by `binary`, forced text by `text`
2117
    /// only when it has no NUL bytes, else sniffed.
2118
    /// The blob for an opaque entry: the cached one, else stored now.
2119132×
    fn blob_of(
2120132×
        &mut self,
2121132×
        repo: &Repo,
2122132×
        path: &str,
2123132×
        e: &FsEntry,
2124132×
        nocompress: bool,
2125132×
    ) -> Result<ObjectRef> {
2126132×
        let b = match e.blob {
21270×
            Some(b) => b,
2128132×
            None => repo.store_blob_for(&e.content, nocompress)?,
2129
        };
2130132×
        self.blobs.insert(path.to_string(), b);
2131132×
        Ok(b)
2132132×
    }
2133
213423188×
    fn opaque_for(&self, path: &str, e: &FsEntry) -> bool {
213523188×
        if e.blob.is_some() {
21368×
            return true;
213723180×
        }
213823180×
        if e.kind == NodeKind::Symlink || e.kind == NodeKind::Subrepo {
213979×
            return true;
214023101×
        }
214123101×
        match self.attrs.lookup(path).binary {
214212×
            Some(true) => true,
21430×
            Some(false) => is_binary(&e.content),
214423089×
            None => is_binary(&e.content),
2145
        }
214623188×
    }
2147
2148
    /// Text content as stored: `\r\n` normalized for `eol=` files.
214914506×
    fn stored_text(
215014506×
        &self,
215114506×
        path: &str,
215214506×
        content: &std::sync::Arc<Vec<u8>>,
215314506×
    ) -> std::sync::Arc<Vec<u8>> {
215414506×
        if self.attrs.lookup(path).eol.is_some() {
21557×
            std::sync::Arc::new(crate::attributes::normalize_eol(content))
2156
        } else {
215714499×
            content.clone()
2158
        }
215914506×
    }
2160
2161
    /// The identifier of a node added at `path`: reused when asked, derived
2162
    /// from the seed when there is one, random otherwise.
21636191×
    fn new_node(&self, path: &str, kind: NodeKind) -> NodeId {
21646191×
        if let Some(n) = self.reused_node(path, kind) {
2165141×
            return n;
21666050×
        }
21676050×
        match &self.node_seed {
216859×
            Some(seed) => seeded_node(seed, path, kind),
21695991×
            None => NodeId::random(),
2170
        }
21716191×
    }
2172
21736191×
    fn reused_node(&self, path: &str, kind: NodeKind) -> Option<NodeId> {
21746191×
        self.reuse
21756191×
            .get(path)
21766191×
            .filter(|(_, k)| *k == kind)
21776191×
            .map(|(n, _)| *n)
21786191×
    }
2179
2180
    /// A dead directory last placed at (`parent`, `name`) in the base.
218115×
    fn revivable_dir(
218215×
        &mut self,
218315×
        parent: NodeId,
218415×
        name: &str,
218515×
    ) -> Option<(NodeId, crate::tree::OpKey)> {
218615×
        let base = self.base;
218715×
        self.dead_dirs
218815×
            .get_or_insert_with(|| base.tree().dead_dirs())
218915×
            .get(&(parent, name.to_string()))
219015×
            .copied()
219115×
    }
2192
21936070×
    fn ensure_dir(&mut self, path: &str) -> NodeId {
21946070×
        if let Some(n) = self.dir_nodes.get(path) {
21955920×
            return *n;
2196150×
        }
2197150×
        let mut parent = NodeId::ROOT;
2198150×
        let mut prefix = String::new();
2199169×
        for comp in path.split('/') {
2200169×
            if !prefix.is_empty() {
220119×
                prefix.push('/');
2202150×
            }
2203169×
            prefix.push_str(comp);
2204169×
            let known = self.dir_nodes.get(&prefix).copied();
2205169×
            let revive = match known {
220613×
                Some(_) => None,
2207156×
                None if self.node_seed.is_some() => self.revivable_dir(parent, comp),
2208141×
                None => None,
2209
            };
2210169×
            parent = match (known, revive) {
221113×
                (Some(n), _) => n,
22122×
                (None, Some((node, old))) => {
2213
                    // Git has no identity for a directory: one that comes
2214
                    // back where it was is the same directory, brought back
2215
                    // with a move, so lines of history that placed files in
2216
                    // it before and after agree (oxygen#30).
22172×
                    self.tree_ops.push(TreeOp::Move {
22182×
                        node,
22192×
                        old: OpRef {
22202×
                            change: old.0,
22212×
                            index: old.1,
22222×
                        },
22232×
                        parent,
22242×
                        name: comp.to_string(),
22252×
                    });
22262×
                    self.dir_nodes.insert(prefix.clone(), node);
22272×
                    node
2228
                }
2229
                (None, None) => {
2230154×
                    let node = self.new_node(&prefix, NodeKind::Dir);
2231154×
                    self.tree_ops.push(TreeOp::AddNode {
2232154×
                        node,
2233154×
                        kind: NodeKind::Dir,
2234154×
                        mode: Mode::default(),
2235154×
                        parent,
2236154×
                        name: comp.to_string(),
2237154×
                    });
2238154×
                    self.dir_nodes.insert(prefix.clone(), node);
2239154×
                    node
2240
                }
2241
            };
2242
        }
2243150×
        parent
22446070×
    }
2245
22466037×
    fn add_path(&mut self, repo: &Repo, path: &str, e: &FsEntry) -> Result<()> {
22476037×
        let (dir, name) = split_path(path);
22486037×
        let parent = self.ensure_dir(dir);
22496037×
        let node = self.new_node(path, e.kind);
22506037×
        let opaque = self.opaque_for(path, e);
22516037×
        let nocompress = self.attrs.lookup(path).nocompress;
22526037×
        self.tree_ops.push(TreeOp::AddNode {
22536037×
            node,
22546037×
            kind: e.kind,
22556037×
            mode: Mode {
22566037×
                exec: e.exec,
22576037×
                opaque,
22586037×
            },
22596037×
            parent,
22606037×
            name: name.to_string(),
22616037×
        });
22626037×
        if opaque {
226396×
            let blob = self.blob_of(repo, path, e, nocompress)?;
226496×
            self.edits.push(Edit::Replace {
226596×
                node,
226696×
                old: None,
226796×
                new: Some(blob),
226896×
            });
22695941×
        } else if !e.content.is_empty() {
22705914×
            let content = self.stored_text(path, &e.content);
22715914×
            self.edits.push(Edit::Insert {
22725914×
                node,
22735914×
                after: crate::objects::AtomRef::Start,
22745914×
                before: crate::objects::AtomRef::End,
22755914×
                lines: crate::lines::Lines::split_shared(content),
22765914×
            });
22775914×
        }
22786037×
        self.statuses.push(PathStatus {
22796037×
            path: path.to_string(),
22806037×
            status: ChangeStatus::Added,
22816037×
        });
22826037×
        Ok(())
22836037×
    }
2284
2285
    /// Move the node at `old` to `new` and apply `e`'s content to it.
228633×
    fn move_path(
228733×
        &mut self,
228833×
        repo: &Repo,
228933×
        old: &str,
229033×
        new: &str,
229133×
        e: &FsEntry,
229233×
        expected: &crate::state::FileState,
229333×
    ) -> Result<()> {
229433×
        let placement = self.base_snapshot.tree.entries[old].placement;
229533×
        let (dir, name) = split_path(new);
229633×
        let parent = self.ensure_dir(dir);
229733×
        self.tree_ops.push(TreeOp::Move {
229833×
            node: expected.node,
229933×
            old: op_ref(placement),
230033×
            parent,
230133×
            name: name.to_string(),
230233×
        });
230333×
        for k in self.same_place(&expected.node, placement) {
23040×
            self.tree_ops.push(TreeOp::RemoveNode {
23050×
                node: expected.node,
23060×
                placement: op_ref(k),
23070×
            });
23080×
        }
230933×
        self.update_path(repo, old, e, expected)?;
2310
        // update_path reports under the old path; the rename is what the user sees.
231133×
        self.statuses.retain(|s| s.path != old);
231233×
        self.statuses.push(PathStatus {
231333×
            path: new.to_string(),
231433×
            status: ChangeStatus::Renamed,
231533×
        });
231633×
        Ok(())
231733×
    }
2318
2319
    /// For a Git import: a node the commit keeps is in one place, the one
2320
    /// its tree names, so any other live placement it has in the base goes;
2321
    /// and a node the tree cannot show at all (an orphan) goes too. Such a
2322
    /// placement is out of sight, under a directory another line of history
2323
    /// removed, where no diff of the tree would ever reach it (oxygen#30).
232488×
    fn retire_stray_placements(&mut self) {
232588×
        let mut retired: HashSet<(ChangeHash, u32)> = HashSet::new();
232688×
        let mut placed: BTreeSet<NodeId> = BTreeSet::new();
232799×
        for op in &self.tree_ops {
232899×
            match op {
232919×
                TreeOp::Move { node, old, .. } => {
233019×
                    retired.insert((old.change, old.index));
233119×
                    placed.insert(*node);
233219×
                }
233321×
                TreeOp::RemoveNode { placement, .. } => {
233421×
                    retired.insert((placement.change, placement.index));
233521×
                }
233659×
                TreeOp::AddNode { .. } | TreeOp::SetMode { .. } => {}
2337
            }
2338
        }
2339
        // Nodes kept where they were: what the base's tree view shows and
2340
        // this change neither moves nor removes.
234188×
        let mut kept: HashMap<NodeId, (ChangeHash, u32)> = HashMap::new();
2342241×
        for e in self.base_snapshot.tree.entries.values() {
2343241×
            if !retired.contains(&e.placement) {
2344204×
                kept.insert(e.node, e.placement);
2345204×
            }
2346
        }
2347
        // Only a node with several live placements can have a stray one,
2348
        // and the tree view names each as a conflict.
234988×
        let multi: BTreeSet<NodeId> = self
235088×
            .base_snapshot
235188×
            .tree
235288×
            .conflicts
235388×
            .iter()
235488×
            .filter_map(|c| match c {
23551×
                crate::tree::TreeConflict::MultiPlacement { node, .. } => Some(*node),
23566×
                _ => None,
23577×
            })
235888×
            .collect();
235988×
        let mut extra = Vec::new();
2360
        // A node whose only placements are under a directory another line
2361
        // removed (an orphan) is nowhere the tree can show, and Git's tree
2362
        // has no such path: it goes.
236388×
        for c in &self.base_snapshot.tree.conflicts {
23647×
            let crate::tree::TreeConflict::Orphan { node, .. } = c else {
23656×
                continue;
2366
            };
23671×
            if kept.contains_key(node) || placed.contains(node) {
23680×
                continue;
23691×
            }
23701×
            for (k, _) in self.base.tree().live_placements(node) {
23711×
                if retired.insert(k) {
23721×
                    extra.push(TreeOp::RemoveNode {
23731×
                        node: *node,
23741×
                        placement: op_ref(k),
23751×
                    });
23761×
                }
2377
            }
2378
        }
237988×
        for node in placed
238088×
            .iter()
238188×
            .chain(multi.iter().filter(|n| kept.contains_key(*n)))
2382
        {
238319×
            for (k, _) in self.base.tree().live_placements(node) {
238418×
                if retired.contains(&k) || kept.get(node) == Some(&k) {
238517×
                    continue;
23861×
                }
23871×
                retired.insert(k);
23881×
                extra.push(TreeOp::RemoveNode {
23891×
                    node: *node,
23901×
                    placement: op_ref(k),
23911×
                });
2392
            }
2393
        }
239488×
        if !extra.is_empty() {
23952×
            self.resolves = true;
23962×
            self.tree_ops.extend(extra);
239786×
        }
239888×
    }
2399
2400
    /// The node's other live placements at the same place as `k`, the one
2401
    /// the tree shows: two lines of history that put a node back where it
2402
    /// was each leave a placement, and the tree shows them as one file. A
2403
    /// change that removes or moves it retires them together, or the copy
2404
    /// left behind outlives its directory (oxygen#88).
2405164×
    fn same_place(&self, node: &NodeId, k: (ChangeHash, u32)) -> Vec<(ChangeHash, u32)> {
2406164×
        let tree = self.base.tree();
2407164×
        let Some(shown) = tree.placement(&k) else {
24080×
            return Vec::new();
2409
        };
2410164×
        tree.live_placements(node)
2411164×
            .into_iter()
2412166×
            .filter(|(o, p)| *o != k && p.parent == shown.parent && p.name == shown.name)
2413164×
            .map(|(o, _)| o)
2414164×
            .collect()
2415164×
    }
2416
2417131×
    fn remove_path(&mut self, path: &str, expected: &crate::state::FileState) {
2418131×
        let entry = &self.base_snapshot.tree.entries[path];
2419131×
        let placement = entry.placement;
2420131×
        self.tree_ops.push(TreeOp::RemoveNode {
2421131×
            node: expected.node,
2422131×
            placement: op_ref(placement),
2423131×
        });
2424131×
        for k in self.same_place(&expected.node, placement) {
24251×
            self.tree_ops.push(TreeOp::RemoveNode {
24261×
                node: expected.node,
24271×
                placement: op_ref(k),
24281×
            });
24291×
        }
2430131×
        if path.contains(".oxy-conflict-") || expected.is_conflicted() {
24317×
            self.resolves = true;
2432124×
        }
2433131×
        self.statuses.push(PathStatus {
2434131×
            path: path.to_string(),
2435131×
            status: ChangeStatus::Removed,
2436131×
        });
2437131×
    }
2438
243912836×
    fn update_path(
244012836×
        &mut self,
244112836×
        repo: &Repo,
244212836×
        path: &str,
244312836×
        e: &FsEntry,
244412836×
        expected: &crate::state::FileState,
244512836×
    ) -> Result<()> {
244612836×
        if expected.kind != e.kind {
24471×
            self.remove_path(path, expected);
24481×
            self.statuses.pop();
24491×
            self.add_path(repo, path, e)?;
24501×
            self.statuses.pop();
24511×
            self.statuses.push(PathStatus {
24521×
                path: path.to_string(),
24531×
                status: ChangeStatus::Modified,
24541×
            });
24551×
            return Ok(());
245612835×
        }
245712835×
        let entry = &self.base_snapshot.tree.entries[path];
245812835×
        let node = expected.node;
245912835×
        let mode_atom = entry.mode_atom.map(op_ref);
246012835×
        if e.unchanged {
2461
            // Known equal to the base's unconflicted rendering (spec
2462
            // §12.3); only the executable bit can differ.
24634243×
            if e.exec != expected.mode.exec {
24643×
                if let Some(old) = mode_atom {
24653×
                    self.tree_ops.push(TreeOp::SetMode {
24663×
                        node,
24673×
                        old,
24683×
                        mode: Mode {
24693×
                            exec: e.exec,
24703×
                            opaque: false,
24713×
                        },
24723×
                    });
24733×
                    self.statuses.push(PathStatus {
24743×
                        path: path.to_string(),
24753×
                        status: ChangeStatus::ModeChanged,
24763×
                    });
24773×
                }
24784240×
            }
24794243×
            return Ok(());
24808592×
        }
24818592×
        let mut status: Option<ChangeStatus> = None;
24828592×
        let wants_opaque = self.opaque_for(path, e);
24838592×
        let nocompress = self.attrs.lookup(path).nocompress;
24848592×
        let disk_text = self.stored_text(path, &e.content);
24858592×
        match &expected.content {
24860×
            FileContent::Dir => {}
2487
            FileContent::Text {
24888368×
                bytes,
24898368×
                materialized,
2490
            } => {
24918368×
                if materialized.is_conflicted() {
249233×
                    if bytes == &*disk_text {
24936×
                        return Ok(());
249427×
                    }
249527×
                    if has_conflict_markers(&e.content) {
24964×
                        self.statuses.push(PathStatus {
24974×
                            path: path.to_string(),
24984×
                            status: ChangeStatus::ConflictEdited,
24994×
                        });
25004×
                        return Ok(());
250123×
                    }
2502
                    // Resolution (spec §9.6): diff against the unconflicted lines
2503
                    // with each region as a gap, then retire every region atom.
2504
                    // Whatever the author kept from a region is re-inserted as
2505
                    // new atoms, which leaves the graph totally ordered.
250623×
                    let regions = self.base.conflict_regions(&node);
250723×
                    let mut edits = text_edits(node, &regions.plain, &disk_text);
250823×
                    if !regions.region_atoms.is_empty() {
250923×
                        edits.insert(
251023×
                            0,
251123×
                            Edit::Delete {
251223×
                                node,
251323×
                                atoms: ranges(&regions.region_atoms),
251423×
                            },
251523×
                        );
251623×
                    }
251723×
                    self.edits.extend(edits);
251823×
                    self.contributors.extend(regions.contributors);
251923×
                    self.resolves = true;
252023×
                    if e.exec != expected.mode.exec {
25210×
                        if let Some(old) = mode_atom {
25220×
                            self.tree_ops.push(TreeOp::SetMode {
25230×
                                node,
25240×
                                old,
25250×
                                mode: Mode {
25260×
                                    exec: e.exec,
25270×
                                    opaque: false,
25280×
                                },
25290×
                            });
25300×
                        }
253123×
                    }
253223×
                    self.statuses.push(PathStatus {
253323×
                        path: path.to_string(),
253423×
                        status: ChangeStatus::Resolved,
253523×
                    });
253623×
                    return Ok(());
25378335×
                }
25388335×
                if wants_opaque {
2539
                    // Text → opaque (spec §7.5), by content or by attribute.
25402×
                    if let Some(old) = mode_atom {
25412×
                        self.tree_ops.push(TreeOp::SetMode {
25422×
                            node,
25432×
                            old,
25442×
                            mode: Mode {
25452×
                                exec: e.exec,
25462×
                                opaque: true,
25472×
                            },
25482×
                        });
25492×
                    }
25502×
                    let live: Vec<_> = repo_live_keys(self.base, &node);
25512×
                    if !live.is_empty() {
25522×
                        self.edits.push(Edit::Delete {
25532×
                            node,
25542×
                            atoms: ranges(&live),
25552×
                        });
25562×
                    }
25572×
                    let blob = self.blob_of(repo, path, e, nocompress)?;
25582×
                    self.edits.push(Edit::Replace {
25592×
                        node,
25602×
                        old: None,
25612×
                        new: Some(blob),
25622×
                    });
25632×
                    status = Some(ChangeStatus::Modified);
25648333×
                } else if bytes != &*disk_text {
2565842×
                    let mut laps = crate::timing::Laps::start();
2566
                    // The base's rendering holds its live atoms in order,
2567
                    // one per line (it is not conflicted here).
2568842×
                    let edits = match self.diffs.remove(path) {
256980×
                        Some(edits) => edits,
2570
                        None => {
2571762×
                            let keys = materialized.live_atoms();
2572762×
                            let lines = crate::diff::split_lines(bytes);
2573762×
                            if keys.len() == lines.len() {
2574762×
                                crate::diff::text_edits_of(node, &keys, &lines, &disk_text)
2575
                            } else {
25760×
                                text_edits(node, &self.base.live_lines(&node), &disk_text)
2577
                            }
2578
                        }
2579
                    };
2580842×
                    laps.lap("build: text diff");
2581842×
                    if !edits.is_empty() {
2582842×
                        self.edits.extend(edits);
2583842×
                        status = Some(ChangeStatus::Modified);
2584842×
                    }
25857491×
                }
25868335×
                let switched_to_opaque = wants_opaque;
25878335×
                if !switched_to_opaque && e.exec != expected.mode.exec {
25884×
                    if let Some(old) = mode_atom {
25894×
                        self.tree_ops.push(TreeOp::SetMode {
25904×
                            node,
25914×
                            old,
25924×
                            mode: Mode {
25934×
                                exec: e.exec,
25944×
                                opaque: false,
25954×
                            },
25964×
                        });
25974×
                        status.get_or_insert(ChangeStatus::ModeChanged);
25984×
                    }
25998331×
                }
2600
            }
2601224×
            FileContent::Opaque { blobs } => {
2602224×
                let new_ref = e.blob.unwrap_or_else(|| Repo::blob_ref(&e.content));
2603224×
                if e.kind == NodeKind::File && wants_opaque {
2604191×
                    // Unchanged or replaced, the file stays opaque: remember its blob.
2605191×
                    self.blobs.insert(path.to_string(), new_ref);
2606191×
                }
2607224×
                if blobs.len() > 1 && self.resolve.contains(path) && e.kind == expected.kind {
2608
                    // Settle the replace conflict (spec §9.3): replace every
2609
                    // live candidate with the chosen blob, depending on each
2610
                    // change that made one live, so all are superseded.
26112×
                    let chosen = self.blob_of(repo, path, e, nocompress)?;
26124×
                    for b in blobs {
26134×
                        self.edits.push(Edit::Replace {
26144×
                            node,
26154×
                            old: Some(*b),
26164×
                            new: Some(chosen),
26174×
                        });
26184×
                    }
26192×
                    self.contributors
26202×
                        .extend(self.base.blob_contributors(&node, blobs));
26212×
                    self.resolves = true;
26222×
                    self.statuses.push(PathStatus {
26232×
                        path: path.to_string(),
26242×
                        status: ChangeStatus::Resolved,
26252×
                    });
26262×
                    return Ok(());
2627222×
                }
2628222×
                if blobs.len() > 1 {
26292×
                    if !blobs.contains(&new_ref) {
26300×
                        self.statuses.push(PathStatus {
26310×
                            path: path.to_string(),
26320×
                            status: ChangeStatus::ConflictEdited,
26330×
                        });
26342×
                    }
26352×
                    return Ok(());
2636220×
                }
2637220×
                let current = blobs.first().copied();
2638220×
                if current != Some(new_ref) {
263934×
                    if e.kind == NodeKind::File && !wants_opaque {
2640
                        // Opaque → text (spec §7.5).
26412×
                        if let Some(old) = mode_atom {
26422×
                            self.tree_ops.push(TreeOp::SetMode {
26432×
                                node,
26442×
                                old,
26452×
                                mode: Mode {
26462×
                                    exec: e.exec,
26472×
                                    opaque: false,
26482×
                                },
26492×
                            });
26502×
                        }
26512×
                        self.edits.push(Edit::Replace {
26522×
                            node,
26532×
                            old: current,
26542×
                            new: None,
26552×
                        });
26562×
                        if !e.content.is_empty() {
26572×
                            self.edits.push(Edit::Insert {
26582×
                                node,
26592×
                                after: crate::objects::AtomRef::Start,
26602×
                                before: crate::objects::AtomRef::End,
26612×
                                lines: crate::lines::Lines::split(&e.content),
26622×
                            });
26632×
                        }
2664
                    } else {
266532×
                        let blob = self.blob_of(repo, path, e, nocompress)?;
266632×
                        self.edits.push(Edit::Replace {
266732×
                            node,
266832×
                            old: current,
266932×
                            new: Some(blob),
267032×
                        });
2671
                        // New contents and a new executable bit at once: the
2672
                        // bit was dropped (VS Code's inno_updater.exe,
2673
                        // 2018-02-28, lost +x for 49 commits; oxygen#87).
267432×
                        if e.kind == NodeKind::File && e.exec != expected.mode.exec {
26752×
                            if let Some(old) = mode_atom {
26762×
                                self.tree_ops.push(TreeOp::SetMode {
26772×
                                    node,
26782×
                                    old,
26792×
                                    mode: Mode {
26802×
                                        exec: e.exec,
26812×
                                        opaque: true,
26822×
                                    },
26832×
                                });
26842×
                            }
268530×
                        }
2686
                    }
268734×
                    status = Some(ChangeStatus::Modified);
2688186×
                } else if e.kind == NodeKind::File && e.exec != expected.mode.exec {
26890×
                    if let Some(old) = mode_atom {
26900×
                        self.tree_ops.push(TreeOp::SetMode {
26910×
                            node,
26920×
                            old,
26930×
                            mode: Mode {
26940×
                                exec: e.exec,
26950×
                                opaque: true,
26960×
                            },
26970×
                        });
26980×
                        status = Some(ChangeStatus::ModeChanged);
26990×
                    }
2700186×
                }
2701
            }
2702
        }
27038555×
        if let Some(s) = status {
2704882×
            self.statuses.push(PathStatus {
2705882×
                path: path.to_string(),
2706882×
                status: s,
2707882×
            });
27087673×
        }
27098555×
        Ok(())
271012836×
    }
2711
}
2712
27132×
fn repo_live_keys(base: &State, node: &NodeId) -> Vec<crate::graph::AtomKey> {
27142×
    base.live_lines(node).into_iter().map(|(k, _)| k).collect()
27152×
}
2716
2717
/// The changes a change's scope references (spec §8.1): introducers of every
2718
/// atom, placement, and mode it touches, and of every node it operates on.
27192143×
pub fn referenced_changes(change: &Change, base: &State) -> BTreeSet<ChangeHash> {
27202143×
    let mut out = BTreeSet::new();
27212143×
    let opref = |r: &OpRef, out: &mut BTreeSet<ChangeHash>| {
2722191×
        if !r.change.is_zero() {
2723191×
            out.insert(r.change);
2724191×
        }
2725191×
    };
27262143×
    let mut nodes: Vec<NodeId> = Vec::new();
27276596×
    for op in &change.tree_ops {
27286596×
        match op {
27296405×
            TreeOp::AddNode { parent, .. } => nodes.push(*parent),
2730143×
            TreeOp::RemoveNode { node, placement } => {
2731143×
                nodes.push(*node);
2732143×
                opref(placement, &mut out);
2733143×
            }
2734
            TreeOp::Move {
273536×
                node, old, parent, ..
273636×
            } => {
273736×
                nodes.push(*node);
273836×
                nodes.push(*parent);
273936×
                opref(old, &mut out);
274036×
            }
274112×
            TreeOp::SetMode { node, old, .. } => {
274212×
                nodes.push(*node);
274312×
                opref(old, &mut out);
274412×
            }
2745
        }
2746
    }
27478290×
    for e in &change.edits {
27488290×
        nodes.push(e.node());
2749134×
        match e {
27507573×
            Edit::Insert { after, before, .. } => {
275115146×
                for r in [after, before] {
275215146×
                    if let crate::objects::AtomRef::Atom { change, .. } = r {
27532304×
                        if !change.is_zero() {
27542302×
                            out.insert(*change);
27552302×
                        }
275612842×
                    }
2757
                }
2758
            }
2759583×
            Edit::Delete { atoms, .. } => {
2760
                // Deleting an atom also depends on whoever inserted the live
2761
                // atoms right after it: the author saw those insertions, and
2762
                // without the dependency spec §9.1 would call the deletion
2763
                // concurrent with them (a delete/insert conflict).
2764583×
                let graph = base.file(&e.node());
27651132×
                for r in atoms {
27661132×
                    if !r.change.is_zero() {
27671131×
                        out.insert(r.change);
27681131×
                    }
27691132×
                    if let Some(g) = graph {
27701157×
                        for i in r.from..r.to {
27711157×
                            out.extend(
27721157×
                                g.live_successor_changes(&(r.change, i))
27731157×
                                    .into_iter()
27741157×
                                    .filter(|c| !c.is_zero()),
2775
                            );
2776
                        }
27770×
                    }
2778
                }
2779
            }
2780
            // Replacing a blob depends on the change that made it current,
2781
            // as deleting a line depends on the line's introducer.
2782
            Edit::Replace {
278339×
                node,
278439×
                old: Some(old),
2785
                ..
2786
            } => {
278739×
                out.extend(
278839×
                    base.live_replaces(node)
278939×
                        .into_iter()
279046×
                        .filter(|(c, b)| b == old && !c.is_zero())
279139×
                        .map(|(c, _)| c),
2792
                );
2793
            }
279495×
            Edit::Replace { .. } => {}
2795
        }
2796
    }
279714922×
    for n in nodes {
279814922×
        if let Some(h) = base.tree().introducer(&n) {
27992334×
            out.insert(h);
280012588×
        }
2801
    }
28022143×
    out
28032143×
}
2804
2805
/// Paths of the nodes a change adds on top of `base_snapshot`.
28061341×
pub fn added_node_paths(
28071341×
    change: &Change,
28081341×
    base_snapshot: &Snapshot,
28091341×
) -> HashMap<String, (NodeId, NodeKind)> {
28101341×
    let by_node = base_snapshot.tree.by_node();
28111341×
    let mut new_names: HashMap<NodeId, (NodeId, String, NodeKind)> = HashMap::new();
28121341×
    for op in &change.tree_ops {
2813
        if let TreeOp::AddNode {
281480×
            node,
281580×
            parent,
281680×
            name,
281780×
            kind,
2818
            ..
2819104×
        } = op
282080×
        {
282180×
            new_names.insert(*node, (*parent, name.clone(), *kind));
282280×
        }
2823
    }
28241341×
    let mut out = HashMap::new();
28251341×
    for (node, (_, _, kind)) in &new_names {
282680×
        if let Some(path) = path_of_node(node, &by_node, &new_names) {
282780×
            out.insert(path, (*node, *kind));
282880×
        }
2829
    }
28301341×
    out
28311341×
}
2832
2833190×
fn path_of_node(
2834190×
    n: &NodeId,
2835190×
    by_node: &HashMap<NodeId, &crate::tree::TreeEntry>,
2836190×
    new_names: &HashMap<NodeId, (NodeId, String, NodeKind)>,
2837190×
) -> Option<String> {
2838190×
    if let Some(e) = by_node.get(n) {
283958×
        return Some(e.path.clone());
2840132×
    }
2841132×
    let mut parts = Vec::new();
2842132×
    let mut cur = *n;
2843
    loop {
2844263×
        if cur.is_root() {
2845118×
            break;
2846145×
        }
2847145×
        if let Some(e) = by_node.get(&cur) {
28480×
            if !e.path.is_empty() {
28490×
                parts.push(e.path.clone());
28500×
            }
28510×
            break;
2852145×
        }
2853145×
        let (parent, name, _) = new_names.get(&cur)?;
2854131×
        parts.push(name.clone());
2855131×
        cur = *parent;
2856
    }
2857118×
    parts.reverse();
2858118×
    Some(parts.join("/"))
2859190×
}
2860
2861
/// Render a change's operations with line content, using `base` for deleted lines.
286229×
pub fn render_change(change: &Change, base: &State, base_snapshot: &Snapshot) -> String {
286329×
    let by_node = base_snapshot.tree.by_node();
286429×
    let mut new_names: HashMap<NodeId, (NodeId, String, NodeKind)> = HashMap::new();
286529×
    for op in &change.tree_ops {
2866
        if let TreeOp::AddNode {
286715×
            node,
286815×
            parent,
286915×
            name,
287015×
            kind,
2871
            ..
287222×
        } = op
287315×
        {
287415×
            new_names.insert(*node, (*parent, name.clone(), *kind));
287515×
        }
2876
    }
287766×
    let path_of = |n: &NodeId| -> String {
287866×
        path_of_node(n, &by_node, &new_names).unwrap_or_else(|| format!("<node {}>", n.short(8)))
287966×
    };
2880
288129×
    let mut out = String::new();
288229×
    for op in &change.tree_ops {
288322×
        match op {
2884
            TreeOp::AddNode {
288515×
                node, kind, mode, ..
2886
            } => {
288715×
                out.push_str(&format!(
2888
                    "A {} ({:?}{}{})\n",
288915×
                    path_of(node),
2890
                    kind,
289115×
                    if mode.exec { ", exec" } else { "" },
289215×
                    if mode.opaque { ", opaque" } else { "" }
2893
                ));
2894
            }
28955×
            TreeOp::RemoveNode { node, .. } => out.push_str(&format!("D {}\n", path_of(node))),
2896
            TreeOp::Move {
28972×
                node, parent, name, ..
2898
            } => {
28992×
                let to = if parent.is_root() {
29000×
                    name.clone()
2901
                } else {
29022×
                    format!("{}/{name}", path_of(parent))
2903
                };
29042×
                out.push_str(&format!("R {} -> {to}\n", path_of(node)))
2905
            }
29060×
            TreeOp::SetMode { node, mode, .. } => {
29070×
                out.push_str(&format!(
29080×
                    "M {} mode: exec={} opaque={}\n",
29090×
                    path_of(node),
29100×
                    mode.exec,
29110×
                    mode.opaque
29120×
                ));
29130×
            }
2914
        }
2915
    }
2916
    // Every other file the change edits is modified: the summary names
2917
    // every path it touches, not only those with a tree operation.
291829×
    let with_op: HashSet<NodeId> = change.tree_ops.iter().map(|o| o.node()).collect();
291929×
    let mut listed: HashSet<NodeId> = HashSet::new();
292032×
    for e in &change.edits {
292132×
        let n = e.node();
292232×
        if !with_op.contains(&n) && listed.insert(n) {
292318×
            out.push_str(&format!("M {}\n", path_of(&n)));
292418×
        }
2925
    }
292629×
    let mut last_node: Option<NodeId> = None;
292732×
    for e in &change.edits {
292832×
        let n = e.node();
292932×
        if last_node != Some(n) {
293024×
            out.push_str(&format!("--- {}\n", path_of(&n)));
293124×
            last_node = Some(n);
293224×
        }
293332×
        match e {
293424×
            Edit::Insert { lines, .. } => {
293529×
                for l in lines.iter() {
293629×
                    out.push('+');
293729×
                    out.push_str(&String::from_utf8_lossy(l));
293829×
                    if !l.ends_with(b"\n") {
29390×
                        out.push('\n');
294029×
                    }
2941
                }
2942
            }
29437×
            Edit::Delete { atoms, .. } => {
29447×
                for r in atoms {
29457×
                    for i in r.from..r.to {
29467×
                        let content = base
29477×
                            .file(&n)
29487×
                            .and_then(|g| g.content(&(r.change, i)))
29497×
                            .unwrap_or(b"<unknown>\n");
29507×
                        out.push('-');
29517×
                        out.push_str(&String::from_utf8_lossy(content));
29527×
                        if !content.ends_with(b"\n") {
29530×
                            out.push('\n');
29547×
                        }
2955
                    }
2956
                }
2957
            }
29581×
            Edit::Replace { old, new, .. } => {
29591×
                out.push_str(&format!(
2960
                    "  opaque content {} -> {}\n",
29611×
                    old.map(|o| o.short(12)).unwrap_or_else(|| "none".into()),
29621×
                    new.map(|o| o.short(12)).unwrap_or_else(|| "none".into())
2963
                ));
2964
            }
2965
        }
2966
    }
296729×
    out
296829×
}
2969
2970
/// Pair removed files with added files of the same kind whose contents are
2971
/// at least `RENAME_THRESHOLD` percent alike, best matches first. Beyond
2972
/// `RENAME_LIMIT` candidate pairs only identical contents are paired.
2973
const RENAME_THRESHOLD: u32 = 50;
2974
const RENAME_LIMIT: usize = 10_000;
2975
2976
/// How a change is built beyond its entries: for a Git import, the seed
2977
/// its new nodes' identifiers derive from; and, when it is built from part
2978
/// of the tree, whether the new tree has anything under a directory.
2979
#[derive(Default)]
2980
struct Scope<'a> {
2981
    seed: Option<[u8; 32]>,
2982
    dir_needed: Option<&'a dyn Fn(&str) -> bool>,
2983
}
2984
29852048×
fn detect_renames(
29862048×
    base_snapshot: &Snapshot,
29872048×
    fs_entries: &BTreeMap<String, FsEntry>,
29882048×
    in_scope: impl Fn(&str) -> bool,
29892048×
) -> Vec<(String, String)> {
29902048×
    let removed: Vec<(&String, &crate::state::FileState)> = base_snapshot
29912048×
        .files
29922048×
        .iter()
299313385×
        .filter(|(p, f)| {
299413385×
            f.kind != NodeKind::Dir
299512949×
                && !fs_entries.contains_key(*p)
2996146×
                && in_scope(p)
2997136×
                && !f.is_conflicted()
299813385×
        })
29992048×
        .collect();
30002048×
    let added: Vec<(&String, &FsEntry)> = fs_entries
30012048×
        .iter()
300218872×
        .filter(|(p, e)| e.kind != NodeKind::Dir && !base_snapshot.files.contains_key(*p))
30032048×
        .collect();
30042048×
    if removed.is_empty() || added.is_empty() {
30051989×
        return vec![];
300659×
    }
300759×
    let exact_only = removed.len() * added.len() > RENAME_LIMIT;
300873×
    let old_content = |f: &crate::state::FileState| -> Option<Vec<u8>> {
300973×
        match &f.content {
301069×
            FileContent::Text { bytes, .. } => Some(bytes.clone()),
30114×
            _ => None,
3012
        }
301373×
    };
301459×
    let mut scored: Vec<(u32, usize, usize)> = Vec::new();
301573×
    for (ri, (_, f)) in removed.iter().enumerate() {
301673×
        let old = old_content(f);
301773×
        let old_blob = match &f.content {
30184×
            FileContent::Opaque { blobs } if blobs.len() == 1 => Some(blobs[0]),
301969×
            _ => None,
3020
        };
302192×
        for (ai, (_, e)) in added.iter().enumerate() {
302292×
            if e.kind != f.kind {
30230×
                continue;
302492×
            }
302592×
            let score = match (&old, old_blob) {
302682×
                (Some(o), _) => {
302782×
                    if exact_only {
30280×
                        if *o == *e.content {
30290×
                            100
3030
                        } else {
30310×
                            0
3032
                        }
3033
                    } else {
303482×
                        similarity(o, &e.content)
3035
                    }
3036
                }
303710×
                (None, Some(b)) if e.blob.unwrap_or_else(|| Repo::blob_ref(&e.content)) == b => 100,
30387×
                _ => 0,
3039
            };
304092×
            if score >= RENAME_THRESHOLD {
304139×
                scored.push((score, ri, ai));
304253×
            }
3043
        }
3044
    }
304559×
    scored.sort_by(|a, b| {
30469×
        b.0.cmp(&a.0)
30479×
            .then(removed[a.1].0.cmp(removed[b.1].0))
30489×
            .then(added[a.2].0.cmp(added[b.2].0))
30499×
    });
305059×
    let mut used_r = vec![false; removed.len()];
305159×
    let mut used_a = vec![false; added.len()];
305259×
    let mut out = Vec::new();
305359×
    for (_, ri, ai) in scored {
305439×
        if used_r[ri] || used_a[ai] {
30556×
            continue;
305633×
        }
305733×
        used_r[ri] = true;
305833×
        used_a[ai] = true;
305933×
        out.push((removed[ri].0.clone(), added[ai].0.clone()));
3060
    }
306159×
    out
30622048×
}
3063
3064
/// Percentage of the larger file's bytes found in lines the two share
3065
/// (multiset intersection of lines), like Git's similarity index.
306686×
pub fn similarity(a: &[u8], b: &[u8]) -> u32 {
306786×
    if a == b {
306822×
        return 100;
306964×
    }
307064×
    if a.is_empty() || b.is_empty() {
30712×
        return 0;
307262×
    }
307362×
    let mut counts: HashMap<&[u8], usize> = HashMap::new();
3074120×
    for l in split_lines(a) {
3075120×
        *counts.entry(l).or_default() += 1;
3076120×
    }
307762×
    let mut shared = 0usize;
3078115×
    for l in split_lines(b) {
3079115×
        if let Some(n) = counts.get_mut(l) {
308044×
            if *n > 0 {
308144×
                *n -= 1;
308244×
                shared += l.len();
308344×
            }
308471×
        }
3085
    }
308662×
    (shared * 100 / a.len().max(b.len())) as u32
308786×
}
3088
3089
#[cfg(test)]
3090
mod join_tests {
3091
    use super::*;
3092
3093
    #[test]
30941×
    fn missing_from_finds_what_the_other_lacks() {
30951×
        let a: BTreeMap<String, u8> = [("a", 1), ("b", 2), ("c/d", 3), ("e", 4)]
30961×
            .into_iter()
30974×
            .map(|(k, v)| (k.to_string(), v))
30981×
            .collect();
30991×
        let b: BTreeMap<String, ()> = [("0", ()), ("b", ()), ("c", ()), ("e", ())]
31001×
            .into_iter()
31014×
            .map(|(k, v)| (k.to_string(), v))
31021×
            .collect();
31031×
        let got: Vec<&str> = missing_from(&a, &b)
31041×
            .iter()
31052×
            .map(|(k, _)| k.as_str())
31061×
            .collect();
31071×
        assert_eq!(got, vec!["a", "c/d"]);
31081×
    }
3109
3110
    #[test]
31111×
    fn join_pairs_every_key_in_order() {
31121×
        let a: BTreeMap<String, u8> = [("a", 1), ("b/c", 2), ("d", 3)]
31131×
            .into_iter()
31143×
            .map(|(k, v)| (k.to_string(), v))
31151×
            .collect();
31161×
        let b: BTreeMap<String, char> = [("b", 'x'), ("b/c", 'y'), ("e", 'z')]
31171×
            .into_iter()
31183×
            .map(|(k, v)| (k.to_string(), v))
31191×
            .collect();
31201×
        let got: Vec<(String, Option<u8>, Option<char>)> = join(&a, &b)
31215×
            .map(|(k, x, y)| (k.clone(), x.copied(), y.copied()))
31221×
            .collect();
31231×
        let want = vec![
31241×
            ("a".to_string(), Some(1), None),
31251×
            ("b".to_string(), None, Some('x')),
31261×
            ("b/c".to_string(), Some(2), Some('y')),
31271×
            ("d".to_string(), Some(3), None),
31281×
            ("e".to_string(), None, Some('z')),
3129
        ];
31301×
        assert_eq!(got, want);
31311×
    }
3132
}