OXYGENHUB
# e8e6e0cac26a oxygen / crates / oxy-core / src / repo / snapshot.rs
117.2 KiB · Rust · last changed Remove or move every copy of a node at one place 26 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 => self.working_copy_with_base()?,
1673
        };
1674
        Ok(diff_files_of(&c, &base, &base_snapshot))
1675
    }
1676
1677
    /// The snapshot a command would take, without taking it, when the
1678
    /// status cache holds: every file is as the last snapshot left it, so
1679
    /// that snapshot's working-copy change is the answer. Its base comes
1680
    /// from the state index, the `.oxyattributes` files from disk. `None`
1681
    /// when a snapshot must be taken, and when there is nothing to commit
1682
    /// (the snapshot then says so). A conflicted base never gets here: the
1683
    /// cache does not hold for one.
1684
    pub(crate) fn snapshot_from_cache(&self) -> Result<Option<SnapshotResult>> {
1685
        let Some(statuses) = self.status_by_manifest()? else {
1686
            return Ok(None);
1687
        };
1688
        if statuses.is_empty() {
1689
            return Ok(None);
1690
        }
1691
        let _t = crate::timing::phase("snapshot: from the status cache");
1692
        let (wc_hash, wc) = self.working_copy()?;
1693
        let base = self.load_state_indexed(&wc.deps)?;
1694
        let (base, base_snapshot) = self.render_base_for(&wc, base)?;
1695
        let attribute_files: Vec<(String, Vec<u8>)> = match self.read_manifest()? {
1696
            Some((_, _, m)) => m
1697
                .entries
1698
                .keys()
1699
                .filter(|p| is_attributes(p))
1700
                .filter_map(|p| fs::read(self.root.join(p)).ok().map(|b| (p.clone(), b)))
1701
                .collect(),
1702
            None => Vec::new(),
1703
        };
1704
        let attributes = crate::attributes::Attributes::from_files(
1705
            attribute_files
1706
                .iter()
1707
                .map(|(p, b)| (p.as_str(), b.as_slice())),
1708
        );
1709
        Ok(Some(SnapshotResult {
1710
            wc_hash,
1711
            wc,
1712
            base,
1713
            base_snapshot,
1714
            statuses,
1715
            changed: false,
1716
            resolves: false,
1717
            contributors: Vec::new(),
1718
            attributes,
1719
            untracked_nested: self.untracked_nested.borrow().clone(),
1720
            manifest: None,
1721
        }))
1722
    }
1723
1724
    /// The working-copy change with its base state and the base's
1725
    /// rendering, for showing what the working copy changes. While the
1726
    /// status cache holds (every file as the last snapshot left it), the
1727
    /// stored working-copy change is the answer and no snapshot is taken;
1728
    /// otherwise a snapshot makes it.
1729
    pub fn working_copy_with_base(&self) -> Result<(Change, State, Snapshot)> {
1730
        if self.status_by_manifest()?.is_some() {
1731
            let (_, wc) = self.working_copy()?;
1732
            let base = self.load_state_indexed(&wc.deps)?;
1733
            let (base, snapshot) = self.render_base_for(&wc, base)?;
1734
            return Ok((wc, base, snapshot));
1735
        }
1736
        let snap = self.snapshot_status("oxy diff")?;
1737
        Ok((snap.wc, snap.base, snap.base_snapshot))
1738
    }
1739
1740
    /// The log restricted to changes touching `path` (its node, so renames
1741
    /// are followed), on the current bookmark.
1742
    pub fn log_for_path(&self, path: &str) -> Result<Vec<LogEntry>> {
1743
        let heads = self.bookmark_heads()?;
1744
        if self.is_bare() {
1745
            return self.log_for_path_in(path, &heads);
1746
        }
1747
        let entries = self.log()?;
1748
        let (_, wc) = self.working_copy()?;
1749
        // The path's node from the trees alone: the base's (from the
1750
        // workspace's state index), else the bookmark's. Nothing is
1751
        // rendered.
1752
        let node_in = |state: State| state.tree().view().entries.get(path).map(|e| e.node);
1753
        let node = match node_in(self.load_state_indexed(&wc.deps)?) {
1754
            Some(n) => Some(n),
1755
            None => node_in(self.load_state_history(&heads)?),
1756
        };
1757
        let Some(node) = node else {
1758
            return fail(format!("{path} is not tracked"));
1759
        };
1760
        Ok(self.entries_touching(entries, node))
1761
    }
1762
1763
    /// The log of the state with these heads restricted to changes touching
1764
    /// `path` (its node, so renames are followed).
1765
    pub fn log_for_path_in(&self, path: &str, heads: &[ChangeHash]) -> Result<Vec<LogEntry>> {
1766
        self.log_for_path_of(&self.load_state_history(heads)?, path, None)
1767
    }
1768
1769
    /// The changes of a loaded state touching `path`, newest first, at most
1770
    /// `limit` of them. The path is found in the state's tree alone, so no
1771
    /// file is rendered, and the walk stops once `limit` are found.
1772
    pub fn log_for_path_of(
1773
        &self,
1774
        state: &State,
1775
        path: &str,
1776
        limit: Option<usize>,
1777
    ) -> Result<Vec<LogEntry>> {
1778
        let Some(node) = state.tree().view().entries.get(path).map(|e| e.node) else {
1779
            return fail(format!("{path} is not in that state"));
1780
        };
1781
        Ok(self.entries_touching_up_to(self.log_of(state), node, limit))
1782
    }
1783
1784
    fn entries_touching(&self, entries: Vec<LogEntry>, node: NodeId) -> Vec<LogEntry> {
1785
        self.entries_touching_up_to(entries, node, None)
1786
    }
1787
1788
    fn entries_touching_up_to(
1789
        &self,
1790
        entries: Vec<LogEntry>,
1791
        node: NodeId,
1792
        limit: Option<usize>,
1793
    ) -> Vec<LogEntry> {
1794
        let mut touched = self.touched();
1795
        if limit.is_none() {
1796
            let hashes: Vec<ChangeHash> = entries.iter().map(|e| e.hash).collect();
1797
            touched.fill(self, &hashes);
1798
        }
1799
        let wanted = HashSet::from([node]);
1800
        let mut out = Vec::new();
1801
        for e in entries {
1802
            if limit.is_some_and(|n| out.len() >= n) {
1803
                break;
1804
            }
1805
            if touched.touches(self, &e.hash, &wanted) {
1806
                out.push(e);
1807
            }
1808
        }
1809
        touched.save();
1810
        out
1811
    }
