OXYGENHUB
# e8d38e47e9d7 oxygen / crates / oxy-core / src / repo / snapshot.rs
76.1 KiB · Rust · last changed History-only states: log, log of a path and blame_in load changes and tree only, deferring file edits; load_graphs builds the graphs a command needs from checkpoint blobs or by replay, identical to a full load; an unloaded graph is never read as empty 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
        // Attributes come from the files being committed, so a new
114
        // `.oxyattributes` applies to the same change that adds it.
115
        let attrs = crate::attributes::Attributes::from_files(
116
            fs_entries
117
                .iter()
118
                .filter(|(p, _)| p.as_str() == ".oxyattributes" || p.ends_with("/.oxyattributes"))
119
                .map(|(p, e)| (p.as_str(), e.content.as_slice())),
120
        );
121
        let mut b = ChangeBuilder::new(base, base_snapshot, reuse).with_attributes(attrs);
122
        // Rename detection (spec §7.1, §23): a removed file and an added file
123
        // of the same kind whose contents are at least half alike become one
124
        // move of the same node, so identity survives across the rename.
125
        let renames = detect_renames(base_snapshot, fs_entries, |p| self.in_scope(p));
126
        let renamed_from: HashMap<&str, &str> = renames
127
            .iter()
128
            .map(|(old, new)| (new.as_str(), old.as_str()))
129
            .collect();
130
        let renamed_to: HashMap<&str, &str> = renames
131
            .iter()
132
            .map(|(old, new)| (old.as_str(), new.as_str()))
133
            .collect();
134
        for (path, fs_entry) in fs_entries {
135
            match base_snapshot.files.get(path) {
136
                None => match renamed_from.get(path.as_str()) {
137
                    Some(old) => {
138
                        b.move_path(self, old, path, fs_entry, &base_snapshot.files[*old])?
139
                    }
140
                    None => b.add_path(self, path, fs_entry)?,
141
                },
142
                Some(expected) => b.update_path(self, path, fs_entry, expected)?,
143
            }
144
        }
145
        for (path, expected) in &base_snapshot.files {
146
            if fs_entries.contains_key(path)
147
                || !self.in_scope(path)
148
                || renamed_to.contains_key(path.as_str())
149
            {
150
                continue;
151
            }
152
            // A directory stays while anything under it exists or is out of scope.
153
            let still_needed = expected.kind == NodeKind::Dir
154
                && (fs_entries
155
                    .keys()
156
                    .any(|p| p.starts_with(&format!("{path}/")))
157
                    || base_snapshot
158
                        .files
159
                        .keys()
160
                        .any(|p| p.starts_with(&format!("{path}/")) && !self.in_scope(p)));
161
            if !still_needed {
162
                b.remove_path(path, expected);
163
            }
164
        }
165
        let mut statuses = b.statuses;
166
        statuses.sort_by(|a, b| a.path.cmp(&b.path));
167
        Ok(BuiltChange {
168
            tree_ops: b.tree_ops,
169
            edits: b.edits,
170
            contributors: b.contributors.into_iter().collect(),
171
            resolves: b.resolves,
172
            statuses,
173
            blobs: b.blobs,
174
        })
175
    }
176
177
    /// Store a change and, when `core.sign = change` and we are its author,
178
    /// sign it. A rewritten change by another author is stored unsigned: only
179
    /// its author (or a delegate) can vouch for it.
180
    pub(crate) fn store_signed(&self, change: &Change) -> Result<ChangeHash> {
181
        let ours = change.author == self.author();
182
        if self.config.sign_changes && ours && self.secret_key()?.is_none() {
183
            return fail("core.sign is \"change\" but no secret key is available for author.key");
184
        }
185
        let hash = self.store.put_change(change)?;
186
        if self.config.sign_changes && ours {
187
            self.sign_change(&hash)?;
188
        }
189
        Ok(hash)
190
    }
191
192
    /// Snapshot the working copy into the working-copy change (spec §12.3).
193
    pub fn snapshot(&self, command: &str) -> Result<SnapshotResult> {
194
        let _lock = self.lock_snapshot()?;
195
        let batch = self.store.begin_batch()?;
196
        let result = self.snapshot_locked(command);
197
        batch.finish()?;
198
        result
199
    }
200
201
    fn snapshot_locked(&self, command: &str) -> Result<SnapshotResult> {
202
        let _all = crate::timing::phase("snapshot");
203
        let (op_ref, op) = self.head_op()?;
204
        let (old_hash, old_wc) = self.working_copy()?;
205
        let base = {
206
            let _t = crate::timing::phase("snapshot: load base state");
207
            self.load_state(&old_wc.deps)?
208
        };
209
        let base_snapshot = {
210
            let _t = crate::timing::phase("snapshot: materialize base");
211
            base.materialize()
212
        };
213
214
        // Reuse the NodeIds the previous working-copy version assigned to new
215
        // paths, so an unchanged working copy hashes identically (spec §12.3).
216
        let reuse = added_node_paths(&old_wc, &base_snapshot);
217
        // The last manifest lets unchanged opaque files go unread.
218
        let manifest = self.read_manifest()?.map(|(_, _, m)| m);
219
        let mut fs_entries = {
220
            let _t = crate::timing::phase("snapshot: read working copy");
221
            self.walk_working_copy_with(
222
                manifest.as_ref(),
223
                &Self::tracked_kinds(&base_snapshot),
224
                Some(&base_snapshot),
225
            )?
226
        };
227
        self.platform_normalize(&mut fs_entries, &base_snapshot);
228
        let built = {
229
            let _t = crate::timing::phase("snapshot: diff against base");
230
            self.build_from_entries(&base, &base_snapshot, reuse, &fs_entries)?
231
        };
232
233
        let mut wc = Change {
234
            change_id: old_wc.change_id,
235
            deps: vec![],
236
            author: self.author(),
237
            hlc: old_wc.hlc,
238
            message: old_wc.message.clone(),
239
            tree_ops: built.tree_ops,
240
            edits: built.edits,
241
            kind: ChangeKind::WorkingCopy,
242
        };
243
        let base_heads = base.maximal(&old_wc.deps);
244
        let mut deps: BTreeSet<ChangeHash> = base_heads.into_iter().collect();
245
        deps.extend(referenced_changes(&wc, &base));
246
        deps.extend(built.contributors.iter().copied());
247
        wc.deps = deps.into_iter().collect();
248
        wc.normalize();
249
        let resolves = built.resolves;
250
        let contributors = built.contributors;
251
        let statuses = built.statuses;
252
        // Empty snapshot: hash the candidate before storing; only record an op on change.
253
        let new_hash = wc.hash();
254
        let changed = new_hash != old_hash;
255
        if changed {
256
            self.store.put_change(&wc)?;
257
            let mut view = op.view.clone();
258
            view.workspaces.insert(self.workspace, new_hash);
259
            self.record_op(&[op_ref], &format!("{command}{SNAPSHOT_SUFFIX}"), view)?;
260
        }
261
        // The prompt compares against this without recording anything.
262
        let _t = crate::timing::phase("snapshot: write manifest");
263
        self.write_manifest_entries(
264
            base_snapshot.is_conflicted(),
265
            !wc.tree_ops.is_empty() || !wc.edits.is_empty(),
266
            &fs_entries,
267
            &built.blobs,
268
        )?;
269
        Ok(SnapshotResult {
270
            wc_hash: new_hash,
271
            wc,
272
            base,
273
            base_snapshot,
274
            statuses,
275
            changed,
276
            resolves,
277
            contributors,
278
        })
279
    }
280
281
    /// `oxy status --json` (spec §9.5): the changed paths and every conflict
282
    /// of the working copy's base with its kind, path, and contributing
283
    /// ChangeIds.
