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