OXYGENHUB
# 10b4fd430eab oxygen / crates / oxy-core / src / repo / snapshot.rs
106.2 KiB · Rust · last changed Diff from the status cache: the working-copy change rendered against its indexed base (refs #41) 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
                    // With uncommitted work, the status cache below holds
608
                    // only while the manifest describes the edited files as
609
                    // they are now.
610
                    || (uncommitted && statuses.iter().any(|st| {
611
                        let Some(e) = fs_entries.get(&st.path) else {
612
                            return m.entries.contains_key(&st.path);
613
                        };
614
                        let Some(me) = m.entries.get(&st.path) else {
615
                            return true;
616
                        };
617
                        let hash = e
618
                            .content_hash
619
                            .unwrap_or_else(|| *blake3::hash(&e.content).as_bytes());
620
                        let stat = e.stat.or_else(|| {
621
                            fs::symlink_metadata(self.root.join(&st.path))
622
                                .ok()
623
                                .map(|md| (md.len(), super::prompt::mtime_ns(&md)))
624
                        });
625
                        me.hash != hash || stat != Some((me.size, me.mtime_ns))
626
                    }))
627
            }
628
        };
629
        if worth {
630
            self.write_manifest_entries(conflicted, uncommitted, &fs_entries, &built.blobs)?;
631
        }
632
        self.write_status_cache((uncommitted && !conflicted).then_some(&new_hash), &statuses);
633
        let attributes = crate::attributes::Attributes::from_files(
634
            fs_entries
635
                .iter()
636
                .filter(|(p, _)| is_attributes(p))
637
                .map(|(p, e)| (p.as_str(), e.content.as_slice())),
638
        );
639
        Ok(SnapshotResult {
640
            wc_hash: new_hash,
641
            wc,
642
            base,
643
            base_snapshot,
644
            statuses,
645
            changed,
646
            resolves,
647
            contributors,
648
            attributes,
649
            untracked_nested: self.untracked_nested.borrow().clone(),
650
        })
651
    }
652
653
    /// `oxy status --json` (spec §9.5): the changed paths and every conflict
654
    /// of the working copy's base with its kind, path, and contributing
655
    /// ChangeIds.
656
    pub fn status_json(&self, snap: &SnapshotResult) -> Result<String> {
657
        let heads = self.bookmark_heads()?;
658
        let base_snapshot = &snap.base_snapshot;
659
        let by_node = base_snapshot.tree.by_node();
660
        let path_of = |n: &NodeId| by_node.get(n).map(|e| e.path.clone());
661
        let id_of = |h: &ChangeHash| {
662
            snap.base
663
                .get(h)
664
                .map(|m| m.change_id.to_hex())
665
                .unwrap_or_else(|| h.to_hex())
666
        };
667
        let paths = json_array(snap.statuses.iter().map(|s| {
668
            format!(
669
                "{{\"path\":{},\"status\":{}}}",
670
                json_str(&s.path),
671
                json_str(&format!("{:?}", s.status))
672
            )
673
        }));
674
        let mut conflicts: Vec<String> = Vec::new();
675
        for (p, f) in &base_snapshot.files {
676
            if !f.is_conflicted() {
677
                continue;
678
            }
679
            let (kind, changes) = match &f.content {
680
                FileContent::Text { .. } => {
681
                    ("text", snap.base.conflict_regions(&f.node).contributors)
682
                }
683
                FileContent::Opaque { blobs } => {
684
                    ("replace", snap.base.blob_contributors(&f.node, blobs))
685
                }
686
                FileContent::Dir => continue,
687
            };
688
            let resolved = match snap
689
                .statuses
690
                .iter()
691
                .find(|s| s.path == *p)
692
                .map(|s| s.status)
693
            {
694
                Some(ChangeStatus::Resolved) => "true",
695
                Some(ChangeStatus::ConflictEdited) => "\"markers\"",
696
                _ => "false",
697
            };
698
            conflicts.push(format!(
699
                "{{\"kind\":{},\"path\":{},\"node\":{},\"changes\":{},\"resolved\":{resolved}}}",
700
                json_str(kind),
701
                json_str(p),
702
                json_str(&f.node.to_hex()),
703
                json_array(changes.iter().map(|h| json_str(&id_of(h))))
704
            ));
705
        }
706
        for c in &base_snapshot.tree.conflicts {
707
            let (kind, nodes): (&str, Vec<NodeId>) = match c {
708
                crate::tree::TreeConflict::Name { nodes, .. } => ("name", nodes.clone()),
709
                crate::tree::TreeConflict::MultiPlacement { node, .. } => {
710
                    ("multi-placement", vec![*node])
711
                }
712
                crate::tree::TreeConflict::Orphan { node, .. } => ("orphan", vec![*node]),
713
                crate::tree::TreeConflict::Cycle { node } => ("cycle", vec![*node]),
714
                crate::tree::TreeConflict::Mode { node, .. } => ("mode", vec![*node]),
715
            };
716
            let detail = match c {
717
                crate::tree::TreeConflict::Name { name, parent, .. } => {
718
                    let dir = if *parent == NodeId::ROOT {
719
                        String::new()
720
                    } else {
721
                        path_of(parent).unwrap_or_default()
722
                    };
723
                    format!(
724
                        ",\"path\":{}",
725
                        json_str(&if dir.is_empty() {
726
                            name.clone()
727
                        } else {
728
                            format!("{dir}/{name}")
729
                        })
730
                    )
731
                }
732
                _ => nodes
733
                    .first()
734
                    .and_then(path_of)
735
                    .map(|p| format!(",\"path\":{}", json_str(&p)))
736
                    .unwrap_or_default(),
737
            };
738
            conflicts.push(format!(
739
                "{{\"kind\":{},\"nodes\":{}{detail}}}",
740
                json_str(kind),
741
                json_array(nodes.iter().map(|n| json_str(&n.to_hex())))
742
            ));
743
        }
744
        Ok(format!(
745
            "{{\"bookmark\":{},\"working_copy\":{},\"heads\":{},\"clean\":{},\"conflicted\":{},\"paths\":{paths},\"conflicts\":{},\"untracked_nested\":{}}}",
746
            json_str(&self.config.bookmark),
747
            json_str(&snap.wc.change_id.to_hex()),
748
            heads.len(),
749
            snap.statuses.is_empty(),
750
            base_snapshot.is_conflicted(),
751
            json_array(conflicts),
752
            json_array(snap.untracked_nested.iter().map(|p| json_str(p)))
753
        ))
754
    }
755
756
    /// Turn the working-copy change into a normal change on the bookmark (spec §12.3).
757
    pub fn commit(&self, message: &str, extra_deps: &[ChangeHash]) -> Result<ChangeHash> {
758
        self.commit_selection(message, extra_deps, &Selection::All)
759
    }
760
761
    /// The hunks of the working copy, for `oxy commit --interactive`: each
762
    /// tree operation and each edit, in the order `select_hunks` numbers them.
763
    pub fn hunks(&self) -> Result<(SnapshotResult, Vec<Hunk>)> {
764
        let snap = self.snapshot_status("oxy commit")?;
765
        let hunks = render_hunks(&snap.wc, &snap.base, &snap.base_snapshot);
766
        Ok((snap, hunks))
767
    }
768
769
    /// Commit part of the working copy (spec §12.3). What is not selected
770
    /// stays on disk as uncommitted work: the next snapshot rebuilds it
771
    /// against the new base, so the working copy always describes the
772
    /// directory.
773
    /// The graph key in `st` of each text file at `paths`, the paths a
774
    /// commit changed: only their graphs changed, so the keys the manifest
775
    /// holds for the others still stand (and any that does not is simply
776
    /// not trusted by the next snapshot, which compares keys). Files with
777
    /// an `eol` attribute are left out: their bytes on disk are not the
778
    /// rendering.
779
    fn committed_graph_keys(
780
        &self,
781
        st: &State,
782
        paths: &[String],
783
        attrs: &crate::attributes::Attributes,
784
    ) -> HashMap<String, [u8; 32]> {
785
        let _t = crate::timing::phase("commit: graph keys");
786
        let view = st.tree().view();
787
        paths
788
            .iter()
789
            .filter_map(|p| {
790
                let e = view.entries.get(p)?;
791
                (e.kind == NodeKind::File && !e.mode.opaque && attrs.lookup(p).eol.is_none())
792
                    .then_some(())?;
793
                Some((p.clone(), st.graph_key(&e.node)?))
794
            })
795
            .collect()
796
    }
