OXYGENHUB

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

2354 of 2584 lines run, 311 of 421 functions · run #359 on main · run missed

1
//! Working-copy snapshots, commits, and the change builder (spec §12.3).
2
3
use super::*;
4
use crate::objects::AtomRef;
5
6
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
7
pub enum ChangeStatus {
8
    Added,
9
    Modified,
10
    Removed,
11
    /// Moved from another path (detected by similarity, tracked as a placement change).
12
    Renamed,
13
    ModeChanged,
14
    /// The file is conflicted in the base state and still contains conflict markers.
15
    ConflictEdited,
16
    /// The file was conflicted in the base state and the working copy resolves it.
17
    Resolved,
18
}
19
20
/// Lines that mark a conflict region in a materialized file (spec §9.5).
211×
pub fn has_conflict_markers(content: &[u8]) -> bool {
222×
    split_lines(content).iter().any(|l| {
232×
        l.starts_with(b"<<<<<<< oxy conflict")
241×
            || l.starts_with(b"======= oxy conflict")
251×
            || l.starts_with(b">>>>>>> oxy conflict")
262×
    })
271×
}
28
29
/// Whether `content` still holds a conflict marker oxy wrote for this file
30
/// (oxygen#126): a marker-like line of the materialized conflicted file
31
/// that is not one of its unconflicted lines (`plain`). Text that merely
32
/// looks like a marker, as oxy's own documentation or a test fixture has,
33
/// is in the unconflicted lines, so it is not taken for one.
3436×
pub fn has_own_conflict_markers(content: &[u8], materialized: &[u8], plain: &[&[u8]]) -> bool {
35470×
    let line = |l: &[u8]| -> Vec<u8> {
36470×
        let l = l.strip_suffix(b"\n").unwrap_or(l);
37470×
        l.strip_suffix(b"\r").unwrap_or(l).to_vec()
38470×
    };
39263×
    let marker = |l: &[u8]| {
40263×
        l.starts_with(b"<<<<<<< oxy conflict")
41223×
            || l.starts_with(b"======= oxy conflict")
42183×
            || l.starts_with(b">>>>>>> oxy conflict")
43263×
    };
4481×
    let unconflicted: HashSet<Vec<u8>> = plain.iter().map(|l| line(l)).collect();
4536×
    let own: HashSet<Vec<u8>> = split_lines(materialized)
4636×
        .into_iter()
4736×
        .map(line)
48263×
        .filter(|l| marker(l) && !unconflicted.contains(l))
4936×
        .collect();
5036×
    !own.is_empty()
5136×
        && split_lines(content)
5236×
            .into_iter()
53126×
            .any(|l| own.contains(&line(l)))
5436×
}
55
56
#[derive(Clone, Debug, PartialEq, Eq)]
57
pub struct PathStatus {
58
    pub path: String,
59
    pub status: ChangeStatus,
60
}
61
62
/// Operations of a change built from the working directory against a base.
63
pub(crate) struct BuiltChange {
64
    pub tree_ops: Vec<TreeOp>,
65
    pub edits: Vec<Edit>,
66
    pub contributors: Vec<ChangeHash>,
67
    pub resolves: bool,
68
    pub statuses: Vec<PathStatus>,
69
    /// The stored blob of every opaque path, for the manifest's stat cache.
70
    pub blobs: HashMap<String, ObjectRef>,
71
}
72
73
/// Result of snapshotting the working copy.
74
pub struct SnapshotResult {
75
    /// The working-copy change's hash; for a commit's own snapshot, which
76
    /// does not encode it, the hash it had before.
77
    pub wc_hash: ChangeHash,
78
    pub wc: Change,
79
    /// The base state (closure of the working-copy change's dependencies).
80
    pub base: State,
81
    pub base_snapshot: Snapshot,
82
    pub statuses: Vec<PathStatus>,
83
    /// Whether the snapshot rewrote the working-copy change.
84
    pub changed: bool,
85
    /// Whether the working copy resolves conflicts of its base (spec §9.6).
86
    pub resolves: bool,
87
    /// Changes that contributed to the conflicts being resolved.
88
    pub contributors: Vec<ChangeHash>,
89
    /// The `.oxyattributes` in force on disk, from the files the walk read.
90
    pub(crate) attributes: crate::attributes::Attributes,
91
    /// Folders holding a repository of their own (`.git` or `.oxy`) that
92
    /// are not subrepos, so nothing in them is tracked (oxygen#43).
93
    pub untracked_nested: Vec<String>,
94
    /// A commit's snapshot leaves the manifest to the commit, which writes
95
    /// it once with the new base's graph keys.
96
    pub(crate) manifest: Option<PendingManifest>,
97
}
98
99
/// The manifest a commit's snapshot would have written, as of the moment
100
/// it would have written it (that moment is the racy-window stamp).
101
pub(crate) struct PendingManifest {
102
    entries: BTreeMap<String, FsEntry>,
103
    blobs: HashMap<String, ObjectRef>,
104
    dirs: Option<super::WalkedDirs>,
105
    written: u128,
106
}
107
10823391×
pub fn is_binary(content: &[u8]) -> bool {
10923391×
    content[..content.len().min(BINARY_SNIFF)].contains(&0)
11023391×
}
111
112
impl Repo {
113
    /// Diff the files on disk against `base` and build the operations of a
114
    /// change from `base` to the working directory. `reuse` maps paths to the
115
    /// NodeIds an earlier version of the same change assigned to new paths.
1163×
    pub(crate) fn build_against(
1173×
        &self,
1183×
        base: &State,
1193×
        base_snapshot: &Snapshot,
1203×
        reuse: HashMap<String, (NodeId, NodeKind)>,
1213×
    ) -> Result<BuiltChange> {
1223×
        let mut fs_entries =
1233×
            self.walk_working_copy_with(None, &Self::tracked_kinds(base_snapshot), None)?;
1243×
        self.platform_normalize(&mut fs_entries, base_snapshot);
1253×
        self.build_from_entries(base, base_snapshot, reuse, &fs_entries)
1263×
    }
127
128
    /// Read the working copy as the platform left it (spec §7.7): without
129
    /// executable bits a file keeps the bit it has in the base, and without
130
    /// symbolic links a plain file where the base has a symlink is that
131
    /// symlink, written out as its target, not a new file.
1321422×
    fn platform_normalize(&self, entries: &mut BTreeMap<String, FsEntry>, base: &Snapshot) {
1331422×
        let p = self.platform;
1341422×
        if p.exec_bits && p.symlinks {
1351420×
            return;
1362×
        }
1374×
        for (path, e) in entries.iter_mut() {
1384×
            let Some(f) = base.files.get(path) else {
1390×
                continue;
140
            };
1414×
            if !p.symlinks && f.kind == NodeKind::Symlink && e.kind == NodeKind::File {
1422×
                e.kind = NodeKind::Symlink;
1432×
                e.exec = false;
1442×
            }
1454×
            if !p.exec_bits && f.kind == NodeKind::File && e.kind == NodeKind::File {
1462×
                e.exec = f.mode.exec;
1472×
            }
148
        }
1491422×
    }
150
151
    /// Like `build_against`, for files given in memory (imports).
1521146×
    pub(crate) fn build_from_entries(
1531146×
        &self,
1541146×
        base: &State,
1551146×
        base_snapshot: &Snapshot,
1561146×
        reuse: HashMap<String, (NodeId, NodeKind)>,
1571146×
        fs_entries: &BTreeMap<String, FsEntry>,
1581146×
    ) -> Result<BuiltChange> {
1591146×
        self.build_from_entries_resolving(base, base_snapshot, reuse, fs_entries, &HashSet::new())
1601146×
    }
161
162
    /// Like `build_from_entries`, settling the replace conflicts of the
163
    /// opaque files in `resolve` to their content (spec §9.3, §9.6): a
164
    /// caller that knows the user chose it, such as the hub's resolver. A
165
    /// snapshot never settles one on its own, since a checkout writes one
166
    /// candidate at the path.
1671161×
    pub(crate) fn build_from_entries_resolving(
1681161×
        &self,
1691161×
        base: &State,
1701161×
        base_snapshot: &Snapshot,
1711161×
        reuse: HashMap<String, (NodeId, NodeKind)>,
1721161×
        fs_entries: &BTreeMap<String, FsEntry>,
1731161×
        resolve: &HashSet<String>,
1741161×
    ) -> Result<BuiltChange> {
1751161×
        self.build_from_entries_with(
1761161×
            base,
1771161×
            base_snapshot,
1781161×
            reuse,
1791161×
            fs_entries,
1801161×
            resolve,
1811161×
            Scope::default(),
182
        )
1831161×
    }
184
185
    /// `build_from_entries` whose new nodes take identifiers derived from
186
    /// `seed` and their paths instead of random ones, so the same input
187
    /// always builds the same change (a Git import, spec §23).
188
    ///
189
    /// With `dir_needed`, the snapshot and entries hold only the paths the
190
    /// import touches (and the directories a removal may leave empty); a
191
    /// directory stays while `dir_needed` says the new tree has something
192
    /// under it.
19388×
    pub(crate) fn build_from_entries_seeded(
19488×
        &self,
19588×
        base: &State,
19688×
        base_snapshot: &Snapshot,
19788×
        fs_entries: &BTreeMap<String, FsEntry>,
19888×
        seed: [u8; 32],
19988×
        dir_needed: Option<&dyn Fn(&str) -> bool>,
20088×
    ) -> Result<BuiltChange> {
20188×
        self.build_from_entries_with(
20288×
            base,
20388×
            base_snapshot,
20488×
            HashMap::new(),
20588×
            fs_entries,
20688×
            &HashSet::new(),
20788×
            Scope {
20888×
                seed: Some(seed),
20988×
                dir_needed,
21088×
            },
211
        )
21288×
    }
213
214
    /// `build_from_entries` for a snapshot most of whose files are known
215
    /// unchanged (oxygen#41): only the paths that may differ are built
216
    /// (files read rather than known unchanged, base files gone from disk,
217
    /// and the directories those may leave empty), against a snapshot of
218
    /// just those, so a large tree with a few edits costs what they touch.
219939×
    fn build_changed_only(
220939×
        &self,
221939×
        base: &State,
222939×
        base_snapshot: &Snapshot,
223939×
        reuse: HashMap<String, (NodeId, NodeKind)>,
224939×
        fs_entries: &BTreeMap<String, FsEntry>,
225939×
    ) -> Result<BuiltChange> {
226939×
        let pick = crate::timing::phase("snapshot:   of which picking the changed");
227
        // A file known unchanged may still have changed mode: that alters
228
        // neither its size nor its time.
229939×
        let changed: BTreeMap<String, FsEntry> = join(fs_entries, &base_snapshot.files)
23011138×
            .filter_map(|(p, e, f)| {
23111138×
                let e = e?;
23211005×
                (!e.unchanged || f.is_none_or(|f| f.kind != e.kind || f.mode.exec != e.exec))
23311005×
                    .then(|| (p.clone(), e.clone()))
23411138×
            })
235939×
            .collect();
236939×
        let mut files: BTreeMap<String, crate::state::FileState> = BTreeMap::new();
2376775×
        for p in changed.keys() {
2386775×
            if let Some(f) = base_snapshot.files.get(p) {
2393728×
                files.insert(p.clone(), f.clone());
2403728×
            }
241
        }
242
        // Paths the base has and the disk does not.
243939×
        let gone = join(&base_snapshot.files, fs_entries)
24411138×
            .filter_map(|(p, f, e)| (e.is_none()).then_some((p, f?)));
245939×
        for (p, f) in gone {
246133×
            if f.kind == NodeKind::Dir {
24796×
                continue;
24837×
            }
24937×
            files.insert(p.clone(), f.clone());
25037×
            let mut end = p.len();
25142×
            while let Some(i) = p[..end].rfind('/') {
2525×
                let dir = &p[..i];
2535×
                if files.contains_key(dir) {
2540×
                    break;
2555×
                }
2565×
                if let Some(d) = base_snapshot.files.get(dir) {
2575×
                    files.insert(dir.to_string(), d.clone());
2585×
                }
2595×
                end = i;
260
            }
261
        }
262939×
        let part = Snapshot {
263939×
            tree: base_snapshot.tree.clone(),
264939×
            files,
265939×
            unrendered: BTreeSet::new(),
266939×
        };
267939×
        drop(pick);
268939×
        let _build = crate::timing::phase("snapshot:   of which building the change");
269
        // Whether anything on disk is under `dir`.
270939×
        let dir_needed = |dir: &str| {
2715×
            let prefix = format!("{dir}/");
2725×
            fs_entries
2735×
                .range(prefix.clone()..)
2745×
                .next()
2755×
                .is_some_and(|(k, _)| k.starts_with(&prefix))
2765×
        };
277939×
        self.build_from_entries_with(
278939×
            base,
279939×
            &part,
280939×
            reuse,
281939×
            &changed,
282939×
            &HashSet::new(),
283939×
            Scope {
284939×
                seed: None,
285939×
                dir_needed: Some(&dir_needed),
286939×
            },
287
        )
288939×
    }
289
2902188×
    fn build_from_entries_with(
2912188×
        &self,
2922188×
        base: &State,
2932188×
        base_snapshot: &Snapshot,
2942188×
        reuse: HashMap<String, (NodeId, NodeKind)>,
2952188×
        fs_entries: &BTreeMap<String, FsEntry>,
2962188×
        resolve: &HashSet<String>,
2972188×
        scope: Scope,
2982188×
    ) -> Result<BuiltChange> {
2992188×
        let Scope { seed, dir_needed } = scope;
3002188×
        let mut laps = crate::timing::Laps::start();
301
        // Attributes come from the files being committed, so a new
302
        // `.oxyattributes` applies to the same change that adds it.
3032188×
        let attrs = crate::attributes::Attributes::from_files(
3042188×
            fs_entries
3052188×
                .iter()
30619081×
                .filter(|(p, _)| p.as_str() == ".oxyattributes" || p.ends_with("/.oxyattributes"))
3072188×
                .map(|(p, e)| (p.as_str(), e.content.as_slice())),
308
        );
3092188×
        let mut b = ChangeBuilder::new(base, base_snapshot, reuse).with_attributes(attrs);
3102188×
        b.resolve = resolve.clone();
3112188×
        b.node_seed = seed;
3122188×
        laps.lap("build: builder");
313
        // Rename detection (spec §7.1, §23): a removed file and an added file
314
        // of the same kind whose contents are at least half alike become one
315
        // move of the same node, so identity survives across the rename.
3162188×
        let renames = detect_renames(base_snapshot, fs_entries, |p| self.in_scope(p));
3172188×
        let renamed_from: HashMap<&str, &str> = renames
3182188×
            .iter()
3192188×
            .map(|(old, new)| (new.as_str(), old.as_str()))
3202188×
            .collect();
3212188×
        let renamed_to: HashMap<&str, &str> = renames
3222188×
            .iter()
3232188×
            .map(|(old, new)| (old.as_str(), new.as_str()))
3242188×
            .collect();
3252188×
        laps.lap("build: renames");
3262188×
        b.diff_in_parallel(fs_entries);
3272188×
        laps.lap("build: diffs");
32819081×
        for (path, fs_entry) in fs_entries {
32919081×
            match base_snapshot.files.get(path) {
3306162×
                None => match renamed_from.get(path.as_str()) {
33135×
                    Some(old) => {
33235×
                        b.move_path(self, old, path, fs_entry, &base_snapshot.files[*old])?
333
                    }
3346127×
                    None => b.add_path(self, path, fs_entry)?,
335
                },
33612919×
                Some(expected) => b.update_path(self, path, fs_entry, expected)?,
337
            }
338
        }
3392188×
        laps.lap("build: paths");
340
        // A directory stays while anything under it exists or is out of
341
        // scope: the directories above each such path, gathered once.
3422188×
        let mut needed_dirs: HashSet<&str> = HashSet::new();
34319094×
        fn parents_of<'a>(p: &'a str, set: &mut HashSet<&'a str>) {
34419094×
            let mut end = p.len();
34519769×
            while let Some(i) = p[..end].rfind('/') {
34615457×
                if !set.insert(&p[..i]) {
34714782×
                    break;
348675×
                }
349675×
                end = i;
350
            }
35119094×
        }
35219081×
        for p in fs_entries.keys() {
35319081×
            parents_of(p, &mut needed_dirs);
35419081×
        }
35513503×
        for p in base_snapshot.files.keys() {
35613503×
            if !self.in_scope(p) {
35713×
                parents_of(p, &mut needed_dirs);
35813490×
            }
359
        }
36013503×
        for (path, expected) in &base_snapshot.files {
36113503×
            if fs_entries.contains_key(path)
362584×
                || !self.in_scope(path)
363571×
                || renamed_to.contains_key(path.as_str())
364
            {
36512967×
                continue;
366536×
            }
367536×
            let still_needed = expected.kind == NodeKind::Dir
368431×
                && match dir_needed {
36921×
                    Some(f) => f(path),
370410×
                    None => needed_dirs.contains(path.as_str()),
371
                };
372536×
            if !still_needed {
373127×
                b.remove_path(path, expected);
374409×
            }
375
        }
3762188×
        laps.lap("build: removals");
3772188×
        if seed.is_some() {
37888×
            b.retire_stray_placements();
3792100×
        }
3802188×
        b.retire_unified();
3812188×
        laps.lap("build: stray placements");
3822188×
        let mut statuses = b.statuses;
3835685×
        statuses.sort_by(|a, b| a.path.cmp(&b.path));
3842188×
        Ok(BuiltChange {
3852188×
            tree_ops: b.tree_ops,
3862188×
            edits: b.edits,
3872188×
            contributors: b.contributors.into_iter().collect(),
3882188×
            resolves: b.resolves,
3892188×
            statuses,
3902188×
            blobs: b.blobs,
3912188×
        })
3922188×
    }
393
394
    /// Store a change and, when `core.sign = change` and we are its author,
395
    /// sign it. A rewritten change by another author is stored unsigned: only
