OXYGENHUB
# ad2496f7e608 oxygen / crates / oxy-core / src / repo / snapshot.rs
74.6 KiB · Rust · last changed Portability: exec bits, symlinks and path names on macOS and Windows 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
        let entries = self.log_state(heads)?;
1120
        let snapshot = self.load_state(heads)?.materialize();
1121
        let Some(node) = snapshot.files.get(path).map(|f| f.node) else {
1122
            return fail(format!("{path} is not in that state"));
1123
        };
1124
        Ok(self.entries_touching(entries, node))
1125
    }
1126
1127
    fn entries_touching(&self, entries: Vec<LogEntry>, node: NodeId) -> Vec<LogEntry> {
1128
        let mut out = Vec::new();
1129
        for e in entries {
1130
            let Ok(c) = self.store.get_change(&e.hash) else {
1131
                continue;
1132
            };
1133
            if c.tree_ops.iter().any(|o| o.node() == node)
1134
                || c.edits.iter().any(|x| x.node() == node)
1135
            {
1136
                out.push(e);
1137
            }
1138
        }
1139
        out
1140
    }
1141
}
1142
1143
/// Per-file hunks of `change` against `base`.
1144
pub fn diff_files_of(change: &Change, base: &State, base_snapshot: &Snapshot) -> Vec<FileDiff> {
1145
    let by_node = base_snapshot.tree.by_node();
1146
    let mut new_names: HashMap<NodeId, (NodeId, String, NodeKind)> = HashMap::new();
1147
    for op in &change.tree_ops {
1148
        if let TreeOp::AddNode {
1149
            node,
1150
            parent,
1151
            name,
1152
            kind,
1153
            ..
1154
        } = op
1155
        {
1156
            new_names.insert(*node, (*parent, name.clone(), *kind));
1157
        }
1158
    }
1159
    let path_of = |n: &NodeId| -> String {
1160
        path_of_node(n, &by_node, &new_names).unwrap_or_else(|| format!("<node {}>", n.short(8)))
1161
    };
1162
    let mut files: BTreeMap<NodeId, FileDiff> = BTreeMap::new();
1163
    let mut order: Vec<NodeId> = Vec::new();
1164
    let mut entry = |files: &mut BTreeMap<NodeId, FileDiff>, n: NodeId, kind: &str| {
1165
        if let std::collections::btree_map::Entry::Vacant(v) = files.entry(n) {
1166
            order.push(n);
1167
            v.insert(FileDiff {
1168
                path: path_of(&n),
1169
                kind: kind.to_string(),
1170
                hunks: vec![],
1171
                from: None,
1172
            });
1173
        }
1174
    };
1175
    for op in &change.tree_ops {
1176
        match op {
1177
            TreeOp::AddNode { node, kind, .. } => {
1178
                if *kind != NodeKind::Dir {
1179
                    entry(&mut files, *node, "added");
1180
                }
1181
            }
1182
            TreeOp::RemoveNode { node, .. } => {
1183
                entry(&mut files, *node, "removed");
1184
                if let Some(e) = by_node.get(node) {
1185
                    files.get_mut(node).unwrap().path = e.path.clone();
1186
                }
1187
            }
1188
            TreeOp::Move {
1189
                node, parent, name, ..
1190
            } => {
1191
                entry(&mut files, *node, "renamed");
1192
                let f = files.get_mut(node).unwrap();
1193
                f.from = by_node.get(node).map(|e| e.path.clone());
1194
                let dir = if parent.is_root() {
1195
                    String::new()
1196
                } else {
1197
                    path_of_node(parent, &by_node, &new_names).unwrap_or_default()
1198
                };
1199
                f.path = if dir.is_empty() {
1200
                    name.clone()
1201
                } else {
1202
                    format!("{dir}/{name}")
1203
                };
1204
            }
1205
            TreeOp::SetMode { node, .. } => entry(&mut files, *node, "mode"),
1206
        }
1207
    }
1208
    // Base line numbers per node, 1-based.
1209
    let mut line_of: HashMap<NodeId, HashMap<(ChangeHash, u32), u32>> = HashMap::new();
1210
    let mut lines_for = |n: &NodeId| -> HashMap<(ChangeHash, u32), u32> {
1211
        line_of
1212
            .entry(*n)
1213
            .or_insert_with(|| {
1214
                base.live_lines(n)
1215
                    .into_iter()
1216
                    .enumerate()
1217
                    .map(|(i, (k, _))| (k, i as u32 + 1))
1218
                    .collect()
1219
            })
1220
            .clone()
1221
    };
1222
    for e in &change.edits {
1223
        let n = e.node();
1224
        let is_new = new_names.contains_key(&n);
1225
        entry(&mut files, n, if is_new { "added" } else { "modified" });
1226
        let f = files.get_mut(&n).unwrap();
1227
        match e {
1228
            Edit::Insert { after, lines, .. } => {
1229
                let map = lines_for(&n);
1230
                let base_line = match after {
1231
                    AtomRef::Start => 0,
1232
                    AtomRef::End => map.len() as u32,
1233
                    AtomRef::Atom { change, index } if change.is_zero() => {
1234
                        f.hunks.last().map(|h| h.base_line).unwrap_or(0)
1235
                    }
1236
                    AtomRef::Atom { change, index } => {
1237
                        map.get(&(*change, *index)).copied().unwrap_or(0)
1238
                    }
1239
                };
1240
                f.hunks.push(DiffHunk {
1241
                    base_line,
1242
                    added: lines.clone(),
1243
                    removed: vec![],
1244
                });
1245
            }
1246
            Edit::Delete { atoms, .. } => {
1247
                let map = lines_for(&n);
1248
                let mut removed = Vec::new();
1249
                for r in atoms {
1250
                    for i in r.from..r.to {
1251
                        let line = map.get(&(r.change, i)).copied().unwrap_or(0);
1252
                        let text = base
1253
                            .file(&n)
1254
                            .and_then(|g| g.content(&(r.change, i)))
1255
                            .unwrap_or(b"")
1256
                            .to_vec();
1257
                        removed.push((line, text));
1258
                    }
1259
                }
1260
                let base_line = removed
1261
                    .first()
1262
                    .map(|(l, _)| l.saturating_sub(1))
1263
                    .unwrap_or(0);
1264
                f.hunks.push(DiffHunk {
1265
                    base_line,
1266
                    added: vec![],
1267
                    removed,
1268
                });
1269
            }
1270
            Edit::Replace { .. } => {
1271
                if !is_new {
1272
                    f.kind = "replaced".into();
1273
                }
1274
            }
1275
        }
1276
    }
1277
    order.into_iter().filter_map(|n| files.remove(&n)).collect()
1278
}
1279
1280
/// Builds the tree ops and edits of a working-copy change against a base.
1281
struct ChangeBuilder<'a> {
1282
    base: &'a State,
