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