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