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