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