OXYGENHUB

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

2548 of 2790 lines run, 340 of 469 functions · run #387 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).
212×
pub fn has_conflict_markers(content: &[u8]) -> bool {
224×
    split_lines(content).iter().any(|l| {
234×
        l.starts_with(b"<<<<<<< oxy conflict")
242×
            || l.starts_with(b"======= oxy conflict")
252×
            || l.starts_with(b">>>>>>> oxy conflict")
264×
    })
272×
}
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.
3443×
pub fn has_own_conflict_markers(content: &[u8], materialized: &[u8], plain: &[&[u8]]) -> bool {
35564×
    let line = |l: &[u8]| -> Vec<u8> {
36564×
        let l = l.strip_suffix(b"\n").unwrap_or(l);
37564×
        l.strip_suffix(b"\r").unwrap_or(l).to_vec()
38564×
    };
39313×
    let marker = |l: &[u8]| {
40313×
        l.starts_with(b"<<<<<<< oxy conflict")
41266×
            || l.starts_with(b"======= oxy conflict")
42219×
            || l.starts_with(b">>>>>>> oxy conflict")
43313×
    };
4496×
    let unconflicted: HashSet<Vec<u8>> = plain.iter().map(|l| line(l)).collect();
4543×
    let own: HashSet<Vec<u8>> = split_lines(materialized)
4643×
        .into_iter()
4743×
        .map(line)
48313×
        .filter(|l| marker(l) && !unconflicted.contains(l))
4943×
        .collect();
5043×
    !own.is_empty()
5143×
        && split_lines(content)
5243×
            .into_iter()
53155×
            .any(|l| own.contains(&line(l)))
5443×
}
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.
1276×
pub(crate) fn keep_both_text(
1286×
    text: &[u8],
1296×
    sides: &[Option<Vec<Vec<u8>>>],
1306×
    reverse: bool,
1316×
) -> (Vec<u8>, Vec<usize>, Vec<(usize, &'static str)>) {
132
    // A side as the markers hold it: the renderer ends each with a newline.
13318×
    let with_newline = |s: &[u8]| {
13418×
        let mut s = s.to_vec();
13518×
        if !s.is_empty() && !s.ends_with(b"\n") {
1360×
            s.push(b'\n');
13718×
        }
13818×
        s
13918×
    };
1401039×
    let lines: Vec<&[u8]> = text.split_inclusive(|&b| b == b'\n').collect();
1416×
    let (mut out, mut settled, mut left) = (Vec::new(), Vec::new(), Vec::new());
1426×
    let mut i = 0;
14325×
    while i < lines.len() {
14419×
        let Some((n, total)) = conflict_header(lines[i]) else {
14513×
            out.extend_from_slice(lines[i]);
14613×
            i += 1;
14713×
            continue;
148
        };
1496×
        let end = format!(">>>>>>> oxy conflict {n} of {total} end");
1506×
        let next_side = format!("======= oxy conflict {n} of {total}, side ");
1516×
        let Some(stop) =
15224×
            (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
        };
1596×
        let mut found: Vec<Vec<u8>> = vec![Vec::new()];
16018×
        for line in &lines[i + 1..stop] {
16118×
            if line.starts_with(next_side.as_bytes()) {
1626×
                found.push(Vec::new());
16312×
            } else {
16412×
                found.last_mut().unwrap().extend_from_slice(line);
16512×
            }
166
        }
1676×
        let wanted = match sides.get(n.wrapping_sub(1)) {
1686×
            _ if total != sides.len() => {
1690×
                Err("the markers are not the file's conflicts now; see `oxy status`")
170
            }
1715×
            Some(Some(w)) => Ok(w),
1721×
            _ => Err("both sides changed these lines; edit the markers"),
173
        };
1746×
        let keep = wanted.and_then(|w| {
17510×
            let mut a: Vec<Vec<u8>> = w.iter().map(|s| with_newline(s)).collect();
1765×
            let mut b = found.clone();
1775×
            a.sort();
1785×
            b.sort();
1795×
            if a == b {
1804×
                Ok(w)
181
            } else {
1821×
                Err("the lines between its markers were edited; finish it by hand")
183
            }
1845×
        });
1856×
        match keep {
1864×
            Ok(w) => {
1874×
                let order: Vec<&Vec<u8>> = if reverse {
1881×
                    w.iter().rev().collect()
189
                } else {
1903×
                    w.iter().collect()
191
                };
1928×
                for s in order {
1938×
                    out.extend_from_slice(&with_newline(s));
1948×
                }
1954×
                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
        }
2046×
        i = stop + 1;
205
    }
2066×
    (out, settled, left)
2076×
}
208
209
/// `(n, total)` from a conflict's opening marker (spec §9.5).
21019×
fn conflict_header(line: &[u8]) -> Option<(usize, usize)> {
21119×
    let rest = line.strip_prefix(b"<<<<<<< oxy conflict ")?;
2126×
    let rest = std::str::from_utf8(rest).ok()?;
2136×
    let (n, rest) = rest.split_once(" of ")?;
21412×
    let total = rest.split(|c: char| !c.is_ascii_digit()).next()?;
2156×
    Some((n.parse().ok()?, total.parse().ok()?))
21619×
}
217
21824133×
pub fn is_binary(content: &[u8]) -> bool {
21924133×
    content[..content.len().min(BINARY_SNIFF)].contains(&0)
22024133×
}
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.
2421573×
    fn platform_normalize(&self, entries: &mut BTreeMap<String, FsEntry>, base: &Snapshot) {
2431573×
        let p = self.platform;
2441573×
        if p.exec_bits && p.symlinks {
2451571×
            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
        }
2591573×
    }
260
261
    /// Like `build_against`, for files given in memory (imports).
2621289×
    pub(crate) fn build_from_entries(
2631289×
        &self,
2641289×
        base: &State,
2651289×
        base_snapshot: &Snapshot,
2661289×
        reuse: HashMap<String, (NodeId, NodeKind)>,
2671289×
        fs_entries: &BTreeMap<String, FsEntry>,
2681289×
    ) -> Result<BuiltChange> {
2691289×
        self.build_from_entries_resolving(base, base_snapshot, reuse, fs_entries, &HashSet::new())
2701289×
    }
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.
2771307×
    pub(crate) fn build_from_entries_resolving(
2781307×
        &self,
2791307×
        base: &State,
2801307×
        base_snapshot: &Snapshot,
2811307×
        reuse: HashMap<String, (NodeId, NodeKind)>,
2821307×
        fs_entries: &BTreeMap<String, FsEntry>,
2831307×
        resolve: &HashSet<String>,
2841307×
    ) -> Result<BuiltChange> {
2851307×
        self.build_from_entries_with(
2861307×
            base,
2871307×
            base_snapshot,
2881307×
            reuse,
2891307×
            fs_entries,
2901307×
            resolve,
2911307×
            Scope::default(),
292
        )
2931307×
    }
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.
3291008×
    fn build_changed_only(
3301008×
        &self,
3311008×
        base: &State,
3321008×
        base_snapshot: &Snapshot,
3331008×
        reuse: HashMap<String, (NodeId, NodeKind)>,
3341008×
        fs_entries: &BTreeMap<String, FsEntry>,
3351008×
    ) -> Result<BuiltChange> {
3361008×
        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.
3391008×
        let changed: BTreeMap<String, FsEntry> = join(fs_entries, &base_snapshot.files)
34011214×
            .filter_map(|(p, e, f)| {
34111214×
                let e = e?;
34211086×
                (!e.unchanged || f.is_none_or(|f| f.kind != e.kind || f.mode.exec != e.exec))
34311086×
                    .then(|| (p.clone(), e.clone()))
34411214×
            })
3451008×
            .collect();
3461008×
        let mut files: BTreeMap<String, crate::state::FileState> = BTreeMap::new();
3476857×
        for p in changed.keys() {
3486857×
            if let Some(f) = base_snapshot.files.get(p) {
3493779×
                files.insert(p.clone(), f.clone());
3503779×
            }
351
        }
352
        // Paths the base has and the disk does not.
3531008×
        let gone = join(&base_snapshot.files, fs_entries)
35411214×
            .filter_map(|(p, f, e)| (e.is_none()).then_some((p, f?)));
3551008×
        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
        }
3721008×
        let part = Snapshot {
3731008×
            tree: base_snapshot.tree.clone(),
3741008×
            files,
3751008×
            unrendered: BTreeSet::new(),
3761008×
        };
3771008×
        drop(pick);
3781008×
        let _build = crate::timing::phase("snapshot:   of which building the change");
379
        // Whether anything on disk is under `dir`.
3801008×
        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×
        };
3871008×
        self.build_from_entries_with(
3881008×
            base,
3891008×
            &part,
3901008×
            reuse,
3911008×
            &changed,
3921008×
            &HashSet::new(),
3931008×
            Scope {
3941008×
                seed: None,
3951008×
                dir_needed: Some(&dir_needed),
3961008×
            },
397
        )
3981008×
    }
399
4002403×
    fn build_from_entries_with(
4012403×
        &self,
4022403×
        base: &State,
4032403×
        base_snapshot: &Snapshot,
4042403×
        reuse: HashMap<String, (NodeId, NodeKind)>,
4052403×
        fs_entries: &BTreeMap<String, FsEntry>,
4062403×
        resolve: &HashSet<String>,
4072403×
        scope: Scope,
4082403×
    ) -> Result<BuiltChange> {
4092403×
        let Scope { seed, dir_needed } = scope;
4102403×
        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.
4132403×
        let attrs = crate::attributes::Attributes::from_files(
4142403×
            fs_entries
4152403×
                .iter()
41619498×
                .filter(|(p, _)| p.as_str() == ".oxyattributes" || p.ends_with("/.oxyattributes"))
4172403×
                .map(|(p, e)| (p.as_str(), e.content.as_slice())),
418
        );
4192403×
        let mut b = ChangeBuilder::new(base, base_snapshot, reuse).with_attributes(attrs);
4202403×
        b.resolve = resolve.clone();
4212403×
        b.node_seed = seed;
4222403×
        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.
4262403×
        let renames = detect_renames(base_snapshot, fs_entries, |p| self.in_scope(p));
4272403×
        let renamed_from: HashMap<&str, &str> = renames
4282403×
            .iter()
4292403×
            .map(|(old, new)| (new.as_str(), old.as_str()))
4302403×
            .collect();
4312403×
        let renamed_to: HashMap<&str, &str> = renames
4322403×
            .iter()
4332403×
            .map(|(old, new)| (old.as_str(), new.as_str()))
4342403×
            .collect();
4352403×
        laps.lap("build: renames");
4362403×
        b.diff_in_parallel(fs_entries);
4372403×
        laps.lap("build: diffs");
43819498×
        for (path, fs_entry) in fs_entries {
43919498×
            match base_snapshot.files.get(path) {
4406228×
                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
                    }
4446193×
                    None => b.add_path(self, path, fs_entry)?,
445
                },
44613270×
                Some(expected) => b.update_path(self, path, fs_entry, expected)?,
447
            }
448
        }
4492403×
        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.
4522403×
        let mut needed_dirs: HashSet<&str> = HashSet::new();
45319511×
        fn parents_of<'a>(p: &'a str, set: &mut HashSet<&'a str>) {
45419511×
            let mut end = p.len();
45520222×
            while let Some(i) = p[..end].rfind('/') {
45615495×
                if !set.insert(&p[..i]) {
45714784×
                    break;
458711×
                }
459711×
                end = i;
460
            }
46119511×
        }
46219498×
        for p in fs_entries.keys() {
46319498×
            parents_of(p, &mut needed_dirs);
46419498×
        }
46513877×
        for p in base_snapshot.files.keys() {
46613877×
            if !self.in_scope(p) {
46713×
                parents_of(p, &mut needed_dirs);
46813864×
            }
469
        }
47013877×
        for (path, expected) in &base_snapshot.files {
47113877×
            if fs_entries.contains_key(path)
472607×
                || !self.in_scope(path)
473594×
                || renamed_to.contains_key(path.as_str())
474
            {
47513318×
                continue;
476559×
            }
477559×
            let still_needed = expected.kind == NodeKind::Dir
478465×
                && match dir_needed {
47921×
                    Some(f) => f(path),
480444×
                    None => needed_dirs.contains(path.as_str()),
481
                };
482559×
            if !still_needed {
483121×
                b.remove_path(path, expected);
484438×
            }
485
        }
4862403×
        laps.lap("build: removals");
4872403×
        if seed.is_some() {
48888×
            b.retire_stray_placements();
4892315×
        }
4902403×
        b.retire_unified();
4912403×
        laps.lap("build: stray placements");
4922403×
        let mut statuses = b.statuses;
4935731×
        statuses.sort_by(|a, b| a.path.cmp(&b.path));
4942403×
        Ok(BuiltChange {
4952403×
            tree_ops: b.tree_ops,
4962403×
            edits: b.edits,
4972403×
            contributors: b.contributors.into_iter().collect(),
4982403×
            resolves: b.resolves,
4992403×
            statuses,
5002403×
            blobs: b.blobs,
5012403×
        })
5022403×
    }
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.
507799×
    pub(crate) fn store_signed(&self, change: &Change) -> Result<ChangeHash> {
508799×
        let ours = change.author == self.author();
509799×
        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");
511798×
        }
512798×
        let storing = crate::timing::phase("store: the change");
513798×
        let hash = self.store.put_change(change)?;
514798×
        drop(storing);
515798×
        if self.config.sign_changes && ours {
51643×
            let _t = crate::timing::phase("store: sign it");
51743×
            self.sign_change(&hash)?;
518755×
        }
519798×
        Ok(hash)
520799×
    }
521
5221577×
    fn resolutions_path(&self) -> PathBuf {
5231577×
        self.oxy
5241577×
            .join("workspaces")
5251577×
            .join(self.workspace.to_hex())
5261577×
            .join("resolve")
5271577×
    }
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).
5311573×
    pub fn resolutions(&self) -> Result<BTreeSet<String>> {
5321573×
        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()),
5381568×
            Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(BTreeSet::new()),
5390×
            Err(e) => Err(e.into()),
540
        }
