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