OXYGENHUB
# 141b1fb2ebe9 oxygen / crates / oxy-core / src / repo / snapshot.rs
72.3 KiB · Rust · last changed Unbound hosted repositories adopt the first pusher's id 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 fs_entries = self.walk_working_copy_with(None, &Self::tracked_kinds(base_snapshot))?;
77
        self.build_from_entries(base, base_snapshot, reuse, &fs_entries)
78
    }
79
80
    /// Like `build_against`, for files given in memory (imports).
81
    pub(crate) fn build_from_entries(
82
        &self,
83
        base: &State,
84
        base_snapshot: &Snapshot,
85
        reuse: HashMap<String, (NodeId, NodeKind)>,
86
        fs_entries: &BTreeMap<String, FsEntry>,
87
    ) -> Result<BuiltChange> {
88
        // Attributes come from the files being committed, so a new
89
        // `.oxyattributes` applies to the same change that adds it.
90
        let attrs = crate::attributes::Attributes::from_files(
91
            fs_entries
92
                .iter()
93
                .filter(|(p, _)| p.as_str() == ".oxyattributes" || p.ends_with("/.oxyattributes"))
94
                .map(|(p, e)| (p.as_str(), e.content.as_slice())),
95
        );
96
        let mut b = ChangeBuilder::new(base, base_snapshot, reuse).with_attributes(attrs);
97
        // Rename detection (spec §7.1, §23): a removed file and an added file
98
        // of the same kind whose contents are at least half alike become one
99
        // move of the same node, so identity survives across the rename.
100
        let renames = detect_renames(base_snapshot, fs_entries, |p| self.in_scope(p));
101
        let renamed_from: HashMap<&str, &str> = renames
102
            .iter()
103
            .map(|(old, new)| (new.as_str(), old.as_str()))
104
            .collect();
105
        let renamed_to: HashMap<&str, &str> = renames
106
            .iter()
107
            .map(|(old, new)| (old.as_str(), new.as_str()))
108
            .collect();
109
        for (path, fs_entry) in fs_entries {
110
            match base_snapshot.files.get(path) {
111
                None => match renamed_from.get(path.as_str()) {
112
                    Some(old) => {
113
                        b.move_path(self, old, path, fs_entry, &base_snapshot.files[*old])?
114
                    }
115
                    None => b.add_path(self, path, fs_entry)?,
116
                },
117
                Some(expected) => b.update_path(self, path, fs_entry, expected)?,
118
            }
119
        }
120
        for (path, expected) in &base_snapshot.files {
121
            if fs_entries.contains_key(path)
122
                || !self.in_scope(path)
123
                || renamed_to.contains_key(path.as_str())
124
            {
125
                continue;
126
            }
127
            // A directory stays while anything under it exists or is out of scope.
128
            let still_needed = expected.kind == NodeKind::Dir
129
                && (fs_entries
130
                    .keys()
131
                    .any(|p| p.starts_with(&format!("{path}/")))
132
                    || base_snapshot
133
                        .files
134
                        .keys()
135
                        .any(|p| p.starts_with(&format!("{path}/")) && !self.in_scope(p)));
136
            if !still_needed {
137
                b.remove_path(path, expected);
138
            }
139
        }
140
        let mut statuses = b.statuses;
141
        statuses.sort_by(|a, b| a.path.cmp(&b.path));
142
        Ok(BuiltChange {
143
            tree_ops: b.tree_ops,
144
            edits: b.edits,
145
            contributors: b.contributors.into_iter().collect(),
146
            resolves: b.resolves,
147
            statuses,
148
            blobs: b.blobs,
149
        })
150
    }
151
152
    /// Store a change and, when `core.sign = change` and we are its author,
153
    /// sign it. A rewritten change by another author is stored unsigned: only
154
    /// its author (or a delegate) can vouch for it.
155
    pub(crate) fn store_signed(&self, change: &Change) -> Result<ChangeHash> {
156
        let ours = change.author == self.author();
157
        if self.config.sign_changes && ours && self.secret_key()?.is_none() {
158
            return fail("core.sign is \"change\" but no secret key is available for author.key");
159
        }
160
        let hash = self.store.put_change(change)?;
161
        if self.config.sign_changes && ours {
162
            self.sign_change(&hash)?;
163
        }
164
        Ok(hash)
165
    }
166
167
    /// Snapshot the working copy into the working-copy change (spec §12.3).
168
    pub fn snapshot(&self, command: &str) -> Result<SnapshotResult> {
169
        let _lock = self.lock_snapshot()?;
170
        let batch = self.store.begin_batch()?;
171
        let result = self.snapshot_locked(command);
172
        batch.finish()?;
173
        result
174
    }
175
176
    fn snapshot_locked(&self, command: &str) -> Result<SnapshotResult> {
177
        let (op_ref, op) = self.head_op()?;
178
        let (old_hash, old_wc) = self.working_copy()?;
179
        let base = self.load_state(&old_wc.deps)?;
180
        let base_snapshot = base.materialize();
181
182
        // Reuse the NodeIds the previous working-copy version assigned to new
183
        // paths, so an unchanged working copy hashes identically (spec §12.3).
184
        let reuse = added_node_paths(&old_wc, &base_snapshot);
185
        // The last manifest lets unchanged opaque files go unread.
186
        let manifest = self.read_manifest()?.map(|(_, _, m)| m);
187
        let fs_entries =
188
            self.walk_working_copy_with(manifest.as_ref(), &Self::tracked_kinds(&base_snapshot))?;
189
        let built = self.build_from_entries(&base, &base_snapshot, reuse, &fs_entries)?;
190
191
        let mut wc = Change {
192
            change_id: old_wc.change_id,
193
            deps: vec![],
194
            author: self.author(),
195
            hlc: old_wc.hlc,
196
            message: old_wc.message.clone(),
197
            tree_ops: built.tree_ops,
198
            edits: built.edits,
199
            kind: ChangeKind::WorkingCopy,
200
        };
201
        let base_heads = base.maximal(&old_wc.deps);
202
        let mut deps: BTreeSet<ChangeHash> = base_heads.into_iter().collect();
203
        deps.extend(referenced_changes(&wc, &base));
204
        deps.extend(built.contributors.iter().copied());
205
        wc.deps = deps.into_iter().collect();
206
        wc.normalize();
207
        let resolves = built.resolves;
208
        let contributors = built.contributors;
209
        let statuses = built.statuses;
210
        // Empty snapshot: hash the candidate before storing; only record an op on change.
211
        let new_hash = wc.hash();
212
        let changed = new_hash != old_hash;
213
        if changed {
214
            self.store.put_change(&wc)?;
215
            let mut view = op.view.clone();
216
            view.workspaces.insert(self.workspace, new_hash);
217
            self.record_op(&[op_ref], &format!("{command}{SNAPSHOT_SUFFIX}"), view)?;
218
        }
219
        // The prompt compares against this without recording anything.
220
        self.write_manifest_entries(
221
            base_snapshot.is_conflicted(),
222
            !wc.tree_ops.is_empty() || !wc.edits.is_empty(),
223
            &fs_entries,
224
            &built.blobs,
225
        )?;
226
        Ok(SnapshotResult {
227
            wc_hash: new_hash,
228
            wc,
229
            base,
230
            base_snapshot,
231
            statuses,
232
            changed,
233
            resolves,
234
            contributors,
235
        })
236
    }
237
238
    /// `oxy status --json` (spec §9.5): the changed paths and every conflict
239
    /// of the working copy's base with its kind, path, and contributing
240
    /// ChangeIds.
