OXYGENHUB

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

2193 of 2424 lines run, 286 of 371 functions · run #264 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
8122549×
pub fn is_binary(content: &[u8]) -> bool {
8222549×
    content[..content.len().min(BINARY_SNIFF)].contains(&0)
8322549×
}
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.
1051214×
    fn platform_normalize(&self, entries: &mut BTreeMap<String, FsEntry>, base: &Snapshot) {
1061214×
        let p = self.platform;
1071214×
        if p.exec_bits && p.symlinks {
1081212×
            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
        }
1221214×
    }
123
124
    /// Like `build_against`, for files given in memory (imports).
125952×
    pub(crate) fn build_from_entries(
126952×
        &self,
127952×
        base: &State,
128952×
        base_snapshot: &Snapshot,
129952×
        reuse: HashMap<String, (NodeId, NodeKind)>,
130952×
        fs_entries: &BTreeMap<String, FsEntry>,
131952×
    ) -> Result<BuiltChange> {
132952×
        self.build_from_entries_resolving(base, base_snapshot, reuse, fs_entries, &HashSet::new())
133952×
    }
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.
140966×
    pub(crate) fn build_from_entries_resolving(
141966×
        &self,
142966×
        base: &State,
143966×
        base_snapshot: &Snapshot,
144966×
        reuse: HashMap<String, (NodeId, NodeKind)>,
145966×
        fs_entries: &BTreeMap<String, FsEntry>,
146966×
        resolve: &HashSet<String>,
147966×
    ) -> Result<BuiltChange> {
148966×
        self.build_from_entries_with(
149966×
            base,
150966×
            base_snapshot,
151966×
            reuse,
152966×
            fs_entries,
153966×
            resolve,
154966×
            Scope::default(),
155
        )
156966×
    }
157
158
    /// `build_from_entries` whose new nodes take identifiers derived from
159
    /// `seed` and their paths instead of random ones, so the same input
160
    /// always builds the same change (a Git import, spec §23).
161
    ///
162
    /// With `dir_needed`, the snapshot and entries hold only the paths the
163
    /// import touches (and the directories a removal may leave empty); a
164
    /// directory stays while `dir_needed` says the new tree has something
165
    /// under it.
16686×
    pub(crate) fn build_from_entries_seeded(
16786×
        &self,
16886×
        base: &State,
16986×
        base_snapshot: &Snapshot,
17086×
        fs_entries: &BTreeMap<String, FsEntry>,
17186×
        seed: [u8; 32],
17286×
        dir_needed: Option<&dyn Fn(&str) -> bool>,
17386×
    ) -> Result<BuiltChange> {
17486×
        self.build_from_entries_with(
17586×
            base,
17686×
            base_snapshot,
17786×
            HashMap::new(),
17886×
            fs_entries,
17986×
            &HashSet::new(),
18086×
            Scope {
18186×
                seed: Some(seed),
18286×
                dir_needed,
18386×
            },
184
        )
18586×
    }
186
187
    /// `build_from_entries` for a snapshot most of whose files are known
188
    /// unchanged (oxygen#41): only the paths that may differ are built
189
    /// (files read rather than known unchanged, base files gone from disk,
190
    /// and the directories those may leave empty), against a snapshot of
191
    /// just those, so a large tree with a few edits costs what they touch.
192800×
    fn build_changed_only(
193800×
        &self,
194800×
        base: &State,
195800×
        base_snapshot: &Snapshot,
196800×
        reuse: HashMap<String, (NodeId, NodeKind)>,
197800×
        fs_entries: &BTreeMap<String, FsEntry>,
198800×
    ) -> Result<BuiltChange> {
199800×
        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.
202800×
        let changed: BTreeMap<String, FsEntry> = join(fs_entries, &base_snapshot.files)
20310949×
            .filter_map(|(p, e, f)| {
20410949×
                let e = e?;
20510824×
                (!e.unchanged || f.is_none_or(|f| f.kind != e.kind || f.mode.exec != e.exec))
20610824×
                    .then(|| (p.clone(), e.clone()))
20710949×
            })
208800×
            .collect();
209800×
        let mut files: BTreeMap<String, crate::state::FileState> = BTreeMap::new();
2106593×
        for p in changed.keys() {
2116593×
            if let Some(f) = base_snapshot.files.get(p) {
2123633×
                files.insert(p.clone(), f.clone());
2133633×
            }
214
        }
215
        // Paths the base has and the disk does not.
216800×
        let gone = join(&base_snapshot.files, fs_entries)
21710949×
            .filter_map(|(p, f, e)| (e.is_none()).then_some((p, f?)));
218800×
        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
        }
235800×
        let part = Snapshot {
236800×
            tree: base_snapshot.tree.clone(),
237800×
            files,
238800×
            unrendered: BTreeSet::new(),
239800×
        };
240800×
        drop(pick);
241800×
        let _build = crate::timing::phase("snapshot:   of which building the change");
242
        // Whether anything on disk is under `dir`.
243800×
        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×
        };
250800×
        self.build_from_entries_with(
251800×
            base,
252800×
            &part,
253800×
            reuse,
254800×
            &changed,
255800×
            &HashSet::new(),
256800×
            Scope {
257800×
                seed: None,
258800×
                dir_needed: Some(&dir_needed),
259800×
            },
260
        )
261800×
    }
262
2631852×
    fn build_from_entries_with(
2641852×
        &self,
2651852×
        base: &State,
2661852×
        base_snapshot: &Snapshot,
2671852×
        reuse: HashMap<String, (NodeId, NodeKind)>,
2681852×
        fs_entries: &BTreeMap<String, FsEntry>,
2691852×
        resolve: &HashSet<String>,
2701852×
        scope: Scope,
2711852×
    ) -> Result<BuiltChange> {
2721852×
        let Scope { seed, dir_needed } = scope;
2731852×
        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.
2761852×
        let attrs = crate::attributes::Attributes::from_files(
2771852×
            fs_entries
2781852×
                .iter()
27918550×
                .filter(|(p, _)| p.as_str() == ".oxyattributes" || p.ends_with("/.oxyattributes"))
2801852×
                .map(|(p, e)| (p.as_str(), e.content.as_slice())),
281
        );
2821852×
        let mut b = ChangeBuilder::new(base, base_snapshot, reuse).with_attributes(attrs);
2831852×
        b.resolve = resolve.clone();
2841852×
        b.node_seed = seed;
2851852×
        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.
2891852×
        let renames = detect_renames(base_snapshot, fs_entries, |p| self.in_scope(p));
2901852×
        let renamed_from: HashMap<&str, &str> = renames
2911852×
            .iter()
2921852×
            .map(|(old, new)| (new.as_str(), old.as_str()))
2931852×
            .collect();
2941852×
        let renamed_to: HashMap<&str, &str> = renames
2951852×
            .iter()
2961852×
            .map(|(old, new)| (old.as_str(), new.as_str()))
2971852×
            .collect();
2981852×
        laps.lap("build: renames");
2991852×
        b.diff_in_parallel(fs_entries);
3001852×
        laps.lap("build: diffs");
30118550×
        for (path, fs_entry) in fs_entries {
30218550×
            match base_snapshot.files.get(path) {
3035965×
                None => match renamed_from.get(path.as_str()) {
30433×
                    Some(old) => {
30533×
                        b.move_path(self, old, path, fs_entry, &base_snapshot.files[*old])?
306
                    }
3075932×
                    None => b.add_path(self, path, fs_entry)?,
308
                },
30912585×
                Some(expected) => b.update_path(self, path, fs_entry, expected)?,
310
            }
311
        }
3121852×
        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.
3151852×
        let mut needed_dirs: HashSet<&str> = HashSet::new();
31618563×
        fn parents_of<'a>(p: &'a str, set: &mut HashSet<&'a str>) {
31718563×
            let mut end = p.len();
31819196×
            while let Some(i) = p[..end].rfind('/') {
31915415×
                if !set.insert(&p[..i]) {
32014782×
                    break;
321633×
                }
322633×
                end = i;
323
            }
32418563×
        }
32518550×
        for p in fs_entries.keys() {
32618550×
            parents_of(p, &mut needed_dirs);
32718550×
        }
32813123×
        for p in base_snapshot.files.keys() {
32913123×
            if !self.in_scope(p) {
33013×
                parents_of(p, &mut needed_dirs);
33113110×
            }
332
        }
