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