5411573×
    }
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.
5694×
    pub fn keep_both(
5704×
        &self,
5714×
        snap: &SnapshotResult,
5724×
        paths: &[String],
5734×
        reverse: bool,
5744×
    ) -> Result<Vec<KeptBoth>> {
5754×
        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 {
5832×
            paths.to_vec()
584
        };
5854×
        let mut out = Vec::new();
5864×
        for p in paths {
5874×
            let conflicted = match snap.base_snapshot.files.get(&p).map(|f| (f, &f.content)) {
5884×
                Some((f, FileContent::Text { materialized, .. }))
5894×
                    if materialized.is_conflicted() =>
590
                {
5914×
                    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
            };
6044×
            let sides = snap.base.both_sides(&conflicted.node);
6054×
            let disk = self.root().join(&p);
6064×
            let text = fs::read(&disk)?;
6074×
            let (bytes, settled, left) = keep_both_text(&text, &sides, reverse);
6084×
            if !settled.is_empty() {
6093×
                fs::write(&disk, bytes)?;
6101×
            }
6114×
            out.push(KeptBoth {
6124×
                path: p,
6134×
                settled,
6144×
                left,
6154×
            });
616
        }
6174×
        Ok(out)
6184×
    }
619
620
    /// Settle the adjacent insertions of each conflicted text file whose
621
    /// `.oxyattributes` say `merge=union` (oxygen#145) by keeping both
622
    /// sides, earliest change first, as [`Repo::keep_both`] does: a
623
    /// checkout calls it, and the next commit records the resolution. The
624
    /// files it settled something in.
62574×
    pub(crate) fn settle_unions(&self, command: &str) -> Result<Vec<KeptBoth>> {
62674×
        let snap = self.snapshot(command)?;
62774×
        let paths: Vec<String> = snap
62874×
            .base_snapshot
62974×
            .files
63074×
            .iter()
631317×
            .filter(|(p, f)| {
632261×
                matches!(&f.content, FileContent::Text { materialized, .. } if materialized.is_conflicted())
63370×
                    && snap.attributes.lookup(p).union
634317×
            })
63574×
            .map(|(p, _)| p.clone())
63674×
            .collect();
63774×
        if paths.is_empty() {
63873×
            return Ok(Vec::new());
6391×
        }
6401×
        let kept = self.keep_both(&snap, &paths, false)?;
6411×
        Ok(kept.into_iter().filter(|k| !k.settled.is_empty()).collect())
64274×
    }
643
644
    /// The chosen resolutions `base` still needs; the rest are forgotten.
6451570×
    fn resolutions_for(&self, base: &Snapshot) -> Result<HashSet<String>> {
6461570×
        let all = self.resolutions()?;
6471570×
        if all.is_empty() {
6481565×
            return Ok(HashSet::new());
6495×
        }
6505×
        let live: HashSet<String> = all
6515×
            .iter()
6525×
            .filter(|p| has_replace_conflict(base, p))
6535×
            .cloned()
6545×
            .collect();
6555×
        if live.is_empty() {
6562×
            match fs::remove_file(self.resolutions_path()) {
6572×
                Ok(()) => {}
6580×
                Err(e) if e.kind() == std::io::ErrorKind::NotFound => {}
6590×
                Err(e) => return Err(e.into()),
660
            }
6613×
        }
6625×
        Ok(live)
6631570×
    }
664
665
    /// Snapshot the working copy into the working-copy change (spec §12.3).
666
    /// The result carries the full base state and its whole rendering.
667560×
    pub fn snapshot(&self, command: &str) -> Result<SnapshotResult> {
668560×
        self.snapshot_as(command, false, false)
669560×
    }
670
671
    /// Snapshot the working copy as [`Repo::snapshot`] does, for commands
672
    /// that need its statuses, conflicts and base history, and the graphs
673
    /// of the files it changes: status, log, show, commit, diff, hunks and
674
    /// discard. Text files known unchanged since the last manifest are
675
    /// neither read nor rendered: the result's `base` is a history-only
676
    /// state without their graphs, and its `base_snapshot` lists them in
677
    /// `unrendered` with empty bytes. They are never conflicted, and no
678
    /// change the working copy makes touches them.
679468×
    pub fn snapshot_status(&self, command: &str) -> Result<SnapshotResult> {
680468×
        self.snapshot_as(command, true, false)
681468×
    }
682
683
    /// `snapshot_as`; `for_commit` writes the manifest even where a status
684
    /// would not bother (an edited file is read next time whatever it
685
    /// says), since after the commit that file is unchanged, and records no
686
    /// operation: the commit's own, recorded straight after, replaces the
687
    /// working copy, so the snapshot's would cost a durable write for
688
    /// nothing. Should the commit fail, the files are still on disk and the
689
    /// next snapshot finds them.
6901573×
    fn snapshot_as(
6911573×
        &self,
6921573×
        command: &str,
6931573×
        partial: bool,
6941573×
        for_commit: bool,
6951573×
    ) -> Result<SnapshotResult> {
6961573×
        let _lock = self.lock_snapshot()?;
6971573×
        let batch = self.store.begin_batch()?;
6981573×
        let result = self.snapshot_locked(command, partial, for_commit);
6991573×
        batch.finish()?;
7001573×
        result
7011573×
    }
702
7031573×
    fn snapshot_locked(
7041573×
        &self,
7051573×
        command: &str,
7061573×
        partial: bool,
7071573×
        for_commit: bool,
7081573×
    ) -> Result<SnapshotResult> {
7091573×
        let _all = crate::timing::phase("snapshot");
7101573×
        let (op_ref, op) = self.head_op()?;
7111573×
        let (old_hash, old_wc) = self.working_copy()?;
712
        // The base's history first: its graph keys say which files the
713
        // manifest already knows equal to it.
7141571×
        let mut base = {
7151571×
            let _t = crate::timing::phase("snapshot: load base history");
7161571×
            self.load_state_indexed(&old_wc.deps)?
717
        };
7181571×
        let view = {
7191571×
            let _t = crate::timing::phase("snapshot: tree view");
7201571×
            self.tree_view(&mut base)?
721
        };
7221571×
        let manifest = {
7231571×
            let _t = crate::timing::phase("snapshot: read manifest");
7241571×
            self.read_manifest()?.map(|(_, _, m)| m)
725
        };
7261571×
        let tracked: BTreeMap<String, (NodeKind, Option<ObjectRef>)> = {
7271571×
            let _t = crate::timing::phase("snapshot: tracked paths");
728
            // In the view's path order, so the map is built without searching.
7291571×
            view.entries
7301571×
                .iter()
73110003×
                .filter(|(_, e)| e.kind != NodeKind::Dir)
7329564×
                .map(|(p, e)| {
7339564×
                    let blob = if e.kind != NodeKind::File || e.mode.opaque {
734185×
                        base.live_blobs(&e.node).first().copied()
735
                    } else {
7369379×
                        None
737
                    };
7389564×
                    (p.clone(), (e.kind, blob))
7399564×
                })
7401571×
                .collect()
741
        };
742
        // A text file's graph key, worked out when the walk asks for it.
74312660×
        let key_of = |p: &str| -> Option<[u8; 32]> {
74412660×
            let e = view.entries.get(p)?;
7459449×
            if e.kind != NodeKind::File || e.mode.opaque {
746143×
                return None;
7479306×
            }
7489306×
            base.graph_key(&e.node)
74912660×
        };
7501570×
        let mut fs_entries = {
7511571×
            let _t = crate::timing::phase("snapshot: read working copy");
7521571×
            self.walk_working_copy_with(manifest.as_deref(), &tracked, Some(&key_of))?
753
        };
754
        // The keys of the files read, before building graphs drops them: a
755
        // file found equal to its base rendering keeps its key.
7561570×
        let keys: HashMap<String, [u8; 32]> = fs_entries
7571570×
            .iter()
75812708×
            .filter(|(_, e)| !e.unchanged && e.kind == NodeKind::File)
7598419×
            .filter_map(|(p, _)| Some((p.clone(), key_of(p)?)))
7601570×
            .collect();
7611570×
        let base_snapshot = {
7621570×
            let _t = crate::timing::phase("snapshot: load and render base");
7631570×
            if partial {
7641013×
                let sets = crate::timing::phase("snapshot:   of which choosing graphs");
765
                // Every file but those on disk known unchanged.
7661013×
                let need: Vec<(&str, NodeId)> = join(&view.entries, &fs_entries)
76711236×
                    .filter_map(|(p, v, f)| {
76811236×
                        let v = v?;
7698156×
                        (v.kind == NodeKind::File && !f.is_some_and(|f| f.unchanged))
7708156×
                            .then_some((p.as_str(), v.node))
77111236×
                    })
7721013×
                    .collect();
7731013×
                let render: std::collections::HashSet<&str> =
7741013×
                    need.iter().map(|(p, _)| *p).collect();
7751013×
                let need: Vec<NodeId> = need.iter().map(|(_, n)| *n).collect();
7761013×
                drop(sets);
777
                {
7781013×
                    let _t = crate::timing::phase("snapshot:   of which building graphs");
7791013×
                    self.load_graphs_of(&mut base, &need)?;
780
                }
7811013×
                let _t = crate::timing::phase("snapshot:   of which rendering");
7821013×
                base.materialize_only(&render)
783
            } else {
784557×
                self.load_all_graphs(&mut base)?;
785557×
                base.materialize()
786
            }
787
        };
788
789
        // Reuse the NodeIds the previous working-copy version assigned to new
790
        // paths, so an unchanged working copy hashes identically (spec §12.3).
7911570×
        let reuse = added_node_paths(&old_wc, &base_snapshot);
7921570×
        self.platform_normalize(&mut fs_entries, &base_snapshot);
793
        // Replace conflicts the user settled with `oxy resolve PATH`
794
        // (oxygen#140): those still in the base; a choice the base no longer
795
        // needs (once committed) is forgotten.
7961570×
        let resolve = self.resolutions_for(&base_snapshot)?;
7971570×
        let built = {
7981570×
            let _t = crate::timing::phase("snapshot: diff against base");
7991570×
            if !resolve.is_empty() {
8003×
                self.build_from_entries_resolving(
8013×
                    &base,
8023×
                    &base_snapshot,
8033×
                    reuse,
8043×
                    &fs_entries,
8053×
                    &resolve,
8060×
                )?
8071567×
            } else if partial && self.config.sparse_paths.is_empty() {
808
                #[cfg(test)]
809723×
                let full =
810723×
                    self.build_from_entries(&base, &base_snapshot, reuse.clone(), &fs_entries)?;
8111008×
                let built = self.build_changed_only(&base, &base_snapshot, reuse, &fs_entries)?;
812
                #[cfg(test)]
813
                {
814
                    // New nodes take random identifiers: compare them by
815
                    // order of appearance.
8161446×
                    let norm = |b: &BuiltChange| {
8171446×
                        let text = format!("{:?} {:?} {:?}", b.tree_ops, b.edits, b.statuses);
8181446×
                        let mut seen: Vec<String> = Vec::new();
8191446×
                        let mut out = String::new();
8201446×
                        let mut rest = text.as_str();
82120720×
                        while let Some(i) = rest.find("NodeId(") {
82219274×
                            out.push_str(&rest[..i]);
82319274×
                            let end = i + rest[i..].find(')').unwrap() + 1;
82419274×
                            let id = rest[i..end].to_string();
8259046518×
                            let n = seen.iter().position(|x| *x == id).unwrap_or_else(|| {
8267390×
                                seen.push(id);
8277390×
                                seen.len() - 1
8287390×
                            });
82919274×
                            out.push_str(&format!("N{n}"));
83019274×
                            rest = &rest[end..];
831
                        }
8321446×
                        out.push_str(rest);
8331446×
                        out
8341446×
                    };
835723×
                    assert_eq!(
836723×
                        norm(&built),
837723×
                        norm(&full),
838
                        "a changed-only build is the full one"
839
                    );
840
                }
8411008×
                built
842
            } else {
843559×
                self.build_from_entries(&base, &base_snapshot, reuse, &fs_entries)?
844
            }
845
        };
846
        // Text files found equal to an unconflicted base rendering keep its
847
        // graph key, so the next snapshot need not read or render them.
848
        {
8493912×
            let changed: HashSet<&str> = built.statuses.iter().map(|s| s.path.as_str()).collect();
85012708×
            for (p, e) in fs_entries.iter_mut() {
85112708×
                if e.unchanged || e.kind != NodeKind::File || changed.contains(p.as_str()) {
8528098×
                    continue;
8534610×
                }
8544610×
                e.graph_key = match base_snapshot.files.get(p).map(|f| &f.content) {
855
                    Some(FileContent::Text {
8564486×
                        bytes,
8574486×
                        materialized,
8584486×
                    }) if !materialized.is_conflicted() && *bytes == *e.content => {
8594406×
                        keys.get(p).copied()
860
                    }
861204×
                    _ => None,
862
                };
863
            }
864
        }
865
8661570×
        let mut wc = Change {
8671570×
            version: crate::objects::CHANGE_VERSION,
8681570×
            change_id: old_wc.change_id,
8691570×
            deps: vec![],
8701570×
            author: self.author(),
8711570×
            hlc: old_wc.hlc,
8721570×
            message: old_wc.message.clone(),
8731570×
            tree_ops: built.tree_ops,
8741570×
            edits: built.edits,
8751570×
            kind: ChangeKind::WorkingCopy,
8761570×
        };
8771570×
        let base_heads = base.maximal(&old_wc.deps);
8781570×
        let mut deps: BTreeSet<ChangeHash> = base_heads.into_iter().collect();
8791570×
        deps.extend(referenced_changes(&wc, &base));
8801570×
        deps.extend(built.contributors.iter().copied());
8811570×
        wc.deps = deps.into_iter().collect();
8821570×
        wc.normalize();
8831570×
        let resolves = built.resolves;
8841570×
        let contributors = built.contributors;
8851570×
        let statuses = built.statuses;
886
        // Empty snapshot: hash the candidate before storing; only record an op on change.
8871570×
        let record = crate::timing::phase("snapshot: hash and record");
888
        // Encoded once, its texts stored a batch at a time as they are
889
        // made (a stored blob is not stored again); the change itself only
890
        // when it changed.
891
        // For a commit the change is neither encoded, stored nor recorded:
892
        // the commit stores its own, built from this one's operations, and
893
        // its texts with it. The hash it would have is not needed.
8941570×
        let (new_hash, changed, encoded) = if for_commit {
895545×
            (old_hash, true, Vec::new())
896
        } else {
8971025×
            let encoded = wc.encode_streaming(|batch| self.store.put_texts(&batch))?;
8981025×
            let new_hash = crate::hash::hash_object(crate::hash::ObjectType::Change, &encoded);
8991025×
            (new_hash, new_hash != old_hash, encoded)
900
        };
9011570×
        if changed && !for_commit {
902311×
            self.store.put(crate::hash::ObjectType::Change, &encoded)?;
903311×
            let mut view = op.view.clone();
904311×
            view.workspaces.insert(self.workspace, new_hash);
905311×
            self.record_op(&[op_ref], &format!("{command}{SNAPSHOT_SUFFIX}"), view)?;
9061259×
        }
9071570×
        drop(record);
908
        // The prompt compares against this without recording anything.
9091570×
        let _t = crate::timing::phase("snapshot: write manifest");
9101570×
        let conflicted = base_snapshot.is_conflicted();
9111570×
        let uncommitted = !wc.tree_ops.is_empty() || !wc.edits.is_empty();
912
        // Rewriting the manifest pays only when it would teach the next
913
        // snapshot something: other flags, a file found equal to the base
914
        // (it need not be read again), a new blob, a path added or gone.
915
        // An edited file is read next time whatever it says.
9161570×
        let worth = match self.read_manifest()? {
917545×
            _ if for_commit => true,
918363×
            None => true,
919662×
            Some((c, u, m)) => {
920662×
                c != conflicted
921662×
                    || u != uncommitted
922417×
                    || m.entries.len() != fs_entries.len()
923537×
                    || fs_entries.iter().any(|(p, e)| {
924537×
                        !e.unchanged && (e.graph_key.is_some() || !m.entries.contains_key(p))
925537×
                    })
92670×
                    || built
92770×
                        .blobs
92870×
                        .iter()
92970×
                        .any(|(p, b)| m.entries.get(p).and_then(|e| e.blob) != Some(*b))
930
                    // With uncommitted work, the status cache below holds
931
                    // only while the manifest describes the edited files as
932
                    // they are now.
93374×
                    || (uncommitted && statuses.iter().any(|st| {
93474×
                        let Some(e) = fs_entries.get(&st.path) else {
9354×
                            return m.entries.contains_key(&st.path);
936
                        };
93770×
                        let Some(me) = m.entries.get(&st.path) else {
9380×
                            return true;
939
                        };
94070×
                        let hash = e
94170×
                            .content_hash
94270×
                            .unwrap_or_else(|| *blake3::hash(&e.content).as_bytes());
94370×
                        let stat = e.stat.or_else(|| {
9440×
                            fs::symlink_metadata(self.root.join(&st.path))
9450×
                                .ok()
9460×
                                .map(|md| (md.len(), super::prompt::mtime_ns(&md)))
9470×
                        });
948
                        // The executable bit too: a mode change moves
949
                        // neither size nor time.
95070×
                        me.hash != hash || me.exec != e.exec || stat != Some((me.size, me.mtime_ns))
95174×
                    }))
952
            }
953
        };
9541570×
        let attributes = crate::attributes::Attributes::from_files(
9551570×
            fs_entries
9561570×
                .iter()
95712708×
                .filter(|(p, _)| is_attributes(p))
9581570×
                .map(|(p, e)| (p.as_str(), e.content.as_slice())),
959
        );
9601570×
        let mut manifest = None;
9611570×
        if for_commit {
962545×
            manifest = Some(PendingManifest {
963545×
                entries: fs_entries,
964545×
                blobs: built.blobs.clone(),
965545×
                dirs: self.walked_dirs.take(),
966545×
                written: super::prompt::now_ns(),
967545×
            });
968545×
        } else {
9691025×
            if worth {
970959×
                self.write_manifest_entries(conflicted, uncommitted, &fs_entries, &built.blobs)?;
97166×
            }
9721025×
            self.write_status_cache((uncommitted && !conflicted).then_some(&new_hash), &statuses);
973
        }
9741570×
        Ok(SnapshotResult {
9751570×
            wc_hash: new_hash,
9761570×
            wc,
9771570×
            base,
9781570×
            base_snapshot,
9791570×
            statuses,
9801570×
            changed,
9811570×
            resolves,
9821570×
            contributors,
9831570×
            attributes,
9841570×
            untracked_nested: self.untracked_nested.borrow().clone(),
9851570×
            manifest,
9861570×
        })
9871573×
    }
988
989
    /// `oxy status --json` (spec §9.5): the changed paths and every conflict
990
    /// of the working copy's base with its kind, path, and contributing
991
    /// ChangeIds.
9928×
    pub fn status_json(&self, snap: &SnapshotResult) -> Result<String> {
9938×
        let heads = self.bookmark_heads()?;
9948×
        let base_snapshot = &snap.base_snapshot;
9958×
        let by_node = base_snapshot.tree.by_node();
9968×
        let path_of = |n: &NodeId| by_node.get(n).map(|e| e.path.clone());
9978×
        let id_of = |h: &ChangeHash| {
9984×
            snap.base
9994×
                .get(h)
10004×
                .map(|m| m.change_id.to_hex())
10014×
                .unwrap_or_else(|| h.to_hex())
10024×
        };
10038×
        let paths = json_array(snap.statuses.iter().map(|s| {
10044×
            format!(
1005
                "{{\"path\":{},\"status\":{}}}",
10064×
                json_str(&s.path),
10074×
                json_str(&format!("{:?}", s.status))
1008
            )
10094×
        }));
10108×
        let mut conflicts: Vec<String> = Vec::new();
10119×
        for (p, f) in &base_snapshot.files {
10129×
            if !f.is_conflicted() {
10137×
                continue;
10142×
            }
10152×
            let (kind, changes) = match &f.content {
1016
                FileContent::Text { .. } => {
10172×
                    ("text", snap.base.conflict_regions(&f.node).contributors)
1018
                }
10190×
                FileContent::Opaque { blobs } => {
10200×
                    ("replace", snap.base.blob_contributors(&f.node, blobs))
1021
                }
10220×
                FileContent::Dir => continue,
1023
            };
10242×
            let resolved = match snap
10252×
                .statuses
10262×
                .iter()
10272×
                .find(|s| s.path == *p)
10282×
                .map(|s| s.status)
1029
            {
10301×
                Some(ChangeStatus::Resolved) => "true",
10310×
                Some(ChangeStatus::ConflictEdited) => "\"markers\"",
10321×
                _ => "false",
1033
            };
10342×
            conflicts.push(format!(
1035
                "{{\"kind\":{},\"path\":{},\"node\":{},\"changes\":{},\"resolved\":{resolved}}}",
10362×
                json_str(kind),
10372×
                json_str(p),
10382×
                json_str(&f.node.to_hex()),
10394×
                json_array(changes.iter().map(|h| json_str(&id_of(h))))
1040
            ));
1041
        }
10428×
        for c in &base_snapshot.tree.conflicts {
10430×
            let (kind, nodes): (&str, Vec<NodeId>) = match c {
10440×
                crate::tree::TreeConflict::Name { nodes, .. } => ("name", nodes.clone()),
10450×
                crate::tree::TreeConflict::MultiPlacement { node, .. } => {
10460×
                    ("multi-placement", vec![*node])
1047
                }
10480×
                crate::tree::TreeConflict::Orphan { node, .. } => ("orphan", vec![*node]),
10490×
                crate::tree::TreeConflict::Cycle { node } => ("cycle", vec![*node]),
10500×
                crate::tree::TreeConflict::Mode { node, .. } => ("mode", vec![*node]),
1051
            };
10520×
            let detail = match c {
10530×
                crate::tree::TreeConflict::Name { name, parent, .. } => {
10540×
                    let dir = if *parent == NodeId::ROOT {
10550×
                        String::new()
1056
                    } else {
10570×
                        path_of(parent).unwrap_or_default()
1058
                    };
10590×
                    format!(
1060
                        ",\"path\":{}",
10610×
                        json_str(&if dir.is_empty() {
10620×
                            name.clone()
1063
                        } else {
10640×
                            format!("{dir}/{name}")
1065
                        })
1066
                    )
1067
                }
10680×
                _ => nodes
10690×
                    .first()
10700×
                    .and_then(path_of)
10710×
                    .map(|p| format!(",\"path\":{}", json_str(&p)))
10720×
                    .unwrap_or_default(),
1073
            };
10740×
            conflicts.push(format!(
1075
                "{{\"kind\":{},\"nodes\":{}{detail}}}",
10760×
                json_str(kind),
10770×
                json_array(nodes.iter().map(|n| json_str(&n.to_hex())))
1078
            ));
1079
        }
10808×
        Ok(format!(
1081
            "{{\"bookmark\":{},\"working_copy\":{},\"heads\":{},\"clean\":{},\"conflicted\":{},\"paths\":{paths},\"conflicts\":{},\"untracked_nested\":{},\"skipped_large\":{}}}",
10828×
            json_str(&self.config.bookmark),
10838×
            json_str(&snap.wc.change_id.to_hex()),
10848×
            heads.len(),
10858×
            snap.statuses.is_empty(),
10868×
            base_snapshot.is_conflicted(),
10878×
            json_array(conflicts),
10888×
            json_array(snap.untracked_nested.iter().map(|p| json_str(p))),
10898×
            json_array(
10908×
                self.skipped_large
10918×
                    .borrow()
10928×
                    .iter()
10938×
                    .map(|(p, n)| format!("{{\"path\":{},\"size\":{n}}}", json_str(p)))
1094
            )
1095
        ))
10968×
    }
1097
1098
    /// Turn the working-copy change into a normal change on the bookmark (spec §12.3).
1099734×
    pub fn commit(&self, message: &str, extra_deps: &[ChangeHash]) -> Result<ChangeHash> {
1100734×
        self.commit_selection(message, extra_deps, &Selection::All)
1101734×
    }
1102
1103
    /// The hunks of the working copy, for `oxy commit --interactive`: each
1104
    /// tree operation and each edit, in the order `select_hunks` numbers them.
11058×
    pub fn hunks(&self) -> Result<(SnapshotResult, Vec<Hunk>)> {
11068×
        let snap = self.snapshot_status("oxy commit")?;
11078×
        let hunks = render_hunks(&snap.wc, &snap.base, &snap.base_snapshot);
11088×
        Ok((snap, hunks))
11098×
    }
1110
1111
    /// Commit part of the working copy (spec §12.3). What is not selected
1112
    /// stays on disk as uncommitted work: the next snapshot rebuilds it
1113
    /// against the new base, so the working copy always describes the
1114
    /// directory.
1115
    /// The graph key in `st` of each text file at `paths`, the paths a
1116
    /// commit changed: only their graphs changed, so the keys the manifest
1117
    /// holds for the others still stand (and any that does not is simply
1118
    /// not trusted by the next snapshot, which compares keys). Files with
1119
    /// an `eol` attribute are left out: their bytes on disk are not the
1120
    /// rendering.
1121752×
    fn committed_graph_keys(
1122752×
        &self,
1123752×
        st: &State,
1124752×
        paths: &[String],
1125752×
        attrs: &crate::attributes::Attributes,
1126752×
    ) -> HashMap<String, [u8; 32]> {
1127752×
        let _t = crate::timing::phase("commit: graph keys");
1128752×
        let view = st.view();
1129752×
        paths
1130752×
            .iter()
11313617×
            .filter_map(|p| {
11323617×
                let e = view.entries.get(p)?;
11333567×
                (e.kind == NodeKind::File && !e.mode.opaque && attrs.lookup(p).eol.is_none())
11343567×
                    .then_some(())?;
11353497×
                Some((p.clone(), st.graph_key(&e.node)?))
11363617×
            })
1137752×
            .collect()
1138752×
    }
1139
1140741×
    pub fn commit_selection(
1141741×
        &self,
1142741×
        message: &str,
1143741×
        extra_deps: &[ChangeHash],
1144741×
        selection: &Selection,
1145741×
    ) -> Result<ChangeHash> {
1146741×
        Ok(self
1147741×
            .commit_selection_partial(message, extra_deps, selection)?
1148
            .0)
1149741×
    }
1150
1151
    /// As [`Repo::commit_selection`], and whether the commit left part of
1152
    /// the working copy uncommitted: when it did not, nothing is left, and
1153
    /// no snapshot is needed to say so.
1154770×
    pub fn commit_selection_partial(
1155770×
        &self,
1156770×
        message: &str,
1157770×
        extra_deps: &[ChangeHash],
1158770×
        selection: &Selection,
1159770×
    ) -> Result<(ChangeHash, bool)> {
1160
        // The commit's objects are written together, made durable at once
1161
        // before the operation that names them (spec §13.6).
1162770×
        let batch = self.store.begin_batch()?;
1163770×
        let out = self.commit_selection_batched(message, extra_deps, selection);
1164770×
        batch.finish()?;
1165770×
        out
1166770×
    }
1167
1168
    /// Write the manifest a commit's snapshot left to the commit, with the
1169
    /// graph keys `keys` sets.
1170533×
    fn write_pending_manifest(
1171533×
        &self,
1172533×
        mut m: PendingManifest,
1173533×
        conflicted: bool,
1174533×
        keys: HashMap<String, [u8; 32]>,
1175533×
    ) -> Result<()> {
11762892×
        for (path, k) in keys {
11772892×
            if let Some(e) = m.entries.get_mut(&path) {
11782892×
                e.graph_key = Some(k);
11792892×
            }
1180
        }
1181533×
        self.write_manifest_entries_as_of(
1182533×
            conflicted,
1183
            false,
1184533×
            &m.entries,
1185533×
            &m.blobs,
1186533×
            m.written,
1187533×
            m.dirs.unwrap_or_default(),
1188
        )
1189533×
    }
1190
1191770×
    fn commit_selection_batched(
1192770×
        &self,
1193770×
        message: &str,
1194770×
        extra_deps: &[ChangeHash],
1195770×
        selection: &Selection,
1196770×
    ) -> Result<(ChangeHash, bool)> {
1197770×
        let _wc = self.lock_working_copy()?;
1198770×
        let mut snap = match self.snapshot_from_cache()? {
1199225×
            Some(snap) => snap,
1200545×
            None => self.snapshot_as("oxy commit", true, true)?,
1201
        };
1202770×
        let pending = snap.manifest.take();
1203770×
        if snap.wc.tree_ops.is_empty() && snap.wc.edits.is_empty() {
12044×
            if let Some(m) = pending {
12054×
                let conflicted = snap.base_snapshot.is_conflicted();
12064×
                self.write_pending_manifest(m, conflicted, HashMap::new())?;
12070×
            }
12084×
            return fail("nothing to commit: the working copy matches its base");
1209766×
        }
1210766×
        if let Some(s) = snap
1211766×
            .statuses
1212766×
            .iter()
12133646×
            .find(|s| s.status == ChangeStatus::ConflictEdited)
1214
        {
12151×
            return fail(format!("{} still contains conflict markers", s.path));
1216765×
        }
1217765×
        if message.trim().is_empty() {
12180×
            return fail("a commit message is required");
1219765×
        }
1220
        // What the whole working copy references, before a whole commit
1221
        // takes its operations over (they are moved, not copied: for a
1222
        // large tree they are most of the memory).
1223765×
        let wc_refs = referenced_changes(&snap.wc, &snap.base);
12243644×
        let changed_paths: Vec<String> = snap.statuses.iter().map(|s| s.path.clone()).collect();
1225765×
        let (tree_ops, edits, partial) = match selection {
1226752×
            Selection::All => (
1227752×
                std::mem::take(&mut snap.wc.tree_ops),
1228752×
                std::mem::take(&mut snap.wc.edits),
1229752×
                false,
1230752×
            ),
12318×
            Selection::Paths(paths) => {
12328×
                let (o, e) = select_paths(&snap.wc, &snap.base_snapshot, paths);
12338×
                let partial = o.len() != snap.wc.tree_ops.len() || e.len() != snap.wc.edits.len();
12348×
                (o, e, partial)
1235
            }
12365×
            Selection::Hunks(indices) => {
12375×
                let (o, e) = select_hunks(&snap.wc, indices, &snap.base_snapshot.tree.unified);
12385×
                let partial = o.len() != snap.wc.tree_ops.len() || e.len() != snap.wc.edits.len();
12395×
                (o, e, partial)
1240
            }
1241
        };
1242765×
        if tree_ops.is_empty() && edits.is_empty() {
12430×
            return fail("nothing selected to commit");
1244765×
        }
1245
        // A resolution may leave other work uncommitted (oxygen#118), but
1246
        // takes every file it resolves, whole.
1247765×
        if partial && snap.resolves {
12482×
            let resolved = snap
12492×
                .statuses
12502×
                .iter()
12514×
                .filter(|s| s.status == ChangeStatus::Resolved)
12522×
                .map(|s| s.path.as_str());
12532×
            let missing: Vec<&str> = match selection {
12542×
                Selection::Paths(paths) => resolved
12552×
                    .filter(|p| {
12562×
                        !paths.iter().any(|x| {
12572×
                            p == x || p.starts_with(&format!("{}/", x.trim_end_matches('/')))
12582×
                        })
12592×
                    })
12602×
                    .collect(),
12610×
                _ => resolved.collect(),
1262
            };
12632×
            if !missing.is_empty() {
12641×
                return fail(format!(
1265
                    "a conflict resolution takes every file it resolves, whole: commit by paths, including {}",
12661×
                    missing.join(", ")
1267
                ));
12681×
            }
1269763×
        }
1270
        // pre-commit hook: may veto.
1271764×
        self.run_hook(
1272764×
            "pre-commit",
1273764×
            &format!(
1274
                "{{\"event\":\"pre-commit\",\"message\":{},\"paths\":{}}}",
1275764×
                json_str(message),
12763642×
                json_array(snap.statuses.iter().map(|s| format!(
1277
                    "{{\"path\":{},\"status\":{}}}",
12783642×
                    json_str(&s.path),
12793642×
                    json_str(&format!("{:?}", s.status))
1280
                )))
1281
            ),
12821×
        )?;
1283763×
        let (op_ref, op) = self.head_op()?;
1284763×
        let mut deps: BTreeSet<ChangeHash> = wc_refs;
1285
        // semantic-deps hook: may add explicit dependencies (spec §8.1).
1286763×
        if self.config.semantic_deps {
12871×
            let touched: Vec<String> = snap.statuses.iter().map(|s| s.path.clone()).collect();
12881×
            let by_node = snap.base_snapshot.tree.by_node();
12891×
            let mut candidates: Vec<(ChangeId, ChangeHash, Vec<String>)> = Vec::new();
12901×
            let mut seen: BTreeSet<ChangeHash> = BTreeSet::new();
12912×
            for h in deps.iter().chain(snap.base.maximal(&snap.wc.deps).iter()) {
12922×
                if !seen.insert(*h) {
12930×
                    continue;
12942×
                }
12952×
                let c = self.store.get_change(h)?;
12962×
                let mut paths: BTreeSet<String> = BTreeSet::new();
12976×
                for n in c
12982×
                    .tree_ops
12992×
                    .iter()
13003×
                    .map(|o| o.node())
13013×
                    .chain(c.edits.iter().map(|e| e.node()))
1302
                {
13036×
                    if let Some(e) = by_node.get(&n) {
13046×
                        paths.insert(e.path.clone());
13056×
                    }
1306
                }
13072×
                candidates.push((c.change_id, *h, paths.into_iter().collect()));
1308
            }
13091×
            for d in self.semantic_deps(&snap.wc.change_id, &touched, &candidates)? {
13101×
                if snap.base.contains(&d) {
13111×
                    deps.insert(d);
13121×
                }
1313
            }
1314762×
        }
1315
        // A resolution depends on every change that contributed to the
1316
        // conflict (spec §8.1). Tree and opaque conflicts are resolved through
1317
        // ordinary operations whose references already cover the contributors.
1318763×
        deps.extend(snap.contributors.iter().copied());
1319763×
        for d in extra_deps {
13204×
            if !snap.base.contains(d) {
13210×
                return fail(format!(
1322
                    "--depends-on {d}: not in the working copy's base state"
1323
                ));
13244×
            }
13254×
            deps.insert(*d);
1326
        }
1327763×
        let mut change = Change {
1328
            version: crate::objects::CHANGE_VERSION,
1329763×
            change_id: if partial {
133010×
                ChangeId::random()
1331
            } else {
1332753×
                snap.wc.change_id
1333
            },
1334763×
            deps: vec![],
1335763×
            author: self.author(),
1336763×
            hlc: Hlc::now(),
1337763×
            message: message.trim_end().to_string(),
1338763×
            tree_ops,
1339763×
            edits,
1340763×
            kind: if snap.resolves {
134113×
                ChangeKind::Resolution
1342
            } else {
1343750×
                ChangeKind::Normal
1344
            },
1345
        };
1346763×
        if partial {
1347
            // Dependencies come from what the selected part references, not
1348
            // from the whole working copy.
134910×
            deps = referenced_changes(&change, &snap.base);
135010×
            for d in extra_deps {
13511×
                deps.insert(*d);
13521×
            }
1353753×
        }
1354763×
        change.deps = deps.into_iter().collect();
1355763×
        change.normalize();
1356763×
        let signing = crate::timing::phase("commit: sign and store");
1357763×
        let hash = self.store_signed(&change)?;
1358762×
        drop(signing);
1359762×
        let extending = crate::timing::phase("commit: extend the state");
1360
1361
        // New bookmark heads: maximal elements of old heads plus the new change.
1362
        // The working copy continues on its own base plus the new change, which
1363
        // is exactly what the files on disk contain; the bookmark may hold
1364
        // other heads (and conflicts) the working copy has not checked out.
1365762×
        let old_heads = self.heads_of(&op.view, &self.config.bookmark)?;
1366762×
        let old_base = snap.base.maximal(&snap.wc.deps);
1367762×
        let mut all: Vec<ChangeHash> = old_heads.clone();
1368762×
        all.extend(old_base.iter().copied());
1369762×
        all.push(hash);
1370
        // The snapshot already loaded the working copy's base; when that also
1371
        // holds every bookmark head, it is the state to extend.
1372762×
        let mut st = if old_heads.iter().all(|h| snap.base.contains(h)) {
1373717×
            snap.base
1374
        } else {
137545×
            self.load_state(&all)?
1376
        };
1377762×
        st.add_hashed(hash, change)?;
1378762×
        let mut with_new = old_heads.clone();
1379762×
        with_new.push(hash);
1380762×
        let new_heads = st.maximal(&with_new);
1381
        // Automatic checkpoint once enough changes accumulated (spec §11).
1382762×
        let since = self
1383762×
            .latest_checkpoint(&self.config.bookmark)?
1384762×
            .map(|(_, cp)| cp.count)
1385762×
            .unwrap_or(0);
1386762×
        if self.config.checkpoint_interval > 0
1387762×
            && (st.len() as u64).saturating_sub(since) >= self.config.checkpoint_interval
1388
        {
13892×
            let cp_state = self.load_state_full(&new_heads)?;
13902×
            self.write_checkpoint(&self.config.bookmark, &cp_state, &new_heads)?;
1391760×
        }
1392762×
        let mut wc_base = old_base.clone();
1393762×
        wc_base.push(hash);
1394762×
        let wc_base = st.maximal(&wc_base);
1395762×
        drop(extending);
1396
1397
        // The graph keys of the files as they now are, from the state the
1398
        // commit just extended: a file whose graph it built has none, and
1399
        // is read by the next snapshot; a key the next base does not share
1400
        // (the bookmark held other heads) is simply not trusted then.
1401762×
        let keying = crate::timing::phase("commit: graph keys of the files");
1402762×
        let committed_keys =
1403762×
            (!partial).then(|| self.committed_graph_keys(&st, &changed_paths, &snap.attributes));
1404762×
        drop(keying);
1405762×
        let recording = crate::timing::phase("commit: record");
1406762×
        let wc = self.new_working_copy(wc_base, "");
1407762×
        let wc_hash = self.store.put_change(&wc)?;
1408762×
        let mut view = op.view.clone();
1409762×
        view.bookmarks.insert(
1410762×
            self.config.bookmark.clone(),
1411762×
            self.store.put_state(&StateObject::new(new_heads))?,
1412
        );
1413762×
        view.workspaces.insert(self.workspace, wc_hash);
1414762×
        self.record_op(&[op_ref], &format!("oxy commit -m {message:?}"), view)?;
1415757×
        drop(recording);
1416757×
        let rewriting = crate::timing::phase("commit: manifest");
1417757×
        if partial {
141810×
            // The rest is rebuilt from disk by the next snapshot.
141910×
            self.drop_manifest();
142010×
        } else {
1421747×
            let conflicted = snap.base_snapshot.is_conflicted() && !snap.resolves;
1422
            // The files on disk are now exactly the new base's renderings:
1423
            // record their graph keys, so the next snapshot neither reads nor
1424
            // renders them (oxygen#35).
1425747×
            let keys = if conflicted {
14260×
                HashMap::new()
1427
            } else {
1428747×
                committed_keys.unwrap_or_default()
1429
            };
1430747×
            match pending {
1431529×
                Some(m) => self.write_pending_manifest(m, conflicted, keys)?,
1432218×
                None => self.rewrite_manifest(conflicted, false, &keys)?,
1433
            }
1434
        }
1435757×
        drop(rewriting);
1436757×
        let packing = crate::timing::phase("commit: autopack");
1437757×
        self.maybe_autopack()?;
1438757×
        drop(packing);
1439757×
        let _hook = crate::timing::phase("commit: hook");
1440757×
        let _ = self.run_hook(
1441757×
            "post-commit",
1442757×
            &format!(
1443757×
                "{{\"event\":\"post-commit\",\"change_id\":{},\"hash\":{},\"message\":{}}}",
1444757×
                json_str(&snap.wc.change_id.to_hex()),
1445757×
                json_str(&hash.to_hex()),
1446757×
                json_str(message)
1447757×
            ),
1448757×
        );
1449757×
        Ok((hash, partial))
1450770×
    }
1451
}
1452
1453
/// What part of the working copy a commit takes (spec §12.3).
1454
#[derive(Clone, Debug)]
1455
pub enum Selection {
1456
    All,
1457
    /// Every operation and edit on nodes under these paths.
1458
    Paths(Vec<String>),
1459
    /// Hunk indices as `Repo::hunks` numbers them; dependent hunks are added.
1460
    Hunks(Vec<usize>),
1461
}
1462
1463
/// One selectable piece of the working copy: a tree operation or an edit.
1464
#[derive(Clone, Debug)]
1465
pub struct Hunk {
1466
    pub index: usize,
1467
    pub path: String,
1468
    /// Rendered like `oxy diff`.
1469
    pub text: String,
1470
}
1471
1472
/// The tree operations and edits on nodes under `paths`, plus the
1473
/// additions of any new parent directories they need.
14748×
fn select_paths(
14758×
    wc: &Change,
14768×
    base_snapshot: &Snapshot,
14778×
    paths: &[String],
14788×
) -> (Vec<TreeOp>, Vec<Edit>) {
147927×
    let selected = |p: &str| {
148027×
        paths
148127×
            .iter()
148227×
            .any(|x| p == x || p.starts_with(&format!("{}/", x.trim_end_matches('/'))))
148327×
    };
14848×
    let by_node = base_snapshot.tree.by_node();
14858×
    let mut new_names: HashMap<NodeId, (NodeId, String, NodeKind)> = HashMap::new();
14868×
    for op in &wc.tree_ops {
1487
        if let TreeOp::AddNode {
14885×
            node,
14895×
            parent,
14905×
            name,
14915×
            kind,
1492
            ..
14936×
        } = op
14945×
        {
14955×
            new_names.insert(*node, (*parent, name.clone(), *kind));
14965×
        }
1497
    }
14988×
    let mut nodes: BTreeSet<NodeId> = BTreeSet::new();
149928×
    for n in wc
15008×
        .tree_ops
15018×
        .iter()
15028×
        .map(|o| o.node())
150322×
        .chain(wc.edits.iter().map(|e| e.node()))
1504
    {
150528×
        if path_of_node(&n, &by_node, &new_names).is_some_and(|p| selected(&p)) {
150614×
            nodes.insert(n);
150714×
        }
1508
    }
1509
    // The nodes shown as one with a selected node are retired with it.
15108×
    for (dup, shown) in &base_snapshot.tree.unified {
15111×
        if nodes.contains(shown) {
15121×
            nodes.insert(*dup);
15131×
        }
1514
    }
1515
    // New parents of selected new nodes come along.
15168×
    let mut changed = true;
151716×
    while changed {
15188×
        changed = false;
15198×
        for (n, (parent, _, _)) in &new_names {
15205×
            if nodes.contains(n) && new_names.contains_key(parent) && nodes.insert(*parent) {
15210×
                changed = true;
15225×
            }
1523
        }
1524
    }
15258×
    let ops = wc
15268×
        .tree_ops
15278×
        .iter()
15288×
        .filter(|o| nodes.contains(&o.node()))
15298×
        .cloned()
15308×
        .collect();
15318×
    let edits = wc
15328×
        .edits
15338×
        .iter()
153422×
        .filter(|e| nodes.contains(&e.node()))
15358×
        .cloned()
15368×
        .collect();
15378×
    (ops, edits)
15388×
}
1539
1540
/// The hunks `indices` name plus whatever they refer to within the working
1541
/// copy (the parent directory of an added node, the insert that introduced
1542
/// an anchor line), renumbered so the result is a well-formed change.
1543
/// The nodes `unified` shows as one with another (a base's
1544
/// [`TreeView::unified`](crate::tree::TreeView::unified)) are retired with
1545
/// any hunk of the node shown.
15466×
fn select_hunks(
15476×
    wc: &Change,
15486×
    indices: &[usize],
15496×
    unified: &BTreeMap<NodeId, NodeId>,
15506×
) -> (Vec<TreeOp>, Vec<Edit>) {
15516×
    let n_ops = wc.tree_ops.len();
15526×
    let mut ops_sel = vec![false; n_ops];
15536×
    let mut edits_sel = vec![false; wc.edits.len()];
15546×
    for &i in indices {
15555×
        if i < n_ops {
15561×
            ops_sel[i] = true;
15574×
        } else if i - n_ops < wc.edits.len() {
15584×
            edits_sel[i - n_ops] = true;
15594×
        }
1560
    }
1561
    // Atom ranges each insert introduces, per node, in the working copy's numbering.
15626×
    let mut per_node: HashMap<NodeId, u32> = HashMap::new();
15636×
    let mut insert_ranges: Vec<Option<(NodeId, u32, u32)>> = Vec::new();
156412×
    for e in &wc.edits {
156512×
        insert_ranges.push(match e {
156612×
            Edit::Insert { node, lines, .. } => {
156712×
                let start = per_node.entry(*node).or_default();
156812×
                let r = (*node, *start, *start + lines.len() as u32);
156912×
                *start += lines.len() as u32;
157012×
                Some(r)
1571
            }
15720×
            _ => None,
1573
        });
1574
    }
15756×
    let add_index: HashMap<NodeId, usize> = wc
15766×
        .tree_ops
15776×
        .iter()
15786×
        .enumerate()
157910×
        .filter_map(|(i, o)| {
158010×
            if let TreeOp::AddNode { node, .. } = o {
15819×
                Some((*node, i))
1582
            } else {
15831×
                None
1584
            }
158510×
        })
15866×
        .collect();
15876×
    let insert_for = |node: &NodeId, index: u32| -> Option<usize> {
15880×
        insert_ranges
15890×
            .iter()
15900×
            .position(|r| matches!(r, Some((n, a, b)) if n == node && *a <= index && index < *b))
15910×
    };
1592
    // Closure.
15936×
    let mut changed = true;
159415×
    while changed {
15959×
        changed = false;
159619×
        for i in 0..n_ops {
159719×
            if !ops_sel[i] {
159813×
                continue;
15996×
            }
16006×
            if let TreeOp::AddNode { node, parent, .. } = &wc.tree_ops[i] {
16016×
                if let Some(&p) = add_index.get(parent) {
16024×
                    if !ops_sel[p] {
16032×
                        ops_sel[p] = true;
16042×
                        changed = true;
16052×
                    }
16062×
                }
1607
                // A new node's content belongs with its addition: nobody
1608
                // wants an empty file committed apart from its lines.
160912×
                for (j, e) in wc.edits.iter().enumerate() {
161012×
                    if e.node() == *node && !edits_sel[j] {
16111×
                        edits_sel[j] = true;
16121×
                        changed = true;
161311×
                    }
1614
                }
16150×
            }
1616
        }
161718×
        for j in 0..wc.edits.len() {
161818×
            if !edits_sel[j] {
161910×
                continue;
16208×
            }
16218×
            let e = &wc.edits[j];
16228×
            if let Some(&a) = add_index.get(&e.node()) {
16235×
                if !ops_sel[a] {
16241×
                    ops_sel[a] = true;
16251×
                    changed = true;
16264×
                }
16273×
            }
1628
            if let Edit::Insert {
16298×
                node,
16308×
                after,
16318×
                before,
1632
                ..
16338×
            } = e
1634
            {
163516×
                for r in [after, before] {
163616×
                    if let AtomRef::Atom { change, index } = r {
16373×
                        if change.is_zero() {
16380×
                            if let Some(k) = insert_for(node, *index) {
16390×
                                if !edits_sel[k] {
16400×
                                    edits_sel[k] = true;
16410×
                                    changed = true;
16420×
                                }
16430×
                            }
16443×
                        }
164513×
                    }
1646
                }
16470×
            }
1648
        }
1649
    }
1650
    // The retirement of a node shown as one with a selected node.
16516×
    if !unified.is_empty() {
16521×
        let chosen: HashSet<NodeId> = (0..n_ops)
16532×
            .filter(|i| ops_sel[*i])
16541×
            .map(|i| wc.tree_ops[i].node())
16551×
            .chain(
16561×
                (0..wc.edits.len())
16572×
                    .filter(|j| edits_sel[*j])
16581×
                    .map(|j| wc.edits[j].node()),
1659
            )
16601×
            .collect();
16612×
        for (i, o) in wc.tree_ops.iter().enumerate() {
16622×
            if let TreeOp::RemoveNode { node, .. } = o {
16631×
                if unified.get(node).is_some_and(|s| chosen.contains(s)) {
16641×
                    ops_sel[i] = true;
16651×
                }
16661×
            }
1667
        }
16685×
    }
1669
    // Renumber self-references: old atom index → new index among selected inserts.
16706×
    let mut remap: HashMap<(NodeId, u32), u32> = HashMap::new();
16716×
    let mut new_counts: HashMap<NodeId, u32> = HashMap::new();
167212×
    for (j, r) in insert_ranges.iter().enumerate() {
167312×
        if let (true, Some((node, a, b))) = (edits_sel[j], r) {
16745×
            let next = new_counts.entry(*node).or_default();
16755×
            for old in *a..*b {
16765×
                remap.insert((*node, old), *next);
16775×
                *next += 1;
16785×
            }
16797×
        }
1680
    }
168110×
    let map_ref = |r: AtomRef, node: &NodeId| -> AtomRef {
16823×
        match r {
16833×
            AtomRef::Atom { change, index } if change.is_zero() => AtomRef::Atom {
16840×
                change,
16850×
                index: remap.get(&(*node, index)).copied().unwrap_or(index),
16860×
            },
168710×
            other => other,
1688
        }
168910×
    };
16906×
    let ops = wc
16916×
        .tree_ops
16926×
        .iter()
16936×
        .enumerate()
169410×
        .filter(|(i, _)| ops_sel[*i])
16956×
        .map(|(_, o)| o.clone())
16966×
        .collect();
16976×
    let edits = wc
16986×
        .edits
16996×
        .iter()
17006×
        .enumerate()
170112×
        .filter(|(j, _)| edits_sel[*j])
17026×
        .map(|(_, e)| match e {
1703
            Edit::Insert {
17045×
                node,
17055×
                after,
17065×
                before,
17075×
                lines,
17085×
            } => Edit::Insert {
17095×
                node: *node,
17105×
                after: map_ref(*after, node),
17115×
                before: map_ref(*before, node),
17125×
                lines: lines.clone(),
17135×
            },
17140×
            other => other.clone(),
17155×
        })
17166×
        .collect();
17176×
    (ops, edits)
17186×
}
1719
1720
/// Render each tree operation and edit of `change` on its own, numbered.
17218×
pub fn render_hunks(change: &Change, base: &State, base_snapshot: &Snapshot) -> Vec<Hunk> {
17228×
    let by_node = base_snapshot.tree.by_node();
17238×
    let mut new_names: HashMap<NodeId, (NodeId, String, NodeKind)> = HashMap::new();
172410×
    for op in &change.tree_ops {
1725
        if let TreeOp::AddNode {
17269×
            node,
17279×
            parent,
17289×
            name,
17299×
            kind,
1730
            ..
173110×
        } = op
17329×
        {
17339×
            new_names.insert(*node, (*parent, name.clone(), *kind));
17349×
        }
1735
    }
17368×
    let mut out = Vec::new();
173710×
    for (i, op) in change.tree_ops.iter().enumerate() {
1738
        // A retired duplicate goes with the node shown: no hunk of its own.
173910×
        if is_unified_retirement(op, base_snapshot) {
17401×
            continue;
17419×
        }
17429×
        let one = Change {
17439×
            tree_ops: vec![op.clone()],
17449×
            edits: vec![],
17459×
            ..change.clone()
17469×
        };
17479×
        let path = path_of_node(&op.node(), &by_node, &new_names).unwrap_or_default();
17489×
        out.push(Hunk {
17499×
            index: i,
17509×
            path,
17519×
            text: render_change(&one, base, base_snapshot),
17529×
        });
1753
    }
175415×
    for (j, e) in change.edits.iter().enumerate() {
175515×
        let one = Change {
175615×
            tree_ops: vec![],
175715×
            edits: vec![e.clone()],
175815×
            ..change.clone()
175915×
        };
176015×
        let path = path_of_node(&e.node(), &by_node, &new_names).unwrap_or_default();
176115×
        out.push(Hunk {
176215×
            index: change.tree_ops.len() + j,
176315×
            path,
176415×
            text: render_change(&one, base, base_snapshot),
176515×
        });
176615×
    }
17678×
    out
17688×
}
1769
1770
/// One file's part of a diff, for `oxy diff --json`.
1771
#[derive(Clone, Debug)]
1772
pub struct FileDiff {
1773
    pub path: String,
1774
    /// `added`, `removed`, `modified`, `renamed`, `mode`, `replaced`.
1775
    pub kind: String,
1776
    pub hunks: Vec<DiffHunk>,
1777
    /// For renames, the previous path.
1778
    pub from: Option<String>,
1779
}
1780
1781
/// Lines inserted after `base_line` (0 = before the first line) and lines
1782
/// removed, with their base line numbers.
1783
#[derive(Clone, Debug, Default)]
1784
pub struct DiffHunk {
1785
    pub base_line: u32,
1786
    pub added: Vec<Vec<u8>>,
1787
    pub removed: Vec<(u32, Vec<u8>)>,
1788
}
1789
1790
impl Repo {
1791
    /// The content of `path` in a state: `heads`, or the working copy's base.
179227×
    pub fn file_at(&self, path: &str, heads: Option<&[ChangeHash]>) -> Result<Vec<u8>> {
1793
        // The state's history and tree, then the one file's graph: nothing
1794
        // else is built or rendered (oxygen#92).
1795
        // The working copy's base, and a state named by its heads (`-r
1796
        // main` on main), come from the workspace's state index.
179727×
        let base = if self.is_bare() {
17985×
            None
1799
        } else {
180022×
            Some(self.working_copy()?.1.deps)
1801
        };
180227×
        let same = |a: &[ChangeHash], b: &[ChangeHash]| {
18031×
            let (mut a, mut b) = (a.to_vec(), b.to_vec());
18041×
            a.sort();
18051×
            b.sort();
18061×
            a == b
18071×
        };
180827×
        let mut state = match (heads, base) {
18091×
            (Some(h), Some(b)) if same(h, &b) => self.load_state_indexed(&b)?,
18105×
            (Some(h), _) => self.load_state_history(h)?,
181121×
            (None, Some(b)) => self.load_state_indexed(&b)?,
18120×
            (None, None) => return fail("this is a bare repository: it has no working copy"),
1813
        };
181427×
        let view = self.tree_view(&mut state)?;
181527×
        let Some(node) = view.entries.get(path).map(|e| e.node) else {
18160×
            return fail(format!("{path} is not in that state"));
1817
        };
181827×
        self.load_graphs_of(&mut state, &[node])?;
181926×
        let snapshot = state.materialize_paths(view, [path]);
182026×
        let Some(f) = snapshot.files.get(path) else {
18210×
            return fail(format!("{path} is not in that state"));
1822
        };
182326×
        match &f.content {
18240×
            FileContent::Dir => fail(format!("{path} is a directory")),
182526×
            FileContent::Text { bytes, .. } => Ok(bytes.clone()),
18260×
            FileContent::Opaque { blobs } => match blobs.first() {
18270×
                Some(b) => self.read_blob(b),
18280×
                None => Ok(vec![]),
1829
            },
1830
        }
183127×
    }
1832
1833
    /// Restore `paths` (files or directories) to the working copy's base:
1834
    /// edits are undone, additions removed, removals put back. Returns the
1835
    /// number of paths touched.
18362×
    pub fn discard(&self, paths: &[String]) -> Result<usize> {
18372×
        let _wc = self.lock_working_copy()?;
18382×
        let snap = self.snapshot_status("oxy discard")?;
18397×
        let under = |p: &str| {
18407×
            paths
18417×
                .iter()
18427×
                .any(|x| p == x || p.starts_with(&format!("{}/", x.trim_end_matches('/'))))
18437×
        };
18442×
        let attrs = Repo::state_attributes(&snap.base_snapshot);
18452×
        let mut n = 0;
18463×
        for s in &snap.statuses {
18473×
            if !under(&s.path) {
18481×
                continue;
18492×
            }
18502×
            match snap.base_snapshot.files.get(&s.path) {
1851
                None => {
1852
                    // Added (or the new name of a rename): remove it.
18531×
                    let full = self.root.join(&s.path);
18541×
                    if full.is_dir() {
18550×
                        let _ = fs::remove_dir_all(&full);
18561×
                    } else {
18571×
                        let _ = fs::remove_file(&full);
18581×
                    }
18591×
                    n += 1;
1860
                }
18611×
                Some(f) => {
18621×
                    match &f.content {
18630×
                        FileContent::Dir => fs::create_dir_all(self.root.join(&s.path))?,
18641×
                        FileContent::Text { bytes, .. } => {
18651×
                            let on_disk: std::borrow::Cow<[u8]> = if attrs.lookup(&s.path).eol
18661×
                                == Some(crate::attributes::Eol::Crlf)
1867
                            {
18680×
                                crate::attributes::to_crlf(bytes).into()
1869
                            } else {
18701×
                                bytes.as_slice().into()
1871
                            };
18721×
                            self.write_file(&s.path, &on_disk, f.mode.exec)?;
1873
                        }
18740×
                        FileContent::Opaque { blobs } => {
18750×
                            let bytes = match blobs.first() {
18760×
                                Some(b) => self.read_blob(b)?,
18770×
                                None => vec![],
1878
                            };
18790×
                            if f.kind == NodeKind::Symlink {
18800×
                                self.write_symlink(&s.path, &bytes)?;
18810×
                            } else if f.kind == NodeKind::File {
18820×
                                self.write_file(&s.path, &bytes, f.mode.exec)?;
18830×
                            }
1884
                        }
1885
                    }
18861×
                    n += 1;
1887
                }
1888
            }
1889
        }
1890
        // A rename's old name is not in the statuses; put it back too.
18914×
        for (p, f) in &snap.base_snapshot.files {
18924×
            if under(p)
18931×
                && !self.root.join(p).exists()
18940×
                && f.kind != NodeKind::Dir
18950×
                && f.kind != NodeKind::Subrepo
18960×
                && !snap.statuses.iter().any(|s| s.path == *p)
1897
            {
18980×
                let bytes = match &f.content {
18990×
                    FileContent::Text { bytes, .. } => bytes.clone(),
19000×
                    FileContent::Opaque { blobs } => blobs
19010×
                        .first()
19020×
                        .map(|b| self.read_blob(b))
19030×
                        .transpose()?
19040×
                        .unwrap_or_default(),
19050×
                    FileContent::Dir => continue,
1906
                };
19070×
                if f.kind == NodeKind::Symlink {
19080×
                    self.write_symlink(p, &bytes)?
1909
                } else {
19100×
                    self.write_file(p, &bytes, f.mode.exec)?
1911
                }
19120×
                n += 1;
19134×
            }
1914
        }
19152×
        self.drop_manifest();
19162×
        Ok(n)
19172×
    }
1918
1919
    /// Undo the working-copy hunks `indices` (as `hunks` numbers them) on
1920
    /// disk, keeping the others: the files are rewritten from the base plus
1921
    /// the remaining hunks.
19221×
    pub fn discard_hunks(&self, indices: &[usize]) -> Result<usize> {
19231×
        let _wc = self.lock_working_copy()?;
19241×
        let (snap, hunks) = self.hunks()?;
19251×
        let keep: Vec<usize> = hunks
19261×
            .iter()
19271×
            .map(|h| h.index)
19281×
            .filter(|i| !indices.contains(i))
19291×
            .collect();
19301×
        let (ops, edits) = select_hunks(&snap.wc, &keep, &snap.base_snapshot.tree.unified);
19311×
        let dropped_nodes: BTreeSet<NodeId> = hunks
19321×
            .iter()
19331×
            .filter(|h| indices.contains(&h.index))
19341×
            .map(|h| {
19351×
                if h.index < snap.wc.tree_ops.len() {
19360×
                    snap.wc.tree_ops[h.index].node()
1937
                } else {
19381×
                    snap.wc.edits[h.index - snap.wc.tree_ops.len()].node()
1939
                }
19401×
            })
19411×
            .collect();
19421×
        let mut partial = snap.wc.clone();
19431×
        partial.tree_ops = ops;
19441×
        partial.edits = edits;
19451×
        partial.normalize();
19461×
        let mut st = snap.base.clone();
19471×
        st.add_unchecked(partial);
1948
        // Every file of the target is rendered: build the graphs the
1949
        // partial snapshot left out.
19501×
        self.load_all_graphs(&mut st)?;
19511×
        let target = st.materialize();
19521×
        let by_node_target = target.tree.by_node();
19531×
        let by_node_base = snap.base_snapshot.tree.by_node();
19541×
        let attrs = Repo::state_attributes(&target);
19551×
        let mut n = 0;
19561×
        for node in dropped_nodes {
19571×
            match by_node_target.get(&node) {
19581×
                Some(e) => {
19591×
                    let f = &target.files[&e.path];
19601×
                    match &f.content {
19610×
                        FileContent::Dir => {}
19621×
                        FileContent::Text { bytes, .. } => {
19631×
                            let on_disk: std::borrow::Cow<[u8]> = if attrs.lookup(&e.path).eol
19641×
                                == Some(crate::attributes::Eol::Crlf)
1965
                            {
19660×
                                crate::attributes::to_crlf(bytes).into()
1967
                            } else {
19681×
                                bytes.as_slice().into()
1969
                            };
19701×
                            self.write_file(&e.path, &on_disk, f.mode.exec)?;
1971
                        }
19720×
                        FileContent::Opaque { blobs } => {
19730×
                            let bytes = blobs
19740×
                                .first()
19750×
                                .map(|b| self.read_blob(b))
19760×
                                .transpose()?
19770×
                                .unwrap_or_default();
19780×
                            if f.kind == NodeKind::Symlink {
19790×
                                self.write_symlink(&e.path, &bytes)?
1980
                            } else {
19810×
                                self.write_file(&e.path, &bytes, f.mode.exec)?
1982
                            }
1983
                        }
1984
                    }
1985
                    // A discarded rename: the new name goes.
19861×
                    if let Some(old_path) = snap
19871×
                        .statuses
19881×
                        .iter()
19891×
                        .find(|s| {
19901×
                            s.status == ChangeStatus::Renamed && !target.files.contains_key(&s.path)
19911×
                        })
19921×
                        .map(|s| s.path.clone())
19930×
                    {
19940×
                        let _ = fs::remove_file(self.root.join(old_path));
19951×
                    }
19961×
                    n += 1;
1997
                }
1998
                None => {
1999
                    // The node exists in neither target nor base with a live path: an addition to remove.
20000×
                    if let Some(added) = snap.statuses.iter().find(|s| {
20010×
                        s.status == ChangeStatus::Added
20020×
                            && !target.files.contains_key(&s.path)
20030×
                            && !by_node_base.contains_key(&node)
20040×
                    }) {
20050×
                        let full = self.root.join(&added.path);
20060×
                        if full.is_dir() {
20070×
                            let _ = fs::remove_dir_all(&full);
20080×
                        } else {
20090×
                            let _ = fs::remove_file(&full);
20100×
                        }
20110×
                        n += 1;
20120×
                    }
2013
                }
2014
            }
2015
        }
20161×
        self.drop_manifest();
20171×
        Ok(n)
20181×
    }
2019
2020
    /// The diff of the working copy (`None`) or of a change, per file with
2021
    /// line-numbered hunks (spec: `oxy diff --json`).
20227×
    pub fn diff_files(&self, change: Option<&ChangeHash>) -> Result<Vec<FileDiff>> {
20237×
        let (c, base, base_snapshot) = match change {
20243×
            Some(h) => {
20253×
                let c = self.store.get_change(h)?;
20263×
                let (base, snapshot) = self.change_base(&c)?;
20273×
                (c, base, snapshot)
2028
            }
20294×
            None => match self.working_copy_with_base_unless_unchanged()? {
20303×
                Some(all) => all,
20311×
                None => return Ok(Vec::new()),
2032
            },
2033
        };
20346×
        Ok(diff_files_of(&c, &base, &base_snapshot))
20357×
    }
2036
2037
    /// The snapshot a command would take, without taking it, when the
2038
    /// status cache holds: every file is as the last snapshot left it, so
2039
    /// that snapshot's working-copy change is the answer. Its base comes
2040
    /// from the state index, the `.oxyattributes` files from disk. `None`
2041
    /// when a snapshot must be taken, and when there is nothing to commit
2042
    /// (the snapshot then says so). A conflicted base never gets here: the
2043
    /// cache does not hold for one.
2044771×
    pub(crate) fn snapshot_from_cache(&self) -> Result<Option<SnapshotResult>> {
2045771×
        let Some(statuses) = self.status_by_manifest()? else {
2046542×
            return Ok(None);
2047
        };
2048229×
        if statuses.is_empty() {
20493×
            return Ok(None);
2050226×
        }
2051226×
        let _t = crate::timing::phase("snapshot: from the status cache");
2052226×
        let (wc_hash, wc) = self.working_copy()?;
2053226×
        let base = self.load_state_indexed(&wc.deps)?;
2054226×
        let (base, base_snapshot) = self.render_base_for(&wc, base)?;
2055226×
        let attribute_files: Vec<(String, Vec<u8>)> = match self.read_manifest()? {
2056226×
            Some((_, _, m)) => m
2057226×
                .entries
2058226×
                .keys()
2059684×
                .filter(|p| is_attributes(p))
2060226×
                .filter_map(|p| fs::read(self.root.join(p)).ok().map(|b| (p.clone(), b)))
2061226×
                .collect(),
20620×
            None => Vec::new(),
2063
        };
2064226×
        let attributes = crate::attributes::Attributes::from_files(
2065226×
            attribute_files
2066226×
                .iter()
2067226×
                .map(|(p, b)| (p.as_str(), b.as_slice())),
2068
        );
2069226×
        Ok(Some(SnapshotResult {
2070226×
            wc_hash,
2071226×
            wc,
2072226×
            base,
2073226×
            base_snapshot,
2074226×
            statuses,
2075226×
            changed: false,
2076226×
            resolves: false,
2077226×
            contributors: Vec::new(),
2078226×
            attributes,
2079226×
            untracked_nested: self.untracked_nested.borrow().clone(),
2080226×
            manifest: None,
2081226×
        }))
2082771×
    }
2083
2084
    /// The working-copy change with its base state and a snapshot of the
2085
    /// base, for showing what the working copy changes ([`render_change`],
2086
    /// [`diff_files_of`]). While the status cache holds (every file as the
2087
    /// last snapshot left it), the stored working-copy change is the
2088
    /// answer, no snapshot is taken, and the base's snapshot holds its tree
2089
    /// but no file; otherwise a snapshot makes all three.
20902×
    pub fn working_copy_with_base(&self) -> Result<(Change, State, Snapshot)> {
20912×
        match self.working_copy_with_base_unless_unchanged()? {
20921×
            Some(all) => Ok(all),
2093
            None => {
20941×
                let (_, wc) = self.working_copy()?;
20951×
                let base = self.load_state_indexed(&wc.deps)?;
20961×
                let (base, snapshot) = self.tree_base_for(&wc, base)?;
20971×
                Ok((wc, base, snapshot))
2098
            }
2099
        }
21002×
    }
2101
2102
    /// [`Repo::working_copy_with_base`], or `None` when the status cache
2103
    /// holds and the working-copy change changes nothing: its diff is
2104
    /// empty, and the base is not loaded for it (oxygen#94).
21057×
    pub fn working_copy_with_base_unless_unchanged(
21067×
        &self,
21077×
    ) -> Result<Option<(Change, State, Snapshot)>> {
21087×
        if self.status_by_manifest()?.is_some() {
21095×
            let (_, wc) = self.working_copy()?;
21105×
            if wc.tree_ops.is_empty() && wc.edits.is_empty() {
21113×
                return Ok(None);
21122×
            }
21132×
            let base = self.load_state_indexed(&wc.deps)?;
21142×
            let (base, snapshot) = self.tree_base_for(&wc, base)?;
21152×
            return Ok(Some((wc, base, snapshot)));
21162×
        }
21172×
        let snap = self.snapshot_status("oxy diff")?;
21182×
        Ok(Some((snap.wc, snap.base, snap.base_snapshot)))
21197×
    }
2120
2121
    /// The log restricted to changes touching `path` (its node, so renames
2122
    /// are followed), on the current bookmark.
21236×
    pub fn log_for_path(&self, path: &str) -> Result<Vec<LogEntry>> {
21246×
        let heads = self.bookmark_heads()?;
21256×
        if self.is_bare() {
21261×
            return self.log_for_path_in(path, &heads);
21275×
        }
21285×
        let entries = self.log()?;
21295×
        let (_, wc) = self.working_copy()?;
2130
        // The path's node from the trees alone: the base's (from the
2131
        // workspace's state index), else the bookmark's. Nothing is
2132
        // rendered.
21335×
        let node_in = |mut state: State| -> Result<Option<HashSet<NodeId>>> {
21345×
            Ok(nodes_at(&self.tree_view(&mut state)?, path))
21355×
        };
21365×
        let nodes = match node_in(self.load_state_indexed(&wc.deps)?)? {
21375×
            Some(n) => Some(n),
21380×
            None => node_in(self.load_state_history(&heads)?)?,
2139
        };
21405×
        let Some(nodes) = nodes else {
21410×
            return fail(format!("{path} is not tracked"));
2142
        };
21435×
        Ok(self.entries_touching_up_to(entries, nodes, None))
21446×
    }
2145
2146
    /// The log of the state with these heads restricted to changes touching
2147
    /// `path` (its node, so renames are followed).
21482×
    pub fn log_for_path_in(&self, path: &str, heads: &[ChangeHash]) -> Result<Vec<LogEntry>> {
21492×
        self.log_for_path_of(&self.load_state_history(heads)?, path, None)
21502×
    }
2151
2152
    /// The changes of a loaded state touching `path`, newest first, at most
2153
    /// `limit` of them. The path is found in the state's tree alone, so no
2154
    /// file is rendered, and the walk stops once `limit` are found.
21555×
    pub fn log_for_path_of(
21565×
        &self,
21575×
        state: &State,
21585×
        path: &str,
21595×
        limit: Option<usize>,
21605×
    ) -> Result<Vec<LogEntry>> {
21615×
        let Some(nodes) = nodes_at(&state.view(), path) else {
21621×
            return fail(format!("{path} is not in that state"));
2163
        };
21644×
        Ok(self.entries_touching_up_to(self.log_of(state), nodes, limit))
21655×
    }
2166
21679×
    fn entries_touching_up_to(
21689×
        &self,
21699×
        entries: Vec<LogEntry>,
21709×
        wanted: HashSet<NodeId>,
21719×
        limit: Option<usize>,
21729×
    ) -> Vec<LogEntry> {
21739×
        let mut touched = self.touched();
21749×
        if limit.is_none() {
21758×
            let hashes: Vec<ChangeHash> = entries.iter().map(|e| e.hash).collect();
21768×
            touched.fill(self, &hashes);
21771×
        }
21789×
        let mut out = Vec::new();
217932×
        for e in entries {
218032×
            if limit.is_some_and(|n| out.len() >= n) {
21811×
                break;
218231×
            }
218331×
            if touched.touches(self, &e.hash, &wanted) {
218420×
                out.push(e);
218520×
            }
2186
        }
21879×
        touched.save();
21889×
        out
21899×
    }
2190
}
2191
2192
/// The node at `path` in `view`, with the nodes it shows as one with it
2193
/// (identical additions, spec §9.2): the file's history is all of theirs.
219410×
fn nodes_at(view: &crate::tree::TreeView, path: &str) -> Option<HashSet<NodeId>> {
219510×
    let node = view.entries.get(path)?.node;
21969×
    let mut out = HashSet::from([node]);
21979×
    out.extend(
21989×
        view.unified
21999×
            .iter()
22009×
            .filter(|(_, shown)| **shown == node)
22019×
            .map(|(dup, _)| *dup),
2202
    );
22039×
    Some(out)
220410×
}
2205
2206
/// Per-file hunks of `change` against `base`.
22076×
pub fn diff_files_of(change: &Change, base: &State, base_snapshot: &Snapshot) -> Vec<FileDiff> {
22086×
    let by_node = base_snapshot.tree.by_node();
22096×
    let mut new_names: HashMap<NodeId, (NodeId, String, NodeKind)> = HashMap::new();
22106×
    for op in &change.tree_ops {
2211
        if let TreeOp::AddNode {
22122×
            node,
22132×
            parent,
22142×
            name,
22152×
            kind,
2216
            ..
22173×
        } = op
22182×
        {
22192×
            new_names.insert(*node, (*parent, name.clone(), *kind));
22202×
        }
2221
    }
222210×
    let path_of = |n: &NodeId| -> String {
222310×
        path_of_node(n, &by_node, &new_names).unwrap_or_else(|| format!("<node {}>", n.short(8)))
222410×
    };
22256×
    let mut files: BTreeMap<NodeId, FileDiff> = BTreeMap::new();
22266×
    let mut order: Vec<NodeId> = Vec::new();
222715×
    let mut entry = |files: &mut BTreeMap<NodeId, FileDiff>, n: NodeId, kind: &str| {
222815×
        if let std::collections::btree_map::Entry::Vacant(v) = files.entry(n) {
222910×
            order.push(n);
223010×
            v.insert(FileDiff {
223110×
                path: path_of(&n),
223210×
                kind: kind.to_string(),
223310×
                hunks: vec![],
223410×
                from: None,
223510×
            });
223610×
        }
223715×
    };
22386×
    for op in change
22396×
        .tree_ops
22406×
        .iter()
22416×
        .filter(|o| !is_unified_retirement(o, base_snapshot))
2242
    {
22433×
        match op {
22442×
            TreeOp::AddNode { node, kind, .. } => {
22452×
                if *kind != NodeKind::Dir {
22462×
                    entry(&mut files, *node, "added");
22472×
                }
2248
            }
22491×
            TreeOp::RemoveNode { node, .. } => {
22501×
                entry(&mut files, *node, "removed");
22511×
                if let Some(e) = by_node.get(node) {
22521×
                    files.get_mut(node).unwrap().path = e.path.clone();
22531×
                }
2254
            }
2255
            TreeOp::Move {
22560×
                node, parent, name, ..
2257
            } => {
22580×
                entry(&mut files, *node, "renamed");
22590×
                let f = files.get_mut(node).unwrap();
22600×
                f.from = by_node.get(node).map(|e| e.path.clone());
22610×
                let dir = if parent.is_root() {
22620×
                    String::new()
2263
                } else {
22640×
                    path_of_node(parent, &by_node, &new_names).unwrap_or_default()
2265
                };
22660×
                f.path = if dir.is_empty() {
22670×
                    name.clone()
2268
                } else {
22690×
                    format!("{dir}/{name}")
2270
                };
2271
            }
22720×
            TreeOp::SetMode { node, .. } => entry(&mut files, *node, "mode"),
2273
        }
2274
    }
2275
    // Base line numbers per node, 1-based.
22766×
    let mut line_of: HashMap<NodeId, HashMap<(ChangeHash, u32), u32>> = HashMap::new();
227712×
    let mut lines_for = |n: &NodeId| -> HashMap<(ChangeHash, u32), u32> {
227812×
        line_of
227912×
            .entry(*n)
228012×
            .or_insert_with(|| {
22819×
                base.live_lines(n)
22829×
                    .into_iter()
22839×
                    .enumerate()
228412×
                    .map(|(i, (k, _))| (k, i as u32 + 1))
22859×
                    .collect()
22869×
            })
228712×
            .clone()
228812×
    };
228912×
    for e in &change.edits {
229012×
        let n = e.node();
229112×
        let is_new = new_names.contains_key(&n);
229212×
        entry(&mut files, n, if is_new { "added" } else { "modified" });
229312×
        let f = files.get_mut(&n).unwrap();
229412×
        match e {
229510×
            Edit::Insert { after, lines, .. } => {
229610×
                let map = lines_for(&n);
229710×
                let base_line = match after {
22983×
                    AtomRef::Start => 0,
22990×
                    AtomRef::End => map.len() as u32,
23007×
                    AtomRef::Atom { change, index } if change.is_zero() => {
23010×
                        f.hunks.last().map(|h| h.base_line).unwrap_or(0)
2302
                    }
23037×
                    AtomRef::Atom { change, index } => {
23047×
                        map.get(&(*change, *index)).copied().unwrap_or(0)
2305
                    }
2306
                };
230710×
                f.hunks.push(DiffHunk {
230810×
                    base_line,
230910×
                    added: lines.to_vec(),
231010×
                    removed: vec![],
231110×
                });
2312
            }
23132×
            Edit::Delete { atoms, .. } => {
23142×
                let map = lines_for(&n);
23152×
                let mut removed = Vec::new();
23162×
                for r in atoms {
23172×
                    for i in r.from..r.to {
23182×
                        let line = map.get(&(r.change, i)).copied().unwrap_or(0);
23192×
                        let text = base
23202×
                            .file(&n)
23212×
                            .and_then(|g| g.content(&(r.change, i)))
23222×
                            .unwrap_or(b"")
23232×
                            .to_vec();
23242×
                        removed.push((line, text));
2325
                    }
2326
                }
23272×
                let base_line = removed
23282×
                    .first()
23292×
                    .map(|(l, _)| l.saturating_sub(1))
23302×
                    .unwrap_or(0);
23312×
                f.hunks.push(DiffHunk {
23322×
                    base_line,
23332×
                    added: vec![],
23342×
                    removed,
23352×
                });
2336
            }
2337
            Edit::Replace { .. } => {
23380×
                if !is_new {
23390×
                    f.kind = "replaced".into();
23400×
                }
2341
            }
2342
        }
2343
    }
234410×
    order.into_iter().filter_map(|n| files.remove(&n)).collect()
23456×
}
2346
2347
/// Builds the tree ops and edits of a working-copy change against a base.
2348
/// `BLAKE3("oxy node 1" 0 seed kind path)`, truncated: a node identifier
2349
/// that the same seed and path always give (never the root's).
235059×
fn seeded_node(seed: &[u8; 32], path: &str, kind: NodeKind) -> NodeId {
235159×
    let mut h = blake3::Hasher::new();
235259×
    h.update(b"oxy node 1\0");
235359×
    h.update(seed);
235459×
    h.update(&[match kind {
235545×
        NodeKind::File => 1,
235613×
        NodeKind::Dir => 2,
23570×
        NodeKind::Symlink => 3,
23581×
        NodeKind::Subrepo => 4,
2359
    }]);
236059×
    h.update(path.as_bytes());
236159×
    let mut id = [0u8; 16];
236259×
    id.copy_from_slice(&h.finalize().as_bytes()[..16]);
236359×
    if id == [0; 16] {
23640×
        id[15] = 1;
236559×
    }
236659×
    NodeId(id)
236759×
}
2368
2369
struct ChangeBuilder<'a> {
2370
    base: &'a State,
