OXYGENHUB

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

2417 of 2646 lines run, 322 of 437 functions · run #383 on main · run missed

1
//! Working-copy snapshots, commits, and the change builder (spec §12.3).
2
3
use super::*;
4
use crate::objects::AtomRef;
5
6
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
7
pub enum ChangeStatus {
8
    Added,
9
    Modified,
10
    Removed,
11
    /// Moved from another path (detected by similarity, tracked as a placement change).
12
    Renamed,
13
    ModeChanged,
14
    /// The file is conflicted in the base state and still contains conflict markers.
15
    ConflictEdited,
16
    /// The file was conflicted in the base state and the working copy resolves it.
17
    Resolved,
18
}
19
20
/// Lines that mark a conflict region in a materialized file (spec §9.5).
211×
pub fn has_conflict_markers(content: &[u8]) -> bool {
222×
    split_lines(content).iter().any(|l| {
232×
        l.starts_with(b"<<<<<<< oxy conflict")
241×
            || l.starts_with(b"======= oxy conflict")
251×
            || l.starts_with(b">>>>>>> oxy conflict")
262×
    })
271×
}
28
29
/// Whether `content` still holds a conflict marker oxy wrote for this file
30
/// (oxygen#126): a marker-like line of the materialized conflicted file
31
/// that is not one of its unconflicted lines (`plain`). Text that merely
32
/// looks like a marker, as oxy's own documentation or a test fixture has,
33
/// is in the unconflicted lines, so it is not taken for one.
3436×
pub fn has_own_conflict_markers(content: &[u8], materialized: &[u8], plain: &[&[u8]]) -> bool {
35470×
    let line = |l: &[u8]| -> Vec<u8> {
36470×
        let l = l.strip_suffix(b"\n").unwrap_or(l);
37470×
        l.strip_suffix(b"\r").unwrap_or(l).to_vec()
38470×
    };
39263×
    let marker = |l: &[u8]| {
40263×
        l.starts_with(b"<<<<<<< oxy conflict")
41223×
            || l.starts_with(b"======= oxy conflict")
42183×
            || l.starts_with(b">>>>>>> oxy conflict")
43263×
    };
4481×
    let unconflicted: HashSet<Vec<u8>> = plain.iter().map(|l| line(l)).collect();
4536×
    let own: HashSet<Vec<u8>> = split_lines(materialized)
4636×
        .into_iter()
4736×
        .map(line)
48263×
        .filter(|l| marker(l) && !unconflicted.contains(l))
4936×
        .collect();
5036×
    !own.is_empty()
5136×
        && split_lines(content)
5236×
            .into_iter()
53126×
            .any(|l| own.contains(&line(l)))
5436×
}
55
56
#[derive(Clone, Debug, PartialEq, Eq)]
57
pub struct PathStatus {
58
    pub path: String,
59
    pub status: ChangeStatus,
60
}
61
62
/// Operations of a change built from the working directory against a base.
63
pub(crate) struct BuiltChange {
64
    pub tree_ops: Vec<TreeOp>,
65
    pub edits: Vec<Edit>,
66
    pub contributors: Vec<ChangeHash>,
67
    pub resolves: bool,
68
    pub statuses: Vec<PathStatus>,
69
    /// The stored blob of every opaque path, for the manifest's stat cache.
70
    pub blobs: HashMap<String, ObjectRef>,
71
}
72
73
/// Result of snapshotting the working copy.
74
pub struct SnapshotResult {
75
    /// The working-copy change's hash; for a commit's own snapshot, which
76
    /// does not encode it, the hash it had before.
77
    pub wc_hash: ChangeHash,
78
    pub wc: Change,
79
    /// The base state (closure of the working-copy change's dependencies).
80
    pub base: State,
81
    pub base_snapshot: Snapshot,
82
    pub statuses: Vec<PathStatus>,
83
    /// Whether the snapshot rewrote the working-copy change.
84
    pub changed: bool,
85
    /// Whether the working copy resolves conflicts of its base (spec §9.6).
86
    pub resolves: bool,
87
    /// Changes that contributed to the conflicts being resolved.
88
    pub contributors: Vec<ChangeHash>,
89
    /// The `.oxyattributes` in force on disk, from the files the walk read.
90
    pub(crate) attributes: crate::attributes::Attributes,
91
    /// Folders holding a repository of their own (`.git` or `.oxy`) that
92
    /// are not subrepos, so nothing in them is tracked (oxygen#43).
93
    pub untracked_nested: Vec<String>,
94
    /// A commit's snapshot leaves the manifest to the commit, which writes
95
    /// it once with the new base's graph keys.
96
    pub(crate) manifest: Option<PendingManifest>,
97
}
98
99
/// The manifest a commit's snapshot would have written, as of the moment
100
/// it would have written it (that moment is the racy-window stamp).
101
pub(crate) struct PendingManifest {
102
    entries: BTreeMap<String, FsEntry>,
103
    blobs: HashMap<String, ObjectRef>,
104
    dirs: Option<super::WalkedDirs>,
105
    written: u128,
106
}
107
108
/// Whether `base` has two or more live versions of the opaque file or
109
/// subrepo pin at `path` (a replace conflict, spec §9.3).
1108×
fn has_replace_conflict(base: &Snapshot, path: &str) -> bool {
1118×
    matches!(base.files.get(path).map(|f| &f.content), Some(FileContent::Opaque { blobs }) if blobs.len() > 1)
1128×
}
113
11423516×
pub fn is_binary(content: &[u8]) -> bool {
11523516×
    content[..content.len().min(BINARY_SNIFF)].contains(&0)
11623516×
}
117
118
impl Repo {
119
    /// Diff the files on disk against `base` and build the operations of a
120
    /// change from `base` to the working directory. `reuse` maps paths to the
121
    /// NodeIds an earlier version of the same change assigned to new paths.
1223×
    pub(crate) fn build_against(
1233×
        &self,
1243×
        base: &State,
1253×
        base_snapshot: &Snapshot,
1263×
        reuse: HashMap<String, (NodeId, NodeKind)>,
1273×
    ) -> Result<BuiltChange> {
1283×
        let mut fs_entries =
1293×
            self.walk_working_copy_with(None, &Self::tracked_kinds(base_snapshot), None)?;
1303×
        self.platform_normalize(&mut fs_entries, base_snapshot);
1313×
        self.build_from_entries(base, base_snapshot, reuse, &fs_entries)
1323×
    }
133
134
    /// Read the working copy as the platform left it (spec §7.7): without
135
    /// executable bits a file keeps the bit it has in the base, and without
136
    /// symbolic links a plain file where the base has a symlink is that
137
    /// symlink, written out as its target, not a new file.
1381473×
    fn platform_normalize(&self, entries: &mut BTreeMap<String, FsEntry>, base: &Snapshot) {
1391473×
        let p = self.platform;
1401473×
        if p.exec_bits && p.symlinks {
1411471×
            return;
1422×
        }
1434×
        for (path, e) in entries.iter_mut() {
1444×
            let Some(f) = base.files.get(path) else {
1450×
                continue;
146
            };
1474×
            if !p.symlinks && f.kind == NodeKind::Symlink && e.kind == NodeKind::File {
1482×
                e.kind = NodeKind::Symlink;
1492×
                e.exec = false;
1502×
            }
1514×
            if !p.exec_bits && f.kind == NodeKind::File && e.kind == NodeKind::File {
1522×
                e.exec = f.mode.exec;
1532×
            }
154
        }
1551473×
    }
156
157
    /// Like `build_against`, for files given in memory (imports).
1581192×
    pub(crate) fn build_from_entries(
1591192×
        &self,
1601192×
        base: &State,
1611192×
        base_snapshot: &Snapshot,
1621192×
        reuse: HashMap<String, (NodeId, NodeKind)>,
1631192×
        fs_entries: &BTreeMap<String, FsEntry>,
1641192×
    ) -> Result<BuiltChange> {
1651192×
        self.build_from_entries_resolving(base, base_snapshot, reuse, fs_entries, &HashSet::new())
1661192×
    }
167
168
    /// Like `build_from_entries`, settling the replace conflicts of the
169
    /// opaque files in `resolve` to their content (spec §9.3, §9.6): a
170
    /// caller that knows the user chose it, such as the hub's resolver. A
171
    /// snapshot never settles one on its own, since a checkout writes one
172
    /// candidate at the path.
1731210×
    pub(crate) fn build_from_entries_resolving(
1741210×
        &self,
1751210×
        base: &State,
1761210×
        base_snapshot: &Snapshot,
1771210×
        reuse: HashMap<String, (NodeId, NodeKind)>,
1781210×
        fs_entries: &BTreeMap<String, FsEntry>,
1791210×
        resolve: &HashSet<String>,
1801210×
    ) -> Result<BuiltChange> {
1811210×
        self.build_from_entries_with(
1821210×
            base,
1831210×
            base_snapshot,
1841210×
            reuse,
1851210×
            fs_entries,
1861210×
            resolve,
1871210×
            Scope::default(),
188
        )
1891210×
    }
190
191
    /// `build_from_entries` whose new nodes take identifiers derived from
192
    /// `seed` and their paths instead of random ones, so the same input
193
    /// always builds the same change (a Git import, spec §23).
194
    ///
195
    /// With `dir_needed`, the snapshot and entries hold only the paths the
196
    /// import touches (and the directories a removal may leave empty); a
197
    /// directory stays while `dir_needed` says the new tree has something
198
    /// under it.
19988×
    pub(crate) fn build_from_entries_seeded(
20088×
        &self,
20188×
        base: &State,
20288×
        base_snapshot: &Snapshot,
20388×
        fs_entries: &BTreeMap<String, FsEntry>,
20488×
        seed: [u8; 32],
20588×
        dir_needed: Option<&dyn Fn(&str) -> bool>,
20688×
    ) -> Result<BuiltChange> {
20788×
        self.build_from_entries_with(
20888×
            base,
20988×
            base_snapshot,
21088×
            HashMap::new(),
21188×
            fs_entries,
21288×
            &HashSet::new(),
21388×
            Scope {
21488×
                seed: Some(seed),
21588×
                dir_needed,
21688×
            },
217
        )
21888×
    }
219
220
    /// `build_from_entries` for a snapshot most of whose files are known
221
    /// unchanged (oxygen#41): only the paths that may differ are built
222
    /// (files read rather than known unchanged, base files gone from disk,
223
    /// and the directories those may leave empty), against a snapshot of
224
    /// just those, so a large tree with a few edits costs what they touch.
225991×
    fn build_changed_only(
226991×
        &self,
227991×
        base: &State,
228991×
        base_snapshot: &Snapshot,
229991×
        reuse: HashMap<String, (NodeId, NodeKind)>,
230991×
        fs_entries: &BTreeMap<String, FsEntry>,
231991×
    ) -> Result<BuiltChange> {
232991×
        let pick = crate::timing::phase("snapshot:   of which picking the changed");
233
        // A file known unchanged may still have changed mode: that alters
234
        // neither its size nor its time.
235991×
        let changed: BTreeMap<String, FsEntry> = join(fs_entries, &base_snapshot.files)
23611194×
            .filter_map(|(p, e, f)| {
23711194×
                let e = e?;
23811066×
                (!e.unchanged || f.is_none_or(|f| f.kind != e.kind || f.mode.exec != e.exec))
23911066×
                    .then(|| (p.clone(), e.clone()))
24011194×
            })
241991×
            .collect();
242991×
        let mut files: BTreeMap<String, crate::state::FileState> = BTreeMap::new();
2436837×
        for p in changed.keys() {
2446837×
            if let Some(f) = base_snapshot.files.get(p) {
2453765×
                files.insert(p.clone(), f.clone());
2463765×
            }
247
        }
248
        // Paths the base has and the disk does not.
249991×
        let gone = join(&base_snapshot.files, fs_entries)
25011194×
            .filter_map(|(p, f, e)| (e.is_none()).then_some((p, f?)));
251991×
        for (p, f) in gone {
252128×
            if f.kind == NodeKind::Dir {
253100×
                continue;
25428×
            }
25528×
            files.insert(p.clone(), f.clone());
25628×
            let mut end = p.len();
25733×
            while let Some(i) = p[..end].rfind('/') {
2585×
                let dir = &p[..i];
2595×
                if files.contains_key(dir) {
2600×
                    break;
2615×
                }
2625×
                if let Some(d) = base_snapshot.files.get(dir) {
2635×
                    files.insert(dir.to_string(), d.clone());
2645×
                }
2655×
                end = i;
266
            }
267
        }
268991×
        let part = Snapshot {
269991×
            tree: base_snapshot.tree.clone(),
270991×
            files,
271991×
            unrendered: BTreeSet::new(),
272991×
        };
273991×
        drop(pick);
274991×
        let _build = crate::timing::phase("snapshot:   of which building the change");
275
        // Whether anything on disk is under `dir`.
276991×
        let dir_needed = |dir: &str| {
2775×
            let prefix = format!("{dir}/");
2785×
            fs_entries
2795×
                .range(prefix.clone()..)
2805×
                .next()
2815×
                .is_some_and(|(k, _)| k.starts_with(&prefix))
2825×
        };
283991×
        self.build_from_entries_with(
284991×
            base,
285991×
            &part,
286991×
            reuse,
287991×
            &changed,
288991×
            &HashSet::new(),
289991×
            Scope {
290991×
                seed: None,
291991×
                dir_needed: Some(&dir_needed),
292991×
            },
293
        )
294991×
    }
295
2962289×
    fn build_from_entries_with(
2972289×
        &self,
2982289×
        base: &State,
2992289×
        base_snapshot: &Snapshot,
3002289×
        reuse: HashMap<String, (NodeId, NodeKind)>,
3012289×
        fs_entries: &BTreeMap<String, FsEntry>,
3022289×
        resolve: &HashSet<String>,
3032289×
        scope: Scope,
3042289×
    ) -> Result<BuiltChange> {
3052289×
        let Scope { seed, dir_needed } = scope;
3062289×
        let mut laps = crate::timing::Laps::start();
307
        // Attributes come from the files being committed, so a new
308
        // `.oxyattributes` applies to the same change that adds it.
3092289×
        let attrs = crate::attributes::Attributes::from_files(
3102289×
            fs_entries
3112289×
                .iter()
31219178×
                .filter(|(p, _)| p.as_str() == ".oxyattributes" || p.ends_with("/.oxyattributes"))
3132289×
                .map(|(p, e)| (p.as_str(), e.content.as_slice())),
314
        );
3152289×
        let mut b = ChangeBuilder::new(base, base_snapshot, reuse).with_attributes(attrs);
3162289×
        b.resolve = resolve.clone();
3172289×
        b.node_seed = seed;
3182289×
        laps.lap("build: builder");
319
        // Rename detection (spec §7.1, §23): a removed file and an added file
320
        // of the same kind whose contents are at least half alike become one
321
        // move of the same node, so identity survives across the rename.
3222289×
        let renames = detect_renames(base_snapshot, fs_entries, |p| self.in_scope(p));
3232289×
        let renamed_from: HashMap<&str, &str> = renames
3242289×
            .iter()
3252289×
            .map(|(old, new)| (new.as_str(), old.as_str()))
3262289×
            .collect();
3272289×
        let renamed_to: HashMap<&str, &str> = renames
3282289×
            .iter()
3292289×
            .map(|(old, new)| (old.as_str(), new.as_str()))
3302289×
            .collect();
3312289×
        laps.lap("build: renames");
3322289×
        b.diff_in_parallel(fs_entries);
3332289×
        laps.lap("build: diffs");
33419178×
        for (path, fs_entry) in fs_entries {
33519178×
            match base_snapshot.files.get(path) {
3366207×
                None => match renamed_from.get(path.as_str()) {
33735×
                    Some(old) => {
33835×
                        b.move_path(self, old, path, fs_entry, &base_snapshot.files[*old])?
339
                    }
3406172×
                    None => b.add_path(self, path, fs_entry)?,
341
                },
34212971×
                Some(expected) => b.update_path(self, path, fs_entry, expected)?,
343
            }
344
        }
3452289×
        laps.lap("build: paths");
346
        // A directory stays while anything under it exists or is out of
347
        // scope: the directories above each such path, gathered once.
3482289×
        let mut needed_dirs: HashSet<&str> = HashSet::new();
34919191×
        fn parents_of<'a>(p: &'a str, set: &mut HashSet<&'a str>) {
35019191×
            let mut end = p.len();
35119859×
            while let Some(i) = p[..end].rfind('/') {
35215450×
                if !set.insert(&p[..i]) {
35314782×
                    break;
354668×
                }
355668×
                end = i;
356
            }
35719191×
        }
35819178×
        for p in fs_entries.keys() {
35919178×
            parents_of(p, &mut needed_dirs);
36019178×
        }
36113528×
        for p in base_snapshot.files.keys() {
36213528×
            if !self.in_scope(p) {
36313×
                parents_of(p, &mut needed_dirs);
36413515×
            }
365
        }
36613528×
        for (path, expected) in &base_snapshot.files {
36713528×
            if fs_entries.contains_key(path)
368557×
                || !self.in_scope(path)
369544×
                || renamed_to.contains_key(path.as_str())
370
            {
37113019×
                continue;
372509×
            }
373509×
            let still_needed = expected.kind == NodeKind::Dir
374421×
                && match dir_needed {
37521×
                    Some(f) => f(path),
376400×
                    None => needed_dirs.contains(path.as_str()),
377
                };
378509×
            if !still_needed {
379113×
                b.remove_path(path, expected);
380396×
            }
381
        }
3822289×
        laps.lap("build: removals");
3832289×
        if seed.is_some() {
38488×
            b.retire_stray_placements();
3852201×
        }
3862289×
        b.retire_unified();
3872289×
        laps.lap("build: stray placements");
3882289×
        let mut statuses = b.statuses;
3895716×
        statuses.sort_by(|a, b| a.path.cmp(&b.path));
3902289×
        Ok(BuiltChange {
3912289×
            tree_ops: b.tree_ops,
3922289×
            edits: b.edits,
3932289×
            contributors: b.contributors.into_iter().collect(),
3942289×
            resolves: b.resolves,
3952289×
            statuses,
3962289×
            blobs: b.blobs,
3972289×
        })
3982289×
    }
399
400
    /// Store a change and, when `core.sign = change` and we are its author,
401
    /// sign it. A rewritten change by another author is stored unsigned: only
402
    /// its author (or a delegate) can vouch for it.
