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