1812
}
1813
1814
/// Per-file hunks of `change` against `base`.
1815
pub fn diff_files_of(change: &Change, base: &State, base_snapshot: &Snapshot) -> Vec<FileDiff> {
1816
    let by_node = base_snapshot.tree.by_node();
1817
    let mut new_names: HashMap<NodeId, (NodeId, String, NodeKind)> = HashMap::new();
1818
    for op in &change.tree_ops {
1819
        if let TreeOp::AddNode {
1820
            node,
1821
            parent,
1822
            name,
1823
            kind,
1824
            ..
1825
        } = op
1826
        {
1827
            new_names.insert(*node, (*parent, name.clone(), *kind));
1828
        }
1829
    }
1830
    let path_of = |n: &NodeId| -> String {
1831
        path_of_node(n, &by_node, &new_names).unwrap_or_else(|| format!("<node {}>", n.short(8)))
1832
    };
1833
    let mut files: BTreeMap<NodeId, FileDiff> = BTreeMap::new();
1834
    let mut order: Vec<NodeId> = Vec::new();
1835
    let mut entry = |files: &mut BTreeMap<NodeId, FileDiff>, n: NodeId, kind: &str| {
1836
        if let std::collections::btree_map::Entry::Vacant(v) = files.entry(n) {
1837
            order.push(n);
1838
            v.insert(FileDiff {
1839
                path: path_of(&n),
1840
                kind: kind.to_string(),
1841
                hunks: vec![],
1842
                from: None,
1843
            });
1844
        }
1845
    };
1846
    for op in &change.tree_ops {
1847
        match op {
1848
            TreeOp::AddNode { node, kind, .. } => {
1849
                if *kind != NodeKind::Dir {
1850
                    entry(&mut files, *node, "added");
1851
                }
1852
            }
1853
            TreeOp::RemoveNode { node, .. } => {
1854
                entry(&mut files, *node, "removed");
1855
                if let Some(e) = by_node.get(node) {
1856
                    files.get_mut(node).unwrap().path = e.path.clone();
1857
                }
1858
            }
1859
            TreeOp::Move {
1860
                node, parent, name, ..
1861
            } => {
1862
                entry(&mut files, *node, "renamed");
1863
                let f = files.get_mut(node).unwrap();
1864
                f.from = by_node.get(node).map(|e| e.path.clone());
1865
                let dir = if parent.is_root() {
1866
                    String::new()
1867
                } else {
1868
                    path_of_node(parent, &by_node, &new_names).unwrap_or_default()
1869
                };
1870
                f.path = if dir.is_empty() {
1871
                    name.clone()
1872
                } else {
1873
                    format!("{dir}/{name}")
1874
                };
1875
            }
1876
            TreeOp::SetMode { node, .. } => entry(&mut files, *node, "mode"),
1877
        }
1878
    }
1879
    // Base line numbers per node, 1-based.
1880
    let mut line_of: HashMap<NodeId, HashMap<(ChangeHash, u32), u32>> = HashMap::new();
1881
    let mut lines_for = |n: &NodeId| -> HashMap<(ChangeHash, u32), u32> {
1882
        line_of
1883
            .entry(*n)
1884
            .or_insert_with(|| {
1885
                base.live_lines(n)
1886
                    .into_iter()
1887
                    .enumerate()
1888
                    .map(|(i, (k, _))| (k, i as u32 + 1))
1889
                    .collect()
1890
            })
1891
            .clone()
1892
    };
1893
    for e in &change.edits {
1894
        let n = e.node();
1895
        let is_new = new_names.contains_key(&n);
1896
        entry(&mut files, n, if is_new { "added" } else { "modified" });
1897
        let f = files.get_mut(&n).unwrap();
1898
        match e {
1899
            Edit::Insert { after, lines, .. } => {
1900
                let map = lines_for(&n);
1901
                let base_line = match after {
1902
                    AtomRef::Start => 0,
1903
                    AtomRef::End => map.len() as u32,
1904
                    AtomRef::Atom { change, index } if change.is_zero() => {
1905
                        f.hunks.last().map(|h| h.base_line).unwrap_or(0)
1906
                    }
1907
                    AtomRef::Atom { change, index } => {
1908
                        map.get(&(*change, *index)).copied().unwrap_or(0)
1909
                    }
1910
                };
1911
                f.hunks.push(DiffHunk {
1912
                    base_line,
1913
                    added: lines.to_vec(),
1914
                    removed: vec![],
1915
                });
1916
            }
1917
            Edit::Delete { atoms, .. } => {
1918
                let map = lines_for(&n);
1919
                let mut removed = Vec::new();
1920
                for r in atoms {
1921
                    for i in r.from..r.to {
1922
                        let line = map.get(&(r.change, i)).copied().unwrap_or(0);
1923
                        let text = base
1924
                            .file(&n)
1925
                            .and_then(|g| g.content(&(r.change, i)))
1926
                            .unwrap_or(b"")
1927
                            .to_vec();
1928
                        removed.push((line, text));
1929
                    }
1930
                }
1931
                let base_line = removed
1932
                    .first()
1933
                    .map(|(l, _)| l.saturating_sub(1))
1934
                    .unwrap_or(0);
1935
                f.hunks.push(DiffHunk {
1936
                    base_line,
1937
                    added: vec![],
1938
                    removed,
1939
                });
1940
            }
1941
            Edit::Replace { .. } => {
1942
                if !is_new {
1943
                    f.kind = "replaced".into();
1944
                }
1945
            }
1946
        }
1947
    }
1948
    order.into_iter().filter_map(|n| files.remove(&n)).collect()
1949
}
1950
1951
/// Builds the tree ops and edits of a working-copy change against a base.
1952
/// `BLAKE3("oxy node 1" 0 seed kind path)`, truncated: a node identifier
1953
/// that the same seed and path always give (never the root's).
1954
fn seeded_node(seed: &[u8; 32], path: &str, kind: NodeKind) -> NodeId {
1955
    let mut h = blake3::Hasher::new();
1956
    h.update(b"oxy node 1\0");
1957
    h.update(seed);
1958
    h.update(&[match kind {
1959
        NodeKind::File => 1,
1960
        NodeKind::Dir => 2,
1961
        NodeKind::Symlink => 3,
1962
        NodeKind::Subrepo => 4,
1963
    }]);
1964
    h.update(path.as_bytes());
1965
    let mut id = [0u8; 16];
1966
    id.copy_from_slice(&h.finalize().as_bytes()[..16]);
1967
    if id == [0; 16] {
1968
        id[15] = 1;
1969
    }
1970
    NodeId(id)
1971
}
1972
1973
struct ChangeBuilder<'a> {
1974
    base: &'a State,
1975
    base_snapshot: &'a Snapshot,
1976
    tree_ops: Vec<TreeOp>,
1977
    edits: Vec<Edit>,
1978
    statuses: Vec<PathStatus>,
1979
    dir_nodes: HashMap<String, NodeId>,
1980
    reuse: HashMap<String, (NodeId, NodeKind)>,
1981
    /// Changes that contributed to conflicts this working copy resolves.
1982
    contributors: BTreeSet<ChangeHash>,
1983
    resolves: bool,
1984
    attrs: crate::attributes::Attributes,
1985
    blobs: HashMap<String, ObjectRef>,
1986
    /// Opaque files whose replace conflict the content settles.
1987
    resolve: HashSet<String>,
1988
    /// When set, new nodes' identifiers derive from it and their paths.
1989
    node_seed: Option<[u8; 32]>,
1990
    /// For a Git import, the base's dead directories by where they were
1991
    /// (see `ensure_dir`), worked out when first needed.
1992
    dead_dirs: Option<HashMap<(NodeId, String), (NodeId, crate::tree::OpKey)>>,