396
    /// its author (or a delegate) can vouch for it.
397760×
    pub(crate) fn store_signed(&self, change: &Change) -> Result<ChangeHash> {
398760×
        let ours = change.author == self.author();
399760×
        if self.config.sign_changes && ours && self.secret_key()?.is_none() {
4001×
            return fail("core.sign is \"change\" but no secret key is available for author.key");
401759×
        }
402759×
        let storing = crate::timing::phase("store: the change");
403759×
        let hash = self.store.put_change(change)?;
404759×
        drop(storing);
405759×
        if self.config.sign_changes && ours {
40643×
            let _t = crate::timing::phase("store: sign it");
40743×
            self.sign_change(&hash)?;
408716×
        }
409759×
        Ok(hash)
410760×
    }
411
412
    /// Snapshot the working copy into the working-copy change (spec §12.3).
413
    /// The result carries the full base state and its whole rendering.
414480×
    pub fn snapshot(&self, command: &str) -> Result<SnapshotResult> {
415480×
        self.snapshot_as(command, false, false)
416480×
    }
417
418
    /// Snapshot the working copy as [`Repo::snapshot`] does, for commands
419
    /// that need its statuses, conflicts and base history, and the graphs
420
    /// of the files it changes: status, log, show, commit, diff, hunks and
421
    /// discard. Text files known unchanged since the last manifest are
422
    /// neither read nor rendered: the result's `base` is a history-only
423
    /// state without their graphs, and its `base_snapshot` lists them in
424
    /// `unrendered` with empty bytes. They are never conflicted, and no
425
    /// change the working copy makes touches them.
426444×
    pub fn snapshot_status(&self, command: &str) -> Result<SnapshotResult> {
427444×
        self.snapshot_as(command, true, false)
428444×
    }
429
430
    /// `snapshot_as`; `for_commit` writes the manifest even where a status
431
    /// would not bother (an edited file is read next time whatever it
432
    /// says), since after the commit that file is unchanged, and records no
433
    /// operation: the commit's own, recorded straight after, replaces the
434
    /// working copy, so the snapshot's would cost a durable write for
435
    /// nothing. Should the commit fail, the files are still on disk and the
436
    /// next snapshot finds them.
4371422×
    fn snapshot_as(
4381422×
        &self,
4391422×
        command: &str,
4401422×
        partial: bool,
4411422×
        for_commit: bool,
4421422×
    ) -> Result<SnapshotResult> {
4431422×
        let _lock = self.lock_snapshot()?;
4441422×
        let batch = self.store.begin_batch()?;
4451422×
        let result = self.snapshot_locked(command, partial, for_commit);
4461422×
        batch.finish()?;
4471422×
        result
4481422×
    }
449
4501422×
    fn snapshot_locked(
4511422×
        &self,
4521422×
        command: &str,
4531422×
        partial: bool,
4541422×
        for_commit: bool,
4551422×
    ) -> Result<SnapshotResult> {
4561422×
        let _all = crate::timing::phase("snapshot");
4571422×
        let (op_ref, op) = self.head_op()?;
4581422×
        let (old_hash, old_wc) = self.working_copy()?;
459
        // The base's history first: its graph keys say which files the
460
        // manifest already knows equal to it.
4611420×
        let mut base = {
4621420×
            let _t = crate::timing::phase("snapshot: load base history");
4631420×
            self.load_state_indexed(&old_wc.deps)?
464
        };
4651420×
        let view = {
4661420×
            let _t = crate::timing::phase("snapshot: tree view");
4671420×
            self.tree_view(&mut base)?
468
        };
4691420×
        let manifest = {
4701420×
            let _t = crate::timing::phase("snapshot: read manifest");
4711420×
            self.read_manifest()?.map(|(_, _, m)| m)
472
        };
4731420×
        let tracked: BTreeMap<String, (NodeKind, Option<ObjectRef>)> = {
4741420×
            let _t = crate::timing::phase("snapshot: tracked paths");
475
            // In the view's path order, so the map is built without searching.
4761420×
            view.entries
4771420×
                .iter()
4789670×
                .filter(|(_, e)| e.kind != NodeKind::Dir)
4799265×
                .map(|(p, e)| {
4809265×
                    let blob = if e.kind != NodeKind::File || e.mode.opaque {
481156×
                        base.live_blobs(&e.node).first().copied()
482
                    } else {
4839109×
                        None
484
                    };
4859265×
                    (p.clone(), (e.kind, blob))
4869265×
                })
4871420×
                .collect()
488
        };
489
        // A text file's graph key, worked out when the walk asks for it.
49012331×
        let key_of = |p: &str| -> Option<[u8; 32]> {
49112331×
            let e = view.entries.get(p)?;
4929157×
            if e.kind != NodeKind::File || e.mode.opaque {
493124×
                return None;
4949033×
            }
4959033×
            base.graph_key(&e.node)
49612331×
        };
4971419×
        let mut fs_entries = {
4981420×
            let _t = crate::timing::phase("snapshot: read working copy");
4991420×
            self.walk_working_copy_with(manifest.as_deref(), &tracked, Some(&key_of))?
500
        };
501
        // The keys of the files read, before building graphs drops them: a
502
        // file found equal to its base rendering keeps its key.
5031419×
        let keys: HashMap<String, [u8; 32]> = fs_entries
5041419×
            .iter()
50512369×
            .filter(|(_, e)| !e.unchanged && e.kind == NodeKind::File)
5068089×
            .filter_map(|(p, _)| Some((p.clone(), key_of(p)?)))
5071419×
            .collect();
5081419×
        let base_snapshot = {
5091419×
            let _t = crate::timing::phase("snapshot: load and render base");
5101419×
            if partial {
511942×
                let sets = crate::timing::phase("snapshot:   of which choosing graphs");
512
                // Every file but those on disk known unchanged.
513942×
                let need: Vec<(&str, NodeId)> = join(&view.entries, &fs_entries)
51411153×
                    .filter_map(|(p, v, f)| {
51511153×
                        let v = v?;
5168105×
                        (v.kind == NodeKind::File && !f.is_some_and(|f| f.unchanged))
5178105×
                            .then_some((p.as_str(), v.node))
51811153×
                    })
519942×
                    .collect();
520942×
                let render: std::collections::HashSet<&str> =
521942×
                    need.iter().map(|(p, _)| *p).collect();
522942×
                let need: Vec<NodeId> = need.iter().map(|(_, n)| *n).collect();
523942×
                drop(sets);
524
                {
525942×
                    let _t = crate::timing::phase("snapshot:   of which building graphs");
526942×
                    self.load_graphs_of(&mut base, &need)?;
527
                }
528942×
                let _t = crate::timing::phase("snapshot:   of which rendering");
529942×
                base.materialize_only(&render)
530
            } else {
531477×
                self.load_all_graphs(&mut base)?;
532477×
                base.materialize()
533
            }
534
        };
535
536
        // Reuse the NodeIds the previous working-copy version assigned to new
537
        // paths, so an unchanged working copy hashes identically (spec §12.3).
5381419×
        let reuse = added_node_paths(&old_wc, &base_snapshot);
5391419×
        self.platform_normalize(&mut fs_entries, &base_snapshot);
5401419×
        let built = {
5411419×
            let _t = crate::timing::phase("snapshot: diff against base");
5421419×
            if partial && self.config.sparse_paths.is_empty() {
543
                #[cfg(test)]
544659×
                let full =
545659×
                    self.build_from_entries(&base, &base_snapshot, reuse.clone(), &fs_entries)?;
546939×
                let built = self.build_changed_only(&base, &base_snapshot, reuse, &fs_entries)?;
547
                #[cfg(test)]
548
                {
549
                    // New nodes take random identifiers: compare them by
550
                    // order of appearance.
5511318×
                    let norm = |b: &BuiltChange| {
5521318×
                        let text = format!("{:?} {:?} {:?}", b.tree_ops, b.edits, b.statuses);
5531318×
                        let mut seen: Vec<String> = Vec::new();
5541318×
                        let mut out = String::new();
5551318×
                        let mut rest = text.as_str();
55620360×
                        while let Some(i) = rest.find("NodeId(") {
55719042×
                            out.push_str(&rest[..i]);
55819042×
                            let end = i + rest[i..].find(')').unwrap() + 1;
55919042×
                            let id = rest[i..end].to_string();
5609046244×
                            let n = seen.iter().position(|x| *x == id).unwrap_or_else(|| {
5617258×
                                seen.push(id);
5627258×
                                seen.len() - 1
5637258×
                            });
56419042×
                            out.push_str(&format!("N{n}"));
56519042×
                            rest = &rest[end..];
566
                        }
5671318×
                        out.push_str(rest);
5681318×
                        out
5691318×
                    };
570659×
                    assert_eq!(
571659×
                        norm(&built),
572659×
                        norm(&full),
573
                        "a changed-only build is the full one"
574
                    );
575
                }
576939×
                built
577
            } else {
578480×
                self.build_from_entries(&base, &base_snapshot, reuse, &fs_entries)?
579
            }
580
        };
581
        // Text files found equal to an unconflicted base rendering keep its
582
        // graph key, so the next snapshot need not read or render them.
583
        {
5843837×
            let changed: HashSet<&str> = built.statuses.iter().map(|s| s.path.as_str()).collect();
58512369×
            for (p, e) in fs_entries.iter_mut() {
58612369×
                if e.unchanged || e.kind != NodeKind::File || changed.contains(p.as_str()) {
5878022×
                    continue;
5884347×
                }
5894347×
                e.graph_key = match base_snapshot.files.get(p).map(|f| &f.content) {
590
                    Some(FileContent::Text {
5914235×
                        bytes,
5924235×
                        materialized,
5934235×
                    }) if !materialized.is_conflicted() && *bytes == *e.content => {
5944229×
                        keys.get(p).copied()
595
                    }
596118×
                    _ => None,
597
                };
598
            }
599
        }
600
6011419×
        let mut wc = Change {
6021419×
            version: crate::objects::CHANGE_VERSION,
6031419×
            change_id: old_wc.change_id,
6041419×
            deps: vec![],
6051419×
            author: self.author(),
6061419×
            hlc: old_wc.hlc,
6071419×
            message: old_wc.message.clone(),
6081419×
            tree_ops: built.tree_ops,
6091419×
            edits: built.edits,
6101419×
            kind: ChangeKind::WorkingCopy,
6111419×
        };
6121419×
        let base_heads = base.maximal(&old_wc.deps);
6131419×
        let mut deps: BTreeSet<ChangeHash> = base_heads.into_iter().collect();
6141419×
        deps.extend(referenced_changes(&wc, &base));
6151419×
        deps.extend(built.contributors.iter().copied());
6161419×
        wc.deps = deps.into_iter().collect();
6171419×
        wc.normalize();
6181419×
        let resolves = built.resolves;
6191419×
        let contributors = built.contributors;
6201419×
        let statuses = built.statuses;
621
        // Empty snapshot: hash the candidate before storing; only record an op on change.
6221419×
        let record = crate::timing::phase("snapshot: hash and record");
623
        // Encoded once, its texts stored a batch at a time as they are
624
        // made (a stored blob is not stored again); the change itself only
625
        // when it changed.
626
        // For a commit the change is neither encoded, stored nor recorded:
627
        // the commit stores its own, built from this one's operations, and
628
        // its texts with it. The hash it would have is not needed.
6291419×
        let (new_hash, changed, encoded) = if for_commit {
630498×
            (old_hash, true, Vec::new())
631
        } else {
632921×
            let encoded = wc.encode_streaming(|batch| self.store.put_texts(&batch))?;
633921×
            let new_hash = crate::hash::hash_object(crate::hash::ObjectType::Change, &encoded);
634921×
            (new_hash, new_hash != old_hash, encoded)
635
        };
6361419×
        if changed && !for_commit {
637319×
            self.store.put(crate::hash::ObjectType::Change, &encoded)?;
638319×
            let mut view = op.view.clone();
639319×
            view.workspaces.insert(self.workspace, new_hash);
640319×
            self.record_op(&[op_ref], &format!("{command}{SNAPSHOT_SUFFIX}"), view)?;
6411100×
        }
6421419×
        drop(record);
643
        // The prompt compares against this without recording anything.
6441419×
        let _t = crate::timing::phase("snapshot: write manifest");
6451419×
        let conflicted = base_snapshot.is_conflicted();
6461419×
        let uncommitted = !wc.tree_ops.is_empty() || !wc.edits.is_empty();
647
        // Rewriting the manifest pays only when it would teach the next
648
        // snapshot something: other flags, a file found equal to the base
649
        // (it need not be read again), a new blob, a path added or gone.
650
        // An edited file is read next time whatever it says.
6511419×
        let worth = match self.read_manifest()? {
652498×
            _ if for_commit => true,
653343×
            None => true,
654578×
            Some((c, u, m)) => {
655578×
                c != conflicted
656578×
                    || u != uncommitted
657330×
                    || m.entries.len() != fs_entries.len()
658413×
                    || fs_entries.iter().any(|(p, e)| {
659413×
                        !e.unchanged && (e.graph_key.is_some() || !m.entries.contains_key(p))
660413×
                    })
66153×
                    || built
66253×
                        .blobs
66353×
                        .iter()
66453×
                        .any(|(p, b)| m.entries.get(p).and_then(|e| e.blob) != Some(*b))
665
                    // With uncommitted work, the status cache below holds
666
                    // only while the manifest describes the edited files as
667
                    // they are now.
66869×
                    || (uncommitted && statuses.iter().any(|st| {
66969×
                        let Some(e) = fs_entries.get(&st.path) else {
6704×
                            return m.entries.contains_key(&st.path);
671
                        };
67265×
                        let Some(me) = m.entries.get(&st.path) else {
6730×
                            return true;
674
                        };
67565×
                        let hash = e
67665×
                            .content_hash
67765×
                            .unwrap_or_else(|| *blake3::hash(&e.content).as_bytes());
67865×
                        let stat = e.stat.or_else(|| {
6790×
                            fs::symlink_metadata(self.root.join(&st.path))
6800×
                                .ok()
6810×
                                .map(|md| (md.len(), super::prompt::mtime_ns(&md)))
6820×
                        });
683
                        // The executable bit too: a mode change moves
684
                        // neither size nor time.
68565×
                        me.hash != hash || me.exec != e.exec || stat != Some((me.size, me.mtime_ns))
68669×
                    }))
687
            }
688
        };
6891419×
        let attributes = crate::attributes::Attributes::from_files(
6901419×
            fs_entries
6911419×
                .iter()
69212369×
                .filter(|(p, _)| is_attributes(p))
6931419×
                .map(|(p, e)| (p.as_str(), e.content.as_slice())),
694
        );
6951419×
        let mut manifest = None;
6961419×
        if for_commit {
697498×
            manifest = Some(PendingManifest {
698498×
                entries: fs_entries,
699498×
                blobs: built.blobs.clone(),
700498×
                dirs: self.walked_dirs.take(),
701498×
                written: super::prompt::now_ns(),
702498×
            });
703498×
        } else {
704921×
            if worth {
705871×
                self.write_manifest_entries(conflicted, uncommitted, &fs_entries, &built.blobs)?;
70650×
            }
707921×
            self.write_status_cache((uncommitted && !conflicted).then_some(&new_hash), &statuses);
708
        }
7091419×
        Ok(SnapshotResult {
7101419×
            wc_hash: new_hash,
7111419×
            wc,
7121419×
            base,
7131419×
            base_snapshot,
7141419×
            statuses,
7151419×
            changed,
7161419×
            resolves,
7171419×
            contributors,
7181419×
            attributes,
7191419×
            untracked_nested: self.untracked_nested.borrow().clone(),
7201419×
            manifest,
7211419×
        })
7221422×
    }
723
724
    /// `oxy status --json` (spec §9.5): the changed paths and every conflict
725
    /// of the working copy's base with its kind, path, and contributing
726
    /// ChangeIds.
