OXYGENHUB

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

2527 of 2769 lines run, 334 of 461 functions · run #386 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.
3442×
pub fn has_own_conflict_markers(content: &[u8], materialized: &[u8], plain: &[&[u8]]) -> bool {
35548×
    let line = |l: &[u8]| -> Vec<u8> {
36548×
        let l = l.strip_suffix(b"\n").unwrap_or(l);
37548×
        l.strip_suffix(b"\r").unwrap_or(l).to_vec()
38548×
    };
39305×
    let marker = |l: &[u8]| {
40305×
        l.starts_with(b"<<<<<<< oxy conflict")
41259×
            || l.starts_with(b"======= oxy conflict")
42213×
            || l.starts_with(b">>>>>>> oxy conflict")
43305×
    };
4493×
    let unconflicted: HashSet<Vec<u8>> = plain.iter().map(|l| line(l)).collect();
4542×
    let own: HashSet<Vec<u8>> = split_lines(materialized)
4642×
        .into_iter()
4742×
        .map(line)
48305×
        .filter(|l| marker(l) && !unconflicted.contains(l))
4942×
        .collect();
5042×
    !own.is_empty()
5142×
        && split_lines(content)
5242×
            .into_iter()
53150×
            .any(|l| own.contains(&line(l)))
5442×
}
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
114
/// What `oxy resolve --both` did to one file (oxygen#121).
115
#[derive(Debug, Default, Clone, PartialEq, Eq)]
116
pub struct KeptBoth {
117
    pub path: String,
118
    /// The conflicts settled by keeping every side, by number.
119
    pub settled: Vec<usize>,
120
    /// The conflicts that keep their markers, by number, and why.
121
    pub left: Vec<(usize, &'static str)>,
122
}
123
124
/// `text` (a working-copy file) with the marker block of each conflict that
125
/// `sides` (from [`State::both_sides`]) says keeping both settles replaced
126
/// by its sides' lines; the conflicts settled, and those left and why.
1275×
pub(crate) fn keep_both_text(
1285×
    text: &[u8],
1295×
    sides: &[Option<Vec<Vec<u8>>>],
1305×
    reverse: bool,
1315×
) -> (Vec<u8>, Vec<usize>, Vec<(usize, &'static str)>) {
132
    // A side as the markers hold it: the renderer ends each with a newline.
13314×
    let with_newline = |s: &[u8]| {
13414×
        let mut s = s.to_vec();
13514×
        if !s.is_empty() && !s.ends_with(b"\n") {
1360×
            s.push(b'\n');
13714×
        }
13814×
        s
13914×
    };
140834×
    let lines: Vec<&[u8]> = text.split_inclusive(|&b| b == b'\n').collect();
1415×
    let (mut out, mut settled, mut left) = (Vec::new(), Vec::new(), Vec::new());
1425×
    let mut i = 0;
14320×
    while i < lines.len() {
14415×
        let Some((n, total)) = conflict_header(lines[i]) else {
14510×
            out.extend_from_slice(lines[i]);
14610×
            i += 1;
14710×
            continue;
148
        };
1495×
        let end = format!(">>>>>>> oxy conflict {n} of {total} end");
1505×
        let next_side = format!("======= oxy conflict {n} of {total}, side ");
1515×
        let Some(stop) =
15220×
            (i + 1..lines.len()).find(|&j| lines[j].trim_ascii_end() == end.as_bytes())
153
        else {
1540×
            left.push((n, "its end marker is missing; edit it by hand"));
1550×
            out.extend_from_slice(lines[i]);
1560×
            i += 1;
1570×
            continue;
158
        };
1595×
        let mut found: Vec<Vec<u8>> = vec![Vec::new()];
16015×
        for line in &lines[i + 1..stop] {
16115×
            if line.starts_with(next_side.as_bytes()) {
1625×
                found.push(Vec::new());
16310×
            } else {
16410×
                found.last_mut().unwrap().extend_from_slice(line);
16510×
            }
166
        }
1675×
        let wanted = match sides.get(n.wrapping_sub(1)) {
1685×
            _ if total != sides.len() => {
1690×
                Err("the markers are not the file's conflicts now; see `oxy status`")
170
            }
1714×
            Some(Some(w)) => Ok(w),
1721×
            _ => Err("both sides changed these lines; edit the markers"),
173
        };
1745×
        let keep = wanted.and_then(|w| {
1758×
            let mut a: Vec<Vec<u8>> = w.iter().map(|s| with_newline(s)).collect();
1764×
            let mut b = found.clone();
1774×
            a.sort();
1784×
            b.sort();
1794×
            if a == b {
1803×
                Ok(w)
181
            } else {
1821×
                Err("the lines between its markers were edited; finish it by hand")
183
            }
1844×
        });
1855×
        match keep {
1863×
            Ok(w) => {
1873×
                let order: Vec<&Vec<u8>> = if reverse {
1881×
                    w.iter().rev().collect()
189
                } else {
1902×
                    w.iter().collect()
191
                };
1926×
                for s in order {
1936×
                    out.extend_from_slice(&with_newline(s));
1946×
                }
1953×
                settled.push(n);
196
            }
1972×
            Err(why) => {
1982×
                left.push((n, why));
19910×
                for line in &lines[i..=stop] {
20010×
                    out.extend_from_slice(line);
20110×
                }
202
            }
203
        }
2045×
        i = stop + 1;
205
    }
2065×
    (out, settled, left)
2075×
}
208
209
/// `(n, total)` from a conflict's opening marker (spec §9.5).
21015×
fn conflict_header(line: &[u8]) -> Option<(usize, usize)> {
21115×
    let rest = line.strip_prefix(b"<<<<<<< oxy conflict ")?;
2125×
    let rest = std::str::from_utf8(rest).ok()?;
2135×
    let (n, rest) = rest.split_once(" of ")?;
21410×
    let total = rest.split(|c: char| !c.is_ascii_digit()).next()?;
2155×
    Some((n.parse().ok()?, total.parse().ok()?))
21615×
}
217
21823550×
pub fn is_binary(content: &[u8]) -> bool {
21923550×
    content[..content.len().min(BINARY_SNIFF)].contains(&0)
22023550×
}
221
222
impl Repo {
223
    /// Diff the files on disk against `base` and build the operations of a
224
    /// change from `base` to the working directory. `reuse` maps paths to the
225
    /// NodeIds an earlier version of the same change assigned to new paths.
2263×
    pub(crate) fn build_against(
2273×
        &self,
2283×
        base: &State,
2293×
        base_snapshot: &Snapshot,
2303×
        reuse: HashMap<String, (NodeId, NodeKind)>,
2313×
    ) -> Result<BuiltChange> {
2323×
        let mut fs_entries =
2333×
            self.walk_working_copy_with(None, &Self::tracked_kinds(base_snapshot), None)?;
2343×
        self.platform_normalize(&mut fs_entries, base_snapshot);
2353×
        self.build_from_entries(base, base_snapshot, reuse, &fs_entries)
2363×
    }
237
238
    /// Read the working copy as the platform left it (spec §7.7): without
239
    /// executable bits a file keeps the bit it has in the base, and without
240
    /// symbolic links a plain file where the base has a symlink is that
241
    /// symlink, written out as its target, not a new file.
2421492×
    fn platform_normalize(&self, entries: &mut BTreeMap<String, FsEntry>, base: &Snapshot) {
2431492×
        let p = self.platform;
2441492×
        if p.exec_bits && p.symlinks {
2451490×
            return;
2462×
        }
2474×
        for (path, e) in entries.iter_mut() {
2484×
            let Some(f) = base.files.get(path) else {
2490×
                continue;
250
            };
2514×
            if !p.symlinks && f.kind == NodeKind::Symlink && e.kind == NodeKind::File {
2522×
                e.kind = NodeKind::Symlink;
2532×
                e.exec = false;
2542×
            }
2554×
            if !p.exec_bits && f.kind == NodeKind::File && e.kind == NodeKind::File {
2562×
                e.exec = f.mode.exec;
2572×
            }
258
        }
2591492×
    }
260
261
    /// Like `build_against`, for files given in memory (imports).
2621207×
    pub(crate) fn build_from_entries(
2631207×
        &self,
2641207×
        base: &State,
2651207×
        base_snapshot: &Snapshot,
2661207×
        reuse: HashMap<String, (NodeId, NodeKind)>,
2671207×
        fs_entries: &BTreeMap<String, FsEntry>,
2681207×
    ) -> Result<BuiltChange> {
2691207×
        self.build_from_entries_resolving(base, base_snapshot, reuse, fs_entries, &HashSet::new())
2701207×
    }
271
272
    /// Like `build_from_entries`, settling the replace conflicts of the
273
    /// opaque files in `resolve` to their content (spec §9.3, §9.6): a
274
    /// caller that knows the user chose it, such as the hub's resolver. A
275
    /// snapshot never settles one on its own, since a checkout writes one
276
    /// candidate at the path.
2771225×
    pub(crate) fn build_from_entries_resolving(
2781225×
        &self,
2791225×
        base: &State,
2801225×
        base_snapshot: &Snapshot,
2811225×
        reuse: HashMap<String, (NodeId, NodeKind)>,
2821225×
        fs_entries: &BTreeMap<String, FsEntry>,
2831225×
        resolve: &HashSet<String>,
2841225×
    ) -> Result<BuiltChange> {
2851225×
        self.build_from_entries_with(
2861225×
            base,
2871225×
            base_snapshot,
2881225×
            reuse,
2891225×
            fs_entries,
2901225×
            resolve,
2911225×
            Scope::default(),
292
        )
2931225×
    }
294
295
    /// `build_from_entries` whose new nodes take identifiers derived from
296
    /// `seed` and their paths instead of random ones, so the same input
297
    /// always builds the same change (a Git import, spec §23).
298
    ///
299
    /// With `dir_needed`, the snapshot and entries hold only the paths the
300
    /// import touches (and the directories a removal may leave empty); a
301
    /// directory stays while `dir_needed` says the new tree has something
302
    /// under it.
30388×
    pub(crate) fn build_from_entries_seeded(
30488×
        &self,
30588×
        base: &State,
30688×
        base_snapshot: &Snapshot,
30788×
        fs_entries: &BTreeMap<String, FsEntry>,
30888×
        seed: [u8; 32],
30988×
        dir_needed: Option<&dyn Fn(&str) -> bool>,
31088×
    ) -> Result<BuiltChange> {
31188×
        self.build_from_entries_with(
31288×
            base,
31388×
            base_snapshot,
31488×
            HashMap::new(),
31588×
            fs_entries,
31688×
            &HashSet::new(),
31788×
            Scope {
31888×
                seed: Some(seed),
31988×
                dir_needed,
32088×
            },
321
        )
32288×
    }
323
324
    /// `build_from_entries` for a snapshot most of whose files are known
325
    /// unchanged (oxygen#41): only the paths that may differ are built
326
    /// (files read rather than known unchanged, base files gone from disk,
327
    /// and the directories those may leave empty), against a snapshot of
328
    /// just those, so a large tree with a few edits costs what they touch.
3291006×
    fn build_changed_only(
3301006×
        &self,
3311006×
        base: &State,
3321006×
        base_snapshot: &Snapshot,
3331006×
        reuse: HashMap<String, (NodeId, NodeKind)>,
3341006×
        fs_entries: &BTreeMap<String, FsEntry>,
3351006×
    ) -> Result<BuiltChange> {
3361006×
        let pick = crate::timing::phase("snapshot:   of which picking the changed");
337
        // A file known unchanged may still have changed mode: that alters
338
        // neither its size nor its time.
3391006×
        let changed: BTreeMap<String, FsEntry> = join(fs_entries, &base_snapshot.files)
34011205×
            .filter_map(|(p, e, f)| {
34111205×
                let e = e?;
34211077×
                (!e.unchanged || f.is_none_or(|f| f.kind != e.kind || f.mode.exec != e.exec))
34311077×
                    .then(|| (p.clone(), e.clone()))
34411205×
            })
3451006×
            .collect();
3461006×
        let mut files: BTreeMap<String, crate::state::FileState> = BTreeMap::new();
3476846×
        for p in changed.keys() {
3486846×
            if let Some(f) = base_snapshot.files.get(p) {
3493771×
                files.insert(p.clone(), f.clone());
3503771×
            }
351
        }
352
        // Paths the base has and the disk does not.
3531006×
        let gone = join(&base_snapshot.files, fs_entries)
35411205×
            .filter_map(|(p, f, e)| (e.is_none()).then_some((p, f?)));
3551006×
        for (p, f) in gone {
356128×
            if f.kind == NodeKind::Dir {
357100×
                continue;
35828×
            }
35928×
            files.insert(p.clone(), f.clone());
36028×
            let mut end = p.len();
36133×
            while let Some(i) = p[..end].rfind('/') {
3625×
                let dir = &p[..i];
3635×
                if files.contains_key(dir) {
3640×
                    break;
3655×
                }
3665×
                if let Some(d) = base_snapshot.files.get(dir) {
3675×
                    files.insert(dir.to_string(), d.clone());
3685×
                }
3695×
                end = i;
370
            }
371
        }
3721006×
        let part = Snapshot {
3731006×
            tree: base_snapshot.tree.clone(),
3741006×
            files,
3751006×
            unrendered: BTreeSet::new(),
3761006×
        };
3771006×
        drop(pick);
3781006×
        let _build = crate::timing::phase("snapshot:   of which building the change");
379
        // Whether anything on disk is under `dir`.
3801006×
        let dir_needed = |dir: &str| {
3815×
            let prefix = format!("{dir}/");
3825×
            fs_entries
3835×
                .range(prefix.clone()..)
3845×
                .next()
3855×
                .is_some_and(|(k, _)| k.starts_with(&prefix))
3865×
        };
3871006×
        self.build_from_entries_with(
3881006×
            base,
3891006×
            &part,
3901006×
            reuse,
3911006×
            &changed,
3921006×
            &HashSet::new(),
3931006×
            Scope {
3941006×
                seed: None,
3951006×
                dir_needed: Some(&dir_needed),
3961006×
            },
397
        )
3981006×
    }
399
4002319×
    fn build_from_entries_with(
4012319×
        &self,
4022319×
        base: &State,
4032319×
        base_snapshot: &Snapshot,
4042319×
        reuse: HashMap<String, (NodeId, NodeKind)>,
4052319×
        fs_entries: &BTreeMap<String, FsEntry>,
4062319×
        resolve: &HashSet<String>,
4072319×
        scope: Scope,
4082319×
    ) -> Result<BuiltChange> {
4092319×
        let Scope { seed, dir_needed } = scope;
4102319×
        let mut laps = crate::timing::Laps::start();
411
        // Attributes come from the files being committed, so a new
412
        // `.oxyattributes` applies to the same change that adds it.
4132319×
        let attrs = crate::attributes::Attributes::from_files(
4142319×
            fs_entries
4152319×
                .iter()
41619202×
                .filter(|(p, _)| p.as_str() == ".oxyattributes" || p.ends_with("/.oxyattributes"))
4172319×
                .map(|(p, e)| (p.as_str(), e.content.as_slice())),
418
        );
4192319×
        let mut b = ChangeBuilder::new(base, base_snapshot, reuse).with_attributes(attrs);
4202319×
        b.resolve = resolve.clone();
4212319×
        b.node_seed = seed;
4222319×
        laps.lap("build: builder");
423
        // Rename detection (spec §7.1, §23): a removed file and an added file
424
        // of the same kind whose contents are at least half alike become one
425
        // move of the same node, so identity survives across the rename.
4262319×
        let renames = detect_renames(base_snapshot, fs_entries, |p| self.in_scope(p));
4272319×
        let renamed_from: HashMap<&str, &str> = renames
4282319×
            .iter()
4292319×
            .map(|(old, new)| (new.as_str(), old.as_str()))
4302319×
            .collect();
4312319×
        let renamed_to: HashMap<&str, &str> = renames
4322319×
            .iter()
4332319×
            .map(|(old, new)| (old.as_str(), new.as_str()))
4342319×
            .collect();
4352319×
        laps.lap("build: renames");
4362319×
        b.diff_in_parallel(fs_entries);
4372319×
        laps.lap("build: diffs");
43819202×
        for (path, fs_entry) in fs_entries {
43919202×
            match base_snapshot.files.get(path) {
4406217×
                None => match renamed_from.get(path.as_str()) {
44135×
                    Some(old) => {
44235×
                        b.move_path(self, old, path, fs_entry, &base_snapshot.files[*old])?
443
                    }
4446182×
                    None => b.add_path(self, path, fs_entry)?,
445
                },
44612985×
                Some(expected) => b.update_path(self, path, fs_entry, expected)?,
447
            }
448
        }
4492319×
        laps.lap("build: paths");
450
        // A directory stays while anything under it exists or is out of
451
        // scope: the directories above each such path, gathered once.
4522319×
        let mut needed_dirs: HashSet<&str> = HashSet::new();
45319215×
        fn parents_of<'a>(p: &'a str, set: &mut HashSet<&'a str>) {
45419215×
            let mut end = p.len();
45519884×
            while let Some(i) = p[..end].rfind('/') {
45615451×
                if !set.insert(&p[..i]) {
45714782×
                    break;
458669×
                }
459669×
                end = i;
460
            }
46119215×
        }
46219202×
        for p in fs_entries.keys() {
46319202×
            parents_of(p, &mut needed_dirs);
46419202×
        }
46513544×
        for p in base_snapshot.files.keys() {
46613544×
            if !self.in_scope(p) {
46713×
                parents_of(p, &mut needed_dirs);
46813531×
            }
469
        }
47013544×
        for (path, expected) in &base_snapshot.files {
47113544×
            if fs_entries.contains_key(path)
472559×
                || !self.in_scope(path)
473546×
                || renamed_to.contains_key(path.as_str())
474
            {
47513033×
                continue;
476511×
            }
477511×
            let still_needed = expected.kind == NodeKind::Dir
478422×
                && match dir_needed {
47921×
                    Some(f) => f(path),
480401×
                    None => needed_dirs.contains(path.as_str()),
481
                };
482511×
            if !still_needed {
483115×
                b.remove_path(path, expected);
484396×
            }
485
        }
4862319×
        laps.lap("build: removals");
4872319×
        if seed.is_some() {
48888×
            b.retire_stray_placements();
4892231×
        }
4902319×
        b.retire_unified();
4912319×
        laps.lap("build: stray placements");
4922319×
        let mut statuses = b.statuses;
4935714×
        statuses.sort_by(|a, b| a.path.cmp(&b.path));
4942319×
        Ok(BuiltChange {
4952319×
            tree_ops: b.tree_ops,
4962319×
            edits: b.edits,
4972319×
            contributors: b.contributors.into_iter().collect(),
4982319×
            resolves: b.resolves,
4992319×
            statuses,
5002319×
            blobs: b.blobs,
5012319×
        })
5022319×
    }
503
504
    /// Store a change and, when `core.sign = change` and we are its author,
505
    /// sign it. A rewritten change by another author is stored unsigned: only
506
    /// its author (or a delegate) can vouch for it.
507796×
    pub(crate) fn store_signed(&self, change: &Change) -> Result<ChangeHash> {
508796×
        let ours = change.author == self.author();
509796×
        if self.config.sign_changes && ours && self.secret_key()?.is_none() {
5101×
            return fail("core.sign is \"change\" but no secret key is available for author.key");
511795×
        }
512795×
        let storing = crate::timing::phase("store: the change");
513795×
        let hash = self.store.put_change(change)?;
514795×
        drop(storing);
515795×
        if self.config.sign_changes && ours {
51643×
            let _t = crate::timing::phase("store: sign it");
51743×
            self.sign_change(&hash)?;
518752×
        }
519795×
        Ok(hash)
520796×
    }
521
5221496×
    fn resolutions_path(&self) -> PathBuf {
5231496×
        self.oxy
5241496×
            .join("workspaces")
5251496×
            .join(self.workspace.to_hex())
5261496×
            .join("resolve")
5271496×
    }
528
529
    /// The paths whose replace conflicts the user chose to settle with what
530
    /// the working copy holds there (`oxy resolve PATH`, spec §9.3).
5311492×
    pub fn resolutions(&self) -> Result<BTreeSet<String>> {
5321492×
        match fs::read_to_string(self.resolutions_path()) {
5335×
            Ok(text) => Ok(text
5345×
                .lines()
5355×
                .filter(|l| !l.is_empty())
5365×
                .map(String::from)
5375×
                .collect()),
5381487×
            Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(BTreeSet::new()),
5390×
            Err(e) => Err(e.into()),
540
        }
5411492×
    }
542
543
    /// Settle the replace conflicts at `paths` (a file's or a subrepo pin's,
544
    /// spec §9.3) with what the working copy holds there: the next snapshot
545
    /// replaces every live candidate with it. Refused for a path whose base
546
    /// has no replace conflict.
5473×
    pub fn choose_resolutions(&self, base: &Snapshot, paths: &[String]) -> Result<()> {
5483×
        for p in paths {
5493×
            if !has_replace_conflict(base, p) {
5501×
                return Err(RepoError::Msg(format!(
5511×
                    "{p} has no replace conflict to settle (a text file's conflict is settled by editing out its markers, or `oxy resolve --both {p}`)"
5521×
                )));
5532×
            }
554
        }
5552×
        let mut all = self.resolutions()?;
5562×
        all.extend(paths.iter().cloned());
5572×
        let text: String = all.iter().map(|p| format!("{p}\n")).collect();
5582×
        crate::durable::write_atomic(&self.resolutions_path(), text.as_bytes())?;
5592×
        Ok(())
5603×
    }
561
562
    /// Settle the adjacent-insertion conflicts of the text files at `paths`
563
    /// (oxygen#121) by keeping every side, earliest change first (latest
564
    /// first with `reverse`): each one's markers in the working copy give
565
    /// way to its sides' lines, and the next snapshot records the result.
566
    /// A conflict whose sides changed the same lines, or whose text between
567
    /// the markers was edited, keeps its markers. With no paths, every
568
    /// conflicted text file.
5693×
    pub fn keep_both(
5703×
        &self,
5713×
        snap: &SnapshotResult,
5723×
        paths: &[String],
5733×
        reverse: bool,
5743×
    ) -> Result<Vec<KeptBoth>> {
5753×
        let paths: Vec<String> = if paths.is_empty() {
5762×
            snap.base_snapshot
5772×
                .files
5782×
                .iter()
5792×
                .filter(|(_, f)| matches!(&f.content, FileContent::Text { materialized, .. } if materialized.is_conflicted()))
5802×
                .map(|(p, _)| p.clone())
5812×
                .collect()
582
        } else {
5831×
            paths.to_vec()
584
        };
5853×
        let mut out = Vec::new();
5863×
        for p in paths {
5873×
            let conflicted = match snap.base_snapshot.files.get(&p).map(|f| (f, &f.content)) {
5883×
                Some((f, FileContent::Text { materialized, .. }))
5893×
                    if materialized.is_conflicted() =>
590
                {
5913×
                    f
592
                }
5930×
                Some((_, FileContent::Opaque { blobs })) if blobs.len() > 1 => {
5940×
                    return Err(RepoError::Msg(format!(
5950×
                        "{p} has a replace conflict: keep one version with `oxy resolve {p}`"
5960×
                    )))
597
                }
598
                _ => {
5990×
                    return Err(RepoError::Msg(format!(
6000×
                        "{p} has no text conflict to settle"
6010×
                    )))
602
                }
603
            };
6043×
            let sides = snap.base.both_sides(&conflicted.node);
6053×
            let disk = self.root().join(&p);
6063×
            let text = fs::read(&disk)?;
6073×
            let (bytes, settled, left) = keep_both_text(&text, &sides, reverse);
6083×
            if !settled.is_empty() {
6092×
                fs::write(&disk, bytes)?;
6101×
            }
6113×
            out.push(KeptBoth {
6123×
                path: p,
6133×
                settled,
6143×
                left,
6153×
            });
616
        }
6173×
        Ok(out)
6183×
    }
619
620
    /// The chosen resolutions `base` still needs; the rest are forgotten.
6211489×
    fn resolutions_for(&self, base: &Snapshot) -> Result<HashSet<String>> {
6221489×
        let all = self.resolutions()?;
6231489×
        if all.is_empty() {
6241484×
            return Ok(HashSet::new());
6255×
        }
6265×
        let live: HashSet<String> = all
6275×
            .iter()
6285×
            .filter(|p| has_replace_conflict(base, p))
6295×
            .cloned()
6305×
            .collect();
6315×
        if live.is_empty() {
6322×
            match fs::remove_file(self.resolutions_path()) {
6332×
                Ok(()) => {}
6340×
                Err(e) if e.kind() == std::io::ErrorKind::NotFound => {}
6350×
                Err(e) => return Err(e.into()),
636
            }
6373×
        }
6385×
        Ok(live)
6391489×
    }
640
641
    /// Snapshot the working copy into the working-copy change (spec §12.3).
642
    /// The result carries the full base state and its whole rendering.
643481×
    pub fn snapshot(&self, command: &str) -> Result<SnapshotResult> {
644481×
        self.snapshot_as(command, false, false)
645481×
    }
646
647
    /// Snapshot the working copy as [`Repo::snapshot`] does, for commands
648
    /// that need its statuses, conflicts and base history, and the graphs
649
    /// of the files it changes: status, log, show, commit, diff, hunks and
650
    /// discard. Text files known unchanged since the last manifest are
651
    /// neither read nor rendered: the result's `base` is a history-only
652
    /// state without their graphs, and its `base_snapshot` lists them in
653
    /// `unrendered` with empty bytes. They are never conflicted, and no
654
    /// change the working copy makes touches them.
655469×
    pub fn snapshot_status(&self, command: &str) -> Result<SnapshotResult> {
656469×
        self.snapshot_as(command, true, false)
657469×
    }
658
659
    /// `snapshot_as`; `for_commit` writes the manifest even where a status
660
    /// would not bother (an edited file is read next time whatever it
661
    /// says), since after the commit that file is unchanged, and records no
662
    /// operation: the commit's own, recorded straight after, replaces the
663
    /// working copy, so the snapshot's would cost a durable write for
664
    /// nothing. Should the commit fail, the files are still on disk and the
665
    /// next snapshot finds them.
6661492×
    fn snapshot_as(
6671492×
        &self,
6681492×
        command: &str,
6691492×
        partial: bool,
6701492×
        for_commit: bool,
6711492×
    ) -> Result<SnapshotResult> {
6721492×
        let _lock = self.lock_snapshot()?;
6731492×
        let batch = self.store.begin_batch()?;
6741492×
        let result = self.snapshot_locked(command, partial, for_commit);
6751492×
        batch.finish()?;
6761492×
        result
6771492×
    }
678
6791492×
    fn snapshot_locked(
6801492×
        &self,
6811492×
        command: &str,
6821492×
        partial: bool,
6831492×
        for_commit: bool,
6841492×
    ) -> Result<SnapshotResult> {
6851492×
        let _all = crate::timing::phase("snapshot");
6861492×
        let (op_ref, op) = self.head_op()?;
6871492×
        let (old_hash, old_wc) = self.working_copy()?;
688
        // The base's history first: its graph keys say which files the
689
        // manifest already knows equal to it.
6901490×
        let mut base = {
6911490×
            let _t = crate::timing::phase("snapshot: load base history");
6921490×
            self.load_state_indexed(&old_wc.deps)?
693
        };
6941490×
        let view = {
6951490×
            let _t = crate::timing::phase("snapshot: tree view");
6961490×
            self.tree_view(&mut base)?
697
        };
6981490×
        let manifest = {
6991490×
            let _t = crate::timing::phase("snapshot: read manifest");
7001490×
            self.read_manifest()?.map(|(_, _, m)| m)
701
        };
7021490×
        let tracked: BTreeMap<String, (NodeKind, Option<ObjectRef>)> = {
7031490×
            let _t = crate::timing::phase("snapshot: tracked paths");
704
            // In the view's path order, so the map is built without searching.
7051490×
            view.entries
7061490×
                .iter()
7079678×
                .filter(|(_, e)| e.kind != NodeKind::Dir)
7089282×
                .map(|(p, e)| {
7099282×
                    let blob = if e.kind != NodeKind::File || e.mode.opaque {
710180×
                        base.live_blobs(&e.node).first().copied()
711
                    } else {
7129102×
                        None
713
                    };
7149282×
                    (p.clone(), (e.kind, blob))
7159282×
                })
7161490×
                .collect()
717
        };
718
        // A text file's graph key, worked out when the walk asks for it.
71912376×
        let key_of = |p: &str| -> Option<[u8; 32]> {
72012376×
            let e = view.entries.get(p)?;
7219173×
            if e.kind != NodeKind::File || e.mode.opaque {
722139×
                return None;
7239034×
            }
7249034×
            base.graph_key(&e.node)
72512376×
        };
7261489×
        let mut fs_entries = {
7271490×
            let _t = crate::timing::phase("snapshot: read working copy");
7281490×
            self.walk_working_copy_with(manifest.as_deref(), &tracked, Some(&key_of))?
729
        };
730
        // The keys of the files read, before building graphs drops them: a
731
        // file found equal to its base rendering keeps its key.
7321489×
        let keys: HashMap<String, [u8; 32]> = fs_entries
7331489×
            .iter()
73412423×
            .filter(|(_, e)| !e.unchanged && e.kind == NodeKind::File)
7358133×
            .filter_map(|(p, _)| Some((p.clone(), key_of(p)?)))
7361489×
            .collect();
7371489×
        let base_snapshot = {
7381489×
            let _t = crate::timing::phase("snapshot: load and render base");
7391489×
            if partial {
7401011×
                let sets = crate::timing::phase("snapshot:   of which choosing graphs");
741
                // Every file but those on disk known unchanged.
7421011×
                let need: Vec<(&str, NodeId)> = join(&view.entries, &fs_entries)
74311227×
                    .filter_map(|(p, v, f)| {
74411227×
                        let v = v?;
7458150×
                        (v.kind == NodeKind::File && !f.is_some_and(|f| f.unchanged))
7468150×
                            .then_some((p.as_str(), v.node))
74711227×
                    })
7481011×
                    .collect();
7491011×
                let render: std::collections::HashSet<&str> =
7501011×
                    need.iter().map(|(p, _)| *p).collect();
7511011×
                let need: Vec<NodeId> = need.iter().map(|(_, n)| *n).collect();
7521011×
                drop(sets);
753
                {
7541011×
                    let _t = crate::timing::phase("snapshot:   of which building graphs");
7551011×
                    self.load_graphs_of(&mut base, &need)?;
756
                }
7571011×
                let _t = crate::timing::phase("snapshot:   of which rendering");
7581011×
                base.materialize_only(&render)
759
            } else {
760478×
                self.load_all_graphs(&mut base)?;
761478×
                base.materialize()
762
            }
763
        };
764
765
        // Reuse the NodeIds the previous working-copy version assigned to new
766
        // paths, so an unchanged working copy hashes identically (spec §12.3).
7671489×
        let reuse = added_node_paths(&old_wc, &base_snapshot);
7681489×
        self.platform_normalize(&mut fs_entries, &base_snapshot);
769
        // Replace conflicts the user settled with `oxy resolve PATH`
770
        // (oxygen#140): those still in the base; a choice the base no longer
771
        // needs (once committed) is forgotten.
7721489×
        let resolve = self.resolutions_for(&base_snapshot)?;
7731489×
        let built = {
7741489×
            let _t = crate::timing::phase("snapshot: diff against base");
7751489×
            if !resolve.is_empty() {
7763×
                self.build_from_entries_resolving(
7773×
                    &base,
7783×
                    &base_snapshot,
7793×
                    reuse,
7803×
                    &fs_entries,
7813×
                    &resolve,
7820×
                )?
7831486×
            } else if partial && self.config.sparse_paths.is_empty() {
784
                #[cfg(test)]
785720×
                let full =
786720×
                    self.build_from_entries(&base, &base_snapshot, reuse.clone(), &fs_entries)?;
7871006×
                let built = self.build_changed_only(&base, &base_snapshot, reuse, &fs_entries)?;
788
                #[cfg(test)]
789
                {
790
                    // New nodes take random identifiers: compare them by
791
                    // order of appearance.
7921440×
                    let norm = |b: &BuiltChange| {
7931440×
                        let text = format!("{:?} {:?} {:?}", b.tree_ops, b.edits, b.statuses);
7941440×
                        let mut seen: Vec<String> = Vec::new();
7951440×
                        let mut out = String::new();
7961440×
                        let mut rest = text.as_str();
79720688×
                        while let Some(i) = rest.find("NodeId(") {
79819248×
                            out.push_str(&rest[..i]);
79919248×
                            let end = i + rest[i..].find(')').unwrap() + 1;
80019248×
                            let id = rest[i..end].to_string();
8019046478×
                            let n = seen.iter().position(|x| *x == id).unwrap_or_else(|| {
8027374×
                                seen.push(id);
8037374×
                                seen.len() - 1
8047374×
                            });
80519248×
                            out.push_str(&format!("N{n}"));
80619248×
                            rest = &rest[end..];
807
                        }
8081440×
                        out.push_str(rest);
8091440×
                        out
8101440×
                    };
811720×
                    assert_eq!(
812720×
                        norm(&built),
813720×
                        norm(&full),
814
                        "a changed-only build is the full one"
815
                    );
816
                }
8171006×
                built
818
            } else {
819480×
                self.build_from_entries(&base, &base_snapshot, reuse, &fs_entries)?
820
            }
821
        };
822
        // Text files found equal to an unconflicted base rendering keep its
823
        // graph key, so the next snapshot need not read or render them.
824
        {
8253890×
            let changed: HashSet<&str> = built.statuses.iter().map(|s| s.path.as_str()).collect();
82612423×
            for (p, e) in fs_entries.iter_mut() {
82712423×
                if e.unchanged || e.kind != NodeKind::File || changed.contains(p.as_str()) {
8288083×
                    continue;
8294340×
                }
8304340×
                e.graph_key = match base_snapshot.files.get(p).map(|f| &f.content) {
831
                    Some(FileContent::Text {
8324220×
                        bytes,
8334220×
                        materialized,
8344220×
                    }) if !materialized.is_conflicted() && *bytes == *e.content => {
8354211×
                        keys.get(p).copied()
836
                    }
837129×
                    _ => None,
838
                };
839
            }
840
        }
841
8421489×
        let mut wc = Change {
8431489×
            version: crate::objects::CHANGE_VERSION,
8441489×
            change_id: old_wc.change_id,
8451489×
            deps: vec![],
8461489×
            author: self.author(),
8471489×
            hlc: old_wc.hlc,
8481489×
            message: old_wc.message.clone(),
8491489×
            tree_ops: built.tree_ops,
8501489×
            edits: built.edits,
8511489×
            kind: ChangeKind::WorkingCopy,
8521489×
        };
8531489×
        let base_heads = base.maximal(&old_wc.deps);
8541489×
        let mut deps: BTreeSet<ChangeHash> = base_heads.into_iter().collect();
8551489×
        deps.extend(referenced_changes(&wc, &base));
8561489×
        deps.extend(built.contributors.iter().copied());
8571489×
        wc.deps = deps.into_iter().collect();
8581489×
        wc.normalize();
8591489×
        let resolves = built.resolves;
8601489×
        let contributors = built.contributors;
8611489×
        let statuses = built.statuses;
862
        // Empty snapshot: hash the candidate before storing; only record an op on change.
8631489×
        let record = crate::timing::phase("snapshot: hash and record");
864
        // Encoded once, its texts stored a batch at a time as they are
865
        // made (a stored blob is not stored again); the change itself only
866
        // when it changed.
867
        // For a commit the change is neither encoded, stored nor recorded:
868
        // the commit stores its own, built from this one's operations, and
869
        // its texts with it. The hash it would have is not needed.
8701489×
        let (new_hash, changed, encoded) = if for_commit {
871542×
            (old_hash, true, Vec::new())
872
        } else {
873947×
            let encoded = wc.encode_streaming(|batch| self.store.put_texts(&batch))?;
874947×
            let new_hash = crate::hash::hash_object(crate::hash::ObjectType::Change, &encoded);
875947×
            (new_hash, new_hash != old_hash, encoded)
876
        };
8771489×
        if changed && !for_commit {
878309×
            self.store.put(crate::hash::ObjectType::Change, &encoded)?;
879309×
            let mut view = op.view.clone();
880309×
            view.workspaces.insert(self.workspace, new_hash);
881309×
            self.record_op(&[op_ref], &format!("{command}{SNAPSHOT_SUFFIX}"), view)?;
8821180×
        }
8831489×
        drop(record);
884
        // The prompt compares against this without recording anything.
8851489×
        let _t = crate::timing::phase("snapshot: write manifest");
8861489×
        let conflicted = base_snapshot.is_conflicted();
8871489×
        let uncommitted = !wc.tree_ops.is_empty() || !wc.edits.is_empty();
888
        // Rewriting the manifest pays only when it would teach the next
889
        // snapshot something: other flags, a file found equal to the base
890
        // (it need not be read again), a new blob, a path added or gone.
891
        // An edited file is read next time whatever it says.
8921489×
        let worth = match self.read_manifest()? {
893542×
            _ if for_commit => true,
894364×
            None => true,
895583×
            Some((c, u, m)) => {
896583×
                c != conflicted
897583×
                    || u != uncommitted
898339×
                    || m.entries.len() != fs_entries.len()
899424×
                    || fs_entries.iter().any(|(p, e)| {
900424×
                        !e.unchanged && (e.graph_key.is_some() || !m.entries.contains_key(p))
901424×
                    })
90258×
                    || built
90358×
                        .blobs
90458×
                        .iter()
90558×
                        .any(|(p, b)| m.entries.get(p).and_then(|e| e.blob) != Some(*b))
906
                    // With uncommitted work, the status cache below holds
907
                    // only while the manifest describes the edited files as
908
                    // they are now.
90973×
                    || (uncommitted && statuses.iter().any(|st| {
91073×
                        let Some(e) = fs_entries.get(&st.path) else {
9114×
                            return m.entries.contains_key(&st.path);
912
                        };
91369×
                        let Some(me) = m.entries.get(&st.path) else {
9140×
                            return true;
915
                        };
91669×
                        let hash = e
91769×
                            .content_hash
91869×
                            .unwrap_or_else(|| *blake3::hash(&e.content).as_bytes());
91969×
                        let stat = e.stat.or_else(|| {
9200×
                            fs::symlink_metadata(self.root.join(&st.path))
9210×
                                .ok()
9220×
                                .map(|md| (md.len(), super::prompt::mtime_ns(&md)))
9230×
                        });
924
                        // The executable bit too: a mode change moves
925
                        // neither size nor time.
92669×
                        me.hash != hash || me.exec != e.exec || stat != Some((me.size, me.mtime_ns))
92773×
                    }))
928
            }
929
        };
9301489×
        let attributes = crate::attributes::Attributes::from_files(
9311489×
            fs_entries
9321489×
                .iter()
93312423×
                .filter(|(p, _)| is_attributes(p))
9341489×
                .map(|(p, e)| (p.as_str(), e.content.as_slice())),
935
        );
9361489×
        let mut manifest = None;
9371489×
        if for_commit {
938542×
            manifest = Some(PendingManifest {
939542×
                entries: fs_entries,
940542×
                blobs: built.blobs.clone(),
941542×
                dirs: self.walked_dirs.take(),
942542×
                written: super::prompt::now_ns(),
943542×
            });
944542×
        } else {
945947×
            if worth {
946892×
                self.write_manifest_entries(conflicted, uncommitted, &fs_entries, &built.blobs)?;
94755×
            }
948947×
            self.write_status_cache((uncommitted && !conflicted).then_some(&new_hash), &statuses);
949
        }
9501489×
        Ok(SnapshotResult {
9511489×
            wc_hash: new_hash,
9521489×
            wc,
9531489×
            base,
9541489×
            base_snapshot,
9551489×
            statuses,
9561489×
            changed,
9571489×
            resolves,
9581489×
            contributors,
9591489×
            attributes,
9601489×
            untracked_nested: self.untracked_nested.borrow().clone(),
9611489×
            manifest,
9621489×
        })
9631492×
    }
964
965
    /// `oxy status --json` (spec §9.5): the changed paths and every conflict
966
    /// of the working copy's base with its kind, path, and contributing
967
    /// ChangeIds.
9688×
    pub fn status_json(&self, snap: &SnapshotResult) -> Result<String> {
9698×
        let heads = self.bookmark_heads()?;
9708×
        let base_snapshot = &snap.base_snapshot;
9718×
        let by_node = base_snapshot.tree.by_node();
9728×
        let path_of = |n: &NodeId| by_node.get(n).map(|e| e.path.clone());
9738×
        let id_of = |h: &ChangeHash| {
9744×
            snap.base
9754×
                .get(h)
9764×
                .map(|m| m.change_id.to_hex())
9774×
                .unwrap_or_else(|| h.to_hex())
9784×
        };
9798×
        let paths = json_array(snap.statuses.iter().map(|s| {
9804×
            format!(
981
                "{{\"path\":{},\"status\":{}}}",
9824×
                json_str(&s.path),
9834×
                json_str(&format!("{:?}", s.status))
984
            )
9854×
        }));
9868×
        let mut conflicts: Vec<String> = Vec::new();
9879×
        for (p, f) in &base_snapshot.files {
9889×
            if !f.is_conflicted() {
9897×
                continue;
9902×
            }
9912×
            let (kind, changes) = match &f.content {
992
                FileContent::Text { .. } => {
9932×
                    ("text", snap.base.conflict_regions(&f.node).contributors)
994
                }
9950×
                FileContent::Opaque { blobs } => {
9960×
                    ("replace", snap.base.blob_contributors(&f.node, blobs))
997
                }
9980×
                FileContent::Dir => continue,
999
            };
10002×
            let resolved = match snap
10012×
                .statuses
10022×
                .iter()
10032×
                .find(|s| s.path == *p)
10042×
                .map(|s| s.status)
1005
            {
10061×
                Some(ChangeStatus::Resolved) => "true",
10070×
                Some(ChangeStatus::ConflictEdited) => "\"markers\"",
10081×
                _ => "false",
1009
            };
10102×
            conflicts.push(format!(
1011
                "{{\"kind\":{},\"path\":{},\"node\":{},\"changes\":{},\"resolved\":{resolved}}}",
10122×
                json_str(kind),
10132×
                json_str(p),
10142×
                json_str(&f.node.to_hex()),
10154×
                json_array(changes.iter().map(|h| json_str(&id_of(h))))
1016
            ));
1017
        }
10188×
        for c in &base_snapshot.tree.conflicts {
10190×
            let (kind, nodes): (&str, Vec<NodeId>) = match c {
10200×
                crate::tree::TreeConflict::Name { nodes, .. } => ("name", nodes.clone()),
10210×
                crate::tree::TreeConflict::MultiPlacement { node, .. } => {
10220×
                    ("multi-placement", vec![*node])
1023
                }
10240×
                crate::tree::TreeConflict::Orphan { node, .. } => ("orphan", vec![*node]),
10250×
                crate::tree::TreeConflict::Cycle { node } => ("cycle", vec![*node]),
10260×
                crate::tree::TreeConflict::Mode { node, .. } => ("mode", vec![*node]),
1027
            };
10280×
            let detail = match c {
10290×
                crate::tree::TreeConflict::Name { name, parent, .. } => {
10300×
                    let dir = if *parent == NodeId::ROOT {
10310×
                        String::new()
1032
                    } else {
10330×
                        path_of(parent).unwrap_or_default()
1034
                    };
10350×
                    format!(
1036
                        ",\"path\":{}",
10370×
                        json_str(&if dir.is_empty() {
10380×
                            name.clone()
1039
                        } else {
10400×
                            format!("{dir}/{name}")
1041
                        })
1042
                    )
1043
                }
10440×
                _ => nodes
10450×
                    .first()
10460×
                    .and_then(path_of)
10470×
                    .map(|p| format!(",\"path\":{}", json_str(&p)))
10480×
                    .unwrap_or_default(),
1049
            };
10500×
            conflicts.push(format!(
1051
                "{{\"kind\":{},\"nodes\":{}{detail}}}",
10520×
                json_str(kind),
10530×
                json_array(nodes.iter().map(|n| json_str(&n.to_hex())))
1054
            ));
1055
        }
10568×
        Ok(format!(
1057
            "{{\"bookmark\":{},\"working_copy\":{},\"heads\":{},\"clean\":{},\"conflicted\":{},\"paths\":{paths},\"conflicts\":{},\"untracked_nested\":{},\"skipped_large\":{}}}",
10588×
            json_str(&self.config.bookmark),
10598×
            json_str(&snap.wc.change_id.to_hex()),
10608×
            heads.len(),
10618×
            snap.statuses.is_empty(),
10628×
            base_snapshot.is_conflicted(),
10638×
            json_array(conflicts),
10648×
            json_array(snap.untracked_nested.iter().map(|p| json_str(p))),
10658×
            json_array(
10668×
                self.skipped_large
10678×
                    .borrow()
10688×
                    .iter()
10698×
                    .map(|(p, n)| format!("{{\"path\":{},\"size\":{n}}}", json_str(p)))
1070
            )
1071
        ))
10728×
    }
1073
1074
    /// Turn the working-copy change into a normal change on the bookmark (spec §12.3).
1075731×
    pub fn commit(&self, message: &str, extra_deps: &[ChangeHash]) -> Result<ChangeHash> {
1076731×
        self.commit_selection(message, extra_deps, &Selection::All)
1077731×
    }
1078
1079
    /// The hunks of the working copy, for `oxy commit --interactive`: each
1080
    /// tree operation and each edit, in the order `select_hunks` numbers them.
10818×
    pub fn hunks(&self) -> Result<(SnapshotResult, Vec<Hunk>)> {
10828×
        let snap = self.snapshot_status("oxy commit")?;
10838×
        let hunks = render_hunks(&snap.wc, &snap.base, &snap.base_snapshot);
10848×
        Ok((snap, hunks))
10858×
    }
1086
1087
    /// Commit part of the working copy (spec §12.3). What is not selected
1088
    /// stays on disk as uncommitted work: the next snapshot rebuilds it
1089
    /// against the new base, so the working copy always describes the
1090
    /// directory.
1091
    /// The graph key in `st` of each text file at `paths`, the paths a
1092
    /// commit changed: only their graphs changed, so the keys the manifest
1093
    /// holds for the others still stand (and any that does not is simply
1094
    /// not trusted by the next snapshot, which compares keys). Files with
1095
    /// an `eol` attribute are left out: their bytes on disk are not the
1096
    /// rendering.
1097749×
    fn committed_graph_keys(
1098749×
        &self,
1099749×
        st: &State,
1100749×
        paths: &[String],
1101749×
        attrs: &crate::attributes::Attributes,
1102749×
    ) -> HashMap<String, [u8; 32]> {
1103749×
        let _t = crate::timing::phase("commit: graph keys");
1104749×
        let view = st.view();
1105749×
        paths
1106749×
            .iter()
11073598×
            .filter_map(|p| {
11083598×
                let e = view.entries.get(p)?;
11093554×
                (e.kind == NodeKind::File && !e.mode.opaque && attrs.lookup(p).eol.is_none())
11103554×
                    .then_some(())?;
11113484×
                Some((p.clone(), st.graph_key(&e.node)?))
11123598×
            })
1113749×
            .collect()
1114749×
    }
1115
1116738×
    pub fn commit_selection(
1117738×
        &self,
1118738×
        message: &str,
1119738×
        extra_deps: &[ChangeHash],
1120738×
        selection: &Selection,
1121738×
    ) -> Result<ChangeHash> {
1122738×
        Ok(self
1123738×
            .commit_selection_partial(message, extra_deps, selection)?
1124
            .0)
1125738×
    }
1126
1127
    /// As [`Repo::commit_selection`], and whether the commit left part of
1128
    /// the working copy uncommitted: when it did not, nothing is left, and
1129
    /// no snapshot is needed to say so.
1130767×
    pub fn commit_selection_partial(
1131767×
        &self,
1132767×
        message: &str,
1133767×
        extra_deps: &[ChangeHash],
1134767×
        selection: &Selection,
1135767×
    ) -> Result<(ChangeHash, bool)> {
1136
        // The commit's objects are written together, made durable at once
1137
        // before the operation that names them (spec §13.6).
1138767×
        let batch = self.store.begin_batch()?;
1139767×
        let out = self.commit_selection_batched(message, extra_deps, selection);
1140767×
        batch.finish()?;
1141767×
        out
1142767×
    }
1143
1144
    /// Write the manifest a commit's snapshot left to the commit, with the
1145
    /// graph keys `keys` sets.
1146530×
    fn write_pending_manifest(
1147530×
        &self,
1148530×
        mut m: PendingManifest,
1149530×
        conflicted: bool,
1150530×
        keys: HashMap<String, [u8; 32]>,
1151530×
    ) -> Result<()> {
11522889×
        for (path, k) in keys {
11532889×
            if let Some(e) = m.entries.get_mut(&path) {
11542889×
                e.graph_key = Some(k);
11552889×
            }
1156
        }
1157530×
        self.write_manifest_entries_as_of(
1158530×
            conflicted,
1159
            false,
1160530×
            &m.entries,
1161530×
            &m.blobs,
1162530×
            m.written,
1163530×
            m.dirs.unwrap_or_default(),
1164
        )
1165530×
    }
1166
1167767×
    fn commit_selection_batched(
1168767×
        &self,
1169767×
        message: &str,
1170767×
        extra_deps: &[ChangeHash],
1171767×
        selection: &Selection,
1172767×
    ) -> Result<(ChangeHash, bool)> {
1173767×
        let _wc = self.lock_working_copy()?;
1174767×
        let mut snap = match self.snapshot_from_cache()? {
1175225×
            Some(snap) => snap,
1176542×
            None => self.snapshot_as("oxy commit", true, true)?,
1177
        };
1178767×
        let pending = snap.manifest.take();
1179767×
        if snap.wc.tree_ops.is_empty() && snap.wc.edits.is_empty() {
11804×
            if let Some(m) = pending {
11814×
                let conflicted = snap.base_snapshot.is_conflicted();
11824×
                self.write_pending_manifest(m, conflicted, HashMap::new())?;
11830×
            }
11844×
            return fail("nothing to commit: the working copy matches its base");
1185763×
        }
1186763×
        if let Some(s) = snap
1187763×
            .statuses
1188763×
            .iter()
11893627×
            .find(|s| s.status == ChangeStatus::ConflictEdited)
1190
        {
11911×
            return fail(format!("{} still contains conflict markers", s.path));
1192762×
        }
1193762×
        if message.trim().is_empty() {
11940×
            return fail("a commit message is required");
1195762×
        }
1196
        // What the whole working copy references, before a whole commit
1197
        // takes its operations over (they are moved, not copied: for a
1198
        // large tree they are most of the memory).
1199762×
        let wc_refs = referenced_changes(&snap.wc, &snap.base);
12003625×
        let changed_paths: Vec<String> = snap.statuses.iter().map(|s| s.path.clone()).collect();
1201762×
        let (tree_ops, edits, partial) = match selection {
1202749×
            Selection::All => (
1203749×
                std::mem::take(&mut snap.wc.tree_ops),
1204749×
                std::mem::take(&mut snap.wc.edits),
1205749×
                false,
1206749×
            ),
12078×
            Selection::Paths(paths) => {
12088×
                let (o, e) = select_paths(&snap.wc, &snap.base_snapshot, paths);
12098×
                let partial = o.len() != snap.wc.tree_ops.len() || e.len() != snap.wc.edits.len();
12108×
                (o, e, partial)
1211
            }
12125×
            Selection::Hunks(indices) => {
12135×
                let (o, e) = select_hunks(&snap.wc, indices, &snap.base_snapshot.tree.unified);
12145×
                let partial = o.len() != snap.wc.tree_ops.len() || e.len() != snap.wc.edits.len();
12155×
                (o, e, partial)
1216
            }
1217
        };
1218762×
        if tree_ops.is_empty() && edits.is_empty() {
12190×
            return fail("nothing selected to commit");
1220762×
        }
1221
        // A resolution may leave other work uncommitted (oxygen#118), but
1222
        // takes every file it resolves, whole.
1223762×
        if partial && snap.resolves {
12242×
            let resolved = snap
12252×
                .statuses
12262×
                .iter()
12274×
                .filter(|s| s.status == ChangeStatus::Resolved)
12282×
                .map(|s| s.path.as_str());
12292×
            let missing: Vec<&str> = match selection {
12302×
                Selection::Paths(paths) => resolved
12312×
                    .filter(|p| {
12322×
                        !paths.iter().any(|x| {
12332×
                            p == x || p.starts_with(&format!("{}/", x.trim_end_matches('/')))
12342×
                        })
12352×
                    })
12362×
                    .collect(),
12370×
                _ => resolved.collect(),
1238
            };
12392×
            if !missing.is_empty() {
12401×
                return fail(format!(
1241
                    "a conflict resolution takes every file it resolves, whole: commit by paths, including {}",
12421×
                    missing.join(", ")
1243
                ));
12441×
            }
1245760×
        }
1246
        // pre-commit hook: may veto.
1247761×
        self.run_hook(
1248761×
            "pre-commit",
1249761×
            &format!(
1250
                "{{\"event\":\"pre-commit\",\"message\":{},\"paths\":{}}}",
1251761×
                json_str(message),
12523623×
                json_array(snap.statuses.iter().map(|s| format!(
1253
                    "{{\"path\":{},\"status\":{}}}",
12543623×
                    json_str(&s.path),
12553623×
                    json_str(&format!("{:?}", s.status))
1256
                )))
1257
            ),
12581×
        )?;
1259760×
        let (op_ref, op) = self.head_op()?;
1260760×
        let mut deps: BTreeSet<ChangeHash> = wc_refs;
1261
        // semantic-deps hook: may add explicit dependencies (spec §8.1).
1262760×
        if self.config.semantic_deps {
12631×
            let touched: Vec<String> = snap.statuses.iter().map(|s| s.path.clone()).collect();
12641×
            let by_node = snap.base_snapshot.tree.by_node();
12651×
            let mut candidates: Vec<(ChangeId, ChangeHash, Vec<String>)> = Vec::new();
12661×
            let mut seen: BTreeSet<ChangeHash> = BTreeSet::new();
12672×
            for h in deps.iter().chain(snap.base.maximal(&snap.wc.deps).iter()) {
12682×
                if !seen.insert(*h) {
12690×
                    continue;
12702×
                }
12712×
                let c = self.store.get_change(h)?;
12722×
                let mut paths: BTreeSet<String> = BTreeSet::new();
12736×
                for n in c
12742×
                    .tree_ops
12752×
                    .iter()
12763×
                    .map(|o| o.node())
12773×
                    .chain(c.edits.iter().map(|e| e.node()))
1278
                {
12796×
                    if let Some(e) = by_node.get(&n) {
12806×
                        paths.insert(e.path.clone());
12816×
                    }
1282
                }
12832×
                candidates.push((c.change_id, *h, paths.into_iter().collect()));
1284
            }
12851×
            for d in self.semantic_deps(&snap.wc.change_id, &touched, &candidates)? {
12861×
                if snap.base.contains(&d) {
12871×
                    deps.insert(d);
12881×
                }
1289
            }
1290759×
        }
1291
        // A resolution depends on every change that contributed to the
1292
        // conflict (spec §8.1). Tree and opaque conflicts are resolved through
1293
        // ordinary operations whose references already cover the contributors.
1294760×
        deps.extend(snap.contributors.iter().copied());
1295760×
        for d in extra_deps {
12964×
            if !snap.base.contains(d) {
12970×
                return fail(format!(
1298
                    "--depends-on {d}: not in the working copy's base state"
1299
                ));
13004×
            }
13014×
            deps.insert(*d);
1302
        }
1303760×
        let mut change = Change {
1304
            version: crate::objects::CHANGE_VERSION,
1305760×
            change_id: if partial {
130610×
                ChangeId::random()
1307
            } else {
1308750×
                snap.wc.change_id
1309
            },
1310760×
            deps: vec![],
1311760×
            author: self.author(),
1312760×
            hlc: Hlc::now(),
1313760×
            message: message.trim_end().to_string(),
1314760×
            tree_ops,
1315760×
            edits,
1316760×
            kind: if snap.resolves {
131713×
                ChangeKind::Resolution
1318
            } else {
1319747×
                ChangeKind::Normal
1320
            },
1321
        };
1322760×
        if partial {
1323
            // Dependencies come from what the selected part references, not
1324
            // from the whole working copy.
132510×
            deps = referenced_changes(&change, &snap.base);
132610×
            for d in extra_deps {
13271×
                deps.insert(*d);
13281×
            }
1329750×
        }
1330760×
        change.deps = deps.into_iter().collect();
1331760×
        change.normalize();
1332760×
        let signing = crate::timing::phase("commit: sign and store");
1333760×
        let hash = self.store_signed(&change)?;
1334759×
        drop(signing);
1335759×
        let extending = crate::timing::phase("commit: extend the state");
1336
1337
        // New bookmark heads: maximal elements of old heads plus the new change.
1338
        // The working copy continues on its own base plus the new change, which
1339
        // is exactly what the files on disk contain; the bookmark may hold
1340
        // other heads (and conflicts) the working copy has not checked out.
1341759×
        let old_heads = self.heads_of(&op.view, &self.config.bookmark)?;
1342759×
        let old_base = snap.base.maximal(&snap.wc.deps);
1343759×
        let mut all: Vec<ChangeHash> = old_heads.clone();
1344759×
        all.extend(old_base.iter().copied());
1345759×
        all.push(hash);
1346
        // The snapshot already loaded the working copy's base; when that also
1347
        // holds every bookmark head, it is the state to extend.
1348759×
        let mut st = if old_heads.iter().all(|h| snap.base.contains(h)) {
1349715×
            snap.base
1350
        } else {
135144×
            self.load_state(&all)?
1352
        };
1353759×
        st.add_hashed(hash, change)?;
1354759×
        let mut with_new = old_heads.clone();
1355759×
        with_new.push(hash);
1356759×
        let new_heads = st.maximal(&with_new);
1357
        // Automatic checkpoint once enough changes accumulated (spec §11).
1358759×
        let since = self
1359759×
            .latest_checkpoint(&self.config.bookmark)?
1360759×
            .map(|(_, cp)| cp.count)
1361759×
            .unwrap_or(0);
1362759×
        if self.config.checkpoint_interval > 0
1363759×
            && (st.len() as u64).saturating_sub(since) >= self.config.checkpoint_interval
1364
        {
13652×
            let cp_state = self.load_state_full(&new_heads)?;
13662×
            self.write_checkpoint(&self.config.bookmark, &cp_state, &new_heads)?;
1367757×
        }
1368759×
        let mut wc_base = old_base.clone();
1369759×
        wc_base.push(hash);
1370759×
        let wc_base = st.maximal(&wc_base);
1371759×
        drop(extending);
1372
1373
        // The graph keys of the files as they now are, from the state the
1374
        // commit just extended: a file whose graph it built has none, and
1375
        // is read by the next snapshot; a key the next base does not share
1376
        // (the bookmark held other heads) is simply not trusted then.
1377759×
        let keying = crate::timing::phase("commit: graph keys of the files");
1378759×
        let committed_keys =
1379759×
            (!partial).then(|| self.committed_graph_keys(&st, &changed_paths, &snap.attributes));
1380759×
        drop(keying);
1381759×
        let recording = crate::timing::phase("commit: record");
1382759×
        let wc = self.new_working_copy(wc_base, "");
1383759×
        let wc_hash = self.store.put_change(&wc)?;
1384759×
        let mut view = op.view.clone();
1385759×
        view.bookmarks.insert(
1386759×
            self.config.bookmark.clone(),
1387759×
            self.store.put_state(&StateObject::new(new_heads))?,
1388
        );
1389759×
        view.workspaces.insert(self.workspace, wc_hash);
1390759×
        self.record_op(&[op_ref], &format!("oxy commit -m {message:?}"), view)?;
1391754×
        drop(recording);
1392754×
        let rewriting = crate::timing::phase("commit: manifest");
1393754×
        if partial {
139410×
            // The rest is rebuilt from disk by the next snapshot.
139510×
            self.drop_manifest();
139610×
        } else {
1397744×
            let conflicted = snap.base_snapshot.is_conflicted() && !snap.resolves;
1398
            // The files on disk are now exactly the new base's renderings:
1399
            // record their graph keys, so the next snapshot neither reads nor
1400
            // renders them (oxygen#35).
1401744×
            let keys = if conflicted {
14020×
                HashMap::new()
1403
            } else {
1404744×
                committed_keys.unwrap_or_default()
1405
            };
1406744×
            match pending {
1407526×
                Some(m) => self.write_pending_manifest(m, conflicted, keys)?,
1408218×
                None => self.rewrite_manifest(conflicted, false, &keys)?,
1409
            }
1410
        }
1411754×
        drop(rewriting);
1412754×
        let packing = crate::timing::phase("commit: autopack");
1413754×
        self.maybe_autopack()?;
1414754×
        drop(packing);
1415754×
        let _hook = crate::timing::phase("commit: hook");
1416754×
        let _ = self.run_hook(
1417754×
            "post-commit",
1418754×
            &format!(
1419754×
                "{{\"event\":\"post-commit\",\"change_id\":{},\"hash\":{},\"message\":{}}}",
1420754×
                json_str(&snap.wc.change_id.to_hex()),
1421754×
                json_str(&hash.to_hex()),
1422754×
                json_str(message)
1423754×
            ),
1424754×
        );
1425754×
        Ok((hash, partial))
1426767×
    }
1427
}
1428
1429
/// What part of the working copy a commit takes (spec §12.3).
1430
#[derive(Clone, Debug)]
1431
pub enum Selection {
1432
    All,
1433
    /// Every operation and edit on nodes under these paths.
1434
    Paths(Vec<String>),
1435
    /// Hunk indices as `Repo::hunks` numbers them; dependent hunks are added.
1436
    Hunks(Vec<usize>),
1437
}
1438
1439
/// One selectable piece of the working copy: a tree operation or an edit.
1440
#[derive(Clone, Debug)]
1441
pub struct Hunk {
1442
    pub index: usize,
1443
    pub path: String,
1444
    /// Rendered like `oxy diff`.
1445
    pub text: String,
1446
}
1447
1448
/// The tree operations and edits on nodes under `paths`, plus the
1449
/// additions of any new parent directories they need.
14508×
fn select_paths(
14518×
    wc: &Change,
14528×
    base_snapshot: &Snapshot,
14538×
    paths: &[String],
14548×
) -> (Vec<TreeOp>, Vec<Edit>) {
145527×
    let selected = |p: &str| {
145627×
        paths
145727×
            .iter()
145827×
            .any(|x| p == x || p.starts_with(&format!("{}/", x.trim_end_matches('/'))))
145927×
    };
14608×
    let by_node = base_snapshot.tree.by_node();
14618×
    let mut new_names: HashMap<NodeId, (NodeId, String, NodeKind)> = HashMap::new();
14628×
    for op in &wc.tree_ops {
1463
        if let TreeOp::AddNode {
14645×
            node,
14655×
            parent,
14665×
            name,
14675×
            kind,
1468
            ..
14696×
        } = op
14705×
        {
14715×
            new_names.insert(*node, (*parent, name.clone(), *kind));
14725×
        }
1473
    }
14748×
    let mut nodes: BTreeSet<NodeId> = BTreeSet::new();
147528×
    for n in wc
14768×
        .tree_ops
14778×
        .iter()
14788×
        .map(|o| o.node())
147922×
        .chain(wc.edits.iter().map(|e| e.node()))
1480
    {
148128×
        if path_of_node(&n, &by_node, &new_names).is_some_and(|p| selected(&p)) {
148214×
            nodes.insert(n);
148314×
        }
1484
    }
1485
    // The nodes shown as one with a selected node are retired with it.
14868×
    for (dup, shown) in &base_snapshot.tree.unified {
14871×
        if nodes.contains(shown) {
14881×
            nodes.insert(*dup);
14891×
        }
1490
    }
1491
    // New parents of selected new nodes come along.
14928×
    let mut changed = true;
149316×
    while changed {
14948×
        changed = false;
14958×
        for (n, (parent, _, _)) in &new_names {
14965×
            if nodes.contains(n) && new_names.contains_key(parent) && nodes.insert(*parent) {
14970×
                changed = true;
14985×
            }
1499
        }
1500
    }
15018×
    let ops = wc
15028×
        .tree_ops
15038×
        .iter()
15048×
        .filter(|o| nodes.contains(&o.node()))
15058×
        .cloned()
15068×
        .collect();
15078×
    let edits = wc
15088×
        .edits
15098×
        .iter()
151022×
        .filter(|e| nodes.contains(&e.node()))
15118×
        .cloned()
15128×
        .collect();
15138×
    (ops, edits)
15148×
}
1515
1516
/// The hunks `indices` name plus whatever they refer to within the working
1517
/// copy (the parent directory of an added node, the insert that introduced
1518
/// an anchor line), renumbered so the result is a well-formed change.
1519
/// The nodes `unified` shows as one with another (a base's
1520
/// [`TreeView::unified`](crate::tree::TreeView::unified)) are retired with
1521
/// any hunk of the node shown.
15226×
fn select_hunks(
15236×
    wc: &Change,
15246×
    indices: &[usize],
15256×
    unified: &BTreeMap<NodeId, NodeId>,
15266×
) -> (Vec<TreeOp>, Vec<Edit>) {
15276×
    let n_ops = wc.tree_ops.len();
15286×
    let mut ops_sel = vec![false; n_ops];
15296×
    let mut edits_sel = vec![false; wc.edits.len()];
15306×
    for &i in indices {
15315×
        if i < n_ops {
15321×
            ops_sel[i] = true;
15334×
        } else if i - n_ops < wc.edits.len() {
15344×
            edits_sel[i - n_ops] = true;
15354×
        }
1536
    }
1537
    // Atom ranges each insert introduces, per node, in the working copy's numbering.
15386×
    let mut per_node: HashMap<NodeId, u32> = HashMap::new();
15396×
    let mut insert_ranges: Vec<Option<(NodeId, u32, u32)>> = Vec::new();
154012×
    for e in &wc.edits {
154112×
        insert_ranges.push(match e {
154212×
            Edit::Insert { node, lines, .. } => {
154312×
                let start = per_node.entry(*node).or_default();
154412×
                let r = (*node, *start, *start + lines.len() as u32);
154512×
                *start += lines.len() as u32;
154612×
                Some(r)
1547
            }
15480×
            _ => None,
1549
        });
1550
    }
15516×
    let add_index: HashMap<NodeId, usize> = wc
15526×
        .tree_ops
15536×
        .iter()
15546×
        .enumerate()
155510×
        .filter_map(|(i, o)| {
155610×
            if let TreeOp::AddNode { node, .. } = o {
15579×
                Some((*node, i))
1558
            } else {
15591×
                None
1560
            }
156110×
        })
15626×
        .collect();
15636×
    let insert_for = |node: &NodeId, index: u32| -> Option<usize> {
15640×
        insert_ranges
15650×
            .iter()
15660×
            .position(|r| matches!(r, Some((n, a, b)) if n == node && *a <= index && index < *b))
15670×
    };
1568
    // Closure.
15696×
    let mut changed = true;
157015×
    while changed {
15719×
        changed = false;
157219×
        for i in 0..n_ops {
157319×
            if !ops_sel[i] {
157413×
                continue;
15756×
            }
15766×
            if let TreeOp::AddNode { node, parent, .. } = &wc.tree_ops[i] {
15776×
                if let Some(&p) = add_index.get(parent) {
15784×
                    if !ops_sel[p] {
15792×
                        ops_sel[p] = true;
15802×
                        changed = true;
15812×
                    }
15822×
                }
1583
                // A new node's content belongs with its addition: nobody
1584
                // wants an empty file committed apart from its lines.
158512×
                for (j, e) in wc.edits.iter().enumerate() {
158612×
                    if e.node() == *node && !edits_sel[j] {
15871×
                        edits_sel[j] = true;
15881×
                        changed = true;
158911×
                    }
1590
                }
15910×
            }
1592
        }
159318×
        for j in 0..wc.edits.len() {
159418×
            if !edits_sel[j] {
159510×
                continue;
15968×
            }
15978×
            let e = &wc.edits[j];
15988×
            if let Some(&a) = add_index.get(&e.node()) {
15995×
                if !ops_sel[a] {
16001×
                    ops_sel[a] = true;
16011×
                    changed = true;
16024×
                }
16033×
            }
1604
            if let Edit::Insert {
16058×
                node,
16068×
                after,
16078×
                before,
1608
                ..
16098×
            } = e
1610
            {
161116×
                for r in [after, before] {
161216×
                    if let AtomRef::Atom { change, index } = r {
16133×
                        if change.is_zero() {
16140×
                            if let Some(k) = insert_for(node, *index) {
16150×
                                if !edits_sel[k] {
16160×
                                    edits_sel[k] = true;
16170×
                                    changed = true;
16180×
                                }
16190×
                            }
16203×
                        }
162113×
                    }
1622
                }
16230×
            }
1624
        }
1625
    }
1626
    // The retirement of a node shown as one with a selected node.
16276×
    if !unified.is_empty() {
16281×
        let chosen: HashSet<NodeId> = (0..n_ops)
16292×
            .filter(|i| ops_sel[*i])
16301×
            .map(|i| wc.tree_ops[i].node())
16311×
            .chain(
16321×
                (0..wc.edits.len())
16332×
                    .filter(|j| edits_sel[*j])
16341×
                    .map(|j| wc.edits[j].node()),
1635
            )
16361×
            .collect();
16372×
        for (i, o) in wc.tree_ops.iter().enumerate() {
16382×
            if let TreeOp::RemoveNode { node, .. } = o {
16391×
                if unified.get(node).is_some_and(|s| chosen.contains(s)) {
16401×
                    ops_sel[i] = true;
16411×
                }
16421×
            }
1643
        }
16445×
    }
1645
    // Renumber self-references: old atom index → new index among selected inserts.
16466×
    let mut remap: HashMap<(NodeId, u32), u32> = HashMap::new();
16476×
    let mut new_counts: HashMap<NodeId, u32> = HashMap::new();
164812×
    for (j, r) in insert_ranges.iter().enumerate() {
164912×
        if let (true, Some((node, a, b))) = (edits_sel[j], r) {
16505×
            let next = new_counts.entry(*node).or_default();
16515×
            for old in *a..*b {
16525×
                remap.insert((*node, old), *next);
16535×
                *next += 1;
16545×
            }
16557×
        }
1656
    }
165710×
    let map_ref = |r: AtomRef, node: &NodeId| -> AtomRef {
16583×
        match r {
16593×
            AtomRef::Atom { change, index } if change.is_zero() => AtomRef::Atom {
16600×
                change,
16610×
                index: remap.get(&(*node, index)).copied().unwrap_or(index),
16620×
            },
166310×
            other => other,
1664
        }
166510×
    };
16666×
    let ops = wc
16676×
        .tree_ops
16686×
        .iter()
16696×
        .enumerate()
167010×
        .filter(|(i, _)| ops_sel[*i])
16716×
        .map(|(_, o)| o.clone())
16726×
        .collect();
16736×
    let edits = wc
16746×
        .edits
16756×
        .iter()
16766×
        .enumerate()
167712×
        .filter(|(j, _)| edits_sel[*j])
16786×
        .map(|(_, e)| match e {
1679
            Edit::Insert {
16805×
                node,
16815×
                after,
16825×
                before,
16835×
                lines,
16845×
            } => Edit::Insert {
16855×
                node: *node,
16865×
                after: map_ref(*after, node),
16875×
                before: map_ref(*before, node),
16885×
                lines: lines.clone(),
16895×
            },
16900×
            other => other.clone(),
16915×
        })
16926×
        .collect();
16936×
    (ops, edits)
16946×
}
1695
1696
/// Render each tree operation and edit of `change` on its own, numbered.
16978×
pub fn render_hunks(change: &Change, base: &State, base_snapshot: &Snapshot) -> Vec<Hunk> {
16988×
    let by_node = base_snapshot.tree.by_node();
16998×
    let mut new_names: HashMap<NodeId, (NodeId, String, NodeKind)> = HashMap::new();
170010×
    for op in &change.tree_ops {
1701
        if let TreeOp::AddNode {
17029×
            node,
17039×
            parent,
17049×
            name,
17059×
            kind,
1706
            ..
170710×
        } = op
17089×
        {
17099×
            new_names.insert(*node, (*parent, name.clone(), *kind));
17109×
        }
1711
    }
17128×
    let mut out = Vec::new();
171310×
    for (i, op) in change.tree_ops.iter().enumerate() {
1714
        // A retired duplicate goes with the node shown: no hunk of its own.
171510×
        if is_unified_retirement(op, base_snapshot) {
17161×
            continue;
17179×
        }
17189×
        let one = Change {
17199×
            tree_ops: vec![op.clone()],
17209×
            edits: vec![],
17219×
            ..change.clone()
17229×
        };
17239×
        let path = path_of_node(&op.node(), &by_node, &new_names).unwrap_or_default();
17249×
        out.push(Hunk {
17259×
            index: i,
17269×
            path,
17279×
            text: render_change(&one, base, base_snapshot),
17289×
        });
1729
    }
173015×
    for (j, e) in change.edits.iter().enumerate() {
173115×
        let one = Change {
173215×
            tree_ops: vec![],
173315×
            edits: vec![e.clone()],
173415×
            ..change.clone()
173515×
        };
173615×
        let path = path_of_node(&e.node(), &by_node, &new_names).unwrap_or_default();
173715×
        out.push(Hunk {
173815×
            index: change.tree_ops.len() + j,
173915×
            path,
174015×
            text: render_change(&one, base, base_snapshot),
174115×
        });
174215×
    }
17438×
    out
17448×
}
1745
1746
/// One file's part of a diff, for `oxy diff --json`.
1747
#[derive(Clone, Debug)]
1748
pub struct FileDiff {
1749
    pub path: String,
1750
    /// `added`, `removed`, `modified`, `renamed`, `mode`, `replaced`.
1751
    pub kind: String,
1752
    pub hunks: Vec<DiffHunk>,
1753
    /// For renames, the previous path.
1754
    pub from: Option<String>,
1755
}
1756
1757
/// Lines inserted after `base_line` (0 = before the first line) and lines
1758
/// removed, with their base line numbers.
1759
#[derive(Clone, Debug, Default)]
1760
pub struct DiffHunk {
1761
    pub base_line: u32,
1762
    pub added: Vec<Vec<u8>>,
1763
    pub removed: Vec<(u32, Vec<u8>)>,
1764
}
1765
1766
impl Repo {
1767
    /// The content of `path` in a state: `heads`, or the working copy's base.
176827×
    pub fn file_at(&self, path: &str, heads: Option<&[ChangeHash]>) -> Result<Vec<u8>> {
1769
        // The state's history and tree, then the one file's graph: nothing
1770
        // else is built or rendered (oxygen#92).
1771
        // The working copy's base, and a state named by its heads (`-r
1772
        // main` on main), come from the workspace's state index.
177327×
        let base = if self.is_bare() {
17745×
            None
1775
        } else {
177622×
            Some(self.working_copy()?.1.deps)
1777
        };
177827×
        let same = |a: &[ChangeHash], b: &[ChangeHash]| {
17791×
            let (mut a, mut b) = (a.to_vec(), b.to_vec());
17801×
            a.sort();
17811×
            b.sort();
17821×
            a == b
17831×
        };
178427×
        let mut state = match (heads, base) {
17851×
            (Some(h), Some(b)) if same(h, &b) => self.load_state_indexed(&b)?,
17865×
            (Some(h), _) => self.load_state_history(h)?,
178721×
            (None, Some(b)) => self.load_state_indexed(&b)?,
17880×
            (None, None) => return fail("this is a bare repository: it has no working copy"),
1789
        };
179027×
        let view = self.tree_view(&mut state)?;
179127×
        let Some(node) = view.entries.get(path).map(|e| e.node) else {
17920×
            return fail(format!("{path} is not in that state"));
1793
        };
179427×
        self.load_graphs_of(&mut state, &[node])?;
179526×
        let snapshot = state.materialize_paths(view, [path]);
179626×
        let Some(f) = snapshot.files.get(path) else {
17970×
            return fail(format!("{path} is not in that state"));
1798
        };
179926×
        match &f.content {
18000×
            FileContent::Dir => fail(format!("{path} is a directory")),
180126×
            FileContent::Text { bytes, .. } => Ok(bytes.clone()),
18020×
            FileContent::Opaque { blobs } => match blobs.first() {
18030×
                Some(b) => self.read_blob(b),
18040×
                None => Ok(vec![]),
1805
            },
1806
        }
180727×
    }
1808
1809
    /// Restore `paths` (files or directories) to the working copy's base:
1810
    /// edits are undone, additions removed, removals put back. Returns the
1811
    /// number of paths touched.
18122×
    pub fn discard(&self, paths: &[String]) -> Result<usize> {
18132×
        let _wc = self.lock_working_copy()?;
18142×
        let snap = self.snapshot_status("oxy discard")?;
18157×
        let under = |p: &str| {
18167×
            paths
18177×
                .iter()
18187×
                .any(|x| p == x || p.starts_with(&format!("{}/", x.trim_end_matches('/'))))
18197×
        };
18202×
        let attrs = Repo::state_attributes(&snap.base_snapshot);
18212×
        let mut n = 0;
18223×
        for s in &snap.statuses {
18233×
            if !under(&s.path) {
18241×
                continue;
18252×
            }
18262×
            match snap.base_snapshot.files.get(&s.path) {
1827
                None => {
1828
                    // Added (or the new name of a rename): remove it.
18291×
                    let full = self.root.join(&s.path);
18301×
                    if full.is_dir() {
18310×
                        let _ = fs::remove_dir_all(&full);
18321×
                    } else {
18331×
                        let _ = fs::remove_file(&full);
18341×
                    }
18351×
                    n += 1;
1836
                }
18371×
                Some(f) => {
18381×
                    match &f.content {
18390×
                        FileContent::Dir => fs::create_dir_all(self.root.join(&s.path))?,
18401×
                        FileContent::Text { bytes, .. } => {
18411×
                            let on_disk: std::borrow::Cow<[u8]> = if attrs.lookup(&s.path).eol
18421×
                                == Some(crate::attributes::Eol::Crlf)
1843
                            {
18440×
                                crate::attributes::to_crlf(bytes).into()
1845
                            } else {
18461×
                                bytes.as_slice().into()
1847
                            };
18481×
                            self.write_file(&s.path, &on_disk, f.mode.exec)?;
1849
                        }
18500×
                        FileContent::Opaque { blobs } => {
18510×
                            let bytes = match blobs.first() {
18520×
                                Some(b) => self.read_blob(b)?,
18530×
                                None => vec![],
1854
                            };
18550×
                            if f.kind == NodeKind::Symlink {
18560×
                                self.write_symlink(&s.path, &bytes)?;
18570×
                            } else if f.kind == NodeKind::File {
18580×
                                self.write_file(&s.path, &bytes, f.mode.exec)?;
18590×
                            }
1860
                        }
1861
                    }
18621×
                    n += 1;
1863
                }
1864
            }
1865
        }
1866
        // A rename's old name is not in the statuses; put it back too.
18674×
        for (p, f) in &snap.base_snapshot.files {
18684×
            if under(p)
18691×
                && !self.root.join(p).exists()
18700×
                && f.kind != NodeKind::Dir
18710×
                && f.kind != NodeKind::Subrepo
18720×
                && !snap.statuses.iter().any(|s| s.path == *p)
1873
            {
18740×
                let bytes = match &f.content {
18750×
                    FileContent::Text { bytes, .. } => bytes.clone(),
18760×
                    FileContent::Opaque { blobs } => blobs
18770×
                        .first()
18780×
                        .map(|b| self.read_blob(b))
18790×
                        .transpose()?
18800×
                        .unwrap_or_default(),
18810×
                    FileContent::Dir => continue,
1882
                };
18830×
                if f.kind == NodeKind::Symlink {
18840×
                    self.write_symlink(p, &bytes)?
1885
                } else {
18860×
                    self.write_file(p, &bytes, f.mode.exec)?
1887
                }
18880×
                n += 1;
18894×
            }
1890
        }
18912×
        self.drop_manifest();
18922×
        Ok(n)
18932×
    }
1894
1895
    /// Undo the working-copy hunks `indices` (as `hunks` numbers them) on
1896
    /// disk, keeping the others: the files are rewritten from the base plus
1897
    /// the remaining hunks.
18981×
    pub fn discard_hunks(&self, indices: &[usize]) -> Result<usize> {
18991×
        let _wc = self.lock_working_copy()?;
19001×
        let (snap, hunks) = self.hunks()?;
19011×
        let keep: Vec<usize> = hunks
19021×
            .iter()
19031×
            .map(|h| h.index)
19041×
            .filter(|i| !indices.contains(i))
19051×
            .collect();
19061×
        let (ops, edits) = select_hunks(&snap.wc, &keep, &snap.base_snapshot.tree.unified);
19071×
        let dropped_nodes: BTreeSet<NodeId> = hunks
19081×
            .iter()
19091×
            .filter(|h| indices.contains(&h.index))
19101×
            .map(|h| {
19111×
                if h.index < snap.wc.tree_ops.len() {
19120×
                    snap.wc.tree_ops[h.index].node()
1913
                } else {
19141×
                    snap.wc.edits[h.index - snap.wc.tree_ops.len()].node()
1915
                }
19161×
            })
19171×
            .collect();
19181×
        let mut partial = snap.wc.clone();
19191×
        partial.tree_ops = ops;
19201×
        partial.edits = edits;
19211×
        partial.normalize();
19221×
        let mut st = snap.base.clone();
19231×
        st.add_unchecked(partial);
1924
        // Every file of the target is rendered: build the graphs the
1925
        // partial snapshot left out.
19261×
        self.load_all_graphs(&mut st)?;
19271×
        let target = st.materialize();
19281×
        let by_node_target = target.tree.by_node();
19291×
        let by_node_base = snap.base_snapshot.tree.by_node();
19301×
        let attrs = Repo::state_attributes(&target);
19311×
        let mut n = 0;
19321×
        for node in dropped_nodes {
19331×
            match by_node_target.get(&node) {
19341×
                Some(e) => {
19351×
                    let f = &target.files[&e.path];
19361×
                    match &f.content {
19370×
                        FileContent::Dir => {}
19381×
                        FileContent::Text { bytes, .. } => {
19391×
                            let on_disk: std::borrow::Cow<[u8]> = if attrs.lookup(&e.path).eol
19401×
                                == Some(crate::attributes::Eol::Crlf)
1941
                            {
19420×
                                crate::attributes::to_crlf(bytes).into()
1943
                            } else {
19441×
                                bytes.as_slice().into()
1945
                            };
19461×
                            self.write_file(&e.path, &on_disk, f.mode.exec)?;
1947
                        }
19480×
                        FileContent::Opaque { blobs } => {
19490×
                            let bytes = blobs
19500×
                                .first()
19510×
                                .map(|b| self.read_blob(b))
19520×
                                .transpose()?
19530×
                                .unwrap_or_default();
19540×
                            if f.kind == NodeKind::Symlink {
19550×
                                self.write_symlink(&e.path, &bytes)?
1956
                            } else {
19570×
                                self.write_file(&e.path, &bytes, f.mode.exec)?
1958
                            }
1959
                        }
1960
                    }
1961
                    // A discarded rename: the new name goes.
19621×
                    if let Some(old_path) = snap
19631×
                        .statuses
19641×
                        .iter()
19651×
                        .find(|s| {
19661×
                            s.status == ChangeStatus::Renamed && !target.files.contains_key(&s.path)
19671×
                        })
19681×
                        .map(|s| s.path.clone())
19690×
                    {
19700×
                        let _ = fs::remove_file(self.root.join(old_path));
19711×
                    }
19721×
                    n += 1;
1973
                }
1974
                None => {
1975
                    // The node exists in neither target nor base with a live path: an addition to remove.
19760×
                    if let Some(added) = snap.statuses.iter().find(|s| {
19770×
                        s.status == ChangeStatus::Added
19780×
                            && !target.files.contains_key(&s.path)
19790×
                            && !by_node_base.contains_key(&node)
19800×
                    }) {
19810×
                        let full = self.root.join(&added.path);
19820×
                        if full.is_dir() {
19830×
                            let _ = fs::remove_dir_all(&full);
19840×
                        } else {
19850×
                            let _ = fs::remove_file(&full);
19860×
                        }
19870×
                        n += 1;
19880×
                    }
1989
                }
1990
            }
1991
        }
19921×
        self.drop_manifest();
19931×
        Ok(n)
19941×
    }
1995
1996
    /// The diff of the working copy (`None`) or of a change, per file with
1997
    /// line-numbered hunks (spec: `oxy diff --json`).
19987×
    pub fn diff_files(&self, change: Option<&ChangeHash>) -> Result<Vec<FileDiff>> {
19997×
        let (c, base, base_snapshot) = match change {
20003×
            Some(h) => {
20013×
                let c = self.store.get_change(h)?;
20023×
                let (base, snapshot) = self.change_base(&c)?;
20033×
                (c, base, snapshot)
2004
            }
20054×
            None => match self.working_copy_with_base_unless_unchanged()? {
20063×
                Some(all) => all,
20071×
                None => return Ok(Vec::new()),
2008
            },
2009
        };
20106×
        Ok(diff_files_of(&c, &base, &base_snapshot))
20117×
    }
2012
2013
    /// The snapshot a command would take, without taking it, when the
2014
    /// status cache holds: every file is as the last snapshot left it, so
2015
    /// that snapshot's working-copy change is the answer. Its base comes
2016
    /// from the state index, the `.oxyattributes` files from disk. `None`
2017
    /// when a snapshot must be taken, and when there is nothing to commit
2018
    /// (the snapshot then says so). A conflicted base never gets here: the
2019
    /// cache does not hold for one.
2020768×
    pub(crate) fn snapshot_from_cache(&self) -> Result<Option<SnapshotResult>> {
2021768×
        let Some(statuses) = self.status_by_manifest()? else {
2022539×
            return Ok(None);
2023
        };
2024229×
        if statuses.is_empty() {
20253×
            return Ok(None);
2026226×
        }
2027226×
        let _t = crate::timing::phase("snapshot: from the status cache");
2028226×
        let (wc_hash, wc) = self.working_copy()?;
2029226×
        let base = self.load_state_indexed(&wc.deps)?;
2030226×
        let (base, base_snapshot) = self.render_base_for(&wc, base)?;
2031226×
        let attribute_files: Vec<(String, Vec<u8>)> = match self.read_manifest()? {
2032226×
            Some((_, _, m)) => m
2033226×
                .entries
2034226×
                .keys()
2035692×
                .filter(|p| is_attributes(p))
2036226×
                .filter_map(|p| fs::read(self.root.join(p)).ok().map(|b| (p.clone(), b)))
2037226×
                .collect(),
20380×
            None => Vec::new(),
2039
        };
2040226×
        let attributes = crate::attributes::Attributes::from_files(
2041226×
            attribute_files
2042226×
                .iter()
2043226×
                .map(|(p, b)| (p.as_str(), b.as_slice())),
2044
        );
2045226×
        Ok(Some(SnapshotResult {
2046226×
            wc_hash,
2047226×
            wc,
2048226×
            base,
2049226×
            base_snapshot,
2050226×
            statuses,
2051226×
            changed: false,
2052226×
            resolves: false,
2053226×
            contributors: Vec::new(),
2054226×
            attributes,
2055226×
            untracked_nested: self.untracked_nested.borrow().clone(),
2056226×
            manifest: None,
2057226×
        }))
2058768×
    }
2059
2060
    /// The working-copy change with its base state and a snapshot of the
2061
    /// base, for showing what the working copy changes ([`render_change`],
2062
    /// [`diff_files_of`]). While the status cache holds (every file as the
2063
    /// last snapshot left it), the stored working-copy change is the
2064
    /// answer, no snapshot is taken, and the base's snapshot holds its tree
2065
    /// but no file; otherwise a snapshot makes all three.
20662×
    pub fn working_copy_with_base(&self) -> Result<(Change, State, Snapshot)> {
20672×
        match self.working_copy_with_base_unless_unchanged()? {
20681×
            Some(all) => Ok(all),
2069
            None => {
20701×
                let (_, wc) = self.working_copy()?;
20711×
                let base = self.load_state_indexed(&wc.deps)?;
20721×
                let (base, snapshot) = self.tree_base_for(&wc, base)?;
20731×
                Ok((wc, base, snapshot))
2074
            }
2075
        }
20762×
    }
2077
2078
    /// [`Repo::working_copy_with_base`], or `None` when the status cache
2079
    /// holds and the working-copy change changes nothing: its diff is
2080
    /// empty, and the base is not loaded for it (oxygen#94).
20817×
    pub fn working_copy_with_base_unless_unchanged(
20827×
        &self,
20837×
    ) -> Result<Option<(Change, State, Snapshot)>> {
20847×
        if self.status_by_manifest()?.is_some() {
20855×
            let (_, wc) = self.working_copy()?;
20865×
            if wc.tree_ops.is_empty() && wc.edits.is_empty() {
20873×
                return Ok(None);
20882×
            }
20892×
            let base = self.load_state_indexed(&wc.deps)?;
20902×
            let (base, snapshot) = self.tree_base_for(&wc, base)?;
20912×
            return Ok(Some((wc, base, snapshot)));
20922×
        }
20932×
        let snap = self.snapshot_status("oxy diff")?;
20942×
        Ok(Some((snap.wc, snap.base, snap.base_snapshot)))
20957×
    }
2096
2097
    /// The log restricted to changes touching `path` (its node, so renames
2098
    /// are followed), on the current bookmark.
20996×
    pub fn log_for_path(&self, path: &str) -> Result<Vec<LogEntry>> {
21006×
        let heads = self.bookmark_heads()?;
21016×
        if self.is_bare() {
21021×
            return self.log_for_path_in(path, &heads);
21035×
        }
21045×
        let entries = self.log()?;
21055×
        let (_, wc) = self.working_copy()?;
2106
        // The path's node from the trees alone: the base's (from the
2107
        // workspace's state index), else the bookmark's. Nothing is
2108
        // rendered.
21095×
        let node_in = |mut state: State| -> Result<Option<HashSet<NodeId>>> {
21105×
            Ok(nodes_at(&self.tree_view(&mut state)?, path))
21115×
        };
21125×
        let nodes = match node_in(self.load_state_indexed(&wc.deps)?)? {
21135×
            Some(n) => Some(n),
21140×
            None => node_in(self.load_state_history(&heads)?)?,
2115
        };
21165×
        let Some(nodes) = nodes else {
21170×
            return fail(format!("{path} is not tracked"));
2118
        };
21195×
        Ok(self.entries_touching_up_to(entries, nodes, None))
21206×
    }
2121
2122
    /// The log of the state with these heads restricted to changes touching
2123
    /// `path` (its node, so renames are followed).
21242×
    pub fn log_for_path_in(&self, path: &str, heads: &[ChangeHash]) -> Result<Vec<LogEntry>> {
21252×
        self.log_for_path_of(&self.load_state_history(heads)?, path, None)
21262×
    }
2127
2128
    /// The changes of a loaded state touching `path`, newest first, at most
2129
    /// `limit` of them. The path is found in the state's tree alone, so no
2130
    /// file is rendered, and the walk stops once `limit` are found.
21315×
    pub fn log_for_path_of(
21325×
        &self,
21335×
        state: &State,
21345×
        path: &str,
21355×
        limit: Option<usize>,
21365×
    ) -> Result<Vec<LogEntry>> {
21375×
        let Some(nodes) = nodes_at(&state.view(), path) else {
21381×
            return fail(format!("{path} is not in that state"));
2139
        };
21404×
        Ok(self.entries_touching_up_to(self.log_of(state), nodes, limit))
21415×
    }
2142
21439×
    fn entries_touching_up_to(
21449×
        &self,
21459×
        entries: Vec<LogEntry>,
21469×
        wanted: HashSet<NodeId>,
21479×
        limit: Option<usize>,
21489×
    ) -> Vec<LogEntry> {
21499×
        let mut touched = self.touched();
21509×
        if limit.is_none() {
21518×
            let hashes: Vec<ChangeHash> = entries.iter().map(|e| e.hash).collect();
21528×
            touched.fill(self, &hashes);
21531×
        }
21549×
        let mut out = Vec::new();
215532×
        for e in entries {
215632×
            if limit.is_some_and(|n| out.len() >= n) {
21571×
                break;
215831×
            }
215931×
            if touched.touches(self, &e.hash, &wanted) {
216020×
                out.push(e);
216120×
            }
2162
        }
21639×
        touched.save();
21649×
        out
21659×
    }
2166
}
2167
2168
/// The node at `path` in `view`, with the nodes it shows as one with it
2169
/// (identical additions, spec §9.2): the file's history is all of theirs.
217010×
fn nodes_at(view: &crate::tree::TreeView, path: &str) -> Option<HashSet<NodeId>> {
217110×
    let node = view.entries.get(path)?.node;
21729×
    let mut out = HashSet::from([node]);
21739×
    out.extend(
21749×
        view.unified
21759×
            .iter()
21769×
            .filter(|(_, shown)| **shown == node)
21779×
            .map(|(dup, _)| *dup),
2178
    );
21799×
    Some(out)
218010×
}
2181
2182
/// Per-file hunks of `change` against `base`.
21836×
pub fn diff_files_of(change: &Change, base: &State, base_snapshot: &Snapshot) -> Vec<FileDiff> {
21846×
    let by_node = base_snapshot.tree.by_node();
21856×
    let mut new_names: HashMap<NodeId, (NodeId, String, NodeKind)> = HashMap::new();
21866×
    for op in &change.tree_ops {
2187
        if let TreeOp::AddNode {
21882×
            node,
21892×
            parent,
21902×
            name,
21912×
            kind,
2192
            ..
21933×
        } = op
21942×
        {
21952×
            new_names.insert(*node, (*parent, name.clone(), *kind));
21962×
        }
2197
    }
219810×
    let path_of = |n: &NodeId| -> String {
219910×
        path_of_node(n, &by_node, &new_names).unwrap_or_else(|| format!("<node {}>", n.short(8)))
220010×
    };
22016×
    let mut files: BTreeMap<NodeId, FileDiff> = BTreeMap::new();
22026×
    let mut order: Vec<NodeId> = Vec::new();
220315×
    let mut entry = |files: &mut BTreeMap<NodeId, FileDiff>, n: NodeId, kind: &str| {
220415×
        if let std::collections::btree_map::Entry::Vacant(v) = files.entry(n) {
220510×
            order.push(n);
220610×
            v.insert(FileDiff {
220710×
                path: path_of(&n),
220810×
                kind: kind.to_string(),
220910×
                hunks: vec![],
221010×
                from: None,
221110×
            });
221210×
        }
221315×
    };
22146×
    for op in change
22156×
        .tree_ops
22166×
        .iter()
22176×
        .filter(|o| !is_unified_retirement(o, base_snapshot))
2218
    {
22193×
        match op {
22202×
            TreeOp::AddNode { node, kind, .. } => {
22212×
                if *kind != NodeKind::Dir {
22222×
                    entry(&mut files, *node, "added");
22232×
                }
2224
            }
22251×
            TreeOp::RemoveNode { node, .. } => {
22261×
                entry(&mut files, *node, "removed");
22271×
                if let Some(e) = by_node.get(node) {
22281×
                    files.get_mut(node).unwrap().path = e.path.clone();
22291×
                }
2230
            }
2231
            TreeOp::Move {
22320×
                node, parent, name, ..
2233
            } => {
22340×
                entry(&mut files, *node, "renamed");
22350×
                let f = files.get_mut(node).unwrap();
22360×
                f.from = by_node.get(node).map(|e| e.path.clone());
22370×
                let dir = if parent.is_root() {
22380×
                    String::new()
2239
                } else {
22400×
                    path_of_node(parent, &by_node, &new_names).unwrap_or_default()
2241
                };
22420×
                f.path = if dir.is_empty() {
22430×
                    name.clone()
2244
                } else {
22450×
                    format!("{dir}/{name}")
2246
                };
2247
            }
22480×
            TreeOp::SetMode { node, .. } => entry(&mut files, *node, "mode"),
2249
        }
2250
    }
2251
    // Base line numbers per node, 1-based.
22526×
    let mut line_of: HashMap<NodeId, HashMap<(ChangeHash, u32), u32>> = HashMap::new();
225312×
    let mut lines_for = |n: &NodeId| -> HashMap<(ChangeHash, u32), u32> {
225412×
        line_of
225512×
            .entry(*n)
225612×
            .or_insert_with(|| {
22579×
                base.live_lines(n)
22589×
                    .into_iter()
22599×
                    .enumerate()
226012×
                    .map(|(i, (k, _))| (k, i as u32 + 1))
22619×
                    .collect()
22629×
            })
226312×
            .clone()
226412×
    };
226512×
    for e in &change.edits {
226612×
        let n = e.node();
226712×
        let is_new = new_names.contains_key(&n);
226812×
        entry(&mut files, n, if is_new { "added" } else { "modified" });
226912×
        let f = files.get_mut(&n).unwrap();
227012×
        match e {
227110×
            Edit::Insert { after, lines, .. } => {
227210×
                let map = lines_for(&n);
227310×
                let base_line = match after {
22743×
                    AtomRef::Start => 0,
22750×
                    AtomRef::End => map.len() as u32,
22767×
                    AtomRef::Atom { change, index } if change.is_zero() => {
22770×
                        f.hunks.last().map(|h| h.base_line).unwrap_or(0)
2278
                    }
22797×
                    AtomRef::Atom { change, index } => {
22807×
                        map.get(&(*change, *index)).copied().unwrap_or(0)
2281
                    }
2282
                };
228310×
                f.hunks.push(DiffHunk {
228410×
                    base_line,
228510×
                    added: lines.to_vec(),
228610×
                    removed: vec![],
228710×
                });
2288
            }
22892×
            Edit::Delete { atoms, .. } => {
22902×
                let map = lines_for(&n);
22912×
                let mut removed = Vec::new();
22922×
                for r in atoms {
22932×
                    for i in r.from..r.to {
22942×
                        let line = map.get(&(r.change, i)).copied().unwrap_or(0);
22952×
                        let text = base
22962×
                            .file(&n)
22972×
                            .and_then(|g| g.content(&(r.change, i)))
22982×
                            .unwrap_or(b"")
22992×
                            .to_vec();
23002×
                        removed.push((line, text));
2301
                    }
2302
                }
23032×
                let base_line = removed
23042×
                    .first()
23052×
                    .map(|(l, _)| l.saturating_sub(1))
23062×
                    .unwrap_or(0);
23072×
                f.hunks.push(DiffHunk {
23082×
                    base_line,
23092×
                    added: vec![],
23102×
                    removed,
23112×
                });
2312
            }
2313
            Edit::Replace { .. } => {
23140×
                if !is_new {
23150×
                    f.kind = "replaced".into();
23160×
                }
2317
            }
2318
        }
2319
    }
232010×
    order.into_iter().filter_map(|n| files.remove(&n)).collect()
23216×
}
2322
2323
/// Builds the tree ops and edits of a working-copy change against a base.
2324
/// `BLAKE3("oxy node 1" 0 seed kind path)`, truncated: a node identifier
2325
/// that the same seed and path always give (never the root's).
232659×
fn seeded_node(seed: &[u8; 32], path: &str, kind: NodeKind) -> NodeId {
232759×
    let mut h = blake3::Hasher::new();
232859×
    h.update(b"oxy node 1\0");
232959×
    h.update(seed);
233059×
    h.update(&[match kind {
233145×
        NodeKind::File => 1,
233213×
        NodeKind::Dir => 2,
23330×
        NodeKind::Symlink => 3,
23341×
        NodeKind::Subrepo => 4,
2335
    }]);
233659×
    h.update(path.as_bytes());
233759×
    let mut id = [0u8; 16];
233859×
    id.copy_from_slice(&h.finalize().as_bytes()[..16]);
233959×
    if id == [0; 16] {
23400×
        id[15] = 1;
234159×
    }
234259×
    NodeId(id)
234359×
}
2344
2345
struct ChangeBuilder<'a> {
2346
    base: &'a State,
2347
    base_snapshot: &'a Snapshot,
2348
    tree_ops: Vec<TreeOp>,
2349
    edits: Vec<Edit>,
2350
    statuses: Vec<PathStatus>,
2351
    dir_nodes: HashMap<String, NodeId>,
2352
    reuse: HashMap<String, (NodeId, NodeKind)>,
2353
    /// Changes that contributed to conflicts this working copy resolves.
2354
    contributors: BTreeSet<ChangeHash>,
2355
    resolves: bool,
2356
    attrs: crate::attributes::Attributes,
2357
    blobs: HashMap<String, ObjectRef>,
2358
    /// Opaque files whose replace conflict the content settles.
2359
    resolve: HashSet<String>,
2360
    /// When set, new nodes' identifiers derive from it and their paths.
2361
    node_seed: Option<[u8; 32]>,
2362
    /// For a Git import, the base's dead directories by where they were
2363
    /// (see `ensure_dir`), worked out when first needed.
2364
    dead_dirs: Option<HashMap<(NodeId, String), (NodeId, crate::tree::OpKey)>>,
2365
    /// Text edits of edited files, worked out in parallel beforehand
2366
    /// (`diff_in_parallel`); a file not here is diffed when it is updated.
2367
    diffs: HashMap<String, Vec<Edit>>,
2368
}
2369
2370
impl<'a> ChangeBuilder<'a> {
23712319×
    fn new(
23722319×
        base: &'a State,
23732319×
        base_snapshot: &'a Snapshot,
23742319×
        reuse: HashMap<String, (NodeId, NodeKind)>,
23752319×
    ) -> Self {
23762319×
        let mut dir_nodes: HashMap<String, NodeId> = HashMap::new();
23772319×
        dir_nodes.insert(String::new(), NodeId::ROOT);
237818009×
        for (p, e) in base_snapshot.tree.entries.iter() {
237918009×
            if e.kind == NodeKind::Dir {
2380561×
                dir_nodes.insert(p.clone(), e.node);
238117448×
            }
2382
        }
23832319×
        ChangeBuilder {
23842319×
            base,
23852319×
            base_snapshot,
23862319×
            tree_ops: vec![],
23872319×
            edits: vec![],
23882319×
            statuses: vec![],
23892319×
            dir_nodes,
23902319×
            reuse,
23912319×
            contributors: BTreeSet::new(),
23922319×
            resolves: false,
23932319×
            attrs: crate::attributes::Attributes::default(),
23942319×
            blobs: HashMap::new(),
23952319×
            resolve: HashSet::new(),
23962319×
            node_seed: None,
23972319×
            dead_dirs: None,
23982319×
            diffs: HashMap::new(),
23992319×
        }
24002319×
    }
2401
2402
    /// Diff the edited text files among `entries` against their base
2403
    /// renderings at once, on every core, for `update_path` to take: the
2404
    /// same diff it would make, only not one file after another.
24052319×
    fn diff_in_parallel(&mut self, entries: &BTreeMap<String, FsEntry>) {
2406
        use rayon::prelude::*;
24072319×
        let files = &self.base_snapshot.files;
24082319×
        let edited: Vec<(&String, &FsEntry, &crate::state::FileState)> = entries
24092319×
            .iter()
241019202×
            .filter_map(|(p, e)| {
241119202×
                let x = files.get(p)?;
241212985×
                (x.kind == e.kind && !e.unchanged && !self.opaque_for(p, e)).then_some((p, e, x))
241319202×
            })
24142319×
            .collect();
2415
        // Below this, starting the threads costs more than it saves.
24162319×
        if edited.len() < 16 {
24172309×
            return;
241810×
        }
241910×
        let this = &*self;
242010×
        let attrs = &this.attrs;
242110×
        let diffs: Vec<(String, Vec<Edit>)> = edited
242210×
            .par_iter()
24235560×
            .filter_map(|(p, e, x)| {
2424
                let FileContent::Text {
24255560×
                    bytes,
24265560×
                    materialized,
24275560×
                } = &x.content
2428
                else {
24290×
                    return None;
2430
                };
24315560×
                if materialized.is_conflicted() {
24320×
                    return None;
24335560×
                }
24345560×
                let disk_text = if attrs.lookup(p).eol.is_some() {
24350×
                    std::sync::Arc::new(crate::attributes::normalize_eol(&e.content))
2436
                } else {
24375560×
                    e.content.clone()
2438
                };
24395560×
                if *bytes == *disk_text {
24405480×
                    return None;
244180×
                }
244280×
                let keys = materialized.live_atoms();
244380×
                let lines = crate::diff::split_lines(bytes);
244480×
                (keys.len() == lines.len()).then(|| {
244580×
                    let edits = crate::diff::text_edits_of(x.node, &keys, &lines, &disk_text);
244680×
                    ((*p).clone(), edits)
244780×
                })
24485560×
            })
244910×
            .collect();
245010×
        self.diffs = diffs.into_iter().collect();
24512319×
    }
2452
24532319×
    fn with_attributes(mut self, attrs: crate::attributes::Attributes) -> Self {
24542319×
        self.attrs = attrs;
24552319×
        self
24562319×
    }
2457
2458
    /// Whether a file is opaque: forced by `binary`, forced text by `text`
2459
    /// only when it has no NUL bytes, else sniffed.
2460
    /// The blob for an opaque entry: the cached one, else stored now.
2461174×
    fn blob_of(
2462174×
        &mut self,
2463174×
        repo: &Repo,
2464174×
        path: &str,
2465174×
        e: &FsEntry,
2466174×
        nocompress: bool,
2467174×
    ) -> Result<ObjectRef> {
2468174×
        let b = match e.blob {
24690×
            Some(b) => b,
2470174×
            None => repo.store_blob_for(&e.content, nocompress)?,
2471
        };
2472174×
        self.blobs.insert(path.to_string(), b);
2473174×
        Ok(b)
2474174×
    }
2475
247623696×
    fn opaque_for(&self, path: &str, e: &FsEntry) -> bool {
247723696×
        if e.blob.is_some() {
24784×
            return true;
247923692×
        }
248023692×
        if e.kind == NodeKind::Symlink || e.kind == NodeKind::Subrepo {
2481130×
            return true;
248223562×
        }
248323562×
        match self.attrs.lookup(path).binary {
248412×
            Some(true) => true,
24850×
            Some(false) => is_binary(&e.content),
248623550×
            None => is_binary(&e.content),
2487
        }
248823696×
    }
2489
2490
    /// Text content as stored: `\r\n` normalized for `eol=` files.
249114803×
    fn stored_text(
249214803×
        &self,
249314803×
        path: &str,
249414803×
        content: &std::sync::Arc<Vec<u8>>,
249514803×
    ) -> std::sync::Arc<Vec<u8>> {
249614803×
        if self.attrs.lookup(path).eol.is_some() {
24977×
            std::sync::Arc::new(crate::attributes::normalize_eol(content))
2498
        } else {
249914796×
            content.clone()
2500
        }
250114803×
    }
2502
2503
    /// The identifier of a node added at `path`: reused when asked, derived
2504
    /// from the seed when there is one, random otherwise.
25056341×
    fn new_node(&self, path: &str, kind: NodeKind) -> NodeId {
25066341×
        if let Some(n) = self.reused_node(path, kind) {
2507166×
            return n;
25086175×
        }
25096175×
        match &self.node_seed {
251059×
            Some(seed) => seeded_node(seed, path, kind),
25116116×
            None => NodeId::random(),
2512
        }
25136341×
    }
2514
25156341×
    fn reused_node(&self, path: &str, kind: NodeKind) -> Option<NodeId> {
25166341×
        self.reuse
25176341×
            .get(path)
25186341×
            .filter(|(_, k)| *k == kind)
25196341×
            .map(|(n, _)| *n)
25206341×
    }
2521
2522
    /// A dead directory last placed at (`parent`, `name`) in the base.
252315×
    fn revivable_dir(
252415×
        &mut self,
252515×
        parent: NodeId,
252615×
        name: &str,
252715×
    ) -> Option<(NodeId, crate::tree::OpKey)> {
252815×
        let base = self.base;
252915×
        self.dead_dirs
253015×
            .get_or_insert_with(|| base.tree().dead_dirs())
253115×
            .get(&(parent, name.to_string()))
253215×
            .copied()
253315×
    }
2534
25356218×
    fn ensure_dir(&mut self, path: &str) -> NodeId {
25366218×
        if let Some(n) = self.dir_nodes.get(path) {
25376064×
            return *n;
2538154×
        }
2539154×
        let mut parent = NodeId::ROOT;
2540154×
        let mut prefix = String::new();
2541173×
        for comp in path.split('/') {
2542173×
            if !prefix.is_empty() {
254319×
                prefix.push('/');
2544154×
            }
2545173×
            prefix.push_str(comp);
2546173×
            let known = self.dir_nodes.get(&prefix).copied();
2547173×
            let revive = match known {
254813×
                Some(_) => None,
2549160×
                None if self.node_seed.is_some() => self.revivable_dir(parent, comp),
2550145×
                None => None,
2551
            };
2552173×
            parent = match (known, revive) {
255313×
                (Some(n), _) => n,
25542×
                (None, Some((node, old))) => {
2555
                    // Git has no identity for a directory: one that comes
2556
                    // back where it was is the same directory, brought back
2557
                    // with a move, so lines of history that placed files in
2558
                    // it before and after agree (oxygen#30).
25592×
                    self.tree_ops.push(TreeOp::Move {
25602×
                        node,
25612×
                        old: OpRef {
25622×
                            change: old.0,
25632×
                            index: old.1,
25642×
                        },
25652×
                        parent,
25662×
                        name: comp.to_string(),
25672×
                    });
25682×
                    self.dir_nodes.insert(prefix.clone(), node);
25692×
                    node
2570
                }
2571
                (None, None) => {
2572158×
                    let node = self.new_node(&prefix, NodeKind::Dir);
2573158×
                    self.tree_ops.push(TreeOp::AddNode {
2574158×
                        node,
2575158×
                        kind: NodeKind::Dir,
2576158×
                        mode: Mode::default(),
2577158×
                        parent,
2578158×
                        name: comp.to_string(),
2579158×
                    });
2580158×
                    self.dir_nodes.insert(prefix.clone(), node);
2581158×
                    node
2582
                }
2583
            };
2584
        }
2585154×
        parent
25866218×
    }
2587
25886183×
    fn add_path(&mut self, repo: &Repo, path: &str, e: &FsEntry) -> Result<()> {
25896183×
        let (dir, name) = split_path(path);
25906183×
        let parent = self.ensure_dir(dir);
25916183×
        let node = self.new_node(path, e.kind);
25926183×
        let opaque = self.opaque_for(path, e);
25936183×
        let nocompress = self.attrs.lookup(path).nocompress;
25946183×
        self.tree_ops.push(TreeOp::AddNode {
25956183×
            node,
25966183×
            kind: e.kind,
25976183×
            mode: Mode {
25986183×
                exec: e.exec,
25996183×
                opaque,
26006183×
            },
26016183×
            parent,
26026183×
            name: name.to_string(),
26036183×
        });
26046183×
        if opaque {
2605125×
            let blob = self.blob_of(repo, path, e, nocompress)?;
2606125×
            self.edits.push(Edit::Replace {
2607125×
                node,
2608125×
                old: None,
2609125×
                new: Some(blob),
2610125×
            });
26116058×
        } else if !e.content.is_empty() {
26126029×
            let content = self.stored_text(path, &e.content);
26136029×
            self.edits.push(Edit::Insert {
26146029×
                node,
26156029×
                after: crate::objects::AtomRef::Start,
26166029×
                before: crate::objects::AtomRef::End,
26176029×
                lines: crate::lines::Lines::split_shared(content),
26186029×
            });
26196029×
        }
26206183×
        self.statuses.push(PathStatus {
26216183×
            path: path.to_string(),
26226183×
            status: ChangeStatus::Added,
26236183×
        });
26246183×
        Ok(())
26256183×
    }
2626
2627
    /// Move the node at `old` to `new` and apply `e`'s content to it.
262835×
    fn move_path(
262935×
        &mut self,
263035×
        repo: &Repo,
263135×
        old: &str,
263235×
        new: &str,
263335×
        e: &FsEntry,
263435×
        expected: &crate::state::FileState,
263535×
    ) -> Result<()> {
263635×
        let placement = self.base_snapshot.tree.entries[old].placement;
263735×
        let (dir, name) = split_path(new);
263835×
        let parent = self.ensure_dir(dir);
263935×
        self.tree_ops.push(TreeOp::Move {
264035×
            node: expected.node,
264135×
            old: op_ref(placement),
264235×
            parent,
264335×
            name: name.to_string(),
264435×
        });
264535×
        for k in self.same_place(&expected.node, placement) {
26460×
            self.tree_ops.push(TreeOp::RemoveNode {
26470×
                node: expected.node,
26480×
                placement: op_ref(k),
26490×
            });
26500×
        }
265135×
        self.update_path(repo, old, e, expected)?;
2652
        // update_path reports under the old path; the rename is what the user sees.
265335×
        self.statuses.retain(|s| s.path != old);
265435×
        self.statuses.push(PathStatus {
265535×
            path: new.to_string(),
265635×
            status: ChangeStatus::Renamed,
265735×
        });
265835×
        Ok(())
265935×
    }
2660
2661
    /// For a Git import: a node the commit keeps is in one place, the one
2662
    /// its tree names, so any other live placement it has in the base goes;
2663
    /// and a node the tree cannot show at all (an orphan) goes too. Such a
2664
    /// placement is out of sight, under a directory another line of history
2665
    /// removed, where no diff of the tree would ever reach it (oxygen#30).
266688×
    fn retire_stray_placements(&mut self) {
266788×
        let mut retired: HashSet<(ChangeHash, u32)> = HashSet::new();
266888×
        let mut placed: BTreeSet<NodeId> = BTreeSet::new();
266999×
        for op in &self.tree_ops {
267099×
            match op {
267119×
                TreeOp::Move { node, old, .. } => {
267219×
                    retired.insert((old.change, old.index));
267319×
                    placed.insert(*node);
267419×
                }
267521×
                TreeOp::RemoveNode { placement, .. } => {
267621×
                    retired.insert((placement.change, placement.index));
267721×
                }
267859×
                TreeOp::AddNode { .. } | TreeOp::SetMode { .. } => {}
2679
            }
2680
        }
2681
        // Nodes kept where they were: what the base's tree view shows and
2682
        // this change neither moves nor removes.
268388×
        let mut kept: HashMap<NodeId, (ChangeHash, u32)> = HashMap::new();
2684241×
        for e in self.base_snapshot.tree.entries.values() {
2685241×
            if !retired.contains(&e.placement) {
2686204×
                kept.insert(e.node, e.placement);
2687204×
            }
2688
        }
2689
        // Only a node with several live placements can have a stray one,
2690
        // and the tree view names each as a conflict.
269188×
        let multi: BTreeSet<NodeId> = self
269288×
            .base_snapshot
269388×
            .tree
269488×
            .conflicts
269588×
            .iter()
269688×
            .filter_map(|c| match c {
26971×
                crate::tree::TreeConflict::MultiPlacement { node, .. } => Some(*node),
26986×
                _ => None,
26997×
            })
270088×
            .collect();
270188×
        let mut extra = Vec::new();
2702
        // A node whose only placements are under a directory another line
2703
        // removed (an orphan) is nowhere the tree can show, and Git's tree
2704
        // has no such path: it goes.
270588×
        for c in &self.base_snapshot.tree.conflicts {
27067×
            let crate::tree::TreeConflict::Orphan { node, .. } = c else {
27076×
                continue;
2708
            };
27091×
            if kept.contains_key(node) || placed.contains(node) {
27100×
                continue;
27111×
            }
27121×
            for (k, _) in self.base.tree().live_placements(node) {
27131×
                if retired.insert(k) {
27141×
                    extra.push(TreeOp::RemoveNode {
27151×
                        node: *node,
27161×
                        placement: op_ref(k),
27171×
                    });
27181×
                }
2719
            }
2720
        }
272188×
        for node in placed
272288×
            .iter()
272388×
            .chain(multi.iter().filter(|n| kept.contains_key(*n)))
2724
        {
272519×
            for (k, _) in self.base.tree().live_placements(node) {
272618×
                if retired.contains(&k) || kept.get(node) == Some(&k) {
272717×
                    continue;
27281×
                }
27291×
                retired.insert(k);
27301×
                extra.push(TreeOp::RemoveNode {
27311×
                    node: *node,
27321×
                    placement: op_ref(k),
27331×
                });
2734
            }
2735
        }
273688×
        if !extra.is_empty() {
27372×
            self.resolves = true;
27382×
            self.tree_ops.extend(extra);
273986×
        }
274088×
    }
2741
2742
    /// Nodes the base shows as one with another (identical additions at one
2743
    /// path, spec §9.2) are retired by the change that first touches the
2744
    /// node shown: edited, moved, removed or given a mode alone, it would
2745
    /// differ from them and the name conflict would come back. Nothing
2746
    /// else changes for the user, so no status reports it.
27472319×
    fn retire_unified(&mut self) {
27482319×
        let unified = &self.base_snapshot.tree.unified;
27492319×
        if unified.is_empty() {
27502298×
            return;
275121×
        }
275221×
        let touched: HashSet<NodeId> = self
275321×
            .tree_ops
275421×
            .iter()
275521×
            .map(|o| o.node())
275622×
            .chain(self.edits.iter().map(|e| e.node()))
275721×
            .collect();
275821×
        let mut retired: HashSet<(ChangeHash, u32)> = HashSet::new();
275921×
        for op in &self.tree_ops {
276014×
            match op {
27613×
                TreeOp::Move { old, .. } => {
27623×
                    retired.insert((old.change, old.index));
27633×
                }
27643×
                TreeOp::RemoveNode { placement, .. } => {
27653×
                    retired.insert((placement.change, placement.index));
27663×
                }
27678×
                TreeOp::AddNode { .. } | TreeOp::SetMode { .. } => {}
2768
            }
2769
        }
277021×
        let mut extra = Vec::new();
277122×
        for (dup, shown) in unified {
277222×
            if !touched.contains(shown) {
27735×
                continue;
277417×
            }
277517×
            for (k, _) in self.base.tree().live_placements(dup) {
277617×
                if retired.insert(k) {
277717×
                    extra.push(TreeOp::RemoveNode {
277817×
                        node: *dup,
277917×
                        placement: op_ref(k),
278017×
                    });
278117×
                }
2782
            }
2783
        }
278421×
        self.tree_ops.extend(extra);
27852319×
    }
2786
2787
    /// The node's other live placements at the same place as `k`, the one
2788
    /// the tree shows: two lines of history that put a node back where it
2789
    /// was each leave a placement, and the tree shows them as one file. A
2790
    /// change that removes or moves it retires them together, or the copy
2791
    /// left behind outlives its directory (oxygen#88).
2792151×
    fn same_place(&self, node: &NodeId, k: (ChangeHash, u32)) -> Vec<(ChangeHash, u32)> {
2793151×
        let tree = self.base.tree();
2794151×
        let Some(shown) = tree.placement(&k) else {
27950×
            return Vec::new();
2796
        };
2797151×
        tree.live_placements(node)
2798151×
            .into_iter()
2799153×
            .filter(|(o, p)| *o != k && p.parent == shown.parent && p.name == shown.name)
2800151×
            .map(|(o, _)| o)
2801151×
            .collect()
2802151×
    }
2803
2804116×
    fn remove_path(&mut self, path: &str, expected: &crate::state::FileState) {
2805116×
        let entry = &self.base_snapshot.tree.entries[path];
2806116×
        let placement = entry.placement;
2807116×
        self.tree_ops.push(TreeOp::RemoveNode {
2808116×
            node: expected.node,
2809116×
            placement: op_ref(placement),
2810116×
        });
2811116×
        for k in self.same_place(&expected.node, placement) {
28121×
            self.tree_ops.push(TreeOp::RemoveNode {
28131×
                node: expected.node,
28141×
                placement: op_ref(k),
28151×
            });
28161×
        }
2817116×
        if path.contains(".oxy-conflict-") || expected.is_conflicted() {
28187×
            self.resolves = true;
2819109×
        }
2820116×
        self.statuses.push(PathStatus {
2821116×
            path: path.to_string(),
2822116×
            status: ChangeStatus::Removed,
2823116×
        });
2824116×
    }
2825
282613020×
    fn update_path(
282713020×
        &mut self,
282813020×
        repo: &Repo,
282913020×
        path: &str,
283013020×
        e: &FsEntry,
283113020×
        expected: &crate::state::FileState,
283213020×
    ) -> Result<()> {
283313020×
        if expected.kind != e.kind {
28341×
            self.remove_path(path, expected);
28351×
            self.statuses.pop();
28361×
            self.add_path(repo, path, e)?;
28371×
            self.statuses.pop();
28381×
            self.statuses.push(PathStatus {
28391×
                path: path.to_string(),
28401×
                status: ChangeStatus::Modified,
28411×
            });
28421×
            return Ok(());
284313019×
        }
284413019×
        let entry = &self.base_snapshot.tree.entries[path];
284513019×
        let node = expected.node;
284613019×
        let mode_atom = entry.mode_atom.map(op_ref);
284713019×
        if e.unchanged {
2848
            // Known equal to the base's unconflicted rendering (spec
2849
            // §12.3); only the executable bit can differ.
28504245×
            if e.exec != expected.mode.exec {
28513×
                if let Some(old) = mode_atom {
28523×
                    self.tree_ops.push(TreeOp::SetMode {
28533×
                        node,
28543×
                        old,
28553×
                        mode: Mode {
28563×
                            exec: e.exec,
28573×
                            opaque: false,
28583×
                        },
28593×
                    });
28603×
                    self.statuses.push(PathStatus {
28613×
                        path: path.to_string(),
28623×
                        status: ChangeStatus::ModeChanged,
28633×
                    });
28643×
                }
28654242×
            }
28664245×
            return Ok(());
28678774×
        }
28688774×
        let mut status: Option<ChangeStatus> = None;
28698774×
        let wants_opaque = self.opaque_for(path, e);
28708774×
        let nocompress = self.attrs.lookup(path).nocompress;
28718774×
        let disk_text = self.stored_text(path, &e.content);
28728774×
        match &expected.content {
28730×
            FileContent::Dir => {}
2874
            FileContent::Text {
28758508×
                bytes,
28768508×
                materialized,
2877
            } => {
28788508×
                if materialized.is_conflicted() {
287951×
                    if bytes == &*disk_text {
28809×
                        return Ok(());
288142×
                    }
288242×
                    let regions = self.base.conflict_regions(&node);
288342×
                    let plain: Vec<&[u8]> =
288493×
                        regions.plain.iter().map(|(_, l)| l.as_slice()).collect();
288542×
                    if has_own_conflict_markers(&e.content, bytes, &plain) {
28865×
                        self.statuses.push(PathStatus {
28875×
                            path: path.to_string(),
28885×
                            status: ChangeStatus::ConflictEdited,
28895×
                        });
28905×
                        return Ok(());
289137×
                    }
2892
                    // Resolution (spec §9.6): diff against the unconflicted lines
2893
                    // with each region as a gap, then retire every region atom.
2894
                    // Whatever the author kept from a region is re-inserted as
2895
                    // new atoms, which leaves the graph totally ordered.
289637×
                    let mut edits = text_edits(node, &regions.plain, &disk_text);
289737×
                    if !regions.region_atoms.is_empty() {
289837×
                        edits.insert(
289937×
                            0,
290037×
                            Edit::Delete {
290137×
                                node,
290237×
                                atoms: ranges(&regions.region_atoms),
290337×
                            },
290437×
                        );
290537×
                    }
290637×
                    self.edits.extend(edits);
290737×
                    self.contributors.extend(regions.contributors);
290837×
                    self.resolves = true;
290937×
                    if e.exec != expected.mode.exec {
29100×
                        if let Some(old) = mode_atom {
29110×
                            self.tree_ops.push(TreeOp::SetMode {
29120×
                                node,
29130×
                                old,
29140×
                                mode: Mode {
29150×
                                    exec: e.exec,
29160×
                                    opaque: false,
29170×
                                },
29180×
                            });
29190×
                        }
292037×
                    }
292137×
                    self.statuses.push(PathStatus {
292237×
                        path: path.to_string(),
292337×
                        status: ChangeStatus::Resolved,
292437×
                    });
292537×
                    return Ok(());
29268457×
                }
29278457×
                if wants_opaque {
2928
                    // Text → opaque (spec §7.5), by content or by attribute.
29292×
                    if let Some(old) = mode_atom {
29302×
                        self.tree_ops.push(TreeOp::SetMode {
29312×
                            node,
29322×
                            old,
29332×
                            mode: Mode {
29342×
                                exec: e.exec,
29352×
                                opaque: true,
29362×
                            },
29372×
                        });
29382×
                    }
29392×
                    let live: Vec<_> = repo_live_keys(self.base, &node);
29402×
                    if !live.is_empty() {
29412×
                        self.edits.push(Edit::Delete {
29422×
                            node,
29432×
                            atoms: ranges(&live),
29442×
                        });
29452×
                    }
29462×
                    let blob = self.blob_of(repo, path, e, nocompress)?;
29472×
                    self.edits.push(Edit::Replace {
29482×
                        node,
29492×
                        old: None,
29502×
                        new: Some(blob),
29512×
                    });
29522×
                    status = Some(ChangeStatus::Modified);
29538455×
                } else if bytes != &*disk_text {
2954855×
                    let mut laps = crate::timing::Laps::start();
2955
                    // The base's rendering holds its live atoms in order,
2956
                    // one per line (it is not conflicted here).
2957855×
                    let edits = match self.diffs.remove(path) {
295880×
                        Some(edits) => edits,
2959
                        None => {
2960775×
                            let keys = materialized.live_atoms();
2961775×
                            let lines = crate::diff::split_lines(bytes);
2962775×
                            if keys.len() == lines.len() {
2963775×
                                crate::diff::text_edits_of(node, &keys, &lines, &disk_text)
2964
                            } else {
29650×
                                text_edits(node, &self.base.live_lines(&node), &disk_text)
2966
                            }
2967
                        }
2968
                    };
2969855×
                    laps.lap("build: text diff");
2970855×
                    if !edits.is_empty() {
2971855×
                        self.edits.extend(edits);
2972855×
                        status = Some(ChangeStatus::Modified);
2973855×
                    }
29747600×
                }
29758457×
                let switched_to_opaque = wants_opaque;
29768457×
                if !switched_to_opaque && e.exec != expected.mode.exec {
29774×
                    if let Some(old) = mode_atom {
29784×
                        self.tree_ops.push(TreeOp::SetMode {
29794×
                            node,
29804×
                            old,
29814×
                            mode: Mode {
29824×
                                exec: e.exec,
29834×
                                opaque: false,
29844×
                            },
29854×
                        });
29864×
                        status.get_or_insert(ChangeStatus::ModeChanged);
29874×
                    }
29888453×
                }
2989
            }
2990266×
            FileContent::Opaque { blobs } => {
2991266×
                let new_ref = e.blob.unwrap_or_else(|| Repo::blob_ref(&e.content));
2992266×
                if e.kind == NodeKind::File && wants_opaque {
2993213×
                    // Unchanged or replaced, the file stays opaque: remember its blob.
2994213×
                    self.blobs.insert(path.to_string(), new_ref);
2995213×
                }
2996266×
                if blobs.len() > 1 && self.resolve.contains(path) && e.kind == expected.kind {
2997
                    // Settle the replace conflict (spec §9.3): replace every
2998
                    // live candidate with the chosen blob, depending on each
2999
                    // change that made one live, so all are superseded.
30005×
                    let chosen = self.blob_of(repo, path, e, nocompress)?;
300110×
                    for b in blobs {
300210×
                        self.edits.push(Edit::Replace {
300310×
                            node,
300410×
                            old: Some(*b),
300510×
                            new: Some(chosen),
300610×
                        });
300710×
                    }
30085×
                    self.contributors
30095×
                        .extend(self.base.blob_contributors(&node, blobs));
30105×
                    self.resolves = true;
30115×
                    self.statuses.push(PathStatus {
30125×
                        path: path.to_string(),
30135×
                        status: ChangeStatus::Resolved,
30145×
                    });
30155×
                    return Ok(());
3016261×
                }
3017261×
                if blobs.len() > 1 {
30186×
                    if !blobs.contains(&new_ref) {
30194×
                        self.statuses.push(PathStatus {
30204×
                            path: path.to_string(),
30214×
                            status: ChangeStatus::ConflictEdited,
30224×
                        });
30234×
                    }
30246×
                    return Ok(());
3025255×
                }
3026255×
                let current = blobs.first().copied();
3027255×
                if current != Some(new_ref) {
302844×
                    if e.kind == NodeKind::File && !wants_opaque {
3029
                        // Opaque → text (spec §7.5).
30302×
                        if let Some(old) = mode_atom {
30312×
                            self.tree_ops.push(TreeOp::SetMode {
30322×
                                node,
30332×
                                old,
30342×
                                mode: Mode {
30352×
                                    exec: e.exec,
30362×
                                    opaque: false,
30372×
                                },
30382×
                            });
30392×
                        }
30402×
                        self.edits.push(Edit::Replace {
30412×
                            node,
30422×
                            old: current,
30432×
                            new: None,
30442×
                        });
30452×
                        if !e.content.is_empty() {
30462×
                            self.edits.push(Edit::Insert {
30472×
                                node,
30482×
                                after: crate::objects::AtomRef::Start,
30492×
                                before: crate::objects::AtomRef::End,
30502×
                                lines: crate::lines::Lines::split(&e.content),
30512×
                            });
30522×
                        }
3053
                    } else {
305442×
                        let blob = self.blob_of(repo, path, e, nocompress)?;
305542×
                        self.edits.push(Edit::Replace {
305642×
                            node,
305742×
                            old: current,
305842×
                            new: Some(blob),
305942×
                        });
3060
                        // New contents and a new executable bit at once: the
3061
                        // bit was dropped (VS Code's inno_updater.exe,
3062
                        // 2018-02-28, lost +x for 49 commits; oxygen#87).
306342×
                        if e.kind == NodeKind::File && e.exec != expected.mode.exec {
30642×
                            if let Some(old) = mode_atom {
30652×
                                self.tree_ops.push(TreeOp::SetMode {
30662×
                                    node,
30672×
                                    old,
30682×
                                    mode: Mode {
30692×
                                        exec: e.exec,
30702×
                                        opaque: true,
30712×
                                    },
30722×
                                });
30732×
                            }
307440×
                        }
3075
                    }
307644×
                    status = Some(ChangeStatus::Modified);
3077211×
                } else if e.kind == NodeKind::File && e.exec != expected.mode.exec {
30780×
                    if let Some(old) = mode_atom {
30790×
                        self.tree_ops.push(TreeOp::SetMode {
30800×
                            node,
30810×
                            old,
30820×
                            mode: Mode {
30830×
                                exec: e.exec,
30840×
                                opaque: true,
30850×
                            },
30860×
                        });
30870×
                        status = Some(ChangeStatus::ModeChanged);
30880×
                    }
3089211×
                }
3090
            }
3091
        }
30928712×
        if let Some(s) = status {
3093905×
            self.statuses.push(PathStatus {
3094905×
                path: path.to_string(),
3095905×
                status: s,
3096905×
            });
30977807×
        }
30988712×
        Ok(())
309913020×
    }
3100
}
3101
31022×
fn repo_live_keys(base: &State, node: &NodeId) -> Vec<crate::graph::AtomKey> {
31032×
    base.live_lines(node).into_iter().map(|(k, _)| k).collect()
31042×
}
3105
3106
/// The changes a change's scope references (spec §8.1): introducers of every
3107
/// atom, placement, and mode it touches, and of every node it operates on.
31082373×
pub fn referenced_changes(change: &Change, base: &State) -> BTreeSet<ChangeHash> {
31092373×
    let mut out = BTreeSet::new();
31102373×
    let opref = |r: &OpRef, out: &mut BTreeSet<ChangeHash>| {
3111203×
        if !r.change.is_zero() {
3112203×
            out.insert(r.change);
3113203×
        }
3114203×
    };
31152373×
    let mut nodes: Vec<NodeId> = Vec::new();
31166762×
    for op in &change.tree_ops {
31176762×
        match op {
31186559×
            TreeOp::AddNode { parent, .. } => nodes.push(*parent),
3119154×
            TreeOp::RemoveNode { node, placement } => {
3120154×
                nodes.push(*node);
3121154×
                opref(placement, &mut out);
3122154×
            }
3123
            TreeOp::Move {
312437×
                node, old, parent, ..
312537×
            } => {
312637×
                nodes.push(*node);
312737×
                nodes.push(*parent);
312837×
                opref(old, &mut out);
312937×
            }
313012×
            TreeOp::SetMode { node, old, .. } => {
313112×
                nodes.push(*node);
313212×
                opref(old, &mut out);
313312×
            }
3134
        }
3135
    }
31368466×
    for e in &change.edits {
31378466×
        nodes.push(e.node());
3138184×
        match e {
31397681×
            Edit::Insert { after, before, .. } => {
314015362×
                for r in [after, before] {
314115362×
                    if let crate::objects::AtomRef::Atom { change, .. } = r {
31422318×
                        if !change.is_zero() {
31432315×
                            out.insert(*change);
31442315×
                        }
314513044×
                    }
3146
                }
3147
            }
3148601×
            Edit::Delete { atoms, .. } => {
3149
                // Deleting an atom also depends on whoever inserted the live
3150
                // atoms right after it: the author saw those insertions, and
3151
                // without the dependency spec §9.1 would call the deletion
3152
                // concurrent with them (a delete/insert conflict).
3153601×
                let graph = base.file(&e.node());
31541165×
                for r in atoms {
31551165×
                    if !r.change.is_zero() {
31561164×
                        out.insert(r.change);
31571164×
                    }
31581165×
                    if let Some(g) = graph {
31591224×
                        for i in r.from..r.to {
31601224×
                            out.extend(
31611224×
                                g.live_successor_changes(&(r.change, i))
31621224×
                                    .into_iter()
31631224×
                                    .filter(|c| !c.is_zero()),
3164
                            );
3165
                        }
31660×
                    }
3167
                }
3168
            }
3169
            // Replacing a blob depends on the change that made it current,
3170
            // as deleting a line depends on the line's introducer.
3171
            Edit::Replace {
317259×
                node,
317359×
                old: Some(old),
3174
                ..
3175
            } => {
317659×
                out.extend(
317759×
                    base.live_replaces(node)
317859×
                        .into_iter()
317976×
                        .filter(|(c, b)| b == old && !c.is_zero())
318059×
                        .map(|(c, _)| c),
3181
                );
3182
            }
3183125×
            Edit::Replace { .. } => {}
3184
        }
3185
    }
318615265×
    for n in nodes {
318715265×
        if let Some(h) = base.tree().introducer(&n) {
31882377×
            out.insert(h);
318912888×
        }
3190
    }
31912373×
    out
31922373×
}
3193
3194
/// Paths of the nodes a change adds on top of `base_snapshot`.
31951492×
pub fn added_node_paths(
31961492×
    change: &Change,
31971492×
    base_snapshot: &Snapshot,
31981492×
) -> HashMap<String, (NodeId, NodeKind)> {
31991492×
    let by_node = base_snapshot.tree.by_node();
32001492×
    let mut new_names: HashMap<NodeId, (NodeId, String, NodeKind)> = HashMap::new();
32011492×
    for op in &change.tree_ops {
3202
        if let TreeOp::AddNode {
320394×
            node,
320494×
            parent,
320594×
            name,
320694×
            kind,
3207
            ..
3208126×
        } = op
320994×
        {
321094×
            new_names.insert(*node, (*parent, name.clone(), *kind));
321194×
        }
3212
    }
32131492×
    let mut out = HashMap::new();
32141492×
    for (node, (_, _, kind)) in &new_names {
321594×
        if let Some(path) = path_of_node(node, &by_node, &new_names) {
321694×
            out.insert(path, (*node, *kind));
321794×
        }
3218
    }
32191492×
    out
32201492×
}
3221
3222
/// Whether `op` retires a node `base_snapshot` shows as one with another
3223
/// (spec §9.2): part of touching that node, never a removal the user made.
322437×
fn is_unified_retirement(op: &TreeOp, base_snapshot: &Snapshot) -> bool {
32258×
    matches!(op, TreeOp::RemoveNode { node, .. } if base_snapshot.tree.unified.contains_key(node))
322637×
}
3227
3228229×
fn path_of_node(
3229229×
    n: &NodeId,
3230229×
    by_node: &HashMap<NodeId, &crate::tree::TreeEntry>,
3231229×
    new_names: &HashMap<NodeId, (NodeId, String, NodeKind)>,
3232229×
) -> Option<String> {
3233229×
    if let Some(e) = by_node.get(n) {
323469×
        return Some(e.path.clone());
3235160×
    }
3236160×
    let mut parts = Vec::new();
3237160×
    let mut cur = *n;
3238
    loop {
3239316×
        if cur.is_root() {
3240143×
            break;
3241173×
        }
3242173×
        if let Some(e) = by_node.get(&cur) {
32430×
            if !e.path.is_empty() {
32440×
                parts.push(e.path.clone());
32450×
            }
32460×
            break;
3247173×
        }
3248173×
        let (parent, name, _) = new_names.get(&cur)?;
3249156×
        parts.push(name.clone());
3250156×
        cur = *parent;
3251
    }
3252143×
    parts.reverse();
3253143×
    Some(parts.join("/"))
3254229×
}
3255
3256
/// Render a change's operations with line content, using `base` for deleted lines.
325733×
pub fn render_change(change: &Change, base: &State, base_snapshot: &Snapshot) -> String {
325833×
    let by_node = base_snapshot.tree.by_node();
325933×
    let mut new_names: HashMap<NodeId, (NodeId, String, NodeKind)> = HashMap::new();
326033×
    for op in &change.tree_ops {
3261
        if let TreeOp::AddNode {
326216×
            node,
326316×
            parent,
326416×
            name,
326516×
            kind,
3266
            ..
326724×
        } = op
326816×
        {
326916×
            new_names.insert(*node, (*parent, name.clone(), *kind));
327016×
        }
3271
    }
327273×
    let path_of = |n: &NodeId| -> String {
327373×
        path_of_node(n, &by_node, &new_names).unwrap_or_else(|| format!("<node {}>", n.short(8)))
327473×
    };
3275
327633×
    let mut out = String::new();
327733×
    for op in change
327833×
        .tree_ops
327933×
        .iter()
328033×
        .filter(|o| !is_unified_retirement(o, base_snapshot))
3281
    {
328223×
        match op {
3283
            TreeOp::AddNode {
328416×
                node, kind, mode, ..
3285
            } => {
328616×
                out.push_str(&format!(
3287
                    "A {} ({:?}{}{})\n",
328816×
                    path_of(node),
3289
                    kind,
329016×
                    if mode.exec { ", exec" } else { "" },
329116×
                    if mode.opaque { ", opaque" } else { "" }
3292
                ));
3293
            }
32945×
            TreeOp::RemoveNode { node, .. } => out.push_str(&format!("D {}\n", path_of(node))),
3295
            TreeOp::Move {
32962×
                node, parent, name, ..
3297
            } => {
32982×
                let to = if parent.is_root() {
32990×
                    name.clone()
3300
                } else {
33012×
                    format!("{}/{name}", path_of(parent))
3302
                };
33032×
                out.push_str(&format!("R {} -> {to}\n", path_of(node)))
3304
            }
33050×
            TreeOp::SetMode { node, mode, .. } => {
33060×
                out.push_str(&format!(
33070×
                    "M {} mode: exec={} opaque={}\n",
33080×
                    path_of(node),
33090×
                    mode.exec,
33100×
                    mode.opaque
33110×
                ));
33120×
            }
3313
        }
3314
    }
3315
    // Every other file the change edits is modified: the summary names
3316
    // every path it touches, not only those with a tree operation.
331733×
    let with_op: HashSet<NodeId> = change.tree_ops.iter().map(|o| o.node()).collect();
331833×
    let mut listed: HashSet<NodeId> = HashSet::new();
331936×
    for e in &change.edits {
332036×
        let n = e.node();
332136×
        if !with_op.contains(&n) && listed.insert(n) {
332221×
            out.push_str(&format!("M {}\n", path_of(&n)));
332321×
        }
3324
    }
332533×
    let mut last_node: Option<NodeId> = None;
332636×
    for e in &change.edits {
332736×
        let n = e.node();
332836×
        if last_node != Some(n) {
332927×
            out.push_str(&format!("--- {}\n", path_of(&n)));
333027×
            last_node = Some(n);
333127×
        }
333236×
        match e {
333327×
            Edit::Insert { lines, .. } => {
333432×
                for l in lines.iter() {
333532×
                    out.push('+');
333632×
                    out.push_str(&String::from_utf8_lossy(l));
333732×
                    if !l.ends_with(b"\n") {
33380×
                        out.push('\n');
333932×
                    }
3340
                }
3341
            }
33428×
            Edit::Delete { atoms, .. } => {
33438×
                for r in atoms {
33448×
                    for i in r.from..r.to {
33458×
                        let content = base
33468×
                            .file(&n)
33478×
                            .and_then(|g| g.content(&(r.change, i)))
33488×
                            .unwrap_or(b"<unknown>\n");
33498×
                        out.push('-');
33508×
                        out.push_str(&String::from_utf8_lossy(content));
33518×
                        if !content.ends_with(b"\n") {
33520×
                            out.push('\n');
33538×
                        }
3354
                    }
3355
                }
3356
            }
33571×
            Edit::Replace { old, new, .. } => {
33581×
                out.push_str(&format!(
3359
                    "  opaque content {} -> {}\n",
33601×
                    old.map(|o| o.short(12)).unwrap_or_else(|| "none".into()),
33611×
                    new.map(|o| o.short(12)).unwrap_or_else(|| "none".into())
3362
                ));
3363
            }
3364
        }
3365
    }
336633×
    out
336733×
}
3368
3369
/// Pair removed files with added files of the same kind whose contents are
3370
/// at least `RENAME_THRESHOLD` percent alike, best matches first. Beyond
3371
/// `RENAME_LIMIT` candidate pairs only identical contents are paired.
3372
const RENAME_THRESHOLD: u32 = 50;
3373
const RENAME_LIMIT: usize = 10_000;
3374
3375
/// How a change is built beyond its entries: for a Git import, the seed
3376
/// its new nodes' identifiers derive from; and, when it is built from part
3377
/// of the tree, whether the new tree has anything under a directory.
3378
#[derive(Default)]
3379
struct Scope<'a> {
3380
    seed: Option<[u8; 32]>,
