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