OXYGENHUB

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

2193 of 2424 lines run, 282 of 371 functions · run #268 on main · run missed

1
//! Working-copy snapshots, commits, and the change builder (spec §12.3).
2
3
use super::*;
4
use crate::objects::AtomRef;
5
6
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
7
pub enum ChangeStatus {
8
    Added,
9
    Modified,
10
    Removed,
11
    /// Moved from another path (detected by similarity, tracked as a placement change).
12
    Renamed,
13
    ModeChanged,
14
    /// The file is conflicted in the base state and still contains conflict markers.
15
    ConflictEdited,
16
    /// The file was conflicted in the base state and the working copy resolves it.
17
    Resolved,
18
}
19
20
/// Lines that mark a conflict region in a materialized file (spec §9.5).
2128×
pub fn has_conflict_markers(content: &[u8]) -> bool {
2278×
    split_lines(content).iter().any(|l| {
2378×
        l.starts_with(b"<<<<<<< oxy conflict")
2473×
            || l.starts_with(b"======= oxy conflict")
2573×
            || l.starts_with(b">>>>>>> oxy conflict")
2678×
    })
2728×
}
28
29
#[derive(Clone, Debug, PartialEq, Eq)]
30
pub struct PathStatus {
31
    pub path: String,
32
    pub status: ChangeStatus,
33
}
34
35
/// Operations of a change built from the working directory against a base.
36
pub(crate) struct BuiltChange {
37
    pub tree_ops: Vec<TreeOp>,
38
    pub edits: Vec<Edit>,
39
    pub contributors: Vec<ChangeHash>,
40
    pub resolves: bool,
41
    pub statuses: Vec<PathStatus>,
42
    /// The stored blob of every opaque path, for the manifest's stat cache.
43
    pub blobs: HashMap<String, ObjectRef>,
44
}
45
46
/// Result of snapshotting the working copy.
47
pub struct SnapshotResult {
48
    /// The working-copy change's hash; for a commit's own snapshot, which
49
    /// does not encode it, the hash it had before.
50
    pub wc_hash: ChangeHash,
51
    pub wc: Change,
52
    /// The base state (closure of the working-copy change's dependencies).
53
    pub base: State,
54
    pub base_snapshot: Snapshot,
55
    pub statuses: Vec<PathStatus>,
56
    /// Whether the snapshot rewrote the working-copy change.
57
    pub changed: bool,
58
    /// Whether the working copy resolves conflicts of its base (spec §9.6).
59
    pub resolves: bool,
60
    /// Changes that contributed to the conflicts being resolved.
61
    pub contributors: Vec<ChangeHash>,
62
    /// The `.oxyattributes` in force on disk, from the files the walk read.
63
    pub(crate) attributes: crate::attributes::Attributes,
64
    /// Folders holding a repository of their own (`.git` or `.oxy`) that
65
    /// are not subrepos, so nothing in them is tracked (oxygen#43).
66
    pub untracked_nested: Vec<String>,
67
    /// A commit's snapshot leaves the manifest to the commit, which writes
68
    /// it once with the new base's graph keys.
69
    pub(crate) manifest: Option<PendingManifest>,
70
}
71
72
/// The manifest a commit's snapshot would have written, as of the moment
73
/// it would have written it (that moment is the racy-window stamp).
74
pub(crate) struct PendingManifest {
75
    entries: BTreeMap<String, FsEntry>,
76
    blobs: HashMap<String, ObjectRef>,
77
    dirs: Option<super::WalkedDirs>,
78
    written: u128,
79
}
80
8122463×
pub fn is_binary(content: &[u8]) -> bool {
8222463×
    content[..content.len().min(BINARY_SNIFF)].contains(&0)
8322463×
}
84
85
impl Repo {
86
    /// Diff the files on disk against `base` and build the operations of a
87
    /// change from `base` to the working directory. `reuse` maps paths to the
88
    /// NodeIds an earlier version of the same change assigned to new paths.
892×
    pub(crate) fn build_against(
902×
        &self,
912×
        base: &State,
922×
        base_snapshot: &Snapshot,
932×
        reuse: HashMap<String, (NodeId, NodeKind)>,
942×
    ) -> Result<BuiltChange> {
952×
        let mut fs_entries =
962×
            self.walk_working_copy_with(None, &Self::tracked_kinds(base_snapshot), None)?;
972×
        self.platform_normalize(&mut fs_entries, base_snapshot);
982×
        self.build_from_entries(base, base_snapshot, reuse, &fs_entries)
992×
    }
100
101
    /// Read the working copy as the platform left it (spec §7.7): without
102
    /// executable bits a file keeps the bit it has in the base, and without
103
    /// symbolic links a plain file where the base has a symlink is that
104
    /// symlink, written out as its target, not a new file.
1051213×
    fn platform_normalize(&self, entries: &mut BTreeMap<String, FsEntry>, base: &Snapshot) {
1061213×
        let p = self.platform;
1071213×
        if p.exec_bits && p.symlinks {
1081211×
            return;
1092×
        }
1104×
        for (path, e) in entries.iter_mut() {
1114×
            let Some(f) = base.files.get(path) else {
1120×
                continue;
113
            };
1144×
            if !p.symlinks && f.kind == NodeKind::Symlink && e.kind == NodeKind::File {
1152×
                e.kind = NodeKind::Symlink;
1162×
                e.exec = false;
1172×
            }
1184×
            if !p.exec_bits && f.kind == NodeKind::File && e.kind == NodeKind::File {
1192×
                e.exec = f.mode.exec;
1202×
            }
121
        }
1221213×
    }
123
124
    /// Like `build_against`, for files given in memory (imports).
125950×
    pub(crate) fn build_from_entries(
126950×
        &self,
127950×
        base: &State,
128950×
        base_snapshot: &Snapshot,
129950×
        reuse: HashMap<String, (NodeId, NodeKind)>,
130950×
        fs_entries: &BTreeMap<String, FsEntry>,
131950×
    ) -> Result<BuiltChange> {
132950×
        self.build_from_entries_resolving(base, base_snapshot, reuse, fs_entries, &HashSet::new())
133950×
    }
134
135
    /// Like `build_from_entries`, settling the replace conflicts of the
136
    /// opaque files in `resolve` to their content (spec §9.3, §9.6): a
137
    /// caller that knows the user chose it, such as the hub's resolver. A
138
    /// snapshot never settles one on its own, since a checkout writes one
139
    /// candidate at the path.
140964×
    pub(crate) fn build_from_entries_resolving(
141964×
        &self,
142964×
        base: &State,
143964×
        base_snapshot: &Snapshot,
144964×
        reuse: HashMap<String, (NodeId, NodeKind)>,
145964×
        fs_entries: &BTreeMap<String, FsEntry>,
146964×
        resolve: &HashSet<String>,
147964×
    ) -> Result<BuiltChange> {
148964×
        self.build_from_entries_with(
149964×
            base,
150964×
            base_snapshot,
151964×
            reuse,
152964×
            fs_entries,
153964×
            resolve,
154964×
            Scope::default(),
155
        )
156964×
    }
157
158
    /// `build_from_entries` whose new nodes take identifiers derived from
159
    /// `seed` and their paths instead of random ones, so the same input
160
    /// always builds the same change (a Git import, spec §23).
161
    ///
162
    /// With `dir_needed`, the snapshot and entries hold only the paths the
163
    /// import touches (and the directories a removal may leave empty); a
164
    /// directory stays while `dir_needed` says the new tree has something
165
    /// under it.
16688×
    pub(crate) fn build_from_entries_seeded(
16788×
        &self,
16888×
        base: &State,
16988×
        base_snapshot: &Snapshot,
17088×
        fs_entries: &BTreeMap<String, FsEntry>,
17188×
        seed: [u8; 32],
17288×
        dir_needed: Option<&dyn Fn(&str) -> bool>,
17388×
    ) -> Result<BuiltChange> {
17488×
        self.build_from_entries_with(
17588×
            base,
17688×
            base_snapshot,
17788×
            HashMap::new(),
17888×
            fs_entries,
17988×
            &HashSet::new(),
18088×
            Scope {
18188×
                seed: Some(seed),
18288×
                dir_needed,
18388×
            },
184
        )
18588×
    }
186
187
    /// `build_from_entries` for a snapshot most of whose files are known
188
    /// unchanged (oxygen#41): only the paths that may differ are built
189
    /// (files read rather than known unchanged, base files gone from disk,
190
    /// and the directories those may leave empty), against a snapshot of
191
    /// just those, so a large tree with a few edits costs what they touch.
192804×
    fn build_changed_only(
193804×
        &self,
194804×
        base: &State,
195804×
        base_snapshot: &Snapshot,
196804×
        reuse: HashMap<String, (NodeId, NodeKind)>,
197804×
        fs_entries: &BTreeMap<String, FsEntry>,
198804×
    ) -> Result<BuiltChange> {
199804×
        let pick = crate::timing::phase("snapshot:   of which picking the changed");
200
        // A file known unchanged may still have changed mode: that alters
201
        // neither its size nor its time.
202804×
        let changed: BTreeMap<String, FsEntry> = join(fs_entries, &base_snapshot.files)
20310951×
            .filter_map(|(p, e, f)| {
20410951×
                let e = e?;
20510826×
                (!e.unchanged || f.is_none_or(|f| f.kind != e.kind || f.mode.exec != e.exec))
20610826×
                    .then(|| (p.clone(), e.clone()))
20710951×
            })
208804×
            .collect();
209804×
        let mut files: BTreeMap<String, crate::state::FileState> = BTreeMap::new();
2106594×
        for p in changed.keys() {
2116594×
            if let Some(f) = base_snapshot.files.get(p) {
2123632×
                files.insert(p.clone(), f.clone());
2133632×
            }
214
        }
215
        // Paths the base has and the disk does not.
216804×
        let gone = join(&base_snapshot.files, fs_entries)
21710951×
            .filter_map(|(p, f, e)| (e.is_none()).then_some((p, f?)));
218804×
        for (p, f) in gone {
219125×
            if f.kind == NodeKind::Dir {
22096×
                continue;
22129×
            }
22229×
            files.insert(p.clone(), f.clone());
22329×
            let mut end = p.len();
22434×
            while let Some(i) = p[..end].rfind('/') {
2255×
                let dir = &p[..i];
2265×
                if files.contains_key(dir) {
2270×
                    break;
2285×
                }
2295×
                if let Some(d) = base_snapshot.files.get(dir) {
2305×
                    files.insert(dir.to_string(), d.clone());
2315×
                }
2325×
                end = i;
233
            }
234
        }
235804×
        let part = Snapshot {
236804×
            tree: base_snapshot.tree.clone(),
237804×
            files,
238804×
            unrendered: BTreeSet::new(),
239804×
        };
240804×
        drop(pick);
241804×
        let _build = crate::timing::phase("snapshot:   of which building the change");
242
        // Whether anything on disk is under `dir`.
243804×
        let dir_needed = |dir: &str| {
2445×
            let prefix = format!("{dir}/");
2455×
            fs_entries
2465×
                .range(prefix.clone()..)
2475×
                .next()
2485×
                .is_some_and(|(k, _)| k.starts_with(&prefix))
2495×
        };
250804×
        self.build_from_entries_with(
251804×
            base,
252804×
            &part,
253804×
            reuse,
254804×
            &changed,
255804×
            &HashSet::new(),
256804×
            Scope {
257804×
                seed: None,
258804×
                dir_needed: Some(&dir_needed),
259804×
            },
260
        )
261804×
    }
262
2631856×
    fn build_from_entries_with(
2641856×
        &self,
2651856×
        base: &State,
2661856×
        base_snapshot: &Snapshot,
2671856×
        reuse: HashMap<String, (NodeId, NodeKind)>,
2681856×
        fs_entries: &BTreeMap<String, FsEntry>,
2691856×
        resolve: &HashSet<String>,
2701856×
        scope: Scope,
2711856×
    ) -> Result<BuiltChange> {
2721856×
        let Scope { seed, dir_needed } = scope;
2731856×
        let mut laps = crate::timing::Laps::start();
274
        // Attributes come from the files being committed, so a new
275
        // `.oxyattributes` applies to the same change that adds it.
2761856×
        let attrs = crate::attributes::Attributes::from_files(
2771856×
            fs_entries
2781856×
                .iter()
27918508×
                .filter(|(p, _)| p.as_str() == ".oxyattributes" || p.ends_with("/.oxyattributes"))
2801856×
                .map(|(p, e)| (p.as_str(), e.content.as_slice())),
281
        );
2821856×
        let mut b = ChangeBuilder::new(base, base_snapshot, reuse).with_attributes(attrs);
2831856×
        b.resolve = resolve.clone();
2841856×
        b.node_seed = seed;
2851856×
        laps.lap("build: builder");
286
        // Rename detection (spec §7.1, §23): a removed file and an added file
287
        // of the same kind whose contents are at least half alike become one
288
        // move of the same node, so identity survives across the rename.
2891856×
        let renames = detect_renames(base_snapshot, fs_entries, |p| self.in_scope(p));
2901856×
        let renamed_from: HashMap<&str, &str> = renames
2911856×
            .iter()
2921856×
            .map(|(old, new)| (new.as_str(), old.as_str()))
2931856×
            .collect();
2941856×
        let renamed_to: HashMap<&str, &str> = renames
2951856×
            .iter()
2961856×
            .map(|(old, new)| (old.as_str(), new.as_str()))
2971856×
            .collect();
2981856×
        laps.lap("build: renames");
2991856×
        b.diff_in_parallel(fs_entries);
3001856×
        laps.lap("build: diffs");
30118508×
        for (path, fs_entry) in fs_entries {
30218508×
            match base_snapshot.files.get(path) {
3035965×
                None => match renamed_from.get(path.as_str()) {
30432×
                    Some(old) => {
30532×
                        b.move_path(self, old, path, fs_entry, &base_snapshot.files[*old])?
306
                    }
3075933×
                    None => b.add_path(self, path, fs_entry)?,
308
                },
30912543×
                Some(expected) => b.update_path(self, path, fs_entry, expected)?,
310
            }
311
        }
3121856×
        laps.lap("build: paths");
313
        // A directory stays while anything under it exists or is out of
314
        // scope: the directories above each such path, gathered once.
3151856×
        let mut needed_dirs: HashSet<&str> = HashSet::new();
31618521×
        fn parents_of<'a>(p: &'a str, set: &mut HashSet<&'a str>) {
31718521×
            let mut end = p.len();
31819161×
            while let Some(i) = p[..end].rfind('/') {
31915422×
                if !set.insert(&p[..i]) {
32014782×
                    break;
321640×
                }
322640×
                end = i;
323
            }
32418521×
        }
32518508×
        for p in fs_entries.keys() {
32618508×
            parents_of(p, &mut needed_dirs);
32718508×
        }
32813091×
        for p in base_snapshot.files.keys() {
32913091×
            if !self.in_scope(p) {
33013×
                parents_of(p, &mut needed_dirs);
33113078×
            }
332
        }
33313091×
        for (path, expected) in &base_snapshot.files {
33413091×
            if fs_entries.contains_key(path)
335548×
                || !self.in_scope(path)
336535×
                || renamed_to.contains_key(path.as_str())
337
            {
33812588×
                continue;
339503×
            }
340503×
            let still_needed = expected.kind == NodeKind::Dir
341400×
                && match dir_needed {
34221×
                    Some(f) => f(path),
343379×
                    None => needed_dirs.contains(path.as_str()),
344
                };
345503×
            if !still_needed {
346127×
                b.remove_path(path, expected);
347376×
            }
348
        }
3491856×
        laps.lap("build: removals");
3501856×
        if seed.is_some() {
35188×
            b.retire_stray_placements();
3521768×
        }
3531856×
        laps.lap("build: stray placements");
3541856×
        let mut statuses = b.statuses;
3555640×
        statuses.sort_by(|a, b| a.path.cmp(&b.path));
3561856×
        Ok(BuiltChange {
3571856×
            tree_ops: b.tree_ops,
3581856×
            edits: b.edits,
3591856×
            contributors: b.contributors.into_iter().collect(),
3601856×
            resolves: b.resolves,
3611856×
            statuses,
3621856×
            blobs: b.blobs,
3631856×
        })
3641856×
    }
365
366
    /// Store a change and, when `core.sign = change` and we are its author,
367
    /// sign it. A rewritten change by another author is stored unsigned: only
368
    /// its author (or a delegate) can vouch for it.
369641×
    pub(crate) fn store_signed(&self, change: &Change) -> Result<ChangeHash> {
370641×
        let ours = change.author == self.author();
371641×
        if self.config.sign_changes && ours && self.secret_key()?.is_none() {
3721×
            return fail("core.sign is \"change\" but no secret key is available for author.key");
373640×
        }
374640×
        let storing = crate::timing::phase("store: the change");
375640×
        let hash = self.store.put_change(change)?;
376640×
        drop(storing);
377640×
        if self.config.sign_changes && ours {
37840×
            let _t = crate::timing::phase("store: sign it");
37940×
            self.sign_change(&hash)?;
380600×
        }
381640×
        Ok(hash)
382641×
    }