797
798
    pub fn commit_selection(
799
        &self,
800
        message: &str,
801
        extra_deps: &[ChangeHash],
802
        selection: &Selection,
803
    ) -> Result<ChangeHash> {
804
        let _wc = self.lock_working_copy()?;
805
        let mut snap = self.snapshot_as("oxy commit", true, true)?;
806
        if snap.wc.tree_ops.is_empty() && snap.wc.edits.is_empty() {
807
            return fail("nothing to commit: the working copy matches its base");
808
        }
809
        if let Some(s) = snap
810
            .statuses
811
            .iter()
812
            .find(|s| s.status == ChangeStatus::ConflictEdited)
813
        {
814
            return fail(format!("{} still contains conflict markers", s.path));
815
        }
816
        if message.trim().is_empty() {
817
            return fail("a commit message is required");
818
        }
819
        // What the whole working copy references, before a whole commit
820
        // takes its operations over (they are moved, not copied: for a
821
        // large tree they are most of the memory).
822
        let wc_refs = referenced_changes(&snap.wc, &snap.base);
823
        let changed_paths: Vec<String> = snap.statuses.iter().map(|s| s.path.clone()).collect();
824
        let (tree_ops, edits, partial) = match selection {
825
            Selection::All => (
826
                std::mem::take(&mut snap.wc.tree_ops),
827
                std::mem::take(&mut snap.wc.edits),
828
                false,
829
            ),
830
            Selection::Paths(paths) => {
831
                let (o, e) = select_paths(&snap.wc, &snap.base_snapshot, paths);
832
                let partial = o.len() != snap.wc.tree_ops.len() || e.len() != snap.wc.edits.len();
833
                (o, e, partial)
834
            }
835
            Selection::Hunks(indices) => {
836
                let (o, e) = select_hunks(&snap.wc, indices);
837
                let partial = o.len() != snap.wc.tree_ops.len() || e.len() != snap.wc.edits.len();
838
                (o, e, partial)
839
            }
840
        };
841
        if tree_ops.is_empty() && edits.is_empty() {
842
            return fail("nothing selected to commit");
843
        }
844
        if partial && snap.resolves {
845
            return fail("a conflict resolution must be committed whole");
846
        }
847
        // pre-commit hook: may veto.
848
        self.run_hook(
849
            "pre-commit",
850
            &format!(
851
                "{{\"event\":\"pre-commit\",\"message\":{},\"paths\":{}}}",
852
                json_str(message),
853
                json_array(snap.statuses.iter().map(|s| format!(
854
                    "{{\"path\":{},\"status\":{}}}",
855
                    json_str(&s.path),
856
                    json_str(&format!("{:?}", s.status))
857
                )))
858
            ),
859
        )?;
860
        let (op_ref, op) = self.head_op()?;
861
        let mut deps: BTreeSet<ChangeHash> = wc_refs;
862
        // semantic-deps hook: may add explicit dependencies (spec §8.1).
863
        if self.config.semantic_deps {
864
            let touched: Vec<String> = snap.statuses.iter().map(|s| s.path.clone()).collect();
865
            let by_node = snap.base_snapshot.tree.by_node();
866
            let mut candidates: Vec<(ChangeId, ChangeHash, Vec<String>)> = Vec::new();
867
            let mut seen: BTreeSet<ChangeHash> = BTreeSet::new();
868
            for h in deps.iter().chain(snap.base.maximal(&snap.wc.deps).iter()) {
869
                if !seen.insert(*h) {
870
                    continue;
871
                }
872
                let c = self.store.get_change(h)?;
873
                let mut paths: BTreeSet<String> = BTreeSet::new();
874
                for n in c
875
                    .tree_ops
876
                    .iter()
877
                    .map(|o| o.node())
878
                    .chain(c.edits.iter().map(|e| e.node()))
879
                {
880
                    if let Some(e) = by_node.get(&n) {
881
                        paths.insert(e.path.clone());
882
                    }
883
                }
884
                candidates.push((c.change_id, *h, paths.into_iter().collect()));
885
            }
886
            for d in self.semantic_deps(&snap.wc.change_id, &touched, &candidates)? {
887
                if snap.base.contains(&d) {
888
                    deps.insert(d);
889
                }
890
            }
891
        }
892
        // A resolution depends on every change that contributed to the
893
        // conflict (spec §8.1). Tree and opaque conflicts are resolved through
894
        // ordinary operations whose references already cover the contributors.
895
        deps.extend(snap.contributors.iter().copied());
896
        for d in extra_deps {
897
            if !snap.base.contains(d) {
898
                return fail(format!(
899
                    "--depends-on {d}: not in the working copy's base state"
900
                ));
901
            }
902
            deps.insert(*d);
903
        }
904
        let mut change = Change {
905
            version: crate::objects::CHANGE_VERSION,
906
            change_id: if partial {
907
                ChangeId::random()
908
            } else {
909
                snap.wc.change_id
910
            },
911
            deps: vec![],
912
            author: self.author(),
913
            hlc: Hlc::now(),
914
            message: message.trim_end().to_string(),
915
            tree_ops,
916
            edits,
917
            kind: if snap.resolves {
918
                ChangeKind::Resolution
919
            } else {
920
                ChangeKind::Normal
921
            },
922
        };
923
        if partial {
924
            // Dependencies come from what the selected part references, not
925
            // from the whole working copy.
926
            deps = referenced_changes(&change, &snap.base);
927
            for d in extra_deps {
928
                deps.insert(*d);
929
            }
930
        }
931
        change.deps = deps.into_iter().collect();
932
        change.normalize();
933
        let signing = crate::timing::phase("commit: sign and store");
934
        let hash = self.store_signed(&change)?;
935
        drop(signing);
936
        let extending = crate::timing::phase("commit: extend the state");
937
938
        // New bookmark heads: maximal elements of old heads plus the new change.
939
        // The working copy continues on its own base plus the new change, which
940
        // is exactly what the files on disk contain; the bookmark may hold
941
        // other heads (and conflicts) the working copy has not checked out.
942
        let old_heads = self.heads_of(&op.view, &self.config.bookmark)?;
943
        let old_base = snap.base.maximal(&snap.wc.deps);
944
        let mut all: Vec<ChangeHash> = old_heads.clone();
945
        all.extend(old_base.iter().copied());
946
        all.push(hash);
947
        // The snapshot already loaded the working copy's base; when that also
948
        // holds every bookmark head, it is the state to extend.
949
        let mut st = if old_heads.iter().all(|h| snap.base.contains(h)) {
950
            snap.base
951
        } else {
952
            self.load_state(&all)?
953
        };
954
        st.add_hashed(hash, change)?;
955
        let mut with_new = old_heads.clone();
956
        with_new.push(hash);
957
        let new_heads = st.maximal(&with_new);
958
        // Automatic checkpoint once enough changes accumulated (spec §11).
959
        let since = self
960
            .latest_checkpoint(&self.config.bookmark)?
961
            .map(|(_, cp)| cp.count)
962
            .unwrap_or(0);
963
        if self.config.checkpoint_interval > 0
964
            && (st.len() as u64).saturating_sub(since) >= self.config.checkpoint_interval
965
        {
966
            let cp_state = self.load_state_full(&new_heads)?;
967
            self.write_checkpoint(&self.config.bookmark, &cp_state, &new_heads)?;
968
        }
969
        let mut wc_base = old_base.clone();
970
        wc_base.push(hash);
971
        let wc_base = st.maximal(&wc_base);
972
        drop(extending);
973
974
        // The graph keys of the files as they now are, from the state the
975
        // commit just extended: a file whose graph it built has none, and
976
        // is read by the next snapshot; a key the next base does not share
977
        // (the bookmark held other heads) is simply not trusted then.
978
        let committed_keys =
979
            (!partial).then(|| self.committed_graph_keys(&st, &changed_paths, &snap.attributes));
980
        let recording = crate::timing::phase("commit: record");
981
        let wc = self.new_working_copy(wc_base, "");
982
        let wc_hash = self.store.put_change(&wc)?;
983
        let mut view = op.view.clone();
984
        view.bookmarks.insert(
985
            self.config.bookmark.clone(),
986
            self.store.put_state(&StateObject::new(new_heads))?,
987
        );
988
        view.workspaces.insert(self.workspace, wc_hash);
989
        self.record_op(&[op_ref], &format!("oxy commit -m {message:?}"), view)?;
990
        drop(recording);
991
        let _rewrite = crate::timing::phase("commit: manifest and hooks");
992
        if partial {
993
            // The rest is rebuilt from disk by the next snapshot.
994
            self.drop_manifest();
995
        } else {
996
            let conflicted = snap.base_snapshot.is_conflicted() && !snap.resolves;
997
            // The files on disk are now exactly the new base's renderings:
998
            // record their graph keys, so the next snapshot neither reads nor
999
            // renders them (oxygen#35).
1000
            let keys = if conflicted {
1001
                HashMap::new()
1002
            } else {
1003
                committed_keys.unwrap_or_default()
1004
            };
1005
            self.rewrite_manifest(conflicted, false, &keys)?;
1006
        }
1007
        self.maybe_autopack()?;
1008
        let _ = self.run_hook(
1009
            "post-commit",
1010
            &format!(
1011
                "{{\"event\":\"post-commit\",\"change_id\":{},\"hash\":{},\"message\":{}}}",
1012
                json_str(&snap.wc.change_id.to_hex()),
1013
                json_str(&hash.to_hex()),
1014
                json_str(message)
1015
            ),
1016
        );
1017
        Ok(hash)
1018
    }
