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