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