OXYGENHUB
# 6f16ce2be33b oxygen / crates / oxy-core / src / repo / snapshot.rs
72.6 KiB · Rust · last changed Commit and status no longer slow down with the number of heads 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
        // The snapshot already loaded the working copy's base; when that also
493
        // holds every bookmark head, it is the state to extend.
494
        let mut st = if old_heads.iter().all(|h| snap.base.contains(h)) {
495
            snap.base
496
        } else {
497
            self.load_state(&all)?
498
        };
499
        st.add(change)?;
500
        let mut with_new = old_heads.clone();
501
        with_new.push(hash);
502
        let new_heads = st.maximal(&with_new);
503
        // Automatic checkpoint once enough changes accumulated (spec §11).
504
        let since = self
505
            .latest_checkpoint(&self.config.bookmark)?
506
            .map(|(_, cp)| cp.count)
507
            .unwrap_or(0);
508
        if self.config.checkpoint_interval > 0
509
            && (st.len() as u64).saturating_sub(since) >= self.config.checkpoint_interval
510
        {
511
            let cp_state = self.load_state_full(&new_heads)?;
512
            self.write_checkpoint(&self.config.bookmark, &cp_state, &new_heads)?;
513
        }
514
        let mut wc_base = old_base.clone();
515
        wc_base.push(hash);
516
        let wc_base = st.maximal(&wc_base);
517
518
        let wc = self.new_working_copy(wc_base, "");
519
        let wc_hash = self.store.put_change(&wc)?;
520
        let mut view = op.view.clone();
521
        view.bookmarks.insert(
522
            self.config.bookmark.clone(),
523
            self.store.put_state(&StateObject::new(new_heads))?,
524
        );
525
        view.workspaces.insert(self.workspace, wc_hash);
526
        self.record_op(&[op_ref], &format!("oxy commit -m {message:?}"), view)?;
527
        if partial {
528
            // The rest is rebuilt from disk by the next snapshot.
529
            self.drop_manifest();
530
        } else {
531
            self.rewrite_manifest_flags(
532
                snap.base_snapshot.is_conflicted() && !snap.resolves,
533
                false,
534
            )?;
535
        }
536
        self.maybe_autopack()?;
537
        let _ = self.run_hook(
538
            "post-commit",
539
            &format!(
540
                "{{\"event\":\"post-commit\",\"change_id\":{},\"hash\":{},\"message\":{}}}",
541
                json_str(&snap.wc.change_id.to_hex()),
542
                json_str(&hash.to_hex()),
543
                json_str(message)
544
            ),
545
        );
546
        Ok(hash)
547
    }
