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