1993
    /// Text edits of edited files, worked out in parallel beforehand
1994
    /// (`diff_in_parallel`); a file not here is diffed when it is updated.
1995
    diffs: HashMap<String, Vec<Edit>>,
1996
}
1997
1998
impl<'a> ChangeBuilder<'a> {
1999
    fn new(
2000
        base: &'a State,
2001
        base_snapshot: &'a Snapshot,
2002
        reuse: HashMap<String, (NodeId, NodeKind)>,
2003
    ) -> Self {
2004
        let mut dir_nodes: HashMap<String, NodeId> = HashMap::new();
2005
        dir_nodes.insert(String::new(), NodeId::ROOT);
2006
        for (p, e) in base_snapshot.tree.entries.iter() {
2007
            if e.kind == NodeKind::Dir {
2008
                dir_nodes.insert(p.clone(), e.node);
2009
            }
2010
        }
2011
        ChangeBuilder {
2012
            base,
2013
            base_snapshot,
2014
            tree_ops: vec![],
2015
            edits: vec![],
2016
            statuses: vec![],
2017
            dir_nodes,
2018
            reuse,
2019
            contributors: BTreeSet::new(),
2020
            resolves: false,
2021
            attrs: crate::attributes::Attributes::default(),
2022
            blobs: HashMap::new(),
2023
            resolve: HashSet::new(),
2024
            node_seed: None,
2025
            dead_dirs: None,
2026
            diffs: HashMap::new(),
2027
        }
2028
    }
2029
2030
    /// Diff the edited text files among `entries` against their base
2031
    /// renderings at once, on every core, for `update_path` to take: the
2032
    /// same diff it would make, only not one file after another.
2033
    fn diff_in_parallel(&mut self, entries: &BTreeMap<String, FsEntry>) {
2034
        use rayon::prelude::*;
2035
        let files = &self.base_snapshot.files;
2036
        let edited: Vec<(&String, &FsEntry, &crate::state::FileState)> = entries
2037
            .iter()
2038
            .filter_map(|(p, e)| {
2039
                let x = files.get(p)?;
2040
                (x.kind == e.kind && !e.unchanged && !self.opaque_for(p, e)).then_some((p, e, x))
2041
            })
2042
            .collect();
2043
        // Below this, starting the threads costs more than it saves.
2044
        if edited.len() < 16 {
2045
            return;
2046
        }
2047
        let this = &*self;
2048
        let attrs = &this.attrs;
2049
        let diffs: Vec<(String, Vec<Edit>)> = edited
2050
            .par_iter()
2051
            .filter_map(|(p, e, x)| {
2052
                let FileContent::Text {
2053
                    bytes,
2054
                    materialized,
2055
                } = &x.content
2056
                else {
2057
                    return None;
2058
                };
2059
                if materialized.is_conflicted() {
2060
                    return None;
2061
                }
2062
                let disk_text = if attrs.lookup(p).eol.is_some() {
2063
                    std::sync::Arc::new(crate::attributes::normalize_eol(&e.content))
2064
                } else {
2065
                    e.content.clone()
2066
                };
2067
                if *bytes == *disk_text {
2068
                    return None;
2069
                }
2070
                let keys = materialized.live_atoms();
2071
                let lines = crate::diff::split_lines(bytes);
2072
                (keys.len() == lines.len()).then(|| {
2073
                    let edits = crate::diff::text_edits_of(x.node, &keys, &lines, &disk_text);
2074
                    ((*p).clone(), edits)
2075
                })
2076
            })
2077
            .collect();
2078
        self.diffs = diffs.into_iter().collect();
2079
    }
2080
2081
    fn with_attributes(mut self, attrs: crate::attributes::Attributes) -> Self {
2082
        self.attrs = attrs;
2083
        self
2084
    }
2085
2086
    /// Whether a file is opaque: forced by `binary`, forced text by `text`
2087
    /// only when it has no NUL bytes, else sniffed.
2088
    /// The blob for an opaque entry: the cached one, else stored now.
2089
    fn blob_of(
2090
        &mut self,
2091
        repo: &Repo,
2092
        path: &str,
2093
        e: &FsEntry,
2094
        nocompress: bool,
2095
    ) -> Result<ObjectRef> {
2096
        let b = match e.blob {
2097
            Some(b) => b,
2098
            None => repo.store_blob_for(&e.content, nocompress)?,
2099
        };
2100
        self.blobs.insert(path.to_string(), b);
2101
        Ok(b)
2102
    }
2103
2104
    fn opaque_for(&self, path: &str, e: &FsEntry) -> bool {
2105
        if e.blob.is_some() {
2106
            return true;
2107
        }
2108
        if e.kind == NodeKind::Symlink || e.kind == NodeKind::Subrepo {
2109
            return true;
2110
        }
2111
        match self.attrs.lookup(path).binary {
2112
            Some(true) => true,
2113
            Some(false) => is_binary(&e.content),
2114
            None => is_binary(&e.content),
2115
        }
2116
    }
2117
2118
    /// Text content as stored: `\r\n` normalized for `eol=` files.
2119
    fn stored_text(
2120
        &self,
2121
        path: &str,
2122
        content: &std::sync::Arc<Vec<u8>>,
2123
    ) -> std::sync::Arc<Vec<u8>> {
2124
        if self.attrs.lookup(path).eol.is_some() {
2125
            std::sync::Arc::new(crate::attributes::normalize_eol(content))
2126
        } else {
2127
            content.clone()
2128
        }
2129
    }
2130
2131
    /// The identifier of a node added at `path`: reused when asked, derived
2132
    /// from the seed when there is one, random otherwise.
2133
    fn new_node(&self, path: &str, kind: NodeKind) -> NodeId {
2134
        if let Some(n) = self.reused_node(path, kind) {
2135
            return n;
2136
        }
2137
        match &self.node_seed {
2138
            Some(seed) => seeded_node(seed, path, kind),
2139
            None => NodeId::random(),
2140
        }
2141
    }
2142
2143
    fn reused_node(&self, path: &str, kind: NodeKind) -> Option<NodeId> {
2144
        self.reuse
2145
            .get(path)
2146
            .filter(|(_, k)| *k == kind)
2147
            .map(|(n, _)| *n)
2148
    }
2149
2150
    /// A dead directory last placed at (`parent`, `name`) in the base.
2151
    fn revivable_dir(
2152
        &mut self,
2153
        parent: NodeId,
2154
        name: &str,
2155
    ) -> Option<(NodeId, crate::tree::OpKey)> {
2156
        let base = self.base;
2157
        self.dead_dirs
2158
            .get_or_insert_with(|| base.tree().dead_dirs())
2159
            .get(&(parent, name.to_string()))
2160
            .copied()
2161
    }
2162
2163
    fn ensure_dir(&mut self, path: &str) -> NodeId {
2164
        if let Some(n) = self.dir_nodes.get(path) {
2165
            return *n;
2166
        }
2167
        let mut parent = NodeId::ROOT;
2168
        let mut prefix = String::new();
2169
        for comp in path.split('/') {
2170
            if !prefix.is_empty() {
2171
                prefix.push('/');
2172
            }
2173
            prefix.push_str(comp);
2174
            let known = self.dir_nodes.get(&prefix).copied();
2175
            let revive = match known {
2176
                Some(_) => None,
2177
                None if self.node_seed.is_some() => self.revivable_dir(parent, comp),
2178
                None => None,
2179
            };
2180
            parent = match (known, revive) {
2181
                (Some(n), _) => n,
2182
                (None, Some((node, old))) => {
2183
                    // Git has no identity for a directory: one that comes
2184
                    // back where it was is the same directory, brought back
2185
                    // with a move, so lines of history that placed files in
2186
                    // it before and after agree (oxygen#30).
2187
                    self.tree_ops.push(TreeOp::Move {
2188
                        node,
2189
                        old: OpRef {
2190
                            change: old.0,
2191
                            index: old.1,
2192
                        },
2193
                        parent,
2194
                        name: comp.to_string(),
2195
                    });
2196
                    self.dir_nodes.insert(prefix.clone(), node);
2197
                    node
2198
                }
2199
                (None, None) => {
2200
                    let node = self.new_node(&prefix, NodeKind::Dir);
2201
                    self.tree_ops.push(TreeOp::AddNode {
2202
                        node,
2203
                        kind: NodeKind::Dir,
2204
                        mode: Mode::default(),
2205
                        parent,
2206
                        name: comp.to_string(),
2207
                    });
2208
                    self.dir_nodes.insert(prefix.clone(), node);
2209
                    node
2210
                }
2211
            };
2212
        }
2213
        parent
2214
    }
2215
2216
    fn add_path(&mut self, repo: &Repo, path: &str, e: &FsEntry) -> Result<()> {
2217
        let (dir, name) = split_path(path);
2218
        let parent = self.ensure_dir(dir);
2219
        let node = self.new_node(path, e.kind);
2220
        let opaque = self.opaque_for(path, e);
2221
        let nocompress = self.attrs.lookup(path).nocompress;
2222
        self.tree_ops.push(TreeOp::AddNode {
2223
            node,
2224
            kind: e.kind,
2225
            mode: Mode {
2226
                exec: e.exec,
2227
                opaque,
2228
            },
2229
            parent,
2230
            name: name.to_string(),
2231
        });
2232
        if opaque {
2233
            let blob = self.blob_of(repo, path, e, nocompress)?;
2234
            self.edits.push(Edit::Replace {
2235
                node,
2236
                old: None,
2237
                new: Some(blob),
2238
            });
2239
        } else if !e.content.is_empty() {
2240
            let content = self.stored_text(path, &e.content);
2241
            self.edits.push(Edit::Insert {
2242
                node,
2243
                after: crate::objects::AtomRef::Start,
2244
                before: crate::objects::AtomRef::End,
2245
                lines: crate::lines::Lines::split_shared(content),
2246
            });
2247
        }
2248
        self.statuses.push(PathStatus {
2249
            path: path.to_string(),
2250
            status: ChangeStatus::Added,
2251
        });
2252
        Ok(())
2253
    }
2254
2255
    /// Move the node at `old` to `new` and apply `e`'s content to it.
2256
    fn move_path(
2257
        &mut self,
2258
        repo: &Repo,
2259
        old: &str,
2260
        new: &str,
2261
        e: &FsEntry,
2262
        expected: &crate::state::FileState,
2263
    ) -> Result<()> {
2264
        let placement = self.base_snapshot.tree.entries[old].placement;
2265
        let (dir, name) = split_path(new);
2266
        let parent = self.ensure_dir(dir);
2267
        self.tree_ops.push(TreeOp::Move {
2268
            node: expected.node,
2269
            old: op_ref(placement),
2270
            parent,
2271
            name: name.to_string(),
2272
        });
2273
        for k in self.same_place(&expected.node, placement) {
2274
            self.tree_ops.push(TreeOp::RemoveNode {
2275
                node: expected.node,
2276
                placement: op_ref(k),
2277
            });
2278
        }
2279
        self.update_path(repo, old, e, expected)?;
2280
        // update_path reports under the old path; the rename is what the user sees.
2281
        self.statuses.retain(|s| s.path != old);
2282
        self.statuses.push(PathStatus {
2283
            path: new.to_string(),
2284
            status: ChangeStatus::Renamed,
2285
        });
2286
        Ok(())
2287
    }
2288
2289
    /// For a Git import: a node the commit keeps is in one place, the one
2290
    /// its tree names, so any other live placement it has in the base goes;
2291
    /// and a node the tree cannot show at all (an orphan) goes too. Such a
2292
    /// placement is out of sight, under a directory another line of history
2293
    /// removed, where no diff of the tree would ever reach it (oxygen#30).
2294
    fn retire_stray_placements(&mut self) {
2295
        let mut retired: HashSet<(ChangeHash, u32)> = HashSet::new();
2296
        let mut placed: BTreeSet<NodeId> = BTreeSet::new();
2297
        for op in &self.tree_ops {
2298
            match op {
2299
                TreeOp::Move { node, old, .. } => {
2300
                    retired.insert((old.change, old.index));
2301
                    placed.insert(*node);
2302
                }
2303
                TreeOp::RemoveNode { placement, .. } => {
2304
                    retired.insert((placement.change, placement.index));
2305
                }
2306
                TreeOp::AddNode { .. } | TreeOp::SetMode { .. } => {}
2307
            }
2308
        }
2309
        // Nodes kept where they were: what the base's tree view shows and
2310
        // this change neither moves nor removes.
2311
        let mut kept: HashMap<NodeId, (ChangeHash, u32)> = HashMap::new();
2312
        for e in self.base_snapshot.tree.entries.values() {
2313
            if !retired.contains(&e.placement) {
2314
                kept.insert(e.node, e.placement);
2315
            }
2316
        }
2317
        // Only a node with several live placements can have a stray one,
2318
        // and the tree view names each as a conflict.
2319
        let multi: BTreeSet<NodeId> = self
2320
            .base_snapshot
2321
            .tree
2322
            .conflicts
2323
            .iter()
2324
            .filter_map(|c| match c {
2325
                crate::tree::TreeConflict::MultiPlacement { node, .. } => Some(*node),
2326
                _ => None,
2327
            })
2328
            .collect();
2329
        let mut extra = Vec::new();
2330
        // A node whose only placements are under a directory another line
2331
        // removed (an orphan) is nowhere the tree can show, and Git's tree
2332
        // has no such path: it goes.
2333
        for c in &self.base_snapshot.tree.conflicts {
2334
            let crate::tree::TreeConflict::Orphan { node, .. } = c else {
2335
                continue;
2336
            };
2337
            if kept.contains_key(node) || placed.contains(node) {
2338
                continue;
2339
            }
2340
            for (k, _) in self.base.tree().live_placements(node) {
2341
                if retired.insert(k) {
2342
                    extra.push(TreeOp::RemoveNode {
2343
                        node: *node,
2344
                        placement: op_ref(k),
2345
                    });
2346
                }
2347
            }
2348
        }
2349
        for node in placed
2350
            .iter()
2351
            .chain(multi.iter().filter(|n| kept.contains_key(*n)))
2352
        {
2353
            for (k, _) in self.base.tree().live_placements(node) {
2354
                if retired.contains(&k) || kept.get(node) == Some(&k) {
2355
                    continue;
2356
                }
2357
                retired.insert(k);
2358
                extra.push(TreeOp::RemoveNode {
2359
                    node: *node,
2360
                    placement: op_ref(k),
2361
                });
2362
            }
2363
        }
2364
        if !extra.is_empty() {
2365
            self.resolves = true;
2366
            self.tree_ops.extend(extra);
2367
        }
2368
    }
2369
2370
    /// The node's other live placements at the same place as `k`, the one
2371
    /// the tree shows: two lines of history that put a node back where it
2372
    /// was each leave a placement, and the tree shows them as one file. A
2373
    /// change that removes or moves it retires them together, or the copy
2374
    /// left behind outlives its directory (oxygen#88).
2375
    fn same_place(&self, node: &NodeId, k: (ChangeHash, u32)) -> Vec<(ChangeHash, u32)> {
2376
        let tree = self.base.tree();
2377
        let Some(shown) = tree.placement(&k) else {
2378
            return Vec::new();
2379
        };
2380
        tree.live_placements(node)
2381
            .into_iter()
2382
            .filter(|(o, p)| *o != k && p.parent == shown.parent && p.name == shown.name)
2383
            .map(|(o, _)| o)
2384
            .collect()
2385
    }
2386
2387
    fn remove_path(&mut self, path: &str, expected: &crate::state::FileState) {
2388
        let entry = &self.base_snapshot.tree.entries[path];
2389
        let placement = entry.placement;
2390
        self.tree_ops.push(TreeOp::RemoveNode {
2391
            node: expected.node,
2392
            placement: op_ref(placement),
2393
        });
2394
        for k in self.same_place(&expected.node, placement) {
2395
            self.tree_ops.push(TreeOp::RemoveNode {
2396
                node: expected.node,
2397
                placement: op_ref(k),
2398
            });
2399
        }
2400
        if path.contains(".oxy-conflict-") || expected.is_conflicted() {
2401
            self.resolves = true;
2402
        }
2403
        self.statuses.push(PathStatus {
2404
            path: path.to_string(),
2405
            status: ChangeStatus::Removed,
2406
        });
2407
    }
2408
2409
    fn update_path(
2410
        &mut self,
2411
        repo: &Repo,
2412
        path: &str,
2413
        e: &FsEntry,
2414
        expected: &crate::state::FileState,
2415
    ) -> Result<()> {
2416
        if expected.kind != e.kind {
2417
            self.remove_path(path, expected);
2418
            self.statuses.pop();
2419
            self.add_path(repo, path, e)?;
2420
            self.statuses.pop();
2421
            self.statuses.push(PathStatus {
2422
                path: path.to_string(),
2423
                status: ChangeStatus::Modified,
2424
            });
2425
            return Ok(());
2426
        }
2427
        let entry = &self.base_snapshot.tree.entries[path];
2428
        let node = expected.node;
2429
        let mode_atom = entry.mode_atom.map(op_ref);
2430
        if e.unchanged {
2431
            // Known equal to the base's unconflicted rendering (spec
2432
            // §12.3); only the executable bit can differ.
2433
            if e.exec != expected.mode.exec {
2434
                if let Some(old) = mode_atom {
2435
                    self.tree_ops.push(TreeOp::SetMode {
2436
                        node,
2437
                        old,
2438
                        mode: Mode {
2439
                            exec: e.exec,
2440
                            opaque: false,
2441
                        },
2442
                    });
2443
                    self.statuses.push(PathStatus {
2444
                        path: path.to_string(),
2445
                        status: ChangeStatus::ModeChanged,
2446
                    });
2447
                }
2448
            }
2449
            return Ok(());
2450
        }
2451
        let mut status: Option<ChangeStatus> = None;
2452
        let wants_opaque = self.opaque_for(path, e);
2453
        let nocompress = self.attrs.lookup(path).nocompress;
2454
        let disk_text = self.stored_text(path, &e.content);
2455
        match &expected.content {
2456
            FileContent::Dir => {}
2457
            FileContent::Text {
2458
                bytes,
2459
                materialized,
2460
            } => {
2461
                if materialized.is_conflicted() {
2462
                    if bytes == &*disk_text {
2463
                        return Ok(());
2464
                    }
2465
                    if has_conflict_markers(&e.content) {
2466
                        self.statuses.push(PathStatus {
2467
                            path: path.to_string(),
2468
                            status: ChangeStatus::ConflictEdited,
2469
                        });
2470
                        return Ok(());
2471
                    }
2472
                    // Resolution (spec §9.6): diff against the unconflicted lines
2473
                    // with each region as a gap, then retire every region atom.
2474
                    // Whatever the author kept from a region is re-inserted as
2475
                    // new atoms, which leaves the graph totally ordered.
2476
                    let regions = self.base.conflict_regions(&node);
2477
                    let mut edits = text_edits(node, &regions.plain, &disk_text);
2478
                    if !regions.region_atoms.is_empty() {
2479
                        edits.insert(
2480
                            0,
2481
                            Edit::Delete {
2482
                                node,
2483
                                atoms: ranges(&regions.region_atoms),
2484
                            },
2485
                        );
2486
                    }
2487
                    self.edits.extend(edits);
2488
                    self.contributors.extend(regions.contributors);
2489
                    self.resolves = true;
2490
                    if e.exec != expected.mode.exec {
2491
                        if let Some(old) = mode_atom {
2492
                            self.tree_ops.push(TreeOp::SetMode {
2493
                                node,
2494
                                old,
2495
                                mode: Mode {
2496
                                    exec: e.exec,
2497
                                    opaque: false,
2498
                                },
2499
                            });
2500
                        }
2501
                    }
2502
                    self.statuses.push(PathStatus {
2503
                        path: path.to_string(),
2504
                        status: ChangeStatus::Resolved,
2505
                    });
2506
                    return Ok(());
2507
                }
2508
                if wants_opaque {
2509
                    // Text → opaque (spec §7.5), by content or by attribute.
2510
                    if let Some(old) = mode_atom {
2511
                        self.tree_ops.push(TreeOp::SetMode {
2512
                            node,
2513
                            old,
2514
                            mode: Mode {
2515
                                exec: e.exec,
2516
                                opaque: true,
2517
                            },
2518
                        });
2519
                    }
2520
                    let live: Vec<_> = repo_live_keys(self.base, &node);
2521
                    if !live.is_empty() {
2522
                        self.edits.push(Edit::Delete {
2523
                            node,
2524
                            atoms: ranges(&live),
2525
                        });
2526
                    }
2527
                    let blob = self.blob_of(repo, path, e, nocompress)?;
2528
                    self.edits.push(Edit::Replace {
2529
                        node,
2530
                        old: None,
2531
                        new: Some(blob),
2532
                    });
2533
                    status = Some(ChangeStatus::Modified);
2534
                } else if bytes != &*disk_text {
2535
                    let mut laps = crate::timing::Laps::start();
2536
                    // The base's rendering holds its live atoms in order,
2537
                    // one per line (it is not conflicted here).
2538
                    let edits = match self.diffs.remove(path) {
2539
                        Some(edits) => edits,
2540
                        None => {
2541
                            let keys = materialized.live_atoms();
2542
                            let lines = crate::diff::split_lines(bytes);
2543
                            if keys.len() == lines.len() {
2544
                                crate::diff::text_edits_of(node, &keys, &lines, &disk_text)
2545
                            } else {
2546
                                text_edits(node, &self.base.live_lines(&node), &disk_text)
2547
                            }
2548
                        }
2549
                    };
2550
                    laps.lap("build: text diff");
2551
                    if !edits.is_empty() {
2552
                        self.edits.extend(edits);
2553
                        status = Some(ChangeStatus::Modified);
2554
                    }
2555
                }
2556
                let switched_to_opaque = wants_opaque;
2557
                if !switched_to_opaque && e.exec != expected.mode.exec {
2558
                    if let Some(old) = mode_atom {
2559
                        self.tree_ops.push(TreeOp::SetMode {
2560
                            node,
2561
                            old,
2562
                            mode: Mode {
2563
                                exec: e.exec,
2564
                                opaque: false,
2565
                            },
2566
                        });
2567
                        status.get_or_insert(ChangeStatus::ModeChanged);
2568
                    }
2569
                }
2570
            }
2571
            FileContent::Opaque { blobs } => {
2572
                let new_ref = e.blob.unwrap_or_else(|| Repo::blob_ref(&e.content));
2573
                if e.kind == NodeKind::File && wants_opaque {
2574
                    // Unchanged or replaced, the file stays opaque: remember its blob.
2575
                    self.blobs.insert(path.to_string(), new_ref);
2576
                }
2577
                if blobs.len() > 1 && self.resolve.contains(path) && e.kind == expected.kind {
2578
                    // Settle the replace conflict (spec §9.3): replace every
2579
                    // live candidate with the chosen blob, depending on each
2580
                    // change that made one live, so all are superseded.
2581
                    let chosen = self.blob_of(repo, path, e, nocompress)?;
2582
                    for b in blobs {
2583
                        self.edits.push(Edit::Replace {
2584
                            node,
2585
                            old: Some(*b),
2586
                            new: Some(chosen),
2587
                        });
2588
                    }
2589
                    self.contributors
2590
                        .extend(self.base.blob_contributors(&node, blobs));
2591
                    self.resolves = true;
2592
                    self.statuses.push(PathStatus {
2593
                        path: path.to_string(),
2594
                        status: ChangeStatus::Resolved,
2595
                    });
2596
                    return Ok(());
2597
                }
2598
                if blobs.len() > 1 {
2599
                    if !blobs.contains(&new_ref) {
2600
                        self.statuses.push(PathStatus {
2601
                            path: path.to_string(),
2602
                            status: ChangeStatus::ConflictEdited,
2603
                        });
2604
                    }
2605
                    return Ok(());
2606
                }
2607
                let current = blobs.first().copied();
2608
                if current != Some(new_ref) {
2609
                    if e.kind == NodeKind::File && !wants_opaque {
2610
                        // Opaque → text (spec §7.5).
2611
                        if let Some(old) = mode_atom {
2612
                            self.tree_ops.push(TreeOp::SetMode {
2613
                                node,
2614
                                old,
2615
                                mode: Mode {
2616
                                    exec: e.exec,
2617
                                    opaque: false,
2618
                                },
2619
                            });
2620
                        }
2621
                        self.edits.push(Edit::Replace {
2622
                            node,
2623
                            old: current,
2624
                            new: None,
2625
                        });
2626
                        if !e.content.is_empty() {
2627
                            self.edits.push(Edit::Insert {
2628
                                node,
2629
                                after: crate::objects::AtomRef::Start,
2630
                                before: crate::objects::AtomRef::End,
2631
                                lines: crate::lines::Lines::split(&e.content),
2632
                            });
2633
                        }
2634
                    } else {
2635
                        let blob = self.blob_of(repo, path, e, nocompress)?;
2636
                        self.edits.push(Edit::Replace {
2637
                            node,
2638
                            old: current,
2639
                            new: Some(blob),
2640
                        });
2641
                    }
2642
                    status = Some(ChangeStatus::Modified);
2643
                } else if e.kind == NodeKind::File && e.exec != expected.mode.exec {
2644
                    if let Some(old) = mode_atom {
2645
                        self.tree_ops.push(TreeOp::SetMode {
2646
                            node,
2647
                            old,
2648
                            mode: Mode {
2649
                                exec: e.exec,
2650
                                opaque: true,
2651
                            },
2652
                        });
2653
                        status = Some(ChangeStatus::ModeChanged);
2654
                    }
2655
                }
2656
            }
2657
        }
2658
        if let Some(s) = status {
2659
            self.statuses.push(PathStatus {
2660
                path: path.to_string(),
2661
                status: s,
2662
            });
2663
        }
2664
        Ok(())
2665
    }
2666
}
2667
2668
fn repo_live_keys(base: &State, node: &NodeId) -> Vec<crate::graph::AtomKey> {
2669
    base.live_lines(node).into_iter().map(|(k, _)| k).collect()
2670
}
2671
2672
/// The changes a change's scope references (spec §8.1): introducers of every
2673
/// atom, placement, and mode it touches, and of every node it operates on.
2674
pub fn referenced_changes(change: &Change, base: &State) -> BTreeSet<ChangeHash> {
2675
    let mut out = BTreeSet::new();
2676
    let opref = |r: &OpRef, out: &mut BTreeSet<ChangeHash>| {
2677
        if !r.change.is_zero() {
2678
            out.insert(r.change);
2679
        }
2680
    };
2681
    let mut nodes: Vec<NodeId> = Vec::new();
2682
    for op in &change.tree_ops {
2683
        match op {
2684
            TreeOp::AddNode { parent, .. } => nodes.push(*parent),
2685
            TreeOp::RemoveNode { node, placement } => {
2686
                nodes.push(*node);
2687
                opref(placement, &mut out);
2688
            }
2689
            TreeOp::Move {
2690
                node, old, parent, ..
2691
            } => {
2692
                nodes.push(*node);
2693
                nodes.push(*parent);
2694
                opref(old, &mut out);
2695
            }
2696
            TreeOp::SetMode { node, old, .. } => {
2697
                nodes.push(*node);
2698
                opref(old, &mut out);
2699
            }
2700
        }
2701
    }
2702
    for e in &change.edits {
2703
        nodes.push(e.node());
2704
        match e {
2705
            Edit::Insert { after, before, .. } => {
2706
                for r in [after, before] {
2707
                    if let crate::objects::AtomRef::Atom { change, .. } = r {
2708
                        if !change.is_zero() {
2709
                            out.insert(*change);
2710
                        }
2711
                    }
2712
                }
2713
            }
2714
            Edit::Delete { atoms, .. } => {
2715
                // Deleting an atom also depends on whoever inserted the live
2716
                // atoms right after it: the author saw those insertions, and
2717
                // without the dependency spec §9.1 would call the deletion
2718
                // concurrent with them (a delete/insert conflict).
2719
                let graph = base.file(&e.node());
2720
                for r in atoms {
2721
                    if !r.change.is_zero() {
2722
                        out.insert(r.change);
2723
                    }
2724
                    if let Some(g) = graph {
2725
                        for i in r.from..r.to {
2726
                            out.extend(
2727
                                g.live_successor_changes(&(r.change, i))
2728
                                    .into_iter()
2729
                                    .filter(|c| !c.is_zero()),
2730
                            );
2731
                        }
2732
                    }
2733
                }
2734
            }
2735
            // Replacing a blob depends on the change that made it current,
2736
            // as deleting a line depends on the line's introducer.
2737
            Edit::Replace {
2738
                node,
2739
                old: Some(old),
2740
                ..
2741
            } => {
2742
                out.extend(
2743
                    base.live_replaces(node)
2744
                        .into_iter()
2745
                        .filter(|(c, b)| b == old && !c.is_zero())
2746
                        .map(|(c, _)| c),
2747
                );
2748
            }
2749
            Edit::Replace { .. } => {}
2750
        }
2751
    }
2752
    for n in nodes {
2753
        if let Some(h) = base.tree().introducer(&n) {
2754
            out.insert(h);
2755
        }
2756
    }
2757
    out
2758
}
2759
2760
/// Paths of the nodes a change adds on top of `base_snapshot`.
2761
pub fn added_node_paths(
2762
    change: &Change,
2763
    base_snapshot: &Snapshot,
2764
) -> HashMap<String, (NodeId, NodeKind)> {
2765
    let by_node = base_snapshot.tree.by_node();
2766
    let mut new_names: HashMap<NodeId, (NodeId, String, NodeKind)> = HashMap::new();
2767
    for op in &change.tree_ops {
2768
        if let TreeOp::AddNode {
2769
            node,
2770
            parent,
2771
            name,
2772
            kind,
2773
            ..
2774
        } = op
2775
        {
2776
            new_names.insert(*node, (*parent, name.clone(), *kind));
2777
        }
2778
    }
2779
    let mut out = HashMap::new();
2780
    for (node, (_, _, kind)) in &new_names {
2781
        if let Some(path) = path_of_node(node, &by_node, &new_names) {
2782
            out.insert(path, (*node, *kind));
2783
        }
2784
    }
2785
    out
2786
}
2787
2788
fn path_of_node(
2789
    n: &NodeId,
2790
    by_node: &HashMap<NodeId, &crate::tree::TreeEntry>,
2791
    new_names: &HashMap<NodeId, (NodeId, String, NodeKind)>,
2792
) -> Option<String> {
2793
    if let Some(e) = by_node.get(n) {
2794
        return Some(e.path.clone());
2795
    }
2796
    let mut parts = Vec::new();
2797
    let mut cur = *n;
2798
    loop {
2799
        if cur.is_root() {
2800
            break;
2801
        }
2802
        if let Some(e) = by_node.get(&cur) {
2803
            if !e.path.is_empty() {
2804
                parts.push(e.path.clone());
2805
            }
2806
            break;
2807
        }
2808
        let (parent, name, _) = new_names.get(&cur)?;
2809
        parts.push(name.clone());
2810
        cur = *parent;
2811
    }
2812
    parts.reverse();
2813
    Some(parts.join("/"))
2814
}
2815
2816
/// Render a change's operations with line content, using `base` for deleted lines.
2817
pub fn render_change(change: &Change, base: &State, base_snapshot: &Snapshot) -> String {
2818
    let by_node = base_snapshot.tree.by_node();
2819
    let mut new_names: HashMap<NodeId, (NodeId, String, NodeKind)> = HashMap::new();
2820
    for op in &change.tree_ops {
2821
        if let TreeOp::AddNode {
2822
            node,
2823
            parent,
2824
            name,
2825
            kind,
2826
            ..
2827
        } = op
2828
        {
2829
            new_names.insert(*node, (*parent, name.clone(), *kind));
2830
        }
2831
    }
2832
    let path_of = |n: &NodeId| -> String {
2833
        path_of_node(n, &by_node, &new_names).unwrap_or_else(|| format!("<node {}>", n.short(8)))
2834
    };
2835
2836
    let mut out = String::new();
2837
    for op in &change.tree_ops {
2838
        match op {
2839
            TreeOp::AddNode {
2840
                node, kind, mode, ..
2841
            } => {
2842
                out.push_str(&format!(
2843
                    "A {} ({:?}{}{})\n",
2844
                    path_of(node),
2845
                    kind,
2846
                    if mode.exec { ", exec" } else { "" },
2847
                    if mode.opaque { ", opaque" } else { "" }
2848
                ));
2849
            }
2850
            TreeOp::RemoveNode { node, .. } => out.push_str(&format!("D {}\n", path_of(node))),
2851
            TreeOp::Move { node, name, .. } => {
2852
                out.push_str(&format!("R {} -> {}\n", path_of(node), name))
2853
            }
2854
            TreeOp::SetMode { node, mode, .. } => {
2855
                out.push_str(&format!(
2856
                    "M {} mode: exec={} opaque={}\n",
2857
                    path_of(node),
2858
                    mode.exec,
2859
                    mode.opaque
2860
                ));
2861
            }
2862
        }
2863
    }
2864
    let mut last_node: Option<NodeId> = None;
2865
    for e in &change.edits {
2866
        let n = e.node();
2867
        if last_node != Some(n) {
2868
            out.push_str(&format!("--- {}\n", path_of(&n)));
2869
            last_node = Some(n);
2870
        }
2871
        match e {
2872
            Edit::Insert { lines, .. } => {
2873
                for l in lines.iter() {
2874
                    out.push('+');
2875
                    out.push_str(&String::from_utf8_lossy(l));
2876
                    if !l.ends_with(b"\n") {
2877
                        out.push('\n');
2878
                    }
2879
                }
2880
            }
2881
            Edit::Delete { atoms, .. } => {
2882
                for r in atoms {
2883
                    for i in r.from..r.to {
2884
                        let content = base
2885
                            .file(&n)
2886
                            .and_then(|g| g.content(&(r.change, i)))
2887
                            .unwrap_or(b"<unknown>\n");
2888
                        out.push('-');
2889
                        out.push_str(&String::from_utf8_lossy(content));
2890
                        if !content.ends_with(b"\n") {
2891
                            out.push('\n');
2892
                        }
2893
                    }
2894
                }
2895
            }
2896
            Edit::Replace { old, new, .. } => {
2897
                out.push_str(&format!(
2898
                    "  opaque content {} -> {}\n",
2899
                    old.map(|o| o.short(12)).unwrap_or_else(|| "none".into()),
2900
                    new.map(|o| o.short(12)).unwrap_or_else(|| "none".into())
2901
                ));
2902
            }
2903
        }
2904
    }
2905
    out
2906
}
2907
2908
/// Pair removed files with added files of the same kind whose contents are
2909
/// at least `RENAME_THRESHOLD` percent alike, best matches first. Beyond
2910
/// `RENAME_LIMIT` candidate pairs only identical contents are paired.
2911
const RENAME_THRESHOLD: u32 = 50;
2912
const RENAME_LIMIT: usize = 10_000;
2913
2914
/// How a change is built beyond its entries: for a Git import, the seed
2915
/// its new nodes' identifiers derive from; and, when it is built from part
2916
/// of the tree, whether the new tree has anything under a directory.
2917
#[derive(Default)]
2918
struct Scope<'a> {
2919
    seed: Option<[u8; 32]>,
