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