1283
    base_snapshot: &'a Snapshot,
1284
    tree_ops: Vec<TreeOp>,
1285
    edits: Vec<Edit>,
1286
    statuses: Vec<PathStatus>,
1287
    dir_nodes: HashMap<String, NodeId>,
1288
    reuse: HashMap<String, (NodeId, NodeKind)>,
1289
    /// Changes that contributed to conflicts this working copy resolves.
1290
    contributors: BTreeSet<ChangeHash>,
1291
    resolves: bool,
1292
    attrs: crate::attributes::Attributes,
1293
    blobs: HashMap<String, ObjectRef>,
1294
}
1295
1296
impl<'a> ChangeBuilder<'a> {
1297
    fn new(
1298
        base: &'a State,
1299
        base_snapshot: &'a Snapshot,
1300
        reuse: HashMap<String, (NodeId, NodeKind)>,
1301
    ) -> Self {
1302
        let mut dir_nodes: HashMap<String, NodeId> = HashMap::new();
1303
        dir_nodes.insert(String::new(), NodeId::ROOT);
1304
        for (p, f) in &base_snapshot.files {
1305
            if f.kind == NodeKind::Dir {
1306
                dir_nodes.insert(p.clone(), f.node);
1307
            }
1308
        }
1309
        ChangeBuilder {
1310
            base,
1311
            base_snapshot,
1312
            tree_ops: vec![],
1313
            edits: vec![],
1314
            statuses: vec![],
1315
            dir_nodes,
1316
            reuse,
1317
            contributors: BTreeSet::new(),
1318
            resolves: false,
1319
            attrs: crate::attributes::Attributes::default(),
1320
            blobs: HashMap::new(),
1321
        }
1322
    }
1323
1324
    fn with_attributes(mut self, attrs: crate::attributes::Attributes) -> Self {
1325
        self.attrs = attrs;
1326
        self
1327
    }
1328
1329
    /// Whether a file is opaque: forced by `binary`, forced text by `text`
1330
    /// only when it has no NUL bytes, else sniffed.
1331
    /// The blob for an opaque entry: the cached one, else stored now.
1332
    fn blob_of(
1333
        &mut self,
1334
        repo: &Repo,
1335
        path: &str,
1336
        e: &FsEntry,
1337
        nocompress: bool,
1338
    ) -> Result<ObjectRef> {
1339
        let b = match e.blob {
1340
            Some(b) => b,
1341
            None => repo.store_blob_for(&e.content, nocompress)?,
1342
        };
1343
        self.blobs.insert(path.to_string(), b);
1344
        Ok(b)
1345
    }
1346
1347
    fn opaque_for(&self, path: &str, e: &FsEntry) -> bool {
1348
        if e.blob.is_some() {
1349
            return true;
1350
        }
1351
        if e.kind == NodeKind::Symlink || e.kind == NodeKind::Subrepo {
1352
            return true;
1353
        }
1354
        match self.attrs.lookup(path).binary {
1355
            Some(true) => true,
1356
            Some(false) => is_binary(&e.content),
1357
            None => is_binary(&e.content),
1358
        }
1359
    }
1360
1361
    /// Text content as stored: `\r\n` normalized for `eol=` files.
1362
    fn stored_text(&self, path: &str, content: &[u8]) -> Vec<u8> {
1363
        if self.attrs.lookup(path).eol.is_some() {
1364
            crate::attributes::normalize_eol(content)
1365
        } else {
1366
            content.to_vec()
1367
        }
1368
    }
1369
1370
    fn reused_node(&self, path: &str, kind: NodeKind) -> Option<NodeId> {
1371
        self.reuse
1372
            .get(path)
1373
            .filter(|(_, k)| *k == kind)
1374
            .map(|(n, _)| *n)
1375
    }
1376
1377
    fn ensure_dir(&mut self, path: &str) -> NodeId {
1378
        if let Some(n) = self.dir_nodes.get(path) {
1379
            return *n;
1380
        }
1381
        let mut parent = NodeId::ROOT;
1382
        let mut prefix = String::new();
1383
        for comp in path.split('/') {
1384
            if !prefix.is_empty() {
1385
                prefix.push('/');
1386
            }
1387
            prefix.push_str(comp);
1388
            parent = match self.dir_nodes.get(&prefix) {
1389
                Some(n) => *n,
1390
                None => {
1391
                    let node = self
1392
                        .reused_node(&prefix, NodeKind::Dir)
1393
                        .unwrap_or_else(NodeId::random);
1394
                    self.tree_ops.push(TreeOp::AddNode {
1395
                        node,
1396
                        kind: NodeKind::Dir,
1397
                        mode: Mode::default(),
1398
                        parent,
1399
                        name: comp.to_string(),
1400
                    });
1401
                    self.dir_nodes.insert(prefix.clone(), node);
1402
                    node
1403
                }
1404
            };
1405
        }
1406
        parent
1407
    }
1408
1409
    fn add_path(&mut self, repo: &Repo, path: &str, e: &FsEntry) -> Result<()> {
1410
        let (dir, name) = split_path(path);
1411
        let parent = self.ensure_dir(dir);
1412
        let node = self
1413
            .reused_node(path, e.kind)
1414
            .unwrap_or_else(NodeId::random);
1415
        let opaque = self.opaque_for(path, e);
1416
        let nocompress = self.attrs.lookup(path).nocompress;
1417
        self.tree_ops.push(TreeOp::AddNode {
1418
            node,
1419
            kind: e.kind,
1420
            mode: Mode {
1421
                exec: e.exec,
1422
                opaque,
1423
            },
1424
            parent,
1425
            name: name.to_string(),
1426
        });
1427
        if opaque {
1428
            let blob = self.blob_of(repo, path, e, nocompress)?;
1429
            self.edits.push(Edit::Replace {
1430
                node,
1431
                old: None,
1432
                new: Some(blob),
1433
            });
1434
        } else if !e.content.is_empty() {
1435
            let content = self.stored_text(path, &e.content);
1436
            self.edits.push(Edit::Insert {
1437
                node,
1438
                after: crate::objects::AtomRef::Start,
1439
                before: crate::objects::AtomRef::End,
1440
                lines: split_lines(&content).iter().map(|l| l.to_vec()).collect(),
1441
            });
1442
        }
1443
        self.statuses.push(PathStatus {
1444
            path: path.to_string(),
1445
            status: ChangeStatus::Added,
1446
        });
1447
        Ok(())
1448
    }
1449
1450
    /// Move the node at `old` to `new` and apply `e`'s content to it.
1451
    fn move_path(
1452
        &mut self,
1453
        repo: &Repo,
1454
        old: &str,
1455
        new: &str,
1456
        e: &FsEntry,
1457
        expected: &crate::state::FileState,
1458
    ) -> Result<()> {
1459
        let entry = &self.base_snapshot.tree.entries[old];
1460
        let (dir, name) = split_path(new);
1461
        let parent = self.ensure_dir(dir);
1462
        self.tree_ops.push(TreeOp::Move {
1463
            node: expected.node,
1464
            old: op_ref(entry.placement),
1465
            parent,
1466
            name: name.to_string(),
1467
        });
1468
        self.update_path(repo, old, e, expected)?;
1469
        // update_path reports under the old path; the rename is what the user sees.
1470
        self.statuses.retain(|s| s.path != old);
1471
        self.statuses.push(PathStatus {
1472
            path: new.to_string(),
1473
            status: ChangeStatus::Renamed,
1474
        });
1475
        Ok(())
1476
    }
1477
1478
    fn remove_path(&mut self, path: &str, expected: &crate::state::FileState) {
1479
        let entry = &self.base_snapshot.tree.entries[path];
1480
        self.tree_ops.push(TreeOp::RemoveNode {
1481
            node: expected.node,
1482
            placement: op_ref(entry.placement),
1483
        });
1484
        if path.contains(".oxy-conflict-") || expected.is_conflicted() {
1485
            self.resolves = true;
1486
        }
1487
        self.statuses.push(PathStatus {
1488
            path: path.to_string(),
1489
            status: ChangeStatus::Removed,
1490
        });
1491
    }
1492
1493
    fn update_path(
1494
        &mut self,
1495
        repo: &Repo,
1496
        path: &str,
1497
        e: &FsEntry,
1498
        expected: &crate::state::FileState,
1499
    ) -> Result<()> {
1500
        if expected.kind != e.kind {
1501
            self.remove_path(path, expected);
1502
            self.statuses.pop();
1503
            self.add_path(repo, path, e)?;
1504
            self.statuses.pop();
1505
            self.statuses.push(PathStatus {
1506
                path: path.to_string(),
1507
                status: ChangeStatus::Modified,
1508
            });
1509
            return Ok(());
1510
        }
1511
        let entry = &self.base_snapshot.tree.entries[path];
1512
        let node = expected.node;
1513
        let mode_atom = entry.mode_atom.map(op_ref);
1514
        let mut status: Option<ChangeStatus> = None;
1515
        let wants_opaque = self.opaque_for(path, e);
1516
        let nocompress = self.attrs.lookup(path).nocompress;
1517
        let disk_text = self.stored_text(path, &e.content);
1518
        match &expected.content {
1519
            FileContent::Dir => {}
1520
            FileContent::Text {
1521
                bytes,
1522
                materialized,
1523
            } => {
1524
                if materialized.is_conflicted() {
1525
                    if bytes == &disk_text {
1526
                        return Ok(());
1527
                    }
1528
                    if has_conflict_markers(&e.content) {
1529
                        self.statuses.push(PathStatus {
1530
                            path: path.to_string(),
1531
                            status: ChangeStatus::ConflictEdited,
1532
                        });
1533
                        return Ok(());
1534
                    }
1535
                    // Resolution (spec §9.6): diff against the unconflicted lines
1536
                    // with each region as a gap, then retire every region atom.
1537
                    // Whatever the author kept from a region is re-inserted as
1538
                    // new atoms, which leaves the graph totally ordered.
1539
                    let regions = self.base.conflict_regions(&node);
1540
                    let mut edits = text_edits(node, &regions.plain, &disk_text);
1541
                    if !regions.region_atoms.is_empty() {
1542
                        edits.insert(
1543
                            0,
1544
                            Edit::Delete {
1545
                                node,
1546
                                atoms: ranges(&regions.region_atoms),
1547
                            },
1548
                        );
1549
                    }
1550
                    self.edits.extend(edits);
1551
                    self.contributors.extend(regions.contributors);
1552
                    self.resolves = true;
1553
                    if e.exec != expected.mode.exec {
1554
                        if let Some(old) = mode_atom {
1555
                            self.tree_ops.push(TreeOp::SetMode {
1556
                                node,
1557
                                old,
1558
                                mode: Mode {
1559
                                    exec: e.exec,
1560
                                    opaque: false,
1561
                                },
1562
                            });
1563
                        }
1564
                    }
1565
                    self.statuses.push(PathStatus {
1566
                        path: path.to_string(),
1567
                        status: ChangeStatus::Resolved,
1568
                    });
1569
                    return Ok(());
1570
                }
1571
                if wants_opaque {
1572
                    // Text → opaque (spec §7.5), by content or by attribute.
1573
                    if let Some(old) = mode_atom {
1574
                        self.tree_ops.push(TreeOp::SetMode {
1575
                            node,
1576
                            old,
1577
                            mode: Mode {
1578
                                exec: e.exec,
1579
                                opaque: true,
1580
                            },
1581
                        });
1582
                    }
1583
                    let live: Vec<_> = repo_live_keys(self.base, &node);
1584
                    if !live.is_empty() {
1585
                        self.edits.push(Edit::Delete {
1586
                            node,
1587
                            atoms: ranges(&live),
1588
                        });
1589
                    }
1590
                    let blob = self.blob_of(repo, path, e, nocompress)?;
1591
                    self.edits.push(Edit::Replace {
1592
                        node,
1593
                        old: None,
1594
                        new: Some(blob),
1595
                    });
1596
                    status = Some(ChangeStatus::Modified);
1597
                } else if bytes != &disk_text {
1598
                    let old = self.base.live_lines(&node);
1599
                    let edits = text_edits(node, &old, &disk_text);
1600
                    if !edits.is_empty() {
1601
                        self.edits.extend(edits);
1602
                        status = Some(ChangeStatus::Modified);
1603
                    }
1604
                }
1605
                let switched_to_opaque = wants_opaque;
1606
                if !switched_to_opaque && e.exec != expected.mode.exec {
1607
                    if let Some(old) = mode_atom {
1608
                        self.tree_ops.push(TreeOp::SetMode {
1609
                            node,
1610
                            old,
1611
                            mode: Mode {
1612
                                exec: e.exec,
1613
                                opaque: false,
1614
                            },
1615
                        });
1616
                        status.get_or_insert(ChangeStatus::ModeChanged);
1617
                    }
1618
                }
1619
            }
1620
            FileContent::Opaque { blobs } => {
1621
                let new_ref = e.blob.unwrap_or_else(|| Repo::blob_ref(&e.content));
1622
                if e.kind == NodeKind::File && wants_opaque {
1623
                    // Unchanged or replaced, the file stays opaque: remember its blob.
1624
                    self.blobs.insert(path.to_string(), new_ref);
1625
                }
1626
                if blobs.len() > 1 {
1627
                    if !blobs.contains(&new_ref) {
1628
                        self.statuses.push(PathStatus {
1629
                            path: path.to_string(),
1630
                            status: ChangeStatus::ConflictEdited,
1631
                        });
1632
                    }
1633
                    return Ok(());
1634
                }
1635
                let current = blobs.first().copied();
1636
                if current != Some(new_ref) {
1637
                    if e.kind == NodeKind::File && !wants_opaque {
1638
                        // Opaque → text (spec §7.5).
1639
                        if let Some(old) = mode_atom {
1640
                            self.tree_ops.push(TreeOp::SetMode {
1641
                                node,
1642
                                old,
1643
                                mode: Mode {
1644
                                    exec: e.exec,
1645
                                    opaque: false,
1646
                                },
1647
                            });
1648
                        }
1649
                        self.edits.push(Edit::Replace {
1650
                            node,
1651
                            old: current,
1652
                            new: None,
1653
                        });
1654
                        if !e.content.is_empty() {
1655
                            self.edits.push(Edit::Insert {
1656
                                node,
1657
                                after: crate::objects::AtomRef::Start,
1658
                                before: crate::objects::AtomRef::End,
1659
                                lines: split_lines(&e.content).iter().map(|l| l.to_vec()).collect(),
1660
                            });
1661
                        }
1662
                    } else {
1663
                        let blob = self.blob_of(repo, path, e, nocompress)?;
1664
                        self.edits.push(Edit::Replace {
1665
                            node,
1666
                            old: current,
1667
                            new: Some(blob),
1668
                        });
1669
                    }
1670
                    status = Some(ChangeStatus::Modified);
1671
                } else if e.kind == NodeKind::File && e.exec != expected.mode.exec {
1672
                    if let Some(old) = mode_atom {
1673
                        self.tree_ops.push(TreeOp::SetMode {
1674
                            node,
1675
                            old,
1676
                            mode: Mode {
1677
                                exec: e.exec,
1678
                                opaque: true,
1679
                            },
1680
                        });
1681
                        status = Some(ChangeStatus::ModeChanged);
1682
                    }
1683
                }
1684
            }
1685
        }
1686
        if let Some(s) = status {
1687
            self.statuses.push(PathStatus {
1688
                path: path.to_string(),
1689
                status: s,
1690
            });
1691
        }
1692
        Ok(())
1693
    }
1694
}
1695
1696
fn repo_live_keys(base: &State, node: &NodeId) -> Vec<crate::graph::AtomKey> {
1697
    base.live_lines(node).into_iter().map(|(k, _)| k).collect()
1698
}
1699
1700
/// The changes a change's scope references (spec §8.1): introducers of every
1701
/// atom, placement, and mode it touches, and of every node it operates on.
1702
pub fn referenced_changes(change: &Change, base: &State) -> BTreeSet<ChangeHash> {
1703
    let mut out = BTreeSet::new();
1704
    let opref = |r: &OpRef, out: &mut BTreeSet<ChangeHash>| {
1705
        if !r.change.is_zero() {
1706
            out.insert(r.change);
1707
        }
1708
    };
1709
    let mut nodes: Vec<NodeId> = Vec::new();
1710
    for op in &change.tree_ops {
1711
        match op {
1712
            TreeOp::AddNode { parent, .. } => nodes.push(*parent),
1713
            TreeOp::RemoveNode { node, placement } => {
1714
                nodes.push(*node);
1715
                opref(placement, &mut out);
1716
            }
1717
            TreeOp::Move {
1718
                node, old, parent, ..
1719
            } => {
1720
                nodes.push(*node);
1721
                nodes.push(*parent);
1722
                opref(old, &mut out);
1723
            }
1724
            TreeOp::SetMode { node, old, .. } => {
1725
                nodes.push(*node);
1726
                opref(old, &mut out);
1727
            }
1728
        }
1729
    }
1730
    for e in &change.edits {
1731
        nodes.push(e.node());
1732
        match e {
1733
            Edit::Insert { after, before, .. } => {
1734
                for r in [after, before] {
1735
                    if let crate::objects::AtomRef::Atom { change, .. } = r {
1736
                        if !change.is_zero() {
1737
                            out.insert(*change);
1738
                        }
1739
                    }
1740
                }
1741
            }
1742
            Edit::Delete { atoms, .. } => {
1743
                // Deleting an atom also depends on whoever inserted the live
1744
                // atoms right after it: the author saw those insertions, and
1745
                // without the dependency spec §9.1 would call the deletion
1746
                // concurrent with them (a delete/insert conflict).
1747
                let graph = base.file(&e.node());
1748
                for r in atoms {
1749
                    if !r.change.is_zero() {
1750
                        out.insert(r.change);
1751
                    }
1752
                    if let Some(g) = graph {
1753
                        for i in r.from..r.to {
1754
                            out.extend(
1755
                                g.live_successor_changes(&(r.change, i))
1756
                                    .into_iter()
1757
                                    .filter(|c| !c.is_zero()),
1758
                            );
1759
                        }
1760
                    }
1761
                }
1762
            }
1763
            // Replacing a blob depends on the change that made it current,
1764
            // as deleting a line depends on the line's introducer.
1765
            Edit::Replace {
1766
                node,
1767
                old: Some(old),
1768
                ..
1769
            } => {
1770
                out.extend(
1771
                    base.live_replaces(node)
1772
                        .into_iter()
1773
                        .filter(|(c, b)| b == old && !c.is_zero())
1774
                        .map(|(c, _)| c),
1775
                );
1776
            }
1777
            Edit::Replace { .. } => {}
1778
        }
1779
    }
1780
    for n in nodes {
1781
        if let Some(h) = base.tree().introducer(&n) {
1782
            out.insert(h);
1783
        }
1784
    }
1785
    out
1786
}
1787
1788
/// Paths of the nodes a change adds on top of `base_snapshot`.
1789
pub fn added_node_paths(
1790
    change: &Change,
1791
    base_snapshot: &Snapshot,
1792
) -> HashMap<String, (NodeId, NodeKind)> {
1793
    let by_node = base_snapshot.tree.by_node();
1794
    let mut new_names: HashMap<NodeId, (NodeId, String, NodeKind)> = HashMap::new();
1795
    for op in &change.tree_ops {
1796
        if let TreeOp::AddNode {
1797
            node,
1798
            parent,
1799
            name,
1800
            kind,
1801
            ..
1802
        } = op
1803
        {
1804
            new_names.insert(*node, (*parent, name.clone(), *kind));
1805
        }
1806
    }
1807
    let mut out = HashMap::new();
1808
    for (node, (_, _, kind)) in &new_names {
1809
        if let Some(path) = path_of_node(node, &by_node, &new_names) {
1810
            out.insert(path, (*node, *kind));
1811
        }
1812
    }
1813
    out
1814
}
1815
1816
fn path_of_node(
1817
    n: &NodeId,
1818
    by_node: &HashMap<NodeId, &crate::tree::TreeEntry>,
1819
    new_names: &HashMap<NodeId, (NodeId, String, NodeKind)>,
1820
) -> Option<String> {
1821
    if let Some(e) = by_node.get(n) {
1822
        return Some(e.path.clone());
1823
    }
1824
    let mut parts = Vec::new();
1825
    let mut cur = *n;
1826
    loop {
1827
        if cur.is_root() {
1828
            break;
1829
        }
1830
        if let Some(e) = by_node.get(&cur) {
1831
            if !e.path.is_empty() {
1832
                parts.push(e.path.clone());
1833
            }
1834
            break;
1835
        }
1836
        let (parent, name, _) = new_names.get(&cur)?;
1837
        parts.push(name.clone());
1838
        cur = *parent;
1839
    }
1840
    parts.reverse();
1841
    Some(parts.join("/"))
1842
}
1843
1844
/// Render a change's operations with line content, using `base` for deleted lines.
1845
pub fn render_change(change: &Change, base: &State, base_snapshot: &Snapshot) -> String {
1846
    let by_node = base_snapshot.tree.by_node();
1847
    let mut new_names: HashMap<NodeId, (NodeId, String, NodeKind)> = HashMap::new();
1848
    for op in &change.tree_ops {
1849
        if let TreeOp::AddNode {
1850
            node,
1851
            parent,
1852
            name,
1853
            kind,
1854
            ..
1855
        } = op
1856
        {
1857
            new_names.insert(*node, (*parent, name.clone(), *kind));
1858
        }
1859
    }
1860
    let path_of = |n: &NodeId| -> String {
1861
        path_of_node(n, &by_node, &new_names).unwrap_or_else(|| format!("<node {}>", n.short(8)))
1862
    };
1863
1864
    let mut out = String::new();
1865
    for op in &change.tree_ops {
1866
        match op {
1867
            TreeOp::AddNode {
1868
                node, kind, mode, ..
1869
            } => {
1870
                out.push_str(&format!(
1871
                    "A {} ({:?}{}{})\n",
1872
                    path_of(node),
1873
                    kind,
1874
                    if mode.exec { ", exec" } else { "" },
1875
                    if mode.opaque { ", opaque" } else { "" }
1876
                ));
1877
            }
1878
            TreeOp::RemoveNode { node, .. } => out.push_str(&format!("D {}\n", path_of(node))),
1879
            TreeOp::Move { node, name, .. } => {
1880
                out.push_str(&format!("R {} -> {}\n", path_of(node), name))
1881
            }
1882
            TreeOp::SetMode { node, mode, .. } => {
1883
                out.push_str(&format!(
1884
                    "M {} mode: exec={} opaque={}\n",
1885
                    path_of(node),
1886
                    mode.exec,
1887
                    mode.opaque
1888
                ));
1889
            }
1890
        }
1891
    }
1892
    let mut last_node: Option<NodeId> = None;
1893
    for e in &change.edits {
1894
        let n = e.node();
1895
        if last_node != Some(n) {
1896
            out.push_str(&format!("--- {}\n", path_of(&n)));
1897
            last_node = Some(n);
1898
        }
1899
        match e {
1900
            Edit::Insert { lines, .. } => {
1901
                for l in lines {
1902
                    out.push('+');
1903
                    out.push_str(&String::from_utf8_lossy(l));
1904
                    if !l.ends_with(b"\n") {
1905
                        out.push('\n');
1906
                    }
1907
                }
1908
            }
1909
            Edit::Delete { atoms, .. } => {
1910
                for r in atoms {
1911
                    for i in r.from..r.to {
1912
                        let content = base
1913
                            .file(&n)
1914
                            .and_then(|g| g.content(&(r.change, i)))
1915
                            .unwrap_or(b"<unknown>\n");
1916
                        out.push('-');
1917
                        out.push_str(&String::from_utf8_lossy(content));
1918
                        if !content.ends_with(b"\n") {
1919
                            out.push('\n');
1920
                        }
1921
                    }
1922
                }
1923
            }
1924
            Edit::Replace { old, new, .. } => {
1925
                out.push_str(&format!(
1926
                    "  opaque content {} -> {}\n",
1927
                    old.map(|o| o.short(12)).unwrap_or_else(|| "none".into()),
1928
                    new.map(|o| o.short(12)).unwrap_or_else(|| "none".into())
1929
                ));
1930
            }
1931
        }
1932
    }
1933
    out
1934
}
1935
1936
/// Pair removed files with added files of the same kind whose contents are
1937
/// at least `RENAME_THRESHOLD` percent alike, best matches first. Beyond
1938
/// `RENAME_LIMIT` candidate pairs only identical contents are paired.
1939
const RENAME_THRESHOLD: u32 = 50;
1940
const RENAME_LIMIT: usize = 10_000;
1941
1942
fn detect_renames(
1943
    base_snapshot: &Snapshot,
1944
    fs_entries: &BTreeMap<String, FsEntry>,
1945
    in_scope: impl Fn(&str) -> bool,
1946
) -> Vec<(String, String)> {
1947
    let removed: Vec<(&String, &crate::state::FileState)> = base_snapshot
1948
        .files
1949
        .iter()
1950
        .filter(|(p, f)| {
1951
            f.kind != NodeKind::Dir
1952
                && !fs_entries.contains_key(*p)
1953
                && in_scope(p)
1954
                && !f.is_conflicted()
1955
        })
1956
        .collect();
1957
    let added: Vec<(&String, &FsEntry)> = fs_entries
1958
        .iter()
1959
        .filter(|(p, e)| e.kind != NodeKind::Dir && !base_snapshot.files.contains_key(*p))
1960
        .collect();
1961
    if removed.is_empty() || added.is_empty() {
1962
        return vec![];
1963
    }
1964
    let exact_only = removed.len() * added.len() > RENAME_LIMIT;
1965
    let old_content = |f: &crate::state::FileState| -> Option<Vec<u8>> {
1966
        match &f.content {
1967
            FileContent::Text { bytes, .. } => Some(bytes.clone()),
1968
            _ => None,
1969
        }
1970
    };
1971
    let mut scored: Vec<(u32, usize, usize)> = Vec::new();
1972
    for (ri, (_, f)) in removed.iter().enumerate() {
1973
        let old = old_content(f);
1974
        let old_blob = match &f.content {
1975
            FileContent::Opaque { blobs } if blobs.len() == 1 => Some(blobs[0]),
1976
            _ => None,
1977
        };
1978
        for (ai, (_, e)) in added.iter().enumerate() {
1979
            if e.kind != f.kind {
1980
                continue;
1981
            }
1982
            let score = match (&old, old_blob) {
1983
                (Some(o), _) => {
1984
                    if exact_only {
1985
                        if *o == e.content {
1986
                            100
1987
                        } else {
1988
                            0
1989
                        }
1990
                    } else {
1991
                        similarity(o, &e.content)
1992
                    }
1993
                }
1994
                (None, Some(b)) if e.blob.unwrap_or_else(|| Repo::blob_ref(&e.content)) == b => 100,
1995
                _ => 0,
1996
            };
1997
            if score >= RENAME_THRESHOLD {
1998
                scored.push((score, ri, ai));
1999
            }
2000
        }
2001
    }
2002
    scored.sort_by(|a, b| {
2003
        b.0.cmp(&a.0)
2004
            .then(removed[a.1].0.cmp(removed[b.1].0))
2005
            .then(added[a.2].0.cmp(added[b.2].0))
2006
    });
2007
    let mut used_r = vec![false; removed.len()];
2008
    let mut used_a = vec![false; added.len()];
2009
    let mut out = Vec::new();
2010
    for (_, ri, ai) in scored {
2011
        if used_r[ri] || used_a[ai] {
2012
            continue;
2013
        }
2014
        used_r[ri] = true;
2015
        used_a[ai] = true;
2016
        out.push((removed[ri].0.clone(), added[ai].0.clone()));
2017
    }
2018
    out
2019
}
2020
2021
/// Percentage of the larger file's bytes found in lines the two share
2022
/// (multiset intersection of lines), like Git's similarity index.
2023
pub fn similarity(a: &[u8], b: &[u8]) -> u32 {
2024
    if a == b {
2025
        return 100;
2026
    }
2027
    if a.is_empty() || b.is_empty() {
2028
        return 0;
2029
    }
2030
    let mut counts: HashMap<&[u8], usize> = HashMap::new();
2031
    for l in split_lines(a) {
2032
        *counts.entry(l).or_default() += 1;
2033
    }
2034
    let mut shared = 0usize;
2035
    for l in split_lines(b) {
2036
        if let Some(n) = counts.get_mut(l) {
2037
            if *n > 0 {
2038
                *n -= 1;
2039
                shared += l.len();
2040
            }
2041
        }
2042
    }
2043
    (shared * 100 / a.len().max(b.len())) as u32
2044
}