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