284
    pub fn status_json(&self, snap: &SnapshotResult) -> Result<String> {
285
        let heads = self.bookmark_heads()?;
286
        let base_snapshot = &snap.base_snapshot;
287
        let by_node = base_snapshot.tree.by_node();
288
        let path_of = |n: &NodeId| by_node.get(n).map(|e| e.path.clone());
289
        let id_of = |h: &ChangeHash| {
290
            snap.base
291
                .get(h)
292
                .map(|m| m.change_id.to_hex())
293
                .unwrap_or_else(|| h.to_hex())
294
        };
295
        let paths = json_array(snap.statuses.iter().map(|s| {
296
            format!(
297
                "{{\"path\":{},\"status\":{}}}",
298
                json_str(&s.path),
299
                json_str(&format!("{:?}", s.status))
300
            )
301
        }));
302
        let mut conflicts: Vec<String> = Vec::new();
303
        for (p, f) in &base_snapshot.files {
304
            if !f.is_conflicted() {
305
                continue;
306
            }
307
            let (kind, changes) = match &f.content {
308
                FileContent::Text { .. } => {
309
                    ("text", snap.base.conflict_regions(&f.node).contributors)
310
                }
311
                FileContent::Opaque { blobs } => {
312
                    ("replace", snap.base.blob_contributors(&f.node, blobs))
313
                }
314
                FileContent::Dir => continue,
315
            };
316
            let resolved = match snap
317
                .statuses
318
                .iter()
319
                .find(|s| s.path == *p)
320
                .map(|s| s.status)
321
            {
322
                Some(ChangeStatus::Resolved) => "true",
323
                Some(ChangeStatus::ConflictEdited) => "\"markers\"",
324
                _ => "false",
325
            };
326
            conflicts.push(format!(
327
                "{{\"kind\":{},\"path\":{},\"node\":{},\"changes\":{},\"resolved\":{resolved}}}",
328
                json_str(kind),
329
                json_str(p),
330
                json_str(&f.node.to_hex()),
331
                json_array(changes.iter().map(|h| json_str(&id_of(h))))
332
            ));
333
        }
334
        for c in &base_snapshot.tree.conflicts {
335
            let (kind, nodes): (&str, Vec<NodeId>) = match c {
336
                crate::tree::TreeConflict::Name { nodes, .. } => ("name", nodes.clone()),
337
                crate::tree::TreeConflict::MultiPlacement { node, .. } => {
338
                    ("multi-placement", vec![*node])
339
                }
340
                crate::tree::TreeConflict::Orphan { node, .. } => ("orphan", vec![*node]),
341
                crate::tree::TreeConflict::Cycle { node } => ("cycle", vec![*node]),
342
                crate::tree::TreeConflict::Mode { node, .. } => ("mode", vec![*node]),
343
            };
344
            let detail = match c {
345
                crate::tree::TreeConflict::Name { name, parent, .. } => {
346
                    let dir = if *parent == NodeId::ROOT {
347
                        String::new()
348
                    } else {
349
                        path_of(parent).unwrap_or_default()
350
                    };
351
                    format!(
352
                        ",\"path\":{}",
353
                        json_str(&if dir.is_empty() {
354
                            name.clone()
355
                        } else {
356
                            format!("{dir}/{name}")
357
                        })
358
                    )
359
                }
360
                _ => nodes
361
                    .first()
362
                    .and_then(path_of)
363
                    .map(|p| format!(",\"path\":{}", json_str(&p)))
364
                    .unwrap_or_default(),
365
            };
366
            conflicts.push(format!(
367
                "{{\"kind\":{},\"nodes\":{}{detail}}}",
368
                json_str(kind),
369
                json_array(nodes.iter().map(|n| json_str(&n.to_hex())))
370
            ));
371
        }
372
        Ok(format!(
373
            "{{\"bookmark\":{},\"working_copy\":{},\"heads\":{},\"clean\":{},\"conflicted\":{},\"paths\":{paths},\"conflicts\":{}}}",
374
            json_str(&self.config.bookmark),
375
            json_str(&snap.wc.change_id.to_hex()),
376
            heads.len(),
377
            snap.statuses.is_empty(),
378
            base_snapshot.is_conflicted(),
379
            json_array(conflicts)
380
        ))
381
    }
382
383
    /// Turn the working-copy change into a normal change on the bookmark (spec §12.3).
384
    pub fn commit(&self, message: &str, extra_deps: &[ChangeHash]) -> Result<ChangeHash> {
385
        self.commit_selection(message, extra_deps, &Selection::All)
386
    }
387
388
    /// The hunks of the working copy, for `oxy commit --interactive`: each
389
    /// tree operation and each edit, in the order `select_hunks` numbers them.
390
    pub fn hunks(&self) -> Result<(SnapshotResult, Vec<Hunk>)> {
391
        let snap = self.snapshot("oxy commit")?;
392
        let hunks = render_hunks(&snap.wc, &snap.base, &snap.base_snapshot);
393
        Ok((snap, hunks))
394
    }
395
396
    /// Commit part of the working copy (spec §12.3). What is not selected
397
    /// stays on disk as uncommitted work: the next snapshot rebuilds it
398
    /// against the new base, so the working copy always describes the
399
    /// directory.
400
    pub fn commit_selection(
401
        &self,
402
        message: &str,
403
        extra_deps: &[ChangeHash],
404
        selection: &Selection,
405
    ) -> Result<ChangeHash> {
406
        let snap = self.snapshot("oxy commit")?;
407
        if snap.wc.tree_ops.is_empty() && snap.wc.edits.is_empty() {
408
            return fail("nothing to commit: the working copy matches its base");
409
        }
410
        if let Some(s) = snap
411
            .statuses
412
            .iter()
413
            .find(|s| s.status == ChangeStatus::ConflictEdited)
414
        {
415
            return fail(format!("{} still contains conflict markers", s.path));
416
        }
417
        if message.trim().is_empty() {
418
            return fail("a commit message is required");
419
        }
420
        let (tree_ops, edits, partial) = match selection {
421
            Selection::All => (snap.wc.tree_ops.clone(), snap.wc.edits.clone(), false),
422
            Selection::Paths(paths) => {
423
                let (o, e) = select_paths(&snap.wc, &snap.base_snapshot, paths);
424
                let partial = o.len() != snap.wc.tree_ops.len() || e.len() != snap.wc.edits.len();
425
                (o, e, partial)
426
            }
427
            Selection::Hunks(indices) => {
428
                let (o, e) = select_hunks(&snap.wc, indices);
429
                let partial = o.len() != snap.wc.tree_ops.len() || e.len() != snap.wc.edits.len();
430
                (o, e, partial)
431
            }
432
        };
433
        if tree_ops.is_empty() && edits.is_empty() {
434
            return fail("nothing selected to commit");
435
        }
436
        if partial && snap.resolves {
437
            return fail("a conflict resolution must be committed whole");
438
        }
439
        // pre-commit hook: may veto.
440
        self.run_hook(
441
            "pre-commit",
442
            &format!(
443
                "{{\"event\":\"pre-commit\",\"message\":{},\"paths\":{}}}",
444
                json_str(message),
445
                json_array(snap.statuses.iter().map(|s| format!(
446
                    "{{\"path\":{},\"status\":{}}}",
447
                    json_str(&s.path),
448
                    json_str(&format!("{:?}", s.status))
449
                )))
450
            ),
451
        )?;
452
        let (op_ref, op) = self.head_op()?;
453
        let mut deps: BTreeSet<ChangeHash> = referenced_changes(&snap.wc, &snap.base);
454
        // semantic-deps hook: may add explicit dependencies (spec §8.1).
455
        if self.config.semantic_deps {
456
            let touched: Vec<String> = snap.statuses.iter().map(|s| s.path.clone()).collect();
457
            let by_node = snap.base_snapshot.tree.by_node();
458
            let mut candidates: Vec<(ChangeId, ChangeHash, Vec<String>)> = Vec::new();
459
            let mut seen: BTreeSet<ChangeHash> = BTreeSet::new();
460
            for h in deps.iter().chain(snap.base.maximal(&snap.wc.deps).iter()) {
461
                if !seen.insert(*h) {
462
                    continue;
463
                }
464
                let c = self.store.get_change(h)?;
465
                let mut paths: BTreeSet<String> = BTreeSet::new();
466
                for n in c
467
                    .tree_ops
468
                    .iter()
469
                    .map(|o| o.node())
470
                    .chain(c.edits.iter().map(|e| e.node()))
471
                {
472
                    if let Some(e) = by_node.get(&n) {
473
                        paths.insert(e.path.clone());
474
                    }
475
                }
476
                candidates.push((c.change_id, *h, paths.into_iter().collect()));
477
            }
478
            for d in self.semantic_deps(&snap.wc.change_id, &touched, &candidates)? {
479
                if snap.base.contains(&d) {
480
                    deps.insert(d);
481
                }
482
            }
483
        }
484
        // A resolution depends on every change that contributed to the
485
        // conflict (spec §8.1). Tree and opaque conflicts are resolved through
486
        // ordinary operations whose references already cover the contributors.
487
        deps.extend(snap.contributors.iter().copied());
488
        for d in extra_deps {
489
            if !snap.base.contains(d) {
490
                return fail(format!(
491
                    "--depends-on {d}: not in the working copy's base state"
492
                ));
493
            }
494
            deps.insert(*d);
495
        }
496
        let mut change = Change {
497
            change_id: if partial {
498
                ChangeId::random()
499
            } else {
500
                snap.wc.change_id
501
            },
502
            deps: vec![],
503
            author: self.author(),
504
            hlc: Hlc::now(),
505
            message: message.trim_end().to_string(),
506
            tree_ops,
507
            edits,
508
            kind: if snap.resolves {
509
                ChangeKind::Resolution
510
            } else {
511
                ChangeKind::Normal
512
            },
513
        };
514
        if partial {
515
            // Dependencies come from what the selected part references, not
516
            // from the whole working copy.
517
            deps = referenced_changes(&change, &snap.base);
518
            for d in extra_deps {
519
                deps.insert(*d);
520
            }
521
        }
522
        change.deps = deps.into_iter().collect();
523
        change.normalize();
524
        let hash = self.store_signed(&change)?;
525
526
        // New bookmark heads: maximal elements of old heads plus the new change.
527
        // The working copy continues on its own base plus the new change, which
528
        // is exactly what the files on disk contain; the bookmark may hold
529
        // other heads (and conflicts) the working copy has not checked out.
530
        let old_heads = self.heads_of(&op.view, &self.config.bookmark)?;
531
        let old_base = snap.base.maximal(&snap.wc.deps);
532
        let mut all: Vec<ChangeHash> = old_heads.clone();
533
        all.extend(old_base.iter().copied());
534
        all.push(hash);
535
        // The snapshot already loaded the working copy's base; when that also
536
        // holds every bookmark head, it is the state to extend.
537
        let mut st = if old_heads.iter().all(|h| snap.base.contains(h)) {
538
            snap.base
539
        } else {
540
            self.load_state(&all)?
541
        };
542
        st.add(change)?;
543
        let mut with_new = old_heads.clone();
544
        with_new.push(hash);
545
        let new_heads = st.maximal(&with_new);
546
        // Automatic checkpoint once enough changes accumulated (spec §11).
547
        let since = self
548
            .latest_checkpoint(&self.config.bookmark)?
549
            .map(|(_, cp)| cp.count)
550
            .unwrap_or(0);
551
        if self.config.checkpoint_interval > 0
552
            && (st.len() as u64).saturating_sub(since) >= self.config.checkpoint_interval
553
        {
554
            let cp_state = self.load_state_full(&new_heads)?;
555
            self.write_checkpoint(&self.config.bookmark, &cp_state, &new_heads)?;
556
        }
557
        let mut wc_base = old_base.clone();
558
        wc_base.push(hash);
559
        let wc_base = st.maximal(&wc_base);
560
561
        let wc = self.new_working_copy(wc_base, "");
562
        let wc_hash = self.store.put_change(&wc)?;
563
        let mut view = op.view.clone();
564
        view.bookmarks.insert(
565
            self.config.bookmark.clone(),
566
            self.store.put_state(&StateObject::new(new_heads))?,
567
        );
568
        view.workspaces.insert(self.workspace, wc_hash);
569
        self.record_op(&[op_ref], &format!("oxy commit -m {message:?}"), view)?;
570
        if partial {
571
            // The rest is rebuilt from disk by the next snapshot.
572
            self.drop_manifest();
573
        } else {
574
            self.rewrite_manifest_flags(
575
                snap.base_snapshot.is_conflicted() && !snap.resolves,
576
                false,
577
            )?;
578
        }
579
        self.maybe_autopack()?;
580
        let _ = self.run_hook(
581
            "post-commit",
582
            &format!(
583
                "{{\"event\":\"post-commit\",\"change_id\":{},\"hash\":{},\"message\":{}}}",
584
                json_str(&snap.wc.change_id.to_hex()),
585
                json_str(&hash.to_hex()),
586
                json_str(message)
587
            ),
588
        );
589
        Ok(hash)
590
    }