33313123×
        for (path, expected) in &base_snapshot.files {
33413123×
            if fs_entries.contains_key(path)
335538×
                || !self.in_scope(path)
336525×
                || renamed_to.contains_key(path.as_str())
337
            {
33812631×
                continue;
339492×
            }
340492×
            let still_needed = expected.kind == NodeKind::Dir
341397×
                && match dir_needed {
34221×
                    Some(f) => f(path),
343376×
                    None => needed_dirs.contains(path.as_str()),
344
                };
345492×
            if !still_needed {
346122×
                b.remove_path(path, expected);
347370×
            }
348
        }
3491852×
        laps.lap("build: removals");
3501852×
        if seed.is_some() {
35186×
            b.retire_stray_placements();
3521766×
        }
3531852×
        laps.lap("build: stray placements");
3541852×
        let mut statuses = b.statuses;
3555654×
        statuses.sort_by(|a, b| a.path.cmp(&b.path));
3561852×
        Ok(BuiltChange {
3571852×
            tree_ops: b.tree_ops,
3581852×
            edits: b.edits,
3591852×
            contributors: b.contributors.into_iter().collect(),
3601852×
            resolves: b.resolves,
3611852×
            statuses,
3621852×
            blobs: b.blobs,
3631852×
        })
3641852×
    }
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.
369651×
    pub(crate) fn store_signed(&self, change: &Change) -> Result<ChangeHash> {
370651×
        let ours = change.author == self.author();
371651×
        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");
373650×
        }
374650×
        let storing = crate::timing::phase("store: the change");
375650×
        let hash = self.store.put_change(change)?;
376650×
        drop(storing);
377650×
        if self.config.sign_changes && ours {
37840×
            let _t = crate::timing::phase("store: sign it");
37940×
            self.sign_change(&hash)?;
380610×
        }
381650×
        Ok(hash)
382651×
    }
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.
386412×
    pub fn snapshot(&self, command: &str) -> Result<SnapshotResult> {
387412×
        self.snapshot_as(command, false, false)
388412×
    }
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.
398384×
    pub fn snapshot_status(&self, command: &str) -> Result<SnapshotResult> {
399384×
        self.snapshot_as(command, true, false)
400384×
    }
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.
4091215×
    fn snapshot_as(
4101215×
        &self,
4111215×
        command: &str,
4121215×
        partial: bool,
4131215×
        for_commit: bool,
4141215×
    ) -> Result<SnapshotResult> {
4151215×
        let _lock = self.lock_snapshot()?;
4161215×
        let batch = self.store.begin_batch()?;
4171215×
        let result = self.snapshot_locked(command, partial, for_commit);
4181215×
        batch.finish()?;
4191215×
        result
4201215×
    }