1019
}
1020
1021
/// What part of the working copy a commit takes (spec §12.3).
1022
#[derive(Clone, Debug)]
1023
pub enum Selection {
1024
    All,
1025
    /// Every operation and edit on nodes under these paths.
1026
    Paths(Vec<String>),
1027
    /// Hunk indices as `Repo::hunks` numbers them; dependent hunks are added.
1028
    Hunks(Vec<usize>),
1029
}
1030
1031
/// One selectable piece of the working copy: a tree operation or an edit.
1032
#[derive(Clone, Debug)]
1033
pub struct Hunk {
1034
    pub index: usize,
1035
    pub path: String,
1036
    /// Rendered like `oxy diff`.
1037
    pub text: String,
1038
}
1039
1040
/// The tree operations and edits on nodes under `paths`, plus the
1041
/// additions of any new parent directories they need.
1042
fn select_paths(
1043
    wc: &Change,
1044
    base_snapshot: &Snapshot,
1045
    paths: &[String],
1046
) -> (Vec<TreeOp>, Vec<Edit>) {
1047
    let selected = |p: &str| {
1048
        paths
1049
            .iter()
1050
            .any(|x| p == x || p.starts_with(&format!("{}/", x.trim_end_matches('/'))))
1051
    };
1052
    let by_node = base_snapshot.tree.by_node();
1053
    let mut new_names: HashMap<NodeId, (NodeId, String, NodeKind)> = HashMap::new();
1054
    for op in &wc.tree_ops {
1055
        if let TreeOp::AddNode {
1056
            node,
1057
            parent,
1058
            name,
1059
            kind,
1060
            ..
1061
        } = op
1062
        {
1063
            new_names.insert(*node, (*parent, name.clone(), *kind));
1064
        }
1065
    }
1066
    let mut nodes: BTreeSet<NodeId> = BTreeSet::new();
1067
    for n in wc
1068
        .tree_ops
1069
        .iter()
1070
        .map(|o| o.node())
1071
        .chain(wc.edits.iter().map(|e| e.node()))
1072
    {
1073
        if path_of_node(&n, &by_node, &new_names).is_some_and(|p| selected(&p)) {
1074
            nodes.insert(n);
1075
        }
1076
    }
1077
    // New parents of selected new nodes come along.
1078
    let mut changed = true;
1079
    while changed {
1080
        changed = false;
1081
        for (n, (parent, _, _)) in &new_names {
1082
            if nodes.contains(n) && new_names.contains_key(parent) && nodes.insert(*parent) {
1083
                changed = true;
1084
            }
1085
        }
1086
    }
1087
    let ops = wc
1088
        .tree_ops
1089
        .iter()
1090
        .filter(|o| nodes.contains(&o.node()))
1091
        .cloned()
1092
        .collect();
1093
    let edits = wc
1094
        .edits
1095
        .iter()
1096
        .filter(|e| nodes.contains(&e.node()))
1097
        .cloned()
1098
        .collect();
1099
    (ops, edits)
1100
}
1101
1102
/// The hunks `indices` name plus whatever they refer to within the working
1103
/// copy (the parent directory of an added node, the insert that introduced
1104
/// an anchor line), renumbered so the result is a well-formed change.
1105
fn select_hunks(wc: &Change, indices: &[usize]) -> (Vec<TreeOp>, Vec<Edit>) {
1106
    let n_ops = wc.tree_ops.len();
1107
    let mut ops_sel = vec![false; n_ops];
1108
    let mut edits_sel = vec![false; wc.edits.len()];
1109
    for &i in indices {
1110
        if i < n_ops {
1111
            ops_sel[i] = true;
1112
        } else if i - n_ops < wc.edits.len() {
1113
            edits_sel[i - n_ops] = true;
1114
        }
1115
    }
1116
    // Atom ranges each insert introduces, per node, in the working copy's numbering.
1117
    let mut per_node: HashMap<NodeId, u32> = HashMap::new();
1118
    let mut insert_ranges: Vec<Option<(NodeId, u32, u32)>> = Vec::new();
1119
    for e in &wc.edits {
1120
        insert_ranges.push(match e {
1121
            Edit::Insert { node, lines, .. } => {
1122
                let start = per_node.entry(*node).or_default();
1123
                let r = (*node, *start, *start + lines.len() as u32);
1124
                *start += lines.len() as u32;
1125
                Some(r)
1126
            }
1127
            _ => None,
1128
        });
1129
    }
1130
    let add_index: HashMap<NodeId, usize> = wc
1131
        .tree_ops
1132
        .iter()
1133
        .enumerate()
1134
        .filter_map(|(i, o)| {
1135
            if let TreeOp::AddNode { node, .. } = o {
1136
                Some((*node, i))
1137
            } else {
1138
                None
1139
            }
1140
        })
1141
        .collect();
1142
    let insert_for = |node: &NodeId, index: u32| -> Option<usize> {
1143
        insert_ranges
1144
            .iter()
1145
            .position(|r| matches!(r, Some((n, a, b)) if n == node && *a <= index && index < *b))
1146
    };
1147
    // Closure.
1148
    let mut changed = true;
1149
    while changed {
1150
        changed = false;
1151
        for i in 0..n_ops {
1152
            if !ops_sel[i] {
1153
                continue;
1154
            }
1155
            if let TreeOp::AddNode { node, parent, .. } = &wc.tree_ops[i] {
1156
                if let Some(&p) = add_index.get(parent) {
1157
                    if !ops_sel[p] {
1158
                        ops_sel[p] = true;
1159
                        changed = true;
1160
                    }
1161
                }
1162
                // A new node's content belongs with its addition: nobody
1163
                // wants an empty file committed apart from its lines.
1164
                for (j, e) in wc.edits.iter().enumerate() {
1165
                    if e.node() == *node && !edits_sel[j] {
1166
                        edits_sel[j] = true;
1167
                        changed = true;
1168
                    }
1169
                }
1170
            }
1171
        }
1172
        for j in 0..wc.edits.len() {
1173
            if !edits_sel[j] {
1174
                continue;
1175
            }
1176
            let e = &wc.edits[j];
1177
            if let Some(&a) = add_index.get(&e.node()) {
1178
                if !ops_sel[a] {
1179
                    ops_sel[a] = true;
1180
                    changed = true;
1181
                }
1182
            }
1183
            if let Edit::Insert {
1184
                node,
1185
                after,
1186
                before,
1187
                ..
1188
            } = e
1189
            {
1190
                for r in [after, before] {
1191
                    if let AtomRef::Atom { change, index } = r {
1192
                        if change.is_zero() {
1193
                            if let Some(k) = insert_for(node, *index) {
1194
                                if !edits_sel[k] {
1195
                                    edits_sel[k] = true;
1196
                                    changed = true;
1197
                                }
1198
                            }
1199
                        }
1200
                    }
1201
                }
1202
            }
1203
        }
1204
    }
1205
    // Renumber self-references: old atom index → new index among selected inserts.
1206
    let mut remap: HashMap<(NodeId, u32), u32> = HashMap::new();
1207
    let mut new_counts: HashMap<NodeId, u32> = HashMap::new();
1208
    for (j, r) in insert_ranges.iter().enumerate() {
1209
        if let (true, Some((node, a, b))) = (edits_sel[j], r) {
1210
            let next = new_counts.entry(*node).or_default();
1211
            for old in *a..*b {
1212
                remap.insert((*node, old), *next);
1213
                *next += 1;
1214
            }
1215
        }
1216
    }
1217
    let map_ref = |r: AtomRef, node: &NodeId| -> AtomRef {
1218
        match r {
1219
            AtomRef::Atom { change, index } if change.is_zero() => AtomRef::Atom {
1220
                change,
1221
                index: remap.get(&(*node, index)).copied().unwrap_or(index),
1222
            },
1223
            other => other,
1224
        }
1225
    };
1226
    let ops = wc
1227
        .tree_ops
1228
        .iter()
1229
        .enumerate()
1230
        .filter(|(i, _)| ops_sel[*i])
1231
        .map(|(_, o)| o.clone())
1232
        .collect();
1233
    let edits = wc
1234
        .edits
1235
        .iter()
1236
        .enumerate()
1237
        .filter(|(j, _)| edits_sel[*j])
1238
        .map(|(_, e)| match e {
1239
            Edit::Insert {
1240
                node,
1241
                after,
1242
                before,
1243
                lines,
1244
            } => Edit::Insert {
1245
                node: *node,
1246
                after: map_ref(*after, node),
1247
                before: map_ref(*before, node),
1248
                lines: lines.clone(),
1249
            },
1250
            other => other.clone(),
1251
        })
1252
        .collect();
1253
    (ops, edits)
1254
}
1255
1256
/// Render each tree operation and edit of `change` on its own, numbered.
1257
pub fn render_hunks(change: &Change, base: &State, base_snapshot: &Snapshot) -> Vec<Hunk> {
1258
    let by_node = base_snapshot.tree.by_node();
1259
    let mut new_names: HashMap<NodeId, (NodeId, String, NodeKind)> = HashMap::new();
1260
    for op in &change.tree_ops {
1261
        if let TreeOp::AddNode {
1262
            node,
1263
            parent,
1264
            name,
1265
            kind,
1266
            ..
1267
        } = op
1268
        {
1269
            new_names.insert(*node, (*parent, name.clone(), *kind));
1270
        }
1271
    }
1272
    let mut out = Vec::new();
1273
    for (i, op) in change.tree_ops.iter().enumerate() {
1274
        let one = Change {
1275
            tree_ops: vec![op.clone()],
1276
            edits: vec![],
1277
            ..change.clone()
1278
        };
1279
        let path = path_of_node(&op.node(), &by_node, &new_names).unwrap_or_default();
1280
        out.push(Hunk {
1281
            index: i,
1282
            path,
1283
            text: render_change(&one, base, base_snapshot),
1284
        });
1285
    }
1286
    for (j, e) in change.edits.iter().enumerate() {
1287
        let one = Change {
1288
            tree_ops: vec![],
1289
            edits: vec![e.clone()],
1290
            ..change.clone()
1291
        };
1292
        let path = path_of_node(&e.node(), &by_node, &new_names).unwrap_or_default();
1293
        out.push(Hunk {
1294
            index: change.tree_ops.len() + j,
1295
            path,
1296
            text: render_change(&one, base, base_snapshot),
1297
        });
1298
    }
1299
    out
1300
}
1301
1302
/// One file's part of a diff, for `oxy diff --json`.
1303
#[derive(Clone, Debug)]
1304
pub struct FileDiff {
1305
    pub path: String,
1306
    /// `added`, `removed`, `modified`, `renamed`, `mode`, `replaced`.
1307
    pub kind: String,
1308
    pub hunks: Vec<DiffHunk>,
1309
    /// For renames, the previous path.
1310
    pub from: Option<String>,
1311
}
1312
1313
/// Lines inserted after `base_line` (0 = before the first line) and lines
1314
/// removed, with their base line numbers.
1315
#[derive(Clone, Debug, Default)]
1316
pub struct DiffHunk {
1317
    pub base_line: u32,
1318
    pub added: Vec<Vec<u8>>,
1319
    pub removed: Vec<(u32, Vec<u8>)>,
1320
}
1321
1322
impl Repo {
1323
    /// The content of `path` in a state: `heads`, or the working copy's base.
1324
    pub fn file_at(&self, path: &str, heads: Option<&[ChangeHash]>) -> Result<Vec<u8>> {
1325
        let snapshot = match heads {
1326
            Some(h) => self.load_state(h)?.materialize(),
1327
            None => {
1328
                let (_, wc) = self.working_copy()?;
1329
                self.load_state(&wc.deps)?.materialize()
1330
            }
1331
        };
1332
        let Some(f) = snapshot.files.get(path) else {
1333
            return fail(format!("{path} is not in that state"));
1334
        };
1335
        match &f.content {
1336
            FileContent::Dir => fail(format!("{path} is a directory")),
1337
            FileContent::Text { bytes, .. } => Ok(bytes.clone()),
1338
            FileContent::Opaque { blobs } => match blobs.first() {
1339
                Some(b) => self.read_blob(b),
1340
                None => Ok(vec![]),
1341
            },
1342
        }
1343
    }
1344
1345
    /// Restore `paths` (files or directories) to the working copy's base:
1346
    /// edits are undone, additions removed, removals put back. Returns the
1347
    /// number of paths touched.
1348
    pub fn discard(&self, paths: &[String]) -> Result<usize> {
1349
        let _wc = self.lock_working_copy()?;
1350
        let snap = self.snapshot_status("oxy discard")?;
1351
        let under = |p: &str| {
1352
            paths
1353
                .iter()
1354
                .any(|x| p == x || p.starts_with(&format!("{}/", x.trim_end_matches('/'))))
1355
        };
1356
        let attrs = Repo::state_attributes(&snap.base_snapshot);
1357
        let mut n = 0;
1358
        for s in &snap.statuses {
1359
            if !under(&s.path) {
1360
                continue;
1361
            }
1362
            match snap.base_snapshot.files.get(&s.path) {
1363
                None => {
1364
                    // Added (or the new name of a rename): remove it.
1365
                    let full = self.root.join(&s.path);
1366
                    if full.is_dir() {
1367
                        let _ = fs::remove_dir_all(&full);
1368
                    } else {
1369
                        let _ = fs::remove_file(&full);
1370
                    }
1371
                    n += 1;
1372
                }
1373
                Some(f) => {
1374
                    match &f.content {
1375
                        FileContent::Dir => fs::create_dir_all(self.root.join(&s.path))?,
1376
                        FileContent::Text { bytes, .. } => {
1377
                            let on_disk: std::borrow::Cow<[u8]> = if attrs.lookup(&s.path).eol
1378
                                == Some(crate::attributes::Eol::Crlf)
1379
                            {
1380
                                crate::attributes::to_crlf(bytes).into()
1381
                            } else {
1382
                                bytes.as_slice().into()
1383
                            };
1384
                            self.write_file(&s.path, &on_disk, f.mode.exec)?;
1385
                        }
1386
                        FileContent::Opaque { blobs } => {
1387
                            let bytes = match blobs.first() {
1388
                                Some(b) => self.read_blob(b)?,
1389
                                None => vec![],
1390
                            };
1391
                            if f.kind == NodeKind::Symlink {
1392
                                self.write_symlink(&s.path, &bytes)?;
1393
                            } else if f.kind == NodeKind::File {
1394
                                self.write_file(&s.path, &bytes, f.mode.exec)?;
1395
                            }
1396
                        }
1397
                    }
1398
                    n += 1;
1399
                }
1400
            }
1401
        }
1402
        // A rename's old name is not in the statuses; put it back too.
1403
        for (p, f) in &snap.base_snapshot.files {
1404
            if under(p)
1405
                && !self.root.join(p).exists()
1406
                && f.kind != NodeKind::Dir
1407
                && f.kind != NodeKind::Subrepo
1408
                && !snap.statuses.iter().any(|s| s.path == *p)
1409
            {
1410
                let bytes = match &f.content {
1411
                    FileContent::Text { bytes, .. } => bytes.clone(),
1412
                    FileContent::Opaque { blobs } => blobs
1413
                        .first()
1414
                        .map(|b| self.read_blob(b))
1415
                        .transpose()?
1416
                        .unwrap_or_default(),
1417
                    FileContent::Dir => continue,
1418
                };
1419
                if f.kind == NodeKind::Symlink {
1420
                    self.write_symlink(p, &bytes)?
1421
                } else {
1422
                    self.write_file(p, &bytes, f.mode.exec)?
1423
                }
1424
                n += 1;
1425
            }
1426
        }
1427
        self.drop_manifest();
1428
        Ok(n)
1429
    }
1430
1431
    /// Undo the working-copy hunks `indices` (as `hunks` numbers them) on
1432
    /// disk, keeping the others: the files are rewritten from the base plus
1433
    /// the remaining hunks.
1434
    pub fn discard_hunks(&self, indices: &[usize]) -> Result<usize> {
1435
        let _wc = self.lock_working_copy()?;
1436
        let (snap, hunks) = self.hunks()?;
1437
        let keep: Vec<usize> = hunks
1438
            .iter()
1439
            .map(|h| h.index)
1440
            .filter(|i| !indices.contains(i))
1441
            .collect();
1442
        let (ops, edits) = select_hunks(&snap.wc, &keep);
1443
        let dropped_nodes: BTreeSet<NodeId> = hunks
1444
            .iter()
1445
            .filter(|h| indices.contains(&h.index))
1446
            .map(|h| {
1447
                if h.index < snap.wc.tree_ops.len() {
1448
                    snap.wc.tree_ops[h.index].node()
1449
                } else {
1450
                    snap.wc.edits[h.index - snap.wc.tree_ops.len()].node()
1451
                }
1452
            })
1453
            .collect();
1454
        let mut partial = snap.wc.clone();
1455
        partial.tree_ops = ops;
1456
        partial.edits = edits;
1457
        partial.normalize();
1458
        let mut st = snap.base.clone();
1459
        st.add_unchecked(partial);
1460
        // Every file of the target is rendered: build the graphs the
1461
        // partial snapshot left out.
1462
        self.load_all_graphs(&mut st)?;
1463
        let target = st.materialize();
1464
        let by_node_target = target.tree.by_node();
1465
        let by_node_base = snap.base_snapshot.tree.by_node();
1466
        let attrs = Repo::state_attributes(&target);
1467
        let mut n = 0;
1468
        for node in dropped_nodes {
1469
            match by_node_target.get(&node) {
1470
                Some(e) => {
1471
                    let f = &target.files[&e.path];
1472
                    match &f.content {
1473
                        FileContent::Dir => {}
1474
                        FileContent::Text { bytes, .. } => {
1475
                            let on_disk: std::borrow::Cow<[u8]> = if attrs.lookup(&e.path).eol
1476
                                == Some(crate::attributes::Eol::Crlf)
1477
                            {
1478
                                crate::attributes::to_crlf(bytes).into()
1479
                            } else {
1480
                                bytes.as_slice().into()
1481
                            };
1482
                            self.write_file(&e.path, &on_disk, f.mode.exec)?;
1483
                        }
1484
                        FileContent::Opaque { blobs } => {
1485
                            let bytes = blobs
1486
                                .first()
1487
                                .map(|b| self.read_blob(b))
1488
                                .transpose()?
1489
                                .unwrap_or_default();
1490
                            if f.kind == NodeKind::Symlink {
1491
                                self.write_symlink(&e.path, &bytes)?
1492
                            } else {
1493
                                self.write_file(&e.path, &bytes, f.mode.exec)?
1494
                            }
1495
                        }
1496
                    }
1497
                    // A discarded rename: the new name goes.
1498
                    if let Some(old_path) = snap
1499
                        .statuses
1500
                        .iter()
1501
                        .find(|s| {
1502
                            s.status == ChangeStatus::Renamed && !target.files.contains_key(&s.path)
1503
                        })
1504
                        .map(|s| s.path.clone())
1505
                    {
1506
                        let _ = fs::remove_file(self.root.join(old_path));
1507
                    }
1508
                    n += 1;
1509
                }
1510
                None => {
1511
                    // The node exists in neither target nor base with a live path: an addition to remove.
1512
                    if let Some(added) = snap.statuses.iter().find(|s| {
1513
                        s.status == ChangeStatus::Added
1514
                            && !target.files.contains_key(&s.path)
1515
                            && !by_node_base.contains_key(&node)
1516
                    }) {
1517
                        let full = self.root.join(&added.path);
1518
                        if full.is_dir() {
1519
                            let _ = fs::remove_dir_all(&full);
1520
                        } else {
1521
                            let _ = fs::remove_file(&full);
1522
                        }
1523
                        n += 1;
1524
                    }
1525
                }
1526
            }
1527
        }
1528
        self.drop_manifest();
1529
        Ok(n)
1530
    }
1531
1532
    /// The diff of the working copy (`None`) or of a change, per file with
1533
    /// line-numbered hunks (spec: `oxy diff --json`).
1534
    pub fn diff_files(&self, change: Option<&ChangeHash>) -> Result<Vec<FileDiff>> {
1535
        let (c, base, base_snapshot) = match change {
1536
            Some(h) => {
1537
                let c = self.store.get_change(h)?;
1538
                let (base, snapshot) = self.change_base(&c)?;
1539
                (c, base, snapshot)
1540
            }
1541
            None => self.working_copy_with_base()?,
1542
        };
1543
        Ok(diff_files_of(&c, &base, &base_snapshot))
1544
    }
1545
1546
    /// The working-copy change with its base state and the base's
1547
    /// rendering, for showing what the working copy changes. While the
1548
    /// status cache holds (every file as the last snapshot left it), the
1549
    /// stored working-copy change is the answer and no snapshot is taken;
1550
    /// otherwise a snapshot makes it.
1551
    pub fn working_copy_with_base(&self) -> Result<(Change, State, Snapshot)> {
1552
        if self.status_by_manifest()?.is_some() {
1553
            let (_, wc) = self.working_copy()?;
1554
            let base = self.load_state_indexed(&wc.deps)?;
1555
            let (base, snapshot) = self.render_base_for(&wc, base)?;
1556
            return Ok((wc, base, snapshot));
1557
        }
1558
        let snap = self.snapshot_status("oxy diff")?;
1559
        Ok((snap.wc, snap.base, snap.base_snapshot))
1560
    }
1561
1562
    /// The log restricted to changes touching `path` (its node, so renames
1563
    /// are followed), on the current bookmark.
1564
    pub fn log_for_path(&self, path: &str) -> Result<Vec<LogEntry>> {
1565
        let heads = self.bookmark_heads()?;
1566
        if self.is_bare() {
1567
            return self.log_for_path_in(path, &heads);
1568
        }
1569
        let entries = self.log()?;
1570
        let (_, wc) = self.working_copy()?;
1571
        let base_snapshot = self.load_state(&wc.deps)?.materialize();
1572
        let state_snapshot = self.load_state(&heads)?.materialize();
1573
        let node = base_snapshot
1574
            .files
1575
            .get(path)
1576
            .or_else(|| state_snapshot.files.get(path))
1577
            .map(|f| f.node);
1578
        let Some(node) = node else {
1579
            return fail(format!("{path} is not tracked"));
1580
        };
1581
        Ok(self.entries_touching(entries, node))
1582
    }
1583
1584
    /// The log of the state with these heads restricted to changes touching
1585
    /// `path` (its node, so renames are followed).
1586
    pub fn log_for_path_in(&self, path: &str, heads: &[ChangeHash]) -> Result<Vec<LogEntry>> {
1587
        self.log_for_path_of(&self.load_state_history(heads)?, path, None)
1588
    }
1589
1590
    /// The changes of a loaded state touching `path`, newest first, at most
1591
    /// `limit` of them. The path is found in the state's tree alone, so no
1592
    /// file is rendered, and the walk stops once `limit` are found.
1593
    pub fn log_for_path_of(
1594
        &self,
1595
        state: &State,
1596
        path: &str,
1597
        limit: Option<usize>,
1598
    ) -> Result<Vec<LogEntry>> {
1599
        let Some(node) = state.tree().view().entries.get(path).map(|e| e.node) else {
1600
            return fail(format!("{path} is not in that state"));
1601
        };
1602
        Ok(self.entries_touching_up_to(self.log_of(state), node, limit))
1603
    }
1604
1605
    fn entries_touching(&self, entries: Vec<LogEntry>, node: NodeId) -> Vec<LogEntry> {
1606
        self.entries_touching_up_to(entries, node, None)
1607
    }
1608
1609
    fn entries_touching_up_to(
1610
        &self,
1611
        entries: Vec<LogEntry>,
1612
        node: NodeId,
1613
        limit: Option<usize>,
1614
    ) -> Vec<LogEntry> {
1615
        let mut out = Vec::new();
1616
        for e in entries {
1617
            if limit.is_some_and(|n| out.len() >= n) {
1618
                break;
1619
            }
1620
            let Ok(c) = self.store.get_change(&e.hash) else {
1621
                continue;
1622
            };
1623
            if c.tree_ops.iter().any(|o| o.node() == node)
1624
                || c.edits.iter().any(|x| x.node() == node)
1625
            {
1626
                out.push(e);
1627
            }
1628
        }
1629
        out
1630
    }
1631
}
1632
1633
/// Per-file hunks of `change` against `base`.
1634
pub fn diff_files_of(change: &Change, base: &State, base_snapshot: &Snapshot) -> Vec<FileDiff> {
1635
    let by_node = base_snapshot.tree.by_node();
1636
    let mut new_names: HashMap<NodeId, (NodeId, String, NodeKind)> = HashMap::new();
1637
    for op in &change.tree_ops {
1638
        if let TreeOp::AddNode {
1639
            node,
1640
            parent,
1641
            name,
1642
            kind,
1643
            ..
1644
        } = op
1645
        {
1646
            new_names.insert(*node, (*parent, name.clone(), *kind));
1647
        }
1648
    }
1649
    let path_of = |n: &NodeId| -> String {
1650
        path_of_node(n, &by_node, &new_names).unwrap_or_else(|| format!("<node {}>", n.short(8)))
1651
    };
1652
    let mut files: BTreeMap<NodeId, FileDiff> = BTreeMap::new();
1653
    let mut order: Vec<NodeId> = Vec::new();
1654
    let mut entry = |files: &mut BTreeMap<NodeId, FileDiff>, n: NodeId, kind: &str| {
1655
        if let std::collections::btree_map::Entry::Vacant(v) = files.entry(n) {
1656
            order.push(n);
1657
            v.insert(FileDiff {
1658
                path: path_of(&n),
1659
                kind: kind.to_string(),
1660
                hunks: vec![],
1661
                from: None,
1662
            });
1663
        }
1664
    };
1665
    for op in &change.tree_ops {
1666
        match op {
1667
            TreeOp::AddNode { node, kind, .. } => {
1668
                if *kind != NodeKind::Dir {
1669
                    entry(&mut files, *node, "added");
1670
                }
1671
            }
1672
            TreeOp::RemoveNode { node, .. } => {
1673
                entry(&mut files, *node, "removed");
1674
                if let Some(e) = by_node.get(node) {
1675
                    files.get_mut(node).unwrap().path = e.path.clone();
1676
                }
1677
            }
1678
            TreeOp::Move {
1679
                node, parent, name, ..
1680
            } => {
1681
                entry(&mut files, *node, "renamed");
1682
                let f = files.get_mut(node).unwrap();
1683
                f.from = by_node.get(node).map(|e| e.path.clone());
1684
                let dir = if parent.is_root() {
1685
                    String::new()
1686
                } else {
1687
                    path_of_node(parent, &by_node, &new_names).unwrap_or_default()
1688
                };
1689
                f.path = if dir.is_empty() {
1690
                    name.clone()
1691
                } else {
1692
                    format!("{dir}/{name}")
1693
                };
1694
            }
1695
            TreeOp::SetMode { node, .. } => entry(&mut files, *node, "mode"),
1696
        }
1697
    }
1698
    // Base line numbers per node, 1-based.
1699
    let mut line_of: HashMap<NodeId, HashMap<(ChangeHash, u32), u32>> = HashMap::new();
1700
    let mut lines_for = |n: &NodeId| -> HashMap<(ChangeHash, u32), u32> {
1701
        line_of
1702
            .entry(*n)
1703
            .or_insert_with(|| {
1704
                base.live_lines(n)
1705
                    .into_iter()
1706
                    .enumerate()
1707
                    .map(|(i, (k, _))| (k, i as u32 + 1))
1708
                    .collect()
1709
            })
1710
            .clone()
1711
    };
1712
    for e in &change.edits {
1713
        let n = e.node();
1714
        let is_new = new_names.contains_key(&n);
1715
        entry(&mut files, n, if is_new { "added" } else { "modified" });
1716
        let f = files.get_mut(&n).unwrap();
1717
        match e {
1718
            Edit::Insert { after, lines, .. } => {
1719
                let map = lines_for(&n);
1720
                let base_line = match after {
1721
                    AtomRef::Start => 0,
1722
                    AtomRef::End => map.len() as u32,
1723
                    AtomRef::Atom { change, index } if change.is_zero() => {
1724
                        f.hunks.last().map(|h| h.base_line).unwrap_or(0)
1725
                    }
1726
                    AtomRef::Atom { change, index } => {
1727
                        map.get(&(*change, *index)).copied().unwrap_or(0)
1728
                    }
1729
                };
1730
                f.hunks.push(DiffHunk {
1731
                    base_line,
1732
                    added: lines.to_vec(),
1733
                    removed: vec![],
1734
                });
1735
            }
1736
            Edit::Delete { atoms, .. } => {
1737
                let map = lines_for(&n);
1738
                let mut removed = Vec::new();
1739
                for r in atoms {
1740
                    for i in r.from..r.to {
1741
                        let line = map.get(&(r.change, i)).copied().unwrap_or(0);
1742
                        let text = base
1743
                            .file(&n)
1744
                            .and_then(|g| g.content(&(r.change, i)))
1745
                            .unwrap_or(b"")
1746
                            .to_vec();
1747
                        removed.push((line, text));
1748
                    }
1749
                }
1750
                let base_line = removed
1751
                    .first()
1752
                    .map(|(l, _)| l.saturating_sub(1))
1753
                    .unwrap_or(0);
1754
                f.hunks.push(DiffHunk {
1755
                    base_line,
1756
                    added: vec![],
1757
                    removed,
1758
                });
1759
            }
1760
            Edit::Replace { .. } => {
1761
                if !is_new {
1762
                    f.kind = "replaced".into();
1763
                }
1764
            }
1765
        }
1766
    }
1767
    order.into_iter().filter_map(|n| files.remove(&n)).collect()
1768
}
1769
1770
/// Builds the tree ops and edits of a working-copy change against a base.
1771
/// `BLAKE3("oxy node 1" 0 seed kind path)`, truncated: a node identifier
1772
/// that the same seed and path always give (never the root's).
1773
fn seeded_node(seed: &[u8; 32], path: &str, kind: NodeKind) -> NodeId {
1774
    let mut h = blake3::Hasher::new();
1775
    h.update(b"oxy node 1\0");
1776
    h.update(seed);
1777
    h.update(&[match kind {
1778
        NodeKind::File => 1,
1779
        NodeKind::Dir => 2,
1780
        NodeKind::Symlink => 3,
1781
        NodeKind::Subrepo => 4,
1782
    }]);
1783
    h.update(path.as_bytes());
1784
    let mut id = [0u8; 16];
1785
    id.copy_from_slice(&h.finalize().as_bytes()[..16]);
1786
    if id == [0; 16] {
1787
        id[15] = 1;
1788
    }
1789
    NodeId(id)
1790
}
1791
1792
struct ChangeBuilder<'a> {
1793
    base: &'a State,