403787×
    pub(crate) fn store_signed(&self, change: &Change) -> Result<ChangeHash> {
404787×
        let ours = change.author == self.author();
405787×
        if self.config.sign_changes && ours && self.secret_key()?.is_none() {
4061×
            return fail("core.sign is \"change\" but no secret key is available for author.key");
407786×
        }
408786×
        let storing = crate::timing::phase("store: the change");
409786×
        let hash = self.store.put_change(change)?;
410786×
        drop(storing);
411786×
        if self.config.sign_changes && ours {
41243×
            let _t = crate::timing::phase("store: sign it");
41343×
            self.sign_change(&hash)?;
414743×
        }
415786×
        Ok(hash)
416787×
    }
417
4181477×
    fn resolutions_path(&self) -> PathBuf {
4191477×
        self.oxy
4201477×
            .join("workspaces")
4211477×
            .join(self.workspace.to_hex())
4221477×
            .join("resolve")
4231477×
    }
424
425
    /// The paths whose replace conflicts the user chose to settle with what
426
    /// the working copy holds there (`oxy resolve PATH`, spec §9.3).
4271473×
    pub fn resolutions(&self) -> Result<BTreeSet<String>> {
4281473×
        match fs::read_to_string(self.resolutions_path()) {
4295×
            Ok(text) => Ok(text
4305×
                .lines()
4315×
                .filter(|l| !l.is_empty())
4325×
                .map(String::from)
4335×
                .collect()),
4341468×
            Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(BTreeSet::new()),
4350×
            Err(e) => Err(e.into()),
436
        }
4371473×
    }
438
439
    /// Settle the replace conflicts at `paths` (a file's or a subrepo pin's,
440
    /// spec §9.3) with what the working copy holds there: the next snapshot
441
    /// replaces every live candidate with it. Refused for a path whose base
442
    /// has no replace conflict.
4433×
    pub fn choose_resolutions(&self, base: &Snapshot, paths: &[String]) -> Result<()> {
4443×
        for p in paths {
4453×
            if !has_replace_conflict(base, p) {
4461×
                return Err(RepoError::Msg(format!(
4471×
                    "{p} has no replace conflict to settle (a text file's conflict is settled by editing out its markers)"
4481×
                )));
4492×
            }
450
        }
4512×
        let mut all = self.resolutions()?;
4522×
        all.extend(paths.iter().cloned());
4532×
        let text: String = all.iter().map(|p| format!("{p}\n")).collect();
4542×
        crate::durable::write_atomic(&self.resolutions_path(), text.as_bytes())?;
4552×
        Ok(())
4563×
    }
457
458
    /// The chosen resolutions `base` still needs; the rest are forgotten.
4591470×
    fn resolutions_for(&self, base: &Snapshot) -> Result<HashSet<String>> {
4601470×
        let all = self.resolutions()?;
4611470×
        if all.is_empty() {
4621465×
            return Ok(HashSet::new());
4635×
        }
4645×
        let live: HashSet<String> = all
4655×
            .iter()
4665×
            .filter(|p| has_replace_conflict(base, p))
4675×
            .cloned()
4685×
            .collect();
4695×
        if live.is_empty() {
4702×
            match fs::remove_file(self.resolutions_path()) {
4712×
                Ok(()) => {}
4720×
                Err(e) if e.kind() == std::io::ErrorKind::NotFound => {}
4730×
                Err(e) => return Err(e.into()),
474
            }
4753×
        }
4765×
        Ok(live)
4771470×
    }
478
479
    /// Snapshot the working copy into the working-copy change (spec §12.3).
480
    /// The result carries the full base state and its whole rendering.
481477×
    pub fn snapshot(&self, command: &str) -> Result<SnapshotResult> {
482477×
        self.snapshot_as(command, false, false)
483477×
    }
484
485
    /// Snapshot the working copy as [`Repo::snapshot`] does, for commands
486
    /// that need its statuses, conflicts and base history, and the graphs
487
    /// of the files it changes: status, log, show, commit, diff, hunks and
488
    /// discard. Text files known unchanged since the last manifest are
489
    /// neither read nor rendered: the result's `base` is a history-only
490
    /// state without their graphs, and its `base_snapshot` lists them in
491
    /// `unrendered` with empty bytes. They are never conflicted, and no
492
    /// change the working copy makes touches them.
493465×
    pub fn snapshot_status(&self, command: &str) -> Result<SnapshotResult> {
494465×
        self.snapshot_as(command, true, false)
495465×
    }
496
497
    /// `snapshot_as`; `for_commit` writes the manifest even where a status
498
    /// would not bother (an edited file is read next time whatever it
499
    /// says), since after the commit that file is unchanged, and records no
500
    /// operation: the commit's own, recorded straight after, replaces the
501
    /// working copy, so the snapshot's would cost a durable write for
502
    /// nothing. Should the commit fail, the files are still on disk and the
503
    /// next snapshot finds them.
5041473×
    fn snapshot_as(
5051473×
        &self,
5061473×
        command: &str,
5071473×
        partial: bool,
5081473×
        for_commit: bool,
5091473×
    ) -> Result<SnapshotResult> {
5101473×
        let _lock = self.lock_snapshot()?;
5111473×
        let batch = self.store.begin_batch()?;
5121473×
        let result = self.snapshot_locked(command, partial, for_commit);
5131473×
        batch.finish()?;
5141473×
        result
5151473×
    }
516
5171473×
    fn snapshot_locked(
5181473×
        &self,
5191473×
        command: &str,
5201473×
        partial: bool,
5211473×
        for_commit: bool,
5221473×
    ) -> Result<SnapshotResult> {
5231473×
        let _all = crate::timing::phase("snapshot");
5241473×
        let (op_ref, op) = self.head_op()?;
5251473×
        let (old_hash, old_wc) = self.working_copy()?;
526
        // The base's history first: its graph keys say which files the
527
        // manifest already knows equal to it.
5281471×
        let mut base = {
5291471×
            let _t = crate::timing::phase("snapshot: load base history");
5301471×
            self.load_state_indexed(&old_wc.deps)?
531
        };
5321471×
        let view = {
5331471×
            let _t = crate::timing::phase("snapshot: tree view");
5341471×
            self.tree_view(&mut base)?
535
        };
5361471×
        let manifest = {
5371471×
            let _t = crate::timing::phase("snapshot: read manifest");
5381471×
            self.read_manifest()?.map(|(_, _, m)| m)
539
        };
5401471×
        let tracked: BTreeMap<String, (NodeKind, Option<ObjectRef>)> = {
5411471×
            let _t = crate::timing::phase("snapshot: tracked paths");
542
            // In the view's path order, so the map is built without searching.
5431471×
            view.entries
5441471×
                .iter()
5459668×
                .filter(|(_, e)| e.kind != NodeKind::Dir)
5469273×
                .map(|(p, e)| {
5479273×
                    let blob = if e.kind != NodeKind::File || e.mode.opaque {
548180×
                        base.live_blobs(&e.node).first().copied()
549
                    } else {
5509093×
                        None
551
                    };
5529273×
                    (p.clone(), (e.kind, blob))
5539273×
                })
5541471×
                .collect()
555
        };
556
        // A text file's graph key, worked out when the walk asks for it.
55712361×
        let key_of = |p: &str| -> Option<[u8; 32]> {
55812361×
            let e = view.entries.get(p)?;
5599165×
            if e.kind != NodeKind::File || e.mode.opaque {
560139×
                return None;
5619026×
            }
5629026×
            base.graph_key(&e.node)
56312361×
        };
5641470×
        let mut fs_entries = {
5651471×
            let _t = crate::timing::phase("snapshot: read working copy");
5661471×
            self.walk_working_copy_with(manifest.as_deref(), &tracked, Some(&key_of))?
567
        };
568
        // The keys of the files read, before building graphs drops them: a
569
        // file found equal to its base rendering keeps its key.
5701470×
        let keys: HashMap<String, [u8; 32]> = fs_entries
5711470×
            .iter()
57212408×
            .filter(|(_, e)| !e.unchanged && e.kind == NodeKind::File)
5738120×
            .filter_map(|(p, _)| Some((p.clone(), key_of(p)?)))
5741470×
            .collect();
5751470×
        let base_snapshot = {
5761470×
            let _t = crate::timing::phase("snapshot: load and render base");
5771470×
            if partial {
578996×
                let sets = crate::timing::phase("snapshot:   of which choosing graphs");
579
                // Every file but those on disk known unchanged.
580996×
                let need: Vec<(&str, NodeId)> = join(&view.entries, &fs_entries)
58111216×
                    .filter_map(|(p, v, f)| {
58211216×
                        let v = v?;
5838142×
                        (v.kind == NodeKind::File && !f.is_some_and(|f| f.unchanged))
5848142×
                            .then_some((p.as_str(), v.node))
58511216×
                    })
586996×
                    .collect();
587996×
                let render: std::collections::HashSet<&str> =
588996×
                    need.iter().map(|(p, _)| *p).collect();
589996×
                let need: Vec<NodeId> = need.iter().map(|(_, n)| *n).collect();
590996×
                drop(sets);
591
                {
592996×
                    let _t = crate::timing::phase("snapshot:   of which building graphs");
593996×
                    self.load_graphs_of(&mut base, &need)?;
594
                }
595996×
                let _t = crate::timing::phase("snapshot:   of which rendering");
596996×
                base.materialize_only(&render)
597
            } else {
598474×
                self.load_all_graphs(&mut base)?;
599474×
                base.materialize()
600
            }
601
        };
602
603
        // Reuse the NodeIds the previous working-copy version assigned to new
604
        // paths, so an unchanged working copy hashes identically (spec §12.3).
6051470×
        let reuse = added_node_paths(&old_wc, &base_snapshot);
6061470×
        self.platform_normalize(&mut fs_entries, &base_snapshot);
607
        // Replace conflicts the user settled with `oxy resolve PATH`
608
        // (oxygen#140): those still in the base; a choice the base no longer
609
        // needs (once committed) is forgotten.
6101470×
        let resolve = self.resolutions_for(&base_snapshot)?;
6111470×
        let built = {
6121470×
            let _t = crate::timing::phase("snapshot: diff against base");
6131470×
            if !resolve.is_empty() {
6143×
                self.build_from_entries_resolving(
6153×
                    &base,
6163×
                    &base_snapshot,
6173×
                    reuse,
6183×
                    &fs_entries,
6193×
                    &resolve,
6200×
                )?
6211467×
            } else if partial && self.config.sparse_paths.is_empty() {
622
                #[cfg(test)]
623709×
                let full =
624709×
                    self.build_from_entries(&base, &base_snapshot, reuse.clone(), &fs_entries)?;
625991×
                let built = self.build_changed_only(&base, &base_snapshot, reuse, &fs_entries)?;
626
                #[cfg(test)]
627
                {
628
                    // New nodes take random identifiers: compare them by
629
                    // order of appearance.
6301418×
                    let norm = |b: &BuiltChange| {
6311418×
                        let text = format!("{:?} {:?} {:?}", b.tree_ops, b.edits, b.statuses);
6321418×
                        let mut seen: Vec<String> = Vec::new();
6331418×
                        let mut out = String::new();
6341418×
                        let mut rest = text.as_str();
63520624×
                        while let Some(i) = rest.find("NodeId(") {
63619206×
                            out.push_str(&rest[..i]);
63719206×
                            let end = i + rest[i..].find(')').unwrap() + 1;
63819206×
                            let id = rest[i..end].to_string();
6399046458×
                            let n = seen.iter().position(|x| *x == id).unwrap_or_else(|| {
6407346×
                                seen.push(id);
6417346×
                                seen.len() - 1
6427346×
                            });
64319206×
                            out.push_str(&format!("N{n}"));
64419206×
                            rest = &rest[end..];
645
                        }
6461418×
                        out.push_str(rest);
6471418×
                        out
6481418×
                    };
649709×
                    assert_eq!(
650709×
                        norm(&built),
651709×
                        norm(&full),
652
                        "a changed-only build is the full one"
653
                    );
654
                }
655991×
                built
656
            } else {
657476×
                self.build_from_entries(&base, &base_snapshot, reuse, &fs_entries)?
658
            }
659
        };
660
        // Text files found equal to an unconflicted base rendering keep its
661
        // graph key, so the next snapshot need not read or render them.
662
        {
6633885×
            let changed: HashSet<&str> = built.statuses.iter().map(|s| s.path.as_str()).collect();
66412408×
            for (p, e) in fs_entries.iter_mut() {
66512408×
                if e.unchanged || e.kind != NodeKind::File || changed.contains(p.as_str()) {
6668078×
                    continue;
6674330×
                }
6684330×
                e.graph_key = match base_snapshot.files.get(p).map(|f| &f.content) {
669
                    Some(FileContent::Text {
6704210×
                        bytes,
6714210×
                        materialized,
6724210×
                    }) if !materialized.is_conflicted() && *bytes == *e.content => {
6734204×
                        keys.get(p).copied()
674
                    }
675126×
                    _ => None,
676
                };
677
            }
678
        }
679
6801470×
        let mut wc = Change {
6811470×
            version: crate::objects::CHANGE_VERSION,
6821470×
            change_id: old_wc.change_id,
6831470×
            deps: vec![],
6841470×
            author: self.author(),
6851470×
            hlc: old_wc.hlc,
6861470×
            message: old_wc.message.clone(),
6871470×
            tree_ops: built.tree_ops,
6881470×
            edits: built.edits,
6891470×
            kind: ChangeKind::WorkingCopy,
6901470×
        };
6911470×
        let base_heads = base.maximal(&old_wc.deps);
6921470×
        let mut deps: BTreeSet<ChangeHash> = base_heads.into_iter().collect();
6931470×
        deps.extend(referenced_changes(&wc, &base));
6941470×
        deps.extend(built.contributors.iter().copied());
6951470×
        wc.deps = deps.into_iter().collect();
6961470×
        wc.normalize();
6971470×
        let resolves = built.resolves;
6981470×
        let contributors = built.contributors;
6991470×
        let statuses = built.statuses;
700
        // Empty snapshot: hash the candidate before storing; only record an op on change.
7011470×
        let record = crate::timing::phase("snapshot: hash and record");
702
        // Encoded once, its texts stored a batch at a time as they are
703
        // made (a stored blob is not stored again); the change itself only
704
        // when it changed.
705
        // For a commit the change is neither encoded, stored nor recorded:
706
        // the commit stores its own, built from this one's operations, and
707
        // its texts with it. The hash it would have is not needed.
7081470×
        let (new_hash, changed, encoded) = if for_commit {
709531×
            (old_hash, true, Vec::new())
710
        } else {
711939×
            let encoded = wc.encode_streaming(|batch| self.store.put_texts(&batch))?;
712939×
            let new_hash = crate::hash::hash_object(crate::hash::ObjectType::Change, &encoded);
713939×
            (new_hash, new_hash != old_hash, encoded)
714
        };
7151470×
        if changed && !for_commit {
716309×
            self.store.put(crate::hash::ObjectType::Change, &encoded)?;
717309×
            let mut view = op.view.clone();
718309×
            view.workspaces.insert(self.workspace, new_hash);
719309×
            self.record_op(&[op_ref], &format!("{command}{SNAPSHOT_SUFFIX}"), view)?;
7201161×
        }
7211470×
        drop(record);
722
        // The prompt compares against this without recording anything.
7231470×
        let _t = crate::timing::phase("snapshot: write manifest");
7241470×
        let conflicted = base_snapshot.is_conflicted();
7251470×
        let uncommitted = !wc.tree_ops.is_empty() || !wc.edits.is_empty();
726
        // Rewriting the manifest pays only when it would teach the next
727
        // snapshot something: other flags, a file found equal to the base
728
        // (it need not be read again), a new blob, a path added or gone.
729
        // An edited file is read next time whatever it says.
7301470×
        let worth = match self.read_manifest()? {
731531×
            _ if for_commit => true,
732360×
            None => true,
733579×
            Some((c, u, m)) => {
734579×
                c != conflicted
735579×
                    || u != uncommitted
736335×
                    || m.entries.len() != fs_entries.len()
737418×
                    || fs_entries.iter().any(|(p, e)| {
738418×
                        !e.unchanged && (e.graph_key.is_some() || !m.entries.contains_key(p))
739418×
                    })
74055×
                    || built
74155×
                        .blobs
74255×
                        .iter()
74355×
                        .any(|(p, b)| m.entries.get(p).and_then(|e| e.blob) != Some(*b))
744
                    // With uncommitted work, the status cache below holds
745
                    // only while the manifest describes the edited files as
746
                    // they are now.
74773×
                    || (uncommitted && statuses.iter().any(|st| {
74873×
                        let Some(e) = fs_entries.get(&st.path) else {
7494×
                            return m.entries.contains_key(&st.path);
750
                        };
75169×
                        let Some(me) = m.entries.get(&st.path) else {
7520×
                            return true;
753
                        };
75469×
                        let hash = e
75569×
                            .content_hash
75669×
                            .unwrap_or_else(|| *blake3::hash(&e.content).as_bytes());
75769×
                        let stat = e.stat.or_else(|| {
7580×
                            fs::symlink_metadata(self.root.join(&st.path))
7590×
                                .ok()
7600×
                                .map(|md| (md.len(), super::prompt::mtime_ns(&md)))
7610×
                        });
762
                        // The executable bit too: a mode change moves
763
                        // neither size nor time.
76469×
                        me.hash != hash || me.exec != e.exec || stat != Some((me.size, me.mtime_ns))
76573×
                    }))
766
            }
767
        };
7681470×
        let attributes = crate::attributes::Attributes::from_files(
7691470×
            fs_entries
7701470×
                .iter()
77112408×
                .filter(|(p, _)| is_attributes(p))
7721470×
                .map(|(p, e)| (p.as_str(), e.content.as_slice())),
773
        );
7741470×
        let mut manifest = None;
7751470×
        if for_commit {
776531×
            manifest = Some(PendingManifest {
777531×
                entries: fs_entries,
778531×
                blobs: built.blobs.clone(),
779531×
                dirs: self.walked_dirs.take(),
780531×
                written: super::prompt::now_ns(),
781531×
            });
782531×
        } else {
783939×
            if worth {
784887×
                self.write_manifest_entries(conflicted, uncommitted, &fs_entries, &built.blobs)?;
78552×
            }
786939×
            self.write_status_cache((uncommitted && !conflicted).then_some(&new_hash), &statuses);
787
        }
7881470×
        Ok(SnapshotResult {
7891470×
            wc_hash: new_hash,
7901470×
            wc,
7911470×
            base,
7921470×
            base_snapshot,
7931470×
            statuses,
7941470×
            changed,
7951470×
            resolves,
7961470×
            contributors,
7971470×
            attributes,
7981470×
            untracked_nested: self.untracked_nested.borrow().clone(),
7991470×
            manifest,
8001470×
        })
8011473×
    }
