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