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