7278×
    pub fn status_json(&self, snap: &SnapshotResult) -> Result<String> {
7288×
        let heads = self.bookmark_heads()?;
7298×
        let base_snapshot = &snap.base_snapshot;
7308×
        let by_node = base_snapshot.tree.by_node();
7318×
        let path_of = |n: &NodeId| by_node.get(n).map(|e| e.path.clone());
7328×
        let id_of = |h: &ChangeHash| {
7334×
            snap.base
7344×
                .get(h)
7354×
                .map(|m| m.change_id.to_hex())
7364×
                .unwrap_or_else(|| h.to_hex())
7374×
        };
7388×
        let paths = json_array(snap.statuses.iter().map(|s| {
7394×
            format!(
740
                "{{\"path\":{},\"status\":{}}}",
7414×
                json_str(&s.path),
7424×
                json_str(&format!("{:?}", s.status))
743
            )
7444×
        }));
7458×
        let mut conflicts: Vec<String> = Vec::new();
7469×
        for (p, f) in &base_snapshot.files {
7479×
            if !f.is_conflicted() {
7487×
                continue;
7492×
            }
7502×
            let (kind, changes) = match &f.content {
751
                FileContent::Text { .. } => {
7522×
                    ("text", snap.base.conflict_regions(&f.node).contributors)
753
                }
7540×
                FileContent::Opaque { blobs } => {
7550×
                    ("replace", snap.base.blob_contributors(&f.node, blobs))
756
                }
7570×
                FileContent::Dir => continue,
758
            };
7592×
            let resolved = match snap
7602×
                .statuses
7612×
                .iter()
7622×
                .find(|s| s.path == *p)
7632×
                .map(|s| s.status)
764
            {
7651×
                Some(ChangeStatus::Resolved) => "true",
7660×
                Some(ChangeStatus::ConflictEdited) => "\"markers\"",
7671×
                _ => "false",
768
            };
7692×
            conflicts.push(format!(
770
                "{{\"kind\":{},\"path\":{},\"node\":{},\"changes\":{},\"resolved\":{resolved}}}",
7712×
                json_str(kind),
7722×
                json_str(p),
7732×
                json_str(&f.node.to_hex()),
7744×
                json_array(changes.iter().map(|h| json_str(&id_of(h))))
775
            ));
776
        }
7778×
        for c in &base_snapshot.tree.conflicts {
7780×
            let (kind, nodes): (&str, Vec<NodeId>) = match c {
7790×
                crate::tree::TreeConflict::Name { nodes, .. } => ("name", nodes.clone()),
7800×
                crate::tree::TreeConflict::MultiPlacement { node, .. } => {
7810×
                    ("multi-placement", vec![*node])
782
                }
7830×
                crate::tree::TreeConflict::Orphan { node, .. } => ("orphan", vec![*node]),
7840×
                crate::tree::TreeConflict::Cycle { node } => ("cycle", vec![*node]),
7850×
                crate::tree::TreeConflict::Mode { node, .. } => ("mode", vec![*node]),
786
            };
7870×
            let detail = match c {
7880×
                crate::tree::TreeConflict::Name { name, parent, .. } => {
7890×
                    let dir = if *parent == NodeId::ROOT {
7900×
                        String::new()
791
                    } else {
7920×
                        path_of(parent).unwrap_or_default()
793
                    };
7940×
                    format!(
795
                        ",\"path\":{}",
7960×
                        json_str(&if dir.is_empty() {
7970×
                            name.clone()
798
                        } else {
7990×
                            format!("{dir}/{name}")
800
                        })
801
                    )
802
                }
8030×
                _ => nodes
8040×
                    .first()
8050×
                    .and_then(path_of)
8060×
                    .map(|p| format!(",\"path\":{}", json_str(&p)))
8070×
                    .unwrap_or_default(),
808
            };
8090×
            conflicts.push(format!(
810
                "{{\"kind\":{},\"nodes\":{}{detail}}}",
8110×
                json_str(kind),
8120×
                json_array(nodes.iter().map(|n| json_str(&n.to_hex())))
813
            ));
814
        }
8158×
        Ok(format!(
816
            "{{\"bookmark\":{},\"working_copy\":{},\"heads\":{},\"clean\":{},\"conflicted\":{},\"paths\":{paths},\"conflicts\":{},\"untracked_nested\":{},\"skipped_large\":{}}}",
8178×
            json_str(&self.config.bookmark),
8188×
            json_str(&snap.wc.change_id.to_hex()),
8198×
            heads.len(),
8208×
            snap.statuses.is_empty(),
8218×
            base_snapshot.is_conflicted(),
8228×
            json_array(conflicts),
8238×
            json_array(snap.untracked_nested.iter().map(|p| json_str(p))),
8248×
            json_array(
8258×
                self.skipped_large
8268×
                    .borrow()
8278×
                    .iter()
8288×
                    .map(|(p, n)| format!("{{\"path\":{},\"size\":{n}}}", json_str(p)))
829
            )
830
        ))
8318×
    }
832
833
    /// Turn the working-copy change into a normal change on the bookmark (spec §12.3).
834694×
    pub fn commit(&self, message: &str, extra_deps: &[ChangeHash]) -> Result<ChangeHash> {
835694×
        self.commit_selection(message, extra_deps, &Selection::All)
836694×
    }
837
838
    /// The hunks of the working copy, for `oxy commit --interactive`: each
839
    /// tree operation and each edit, in the order `select_hunks` numbers them.
8408×
    pub fn hunks(&self) -> Result<(SnapshotResult, Vec<Hunk>)> {
8418×
        let snap = self.snapshot_status("oxy commit")?;
8428×
        let hunks = render_hunks(&snap.wc, &snap.base, &snap.base_snapshot);
8438×
        Ok((snap, hunks))
8448×
    }
845
846
    /// Commit part of the working copy (spec §12.3). What is not selected
847
    /// stays on disk as uncommitted work: the next snapshot rebuilds it
848
    /// against the new base, so the working copy always describes the
849
    /// directory.
850
    /// The graph key in `st` of each text file at `paths`, the paths a
851
    /// commit changed: only their graphs changed, so the keys the manifest
852
    /// holds for the others still stand (and any that does not is simply
853
    /// not trusted by the next snapshot, which compares keys). Files with
854
    /// an `eol` attribute are left out: their bytes on disk are not the
855
    /// rendering.
856713×
    fn committed_graph_keys(
857713×
        &self,
858713×
        st: &State,
859713×
        paths: &[String],
860713×
        attrs: &crate::attributes::Attributes,
861713×
    ) -> HashMap<String, [u8; 32]> {
862713×
        let _t = crate::timing::phase("commit: graph keys");
863713×
        let view = st.view();
864713×
        paths
865713×
            .iter()
8663548×
            .filter_map(|p| {
8673548×
                let e = view.entries.get(p)?;
8683511×
                (e.kind == NodeKind::File && !e.mode.opaque && attrs.lookup(p).eol.is_none())
8693511×
                    .then_some(())?;
8703459×
                Some((p.clone(), st.graph_key(&e.node)?))
8713548×
            })
872713×
            .collect()
873713×
    }
874
875701×
    pub fn commit_selection(
876701×
        &self,
877701×
        message: &str,
878701×
        extra_deps: &[ChangeHash],
879701×
        selection: &Selection,
880701×
    ) -> Result<ChangeHash> {
881701×
        Ok(self
882701×
            .commit_selection_partial(message, extra_deps, selection)?
883
            .0)
884701×
    }
885
886
    /// As [`Repo::commit_selection`], and whether the commit left part of
887
    /// the working copy uncommitted: when it did not, nothing is left, and
888
    /// no snapshot is needed to say so.
889730×
    pub fn commit_selection_partial(
890730×
        &self,
891730×
        message: &str,
892730×
        extra_deps: &[ChangeHash],
893730×
        selection: &Selection,
894730×
    ) -> Result<(ChangeHash, bool)> {
895
        // The commit's objects are written together, made durable at once
896
        // before the operation that names them (spec §13.6).
897730×
        let batch = self.store.begin_batch()?;
898730×
        let out = self.commit_selection_batched(message, extra_deps, selection);
899730×
        batch.finish()?;
900730×
        out
901730×
    }
902
903
    /// Write the manifest a commit's snapshot left to the commit, with the
904
    /// graph keys `keys` sets.
905487×
    fn write_pending_manifest(
906487×
        &self,
907487×
        mut m: PendingManifest,
908487×
        conflicted: bool,
909487×
        keys: HashMap<String, [u8; 32]>,
910487×
    ) -> Result<()> {
9112873×
        for (path, k) in keys {
9122873×
            if let Some(e) = m.entries.get_mut(&path) {
9132873×
                e.graph_key = Some(k);
9142873×
            }
915
        }
916487×
        self.write_manifest_entries_as_of(
917487×
            conflicted,
918
            false,
919487×
            &m.entries,
920487×
            &m.blobs,
921487×
            m.written,
922487×
            m.dirs.unwrap_or_default(),
923
        )
924487×
    }
925
926730×
    fn commit_selection_batched(
927730×
        &self,
928730×
        message: &str,
929730×
        extra_deps: &[ChangeHash],
930730×
        selection: &Selection,
931730×
    ) -> Result<(ChangeHash, bool)> {
932730×
        let _wc = self.lock_working_copy()?;
933730×
        let mut snap = match self.snapshot_from_cache()? {
934232×
            Some(snap) => snap,
935498×
            None => self.snapshot_as("oxy commit", true, true)?,
936
        };
937730×
        let pending = snap.manifest.take();
938730×
        if snap.wc.tree_ops.is_empty() && snap.wc.edits.is_empty() {
9394×
            if let Some(m) = pending {
9404×
                let conflicted = snap.base_snapshot.is_conflicted();
9414×
                self.write_pending_manifest(m, conflicted, HashMap::new())?;
9420×
            }
9434×
            return fail("nothing to commit: the working copy matches its base");
944726×
        }
945726×
        if let Some(s) = snap
946726×
            .statuses
947726×
            .iter()
9483575×
            .find(|s| s.status == ChangeStatus::ConflictEdited)
949
        {
9500×
            return fail(format!("{} still contains conflict markers", s.path));
951726×
        }
952726×
        if message.trim().is_empty() {
9530×
            return fail("a commit message is required");
954726×
        }
955
        // What the whole working copy references, before a whole commit
956
        // takes its operations over (they are moved, not copied: for a
957
        // large tree they are most of the memory).
958726×
        let wc_refs = referenced_changes(&snap.wc, &snap.base);
9593575×
        let changed_paths: Vec<String> = snap.statuses.iter().map(|s| s.path.clone()).collect();
960726×
        let (tree_ops, edits, partial) = match selection {
961713×
            Selection::All => (
962713×
                std::mem::take(&mut snap.wc.tree_ops),
963713×
                std::mem::take(&mut snap.wc.edits),
964713×
                false,
965713×
            ),
9668×
            Selection::Paths(paths) => {
9678×
                let (o, e) = select_paths(&snap.wc, &snap.base_snapshot, paths);
9688×
                let partial = o.len() != snap.wc.tree_ops.len() || e.len() != snap.wc.edits.len();
9698×
                (o, e, partial)
970
            }
9715×
            Selection::Hunks(indices) => {
9725×
                let (o, e) = select_hunks(&snap.wc, indices, &snap.base_snapshot.tree.unified);
9735×
                let partial = o.len() != snap.wc.tree_ops.len() || e.len() != snap.wc.edits.len();
9745×
                (o, e, partial)
975
            }
976
        };
977726×
        if tree_ops.is_empty() && edits.is_empty() {
9780×
            return fail("nothing selected to commit");
979726×
        }
980
        // A resolution may leave other work uncommitted (oxygen#118), but
981
        // takes every file it resolves, whole.
982726×
        if partial && snap.resolves {
9832×
            let resolved = snap
9842×
                .statuses
9852×
                .iter()
9864×
                .filter(|s| s.status == ChangeStatus::Resolved)
9872×
                .map(|s| s.path.as_str());
9882×
            let missing: Vec<&str> = match selection {
9892×
                Selection::Paths(paths) => resolved
9902×
                    .filter(|p| {
9912×
                        !paths.iter().any(|x| {
9922×
                            p == x || p.starts_with(&format!("{}/", x.trim_end_matches('/')))
9932×
                        })
9942×
                    })
9952×
                    .collect(),
9960×
                _ => resolved.collect(),
997
            };
9982×
            if !missing.is_empty() {
9991×
                return fail(format!(
1000
                    "a conflict resolution takes every file it resolves, whole: commit by paths, including {}",
10011×
                    missing.join(", ")
1002
                ));
10031×
            }
1004724×
        }
1005
        // pre-commit hook: may veto.
1006725×
        self.run_hook(
1007725×
            "pre-commit",
1008725×
            &format!(
1009
                "{{\"event\":\"pre-commit\",\"message\":{},\"paths\":{}}}",
1010725×
                json_str(message),
10113573×
                json_array(snap.statuses.iter().map(|s| format!(
1012
                    "{{\"path\":{},\"status\":{}}}",
10133573×
                    json_str(&s.path),
10143573×
                    json_str(&format!("{:?}", s.status))
1015
                )))
1016
            ),
10171×
        )?;
1018724×
        let (op_ref, op) = self.head_op()?;
1019724×
        let mut deps: BTreeSet<ChangeHash> = wc_refs;
1020
        // semantic-deps hook: may add explicit dependencies (spec §8.1).
1021724×
        if self.config.semantic_deps {
10221×
            let touched: Vec<String> = snap.statuses.iter().map(|s| s.path.clone()).collect();
10231×
            let by_node = snap.base_snapshot.tree.by_node();
10241×
            let mut candidates: Vec<(ChangeId, ChangeHash, Vec<String>)> = Vec::new();
10251×
            let mut seen: BTreeSet<ChangeHash> = BTreeSet::new();
10262×
            for h in deps.iter().chain(snap.base.maximal(&snap.wc.deps).iter()) {
10272×
                if !seen.insert(*h) {
10280×
                    continue;
10292×
                }
10302×
                let c = self.store.get_change(h)?;
10312×
                let mut paths: BTreeSet<String> = BTreeSet::new();
10326×
                for n in c
10332×
                    .tree_ops
10342×
                    .iter()
10353×
                    .map(|o| o.node())
10363×
                    .chain(c.edits.iter().map(|e| e.node()))
1037
                {
10386×
                    if let Some(e) = by_node.get(&n) {
10396×
                        paths.insert(e.path.clone());
10406×
                    }
1041
                }
10422×
                candidates.push((c.change_id, *h, paths.into_iter().collect()));
1043
            }
10441×
            for d in self.semantic_deps(&snap.wc.change_id, &touched, &candidates)? {
10451×
                if snap.base.contains(&d) {
10461×
                    deps.insert(d);
10471×
                }
1048
            }
1049723×
        }
1050
        // A resolution depends on every change that contributed to the
1051
        // conflict (spec §8.1). Tree and opaque conflicts are resolved through
1052
        // ordinary operations whose references already cover the contributors.
1053724×
        deps.extend(snap.contributors.iter().copied());
1054724×
        for d in extra_deps {
10554×
            if !snap.base.contains(d) {
10560×
                return fail(format!(
1057
                    "--depends-on {d}: not in the working copy's base state"
1058
                ));
10594×
            }
10604×
            deps.insert(*d);
1061
        }
1062724×
        let mut change = Change {
1063
            version: crate::objects::CHANGE_VERSION,
1064724×
            change_id: if partial {
106510×
                ChangeId::random()
1066
            } else {
1067714×
                snap.wc.change_id
1068
            },
1069724×
            deps: vec![],
1070724×
            author: self.author(),
1071724×
            hlc: Hlc::now(),
1072724×
            message: message.trim_end().to_string(),
1073724×
            tree_ops,
1074724×
            edits,
1075724×
            kind: if snap.resolves {
10769×
                ChangeKind::Resolution
1077
            } else {
1078715×
                ChangeKind::Normal
1079
            },
1080
        };
1081724×
        if partial {
1082
            // Dependencies come from what the selected part references, not
1083
            // from the whole working copy.
108410×
            deps = referenced_changes(&change, &snap.base);
108510×
            for d in extra_deps {
10861×
                deps.insert(*d);
10871×
            }
1088714×
        }
1089724×
        change.deps = deps.into_iter().collect();
1090724×
        change.normalize();
1091724×
        let signing = crate::timing::phase("commit: sign and store");
1092724×
        let hash = self.store_signed(&change)?;
1093723×
        drop(signing);
1094723×
        let extending = crate::timing::phase("commit: extend the state");
1095
1096
        // New bookmark heads: maximal elements of old heads plus the new change.
1097
        // The working copy continues on its own base plus the new change, which
1098
        // is exactly what the files on disk contain; the bookmark may hold
1099
        // other heads (and conflicts) the working copy has not checked out.
1100723×
        let old_heads = self.heads_of(&op.view, &self.config.bookmark)?;
1101723×
        let old_base = snap.base.maximal(&snap.wc.deps);
1102723×
        let mut all: Vec<ChangeHash> = old_heads.clone();
1103723×
        all.extend(old_base.iter().copied());
1104723×
        all.push(hash);
1105
        // The snapshot already loaded the working copy's base; when that also
1106
        // holds every bookmark head, it is the state to extend.
1107723×
        let mut st = if old_heads.iter().all(|h| snap.base.contains(h)) {
1108685×
            snap.base
1109
        } else {
111038×
            self.load_state(&all)?
1111
        };
1112723×
        st.add_hashed(hash, change)?;
1113723×
        let mut with_new = old_heads.clone();
1114723×
        with_new.push(hash);
1115723×
        let new_heads = st.maximal(&with_new);
1116
        // Automatic checkpoint once enough changes accumulated (spec §11).
1117723×
        let since = self
1118723×
            .latest_checkpoint(&self.config.bookmark)?
1119723×
            .map(|(_, cp)| cp.count)
1120723×
            .unwrap_or(0);
1121723×
        if self.config.checkpoint_interval > 0
1122723×
            && (st.len() as u64).saturating_sub(since) >= self.config.checkpoint_interval
1123
        {
11242×
            let cp_state = self.load_state_full(&new_heads)?;
11252×
            self.write_checkpoint(&self.config.bookmark, &cp_state, &new_heads)?;
1126721×
        }
1127723×
        let mut wc_base = old_base.clone();
1128723×
        wc_base.push(hash);
1129723×
        let wc_base = st.maximal(&wc_base);
1130723×
        drop(extending);
1131
1132
        // The graph keys of the files as they now are, from the state the
1133
        // commit just extended: a file whose graph it built has none, and
1134
        // is read by the next snapshot; a key the next base does not share
1135
        // (the bookmark held other heads) is simply not trusted then.
1136723×
        let keying = crate::timing::phase("commit: graph keys of the files");
1137723×
        let committed_keys =
1138723×
            (!partial).then(|| self.committed_graph_keys(&st, &changed_paths, &snap.attributes));
1139723×
        drop(keying);
1140723×
        let recording = crate::timing::phase("commit: record");
1141723×
        let wc = self.new_working_copy(wc_base, "");
1142723×
        let wc_hash = self.store.put_change(&wc)?;
1143723×
        let mut view = op.view.clone();
1144723×
        view.bookmarks.insert(
1145723×
            self.config.bookmark.clone(),
1146723×
            self.store.put_state(&StateObject::new(new_heads))?,
1147
        );
1148723×
        view.workspaces.insert(self.workspace, wc_hash);
1149723×
        self.record_op(&[op_ref], &format!("oxy commit -m {message:?}"), view)?;
1150718×
        drop(recording);
1151718×
        let rewriting = crate::timing::phase("commit: manifest");
1152718×
        if partial {
115310×
            // The rest is rebuilt from disk by the next snapshot.
115410×
            self.drop_manifest();
115510×
        } else {
1156708×
            let conflicted = snap.base_snapshot.is_conflicted() && !snap.resolves;
1157
            // The files on disk are now exactly the new base's renderings:
1158
            // record their graph keys, so the next snapshot neither reads nor
1159
            // renders them (oxygen#35).
1160708×
            let keys = if conflicted {
11610×
                HashMap::new()
1162
            } else {
1163708×
                committed_keys.unwrap_or_default()
1164
            };
1165708×
            match pending {
1166483×
                Some(m) => self.write_pending_manifest(m, conflicted, keys)?,
1167225×
                None => self.rewrite_manifest(conflicted, false, &keys)?,
1168
            }
1169
        }
1170718×
        drop(rewriting);
1171718×
        let packing = crate::timing::phase("commit: autopack");
1172718×
        self.maybe_autopack()?;
1173718×
        drop(packing);
1174718×
        let _hook = crate::timing::phase("commit: hook");
1175718×
        let _ = self.run_hook(
1176718×
            "post-commit",
1177718×
            &format!(
1178718×
                "{{\"event\":\"post-commit\",\"change_id\":{},\"hash\":{},\"message\":{}}}",
1179718×
                json_str(&snap.wc.change_id.to_hex()),
1180718×
                json_str(&hash.to_hex()),
1181718×
                json_str(message)
1182718×
            ),
1183718×
        );
1184718×
        Ok((hash, partial))
1185730×
    }