802
803
    /// `oxy status --json` (spec §9.5): the changed paths and every conflict
804
    /// of the working copy's base with its kind, path, and contributing
805
    /// ChangeIds.
8068×
    pub fn status_json(&self, snap: &SnapshotResult) -> Result<String> {
8078×
        let heads = self.bookmark_heads()?;
8088×
        let base_snapshot = &snap.base_snapshot;
8098×
        let by_node = base_snapshot.tree.by_node();
8108×
        let path_of = |n: &NodeId| by_node.get(n).map(|e| e.path.clone());
8118×
        let id_of = |h: &ChangeHash| {
8124×
            snap.base
8134×
                .get(h)
8144×
                .map(|m| m.change_id.to_hex())
8154×
                .unwrap_or_else(|| h.to_hex())
8164×
        };
8178×
        let paths = json_array(snap.statuses.iter().map(|s| {
8184×
            format!(
819
                "{{\"path\":{},\"status\":{}}}",
8204×
                json_str(&s.path),
8214×
                json_str(&format!("{:?}", s.status))
822
            )
8234×
        }));
8248×
        let mut conflicts: Vec<String> = Vec::new();
8259×
        for (p, f) in &base_snapshot.files {
8269×
            if !f.is_conflicted() {
8277×
                continue;
8282×
            }
8292×
            let (kind, changes) = match &f.content {
830
                FileContent::Text { .. } => {
8312×
                    ("text", snap.base.conflict_regions(&f.node).contributors)
832
                }
8330×
                FileContent::Opaque { blobs } => {
8340×
                    ("replace", snap.base.blob_contributors(&f.node, blobs))
835
                }
8360×
                FileContent::Dir => continue,
837
            };
8382×
            let resolved = match snap
8392×
                .statuses
8402×
                .iter()
8412×
                .find(|s| s.path == *p)
8422×
                .map(|s| s.status)
843
            {
8441×
                Some(ChangeStatus::Resolved) => "true",
8450×
                Some(ChangeStatus::ConflictEdited) => "\"markers\"",
8461×
                _ => "false",
847
            };
8482×
            conflicts.push(format!(
849
                "{{\"kind\":{},\"path\":{},\"node\":{},\"changes\":{},\"resolved\":{resolved}}}",
8502×
                json_str(kind),
8512×
                json_str(p),
8522×
                json_str(&f.node.to_hex()),
8534×
                json_array(changes.iter().map(|h| json_str(&id_of(h))))
854
            ));
855
        }
8568×
        for c in &base_snapshot.tree.conflicts {
8570×
            let (kind, nodes): (&str, Vec<NodeId>) = match c {
8580×
                crate::tree::TreeConflict::Name { nodes, .. } => ("name", nodes.clone()),
8590×
                crate::tree::TreeConflict::MultiPlacement { node, .. } => {
8600×
                    ("multi-placement", vec![*node])
861
                }
8620×
                crate::tree::TreeConflict::Orphan { node, .. } => ("orphan", vec![*node]),
8630×
                crate::tree::TreeConflict::Cycle { node } => ("cycle", vec![*node]),
8640×
                crate::tree::TreeConflict::Mode { node, .. } => ("mode", vec![*node]),
865
            };
8660×
            let detail = match c {
8670×
                crate::tree::TreeConflict::Name { name, parent, .. } => {
8680×
                    let dir = if *parent == NodeId::ROOT {
8690×
                        String::new()
870
                    } else {
8710×
                        path_of(parent).unwrap_or_default()
872
                    };
8730×
                    format!(
874
                        ",\"path\":{}",
8750×
                        json_str(&if dir.is_empty() {
8760×
                            name.clone()
877
                        } else {
8780×
                            format!("{dir}/{name}")
879
                        })
880
                    )
881
                }
8820×
                _ => nodes
8830×
                    .first()
8840×
                    .and_then(path_of)
8850×
                    .map(|p| format!(",\"path\":{}", json_str(&p)))
8860×
                    .unwrap_or_default(),
887
            };
8880×
            conflicts.push(format!(
889
                "{{\"kind\":{},\"nodes\":{}{detail}}}",
8900×
                json_str(kind),
8910×
                json_array(nodes.iter().map(|n| json_str(&n.to_hex())))
892
            ));
893
        }
8948×
        Ok(format!(
895
            "{{\"bookmark\":{},\"working_copy\":{},\"heads\":{},\"clean\":{},\"conflicted\":{},\"paths\":{paths},\"conflicts\":{},\"untracked_nested\":{},\"skipped_large\":{}}}",
8968×
            json_str(&self.config.bookmark),
8978×
            json_str(&snap.wc.change_id.to_hex()),
8988×
            heads.len(),
8998×
            snap.statuses.is_empty(),
9008×
            base_snapshot.is_conflicted(),
9018×
            json_array(conflicts),
9028×
            json_array(snap.untracked_nested.iter().map(|p| json_str(p))),
9038×
            json_array(
9048×
                self.skipped_large
9058×
                    .borrow()
9068×
                    .iter()
9078×
                    .map(|(p, n)| format!("{{\"path\":{},\"size\":{n}}}", json_str(p)))
908
            )
909
        ))
9108×
    }
911
912
    /// Turn the working-copy change into a normal change on the bookmark (spec §12.3).
913722×
    pub fn commit(&self, message: &str, extra_deps: &[ChangeHash]) -> Result<ChangeHash> {
914722×
        self.commit_selection(message, extra_deps, &Selection::All)
915722×
    }
916
917
    /// The hunks of the working copy, for `oxy commit --interactive`: each
918
    /// tree operation and each edit, in the order `select_hunks` numbers them.
9198×
    pub fn hunks(&self) -> Result<(SnapshotResult, Vec<Hunk>)> {
9208×
        let snap = self.snapshot_status("oxy commit")?;
9218×
        let hunks = render_hunks(&snap.wc, &snap.base, &snap.base_snapshot);
9228×
        Ok((snap, hunks))
9238×
    }
924
925
    /// Commit part of the working copy (spec §12.3). What is not selected
926
    /// stays on disk as uncommitted work: the next snapshot rebuilds it
927
    /// against the new base, so the working copy always describes the
928
    /// directory.
929
    /// The graph key in `st` of each text file at `paths`, the paths a
930
    /// commit changed: only their graphs changed, so the keys the manifest
931
    /// holds for the others still stand (and any that does not is simply
932
    /// not trusted by the next snapshot, which compares keys). Files with
933
    /// an `eol` attribute are left out: their bytes on disk are not the
934
    /// rendering.
935740×
    fn committed_graph_keys(
936740×
        &self,
937740×
        st: &State,
938740×
        paths: &[String],
939740×
        attrs: &crate::attributes::Attributes,
940740×
    ) -> HashMap<String, [u8; 32]> {
941740×
        let _t = crate::timing::phase("commit: graph keys");
942740×
        let view = st.view();
943740×
        paths
944740×
            .iter()
9453595×
            .filter_map(|p| {
9463595×
                let e = view.entries.get(p)?;
9473553×
                (e.kind == NodeKind::File && !e.mode.opaque && attrs.lookup(p).eol.is_none())
9483553×
                    .then_some(())?;
9493483×
                Some((p.clone(), st.graph_key(&e.node)?))
9503595×
            })
951740×
            .collect()
952740×
    }
953
954729×
    pub fn commit_selection(
955729×
        &self,
956729×
        message: &str,
957729×
        extra_deps: &[ChangeHash],
958729×
        selection: &Selection,
959729×
    ) -> Result<ChangeHash> {
960729×
        Ok(self
961729×
            .commit_selection_partial(message, extra_deps, selection)?
962
            .0)
963729×
    }
964
965
    /// As [`Repo::commit_selection`], and whether the commit left part of
966
    /// the working copy uncommitted: when it did not, nothing is left, and
967
    /// no snapshot is needed to say so.
968758×
    pub fn commit_selection_partial(
969758×
        &self,
970758×
        message: &str,
971758×
        extra_deps: &[ChangeHash],
972758×
        selection: &Selection,
973758×
    ) -> Result<(ChangeHash, bool)> {
974
        // The commit's objects are written together, made durable at once
975
        // before the operation that names them (spec §13.6).
976758×
        let batch = self.store.begin_batch()?;
977758×
        let out = self.commit_selection_batched(message, extra_deps, selection);
978758×
        batch.finish()?;
979758×
        out
980758×
    }
981
982
    /// Write the manifest a commit's snapshot left to the commit, with the
983
    /// graph keys `keys` sets.
984519×
    fn write_pending_manifest(
985519×
        &self,
986519×
        mut m: PendingManifest,
987519×
        conflicted: bool,
988519×
        keys: HashMap<String, [u8; 32]>,
989519×
    ) -> Result<()> {
9902885×
        for (path, k) in keys {
9912885×
            if let Some(e) = m.entries.get_mut(&path) {
9922885×
                e.graph_key = Some(k);
9932885×
            }
994
        }
995519×
        self.write_manifest_entries_as_of(
996519×
            conflicted,
997
            false,
998519×
            &m.entries,
999519×
            &m.blobs,
1000519×
            m.written,
1001519×
            m.dirs.unwrap_or_default(),
1002
        )
1003519×
    }
1004
1005758×
    fn commit_selection_batched(
1006758×
        &self,
1007758×
        message: &str,
1008758×
        extra_deps: &[ChangeHash],
1009758×
        selection: &Selection,
1010758×
    ) -> Result<(ChangeHash, bool)> {
1011758×
        let _wc = self.lock_working_copy()?;
1012758×
        let mut snap = match self.snapshot_from_cache()? {
1013227×
            Some(snap) => snap,
1014531×
            None => self.snapshot_as("oxy commit", true, true)?,
1015
        };
1016758×
        let pending = snap.manifest.take();
1017758×
        if snap.wc.tree_ops.is_empty() && snap.wc.edits.is_empty() {
10184×
            if let Some(m) = pending {
10194×
                let conflicted = snap.base_snapshot.is_conflicted();
10204×
                self.write_pending_manifest(m, conflicted, HashMap::new())?;
10210×
            }
10224×
            return fail("nothing to commit: the working copy matches its base");
1023754×
        }
1024754×
        if let Some(s) = snap
1025754×
            .statuses
1026754×
            .iter()
10273624×
            .find(|s| s.status == ChangeStatus::ConflictEdited)
1028
        {
10291×
            return fail(format!("{} still contains conflict markers", s.path));
1030753×
        }
1031753×
        if message.trim().is_empty() {
10320×
            return fail("a commit message is required");
1033753×
        }
1034
        // What the whole working copy references, before a whole commit
1035
        // takes its operations over (they are moved, not copied: for a
1036
        // large tree they are most of the memory).
1037753×
        let wc_refs = referenced_changes(&snap.wc, &snap.base);
10383622×
        let changed_paths: Vec<String> = snap.statuses.iter().map(|s| s.path.clone()).collect();
1039753×
        let (tree_ops, edits, partial) = match selection {
1040740×
            Selection::All => (
1041740×
                std::mem::take(&mut snap.wc.tree_ops),
1042740×
                std::mem::take(&mut snap.wc.edits),
1043740×
                false,
1044740×
            ),
10458×
            Selection::Paths(paths) => {
10468×
                let (o, e) = select_paths(&snap.wc, &snap.base_snapshot, paths);
10478×
                let partial = o.len() != snap.wc.tree_ops.len() || e.len() != snap.wc.edits.len();
10488×
                (o, e, partial)
1049
            }
10505×
            Selection::Hunks(indices) => {
10515×
                let (o, e) = select_hunks(&snap.wc, indices, &snap.base_snapshot.tree.unified);
10525×
                let partial = o.len() != snap.wc.tree_ops.len() || e.len() != snap.wc.edits.len();
10535×
                (o, e, partial)
1054
            }
1055
        };
1056753×
        if tree_ops.is_empty() && edits.is_empty() {
10570×
            return fail("nothing selected to commit");
1058753×
        }
1059
        // A resolution may leave other work uncommitted (oxygen#118), but
1060
        // takes every file it resolves, whole.
1061753×
        if partial && snap.resolves {
10622×
            let resolved = snap
10632×
                .statuses
10642×
                .iter()
10654×
                .filter(|s| s.status == ChangeStatus::Resolved)
10662×
                .map(|s| s.path.as_str());
10672×
            let missing: Vec<&str> = match selection {
10682×
                Selection::Paths(paths) => resolved
10692×
                    .filter(|p| {
10702×
                        !paths.iter().any(|x| {
10712×
                            p == x || p.starts_with(&format!("{}/", x.trim_end_matches('/')))
10722×
                        })
10732×
                    })
10742×
                    .collect(),
10750×
                _ => resolved.collect(),
1076
            };
10772×
            if !missing.is_empty() {
10781×
                return fail(format!(
1079
                    "a conflict resolution takes every file it resolves, whole: commit by paths, including {}",
10801×
                    missing.join(", ")
1081
                ));
10821×
            }
1083751×
        }
1084
        // pre-commit hook: may veto.
1085752×
        self.run_hook(
1086752×
            "pre-commit",
1087752×
            &format!(
1088
                "{{\"event\":\"pre-commit\",\"message\":{},\"paths\":{}}}",
1089752×
                json_str(message),
10903620×
                json_array(snap.statuses.iter().map(|s| format!(
1091
                    "{{\"path\":{},\"status\":{}}}",
10923620×
                    json_str(&s.path),
10933620×
                    json_str(&format!("{:?}", s.status))
1094
                )))
1095
            ),
10961×
        )?;
1097751×
        let (op_ref, op) = self.head_op()?;
1098751×
        let mut deps: BTreeSet<ChangeHash> = wc_refs;
1099
        // semantic-deps hook: may add explicit dependencies (spec §8.1).
1100751×
        if self.config.semantic_deps {
11011×
            let touched: Vec<String> = snap.statuses.iter().map(|s| s.path.clone()).collect();
11021×
            let by_node = snap.base_snapshot.tree.by_node();
11031×
            let mut candidates: Vec<(ChangeId, ChangeHash, Vec<String>)> = Vec::new();
11041×
            let mut seen: BTreeSet<ChangeHash> = BTreeSet::new();
11052×
            for h in deps.iter().chain(snap.base.maximal(&snap.wc.deps).iter()) {
11062×
                if !seen.insert(*h) {
11070×
                    continue;
11082×
                }
11092×
                let c = self.store.get_change(h)?;
11102×
                let mut paths: BTreeSet<String> = BTreeSet::new();
11116×
                for n in c
11122×
                    .tree_ops
11132×
                    .iter()
11143×
                    .map(|o| o.node())
11153×
                    .chain(c.edits.iter().map(|e| e.node()))
1116
                {
11176×
                    if let Some(e) = by_node.get(&n) {
11186×
                        paths.insert(e.path.clone());
11196×
                    }
1120
                }
11212×
                candidates.push((c.change_id, *h, paths.into_iter().collect()));
1122
            }
11231×
            for d in self.semantic_deps(&snap.wc.change_id, &touched, &candidates)? {
11241×
                if snap.base.contains(&d) {
11251×
                    deps.insert(d);
11261×
                }
1127
            }
1128750×
        }
1129
        // A resolution depends on every change that contributed to the
1130
        // conflict (spec §8.1). Tree and opaque conflicts are resolved through
1131
        // ordinary operations whose references already cover the contributors.
1132751×
        deps.extend(snap.contributors.iter().copied());
1133751×
        for d in extra_deps {
11344×
            if !snap.base.contains(d) {
11350×
                return fail(format!(
1136
                    "--depends-on {d}: not in the working copy's base state"
1137
                ));
11384×
            }
11394×
            deps.insert(*d);
1140
        }
1141751×
        let mut change = Change {
1142
            version: crate::objects::CHANGE_VERSION,
1143751×
            change_id: if partial {
114410×
                ChangeId::random()
1145
            } else {
1146741×
                snap.wc.change_id
1147
            },
1148751×
            deps: vec![],
1149751×
            author: self.author(),
1150751×
            hlc: Hlc::now(),
1151751×
            message: message.trim_end().to_string(),
1152751×
            tree_ops,
1153751×
            edits,
1154751×
            kind: if snap.resolves {
115511×
                ChangeKind::Resolution
1156
            } else {
1157740×
                ChangeKind::Normal
1158
            },
1159
        };
1160751×
        if partial {
1161
            // Dependencies come from what the selected part references, not
1162
            // from the whole working copy.
116310×
            deps = referenced_changes(&change, &snap.base);
116410×
            for d in extra_deps {
11651×
                deps.insert(*d);
11661×
            }
1167741×
        }
1168751×
        change.deps = deps.into_iter().collect();
1169751×
        change.normalize();
1170751×
        let signing = crate::timing::phase("commit: sign and store");
1171751×
        let hash = self.store_signed(&change)?;
1172750×
        drop(signing);
1173750×
        let extending = crate::timing::phase("commit: extend the state");
1174
1175
        // New bookmark heads: maximal elements of old heads plus the new change.
1176
        // The working copy continues on its own base plus the new change, which
1177
        // is exactly what the files on disk contain; the bookmark may hold
1178
        // other heads (and conflicts) the working copy has not checked out.
1179750×
        let old_heads = self.heads_of(&op.view, &self.config.bookmark)?;
1180750×
        let old_base = snap.base.maximal(&snap.wc.deps);
1181750×
        let mut all: Vec<ChangeHash> = old_heads.clone();
1182750×
        all.extend(old_base.iter().copied());
1183750×
        all.push(hash);
1184
        // The snapshot already loaded the working copy's base; when that also
1185
        // holds every bookmark head, it is the state to extend.
1186750×
        let mut st = if old_heads.iter().all(|h| snap.base.contains(h)) {
1187708×
            snap.base
1188
        } else {
118942×
            self.load_state(&all)?
1190
        };
1191750×
        st.add_hashed(hash, change)?;
1192750×
        let mut with_new = old_heads.clone();
1193750×
        with_new.push(hash);
1194750×
        let new_heads = st.maximal(&with_new);
1195
        // Automatic checkpoint once enough changes accumulated (spec §11).
1196750×
        let since = self
1197750×
            .latest_checkpoint(&self.config.bookmark)?
1198750×
            .map(|(_, cp)| cp.count)
1199750×
            .unwrap_or(0);
1200750×
        if self.config.checkpoint_interval > 0
1201750×
            && (st.len() as u64).saturating_sub(since) >= self.config.checkpoint_interval
1202
        {
12032×
            let cp_state = self.load_state_full(&new_heads)?;
12042×
            self.write_checkpoint(&self.config.bookmark, &cp_state, &new_heads)?;
1205748×
        }
1206750×
        let mut wc_base = old_base.clone();
1207750×
        wc_base.push(hash);
1208750×
        let wc_base = st.maximal(&wc_base);
1209750×
        drop(extending);
1210
1211
        // The graph keys of the files as they now are, from the state the
1212
        // commit just extended: a file whose graph it built has none, and
1213
        // is read by the next snapshot; a key the next base does not share
1214
        // (the bookmark held other heads) is simply not trusted then.
1215750×
        let keying = crate::timing::phase("commit: graph keys of the files");
1216750×
        let committed_keys =
1217750×
            (!partial).then(|| self.committed_graph_keys(&st, &changed_paths, &snap.attributes));
1218750×
        drop(keying);
1219750×
        let recording = crate::timing::phase("commit: record");
1220750×
        let wc = self.new_working_copy(wc_base, "");
1221750×
        let wc_hash = self.store.put_change(&wc)?;
1222750×
        let mut view = op.view.clone();
1223750×
        view.bookmarks.insert(
1224750×
            self.config.bookmark.clone(),
1225750×
            self.store.put_state(&StateObject::new(new_heads))?,
1226
        );
1227750×
        view.workspaces.insert(self.workspace, wc_hash);
1228750×
        self.record_op(&[op_ref], &format!("oxy commit -m {message:?}"), view)?;
1229745×
        drop(recording);
1230745×
        let rewriting = crate::timing::phase("commit: manifest");
1231745×
        if partial {
123210×
            // The rest is rebuilt from disk by the next snapshot.
123310×
            self.drop_manifest();
123410×
        } else {
1235735×
            let conflicted = snap.base_snapshot.is_conflicted() && !snap.resolves;
1236
            // The files on disk are now exactly the new base's renderings:
1237
            // record their graph keys, so the next snapshot neither reads nor
1238
            // renders them (oxygen#35).
1239735×
            let keys = if conflicted {
12400×
                HashMap::new()
1241
            } else {
1242735×
                committed_keys.unwrap_or_default()
1243
            };
1244735×
            match pending {
1245515×
                Some(m) => self.write_pending_manifest(m, conflicted, keys)?,
1246220×
                None => self.rewrite_manifest(conflicted, false, &keys)?,
1247
            }
1248
        }
1249745×
        drop(rewriting);
1250745×
        let packing = crate::timing::phase("commit: autopack");
1251745×
        self.maybe_autopack()?;
1252745×
        drop(packing);
1253745×
        let _hook = crate::timing::phase("commit: hook");
1254745×
        let _ = self.run_hook(
1255745×
            "post-commit",
1256745×
            &format!(
1257745×
                "{{\"event\":\"post-commit\",\"change_id\":{},\"hash\":{},\"message\":{}}}",
1258745×
                json_str(&snap.wc.change_id.to_hex()),
1259745×
                json_str(&hash.to_hex()),
1260745×
                json_str(message)
1261745×
            ),
1262745×
        );
1263745×
        Ok((hash, partial))
1264758×
    }
