OXYGENHUB
# 36e51aa806c6 oxygen / crates / oxy-core / src / repo / snapshot.rs
94.3 KiB · Rust · last changed Status: maps built in path order, fast maps for node lookups (refs #41) 1 month ago source blame history raw
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).
21
pub fn has_conflict_markers(content: &[u8]) -> bool {
22
    split_lines(content).iter().any(|l| {
23
        l.starts_with(b"<<<<<<< oxy conflict")
24
            || l.starts_with(b"======= oxy conflict")
25
            || l.starts_with(b">>>>>>> oxy conflict")
26
    })
27
}
28
29
#[derive(Clone, Debug, PartialEq, Eq)]
30
pub struct PathStatus {
31
    pub path: String,
32
    pub status: ChangeStatus,
33
}
34
35
/// Operations of a change built from the working directory against a base.
36
pub(crate) struct BuiltChange {
37
    pub tree_ops: Vec<TreeOp>,
38
    pub edits: Vec<Edit>,
39
    pub contributors: Vec<ChangeHash>,
40
    pub resolves: bool,
41
    pub statuses: Vec<PathStatus>,
42
    /// The stored blob of every opaque path, for the manifest's stat cache.
43
    pub blobs: HashMap<String, ObjectRef>,
44
}
45
46
/// Result of snapshotting the working copy.
47
pub struct SnapshotResult {
48
    pub wc_hash: ChangeHash,
49
    pub wc: Change,
50
    /// The base state (closure of the working-copy change's dependencies).
51
    pub base: State,
52
    pub base_snapshot: Snapshot,
53
    pub statuses: Vec<PathStatus>,
54
    /// Whether the snapshot rewrote the working-copy change.
55
    pub changed: bool,
56
    /// Whether the working copy resolves conflicts of its base (spec §9.6).
57
    pub resolves: bool,
58
    /// Changes that contributed to the conflicts being resolved.
59
    pub contributors: Vec<ChangeHash>,
60
}
61
62
pub fn is_binary(content: &[u8]) -> bool {
63
    content[..content.len().min(BINARY_SNIFF)].contains(&0)
64
}
65
66
impl Repo {
67
    /// Diff the files on disk against `base` and build the operations of a
68
    /// change from `base` to the working directory. `reuse` maps paths to the
69
    /// NodeIds an earlier version of the same change assigned to new paths.
70
    pub(crate) fn build_against(
71
        &self,
72
        base: &State,
73
        base_snapshot: &Snapshot,
74
        reuse: HashMap<String, (NodeId, NodeKind)>,
75
    ) -> Result<BuiltChange> {
76
        let mut fs_entries =
77
            self.walk_working_copy_with(None, &Self::tracked_kinds(base_snapshot), None)?;
78
        self.platform_normalize(&mut fs_entries, base_snapshot);
79
        self.build_from_entries(base, base_snapshot, reuse, &fs_entries)
80
    }
81
82
    /// Read the working copy as the platform left it (spec §7.7): without
83
    /// executable bits a file keeps the bit it has in the base, and without
84
    /// symbolic links a plain file where the base has a symlink is that
85
    /// symlink, written out as its target, not a new file.
86
    fn platform_normalize(&self, entries: &mut BTreeMap<String, FsEntry>, base: &Snapshot) {
87
        let p = self.platform;
88
        if p.exec_bits && p.symlinks {
89
            return;
90
        }
91
        for (path, e) in entries.iter_mut() {
92
            let Some(f) = base.files.get(path) else {
93
                continue;
94
            };
95
            if !p.symlinks && f.kind == NodeKind::Symlink && e.kind == NodeKind::File {
96
                e.kind = NodeKind::Symlink;
97
                e.exec = false;
98
            }
99
            if !p.exec_bits && f.kind == NodeKind::File && e.kind == NodeKind::File {
100
                e.exec = f.mode.exec;
101
            }
102
        }
103
    }
104
105
    /// Like `build_against`, for files given in memory (imports).
106
    pub(crate) fn build_from_entries(
107
        &self,
108
        base: &State,
109
        base_snapshot: &Snapshot,
110
        reuse: HashMap<String, (NodeId, NodeKind)>,
111
        fs_entries: &BTreeMap<String, FsEntry>,
112
    ) -> Result<BuiltChange> {
113
        self.build_from_entries_resolving(base, base_snapshot, reuse, fs_entries, &HashSet::new())
114
    }
115
116
    /// Like `build_from_entries`, settling the replace conflicts of the
117
    /// opaque files in `resolve` to their content (spec §9.3, §9.6): a
118
    /// caller that knows the user chose it, such as the hub's resolver. A
119
    /// snapshot never settles one on its own, since a checkout writes one
120
    /// candidate at the path.
121
    pub(crate) fn build_from_entries_resolving(
122
        &self,
123
        base: &State,
124
        base_snapshot: &Snapshot,
125
        reuse: HashMap<String, (NodeId, NodeKind)>,
126
        fs_entries: &BTreeMap<String, FsEntry>,
127
        resolve: &HashSet<String>,
128
    ) -> Result<BuiltChange> {
129
        self.build_from_entries_with(base, base_snapshot, reuse, fs_entries, resolve, None)
130
    }
131
132
    /// `build_from_entries` whose new nodes take identifiers derived from
133
    /// `seed` and their paths instead of random ones, so the same input
134
    /// always builds the same change (a Git import, spec §23).
135
    ///
136
    /// With `dir_needed`, the snapshot and entries hold only the paths the
137
    /// import touches (and the directories a removal may leave empty); a
138
    /// directory stays while `dir_needed` says the new tree has something
139
    /// under it.
140
    pub(crate) fn build_from_entries_seeded(
141
        &self,
142
        base: &State,
143
        base_snapshot: &Snapshot,
144
        fs_entries: &BTreeMap<String, FsEntry>,
145
        seed: [u8; 32],
146
        dir_needed: Option<&dyn Fn(&str) -> bool>,
147
    ) -> Result<BuiltChange> {
148
        self.build_from_entries_with(
149
            base,
150
            base_snapshot,
151
            HashMap::new(),
152
            fs_entries,
153
            &HashSet::new(),
154
            Some(Import { seed, dir_needed }),
155
        )
156
    }
157
158
    fn build_from_entries_with(
159
        &self,
160
        base: &State,
161
        base_snapshot: &Snapshot,
162
        reuse: HashMap<String, (NodeId, NodeKind)>,
163
        fs_entries: &BTreeMap<String, FsEntry>,
164
        resolve: &HashSet<String>,
165
        import: Option<Import>,
166
    ) -> Result<BuiltChange> {
167
        let seed = import.as_ref().map(|i| i.seed);
168
        let dir_needed = import.and_then(|i| i.dir_needed);
169
        let mut laps = crate::timing::Laps::start();
170
        // Attributes come from the files being committed, so a new
171
        // `.oxyattributes` applies to the same change that adds it.
172
        let attrs = crate::attributes::Attributes::from_files(
173
            fs_entries
174
                .iter()
175
                .filter(|(p, _)| p.as_str() == ".oxyattributes" || p.ends_with("/.oxyattributes"))
176
                .map(|(p, e)| (p.as_str(), e.content.as_slice())),
177
        );
178
        let mut b = ChangeBuilder::new(base, base_snapshot, reuse).with_attributes(attrs);
179
        b.resolve = resolve.clone();
180
        b.node_seed = seed;
181
        laps.lap("build: builder");
182
        // Rename detection (spec §7.1, §23): a removed file and an added file
183
        // of the same kind whose contents are at least half alike become one
184
        // move of the same node, so identity survives across the rename.
185
        let renames = detect_renames(base_snapshot, fs_entries, |p| self.in_scope(p));
186
        let renamed_from: HashMap<&str, &str> = renames
187
            .iter()
188
            .map(|(old, new)| (new.as_str(), old.as_str()))
189
            .collect();
190
        let renamed_to: HashMap<&str, &str> = renames
191
            .iter()
192
            .map(|(old, new)| (old.as_str(), new.as_str()))
193
            .collect();
194
        laps.lap("build: renames");
195
        for (path, fs_entry) in fs_entries {
196
            match base_snapshot.files.get(path) {
197
                None => match renamed_from.get(path.as_str()) {
198
                    Some(old) => {
199
                        b.move_path(self, old, path, fs_entry, &base_snapshot.files[*old])?
200
                    }
201
                    None => b.add_path(self, path, fs_entry)?,
202
                },
203
                Some(expected) => b.update_path(self, path, fs_entry, expected)?,
204
            }
205
        }
206
        laps.lap("build: paths");
207
        // A directory stays while anything under it exists or is out of
208
        // scope: the directories above each such path, gathered once.
209
        let mut needed_dirs: HashSet<&str> = HashSet::new();
210
        fn parents_of<'a>(p: &'a str, set: &mut HashSet<&'a str>) {
211
            let mut end = p.len();
212
            while let Some(i) = p[..end].rfind('/') {
213
                if !set.insert(&p[..i]) {
214
                    break;
215
                }
216
                end = i;
217
            }
218
        }
219
        for p in fs_entries.keys() {
220
            parents_of(p, &mut needed_dirs);
221
        }
222
        for p in base_snapshot.files.keys() {
223
            if !self.in_scope(p) {
224
                parents_of(p, &mut needed_dirs);
225
            }
226
        }
227
        for (path, expected) in &base_snapshot.files {
228
            if fs_entries.contains_key(path)
229
                || !self.in_scope(path)
230
                || renamed_to.contains_key(path.as_str())
231
            {
232
                continue;
233
            }
234
            let still_needed = expected.kind == NodeKind::Dir
235
                && match dir_needed {
236
                    Some(f) => f(path),
237
                    None => needed_dirs.contains(path.as_str()),
238
                };
239
            if !still_needed {
240
                b.remove_path(path, expected);
241
            }
242
        }
243
        laps.lap("build: removals");
244
        if seed.is_some() {
245
            b.retire_stray_placements();
246
        }
247
        laps.lap("build: stray placements");
248
        let mut statuses = b.statuses;
249
        statuses.sort_by(|a, b| a.path.cmp(&b.path));
250
        Ok(BuiltChange {
251
            tree_ops: b.tree_ops,
252
            edits: b.edits,
253
            contributors: b.contributors.into_iter().collect(),
254
            resolves: b.resolves,
255
            statuses,
256
            blobs: b.blobs,
257
        })
258
    }
259
260
    /// Store a change and, when `core.sign = change` and we are its author,
261
    /// sign it. A rewritten change by another author is stored unsigned: only
262
    /// its author (or a delegate) can vouch for it.
263
    pub(crate) fn store_signed(&self, change: &Change) -> Result<ChangeHash> {
264
        let ours = change.author == self.author();
265
        if self.config.sign_changes && ours && self.secret_key()?.is_none() {
266
            return fail("core.sign is \"change\" but no secret key is available for author.key");
267
        }
268
        let hash = self.store.put_change(change)?;
269
        if self.config.sign_changes && ours {
270
            self.sign_change(&hash)?;
271
        }
272
        Ok(hash)
273
    }
274
275
    /// Snapshot the working copy into the working-copy change (spec §12.3).
276
    /// The result carries the full base state and its whole rendering.
277
    pub fn snapshot(&self, command: &str) -> Result<SnapshotResult> {
278
        self.snapshot_as(command, false)
279
    }
280
281
    /// Snapshot the working copy as [`Repo::snapshot`] does, for commands
282
    /// that need its statuses, conflicts and base history, and the graphs
283
    /// of the files it changes: status, log, show, commit, diff, hunks and
284
    /// discard. Text files known unchanged since the last manifest are
285
    /// neither read nor rendered: the result's `base` is a history-only
286
    /// state without their graphs, and its `base_snapshot` lists them in
287
    /// `unrendered` with empty bytes. They are never conflicted, and no
288
    /// change the working copy makes touches them.
289
    pub fn snapshot_status(&self, command: &str) -> Result<SnapshotResult> {
290
        self.snapshot_as(command, true)
291
    }
292
293
    fn snapshot_as(&self, command: &str, partial: bool) -> Result<SnapshotResult> {
294
        let _lock = self.lock_snapshot()?;
295
        let batch = self.store.begin_batch()?;
296
        let result = self.snapshot_locked(command, partial);
297
        batch.finish()?;
298
        result
299
    }
