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