421
4221215×
    fn snapshot_locked(
4231215×
        &self,
4241215×
        command: &str,
4251215×
        partial: bool,
4261215×
        for_commit: bool,
4271215×
    ) -> Result<SnapshotResult> {
4281215×
        let _all = crate::timing::phase("snapshot");
4291215×
        let (op_ref, op) = self.head_op()?;
4301215×
        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.
4331213×
        let mut base = {
4341213×
            let _t = crate::timing::phase("snapshot: load base history");
4351213×
            self.load_state_indexed(&old_wc.deps)?
436
        };
4371213×
        let view = {
4381213×
            let _t = crate::timing::phase("snapshot: tree view");
4391213×
            base.tree().view()
440
        };
4411213×
        let manifest = {
4421213×
            let _t = crate::timing::phase("snapshot: read manifest");
4431213×
            self.read_manifest()?.map(|(_, _, m)| m)
444
        };
4451213×
        let tracked: BTreeMap<String, (NodeKind, Option<ObjectRef>)> = {
4461213×
            let _t = crate::timing::phase("snapshot: tracked paths");
447
            // In the view's path order, so the map is built without searching.
4481213×
            view.entries
4491213×
                .iter()
4509394×
                .filter(|(_, e)| e.kind != NodeKind::Dir)
4519022×
                .map(|(p, e)| {
4529022×
                    let blob = if e.kind != NodeKind::File || e.mode.opaque {
453151×
                        base.live_blobs(&e.node).first().copied()
454
                    } else {
4558871×
                        None
456
                    };
4579022×
                    (p.clone(), (e.kind, blob))
4589022×
                })
4591213×
                .collect()
460
        };
461
        // A text file's graph key, worked out when the walk asks for it.
46211992×
        let key_of = |p: &str| -> Option<[u8; 32]> {
46311992×
            let e = view.entries.get(p)?;
4648923×
            if e.kind != NodeKind::File || e.mode.opaque {
465124×
                return None;
4668799×
            }
4678799×
            base.graph_key(&e.node)
46811992×
        };
4691212×
        let mut fs_entries = {
4701213×
            let _t = crate::timing::phase("snapshot: read working copy");
4711213×
            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.
4751212×
        let keys: HashMap<String, [u8; 32]> = fs_entries
4761212×
            .iter()
47712021×
            .filter(|(_, e)| !e.unchanged && e.kind == NodeKind::File)
4787749×
            .filter_map(|(p, _)| Some((p.clone(), key_of(p)?)))
4791212×
            .collect();
4801212×
        let base_snapshot = {
4811212×
            let _t = crate::timing::phase("snapshot: load and render base");
4821212×
            if partial {
483803×
                let sets = crate::timing::phase("snapshot:   of which choosing graphs");
484
                // Every file but those on disk known unchanged.
485803×
                let need: Vec<(&str, NodeId)> = join(&view.entries, &fs_entries)
48610964×
                    .filter_map(|(p, v, f)| {
48710964×
                        let v = v?;
4888003×
                        (v.kind == NodeKind::File && !f.is_some_and(|f| f.unchanged))
4898003×
                            .then_some((p.as_str(), v.node))
49010964×
                    })
491803×
                    .collect();
492803×
                let render: std::collections::HashSet<&str> =
493803×
                    need.iter().map(|(p, _)| *p).collect();
494803×
                let need: Vec<NodeId> = need.iter().map(|(_, n)| *n).collect();
495803×
                drop(sets);
496
                {
497803×
                    let _t = crate::timing::phase("snapshot:   of which building graphs");
498803×
                    self.load_graphs_of(&mut base, &need)?;
499
                }
500803×
                let _t = crate::timing::phase("snapshot:   of which rendering");
501803×
                base.materialize_only(&render)
502
            } else {
503409×
                self.load_all_graphs(&mut base)?;
504409×
                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).
5101212×
        let reuse = added_node_paths(&old_wc, &base_snapshot);
5111212×
        self.platform_normalize(&mut fs_entries, &base_snapshot);
5121212×
        let built = {
5131212×
            let _t = crate::timing::phase("snapshot: diff against base");
5141212×
            if partial && self.config.sparse_paths.is_empty() {
515
                #[cfg(test)]
516534×
                let full =
517534×
                    self.build_from_entries(&base, &base_snapshot, reuse.clone(), &fs_entries)?;
518800×
                let built = self.build_changed_only(&base, &base_snapshot, reuse, &fs_entries)?;
519
                #[cfg(test)]
520
                {
521
                    // New nodes take random identifiers: compare them by
522
                    // order of appearance.
5231068×
                    let norm = |b: &BuiltChange| {
5241068×
                        let text = format!("{:?} {:?} {:?}", b.tree_ops, b.edits, b.statuses);
5251068×
                        let mut seen: Vec<String> = Vec::new();
5261068×
                        let mut out = String::new();
5271068×
                        let mut rest = text.as_str();
52819496×
                        while let Some(i) = rest.find("NodeId(") {
52918428×
                            out.push_str(&rest[..i]);
53018428×
                            let end = i + rest[i..].find(')').unwrap() + 1;
53118428×
                            let id = rest[i..end].to_string();
5329045708×
                            let n = seen.iter().position(|x| *x == id).unwrap_or_else(|| {
5336860×
                                seen.push(id);
5346860×
                                seen.len() - 1
5356860×
                            });
53618428×
                            out.push_str(&format!("N{n}"));
53718428×
                            rest = &rest[end..];
538
                        }
5391068×
                        out.push_str(rest);
5401068×
                        out
5411068×
                    };
542534×
                    assert_eq!(
543534×
                        norm(&built),
544534×
                        norm(&full),
545
                        "a changed-only build is the full one"
546
                    );
547
                }
548800×
                built
549
            } else {
550412×
                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
        {
5563682×
            let changed: HashSet<&str> = built.statuses.iter().map(|s| s.path.as_str()).collect();
55712021×
            for (p, e) in fs_entries.iter_mut() {
55812021×
                if e.unchanged || e.kind != NodeKind::File || changed.contains(p.as_str()) {
5597861×
                    continue;
5604160×
                }
5614160×
                e.graph_key = match base_snapshot.files.get(p).map(|f| &f.content) {
562
                    Some(FileContent::Text {
5634048×
                        bytes,
5644048×
                        materialized,
5654048×
                    }) if !materialized.is_conflicted() && *bytes == *e.content => {
5664042×
                        keys.get(p).copied()
567
                    }
568118×
                    _ => None,
569
                };
570
            }
571
        }
572
5731212×
        let mut wc = Change {
5741212×
            version: crate::objects::CHANGE_VERSION,
5751212×
            change_id: old_wc.change_id,
5761212×
            deps: vec![],
5771212×
            author: self.author(),
5781212×
            hlc: old_wc.hlc,
5791212×
            message: old_wc.message.clone(),
5801212×
            tree_ops: built.tree_ops,
5811212×
            edits: built.edits,
5821212×
            kind: ChangeKind::WorkingCopy,
5831212×
        };
5841212×
        let base_heads = base.maximal(&old_wc.deps);
5851212×
        let mut deps: BTreeSet<ChangeHash> = base_heads.into_iter().collect();
5861212×
        deps.extend(referenced_changes(&wc, &base));
5871212×
        deps.extend(built.contributors.iter().copied());
5881212×
        wc.deps = deps.into_iter().collect();
5891212×
        wc.normalize();
5901212×
        let resolves = built.resolves;
5911212×
        let contributors = built.contributors;
5921212×
        let statuses = built.statuses;
593
        // Empty snapshot: hash the candidate before storing; only record an op on change.
5941212×
        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.
6011212×
        let (new_hash, changed, encoded) = if for_commit {
602419×
            (old_hash, true, Vec::new())
603
        } else {
604793×
            let encoded = wc.encode_streaming(|batch| self.store.put_texts(&batch))?;
605793×
            let new_hash = crate::hash::hash_object(crate::hash::ObjectType::Change, &encoded);
606793×
            (new_hash, new_hash != old_hash, encoded)
607
        };
6081212×
        if changed && !for_commit {
609273×
            self.store.put(crate::hash::ObjectType::Change, &encoded)?;
610273×
            let mut view = op.view.clone();
611273×
            view.workspaces.insert(self.workspace, new_hash);
612273×
            self.record_op(&[op_ref], &format!("{command}{SNAPSHOT_SUFFIX}"), view)?;
613939×
        }
6141212×
        drop(record);
615
        // The prompt compares against this without recording anything.
6161212×
        let _t = crate::timing::phase("snapshot: write manifest");
6171212×
        let conflicted = base_snapshot.is_conflicted();
6181212×
        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.
6231212×
        let worth = match self.read_manifest()? {
624419×
            _ if for_commit => true,
625294×
            None => true,
626499×
            Some((c, u, m)) => {
627499×
                c != conflicted
628499×
                    || u != uncommitted
629281×
                    || m.entries.len() != fs_entries.len()
630364×
                    || fs_entries.iter().any(|(p, e)| {
631364×
                        !e.unchanged && (e.graph_key.is_some() || !m.entries.contains_key(p))
632364×
                    })
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
        };
6611212×
        let attributes = crate::attributes::Attributes::from_files(
6621212×
            fs_entries
6631212×
                .iter()
66412021×
                .filter(|(p, _)| is_attributes(p))
6651212×
                .map(|(p, e)| (p.as_str(), e.content.as_slice())),
666
        );
6671212×
        let mut manifest = None;
6681212×
        if for_commit {
669419×
            manifest = Some(PendingManifest {
670419×
                entries: fs_entries,
671419×
                blobs: built.blobs.clone(),
672419×
                dirs: self.walked_dirs.take(),
673419×
                written: super::prompt::now_ns(),
674419×
            });
675419×
        } else {
676793×
            if worth {
677751×
                self.write_manifest_entries(conflicted, uncommitted, &fs_entries, &built.blobs)?;
67842×
            }
679793×
            self.write_status_cache((uncommitted && !conflicted).then_some(&new_hash), &statuses);
680
        }
6811212×
        Ok(SnapshotResult {
6821212×
            wc_hash: new_hash,
6831212×
            wc,
6841212×
            base,
6851212×
            base_snapshot,
6861212×
            statuses,
6871212×
            changed,
6881212×
            resolves,
6891212×
            contributors,
6901212×
            attributes,
6911212×
            untracked_nested: self.untracked_nested.borrow().clone(),
6921212×
            manifest,
6931212×
        })
6941215×
    }
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).
800593×
    pub fn commit(&self, message: &str, extra_deps: &[ChangeHash]) -> Result<ChangeHash> {
801593×
        self.commit_selection(message, extra_deps, &Selection::All)
802593×
    }
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.
822613×
    fn committed_graph_keys(
823613×
        &self,
824613×
        st: &State,
825613×
        paths: &[String],
826613×
        attrs: &crate::attributes::Attributes,
827613×
    ) -> HashMap<String, [u8; 32]> {
828613×
        let _t = crate::timing::phase("commit: graph keys");
829613×
        let view = st.tree().view();
830613×
        paths
831613×
            .iter()
8323450×
            .filter_map(|p| {
8333450×
                let e = view.entries.get(p)?;
8343406×
                (e.kind == NodeKind::File && !e.mode.opaque && attrs.lookup(p).eol.is_none())
8353406×
                    .then_some(())?;
8363357×
                Some((p.clone(), st.graph_key(&e.node)?))
8373450×
            })
838613×
            .collect()
839613×
    }
840
841598×
    pub fn commit_selection(
842598×
        &self,
843598×
        message: &str,
844598×
        extra_deps: &[ChangeHash],
845598×
        selection: &Selection,
846598×
    ) -> Result<ChangeHash> {
847598×
        Ok(self
848598×
            .commit_selection_partial(message, extra_deps, selection)?
849
            .0)
850598×
    }
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.
855624×
    pub fn commit_selection_partial(
856624×
        &self,
857624×
        message: &str,
858624×
        extra_deps: &[ChangeHash],
859624×
        selection: &Selection,
860624×
    ) -> 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).
863624×
        let batch = self.store.begin_batch()?;
864624×
        let out = self.commit_selection_batched(message, extra_deps, selection);
865624×
        batch.finish()?;
866624×
        out
867624×
    }
868
869
    /// Write the manifest a commit's snapshot left to the commit, with the
870
    /// graph keys `keys` sets.
871410×
    fn write_pending_manifest(
872410×
        &self,
873410×
        mut m: PendingManifest,
874410×
        conflicted: bool,
875410×
        keys: HashMap<String, [u8; 32]>,
876410×
    ) -> Result<()> {
8772804×
        for (path, k) in keys {
8782804×
            if let Some(e) = m.entries.get_mut(&path) {
8792804×
                e.graph_key = Some(k);
8802804×
            }
881
        }
882410×
        self.write_manifest_entries_as_of(
883410×
            conflicted,
884
            false,
885410×
            &m.entries,
886410×
            &m.blobs,
887410×
            m.written,
888410×
            m.dirs.unwrap_or_default(),
889
        )
890410×
    }
891
892624×
    fn commit_selection_batched(
893624×
        &self,
894624×
        message: &str,
895624×
        extra_deps: &[ChangeHash],
896624×
        selection: &Selection,
897624×
    ) -> Result<(ChangeHash, bool)> {
898624×
        let _wc = self.lock_working_copy()?;
899624×
        let mut snap = match self.snapshot_from_cache()? {
900205×
            Some(snap) => snap,
901419×
            None => self.snapshot_as("oxy commit", true, true)?,
902
        };
903624×
        let pending = snap.manifest.take();
904624×
        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");
910621×
        }
911621×
        if let Some(s) = snap
912621×
            .statuses
913621×
            .iter()
9143467×
            .find(|s| s.status == ChangeStatus::ConflictEdited)
915
        {
9160×
            return fail(format!("{} still contains conflict markers", s.path));
917621×
        }
918621×
        if message.trim().is_empty() {
9190×
            return fail("a commit message is required");
920621×
        }
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).
924621×
        let wc_refs = referenced_changes(&snap.wc, &snap.base);
9253467×
        let changed_paths: Vec<String> = snap.statuses.iter().map(|s| s.path.clone()).collect();
926621×
        let (tree_ops, edits, partial) = match selection {
927613×
            Selection::All => (
928613×
                std::mem::take(&mut snap.wc.tree_ops),
929613×
                std::mem::take(&mut snap.wc.edits),
930613×
                false,
931613×
            ),
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
        };
943621×
        if tree_ops.is_empty() && edits.is_empty() {
9440×
            return fail("nothing selected to commit");
945621×
        }
946621×
        if partial && snap.resolves {
9470×
            return fail("a conflict resolution must be committed whole");
948621×
        }
949
        // pre-commit hook: may veto.
950621×
        self.run_hook(
951621×
            "pre-commit",
952621×
            &format!(
953
                "{{\"event\":\"pre-commit\",\"message\":{},\"paths\":{}}}",
954621×
                json_str(message),
9553467×
                json_array(snap.statuses.iter().map(|s| format!(
956
                    "{{\"path\":{},\"status\":{}}}",
9573467×
                    json_str(&s.path),
9583467×
                    json_str(&format!("{:?}", s.status))
959
                )))
960
            ),
9611×
        )?;
962620×
        let (op_ref, op) = self.head_op()?;
963620×
        let mut deps: BTreeSet<ChangeHash> = wc_refs;
964
        // semantic-deps hook: may add explicit dependencies (spec §8.1).
965620×
        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
            }
