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