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