2920
    dir_needed: Option<&'a dyn Fn(&str) -> bool>,
2921
}
2922
2923
fn detect_renames(
2924
    base_snapshot: &Snapshot,
2925
    fs_entries: &BTreeMap<String, FsEntry>,
2926
    in_scope: impl Fn(&str) -> bool,
2927
) -> Vec<(String, String)> {
2928
    let removed: Vec<(&String, &crate::state::FileState)> = base_snapshot
2929
        .files
2930
        .iter()
2931
        .filter(|(p, f)| {
2932
            f.kind != NodeKind::Dir
2933
                && !fs_entries.contains_key(*p)
2934
                && in_scope(p)
2935
                && !f.is_conflicted()
2936
        })
2937
        .collect();
2938
    let added: Vec<(&String, &FsEntry)> = fs_entries
2939
        .iter()
2940
        .filter(|(p, e)| e.kind != NodeKind::Dir && !base_snapshot.files.contains_key(*p))
2941
        .collect();
2942
    if removed.is_empty() || added.is_empty() {
2943
        return vec![];
2944
    }
2945
    let exact_only = removed.len() * added.len() > RENAME_LIMIT;
2946
    let old_content = |f: &crate::state::FileState| -> Option<Vec<u8>> {
2947
        match &f.content {
2948
            FileContent::Text { bytes, .. } => Some(bytes.clone()),
2949
            _ => None,
2950
        }
2951
    };
2952
    let mut scored: Vec<(u32, usize, usize)> = Vec::new();
2953
    for (ri, (_, f)) in removed.iter().enumerate() {
2954
        let old = old_content(f);
2955
        let old_blob = match &f.content {
2956
            FileContent::Opaque { blobs } if blobs.len() == 1 => Some(blobs[0]),
2957
            _ => None,
2958
        };
2959
        for (ai, (_, e)) in added.iter().enumerate() {
2960
            if e.kind != f.kind {
2961
                continue;
2962
            }
2963
            let score = match (&old, old_blob) {
2964
                (Some(o), _) => {
2965
                    if exact_only {
2966
                        if *o == *e.content {
2967
                            100
2968
                        } else {
2969
                            0
2970
                        }
2971
                    } else {
2972
                        similarity(o, &e.content)
2973
                    }
2974
                }
2975
                (None, Some(b)) if e.blob.unwrap_or_else(|| Repo::blob_ref(&e.content)) == b => 100,
2976
                _ => 0,
2977
            };
2978
            if score >= RENAME_THRESHOLD {
2979
                scored.push((score, ri, ai));
2980
            }
2981
        }
2982
    }
2983
    scored.sort_by(|a, b| {
2984
        b.0.cmp(&a.0)
2985
            .then(removed[a.1].0.cmp(removed[b.1].0))
2986
            .then(added[a.2].0.cmp(added[b.2].0))
2987
    });
2988
    let mut used_r = vec![false; removed.len()];
2989
    let mut used_a = vec![false; added.len()];
2990
    let mut out = Vec::new();
2991
    for (_, ri, ai) in scored {
2992
        if used_r[ri] || used_a[ai] {
2993
            continue;
2994
        }
2995
        used_r[ri] = true;
2996
        used_a[ai] = true;
2997
        out.push((removed[ri].0.clone(), added[ai].0.clone()));
2998
    }
2999
    out
3000
}
3001
3002
/// Percentage of the larger file's bytes found in lines the two share
3003
/// (multiset intersection of lines), like Git's similarity index.
3004
pub fn similarity(a: &[u8], b: &[u8]) -> u32 {
3005
    if a == b {
3006
        return 100;
3007
    }
3008
    if a.is_empty() || b.is_empty() {
3009
        return 0;
3010
    }
3011
    let mut counts: HashMap<&[u8], usize> = HashMap::new();
3012
    for l in split_lines(a) {
3013
        *counts.entry(l).or_default() += 1;
3014
    }
3015
    let mut shared = 0usize;
3016
    for l in split_lines(b) {
3017
        if let Some(n) = counts.get_mut(l) {
3018
            if *n > 0 {
3019
                *n -= 1;
3020
                shared += l.len();
3021
            }
3022
        }
3023
    }
3024
    (shared * 100 / a.len().max(b.len())) as u32
3025
}
3026
3027
/// Two maps side by side in key order: each key of either, with its value
3028
/// in each. Linear, with no lookups, for maps of a whole tree.
3029
fn join<'a, A, B>(
3030
    a: &'a BTreeMap<String, A>,
