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