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