383
384
    /// Snapshot the working copy into the working-copy change (spec §12.3).
385
    /// The result carries the full base state and its whole rendering.
386407×
    pub fn snapshot(&self, command: &str) -> Result<SnapshotResult> {
387407×
        self.snapshot_as(command, false, false)
388407×
    }
389
390
    /// Snapshot the working copy as [`Repo::snapshot`] does, for commands
391
    /// that need its statuses, conflicts and base history, and the graphs
392
    /// of the files it changes: status, log, show, commit, diff, hunks and
393
    /// discard. Text files known unchanged since the last manifest are
394
    /// neither read nor rendered: the result's `base` is a history-only
395
    /// state without their graphs, and its `base_snapshot` lists them in
396
    /// `unrendered` with empty bytes. They are never conflicted, and no
397
    /// change the working copy makes touches them.
398386×
    pub fn snapshot_status(&self, command: &str) -> Result<SnapshotResult> {
399386×
        self.snapshot_as(command, true, false)
400386×
    }
401
402
    /// `snapshot_as`; `for_commit` writes the manifest even where a status
403
    /// would not bother (an edited file is read next time whatever it
404
    /// says), since after the commit that file is unchanged, and records no
405
    /// operation: the commit's own, recorded straight after, replaces the
406
    /// working copy, so the snapshot's would cost a durable write for
407
    /// nothing. Should the commit fail, the files are still on disk and the
408
    /// next snapshot finds them.
4091214×
    fn snapshot_as(
4101214×
        &self,
4111214×
        command: &str,
4121214×
        partial: bool,
4131214×
        for_commit: bool,
4141214×
    ) -> Result<SnapshotResult> {
4151214×
        let _lock = self.lock_snapshot()?;
4161214×
        let batch = self.store.begin_batch()?;
4171214×
        let result = self.snapshot_locked(command, partial, for_commit);
4181214×
        batch.finish()?;
4191214×
        result
4201214×
    }
421
4221214×
    fn snapshot_locked(
4231214×
        &self,
4241214×
        command: &str,
4251214×
        partial: bool,
4261214×
        for_commit: bool,
4271214×
    ) -> Result<SnapshotResult> {
4281214×
        let _all = crate::timing::phase("snapshot");
4291214×
        let (op_ref, op) = self.head_op()?;
4301214×
        let (old_hash, old_wc) = self.working_copy()?;
431
        // The base's history first: its graph keys say which files the
432
        // manifest already knows equal to it.
4331212×
        let mut base = {
4341212×
            let _t = crate::timing::phase("snapshot: load base history");
4351212×
            self.load_state_indexed(&old_wc.deps)?
436
        };
4371212×
        let view = {
4381212×
            let _t = crate::timing::phase("snapshot: tree view");
4391212×
            base.tree().view()
440
        };
4411212×
        let manifest = {
4421212×
            let _t = crate::timing::phase("snapshot: read manifest");
4431212×
            self.read_manifest()?.map(|(_, _, m)| m)
444
        };
4451212×
        let tracked: BTreeMap<String, (NodeKind, Option<ObjectRef>)> = {
4461212×
            let _t = crate::timing::phase("snapshot: tracked paths");
447
            // In the view's path order, so the map is built without searching.
4481212×
            view.entries
4491212×
                .iter()
4509363×
                .filter(|(_, e)| e.kind != NodeKind::Dir)
4518988×
                .map(|(p, e)| {
4528988×
                    let blob = if e.kind != NodeKind::File || e.mode.opaque {
453151×
                        base.live_blobs(&e.node).first().copied()
454
                    } else {
4558837×
                        None
456
                    };
4578988×
                    (p.clone(), (e.kind, blob))
4588988×
                })
4591212×
                .collect()
460
        };
461
        // A text file's graph key, worked out when the walk asks for it.
46211947×
        let key_of = |p: &str| -> Option<[u8; 32]> {
46311947×
            let e = view.entries.get(p)?;
4648882×
            if e.kind != NodeKind::File || e.mode.opaque {
465124×
                return None;
4668758×
            }
4678758×
            base.graph_key(&e.node)
46811947×
        };
4691211×
        let mut fs_entries = {
4701212×
            let _t = crate::timing::phase("snapshot: read working copy");
4711212×
            self.walk_working_copy_with(manifest.as_deref(), &tracked, Some(&key_of))?
472
        };
473
        // The keys of the files read, before building graphs drops them: a
474
        // file found equal to its base rendering keeps its key.
4751211×
        let keys: HashMap<String, [u8; 32]> = fs_entries
4761211×
            .iter()
47711976×
            .filter(|(_, e)| !e.unchanged && e.kind == NodeKind::File)
4787703×
            .filter_map(|(p, _)| Some((p.clone(), key_of(p)?)))
4791211×
            .collect();
4801211×
        let base_snapshot = {
4811211×
            let _t = crate::timing::phase("snapshot: load and render base");
4821211×
            if partial {
483807×
                let sets = crate::timing::phase("snapshot:   of which choosing graphs");
484
                // Every file but those on disk known unchanged.
485807×
                let need: Vec<(&str, NodeId)> = join(&view.entries, &fs_entries)
48610966×
                    .filter_map(|(p, v, f)| {
48710966×
                        let v = v?;
4888003×
                        (v.kind == NodeKind::File && !f.is_some_and(|f| f.unchanged))
4898003×
                            .then_some((p.as_str(), v.node))
49010966×
                    })
491807×
                    .collect();
492807×
                let render: std::collections::HashSet<&str> =
493807×
                    need.iter().map(|(p, _)| *p).collect();
494807×
                let need: Vec<NodeId> = need.iter().map(|(_, n)| *n).collect();
495807×
                drop(sets);
496
                {
497807×
                    let _t = crate::timing::phase("snapshot:   of which building graphs");
498807×
                    self.load_graphs_of(&mut base, &need)?;
499
                }
500807×
                let _t = crate::timing::phase("snapshot:   of which rendering");
501807×
                base.materialize_only(&render)
502
            } else {
503404×
                self.load_all_graphs(&mut base)?;
504404×
                base.materialize()
505
            }
506
        };
507
508
        // Reuse the NodeIds the previous working-copy version assigned to new
509
        // paths, so an unchanged working copy hashes identically (spec §12.3).
5101211×
        let reuse = added_node_paths(&old_wc, &base_snapshot);
5111211×
        self.platform_normalize(&mut fs_entries, &base_snapshot);
5121211×
        let built = {
5131211×
            let _t = crate::timing::phase("snapshot: diff against base");
5141211×
            if partial && self.config.sparse_paths.is_empty() {
515
                #[cfg(test)]
516537×
                let full =
517537×
                    self.build_from_entries(&base, &base_snapshot, reuse.clone(), &fs_entries)?;
518804×
                let built = self.build_changed_only(&base, &base_snapshot, reuse, &fs_entries)?;
519
                #[cfg(test)]
520
                {
521
                    // New nodes take random identifiers: compare them by
522
                    // order of appearance.
5231074×
                    let norm = |b: &BuiltChange| {
5241074×
                        let text = format!("{:?} {:?} {:?}", b.tree_ops, b.edits, b.statuses);
5251074×
                        let mut seen: Vec<String> = Vec::new();
5261074×
                        let mut out = String::new();
5271074×
                        let mut rest = text.as_str();
52819514×
                        while let Some(i) = rest.find("NodeId(") {
52918440×
                            out.push_str(&rest[..i]);
53018440×
                            let end = i + rest[i..].find(')').unwrap() + 1;
53118440×
                            let id = rest[i..end].to_string();
5329045716×
                            let n = seen.iter().position(|x| *x == id).unwrap_or_else(|| {
5336868×
                                seen.push(id);
5346868×
                                seen.len() - 1
5356868×
                            });
53618440×
                            out.push_str(&format!("N{n}"));
53718440×
                            rest = &rest[end..];
538
                        }
5391074×
                        out.push_str(rest);
5401074×
                        out
5411074×
                    };
542537×
                    assert_eq!(
543537×
                        norm(&built),
544537×
                        norm(&full),
545
                        "a changed-only build is the full one"
546
                    );
547
                }
548804×
                built
549
            } else {
550407×
                self.build_from_entries(&base, &base_snapshot, reuse, &fs_entries)?
551
            }
552
        };
553
        // Text files found equal to an unconflicted base rendering keep its
554
        // graph key, so the next snapshot need not read or render them.
555
        {
5563655×
            let changed: HashSet<&str> = built.statuses.iter().map(|s| s.path.as_str()).collect();
55711976×
            for (p, e) in fs_entries.iter_mut() {
55811976×
                if e.unchanged || e.kind != NodeKind::File || changed.contains(p.as_str()) {
5597830×
                    continue;
5604146×
                }
5614146×
                e.graph_key = match base_snapshot.files.get(p).map(|f| &f.content) {
562
                    Some(FileContent::Text {
5634034×
                        bytes,
5644034×
                        materialized,
5654034×
                    }) if !materialized.is_conflicted() && *bytes == *e.content => {
5664028×
                        keys.get(p).copied()
567
                    }
568118×
                    _ => None,
569
                };
570
            }
571
        }
572
5731211×
        let mut wc = Change {
5741211×
            version: crate::objects::CHANGE_VERSION,
5751211×
            change_id: old_wc.change_id,
5761211×
            deps: vec![],
5771211×
            author: self.author(),
5781211×
            hlc: old_wc.hlc,
5791211×
            message: old_wc.message.clone(),
5801211×
            tree_ops: built.tree_ops,
5811211×
            edits: built.edits,
5821211×
            kind: ChangeKind::WorkingCopy,
5831211×
        };
5841211×
        let base_heads = base.maximal(&old_wc.deps);
5851211×
        let mut deps: BTreeSet<ChangeHash> = base_heads.into_iter().collect();
5861211×
        deps.extend(referenced_changes(&wc, &base));
5871211×
        deps.extend(built.contributors.iter().copied());
5881211×
        wc.deps = deps.into_iter().collect();
5891211×
        wc.normalize();
5901211×
        let resolves = built.resolves;
5911211×
        let contributors = built.contributors;
5921211×
        let statuses = built.statuses;
593
        // Empty snapshot: hash the candidate before storing; only record an op on change.
5941211×
        let record = crate::timing::phase("snapshot: hash and record");
595
        // Encoded once, its texts stored a batch at a time as they are
596
        // made (a stored blob is not stored again); the change itself only
597
        // when it changed.
598
        // For a commit the change is neither encoded, stored nor recorded:
599
        // the commit stores its own, built from this one's operations, and
600
        // its texts with it. The hash it would have is not needed.
6011211×
        let (new_hash, changed, encoded) = if for_commit {
602421×
            (old_hash, true, Vec::new())
603
        } else {
604790×
            let encoded = wc.encode_streaming(|batch| self.store.put_texts(&batch))?;
605790×
            let new_hash = crate::hash::hash_object(crate::hash::ObjectType::Change, &encoded);
606790×
            (new_hash, new_hash != old_hash, encoded)
607
        };
6081211×
        if changed && !for_commit {
609262×
            self.store.put(crate::hash::ObjectType::Change, &encoded)?;
610262×
            let mut view = op.view.clone();
611262×
            view.workspaces.insert(self.workspace, new_hash);
612262×
            self.record_op(&[op_ref], &format!("{command}{SNAPSHOT_SUFFIX}"), view)?;
613949×
        }
6141211×
        drop(record);
615
        // The prompt compares against this without recording anything.
6161211×
        let _t = crate::timing::phase("snapshot: write manifest");
6171211×
        let conflicted = base_snapshot.is_conflicted();
6181211×
        let uncommitted = !wc.tree_ops.is_empty() || !wc.edits.is_empty();
619
        // Rewriting the manifest pays only when it would teach the next
620
        // snapshot something: other flags, a file found equal to the base
621
        // (it need not be read again), a new blob, a path added or gone.
622
        // An edited file is read next time whatever it says.
6231211×
        let worth = match self.read_manifest()? {
624421×
            _ if for_commit => true,
625296×
            None => true,
626494×
            Some((c, u, m)) => {
627494×
                c != conflicted
628494×
                    || u != uncommitted
629288×
                    || m.entries.len() != fs_entries.len()
630371×
                    || fs_entries.iter().any(|(p, e)| {
631371×
                        !e.unchanged && (e.graph_key.is_some() || !m.entries.contains_key(p))
632371×
                    })
63345×
                    || built
63445×
                        .blobs
63545×
                        .iter()
63645×
                        .any(|(p, b)| m.entries.get(p).and_then(|e| e.blob) != Some(*b))
637
                    // With uncommitted work, the status cache below holds
638
                    // only while the manifest describes the edited files as
639
                    // they are now.
64058×
                    || (uncommitted && statuses.iter().any(|st| {
64158×
                        let Some(e) = fs_entries.get(&st.path) else {
6423×
                            return m.entries.contains_key(&st.path);
643
                        };
64455×
                        let Some(me) = m.entries.get(&st.path) else {
6450×
                            return true;
646
                        };
64755×
                        let hash = e
64855×
                            .content_hash
64955×
                            .unwrap_or_else(|| *blake3::hash(&e.content).as_bytes());
65055×
                        let stat = e.stat.or_else(|| {
6510×
                            fs::symlink_metadata(self.root.join(&st.path))
6520×
                                .ok()
6530×
                                .map(|md| (md.len(), super::prompt::mtime_ns(&md)))
6540×
                        });
655
                        // The executable bit too: a mode change moves
656
                        // neither size nor time.
65755×
                        me.hash != hash || me.exec != e.exec || stat != Some((me.size, me.mtime_ns))
65858×
                    }))
659
            }
660
        };
6611211×
        let attributes = crate::attributes::Attributes::from_files(
6621211×
            fs_entries
6631211×
                .iter()
66411976×
                .filter(|(p, _)| is_attributes(p))
6651211×
                .map(|(p, e)| (p.as_str(), e.content.as_slice())),
666
        );
6671211×
        let mut manifest = None;
6681211×
        if for_commit {
669421×
            manifest = Some(PendingManifest {
670421×
                entries: fs_entries,
671421×
                blobs: built.blobs.clone(),
672421×
                dirs: self.walked_dirs.take(),
673421×
                written: super::prompt::now_ns(),
674421×
            });
675421×
        } else {
676790×
            if worth {
677748×
                self.write_manifest_entries(conflicted, uncommitted, &fs_entries, &built.blobs)?;
67842×
            }
679790×
            self.write_status_cache((uncommitted && !conflicted).then_some(&new_hash), &statuses);
680
        }
6811211×
        Ok(SnapshotResult {
6821211×
            wc_hash: new_hash,
6831211×
            wc,
6841211×
            base,
6851211×
            base_snapshot,
6861211×
            statuses,
6871211×
            changed,
6881211×
            resolves,
6891211×
            contributors,
6901211×
            attributes,
6911211×
            untracked_nested: self.untracked_nested.borrow().clone(),
6921211×
            manifest,
6931211×
        })
6941214×
    }
695
696
    /// `oxy status --json` (spec §9.5): the changed paths and every conflict
697
    /// of the working copy's base with its kind, path, and contributing
698
    /// ChangeIds.