300
301
    fn snapshot_locked(&self, command: &str, partial: bool) -> Result<SnapshotResult> {
302
        let _all = crate::timing::phase("snapshot");
303
        let (op_ref, op) = self.head_op()?;
304
        let (old_hash, old_wc) = self.working_copy()?;
305
        // The base's history first: its graph keys say which files the
306
        // manifest already knows equal to it.
307
        let mut base = {
308
            let _t = crate::timing::phase("snapshot: load base history");
309
            self.load_state_indexed(&old_wc.deps)?
310
        };
311
        let view = {
312
            let _t = crate::timing::phase("snapshot: tree view");
313
            base.tree().view()
314
        };
315
        let keys_phase = crate::timing::phase("snapshot: graph keys");
316
        let keys: HashMap<String, String> = view
317
            .entries
318
            .iter()
319
            .filter(|(_, e)| e.kind == NodeKind::File && !e.mode.opaque)
320
            .filter_map(|(p, e)| {
321
                let k = base.graph_key(&e.node)?;
322
                Some((p.clone(), crate::hash::ObjectRef(k).to_hex()))
323
            })
324
            .collect();
325
        drop(keys_phase);
326
        let manifest = {
327
            let _t = crate::timing::phase("snapshot: read manifest");
328
            self.read_manifest()?.map(|(_, _, m)| m)
329
        };
330
        let tracked: BTreeMap<String, (NodeKind, Option<ObjectRef>)> = {
331
            let _t = crate::timing::phase("snapshot: tracked paths");
332
            // In the view's path order, so the map is built without searching.
333
            view.entries
334
                .iter()
335
                .filter(|(_, e)| e.kind != NodeKind::Dir)
336
                .map(|(p, e)| {
337
                    let blob = if e.kind != NodeKind::File || e.mode.opaque {
338
                        base.live_blobs(&e.node).first().copied()
339
                    } else {
340
                        None
341
                    };
342
                    (p.clone(), (e.kind, blob))
343
                })
344
                .collect()
345
        };
346
        let mut fs_entries = {
347
            let _t = crate::timing::phase("snapshot: read working copy");
348
            self.walk_working_copy_with(manifest.as_deref(), &tracked, Some(&keys))?
349
        };
350
        let base_snapshot = {
351
            let _t = crate::timing::phase("snapshot: load and render base");
352
            if partial {
353
                let skip: HashSet<NodeId> = fs_entries
354
                    .iter()
355
                    .filter(|(_, e)| e.unchanged)
356
                    .filter_map(|(p, _)| view.entries.get(p).map(|e| e.node))
357
                    .collect();
358
                let need: Vec<NodeId> = view
359
                    .entries
360
                    .values()
361
                    .filter(|e| e.kind == NodeKind::File && !skip.contains(&e.node))
362
                    .map(|e| e.node)
363
                    .collect();
364
                {
365
                    let _t = crate::timing::phase("snapshot:   of which building graphs");
366
                    self.load_graphs_of(&mut base, &need)?;
367
                }
368
                let _t = crate::timing::phase("snapshot:   of which rendering");
369
                base.materialize_except(&skip)
370
            } else {
371
                self.load_all_graphs(&mut base)?;
372
                base.materialize()
373
            }
374
        };
375
376
        // Reuse the NodeIds the previous working-copy version assigned to new
377
        // paths, so an unchanged working copy hashes identically (spec §12.3).
378
        let reuse = added_node_paths(&old_wc, &base_snapshot);
379
        self.platform_normalize(&mut fs_entries, &base_snapshot);
380
        let built = {
381
            let _t = crate::timing::phase("snapshot: diff against base");
382
            self.build_from_entries(&base, &base_snapshot, reuse, &fs_entries)?
383
        };
384
        // Text files found equal to an unconflicted base rendering keep its
385
        // graph key, so the next snapshot need not read or render them.
386
        {
387
            let changed: HashSet<&str> = built.statuses.iter().map(|s| s.path.as_str()).collect();
388
            for (p, e) in fs_entries.iter_mut() {
389
                if e.unchanged || e.kind != NodeKind::File || changed.contains(p.as_str()) {
390
                    continue;
391
                }
392
                e.graph_key = match base_snapshot.files.get(p).map(|f| &f.content) {
393
                    Some(FileContent::Text {
394
                        bytes,
395
                        materialized,
396
                    }) if !materialized.is_conflicted() && *bytes == *e.content => {
397
                        keys.get(p).cloned()
398
                    }
399
                    _ => None,
400
                };
401
            }
402
        }
403
404
        let mut wc = Change {
405
            version: crate::objects::CHANGE_VERSION,
406
            change_id: old_wc.change_id,
407
            deps: vec![],
408
            author: self.author(),
409
            hlc: old_wc.hlc,
410
            message: old_wc.message.clone(),
411
            tree_ops: built.tree_ops,
412
            edits: built.edits,
413
            kind: ChangeKind::WorkingCopy,
414
        };
415
        let base_heads = base.maximal(&old_wc.deps);
416
        let mut deps: BTreeSet<ChangeHash> = base_heads.into_iter().collect();
417
        deps.extend(referenced_changes(&wc, &base));
418
        deps.extend(built.contributors.iter().copied());
419
        wc.deps = deps.into_iter().collect();
420
        wc.normalize();
421
        let resolves = built.resolves;
422
        let contributors = built.contributors;
423
        let statuses = built.statuses;
424
        // Empty snapshot: hash the candidate before storing; only record an op on change.
425
        let record = crate::timing::phase("snapshot: hash and record");
426
        // Encoded once, its texts stored a batch at a time as they are
427
        // made (a stored blob is not stored again); the change itself only
428
        // when it changed.
429
        let encoded = wc.encode_streaming(|batch| self.store.put_texts(&batch))?;
430
        let new_hash = crate::hash::hash_object(crate::hash::ObjectType::Change, &encoded);
431
        let changed = new_hash != old_hash;
432
        if changed {
433
            self.store.put(crate::hash::ObjectType::Change, &encoded)?;
434
            let mut view = op.view.clone();
435
            view.workspaces.insert(self.workspace, new_hash);
436
            self.record_op(&[op_ref], &format!("{command}{SNAPSHOT_SUFFIX}"), view)?;
437
        }
438
        drop(record);
439
        // The prompt compares against this without recording anything.
440
        let _t = crate::timing::phase("snapshot: write manifest");
441
        self.write_manifest_entries(
442
            base_snapshot.is_conflicted(),
443
            !wc.tree_ops.is_empty() || !wc.edits.is_empty(),
444
            &fs_entries,
445
            &built.blobs,
446
        )?;
447
        Ok(SnapshotResult {
448
            wc_hash: new_hash,
449
            wc,
450
            base,
451
            base_snapshot,
452
            statuses,
453
            changed,
454
            resolves,
455
            contributors,
456
        })
457
    }
458
459
    /// `oxy status --json` (spec §9.5): the changed paths and every conflict
460
    /// of the working copy's base with its kind, path, and contributing
461
    /// ChangeIds.
462
    pub fn status_json(&self, snap: &SnapshotResult) -> Result<String> {
463
        let heads = self.bookmark_heads()?;
464
        let base_snapshot = &snap.base_snapshot;
465
        let by_node = base_snapshot.tree.by_node();
466
        let path_of = |n: &NodeId| by_node.get(n).map(|e| e.path.clone());
467
        let id_of = |h: &ChangeHash| {
468
            snap.base
469
                .get(h)
470
                .map(|m| m.change_id.to_hex())
471
                .unwrap_or_else(|| h.to_hex())
472
        };
473
        let paths = json_array(snap.statuses.iter().map(|s| {
474
            format!(
475
                "{{\"path\":{},\"status\":{}}}",
476
                json_str(&s.path),
477
                json_str(&format!("{:?}", s.status))
478
            )
479
        }));
480
        let mut conflicts: Vec<String> = Vec::new();
481
        for (p, f) in &base_snapshot.files {
482
            if !f.is_conflicted() {
483
                continue;
484
            }
485
            let (kind, changes) = match &f.content {
486
                FileContent::Text { .. } => {
487
                    ("text", snap.base.conflict_regions(&f.node).contributors)
488
                }
489
                FileContent::Opaque { blobs } => {
490
                    ("replace", snap.base.blob_contributors(&f.node, blobs))
491
                }
492
                FileContent::Dir => continue,
493
            };
494
            let resolved = match snap
495
                .statuses
496
                .iter()
497
                .find(|s| s.path == *p)
498
                .map(|s| s.status)
499
            {
500
                Some(ChangeStatus::Resolved) => "true",
501
                Some(ChangeStatus::ConflictEdited) => "\"markers\"",
502
                _ => "false",
503
            };
504
            conflicts.push(format!(
505
                "{{\"kind\":{},\"path\":{},\"node\":{},\"changes\":{},\"resolved\":{resolved}}}",
506
                json_str(kind),
507
                json_str(p),
508
                json_str(&f.node.to_hex()),
509
                json_array(changes.iter().map(|h| json_str(&id_of(h))))
510
            ));
511
        }
512
        for c in &base_snapshot.tree.conflicts {
513
            let (kind, nodes): (&str, Vec<NodeId>) = match c {
514
                crate::tree::TreeConflict::Name { nodes, .. } => ("name", nodes.clone()),
515
                crate::tree::TreeConflict::MultiPlacement { node, .. } => {
516
                    ("multi-placement", vec![*node])
517
                }
518
                crate::tree::TreeConflict::Orphan { node, .. } => ("orphan", vec![*node]),
519
                crate::tree::TreeConflict::Cycle { node } => ("cycle", vec![*node]),
520
                crate::tree::TreeConflict::Mode { node, .. } => ("mode", vec![*node]),
521
            };
522
            let detail = match c {
523
                crate::tree::TreeConflict::Name { name, parent, .. } => {
524
                    let dir = if *parent == NodeId::ROOT {
525
                        String::new()
526
                    } else {
527
                        path_of(parent).unwrap_or_default()
528
                    };
529
                    format!(
530
                        ",\"path\":{}",
531
                        json_str(&if dir.is_empty() {
532
                            name.clone()
533
                        } else {
534
                            format!("{dir}/{name}")
535
                        })
536
                    )
537
                }
538
                _ => nodes
539
                    .first()
540
                    .and_then(path_of)
541
                    .map(|p| format!(",\"path\":{}", json_str(&p)))
542
                    .unwrap_or_default(),
543
            };
544
            conflicts.push(format!(
545
                "{{\"kind\":{},\"nodes\":{}{detail}}}",
546
                json_str(kind),
547
                json_array(nodes.iter().map(|n| json_str(&n.to_hex())))
548
            ));
549
        }
550
        Ok(format!(
551
            "{{\"bookmark\":{},\"working_copy\":{},\"heads\":{},\"clean\":{},\"conflicted\":{},\"paths\":{paths},\"conflicts\":{}}}",
552
            json_str(&self.config.bookmark),
553
            json_str(&snap.wc.change_id.to_hex()),
554
            heads.len(),
555
            snap.statuses.is_empty(),
556
            base_snapshot.is_conflicted(),
557
            json_array(conflicts)
558
        ))
559
    }
560
561
    /// Turn the working-copy change into a normal change on the bookmark (spec §12.3).
562
    pub fn commit(&self, message: &str, extra_deps: &[ChangeHash]) -> Result<ChangeHash> {
563
        self.commit_selection(message, extra_deps, &Selection::All)
564
    }
565
566
    /// The hunks of the working copy, for `oxy commit --interactive`: each
567
    /// tree operation and each edit, in the order `select_hunks` numbers them.
568
    pub fn hunks(&self) -> Result<(SnapshotResult, Vec<Hunk>)> {
569
        let snap = self.snapshot_status("oxy commit")?;
570
        let hunks = render_hunks(&snap.wc, &snap.base, &snap.base_snapshot);
571
        Ok((snap, hunks))
572
    }
573
574
    /// Commit part of the working copy (spec §12.3). What is not selected
575
    /// stays on disk as uncommitted work: the next snapshot rebuilds it
576
    /// against the new base, so the working copy always describes the
577
    /// directory.
578
    /// The graph key of each text file of the state at `heads`, by path,
579
    /// from a history-only load that builds no graph. Files with an `eol`
580
    /// attribute are left out: their bytes on disk are not the rendering.
581
    fn committed_graph_keys(&self, heads: &[ChangeHash]) -> Result<HashMap<String, String>> {
582
        let _t = crate::timing::phase("commit: graph keys");
583
        let st = self.load_state_history(heads)?;
584
        let attrs = self.disk_attributes();
585
        Ok(st
586
            .tree()
587
            .view()
588
            .entries
589
            .iter()
590
            .filter(|(p, e)| {
591
                e.kind == NodeKind::File && !e.mode.opaque && attrs.lookup(p).eol.is_none()
592
            })
593
            .filter_map(|(p, e)| {
594
                let k = st.graph_key(&e.node)?;
595
                Some((p.clone(), crate::hash::ObjectRef(k).to_hex()))
596
            })
597
            .collect())
598
    }
