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