3031
    b: &'a BTreeMap<String, B>,
3032
) -> impl Iterator<Item = (&'a String, Option<&'a A>, Option<&'a B>)> {
3033
    let (mut a, mut b) = (a.iter().peekable(), b.iter().peekable());
3034
    std::iter::from_fn(move || match (a.peek(), b.peek()) {
3035
        (None, None) => None,
3036
        (Some(_), None) => a.next().map(|(k, v)| (k, Some(v), None)),
3037
        (None, Some(_)) => b.next().map(|(k, v)| (k, None, Some(v))),
3038
        (Some((ka, _)), Some((kb, _))) => match ka.cmp(kb) {
3039
            std::cmp::Ordering::Less => a.next().map(|(k, v)| (k, Some(v), None)),
3040
            std::cmp::Ordering::Greater => b.next().map(|(k, v)| (k, None, Some(v))),
3041
            std::cmp::Ordering::Equal => {
3042
                let (k, va) = a.next()?;
3043
                let (_, vb) = b.next()?;
3044
                Some((k, Some(va), Some(vb)))
3045
            }
3046
        },
3047
    })
3048
}
3049
3050
#[cfg(test)]
3051
mod join_tests {
3052
    use super::*;
3053
3054
    #[test]
3055
    fn join_pairs_every_key_in_order() {
3056
        let a: BTreeMap<String, u8> = [("a", 1), ("b/c", 2), ("d", 3)]
3057
            .into_iter()
3058
            .map(|(k, v)| (k.to_string(), v))
3059
            .collect();
3060
        let b: BTreeMap<String, char> = [("b", 'x'), ("b/c", 'y'), ("e", 'z')]
3061
            .into_iter()
3062
            .map(|(k, v)| (k.to_string(), v))
3063
            .collect();
3064
        let got: Vec<(String, Option<u8>, Option<char>)> = join(&a, &b)
3065
            .map(|(k, x, y)| (k.clone(), x.copied(), y.copied()))
3066
            .collect();
3067
        let want = vec![
3068
            ("a".to_string(), Some(1), None),
3069
            ("b".to_string(), None, Some('x')),
3070
            ("b/c".to_string(), Some(2), Some('y')),
3071
            ("d".to_string(), Some(3), None),
3072
            ("e".to_string(), None, Some('z')),
3073
        ];
3074
        assert_eq!(got, want);
3075
    }
3076
}