1186
}
1187
1188
/// What part of the working copy a commit takes (spec §12.3).
1189
#[derive(Clone, Debug)]
1190
pub enum Selection {
1191
    All,
1192
    /// Every operation and edit on nodes under these paths.
1193
    Paths(Vec<String>),
1194
    /// Hunk indices as `Repo::hunks` numbers them; dependent hunks are added.
1195
    Hunks(Vec<usize>),
1196
}
1197
1198
/// One selectable piece of the working copy: a tree operation or an edit.
1199
#[derive(Clone, Debug)]
1200
pub struct Hunk {
1201
    pub index: usize,
1202
    pub path: String,
1203
    /// Rendered like `oxy diff`.
1204
    pub text: String,
1205
}
1206
1207
/// The tree operations and edits on nodes under `paths`, plus the
1208
/// additions of any new parent directories they need.
12098×
fn select_paths(
12108×
    wc: &Change,
12118×
    base_snapshot: &Snapshot,
12128×
    paths: &[String],
12138×
) -> (Vec<TreeOp>, Vec<Edit>) {
121427×
    let selected = |p: &str| {
121527×
        paths
121627×
            .iter()
121727×
            .any(|x| p == x || p.starts_with(&format!("{}/", x.trim_end_matches('/'))))
121827×
    };
12198×
    let by_node = base_snapshot.tree.by_node();
12208×
    let mut new_names: HashMap<NodeId, (NodeId, String, NodeKind)> = HashMap::new();
12218×
    for op in &wc.tree_ops {
1222
        if let TreeOp::AddNode {
12235×
            node,
12245×
            parent,
12255×
            name,
12265×
            kind,
1227
            ..
12286×
        } = op
12295×
        {
12305×
            new_names.insert(*node, (*parent, name.clone(), *kind));
12315×
        }
1232
    }
12338×
    let mut nodes: BTreeSet<NodeId> = BTreeSet::new();
123428×
    for n in wc
12358×
        .tree_ops
12368×
        .iter()
12378×
        .map(|o| o.node())
123822×
        .chain(wc.edits.iter().map(|e| e.node()))
1239
    {
124028×
        if path_of_node(&n, &by_node, &new_names).is_some_and(|p| selected(&p)) {
124114×
            nodes.insert(n);
124214×
        }
1243
    }
1244
    // The nodes shown as one with a selected node are retired with it.
12458×
    for (dup, shown) in &base_snapshot.tree.unified {
12461×
        if nodes.contains(shown) {
12471×
            nodes.insert(*dup);
12481×
        }
1249
    }
1250
    // New parents of selected new nodes come along.
12518×
    let mut changed = true;
125216×
    while changed {
12538×
        changed = false;
12548×
        for (n, (parent, _, _)) in &new_names {
12555×
            if nodes.contains(n) && new_names.contains_key(parent) && nodes.insert(*parent) {
12560×
                changed = true;
12575×
            }
1258
        }
1259
    }
12608×
    let ops = wc
12618×
        .tree_ops
12628×
        .iter()
12638×
        .filter(|o| nodes.contains(&o.node()))
12648×
        .cloned()
12658×
        .collect();
12668×
    let edits = wc
12678×
        .edits
12688×
        .iter()
126922×
        .filter(|e| nodes.contains(&e.node()))
12708×
        .cloned()
12718×
        .collect();
12728×
    (ops, edits)
12738×
}
1274
1275
/// The hunks `indices` name plus whatever they refer to within the working
1276
/// copy (the parent directory of an added node, the insert that introduced
1277
/// an anchor line), renumbered so the result is a well-formed change.
1278
/// The nodes `unified` shows as one with another (a base's
1279
/// [`TreeView::unified`](crate::tree::TreeView::unified)) are retired with
1280
/// any hunk of the node shown.
12816×
fn select_hunks(
12826×
    wc: &Change,
12836×
    indices: &[usize],
12846×
    unified: &BTreeMap<NodeId, NodeId>,
12856×
) -> (Vec<TreeOp>, Vec<Edit>) {
12866×
    let n_ops = wc.tree_ops.len();
12876×
    let mut ops_sel = vec![false; n_ops];
12886×
    let mut edits_sel = vec![false; wc.edits.len()];
12896×
    for &i in indices {
12905×
        if i < n_ops {
12911×
            ops_sel[i] = true;
12924×
        } else if i - n_ops < wc.edits.len() {
12934×
            edits_sel[i - n_ops] = true;
12944×
        }
1295
    }
1296
    // Atom ranges each insert introduces, per node, in the working copy's numbering.
12976×
    let mut per_node: HashMap<NodeId, u32> = HashMap::new();
12986×
    let mut insert_ranges: Vec<Option<(NodeId, u32, u32)>> = Vec::new();
129912×
    for e in &wc.edits {
130012×
        insert_ranges.push(match e {
130112×
            Edit::Insert { node, lines, .. } => {
130212×
                let start = per_node.entry(*node).or_default();
130312×
                let r = (*node, *start, *start + lines.len() as u32);
130412×
                *start += lines.len() as u32;
130512×
                Some(r)
1306
            }
13070×
            _ => None,
1308
        });
1309
    }
13106×
    let add_index: HashMap<NodeId, usize> = wc
13116×
        .tree_ops
13126×
        .iter()
13136×
        .enumerate()
131410×
        .filter_map(|(i, o)| {
131510×
            if let TreeOp::AddNode { node, .. } = o {
13169×
                Some((*node, i))
1317
            } else {
13181×
                None
1319
            }
132010×
        })
13216×
        .collect();
13226×
    let insert_for = |node: &NodeId, index: u32| -> Option<usize> {
13230×
        insert_ranges
13240×
            .iter()
13250×
            .position(|r| matches!(r, Some((n, a, b)) if n == node && *a <= index && index < *b))
13260×
    };
1327
    // Closure.
13286×
    let mut changed = true;
132915×
    while changed {
13309×
        changed = false;
133119×
        for i in 0..n_ops {
133219×
            if !ops_sel[i] {
133313×
                continue;
13346×
            }
13356×
            if let TreeOp::AddNode { node, parent, .. } = &wc.tree_ops[i] {
13366×
                if let Some(&p) = add_index.get(parent) {
13374×
                    if !ops_sel[p] {
13382×
                        ops_sel[p] = true;
13392×
                        changed = true;
13402×
                    }
13412×
                }
1342
                // A new node's content belongs with its addition: nobody
1343
                // wants an empty file committed apart from its lines.
134412×
                for (j, e) in wc.edits.iter().enumerate() {
134512×
                    if e.node() == *node && !edits_sel[j] {
13461×
                        edits_sel[j] = true;
13471×
                        changed = true;
134811×
                    }
1349
                }
13500×
            }
1351
        }
135218×
        for j in 0..wc.edits.len() {
135318×
            if !edits_sel[j] {
135410×
                continue;
13558×
            }
13568×
            let e = &wc.edits[j];
13578×
            if let Some(&a) = add_index.get(&e.node()) {
13585×
                if !ops_sel[a] {
13591×
                    ops_sel[a] = true;
13601×
                    changed = true;
13614×
                }
13623×
            }
1363
            if let Edit::Insert {
13648×
                node,
13658×
                after,
13668×
                before,
1367
                ..
13688×
            } = e
1369
            {
137016×
                for r in [after, before] {
137116×
                    if let AtomRef::Atom { change, index } = r {
13723×
                        if change.is_zero() {
13730×
                            if let Some(k) = insert_for(node, *index) {
13740×
                                if !edits_sel[k] {
13750×
                                    edits_sel[k] = true;
13760×
                                    changed = true;
13770×
                                }
13780×
                            }
13793×
                        }
138013×
                    }
1381
                }
13820×
            }
1383
        }
1384
    }
1385
    // The retirement of a node shown as one with a selected node.
13866×
    if !unified.is_empty() {
13871×
        let chosen: HashSet<NodeId> = (0..n_ops)
13882×
            .filter(|i| ops_sel[*i])
13891×
            .map(|i| wc.tree_ops[i].node())
13901×
            .chain(
13911×
                (0..wc.edits.len())
13922×
                    .filter(|j| edits_sel[*j])
13931×
                    .map(|j| wc.edits[j].node()),
1394
            )
13951×
            .collect();
13962×
        for (i, o) in wc.tree_ops.iter().enumerate() {
13972×
            if let TreeOp::RemoveNode { node, .. } = o {
13981×
                if unified.get(node).is_some_and(|s| chosen.contains(s)) {
13991×
                    ops_sel[i] = true;
14001×
                }
14011×
            }
1402
        }
14035×
    }
1404
    // Renumber self-references: old atom index → new index among selected inserts.
14056×
    let mut remap: HashMap<(NodeId, u32), u32> = HashMap::new();
14066×
    let mut new_counts: HashMap<NodeId, u32> = HashMap::new();
140712×
    for (j, r) in insert_ranges.iter().enumerate() {
140812×
        if let (true, Some((node, a, b))) = (edits_sel[j], r) {
14095×
            let next = new_counts.entry(*node).or_default();
14105×
            for old in *a..*b {
14115×
                remap.insert((*node, old), *next);
14125×
                *next += 1;
14135×
            }
14147×
        }
1415
    }
141610×
    let map_ref = |r: AtomRef, node: &NodeId| -> AtomRef {
14173×
        match r {
14183×
            AtomRef::Atom { change, index } if change.is_zero() => AtomRef::Atom {
14190×
                change,
14200×
                index: remap.get(&(*node, index)).copied().unwrap_or(index),
14210×
            },
142210×
            other => other,
1423
        }
142410×
    };
14256×
    let ops = wc
14266×
        .tree_ops
14276×
        .iter()
14286×
        .enumerate()
142910×
        .filter(|(i, _)| ops_sel[*i])
14306×
        .map(|(_, o)| o.clone())
14316×
        .collect();
14326×
    let edits = wc
14336×
        .edits
14346×
        .iter()
14356×
        .enumerate()
143612×
        .filter(|(j, _)| edits_sel[*j])
14376×
        .map(|(_, e)| match e {
1438
            Edit::Insert {
14395×
                node,
14405×
                after,
14415×
                before,
14425×
                lines,
14435×
            } => Edit::Insert {
14445×
                node: *node,
14455×
                after: map_ref(*after, node),
14465×
                before: map_ref(*before, node),
14475×
                lines: lines.clone(),
14485×
            },
14490×
            other => other.clone(),
14505×
        })
14516×
        .collect();
14526×
    (ops, edits)
14536×
}
1454
1455
/// Render each tree operation and edit of `change` on its own, numbered.
14568×
pub fn render_hunks(change: &Change, base: &State, base_snapshot: &Snapshot) -> Vec<Hunk> {
14578×
    let by_node = base_snapshot.tree.by_node();
14588×
    let mut new_names: HashMap<NodeId, (NodeId, String, NodeKind)> = HashMap::new();
145910×
    for op in &change.tree_ops {
1460
        if let TreeOp::AddNode {
14619×
            node,
14629×
            parent,
14639×
            name,
14649×
            kind,
1465
            ..
146610×
        } = op
14679×
        {
14689×
            new_names.insert(*node, (*parent, name.clone(), *kind));
14699×
        }
1470
    }
14718×
    let mut out = Vec::new();
147210×
    for (i, op) in change.tree_ops.iter().enumerate() {
1473
        // A retired duplicate goes with the node shown: no hunk of its own.
147410×
        if is_unified_retirement(op, base_snapshot) {
14751×
            continue;
14769×
        }
14779×
        let one = Change {
14789×
            tree_ops: vec![op.clone()],
14799×
            edits: vec![],
14809×
            ..change.clone()
14819×
        };
14829×
        let path = path_of_node(&op.node(), &by_node, &new_names).unwrap_or_default();
14839×
        out.push(Hunk {
14849×
            index: i,
14859×
            path,
14869×
            text: render_change(&one, base, base_snapshot),
14879×
        });
1488
    }
148915×
    for (j, e) in change.edits.iter().enumerate() {
149015×
        let one = Change {
149115×
            tree_ops: vec![],
149215×
            edits: vec![e.clone()],
149315×
            ..change.clone()
149415×
        };
149515×
        let path = path_of_node(&e.node(), &by_node, &new_names).unwrap_or_default();
149615×
        out.push(Hunk {
149715×
            index: change.tree_ops.len() + j,
149815×
            path,
149915×
            text: render_change(&one, base, base_snapshot),
150015×
        });
150115×
    }
15028×
    out
15038×
}
1504
1505
/// One file's part of a diff, for `oxy diff --json`.
1506
#[derive(Clone, Debug)]
1507
pub struct FileDiff {
1508
    pub path: String,
1509
    /// `added`, `removed`, `modified`, `renamed`, `mode`, `replaced`.
1510
    pub kind: String,
1511
    pub hunks: Vec<DiffHunk>,
1512
    /// For renames, the previous path.
1513
    pub from: Option<String>,
1514
}
1515
1516
/// Lines inserted after `base_line` (0 = before the first line) and lines
1517
/// removed, with their base line numbers.
1518
#[derive(Clone, Debug, Default)]
1519
pub struct DiffHunk {
1520
    pub base_line: u32,
1521
    pub added: Vec<Vec<u8>>,
1522
    pub removed: Vec<(u32, Vec<u8>)>,
1523
}
1524
1525
impl Repo {
1526
    /// The content of `path` in a state: `heads`, or the working copy's base.
152727×
    pub fn file_at(&self, path: &str, heads: Option<&[ChangeHash]>) -> Result<Vec<u8>> {
1528
        // The state's history and tree, then the one file's graph: nothing
1529
        // else is built or rendered (oxygen#92).
1530
        // The working copy's base, and a state named by its heads (`-r
1531
        // main` on main), come from the workspace's state index.
153227×
        let base = if self.is_bare() {
15335×
            None
1534
        } else {
153522×
            Some(self.working_copy()?.1.deps)
1536
        };
153727×
        let same = |a: &[ChangeHash], b: &[ChangeHash]| {
15381×
            let (mut a, mut b) = (a.to_vec(), b.to_vec());
15391×
            a.sort();
15401×
            b.sort();
15411×
            a == b
15421×
        };
154327×
        let mut state = match (heads, base) {
15441×
            (Some(h), Some(b)) if same(h, &b) => self.load_state_indexed(&b)?,
15455×
            (Some(h), _) => self.load_state_history(h)?,
154621×
            (None, Some(b)) => self.load_state_indexed(&b)?,
15470×
            (None, None) => return fail("this is a bare repository: it has no working copy"),
1548
        };
154927×
        let view = self.tree_view(&mut state)?;
155027×
        let Some(node) = view.entries.get(path).map(|e| e.node) else {
15510×
            return fail(format!("{path} is not in that state"));
1552
        };
155327×
        self.load_graphs_of(&mut state, &[node])?;
155426×
        let snapshot = state.materialize_paths(view, [path]);
155526×
        let Some(f) = snapshot.files.get(path) else {
15560×
            return fail(format!("{path} is not in that state"));
1557
        };
155826×
        match &f.content {
15590×
            FileContent::Dir => fail(format!("{path} is a directory")),
156026×
            FileContent::Text { bytes, .. } => Ok(bytes.clone()),
15610×
            FileContent::Opaque { blobs } => match blobs.first() {
15620×
                Some(b) => self.read_blob(b),
15630×
                None => Ok(vec![]),
1564
            },
1565
        }
156627×
    }
1567
1568
    /// Restore `paths` (files or directories) to the working copy's base:
1569
    /// edits are undone, additions removed, removals put back. Returns the
1570
    /// number of paths touched.
15712×
    pub fn discard(&self, paths: &[String]) -> Result<usize> {
15722×
        let _wc = self.lock_working_copy()?;
15732×
        let snap = self.snapshot_status("oxy discard")?;
15747×
        let under = |p: &str| {
15757×
            paths
15767×
                .iter()
15777×
                .any(|x| p == x || p.starts_with(&format!("{}/", x.trim_end_matches('/'))))
15787×
        };
15792×
        let attrs = Repo::state_attributes(&snap.base_snapshot);
15802×
        let mut n = 0;
15813×
        for s in &snap.statuses {
15823×
            if !under(&s.path) {
15831×
                continue;
15842×
            }
15852×
            match snap.base_snapshot.files.get(&s.path) {
1586
                None => {
1587
                    // Added (or the new name of a rename): remove it.
15881×
                    let full = self.root.join(&s.path);
15891×
                    if full.is_dir() {
15900×
                        let _ = fs::remove_dir_all(&full);
15911×
                    } else {
15921×
                        let _ = fs::remove_file(&full);
15931×
                    }
15941×
                    n += 1;
1595
                }
15961×
                Some(f) => {
15971×
                    match &f.content {
15980×
                        FileContent::Dir => fs::create_dir_all(self.root.join(&s.path))?,
15991×
                        FileContent::Text { bytes, .. } => {
16001×
                            let on_disk: std::borrow::Cow<[u8]> = if attrs.lookup(&s.path).eol
16011×
                                == Some(crate::attributes::Eol::Crlf)
1602
                            {
16030×
                                crate::attributes::to_crlf(bytes).into()
1604
                            } else {
16051×
                                bytes.as_slice().into()
1606
                            };
16071×
                            self.write_file(&s.path, &on_disk, f.mode.exec)?;
1608
                        }
16090×
                        FileContent::Opaque { blobs } => {
16100×
                            let bytes = match blobs.first() {
16110×
                                Some(b) => self.read_blob(b)?,
16120×
                                None => vec![],
1613
                            };
16140×
                            if f.kind == NodeKind::Symlink {
16150×
                                self.write_symlink(&s.path, &bytes)?;
16160×
                            } else if f.kind == NodeKind::File {
16170×
                                self.write_file(&s.path, &bytes, f.mode.exec)?;
16180×
                            }
1619
                        }
1620
                    }
16211×
                    n += 1;
1622
                }
1623
            }
1624
        }
1625
        // A rename's old name is not in the statuses; put it back too.
16264×
        for (p, f) in &snap.base_snapshot.files {
16274×
            if under(p)
16281×
                && !self.root.join(p).exists()
16290×
                && f.kind != NodeKind::Dir
16300×
                && f.kind != NodeKind::Subrepo
16310×
                && !snap.statuses.iter().any(|s| s.path == *p)
1632
            {
16330×
                let bytes = match &f.content {
16340×
                    FileContent::Text { bytes, .. } => bytes.clone(),
16350×
                    FileContent::Opaque { blobs } => blobs
16360×
                        .first()
16370×
                        .map(|b| self.read_blob(b))
16380×
                        .transpose()?
16390×
                        .unwrap_or_default(),
16400×
                    FileContent::Dir => continue,
1641
                };
16420×
                if f.kind == NodeKind::Symlink {
16430×
                    self.write_symlink(p, &bytes)?
1644
                } else {
16450×
                    self.write_file(p, &bytes, f.mode.exec)?
1646
                }
16470×
                n += 1;
16484×
            }
1649
        }
16502×
        self.drop_manifest();
16512×
        Ok(n)
16522×
    }
1653
1654
    /// Undo the working-copy hunks `indices` (as `hunks` numbers them) on
1655
    /// disk, keeping the others: the files are rewritten from the base plus
1656
    /// the remaining hunks.
16571×
    pub fn discard_hunks(&self, indices: &[usize]) -> Result<usize> {
16581×
        let _wc = self.lock_working_copy()?;
16591×
        let (snap, hunks) = self.hunks()?;
16601×
        let keep: Vec<usize> = hunks
16611×
            .iter()
16621×
            .map(|h| h.index)
16631×
            .filter(|i| !indices.contains(i))
16641×
            .collect();
16651×
        let (ops, edits) = select_hunks(&snap.wc, &keep, &snap.base_snapshot.tree.unified);
16661×
        let dropped_nodes: BTreeSet<NodeId> = hunks
16671×
            .iter()
16681×
            .filter(|h| indices.contains(&h.index))
16691×
            .map(|h| {
16701×
                if h.index < snap.wc.tree_ops.len() {
16710×
                    snap.wc.tree_ops[h.index].node()
1672
                } else {
16731×
                    snap.wc.edits[h.index - snap.wc.tree_ops.len()].node()
1674
                }
16751×
            })
16761×
            .collect();
16771×
        let mut partial = snap.wc.clone();
16781×
        partial.tree_ops = ops;
16791×
        partial.edits = edits;
16801×
        partial.normalize();
16811×
        let mut st = snap.base.clone();
16821×
        st.add_unchecked(partial);
1683
        // Every file of the target is rendered: build the graphs the
1684
        // partial snapshot left out.
16851×
        self.load_all_graphs(&mut st)?;
16861×
        let target = st.materialize();
16871×
        let by_node_target = target.tree.by_node();
16881×
        let by_node_base = snap.base_snapshot.tree.by_node();
16891×
        let attrs = Repo::state_attributes(&target);
16901×
        let mut n = 0;
16911×
        for node in dropped_nodes {
16921×
            match by_node_target.get(&node) {
16931×
                Some(e) => {
16941×
                    let f = &target.files[&e.path];
16951×
                    match &f.content {
16960×
                        FileContent::Dir => {}
16971×
                        FileContent::Text { bytes, .. } => {
16981×
                            let on_disk: std::borrow::Cow<[u8]> = if attrs.lookup(&e.path).eol
16991×
                                == Some(crate::attributes::Eol::Crlf)
1700
                            {
17010×
                                crate::attributes::to_crlf(bytes).into()
1702
                            } else {
17031×
                                bytes.as_slice().into()
1704
                            };
17051×
                            self.write_file(&e.path, &on_disk, f.mode.exec)?;
1706
                        }
17070×
                        FileContent::Opaque { blobs } => {
17080×
                            let bytes = blobs
17090×
                                .first()
17100×
                                .map(|b| self.read_blob(b))
17110×
                                .transpose()?
17120×
                                .unwrap_or_default();
17130×
                            if f.kind == NodeKind::Symlink {
17140×
                                self.write_symlink(&e.path, &bytes)?
1715
                            } else {
17160×
                                self.write_file(&e.path, &bytes, f.mode.exec)?
1717
                            }
1718
                        }
1719
                    }
1720
                    // A discarded rename: the new name goes.
17211×
                    if let Some(old_path) = snap
17221×
                        .statuses
17231×
                        .iter()
17241×
                        .find(|s| {
17251×
                            s.status == ChangeStatus::Renamed && !target.files.contains_key(&s.path)
17261×
                        })
17271×
                        .map(|s| s.path.clone())
17280×
                    {
17290×
                        let _ = fs::remove_file(self.root.join(old_path));
17301×
                    }
17311×
                    n += 1;
1732
                }
1733
                None => {
1734
                    // The node exists in neither target nor base with a live path: an addition to remove.
17350×
                    if let Some(added) = snap.statuses.iter().find(|s| {
17360×
                        s.status == ChangeStatus::Added
17370×
                            && !target.files.contains_key(&s.path)
17380×
                            && !by_node_base.contains_key(&node)
17390×
                    }) {
17400×
                        let full = self.root.join(&added.path);
17410×
                        if full.is_dir() {
17420×
                            let _ = fs::remove_dir_all(&full);
17430×
                        } else {
17440×
                            let _ = fs::remove_file(&full);
17450×
                        }
17460×
                        n += 1;
17470×
                    }
1748
                }
1749
            }
1750
        }
17511×
        self.drop_manifest();
17521×
        Ok(n)
17531×
    }
1754
1755
    /// The diff of the working copy (`None`) or of a change, per file with
1756
    /// line-numbered hunks (spec: `oxy diff --json`).
17577×
    pub fn diff_files(&self, change: Option<&ChangeHash>) -> Result<Vec<FileDiff>> {
17587×
        let (c, base, base_snapshot) = match change {
17593×
            Some(h) => {
17603×
                let c = self.store.get_change(h)?;
17613×
                let (base, snapshot) = self.change_base(&c)?;
17623×
                (c, base, snapshot)
1763
            }
17644×
            None => match self.working_copy_with_base_unless_unchanged()? {
17653×
                Some(all) => all,
17661×
                None => return Ok(Vec::new()),
1767
            },
1768
        };
17696×
        Ok(diff_files_of(&c, &base, &base_snapshot))
17707×
    }
1771
1772
    /// The snapshot a command would take, without taking it, when the
1773
    /// status cache holds: every file is as the last snapshot left it, so
1774
    /// that snapshot's working-copy change is the answer. Its base comes
1775
    /// from the state index, the `.oxyattributes` files from disk. `None`
1776
    /// when a snapshot must be taken, and when there is nothing to commit
1777
    /// (the snapshot then says so). A conflicted base never gets here: the
1778
    /// cache does not hold for one.
1779731×
    pub(crate) fn snapshot_from_cache(&self) -> Result<Option<SnapshotResult>> {
1780731×
        let Some(statuses) = self.status_by_manifest()? else {
1781495×
            return Ok(None);
1782
        };
1783236×
        if statuses.is_empty() {
17843×
            return Ok(None);
1785233×
        }
1786233×
        let _t = crate::timing::phase("snapshot: from the status cache");
1787233×
        let (wc_hash, wc) = self.working_copy()?;
1788233×
        let base = self.load_state_indexed(&wc.deps)?;
1789233×
        let (base, base_snapshot) = self.render_base_for(&wc, base)?;
1790233×
        let attribute_files: Vec<(String, Vec<u8>)> = match self.read_manifest()? {
1791233×
            Some((_, _, m)) => m
1792233×
                .entries
1793233×
                .keys()
1794721×
                .filter(|p| is_attributes(p))
1795233×
                .filter_map(|p| fs::read(self.root.join(p)).ok().map(|b| (p.clone(), b)))
1796233×
                .collect(),
17970×
            None => Vec::new(),
1798
        };
1799233×
        let attributes = crate::attributes::Attributes::from_files(
1800233×
            attribute_files
1801233×
                .iter()
1802233×
                .map(|(p, b)| (p.as_str(), b.as_slice())),
1803
        );
1804233×
        Ok(Some(SnapshotResult {
1805233×
            wc_hash,
1806233×
            wc,
1807233×
            base,
1808233×
            base_snapshot,
1809233×
            statuses,
1810233×
            changed: false,
1811233×
            resolves: false,
1812233×
            contributors: Vec::new(),
1813233×
            attributes,
1814233×
            untracked_nested: self.untracked_nested.borrow().clone(),
1815233×
            manifest: None,
1816233×
        }))
1817731×
    }
1818
1819
    /// The working-copy change with its base state and a snapshot of the
1820
    /// base, for showing what the working copy changes ([`render_change`],
1821
    /// [`diff_files_of`]). While the status cache holds (every file as the
1822
    /// last snapshot left it), the stored working-copy change is the
1823
    /// answer, no snapshot is taken, and the base's snapshot holds its tree
1824
    /// but no file; otherwise a snapshot makes all three.
18252×
    pub fn working_copy_with_base(&self) -> Result<(Change, State, Snapshot)> {
18262×
        match self.working_copy_with_base_unless_unchanged()? {
18271×
            Some(all) => Ok(all),
1828
            None => {
18291×
                let (_, wc) = self.working_copy()?;
18301×
                let base = self.load_state_indexed(&wc.deps)?;
18311×
                let (base, snapshot) = self.tree_base_for(&wc, base)?;
18321×
                Ok((wc, base, snapshot))
1833
            }
1834
        }
18352×
    }
1836
1837
    /// [`Repo::working_copy_with_base`], or `None` when the status cache
1838
    /// holds and the working-copy change changes nothing: its diff is
1839
    /// empty, and the base is not loaded for it (oxygen#94).
18407×
    pub fn working_copy_with_base_unless_unchanged(
18417×
        &self,
18427×
    ) -> Result<Option<(Change, State, Snapshot)>> {
18437×
        if self.status_by_manifest()?.is_some() {
18445×
            let (_, wc) = self.working_copy()?;
18455×
            if wc.tree_ops.is_empty() && wc.edits.is_empty() {
18463×
                return Ok(None);
18472×
            }
18482×
            let base = self.load_state_indexed(&wc.deps)?;
18492×
            let (base, snapshot) = self.tree_base_for(&wc, base)?;
18502×
            return Ok(Some((wc, base, snapshot)));
18512×
        }
18522×
        let snap = self.snapshot_status("oxy diff")?;
18532×
        Ok(Some((snap.wc, snap.base, snap.base_snapshot)))
18547×
    }
1855
1856
    /// The log restricted to changes touching `path` (its node, so renames
1857
    /// are followed), on the current bookmark.
18586×
    pub fn log_for_path(&self, path: &str) -> Result<Vec<LogEntry>> {
18596×
        let heads = self.bookmark_heads()?;
18606×
        if self.is_bare() {
18611×
            return self.log_for_path_in(path, &heads);
18625×
        }
18635×
        let entries = self.log()?;
18645×
        let (_, wc) = self.working_copy()?;
1865
        // The path's node from the trees alone: the base's (from the
1866
        // workspace's state index), else the bookmark's. Nothing is
1867
        // rendered.
18685×
        let node_in = |mut state: State| -> Result<Option<HashSet<NodeId>>> {
18695×
            Ok(nodes_at(&self.tree_view(&mut state)?, path))
18705×
        };
18715×
        let nodes = match node_in(self.load_state_indexed(&wc.deps)?)? {
18725×
            Some(n) => Some(n),
18730×
            None => node_in(self.load_state_history(&heads)?)?,
1874
        };
18755×
        let Some(nodes) = nodes else {
18760×
            return fail(format!("{path} is not tracked"));
1877
        };
18785×
        Ok(self.entries_touching_up_to(entries, nodes, None))
18796×
    }
1880
1881
    /// The log of the state with these heads restricted to changes touching
1882
    /// `path` (its node, so renames are followed).
18832×
    pub fn log_for_path_in(&self, path: &str, heads: &[ChangeHash]) -> Result<Vec<LogEntry>> {
18842×
        self.log_for_path_of(&self.load_state_history(heads)?, path, None)
18852×
    }
1886
1887
    /// The changes of a loaded state touching `path`, newest first, at most
1888
    /// `limit` of them. The path is found in the state's tree alone, so no
1889
    /// file is rendered, and the walk stops once `limit` are found.
18905×
    pub fn log_for_path_of(
18915×
        &self,
18925×
        state: &State,
18935×
        path: &str,
18945×
        limit: Option<usize>,
18955×
    ) -> Result<Vec<LogEntry>> {
18965×
        let Some(nodes) = nodes_at(&state.view(), path) else {
18971×
            return fail(format!("{path} is not in that state"));
1898
        };
18994×
        Ok(self.entries_touching_up_to(self.log_of(state), nodes, limit))
19005×
    }
1901
19029×
    fn entries_touching_up_to(
19039×
        &self,
19049×
        entries: Vec<LogEntry>,
19059×
        wanted: HashSet<NodeId>,
19069×
        limit: Option<usize>,
19079×
    ) -> Vec<LogEntry> {
19089×
        let mut touched = self.touched();
19099×
        if limit.is_none() {
19108×
            let hashes: Vec<ChangeHash> = entries.iter().map(|e| e.hash).collect();
19118×
            touched.fill(self, &hashes);
19121×
        }
19139×
        let mut out = Vec::new();
191432×
        for e in entries {
191532×
            if limit.is_some_and(|n| out.len() >= n) {
19161×
                break;
191731×
            }
191831×
            if touched.touches(self, &e.hash, &wanted) {
191920×
                out.push(e);
192020×
            }
1921
        }
19229×
        touched.save();
19239×
        out
19249×
    }
1925
}
1926
1927
/// The node at `path` in `view`, with the nodes it shows as one with it
1928
/// (identical additions, spec §9.2): the file's history is all of theirs.
192910×
fn nodes_at(view: &crate::tree::TreeView, path: &str) -> Option<HashSet<NodeId>> {
193010×
    let node = view.entries.get(path)?.node;
19319×
    let mut out = HashSet::from([node]);
19329×
    out.extend(
19339×
        view.unified
19349×
            .iter()
19359×
            .filter(|(_, shown)| **shown == node)
19369×
            .map(|(dup, _)| *dup),
1937
    );
19389×
    Some(out)
193910×
}
1940
1941
/// Per-file hunks of `change` against `base`.
19426×
pub fn diff_files_of(change: &Change, base: &State, base_snapshot: &Snapshot) -> Vec<FileDiff> {
19436×
    let by_node = base_snapshot.tree.by_node();
19446×
    let mut new_names: HashMap<NodeId, (NodeId, String, NodeKind)> = HashMap::new();
19456×
    for op in &change.tree_ops {
1946
        if let TreeOp::AddNode {
19472×
            node,
19482×
            parent,
19492×
            name,
19502×
            kind,
1951
            ..
19523×
        } = op
19532×
        {
19542×
            new_names.insert(*node, (*parent, name.clone(), *kind));
19552×
        }
1956
    }
195710×
    let path_of = |n: &NodeId| -> String {
195810×
        path_of_node(n, &by_node, &new_names).unwrap_or_else(|| format!("<node {}>", n.short(8)))
195910×
    };
19606×
    let mut files: BTreeMap<NodeId, FileDiff> = BTreeMap::new();
19616×
    let mut order: Vec<NodeId> = Vec::new();
196215×
    let mut entry = |files: &mut BTreeMap<NodeId, FileDiff>, n: NodeId, kind: &str| {
196315×
        if let std::collections::btree_map::Entry::Vacant(v) = files.entry(n) {
196410×
            order.push(n);
196510×
            v.insert(FileDiff {
196610×
                path: path_of(&n),
196710×
                kind: kind.to_string(),
196810×
                hunks: vec![],
196910×
                from: None,
197010×
            });
197110×
        }
197215×
    };
19736×
    for op in change
19746×
        .tree_ops
19756×
        .iter()
19766×
        .filter(|o| !is_unified_retirement(o, base_snapshot))
1977
    {
19783×
        match op {
19792×
            TreeOp::AddNode { node, kind, .. } => {
19802×
                if *kind != NodeKind::Dir {
19812×
                    entry(&mut files, *node, "added");
19822×
                }
1983
            }
19841×
            TreeOp::RemoveNode { node, .. } => {
19851×
                entry(&mut files, *node, "removed");
19861×
                if let Some(e) = by_node.get(node) {
19871×
                    files.get_mut(node).unwrap().path = e.path.clone();
19881×
                }
1989
            }
1990
            TreeOp::Move {
19910×
                node, parent, name, ..
1992
            } => {
19930×
                entry(&mut files, *node, "renamed");
19940×
                let f = files.get_mut(node).unwrap();
19950×
                f.from = by_node.get(node).map(|e| e.path.clone());
19960×
                let dir = if parent.is_root() {
19970×
                    String::new()
1998
                } else {
19990×
                    path_of_node(parent, &by_node, &new_names).unwrap_or_default()
2000
                };
20010×
                f.path = if dir.is_empty() {
20020×
                    name.clone()
2003
                } else {
20040×
                    format!("{dir}/{name}")
2005
                };
2006
            }
20070×
            TreeOp::SetMode { node, .. } => entry(&mut files, *node, "mode"),
2008
        }
2009
    }
2010
    // Base line numbers per node, 1-based.
20116×
    let mut line_of: HashMap<NodeId, HashMap<(ChangeHash, u32), u32>> = HashMap::new();
201212×
    let mut lines_for = |n: &NodeId| -> HashMap<(ChangeHash, u32), u32> {
201312×
        line_of
201412×
            .entry(*n)
201512×
            .or_insert_with(|| {
20169×
                base.live_lines(n)
20179×
                    .into_iter()
20189×
                    .enumerate()
201912×
                    .map(|(i, (k, _))| (k, i as u32 + 1))
20209×
                    .collect()
20219×
            })
202212×
            .clone()
202312×
    };
202412×
    for e in &change.edits {
202512×
        let n = e.node();
202612×
        let is_new = new_names.contains_key(&n);
202712×
        entry(&mut files, n, if is_new { "added" } else { "modified" });
202812×
        let f = files.get_mut(&n).unwrap();
202912×
        match e {
203010×
            Edit::Insert { after, lines, .. } => {
203110×
                let map = lines_for(&n);
203210×
                let base_line = match after {
20333×
                    AtomRef::Start => 0,
20340×
                    AtomRef::End => map.len() as u32,
20357×
                    AtomRef::Atom { change, index } if change.is_zero() => {
20360×
                        f.hunks.last().map(|h| h.base_line).unwrap_or(0)
2037
                    }
20387×
                    AtomRef::Atom { change, index } => {
20397×
                        map.get(&(*change, *index)).copied().unwrap_or(0)
2040
                    }
2041
                };
204210×
                f.hunks.push(DiffHunk {
204310×
                    base_line,
204410×
                    added: lines.to_vec(),
204510×
                    removed: vec![],
204610×
                });
2047
            }
20482×
            Edit::Delete { atoms, .. } => {
20492×
                let map = lines_for(&n);
20502×
                let mut removed = Vec::new();
20512×
                for r in atoms {
20522×
                    for i in r.from..r.to {
20532×
                        let line = map.get(&(r.change, i)).copied().unwrap_or(0);
20542×
                        let text = base
20552×
                            .file(&n)
20562×
                            .and_then(|g| g.content(&(r.change, i)))
20572×
                            .unwrap_or(b"")
20582×
                            .to_vec();
20592×
                        removed.push((line, text));
2060
                    }
2061
                }
20622×
                let base_line = removed
20632×
                    .first()
20642×
                    .map(|(l, _)| l.saturating_sub(1))
20652×
                    .unwrap_or(0);
20662×
                f.hunks.push(DiffHunk {
20672×
                    base_line,
20682×
                    added: vec![],
20692×
                    removed,
20702×
                });
2071
            }
2072
            Edit::Replace { .. } => {
20730×
                if !is_new {
20740×
                    f.kind = "replaced".into();
20750×
                }
2076
            }
2077
        }
2078
    }
207910×
    order.into_iter().filter_map(|n| files.remove(&n)).collect()
20806×
}
2081
2082
/// Builds the tree ops and edits of a working-copy change against a base.
2083
/// `BLAKE3("oxy node 1" 0 seed kind path)`, truncated: a node identifier
2084
/// that the same seed and path always give (never the root's).
208559×
fn seeded_node(seed: &[u8; 32], path: &str, kind: NodeKind) -> NodeId {
208659×
    let mut h = blake3::Hasher::new();
208759×
    h.update(b"oxy node 1\0");
208859×
    h.update(seed);
208959×
    h.update(&[match kind {
209045×
        NodeKind::File => 1,
209113×
        NodeKind::Dir => 2,
20920×
        NodeKind::Symlink => 3,
20931×
        NodeKind::Subrepo => 4,
2094
    }]);
209559×
    h.update(path.as_bytes());
209659×
    let mut id = [0u8; 16];
209759×
    id.copy_from_slice(&h.finalize().as_bytes()[..16]);
209859×
    if id == [0; 16] {
20990×
        id[15] = 1;
210059×
    }
210159×
    NodeId(id)
210259×
}
2103
2104
struct ChangeBuilder<'a> {
2105
    base: &'a State,
