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