993619×
        }
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.
997620×
        deps.extend(snap.contributors.iter().copied());
998620×
        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
        }
1006620×
        let mut change = Change {
1007
            version: crate::objects::CHANGE_VERSION,
1008620×
            change_id: if partial {
10096×
                ChangeId::random()
1010
            } else {
1011614×
                snap.wc.change_id
1012
            },
1013620×
            deps: vec![],
1014620×
            author: self.author(),
1015620×
            hlc: Hlc::now(),
1016620×
            message: message.trim_end().to_string(),
1017620×
            tree_ops,
1018620×
            edits,
1019620×
            kind: if snap.resolves {
10207×
                ChangeKind::Resolution
1021
            } else {
1022613×
                ChangeKind::Normal
1023
            },
1024
        };
1025620×
        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×
            }
1032614×
        }
1033620×
        change.deps = deps.into_iter().collect();
1034620×
        change.normalize();
1035620×
        let signing = crate::timing::phase("commit: sign and store");
1036620×
        let hash = self.store_signed(&change)?;
1037619×
        drop(signing);
1038619×
        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.
1044619×
        let old_heads = self.heads_of(&op.view, &self.config.bookmark)?;
1045619×
        let old_base = snap.base.maximal(&snap.wc.deps);
1046619×
        let mut all: Vec<ChangeHash> = old_heads.clone();
1047619×
        all.extend(old_base.iter().copied());
1048619×
        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.
1051619×
        let mut st = if old_heads.iter().all(|h| snap.base.contains(h)) {
1052582×
            snap.base
1053
        } else {
105437×
            self.load_state(&all)?
1055
        };
1056619×
        st.add_hashed(hash, change)?;
1057619×
        let mut with_new = old_heads.clone();
1058619×
        with_new.push(hash);
1059619×
        let new_heads = st.maximal(&with_new);
1060
        // Automatic checkpoint once enough changes accumulated (spec §11).
1061619×
        let since = self
1062619×
            .latest_checkpoint(&self.config.bookmark)?
1063619×
            .map(|(_, cp)| cp.count)
1064619×
            .unwrap_or(0);
1065619×
        if self.config.checkpoint_interval > 0
1066619×
            && (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)?;
1070617×
        }
1071619×
        let mut wc_base = old_base.clone();
1072619×
        wc_base.push(hash);
1073619×
        let wc_base = st.maximal(&wc_base);
1074619×
        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.
1080619×
        let keying = crate::timing::phase("commit: graph keys of the files");
1081619×
        let committed_keys =
1082619×
            (!partial).then(|| self.committed_graph_keys(&st, &changed_paths, &snap.attributes));
1083619×
        drop(keying);
1084619×
        let recording = crate::timing::phase("commit: record");
1085619×
        let wc = self.new_working_copy(wc_base, "");
1086619×
        let wc_hash = self.store.put_change(&wc)?;
1087619×
        let mut view = op.view.clone();
1088619×
        view.bookmarks.insert(
1089619×
            self.config.bookmark.clone(),
1090619×
            self.store.put_state(&StateObject::new(new_heads))?,
1091
        );
1092619×
        view.workspaces.insert(self.workspace, wc_hash);
1093619×
        self.record_op(&[op_ref], &format!("oxy commit -m {message:?}"), view)?;
1094614×
        drop(recording);
1095614×
        let rewriting = crate::timing::phase("commit: manifest");
1096614×
        if partial {
10976×
            // The rest is rebuilt from disk by the next snapshot.
10986×
            self.drop_manifest();
10996×
        } else {
1100608×
            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).
1104608×
            let keys = if conflicted {
11050×
                HashMap::new()
1106
            } else {
1107608×
                committed_keys.unwrap_or_default()
1108
            };
1109608×
            match pending {
1110407×
                Some(m) => self.write_pending_manifest(m, conflicted, keys)?,
1111201×
                None => self.rewrite_manifest(conflicted, false, &keys)?,
1112
            }
1113
        }
1114614×
        drop(rewriting);
1115614×
        let packing = crate::timing::phase("commit: autopack");
1116614×
        self.maybe_autopack()?;
1117614×
        drop(packing);
1118614×
        let _hook = crate::timing::phase("commit: hook");
1119614×
        let _ = self.run_hook(
1120614×
            "post-commit",
1121614×
            &format!(
1122614×
                "{{\"event\":\"post-commit\",\"change_id\":{},\"hash\":{},\"message\":{}}}",
1123614×
                json_str(&snap.wc.change_id.to_hex()),
1124614×
                json_str(&hash.to_hex()),
1125614×
                json_str(message)
1126614×
            ),
1127614×
        );
1128614×
        Ok((hash, partial))
1129624×
    }
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.
1684625×
    pub(crate) fn snapshot_from_cache(&self) -> Result<Option<SnapshotResult>> {
1685625×
        let Some(statuses) = self.status_by_manifest()? else {
1686417×
            return Ok(None);
1687
        };
1688208×
        if statuses.is_empty() {
16892×
            return Ok(None);
1690206×
        }
1691206×
        let _t = crate::timing::phase("snapshot: from the status cache");
1692206×
        let (wc_hash, wc) = self.working_copy()?;
1693206×
        let base = self.load_state_indexed(&wc.deps)?;
1694206×
        let (base, base_snapshot) = self.render_base_for(&wc, base)?;
1695206×
        let attribute_files: Vec<(String, Vec<u8>)> = match self.read_manifest()? {
1696206×
            Some((_, _, m)) => m
1697206×
                .entries
1698206×
                .keys()
1699641×
                .filter(|p| is_attributes(p))
1700206×
                .filter_map(|p| fs::read(self.root.join(p)).ok().map(|b| (p.clone(), b)))
1701206×
                .collect(),
17020×
            None => Vec::new(),
1703
        };
1704206×
        let attributes = crate::attributes::Attributes::from_files(
1705206×
            attribute_files
1706206×
                .iter()
1707206×
                .map(|(p, b)| (p.as_str(), b.as_slice())),
1708
        );
1709206×
        Ok(Some(SnapshotResult {
1710206×
            wc_hash,
1711206×
            wc,
1712206×
            base,
1713206×
            base_snapshot,
1714206×
            statuses,
1715206×
            changed: false,
1716206×
            resolves: false,
1717206×
            contributors: Vec::new(),
1718206×
            attributes,
1719206×
            untracked_nested: self.untracked_nested.borrow().clone(),
1720206×
            manifest: None,
1721206×
        }))
1722625×
    }
1723
1724
    /// The working-copy change with its base state and a snapshot of the
1725
    /// base, for showing what the working copy changes ([`render_change`],
1726
    /// [`diff_files_of`]). While the status cache holds (every file as the
1727
    /// last snapshot left it), the stored working-copy change is the
1728
    /// answer, no snapshot is taken, and the base's snapshot holds its tree
1729
    /// but no file; otherwise a snapshot makes all three.
17304×
    pub fn working_copy_with_base(&self) -> Result<(Change, State, Snapshot)> {
17314×
        if self.status_by_manifest()?.is_some() {
17322×
            let (_, wc) = self.working_copy()?;
17332×
            let base = self.load_state_indexed(&wc.deps)?;
17342×
            let (base, snapshot) = self.tree_base_for(&wc, base)?;
17352×
            return Ok((wc, base, snapshot));
17362×
        }
17372×
        let snap = self.snapshot_status("oxy diff")?;
17382×
        Ok((snap.wc, snap.base, snap.base_snapshot))
17394×
    }
1740
1741
    /// The log restricted to changes touching `path` (its node, so renames
1742
    /// are followed), on the current bookmark.