599
600
    pub fn commit_selection(
601
        &self,
602
        message: &str,
603
        extra_deps: &[ChangeHash],
604
        selection: &Selection,
605
    ) -> Result<ChangeHash> {
606
        let _wc = self.lock_working_copy()?;
607
        let mut snap = self.snapshot_status("oxy commit")?;
608
        if snap.wc.tree_ops.is_empty() && snap.wc.edits.is_empty() {
609
            return fail("nothing to commit: the working copy matches its base");
610
        }
611
        if let Some(s) = snap
612
            .statuses
613
            .iter()
614
            .find(|s| s.status == ChangeStatus::ConflictEdited)
615
        {
616
            return fail(format!("{} still contains conflict markers", s.path));
617
        }
618
        if message.trim().is_empty() {
619
            return fail("a commit message is required");
620
        }
621
        // What the whole working copy references, before a whole commit
622
        // takes its operations over (they are moved, not copied: for a
623
        // large tree they are most of the memory).
624
        let wc_refs = referenced_changes(&snap.wc, &snap.base);
625
        let (tree_ops, edits, partial) = match selection {
626
            Selection::All => (
627
                std::mem::take(&mut snap.wc.tree_ops),
628
                std::mem::take(&mut snap.wc.edits),
629
                false,
630
            ),
631
            Selection::Paths(paths) => {
632
                let (o, e) = select_paths(&snap.wc, &snap.base_snapshot, paths);
633
                let partial = o.len() != snap.wc.tree_ops.len() || e.len() != snap.wc.edits.len();
634
                (o, e, partial)
635
            }
636
            Selection::Hunks(indices) => {
637
                let (o, e) = select_hunks(&snap.wc, indices);
638
                let partial = o.len() != snap.wc.tree_ops.len() || e.len() != snap.wc.edits.len();
639
                (o, e, partial)
640
            }
641
        };
642
        if tree_ops.is_empty() && edits.is_empty() {
643
            return fail("nothing selected to commit");
644
        }
645
        if partial && snap.resolves {
646
            return fail("a conflict resolution must be committed whole");
647
        }
648
        // pre-commit hook: may veto.
649
        self.run_hook(
650
            "pre-commit",
651
            &format!(
652
                "{{\"event\":\"pre-commit\",\"message\":{},\"paths\":{}}}",
653
                json_str(message),
654
                json_array(snap.statuses.iter().map(|s| format!(
655
                    "{{\"path\":{},\"status\":{}}}",
656
                    json_str(&s.path),
657
                    json_str(&format!("{:?}", s.status))
658
                )))
659
            ),
660
        )?;
661
        let (op_ref, op) = self.head_op()?;
662
        let mut deps: BTreeSet<ChangeHash> = wc_refs;
663
        // semantic-deps hook: may add explicit dependencies (spec §8.1).
664
        if self.config.semantic_deps {
665
            let touched: Vec<String> = snap.statuses.iter().map(|s| s.path.clone()).collect();
666
            let by_node = snap.base_snapshot.tree.by_node();
667
            let mut candidates: Vec<(ChangeId, ChangeHash, Vec<String>)> = Vec::new();
668
            let mut seen: BTreeSet<ChangeHash> = BTreeSet::new();
669
            for h in deps.iter().chain(snap.base.maximal(&snap.wc.deps).iter()) {
670
                if !seen.insert(*h) {
671
                    continue;
672
                }
673
                let c = self.store.get_change(h)?;
674
                let mut paths: BTreeSet<String> = BTreeSet::new();
675
                for n in c
676
                    .tree_ops
677
                    .iter()
678
                    .map(|o| o.node())
679
                    .chain(c.edits.iter().map(|e| e.node()))
680
                {
681
                    if let Some(e) = by_node.get(&n) {
682
                        paths.insert(e.path.clone());
683
                    }
684
                }
685
                candidates.push((c.change_id, *h, paths.into_iter().collect()));
686
            }
687
            for d in self.semantic_deps(&snap.wc.change_id, &touched, &candidates)? {
688
                if snap.base.contains(&d) {
689
                    deps.insert(d);
690
                }
691
            }
692
        }
693
        // A resolution depends on every change that contributed to the
694
        // conflict (spec §8.1). Tree and opaque conflicts are resolved through
695
        // ordinary operations whose references already cover the contributors.
696
        deps.extend(snap.contributors.iter().copied());
697
        for d in extra_deps {
698
            if !snap.base.contains(d) {
699
                return fail(format!(
700
                    "--depends-on {d}: not in the working copy's base state"
701
                ));
702
            }
703
            deps.insert(*d);
704
        }
705
        let mut change = Change {
706
            version: crate::objects::CHANGE_VERSION,
707
            change_id: if partial {
708
                ChangeId::random()
709
            } else {
710
                snap.wc.change_id
711
            },
712
            deps: vec![],
713
            author: self.author(),
714
            hlc: Hlc::now(),
715
            message: message.trim_end().to_string(),
716
            tree_ops,
717
            edits,
718
            kind: if snap.resolves {
719
                ChangeKind::Resolution
720
            } else {
721
                ChangeKind::Normal
722
            },
723
        };
724
        if partial {
725
            // Dependencies come from what the selected part references, not
726
            // from the whole working copy.
727
            deps = referenced_changes(&change, &snap.base);
728
            for d in extra_deps {
729
                deps.insert(*d);
730
            }
731
        }
732
        change.deps = deps.into_iter().collect();
733
        change.normalize();
734
        let hash = self.store_signed(&change)?;
735
736
        // New bookmark heads: maximal elements of old heads plus the new change.
737
        // The working copy continues on its own base plus the new change, which
738
        // is exactly what the files on disk contain; the bookmark may hold
739
        // other heads (and conflicts) the working copy has not checked out.
740
        let old_heads = self.heads_of(&op.view, &self.config.bookmark)?;
741
        let old_base = snap.base.maximal(&snap.wc.deps);
742
        let mut all: Vec<ChangeHash> = old_heads.clone();
743
        all.extend(old_base.iter().copied());
744
        all.push(hash);
745
        // The snapshot already loaded the working copy's base; when that also
746
        // holds every bookmark head, it is the state to extend.
747
        let mut st = if old_heads.iter().all(|h| snap.base.contains(h)) {
748
            snap.base
749
        } else {
750
            self.load_state(&all)?
751
        };
752
        st.add_hashed(hash, change)?;
753
        let mut with_new = old_heads.clone();
754
        with_new.push(hash);
755
        let new_heads = st.maximal(&with_new);
756
        // Automatic checkpoint once enough changes accumulated (spec §11).
757
        let since = self
758
            .latest_checkpoint(&self.config.bookmark)?
759
            .map(|(_, cp)| cp.count)
760
            .unwrap_or(0);
761
        if self.config.checkpoint_interval > 0
762
            && (st.len() as u64).saturating_sub(since) >= self.config.checkpoint_interval
763
        {
764
            let cp_state = self.load_state_full(&new_heads)?;
765
            self.write_checkpoint(&self.config.bookmark, &cp_state, &new_heads)?;
766
        }
767
        let mut wc_base = old_base.clone();
768
        wc_base.push(hash);
769
        let wc_base = st.maximal(&wc_base);
770
771
        let wc = self.new_working_copy(wc_base, "");
772
        let wc_hash = self.store.put_change(&wc)?;
773
        let mut view = op.view.clone();
774
        view.bookmarks.insert(
775
            self.config.bookmark.clone(),
776
            self.store.put_state(&StateObject::new(new_heads))?,
777
        );
778
        view.workspaces.insert(self.workspace, wc_hash);
779
        self.record_op(&[op_ref], &format!("oxy commit -m {message:?}"), view)?;
780
        if partial {
781
            // The rest is rebuilt from disk by the next snapshot.
782
            self.drop_manifest();
783
        } else {
784
            let conflicted = snap.base_snapshot.is_conflicted() && !snap.resolves;
785
            // The files on disk are now exactly the new base's renderings:
786
            // record their graph keys, so the next snapshot neither reads nor
787
            // renders them (oxygen#35).
788
            let keys = if conflicted {
789
                HashMap::new()
790
            } else {
791
                self.committed_graph_keys(&wc.deps).unwrap_or_default()
792
            };
793
            self.rewrite_manifest(conflicted, false, &keys)?;
794
        }
795
        self.maybe_autopack()?;
796
        let _ = self.run_hook(
797
            "post-commit",
798
            &format!(
799
                "{{\"event\":\"post-commit\",\"change_id\":{},\"hash\":{},\"message\":{}}}",
800
                json_str(&snap.wc.change_id.to_hex()),
801
                json_str(&hash.to_hex()),
802
                json_str(message)
803
            ),
804
        );
805
        Ok(hash)
806
    }