1265
}
1266
1267
/// What part of the working copy a commit takes (spec §12.3).
1268
#[derive(Clone, Debug)]
1269
pub enum Selection {
1270
    All,
1271
    /// Every operation and edit on nodes under these paths.
1272
    Paths(Vec<String>),
1273
    /// Hunk indices as `Repo::hunks` numbers them; dependent hunks are added.
1274
    Hunks(Vec<usize>),
1275
}
1276
1277
/// One selectable piece of the working copy: a tree operation or an edit.
1278
#[derive(Clone, Debug)]
1279
pub struct Hunk {
1280
    pub index: usize,
1281
    pub path: String,
1282
    /// Rendered like `oxy diff`.
1283
    pub text: String,
1284
}
1285
1286
/// The tree operations and edits on nodes under `paths`, plus the
1287
/// additions of any new parent directories they need.
12888×
fn select_paths(
12898×
    wc: &Change,
12908×
    base_snapshot: &Snapshot,
12918×
    paths: &[String],
12928×
) -> (Vec<TreeOp>, Vec<Edit>) {
129327×
    let selected = |p: &str| {
129427×
        paths
129527×
            .iter()
129627×
            .any(|x| p == x || p.starts_with(&format!("{}/", x.trim_end_matches('/'))))
129727×
    };
12988×
    let by_node = base_snapshot.tree.by_node();
12998×
    let mut new_names: HashMap<NodeId, (NodeId, String, NodeKind)> = HashMap::new();
13008×
    for op in &wc.tree_ops {
1301
        if let TreeOp::AddNode {
13025×
            node,
13035×
            parent,
13045×
            name,
13055×
            kind,
1306
            ..
13076×
        } = op
13085×
        {
13095×
            new_names.insert(*node, (*parent, name.clone(), *kind));
13105×
        }
1311
    }
13128×
    let mut nodes: BTreeSet<NodeId> = BTreeSet::new();
131328×
    for n in wc
13148×
        .tree_ops
13158×
        .iter()
13168×
        .map(|o| o.node())
131722×
        .chain(wc.edits.iter().map(|e| e.node()))
1318
    {
131928×
        if path_of_node(&n, &by_node, &new_names).is_some_and(|p| selected(&p)) {
132014×
            nodes.insert(n);
132114×
        }
1322
    }
1323
    // The nodes shown as one with a selected node are retired with it.
13248×
    for (dup, shown) in &base_snapshot.tree.unified {
13251×
        if nodes.contains(shown) {
13261×
            nodes.insert(*dup);
13271×
        }
1328
    }
1329
    // New parents of selected new nodes come along.
13308×
    let mut changed = true;
133116×
    while changed {
13328×
        changed = false;
13338×
        for (n, (parent, _, _)) in &new_names {
13345×
            if nodes.contains(n) && new_names.contains_key(parent) && nodes.insert(*parent) {
13350×
                changed = true;
13365×
            }
1337
        }
1338
    }
13398×
    let ops = wc
13408×
        .tree_ops
13418×
        .iter()
13428×
        .filter(|o| nodes.contains(&o.node()))
13438×
        .cloned()
13448×
        .collect();
13458×
    let edits = wc
13468×
        .edits
13478×
        .iter()
134822×
        .filter(|e| nodes.contains(&e.node()))
13498×
        .cloned()
13508×
        .collect();
13518×
    (ops, edits)
13528×
}
1353
1354
/// The hunks `indices` name plus whatever they refer to within the working
1355
/// copy (the parent directory of an added node, the insert that introduced
1356
/// an anchor line), renumbered so the result is a well-formed change.
1357
/// The nodes `unified` shows as one with another (a base's
1358
/// [`TreeView::unified`](crate::tree::TreeView::unified)) are retired with
1359
/// any hunk of the node shown.
13606×
fn select_hunks(
13616×
    wc: &Change,
13626×
    indices: &[usize],
13636×
    unified: &BTreeMap<NodeId, NodeId>,
13646×
) -> (Vec<TreeOp>, Vec<Edit>) {
13656×
    let n_ops = wc.tree_ops.len();
13666×
    let mut ops_sel = vec![false; n_ops];
13676×
    let mut edits_sel = vec![false; wc.edits.len()];
13686×
    for &i in indices {
13695×
        if i < n_ops {
13701×
            ops_sel[i] = true;
13714×
        } else if i - n_ops < wc.edits.len() {
13724×
            edits_sel[i - n_ops] = true;
13734×
        }
1374
    }
1375
    // Atom ranges each insert introduces, per node, in the working copy's numbering.
13766×
    let mut per_node: HashMap<NodeId, u32> = HashMap::new();
13776×
    let mut insert_ranges: Vec<Option<(NodeId, u32, u32)>> = Vec::new();
137812×
    for e in &wc.edits {
137912×
        insert_ranges.push(match e {
138012×
            Edit::Insert { node, lines, .. } => {
138112×
                let start = per_node.entry(*node).or_default();
138212×
                let r = (*node, *start, *start + lines.len() as u32);
138312×
                *start += lines.len() as u32;
138412×
                Some(r)
1385
            }
13860×
            _ => None,
1387
        });
1388
    }
13896×
    let add_index: HashMap<NodeId, usize> = wc
13906×
        .tree_ops
13916×
        .iter()
13926×
        .enumerate()
139310×
        .filter_map(|(i, o)| {
139410×
            if let TreeOp::AddNode { node, .. } = o {
13959×
                Some((*node, i))
1396
            } else {
13971×
                None
1398
            }
139910×
        })
14006×
        .collect();
14016×
    let insert_for = |node: &NodeId, index: u32| -> Option<usize> {
14020×
        insert_ranges
14030×
            .iter()
14040×
            .position(|r| matches!(r, Some((n, a, b)) if n == node && *a <= index && index < *b))
14050×
    };
1406
    // Closure.
14076×
    let mut changed = true;
140815×
    while changed {
14099×
        changed = false;
141019×
        for i in 0..n_ops {
141119×
            if !ops_sel[i] {
141213×
                continue;
14136×
            }
14146×
            if let TreeOp::AddNode { node, parent, .. } = &wc.tree_ops[i] {
14156×
                if let Some(&p) = add_index.get(parent) {
14164×
                    if !ops_sel[p] {
14172×
                        ops_sel[p] = true;
14182×
                        changed = true;
14192×
                    }
14202×
                }
1421
                // A new node's content belongs with its addition: nobody
1422
                // wants an empty file committed apart from its lines.
142312×
                for (j, e) in wc.edits.iter().enumerate() {
142412×
                    if e.node() == *node && !edits_sel[j] {
14251×
                        edits_sel[j] = true;
14261×
                        changed = true;
142711×
                    }
1428
                }
14290×
            }
1430
        }
143118×
        for j in 0..wc.edits.len() {
143218×
            if !edits_sel[j] {
143310×
                continue;
14348×
            }
14358×
            let e = &wc.edits[j];
14368×
            if let Some(&a) = add_index.get(&e.node()) {
14375×
                if !ops_sel[a] {
14381×
                    ops_sel[a] = true;
14391×
                    changed = true;
14404×
                }
14413×
            }
1442
            if let Edit::Insert {
14438×
                node,
14448×
                after,
14458×
                before,
1446
                ..
14478×
            } = e
1448
            {
144916×
                for r in [after, before] {
145016×
                    if let AtomRef::Atom { change, index } = r {
14513×
                        if change.is_zero() {
14520×
                            if let Some(k) = insert_for(node, *index) {
14530×
                                if !edits_sel[k] {
14540×
                                    edits_sel[k] = true;
14550×
                                    changed = true;
14560×
                                }
14570×
                            }
14583×
                        }
145913×
                    }
1460
                }
14610×
            }
1462
        }
1463
    }
1464
    // The retirement of a node shown as one with a selected node.
14656×
    if !unified.is_empty() {
14661×
        let chosen: HashSet<NodeId> = (0..n_ops)
14672×
            .filter(|i| ops_sel[*i])
14681×
            .map(|i| wc.tree_ops[i].node())
14691×
            .chain(
14701×
                (0..wc.edits.len())
14712×
                    .filter(|j| edits_sel[*j])
14721×
                    .map(|j| wc.edits[j].node()),
1473
            )
14741×
            .collect();
14752×
        for (i, o) in wc.tree_ops.iter().enumerate() {
14762×
            if let TreeOp::RemoveNode { node, .. } = o {
14771×
                if unified.get(node).is_some_and(|s| chosen.contains(s)) {
14781×
                    ops_sel[i] = true;
14791×
                }
14801×
            }
1481
        }
14825×
    }
1483
    // Renumber self-references: old atom index → new index among selected inserts.
14846×
    let mut remap: HashMap<(NodeId, u32), u32> = HashMap::new();
14856×
    let mut new_counts: HashMap<NodeId, u32> = HashMap::new();
148612×
    for (j, r) in insert_ranges.iter().enumerate() {
148712×
        if let (true, Some((node, a, b))) = (edits_sel[j], r) {
14885×
            let next = new_counts.entry(*node).or_default();
14895×
            for old in *a..*b {
14905×
                remap.insert((*node, old), *next);
14915×
                *next += 1;
14925×
            }
14937×
        }
1494
    }
149510×
    let map_ref = |r: AtomRef, node: &NodeId| -> AtomRef {
14963×
        match r {
14973×
            AtomRef::Atom { change, index } if change.is_zero() => AtomRef::Atom {
14980×
                change,
14990×
                index: remap.get(&(*node, index)).copied().unwrap_or(index),
15000×
            },
150110×
            other => other,
1502
        }
150310×
    };
15046×
    let ops = wc
15056×
        .tree_ops
15066×
        .iter()
15076×
        .enumerate()
150810×
        .filter(|(i, _)| ops_sel[*i])
15096×
        .map(|(_, o)| o.clone())
15106×
        .collect();
15116×
    let edits = wc
15126×
        .edits
15136×
        .iter()
15146×
        .enumerate()
151512×
        .filter(|(j, _)| edits_sel[*j])
15166×
        .map(|(_, e)| match e {
1517
            Edit::Insert {
15185×
                node,
15195×
                after,
15205×
                before,
15215×
                lines,
15225×
            } => Edit::Insert {
15235×
                node: *node,
15245×
                after: map_ref(*after, node),
15255×
                before: map_ref(*before, node),
15265×
                lines: lines.clone(),
15275×
            },
15280×
            other => other.clone(),
15295×
        })
15306×
        .collect();
15316×
    (ops, edits)
15326×
}
1533
1534
/// Render each tree operation and edit of `change` on its own, numbered.
15358×
pub fn render_hunks(change: &Change, base: &State, base_snapshot: &Snapshot) -> Vec<Hunk> {
15368×
    let by_node = base_snapshot.tree.by_node();
15378×
    let mut new_names: HashMap<NodeId, (NodeId, String, NodeKind)> = HashMap::new();
153810×
    for op in &change.tree_ops {
1539
        if let TreeOp::AddNode {
15409×
            node,
15419×
            parent,
15429×
            name,
15439×
            kind,
1544
            ..
154510×
        } = op
15469×
        {
15479×
            new_names.insert(*node, (*parent, name.clone(), *kind));
15489×
        }
1549
    }
15508×
    let mut out = Vec::new();
155110×
    for (i, op) in change.tree_ops.iter().enumerate() {
1552
        // A retired duplicate goes with the node shown: no hunk of its own.
155310×
        if is_unified_retirement(op, base_snapshot) {
15541×
            continue;
15559×
        }
15569×
        let one = Change {
15579×
            tree_ops: vec![op.clone()],
15589×
            edits: vec![],
15599×
            ..change.clone()
15609×
        };
15619×
        let path = path_of_node(&op.node(), &by_node, &new_names).unwrap_or_default();
15629×
        out.push(Hunk {
15639×
            index: i,
15649×
            path,
15659×
            text: render_change(&one, base, base_snapshot),
15669×
        });
1567
    }
156815×
    for (j, e) in change.edits.iter().enumerate() {
156915×
        let one = Change {
157015×
            tree_ops: vec![],
157115×
            edits: vec![e.clone()],
157215×
            ..change.clone()
157315×
        };
157415×
        let path = path_of_node(&e.node(), &by_node, &new_names).unwrap_or_default();
157515×
        out.push(Hunk {
157615×
            index: change.tree_ops.len() + j,
157715×
            path,
157815×
            text: render_change(&one, base, base_snapshot),
157915×
        });
158015×
    }
15818×
    out
15828×
}
1583
1584
/// One file's part of a diff, for `oxy diff --json`.
1585
#[derive(Clone, Debug)]
1586
pub struct FileDiff {
1587
    pub path: String,
1588
    /// `added`, `removed`, `modified`, `renamed`, `mode`, `replaced`.
1589
    pub kind: String,
1590
    pub hunks: Vec<DiffHunk>,
1591
    /// For renames, the previous path.
1592
    pub from: Option<String>,
1593
}
1594
1595
/// Lines inserted after `base_line` (0 = before the first line) and lines
1596
/// removed, with their base line numbers.
1597
#[derive(Clone, Debug, Default)]
1598
pub struct DiffHunk {
1599
    pub base_line: u32,
1600
    pub added: Vec<Vec<u8>>,
1601
    pub removed: Vec<(u32, Vec<u8>)>,
1602
}
1603
1604
impl Repo {
1605
    /// The content of `path` in a state: `heads`, or the working copy's base.
160627×
    pub fn file_at(&self, path: &str, heads: Option<&[ChangeHash]>) -> Result<Vec<u8>> {
1607
        // The state's history and tree, then the one file's graph: nothing
1608
        // else is built or rendered (oxygen#92).
1609
        // The working copy's base, and a state named by its heads (`-r
1610
        // main` on main), come from the workspace's state index.
161127×
        let base = if self.is_bare() {
16125×
            None
1613
        } else {
161422×
            Some(self.working_copy()?.1.deps)
1615
        };
161627×
        let same = |a: &[ChangeHash], b: &[ChangeHash]| {
16171×
            let (mut a, mut b) = (a.to_vec(), b.to_vec());
16181×
            a.sort();
16191×
            b.sort();
16201×
            a == b
16211×
        };
162227×
        let mut state = match (heads, base) {
16231×
            (Some(h), Some(b)) if same(h, &b) => self.load_state_indexed(&b)?,
16245×
            (Some(h), _) => self.load_state_history(h)?,
162521×
            (None, Some(b)) => self.load_state_indexed(&b)?,
16260×
            (None, None) => return fail("this is a bare repository: it has no working copy"),
1627
        };
162827×
        let view = self.tree_view(&mut state)?;
162927×
        let Some(node) = view.entries.get(path).map(|e| e.node) else {
16300×
            return fail(format!("{path} is not in that state"));
1631
        };
163227×
        self.load_graphs_of(&mut state, &[node])?;
163326×
        let snapshot = state.materialize_paths(view, [path]);
163426×
        let Some(f) = snapshot.files.get(path) else {
16350×
            return fail(format!("{path} is not in that state"));
1636
        };
163726×
        match &f.content {
16380×
            FileContent::Dir => fail(format!("{path} is a directory")),
163926×
            FileContent::Text { bytes, .. } => Ok(bytes.clone()),
16400×
            FileContent::Opaque { blobs } => match blobs.first() {
16410×
                Some(b) => self.read_blob(b),
16420×
                None => Ok(vec![]),
1643
            },
1644
        }
164527×
    }
1646
1647
    /// Restore `paths` (files or directories) to the working copy's base:
1648
    /// edits are undone, additions removed, removals put back. Returns the
1649
    /// number of paths touched.
16502×
    pub fn discard(&self, paths: &[String]) -> Result<usize> {
16512×
        let _wc = self.lock_working_copy()?;
16522×
        let snap = self.snapshot_status("oxy discard")?;
16537×
        let under = |p: &str| {
16547×
            paths
16557×
                .iter()
16567×
                .any(|x| p == x || p.starts_with(&format!("{}/", x.trim_end_matches('/'))))
16577×
        };
16582×
        let attrs = Repo::state_attributes(&snap.base_snapshot);
16592×
        let mut n = 0;
16603×
        for s in &snap.statuses {
16613×
            if !under(&s.path) {
16621×
                continue;
16632×
            }
16642×
            match snap.base_snapshot.files.get(&s.path) {
1665
                None => {
1666
                    // Added (or the new name of a rename): remove it.
16671×
                    let full = self.root.join(&s.path);
16681×
                    if full.is_dir() {
16690×
                        let _ = fs::remove_dir_all(&full);
16701×
                    } else {
16711×
                        let _ = fs::remove_file(&full);
16721×
                    }
16731×
                    n += 1;
1674
                }
16751×
                Some(f) => {
16761×
                    match &f.content {
16770×
                        FileContent::Dir => fs::create_dir_all(self.root.join(&s.path))?,
16781×
                        FileContent::Text { bytes, .. } => {
16791×
                            let on_disk: std::borrow::Cow<[u8]> = if attrs.lookup(&s.path).eol
16801×
                                == Some(crate::attributes::Eol::Crlf)
1681
                            {
16820×
                                crate::attributes::to_crlf(bytes).into()
1683
                            } else {
16841×
                                bytes.as_slice().into()
1685
                            };
16861×
                            self.write_file(&s.path, &on_disk, f.mode.exec)?;
1687
                        }
16880×
                        FileContent::Opaque { blobs } => {
16890×
                            let bytes = match blobs.first() {
16900×
                                Some(b) => self.read_blob(b)?,
16910×
                                None => vec![],
1692
                            };
16930×
                            if f.kind == NodeKind::Symlink {
16940×
                                self.write_symlink(&s.path, &bytes)?;
16950×
                            } else if f.kind == NodeKind::File {
16960×
                                self.write_file(&s.path, &bytes, f.mode.exec)?;
16970×
                            }
1698
                        }
1699
                    }
17001×
                    n += 1;
1701
                }
1702
            }
1703
        }
1704
        // A rename's old name is not in the statuses; put it back too.
17054×
        for (p, f) in &snap.base_snapshot.files {
17064×
            if under(p)
17071×
                && !self.root.join(p).exists()
17080×
                && f.kind != NodeKind::Dir
17090×
                && f.kind != NodeKind::Subrepo
17100×
                && !snap.statuses.iter().any(|s| s.path == *p)
1711
            {
17120×
                let bytes = match &f.content {
17130×
                    FileContent::Text { bytes, .. } => bytes.clone(),
17140×
                    FileContent::Opaque { blobs } => blobs
17150×
                        .first()
17160×
                        .map(|b| self.read_blob(b))
17170×
                        .transpose()?
17180×
                        .unwrap_or_default(),
17190×
                    FileContent::Dir => continue,
1720
                };
17210×
                if f.kind == NodeKind::Symlink {
17220×
                    self.write_symlink(p, &bytes)?
1723
                } else {
17240×
                    self.write_file(p, &bytes, f.mode.exec)?
1725
                }
17260×
                n += 1;
17274×
            }
1728
        }
17292×
        self.drop_manifest();
17302×
        Ok(n)
17312×
    }
1732
1733
    /// Undo the working-copy hunks `indices` (as `hunks` numbers them) on
1734
    /// disk, keeping the others: the files are rewritten from the base plus
1735
    /// the remaining hunks.
17361×
    pub fn discard_hunks(&self, indices: &[usize]) -> Result<usize> {
17371×
        let _wc = self.lock_working_copy()?;
17381×
        let (snap, hunks) = self.hunks()?;
17391×
        let keep: Vec<usize> = hunks
17401×
            .iter()
17411×
            .map(|h| h.index)
17421×
            .filter(|i| !indices.contains(i))
17431×
            .collect();
17441×
        let (ops, edits) = select_hunks(&snap.wc, &keep, &snap.base_snapshot.tree.unified);
17451×
        let dropped_nodes: BTreeSet<NodeId> = hunks
17461×
            .iter()
17471×
            .filter(|h| indices.contains(&h.index))
17481×
            .map(|h| {
17491×
                if h.index < snap.wc.tree_ops.len() {
17500×
                    snap.wc.tree_ops[h.index].node()
1751
                } else {
17521×
                    snap.wc.edits[h.index - snap.wc.tree_ops.len()].node()
1753
                }
17541×
            })
17551×
            .collect();
17561×
        let mut partial = snap.wc.clone();
17571×
        partial.tree_ops = ops;
17581×
        partial.edits = edits;
17591×
        partial.normalize();
17601×
        let mut st = snap.base.clone();
17611×
        st.add_unchecked(partial);
1762
        // Every file of the target is rendered: build the graphs the
1763
        // partial snapshot left out.
17641×
        self.load_all_graphs(&mut st)?;
17651×
        let target = st.materialize();
17661×
        let by_node_target = target.tree.by_node();
17671×
        let by_node_base = snap.base_snapshot.tree.by_node();
17681×
        let attrs = Repo::state_attributes(&target);
17691×
        let mut n = 0;
17701×
        for node in dropped_nodes {
17711×
            match by_node_target.get(&node) {
17721×
                Some(e) => {
17731×
                    let f = &target.files[&e.path];
17741×
                    match &f.content {
17750×
                        FileContent::Dir => {}
17761×
                        FileContent::Text { bytes, .. } => {
17771×
                            let on_disk: std::borrow::Cow<[u8]> = if attrs.lookup(&e.path).eol
17781×
                                == Some(crate::attributes::Eol::Crlf)
1779
                            {
17800×
                                crate::attributes::to_crlf(bytes).into()
1781
                            } else {
17821×
                                bytes.as_slice().into()
1783
                            };
17841×
                            self.write_file(&e.path, &on_disk, f.mode.exec)?;
1785
                        }
17860×
                        FileContent::Opaque { blobs } => {
17870×
                            let bytes = blobs
17880×
                                .first()
17890×
                                .map(|b| self.read_blob(b))
17900×
                                .transpose()?
17910×
                                .unwrap_or_default();
17920×
                            if f.kind == NodeKind::Symlink {
17930×
                                self.write_symlink(&e.path, &bytes)?
1794
                            } else {
17950×
                                self.write_file(&e.path, &bytes, f.mode.exec)?
1796
                            }
1797
                        }
1798
                    }
1799
                    // A discarded rename: the new name goes.
18001×
                    if let Some(old_path) = snap
18011×
                        .statuses
18021×
                        .iter()
18031×
                        .find(|s| {
18041×
                            s.status == ChangeStatus::Renamed && !target.files.contains_key(&s.path)
18051×
                        })
18061×
                        .map(|s| s.path.clone())
18070×
                    {
18080×
                        let _ = fs::remove_file(self.root.join(old_path));
18091×
                    }
18101×
                    n += 1;
1811
                }
1812
                None => {
1813
                    // The node exists in neither target nor base with a live path: an addition to remove.
18140×
                    if let Some(added) = snap.statuses.iter().find(|s| {
18150×
                        s.status == ChangeStatus::Added
18160×
                            && !target.files.contains_key(&s.path)
18170×
                            && !by_node_base.contains_key(&node)
18180×
                    }) {
18190×
                        let full = self.root.join(&added.path);
18200×
                        if full.is_dir() {
18210×
                            let _ = fs::remove_dir_all(&full);
18220×
                        } else {
18230×
                            let _ = fs::remove_file(&full);
18240×
                        }
18250×
                        n += 1;
18260×
                    }
1827
                }
1828
            }
1829
        }
18301×
        self.drop_manifest();
18311×
        Ok(n)
18321×
    }
1833
1834
    /// The diff of the working copy (`None`) or of a change, per file with
1835
    /// line-numbered hunks (spec: `oxy diff --json`).
18367×
    pub fn diff_files(&self, change: Option<&ChangeHash>) -> Result<Vec<FileDiff>> {
18377×
        let (c, base, base_snapshot) = match change {
18383×
            Some(h) => {
18393×
                let c = self.store.get_change(h)?;
18403×
                let (base, snapshot) = self.change_base(&c)?;
18413×
                (c, base, snapshot)
1842
            }
18434×
            None => match self.working_copy_with_base_unless_unchanged()? {
18443×
                Some(all) => all,
18451×
                None => return Ok(Vec::new()),
1846
            },
1847
        };
18486×
        Ok(diff_files_of(&c, &base, &base_snapshot))
18497×
    }
1850
1851
    /// The snapshot a command would take, without taking it, when the
1852
    /// status cache holds: every file is as the last snapshot left it, so
1853
    /// that snapshot's working-copy change is the answer. Its base comes
1854
    /// from the state index, the `.oxyattributes` files from disk. `None`
1855
    /// when a snapshot must be taken, and when there is nothing to commit
1856
    /// (the snapshot then says so). A conflicted base never gets here: the
1857
    /// cache does not hold for one.
1858759×
    pub(crate) fn snapshot_from_cache(&self) -> Result<Option<SnapshotResult>> {
1859759×
        let Some(statuses) = self.status_by_manifest()? else {
1860528×
            return Ok(None);
1861
        };
1862231×
        if statuses.is_empty() {
18633×
            return Ok(None);
1864228×
        }
1865228×
        let _t = crate::timing::phase("snapshot: from the status cache");
1866228×
        let (wc_hash, wc) = self.working_copy()?;
1867228×
        let base = self.load_state_indexed(&wc.deps)?;
1868228×
        let (base, base_snapshot) = self.render_base_for(&wc, base)?;
1869228×
        let attribute_files: Vec<(String, Vec<u8>)> = match self.read_manifest()? {
1870228×
            Some((_, _, m)) => m
1871228×
                .entries
1872228×
                .keys()
1873699×
                .filter(|p| is_attributes(p))
1874228×
                .filter_map(|p| fs::read(self.root.join(p)).ok().map(|b| (p.clone(), b)))
1875228×
                .collect(),
18760×
            None => Vec::new(),
1877
        };
1878228×
        let attributes = crate::attributes::Attributes::from_files(
1879228×
            attribute_files
1880228×
                .iter()
1881228×
                .map(|(p, b)| (p.as_str(), b.as_slice())),
1882
        );
1883228×
        Ok(Some(SnapshotResult {
1884228×
            wc_hash,
1885228×
            wc,
1886228×
            base,
1887228×
            base_snapshot,
1888228×
            statuses,
1889228×
            changed: false,
1890228×
            resolves: false,
1891228×
            contributors: Vec::new(),
1892228×
            attributes,
1893228×
            untracked_nested: self.untracked_nested.borrow().clone(),
1894228×
            manifest: None,
1895228×
        }))
1896759×
    }
1897
1898
    /// The working-copy change with its base state and a snapshot of the
1899
    /// base, for showing what the working copy changes ([`render_change`],
1900
    /// [`diff_files_of`]). While the status cache holds (every file as the
1901
    /// last snapshot left it), the stored working-copy change is the
1902
    /// answer, no snapshot is taken, and the base's snapshot holds its tree
1903
    /// but no file; otherwise a snapshot makes all three.
19042×
    pub fn working_copy_with_base(&self) -> Result<(Change, State, Snapshot)> {
19052×
        match self.working_copy_with_base_unless_unchanged()? {
19061×
            Some(all) => Ok(all),
1907
            None => {
19081×
                let (_, wc) = self.working_copy()?;
19091×
                let base = self.load_state_indexed(&wc.deps)?;
19101×
                let (base, snapshot) = self.tree_base_for(&wc, base)?;
19111×
                Ok((wc, base, snapshot))
1912
            }
1913
        }
19142×
    }
1915
1916
    /// [`Repo::working_copy_with_base`], or `None` when the status cache
1917
    /// holds and the working-copy change changes nothing: its diff is
1918
    /// empty, and the base is not loaded for it (oxygen#94).
19197×
    pub fn working_copy_with_base_unless_unchanged(
19207×
        &self,
19217×
    ) -> Result<Option<(Change, State, Snapshot)>> {
19227×
        if self.status_by_manifest()?.is_some() {
19235×
            let (_, wc) = self.working_copy()?;
19245×
            if wc.tree_ops.is_empty() && wc.edits.is_empty() {
19253×
                return Ok(None);
19262×
            }
19272×
            let base = self.load_state_indexed(&wc.deps)?;
19282×
            let (base, snapshot) = self.tree_base_for(&wc, base)?;
19292×
            return Ok(Some((wc, base, snapshot)));
19302×
        }
19312×
        let snap = self.snapshot_status("oxy diff")?;
19322×
        Ok(Some((snap.wc, snap.base, snap.base_snapshot)))
19337×
    }
1934
1935
    /// The log restricted to changes touching `path` (its node, so renames
1936
    /// are followed), on the current bookmark.
19376×
    pub fn log_for_path(&self, path: &str) -> Result<Vec<LogEntry>> {
19386×
        let heads = self.bookmark_heads()?;
19396×
        if self.is_bare() {
19401×
            return self.log_for_path_in(path, &heads);
19415×
        }
19425×
        let entries = self.log()?;
19435×
        let (_, wc) = self.working_copy()?;
1944
        // The path's node from the trees alone: the base's (from the
1945
        // workspace's state index), else the bookmark's. Nothing is
1946
        // rendered.
19475×
        let node_in = |mut state: State| -> Result<Option<HashSet<NodeId>>> {
19485×
            Ok(nodes_at(&self.tree_view(&mut state)?, path))
19495×
        };
19505×
        let nodes = match node_in(self.load_state_indexed(&wc.deps)?)? {
19515×
            Some(n) => Some(n),
19520×
            None => node_in(self.load_state_history(&heads)?)?,
1953
        };
19545×
        let Some(nodes) = nodes else {
19550×
            return fail(format!("{path} is not tracked"));
1956
        };
19575×
        Ok(self.entries_touching_up_to(entries, nodes, None))
19586×
    }
1959
1960
    /// The log of the state with these heads restricted to changes touching
1961
    /// `path` (its node, so renames are followed).
19622×
    pub fn log_for_path_in(&self, path: &str, heads: &[ChangeHash]) -> Result<Vec<LogEntry>> {
19632×
        self.log_for_path_of(&self.load_state_history(heads)?, path, None)
19642×
    }
1965
1966
    /// The changes of a loaded state touching `path`, newest first, at most
1967
    /// `limit` of them. The path is found in the state's tree alone, so no
1968
    /// file is rendered, and the walk stops once `limit` are found.
19695×
    pub fn log_for_path_of(
19705×
        &self,
19715×
        state: &State,
19725×
        path: &str,
19735×
        limit: Option<usize>,
19745×
    ) -> Result<Vec<LogEntry>> {
19755×
        let Some(nodes) = nodes_at(&state.view(), path) else {
19761×
            return fail(format!("{path} is not in that state"));
1977
        };
19784×
        Ok(self.entries_touching_up_to(self.log_of(state), nodes, limit))
19795×
    }
1980
19819×
    fn entries_touching_up_to(
19829×
        &self,
19839×
        entries: Vec<LogEntry>,
19849×
        wanted: HashSet<NodeId>,
19859×
        limit: Option<usize>,
19869×
    ) -> Vec<LogEntry> {
19879×
        let mut touched = self.touched();
19889×
        if limit.is_none() {
19898×
            let hashes: Vec<ChangeHash> = entries.iter().map(|e| e.hash).collect();
19908×
            touched.fill(self, &hashes);
19911×
        }
19929×
        let mut out = Vec::new();
199332×
        for e in entries {
199432×
            if limit.is_some_and(|n| out.len() >= n) {
19951×
                break;
199631×
            }
199731×
            if touched.touches(self, &e.hash, &wanted) {
199820×
                out.push(e);
199920×
            }
2000
        }
20019×
        touched.save();
20029×
        out
20039×
    }
2004
}
2005
2006
/// The node at `path` in `view`, with the nodes it shows as one with it
2007
/// (identical additions, spec §9.2): the file's history is all of theirs.
200810×
fn nodes_at(view: &crate::tree::TreeView, path: &str) -> Option<HashSet<NodeId>> {
200910×
    let node = view.entries.get(path)?.node;
20109×
    let mut out = HashSet::from([node]);
20119×
    out.extend(
20129×
        view.unified
20139×
            .iter()
20149×
            .filter(|(_, shown)| **shown == node)
20159×
            .map(|(dup, _)| *dup),
2016
    );
20179×
    Some(out)
201810×
}
2019
2020
/// Per-file hunks of `change` against `base`.
20216×
pub fn diff_files_of(change: &Change, base: &State, base_snapshot: &Snapshot) -> Vec<FileDiff> {
20226×
    let by_node = base_snapshot.tree.by_node();
20236×
    let mut new_names: HashMap<NodeId, (NodeId, String, NodeKind)> = HashMap::new();
20246×
    for op in &change.tree_ops {
2025
        if let TreeOp::AddNode {
20262×
            node,
20272×
            parent,
20282×
            name,
20292×
            kind,
2030
            ..
20313×
        } = op
20322×
        {
20332×
            new_names.insert(*node, (*parent, name.clone(), *kind));
20342×
        }
2035
    }
203610×
    let path_of = |n: &NodeId| -> String {
203710×
        path_of_node(n, &by_node, &new_names).unwrap_or_else(|| format!("<node {}>", n.short(8)))
203810×
    };
20396×
    let mut files: BTreeMap<NodeId, FileDiff> = BTreeMap::new();
20406×
    let mut order: Vec<NodeId> = Vec::new();
204115×
    let mut entry = |files: &mut BTreeMap<NodeId, FileDiff>, n: NodeId, kind: &str| {
204215×
        if let std::collections::btree_map::Entry::Vacant(v) = files.entry(n) {
204310×
            order.push(n);
204410×
            v.insert(FileDiff {
204510×
                path: path_of(&n),
204610×
                kind: kind.to_string(),
204710×
                hunks: vec![],
204810×
                from: None,
204910×
            });
205010×
        }
205115×
    };
20526×
    for op in change
20536×
        .tree_ops
20546×
        .iter()
20556×
        .filter(|o| !is_unified_retirement(o, base_snapshot))
2056
    {
20573×
        match op {
20582×
            TreeOp::AddNode { node, kind, .. } => {
20592×
                if *kind != NodeKind::Dir {
20602×
                    entry(&mut files, *node, "added");
20612×
                }
2062
            }
20631×
            TreeOp::RemoveNode { node, .. } => {
20641×
                entry(&mut files, *node, "removed");
20651×
                if let Some(e) = by_node.get(node) {
20661×
                    files.get_mut(node).unwrap().path = e.path.clone();
20671×
                }
2068
            }
2069
            TreeOp::Move {
20700×
                node, parent, name, ..
2071
            } => {
20720×
                entry(&mut files, *node, "renamed");
20730×
                let f = files.get_mut(node).unwrap();
20740×
                f.from = by_node.get(node).map(|e| e.path.clone());
20750×
                let dir = if parent.is_root() {
20760×
                    String::new()
2077
                } else {
20780×
                    path_of_node(parent, &by_node, &new_names).unwrap_or_default()
2079
                };
20800×
                f.path = if dir.is_empty() {
20810×
                    name.clone()
2082
                } else {
20830×
                    format!("{dir}/{name}")
2084
                };
2085
            }
20860×
            TreeOp::SetMode { node, .. } => entry(&mut files, *node, "mode"),
2087
        }
2088
    }
2089
    // Base line numbers per node, 1-based.
20906×
    let mut line_of: HashMap<NodeId, HashMap<(ChangeHash, u32), u32>> = HashMap::new();
209112×
    let mut lines_for = |n: &NodeId| -> HashMap<(ChangeHash, u32), u32> {
209212×
        line_of
209312×
            .entry(*n)
209412×
            .or_insert_with(|| {
20959×
                base.live_lines(n)
20969×
                    .into_iter()
20979×
                    .enumerate()
209812×
                    .map(|(i, (k, _))| (k, i as u32 + 1))
20999×
                    .collect()
21009×
            })
210112×
            .clone()
210212×
    };
210312×
    for e in &change.edits {
210412×
        let n = e.node();
210512×
        let is_new = new_names.contains_key(&n);
210612×
        entry(&mut files, n, if is_new { "added" } else { "modified" });
210712×
        let f = files.get_mut(&n).unwrap();
210812×
        match e {
210910×
            Edit::Insert { after, lines, .. } => {
211010×
                let map = lines_for(&n);
211110×
                let base_line = match after {
21123×
                    AtomRef::Start => 0,
21130×
                    AtomRef::End => map.len() as u32,
21147×
                    AtomRef::Atom { change, index } if change.is_zero() => {
21150×
                        f.hunks.last().map(|h| h.base_line).unwrap_or(0)
2116
                    }
21177×
                    AtomRef::Atom { change, index } => {
21187×
                        map.get(&(*change, *index)).copied().unwrap_or(0)
2119
                    }
2120
                };
212110×
                f.hunks.push(DiffHunk {
212210×
                    base_line,
212310×
                    added: lines.to_vec(),
212410×
                    removed: vec![],
212510×
                });
2126
            }
21272×
            Edit::Delete { atoms, .. } => {
21282×
                let map = lines_for(&n);
21292×
                let mut removed = Vec::new();
21302×
                for r in atoms {
21312×
                    for i in r.from..r.to {
21322×
                        let line = map.get(&(r.change, i)).copied().unwrap_or(0);
21332×
                        let text = base
21342×
                            .file(&n)
21352×
                            .and_then(|g| g.content(&(r.change, i)))
21362×
                            .unwrap_or(b"")
21372×
                            .to_vec();
21382×
                        removed.push((line, text));
2139
                    }
2140
                }
21412×
                let base_line = removed
21422×
                    .first()
21432×
                    .map(|(l, _)| l.saturating_sub(1))
21442×
                    .unwrap_or(0);
21452×
                f.hunks.push(DiffHunk {
21462×
                    base_line,
21472×
                    added: vec![],
21482×
                    removed,
21492×
                });
2150
            }
2151
            Edit::Replace { .. } => {
21520×
                if !is_new {
21530×
                    f.kind = "replaced".into();
21540×
                }
2155
            }
2156
        }
2157
    }
215810×
    order.into_iter().filter_map(|n| files.remove(&n)).collect()
21596×
}
2160
2161
/// Builds the tree ops and edits of a working-copy change against a base.
2162
/// `BLAKE3("oxy node 1" 0 seed kind path)`, truncated: a node identifier
2163
/// that the same seed and path always give (never the root's).
216459×
fn seeded_node(seed: &[u8; 32], path: &str, kind: NodeKind) -> NodeId {
216559×
    let mut h = blake3::Hasher::new();
216659×
    h.update(b"oxy node 1\0");
216759×
    h.update(seed);
216859×
    h.update(&[match kind {
216945×
        NodeKind::File => 1,
217013×
        NodeKind::Dir => 2,
21710×
        NodeKind::Symlink => 3,
21721×
        NodeKind::Subrepo => 4,
2173
    }]);
217459×
    h.update(path.as_bytes());
217559×
    let mut id = [0u8; 16];
217659×
    id.copy_from_slice(&h.finalize().as_bytes()[..16]);
217759×
    if id == [0; 16] {
21780×
        id[15] = 1;
217959×
    }
218059×
    NodeId(id)
218159×
}
2182
2183
struct ChangeBuilder<'a> {
2184
    base: &'a State,