17435×
    pub fn log_for_path(&self, path: &str) -> Result<Vec<LogEntry>> {
17445×
        let heads = self.bookmark_heads()?;
17455×
        if self.is_bare() {
17461×
            return self.log_for_path_in(path, &heads);
17474×
        }
17484×
        let entries = self.log()?;
17494×
        let (_, wc) = self.working_copy()?;
1750
        // The path's node from the trees alone: the base's (from the
1751
        // workspace's state index), else the bookmark's. Nothing is
1752
        // rendered.
17534×
        let node_in = |state: State| state.tree().view().entries.get(path).map(|e| e.node);
17544×
        let node = match node_in(self.load_state_indexed(&wc.deps)?) {
17554×
            Some(n) => Some(n),
17560×
            None => node_in(self.load_state_history(&heads)?),
1757
        };
17584×
        let Some(node) = node else {
17590×
            return fail(format!("{path} is not tracked"));
1760
        };
17614×
        Ok(self.entries_touching(entries, node))
17625×
    }
1763
1764
    /// The log of the state with these heads restricted to changes touching
1765
    /// `path` (its node, so renames are followed).
17662×
    pub fn log_for_path_in(&self, path: &str, heads: &[ChangeHash]) -> Result<Vec<LogEntry>> {
17672×
        self.log_for_path_of(&self.load_state_history(heads)?, path, None)
17682×
    }
1769
1770
    /// The changes of a loaded state touching `path`, newest first, at most
1771
    /// `limit` of them. The path is found in the state's tree alone, so no
1772
    /// file is rendered, and the walk stops once `limit` are found.
17735×
    pub fn log_for_path_of(
17745×
        &self,
17755×
        state: &State,
17765×
        path: &str,
17775×
        limit: Option<usize>,
17785×
    ) -> Result<Vec<LogEntry>> {
17795×
        let Some(node) = state.tree().view().entries.get(path).map(|e| e.node) else {
17801×
            return fail(format!("{path} is not in that state"));
1781
        };
17824×
        Ok(self.entries_touching_up_to(self.log_of(state), node, limit))
17835×
    }
1784
17854×
    fn entries_touching(&self, entries: Vec<LogEntry>, node: NodeId) -> Vec<LogEntry> {
17864×
        self.entries_touching_up_to(entries, node, None)
17874×
    }
1788
17898×
    fn entries_touching_up_to(
17908×
        &self,
17918×
        entries: Vec<LogEntry>,
17928×
        node: NodeId,
17938×
        limit: Option<usize>,
17948×
    ) -> Vec<LogEntry> {
17958×
        let mut touched = self.touched();
17968×
        if limit.is_none() {
17977×
            let hashes: Vec<ChangeHash> = entries.iter().map(|e| e.hash).collect();
17987×
            touched.fill(self, &hashes);
17991×
        }
18008×
        let wanted = HashSet::from([node]);
18018×
        let mut out = Vec::new();
180228×
        for e in entries {
180328×
            if limit.is_some_and(|n| out.len() >= n) {
18041×
                break;
180527×
            }
180627×
            if touched.touches(self, &e.hash, &wanted) {
180718×
                out.push(e);
180818×
            }
1809
        }
18108×
        touched.save();
18118×
        out
18128×
    }
1813
}
1814
1815
/// Per-file hunks of `change` against `base`.
18165×
pub fn diff_files_of(change: &Change, base: &State, base_snapshot: &Snapshot) -> Vec<FileDiff> {
18175×
    let by_node = base_snapshot.tree.by_node();
18185×
    let mut new_names: HashMap<NodeId, (NodeId, String, NodeKind)> = HashMap::new();
18195×
    for op in &change.tree_ops {
1820
        if let TreeOp::AddNode {
18212×
            node,
18222×
            parent,
18232×
            name,
18242×
            kind,
1825
            ..
18263×
        } = op
18272×
        {
18282×
            new_names.insert(*node, (*parent, name.clone(), *kind));
18292×
        }
1830
    }
18319×
    let path_of = |n: &NodeId| -> String {
18329×
        path_of_node(n, &by_node, &new_names).unwrap_or_else(|| format!("<node {}>", n.short(8)))
18339×
    };
18345×
    let mut files: BTreeMap<NodeId, FileDiff> = BTreeMap::new();
18355×
    let mut order: Vec<NodeId> = Vec::new();
183614×
    let mut entry = |files: &mut BTreeMap<NodeId, FileDiff>, n: NodeId, kind: &str| {
183714×
        if let std::collections::btree_map::Entry::Vacant(v) = files.entry(n) {
18389×
            order.push(n);
18399×
            v.insert(FileDiff {
18409×
                path: path_of(&n),
18419×
                kind: kind.to_string(),
18429×
                hunks: vec![],
18439×
                from: None,
18449×
            });
18459×
        }
184614×
    };
18475×
    for op in &change.tree_ops {
18483×
        match op {
18492×
            TreeOp::AddNode { node, kind, .. } => {
18502×
                if *kind != NodeKind::Dir {
18512×
                    entry(&mut files, *node, "added");
18522×
                }
1853
            }
18541×
            TreeOp::RemoveNode { node, .. } => {
18551×
                entry(&mut files, *node, "removed");
18561×
                if let Some(e) = by_node.get(node) {
18571×
                    files.get_mut(node).unwrap().path = e.path.clone();
18581×
                }
1859
            }
1860
            TreeOp::Move {
18610×
                node, parent, name, ..
1862
            } => {
18630×
                entry(&mut files, *node, "renamed");
18640×
                let f = files.get_mut(node).unwrap();
18650×
                f.from = by_node.get(node).map(|e| e.path.clone());
18660×
                let dir = if parent.is_root() {
18670×
                    String::new()
1868
                } else {
18690×
                    path_of_node(parent, &by_node, &new_names).unwrap_or_default()
1870
                };
18710×
                f.path = if dir.is_empty() {
18720×
                    name.clone()
1873
                } else {
18740×
                    format!("{dir}/{name}")
1875
                };
1876
            }
18770×
            TreeOp::SetMode { node, .. } => entry(&mut files, *node, "mode"),
1878
        }
1879
    }
1880
    // Base line numbers per node, 1-based.
18815×
    let mut line_of: HashMap<NodeId, HashMap<(ChangeHash, u32), u32>> = HashMap::new();
188211×
    let mut lines_for = |n: &NodeId| -> HashMap<(ChangeHash, u32), u32> {
188311×
        line_of
188411×
            .entry(*n)
188511×
            .or_insert_with(|| {
18868×
                base.live_lines(n)
18878×
                    .into_iter()
18888×
                    .enumerate()
188911×
                    .map(|(i, (k, _))| (k, i as u32 + 1))
18908×
                    .collect()
18918×
            })
189211×
            .clone()
189311×
    };
189411×
    for e in &change.edits {
189511×
        let n = e.node();
189611×
        let is_new = new_names.contains_key(&n);
189711×
        entry(&mut files, n, if is_new { "added" } else { "modified" });
189811×
        let f = files.get_mut(&n).unwrap();
189911×
        match e {
19009×
            Edit::Insert { after, lines, .. } => {
19019×
                let map = lines_for(&n);
19029×
                let base_line = match after {
19033×
                    AtomRef::Start => 0,
19040×
                    AtomRef::End => map.len() as u32,
19056×
                    AtomRef::Atom { change, index } if change.is_zero() => {
19060×
                        f.hunks.last().map(|h| h.base_line).unwrap_or(0)
1907
                    }
19086×
                    AtomRef::Atom { change, index } => {
19096×
                        map.get(&(*change, *index)).copied().unwrap_or(0)
1910
                    }
1911
                };
19129×
                f.hunks.push(DiffHunk {
19139×
                    base_line,
19149×
                    added: lines.to_vec(),
19159×
                    removed: vec![],
19169×
                });
1917
            }
19182×
            Edit::Delete { atoms, .. } => {
19192×
                let map = lines_for(&n);
19202×
                let mut removed = Vec::new();
19212×
                for r in atoms {
19222×
                    for i in r.from..r.to {
19232×
                        let line = map.get(&(r.change, i)).copied().unwrap_or(0);
19242×
                        let text = base
19252×
                            .file(&n)
19262×
                            .and_then(|g| g.content(&(r.change, i)))
19272×
                            .unwrap_or(b"")
19282×
                            .to_vec();
19292×
                        removed.push((line, text));
1930
                    }
1931
                }
19322×
                let base_line = removed
19332×
                    .first()
19342×
                    .map(|(l, _)| l.saturating_sub(1))
19352×
                    .unwrap_or(0);
19362×
                f.hunks.push(DiffHunk {
19372×
                    base_line,
19382×
                    added: vec![],
19392×
                    removed,
19402×
                });
1941
            }
1942
            Edit::Replace { .. } => {
19430×
                if !is_new {
19440×
                    f.kind = "replaced".into();
19450×
                }
1946
            }
1947
        }
1948
    }
19499×
    order.into_iter().filter_map(|n| files.remove(&n)).collect()
19505×
}
1951
1952
/// Builds the tree ops and edits of a working-copy change against a base.
1953
/// `BLAKE3("oxy node 1" 0 seed kind path)`, truncated: a node identifier
1954
/// that the same seed and path always give (never the root's).
195557×
fn seeded_node(seed: &[u8; 32], path: &str, kind: NodeKind) -> NodeId {
195657×
    let mut h = blake3::Hasher::new();
195757×
    h.update(b"oxy node 1\0");
195857×
    h.update(seed);
195957×
    h.update(&[match kind {
196043×
        NodeKind::File => 1,
196113×
        NodeKind::Dir => 2,
19620×
        NodeKind::Symlink => 3,
19631×
        NodeKind::Subrepo => 4,
1964
    }]);
196557×
    h.update(path.as_bytes());
196657×
    let mut id = [0u8; 16];
196757×
    id.copy_from_slice(&h.finalize().as_bytes()[..16]);
196857×
    if id == [0; 16] {
19690×
        id[15] = 1;
197057×
    }
197157×
    NodeId(id)
197257×
}
1973
1974
struct ChangeBuilder<'a> {
1975
    base: &'a State,
