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