2185
    base_snapshot: &'a Snapshot,
2186
    tree_ops: Vec<TreeOp>,
2187
    edits: Vec<Edit>,
2188
    statuses: Vec<PathStatus>,
2189
    dir_nodes: HashMap<String, NodeId>,
2190
    reuse: HashMap<String, (NodeId, NodeKind)>,
2191
    /// Changes that contributed to conflicts this working copy resolves.
2192
    contributors: BTreeSet<ChangeHash>,
2193
    resolves: bool,
2194
    attrs: crate::attributes::Attributes,
2195
    blobs: HashMap<String, ObjectRef>,
2196
    /// Opaque files whose replace conflict the content settles.
2197
    resolve: HashSet<String>,
2198
    /// When set, new nodes' identifiers derive from it and their paths.
2199
    node_seed: Option<[u8; 32]>,
2200
    /// For a Git import, the base's dead directories by where they were
2201
    /// (see `ensure_dir`), worked out when first needed.
2202
    dead_dirs: Option<HashMap<(NodeId, String), (NodeId, crate::tree::OpKey)>>,
2203
    /// Text edits of edited files, worked out in parallel beforehand
2204
    /// (`diff_in_parallel`); a file not here is diffed when it is updated.
2205
    diffs: HashMap<String, Vec<Edit>>,
