OXYGENHUB
# dbf06d342e1d oxygen / crates / oxy-core / src / repo / snapshot.rs
93.9 KiB · Rust · last changed Tree views updated in place, and a faster render of edited files 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(&self, path: &str, content: &[u8]) -> Vec<u8> {
1655
        if self.attrs.lookup(path).eol.is_some() {
1656
            crate::attributes::normalize_eol(content)
1657
        } else {
1658
            content.to_vec()
1659
        }
1660
    }
1661
1662
    /// The identifier of a node added at `path`: reused when asked, derived
1663
    /// from the seed when there is one, random otherwise.
1664
    fn new_node(&self, path: &str, kind: NodeKind) -> NodeId {
1665
        if let Some(n) = self.reused_node(path, kind) {
1666
            return n;
1667
        }
1668
        match &self.node_seed {
1669
            Some(seed) => seeded_node(seed, path, kind),
1670
            None => NodeId::random(),
1671
        }
1672
    }
1673
1674
    fn reused_node(&self, path: &str, kind: NodeKind) -> Option<NodeId> {
1675
        self.reuse
1676
            .get(path)
1677
            .filter(|(_, k)| *k == kind)
1678
            .map(|(n, _)| *n)
1679
    }
1680
1681
    /// A dead directory last placed at (`parent`, `name`) in the base.
1682
    fn revivable_dir(
1683
        &mut self,
1684
        parent: NodeId,
1685
        name: &str,
1686
    ) -> Option<(NodeId, crate::tree::OpKey)> {
1687
        let base = self.base;
1688
        self.dead_dirs
1689
            .get_or_insert_with(|| base.tree().dead_dirs())
1690
            .get(&(parent, name.to_string()))
1691
            .copied()
1692
    }
1693
1694
    fn ensure_dir(&mut self, path: &str) -> NodeId {
1695
        if let Some(n) = self.dir_nodes.get(path) {
1696
            return *n;
1697
        }
1698
        let mut parent = NodeId::ROOT;
1699
        let mut prefix = String::new();
1700
        for comp in path.split('/') {
1701
            if !prefix.is_empty() {
1702
                prefix.push('/');
1703
            }
1704
            prefix.push_str(comp);
1705
            let known = self.dir_nodes.get(&prefix).copied();
1706
            let revive = match known {
1707
                Some(_) => None,
1708
                None if self.node_seed.is_some() => self.revivable_dir(parent, comp),
1709
                None => None,
1710
            };
1711
            parent = match (known, revive) {
1712
                (Some(n), _) => n,
1713
                (None, Some((node, old))) => {
1714
                    // Git has no identity for a directory: one that comes
1715
                    // back where it was is the same directory, brought back
1716
                    // with a move, so lines of history that placed files in
1717
                    // it before and after agree (oxygen#30).
1718
                    self.tree_ops.push(TreeOp::Move {
1719
                        node,
1720
                        old: OpRef {
1721
                            change: old.0,
1722
                            index: old.1,
1723
                        },
1724
                        parent,
1725
                        name: comp.to_string(),
1726
                    });
1727
                    self.dir_nodes.insert(prefix.clone(), node);
1728
                    node
1729
                }
1730
                (None, None) => {
1731
                    let node = self.new_node(&prefix, NodeKind::Dir);
1732
                    self.tree_ops.push(TreeOp::AddNode {
1733
                        node,
1734
                        kind: NodeKind::Dir,
1735
                        mode: Mode::default(),
1736
                        parent,
1737
                        name: comp.to_string(),
1738
                    });
1739
                    self.dir_nodes.insert(prefix.clone(), node);
1740
                    node
1741
                }
1742
            };
1743
        }
1744
        parent
1745
    }