6997×
    pub fn status_json(&self, snap: &SnapshotResult) -> Result<String> {
7007×
        let heads = self.bookmark_heads()?;
7017×
        let base_snapshot = &snap.base_snapshot;
7027×
        let by_node = base_snapshot.tree.by_node();
7037×
        let path_of = |n: &NodeId| by_node.get(n).map(|e| e.path.clone());
7047×
        let id_of = |h: &ChangeHash| {
7054×
            snap.base
7064×
                .get(h)
7074×
                .map(|m| m.change_id.to_hex())
7084×
                .unwrap_or_else(|| h.to_hex())
7094×
        };
7107×
        let paths = json_array(snap.statuses.iter().map(|s| {
7114×
            format!(
712
                "{{\"path\":{},\"status\":{}}}",
7134×
                json_str(&s.path),
7144×
                json_str(&format!("{:?}", s.status))
715
            )
7164×
        }));
7177×
        let mut conflicts: Vec<String> = Vec::new();
7187×
        for (p, f) in &base_snapshot.files {
7197×
            if !f.is_conflicted() {
7205×
                continue;
7212×
            }
7222×
            let (kind, changes) = match &f.content {
723
                FileContent::Text { .. } => {
7242×
                    ("text", snap.base.conflict_regions(&f.node).contributors)
725
                }
7260×
                FileContent::Opaque { blobs } => {
7270×
                    ("replace", snap.base.blob_contributors(&f.node, blobs))
728
                }
7290×
                FileContent::Dir => continue,
730
            };
7312×
            let resolved = match snap
7322×
                .statuses
7332×
                .iter()
7342×
                .find(|s| s.path == *p)
7352×
                .map(|s| s.status)
736
            {
7371×
                Some(ChangeStatus::Resolved) => "true",
7380×
                Some(ChangeStatus::ConflictEdited) => "\"markers\"",
7391×
                _ => "false",
740
            };
7412×
            conflicts.push(format!(
742
                "{{\"kind\":{},\"path\":{},\"node\":{},\"changes\":{},\"resolved\":{resolved}}}",
7432×
                json_str(kind),
7442×
                json_str(p),
7452×
                json_str(&f.node.to_hex()),
7464×
                json_array(changes.iter().map(|h| json_str(&id_of(h))))
747
            ));
748
        }
7497×
        for c in &base_snapshot.tree.conflicts {
7500×
            let (kind, nodes): (&str, Vec<NodeId>) = match c {
7510×
                crate::tree::TreeConflict::Name { nodes, .. } => ("name", nodes.clone()),
7520×
                crate::tree::TreeConflict::MultiPlacement { node, .. } => {
7530×
                    ("multi-placement", vec![*node])
754
                }
7550×
                crate::tree::TreeConflict::Orphan { node, .. } => ("orphan", vec![*node]),
7560×
                crate::tree::TreeConflict::Cycle { node } => ("cycle", vec![*node]),
7570×
                crate::tree::TreeConflict::Mode { node, .. } => ("mode", vec![*node]),
758
            };
7590×
            let detail = match c {
7600×
                crate::tree::TreeConflict::Name { name, parent, .. } => {
7610×
                    let dir = if *parent == NodeId::ROOT {
7620×
                        String::new()
763
                    } else {
7640×
                        path_of(parent).unwrap_or_default()
765
                    };
7660×
                    format!(
767
                        ",\"path\":{}",
7680×
                        json_str(&if dir.is_empty() {
7690×
                            name.clone()
770
                        } else {
7710×
                            format!("{dir}/{name}")
772
                        })
773
                    )
774
                }
7750×
                _ => nodes
7760×
                    .first()
7770×
                    .and_then(path_of)
7780×
                    .map(|p| format!(",\"path\":{}", json_str(&p)))
7790×
                    .unwrap_or_default(),
780
            };
7810×
            conflicts.push(format!(
782
                "{{\"kind\":{},\"nodes\":{}{detail}}}",
7830×
                json_str(kind),
7840×
                json_array(nodes.iter().map(|n| json_str(&n.to_hex())))
785
            ));
786
        }
7877×
        Ok(format!(
788
            "{{\"bookmark\":{},\"working_copy\":{},\"heads\":{},\"clean\":{},\"conflicted\":{},\"paths\":{paths},\"conflicts\":{},\"untracked_nested\":{}}}",
7897×
            json_str(&self.config.bookmark),
7907×
            json_str(&snap.wc.change_id.to_hex()),
7917×
            heads.len(),
7927×
            snap.statuses.is_empty(),
7937×
            base_snapshot.is_conflicted(),
7947×
            json_array(conflicts),
7957×
            json_array(snap.untracked_nested.iter().map(|p| json_str(p)))
796
        ))
7977×
    }
798
799
    /// Turn the working-copy change into a normal change on the bookmark (spec §12.3).
800583×
    pub fn commit(&self, message: &str, extra_deps: &[ChangeHash]) -> Result<ChangeHash> {
801583×
        self.commit_selection(message, extra_deps, &Selection::All)
802583×
    }
803
804
    /// The hunks of the working copy, for `oxy commit --interactive`: each
805
    /// tree operation and each edit, in the order `select_hunks` numbers them.
8067×
    pub fn hunks(&self) -> Result<(SnapshotResult, Vec<Hunk>)> {
8077×
        let snap = self.snapshot_status("oxy commit")?;
8087×
        let hunks = render_hunks(&snap.wc, &snap.base, &snap.base_snapshot);
8097×
        Ok((snap, hunks))
8107×
    }
811
812
    /// Commit part of the working copy (spec §12.3). What is not selected
813
    /// stays on disk as uncommitted work: the next snapshot rebuilds it
814
    /// against the new base, so the working copy always describes the
815
    /// directory.
816
    /// The graph key in `st` of each text file at `paths`, the paths a
817
    /// commit changed: only their graphs changed, so the keys the manifest
818
    /// holds for the others still stand (and any that does not is simply
819
    /// not trusted by the next snapshot, which compares keys). Files with
820
    /// an `eol` attribute are left out: their bytes on disk are not the
821
    /// rendering.
822603×
    fn committed_graph_keys(
823603×
        &self,
824603×
        st: &State,
825603×
        paths: &[String],
826603×
        attrs: &crate::attributes::Attributes,
827603×
    ) -> HashMap<String, [u8; 32]> {
828603×
        let _t = crate::timing::phase("commit: graph keys");
829603×
        let view = st.tree().view();
830603×
        paths
831603×
            .iter()
8323423×
            .filter_map(|p| {
8333423×
                let e = view.entries.get(p)?;
8343374×
                (e.kind == NodeKind::File && !e.mode.opaque && attrs.lookup(p).eol.is_none())
8353374×
                    .then_some(())?;
8363325×
                Some((p.clone(), st.graph_key(&e.node)?))
8373423×
            })
838603×
            .collect()
839603×
    }
840
841588×
    pub fn commit_selection(
842588×
        &self,
843588×
        message: &str,
844588×
        extra_deps: &[ChangeHash],
845588×
        selection: &Selection,
846588×
    ) -> Result<ChangeHash> {
847588×
        Ok(self
848588×
            .commit_selection_partial(message, extra_deps, selection)?
849
            .0)
850588×
    }
851
852
    /// As [`Repo::commit_selection`], and whether the commit left part of
853
    /// the working copy uncommitted: when it did not, nothing is left, and
854
    /// no snapshot is needed to say so.
855614×
    pub fn commit_selection_partial(
856614×
        &self,
857614×
        message: &str,
858614×
        extra_deps: &[ChangeHash],
859614×
        selection: &Selection,
860614×
    ) -> Result<(ChangeHash, bool)> {
861
        // The commit's objects are written together, made durable at once
862
        // before the operation that names them (spec §13.6).
863614×
        let batch = self.store.begin_batch()?;
864614×
        let out = self.commit_selection_batched(message, extra_deps, selection);
865614×
        batch.finish()?;
866614×
        out
867614×
    }
868
869
    /// Write the manifest a commit's snapshot left to the commit, with the
870
    /// graph keys `keys` sets.
871412×
    fn write_pending_manifest(
872412×
        &self,
873412×
        mut m: PendingManifest,
874412×
        conflicted: bool,
875412×
        keys: HashMap<String, [u8; 32]>,
876412×
    ) -> Result<()> {
8772805×
        for (path, k) in keys {
8782805×
            if let Some(e) = m.entries.get_mut(&path) {
8792805×
                e.graph_key = Some(k);
8802805×
            }
881
        }
882412×
        self.write_manifest_entries_as_of(
883412×
            conflicted,
884
            false,
885412×
            &m.entries,
886412×
            &m.blobs,
887412×
            m.written,
888412×
            m.dirs.unwrap_or_default(),
889
        )
890412×
    }
891
892614×
    fn commit_selection_batched(
893614×
        &self,
894614×
        message: &str,
895614×
        extra_deps: &[ChangeHash],
896614×
        selection: &Selection,
897614×
    ) -> Result<(ChangeHash, bool)> {
898614×
        let _wc = self.lock_working_copy()?;
899614×
        let mut snap = match self.snapshot_from_cache()? {
900193×
            Some(snap) => snap,
901421×
            None => self.snapshot_as("oxy commit", true, true)?,
902
        };
903614×
        let pending = snap.manifest.take();
904614×
        if snap.wc.tree_ops.is_empty() && snap.wc.edits.is_empty() {
9053×
            if let Some(m) = pending {
9063×
                let conflicted = snap.base_snapshot.is_conflicted();
9073×
                self.write_pending_manifest(m, conflicted, HashMap::new())?;
9080×
            }
9093×
            return fail("nothing to commit: the working copy matches its base");
910611×
        }
911611×
        if let Some(s) = snap
912611×
            .statuses
913611×
            .iter()
9143440×
            .find(|s| s.status == ChangeStatus::ConflictEdited)
915
        {
9160×
            return fail(format!("{} still contains conflict markers", s.path));
917611×
        }
918611×
        if message.trim().is_empty() {
9190×
            return fail("a commit message is required");
920611×
        }
921
        // What the whole working copy references, before a whole commit
922
        // takes its operations over (they are moved, not copied: for a
923
        // large tree they are most of the memory).
924611×
        let wc_refs = referenced_changes(&snap.wc, &snap.base);
9253440×
        let changed_paths: Vec<String> = snap.statuses.iter().map(|s| s.path.clone()).collect();
926611×
        let (tree_ops, edits, partial) = match selection {
927603×
            Selection::All => (
928603×
                std::mem::take(&mut snap.wc.tree_ops),
929603×
                std::mem::take(&mut snap.wc.edits),
930603×
                false,
931603×
            ),
9324×
            Selection::Paths(paths) => {
9334×
                let (o, e) = select_paths(&snap.wc, &snap.base_snapshot, paths);
9344×
                let partial = o.len() != snap.wc.tree_ops.len() || e.len() != snap.wc.edits.len();
9354×
                (o, e, partial)
936
            }
9374×
            Selection::Hunks(indices) => {
9384×
                let (o, e) = select_hunks(&snap.wc, indices);
9394×
                let partial = o.len() != snap.wc.tree_ops.len() || e.len() != snap.wc.edits.len();
9404×
                (o, e, partial)
941
            }
942
        };
943611×
        if tree_ops.is_empty() && edits.is_empty() {
9440×
            return fail("nothing selected to commit");
945611×
        }
946611×
        if partial && snap.resolves {
9470×
            return fail("a conflict resolution must be committed whole");
948611×
        }
949
        // pre-commit hook: may veto.
950611×
        self.run_hook(
951611×
            "pre-commit",
952611×
            &format!(
953
                "{{\"event\":\"pre-commit\",\"message\":{},\"paths\":{}}}",
954611×
                json_str(message),
9553440×
                json_array(snap.statuses.iter().map(|s| format!(
956
                    "{{\"path\":{},\"status\":{}}}",
9573440×
                    json_str(&s.path),
9583440×
                    json_str(&format!("{:?}", s.status))
959
                )))
960
            ),
9611×
        )?;
962610×
        let (op_ref, op) = self.head_op()?;
963610×
        let mut deps: BTreeSet<ChangeHash> = wc_refs;
964
        // semantic-deps hook: may add explicit dependencies (spec §8.1).
965610×
        if self.config.semantic_deps {
9661×
            let touched: Vec<String> = snap.statuses.iter().map(|s| s.path.clone()).collect();
9671×
            let by_node = snap.base_snapshot.tree.by_node();
9681×
            let mut candidates: Vec<(ChangeId, ChangeHash, Vec<String>)> = Vec::new();
9691×
            let mut seen: BTreeSet<ChangeHash> = BTreeSet::new();
9702×
            for h in deps.iter().chain(snap.base.maximal(&snap.wc.deps).iter()) {
9712×
                if !seen.insert(*h) {
9720×
                    continue;
9732×
                }
9742×
                let c = self.store.get_change(h)?;
9752×
                let mut paths: BTreeSet<String> = BTreeSet::new();
9766×
                for n in c
9772×
                    .tree_ops
9782×
                    .iter()
9793×
                    .map(|o| o.node())
9803×
                    .chain(c.edits.iter().map(|e| e.node()))
981
                {
9826×
                    if let Some(e) = by_node.get(&n) {
9836×
                        paths.insert(e.path.clone());
9846×
                    }
985
                }
9862×
                candidates.push((c.change_id, *h, paths.into_iter().collect()));
987
            }
9881×
            for d in self.semantic_deps(&snap.wc.change_id, &touched, &candidates)? {
9891×
                if snap.base.contains(&d) {
9901×
                    deps.insert(d);
9911×
                }
992
            }
993609×
        }
994
        // A resolution depends on every change that contributed to the
995
        // conflict (spec §8.1). Tree and opaque conflicts are resolved through
996
        // ordinary operations whose references already cover the contributors.
997610×
        deps.extend(snap.contributors.iter().copied());
998610×
        for d in extra_deps {
9992×
            if !snap.base.contains(d) {
10000×
                return fail(format!(
1001
                    "--depends-on {d}: not in the working copy's base state"
1002
                ));
10032×
            }
10042×
            deps.insert(*d);
1005
        }
1006610×
        let mut change = Change {
1007
            version: crate::objects::CHANGE_VERSION,
1008610×
            change_id: if partial {
10096×
                ChangeId::random()
1010
            } else {
1011604×
                snap.wc.change_id
1012
            },
1013610×
            deps: vec![],
1014610×
            author: self.author(),
1015610×
            hlc: Hlc::now(),
1016610×
            message: message.trim_end().to_string(),
1017610×
            tree_ops,
1018610×
            edits,
1019610×
            kind: if snap.resolves {
10207×
                ChangeKind::Resolution
1021
            } else {
1022603×
                ChangeKind::Normal
1023
            },
1024
        };
1025610×
        if partial {
1026
            // Dependencies come from what the selected part references, not
1027
            // from the whole working copy.
10286×
            deps = referenced_changes(&change, &snap.base);
10296×
            for d in extra_deps {
10300×
                deps.insert(*d);
10310×
            }
1032604×
        }
1033610×
        change.deps = deps.into_iter().collect();
1034610×
        change.normalize();
1035610×
        let signing = crate::timing::phase("commit: sign and store");
1036610×
        let hash = self.store_signed(&change)?;
1037609×
        drop(signing);
1038609×
        let extending = crate::timing::phase("commit: extend the state");
1039
1040
        // New bookmark heads: maximal elements of old heads plus the new change.
1041
        // The working copy continues on its own base plus the new change, which
1042
        // is exactly what the files on disk contain; the bookmark may hold
1043
        // other heads (and conflicts) the working copy has not checked out.
1044609×
        let old_heads = self.heads_of(&op.view, &self.config.bookmark)?;
1045609×
        let old_base = snap.base.maximal(&snap.wc.deps);
1046609×
        let mut all: Vec<ChangeHash> = old_heads.clone();
1047609×
        all.extend(old_base.iter().copied());
1048609×
        all.push(hash);
1049
        // The snapshot already loaded the working copy's base; when that also
1050
        // holds every bookmark head, it is the state to extend.
1051609×
        let mut st = if old_heads.iter().all(|h| snap.base.contains(h)) {
1052571×
            snap.base
1053
        } else {
105438×
            self.load_state(&all)?
1055
        };
1056609×
        st.add_hashed(hash, change)?;
1057609×
        let mut with_new = old_heads.clone();
1058609×
        with_new.push(hash);
1059609×
        let new_heads = st.maximal(&with_new);
1060
        // Automatic checkpoint once enough changes accumulated (spec §11).
1061609×
        let since = self
1062609×
            .latest_checkpoint(&self.config.bookmark)?
1063609×
            .map(|(_, cp)| cp.count)
1064609×
            .unwrap_or(0);
1065609×
        if self.config.checkpoint_interval > 0
1066609×
            && (st.len() as u64).saturating_sub(since) >= self.config.checkpoint_interval
1067
        {
10682×
            let cp_state = self.load_state_full(&new_heads)?;
10692×
            self.write_checkpoint(&self.config.bookmark, &cp_state, &new_heads)?;
1070607×
        }
1071609×
        let mut wc_base = old_base.clone();
1072609×
        wc_base.push(hash);
1073609×
        let wc_base = st.maximal(&wc_base);
1074609×
        drop(extending);
1075
1076
        // The graph keys of the files as they now are, from the state the
1077
        // commit just extended: a file whose graph it built has none, and
1078
        // is read by the next snapshot; a key the next base does not share
1079
        // (the bookmark held other heads) is simply not trusted then.
1080609×
        let keying = crate::timing::phase("commit: graph keys of the files");
1081609×
        let committed_keys =
1082609×
            (!partial).then(|| self.committed_graph_keys(&st, &changed_paths, &snap.attributes));
1083609×
        drop(keying);
1084609×
        let recording = crate::timing::phase("commit: record");
1085609×
        let wc = self.new_working_copy(wc_base, "");
1086609×
        let wc_hash = self.store.put_change(&wc)?;
1087609×
        let mut view = op.view.clone();
1088609×
        view.bookmarks.insert(
1089609×
            self.config.bookmark.clone(),
1090609×
            self.store.put_state(&StateObject::new(new_heads))?,
1091
        );
1092609×
        view.workspaces.insert(self.workspace, wc_hash);
1093609×
        self.record_op(&[op_ref], &format!("oxy commit -m {message:?}"), view)?;
1094604×
        drop(recording);
1095604×
        let rewriting = crate::timing::phase("commit: manifest");
1096604×
        if partial {
10976×
            // The rest is rebuilt from disk by the next snapshot.
10986×
            self.drop_manifest();
10996×
        } else {
1100598×
            let conflicted = snap.base_snapshot.is_conflicted() && !snap.resolves;
1101
            // The files on disk are now exactly the new base's renderings:
1102
            // record their graph keys, so the next snapshot neither reads nor
1103
            // renders them (oxygen#35).
1104598×
            let keys = if conflicted {
11050×
                HashMap::new()
1106
            } else {
1107598×
                committed_keys.unwrap_or_default()
1108
            };
1109598×
            match pending {
1110409×
                Some(m) => self.write_pending_manifest(m, conflicted, keys)?,
1111189×
                None => self.rewrite_manifest(conflicted, false, &keys)?,
1112
            }
1113
        }
1114604×
        drop(rewriting);
1115604×
        let packing = crate::timing::phase("commit: autopack");
1116604×
        self.maybe_autopack()?;
1117604×
        drop(packing);
1118604×
        let _hook = crate::timing::phase("commit: hook");
1119604×
        let _ = self.run_hook(
1120604×
            "post-commit",
1121604×
            &format!(
1122604×
                "{{\"event\":\"post-commit\",\"change_id\":{},\"hash\":{},\"message\":{}}}",
1123604×
                json_str(&snap.wc.change_id.to_hex()),
1124604×
                json_str(&hash.to_hex()),
1125604×
                json_str(message)
1126604×
            ),
1127604×
        );
1128604×
        Ok((hash, partial))
1129614×
    }