1976
    base_snapshot: &'a Snapshot,
1977
    tree_ops: Vec<TreeOp>,
1978
    edits: Vec<Edit>,
1979
    statuses: Vec<PathStatus>,
1980
    dir_nodes: HashMap<String, NodeId>,
1981
    reuse: HashMap<String, (NodeId, NodeKind)>,
1982
    /// Changes that contributed to conflicts this working copy resolves.
1983
    contributors: BTreeSet<ChangeHash>,
1984
    resolves: bool,
1985
    attrs: crate::attributes::Attributes,
1986
    blobs: HashMap<String, ObjectRef>,
1987
    /// Opaque files whose replace conflict the content settles.
1988
    resolve: HashSet<String>,
1989
    /// When set, new nodes' identifiers derive from it and their paths.
1990
    node_seed: Option<[u8; 32]>,
1991
    /// For a Git import, the base's dead directories by where they were
1992
    /// (see `ensure_dir`), worked out when first needed.
1993
    dead_dirs: Option<HashMap<(NodeId, String), (NodeId, crate::tree::OpKey)>>,
1994
    /// Text edits of edited files, worked out in parallel beforehand
1995
    /// (`diff_in_parallel`); a file not here is diffed when it is updated.
1996
    diffs: HashMap<String, Vec<Edit>>,
1997
}
1998
1999
impl<'a> ChangeBuilder<'a> {
20001852×
    fn new(
20011852×
        base: &'a State,
20021852×
        base_snapshot: &'a Snapshot,
20031852×
        reuse: HashMap<String, (NodeId, NodeKind)>,
20041852×
    ) -> Self {
20051852×
        let mut dir_nodes: HashMap<String, NodeId> = HashMap::new();
20061852×
        dir_nodes.insert(String::new(), NodeId::ROOT);
200717583×
        for (p, e) in base_snapshot.tree.entries.iter() {
200817583×
            if e.kind == NodeKind::Dir {
2009532×
                dir_nodes.insert(p.clone(), e.node);
201017051×
            }
2011
        }
20121852×
        ChangeBuilder {
20131852×
            base,
20141852×
            base_snapshot,
20151852×
            tree_ops: vec![],
20161852×
            edits: vec![],
20171852×
            statuses: vec![],
20181852×
            dir_nodes,
20191852×
            reuse,
20201852×
            contributors: BTreeSet::new(),
20211852×
            resolves: false,
20221852×
            attrs: crate::attributes::Attributes::default(),
20231852×
            blobs: HashMap::new(),
20241852×
            resolve: HashSet::new(),
20251852×
            node_seed: None,
20261852×
            dead_dirs: None,
20271852×
            diffs: HashMap::new(),
20281852×
        }
20291852×
    }
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.
20341852×
    fn diff_in_parallel(&mut self, entries: &BTreeMap<String, FsEntry>) {
2035
        use rayon::prelude::*;
20361852×
        let files = &self.base_snapshot.files;
20371852×
        let edited: Vec<(&String, &FsEntry, &crate::state::FileState)> = entries
20381852×
            .iter()
203918550×
            .filter_map(|(p, e)| {
204018550×
                let x = files.get(p)?;
204112585×
                (x.kind == e.kind && !e.unchanged && !self.opaque_for(p, e)).then_some((p, e, x))
204218550×
            })
20431852×
            .collect();
2044
        // Below this, starting the threads costs more than it saves.
20451852×
        if edited.len() < 16 {
20461842×
            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();
20801852×
    }
2081
20821852×
    fn with_attributes(mut self, attrs: crate::attributes::Attributes) -> Self {
20831852×
        self.attrs = attrs;
20841852×
        self
20851852×
    }
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
210522644×
    fn opaque_for(&self, path: &str, e: &FsEntry) -> bool {
210622644×
        if e.blob.is_some() {
21078×
            return true;
210822636×
        }
210922636×
        if e.kind == NodeKind::Symlink || e.kind == NodeKind::Subrepo {
211075×
            return true;
211122561×
        }
211222561×
        match self.attrs.lookup(path).binary {
211312×
            Some(true) => true,
21140×
            Some(false) => is_binary(&e.content),
211522549×
            None => is_binary(&e.content),
2116
        }
211722644×
    }
2118
2119
    /// Text content as stored: `\r\n` normalized for `eol=` files.
212014181×
    fn stored_text(
212114181×
        &self,
212214181×
        path: &str,
212314181×
        content: &std::sync::Arc<Vec<u8>>,
212414181×
    ) -> std::sync::Arc<Vec<u8>> {
212514181×
        if self.attrs.lookup(path).eol.is_some() {
21267×
            std::sync::Arc::new(crate::attributes::normalize_eol(content))
2127
        } else {
212814174×
            content.clone()
2129
        }
213014181×
    }
2131
2132
    /// The identifier of a node added at `path`: reused when asked, derived
2133
    /// from the seed when there is one, random otherwise.
21346085×
    fn new_node(&self, path: &str, kind: NodeKind) -> NodeId {
21356085×
        if let Some(n) = self.reused_node(path, kind) {
2136134×
            return n;
21375951×
        }
21385951×
        match &self.node_seed {
213957×
            Some(seed) => seeded_node(seed, path, kind),
21405894×
            None => NodeId::random(),
2141
        }
21426085×
    }
2143
21446085×
    fn reused_node(&self, path: &str, kind: NodeKind) -> Option<NodeId> {
21456085×
        self.reuse
21466085×
            .get(path)
21476085×
            .filter(|(_, k)| *k == kind)
21486085×
            .map(|(n, _)| *n)
21496085×
    }
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) {
21665818×
            return *n;
2167148×
        }
2168148×
        let mut parent = NodeId::ROOT;
2169148×
        let mut prefix = String::new();
2170167×
        for comp in path.split('/') {
2171167×
            if !prefix.is_empty() {
217219×
                prefix.push('/');
2173148×
            }
2174167×
            prefix.push_str(comp);
2175167×
            let known = self.dir_nodes.get(&prefix).copied();
2176167×
            let revive = match known {
217713×
                Some(_) => None,
2178154×
                None if self.node_seed.is_some() => self.revivable_dir(parent, comp),
2179139×
                None => None,
2180
            };
2181167×
            parent = match (known, revive) {
218213×
                (Some(n), _) => n,
21832×
                (None, Some((node, old))) => {
2184
                    // Git has no identity for a directory: one that comes
2185
                    // back where it was is the same directory, brought back
2186
                    // with a move, so lines of history that placed files in
2187
                    // it before and after agree (oxygen#30).
21882×
                    self.tree_ops.push(TreeOp::Move {
21892×
                        node,
21902×
                        old: OpRef {
21912×
                            change: old.0,
21922×
                            index: old.1,
21932×
                        },
21942×
                        parent,
21952×
                        name: comp.to_string(),
21962×
                    });
21972×
                    self.dir_nodes.insert(prefix.clone(), node);
21982×
                    node
2199
                }
2200
                (None, None) => {
2201152×
                    let node = self.new_node(&prefix, NodeKind::Dir);
2202152×
                    self.tree_ops.push(TreeOp::AddNode {
2203152×
                        node,
2204152×
                        kind: NodeKind::Dir,
2205152×
                        mode: Mode::default(),
2206152×
                        parent,
2207152×
                        name: comp.to_string(),
2208152×
                    });
2209152×
                    self.dir_nodes.insert(prefix.clone(), node);
2210152×
                    node
2211
                }
2212
            };
2213
        }
2214148×
        parent
22155966×
    }