1746
1747
    fn add_path(&mut self, repo: &Repo, path: &str, e: &FsEntry) -> Result<()> {
1748
        let (dir, name) = split_path(path);
1749
        let parent = self.ensure_dir(dir);
1750
        let node = self.new_node(path, e.kind);
1751
        let opaque = self.opaque_for(path, e);
1752
        let nocompress = self.attrs.lookup(path).nocompress;
1753
        self.tree_ops.push(TreeOp::AddNode {
1754
            node,
1755
            kind: e.kind,
1756
            mode: Mode {
1757
                exec: e.exec,
1758
                opaque,
1759
            },
1760
            parent,
1761
            name: name.to_string(),
1762
        });
1763
        if opaque {
1764
            let blob = self.blob_of(repo, path, e, nocompress)?;
1765
            self.edits.push(Edit::Replace {
1766
                node,
1767
                old: None,
1768
                new: Some(blob),
1769
            });
1770
        } else if !e.content.is_empty() {
1771
            let content = self.stored_text(path, &e.content);
1772
            self.edits.push(Edit::Insert {
1773
                node,
1774
                after: crate::objects::AtomRef::Start,
1775
                before: crate::objects::AtomRef::End,
1776
                lines: crate::lines::Lines::split(&content),
1777
            });
1778
        }
1779
        self.statuses.push(PathStatus {
1780
            path: path.to_string(),
1781
            status: ChangeStatus::Added,
1782
        });
1783
        Ok(())
1784
    }
1785
1786
    /// Move the node at `old` to `new` and apply `e`'s content to it.
1787
    fn move_path(
1788
        &mut self,
1789
        repo: &Repo,
1790
        old: &str,
1791
        new: &str,
1792
        e: &FsEntry,
1793
        expected: &crate::state::FileState,
1794
    ) -> Result<()> {
1795
        let entry = &self.base_snapshot.tree.entries[old];
1796
        let (dir, name) = split_path(new);
1797
        let parent = self.ensure_dir(dir);
1798
        self.tree_ops.push(TreeOp::Move {
1799
            node: expected.node,
1800
            old: op_ref(entry.placement),
1801
            parent,
1802
            name: name.to_string(),
1803
        });
1804
        self.update_path(repo, old, e, expected)?;
1805
        // update_path reports under the old path; the rename is what the user sees.
1806
        self.statuses.retain(|s| s.path != old);
1807
        self.statuses.push(PathStatus {
1808
            path: new.to_string(),
1809
            status: ChangeStatus::Renamed,
1810
        });
1811
        Ok(())
1812
    }
1813
1814
    /// For a Git import: a node the commit keeps is in one place, the one
1815
    /// its tree names, so any other live placement it has in the base goes;
1816
    /// and a node the tree cannot show at all (an orphan) goes too. Such a
1817
    /// placement is out of sight, under a directory another line of history
1818
    /// removed, where no diff of the tree would ever reach it (oxygen#30).
1819
    fn retire_stray_placements(&mut self) {
1820
        let mut retired: HashSet<(ChangeHash, u32)> = HashSet::new();
1821
        let mut placed: BTreeSet<NodeId> = BTreeSet::new();
1822
        for op in &self.tree_ops {
1823
            match op {
1824
                TreeOp::Move { node, old, .. } => {
1825
                    retired.insert((old.change, old.index));
1826
                    placed.insert(*node);
1827
                }
1828
                TreeOp::RemoveNode { placement, .. } => {
1829
                    retired.insert((placement.change, placement.index));
1830
                }
1831
                TreeOp::AddNode { .. } | TreeOp::SetMode { .. } => {}
1832
            }
1833
        }
1834
        // Nodes kept where they were: what the base's tree view shows and
1835
        // this change neither moves nor removes.
1836
        let mut kept: HashMap<NodeId, (ChangeHash, u32)> = HashMap::new();
1837
        for e in self.base_snapshot.tree.entries.values() {
1838
            if !retired.contains(&e.placement) {
1839
                kept.insert(e.node, e.placement);
1840
            }
1841
        }
1842
        // Only a node with several live placements can have a stray one,
1843
        // and the tree view names each as a conflict.
1844
        let multi: BTreeSet<NodeId> = self
1845
            .base_snapshot
1846
            .tree
1847
            .conflicts
1848
            .iter()
1849
            .filter_map(|c| match c {
1850
                crate::tree::TreeConflict::MultiPlacement { node, .. } => Some(*node),
1851
                _ => None,
1852
            })
1853
            .collect();
1854
        let mut extra = Vec::new();
1855
        // A node whose only placements are under a directory another line
1856
        // removed (an orphan) is nowhere the tree can show, and Git's tree
1857
        // has no such path: it goes.
1858
        for c in &self.base_snapshot.tree.conflicts {
1859
            let crate::tree::TreeConflict::Orphan { node, .. } = c else {
1860
                continue;
1861
            };
1862
            if kept.contains_key(node) || placed.contains(node) {
1863
                continue;
1864
            }
1865
            for (k, _) in self.base.tree().live_placements(node) {
1866
                if retired.insert(k) {
1867
                    extra.push(TreeOp::RemoveNode {
1868
                        node: *node,
1869
                        placement: op_ref(k),
1870
                    });
1871
                }
1872
            }
1873
        }
1874
        for node in placed
1875
            .iter()
1876
            .chain(multi.iter().filter(|n| kept.contains_key(*n)))
1877
        {
1878
            for (k, _) in self.base.tree().live_placements(node) {
1879
                if retired.contains(&k) || kept.get(node) == Some(&k) {
1880
                    continue;
1881
                }
1882
                retired.insert(k);
1883
                extra.push(TreeOp::RemoveNode {
1884
                    node: *node,
1885
                    placement: op_ref(k),
1886
                });
1887
            }
1888
        }
1889
        if !extra.is_empty() {
1890
            self.resolves = true;
1891
            self.tree_ops.extend(extra);
1892
        }
1893
    }