1794
    base_snapshot: &'a Snapshot,
1795
    tree_ops: Vec<TreeOp>,
1796
    edits: Vec<Edit>,
1797
    statuses: Vec<PathStatus>,
1798
    dir_nodes: HashMap<String, NodeId>,
1799
    reuse: HashMap<String, (NodeId, NodeKind)>,
1800
    /// Changes that contributed to conflicts this working copy resolves.
1801
    contributors: BTreeSet<ChangeHash>,
1802
    resolves: bool,
1803
    attrs: crate::attributes::Attributes,
1804
    blobs: HashMap<String, ObjectRef>,
1805
    /// Opaque files whose replace conflict the content settles.
1806
    resolve: HashSet<String>,
1807
    /// When set, new nodes' identifiers derive from it and their paths.
1808
    node_seed: Option<[u8; 32]>,
1809
    /// For a Git import, the base's dead directories by where they were
1810
    /// (see `ensure_dir`), worked out when first needed.
1811
    dead_dirs: Option<HashMap<(NodeId, String), (NodeId, crate::tree::OpKey)>>,
1812
}
1813
1814
impl<'a> ChangeBuilder<'a> {
1815
    fn new(
1816
        base: &'a State,
1817
        base_snapshot: &'a Snapshot,
1818
        reuse: HashMap<String, (NodeId, NodeKind)>,
1819
    ) -> Self {
1820
        let mut dir_nodes: HashMap<String, NodeId> = HashMap::new();
1821
        dir_nodes.insert(String::new(), NodeId::ROOT);
1822
        for (p, e) in base_snapshot.tree.entries.iter() {
1823
            if e.kind == NodeKind::Dir {
1824
                dir_nodes.insert(p.clone(), e.node);
1825
            }
1826
        }
1827
        ChangeBuilder {
1828
            base,
1829
            base_snapshot,
1830
            tree_ops: vec![],
1831
            edits: vec![],
1832
            statuses: vec![],
1833
            dir_nodes,
1834
            reuse,
1835
            contributors: BTreeSet::new(),
1836
            resolves: false,
1837
            attrs: crate::attributes::Attributes::default(),
1838
            blobs: HashMap::new(),
1839
            resolve: HashSet::new(),
1840
            node_seed: None,
1841
            dead_dirs: None,
1842
        }
1843
    }
1844
1845
    fn with_attributes(mut self, attrs: crate::attributes::Attributes) -> Self {
1846
        self.attrs = attrs;
1847
        self
1848
    }
1849
1850
    /// Whether a file is opaque: forced by `binary`, forced text by `text`
1851
    /// only when it has no NUL bytes, else sniffed.
1852
    /// The blob for an opaque entry: the cached one, else stored now.
1853
    fn blob_of(
1854
        &mut self,
1855
        repo: &Repo,
1856
        path: &str,
1857
        e: &FsEntry,
1858
        nocompress: bool,
1859
    ) -> Result<ObjectRef> {
1860
        let b = match e.blob {
1861
            Some(b) => b,
1862
            None => repo.store_blob_for(&e.content, nocompress)?,
1863
        };
1864
        self.blobs.insert(path.to_string(), b);
1865
        Ok(b)
1866
    }
1867
1868
    fn opaque_for(&self, path: &str, e: &FsEntry) -> bool {
1869
        if e.blob.is_some() {
1870
            return true;
1871
        }
1872
        if e.kind == NodeKind::Symlink || e.kind == NodeKind::Subrepo {
1873
            return true;
1874
        }
1875
        match self.attrs.lookup(path).binary {
1876
            Some(true) => true,
1877
            Some(false) => is_binary(&e.content),
1878
            None => is_binary(&e.content),
1879
        }
1880
    }
1881
1882
    /// Text content as stored: `\r\n` normalized for `eol=` files.
1883
    fn stored_text(
1884
        &self,
1885
        path: &str,
1886
        content: &std::sync::Arc<Vec<u8>>,
1887
    ) -> std::sync::Arc<Vec<u8>> {
1888
        if self.attrs.lookup(path).eol.is_some() {
1889
            std::sync::Arc::new(crate::attributes::normalize_eol(content))
1890
        } else {
1891
            content.clone()
1892
        }
1893
    }
1894
1895
    /// The identifier of a node added at `path`: reused when asked, derived
1896
    /// from the seed when there is one, random otherwise.
1897
    fn new_node(&self, path: &str, kind: NodeKind) -> NodeId {
1898
        if let Some(n) = self.reused_node(path, kind) {
1899
            return n;
1900
        }
1901
        match &self.node_seed {
1902
            Some(seed) => seeded_node(seed, path, kind),
1903
            None => NodeId::random(),
1904
        }
1905
    }
1906
1907
    fn reused_node(&self, path: &str, kind: NodeKind) -> Option<NodeId> {
1908
        self.reuse
1909
            .get(path)
1910
            .filter(|(_, k)| *k == kind)
1911
            .map(|(n, _)| *n)
1912
    }
1913
1914
    /// A dead directory last placed at (`parent`, `name`) in the base.
1915
    fn revivable_dir(
1916
        &mut self,
1917
        parent: NodeId,
1918
        name: &str,
1919
    ) -> Option<(NodeId, crate::tree::OpKey)> {
1920
        let base = self.base;
1921
        self.dead_dirs
1922
            .get_or_insert_with(|| base.tree().dead_dirs())
1923
            .get(&(parent, name.to_string()))
1924
            .copied()
1925
    }
1926
1927
    fn ensure_dir(&mut self, path: &str) -> NodeId {
1928
        if let Some(n) = self.dir_nodes.get(path) {
1929
            return *n;
1930
        }
1931
        let mut parent = NodeId::ROOT;
1932
        let mut prefix = String::new();
1933
        for comp in path.split('/') {
1934
            if !prefix.is_empty() {
1935
                prefix.push('/');
1936
            }
1937
            prefix.push_str(comp);
1938
            let known = self.dir_nodes.get(&prefix).copied();
1939
            let revive = match known {
1940
                Some(_) => None,
1941
                None if self.node_seed.is_some() => self.revivable_dir(parent, comp),
1942
                None => None,
1943
            };
1944
            parent = match (known, revive) {
1945
                (Some(n), _) => n,
1946
                (None, Some((node, old))) => {
1947
                    // Git has no identity for a directory: one that comes
1948
                    // back where it was is the same directory, brought back
1949
                    // with a move, so lines of history that placed files in
1950
                    // it before and after agree (oxygen#30).
1951
                    self.tree_ops.push(TreeOp::Move {
1952
                        node,
1953
                        old: OpRef {
1954
                            change: old.0,
1955
                            index: old.1,
1956
                        },
1957
                        parent,
1958
                        name: comp.to_string(),
1959
                    });
1960
                    self.dir_nodes.insert(prefix.clone(), node);
1961
                    node
1962
                }
1963
                (None, None) => {
1964
                    let node = self.new_node(&prefix, NodeKind::Dir);
1965
                    self.tree_ops.push(TreeOp::AddNode {
1966
                        node,
1967
                        kind: NodeKind::Dir,
1968
                        mode: Mode::default(),
1969
                        parent,
1970
                        name: comp.to_string(),
1971
                    });
1972
                    self.dir_nodes.insert(prefix.clone(), node);
1973
                    node
1974
                }
1975
            };
1976
        }
1977
        parent
1978
    }
1979
1980
    fn add_path(&mut self, repo: &Repo, path: &str, e: &FsEntry) -> Result<()> {
1981
        let (dir, name) = split_path(path);
1982
        let parent = self.ensure_dir(dir);
1983
        let node = self.new_node(path, e.kind);
1984
        let opaque = self.opaque_for(path, e);
1985
        let nocompress = self.attrs.lookup(path).nocompress;
1986
        self.tree_ops.push(TreeOp::AddNode {
1987
            node,
1988
            kind: e.kind,
1989
            mode: Mode {
1990
                exec: e.exec,
1991
                opaque,
1992
            },
1993
            parent,
1994
            name: name.to_string(),
1995
        });
1996
        if opaque {
1997
            let blob = self.blob_of(repo, path, e, nocompress)?;
1998
            self.edits.push(Edit::Replace {
1999
                node,
2000
                old: None,
2001
                new: Some(blob),
2002
            });
2003
        } else if !e.content.is_empty() {
2004
            let content = self.stored_text(path, &e.content);
2005
            self.edits.push(Edit::Insert {
2006
                node,
2007
                after: crate::objects::AtomRef::Start,
2008
                before: crate::objects::AtomRef::End,
2009
                lines: crate::lines::Lines::split_shared(content),
2010
            });
2011
        }
2012
        self.statuses.push(PathStatus {
2013
            path: path.to_string(),
2014
            status: ChangeStatus::Added,
2015
        });
2016
        Ok(())
2017
    }
2018
2019
    /// Move the node at `old` to `new` and apply `e`'s content to it.
2020
    fn move_path(
2021
        &mut self,
2022
        repo: &Repo,
2023
        old: &str,
2024
        new: &str,
2025
        e: &FsEntry,
2026
        expected: &crate::state::FileState,
2027
    ) -> Result<()> {
2028
        let entry = &self.base_snapshot.tree.entries[old];
2029
        let (dir, name) = split_path(new);
2030
        let parent = self.ensure_dir(dir);
2031
        self.tree_ops.push(TreeOp::Move {
2032
            node: expected.node,
2033
            old: op_ref(entry.placement),
2034
            parent,
2035
            name: name.to_string(),
2036
        });
2037
        self.update_path(repo, old, e, expected)?;
2038
        // update_path reports under the old path; the rename is what the user sees.
2039
        self.statuses.retain(|s| s.path != old);
2040
        self.statuses.push(PathStatus {
2041
            path: new.to_string(),
2042
            status: ChangeStatus::Renamed,
2043
        });
2044
        Ok(())
2045
    }
2046
2047
    /// For a Git import: a node the commit keeps is in one place, the one
2048
    /// its tree names, so any other live placement it has in the base goes;
2049
    /// and a node the tree cannot show at all (an orphan) goes too. Such a
2050
    /// placement is out of sight, under a directory another line of history
2051
    /// removed, where no diff of the tree would ever reach it (oxygen#30).
2052
    fn retire_stray_placements(&mut self) {
2053
        let mut retired: HashSet<(ChangeHash, u32)> = HashSet::new();
2054
        let mut placed: BTreeSet<NodeId> = BTreeSet::new();
2055
        for op in &self.tree_ops {
2056
            match op {
2057
                TreeOp::Move { node, old, .. } => {
2058
                    retired.insert((old.change, old.index));
2059
                    placed.insert(*node);
2060
                }
2061
                TreeOp::RemoveNode { placement, .. } => {
2062
                    retired.insert((placement.change, placement.index));
2063
                }
2064
                TreeOp::AddNode { .. } | TreeOp::SetMode { .. } => {}
2065
            }
2066
        }
2067
        // Nodes kept where they were: what the base's tree view shows and
2068
        // this change neither moves nor removes.
2069
        let mut kept: HashMap<NodeId, (ChangeHash, u32)> = HashMap::new();
2070
        for e in self.base_snapshot.tree.entries.values() {
2071
            if !retired.contains(&e.placement) {
2072
                kept.insert(e.node, e.placement);
2073
            }
2074
        }
2075
        // Only a node with several live placements can have a stray one,
2076
        // and the tree view names each as a conflict.
2077
        let multi: BTreeSet<NodeId> = self
2078
            .base_snapshot
2079
            .tree
2080
            .conflicts
2081
            .iter()
2082
            .filter_map(|c| match c {
2083
                crate::tree::TreeConflict::MultiPlacement { node, .. } => Some(*node),
2084
                _ => None,
2085
            })
2086
            .collect();
2087
        let mut extra = Vec::new();
2088
        // A node whose only placements are under a directory another line
2089
        // removed (an orphan) is nowhere the tree can show, and Git's tree
2090
        // has no such path: it goes.
2091
        for c in &self.base_snapshot.tree.conflicts {
2092
            let crate::tree::TreeConflict::Orphan { node, .. } = c else {
2093
                continue;
2094
            };
2095
            if kept.contains_key(node) || placed.contains(node) {
2096
                continue;
2097
            }
2098
            for (k, _) in self.base.tree().live_placements(node) {
2099
                if retired.insert(k) {
2100
                    extra.push(TreeOp::RemoveNode {
2101
                        node: *node,
2102
                        placement: op_ref(k),
2103
                    });
2104
                }
2105
            }
2106
        }
2107
        for node in placed
2108
            .iter()
2109
            .chain(multi.iter().filter(|n| kept.contains_key(*n)))
2110
        {
2111
            for (k, _) in self.base.tree().live_placements(node) {
2112
                if retired.contains(&k) || kept.get(node) == Some(&k) {
2113
                    continue;
2114
                }
2115
                retired.insert(k);
2116
                extra.push(TreeOp::RemoveNode {
2117
                    node: *node,
2118
                    placement: op_ref(k),
2119
                });
2120
            }
2121
        }
2122
        if !extra.is_empty() {
2123
            self.resolves = true;
2124
            self.tree_ops.extend(extra);
2125
        }
2126
    }
2127
2128
    fn remove_path(&mut self, path: &str, expected: &crate::state::FileState) {
2129
        let entry = &self.base_snapshot.tree.entries[path];
2130
        self.tree_ops.push(TreeOp::RemoveNode {
2131
            node: expected.node,
2132
            placement: op_ref(entry.placement),
2133
        });
2134
        if path.contains(".oxy-conflict-") || expected.is_conflicted() {
2135
            self.resolves = true;
2136
        }
2137
        self.statuses.push(PathStatus {
2138
            path: path.to_string(),
2139
            status: ChangeStatus::Removed,
2140
        });
2141
    }
2142
2143
    fn update_path(
2144
        &mut self,
2145
        repo: &Repo,
2146
        path: &str,
2147
        e: &FsEntry,
2148
        expected: &crate::state::FileState,
2149
    ) -> Result<()> {
2150
        if expected.kind != e.kind {
2151
            self.remove_path(path, expected);
2152
            self.statuses.pop();
2153
            self.add_path(repo, path, e)?;
2154
            self.statuses.pop();
2155
            self.statuses.push(PathStatus {
2156
                path: path.to_string(),
2157
                status: ChangeStatus::Modified,
2158
            });
2159
            return Ok(());
2160
        }
2161
        let entry = &self.base_snapshot.tree.entries[path];
2162
        let node = expected.node;
2163
        let mode_atom = entry.mode_atom.map(op_ref);
2164
        if e.unchanged {
2165
            // Known equal to the base's unconflicted rendering (spec
2166
            // §12.3); only the executable bit can differ.
2167
            if e.exec != expected.mode.exec {
2168
                if let Some(old) = mode_atom {
2169
                    self.tree_ops.push(TreeOp::SetMode {
2170
                        node,
2171
                        old,
2172
                        mode: Mode {
2173
                            exec: e.exec,
2174
                            opaque: false,
2175
                        },
2176
                    });
2177
                    self.statuses.push(PathStatus {
2178
                        path: path.to_string(),
2179
                        status: ChangeStatus::ModeChanged,
2180
                    });
2181
                }
2182
            }
2183
            return Ok(());
2184
        }
2185
        let mut status: Option<ChangeStatus> = None;
2186
        let wants_opaque = self.opaque_for(path, e);
2187
        let nocompress = self.attrs.lookup(path).nocompress;
2188
        let disk_text = self.stored_text(path, &e.content);
2189
        match &expected.content {
2190
            FileContent::Dir => {}
2191
            FileContent::Text {
2192
                bytes,
2193
                materialized,
2194
            } => {
2195
                if materialized.is_conflicted() {
2196
                    if bytes == &*disk_text {
2197
                        return Ok(());
2198
                    }
2199
                    if has_conflict_markers(&e.content) {
2200
                        self.statuses.push(PathStatus {
2201
                            path: path.to_string(),
2202
                            status: ChangeStatus::ConflictEdited,
2203
                        });
2204
                        return Ok(());
2205
                    }
2206
                    // Resolution (spec §9.6): diff against the unconflicted lines
2207
                    // with each region as a gap, then retire every region atom.
2208
                    // Whatever the author kept from a region is re-inserted as
2209
                    // new atoms, which leaves the graph totally ordered.
2210
                    let regions = self.base.conflict_regions(&node);
2211
                    let mut edits = text_edits(node, &regions.plain, &disk_text);
2212
                    if !regions.region_atoms.is_empty() {
2213
                        edits.insert(
2214
                            0,
2215
                            Edit::Delete {
2216
                                node,
2217
                                atoms: ranges(&regions.region_atoms),
2218
                            },
2219
                        );
2220
                    }
2221
                    self.edits.extend(edits);
2222
                    self.contributors.extend(regions.contributors);
2223
                    self.resolves = true;
2224
                    if e.exec != expected.mode.exec {
2225
                        if let Some(old) = mode_atom {
2226
                            self.tree_ops.push(TreeOp::SetMode {
2227
                                node,
2228
                                old,
2229
                                mode: Mode {
2230
                                    exec: e.exec,
2231
                                    opaque: false,
2232
                                },
2233
                            });
2234
                        }
2235
                    }
2236
                    self.statuses.push(PathStatus {
2237
                        path: path.to_string(),
2238
                        status: ChangeStatus::Resolved,
2239
                    });
2240
                    return Ok(());
2241
                }
2242
                if wants_opaque {
2243
                    // Text → opaque (spec §7.5), by content or by attribute.
2244
                    if let Some(old) = mode_atom {
2245
                        self.tree_ops.push(TreeOp::SetMode {
2246
                            node,
2247
                            old,
2248
                            mode: Mode {
2249
                                exec: e.exec,
2250
                                opaque: true,
2251
                            },
2252
                        });
2253
                    }
2254
                    let live: Vec<_> = repo_live_keys(self.base, &node);
2255
                    if !live.is_empty() {
2256
                        self.edits.push(Edit::Delete {
2257
                            node,
2258
                            atoms: ranges(&live),
2259
                        });
2260
                    }
2261
                    let blob = self.blob_of(repo, path, e, nocompress)?;
2262
                    self.edits.push(Edit::Replace {
2263
                        node,
2264
                        old: None,
2265
                        new: Some(blob),
2266
                    });
2267
                    status = Some(ChangeStatus::Modified);
2268
                } else if bytes != &*disk_text {
2269
                    let mut laps = crate::timing::Laps::start();
2270
                    // The base's rendering holds its live atoms in order,
2271
                    // one per line (it is not conflicted here).
2272
                    let keys = materialized.live_atoms();
2273
                    let lines = crate::diff::split_lines(bytes);
2274
                    let edits = if keys.len() == lines.len() {
2275
                        crate::diff::text_edits_of(node, &keys, &lines, &disk_text)
2276
                    } else {
2277
                        text_edits(node, &self.base.live_lines(&node), &disk_text)
2278
                    };
2279
                    laps.lap("build: text diff");
2280
                    if !edits.is_empty() {
2281
                        self.edits.extend(edits);
2282
                        status = Some(ChangeStatus::Modified);
2283
                    }
2284
                }
2285
                let switched_to_opaque = wants_opaque;
2286
                if !switched_to_opaque && e.exec != expected.mode.exec {
2287
                    if let Some(old) = mode_atom {
2288
                        self.tree_ops.push(TreeOp::SetMode {
2289
                            node,
2290
                            old,
2291
                            mode: Mode {
2292
                                exec: e.exec,
2293
                                opaque: false,
2294
                            },
2295
                        });
2296
                        status.get_or_insert(ChangeStatus::ModeChanged);
2297
                    }
2298
                }
2299
            }
2300
            FileContent::Opaque { blobs } => {
2301
                let new_ref = e.blob.unwrap_or_else(|| Repo::blob_ref(&e.content));
2302
                if e.kind == NodeKind::File && wants_opaque {
2303
                    // Unchanged or replaced, the file stays opaque: remember its blob.
2304
                    self.blobs.insert(path.to_string(), new_ref);
2305
                }
2306
                if blobs.len() > 1 && self.resolve.contains(path) && e.kind == expected.kind {
2307
                    // Settle the replace conflict (spec §9.3): replace every
2308
                    // live candidate with the chosen blob, depending on each
2309
                    // change that made one live, so all are superseded.
2310
                    let chosen = self.blob_of(repo, path, e, nocompress)?;
2311
                    for b in blobs {
2312
                        self.edits.push(Edit::Replace {
2313
                            node,
2314
                            old: Some(*b),
2315
                            new: Some(chosen),
2316
                        });
2317
                    }
2318
                    self.contributors
2319
                        .extend(self.base.blob_contributors(&node, blobs));
2320
                    self.resolves = true;
2321
                    self.statuses.push(PathStatus {
2322
                        path: path.to_string(),
2323
                        status: ChangeStatus::Resolved,
2324
                    });
2325
                    return Ok(());
2326
                }
2327
                if blobs.len() > 1 {
2328
                    if !blobs.contains(&new_ref) {
2329
                        self.statuses.push(PathStatus {
2330
                            path: path.to_string(),
2331
                            status: ChangeStatus::ConflictEdited,
2332
                        });
2333
                    }
2334
                    return Ok(());
2335
                }
2336
                let current = blobs.first().copied();
2337
                if current != Some(new_ref) {
2338
                    if e.kind == NodeKind::File && !wants_opaque {
2339
                        // Opaque → text (spec §7.5).
2340
                        if let Some(old) = mode_atom {
2341
                            self.tree_ops.push(TreeOp::SetMode {
2342
                                node,
2343
                                old,
2344
                                mode: Mode {
2345
                                    exec: e.exec,
2346
                                    opaque: false,
2347
                                },
2348
                            });
2349
                        }
2350
                        self.edits.push(Edit::Replace {
2351
                            node,
2352
                            old: current,
2353
                            new: None,
2354
                        });
2355
                        if !e.content.is_empty() {
2356
                            self.edits.push(Edit::Insert {
2357
                                node,
2358
                                after: crate::objects::AtomRef::Start,
2359
                                before: crate::objects::AtomRef::End,
2360
                                lines: crate::lines::Lines::split(&e.content),
2361
                            });
2362
                        }
2363
                    } else {
2364
                        let blob = self.blob_of(repo, path, e, nocompress)?;
2365
                        self.edits.push(Edit::Replace {
2366
                            node,
2367
                            old: current,
2368
                            new: Some(blob),
2369
                        });
2370
                    }
2371
                    status = Some(ChangeStatus::Modified);
2372
                } else if e.kind == NodeKind::File && e.exec != expected.mode.exec {
2373
                    if let Some(old) = mode_atom {
2374
                        self.tree_ops.push(TreeOp::SetMode {
2375
                            node,
2376
                            old,
2377
                            mode: Mode {
2378
                                exec: e.exec,
2379
                                opaque: true,
2380
                            },
2381
                        });
2382
                        status = Some(ChangeStatus::ModeChanged);
2383
                    }
2384
                }
2385
            }
2386
        }
2387
        if let Some(s) = status {
2388
            self.statuses.push(PathStatus {
2389
                path: path.to_string(),
2390
                status: s,
2391
            });
2392
        }
2393
        Ok(())
2394
    }
2395
}
2396
2397
fn repo_live_keys(base: &State, node: &NodeId) -> Vec<crate::graph::AtomKey> {
2398
    base.live_lines(node).into_iter().map(|(k, _)| k).collect()
2399
}
2400
2401
/// The changes a change's scope references (spec §8.1): introducers of every
2402
/// atom, placement, and mode it touches, and of every node it operates on.
2403
pub fn referenced_changes(change: &Change, base: &State) -> BTreeSet<ChangeHash> {
2404
    let mut out = BTreeSet::new();
2405
    let opref = |r: &OpRef, out: &mut BTreeSet<ChangeHash>| {
2406
        if !r.change.is_zero() {
2407
            out.insert(r.change);
2408
        }
2409
    };
2410
    let mut nodes: Vec<NodeId> = Vec::new();
2411
    for op in &change.tree_ops {
2412
        match op {
2413
            TreeOp::AddNode { parent, .. } => nodes.push(*parent),
2414
            TreeOp::RemoveNode { node, placement } => {
2415
                nodes.push(*node);
2416
                opref(placement, &mut out);
2417
            }
2418
            TreeOp::Move {
2419
                node, old, parent, ..
2420
            } => {
2421
                nodes.push(*node);
2422
                nodes.push(*parent);
2423
                opref(old, &mut out);
2424
            }
2425
            TreeOp::SetMode { node, old, .. } => {
2426
                nodes.push(*node);
2427
                opref(old, &mut out);
2428
            }
2429
        }
2430
    }
2431
    for e in &change.edits {
2432
        nodes.push(e.node());
2433
        match e {
2434
            Edit::Insert { after, before, .. } => {
2435
                for r in [after, before] {
2436
                    if let crate::objects::AtomRef::Atom { change, .. } = r {
2437
                        if !change.is_zero() {
2438
                            out.insert(*change);
2439
                        }
2440
                    }
2441
                }
2442
            }
2443
            Edit::Delete { atoms, .. } => {
2444
                // Deleting an atom also depends on whoever inserted the live
2445
                // atoms right after it: the author saw those insertions, and
2446
                // without the dependency spec §9.1 would call the deletion
2447
                // concurrent with them (a delete/insert conflict).
2448
                let graph = base.file(&e.node());
2449
                for r in atoms {
2450
                    if !r.change.is_zero() {
2451
                        out.insert(r.change);
2452
                    }
2453
                    if let Some(g) = graph {
2454
                        for i in r.from..r.to {
2455
                            out.extend(
2456
                                g.live_successor_changes(&(r.change, i))
2457
                                    .into_iter()
2458
                                    .filter(|c| !c.is_zero()),
2459
                            );
2460
                        }
2461
                    }
2462
                }
2463
            }
2464
            // Replacing a blob depends on the change that made it current,
2465
            // as deleting a line depends on the line's introducer.
2466
            Edit::Replace {
2467
                node,
2468
                old: Some(old),
2469
                ..
2470
            } => {
2471
                out.extend(
2472
                    base.live_replaces(node)
2473
                        .into_iter()
2474
                        .filter(|(c, b)| b == old && !c.is_zero())
2475
                        .map(|(c, _)| c),
2476
                );
2477
            }
2478
            Edit::Replace { .. } => {}
2479
        }
2480
    }
2481
    for n in nodes {
2482
        if let Some(h) = base.tree().introducer(&n) {
2483
            out.insert(h);
2484
        }
2485
    }
2486
    out
2487
}
2488
2489
/// Paths of the nodes a change adds on top of `base_snapshot`.
2490
pub fn added_node_paths(
2491
    change: &Change,
2492
    base_snapshot: &Snapshot,
2493
) -> HashMap<String, (NodeId, NodeKind)> {
2494
    let by_node = base_snapshot.tree.by_node();
2495
    let mut new_names: HashMap<NodeId, (NodeId, String, NodeKind)> = HashMap::new();
2496
    for op in &change.tree_ops {
2497
        if let TreeOp::AddNode {
2498
            node,
2499
            parent,
2500
            name,
2501
            kind,
2502
            ..
2503
        } = op
2504
        {
2505
            new_names.insert(*node, (*parent, name.clone(), *kind));
2506
        }
2507
    }
2508
    let mut out = HashMap::new();
2509
    for (node, (_, _, kind)) in &new_names {
2510
        if let Some(path) = path_of_node(node, &by_node, &new_names) {
2511
            out.insert(path, (*node, *kind));
2512
        }
2513
    }
2514
    out
2515
}
2516
2517
fn path_of_node(
2518
    n: &NodeId,
2519
    by_node: &HashMap<NodeId, &crate::tree::TreeEntry>,
2520
    new_names: &HashMap<NodeId, (NodeId, String, NodeKind)>,
2521
) -> Option<String> {
2522
    if let Some(e) = by_node.get(n) {
2523
        return Some(e.path.clone());
2524
    }
2525
    let mut parts = Vec::new();
2526
    let mut cur = *n;
2527
    loop {
2528
        if cur.is_root() {
2529
            break;
2530
        }
2531
        if let Some(e) = by_node.get(&cur) {
2532
            if !e.path.is_empty() {
2533
                parts.push(e.path.clone());
2534
            }
2535
            break;
2536
        }
2537
        let (parent, name, _) = new_names.get(&cur)?;
2538
        parts.push(name.clone());
2539
        cur = *parent;
2540
    }
2541
    parts.reverse();
2542
    Some(parts.join("/"))
2543
}
2544
2545
/// Render a change's operations with line content, using `base` for deleted lines.
2546
pub fn render_change(change: &Change, base: &State, base_snapshot: &Snapshot) -> String {
2547
    let by_node = base_snapshot.tree.by_node();
2548
    let mut new_names: HashMap<NodeId, (NodeId, String, NodeKind)> = HashMap::new();
2549
    for op in &change.tree_ops {
2550
        if let TreeOp::AddNode {
2551
            node,
2552
            parent,
2553
            name,
2554
            kind,
2555
            ..
2556
        } = op
2557
        {
2558
            new_names.insert(*node, (*parent, name.clone(), *kind));
2559
        }
2560
    }
2561
    let path_of = |n: &NodeId| -> String {
2562
        path_of_node(n, &by_node, &new_names).unwrap_or_else(|| format!("<node {}>", n.short(8)))
2563
    };
2564
2565
    let mut out = String::new();
2566
    for op in &change.tree_ops {
2567
        match op {
2568
            TreeOp::AddNode {
2569
                node, kind, mode, ..
2570
            } => {
2571
                out.push_str(&format!(
2572
                    "A {} ({:?}{}{})\n",
2573
                    path_of(node),
2574
                    kind,
2575
                    if mode.exec { ", exec" } else { "" },
2576
                    if mode.opaque { ", opaque" } else { "" }
2577
                ));
2578
            }
2579
            TreeOp::RemoveNode { node, .. } => out.push_str(&format!("D {}\n", path_of(node))),
2580
            TreeOp::Move { node, name, .. } => {
2581
                out.push_str(&format!("R {} -> {}\n", path_of(node), name))
2582
            }
2583
            TreeOp::SetMode { node, mode, .. } => {
2584
                out.push_str(&format!(
2585
                    "M {} mode: exec={} opaque={}\n",
2586
                    path_of(node),
2587
                    mode.exec,
2588
                    mode.opaque
2589
                ));
2590
            }
2591
        }
2592
    }
2593
    let mut last_node: Option<NodeId> = None;
2594
    for e in &change.edits {
2595
        let n = e.node();
2596
        if last_node != Some(n) {
2597
            out.push_str(&format!("--- {}\n", path_of(&n)));
2598
            last_node = Some(n);
2599
        }
2600
        match e {
2601
            Edit::Insert { lines, .. } => {
2602
                for l in lines.iter() {
2603
                    out.push('+');
2604
                    out.push_str(&String::from_utf8_lossy(l));
2605
                    if !l.ends_with(b"\n") {
2606
                        out.push('\n');
2607
                    }
2608
                }
2609
            }
2610
            Edit::Delete { atoms, .. } => {
2611
                for r in atoms {
2612
                    for i in r.from..r.to {
2613
                        let content = base
2614
                            .file(&n)
2615
                            .and_then(|g| g.content(&(r.change, i)))
2616
                            .unwrap_or(b"<unknown>\n");
2617
                        out.push('-');
2618
                        out.push_str(&String::from_utf8_lossy(content));
2619
                        if !content.ends_with(b"\n") {
2620
                            out.push('\n');
2621
                        }
2622
                    }
2623
                }
2624
            }
2625
            Edit::Replace { old, new, .. } => {
2626
                out.push_str(&format!(
2627
                    "  opaque content {} -> {}\n",
2628
                    old.map(|o| o.short(12)).unwrap_or_else(|| "none".into()),
2629
                    new.map(|o| o.short(12)).unwrap_or_else(|| "none".into())
2630
                ));
2631
            }
2632
        }
2633
    }
2634
    out
2635
}
2636
2637
/// Pair removed files with added files of the same kind whose contents are
2638
/// at least `RENAME_THRESHOLD` percent alike, best matches first. Beyond
2639
/// `RENAME_LIMIT` candidate pairs only identical contents are paired.
2640
const RENAME_THRESHOLD: u32 = 50;
2641
const RENAME_LIMIT: usize = 10_000;
2642
2643
/// How a change is built beyond its entries: for a Git import, the seed
2644
/// its new nodes' identifiers derive from; and, when it is built from part
2645
/// of the tree, whether the new tree has anything under a directory.
2646
#[derive(Default)]
2647
struct Scope<'a> {
2648
    seed: Option<[u8; 32]>,
