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