1894
1895
    fn remove_path(&mut self, path: &str, expected: &crate::state::FileState) {
1896
        let entry = &self.base_snapshot.tree.entries[path];
1897
        self.tree_ops.push(TreeOp::RemoveNode {
1898
            node: expected.node,
1899
            placement: op_ref(entry.placement),
1900
        });
1901
        if path.contains(".oxy-conflict-") || expected.is_conflicted() {
1902
            self.resolves = true;
1903
        }
1904
        self.statuses.push(PathStatus {
1905
            path: path.to_string(),
1906
            status: ChangeStatus::Removed,
1907
        });
1908
    }
1909
1910
    fn update_path(
1911
        &mut self,
1912
        repo: &Repo,
1913
        path: &str,
1914
        e: &FsEntry,
1915
        expected: &crate::state::FileState,
1916
    ) -> Result<()> {
1917
        if expected.kind != e.kind {
1918
            self.remove_path(path, expected);
1919
            self.statuses.pop();
1920
            self.add_path(repo, path, e)?;
1921
            self.statuses.pop();
1922
            self.statuses.push(PathStatus {
1923
                path: path.to_string(),
1924
                status: ChangeStatus::Modified,
1925
            });
1926
            return Ok(());
1927
        }
1928
        let entry = &self.base_snapshot.tree.entries[path];
1929
        let node = expected.node;
1930
        let mode_atom = entry.mode_atom.map(op_ref);
1931
        if e.unchanged {
1932
            // Known equal to the base's unconflicted rendering (spec
1933
            // §12.3); only the executable bit can differ.
1934
            if e.exec != expected.mode.exec {
1935
                if let Some(old) = mode_atom {
1936
                    self.tree_ops.push(TreeOp::SetMode {
1937
                        node,
1938
                        old,
1939
                        mode: Mode {
1940
                            exec: e.exec,
1941
                            opaque: false,
1942
                        },
1943
                    });
1944
                    self.statuses.push(PathStatus {
1945
                        path: path.to_string(),
1946
                        status: ChangeStatus::ModeChanged,
1947
                    });
1948
                }
1949
            }
1950
            return Ok(());
1951
        }
1952
        let mut status: Option<ChangeStatus> = None;
1953
        let wants_opaque = self.opaque_for(path, e);
1954
        let nocompress = self.attrs.lookup(path).nocompress;
1955
        let disk_text = self.stored_text(path, &e.content);
1956
        match &expected.content {
1957
            FileContent::Dir => {}
1958
            FileContent::Text {
1959
                bytes,
1960
                materialized,
1961
            } => {
1962
                if materialized.is_conflicted() {
1963
                    if bytes == &disk_text {
1964
                        return Ok(());
1965
                    }
1966
                    if has_conflict_markers(&e.content) {
1967
                        self.statuses.push(PathStatus {
1968
                            path: path.to_string(),
1969
                            status: ChangeStatus::ConflictEdited,
1970
                        });
1971
                        return Ok(());
1972
                    }
1973
                    // Resolution (spec §9.6): diff against the unconflicted lines
1974
                    // with each region as a gap, then retire every region atom.
1975
                    // Whatever the author kept from a region is re-inserted as
1976
                    // new atoms, which leaves the graph totally ordered.
1977
                    let regions = self.base.conflict_regions(&node);
1978
                    let mut edits = text_edits(node, &regions.plain, &disk_text);
1979
                    if !regions.region_atoms.is_empty() {
1980
                        edits.insert(
1981
                            0,
1982
                            Edit::Delete {
1983
                                node,
1984
                                atoms: ranges(&regions.region_atoms),
1985
                            },
1986
                        );
1987
                    }
1988
                    self.edits.extend(edits);
1989
                    self.contributors.extend(regions.contributors);
1990
                    self.resolves = true;
1991
                    if e.exec != expected.mode.exec {
1992
                        if let Some(old) = mode_atom {
1993
                            self.tree_ops.push(TreeOp::SetMode {
1994
                                node,
1995
                                old,
1996
                                mode: Mode {
1997
                                    exec: e.exec,
1998
                                    opaque: false,
1999
                                },
2000
                            });
2001
                        }
2002
                    }
2003
                    self.statuses.push(PathStatus {
2004
                        path: path.to_string(),
2005
                        status: ChangeStatus::Resolved,
2006
                    });
2007
                    return Ok(());
2008
                }
2009
                if wants_opaque {
2010
                    // Text → opaque (spec §7.5), by content or by attribute.
2011
                    if let Some(old) = mode_atom {
2012
                        self.tree_ops.push(TreeOp::SetMode {
2013
                            node,
2014
                            old,
2015
                            mode: Mode {
2016
                                exec: e.exec,
2017
                                opaque: true,
2018
                            },
2019
                        });
2020
                    }
2021
                    let live: Vec<_> = repo_live_keys(self.base, &node);
2022
                    if !live.is_empty() {
2023
                        self.edits.push(Edit::Delete {
2024
                            node,
2025
                            atoms: ranges(&live),
2026
                        });
2027
                    }
2028
                    let blob = self.blob_of(repo, path, e, nocompress)?;
2029
                    self.edits.push(Edit::Replace {
2030
                        node,
2031
                        old: None,
2032
                        new: Some(blob),
2033
                    });
2034
                    status = Some(ChangeStatus::Modified);
2035
                } else if bytes != &disk_text {
2036
                    let mut laps = crate::timing::Laps::start();
2037
                    // The base's rendering holds its live atoms in order,
2038
                    // one per line (it is not conflicted here).
2039
                    let keys = materialized.live_atoms();
2040
                    let lines = crate::diff::split_lines(bytes);
2041
                    let edits = if keys.len() == lines.len() {
2042
                        crate::diff::text_edits_of(node, &keys, &lines, &disk_text)
2043
                    } else {
2044
                        text_edits(node, &self.base.live_lines(&node), &disk_text)
2045
                    };
2046
                    laps.lap("build: text diff");
2047
                    if !edits.is_empty() {
2048
                        self.edits.extend(edits);
2049
                        status = Some(ChangeStatus::Modified);
2050
                    }
2051
                }
2052
                let switched_to_opaque = wants_opaque;
2053
                if !switched_to_opaque && e.exec != expected.mode.exec {
2054
                    if let Some(old) = mode_atom {
2055
                        self.tree_ops.push(TreeOp::SetMode {
2056
                            node,
2057
                            old,
2058
                            mode: Mode {
2059
                                exec: e.exec,
2060
                                opaque: false,
2061
                            },
2062
                        });
2063
                        status.get_or_insert(ChangeStatus::ModeChanged);
2064
                    }
2065
                }
2066
            }
2067
            FileContent::Opaque { blobs } => {
2068
                let new_ref = e.blob.unwrap_or_else(|| Repo::blob_ref(&e.content));
2069
                if e.kind == NodeKind::File && wants_opaque {
2070
                    // Unchanged or replaced, the file stays opaque: remember its blob.
2071
                    self.blobs.insert(path.to_string(), new_ref);
2072
                }
2073
                if blobs.len() > 1 && self.resolve.contains(path) && e.kind == expected.kind {
2074
                    // Settle the replace conflict (spec §9.3): replace every
2075
                    // live candidate with the chosen blob, depending on each
2076
                    // change that made one live, so all are superseded.
2077
                    let chosen = self.blob_of(repo, path, e, nocompress)?;
2078
                    for b in blobs {
2079
                        self.edits.push(Edit::Replace {
2080
                            node,
2081
                            old: Some(*b),
2082
                            new: Some(chosen),
2083
                        });
2084
                    }
2085
                    self.contributors
2086
                        .extend(self.base.blob_contributors(&node, blobs));
2087
                    self.resolves = true;
2088
                    self.statuses.push(PathStatus {
2089
                        path: path.to_string(),
2090
                        status: ChangeStatus::Resolved,
2091
                    });
2092
                    return Ok(());
2093
                }
2094
                if blobs.len() > 1 {
2095
                    if !blobs.contains(&new_ref) {
2096
                        self.statuses.push(PathStatus {
2097
                            path: path.to_string(),
2098
                            status: ChangeStatus::ConflictEdited,
2099
                        });
2100
                    }
2101
                    return Ok(());
2102
                }
2103
                let current = blobs.first().copied();
2104
                if current != Some(new_ref) {
2105
                    if e.kind == NodeKind::File && !wants_opaque {
2106
                        // Opaque → text (spec §7.5).
2107
                        if let Some(old) = mode_atom {
2108
                            self.tree_ops.push(TreeOp::SetMode {
2109
                                node,
2110
                                old,
2111
                                mode: Mode {
2112
                                    exec: e.exec,
2113
                                    opaque: false,
2114
                                },
2115
                            });
2116
                        }
2117
                        self.edits.push(Edit::Replace {
2118
                            node,
2119
                            old: current,
2120
                            new: None,
2121
                        });
2122
                        if !e.content.is_empty() {
2123
                            self.edits.push(Edit::Insert {
2124
                                node,
2125
                                after: crate::objects::AtomRef::Start,
2126
                                before: crate::objects::AtomRef::End,
2127
                                lines: crate::lines::Lines::split(&e.content),
2128
                            });
2129
                        }
2130
                    } else {
2131
                        let blob = self.blob_of(repo, path, e, nocompress)?;
2132
                        self.edits.push(Edit::Replace {
2133
                            node,
2134
                            old: current,
2135
                            new: Some(blob),
2136
                        });
2137
                    }
2138
                    status = Some(ChangeStatus::Modified);
2139
                } else if e.kind == NodeKind::File && e.exec != expected.mode.exec {
2140
                    if let Some(old) = mode_atom {
2141
                        self.tree_ops.push(TreeOp::SetMode {
2142
                            node,
2143
                            old,
2144
                            mode: Mode {
2145
                                exec: e.exec,
2146
                                opaque: true,
2147
                            },
2148
                        });
2149
                        status = Some(ChangeStatus::ModeChanged);
2150
                    }
2151
                }
2152
            }
2153
        }
2154
        if let Some(s) = status {
2155
            self.statuses.push(PathStatus {
2156
                path: path.to_string(),
2157
                status: s,
2158
            });
2159
        }
2160
        Ok(())
2161
    }
