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