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