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