2106
    base_snapshot: &'a Snapshot,
2107
    tree_ops: Vec<TreeOp>,
2108
    edits: Vec<Edit>,
2109
    statuses: Vec<PathStatus>,
2110
    dir_nodes: HashMap<String, NodeId>,
2111
    reuse: HashMap<String, (NodeId, NodeKind)>,
2112
    /// Changes that contributed to conflicts this working copy resolves.
2113
    contributors: BTreeSet<ChangeHash>,
2114
    resolves: bool,
2115
    attrs: crate::attributes::Attributes,
2116
    blobs: HashMap<String, ObjectRef>,
2117
    /// Opaque files whose replace conflict the content settles.
2118
    resolve: HashSet<String>,
2119
    /// When set, new nodes' identifiers derive from it and their paths.
2120
    node_seed: Option<[u8; 32]>,
2121
    /// For a Git import, the base's dead directories by where they were
2122
    /// (see `ensure_dir`), worked out when first needed.
2123
    dead_dirs: Option<HashMap<(NodeId, String), (NodeId, crate::tree::OpKey)>>,
2124
    /// Text edits of edited files, worked out in parallel beforehand
2125
    /// (`diff_in_parallel`); a file not here is diffed when it is updated.
2126
    diffs: HashMap<String, Vec<Edit>>,