2649
    dir_needed: Option<&'a dyn Fn(&str) -> bool>,
2650
}
2651
2652
fn detect_renames(
2653
    base_snapshot: &Snapshot,
2654
    fs_entries: &BTreeMap<String, FsEntry>,
2655
    in_scope: impl Fn(&str) -> bool,
2656
) -> Vec<(String, String)> {
2657
    let removed: Vec<(&String, &crate::state::FileState)> = base_snapshot
2658
        .files
2659
        .iter()
2660
        .filter(|(p, f)| {
2661
            f.kind != NodeKind::Dir
2662
                && !fs_entries.contains_key(*p)
2663
                && in_scope(p)
2664
                && !f.is_conflicted()
2665
        })
2666
        .collect();
2667
    let added: Vec<(&String, &FsEntry)> = fs_entries
2668
        .iter()
2669
        .filter(|(p, e)| e.kind != NodeKind::Dir && !base_snapshot.files.contains_key(*p))
2670
        .collect();
2671
    if removed.is_empty() || added.is_empty() {
2672
        return vec![];
2673
    }
2674
    let exact_only = removed.len() * added.len() > RENAME_LIMIT;
2675
    let old_content = |f: &crate::state::FileState| -> Option<Vec<u8>> {
2676
        match &f.content {
2677
            FileContent::Text { bytes, .. } => Some(bytes.clone()),
2678
            _ => None,
2679
        }
2680
    };
2681
    let mut scored: Vec<(u32, usize, usize)> = Vec::new();
2682
    for (ri, (_, f)) in removed.iter().enumerate() {
2683
        let old = old_content(f);
2684
        let old_blob = match &f.content {
2685
            FileContent::Opaque { blobs } if blobs.len() == 1 => Some(blobs[0]),
2686
            _ => None,
2687
        };
2688
        for (ai, (_, e)) in added.iter().enumerate() {
2689
            if e.kind != f.kind {
2690
                continue;
2691
            }
2692
            let score = match (&old, old_blob) {
2693
                (Some(o), _) => {
2694
                    if exact_only {
2695
                        if *o == *e.content {
2696
                            100
2697
                        } else {
2698
                            0
2699
                        }
2700
                    } else {
2701
                        similarity(o, &e.content)
2702
                    }
2703
                }
2704
                (None, Some(b)) if e.blob.unwrap_or_else(|| Repo::blob_ref(&e.content)) == b => 100,
2705
                _ => 0,
2706
            };
2707
            if score >= RENAME_THRESHOLD {
2708
                scored.push((score, ri, ai));
2709
            }
2710
        }
2711
    }
2712
    scored.sort_by(|a, b| {
2713
        b.0.cmp(&a.0)
2714
            .then(removed[a.1].0.cmp(removed[b.1].0))
2715
            .then(added[a.2].0.cmp(added[b.2].0))
2716
    });
2717
    let mut used_r = vec![false; removed.len()];
2718
    let mut used_a = vec![false; added.len()];
2719
    let mut out = Vec::new();
2720
    for (_, ri, ai) in scored {
2721
        if used_r[ri] || used_a[ai] {
2722
            continue;
2723
        }
2724
        used_r[ri] = true;
2725
        used_a[ai] = true;
2726
        out.push((removed[ri].0.clone(), added[ai].0.clone()));
2727
    }
2728
    out
2729
}
2730
2731
/// Percentage of the larger file's bytes found in lines the two share
2732
/// (multiset intersection of lines), like Git's similarity index.
2733
pub fn similarity(a: &[u8], b: &[u8]) -> u32 {
2734
    if a == b {
2735
        return 100;
2736
    }
2737
    if a.is_empty() || b.is_empty() {
2738
        return 0;
2739
    }
2740
    let mut counts: HashMap<&[u8], usize> = HashMap::new();
2741
    for l in split_lines(a) {
2742
        *counts.entry(l).or_default() += 1;
2743
    }
2744
    let mut shared = 0usize;
2745
    for l in split_lines(b) {
2746
        if let Some(n) = counts.get_mut(l) {
2747
            if *n > 0 {
2748
                *n -= 1;
2749
                shared += l.len();
2750
            }
2751
        }
2752
    }
2753
    (shared * 100 / a.len().max(b.len())) as u32
2754
}
2755
2756
/// Two maps side by side in key order: each key of either, with its value
2757
/// in each. Linear, with no lookups, for maps of a whole tree.
2758
fn join<'a, A, B>(
2759
    a: &'a BTreeMap<String, A>,