1130
}
1131
1132
/// What part of the working copy a commit takes (spec §12.3).
1133
#[derive(Clone, Debug)]
1134
pub enum Selection {
1135
    All,
1136
    /// Every operation and edit on nodes under these paths.
1137
    Paths(Vec<String>),
1138
    /// Hunk indices as `Repo::hunks` numbers them; dependent hunks are added.
1139
    Hunks(Vec<usize>),
1140
}
1141
1142
/// One selectable piece of the working copy: a tree operation or an edit.
1143
#[derive(Clone, Debug)]
1144
pub struct Hunk {
1145
    pub index: usize,
1146
    pub path: String,
1147
    /// Rendered like `oxy diff`.
1148
    pub text: String,
1149
}
1150
1151
/// The tree operations and edits on nodes under `paths`, plus the
1152
/// additions of any new parent directories they need.
11534×
fn select_paths(
11544×
    wc: &Change,
11554×
    base_snapshot: &Snapshot,
11564×
    paths: &[String],
11574×
) -> (Vec<TreeOp>, Vec<Edit>) {
115813×
    let selected = |p: &str| {
115913×
        paths
116013×
            .iter()
116113×
            .any(|x| p == x || p.starts_with(&format!("{}/", x.trim_end_matches('/'))))
116213×
    };
11634×
    let by_node = base_snapshot.tree.by_node();
11644×
    let mut new_names: HashMap<NodeId, (NodeId, String, NodeKind)> = HashMap::new();
11654×
    for op in &wc.tree_ops {
1166
        if let TreeOp::AddNode {
11671×
            node,
11681×
            parent,
11691×
            name,
11701×
            kind,
1171
            ..
11721×
        } = op
11731×
        {
11741×
            new_names.insert(*node, (*parent, name.clone(), *kind));
11751×
        }
1176
    }
11774×
    let mut nodes: BTreeSet<NodeId> = BTreeSet::new();
117813×
    for n in wc
11794×
        .tree_ops
11804×
        .iter()
11814×
        .map(|o| o.node())
118212×
        .chain(wc.edits.iter().map(|e| e.node()))
1183
    {
118413×
        if path_of_node(&n, &by_node, &new_names).is_some_and(|p| selected(&p)) {
11858×
            nodes.insert(n);
11868×
        }
1187
    }
1188
    // New parents of selected new nodes come along.
11894×
    let mut changed = true;
11908×
    while changed {
11914×
        changed = false;
11924×
        for (n, (parent, _, _)) in &new_names {
11931×
            if nodes.contains(n) && new_names.contains_key(parent) && nodes.insert(*parent) {
11940×
                changed = true;
11951×
            }
1196
        }
1197
    }
11984×
    let ops = wc
11994×
        .tree_ops
12004×
        .iter()
12014×
        .filter(|o| nodes.contains(&o.node()))
12024×
        .cloned()
12034×
        .collect();
12044×
    let edits = wc
12054×
        .edits
12064×
        .iter()
120712×
        .filter(|e| nodes.contains(&e.node()))
12084×
        .cloned()
12094×
        .collect();
12104×
    (ops, edits)
12114×
}
1212
1213
/// The hunks `indices` name plus whatever they refer to within the working
1214
/// copy (the parent directory of an added node, the insert that introduced
1215
/// an anchor line), renumbered so the result is a well-formed change.
12165×
fn select_hunks(wc: &Change, indices: &[usize]) -> (Vec<TreeOp>, Vec<Edit>) {
12175×
    let n_ops = wc.tree_ops.len();
12185×
    let mut ops_sel = vec![false; n_ops];
12195×
    let mut edits_sel = vec![false; wc.edits.len()];
12205×
    for &i in indices {
12214×
        if i < n_ops {
12221×
            ops_sel[i] = true;
12233×
        } else if i - n_ops < wc.edits.len() {
12243×
            edits_sel[i - n_ops] = true;
12253×
        }
1226
    }
1227
    // Atom ranges each insert introduces, per node, in the working copy's numbering.
12285×
    let mut per_node: HashMap<NodeId, u32> = HashMap::new();
12295×
    let mut insert_ranges: Vec<Option<(NodeId, u32, u32)>> = Vec::new();
123010×
    for e in &wc.edits {
123110×
        insert_ranges.push(match e {
123210×
            Edit::Insert { node, lines, .. } => {
123310×
                let start = per_node.entry(*node).or_default();
123410×
                let r = (*node, *start, *start + lines.len() as u32);
123510×
                *start += lines.len() as u32;
123610×
                Some(r)
1237
            }
12380×
            _ => None,
1239
        });
1240
    }
12415×
    let add_index: HashMap<NodeId, usize> = wc
12425×
        .tree_ops
12435×
        .iter()
12445×
        .enumerate()
12458×
        .filter_map(|(i, o)| {
12468×
            if let TreeOp::AddNode { node, .. } = o {
12478×
                Some((*node, i))
1248
            } else {
12490×
                None
1250
            }
12518×
        })
12525×
        .collect();
12535×
    let insert_for = |node: &NodeId, index: u32| -> Option<usize> {
12540×
        insert_ranges
12550×
            .iter()
12560×
            .position(|r| matches!(r, Some((n, a, b)) if n == node && *a <= index && index < *b))
12570×
    };
1258
    // Closure.
12595×
    let mut changed = true;
126013×
    while changed {
12618×
        changed = false;
126217×
        for i in 0..n_ops {
126317×
            if !ops_sel[i] {
126411×
                continue;
12656×
            }
12666×
            if let TreeOp::AddNode { node, parent, .. } = &wc.tree_ops[i] {
12676×
                if let Some(&p) = add_index.get(parent) {
12684×
                    if !ops_sel[p] {
12692×
                        ops_sel[p] = true;
12702×
                        changed = true;
12712×
                    }
12722×
                }
1273
                // A new node's content belongs with its addition: nobody
1274
                // wants an empty file committed apart from its lines.
127512×
                for (j, e) in wc.edits.iter().enumerate() {
127612×
                    if e.node() == *node && !edits_sel[j] {
12771×
                        edits_sel[j] = true;
12781×
                        changed = true;
127911×
                    }
1280
                }
12810×
            }
1282
        }
128316×
        for j in 0..wc.edits.len() {
128416×
            if !edits_sel[j] {
12859×
                continue;
12867×
            }
12877×
            let e = &wc.edits[j];
12887×
            if let Some(&a) = add_index.get(&e.node()) {
12895×
                if !ops_sel[a] {
12901×
                    ops_sel[a] = true;
12911×
                    changed = true;
12924×
                }
12932×
            }
1294
            if let Edit::Insert {
12957×
                node,
12967×
                after,
12977×
                before,
1298
                ..
12997×
            } = e
1300
            {
130114×
                for r in [after, before] {
130214×
                    if let AtomRef::Atom { change, index } = r {
13032×
                        if change.is_zero() {
13040×
                            if let Some(k) = insert_for(node, *index) {
13050×
                                if !edits_sel[k] {
13060×
                                    edits_sel[k] = true;
13070×
                                    changed = true;
13080×
                                }
13090×
                            }
13102×
                        }
131112×
                    }
1312
                }
13130×
            }
1314
        }
1315
    }
1316
    // Renumber self-references: old atom index → new index among selected inserts.
13175×
    let mut remap: HashMap<(NodeId, u32), u32> = HashMap::new();
13185×
    let mut new_counts: HashMap<NodeId, u32> = HashMap::new();
131910×
    for (j, r) in insert_ranges.iter().enumerate() {
132010×
        if let (true, Some((node, a, b))) = (edits_sel[j], r) {
13214×
            let next = new_counts.entry(*node).or_default();
13224×
            for old in *a..*b {
13234×
                remap.insert((*node, old), *next);
13244×
                *next += 1;
13254×
            }
13266×
        }
1327
    }
13288×
    let map_ref = |r: AtomRef, node: &NodeId| -> AtomRef {
13292×
        match r {
13302×
            AtomRef::Atom { change, index } if change.is_zero() => AtomRef::Atom {
13310×
                change,
13320×
                index: remap.get(&(*node, index)).copied().unwrap_or(index),
13330×
            },
13348×
            other => other,
1335
        }
13368×
    };
13375×
    let ops = wc
13385×
        .tree_ops
13395×
        .iter()
13405×
        .enumerate()
13418×
        .filter(|(i, _)| ops_sel[*i])
13425×
        .map(|(_, o)| o.clone())
13435×
        .collect();
13445×
    let edits = wc
13455×
        .edits
13465×
        .iter()
13475×
        .enumerate()
134810×
        .filter(|(j, _)| edits_sel[*j])
13495×
        .map(|(_, e)| match e {
1350
            Edit::Insert {
13514×
                node,
13524×
                after,
13534×
                before,
13544×
                lines,
13554×
            } => Edit::Insert {
13564×
                node: *node,
13574×
                after: map_ref(*after, node),
13584×
                before: map_ref(*before, node),
13594×
                lines: lines.clone(),
13604×
            },
13610×
            other => other.clone(),
13624×
        })
13635×
        .collect();
13645×
    (ops, edits)
13655×
}
1366
1367
/// Render each tree operation and edit of `change` on its own, numbered.
13687×
pub fn render_hunks(change: &Change, base: &State, base_snapshot: &Snapshot) -> Vec<Hunk> {
13697×
    let by_node = base_snapshot.tree.by_node();
13707×
    let mut new_names: HashMap<NodeId, (NodeId, String, NodeKind)> = HashMap::new();
13718×
    for op in &change.tree_ops {
1372
        if let TreeOp::AddNode {
13738×
            node,
13748×
            parent,
13758×
            name,
13768×
            kind,
1377
            ..
13788×
        } = op
13798×
        {
13808×
            new_names.insert(*node, (*parent, name.clone(), *kind));
13818×
        }
1382
    }
13837×
    let mut out = Vec::new();
13848×
    for (i, op) in change.tree_ops.iter().enumerate() {
13858×
        let one = Change {
13868×
            tree_ops: vec![op.clone()],
13878×
            edits: vec![],
13888×
            ..change.clone()
13898×
        };
13908×
        let path = path_of_node(&op.node(), &by_node, &new_names).unwrap_or_default();
13918×
        out.push(Hunk {
13928×
            index: i,
13938×
            path,
13948×
            text: render_change(&one, base, base_snapshot),
13958×
        });
13968×
    }
139713×
    for (j, e) in change.edits.iter().enumerate() {
139813×
        let one = Change {
139913×
            tree_ops: vec![],
140013×
            edits: vec![e.clone()],
140113×
            ..change.clone()
140213×
        };
140313×
        let path = path_of_node(&e.node(), &by_node, &new_names).unwrap_or_default();
140413×
        out.push(Hunk {
140513×
            index: change.tree_ops.len() + j,
140613×
            path,
140713×
            text: render_change(&one, base, base_snapshot),
140813×
        });
140913×
    }
14107×
    out
14117×
}
1412
1413
/// One file's part of a diff, for `oxy diff --json`.
1414
#[derive(Clone, Debug)]
1415
pub struct FileDiff {
1416
    pub path: String,
1417
    /// `added`, `removed`, `modified`, `renamed`, `mode`, `replaced`.
1418
    pub kind: String,
1419
    pub hunks: Vec<DiffHunk>,
1420
    /// For renames, the previous path.
1421
    pub from: Option<String>,
1422
}
1423
1424
/// Lines inserted after `base_line` (0 = before the first line) and lines
1425
/// removed, with their base line numbers.
1426
#[derive(Clone, Debug, Default)]
1427
pub struct DiffHunk {
1428
    pub base_line: u32,
1429
    pub added: Vec<Vec<u8>>,
1430
    pub removed: Vec<(u32, Vec<u8>)>,
1431
}
1432
1433
impl Repo {
1434
    /// The content of `path` in a state: `heads`, or the working copy's base.
143525×
    pub fn file_at(&self, path: &str, heads: Option<&[ChangeHash]>) -> Result<Vec<u8>> {
1436
        // The state's history and tree, then the one file's graph: nothing
1437
        // else is built or rendered (oxygen#92).
1438
        // The working copy's base, and a state named by its heads (`-r
1439
        // main` on main), come from the workspace's state index.
144025×
        let base = if self.is_bare() {
14415×
            None
1442
        } else {
144320×
            Some(self.working_copy()?.1.deps)
1444
        };
144525×
        let same = |a: &[ChangeHash], b: &[ChangeHash]| {
14461×
            let (mut a, mut b) = (a.to_vec(), b.to_vec());
14471×
            a.sort();
14481×
            b.sort();
14491×
            a == b
14501×
        };
145125×
        let mut state = match (heads, base) {
14521×
            (Some(h), Some(b)) if same(h, &b) => self.load_state_indexed(&b)?,
14535×
            (Some(h), _) => self.load_state_history(h)?,
145419×
            (None, Some(b)) => self.load_state_indexed(&b)?,
14550×
            (None, None) => return fail("this is a bare repository: it has no working copy"),
1456
        };
145725×
        let view = state.tree().view();
145825×
        let Some(node) = view.entries.get(path).map(|e| e.node) else {
14590×
            return fail(format!("{path} is not in that state"));
1460
        };
146125×
        self.load_graphs_of(&mut state, &[node])?;
146224×
        let snapshot = state.materialize_paths(view, [path]);
146324×
        let Some(f) = snapshot.files.get(path) else {
14640×
            return fail(format!("{path} is not in that state"));
1465
        };
146624×
        match &f.content {
14670×
            FileContent::Dir => fail(format!("{path} is a directory")),
146824×
            FileContent::Text { bytes, .. } => Ok(bytes.clone()),
14690×
            FileContent::Opaque { blobs } => match blobs.first() {
14700×
                Some(b) => self.read_blob(b),
14710×
                None => Ok(vec![]),
1472
            },
1473
        }
147425×
    }
1475
1476
    /// Restore `paths` (files or directories) to the working copy's base:
1477
    /// edits are undone, additions removed, removals put back. Returns the
1478
    /// number of paths touched.
14792×
    pub fn discard(&self, paths: &[String]) -> Result<usize> {
14802×
        let _wc = self.lock_working_copy()?;
14812×
        let snap = self.snapshot_status("oxy discard")?;
14827×
        let under = |p: &str| {
14837×
            paths
14847×
                .iter()
14857×
                .any(|x| p == x || p.starts_with(&format!("{}/", x.trim_end_matches('/'))))
14867×
        };
14872×
        let attrs = Repo::state_attributes(&snap.base_snapshot);
14882×
        let mut n = 0;
14893×
        for s in &snap.statuses {
14903×
            if !under(&s.path) {
14911×
                continue;
14922×
            }
14932×
            match snap.base_snapshot.files.get(&s.path) {
1494
                None => {
1495
                    // Added (or the new name of a rename): remove it.
14961×
                    let full = self.root.join(&s.path);
14971×
                    if full.is_dir() {
14980×
                        let _ = fs::remove_dir_all(&full);
14991×
                    } else {
15001×
                        let _ = fs::remove_file(&full);
15011×
                    }
15021×
                    n += 1;
1503
                }
15041×
                Some(f) => {
15051×
                    match &f.content {
15060×
                        FileContent::Dir => fs::create_dir_all(self.root.join(&s.path))?,
15071×
                        FileContent::Text { bytes, .. } => {
15081×
                            let on_disk: std::borrow::Cow<[u8]> = if attrs.lookup(&s.path).eol
15091×
                                == Some(crate::attributes::Eol::Crlf)
1510
                            {
15110×
                                crate::attributes::to_crlf(bytes).into()
1512
                            } else {
15131×
                                bytes.as_slice().into()
1514
                            };
15151×
                            self.write_file(&s.path, &on_disk, f.mode.exec)?;
1516
                        }
15170×
                        FileContent::Opaque { blobs } => {
15180×
                            let bytes = match blobs.first() {
15190×
                                Some(b) => self.read_blob(b)?,
15200×
                                None => vec![],
1521
                            };
15220×
                            if f.kind == NodeKind::Symlink {
15230×
                                self.write_symlink(&s.path, &bytes)?;
15240×
                            } else if f.kind == NodeKind::File {
15250×
                                self.write_file(&s.path, &bytes, f.mode.exec)?;
15260×
                            }
1527
                        }
1528
                    }
15291×
                    n += 1;
1530
                }
1531
            }
1532
        }
1533
        // A rename's old name is not in the statuses; put it back too.
15344×
        for (p, f) in &snap.base_snapshot.files {
15354×
            if under(p)
15361×
                && !self.root.join(p).exists()
15370×
                && f.kind != NodeKind::Dir
15380×
                && f.kind != NodeKind::Subrepo
15390×
                && !snap.statuses.iter().any(|s| s.path == *p)
1540
            {
15410×
                let bytes = match &f.content {
15420×
                    FileContent::Text { bytes, .. } => bytes.clone(),
15430×
                    FileContent::Opaque { blobs } => blobs
15440×
                        .first()
15450×
                        .map(|b| self.read_blob(b))
15460×
                        .transpose()?
15470×
                        .unwrap_or_default(),
15480×
                    FileContent::Dir => continue,
1549
                };
15500×
                if f.kind == NodeKind::Symlink {
15510×
                    self.write_symlink(p, &bytes)?
1552
                } else {
15530×
                    self.write_file(p, &bytes, f.mode.exec)?
1554
                }
15550×
                n += 1;
15564×
            }
1557
        }
15582×
        self.drop_manifest();
15592×
        Ok(n)
15602×
    }
1561
1562
    /// Undo the working-copy hunks `indices` (as `hunks` numbers them) on
1563
    /// disk, keeping the others: the files are rewritten from the base plus
1564
    /// the remaining hunks.
15651×
    pub fn discard_hunks(&self, indices: &[usize]) -> Result<usize> {
15661×
        let _wc = self.lock_working_copy()?;
15671×
        let (snap, hunks) = self.hunks()?;
15681×
        let keep: Vec<usize> = hunks
15691×
            .iter()
15701×
            .map(|h| h.index)
15711×
            .filter(|i| !indices.contains(i))
15721×
            .collect();
15731×
        let (ops, edits) = select_hunks(&snap.wc, &keep);
15741×
        let dropped_nodes: BTreeSet<NodeId> = hunks
15751×
            .iter()
15761×
            .filter(|h| indices.contains(&h.index))
15771×
            .map(|h| {
15781×
                if h.index < snap.wc.tree_ops.len() {
15790×
                    snap.wc.tree_ops[h.index].node()
1580
                } else {
15811×
                    snap.wc.edits[h.index - snap.wc.tree_ops.len()].node()
1582
                }
15831×
            })
15841×
            .collect();
15851×
        let mut partial = snap.wc.clone();
15861×
        partial.tree_ops = ops;
15871×
        partial.edits = edits;
15881×
        partial.normalize();
15891×
        let mut st = snap.base.clone();
15901×
        st.add_unchecked(partial);
1591
        // Every file of the target is rendered: build the graphs the
1592
        // partial snapshot left out.
15931×
        self.load_all_graphs(&mut st)?;
15941×
        let target = st.materialize();
15951×
        let by_node_target = target.tree.by_node();
15961×
        let by_node_base = snap.base_snapshot.tree.by_node();
15971×
        let attrs = Repo::state_attributes(&target);
15981×
        let mut n = 0;
15991×
        for node in dropped_nodes {
16001×
            match by_node_target.get(&node) {
16011×
                Some(e) => {
16021×
                    let f = &target.files[&e.path];
16031×
                    match &f.content {
16040×
                        FileContent::Dir => {}
16051×
                        FileContent::Text { bytes, .. } => {
16061×
                            let on_disk: std::borrow::Cow<[u8]> = if attrs.lookup(&e.path).eol
16071×
                                == Some(crate::attributes::Eol::Crlf)
1608
                            {
16090×
                                crate::attributes::to_crlf(bytes).into()
1610
                            } else {
16111×
                                bytes.as_slice().into()
1612
                            };
16131×
                            self.write_file(&e.path, &on_disk, f.mode.exec)?;
1614
                        }
16150×
                        FileContent::Opaque { blobs } => {
16160×
                            let bytes = blobs
16170×
                                .first()
16180×
                                .map(|b| self.read_blob(b))
16190×
                                .transpose()?
16200×
                                .unwrap_or_default();
16210×
                            if f.kind == NodeKind::Symlink {
16220×
                                self.write_symlink(&e.path, &bytes)?
1623
                            } else {
16240×
                                self.write_file(&e.path, &bytes, f.mode.exec)?
1625
                            }
1626
                        }
1627
                    }
1628
                    // A discarded rename: the new name goes.
16291×
                    if let Some(old_path) = snap
16301×
                        .statuses
16311×
                        .iter()
16321×
                        .find(|s| {
16331×
                            s.status == ChangeStatus::Renamed && !target.files.contains_key(&s.path)
16341×
                        })
16351×
                        .map(|s| s.path.clone())
16360×
                    {
16370×
                        let _ = fs::remove_file(self.root.join(old_path));
16381×
                    }
16391×
                    n += 1;
1640
                }
1641
                None => {
1642
                    // The node exists in neither target nor base with a live path: an addition to remove.
16430×
                    if let Some(added) = snap.statuses.iter().find(|s| {
16440×
                        s.status == ChangeStatus::Added
16450×
                            && !target.files.contains_key(&s.path)
16460×
                            && !by_node_base.contains_key(&node)
16470×
                    }) {
16480×
                        let full = self.root.join(&added.path);
16490×
                        if full.is_dir() {
16500×
                            let _ = fs::remove_dir_all(&full);
16510×
                        } else {
16520×
                            let _ = fs::remove_file(&full);
16530×
                        }
16540×
                        n += 1;
16550×
                    }
1656
                }
1657
            }
1658
        }
16591×
        self.drop_manifest();
16601×
        Ok(n)
16611×
    }
1662
1663
    /// The diff of the working copy (`None`) or of a change, per file with
1664
    /// line-numbered hunks (spec: `oxy diff --json`).
16655×
    pub fn diff_files(&self, change: Option<&ChangeHash>) -> Result<Vec<FileDiff>> {
16665×
        let (c, base, base_snapshot) = match change {
16672×
            Some(h) => {
16682×
                let c = self.store.get_change(h)?;
16692×
                let (base, snapshot) = self.change_base(&c)?;
16702×
                (c, base, snapshot)
1671
            }
16723×
            None => self.working_copy_with_base()?,
1673
        };
16745×
        Ok(diff_files_of(&c, &base, &base_snapshot))
16755×
    }
1676
1677
    /// The snapshot a command would take, without taking it, when the
1678
    /// status cache holds: every file is as the last snapshot left it, so
1679
    /// that snapshot's working-copy change is the answer. Its base comes
1680
    /// from the state index, the `.oxyattributes` files from disk. `None`
1681
    /// when a snapshot must be taken, and when there is nothing to commit
1682
    /// (the snapshot then says so). A conflicted base never gets here: the
1683
    /// cache does not hold for one.
1684615×
    pub(crate) fn snapshot_from_cache(&self) -> Result<Option<SnapshotResult>> {
1685615×
        let Some(statuses) = self.status_by_manifest()? else {
1686419×
            return Ok(None);
1687
        };
1688196×
        if statuses.is_empty() {
16892×
            return Ok(None);
1690194×
        }
1691194×
        let _t = crate::timing::phase("snapshot: from the status cache");
1692194×
        let (wc_hash, wc) = self.working_copy()?;
1693194×
        let base = self.load_state_indexed(&wc.deps)?;
1694194×
        let (base, base_snapshot) = self.render_base_for(&wc, base)?;
1695194×
        let attribute_files: Vec<(String, Vec<u8>)> = match self.read_manifest()? {
1696194×
            Some((_, _, m)) => m
1697194×
                .entries
1698194×
                .keys()
1699585×
                .filter(|p| is_attributes(p))
1700194×
                .filter_map(|p| fs::read(self.root.join(p)).ok().map(|b| (p.clone(), b)))
1701194×
                .collect(),
17020×
            None => Vec::new(),
1703
        };
1704194×
        let attributes = crate::attributes::Attributes::from_files(
1705194×
            attribute_files
1706194×
                .iter()
1707194×
                .map(|(p, b)| (p.as_str(), b.as_slice())),
1708
        );
1709194×
        Ok(Some(SnapshotResult {
1710194×
            wc_hash,
1711194×
            wc,
1712194×
            base,
1713194×
            base_snapshot,
1714194×
            statuses,
1715194×
            changed: false,
1716194×
            resolves: false,
1717194×
            contributors: Vec::new(),
1718194×
            attributes,
1719194×
            untracked_nested: self.untracked_nested.borrow().clone(),
1720194×
            manifest: None,
1721194×
        }))
1722615×
    }
1723
1724
    /// The working-copy change with its base state and a snapshot of the
1725
    /// base, for showing what the working copy changes ([`render_change`],
1726
    /// [`diff_files_of`]). While the status cache holds (every file as the
1727
    /// last snapshot left it), the stored working-copy change is the
1728
    /// answer, no snapshot is taken, and the base's snapshot holds its tree
1729
    /// but no file; otherwise a snapshot makes all three.
17304×
    pub fn working_copy_with_base(&self) -> Result<(Change, State, Snapshot)> {
17314×
        if self.status_by_manifest()?.is_some() {
17322×
            let (_, wc) = self.working_copy()?;
17332×
            let base = self.load_state_indexed(&wc.deps)?;
17342×
            let (base, snapshot) = self.tree_base_for(&wc, base)?;
17352×
            return Ok((wc, base, snapshot));
17362×
        }
17372×
        let snap = self.snapshot_status("oxy diff")?;
17382×
        Ok((snap.wc, snap.base, snap.base_snapshot))
17394×
    }
1740
1741
    /// The log restricted to changes touching `path` (its node, so renames
1742
    /// are followed), on the current bookmark.
17435×
    pub fn log_for_path(&self, path: &str) -> Result<Vec<LogEntry>> {
17445×
        let heads = self.bookmark_heads()?;
17455×
        if self.is_bare() {
17461×
            return self.log_for_path_in(path, &heads);
17474×
        }
17484×
        let entries = self.log()?;
17494×
        let (_, wc) = self.working_copy()?;
1750
        // The path's node from the trees alone: the base's (from the
1751
        // workspace's state index), else the bookmark's. Nothing is
1752
        // rendered.
17534×
        let node_in = |state: State| state.tree().view().entries.get(path).map(|e| e.node);
17544×
        let node = match node_in(self.load_state_indexed(&wc.deps)?) {
17554×
            Some(n) => Some(n),
17560×
            None => node_in(self.load_state_history(&heads)?),
1757
        };
17584×
        let Some(node) = node else {
17590×
            return fail(format!("{path} is not tracked"));
1760
        };
17614×
        Ok(self.entries_touching(entries, node))
17625×
    }
1763
1764
    /// The log of the state with these heads restricted to changes touching
1765
    /// `path` (its node, so renames are followed).
17662×
    pub fn log_for_path_in(&self, path: &str, heads: &[ChangeHash]) -> Result<Vec<LogEntry>> {
17672×
        self.log_for_path_of(&self.load_state_history(heads)?, path, None)
17682×
    }
1769
1770
    /// The changes of a loaded state touching `path`, newest first, at most
1771
    /// `limit` of them. The path is found in the state's tree alone, so no
1772
    /// file is rendered, and the walk stops once `limit` are found.
17735×
    pub fn log_for_path_of(
17745×
        &self,
17755×
        state: &State,
17765×
        path: &str,
17775×
        limit: Option<usize>,
17785×
    ) -> Result<Vec<LogEntry>> {
17795×
        let Some(node) = state.tree().view().entries.get(path).map(|e| e.node) else {
17801×
            return fail(format!("{path} is not in that state"));
1781
        };
17824×
        Ok(self.entries_touching_up_to(self.log_of(state), node, limit))
17835×
    }
1784
17854×
    fn entries_touching(&self, entries: Vec<LogEntry>, node: NodeId) -> Vec<LogEntry> {
17864×
        self.entries_touching_up_to(entries, node, None)
17874×
    }
1788
17898×
    fn entries_touching_up_to(
17908×
        &self,
17918×
        entries: Vec<LogEntry>,
17928×
        node: NodeId,
17938×
        limit: Option<usize>,
17948×
    ) -> Vec<LogEntry> {
17958×
        let mut touched = self.touched();
17968×
        if limit.is_none() {
17977×
            let hashes: Vec<ChangeHash> = entries.iter().map(|e| e.hash).collect();
17987×
            touched.fill(self, &hashes);
17991×
        }
18008×
        let wanted = HashSet::from([node]);
18018×
        let mut out = Vec::new();
180228×
        for e in entries {
180328×
            if limit.is_some_and(|n| out.len() >= n) {
18041×
                break;
180527×
            }
180627×
            if touched.touches(self, &e.hash, &wanted) {
180718×
                out.push(e);
180818×
            }
1809
        }
18108×
        touched.save();
18118×
        out
18128×
    }
1813
}
1814
1815
/// Per-file hunks of `change` against `base`.
18165×
pub fn diff_files_of(change: &Change, base: &State, base_snapshot: &Snapshot) -> Vec<FileDiff> {
18175×
    let by_node = base_snapshot.tree.by_node();
18185×
    let mut new_names: HashMap<NodeId, (NodeId, String, NodeKind)> = HashMap::new();
18195×
    for op in &change.tree_ops {
1820
        if let TreeOp::AddNode {
18212×
            node,
18222×
            parent,
18232×
            name,
18242×
            kind,
1825
            ..
18263×
        } = op
18272×
        {
18282×
            new_names.insert(*node, (*parent, name.clone(), *kind));
18292×
        }
1830
    }
18319×
    let path_of = |n: &NodeId| -> String {
18329×
        path_of_node(n, &by_node, &new_names).unwrap_or_else(|| format!("<node {}>", n.short(8)))
18339×
    };
18345×
    let mut files: BTreeMap<NodeId, FileDiff> = BTreeMap::new();
18355×
    let mut order: Vec<NodeId> = Vec::new();
183614×
    let mut entry = |files: &mut BTreeMap<NodeId, FileDiff>, n: NodeId, kind: &str| {
183714×
        if let std::collections::btree_map::Entry::Vacant(v) = files.entry(n) {
18389×
            order.push(n);
18399×
            v.insert(FileDiff {
18409×
                path: path_of(&n),
18419×
                kind: kind.to_string(),
18429×
                hunks: vec![],
18439×
                from: None,
18449×
            });
18459×
        }
184614×
    };
18475×
    for op in &change.tree_ops {
18483×
        match op {
18492×
            TreeOp::AddNode { node, kind, .. } => {
18502×
                if *kind != NodeKind::Dir {
18512×
                    entry(&mut files, *node, "added");
18522×
                }
1853
            }
18541×
            TreeOp::RemoveNode { node, .. } => {
18551×
                entry(&mut files, *node, "removed");
18561×
                if let Some(e) = by_node.get(node) {
18571×
                    files.get_mut(node).unwrap().path = e.path.clone();
18581×
                }
1859
            }
1860
            TreeOp::Move {
18610×
                node, parent, name, ..
1862
            } => {
18630×
                entry(&mut files, *node, "renamed");
18640×
                let f = files.get_mut(node).unwrap();
18650×
                f.from = by_node.get(node).map(|e| e.path.clone());
18660×
                let dir = if parent.is_root() {
18670×
                    String::new()
1868
                } else {
18690×
                    path_of_node(parent, &by_node, &new_names).unwrap_or_default()
1870
                };
18710×
                f.path = if dir.is_empty() {
18720×
                    name.clone()
1873
                } else {
18740×
                    format!("{dir}/{name}")
1875
                };
1876
            }
18770×
            TreeOp::SetMode { node, .. } => entry(&mut files, *node, "mode"),
1878
        }
1879
    }
1880
    // Base line numbers per node, 1-based.
18815×
    let mut line_of: HashMap<NodeId, HashMap<(ChangeHash, u32), u32>> = HashMap::new();
188211×
    let mut lines_for = |n: &NodeId| -> HashMap<(ChangeHash, u32), u32> {
188311×
        line_of
188411×
            .entry(*n)
188511×
            .or_insert_with(|| {
18868×
                base.live_lines(n)
18878×
                    .into_iter()
18888×
                    .enumerate()
188911×
                    .map(|(i, (k, _))| (k, i as u32 + 1))
18908×
                    .collect()
18918×
            })
189211×
            .clone()
189311×
    };
189411×
    for e in &change.edits {
189511×
        let n = e.node();
189611×
        let is_new = new_names.contains_key(&n);
189711×
        entry(&mut files, n, if is_new { "added" } else { "modified" });
189811×
        let f = files.get_mut(&n).unwrap();
189911×
        match e {
19009×
            Edit::Insert { after, lines, .. } => {
19019×
                let map = lines_for(&n);
19029×
                let base_line = match after {
19033×
                    AtomRef::Start => 0,
19040×
                    AtomRef::End => map.len() as u32,
19056×
                    AtomRef::Atom { change, index } if change.is_zero() => {
19060×
                        f.hunks.last().map(|h| h.base_line).unwrap_or(0)
1907
                    }
19086×
                    AtomRef::Atom { change, index } => {
19096×
                        map.get(&(*change, *index)).copied().unwrap_or(0)
1910
                    }
1911
                };
19129×
                f.hunks.push(DiffHunk {
19139×
                    base_line,
19149×
                    added: lines.to_vec(),
19159×
                    removed: vec![],
19169×
                });
1917
            }
19182×
            Edit::Delete { atoms, .. } => {
19192×
                let map = lines_for(&n);
19202×
                let mut removed = Vec::new();
19212×
                for r in atoms {
19222×
                    for i in r.from..r.to {
19232×
                        let line = map.get(&(r.change, i)).copied().unwrap_or(0);
19242×
                        let text = base
19252×
                            .file(&n)
19262×
                            .and_then(|g| g.content(&(r.change, i)))
19272×
                            .unwrap_or(b"")
19282×
                            .to_vec();
19292×
                        removed.push((line, text));
1930
                    }
1931
                }
19322×
                let base_line = removed
19332×
                    .first()
19342×
                    .map(|(l, _)| l.saturating_sub(1))
19352×
                    .unwrap_or(0);
19362×
                f.hunks.push(DiffHunk {
19372×
                    base_line,
19382×
                    added: vec![],
19392×
                    removed,
19402×
                });
1941
            }
1942
            Edit::Replace { .. } => {
19430×
                if !is_new {
19440×
                    f.kind = "replaced".into();
19450×
                }
1946
            }
1947
        }
1948
    }
19499×
    order.into_iter().filter_map(|n| files.remove(&n)).collect()
19505×
}
1951
1952
/// Builds the tree ops and edits of a working-copy change against a base.
1953
/// `BLAKE3("oxy node 1" 0 seed kind path)`, truncated: a node identifier
1954
/// that the same seed and path always give (never the root's).
195559×
fn seeded_node(seed: &[u8; 32], path: &str, kind: NodeKind) -> NodeId {
195659×
    let mut h = blake3::Hasher::new();
195759×
    h.update(b"oxy node 1\0");
195859×
    h.update(seed);
195959×
    h.update(&[match kind {
196045×
        NodeKind::File => 1,
196113×
        NodeKind::Dir => 2,
19620×
        NodeKind::Symlink => 3,
19631×
        NodeKind::Subrepo => 4,
1964
    }]);
196559×
    h.update(path.as_bytes());
196659×
    let mut id = [0u8; 16];
196759×
    id.copy_from_slice(&h.finalize().as_bytes()[..16]);
196859×
    if id == [0; 16] {
19690×
        id[15] = 1;
197059×
    }
197159×
    NodeId(id)
197259×
}
1973
1974
struct ChangeBuilder<'a> {
1975
    base: &'a State,