241
    pub fn status_json(&self, snap: &SnapshotResult) -> Result<String> {
242
        let heads = self.bookmark_heads()?;
243
        let base_snapshot = &snap.base_snapshot;
244
        let by_node = base_snapshot.tree.by_node();
245
        let path_of = |n: &NodeId| by_node.get(n).map(|e| e.path.clone());
246
        let id_of = |h: &ChangeHash| {
247
            snap.base
248
                .get(h)
249
                .map(|m| m.change_id.to_hex())
250
                .unwrap_or_else(|| h.to_hex())
251
        };
252
        let paths = json_array(snap.statuses.iter().map(|s| {
253
            format!(
254
                "{{\"path\":{},\"status\":{}}}",
255
                json_str(&s.path),
256
                json_str(&format!("{:?}", s.status))
257
            )
258
        }));
259
        let mut conflicts: Vec<String> = Vec::new();
260
        for (p, f) in &base_snapshot.files {
261
            if !f.is_conflicted() {
262
                continue;
263
            }
264
            let (kind, changes) = match &f.content {
265
                FileContent::Text { .. } => {
266
                    ("text", snap.base.conflict_regions(&f.node).contributors)
267
                }
268
                FileContent::Opaque { blobs } => {
269
                    ("replace", snap.base.blob_contributors(&f.node, blobs))
270
                }
271
                FileContent::Dir => continue,
272
            };
273
            let resolved = match snap
274
                .statuses
275
                .iter()
276
                .find(|s| s.path == *p)
277
                .map(|s| s.status)
278
            {
279
                Some(ChangeStatus::Resolved) => "true",
280
                Some(ChangeStatus::ConflictEdited) => "\"markers\"",
281
                _ => "false",
282
            };
283
            conflicts.push(format!(
284
                "{{\"kind\":{},\"path\":{},\"node\":{},\"changes\":{},\"resolved\":{resolved}}}",
285
                json_str(kind),
286
                json_str(p),
287
                json_str(&f.node.to_hex()),
288
                json_array(changes.iter().map(|h| json_str(&id_of(h))))
289
            ));
290
        }
291
        for c in &base_snapshot.tree.conflicts {
292
            let (kind, nodes): (&str, Vec<NodeId>) = match c {
293
                crate::tree::TreeConflict::Name { nodes, .. } => ("name", nodes.clone()),
294
                crate::tree::TreeConflict::MultiPlacement { node, .. } => {
295
                    ("multi-placement", vec![*node])
296
                }
297
                crate::tree::TreeConflict::Orphan { node, .. } => ("orphan", vec![*node]),
298
                crate::tree::TreeConflict::Cycle { node } => ("cycle", vec![*node]),
299
                crate::tree::TreeConflict::Mode { node, .. } => ("mode", vec![*node]),
300
            };
301
            let detail = match c {
302
                crate::tree::TreeConflict::Name { name, parent, .. } => {
303
                    let dir = if *parent == NodeId::ROOT {
304
                        String::new()
305
                    } else {
306
                        path_of(parent).unwrap_or_default()
307
                    };
308
                    format!(
309
                        ",\"path\":{}",
310
                        json_str(&if dir.is_empty() {
311
                            name.clone()
312
                        } else {
313
                            format!("{dir}/{name}")
314
                        })
315
                    )
316
                }
317
                _ => nodes
318
                    .first()
319
                    .and_then(path_of)
320
                    .map(|p| format!(",\"path\":{}", json_str(&p)))
321
                    .unwrap_or_default(),
322
            };
323
            conflicts.push(format!(
324
                "{{\"kind\":{},\"nodes\":{}{detail}}}",
325
                json_str(kind),
326
                json_array(nodes.iter().map(|n| json_str(&n.to_hex())))
327
            ));
328
        }
329
        Ok(format!(
330
            "{{\"bookmark\":{},\"working_copy\":{},\"heads\":{},\"clean\":{},\"conflicted\":{},\"paths\":{paths},\"conflicts\":{}}}",
331
            json_str(&self.config.bookmark),
332
            json_str(&snap.wc.change_id.to_hex()),
333
            heads.len(),
334
            snap.statuses.is_empty(),
335
            base_snapshot.is_conflicted(),
336
            json_array(conflicts)
337
        ))
338
    }
339
340
    /// Turn the working-copy change into a normal change on the bookmark (spec §12.3).
341
    pub fn commit(&self, message: &str, extra_deps: &[ChangeHash]) -> Result<ChangeHash> {
342
        self.commit_selection(message, extra_deps, &Selection::All)
343
    }
344
345
    /// The hunks of the working copy, for `oxy commit --interactive`: each
346
    /// tree operation and each edit, in the order `select_hunks` numbers them.
347
    pub fn hunks(&self) -> Result<(SnapshotResult, Vec<Hunk>)> {
348
        let snap = self.snapshot("oxy commit")?;
349
        let hunks = render_hunks(&snap.wc, &snap.base, &snap.base_snapshot);
350
        Ok((snap, hunks))
351
    }
352
353
    /// Commit part of the working copy (spec §12.3). What is not selected
354
    /// stays on disk as uncommitted work: the next snapshot rebuilds it
355
    /// against the new base, so the working copy always describes the
356
    /// directory.
357
    pub fn commit_selection(
358
        &self,
359
        message: &str,
360
        extra_deps: &[ChangeHash],
361
        selection: &Selection,
362
    ) -> Result<ChangeHash> {
363
        let snap = self.snapshot("oxy commit")?;
364
        if snap.wc.tree_ops.is_empty() && snap.wc.edits.is_empty() {
365
            return fail("nothing to commit: the working copy matches its base");
366
        }
367
        if let Some(s) = snap
368
            .statuses
369
            .iter()
370
            .find(|s| s.status == ChangeStatus::ConflictEdited)
371
        {
372
            return fail(format!("{} still contains conflict markers", s.path));
373
        }
374
        if message.trim().is_empty() {
375
            return fail("a commit message is required");
376
        }
377
        let (tree_ops, edits, partial) = match selection {
378
            Selection::All => (snap.wc.tree_ops.clone(), snap.wc.edits.clone(), false),
379
            Selection::Paths(paths) => {
380
                let (o, e) = select_paths(&snap.wc, &snap.base_snapshot, paths);
381
                let partial = o.len() != snap.wc.tree_ops.len() || e.len() != snap.wc.edits.len();
382
                (o, e, partial)
383
            }
384
            Selection::Hunks(indices) => {
385
                let (o, e) = select_hunks(&snap.wc, indices);
386
                let partial = o.len() != snap.wc.tree_ops.len() || e.len() != snap.wc.edits.len();
387
                (o, e, partial)
388
            }
389
        };
390
        if tree_ops.is_empty() && edits.is_empty() {
391
            return fail("nothing selected to commit");
392
        }
393
        if partial && snap.resolves {
394
            return fail("a conflict resolution must be committed whole");
395
        }
396
        // pre-commit hook: may veto.
397
        self.run_hook(
398
            "pre-commit",
399
            &format!(
400
                "{{\"event\":\"pre-commit\",\"message\":{},\"paths\":{}}}",
401
                json_str(message),
402
                json_array(snap.statuses.iter().map(|s| format!(
403
                    "{{\"path\":{},\"status\":{}}}",
404
                    json_str(&s.path),
405
                    json_str(&format!("{:?}", s.status))
406
                )))
407
            ),
408
        )?;
409
        let (op_ref, op) = self.head_op()?;
410
        let mut deps: BTreeSet<ChangeHash> = referenced_changes(&snap.wc, &snap.base);
411
        // semantic-deps hook: may add explicit dependencies (spec §8.1).
412
        if self.config.semantic_deps {
413
            let touched: Vec<String> = snap.statuses.iter().map(|s| s.path.clone()).collect();
414
            let by_node = snap.base_snapshot.tree.by_node();
415
            let mut candidates: Vec<(ChangeId, ChangeHash, Vec<String>)> = Vec::new();
416
            let mut seen: BTreeSet<ChangeHash> = BTreeSet::new();
417
            for h in deps.iter().chain(snap.base.maximal(&snap.wc.deps).iter()) {
418
                if !seen.insert(*h) {
419
                    continue;
420
                }
421
                let c = self.store.get_change(h)?;
422
                let mut paths: BTreeSet<String> = BTreeSet::new();
423
                for n in c
424
                    .tree_ops
425
                    .iter()
426
                    .map(|o| o.node())
427
                    .chain(c.edits.iter().map(|e| e.node()))
428
                {
429
                    if let Some(e) = by_node.get(&n) {
430
                        paths.insert(e.path.clone());
431
                    }
432
                }
433
                candidates.push((c.change_id, *h, paths.into_iter().collect()));
434
            }
435
            for d in self.semantic_deps(&snap.wc.change_id, &touched, &candidates)? {
436
                if snap.base.contains(&d) {
437
                    deps.insert(d);
438
                }
439
            }
440
        }
441
        // A resolution depends on every change that contributed to the
442
        // conflict (spec §8.1). Tree and opaque conflicts are resolved through
443
        // ordinary operations whose references already cover the contributors.
444
        deps.extend(snap.contributors.iter().copied());
445
        for d in extra_deps {
446
            if !snap.base.contains(d) {
447
                return fail(format!(
448
                    "--depends-on {d}: not in the working copy's base state"
449
                ));
450
            }
451
            deps.insert(*d);
452
        }
453
        let mut change = Change {
454
            change_id: if partial {
455
                ChangeId::random()
456
            } else {
457
                snap.wc.change_id
458
            },
459
            deps: vec![],
460
            author: self.author(),
461
            hlc: Hlc::now(),
462
            message: message.trim_end().to_string(),
463
            tree_ops,
464
            edits,
465
            kind: if snap.resolves {
466
                ChangeKind::Resolution
467
            } else {
468
                ChangeKind::Normal
469
            },
470
        };
471
        if partial {
472
            // Dependencies come from what the selected part references, not
473
            // from the whole working copy.
474
            deps = referenced_changes(&change, &snap.base);
475
            for d in extra_deps {
476
                deps.insert(*d);
477
            }
478
        }
479
        change.deps = deps.into_iter().collect();
480
        change.normalize();
481
        let hash = self.store_signed(&change)?;
482
483
        // New bookmark heads: maximal elements of old heads plus the new change.
484
        // The working copy continues on its own base plus the new change, which
485
        // is exactly what the files on disk contain; the bookmark may hold
486
        // other heads (and conflicts) the working copy has not checked out.
487
        let old_heads = self.heads_of(&op.view, &self.config.bookmark)?;
488
        let old_base = snap.base.maximal(&snap.wc.deps);
489
        let mut all: Vec<ChangeHash> = old_heads.clone();
490
        all.extend(old_base.iter().copied());
491
        all.push(hash);
492
        let mut st = self.load_state(&all)?;
493
        st.add(change)?;
494
        let mut with_new = old_heads.clone();
495
        with_new.push(hash);
496
        let new_heads = st.maximal(&with_new);
497
        // Automatic checkpoint once enough changes accumulated (spec §11).
498
        let since = self
499
            .latest_checkpoint(&self.config.bookmark)?
500
            .map(|(_, cp)| cp.count)
501
            .unwrap_or(0);
502
        if self.config.checkpoint_interval > 0
503
            && (st.len() as u64).saturating_sub(since) >= self.config.checkpoint_interval
504
        {
505
            let cp_state = self.load_state_full(&new_heads)?;
506
            self.write_checkpoint(&self.config.bookmark, &cp_state, &new_heads)?;
507
        }
508
        let mut wc_base = old_base.clone();
509
        wc_base.push(hash);
510
        let wc_base = st.maximal(&wc_base);
511
512
        let wc = self.new_working_copy(wc_base, "");
513
        let wc_hash = self.store.put_change(&wc)?;
514
        let mut view = op.view.clone();
515
        view.bookmarks.insert(
516
            self.config.bookmark.clone(),
517
            self.store.put_state(&StateObject::new(new_heads))?,
518
        );
519
        view.workspaces.insert(self.workspace, wc_hash);
520
        self.record_op(&[op_ref], &format!("oxy commit -m {message:?}"), view)?;
521
        if partial {
522
            // The rest is rebuilt from disk by the next snapshot.
523
            self.drop_manifest();
524
        } else {
525
            self.rewrite_manifest_flags(
526
                snap.base_snapshot.is_conflicted() && !snap.resolves,
527
                false,
528
            )?;
529
        }
530
        self.maybe_autopack()?;
531
        let _ = self.run_hook(
532
            "post-commit",
533
            &format!(
534
                "{{\"event\":\"post-commit\",\"change_id\":{},\"hash\":{},\"message\":{}}}",
535
                json_str(&snap.wc.change_id.to_hex()),
536
                json_str(&hash.to_hex()),
537
                json_str(message)
538
            ),
539
        );
540
        Ok(hash)
541
    }