2371
    base_snapshot: &'a Snapshot,
2372
    tree_ops: Vec<TreeOp>,
2373
    edits: Vec<Edit>,
2374
    statuses: Vec<PathStatus>,
2375
    dir_nodes: HashMap<String, NodeId>,
2376
    reuse: HashMap<String, (NodeId, NodeKind)>,
2377
    /// Changes that contributed to conflicts this working copy resolves.
2378
    contributors: BTreeSet<ChangeHash>,
2379
    resolves: bool,
2380
    attrs: crate::attributes::Attributes,
2381
    blobs: HashMap<String, ObjectRef>,
2382
    /// Opaque files whose replace conflict the content settles.
2383
    resolve: HashSet<String>,
2384
    /// When set, new nodes' identifiers derive from it and their paths.
2385
    node_seed: Option<[u8; 32]>,
2386
    /// For a Git import, the base's dead directories by where they were
2387
    /// (see `ensure_dir`), worked out when first needed.
2388
    dead_dirs: Option<HashMap<(NodeId, String), (NodeId, crate::tree::OpKey)>>,
2389
    /// Text edits of edited files, worked out in parallel beforehand
2390
    /// (`diff_in_parallel`); a file not here is diffed when it is updated.
2391
    diffs: HashMap<String, Vec<Edit>>,