2216
22175933×
    fn add_path(&mut self, repo: &Repo, path: &str, e: &FsEntry) -> Result<()> {
22185933×
        let (dir, name) = split_path(path);
22195933×
        let parent = self.ensure_dir(dir);
22205933×
        let node = self.new_node(path, e.kind);
22215933×
        let opaque = self.opaque_for(path, e);
22225933×
        let nocompress = self.attrs.lookup(path).nocompress;
22235933×
        self.tree_ops.push(TreeOp::AddNode {
22245933×
            node,
22255933×
            kind: e.kind,
22265933×
            mode: Mode {
22275933×
                exec: e.exec,
22285933×
                opaque,
22295933×
            },
22305933×
            parent,
22315933×
            name: name.to_string(),
22325933×
        });
22335933×
        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×
            });
22405842×
        } else if !e.content.is_empty() {
22415809×
            let content = self.stored_text(path, &e.content);
22425809×
            self.edits.push(Edit::Insert {
22435809×
                node,
22445809×
                after: crate::objects::AtomRef::Start,
22455809×
                before: crate::objects::AtomRef::End,
22465809×
                lines: crate::lines::Lines::split_shared(content),
22475809×
            });
22485809×
        }
22495933×
        self.statuses.push(PathStatus {
22505933×
            path: path.to_string(),
22515933×
            status: ChangeStatus::Added,
22525933×
        });
22535933×
        Ok(())
22545933×
    }
2255
2256
    /// Move the node at `old` to `new` and apply `e`'s content to it.
225733×
    fn move_path(
225833×
        &mut self,
225933×
        repo: &Repo,
226033×
        old: &str,
226133×
        new: &str,
226233×
        e: &FsEntry,
226333×
        expected: &crate::state::FileState,
226433×
    ) -> Result<()> {
226533×
        let placement = self.base_snapshot.tree.entries[old].placement;
226633×
        let (dir, name) = split_path(new);
226733×
        let parent = self.ensure_dir(dir);
226833×
        self.tree_ops.push(TreeOp::Move {
226933×
            node: expected.node,
227033×
            old: op_ref(placement),
227133×
            parent,
227233×
            name: name.to_string(),
227333×
        });
227433×
        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×
        }
228033×
        self.update_path(repo, old, e, expected)?;
2281
        // update_path reports under the old path; the rename is what the user sees.
228233×
        self.statuses.retain(|s| s.path != old);
228333×
        self.statuses.push(PathStatus {
228433×
            path: new.to_string(),
228533×
            status: ChangeStatus::Renamed,
228633×
        });
228733×
        Ok(())
228833×
    }
2289
2290
    /// For a Git import: a node the commit keeps is in one place, the one
2291
    /// its tree names, so any other live placement it has in the base goes;
2292
    /// and a node the tree cannot show at all (an orphan) goes too. Such a
2293
    /// placement is out of sight, under a directory another line of history
2294
    /// removed, where no diff of the tree would ever reach it (oxygen#30).
229586×
    fn retire_stray_placements(&mut self) {
229686×
        let mut retired: HashSet<(ChangeHash, u32)> = HashSet::new();
229786×
        let mut placed: BTreeSet<NodeId> = BTreeSet::new();
229897×
        for op in &self.tree_ops {
229997×
            match op {
230019×
                TreeOp::Move { node, old, .. } => {
230119×
                    retired.insert((old.change, old.index));
230219×
                    placed.insert(*node);
230319×
                }
230421×
                TreeOp::RemoveNode { placement, .. } => {
230521×
                    retired.insert((placement.change, placement.index));
230621×
                }
230757×
                TreeOp::AddNode { .. } | TreeOp::SetMode { .. } => {}
2308
            }
2309
        }
2310
        // Nodes kept where they were: what the base's tree view shows and
2311
        // this change neither moves nor removes.
231286×
        let mut kept: HashMap<NodeId, (ChangeHash, u32)> = HashMap::new();
2313240×
        for e in self.base_snapshot.tree.entries.values() {
2314240×
            if !retired.contains(&e.placement) {
2315203×
                kept.insert(e.node, e.placement);
2316203×
            }
2317
        }
2318
        // Only a node with several live placements can have a stray one,
2319
        // and the tree view names each as a conflict.
232086×
        let multi: BTreeSet<NodeId> = self
232186×
            .base_snapshot
232286×
            .tree
232386×
            .conflicts
232486×
            .iter()
232586×
            .filter_map(|c| match c {
23261×
                crate::tree::TreeConflict::MultiPlacement { node, .. } => Some(*node),
23276×
                _ => None,
23287×
            })
232986×
            .collect();
233086×
        let mut extra = Vec::new();
2331
        // A node whose only placements are under a directory another line
2332
        // removed (an orphan) is nowhere the tree can show, and Git's tree
2333
        // has no such path: it goes.
233486×
        for c in &self.base_snapshot.tree.conflicts {
23357×
            let crate::tree::TreeConflict::Orphan { node, .. } = c else {
23366×
                continue;
2337
            };
23381×
            if kept.contains_key(node) || placed.contains(node) {
23390×
                continue;
23401×
            }
23411×
            for (k, _) in self.base.tree().live_placements(node) {
23421×
                if retired.insert(k) {
23431×
                    extra.push(TreeOp::RemoveNode {
23441×
                        node: *node,
23451×
                        placement: op_ref(k),
23461×
                    });
23471×
                }
2348
            }
2349
        }
235086×
        for node in placed
235186×
            .iter()
235286×
            .chain(multi.iter().filter(|n| kept.contains_key(*n)))
2353
        {
235419×
            for (k, _) in self.base.tree().live_placements(node) {
235518×
                if retired.contains(&k) || kept.get(node) == Some(&k) {
235617×
                    continue;
23571×
                }
23581×
                retired.insert(k);
23591×
                extra.push(TreeOp::RemoveNode {
23601×
                    node: *node,
23611×
                    placement: op_ref(k),
23621×
                });
2363
            }
2364
        }
236586×
        if !extra.is_empty() {
23662×
            self.resolves = true;
23672×
            self.tree_ops.extend(extra);
236884×
        }
236986×
    }
2370
2371
    /// The node's other live placements at the same place as `k`, the one
2372
    /// the tree shows: two lines of history that put a node back where it
2373
    /// was each leave a placement, and the tree shows them as one file. A
2374
    /// change that removes or moves it retires them together, or the copy
2375
    /// left behind outlives its directory (oxygen#88).
2376156×
    fn same_place(&self, node: &NodeId, k: (ChangeHash, u32)) -> Vec<(ChangeHash, u32)> {
2377156×
        let tree = self.base.tree();
2378156×
        let Some(shown) = tree.placement(&k) else {
23790×
            return Vec::new();
2380
        };
2381156×
        tree.live_placements(node)
2382156×
            .into_iter()
2383158×
            .filter(|(o, p)| *o != k && p.parent == shown.parent && p.name == shown.name)
2384156×
            .map(|(o, _)| o)
2385156×
            .collect()
2386156×
    }
2387
2388123×
    fn remove_path(&mut self, path: &str, expected: &crate::state::FileState) {
2389123×
        let entry = &self.base_snapshot.tree.entries[path];
2390123×
        let placement = entry.placement;
2391123×
        self.tree_ops.push(TreeOp::RemoveNode {
2392123×
            node: expected.node,
2393123×
            placement: op_ref(placement),
2394123×
        });
2395123×
        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×
        }
2401123×
        if path.contains(".oxy-conflict-") || expected.is_conflicted() {
24027×
            self.resolves = true;
2403116×
        }
2404123×
        self.statuses.push(PathStatus {
2405123×
            path: path.to_string(),
2406123×
            status: ChangeStatus::Removed,
2407123×
        });
2408123×
    }
2409
241012618×
    fn update_path(
241112618×
        &mut self,
241212618×
        repo: &Repo,
241312618×
        path: &str,
241412618×
        e: &FsEntry,
241512618×
        expected: &crate::state::FileState,
241612618×
    ) -> Result<()> {
241712618×
        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(());
242712617×
        }
242812617×
        let entry = &self.base_snapshot.tree.entries[path];
242912617×
        let node = expected.node;
243012617×
        let mode_atom = entry.mode_atom.map(op_ref);
243112617×
        if e.unchanged {
2432
            // Known equal to the base's unconflicted rendering (spec
2433
            // §12.3); only the executable bit can differ.
24344245×
            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×
                }
24494242×
            }
24504245×
            return Ok(());
