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