2392
}
2393
2394
impl<'a> ChangeBuilder<'a> {
23952403×
    fn new(
23962403×
        base: &'a State,
23972403×
        base_snapshot: &'a Snapshot,
23982403×
        reuse: HashMap<String, (NodeId, NodeKind)>,
23992403×
    ) -> Self {
24002403×
        let mut dir_nodes: HashMap<String, NodeId> = HashMap::new();
24012403×
        dir_nodes.insert(String::new(), NodeId::ROOT);
240218340×
        for (p, e) in base_snapshot.tree.entries.iter() {
240318340×
            if e.kind == NodeKind::Dir {
2404604×
                dir_nodes.insert(p.clone(), e.node);
240517736×
            }
2406
        }
24072403×
        ChangeBuilder {
24082403×
            base,
24092403×
            base_snapshot,
24102403×
            tree_ops: vec![],
24112403×
            edits: vec![],
24122403×
            statuses: vec![],
24132403×
            dir_nodes,
24142403×
            reuse,
24152403×
            contributors: BTreeSet::new(),
24162403×
            resolves: false,
24172403×
            attrs: crate::attributes::Attributes::default(),
24182403×
            blobs: HashMap::new(),
24192403×
            resolve: HashSet::new(),
24202403×
            node_seed: None,
24212403×
            dead_dirs: None,
24222403×
            diffs: HashMap::new(),
24232403×
        }
24242403×
    }
2425
2426
    /// Diff the edited text files among `entries` against their base
2427
    /// renderings at once, on every core, for `update_path` to take: the
2428
    /// same diff it would make, only not one file after another.
24292403×
    fn diff_in_parallel(&mut self, entries: &BTreeMap<String, FsEntry>) {
2430
        use rayon::prelude::*;
24312403×
        let files = &self.base_snapshot.files;
24322403×
        let edited: Vec<(&String, &FsEntry, &crate::state::FileState)> = entries
24332403×
            .iter()
243419498×
            .filter_map(|(p, e)| {
243519498×
                let x = files.get(p)?;
243613270×
                (x.kind == e.kind && !e.unchanged && !self.opaque_for(p, e)).then_some((p, e, x))
243719498×
            })
24382403×
            .collect();
2439
        // Below this, starting the threads costs more than it saves.
24402403×
        if edited.len() < 16 {
24412393×
            return;
244210×
        }
244310×
        let this = &*self;
244410×
        let attrs = &this.attrs;
244510×
        let diffs: Vec<(String, Vec<Edit>)> = edited
244610×
            .par_iter()
24475564×
            .filter_map(|(p, e, x)| {
2448
                let FileContent::Text {
24495564×
                    bytes,
24505564×
                    materialized,
24515564×
                } = &x.content
2452
                else {
24530×
                    return None;
2454
                };
24555564×
                if materialized.is_conflicted() {
24560×
                    return None;
24575564×
                }
24585564×
                let disk_text = if attrs.lookup(p).eol.is_some() {
24590×
                    std::sync::Arc::new(crate::attributes::normalize_eol(&e.content))
2460
                } else {
24615564×
                    e.content.clone()
2462
                };
24635564×
                if *bytes == *disk_text {
24645484×
                    return None;
246580×
                }
246680×
                let keys = materialized.live_atoms();
246780×
                let lines = crate::diff::split_lines(bytes);
246880×
                (keys.len() == lines.len()).then(|| {
246980×
                    let edits = crate::diff::text_edits_of(x.node, &keys, &lines, &disk_text);
247080×
                    ((*p).clone(), edits)
247180×
                })
24725564×
            })
247310×
            .collect();
247410×
        self.diffs = diffs.into_iter().collect();
24752403×
    }
2476
24772403×
    fn with_attributes(mut self, attrs: crate::attributes::Attributes) -> Self {
24782403×
        self.attrs = attrs;
24792403×
        self
24802403×
    }
2481
2482
    /// Whether a file is opaque: forced by `binary`, forced text by `text`
2483
    /// only when it has no NUL bytes, else sniffed.
2484
    /// The blob for an opaque entry: the cached one, else stored now.
2485176×
    fn blob_of(
2486176×
        &mut self,
2487176×
        repo: &Repo,
2488176×
        path: &str,
2489176×
        e: &FsEntry,
2490176×
        nocompress: bool,
2491176×
    ) -> Result<ObjectRef> {
2492176×
        let b = match e.blob {
24930×
            Some(b) => b,
2494176×
            None => repo.store_blob_for(&e.content, nocompress)?,
2495
        };
2496176×
        self.blobs.insert(path.to_string(), b);
2497176×
        Ok(b)
2498176×
    }
2499
250024281×
    fn opaque_for(&self, path: &str, e: &FsEntry) -> bool {
250124281×
        if e.blob.is_some() {
25024×
            return true;
250324277×
        }
250424277×
        if e.kind == NodeKind::Symlink || e.kind == NodeKind::Subrepo {
2505132×
            return true;
250624145×
        }
250724145×
        match self.attrs.lookup(path).binary {
250812×
            Some(true) => true,
25090×
            Some(false) => is_binary(&e.content),
251024133×
            None => is_binary(&e.content),
2511
        }
251224281×
    }
2513
2514
    /// Text content as stored: `\r\n` normalized for `eol=` files.
251515088×
    fn stored_text(
251615088×
        &self,
251715088×
        path: &str,
251815088×
        content: &std::sync::Arc<Vec<u8>>,
251915088×
    ) -> std::sync::Arc<Vec<u8>> {
252015088×
        if self.attrs.lookup(path).eol.is_some() {
25217×
            std::sync::Arc::new(crate::attributes::normalize_eol(content))
2522
        } else {
252315081×
            content.clone()
2524
        }
252515088×
    }
2526
2527
    /// The identifier of a node added at `path`: reused when asked, derived
2528
    /// from the seed when there is one, random otherwise.
25296352×
    fn new_node(&self, path: &str, kind: NodeKind) -> NodeId {
25306352×
        if let Some(n) = self.reused_node(path, kind) {
2531170×
            return n;
25326182×
        }
25336182×
        match &self.node_seed {
253459×
            Some(seed) => seeded_node(seed, path, kind),
25356123×
            None => NodeId::random(),
2536
        }
25376352×
    }
2538
25396352×
    fn reused_node(&self, path: &str, kind: NodeKind) -> Option<NodeId> {
25406352×
        self.reuse
25416352×
            .get(path)
25426352×
            .filter(|(_, k)| *k == kind)
25436352×
            .map(|(n, _)| *n)
25446352×
    }
2545
2546
    /// A dead directory last placed at (`parent`, `name`) in the base.
254715×
    fn revivable_dir(
254815×
        &mut self,
254915×
        parent: NodeId,
255015×
        name: &str,
255115×
    ) -> Option<(NodeId, crate::tree::OpKey)> {
255215×
        let base = self.base;
255315×
        self.dead_dirs
255415×
            .get_or_insert_with(|| base.tree().dead_dirs())
255515×
            .get(&(parent, name.to_string()))
255615×
            .copied()
255715×
    }
2558
25596229×
    fn ensure_dir(&mut self, path: &str) -> NodeId {
25606229×
        if let Some(n) = self.dir_nodes.get(path) {
25616075×
            return *n;
2562154×
        }
2563154×
        let mut parent = NodeId::ROOT;
2564154×
        let mut prefix = String::new();
2565173×
        for comp in path.split('/') {
2566173×
            if !prefix.is_empty() {
256719×
                prefix.push('/');
2568154×
            }
2569173×
            prefix.push_str(comp);
2570173×
            let known = self.dir_nodes.get(&prefix).copied();
2571173×
            let revive = match known {
257213×
                Some(_) => None,
2573160×
                None if self.node_seed.is_some() => self.revivable_dir(parent, comp),
2574145×
                None => None,
2575
            };
2576173×
            parent = match (known, revive) {
257713×
                (Some(n), _) => n,
25782×
                (None, Some((node, old))) => {
2579
                    // Git has no identity for a directory: one that comes
2580
                    // back where it was is the same directory, brought back
2581
                    // with a move, so lines of history that placed files in
2582
                    // it before and after agree (oxygen#30).
25832×
                    self.tree_ops.push(TreeOp::Move {
25842×
                        node,
25852×
                        old: OpRef {
25862×
                            change: old.0,
25872×
                            index: old.1,
25882×
                        },
25892×
                        parent,
25902×
                        name: comp.to_string(),
25912×
                    });
25922×
                    self.dir_nodes.insert(prefix.clone(), node);
25932×
                    node
2594
                }
2595
                (None, None) => {
2596158×
                    let node = self.new_node(&prefix, NodeKind::Dir);
2597158×
                    self.tree_ops.push(TreeOp::AddNode {
2598158×
                        node,
2599158×
                        kind: NodeKind::Dir,
2600158×
                        mode: Mode::default(),
2601158×
                        parent,
2602158×
                        name: comp.to_string(),
2603158×
                    });
2604158×
                    self.dir_nodes.insert(prefix.clone(), node);
2605158×
                    node
2606
                }
2607
            };
2608
        }
2609154×
        parent
26106229×
    }
2611
26126194×
    fn add_path(&mut self, repo: &Repo, path: &str, e: &FsEntry) -> Result<()> {
26136194×
        let (dir, name) = split_path(path);
26146194×
        let parent = self.ensure_dir(dir);
26156194×
        let node = self.new_node(path, e.kind);
26166194×
        let opaque = self.opaque_for(path, e);
26176194×
        let nocompress = self.attrs.lookup(path).nocompress;
26186194×
        self.tree_ops.push(TreeOp::AddNode {
26196194×
            node,
26206194×
            kind: e.kind,
26216194×
            mode: Mode {
26226194×
                exec: e.exec,
26236194×
                opaque,
26246194×
            },
26256194×
            parent,
26266194×
            name: name.to_string(),
26276194×
        });
26286194×
        if opaque {
2629127×
            let blob = self.blob_of(repo, path, e, nocompress)?;
2630127×
            self.edits.push(Edit::Replace {
2631127×
                node,
2632127×
                old: None,
2633127×
                new: Some(blob),
2634127×
            });
26356067×
        } else if !e.content.is_empty() {
26366027×
            let content = self.stored_text(path, &e.content);
26376027×
            self.edits.push(Edit::Insert {
26386027×
                node,
26396027×
                after: crate::objects::AtomRef::Start,
26406027×
                before: crate::objects::AtomRef::End,
26416027×
                lines: crate::lines::Lines::split_shared(content),
26426027×
            });
26436027×
        }
26446194×
        self.statuses.push(PathStatus {
26456194×
            path: path.to_string(),
26466194×
            status: ChangeStatus::Added,
26476194×
        });
26486194×
        Ok(())
26496194×
    }
2650
2651
    /// Move the node at `old` to `new` and apply `e`'s content to it.
265235×
    fn move_path(
265335×
        &mut self,
265435×
        repo: &Repo,
265535×
        old: &str,
265635×
        new: &str,
265735×
        e: &FsEntry,
265835×
        expected: &crate::state::FileState,
265935×
    ) -> Result<()> {
266035×
        let placement = self.base_snapshot.tree.entries[old].placement;
266135×
        let (dir, name) = split_path(new);
266235×
        let parent = self.ensure_dir(dir);
266335×
        self.tree_ops.push(TreeOp::Move {
266435×
            node: expected.node,
266535×
            old: op_ref(placement),
266635×
            parent,
266735×
            name: name.to_string(),
266835×
        });
266935×
        for k in self.same_place(&expected.node, placement) {
26700×
            self.tree_ops.push(TreeOp::RemoveNode {
26710×
                node: expected.node,
26720×
                placement: op_ref(k),
26730×
            });
26740×
        }
267535×
        self.update_path(repo, old, e, expected)?;
2676
        // update_path reports under the old path; the rename is what the user sees.
267735×
        self.statuses.retain(|s| s.path != old);
267835×
        self.statuses.push(PathStatus {
267935×
            path: new.to_string(),
268035×
            status: ChangeStatus::Renamed,
268135×
        });
268235×
        Ok(())
268335×
    }
2684
2685
    /// For a Git import: a node the commit keeps is in one place, the one
2686
    /// its tree names, so any other live placement it has in the base goes;
2687
    /// and a node the tree cannot show at all (an orphan) goes too. Such a
2688
    /// placement is out of sight, under a directory another line of history
2689
    /// removed, where no diff of the tree would ever reach it (oxygen#30).
269088×
    fn retire_stray_placements(&mut self) {
269188×
        let mut retired: HashSet<(ChangeHash, u32)> = HashSet::new();
269288×
        let mut placed: BTreeSet<NodeId> = BTreeSet::new();
269399×
        for op in &self.tree_ops {
269499×
            match op {
269519×
                TreeOp::Move { node, old, .. } => {
269619×
                    retired.insert((old.change, old.index));
269719×
                    placed.insert(*node);
269819×
                }
269921×
                TreeOp::RemoveNode { placement, .. } => {
270021×
                    retired.insert((placement.change, placement.index));
270121×
                }
270259×
                TreeOp::AddNode { .. } | TreeOp::SetMode { .. } => {}
2703
            }
2704
        }
2705
        // Nodes kept where they were: what the base's tree view shows and
2706
        // this change neither moves nor removes.
270788×
        let mut kept: HashMap<NodeId, (ChangeHash, u32)> = HashMap::new();
2708241×
        for e in self.base_snapshot.tree.entries.values() {
2709241×
            if !retired.contains(&e.placement) {
2710204×
                kept.insert(e.node, e.placement);
2711204×
            }
2712
        }
2713
        // Only a node with several live placements can have a stray one,
2714
        // and the tree view names each as a conflict.
271588×
        let multi: BTreeSet<NodeId> = self
271688×
            .base_snapshot
271788×
            .tree
271888×
            .conflicts
271988×
            .iter()
272088×
            .filter_map(|c| match c {
27211×
                crate::tree::TreeConflict::MultiPlacement { node, .. } => Some(*node),
27226×
                _ => None,
27237×
            })
272488×
            .collect();
272588×
        let mut extra = Vec::new();
2726
        // A node whose only placements are under a directory another line
2727
        // removed (an orphan) is nowhere the tree can show, and Git's tree
2728
        // has no such path: it goes.
272988×
        for c in &self.base_snapshot.tree.conflicts {
27307×
            let crate::tree::TreeConflict::Orphan { node, .. } = c else {
27316×
                continue;
2732
            };
27331×
            if kept.contains_key(node) || placed.contains(node) {
27340×
                continue;
27351×
            }
27361×
            for (k, _) in self.base.tree().live_placements(node) {
27371×
                if retired.insert(k) {
27381×
                    extra.push(TreeOp::RemoveNode {
27391×
                        node: *node,
27401×
                        placement: op_ref(k),
27411×
                    });
27421×
                }
2743
            }
2744
        }
274588×
        for node in placed
274688×
            .iter()
274788×
            .chain(multi.iter().filter(|n| kept.contains_key(*n)))
2748
        {
274919×
            for (k, _) in self.base.tree().live_placements(node) {
275018×
                if retired.contains(&k) || kept.get(node) == Some(&k) {
275117×
                    continue;
27521×
                }
27531×
                retired.insert(k);
27541×
                extra.push(TreeOp::RemoveNode {
27551×
                    node: *node,
27561×
                    placement: op_ref(k),
27571×
                });
2758
            }
2759
        }
276088×
        if !extra.is_empty() {
27612×
            self.resolves = true;
27622×
            self.tree_ops.extend(extra);
276386×
        }
276488×
    }
2765
2766
    /// Nodes the base shows as one with another (identical additions at one
2767
    /// path, spec §9.2) are retired by the change that first touches the
2768
    /// node shown: edited, moved, removed or given a mode alone, it would
2769
    /// differ from them and the name conflict would come back. Nothing
2770
    /// else changes for the user, so no status reports it.
27712403×
    fn retire_unified(&mut self) {
27722403×
        let unified = &self.base_snapshot.tree.unified;
27732403×
        if unified.is_empty() {
27742376×
            return;
277527×
        }
277627×
        let touched: HashSet<NodeId> = self
277727×
            .tree_ops
277827×
            .iter()
277927×
            .map(|o| o.node())
278027×
            .chain(self.edits.iter().map(|e| e.node()))
278127×
            .collect();
278227×
        let mut retired: HashSet<(ChangeHash, u32)> = HashSet::new();
278327×
        for op in &self.tree_ops {
278414×
            match op {
27853×
                TreeOp::Move { old, .. } => {
27863×
                    retired.insert((old.change, old.index));
27873×
                }
27883×
                TreeOp::RemoveNode { placement, .. } => {
27893×
                    retired.insert((placement.change, placement.index));
27903×
                }
27918×
                TreeOp::AddNode { .. } | TreeOp::SetMode { .. } => {}
2792
            }
2793
        }
279427×
        let mut extra = Vec::new();
279530×
        for (dup, shown) in unified {
279630×
            if !touched.contains(shown) {
279713×
                continue;
279817×
            }
279917×
            for (k, _) in self.base.tree().live_placements(dup) {
280017×
                if retired.insert(k) {
280117×
                    extra.push(TreeOp::RemoveNode {
280217×
                        node: *dup,
280317×
                        placement: op_ref(k),
280417×
                    });
280517×
                }
2806
            }
2807
        }
280827×
        self.tree_ops.extend(extra);
28092403×
    }
2810
2811
    /// The node's other live placements at the same place as `k`, the one
2812
    /// the tree shows: two lines of history that put a node back where it
2813
    /// was each leave a placement, and the tree shows them as one file. A
2814
    /// change that removes or moves it retires them together, or the copy
2815
    /// left behind outlives its directory (oxygen#88).
2816157×
    fn same_place(&self, node: &NodeId, k: (ChangeHash, u32)) -> Vec<(ChangeHash, u32)> {
2817157×
        let tree = self.base.tree();
2818157×
        let Some(shown) = tree.placement(&k) else {
28190×
            return Vec::new();
2820
        };
2821157×
        tree.live_placements(node)
2822157×
            .into_iter()
2823159×
            .filter(|(o, p)| *o != k && p.parent == shown.parent && p.name == shown.name)
2824157×
            .map(|(o, _)| o)
2825157×
            .collect()
2826157×
    }
2827
2828122×
    fn remove_path(&mut self, path: &str, expected: &crate::state::FileState) {
2829122×
        let entry = &self.base_snapshot.tree.entries[path];
2830122×
        let placement = entry.placement;
2831122×
        self.tree_ops.push(TreeOp::RemoveNode {
2832122×
            node: expected.node,
2833122×
            placement: op_ref(placement),
2834122×
        });
2835122×
        for k in self.same_place(&expected.node, placement) {
28361×
            self.tree_ops.push(TreeOp::RemoveNode {
28371×
                node: expected.node,
28381×
                placement: op_ref(k),
28391×
            });
28401×
        }
2841122×
        if path.contains(".oxy-conflict-") || expected.is_conflicted() {
28427×
            self.resolves = true;
2843115×
        }
2844122×
        self.statuses.push(PathStatus {
2845122×
            path: path.to_string(),
2846122×
            status: ChangeStatus::Removed,
2847122×
        });
2848122×
    }
2849
285013305×
    fn update_path(
285113305×
        &mut self,
285213305×
        repo: &Repo,
285313305×
        path: &str,
285413305×
        e: &FsEntry,
285513305×
        expected: &crate::state::FileState,
285613305×
    ) -> Result<()> {
285713305×
        if expected.kind != e.kind {
28581×
            self.remove_path(path, expected);
28591×
            self.statuses.pop();
28601×
            self.add_path(repo, path, e)?;
28611×
            self.statuses.pop();
28621×
            self.statuses.push(PathStatus {
28631×
                path: path.to_string(),
28641×
                status: ChangeStatus::Modified,
28651×
            });
28661×
            return Ok(());
286713304×
        }
286813304×
        let entry = &self.base_snapshot.tree.entries[path];
286913304×
        let node = expected.node;
287013304×
        let mode_atom = entry.mode_atom.map(op_ref);
287113304×
        if e.unchanged {
2872
            // Known equal to the base's unconflicted rendering (spec
2873
            // §12.3); only the executable bit can differ.
28744243×
            if e.exec != expected.mode.exec {
28753×
                if let Some(old) = mode_atom {
28763×
                    self.tree_ops.push(TreeOp::SetMode {
28773×
                        node,
28783×
                        old,
28793×
                        mode: Mode {
28803×
                            exec: e.exec,
28813×
                            opaque: false,
28823×
                        },
28833×
                    });
28843×
                    self.statuses.push(PathStatus {
28853×
                        path: path.to_string(),
28863×
                        status: ChangeStatus::ModeChanged,
28873×
                    });
28883×
                }
28894240×
            }
28904243×
            return Ok(());
28919061×
        }
28929061×
        let mut status: Option<ChangeStatus> = None;
28939061×
        let wants_opaque = self.opaque_for(path, e);
28949061×
        let nocompress = self.attrs.lookup(path).nocompress;
28959061×
        let disk_text = self.stored_text(path, &e.content);
28969061×
        match &expected.content {
28970×
            FileContent::Dir => {}
2898
            FileContent::Text {
28998790×
                bytes,
29008790×
                materialized,
2901
            } => {
29028790×
                if materialized.is_conflicted() {
2903123×
                    if bytes == &*disk_text {
290480×
                        return Ok(());
290543×
                    }
290643×
                    let regions = self.base.conflict_regions(&node);
290743×
                    let plain: Vec<&[u8]> =
290896×
                        regions.plain.iter().map(|(_, l)| l.as_slice()).collect();
290943×
                    if has_own_conflict_markers(&e.content, bytes, &plain) {
29105×
                        self.statuses.push(PathStatus {
29115×
                            path: path.to_string(),
29125×
                            status: ChangeStatus::ConflictEdited,
29135×
                        });
29145×
                        return Ok(());
291538×
                    }
2916
                    // Resolution (spec §9.6): diff against the unconflicted lines
2917
                    // with each region as a gap, then retire every region atom.
2918
                    // Whatever the author kept from a region is re-inserted as
2919
                    // new atoms, which leaves the graph totally ordered.
292038×
                    let mut edits = text_edits(node, &regions.plain, &disk_text);
292138×
                    if !regions.region_atoms.is_empty() {
292238×
                        edits.insert(
292338×
                            0,
292438×
                            Edit::Delete {
292538×
                                node,
292638×
                                atoms: ranges(&regions.region_atoms),
292738×
                            },
292838×
                        );
292938×
                    }
293038×
                    self.edits.extend(edits);
293138×
                    self.contributors.extend(regions.contributors);
293238×
                    self.resolves = true;
293338×
                    if e.exec != expected.mode.exec {
29340×
                        if let Some(old) = mode_atom {
29350×
                            self.tree_ops.push(TreeOp::SetMode {
29360×
                                node,
29370×
                                old,
29380×
                                mode: Mode {
29390×
                                    exec: e.exec,
29400×
                                    opaque: false,
29410×
                                },
29420×
                            });
29430×
                        }
294438×
                    }
294538×
                    self.statuses.push(PathStatus {
294638×
                        path: path.to_string(),
294738×
                        status: ChangeStatus::Resolved,
294838×
                    });
294938×
                    return Ok(());
29508667×
                }
29518667×
                if wants_opaque {
2952
                    // Text → opaque (spec §7.5), by content or by attribute.
29532×
                    if let Some(old) = mode_atom {
29542×
                        self.tree_ops.push(TreeOp::SetMode {
29552×
                            node,
29562×
                            old,
29572×
                            mode: Mode {
29582×
                                exec: e.exec,
29592×
                                opaque: true,
29602×
                            },
29612×
                        });
29622×
                    }
29632×
                    let live: Vec<_> = repo_live_keys(self.base, &node);
29642×
                    if !live.is_empty() {
29652×
                        self.edits.push(Edit::Delete {
29662×
                            node,
29672×
                            atoms: ranges(&live),
29682×
                        });
29692×
                    }
29702×
                    let blob = self.blob_of(repo, path, e, nocompress)?;
29712×
                    self.edits.push(Edit::Replace {
29722×
                        node,
29732×
                        old: None,
29742×
                        new: Some(blob),
29752×
                    });
29762×
                    status = Some(ChangeStatus::Modified);
29778665×
                } else if bytes != &*disk_text {
2978866×
                    let mut laps = crate::timing::Laps::start();
2979
                    // The base's rendering holds its live atoms in order,
2980
                    // one per line (it is not conflicted here).
2981866×
                    let edits = match self.diffs.remove(path) {
298280×
                        Some(edits) => edits,
2983
                        None => {
2984786×
                            let keys = materialized.live_atoms();
2985786×
                            let lines = crate::diff::split_lines(bytes);
2986786×
                            if keys.len() == lines.len() {
2987786×
                                crate::diff::text_edits_of(node, &keys, &lines, &disk_text)
2988
                            } else {
29890×
                                text_edits(node, &self.base.live_lines(&node), &disk_text)
2990
                            }
2991
                        }
2992
                    };
2993866×
                    laps.lap("build: text diff");
2994866×
                    if !edits.is_empty() {
2995866×
                        self.edits.extend(edits);
2996866×
                        status = Some(ChangeStatus::Modified);
2997866×
                    }
29987799×
                }
29998667×
                let switched_to_opaque = wants_opaque;
30008667×
                if !switched_to_opaque && e.exec != expected.mode.exec {
30014×
                    if let Some(old) = mode_atom {
30024×
                        self.tree_ops.push(TreeOp::SetMode {
30034×
                            node,
30044×
                            old,
30054×
                            mode: Mode {
30064×
                                exec: e.exec,
30074×
                                opaque: false,
30084×
                            },
30094×
                        });
30104×
                        status.get_or_insert(ChangeStatus::ModeChanged);
30114×
                    }
30128663×
                }
3013
            }
3014271×
            FileContent::Opaque { blobs } => {
3015271×
                let new_ref = e.blob.unwrap_or_else(|| Repo::blob_ref(&e.content));
3016271×
                if e.kind == NodeKind::File && wants_opaque {
3017217×
                    // Unchanged or replaced, the file stays opaque: remember its blob.
3018217×
                    self.blobs.insert(path.to_string(), new_ref);
3019217×
                }
3020271×
                if blobs.len() > 1 && self.resolve.contains(path) && e.kind == expected.kind {
3021
                    // Settle the replace conflict (spec §9.3): replace every
3022
                    // live candidate with the chosen blob, depending on each
3023
                    // change that made one live, so all are superseded.
30245×
                    let chosen = self.blob_of(repo, path, e, nocompress)?;
302510×
                    for b in blobs {
302610×
                        self.edits.push(Edit::Replace {
302710×
                            node,
302810×
                            old: Some(*b),
302910×
                            new: Some(chosen),
303010×
                        });
303110×
                    }
30325×
                    self.contributors
30335×
                        .extend(self.base.blob_contributors(&node, blobs));
30345×
                    self.resolves = true;
30355×
                    self.statuses.push(PathStatus {
30365×
                        path: path.to_string(),
30375×
                        status: ChangeStatus::Resolved,
30385×
                    });
30395×
                    return Ok(());
3040266×
                }
3041266×
                if blobs.len() > 1 {
30429×
                    if !blobs.contains(&new_ref) {
30434×
                        self.statuses.push(PathStatus {
30444×
                            path: path.to_string(),
30454×
                            status: ChangeStatus::ConflictEdited,
30464×
                        });
30475×
                    }
30489×
                    return Ok(());
3049257×
                }
3050257×
                let current = blobs.first().copied();
3051257×
                if current != Some(new_ref) {
305244×
                    if e.kind == NodeKind::File && !wants_opaque {
3053
                        // Opaque → text (spec §7.5).
30542×
                        if let Some(old) = mode_atom {
30552×
                            self.tree_ops.push(TreeOp::SetMode {
30562×
                                node,
30572×
                                old,
30582×
                                mode: Mode {
30592×
                                    exec: e.exec,
30602×
                                    opaque: false,
30612×
                                },
30622×
                            });
30632×
                        }
30642×
                        self.edits.push(Edit::Replace {
30652×
                            node,
30662×
                            old: current,
30672×
                            new: None,
30682×
                        });
30692×
                        if !e.content.is_empty() {
30702×
                            self.edits.push(Edit::Insert {
30712×
                                node,
30722×
                                after: crate::objects::AtomRef::Start,
30732×
                                before: crate::objects::AtomRef::End,
30742×
                                lines: crate::lines::Lines::split(&e.content),
30752×
                            });
30762×
                        }
3077
                    } else {
307842×
                        let blob = self.blob_of(repo, path, e, nocompress)?;
307942×
                        self.edits.push(Edit::Replace {
308042×
                            node,
308142×
                            old: current,
308242×
                            new: Some(blob),
308342×
                        });
3084
                        // New contents and a new executable bit at once: the
3085
                        // bit was dropped (VS Code's inno_updater.exe,
3086
                        // 2018-02-28, lost +x for 49 commits; oxygen#87).
308742×
                        if e.kind == NodeKind::File && e.exec != expected.mode.exec {
30882×
                            if let Some(old) = mode_atom {
30892×
                                self.tree_ops.push(TreeOp::SetMode {
30902×
                                    node,
30912×
                                    old,
30922×
                                    mode: Mode {
30932×
                                        exec: e.exec,
30942×
                                        opaque: true,
30952×
                                    },
30962×
                                });
30972×
                            }
309840×
                        }
3099
                    }
310044×
                    status = Some(ChangeStatus::Modified);
3101213×
                } else if e.kind == NodeKind::File && e.exec != expected.mode.exec {
31020×
                    if let Some(old) = mode_atom {
31030×
                        self.tree_ops.push(TreeOp::SetMode {
31040×
                            node,
31050×
                            old,
31060×
                            mode: Mode {
31070×
                                exec: e.exec,
31080×
                                opaque: true,
31090×
                            },
31100×
                        });
31110×
                        status = Some(ChangeStatus::ModeChanged);
31120×
                    }
3113213×
                }
3114
            }
3115
        }
31168924×
        if let Some(s) = status {
3117916×
            self.statuses.push(PathStatus {
3118916×
                path: path.to_string(),
3119916×
                status: s,
3120916×
            });
31218008×
        }
31228924×
        Ok(())
312313305×
    }
3124
}
3125
31262×
fn repo_live_keys(base: &State, node: &NodeId) -> Vec<crate::graph::AtomKey> {
31272×
    base.live_lines(node).into_iter().map(|(k, _)| k).collect()
31282×
}
3129
3130
/// The changes a change's scope references (spec §8.1): introducers of every
3131
/// atom, placement, and mode it touches, and of every node it operates on.
31322457×
pub fn referenced_changes(change: &Change, base: &State) -> BTreeSet<ChangeHash> {
31332457×
    let mut out = BTreeSet::new();
31342457×
    let opref = |r: &OpRef, out: &mut BTreeSet<ChangeHash>| {
3135215×
        if !r.change.is_zero() {
3136215×
            out.insert(r.change);
3137215×
        }
3138215×
    };
31392457×
    let mut nodes: Vec<NodeId> = Vec::new();
31406788×
    for op in &change.tree_ops {
31416788×
        match op {
31426573×
            TreeOp::AddNode { parent, .. } => nodes.push(*parent),
3143166×
            TreeOp::RemoveNode { node, placement } => {
3144166×
                nodes.push(*node);
3145166×
                opref(placement, &mut out);
3146166×
            }
3147
            TreeOp::Move {
314837×
                node, old, parent, ..
314937×
            } => {
315037×
                nodes.push(*node);
315137×
                nodes.push(*parent);
315237×
                opref(old, &mut out);
315337×
            }
315412×
            TreeOp::SetMode { node, old, .. } => {
315512×
                nodes.push(*node);
315612×
                opref(old, &mut out);
315712×
            }
3158
        }
3159
    }
31608466×
    for e in &change.edits {
31618466×
        nodes.push(e.node());
3162186×
        match e {
31637670×
            Edit::Insert { after, before, .. } => {
316415340×
                for r in [after, before] {
316515340×
                    if let crate::objects::AtomRef::Atom { change, .. } = r {
31662310×
                        if !change.is_zero() {
31672307×
                            out.insert(*change);
31682307×
                        }
316913030×
                    }
3170
                }
3171
            }
3172610×
            Edit::Delete { atoms, .. } => {
3173
                // Deleting an atom also depends on whoever inserted the live
3174
                // atoms right after it: the author saw those insertions, and
3175
                // without the dependency spec §9.1 would call the deletion
3176
                // concurrent with them (a delete/insert conflict).
3177610×
                let graph = base.file(&e.node());
31781173×
                for r in atoms {
31791173×
                    if !r.change.is_zero() {
31801172×
                        out.insert(r.change);
31811172×
                    }
31821173×
                    if let Some(g) = graph {
31831200×
                        for i in r.from..r.to {
31841200×
                            out.extend(
31851200×
                                g.live_successor_changes(&(r.change, i))
31861200×
                                    .into_iter()
31871200×
                                    .filter(|c| !c.is_zero()),
3188
                            );
3189
                        }
31900×
                    }
3191
                }
3192
            }
3193
            // Replacing a blob depends on the change that made it current,
3194
            // as deleting a line depends on the line's introducer.
3195
            Edit::Replace {
319659×
                node,
319759×
                old: Some(old),
3198
                ..
3199
            } => {
320059×
                out.extend(
320159×
                    base.live_replaces(node)
320259×
                        .into_iter()
320376×
                        .filter(|(c, b)| b == old && !c.is_zero())
320459×
                        .map(|(c, _)| c),
3205
                );
3206
            }
3207127×
            Edit::Replace { .. } => {}
3208
        }
3209
    }
321015291×
    for n in nodes {
321115291×
        if let Some(h) = base.tree().introducer(&n) {
32122397×
            out.insert(h);
321312894×
        }
3214
    }
32152457×
    out
32162457×
}
3217
3218
/// Paths of the nodes a change adds on top of `base_snapshot`.
32191573×
pub fn added_node_paths(
32201573×
    change: &Change,
32211573×
    base_snapshot: &Snapshot,
32221573×
) -> HashMap<String, (NodeId, NodeKind)> {
32231573×
    let by_node = base_snapshot.tree.by_node();
32241573×
    let mut new_names: HashMap<NodeId, (NodeId, String, NodeKind)> = HashMap::new();
32251573×
    for op in &change.tree_ops {
3226
        if let TreeOp::AddNode {
322797×
            node,
322897×
            parent,
322997×
            name,
323097×
            kind,
3231
            ..
3232129×
        } = op
323397×
        {
323497×
            new_names.insert(*node, (*parent, name.clone(), *kind));
323597×
        }
3236
    }
32371573×
    let mut out = HashMap::new();
32381573×
    for (node, (_, _, kind)) in &new_names {
323997×
        if let Some(path) = path_of_node(node, &by_node, &new_names) {
324097×
            out.insert(path, (*node, *kind));
324197×
        }
3242
    }
32431573×
    out
32441573×
}
3245
3246
/// Whether `op` retires a node `base_snapshot` shows as one with another
3247
/// (spec §9.2): part of touching that node, never a removal the user made.
324837×
fn is_unified_retirement(op: &TreeOp, base_snapshot: &Snapshot) -> bool {
32498×
    matches!(op, TreeOp::RemoveNode { node, .. } if base_snapshot.tree.unified.contains_key(node))
325037×
}
3251
3252232×
fn path_of_node(
3253232×
    n: &NodeId,
3254232×
    by_node: &HashMap<NodeId, &crate::tree::TreeEntry>,
3255232×
    new_names: &HashMap<NodeId, (NodeId, String, NodeKind)>,
3256232×
) -> Option<String> {
3257232×
    if let Some(e) = by_node.get(n) {
325869×
        return Some(e.path.clone());
3259163×
    }
3260163×
    let mut parts = Vec::new();
3261163×
    let mut cur = *n;
3262
    loop {
3263322×
        if cur.is_root() {
3264146×
            break;
3265176×
        }
3266176×
        if let Some(e) = by_node.get(&cur) {
32670×
            if !e.path.is_empty() {
32680×
                parts.push(e.path.clone());
32690×
            }
32700×
            break;
3271176×
        }
3272176×
        let (parent, name, _) = new_names.get(&cur)?;
3273159×
        parts.push(name.clone());
3274159×
        cur = *parent;
3275
    }
3276146×
    parts.reverse();
3277146×
    Some(parts.join("/"))
3278232×
}
3279
3280
/// Render a change's operations with line content, using `base` for deleted lines.
328133×
pub fn render_change(change: &Change, base: &State, base_snapshot: &Snapshot) -> String {
328233×
    let by_node = base_snapshot.tree.by_node();
328333×
    let mut new_names: HashMap<NodeId, (NodeId, String, NodeKind)> = HashMap::new();
328433×
    for op in &change.tree_ops {
3285
        if let TreeOp::AddNode {
328616×
            node,
328716×
            parent,
328816×
            name,
328916×
            kind,
3290
            ..
329124×
        } = op
329216×
        {
329316×
            new_names.insert(*node, (*parent, name.clone(), *kind));
329416×
        }
3295
    }
329673×
    let path_of = |n: &NodeId| -> String {
329773×
        path_of_node(n, &by_node, &new_names).unwrap_or_else(|| format!("<node {}>", n.short(8)))
329873×
    };
3299
330033×
    let mut out = String::new();
330133×
    for op in change
330233×
        .tree_ops
330333×
        .iter()
330433×
        .filter(|o| !is_unified_retirement(o, base_snapshot))
3305
    {
330623×
        match op {
3307
            TreeOp::AddNode {
330816×
                node, kind, mode, ..
3309
            } => {
331016×
                out.push_str(&format!(
3311
                    "A {} ({:?}{}{})\n",
331216×
                    path_of(node),
3313
                    kind,
331416×
                    if mode.exec { ", exec" } else { "" },
331516×
                    if mode.opaque { ", opaque" } else { "" }
3316
                ));
3317
            }
33185×
            TreeOp::RemoveNode { node, .. } => out.push_str(&format!("D {}\n", path_of(node))),
3319
            TreeOp::Move {
33202×
                node, parent, name, ..
3321
            } => {
33222×
                let to = if parent.is_root() {
33230×
                    name.clone()
3324
                } else {
33252×
                    format!("{}/{name}", path_of(parent))
3326
                };
33272×
                out.push_str(&format!("R {} -> {to}\n", path_of(node)))
3328
            }
33290×
            TreeOp::SetMode { node, mode, .. } => {
33300×
                out.push_str(&format!(
33310×
                    "M {} mode: exec={} opaque={}\n",
33320×
                    path_of(node),
33330×
                    mode.exec,
33340×
                    mode.opaque
33350×
                ));
33360×
            }
3337
        }
3338
    }
3339
    // Every other file the change edits is modified: the summary names
3340
    // every path it touches, not only those with a tree operation.
334133×
    let with_op: HashSet<NodeId> = change.tree_ops.iter().map(|o| o.node()).collect();
334233×
    let mut listed: HashSet<NodeId> = HashSet::new();
334336×
    for e in &change.edits {
334436×
        let n = e.node();
334536×
        if !with_op.contains(&n) && listed.insert(n) {
334621×
            out.push_str(&format!("M {}\n", path_of(&n)));
334721×
        }
3348
    }
334933×
    let mut last_node: Option<NodeId> = None;
335036×
    for e in &change.edits {
335136×
        let n = e.node();
335236×
        if last_node != Some(n) {
335327×
            out.push_str(&format!("--- {}\n", path_of(&n)));
335427×
            last_node = Some(n);
335527×
        }
335636×
        match e {
335727×
            Edit::Insert { lines, .. } => {
335832×
                for l in lines.iter() {
335932×
                    out.push('+');
336032×
                    out.push_str(&String::from_utf8_lossy(l));
336132×
                    if !l.ends_with(b"\n") {
33620×
                        out.push('\n');
336332×
                    }
3364
                }
3365
            }
33668×
            Edit::Delete { atoms, .. } => {
33678×
                for r in atoms {
33688×
                    for i in r.from..r.to {
33698×
                        let content = base
33708×
                            .file(&n)
33718×
                            .and_then(|g| g.content(&(r.change, i)))
33728×
                            .unwrap_or(b"<unknown>\n");
33738×
                        out.push('-');
33748×
                        out.push_str(&String::from_utf8_lossy(content));
33758×
                        if !content.ends_with(b"\n") {
33760×
                            out.push('\n');
33778×
                        }
3378
                    }
3379
                }
3380
            }
33811×
            Edit::Replace { old, new, .. } => {
33821×
                out.push_str(&format!(
3383
                    "  opaque content {} -> {}\n",
33841×
                    old.map(|o| o.short(12)).unwrap_or_else(|| "none".into()),
33851×
                    new.map(|o| o.short(12)).unwrap_or_else(|| "none".into())
3386
                ));
3387
            }
3388
        }
3389
    }
339033×
    out
339133×
}
3392
3393
/// Pair removed files with added files of the same kind whose contents are
3394
/// at least `RENAME_THRESHOLD` percent alike, best matches first. Beyond
3395
/// `RENAME_LIMIT` candidate pairs only identical contents are paired.
3396
const RENAME_THRESHOLD: u32 = 50;
3397
const RENAME_LIMIT: usize = 10_000;
3398
3399
/// How a change is built beyond its entries: for a Git import, the seed
3400
/// its new nodes' identifiers derive from; and, when it is built from part
3401
/// of the tree, whether the new tree has anything under a directory.
3402
#[derive(Default)]
3403
struct Scope<'a> {
3404
    seed: Option<[u8; 32]>,