2760
    b: &'a BTreeMap<String, B>,
2761
) -> impl Iterator<Item = (&'a String, Option<&'a A>, Option<&'a B>)> {
2762
    let (mut a, mut b) = (a.iter().peekable(), b.iter().peekable());
2763
    std::iter::from_fn(move || match (a.peek(), b.peek()) {
2764
        (None, None) => None,
2765
        (Some(_), None) => a.next().map(|(k, v)| (k, Some(v), None)),
2766
        (None, Some(_)) => b.next().map(|(k, v)| (k, None, Some(v))),
2767
        (Some((ka, _)), Some((kb, _))) => match ka.cmp(kb) {
2768
            std::cmp::Ordering::Less => a.next().map(|(k, v)| (k, Some(v), None)),
2769
            std::cmp::Ordering::Greater => b.next().map(|(k, v)| (k, None, Some(v))),
2770
            std::cmp::Ordering::Equal => {
2771
                let (k, va) = a.next()?;
2772
                let (_, vb) = b.next()?;
2773
                Some((k, Some(va), Some(vb)))
2774
            }
2775
        },
2776
    })
2777
}
2778
2779
#[cfg(test)]
2780
mod join_tests {
2781
    use super::*;
2782
2783
    #[test]
2784
    fn join_pairs_every_key_in_order() {
2785
        let a: BTreeMap<String, u8> = [("a", 1), ("b/c", 2), ("d", 3)]
2786
            .into_iter()
2787
            .map(|(k, v)| (k.to_string(), v))
2788
            .collect();
2789
        let b: BTreeMap<String, char> = [("b", 'x'), ("b/c", 'y'), ("e", 'z')]
2790
            .into_iter()
2791
            .map(|(k, v)| (k.to_string(), v))
2792
            .collect();
2793
        let got: Vec<(String, Option<u8>, Option<char>)> = join(&a, &b)
2794
            .map(|(k, x, y)| (k.clone(), x.copied(), y.copied()))
2795
            .collect();
2796
        let want = vec![
2797
            ("a".to_string(), Some(1), None),
2798
            ("b".to_string(), None, Some('x')),
2799
            ("b/c".to_string(), Some(2), Some('y')),
2800
            ("d".to_string(), Some(3), None),
2801
            ("e".to_string(), None, Some('z')),
2802
        ];
2803
        assert_eq!(got, want);
2804
    }
2805
}