807
}
808
809
/// What part of the working copy a commit takes (spec §12.3).
810
#[derive(Clone, Debug)]
811
pub enum Selection {
812
    All,
813
    /// Every operation and edit on nodes under these paths.
814
    Paths(Vec<String>),
815
    /// Hunk indices as `Repo::hunks` numbers them; dependent hunks are added.
816
    Hunks(Vec<usize>),
817
}
818
819
/// One selectable piece of the working copy: a tree operation or an edit.
820
#[derive(Clone, Debug)]
821
pub struct Hunk {
822
    pub index: usize,
823
    pub path: String,
824
    /// Rendered like `oxy diff`.
825
    pub text: String,
826
}
827
828
/// The tree operations and edits on nodes under `paths`, plus the
829
/// additions of any new parent directories they need.
830
fn select_paths(
831
    wc: &Change,
832
    base_snapshot: &Snapshot,
833
    paths: &[String],
834
) -> (Vec<TreeOp>, Vec<Edit>) {
835
    let selected = |p: &str| {
836
        paths
837
            .iter()
838
            .any(|x| p == x || p.starts_with(&format!("{}/", x.trim_end_matches('/'))))
839
    };
840
    let by_node = base_snapshot.tree.by_node();
841
    let mut new_names: HashMap<NodeId, (NodeId, String, NodeKind)> = HashMap::new();
842
    for op in &wc.tree_ops {
843
        if let TreeOp::AddNode {
844
            node,
845
            parent,
846
            name,
847
            kind,
848
            ..
849
        } = op
850
        {
851
            new_names.insert(*node, (*parent, name.clone(), *kind));
852
        }
853
    }
854
    let mut nodes: BTreeSet<NodeId> = BTreeSet::new();
855
    for n in wc
856
        .tree_ops
857
        .iter()
858
        .map(|o| o.node())
859
        .chain(wc.edits.iter().map(|e| e.node()))
860
    {
861
        if path_of_node(&n, &by_node, &new_names).is_some_and(|p| selected(&p)) {
862
            nodes.insert(n);
863
        }
864
    }
865
    // New parents of selected new nodes come along.
866
    let mut changed = true;
867
    while changed {
868
        changed = false;
869
        for (n, (parent, _, _)) in &new_names {
870
            if nodes.contains(n) && new_names.contains_key(parent) && nodes.insert(*parent) {
871
                changed = true;
872
            }
873
        }
874
    }
875
    let ops = wc
876
        .tree_ops
877
        .iter()
878
        .filter(|o| nodes.contains(&o.node()))
879
        .cloned()
880
        .collect();
881
    let edits = wc
882
        .edits
883
        .iter()
884
        .filter(|e| nodes.contains(&e.node()))
885
        .cloned()
886
        .collect();
887
    (ops, edits)
888
}
889
890
/// The hunks `indices` name plus whatever they refer to within the working
891
/// copy (the parent directory of an added node, the insert that introduced
892
/// an anchor line), renumbered so the result is a well-formed change.
893
fn select_hunks(wc: &Change, indices: &[usize]) -> (Vec<TreeOp>, Vec<Edit>) {
894
    let n_ops = wc.tree_ops.len();
895
    let mut ops_sel = vec![false; n_ops];
896
    let mut edits_sel = vec![false; wc.edits.len()];
897
    for &i in indices {
898
        if i < n_ops {
899
            ops_sel[i] = true;
900
        } else if i - n_ops < wc.edits.len() {
901
            edits_sel[i - n_ops] = true;
902
        }
903
    }
904
    // Atom ranges each insert introduces, per node, in the working copy's numbering.
905
    let mut per_node: HashMap<NodeId, u32> = HashMap::new();
906
    let mut insert_ranges: Vec<Option<(NodeId, u32, u32)>> = Vec::new();
907
    for e in &wc.edits {
908
        insert_ranges.push(match e {
909
            Edit::Insert { node, lines, .. } => {
910
                let start = per_node.entry(*node).or_default();
911
                let r = (*node, *start, *start + lines.len() as u32);
912
                *start += lines.len() as u32;
913
                Some(r)
914
            }
915
            _ => None,
916
        });
917
    }
918
    let add_index: HashMap<NodeId, usize> = wc
919
        .tree_ops
920
        .iter()
921
        .enumerate()
922
        .filter_map(|(i, o)| {
923
            if let TreeOp::AddNode { node, .. } = o {
924
                Some((*node, i))
925
            } else {
926
                None
927
            }
928
        })
929
        .collect();
930
    let insert_for = |node: &NodeId, index: u32| -> Option<usize> {
931
        insert_ranges
932
            .iter()
933
            .position(|r| matches!(r, Some((n, a, b)) if n == node && *a <= index && index < *b))
934
    };
935
    // Closure.
936
    let mut changed = true;
937
    while changed {
938
        changed = false;
939
        for i in 0..n_ops {
940
            if !ops_sel[i] {
941
                continue;
942
            }
943
            if let TreeOp::AddNode { node, parent, .. } = &wc.tree_ops[i] {
944
                if let Some(&p) = add_index.get(parent) {
945
                    if !ops_sel[p] {
946
                        ops_sel[p] = true;
947
                        changed = true;
948
                    }
949
                }
950
                // A new node's content belongs with its addition: nobody
951
                // wants an empty file committed apart from its lines.
952
                for (j, e) in wc.edits.iter().enumerate() {
953
                    if e.node() == *node && !edits_sel[j] {
954
                        edits_sel[j] = true;
955
                        changed = true;
956
                    }
957
                }
958
            }
959
        }
960
        for j in 0..wc.edits.len() {
961
            if !edits_sel[j] {
962
                continue;
963
            }
964
            let e = &wc.edits[j];
965
            if let Some(&a) = add_index.get(&e.node()) {
966
                if !ops_sel[a] {
967
                    ops_sel[a] = true;
968
                    changed = true;
969
                }
970
            }
971
            if let Edit::Insert {
972
                node,
973
                after,
974
                before,
975
                ..
976
            } = e
977
            {
978
                for r in [after, before] {
979
                    if let AtomRef::Atom { change, index } = r {
980
                        if change.is_zero() {
981
                            if let Some(k) = insert_for(node, *index) {
982
                                if !edits_sel[k] {
983
                                    edits_sel[k] = true;
984
                                    changed = true;
985
                                }
986
                            }
987
                        }
988
                    }
989
                }
990
            }
991
        }
992
    }
993
    // Renumber self-references: old atom index → new index among selected inserts.
994
    let mut remap: HashMap<(NodeId, u32), u32> = HashMap::new();
995
    let mut new_counts: HashMap<NodeId, u32> = HashMap::new();
996
    for (j, r) in insert_ranges.iter().enumerate() {
997
        if let (true, Some((node, a, b))) = (edits_sel[j], r) {
998
            let next = new_counts.entry(*node).or_default();
999
            for old in *a..*b {
1000
                remap.insert((*node, old), *next);
1001
                *next += 1;
1002
            }
1003
        }
1004
    }
1005
    let map_ref = |r: AtomRef, node: &NodeId| -> AtomRef {
1006
        match r {
1007
            AtomRef::Atom { change, index } if change.is_zero() => AtomRef::Atom {
1008
                change,
1009
                index: remap.get(&(*node, index)).copied().unwrap_or(index),
1010
            },
1011
            other => other,
1012
        }
1013
    };
1014
    let ops = wc
1015
        .tree_ops
1016
        .iter()
1017
        .enumerate()
1018
        .filter(|(i, _)| ops_sel[*i])
1019
        .map(|(_, o)| o.clone())
1020
        .collect();
1021
    let edits = wc
1022
        .edits
1023
        .iter()
1024
        .enumerate()
1025
        .filter(|(j, _)| edits_sel[*j])
1026
        .map(|(_, e)| match e {
1027
            Edit::Insert {
1028
                node,
1029
                after,
1030
                before,
1031
                lines,
1032
            } => Edit::Insert {
1033
                node: *node,
1034
                after: map_ref(*after, node),
1035
                before: map_ref(*before, node),
1036
                lines: lines.clone(),
1037
            },
1038
            other => other.clone(),
1039
        })
1040
        .collect();
1041
    (ops, edits)
1042
}
1043
1044
/// Render each tree operation and edit of `change` on its own, numbered.
1045
pub fn render_hunks(change: &Change, base: &State, base_snapshot: &Snapshot) -> Vec<Hunk> {
1046
    let by_node = base_snapshot.tree.by_node();
1047
    let mut new_names: HashMap<NodeId, (NodeId, String, NodeKind)> = HashMap::new();
1048
    for op in &change.tree_ops {
1049
        if let TreeOp::AddNode {
1050
            node,
1051
            parent,
1052
            name,
1053
            kind,
1054
            ..
1055
        } = op
1056
        {
1057
            new_names.insert(*node, (*parent, name.clone(), *kind));
1058
        }
1059
    }
1060
    let mut out = Vec::new();
1061
    for (i, op) in change.tree_ops.iter().enumerate() {
1062
        let one = Change {
1063
            tree_ops: vec![op.clone()],
1064
            edits: vec![],
1065
            ..change.clone()
1066
        };
1067
        let path = path_of_node(&op.node(), &by_node, &new_names).unwrap_or_default();
1068
        out.push(Hunk {
1069
            index: i,
1070
            path,
1071
            text: render_change(&one, base, base_snapshot),
1072
        });
1073
    }
1074
    for (j, e) in change.edits.iter().enumerate() {
1075
        let one = Change {
1076
            tree_ops: vec![],
1077
            edits: vec![e.clone()],
1078
            ..change.clone()
1079
        };
1080
        let path = path_of_node(&e.node(), &by_node, &new_names).unwrap_or_default();
1081
        out.push(Hunk {
1082
            index: change.tree_ops.len() + j,
1083
            path,
1084
            text: render_change(&one, base, base_snapshot),
1085
        });
1086
    }
1087
    out
1088
}
1089
1090
/// One file's part of a diff, for `oxy diff --json`.
1091
#[derive(Clone, Debug)]
1092
pub struct FileDiff {
1093
    pub path: String,
1094
    /// `added`, `removed`, `modified`, `renamed`, `mode`, `replaced`.
1095
    pub kind: String,
1096
    pub hunks: Vec<DiffHunk>,
1097
    /// For renames, the previous path.
1098
    pub from: Option<String>,
1099
}
1100
1101
/// Lines inserted after `base_line` (0 = before the first line) and lines
1102
/// removed, with their base line numbers.
1103
#[derive(Clone, Debug, Default)]
1104
pub struct DiffHunk {
1105
    pub base_line: u32,
1106
    pub added: Vec<Vec<u8>>,
1107
    pub removed: Vec<(u32, Vec<u8>)>,
1108
}
1109
1110
impl Repo {
1111
    /// The content of `path` in a state: `heads`, or the working copy's base.
1112
    pub fn file_at(&self, path: &str, heads: Option<&[ChangeHash]>) -> Result<Vec<u8>> {
1113
        let snapshot = match heads {
1114
            Some(h) => self.load_state(h)?.materialize(),
1115
            None => {
1116
                let (_, wc) = self.working_copy()?;
1117
                self.load_state(&wc.deps)?.materialize()
1118
            }
1119
        };
1120
        let Some(f) = snapshot.files.get(path) else {
1121
            return fail(format!("{path} is not in that state"));
1122
        };
1123
        match &f.content {
1124
            FileContent::Dir => fail(format!("{path} is a directory")),
1125
            FileContent::Text { bytes, .. } => Ok(bytes.clone()),
1126
            FileContent::Opaque { blobs } => match blobs.first() {
1127
                Some(b) => self.read_blob(b),
1128
                None => Ok(vec![]),
1129
            },
1130
        }
1131
    }
1132
1133
    /// Restore `paths` (files or directories) to the working copy's base:
1134
    /// edits are undone, additions removed, removals put back. Returns the
1135
    /// number of paths touched.
1136
    pub fn discard(&self, paths: &[String]) -> Result<usize> {
1137
        let _wc = self.lock_working_copy()?;
1138
        let snap = self.snapshot_status("oxy discard")?;
1139
        let under = |p: &str| {
1140
            paths
1141
                .iter()
1142
                .any(|x| p == x || p.starts_with(&format!("{}/", x.trim_end_matches('/'))))
1143
        };
1144
        let attrs = Repo::state_attributes(&snap.base_snapshot);
1145
        let mut n = 0;
1146
        for s in &snap.statuses {
1147
            if !under(&s.path) {
1148
                continue;
1149
            }
1150
            match snap.base_snapshot.files.get(&s.path) {
1151
                None => {
1152
                    // Added (or the new name of a rename): remove it.
1153
                    let full = self.root.join(&s.path);
1154
                    if full.is_dir() {
1155
                        let _ = fs::remove_dir_all(&full);
1156
                    } else {
1157
                        let _ = fs::remove_file(&full);
1158
                    }
1159
                    n += 1;
1160
                }
1161
                Some(f) => {
1162
                    match &f.content {
1163
                        FileContent::Dir => fs::create_dir_all(self.root.join(&s.path))?,
1164
                        FileContent::Text { bytes, .. } => {
1165
                            let on_disk: std::borrow::Cow<[u8]> = if attrs.lookup(&s.path).eol
1166
                                == Some(crate::attributes::Eol::Crlf)
1167
                            {
1168
                                crate::attributes::to_crlf(bytes).into()
1169
                            } else {
1170
                                bytes.as_slice().into()
1171
                            };
1172
                            self.write_file(&s.path, &on_disk, f.mode.exec)?;
1173
                        }
1174
                        FileContent::Opaque { blobs } => {
1175
                            let bytes = match blobs.first() {
1176
                                Some(b) => self.read_blob(b)?,
1177
                                None => vec![],
1178
                            };
1179
                            if f.kind == NodeKind::Symlink {
1180
                                self.write_symlink(&s.path, &bytes)?;
1181
                            } else if f.kind == NodeKind::File {
1182
                                self.write_file(&s.path, &bytes, f.mode.exec)?;
1183
                            }
1184
                        }
1185
                    }
1186
                    n += 1;
1187
                }
1188
            }
1189
        }
1190
        // A rename's old name is not in the statuses; put it back too.
1191
        for (p, f) in &snap.base_snapshot.files {
1192
            if under(p)
1193
                && !self.root.join(p).exists()
1194
                && f.kind != NodeKind::Dir
1195
                && f.kind != NodeKind::Subrepo
1196
                && !snap.statuses.iter().any(|s| s.path == *p)
1197
            {
1198
                let bytes = match &f.content {
1199
                    FileContent::Text { bytes, .. } => bytes.clone(),
1200
                    FileContent::Opaque { blobs } => blobs
1201
                        .first()
1202
                        .map(|b| self.read_blob(b))
1203
                        .transpose()?
1204
                        .unwrap_or_default(),
1205
                    FileContent::Dir => continue,
1206
                };
1207
                if f.kind == NodeKind::Symlink {
1208
                    self.write_symlink(p, &bytes)?
1209
                } else {
1210
                    self.write_file(p, &bytes, f.mode.exec)?
1211
                }
1212
                n += 1;
1213
            }
1214
        }
1215
        self.drop_manifest();
1216
        Ok(n)
1217
    }
1218
1219
    /// Undo the working-copy hunks `indices` (as `hunks` numbers them) on
1220
    /// disk, keeping the others: the files are rewritten from the base plus
1221
    /// the remaining hunks.
1222
    pub fn discard_hunks(&self, indices: &[usize]) -> Result<usize> {
1223
        let _wc = self.lock_working_copy()?;
1224
        let (snap, hunks) = self.hunks()?;
1225
        let keep: Vec<usize> = hunks
1226
            .iter()
1227
            .map(|h| h.index)
1228
            .filter(|i| !indices.contains(i))
1229
            .collect();
1230
        let (ops, edits) = select_hunks(&snap.wc, &keep);
1231
        let dropped_nodes: BTreeSet<NodeId> = hunks
1232
            .iter()
1233
            .filter(|h| indices.contains(&h.index))
1234
            .map(|h| {
1235
                if h.index < snap.wc.tree_ops.len() {
1236
                    snap.wc.tree_ops[h.index].node()
1237
                } else {
1238
                    snap.wc.edits[h.index - snap.wc.tree_ops.len()].node()
1239
                }
1240
            })
1241
            .collect();
1242
        let mut partial = snap.wc.clone();
1243
        partial.tree_ops = ops;
1244
        partial.edits = edits;
1245
        partial.normalize();
1246
        let mut st = snap.base.clone();
1247
        st.add_unchecked(partial);
1248
        // Every file of the target is rendered: build the graphs the
1249
        // partial snapshot left out.
1250
        self.load_all_graphs(&mut st)?;
1251
        let target = st.materialize();
1252
        let by_node_target = target.tree.by_node();
1253
        let by_node_base = snap.base_snapshot.tree.by_node();
1254
        let attrs = Repo::state_attributes(&target);
1255
        let mut n = 0;
1256
        for node in dropped_nodes {
1257
            match by_node_target.get(&node) {
1258
                Some(e) => {
1259
                    let f = &target.files[&e.path];
1260
                    match &f.content {
1261
                        FileContent::Dir => {}
1262
                        FileContent::Text { bytes, .. } => {
1263
                            let on_disk: std::borrow::Cow<[u8]> = if attrs.lookup(&e.path).eol
1264
                                == Some(crate::attributes::Eol::Crlf)
1265
                            {
1266
                                crate::attributes::to_crlf(bytes).into()
1267
                            } else {
1268
                                bytes.as_slice().into()
1269
                            };
1270
                            self.write_file(&e.path, &on_disk, f.mode.exec)?;
1271
                        }
1272
                        FileContent::Opaque { blobs } => {
1273
                            let bytes = blobs
1274
                                .first()
1275
                                .map(|b| self.read_blob(b))
1276
                                .transpose()?
1277
                                .unwrap_or_default();
1278
                            if f.kind == NodeKind::Symlink {
1279
                                self.write_symlink(&e.path, &bytes)?
1280
                            } else {
1281
                                self.write_file(&e.path, &bytes, f.mode.exec)?
1282
                            }
1283
                        }
1284
                    }
1285
                    // A discarded rename: the new name goes.
1286
                    if let Some(old_path) = snap
1287
                        .statuses
1288
                        .iter()
1289
                        .find(|s| {
1290
                            s.status == ChangeStatus::Renamed && !target.files.contains_key(&s.path)
1291
                        })
1292
                        .map(|s| s.path.clone())
1293
                    {
1294
                        let _ = fs::remove_file(self.root.join(old_path));
1295
                    }
1296
                    n += 1;
1297
                }
1298
                None => {
1299
                    // The node exists in neither target nor base with a live path: an addition to remove.
1300
                    if let Some(added) = snap.statuses.iter().find(|s| {
1301
                        s.status == ChangeStatus::Added
1302
                            && !target.files.contains_key(&s.path)
1303
                            && !by_node_base.contains_key(&node)
1304
                    }) {
1305
                        let full = self.root.join(&added.path);
1306
                        if full.is_dir() {
1307
                            let _ = fs::remove_dir_all(&full);
1308
                        } else {
1309
                            let _ = fs::remove_file(&full);
1310
                        }
1311
                        n += 1;
1312
                    }
1313
                }
1314
            }
1315
        }
1316
        self.drop_manifest();
1317
        Ok(n)
1318
    }
1319
1320
    /// The diff of the working copy (`None`) or of a change, per file with
1321
    /// line-numbered hunks (spec: `oxy diff --json`).
1322
    pub fn diff_files(&self, change: Option<&ChangeHash>) -> Result<Vec<FileDiff>> {
1323
        let (c, base, base_snapshot) = match change {
1324
            Some(h) => {
1325
                let c = self.store.get_change(h)?;
1326
                let (base, snapshot) = self.change_base(&c)?;
1327
                (c, base, snapshot)
1328
            }
1329
            None => {
1330
                let snap = self.snapshot_status("oxy diff")?;
1331
                (snap.wc, snap.base, snap.base_snapshot)
1332
            }
1333
        };
1334
        Ok(diff_files_of(&c, &base, &base_snapshot))
1335
    }
1336
1337
    /// The log restricted to changes touching `path` (its node, so renames
1338
    /// are followed), on the current bookmark.
1339
    pub fn log_for_path(&self, path: &str) -> Result<Vec<LogEntry>> {
1340
        let heads = self.bookmark_heads()?;
1341
        if self.is_bare() {
1342
            return self.log_for_path_in(path, &heads);
1343
        }
1344
        let entries = self.log()?;
1345
        let (_, wc) = self.working_copy()?;
1346
        let base_snapshot = self.load_state(&wc.deps)?.materialize();
1347
        let state_snapshot = self.load_state(&heads)?.materialize();
1348
        let node = base_snapshot
1349
            .files
1350
            .get(path)
1351
            .or_else(|| state_snapshot.files.get(path))
1352
            .map(|f| f.node);
1353
        let Some(node) = node else {
1354
            return fail(format!("{path} is not tracked"));
1355
        };
1356
        Ok(self.entries_touching(entries, node))
1357
    }
1358
1359
    /// The log of the state with these heads restricted to changes touching
1360
    /// `path` (its node, so renames are followed).
1361
    pub fn log_for_path_in(&self, path: &str, heads: &[ChangeHash]) -> Result<Vec<LogEntry>> {
1362
        self.log_for_path_of(&self.load_state_history(heads)?, path, None)
1363
    }
1364
1365
    /// The changes of a loaded state touching `path`, newest first, at most
1366
    /// `limit` of them. The path is found in the state's tree alone, so no
1367
    /// file is rendered, and the walk stops once `limit` are found.
1368
    pub fn log_for_path_of(
1369
        &self,
1370
        state: &State,
1371
        path: &str,
1372
        limit: Option<usize>,
1373
    ) -> Result<Vec<LogEntry>> {
1374
        let Some(node) = state.tree().view().entries.get(path).map(|e| e.node) else {
1375
            return fail(format!("{path} is not in that state"));
1376
        };
1377
        Ok(self.entries_touching_up_to(self.log_of(state), node, limit))
1378
    }
1379
1380
    fn entries_touching(&self, entries: Vec<LogEntry>, node: NodeId) -> Vec<LogEntry> {
1381
        self.entries_touching_up_to(entries, node, None)
1382
    }
1383
1384
    fn entries_touching_up_to(
1385
        &self,
1386
        entries: Vec<LogEntry>,
1387
        node: NodeId,
1388
        limit: Option<usize>,
1389
    ) -> Vec<LogEntry> {
1390
        let mut out = Vec::new();
1391
        for e in entries {
1392
            if limit.is_some_and(|n| out.len() >= n) {
1393
                break;
1394
            }
1395
            let Ok(c) = self.store.get_change(&e.hash) else {
1396
                continue;
1397
            };
1398
            if c.tree_ops.iter().any(|o| o.node() == node)
1399
                || c.edits.iter().any(|x| x.node() == node)
1400
            {
1401
                out.push(e);
1402
            }
1403
        }
1404
        out
1405
    }
1406
}
1407
1408
/// Per-file hunks of `change` against `base`.
1409
pub fn diff_files_of(change: &Change, base: &State, base_snapshot: &Snapshot) -> Vec<FileDiff> {
1410
    let by_node = base_snapshot.tree.by_node();
1411
    let mut new_names: HashMap<NodeId, (NodeId, String, NodeKind)> = HashMap::new();
1412
    for op in &change.tree_ops {
1413
        if let TreeOp::AddNode {
1414
            node,
1415
            parent,
1416
            name,
1417
            kind,
1418
            ..
1419
        } = op
1420
        {
1421
            new_names.insert(*node, (*parent, name.clone(), *kind));
1422
        }
1423
    }
1424
    let path_of = |n: &NodeId| -> String {
1425
        path_of_node(n, &by_node, &new_names).unwrap_or_else(|| format!("<node {}>", n.short(8)))
1426
    };
1427
    let mut files: BTreeMap<NodeId, FileDiff> = BTreeMap::new();
1428
    let mut order: Vec<NodeId> = Vec::new();
1429
    let mut entry = |files: &mut BTreeMap<NodeId, FileDiff>, n: NodeId, kind: &str| {
1430
        if let std::collections::btree_map::Entry::Vacant(v) = files.entry(n) {
1431
            order.push(n);
1432
            v.insert(FileDiff {
1433
                path: path_of(&n),
1434
                kind: kind.to_string(),
1435
                hunks: vec![],
1436
                from: None,
1437
            });
1438
        }
1439
    };
1440
    for op in &change.tree_ops {
1441
        match op {
1442
            TreeOp::AddNode { node, kind, .. } => {
1443
                if *kind != NodeKind::Dir {
1444
                    entry(&mut files, *node, "added");
1445
                }
1446
            }
1447
            TreeOp::RemoveNode { node, .. } => {
1448
                entry(&mut files, *node, "removed");
1449
                if let Some(e) = by_node.get(node) {
1450
                    files.get_mut(node).unwrap().path = e.path.clone();
1451
                }
1452
            }
1453
            TreeOp::Move {
1454
                node, parent, name, ..
1455
            } => {
1456
                entry(&mut files, *node, "renamed");
1457
                let f = files.get_mut(node).unwrap();
1458
                f.from = by_node.get(node).map(|e| e.path.clone());
1459
                let dir = if parent.is_root() {
1460
                    String::new()
1461
                } else {
1462
                    path_of_node(parent, &by_node, &new_names).unwrap_or_default()
1463
                };
1464
                f.path = if dir.is_empty() {
1465
                    name.clone()
1466
                } else {
1467
                    format!("{dir}/{name}")
1468
                };
1469
            }
1470
            TreeOp::SetMode { node, .. } => entry(&mut files, *node, "mode"),
1471
        }
1472
    }
1473
    // Base line numbers per node, 1-based.
1474
    let mut line_of: HashMap<NodeId, HashMap<(ChangeHash, u32), u32>> = HashMap::new();
1475
    let mut lines_for = |n: &NodeId| -> HashMap<(ChangeHash, u32), u32> {
1476
        line_of
1477
            .entry(*n)
1478
            .or_insert_with(|| {
1479
                base.live_lines(n)
1480
                    .into_iter()
1481
                    .enumerate()
1482
                    .map(|(i, (k, _))| (k, i as u32 + 1))
1483
                    .collect()
1484
            })
1485
            .clone()
1486
    };
1487
    for e in &change.edits {
1488
        let n = e.node();
1489
        let is_new = new_names.contains_key(&n);
1490
        entry(&mut files, n, if is_new { "added" } else { "modified" });
1491
        let f = files.get_mut(&n).unwrap();
1492
        match e {
1493
            Edit::Insert { after, lines, .. } => {
1494
                let map = lines_for(&n);
1495
                let base_line = match after {
1496
                    AtomRef::Start => 0,
1497
                    AtomRef::End => map.len() as u32,
1498
                    AtomRef::Atom { change, index } if change.is_zero() => {
1499
                        f.hunks.last().map(|h| h.base_line).unwrap_or(0)
1500
                    }
1501
                    AtomRef::Atom { change, index } => {
1502
                        map.get(&(*change, *index)).copied().unwrap_or(0)
1503
                    }
1504
                };
1505
                f.hunks.push(DiffHunk {
1506
                    base_line,
1507
                    added: lines.to_vec(),
1508
                    removed: vec![],
1509
                });
1510
            }
1511
            Edit::Delete { atoms, .. } => {
1512
                let map = lines_for(&n);
1513
                let mut removed = Vec::new();
1514
                for r in atoms {
1515
                    for i in r.from..r.to {
1516
                        let line = map.get(&(r.change, i)).copied().unwrap_or(0);
1517
                        let text = base
1518
                            .file(&n)
1519
                            .and_then(|g| g.content(&(r.change, i)))
1520
                            .unwrap_or(b"")
1521
                            .to_vec();
1522
                        removed.push((line, text));
1523
                    }
1524
                }
1525
                let base_line = removed
1526
                    .first()
1527
                    .map(|(l, _)| l.saturating_sub(1))
1528
                    .unwrap_or(0);
1529
                f.hunks.push(DiffHunk {
1530
                    base_line,
1531
                    added: vec![],
1532
                    removed,
1533
                });
1534
            }
1535
            Edit::Replace { .. } => {
1536
                if !is_new {
1537
                    f.kind = "replaced".into();
1538
                }
1539
            }
1540
        }
1541
    }
1542
    order.into_iter().filter_map(|n| files.remove(&n)).collect()
1543
}
1544
1545
/// Builds the tree ops and edits of a working-copy change against a base.
1546
/// `BLAKE3("oxy node 1" 0 seed kind path)`, truncated: a node identifier
1547
/// that the same seed and path always give (never the root's).
1548
fn seeded_node(seed: &[u8; 32], path: &str, kind: NodeKind) -> NodeId {
1549
    let mut h = blake3::Hasher::new();
1550
    h.update(b"oxy node 1\0");
1551
    h.update(seed);
1552
    h.update(&[match kind {
1553
        NodeKind::File => 1,
1554
        NodeKind::Dir => 2,
1555
        NodeKind::Symlink => 3,
1556
        NodeKind::Subrepo => 4,
1557
    }]);
1558
    h.update(path.as_bytes());
1559
    let mut id = [0u8; 16];
1560
    id.copy_from_slice(&h.finalize().as_bytes()[..16]);
1561
    if id == [0; 16] {
1562
        id[15] = 1;
1563
    }
1564
    NodeId(id)
1565
}
1566
1567
struct ChangeBuilder<'a> {
1568
    base: &'a State,