1976
    base_snapshot: &'a Snapshot,
1977
    tree_ops: Vec<TreeOp>,
1978
    edits: Vec<Edit>,
1979
    statuses: Vec<PathStatus>,
1980
    dir_nodes: HashMap<String, NodeId>,
1981
    reuse: HashMap<String, (NodeId, NodeKind)>,
1982
    /// Changes that contributed to conflicts this working copy resolves.
1983
    contributors: BTreeSet<ChangeHash>,
1984
    resolves: bool,
1985
    attrs: crate::attributes::Attributes,
1986
    blobs: HashMap<String, ObjectRef>,
1987
    /// Opaque files whose replace conflict the content settles.
1988
    resolve: HashSet<String>,
1989
    /// When set, new nodes' identifiers derive from it and their paths.
1990
    node_seed: Option<[u8; 32]>,
1991
    /// For a Git import, the base's dead directories by where they were
1992
    /// (see `ensure_dir`), worked out when first needed.
1993
    dead_dirs: Option<HashMap<(NodeId, String), (NodeId, crate::tree::OpKey)>>,
1994
    /// Text edits of edited files, worked out in parallel beforehand
1995
    /// (`diff_in_parallel`); a file not here is diffed when it is updated.
1996
    diffs: HashMap<String, Vec<Edit>>,