2206
}
2207
2208
impl<'a> ChangeBuilder<'a> {
22092289×
    fn new(
22102289×
        base: &'a State,
22112289×
        base_snapshot: &'a Snapshot,
22122289×
        reuse: HashMap<String, (NodeId, NodeKind)>,
22132289×
    ) -> Self {
22142289×
        let mut dir_nodes: HashMap<String, NodeId> = HashMap::new();
22152289×
        dir_nodes.insert(String::new(), NodeId::ROOT);
221617991×
        for (p, e) in base_snapshot.tree.entries.iter() {
221717991×
            if e.kind == NodeKind::Dir {
2218560×
                dir_nodes.insert(p.clone(), e.node);
221917431×
            }
2220
        }
22212289×
        ChangeBuilder {
22222289×
            base,
22232289×
            base_snapshot,
22242289×
            tree_ops: vec![],
22252289×
            edits: vec![],
22262289×
            statuses: vec![],
22272289×
            dir_nodes,
22282289×
            reuse,
22292289×
            contributors: BTreeSet::new(),
22302289×
            resolves: false,
22312289×
            attrs: crate::attributes::Attributes::default(),
22322289×
            blobs: HashMap::new(),
22332289×
            resolve: HashSet::new(),
22342289×
            node_seed: None,
22352289×
            dead_dirs: None,
22362289×
            diffs: HashMap::new(),
22372289×
        }
22382289×
    }
2239
2240
    /// Diff the edited text files among `entries` against their base
2241
    /// renderings at once, on every core, for `update_path` to take: the
2242
    /// same diff it would make, only not one file after another.
22432289×
    fn diff_in_parallel(&mut self, entries: &BTreeMap<String, FsEntry>) {
2244
        use rayon::prelude::*;
22452289×
        let files = &self.base_snapshot.files;
22462289×
        let edited: Vec<(&String, &FsEntry, &crate::state::FileState)> = entries
22472289×
            .iter()
224819178×
            .filter_map(|(p, e)| {
224919178×
                let x = files.get(p)?;
225012971×
                (x.kind == e.kind && !e.unchanged && !self.opaque_for(p, e)).then_some((p, e, x))
225119178×
            })
22522289×
            .collect();
2253
        // Below this, starting the threads costs more than it saves.
22542289×
        if edited.len() < 16 {
22552279×
            return;
225610×
        }
225710×
        let this = &*self;
225810×
        let attrs = &this.attrs;
225910×
        let diffs: Vec<(String, Vec<Edit>)> = edited
226010×
            .par_iter()
22615564×
            .filter_map(|(p, e, x)| {
2262
                let FileContent::Text {
22635564×
                    bytes,
22645564×
                    materialized,
22655564×
                } = &x.content
2266
                else {
22670×
                    return None;
2268
                };
22695564×
                if materialized.is_conflicted() {
22700×
                    return None;
22715564×
                }
22725564×
                let disk_text = if attrs.lookup(p).eol.is_some() {
22730×
                    std::sync::Arc::new(crate::attributes::normalize_eol(&e.content))
2274
                } else {
22755564×
                    e.content.clone()
2276
                };
22775564×
                if *bytes == *disk_text {
22785484×
                    return None;
227980×
                }
228080×
                let keys = materialized.live_atoms();
228180×
                let lines = crate::diff::split_lines(bytes);
228280×
                (keys.len() == lines.len()).then(|| {
228380×
                    let edits = crate::diff::text_edits_of(x.node, &keys, &lines, &disk_text);
228480×
                    ((*p).clone(), edits)
228580×
                })
22865564×
            })
228710×
            .collect();
228810×
        self.diffs = diffs.into_iter().collect();
22892289×
    }
2290
22912289×
    fn with_attributes(mut self, attrs: crate::attributes::Attributes) -> Self {
22922289×
        self.attrs = attrs;
22932289×
        self
22942289×
    }
2295
2296
    /// Whether a file is opaque: forced by `binary`, forced text by `text`
2297
    /// only when it has no NUL bytes, else sniffed.
2298
    /// The blob for an opaque entry: the cached one, else stored now.
2299174×
    fn blob_of(
2300174×
        &mut self,
2301174×
        repo: &Repo,
2302174×
        path: &str,
2303174×
        e: &FsEntry,
2304174×
        nocompress: bool,
2305174×
    ) -> Result<ObjectRef> {
2306174×
        let b = match e.blob {
23070×
            Some(b) => b,
2308174×
            None => repo.store_blob_for(&e.content, nocompress)?,
2309
        };
2310174×
        self.blobs.insert(path.to_string(), b);
2311174×
        Ok(b)
2312174×
    }
2313
231423662×
    fn opaque_for(&self, path: &str, e: &FsEntry) -> bool {
231523662×
        if e.blob.is_some() {
23164×
            return true;
231723658×
        }
231823658×
        if e.kind == NodeKind::Symlink || e.kind == NodeKind::Subrepo {
2319130×
            return true;
232023528×
        }
232123528×
        match self.attrs.lookup(path).binary {
232212×
            Some(true) => true,
23230×
            Some(false) => is_binary(&e.content),
232423516×
            None => is_binary(&e.content),
2325
        }
232623662×
    }
2327
2328
    /// Text content as stored: `\r\n` normalized for `eol=` files.
232914782×
    fn stored_text(
233014782×
        &self,
233114782×
        path: &str,
233214782×
        content: &std::sync::Arc<Vec<u8>>,
233314782×
    ) -> std::sync::Arc<Vec<u8>> {
233414782×
        if self.attrs.lookup(path).eol.is_some() {
23357×
            std::sync::Arc::new(crate::attributes::normalize_eol(content))
2336
        } else {
233714775×
            content.clone()
2338
        }
233914782×
    }
2340
2341
    /// The identifier of a node added at `path`: reused when asked, derived
2342
    /// from the seed when there is one, random otherwise.
23436330×
    fn new_node(&self, path: &str, kind: NodeKind) -> NodeId {
23446330×
        if let Some(n) = self.reused_node(path, kind) {
2345166×
            return n;
23466164×
        }
23476164×
        match &self.node_seed {
234859×
            Some(seed) => seeded_node(seed, path, kind),
23496105×
            None => NodeId::random(),
2350
        }
23516330×
    }
2352
23536330×
    fn reused_node(&self, path: &str, kind: NodeKind) -> Option<NodeId> {
23546330×
        self.reuse
23556330×
            .get(path)
23566330×
            .filter(|(_, k)| *k == kind)
23576330×
            .map(|(n, _)| *n)
23586330×
    }
2359
2360
    /// A dead directory last placed at (`parent`, `name`) in the base.
236115×
    fn revivable_dir(
236215×
        &mut self,
236315×
        parent: NodeId,
236415×
        name: &str,
236515×
    ) -> Option<(NodeId, crate::tree::OpKey)> {
236615×
        let base = self.base;
236715×
        self.dead_dirs
236815×
            .get_or_insert_with(|| base.tree().dead_dirs())
236915×
            .get(&(parent, name.to_string()))
237015×
            .copied()
237115×
    }
2372
23736208×
    fn ensure_dir(&mut self, path: &str) -> NodeId {
23746208×
        if let Some(n) = self.dir_nodes.get(path) {
23756055×
            return *n;
2376153×
        }
2377153×
        let mut parent = NodeId::ROOT;
2378153×
        let mut prefix = String::new();
2379172×
        for comp in path.split('/') {
2380172×
            if !prefix.is_empty() {
238119×
                prefix.push('/');
2382153×
            }
2383172×
            prefix.push_str(comp);
2384172×
            let known = self.dir_nodes.get(&prefix).copied();
2385172×
            let revive = match known {
238613×
                Some(_) => None,
2387159×
                None if self.node_seed.is_some() => self.revivable_dir(parent, comp),
2388144×
                None => None,
2389
            };
2390172×
            parent = match (known, revive) {
239113×
                (Some(n), _) => n,
23922×
                (None, Some((node, old))) => {
2393
                    // Git has no identity for a directory: one that comes
2394
                    // back where it was is the same directory, brought back
2395
                    // with a move, so lines of history that placed files in
2396
                    // it before and after agree (oxygen#30).
23972×
                    self.tree_ops.push(TreeOp::Move {
23982×
                        node,
23992×
                        old: OpRef {
24002×
                            change: old.0,
24012×
                            index: old.1,
24022×
                        },
24032×
                        parent,
24042×
                        name: comp.to_string(),
24052×
                    });
24062×
                    self.dir_nodes.insert(prefix.clone(), node);
24072×
                    node
2408
                }
2409
                (None, None) => {
2410157×
                    let node = self.new_node(&prefix, NodeKind::Dir);
2411157×
                    self.tree_ops.push(TreeOp::AddNode {
2412157×
                        node,
2413157×
                        kind: NodeKind::Dir,
2414157×
                        mode: Mode::default(),
2415157×
                        parent,
2416157×
                        name: comp.to_string(),
2417157×
                    });
2418157×
                    self.dir_nodes.insert(prefix.clone(), node);
2419157×
                    node
2420
                }
2421
            };
2422
        }
2423153×
        parent
24246208×
    }
2425
24266173×
    fn add_path(&mut self, repo: &Repo, path: &str, e: &FsEntry) -> Result<()> {
24276173×
        let (dir, name) = split_path(path);
24286173×
        let parent = self.ensure_dir(dir);
24296173×
        let node = self.new_node(path, e.kind);
24306173×
        let opaque = self.opaque_for(path, e);
24316173×
        let nocompress = self.attrs.lookup(path).nocompress;
24326173×
        self.tree_ops.push(TreeOp::AddNode {
24336173×
            node,
24346173×
            kind: e.kind,
24356173×
            mode: Mode {
24366173×
                exec: e.exec,
24376173×
                opaque,
24386173×
            },
24396173×
            parent,
24406173×
            name: name.to_string(),
24416173×
        });
24426173×
        if opaque {
2443125×
            let blob = self.blob_of(repo, path, e, nocompress)?;
2444125×
            self.edits.push(Edit::Replace {
2445125×
                node,
2446125×
                old: None,
2447125×
                new: Some(blob),
2448125×
            });
24496048×
        } else if !e.content.is_empty() {
24506020×
            let content = self.stored_text(path, &e.content);
24516020×
            self.edits.push(Edit::Insert {
24526020×
                node,
24536020×
                after: crate::objects::AtomRef::Start,
24546020×
                before: crate::objects::AtomRef::End,
24556020×
                lines: crate::lines::Lines::split_shared(content),
24566020×
            });
24576020×
        }
24586173×
        self.statuses.push(PathStatus {
24596173×
            path: path.to_string(),
24606173×
            status: ChangeStatus::Added,
24616173×
        });
24626173×
        Ok(())
24636173×
    }
2464
2465
    /// Move the node at `old` to `new` and apply `e`'s content to it.
246635×
    fn move_path(
246735×
        &mut self,
246835×
        repo: &Repo,
246935×
        old: &str,
247035×
        new: &str,
247135×
        e: &FsEntry,
247235×
        expected: &crate::state::FileState,
247335×
    ) -> Result<()> {
247435×
        let placement = self.base_snapshot.tree.entries[old].placement;
247535×
        let (dir, name) = split_path(new);
247635×
        let parent = self.ensure_dir(dir);
247735×
        self.tree_ops.push(TreeOp::Move {
247835×
            node: expected.node,
247935×
            old: op_ref(placement),
248035×
            parent,
248135×
            name: name.to_string(),
248235×
        });
248335×
        for k in self.same_place(&expected.node, placement) {
24840×
            self.tree_ops.push(TreeOp::RemoveNode {
24850×
                node: expected.node,
24860×
                placement: op_ref(k),
24870×
            });
24880×
        }
248935×
        self.update_path(repo, old, e, expected)?;
2490
        // update_path reports under the old path; the rename is what the user sees.
249135×
        self.statuses.retain(|s| s.path != old);
249235×
        self.statuses.push(PathStatus {
249335×
            path: new.to_string(),
249435×
            status: ChangeStatus::Renamed,
249535×
        });
249635×
        Ok(())
249735×
    }
2498
2499
    /// For a Git import: a node the commit keeps is in one place, the one
2500
    /// its tree names, so any other live placement it has in the base goes;
2501
    /// and a node the tree cannot show at all (an orphan) goes too. Such a
2502
    /// placement is out of sight, under a directory another line of history
2503
    /// removed, where no diff of the tree would ever reach it (oxygen#30).
250488×
    fn retire_stray_placements(&mut self) {
250588×
        let mut retired: HashSet<(ChangeHash, u32)> = HashSet::new();
250688×
        let mut placed: BTreeSet<NodeId> = BTreeSet::new();
250799×
        for op in &self.tree_ops {
250899×
            match op {
250919×
                TreeOp::Move { node, old, .. } => {
251019×
                    retired.insert((old.change, old.index));
251119×
                    placed.insert(*node);
251219×
                }
251321×
                TreeOp::RemoveNode { placement, .. } => {
251421×
                    retired.insert((placement.change, placement.index));
251521×
                }
251659×
                TreeOp::AddNode { .. } | TreeOp::SetMode { .. } => {}
2517
            }
2518
        }
2519
        // Nodes kept where they were: what the base's tree view shows and
2520
        // this change neither moves nor removes.
252188×
        let mut kept: HashMap<NodeId, (ChangeHash, u32)> = HashMap::new();
2522241×
        for e in self.base_snapshot.tree.entries.values() {
2523241×
            if !retired.contains(&e.placement) {
2524204×
                kept.insert(e.node, e.placement);
2525204×
            }
2526
        }
2527
        // Only a node with several live placements can have a stray one,
2528
        // and the tree view names each as a conflict.
252988×
        let multi: BTreeSet<NodeId> = self
253088×
            .base_snapshot
253188×
            .tree
253288×
            .conflicts
253388×
            .iter()
253488×
            .filter_map(|c| match c {
25351×
                crate::tree::TreeConflict::MultiPlacement { node, .. } => Some(*node),
25366×
                _ => None,
25377×
            })
253888×
            .collect();
253988×
        let mut extra = Vec::new();
2540
        // A node whose only placements are under a directory another line
2541
        // removed (an orphan) is nowhere the tree can show, and Git's tree
2542
        // has no such path: it goes.
254388×
        for c in &self.base_snapshot.tree.conflicts {
25447×
            let crate::tree::TreeConflict::Orphan { node, .. } = c else {
25456×
                continue;
2546
            };
25471×
            if kept.contains_key(node) || placed.contains(node) {
25480×
                continue;
25491×
            }
25501×
            for (k, _) in self.base.tree().live_placements(node) {
25511×
                if retired.insert(k) {
25521×
                    extra.push(TreeOp::RemoveNode {
25531×
                        node: *node,
25541×
                        placement: op_ref(k),
25551×
                    });
25561×
                }
2557
            }
2558
        }
255988×
        for node in placed
256088×
            .iter()
256188×
            .chain(multi.iter().filter(|n| kept.contains_key(*n)))
2562
        {
256319×
            for (k, _) in self.base.tree().live_placements(node) {
256418×
                if retired.contains(&k) || kept.get(node) == Some(&k) {
256517×
                    continue;
25661×
                }
25671×
                retired.insert(k);
25681×
                extra.push(TreeOp::RemoveNode {
25691×
                    node: *node,
25701×
                    placement: op_ref(k),
25711×
                });
2572
            }
2573
        }
257488×
        if !extra.is_empty() {
25752×
            self.resolves = true;
25762×
            self.tree_ops.extend(extra);
257786×
        }
257888×
    }
2579
2580
    /// Nodes the base shows as one with another (identical additions at one
2581
    /// path, spec §9.2) are retired by the change that first touches the
2582
    /// node shown: edited, moved, removed or given a mode alone, it would
2583
    /// differ from them and the name conflict would come back. Nothing
2584
    /// else changes for the user, so no status reports it.
25852289×
    fn retire_unified(&mut self) {
25862289×
        let unified = &self.base_snapshot.tree.unified;
25872289×
        if unified.is_empty() {
25882268×
            return;
258921×
        }
259021×
        let touched: HashSet<NodeId> = self
259121×
            .tree_ops
259221×
            .iter()
259321×
            .map(|o| o.node())
259422×
            .chain(self.edits.iter().map(|e| e.node()))
259521×
            .collect();
259621×
        let mut retired: HashSet<(ChangeHash, u32)> = HashSet::new();
259721×
        for op in &self.tree_ops {
259814×
            match op {
25993×
                TreeOp::Move { old, .. } => {
26003×
                    retired.insert((old.change, old.index));
26013×
                }
26023×
                TreeOp::RemoveNode { placement, .. } => {
26033×
                    retired.insert((placement.change, placement.index));
26043×
                }
26058×
                TreeOp::AddNode { .. } | TreeOp::SetMode { .. } => {}
2606
            }
2607
        }
260821×
        let mut extra = Vec::new();
260922×
        for (dup, shown) in unified {
261022×
            if !touched.contains(shown) {
26115×
                continue;
261217×
            }
261317×
            for (k, _) in self.base.tree().live_placements(dup) {
261417×
                if retired.insert(k) {
261517×
                    extra.push(TreeOp::RemoveNode {
261617×
                        node: *dup,
261717×
                        placement: op_ref(k),
261817×
                    });
261917×
                }
2620
            }
2621
        }
262221×
        self.tree_ops.extend(extra);
26232289×
    }
2624
2625
    /// The node's other live placements at the same place as `k`, the one
2626
    /// the tree shows: two lines of history that put a node back where it
2627
    /// was each leave a placement, and the tree shows them as one file. A
2628
    /// change that removes or moves it retires them together, or the copy
2629
    /// left behind outlives its directory (oxygen#88).
2630149×
    fn same_place(&self, node: &NodeId, k: (ChangeHash, u32)) -> Vec<(ChangeHash, u32)> {
2631149×
        let tree = self.base.tree();
2632149×
        let Some(shown) = tree.placement(&k) else {
26330×
            return Vec::new();
2634
        };
2635149×
        tree.live_placements(node)
2636149×
            .into_iter()
2637151×
            .filter(|(o, p)| *o != k && p.parent == shown.parent && p.name == shown.name)
2638149×
            .map(|(o, _)| o)
2639149×
            .collect()
2640149×
    }
2641
2642114×
    fn remove_path(&mut self, path: &str, expected: &crate::state::FileState) {
2643114×
        let entry = &self.base_snapshot.tree.entries[path];
2644114×
        let placement = entry.placement;
2645114×
        self.tree_ops.push(TreeOp::RemoveNode {
2646114×
            node: expected.node,
2647114×
            placement: op_ref(placement),
2648114×
        });
2649114×
        for k in self.same_place(&expected.node, placement) {
26501×
            self.tree_ops.push(TreeOp::RemoveNode {
26511×
                node: expected.node,
26521×
                placement: op_ref(k),
26531×
            });
26541×
        }
2655114×
        if path.contains(".oxy-conflict-") || expected.is_conflicted() {
26567×
            self.resolves = true;
2657107×
        }
2658114×
        self.statuses.push(PathStatus {
2659114×
            path: path.to_string(),
2660114×
            status: ChangeStatus::Removed,
2661114×
        });
2662114×
    }
2663
266413006×
    fn update_path(
266513006×
        &mut self,
266613006×
        repo: &Repo,
266713006×
        path: &str,
266813006×
        e: &FsEntry,
266913006×
        expected: &crate::state::FileState,
267013006×
    ) -> Result<()> {
267113006×
        if expected.kind != e.kind {
26721×
            self.remove_path(path, expected);
26731×
            self.statuses.pop();
26741×
            self.add_path(repo, path, e)?;
26751×
            self.statuses.pop();
26761×
            self.statuses.push(PathStatus {
26771×
                path: path.to_string(),
26781×
                status: ChangeStatus::Modified,
26791×
            });
26801×
            return Ok(());
268113005×
        }
268213005×
        let entry = &self.base_snapshot.tree.entries[path];
268313005×
        let node = expected.node;
268413005×
        let mode_atom = entry.mode_atom.map(op_ref);
268513005×
        if e.unchanged {
2686
            // Known equal to the base's unconflicted rendering (spec
2687
            // §12.3); only the executable bit can differ.
26884243×
            if e.exec != expected.mode.exec {
26893×
                if let Some(old) = mode_atom {
26903×
                    self.tree_ops.push(TreeOp::SetMode {
26913×
                        node,
26923×
                        old,
26933×
                        mode: Mode {
26943×
                            exec: e.exec,
26953×
                            opaque: false,
26963×
                        },
26973×
                    });
26983×
                    self.statuses.push(PathStatus {
26993×
                        path: path.to_string(),
27003×
                        status: ChangeStatus::ModeChanged,
27013×
                    });
27023×
                }
27034240×
            }
27044243×
            return Ok(());
27058762×
        }
27068762×
        let mut status: Option<ChangeStatus> = None;
27078762×
        let wants_opaque = self.opaque_for(path, e);
27088762×
        let nocompress = self.attrs.lookup(path).nocompress;
27098762×
        let disk_text = self.stored_text(path, &e.content);
27108762×
        match &expected.content {
27110×
            FileContent::Dir => {}
2712
            FileContent::Text {
27138496×
                bytes,
27148496×
                materialized,
2715
            } => {
27168496×
                if materialized.is_conflicted() {
271742×
                    if bytes == &*disk_text {
27186×
                        return Ok(());
271936×
                    }
272036×
                    let regions = self.base.conflict_regions(&node);
272136×
                    let plain: Vec<&[u8]> =
272281×
                        regions.plain.iter().map(|(_, l)| l.as_slice()).collect();
272336×
                    if has_own_conflict_markers(&e.content, bytes, &plain) {
27245×
                        self.statuses.push(PathStatus {
27255×
                            path: path.to_string(),
27265×
                            status: ChangeStatus::ConflictEdited,
27275×
                        });
27285×
                        return Ok(());
272931×
                    }
2730
                    // Resolution (spec §9.6): diff against the unconflicted lines
2731
                    // with each region as a gap, then retire every region atom.
2732
                    // Whatever the author kept from a region is re-inserted as
2733
                    // new atoms, which leaves the graph totally ordered.
273431×
                    let mut edits = text_edits(node, &regions.plain, &disk_text);
273531×
                    if !regions.region_atoms.is_empty() {
273631×
                        edits.insert(
273731×
                            0,
273831×
                            Edit::Delete {
273931×
                                node,
274031×
                                atoms: ranges(&regions.region_atoms),
274131×
                            },
274231×
                        );
274331×
                    }
274431×
                    self.edits.extend(edits);
274531×
                    self.contributors.extend(regions.contributors);
274631×
                    self.resolves = true;
274731×
                    if e.exec != expected.mode.exec {
27480×
                        if let Some(old) = mode_atom {
27490×
                            self.tree_ops.push(TreeOp::SetMode {
27500×
                                node,
27510×
                                old,
27520×
                                mode: Mode {
27530×
                                    exec: e.exec,
27540×
                                    opaque: false,
27550×
                                },
27560×
                            });
27570×
                        }
275831×
                    }
275931×
                    self.statuses.push(PathStatus {
276031×
                        path: path.to_string(),
276131×
                        status: ChangeStatus::Resolved,
276231×
                    });
276331×
                    return Ok(());
27648454×
                }
27658454×
                if wants_opaque {
2766
                    // Text → opaque (spec §7.5), by content or by attribute.
27672×
                    if let Some(old) = mode_atom {
27682×
                        self.tree_ops.push(TreeOp::SetMode {
27692×
                            node,
27702×
                            old,
27712×
                            mode: Mode {
27722×
                                exec: e.exec,
27732×
                                opaque: true,
27742×
                            },
27752×
                        });
27762×
                    }
27772×
                    let live: Vec<_> = repo_live_keys(self.base, &node);
27782×
                    if !live.is_empty() {
27792×
                        self.edits.push(Edit::Delete {
27802×
                            node,
27812×
                            atoms: ranges(&live),
27822×
                        });
27832×
                    }
27842×
                    let blob = self.blob_of(repo, path, e, nocompress)?;
27852×
                    self.edits.push(Edit::Replace {
27862×
                        node,
27872×
                        old: None,
27882×
                        new: Some(blob),
27892×
                    });
27902×
                    status = Some(ChangeStatus::Modified);
27918452×
                } else if bytes != &*disk_text {
2792857×
                    let mut laps = crate::timing::Laps::start();
2793
                    // The base's rendering holds its live atoms in order,
2794
                    // one per line (it is not conflicted here).
2795857×
                    let edits = match self.diffs.remove(path) {
279680×
                        Some(edits) => edits,
2797
                        None => {
2798777×
                            let keys = materialized.live_atoms();
2799777×
                            let lines = crate::diff::split_lines(bytes);
2800777×
                            if keys.len() == lines.len() {
2801777×
                                crate::diff::text_edits_of(node, &keys, &lines, &disk_text)
2802
                            } else {
28030×
                                text_edits(node, &self.base.live_lines(&node), &disk_text)
2804
                            }
2805
                        }
2806
                    };
2807857×
                    laps.lap("build: text diff");
2808857×
                    if !edits.is_empty() {
2809857×
                        self.edits.extend(edits);
2810857×
                        status = Some(ChangeStatus::Modified);
2811857×
                    }
28127595×
                }
28138454×
                let switched_to_opaque = wants_opaque;
28148454×
                if !switched_to_opaque && e.exec != expected.mode.exec {
28154×
                    if let Some(old) = mode_atom {
28164×
                        self.tree_ops.push(TreeOp::SetMode {
28174×
                            node,
28184×
                            old,
28194×
                            mode: Mode {
28204×
                                exec: e.exec,
28214×
                                opaque: false,
28224×
                            },
28234×
                        });
28244×
                        status.get_or_insert(ChangeStatus::ModeChanged);
28254×
                    }
28268450×
                }
2827
            }
2828266×
            FileContent::Opaque { blobs } => {
2829266×
                let new_ref = e.blob.unwrap_or_else(|| Repo::blob_ref(&e.content));
2830266×
                if e.kind == NodeKind::File && wants_opaque {
2831213×
                    // Unchanged or replaced, the file stays opaque: remember its blob.
2832213×
                    self.blobs.insert(path.to_string(), new_ref);
2833213×
                }
2834266×
                if blobs.len() > 1 && self.resolve.contains(path) && e.kind == expected.kind {
2835
                    // Settle the replace conflict (spec §9.3): replace every
2836
                    // live candidate with the chosen blob, depending on each
2837
                    // change that made one live, so all are superseded.
28385×
                    let chosen = self.blob_of(repo, path, e, nocompress)?;
283910×
                    for b in blobs {
284010×
                        self.edits.push(Edit::Replace {
284110×
                            node,
284210×
                            old: Some(*b),
284310×
                            new: Some(chosen),
284410×
                        });
284510×
                    }
28465×
                    self.contributors
28475×
                        .extend(self.base.blob_contributors(&node, blobs));
28485×
                    self.resolves = true;
28495×
                    self.statuses.push(PathStatus {
28505×
                        path: path.to_string(),
28515×
                        status: ChangeStatus::Resolved,
28525×
                    });
28535×
                    return Ok(());
2854261×
                }
2855261×
                if blobs.len() > 1 {
28566×
                    if !blobs.contains(&new_ref) {
28574×
                        self.statuses.push(PathStatus {
28584×
                            path: path.to_string(),
28594×
                            status: ChangeStatus::ConflictEdited,
28604×
                        });
28614×
                    }
28626×
                    return Ok(());
2863255×
                }
2864255×
                let current = blobs.first().copied();
2865255×
                if current != Some(new_ref) {
286644×
                    if e.kind == NodeKind::File && !wants_opaque {
2867
                        // Opaque → text (spec §7.5).
28682×
                        if let Some(old) = mode_atom {
28692×
                            self.tree_ops.push(TreeOp::SetMode {
28702×
                                node,
28712×
                                old,
28722×
                                mode: Mode {
28732×
                                    exec: e.exec,
28742×
                                    opaque: false,
28752×
                                },
28762×
                            });
28772×
                        }
28782×
                        self.edits.push(Edit::Replace {
28792×
                            node,
28802×
                            old: current,
28812×
                            new: None,
28822×
                        });
28832×
                        if !e.content.is_empty() {
28842×
                            self.edits.push(Edit::Insert {
28852×
                                node,
28862×
                                after: crate::objects::AtomRef::Start,
28872×
                                before: crate::objects::AtomRef::End,
28882×
                                lines: crate::lines::Lines::split(&e.content),
28892×
                            });
28902×
                        }
2891
                    } else {
289242×
                        let blob = self.blob_of(repo, path, e, nocompress)?;
289342×
                        self.edits.push(Edit::Replace {
289442×
                            node,
289542×
                            old: current,
289642×
                            new: Some(blob),
289742×
                        });
2898
                        // New contents and a new executable bit at once: the
2899
                        // bit was dropped (VS Code's inno_updater.exe,
2900
                        // 2018-02-28, lost +x for 49 commits; oxygen#87).
290142×
                        if e.kind == NodeKind::File && e.exec != expected.mode.exec {
29022×
                            if let Some(old) = mode_atom {
29032×
                                self.tree_ops.push(TreeOp::SetMode {
29042×
                                    node,
29052×
                                    old,
29062×
                                    mode: Mode {
29072×
                                        exec: e.exec,
29082×
                                        opaque: true,
29092×
                                    },
29102×
                                });
29112×
                            }
291240×
                        }
2913
                    }
291444×
                    status = Some(ChangeStatus::Modified);
2915211×
                } else if e.kind == NodeKind::File && e.exec != expected.mode.exec {
29160×
                    if let Some(old) = mode_atom {
29170×
                        self.tree_ops.push(TreeOp::SetMode {
29180×
                            node,
29190×
                            old,
29200×
                            mode: Mode {
29210×
                                exec: e.exec,
29220×
                                opaque: true,
29230×
                            },
29240×
                        });
29250×
                        status = Some(ChangeStatus::ModeChanged);
29260×
                    }
2927211×
                }
2928
            }
2929
        }
29308709×
        if let Some(s) = status {
2931907×
            self.statuses.push(PathStatus {
2932907×
                path: path.to_string(),
2933907×
                status: s,
2934907×
            });
29357802×
        }
29368709×
        Ok(())
293713006×
    }
2938
}
2939
29402×
fn repo_live_keys(base: &State, node: &NodeId) -> Vec<crate::graph::AtomKey> {
29412×
    base.live_lines(node).into_iter().map(|(k, _)| k).collect()
29422×
}
2943
2944
/// The changes a change's scope references (spec §8.1): introducers of every
2945
/// atom, placement, and mode it touches, and of every node it operates on.
29462345×
pub fn referenced_changes(change: &Change, base: &State) -> BTreeSet<ChangeHash> {
29472345×
    let mut out = BTreeSet::new();
29482345×
    let opref = |r: &OpRef, out: &mut BTreeSet<ChangeHash>| {
2949199×
        if !r.change.is_zero() {
2950199×
            out.insert(r.change);
2951199×
        }
2952199×
    };
29532345×
    let mut nodes: Vec<NodeId> = Vec::new();
29546742×
    for op in &change.tree_ops {
29556742×
        match op {
29566543×
            TreeOp::AddNode { parent, .. } => nodes.push(*parent),
2957150×
            TreeOp::RemoveNode { node, placement } => {
2958150×
                nodes.push(*node);
2959150×
                opref(placement, &mut out);
2960150×
            }
2961
            TreeOp::Move {
296237×
                node, old, parent, ..
296337×
            } => {
296437×
                nodes.push(*node);
296537×
                nodes.push(*parent);
296637×
                opref(old, &mut out);
296737×
            }
296812×
            TreeOp::SetMode { node, old, .. } => {
296912×
                nodes.push(*node);
297012×
                opref(old, &mut out);
297112×
            }
2972
        }
2973
    }
29748458×
    for e in &change.edits {
29758458×
        nodes.push(e.node());
2976184×
        match e {
29777689×
            Edit::Insert { after, before, .. } => {
297815378×
                for r in [after, before] {
297915378×
                    if let crate::objects::AtomRef::Atom { change, .. } = r {
29802316×
                        if !change.is_zero() {
29812313×
                            out.insert(*change);
29822313×
                        }
298313062×
                    }
2984
                }
2985
            }
2986585×
            Edit::Delete { atoms, .. } => {
2987
                // Deleting an atom also depends on whoever inserted the live
2988
                // atoms right after it: the author saw those insertions, and
2989
                // without the dependency spec §9.1 would call the deletion
2990
                // concurrent with them (a delete/insert conflict).
2991585×
                let graph = base.file(&e.node());
29921149×
                for r in atoms {
29931149×
                    if !r.change.is_zero() {
29941148×
                        out.insert(r.change);
29951148×
                    }
29961149×
                    if let Some(g) = graph {
29971184×
                        for i in r.from..r.to {
29981184×
                            out.extend(
29991184×
                                g.live_successor_changes(&(r.change, i))
30001184×
                                    .into_iter()
30011184×
                                    .filter(|c| !c.is_zero()),
3002
                            );
3003
                        }
30040×
                    }
3005
                }
3006
            }
3007
            // Replacing a blob depends on the change that made it current,
3008
            // as deleting a line depends on the line's introducer.
3009
            Edit::Replace {
301059×
                node,
301159×
                old: Some(old),
3012
                ..
3013
            } => {
301459×
                out.extend(
301559×
                    base.live_replaces(node)
301659×
                        .into_iter()
301776×
                        .filter(|(c, b)| b == old && !c.is_zero())
301859×
                        .map(|(c, _)| c),
3019
                );
3020
            }
3021125×
            Edit::Replace { .. } => {}
3022
        }
3023
    }
302415237×
    for n in nodes {
302515237×
        if let Some(h) = base.tree().introducer(&n) {
30262377×
            out.insert(h);
302712860×
        }
3028
    }
30292345×
    out
30302345×
}
3031
3032
/// Paths of the nodes a change adds on top of `base_snapshot`.
30331473×
pub fn added_node_paths(
30341473×
    change: &Change,
30351473×
    base_snapshot: &Snapshot,
30361473×
) -> HashMap<String, (NodeId, NodeKind)> {
30371473×
    let by_node = base_snapshot.tree.by_node();
30381473×
    let mut new_names: HashMap<NodeId, (NodeId, String, NodeKind)> = HashMap::new();
30391473×
    for op in &change.tree_ops {
3040
        if let TreeOp::AddNode {
304194×
            node,
304294×
            parent,
304394×
            name,
304494×
            kind,
3045
            ..
3046126×
        } = op
304794×
        {
304894×
            new_names.insert(*node, (*parent, name.clone(), *kind));
304994×
        }
3050
    }
30511473×
    let mut out = HashMap::new();
30521473×
    for (node, (_, _, kind)) in &new_names {
305394×
        if let Some(path) = path_of_node(node, &by_node, &new_names) {
305494×
            out.insert(path, (*node, *kind));
305594×
        }
3056
    }
30571473×
    out
30581473×
}
3059
3060
/// Whether `op` retires a node `base_snapshot` shows as one with another
3061
/// (spec §9.2): part of touching that node, never a removal the user made.
306237×
fn is_unified_retirement(op: &TreeOp, base_snapshot: &Snapshot) -> bool {
30638×
    matches!(op, TreeOp::RemoveNode { node, .. } if base_snapshot.tree.unified.contains_key(node))
306437×
}
3065
3066229×
fn path_of_node(
3067229×
    n: &NodeId,
3068229×
    by_node: &HashMap<NodeId, &crate::tree::TreeEntry>,
3069229×
    new_names: &HashMap<NodeId, (NodeId, String, NodeKind)>,
3070229×
) -> Option<String> {
3071229×
    if let Some(e) = by_node.get(n) {
307269×
        return Some(e.path.clone());
3073160×
    }
3074160×
    let mut parts = Vec::new();
3075160×
    let mut cur = *n;
3076
    loop {
3077316×
        if cur.is_root() {
3078143×
            break;
3079173×
        }
3080173×
        if let Some(e) = by_node.get(&cur) {
30810×
            if !e.path.is_empty() {
30820×
                parts.push(e.path.clone());
30830×
            }
30840×
            break;
3085173×
        }
3086173×
        let (parent, name, _) = new_names.get(&cur)?;
3087156×
        parts.push(name.clone());
3088156×
        cur = *parent;
3089
    }
3090143×
    parts.reverse();
3091143×
    Some(parts.join("/"))
3092229×
}
3093
3094
/// Render a change's operations with line content, using `base` for deleted lines.
309533×
pub fn render_change(change: &Change, base: &State, base_snapshot: &Snapshot) -> String {
309633×
    let by_node = base_snapshot.tree.by_node();
309733×
    let mut new_names: HashMap<NodeId, (NodeId, String, NodeKind)> = HashMap::new();
309833×
    for op in &change.tree_ops {
3099
        if let TreeOp::AddNode {
310016×
            node,
310116×
            parent,
310216×
            name,
310316×
            kind,
3104
            ..
310524×
        } = op
310616×
        {
310716×
            new_names.insert(*node, (*parent, name.clone(), *kind));
310816×
        }
3109
    }
311073×
    let path_of = |n: &NodeId| -> String {
311173×
        path_of_node(n, &by_node, &new_names).unwrap_or_else(|| format!("<node {}>", n.short(8)))
311273×
    };
3113
311433×
    let mut out = String::new();
311533×
    for op in change
311633×
        .tree_ops
311733×
        .iter()
311833×
        .filter(|o| !is_unified_retirement(o, base_snapshot))
3119
    {
312023×
        match op {
3121
            TreeOp::AddNode {
312216×
                node, kind, mode, ..
3123
            } => {
312416×
                out.push_str(&format!(
3125
                    "A {} ({:?}{}{})\n",
312616×
                    path_of(node),
3127
                    kind,
312816×
                    if mode.exec { ", exec" } else { "" },
312916×
                    if mode.opaque { ", opaque" } else { "" }
3130
                ));
3131
            }
31325×
            TreeOp::RemoveNode { node, .. } => out.push_str(&format!("D {}\n", path_of(node))),
3133
            TreeOp::Move {
31342×
                node, parent, name, ..
3135
            } => {
31362×
                let to = if parent.is_root() {
31370×
                    name.clone()
3138
                } else {
31392×
                    format!("{}/{name}", path_of(parent))
3140
                };
31412×
                out.push_str(&format!("R {} -> {to}\n", path_of(node)))
3142
            }
31430×
            TreeOp::SetMode { node, mode, .. } => {
31440×
                out.push_str(&format!(
31450×
                    "M {} mode: exec={} opaque={}\n",
31460×
                    path_of(node),
31470×
                    mode.exec,
31480×
                    mode.opaque
31490×
                ));
31500×
            }
3151
        }
3152
    }
3153
    // Every other file the change edits is modified: the summary names
3154
    // every path it touches, not only those with a tree operation.
315533×
    let with_op: HashSet<NodeId> = change.tree_ops.iter().map(|o| o.node()).collect();
315633×
    let mut listed: HashSet<NodeId> = HashSet::new();
315736×
    for e in &change.edits {
315836×
        let n = e.node();
315936×
        if !with_op.contains(&n) && listed.insert(n) {
316021×
            out.push_str(&format!("M {}\n", path_of(&n)));
316121×
        }
3162
    }
316333×
    let mut last_node: Option<NodeId> = None;
316436×
    for e in &change.edits {
316536×
        let n = e.node();
316636×
        if last_node != Some(n) {
316727×
            out.push_str(&format!("--- {}\n", path_of(&n)));
316827×
            last_node = Some(n);
316927×
        }
317036×
        match e {
317127×
            Edit::Insert { lines, .. } => {
317232×
                for l in lines.iter() {
317332×
                    out.push('+');
317432×
                    out.push_str(&String::from_utf8_lossy(l));
317532×
                    if !l.ends_with(b"\n") {
31760×
                        out.push('\n');
317732×
                    }
3178
                }
3179
            }
31808×
            Edit::Delete { atoms, .. } => {
31818×
                for r in atoms {
31828×
                    for i in r.from..r.to {
31838×
                        let content = base
31848×
                            .file(&n)
31858×
                            .and_then(|g| g.content(&(r.change, i)))
31868×
                            .unwrap_or(b"<unknown>\n");
31878×
                        out.push('-');
31888×
                        out.push_str(&String::from_utf8_lossy(content));
31898×
                        if !content.ends_with(b"\n") {
31900×
                            out.push('\n');
31918×
                        }
3192
                    }
3193
                }
3194
            }
31951×
            Edit::Replace { old, new, .. } => {
31961×
                out.push_str(&format!(
3197
                    "  opaque content {} -> {}\n",
31981×
                    old.map(|o| o.short(12)).unwrap_or_else(|| "none".into()),
31991×
                    new.map(|o| o.short(12)).unwrap_or_else(|| "none".into())
3200
                ));
3201
            }
3202
        }
3203
    }
320433×
    out
320533×
}
3206
3207
/// Pair removed files with added files of the same kind whose contents are
3208
/// at least `RENAME_THRESHOLD` percent alike, best matches first. Beyond
3209
/// `RENAME_LIMIT` candidate pairs only identical contents are paired.
3210
const RENAME_THRESHOLD: u32 = 50;
3211
const RENAME_LIMIT: usize = 10_000;
3212
3213
/// How a change is built beyond its entries: for a Git import, the seed
3214
/// its new nodes' identifiers derive from; and, when it is built from part
3215
/// of the tree, whether the new tree has anything under a directory.
3216
#[derive(Default)]
3217
struct Scope<'a> {
3218
    seed: Option<[u8; 32]>,
