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