542
}
543
544
/// What part of the working copy a commit takes (spec §12.3).
545
#[derive(Clone, Debug)]
546
pub enum Selection {
547
    All,
548
    /// Every operation and edit on nodes under these paths.
549
    Paths(Vec<String>),
550
    /// Hunk indices as `Repo::hunks` numbers them; dependent hunks are added.
551
    Hunks(Vec<usize>),
552
}
553
554
/// One selectable piece of the working copy: a tree operation or an edit.
555
#[derive(Clone, Debug)]
556
pub struct Hunk {
557
    pub index: usize,
558
    pub path: String,
559
    /// Rendered like `oxy diff`.
560
    pub text: String,
561
}
562
563
/// The tree operations and edits on nodes under `paths`, plus the
564
/// additions of any new parent directories they need.
565
fn select_paths(
566
    wc: &Change,
567
    base_snapshot: &Snapshot,
568
    paths: &[String],
569
) -> (Vec<TreeOp>, Vec<Edit>) {
570
    let selected = |p: &str| {
571
        paths
572
            .iter()
573
            .any(|x| p == x || p.starts_with(&format!("{}/", x.trim_end_matches('/'))))
574
    };
575
    let by_node = base_snapshot.tree.by_node();
576
    let mut new_names: HashMap<NodeId, (NodeId, String, NodeKind)> = HashMap::new();
577
    for op in &wc.tree_ops {
578
        if let TreeOp::AddNode {
579
            node,
580
            parent,
581
            name,
582
            kind,
583
            ..
584
        } = op
585
        {
586
            new_names.insert(*node, (*parent, name.clone(), *kind));
587
        }
588
    }
589
    let mut nodes: BTreeSet<NodeId> = BTreeSet::new();
590
    for n in wc
591
        .tree_ops
592
        .iter()
593
        .map(|o| o.node())
594
        .chain(wc.edits.iter().map(|e| e.node()))
595
    {
596
        if path_of_node(&n, &by_node, &new_names).is_some_and(|p| selected(&p)) {
597
            nodes.insert(n);
598
        }
599
    }
600
    // New parents of selected new nodes come along.
601
    let mut changed = true;
602
    while changed {
603
        changed = false;
604
        for (n, (parent, _, _)) in &new_names {
605
            if nodes.contains(n) && new_names.contains_key(parent) && nodes.insert(*parent) {
606
                changed = true;
607
            }
608
        }
609
    }
610
    let ops = wc
611
        .tree_ops
612
        .iter()
613
        .filter(|o| nodes.contains(&o.node()))
614
        .cloned()
615
        .collect();
616
    let edits = wc
617
        .edits
618
        .iter()
619
        .filter(|e| nodes.contains(&e.node()))
620
        .cloned()
621
        .collect();
622
    (ops, edits)
623
}
624
625
/// The hunks `indices` name plus whatever they refer to within the working
626
/// copy (the parent directory of an added node, the insert that introduced
627
/// an anchor line), renumbered so the result is a well-formed change.
628
fn select_hunks(wc: &Change, indices: &[usize]) -> (Vec<TreeOp>, Vec<Edit>) {
629
    let n_ops = wc.tree_ops.len();
630
    let mut ops_sel = vec![false; n_ops];
631
    let mut edits_sel = vec![false; wc.edits.len()];
632
    for &i in indices {
633
        if i < n_ops {
634
            ops_sel[i] = true;
635
        } else if i - n_ops < wc.edits.len() {
636
            edits_sel[i - n_ops] = true;
637
        }
638
    }
639
    // Atom ranges each insert introduces, per node, in the working copy's numbering.
640
    let mut per_node: HashMap<NodeId, u32> = HashMap::new();
641
    let mut insert_ranges: Vec<Option<(NodeId, u32, u32)>> = Vec::new();
642
    for e in &wc.edits {
643
        insert_ranges.push(match e {
644
            Edit::Insert { node, lines, .. } => {
645
                let start = per_node.entry(*node).or_default();
646
                let r = (*node, *start, *start + lines.len() as u32);
647
                *start += lines.len() as u32;
648
                Some(r)
649
            }
650
            _ => None,
651
        });
652
    }
653
    let add_index: HashMap<NodeId, usize> = wc
654
        .tree_ops
655
        .iter()
656
        .enumerate()
657
        .filter_map(|(i, o)| {
658
            if let TreeOp::AddNode { node, .. } = o {
659
                Some((*node, i))
660
            } else {
661
                None
662
            }
663
        })
664
        .collect();
665
    let insert_for = |node: &NodeId, index: u32| -> Option<usize> {
666
        insert_ranges
667
            .iter()
668
            .position(|r| matches!(r, Some((n, a, b)) if n == node && *a <= index && index < *b))
669
    };
670
    // Closure.
671
    let mut changed = true;
672
    while changed {
673
        changed = false;
674
        for i in 0..n_ops {
675
            if !ops_sel[i] {
676
                continue;
677
            }
678
            if let TreeOp::AddNode { node, parent, .. } = &wc.tree_ops[i] {
679
                if let Some(&p) = add_index.get(parent) {
680
                    if !ops_sel[p] {
681
                        ops_sel[p] = true;
682
                        changed = true;
683
                    }
684
                }
685
                // A new node's content belongs with its addition: nobody
686
                // wants an empty file committed apart from its lines.
687
                for (j, e) in wc.edits.iter().enumerate() {
688
                    if e.node() == *node && !edits_sel[j] {
689
                        edits_sel[j] = true;
690
                        changed = true;
691
                    }
692
                }
693
            }
694
        }
695
        for j in 0..wc.edits.len() {
696
            if !edits_sel[j] {
697
                continue;
698
            }
699
            let e = &wc.edits[j];
700
            if let Some(&a) = add_index.get(&e.node()) {
701
                if !ops_sel[a] {
702
                    ops_sel[a] = true;
703
                    changed = true;
704
                }
705
            }
706
            if let Edit::Insert {
707
                node,
708
                after,
709
                before,
710
                ..
711
            } = e
712
            {
713
                for r in [after, before] {
714
                    if let AtomRef::Atom { change, index } = r {
715
                        if change.is_zero() {
716
                            if let Some(k) = insert_for(node, *index) {
717
                                if !edits_sel[k] {
718
                                    edits_sel[k] = true;
719
                                    changed = true;
720
                                }
721
                            }
722
                        }
723
                    }
724
                }
725
            }
726
        }
727
    }
728
    // Renumber self-references: old atom index → new index among selected inserts.
729
    let mut remap: HashMap<(NodeId, u32), u32> = HashMap::new();
730
    let mut new_counts: HashMap<NodeId, u32> = HashMap::new();
731
    for (j, r) in insert_ranges.iter().enumerate() {
732
        if let (true, Some((node, a, b))) = (edits_sel[j], r) {
733
            let next = new_counts.entry(*node).or_default();
734
            for old in *a..*b {
735
                remap.insert((*node, old), *next);
736
                *next += 1;
737
            }
738
        }
739
    }
740
    let map_ref = |r: AtomRef, node: &NodeId| -> AtomRef {
741
        match r {
742
            AtomRef::Atom { change, index } if change.is_zero() => AtomRef::Atom {
743
                change,
744
                index: remap.get(&(*node, index)).copied().unwrap_or(index),
745
            },
746
            other => other,
747
        }
748
    };
749
    let ops = wc
750
        .tree_ops
751
        .iter()
752
        .enumerate()
753
        .filter(|(i, _)| ops_sel[*i])
754
        .map(|(_, o)| o.clone())
755
        .collect();
756
    let edits = wc
757
        .edits
758
        .iter()
759
        .enumerate()
760
        .filter(|(j, _)| edits_sel[*j])
761
        .map(|(_, e)| match e {
762
            Edit::Insert {
763
                node,
764
                after,
765
                before,
766
                lines,
767
            } => Edit::Insert {
768
                node: *node,
769
                after: map_ref(*after, node),
770
                before: map_ref(*before, node),
771
                lines: lines.clone(),
772
            },
773
            other => other.clone(),
774
        })
775
        .collect();
776
    (ops, edits)
777
}
778
779
/// Render each tree operation and edit of `change` on its own, numbered.
780
pub fn render_hunks(change: &Change, base: &State, base_snapshot: &Snapshot) -> Vec<Hunk> {
781
    let by_node = base_snapshot.tree.by_node();
782
    let mut new_names: HashMap<NodeId, (NodeId, String, NodeKind)> = HashMap::new();
783
    for op in &change.tree_ops {
784
        if let TreeOp::AddNode {
785
            node,
786
            parent,
787
            name,
788
            kind,
789
            ..
790
        } = op
791
        {
792
            new_names.insert(*node, (*parent, name.clone(), *kind));
793
        }
794
    }
795
    let mut out = Vec::new();
796
    for (i, op) in change.tree_ops.iter().enumerate() {
797
        let one = Change {
798
            tree_ops: vec![op.clone()],
799
            edits: vec![],
800
            ..change.clone()
801
        };
802
        let path = path_of_node(&op.node(), &by_node, &new_names).unwrap_or_default();
803
        out.push(Hunk {
804
            index: i,
805
            path,
806
            text: render_change(&one, base, base_snapshot),
807
        });
808
    }
809
    for (j, e) in change.edits.iter().enumerate() {
810
        let one = Change {
811
            tree_ops: vec![],
812
            edits: vec![e.clone()],
813
            ..change.clone()
814
        };
815
        let path = path_of_node(&e.node(), &by_node, &new_names).unwrap_or_default();
816
        out.push(Hunk {
817
            index: change.tree_ops.len() + j,
818
            path,
819
            text: render_change(&one, base, base_snapshot),
820
        });
821
    }
822
    out
823
}
824
825
/// One file's part of a diff, for `oxy diff --json`.
826
#[derive(Clone, Debug)]
827
pub struct FileDiff {
828
    pub path: String,
829
    /// `added`, `removed`, `modified`, `renamed`, `mode`, `replaced`.
830
    pub kind: String,
831
    pub hunks: Vec<DiffHunk>,
832
    /// For renames, the previous path.
833
    pub from: Option<String>,
834
}
835
836
/// Lines inserted after `base_line` (0 = before the first line) and lines
837
/// removed, with their base line numbers.
838
#[derive(Clone, Debug, Default)]
839
pub struct DiffHunk {
840
    pub base_line: u32,
841
    pub added: Vec<Vec<u8>>,
842
    pub removed: Vec<(u32, Vec<u8>)>,
843
}
844
845
impl Repo {
846
    /// The content of `path` in a state: `heads`, or the working copy's base.
847
    pub fn file_at(&self, path: &str, heads: Option<&[ChangeHash]>) -> Result<Vec<u8>> {
848
        let snapshot = match heads {
849
            Some(h) => self.load_state(h)?.materialize(),
850
            None => {
851
                let (_, wc) = self.working_copy()?;
852
                self.load_state(&wc.deps)?.materialize()
853
            }
854
        };
855
        let Some(f) = snapshot.files.get(path) else {
856
            return fail(format!("{path} is not in that state"));
857
        };
858
        match &f.content {
859
            FileContent::Dir => fail(format!("{path} is a directory")),
860
            FileContent::Text { bytes, .. } => Ok(bytes.clone()),
861
            FileContent::Opaque { blobs } => match blobs.first() {
862
                Some(b) => self.read_blob(b),
863
                None => Ok(vec![]),
864
            },
865
        }
866
    }
867
868
    /// Restore `paths` (files or directories) to the working copy's base:
869
    /// edits are undone, additions removed, removals put back. Returns the
870
    /// number of paths touched.
871
    pub fn discard(&self, paths: &[String]) -> Result<usize> {
872
        let snap = self.snapshot("oxy discard")?;
873
        let under = |p: &str| {
874
            paths
875
                .iter()
876
                .any(|x| p == x || p.starts_with(&format!("{}/", x.trim_end_matches('/'))))
877
        };
878
        let attrs = Repo::state_attributes(&snap.base_snapshot);
879
        let mut n = 0;
880
        for s in &snap.statuses {
881
            if !under(&s.path) {
882
                continue;
883
            }
884
            match snap.base_snapshot.files.get(&s.path) {
885
                None => {
886
                    // Added (or the new name of a rename): remove it.
887
                    let full = self.root.join(&s.path);
888
                    if full.is_dir() {
889
                        let _ = fs::remove_dir_all(&full);
890
                    } else {
891
                        let _ = fs::remove_file(&full);
892
                    }
893
                    n += 1;
894
                }
895
                Some(f) => {
896
                    match &f.content {
897
                        FileContent::Dir => fs::create_dir_all(self.root.join(&s.path))?,
898
                        FileContent::Text { bytes, .. } => {
899
                            let on_disk: std::borrow::Cow<[u8]> = if attrs.lookup(&s.path).eol
900
                                == Some(crate::attributes::Eol::Crlf)
901
                            {
902
                                crate::attributes::to_crlf(bytes).into()
903
                            } else {
904
                                bytes.as_slice().into()
905
                            };
906
                            self.write_file(&s.path, &on_disk, f.mode.exec)?;
907
                        }
908
                        FileContent::Opaque { blobs } => {
909
                            let bytes = match blobs.first() {
910
                                Some(b) => self.read_blob(b)?,
911
                                None => vec![],
912
                            };
913
                            if f.kind == NodeKind::Symlink {
914
                                self.write_symlink(&s.path, &bytes)?;
915
                            } else if f.kind == NodeKind::File {
916
                                self.write_file(&s.path, &bytes, f.mode.exec)?;
917
                            }
918
                        }
919
                    }
920
                    n += 1;
921
                }
922
            }
923
        }
924
        // A rename's old name is not in the statuses; put it back too.
925
        for (p, f) in &snap.base_snapshot.files {
926
            if under(p)
927
                && !self.root.join(p).exists()
928
                && f.kind != NodeKind::Dir
929
                && f.kind != NodeKind::Subrepo
930
                && !snap.statuses.iter().any(|s| s.path == *p)
931
            {
932
                let bytes = match &f.content {
933
                    FileContent::Text { bytes, .. } => bytes.clone(),
934
                    FileContent::Opaque { blobs } => blobs
935
                        .first()
936
                        .map(|b| self.read_blob(b))
937
                        .transpose()?
938
                        .unwrap_or_default(),
939
                    FileContent::Dir => continue,
940
                };
941
                if f.kind == NodeKind::Symlink {
942
                    self.write_symlink(p, &bytes)?
943
                } else {
944
                    self.write_file(p, &bytes, f.mode.exec)?
945
                }
946
                n += 1;
947
            }
948
        }
949
        self.drop_manifest();
950
        Ok(n)
951
    }
952
953
    /// Undo the working-copy hunks `indices` (as `hunks` numbers them) on
954
    /// disk, keeping the others: the files are rewritten from the base plus
955
    /// the remaining hunks.
956
    pub fn discard_hunks(&self, indices: &[usize]) -> Result<usize> {
957
        let (snap, hunks) = self.hunks()?;
958
        let keep: Vec<usize> = hunks
959
            .iter()
960
            .map(|h| h.index)
961
            .filter(|i| !indices.contains(i))
962
            .collect();
963
        let (ops, edits) = select_hunks(&snap.wc, &keep);
964
        let dropped_nodes: BTreeSet<NodeId> = hunks
965
            .iter()
966
            .filter(|h| indices.contains(&h.index))
967
            .map(|h| {
968
                if h.index < snap.wc.tree_ops.len() {
969
                    snap.wc.tree_ops[h.index].node()
970
                } else {
971
                    snap.wc.edits[h.index - snap.wc.tree_ops.len()].node()
972
                }
973
            })
974
            .collect();
975
        let mut partial = snap.wc.clone();
976
        partial.tree_ops = ops;
977
        partial.edits = edits;
978
        partial.normalize();
979
        let mut st = snap.base.clone();
980
        st.add_unchecked(partial);
981
        let target = st.materialize();
982
        let by_node_target = target.tree.by_node();
983
        let by_node_base = snap.base_snapshot.tree.by_node();
984
        let attrs = Repo::state_attributes(&target);
985
        let mut n = 0;
986
        for node in dropped_nodes {
987
            match by_node_target.get(&node) {
988
                Some(e) => {
989
                    let f = &target.files[&e.path];
990
                    match &f.content {
991
                        FileContent::Dir => {}
992
                        FileContent::Text { bytes, .. } => {
993
                            let on_disk: std::borrow::Cow<[u8]> = if attrs.lookup(&e.path).eol
994
                                == Some(crate::attributes::Eol::Crlf)
995
                            {
996
                                crate::attributes::to_crlf(bytes).into()
997
                            } else {
998
                                bytes.as_slice().into()
999
                            };
1000
                            self.write_file(&e.path, &on_disk, f.mode.exec)?;
1001
                        }
1002
                        FileContent::Opaque { blobs } => {
1003
                            let bytes = blobs
1004
                                .first()
1005
                                .map(|b| self.read_blob(b))
1006
                                .transpose()?
1007
                                .unwrap_or_default();
1008
                            if f.kind == NodeKind::Symlink {
1009
                                self.write_symlink(&e.path, &bytes)?
1010
                            } else {
1011
                                self.write_file(&e.path, &bytes, f.mode.exec)?
1012
                            }
1013
                        }
1014
                    }
1015
                    // A discarded rename: the new name goes.
1016
                    if let Some(old_path) = snap
1017
                        .statuses
1018
                        .iter()
1019
                        .find(|s| {
1020
                            s.status == ChangeStatus::Renamed && !target.files.contains_key(&s.path)
1021
                        })
1022
                        .map(|s| s.path.clone())
1023
                    {
1024
                        let _ = fs::remove_file(self.root.join(old_path));
1025
                    }
1026
                    n += 1;
1027
                }
1028
                None => {
1029
                    // The node exists in neither target nor base with a live path: an addition to remove.
1030
                    if let Some(added) = snap.statuses.iter().find(|s| {
1031
                        s.status == ChangeStatus::Added
1032
                            && !target.files.contains_key(&s.path)
1033
                            && !by_node_base.contains_key(&node)
1034
                    }) {
1035
                        let full = self.root.join(&added.path);
1036
                        if full.is_dir() {
1037
                            let _ = fs::remove_dir_all(&full);
1038
                        } else {
1039
                            let _ = fs::remove_file(&full);
1040
                        }
1041
                        n += 1;
1042
                    }
1043
                }
1044
            }
1045
        }
1046
        self.drop_manifest();
1047
        Ok(n)
1048
    }
1049
1050
    /// The diff of the working copy (`None`) or of a change, per file with
1051
    /// line-numbered hunks (spec: `oxy diff --json`).
1052
    pub fn diff_files(&self, change: Option<&ChangeHash>) -> Result<Vec<FileDiff>> {
1053
        let (c, base) = match change {
1054
            Some(h) => {
1055
                let c = self.store.get_change(h)?;
1056
                let base = self.load_state(&c.deps)?;
1057
                (c, base)
1058
            }
1059
            None => {
1060
                let snap = self.snapshot("oxy diff")?;
1061
                (snap.wc, snap.base)
1062
            }
1063
        };
1064
        let base_snapshot = base.materialize();
1065
        Ok(diff_files_of(&c, &base, &base_snapshot))
1066
    }
1067
1068
    /// The log restricted to changes touching `path` (its node, so renames
1069
    /// are followed), on the current bookmark.
1070
    pub fn log_for_path(&self, path: &str) -> Result<Vec<LogEntry>> {
1071
        let heads = self.bookmark_heads()?;
1072
        if self.is_bare() {
1073
            return self.log_for_path_in(path, &heads);
1074
        }
1075
        let entries = self.log()?;
1076
        let (_, wc) = self.working_copy()?;
1077
        let base_snapshot = self.load_state(&wc.deps)?.materialize();
1078
        let state_snapshot = self.load_state(&heads)?.materialize();
1079
        let node = base_snapshot
1080
            .files
1081
            .get(path)
1082
            .or_else(|| state_snapshot.files.get(path))
1083
            .map(|f| f.node);
1084
        let Some(node) = node else {
1085
            return fail(format!("{path} is not tracked"));
1086
        };
1087
        Ok(self.entries_touching(entries, node))
1088
    }
1089
1090
    /// The log of the state with these heads restricted to changes touching
1091
    /// `path` (its node, so renames are followed).
1092
    pub fn log_for_path_in(&self, path: &str, heads: &[ChangeHash]) -> Result<Vec<LogEntry>> {
1093
        let entries = self.log_state(heads)?;
1094
        let snapshot = self.load_state(heads)?.materialize();
1095
        let Some(node) = snapshot.files.get(path).map(|f| f.node) else {
1096
            return fail(format!("{path} is not in that state"));
1097
        };
1098
        Ok(self.entries_touching(entries, node))
1099
    }
1100
1101
    fn entries_touching(&self, entries: Vec<LogEntry>, node: NodeId) -> Vec<LogEntry> {
1102
        let mut out = Vec::new();
1103
        for e in entries {
1104
            let Ok(c) = self.store.get_change(&e.hash) else {
1105
                continue;
1106
            };
1107
            if c.tree_ops.iter().any(|o| o.node() == node)
1108
                || c.edits.iter().any(|x| x.node() == node)
1109
            {
1110
                out.push(e);
1111
            }
1112
        }
1113
        out
1114
    }
1115
}
1116
1117
/// Per-file hunks of `change` against `base`.
1118
pub fn diff_files_of(change: &Change, base: &State, base_snapshot: &Snapshot) -> Vec<FileDiff> {
1119
    let by_node = base_snapshot.tree.by_node();
1120
    let mut new_names: HashMap<NodeId, (NodeId, String, NodeKind)> = HashMap::new();
1121
    for op in &change.tree_ops {
1122
        if let TreeOp::AddNode {
1123
            node,
1124
            parent,
1125
            name,
1126
            kind,
1127
            ..
1128
        } = op
1129
        {
1130
            new_names.insert(*node, (*parent, name.clone(), *kind));
1131
        }
1132
    }
1133
    let path_of = |n: &NodeId| -> String {
1134
        path_of_node(n, &by_node, &new_names).unwrap_or_else(|| format!("<node {}>", n.short(8)))
1135
    };
1136
    let mut files: BTreeMap<NodeId, FileDiff> = BTreeMap::new();
1137
    let mut order: Vec<NodeId> = Vec::new();
1138
    let mut entry = |files: &mut BTreeMap<NodeId, FileDiff>, n: NodeId, kind: &str| {
1139
        if let std::collections::btree_map::Entry::Vacant(v) = files.entry(n) {
1140
            order.push(n);
1141
            v.insert(FileDiff {
1142
                path: path_of(&n),
1143
                kind: kind.to_string(),
1144
                hunks: vec![],
1145
                from: None,
1146
            });
1147
        }
1148
    };
1149
    for op in &change.tree_ops {
1150
        match op {
1151
            TreeOp::AddNode { node, kind, .. } => {
1152
                if *kind != NodeKind::Dir {
1153
                    entry(&mut files, *node, "added");
1154
                }
1155
            }
1156
            TreeOp::RemoveNode { node, .. } => {
1157
                entry(&mut files, *node, "removed");
1158
                if let Some(e) = by_node.get(node) {
1159
                    files.get_mut(node).unwrap().path = e.path.clone();
1160
                }
1161
            }
1162
            TreeOp::Move {
1163
                node, parent, name, ..
1164
            } => {
1165
                entry(&mut files, *node, "renamed");
1166
                let f = files.get_mut(node).unwrap();
1167
                f.from = by_node.get(node).map(|e| e.path.clone());
1168
                let dir = if parent.is_root() {
1169
                    String::new()
1170
                } else {
1171
                    path_of_node(parent, &by_node, &new_names).unwrap_or_default()
1172
                };
1173
                f.path = if dir.is_empty() {
1174
                    name.clone()
1175
                } else {
1176
                    format!("{dir}/{name}")
1177
                };
1178
            }
1179
            TreeOp::SetMode { node, .. } => entry(&mut files, *node, "mode"),
1180
        }
1181
    }
1182
    // Base line numbers per node, 1-based.
1183
    let mut line_of: HashMap<NodeId, HashMap<(ChangeHash, u32), u32>> = HashMap::new();
1184
    let mut lines_for = |n: &NodeId| -> HashMap<(ChangeHash, u32), u32> {
1185
        line_of
1186
            .entry(*n)
1187
            .or_insert_with(|| {
1188
                base.live_lines(n)
1189
                    .into_iter()
1190
                    .enumerate()
1191
                    .map(|(i, (k, _))| (k, i as u32 + 1))
1192
                    .collect()
1193
            })
1194
            .clone()
1195
    };
1196
    for e in &change.edits {
1197
        let n = e.node();
1198
        let is_new = new_names.contains_key(&n);
1199
        entry(&mut files, n, if is_new { "added" } else { "modified" });
1200
        let f = files.get_mut(&n).unwrap();
1201
        match e {
1202
            Edit::Insert { after, lines, .. } => {
1203
                let map = lines_for(&n);
1204
                let base_line = match after {
1205
                    AtomRef::Start => 0,
1206
                    AtomRef::End => map.len() as u32,
1207
                    AtomRef::Atom { change, index } if change.is_zero() => {
1208
                        f.hunks.last().map(|h| h.base_line).unwrap_or(0)
1209
                    }
1210
                    AtomRef::Atom { change, index } => {
1211
                        map.get(&(*change, *index)).copied().unwrap_or(0)
1212
                    }
1213
                };
1214
                f.hunks.push(DiffHunk {
1215
                    base_line,
1216
                    added: lines.clone(),
1217
                    removed: vec![],
1218
                });
1219
            }
1220
            Edit::Delete { atoms, .. } => {
1221
                let map = lines_for(&n);
1222
                let mut removed = Vec::new();
1223
                for r in atoms {
1224
                    for i in r.from..r.to {
1225
                        let line = map.get(&(r.change, i)).copied().unwrap_or(0);
1226
                        let text = base
1227
                            .file(&n)
1228
                            .and_then(|g| g.content(&(r.change, i)))
1229
                            .unwrap_or(b"")
1230
                            .to_vec();
1231
                        removed.push((line, text));
1232
                    }
1233
                }
1234
                let base_line = removed
1235
                    .first()
1236
                    .map(|(l, _)| l.saturating_sub(1))
1237
                    .unwrap_or(0);
1238
                f.hunks.push(DiffHunk {
1239
                    base_line,
1240
                    added: vec![],
1241
                    removed,
1242
                });
1243
            }
1244
            Edit::Replace { .. } => {
1245
                if !is_new {
1246
                    f.kind = "replaced".into();
1247
                }
1248
            }
1249
        }
1250
    }
1251
    order.into_iter().filter_map(|n| files.remove(&n)).collect()
1252
}
1253
1254
/// Builds the tree ops and edits of a working-copy change against a base.
1255
struct ChangeBuilder<'a> {
1256
    base: &'a State,