548
}
549
550
/// What part of the working copy a commit takes (spec §12.3).
551
#[derive(Clone, Debug)]
552
pub enum Selection {
553
    All,
554
    /// Every operation and edit on nodes under these paths.
555
    Paths(Vec<String>),
556
    /// Hunk indices as `Repo::hunks` numbers them; dependent hunks are added.
557
    Hunks(Vec<usize>),
558
}
559
560
/// One selectable piece of the working copy: a tree operation or an edit.
561
#[derive(Clone, Debug)]
562
pub struct Hunk {
563
    pub index: usize,
564
    pub path: String,
565
    /// Rendered like `oxy diff`.
566
    pub text: String,
567
}
568
569
/// The tree operations and edits on nodes under `paths`, plus the
570
/// additions of any new parent directories they need.
571
fn select_paths(
572
    wc: &Change,
573
    base_snapshot: &Snapshot,
574
    paths: &[String],
575
) -> (Vec<TreeOp>, Vec<Edit>) {
576
    let selected = |p: &str| {
577
        paths
578
            .iter()
579
            .any(|x| p == x || p.starts_with(&format!("{}/", x.trim_end_matches('/'))))
580
    };
581
    let by_node = base_snapshot.tree.by_node();
582
    let mut new_names: HashMap<NodeId, (NodeId, String, NodeKind)> = HashMap::new();
583
    for op in &wc.tree_ops {
584
        if let TreeOp::AddNode {
585
            node,
586
            parent,
587
            name,
588
            kind,
589
            ..
590
        } = op
591
        {
592
            new_names.insert(*node, (*parent, name.clone(), *kind));
593
        }
594
    }
595
    let mut nodes: BTreeSet<NodeId> = BTreeSet::new();
596
    for n in wc
597
        .tree_ops
598
        .iter()
599
        .map(|o| o.node())
600
        .chain(wc.edits.iter().map(|e| e.node()))
601
    {
602
        if path_of_node(&n, &by_node, &new_names).is_some_and(|p| selected(&p)) {
603
            nodes.insert(n);
604
        }
605
    }
606
    // New parents of selected new nodes come along.
607
    let mut changed = true;
608
    while changed {
609
        changed = false;
610
        for (n, (parent, _, _)) in &new_names {
611
            if nodes.contains(n) && new_names.contains_key(parent) && nodes.insert(*parent) {
612
                changed = true;
613
            }
614
        }
615
    }
616
    let ops = wc
617
        .tree_ops
618
        .iter()
619
        .filter(|o| nodes.contains(&o.node()))
620
        .cloned()
621
        .collect();
622
    let edits = wc
623
        .edits
624
        .iter()
625
        .filter(|e| nodes.contains(&e.node()))
626
        .cloned()
627
        .collect();
628
    (ops, edits)
629
}
630
631
/// The hunks `indices` name plus whatever they refer to within the working
632
/// copy (the parent directory of an added node, the insert that introduced
633
/// an anchor line), renumbered so the result is a well-formed change.
634
fn select_hunks(wc: &Change, indices: &[usize]) -> (Vec<TreeOp>, Vec<Edit>) {
635
    let n_ops = wc.tree_ops.len();
636
    let mut ops_sel = vec![false; n_ops];
637
    let mut edits_sel = vec![false; wc.edits.len()];
638
    for &i in indices {
639
        if i < n_ops {
640
            ops_sel[i] = true;
641
        } else if i - n_ops < wc.edits.len() {
642
            edits_sel[i - n_ops] = true;
643
        }
644
    }
645
    // Atom ranges each insert introduces, per node, in the working copy's numbering.
646
    let mut per_node: HashMap<NodeId, u32> = HashMap::new();
647
    let mut insert_ranges: Vec<Option<(NodeId, u32, u32)>> = Vec::new();
648
    for e in &wc.edits {
649
        insert_ranges.push(match e {
650
            Edit::Insert { node, lines, .. } => {
651
                let start = per_node.entry(*node).or_default();
652
                let r = (*node, *start, *start + lines.len() as u32);
653
                *start += lines.len() as u32;
654
                Some(r)
655
            }
656
            _ => None,
657
        });
658
    }
659
    let add_index: HashMap<NodeId, usize> = wc
660
        .tree_ops
661
        .iter()
662
        .enumerate()
663
        .filter_map(|(i, o)| {
664
            if let TreeOp::AddNode { node, .. } = o {
665
                Some((*node, i))
666
            } else {
667
                None
668
            }
669
        })
670
        .collect();
671
    let insert_for = |node: &NodeId, index: u32| -> Option<usize> {
672
        insert_ranges
673
            .iter()
674
            .position(|r| matches!(r, Some((n, a, b)) if n == node && *a <= index && index < *b))
675
    };
676
    // Closure.
677
    let mut changed = true;
678
    while changed {
679
        changed = false;
680
        for i in 0..n_ops {
681
            if !ops_sel[i] {
682
                continue;
683
            }
684
            if let TreeOp::AddNode { node, parent, .. } = &wc.tree_ops[i] {
685
                if let Some(&p) = add_index.get(parent) {
686
                    if !ops_sel[p] {
687
                        ops_sel[p] = true;
688
                        changed = true;
689
                    }
690
                }
691
                // A new node's content belongs with its addition: nobody
692
                // wants an empty file committed apart from its lines.
693
                for (j, e) in wc.edits.iter().enumerate() {
694
                    if e.node() == *node && !edits_sel[j] {
695
                        edits_sel[j] = true;
696
                        changed = true;
697
                    }
698
                }
699
            }
700
        }
701
        for j in 0..wc.edits.len() {
702
            if !edits_sel[j] {
703
                continue;
704
            }
705
            let e = &wc.edits[j];
706
            if let Some(&a) = add_index.get(&e.node()) {
707
                if !ops_sel[a] {
708
                    ops_sel[a] = true;
709
                    changed = true;
710
                }
711
            }
712
            if let Edit::Insert {
713
                node,
714
                after,
715
                before,
716
                ..
717
            } = e
718
            {
719
                for r in [after, before] {
720
                    if let AtomRef::Atom { change, index } = r {
721
                        if change.is_zero() {
722
                            if let Some(k) = insert_for(node, *index) {
723
                                if !edits_sel[k] {
724
                                    edits_sel[k] = true;
725
                                    changed = true;
726
                                }
727
                            }
728
                        }
729
                    }
730
                }
731
            }
732
        }
733
    }
734
    // Renumber self-references: old atom index → new index among selected inserts.
735
    let mut remap: HashMap<(NodeId, u32), u32> = HashMap::new();
736
    let mut new_counts: HashMap<NodeId, u32> = HashMap::new();
737
    for (j, r) in insert_ranges.iter().enumerate() {
738
        if let (true, Some((node, a, b))) = (edits_sel[j], r) {
739
            let next = new_counts.entry(*node).or_default();
740
            for old in *a..*b {
741
                remap.insert((*node, old), *next);
742
                *next += 1;
743
            }
744
        }
745
    }
746
    let map_ref = |r: AtomRef, node: &NodeId| -> AtomRef {
747
        match r {
748
            AtomRef::Atom { change, index } if change.is_zero() => AtomRef::Atom {
749
                change,
750
                index: remap.get(&(*node, index)).copied().unwrap_or(index),
751
            },
752
            other => other,
753
        }
754
    };
755
    let ops = wc
756
        .tree_ops
757
        .iter()
758
        .enumerate()
759
        .filter(|(i, _)| ops_sel[*i])
760
        .map(|(_, o)| o.clone())
761
        .collect();
762
    let edits = wc
763
        .edits
764
        .iter()
765
        .enumerate()
766
        .filter(|(j, _)| edits_sel[*j])
767
        .map(|(_, e)| match e {
768
            Edit::Insert {
769
                node,
770
                after,
771
                before,
772
                lines,
773
            } => Edit::Insert {
774
                node: *node,
775
                after: map_ref(*after, node),
776
                before: map_ref(*before, node),
777
                lines: lines.clone(),
778
            },
779
            other => other.clone(),
780
        })
781
        .collect();
782
    (ops, edits)
783
}
784
785
/// Render each tree operation and edit of `change` on its own, numbered.
786
pub fn render_hunks(change: &Change, base: &State, base_snapshot: &Snapshot) -> Vec<Hunk> {
787
    let by_node = base_snapshot.tree.by_node();
788
    let mut new_names: HashMap<NodeId, (NodeId, String, NodeKind)> = HashMap::new();
789
    for op in &change.tree_ops {
790
        if let TreeOp::AddNode {
791
            node,
792
            parent,
793
            name,
794
            kind,
795
            ..
796
        } = op
797
        {
798
            new_names.insert(*node, (*parent, name.clone(), *kind));
799
        }
800
    }
801
    let mut out = Vec::new();
802
    for (i, op) in change.tree_ops.iter().enumerate() {
803
        let one = Change {
804
            tree_ops: vec![op.clone()],
805
            edits: vec![],
806
            ..change.clone()
807
        };
808
        let path = path_of_node(&op.node(), &by_node, &new_names).unwrap_or_default();
809
        out.push(Hunk {
810
            index: i,
811
            path,
812
            text: render_change(&one, base, base_snapshot),
813
        });
814
    }
815
    for (j, e) in change.edits.iter().enumerate() {
816
        let one = Change {
817
            tree_ops: vec![],
818
            edits: vec![e.clone()],
819
            ..change.clone()
820
        };
821
        let path = path_of_node(&e.node(), &by_node, &new_names).unwrap_or_default();
822
        out.push(Hunk {
823
            index: change.tree_ops.len() + j,
824
            path,
825
            text: render_change(&one, base, base_snapshot),
826
        });
827
    }
828
    out
829
}
830
831
/// One file's part of a diff, for `oxy diff --json`.
832
#[derive(Clone, Debug)]
833
pub struct FileDiff {
834
    pub path: String,
835
    /// `added`, `removed`, `modified`, `renamed`, `mode`, `replaced`.
836
    pub kind: String,
837
    pub hunks: Vec<DiffHunk>,
838
    /// For renames, the previous path.
839
    pub from: Option<String>,
840
}
841
842
/// Lines inserted after `base_line` (0 = before the first line) and lines
843
/// removed, with their base line numbers.
844
#[derive(Clone, Debug, Default)]
845
pub struct DiffHunk {
846
    pub base_line: u32,
847
    pub added: Vec<Vec<u8>>,
848
    pub removed: Vec<(u32, Vec<u8>)>,
849
}
850
851
impl Repo {
852
    /// The content of `path` in a state: `heads`, or the working copy's base.
853
    pub fn file_at(&self, path: &str, heads: Option<&[ChangeHash]>) -> Result<Vec<u8>> {
854
        let snapshot = match heads {
855
            Some(h) => self.load_state(h)?.materialize(),
856
            None => {
857
                let (_, wc) = self.working_copy()?;
858
                self.load_state(&wc.deps)?.materialize()
859
            }
860
        };
861
        let Some(f) = snapshot.files.get(path) else {
862
            return fail(format!("{path} is not in that state"));
863
        };
864
        match &f.content {
865
            FileContent::Dir => fail(format!("{path} is a directory")),
866
            FileContent::Text { bytes, .. } => Ok(bytes.clone()),
867
            FileContent::Opaque { blobs } => match blobs.first() {
868
                Some(b) => self.read_blob(b),
869
                None => Ok(vec![]),
870
            },
871
        }
872
    }
873
874
    /// Restore `paths` (files or directories) to the working copy's base:
875
    /// edits are undone, additions removed, removals put back. Returns the
876
    /// number of paths touched.
877
    pub fn discard(&self, paths: &[String]) -> Result<usize> {
878
        let snap = self.snapshot("oxy discard")?;
879
        let under = |p: &str| {
880
            paths
881
                .iter()
882
                .any(|x| p == x || p.starts_with(&format!("{}/", x.trim_end_matches('/'))))
883
        };
884
        let attrs = Repo::state_attributes(&snap.base_snapshot);
885
        let mut n = 0;
886
        for s in &snap.statuses {
887
            if !under(&s.path) {
888
                continue;
889
            }
890
            match snap.base_snapshot.files.get(&s.path) {
891
                None => {
892
                    // Added (or the new name of a rename): remove it.
893
                    let full = self.root.join(&s.path);
894
                    if full.is_dir() {
895
                        let _ = fs::remove_dir_all(&full);
896
                    } else {
897
                        let _ = fs::remove_file(&full);
898
                    }
899
                    n += 1;
900
                }
901
                Some(f) => {
902
                    match &f.content {
903
                        FileContent::Dir => fs::create_dir_all(self.root.join(&s.path))?,
904
                        FileContent::Text { bytes, .. } => {
905
                            let on_disk: std::borrow::Cow<[u8]> = if attrs.lookup(&s.path).eol
906
                                == Some(crate::attributes::Eol::Crlf)
907
                            {
908
                                crate::attributes::to_crlf(bytes).into()
909
                            } else {
910
                                bytes.as_slice().into()
911
                            };
912
                            self.write_file(&s.path, &on_disk, f.mode.exec)?;
913
                        }
914
                        FileContent::Opaque { blobs } => {
915
                            let bytes = match blobs.first() {
916
                                Some(b) => self.read_blob(b)?,
917
                                None => vec![],
918
                            };
919
                            if f.kind == NodeKind::Symlink {
920
                                self.write_symlink(&s.path, &bytes)?;
921
                            } else if f.kind == NodeKind::File {
922
                                self.write_file(&s.path, &bytes, f.mode.exec)?;
923
                            }
924
                        }
925
                    }
926
                    n += 1;
927
                }
928
            }
929
        }
930
        // A rename's old name is not in the statuses; put it back too.
931
        for (p, f) in &snap.base_snapshot.files {
932
            if under(p)
933
                && !self.root.join(p).exists()
934
                && f.kind != NodeKind::Dir
935
                && f.kind != NodeKind::Subrepo
936
                && !snap.statuses.iter().any(|s| s.path == *p)
937
            {
938
                let bytes = match &f.content {
939
                    FileContent::Text { bytes, .. } => bytes.clone(),
940
                    FileContent::Opaque { blobs } => blobs
941
                        .first()
942
                        .map(|b| self.read_blob(b))
943
                        .transpose()?
944
                        .unwrap_or_default(),
945
                    FileContent::Dir => continue,
946
                };
947
                if f.kind == NodeKind::Symlink {
948
                    self.write_symlink(p, &bytes)?
949
                } else {
950
                    self.write_file(p, &bytes, f.mode.exec)?
951
                }
952
                n += 1;
953
            }
954
        }
955
        self.drop_manifest();
956
        Ok(n)
957
    }
958
959
    /// Undo the working-copy hunks `indices` (as `hunks` numbers them) on
960
    /// disk, keeping the others: the files are rewritten from the base plus
961
    /// the remaining hunks.
962
    pub fn discard_hunks(&self, indices: &[usize]) -> Result<usize> {
963
        let (snap, hunks) = self.hunks()?;
964
        let keep: Vec<usize> = hunks
965
            .iter()
966
            .map(|h| h.index)
967
            .filter(|i| !indices.contains(i))
968
            .collect();
969
        let (ops, edits) = select_hunks(&snap.wc, &keep);
970
        let dropped_nodes: BTreeSet<NodeId> = hunks
971
            .iter()
972
            .filter(|h| indices.contains(&h.index))
973
            .map(|h| {
974
                if h.index < snap.wc.tree_ops.len() {
975
                    snap.wc.tree_ops[h.index].node()
976
                } else {
977
                    snap.wc.edits[h.index - snap.wc.tree_ops.len()].node()
978
                }
979
            })
980
            .collect();
981
        let mut partial = snap.wc.clone();
982
        partial.tree_ops = ops;
983
        partial.edits = edits;
984
        partial.normalize();
985
        let mut st = snap.base.clone();
986
        st.add_unchecked(partial);
987
        let target = st.materialize();
988
        let by_node_target = target.tree.by_node();
989
        let by_node_base = snap.base_snapshot.tree.by_node();
990
        let attrs = Repo::state_attributes(&target);
991
        let mut n = 0;
992
        for node in dropped_nodes {
993
            match by_node_target.get(&node) {
994
                Some(e) => {
995
                    let f = &target.files[&e.path];
996
                    match &f.content {
997
                        FileContent::Dir => {}
998
                        FileContent::Text { bytes, .. } => {
999
                            let on_disk: std::borrow::Cow<[u8]> = if attrs.lookup(&e.path).eol
1000
                                == Some(crate::attributes::Eol::Crlf)
1001
                            {
1002
                                crate::attributes::to_crlf(bytes).into()
1003
                            } else {
1004
                                bytes.as_slice().into()
1005
                            };
1006
                            self.write_file(&e.path, &on_disk, f.mode.exec)?;
1007
                        }
1008
                        FileContent::Opaque { blobs } => {
1009
                            let bytes = blobs
1010
                                .first()
1011
                                .map(|b| self.read_blob(b))
1012
                                .transpose()?
1013
                                .unwrap_or_default();
1014
                            if f.kind == NodeKind::Symlink {
1015
                                self.write_symlink(&e.path, &bytes)?
1016
                            } else {
1017
                                self.write_file(&e.path, &bytes, f.mode.exec)?
1018
                            }
1019
                        }
1020
                    }
1021
                    // A discarded rename: the new name goes.
1022
                    if let Some(old_path) = snap
1023
                        .statuses
1024
                        .iter()
1025
                        .find(|s| {
1026
                            s.status == ChangeStatus::Renamed && !target.files.contains_key(&s.path)
1027
                        })
1028
                        .map(|s| s.path.clone())
1029
                    {
1030
                        let _ = fs::remove_file(self.root.join(old_path));
1031
                    }
1032
                    n += 1;
1033
                }
1034
                None => {
1035
                    // The node exists in neither target nor base with a live path: an addition to remove.
1036
                    if let Some(added) = snap.statuses.iter().find(|s| {
1037
                        s.status == ChangeStatus::Added
1038
                            && !target.files.contains_key(&s.path)
1039
                            && !by_node_base.contains_key(&node)
1040
                    }) {
1041
                        let full = self.root.join(&added.path);
1042
                        if full.is_dir() {
1043
                            let _ = fs::remove_dir_all(&full);
1044
                        } else {
1045
                            let _ = fs::remove_file(&full);
1046
                        }
1047
                        n += 1;
1048
                    }
1049
                }
1050
            }
1051
        }
1052
        self.drop_manifest();
1053
        Ok(n)
1054
    }
1055
1056
    /// The diff of the working copy (`None`) or of a change, per file with
1057
    /// line-numbered hunks (spec: `oxy diff --json`).
1058
    pub fn diff_files(&self, change: Option<&ChangeHash>) -> Result<Vec<FileDiff>> {
1059
        let (c, base) = match change {
1060
            Some(h) => {
1061
                let c = self.store.get_change(h)?;
1062
                let base = self.load_state(&c.deps)?;
1063
                (c, base)
1064
            }
1065
            None => {
1066
                let snap = self.snapshot("oxy diff")?;
1067
                (snap.wc, snap.base)
1068
            }
1069
        };
1070
        let base_snapshot = base.materialize();
1071
        Ok(diff_files_of(&c, &base, &base_snapshot))
1072
    }
1073
1074
    /// The log restricted to changes touching `path` (its node, so renames
1075
    /// are followed), on the current bookmark.
1076
    pub fn log_for_path(&self, path: &str) -> Result<Vec<LogEntry>> {
1077
        let heads = self.bookmark_heads()?;
1078
        if self.is_bare() {
1079
            return self.log_for_path_in(path, &heads);
1080
        }
1081
        let entries = self.log()?;
1082
        let (_, wc) = self.working_copy()?;
1083
        let base_snapshot = self.load_state(&wc.deps)?.materialize();
1084
        let state_snapshot = self.load_state(&heads)?.materialize();
1085
        let node = base_snapshot
1086
            .files
1087
            .get(path)
1088
            .or_else(|| state_snapshot.files.get(path))
1089
            .map(|f| f.node);
1090
        let Some(node) = node else {
1091
            return fail(format!("{path} is not tracked"));
1092
        };
1093
        Ok(self.entries_touching(entries, node))
1094
    }
1095
1096
    /// The log of the state with these heads restricted to changes touching
1097
    /// `path` (its node, so renames are followed).
1098
    pub fn log_for_path_in(&self, path: &str, heads: &[ChangeHash]) -> Result<Vec<LogEntry>> {
1099
        let entries = self.log_state(heads)?;
1100
        let snapshot = self.load_state(heads)?.materialize();
1101
        let Some(node) = snapshot.files.get(path).map(|f| f.node) else {
1102
            return fail(format!("{path} is not in that state"));
1103
        };
1104
        Ok(self.entries_touching(entries, node))
1105
    }
1106
1107
    fn entries_touching(&self, entries: Vec<LogEntry>, node: NodeId) -> Vec<LogEntry> {
1108
        let mut out = Vec::new();
1109
        for e in entries {
1110
            let Ok(c) = self.store.get_change(&e.hash) else {
1111
                continue;
1112
            };
1113
            if c.tree_ops.iter().any(|o| o.node() == node)
1114
                || c.edits.iter().any(|x| x.node() == node)
1115
            {
1116
                out.push(e);
1117
            }
1118
        }
1119
        out
1120
    }
1121
}
1122
1123
/// Per-file hunks of `change` against `base`.
1124
pub fn diff_files_of(change: &Change, base: &State, base_snapshot: &Snapshot) -> Vec<FileDiff> {
1125
    let by_node = base_snapshot.tree.by_node();
1126
    let mut new_names: HashMap<NodeId, (NodeId, String, NodeKind)> = HashMap::new();
1127
    for op in &change.tree_ops {
1128
        if let TreeOp::AddNode {
1129
            node,
1130
            parent,
1131
            name,
1132
            kind,
1133
            ..
1134
        } = op
1135
        {
1136
            new_names.insert(*node, (*parent, name.clone(), *kind));
1137
        }
1138
    }
1139
    let path_of = |n: &NodeId| -> String {
1140
        path_of_node(n, &by_node, &new_names).unwrap_or_else(|| format!("<node {}>", n.short(8)))
1141
    };
1142
    let mut files: BTreeMap<NodeId, FileDiff> = BTreeMap::new();
1143
    let mut order: Vec<NodeId> = Vec::new();
1144
    let mut entry = |files: &mut BTreeMap<NodeId, FileDiff>, n: NodeId, kind: &str| {
1145
        if let std::collections::btree_map::Entry::Vacant(v) = files.entry(n) {
1146
            order.push(n);
1147
            v.insert(FileDiff {
1148
                path: path_of(&n),
1149
                kind: kind.to_string(),
1150
                hunks: vec![],
1151
                from: None,
1152
            });
1153
        }
1154
    };
1155
    for op in &change.tree_ops {
1156
        match op {
1157
            TreeOp::AddNode { node, kind, .. } => {
1158
                if *kind != NodeKind::Dir {
1159
                    entry(&mut files, *node, "added");
1160
                }
1161
            }
1162
            TreeOp::RemoveNode { node, .. } => {
1163
                entry(&mut files, *node, "removed");
1164
                if let Some(e) = by_node.get(node) {
1165
                    files.get_mut(node).unwrap().path = e.path.clone();
1166
                }
1167
            }
1168
            TreeOp::Move {
1169
                node, parent, name, ..
1170
            } => {
1171
                entry(&mut files, *node, "renamed");
1172
                let f = files.get_mut(node).unwrap();
1173
                f.from = by_node.get(node).map(|e| e.path.clone());
1174
                let dir = if parent.is_root() {
1175
                    String::new()
1176
                } else {
1177
                    path_of_node(parent, &by_node, &new_names).unwrap_or_default()
1178
                };
1179
                f.path = if dir.is_empty() {
1180
                    name.clone()
1181
                } else {
1182
                    format!("{dir}/{name}")
1183
                };
1184
            }
1185
            TreeOp::SetMode { node, .. } => entry(&mut files, *node, "mode"),
1186
        }
1187
    }
1188
    // Base line numbers per node, 1-based.
1189
    let mut line_of: HashMap<NodeId, HashMap<(ChangeHash, u32), u32>> = HashMap::new();
1190
    let mut lines_for = |n: &NodeId| -> HashMap<(ChangeHash, u32), u32> {
1191
        line_of
1192
            .entry(*n)
1193
            .or_insert_with(|| {
1194
                base.live_lines(n)
1195
                    .into_iter()
1196
                    .enumerate()
1197
                    .map(|(i, (k, _))| (k, i as u32 + 1))
1198
                    .collect()
1199
            })
1200
            .clone()
1201
    };
1202
    for e in &change.edits {
1203
        let n = e.node();
1204
        let is_new = new_names.contains_key(&n);
1205
        entry(&mut files, n, if is_new { "added" } else { "modified" });
1206
        let f = files.get_mut(&n).unwrap();
1207
        match e {
1208
            Edit::Insert { after, lines, .. } => {
1209
                let map = lines_for(&n);
1210
                let base_line = match after {
1211
                    AtomRef::Start => 0,
1212
                    AtomRef::End => map.len() as u32,
1213
                    AtomRef::Atom { change, index } if change.is_zero() => {
1214
                        f.hunks.last().map(|h| h.base_line).unwrap_or(0)
1215
                    }
1216
                    AtomRef::Atom { change, index } => {
1217
                        map.get(&(*change, *index)).copied().unwrap_or(0)
1218
                    }
1219
                };
1220
                f.hunks.push(DiffHunk {
1221
                    base_line,
1222
                    added: lines.clone(),
1223
                    removed: vec![],
1224
                });
1225
            }
1226
            Edit::Delete { atoms, .. } => {
1227
                let map = lines_for(&n);
1228
                let mut removed = Vec::new();
1229
                for r in atoms {
1230
                    for i in r.from..r.to {
1231
                        let line = map.get(&(r.change, i)).copied().unwrap_or(0);
1232
                        let text = base
1233
                            .file(&n)
1234
                            .and_then(|g| g.content(&(r.change, i)))
1235
                            .unwrap_or(b"")
1236
                            .to_vec();
1237
                        removed.push((line, text));
1238
                    }
1239
                }
1240
                let base_line = removed
1241
                    .first()
1242
                    .map(|(l, _)| l.saturating_sub(1))
1243
                    .unwrap_or(0);
1244
                f.hunks.push(DiffHunk {
1245
                    base_line,
1246
                    added: vec![],
1247
                    removed,
1248
                });
1249
            }
1250
            Edit::Replace { .. } => {
1251
                if !is_new {
1252
                    f.kind = "replaced".into();
1253
                }
1254
            }
1255
        }
1256
    }
1257
    order.into_iter().filter_map(|n| files.remove(&n)).collect()
1258
}
1259
1260
/// Builds the tree ops and edits of a working-copy change against a base.
1261
struct ChangeBuilder<'a> {
1262
    base: &'a State,