3405
    dir_needed: Option<&'a dyn Fn(&str) -> bool>,
3406
}
3407
34082403×
fn detect_renames(
34092403×
    base_snapshot: &Snapshot,
34102403×
    fs_entries: &BTreeMap<String, FsEntry>,
34112403×
    in_scope: impl Fn(&str) -> bool,
34122403×
) -> Vec<(String, String)> {
34132403×
    let removed: Vec<(&String, &crate::state::FileState)> = base_snapshot
34142403×
        .files
34152403×
        .iter()
341613877×
        .filter(|(p, f)| {
341713877×
            f.kind != NodeKind::Dir
341813409×
                && !fs_entries.contains_key(*p)
3419139×
                && in_scope(p)
3420129×
                && !f.is_conflicted()
342113877×
        })
34222403×
        .collect();
34232403×
    let added: Vec<(&String, &FsEntry)> = fs_entries
34242403×
        .iter()
342519498×
        .filter(|(p, e)| e.kind != NodeKind::Dir && !base_snapshot.files.contains_key(*p))
34262403×
        .collect();
34272403×
    if removed.is_empty() || added.is_empty() {
34282337×
        return vec![];
342966×
    }
343066×
    let exact_only = removed.len() * added.len() > RENAME_LIMIT;
343181×
    let old_content = |f: &crate::state::FileState| -> Option<Vec<u8>> {
343281×
        match &f.content {
343377×
            FileContent::Text { bytes, .. } => Some(bytes.clone()),
34344×
            _ => None,
3435
        }
343681×
    };
343766×
    let mut scored: Vec<(u32, usize, usize)> = Vec::new();
343881×
    for (ri, (_, f)) in removed.iter().enumerate() {
343981×
        let old = old_content(f);
344081×
        let old_blob = match &f.content {
34414×
            FileContent::Opaque { blobs } if blobs.len() == 1 => Some(blobs[0]),
344277×
            _ => None,
3443
        };
3444100×
        for (ai, (_, e)) in added.iter().enumerate() {
3445100×
            if e.kind != f.kind {
34460×
                continue;
3447100×
            }
3448100×
            let score = match (&old, old_blob) {
344990×
                (Some(o), _) => {
345090×
                    if exact_only {
34510×
                        if *o == *e.content {
34520×
                            100
3453
                        } else {
34540×
                            0
3455
                        }
3456
                    } else {
345790×
                        similarity(o, &e.content)
3458
                    }
3459
                }
346010×
                (None, Some(b)) if e.blob.unwrap_or_else(|| Repo::blob_ref(&e.content)) == b => 100,
34617×
                _ => 0,
3462
            };
3463100×
            if score >= RENAME_THRESHOLD {
346441×
                scored.push((score, ri, ai));
346559×
            }
3466
        }
3467
    }
346866×
    scored.sort_by(|a, b| {
34699×
        b.0.cmp(&a.0)
34709×
            .then(removed[a.1].0.cmp(removed[b.1].0))
34719×
            .then(added[a.2].0.cmp(added[b.2].0))
34729×
    });
347366×
    let mut used_r = vec![false; removed.len()];
347466×
    let mut used_a = vec![false; added.len()];
347566×
    let mut out = Vec::new();
347666×
    for (_, ri, ai) in scored {
347741×
        if used_r[ri] || used_a[ai] {
34786×
            continue;
347935×
        }
348035×
        used_r[ri] = true;
348135×
        used_a[ai] = true;
348235×
        out.push((removed[ri].0.clone(), added[ai].0.clone()));
3483
    }
348466×
    out
34852403×
}
3486
3487
/// Percentage of the larger file's bytes found in lines the two share
3488
/// (multiset intersection of lines), like Git's similarity index.
348994×
pub fn similarity(a: &[u8], b: &[u8]) -> u32 {
349094×
    if a == b {
349125×
        return 100;
349269×
    }
349369×
    if a.is_empty() || b.is_empty() {
34947×
        return 0;
349562×
    }
349662×
    let mut counts: HashMap<&[u8], usize> = HashMap::new();
3497124×
    for l in split_lines(a) {
3498124×
        *counts.entry(l).or_default() += 1;
3499124×
    }
350062×
    let mut shared = 0usize;
3501115×
    for l in split_lines(b) {
3502115×
        if let Some(n) = counts.get_mut(l) {
350345×
            if *n > 0 {
350445×
                *n -= 1;
350545×
                shared += l.len();
350645×
            }
350770×
        }
3508
    }
350962×
    (shared * 100 / a.len().max(b.len())) as u32
351094×
}
3511
3512
#[cfg(test)]
3513
mod join_tests {
3514
    use super::*;
3515
3516
    #[test]
35171×
    fn missing_from_finds_what_the_other_lacks() {
35181×
        let a: BTreeMap<String, u8> = [("a", 1), ("b", 2), ("c/d", 3), ("e", 4)]
35191×
            .into_iter()
35204×
            .map(|(k, v)| (k.to_string(), v))
35211×
            .collect();
35221×
        let b: BTreeMap<String, ()> = [("0", ()), ("b", ()), ("c", ()), ("e", ())]
35231×
            .into_iter()
35244×
            .map(|(k, v)| (k.to_string(), v))
35251×
            .collect();
35261×
        let got: Vec<&str> = missing_from(&a, &b)
35271×
            .iter()
35282×
            .map(|(k, _)| k.as_str())
35291×
            .collect();
35301×
        assert_eq!(got, vec!["a", "c/d"]);
35311×
    }
3532
3533
    #[test]
35341×
    fn join_pairs_every_key_in_order() {
35351×
        let a: BTreeMap<String, u8> = [("a", 1), ("b/c", 2), ("d", 3)]
35361×
            .into_iter()
35373×
            .map(|(k, v)| (k.to_string(), v))
35381×
            .collect();
35391×
        let b: BTreeMap<String, char> = [("b", 'x'), ("b/c", 'y'), ("e", 'z')]
35401×
            .into_iter()
35413×
            .map(|(k, v)| (k.to_string(), v))
35421×
            .collect();
35431×
        let got: Vec<(String, Option<u8>, Option<char>)> = join(&a, &b)
35445×
            .map(|(k, x, y)| (k.clone(), x.copied(), y.copied()))
35451×
            .collect();
35461×
        let want = vec![
35471×
            ("a".to_string(), Some(1), None),
35481×
            ("b".to_string(), None, Some('x')),
35491×
            ("b/c".to_string(), Some(2), Some('y')),
35501×
            ("d".to_string(), Some(3), None),
35511×
            ("e".to_string(), None, Some('z')),
3552
        ];
35531×
        assert_eq!(got, want);
35541×
    }
3555
}