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