2127
}
2128
2129
impl<'a> ChangeBuilder<'a> {
21302188×
    fn new(
21312188×
        base: &'a State,
21322188×
        base_snapshot: &'a Snapshot,
21332188×
        reuse: HashMap<String, (NodeId, NodeKind)>,
21342188×
    ) -> Self {
21352188×
        let mut dir_nodes: HashMap<String, NodeId> = HashMap::new();
21362188×
        dir_nodes.insert(String::new(), NodeId::ROOT);
213717963×
        for (p, e) in base_snapshot.tree.entries.iter() {
213817963×
            if e.kind == NodeKind::Dir {
2139566×
                dir_nodes.insert(p.clone(), e.node);
214017397×
            }
2141
        }
21422188×
        ChangeBuilder {
21432188×
            base,
21442188×
            base_snapshot,
21452188×
            tree_ops: vec![],
21462188×
            edits: vec![],
21472188×
            statuses: vec![],
21482188×
            dir_nodes,
21492188×
            reuse,
21502188×
            contributors: BTreeSet::new(),
21512188×
            resolves: false,
21522188×
            attrs: crate::attributes::Attributes::default(),
21532188×
            blobs: HashMap::new(),
21542188×
            resolve: HashSet::new(),
21552188×
            node_seed: None,
21562188×
            dead_dirs: None,
21572188×
            diffs: HashMap::new(),
21582188×
        }
21592188×
    }
2160
2161
    /// Diff the edited text files among `entries` against their base
2162
    /// renderings at once, on every core, for `update_path` to take: the
2163
    /// same diff it would make, only not one file after another.
21642188×
    fn diff_in_parallel(&mut self, entries: &BTreeMap<String, FsEntry>) {
2165
        use rayon::prelude::*;
21662188×
        let files = &self.base_snapshot.files;
21672188×
        let edited: Vec<(&String, &FsEntry, &crate::state::FileState)> = entries
21682188×
            .iter()
216919081×
            .filter_map(|(p, e)| {
217019081×
                let x = files.get(p)?;
217112919×
                (x.kind == e.kind && !e.unchanged && !self.opaque_for(p, e)).then_some((p, e, x))
217219081×
            })
21732188×
            .collect();
2174
        // Below this, starting the threads costs more than it saves.
21752188×
        if edited.len() < 16 {
21762178×
            return;
217710×
        }
217810×
        let this = &*self;
217910×
        let attrs = &this.attrs;
218010×
        let diffs: Vec<(String, Vec<Edit>)> = edited
218110×
            .par_iter()
21825562×
            .filter_map(|(p, e, x)| {
2183
                let FileContent::Text {
21845562×
                    bytes,
21855562×
                    materialized,
21865562×
                } = &x.content
2187
                else {
21880×
                    return None;
2189
                };
21905562×
                if materialized.is_conflicted() {
21910×
                    return None;
21925562×
                }
21935562×
                let disk_text = if attrs.lookup(p).eol.is_some() {
21940×
                    std::sync::Arc::new(crate::attributes::normalize_eol(&e.content))
2195
                } else {
21965562×
                    e.content.clone()
2197
                };
21985562×
                if *bytes == *disk_text {
21995482×
                    return None;
220080×
                }
220180×
                let keys = materialized.live_atoms();
220280×
                let lines = crate::diff::split_lines(bytes);
220380×
                (keys.len() == lines.len()).then(|| {
220480×
                    let edits = crate::diff::text_edits_of(x.node, &keys, &lines, &disk_text);
220580×
                    ((*p).clone(), edits)
220680×
                })
22075562×
            })
220810×
            .collect();
220910×
        self.diffs = diffs.into_iter().collect();
22102188×
    }
2211
22122188×
    fn with_attributes(mut self, attrs: crate::attributes::Attributes) -> Self {
22132188×
        self.attrs = attrs;
22142188×
        self
22152188×
    }
2216
2217
    /// Whether a file is opaque: forced by `binary`, forced text by `text`
2218
    /// only when it has no NUL bytes, else sniffed.
2219
    /// The blob for an opaque entry: the cached one, else stored now.
2220137×
    fn blob_of(
2221137×
        &mut self,
2222137×
        repo: &Repo,
2223137×
        path: &str,
2224137×
        e: &FsEntry,
2225137×
        nocompress: bool,
2226137×
    ) -> Result<ObjectRef> {
2227137×
        let b = match e.blob {
22280×
            Some(b) => b,
2229137×
            None => repo.store_blob_for(&e.content, nocompress)?,
2230
        };
2231137×
        self.blobs.insert(path.to_string(), b);
2232137×
        Ok(b)
2233137×
    }
2234
223523511×
    fn opaque_for(&self, path: &str, e: &FsEntry) -> bool {
223623511×
        if e.blob.is_some() {
22378×
            return true;
223823503×
        }
223923503×
        if e.kind == NodeKind::Symlink || e.kind == NodeKind::Subrepo {
2240100×
            return true;
224123403×
        }
224223403×
        match self.attrs.lookup(path).binary {
224312×
            Some(true) => true,
22440×
            Some(false) => is_binary(&e.content),
224523391×
            None => is_binary(&e.content),
2246
        }
224723511×
    }
2248
2249
    /// Text content as stored: `\r\n` normalized for `eol=` files.
225014701×
    fn stored_text(
225114701×
        &self,
225214701×
        path: &str,
225314701×
        content: &std::sync::Arc<Vec<u8>>,
225414701×
    ) -> std::sync::Arc<Vec<u8>> {
225514701×
        if self.attrs.lookup(path).eol.is_some() {
22567×
            std::sync::Arc::new(crate::attributes::normalize_eol(content))
2257
        } else {
225814694×
            content.clone()
2259
        }
226014701×
    }
2261
2262
    /// The identifier of a node added at `path`: reused when asked, derived
2263
    /// from the seed when there is one, random otherwise.
22646283×
    fn new_node(&self, path: &str, kind: NodeKind) -> NodeId {
22656283×
        if let Some(n) = self.reused_node(path, kind) {
2266164×
            return n;
22676119×
        }
22686119×
        match &self.node_seed {
226959×
            Some(seed) => seeded_node(seed, path, kind),
22706060×
            None => NodeId::random(),
2271
        }
22726283×
    }
2273
22746283×
    fn reused_node(&self, path: &str, kind: NodeKind) -> Option<NodeId> {
22756283×
        self.reuse
22766283×
            .get(path)
22776283×
            .filter(|(_, k)| *k == kind)
22786283×
            .map(|(n, _)| *n)
22796283×
    }
2280
2281
    /// A dead directory last placed at (`parent`, `name`) in the base.
228215×
    fn revivable_dir(
228315×
        &mut self,
228415×
        parent: NodeId,
228515×
        name: &str,
228615×
    ) -> Option<(NodeId, crate::tree::OpKey)> {
228715×
        let base = self.base;
228815×
        self.dead_dirs
228915×
            .get_or_insert_with(|| base.tree().dead_dirs())
229015×
            .get(&(parent, name.to_string()))
229115×
            .copied()
229215×
    }
2293
22946163×
    fn ensure_dir(&mut self, path: &str) -> NodeId {
22956163×
        if let Some(n) = self.dir_nodes.get(path) {
22966012×
            return *n;
2297151×
        }
2298151×
        let mut parent = NodeId::ROOT;
2299151×
        let mut prefix = String::new();
2300170×
        for comp in path.split('/') {
2301170×
            if !prefix.is_empty() {
230219×
                prefix.push('/');
2303151×
            }
2304170×
            prefix.push_str(comp);
2305170×
            let known = self.dir_nodes.get(&prefix).copied();
2306170×
            let revive = match known {
230713×
                Some(_) => None,
2308157×
                None if self.node_seed.is_some() => self.revivable_dir(parent, comp),
2309142×
                None => None,
2310
            };
2311170×
            parent = match (known, revive) {
231213×
                (Some(n), _) => n,
23132×
                (None, Some((node, old))) => {
2314
                    // Git has no identity for a directory: one that comes
2315
                    // back where it was is the same directory, brought back
2316
                    // with a move, so lines of history that placed files in
2317
                    // it before and after agree (oxygen#30).
23182×
                    self.tree_ops.push(TreeOp::Move {
23192×
                        node,
23202×
                        old: OpRef {
23212×
                            change: old.0,
23222×
                            index: old.1,
23232×
                        },
23242×
                        parent,
23252×
                        name: comp.to_string(),
23262×
                    });
23272×
                    self.dir_nodes.insert(prefix.clone(), node);
23282×
                    node
2329
                }
2330
                (None, None) => {
2331155×
                    let node = self.new_node(&prefix, NodeKind::Dir);
2332155×
                    self.tree_ops.push(TreeOp::AddNode {
2333155×
                        node,
2334155×
                        kind: NodeKind::Dir,
2335155×
                        mode: Mode::default(),
2336155×
                        parent,
2337155×
                        name: comp.to_string(),
2338155×
                    });
2339155×
                    self.dir_nodes.insert(prefix.clone(), node);
2340155×
                    node
2341
                }
2342
            };
2343
        }
2344151×
        parent
23456163×
    }
2346
23476128×
    fn add_path(&mut self, repo: &Repo, path: &str, e: &FsEntry) -> Result<()> {
23486128×
        let (dir, name) = split_path(path);
23496128×
        let parent = self.ensure_dir(dir);
23506128×
        let node = self.new_node(path, e.kind);
23516128×
        let opaque = self.opaque_for(path, e);
23526128×
        let nocompress = self.attrs.lookup(path).nocompress;
23536128×
        self.tree_ops.push(TreeOp::AddNode {
23546128×
            node,
23556128×
            kind: e.kind,
23566128×
            mode: Mode {
23576128×
                exec: e.exec,
23586128×
                opaque,
23596128×
            },
23606128×
            parent,
23616128×
            name: name.to_string(),
23626128×
        });
23636128×
        if opaque {
2364101×
            let blob = self.blob_of(repo, path, e, nocompress)?;
2365101×
            self.edits.push(Edit::Replace {
2366101×
                node,
2367101×
                old: None,
2368101×
                new: Some(blob),
2369101×
            });
23706027×
        } else if !e.content.is_empty() {
23715992×
            let content = self.stored_text(path, &e.content);
23725992×
            self.edits.push(Edit::Insert {
23735992×
                node,
23745992×
                after: crate::objects::AtomRef::Start,
23755992×
                before: crate::objects::AtomRef::End,
23765992×
                lines: crate::lines::Lines::split_shared(content),
23775992×
            });
23785992×
        }
23796128×
        self.statuses.push(PathStatus {
23806128×
            path: path.to_string(),
23816128×
            status: ChangeStatus::Added,
23826128×
        });
23836128×
        Ok(())
23846128×
    }
2385
2386
    /// Move the node at `old` to `new` and apply `e`'s content to it.
238735×
    fn move_path(
238835×
        &mut self,
238935×
        repo: &Repo,
239035×
        old: &str,
239135×
        new: &str,
239235×
        e: &FsEntry,
239335×
        expected: &crate::state::FileState,
239435×
    ) -> Result<()> {
239535×
        let placement = self.base_snapshot.tree.entries[old].placement;
239635×
        let (dir, name) = split_path(new);
239735×
        let parent = self.ensure_dir(dir);
239835×
        self.tree_ops.push(TreeOp::Move {
239935×
            node: expected.node,
240035×
            old: op_ref(placement),
240135×
            parent,
240235×
            name: name.to_string(),
240335×
        });
240435×
        for k in self.same_place(&expected.node, placement) {
24050×
            self.tree_ops.push(TreeOp::RemoveNode {
24060×
                node: expected.node,
24070×
                placement: op_ref(k),
24080×
            });
24090×
        }
241035×
        self.update_path(repo, old, e, expected)?;
2411
        // update_path reports under the old path; the rename is what the user sees.
241235×
        self.statuses.retain(|s| s.path != old);
241335×
        self.statuses.push(PathStatus {
241435×
            path: new.to_string(),
241535×
            status: ChangeStatus::Renamed,
241635×
        });
241735×
        Ok(())
241835×
    }
2419
2420
    /// For a Git import: a node the commit keeps is in one place, the one
2421
    /// its tree names, so any other live placement it has in the base goes;
2422
    /// and a node the tree cannot show at all (an orphan) goes too. Such a
2423
    /// placement is out of sight, under a directory another line of history
2424
    /// removed, where no diff of the tree would ever reach it (oxygen#30).
242588×
    fn retire_stray_placements(&mut self) {
242688×
        let mut retired: HashSet<(ChangeHash, u32)> = HashSet::new();
242788×
        let mut placed: BTreeSet<NodeId> = BTreeSet::new();
242899×
        for op in &self.tree_ops {
242999×
            match op {
243019×
                TreeOp::Move { node, old, .. } => {
243119×
                    retired.insert((old.change, old.index));
243219×
                    placed.insert(*node);
243319×
                }
243421×
                TreeOp::RemoveNode { placement, .. } => {
243521×
                    retired.insert((placement.change, placement.index));
243621×
                }
243759×
                TreeOp::AddNode { .. } | TreeOp::SetMode { .. } => {}
2438
            }
2439
        }
2440
        // Nodes kept where they were: what the base's tree view shows and
2441
        // this change neither moves nor removes.
244288×
        let mut kept: HashMap<NodeId, (ChangeHash, u32)> = HashMap::new();
2443241×
        for e in self.base_snapshot.tree.entries.values() {
2444241×
            if !retired.contains(&e.placement) {
2445204×
                kept.insert(e.node, e.placement);
2446204×
            }
2447
        }
2448
        // Only a node with several live placements can have a stray one,
2449
        // and the tree view names each as a conflict.
245088×
        let multi: BTreeSet<NodeId> = self
245188×
            .base_snapshot
245288×
            .tree
245388×
            .conflicts
245488×
            .iter()
245588×
            .filter_map(|c| match c {
24561×
                crate::tree::TreeConflict::MultiPlacement { node, .. } => Some(*node),
24576×
                _ => None,
24587×
            })
245988×
            .collect();
246088×
        let mut extra = Vec::new();
2461
        // A node whose only placements are under a directory another line
2462
        // removed (an orphan) is nowhere the tree can show, and Git's tree
2463
        // has no such path: it goes.
246488×
        for c in &self.base_snapshot.tree.conflicts {
24657×
            let crate::tree::TreeConflict::Orphan { node, .. } = c else {
24666×
                continue;
2467
            };
24681×
            if kept.contains_key(node) || placed.contains(node) {
24690×
                continue;
24701×
            }
24711×
            for (k, _) in self.base.tree().live_placements(node) {
24721×
                if retired.insert(k) {
24731×
                    extra.push(TreeOp::RemoveNode {
24741×
                        node: *node,
24751×
                        placement: op_ref(k),
24761×
                    });
24771×
                }
2478
            }
2479
        }
248088×
        for node in placed
248188×
            .iter()
248288×
            .chain(multi.iter().filter(|n| kept.contains_key(*n)))
2483
        {
248419×
            for (k, _) in self.base.tree().live_placements(node) {
248518×
                if retired.contains(&k) || kept.get(node) == Some(&k) {
248617×
                    continue;
24871×
                }
24881×
                retired.insert(k);
24891×
                extra.push(TreeOp::RemoveNode {
24901×
                    node: *node,
24911×
                    placement: op_ref(k),
24921×
                });
2493
            }
2494
        }
249588×
        if !extra.is_empty() {
24962×
            self.resolves = true;
24972×
            self.tree_ops.extend(extra);
249886×
        }
249988×
    }
2500
2501
    /// Nodes the base shows as one with another (identical additions at one
2502
    /// path, spec §9.2) are retired by the change that first touches the
2503
    /// node shown: edited, moved, removed or given a mode alone, it would
2504
    /// differ from them and the name conflict would come back. Nothing
2505
    /// else changes for the user, so no status reports it.
25062188×
    fn retire_unified(&mut self) {
25072188×
        let unified = &self.base_snapshot.tree.unified;
25082188×
        if unified.is_empty() {
25092167×
            return;
251021×
        }
251121×
        let touched: HashSet<NodeId> = self
251221×
            .tree_ops
251321×
            .iter()
251421×
            .map(|o| o.node())
251522×
            .chain(self.edits.iter().map(|e| e.node()))
251621×
            .collect();
251721×
        let mut retired: HashSet<(ChangeHash, u32)> = HashSet::new();
251821×
        for op in &self.tree_ops {
251914×
            match op {
25203×
                TreeOp::Move { old, .. } => {
25213×
                    retired.insert((old.change, old.index));
25223×
                }
25233×
                TreeOp::RemoveNode { placement, .. } => {
25243×
                    retired.insert((placement.change, placement.index));
25253×
                }
25268×
                TreeOp::AddNode { .. } | TreeOp::SetMode { .. } => {}
2527
            }
2528
        }
252921×
        let mut extra = Vec::new();
253022×
        for (dup, shown) in unified {
253122×
            if !touched.contains(shown) {
25325×
                continue;
253317×
            }
253417×
            for (k, _) in self.base.tree().live_placements(dup) {
253517×
                if retired.insert(k) {
253617×
                    extra.push(TreeOp::RemoveNode {
253717×
                        node: *dup,
253817×
                        placement: op_ref(k),
253917×
                    });
254017×
                }
2541
            }
2542
        }
254321×
        self.tree_ops.extend(extra);
25442188×
    }
2545
2546
    /// The node's other live placements at the same place as `k`, the one
2547
    /// the tree shows: two lines of history that put a node back where it
2548
    /// was each leave a placement, and the tree shows them as one file. A
2549
    /// change that removes or moves it retires them together, or the copy
2550
    /// left behind outlives its directory (oxygen#88).
2551163×
    fn same_place(&self, node: &NodeId, k: (ChangeHash, u32)) -> Vec<(ChangeHash, u32)> {
2552163×
        let tree = self.base.tree();
2553163×
        let Some(shown) = tree.placement(&k) else {
25540×
            return Vec::new();
2555
        };
2556163×
        tree.live_placements(node)
2557163×
            .into_iter()
2558165×
            .filter(|(o, p)| *o != k && p.parent == shown.parent && p.name == shown.name)
2559163×
            .map(|(o, _)| o)
2560163×
            .collect()
2561163×
    }
2562
2563128×
    fn remove_path(&mut self, path: &str, expected: &crate::state::FileState) {
2564128×
        let entry = &self.base_snapshot.tree.entries[path];
2565128×
        let placement = entry.placement;
2566128×
        self.tree_ops.push(TreeOp::RemoveNode {
2567128×
            node: expected.node,
2568128×
            placement: op_ref(placement),
2569128×
        });
2570128×
        for k in self.same_place(&expected.node, placement) {
25711×
            self.tree_ops.push(TreeOp::RemoveNode {
25721×
                node: expected.node,
25731×
                placement: op_ref(k),
25741×
            });
25751×
        }
2576128×
        if path.contains(".oxy-conflict-") || expected.is_conflicted() {
25777×
            self.resolves = true;
2578121×
        }
2579128×
        self.statuses.push(PathStatus {
2580128×
            path: path.to_string(),
2581128×
            status: ChangeStatus::Removed,
2582128×
        });
2583128×
    }
2584
258512954×
    fn update_path(
258612954×
        &mut self,
258712954×
        repo: &Repo,
258812954×
        path: &str,
258912954×
        e: &FsEntry,
259012954×
        expected: &crate::state::FileState,
259112954×
    ) -> Result<()> {
259212954×
        if expected.kind != e.kind {
25931×
            self.remove_path(path, expected);
25941×
            self.statuses.pop();
25951×
            self.add_path(repo, path, e)?;
25961×
            self.statuses.pop();
25971×
            self.statuses.push(PathStatus {
25981×
                path: path.to_string(),
25991×
                status: ChangeStatus::Modified,
26001×
            });
26011×
            return Ok(());
260212953×
        }
260312953×
        let entry = &self.base_snapshot.tree.entries[path];
260412953×
        let node = expected.node;
260512953×
        let mode_atom = entry.mode_atom.map(op_ref);
260612953×
        if e.unchanged {
2607
            // Known equal to the base's unconflicted rendering (spec
2608
            // §12.3); only the executable bit can differ.
26094244×
            if e.exec != expected.mode.exec {
26103×
                if let Some(old) = mode_atom {
26113×
                    self.tree_ops.push(TreeOp::SetMode {
26123×
                        node,
26133×
                        old,
26143×
                        mode: Mode {
26153×
                            exec: e.exec,
26163×
                            opaque: false,
26173×
                        },
26183×
                    });
26193×
                    self.statuses.push(PathStatus {
26203×
                        path: path.to_string(),
26213×
                        status: ChangeStatus::ModeChanged,
26223×
                    });
26233×
                }
26244241×
            }
26254244×
            return Ok(());
26268709×
        }
26278709×
        let mut status: Option<ChangeStatus> = None;
26288709×
        let wants_opaque = self.opaque_for(path, e);
26298709×
        let nocompress = self.attrs.lookup(path).nocompress;
26308709×
        let disk_text = self.stored_text(path, &e.content);
26318709×
        match &expected.content {
26320×
            FileContent::Dir => {}
2633
            FileContent::Text {
26348477×
                bytes,
26358477×
                materialized,
2636
            } => {
26378477×
                if materialized.is_conflicted() {
263842×
                    if bytes == &*disk_text {
26396×
                        return Ok(());
264036×
                    }
264136×
                    let regions = self.base.conflict_regions(&node);
264236×
                    let plain: Vec<&[u8]> =
264381×
                        regions.plain.iter().map(|(_, l)| l.as_slice()).collect();
264436×
                    if has_own_conflict_markers(&e.content, bytes, &plain) {
26455×
                        self.statuses.push(PathStatus {
26465×
                            path: path.to_string(),
26475×
                            status: ChangeStatus::ConflictEdited,
26485×
                        });
26495×
                        return Ok(());
265031×
                    }
2651
                    // Resolution (spec §9.6): diff against the unconflicted lines
2652
                    // with each region as a gap, then retire every region atom.
2653
                    // Whatever the author kept from a region is re-inserted as
2654
                    // new atoms, which leaves the graph totally ordered.
265531×
                    let mut edits = text_edits(node, &regions.plain, &disk_text);
265631×
                    if !regions.region_atoms.is_empty() {
265731×
                        edits.insert(
265831×
                            0,
265931×
                            Edit::Delete {
266031×
                                node,
266131×
                                atoms: ranges(&regions.region_atoms),
266231×
                            },
266331×
                        );
266431×
                    }
266531×
                    self.edits.extend(edits);
266631×
                    self.contributors.extend(regions.contributors);
266731×
                    self.resolves = true;
266831×
                    if e.exec != expected.mode.exec {
26690×
                        if let Some(old) = mode_atom {
26700×
                            self.tree_ops.push(TreeOp::SetMode {
26710×
                                node,
26720×
                                old,
26730×
                                mode: Mode {
26740×
                                    exec: e.exec,
26750×
                                    opaque: false,
26760×
                                },
26770×
                            });
26780×
                        }
267931×
                    }
268031×
                    self.statuses.push(PathStatus {
268131×
                        path: path.to_string(),
268231×
                        status: ChangeStatus::Resolved,
268331×
                    });
268431×
                    return Ok(());
26858435×
                }
26868435×
                if wants_opaque {
2687
                    // Text → opaque (spec §7.5), by content or by attribute.
26882×
                    if let Some(old) = mode_atom {
26892×
                        self.tree_ops.push(TreeOp::SetMode {
26902×
                            node,
26912×
                            old,
26922×
                            mode: Mode {
26932×
                                exec: e.exec,
26942×
                                opaque: true,
26952×
                            },
26962×
                        });
26972×
                    }
26982×
                    let live: Vec<_> = repo_live_keys(self.base, &node);
26992×
                    if !live.is_empty() {
27002×
                        self.edits.push(Edit::Delete {
27012×
                            node,
27022×
                            atoms: ranges(&live),
27032×
                        });
27042×
                    }
27052×
                    let blob = self.blob_of(repo, path, e, nocompress)?;
27062×
                    self.edits.push(Edit::Replace {
27072×
                        node,
27082×
                        old: None,
27092×
                        new: Some(blob),
27102×
                    });
27112×
                    status = Some(ChangeStatus::Modified);
27128433×
                } else if bytes != &*disk_text {
2713827×
                    let mut laps = crate::timing::Laps::start();
2714
                    // The base's rendering holds its live atoms in order,
2715
                    // one per line (it is not conflicted here).
2716827×
                    let edits = match self.diffs.remove(path) {
271780×
                        Some(edits) => edits,
2718
                        None => {
2719747×
                            let keys = materialized.live_atoms();
2720747×
                            let lines = crate::diff::split_lines(bytes);
2721747×
                            if keys.len() == lines.len() {
2722747×
                                crate::diff::text_edits_of(node, &keys, &lines, &disk_text)
2723
                            } else {
27240×
                                text_edits(node, &self.base.live_lines(&node), &disk_text)
2725
                            }
2726
                        }
2727
                    };
2728827×
                    laps.lap("build: text diff");
2729827×
                    if !edits.is_empty() {
2730827×
                        self.edits.extend(edits);
2731827×
                        status = Some(ChangeStatus::Modified);
2732827×
                    }
27337606×
                }
27348435×
                let switched_to_opaque = wants_opaque;
27358435×
                if !switched_to_opaque && e.exec != expected.mode.exec {
27364×
                    if let Some(old) = mode_atom {
27374×
                        self.tree_ops.push(TreeOp::SetMode {
27384×
                            node,
27394×
                            old,
27404×
                            mode: Mode {
27414×
                                exec: e.exec,
27424×
                                opaque: false,
27434×
                            },
27444×
                        });
27454×
                        status.get_or_insert(ChangeStatus::ModeChanged);
27464×
                    }
27478431×
                }
2748
            }
2749232×
            FileContent::Opaque { blobs } => {
2750232×
                let new_ref = e.blob.unwrap_or_else(|| Repo::blob_ref(&e.content));
2751232×
                if e.kind == NodeKind::File && wants_opaque {
2752191×
                    // Unchanged or replaced, the file stays opaque: remember its blob.
2753191×
                    self.blobs.insert(path.to_string(), new_ref);
2754191×
                }
2755232×
                if blobs.len() > 1 && self.resolve.contains(path) && e.kind == expected.kind {
2756
                    // Settle the replace conflict (spec §9.3): replace every
2757
                    // live candidate with the chosen blob, depending on each
2758
                    // change that made one live, so all are superseded.
27592×
                    let chosen = self.blob_of(repo, path, e, nocompress)?;
27604×
                    for b in blobs {
27614×
                        self.edits.push(Edit::Replace {
27624×
                            node,
27634×
                            old: Some(*b),
27644×
                            new: Some(chosen),
27654×
                        });
27664×
                    }
27672×
                    self.contributors
27682×
                        .extend(self.base.blob_contributors(&node, blobs));
27692×
                    self.resolves = true;
27702×
                    self.statuses.push(PathStatus {
27712×
                        path: path.to_string(),
27722×
                        status: ChangeStatus::Resolved,
27732×
                    });
27742×
                    return Ok(());
2775230×
                }
2776230×
                if blobs.len() > 1 {
27772×
                    if !blobs.contains(&new_ref) {
27780×
                        self.statuses.push(PathStatus {
27790×
                            path: path.to_string(),
27800×
                            status: ChangeStatus::ConflictEdited,
27810×
                        });
27822×
                    }
27832×
                    return Ok(());
2784228×
                }
2785228×
                let current = blobs.first().copied();
2786228×
                if current != Some(new_ref) {
278734×
                    if e.kind == NodeKind::File && !wants_opaque {
2788
                        // Opaque → text (spec §7.5).
27892×
                        if let Some(old) = mode_atom {
27902×
                            self.tree_ops.push(TreeOp::SetMode {
27912×
                                node,
27922×
                                old,
27932×
                                mode: Mode {
27942×
                                    exec: e.exec,
27952×
                                    opaque: false,
27962×
                                },
27972×
                            });
27982×
                        }
27992×
                        self.edits.push(Edit::Replace {
28002×
                            node,
28012×
                            old: current,
28022×
                            new: None,
28032×
                        });
28042×
                        if !e.content.is_empty() {
28052×
                            self.edits.push(Edit::Insert {
28062×
                                node,
28072×
                                after: crate::objects::AtomRef::Start,
28082×
                                before: crate::objects::AtomRef::End,
28092×
                                lines: crate::lines::Lines::split(&e.content),
28102×
                            });
28112×
                        }
2812
                    } else {
281332×
                        let blob = self.blob_of(repo, path, e, nocompress)?;
281432×
                        self.edits.push(Edit::Replace {
281532×
                            node,
281632×
                            old: current,
281732×
                            new: Some(blob),
281832×
                        });
2819
                        // New contents and a new executable bit at once: the
2820
                        // bit was dropped (VS Code's inno_updater.exe,
2821
                        // 2018-02-28, lost +x for 49 commits; oxygen#87).
282232×
                        if e.kind == NodeKind::File && e.exec != expected.mode.exec {
28232×
                            if let Some(old) = mode_atom {
28242×
                                self.tree_ops.push(TreeOp::SetMode {
28252×
                                    node,
28262×
                                    old,
28272×
                                    mode: Mode {
28282×
                                        exec: e.exec,
28292×
                                        opaque: true,
28302×
                                    },
28312×
                                });
28322×
                            }
283330×
                        }
2834
                    }
283534×
                    status = Some(ChangeStatus::Modified);
2836194×
                } else if e.kind == NodeKind::File && e.exec != expected.mode.exec {
28370×
                    if let Some(old) = mode_atom {
28380×
                        self.tree_ops.push(TreeOp::SetMode {
28390×
                            node,
28400×
                            old,
28410×
                            mode: Mode {
28420×
                                exec: e.exec,
28430×
                                opaque: true,
28440×
                            },
28450×
                        });
28460×
                        status = Some(ChangeStatus::ModeChanged);
28470×
                    }
2848194×
                }
2849
            }
2850
        }
28518663×
        if let Some(s) = status {
2852867×
            self.statuses.push(PathStatus {
2853867×
                path: path.to_string(),
2854867×
                status: s,
2855867×
            });
28567796×
        }
28578663×
        Ok(())
285812954×
    }
2859
}
2860
28612×
fn repo_live_keys(base: &State, node: &NodeId) -> Vec<crate::graph::AtomKey> {
28622×
    base.live_lines(node).into_iter().map(|(k, _)| k).collect()
28632×
}
2864
2865
/// The changes a change's scope references (spec §8.1): introducers of every
2866
/// atom, placement, and mode it touches, and of every node it operates on.
28672267×
pub fn referenced_changes(change: &Change, base: &State) -> BTreeSet<ChangeHash> {
28682267×
    let mut out = BTreeSet::new();
28692267×
    let opref = |r: &OpRef, out: &mut BTreeSet<ChangeHash>| {
2870199×
        if !r.change.is_zero() {
2871199×
            out.insert(r.change);
2872199×
        }
2873199×
    };
28742267×
    let mut nodes: Vec<NodeId> = Vec::new();
28756697×
    for op in &change.tree_ops {
28766697×
        match op {
28776498×
            TreeOp::AddNode { parent, .. } => nodes.push(*parent),
2878150×
            TreeOp::RemoveNode { node, placement } => {
2879150×
                nodes.push(*node);
2880150×
                opref(placement, &mut out);
2881150×
            }
2882
            TreeOp::Move {
288337×
                node, old, parent, ..
288437×
            } => {
288537×
                nodes.push(*node);
288637×
                nodes.push(*parent);
288737×
                opref(old, &mut out);
288837×
            }
288912×
            TreeOp::SetMode { node, old, .. } => {
289012×
                nodes.push(*node);
289112×
                opref(old, &mut out);
289212×
            }
2893
        }
2894
    }
28958330×
    for e in &change.edits {
28968330×
        nodes.push(e.node());
2897139×
        match e {
28987632×
            Edit::Insert { after, before, .. } => {
289915264×
                for r in [after, before] {
290015264×
                    if let crate::objects::AtomRef::Atom { change, .. } = r {
29012296×
                        if !change.is_zero() {
29022293×
                            out.insert(*change);
29032293×
                        }
290412968×
                    }
2905
                }
2906
            }
2907559×
            Edit::Delete { atoms, .. } => {
2908
                // Deleting an atom also depends on whoever inserted the live
2909
                // atoms right after it: the author saw those insertions, and
2910
                // without the dependency spec §9.1 would call the deletion
2911
                // concurrent with them (a delete/insert conflict).
2912559×
                let graph = base.file(&e.node());
29131127×
                for r in atoms {
29141127×
                    if !r.change.is_zero() {
29151126×
                        out.insert(r.change);
29161126×
                    }
29171127×
                    if let Some(g) = graph {
29181168×
                        for i in r.from..r.to {
29191168×
                            out.extend(
29201168×
                                g.live_successor_changes(&(r.change, i))
29211168×
                                    .into_iter()
29221168×
                                    .filter(|c| !c.is_zero()),
2923
                            );
2924
                        }
29250×
                    }
2926
                }
2927
            }
2928
            // Replacing a blob depends on the change that made it current,
2929
            // as deleting a line depends on the line's introducer.
2930
            Edit::Replace {
293139×
                node,
293239×
                old: Some(old),
2933
                ..
2934
            } => {
293539×
                out.extend(
293639×
                    base.live_replaces(node)
293739×
                        .into_iter()
293846×
                        .filter(|(c, b)| b == old && !c.is_zero())
293939×
                        .map(|(c, _)| c),
2940
                );
2941
            }
2942100×
            Edit::Replace { .. } => {}
2943
        }
2944
    }
294515064×
    for n in nodes {
294615064×
        if let Some(h) = base.tree().introducer(&n) {
29472306×
            out.insert(h);
294812758×
        }
2949
    }
29502267×
    out
29512267×
}
2952
2953
/// Paths of the nodes a change adds on top of `base_snapshot`.
29541422×
pub fn added_node_paths(
29551422×
    change: &Change,
29561422×
    base_snapshot: &Snapshot,
29571422×
) -> HashMap<String, (NodeId, NodeKind)> {
29581422×
    let by_node = base_snapshot.tree.by_node();
29591422×
    let mut new_names: HashMap<NodeId, (NodeId, String, NodeKind)> = HashMap::new();
29601422×
    for op in &change.tree_ops {
2961
        if let TreeOp::AddNode {
296292×
            node,
296392×
            parent,
296492×
            name,
296592×
            kind,
2966
            ..
2967124×
        } = op
296892×
        {
296992×
            new_names.insert(*node, (*parent, name.clone(), *kind));
297092×
        }
2971
    }
29721422×
    let mut out = HashMap::new();
29731422×
    for (node, (_, _, kind)) in &new_names {
297492×
        if let Some(path) = path_of_node(node, &by_node, &new_names) {
297592×
            out.insert(path, (*node, *kind));
297692×
        }
2977
    }
29781422×
    out
29791422×
}
2980
2981
/// Whether `op` retires a node `base_snapshot` shows as one with another
2982
/// (spec §9.2): part of touching that node, never a removal the user made.
298337×
fn is_unified_retirement(op: &TreeOp, base_snapshot: &Snapshot) -> bool {
29848×
    matches!(op, TreeOp::RemoveNode { node, .. } if base_snapshot.tree.unified.contains_key(node))
298537×
}
2986
2987227×
fn path_of_node(
2988227×
    n: &NodeId,
2989227×
    by_node: &HashMap<NodeId, &crate::tree::TreeEntry>,
2990227×
    new_names: &HashMap<NodeId, (NodeId, String, NodeKind)>,
2991227×
) -> Option<String> {
2992227×
    if let Some(e) = by_node.get(n) {
299369×
        return Some(e.path.clone());
2994158×
    }
2995158×
    let mut parts = Vec::new();
2996158×
    let mut cur = *n;
2997
    loop {
2998312×
        if cur.is_root() {
2999141×
            break;
3000171×
        }
3001171×
        if let Some(e) = by_node.get(&cur) {
30020×
            if !e.path.is_empty() {
30030×
                parts.push(e.path.clone());
30040×
            }
30050×
            break;
3006171×
        }
3007171×
        let (parent, name, _) = new_names.get(&cur)?;
3008154×
        parts.push(name.clone());
3009154×
        cur = *parent;
3010
    }
3011141×
    parts.reverse();
3012141×
    Some(parts.join("/"))
3013227×
}
3014
3015
/// Render a change's operations with line content, using `base` for deleted lines.
301633×
pub fn render_change(change: &Change, base: &State, base_snapshot: &Snapshot) -> String {
301733×
    let by_node = base_snapshot.tree.by_node();
301833×
    let mut new_names: HashMap<NodeId, (NodeId, String, NodeKind)> = HashMap::new();
301933×
    for op in &change.tree_ops {
3020
        if let TreeOp::AddNode {
302116×
            node,
302216×
            parent,
302316×
            name,
302416×
            kind,
3025
            ..
302624×
        } = op
302716×
        {
302816×
            new_names.insert(*node, (*parent, name.clone(), *kind));
302916×
        }
3030
    }
303173×
    let path_of = |n: &NodeId| -> String {
303273×
        path_of_node(n, &by_node, &new_names).unwrap_or_else(|| format!("<node {}>", n.short(8)))
303373×
    };
3034
303533×
    let mut out = String::new();
303633×
    for op in change
303733×
        .tree_ops
303833×
        .iter()
303933×
        .filter(|o| !is_unified_retirement(o, base_snapshot))
3040
    {
304123×
        match op {
3042
            TreeOp::AddNode {
304316×
                node, kind, mode, ..
3044
            } => {
304516×
                out.push_str(&format!(
3046
                    "A {} ({:?}{}{})\n",
304716×
                    path_of(node),
3048
                    kind,
304916×
                    if mode.exec { ", exec" } else { "" },
305016×
                    if mode.opaque { ", opaque" } else { "" }
3051
                ));
3052
            }
30535×
            TreeOp::RemoveNode { node, .. } => out.push_str(&format!("D {}\n", path_of(node))),
3054
            TreeOp::Move {
30552×
                node, parent, name, ..
3056
            } => {
30572×
                let to = if parent.is_root() {
30580×
                    name.clone()
3059
                } else {
30602×
                    format!("{}/{name}", path_of(parent))
3061
                };
30622×
                out.push_str(&format!("R {} -> {to}\n", path_of(node)))
3063
            }
30640×
            TreeOp::SetMode { node, mode, .. } => {
30650×
                out.push_str(&format!(
30660×
                    "M {} mode: exec={} opaque={}\n",
30670×
                    path_of(node),
30680×
                    mode.exec,
30690×
                    mode.opaque
30700×
                ));
30710×
            }
3072
        }
3073
    }
3074
    // Every other file the change edits is modified: the summary names
3075
    // every path it touches, not only those with a tree operation.
307633×
    let with_op: HashSet<NodeId> = change.tree_ops.iter().map(|o| o.node()).collect();
307733×
    let mut listed: HashSet<NodeId> = HashSet::new();
307836×
    for e in &change.edits {
307936×
        let n = e.node();
308036×
        if !with_op.contains(&n) && listed.insert(n) {
308121×
            out.push_str(&format!("M {}\n", path_of(&n)));
308221×
        }
3083
    }
308433×
    let mut last_node: Option<NodeId> = None;
308536×
    for e in &change.edits {
308636×
        let n = e.node();
308736×
        if last_node != Some(n) {
308827×
            out.push_str(&format!("--- {}\n", path_of(&n)));
308927×
            last_node = Some(n);
309027×
        }
309136×
        match e {
309227×
            Edit::Insert { lines, .. } => {
309332×
                for l in lines.iter() {
309432×
                    out.push('+');
309532×
                    out.push_str(&String::from_utf8_lossy(l));
309632×
                    if !l.ends_with(b"\n") {
30970×
                        out.push('\n');
309832×
                    }
3099
                }
3100
            }
31018×
            Edit::Delete { atoms, .. } => {
31028×
                for r in atoms {
31038×
                    for i in r.from..r.to {
31048×
                        let content = base
31058×
                            .file(&n)
31068×
                            .and_then(|g| g.content(&(r.change, i)))
31078×
                            .unwrap_or(b"<unknown>\n");
31088×
                        out.push('-');
31098×
                        out.push_str(&String::from_utf8_lossy(content));
31108×
                        if !content.ends_with(b"\n") {
31110×
                            out.push('\n');
31128×
                        }
3113
                    }
3114
                }
3115
            }
31161×
            Edit::Replace { old, new, .. } => {
31171×
                out.push_str(&format!(
3118
                    "  opaque content {} -> {}\n",
31191×
                    old.map(|o| o.short(12)).unwrap_or_else(|| "none".into()),
31201×
                    new.map(|o| o.short(12)).unwrap_or_else(|| "none".into())
3121
                ));
3122
            }
3123
        }
3124
    }
312533×
    out
312633×
}
3127
3128
/// Pair removed files with added files of the same kind whose contents are
3129
/// at least `RENAME_THRESHOLD` percent alike, best matches first. Beyond
3130
/// `RENAME_LIMIT` candidate pairs only identical contents are paired.
3131
const RENAME_THRESHOLD: u32 = 50;
3132
const RENAME_LIMIT: usize = 10_000;
3133
3134
/// How a change is built beyond its entries: for a Git import, the seed
3135
/// its new nodes' identifiers derive from; and, when it is built from part
3136
/// of the tree, whether the new tree has anything under a directory.
3137
#[derive(Default)]
3138
struct Scope<'a> {
3139
    seed: Option<[u8; 32]>,