1257
    base_snapshot: &'a Snapshot,
1258
    tree_ops: Vec<TreeOp>,
1259
    edits: Vec<Edit>,
1260
    statuses: Vec<PathStatus>,
1261
    dir_nodes: HashMap<String, NodeId>,
1262
    reuse: HashMap<String, (NodeId, NodeKind)>,
1263
    /// Changes that contributed to conflicts this working copy resolves.
1264
    contributors: BTreeSet<ChangeHash>,
1265
    resolves: bool,
1266
    attrs: crate::attributes::Attributes,
1267
    blobs: HashMap<String, ObjectRef>,
1268
}
1269
1270
impl<'a> ChangeBuilder<'a> {
1271
    fn new(
1272
        base: &'a State,
1273
        base_snapshot: &'a Snapshot,
1274
        reuse: HashMap<String, (NodeId, NodeKind)>,
1275
    ) -> Self {
1276
        let mut dir_nodes: HashMap<String, NodeId> = HashMap::new();
1277
        dir_nodes.insert(String::new(), NodeId::ROOT);
1278
        for (p, f) in &base_snapshot.files {
1279
            if f.kind == NodeKind::Dir {
1280
                dir_nodes.insert(p.clone(), f.node);
1281
            }
1282
        }
1283
        ChangeBuilder {
1284
            base,
1285
            base_snapshot,
1286
            tree_ops: vec![],
1287
            edits: vec![],
1288
            statuses: vec![],
1289
            dir_nodes,
1290
            reuse,
1291
            contributors: BTreeSet::new(),
1292
            resolves: false,
1293
            attrs: crate::attributes::Attributes::default(),
1294
            blobs: HashMap::new(),
1295
        }
1296
    }
1297
1298
    fn with_attributes(mut self, attrs: crate::attributes::Attributes) -> Self {
1299
        self.attrs = attrs;
1300
        self
1301
    }
1302
1303
    /// Whether a file is opaque: forced by `binary`, forced text by `text`
1304
    /// only when it has no NUL bytes, else sniffed.
1305
    /// The blob for an opaque entry: the cached one, else stored now.
1306
    fn blob_of(
1307
        &mut self,
1308
        repo: &Repo,
1309
        path: &str,
1310
        e: &FsEntry,
1311
        nocompress: bool,
1312
    ) -> Result<ObjectRef> {
1313
        let b = match e.blob {
1314
            Some(b) => b,
1315
            None => repo.store_blob_for(&e.content, nocompress)?,
1316
        };
1317
        self.blobs.insert(path.to_string(), b);
1318
        Ok(b)
1319
    }
1320
1321
    fn opaque_for(&self, path: &str, e: &FsEntry) -> bool {
1322
        if e.blob.is_some() {
1323
            return true;
1324
        }
1325
        if e.kind == NodeKind::Symlink || e.kind == NodeKind::Subrepo {
1326
            return true;
1327
        }
1328
        match self.attrs.lookup(path).binary {
1329
            Some(true) => true,
1330
            Some(false) => is_binary(&e.content),
1331
            None => is_binary(&e.content),
1332
        }
1333
    }
1334
1335
    /// Text content as stored: `\r\n` normalized for `eol=` files.
1336
    fn stored_text(&self, path: &str, content: &[u8]) -> Vec<u8> {
1337
        if self.attrs.lookup(path).eol.is_some() {
1338
            crate::attributes::normalize_eol(content)
1339
        } else {
1340
            content.to_vec()
1341
        }
1342
    }
1343
1344
    fn reused_node(&self, path: &str, kind: NodeKind) -> Option<NodeId> {
1345
        self.reuse
1346
            .get(path)
1347
            .filter(|(_, k)| *k == kind)
1348
            .map(|(n, _)| *n)
1349
    }
1350
1351
    fn ensure_dir(&mut self, path: &str) -> NodeId {
1352
        if let Some(n) = self.dir_nodes.get(path) {
1353
            return *n;
1354
        }
1355
        let mut parent = NodeId::ROOT;
1356
        let mut prefix = String::new();
1357
        for comp in path.split('/') {
1358
            if !prefix.is_empty() {
1359
                prefix.push('/');
1360
            }
1361
            prefix.push_str(comp);
1362
            parent = match self.dir_nodes.get(&prefix) {
1363
                Some(n) => *n,
1364
                None => {
1365
                    let node = self
1366
                        .reused_node(&prefix, NodeKind::Dir)
1367
                        .unwrap_or_else(NodeId::random);
1368
                    self.tree_ops.push(TreeOp::AddNode {
1369
                        node,
1370
                        kind: NodeKind::Dir,
1371
                        mode: Mode::default(),
1372
                        parent,
1373
                        name: comp.to_string(),
1374
                    });
1375
                    self.dir_nodes.insert(prefix.clone(), node);
1376
                    node
1377
                }
1378
            };
1379
        }
1380
        parent
1381
    }
1382
1383
    fn add_path(&mut self, repo: &Repo, path: &str, e: &FsEntry) -> Result<()> {
1384
        let (dir, name) = split_path(path);
1385
        let parent = self.ensure_dir(dir);
1386
        let node = self
1387
            .reused_node(path, e.kind)
1388
            .unwrap_or_else(NodeId::random);
1389
        let opaque = self.opaque_for(path, e);
1390
        let nocompress = self.attrs.lookup(path).nocompress;
1391
        self.tree_ops.push(TreeOp::AddNode {
1392
            node,
1393
            kind: e.kind,
1394
            mode: Mode {
1395
                exec: e.exec,
1396
                opaque,
1397
            },
1398
            parent,
1399
            name: name.to_string(),
1400
        });
1401
        if opaque {
1402
            let blob = self.blob_of(repo, path, e, nocompress)?;
1403
            self.edits.push(Edit::Replace {
1404
                node,
1405
                old: None,
1406
                new: Some(blob),
1407
            });
1408
        } else if !e.content.is_empty() {
1409
            let content = self.stored_text(path, &e.content);
1410
            self.edits.push(Edit::Insert {
1411
                node,
1412
                after: crate::objects::AtomRef::Start,
1413
                before: crate::objects::AtomRef::End,
1414
                lines: split_lines(&content).iter().map(|l| l.to_vec()).collect(),
1415
            });
1416
        }
1417
        self.statuses.push(PathStatus {
1418
            path: path.to_string(),
1419
            status: ChangeStatus::Added,
1420
        });
1421
        Ok(())
1422
    }
1423
1424
    /// Move the node at `old` to `new` and apply `e`'s content to it.
1425
    fn move_path(
1426
        &mut self,
1427
        repo: &Repo,
1428
        old: &str,
1429
        new: &str,
1430
        e: &FsEntry,
1431
        expected: &crate::state::FileState,
1432
    ) -> Result<()> {
1433
        let entry = &self.base_snapshot.tree.entries[old];
1434
        let (dir, name) = split_path(new);
1435
        let parent = self.ensure_dir(dir);
1436
        self.tree_ops.push(TreeOp::Move {
1437
            node: expected.node,
1438
            old: op_ref(entry.placement),
1439
            parent,
1440
            name: name.to_string(),
1441
        });
1442
        self.update_path(repo, old, e, expected)?;
1443
        // update_path reports under the old path; the rename is what the user sees.
1444
        self.statuses.retain(|s| s.path != old);
1445
        self.statuses.push(PathStatus {
1446
            path: new.to_string(),
1447
            status: ChangeStatus::Renamed,
1448
        });
1449
        Ok(())
1450
    }
1451
1452
    fn remove_path(&mut self, path: &str, expected: &crate::state::FileState) {
1453
        let entry = &self.base_snapshot.tree.entries[path];
1454
        self.tree_ops.push(TreeOp::RemoveNode {
1455
            node: expected.node,
1456
            placement: op_ref(entry.placement),
1457
        });
1458
        if path.contains(".oxy-conflict-") || expected.is_conflicted() {
1459
            self.resolves = true;
1460
        }
1461
        self.statuses.push(PathStatus {
1462
            path: path.to_string(),
1463
            status: ChangeStatus::Removed,
1464
        });
1465
    }
1466
1467
    fn update_path(
1468
        &mut self,
1469
        repo: &Repo,
1470
        path: &str,
1471
        e: &FsEntry,
1472
        expected: &crate::state::FileState,
1473
    ) -> Result<()> {
1474
        if expected.kind != e.kind {
1475
            self.remove_path(path, expected);
1476
            self.statuses.pop();
1477
            self.add_path(repo, path, e)?;
1478
            self.statuses.pop();
1479
            self.statuses.push(PathStatus {
1480
                path: path.to_string(),
1481
                status: ChangeStatus::Modified,
1482
            });
1483
            return Ok(());
1484
        }
1485
        let entry = &self.base_snapshot.tree.entries[path];
1486
        let node = expected.node;
1487
        let mode_atom = entry.mode_atom.map(op_ref);
1488
        let mut status: Option<ChangeStatus> = None;
1489
        let wants_opaque = self.opaque_for(path, e);
1490
        let nocompress = self.attrs.lookup(path).nocompress;
1491
        let disk_text = self.stored_text(path, &e.content);
1492
        match &expected.content {
1493
            FileContent::Dir => {}
1494
            FileContent::Text {
1495
                bytes,
1496
                materialized,
1497
            } => {
1498
                if materialized.is_conflicted() {
1499
                    if bytes == &disk_text {
1500
                        return Ok(());
1501
                    }
1502
                    if has_conflict_markers(&e.content) {
1503
                        self.statuses.push(PathStatus {
1504
                            path: path.to_string(),
1505
                            status: ChangeStatus::ConflictEdited,
1506
                        });
1507
                        return Ok(());
1508
                    }
1509
                    // Resolution (spec §9.6): diff against the unconflicted lines
1510
                    // with each region as a gap, then retire every region atom.
1511
                    // Whatever the author kept from a region is re-inserted as
1512
                    // new atoms, which leaves the graph totally ordered.
1513
                    let regions = self.base.conflict_regions(&node);
1514
                    let mut edits = text_edits(node, &regions.plain, &disk_text);
1515
                    if !regions.region_atoms.is_empty() {
1516
                        edits.insert(
1517
                            0,
1518
                            Edit::Delete {
1519
                                node,
1520
                                atoms: ranges(&regions.region_atoms),
1521
                            },
1522
                        );
1523
                    }
1524
                    self.edits.extend(edits);
1525
                    self.contributors.extend(regions.contributors);
1526
                    self.resolves = true;
1527
                    if e.exec != expected.mode.exec {
1528
                        if let Some(old) = mode_atom {
1529
                            self.tree_ops.push(TreeOp::SetMode {
1530
                                node,
1531
                                old,
1532
                                mode: Mode {
1533
                                    exec: e.exec,
1534
                                    opaque: false,
1535
                                },
1536
                            });
1537
                        }
1538
                    }
1539
                    self.statuses.push(PathStatus {
1540
                        path: path.to_string(),
1541
                        status: ChangeStatus::Resolved,
1542
                    });
1543
                    return Ok(());
1544
                }
1545
                if wants_opaque {
1546
                    // Text → opaque (spec §7.5), by content or by attribute.
1547
                    if let Some(old) = mode_atom {
1548
                        self.tree_ops.push(TreeOp::SetMode {
1549
                            node,
1550
                            old,
1551
                            mode: Mode {
1552
                                exec: e.exec,
1553
                                opaque: true,
1554
                            },
1555
                        });
1556
                    }
1557
                    let live: Vec<_> = repo_live_keys(self.base, &node);
1558
                    if !live.is_empty() {
1559
                        self.edits.push(Edit::Delete {
1560
                            node,
1561
                            atoms: ranges(&live),
1562
                        });
1563
                    }
1564
                    let blob = self.blob_of(repo, path, e, nocompress)?;
1565
                    self.edits.push(Edit::Replace {
1566
                        node,
1567
                        old: None,
1568
                        new: Some(blob),
1569
                    });
1570
                    status = Some(ChangeStatus::Modified);
1571
                } else if bytes != &disk_text {
1572
                    let old = self.base.live_lines(&node);
1573
                    let edits = text_edits(node, &old, &disk_text);
1574
                    if !edits.is_empty() {
1575
                        self.edits.extend(edits);
1576
                        status = Some(ChangeStatus::Modified);
1577
                    }
1578
                }
1579
                let switched_to_opaque = wants_opaque;
1580
                if !switched_to_opaque && e.exec != expected.mode.exec {
1581
                    if let Some(old) = mode_atom {
1582
                        self.tree_ops.push(TreeOp::SetMode {
1583
                            node,
1584
                            old,
1585
                            mode: Mode {
1586
                                exec: e.exec,
1587
                                opaque: false,
1588
                            },
1589
                        });
1590
                        status.get_or_insert(ChangeStatus::ModeChanged);
1591
                    }
1592
                }
1593
            }
1594
            FileContent::Opaque { blobs } => {
1595
                let new_ref = e.blob.unwrap_or_else(|| Repo::blob_ref(&e.content));
1596
                if e.kind == NodeKind::File && wants_opaque {
1597
                    // Unchanged or replaced, the file stays opaque: remember its blob.
1598
                    self.blobs.insert(path.to_string(), new_ref);
1599
                }
1600
                if blobs.len() > 1 {
1601
                    if !blobs.contains(&new_ref) {
1602
                        self.statuses.push(PathStatus {
1603
                            path: path.to_string(),
1604
                            status: ChangeStatus::ConflictEdited,
1605
                        });
1606
                    }
1607
                    return Ok(());
1608
                }
1609
                let current = blobs.first().copied();
1610
                if current != Some(new_ref) {
1611
                    if e.kind == NodeKind::File && !wants_opaque {
1612
                        // Opaque → text (spec §7.5).
1613
                        if let Some(old) = mode_atom {
1614
                            self.tree_ops.push(TreeOp::SetMode {
1615
                                node,
1616
                                old,
1617
                                mode: Mode {
1618
                                    exec: e.exec,
1619
                                    opaque: false,
1620
                                },
1621
                            });
1622
                        }
1623
                        self.edits.push(Edit::Replace {
1624
                            node,
1625
                            old: current,
1626
                            new: None,
1627
                        });
1628
                        if !e.content.is_empty() {
1629
                            self.edits.push(Edit::Insert {
1630
                                node,
1631
                                after: crate::objects::AtomRef::Start,
1632
                                before: crate::objects::AtomRef::End,
1633
                                lines: split_lines(&e.content).iter().map(|l| l.to_vec()).collect(),
1634
                            });
1635
                        }
1636
                    } else {
1637
                        let blob = self.blob_of(repo, path, e, nocompress)?;
1638
                        self.edits.push(Edit::Replace {
1639
                            node,
1640
                            old: current,
1641
                            new: Some(blob),
1642
                        });
1643
                    }
1644
                    status = Some(ChangeStatus::Modified);
1645
                } else if e.kind == NodeKind::File && e.exec != expected.mode.exec {
1646
                    if let Some(old) = mode_atom {
1647
                        self.tree_ops.push(TreeOp::SetMode {
1648
                            node,
1649
                            old,
1650
                            mode: Mode {
1651
                                exec: e.exec,
1652
                                opaque: true,
1653
                            },
1654
                        });
1655
                        status = Some(ChangeStatus::ModeChanged);
1656
                    }
1657
                }
1658
            }
1659
        }
1660
        if let Some(s) = status {
1661
            self.statuses.push(PathStatus {
1662
                path: path.to_string(),
1663
                status: s,
1664
            });
1665
        }
1666
        Ok(())
1667
    }
1668
}
1669
1670
fn repo_live_keys(base: &State, node: &NodeId) -> Vec<crate::graph::AtomKey> {
1671
    base.live_lines(node).into_iter().map(|(k, _)| k).collect()
1672
}
1673
1674
/// The changes a change's scope references (spec §8.1): introducers of every
1675
/// atom, placement, and mode it touches, and of every node it operates on.
1676
pub fn referenced_changes(change: &Change, base: &State) -> BTreeSet<ChangeHash> {
1677
    let mut out = BTreeSet::new();
1678
    let opref = |r: &OpRef, out: &mut BTreeSet<ChangeHash>| {
1679
        if !r.change.is_zero() {
1680
            out.insert(r.change);
1681
        }
1682
    };
1683
    let mut nodes: Vec<NodeId> = Vec::new();
1684
    for op in &change.tree_ops {
1685
        match op {
1686
            TreeOp::AddNode { parent, .. } => nodes.push(*parent),
1687
            TreeOp::RemoveNode { node, placement } => {
1688
                nodes.push(*node);
1689
                opref(placement, &mut out);
1690
            }
1691
            TreeOp::Move {
1692
                node, old, parent, ..
1693
            } => {
1694
                nodes.push(*node);
1695
                nodes.push(*parent);
1696
                opref(old, &mut out);
1697
            }
1698
            TreeOp::SetMode { node, old, .. } => {
1699
                nodes.push(*node);
1700
                opref(old, &mut out);
1701
            }
1702
        }
1703
    }
1704
    for e in &change.edits {
1705
        nodes.push(e.node());
1706
        match e {
1707
            Edit::Insert { after, before, .. } => {
1708
                for r in [after, before] {
1709
                    if let crate::objects::AtomRef::Atom { change, .. } = r {
1710
                        if !change.is_zero() {
1711
                            out.insert(*change);
1712
                        }
1713
                    }
1714
                }
1715
            }
1716
            Edit::Delete { atoms, .. } => {
1717
                for r in atoms {
1718
                    if !r.change.is_zero() {
1719
                        out.insert(r.change);
1720
                    }
1721
                }
1722
            }
1723
            Edit::Replace { .. } => {}
1724
        }
1725
    }
1726
    for n in nodes {
1727
        if let Some(h) = base.tree().introducer(&n) {
1728
            out.insert(h);
1729
        }
1730
    }
1731
    out
1732
}
1733
1734
/// Paths of the nodes a change adds on top of `base_snapshot`.
1735
pub fn added_node_paths(
1736
    change: &Change,
1737
    base_snapshot: &Snapshot,
1738
) -> HashMap<String, (NodeId, NodeKind)> {
1739
    let by_node = base_snapshot.tree.by_node();
1740
    let mut new_names: HashMap<NodeId, (NodeId, String, NodeKind)> = HashMap::new();
1741
    for op in &change.tree_ops {
1742
        if let TreeOp::AddNode {
1743
            node,
1744
            parent,
1745
            name,
1746
            kind,
1747
            ..
1748
        } = op
1749
        {
1750
            new_names.insert(*node, (*parent, name.clone(), *kind));
1751
        }
1752
    }
1753
    let mut out = HashMap::new();
1754
    for (node, (_, _, kind)) in &new_names {
1755
        if let Some(path) = path_of_node(node, &by_node, &new_names) {
1756
            out.insert(path, (*node, *kind));
1757
        }
1758
    }
1759
    out
1760
}
1761
1762
fn path_of_node(
1763
    n: &NodeId,
1764
    by_node: &HashMap<NodeId, &crate::tree::TreeEntry>,
1765
    new_names: &HashMap<NodeId, (NodeId, String, NodeKind)>,
1766
) -> Option<String> {
1767
    if let Some(e) = by_node.get(n) {
1768
        return Some(e.path.clone());
1769
    }
1770
    let mut parts = Vec::new();
1771
    let mut cur = *n;
1772
    loop {
1773
        if cur.is_root() {
1774
            break;
1775
        }
1776
        if let Some(e) = by_node.get(&cur) {
1777
            if !e.path.is_empty() {
1778
                parts.push(e.path.clone());
1779
            }
1780
            break;
1781
        }
1782
        let (parent, name, _) = new_names.get(&cur)?;
1783
        parts.push(name.clone());
1784
        cur = *parent;
1785
    }
1786
    parts.reverse();
1787
    Some(parts.join("/"))
1788
}
1789
1790
/// Render a change's operations with line content, using `base` for deleted lines.
1791
pub fn render_change(change: &Change, base: &State, base_snapshot: &Snapshot) -> String {
1792
    let by_node = base_snapshot.tree.by_node();
1793
    let mut new_names: HashMap<NodeId, (NodeId, String, NodeKind)> = HashMap::new();
1794
    for op in &change.tree_ops {
1795
        if let TreeOp::AddNode {
1796
            node,
1797
            parent,
1798
            name,
1799
            kind,
1800
            ..
1801
        } = op
1802
        {
1803
            new_names.insert(*node, (*parent, name.clone(), *kind));
1804
        }
1805
    }
1806
    let path_of = |n: &NodeId| -> String {
1807
        path_of_node(n, &by_node, &new_names).unwrap_or_else(|| format!("<node {}>", n.short(8)))
1808
    };
1809
1810
    let mut out = String::new();
1811
    for op in &change.tree_ops {
1812
        match op {
1813
            TreeOp::AddNode {
1814
                node, kind, mode, ..
1815
            } => {
1816
                out.push_str(&format!(
1817
                    "A {} ({:?}{}{})\n",
1818
                    path_of(node),
1819
                    kind,
1820
                    if mode.exec { ", exec" } else { "" },
1821
                    if mode.opaque { ", opaque" } else { "" }
1822
                ));
1823
            }
1824
            TreeOp::RemoveNode { node, .. } => out.push_str(&format!("D {}\n", path_of(node))),
1825
            TreeOp::Move { node, name, .. } => {
1826
                out.push_str(&format!("R {} -> {}\n", path_of(node), name))
1827
            }
1828
            TreeOp::SetMode { node, mode, .. } => {
1829
                out.push_str(&format!(
1830
                    "M {} mode: exec={} opaque={}\n",
1831
                    path_of(node),
1832
                    mode.exec,
1833
                    mode.opaque
1834
                ));
1835
            }
1836
        }
1837
    }
1838
    let mut last_node: Option<NodeId> = None;
1839
    for e in &change.edits {
1840
        let n = e.node();
1841
        if last_node != Some(n) {
1842
            out.push_str(&format!("--- {}\n", path_of(&n)));
1843
            last_node = Some(n);
1844
        }
1845
        match e {
1846
            Edit::Insert { lines, .. } => {
1847
                for l in lines {
1848
                    out.push('+');
1849
                    out.push_str(&String::from_utf8_lossy(l));
1850
                    if !l.ends_with(b"\n") {
1851
                        out.push('\n');
1852
                    }
1853
                }
1854
            }
1855
            Edit::Delete { atoms, .. } => {
1856
                for r in atoms {
1857
                    for i in r.from..r.to {
1858
                        let content = base
1859
                            .file(&n)
1860
                            .and_then(|g| g.content(&(r.change, i)))
1861
                            .unwrap_or(b"<unknown>\n");
1862
                        out.push('-');
1863
                        out.push_str(&String::from_utf8_lossy(content));
1864
                        if !content.ends_with(b"\n") {
1865
                            out.push('\n');
1866
                        }
1867
                    }
1868
                }
1869
            }
1870
            Edit::Replace { old, new, .. } => {
1871
                out.push_str(&format!(
1872
                    "  opaque content {} -> {}\n",
1873
                    old.map(|o| o.short(12)).unwrap_or_else(|| "none".into()),
1874
                    new.map(|o| o.short(12)).unwrap_or_else(|| "none".into())
1875
                ));
1876
            }
1877
        }
1878
    }
1879
    out
1880
}
1881
1882
/// Pair removed files with added files of the same kind whose contents are
1883
/// at least `RENAME_THRESHOLD` percent alike, best matches first. Beyond
1884
/// `RENAME_LIMIT` candidate pairs only identical contents are paired.
1885
const RENAME_THRESHOLD: u32 = 50;
1886
const RENAME_LIMIT: usize = 10_000;
1887
1888
fn detect_renames(
1889
    base_snapshot: &Snapshot,
1890
    fs_entries: &BTreeMap<String, FsEntry>,
1891
    in_scope: impl Fn(&str) -> bool,
1892
) -> Vec<(String, String)> {
1893
    let removed: Vec<(&String, &crate::state::FileState)> = base_snapshot
1894
        .files
1895
        .iter()
1896
        .filter(|(p, f)| {
1897
            f.kind != NodeKind::Dir
1898
                && !fs_entries.contains_key(*p)
1899
                && in_scope(p)
1900
                && !f.is_conflicted()
1901
        })
1902
        .collect();
1903
    let added: Vec<(&String, &FsEntry)> = fs_entries
1904
        .iter()
1905
        .filter(|(p, e)| e.kind != NodeKind::Dir && !base_snapshot.files.contains_key(*p))
1906
        .collect();
1907
    if removed.is_empty() || added.is_empty() {
1908
        return vec![];
1909
    }
1910
    let exact_only = removed.len() * added.len() > RENAME_LIMIT;
1911
    let old_content = |f: &crate::state::FileState| -> Option<Vec<u8>> {
1912
        match &f.content {
1913
            FileContent::Text { bytes, .. } => Some(bytes.clone()),
1914
            _ => None,
1915
        }
1916
    };
1917
    let mut scored: Vec<(u32, usize, usize)> = Vec::new();
1918
    for (ri, (_, f)) in removed.iter().enumerate() {
1919
        let old = old_content(f);
1920
        let old_blob = match &f.content {
1921
            FileContent::Opaque { blobs } if blobs.len() == 1 => Some(blobs[0]),
1922
            _ => None,
1923
        };
1924
        for (ai, (_, e)) in added.iter().enumerate() {
1925
            if e.kind != f.kind {
1926
                continue;
1927
            }
1928
            let score = match (&old, old_blob) {
1929
                (Some(o), _) => {
1930
                    if exact_only {
1931
                        if *o == e.content {
1932
                            100
1933
                        } else {
1934
                            0
1935
                        }
1936
                    } else {
1937
                        similarity(o, &e.content)
1938
                    }
1939
                }
1940
                (None, Some(b)) if e.blob.unwrap_or_else(|| Repo::blob_ref(&e.content)) == b => 100,
1941
                _ => 0,
1942
            };
1943
            if score >= RENAME_THRESHOLD {
1944
                scored.push((score, ri, ai));
1945
            }
1946
        }
1947
    }
1948
    scored.sort_by(|a, b| {
1949
        b.0.cmp(&a.0)
1950
            .then(removed[a.1].0.cmp(removed[b.1].0))
1951
            .then(added[a.2].0.cmp(added[b.2].0))
1952
    });
1953
    let mut used_r = vec![false; removed.len()];
1954
    let mut used_a = vec![false; added.len()];
1955
    let mut out = Vec::new();
1956
    for (_, ri, ai) in scored {
1957
        if used_r[ri] || used_a[ai] {
1958
            continue;
1959
        }
1960
        used_r[ri] = true;
1961
        used_a[ai] = true;
1962
        out.push((removed[ri].0.clone(), added[ai].0.clone()));
1963
    }
1964
    out
1965
}
1966
1967
/// Percentage of the larger file's bytes found in lines the two share
1968
/// (multiset intersection of lines), like Git's similarity index.
1969
pub fn similarity(a: &[u8], b: &[u8]) -> u32 {
1970
    if a == b {
1971
        return 100;
1972
    }
1973
    if a.is_empty() || b.is_empty() {
1974
        return 0;
1975
    }
1976
    let mut counts: HashMap<&[u8], usize> = HashMap::new();
1977
    for l in split_lines(a) {
1978
        *counts.entry(l).or_default() += 1;
1979
    }
1980
    let mut shared = 0usize;
1981
    for l in split_lines(b) {
1982
        if let Some(n) = counts.get_mut(l) {
1983
            if *n > 0 {
1984
                *n -= 1;
1985
                shared += l.len();
1986
            }
1987
        }
1988
    }
1989
    (shared * 100 / a.len().max(b.len())) as u32
1990
}