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