1997
}
1998
1999
impl<'a> ChangeBuilder<'a> {
20001856×
    fn new(
20011856×
        base: &'a State,
20021856×
        base_snapshot: &'a Snapshot,
20031856×
        reuse: HashMap<String, (NodeId, NodeKind)>,
20041856×
    ) -> Self {
20051856×
        let mut dir_nodes: HashMap<String, NodeId> = HashMap::new();
20061856×
        dir_nodes.insert(String::new(), NodeId::ROOT);
200717553×
        for (p, e) in base_snapshot.tree.entries.iter() {
200817553×
            if e.kind == NodeKind::Dir {
2009535×
                dir_nodes.insert(p.clone(), e.node);
201017018×
            }
2011
        }
20121856×
        ChangeBuilder {
20131856×
            base,
20141856×
            base_snapshot,
20151856×
            tree_ops: vec![],
20161856×
            edits: vec![],
20171856×
            statuses: vec![],
20181856×
            dir_nodes,
20191856×
            reuse,
20201856×
            contributors: BTreeSet::new(),
20211856×
            resolves: false,
20221856×
            attrs: crate::attributes::Attributes::default(),
20231856×
            blobs: HashMap::new(),
20241856×
            resolve: HashSet::new(),
20251856×
            node_seed: None,
20261856×
            dead_dirs: None,
20271856×
            diffs: HashMap::new(),
20281856×
        }
20291856×
    }
2030
2031
    /// Diff the edited text files among `entries` against their base
2032
    /// renderings at once, on every core, for `update_path` to take: the
2033
    /// same diff it would make, only not one file after another.
20341856×
    fn diff_in_parallel(&mut self, entries: &BTreeMap<String, FsEntry>) {
2035
        use rayon::prelude::*;
20361856×
        let files = &self.base_snapshot.files;
20371856×
        let edited: Vec<(&String, &FsEntry, &crate::state::FileState)> = entries
20381856×
            .iter()
203918508×
            .filter_map(|(p, e)| {
204018508×
                let x = files.get(p)?;
204112543×
                (x.kind == e.kind && !e.unchanged && !self.opaque_for(p, e)).then_some((p, e, x))
204218508×
            })
20431856×
            .collect();
2044
        // Below this, starting the threads costs more than it saves.
20451856×
        if edited.len() < 16 {
20461846×
            return;
204710×
        }
204810×
        let this = &*self;
204910×
        let attrs = &this.attrs;
205010×
        let diffs: Vec<(String, Vec<Edit>)> = edited
205110×
            .par_iter()
20525560×
            .filter_map(|(p, e, x)| {
2053
                let FileContent::Text {
20545560×
                    bytes,
20555560×
                    materialized,
20565560×
                } = &x.content
2057
                else {
20580×
                    return None;
2059
                };
20605560×
                if materialized.is_conflicted() {
20610×
                    return None;
20625560×
                }
20635560×
                let disk_text = if attrs.lookup(p).eol.is_some() {
20640×
                    std::sync::Arc::new(crate::attributes::normalize_eol(&e.content))
2065
                } else {
20665560×
                    e.content.clone()
2067
                };
20685560×
                if *bytes == *disk_text {
20695480×
                    return None;
207080×
                }
207180×
                let keys = materialized.live_atoms();
207280×
                let lines = crate::diff::split_lines(bytes);
207380×
                (keys.len() == lines.len()).then(|| {
207480×
                    let edits = crate::diff::text_edits_of(x.node, &keys, &lines, &disk_text);
207580×
                    ((*p).clone(), edits)
207680×
                })
20775560×
            })
207810×
            .collect();
207910×
        self.diffs = diffs.into_iter().collect();
20801856×
    }
2081
20821856×
    fn with_attributes(mut self, attrs: crate::attributes::Attributes) -> Self {
20831856×
        self.attrs = attrs;
20841856×
        self
20851856×
    }
2086
2087
    /// Whether a file is opaque: forced by `binary`, forced text by `text`
2088
    /// only when it has no NUL bytes, else sniffed.
2089
    /// The blob for an opaque entry: the cached one, else stored now.
2090126×
    fn blob_of(
2091126×
        &mut self,
2092126×
        repo: &Repo,
2093126×
        path: &str,
2094126×
        e: &FsEntry,
2095126×
        nocompress: bool,
2096126×
    ) -> Result<ObjectRef> {
2097126×
        let b = match e.blob {
20980×
            Some(b) => b,
2099126×
            None => repo.store_blob_for(&e.content, nocompress)?,
2100
        };
2101126×
        self.blobs.insert(path.to_string(), b);
2102126×
        Ok(b)
2103126×
    }
2104
210522558×
    fn opaque_for(&self, path: &str, e: &FsEntry) -> bool {
210622558×
        if e.blob.is_some() {
21078×
            return true;
210822550×
        }
210922550×
        if e.kind == NodeKind::Symlink || e.kind == NodeKind::Subrepo {
211075×
            return true;
211122475×
        }
211222475×
        match self.attrs.lookup(path).binary {
211312×
            Some(true) => true,
21140×
            Some(false) => is_binary(&e.content),
211522463×
            None => is_binary(&e.content),
2116
        }
211722558×
    }
2118
2119
    /// Text content as stored: `\r\n` normalized for `eol=` files.
212014142×
    fn stored_text(
212114142×
        &self,
212214142×
        path: &str,
212314142×
        content: &std::sync::Arc<Vec<u8>>,
212414142×
    ) -> std::sync::Arc<Vec<u8>> {
212514142×
        if self.attrs.lookup(path).eol.is_some() {
21267×
            std::sync::Arc::new(crate::attributes::normalize_eol(content))
2127
        } else {
212814135×
            content.clone()
2129
        }
213014142×
    }
2131
2132
    /// The identifier of a node added at `path`: reused when asked, derived
2133
    /// from the seed when there is one, random otherwise.
21346087×
    fn new_node(&self, path: &str, kind: NodeKind) -> NodeId {
21356087×
        if let Some(n) = self.reused_node(path, kind) {
2136134×
            return n;
21375953×
        }
21385953×
        match &self.node_seed {
213959×
            Some(seed) => seeded_node(seed, path, kind),
21405894×
            None => NodeId::random(),
2141
        }
21426087×
    }
2143
21446087×
    fn reused_node(&self, path: &str, kind: NodeKind) -> Option<NodeId> {
21456087×
        self.reuse
21466087×
            .get(path)
21476087×
            .filter(|(_, k)| *k == kind)
21486087×
            .map(|(n, _)| *n)
21496087×
    }
2150
2151
    /// A dead directory last placed at (`parent`, `name`) in the base.
215215×
    fn revivable_dir(
215315×
        &mut self,
215415×
        parent: NodeId,
215515×
        name: &str,
215615×
    ) -> Option<(NodeId, crate::tree::OpKey)> {
215715×
        let base = self.base;
215815×
        self.dead_dirs
215915×
            .get_or_insert_with(|| base.tree().dead_dirs())
216015×
            .get(&(parent, name.to_string()))
216115×
            .copied()
216215×
    }
2163
21645966×
    fn ensure_dir(&mut self, path: &str) -> NodeId {
21655966×
        if let Some(n) = self.dir_nodes.get(path) {
21665817×
            return *n;
2167149×
        }
2168149×
        let mut parent = NodeId::ROOT;
2169149×
        let mut prefix = String::new();
2170168×
        for comp in path.split('/') {
2171168×
            if !prefix.is_empty() {
217219×
                prefix.push('/');
2173149×
            }
2174168×
            prefix.push_str(comp);
2175168×
            let known = self.dir_nodes.get(&prefix).copied();
2176168×
            let revive = match known {
217713×
                Some(_) => None,
2178155×
                None if self.node_seed.is_some() => self.revivable_dir(parent, comp),
2179140×
                None => None,
2180
            };
2181168×
            parent = match (known, revive) {
218213×
                (Some(n), _) => n,
21832×
                (None, Some((node, old))) => {
2184
                    // Git has no identity for a directory: one that comes
2185
                    // back where it was is the same directory, brought back
2186
                    // with a move, so lines of history that placed files in
2187
                    // it before and after agree (oxygen#30).
21882×
                    self.tree_ops.push(TreeOp::Move {
21892×
                        node,
21902×
                        old: OpRef {
21912×
                            change: old.0,
21922×
                            index: old.1,
21932×
                        },
21942×
                        parent,
21952×
                        name: comp.to_string(),
21962×
                    });
21972×
                    self.dir_nodes.insert(prefix.clone(), node);
21982×
                    node
2199
                }
2200
                (None, None) => {
2201153×
                    let node = self.new_node(&prefix, NodeKind::Dir);
2202153×
                    self.tree_ops.push(TreeOp::AddNode {
2203153×
                        node,
2204153×
                        kind: NodeKind::Dir,
2205153×
                        mode: Mode::default(),
2206153×
                        parent,
2207153×
                        name: comp.to_string(),
2208153×
                    });
2209153×
                    self.dir_nodes.insert(prefix.clone(), node);
2210153×
                    node
2211
                }
2212
            };
2213
        }
2214149×
        parent
22155966×
    }
2216
22175934×
    fn add_path(&mut self, repo: &Repo, path: &str, e: &FsEntry) -> Result<()> {
22185934×
        let (dir, name) = split_path(path);
22195934×
        let parent = self.ensure_dir(dir);
22205934×
        let node = self.new_node(path, e.kind);
22215934×
        let opaque = self.opaque_for(path, e);
22225934×
        let nocompress = self.attrs.lookup(path).nocompress;
22235934×
        self.tree_ops.push(TreeOp::AddNode {
22245934×
            node,
22255934×
            kind: e.kind,
22265934×
            mode: Mode {
22275934×
                exec: e.exec,
22285934×
                opaque,
22295934×
            },
22305934×
            parent,
22315934×
            name: name.to_string(),
22325934×
        });
22335934×
        if opaque {
223491×
            let blob = self.blob_of(repo, path, e, nocompress)?;
223591×
            self.edits.push(Edit::Replace {
223691×
                node,
223791×
                old: None,
223891×
                new: Some(blob),
223991×
            });
22405843×
        } else if !e.content.is_empty() {
22415814×
            let content = self.stored_text(path, &e.content);
22425814×
            self.edits.push(Edit::Insert {
22435814×
                node,
22445814×
                after: crate::objects::AtomRef::Start,
22455814×
                before: crate::objects::AtomRef::End,
22465814×
                lines: crate::lines::Lines::split_shared(content),
22475814×
            });
22485814×
        }
22495934×
        self.statuses.push(PathStatus {
22505934×
            path: path.to_string(),
22515934×
            status: ChangeStatus::Added,
22525934×
        });
22535934×
        Ok(())
22545934×
    }
2255
2256
    /// Move the node at `old` to `new` and apply `e`'s content to it.
225732×
    fn move_path(
225832×
        &mut self,
225932×
        repo: &Repo,
226032×
        old: &str,
226132×
        new: &str,
226232×
        e: &FsEntry,
226332×
        expected: &crate::state::FileState,
226432×
    ) -> Result<()> {
226532×
        let placement = self.base_snapshot.tree.entries[old].placement;
226632×
        let (dir, name) = split_path(new);
226732×
        let parent = self.ensure_dir(dir);
226832×
        self.tree_ops.push(TreeOp::Move {
226932×
            node: expected.node,
227032×
            old: op_ref(placement),
227132×
            parent,
227232×
            name: name.to_string(),
227332×
        });
227432×
        for k in self.same_place(&expected.node, placement) {
22750×
            self.tree_ops.push(TreeOp::RemoveNode {
22760×
                node: expected.node,
22770×
                placement: op_ref(k),
22780×
            });
22790×
        }
228032×
        self.update_path(repo, old, e, expected)?;
2281
        // update_path reports under the old path; the rename is what the user sees.
228232×
        self.statuses.retain(|s| s.path != old);
228332×
        self.statuses.push(PathStatus {
228432×
            path: new.to_string(),
228532×
            status: ChangeStatus::Renamed,
228632×
        });
228732×
        Ok(())
228832×
    }
2289
2290
    /// For a Git import: a node the commit keeps is in one place, the one
2291
    /// its tree names, so any other live placement it has in the base goes;
2292
    /// and a node the tree cannot show at all (an orphan) goes too. Such a
2293
    /// placement is out of sight, under a directory another line of history
2294
    /// removed, where no diff of the tree would ever reach it (oxygen#30).
229588×
    fn retire_stray_placements(&mut self) {
229688×
        let mut retired: HashSet<(ChangeHash, u32)> = HashSet::new();
229788×
        let mut placed: BTreeSet<NodeId> = BTreeSet::new();
229899×
        for op in &self.tree_ops {
229999×
            match op {
230019×
                TreeOp::Move { node, old, .. } => {
230119×
                    retired.insert((old.change, old.index));
230219×
                    placed.insert(*node);
230319×
                }
230421×
                TreeOp::RemoveNode { placement, .. } => {
230521×
                    retired.insert((placement.change, placement.index));
230621×
                }
230759×
                TreeOp::AddNode { .. } | TreeOp::SetMode { .. } => {}
2308
            }
2309
        }
2310
        // Nodes kept where they were: what the base's tree view shows and
2311
        // this change neither moves nor removes.
231288×
        let mut kept: HashMap<NodeId, (ChangeHash, u32)> = HashMap::new();
2313241×
        for e in self.base_snapshot.tree.entries.values() {
2314241×
            if !retired.contains(&e.placement) {
2315204×
                kept.insert(e.node, e.placement);
2316204×
            }
2317
        }
2318
        // Only a node with several live placements can have a stray one,
2319
        // and the tree view names each as a conflict.
232088×
        let multi: BTreeSet<NodeId> = self
232188×
            .base_snapshot
232288×
            .tree
232388×
            .conflicts
232488×
            .iter()
232588×
            .filter_map(|c| match c {
23261×
                crate::tree::TreeConflict::MultiPlacement { node, .. } => Some(*node),
23276×
                _ => None,
23287×
            })
232988×
            .collect();
233088×
        let mut extra = Vec::new();
2331
        // A node whose only placements are under a directory another line
2332
        // removed (an orphan) is nowhere the tree can show, and Git's tree
2333
        // has no such path: it goes.
233488×
        for c in &self.base_snapshot.tree.conflicts {
23357×
            let crate::tree::TreeConflict::Orphan { node, .. } = c else {
23366×
                continue;
2337
            };
23381×
            if kept.contains_key(node) || placed.contains(node) {
23390×
                continue;
23401×
            }
23411×
            for (k, _) in self.base.tree().live_placements(node) {
23421×
                if retired.insert(k) {
23431×
                    extra.push(TreeOp::RemoveNode {
23441×
                        node: *node,
23451×
                        placement: op_ref(k),
23461×
                    });
23471×
                }
2348
            }
2349
        }
235088×
        for node in placed
235188×
            .iter()
235288×
            .chain(multi.iter().filter(|n| kept.contains_key(*n)))
2353
        {
235419×
            for (k, _) in self.base.tree().live_placements(node) {
235518×
                if retired.contains(&k) || kept.get(node) == Some(&k) {
235617×
                    continue;
23571×
                }
23581×
                retired.insert(k);
23591×
                extra.push(TreeOp::RemoveNode {
23601×
                    node: *node,
23611×
                    placement: op_ref(k),
23621×
                });
2363
            }
2364
        }
236588×
        if !extra.is_empty() {
23662×
            self.resolves = true;
23672×
            self.tree_ops.extend(extra);
236886×
        }
236988×
    }
2370
2371
    /// The node's other live placements at the same place as `k`, the one
2372
    /// the tree shows: two lines of history that put a node back where it
2373
    /// was each leave a placement, and the tree shows them as one file. A
2374
    /// change that removes or moves it retires them together, or the copy
2375
    /// left behind outlives its directory (oxygen#88).
2376160×
    fn same_place(&self, node: &NodeId, k: (ChangeHash, u32)) -> Vec<(ChangeHash, u32)> {
2377160×
        let tree = self.base.tree();
2378160×
        let Some(shown) = tree.placement(&k) else {
23790×
            return Vec::new();
2380
        };
2381160×
        tree.live_placements(node)
2382160×
            .into_iter()
2383162×
            .filter(|(o, p)| *o != k && p.parent == shown.parent && p.name == shown.name)
2384160×
            .map(|(o, _)| o)
2385160×
            .collect()
2386160×
    }
2387
2388128×
    fn remove_path(&mut self, path: &str, expected: &crate::state::FileState) {
2389128×
        let entry = &self.base_snapshot.tree.entries[path];
2390128×
        let placement = entry.placement;
2391128×
        self.tree_ops.push(TreeOp::RemoveNode {
2392128×
            node: expected.node,
2393128×
            placement: op_ref(placement),
2394128×
        });
2395128×
        for k in self.same_place(&expected.node, placement) {
23961×
            self.tree_ops.push(TreeOp::RemoveNode {
23971×
                node: expected.node,
23981×
                placement: op_ref(k),
23991×
            });
24001×
        }
2401128×
        if path.contains(".oxy-conflict-") || expected.is_conflicted() {
24027×
            self.resolves = true;
2403121×
        }
2404128×
        self.statuses.push(PathStatus {
2405128×
            path: path.to_string(),
2406128×
            status: ChangeStatus::Removed,
2407128×
        });
2408128×
    }
2409
241012575×
    fn update_path(
241112575×
        &mut self,
241212575×
        repo: &Repo,
241312575×
        path: &str,
241412575×
        e: &FsEntry,
241512575×
        expected: &crate::state::FileState,
241612575×
    ) -> Result<()> {
241712575×
        if expected.kind != e.kind {
24181×
            self.remove_path(path, expected);
24191×
            self.statuses.pop();
24201×
            self.add_path(repo, path, e)?;
24211×
            self.statuses.pop();
24221×
            self.statuses.push(PathStatus {
24231×
                path: path.to_string(),
24241×
                status: ChangeStatus::Modified,
24251×
            });
24261×
            return Ok(());
242712574×
        }
242812574×
        let entry = &self.base_snapshot.tree.entries[path];
242912574×
        let node = expected.node;
243012574×
        let mode_atom = entry.mode_atom.map(op_ref);
243112574×
        if e.unchanged {
2432
            // Known equal to the base's unconflicted rendering (spec
2433
            // §12.3); only the executable bit can differ.
24344246×
            if e.exec != expected.mode.exec {
24353×
                if let Some(old) = mode_atom {
24363×
                    self.tree_ops.push(TreeOp::SetMode {
24373×
                        node,
24383×
                        old,
24393×
                        mode: Mode {
24403×
                            exec: e.exec,
24413×
                            opaque: false,
24423×
                        },
24433×
                    });
24443×
                    self.statuses.push(PathStatus {
24453×
                        path: path.to_string(),
24463×
                        status: ChangeStatus::ModeChanged,
24473×
                    });
24483×
                }
24494243×
            }
24504246×
            return Ok(());
24518328×
        }
24528328×
        let mut status: Option<ChangeStatus> = None;
24538328×
        let wants_opaque = self.opaque_for(path, e);
24548328×
        let nocompress = self.attrs.lookup(path).nocompress;
24558328×
        let disk_text = self.stored_text(path, &e.content);
24568328×
        match &expected.content {
24570×
            FileContent::Dir => {}
2458
            FileContent::Text {
24598105×
                bytes,
24608105×
                materialized,
2461
            } => {
24628105×
                if materialized.is_conflicted() {
246333×
                    if bytes == &*disk_text {
24646×
                        return Ok(());
246527×
                    }
246627×
                    if has_conflict_markers(&e.content) {
24674×
                        self.statuses.push(PathStatus {
24684×
                            path: path.to_string(),
24694×
                            status: ChangeStatus::ConflictEdited,
24704×
                        });
24714×
                        return Ok(());
247223×
                    }
2473
                    // Resolution (spec §9.6): diff against the unconflicted lines
2474
                    // with each region as a gap, then retire every region atom.
2475
                    // Whatever the author kept from a region is re-inserted as
2476
                    // new atoms, which leaves the graph totally ordered.
247723×
                    let regions = self.base.conflict_regions(&node);
247823×
                    let mut edits = text_edits(node, &regions.plain, &disk_text);
247923×
                    if !regions.region_atoms.is_empty() {
248023×
                        edits.insert(
248123×
                            0,
248223×
                            Edit::Delete {
248323×
                                node,
248423×
                                atoms: ranges(&regions.region_atoms),
248523×
                            },
248623×
                        );
248723×
                    }
248823×
                    self.edits.extend(edits);
248923×
                    self.contributors.extend(regions.contributors);
249023×
                    self.resolves = true;
249123×
                    if e.exec != expected.mode.exec {
24920×
                        if let Some(old) = mode_atom {
24930×
                            self.tree_ops.push(TreeOp::SetMode {
24940×
                                node,
24950×
                                old,
24960×
                                mode: Mode {
24970×
                                    exec: e.exec,
24980×
                                    opaque: false,
24990×
                                },
25000×
                            });
25010×
                        }
250223×
                    }
250323×
                    self.statuses.push(PathStatus {
250423×
                        path: path.to_string(),
250523×
                        status: ChangeStatus::Resolved,
250623×
                    });
250723×
                    return Ok(());
25088072×
                }
25098072×
                if wants_opaque {
2510
                    // Text → opaque (spec §7.5), by content or by attribute.
25112×
                    if let Some(old) = mode_atom {
25122×
                        self.tree_ops.push(TreeOp::SetMode {
25132×
                            node,
25142×
                            old,
25152×
                            mode: Mode {
25162×
                                exec: e.exec,
25172×
                                opaque: true,
25182×
                            },
25192×
                        });
25202×
                    }
25212×
                    let live: Vec<_> = repo_live_keys(self.base, &node);
25222×
                    if !live.is_empty() {
25232×
                        self.edits.push(Edit::Delete {
25242×
                            node,
25252×
                            atoms: ranges(&live),
25262×
                        });
25272×
                    }
25282×
                    let blob = self.blob_of(repo, path, e, nocompress)?;
25292×
                    self.edits.push(Edit::Replace {
25302×
                        node,
25312×
                        old: None,
25322×
                        new: Some(blob),
25332×
                    });
25342×
                    status = Some(ChangeStatus::Modified);
25358070×
                } else if bytes != &*disk_text {
2536740×
                    let mut laps = crate::timing::Laps::start();
2537
                    // The base's rendering holds its live atoms in order,
2538
                    // one per line (it is not conflicted here).
2539740×
                    let edits = match self.diffs.remove(path) {
254080×
                        Some(edits) => edits,
2541
                        None => {
2542660×
                            let keys = materialized.live_atoms();
2543660×
                            let lines = crate::diff::split_lines(bytes);
2544660×
                            if keys.len() == lines.len() {
2545660×
                                crate::diff::text_edits_of(node, &keys, &lines, &disk_text)
2546
                            } else {
25470×
                                text_edits(node, &self.base.live_lines(&node), &disk_text)
2548
                            }
2549
                        }
2550
                    };
2551740×
                    laps.lap("build: text diff");
2552740×
                    if !edits.is_empty() {
2553740×
                        self.edits.extend(edits);
2554740×
                        status = Some(ChangeStatus::Modified);
2555740×
                    }
25567330×
                }
25578072×
                let switched_to_opaque = wants_opaque;
25588072×
                if !switched_to_opaque && e.exec != expected.mode.exec {
25594×
                    if let Some(old) = mode_atom {
25604×
                        self.tree_ops.push(TreeOp::SetMode {
25614×
                            node,
25624×
                            old,
25634×
                            mode: Mode {
25644×
                                exec: e.exec,
25654×
                                opaque: false,
25664×
                            },
25674×
                        });
25684×
                        status.get_or_insert(ChangeStatus::ModeChanged);
25694×
                    }
25708068×
                }
2571
            }
2572223×
            FileContent::Opaque { blobs } => {
2573223×
                let new_ref = e.blob.unwrap_or_else(|| Repo::blob_ref(&e.content));
2574223×
                if e.kind == NodeKind::File && wants_opaque {
2575191×
                    // Unchanged or replaced, the file stays opaque: remember its blob.
2576191×
                    self.blobs.insert(path.to_string(), new_ref);
2577191×
                }
2578223×
                if blobs.len() > 1 && self.resolve.contains(path) && e.kind == expected.kind {
2579
                    // Settle the replace conflict (spec §9.3): replace every
2580
                    // live candidate with the chosen blob, depending on each
2581
                    // change that made one live, so all are superseded.
25822×
                    let chosen = self.blob_of(repo, path, e, nocompress)?;
25834×
                    for b in blobs {
25844×
                        self.edits.push(Edit::Replace {
25854×
                            node,
25864×
                            old: Some(*b),
25874×
                            new: Some(chosen),
25884×
                        });
25894×
                    }
25902×
                    self.contributors
25912×
                        .extend(self.base.blob_contributors(&node, blobs));
25922×
                    self.resolves = true;
25932×
                    self.statuses.push(PathStatus {
25942×
                        path: path.to_string(),
25952×
                        status: ChangeStatus::Resolved,
25962×
                    });
25972×
                    return Ok(());
2598221×
                }
2599221×
                if blobs.len() > 1 {
26002×
                    if !blobs.contains(&new_ref) {
26010×
                        self.statuses.push(PathStatus {
26020×
                            path: path.to_string(),
26030×
                            status: ChangeStatus::ConflictEdited,
26040×
                        });
26052×
                    }
26062×
                    return Ok(());
2607219×
                }
2608219×
                let current = blobs.first().copied();
2609219×
                if current != Some(new_ref) {
261033×
                    if e.kind == NodeKind::File && !wants_opaque {
2611
                        // Opaque → text (spec §7.5).
26122×
                        if let Some(old) = mode_atom {
26132×
                            self.tree_ops.push(TreeOp::SetMode {
26142×
                                node,
26152×
                                old,
26162×
                                mode: Mode {
26172×
                                    exec: e.exec,
26182×
                                    opaque: false,
26192×
                                },
26202×
                            });
26212×
                        }
26222×
                        self.edits.push(Edit::Replace {
26232×
                            node,
26242×
                            old: current,
26252×
                            new: None,
26262×
                        });
26272×
                        if !e.content.is_empty() {
26282×
                            self.edits.push(Edit::Insert {
26292×
                                node,
26302×
                                after: crate::objects::AtomRef::Start,
26312×
                                before: crate::objects::AtomRef::End,
26322×
                                lines: crate::lines::Lines::split(&e.content),
26332×
                            });
26342×
                        }
2635
                    } else {
263631×
                        let blob = self.blob_of(repo, path, e, nocompress)?;
263731×
                        self.edits.push(Edit::Replace {
263831×
                            node,
263931×
                            old: current,
264031×
                            new: Some(blob),
264131×
                        });
2642
                        // New contents and a new executable bit at once: the
2643
                        // bit was dropped (VS Code's inno_updater.exe,
2644
                        // 2018-02-28, lost +x for 49 commits; oxygen#87).
264531×
                        if e.kind == NodeKind::File && e.exec != expected.mode.exec {
26462×
                            if let Some(old) = mode_atom {
26472×
                                self.tree_ops.push(TreeOp::SetMode {
26482×
                                    node,
26492×
                                    old,
26502×
                                    mode: Mode {
26512×
                                        exec: e.exec,
26522×
                                        opaque: true,
26532×
                                    },
26542×
                                });
26552×
                            }
265629×
                        }
2657
                    }
265833×
                    status = Some(ChangeStatus::Modified);
2659186×
                } else if e.kind == NodeKind::File && e.exec != expected.mode.exec {
26600×
                    if let Some(old) = mode_atom {
26610×
                        self.tree_ops.push(TreeOp::SetMode {
26620×
                            node,
26630×
                            old,
26640×
                            mode: Mode {
26650×
                                exec: e.exec,
26660×
                                opaque: true,
26670×
                            },
26680×
                        });
26690×
                        status = Some(ChangeStatus::ModeChanged);
26700×
                    }
2671186×
                }
2672
            }
2673
        }
26748291×
        if let Some(s) = status {
2675779×
            self.statuses.push(PathStatus {
2676779×
                path: path.to_string(),
2677779×
                status: s,
2678779×
            });
26797512×
        }
26808291×
        Ok(())
268112575×
    }
2682
}
2683
26842×
fn repo_live_keys(base: &State, node: &NodeId) -> Vec<crate::graph::AtomKey> {
26852×
    base.live_lines(node).into_iter().map(|(k, _)| k).collect()
26862×
}
2687
2688
/// The changes a change's scope references (spec §8.1): introducers of every
2689
/// atom, placement, and mode it touches, and of every node it operates on.
26901937×
pub fn referenced_changes(change: &Change, base: &State) -> BTreeSet<ChangeHash> {
26911937×
    let mut out = BTreeSet::new();
26921937×
    let opref = |r: &OpRef, out: &mut BTreeSet<ChangeHash>| {
2693197×
        if !r.change.is_zero() {
2694197×
            out.insert(r.change);
2695197×
        }
2696197×
    };
26971937×
    let mut nodes: Vec<NodeId> = Vec::new();
26986489×
    for op in &change.tree_ops {
26996489×
        match op {
27006292×
            TreeOp::AddNode { parent, .. } => nodes.push(*parent),
2701151×
            TreeOp::RemoveNode { node, placement } => {
2702151×
                nodes.push(*node);
2703151×
                opref(placement, &mut out);
2704151×
            }
2705
            TreeOp::Move {
270634×
                node, old, parent, ..
270734×
            } => {
270834×
                nodes.push(*node);
270934×
                nodes.push(*parent);
271034×
                opref(old, &mut out);
271134×
            }
271212×
            TreeOp::SetMode { node, old, .. } => {
271312×
                nodes.push(*node);
271412×
                opref(old, &mut out);
271512×
            }
2716
        }
2717
    }
27187928×
    for e in &change.edits {
27197928×
        nodes.push(e.node());
2720128×
        match e {
27217324×
            Edit::Insert { after, before, .. } => {
272214648×
                for r in [after, before] {
272314648×
                    if let crate::objects::AtomRef::Atom { change, .. } = r {
27242125×
                        if !change.is_zero() {
27252123×
                            out.insert(*change);
27262123×
                        }
272712523×
                    }
2728
                }
2729
            }
2730476×
            Edit::Delete { atoms, .. } => {
2731
                // Deleting an atom also depends on whoever inserted the live
2732
                // atoms right after it: the author saw those insertions, and
2733
                // without the dependency spec §9.1 would call the deletion
2734
                // concurrent with them (a delete/insert conflict).
2735476×
                let graph = base.file(&e.node());
27361029×
                for r in atoms {
27371029×
                    if !r.change.is_zero() {
27381028×
                        out.insert(r.change);
27391028×
                    }
27401029×
                    if let Some(g) = graph {
27411070×
                        for i in r.from..r.to {
27421070×
                            out.extend(
27431070×
                                g.live_successor_changes(&(r.change, i))
27441070×
                                    .into_iter()
27451070×
                                    .filter(|c| !c.is_zero()),
2746
                            );
2747
                        }
27480×
                    }
2749
                }
2750
            }
2751
            // Replacing a blob depends on the change that made it current,
2752
            // as deleting a line depends on the line's introducer.
2753
            Edit::Replace {
275438×
                node,
275538×
                old: Some(old),
2756
                ..
2757
            } => {
275838×
                out.extend(
275938×
                    base.live_replaces(node)
276038×
                        .into_iter()
276145×
                        .filter(|(c, b)| b == old && !c.is_zero())
276238×
                        .map(|(c, _)| c),
2763
                );
2764
            }
276590×
            Edit::Replace { .. } => {}
2766
        }
2767
    }
276814451×
    for n in nodes {
276914451×
        if let Some(h) = base.tree().introducer(&n) {
27702095×
            out.insert(h);
277112356×
        }
2772
    }
27731937×
    out
27741937×
}
2775
2776
/// Paths of the nodes a change adds on top of `base_snapshot`.
27771213×
pub fn added_node_paths(
27781213×
    change: &Change,
27791213×
    base_snapshot: &Snapshot,
27801213×
) -> HashMap<String, (NodeId, NodeKind)> {
27811213×
    let by_node = base_snapshot.tree.by_node();
27821213×
    let mut new_names: HashMap<NodeId, (NodeId, String, NodeKind)> = HashMap::new();
27831213×
    for op in &change.tree_ops {
2784
        if let TreeOp::AddNode {
278575×
            node,
278675×
            parent,
278775×
            name,
278875×
            kind,
2789
            ..
279098×
        } = op
279175×
        {
279275×
            new_names.insert(*node, (*parent, name.clone(), *kind));
279375×
        }
2794
    }
27951213×
    let mut out = HashMap::new();
27961213×
    for (node, (_, _, kind)) in &new_names {
279775×
        if let Some(path) = path_of_node(node, &by_node, &new_names) {
279875×
            out.insert(path, (*node, *kind));
279975×
        }
2800
    }
28011213×
    out
28021213×
}
2803
2804184×
fn path_of_node(
2805184×
    n: &NodeId,
2806184×
    by_node: &HashMap<NodeId, &crate::tree::TreeEntry>,
2807184×
    new_names: &HashMap<NodeId, (NodeId, String, NodeKind)>,
2808184×
) -> Option<String> {
2809184×
    if let Some(e) = by_node.get(n) {
281057×
        return Some(e.path.clone());
2811127×
    }
2812127×
    let mut parts = Vec::new();
2813127×
    let mut cur = *n;
2814
    loop {
2815253×
        if cur.is_root() {
2816113×
            break;
2817140×
        }
2818140×
        if let Some(e) = by_node.get(&cur) {
28190×
            if !e.path.is_empty() {
28200×
                parts.push(e.path.clone());
28210×
            }
28220×
            break;
2823140×
        }
2824140×
        let (parent, name, _) = new_names.get(&cur)?;
2825126×
        parts.push(name.clone());
2826126×
        cur = *parent;
2827
    }
2828113×
    parts.reverse();
2829113×
    Some(parts.join("/"))
2830184×
}
2831
2832
/// Render a change's operations with line content, using `base` for deleted lines.
283328×
pub fn render_change(change: &Change, base: &State, base_snapshot: &Snapshot) -> String {
283428×
    let by_node = base_snapshot.tree.by_node();
283528×
    let mut new_names: HashMap<NodeId, (NodeId, String, NodeKind)> = HashMap::new();
283628×
    for op in &change.tree_ops {
2837
        if let TreeOp::AddNode {
283815×
            node,
283915×
            parent,
284015×
            name,
284115×
            kind,
2842
            ..
284322×
        } = op
284415×
        {
284515×
            new_names.insert(*node, (*parent, name.clone(), *kind));
284615×
        }
2847
    }
284866×
    let path_of = |n: &NodeId| -> String {
284966×
        path_of_node(n, &by_node, &new_names).unwrap_or_else(|| format!("<node {}>", n.short(8)))
285066×
    };
2851
285228×
    let mut out = String::new();
285328×
    for op in &change.tree_ops {
285422×
        match op {
2855
            TreeOp::AddNode {
285615×
                node, kind, mode, ..
2857
            } => {
285815×
                out.push_str(&format!(
2859
                    "A {} ({:?}{}{})\n",
286015×
                    path_of(node),
2861
                    kind,
286215×
                    if mode.exec { ", exec" } else { "" },
286315×
                    if mode.opaque { ", opaque" } else { "" }
2864
                ));
2865
            }
28665×
            TreeOp::RemoveNode { node, .. } => out.push_str(&format!("D {}\n", path_of(node))),
2867
            TreeOp::Move {
28682×
                node, parent, name, ..
2869
            } => {
28702×
                let to = if parent.is_root() {
28710×
                    name.clone()
2872
                } else {
28732×
                    format!("{}/{name}", path_of(parent))
2874
                };
28752×
                out.push_str(&format!("R {} -> {to}\n", path_of(node)))
2876
            }
28770×
            TreeOp::SetMode { node, mode, .. } => {
28780×
                out.push_str(&format!(
28790×
                    "M {} mode: exec={} opaque={}\n",
28800×
                    path_of(node),
28810×
                    mode.exec,
28820×
                    mode.opaque
28830×
                ));
28840×
            }
2885
        }
2886
    }
2887
    // Every other file the change edits is modified: the summary names
2888
    // every path it touches, not only those with a tree operation.
288928×
    let with_op: HashSet<NodeId> = change.tree_ops.iter().map(|o| o.node()).collect();
289028×
    let mut listed: HashSet<NodeId> = HashSet::new();
289132×
    for e in &change.edits {
289232×
        let n = e.node();
289332×
        if !with_op.contains(&n) && listed.insert(n) {
289418×
            out.push_str(&format!("M {}\n", path_of(&n)));
289518×
        }
2896
    }
289728×
    let mut last_node: Option<NodeId> = None;
289832×
    for e in &change.edits {
289932×
        let n = e.node();
290032×
        if last_node != Some(n) {
290124×
            out.push_str(&format!("--- {}\n", path_of(&n)));
290224×
            last_node = Some(n);
290324×
        }
290432×
        match e {
290524×
            Edit::Insert { lines, .. } => {
290629×
                for l in lines.iter() {
290729×
                    out.push('+');
290829×
                    out.push_str(&String::from_utf8_lossy(l));
290929×
                    if !l.ends_with(b"\n") {
29100×
                        out.push('\n');
291129×
                    }
2912
                }
2913
            }
29147×
            Edit::Delete { atoms, .. } => {
29157×
                for r in atoms {
29167×
                    for i in r.from..r.to {
29177×
                        let content = base
29187×
                            .file(&n)
29197×
                            .and_then(|g| g.content(&(r.change, i)))
29207×
                            .unwrap_or(b"<unknown>\n");
29217×
                        out.push('-');
29227×
                        out.push_str(&String::from_utf8_lossy(content));
29237×
                        if !content.ends_with(b"\n") {
29240×
                            out.push('\n');
29257×
                        }
2926
                    }
2927
                }
2928
            }
29291×
            Edit::Replace { old, new, .. } => {
29301×
                out.push_str(&format!(
2931
                    "  opaque content {} -> {}\n",
29321×
                    old.map(|o| o.short(12)).unwrap_or_else(|| "none".into()),
29331×
                    new.map(|o| o.short(12)).unwrap_or_else(|| "none".into())
2934
                ));
2935
            }
2936
        }
2937
    }
293828×
    out
293928×
}
2940
2941
/// Pair removed files with added files of the same kind whose contents are
2942
/// at least `RENAME_THRESHOLD` percent alike, best matches first. Beyond
2943
/// `RENAME_LIMIT` candidate pairs only identical contents are paired.
2944
const RENAME_THRESHOLD: u32 = 50;
2945
const RENAME_LIMIT: usize = 10_000;
2946
2947
/// How a change is built beyond its entries: for a Git import, the seed
2948
/// its new nodes' identifiers derive from; and, when it is built from part
2949
/// of the tree, whether the new tree has anything under a directory.
2950
#[derive(Default)]
2951
struct Scope<'a> {
2952
    seed: Option<[u8; 32]>,