24518372×
        }
24528372×
        let mut status: Option<ChangeStatus> = None;
24538372×
        let wants_opaque = self.opaque_for(path, e);
24548372×
        let nocompress = self.attrs.lookup(path).nocompress;
24558372×
        let disk_text = self.stored_text(path, &e.content);
24568372×
        match &expected.content {
24570×
            FileContent::Dir => {}
2458
            FileContent::Text {
24598149×
                bytes,
24608149×
                materialized,
2461
            } => {
24628149×
                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(());
25088116×
                }
25098116×
                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);
25358114×
                } else if bytes != &*disk_text {
2536768×
                    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).
2539768×
                    let edits = match self.diffs.remove(path) {
254080×
                        Some(edits) => edits,
2541
                        None => {
2542688×
                            let keys = materialized.live_atoms();
2543688×
                            let lines = crate::diff::split_lines(bytes);
2544688×
                            if keys.len() == lines.len() {
2545688×
                                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
                    };
2551768×
                    laps.lap("build: text diff");
2552768×
                    if !edits.is_empty() {
2553768×
                        self.edits.extend(edits);
2554768×
                        status = Some(ChangeStatus::Modified);
2555768×
                    }
25567346×
                }
25578116×
                let switched_to_opaque = wants_opaque;
25588116×
                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×
                    }
25708112×
                }
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
        }
26748335×
        if let Some(s) = status {
2675807×
            self.statuses.push(PathStatus {
2676807×
                path: path.to_string(),
2677807×
                status: s,
2678807×
            });
26797528×
        }
26808335×
        Ok(())
268112618×
    }
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.
26901946×
pub fn referenced_changes(change: &Change, base: &State) -> BTreeSet<ChangeHash> {
26911946×
    let mut out = BTreeSet::new();
26921946×
    let opref = |r: &OpRef, out: &mut BTreeSet<ChangeHash>| {
2693189×
        if !r.change.is_zero() {
2694189×
            out.insert(r.change);
2695189×
        }
2696189×
    };
26971946×
    let mut nodes: Vec<NodeId> = Vec::new();
26986483×
    for op in &change.tree_ops {
26996483×
        match op {
27006294×
            TreeOp::AddNode { parent, .. } => nodes.push(*parent),
2701141×
            TreeOp::RemoveNode { node, placement } => {
2702141×
                nodes.push(*node);
2703141×
                opref(placement, &mut out);
2704141×
            }
2705
            TreeOp::Move {
270636×
                node, old, parent, ..
270736×
            } => {
270836×
                nodes.push(*node);
270936×
                nodes.push(*parent);
271036×
                opref(old, &mut out);
271136×
            }
271212×
            TreeOp::SetMode { node, old, .. } => {
271312×
                nodes.push(*node);
271412×
                opref(old, &mut out);
271512×
            }
2716
        }
2717
    }
27187992×
    for e in &change.edits {
27197992×
        nodes.push(e.node());
2720128×
        match e {
27217326×
            Edit::Insert { after, before, .. } => {
272214652×
                for r in [after, before] {
272314652×
                    if let crate::objects::AtomRef::Atom { change, .. } = r {
27242123×
                        if !change.is_zero() {
27252121×
                            out.insert(*change);
27262121×
                        }
272712529×
                    }
2728
                }
2729
            }
2730538×
            Edit::Delete { atoms, .. } => {
2731
                // Deleting an atom also depends on whoever inserted the live
2732
                // atoms right after it: the author saw those insertions, and
2733
                // without the dependency spec §9.1 would call the deletion
2734
                // concurrent with them (a delete/insert conflict).
2735538×
                let graph = base.file(&e.node());
27361083×
                for r in atoms {
27371083×
                    if !r.change.is_zero() {
27381082×
                        out.insert(r.change);
27391082×
                    }
27401083×
                    if let Some(g) = graph {
27411112×
                        for i in r.from..r.to {
27421112×
                            out.extend(
27431112×
                                g.live_successor_changes(&(r.change, i))
27441112×
                                    .into_iter()
27451112×
                                    .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
    }
276814511×
    for n in nodes {
276914511×
        if let Some(h) = base.tree().introducer(&n) {
27702155×
            out.insert(h);
277112356×
        }
2772
    }
27731946×
    out
27741946×
}
2775
2776
/// Paths of the nodes a change adds on top of `base_snapshot`.
27771214×
pub fn added_node_paths(
27781214×
    change: &Change,
27791214×
    base_snapshot: &Snapshot,
27801214×
) -> HashMap<String, (NodeId, NodeKind)> {
27811214×
    let by_node = base_snapshot.tree.by_node();
27821214×
    let mut new_names: HashMap<NodeId, (NodeId, String, NodeKind)> = HashMap::new();
27831214×
    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
    }
27951214×
    let mut out = HashMap::new();
27961214×
    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
    }
28011214×
    out
28021214×
}
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
29561852×
fn detect_renames(
29571852×
    base_snapshot: &Snapshot,
29581852×
    fs_entries: &BTreeMap<String, FsEntry>,
29591852×
    in_scope: impl Fn(&str) -> bool,
29601852×
) -> Vec<(String, String)> {
29611852×
    let removed: Vec<(&String, &crate::state::FileState)> = base_snapshot
29621852×
        .files
29631852×
        .iter()
296413123×
        .filter(|(p, f)| {
296513123×
            f.kind != NodeKind::Dir
296612723×
                && !fs_entries.contains_key(*p)
2967138×
                && in_scope(p)
2968128×
                && !f.is_conflicted()
296913123×
        })
29701852×
        .collect();
29711852×
    let added: Vec<(&String, &FsEntry)> = fs_entries
29721852×
        .iter()
297318550×
        .filter(|(p, e)| e.kind != NodeKind::Dir && !base_snapshot.files.contains_key(*p))
29741852×
        .collect();
29751852×
    if removed.is_empty() || added.is_empty() {
29761792×
        return vec![];
297760×
    }
297860×
    let exact_only = removed.len() * added.len() > RENAME_LIMIT;
297975×
    let old_content = |f: &crate::state::FileState| -> Option<Vec<u8>> {
298075×
        match &f.content {
298171×
            FileContent::Text { bytes, .. } => Some(bytes.clone()),
29824×
            _ => None,
2983
        }
298475×
    };
298560×
    let mut scored: Vec<(u32, usize, usize)> = Vec::new();
298675×
    for (ri, (_, f)) in removed.iter().enumerate() {
298775×
        let old = old_content(f);
298875×
        let old_blob = match &f.content {
29894×
            FileContent::Opaque { blobs } if blobs.len() == 1 => Some(blobs[0]),
299071×
            _ => None,
2991
        };
299294×
        for (ai, (_, e)) in added.iter().enumerate() {
299394×
            if e.kind != f.kind {
29940×
                continue;
299594×
            }
299694×
            let score = match (&old, old_blob) {
299784×
                (Some(o), _) => {
299884×
                    if exact_only {
29990×
                        if *o == *e.content {
30000×
                            100
3001
                        } else {
30020×
                            0
3003
                        }
3004
                    } else {
300584×
                        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
            };
301194×
            if score >= RENAME_THRESHOLD {
301239×
                scored.push((score, ri, ai));
301355×
            }
3014
        }
3015
    }
301660×
    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×
    });
302160×
    let mut used_r = vec![false; removed.len()];
302260×
    let mut used_a = vec![false; added.len()];
302360×
    let mut out = Vec::new();
302460×
    for (_, ri, ai) in scored {
302539×
        if used_r[ri] || used_a[ai] {
30266×
            continue;
302733×
        }
302833×
        used_r[ri] = true;
302933×
        used_a[ai] = true;
303033×
        out.push((removed[ri].0.clone(), added[ai].0.clone()));
3031
    }
303260×
    out
30331852×
}
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.
303788×
pub fn similarity(a: &[u8], b: &[u8]) -> u32 {
303888×
    if a == b {
303923×
        return 100;
304065×
    }
304165×
    if a.is_empty() || b.is_empty() {
30427×
        return 0;
304358×
    }
304458×
    let mut counts: HashMap<&[u8], usize> = HashMap::new();
3045114×
    for l in split_lines(a) {
3046114×
        *counts.entry(l).or_default() += 1;
3047114×
    }
304858×
    let mut shared = 0usize;
3049110×
    for l in split_lines(b) {
3050110×
        if let Some(n) = counts.get_mut(l) {
305142×
            if *n > 0 {
305242×
                *n -= 1;
305342×
                shared += l.len();
305442×
            }
305568×
        }
3056
    }
305758×
    (shared * 100 / a.len().max(b.len())) as u32
305888×
}
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
}