1569
    base_snapshot: &'a Snapshot,
1570
    tree_ops: Vec<TreeOp>,
1571
    edits: Vec<Edit>,
1572
    statuses: Vec<PathStatus>,
1573
    dir_nodes: HashMap<String, NodeId>,
1574
    reuse: HashMap<String, (NodeId, NodeKind)>,
1575
    /// Changes that contributed to conflicts this working copy resolves.
1576
    contributors: BTreeSet<ChangeHash>,
1577
    resolves: bool,
1578
    attrs: crate::attributes::Attributes,
1579
    blobs: HashMap<String, ObjectRef>,
1580
    /// Opaque files whose replace conflict the content settles.
1581
    resolve: HashSet<String>,
1582
    /// When set, new nodes' identifiers derive from it and their paths.
1583
    node_seed: Option<[u8; 32]>,
1584
    /// For a Git import, the base's dead directories by where they were
1585
    /// (see `ensure_dir`), worked out when first needed.
1586
    dead_dirs: Option<HashMap<(NodeId, String), (NodeId, crate::tree::OpKey)>>,
1587
}
1588
1589
impl<'a> ChangeBuilder<'a> {
1590
    fn new(
1591
        base: &'a State,
1592
        base_snapshot: &'a Snapshot,
1593
        reuse: HashMap<String, (NodeId, NodeKind)>,
1594
    ) -> Self {
1595
        let mut dir_nodes: HashMap<String, NodeId> = HashMap::new();
1596
        dir_nodes.insert(String::new(), NodeId::ROOT);
1597
        for (p, e) in base_snapshot.tree.entries.iter() {
1598
            if e.kind == NodeKind::Dir {
1599
                dir_nodes.insert(p.clone(), e.node);
1600
            }
1601
        }
1602
        ChangeBuilder {
1603
            base,
1604
            base_snapshot,
1605
            tree_ops: vec![],
1606
            edits: vec![],
1607
            statuses: vec![],
1608
            dir_nodes,
1609
            reuse,
1610
            contributors: BTreeSet::new(),
1611
            resolves: false,
1612
            attrs: crate::attributes::Attributes::default(),
1613
            blobs: HashMap::new(),
1614
            resolve: HashSet::new(),
1615
            node_seed: None,
1616
            dead_dirs: None,
1617
        }
1618
    }
1619
1620
    fn with_attributes(mut self, attrs: crate::attributes::Attributes) -> Self {
1621
        self.attrs = attrs;
1622
        self
1623
    }
1624
1625
    /// Whether a file is opaque: forced by `binary`, forced text by `text`
1626
    /// only when it has no NUL bytes, else sniffed.
1627
    /// The blob for an opaque entry: the cached one, else stored now.
1628
    fn blob_of(
1629
        &mut self,
1630
        repo: &Repo,
1631
        path: &str,
1632
        e: &FsEntry,
1633
        nocompress: bool,
1634
    ) -> Result<ObjectRef> {
1635
        let b = match e.blob {
1636
            Some(b) => b,
1637
            None => repo.store_blob_for(&e.content, nocompress)?,
1638
        };
1639
        self.blobs.insert(path.to_string(), b);
1640
        Ok(b)
1641
    }
1642
1643
    fn opaque_for(&self, path: &str, e: &FsEntry) -> bool {
1644
        if e.blob.is_some() {
1645
            return true;
1646
        }
1647
        if e.kind == NodeKind::Symlink || e.kind == NodeKind::Subrepo {
1648
            return true;
1649
        }
1650
        match self.attrs.lookup(path).binary {
1651
            Some(true) => true,
1652
            Some(false) => is_binary(&e.content),
1653
            None => is_binary(&e.content),
1654
        }
1655
    }
1656
1657
    /// Text content as stored: `\r\n` normalized for `eol=` files.
1658
    fn stored_text(
1659
        &self,
1660
        path: &str,
1661
        content: &std::sync::Arc<Vec<u8>>,
1662
    ) -> std::sync::Arc<Vec<u8>> {
1663
        if self.attrs.lookup(path).eol.is_some() {
1664
            std::sync::Arc::new(crate::attributes::normalize_eol(content))
1665
        } else {
1666
            content.clone()
1667
        }
1668
    }
1669
1670
    /// The identifier of a node added at `path`: reused when asked, derived
1671
    /// from the seed when there is one, random otherwise.
1672
    fn new_node(&self, path: &str, kind: NodeKind) -> NodeId {
1673
        if let Some(n) = self.reused_node(path, kind) {
1674
            return n;
1675
        }
1676
        match &self.node_seed {
1677
            Some(seed) => seeded_node(seed, path, kind),
1678
            None => NodeId::random(),
1679
        }
1680
    }
1681
1682
    fn reused_node(&self, path: &str, kind: NodeKind) -> Option<NodeId> {
1683
        self.reuse
1684
            .get(path)
1685
            .filter(|(_, k)| *k == kind)
1686
            .map(|(n, _)| *n)
1687
    }
1688
1689
    /// A dead directory last placed at (`parent`, `name`) in the base.
1690
    fn revivable_dir(
1691
        &mut self,
1692
        parent: NodeId,
1693
        name: &str,
1694
    ) -> Option<(NodeId, crate::tree::OpKey)> {
1695
        let base = self.base;
1696
        self.dead_dirs
1697
            .get_or_insert_with(|| base.tree().dead_dirs())
1698
            .get(&(parent, name.to_string()))
1699
            .copied()
1700
    }
1701
1702
    fn ensure_dir(&mut self, path: &str) -> NodeId {
1703
        if let Some(n) = self.dir_nodes.get(path) {
1704
            return *n;
1705
        }
1706
        let mut parent = NodeId::ROOT;
1707
        let mut prefix = String::new();
1708
        for comp in path.split('/') {
1709
            if !prefix.is_empty() {
1710
                prefix.push('/');
1711
            }
1712
            prefix.push_str(comp);
1713
            let known = self.dir_nodes.get(&prefix).copied();
1714
            let revive = match known {
1715
                Some(_) => None,
1716
                None if self.node_seed.is_some() => self.revivable_dir(parent, comp),
1717
                None => None,
1718
            };
1719
            parent = match (known, revive) {
1720
                (Some(n), _) => n,
1721
                (None, Some((node, old))) => {
1722
                    // Git has no identity for a directory: one that comes
1723
                    // back where it was is the same directory, brought back
1724
                    // with a move, so lines of history that placed files in
1725
                    // it before and after agree (oxygen#30).
1726
                    self.tree_ops.push(TreeOp::Move {
1727
                        node,
1728
                        old: OpRef {
1729
                            change: old.0,
1730
                            index: old.1,
1731
                        },
1732
                        parent,
1733
                        name: comp.to_string(),
1734
                    });
1735
                    self.dir_nodes.insert(prefix.clone(), node);
1736
                    node
1737
                }
1738
                (None, None) => {
1739
                    let node = self.new_node(&prefix, NodeKind::Dir);
1740
                    self.tree_ops.push(TreeOp::AddNode {
1741
                        node,
1742
                        kind: NodeKind::Dir,
1743
                        mode: Mode::default(),
1744
                        parent,
1745
                        name: comp.to_string(),
1746
                    });
1747
                    self.dir_nodes.insert(prefix.clone(), node);
1748
                    node
1749
                }
1750
            };
1751
        }
1752
        parent
1753
    }
1754
1755
    fn add_path(&mut self, repo: &Repo, path: &str, e: &FsEntry) -> Result<()> {
1756
        let (dir, name) = split_path(path);
1757
        let parent = self.ensure_dir(dir);
1758
        let node = self.new_node(path, e.kind);
1759
        let opaque = self.opaque_for(path, e);
1760
        let nocompress = self.attrs.lookup(path).nocompress;
1761
        self.tree_ops.push(TreeOp::AddNode {
1762
            node,
1763
            kind: e.kind,
1764
            mode: Mode {
1765
                exec: e.exec,
1766
                opaque,
1767
            },
1768
            parent,
1769
            name: name.to_string(),
1770
        });
1771
        if opaque {
1772
            let blob = self.blob_of(repo, path, e, nocompress)?;
1773
            self.edits.push(Edit::Replace {
1774
                node,
1775
                old: None,
1776
                new: Some(blob),
1777
            });
1778
        } else if !e.content.is_empty() {
1779
            let content = self.stored_text(path, &e.content);
1780
            self.edits.push(Edit::Insert {
1781
                node,
1782
                after: crate::objects::AtomRef::Start,
1783
                before: crate::objects::AtomRef::End,
1784
                lines: crate::lines::Lines::split_shared(content),
1785
            });
1786
        }
1787
        self.statuses.push(PathStatus {
1788
            path: path.to_string(),
1789
            status: ChangeStatus::Added,
1790
        });
1791
        Ok(())
1792
    }
1793
1794
    /// Move the node at `old` to `new` and apply `e`'s content to it.
1795
    fn move_path(
1796
        &mut self,
1797
        repo: &Repo,
1798
        old: &str,
1799
        new: &str,
1800
        e: &FsEntry,
1801
        expected: &crate::state::FileState,
1802
    ) -> Result<()> {
1803
        let entry = &self.base_snapshot.tree.entries[old];
1804
        let (dir, name) = split_path(new);
1805
        let parent = self.ensure_dir(dir);
1806
        self.tree_ops.push(TreeOp::Move {
1807
            node: expected.node,
1808
            old: op_ref(entry.placement),
1809
            parent,
1810
            name: name.to_string(),
1811
        });
1812
        self.update_path(repo, old, e, expected)?;
1813
        // update_path reports under the old path; the rename is what the user sees.
1814
        self.statuses.retain(|s| s.path != old);
1815
        self.statuses.push(PathStatus {
1816
            path: new.to_string(),
1817
            status: ChangeStatus::Renamed,
1818
        });
1819
        Ok(())
1820
    }
1821
1822
    /// For a Git import: a node the commit keeps is in one place, the one
1823
    /// its tree names, so any other live placement it has in the base goes;
1824
    /// and a node the tree cannot show at all (an orphan) goes too. Such a
1825
    /// placement is out of sight, under a directory another line of history
1826
    /// removed, where no diff of the tree would ever reach it (oxygen#30).
1827
    fn retire_stray_placements(&mut self) {
1828
        let mut retired: HashSet<(ChangeHash, u32)> = HashSet::new();
1829
        let mut placed: BTreeSet<NodeId> = BTreeSet::new();
1830
        for op in &self.tree_ops {
1831
            match op {
1832
                TreeOp::Move { node, old, .. } => {
1833
                    retired.insert((old.change, old.index));
1834
                    placed.insert(*node);
1835
                }
1836
                TreeOp::RemoveNode { placement, .. } => {
1837
                    retired.insert((placement.change, placement.index));
1838
                }
1839
                TreeOp::AddNode { .. } | TreeOp::SetMode { .. } => {}
1840
            }
1841
        }
1842
        // Nodes kept where they were: what the base's tree view shows and
1843
        // this change neither moves nor removes.
1844
        let mut kept: HashMap<NodeId, (ChangeHash, u32)> = HashMap::new();
1845
        for e in self.base_snapshot.tree.entries.values() {
1846
            if !retired.contains(&e.placement) {
1847
                kept.insert(e.node, e.placement);
1848
            }
1849
        }
1850
        // Only a node with several live placements can have a stray one,
1851
        // and the tree view names each as a conflict.
1852
        let multi: BTreeSet<NodeId> = self
1853
            .base_snapshot
1854
            .tree
1855
            .conflicts
1856
            .iter()
1857
            .filter_map(|c| match c {
1858
                crate::tree::TreeConflict::MultiPlacement { node, .. } => Some(*node),
1859
                _ => None,
1860
            })
1861
            .collect();
1862
        let mut extra = Vec::new();
1863
        // A node whose only placements are under a directory another line
1864
        // removed (an orphan) is nowhere the tree can show, and Git's tree
1865
        // has no such path: it goes.
1866
        for c in &self.base_snapshot.tree.conflicts {
1867
            let crate::tree::TreeConflict::Orphan { node, .. } = c else {
1868
                continue;
1869
            };
1870
            if kept.contains_key(node) || placed.contains(node) {
1871
                continue;
1872
            }
1873
            for (k, _) in self.base.tree().live_placements(node) {
1874
                if retired.insert(k) {
1875
                    extra.push(TreeOp::RemoveNode {
1876
                        node: *node,
1877
                        placement: op_ref(k),
1878
                    });
1879
                }
1880
            }
1881
        }
1882
        for node in placed
1883
            .iter()
1884
            .chain(multi.iter().filter(|n| kept.contains_key(*n)))
1885
        {
1886
            for (k, _) in self.base.tree().live_placements(node) {
1887
                if retired.contains(&k) || kept.get(node) == Some(&k) {
1888
                    continue;
1889
                }
1890
                retired.insert(k);
1891
                extra.push(TreeOp::RemoveNode {
1892
                    node: *node,
1893
                    placement: op_ref(k),
1894
                });
1895
            }
1896
        }
1897
        if !extra.is_empty() {
1898
            self.resolves = true;
1899
            self.tree_ops.extend(extra);
1900
        }
1901
    }
1902
1903
    fn remove_path(&mut self, path: &str, expected: &crate::state::FileState) {
1904
        let entry = &self.base_snapshot.tree.entries[path];
1905
        self.tree_ops.push(TreeOp::RemoveNode {
1906
            node: expected.node,
1907
            placement: op_ref(entry.placement),
1908
        });
1909
        if path.contains(".oxy-conflict-") || expected.is_conflicted() {
1910
            self.resolves = true;
1911
        }
1912
        self.statuses.push(PathStatus {
1913
            path: path.to_string(),
1914
            status: ChangeStatus::Removed,
1915
        });
1916
    }
1917
1918
    fn update_path(
1919
        &mut self,
1920
        repo: &Repo,
1921
        path: &str,
1922
        e: &FsEntry,
1923
        expected: &crate::state::FileState,
1924
    ) -> Result<()> {
1925
        if expected.kind != e.kind {
1926
            self.remove_path(path, expected);
1927
            self.statuses.pop();
1928
            self.add_path(repo, path, e)?;
1929
            self.statuses.pop();
1930
            self.statuses.push(PathStatus {
1931
                path: path.to_string(),
1932
                status: ChangeStatus::Modified,
1933
            });
1934
            return Ok(());
1935
        }
1936
        let entry = &self.base_snapshot.tree.entries[path];
1937
        let node = expected.node;
1938
        let mode_atom = entry.mode_atom.map(op_ref);
1939
        if e.unchanged {
1940
            // Known equal to the base's unconflicted rendering (spec
1941
            // §12.3); only the executable bit can differ.
1942
            if e.exec != expected.mode.exec {
1943
                if let Some(old) = mode_atom {
1944
                    self.tree_ops.push(TreeOp::SetMode {
1945
                        node,
1946
                        old,
1947
                        mode: Mode {
1948
                            exec: e.exec,
1949
                            opaque: false,
1950
                        },
1951
                    });
1952
                    self.statuses.push(PathStatus {
1953
                        path: path.to_string(),
1954
                        status: ChangeStatus::ModeChanged,
1955
                    });
1956
                }
1957
            }
1958
            return Ok(());
1959
        }
1960
        let mut status: Option<ChangeStatus> = None;
1961
        let wants_opaque = self.opaque_for(path, e);
1962
        let nocompress = self.attrs.lookup(path).nocompress;
1963
        let disk_text = self.stored_text(path, &e.content);
1964
        match &expected.content {
1965
            FileContent::Dir => {}
1966
            FileContent::Text {
1967
                bytes,
1968
                materialized,
1969
            } => {
1970
                if materialized.is_conflicted() {
1971
                    if bytes == &*disk_text {
1972
                        return Ok(());
1973
                    }
1974
                    if has_conflict_markers(&e.content) {
1975
                        self.statuses.push(PathStatus {
1976
                            path: path.to_string(),
1977
                            status: ChangeStatus::ConflictEdited,
1978
                        });
1979
                        return Ok(());
1980
                    }
1981
                    // Resolution (spec §9.6): diff against the unconflicted lines
1982
                    // with each region as a gap, then retire every region atom.
1983
                    // Whatever the author kept from a region is re-inserted as
1984
                    // new atoms, which leaves the graph totally ordered.
1985
                    let regions = self.base.conflict_regions(&node);
1986
                    let mut edits = text_edits(node, &regions.plain, &disk_text);
1987
                    if !regions.region_atoms.is_empty() {
1988
                        edits.insert(
1989
                            0,
1990
                            Edit::Delete {
1991
                                node,
1992
                                atoms: ranges(&regions.region_atoms),
1993
                            },
1994
                        );
1995
                    }
1996
                    self.edits.extend(edits);
1997
                    self.contributors.extend(regions.contributors);
1998
                    self.resolves = true;
1999
                    if e.exec != expected.mode.exec {
2000
                        if let Some(old) = mode_atom {
2001
                            self.tree_ops.push(TreeOp::SetMode {
2002
                                node,
2003
                                old,
2004
                                mode: Mode {
2005
                                    exec: e.exec,
2006
                                    opaque: false,
2007
                                },
2008
                            });
2009
                        }
2010
                    }
2011
                    self.statuses.push(PathStatus {
2012
                        path: path.to_string(),
2013
                        status: ChangeStatus::Resolved,
2014
                    });
2015
                    return Ok(());
2016
                }
2017
                if wants_opaque {
2018
                    // Text → opaque (spec §7.5), by content or by attribute.
2019
                    if let Some(old) = mode_atom {
2020
                        self.tree_ops.push(TreeOp::SetMode {
2021
                            node,
2022
                            old,
2023
                            mode: Mode {
2024
                                exec: e.exec,
2025
                                opaque: true,
2026
                            },
2027
                        });
2028
                    }
2029
                    let live: Vec<_> = repo_live_keys(self.base, &node);
2030
                    if !live.is_empty() {
2031
                        self.edits.push(Edit::Delete {
2032
                            node,
2033
                            atoms: ranges(&live),
2034
                        });
2035
                    }
2036
                    let blob = self.blob_of(repo, path, e, nocompress)?;
2037
                    self.edits.push(Edit::Replace {
2038
                        node,
2039
                        old: None,
2040
                        new: Some(blob),
2041
                    });
2042
                    status = Some(ChangeStatus::Modified);
2043
                } else if bytes != &*disk_text {
2044
                    let mut laps = crate::timing::Laps::start();
2045
                    // The base's rendering holds its live atoms in order,
2046
                    // one per line (it is not conflicted here).
2047
                    let keys = materialized.live_atoms();
2048
                    let lines = crate::diff::split_lines(bytes);
2049
                    let edits = if keys.len() == lines.len() {
2050
                        crate::diff::text_edits_of(node, &keys, &lines, &disk_text)
2051
                    } else {
2052
                        text_edits(node, &self.base.live_lines(&node), &disk_text)
2053
                    };
2054
                    laps.lap("build: text diff");
2055
                    if !edits.is_empty() {
2056
                        self.edits.extend(edits);
2057
                        status = Some(ChangeStatus::Modified);
2058
                    }
2059
                }
2060
                let switched_to_opaque = wants_opaque;
2061
                if !switched_to_opaque && e.exec != expected.mode.exec {
2062
                    if let Some(old) = mode_atom {
2063
                        self.tree_ops.push(TreeOp::SetMode {
2064
                            node,
2065
                            old,
2066
                            mode: Mode {
2067
                                exec: e.exec,
2068
                                opaque: false,
2069
                            },
2070
                        });
2071
                        status.get_or_insert(ChangeStatus::ModeChanged);
2072
                    }
2073
                }
2074
            }
2075
            FileContent::Opaque { blobs } => {
2076
                let new_ref = e.blob.unwrap_or_else(|| Repo::blob_ref(&e.content));
2077
                if e.kind == NodeKind::File && wants_opaque {
2078
                    // Unchanged or replaced, the file stays opaque: remember its blob.
2079
                    self.blobs.insert(path.to_string(), new_ref);
2080
                }
2081
                if blobs.len() > 1 && self.resolve.contains(path) && e.kind == expected.kind {
2082
                    // Settle the replace conflict (spec §9.3): replace every
2083
                    // live candidate with the chosen blob, depending on each
2084
                    // change that made one live, so all are superseded.
2085
                    let chosen = self.blob_of(repo, path, e, nocompress)?;
2086
                    for b in blobs {
2087
                        self.edits.push(Edit::Replace {
2088
                            node,
2089
                            old: Some(*b),
2090
                            new: Some(chosen),
2091
                        });
2092
                    }
2093
                    self.contributors
2094
                        .extend(self.base.blob_contributors(&node, blobs));
2095
                    self.resolves = true;
2096
                    self.statuses.push(PathStatus {
2097
                        path: path.to_string(),
2098
                        status: ChangeStatus::Resolved,
2099
                    });
2100
                    return Ok(());
2101
                }
2102
                if blobs.len() > 1 {
2103
                    if !blobs.contains(&new_ref) {
2104
                        self.statuses.push(PathStatus {
2105
                            path: path.to_string(),
2106
                            status: ChangeStatus::ConflictEdited,
2107
                        });
2108
                    }
2109
                    return Ok(());
2110
                }
2111
                let current = blobs.first().copied();
2112
                if current != Some(new_ref) {
2113
                    if e.kind == NodeKind::File && !wants_opaque {
2114
                        // Opaque → text (spec §7.5).
2115
                        if let Some(old) = mode_atom {
2116
                            self.tree_ops.push(TreeOp::SetMode {
2117
                                node,
2118
                                old,
2119
                                mode: Mode {
2120
                                    exec: e.exec,
2121
                                    opaque: false,
2122
                                },
2123
                            });
2124
                        }
2125
                        self.edits.push(Edit::Replace {
2126
                            node,
2127
                            old: current,
2128
                            new: None,
2129
                        });
2130
                        if !e.content.is_empty() {
2131
                            self.edits.push(Edit::Insert {
2132
                                node,
2133
                                after: crate::objects::AtomRef::Start,
2134
                                before: crate::objects::AtomRef::End,
2135
                                lines: crate::lines::Lines::split(&e.content),
2136
                            });
2137
                        }
2138
                    } else {
2139
                        let blob = self.blob_of(repo, path, e, nocompress)?;
2140
                        self.edits.push(Edit::Replace {
2141
                            node,
2142
                            old: current,
2143
                            new: Some(blob),
2144
                        });
2145
                    }
2146
                    status = Some(ChangeStatus::Modified);
2147
                } else if e.kind == NodeKind::File && e.exec != expected.mode.exec {
2148
                    if let Some(old) = mode_atom {
2149
                        self.tree_ops.push(TreeOp::SetMode {
2150
                            node,
2151
                            old,
2152
                            mode: Mode {
2153
                                exec: e.exec,
2154
                                opaque: true,
2155
                            },
2156
                        });
2157
                        status = Some(ChangeStatus::ModeChanged);
2158
                    }
2159
                }
2160
            }
2161
        }
2162
        if let Some(s) = status {
2163
            self.statuses.push(PathStatus {
2164
                path: path.to_string(),
2165
                status: s,
2166
            });
2167
        }
2168
        Ok(())
2169
    }
2170
}
2171
2172
fn repo_live_keys(base: &State, node: &NodeId) -> Vec<crate::graph::AtomKey> {
2173
    base.live_lines(node).into_iter().map(|(k, _)| k).collect()
2174
}
2175
2176
/// The changes a change's scope references (spec §8.1): introducers of every
2177
/// atom, placement, and mode it touches, and of every node it operates on.
2178
pub fn referenced_changes(change: &Change, base: &State) -> BTreeSet<ChangeHash> {
2179
    let mut out = BTreeSet::new();
2180
    let opref = |r: &OpRef, out: &mut BTreeSet<ChangeHash>| {
2181
        if !r.change.is_zero() {
2182
            out.insert(r.change);
2183
        }
2184
    };
2185
    let mut nodes: Vec<NodeId> = Vec::new();
2186
    for op in &change.tree_ops {
2187
        match op {
2188
            TreeOp::AddNode { parent, .. } => nodes.push(*parent),
2189
            TreeOp::RemoveNode { node, placement } => {
2190
                nodes.push(*node);
2191
                opref(placement, &mut out);
2192
            }
2193
            TreeOp::Move {
2194
                node, old, parent, ..
2195
            } => {
2196
                nodes.push(*node);
2197
                nodes.push(*parent);
2198
                opref(old, &mut out);
2199
            }
2200
            TreeOp::SetMode { node, old, .. } => {
2201
                nodes.push(*node);
2202
                opref(old, &mut out);
2203
            }
2204
        }
2205
    }
2206
    for e in &change.edits {
2207
        nodes.push(e.node());
2208
        match e {
2209
            Edit::Insert { after, before, .. } => {
2210
                for r in [after, before] {
2211
                    if let crate::objects::AtomRef::Atom { change, .. } = r {
2212
                        if !change.is_zero() {
2213
                            out.insert(*change);
2214
                        }
2215
                    }
2216
                }
2217
            }
2218
            Edit::Delete { atoms, .. } => {
2219
                // Deleting an atom also depends on whoever inserted the live
2220
                // atoms right after it: the author saw those insertions, and
2221
                // without the dependency spec §9.1 would call the deletion
2222
                // concurrent with them (a delete/insert conflict).
2223
                let graph = base.file(&e.node());
2224
                for r in atoms {
2225
                    if !r.change.is_zero() {
2226
                        out.insert(r.change);
2227
                    }
2228
                    if let Some(g) = graph {
2229
                        for i in r.from..r.to {
2230
                            out.extend(
2231
                                g.live_successor_changes(&(r.change, i))
2232
                                    .into_iter()
2233
                                    .filter(|c| !c.is_zero()),
2234
                            );
2235
                        }
2236
                    }
2237
                }
2238
            }
2239
            // Replacing a blob depends on the change that made it current,
2240
            // as deleting a line depends on the line's introducer.
2241
            Edit::Replace {
2242
                node,
2243
                old: Some(old),
2244
                ..
2245
            } => {
2246
                out.extend(
2247
                    base.live_replaces(node)
2248
                        .into_iter()
2249
                        .filter(|(c, b)| b == old && !c.is_zero())
2250
                        .map(|(c, _)| c),
2251
                );
2252
            }
2253
            Edit::Replace { .. } => {}
2254
        }
2255
    }
2256
    for n in nodes {
2257
        if let Some(h) = base.tree().introducer(&n) {
2258
            out.insert(h);
2259
        }
2260
    }
2261
    out
2262
}
2263
2264
/// Paths of the nodes a change adds on top of `base_snapshot`.
2265
pub fn added_node_paths(
2266
    change: &Change,
2267
    base_snapshot: &Snapshot,
2268
) -> HashMap<String, (NodeId, NodeKind)> {
2269
    let by_node = base_snapshot.tree.by_node();
2270
    let mut new_names: HashMap<NodeId, (NodeId, String, NodeKind)> = HashMap::new();
2271
    for op in &change.tree_ops {
2272
        if let TreeOp::AddNode {
2273
            node,
2274
            parent,
2275
            name,
2276
            kind,
2277
            ..
2278
        } = op
2279
        {
2280
            new_names.insert(*node, (*parent, name.clone(), *kind));
2281
        }
2282
    }
2283
    let mut out = HashMap::new();
2284
    for (node, (_, _, kind)) in &new_names {
2285
        if let Some(path) = path_of_node(node, &by_node, &new_names) {
2286
            out.insert(path, (*node, *kind));
2287
        }
2288
    }
2289
    out
2290
}
2291
2292
fn path_of_node(
2293
    n: &NodeId,
2294
    by_node: &HashMap<NodeId, &crate::tree::TreeEntry>,
2295
    new_names: &HashMap<NodeId, (NodeId, String, NodeKind)>,
2296
) -> Option<String> {
2297
    if let Some(e) = by_node.get(n) {
2298
        return Some(e.path.clone());
2299
    }
2300
    let mut parts = Vec::new();
2301
    let mut cur = *n;
2302
    loop {
2303
        if cur.is_root() {
2304
            break;
2305
        }
2306
        if let Some(e) = by_node.get(&cur) {
2307
            if !e.path.is_empty() {
2308
                parts.push(e.path.clone());
2309
            }
2310
            break;
2311
        }
2312
        let (parent, name, _) = new_names.get(&cur)?;
2313
        parts.push(name.clone());
2314
        cur = *parent;
2315
    }
2316
    parts.reverse();
2317
    Some(parts.join("/"))
2318
}
2319
2320
/// Render a change's operations with line content, using `base` for deleted lines.
2321
pub fn render_change(change: &Change, base: &State, base_snapshot: &Snapshot) -> String {
2322
    let by_node = base_snapshot.tree.by_node();
2323
    let mut new_names: HashMap<NodeId, (NodeId, String, NodeKind)> = HashMap::new();
2324
    for op in &change.tree_ops {
2325
        if let TreeOp::AddNode {
2326
            node,
2327
            parent,
2328
            name,
2329
            kind,
2330
            ..
2331
        } = op
2332
        {
2333
            new_names.insert(*node, (*parent, name.clone(), *kind));
2334
        }
2335
    }
2336
    let path_of = |n: &NodeId| -> String {
2337
        path_of_node(n, &by_node, &new_names).unwrap_or_else(|| format!("<node {}>", n.short(8)))
2338
    };
2339
2340
    let mut out = String::new();
2341
    for op in &change.tree_ops {
2342
        match op {
2343
            TreeOp::AddNode {
2344
                node, kind, mode, ..
2345
            } => {
2346
                out.push_str(&format!(
2347
                    "A {} ({:?}{}{})\n",
2348
                    path_of(node),
2349
                    kind,
2350
                    if mode.exec { ", exec" } else { "" },
2351
                    if mode.opaque { ", opaque" } else { "" }
2352
                ));
2353
            }
2354
            TreeOp::RemoveNode { node, .. } => out.push_str(&format!("D {}\n", path_of(node))),
2355
            TreeOp::Move { node, name, .. } => {
2356
                out.push_str(&format!("R {} -> {}\n", path_of(node), name))
2357
            }
2358
            TreeOp::SetMode { node, mode, .. } => {
2359
                out.push_str(&format!(
2360
                    "M {} mode: exec={} opaque={}\n",
2361
                    path_of(node),
2362
                    mode.exec,
2363
                    mode.opaque
2364
                ));
2365
            }
2366
        }
2367
    }
2368
    let mut last_node: Option<NodeId> = None;
2369
    for e in &change.edits {
2370
        let n = e.node();
2371
        if last_node != Some(n) {
2372
            out.push_str(&format!("--- {}\n", path_of(&n)));
2373
            last_node = Some(n);
2374
        }
2375
        match e {
2376
            Edit::Insert { lines, .. } => {
2377
                for l in lines.iter() {
2378
                    out.push('+');
2379
                    out.push_str(&String::from_utf8_lossy(l));
2380
                    if !l.ends_with(b"\n") {
2381
                        out.push('\n');
2382
                    }
2383
                }
2384
            }
2385
            Edit::Delete { atoms, .. } => {
2386
                for r in atoms {
2387
                    for i in r.from..r.to {
2388
                        let content = base
2389
                            .file(&n)
2390
                            .and_then(|g| g.content(&(r.change, i)))
2391
                            .unwrap_or(b"<unknown>\n");
2392
                        out.push('-');
2393
                        out.push_str(&String::from_utf8_lossy(content));
2394
                        if !content.ends_with(b"\n") {
2395
                            out.push('\n');
2396
                        }
2397
                    }
2398
                }
2399
            }
2400
            Edit::Replace { old, new, .. } => {
2401
                out.push_str(&format!(
2402
                    "  opaque content {} -> {}\n",
2403
                    old.map(|o| o.short(12)).unwrap_or_else(|| "none".into()),
2404
                    new.map(|o| o.short(12)).unwrap_or_else(|| "none".into())
2405
                ));
2406
            }
2407
        }
2408
    }
2409
    out
2410
}
2411
2412
/// Pair removed files with added files of the same kind whose contents are
2413
/// at least `RENAME_THRESHOLD` percent alike, best matches first. Beyond
2414
/// `RENAME_LIMIT` candidate pairs only identical contents are paired.
2415
const RENAME_THRESHOLD: u32 = 50;
2416
const RENAME_LIMIT: usize = 10_000;
2417
2418
/// What a Git import adds to building a change: the seed its new nodes'
2419
/// identifiers derive from, and, when it builds from part of the tree,
2420
/// whether the new tree has anything under a directory.
2421
struct Import<'a> {
2422
    seed: [u8; 32],
