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