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