3219
    dir_needed: Option<&'a dyn Fn(&str) -> bool>,
3220
}
3221
32222289×
fn detect_renames(
32232289×
    base_snapshot: &Snapshot,
32242289×
    fs_entries: &BTreeMap<String, FsEntry>,
32252289×
    in_scope: impl Fn(&str) -> bool,
32262289×
) -> Vec<(String, String)> {
32272289×
    let removed: Vec<(&String, &crate::state::FileState)> = base_snapshot
32282289×
        .files
32292289×
        .iter()
323013528×
        .filter(|(p, f)| {
323113528×
            f.kind != NodeKind::Dir
323213104×
                && !fs_entries.contains_key(*p)
3233133×
                && in_scope(p)
3234123×
                && !f.is_conflicted()
323513528×
        })
32362289×
        .collect();
32372289×
    let added: Vec<(&String, &FsEntry)> = fs_entries
32382289×
        .iter()
323919178×
        .filter(|(p, e)| e.kind != NodeKind::Dir && !base_snapshot.files.contains_key(*p))
32402289×
        .collect();
32412289×
    if removed.is_empty() || added.is_empty() {
32422228×
        return vec![];
324361×
    }
324461×
    let exact_only = removed.len() * added.len() > RENAME_LIMIT;
324575×
    let old_content = |f: &crate::state::FileState| -> Option<Vec<u8>> {
324675×
        match &f.content {
324771×
            FileContent::Text { bytes, .. } => Some(bytes.clone()),
32484×
            _ => None,
3249
        }
325075×
    };
325161×
    let mut scored: Vec<(u32, usize, usize)> = Vec::new();
325275×
    for (ri, (_, f)) in removed.iter().enumerate() {
325375×
        let old = old_content(f);
325475×
        let old_blob = match &f.content {
32554×
            FileContent::Opaque { blobs } if blobs.len() == 1 => Some(blobs[0]),
325671×
            _ => None,
3257
        };
325894×
        for (ai, (_, e)) in added.iter().enumerate() {
325994×
            if e.kind != f.kind {
32600×
                continue;
326194×
            }
326294×
            let score = match (&old, old_blob) {
326384×
                (Some(o), _) => {
326484×
                    if exact_only {
32650×
                        if *o == *e.content {
32660×
                            100
3267
                        } else {
32680×
                            0
3269
                        }
3270
                    } else {
327184×
                        similarity(o, &e.content)
3272
                    }
3273
                }
327410×
                (None, Some(b)) if e.blob.unwrap_or_else(|| Repo::blob_ref(&e.content)) == b => 100,
32757×
                _ => 0,
3276
            };
327794×
            if score >= RENAME_THRESHOLD {
327841×
                scored.push((score, ri, ai));
327953×
            }
3280
        }
3281
    }
328261×
    scored.sort_by(|a, b| {
32839×
        b.0.cmp(&a.0)
32849×
            .then(removed[a.1].0.cmp(removed[b.1].0))
32859×
            .then(added[a.2].0.cmp(added[b.2].0))
32869×
    });
328761×
    let mut used_r = vec![false; removed.len()];
328861×
    let mut used_a = vec![false; added.len()];
328961×
    let mut out = Vec::new();
329061×
    for (_, ri, ai) in scored {
329141×
        if used_r[ri] || used_a[ai] {
32926×
            continue;
329335×
        }
329435×
        used_r[ri] = true;
329535×
        used_a[ai] = true;
329635×
        out.push((removed[ri].0.clone(), added[ai].0.clone()));
3297
    }
329861×
    out
32992289×
}
3300
3301
/// Percentage of the larger file's bytes found in lines the two share
3302
/// (multiset intersection of lines), like Git's similarity index.
330388×
pub fn similarity(a: &[u8], b: &[u8]) -> u32 {
330488×
    if a == b {
330525×
        return 100;
330663×
    }
330763×
    if a.is_empty() || b.is_empty() {
33083×
        return 0;
330960×
    }
331060×
    let mut counts: HashMap<&[u8], usize> = HashMap::new();
3311116×
    for l in split_lines(a) {
3312116×
        *counts.entry(l).or_default() += 1;
3313116×
    }
331460×
    let mut shared = 0usize;
3315112×
    for l in split_lines(b) {
3316112×
        if let Some(n) = counts.get_mut(l) {
331742×
            if *n > 0 {
331842×
                *n -= 1;
331942×
                shared += l.len();
332042×
            }
332170×
        }
3322
    }
332360×
    (shared * 100 / a.len().max(b.len())) as u32
332488×
}
3325
3326
#[cfg(test)]
3327
mod join_tests {
3328
    use super::*;
3329
3330
    #[test]
33311×
    fn missing_from_finds_what_the_other_lacks() {
33321×
        let a: BTreeMap<String, u8> = [("a", 1), ("b", 2), ("c/d", 3), ("e", 4)]
33331×
            .into_iter()
33344×
            .map(|(k, v)| (k.to_string(), v))
33351×
            .collect();
33361×
        let b: BTreeMap<String, ()> = [("0", ()), ("b", ()), ("c", ()), ("e", ())]
33371×
            .into_iter()
33384×
            .map(|(k, v)| (k.to_string(), v))
33391×
            .collect();
33401×
        let got: Vec<&str> = missing_from(&a, &b)
33411×
            .iter()
33422×
            .map(|(k, _)| k.as_str())
33431×
            .collect();
33441×
        assert_eq!(got, vec!["a", "c/d"]);
33451×
    }
3346
3347
    #[test]
33481×
    fn join_pairs_every_key_in_order() {
33491×
        let a: BTreeMap<String, u8> = [("a", 1), ("b/c", 2), ("d", 3)]
33501×
            .into_iter()
33513×
            .map(|(k, v)| (k.to_string(), v))
33521×
            .collect();
33531×
        let b: BTreeMap<String, char> = [("b", 'x'), ("b/c", 'y'), ("e", 'z')]
33541×
            .into_iter()
33553×
            .map(|(k, v)| (k.to_string(), v))
33561×
            .collect();
33571×
        let got: Vec<(String, Option<u8>, Option<char>)> = join(&a, &b)
33585×
            .map(|(k, x, y)| (k.clone(), x.copied(), y.copied()))
33591×
            .collect();
33601×
        let want = vec![
33611×
            ("a".to_string(), Some(1), None),
33621×
            ("b".to_string(), None, Some('x')),
33631×
            ("b/c".to_string(), Some(2), Some('y')),
33641×
            ("d".to_string(), Some(3), None),
33651×
            ("e".to_string(), None, Some('z')),
3366
        ];
33671×
        assert_eq!(got, want);
33681×
    }
3369
}