2953
    dir_needed: Option<&'a dyn Fn(&str) -> bool>,
2954
}
2955
29561856×
fn detect_renames(
29571856×
    base_snapshot: &Snapshot,
29581856×
    fs_entries: &BTreeMap<String, FsEntry>,
29591856×
    in_scope: impl Fn(&str) -> bool,
29601856×
) -> Vec<(String, String)> {
29611856×
    let removed: Vec<(&String, &crate::state::FileState)> = base_snapshot
29621856×
        .files
29631856×
        .iter()
296413091×
        .filter(|(p, f)| {
296513091×
            f.kind != NodeKind::Dir
296612688×
                && !fs_entries.contains_key(*p)
2967145×
                && in_scope(p)
2968135×
                && !f.is_conflicted()
296913091×
        })
29701856×
        .collect();
29711856×
    let added: Vec<(&String, &FsEntry)> = fs_entries
29721856×
        .iter()
297318508×
        .filter(|(p, e)| e.kind != NodeKind::Dir && !base_snapshot.files.contains_key(*p))
29741856×
        .collect();
29751856×
    if removed.is_empty() || added.is_empty() {
29761798×
        return vec![];
297758×
    }
297858×
    let exact_only = removed.len() * added.len() > RENAME_LIMIT;
297972×
    let old_content = |f: &crate::state::FileState| -> Option<Vec<u8>> {
298072×
        match &f.content {
298168×
            FileContent::Text { bytes, .. } => Some(bytes.clone()),
29824×
            _ => None,
2983
        }
298472×
    };
298558×
    let mut scored: Vec<(u32, usize, usize)> = Vec::new();
298672×
    for (ri, (_, f)) in removed.iter().enumerate() {
298772×
        let old = old_content(f);
298872×
        let old_blob = match &f.content {
29894×
            FileContent::Opaque { blobs } if blobs.len() == 1 => Some(blobs[0]),
299068×
            _ => None,
2991
        };
299291×
        for (ai, (_, e)) in added.iter().enumerate() {
299391×
            if e.kind != f.kind {
29940×
                continue;
299591×
            }
299691×
            let score = match (&old, old_blob) {
299781×
                (Some(o), _) => {
299881×
                    if exact_only {
29990×
                        if *o == *e.content {
30000×
                            100
3001
                        } else {
30020×
                            0
3003
                        }
3004
                    } else {
300581×
                        similarity(o, &e.content)
3006
                    }
3007
                }
300810×
                (None, Some(b)) if e.blob.unwrap_or_else(|| Repo::blob_ref(&e.content)) == b => 100,
30097×
                _ => 0,
3010
            };
301191×
            if score >= RENAME_THRESHOLD {
301238×
                scored.push((score, ri, ai));
301353×
            }
3014
        }
3015
    }
301658×
    scored.sort_by(|a, b| {
30179×
        b.0.cmp(&a.0)
30189×
            .then(removed[a.1].0.cmp(removed[b.1].0))
30199×
            .then(added[a.2].0.cmp(added[b.2].0))
30209×
    });
302158×
    let mut used_r = vec![false; removed.len()];
302258×
    let mut used_a = vec![false; added.len()];
302358×
    let mut out = Vec::new();
302458×
    for (_, ri, ai) in scored {
302538×
        if used_r[ri] || used_a[ai] {
30266×
            continue;
302732×
        }
302832×
        used_r[ri] = true;
302932×
        used_a[ai] = true;
303032×
        out.push((removed[ri].0.clone(), added[ai].0.clone()));
3031
    }
303258×
    out
30331856×
}
3034
3035
/// Percentage of the larger file's bytes found in lines the two share
3036
/// (multiset intersection of lines), like Git's similarity index.
303785×
pub fn similarity(a: &[u8], b: &[u8]) -> u32 {
303885×
    if a == b {
303922×
        return 100;
304063×
    }
304163×
    if a.is_empty() || b.is_empty() {
30425×
        return 0;
304358×
    }
304458×
    let mut counts: HashMap<&[u8], usize> = HashMap::new();
3045115×
    for l in split_lines(a) {
3046115×
        *counts.entry(l).or_default() += 1;
3047115×
    }
304858×
    let mut shared = 0usize;
3049111×
    for l in split_lines(b) {
3050111×
        if let Some(n) = counts.get_mut(l) {
305143×
            if *n > 0 {
305243×
                *n -= 1;
305343×
                shared += l.len();
305443×
            }
305568×
        }
3056
    }
305758×
    (shared * 100 / a.len().max(b.len())) as u32
305885×
}
3059
3060
#[cfg(test)]
3061
mod join_tests {
3062
    use super::*;
3063
3064
    #[test]
30651×
    fn missing_from_finds_what_the_other_lacks() {
30661×
        let a: BTreeMap<String, u8> = [("a", 1), ("b", 2), ("c/d", 3), ("e", 4)]
30671×
            .into_iter()
30684×
            .map(|(k, v)| (k.to_string(), v))
30691×
            .collect();
30701×
        let b: BTreeMap<String, ()> = [("0", ()), ("b", ()), ("c", ()), ("e", ())]
30711×
            .into_iter()
30724×
            .map(|(k, v)| (k.to_string(), v))
30731×
            .collect();
30741×
        let got: Vec<&str> = missing_from(&a, &b)
30751×
            .iter()
30762×
            .map(|(k, _)| k.as_str())
30771×
            .collect();
30781×
        assert_eq!(got, vec!["a", "c/d"]);
30791×
    }
3080
3081
    #[test]
30821×
    fn join_pairs_every_key_in_order() {
30831×
        let a: BTreeMap<String, u8> = [("a", 1), ("b/c", 2), ("d", 3)]
30841×
            .into_iter()
30853×
            .map(|(k, v)| (k.to_string(), v))
30861×
            .collect();
30871×
        let b: BTreeMap<String, char> = [("b", 'x'), ("b/c", 'y'), ("e", 'z')]
30881×
            .into_iter()
30893×
            .map(|(k, v)| (k.to_string(), v))
30901×
            .collect();
30911×
        let got: Vec<(String, Option<u8>, Option<char>)> = join(&a, &b)
30925×
            .map(|(k, x, y)| (k.clone(), x.copied(), y.copied()))
30931×
            .collect();
30941×
        let want = vec![
30951×
            ("a".to_string(), Some(1), None),
30961×
            ("b".to_string(), None, Some('x')),
30971×
            ("b/c".to_string(), Some(2), Some('y')),
30981×
            ("d".to_string(), Some(3), None),
30991×
            ("e".to_string(), None, Some('z')),
3100
        ];
31011×
        assert_eq!(got, want);
31021×
    }
3103
}