2162
}
2163
2164
fn repo_live_keys(base: &State, node: &NodeId) -> Vec<crate::graph::AtomKey> {
2165
    base.live_lines(node).into_iter().map(|(k, _)| k).collect()
2166
}
2167
2168
/// The changes a change's scope references (spec §8.1): introducers of every
2169
/// atom, placement, and mode it touches, and of every node it operates on.
2170
pub fn referenced_changes(change: &Change, base: &State) -> BTreeSet<ChangeHash> {
2171
    let mut out = BTreeSet::new();
2172
    let opref = |r: &OpRef, out: &mut BTreeSet<ChangeHash>| {
2173
        if !r.change.is_zero() {
2174
            out.insert(r.change);
2175
        }
2176
    };
2177
    let mut nodes: Vec<NodeId> = Vec::new();
2178
    for op in &change.tree_ops {
2179
        match op {
2180
            TreeOp::AddNode { parent, .. } => nodes.push(*parent),
2181
            TreeOp::RemoveNode { node, placement } => {
2182
                nodes.push(*node);
2183
                opref(placement, &mut out);
2184
            }
2185
            TreeOp::Move {
2186
                node, old, parent, ..
2187
            } => {
2188
                nodes.push(*node);
2189
                nodes.push(*parent);
2190
                opref(old, &mut out);
2191
            }
2192
            TreeOp::SetMode { node, old, .. } => {
2193
                nodes.push(*node);
2194
                opref(old, &mut out);
2195
            }
2196
        }
2197
    }
2198
    for e in &change.edits {
2199
        nodes.push(e.node());
2200
        match e {
2201
            Edit::Insert { after, before, .. } => {
2202
                for r in [after, before] {
2203
                    if let crate::objects::AtomRef::Atom { change, .. } = r {
2204
                        if !change.is_zero() {
2205
                            out.insert(*change);
2206
                        }
2207
                    }
2208
                }
2209
            }
2210
            Edit::Delete { atoms, .. } => {
2211
                // Deleting an atom also depends on whoever inserted the live
2212
                // atoms right after it: the author saw those insertions, and
2213
                // without the dependency spec §9.1 would call the deletion
2214
                // concurrent with them (a delete/insert conflict).
2215
                let graph = base.file(&e.node());
2216
                for r in atoms {
2217
                    if !r.change.is_zero() {
2218
                        out.insert(r.change);
2219
                    }
2220
                    if let Some(g) = graph {
2221
                        for i in r.from..r.to {
2222
                            out.extend(
2223
                                g.live_successor_changes(&(r.change, i))
2224
                                    .into_iter()
2225
                                    .filter(|c| !c.is_zero()),
2226
                            );
2227
                        }
2228
                    }
2229
                }
2230
            }
2231
            // Replacing a blob depends on the change that made it current,
2232
            // as deleting a line depends on the line's introducer.
2233
            Edit::Replace {
2234
                node,
2235
                old: Some(old),
2236
                ..
2237
            } => {
2238
                out.extend(
2239
                    base.live_replaces(node)
2240
                        .into_iter()
2241
                        .filter(|(c, b)| b == old && !c.is_zero())
2242
                        .map(|(c, _)| c),
2243
                );
2244
            }
2245
            Edit::Replace { .. } => {}
2246
        }
2247
    }
2248
    for n in nodes {
2249
        if let Some(h) = base.tree().introducer(&n) {
2250
            out.insert(h);
2251
        }
2252
    }
2253
    out
2254
}
2255
2256
/// Paths of the nodes a change adds on top of `base_snapshot`.
2257
pub fn added_node_paths(
2258
    change: &Change,
2259
    base_snapshot: &Snapshot,
2260
) -> HashMap<String, (NodeId, NodeKind)> {
2261
    let by_node = base_snapshot.tree.by_node();
2262
    let mut new_names: HashMap<NodeId, (NodeId, String, NodeKind)> = HashMap::new();
2263
    for op in &change.tree_ops {
2264
        if let TreeOp::AddNode {
2265
            node,
2266
            parent,
2267
            name,
2268
            kind,
2269
            ..
2270
        } = op
2271
        {
2272
            new_names.insert(*node, (*parent, name.clone(), *kind));
2273
        }
2274
    }
2275
    let mut out = HashMap::new();
2276
    for (node, (_, _, kind)) in &new_names {
2277
        if let Some(path) = path_of_node(node, &by_node, &new_names) {
2278
            out.insert(path, (*node, *kind));
2279
        }
2280
    }
2281
    out
2282
}
2283
2284
fn path_of_node(
2285
    n: &NodeId,
2286
    by_node: &HashMap<NodeId, &crate::tree::TreeEntry>,
2287
    new_names: &HashMap<NodeId, (NodeId, String, NodeKind)>,
2288
) -> Option<String> {
2289
    if let Some(e) = by_node.get(n) {
2290
        return Some(e.path.clone());
2291
    }
2292
    let mut parts = Vec::new();
2293
    let mut cur = *n;
2294
    loop {
2295
        if cur.is_root() {
2296
            break;
2297
        }
2298
        if let Some(e) = by_node.get(&cur) {
2299
            if !e.path.is_empty() {
2300
                parts.push(e.path.clone());
2301
            }
2302
            break;
2303
        }
2304
        let (parent, name, _) = new_names.get(&cur)?;
2305
        parts.push(name.clone());
2306
        cur = *parent;
2307
    }
2308
    parts.reverse();
2309
    Some(parts.join("/"))
2310
}
2311
2312
/// Render a change's operations with line content, using `base` for deleted lines.
2313
pub fn render_change(change: &Change, base: &State, base_snapshot: &Snapshot) -> String {
2314
    let by_node = base_snapshot.tree.by_node();
2315
    let mut new_names: HashMap<NodeId, (NodeId, String, NodeKind)> = HashMap::new();
2316
    for op in &change.tree_ops {
2317
        if let TreeOp::AddNode {
2318
            node,
2319
            parent,
2320
            name,
2321
            kind,
2322
            ..
2323
        } = op
2324
        {
2325
            new_names.insert(*node, (*parent, name.clone(), *kind));
2326
        }
2327
    }
2328
    let path_of = |n: &NodeId| -> String {
2329
        path_of_node(n, &by_node, &new_names).unwrap_or_else(|| format!("<node {}>", n.short(8)))
2330
    };
2331
2332
    let mut out = String::new();
2333
    for op in &change.tree_ops {
2334
        match op {
2335
            TreeOp::AddNode {
2336
                node, kind, mode, ..
2337
            } => {
2338
                out.push_str(&format!(
2339
                    "A {} ({:?}{}{})\n",
2340
                    path_of(node),
2341
                    kind,
2342
                    if mode.exec { ", exec" } else { "" },
2343
                    if mode.opaque { ", opaque" } else { "" }
2344
                ));
2345
            }
2346
            TreeOp::RemoveNode { node, .. } => out.push_str(&format!("D {}\n", path_of(node))),
2347
            TreeOp::Move { node, name, .. } => {
2348
                out.push_str(&format!("R {} -> {}\n", path_of(node), name))
2349
            }
2350
            TreeOp::SetMode { node, mode, .. } => {
2351
                out.push_str(&format!(
2352
                    "M {} mode: exec={} opaque={}\n",
2353
                    path_of(node),
2354
                    mode.exec,
2355
                    mode.opaque
2356
                ));
2357
            }
2358
        }
2359
    }
2360
    let mut last_node: Option<NodeId> = None;
2361
    for e in &change.edits {
2362
        let n = e.node();
2363
        if last_node != Some(n) {
2364
            out.push_str(&format!("--- {}\n", path_of(&n)));
2365
            last_node = Some(n);
2366
        }
2367
        match e {
2368
            Edit::Insert { lines, .. } => {
2369
                for l in lines.iter() {
2370
                    out.push('+');
2371
                    out.push_str(&String::from_utf8_lossy(l));
2372
                    if !l.ends_with(b"\n") {
2373
                        out.push('\n');
2374
                    }
2375
                }
2376
            }
2377
            Edit::Delete { atoms, .. } => {
2378
                for r in atoms {
2379
                    for i in r.from..r.to {
2380
                        let content = base
2381
                            .file(&n)
2382
                            .and_then(|g| g.content(&(r.change, i)))
2383
                            .unwrap_or(b"<unknown>\n");
2384
                        out.push('-');
2385
                        out.push_str(&String::from_utf8_lossy(content));
2386
                        if !content.ends_with(b"\n") {
2387
                            out.push('\n');
2388
                        }
2389
                    }
2390
                }
2391
            }
2392
            Edit::Replace { old, new, .. } => {
2393
                out.push_str(&format!(
2394
                    "  opaque content {} -> {}\n",
2395
                    old.map(|o| o.short(12)).unwrap_or_else(|| "none".into()),
2396
                    new.map(|o| o.short(12)).unwrap_or_else(|| "none".into())
2397
                ));
2398
            }
2399
        }
2400
    }
2401
    out
2402
}
2403
2404
/// Pair removed files with added files of the same kind whose contents are
2405
/// at least `RENAME_THRESHOLD` percent alike, best matches first. Beyond
2406
/// `RENAME_LIMIT` candidate pairs only identical contents are paired.
2407
const RENAME_THRESHOLD: u32 = 50;
2408
const RENAME_LIMIT: usize = 10_000;
2409
2410
/// What a Git import adds to building a change: the seed its new nodes'
2411
/// identifiers derive from, and, when it builds from part of the tree,
2412
/// whether the new tree has anything under a directory.
2413
struct Import<'a> {
2414
    seed: [u8; 32],