2423
    dir_needed: Option<&'a dyn Fn(&str) -> bool>,
2424
}
2425
2426
fn detect_renames(
2427
    base_snapshot: &Snapshot,
2428
    fs_entries: &BTreeMap<String, FsEntry>,
2429
    in_scope: impl Fn(&str) -> bool,
2430
) -> Vec<(String, String)> {
2431
    let removed: Vec<(&String, &crate::state::FileState)> = base_snapshot
2432
        .files
2433
        .iter()
2434
        .filter(|(p, f)| {
2435
            f.kind != NodeKind::Dir
2436
                && !fs_entries.contains_key(*p)
2437
                && in_scope(p)
2438
                && !f.is_conflicted()
2439
        })
2440
        .collect();
2441
    let added: Vec<(&String, &FsEntry)> = fs_entries
2442
        .iter()
2443
        .filter(|(p, e)| e.kind != NodeKind::Dir && !base_snapshot.files.contains_key(*p))
2444
        .collect();
2445
    if removed.is_empty() || added.is_empty() {
2446
        return vec![];
2447
    }
2448
    let exact_only = removed.len() * added.len() > RENAME_LIMIT;
2449
    let old_content = |f: &crate::state::FileState| -> Option<Vec<u8>> {
2450
        match &f.content {
2451
            FileContent::Text { bytes, .. } => Some(bytes.clone()),
2452
            _ => None,
2453
        }
2454
    };
2455
    let mut scored: Vec<(u32, usize, usize)> = Vec::new();
2456
    for (ri, (_, f)) in removed.iter().enumerate() {
2457
        let old = old_content(f);
2458
        let old_blob = match &f.content {
2459
            FileContent::Opaque { blobs } if blobs.len() == 1 => Some(blobs[0]),
2460
            _ => None,
2461
        };
2462
        for (ai, (_, e)) in added.iter().enumerate() {
2463
            if e.kind != f.kind {
2464
                continue;
2465
            }
2466
            let score = match (&old, old_blob) {
2467
                (Some(o), _) => {
2468
                    if exact_only {
2469
                        if *o == *e.content {
2470
                            100
2471
                        } else {
2472
                            0
2473
                        }
2474
                    } else {
2475
                        similarity(o, &e.content)
2476
                    }
2477
                }
2478
                (None, Some(b)) if e.blob.unwrap_or_else(|| Repo::blob_ref(&e.content)) == b => 100,
2479
                _ => 0,
2480
            };
2481
            if score >= RENAME_THRESHOLD {
2482
                scored.push((score, ri, ai));
2483
            }
2484
        }
2485
    }
2486
    scored.sort_by(|a, b| {
2487
        b.0.cmp(&a.0)
2488
            .then(removed[a.1].0.cmp(removed[b.1].0))
2489
            .then(added[a.2].0.cmp(added[b.2].0))
2490
    });
2491
    let mut used_r = vec![false; removed.len()];
2492
    let mut used_a = vec![false; added.len()];
2493
    let mut out = Vec::new();
2494
    for (_, ri, ai) in scored {
2495
        if used_r[ri] || used_a[ai] {
2496
            continue;
2497
        }
2498
        used_r[ri] = true;
2499
        used_a[ai] = true;
2500
        out.push((removed[ri].0.clone(), added[ai].0.clone()));
2501
    }
2502
    out
2503
}
2504
2505
/// Percentage of the larger file's bytes found in lines the two share
2506
/// (multiset intersection of lines), like Git's similarity index.
2507
pub fn similarity(a: &[u8], b: &[u8]) -> u32 {
2508
    if a == b {
2509
        return 100;
2510
    }
2511
    if a.is_empty() || b.is_empty() {
2512
        return 0;
2513
    }
2514
    let mut counts: HashMap<&[u8], usize> = HashMap::new();
2515
    for l in split_lines(a) {
2516
        *counts.entry(l).or_default() += 1;
2517
    }
2518
    let mut shared = 0usize;
2519
    for l in split_lines(b) {
2520
        if let Some(n) = counts.get_mut(l) {
2521
            if *n > 0 {
2522
                *n -= 1;
2523
                shared += l.len();
2524
            }
2525
        }
2526
    }
2527
    (shared * 100 / a.len().max(b.len())) as u32
2528
}