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