3140
    dir_needed: Option<&'a dyn Fn(&str) -> bool>,
3141
}
3142
31432188×
fn detect_renames(
31442188×
    base_snapshot: &Snapshot,
31452188×
    fs_entries: &BTreeMap<String, FsEntry>,
31462188×
    in_scope: impl Fn(&str) -> bool,
31472188×
) -> Vec<(String, String)> {
31482188×
    let removed: Vec<(&String, &crate::state::FileState)> = base_snapshot
31492188×
        .files
31502188×
        .iter()
315113503×
        .filter(|(p, f)| {
315213503×
            f.kind != NodeKind::Dir
315313069×
                && !fs_entries.contains_key(*p)
3154150×
                && in_scope(p)
3155140×
                && !f.is_conflicted()
315613503×
        })
31572188×
        .collect();
31582188×
    let added: Vec<(&String, &FsEntry)> = fs_entries
31592188×
        .iter()
316019081×
        .filter(|(p, e)| e.kind != NodeKind::Dir && !base_snapshot.files.contains_key(*p))
31612188×
        .collect();
31622188×
    if removed.is_empty() || added.is_empty() {
31632129×
        return vec![];
316459×
    }
316559×
    let exact_only = removed.len() * added.len() > RENAME_LIMIT;
316673×
    let old_content = |f: &crate::state::FileState| -> Option<Vec<u8>> {
316773×
        match &f.content {
316869×
            FileContent::Text { bytes, .. } => Some(bytes.clone()),
31694×
            _ => None,
3170
        }
317173×
    };
317259×
    let mut scored: Vec<(u32, usize, usize)> = Vec::new();
317373×
    for (ri, (_, f)) in removed.iter().enumerate() {
317473×
        let old = old_content(f);
317573×
        let old_blob = match &f.content {
31764×
            FileContent::Opaque { blobs } if blobs.len() == 1 => Some(blobs[0]),
317769×
            _ => None,
3178
        };
317992×
        for (ai, (_, e)) in added.iter().enumerate() {
318092×
            if e.kind != f.kind {
31810×
                continue;
318292×
            }
318392×
            let score = match (&old, old_blob) {
318482×
                (Some(o), _) => {
318582×
                    if exact_only {
31860×
                        if *o == *e.content {
31870×
                            100
3188
                        } else {
31890×
                            0
3190
                        }
3191
                    } else {
319282×
                        similarity(o, &e.content)
3193
                    }
3194
                }
319510×
                (None, Some(b)) if e.blob.unwrap_or_else(|| Repo::blob_ref(&e.content)) == b => 100,
31967×
                _ => 0,
3197
            };
319892×
            if score >= RENAME_THRESHOLD {
319941×
                scored.push((score, ri, ai));
320051×
            }
3201
        }
3202
    }
320359×
    scored.sort_by(|a, b| {
32049×
        b.0.cmp(&a.0)
32059×
            .then(removed[a.1].0.cmp(removed[b.1].0))
32069×
            .then(added[a.2].0.cmp(added[b.2].0))
32079×
    });
320859×
    let mut used_r = vec![false; removed.len()];
320959×
    let mut used_a = vec![false; added.len()];
321059×
    let mut out = Vec::new();
321159×
    for (_, ri, ai) in scored {
321241×
        if used_r[ri] || used_a[ai] {
32136×
            continue;
321435×
        }
321535×
        used_r[ri] = true;
321635×
        used_a[ai] = true;
321735×
        out.push((removed[ri].0.clone(), added[ai].0.clone()));
3218
    }
321959×
    out
32202188×
}
3221
3222
/// Percentage of the larger file's bytes found in lines the two share
3223
/// (multiset intersection of lines), like Git's similarity index.
322486×
pub fn similarity(a: &[u8], b: &[u8]) -> u32 {
322586×
    if a == b {
322625×
        return 100;
322761×
    }
322861×
    if a.is_empty() || b.is_empty() {
32292×
        return 0;
323059×
    }
323159×
    let mut counts: HashMap<&[u8], usize> = HashMap::new();
3232114×
    for l in split_lines(a) {
3233114×
        *counts.entry(l).or_default() += 1;
3234114×
    }
323559×
    let mut shared = 0usize;
3236111×
    for l in split_lines(b) {
3237111×
        if let Some(n) = counts.get_mut(l) {
323842×
            if *n > 0 {
323942×
                *n -= 1;
324042×
                shared += l.len();
324142×
            }
324269×
        }
3243
    }
324459×
    (shared * 100 / a.len().max(b.len())) as u32
324586×
}
3246
3247
#[cfg(test)]
3248
mod join_tests {
3249
    use super::*;
3250
3251
    #[test]
32521×
    fn missing_from_finds_what_the_other_lacks() {
32531×
        let a: BTreeMap<String, u8> = [("a", 1), ("b", 2), ("c/d", 3), ("e", 4)]
32541×
            .into_iter()
32554×
            .map(|(k, v)| (k.to_string(), v))
32561×
            .collect();
32571×
        let b: BTreeMap<String, ()> = [("0", ()), ("b", ()), ("c", ()), ("e", ())]
32581×
            .into_iter()
32594×
            .map(|(k, v)| (k.to_string(), v))
32601×
            .collect();
32611×
        let got: Vec<&str> = missing_from(&a, &b)
32621×
            .iter()
32632×
            .map(|(k, _)| k.as_str())
32641×
            .collect();
32651×
        assert_eq!(got, vec!["a", "c/d"]);
32661×
    }
3267
3268
    #[test]
32691×
    fn join_pairs_every_key_in_order() {
32701×
        let a: BTreeMap<String, u8> = [("a", 1), ("b/c", 2), ("d", 3)]
32711×
            .into_iter()
32723×
            .map(|(k, v)| (k.to_string(), v))
32731×
            .collect();
32741×
        let b: BTreeMap<String, char> = [("b", 'x'), ("b/c", 'y'), ("e", 'z')]
32751×
            .into_iter()
32763×
            .map(|(k, v)| (k.to_string(), v))
32771×
            .collect();
32781×
        let got: Vec<(String, Option<u8>, Option<char>)> = join(&a, &b)
32795×
            .map(|(k, x, y)| (k.clone(), x.copied(), y.copied()))
32801×
            .collect();
32811×
        let want = vec![
32821×
            ("a".to_string(), Some(1), None),
32831×
            ("b".to_string(), None, Some('x')),
32841×
            ("b/c".to_string(), Some(2), Some('y')),
32851×
            ("d".to_string(), Some(3), None),
32861×
            ("e".to_string(), None, Some('z')),
3287
        ];
32881×
        assert_eq!(got, want);
32891×
    }
3290
}