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