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