591
}
592
593
/// What part of the working copy a commit takes (spec §12.3).
594
#[derive(Clone, Debug)]
595
pub enum Selection {
596
    All,
597
    /// Every operation and edit on nodes under these paths.
598
    Paths(Vec<String>),
599
    /// Hunk indices as `Repo::hunks` numbers them; dependent hunks are added.
600
    Hunks(Vec<usize>),
601
}
602
603
/// One selectable piece of the working copy: a tree operation or an edit.
604
#[derive(Clone, Debug)]
605
pub struct Hunk {
606
    pub index: usize,
607
    pub path: String,
608
    /// Rendered like `oxy diff`.
609
    pub text: String,
610
}
611
612
/// The tree operations and edits on nodes under `paths`, plus the
613
/// additions of any new parent directories they need.
614
fn select_paths(
615
    wc: &Change,
616
    base_snapshot: &Snapshot,
617
    paths: &[String],
618
) -> (Vec<TreeOp>, Vec<Edit>) {
619
    let selected = |p: &str| {
620
        paths
621
            .iter()
622
            .any(|x| p == x || p.starts_with(&format!("{}/", x.trim_end_matches('/'))))
623
    };
624
    let by_node = base_snapshot.tree.by_node();
625
    let mut new_names: HashMap<NodeId, (NodeId, String, NodeKind)> = HashMap::new();
626
    for op in &wc.tree_ops {
627
        if let TreeOp::AddNode {
628
            node,
629
            parent,
630
            name,
631
            kind,
632
            ..
633
        } = op
634
        {
635
            new_names.insert(*node, (*parent, name.clone(), *kind));
636
        }
637
    }
638
    let mut nodes: BTreeSet<NodeId> = BTreeSet::new();
639
    for n in wc
640
        .tree_ops
641
        .iter()
642
        .map(|o| o.node())
643
        .chain(wc.edits.iter().map(|e| e.node()))
644
    {
645
        if path_of_node(&n, &by_node, &new_names).is_some_and(|p| selected(&p)) {
646
            nodes.insert(n);
647
        }
648
    }
649
    // New parents of selected new nodes come along.
650
    let mut changed = true;
651
    while changed {
652
        changed = false;
653
        for (n, (parent, _, _)) in &new_names {
654
            if nodes.contains(n) && new_names.contains_key(parent) && nodes.insert(*parent) {
655
                changed = true;
656
            }
657
        }
658
    }
659
    let ops = wc
660
        .tree_ops
661
        .iter()
662
        .filter(|o| nodes.contains(&o.node()))
663
        .cloned()
664
        .collect();
665
    let edits = wc
666
        .edits
667
        .iter()
668
        .filter(|e| nodes.contains(&e.node()))
669
        .cloned()
670
        .collect();
671
    (ops, edits)
672
}
673
674
/// The hunks `indices` name plus whatever they refer to within the working
675
/// copy (the parent directory of an added node, the insert that introduced
676
/// an anchor line), renumbered so the result is a well-formed change.
677
fn select_hunks(wc: &Change, indices: &[usize]) -> (Vec<TreeOp>, Vec<Edit>) {
678
    let n_ops = wc.tree_ops.len();
679
    let mut ops_sel = vec![false; n_ops];
680
    let mut edits_sel = vec![false; wc.edits.len()];
681
    for &i in indices {
682
        if i < n_ops {
683
            ops_sel[i] = true;
684
        } else if i - n_ops < wc.edits.len() {
685
            edits_sel[i - n_ops] = true;
686
        }
687
    }
688
    // Atom ranges each insert introduces, per node, in the working copy's numbering.
689
    let mut per_node: HashMap<NodeId, u32> = HashMap::new();
690
    let mut insert_ranges: Vec<Option<(NodeId, u32, u32)>> = Vec::new();
691
    for e in &wc.edits {
692
        insert_ranges.push(match e {
693
            Edit::Insert { node, lines, .. } => {
694
                let start = per_node.entry(*node).or_default();
695
                let r = (*node, *start, *start + lines.len() as u32);
696
                *start += lines.len() as u32;
697
                Some(r)
698
            }
699
            _ => None,
700
        });
701
    }
702
    let add_index: HashMap<NodeId, usize> = wc
703
        .tree_ops
704
        .iter()
705
        .enumerate()
706
        .filter_map(|(i, o)| {
707
            if let TreeOp::AddNode { node, .. } = o {
708
                Some((*node, i))
709
            } else {
710
                None
711
            }
712
        })
713
        .collect();
714
    let insert_for = |node: &NodeId, index: u32| -> Option<usize> {
715
        insert_ranges
716
            .iter()
717
            .position(|r| matches!(r, Some((n, a, b)) if n == node && *a <= index && index < *b))
718
    };
719
    // Closure.
720
    let mut changed = true;
721
    while changed {
722
        changed = false;
723
        for i in 0..n_ops {
724
            if !ops_sel[i] {
725
                continue;
726
            }
727
            if let TreeOp::AddNode { node, parent, .. } = &wc.tree_ops[i] {
728
                if let Some(&p) = add_index.get(parent) {
729
                    if !ops_sel[p] {
730
                        ops_sel[p] = true;
731
                        changed = true;
732
                    }
733
                }
734
                // A new node's content belongs with its addition: nobody
735
                // wants an empty file committed apart from its lines.
736
                for (j, e) in wc.edits.iter().enumerate() {
737
                    if e.node() == *node && !edits_sel[j] {
738
                        edits_sel[j] = true;
739
                        changed = true;
740
                    }
741
                }
742
            }
743
        }
744
        for j in 0..wc.edits.len() {
745
            if !edits_sel[j] {
746
                continue;
747
            }
748
            let e = &wc.edits[j];
749
            if let Some(&a) = add_index.get(&e.node()) {
750
                if !ops_sel[a] {
751
                    ops_sel[a] = true;
752
                    changed = true;
753
                }
754
            }
755
            if let Edit::Insert {
756
                node,
757
                after,
758
                before,
759
                ..
760
            } = e
761
            {
762
                for r in [after, before] {
763
                    if let AtomRef::Atom { change, index } = r {
764
                        if change.is_zero() {
765
                            if let Some(k) = insert_for(node, *index) {
766
                                if !edits_sel[k] {
767
                                    edits_sel[k] = true;
768
                                    changed = true;
769
                                }
770
                            }
771
                        }
772
                    }
773
                }
774
            }
775
        }
776
    }
777
    // Renumber self-references: old atom index → new index among selected inserts.
778
    let mut remap: HashMap<(NodeId, u32), u32> = HashMap::new();
779
    let mut new_counts: HashMap<NodeId, u32> = HashMap::new();
780
    for (j, r) in insert_ranges.iter().enumerate() {
781
        if let (true, Some((node, a, b))) = (edits_sel[j], r) {
782
            let next = new_counts.entry(*node).or_default();
783
            for old in *a..*b {
784
                remap.insert((*node, old), *next);
785
                *next += 1;
786
            }
787
        }
788
    }
789
    let map_ref = |r: AtomRef, node: &NodeId| -> AtomRef {
790
        match r {
791
            AtomRef::Atom { change, index } if change.is_zero() => AtomRef::Atom {
792
                change,
793
                index: remap.get(&(*node, index)).copied().unwrap_or(index),
794
            },
795
            other => other,
796
        }
797
    };
798
    let ops = wc
799
        .tree_ops
800
        .iter()
801
        .enumerate()
802
        .filter(|(i, _)| ops_sel[*i])
803
        .map(|(_, o)| o.clone())
804
        .collect();
805
    let edits = wc
806
        .edits
807
        .iter()
808
        .enumerate()
809
        .filter(|(j, _)| edits_sel[*j])
810
        .map(|(_, e)| match e {
811
            Edit::Insert {
812
                node,
813
                after,
814
                before,
815
                lines,
816
            } => Edit::Insert {
817
                node: *node,
818
                after: map_ref(*after, node),
819
                before: map_ref(*before, node),
820
                lines: lines.clone(),
821
            },
822
            other => other.clone(),
823
        })
824
        .collect();
825
    (ops, edits)
826
}
827
828
/// Render each tree operation and edit of `change` on its own, numbered.
829
pub fn render_hunks(change: &Change, base: &State, base_snapshot: &Snapshot) -> Vec<Hunk> {
830
    let by_node = base_snapshot.tree.by_node();
831
    let mut new_names: HashMap<NodeId, (NodeId, String, NodeKind)> = HashMap::new();
832
    for op in &change.tree_ops {
833
        if let TreeOp::AddNode {
834
            node,
835
            parent,
836
            name,
837
            kind,
838
            ..
839
        } = op
840
        {
841
            new_names.insert(*node, (*parent, name.clone(), *kind));
842
        }
843
    }
844
    let mut out = Vec::new();
845
    for (i, op) in change.tree_ops.iter().enumerate() {
846
        let one = Change {
847
            tree_ops: vec![op.clone()],
848
            edits: vec![],
849
            ..change.clone()
850
        };
851
        let path = path_of_node(&op.node(), &by_node, &new_names).unwrap_or_default();
852
        out.push(Hunk {
853
            index: i,
854
            path,
855
            text: render_change(&one, base, base_snapshot),
856
        });
857
    }
858
    for (j, e) in change.edits.iter().enumerate() {
859
        let one = Change {
860
            tree_ops: vec![],
861
            edits: vec![e.clone()],
862
            ..change.clone()
863
        };
864
        let path = path_of_node(&e.node(), &by_node, &new_names).unwrap_or_default();
865
        out.push(Hunk {
866
            index: change.tree_ops.len() + j,
867
            path,
868
            text: render_change(&one, base, base_snapshot),
869
        });
870
    }
871
    out
872
}
873
874
/// One file's part of a diff, for `oxy diff --json`.
875
#[derive(Clone, Debug)]
876
pub struct FileDiff {
877
    pub path: String,
878
    /// `added`, `removed`, `modified`, `renamed`, `mode`, `replaced`.
879
    pub kind: String,
880
    pub hunks: Vec<DiffHunk>,
881
    /// For renames, the previous path.
882
    pub from: Option<String>,
883
}
884
885
/// Lines inserted after `base_line` (0 = before the first line) and lines
886
/// removed, with their base line numbers.
887
#[derive(Clone, Debug, Default)]
888
pub struct DiffHunk {
889
    pub base_line: u32,
890
    pub added: Vec<Vec<u8>>,
891
    pub removed: Vec<(u32, Vec<u8>)>,
892
}
893
894
impl Repo {
895
    /// The content of `path` in a state: `heads`, or the working copy's base.
896
    pub fn file_at(&self, path: &str, heads: Option<&[ChangeHash]>) -> Result<Vec<u8>> {
897
        let snapshot = match heads {
898
            Some(h) => self.load_state(h)?.materialize(),
899
            None => {
900
                let (_, wc) = self.working_copy()?;
901
                self.load_state(&wc.deps)?.materialize()
902
            }
903
        };
904
        let Some(f) = snapshot.files.get(path) else {
905
            return fail(format!("{path} is not in that state"));
906
        };
907
        match &f.content {
908
            FileContent::Dir => fail(format!("{path} is a directory")),
909
            FileContent::Text { bytes, .. } => Ok(bytes.clone()),
910
            FileContent::Opaque { blobs } => match blobs.first() {
911
                Some(b) => self.read_blob(b),
912
                None => Ok(vec![]),
913
            },
914
        }
915
    }
916
917
    /// Restore `paths` (files or directories) to the working copy's base:
918
    /// edits are undone, additions removed, removals put back. Returns the
919
    /// number of paths touched.
920
    pub fn discard(&self, paths: &[String]) -> Result<usize> {
921
        let snap = self.snapshot("oxy discard")?;
922
        let under = |p: &str| {
923
            paths
924
                .iter()
925
                .any(|x| p == x || p.starts_with(&format!("{}/", x.trim_end_matches('/'))))
926
        };
927
        let attrs = Repo::state_attributes(&snap.base_snapshot);
928
        let mut n = 0;
929
        for s in &snap.statuses {
930
            if !under(&s.path) {
931
                continue;
932
            }
933
            match snap.base_snapshot.files.get(&s.path) {
934
                None => {
935
                    // Added (or the new name of a rename): remove it.
936
                    let full = self.root.join(&s.path);
937
                    if full.is_dir() {
938
                        let _ = fs::remove_dir_all(&full);
939
                    } else {
940
                        let _ = fs::remove_file(&full);
941
                    }
942
                    n += 1;
943
                }
944
                Some(f) => {
945
                    match &f.content {
946
                        FileContent::Dir => fs::create_dir_all(self.root.join(&s.path))?,
947
                        FileContent::Text { bytes, .. } => {
948
                            let on_disk: std::borrow::Cow<[u8]> = if attrs.lookup(&s.path).eol
949
                                == Some(crate::attributes::Eol::Crlf)
950
                            {
951
                                crate::attributes::to_crlf(bytes).into()
952
                            } else {
953
                                bytes.as_slice().into()
954
                            };
955
                            self.write_file(&s.path, &on_disk, f.mode.exec)?;
956
                        }
957
                        FileContent::Opaque { blobs } => {
958
                            let bytes = match blobs.first() {
959
                                Some(b) => self.read_blob(b)?,
960
                                None => vec![],
961
                            };
962
                            if f.kind == NodeKind::Symlink {
963
                                self.write_symlink(&s.path, &bytes)?;
964
                            } else if f.kind == NodeKind::File {
965
                                self.write_file(&s.path, &bytes, f.mode.exec)?;
966
                            }
967
                        }
968
                    }
969
                    n += 1;
970
                }
971
            }
972
        }
973
        // A rename's old name is not in the statuses; put it back too.
974
        for (p, f) in &snap.base_snapshot.files {
975
            if under(p)
976
                && !self.root.join(p).exists()
977
                && f.kind != NodeKind::Dir
978
                && f.kind != NodeKind::Subrepo
979
                && !snap.statuses.iter().any(|s| s.path == *p)
980
            {
981
                let bytes = match &f.content {
982
                    FileContent::Text { bytes, .. } => bytes.clone(),
983
                    FileContent::Opaque { blobs } => blobs
984
                        .first()
985
                        .map(|b| self.read_blob(b))
986
                        .transpose()?
987
                        .unwrap_or_default(),
988
                    FileContent::Dir => continue,
989
                };
990
                if f.kind == NodeKind::Symlink {
991
                    self.write_symlink(p, &bytes)?
992
                } else {
993
                    self.write_file(p, &bytes, f.mode.exec)?
994
                }
995
                n += 1;
996
            }
997
        }
998
        self.drop_manifest();
999
        Ok(n)
1000
    }
1001
1002
    /// Undo the working-copy hunks `indices` (as `hunks` numbers them) on
1003
    /// disk, keeping the others: the files are rewritten from the base plus
1004
    /// the remaining hunks.
1005
    pub fn discard_hunks(&self, indices: &[usize]) -> Result<usize> {
1006
        let (snap, hunks) = self.hunks()?;
1007
        let keep: Vec<usize> = hunks
1008
            .iter()
1009
            .map(|h| h.index)
1010
            .filter(|i| !indices.contains(i))
1011
            .collect();
1012
        let (ops, edits) = select_hunks(&snap.wc, &keep);
1013
        let dropped_nodes: BTreeSet<NodeId> = hunks
1014
            .iter()
1015
            .filter(|h| indices.contains(&h.index))
1016
            .map(|h| {
1017
                if h.index < snap.wc.tree_ops.len() {
1018
                    snap.wc.tree_ops[h.index].node()
1019
                } else {
1020
                    snap.wc.edits[h.index - snap.wc.tree_ops.len()].node()
1021
                }
1022
            })
1023
            .collect();
1024
        let mut partial = snap.wc.clone();
1025
        partial.tree_ops = ops;
1026
        partial.edits = edits;
1027
        partial.normalize();
1028
        let mut st = snap.base.clone();
1029
        st.add_unchecked(partial);
1030
        let target = st.materialize();
1031
        let by_node_target = target.tree.by_node();
1032
        let by_node_base = snap.base_snapshot.tree.by_node();
1033
        let attrs = Repo::state_attributes(&target);
1034
        let mut n = 0;
1035
        for node in dropped_nodes {
1036
            match by_node_target.get(&node) {
1037
                Some(e) => {
1038
                    let f = &target.files[&e.path];
1039
                    match &f.content {
1040
                        FileContent::Dir => {}
1041
                        FileContent::Text { bytes, .. } => {
1042
                            let on_disk: std::borrow::Cow<[u8]> = if attrs.lookup(&e.path).eol
1043
                                == Some(crate::attributes::Eol::Crlf)
1044
                            {
1045
                                crate::attributes::to_crlf(bytes).into()
1046
                            } else {
1047
                                bytes.as_slice().into()
1048
                            };
1049
                            self.write_file(&e.path, &on_disk, f.mode.exec)?;
1050
                        }
1051
                        FileContent::Opaque { blobs } => {
1052
                            let bytes = blobs
1053
                                .first()
1054
                                .map(|b| self.read_blob(b))
1055
                                .transpose()?
1056
                                .unwrap_or_default();
1057
                            if f.kind == NodeKind::Symlink {
1058
                                self.write_symlink(&e.path, &bytes)?
1059
                            } else {
1060
                                self.write_file(&e.path, &bytes, f.mode.exec)?
1061
                            }
1062
                        }
1063
                    }
1064
                    // A discarded rename: the new name goes.
1065
                    if let Some(old_path) = snap
1066
                        .statuses
1067
                        .iter()
1068
                        .find(|s| {
1069
                            s.status == ChangeStatus::Renamed && !target.files.contains_key(&s.path)
1070
                        })
1071
                        .map(|s| s.path.clone())
1072
                    {
1073
                        let _ = fs::remove_file(self.root.join(old_path));
1074
                    }
1075
                    n += 1;
1076
                }
1077
                None => {
1078
                    // The node exists in neither target nor base with a live path: an addition to remove.
1079
                    if let Some(added) = snap.statuses.iter().find(|s| {
1080
                        s.status == ChangeStatus::Added
1081
                            && !target.files.contains_key(&s.path)
1082
                            && !by_node_base.contains_key(&node)
1083
                    }) {
1084
                        let full = self.root.join(&added.path);
1085
                        if full.is_dir() {
1086
                            let _ = fs::remove_dir_all(&full);
1087
                        } else {
1088
                            let _ = fs::remove_file(&full);
1089
                        }
1090
                        n += 1;
1091
                    }
1092
                }
1093
            }
1094
        }
1095
        self.drop_manifest();
1096
        Ok(n)
1097
    }
1098
1099
    /// The diff of the working copy (`None`) or of a change, per file with
1100
    /// line-numbered hunks (spec: `oxy diff --json`).
1101
    pub fn diff_files(&self, change: Option<&ChangeHash>) -> Result<Vec<FileDiff>> {
1102
        let (c, base) = match change {
1103
            Some(h) => {
1104
                let c = self.store.get_change(h)?;
1105
                let base = self.load_state(&c.deps)?;
1106
                (c, base)
1107
            }
1108
            None => {
1109
                let snap = self.snapshot("oxy diff")?;
1110
                (snap.wc, snap.base)
1111
            }
1112
        };
1113
        let base_snapshot = base.materialize();
1114
        Ok(diff_files_of(&c, &base, &base_snapshot))
1115
    }
1116
1117
    /// The log restricted to changes touching `path` (its node, so renames
1118
    /// are followed), on the current bookmark.
1119
    pub fn log_for_path(&self, path: &str) -> Result<Vec<LogEntry>> {
1120
        let heads = self.bookmark_heads()?;
1121
        if self.is_bare() {
1122
            return self.log_for_path_in(path, &heads);
1123
        }
1124
        let entries = self.log()?;
1125
        let (_, wc) = self.working_copy()?;
1126
        let base_snapshot = self.load_state(&wc.deps)?.materialize();
1127
        let state_snapshot = self.load_state(&heads)?.materialize();
1128
        let node = base_snapshot
1129
            .files
1130
            .get(path)
1131
            .or_else(|| state_snapshot.files.get(path))
1132
            .map(|f| f.node);
1133
        let Some(node) = node else {
1134
            return fail(format!("{path} is not tracked"));
1135
        };
1136
        Ok(self.entries_touching(entries, node))
1137
    }
1138
1139
    /// The log of the state with these heads restricted to changes touching
1140
    /// `path` (its node, so renames are followed).
1141
    pub fn log_for_path_in(&self, path: &str, heads: &[ChangeHash]) -> Result<Vec<LogEntry>> {
1142
        self.log_for_path_of(&self.load_state_history(heads)?, path, None)
1143
    }
1144
1145
    /// The changes of a loaded state touching `path`, newest first, at most
1146
    /// `limit` of them. The path is found in the state's tree alone, so no
1147
    /// file is rendered, and the walk stops once `limit` are found.
1148
    pub fn log_for_path_of(
1149
        &self,
1150
        state: &State,
1151
        path: &str,
1152
        limit: Option<usize>,
1153
    ) -> Result<Vec<LogEntry>> {
1154
        let Some(node) = state.tree().view().entries.get(path).map(|e| e.node) else {
1155
            return fail(format!("{path} is not in that state"));
1156
        };
1157
        Ok(self.entries_touching_up_to(self.log_of(state), node, limit))
1158
    }
1159
1160
    fn entries_touching(&self, entries: Vec<LogEntry>, node: NodeId) -> Vec<LogEntry> {
1161
        self.entries_touching_up_to(entries, node, None)
1162
    }
1163
1164
    fn entries_touching_up_to(
1165
        &self,
1166
        entries: Vec<LogEntry>,
1167
        node: NodeId,
1168
        limit: Option<usize>,
1169
    ) -> Vec<LogEntry> {
1170
        let mut out = Vec::new();
1171
        for e in entries {
1172
            if limit.is_some_and(|n| out.len() >= n) {
1173
                break;
1174
            }
1175
            let Ok(c) = self.store.get_change(&e.hash) else {
1176
                continue;
1177
            };
1178
            if c.tree_ops.iter().any(|o| o.node() == node)
1179
                || c.edits.iter().any(|x| x.node() == node)
1180
            {
1181
                out.push(e);
1182
            }
1183
        }
1184
        out
1185
    }
1186
}
1187
1188
/// Per-file hunks of `change` against `base`.
1189
pub fn diff_files_of(change: &Change, base: &State, base_snapshot: &Snapshot) -> Vec<FileDiff> {
1190
    let by_node = base_snapshot.tree.by_node();
1191
    let mut new_names: HashMap<NodeId, (NodeId, String, NodeKind)> = HashMap::new();
1192
    for op in &change.tree_ops {
1193
        if let TreeOp::AddNode {
1194
            node,
1195
            parent,
1196
            name,
1197
            kind,
1198
            ..
1199
        } = op
1200
        {
1201
            new_names.insert(*node, (*parent, name.clone(), *kind));
1202
        }
1203
    }
1204
    let path_of = |n: &NodeId| -> String {
1205
        path_of_node(n, &by_node, &new_names).unwrap_or_else(|| format!("<node {}>", n.short(8)))
1206
    };
1207
    let mut files: BTreeMap<NodeId, FileDiff> = BTreeMap::new();
1208
    let mut order: Vec<NodeId> = Vec::new();
1209
    let mut entry = |files: &mut BTreeMap<NodeId, FileDiff>, n: NodeId, kind: &str| {
1210
        if let std::collections::btree_map::Entry::Vacant(v) = files.entry(n) {
1211
            order.push(n);
1212
            v.insert(FileDiff {
1213
                path: path_of(&n),
1214
                kind: kind.to_string(),
1215
                hunks: vec![],
1216
                from: None,
1217
            });
1218
        }
1219
    };
1220
    for op in &change.tree_ops {
1221
        match op {
1222
            TreeOp::AddNode { node, kind, .. } => {
1223
                if *kind != NodeKind::Dir {
1224
                    entry(&mut files, *node, "added");
1225
                }
1226
            }
1227
            TreeOp::RemoveNode { node, .. } => {
1228
                entry(&mut files, *node, "removed");
1229
                if let Some(e) = by_node.get(node) {
1230
                    files.get_mut(node).unwrap().path = e.path.clone();
1231
                }
1232
            }
1233
            TreeOp::Move {
1234
                node, parent, name, ..
1235
            } => {
1236
                entry(&mut files, *node, "renamed");
1237
                let f = files.get_mut(node).unwrap();
1238
                f.from = by_node.get(node).map(|e| e.path.clone());
1239
                let dir = if parent.is_root() {
1240
                    String::new()
1241
                } else {
1242
                    path_of_node(parent, &by_node, &new_names).unwrap_or_default()
1243
                };
1244
                f.path = if dir.is_empty() {
1245
                    name.clone()
1246
                } else {
1247
                    format!("{dir}/{name}")
1248
                };
1249
            }
1250
            TreeOp::SetMode { node, .. } => entry(&mut files, *node, "mode"),
1251
        }
1252
    }
1253
    // Base line numbers per node, 1-based.
1254
    let mut line_of: HashMap<NodeId, HashMap<(ChangeHash, u32), u32>> = HashMap::new();
1255
    let mut lines_for = |n: &NodeId| -> HashMap<(ChangeHash, u32), u32> {
1256
        line_of
1257
            .entry(*n)
1258
            .or_insert_with(|| {
1259
                base.live_lines(n)
1260
                    .into_iter()
1261
                    .enumerate()
1262
                    .map(|(i, (k, _))| (k, i as u32 + 1))
1263
                    .collect()
1264
            })
1265
            .clone()
1266
    };
1267
    for e in &change.edits {
1268
        let n = e.node();
1269
        let is_new = new_names.contains_key(&n);
1270
        entry(&mut files, n, if is_new { "added" } else { "modified" });
1271
        let f = files.get_mut(&n).unwrap();
1272
        match e {
1273
            Edit::Insert { after, lines, .. } => {
1274
                let map = lines_for(&n);
1275
                let base_line = match after {
1276
                    AtomRef::Start => 0,
1277
                    AtomRef::End => map.len() as u32,
1278
                    AtomRef::Atom { change, index } if change.is_zero() => {
1279
                        f.hunks.last().map(|h| h.base_line).unwrap_or(0)
1280
                    }
1281
                    AtomRef::Atom { change, index } => {
1282
                        map.get(&(*change, *index)).copied().unwrap_or(0)
1283
                    }
1284
                };
1285
                f.hunks.push(DiffHunk {
1286
                    base_line,
1287
                    added: lines.clone(),
1288
                    removed: vec![],
1289
                });
1290
            }
1291
            Edit::Delete { atoms, .. } => {
1292
                let map = lines_for(&n);
1293
                let mut removed = Vec::new();
1294
                for r in atoms {
1295
                    for i in r.from..r.to {
1296
                        let line = map.get(&(r.change, i)).copied().unwrap_or(0);
1297
                        let text = base
1298
                            .file(&n)
1299
                            .and_then(|g| g.content(&(r.change, i)))
1300
                            .unwrap_or(b"")
1301
                            .to_vec();
1302
                        removed.push((line, text));
1303
                    }
1304
                }
1305
                let base_line = removed
1306
                    .first()
1307
                    .map(|(l, _)| l.saturating_sub(1))
1308
                    .unwrap_or(0);
1309
                f.hunks.push(DiffHunk {
1310
                    base_line,
1311
                    added: vec![],
1312
                    removed,
1313
                });
1314
            }
1315
            Edit::Replace { .. } => {
1316
                if !is_new {
1317
                    f.kind = "replaced".into();
1318
                }
1319
            }
1320
        }
1321
    }
1322
    order.into_iter().filter_map(|n| files.remove(&n)).collect()
1323
}
1324
1325
/// Builds the tree ops and edits of a working-copy change against a base.
1326
struct ChangeBuilder<'a> {
1327
    base: &'a State,
