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