2415
    dir_needed: Option<&'a dyn Fn(&str) -> bool>,
2416
}
2417
2418
fn detect_renames(
2419
    base_snapshot: &Snapshot,
2420
    fs_entries: &BTreeMap<String, FsEntry>,
2421
    in_scope: impl Fn(&str) -> bool,
2422
) -> Vec<(String, String)> {
2423
    let removed: Vec<(&String, &crate::state::FileState)> = base_snapshot
2424
        .files
2425
        .iter()
2426
        .filter(|(p, f)| {
2427
            f.kind != NodeKind::Dir
2428
                && !fs_entries.contains_key(*p)
2429
                && in_scope(p)
2430
                && !f.is_conflicted()
2431
        })
2432
        .collect();
2433
    let added: Vec<(&String, &FsEntry)> = fs_entries
2434
        .iter()
2435
        .filter(|(p, e)| e.kind != NodeKind::Dir && !base_snapshot.files.contains_key(*p))
2436
        .collect();
2437
    if removed.is_empty() || added.is_empty() {
2438
        return vec![];
2439
    }
2440
    let exact_only = removed.len() * added.len() > RENAME_LIMIT;
2441
    let old_content = |f: &crate::state::FileState| -> Option<Vec<u8>> {
2442
        match &f.content {
2443
            FileContent::Text { bytes, .. } => Some(bytes.clone()),
2444
            _ => None,
2445
        }
2446
    };
2447
    let mut scored: Vec<(u32, usize, usize)> = Vec::new();
2448
    for (ri, (_, f)) in removed.iter().enumerate() {
2449
        let old = old_content(f);
2450
        let old_blob = match &f.content {
2451
            FileContent::Opaque { blobs } if blobs.len() == 1 => Some(blobs[0]),
2452
            _ => None,
2453
        };
2454
        for (ai, (_, e)) in added.iter().enumerate() {
2455
            if e.kind != f.kind {
2456
                continue;
2457
            }
2458
            let score = match (&old, old_blob) {
2459
                (Some(o), _) => {
2460
                    if exact_only {
2461
                        if *o == e.content {
2462
                            100
2463
                        } else {
2464
                            0
2465
                        }
2466
                    } else {
2467
                        similarity(o, &e.content)
2468
                    }
2469
                }
2470
                (None, Some(b)) if e.blob.unwrap_or_else(|| Repo::blob_ref(&e.content)) == b => 100,
2471
                _ => 0,
2472
            };
2473
            if score >= RENAME_THRESHOLD {
2474
                scored.push((score, ri, ai));
2475
            }
2476
        }
2477
    }
2478
    scored.sort_by(|a, b| {
2479
        b.0.cmp(&a.0)
2480
            .then(removed[a.1].0.cmp(removed[b.1].0))
2481
            .then(added[a.2].0.cmp(added[b.2].0))
2482
    });
2483
    let mut used_r = vec![false; removed.len()];
2484
    let mut used_a = vec![false; added.len()];
2485
    let mut out = Vec::new();
2486
    for (_, ri, ai) in scored {
2487
        if used_r[ri] || used_a[ai] {
2488
            continue;
2489
        }
2490
        used_r[ri] = true;
2491
        used_a[ai] = true;
2492
        out.push((removed[ri].0.clone(), added[ai].0.clone()));
2493
    }
2494
    out
2495
}
2496
2497
/// Percentage of the larger file's bytes found in lines the two share
2498
/// (multiset intersection of lines), like Git's similarity index.
2499
pub fn similarity(a: &[u8], b: &[u8]) -> u32 {
2500
    if a == b {
2501
        return 100;
2502
    }
2503
    if a.is_empty() || b.is_empty() {
2504
        return 0;
2505
    }
2506
    let mut counts: HashMap<&[u8], usize> = HashMap::new();
2507
    for l in split_lines(a) {
2508
        *counts.entry(l).or_default() += 1;
2509
    }
2510
    let mut shared = 0usize;
2511
    for l in split_lines(b) {
2512
        if let Some(n) = counts.get_mut(l) {
2513
            if *n > 0 {
2514
                *n -= 1;
2515
                shared += l.len();
2516
            }
2517
        }
2518
    }
2519
    (shared * 100 / a.len().max(b.len())) as u32
2520
}