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