3381
    dir_needed: Option<&'a dyn Fn(&str) -> bool>,
3382
}
3383
33842319×
fn detect_renames(
33852319×
    base_snapshot: &Snapshot,
33862319×
    fs_entries: &BTreeMap<String, FsEntry>,
33872319×
    in_scope: impl Fn(&str) -> bool,
33882319×
) -> Vec<(String, String)> {
33892319×
    let removed: Vec<(&String, &crate::state::FileState)> = base_snapshot
33902319×
        .files
33912319×
        .iter()
339213544×
        .filter(|(p, f)| {
339313544×
            f.kind != NodeKind::Dir
339413119×
                && !fs_entries.contains_key(*p)
3395134×
                && in_scope(p)
3396124×
                && !f.is_conflicted()
339713544×
        })
33982319×
        .collect();
33992319×
    let added: Vec<(&String, &FsEntry)> = fs_entries
34002319×
        .iter()
340119202×
        .filter(|(p, e)| e.kind != NodeKind::Dir && !base_snapshot.files.contains_key(*p))
34022319×
        .collect();
34032319×
    if removed.is_empty() || added.is_empty() {
34042258×
        return vec![];
340561×
    }
340661×
    let exact_only = removed.len() * added.len() > RENAME_LIMIT;
340775×
    let old_content = |f: &crate::state::FileState| -> Option<Vec<u8>> {
340875×
        match &f.content {
340971×
            FileContent::Text { bytes, .. } => Some(bytes.clone()),
34104×
            _ => None,
3411
        }
341275×
    };
341361×
    let mut scored: Vec<(u32, usize, usize)> = Vec::new();
341475×
    for (ri, (_, f)) in removed.iter().enumerate() {
341575×
        let old = old_content(f);
341675×
        let old_blob = match &f.content {
34174×
            FileContent::Opaque { blobs } if blobs.len() == 1 => Some(blobs[0]),
341871×
            _ => None,
3419
        };
342094×
        for (ai, (_, e)) in added.iter().enumerate() {
342194×
            if e.kind != f.kind {
34220×
                continue;
342394×
            }
342494×
            let score = match (&old, old_blob) {
342584×
                (Some(o), _) => {
342684×
                    if exact_only {
34270×
                        if *o == *e.content {
34280×
                            100
3429
                        } else {
34300×
                            0
3431
                        }
3432
                    } else {
343384×
                        similarity(o, &e.content)
3434
                    }
3435
                }
343610×
                (None, Some(b)) if e.blob.unwrap_or_else(|| Repo::blob_ref(&e.content)) == b => 100,
34377×
                _ => 0,
3438
            };
343994×
            if score >= RENAME_THRESHOLD {
344041×
                scored.push((score, ri, ai));
344153×
            }
3442
        }
3443
    }
344461×
    scored.sort_by(|a, b| {
34459×
        b.0.cmp(&a.0)
34469×
            .then(removed[a.1].0.cmp(removed[b.1].0))
34479×
            .then(added[a.2].0.cmp(added[b.2].0))
34489×
    });
344961×
    let mut used_r = vec![false; removed.len()];
345061×
    let mut used_a = vec![false; added.len()];
345161×
    let mut out = Vec::new();
345261×
    for (_, ri, ai) in scored {
345341×
        if used_r[ri] || used_a[ai] {
34546×
            continue;
345535×
        }
345635×
        used_r[ri] = true;
345735×
        used_a[ai] = true;
345835×
        out.push((removed[ri].0.clone(), added[ai].0.clone()));
3459
    }
346061×
    out
34612319×
}
3462
3463
/// Percentage of the larger file's bytes found in lines the two share
3464
/// (multiset intersection of lines), like Git's similarity index.
346588×
pub fn similarity(a: &[u8], b: &[u8]) -> u32 {
346688×
    if a == b {
346725×
        return 100;
346863×
    }
346963×
    if a.is_empty() || b.is_empty() {
34704×
        return 0;
347159×
    }
347259×
    let mut counts: HashMap<&[u8], usize> = HashMap::new();
3473113×
    for l in split_lines(a) {
3474113×
        *counts.entry(l).or_default() += 1;
3475113×
    }
347659×
    let mut shared = 0usize;
3477111×
    for l in split_lines(b) {
3478111×
        if let Some(n) = counts.get_mut(l) {
347942×
            if *n > 0 {
348042×
                *n -= 1;
348142×
                shared += l.len();
348242×
            }
348369×
        }
3484
    }
348559×
    (shared * 100 / a.len().max(b.len())) as u32
348688×
}
3487
3488
#[cfg(test)]
3489
mod join_tests {
3490
    use super::*;
3491
3492
    #[test]
34931×
    fn missing_from_finds_what_the_other_lacks() {
34941×
        let a: BTreeMap<String, u8> = [("a", 1), ("b", 2), ("c/d", 3), ("e", 4)]
34951×
            .into_iter()
34964×
            .map(|(k, v)| (k.to_string(), v))
34971×
            .collect();
34981×
        let b: BTreeMap<String, ()> = [("0", ()), ("b", ()), ("c", ()), ("e", ())]
34991×
            .into_iter()
35004×
            .map(|(k, v)| (k.to_string(), v))
35011×
            .collect();
35021×
        let got: Vec<&str> = missing_from(&a, &b)
35031×
            .iter()
35042×
            .map(|(k, _)| k.as_str())
35051×
            .collect();
35061×
        assert_eq!(got, vec!["a", "c/d"]);
35071×
    }
3508
3509
    #[test]
35101×
    fn join_pairs_every_key_in_order() {
35111×
        let a: BTreeMap<String, u8> = [("a", 1), ("b/c", 2), ("d", 3)]
35121×
            .into_iter()
35133×
            .map(|(k, v)| (k.to_string(), v))
35141×
            .collect();
35151×
        let b: BTreeMap<String, char> = [("b", 'x'), ("b/c", 'y'), ("e", 'z')]
35161×
            .into_iter()
35173×
            .map(|(k, v)| (k.to_string(), v))
35181×
            .collect();
35191×
        let got: Vec<(String, Option<u8>, Option<char>)> = join(&a, &b)
35205×
            .map(|(k, x, y)| (k.clone(), x.copied(), y.copied()))
35211×
            .collect();
35221×
        let want = vec![
35231×
            ("a".to_string(), Some(1), None),
35241×
            ("b".to_string(), None, Some('x')),
35251×
            ("b/c".to_string(), Some(2), Some('y')),
35261×
            ("d".to_string(), Some(3), None),
35271×
            ("e".to_string(), None, Some('z')),
3528
        ];
35291×
        assert_eq!(got, want);
35301×
    }
3531
}