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