1263
    base_snapshot: &'a Snapshot,
1264
    tree_ops: Vec<TreeOp>,
1265
    edits: Vec<Edit>,
1266
    statuses: Vec<PathStatus>,
1267
    dir_nodes: HashMap<String, NodeId>,
1268
    reuse: HashMap<String, (NodeId, NodeKind)>,
1269
    /// Changes that contributed to conflicts this working copy resolves.
1270
    contributors: BTreeSet<ChangeHash>,
1271
    resolves: bool,
1272
    attrs: crate::attributes::Attributes,
1273
    blobs: HashMap<String, ObjectRef>,
1274
}
1275
1276
impl<'a> ChangeBuilder<'a> {
1277
    fn new(
1278
        base: &'a State,
1279
        base_snapshot: &'a Snapshot,
1280
        reuse: HashMap<String, (NodeId, NodeKind)>,
1281
    ) -> Self {
1282
        let mut dir_nodes: HashMap<String, NodeId> = HashMap::new();
1283
        dir_nodes.insert(String::new(), NodeId::ROOT);
1284
        for (p, f) in &base_snapshot.files {
1285
            if f.kind == NodeKind::Dir {
1286
                dir_nodes.insert(p.clone(), f.node);
1287
            }
1288
        }
1289
        ChangeBuilder {
1290
            base,
1291
            base_snapshot,
1292
            tree_ops: vec![],
1293
            edits: vec![],
1294
            statuses: vec![],
1295
            dir_nodes,
1296
            reuse,
1297
            contributors: BTreeSet::new(),
1298
            resolves: false,
1299
            attrs: crate::attributes::Attributes::default(),
1300
            blobs: HashMap::new(),
1301
        }
1302
    }
1303
1304
    fn with_attributes(mut self, attrs: crate::attributes::Attributes) -> Self {
1305
        self.attrs = attrs;
1306
        self
1307
    }
1308
1309
    /// Whether a file is opaque: forced by `binary`, forced text by `text`
1310
    /// only when it has no NUL bytes, else sniffed.
1311
    /// The blob for an opaque entry: the cached one, else stored now.
1312
    fn blob_of(
1313
        &mut self,
1314
        repo: &Repo,
1315
        path: &str,
1316
        e: &FsEntry,
1317
        nocompress: bool,
1318
    ) -> Result<ObjectRef> {
1319
        let b = match e.blob {
1320
            Some(b) => b,
1321
            None => repo.store_blob_for(&e.content, nocompress)?,
1322
        };
1323
        self.blobs.insert(path.to_string(), b);
1324
        Ok(b)
1325
    }
1326
1327
    fn opaque_for(&self, path: &str, e: &FsEntry) -> bool {
1328
        if e.blob.is_some() {
1329
            return true;
1330
        }
1331
        if e.kind == NodeKind::Symlink || e.kind == NodeKind::Subrepo {
1332
            return true;
1333
        }
1334
        match self.attrs.lookup(path).binary {
1335
            Some(true) => true,
1336
            Some(false) => is_binary(&e.content),
1337
            None => is_binary(&e.content),
1338
        }
1339
    }
1340
1341
    /// Text content as stored: `\r\n` normalized for `eol=` files.
1342
    fn stored_text(&self, path: &str, content: &[u8]) -> Vec<u8> {
1343
        if self.attrs.lookup(path).eol.is_some() {
1344
            crate::attributes::normalize_eol(content)
1345
        } else {
1346
            content.to_vec()
1347
        }
1348
    }
1349
1350
    fn reused_node(&self, path: &str, kind: NodeKind) -> Option<NodeId> {
1351
        self.reuse
1352
            .get(path)
1353
            .filter(|(_, k)| *k == kind)
1354
            .map(|(n, _)| *n)
1355
    }
1356
1357
    fn ensure_dir(&mut self, path: &str) -> NodeId {
1358
        if let Some(n) = self.dir_nodes.get(path) {
1359
            return *n;
1360
        }
1361
        let mut parent = NodeId::ROOT;
1362
        let mut prefix = String::new();
1363
        for comp in path.split('/') {
1364
            if !prefix.is_empty() {
1365
                prefix.push('/');
1366
            }
1367
            prefix.push_str(comp);
1368
            parent = match self.dir_nodes.get(&prefix) {
1369
                Some(n) => *n,
1370
                None => {
1371
                    let node = self
1372
                        .reused_node(&prefix, NodeKind::Dir)
1373
                        .unwrap_or_else(NodeId::random);
1374
                    self.tree_ops.push(TreeOp::AddNode {
1375
                        node,
1376
                        kind: NodeKind::Dir,
1377
                        mode: Mode::default(),
1378
                        parent,
1379
                        name: comp.to_string(),
1380
                    });
1381
                    self.dir_nodes.insert(prefix.clone(), node);
1382
                    node
1383
                }
1384
            };
1385
        }
1386
        parent
1387
    }
1388
1389
    fn add_path(&mut self, repo: &Repo, path: &str, e: &FsEntry) -> Result<()> {
1390
        let (dir, name) = split_path(path);
1391
        let parent = self.ensure_dir(dir);
1392
        let node = self
1393
            .reused_node(path, e.kind)
1394
            .unwrap_or_else(NodeId::random);
1395
        let opaque = self.opaque_for(path, e);
1396
        let nocompress = self.attrs.lookup(path).nocompress;
1397
        self.tree_ops.push(TreeOp::AddNode {
1398
            node,
1399
            kind: e.kind,
1400
            mode: Mode {
1401
                exec: e.exec,
1402
                opaque,
1403
            },
1404
            parent,
1405
            name: name.to_string(),
1406
        });
1407
        if opaque {
1408
            let blob = self.blob_of(repo, path, e, nocompress)?;
1409
            self.edits.push(Edit::Replace {
1410
                node,
1411
                old: None,
1412
                new: Some(blob),
1413
            });
1414
        } else if !e.content.is_empty() {
1415
            let content = self.stored_text(path, &e.content);
1416
            self.edits.push(Edit::Insert {
1417
                node,
1418
                after: crate::objects::AtomRef::Start,
1419
                before: crate::objects::AtomRef::End,
1420
                lines: split_lines(&content).iter().map(|l| l.to_vec()).collect(),
1421
            });
1422
        }
1423
        self.statuses.push(PathStatus {
1424
            path: path.to_string(),
1425
            status: ChangeStatus::Added,
1426
        });
1427
        Ok(())
1428
    }
1429
1430
    /// Move the node at `old` to `new` and apply `e`'s content to it.
1431
    fn move_path(
1432
        &mut self,
1433
        repo: &Repo,
1434
        old: &str,
1435
        new: &str,
1436
        e: &FsEntry,
1437
        expected: &crate::state::FileState,
1438
    ) -> Result<()> {
1439
        let entry = &self.base_snapshot.tree.entries[old];
1440
        let (dir, name) = split_path(new);
1441
        let parent = self.ensure_dir(dir);
1442
        self.tree_ops.push(TreeOp::Move {
1443
            node: expected.node,
1444
            old: op_ref(entry.placement),
1445
            parent,
1446
            name: name.to_string(),
1447
        });
1448
        self.update_path(repo, old, e, expected)?;
1449
        // update_path reports under the old path; the rename is what the user sees.
1450
        self.statuses.retain(|s| s.path != old);
1451
        self.statuses.push(PathStatus {
1452
            path: new.to_string(),
1453
            status: ChangeStatus::Renamed,
1454
        });
1455
        Ok(())
1456
    }
1457
1458
    fn remove_path(&mut self, path: &str, expected: &crate::state::FileState) {
1459
        let entry = &self.base_snapshot.tree.entries[path];
1460
        self.tree_ops.push(TreeOp::RemoveNode {
1461
            node: expected.node,
1462
            placement: op_ref(entry.placement),
1463
        });
1464
        if path.contains(".oxy-conflict-") || expected.is_conflicted() {
1465
            self.resolves = true;
1466
        }
1467
        self.statuses.push(PathStatus {
1468
            path: path.to_string(),
1469
            status: ChangeStatus::Removed,
1470
        });
1471
    }
1472
1473
    fn update_path(
1474
        &mut self,
1475
        repo: &Repo,
1476
        path: &str,
1477
        e: &FsEntry,
1478
        expected: &crate::state::FileState,
1479
    ) -> Result<()> {
1480
        if expected.kind != e.kind {
1481
            self.remove_path(path, expected);
1482
            self.statuses.pop();
1483
            self.add_path(repo, path, e)?;
1484
            self.statuses.pop();
1485
            self.statuses.push(PathStatus {
1486
                path: path.to_string(),
1487
                status: ChangeStatus::Modified,
1488
            });
1489
            return Ok(());
1490
        }
1491
        let entry = &self.base_snapshot.tree.entries[path];
1492
        let node = expected.node;
1493
        let mode_atom = entry.mode_atom.map(op_ref);
1494
        let mut status: Option<ChangeStatus> = None;
1495
        let wants_opaque = self.opaque_for(path, e);
1496
        let nocompress = self.attrs.lookup(path).nocompress;
1497
        let disk_text = self.stored_text(path, &e.content);
1498
        match &expected.content {
1499
            FileContent::Dir => {}
1500
            FileContent::Text {
1501
                bytes,
1502
                materialized,
1503
            } => {
1504
                if materialized.is_conflicted() {
1505
                    if bytes == &disk_text {
1506
                        return Ok(());
1507
                    }
1508
                    if has_conflict_markers(&e.content) {
1509
                        self.statuses.push(PathStatus {
1510
                            path: path.to_string(),
1511
                            status: ChangeStatus::ConflictEdited,
1512
                        });
1513
                        return Ok(());
1514
                    }
1515
                    // Resolution (spec §9.6): diff against the unconflicted lines
1516
                    // with each region as a gap, then retire every region atom.
1517
                    // Whatever the author kept from a region is re-inserted as
1518
                    // new atoms, which leaves the graph totally ordered.
1519
                    let regions = self.base.conflict_regions(&node);
1520
                    let mut edits = text_edits(node, &regions.plain, &disk_text);
1521
                    if !regions.region_atoms.is_empty() {
1522
                        edits.insert(
1523
                            0,
1524
                            Edit::Delete {
1525
                                node,
1526
                                atoms: ranges(&regions.region_atoms),
1527
                            },
1528
                        );
1529
                    }
1530
                    self.edits.extend(edits);
1531
                    self.contributors.extend(regions.contributors);
1532
                    self.resolves = true;
1533
                    if e.exec != expected.mode.exec {
1534
                        if let Some(old) = mode_atom {
1535
                            self.tree_ops.push(TreeOp::SetMode {
1536
                                node,
1537
                                old,
1538
                                mode: Mode {
1539
                                    exec: e.exec,
1540
                                    opaque: false,
1541
                                },
1542
                            });
1543
                        }
1544
                    }
1545
                    self.statuses.push(PathStatus {
1546
                        path: path.to_string(),
1547
                        status: ChangeStatus::Resolved,
1548
                    });
1549
                    return Ok(());
1550
                }
1551
                if wants_opaque {
1552
                    // Text → opaque (spec §7.5), by content or by attribute.
1553
                    if let Some(old) = mode_atom {
1554
                        self.tree_ops.push(TreeOp::SetMode {
1555
                            node,
1556
                            old,
1557
                            mode: Mode {
1558
                                exec: e.exec,
1559
                                opaque: true,
1560
                            },
1561
                        });
1562
                    }
1563
                    let live: Vec<_> = repo_live_keys(self.base, &node);
1564
                    if !live.is_empty() {
1565
                        self.edits.push(Edit::Delete {
1566
                            node,
1567
                            atoms: ranges(&live),
1568
                        });
1569
                    }
1570
                    let blob = self.blob_of(repo, path, e, nocompress)?;
1571
                    self.edits.push(Edit::Replace {
1572
                        node,
1573
                        old: None,
1574
                        new: Some(blob),
1575
                    });
1576
                    status = Some(ChangeStatus::Modified);
1577
                } else if bytes != &disk_text {
1578
                    let old = self.base.live_lines(&node);
1579
                    let edits = text_edits(node, &old, &disk_text);
1580
                    if !edits.is_empty() {
1581
                        self.edits.extend(edits);
1582
                        status = Some(ChangeStatus::Modified);
1583
                    }
1584
                }
1585
                let switched_to_opaque = wants_opaque;
1586
                if !switched_to_opaque && e.exec != expected.mode.exec {
1587
                    if let Some(old) = mode_atom {
1588
                        self.tree_ops.push(TreeOp::SetMode {
1589
                            node,
1590
                            old,
1591
                            mode: Mode {
1592
                                exec: e.exec,
1593
                                opaque: false,
1594
                            },
1595
                        });
1596
                        status.get_or_insert(ChangeStatus::ModeChanged);
1597
                    }
1598
                }
1599
            }
1600
            FileContent::Opaque { blobs } => {
1601
                let new_ref = e.blob.unwrap_or_else(|| Repo::blob_ref(&e.content));
1602
                if e.kind == NodeKind::File && wants_opaque {
1603
                    // Unchanged or replaced, the file stays opaque: remember its blob.
1604
                    self.blobs.insert(path.to_string(), new_ref);
1605
                }
1606
                if blobs.len() > 1 {
1607
                    if !blobs.contains(&new_ref) {
1608
                        self.statuses.push(PathStatus {
1609
                            path: path.to_string(),
1610
                            status: ChangeStatus::ConflictEdited,
1611
                        });
1612
                    }
1613
                    return Ok(());
1614
                }
1615
                let current = blobs.first().copied();
1616
                if current != Some(new_ref) {
1617
                    if e.kind == NodeKind::File && !wants_opaque {
1618
                        // Opaque → text (spec §7.5).
1619
                        if let Some(old) = mode_atom {
1620
                            self.tree_ops.push(TreeOp::SetMode {
1621
                                node,
1622
                                old,
1623
                                mode: Mode {
1624
                                    exec: e.exec,
1625
                                    opaque: false,
1626
                                },
1627
                            });
1628
                        }
1629
                        self.edits.push(Edit::Replace {
1630
                            node,
1631
                            old: current,
1632
                            new: None,
1633
                        });
1634
                        if !e.content.is_empty() {
1635
                            self.edits.push(Edit::Insert {
1636
                                node,
1637
                                after: crate::objects::AtomRef::Start,
1638
                                before: crate::objects::AtomRef::End,
1639
                                lines: split_lines(&e.content).iter().map(|l| l.to_vec()).collect(),
1640
                            });
1641
                        }
1642
                    } else {
1643
                        let blob = self.blob_of(repo, path, e, nocompress)?;
1644
                        self.edits.push(Edit::Replace {
1645
                            node,
1646
                            old: current,
1647
                            new: Some(blob),
1648
                        });
1649
                    }
1650
                    status = Some(ChangeStatus::Modified);
1651
                } else if e.kind == NodeKind::File && e.exec != expected.mode.exec {
1652
                    if let Some(old) = mode_atom {
1653
                        self.tree_ops.push(TreeOp::SetMode {
1654
                            node,
1655
                            old,
1656
                            mode: Mode {
1657
                                exec: e.exec,
1658
                                opaque: true,
1659
                            },
1660
                        });
1661
                        status = Some(ChangeStatus::ModeChanged);
1662
                    }
1663
                }
1664
            }
1665
        }
1666
        if let Some(s) = status {
1667
            self.statuses.push(PathStatus {
1668
                path: path.to_string(),
1669
                status: s,
1670
            });
1671
        }
1672
        Ok(())
1673
    }
1674
}
1675
1676
fn repo_live_keys(base: &State, node: &NodeId) -> Vec<crate::graph::AtomKey> {
1677
    base.live_lines(node).into_iter().map(|(k, _)| k).collect()
1678
}
1679
1680
/// The changes a change's scope references (spec §8.1): introducers of every
1681
/// atom, placement, and mode it touches, and of every node it operates on.
1682
pub fn referenced_changes(change: &Change, base: &State) -> BTreeSet<ChangeHash> {
1683
    let mut out = BTreeSet::new();
1684
    let opref = |r: &OpRef, out: &mut BTreeSet<ChangeHash>| {
1685
        if !r.change.is_zero() {
1686
            out.insert(r.change);
1687
        }
1688
    };
1689
    let mut nodes: Vec<NodeId> = Vec::new();
1690
    for op in &change.tree_ops {
1691
        match op {
1692
            TreeOp::AddNode { parent, .. } => nodes.push(*parent),
1693
            TreeOp::RemoveNode { node, placement } => {
1694
                nodes.push(*node);
1695
                opref(placement, &mut out);
1696
            }
1697
            TreeOp::Move {
1698
                node, old, parent, ..
1699
            } => {
1700
                nodes.push(*node);
1701
                nodes.push(*parent);
1702
                opref(old, &mut out);
1703
            }
1704
            TreeOp::SetMode { node, old, .. } => {
1705
                nodes.push(*node);
1706
                opref(old, &mut out);
1707
            }
1708
        }
1709
    }
1710
    for e in &change.edits {
1711
        nodes.push(e.node());
1712
        match e {
1713
            Edit::Insert { after, before, .. } => {
1714
                for r in [after, before] {
1715
                    if let crate::objects::AtomRef::Atom { change, .. } = r {
1716
                        if !change.is_zero() {
1717
                            out.insert(*change);
1718
                        }
1719
                    }
1720
                }
1721
            }
1722
            Edit::Delete { atoms, .. } => {
1723
                for r in atoms {
1724
                    if !r.change.is_zero() {
1725
                        out.insert(r.change);
1726
                    }
1727
                }
1728
            }
1729
            Edit::Replace { .. } => {}
1730
        }
1731
    }
1732
    for n in nodes {
1733
        if let Some(h) = base.tree().introducer(&n) {
1734
            out.insert(h);
1735
        }
1736
    }
1737
    out
1738
}
1739
1740
/// Paths of the nodes a change adds on top of `base_snapshot`.
1741
pub fn added_node_paths(
1742
    change: &Change,
1743
    base_snapshot: &Snapshot,
1744
) -> HashMap<String, (NodeId, NodeKind)> {
1745
    let by_node = base_snapshot.tree.by_node();
1746
    let mut new_names: HashMap<NodeId, (NodeId, String, NodeKind)> = HashMap::new();
1747
    for op in &change.tree_ops {
1748
        if let TreeOp::AddNode {
1749
            node,
1750
            parent,
1751
            name,
1752
            kind,
1753
            ..
1754
        } = op
1755
        {
1756
            new_names.insert(*node, (*parent, name.clone(), *kind));
1757
        }
1758
    }
1759
    let mut out = HashMap::new();
1760
    for (node, (_, _, kind)) in &new_names {
1761
        if let Some(path) = path_of_node(node, &by_node, &new_names) {
1762
            out.insert(path, (*node, *kind));
1763
        }
1764
    }
1765
    out
1766
}
1767
1768
fn path_of_node(
1769
    n: &NodeId,
1770
    by_node: &HashMap<NodeId, &crate::tree::TreeEntry>,
1771
    new_names: &HashMap<NodeId, (NodeId, String, NodeKind)>,
1772
) -> Option<String> {
1773
    if let Some(e) = by_node.get(n) {
1774
        return Some(e.path.clone());
1775
    }
1776
    let mut parts = Vec::new();
1777
    let mut cur = *n;
1778
    loop {
1779
        if cur.is_root() {
1780
            break;
1781
        }
1782
        if let Some(e) = by_node.get(&cur) {
1783
            if !e.path.is_empty() {
1784
                parts.push(e.path.clone());
1785
            }
1786
            break;
1787
        }
1788
        let (parent, name, _) = new_names.get(&cur)?;
1789
        parts.push(name.clone());
1790
        cur = *parent;
1791
    }
1792
    parts.reverse();
1793
    Some(parts.join("/"))
1794
}
1795
1796
/// Render a change's operations with line content, using `base` for deleted lines.
1797
pub fn render_change(change: &Change, base: &State, base_snapshot: &Snapshot) -> String {
1798
    let by_node = base_snapshot.tree.by_node();
1799
    let mut new_names: HashMap<NodeId, (NodeId, String, NodeKind)> = HashMap::new();
1800
    for op in &change.tree_ops {
1801
        if let TreeOp::AddNode {
1802
            node,
1803
            parent,
1804
            name,
1805
            kind,
1806
            ..
1807
        } = op
1808
        {
1809
            new_names.insert(*node, (*parent, name.clone(), *kind));
1810
        }
1811
    }
1812
    let path_of = |n: &NodeId| -> String {
1813
        path_of_node(n, &by_node, &new_names).unwrap_or_else(|| format!("<node {}>", n.short(8)))
1814
    };
1815
1816
    let mut out = String::new();
1817
    for op in &change.tree_ops {
1818
        match op {
1819
            TreeOp::AddNode {
1820
                node, kind, mode, ..
1821
            } => {
1822
                out.push_str(&format!(
1823
                    "A {} ({:?}{}{})\n",
1824
                    path_of(node),
1825
                    kind,
1826
                    if mode.exec { ", exec" } else { "" },
1827
                    if mode.opaque { ", opaque" } else { "" }
1828
                ));
1829
            }
1830
            TreeOp::RemoveNode { node, .. } => out.push_str(&format!("D {}\n", path_of(node))),
1831
            TreeOp::Move { node, name, .. } => {
1832
                out.push_str(&format!("R {} -> {}\n", path_of(node), name))
1833
            }
1834
            TreeOp::SetMode { node, mode, .. } => {
1835
                out.push_str(&format!(
1836
                    "M {} mode: exec={} opaque={}\n",
1837
                    path_of(node),
1838
                    mode.exec,
1839
                    mode.opaque
1840
                ));
1841
            }
1842
        }
1843
    }
1844
    let mut last_node: Option<NodeId> = None;
1845
    for e in &change.edits {
1846
        let n = e.node();
1847
        if last_node != Some(n) {
1848
            out.push_str(&format!("--- {}\n", path_of(&n)));
1849
            last_node = Some(n);
1850
        }
1851
        match e {
1852
            Edit::Insert { lines, .. } => {
1853
                for l in lines {
1854
                    out.push('+');
1855
                    out.push_str(&String::from_utf8_lossy(l));
1856
                    if !l.ends_with(b"\n") {
1857
                        out.push('\n');
1858
                    }
1859
                }
1860
            }
1861
            Edit::Delete { atoms, .. } => {
1862
                for r in atoms {
1863
                    for i in r.from..r.to {
1864
                        let content = base
1865
                            .file(&n)
1866
                            .and_then(|g| g.content(&(r.change, i)))
1867
                            .unwrap_or(b"<unknown>\n");
1868
                        out.push('-');
1869
                        out.push_str(&String::from_utf8_lossy(content));
1870
                        if !content.ends_with(b"\n") {
1871
                            out.push('\n');
1872
                        }
1873
                    }
1874
                }
1875
            }
1876
            Edit::Replace { old, new, .. } => {
1877
                out.push_str(&format!(
1878
                    "  opaque content {} -> {}\n",
1879
                    old.map(|o| o.short(12)).unwrap_or_else(|| "none".into()),
1880
                    new.map(|o| o.short(12)).unwrap_or_else(|| "none".into())
1881
                ));
1882
            }
1883
        }
1884
    }
1885
    out
1886
}
1887
1888
/// Pair removed files with added files of the same kind whose contents are
1889
/// at least `RENAME_THRESHOLD` percent alike, best matches first. Beyond
1890
/// `RENAME_LIMIT` candidate pairs only identical contents are paired.
1891
const RENAME_THRESHOLD: u32 = 50;
1892
const RENAME_LIMIT: usize = 10_000;
1893
1894
fn detect_renames(
1895
    base_snapshot: &Snapshot,
1896
    fs_entries: &BTreeMap<String, FsEntry>,
1897
    in_scope: impl Fn(&str) -> bool,
1898
) -> Vec<(String, String)> {
1899
    let removed: Vec<(&String, &crate::state::FileState)> = base_snapshot
1900
        .files
1901
        .iter()
1902
        .filter(|(p, f)| {
1903
            f.kind != NodeKind::Dir
1904
                && !fs_entries.contains_key(*p)
1905
                && in_scope(p)
1906
                && !f.is_conflicted()
1907
        })
1908
        .collect();
1909
    let added: Vec<(&String, &FsEntry)> = fs_entries
1910
        .iter()
1911
        .filter(|(p, e)| e.kind != NodeKind::Dir && !base_snapshot.files.contains_key(*p))
1912
        .collect();
1913
    if removed.is_empty() || added.is_empty() {
1914
        return vec![];
1915
    }
1916
    let exact_only = removed.len() * added.len() > RENAME_LIMIT;
1917
    let old_content = |f: &crate::state::FileState| -> Option<Vec<u8>> {
1918
        match &f.content {
1919
            FileContent::Text { bytes, .. } => Some(bytes.clone()),
1920
            _ => None,
1921
        }
1922
    };
1923
    let mut scored: Vec<(u32, usize, usize)> = Vec::new();
1924
    for (ri, (_, f)) in removed.iter().enumerate() {
1925
        let old = old_content(f);
1926
        let old_blob = match &f.content {
1927
            FileContent::Opaque { blobs } if blobs.len() == 1 => Some(blobs[0]),
1928
            _ => None,
1929
        };
1930
        for (ai, (_, e)) in added.iter().enumerate() {
1931
            if e.kind != f.kind {
1932
                continue;
1933
            }
1934
            let score = match (&old, old_blob) {
1935
                (Some(o), _) => {
1936
                    if exact_only {
1937
                        if *o == e.content {
1938
                            100
1939
                        } else {
1940
                            0
1941
                        }
1942
                    } else {
1943
                        similarity(o, &e.content)
1944
                    }
1945
                }
1946
                (None, Some(b)) if e.blob.unwrap_or_else(|| Repo::blob_ref(&e.content)) == b => 100,
1947
                _ => 0,
1948
            };
1949
            if score >= RENAME_THRESHOLD {
1950
                scored.push((score, ri, ai));
1951
            }
1952
        }
1953
    }
1954
    scored.sort_by(|a, b| {
1955
        b.0.cmp(&a.0)
1956
            .then(removed[a.1].0.cmp(removed[b.1].0))
1957
            .then(added[a.2].0.cmp(added[b.2].0))
1958
    });
1959
    let mut used_r = vec![false; removed.len()];
1960
    let mut used_a = vec![false; added.len()];
1961
    let mut out = Vec::new();
1962
    for (_, ri, ai) in scored {
1963
        if used_r[ri] || used_a[ai] {
1964
            continue;
1965
        }
1966
        used_r[ri] = true;
1967
        used_a[ai] = true;
1968
        out.push((removed[ri].0.clone(), added[ai].0.clone()));
1969
    }
1970
    out
1971
}
1972
1973
/// Percentage of the larger file's bytes found in lines the two share
1974
/// (multiset intersection of lines), like Git's similarity index.
1975
pub fn similarity(a: &[u8], b: &[u8]) -> u32 {
1976
    if a == b {
1977
        return 100;
1978
    }
1979
    if a.is_empty() || b.is_empty() {
1980
        return 0;
1981
    }
1982
    let mut counts: HashMap<&[u8], usize> = HashMap::new();
1983
    for l in split_lines(a) {
1984
        *counts.entry(l).or_default() += 1;
1985
    }
1986
    let mut shared = 0usize;
1987
    for l in split_lines(b) {
1988
        if let Some(n) = counts.get_mut(l) {
1989
            if *n > 0 {
1990
                *n -= 1;
1991
                shared += l.len();
1992
            }
1993
        }
1994
    }
1995
    (shared * 100 / a.len().max(b.len())) as u32
1996
}