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