1328
    base_snapshot: &'a Snapshot,
1329
    tree_ops: Vec<TreeOp>,
1330
    edits: Vec<Edit>,
1331
    statuses: Vec<PathStatus>,
1332
    dir_nodes: HashMap<String, NodeId>,
1333
    reuse: HashMap<String, (NodeId, NodeKind)>,
1334
    /// Changes that contributed to conflicts this working copy resolves.
1335
    contributors: BTreeSet<ChangeHash>,
1336
    resolves: bool,
1337
    attrs: crate::attributes::Attributes,
1338
    blobs: HashMap<String, ObjectRef>,
1339
}
1340
1341
impl<'a> ChangeBuilder<'a> {
1342
    fn new(
1343
        base: &'a State,
1344
        base_snapshot: &'a Snapshot,
1345
        reuse: HashMap<String, (NodeId, NodeKind)>,
1346
    ) -> Self {
1347
        let mut dir_nodes: HashMap<String, NodeId> = HashMap::new();
1348
        dir_nodes.insert(String::new(), NodeId::ROOT);
1349
        for (p, f) in &base_snapshot.files {
1350
            if f.kind == NodeKind::Dir {
1351
                dir_nodes.insert(p.clone(), f.node);
1352
            }
1353
        }
1354
        ChangeBuilder {
1355
            base,
1356
            base_snapshot,
1357
            tree_ops: vec![],
1358
            edits: vec![],
1359
            statuses: vec![],
1360
            dir_nodes,
1361
            reuse,
1362
            contributors: BTreeSet::new(),
1363
            resolves: false,
1364
            attrs: crate::attributes::Attributes::default(),
1365
            blobs: HashMap::new(),
1366
        }
1367
    }
1368
1369
    fn with_attributes(mut self, attrs: crate::attributes::Attributes) -> Self {
1370
        self.attrs = attrs;
1371
        self
1372
    }
1373
1374
    /// Whether a file is opaque: forced by `binary`, forced text by `text`
1375
    /// only when it has no NUL bytes, else sniffed.
1376
    /// The blob for an opaque entry: the cached one, else stored now.
1377
    fn blob_of(
1378
        &mut self,
1379
        repo: &Repo,
1380
        path: &str,
1381
        e: &FsEntry,
1382
        nocompress: bool,
1383
    ) -> Result<ObjectRef> {
1384
        let b = match e.blob {
1385
            Some(b) => b,
1386
            None => repo.store_blob_for(&e.content, nocompress)?,
1387
        };
1388
        self.blobs.insert(path.to_string(), b);
1389
        Ok(b)
1390
    }
1391
1392
    fn opaque_for(&self, path: &str, e: &FsEntry) -> bool {
1393
        if e.blob.is_some() {
1394
            return true;
1395
        }
1396
        if e.kind == NodeKind::Symlink || e.kind == NodeKind::Subrepo {
1397
            return true;
1398
        }
1399
        match self.attrs.lookup(path).binary {
1400
            Some(true) => true,
1401
            Some(false) => is_binary(&e.content),
1402
            None => is_binary(&e.content),
1403
        }
1404
    }
1405
1406
    /// Text content as stored: `\r\n` normalized for `eol=` files.
1407
    fn stored_text(&self, path: &str, content: &[u8]) -> Vec<u8> {
1408
        if self.attrs.lookup(path).eol.is_some() {
1409
            crate::attributes::normalize_eol(content)
1410
        } else {
1411
            content.to_vec()
1412
        }
1413
    }
1414
1415
    fn reused_node(&self, path: &str, kind: NodeKind) -> Option<NodeId> {
1416
        self.reuse
1417
            .get(path)
1418
            .filter(|(_, k)| *k == kind)
1419
            .map(|(n, _)| *n)
1420
    }
1421
1422
    fn ensure_dir(&mut self, path: &str) -> NodeId {
1423
        if let Some(n) = self.dir_nodes.get(path) {
1424
            return *n;
1425
        }
1426
        let mut parent = NodeId::ROOT;
1427
        let mut prefix = String::new();
1428
        for comp in path.split('/') {
1429
            if !prefix.is_empty() {
1430
                prefix.push('/');
1431
            }
1432
            prefix.push_str(comp);
1433
            parent = match self.dir_nodes.get(&prefix) {
1434
                Some(n) => *n,
1435
                None => {
1436
                    let node = self
1437
                        .reused_node(&prefix, NodeKind::Dir)
1438
                        .unwrap_or_else(NodeId::random);
1439
                    self.tree_ops.push(TreeOp::AddNode {
1440
                        node,
1441
                        kind: NodeKind::Dir,
1442
                        mode: Mode::default(),
1443
                        parent,
1444
                        name: comp.to_string(),
1445
                    });
1446
                    self.dir_nodes.insert(prefix.clone(), node);
1447
                    node
1448
                }
1449
            };
1450
        }
1451
        parent
1452
    }
1453
1454
    fn add_path(&mut self, repo: &Repo, path: &str, e: &FsEntry) -> Result<()> {
1455
        let (dir, name) = split_path(path);
1456
        let parent = self.ensure_dir(dir);
1457
        let node = self
1458
            .reused_node(path, e.kind)
1459
            .unwrap_or_else(NodeId::random);
1460
        let opaque = self.opaque_for(path, e);
1461
        let nocompress = self.attrs.lookup(path).nocompress;
1462
        self.tree_ops.push(TreeOp::AddNode {
1463
            node,
1464
            kind: e.kind,
1465
            mode: Mode {
1466
                exec: e.exec,
1467
                opaque,
1468
            },
1469
            parent,
1470
            name: name.to_string(),
1471
        });
1472
        if opaque {
1473
            let blob = self.blob_of(repo, path, e, nocompress)?;
1474
            self.edits.push(Edit::Replace {
1475
                node,
1476
                old: None,
1477
                new: Some(blob),
1478
            });
1479
        } else if !e.content.is_empty() {
1480
            let content = self.stored_text(path, &e.content);
1481
            self.edits.push(Edit::Insert {
1482
                node,
1483
                after: crate::objects::AtomRef::Start,
1484
                before: crate::objects::AtomRef::End,
1485
                lines: split_lines(&content).iter().map(|l| l.to_vec()).collect(),
1486
            });
1487
        }
1488
        self.statuses.push(PathStatus {
1489
            path: path.to_string(),
1490
            status: ChangeStatus::Added,
1491
        });
1492
        Ok(())
1493
    }
1494
1495
    /// Move the node at `old` to `new` and apply `e`'s content to it.
1496
    fn move_path(
1497
        &mut self,
1498
        repo: &Repo,
1499
        old: &str,
1500
        new: &str,
1501
        e: &FsEntry,
1502
        expected: &crate::state::FileState,
1503
    ) -> Result<()> {
1504
        let entry = &self.base_snapshot.tree.entries[old];
1505
        let (dir, name) = split_path(new);
1506
        let parent = self.ensure_dir(dir);
1507
        self.tree_ops.push(TreeOp::Move {
1508
            node: expected.node,
1509
            old: op_ref(entry.placement),
1510
            parent,
1511
            name: name.to_string(),
1512
        });
1513
        self.update_path(repo, old, e, expected)?;
1514
        // update_path reports under the old path; the rename is what the user sees.
1515
        self.statuses.retain(|s| s.path != old);
1516
        self.statuses.push(PathStatus {
1517
            path: new.to_string(),
1518
            status: ChangeStatus::Renamed,
1519
        });
1520
        Ok(())
1521
    }
1522
1523
    fn remove_path(&mut self, path: &str, expected: &crate::state::FileState) {
1524
        let entry = &self.base_snapshot.tree.entries[path];
1525
        self.tree_ops.push(TreeOp::RemoveNode {
1526
            node: expected.node,
1527
            placement: op_ref(entry.placement),
1528
        });
1529
        if path.contains(".oxy-conflict-") || expected.is_conflicted() {
1530
            self.resolves = true;
1531
        }
1532
        self.statuses.push(PathStatus {
1533
            path: path.to_string(),
1534
            status: ChangeStatus::Removed,
1535
        });
1536
    }
1537
1538
    fn update_path(
1539
        &mut self,
1540
        repo: &Repo,
1541
        path: &str,
1542
        e: &FsEntry,
1543
        expected: &crate::state::FileState,
1544
    ) -> Result<()> {
1545
        if expected.kind != e.kind {
1546
            self.remove_path(path, expected);
1547
            self.statuses.pop();
1548
            self.add_path(repo, path, e)?;
1549
            self.statuses.pop();
1550
            self.statuses.push(PathStatus {
1551
                path: path.to_string(),
1552
                status: ChangeStatus::Modified,
1553
            });
1554
            return Ok(());
1555
        }
1556
        let entry = &self.base_snapshot.tree.entries[path];
1557
        let node = expected.node;
1558
        let mode_atom = entry.mode_atom.map(op_ref);
1559
        let mut status: Option<ChangeStatus> = None;
1560
        let wants_opaque = self.opaque_for(path, e);
1561
        let nocompress = self.attrs.lookup(path).nocompress;
1562
        let disk_text = self.stored_text(path, &e.content);
1563
        match &expected.content {
1564
            FileContent::Dir => {}
1565
            FileContent::Text {
1566
                bytes,
1567
                materialized,
1568
            } => {
1569
                if materialized.is_conflicted() {
1570
                    if bytes == &disk_text {
1571
                        return Ok(());
1572
                    }
1573
                    if has_conflict_markers(&e.content) {
1574
                        self.statuses.push(PathStatus {
1575
                            path: path.to_string(),
1576
                            status: ChangeStatus::ConflictEdited,
1577
                        });
1578
                        return Ok(());
1579
                    }
1580
                    // Resolution (spec §9.6): diff against the unconflicted lines
1581
                    // with each region as a gap, then retire every region atom.
1582
                    // Whatever the author kept from a region is re-inserted as
1583
                    // new atoms, which leaves the graph totally ordered.
1584
                    let regions = self.base.conflict_regions(&node);
1585
                    let mut edits = text_edits(node, &regions.plain, &disk_text);
1586
                    if !regions.region_atoms.is_empty() {
1587
                        edits.insert(
1588
                            0,
1589
                            Edit::Delete {
1590
                                node,
1591
                                atoms: ranges(&regions.region_atoms),
1592
                            },
1593
                        );
1594
                    }
1595
                    self.edits.extend(edits);
1596
                    self.contributors.extend(regions.contributors);
1597
                    self.resolves = true;
1598
                    if e.exec != expected.mode.exec {
1599
                        if let Some(old) = mode_atom {
1600
                            self.tree_ops.push(TreeOp::SetMode {
1601
                                node,
1602
                                old,
1603
                                mode: Mode {
1604
                                    exec: e.exec,
1605
                                    opaque: false,
1606
                                },
1607
                            });
1608
                        }
1609
                    }
1610
                    self.statuses.push(PathStatus {
1611
                        path: path.to_string(),
1612
                        status: ChangeStatus::Resolved,
1613
                    });
1614
                    return Ok(());
1615
                }
1616
                if wants_opaque {
1617
                    // Text → opaque (spec §7.5), by content or by attribute.
1618
                    if let Some(old) = mode_atom {
1619
                        self.tree_ops.push(TreeOp::SetMode {
1620
                            node,
1621
                            old,
1622
                            mode: Mode {
1623
                                exec: e.exec,
1624
                                opaque: true,
1625
                            },
1626
                        });
1627
                    }
1628
                    let live: Vec<_> = repo_live_keys(self.base, &node);
1629
                    if !live.is_empty() {
1630
                        self.edits.push(Edit::Delete {
1631
                            node,
1632
                            atoms: ranges(&live),
1633
                        });
1634
                    }
1635
                    let blob = self.blob_of(repo, path, e, nocompress)?;
1636
                    self.edits.push(Edit::Replace {
1637
                        node,
1638
                        old: None,
1639
                        new: Some(blob),
1640
                    });
1641
                    status = Some(ChangeStatus::Modified);
1642
                } else if bytes != &disk_text {
1643
                    let old = self.base.live_lines(&node);
1644
                    let edits = text_edits(node, &old, &disk_text);
1645
                    if !edits.is_empty() {
1646
                        self.edits.extend(edits);
1647
                        status = Some(ChangeStatus::Modified);
1648
                    }
1649
                }
1650
                let switched_to_opaque = wants_opaque;
1651
                if !switched_to_opaque && e.exec != expected.mode.exec {
1652
                    if let Some(old) = mode_atom {
1653
                        self.tree_ops.push(TreeOp::SetMode {
1654
                            node,
1655
                            old,
1656
                            mode: Mode {
1657
                                exec: e.exec,
1658
                                opaque: false,
1659
                            },
1660
                        });
1661
                        status.get_or_insert(ChangeStatus::ModeChanged);
1662
                    }
1663
                }
1664
            }
1665
            FileContent::Opaque { blobs } => {
1666
                let new_ref = e.blob.unwrap_or_else(|| Repo::blob_ref(&e.content));
1667
                if e.kind == NodeKind::File && wants_opaque {
1668
                    // Unchanged or replaced, the file stays opaque: remember its blob.
1669
                    self.blobs.insert(path.to_string(), new_ref);
1670
                }
1671
                if blobs.len() > 1 {
1672
                    if !blobs.contains(&new_ref) {
1673
                        self.statuses.push(PathStatus {
1674
                            path: path.to_string(),
1675
                            status: ChangeStatus::ConflictEdited,
1676
                        });
1677
                    }
1678
                    return Ok(());
1679
                }
1680
                let current = blobs.first().copied();
1681
                if current != Some(new_ref) {
1682
                    if e.kind == NodeKind::File && !wants_opaque {
1683
                        // Opaque → text (spec §7.5).
1684
                        if let Some(old) = mode_atom {
1685
                            self.tree_ops.push(TreeOp::SetMode {
1686
                                node,
1687
                                old,
1688
                                mode: Mode {
1689
                                    exec: e.exec,
1690
                                    opaque: false,
1691
                                },
1692
                            });
1693
                        }
1694
                        self.edits.push(Edit::Replace {
1695
                            node,
1696
                            old: current,
1697
                            new: None,
1698
                        });
1699
                        if !e.content.is_empty() {
1700
                            self.edits.push(Edit::Insert {
1701
                                node,
1702
                                after: crate::objects::AtomRef::Start,
1703
                                before: crate::objects::AtomRef::End,
1704
                                lines: split_lines(&e.content).iter().map(|l| l.to_vec()).collect(),
1705
                            });
1706
                        }
1707
                    } else {
1708
                        let blob = self.blob_of(repo, path, e, nocompress)?;
1709
                        self.edits.push(Edit::Replace {
1710
                            node,
1711
                            old: current,
1712
                            new: Some(blob),
1713
                        });
1714
                    }
1715
                    status = Some(ChangeStatus::Modified);
1716
                } else if e.kind == NodeKind::File && e.exec != expected.mode.exec {
1717
                    if let Some(old) = mode_atom {
1718
                        self.tree_ops.push(TreeOp::SetMode {
1719
                            node,
1720
                            old,
1721
                            mode: Mode {
1722
                                exec: e.exec,
1723
                                opaque: true,
1724
                            },
1725
                        });
1726
                        status = Some(ChangeStatus::ModeChanged);
1727
                    }
1728
                }
1729
            }
1730
        }
1731
        if let Some(s) = status {
1732
            self.statuses.push(PathStatus {
1733
                path: path.to_string(),
1734
                status: s,
1735
            });
1736
        }
1737
        Ok(())
1738
    }
1739
}
1740
1741
fn repo_live_keys(base: &State, node: &NodeId) -> Vec<crate::graph::AtomKey> {
1742
    base.live_lines(node).into_iter().map(|(k, _)| k).collect()
1743
}
1744
1745
/// The changes a change's scope references (spec §8.1): introducers of every
1746
/// atom, placement, and mode it touches, and of every node it operates on.
1747
pub fn referenced_changes(change: &Change, base: &State) -> BTreeSet<ChangeHash> {
1748
    let mut out = BTreeSet::new();
1749
    let opref = |r: &OpRef, out: &mut BTreeSet<ChangeHash>| {
1750
        if !r.change.is_zero() {
1751
            out.insert(r.change);
1752
        }
1753
    };
1754
    let mut nodes: Vec<NodeId> = Vec::new();
1755
    for op in &change.tree_ops {
1756
        match op {
1757
            TreeOp::AddNode { parent, .. } => nodes.push(*parent),
1758
            TreeOp::RemoveNode { node, placement } => {
1759
                nodes.push(*node);
1760
                opref(placement, &mut out);
1761
            }
1762
            TreeOp::Move {
1763
                node, old, parent, ..
1764
            } => {
1765
                nodes.push(*node);
1766
                nodes.push(*parent);
1767
                opref(old, &mut out);
1768
            }
1769
            TreeOp::SetMode { node, old, .. } => {
1770
                nodes.push(*node);
1771
                opref(old, &mut out);
1772
            }
1773
        }
1774
    }
1775
    for e in &change.edits {
1776
        nodes.push(e.node());
1777
        match e {
1778
            Edit::Insert { after, before, .. } => {
1779
                for r in [after, before] {
1780
                    if let crate::objects::AtomRef::Atom { change, .. } = r {
1781
                        if !change.is_zero() {
1782
                            out.insert(*change);
1783
                        }
1784
                    }
1785
                }
1786
            }
1787
            Edit::Delete { atoms, .. } => {
1788
                // Deleting an atom also depends on whoever inserted the live
1789
                // atoms right after it: the author saw those insertions, and
1790
                // without the dependency spec §9.1 would call the deletion
1791
                // concurrent with them (a delete/insert conflict).
1792
                let graph = base.file(&e.node());
1793
                for r in atoms {
1794
                    if !r.change.is_zero() {
1795
                        out.insert(r.change);
1796
                    }
1797
                    if let Some(g) = graph {
1798
                        for i in r.from..r.to {
1799
                            out.extend(
1800
                                g.live_successor_changes(&(r.change, i))
1801
                                    .into_iter()
1802
                                    .filter(|c| !c.is_zero()),
1803
                            );
1804
                        }
1805
                    }
1806
                }
1807
            }
1808
            // Replacing a blob depends on the change that made it current,
1809
            // as deleting a line depends on the line's introducer.
1810
            Edit::Replace {
1811
                node,
1812
                old: Some(old),
1813
                ..
1814
            } => {
1815
                out.extend(
1816
                    base.live_replaces(node)
1817
                        .into_iter()
1818
                        .filter(|(c, b)| b == old && !c.is_zero())
1819
                        .map(|(c, _)| c),
1820
                );
1821
            }
1822
            Edit::Replace { .. } => {}
1823
        }
1824
    }
1825
    for n in nodes {
1826
        if let Some(h) = base.tree().introducer(&n) {
1827
            out.insert(h);
1828
        }
1829
    }
1830
    out
1831
}
1832
1833
/// Paths of the nodes a change adds on top of `base_snapshot`.
1834
pub fn added_node_paths(
1835
    change: &Change,
1836
    base_snapshot: &Snapshot,
1837
) -> HashMap<String, (NodeId, NodeKind)> {
1838
    let by_node = base_snapshot.tree.by_node();
1839
    let mut new_names: HashMap<NodeId, (NodeId, String, NodeKind)> = HashMap::new();
1840
    for op in &change.tree_ops {
1841
        if let TreeOp::AddNode {
1842
            node,
1843
            parent,
1844
            name,
1845
            kind,
1846
            ..
1847
        } = op
1848
        {
1849
            new_names.insert(*node, (*parent, name.clone(), *kind));
1850
        }
1851
    }
1852
    let mut out = HashMap::new();
1853
    for (node, (_, _, kind)) in &new_names {
1854
        if let Some(path) = path_of_node(node, &by_node, &new_names) {
1855
            out.insert(path, (*node, *kind));
1856
        }
1857
    }
1858
    out
1859
}
1860
1861
fn path_of_node(
1862
    n: &NodeId,
1863
    by_node: &HashMap<NodeId, &crate::tree::TreeEntry>,
1864
    new_names: &HashMap<NodeId, (NodeId, String, NodeKind)>,
1865
) -> Option<String> {
1866
    if let Some(e) = by_node.get(n) {
1867
        return Some(e.path.clone());
1868
    }
1869
    let mut parts = Vec::new();
1870
    let mut cur = *n;
1871
    loop {
1872
        if cur.is_root() {
1873
            break;
1874
        }
1875
        if let Some(e) = by_node.get(&cur) {
1876
            if !e.path.is_empty() {
1877
                parts.push(e.path.clone());
1878
            }
1879
            break;
1880
        }
1881
        let (parent, name, _) = new_names.get(&cur)?;
1882
        parts.push(name.clone());
1883
        cur = *parent;
1884
    }
1885
    parts.reverse();
1886
    Some(parts.join("/"))
1887
}
1888
1889
/// Render a change's operations with line content, using `base` for deleted lines.
1890
pub fn render_change(change: &Change, base: &State, base_snapshot: &Snapshot) -> String {
1891
    let by_node = base_snapshot.tree.by_node();
1892
    let mut new_names: HashMap<NodeId, (NodeId, String, NodeKind)> = HashMap::new();
1893
    for op in &change.tree_ops {
1894
        if let TreeOp::AddNode {
1895
            node,
1896
            parent,
1897
            name,
1898
            kind,
1899
            ..
1900
        } = op
1901
        {
1902
            new_names.insert(*node, (*parent, name.clone(), *kind));
1903
        }
1904
    }
1905
    let path_of = |n: &NodeId| -> String {
1906
        path_of_node(n, &by_node, &new_names).unwrap_or_else(|| format!("<node {}>", n.short(8)))
1907
    };
1908
1909
    let mut out = String::new();
1910
    for op in &change.tree_ops {
1911
        match op {
1912
            TreeOp::AddNode {
1913
                node, kind, mode, ..
1914
            } => {
1915
                out.push_str(&format!(
1916
                    "A {} ({:?}{}{})\n",
1917
                    path_of(node),
1918
                    kind,
1919
                    if mode.exec { ", exec" } else { "" },
1920
                    if mode.opaque { ", opaque" } else { "" }
1921
                ));
1922
            }
1923
            TreeOp::RemoveNode { node, .. } => out.push_str(&format!("D {}\n", path_of(node))),
1924
            TreeOp::Move { node, name, .. } => {
1925
                out.push_str(&format!("R {} -> {}\n", path_of(node), name))
1926
            }
1927
            TreeOp::SetMode { node, mode, .. } => {
1928
                out.push_str(&format!(
1929
                    "M {} mode: exec={} opaque={}\n",
1930
                    path_of(node),
1931
                    mode.exec,
1932
                    mode.opaque
1933
                ));
1934
            }
1935
        }
1936
    }
1937
    let mut last_node: Option<NodeId> = None;
1938
    for e in &change.edits {
1939
        let n = e.node();
1940
        if last_node != Some(n) {
1941
            out.push_str(&format!("--- {}\n", path_of(&n)));
1942
            last_node = Some(n);
1943
        }
1944
        match e {
1945
            Edit::Insert { lines, .. } => {
1946
                for l in lines {
1947
                    out.push('+');
1948
                    out.push_str(&String::from_utf8_lossy(l));
1949
                    if !l.ends_with(b"\n") {
1950
                        out.push('\n');
1951
                    }
1952
                }
1953
            }
1954
            Edit::Delete { atoms, .. } => {
1955
                for r in atoms {
1956
                    for i in r.from..r.to {
1957
                        let content = base
1958
                            .file(&n)
1959
                            .and_then(|g| g.content(&(r.change, i)))
1960
                            .unwrap_or(b"<unknown>\n");
1961
                        out.push('-');
1962
                        out.push_str(&String::from_utf8_lossy(content));
1963
                        if !content.ends_with(b"\n") {
1964
                            out.push('\n');
1965
                        }
1966
                    }
1967
                }
1968
            }
1969
            Edit::Replace { old, new, .. } => {
1970
                out.push_str(&format!(
1971
                    "  opaque content {} -> {}\n",
1972
                    old.map(|o| o.short(12)).unwrap_or_else(|| "none".into()),
1973
                    new.map(|o| o.short(12)).unwrap_or_else(|| "none".into())
1974
                ));
1975
            }
1976
        }
1977
    }
1978
    out
1979
}
1980
1981
/// Pair removed files with added files of the same kind whose contents are
1982
/// at least `RENAME_THRESHOLD` percent alike, best matches first. Beyond
1983
/// `RENAME_LIMIT` candidate pairs only identical contents are paired.
1984
const RENAME_THRESHOLD: u32 = 50;
1985
const RENAME_LIMIT: usize = 10_000;
1986
1987
fn detect_renames(
1988
    base_snapshot: &Snapshot,
1989
    fs_entries: &BTreeMap<String, FsEntry>,
1990
    in_scope: impl Fn(&str) -> bool,
1991
) -> Vec<(String, String)> {
1992
    let removed: Vec<(&String, &crate::state::FileState)> = base_snapshot
1993
        .files
1994
        .iter()
1995
        .filter(|(p, f)| {
1996
            f.kind != NodeKind::Dir
1997
                && !fs_entries.contains_key(*p)
1998
                && in_scope(p)
1999
                && !f.is_conflicted()
2000
        })
2001
        .collect();
2002
    let added: Vec<(&String, &FsEntry)> = fs_entries
2003
        .iter()
2004
        .filter(|(p, e)| e.kind != NodeKind::Dir && !base_snapshot.files.contains_key(*p))
2005
        .collect();
2006
    if removed.is_empty() || added.is_empty() {
2007
        return vec![];
2008
    }
2009
    let exact_only = removed.len() * added.len() > RENAME_LIMIT;
2010
    let old_content = |f: &crate::state::FileState| -> Option<Vec<u8>> {
2011
        match &f.content {
2012
            FileContent::Text { bytes, .. } => Some(bytes.clone()),
2013
            _ => None,
2014
        }
2015
    };
2016
    let mut scored: Vec<(u32, usize, usize)> = Vec::new();
2017
    for (ri, (_, f)) in removed.iter().enumerate() {
2018
        let old = old_content(f);
2019
        let old_blob = match &f.content {
2020
            FileContent::Opaque { blobs } if blobs.len() == 1 => Some(blobs[0]),
2021
            _ => None,
2022
        };
2023
        for (ai, (_, e)) in added.iter().enumerate() {
2024
            if e.kind != f.kind {
2025
                continue;
2026
            }
2027
            let score = match (&old, old_blob) {
2028
                (Some(o), _) => {
2029
                    if exact_only {
2030
                        if *o == e.content {
2031
                            100
2032
                        } else {
2033
                            0
2034
                        }
2035
                    } else {
2036
                        similarity(o, &e.content)
2037
                    }
2038
                }
2039
                (None, Some(b)) if e.blob.unwrap_or_else(|| Repo::blob_ref(&e.content)) == b => 100,
2040
                _ => 0,
2041
            };
2042
            if score >= RENAME_THRESHOLD {
2043
                scored.push((score, ri, ai));
2044
            }
2045
        }
2046
    }
2047
    scored.sort_by(|a, b| {
2048
        b.0.cmp(&a.0)
2049
            .then(removed[a.1].0.cmp(removed[b.1].0))
2050
            .then(added[a.2].0.cmp(added[b.2].0))
2051
    });
2052
    let mut used_r = vec![false; removed.len()];
2053
    let mut used_a = vec![false; added.len()];
2054
    let mut out = Vec::new();
2055
    for (_, ri, ai) in scored {
2056
        if used_r[ri] || used_a[ai] {
2057
            continue;
2058
        }
2059
        used_r[ri] = true;
2060
        used_a[ai] = true;
2061
        out.push((removed[ri].0.clone(), added[ai].0.clone()));
2062
    }
2063
    out
2064
}
2065
2066
/// Percentage of the larger file's bytes found in lines the two share
2067
/// (multiset intersection of lines), like Git's similarity index.
2068
pub fn similarity(a: &[u8], b: &[u8]) -> u32 {
2069
    if a == b {
2070
        return 100;
2071
    }
2072
    if a.is_empty() || b.is_empty() {
2073
        return 0;
2074
    }
2075
    let mut counts: HashMap<&[u8], usize> = HashMap::new();
2076
    for l in split_lines(a) {
2077
        *counts.entry(l).or_default() += 1;
2078
    }
2079
    let mut shared = 0usize;
2080
    for l in split_lines(b) {
2081
        if let Some(n) = counts.get_mut(l) {
2082
            if *n > 0 {
2083
                *n -= 1;
2084
                shared += l.len();
2085
            }
2086
        }
2087
    }
2088
    (shared * 100 / a.len().max(b.len())) as u32
2089
}