OXYGENHUB
◆ paths-for-resolutions-and-amend oxygen / crates / oxy-core / src / repo / tests.rs
359.8 KiB · Rust · last changed The same file added on both sides, identically, is one file 17 days ago source blame history raw
1
//! Tests for the repository layer.
2
3
use super::*;
4
use crate::protocol::SignedPolicy;
5
use crate::repo::{BisectStep, Selection};
6
7
/// Point `$OXY_HOME` at a throwaway directory once per test process so no
8
/// test reads or writes the developer's real user configuration or keys.
9
fn hermetic() {
10
    static ONCE: std::sync::Once = std::sync::Once::new();
11
    static DIR: std::sync::OnceLock<tempfile::TempDir> = std::sync::OnceLock::new();
12
    ONCE.call_once(|| {
13
        let d = tempfile::tempdir().unwrap();
14
        std::env::set_var("OXY_HOME", d.path());
15
        DIR.set(d).ok();
16
    });
17
}
18
19
fn write(root: &Path, rel: &str, content: &[u8]) {
20
    let p = root.join(rel);
21
    fs::create_dir_all(p.parent().unwrap()).unwrap();
22
    fs::write(p, content).unwrap();
23
}
24
25
fn statuses(s: &SnapshotResult) -> Vec<(String, ChangeStatus)> {
26
    s.statuses
27
        .iter()
28
        .map(|p| (p.path.clone(), p.status))
29
        .collect()
30
}
31
32
#[test]
33
fn init_snapshot_commit_log_undo() {
34
    hermetic();
35
    let dir = tempfile::tempdir().unwrap();
36
    let root = dir.path();
37
    let repo = Repo::init(root).unwrap();
38
    assert!(Repo::init(root).is_err());
39
    let ops = repo.op_log().unwrap();
40
    assert_eq!(ops.len(), 1);
41
    assert_eq!(ops[0].1.command, "oxy init");
42
43
    // Empty working copy: snapshot records no operation (spec §12.3).
44
    let s = repo.snapshot("oxy status").unwrap();
45
    assert!(!s.changed);
46
    assert_eq!(repo.op_log().unwrap().len(), 1);
47
48
    write(root, "src/main.rs", b"fn main() {}\n");
49
    write(root, "README.md", b"# Hello\n");
50
    write(root, ".oxyignore", b"/target\n");
51
    write(root, "target/junk.o", b"\0\0\0");
52
    let s = repo.snapshot("oxy status").unwrap();
53
    assert!(s.changed);
54
    assert_eq!(
55
        statuses(&s),
56
        vec![
57
            (".oxyignore".into(), ChangeStatus::Added),
58
            ("README.md".into(), ChangeStatus::Added),
59
            ("src/main.rs".into(), ChangeStatus::Added),
60
        ]
61
    );
62
    assert_eq!(repo.op_log().unwrap().len(), 2);
63
    // Snapshotting again with nothing changed records no op.
64
    let s2 = repo.snapshot("oxy status").unwrap();
65
    assert!(!s2.changed);
66
    assert_eq!(s2.wc_hash, s.wc_hash);
67
    assert_eq!(repo.op_log().unwrap().len(), 2);
68
69
    let h1 = repo.commit("Initial import", &[]).unwrap();
70
    let c1 = repo.store().get_change(&h1).unwrap();
71
    assert_eq!(c1.kind, ChangeKind::Normal);
72
    assert!(c1.deps.is_empty(), "first change has nothing to depend on");
73
    assert_eq!(repo.bookmark_heads().unwrap(), vec![h1]);
74
    let (wc_hash, wc) = repo.working_copy().unwrap();
75
    assert_eq!(wc.deps, vec![h1]);
76
    assert!(wc.edits.is_empty());
77
    assert!(repo.commit("nothing", &[]).is_err());
78
79
    // Modify one file, remove another, add a binary file.
80
    write(
81
        root,
82
        "src/main.rs",
83
        b"fn main() {\n    println!(\"hi\");\n}\n",
84
    );
85
    fs::remove_file(root.join("README.md")).unwrap();
86
    write(root, "logo.png", b"\x89PNG\0\0\x01");
87
    let s = repo.snapshot("oxy status").unwrap();
88
    assert_eq!(
89
        statuses(&s),
90
        vec![
91
            ("README.md".into(), ChangeStatus::Removed),
92
            ("logo.png".into(), ChangeStatus::Added),
93
            ("src/main.rs".into(), ChangeStatus::Modified),
94
        ]
95
    );
96
    assert_ne!(s.wc_hash, wc_hash);
97
    // The rewritten working copy keeps its ChangeId and depends on h1.
98
    assert_eq!(s.wc.change_id, wc.change_id);
99
    assert!(s.wc.deps.contains(&h1));
100
101
    let h2 = repo.commit("Second", &[]).unwrap();
102
    let c2 = repo.store().get_change(&h2).unwrap();
103
    assert_eq!(
104
        c2.deps,
105
        vec![h1],
106
        "everything it touches was introduced by h1"
107
    );
108
    assert_eq!(repo.bookmark_heads().unwrap(), vec![h2]);
109
110
    // The materialized head state matches the working copy.
111
    let st = repo.load_state(&[h2]).unwrap();
112
    let snap = st.materialize();
113
    assert!(!snap.is_conflicted());
114
    assert_eq!(
115
        snap.files.keys().cloned().collect::<Vec<_>>(),
116
        [".oxyignore", "logo.png", "src", "src/main.rs"]
117
    );
118
    assert!(
119
        matches!(&snap.files["src/main.rs"].content, FileContent::Text { bytes, .. } if bytes == b"fn main() {\n    println!(\"hi\");\n}\n")
120
    );
121
    assert!(snap.files["logo.png"].mode.opaque);
122
    if let FileContent::Opaque { blobs } = &snap.files["logo.png"].content {
123
        assert_eq!(repo.read_blob(&blobs[0]).unwrap(), b"\x89PNG\0\0\x01");
124
    } else {
125
        panic!("logo should be opaque");
126
    }
127
128
    // Log: newest first, working copy included.
129
    let log = repo.log().unwrap();
130
    assert_eq!(log.len(), 3);
131
    assert!(log[0].is_working_copy);
132
    assert_eq!(log[1].hash, h2);
133
    assert!(log[1].is_head);
134
    assert_eq!(log[2].hash, h1);
135
    let d = repo.describe_change(&h2).unwrap();
136
    assert!(d.contains("D README.md"), "{d}");
137
    assert!(
138
        d.lines()
139
            .any(|l| l.starts_with("M ") && l.ends_with("main.rs")),
140
        "a modified file is in the summary too: {d}"
141
    );
142
    assert!(d.contains("+    println!(\"hi\");"), "{d}");
143
    assert!(d.contains("-fn main() {}"), "{d}");
144
145
    // Resolution by prefix.
146
    assert_eq!(repo.resolve_change(&c2.change_id.short(6)).unwrap(), h2);
147
    assert_eq!(
148
        repo.resolve_change(&format!("#{}", h1.short(8))).unwrap(),
149
        h1
150
    );
151
    assert!(repo.resolve_change("zzzz").is_err());
152
153
    // Undo the commit: bookmark and working copy go back.
154
    repo.undo().unwrap();
155
    assert_eq!(repo.bookmark_heads().unwrap(), vec![h1]);
156
    let s = repo.snapshot("oxy status").unwrap();
157
    assert!(
158
        !s.changed,
159
        "files on disk still match the pre-commit working copy"
160
    );
161
    assert_eq!(s.statuses.len(), 3);
162
}
163
164
/// Make `main` conflicted: two commits on the same base that edit the same line.
165
fn conflicted_repo() -> (tempfile::TempDir, Repo, ChangeHash, ChangeHash, ChangeHash) {
166
    let dir = tempfile::tempdir().unwrap();
167
    let root = dir.path();
168
    let repo = Repo::init(root).unwrap();
169
    write(root, "f.txt", b"a\nb\nc\n");
170
    let h1 = repo.commit("base", &[]).unwrap();
171
    write(root, "f.txt", b"a\nB\nc\n");
172
    let h2 = repo.commit("upper", &[]).unwrap();
173
    repo.checkout(&[h1], false, "checkout").unwrap();
174
    write(root, "f.txt", b"a\nX\nc\n");
175
    let h3 = repo.commit("ex", &[]).unwrap();
176
    (dir, repo, h1, h2, h3)
177
}
178
179
#[test]
180
fn concurrent_edits_conflict_and_can_be_resolved() {
181
    hermetic();
182
    let (dir, repo, h1, h2, h3) = conflicted_repo();
183
    let root = dir.path();
184
    let heads: BTreeSet<_> = repo.bookmark_heads().unwrap().into_iter().collect();
185
    assert_eq!(heads, [h2, h3].into_iter().collect());
186
    let st = repo.load_state(&[h2, h3]).unwrap();
187
    assert!(st.materialize().is_conflicted());
188
189
    // Checking out main writes markers.
190
    let r = repo
191
        .checkout(&repo.bookmark_heads().unwrap(), false, "checkout main")
192
        .unwrap();
193
    assert!(r.conflicted);
194
    let marked = fs::read_to_string(root.join("f.txt")).unwrap();
195
    assert!(
196
        marked.starts_with("a\n<<<<<<< oxy conflict 1 of 1"),
197
        "{marked}"
198
    );
199
    assert!(
200
        marked.contains("B\n") && marked.contains("X\n") && marked.ends_with("end\nc\n"),
201
        "{marked}"
202
    );
203
    assert!(has_conflict_markers(marked.as_bytes()));
204
    // Untouched markers: clean working copy; commit has nothing to do.
205
    let s = repo.snapshot("status").unwrap();
206
    assert!(s.statuses.is_empty());
207
    assert!(!s.resolves);
208
209
    // Partially edited file that still has markers cannot be committed.
210
    write(root, "f.txt", marked.replace("B\n", "BB\n").as_bytes());
211
    let s = repo.snapshot("status").unwrap();
212
    assert_eq!(
213
        statuses(&s),
214
        vec![("f.txt".into(), ChangeStatus::ConflictEdited)]
215
    );
216
    assert!(repo.commit("no", &[]).is_err());
217
218
    // Resolve by keeping one side and adding a line elsewhere.
219
    write(root, "f.txt", b"a\nX\nc\nd\n");
220
    let s = repo.snapshot("status").unwrap();
221
    assert_eq!(statuses(&s), vec![("f.txt".into(), ChangeStatus::Resolved)]);
222
    assert!(s.resolves);
223
    let h4 = repo.commit("resolve", &[]).unwrap();
224
    let c4 = repo.store().get_change(&h4).unwrap();
225
    assert_eq!(c4.kind, ChangeKind::Resolution);
226
    let mut want = vec![h1, h2, h3];
227
    want.sort();
228
    assert_eq!(
229
        c4.deps, want,
230
        "a resolution depends on exactly the contributors and what it references"
231
    );
232
    assert_eq!(repo.bookmark_heads().unwrap(), vec![h4]);
233
    let snap = repo.load_state(&[h4]).unwrap().materialize();
234
    assert!(!snap.is_conflicted());
235
    assert!(
236
        matches!(&snap.files["f.txt"].content, FileContent::Text { bytes, .. } if bytes == b"a\nX\nc\nd\n")
237
    );
238
    assert!(!repo.snapshot("status").unwrap().changed);
239
    // A peer holding only h2 and h3 and receiving h4 sees the same result,
240
    // whatever order the changes arrive in.
241
    let mut st = State::new();
242
    for h in [h4, h3, h1, h2] {
243
        st.add_unchecked(repo.store().get_change(&h).unwrap());
244
    }
245
    st.validate().unwrap();
246
    assert!(
247
        matches!(&st.materialize().files["f.txt"].content, FileContent::Text { bytes, .. } if bytes == b"a\nX\nc\nd\n")
248
    );
249
}
250
251
/// oxygen#118 (Metal Gear): a resolution commits by paths, leaving other
252
/// work uncommitted, so long as it takes every file it resolves; and
253
/// `amend PATHS` folds only those paths into the head.
254
#[test]
255
fn resolutions_and_amends_take_paths() {
256
    hermetic();
257
    let (dir, repo, _h1, _h2, _h3) = conflicted_repo();
258
    let root = dir.path();
259
    repo.checkout(&repo.bookmark_heads().unwrap(), false, "checkout main")
260
        .unwrap();
261
    // The conflict resolved, and other work beside it.
262
    write(root, "f.txt", b"a\nX\nc\n");
263
    write(root, "notes.txt", b"pending\n");
264
    let s = repo.snapshot("status").unwrap();
265
    assert!(s.resolves);
266
    let err = repo
267
        .commit_selection_partial("resolve", &[], &Selection::Paths(vec!["notes.txt".into()]))
268
        .unwrap_err()
269
        .to_string();
270
    assert!(
271
        err.contains("takes every file it resolves") && err.contains("f.txt"),
272
        "{err}"
273
    );
274
    let (h4, partial) = repo
275
        .commit_selection_partial("resolve", &[], &Selection::Paths(vec!["f.txt".into()]))
276
        .unwrap();
277
    assert!(partial);
278
    assert_eq!(
279
        repo.store().get_change(&h4).unwrap().kind,
280
        ChangeKind::Resolution
281
    );
282
    assert!(!repo
283
        .load_state(&[h4])
284
        .unwrap()
285
        .materialize()
286
        .is_conflicted());
287
    let s = repo.snapshot("status").unwrap();
288
    assert_eq!(
289
        statuses(&s),
290
        vec![("notes.txt".into(), ChangeStatus::Added)],
291
        "the other work waits"
292
    );
293
294
    // amend PATHS: only those paths join the head; it keeps its ChangeId.
295
    // On the resolution, so the bookmark has one head to amend.
296
    let h5 = repo.commit("notes", &[h4]).unwrap();
297
    let id5 = repo.store().get_change(&h5).unwrap().change_id;
298
    write(root, "notes.txt", b"pending\nmore\n");
299
    write(root, "other.txt", b"later\n");
300
    let h6 = repo
301
        .amend_paths(Some("notes, amended"), &["notes.txt".into()])
302
        .unwrap();
303
    let c6 = repo.store().get_change(&h6).unwrap();
304
    assert_eq!((c6.change_id, c6.message.as_str()), (id5, "notes, amended"));
305
    assert_eq!(repo.bookmark_heads().unwrap(), vec![h6]);
306
    let snap6 = repo.load_state(&[h6]).unwrap().materialize();
307
    assert!(
308
        matches!(&snap6.files["notes.txt"].content, FileContent::Text { bytes, .. } if bytes == b"pending\nmore\n")
309
    );
310
    assert!(
311
        !snap6.files.contains_key("other.txt"),
312
        "other.txt stays out"
313
    );
314
    let s = repo.snapshot("status").unwrap();
315
    assert_eq!(
316
        statuses(&s),
317
        vec![("other.txt".into(), ChangeStatus::Added)]
318
    );
319
}
320
321
#[test]
322
fn resolution_may_keep_both_sides_or_neither() {
323
    hermetic();
324
    let (dir, repo, _h1, _h2, _h3) = conflicted_repo();
325
    let root = dir.path();
326
    repo.checkout(&repo.bookmark_heads().unwrap(), false, "checkout main")
327
        .unwrap();
328
    // Keep both sides in a chosen order.
329
    write(root, "f.txt", b"a\nX\nB\nc\n");
330
    let h = repo.commit("both", &[]).unwrap();
331
    let snap = repo.load_state(&[h]).unwrap().materialize();
332
    assert!(!snap.is_conflicted());
333
    assert!(
334
        matches!(&snap.files["f.txt"].content, FileContent::Text { bytes, .. } if bytes == b"a\nX\nB\nc\n")
335
    );
336
    // Undo and instead drop the whole region.
337
    repo.undo().unwrap();
338
    write(root, "f.txt", b"a\nc\n");
339
    let h = repo.commit("neither", &[]).unwrap();
340
    let snap = repo.load_state(&[h]).unwrap().materialize();
341
    assert!(!snap.is_conflicted());
342
    assert!(
343
        matches!(&snap.files["f.txt"].content, FileContent::Text { bytes, .. } if bytes == b"a\nc\n")
344
    );
345
}
346
347
#[test]
348
fn name_conflict_resolved_by_removing_a_candidate() {
349
    hermetic();
350
    let dir = tempfile::tempdir().unwrap();
351
    let root = dir.path();
352
    let repo = Repo::init(root).unwrap();
353
    write(root, "keep.txt", b"k\n");
354
    let h1 = repo.commit("base", &[]).unwrap();
355
    write(root, "new.txt", b"one\n");
356
    repo.commit("one", &[]).unwrap();
357
    repo.checkout(&[h1], false, "checkout").unwrap();
358
    write(root, "new.txt", b"two\n");
359
    repo.commit("two", &[]).unwrap();
360
    let r = repo
361
        .checkout(&repo.bookmark_heads().unwrap(), false, "checkout main")
362
        .unwrap();
363
    assert!(r.conflicted);
364
    assert!(
365
        root.join("new.txt.oxy-conflict-1").exists()
366
            && root.join("new.txt.oxy-conflict-2").exists()
367
    );
368
    assert!(!root.join("new.txt").exists());
369
    // Candidate numbering follows change-hash order, so pick by content:
370
    // keep the "two" candidate under the real name and drop the other.
371
    let (keep, drop) = if fs::read(root.join("new.txt.oxy-conflict-1")).unwrap() == b"two\n" {
372
        (1, 2)
373
    } else {
374
        (2, 1)
375
    };
376
    fs::remove_file(root.join(format!("new.txt.oxy-conflict-{drop}"))).unwrap();
377
    fs::rename(
378
        root.join(format!("new.txt.oxy-conflict-{keep}")),
379
        root.join("new.txt"),
380
    )
381
    .unwrap();
382
    let h = repo.commit("pick two", &[]).unwrap();
383
    assert_eq!(
384
        repo.store().get_change(&h).unwrap().kind,
385
        ChangeKind::Resolution
386
    );
387
    // The resolution does not touch keep.txt, so it does not depend on h1;
388
    // the bookmark keeps both as heads and their union is the state.
389
    let heads: BTreeSet<_> = repo.bookmark_heads().unwrap().into_iter().collect();
390
    assert_eq!(heads, [h1, h].into_iter().collect());
391
    let snap = repo
392
        .load_state(&repo.bookmark_heads().unwrap())
393
        .unwrap()
394
        .materialize();
395
    assert!(!snap.is_conflicted(), "{:?}", snap.tree.conflicts);
396
    assert_eq!(
397
        snap.files.keys().cloned().collect::<Vec<_>>(),
398
        ["keep.txt", "new.txt"]
399
    );
400
    assert!(
401
        matches!(&snap.files["new.txt"].content, FileContent::Text { bytes, .. } if bytes == b"two\n")
402
    );
403
}
404
405
/// Each of two bookmarks adds `path` (a file written by `side` on each)
406
/// from the same base, and the second is merged into the first. Returns
407
/// the repository on `main`, the merge's heads, and the three changes.
408
fn merged_additions(
409
    side: impl Fn(&Path, bool),
410
) -> (tempfile::TempDir, Repo, Vec<ChangeHash>, [ChangeHash; 3]) {
411
    let dir = tempfile::tempdir().unwrap();
412
    let root = dir.path().to_path_buf();
413
    let mut repo = Repo::init(&root).unwrap();
414
    write(&root, "keep.txt", b"k\n");
415
    let h1 = repo.commit("base", &[]).unwrap();
416
    repo.bookmark_create("side", None).unwrap();
417
    side(&root, false);
418
    let ha = repo.commit("add on main", &[]).unwrap();
419
    repo.bookmark_switch("side", false).unwrap();
420
    side(&root, true);
421
    let hb = repo.commit("add on side", &[]).unwrap();
422
    repo.bookmark_switch("main", false).unwrap();
423
    let m = repo.merge("side").unwrap();
424
    assert!(m.changed && m.checked_out);
425
    (dir, repo, m.heads, [h1, ha, hb])
426
}
427
428
fn conflict_copies(root: &Path) -> Vec<String> {
429
    let mut out: Vec<String> = fs::read_dir(root)
430
        .unwrap()
431
        .map(|e| e.unwrap().file_name().to_string_lossy().into_owned())
432
        .filter(|n| n.contains(".oxy-conflict-"))
433
        .collect();
434
    out.sort();
435
    out
436
}
437
438
/// The same path added on two bookmarks with identical content is one
439
/// file after the merge (oxygen#101): no conflict, nothing to resolve,
440
/// nothing recorded; and editing or removing it later keeps it one.
441
#[test]
442
fn identical_additions_unify_on_merge() {
443
    hermetic();
444
    let (dir, repo, heads, [h1, ha, hb]) =
445
        merged_additions(|root, _| write(root, "x.txt", b"same\nlines\n"));
446
    let root = dir.path();
447
    // The tree graph has the name conflict; every reader sees one file.
448
    let st = repo.load_state(&heads).unwrap();
449
    assert!(st
450
        .tree()
451
        .view()
452
        .conflicts
453
        .iter()
454
        .any(|c| matches!(c, crate::tree::TreeConflict::Name { .. })));
455
    let snap = st.materialize();
456
    assert!(!snap.is_conflicted(), "{:?}", snap.tree.conflicts);
457
    assert_eq!(
458
        snap.files.keys().cloned().collect::<Vec<_>>(),
459
        ["keep.txt", "x.txt"]
460
    );
461
    assert!(
462
        matches!(&snap.files["x.txt"].content, FileContent::Text { bytes, .. } if bytes == b"same\nlines\n")
463
    );
464
    assert_eq!(snap.tree.unified.len(), 1);
465
    // On disk once, the working copy clean, nothing to commit.
466
    assert_eq!(fs::read(root.join("x.txt")).unwrap(), b"same\nlines\n");
467
    assert!(
468
        conflict_copies(root).is_empty(),
469
        "{:?}",
470
        conflict_copies(root)
471
    );
472
    let s = repo.snapshot("status").unwrap();
473
    assert!(s.statuses.is_empty(), "{:?}", statuses(&s));
474
    assert!(!s.changed && !s.resolves);
475
    assert!(!s.base_snapshot.is_conflicted());
476
    assert!(s.wc.tree_ops.is_empty() && s.wc.edits.is_empty());
477
    let json = repo.status_json(&s).unwrap();
478
    assert!(json.contains("\"conflicted\":false"), "{json}");
479
    assert!(repo.commit("nothing", &[]).is_err());
480
    assert_eq!(repo.file_at("x.txt", None).unwrap(), b"same\nlines\n");
481
    // A peer holding the same changes, added in another order, agrees.
482
    let mut peer = State::new();
483
    for h in [hb, ha, h1] {
484
        peer.add_unchecked(repo.store().get_change(&h).unwrap());
485
    }
486
    peer.validate().unwrap();
487
    let ps = peer.materialize();
488
    assert!(!ps.is_conflicted());
489
    assert_eq!(ps.tree.entries["x.txt"], snap.tree.entries["x.txt"]);
490
    assert_eq!(ps.tree.unified, snap.tree.unified);
491
    // The file's history is both additions.
492
    let log: Vec<ChangeHash> = repo
493
        .log_for_path("x.txt")
494
        .unwrap()
495
        .iter()
496
        .map(|e| e.hash)
497
        .collect();
498
    assert!(log.contains(&ha) && log.contains(&hb), "{log:?}");
499
500
    // Edited and committed: one file still, the duplicate retired with it.
501
    write(root, "x.txt", b"same\nedited\n");
502
    let s = repo.snapshot("status").unwrap();
503
    assert_eq!(statuses(&s), vec![("x.txt".into(), ChangeStatus::Modified)]);
504
    let he = repo.commit("edit x", &[]).unwrap();
505
    let c = repo.store().get_change(&he).unwrap();
506
    assert_eq!(c.kind, ChangeKind::Normal);
507
    let (dup, _) = snap.tree.unified.iter().next().unwrap();
508
    assert!(
509
        c.tree_ops
510
            .iter()
511
            .any(|o| matches!(o, TreeOp::RemoveNode { node, .. } if node == dup)),
512
        "{:?}",
513
        c.tree_ops
514
    );
515
    let d = repo.describe_change(&he).unwrap();
516
    assert!(!d.contains("D x.txt"), "{d}");
517
    let st = repo.load_state(&repo.bookmark_heads().unwrap()).unwrap();
518
    assert!(
519
        st.tree().view().conflicts.is_empty(),
520
        "nothing left to unify"
521
    );
522
    let snap = st.materialize();
523
    assert!(!snap.is_conflicted());
524
    assert!(
525
        matches!(&snap.files["x.txt"].content, FileContent::Text { bytes, .. } if bytes == b"same\nedited\n")
526
    );
527
    assert!(!repo.snapshot("status").unwrap().changed);
528
529
    // Removed and committed: gone.
530
    fs::remove_file(root.join("x.txt")).unwrap();
531
    repo.commit("drop x", &[]).unwrap();
532
    let snap = repo
533
        .load_state(&repo.bookmark_heads().unwrap())
534
        .unwrap()
535
        .materialize();
536
    assert!(!snap.is_conflicted(), "{:?}", snap.tree.conflicts);
537
    assert_eq!(snap.files.keys().cloned().collect::<Vec<_>>(), ["keep.txt"]);
538
    assert!(!root.join("x.txt").exists());
539
}
540
541
/// Removing, renaming, or committing just the path of a unified file
542
/// retires its duplicate with it, so the conflict never comes back.
543
#[test]
544
fn unified_additions_stay_one_when_removed_renamed_or_committed_alone() {
545
    hermetic();
546
    let add = |root: &Path, _: bool| write(root, "x.txt", b"same\n");
547
    for how in ["remove", "rename", "path", "hunk"] {
548
        let (dir, repo, _, _) = merged_additions(add);
549
        let root = dir.path();
550
        match how {
551
            "remove" => fs::remove_file(root.join("x.txt")).unwrap(),
552
            "rename" => fs::rename(root.join("x.txt"), root.join("y.txt")).unwrap(),
553
            _ => {
554
                write(root, "x.txt", b"same\nmore\n");
555
                write(root, "other.txt", b"o\n");
556
            }
557
        }
558
        let s = repo.snapshot("status").unwrap();
559
        let h = match how {
560
            "path" => repo
561
                .commit_selection("x alone", &[], &Selection::Paths(vec!["x.txt".into()]))
562
                .unwrap(),
563
            "hunk" => {
564
                let (_, hunks) = repo.hunks().unwrap();
565
                // The duplicate's retirement is no hunk of its own.
566
                assert!(hunks.iter().all(|h| !h.text.starts_with("D ")), "{hunks:?}");
567
                let x: Vec<usize> = hunks
568
                    .iter()
569
                    .filter(|h| h.path == "x.txt")
570
                    .map(|h| h.index)
571
                    .collect();
572
                assert!(!x.is_empty());
573
                repo.commit_selection("x hunks", &[], &Selection::Hunks(x))
574
                    .unwrap()
575
            }
576
            _ => repo.commit(how, &[]).unwrap(),
577
        };
578
        assert!(!s.base_snapshot.is_conflicted());
579
        let heads = repo.bookmark_heads().unwrap();
580
        assert!(heads.contains(&h));
581
        let snap = repo.load_state(&heads).unwrap().materialize();
582
        assert!(!snap.is_conflicted(), "{how}: {:?}", snap.tree.conflicts);
583
        let want: &[&str] = match how {
584
            "remove" => &["keep.txt"],
585
            "rename" => &["keep.txt", "y.txt"],
586
            _ => &["keep.txt", "x.txt"],
587
        };
588
        assert_eq!(
589
            snap.files.keys().cloned().collect::<Vec<_>>(),
590
            want,
591
            "{how}"
592
        );
593
        assert!(conflict_copies(root).is_empty(), "{how}");
594
    }
595
}
596
597
/// The same path added with different content, or a different mode, is a
598
/// name conflict as before.
599
#[test]
600
fn additions_that_differ_still_conflict() {
601
    hermetic();
602
    #[cfg(unix)]
603
    use std::os::unix::fs::PermissionsExt;
604
    let content =
605
        |root: &Path, side: bool| write(root, "x.txt", if side { b"two\n" } else { b"one\n" });
606
    let mode = |root: &Path, side: bool| {
607
        write(root, "x.txt", b"same\n");
608
        #[cfg(unix)]
609
        if side {
610
            fs::set_permissions(root.join("x.txt"), fs::Permissions::from_mode(0o755)).unwrap();
611
        }
612
    };
613
    let check = |what: &str, side: &dyn Fn(&Path, bool)| {
614
        let (dir, repo, heads, _) = merged_additions(side);
615
        let snap = repo.load_state(&heads).unwrap().materialize();
616
        assert!(snap.tree.unified.is_empty(), "{what}");
617
        assert!(
618
            snap.tree.conflicts.iter().any(
619
                |c| matches!(c, crate::tree::TreeConflict::Name { name, .. } if name == "x.txt")
620
            ),
621
            "{what}: {:?}",
622
            snap.tree.conflicts
623
        );
624
        assert_eq!(
625
            conflict_copies(dir.path()),
626
            ["x.txt.oxy-conflict-1", "x.txt.oxy-conflict-2"],
627
            "{what}"
628
        );
629
        assert!(!dir.path().join("x.txt").exists(), "{what}");
630
    };
631
    check("content", &content);
632
    #[cfg(unix)]
633
    check("mode", &mode);
634
    #[cfg(not(unix))]
635
    let _ = mode;
636
}
637
638
/// The same subrepo at the same pin, added on two bookmarks, is one
639
/// subrepo after the merge (oxygen#101), as is the identical
640
/// `.oxymodules` beside it.
641
#[test]
642
fn the_same_subrepo_added_on_two_bookmarks_unifies() {
643
    hermetic();
644
    let dir = tempfile::tempdir().unwrap();
645
    let root = dir.path();
646
    let lib_origin = Repo::init(&root.join("lib-origin")).unwrap();
647
    let lib_url = root.join("lib-origin").to_string_lossy().to_string();
648
    let lib = Repo::clone(&lib_url, &root.join("lib"))
649
        .unwrap()
650
        .with_home(root.join("home"));
651
    write(&root.join("lib"), "lib.txt", b"v1\n");
652
    lib.commit("lib v1", &[]).unwrap();
653
    assert!(lib.push("origin", false).unwrap()[0].ok);
654
    let _ = lib_origin;
655
656
    let app_dir = root.join("app");
657
    let mut app = Repo::init(&app_dir).unwrap().with_home(root.join("home"));
658
    write(&app_dir, "main.txt", b"app\n");
659
    app.commit("base", &[]).unwrap();
660
    app.bookmark_create("side", None).unwrap();
661
    app.submodule_add(&lib_url, "rstar-api", None).unwrap();
662
    let modules = fs::read(app_dir.join(".oxymodules")).unwrap();
663
    app.commit("rstar-api on main", &[]).unwrap();
664
    // On the other bookmark the nested repository is still there (it is
665
    // never deleted); registering it again adds it at the same pin.
666
    app.bookmark_switch("side", false).unwrap();
667
    assert!(app_dir.join("rstar-api/.oxy").is_dir());
668
    write(&app_dir, ".oxymodules", &modules);
669
    let s = app.snapshot("status").unwrap();
670
    assert_eq!(
671
        statuses(&s),
672
        vec![
673
            (".oxymodules".into(), ChangeStatus::Added),
674
            ("rstar-api".into(), ChangeStatus::Added)
675
        ]
676
    );
677
    app.commit("rstar-api on side", &[]).unwrap();
678
    app.bookmark_switch("main", false).unwrap();
679
680
    let m = app.merge("side").unwrap();
681
    assert!(m.changed && m.checked_out);
682
    let snap = app.load_state(&m.heads).unwrap().materialize();
683
    assert!(!snap.is_conflicted(), "{:?}", snap.tree.conflicts);
684
    assert_eq!(snap.tree.unified.len(), 2);
685
    assert_eq!(snap.files["rstar-api"].kind, NodeKind::Subrepo);
686
    assert!(conflict_copies(&app_dir).is_empty());
687
    let s = app.snapshot("status").unwrap();
688
    assert!(s.statuses.is_empty(), "{:?}", statuses(&s));
689
    assert!(!s.base_snapshot.is_conflicted());
690
    assert_eq!(
691
        fs::read_to_string(app_dir.join("rstar-api/lib.txt")).unwrap(),
692
        "v1\n"
693
    );
694
}
695
696
#[test]
697
fn identities_and_signed_commits() {
698
    hermetic();
699
    let dir = tempfile::tempdir().unwrap();
700
    let root = dir.path();
701
    let mut repo = Repo::init(root).unwrap().with_home(root.join("home"));
702
    write(root, "a.txt", b"a\n");
703
    let h0 = repo.commit("unsigned", &[]).unwrap();
704
    assert_eq!(repo.verify_change(&h0).unwrap(), SignatureStatus::Unsigned);
705
    assert_eq!(
706
        repo.store().get_change(&h0).unwrap().author,
707
        ObjectRef::ZERO
708
    );
709
710
    let (key, id) = repo
711
        .create_identity("Ada", "[email protected]", IdentityScope::Repo)
712
        .unwrap();
713
    assert_eq!(id.hash(), key);
714
    assert_eq!(repo.config.author_key, Some(key));
715
    // Config survives reopen; the secret key is found again.
716
    let reopened = Repo::open(root).unwrap().with_home(root.join("home"));
717
    assert_eq!(reopened.config.author_key, Some(key));
718
    assert_eq!(reopened.secret_key().unwrap().unwrap().0, key);
719
720
    // Default core.sign = seal: commits carry the author but no signature.
721
    write(root, "a.txt", b"a\nb\n");
722
    let h1 = repo.commit("authored", &[]).unwrap();
723
    assert_eq!(repo.store().get_change(&h1).unwrap().author, key);
724
    assert_eq!(repo.verify_change(&h1).unwrap(), SignatureStatus::Unsigned);
725
    // Signing later works too.
726
    repo.sign_change(&h1).unwrap();
727
    assert!(
728
        matches!(repo.verify_change(&h1).unwrap(), SignatureStatus::Valid { key: k, .. } if k == key)
729
    );
730
731
    repo.config.set("core.sign", "change").unwrap();
732
    repo.save_config().unwrap();
733
    write(root, "a.txt", b"a\nb\nc\n");
734
    let h2 = repo.commit("signed", &[]).unwrap();
735
    assert_eq!(
736
        repo.verify_change(&h2).unwrap(),
737
        SignatureStatus::Valid {
738
            key,
739
            name: "Ada".into(),
740
            email: "[email protected]".into(),
741
            sealed: false,
742
            revoked: false
743
        }
744
    );
745
746
    // A signature by a key that is not the author or a delegate is rejected
747
    // when the change names an author; an anonymous change (made before any
748
    // identity, author zero) is adopted by whoever signs it (spec §14.4).
749
    let other = SecretKey::generate();
750
    let other_id = other.identity("Mallory", "[email protected]", 0);
751
    let other_key = repo.store().put_identity(&other_id).unwrap();
752
    write(root, "a.txt", b"a\nb\nc\nd\n");
753
    repo.config.set("core.sign", "seal").unwrap();
754
    let h3 = repo.commit("ada's, unsigned", &[]).unwrap();
755
    let forged = other.sign(Domain::Change, &other_key, &h3);
756
    repo.store().put_signature(&h3, &forged).unwrap();
757
    assert!(
758
        matches!(repo.verify_change(&h3).unwrap(), SignatureStatus::Invalid(m) if m.contains("neither the author"))
759
    );
760
    let adopted = other.sign(Domain::Change, &other_key, &h0);
761
    repo.store().put_signature(&h0, &adopted).unwrap();
762
    assert!(
763
        matches!(repo.verify_change(&h0).unwrap(), SignatureStatus::Valid { name, .. } if name == "Mallory")
764
    );
765
766
    // Tampering with the stored signature invalidates it.
767
    let mut sig = repo.store().signatures(&h2).unwrap().remove(0);
768
    sig.ed[0] ^= 1;
769
    repo.store().put_signature(&h2, &sig).unwrap();
770
    assert!(matches!(
771
        repo.verify_change(&h2).unwrap(),
772
        SignatureStatus::Invalid(_)
773
    ));
774
775
    // Without the secret key, signing at commit fails cleanly.
776
    let no_keys = Repo::open(root).unwrap().with_home(root.join("nowhere"));
777
    write(root, "a.txt", b"z\n");
778
    assert!(no_keys.commit("cannot sign", &[]).is_err());
779
}
780
781
#[test]
782
fn checkout_moves_the_working_copy() {
783
    hermetic();
784
    let dir = tempfile::tempdir().unwrap();
785
    let root = dir.path();
786
    let repo = Repo::init(root).unwrap();
787
    write(root, "a.txt", b"one\n");
788
    write(root, "sub/deep/b.txt", b"b\n");
789
    let h1 = repo.commit("first", &[]).unwrap();
790
    write(root, "a.txt", b"two\n");
791
    fs::remove_file(root.join("sub/deep/b.txt")).unwrap();
792
    write(root, "bin.dat", &[0, 1, 2, 3]);
793
    let h2 = repo.commit("second", &[]).unwrap();
794
795
    let r = repo.checkout(&[h1], false, "oxy checkout").unwrap();
796
    assert_eq!(
797
        r,
798
        CheckoutReport {
799
            written: 2,
800
            removed: 1,
801
            removed_paths: vec!["bin.dat".into()],
802
            conflicted: false,
803
            notes: vec![],
804
            lacks: 1,
805
        }
806
    );
807
    assert_eq!(fs::read(root.join("a.txt")).unwrap(), b"one\n");
808
    assert_eq!(fs::read(root.join("sub/deep/b.txt")).unwrap(), b"b\n");
809
    assert!(!root.join("bin.dat").exists());
810
    let (_, wc) = repo.working_copy().unwrap();
811
    assert_eq!(wc.deps, vec![h1]);
812
    assert!(
813
        !repo.snapshot("status").unwrap().changed,
814
        "checkout leaves a clean working copy"
815
    );
816
    // The bookmark still points at h2.
817
    assert_eq!(repo.bookmark_heads().unwrap(), vec![h2]);
818
819
    // Dirty working copy refuses without --discard.
820
    write(root, "a.txt", b"dirty\n");
821
    assert!(repo.checkout(&[h2], false, "oxy checkout").is_err());
822
    let r = repo
823
        .checkout(&[h2], true, "oxy checkout --discard")
824
        .unwrap();
825
    assert_eq!(fs::read(root.join("a.txt")).unwrap(), b"two\n");
826
    assert_eq!(fs::read(root.join("bin.dat")).unwrap(), [0, 1, 2, 3]);
827
    assert!(!root.join("sub").exists(), "empty directories are pruned");
828
    assert_eq!(r.removed, 1);
829
    assert!(!repo.snapshot("status").unwrap().changed);
830
831
    // Refuses to write through a symlinked directory.
832
    #[cfg(unix)]
833
    {
834
        fs::remove_dir_all(root.join("sub")).ok();
835
        std::os::unix::fs::symlink("/tmp", root.join("sub")).unwrap();
836
        assert!(repo.checkout(&[h1], true, "oxy checkout").is_err());
837
    }
838
}
839
840
#[test]
841
fn large_files_are_chunked_and_read_back() {
842
    hermetic();
843
    let dir = tempfile::tempdir().unwrap();
844
    let repo = Repo::init(dir.path()).unwrap();
845
    let mut big = vec![0u8; 700 * 1024];
846
    for (i, b) in big.iter_mut().enumerate() {
847
        *b = (i as u32).wrapping_mul(2654435761).to_le_bytes()[0];
848
    }
849
    let r = repo.store_blob(&big).unwrap();
850
    let blob = Blob::decode(&repo.store().get_typed(&r, ObjectType::Blob).unwrap()).unwrap();
851
    assert!(blob.chunks.len() >= 3, "{}", blob.chunks.len());
852
    assert_eq!(repo.read_blob(&r).unwrap(), big);
853
    assert_eq!(Repo::blob_ref(&big), r);
854
}
855
856
#[test]
857
fn clone_push_pull_with_seals_and_attestations() {
858
    hermetic();
859
    let dir = tempfile::tempdir().unwrap();
860
    let root = dir.path();
861
    let origin_path = root.join("origin");
862
    let origin = Repo::init(&origin_path).unwrap();
863
    let origin_url = origin_path.to_string_lossy().to_string();
864
865
    // A clones, creates an identity (default core.sign = seal), commits, pushes.
866
    let mut a = Repo::clone(&origin_url, &root.join("a"))
867
        .unwrap()
868
        .with_home(root.join("home-a"));
869
    assert_eq!(a.id().unwrap(), origin.id().unwrap());
870
    let (key_a, _) = a
871
        .create_identity("Ada", "[email protected]", IdentityScope::Repo)
872
        .unwrap();
873
    write(&root.join("a"), "f.txt", b"a\n");
874
    let h1 = a.commit("first", &[]).unwrap();
875
    let results = a.push("origin", false).unwrap();
876
    origin.refresh().unwrap();
877
    assert!(results[0].ok, "{}", results[0].reason);
878
    assert_eq!(origin.bookmark_heads().unwrap(), vec![h1]);
879
    // The change was sealed at push and the reference attested.
880
    assert!(
881
        matches!(origin.authenticate_change(&h1).unwrap(), SignatureStatus::Valid { key, sealed: true, .. } if key == key_a)
882
    );
883
    assert_eq!(
884
        origin.verify_change(&h1).unwrap(),
885
        SignatureStatus::Unsigned
886
    );
887
    let serial_of = |att: &SignedAttest| match att.attest.body {
888
        AttestBody::Ref { serial, .. } => serial,
889
        _ => unreachable!(),
890
    };
891
    let (_, att) = origin.latest_ref_attest("main").unwrap().unwrap();
892
    // A bookmark new to the remote starts at the clock (past any deleted
893
    // namesake's serial); later updates count up from there.
894
    let first = serial_of(&att);
895
    assert!(first > 1_000_000_000_000, "{first}");
896
    let again = a.push("origin", false).unwrap();
897
    origin.refresh().unwrap();
898
    assert!(again[0].ok && again[0].reason.contains("up to date"));
899
    let (_, att) = origin.latest_ref_attest("main").unwrap().unwrap();
900
    assert_eq!(serial_of(&att), first, "a no-op push does not attest again");
901
902
    // B clones and sees the file and the seal.
903
    let b = Repo::clone(&origin_url, &root.join("b")).unwrap();
904
    assert_eq!(fs::read(root.join("b/f.txt")).unwrap(), b"a\n");
905
    assert_eq!(b.bookmark_heads().unwrap(), vec![h1]);
906
    assert!(matches!(
907
        b.authenticate_change(&h1).unwrap(),
908
        SignatureStatus::Valid { sealed: true, .. }
909
    ));
910
911
    // B (no identity) commits and pushes unsigned; the unverified origin accepts.
912
    write(&root.join("b"), "f.txt", b"a\nb\n");
913
    let h2 = b.commit("second", &[]).unwrap();
914
    assert!(b.push("origin", false).unwrap()[0].ok);
915
    origin.refresh().unwrap();
916
    assert_eq!(origin.bookmark_heads().unwrap(), vec![h2]);
917
918
    // A commits an independent change; push is refused until A pulls.
919
    write(&root.join("a"), "g.txt", b"g\n");
920
    let h3 = a.commit("third", &[]).unwrap();
921
    assert!(a.push("origin", false).is_err());
922
    let pr = a.pull("origin").unwrap();
923
    assert!(pr.changed && pr.checked_out);
924
    let mut want = vec![h2, h3];
925
    want.sort();
926
    assert_eq!(pr.heads, want);
927
    assert_eq!(fs::read(root.join("a/f.txt")).unwrap(), b"a\nb\n");
928
    assert_eq!(fs::read(root.join("a/g.txt")).unwrap(), b"g\n");
929
    let results = a.push("origin", false).unwrap();
930
    origin.refresh().unwrap();
931
    assert!(results[0].ok, "{}", results[0].reason);
932
    let mut origin_heads = origin.bookmark_heads().unwrap();
933
    origin_heads.sort();
934
    assert_eq!(origin_heads, want);
935
    let (_, att) = origin.latest_ref_attest("main").unwrap().unwrap();
936
    assert_eq!(serial_of(&att), first + 1);
937
938
    // B pulls and ends up identical.
939
    let pr = b.pull("origin").unwrap();
940
    assert_eq!(pr.heads, want);
941
    assert_eq!(fs::read(root.join("b/g.txt")).unwrap(), b"g\n");
942
    assert!(!b.snapshot("status").unwrap().changed);
943
944
    // Concurrent edits of the same line: the union is a reified conflict.
945
    write(&root.join("a"), "f.txt", b"a\nA\n");
946
    a.commit("a-edit", &[]).unwrap();
947
    a.push("origin", false).unwrap();
948
    origin.refresh().unwrap();
949
    write(&root.join("b"), "f.txt", b"a\nB\n");
950
    b.commit("b-edit", &[]).unwrap();
951
    let pr = b.pull("origin").unwrap();
952
    assert!(pr.changed && pr.checked_out);
953
    let text = fs::read_to_string(root.join("b/f.txt")).unwrap();
954
    assert!(text.contains("<<<<<<< oxy conflict"), "{text}");
955
    write(&root.join("b"), "f.txt", b"a\nAB\n");
956
    let hr = b.commit("resolve", &[]).unwrap();
957
    assert_eq!(
958
        b.store().get_change(&hr).unwrap().kind,
959
        ChangeKind::Resolution
960
    );
961
    assert!(b.push("origin", false).unwrap()[0].ok);
962
    origin.refresh().unwrap();
963
    a.pull("origin").unwrap();
964
    assert_eq!(fs::read(root.join("a/f.txt")).unwrap(), b"a\nAB\n");
965
    // The resolution depends on the conflicting edits, but nothing depends
966
    // on "third" (it only added g.txt), so it stays a head beside it.
967
    let mut want = vec![hr, h3];
968
    want.sort();
969
    assert_eq!(a.bookmark_heads().unwrap(), want);
970
    assert!(!a.load_state(&want).unwrap().materialize().is_conflicted());
971
}
972
973
#[test]
974
fn receive_push_rejects_bad_updates() {
975
    hermetic();
976
    let dir = tempfile::tempdir().unwrap();
977
    let root = dir.path();
978
    let origin = Repo::init(&root.join("origin")).unwrap();
979
    let url = root.join("origin").to_string_lossy().to_string();
980
    let mut a = Repo::clone(&url, &root.join("a"))
981
        .unwrap()
982
        .with_home(root.join("home"));
983
    let (key, _) = a
984
        .create_identity("Ada", "a@b", IdentityScope::Repo)
985
        .unwrap();
986
    write(&root.join("a"), "f.txt", b"x\n");
987
    let h1 = a.commit("one", &[]).unwrap();
988
    assert!(a.push("origin", false).unwrap()[0].ok);
989
    let empty = origin.store().put_state(&StateObject::new(vec![])).unwrap();
990
    let s1 = origin
991
        .store()
992
        .put_state(&StateObject::new(vec![h1]))
993
        .unwrap();
994
995
    // Missing head.
996
    let ghost = origin
997
        .store()
998
        .put_state(&StateObject::new(vec![ObjectRef([9; 32])]))
999
        .unwrap();
1000
    let r = origin
1001
        .receive_push(
1002
            Bundle::default(),
1003
            vec![RefUpdate {
1004
                name: "main".into(),
1005
                old_state: s1,
1006
                new_state: ghost,
1007
                force: false,
1008
                attestation: None,
1009
            }],
1010
            None,
1011
            vec![],
1012
        )
1013
        .unwrap();
1014
    assert!(
1015
        !r[0].ok && r[0].reason.contains("missing"),
1016
        "{}",
1017
        r[0].reason
1018
    );
1019
1020
    // Stale old_state.
1021
    let r = origin
1022
        .receive_push(
1023
            Bundle::default(),
1024
            vec![RefUpdate {
1025
                name: "main".into(),
1026
                old_state: empty,
1027
                new_state: s1,
1028
                force: false,
1029
                attestation: None,
1030
            }],
1031
            None,
1032
            vec![],
1033
        )
1034
        .unwrap();
1035
    assert!(!r[0].ok && r[0].reason.contains("stale"), "{}", r[0].reason);
1036
1037
    // Non-fast-forward without force is refused; with force it passes.
1038
    let r = origin
1039
        .receive_push(
1040
            Bundle::default(),
1041
            vec![RefUpdate {
1042
                name: "main".into(),
1043
                old_state: s1,
1044
                new_state: empty,
1045
                force: false,
1046
                attestation: None,
1047
            }],
1048
            None,
1049
            vec![],
1050
        )
1051
        .unwrap();
1052
    assert!(
1053
        !r[0].ok && r[0].reason.contains("fast-forward"),
1054
        "{}",
1055
        r[0].reason
1056
    );
1057
    let r = origin
1058
        .receive_push(
1059
            Bundle::default(),
1060
            vec![RefUpdate {
1061
                name: "main".into(),
1062
                old_state: s1,
1063
                new_state: empty,
1064
                force: true,
1065
                attestation: None,
1066
            }],
1067
            None,
1068
            vec![],
1069
        )
1070
        .unwrap();
1071
    assert!(r[0].ok);
1072
    assert_eq!(origin.bookmark_heads().unwrap(), vec![]);
1073
1074
    // Attestation with a stale serial is a rollback and is refused.
1075
    let sa = a
1076
        .sign_attest(&Attest {
1077
            repo: a.id().unwrap(),
1078
            hlc: Hlc::now(),
1079
            body: AttestBody::Ref {
1080
                name: "main".into(),
1081
                old_state: empty,
1082
                new_state: s1,
1083
                serial: 1,
1084
            },
1085
        })
1086
        .unwrap();
1087
    let r = origin
1088
        .receive_push(
1089
            Bundle::default(),
1090
            vec![RefUpdate {
1091
                name: "main".into(),
1092
                old_state: empty,
1093
                new_state: s1,
1094
                force: false,
1095
                attestation: Some(sa.clone()),
1096
            }],
1097
            None,
1098
            vec![],
1099
        )
1100
        .unwrap();
1101
    assert!(
1102
        !r[0].ok && r[0].reason.contains("serial"),
1103
        "{}",
1104
        r[0].reason
1105
    );
1106
    // An attestation for a different update is refused too.
1107
    let sa2 = a
1108
        .sign_attest(&Attest {
1109
            repo: a.id().unwrap(),
1110
            hlc: Hlc::now(),
1111
            body: AttestBody::Ref {
1112
                name: "main".into(),
1113
                old_state: s1,
1114
                new_state: empty,
1115
                serial: 5,
1116
            },
1117
        })
1118
        .unwrap();
1119
    let r = origin
1120
        .receive_push(
1121
            Bundle::default(),
1122
            vec![RefUpdate {
1123
                name: "main".into(),
1124
                old_state: empty,
1125
                new_state: s1,
1126
                force: false,
1127
                attestation: Some(sa2),
1128
            }],
1129
            None,
1130
            vec![],
1131
        )
1132
        .unwrap();
1133
    assert!(
1134
        !r[0].ok && r[0].reason.contains("describe"),
1135
        "{}",
1136
        r[0].reason
1137
    );
1138
    let _ = key;
1139
}
1140
1141
#[test]
1142
fn user_config_supplies_defaults_and_clones_sign() {
1143
    hermetic();
1144
    let dir = tempfile::tempdir().unwrap();
1145
    let root = dir.path();
1146
    let home = root.join("home");
1147
    let origin = Repo::init(&root.join("origin")).unwrap();
1148
    let url = root.join("origin").to_string_lossy().to_string();
1149
1150
    // Identity at user scope: the repository file stays free of author keys.
1151
    let mut a = Repo::init(&root.join("a")).unwrap().with_home(&home);
1152
    let (key, _) = a
1153
        .create_identity("Ada", "[email protected]", IdentityScope::User)
1154
        .unwrap();
1155
    assert!(!a.config.repo_layer().contains_key("author.key"));
1156
    assert_eq!(a.config.author_key, Some(key));
1157
    assert!(home.join("config.toml").exists());
1158
    a.set_user_config("core.sign", "change").unwrap();
1159
    assert!(a.config.sign_changes);
1160
1161
    // Repository settings override user settings and are the only ones saved.
1162
    a.config.set("core.sign", "seal").unwrap();
1163
    a.save_config().unwrap();
1164
    let again = Repo::open(&root.join("a")).unwrap().with_home(&home);
1165
    assert!(!again.config.sign_changes);
1166
    assert_eq!(again.config.author_key, Some(key));
1167
    assert_eq!(
1168
        read_config_file(&root.join("a/.oxy/config"))
1169
            .unwrap()
1170
            .get("core.sign")
1171
            .map(String::as_str),
1172
        Some("seal")
1173
    );
1174
1175
    // A fresh clone made by this user signs with the user-level identity,
1176
    // even though the clone's store has never seen the identity object.
1177
    let b = Repo::clone(&url, &root.join("b")).unwrap().with_home(&home);
1178
    assert!(b.config.sign_changes);
1179
    write(&root.join("b"), "f.txt", b"f\n");
1180
    let h = b.commit("signed from a clone", &[]).unwrap();
1181
    assert!(
1182
        matches!(b.verify_change(&h).unwrap(), SignatureStatus::Valid { key: k, .. } if k == key)
1183
    );
1184
    assert!(b.push("origin", false).unwrap()[0].ok);
1185
    assert!(matches!(
1186
        origin.verify_change(&h).unwrap(),
1187
        SignatureStatus::Valid { .. }
1188
    ));
1189
}
1190
1191
#[test]
1192
fn format1_repositories_are_migrated_on_open() {
1193
    hermetic();
1194
    use crate::oplog::{Format1Op, Format1View};
1195
    let dir = tempfile::tempdir().unwrap();
1196
    let root = dir.path();
1197
    let repo = Repo::init(root).unwrap();
1198
    write(root, "a.txt", b"a\n");
1199
    let h1 = repo.commit("one", &[]).unwrap();
1200
    let (wc_hash, _) = repo.working_copy().unwrap();
1201
    // Rewrite the op log the way format 1 stored it: two ops, head lists.
1202
    let mut v1 = Format1View::default();
1203
    v1.bookmarks.insert("main".into(), vec![]);
1204
    v1.workspaces.insert(repo.workspace(), wc_hash);
1205
    let init = Format1Op {
1206
        parents: vec![],
1207
        hlc: Hlc::default(),
1208
        command: "oxy init".into(),
1209
        view: v1.clone(),
1210
    };
1211
    let init_ref = repo.store().put(ObjectType::Op, &init.encode()).unwrap();
1212
    v1.bookmarks.insert("main".into(), vec![h1]);
1213
    let commit = Format1Op {
1214
        parents: vec![init_ref],
1215
        hlc: Hlc::default(),
1216
        command: "oxy commit".into(),
1217
        view: v1,
1218
    };
1219
    let commit_ref = repo.store().put(ObjectType::Op, &commit.encode()).unwrap();
1220
    write_atomic(&root.join(".oxy/ops/head"), commit_ref.to_hex().as_bytes()).unwrap();
1221
    write_atomic(&root.join(".oxy/format"), FORMAT1_LINE.as_bytes()).unwrap();
1222
    drop(repo);
1223
1224
    let repo = Repo::open(root).unwrap();
1225
    assert_eq!(
1226
        fs::read_to_string(root.join(".oxy/format")).unwrap(),
1227
        FORMAT_LINE
1228
    );
1229
    assert_eq!(repo.bookmark_heads().unwrap(), vec![h1]);
1230
    let ops = repo.op_log().unwrap();
1231
    assert_eq!(
1232
        ops.iter()
1233
            .map(|(_, o)| o.command.as_str())
1234
            .collect::<Vec<_>>(),
1235
        ["oxy commit", "oxy init"]
1236
    );
1237
    assert_eq!(repo.heads_of(&ops[1].1.view, "main").unwrap(), vec![]);
1238
    assert!(!repo.snapshot("status").unwrap().changed);
1239
    // Reopening again is a no-op.
1240
    assert_eq!(Repo::open(root).unwrap().op_log().unwrap().len(), 2);
1241
}
1242
1243
#[test]
1244
fn undo_skips_snapshot_operations() {
1245
    hermetic();
1246
    let dir = tempfile::tempdir().unwrap();
1247
    let root = dir.path();
1248
    let repo = Repo::init(root).unwrap();
1249
    write(root, "a.txt", b"a\n");
1250
    let h1 = repo.commit("a", &[]).unwrap();
1251
    // A later command snapshots new edits on top of the commit.
1252
    write(root, "b.txt", b"b\n");
1253
    let s = repo.snapshot("oxy status").unwrap();
1254
    assert!(s.changed);
1255
    assert!(repo.head_op().unwrap().1.is_snapshot());
1256
    assert_eq!(repo.last_command().unwrap().command, "oxy commit -m \"a\"");
1257
    // Undo must undo the commit, not the snapshot.
1258
    repo.undo().unwrap();
1259
    assert_eq!(repo.bookmark_heads().unwrap(), vec![]);
1260
    let s = repo.snapshot("oxy status").unwrap();
1261
    let paths: Vec<_> = s.statuses.iter().map(|p| p.path.as_str()).collect();
1262
    assert_eq!(
1263
        paths,
1264
        ["a.txt", "b.txt"],
1265
        "both files are back in the working copy"
1266
    );
1267
    assert!(repo.store().get_change(&h1).unwrap().deps.is_empty());
1268
    // Only snapshots remain above `init`, so there is nothing left to undo.
1269
    assert_eq!(repo.last_command().unwrap().command, "oxy init");
1270
    assert!(repo.undo().is_err());
1271
}
1272
1273
#[test]
1274
fn independent_changes_commute_and_make_multiple_heads() {
1275
    hermetic();
1276
    let dir = tempfile::tempdir().unwrap();
1277
    let root = dir.path();
1278
    let repo = Repo::init(root).unwrap();
1279
    write(root, "a.txt", b"a\n");
1280
    let h1 = repo.commit("a", &[]).unwrap();
1281
    write(root, "b.txt", b"b\n");
1282
    let h2 = repo.commit("b", &[]).unwrap();
1283
    let c2 = repo.store().get_change(&h2).unwrap();
1284
    assert!(c2.deps.is_empty(), "b.txt touches nothing from h1");
1285
    let mut heads = repo.bookmark_heads().unwrap();
1286
    heads.sort();
1287
    let mut want = vec![h1, h2];
1288
    want.sort();
1289
    assert_eq!(heads, want);
1290
    // Editing a.txt depends on h1 only.
1291
    write(root, "a.txt", b"a\na2\n");
1292
    let h3 = repo.commit("a2", &[]).unwrap();
1293
    assert_eq!(repo.store().get_change(&h3).unwrap().deps, vec![h1]);
1294
    let heads: BTreeSet<_> = repo.bookmark_heads().unwrap().into_iter().collect();
1295
    assert_eq!(heads, [h2, h3].into_iter().collect());
1296
    // Explicit dependency.
1297
    write(root, "c.txt", b"c\n");
1298
    let h4 = repo.commit("c", &[h2]).unwrap();
1299
    assert_eq!(repo.store().get_change(&h4).unwrap().deps, vec![h2]);
1300
}
1301
1302
#[test]
1303
fn mode_change_and_text_binary_switch() {
1304
    hermetic();
1305
    let dir = tempfile::tempdir().unwrap();
1306
    let root = dir.path();
1307
    let repo = Repo::init(root).unwrap();
1308
    write(root, "run.sh", b"#!/bin/sh\n");
1309
    repo.commit("add script", &[]).unwrap();
1310
    #[cfg(unix)]
1311
    {
1312
        use std::os::unix::fs::PermissionsExt;
1313
        fs::set_permissions(root.join("run.sh"), fs::Permissions::from_mode(0o755)).unwrap();
1314
        let s = repo.snapshot("status").unwrap();
1315
        assert_eq!(
1316
            statuses(&s),
1317
            vec![("run.sh".into(), ChangeStatus::ModeChanged)]
1318
        );
1319
        let h = repo.commit("exec", &[]).unwrap();
1320
        let snap = repo.load_state(&[h]).unwrap().materialize();
1321
        assert!(snap.files["run.sh"].mode.exec);
1322
    }
1323
    // Text → binary → text.
1324
    write(root, "run.sh", b"\0binary");
1325
    let h = repo.commit("binary", &[]).unwrap();
1326
    let snap = repo.load_state(&[h]).unwrap().materialize();
1327
    assert!(snap.files["run.sh"].mode.opaque);
1328
    write(root, "run.sh", b"text again\n");
1329
    let h = repo.commit("text", &[]).unwrap();
1330
    let snap = repo.load_state(&[h]).unwrap().materialize();
1331
    assert!(!snap.files["run.sh"].mode.opaque);
1332
    assert!(
1333
        matches!(&snap.files["run.sh"].content, FileContent::Text { bytes, .. } if bytes == b"text again\n")
1334
    );
1335
    assert!(!snap.is_conflicted());
1336
}
1337
1338
/// oxygen#87: a binary file given new contents and the executable bit in
1339
/// one commit kept the contents and lost the bit.
1340
#[cfg(unix)]
1341
#[test]
1342
fn a_binary_file_changed_and_made_executable_at_once_keeps_both() {
1343
    use std::os::unix::fs::PermissionsExt;
1344
    hermetic();
1345
    let dir = tempfile::tempdir().unwrap();
1346
    let root = dir.path();
1347
    let repo = Repo::init(root).unwrap();
1348
    write(root, "tool.exe", b"MZ\0one");
1349
    repo.commit("add", &[]).unwrap();
1350
    write(root, "tool.exe", b"MZ\0two");
1351
    fs::set_permissions(root.join("tool.exe"), fs::Permissions::from_mode(0o755)).unwrap();
1352
    let h = repo.commit("update and +x", &[]).unwrap();
1353
    let snap = repo.load_state(&[h]).unwrap().materialize();
1354
    let f = &snap.files["tool.exe"];
1355
    assert!(f.mode.opaque && f.mode.exec, "{:?}", f.mode);
1356
    assert!(
1357
        repo.snapshot("status").unwrap().statuses.is_empty(),
1358
        "nothing left to commit"
1359
    );
1360
}
1361
1362
/// Keyless step 4 (oxygenhub#241): an agent signing with a short-lived
1363
/// key whose certificate an issuer gave pushes when the policy grants its
1364
/// subject, and a fetch accepts what it attested; an expired certificate,
1365
/// or a subject the policy does not grant, may not move the bookmark.
1366
#[test]
1367
fn a_certified_key_pushes_under_a_subject_grant() {
1368
    use crate::cert::{Certificate, SignedCertificate};
1369
    use crate::identity::Scope;
1370
    hermetic();
1371
    let dir = tempfile::tempdir().unwrap();
1372
    let root = dir.path();
1373
    let _origin = Repo::init(&root.join("origin")).unwrap();
1374
    let url = root.join("origin").to_string_lossy().to_string();
1375
    let mut a = Repo::clone(&url, &root.join("a"))
1376
        .unwrap()
1377
        .with_home(root.join("home-a"));
1378
    a.create_identity("Ada", "[email protected]", IdentityScope::User)
1379
        .unwrap();
1380
    write(&root.join("a"), "a.txt", b"a\n");
1381
    a.commit("a", &[]).unwrap();
1382
    a.policy_init().unwrap();
1383
    assert!(a.push("origin", false).unwrap().iter().all(|r| r.ok));
1384
    let hub_sk = SecretKey::generate();
1385
    let hub = hub_sk.identity("hub", "[email protected]", 1);
1386
    a.policy_grant_subject(
1387
        "agent:claude@ada",
1388
        hub.clone(),
1389
        Scope::CHANGES | Scope::REFS,
1390
        None,
1391
    )
1392
    .unwrap();
1393
    assert!(a
1394
        .push("origin", false)
1395
        .unwrap()
1396
        .iter()
1397
        .any(|r| r.name == "policy" && r.ok));
1398
1399
    let now = Hlc::now().wall_ms;
1400
    // An agent repository whose key the hub certified for `subject`, from
1401
    // `from` to `to`.
1402
    let agent = |name: &str, subject: &str, from: u64, to: u64| {
1403
        let mut r = Repo::clone(&url, &root.join(name))
1404
            .unwrap()
1405
            .with_home(root.join(format!("home-{name}")));
1406
        let (_, id) = r
1407
            .create_identity(name, "[email protected]", IdentityScope::User)
1408
            .unwrap();
1409
        let cert = SignedCertificate::sign(
1410
            Certificate {
1411
                key: id,
1412
                issuer: hub.hash(),
1413
                subject: subject.into(),
1414
                claims: vec![],
1415
                scope: Scope::CHANGES | Scope::REFS,
1416
                not_before: from,
1417
                expires: to,
1418
                grant: None,
1419
            },
1420
            &hub,
1421
            &hub_sk,
1422
        );
1423
        r.store().put_identity(&hub).unwrap();
1424
        r.store().put_certificate(&cert).unwrap();
1425
        write(&root.join(name), &format!("{name}.txt"), b"agent work\n");
1426
        r.commit("work", &[]).unwrap();
1427
        r
1428
    };
1429
1430
    let claude = agent("claude", "agent:claude@ada", now - 60_000, now + 600_000);
1431
    let r = claude.push("origin", false).unwrap();
1432
    assert!(r.iter().all(|x| x.ok), "{r:?}");
1433
    // Ada's fetch accepts the bookmark the certified key attested.
1434
    a.pull("origin").unwrap();
1435
    assert!(a.bookmark_heads().unwrap().iter().any(|h| a
1436
        .store()
1437
        .get_change(h)
1438
        .map(|c| c.message == "work")
1439
        .unwrap_or(false)));
1440
1441
    // Step 4c: a host with an acceptor key records when it accepted the
1442
    // certified update and serves it; a fetch checks the certificate at
1443
    // that time only when the certificate's issuer signed it for exactly
1444
    // this attestation, else at the attestation's own time.
1445
    let host = Repo::open(&root.join("origin"))
1446
        .unwrap()
1447
        .with_acceptor(hub.clone(), hub_sk.clone());
1448
    let (attest_ref, sa) = host.latest_ref_attest("main").unwrap().unwrap();
1449
    host.record_acceptance(&attest_ref).unwrap();
1450
    let served = host.remote_refs().unwrap();
1451
    let acc = served
1452
        .refs
1453
        .iter()
1454
        .find(|r| r.name == "main")
1455
        .unwrap()
1456
        .accepted
1457
        .clone()
1458
        .expect("served with the refs");
1459
    let signer = sa.sigs[0].key;
1460
    assert_eq!(
1461
        a.certified_time(&signer, &sa, Some(&acc)),
1462
        acc.attest.hlc.wall_ms
1463
    );
1464
    assert_eq!(a.certified_time(&signer, &sa, None), sa.attest.hlc.wall_ms);
1465
    let stranger_sk = SecretKey::generate();
1466
    let stranger = stranger_sk.identity("stranger", "s@x", 1);
1467
    let mut forged = acc.clone();
1468
    forged.sigs = vec![stranger_sk.sign(Domain::Attest, &stranger.hash(), &acc.attest.hash())];
1469
    assert_eq!(
1470
        a.certified_time(&signer, &sa, Some(&forged)),
1471
        sa.attest.hlc.wall_ms,
1472
        "not the issuer's"
1473
    );
1474
    let mut elsewhere = acc.clone();
1475
    elsewhere.attest.body = AttestBody::Accepted {
1476
        attest: ObjectRef([7; 32]),
1477
    };
1478
    elsewhere.sigs = vec![hub_sk.sign(Domain::Attest, &hub.hash(), &elsewhere.attest.hash())];
1479
    assert_eq!(
1480
        a.certified_time(&signer, &sa, Some(&elsewhere)),
1481
        sa.attest.hlc.wall_ms,
1482
        "another attestation's"
1483
    );
1484
    a.pull("origin").unwrap();
1485
    // gc keeps the acceptance with the attestation.
1486
    host.gc(true).unwrap();
1487
    assert!(host.acceptance_of(&attest_ref).unwrap().is_some());
1488
1489
    let late = agent("late", "agent:claude@ada", now - 1_200_000, now - 600_000);
1490
    let r = late.push("origin", false).unwrap();
1491
    assert!(
1492
        !r[0].ok && r[0].reason.contains("may not update"),
1493
        "an expired certificate: {r:?}"
1494
    );
1495
    let other = agent("other", "agent:mallory@ada", now - 60_000, now + 600_000);
1496
    let r = other.push("origin", false).unwrap();
1497
    assert!(
1498
        !r[0].ok && r[0].reason.contains("may not update"),
1499
        "a subject not granted: {r:?}"
1500
    );
1501
}
1502
1503
/// Keyless step 5 (oxygenhub#241): an agent's fresh key, certified for a
1504
/// subject the author granted, seals changes in the author's name; with
1505
/// no grant, a stranger's, or one that had ended, it is neither the
1506
/// author nor a delegate.
1507
#[test]
1508
fn a_certified_key_acts_for_its_author_under_a_grant() {
1509
    use crate::cert::{Certificate, Grant, SignedCertificate, SignedGrant};
1510
    use crate::identity::{Identity, Scope};
1511
    hermetic();
1512
    let dir = tempfile::tempdir().unwrap();
1513
    let root = dir.path();
1514
    let _origin = Repo::init(&root.join("origin")).unwrap();
1515
    let url = root.join("origin").to_string_lossy().to_string();
1516
    let mut a = Repo::clone(&url, &root.join("a"))
1517
        .unwrap()
1518
        .with_home(root.join("home-a"));
1519
    let (ada, _) = a
1520
        .create_identity("Ada", "[email protected]", IdentityScope::User)
1521
        .unwrap();
1522
    write(&root.join("a"), "a.txt", b"a\n");
1523
    a.commit("a", &[]).unwrap();
1524
    a.policy_init().unwrap();
1525
    assert!(a.push("origin", false).unwrap().iter().all(|r| r.ok));
1526
    let hub_sk = SecretKey::generate();
1527
    let hub = hub_sk.identity("hub", "[email protected]", 1);
1528
    a.policy_grant_subject(
1529
        "agent:claude@ada",
1530
        hub.clone(),
1531
        Scope::CHANGES | Scope::REFS,
1532
        None,
1533
    )
1534
    .unwrap();
1535
    assert!(a.push("origin", false).unwrap().iter().all(|r| r.ok));
1536
    let (_, ada_sk) = a.secret_key().unwrap().unwrap();
1537
    let ada_id = a.identity(&ada).unwrap();
1538
1539
    let now = Hlc::now().wall_ms;
1540
    let grant = |by: &Identity, sk: &SecretKey, from: u64, to: u64| {
1541
        SignedGrant::sign(
1542
            Grant {
1543
                grantor: by.hash(),
1544
                subject: "agent:claude@ada".into(),
1545
                issuer: hub.hash(),
1546
                scope: Scope::CHANGES | Scope::SEAL,
1547
                not_before: from,
1548
                expires: to,
1549
            },
1550
            by,
1551
            sk,
1552
        )
1553
    };
1554
    // Ada's work as an agent runs it: Ada the author, a fresh key the hub
1555
    // certified (with `g` inside) the signer.
1556
    let agent = |name: &str, g: Option<SignedGrant>| {
1557
        let mut r = Repo::clone(&url, &root.join(name))
1558
            .unwrap()
1559
            .with_home(root.join(format!("home-{name}")));
1560
        let (key, id) = r
1561
            .create_identity(name, "[email protected]", IdentityScope::User)
1562
            .unwrap();
1563
        r.set_user_config("author.key", &ada.to_hex()).unwrap();
1564
        r.set_user_config("author.signer", &key.to_hex()).unwrap();
1565
        let cert = SignedCertificate::sign(
1566
            Certificate {
1567
                key: id,
1568
                issuer: hub.hash(),
1569
                subject: "agent:claude@ada".into(),
1570
                claims: vec![],
1571
                scope: Scope::CHANGES | Scope::REFS | Scope::SEAL,
1572
                not_before: now - 60_000,
1573
                expires: now + 600_000,
1574
                grant: g,
1575
            },
1576
            &hub,
1577
            &hub_sk,
1578
        );
1579
        r.store().put_identity(&hub).unwrap();
1580
        r.store().put_certificate(&cert).unwrap();
1581
        write(&root.join(name), &format!("{name}.txt"), b"agent work\n");
1582
        let h = r.commit("work", &[]).unwrap();
1583
        assert_eq!(r.store().get_change_meta(&h).unwrap().author, ada);
1584
        (r, key, h)
1585
    };
1586
1587
    let (claude, key, h) = agent(
1588
        "claude",
1589
        Some(grant(&ada_id, &ada_sk, now - 60_000, now + 86_400_000)),
1590
    );
1591
    let r = claude.push("origin", false).unwrap();
1592
    assert!(r.iter().all(|x| x.ok), "{r:?}");
1593
    let host = Repo::open(&root.join("origin")).unwrap();
1594
    assert!(
1595
        matches!(
1596
            host.authenticate_change(&h).unwrap(),
1597
            SignatureStatus::Valid { key: k, sealed: true, name, .. } if k == key && name == "agent:claude@ada"
1598
        ),
1599
        "named by its certificate's subject"
1600
    );
1601
    a.pull("origin").unwrap();
1602
    assert!(matches!(
1603
        a.authenticate_change(&h).unwrap(),
1604
        SignatureStatus::Valid { key: k, .. } if k == key
1605
    ));
1606
1607
    let (none, _, _) = agent("none", None);
1608
    let r = none.push("origin", false).unwrap();
1609
    assert!(r.iter().all(|x| !x.ok), "no grant: {r:?}");
1610
    let mallory_sk = SecretKey::generate();
1611
    let mallory = mallory_sk.identity("Mallory", "[email protected]", 1);
1612
    let (stranger, _, _) = agent(
1613
        "stranger",
1614
        Some(grant(&mallory, &mallory_sk, now - 60_000, now + 600_000)),
1615
    );
1616
    let r = stranger.push("origin", false).unwrap();
1617
    assert!(r.iter().all(|x| !x.ok), "a stranger's grant: {r:?}");
1618
    let (ended, _, eh) = agent(
1619
        "ended",
1620
        Some(grant(&ada_id, &ada_sk, now - 7_200_000, now - 3_600_000)),
1621
    );
1622
    let r = ended.push("origin", false).unwrap();
1623
    assert!(r.iter().all(|x| !x.ok), "an ended grant: {r:?}");
1624
    assert!(matches!(
1625
        ended.authenticate_change(&eh).unwrap(),
1626
        SignatureStatus::Invalid(e) if e.contains("grant did not cover")
1627
    ));
1628
}
1629
1630
#[test]
1631
fn trust_policy_governs_pushes_and_fetches() {
1632
    hermetic();
1633
    let dir = tempfile::tempdir().unwrap();
1634
    let root = dir.path();
1635
    let origin = Repo::init(&root.join("origin")).unwrap();
1636
    let url = root.join("origin").to_string_lossy().to_string();
1637
1638
    // A is the root. Before the policy, an unsigned push from B is fine.
1639
    let mut a = Repo::clone(&url, &root.join("a"))
1640
        .unwrap()
1641
        .with_home(root.join("home-a"));
1642
    let (key_a, _) = a
1643
        .create_identity("Ada", "[email protected]", IdentityScope::User)
1644
        .unwrap();
1645
    let mut b = Repo::clone(&url, &root.join("b"))
1646
        .unwrap()
1647
        .with_home(root.join("home-b"));
1648
    write(&root.join("b"), "b.txt", b"b\n");
1649
    b.commit("unsigned before policy", &[]).unwrap();
1650
    assert!(b.push("origin", false).unwrap()[0].ok);
1651
    origin.refresh().unwrap();
1652
1653
    // A creates the policy and pushes it; origin now enforces it.
1654
    write(&root.join("a"), "a.txt", b"a\n");
1655
    a.commit("a", &[]).unwrap();
1656
    let sp = a.policy_init().unwrap();
1657
    assert_eq!(sp.policy.serial, 1);
1658
    a.pull("origin").unwrap();
1659
    let results = a.push("origin", false).unwrap();
1660
    origin.refresh().unwrap();
1661
    assert!(results.iter().all(|r| r.ok), "{results:?}");
1662
    assert_eq!(origin.current_policy().unwrap().unwrap().1.policy.serial, 1);
1663
1664
    // B pulls the policy. Without an identity B cannot push at all.
1665
    b.pull("origin").unwrap();
1666
    assert!(
1667
        b.current_policy().unwrap().is_some(),
1668
        "the policy arrived with the fetch"
1669
    );
1670
    assert!(b.push("origin", false).is_err());
1671
    // With an identity the policy does not list, the push is rejected by origin.
1672
    let (key_b, id_b) = b
1673
        .create_identity("Bob", "[email protected]", IdentityScope::User)
1674
        .unwrap();
1675
    write(&root.join("b"), "b.txt", b"b2\n");
1676
    let h_b2 = b.commit("b2 as Bob", &[]).unwrap();
1677
    assert_eq!(b.store().get_change(&h_b2).unwrap().author, key_b);
1678
    let r = b.push("origin", false).unwrap();
1679
    origin.refresh().unwrap();
1680
    assert!(
1681
        !r[0].ok && r[0].reason.contains("may not update"),
1682
        "{:?}",
1683
        r
1684
    );
1685
1686
    // A grants B (identity handed over as a file) and publishes the policy.
1687
    let sp = a.policy_grant(id_b.clone(), None).unwrap();
1688
    assert_eq!(sp.policy.serial, 2);
1689
    let r = a.push("origin", false).unwrap();
1690
    origin.refresh().unwrap();
1691
    assert!(r.iter().any(|x| x.name == "policy" && x.ok), "{r:?}");
1692
    // B must fetch the new policy before pushing.
1693
    assert!(b
1694
        .push("origin", false)
1695
        .unwrap_or_else(|e| vec![RefResult {
1696
            name: "main".into(),
1697
            ok: false,
1698
            reason: e.to_string()
1699
        }])
1700
        .iter()
1701
        .all(|x| !x.ok));
1702
    b.pull("origin").unwrap();
1703
    assert_eq!(b.current_policy().unwrap().unwrap().1.policy.serial, 2);
1704
    let r = b.push("origin", false).unwrap();
1705
    origin.refresh().unwrap();
1706
    assert!(r[0].ok, "{:?}", r);
1707
    // Origin verified B's change under the policy.
1708
    let heads = origin.bookmark_heads().unwrap();
1709
    for h in &heads {
1710
        let c = origin.store().get_change(h).unwrap();
1711
        if c.author == key_b {
1712
            origin
1713
                .change_allowed(
1714
                    h,
1715
                    &origin.current_policy().unwrap().unwrap().1.policy,
1716
                    "main",
1717
                )
1718
                .unwrap();
1719
        }
1720
    }
1721
1722
    // A policy signed by a non-root (B) is refused, as is a replayed serial.
1723
    let mut forged = b.current_policy().unwrap().unwrap().1.policy.clone();
1724
    forged.serial = 3;
1725
    forged.roots = vec![key_b];
1726
    let fh = forged.hash();
1727
    let (_, sk_b) = b.secret_key().unwrap().unwrap();
1728
    let forged = SignedPolicy {
1729
        policy: forged,
1730
        sigs: vec![sk_b.sign(Domain::Policy, &key_b, &fh)],
1731
    };
1732
    let r = origin
1733
        .receive_push(Bundle::default(), vec![], Some(forged), vec![])
1734
        .unwrap();
1735
    assert!(!r[0].ok && r[0].reason.contains("root"), "{:?}", r);
1736
    let stale = a.current_policy().unwrap().unwrap().1;
1737
    let mut old = stale.clone();
1738
    old.policy.serial = 1;
1739
    let r = origin
1740
        .receive_push(Bundle::default(), vec![], Some(old), vec![])
1741
        .unwrap();
1742
    assert!(!r[0].ok && r[0].reason.contains("serial"), "{:?}", r);
1743
1744
    // A revokes B; after B pulls the policy, B's pushes are refused again.
1745
    a.pull("origin").unwrap();
1746
    a.policy_revoke(&key_b).unwrap();
1747
    let r = a.push("origin", false).unwrap();
1748
    origin.refresh().unwrap();
1749
    assert!(r.iter().any(|x| x.name == "policy" && x.ok), "{r:?}");
1750
    b.pull("origin").unwrap();
1751
    write(&root.join("b"), "b.txt", b"b3\n");
1752
    b.commit("b3", &[]).unwrap();
1753
    let r = b.push("origin", false).unwrap();
1754
    origin.refresh().unwrap();
1755
    assert!(!r[0].ok, "{:?}", r);
1756
1757
    // A clone by a third party receives and verifies everything.
1758
    let c = Repo::clone(&url, &root.join("c"))
1759
        .unwrap()
1760
        .with_home(root.join("home-c"));
1761
    assert_eq!(c.current_policy().unwrap().unwrap().1.policy.serial, 3);
1762
    assert!(c
1763
        .current_policy()
1764
        .unwrap()
1765
        .unwrap()
1766
        .1
1767
        .policy
1768
        .roots
1769
        .contains(&key_a));
1770
    assert!(!c.snapshot("status").unwrap().changed);
1771
}
1772
1773
/// oxygen#66: a gc says what it is doing, phase by phase.
1774
#[test]
1775
fn gc_reports_its_phases() {
1776
    hermetic();
1777
    let dir = tempfile::tempdir().unwrap();
1778
    let repo = Repo::init(dir.path()).unwrap();
1779
    for i in 0..3 {
1780
        write(
1781
            dir.path(),
1782
            &format!("f{i}.txt"),
1783
            format!("{i}\n").as_bytes(),
1784
        );
1785
        repo.commit(&format!("c{i}"), &[]).unwrap();
1786
    }
1787
    let mut phases = Vec::new();
1788
    repo.gc_with(true, &mut |p| phases.push(p.to_string()))
1789
        .unwrap();
1790
    assert_eq!(phases[0], "finding what is reachable", "{phases:?}");
1791
    assert!(
1792
        phases.iter().any(|p| p.starts_with("pruning")),
1793
        "{phases:?}"
1794
    );
1795
    assert!(
1796
        phases.iter().any(|p| p.starts_with("packing 0 of ")),
1797
        "{phases:?}"
1798
    );
1799
    assert!(
1800
        phases
1801
            .iter()
1802
            .any(|p| p.starts_with("writing the index of ")),
1803
        "{phases:?}"
1804
    );
1805
}
1806
1807
#[test]
1808
fn gc_packs_objects_and_history_still_works() {
1809
    hermetic();
1810
    let dir = tempfile::tempdir().unwrap();
1811
    let root = dir.path();
1812
    let mut repo = Repo::init(root).unwrap().with_home(root.join("home"));
1813
    repo.create_identity("Ada", "a@b", IdentityScope::User)
1814
        .unwrap();
1815
    repo.set_user_config("core.sign", "change").unwrap();
1816
    write(root, "a.txt", b"one\n");
1817
    let h1 = repo.commit("one", &[]).unwrap();
1818
    write(root, "a.txt", b"two\n");
1819
    write(root, "big.bin", &vec![0u8; 100_000]);
1820
    let h2 = repo.commit("two", &[]).unwrap();
1821
    // Several snapshots leave superseded working-copy versions behind.
1822
    for i in 0..5 {
1823
        write(root, "a.txt", format!("two\n{i}\n").as_bytes());
1824
        repo.snapshot("status").unwrap();
1825
    }
1826
    write(root, "a.txt", b"two\n");
1827
    repo.snapshot("status").unwrap();
1828
    let before = repo.store().list().unwrap();
1829
    assert!(repo.store().loose_count().unwrap() > 0);
1830
1831
    // With the default retention every operation's view is a root: nothing prunes.
1832
    let r = repo.gc(true).unwrap();
1833
    assert_eq!(r.packed.objects, before.len());
1834
    assert_eq!(r.pruned.objects, 0);
1835
    assert_eq!(repo.store().loose_count().unwrap(), 0);
1836
    assert_eq!(repo.store().list().unwrap(), before);
1837
1838
    // With zero retention only the current view is a root: superseded
1839
    // working copies go, everything reachable stays.
1840
    repo.config.set("core.op-retention", "0").unwrap();
1841
    repo.save_config().unwrap();
1842
    let mut repo = Repo::open(root).unwrap().with_home(root.join("home"));
1843
    let r = repo.gc(true).unwrap();
1844
    assert!(r.pruned.objects >= 5, "{r:?}");
1845
    let after = repo.store().list().unwrap();
1846
    assert!(after.len() < before.len());
1847
    assert!(after.contains(&h1) && after.contains(&h2));
1848
    for (_, op) in repo.op_log().unwrap() {
1849
        assert!(!op.command.is_empty(), "operation objects are all kept");
1850
    }
1851
    // Everything still works from the pruned, packed store.
1852
    assert_eq!(repo.bookmark_heads().unwrap(), vec![h2]);
1853
    assert!(matches!(
1854
        repo.verify_change(&h2).unwrap(),
1855
        SignatureStatus::Valid { .. }
1856
    ));
1857
    assert_eq!(repo.log().unwrap().len(), 3);
1858
    repo.checkout(&[h1], false, "checkout").unwrap();
1859
    assert_eq!(fs::read(root.join("a.txt")).unwrap(), b"one\n");
1860
    repo.checkout(&[h2], false, "checkout").unwrap();
1861
    assert_eq!(fs::read(root.join("big.bin")).unwrap().len(), 100_000);
1862
    assert!(!repo.snapshot("status").unwrap().changed);
1863
    // Grace period defers pruning of young garbage.
1864
    write(root, "a.txt", b"three\n");
1865
    repo.commit("three", &[]).unwrap();
1866
    let r = repo.gc(false).unwrap();
1867
    assert_eq!(r.pruned.objects, 0);
1868
    assert!(r.pruned.deferred > 0);
1869
    let r = repo.gc(true).unwrap();
1870
    assert!(r.pruned.objects > 0);
1871
    assert_eq!(repo.log().unwrap().len(), 4);
1872
    // Restoring the default retention makes the old views roots again; the
1873
    // working copies they name were pruned, which gc tolerates.
1874
    repo.config.set("core.op-retention", "90").unwrap();
1875
    repo.save_config().unwrap();
1876
    let repo = Repo::open(root).unwrap().with_home(root.join("home"));
1877
    let r = repo.gc(false).unwrap();
1878
    assert_eq!(r.pruned.objects, 0);
1879
    assert_eq!(repo.log().unwrap().len(), 4);
1880
}
1881
1882
#[test]
1883
fn describe_amend_abandon_heads() {
1884
    hermetic();
1885
    let dir = tempfile::tempdir().unwrap();
1886
    let root = dir.path();
1887
    let mut repo = Repo::init(root).unwrap().with_home(root.join("home"));
1888
    repo.create_identity("Ada", "a@b", IdentityScope::User)
1889
        .unwrap();
1890
    repo.set_user_config("core.sign", "change").unwrap();
1891
    write(root, "a.txt", b"one\n");
1892
    let h1 = repo.commit("first", &[]).unwrap();
1893
    write(root, "a.txt", b"one\ntwo\n");
1894
    let h2 = repo.commit("secnod", &[]).unwrap();
1895
    let id2 = repo.store().get_change(&h2).unwrap().change_id;
1896
1897
    // describe: same ChangeId, new hash, bookmark and working copy follow.
1898
    let h2b = repo.describe(&h2, "second").unwrap();
1899
    assert_ne!(h2b, h2);
1900
    let c = repo.store().get_change(&h2b).unwrap();
1901
    assert_eq!(
1902
        (c.change_id, c.message.as_str(), c.deps.clone()),
1903
        (id2, "second", vec![h1])
1904
    );
1905
    assert_eq!(repo.bookmark_heads().unwrap(), vec![h2b]);
1906
    assert!(matches!(
1907
        repo.verify_change(&h2b).unwrap(),
1908
        SignatureStatus::Valid { .. }
1909
    ));
1910
    let s = repo.snapshot("status").unwrap();
1911
    assert!(s.statuses.is_empty(), "{:?}", s.statuses);
1912
    assert_eq!(
1913
        repo.resolve_change(&id2.short(8)).unwrap(),
1914
        h2b,
1915
        "the old object is no longer reachable from the log"
1916
    );
1917
    // Describing a non-head rewrites its dependents (h2b → h2c') and the working copy.
1918
    let h1b = repo.describe(&h1, "first, described").unwrap();
1919
    assert_ne!(h1b, h1);
1920
    let heads = repo.bookmark_heads().unwrap();
1921
    assert_eq!(heads.len(), 1);
1922
    let top = repo.store().get_change(&heads[0]).unwrap();
1923
    assert_eq!((top.change_id, top.deps.clone()), (id2, vec![h1b]));
1924
    assert!(
1925
        matches!(
1926
            repo.verify_change(&heads[0]).unwrap(),
1927
            SignatureStatus::Valid { .. }
1928
        ),
1929
        "rewritten own change is re-signed"
1930
    );
1931
    let (_, wc) = repo.working_copy().unwrap();
1932
    assert_eq!(
1933
        wc.deps,
1934
        vec![heads[0]],
1935
        "the working copy follows the rewrite"
1936
    );
1937
    assert!(!repo.snapshot("status").unwrap().changed);
1938
    let snap = repo.load_state(&heads).unwrap().materialize();
1939
    assert!(
1940
        matches!(&snap.files["a.txt"].content, FileContent::Text { bytes, .. } if bytes == b"one\ntwo\n")
1941
    );
1942
1943
    // amend: fold an edit into the head; the result is one change from h1.
1944
    write(root, "a.txt", b"one\ntwo\nthree\n");
1945
    write(root, "b.txt", b"b\n");
1946
    let h2c = repo.amend(None).unwrap();
1947
    let c = repo.store().get_change(&h2c).unwrap();
1948
    assert_eq!(c.change_id, id2);
1949
    assert_eq!(c.message, "second");
1950
    assert_eq!(repo.bookmark_heads().unwrap(), vec![h2c]);
1951
    assert_eq!(
1952
        repo.log().unwrap().len(),
1953
        3,
1954
        "working copy, amended head, first"
1955
    );
1956
    let snap = repo.load_state(&[h2c]).unwrap().materialize();
1957
    assert!(
1958
        matches!(&snap.files["a.txt"].content, FileContent::Text { bytes, .. } if bytes == b"one\ntwo\nthree\n")
1959
    );
1960
    assert!(snap.files.contains_key("b.txt"));
1961
    assert!(!repo.snapshot("status").unwrap().changed);
1962
    assert!(
1963
        repo.amend(None).is_err(),
1964
        "clean working copy and no message"
1965
    );
1966
    let h2d = repo.amend(Some("second, amended")).unwrap();
1967
    assert_eq!(
1968
        repo.store().get_change(&h2d).unwrap().message,
1969
        "second, amended"
1970
    );
1971
1972
    // abandon: the head goes, its content stays as uncommitted work.
1973
    repo.abandon(&h2d).unwrap();
1974
    assert_eq!(
1975
        repo.bookmark_heads().unwrap(),
1976
        vec![h1b],
1977
        "the described first change is the head again"
1978
    );
1979
    let s = repo.snapshot("status").unwrap();
1980
    let paths: Vec<_> = s
1981
        .statuses
1982
        .iter()
1983
        .map(|p| (p.path.as_str(), p.status))
1984
        .collect();
1985
    assert_eq!(
1986
        paths,
1987
        vec![
1988
            ("a.txt", ChangeStatus::Modified),
1989
            ("b.txt", ChangeStatus::Added)
1990
        ]
1991
    );
1992
    assert_eq!(fs::read(root.join("a.txt")).unwrap(), b"one\ntwo\nthree\n");
1993
    let h3 = repo.commit("recommitted", &[]).unwrap();
1994
    assert_eq!(repo.bookmark_heads().unwrap(), vec![h3]);
1995
    // undo brings the abandoned head back.
1996
    repo.undo().unwrap();
1997
    repo.undo().unwrap();
1998
    assert_eq!(repo.bookmark_heads().unwrap(), vec![h2d]);
1999
2000
    // Abandoning a non-head whose dependent references its atoms reifies
2001
    // the references (here: a.txt vanishes with it, so the dependent's edit
2002
    // of a.txt is dropped with a note) instead of refusing; undo restores it.
2003
    let base = repo.bookmark_heads().unwrap()[0];
2004
    let base_change = repo.store().get_change(&base).unwrap();
2005
    let h1_now = base_change.deps[0];
2006
    let notes = repo.abandon(&h1_now).unwrap();
2007
    assert!(
2008
        !notes.is_empty(),
2009
        "the dependent's edit of a.txt was reified"
2010
    );
2011
    let heads = repo.bookmark_heads().unwrap();
2012
    let after = repo.load_state(&heads).unwrap().materialize();
2013
    assert!(
2014
        !after.files.contains_key("a.txt") && after.files.contains_key("b.txt"),
2015
        "{:?}",
2016
        after.files.keys()
2017
    );
2018
    repo.undo().unwrap();
2019
    assert_eq!(repo.bookmark_heads().unwrap(), vec![base]);
2020
    write(root, "c.txt", b"c\n");
2021
    let hc = repo.commit("c", &[]).unwrap();
2022
    write(root, "d.txt", b"d\n");
2023
    let hd = repo.commit("d", &[hc]).unwrap();
2024
    assert_eq!(repo.store().get_change(&hd).unwrap().deps, vec![hc]);
2025
    repo.abandon(&hc).unwrap();
2026
    let heads: BTreeSet<_> = repo.bookmark_heads().unwrap().into_iter().collect();
2027
    assert!(!heads.contains(&hc));
2028
    let d_now = heads
2029
        .iter()
2030
        .find(|h| repo.store().get_change(h).unwrap().message == "d")
2031
        .copied()
2032
        .unwrap();
2033
    assert!(
2034
        repo.store().get_change(&d_now).unwrap().deps.is_empty(),
2035
        "d inherited c's (empty) dependencies"
2036
    );
2037
    let s = repo.snapshot("status").unwrap();
2038
    assert_eq!(
2039
        s.statuses
2040
            .iter()
2041
            .map(|p| p.path.as_str())
2042
            .collect::<Vec<_>>(),
2043
        vec!["c.txt"],
2044
        "c's content is now uncommitted work"
2045
    );
2046
}
2047
2048
#[test]
2049
fn git_export_mirrors_history() {
2050
    hermetic();
2051
    if std::process::Command::new("git")
2052
        .arg("--version")
2053
        .output()
2054
        .is_err()
2055
    {
2056
        eprintln!("git not installed; skipping");
2057
        return;
2058
    }
2059
    let dir = tempfile::tempdir().unwrap();
2060
    let root = dir.path();
2061
    let mut repo = Repo::init(&root.join("r"))
2062
        .unwrap()
2063
        .with_home(root.join("home"));
2064
    repo.create_identity("Ada Lovelace", "[email protected]", IdentityScope::User)
2065
        .unwrap();
2066
    let r = root.join("r");
2067
    write(&r, "README.md", b"hello\n");
2068
    write(&r, "src/main.rs", b"fn main() {}\n");
2069
    let h1 = repo.commit("first", &[]).unwrap();
2070
    write(&r, "src/main.rs", b"fn main() { run(); }\n");
2071
    write(&r, "logo.png", b"\x89PNG\0\0");
2072
    let h2 = repo.commit("second", &[]).unwrap();
2073
2074
    let git_dir = root.join("mirror.git");
2075
    let rep = repo.git_export(&git_dir).unwrap();
2076
    assert_eq!((rep.exported, rep.skipped, rep.heads), (2, 0, 1));
2077
    let git = |args: &[&str]| -> String {
2078
        let out = std::process::Command::new("git")
2079
            .arg("-C")
2080
            .arg(&git_dir)
2081
            .args(args)
2082
            .output()
2083
            .unwrap();
2084
        assert!(
2085
            out.status.success(),
2086
            "{}",
2087
            String::from_utf8_lossy(&out.stderr)
2088
        );
2089
        String::from_utf8_lossy(&out.stdout).trim().to_string()
2090
    };
2091
    assert_eq!(git(&["log", "--format=%s", "main"]), "second\nfirst");
2092
    assert_eq!(git(&["show", "main:src/main.rs"]), "fn main() { run(); }");
2093
    assert_eq!(git(&["show", "main:README.md"]), "hello");
2094
    let body = git(&["log", "-1", "--format=%B", "main"]);
2095
    assert!(
2096
        body.contains(&format!("Oxy-Hash: {}", h2.to_hex())),
2097
        "{body}"
2098
    );
2099
    assert!(body.contains("Change-Id: "), "{body}");
2100
    assert_eq!(
2101
        git(&["log", "-1", "--format=%an <%ae>", "main"]),
2102
        "Ada Lovelace <[email protected]>"
2103
    );
2104
    assert_eq!(
2105
        git(&["ls-tree", "--name-only", "main"]),
2106
        "README.md\nlogo.png\nsrc"
2107
    );
2108
2109
    // Re-export is incremental.
2110
    let rep = repo.git_export(&git_dir).unwrap();
2111
    assert_eq!((rep.exported, rep.skipped), (0, 2));
2112
2113
    // An independent change makes two heads; the next state is one more
2114
    // commit on the linear branch whose tree is the union.
2115
    repo.checkout(&[h1], false, "checkout").unwrap();
2116
    write(&r, "other.txt", b"o\n");
2117
    let h3 = repo.commit("third", &[]).unwrap();
2118
    let rep = repo.git_export(&git_dir).unwrap();
2119
    assert_eq!((rep.exported, rep.heads), (1, 2));
2120
    assert_eq!(git(&["log", "--format=%s", "main"]), "third\nsecond\nfirst");
2121
    let parents = git(&["rev-list", "--parents", "-1", "main"]);
2122
    assert_eq!(parents.split(' ').count(), 2, "one parent: {parents}");
2123
    assert_eq!(git(&["show", "main:other.txt"]), "o");
2124
    assert_eq!(git(&["show", "main:src/main.rs"]), "fn main() { run(); }");
2125
    assert_eq!(
2126
        git(&["ls-tree", "--name-only", "main"]),
2127
        "README.md\nlogo.png\nother.txt\nsrc"
2128
    );
2129
    let body = git(&["log", "-1", "--format=%B", "main"]);
2130
    assert!(
2131
        body.contains(&format!("Oxy-Hash: {}", h3.to_hex())) && body.contains("Oxy-State: "),
2132
        "{body}"
2133
    );
2134
    // A rewrite is a new state whose one new change is the rewritten one.
2135
    repo.describe(&h3, "third, described").unwrap();
2136
    let rep = repo.git_export(&git_dir).unwrap();
2137
    assert_eq!(rep.exported, 1);
2138
    assert_eq!(
2139
        git(&["log", "-1", "--format=%s", "main"]),
2140
        "third, described"
2141
    );
2142
    assert_eq!(git(&["log", "--format=%s", "main"]).lines().count(), 4);
2143
    let _ = h2;
2144
}
2145
2146
#[test]
2147
fn git_import_reproduces_trees() {
2148
    git_import_reproduces_trees_with(None);
2149
}
2150
2151
/// The same import with every merge rendered in batches of one file
2152
/// (oxygen#25): what a merge onto a base of thousands of files takes.
2153
#[test]
2154
fn git_import_reproduces_trees_in_batches() {
2155
    git_import_reproduces_trees_with(Some(1));
2156
}
2157
2158
fn git_import_reproduces_trees_with(batch: Option<usize>) {
2159
    crate::repo::git::set_merge_batch_for_tests(batch);
2160
    hermetic();
2161
    if std::process::Command::new("git")
2162
        .arg("--version")
2163
        .output()
2164
        .is_err()
2165
    {
2166
        eprintln!("git not installed; skipping");
2167
        return;
2168
    }
2169
    let dir = tempfile::tempdir().unwrap();
2170
    let root = dir.path();
2171
    let g = root.join("src.git");
2172
    fs::create_dir_all(&g).unwrap();
2173
    let git = |args: &[&str]| -> String {
2174
        let out = std::process::Command::new("git")
2175
            .arg("-C")
2176
            .arg(&g)
2177
            .args([
2178
                "-c",
2179
                "user.name=Grace",
2180
                "-c",
2181
                "[email protected]",
2182
                "-c",
2183
                "commit.gpgsign=false",
2184
            ])
2185
            .args(args)
2186
            .output()
2187
            .unwrap();
2188
        assert!(
2189
            out.status.success(),
2190
            "git {args:?}: {}",
2191
            String::from_utf8_lossy(&out.stderr)
2192
        );
2193
        String::from_utf8_lossy(&out.stdout).trim().to_string()
2194
    };
2195
    git(&["init", "-q", "-b", "main"]);
2196
    write(&g, "README.md", b"# Hi\n");
2197
    write(&g, "src/lib.rs", b"pub fn a() {}\n");
2198
    git(&["add", "."]);
2199
    git(&["commit", "-q", "-m", "initial"]);
2200
    write(&g, "src/lib.rs", b"pub fn a() {}\npub fn b() {}\n");
2201
    write(&g, "run.sh", b"#!/bin/sh\n");
2202
    #[cfg(unix)]
2203
    {
2204
        use std::os::unix::fs::PermissionsExt;
2205
        fs::set_permissions(g.join("run.sh"), fs::Permissions::from_mode(0o755)).unwrap();
2206
    }
2207
    write(&g, "logo.png", b"\x89PNG\0\0\x01");
2208
    git(&["add", "."]);
2209
    git(&[
2210
        "commit",
2211
        "-q",
2212
        "-m",
2213
        "second\n\nChange-Id: 0123456789abcdef0123456789abcdef",
2214
    ]);
2215
    // A branch that edits README, merged back with a conflict-free merge.
2216
    git(&["checkout", "-q", "-b", "topic", "HEAD~1"]);
2217
    write(&g, "README.md", b"# Hi\n\nMore.\n");
2218
    git(&["commit", "-q", "-am", "readme"]);
2219
    git(&["checkout", "-q", "main"]);
2220
    git(&["merge", "-q", "--no-ff", "-m", "merge topic", "topic"]);
2221
    // A branch from the initial commit inserting at the same place as
2222
    // "second": concurrent in Oxygen too, so the merge commit is a resolution.
2223
    let initial = git(&["rev-list", "--max-parents=0", "HEAD"]);
2224
    git(&["checkout", "-q", "-b", "clash", &initial]);
2225
    write(&g, "src/lib.rs", b"pub fn a() {}\npub fn c() {}\n");
2226
    git(&["commit", "-q", "-am", "clash"]);
2227
    git(&["checkout", "-q", "main"]);
2228
    // Expected to stop at the conflict, so its status is ignored; the
2229
    // identity is passed as for every other git call here, or a machine
2230
    // without one refuses to start the merge at all.
2231
    let _ = std::process::Command::new("git")
2232
        .arg("-C")
2233
        .arg(&g)
2234
        .args([
2235
            "-c",
2236
            "user.name=Grace",
2237
            "-c",
2238
            "[email protected]",
2239
            "merge",
2240
            "-q",
2241
            "clash",
2242
        ])
2243
        .output();
2244
    assert!(
2245
        g.join(".git/MERGE_HEAD").exists(),
2246
        "the clash merge stopped at its conflict"
2247
    );
2248
    write(
2249
        &g,
2250
        "src/lib.rs",
2251
        b"pub fn a() {}\npub fn b() {}\npub fn c() {}\n",
2252
    );
2253
    git(&["add", "."]);
2254
    git(&["commit", "-q", "-m", "resolve clash"]);
2255
    git(&["rm", "-q", "logo.png"]);
2256
    git(&["commit", "-q", "-m", "drop logo"]);
2257
    // A rename with a small edit is imported as a move of the same node.
2258
    git(&["mv", "src/lib.rs", "src/lib2.rs"]);
2259
    write(
2260
        &g,
2261
        "src/lib2.rs",
2262
        b"pub fn a() {}\npub fn b() {}\npub fn c() {}\npub fn d() {}\n",
2263
    );
2264
    git(&["add", "."]);
2265
    git(&["commit", "-q", "-m", "rename lib"]);
2266
    // A branch that edits run.sh, merged keeping main's tree (`-s ours`):
2267
    // run.sh is the same as in the first parent's tree, but the merged
2268
    // change touched it, so the importer must compare it, not skip it.
2269
    git(&["checkout", "-q", "-b", "discarded"]);
2270
    write(&g, "run.sh", b"#!/bin/sh\necho discarded\n");
2271
    git(&["commit", "-q", "-am", "discarded edit"]);
2272
    git(&["checkout", "-q", "main"]);
2273
    git(&[
2274
        "merge",
2275
        "-q",
2276
        "-s",
2277
        "ours",
2278
        "-m",
2279
        "merge discarded, keeping ours",
2280
        "discarded",
2281
    ]);
2282
    let expected_count: usize = git(&["rev-list", "--count", "main"]).parse().unwrap();
2283
2284
    let dest = root.join("oxy");
2285
    let repo = Repo::init(&dest).unwrap().with_home(root.join("home"));
2286
    let rep = repo.import_git(&g, "main").unwrap();
2287
    assert_eq!(rep.commits, expected_count);
2288
    assert_eq!(rep.merges, 3);
2289
    assert_eq!(
2290
        fs::read(dest.join("run.sh")).unwrap(),
2291
        b"#!/bin/sh\n",
2292
        "the ours merge kept main's run.sh"
2293
    );
2294
    let v = repo.verify_git_import(&g, "main").unwrap();
2295
    assert_eq!(v.commits, expected_count, "every commit's tree reproduced");
2296
    assert!(v.mismatches.is_empty(), "{:?}", v.mismatches);
2297
    // The working copy equals the Git tree at main.
2298
    assert_eq!(
2299
        fs::read(dest.join("src/lib2.rs")).unwrap(),
2300
        b"pub fn a() {}\npub fn b() {}\npub fn c() {}\npub fn d() {}\n"
2301
    );
2302
    assert!(!dest.join("src/lib.rs").exists());
2303
    assert_eq!(
2304
        fs::read(dest.join("README.md")).unwrap(),
2305
        b"# Hi\n\nMore.\n"
2306
    );
2307
    assert!(!dest.join("logo.png").exists());
2308
    #[cfg(unix)]
2309
    {
2310
        use std::os::unix::fs::PermissionsExt;
2311
        assert!(
2312
            fs::metadata(dest.join("run.sh"))
2313
                .unwrap()
2314
                .permissions()
2315
                .mode()
2316
                & 0o111
2317
                != 0
2318
        );
2319
    }
2320
    assert!(
2321
        !repo.snapshot("status").unwrap().changed,
2322
        "clean after import"
2323
    );
2324
    let heads = repo.bookmark_heads().unwrap();
2325
    let st = repo.load_state(&heads).unwrap();
2326
    assert!(!st.materialize().is_conflicted());
2327
    assert_eq!(st.len(), expected_count);
2328
    let tip = repo
2329
        .log()
2330
        .unwrap()
2331
        .into_iter()
2332
        .find(|e| e.change.message.starts_with("rename lib"))
2333
        .unwrap();
2334
    let c = repo.store().get_change(&tip.hash).unwrap();
2335
    assert!(
2336
        c.tree_ops
2337
            .iter()
2338
            .any(|op| matches!(op, TreeOp::Move { name, .. } if name == "lib2.rs")),
2339
        "{:?}",
2340
        c.tree_ops
2341
    );
2342
    assert!(!c
2343
        .tree_ops
2344
        .iter()
2345
        .any(|op| matches!(op, TreeOp::AddNode { .. })));
2346
    // Messages carry Git trailers; the Change-Id trailer was honoured.
2347
    let log = repo.log().unwrap();
2348
    let second = log
2349
        .iter()
2350
        .find(|e| e.change.message.starts_with("second"))
2351
        .unwrap();
2352
    assert_eq!(
2353
        second.change.change_id,
2354
        ChangeId::from_hex("0123456789abcdef0123456789abcdef").unwrap()
2355
    );
2356
    assert!(second
2357
        .change
2358
        .message
2359
        .contains("Git-Author: Grace <[email protected]>"));
2360
    let resolve = log
2361
        .iter()
2362
        .find(|e| e.change.message.starts_with("resolve clash"))
2363
        .unwrap();
2364
    assert_eq!(
2365
        resolve.change.kind,
2366
        ChangeKind::Resolution,
2367
        "a conflicting Git merge becomes a resolution"
2368
    );
2369
    // Re-importing into another fresh repository gives the same ChangeIds.
2370
    let repo2 = Repo::init(&root.join("oxy2"))
2371
        .unwrap()
2372
        .with_home(root.join("home"));
2373
    repo2.import_git(&g, "main").unwrap();
2374
    // New nodes' identifiers derive from the commit (spec §23), so the
2375
    // re-import is not just the same ChangeIds but the same changes.
2376
    assert_eq!(
2377
        repo2.bookmark_heads().unwrap(),
2378
        repo.bookmark_heads().unwrap()
2379
    );
2380
    let ids: BTreeSet<ChangeId> = repo
2381
        .log()
2382
        .unwrap()
2383
        .iter()
2384
        .filter(|e| !e.is_working_copy)
2385
        .map(|e| e.change.change_id)
2386
        .collect();
2387
    let ids2: BTreeSet<ChangeId> = repo2
2388
        .log()
2389
        .unwrap()
2390
        .iter()
2391
        .filter(|e| !e.is_working_copy)
2392
        .map(|e| e.change.change_id)
2393
        .collect();
2394
    assert_eq!(ids, ids2);
2395
    // Round trip back out to Git reproduces the tip tree.
2396
    let mirror = root.join("mirror.git");
2397
    repo.git_export(&mirror).unwrap();
2398
    let out = std::process::Command::new("git")
2399
        .arg("-C")
2400
        .arg(&mirror)
2401
        .args(["show", "main:src/lib2.rs"])
2402
        .output()
2403
        .unwrap();
2404
    assert_eq!(
2405
        String::from_utf8_lossy(&out.stdout),
2406
        "pub fn a() {}\npub fn b() {}\npub fn c() {}\npub fn d() {}\n"
2407
    );
2408
    let out = std::process::Command::new("git")
2409
        .arg("-C")
2410
        .arg(&mirror)
2411
        .args(["show", "main:src/lib.rs"])
2412
        .output()
2413
        .unwrap();
2414
    assert!(
2415
        !out.status.success(),
2416
        "the old path is gone from the export"
2417
    );
2418
}
2419
2420
#[test]
2421
fn checkpoints_accelerate_loading_and_stay_correct() {
2422
    hermetic();
2423
    let dir = tempfile::tempdir().unwrap();
2424
    let root = dir.path();
2425
    let mut repo = Repo::init(root).unwrap().with_home(root.join("home"));
2426
    repo.config.set("core.checkpoint-interval", "5").unwrap();
2427
    repo.save_config().unwrap();
2428
    let repo = Repo::open(root).unwrap().with_home(root.join("home"));
2429
    let mut hashes = Vec::new();
2430
    for i in 0..12 {
2431
        write(
2432
            root,
2433
            "a.txt",
2434
            format!(
2435
                "{}\n",
2436
                (0..=i)
2437
                    .map(|k| k.to_string())
2438
                    .collect::<Vec<_>>()
2439
                    .join("\n")
2440
            )
2441
            .as_bytes(),
2442
        );
2443
        write(root, &format!("f{i}.txt"), b"x\n");
2444
        hashes.push(repo.commit(&format!("c{i}"), &[]).unwrap());
2445
    }
2446
    let (_, cp) = repo
2447
        .latest_checkpoint("main")
2448
        .unwrap()
2449
        .expect("automatic checkpoint");
2450
    assert!(cp.count >= 5 && cp.count <= 12, "{}", cp.count);
2451
    // Loading through the checkpoint equals loading everything.
2452
    let heads = repo.bookmark_heads().unwrap();
2453
    let fast = repo.load_state(&heads).unwrap();
2454
    let full = repo.load_state_full(&heads).unwrap();
2455
    assert_eq!(fast.len(), full.len());
2456
    assert_eq!(fast.heads(), full.heads());
2457
    let (a, b) = (fast.materialize(), full.materialize());
2458
    assert_eq!(
2459
        a.files.keys().collect::<Vec<_>>(),
2460
        b.files.keys().collect::<Vec<_>>()
2461
    );
2462
    for (p, f) in &a.files {
2463
        assert_eq!(f.content, b.files[p].content, "{p}");
2464
    }
2465
    assert!(repo.load_state_checkpointed(&heads).unwrap().is_some());
2466
    // A head set that does not contain the checkpoint's heads falls back.
2467
    assert!(repo
2468
        .load_state_checkpointed(&[hashes[0]])
2469
        .unwrap()
2470
        .is_none());
2471
    assert_eq!(repo.load_state(&[hashes[0]]).unwrap().len(), 1);
2472
    // Everything else keeps working on top of the checkpoint.
2473
    assert!(!repo.snapshot("status").unwrap().changed);
2474
    let h = repo.describe(&hashes[3], "c3 described").unwrap();
2475
    assert_eq!(repo.store().get_change(&h).unwrap().message, "c3 described");
2476
    let (r, n, bytes) = repo.checkpoint().unwrap();
2477
    assert!(n >= 12 && bytes > 0);
2478
    assert_eq!(repo.latest_checkpoint("main").unwrap().unwrap().0, r);
2479
    write(root, "a.txt", b"after\n");
2480
    let h_after = repo.commit("after", &[]).unwrap();
2481
    let st = repo.load_state(&repo.bookmark_heads().unwrap()).unwrap();
2482
    assert!(st.contains(&h_after));
2483
    assert!(
2484
        matches!(&st.materialize().files["a.txt"].content, FileContent::Text { bytes, .. } if bytes == b"after\n")
2485
    );
2486
    assert_eq!(repo.log().unwrap().len(), 14);
2487
    // Checkpoints survive gc.
2488
    repo.gc(true).unwrap();
2489
    assert!(repo.latest_checkpoint("main").unwrap().is_some());
2490
    assert!(repo
2491
        .load_state_checkpointed(&repo.bookmark_heads().unwrap())
2492
        .unwrap()
2493
        .is_some());
2494
}
2495
2496
#[test]
2497
fn quick_status_for_prompts() {
2498
    hermetic();
2499
    let dir = tempfile::tempdir().unwrap();
2500
    let root = dir.path();
2501
    let origin = Repo::init(&root.join("origin")).unwrap();
2502
    let url = root.join("origin").to_string_lossy().to_string();
2503
    let a = Repo::clone(&url, &root.join("a"))
2504
        .unwrap()
2505
        .with_home(root.join("home"));
2506
    let ops_before = a.op_log().unwrap().len();
2507
    let info = a.quick_status().unwrap();
2508
    assert_eq!(
2509
        (
2510
            info.bookmark.as_str(),
2511
            info.heads,
2512
            info.dirty,
2513
            info.conflicted,
2514
            info.ahead,
2515
            info.behind
2516
        ),
2517
        ("main", 0, false, false, Some(0), Some(0))
2518
    );
2519
    write(&root.join("a"), "f.txt", b"f\n");
2520
    assert!(a.quick_status().unwrap().dirty, "a new file is dirty");
2521
    assert_eq!(
2522
        a.op_log().unwrap().len(),
2523
        ops_before,
2524
        "quick_status records nothing"
2525
    );
2526
    // A snapshotted but uncommitted change is still dirty.
2527
    a.snapshot("status").unwrap();
2528
    assert!(a.quick_status().unwrap().dirty);
2529
    a.commit("f", &[]).unwrap();
2530
    let info = a.quick_status().unwrap();
2531
    assert!(!info.dirty, "clean right after a commit");
2532
    assert_eq!((info.ahead, info.behind), (Some(1), Some(0)));
2533
    assert_eq!(
2534
        info.format("%b %c%d%x%A%D"),
2535
        format!("main {}+1", info.change_id)
2536
    );
2537
    assert_eq!(info.format("[%h heads] %a/%B %%"), "[1 heads] 1/0 %");
2538
    // Touching a file without changing it is not dirty; changing content of
2539
    // the same size is.
2540
    let p = root.join("a/f.txt");
2541
    let content = fs::read(&p).unwrap();
2542
    fs::write(&p, &content).unwrap();
2543
    assert!(!a.quick_status().unwrap().dirty);
2544
    fs::write(&p, b"g\n").unwrap();
2545
    assert!(a.quick_status().unwrap().dirty);
2546
    fs::write(&p, b"f\n").unwrap();
2547
    // Push, then a second clone commits and pushes: we are behind.
2548
    assert!(a.push("origin", false).unwrap()[0].ok);
2549
    assert_eq!(a.quick_status().unwrap().ahead, Some(0));
2550
    let b = Repo::clone(&url, &root.join("b"))
2551
        .unwrap()
2552
        .with_home(root.join("home-b"));
2553
    write(&root.join("b"), "g.txt", b"g\n");
2554
    b.commit("g", &[]).unwrap();
2555
    b.push("origin", false).unwrap();
2556
    a.fetch("origin").unwrap();
2557
    let info = a.quick_status().unwrap();
2558
    assert_eq!((info.ahead, info.behind), (Some(0), Some(1)));
2559
    assert_eq!(info.format("%A%D"), "-1");
2560
    let _ = origin;
2561
}
2562
2563
#[test]
2564
fn lazy_blobs_are_fetched_on_first_read() {
2565
    hermetic();
2566
    let dir = tempfile::tempdir().unwrap();
2567
    let root = dir.path();
2568
    let origin_dir = root.join("origin");
2569
    let origin = Repo::init(&origin_dir)
2570
        .unwrap()
2571
        .with_home(root.join("home"));
2572
    let url = origin_dir.to_string_lossy().to_string();
2573
    let big: Vec<u8> = (0..200_000u32).map(|i| (i % 251) as u8).collect(); // has NUL bytes: opaque
2574
    write(&origin_dir, "big.bin", &big);
2575
    write(&origin_dir, "small.bin", &[0u8, 1, 2]);
2576
    write(&origin_dir, "t.txt", b"t\n");
2577
    let h = origin.commit("blobs", &[]).unwrap();
2578
    let big_ref = Repo::blob_ref(&big);
2579
2580
    // Fetch only (no checkout) with a filter: the big blob stays absent.
2581
    let a = Repo::init_with_id(&root.join("a"), origin.id().unwrap())
2582
        .unwrap()
2583
        .with_home(root.join("home"));
2584
    let a = {
2585
        let mut a = a;
2586
        a.config.set("remote.origin.url", &url).unwrap();
2587
        a.config.set("filter.max-blob", "100K").unwrap();
2588
        a.save_config().unwrap();
2589
        a
2590
    };
2591
    assert_eq!(a.config.max_blob, Some(100 * 1024));
2592
    a.fetch("origin").unwrap();
2593
    assert!(a.store().has(&h));
2594
    assert!(!a.store().has(&big_ref), "withheld");
2595
    assert!(
2596
        a.store().has(&Repo::blob_ref(&[0u8, 1, 2])),
2597
        "small blob came along"
2598
    );
2599
    assert_eq!(a.lazy_remote(&big_ref).as_deref(), Some("origin"));
2600
2601
    // status and commit do not need it: adopt the state, edit a text file, commit.
2602
    let (op_ref, op) = a.head_op().unwrap();
2603
    let mut view = op.view.clone();
2604
    view.bookmarks.insert(
2605
        "main".into(),
2606
        a.store().put_state(&StateObject::new(vec![h])).unwrap(),
2607
    );
2608
    a.record_op(&[op_ref], "adopt", view).unwrap();
2609
    // Checkout reads the blob lazily, which fetches it.
2610
    a.checkout(&[h], true, "checkout").unwrap();
2611
    assert!(a.store().has(&big_ref), "fetched on first read");
2612
    assert_eq!(fs::read(root.join("a/big.bin")).unwrap(), big);
2613
    assert!(a.lazy_remote(&big_ref).is_none(), "no longer registered");
2614
    write(&root.join("a"), "t.txt", b"t2\n");
2615
    a.commit("text edit", &[]).unwrap();
2616
2617
    // clone --max-blob records the filter; the checkout fetches lazily.
2618
    let b = Repo::clone_with(&url, &root.join("b"), Some(1024), &[]).unwrap();
2619
    assert_eq!(b.config.max_blob, Some(1024));
2620
    assert_eq!(fs::read(root.join("b/big.bin")).unwrap(), big);
2621
    assert_eq!(parse_size("2M").unwrap(), 2 << 20);
2622
    assert!(parse_size("lots").is_err());
2623
}
2624
2625
#[test]
2626
fn sparse_checkout_materializes_only_chosen_paths() {
2627
    hermetic();
2628
    let dir = tempfile::tempdir().unwrap();
2629
    let root = dir.path();
2630
    let origin_dir = root.join("origin");
2631
    let origin = Repo::init(&origin_dir)
2632
        .unwrap()
2633
        .with_home(root.join("home"));
2634
    write(&origin_dir, "src/main.rs", b"fn main() {}\n");
2635
    write(&origin_dir, "src/lib.rs", b"pub fn a() {}\n");
2636
    write(&origin_dir, "docs/guide.md", b"# guide\n");
2637
    let logo: Vec<u8> = (0..50_000u32).map(|i| (i % 7) as u8).collect();
2638
    write(&origin_dir, "docs/logo.png", &logo);
2639
    write(&origin_dir, "README.md", b"# top\n");
2640
    let h1 = origin.commit("tree", &[]).unwrap();
2641
    let url = origin_dir.to_string_lossy().to_string();
2642
2643
    let a = Repo::clone_with(&url, &root.join("a"), None, &["src".into()])
2644
        .unwrap()
2645
        .with_home(root.join("home"));
2646
    assert_eq!(a.config.sparse_paths, vec!["src"]);
2647
    assert_eq!(a.config.max_blob, Some(0), "sparse implies lazy blobs");
2648
    assert!(root.join("a/src/main.rs").exists());
2649
    assert!(!root.join("a/docs").exists() && !root.join("a/README.md").exists());
2650
    assert!(
2651
        !a.store().has(&Repo::blob_ref(&logo)),
2652
        "out-of-scope blob never fetched"
2653
    );
2654
    assert!(
2655
        !a.snapshot("status").unwrap().changed,
2656
        "out-of-scope files are not removals"
2657
    );
2658
    assert!(!a.quick_status().unwrap().dirty);
2659
2660
    // Edits in scope commit normally and keep the rest of the tree intact.
2661
    write(
2662
        &root.join("a"),
2663
        "src/lib.rs",
2664
        b"pub fn a() {}\npub fn b() {}\n",
2665
    );
2666
    let h2 = a.commit("edit lib", &[]).unwrap();
2667
    let st = a.load_state(&[h2]).unwrap().materialize();
2668
    assert!(
2669
        st.files.contains_key("docs/guide.md"),
2670
        "the state still has everything"
2671
    );
2672
    assert!(a.push("origin", false).unwrap()[0].ok);
2673
    origin.refresh().unwrap();
2674
    // Files created outside the scope are ignored by status.
2675
    write(&root.join("a"), "docs/new.md", b"ignored\n");
2676
    assert!(a.snapshot("status").unwrap().statuses.is_empty());
2677
2678
    // Widening the filter checks out the rest; narrowing leaves stray files alone.
2679
    let mut a = a;
2680
    a.config.set("filter.paths", "src,docs").unwrap();
2681
    a.save_config().unwrap();
2682
    let r = a
2683
        .checkout(&a.bookmark_heads().unwrap(), true, "widen")
2684
        .unwrap();
2685
    assert!(r.written >= 2);
2686
    assert_eq!(
2687
        fs::read(root.join("a/docs/logo.png")).unwrap(),
2688
        logo,
2689
        "now fetched lazily"
2690
    );
2691
    assert!(!root.join("a/README.md").exists());
2692
    // Origin sees the change made under a sparse checkout with the full tree intact.
2693
    origin.pull("origin").err();
2694
    let full = origin
2695
        .load_state(&origin.bookmark_heads().unwrap())
2696
        .unwrap()
2697
        .materialize();
2698
    assert!(
2699
        matches!(&full.files["src/lib.rs"].content, FileContent::Text { bytes, .. } if bytes == b"pub fn a() {}\npub fn b() {}\n")
2700
    );
2701
    assert!(full.files.contains_key("README.md"));
2702
    let _ = h1;
2703
}
2704
2705
#[test]
2706
fn shallow_clone_and_deepen() {
2707
    hermetic();
2708
    let dir = tempfile::tempdir().unwrap();
2709
    let root = dir.path();
2710
    let origin_dir = root.join("origin");
2711
    let origin = Repo::init(&origin_dir)
2712
        .unwrap()
2713
        .with_home(root.join("home"));
2714
    let mut hashes = Vec::new();
2715
    for i in 0..8 {
2716
        write(
2717
            &origin_dir,
2718
            "a.txt",
2719
            format!(
2720
                "{}\n",
2721
                (0..=i)
2722
                    .map(|k| k.to_string())
2723
                    .collect::<Vec<_>>()
2724
                    .join("\n")
2725
            )
2726
            .as_bytes(),
2727
        );
2728
        hashes.push(origin.commit(&format!("c{i}"), &[]).unwrap());
2729
    }
2730
    let url = origin_dir.to_string_lossy().to_string();
2731
    let a = Repo::clone_shallow(&url, &root.join("a"), 3, None, &[])
2732
        .unwrap()
2733
        .with_home(root.join("home"));
2734
    assert!(a.is_shallow());
2735
    assert_eq!(
2736
        fs::read_to_string(root.join("a/a.txt")).unwrap(),
2737
        "0\n1\n2\n3\n4\n5\n6\n7\n"
2738
    );
2739
    assert!(
2740
        a.store().has(&hashes[7]) && a.store().has(&hashes[5]),
2741
        "three levels present"
2742
    );
2743
    assert!(!a.store().has(&hashes[4]), "beyond the depth is absent");
2744
    assert_eq!(a.boundary(), [hashes[4]].into_iter().collect());
2745
    assert_eq!(
2746
        a.log().unwrap().len(),
2747
        9,
2748
        "the log shows every change from the checkpoint's metadata"
2749
    );
2750
    assert!(!a.snapshot("status").unwrap().changed);
2751
    assert_eq!(a.quick_status().unwrap().heads, 1);
2752
2753
    // Work continues on top of the shallow history and pushes back.
2754
    write(&root.join("a"), "a.txt", b"0\n1\n2\n3\n4\n5\n6\n7\n8\n");
2755
    let h_new = a.commit("c8", &[]).unwrap();
2756
    assert!(a.push("origin", false).unwrap()[0].ok);
2757
    origin.refresh().unwrap();
2758
    assert_eq!(origin.bookmark_heads().unwrap(), vec![h_new]);
2759
    // Fetching new work from origin into the shallow clone works too.
2760
    write(&origin_dir, "b.txt", b"b\n");
2761
    origin.pull("origin").err();
2762
    let (_, wc) = origin.working_copy().unwrap();
2763
    let _ = wc;
2764
    origin
2765
        .checkout(&origin.bookmark_heads().unwrap(), true, "co")
2766
        .unwrap();
2767
    write(&origin_dir, "b.txt", b"b\n");
2768
    let h_b = origin.commit("b", &[]).unwrap();
2769
    let pr = a.pull("origin").unwrap();
2770
    assert!(pr.changed);
2771
    assert!(a.store().has(&h_b));
2772
    assert!(root.join("a/b.txt").exists());
2773
2774
    // Deepening fetches older history until the boundary is gone.
2775
    // Every commit also depends on the change that created the file, so two
2776
    // levels below the boundary hold h4, h3, and the root.
2777
    assert!(a.deepen("origin", 2).unwrap() >= 2);
2778
    assert!(a.store().has(&hashes[3]));
2779
    assert!(a.is_shallow());
2780
    a.deepen("origin", 100).unwrap();
2781
    assert!(!a.is_shallow(), "boundary reached the root");
2782
    assert!(a.store().has(&hashes[0]));
2783
    assert_eq!(
2784
        a.load_state_full(&a.bookmark_heads().unwrap())
2785
            .unwrap()
2786
            .len(),
2787
        10
2788
    );
2789
}
2790
2791
#[test]
2792
fn tags_are_immutable_named_states_and_travel() {
2793
    hermetic();
2794
    let dir = tempfile::tempdir().unwrap();
2795
    let root = dir.path();
2796
    let origin = Repo::init(&root.join("origin")).unwrap();
2797
    let url = root.join("origin").to_string_lossy().to_string();
2798
    let mut a = Repo::clone(&url, &root.join("a"))
2799
        .unwrap()
2800
        .with_home(root.join("home-a"));
2801
    let (key_a, _) = a
2802
        .create_identity("Ada", "[email protected]", IdentityScope::User)
2803
        .unwrap();
2804
    write(&root.join("a"), "f.txt", b"1\n");
2805
    let h1 = a.commit("one", &[]).unwrap();
2806
    write(&root.join("a"), "f.txt", b"1\n2\n");
2807
    let h2 = a.commit("two", &[]).unwrap();
2808
2809
    let t = a.tag_create("v1", &[h1], "first release").unwrap();
2810
    assert_eq!(
2811
        (t.heads.clone(), t.signer.as_deref()),
2812
        (vec![h1], Some("Ada"))
2813
    );
2814
    assert!(a.tag_create("v1", &[h2], "").is_err(), "immutable");
2815
    assert!(a.tag_create("bad/name", &[h2], "").is_err());
2816
    assert_eq!(a.tag_heads("v1").unwrap(), Some(vec![h1]));
2817
    assert_eq!(a.resolve_heads("v1").unwrap(), vec![h1]);
2818
    assert_eq!(a.resolve_heads("main").unwrap(), vec![h2]);
2819
    let (_, sa) = a.tag_attest("v1").unwrap().unwrap();
2820
    assert_eq!(sa.sigs[0].key, key_a);
2821
    // Checkout by tag.
2822
    a.checkout(&a.resolve_heads("v1").unwrap(), false, "co")
2823
        .unwrap();
2824
    assert_eq!(fs::read(root.join("a/f.txt")).unwrap(), b"1\n");
2825
    a.checkout(&a.bookmark_heads().unwrap(), false, "co")
2826
        .unwrap();
2827
2828
    // Push carries the tag; a second attestation for the name is refused.
2829
    let r = a.push("origin", false).unwrap();
2830
    origin.refresh().unwrap();
2831
    assert!(r.iter().any(|x| x.name == "tags/v1" && x.ok), "{r:?}");
2832
    assert_eq!(origin.tag_heads("v1").unwrap(), Some(vec![h1]));
2833
    let mut forged = a
2834
        .tag_refs()
2835
        .unwrap()
2836
        .into_iter()
2837
        .find(|t| t.name == "v1")
2838
        .unwrap();
2839
    forged.state = origin
2840
        .store()
2841
        .put_state(&StateObject::new(vec![h2]))
2842
        .unwrap();
2843
    forged.heads = vec![h2];
2844
    forged.attestation = None;
2845
    let r = origin
2846
        .receive_push(Bundle::default(), vec![], None, vec![forged])
2847
        .unwrap();
2848
    assert!(!r[0].ok && r[0].reason.contains("immutable"), "{r:?}");
2849
2850
    // A clone gets the tag; a later tag arrives on fetch.
2851
    let b = Repo::clone(&url, &root.join("b"))
2852
        .unwrap()
2853
        .with_home(root.join("home-b"));
2854
    assert_eq!(b.tag_heads("v1").unwrap(), Some(vec![h1]));
2855
    assert!(b.tags().unwrap()[0].signer.as_deref() == Some("Ada"));
2856
    a.tag_create("v2", &[h2], "second").unwrap();
2857
    a.push("origin", false).unwrap();
2858
    origin.refresh().unwrap();
2859
    let rep = b.fetch("origin").unwrap();
2860
    assert_eq!(rep.new_tags, 1);
2861
    assert_eq!(b.tag_heads("v2").unwrap(), Some(vec![h2]));
2862
2863
    // Under a policy, an unattested tag is refused and an attested one by the root passes.
2864
    a.policy_init().unwrap();
2865
    a.push("origin", false).unwrap();
2866
    origin.refresh().unwrap();
2867
    let unattested = crate::protocol::TagRef {
2868
        name: "v3".into(),
2869
        state: origin
2870
            .store()
2871
            .put_state(&StateObject::new(vec![h2]))
2872
            .unwrap(),
2873
        heads: vec![h2],
2874
        attestation: None,
2875
    };
2876
    let r = origin
2877
        .receive_push(Bundle::default(), vec![], None, vec![unattested])
2878
        .unwrap();
2879
    assert!(!r[0].ok && r[0].reason.contains("attestation"), "{r:?}");
2880
    a.tag_create("v3", &[h2], "").unwrap();
2881
    let r = a.push("origin", false).unwrap();
2882
    origin.refresh().unwrap();
2883
    assert!(r.iter().any(|x| x.name == "tags/v3" && x.ok), "{r:?}");
2884
    assert!(a.gc(true).is_ok());
2885
    assert_eq!(a.tags().unwrap().len(), 3, "tags survive gc");
2886
2887
    // After a rotation the policy names only the new key, yet a fresh clone
2888
    // still takes the tags the old key made before it; the old key makes
2889
    // nothing new.
2890
    let rot = a.rotate_identity().unwrap();
2891
    let r = a.push("origin", false).unwrap();
2892
    origin.refresh().unwrap();
2893
    assert!(r.iter().all(|x| x.ok), "{r:?}");
2894
    let c = Repo::clone(&url, &root.join("c"))
2895
        .unwrap()
2896
        .with_home(root.join("home-c"));
2897
    assert_eq!(c.tag_heads("v3").unwrap(), Some(vec![h2]));
2898
    let (_, sp) = c.current_policy().unwrap().unwrap();
2899
    assert!(!sp.policy.authorizes(&key_a, "tags/v9"));
2900
    let made = c.identity(&rot.new).unwrap().created;
2901
    assert!(c.predecessor_authorized(&sp.policy, &key_a, "tags/v9", made - 1));
2902
    assert!(!c.predecessor_authorized(&sp.policy, &key_a, "tags/v9", made));
2903
    assert!(!c.predecessor_authorized(&sp.policy, &rot.new, "tags/v9", 0));
2904
}
2905
2906
#[test]
2907
fn multiple_workspaces_share_a_repository() {
2908
    hermetic();
2909
    let dir = tempfile::tempdir().unwrap();
2910
    let root = dir.path();
2911
    let main_dir = root.join("main");
2912
    let repo = Repo::init(&main_dir).unwrap().with_home(root.join("home"));
2913
    write(&main_dir, "a.txt", b"a\n");
2914
    let h1 = repo.commit("a", &[]).unwrap();
2915
    assert_eq!(repo.workspaces().unwrap().len(), 1);
2916
2917
    // A second workspace elsewhere, checked out on the bookmark.
2918
    let ws_dir = root.join("ws2");
2919
    let ws = repo.workspace_add(&ws_dir, None).unwrap();
2920
    assert!(ws_dir.join(".oxy").is_file());
2921
    assert_eq!(fs::read(ws_dir.join("a.txt")).unwrap(), b"a\n");
2922
    assert_ne!(ws.workspace(), repo.workspace());
2923
    let list = repo.workspaces().unwrap();
2924
    assert_eq!(list.len(), 2);
2925
    assert!(list
2926
        .iter()
2927
        .any(|w| w.id == ws.workspace() && w.path == ws_dir.canonicalize().unwrap() && !w.current));
2928
    assert!(!ws.snapshot("status").unwrap().changed);
2929
2930
    // Work in the second workspace: its own working copy, shared bookmark.
2931
    write(&ws_dir, "b.txt", b"b\n");
2932
    let s = ws.snapshot("status").unwrap();
2933
    assert_eq!(s.statuses.len(), 1);
2934
    assert!(
2935
        !repo.snapshot("status").unwrap().changed,
2936
        "the first workspace is untouched"
2937
    );
2938
    let h2 = ws.commit("b from ws2", &[]).unwrap();
2939
    repo.refresh().unwrap();
2940
    let mut heads = repo.bookmark_heads().unwrap();
2941
    heads.sort();
2942
    let mut want = vec![h1, h2];
2943
    want.sort();
2944
    assert_eq!(heads, want, "both workspaces see the bookmark move");
2945
    assert!(!main_dir.join("b.txt").exists());
2946
    repo.checkout(&repo.bookmark_heads().unwrap(), false, "co")
2947
        .unwrap();
2948
    assert!(main_dir.join("b.txt").exists());
2949
2950
    // Reopening from inside the second workspace finds the shared repository.
2951
    let reopened = Repo::open(&ws_dir).unwrap();
2952
    assert_eq!(reopened.workspace(), ws.workspace());
2953
    assert_eq!(reopened.id().unwrap(), repo.id().unwrap());
2954
    assert_eq!(reopened.quick_status().unwrap().heads, 2);
2955
2956
    // Workspaces cannot nest; forget drops one from the view but keeps files.
2957
    assert!(repo.workspace_add(&main_dir.join("inner"), None).is_err());
2958
    assert!(repo.workspace_forget(&repo.workspace()).is_err());
2959
    repo.workspace_forget(&ws.workspace()).unwrap();
2960
    assert_eq!(repo.workspaces().unwrap().len(), 1);
2961
    assert!(ws_dir.join("b.txt").exists());
2962
    assert!(
2963
        ws.snapshot("status").is_err(),
2964
        "a forgotten workspace is no longer in the view"
2965
    );
2966
2967
    // The working-copy lock: re-entrant in a thread; a lock whose process
2968
    // is gone is taken over, and a live process's is not, however old.
2969
    let lock = repo.lock_snapshot().unwrap();
2970
    let again = repo.lock_working_copy().unwrap();
2971
    drop(again);
2972
    drop(lock);
2973
    let lock_path = main_dir
2974
        .join(".oxy/workspaces")
2975
        .join(repo.workspace().to_hex())
2976
        .join("lock");
2977
    let old = std::time::SystemTime::now() - std::time::Duration::from_secs(120);
2978
    let age = |p: &Path| fs::File::open(p).unwrap().set_modified(old).unwrap();
2979
    fs::write(&lock_path, std::process::id().to_string()).unwrap();
2980
    age(&lock_path);
2981
    assert!(
2982
        !super::workspace::lock_is_stale(&lock_path),
2983
        "a live process keeps its lock"
2984
    );
2985
    fs::write(&lock_path, "4294967295").unwrap();
2986
    age(&lock_path);
2987
    assert!(repo.lock_snapshot().is_ok(), "stale lock taken over");
2988
}
2989
2990
#[test]
2991
fn attributes_binary_eol_nocompress_lockable() {
2992
    hermetic();
2993
    let dir = tempfile::tempdir().unwrap();
2994
    let root = dir.path();
2995
    let repo = Repo::init(root).unwrap().with_home(root.join("home"));
2996
    write(
2997
        root,
2998
        ".oxyattributes",
2999
        b"*.dat binary nocompress\n*.txt eol=crlf\nassets/** lockable\n",
3000
    );
3001
    write(root, "plain.dat", b"no nul bytes here\n");
3002
    write(root, "notes.txt", b"one\r\ntwo\r\n");
3003
    write(root, "assets/model.bin", b"\0model");
3004
    let h = repo.commit("attrs", &[]).unwrap();
3005
    let snap = repo.load_state(&[h]).unwrap().materialize();
3006
    assert!(
3007
        snap.files["plain.dat"].mode.opaque,
3008
        "binary attribute forces opaque without NUL bytes"
3009
    );
3010
    assert!(
3011
        matches!(&snap.files["notes.txt"].content, FileContent::Text { bytes, .. } if bytes == b"one\ntwo\n"),
3012
        "stored with LF"
3013
    );
3014
    assert!(
3015
        !repo.snapshot("status").unwrap().changed,
3016
        "CRLF on disk equals LF in the state"
3017
    );
3018
    // nocompress chunks pack raw.
3019
    let r = repo.gc(true).unwrap();
3020
    assert!(r.packed.objects > 0);
3021
    // Checkout writes CRLF for eol=crlf and makes lockable files read-only.
3022
    fs::remove_file(root.join("notes.txt")).unwrap();
3023
    repo.checkout(&[h], true, "co").unwrap();
3024
    assert_eq!(fs::read(root.join("notes.txt")).unwrap(), b"one\r\ntwo\r\n");
3025
    assert!(fs::metadata(root.join("assets/model.bin"))
3026
        .unwrap()
3027
        .permissions()
3028
        .readonly());
3029
    assert!(repo.lock_path("plain.dat").is_err(), "not lockable");
3030
    repo.lock_path("assets/model.bin").unwrap();
3031
    assert!(!fs::metadata(root.join("assets/model.bin"))
3032
        .unwrap()
3033
        .permissions()
3034
        .readonly());
3035
    assert!(repo.is_locked("assets/model.bin"));
3036
    write(root, "assets/model.bin", b"\0model2");
3037
    repo.commit("edit model", &[]).unwrap();
3038
    repo.unlock_path("assets/model.bin").unwrap();
3039
    assert!(fs::metadata(root.join("assets/model.bin"))
3040
        .unwrap()
3041
        .permissions()
3042
        .readonly());
3043
    // A later checkout can still overwrite a read-only lockable file.
3044
    repo.checkout(&[h], true, "co").unwrap();
3045
    assert_eq!(fs::read(root.join("assets/model.bin")).unwrap(), b"\0model");
3046
}
3047
3048
#[cfg(unix)]
3049
#[test]
3050
fn hooks_can_veto_observe_and_add_dependencies() {
3051
    use std::os::unix::fs::PermissionsExt;
3052
    hermetic();
3053
    let dir = tempfile::tempdir().unwrap();
3054
    let root = dir.path();
3055
    let mut repo = Repo::init(root).unwrap().with_home(root.join("home"));
3056
    let hooks = root.join(".oxy/hooks");
3057
    fs::create_dir_all(&hooks).unwrap();
3058
    let hook = |name: &str, body: &str| {
3059
        let p = hooks.join(name);
3060
        fs::write(&p, format!("#!/bin/sh\n{body}\n")).unwrap();
3061
        fs::set_permissions(&p, fs::Permissions::from_mode(0o755)).unwrap();
3062
    };
3063
    hook("pre-commit", "cat > \"$OXY_ROOT/.last-pre-commit\"; grep -q WIP \"$OXY_ROOT/.last-pre-commit\" && { echo 'no WIP commits' >&2; exit 1; }; exit 0");
3064
    hook("post-commit", "cat > \"$OXY_ROOT/.last-post-commit\"");
3065
    hook("post-checkout", "cat > \"$OXY_ROOT/.last-post-checkout\"");
3066
    hook("pre-push", "echo pushing blocked >&2; exit 3");
3067
    write(root, ".oxyignore", b".last-*\n");
3068
    write(root, "a.txt", b"a\n");
3069
    let err = repo.commit("WIP: nope", &[]).unwrap_err().to_string();
3070
    assert!(err.contains("pre-commit refused: no WIP commits"), "{err}");
3071
    let h1 = repo.commit("first", &[]).unwrap();
3072
    let pre = fs::read_to_string(root.join(".last-pre-commit")).unwrap();
3073
    assert!(
3074
        pre.contains("\"event\":\"pre-commit\"")
3075
            && pre.contains("\"path\":\"a.txt\"")
3076
            && pre.contains("\"message\":\"first\""),
3077
        "{pre}"
3078
    );
3079
    let post = fs::read_to_string(root.join(".last-post-commit")).unwrap();
3080
    assert!(post.contains(&h1.to_hex()), "{post}");
3081
    repo.checkout(&[h1], false, "co").unwrap();
3082
    assert!(fs::read_to_string(root.join(".last-post-checkout"))
3083
        .unwrap()
3084
        .contains("post-checkout"));
3085
    repo.config.set("remote.origin.url", "/nowhere").unwrap();
3086
    repo.save_config().unwrap();
3087
    let err = repo.push("origin", false).unwrap_err().to_string();
3088
    assert!(err.contains("pre-push refused: pushing blocked"), "{err}");
3089
3090
    // semantic-deps: only when enabled; adds an explicit dependency.
3091
    write(root, "b.txt", b"b\n");
3092
    hook(
3093
        "semantic-deps",
3094
        &format!(
3095
            "cat > \"$OXY_ROOT/.last-semantic\"; echo '{{\"deps\": [\"{}\"]}}'",
3096
            h1.to_hex()
3097
        ),
3098
    );
3099
    let h2 = repo.commit("b without hook", &[]).unwrap();
3100
    assert!(
3101
        repo.store().get_change(&h2).unwrap().deps.is_empty(),
3102
        "hook disabled by default"
3103
    );
3104
    repo.config.set("hooks.semantic-deps", "true").unwrap();
3105
    repo.save_config().unwrap();
3106
    write(root, "c.txt", b"c\n");
3107
    let h3 = repo.commit("c with hook", &[]).unwrap();
3108
    assert_eq!(repo.store().get_change(&h3).unwrap().deps, vec![h1]);
3109
    let sem = fs::read_to_string(root.join(".last-semantic")).unwrap();
3110
    assert!(
3111
        sem.contains("\"touched_paths\":[\"c.txt\"]") && sem.contains("candidate_deps"),
3112
        "{sem}"
3113
    );
3114
    assert_eq!(json_str("a\"b\\c\n"), "\"a\\\"b\\\\c\\n\"");
3115
}
3116
3117
#[test]
3118
fn amend_into_older_change_and_split() {
3119
    hermetic();
3120
    let dir = tempfile::tempdir().unwrap();
3121
    let root = dir.path();
3122
    let mut repo = Repo::init(root).unwrap().with_home(root.join("home"));
3123
    repo.create_identity("Ada", "a@b", IdentityScope::User)
3124
        .unwrap();
3125
    repo.set_user_config("core.sign", "change").unwrap();
3126
    write(root, "a.txt", b"one\ntwo\n");
3127
    let h0 = repo.commit("base", &[]).unwrap();
3128
    write(root, "a.txt", b"one\nTWO\n");
3129
    let h1 = repo.commit("edit two", &[]).unwrap();
3130
    write(root, "a.txt", b"one\nTWO\nthree\n");
3131
    let h2 = repo.commit("add three", &[]).unwrap();
3132
    let id1 = repo.store().get_change(&h1).unwrap().change_id;
3133
3134
    // Fixing the line h1 introduced folds into h1; h2 is rewritten on top.
3135
    write(root, "a.txt", b"one\nTWO!\nthree\n");
3136
    let h1b = repo.amend_into(&h1, None).unwrap();
3137
    assert_ne!(h1b, h1);
3138
    let c1b = repo.store().get_change(&h1b).unwrap();
3139
    assert_eq!(c1b.change_id, id1);
3140
    assert_eq!(c1b.deps, vec![h0]);
3141
    assert!(matches!(
3142
        repo.verify_change(&h1b).unwrap(),
3143
        SignatureStatus::Valid { .. }
3144
    ));
3145
    let heads = repo.bookmark_heads().unwrap();
3146
    assert_eq!(heads.len(), 1);
3147
    let top = repo.store().get_change(&heads[0]).unwrap();
3148
    assert_eq!(top.message, "add three");
3149
    assert_eq!(
3150
        top.deps.iter().copied().collect::<BTreeSet<_>>(),
3151
        [h0, h1b].into_iter().collect(),
3152
        "depends on the file's creator and the rewritten line"
3153
    );
3154
    let snap = repo.load_state(&heads).unwrap().materialize();
3155
    assert!(
3156
        matches!(&snap.files["a.txt"].content, FileContent::Text { bytes, .. } if bytes == b"one\nTWO!\nthree\n")
3157
    );
3158
    assert!(
3159
        !repo.snapshot("status").unwrap().changed,
3160
        "the working copy is clean after folding"
3161
    );
3162
    // Only h1b's own state shows the fix without "three".
3163
    let only = repo.load_state(&[h1b]).unwrap().materialize();
3164
    assert!(
3165
        matches!(&only.files["a.txt"].content, FileContent::Text { bytes, .. } if bytes == b"one\nTWO!\n")
3166
    );
3167
    assert_eq!(repo.log().unwrap().len(), 4);
3168
3169
    // An edit to a line introduced by h2 cannot fold into h1.
3170
    write(root, "a.txt", b"one\nTWO!\nthree!\n");
3171
    let err = repo.amend_into(&h1b, None).unwrap_err().to_string();
3172
    assert!(err.contains("introduced after"), "{err}");
3173
    assert!(
3174
        repo.snapshot("status").unwrap().statuses.len() == 1,
3175
        "nothing was changed by the refusal"
3176
    );
3177
    write(root, "a.txt", b"one\nTWO!\nthree\n");
3178
3179
    // Split the head that touches two files.
3180
    write(root, "b.txt", b"b\n");
3181
    write(root, "c.txt", b"c\n");
3182
    let h3 = repo.commit("b and c", &[]).unwrap();
3183
    let id3 = repo.store().get_change(&h3).unwrap().change_id;
3184
    let (p1, p2) = repo.split(&h3, &["b.txt".into()]).unwrap();
3185
    let c_1 = repo.store().get_change(&p1).unwrap();
3186
    let c_2 = repo.store().get_change(&p2).unwrap();
3187
    assert!(c_1.message.contains("part 1: b.txt"));
3188
    assert_eq!(c_2.change_id, id3);
3189
    let heads: BTreeSet<_> = repo.bookmark_heads().unwrap().into_iter().collect();
3190
    assert!(
3191
        heads.contains(&p1) && heads.contains(&p2),
3192
        "independent parts are both heads"
3193
    );
3194
    let snap = repo
3195
        .load_state(&repo.bookmark_heads().unwrap())
3196
        .unwrap()
3197
        .materialize();
3198
    assert!(snap.files.contains_key("b.txt") && snap.files.contains_key("c.txt"));
3199
    let only1 = repo.load_state(&[p1]).unwrap().materialize();
3200
    assert!(only1.files.contains_key("b.txt") && !only1.files.contains_key("c.txt"));
3201
    assert!(!repo.snapshot("status").unwrap().changed);
3202
    assert!(repo.split(&p2, &["nope.txt".into()]).is_err());
3203
    let _ = h2;
3204
}
3205
3206
#[test]
3207
fn identity_lifecycle() {
3208
    hermetic();
3209
    let dir = tempfile::tempdir().unwrap();
3210
    let root = dir.path();
3211
    let origin = Repo::init(&root.join("origin")).unwrap();
3212
    let url = root.join("origin").to_string_lossy().to_string();
3213
    let mut a = Repo::clone(&url, &root.join("a"))
3214
        .unwrap()
3215
        .with_home(root.join("home-a"));
3216
    a.set_user_config("core.sign", "change").unwrap();
3217
    let (key_a, _) = a
3218
        .create_identity("Ada", "[email protected]", IdentityScope::User)
3219
        .unwrap();
3220
    write(&root.join("a"), "a.txt", b"a\n");
3221
    let h1 = a.commit("one", &[]).unwrap();
3222
    assert!(a.policy_init().unwrap().applied);
3223
    assert!(a.push("origin", false).unwrap().iter().all(|r| r.ok));
3224
    origin.refresh().unwrap();
3225
3226
    // Expiry: an identity that had expired when the change was made does not authenticate it.
3227
    let mut e = Repo::init(&root.join("e"))
3228
        .unwrap()
3229
        .with_home(root.join("home-e"));
3230
    e.set_user_config("core.sign", "change").unwrap();
3231
    e.create_identity_with(
3232
        "Eve",
3233
        "[email protected]",
3234
        IdentityScope::User,
3235
        Some(Hlc::now().wall_ms - 1),
3236
    )
3237
    .unwrap();
3238
    write(&root.join("e"), "e.txt", b"e\n");
3239
    let he = e.commit("late", &[]).unwrap();
3240
    assert!(
3241
        matches!(e.verify_change(&he).unwrap(), SignatureStatus::Invalid(m) if m.contains("expired"))
3242
    );
3243
    // Renewal re-issues the identity (same keys, new KeyId) with a later expiry.
3244
    let r = e
3245
        .renew_identity(Some(Hlc::now().wall_ms + 86_400_000))
3246
        .unwrap();
3247
    assert_eq!(e.identity(&r.new).unwrap().previous, Some(r.old));
3248
    write(&root.join("e"), "e.txt", b"e2\n");
3249
    let he2 = e.commit("in time", &[]).unwrap();
3250
    assert!(
3251
        matches!(e.verify_change(&he2).unwrap(), SignatureStatus::Valid { key, .. } if key == r.new)
3252
    );
3253
3254
    // Rotation: a fresh key; the old change still verifies; the policy follows.
3255
    let r = a.rotate_identity().unwrap();
3256
    assert_eq!(r.old, key_a);
3257
    assert_eq!(a.config.author_key, Some(r.new));
3258
    assert_eq!(a.identity(&r.new).unwrap().previous, Some(key_a));
3259
    assert!(r.policy.as_ref().unwrap().applied);
3260
    let (_, sp) = a.current_policy().unwrap().unwrap();
3261
    assert_eq!(
3262
        (sp.policy.serial, sp.policy.roots.clone()),
3263
        (2, vec![r.new])
3264
    );
3265
    assert!(
3266
        !sp.policy.revoked.contains(&key_a) && sp.policy.authorizes(&r.new, "main"),
3267
        "superseded, not revoked"
3268
    );
3269
    assert!(sp.policy.succeeds(&r.new, &key_a) && !sp.policy.succeeds(&key_a, &r.new));
3270
    assert!(
3271
        matches!(a.verify_change(&h1).unwrap(), SignatureStatus::Valid { key, revoked: false, .. } if key == key_a)
3272
    );
3273
    write(&root.join("a"), "a.txt", b"a2\n");
3274
    let h2 = a.commit("two", &[]).unwrap();
3275
    assert!(
3276
        matches!(a.verify_change(&h2).unwrap(), SignatureStatus::Valid { key, revoked: false, .. } if key == r.new)
3277
    );
3278
    // Origin accepts the rotated policy (signed by the old root) and the new key's change.
3279
    let res = a.push("origin", false).unwrap();
3280
    origin.refresh().unwrap();
3281
    assert!(res.iter().all(|x| x.ok), "{res:?}");
3282
    assert_eq!(origin.current_policy().unwrap().unwrap().1.policy.serial, 2);
3283
    let key_a = r.new;
3284
3285
    // Delegation: Bob may sign on Ada's behalf. Delegates live in the
3286
    // identity object, so Ada's KeyId changes while her keys stay the same.
3287
    let mut b = Repo::clone(&url, &root.join("b"))
3288
        .unwrap()
3289
        .with_home(root.join("home-b"));
3290
    let (key_b, id_b) = b
3291
        .create_identity("Bob", "[email protected]", IdentityScope::User)
3292
        .unwrap();
3293
    let r = a.delegate_add(id_b.clone(), Scope::ALL, None).unwrap();
3294
    assert_eq!(r.old, key_a);
3295
    let key_a2 = r.new;
3296
    assert_eq!(
3297
        a.identity(&key_a2).unwrap().delegates,
3298
        vec![Delegate::full(key_b)]
3299
    );
3300
    assert_eq!(
3301
        a.identity(&key_a2).unwrap().ed25519_pk,
3302
        a.identity(&key_a).unwrap().ed25519_pk
3303
    );
3304
    assert!(
3305
        a.delegate_add(id_b.clone(), Scope::ALL, None).is_err(),
3306
        "already a delegate"
3307
    );
3308
    assert!(a.push("origin", false).unwrap().iter().all(|x| x.ok));
3309
    origin.refresh().unwrap();
3310
    write(&root.join("a"), "a.txt", b"a3\n");
3311
    let h3 = a.commit("three", &[]).unwrap();
3312
    assert!(
3313
        matches!(a.verify_change(&h3).unwrap(), SignatureStatus::Valid { key, .. } if key == key_a2),
3314
        "the same secret signs under the new KeyId"
3315
    );
3316
    // A change authored by Ada but signed only by Bob verifies through the delegation.
3317
    a.set_user_config("core.sign", "seal").unwrap();
3318
    write(&root.join("a"), "a.txt", b"a4\n");
3319
    let h4 = a.commit("four", &[]).unwrap();
3320
    assert_eq!(a.verify_change(&h4).unwrap(), SignatureStatus::Unsigned);
3321
    let (_, sk_b) = b.secret_key().unwrap().unwrap();
3322
    a.store()
3323
        .put_signature(&h4, &sk_b.sign(Domain::Change, &key_b, &h4))
3324
        .unwrap();
3325
    assert!(
3326
        matches!(a.verify_change(&h4).unwrap(), SignatureStatus::Valid { key, .. } if key == key_b)
3327
    );
3328
    a.set_user_config("core.sign", "change").unwrap();
3329
    // Withdrawing the delegation re-issues the identity again.
3330
    let r = a.delegate_remove(&key_b).unwrap();
3331
    assert!(a.identity(&r.new).unwrap().delegates.is_empty());
3332
    assert!(a.delegate_remove(&key_b).is_err());
3333
    let key_a3 = r.new;
3334
    let res = a.push("origin", false).unwrap();
3335
    origin.refresh().unwrap();
3336
    assert!(res.iter().all(|x| x.ok), "{res:?}");
3337
3338
    // Multi-signer policy: Bob becomes a root and the threshold rises to 2,
3339
    // both applied under the old threshold of 1. A grant then needs Bob too.
3340
    assert!(a.policy_root_add(id_b.clone()).unwrap().applied);
3341
    assert!(a.policy_root_add(id_b.clone()).is_err());
3342
    assert!(a.policy_set_threshold(3).is_err());
3343
    assert!(a.policy_set_threshold(2).unwrap().applied);
3344
    assert!(a.push("origin", false).unwrap().iter().all(|x| x.ok));
3345
    origin.refresh().unwrap();
3346
    b.pull("origin").unwrap();
3347
    assert_eq!(
3348
        b.current_policy().unwrap().unwrap().1.policy.root_threshold,
3349
        2
3350
    );
3351
    let mut c = Repo::init(&root.join("c"))
3352
        .unwrap()
3353
        .with_home(root.join("home-c"));
3354
    let (key_c, id_c) = c
3355
        .create_identity("Cy", "[email protected]", IdentityScope::User)
3356
        .unwrap();
3357
    let serial_before = a.current_policy().unwrap().unwrap().1.policy.serial;
3358
    let proposal = a.policy_grant(id_c, None).unwrap();
3359
    assert!(!proposal.applied && proposal.sigs.len() == 1);
3360
    assert_eq!(proposal.policy.serial, serial_before + 1);
3361
    assert_eq!(
3362
        a.current_policy().unwrap().unwrap().1.policy.serial,
3363
        serial_before,
3364
        "a proposal changes nothing yet"
3365
    );
3366
    // Bob signs the proposal, handed over as a file, and it applies for him.
3367
    let bytes = proposal.signed().encode();
3368
    let signed = b
3369
        .policy_sign(SignedPolicy::decode(&bytes).unwrap())
3370
        .unwrap();
3371
    assert!(signed.applied && signed.sigs.len() == 2);
3372
    assert!(b
3373
        .current_policy()
3374
        .unwrap()
3375
        .unwrap()
3376
        .1
3377
        .policy
3378
        .authorizes(&key_c, "main"));
3379
    assert!(
3380
        b.policy_sign(signed.signed()).is_err(),
3381
        "a stale proposal is refused"
3382
    );
3383
    // Bob publishes it and Ada picks it up.
3384
    assert!(b
3385
        .push("origin", false)
3386
        .unwrap()
3387
        .iter()
3388
        .any(|x| x.name == "policy" && x.ok));
3389
    origin.refresh().unwrap();
3390
    a.pull("origin").unwrap();
3391
    assert_eq!(
3392
        a.current_policy().unwrap().unwrap().1.policy.serial,
3393
        serial_before + 1
3394
    );
3395
    // A root cannot revoke itself; revoking Cy needs both roots but is recorded locally at once.
3396
    assert!(a.policy_revoke(&key_a3).is_err());
3397
    let u = a
3398
        .revoke_identity(&key_c, "left the project")
3399
        .unwrap()
3400
        .unwrap();
3401
    assert!(!u.applied);
3402
    assert!(a.is_revoked(&key_c).unwrap());
3403
    assert!(!b.is_revoked(&key_c).unwrap());
3404
    let u = b.policy_sign(u.signed()).unwrap();
3405
    assert!(u.applied && u.policy.is_revoked(&key_c));
3406
    assert!(b.is_revoked(&key_c).unwrap());
3407
    // Bob can revoke Ada's root key, leaving himself as the only root (threshold 2 would be unmeetable).
3408
    assert!(
3409
        b.policy_revoke(&key_a3).is_err(),
3410
        "would leave one root for a threshold of 2"
3411
    );
3412
    // Revoking one's own key without a policy root works locally: a plain marker plus attestation.
3413
    let key_c_own = c.config.author_key.unwrap();
3414
    assert!(c
3415
        .revoke_identity(&key_c_own, "lost laptop")
3416
        .unwrap()
3417
        .is_none());
3418
    assert!(c.is_revoked(&key_c_own).unwrap());
3419
    assert_eq!(key_c_own, key_c);
3420
}
3421
3422
#[test]
3423
fn renames_are_detected_and_tracked_as_moves() {
3424
    hermetic();
3425
    let dir = tempfile::tempdir().unwrap();
3426
    let root = dir.path();
3427
    let repo = Repo::init(root).unwrap().with_home(root.join("home"));
3428
    write(
3429
        root,
3430
        "src/old.rs",
3431
        b"fn a() {}\nfn b() {}\nfn c() {}\nfn d() {}\n",
3432
    );
3433
    write(root, "img.bin", b"\x89PNG\0\0\x01\x02");
3434
    write(root, "tiny.txt", b"x\n");
3435
    let h1 = repo.commit("base", &[]).unwrap();
3436
    let node_old = repo.load_state(&[h1]).unwrap().materialize().files["src/old.rs"].node;
3437
    let node_img = repo.load_state(&[h1]).unwrap().materialize().files["img.bin"].node;
3438
3439
    // Rename with a small edit, a binary moved unchanged, and a rewrite
3440
    // that shares nothing with the removed file.
3441
    fs::remove_file(root.join("src/old.rs")).unwrap();
3442
    write(
3443
        root,
3444
        "lib/new.rs",
3445
        b"fn a() {}\nfn b() {}\nfn c() {}\nfn e() {}\n",
3446
    );
3447
    fs::remove_file(root.join("img.bin")).unwrap();
3448
    write(root, "assets/img.bin", b"\x89PNG\0\0\x01\x02");
3449
    fs::remove_file(root.join("tiny.txt")).unwrap();
3450
    write(root, "other.txt", b"completely different\n");
3451
    let snap = repo.snapshot("status").unwrap();
3452
    let statuses: Vec<(&str, ChangeStatus)> = snap
3453
        .statuses
3454
        .iter()
3455
        .map(|s| (s.path.as_str(), s.status))
3456
        .collect();
3457
    assert_eq!(
3458
        statuses,
3459
        vec![
3460
            ("assets/img.bin", ChangeStatus::Renamed),
3461
            ("lib/new.rs", ChangeStatus::Renamed),
3462
            ("other.txt", ChangeStatus::Added),
3463
            ("src", ChangeStatus::Removed),
3464
            ("tiny.txt", ChangeStatus::Removed)
3465
        ]
3466
    );
3467
    let h2 = repo.commit("move things", &[]).unwrap();
3468
    let c = repo.store().get_change(&h2).unwrap();
3469
    let moves: Vec<_> = c
3470
        .tree_ops
3471
        .iter()
3472
        .filter(|op| matches!(op, TreeOp::Move { .. }))
3473
        .collect();
3474
    assert_eq!(moves.len(), 2, "{:?}", c.tree_ops);
3475
    assert!(c.tree_ops.iter().any(
3476
        |op| matches!(op, TreeOp::Move { node, name, .. } if *node == node_old && name == "new.rs")
3477
    ));
3478
    assert!(c.tree_ops.iter().any(
3479
        |op| matches!(op, TreeOp::Move { node, name, .. } if *node == node_img && name == "img.bin")
3480
    ));
3481
    let snap = repo.load_state(&[h2]).unwrap().materialize();
3482
    assert_eq!(
3483
        snap.files["lib/new.rs"].node, node_old,
3484
        "the node survives the rename"
3485
    );
3486
    assert!(
3487
        matches!(&snap.files["lib/new.rs"].content, FileContent::Text { bytes, .. } if bytes == b"fn a() {}\nfn b() {}\nfn c() {}\nfn e() {}\n")
3488
    );
3489
    assert!(!snap.files.contains_key("src/old.rs") && !snap.files.contains_key("src"));
3490
    assert!(render_change(
3491
        &c,
3492
        &repo.load_state(&[h1]).unwrap(),
3493
        &repo.load_state(&[h1]).unwrap().materialize()
3494
    )
3495
    .contains("R src/old.rs -> lib/new.rs"));
3496
    // A fresh checkout reproduces the tree.
3497
    let other = tempfile::tempdir().unwrap();
3498
    let clone = Repo::clone(&root.to_string_lossy(), other.path()).unwrap();
3499
    assert_eq!(
3500
        fs::read(other.path().join("lib/new.rs")).unwrap(),
3501
        b"fn a() {}\nfn b() {}\nfn c() {}\nfn e() {}\n"
3502
    );
3503
    assert!(!other.path().join("src").exists());
3504
    assert!(!clone.snapshot("status").unwrap().changed);
3505
    // Similarity is line based, byte weighted.
3506
    assert_eq!(similarity(b"a\nb\n", b"a\nb\n"), 100);
3507
    assert_eq!(similarity(b"a\nb\nc\nd\n", b"a\nb\nx\ny\n"), 50);
3508
    assert_eq!(similarity(b"hello\n", b"world\n"), 0);
3509
    assert_eq!(similarity(b"", b"x\n"), 0);
3510
}
3511
3512
#[test]
3513
fn git_fetch_and_push_round_trip() {
3514
    hermetic();
3515
    if std::process::Command::new("git")
3516
        .arg("--version")
3517
        .output()
3518
        .is_err()
3519
    {
3520
        eprintln!("git not installed; skipping");
3521
        return;
3522
    }
3523
    let dir = tempfile::tempdir().unwrap();
3524
    let root = dir.path();
3525
    let git_in = |d: &Path, args: &[&str]| -> String {
3526
        let out = std::process::Command::new("git")
3527
            .arg("-C")
3528
            .arg(d)
3529
            .args([
3530
                "-c",
3531
                "user.name=Grace",
3532
                "-c",
3533
                "[email protected]",
3534
                "-c",
3535
                "commit.gpgsign=false",
3536
            ])
3537
            .args(args)
3538
            .output()
3539
            .unwrap();
3540
        assert!(
3541
            out.status.success(),
3542
            "git {args:?}: {}",
3543
            String::from_utf8_lossy(&out.stderr)
3544
        );
3545
        String::from_utf8_lossy(&out.stdout).trim().to_string()
3546
    };
3547
    // A bare "remote" and a work tree that pushes to it.
3548
    let remote = root.join("remote.git");
3549
    fs::create_dir_all(&remote).unwrap();
3550
    git_in(&remote, &["init", "-q", "--bare", "-b", "main"]);
3551
    let work = root.join("work");
3552
    git_in(
3553
        root,
3554
        &[
3555
            "clone",
3556
            "-q",
3557
            remote.to_str().unwrap(),
3558
            work.to_str().unwrap(),
3559
        ],
3560
    );
3561
    git_in(&work, &["checkout", "-q", "-b", "main"]);
3562
    write(&work, "README.md", b"# Project\n");
3563
    write(&work, "src/lib.rs", b"pub fn a() {}\n");
3564
    git_in(&work, &["add", "."]);
3565
    git_in(&work, &["commit", "-q", "-m", "initial"]);
3566
    write(&work, "src/lib.rs", b"pub fn a() {}\npub fn b() {}\n");
3567
    git_in(&work, &["commit", "-q", "-am", "second"]);
3568
    git_in(&work, &["push", "-q", "origin", "main"]);
3569
    let tip1 = git_in(&work, &["rev-parse", "HEAD"]);
3570
3571
    // Fetch into a fresh oxy repository.
3572
    let o = root.join("oxy");
3573
    let mut repo = Repo::init(&o).unwrap().with_home(root.join("home"));
3574
    repo.create_identity("Ada", "[email protected]", IdentityScope::User)
3575
        .unwrap();
3576
    let url = remote.to_string_lossy().to_string();
3577
    let r = repo.git_fetch(&url, "main").unwrap();
3578
    assert_eq!((r.commits, r.heads), (2, 1));
3579
    assert_eq!(
3580
        fs::read(o.join("src/lib.rs")).unwrap(),
3581
        b"pub fn a() {}\npub fn b() {}\n"
3582
    );
3583
    assert!(!repo.snapshot("status").unwrap().changed);
3584
    assert_eq!(
3585
        repo.git_fetch(&url, "main").unwrap().commits,
3586
        0,
3587
        "nothing new"
3588
    );
3589
3590
    // An oxy change, pushed back: one commit on top of the Git tip.
3591
    write(
3592
        &o,
3593
        "src/lib.rs",
3594
        b"pub fn a() {}\npub fn b() {}\npub fn c() {}\n",
3595
    );
3596
    write(&o, "NOTES.md", b"from oxy\n");
3597
    let h_oxy = repo.commit("add c and notes", &[]).unwrap();
3598
    let r = repo.git_push(&url, "main").unwrap();
3599
    assert_eq!(r.exported, 1, "{r:?}");
3600
    git_in(&work, &["pull", "-q", "--ff-only", "origin", "main"]);
3601
    assert_eq!(
3602
        git_in(&work, &["log", "--format=%s", "main"]),
3603
        "add c and notes\nsecond\ninitial"
3604
    );
3605
    assert_eq!(git_in(&work, &["rev-parse", "HEAD~1"]), tip1);
3606
    assert_eq!(fs::read(work.join("NOTES.md")).unwrap(), b"from oxy\n");
3607
    assert_eq!(git_in(&work, &["log", "-1", "--format=%an", "main"]), "Ada");
3608
    assert!(git_in(&work, &["log", "-1", "--format=%B", "main"])
3609
        .contains(&format!("Oxy-Hash: {}", h_oxy.to_hex())));
3610
    assert_eq!(
3611
        repo.git_push(&url, "main").unwrap().exported,
3612
        0,
3613
        "already pushed"
3614
    );
3615
3616
    // Git moves on; pushing without fetching is refused, fetching brings
3617
    // the commit in and the working copy follows.
3618
    write(&work, "README.md", b"# Project\n\nMore.\n");
3619
    git_in(&work, &["commit", "-q", "-am", "readme from git"]);
3620
    git_in(&work, &["push", "-q", "origin", "main"]);
3621
    let tip2 = git_in(&work, &["rev-parse", "HEAD"]);
3622
    assert!(repo
3623
        .git_push(&url, "main")
3624
        .unwrap_err()
3625
        .to_string()
3626
        .contains("fetch"));
3627
    let r = repo.git_fetch(&url, "main").unwrap();
3628
    assert_eq!(
3629
        (r.commits, r.heads),
3630
        (1, 2),
3631
        "the Git change and the oxy change commute"
3632
    );
3633
    assert_eq!(
3634
        fs::read(o.join("README.md")).unwrap(),
3635
        b"# Project\n\nMore.\n"
3636
    );
3637
    assert_eq!(fs::read(o.join("NOTES.md")).unwrap(), b"from oxy\n");
3638
    assert!(!repo.snapshot("status").unwrap().changed);
3639
    // Another oxy change pushes on top of Git's newest commit.
3640
    write(&o, "NOTES.md", b"from oxy\nagain\n");
3641
    repo.commit("notes again", &[]).unwrap();
3642
    assert_eq!(repo.git_push(&url, "main").unwrap().exported, 1);
3643
    git_in(&work, &["pull", "-q", "--ff-only", "origin", "main"]);
3644
    assert_eq!(git_in(&work, &["rev-parse", "HEAD~1"]), tip2);
3645
    assert_eq!(
3646
        fs::read(work.join("NOTES.md")).unwrap(),
3647
        b"from oxy\nagain\n"
3648
    );
3649
    assert_eq!(
3650
        git_in(&work, &["log", "--format=%s", "main"])
3651
            .lines()
3652
            .count(),
3653
        5
3654
    );
3655
}
3656
3657
/// Benchmark, not a gate: `cargo test --release -p oxy-core --lib bench_one_gibibyte -- --ignored --nocapture`.
3658
/// Commits, stores, clones, and reads back a 1 GiB incompressible file.
3659
#[test]
3660
#[ignore]
3661
fn bench_one_gibibyte_file() {
3662
    hermetic();
3663
    // /tmp is often a small tmpfs; `OXY_BENCH_DIR` picks a roomier disk.
3664
    let dir = match std::env::var_os("OXY_BENCH_DIR") {
3665
        Some(d) => tempfile::tempdir_in(d).unwrap(),
3666
        None => tempfile::tempdir().unwrap(),
3667
    };
3668
    let root = dir.path();
3669
    let repo = Repo::init(&root.join("r"))
3670
        .unwrap()
3671
        .with_home(root.join("home"));
3672
    let size = 1usize << 30;
3673
    let mut data = vec![0u8; size];
3674
    let mut x = 0x9e3779b97f4a7c15u64;
3675
    for chunk in data.chunks_mut(8) {
3676
        x ^= x << 13;
3677
        x ^= x >> 7;
3678
        x ^= x << 17;
3679
        let b = x.to_le_bytes();
3680
        chunk.copy_from_slice(&b[..chunk.len()]);
3681
    }
3682
    let t = std::time::Instant::now();
3683
    write(&root.join("r"), "big.bin", &data);
3684
    eprintln!("write 1 GiB to disk: {:.2?}", t.elapsed());
3685
    let t = std::time::Instant::now();
3686
    let h = repo.commit("big", &[]).unwrap();
3687
    eprintln!("commit (chunk + hash + store): {:.2?}", t.elapsed());
3688
    let t = std::time::Instant::now();
3689
    assert!(!repo.snapshot("status").unwrap().changed);
3690
    eprintln!("status on a clean 1 GiB working copy: {:.2?}", t.elapsed());
3691
    let t = std::time::Instant::now();
3692
    let objects = repo.store().list().unwrap().len();
3693
    eprintln!("objects stored: {objects} ({:.2?} to list)", t.elapsed());
3694
    let t = std::time::Instant::now();
3695
    let g = repo.gc(true).unwrap();
3696
    eprintln!("gc (pack): {:.2?} {g:?}", t.elapsed());
3697
    let t = std::time::Instant::now();
3698
    let clone = Repo::clone(&root.join("r").to_string_lossy(), &root.join("c")).unwrap();
3699
    eprintln!("clone (fetch + checkout): {:.2?}", t.elapsed());
3700
    let t = std::time::Instant::now();
3701
    let back = fs::read(root.join("c/big.bin")).unwrap();
3702
    assert_eq!(blake3::hash(&back), blake3::hash(&data));
3703
    eprintln!("read back and verify: {:.2?}", t.elapsed());
3704
    assert_eq!(clone.bookmark_heads().unwrap(), vec![h]);
3705
    let store_bytes: u64 = walkdir_size(&root.join("r/.oxy/objects"));
3706
    eprintln!(
3707
        "store size: {:.1} MiB for 1 GiB of data",
3708
        store_bytes as f64 / (1024.0 * 1024.0)
3709
    );
3710
}
3711
3712
fn walkdir_size(p: &Path) -> u64 {
3713
    let mut total = 0;
3714
    if let Ok(rd) = fs::read_dir(p) {
3715
        for e in rd.flatten() {
3716
            let path = e.path();
3717
            if path.is_dir() {
3718
                total += walkdir_size(&path);
3719
            } else if let Ok(m) = fs::metadata(&path) {
3720
                total += m.len();
3721
            }
3722
        }
3723
    }
3724
    total
3725
}
3726
3727
/// An opaque file whose size and mtime match the manifest is not read on
3728
/// the next snapshot: its blob comes from the manifest's stat cache.
3729
#[cfg(unix)]
3730
#[test]
3731
fn stat_cache_skips_reading_unchanged_opaque_files() {
3732
    use std::os::unix::fs::PermissionsExt;
3733
    hermetic();
3734
    let dir = tempfile::tempdir().unwrap();
3735
    let root = dir.path();
3736
    let repo = Repo::init(root).unwrap().with_home(root.join("home"));
3737
    let mut big = vec![0u8; 300 * 1024];
3738
    for (i, b) in big.iter_mut().enumerate() {
3739
        *b = (i as u32).wrapping_mul(2654435761).to_le_bytes()[1];
3740
    }
3741
    big[0] = 0;
3742
    write(root, "big.bin", &big);
3743
    write(root, "a.txt", b"text\n");
3744
    let h1 = repo.commit("base", &[]).unwrap();
3745
    let (_, _, m) = repo.read_manifest().unwrap().unwrap();
3746
    assert!(
3747
        m.entries["big.bin"].blob.is_some(),
3748
        "opaque files record their blob"
3749
    );
3750
    assert!(m.entries["a.txt"].blob.is_none());
3751
    let blob = m.entries["big.bin"].blob.unwrap();
3752
    assert!(repo.store().has(&blob));
3753
3754
    // Files modified within two seconds of the manifest are racy and still
3755
    // read; age the file so the cache applies, then snapshot to record it.
3756
    let old = std::time::SystemTime::now() - std::time::Duration::from_secs(30);
3757
    fs::File::options()
3758
        .write(true)
3759
        .open(root.join("big.bin"))
3760
        .unwrap()
3761
        .set_modified(old)
3762
        .unwrap();
3763
    assert!(!repo.snapshot("status").unwrap().changed);
3764
    // Now the file cannot be read at all; the snapshot succeeds without it.
3765
    fs::set_permissions(root.join("big.bin"), fs::Permissions::from_mode(0o000)).unwrap();
3766
    let snap = repo.snapshot("status").unwrap();
3767
    assert!(
3768
        !snap.changed && snap.statuses.is_empty(),
3769
        "{:?}",
3770
        snap.statuses
3771
    );
3772
    fs::set_permissions(root.join("big.bin"), fs::Permissions::from_mode(0o644)).unwrap();
3773
    // A real change (new mtime, new content) is seen and committed correctly.
3774
    let mut big2 = big.clone();
3775
    big2[10] ^= 0xff;
3776
    write(root, "big.bin", &big2);
3777
    let snap = repo.snapshot("status").unwrap();
3778
    assert_eq!(
3779
        snap.statuses
3780
            .iter()
3781
            .map(|s| (s.path.as_str(), s.status))
3782
            .collect::<Vec<_>>(),
3783
        vec![("big.bin", ChangeStatus::Modified)]
3784
    );
3785
    let h2 = repo.commit("edit", &[]).unwrap();
3786
    let files = repo.load_state(&[h2]).unwrap().materialize().files;
3787
    assert_eq!(
3788
        files["big.bin"].content,
3789
        FileContent::Opaque {
3790
            blobs: vec![Repo::blob_ref(&big2)]
3791
        }
3792
    );
3793
    // Checkout writes a manifest with blobs too, so the next status is cached.
3794
    repo.checkout(&[h1], false, "checkout").unwrap();
3795
    let (_, _, m) = repo.read_manifest().unwrap().unwrap();
3796
    assert_eq!(m.entries["big.bin"].blob, Some(Repo::blob_ref(&big)));
3797
    assert!(!repo.snapshot("status").unwrap().changed);
3798
}
3799
3800
#[test]
3801
fn status_json_lists_conflicts_with_contributors() {
3802
    hermetic();
3803
    let dir = tempfile::tempdir().unwrap();
3804
    let root = dir.path();
3805
    let repo = Repo::init(root).unwrap().with_home(root.join("home"));
3806
    write(root, "a.txt", b"one\n");
3807
    let h1 = repo.commit("base", &[]).unwrap();
3808
    write(root, "a.txt", b"one\nleft\n");
3809
    let ha = repo.commit("left", &[]).unwrap();
3810
    repo.checkout(&[h1], true, "checkout").unwrap();
3811
    write(root, "a.txt", b"one\nright\n");
3812
    let hb = repo.commit("right", &[]).unwrap();
3813
    repo.checkout(&[ha, hb], true, "checkout").unwrap();
3814
    let snap = repo.snapshot("status").unwrap();
3815
    assert!(snap.base_snapshot.is_conflicted());
3816
    let json = repo.status_json(&snap).unwrap();
3817
    let ida = repo.store().get_change(&ha).unwrap().change_id.to_hex();
3818
    let idb = repo.store().get_change(&hb).unwrap().change_id.to_hex();
3819
    assert!(json.contains("\"conflicted\":true"), "{json}");
3820
    assert!(
3821
        json.contains("\"kind\":\"text\",\"path\":\"a.txt\""),
3822
        "{json}"
3823
    );
3824
    assert!(json.contains(&ida) && json.contains(&idb), "{json}");
3825
    assert!(json.contains("\"resolved\":false"), "{json}");
3826
    assert!(json.starts_with('{') && json.ends_with('}'));
3827
    // Resolve and the report says so; a clean copy has no conflicts.
3828
    write(root, "a.txt", b"one\nleft\nright\n");
3829
    let snap = repo.snapshot("status").unwrap();
3830
    let json = repo.status_json(&snap).unwrap();
3831
    assert!(json.contains("\"resolved\":true"), "{json}");
3832
    repo.commit("resolve", &[]).unwrap();
3833
    let snap = repo.snapshot("status").unwrap();
3834
    let json = repo.status_json(&snap).unwrap();
3835
    assert!(
3836
        json.contains("\"clean\":true,\"conflicted\":false,\"paths\":[],\"conflicts\":[]"),
3837
        "{json}"
3838
    );
3839
}
3840
3841
#[test]
3842
fn ignore_rules_do_not_untrack_files() {
3843
    hermetic();
3844
    let dir = tempfile::tempdir().unwrap();
3845
    let root = dir.path();
3846
    let repo = Repo::init(root).unwrap().with_home(root.join("home"));
3847
    write(root, "src.c", b"int x;\n");
3848
    write(root, "build/out.o", b"\0obj");
3849
    write(root, "sub/keep.log", b"keep\n");
3850
    write(root, "sub/junk.log", b"junk\n");
3851
    write(root, ".oxyignore", b"/build\n*.log\n!sub/keep.log\n");
3852
    let snap = repo.snapshot("status").unwrap();
3853
    let added: Vec<&str> = snap.statuses.iter().map(|s| s.path.as_str()).collect();
3854
    assert_eq!(
3855
        added,
3856
        vec![".oxyignore", "src.c", "sub/keep.log"],
3857
        "anchored, glob, and negated rules"
3858
    );
3859
    let h1 = repo.commit("base", &[]).unwrap();
3860
    // Ignoring a tracked file changes nothing about it.
3861
    write(root, ".oxyignore", b"/build\n*.log\n!sub/keep.log\nsrc.c\n");
3862
    let snap = repo.snapshot("status").unwrap();
3863
    assert_eq!(
3864
        snap.statuses
3865
            .iter()
3866
            .map(|s| s.path.as_str())
3867
            .collect::<Vec<_>>(),
3868
        vec![".oxyignore"]
3869
    );
3870
    let h2 = repo.commit("ignore src.c", &[]).unwrap();
3871
    assert!(repo
3872
        .load_state(&[h2])
3873
        .unwrap()
3874
        .materialize()
3875
        .files
3876
        .contains_key("src.c"));
3877
    // Its edits are still seen, by status and by the prompt.
3878
    assert_eq!(repo.quick_dirty().unwrap(), Some(false));
3879
    write(root, "src.c", b"int x, y;\n");
3880
    assert_eq!(repo.quick_dirty().unwrap(), Some(true));
3881
    let snap = repo.snapshot("status").unwrap();
3882
    assert_eq!(
3883
        snap.statuses
3884
            .iter()
3885
            .map(|s| (s.path.as_str(), s.status))
3886
            .collect::<Vec<_>>(),
3887
        vec![("src.c", ChangeStatus::Modified)]
3888
    );
3889
    let h3 = repo.commit("edit src.c", &[]).unwrap();
3890
    assert!(
3891
        matches!(&repo.load_state(&[h3]).unwrap().materialize().files["src.c"].content, FileContent::Text { bytes, .. } if bytes == b"int x, y;\n")
3892
    );
3893
    // Deleting it on disk removes it, ignored or not; a checkout brings it back.
3894
    fs::remove_file(root.join("src.c")).unwrap();
3895
    let snap = repo.snapshot("status").unwrap();
3896
    assert_eq!(
3897
        snap.statuses
3898
            .iter()
3899
            .map(|s| (s.path.as_str(), s.status))
3900
            .collect::<Vec<_>>(),
3901
        vec![("src.c", ChangeStatus::Removed)]
3902
    );
3903
    repo.checkout(&[h3], true, "checkout").unwrap();
3904
    assert_eq!(fs::read(root.join("src.c")).unwrap(), b"int x, y;\n");
3905
    assert!(!repo.snapshot("status").unwrap().changed);
3906
    let _ = h1;
3907
}
3908
3909
#[test]
3910
fn split_works_on_non_heads_by_node() {
3911
    hermetic();
3912
    let dir = tempfile::tempdir().unwrap();
3913
    let root = dir.path();
3914
    let repo = Repo::init(root).unwrap().with_home(root.join("home"));
3915
    write(root, "a.txt", b"one\n");
3916
    write(root, "junk/x.lock", b"lock\n");
3917
    let h1 = repo.commit("work plus junk", &[]).unwrap();
3918
    write(root, "a.txt", b"one\ntwo\n");
3919
    let h2 = repo.commit("more work", &[]).unwrap();
3920
    assert_eq!(repo.store().get_change(&h2).unwrap().deps, vec![h1]);
3921
    let id1 = repo.store().get_change(&h1).unwrap().change_id;
3922
    // h1 is not a head: split it by node.
3923
    let (hj, h1b) = repo.split(&h1, &["junk".into()]).unwrap();
3924
    assert_ne!(h1b, h1);
3925
    assert_eq!(
3926
        repo.store().get_change(&h1b).unwrap().change_id,
3927
        id1,
3928
        "the rest keeps the ChangeId"
3929
    );
3930
    let junk = repo.store().get_change(&hj).unwrap();
3931
    assert!(junk.tree_ops.iter().all(
3932
        |op| matches!(op, TreeOp::AddNode { name, .. } if name == "junk" || name == "x.lock")
3933
    ));
3934
    let heads = repo.bookmark_heads().unwrap();
3935
    assert!(
3936
        heads.contains(&hj),
3937
        "the split-off part is a head of its own"
3938
    );
3939
    let snap = repo.load_state(&heads).unwrap().materialize();
3940
    assert!(
3941
        matches!(&snap.files["a.txt"].content, FileContent::Text { bytes, .. } if bytes == b"one\ntwo\n"),
3942
        "the dependent was rewritten onto the new hash"
3943
    );
3944
    assert!(snap.files.contains_key("junk/x.lock"));
3945
    let h2b = heads
3946
        .iter()
3947
        .find(|h| repo.store().get_change(h).unwrap().message == "more work")
3948
        .copied()
3949
        .unwrap();
3950
    assert_eq!(repo.store().get_change(&h2b).unwrap().deps, vec![h1b]);
3951
    assert!(!repo.snapshot("status").unwrap().changed);
3952
    // Abandoning the split-off head removes the junk from history.
3953
    repo.abandon(&hj).unwrap();
3954
    let heads = repo.bookmark_heads().unwrap();
3955
    let snap = repo.load_state(&heads).unwrap().materialize();
3956
    assert!(!snap.files.contains_key("junk/x.lock") && !snap.files.contains_key("junk"));
3957
    assert!(snap.files.contains_key("a.txt"));
3958
    // A dependent that touches the split-off paths blocks the split.
3959
    write(root, "junk/y.lock", b"y\n");
3960
    let hb = repo.commit("junk base", &[]).unwrap();
3961
    write(root, "junk/y.lock", b"yy\n");
3962
    write(root, "b.txt", b"b\n");
3963
    repo.commit("touches junk", &[]).unwrap();
3964
    let err = repo.split(&hb, &["junk".into()]).unwrap_err().to_string();
3965
    assert!(err.contains("depends on the split-off paths"), "{err}");
3966
}
3967
3968
#[test]
3969
fn bookmarks_switch_merge_and_push() {
3970
    hermetic();
3971
    let dir = tempfile::tempdir().unwrap();
3972
    let root = dir.path();
3973
    let origin = Repo::init(&root.join("origin")).unwrap();
3974
    let url = root.join("origin").to_string_lossy().to_string();
3975
    let mut repo = Repo::clone(&url, &root.join("r"))
3976
        .unwrap()
3977
        .with_home(root.join("home"));
3978
    let r = root.join("r");
3979
    write(&r, "a.txt", b"a\n");
3980
    let h_a = repo.commit("a", &[]).unwrap();
3981
    assert!(repo.push("origin", false).unwrap()[0].ok);
3982
    origin.refresh().unwrap();
3983
3984
    // A bookmark at the working copy's base, then work on it.
3985
    assert!(repo.bookmark_create("bad name..", None).is_err());
3986
    assert!(repo.bookmark_create("-x", None).is_err());
3987
    assert_eq!(repo.bookmark_create("feature", None).unwrap(), vec![h_a]);
3988
    assert!(repo.bookmark_create("feature", None).is_err(), "exists");
3989
    repo.bookmark_switch("feature", false).unwrap();
3990
    assert_eq!(repo.config.bookmark, "feature");
3991
    write(&r, "a.txt", b"a\nb\n");
3992
    write(&r, "b.txt", b"b\n");
3993
    let h_b = repo.commit("b on feature", &[]).unwrap();
3994
    assert_eq!(
3995
        repo.bookmark_heads().unwrap(),
3996
        vec![h_b],
3997
        "b edits a.txt, so it depends on a"
3998
    );
3999
    assert_eq!(
4000
        repo.resolve_heads("main").unwrap(),
4001
        vec![h_a],
4002
        "main is untouched"
4003
    );
4004
    assert_eq!(
4005
        repo.resolve_change("feature").unwrap(),
4006
        h_b,
4007
        "a one-head bookmark names its change"
4008
    );
4009
    // Reopening keeps the workspace's bookmark.
4010
    let reopened = Repo::open(&r).unwrap().with_home(root.join("home"));
4011
    assert_eq!(reopened.config.bookmark, "feature");
4012
    // Back to main: b.txt goes away; work there.
4013
    repo.bookmark_switch("main", false).unwrap();
4014
    assert!(!r.join("b.txt").exists());
4015
    assert_eq!(fs::read(r.join("a.txt")).unwrap(), b"a\n");
4016
    write(&r, "c.txt", b"c\n");
4017
    let h_c = repo.commit("c on main", &[]).unwrap();
4018
    let list = repo.bookmarks().unwrap();
4019
    assert_eq!(
4020
        list.iter()
4021
            .map(|b| (b.name.as_str(), b.current))
4022
            .collect::<Vec<_>>(),
4023
        vec![("feature", false), ("main", true)]
4024
    );
4025
    assert_eq!(
4026
        list.iter().find(|b| b.name == "main").unwrap().ahead,
4027
        Some(1),
4028
        "c is not on origin yet"
4029
    );
4030
    // Merge feature into main: the union, both heads, no merge change.
4031
    let m = repo.merge("feature").unwrap();
4032
    assert!(m.changed && m.checked_out);
4033
    let mut want = vec![h_b, h_c];
4034
    want.sort();
4035
    assert_eq!(m.heads, want);
4036
    assert_eq!(fs::read(r.join("b.txt")).unwrap(), b"b\n");
4037
    assert!(!repo.merge("feature").unwrap().changed, "already merged");
4038
    assert!(repo.merge("main").is_err());
4039
    // The other bookmark can be pushed by name and appears at origin.
4040
    assert!(repo.push_bookmark("origin", "feature", false).unwrap()[0].ok);
4041
    origin.refresh().unwrap();
4042
    assert_eq!(origin.resolve_heads("feature").unwrap(), vec![h_b]);
4043
    assert!(repo.push("origin", false).unwrap()[0].ok);
4044
    origin.refresh().unwrap();
4045
    assert_eq!(
4046
        repo.bookmarks()
4047
            .unwrap()
4048
            .iter()
4049
            .find(|b| b.name == "main")
4050
            .unwrap()
4051
            .ahead,
4052
        Some(0)
4053
    );
4054
    // A second workspace inherits the current bookmark and can switch independently.
4055
    let ws = repo.workspace_add(&root.join("ws"), None).unwrap();
4056
    assert_eq!(ws.config.bookmark, "main");
4057
    let mut ws = ws;
4058
    ws.bookmark_switch("feature", false).unwrap();
4059
    assert_eq!(
4060
        Repo::open(&r).unwrap().config.bookmark,
4061
        "main",
4062
        "the first workspace is unaffected"
4063
    );
4064
    assert!(
4065
        repo.bookmark_delete("feature").is_err(),
4066
        "current bookmark of another workspace"
4067
    );
4068
    ws.bookmark_switch("main", false).unwrap();
4069
    // Set and delete.
4070
    assert_eq!(repo.bookmark_set("feature", &[h_a]).unwrap(), vec![h_a]);
4071
    assert!(repo.bookmark_delete("main").is_err(), "current here");
4072
    repo.bookmark_delete("feature").unwrap();
4073
    assert!(repo.resolve_heads("feature").is_err());
4074
    assert!(repo.bookmark_set("feature", &[h_a]).is_err());
4075
    assert!(
4076
        repo.checkout(&[h_a], false, "checkout").is_ok(),
4077
        "changes of a deleted bookmark remain"
4078
    );
4079
}
4080
4081
#[test]
4082
fn oxygen_subrepos_pin_follow_and_update() {
4083
    hermetic();
4084
    let dir = tempfile::tempdir().unwrap();
4085
    let root = dir.path();
4086
    // A library repository with two commits, and a bare-ish origin for it.
4087
    let lib_origin = Repo::init(&root.join("lib-origin")).unwrap();
4088
    let lib_url = root.join("lib-origin").to_string_lossy().to_string();
4089
    let lib = Repo::clone(&lib_url, &root.join("lib"))
4090
        .unwrap()
4091
        .with_home(root.join("home"));
4092
    write(&root.join("lib"), "lib.txt", b"v1\n");
4093
    let l1 = lib.commit("lib v1", &[]).unwrap();
4094
    assert!(lib.push("origin", false).unwrap()[0].ok);
4095
    let _ = lib_origin;
4096
4097
    // The application (a clone of its own origin) adds it as a subrepo.
4098
    let app_origin = Repo::init(&root.join("app-origin")).unwrap();
4099
    let app_url = root.join("app-origin").to_string_lossy().to_string();
4100
    let _ = app_origin;
4101
    let app_dir = root.join("app");
4102
    let app = Repo::clone(&app_url, &app_dir)
4103
        .unwrap()
4104
        .with_home(root.join("home"));
4105
    write(&app_dir, "main.txt", b"app\n");
4106
    let pin = app.submodule_add(&lib_url, "libs/lib", None).unwrap();
4107
    assert!(matches!(&pin, crate::subrepo::Pin::Oxy { heads, .. } if heads == &vec![l1]));
4108
    assert!(app_dir.join(".oxymodules").exists() && app_dir.join("libs/lib/.oxy").is_dir());
4109
    let snap = app.snapshot("status").unwrap();
4110
    let paths: Vec<&str> = snap.statuses.iter().map(|s| s.path.as_str()).collect();
4111
    assert_eq!(
4112
        paths,
4113
        vec![".oxymodules", "libs/lib", "main.txt"],
4114
        "the nested files are not walked"
4115
    );
4116
    let a1 = app.commit("app with lib", &[]).unwrap();
4117
    let files = app.load_state(&[a1]).unwrap().materialize().files;
4118
    assert_eq!(files["libs/lib"].kind, NodeKind::Subrepo);
4119
    assert!(!files.contains_key("libs/lib/lib.txt"));
4120
    assert!(!app.snapshot("status").unwrap().changed);
4121
    let subs = app.subrepos().unwrap();
4122
    assert_eq!(subs.len(), 1);
4123
    assert_eq!(subs[0].actual.as_ref(), Some(&subs[0].pin));
4124
4125
    // Advance the nested repository: the parent sees a modified pin.
4126
    let nested = Repo::open(&app_dir.join("libs/lib"))
4127
        .unwrap()
4128
        .with_home(root.join("home"));
4129
    write(&app_dir.join("libs/lib"), "lib.txt", b"v2\n");
4130
    let l2 = nested.commit("lib v2", &[]).unwrap();
4131
    assert!(nested.push("origin", false).unwrap()[0].ok);
4132
    let snap = app.snapshot("status").unwrap();
4133
    assert_eq!(
4134
        snap.statuses
4135
            .iter()
4136
            .map(|s| (s.path.as_str(), s.status))
4137
            .collect::<Vec<_>>(),
4138
        vec![("libs/lib", ChangeStatus::Modified)]
4139
    );
4140
    let a2 = app.commit("bump lib", &[]).unwrap();
4141
    // Checking out the older app state brings the nested working copy back
4142
    // to the older pin, but never moves its bookmark backwards (oxygen#38).
4143
    let r = app.checkout(&[a1], false, "checkout").unwrap();
4144
    assert!(
4145
        r.notes.len() == 1 && r.notes[0].contains("keeps 1 newer change"),
4146
        "{:?}",
4147
        r.notes
4148
    );
4149
    assert_eq!(fs::read(app_dir.join("libs/lib/lib.txt")).unwrap(), b"v1\n");
4150
    let nested = Repo::open(&app_dir.join("libs/lib")).unwrap();
4151
    assert_eq!(nested.bookmark_heads().unwrap(), vec![l2]);
4152
    assert_eq!(nested.working_copy().unwrap().1.deps, vec![l1]);
4153
    assert!(!app.snapshot("status").unwrap().changed);
4154
    // A dirty nested repository is left alone and reported.
4155
    write(&app_dir.join("libs/lib"), "scratch.txt", b"wip\n");
4156
    let r = app.checkout(&[a2], false, "checkout").unwrap();
4157
    assert!(
4158
        r.notes.iter().any(|n| n.contains("uncommitted")),
4159
        "{:?}",
4160
        r.notes
4161
    );
4162
    assert_eq!(fs::read(app_dir.join("libs/lib/lib.txt")).unwrap(), b"v1\n");
4163
    fs::remove_file(app_dir.join("libs/lib/scratch.txt")).unwrap();
4164
    let r = app.submodule_update(false, &[]).unwrap();
4165
    assert_eq!(r, vec![("libs/lib".to_string(), SubrepoSync::Updated)]);
4166
    assert_eq!(fs::read(app_dir.join("libs/lib/lib.txt")).unwrap(), b"v2\n");
4167
    let _ = l2;
4168
4169
    // A fresh clone of the app has the pin but no nested repository until update --init.
4170
    assert!(app.push("origin", false).unwrap()[0].ok);
4171
    let clone_dir = root.join("app-clone");
4172
    let clone = Repo::clone(&app_url, &clone_dir)
4173
        .unwrap()
4174
        .with_home(root.join("home"));
4175
    assert!(!clone_dir.join("libs/lib/.oxy").exists());
4176
    assert_eq!(
4177
        clone.submodule_update(false, &[]).unwrap(),
4178
        vec![("libs/lib".to_string(), SubrepoSync::Missing)]
4179
    );
4180
    assert_eq!(
4181
        clone.submodule_update(true, &[]).unwrap(),
4182
        vec![("libs/lib".to_string(), SubrepoSync::Updated)]
4183
    );
4184
    assert_eq!(
4185
        fs::read(clone_dir.join("libs/lib/lib.txt")).unwrap(),
4186
        b"v2\n"
4187
    );
4188
    assert!(!clone.snapshot("status").unwrap().changed);
4189
    // Removing the subrepo leaves the directory and drops the node.
4190
    clone.submodule_remove("libs/lib").unwrap();
4191
    let snap = clone.snapshot("status").unwrap();
4192
    assert!(
4193
        snap.statuses
4194
            .iter()
4195
            .any(|s| s.path == "libs/lib" && s.status == ChangeStatus::Removed),
4196
        "{:?}",
4197
        snap.statuses
4198
    );
4199
    let c = clone.commit("drop lib", &[]).unwrap();
4200
    assert!(!clone
4201
        .load_state(&[c])
4202
        .unwrap()
4203
        .materialize()
4204
        .files
4205
        .contains_key("libs/lib"));
4206
    assert!(clone_dir.join("libs/lib/lib.txt").exists());
4207
    assert!(
4208
        !clone.snapshot("status").unwrap().changed,
4209
        "an unregistered nested repository is ignored"
4210
    );
4211
}
4212
4213
#[test]
4214
fn git_submodules_import_and_export_as_gitlinks() {
4215
    hermetic();
4216
    if std::process::Command::new("git")
4217
        .arg("--version")
4218
        .output()
4219
        .is_err()
4220
    {
4221
        eprintln!("git not installed; skipping");
4222
        return;
4223
    }
4224
    let dir = tempfile::tempdir().unwrap();
4225
    let root = dir.path();
4226
    let git_in = |d: &Path, args: &[&str]| -> String {
4227
        let out = std::process::Command::new("git")
4228
            .arg("-C")
4229
            .arg(d)
4230
            .args([
4231
                "-c",
4232
                "user.name=Grace",
4233
                "-c",
4234
                "[email protected]",
4235
                "-c",
4236
                "commit.gpgsign=false",
4237
                "-c",
4238
                "protocol.file.allow=always",
4239
            ])
4240
            .args(args)
4241
            .output()
4242
            .unwrap();
4243
        assert!(
4244
            out.status.success(),
4245
            "git {args:?}: {}",
4246
            String::from_utf8_lossy(&out.stderr)
4247
        );
4248
        String::from_utf8_lossy(&out.stdout).trim().to_string()
4249
    };
4250
    let sub = root.join("sub");
4251
    fs::create_dir_all(&sub).unwrap();
4252
    git_in(&sub, &["init", "-q", "-b", "main"]);
4253
    write(&sub, "s.txt", b"sub\n");
4254
    git_in(&sub, &["add", "."]);
4255
    git_in(&sub, &["commit", "-q", "-m", "sub initial"]);
4256
    let sub_sha = git_in(&sub, &["rev-parse", "HEAD"]);
4257
    let g = root.join("main.git");
4258
    fs::create_dir_all(&g).unwrap();
4259
    git_in(&g, &["init", "-q", "-b", "main"]);
4260
    write(&g, "README.md", b"# app\n");
4261
    git_in(&g, &["add", "."]);
4262
    git_in(&g, &["commit", "-q", "-m", "initial"]);
4263
    git_in(
4264
        &g,
4265
        &[
4266
            "submodule",
4267
            "add",
4268
            "-q",
4269
            sub.to_str().unwrap(),
4270
            "vendor/sub",
4271
        ],
4272
    );
4273
    git_in(&g, &["commit", "-q", "-m", "add submodule"]);
4274
4275
    let dest = root.join("oxy");
4276
    let repo = Repo::init(&dest).unwrap().with_home(root.join("home"));
4277
    let rep = repo.import_git(&g, "main").unwrap();
4278
    assert_eq!((rep.commits, rep.submodules), (2, 1));
4279
    let files = repo
4280
        .load_state(&repo.bookmark_heads().unwrap())
4281
        .unwrap()
4282
        .materialize()
4283
        .files;
4284
    assert_eq!(files["vendor/sub"].kind, NodeKind::Subrepo);
4285
    let FileContent::Opaque { blobs } = &files["vendor/sub"].content else {
4286
        panic!()
4287
    };
4288
    assert_eq!(
4289
        crate::subrepo::Pin::decode(&repo.read_blob(&blobs[0]).unwrap()).unwrap(),
4290
        crate::subrepo::Pin::Git {
4291
            sha: sub_sha.clone(),
4292
            branch: "HEAD".into()
4293
        }
4294
    );
4295
    let modules =
4296
        crate::subrepo::Modules::parse(&fs::read_to_string(dest.join(".oxymodules")).unwrap());
4297
    assert_eq!(modules.entries["vendor/sub"].url, sub.to_string_lossy());
4298
    assert!(modules.entries["vendor/sub"].git);
4299
    assert!(
4300
        files.contains_key(".gitmodules"),
4301
        "the Git file is kept for round trips"
4302
    );
4303
    assert!(
4304
        !dest.join("vendor/sub/.git").exists(),
4305
        "not cloned until update --init"
4306
    );
4307
    assert!(!repo.snapshot("status").unwrap().changed);
4308
    // update --init clones it at the pinned commit; status is unchanged.
4309
    assert_eq!(
4310
        repo.submodule_update(true, &[]).unwrap(),
4311
        vec![("vendor/sub".to_string(), SubrepoSync::Updated)]
4312
    );
4313
    assert_eq!(
4314
        git_in(&dest.join("vendor/sub"), &["rev-parse", "HEAD"]),
4315
        sub_sha
4316
    );
4317
    assert!(!repo.snapshot("status").unwrap().changed);
4318
    // Export writes the gitlink and .gitmodules back.
4319
    let mirror = root.join("mirror.git");
4320
    let rep = repo.git_export(&mirror).unwrap();
4321
    assert_eq!(rep.skipped_subrepos, 0);
4322
    let ls = git_in(&mirror, &["ls-tree", "main", "vendor/sub"]);
4323
    assert!(
4324
        ls.starts_with("160000 commit ") && ls.contains(&sub_sha),
4325
        "{ls}"
4326
    );
4327
    assert_eq!(
4328
        git_in(&mirror, &["ls-tree", "--name-only", "main"]),
4329
        ".gitmodules\nREADME.md\nvendor"
4330
    );
4331
    let orig_tree = git_in(&g, &["rev-parse", "main^{tree}"]);
4332
    assert_eq!(
4333
        git_in(&mirror, &["rev-parse", "main^{tree}"]),
4334
        orig_tree,
4335
        "tree round trip"
4336
    );
4337
}
4338
4339
#[test]
4340
fn partial_commits_by_path_and_by_hunk() {
4341
    hermetic();
4342
    let dir = tempfile::tempdir().unwrap();
4343
    let root = dir.path();
4344
    let repo = Repo::init(root).unwrap().with_home(root.join("home"));
4345
    write(root, "a.txt", b"1\n2\n3\n");
4346
    write(root, "b.txt", b"b\n");
4347
    let h0 = repo.commit("base", &[]).unwrap();
4348
    write(root, "a.txt", b"0\n1\n2\n3\n4\n");
4349
    write(root, "b.txt", b"b\nbb\n");
4350
    write(root, "c.txt", b"c\n");
4351
    // By path: only a.txt goes in; the rest stays on disk as uncommitted work.
4352
    let h1 = repo
4353
        .commit_selection("a only", &[], &Selection::Paths(vec!["a.txt".into()]))
4354
        .unwrap();
4355
    let c1 = repo.store().get_change(&h1).unwrap();
4356
    assert!(
4357
        c1.tree_ops.is_empty() && c1.edits.iter().all(|e| e.node() == c1.edits[0].node()),
4358
        "{:?}",
4359
        c1.tree_ops
4360
    );
4361
    assert_eq!(c1.deps, vec![h0]);
4362
    let files = repo.load_state(&[h1]).unwrap().materialize().files;
4363
    assert!(
4364
        matches!(&files["a.txt"].content, FileContent::Text { bytes, .. } if bytes == b"0\n1\n2\n3\n4\n")
4365
    );
4366
    assert!(matches!(&files["b.txt"].content, FileContent::Text { bytes, .. } if bytes == b"b\n"));
4367
    assert!(!files.contains_key("c.txt"));
4368
    let snap = repo.snapshot("status").unwrap();
4369
    assert_eq!(
4370
        snap.statuses
4371
            .iter()
4372
            .map(|s| (s.path.as_str(), s.status))
4373
            .collect::<Vec<_>>(),
4374
        vec![
4375
            ("b.txt", ChangeStatus::Modified),
4376
            ("c.txt", ChangeStatus::Added)
4377
        ]
4378
    );
4379
    assert_eq!(
4380
        fs::read(root.join("b.txt")).unwrap(),
4381
        b"b\nbb\n",
4382
        "disk untouched"
4383
    );
4384
    // By hunk: pick the b.txt insert; c.txt's addition is left.
4385
    let (_, hunks) = repo.hunks().unwrap();
4386
    let b_hunk = hunks
4387
        .iter()
4388
        .find(|h| h.path == "b.txt" && h.text.contains("+bb"))
4389
        .unwrap()
4390
        .index;
4391
    let h2 = repo
4392
        .commit_selection("b only", &[], &Selection::Hunks(vec![b_hunk]))
4393
        .unwrap();
4394
    let files = repo.load_state(&[h2]).unwrap().materialize().files;
4395
    assert!(
4396
        matches!(&files["b.txt"].content, FileContent::Text { bytes, .. } if bytes == b"b\nbb\n")
4397
    );
4398
    assert!(!files.contains_key("c.txt"));
4399
    let snap = repo.snapshot("status").unwrap();
4400
    assert_eq!(
4401
        snap.statuses
4402
            .iter()
4403
            .map(|s| s.path.as_str())
4404
            .collect::<Vec<_>>(),
4405
        vec!["c.txt"]
4406
    );
4407
    // Choosing only the content hunk of a file in a new directory pulls in
4408
    // the directory and file additions it needs.
4409
    write(root, "d/e.txt", b"e\n");
4410
    let (_, hunks) = repo.hunks().unwrap();
4411
    let e_insert = hunks
4412
        .iter()
4413
        .find(|h| h.path == "d/e.txt" && h.text.contains("+e"))
4414
        .unwrap()
4415
        .index;
4416
    let h3 = repo
4417
        .commit_selection("e only", &[], &Selection::Hunks(vec![e_insert]))
4418
        .unwrap();
4419
    let c3 = repo.store().get_change(&h3).unwrap();
4420
    assert_eq!(c3.tree_ops.len(), 2, "{:?}", c3.tree_ops);
4421
    let files = repo.load_state(&[h3]).unwrap().materialize().files;
4422
    assert!(files.contains_key("d/e.txt") && !files.contains_key("c.txt"));
4423
    // Choosing a new file's addition hunk brings its content along.
4424
    write(root, "f/g.txt", b"g\n");
4425
    let (_, hunks) = repo.hunks().unwrap();
4426
    let g_add = hunks
4427
        .iter()
4428
        .find(|h| h.path == "f/g.txt" && h.text.starts_with("A "))
4429
        .unwrap()
4430
        .index;
4431
    let h4 = repo
4432
        .commit_selection("g by addition", &[], &Selection::Hunks(vec![g_add]))
4433
        .unwrap();
4434
    let files = repo.load_state(&[h4]).unwrap().materialize().files;
4435
    assert!(
4436
        matches!(&files["f/g.txt"].content, FileContent::Text { bytes, .. } if bytes == b"g\n")
4437
    );
4438
    assert!(!repo
4439
        .snapshot("status")
4440
        .unwrap()
4441
        .statuses
4442
        .iter()
4443
        .any(|s| s.path == "f/g.txt"));
4444
    // Everything left commits normally; the working copy is then clean.
4445
    repo.commit("the rest", &[]).unwrap();
4446
    assert!(!repo.snapshot("status").unwrap().changed);
4447
    let files = repo
4448
        .load_state(&repo.bookmark_heads().unwrap())
4449
        .unwrap()
4450
        .materialize()
4451
        .files;
4452
    assert!(files.contains_key("c.txt"));
4453
}
4454
4455
#[test]
4456
fn blame_attributes_lines_to_introducing_changes_across_renames() {
4457
    hermetic();
4458
    let dir = tempfile::tempdir().unwrap();
4459
    let root = dir.path();
4460
    let mut repo = Repo::init(root).unwrap().with_home(root.join("home"));
4461
    repo.create_identity("Ada", "[email protected]", IdentityScope::User)
4462
        .unwrap();
4463
    write(root, "a.txt", b"one\n");
4464
    let h1 = repo.commit("first", &[]).unwrap();
4465
    write(root, "a.txt", b"one\ntwo\n");
4466
    let h2 = repo.commit("second", &[]).unwrap();
4467
    let b = repo.blame("a.txt").unwrap();
4468
    assert_eq!(
4469
        b.iter()
4470
            .map(|l| (l.line, l.hash, l.text.as_slice()))
4471
            .collect::<Vec<_>>(),
4472
        vec![(1, h1, b"one\n".as_slice()), (2, h2, b"two\n".as_slice())]
4473
    );
4474
    assert!(b.iter().all(|l| l.author == "Ada"));
4475
    assert_eq!(
4476
        b[0].change_id,
4477
        repo.store().get_change(&h1).unwrap().change_id
4478
    );
4479
    fs::rename(root.join("a.txt"), root.join("b.txt")).unwrap();
4480
    repo.commit("rename", &[]).unwrap();
4481
    let b = repo.blame("b.txt").unwrap();
4482
    assert_eq!(
4483
        b.iter().map(|l| l.hash).collect::<Vec<_>>(),
4484
        vec![h1, h2],
4485
        "the node survives the rename"
4486
    );
4487
    assert!(repo.blame("a.txt").is_err());
4488
}
4489
4490
#[test]
4491
fn bisect_finds_the_first_bad_change() {
4492
    hermetic();
4493
    let dir = tempfile::tempdir().unwrap();
4494
    let root = dir.path();
4495
    let repo = Repo::init(root).unwrap().with_home(root.join("home"));
4496
    let mut content = String::new();
4497
    let mut hashes = Vec::new();
4498
    for i in 1..=8 {
4499
        content.push_str(&format!("line {i}{}\n", if i == 5 { " bug" } else { "" }));
4500
        write(root, "f.txt", content.as_bytes());
4501
        hashes.push(repo.commit(&format!("step {i}"), &[]).unwrap());
4502
    }
4503
    // Each step appends after the previous line, so the chain is linear.
4504
    assert_eq!(repo.bookmark_heads().unwrap(), vec![hashes[7]]);
4505
    repo.bisect_start().unwrap();
4506
    assert!(matches!(
4507
        repo.bisect_mark(Some(true), &[hashes[0]]).unwrap(),
4508
        BisectStep::NeedMarks { good: 1, bad: 0 }
4509
    ));
4510
    let step = repo.bisect_mark(Some(false), &[hashes[7]]).unwrap();
4511
    assert!(
4512
        matches!(step, BisectStep::Testing { remaining: 7, .. }),
4513
        "{step:?}"
4514
    );
4515
    // Automated: bad when the bug line is present.
4516
    let step = repo
4517
        .bisect_run(&["sh".into(), "-c".into(), "! grep -q bug f.txt".into()])
4518
        .unwrap();
4519
    assert_eq!(step, BisectStep::Found { culprit: hashes[4] });
4520
    assert_eq!(
4521
        repo.bisect_status().unwrap(),
4522
        Some(BisectStep::Found { culprit: hashes[4] })
4523
    );
4524
    repo.bisect_reset().unwrap();
4525
    assert_eq!(fs::read_to_string(root.join("f.txt")).unwrap(), content);
4526
    assert!(repo.bisect_status().unwrap().is_none());
4527
    assert!(!repo.snapshot("status").unwrap().changed);
4528
    // Manual marks and a skip.
4529
    repo.bisect_start().unwrap();
4530
    repo.bisect_mark(Some(true), &[hashes[0]]).unwrap();
4531
    let mut step = repo.bisect_mark(Some(false), &[hashes[7]]).unwrap();
4532
    let mut skipped_once = false;
4533
    let mut guard = 0;
4534
    while let BisectStep::Testing { .. } = step {
4535
        guard += 1;
4536
        assert!(guard < 20);
4537
        let text = fs::read_to_string(root.join("f.txt")).unwrap();
4538
        if !skipped_once && text.contains("line 6") {
4539
            // An untestable state away from the boundary: the search routes around it.
4540
            skipped_once = true;
4541
            step = repo.bisect_mark(None, &[]).unwrap();
4542
            continue;
4543
        }
4544
        step = repo.bisect_mark(Some(!text.contains("bug")), &[]).unwrap();
4545
    }
4546
    assert!(skipped_once);
4547
    assert_eq!(step, BisectStep::Found { culprit: hashes[4] });
4548
    repo.bisect_reset().unwrap();
4549
    // Skipping the culprit itself leaves it among the candidates reported.
4550
    repo.bisect_start().unwrap();
4551
    repo.bisect_mark(Some(true), &[hashes[0]]).unwrap();
4552
    let mut step = repo.bisect_mark(Some(false), &[hashes[7]]).unwrap();
4553
    let mut guard = 0;
4554
    while let BisectStep::Testing { heads, .. } = &step {
4555
        guard += 1;
4556
        assert!(guard < 20);
4557
        let text = fs::read_to_string(root.join("f.txt")).unwrap();
4558
        let is_culprit_state =
4559
            heads.contains(&hashes[4]) && !heads.iter().any(|h| hashes[5..].contains(h));
4560
        step = if is_culprit_state {
4561
            repo.bisect_mark(None, &[]).unwrap()
4562
        } else {
4563
            repo.bisect_mark(Some(!text.contains("bug")), &[]).unwrap()
4564
        };
4565
    }
4566
    match step {
4567
        BisectStep::Inconclusive { candidates } => assert!(
4568
            candidates.contains(&hashes[4]) && candidates.len() <= 2,
4569
            "{candidates:?}"
4570
        ),
4571
        other => panic!("{other:?}"),
4572
    }
4573
    repo.bisect_reset().unwrap();
4574
}
4575
4576
#[test]
4577
fn squash_folds_a_change_into_its_dependency() {
4578
    hermetic();
4579
    let dir = tempfile::tempdir().unwrap();
4580
    let root = dir.path();
4581
    let repo = Repo::init(root).unwrap().with_home(root.join("home"));
4582
    write(root, "a.txt", b"1\n");
4583
    let a = repo.commit("A", &[]).unwrap();
4584
    write(root, "a.txt", b"1\n2\n");
4585
    let c = repo.commit("C", &[]).unwrap();
4586
    write(root, "a.txt", b"1\n2\n3\n");
4587
    let e = repo.commit("E", &[]).unwrap();
4588
    write(root, "b.txt", b"b\n");
4589
    let b = repo.commit("B", &[]).unwrap();
4590
    let id_a = repo.store().get_change(&a).unwrap().change_id;
4591
    let id_e = repo.store().get_change(&e).unwrap().change_id;
4592
    // E depends on C which A lacks: refused, naming it.
4593
    let err = repo.squash(&e, &a).unwrap_err().to_string();
4594
    assert!(err.contains(&c.short(12)), "{err}");
4595
    // C into A: A' has both, C is gone, E follows and still reads the same.
4596
    let a2 = repo.squash(&c, &a).unwrap();
4597
    let a2c = repo.store().get_change(&a2).unwrap();
4598
    assert_eq!(a2c.change_id, id_a);
4599
    assert!(a2c.deps.is_empty());
4600
    let heads = repo.bookmark_heads().unwrap();
4601
    let st = repo.load_state(&heads).unwrap();
4602
    assert!(!st.contains(&c) && !st.contains(&a) && !st.contains(&e));
4603
    let e2 = st
4604
        .changes()
4605
        .find(|(_, m)| m.change_id == id_e)
4606
        .map(|(h, _)| *h)
4607
        .unwrap();
4608
    assert_eq!(
4609
        repo.store().get_change(&e2).unwrap().deps,
4610
        vec![a2],
4611
        "E now depends on A' alone"
4612
    );
4613
    let files = st.materialize().files;
4614
    assert!(
4615
        matches!(&files["a.txt"].content, FileContent::Text { bytes, .. } if bytes == b"1\n2\n3\n")
4616
    );
4617
    assert!(files.contains_key("b.txt"));
4618
    assert!(st.contains(&b));
4619
    assert!(!repo.snapshot("status").unwrap().changed);
4620
    assert_eq!(repo.log().unwrap().len(), 4, "working copy, B, E', A'");
4621
    // Undo restores the three original changes.
4622
    repo.undo().unwrap();
4623
    repo.undo().unwrap();
4624
    let st = repo.load_state(&repo.bookmark_heads().unwrap()).unwrap();
4625
    assert!(st.contains(&c) && st.contains(&a) && st.contains(&e));
4626
}
4627
4628
#[test]
4629
fn rebase_re_expresses_a_change_against_another_base() {
4630
    hermetic();
4631
    let dir = tempfile::tempdir().unwrap();
4632
    let root = dir.path();
4633
    let repo = Repo::init(root).unwrap().with_home(root.join("home"));
4634
    write(root, "a.txt", b"1\n2\n");
4635
    let a = repo.commit("A", &[]).unwrap();
4636
    write(root, "a.txt", b"1\n2\n3\n");
4637
    let c = repo.commit("C: append 3", &[]).unwrap();
4638
    write(root, "a.txt", b"1\n2\n3\n4\n");
4639
    let e = repo.commit("E: append 4", &[]).unwrap();
4640
    // A different base: A plus a change that prepends a line.
4641
    repo.checkout(&[a], true, "checkout").unwrap();
4642
    write(root, "a.txt", b"0\n1\n2\n");
4643
    let d = repo.commit("D: prepend 0", &[]).unwrap();
4644
    let id_c = repo.store().get_change(&c).unwrap().change_id;
4645
    let id_e = repo.store().get_change(&e).unwrap().change_id;
4646
    // Rebase C onto D: its effect (append 3) re-derived against D's text.
4647
    let c2 = repo.rebase(&c, &[d]).unwrap();
4648
    let c2c = repo.store().get_change(&c2).unwrap();
4649
    assert_eq!(c2c.change_id, id_c);
4650
    assert!(c2c.deps.contains(&d), "{:?}", c2c.deps);
4651
    let heads = repo.bookmark_heads().unwrap();
4652
    let st = repo.load_state(&heads).unwrap();
4653
    assert!(!st.contains(&c) && st.contains(&d));
4654
    let e2 = st
4655
        .changes()
4656
        .find(|(_, m)| m.change_id == id_e)
4657
        .map(|(h, _)| *h)
4658
        .unwrap();
4659
    let e2deps = repo.store().get_change(&e2).unwrap().deps;
4660
    assert!(
4661
        e2deps.contains(&c2) && !e2deps.contains(&c) && e2deps.contains(&a),
4662
        "E follows C by content and still depends on A, which introduced the file: {e2deps:?}"
4663
    );
4664
    let files = st.materialize().files;
4665
    assert!(
4666
        matches!(&files["a.txt"].content, FileContent::Text { bytes, .. } if bytes == b"0\n1\n2\n3\n4\n"),
4667
        "{:?}",
4668
        files["a.txt"].content
4669
    );
4670
    assert!(!files["a.txt"].is_conflicted());
4671
    // Rebasing onto a state that already contains the change is refused.
4672
    assert!(repo.rebase(&c2, &[c2]).is_err());
4673
    let err = repo.rebase(&e2, &[d]).unwrap_err().to_string();
4674
    assert!(
4675
        err.contains("lacks dependencies"),
4676
        "E needs C, which D's state does not have: {err}"
4677
    );
4678
}
4679
4680
#[test]
4681
fn unsigned_tags_keep_their_message() {
4682
    hermetic();
4683
    let dir = tempfile::tempdir().unwrap();
4684
    let root = dir.path();
4685
    let repo = Repo::init(root).unwrap().with_home(root.join("home"));
4686
    write(root, "a.txt", b"a\n");
4687
    repo.commit("a", &[]).unwrap();
4688
    assert!(repo.secret_key().unwrap().is_none());
4689
    repo.tag_create("v1", &repo.bookmark_heads().unwrap(), "first release")
4690
        .unwrap();
4691
    let tags = repo.tags().unwrap();
4692
    assert_eq!(
4693
        (
4694
            tags[0].name.as_str(),
4695
            tags[0].message.as_str(),
4696
            tags[0].signer.as_deref()
4697
        ),
4698
        ("v1", "first release", None)
4699
    );
4700
    assert!(
4701
        repo.tag_refs().unwrap()[0].attestation.is_none(),
4702
        "an unsigned attestation is not advertised"
4703
    );
4704
}
4705
4706
#[test]
4707
fn fsck_passes_a_sound_repository_and_names_each_fault() {
4708
    // Files on disk are what this tests: tampering with them, and the
4709
    // directory store's crash points.
4710
    if std::env::var_os("OXY_STORE_BACKEND").is_some() {
4711
        return;
4712
    }
4713
    hermetic();
4714
    let dir = tempfile::tempdir().unwrap();
4715
    let root = dir.path();
4716
    let origin_path = root.join("origin");
4717
    let origin = Repo::init(&origin_path).unwrap();
4718
    let mut a = Repo::clone(&origin_path.to_string_lossy(), &root.join("a"))
4719
        .unwrap()
4720
        .with_home(root.join("home-a"));
4721
    a.create_identity("Ada", "[email protected]", IdentityScope::Repo)
4722
        .unwrap();
4723
    write(&root.join("a"), "f.txt", b"one\n");
4724
    write(&root.join("a"), "bin.dat", b"\0\x01\x02binary");
4725
    let h1 = a.commit("first", &[]).unwrap();
4726
    write(&root.join("a"), "f.txt", b"one\ntwo\n");
4727
    let h2 = a.commit("second", &[]).unwrap();
4728
    a.tag_create("v1", &[h2], "first release").unwrap();
4729
    a.checkpoint().unwrap();
4730
    assert!(a.push("origin", false).unwrap()[0].ok);
4731
    origin.refresh().unwrap();
4732
4733
    // Sound: signed changes, a seal, a tag, a checkpoint, a ref attestation.
4734
    for repo in [&a, &origin] {
4735
        let rep = repo.fsck().unwrap();
4736
        assert_eq!(rep.problems, vec![], "{rep:?}");
4737
        // The two commits, plus the working copy's change in `a`.
4738
        assert!(rep.changes >= 2 && rep.signed >= 2, "{rep:?}");
4739
        assert!(rep.ops > 1 && rep.objects > 5);
4740
    }
4741
    assert!(origin.fsck().unwrap().attestations >= 1);
4742
4743
    // A flipped byte in a stored object is corruption, named by hash.
4744
    let c1 = a.store().path_for(&h1);
4745
    let pristine = fs::read(&c1).unwrap();
4746
    let mut bytes = pristine.clone();
4747
    *bytes.last_mut().unwrap() ^= 1;
4748
    fs::write(&c1, &bytes).unwrap();
4749
    let rep = a.fsck().unwrap();
4750
    assert!(rep.errors() >= 1);
4751
    assert!(
4752
        rep.problems
4753
            .iter()
4754
            .any(|p| p.object == Some(h1) && p.what.contains("unreadable")),
4755
        "{rep:?}"
4756
    );
4757
    fs::write(&c1, &pristine).unwrap();
4758
    assert_eq!(a.fsck().unwrap().errors(), 0);
4759
4760
    // A missing change is named with what needed it.
4761
    fs::remove_file(&c1).unwrap();
4762
    let rep = a.fsck().unwrap();
4763
    assert!(
4764
        rep.problems.iter().any(|p| p.severity == Severity::Error
4765
            && p.object == Some(h1)
4766
            && p.what.contains("change missing, needed by change")),
4767
        "{rep:?}"
4768
    );
4769
    fs::write(&c1, &pristine).unwrap();
4770
4771
    // A missing blob is an error in a full clone.
4772
    let c2 = a.store().get_change(&h1).unwrap();
4773
    let blob = c2
4774
        .edits
4775
        .iter()
4776
        .find_map(|e| match e {
4777
            Edit::Replace { new: Some(b), .. } => Some(*b),
4778
            _ => None,
4779
        })
4780
        .expect("the binary file is a blob");
4781
    let bp = a.store().path_for(&blob);
4782
    let blob_bytes = fs::read(&bp).unwrap();
4783
    fs::remove_file(&bp).unwrap();
4784
    let rep = a.fsck().unwrap();
4785
    assert!(
4786
        rep.problems
4787
            .iter()
4788
            .any(|p| p.object == Some(blob) && p.what.contains("blob missing")),
4789
        "{rep:?}"
4790
    );
4791
    fs::write(&bp, &blob_bytes).unwrap();
4792
4793
    // A broken op log head is reported, not a crash.
4794
    let head = root.join("a/.oxy/ops/head");
4795
    let saved = fs::read(&head).unwrap();
4796
    fs::write(&head, b"not a hash").unwrap();
4797
    let rep = a.fsck().unwrap();
4798
    assert!(
4799
        rep.problems.iter().any(|p| p.what.contains("ops/head")),
4800
        "{rep:?}"
4801
    );
4802
    fs::write(&head, saved).unwrap();
4803
    assert_eq!(a.fsck().unwrap().problems, vec![]);
4804
}
4805
4806
/// Copy a directory tree (for restoring a pristine repository).
4807
fn copy_tree(from: &Path, to: &Path) {
4808
    fs::create_dir_all(to).unwrap();
4809
    for e in fs::read_dir(from).unwrap() {
4810
        let e = e.unwrap();
4811
        let target = to.join(e.file_name());
4812
        if e.file_type().unwrap().is_dir() {
4813
            copy_tree(&e.path(), &target);
4814
        } else {
4815
            fs::copy(e.path(), &target).unwrap();
4816
        }
4817
    }
4818
}
4819
4820
/// Spec §13.6: stop `commit` and `push` at every durable step, as a crash
4821
/// would, and check that both repositories still open, pass `fsck`, and
4822
/// accept the same operation again.
4823
#[test]
4824
fn crash_at_every_step_of_commit_and_push_leaves_sound_repositories() {
4825
    // Files on disk are what this tests: tampering with them, and the
4826
    // directory store's crash points.
4827
    if std::env::var_os("OXY_STORE_BACKEND").is_some() {
4828
        return;
4829
    }
4830
    use crate::durable::failpoint;
4831
    hermetic();
4832
    let dir = tempfile::tempdir().unwrap();
4833
    let pristine = dir.path().join("pristine");
4834
    let origin_path = pristine.join("origin");
4835
    Repo::init(&origin_path).unwrap();
4836
    let mut a = Repo::clone(&origin_path.to_string_lossy(), &pristine.join("a"))
4837
        .unwrap()
4838
        .with_home(dir.path().join("home"));
4839
    a.create_identity("Ada", "[email protected]", IdentityScope::Repo)
4840
        .unwrap();
4841
    write(&pristine.join("a"), "f.txt", b"one\n");
4842
    a.commit("first", &[]).unwrap();
4843
    assert!(a.push("origin", false).unwrap()[0].ok);
4844
    drop(a);
4845
4846
    type Op = fn(&Repo) -> Result<()>;
4847
    let edit_and_commit: Op = |r| {
4848
        write(r.root(), "f.txt", b"one\ntwo\n");
4849
        write(r.root(), "big.bin", &vec![7u8; 300_000]);
4850
        r.commit("second", &[]).map(|_| ())
4851
    };
4852
    let push: Op = |r| {
4853
        let res = r.push("origin", false)?;
4854
        if res.iter().all(|x| x.ok) {
4855
            Ok(())
4856
        } else {
4857
            Err(RepoError::Msg(format!("{res:?}")))
4858
        }
4859
    };
4860
4861
    for (name, prepare, op) in [
4862
        ("commit", None, edit_and_commit),
4863
        ("push", Some(edit_and_commit), push),
4864
    ] {
4865
        let mut steps = 0;
4866
        for n in 1.. {
4867
            let run = dir.path().join(format!("{name}-{n}"));
4868
            copy_tree(&pristine, &run);
4869
            // Clones record their remote by path; point it at this copy.
4870
            let open = |p: &Path| {
4871
                let mut r = Repo::open(p).unwrap().with_home(dir.path().join("home"));
4872
                r.config
4873
                    .set("remote.origin.url", &run.join("origin").to_string_lossy())
4874
                    .unwrap();
4875
                r.save_config().unwrap();
4876
                r
4877
            };
4878
            let a = open(&run.join("a"));
4879
            if let Some(prep) = prepare {
4880
                prep(&a).unwrap();
4881
            }
4882
            failpoint::crash_after(n);
4883
            let outcome = op(&a);
4884
            let crashed = failpoint::disarm();
4885
            drop(a);
4886
            if !crashed {
4887
                outcome.unwrap_or_else(|e| panic!("{name} failed without a crash: {e}"));
4888
                steps = n - 1;
4889
                break;
4890
            }
4891
            assert!(
4892
                outcome.is_err(),
4893
                "{name}: a crash at step {n} was swallowed"
4894
            );
4895
            for repo in ["a", "origin"] {
4896
                let r = Repo::open(&run.join(repo)).unwrap_or_else(|e| {
4897
                    panic!("{name} crash at step {n}: {repo} no longer opens: {e}")
4898
                });
4899
                let rep = r.fsck().unwrap();
4900
                assert_eq!(
4901
                    rep.errors(),
4902
                    0,
4903
                    "{name} crash at step {n}: {repo} fails fsck: {:?}",
4904
                    rep.problems
4905
                );
4906
            }
4907
            // The interrupted operation can simply be run again.
4908
            let a = open(&run.join("a"));
4909
            // A crash after the commit point leaves the commit done.
4910
            let landed = a
4911
                .bookmark_heads()
4912
                .unwrap()
4913
                .iter()
4914
                .any(|h| a.store().get_change(h).unwrap().message == "second");
4915
            let again = match (name, landed) {
4916
                ("commit", true) => Ok(()),
4917
                ("commit", false) => a.commit("second", &[]).map(|_| ()),
4918
                _ => op(&a),
4919
            };
4920
            again.unwrap_or_else(|e| panic!("{name} crash at step {n}: retry failed: {e}"));
4921
            assert_eq!(a.fsck().unwrap().errors(), 0);
4922
            fs::remove_dir_all(&run).unwrap();
4923
        }
4924
        assert!(steps >= 3, "{name} has only {steps} durable steps?");
4925
    }
4926
}
4927
4928
/// Spec §12.1: commands in two workspaces of one repository, and pushes,
4929
/// running at the same time lose nothing: every commit ends up on the
4930
/// bookmark, locally and on the remote, and the repository passes fsck.
4931
#[test]
4932
fn concurrent_commits_in_two_workspaces_lose_nothing() {
4933
    hermetic();
4934
    let dir = tempfile::tempdir().unwrap();
4935
    let root = dir.path();
4936
    let origin = root.join("origin");
4937
    Repo::init_bare_unbound(&origin).unwrap();
4938
    let main = root.join("main");
4939
    let mut repo = Repo::init(&main).unwrap();
4940
    repo.config
4941
        .set("remote.origin.url", &origin.to_string_lossy())
4942
        .unwrap();
4943
    repo.save_config().unwrap();
4944
    write(&main, "seed.txt", b"seed\n");
4945
    repo.commit("seed", &[]).unwrap();
4946
    let second = root.join("second");
4947
    repo.workspace_add(&second, None).unwrap();
4948
    drop(repo);
4949
4950
    const EACH: usize = 15;
4951
    std::thread::scope(|s| {
4952
        for (tag, dir, push) in [("a", main.clone(), true), ("b", second.clone(), false)] {
4953
            s.spawn(move || {
4954
                let r = Repo::open(&dir).unwrap();
4955
                for i in 0..EACH {
4956
                    write(
4957
                        &dir,
4958
                        &format!("{tag}-{i}.txt"),
4959
                        format!("{tag} {i}\n").as_bytes(),
4960
                    );
4961
                    r.commit(&format!("{tag} {i}"), &[]).unwrap();
4962
                    if push && i % 5 == 4 {
4963
                        // A push may be refused while the other workspace moves the bookmark; nothing may be lost either way.
4964
                        let _ = r.push("origin", false);
4965
                    }
4966
                }
4967
            });
4968
        }
4969
    });
4970
4971
    let repo = Repo::open(&main).unwrap();
4972
    let heads = repo.bookmark_heads().unwrap();
4973
    let state = repo.load_state(&heads).unwrap();
4974
    let messages: BTreeSet<String> = state.changes().map(|(_, m)| m.message.clone()).collect();
4975
    for tag in ["a", "b"] {
4976
        for i in 0..EACH {
4977
            assert!(
4978
                messages.contains(&format!("{tag} {i}")),
4979
                "lost commit {tag} {i}; have {messages:?}"
4980
            );
4981
        }
4982
    }
4983
    let rep = repo.fsck().unwrap();
4984
    assert_eq!(rep.errors(), 0, "{:?}", rep.problems);
4985
    assert!(repo.push("origin", false).unwrap().iter().all(|r| r.ok));
4986
    let hosted = Repo::open(&origin).unwrap();
4987
    let hosted_heads = hosted.bookmark_heads().unwrap();
4988
    assert_eq!(
4989
        hosted.load_state(&hosted_heads).unwrap().len(),
4990
        state.len(),
4991
        "the remote has every commit"
4992
    );
4993
}
4994
4995
/// Two operations recorded from the same parent (what two processes do
4996
/// when they race) are merged: both bookmarks' heads survive, and a
4997
/// change made on one side only is kept.
4998
#[test]
4999
fn operations_from_the_same_parent_are_merged() {
5000
    hermetic();
5001
    let dir = tempfile::tempdir().unwrap();
5002
    let root = dir.path();
5003
    let repo = Repo::init(root).unwrap();
5004
    write(root, "a.txt", b"a\n");
5005
    let a = repo.commit("a", &[]).unwrap();
5006
    write(root, "b.txt", b"b\n");
5007
    let b = repo.commit("b", &[]).unwrap();
5008
    let (x, op) = repo.head_op().unwrap();
5009
    let state = |heads: Vec<ChangeHash>| repo.store().put_state(&StateObject::new(heads)).unwrap();
5010
5011
    // Side one moves main to just `a` and adds a bookmark; side two moves main to just `b`.
5012
    let mut one = op.view.clone();
5013
    one.bookmarks.insert("main".into(), state(vec![a]));
5014
    one.bookmarks.insert("topic".into(), state(vec![a]));
5015
    let mut two = op.view.clone();
5016
    two.bookmarks.insert("main".into(), state(vec![b]));
5017
    repo.record_op(&[x], "one", one).unwrap();
5018
    let merged = repo.record_op(&[x], "two", two).unwrap();
5019
5020
    let (head, op) = repo.head_op().unwrap();
5021
    assert_eq!(head, merged);
5022
    assert_eq!(op.parents.len(), 2, "a merge of the two operations");
5023
    assert!(op.command.contains("merged with a concurrent operation"));
5024
    let mut main = repo
5025
        .store()
5026
        .get_state(&op.view.bookmarks["main"])
5027
        .unwrap()
5028
        .heads;
5029
    main.sort();
5030
    let mut want = vec![a, b];
5031
    want.sort();
5032
    assert_eq!(main, want, "both sides' heads are kept");
5033
    assert!(
5034
        op.view.bookmarks.contains_key("topic"),
5035
        "a one-sided change survives"
5036
    );
5037
    assert_eq!(repo.fsck().unwrap().errors(), 0);
5038
}
5039
5040
#[test]
5041
fn failed_requests_come_with_a_next_step() {
5042
    use crate::protocol::hint_for;
5043
    assert!(hint_for("https://h/x/oxy/v1/push: HTTP 401: bad token")
5044
        .unwrap()
5045
        .contains("token"));
5046
    assert!(hint_for("…: HTTP 403: forbidden")
5047
        .unwrap()
5048
        .contains("repo:write"));
5049
    assert!(hint_for("…: HTTP 404: no such repository")
5050
        .unwrap()
5051
        .contains("owner and repository name"));
5052
    assert!(hint_for("invalid peer certificate: UnknownIssuer")
5053
        .unwrap()
5054
        .contains("oxyhub-ca.pem"));
5055
    assert!(hint_for("Connect error: Connection refused (os error 111)")
5056
        .unwrap()
5057
        .contains("running"));
5058
    assert!(hint_for("Dns Failed: failed to lookup address information")
5059
        .unwrap()
5060
        .contains("resolve"));
5061
    assert_eq!(hint_for("something else entirely"), None);
5062
}
5063
5064
#[test]
5065
fn doctor_names_problems_and_what_to_do() {
5066
    hermetic();
5067
    let dir = tempfile::tempdir().unwrap();
5068
    let root = dir.path();
5069
    let origin = root.join("origin");
5070
    Repo::init_bare_unbound(&origin).unwrap();
5071
    let mut repo = Repo::init(&root.join("r"))
5072
        .unwrap()
5073
        .with_home(root.join("home"));
5074
    let find = |r: &DoctorReport, area: &str, h: Health| {
5075
        r.checks
5076
            .iter()
5077
            .find(|c| c.area == area && c.health == h)
5078
            .cloned()
5079
    };
5080
5081
    let r = repo.doctor(true);
5082
    assert!(find(&r, "identity", Health::Warn)
5083
        .unwrap()
5084
        .hint
5085
        .unwrap()
5086
        .contains("oxy identity create"));
5087
    assert!(find(&r, "repository", Health::Ok).is_some());
5088
5089
    repo.create_identity("Ada", "[email protected]", IdentityScope::Repo)
5090
        .unwrap();
5091
    repo.config.set("author.name", "Ada").unwrap();
5092
    repo.config.set("author.email", "[email protected]").unwrap();
5093
    repo.config
5094
        .set("remote.origin.url", &origin.to_string_lossy())
5095
        .unwrap();
5096
    repo.config
5097
        .set("remote.down.url", "http://127.0.0.1:9/a/b")
5098
        .unwrap();
5099
    repo.config.set("remote.down.token", "t").unwrap();
5100
    repo.config
5101
        .set("remote.badca.url", "https://example.invalid/a/b")
5102
        .unwrap();
5103
    repo.config
5104
        .set(
5105
            "remote.badca.ca",
5106
            &root.join("missing.pem").to_string_lossy(),
5107
        )
5108
        .unwrap();
5109
    repo.save_config().unwrap();
5110
5111
    let r = repo.doctor(true);
5112
    assert!(find(&r, "identity", Health::Ok).is_some(), "{r:?}");
5113
    assert!(find(&r, "author", Health::Ok).is_some(), "{r:?}");
5114
    assert!(find(&r, "remote origin", Health::Ok)
5115
        .unwrap()
5116
        .message
5117
        .contains("first push binds it"));
5118
    let down = find(&r, "remote down", Health::Fail).unwrap();
5119
    assert!(
5120
        down.hint.as_deref().unwrap_or("").contains("running"),
5121
        "{down:?}"
5122
    );
5123
    let badca = find(&r, "remote badca", Health::Fail).unwrap();
5124
    assert!(
5125
        badca.hint.unwrap().contains("remote.badca.ca"),
5126
        "the remote's own name is in the hint"
5127
    );
5128
    assert_eq!(r.worst(), Health::Fail);
5129
5130
    // Offline, nothing is contacted.
5131
    let r = repo.doctor(false);
5132
    assert!(find(&r, "remote down", Health::Fail).is_none());
5133
    assert!(find(&r, "remote down", Health::Ok)
5134
        .unwrap()
5135
        .message
5136
        .contains("not contacted"));
5137
}
5138
5139
/// Spec §8.1: deleting a line depends on whoever inserted the lines right
5140
/// after it. Inserting after `b` and then deleting `b`, one commit after
5141
/// the other, must not leave a delete/insert conflict.
5142
#[test]
5143
fn deleting_a_line_after_an_insertion_below_it_is_not_a_conflict() {
5144
    hermetic();
5145
    let dir = tempfile::tempdir().unwrap();
5146
    let root = dir.path();
5147
    let repo = Repo::init(root).unwrap();
5148
    write(root, "f", b"a\nb\nc\n");
5149
    repo.commit("base", &[]).unwrap();
5150
    write(root, "f", b"a\nb\nx\nc\n");
5151
    let insert = repo.commit("insert x after b", &[]).unwrap();
5152
    write(root, "f", b"a\nx\nc\n");
5153
    let delete = repo.commit("delete b", &[]).unwrap();
5154
    assert!(
5155
        repo.store()
5156
            .get_change(&delete)
5157
            .unwrap()
5158
            .deps
5159
            .contains(&insert),
5160
        "the deletion depends on the insertion below the deleted line"
5161
    );
5162
    let heads = repo.bookmark_heads().unwrap();
5163
    assert_eq!(heads, vec![delete]);
5164
    let snap = repo.load_state(&heads).unwrap().materialize();
5165
    assert!(!snap.is_conflicted());
5166
    assert!(
5167
        matches!(&snap.files["f"].content, FileContent::Text { bytes, .. } if bytes == b"a\nx\nc\n")
5168
    );
5169
}
5170
5171
/// Spec §9.3: a binary file reverted to an earlier blob keeps it, and each
5172
/// replacement depends on the change that set the blob it replaces.
5173
#[test]
5174
fn a_binary_file_reverted_to_an_earlier_blob_keeps_it() {
5175
    hermetic();
5176
    let dir = tempfile::tempdir().unwrap();
5177
    let root = dir.path();
5178
    let repo = Repo::init(root).unwrap();
5179
    write(root, "bin", b"\0A");
5180
    let v1 = repo.commit("v1", &[]).unwrap();
5181
    write(root, "bin", b"\0B");
5182
    let v2 = repo.commit("v2", &[]).unwrap();
5183
    assert!(repo.store().get_change(&v2).unwrap().deps.contains(&v1));
5184
    write(root, "bin", b"\0A");
5185
    let v3 = repo.commit("back to A", &[]).unwrap();
5186
    assert!(repo.store().get_change(&v3).unwrap().deps.contains(&v2));
5187
    assert_eq!(repo.bookmark_heads().unwrap(), vec![v3]);
5188
    let state = repo.load_state(&[v3]).unwrap();
5189
    let snap = state.materialize();
5190
    let FileContent::Opaque { blobs } = &snap.files["bin"].content else {
5191
        panic!("opaque")
5192
    };
5193
    assert_eq!(blobs.len(), 1, "one live blob, not none and not two");
5194
    assert_eq!(repo.read_blob(&blobs[0]).unwrap(), b"\0A");
5195
}
5196
5197
/// Spec §23: a binary file changed on two branches and merged in Git to
5198
/// one side's version comes back as that version at the merge, and the
5199
/// import verifies commit by commit.
5200
#[test]
5201
fn git_import_resolves_a_binary_merged_in_git_and_verifies() {
5202
    hermetic();
5203
    if std::process::Command::new("git")
5204
        .arg("--version")
5205
        .output()
5206
        .is_err()
5207
    {
5208
        eprintln!("git not installed; skipping");
5209
        return;
5210
    }
5211
    let dir = tempfile::tempdir().unwrap();
5212
    let root = dir.path();
5213
    let g = root.join("src.git");
5214
    fs::create_dir_all(&g).unwrap();
5215
    let git = |args: &[&str]| -> String {
5216
        let out = std::process::Command::new("git")
5217
            .arg("-C")
5218
            .arg(&g)
5219
            .args([
5220
                "-c",
5221
                "user.name=Grace",
5222
                "-c",
5223
                "[email protected]",
5224
                "-c",
5225
                "commit.gpgsign=false",
5226
            ])
5227
            .args(args)
5228
            .output()
5229
            .unwrap();
5230
        assert!(
5231
            out.status.success(),
5232
            "git {args:?}: {}",
5233
            String::from_utf8_lossy(&out.stderr)
5234
        );
5235
        String::from_utf8_lossy(&out.stdout).trim().to_string()
5236
    };
5237
    git(&["init", "-q", "-b", "main"]);
5238
    write(&g, "logo.bin", b"\0base");
5239
    write(&g, "notes.txt", b"a\nb\nc\n");
5240
    git(&["add", "."]);
5241
    git(&["commit", "-qm", "base"]);
5242
    git(&["checkout", "-qb", "side"]);
5243
    write(&g, "logo.bin", b"\0side");
5244
    write(&g, "notes.txt", b"a\nb\nx\nc\n");
5245
    git(&["commit", "-qam", "side"]);
5246
    git(&["checkout", "-q", "main"]);
5247
    write(&g, "logo.bin", b"\0main");
5248
    git(&["commit", "-qam", "main"]);
5249
    // Git cannot merge the binary; the merge takes main's and keeps side's text.
5250
    let _ = std::process::Command::new("git")
5251
        .arg("-C")
5252
        .arg(&g)
5253
        .args([
5254
            "-c",
5255
            "user.name=G",
5256
            "-c",
5257
            "user.email=g@e",
5258
            "merge",
5259
            "-q",
5260
            "side",
5261
        ])
5262
        .output();
5263
    write(&g, "logo.bin", b"\0main");
5264
    git(&["add", "."]);
5265
    git(&["commit", "-qm", "merge side"]);
5266
    // Then a revert of the binary to its first version.
5267
    write(&g, "logo.bin", b"\0base");
5268
    git(&["commit", "-qam", "back to base"]);
5269
5270
    let repo = Repo::init(&root.join("o")).unwrap();
5271
    let rep = repo.import_git(&g, "main").unwrap();
5272
    assert_eq!(rep.merges, 1);
5273
    let v = repo.verify_git_import(&g, "main").unwrap();
5274
    assert!(v.mismatches.is_empty(), "{:?}", v.mismatches);
5275
    assert_eq!(v.commits, 5);
5276
    let snap = repo
5277
        .load_state(&repo.bookmark_heads().unwrap())
5278
        .unwrap()
5279
        .materialize();
5280
    assert!(!snap.is_conflicted());
5281
    let FileContent::Opaque { blobs } = &snap.files["logo.bin"].content else {
5282
        panic!("opaque")
5283
    };
5284
    assert_eq!(repo.read_blob(&blobs[0]).unwrap(), b"\0base");
5285
}
5286
5287
/// Spec §7.7 on a file system without executable bits or symlinks: the
5288
/// recorded bit is kept, and a symlink checked out as a plain file holding
5289
/// its target is still that symlink.
5290
#[cfg(unix)]
5291
#[test]
5292
fn windows_file_systems_keep_exec_bits_and_symlinks() {
5293
    use crate::portable::Platform;
5294
    use std::os::unix::fs::PermissionsExt;
5295
    hermetic();
5296
    let dir = tempfile::tempdir().unwrap();
5297
    let root = dir.path();
5298
    let repo = Repo::init(root).unwrap();
5299
    write(root, "run.sh", b"#!/bin/sh\n");
5300
    fs::set_permissions(root.join("run.sh"), fs::Permissions::from_mode(0o755)).unwrap();
5301
    std::os::unix::fs::symlink("run.sh", root.join("link")).unwrap();
5302
    repo.commit("script and link", &[]).unwrap();
5303
    drop(repo);
5304
5305
    // What checking out on Windows leaves: no exec bit, the link as a file.
5306
    fs::set_permissions(root.join("run.sh"), fs::Permissions::from_mode(0o644)).unwrap();
5307
    fs::remove_file(root.join("link")).unwrap();
5308
    write(root, "link", b"run.sh");
5309
    let win = Repo::open(root).unwrap().with_platform(Platform::windows());
5310
    let s = win.snapshot("oxy status").unwrap();
5311
    assert!(
5312
        s.statuses.is_empty(),
5313
        "nothing changed on Windows: {:?}",
5314
        statuses(&s)
5315
    );
5316
    // Editing the file is a content change, not a mode change; retargeting the link keeps it a link.
5317
    write(root, "run.sh", b"#!/bin/sh\necho hi\n");
5318
    write(root, "link", b"other");
5319
    let h = win.commit("edit on Windows", &[]).unwrap();
5320
    let snap = win.load_state(&[h]).unwrap().materialize();
5321
    assert!(snap.files["run.sh"].mode.exec, "the exec bit survives");
5322
    assert_eq!(snap.files["link"].kind, NodeKind::Symlink);
5323
    // The same working copy read as Linux sees the lost bit and the plain file.
5324
    let linux = Repo::open(root).unwrap();
5325
    assert!(!linux.snapshot("oxy status").unwrap().statuses.is_empty());
5326
}
5327
5328
/// Paths that collide on case-insensitive or Windows file systems are
5329
/// named at checkout there, and by doctor everywhere.
5330
#[test]
5331
fn paths_other_platforms_cannot_hold_are_reported() {
5332
    use crate::portable::Platform;
5333
    hermetic();
5334
    let dir = tempfile::tempdir().unwrap();
5335
    let root = dir.path();
5336
    let repo = Repo::init(root).unwrap();
5337
    write(root, "README.md", b"a\n");
5338
    write(root, "readme.md", b"b\n");
5339
    write(root, "src/aux.c", b"int x;\n");
5340
    let h = repo.commit("unportable", &[]).unwrap();
5341
    let r = repo.doctor(false);
5342
    let port = r.checks.iter().find(|c| c.area == "portability").unwrap();
5343
    assert_eq!(port.health, Health::Warn);
5344
    assert!(
5345
        port.message.contains("differ only in case") && port.message.contains("aux.c"),
5346
        "{}",
5347
        port.message
5348
    );
5349
    let mac = Repo::open(root).unwrap().with_platform(Platform::macos());
5350
    let rep = mac.checkout(&[h], true, "oxy checkout").unwrap();
5351
    assert!(
5352
        rep.notes
5353
            .iter()
5354
            .any(|n| n.contains("README.md and readme.md")),
5355
        "{:?}",
5356
        rep.notes
5357
    );
5358
    assert!(
5359
        !rep.notes.iter().any(|n| n.contains("aux.c")),
5360
        "macOS allows aux.c"
5361
    );
5362
}
5363
5364
#[test]
5365
fn history_and_blame_of_a_loaded_state_match_the_full_walk() {
5366
    hermetic();
5367
    let dir = tempfile::tempdir().unwrap();
5368
    let repo = Repo::init(dir.path()).unwrap();
5369
    write(dir.path(), "a.txt", b"one\n");
5370
    write(dir.path(), "other.txt", b"x\n");
5371
    write(dir.path(), "bin.dat", &[0u8, 1, 2, 0, 255]);
5372
    repo.snapshot("t").unwrap();
5373
    let c1 = repo.commit("first", &[]).unwrap();
5374
    write(dir.path(), "other.txt", b"y\n");
5375
    repo.snapshot("t").unwrap();
5376
    repo.commit("other only", &[]).unwrap();
5377
    write(dir.path(), "a.txt", b"one\ntwo\n");
5378
    repo.snapshot("t").unwrap();
5379
    let c3 = repo.commit("second line", &[]).unwrap();
5380
    write(dir.path(), "other.txt", b"z\n");
5381
    repo.snapshot("t").unwrap();
5382
    repo.commit("other again", &[]).unwrap();
5383
5384
    let heads = repo.bookmark_heads().unwrap();
5385
    let state = repo.load_state(&heads).unwrap();
5386
    let full: Vec<ChangeHash> = repo
5387
        .log_for_path_in("a.txt", &heads)
5388
        .unwrap()
5389
        .iter()
5390
        .map(|e| e.hash)
5391
        .collect();
5392
    assert_eq!(
5393
        full,
5394
        vec![c3, c1],
5395
        "newest first, only changes touching the path"
5396
    );
5397
    let newest: Vec<ChangeHash> = repo
5398
        .log_for_path_of(&state, "a.txt", Some(1))
5399
        .unwrap()
5400
        .iter()
5401
        .map(|e| e.hash)
5402
        .collect();
5403
    assert_eq!(newest, vec![c3], "stops at the first");
5404
    assert_eq!(
5405
        repo.log_for_path_of(&state, "a.txt", None).unwrap().len(),
5406
        2
5407
    );
5408
    assert!(repo
5409
        .log_for_path_of(&state, "missing.txt", Some(1))
5410
        .is_err());
5411
    assert_eq!(
5412
        repo.log_state(&heads).unwrap().len(),
5413
        repo.log_of(&state).len()
5414
    );
5415
5416
    let tree = state.tree().view();
5417
    let via_state = repo.blame_of(&state, &tree, "a.txt").unwrap();
5418
    let via_heads = repo.blame_in("a.txt", &heads).unwrap();
5419
    assert_eq!(
5420
        via_state
5421
            .iter()
5422
            .map(|l| (l.hash, l.text.clone()))
5423
            .collect::<Vec<_>>(),
5424
        via_heads
5425
            .iter()
5426
            .map(|l| (l.hash, l.text.clone()))
5427
            .collect::<Vec<_>>()
5428
    );
5429
    assert_eq!(
5430
        via_state.iter().map(|l| l.hash).collect::<Vec<_>>(),
5431
        vec![c1, c3]
5432
    );
5433
    assert!(repo.blame_of(&state, &tree, "missing.txt").is_err());
5434
}
5435
5436
/// A text file whose stat matches the manifest and whose recorded hash is
5437
/// the base's content is taken from the base without reading it; anything
5438
/// else is read, so no edit is missed (spec §12.3).
5439
#[cfg(unix)]
5440
#[test]
5441
fn stat_cache_takes_unchanged_text_from_the_base_and_misses_no_edit() {
5442
    use std::os::unix::fs::PermissionsExt;
5443
    hermetic();
5444
    let dir = tempfile::tempdir().unwrap();
5445
    let root = dir.path();
5446
    let repo = Repo::init(root).unwrap().with_home(root.join("home"));
5447
    write(root, "a.txt", b"one\ntwo\n");
5448
    write(root, "b.txt", b"bee\n");
5449
    repo.commit("base", &[]).unwrap();
5450
    let age = |p: &str| {
5451
        let old = std::time::SystemTime::now() - std::time::Duration::from_secs(30);
5452
        fs::File::options()
5453
            .write(true)
5454
            .open(root.join(p))
5455
            .unwrap()
5456
            .set_modified(old)
5457
            .unwrap();
5458
    };
5459
    age("a.txt");
5460
    age("b.txt");
5461
    assert!(
5462
        !repo.snapshot("status").unwrap().changed,
5463
        "records the aged stat"
5464
    );
5465
5466
    // Clean and equal to the base: not read at all.
5467
    fs::set_permissions(root.join("a.txt"), fs::Permissions::from_mode(0o000)).unwrap();
5468
    let snap = repo.snapshot("status").unwrap();
5469
    assert!(
5470
        !snap.changed && snap.statuses.is_empty(),
5471
        "{:?}",
5472
        snap.statuses
5473
    );
5474
    fs::set_permissions(root.join("a.txt"), fs::Permissions::from_mode(0o644)).unwrap();
5475
5476
    // An uncommitted edit that is older than the manifest: stat-clean, but
5477
    // its hash is not the base's, so it is read and stays visible.
5478
    write(root, "b.txt", b"bee edited\n");
5479
    age("b.txt");
5480
    let first = repo.snapshot("status").unwrap();
5481
    assert_eq!(
5482
        statuses(&first),
5483
        vec![("b.txt".to_string(), ChangeStatus::Modified)]
5484
    );
5485
    let again = repo.snapshot("status").unwrap();
5486
    assert_eq!(
5487
        statuses(&again),
5488
        vec![("b.txt".to_string(), ChangeStatus::Modified)],
5489
        "still seen once stat-clean"
5490
    );
5491
    assert!(!again.changed, "and the working copy hashes the same");
5492
    fs::set_permissions(root.join("b.txt"), fs::Permissions::from_mode(0o000)).unwrap();
5493
    assert!(
5494
        repo.snapshot("status").is_err(),
5495
        "an edited file must be read, never taken from the base"
5496
    );
5497
    fs::set_permissions(root.join("b.txt"), fs::Permissions::from_mode(0o644)).unwrap();
5498
5499
    // A same-size edit made just now is racy and read.
5500
    write(root, "a.txt", b"one\nTWO\n");
5501
    assert_eq!(
5502
        statuses(&repo.snapshot("status").unwrap()),
5503
        vec![
5504
            ("a.txt".to_string(), ChangeStatus::Modified),
5505
            ("b.txt".to_string(), ChangeStatus::Modified)
5506
        ]
5507
    );
5508
    // Committing makes the edits the base: both are clean and served from it again.
5509
    repo.commit("edits", &[]).unwrap();
5510
    age("a.txt");
5511
    age("b.txt");
5512
    assert!(repo.snapshot("status").unwrap().statuses.is_empty());
5513
    fs::set_permissions(root.join("a.txt"), fs::Permissions::from_mode(0o000)).unwrap();
5514
    fs::set_permissions(root.join("b.txt"), fs::Permissions::from_mode(0o000)).unwrap();
5515
    let snap = repo.snapshot("status").unwrap();
5516
    assert!(!snap.changed && snap.statuses.is_empty());
5517
    fs::set_permissions(root.join("a.txt"), fs::Permissions::from_mode(0o644)).unwrap();
5518
    fs::set_permissions(root.join("b.txt"), fs::Permissions::from_mode(0o644)).unwrap();
5519
}
5520
5521
/// Version 2 checkpoints (spec §11): a large file's graph is a blob of its
5522
/// own, kept by gc, checked by fsck, shared by the next checkpoint when the
5523
/// file is unchanged, and loading through the checkpoint equals a full load.
5524
#[test]
5525
fn checkpoints_keep_large_graphs_as_blobs_of_their_own() {
5526
    hermetic();
5527
    let dir = tempfile::tempdir().unwrap();
5528
    let root = dir.path();
5529
    let repo = Repo::init(root).unwrap().with_home(root.join("home"));
5530
    let long: String = (0..300)
5531
        .map(|i| format!("line {i} of a long file\n"))
5532
        .collect();
5533
    write(root, "long.txt", long.as_bytes());
5534
    write(root, "short.txt", b"short\n");
5535
    repo.commit("base", &[]).unwrap();
5536
    let (r1, _, _) = repo.checkpoint().unwrap();
5537
    let cp1 = crate::objects::Checkpoint::decode(
5538
        &repo.store().get_typed(&r1, ObjectType::Checkpoint).unwrap(),
5539
    )
5540
    .unwrap();
5541
    let graphs1 = repo.checkpoint_graph_blobs(&cp1).unwrap();
5542
    assert_eq!(graphs1.len(), 1, "only the long file's graph is a blob");
5543
5544
    // gc keeps the graph blob; fsck finds the checkpoint sound.
5545
    repo.gc(true).unwrap();
5546
    assert!(repo.store().has(&graphs1[0]));
5547
    let report = repo.fsck().unwrap();
5548
    assert_eq!(report.errors(), 0, "{:?}", report.problems);
5549
5550
    // Loading through the checkpoint equals a full load.
5551
    write(root, "short.txt", b"short, edited\n");
5552
    repo.commit("edit the short file", &[]).unwrap();
5553
    let heads = repo.bookmark_heads().unwrap();
5554
    let fast = repo.load_state(&heads).unwrap();
5555
    let full = repo.load_state_full(&heads).unwrap();
5556
    assert_eq!(fast.checkpoint_payload(), full.checkpoint_payload());
5557
5558
    // The next checkpoint shares the unchanged long file's graph.
5559
    let (r2, _, _) = repo.checkpoint().unwrap();
5560
    let cp2 = crate::objects::Checkpoint::decode(
5561
        &repo.store().get_typed(&r2, ObjectType::Checkpoint).unwrap(),
5562
    )
5563
    .unwrap();
5564
    assert_eq!(repo.checkpoint_graph_blobs(&cp2).unwrap(), graphs1);
5565
5566
    // A shallow clone's bundle carries the graph blob with the checkpoint.
5567
    let bundle = repo.checkpoint_bundle_for(&heads).unwrap();
5568
    assert!(bundle.objects.iter().any(|(t, body)| *t == ObjectType::Blob
5569
        && crate::hash::hash_object(ObjectType::Blob, body) == graphs1[0]));
5570
5571
    // A version 1 checkpoint written by an older oxy still loads.
5572
    let state = repo.load_state_full(&heads).unwrap();
5573
    let old = repo.store_blob(&state.checkpoint_payload()).unwrap();
5574
    let cp_old = crate::objects::Checkpoint {
5575
        heads: cp2.heads.clone(),
5576
        count: cp2.count,
5577
        payload: old,
5578
    };
5579
    let r_old = repo
5580
        .store()
5581
        .put(ObjectType::Checkpoint, &cp_old.encode())
5582
        .unwrap();
5583
    repo.install_checkpoint("main", &r_old).unwrap();
5584
    assert_eq!(
5585
        repo.load_state(&heads).unwrap().checkpoint_payload(),
5586
        full.checkpoint_payload()
5587
    );
5588
    assert_eq!(repo.fsck().unwrap().errors(), 0);
5589
5590
    // A lost graph blob fails the load loudly rather than dropping the
5591
    // file, and fsck reports it (a fresh repository, objects still loose).
5592
    let dir2 = tempfile::tempdir().unwrap();
5593
    let root2 = dir2.path();
5594
    let repo2 = Repo::init(root2).unwrap().with_home(root2.join("home"));
5595
    write(root2, "long.txt", long.as_bytes());
5596
    repo2.commit("base", &[]).unwrap();
5597
    let (r, _, _) = repo2.checkpoint().unwrap();
5598
    let cp = crate::objects::Checkpoint::decode(
5599
        &repo2.store().get_typed(&r, ObjectType::Checkpoint).unwrap(),
5600
    )
5601
    .unwrap();
5602
    let graph = repo2.checkpoint_graph_blobs(&cp).unwrap()[0];
5603
    repo2.store().remove_loose_for_test(&graph).unwrap();
5604
    assert!(repo2.load_state(&repo2.bookmark_heads().unwrap()).is_err());
5605
    assert!(repo2.fsck().unwrap().errors() > 0, "fsck reports it");
5606
}
5607
5608
/// A new repository has not stored the user's identity yet (that happens
5609
/// at the first signed change); looking it up falls back to the key
5610
/// directory, and a file there that does not hash to the key is refused.
5611
#[test]
5612
fn identity_is_found_in_the_key_directory_for_a_new_repository() {
5613
    hermetic();
5614
    let dir = tempfile::tempdir().unwrap();
5615
    let home = dir.path().join("home");
5616
    let mut first = Repo::init(&dir.path().join("a"))
5617
        .unwrap()
5618
        .with_home(home.clone());
5619
    let (key, _) = first
5620
        .create_identity("Ada", "[email protected]", IdentityScope::User)
5621
        .unwrap();
5622
    let fresh = Repo::init(&dir.path().join("b"))
5623
        .unwrap()
5624
        .with_home(home.clone());
5625
    assert!(!fresh.store().has(&key), "nothing stored yet");
5626
    let id = fresh.identity(&key).unwrap();
5627
    assert_eq!((id.name.as_str(), id.hash()), ("Ada", key));
5628
    // A key file that is not this identity is an error, not a wrong answer.
5629
    let keys = fresh.keys_dir.clone();
5630
    let (other, _) = first
5631
        .create_identity("Bob", "[email protected]", IdentityScope::User)
5632
        .unwrap();
5633
    fs::copy(
5634
        keys.join(format!("{}.identity", other.to_hex())),
5635
        keys.join(format!("{}.identity", key.to_hex())),
5636
    )
5637
    .unwrap();
5638
    assert!(fresh
5639
        .identity(&key)
5640
        .unwrap_err()
5641
        .to_string()
5642
        .contains("does not hold identity"));
5643
}
5644
5645
/// Status snapshots (spec §12.3): a text file whose stat matches the
5646
/// manifest, and whose base graph key is the one the manifest recorded it
5647
/// equal to, is neither read nor rendered; any edit, and any change to the
5648
/// file's graph in the base, brings it back.
5649
#[cfg(unix)]
5650
#[test]
5651
fn status_snapshots_skip_files_unchanged_since_the_manifest() {
5652
    use std::os::unix::fs::PermissionsExt;
5653
    hermetic();
5654
    let dir = tempfile::tempdir().unwrap();
5655
    let root = dir.path();
5656
    let repo = Repo::init(root).unwrap().with_home(root.join("home"));
5657
    for (p, c) in [("a.txt", "one\n"), ("b.txt", "bee\n"), ("d/c.txt", "sea\n")] {
5658
        write(root, p, c.as_bytes());
5659
    }
5660
    repo.commit("base", &[]).unwrap();
5661
    let age = |p: &str| {
5662
        let old = std::time::SystemTime::now() - std::time::Duration::from_secs(30);
5663
        fs::File::options()
5664
            .write(true)
5665
            .open(root.join(p))
5666
            .unwrap()
5667
            .set_modified(old)
5668
            .unwrap();
5669
    };
5670
    let lock = |p: &str, mode: u32| {
5671
        fs::set_permissions(root.join(p), fs::Permissions::from_mode(mode)).unwrap()
5672
    };
5673
    for p in ["a.txt", "b.txt", "d/c.txt"] {
5674
        age(p);
5675
    }
5676
    assert!(repo.snapshot("status").unwrap().statuses.is_empty());
5677
    let (_, _, m) = repo.read_manifest().unwrap().unwrap();
5678
    assert!(
5679
        m.entries.values().all(|e| e.graph.is_some()),
5680
        "keys recorded"
5681
    );
5682
5683
    // Unreadable files prove they are not read; the status snapshot does
5684
    // not render them either, and its base lacks their graphs.
5685
    lock("a.txt", 0o000);
5686
    lock("b.txt", 0o000);
5687
    let snap = repo.snapshot_status("status").unwrap();
5688
    assert!(!snap.changed && snap.statuses.is_empty());
5689
    assert_eq!(
5690
        snap.base_snapshot
5691
            .unrendered
5692
            .iter()
5693
            .cloned()
5694
            .collect::<Vec<_>>(),
5695
        vec!["a.txt", "b.txt", "d/c.txt"]
5696
    );
5697
    assert!(!snap.base.is_full());
5698
    assert!(!snap.base_snapshot.is_conflicted());
5699
    // A full snapshot does not read them either, but renders everything.
5700
    let full = repo.snapshot("status").unwrap();
5701
    assert!(full.statuses.is_empty() && full.base.is_full());
5702
    assert!(full.base_snapshot.unrendered.is_empty());
5703
    assert!(matches!(&full.base_snapshot.files["a.txt"].content,
5704
        FileContent::Text { bytes, .. } if bytes == b"one\n"));
5705
5706
    // An edit is seen; the file is rendered, the others still are not.
5707
    write(root, "d/c.txt", b"sea edited\n");
5708
    let snap = repo.snapshot_status("status").unwrap();
5709
    assert_eq!(
5710
        statuses(&snap),
5711
        vec![("d/c.txt".to_string(), ChangeStatus::Modified)]
5712
    );
5713
    assert!(!snap.base_snapshot.unrendered.contains("d/c.txt"));
5714
    // So is a mode change of an unread file.
5715
    lock("b.txt", 0o100);
5716
    assert_eq!(
5717
        statuses(&repo.snapshot_status("status").unwrap()),
5718
        vec![
5719
            ("b.txt".to_string(), ChangeStatus::ModeChanged),
5720
            ("d/c.txt".to_string(), ChangeStatus::Modified)
5721
        ]
5722
    );
5723
    lock("b.txt", 0o000);
5724
5725
    // Committing c.txt changes its graph in the base, not a.txt's: a.txt
5726
    // stays unread, c.txt is read once and then skipped too.
5727
    repo.commit_selection("edit c", &[], &Selection::Paths(vec!["d/c.txt".into()]))
5728
        .unwrap();
5729
    age("d/c.txt");
5730
    let snap = repo.snapshot_status("status").unwrap();
5731
    assert!(snap.statuses.is_empty(), "{:?}", snap.statuses);
5732
    assert!(snap.base_snapshot.unrendered.contains("a.txt"));
5733
    lock("d/c.txt", 0o000);
5734
    let snap = repo.snapshot_status("status").unwrap();
5735
    assert!(snap.statuses.is_empty());
5736
    assert!(snap.base_snapshot.unrendered.contains("d/c.txt"));
5737
    for p in ["a.txt", "b.txt", "d/c.txt"] {
5738
        lock(p, 0o644);
5739
    }
5740
}
5741
5742
/// Attributes decide how a file compares with the base, so a changed
5743
/// `.oxyattributes` makes every text file be compared again.
5744
#[cfg(unix)]
5745
#[test]
5746
fn a_changed_attributes_file_disables_skipping_unchanged_files() {
5747
    hermetic();
5748
    let dir = tempfile::tempdir().unwrap();
5749
    let root = dir.path();
5750
    let repo = Repo::init(root).unwrap().with_home(root.join("home"));
5751
    write(root, "a.txt", b"crlf\r\n");
5752
    repo.commit("base", &[]).unwrap();
5753
    let old = std::time::SystemTime::now() - std::time::Duration::from_secs(30);
5754
    fs::File::options()
5755
        .write(true)
5756
        .open(root.join("a.txt"))
5757
        .unwrap()
5758
        .set_modified(old)
5759
        .unwrap();
5760
    assert!(repo.snapshot_status("status").unwrap().statuses.is_empty());
5761
    assert!(repo
5762
        .snapshot_status("status")
5763
        .unwrap()
5764
        .base_snapshot
5765
        .unrendered
5766
        .contains("a.txt"));
5767
    // With eol=lf, a.txt as stored no longer equals the base.
5768
    write(root, ".oxyattributes", b"*.txt eol=lf\n");
5769
    let snap = repo.snapshot_status("status").unwrap();
5770
    assert_eq!(
5771
        statuses(&snap),
5772
        vec![
5773
            (".oxyattributes".to_string(), ChangeStatus::Added),
5774
            ("a.txt".to_string(), ChangeStatus::Modified)
5775
        ]
5776
    );
5777
}
5778
5779
/// Bookmarks with `/` in their names: pushing records their
5780
/// attestations, and checkpoints are kept for them, beside `feature`
5781
/// itself.
5782
#[test]
5783
fn bookmarks_with_slashes_push_and_checkpoint() {
5784
    hermetic();
5785
    let dir = tempfile::tempdir().unwrap();
5786
    let root = dir.path();
5787
    let origin = Repo::init(&root.join("origin")).unwrap();
5788
    let url = root.join("origin").to_string_lossy().to_string();
5789
    let mut repo = Repo::clone(&url, &root.join("r"))
5790
        .unwrap()
5791
        .with_home(root.join("home"));
5792
    // With an identity, pushes carry reference attestations: the case
5793
    // that failed, since the attestation is a file named after the bookmark.
5794
    repo.create_identity("Ada", "[email protected]", IdentityScope::Repo)
5795
        .unwrap();
5796
    let r = root.join("r");
5797
    write(&r, "a.txt", b"a\n");
5798
    let h_a = repo.commit("a", &[]).unwrap();
5799
    assert!(repo.push("origin", false).unwrap()[0].ok);
5800
    origin.refresh().unwrap();
5801
    repo.bookmark_create("feature", None).unwrap();
5802
    repo.bookmark_create("feature/x", None).unwrap();
5803
    repo.bookmark_switch("feature/x", false).unwrap();
5804
    write(&r, "b.txt", b"b\n");
5805
    let h_b = repo.commit("b", &[]).unwrap();
5806
    for name in ["feature", "feature/x"] {
5807
        let res = repo.push_bookmark("origin", name, false).unwrap();
5808
        origin.refresh().unwrap();
5809
        assert!(res[0].ok, "{name}: {res:?}");
5810
    }
5811
    assert_eq!(origin.resolve_heads("feature").unwrap(), vec![h_a]);
5812
    assert_eq!(
5813
        origin.resolve_heads("feature/x").unwrap(),
5814
        repo.resolve_heads("feature/x").unwrap()
5815
    );
5816
    assert!(origin.resolve_heads("feature/x").unwrap().contains(&h_b));
5817
    assert!(origin.latest_ref_attest("feature/x").unwrap().is_some());
5818
    assert!(origin.latest_ref_attest("feature").unwrap().is_some());
5819
5820
    // A checkpoint of feature/x is found again when loading its state.
5821
    let (cp, _, _) = repo.checkpoint().unwrap();
5822
    assert_eq!(repo.latest_checkpoint("feature/x").unwrap().unwrap().0, cp);
5823
    assert!(repo.latest_checkpoint("feature").unwrap().is_none());
5824
    let heads = repo.resolve_heads("feature/x").unwrap();
5825
    assert!(repo.load_state_checkpointed(&heads).unwrap().is_some());
5826
}
5827
5828
/// Deleting a bookmark on a remote (spec §16.4): attested like any update,
5829
/// never the remote's own bookmark, and a bookmark created again later is
5830
/// accepted although the deletion's attestation stays the latest.
5831
#[test]
5832
fn bookmarks_are_deleted_on_a_remote() {
5833
    hermetic();
5834
    let dir = tempfile::tempdir().unwrap();
5835
    let root = dir.path();
5836
    let origin = Repo::init(&root.join("origin")).unwrap();
5837
    let url = root.join("origin").to_string_lossy().to_string();
5838
    let mut repo = Repo::clone(&url, &root.join("r"))
5839
        .unwrap()
5840
        .with_home(root.join("home"));
5841
    repo.create_identity("Ada", "[email protected]", IdentityScope::Repo)
5842
        .unwrap();
5843
    let r = root.join("r");
5844
    write(&r, "a.txt", b"a\n");
5845
    repo.commit("a", &[]).unwrap();
5846
    assert!(repo.push("origin", false).unwrap()[0].ok);
5847
    origin.refresh().unwrap();
5848
    repo.bookmark_create("feature/x", None).unwrap();
5849
    assert!(repo.push_bookmark("origin", "feature/x", false).unwrap()[0].ok);
5850
    origin.refresh().unwrap();
5851
    assert!(origin.resolve_heads("feature/x").is_ok());
5852
5853
    let res = repo.push_delete("origin", "feature/x").unwrap();
5854
    origin.refresh().unwrap();
5855
    assert!(res[0].ok, "{res:?}");
5856
    assert!(!origin.view().unwrap().bookmarks.contains_key("feature/x"));
5857
    let (_, att) = origin.latest_ref_attest("feature/x").unwrap().unwrap();
5858
    assert!(
5859
        matches!(att.attest.body, AttestBody::Ref { new_state, .. } if new_state.is_zero()),
5860
        "the deletion is attested"
5861
    );
5862
    assert!(
5863
        repo.view().unwrap().bookmarks.contains_key("feature/x"),
5864
        "the local bookmark stays"
5865
    );
5866
    assert!(!repo
5867
        .view()
5868
        .unwrap()
5869
        .remotes
5870
        .get("origin")
5871
        .is_some_and(|m| m.contains_key("feature/x")));
5872
5873
    // Pushing it again creates it again, past the deletion's serial.
5874
    let res = repo.push_bookmark("origin", "feature/x", false).unwrap();
5875
    origin.refresh().unwrap();
5876
    assert!(res[0].ok, "{res:?}");
5877
    assert!(origin.view().unwrap().bookmarks.contains_key("feature/x"));
5878
5879
    // Nothing to delete, and never the remote's own bookmark.
5880
    assert!(repo.push_delete("origin", "nope").is_err());
5881
    let res = repo.push_delete("origin", "main").unwrap();
5882
    origin.refresh().unwrap();
5883
    assert!(
5884
        !res[0].ok && res[0].reason.contains("default bookmark"),
5885
        "{res:?}"
5886
    );
5887
    assert!(origin.view().unwrap().bookmarks.contains_key("main"));
5888
}
5889
5890
/// `bookmark switch --carry` (spec §10.1): uncommitted work goes along
5891
/// when the target has the same versions of the files it touches, and is
5892
/// refused, untouched, when it has others.
5893
#[test]
5894
fn switching_bookmarks_carries_uncommitted_work() {
5895
    hermetic();
5896
    let dir = tempfile::tempdir().unwrap();
5897
    let root = dir.path();
5898
    let mut repo = Repo::init(root).unwrap().with_home(root.join("home"));
5899
    write(root, "a.txt", b"a\n");
5900
    write(root, "b.txt", b"b\n");
5901
    write(root, "gone.txt", b"gone\n");
5902
    repo.commit("base", &[]).unwrap();
5903
    repo.bookmark_create("feature", None).unwrap();
5904
    // Started on main, belongs on feature: edit, add, remove.
5905
    write(root, "a.txt", b"a\nmore\n");
5906
    write(root, "new.txt", b"new\n");
5907
    fs::remove_file(root.join("gone.txt")).unwrap();
5908
    let (report, carried) = repo.bookmark_switch_carry("feature").unwrap();
5909
    assert_eq!(carried, vec!["a.txt", "gone.txt", "new.txt"]);
5910
    // oxygen#120: the new file was carried, not removed.
5911
    assert_eq!(
5912
        (report.removed, report.removed_paths.len()),
5913
        (0, 0),
5914
        "{report:?}"
5915
    );
5916
    assert_eq!(repo.config.bookmark, "feature");
5917
    assert_eq!(fs::read(root.join("a.txt")).unwrap(), b"a\nmore\n");
5918
    assert_eq!(fs::read(root.join("new.txt")).unwrap(), b"new\n");
5919
    assert!(!root.join("gone.txt").exists());
5920
    let snap = repo.snapshot("status").unwrap();
5921
    assert_eq!(
5922
        statuses(&snap),
5923
        vec![
5924
            ("a.txt".to_string(), ChangeStatus::Modified),
5925
            ("gone.txt".to_string(), ChangeStatus::Removed),
5926
            ("new.txt".to_string(), ChangeStatus::Added)
5927
        ]
5928
    );
5929
    repo.commit("the work", &[]).unwrap();
5930
    assert!(repo.resolve_heads("main").unwrap().len() == 1);
5931
5932
    // main moves b.txt on; work on feature touching b.txt cannot follow.
5933
    repo.bookmark_switch("main", false).unwrap();
5934
    write(root, "b.txt", b"b on main\n");
5935
    repo.commit("b on main", &[]).unwrap();
5936
    repo.bookmark_switch("feature", false).unwrap();
5937
    write(root, "b.txt", b"b edited\n");
5938
    let err = repo.bookmark_switch_carry("main").unwrap_err().to_string();
5939
    assert!(err.contains("b.txt") && err.contains("--discard"), "{err}");
5940
    assert_eq!(repo.config.bookmark, "feature", "nothing happened");
5941
    assert_eq!(fs::read(root.join("b.txt")).unwrap(), b"b edited\n");
5942
}
5943
5944
/// Merging and checking out (feedback 3): a working copy without changes
5945
/// follows a merge whichever state it sat on; a refused checkout names
5946
/// what is in the way; `checkout --carry` takes the work along.
5947
#[test]
5948
fn merges_move_clean_working_copies_and_checkouts_say_what_blocks_them() {
5949
    hermetic();
5950
    let dir = tempfile::tempdir().unwrap();
5951
    let root = dir.path();
5952
    let mut repo = Repo::init(root).unwrap().with_home(root.join("home"));
5953
    write(root, "a.txt", b"a\n");
5954
    let h1 = repo.commit("a", &[]).unwrap();
5955
    write(root, "b.txt", b"b\n");
5956
    repo.commit("b", &[]).unwrap();
5957
    repo.bookmark_create("feature", None).unwrap();
5958
    repo.bookmark_switch("feature", false).unwrap();
5959
    write(root, "c.txt", b"c\n");
5960
    repo.commit("c on feature", &[]).unwrap();
5961
    repo.bookmark_switch("main", false).unwrap();
5962
    // The working copy sits on an older state than main's heads.
5963
    repo.checkout(&[h1], false, "checkout").unwrap();
5964
    assert!(!root.join("b.txt").exists());
5965
    let m = repo.merge("feature").unwrap();
5966
    assert!(m.checked_out, "a clean working copy follows the merge");
5967
    for f in ["a.txt", "b.txt", "c.txt"] {
5968
        assert!(root.join(f).exists(), "{f}");
5969
    }
5970
5971
    // A refusal says which paths are in the way and what to do.
5972
    fs::remove_file(root.join("b.txt")).unwrap();
5973
    write(root, "a.txt", b"a edited\n");
5974
    let err = repo
5975
        .checkout(&[h1], false, "checkout")
5976
        .unwrap_err()
5977
        .to_string();
5978
    assert!(
5979
        err.contains("modified a.txt") && err.contains("removed b.txt") && err.contains("--carry"),
5980
        "{err}"
5981
    );
5982
    // --carry takes them along: h1 has a.txt as the base has it, and the
5983
    // removed b.txt is already as h1 has it (none), so that is no conflict
5984
    // either (oxygen#100).
5985
    let (_, carried) = repo
5986
        .checkout_carry(&[h1], "the first change", "checkout")
5987
        .unwrap();
5988
    assert_eq!(carried, vec!["a.txt"]);
5989
    assert_eq!(fs::read(root.join("a.txt")).unwrap(), b"a edited\n");
5990
    assert!(!root.join("b.txt").exists(), "h1 has no b.txt");
5991
}
5992
5993
/// Doctor and subrepos before the first commit (feedback 5 and 8): a
5994
/// user identity not stored in a new repository yet is fine while its
5995
/// secret key is there; an added subrepo is listed as not committed yet.
5996
#[test]
5997
fn a_new_repository_is_healthy_before_its_first_commit() {
5998
    hermetic();
5999
    let dir = tempfile::tempdir().unwrap();
6000
    let root = dir.path();
6001
    let home = root.join("home");
6002
    let mut first = Repo::init(&root.join("first"))
6003
        .unwrap()
6004
        .with_home(home.clone());
6005
    let (key, _) = first
6006
        .create_identity("Ada", "[email protected]", IdentityScope::User)
6007
        .unwrap();
6008
    let repo = Repo::init(&root.join("second"))
6009
        .unwrap()
6010
        .with_home(home.clone());
6011
    // Only the secret key: no identity object anywhere this repository sees.
6012
    let keys = repo.keys_dir.clone();
6013
    let _ = fs::remove_file(keys.join(format!("{}.identity", key.to_hex())));
6014
    assert!(keys.join(format!("{}.secret", key.to_hex())).is_file());
6015
    let r = repo.doctor(true);
6016
    let id = r.checks.iter().find(|c| c.area == "identity").unwrap();
6017
    assert_eq!(id.health, Health::Ok, "{}", id.message);
6018
    assert!(id.message.contains("first signed change"), "{}", id.message);
6019
6020
    // A subrepo added and not committed yet is listed, pinned where it is.
6021
    let lib = root.join("lib");
6022
    let l = Repo::init(&lib).unwrap().with_home(home.clone());
6023
    write(&lib, "x.txt", b"x\n");
6024
    l.commit("x", &[]).unwrap();
6025
    let second = root.join("second");
6026
    write(&second, "a.txt", b"a\n");
6027
    repo.submodule_add(&lib.to_string_lossy(), "deps/lib", None)
6028
        .unwrap();
6029
    let subs = repo.subrepos().unwrap();
6030
    assert_eq!(subs.len(), 1);
6031
    assert_eq!(
6032
        (subs[0].path.as_str(), subs[0].committed),
6033
        ("deps/lib", false)
6034
    );
6035
    assert_eq!(subs[0].actual.as_ref(), Some(&subs[0].pin));
6036
    repo.commit("add lib", &[]).unwrap();
6037
    let subs = repo.subrepos().unwrap();
6038
    assert!(subs[0].committed, "committed now");
6039
}
6040
6041
/// Commit, diff, hunks and discard use the partial snapshot: a file
6042
/// unchanged since the manifest is neither read nor rendered, and showing
6043
/// a change renders only what it edits, the same as from a full base.
6044
#[cfg(unix)]
6045
#[test]
6046
fn commits_and_diffs_leave_unchanged_files_alone() {
6047
    use std::os::unix::fs::PermissionsExt;
6048
    hermetic();
6049
    let dir = tempfile::tempdir().unwrap();
6050
    let root = dir.path();
6051
    let repo = Repo::init(root).unwrap().with_home(root.join("home"));
6052
    write(root, "big.txt", b"lots\nof\nlines\n");
6053
    write(root, "a.txt", b"one\ntwo\n");
6054
    repo.commit("base", &[]).unwrap();
6055
    let old = std::time::SystemTime::now() - std::time::Duration::from_secs(30);
6056
    for f in ["big.txt", "a.txt"] {
6057
        fs::File::options()
6058
            .write(true)
6059
            .open(root.join(f))
6060
            .unwrap()
6061
            .set_modified(old)
6062
            .unwrap();
6063
    }
6064
    assert!(repo.snapshot_status("status").unwrap().statuses.is_empty());
6065
    // big.txt cannot be read at all from here on.
6066
    fs::set_permissions(root.join("big.txt"), fs::Permissions::from_mode(0o000)).unwrap();
6067
6068
    write(root, "a.txt", b"one\nTWO\nthree\n");
6069
    let diff = repo.diff_files(None).unwrap();
6070
    assert_eq!(
6071
        diff.iter().map(|f| f.path.as_str()).collect::<Vec<_>>(),
6072
        ["a.txt"]
6073
    );
6074
    let (_, hunks) = repo.hunks().unwrap();
6075
    assert!(!hunks.is_empty() && hunks.iter().all(|h| h.path == "a.txt"));
6076
    let h = repo.commit("edit a", &[]).unwrap();
6077
6078
    // Showing the change needs only a.txt's graph, and renders as a full base does.
6079
    let c = repo.store().get_change(&h).unwrap();
6080
    let full = repo.load_state(&c.deps).unwrap();
6081
    let want = render_change(&c, &full, &full.materialize());
6082
    assert_eq!(repo.describe_change(&h).unwrap(), want);
6083
    let (base, snap) = repo.change_base(&c).unwrap();
6084
    assert!(!base.is_full() && snap.unrendered.contains("big.txt"));
6085
6086
    // Discarding works the same way.
6087
    write(root, "a.txt", b"scratch\n");
6088
    assert_eq!(repo.discard(&["a.txt".into()]).unwrap(), 1);
6089
    assert_eq!(fs::read(root.join("a.txt")).unwrap(), b"one\nTWO\nthree\n");
6090
    fs::set_permissions(root.join("big.txt"), fs::Permissions::from_mode(0o644)).unwrap();
6091
}
6092
6093
/// A replace conflict (spec §9.3) is settled by a change that writes one
6094
/// candidate, or new bytes, at the path when the caller names it; a plain
6095
/// snapshot of a checkout never settles it on its own.
6096
#[test]
6097
fn replace_conflicts_are_settled_when_asked() {
6098
    hermetic();
6099
    let dir = tempfile::tempdir().unwrap();
6100
    let root = dir.path();
6101
    let mut repo = Repo::init(root).unwrap().with_home(root.join("home"));
6102
    let blob = |n: u8| {
6103
        let mut v = vec![0u8; 64];
6104
        v[1] = n;
6105
        v
6106
    };
6107
    write(root, "img.bin", &blob(1));
6108
    repo.commit("add img", &[]).unwrap();
6109
    repo.bookmark_create("other", None).unwrap();
6110
    write(root, "img.bin", &blob(2));
6111
    repo.commit("img two", &[]).unwrap();
6112
    repo.bookmark_switch("other", false).unwrap();
6113
    write(root, "img.bin", &blob(3));
6114
    repo.commit("img three", &[]).unwrap();
6115
    repo.bookmark_switch("main", false).unwrap();
6116
    repo.merge("other").unwrap();
6117
    let heads = repo.bookmark_heads().unwrap();
6118
    let merged = repo.load_state(&heads).unwrap().materialize();
6119
    assert!(
6120
        matches!(&merged.files["img.bin"].content, FileContent::Opaque { blobs } if blobs.len() == 2),
6121
        "a replace conflict"
6122
    );
6123
    // A snapshot of the checkout records nothing.
6124
    assert!(repo
6125
        .snapshot("status")
6126
        .unwrap()
6127
        .statuses
6128
        .iter()
6129
        .all(|s| s.path != "img.bin"));
6130
6131
    // Keeping candidate 3 settles it.
6132
    let author = repo.author();
6133
    let edits = [FileEdit {
6134
        path: "img.bin".into(),
6135
        content: Some(blob(3)),
6136
    }];
6137
    let c = repo
6138
        .build_change(&heads, &edits, "keep three", author)
6139
        .unwrap();
6140
    assert_eq!(c.kind, ChangeKind::Resolution);
6141
    let mut st = repo.load_state(&heads).unwrap();
6142
    for d in &c.deps {
6143
        assert!(st.contains(d));
6144
    }
6145
    assert!(
6146
        heads.iter().all(|h| c.deps.contains(h)),
6147
        "depends on both contributors"
6148
    );
6149
    st.add(c).unwrap();
6150
    let after = st.materialize();
6151
    assert!(!after.is_conflicted());
6152
    assert_eq!(
6153
        after.files["img.bin"].content,
6154
        FileContent::Opaque {
6155
            blobs: vec![Repo::blob_ref(&blob(3))]
6156
        }
6157
    );
6158
6159
    // New bytes settle it too.
6160
    let edits = [FileEdit {
6161
        path: "img.bin".into(),
6162
        content: Some(blob(9)),
6163
    }];
6164
    let c = repo.build_change(&heads, &edits, "new", author).unwrap();
6165
    let mut st = repo.load_state(&heads).unwrap();
6166
    st.add(c).unwrap();
6167
    assert_eq!(
6168
        st.materialize().files["img.bin"].content,
6169
        FileContent::Opaque {
6170
            blobs: vec![Repo::blob_ref(&blob(9))]
6171
        }
6172
    );
6173
}
6174
6175
/// The history of a range of lines (spec §27): the changes that wrote
6176
/// or deleted its atoms, or deleted atoms from between them; edits outside
6177
/// the range and changes the range's lines survived are not in it.
6178
#[test]
6179
fn line_ranges_have_exact_histories() {
6180
    hermetic();
6181
    let dir = tempfile::tempdir().unwrap();
6182
    let root = dir.path();
6183
    let repo = Repo::init(root).unwrap().with_home(root.join("home"));
6184
    write(root, "f.rs", b"use x;\nfn a() {\n  one();\n  two();\n}\n");
6185
    let base = repo.commit("add f", &[]).unwrap();
6186
    write(root, "f.rs", b"use y;\nfn a() {\n  one();\n  two();\n}\n");
6187
    let outside = repo.commit("change the import", &[]).unwrap();
6188
    write(root, "f.rs", b"use y;\nfn a() {\n  ONE();\n  two();\n}\n");
6189
    let inside = repo.commit("edit a line of a", &[]).unwrap();
6190
    write(root, "f.rs", b"use y;\nfn a() {\n  ONE();\n}\n");
6191
    let deleted = repo.commit("delete a line of a", &[]).unwrap();
6192
    write(root, "f.rs", b"use y;\nfn a() {\n  ONE();\n}\nfn b() {}\n");
6193
    let after = repo.commit("add b after a", &[]).unwrap();
6194
    let heads = repo.bookmark_heads().unwrap();
6195
6196
    // Lines 2..4 are `fn a() {`, `ONE();`, `}` now.
6197
    let hist: Vec<ChangeHash> = repo
6198
        .line_history(&heads, "f.rs", 2, 4)
6199
        .unwrap()
6200
        .iter()
6201
        .map(|e| e.hash)
6202
        .collect();
6203
    for (h, what) in [
6204
        (base, "wrote it"),
6205
        (inside, "edited a line"),
6206
        (deleted, "deleted a line from inside"),
6207
    ] {
6208
        assert!(hist.contains(&h), "{what}");
6209
    }
6210
    for (h, what) in [(outside, "an edit above"), (after, "an addition below")] {
6211
        assert!(!hist.contains(&h), "{what}");
6212
    }
6213
    assert_eq!(hist[0], deleted, "newest first");
6214
    // One line: only what touched it.
6215
    let one: Vec<ChangeHash> = repo
6216
        .line_history(&heads, "f.rs", 1, 1)
6217
        .unwrap()
6218
        .iter()
6219
        .map(|e| e.hash)
6220
        .collect();
6221
    assert!(one.contains(&outside) && !one.contains(&inside));
6222
    assert!(repo.line_history(&heads, "f.rs", 3, 9).is_err());
6223
    assert!(repo.line_history(&heads, "f.rs", 0, 1).is_err());
6224
    assert!(repo.line_history(&heads, "nope.rs", 1, 1).is_err());
6225
}
6226
6227
#[test]
6228
fn receipts_are_kept_with_their_state_and_verified() {
6229
    use crate::receipt::{Receipt, SignedReceipt};
6230
    hermetic();
6231
    let dir = tempfile::tempdir().unwrap();
6232
    let root = dir.path();
6233
    let repo = Repo::init(root).unwrap().with_home(root.join("home"));
6234
    write(root, "a.txt", b"1\n");
6235
    repo.commit("A", &[]).unwrap();
6236
    let heads = repo.bookmark_heads().unwrap();
6237
    let state = repo
6238
        .store()
6239
        .put_state(&StateObject::new(heads.clone()))
6240
        .unwrap();
6241
    let out = repo.store_blob(b"built\n").unwrap();
6242
    let receipt = Receipt {
6243
        job_name: "build".into(),
6244
        pipeline_hash: ObjectRef([1; 32]),
6245
        scope_tree_hash: ObjectRef([2; 32]),
6246
        inputs: vec![],
6247
        environment: ObjectRef([3; 32]),
6248
        outputs: vec![out],
6249
        exit_code: 0,
6250
        duration_ms: 42,
6251
    };
6252
    let sk = SecretKey::generate();
6253
    let runner = sk.identity("earth-1", "runner@earth", 1);
6254
    let sr = SignedReceipt::sign(
6255
        receipt.clone(),
6256
        repo.id().unwrap(),
6257
        state,
6258
        "demo#1",
6259
        &runner,
6260
        &sk,
6261
    );
6262
6263
    let r = repo.add_receipt(&sr).unwrap();
6264
    let found = repo.receipts(&heads).unwrap();
6265
    assert_eq!(found.len(), 1);
6266
    assert_eq!(found[0].attest, r);
6267
    assert_eq!(found[0].signed, sr);
6268
    assert!(found[0].problem.is_none() && !found[0].revoked);
6269
    assert!(repo.receipts(&[ObjectRef([5; 32])]).unwrap().is_empty());
6270
6271
    // Another repository's receipt, or a forged one, is refused.
6272
    let elsewhere = SignedReceipt::sign(receipt.clone(), [0; 16], state, "x", &runner, &sk);
6273
    assert!(repo
6274
        .add_receipt(&elsewhere)
6275
        .unwrap_err()
6276
        .to_string()
6277
        .contains("another repository"));
6278
    let mut forged = sr.clone();
6279
    forged.receipt.exit_code = 1;
6280
    assert!(repo
6281
        .add_receipt(&forged)
6282
        .unwrap_err()
6283
        .to_string()
6284
        .contains("does not verify"));
6285
6286
    // A receipt signed by a short-lived key keeps its certificate and the
6287
    // issuer's identity, and reads back with them (oxygenhub#241).
6288
    let hub_sk = SecretKey::generate();
6289
    let hub = hub_sk.identity("oxygenhub.io", "[email protected]", 1);
6290
    let job_sk = SecretKey::generate();
6291
    let job = job_sk.identity("job 2 test", "[email protected]", 1);
6292
    let mut test_receipt = receipt.clone();
6293
    test_receipt.job_name = "test".into();
6294
    let plain = SignedReceipt::sign(
6295
        test_receipt,
6296
        repo.id().unwrap(),
6297
        state,
6298
        "demo#2",
6299
        &job,
6300
        &job_sk,
6301
    );
6302
    let now = plain.attest.hlc.wall_ms;
6303
    let cert = crate::cert::SignedCertificate::sign(
6304
        crate::cert::Certificate {
6305
            key: job.clone(),
6306
            issuer: hub.hash(),
6307
            subject: "repo:andy/demo:bookmark:main".into(),
6308
            claims: vec![],
6309
            scope: crate::identity::Scope::SEAL,
6310
            not_before: now - 1_000,
6311
            expires: now + 600_000,
6312
            grant: None,
6313
        },
6314
        &hub,
6315
        &hub_sk,
6316
    );
6317
    let certified = plain.with_certificate(cert, hub.clone());
6318
    repo.add_receipt(&certified).unwrap();
6319
    let found = repo.receipts(&heads).unwrap();
6320
    let got = found
6321
        .iter()
6322
        .find(|i| i.signed.receipt.job_name == "test")
6323
        .unwrap();
6324
    assert_eq!(got.signed, certified);
6325
    assert!(got.problem.is_none(), "{:?}", got.problem);
6326
6327
    // gc keeps the receipts, their runners, the certificate and its issuer,
6328
    // and the output while the state lives.
6329
    repo.gc(true).unwrap();
6330
    let found = repo.receipts(&heads).unwrap();
6331
    assert_eq!(found.len(), 2);
6332
    let got = found
6333
        .iter()
6334
        .find(|i| i.signed.receipt.job_name == "test")
6335
        .unwrap();
6336
    assert_eq!(got.signed, certified, "the certificate survives gc");
6337
    assert!(got.problem.is_none());
6338
    assert_eq!(repo.read_blob(&out).unwrap(), b"built\n");
6339
    assert!(repo.fsck().unwrap().problems.is_empty());
6340
}
6341
6342
#[test]
6343
fn approvals_are_kept_with_their_state_and_survive_gc() {
6344
    hermetic();
6345
    let dir = tempfile::tempdir().unwrap();
6346
    let root = dir.path();
6347
    let repo = Repo::init(root).unwrap().with_home(root.join("home"));
6348
    write(root, "a.txt", b"1\n");
6349
    repo.commit("A", &[]).unwrap();
6350
    let heads = repo.bookmark_heads().unwrap();
6351
    let state = repo.store().put_state(&StateObject::new(heads)).unwrap();
6352
    let plan = repo.store_blob(b"the reviewed plan\n").unwrap();
6353
    let sk = SecretKey::generate();
6354
    let andy = sk.identity("Andy", "[email protected]", 1);
6355
    let statement = crate::approval::Statement {
6356
        repo: repo.id().unwrap(),
6357
        run: "https://hub.example/andy/infra/flow/8".into(),
6358
        job: "apply".into(),
6359
        job_hash: ObjectRef([1; 32]),
6360
        state,
6361
        inputs: vec![plan],
6362
        environment: "prod".into(),
6363
        approve: true,
6364
    };
6365
    let sa = crate::approval::SignedApproval::sign(&statement, &andy, &sk);
6366
    let r = repo.add_approval(&sa).unwrap();
6367
    assert_eq!(repo.store().approvals_for(&state).unwrap(), vec![r]);
6368
    // Another repository's approval, or a changed one, is refused.
6369
    let elsewhere = crate::approval::SignedApproval::sign(
6370
        &crate::approval::Statement {
6371
            repo: [0; 16],
6372
            ..statement.clone()
6373
        },
6374
        &andy,
6375
        &sk,
6376
    );
6377
    assert!(repo
6378
        .add_approval(&elsewhere)
6379
        .unwrap_err()
6380
        .to_string()
6381
        .contains("another repository"));
6382
    let mut forged = sa.clone();
6383
    if let AttestBody::Approval { environment, .. } = &mut forged.attest.body {
6384
        *environment = "dev".into();
6385
    }
6386
    assert!(repo
6387
        .add_approval(&forged)
6388
        .unwrap_err()
6389
        .to_string()
6390
        .contains("does not verify"));
6391
    // gc keeps it, its signature and its signer while the state lives.
6392
    repo.gc(true).unwrap();
6393
    assert_eq!(repo.store().approvals_for(&state).unwrap(), vec![r]);
6394
    assert_eq!(repo.store().get_attest(&r).unwrap(), sa.attest);
6395
    assert_eq!(repo.store().signatures(&r).unwrap(), sa.sigs);
6396
    assert!(repo.fsck().unwrap().problems.is_empty());
6397
}
6398
6399
#[test]
6400
fn status_leaves_an_unchanged_manifest_alone() {
6401
    hermetic();
6402
    let dir = tempfile::tempdir().unwrap();
6403
    let root = dir.path();
6404
    let repo = Repo::init(root).unwrap().with_home(root.join("home"));
6405
    write(root, "a.txt", b"1\n");
6406
    write(root, "b.txt", b"2\n");
6407
    repo.commit("A", &[]).unwrap();
6408
    // Files last touched well outside the racy window.
6409
    let old = std::time::SystemTime::now() - std::time::Duration::from_secs(60);
6410
    for f in ["a.txt", "b.txt"] {
6411
        fs::File::options()
6412
            .write(true)
6413
            .open(root.join(f))
6414
            .unwrap()
6415
            .set_modified(old)
6416
            .unwrap();
6417
    }
6418
    repo.snapshot_status("status").unwrap();
6419
    let path = repo.manifest_path();
6420
    let first = fs::read(&path).unwrap();
6421
    repo.snapshot_status("status").unwrap();
6422
    assert_eq!(
6423
        fs::read(&path).unwrap(),
6424
        first,
6425
        "an unchanged tree does not rewrite the manifest"
6426
    );
6427
    // A change rewrites it.
6428
    write(root, "a.txt", b"1\n2\n");
6429
    repo.snapshot_status("status").unwrap();
6430
    assert_ne!(fs::read(&path).unwrap(), first);
6431
}
6432
6433
#[test]
6434
fn large_text_files_travel_and_survive_gc_as_text_blobs() {
6435
    hermetic();
6436
    let dir = tempfile::tempdir().unwrap();
6437
    let root = dir.path();
6438
    let origin_path = root.join("origin");
6439
    Repo::init(&origin_path).unwrap();
6440
    let origin_url = origin_path.to_string_lossy().to_string();
6441
    let a = Repo::clone(&origin_url, &root.join("a")).unwrap();
6442
    let big: String = (0..5000).map(|i| format!("line {i}\n")).collect();
6443
    write(&root.join("a"), "big.txt", big.as_bytes());
6444
    write(&root.join("a"), "small.txt", b"small\n");
6445
    let h1 = a.commit("large", &[]).unwrap();
6446
    let (_, body) = a.store().get(&h1).unwrap();
6447
    assert!(body.len() < 2048, "the change is {} bytes", body.len());
6448
    assert!(a.push("origin", false).unwrap()[0].ok);
6449
6450
    // A clone reads the text from the blobs that came with the change.
6451
    let b = Repo::clone(&origin_url, &root.join("b")).unwrap();
6452
    assert_eq!(fs::read(root.join("b/big.txt")).unwrap(), big.as_bytes());
6453
    // An edit in the middle of the stored insert is an ordinary change.
6454
    let edited = big.replace("line 2500\n", "line 2500, edited\n");
6455
    write(&root.join("b"), "big.txt", edited.as_bytes());
6456
    let h2 = b.commit("edit", &[]).unwrap();
6457
    assert!(b.store().get_change(&h2).unwrap().edits.len() <= 2);
6458
    assert!(b.push("origin", false).unwrap()[0].ok);
6459
    assert!(a.pull("origin").unwrap().checked_out);
6460
    assert_eq!(fs::read(root.join("a/big.txt")).unwrap(), edited.as_bytes());
6461
    assert_eq!(
6462
        a.fsck().unwrap().errors(),
6463
        0,
6464
        "{:?}",
6465
        a.fsck().unwrap().problems
6466
    );
6467
6468
    // With zero retention gc keeps the text blobs of every kept change.
6469
    let mut a = Repo::open(&root.join("a")).unwrap();
6470
    a.config.set("core.op-retention", "0").unwrap();
6471
    a.save_config().unwrap();
6472
    let a = Repo::open(&root.join("a")).unwrap();
6473
    a.gc(true).unwrap();
6474
    let a = Repo::open(&root.join("a")).unwrap();
6475
    assert_eq!(a.store().get_change(&h1).unwrap().message, "large");
6476
    assert_eq!(
6477
        a.fsck().unwrap().errors(),
6478
        0,
6479
        "{:?}",
6480
        a.fsck().unwrap().problems
6481
    );
6482
    // And a clone of the packed repository reads them from its packs.
6483
    let c = Repo::clone(&root.join("a").to_string_lossy(), &root.join("c")).unwrap();
6484
    assert_eq!(fs::read(root.join("c/big.txt")).unwrap(), edited.as_bytes());
6485
    drop(c);
6486
}
6487
6488
#[test]
6489
fn operations_that_both_replace_a_working_copy_are_not_merged() {
6490
    hermetic();
6491
    let dir = tempfile::tempdir().unwrap();
6492
    let root = dir.path();
6493
    let repo = Repo::init(root).unwrap();
6494
    write(root, "a.txt", b"a\n");
6495
    let a = repo.commit("a", &[]).unwrap();
6496
    write(root, "b.txt", b"b\n");
6497
    repo.commit("b", &[]).unwrap();
6498
    let (x, op) = repo.head_op().unwrap();
6499
    let ws = *op.view.workspaces.keys().next().unwrap();
6500
    let mut one = op.view.clone();
6501
    one.workspaces.insert(ws, a);
6502
    let mut two = op.view.clone();
6503
    two.workspaces.insert(ws, ObjectRef([7; 32]));
6504
    let first = repo.record_op(&[x], "one", one).unwrap();
6505
    let e = repo.record_op(&[x], "two", two).unwrap_err();
6506
    assert!(
6507
        e.to_string()
6508
            .contains("changed this working copy at the same time"),
6509
        "{e}"
6510
    );
6511
    assert_eq!(
6512
        repo.head_op().unwrap().0,
6513
        first,
6514
        "the second is not recorded"
6515
    );
6516
}
6517
6518
/// Metalgear, 2026-09-29 (oxygen#36): a status run while a bookmark switch
6519
/// rewrote the working copy recorded the half-written files as edits, and
6520
/// its view replaced the switch's.
6521
#[test]
6522
fn a_snapshot_during_a_switch_never_records_the_switch_as_edits() {
6523
    hermetic();
6524
    let dir = tempfile::tempdir().unwrap();
6525
    let root = dir.path().to_path_buf();
6526
    let mut repo = Repo::init(&root).unwrap();
6527
    write(&root, "keep.txt", b"keep\n");
6528
    repo.commit("base", &[]).unwrap();
6529
    repo.bookmark_create("small", None).unwrap();
6530
    for i in 0..300 {
6531
        write(
6532
            &root,
6533
            &format!("many/f{i}.txt"),
6534
            format!("file {i}\n").as_bytes(),
6535
        );
6536
    }
6537
    repo.commit("many", &[]).unwrap();
6538
    let stop = std::sync::Arc::new(std::sync::atomic::AtomicBool::new(false));
6539
    let watcher = {
6540
        let (root, stop) = (root.clone(), stop.clone());
6541
        std::thread::spawn(move || {
6542
            let r = Repo::open(&root).unwrap();
6543
            let mut ran = 0;
6544
            while !stop.load(std::sync::atomic::Ordering::Relaxed) {
6545
                if r.snapshot_status("oxy status").is_ok() {
6546
                    ran += 1;
6547
                }
6548
            }
6549
            ran
6550
        })
6551
    };
6552
    for i in 0..20 {
6553
        let to = if i % 2 == 0 { "small" } else { "main" };
6554
        repo.bookmark_switch(to, false).unwrap();
6555
    }
6556
    stop.store(true, std::sync::atomic::Ordering::Relaxed);
6557
    assert!(watcher.join().unwrap() > 0, "the watcher snapshotted");
6558
    // Back on main, clean, with every file where main has it.
6559
    let repo = Repo::open(&root).unwrap();
6560
    let s = repo.snapshot_status("oxy status").unwrap();
6561
    assert!(s.statuses.is_empty(), "{:?}", statuses(&s));
6562
    assert!(s.wc.edits.is_empty() && s.wc.tree_ops.is_empty());
6563
    assert_eq!(s.wc.deps, repo.bookmark_heads().unwrap());
6564
    assert!(root.join("many/f299.txt").exists());
6565
}
6566
6567
/// Metalgear, 2026-09-29 (oxygen#38): a parent's `bookmark switch --carry`
6568
/// put a subrepo that was ahead of its pin back at the pin and moved the
6569
/// subrepo's own bookmark backwards.
6570
#[test]
6571
fn a_parent_switch_with_carry_leaves_a_subrepo_ahead_of_its_pin_alone() {
6572
    hermetic();
6573
    let dir = tempfile::tempdir().unwrap();
6574
    let root = dir.path();
6575
    Repo::init(&root.join("lib-origin")).unwrap();
6576
    let lib_url = root.join("lib-origin").to_string_lossy().to_string();
6577
    let lib = Repo::clone(&lib_url, &root.join("lib")).unwrap();
6578
    write(&root.join("lib"), "lib.txt", b"v1\n");
6579
    lib.commit("lib v1", &[]).unwrap();
6580
    assert!(lib.push("origin", false).unwrap()[0].ok);
6581
6582
    let app_dir = root.join("app");
6583
    let mut app = Repo::init(&app_dir).unwrap();
6584
    write(&app_dir, "main.txt", b"app\n");
6585
    app.submodule_add(&lib_url, "libs/lib", None).unwrap();
6586
    app.commit("app with lib", &[]).unwrap();
6587
    app.bookmark_create("feature", None).unwrap();
6588
6589
    // New work in the subrepo, not yet pinned by the parent.
6590
    let nested_dir = app_dir.join("libs/lib");
6591
    let nested = Repo::open(&nested_dir).unwrap();
6592
    write(&nested_dir, "new.txt", b"new\n");
6593
    let l2 = nested.commit("lib: new file", &[]).unwrap();
6594
    drop(nested);
6595
6596
    let (_, carried) = app.bookmark_switch_carry("feature").unwrap();
6597
    assert!(carried.contains(&"libs/lib".to_string()), "{carried:?}");
6598
    let nested = Repo::open(&nested_dir).unwrap();
6599
    assert!(
6600
        nested.bookmark_heads().unwrap().contains(&l2),
6601
        "its bookmark kept its work"
6602
    );
6603
    assert!(nested_dir.join("new.txt").exists(), "and its files");
6604
    let s = app.snapshot("status").unwrap();
6605
    assert_eq!(
6606
        statuses(&s),
6607
        vec![("libs/lib".to_string(), ChangeStatus::Modified)]
6608
    );
6609
}
6610
6611
/// oxygen#29 (metalgear, rstar-api): after a proposal landed on the hub,
6612
/// moving `main` to a change this clone had pushed on another bookmark,
6613
/// the first `pull` said "Already up to date" while `main` was behind.
6614
#[test]
6615
fn pull_takes_a_remote_move_to_changes_already_here() {
6616
    hermetic();
6617
    let dir = tempfile::tempdir().unwrap();
6618
    let root = dir.path();
6619
    let origin_path = root.join("origin");
6620
    let origin = Repo::init(&origin_path).unwrap();
6621
    let url = origin_path.to_string_lossy().to_string();
6622
    let mut b = Repo::clone(&url, &root.join("b")).unwrap();
6623
    write(&root.join("b"), "base.txt", b"base\n");
6624
    b.commit("base", &[]).unwrap();
6625
    assert!(b.push("origin", false).unwrap()[0].ok);
6626
    origin.refresh().unwrap();
6627
6628
    // A feature bookmark with one change, pushed.
6629
    b.bookmark_create("feat", None).unwrap();
6630
    b.bookmark_switch("feat", false).unwrap();
6631
    write(&root.join("b"), "x.txt", b"x\n");
6632
    let x = b.commit("x", &[]).unwrap();
6633
    assert!(b.push("origin", false).unwrap()[0].ok);
6634
    origin.refresh().unwrap();
6635
    b.bookmark_switch("main", false).unwrap();
6636
6637
    // The remote lands it: its main moves to the feature's state.
6638
    let feat = origin
6639
        .store()
6640
        .get_state(&origin.view().unwrap().bookmarks["feat"])
6641
        .unwrap()
6642
        .heads;
6643
    origin.bookmark_set("main", &feat).unwrap();
6644
6645
    let r = b.pull("origin").unwrap();
6646
    assert!(r.changed, "{r:?}");
6647
    assert!(r.heads.contains(&x) || b.load_state(&r.heads).unwrap().contains(&x));
6648
    let main = b
6649
        .bookmarks()
6650
        .unwrap()
6651
        .into_iter()
6652
        .find(|m| m.name == "main")
6653
        .unwrap();
6654
    assert_eq!(main.behind, Some(0), "{main:?}");
6655
}
6656
6657
/// oxygen#48: a remote's bookmarks are names here (`origin/NAME`); switching
6658
/// to one only the remote has makes a local bookmark from it; a pull moves
6659
/// every local bookmark the remote has too; a clone checks out the remote's
6660
/// default bookmark.
6661
#[test]
6662
fn remote_bookmarks_are_named_switched_to_pulled_and_cloned() {
6663
    hermetic();
6664
    let dir = tempfile::tempdir().unwrap();
6665
    let root = dir.path();
6666
    let origin_path = root.join("origin");
6667
    let mut origin = Repo::init(&origin_path).unwrap();
6668
    let url = origin_path.to_string_lossy().to_string();
6669
    let mut a = Repo::clone(&url, &root.join("a")).unwrap();
6670
    write(&root.join("a"), "base.txt", b"base\n");
6671
    a.commit("base", &[]).unwrap();
6672
    assert!(a.push("origin", false).unwrap()[0].ok);
6673
    a.bookmark_create("develop", None).unwrap();
6674
    a.bookmark_switch("develop", false).unwrap();
6675
    write(&root.join("a"), "base.txt", b"base\nd1\n");
6676
    let d1 = a.commit("d1", &[]).unwrap();
6677
    assert!(a.push("origin", false).unwrap()[0].ok);
6678
6679
    // A clone has main only; origin/develop is a name all the same.
6680
    let c_root = root.join("c");
6681
    let mut c = Repo::clone(&url, &c_root).unwrap();
6682
    assert_eq!(c.config.bookmark, "main");
6683
    assert!(!c.view().unwrap().bookmarks.contains_key("develop"));
6684
    assert_eq!(c.resolve_heads("origin/develop").unwrap(), vec![d1]);
6685
    assert_eq!(c.resolve_change("origin/develop").unwrap(), d1);
6686
    assert_eq!(c.remote_only_bookmarks().unwrap().len(), 1);
6687
6688
    // Switching makes the local bookmark from origin's.
6689
    c.bookmark_switch("develop", false).unwrap();
6690
    assert_eq!(c.config.bookmark, "develop");
6691
    assert_eq!(c.bookmark_heads().unwrap(), vec![d1]);
6692
    assert_eq!(fs::read(c_root.join("base.txt")).unwrap(), b"base\nd1\n");
6693
    assert!(c.remote_only_bookmarks().unwrap().is_empty());
6694
    assert!(c.bookmark_switch("nowhere", false).is_err());
6695
6696
    // Both bookmarks move on the remote; one pull takes both.
6697
    write(&root.join("a"), "base.txt", b"base\nd1\nd2\n");
6698
    let d2 = a.commit("d2", &[]).unwrap();
6699
    assert!(a.push("origin", false).unwrap()[0].ok);
6700
    a.bookmark_switch("main", false).unwrap();
6701
    write(&root.join("a"), "m.txt", b"m\n");
6702
    let m = a.commit("m", &[]).unwrap();
6703
    assert!(a.push("origin", false).unwrap()[0].ok);
6704
    // oxygen#117: a remote's bookmark merges without switching to it.
6705
    let f = Repo::clone(&url, &root.join("f")).unwrap();
6706
    assert!(!f.view().unwrap().bookmarks.contains_key("develop"));
6707
    let merged = f.merge("origin/develop").unwrap();
6708
    assert!(merged.changed, "{merged:?}");
6709
    assert!(
6710
        f.load_state_indexed(&f.bookmark_heads().unwrap())
6711
            .unwrap()
6712
            .contains(&d1),
6713
        "main holds develop's change"
6714
    );
6715
    assert!(f
6716
        .merge("origin/nowhere")
6717
        .unwrap_err()
6718
        .to_string()
6719
        .contains("no bookmark origin/nowhere"));
6720
    let r = c.pull("origin").unwrap();
6721
    assert!(r.changed && r.checked_out, "{r:?}");
6722
    assert_eq!(r.heads, vec![d2]);
6723
    assert_eq!(r.others, vec!["main".to_string()]);
6724
    assert!(c.resolve_heads("main").unwrap().contains(&m));
6725
    assert_eq!(
6726
        fs::read(c_root.join("base.txt")).unwrap(),
6727
        b"base\nd1\nd2\n"
6728
    );
6729
    let again = c.pull("origin").unwrap();
6730
    assert!(!again.changed && again.others.is_empty(), "{again:?}");
6731
6732
    // A clone checks out the remote's default bookmark.
6733
    origin.config.set("workspace.bookmark", "develop").unwrap();
6734
    origin.save_config().unwrap();
6735
    let e = Repo::clone(&url, &root.join("e")).unwrap();
6736
    assert_eq!(e.config.bookmark, "develop");
6737
    assert_eq!(e.bookmark_heads().unwrap(), vec![d2]);
6738
    let reopened = Repo::open(&root.join("e")).unwrap();
6739
    assert_eq!(reopened.config.bookmark, "develop");
6740
    // REMOTE/NAME names the remote's bookmark to switch to.
6741
    let mut e = reopened;
6742
    e.bookmark_switch("origin/main", false).unwrap();
6743
    assert_eq!(e.config.bookmark, "main");
6744
    assert!(e.bookmark_heads().unwrap().contains(&m));
6745
}
6746
6747
/// oxygen#51, #52: --at-op reads an earlier view and refuses changes;
6748
/// op restore goes back to an operation, files included, and undo takes
6749
/// the restore back whole; op revert undoes one operation alone; each
6750
/// operation's changes are described from the views.
6751
#[test]
6752
fn operations_can_be_read_restored_and_reverted() {
6753
    hermetic();
6754
    let dir = tempfile::tempdir().unwrap();
6755
    let root = dir.path();
6756
    let repo = Repo::init(root).unwrap();
6757
    write(root, "a.txt", b"a\n");
6758
    let first = repo.commit("first", &[]).unwrap();
6759
    write(root, "a.txt", b"a\nb\n");
6760
    let second = repo.commit("second", &[]).unwrap();
6761
    let at_second = repo.head_op().unwrap().0.to_hex();
6762
    repo.bookmark_create("keep", None).unwrap();
6763
    let created = repo.head_op().unwrap().0.to_hex();
6764
    write(root, "n.txt", b"n\n");
6765
    let third = repo.commit("third", &[]).unwrap();
6766
6767
    // What each operation changed.
6768
    let ops = repo.op_log().unwrap();
6769
    let changes = repo.view_changes(&ops[1].1.view, &ops[0].1.view).unwrap();
6770
    assert!(
6771
        changes
6772
            .iter()
6773
            .any(|c| matches!(c, ViewChange::BookmarkMoved { name, .. } if name == "main")),
6774
        "{changes:?}"
6775
    );
6776
    assert!(changes
6777
        .iter()
6778
        .any(|c| matches!(c, ViewChange::WorkingCopy { .. })));
6779
6780
    // Reading at an earlier operation.
6781
    let old = Repo::open(root).unwrap().at_op(&at_second[..10]).unwrap();
6782
    assert_eq!(old.bookmark_heads().unwrap(), vec![second]);
6783
    assert!(!old.view().unwrap().bookmarks.contains_key("keep"));
6784
    write(root, "z.txt", b"z\n");
6785
    assert!(old.commit("refused", &[]).is_err(), "--at-op is read-only");
6786
    fs::remove_file(root.join("z.txt")).unwrap();
6787
    assert!(repo.resolve_op("zz").is_err());
6788
    assert_eq!(repo.resolve_op("@").unwrap().0, repo.head_op().unwrap().0);
6789
6790
    // Restore goes back, files and all; undo takes it back whole.
6791
    repo.op_restore(&at_second, false).unwrap();
6792
    assert_eq!(repo.bookmark_heads().unwrap(), vec![second]);
6793
    assert!(!root.join("n.txt").exists());
6794
    repo.undo().unwrap();
6795
    let mut heads = repo.bookmark_heads().unwrap();
6796
    heads.sort();
6797
    let mut want = vec![second, third];
6798
    want.sort();
6799
    assert_eq!(heads, want);
6800
    assert!(
6801
        root.join("n.txt").exists(),
6802
        "the files came back with the undo"
6803
    );
6804
6805
    // Revert the bookmark's creation alone: the commit after it stays.
6806
    let r = repo.op_revert(&created).unwrap();
6807
    assert_eq!(r.reverted, vec!["keep".to_string()]);
6808
    assert!(!repo.view().unwrap().bookmarks.contains_key("keep"));
6809
    assert!(repo
6810
        .load_state(&repo.bookmark_heads().unwrap())
6811
        .unwrap()
6812
        .contains(&third));
6813
    assert!(repo.op_revert(&created).is_err(), "nothing left to revert");
6814
    let _ = first;
6815
}
6816
6817
/// oxygen#41: with uncommitted work, a status after a snapshot is answered
6818
/// from the status cache while every file is as the snapshot left it, and
6819
/// from a snapshot again as soon as one is not.
6820
#[test]
6821
fn status_with_uncommitted_work_comes_from_the_cache_until_a_file_changes() {
6822
    hermetic();
6823
    let dir = tempfile::tempdir().unwrap();
6824
    let root = dir.path();
6825
    let repo = Repo::init(root).unwrap();
6826
    write(root, "a.txt", b"a\n");
6827
    write(root, "b.txt", b"b\n");
6828
    repo.commit("base", &[]).unwrap();
6829
    assert_eq!(repo.status_by_manifest().unwrap(), Some(vec![]), "clean");
6830
6831
    write(root, "a.txt", b"a\nmore\n");
6832
    assert_eq!(
6833
        repo.status_by_manifest().unwrap(),
6834
        None,
6835
        "no snapshot of the edit yet"
6836
    );
6837
    let snap = repo.snapshot_status("oxy status").unwrap();
6838
    assert_eq!(snap.statuses.len(), 1);
6839
    let cached = repo
6840
        .status_by_manifest()
6841
        .unwrap()
6842
        .expect("answered from the cache");
6843
    assert_eq!(cached.len(), 1);
6844
    assert_eq!(
6845
        (cached[0].path.as_str(), cached[0].status),
6846
        ("a.txt", ChangeStatus::Modified)
6847
    );
6848
6849
    // Any further change sends status back to a snapshot.
6850
    write(root, "a.txt", b"a\nmore\nand more\n");
6851
    assert_eq!(repo.status_by_manifest().unwrap(), None, "edited again");
6852
    repo.snapshot_status("oxy status").unwrap();
6853
    assert!(repo.status_by_manifest().unwrap().is_some());
6854
    write(root, "new.txt", b"n\n");
6855
    assert_eq!(repo.status_by_manifest().unwrap(), None, "a file added");
6856
    fs::remove_file(root.join("new.txt")).unwrap();
6857
    assert!(
6858
        repo.status_by_manifest().unwrap().is_some(),
6859
        "back as it was"
6860
    );
6861
    fs::remove_file(root.join("b.txt")).unwrap();
6862
    assert_eq!(repo.status_by_manifest().unwrap(), None, "a file removed");
6863
    write(root, "b.txt", b"b\n");
6864
6865
    // A commit leaves nothing uncommitted: clean again, no cache needed.
6866
    repo.snapshot_status("oxy status").unwrap();
6867
    repo.commit("more", &[]).unwrap();
6868
    assert_eq!(repo.status_by_manifest().unwrap(), Some(vec![]));
6869
}
6870
6871
/// oxygen#41: while the status cache holds, the working copy's diff is
6872
/// rendered from the stored working-copy change, and says exactly what a
6873
/// snapshot's diff says.
6874
#[test]
6875
fn the_working_copy_diff_from_the_cache_matches_a_snapshot() {
6876
    hermetic();
6877
    let dir = tempfile::tempdir().unwrap();
6878
    let root = dir.path();
6879
    let repo = Repo::init(root).unwrap();
6880
    write(root, "a.txt", b"one\ntwo\nthree\n");
6881
    write(root, "gone.txt", b"bye\n");
6882
    repo.commit("base", &[]).unwrap();
6883
    write(root, "a.txt", b"one\n2\nthree\nfour\n");
6884
    write(root, "new.txt", b"hello\n");
6885
    fs::remove_file(root.join("gone.txt")).unwrap();
6886
    let snap = repo.snapshot_status("oxy status").unwrap();
6887
    let slow = render_change(&snap.wc, &snap.base, &snap.base_snapshot);
6888
    assert!(
6889
        repo.status_by_manifest().unwrap().is_some(),
6890
        "the cache holds"
6891
    );
6892
    let (wc, base, snapshot) = repo.working_copy_with_base().unwrap();
6893
    assert_eq!(render_change(&wc, &base, &snapshot), slow);
6894
    assert_eq!(repo.diff_files(None).unwrap().len(), 3);
6895
6896
    // Committed, nothing changes: the diff is empty without loading the
6897
    // base (oxygen#94), and the same as rendering it.
6898
    repo.commit("all", &[]).unwrap();
6899
    repo.snapshot_status("oxy status").unwrap();
6900
    assert!(repo.status_by_manifest().unwrap().is_some());
6901
    assert!(repo
6902
        .working_copy_with_base_unless_unchanged()
6903
        .unwrap()
6904
        .is_none());
6905
    let (wc, base, snapshot) = repo.working_copy_with_base().unwrap();
6906
    assert_eq!(render_change(&wc, &base, &snapshot), "");
6907
    assert!(repo.diff_files(None).unwrap().is_empty());
6908
}
6909
6910
/// oxygen#41: a manifest written from a walk keeps every directory's time;
6911
/// while none has moved, the check stats the tracked files without listing
6912
/// the tree, and a file added or removed anywhere moves its directory's
6913
/// time, so the tree is listed again.
6914
#[test]
6915
fn the_manifest_check_skips_listing_while_no_directory_changed() {
6916
    hermetic();
6917
    let dir = tempfile::tempdir().unwrap();
6918
    let root = dir.path();
6919
    let repo = Repo::init(root).unwrap();
6920
    write(root, "a.txt", b"a\n");
6921
    write(root, "sub/deep/b.txt", b"b\n");
6922
    repo.commit("base", &[]).unwrap();
6923
    // Out of the racy window: every file and directory a minute old.
6924
    let old = std::time::SystemTime::now() - std::time::Duration::from_secs(60);
6925
    for p in ["a.txt", "sub/deep/b.txt", "sub/deep", "sub", ""] {
6926
        fs::File::open(root.join(p))
6927
            .unwrap()
6928
            .set_modified(old)
6929
            .unwrap();
6930
    }
6931
    repo.snapshot_status("oxy status").unwrap();
6932
    repo.write_manifest(false, false).unwrap();
6933
    let m = repo.read_manifest().unwrap().unwrap().2;
6934
    assert!(m.dirs.iter().any(|(d, _)| d == "sub/deep"), "{:?}", m.dirs);
6935
    assert_eq!(
6936
        repo.disk_differs_by_dirs(&m),
6937
        Some(false),
6938
        "no listing needed"
6939
    );
6940
    assert_eq!(repo.status_by_manifest().unwrap(), Some(vec![]));
6941
6942
    // A same-size edit with a new time: found by its stat.
6943
    write(root, "sub/deep/b.txt", b"c\n");
6944
    assert_eq!(repo.disk_differs_by_dirs(&m), Some(true));
6945
    write(root, "sub/deep/b.txt", b"b\n");
6946
    fs::File::open(root.join("sub/deep/b.txt"))
6947
        .unwrap()
6948
        .set_modified(old)
6949
        .unwrap();
6950
    assert_eq!(repo.disk_differs_by_dirs(&m), Some(false));
6951
6952
    // A new file moves its directory's time: the tree must be listed.
6953
    write(root, "sub/deep/new.txt", b"n\n");
6954
    assert_eq!(repo.disk_differs_by_dirs(&m), None);
6955
    assert_eq!(repo.status_by_manifest().unwrap(), None);
6956
    fs::remove_file(root.join("sub/deep/new.txt")).unwrap();
6957
    // A removed one too.
6958
    fs::remove_file(root.join("a.txt")).unwrap();
6959
    assert_eq!(repo.disk_differs_by_dirs(&m), None);
6960
}
6961
6962
/// oxygen#41: a commit right after a status takes the snapshot the status
6963
/// left (the status cache holds) rather than walking again, and commits
6964
/// exactly what a snapshot would have.
6965
#[test]
6966
fn a_commit_after_a_status_uses_the_cached_snapshot() {
6967
    hermetic();
6968
    let dir = tempfile::tempdir().unwrap();
6969
    let root = dir.path();
6970
    let repo = Repo::init(root).unwrap();
6971
    write(root, "a.txt", b"a\nb\n");
6972
    write(root, ".oxyattributes", b"*.bin binary\n");
6973
    repo.commit("base", &[]).unwrap();
6974
    write(root, "a.txt", b"a\nB\n");
6975
    write(root, "new.txt", b"new\n");
6976
    let snap = repo.snapshot_status("oxy status").unwrap();
6977
    let cached = repo
6978
        .snapshot_from_cache()
6979
        .unwrap()
6980
        .expect("the cache holds");
6981
    assert_eq!(cached.wc_hash, snap.wc_hash);
6982
    assert_eq!(cached.statuses, snap.statuses);
6983
    assert!(
6984
        !cached.attributes.is_empty(),
6985
        "the .oxyattributes file was read"
6986
    );
6987
    let h = repo.commit("edit", &[]).unwrap();
6988
    let c = repo.store().get_change(&h).unwrap();
6989
    assert_eq!(
6990
        c.tree_ops.len() + c.edits.len(),
6991
        snap.wc.tree_ops.len() + snap.wc.edits.len()
6992
    );
6993
    assert_eq!(
6994
        repo.status_by_manifest().unwrap(),
6995
        Some(vec![]),
6996
        "clean after the commit"
6997
    );
6998
    assert_eq!(fs::read(root.join("a.txt")).unwrap(), b"a\nB\n");
6999
}
7000
7001
/// oxygen#41: a clean check that verified racy entries restamps the
7002
/// manifest, so later checks can trust them, and a same-size rewrite
7003
/// straight afterwards is still found: entries within two seconds of the
7004
/// new time stay racy.
7005
#[test]
7006
fn a_verified_clean_check_restamps_the_manifest_safely() {
7007
    hermetic();
7008
    let dir = tempfile::tempdir().unwrap();
7009
    let root = dir.path();
7010
    let repo = Repo::init(root).unwrap();
7011
    write(root, "a.txt", b"one\n");
7012
    repo.commit("one", &[]).unwrap();
7013
    let before = repo.read_manifest().unwrap().unwrap().2.written_ns;
7014
    assert!(repo.clean_by_manifest().unwrap());
7015
    let after = repo.read_manifest().unwrap().unwrap().2.written_ns;
7016
    assert!(after > before, "restamped");
7017
    write(root, "a.txt", b"two\n");
7018
    assert!(
7019
        !repo.clean_by_manifest().unwrap(),
7020
        "a same-size rewrite is still seen"
7021
    );
7022
}
7023
7024
/// oxygen#35: a history-only state keeps no inserted text. It reads a
7025
/// stored insert's text blob only when it builds that file's graph, and
7026
/// builds the same graph a full load does.
7027
#[test]
7028
fn history_only_states_read_text_only_for_the_graphs_they_build() {
7029
    hermetic();
7030
    let dir = tempfile::tempdir().unwrap();
7031
    let root = dir.path();
7032
    let repo = Repo::init(root).unwrap();
7033
    let big: String = (0..3000).map(|i| format!("big line {i}\n")).collect();
7034
    let other: String = (0..3000).map(|i| format!("other line {i}\n")).collect();
7035
    write(root, "big.txt", big.as_bytes());
7036
    write(root, "other.txt", other.as_bytes());
7037
    let h = repo.commit("two large files", &[]).unwrap();
7038
    write(root, "big.txt", format!("{big}one more\n").as_bytes());
7039
    let h2 = repo.commit("append", &[]).unwrap();
7040
7041
    let full = repo.load_state_full(&[h2]).unwrap().materialize();
7042
    let text = |snap: &crate::state::Snapshot, p: &str| match &snap.files[p].content {
7043
        FileContent::Text { bytes, .. } => bytes.clone(),
7044
        other => panic!("{other:?}"),
7045
    };
7046
    // Built on demand, every graph renders as the full load's.
7047
    let mut hist = repo.load_state_history(&[h2]).unwrap();
7048
    let big_node = full.files["big.txt"].node;
7049
    assert!(hist.graph_key(&big_node).is_some(), "not built yet");
7050
    repo.load_all_graphs(&mut hist).unwrap();
7051
    let rendered = hist.materialize();
7052
    for p in ["big.txt", "other.txt"] {
7053
        assert_eq!(text(&rendered, p), text(&full, p), "{p}");
7054
    }
7055
7056
    // Without other.txt's text blob, history still loads and big.txt still
7057
    // builds: nothing read the other text.
7058
    let (_, texts) = repo.store().get_change_lazy(&h).unwrap();
7059
    assert_eq!(texts.len(), 2);
7060
    let content = |r: &ObjectRef| -> Vec<u8> {
7061
        let blob = crate::objects::Blob::decode(&repo.store().get(r).unwrap().1).unwrap();
7062
        blob.chunks
7063
            .iter()
7064
            .flat_map(|c| repo.store().get(c).unwrap().1)
7065
            .collect()
7066
    };
7067
    let other_text = texts
7068
        .iter()
7069
        .filter_map(|t| match t {
7070
            crate::objects::TextRef::Blob(r, _, _) => Some(*r),
7071
            _ => None,
7072
        })
7073
        .find(|r| content(r).windows(12).any(|w| w == b"other line 1"))
7074
        .unwrap();
7075
    repo.store().remove_loose_for_test(&other_text).unwrap();
7076
    let mut hist = repo.load_state_history(&[h2]).unwrap();
7077
    repo.load_graphs_of(&mut hist, &[big_node]).unwrap();
7078
    assert!(repo
7079
        .load_graphs_of(&mut hist, &[full.files["other.txt"].node])
7080
        .is_err());
7081
}
7082
7083
/// oxygen#35: the first status after a commit read and rendered every
7084
/// file (79 s and more than 14 GB on the Linux tree), because the
7085
/// manifest had no graph keys for files the commit added.
7086
#[test]
7087
fn a_commit_leaves_a_manifest_the_next_status_trusts() {
7088
    use std::os::unix::fs::PermissionsExt;
7089
    hermetic();
7090
    let dir = tempfile::tempdir().unwrap();
7091
    let root = dir.path();
7092
    let repo = Repo::init(root).unwrap();
7093
    let files = ["a.txt", "b.txt", "d/c.txt"];
7094
    for p in files {
7095
        write(root, p, format!("{p}\n").as_bytes());
7096
        let old = std::time::SystemTime::now() - std::time::Duration::from_secs(30);
7097
        fs::File::options()
7098
            .write(true)
7099
            .open(root.join(p))
7100
            .unwrap()
7101
            .set_modified(old)
7102
            .unwrap();
7103
    }
7104
    repo.commit("added", &[]).unwrap();
7105
    let (_, _, m) = repo.read_manifest().unwrap().unwrap();
7106
    assert!(
7107
        m.entries.values().all(|e| e.graph.is_some()),
7108
        "keys recorded at commit"
7109
    );
7110
    // Unreadable files prove the next status reads none of them.
7111
    for p in files {
7112
        fs::set_permissions(root.join(p), fs::Permissions::from_mode(0o000)).unwrap();
7113
    }
7114
    let snap = repo.snapshot_status("status").unwrap();
7115
    for p in files {
7116
        fs::set_permissions(root.join(p), fs::Permissions::from_mode(0o644)).unwrap();
7117
    }
7118
    assert!(!snap.changed && snap.statuses.is_empty());
7119
    assert_eq!(snap.base_snapshot.unrendered.len(), files.len());
7120
}
7121
7122
/// oxygen#35: a checkout reads, renders and writes only the files whose
7123
/// graphs differ, and renders the rest a batch at a time.
7124
#[test]
7125
fn checkout_touches_only_what_differs_and_renders_in_batches() {
7126
    use std::os::unix::fs::PermissionsExt;
7127
    hermetic();
7128
    let dir = tempfile::tempdir().unwrap();
7129
    let root = dir.path();
7130
    let origin = root.join("origin");
7131
    let mut repo = Repo::init(&origin).unwrap();
7132
    // More files than one batch holds.
7133
    let n = 2100;
7134
    let old = std::time::SystemTime::now() - std::time::Duration::from_secs(30);
7135
    for i in 0..n {
7136
        let p = format!("f/{i:04}.txt");
7137
        write(&origin, &p, format!("file {i}\n").as_bytes());
7138
        fs::File::options()
7139
            .write(true)
7140
            .open(origin.join(&p))
7141
            .unwrap()
7142
            .set_modified(old)
7143
            .unwrap();
7144
    }
7145
    repo.commit("many", &[]).unwrap();
7146
    repo.bookmark_create("feature", None).unwrap();
7147
    repo.bookmark_switch("feature", false).unwrap();
7148
    write(&origin, "f/0007.txt", b"changed\n");
7149
    repo.commit("one change", &[]).unwrap();
7150
7151
    // Switching back to main must not read the unchanged files.
7152
    for i in 0..n {
7153
        if i != 7 {
7154
            let p = origin.join(format!("f/{i:04}.txt"));
7155
            fs::set_permissions(&p, fs::Permissions::from_mode(0o000)).unwrap();
7156
        }
7157
    }
7158
    let r = repo.bookmark_switch("main", false).unwrap();
7159
    for i in 0..n {
7160
        let p = origin.join(format!("f/{i:04}.txt"));
7161
        fs::set_permissions(&p, fs::Permissions::from_mode(0o644)).unwrap();
7162
    }
7163
    assert_eq!((r.written, r.removed), (1, 0), "{r:?}");
7164
    assert_eq!(fs::read(origin.join("f/0007.txt")).unwrap(), b"file 7\n");
7165
    assert!(repo.snapshot_status("status").unwrap().statuses.is_empty());
7166
7167
    // A clone renders every file, across batches.
7168
    let c = root.join("clone");
7169
    Repo::clone(&origin.to_string_lossy(), &c).unwrap();
7170
    for i in [0, 2047, 2048, n - 1] {
7171
        assert_eq!(
7172
            fs::read(c.join(format!("f/{i:04}.txt"))).unwrap(),
7173
            format!("file {i}\n").as_bytes()
7174
        );
7175
    }
7176
    let cloned = Repo::open(&c).unwrap();
7177
    assert!(cloned
7178
        .snapshot_status("status")
7179
        .unwrap()
7180
        .statuses
7181
        .is_empty());
7182
}
7183
7184
/// A file written just before the manifest (inside the racy window) is
7185
/// checked by its hash: trusted when equal, caught when edited in place
7186
/// with the same size and time.
7187
#[test]
7188
fn a_racy_manifest_entry_is_checked_by_hash() {
7189
    hermetic();
7190
    let dir = tempfile::tempdir().unwrap();
7191
    let root = dir.path();
7192
    let repo = Repo::init(root).unwrap();
7193
    write(root, "a.txt", b"one\n");
7194
    repo.commit("fresh", &[]).unwrap();
7195
    assert!(repo.clean_by_manifest().unwrap(), "fresh but equal");
7196
    let t = fs::metadata(root.join("a.txt"))
7197
        .unwrap()
7198
        .modified()
7199
        .unwrap();
7200
    write(root, "a.txt", b"two\n");
7201
    fs::File::options()
7202
        .write(true)
7203
        .open(root.join("a.txt"))
7204
        .unwrap()
7205
        .set_modified(t)
7206
        .unwrap();
7207
    assert!(
7208
        !repo.clean_by_manifest().unwrap(),
7209
        "same size and time, other bytes"
7210
    );
7211
    assert_eq!(
7212
        statuses(&repo.snapshot_status("status").unwrap()),
7213
        vec![("a.txt".to_string(), ChangeStatus::Modified)]
7214
    );
7215
}
7216
7217
/// A fetch on one machine moves changes as stored, text blobs among the
7218
/// objects; a change whose text blob did not come is refused, not stored.
7219
#[test]
7220
fn a_raw_bundle_without_a_changes_text_is_refused() {
7221
    hermetic();
7222
    let dir = tempfile::tempdir().unwrap();
7223
    let root = dir.path();
7224
    let a = Repo::init(&root.join("a")).unwrap();
7225
    let big: String = (0..3000).map(|i| format!("line {i}\n")).collect();
7226
    write(&root.join("a"), "big.txt", big.as_bytes());
7227
    let h = a.commit("big", &[]).unwrap();
7228
    let bundle = a.bundle_raw_for(&[h], None).unwrap();
7229
    assert_eq!(bundle.raw_changes.len(), 1);
7230
    assert!(bundle.changes.is_empty());
7231
    let b = Repo::init(&root.join("b")).unwrap();
7232
    let mut without = bundle.clone();
7233
    without.objects.retain(|(ty, _)| *ty != ObjectType::Blob);
7234
    let e = b.import_bundle(&without, false).unwrap_err();
7235
    assert!(e.to_string().contains("came without its text blob"), "{e}");
7236
    assert!(!b.store().has(&h));
7237
    assert_eq!(b.import_bundle(&bundle, false).unwrap(), vec![h]);
7238
    assert_eq!(b.store().get_change(&h).unwrap().message, "big");
7239
}
7240
7241
/// oxygen#30 (vscode): a directory deleted in one line of history and made
7242
/// again was a second node for one Git path, so a file moved into it on
7243
/// another line, where the first node still stood, ended up in two places.
7244
/// An import now brings the directory back rather than make a new one.
7245
#[test]
7246
fn git_import_brings_a_directory_back_rather_than_making_a_second() {
7247
    hermetic();
7248
    if std::process::Command::new("git")
7249
        .arg("--version")
7250
        .output()
7251
        .is_err()
7252
    {
7253
        eprintln!("git not installed; skipping");
7254
        return;
7255
    }
7256
    let dir = tempfile::tempdir().unwrap();
7257
    let root = dir.path();
7258
    let g = root.join("src.git");
7259
    fs::create_dir_all(&g).unwrap();
7260
    let git = |args: &[&str]| -> String {
7261
        let out = std::process::Command::new("git")
7262
            .arg("-C")
7263
            .arg(&g)
7264
            .args([
7265
                "-c",
7266
                "user.name=Grace",
7267
                "-c",
7268
                "[email protected]",
7269
                "-c",
7270
                "commit.gpgsign=false",
7271
            ])
7272
            .args(args)
7273
            .output()
7274
            .unwrap();
7275
        assert!(
7276
            out.status.success(),
7277
            "git {args:?}: {}",
7278
            String::from_utf8_lossy(&out.stderr)
7279
        );
7280
        String::from_utf8_lossy(&out.stdout).trim().to_string()
7281
    };
7282
    git(&["init", "-q", "-b", "main"]);
7283
    write(&g, "d/a.txt", b"a\n");
7284
    write(&g, "c/x.txt", b"x\n");
7285
    git(&["add", "."]);
7286
    git(&["commit", "-qm", "base"]);
7287
    // One line: move x into d while d still stands.
7288
    git(&["checkout", "-qb", "side"]);
7289
    git(&["mv", "c/x.txt", "d/x.txt"]);
7290
    git(&["commit", "-qm", "x into d"]);
7291
    // The other: d goes, comes back, and x moves into it too.
7292
    git(&["checkout", "-q", "main"]);
7293
    git(&["rm", "-q", "d/a.txt"]);
7294
    git(&["commit", "-qm", "d goes"]);
7295
    write(&g, "d/b.txt", b"b\n");
7296
    git(&["add", "."]);
7297
    git(&["commit", "-qm", "d comes back"]);
7298
    git(&["mv", "c/x.txt", "d/x.txt"]);
7299
    git(&["commit", "-qm", "x into d again"]);
7300
    git(&["merge", "-q", "--no-edit", "side"]);
7301
7302
    let repo = Repo::init(&root.join("o")).unwrap();
7303
    repo.import_git(&g, "main").unwrap();
7304
    let v = repo.verify_git_import(&g, "main").unwrap();
7305
    assert!(v.mismatches.is_empty(), "{:?}", v.mismatches);
7306
    let st = repo
7307
        .load_state_history(&repo.bookmark_heads().unwrap())
7308
        .unwrap();
7309
    let view = st.tree().view();
7310
    assert!(view.conflicts.is_empty(), "{:?}", view.conflicts);
7311
    // The directory is the one the first commit made.
7312
    // Commits made in one second tie on time: find the first by its message.
7313
    let first = repo
7314
        .log()
7315
        .unwrap()
7316
        .into_iter()
7317
        .find(|e| e.change.message.starts_with("base"))
7318
        .unwrap();
7319
    let base = repo
7320
        .load_state_history(&[first.hash])
7321
        .unwrap()
7322
        .tree()
7323
        .view();
7324
    assert_eq!(view.entries["d"].node, base.entries["d"].node);
7325
}
7326
7327
/// oxygen#30, the rest: a placement left under a directory another line
7328
/// removed is out of sight, so no diff reaches it; the merge that settles
7329
/// where the file is retires it.
7330
#[test]
7331
fn git_import_merge_retires_a_placement_under_a_removed_directory() {
7332
    hermetic();
7333
    if std::process::Command::new("git")
7334
        .arg("--version")
7335
        .output()
7336
        .is_err()
7337
    {
7338
        eprintln!("git not installed; skipping");
7339
        return;
7340
    }
7341
    let dir = tempfile::tempdir().unwrap();
7342
    let root = dir.path();
7343
    let g = root.join("src.git");
7344
    fs::create_dir_all(&g).unwrap();
7345
    let run = |args: &[&str]| {
7346
        std::process::Command::new("git")
7347
            .arg("-C")
7348
            .arg(&g)
7349
            .args([
7350
                "-c",
7351
                "user.name=Grace",
7352
                "-c",
7353
                "[email protected]",
7354
                "-c",
7355
                "commit.gpgsign=false",
7356
            ])
7357
            .args(args)
7358
            .output()
7359
            .unwrap()
7360
    };
7361
    let git = |args: &[&str]| {
7362
        let out = run(args);
7363
        assert!(
7364
            out.status.success(),
7365
            "git {args:?}: {}",
7366
            String::from_utf8_lossy(&out.stderr)
7367
        );
7368
    };
7369
    git(&["init", "-q", "-b", "main"]);
7370
    write(&g, "c/x.txt", b"x\n");
7371
    write(&g, "keep.txt", b"k\n");
7372
    git(&["add", "."]);
7373
    git(&["commit", "-qm", "base"]);
7374
    // One line renames the file within c; the other moves it out of c,
7375
    // which goes.
7376
    git(&["checkout", "-qb", "side"]);
7377
    git(&["mv", "c/x.txt", "c/y.txt"]);
7378
    git(&["commit", "-qm", "rename within c"]);
7379
    git(&["checkout", "-q", "main"]);
7380
    fs::create_dir_all(g.join("n")).unwrap();
7381
    git(&["mv", "c/x.txt", "n/x.txt"]);
7382
    git(&["commit", "-qm", "move out of c"]);
7383
    // Git cannot merge the two renames; the merge keeps n/x.txt.
7384
    let _ = run(&["merge", "-q", "side"]);
7385
    let _ = run(&[
7386
        "rm",
7387
        "-q",
7388
        "--cached",
7389
        "--ignore-unmatch",
7390
        "c/y.txt",
7391
        "c/x.txt",
7392
    ]);
7393
    let _ = std::fs::remove_dir_all(g.join("c"));
7394
    write(&g, "n/x.txt", b"x\n");
7395
    git(&["add", "-A"]);
7396
    git(&["commit", "-qm", "merge: keep n/x.txt"]);
7397
7398
    let repo = Repo::init(&root.join("o")).unwrap();
7399
    repo.import_git(&g, "main").unwrap();
7400
    let v = repo.verify_git_import(&g, "main").unwrap();
7401
    assert!(v.mismatches.is_empty(), "{:?}", v.mismatches);
7402
    let st = repo
7403
        .load_state_history(&repo.bookmark_heads().unwrap())
7404
        .unwrap();
7405
    let view = st.tree().view();
7406
    assert!(view.conflicts.is_empty(), "{:?}", view.conflicts);
7407
    assert!(view.entries.contains_key("n/x.txt"));
7408
}
7409
7410
/// oxygen#30, orphans: a file added on one line into a directory the other
7411
/// line removed is placed where the tree cannot show it; Git's merge keeps
7412
/// the file, and the import's merge leaves exactly one of it.
7413
#[test]
7414
fn git_import_merge_leaves_no_orphan_behind() {
7415
    hermetic();
7416
    if std::process::Command::new("git")
7417
        .arg("--version")
7418
        .output()
7419
        .is_err()
7420
    {
7421
        eprintln!("git not installed; skipping");
7422
        return;
7423
    }
7424
    let dir = tempfile::tempdir().unwrap();
7425
    let root = dir.path();
7426
    let g = root.join("src.git");
7427
    fs::create_dir_all(&g).unwrap();
7428
    let git = |args: &[&str]| {
7429
        let out = std::process::Command::new("git")
7430
            .arg("-C")
7431
            .arg(&g)
7432
            .args([
7433
                "-c",
7434
                "user.name=Grace",
7435
                "-c",
7436
                "[email protected]",
7437
                "-c",
7438
                "commit.gpgsign=false",
7439
            ])
7440
            .args(args)
7441
            .output()
7442
            .unwrap();
7443
        assert!(
7444
            out.status.success(),
7445
            "git {args:?}: {}",
7446
            String::from_utf8_lossy(&out.stderr)
7447
        );
7448
    };
7449
    git(&["init", "-q", "-b", "main"]);
7450
    write(&g, "d/f.txt", b"f\n");
7451
    write(&g, "keep.txt", b"k\n");
7452
    git(&["add", "."]);
7453
    git(&["commit", "-qm", "base"]);
7454
    git(&["checkout", "-qb", "side"]);
7455
    write(&g, "d/new.txt", b"new\n");
7456
    git(&["add", "."]);
7457
    git(&["commit", "-qm", "add into d"]);
7458
    git(&["checkout", "-q", "main"]);
7459
    git(&["rm", "-q", "d/f.txt"]);
7460
    git(&["commit", "-qm", "d goes"]);
7461
    git(&["merge", "-q", "--no-edit", "side"]);
7462
7463
    let repo = Repo::init(&root.join("o")).unwrap();
7464
    repo.import_git(&g, "main").unwrap();
7465
    let v = repo.verify_git_import(&g, "main").unwrap();
7466
    assert!(v.mismatches.is_empty(), "{:?}", v.mismatches);
7467
    let st = repo
7468
        .load_state_history(&repo.bookmark_heads().unwrap())
7469
        .unwrap();
7470
    let view = st.tree().view();
7471
    assert!(view.conflicts.is_empty(), "{:?}", view.conflicts);
7472
    assert!(view.entries.contains_key("d/new.txt"));
7473
}
7474
7475
/// fsck checks a change's text as the blobs it is stored in, without
7476
/// decoding it: a missing text blob is an error named for the change.
7477
#[test]
7478
fn fsck_names_a_missing_text_blob() {
7479
    hermetic();
7480
    let dir = tempfile::tempdir().unwrap();
7481
    let root = dir.path();
7482
    let repo = Repo::init(root).unwrap();
7483
    let big: String = (0..3000).map(|i| format!("line {i}\n")).collect();
7484
    write(root, "big.txt", big.as_bytes());
7485
    let h = repo.commit("big", &[]).unwrap();
7486
    assert_eq!(repo.fsck().unwrap().errors(), 0);
7487
    let (_, texts) = repo.store().get_change_lazy(&h).unwrap();
7488
    let Some(crate::objects::TextRef::Blob(b, _, _)) = texts.first().copied() else {
7489
        panic!("a stored text")
7490
    };
7491
    repo.store().remove_loose_for_test(&b).unwrap();
7492
    let rep = repo.fsck().unwrap();
7493
    assert!(rep.errors() > 0);
7494
    assert!(
7495
        rep.problems.iter().any(|p| p.what.contains(&h.short(12))),
7496
        "{:?}",
7497
        rep.problems
7498
    );
7499
}
7500
7501
/// oxygen#32: a subrepo on the same hub as one of the parent's remotes is
7502
/// reached with that remote's token and CA (a private subrepo then clones
7503
/// for anyone who can read the parent); another hub gets none of them.
7504
#[test]
7505
fn a_subrepo_on_the_parents_hub_borrows_its_credentials() {
7506
    hermetic();
7507
    let dir = tempfile::tempdir().unwrap();
7508
    let mut repo = Repo::init(dir.path()).unwrap();
7509
    repo.config
7510
        .set(
7511
            "remote.origin.url",
7512
            "https://Hub.example:7343/doomsdayone/metalgear",
7513
        )
7514
        .unwrap();
7515
    repo.config.set("remote.origin.token", "secret").unwrap();
7516
    repo.config
7517
        .set("remote.origin.ca", "/tmp/hub-ca.pem")
7518
        .unwrap();
7519
    let same = repo.credentials_for("https://hub.example:7343/doomsdayone/rstar-api");
7520
    assert_eq!(same.token.as_deref(), Some("secret"));
7521
    assert_eq!(same.ca.as_deref(), Some(Path::new("/tmp/hub-ca.pem")));
7522
    for other in [
7523
        "https://elsewhere.example:7343/doomsdayone/rstar-api",
7524
        "https://hub.example/doomsdayone/rstar-api",
7525
        "http://hub.example:7343/doomsdayone/rstar-api",
7526
    ] {
7527
        let o = repo.credentials_for(other);
7528
        assert_ne!(o.token.as_deref(), Some("secret"), "{other}");
7529
    }
7530
}
7531
7532
/// oxygen#47: a remote with no token of its own uses the user's credential
7533
/// store for its hub, and a nested checkout finds its parent's remote
7534
/// token there instead of keeping a copy.
7535
#[test]
7536
fn remotes_use_the_credential_store_and_the_enclosing_checkout() {
7537
    hermetic();
7538
    let home = tempfile::tempdir().unwrap();
7539
    let dir = tempfile::tempdir().unwrap();
7540
    let mut parent = Repo::init(dir.path()).unwrap().with_home(home.path());
7541
    parent
7542
        .config
7543
        .set("remote.origin.url", "https://hub.example/o/parent")
7544
        .unwrap();
7545
    parent.save_config().unwrap();
7546
    assert_eq!(parent.remote_options("origin").token, None);
7547
    crate::credentials::Credentials::at(home.path())
7548
        .save("https://hub.example", "stored", Some("andy"), None)
7549
        .unwrap();
7550
    assert_eq!(
7551
        parent.remote_options("origin").token.as_deref(),
7552
        Some("stored")
7553
    );
7554
7555
    let empty_home = tempfile::tempdir().unwrap();
7556
    let nested = dir.path().join("deps").join("child");
7557
    let mut child = Repo::init(&nested).unwrap().with_home(empty_home.path());
7558
    child
7559
        .config
7560
        .set("remote.origin.url", "https://hub.example/o/child")
7561
        .unwrap();
7562
    child.save_config().unwrap();
7563
    assert_eq!(child.remote_options("origin").token, None);
7564
    parent
7565
        .config
7566
        .set("remote.origin.token", "checkout")
7567
        .unwrap();
7568
    parent.save_config().unwrap();
7569
    assert_eq!(
7570
        child.remote_options("origin").token.as_deref(),
7571
        Some("checkout")
7572
    );
7573
    // Another hub's checkout token is not borrowed.
7574
    child
7575
        .config
7576
        .set("remote.origin.url", "https://other.example/o/child")
7577
        .unwrap();
7578
    assert_eq!(child.remote_options("origin").token, None);
7579
}
7580
7581
#[test]
7582
fn the_metadata_cache_survives_a_torn_tail() {
7583
    hermetic();
7584
    let dir = tempfile::tempdir().unwrap();
7585
    let root = dir.path();
7586
    let repo = Repo::init(root).unwrap();
7587
    write(root, "a.txt", b"1\n");
7588
    let h = repo.commit("first", &[]).unwrap();
7589
    let meta = repo.store().get_change_meta(&h).unwrap();
7590
    let cache = repo.store().dir().join("metas");
7591
    let len = fs::metadata(&cache).unwrap().len();
7592
    assert!(len > 0, "a change read is cached");
7593
    // A torn record at the end: the cache reads up to it and cuts it off.
7594
    fs::OpenOptions::new()
7595
        .append(true)
7596
        .open(&cache)
7597
        .unwrap()
7598
        .write_all(&[7; 20])
7599
        .unwrap();
7600
    let again = Repo::open(root).unwrap();
7601
    assert_eq!(again.store().get_change_meta(&h).unwrap(), meta);
7602
    assert_eq!(fs::metadata(&cache).unwrap().len(), len);
7603
}
7604
7605
#[test]
7606
fn a_manifest_that_does_not_check_reads_as_none() {
7607
    hermetic();
7608
    let dir = tempfile::tempdir().unwrap();
7609
    let root = dir.path();
7610
    let repo = Repo::init(root).unwrap();
7611
    write(root, "a.txt", b"1\n");
7612
    repo.commit("first", &[]).unwrap();
7613
    let path = repo.manifest_path();
7614
    let mut bytes = fs::read(&path).unwrap();
7615
    assert!(Repo::open(root).unwrap().read_manifest().unwrap().is_some());
7616
    let last = bytes.len() - 1;
7617
    bytes[last] ^= 1;
7618
    fs::write(&path, &bytes).unwrap();
7619
    assert!(Repo::open(root).unwrap().read_manifest().unwrap().is_none());
7620
    // The next status reads the files and writes it again.
7621
    let again = Repo::open(root).unwrap();
7622
    assert!(!again.snapshot("status").unwrap().changed);
7623
    assert!(again.read_manifest().unwrap().is_some());
7624
}
7625
7626
#[test]
7627
fn a_commit_leaves_a_manifest_that_proves_the_working_copy_clean() {
7628
    hermetic();
7629
    let dir = tempfile::tempdir().unwrap();
7630
    let root = dir.path();
7631
    let repo = Repo::init(root).unwrap();
7632
    write(root, "a.txt", b"1\n");
7633
    write(root, "b.txt", b"2\n");
7634
    // b.txt outside the racy window, so snapshots take it as unchanged.
7635
    let old = std::time::SystemTime::now() - std::time::Duration::from_secs(60);
7636
    fs::File::options()
7637
        .write(true)
7638
        .open(root.join("b.txt"))
7639
        .unwrap()
7640
        .set_modified(old)
7641
        .unwrap();
7642
    repo.commit("first", &[]).unwrap();
7643
    assert!(repo.clean_by_manifest().unwrap(), "after the first commit");
7644
    repo.snapshot_status("status").unwrap();
7645
    write(root, "a.txt", b"1\n2\n");
7646
    repo.commit("second", &[]).unwrap();
7647
    assert!(
7648
        repo.clean_by_manifest().unwrap(),
7649
        "after a commit of one file"
7650
    );
7651
    // Edited, seen by a status, edited again, then committed: the status
7652
    // left the first edit's stat, which the commit must not keep.
7653
    write(root, "a.txt", b"1\n2\n3\n");
7654
    repo.snapshot_status("status").unwrap();
7655
    write(root, "a.txt", b"1\n2\n3\n4\n5\n");
7656
    repo.commit("third", &[]).unwrap();
7657
    assert!(
7658
        repo.clean_by_manifest().unwrap(),
7659
        "after an edit a status saw"
7660
    );
7661
}
7662
7663
#[test]
7664
fn a_conflicted_rebase_can_be_resolved_in_the_working_copy() {
7665
    hermetic();
7666
    let dir = tempfile::tempdir().unwrap();
7667
    let root = dir.path();
7668
    let mut repo = Repo::init(root).unwrap().with_home(root.join("home"));
7669
    write(root, "a.txt", b"1\n2\n");
7670
    let a = repo.commit("A", &[]).unwrap();
7671
    repo.bookmark_create("develop", Some(&[a])).unwrap();
7672
    write(root, "a.txt", b"1\nX\n");
7673
    let c = repo.commit("C: 2 to X", &[]).unwrap();
7674
    repo.bookmark_switch("develop", false).unwrap();
7675
    write(root, "a.txt", b"1\nY\n");
7676
    let d = repo.commit("D: 2 to Y", &[]).unwrap();
7677
    repo.bookmark_switch("main", false).unwrap();
7678
7679
    let err = repo.rebase(&c, &[d]).unwrap_err();
7680
    assert!(matches!(err, RepoError::Conflicted(_)), "{err}");
7681
    let r = repo.rebase_into_working_copy(&c, &[d]).unwrap();
7682
    assert!(r.changed && r.checked_out);
7683
    let snap = repo.snapshot_status("status").unwrap();
7684
    assert!(
7685
        snap.base_snapshot.is_conflicted(),
7686
        "the conflict is in the working copy"
7687
    );
7688
    let text = fs::read_to_string(root.join("a.txt")).unwrap();
7689
    assert!(text.contains('X') && text.contains('Y'), "{text}");
7690
7691
    write(root, "a.txt", b"1\nXY\n");
7692
    repo.commit("Resolve", &[]).unwrap();
7693
    let st = repo.load_state(&repo.bookmark_heads().unwrap()).unwrap();
7694
    assert!(st.contains(&c) && st.contains(&d));
7695
    let files = st.materialize().files;
7696
    assert!(!files["a.txt"].is_conflicted());
7697
    assert!(
7698
        matches!(&files["a.txt"].content, FileContent::Text { bytes, .. } if bytes == b"1\nXY\n")
7699
    );
7700
7701
    // A change the current bookmark does not hold is refused.
7702
    repo.bookmark_switch("develop", false).unwrap();
7703
    write(root, "b.txt", b"b\n");
7704
    let e = repo.commit("E", &[]).unwrap();
7705
    repo.bookmark_switch("main", false).unwrap();
7706
    let err = repo.rebase_into_working_copy(&e, &[a]).unwrap_err();
7707
    assert!(
7708
        err.to_string().contains("not on the current bookmark"),
7709
        "{err}"
7710
    );
7711
}
7712
7713
#[test]
7714
fn an_ignore_rule_drops_an_added_file_but_not_a_tracked_one() {
7715
    hermetic();
7716
    let dir = tempfile::tempdir().unwrap();
7717
    let root = dir.path();
7718
    let repo = Repo::init(root).unwrap();
7719
    write(root, "a.txt", b"a\n");
7720
    write(root, "kept.log", b"tracked\n");
7721
    repo.commit("first", &[]).unwrap();
7722
    write(root, "build.log", b"made\n");
7723
    let snap = repo.snapshot_status("status").unwrap();
7724
    assert!(snap.statuses.iter().any(|s| s.path == "build.log"));
7725
    // A rule written afterwards leaves the added file out again, while the
7726
    // committed one stays tracked.
7727
    write(root, ".gitignore", b"*.log\n");
7728
    let snap = repo.snapshot_status("status").unwrap();
7729
    let paths: Vec<&str> = snap.statuses.iter().map(|s| s.path.as_str()).collect();
7730
    assert_eq!(paths, vec![".gitignore"], "{paths:?}");
7731
    write(root, "kept.log", b"tracked, edited\n");
7732
    let snap = repo.snapshot_status("status").unwrap();
7733
    assert!(snap.statuses.iter().any(|s| s.path == "kept.log"));
7734
}
7735
7736
#[test]
7737
fn shed_graphs_come_back_the_same() {
7738
    hermetic();
7739
    let dir = tempfile::tempdir().unwrap();
7740
    let root = dir.path();
7741
    let repo = Repo::init(root).unwrap();
7742
    write(root, "a.txt", b"1\n2\n3\n");
7743
    write(root, "b.txt", b"x\n");
7744
    repo.commit("first", &[]).unwrap();
7745
    write(root, "a.txt", b"1\ntwo\n3\n4\n");
7746
    repo.commit("second", &[]).unwrap();
7747
    let heads = repo.bookmark_heads().unwrap();
7748
    let mut st = repo.load_state_history(&heads).unwrap();
7749
    let view = st.tree().view();
7750
    let nodes: Vec<NodeId> = ["a.txt", "b.txt"]
7751
        .iter()
7752
        .map(|p| view.entries[*p].node)
7753
        .collect();
7754
    repo.load_graphs_of(&mut st, &nodes).unwrap();
7755
    let before: Vec<Vec<u8>> = nodes.iter().map(|n| st.render_file(n).0).collect();
7756
    assert_eq!(st.built_count(), 2);
7757
    let shed = st.shed_graphs(|b| repo.store_blob(b)).unwrap();
7758
    assert_eq!((shed, st.built_count()), (2, 0));
7759
    // A later change applies on top of the shed history.
7760
    write(root, "a.txt", b"1\ntwo\n3\n4\n5\n");
7761
    let h3 = repo.commit("third", &[]).unwrap();
7762
    let (skeleton, texts) = repo.store().get_change_lazy(&h3).unwrap();
7763
    st.add_known(h3, skeleton, texts);
7764
    repo.load_graphs_of(&mut st, &nodes).unwrap();
7765
    let after: Vec<Vec<u8>> = nodes.iter().map(|n| st.render_file(n).0).collect();
7766
    assert_eq!(after[1], before[1]);
7767
    assert_eq!(after[0], b"1\ntwo\n3\n4\n5\n");
7768
}
7769
7770
#[test]
7771
fn many_edited_files_diff_in_parallel() {
7772
    // Enough edited files that the builder diffs them in parallel; the
7773
    // commit must hold exactly what is on disk, and a second snapshot
7774
    // must find nothing left to commit.
7775
    hermetic();
7776
    let dir = tempfile::tempdir().unwrap();
7777
    let root = dir.path();
7778
    let repo = Repo::init(root).unwrap();
7779
    let text = |i: usize, round: usize| {
7780
        let mut s = String::new();
7781
        for line in 0..50 {
7782
            if round > 0 && line % 7 == i % 7 {
7783
                s.push_str(&format!("edited {round} {i} {line}\n"));
7784
            } else {
7785
                s.push_str(&format!("file {i} line {line}\n"));
7786
            }
7787
        }
7788
        if round > 0 && i.is_multiple_of(3) {
7789
            s.push_str("appended\n");
7790
        }
7791
        s
7792
    };
7793
    for i in 0..40 {
7794
        write(root, &format!("d/f{i}.txt"), text(i, 0).as_bytes());
7795
    }
7796
    repo.commit("first", &[]).unwrap();
7797
    for i in 0..40 {
7798
        write(root, &format!("d/f{i}.txt"), text(i, 1).as_bytes());
7799
    }
7800
    let h = repo.commit("edit every file", &[]).unwrap();
7801
    let snap = repo.load_state(&[h]).unwrap().materialize();
7802
    for i in 0..40 {
7803
        let want = text(i, 1);
7804
        assert!(
7805
            matches!(&snap.files[&format!("d/f{i}.txt")].content, FileContent::Text { bytes, .. } if bytes == want.as_bytes()),
7806
            "d/f{i}.txt as committed"
7807
        );
7808
    }
7809
    assert!(
7810
        repo.commit("nothing", &[]).is_err(),
7811
        "nothing left to commit"
7812
    );
7813
}
7814
7815
/// oxygen#56: after a fetch, how a bookmark stands against its remote copy
7816
/// is known (fetch printed "up to date" while main was behind), a change
7817
/// only fetched resolves and says where it is, and a checkout whose only
7818
/// remote is not `origin` uses that one.
7819
#[test]
7820
fn a_fetched_change_shows_as_behind_and_resolves() {
7821
    hermetic();
7822
    let dir = tempfile::tempdir().unwrap();
7823
    let root = dir.path();
7824
    let origin = Repo::init(&root.join("origin")).unwrap();
7825
    drop(origin);
7826
    let url = root.join("origin").to_string_lossy().to_string();
7827
    let a = Repo::clone(&url, &root.join("a"))
7828
        .unwrap()
7829
        .with_home(root.join("home-a"));
7830
    write(&root.join("a"), "f.txt", b"one\n");
7831
    a.commit("one", &[]).unwrap();
7832
    a.push("origin", false).unwrap();
7833
    let b = Repo::clone(&url, &root.join("b"))
7834
        .unwrap()
7835
        .with_home(root.join("home-b"));
7836
    assert_eq!(b.tracking("origin", "main").unwrap(), Some((0, 0)));
7837
7838
    write(&root.join("a"), "f.txt", b"one\ntwo\n");
7839
    let h2 = a.commit("two", &[]).unwrap();
7840
    a.push("origin", false).unwrap();
7841
    b.fetch("origin").unwrap();
7842
    // Fetched, not pulled: one behind, the change found and placed.
7843
    assert_eq!(b.tracking("origin", "main").unwrap(), Some((0, 1)));
7844
    assert_eq!(b.tracking("origin", "nope").unwrap(), None);
7845
    assert_eq!(
7846
        b.resolve_change(&format!("#{}", &h2.to_hex()[..12]))
7847
            .unwrap(),
7848
        h2
7849
    );
7850
    assert_eq!(
7851
        b.remote_only_location(&h2).unwrap().as_deref(),
7852
        Some("origin/main")
7853
    );
7854
    // Fetching again changes nothing: still behind, which is what the
7855
    // CLI now says rather than "up to date".
7856
    b.fetch("origin").unwrap();
7857
    assert_eq!(b.tracking("origin", "main").unwrap(), Some((0, 1)));
7858
    b.pull("origin").unwrap();
7859
    assert_eq!(b.tracking("origin", "main").unwrap(), Some((0, 0)));
7860
    assert_eq!(b.remote_only_location(&h2).unwrap(), None);
7861
7862
    // One remote, not called origin: it is the default.
7863
    let mut c = Repo::init(&root.join("c")).unwrap();
7864
    assert_eq!(c.default_remote(), "origin");
7865
    c.config.set("remote.earth.url", &url).unwrap();
7866
    assert_eq!(c.default_remote(), "earth");
7867
    c.config.set("remote.origin.url", &url).unwrap();
7868
    assert_eq!(c.default_remote(), "origin");
7869
}
7870
7871
/// oxygen#57: a clone from a relative local path records the remote as an
7872
/// absolute path, so fetch still finds it from inside the clone.
7873
#[test]
7874
fn a_clone_from_a_relative_path_records_it_absolute() {
7875
    hermetic();
7876
    let dir = tempfile::tempdir().unwrap();
7877
    let root = dir.path();
7878
    Repo::init(&root.join("origin")).unwrap();
7879
    let rel = crate::protocol::stored_url("relative/repo");
7880
    assert!(std::path::Path::new(&rel).is_absolute(), "{rel}");
7881
    assert_eq!(
7882
        crate::protocol::stored_url("https://hub.example/o/n"),
7883
        "https://hub.example/o/n"
7884
    );
7885
    assert!(crate::protocol::stored_url("file://x").starts_with("file:///"));
7886
    assert!(crate::protocol::stored_url("dir://x").starts_with("dir:///"));
7887
    // A bucket is kept as written: it is not a path.
7888
    assert_eq!(
7889
        crate::protocol::stored_url("s3://bucket/prefix?profile=p"),
7890
        "s3://bucket/prefix?profile=p"
7891
    );
7892
    let url = root.join("origin").to_string_lossy().to_string();
7893
    let b = Repo::clone(&url, &root.join("b")).unwrap();
7894
    assert_eq!(b.config.remotes["origin"], url);
7895
    b.fetch("origin").unwrap();
7896
}
7897
7898
/// oxygen#60 and #61: a workspace added on a bookmark is on that bookmark,
7899
/// and gets its subrepos at their pins from this workspace's copies, with
7900
/// their remotes pointing where the subrepos come from.
7901
#[test]
7902
fn a_workspace_added_on_a_bookmark_is_on_it_with_its_subrepos() {
7903
    hermetic();
7904
    let dir = tempfile::tempdir().unwrap();
7905
    let root = dir.path();
7906
    Repo::init(&root.join("lib-origin")).unwrap();
7907
    let lib_url = root.join("lib-origin").to_string_lossy().to_string();
7908
    let lib = Repo::clone(&lib_url, &root.join("lib"))
7909
        .unwrap()
7910
        .with_home(root.join("home"));
7911
    write(&root.join("lib"), "lib.txt", b"v1\n");
7912
    let l1 = lib.commit("lib v1", &[]).unwrap();
7913
    assert!(lib.push("origin", false).unwrap()[0].ok);
7914
7915
    let app_dir = root.join("app");
7916
    let app = Repo::init(&app_dir).unwrap().with_home(root.join("home"));
7917
    write(&app_dir, "main.txt", b"app\n");
7918
    app.submodule_add(&lib_url, "libs/lib", None).unwrap();
7919
    app.commit("app with lib", &[]).unwrap();
7920
    // A second bookmark, and the main workspace on another.
7921
    app.bookmark_create("develop", None).unwrap();
7922
    app.bookmark_create("feature", None).unwrap();
7923
    let mut app = app;
7924
    app.bookmark_switch("feature", false).unwrap();
7925
    assert_eq!(app.config.bookmark, "feature");
7926
7927
    // The library's origin goes away: the subrepo must come from here.
7928
    std::fs::rename(root.join("lib-origin"), root.join("lib-origin-gone")).unwrap();
7929
    let heads = app.resolve_heads("develop").unwrap();
7930
    let ws = app
7931
        .workspace_add_on(&root.join("ws"), Some(&heads), Some("develop"))
7932
        .unwrap();
7933
    assert_eq!(
7934
        ws.config.bookmark, "develop",
7935
        "the new workspace is on develop"
7936
    );
7937
    assert_eq!(
7938
        app.config.bookmark, "feature",
7939
        "and this one stays on its own"
7940
    );
7941
    let sub = Repo::open(&root.join("ws/libs/lib")).unwrap();
7942
    assert_eq!(
7943
        sub.config.remotes["origin"], lib_url,
7944
        "its origin is the subrepo's URL"
7945
    );
7946
    assert_eq!(sub.bookmark_heads().unwrap(), vec![l1], "at its pin");
7947
    assert_eq!(
7948
        std::fs::read(root.join("ws/libs/lib/lib.txt")).unwrap(),
7949
        b"v1\n"
7950
    );
7951
}
7952
7953
/// Revsets (docs/revset_query_language.md): symbols, relations, set
7954
/// operators and the predicates, over a small graph with two heads and
7955
/// a rename.
7956
#[test]
7957
fn revsets_select_changes_by_relation_author_text_date_and_path() {
7958
    hermetic();
7959
    let dir = tempfile::tempdir().unwrap();
7960
    let root = dir.path();
7961
    let mut repo = Repo::init(root).unwrap().with_home(root.join("home"));
7962
    repo.create_identity("Ada", "[email protected]", IdentityScope::User)
7963
        .unwrap();
7964
    write(root, "src/a.rs", b"one\n");
7965
    let a = repo.commit("first: add a", &[]).unwrap();
7966
    write(root, "src/a.rs", b"one\ntwo\n");
7967
    let b = repo.commit("second: grow a", &[]).unwrap();
7968
    // A second head, independent of b: a new file on top of a.
7969
    repo.checkout(&[a], false, "checkout a").unwrap();
7970
    write(root, "docs/notes.md", b"notes\n");
7971
    let c = repo.commit("third: notes", &[]).unwrap();
7972
    // Back to both heads, then rename a.rs: the node keeps its identity.
7973
    repo.checkout(&repo.bookmark_heads().unwrap(), false, "checkout main")
7974
        .unwrap();
7975
    fs::remove_file(root.join("src/a.rs")).unwrap();
7976
    write(root, "src/z.rs", b"one\ntwo\n");
7977
    let d = repo.commit("fourth: rename a to z", &[]).unwrap();
7978
    let wc = repo.working_copy().unwrap().0;
7979
    // A saved revset is checked when set.
7980
    repo.set_user_config("revset.mine", "author(me) & ::main")
7981
        .unwrap();
7982
    assert!(repo.set_user_config("revset.bad", "a &").is_err());
7983
    let set = |src: &str| -> Vec<ChangeHash> {
7984
        let mut v = repo.revset(src).unwrap().hashes;
7985
        v.sort();
7986
        v
7987
    };
7988
    let sorted = |hs: &[ChangeHash]| -> Vec<ChangeHash> {
7989
        let mut v = hs.to_vec();
7990
        v.sort();
7991
        v
7992
    };
7993
7994
    // Changes commute: a new file depends on nothing and the rename on the
7995
    // file's creation, so the graph is a, b->a, d->a, c, and the working
7996
    // copy on the three heads b, c, d.
7997
    let heads = sorted(&repo.bookmark_heads().unwrap());
7998
    let meta = |h: &ChangeHash| repo.store().get_change_meta(h).unwrap();
7999
    assert!(heads.contains(&d) && heads.contains(&c));
8000
    // Symbols and closures.
8001
    assert_eq!(set("main"), heads);
8002
    assert_eq!(set("::main"), sorted(&[a, b, c, d]));
8003
    assert_eq!(set("@"), vec![wc]);
8004
    assert_eq!(set("::@"), sorted(&[a, b, c, d, wc]));
8005
    assert_eq!(set(&format!("::#{}", b.short(12))), sorted(&[a, b]));
8006
    assert_eq!(set(&format!("#{}::", a.short(12))), sorted(&[a, b, d, wc]));
8007
    assert_eq!(
8008
        set(&format!("#{}::#{}", a.short(12), b.short(12))),
8009
        sorted(&[a, b])
8010
    );
8011
    // Ranges: what main has beyond b, and `..` forms.
8012
    assert_eq!(set(&format!("#{}..main", b.short(12))), sorted(&[c, d]));
8013
    assert_eq!(set(&format!("#{}..", c.short(12))), sorted(&[a, b, d, wc]));
8014
    assert_eq!(set("..main"), sorted(&[a, b, c, d]));
8015
    // Operators and precedence: ~ binds tighter than &, & than |.
8016
    assert_eq!(
8017
        set(&format!("::main ~ #{}", d.short(12))),
8018
        sorted(&[a, b, c])
8019
    );
8020
    assert_eq!(
8021
        set(&format!("::main & #{} | #{}", b.short(12), c.short(12))),
8022
        sorted(&[b, c])
8023
    );
8024
    assert_eq!(set("all() ~ ::main"), vec![wc]);
8025
    // Relations.
8026
    let mut head_deps: Vec<ChangeHash> = heads.iter().flat_map(|h| meta(h).deps).collect();
8027
    head_deps.sort();
8028
    head_deps.dedup();
8029
    assert_eq!(set("deps(main)"), head_deps);
8030
    let on_a: Vec<ChangeHash> = [b, c, d]
8031
        .into_iter()
8032
        .filter(|h| meta(h).deps.contains(&a))
8033
        .collect();
8034
    assert_eq!(set(&format!("dependents(#{})", a.short(12))), sorted(&on_a));
8035
    assert_eq!(set("heads(::main)"), heads);
8036
    assert_eq!(set("roots(::main)"), sorted(&[a, c]));
8037
    assert_eq!(
8038
        set(&format!(
8039
            "heads(#{} | #{} | #{})",
8040
            a.short(12),
8041
            b.short(12),
8042
            c.short(12)
8043
        )),
8044
        sorted(&[b, c])
8045
    );
8046
    assert_eq!(set("latest(::main, 1)"), vec![d]);
8047
    assert_eq!(set("kind(working-copy)"), vec![wc]);
8048
    assert_eq!(set("none()"), vec![]);
8049
    // Predicates: author by name, email, key prefix and `me`.
8050
    let key = repo.config.author_key.unwrap();
8051
    assert_eq!(set("author(ada) & ::main"), sorted(&[a, b, c, d]));
8052
    assert_eq!(set("author(\"[email protected]\") & ::main").len(), 4);
8053
    assert_eq!(set(&format!("author({}) & ::main", key.short(12))).len(), 4);
8054
    assert_eq!(set("author(me) & ::main").len(), 4);
8055
    assert_eq!(set("author(nobody)"), vec![]);
8056
    assert_eq!(set("description(notes)"), vec![c]);
8057
    assert_eq!(set("description(\"rename a\")"), vec![d]);
8058
    assert_eq!(set("date(-1h..) & ::main").len(), 4);
8059
    assert_eq!(set("date(..2000-01-01)"), vec![]);
8060
    // touches follows the node through the rename, in the current state.
8061
    assert_eq!(set("touches(\"src/z.rs\")"), sorted(&[a, b, d]));
8062
    assert_eq!(set("touches(\"src/**\") & ::main"), sorted(&[a, b, d]));
8063
    assert_eq!(set("touches(\"docs/*\")"), vec![c]);
8064
    assert_eq!(set("touches(\"nothing/*\")"), vec![]);
8065
    // Newest first in the result order.
8066
    assert_eq!(repo.revset("::main").unwrap().hashes[0], d);
8067
    // The saved revset, and errors that say what is wrong.
8068
    assert_eq!(set("mine()").len(), 4);
8069
    let e = repo.revset("nosuch()").unwrap_err().to_string();
8070
    assert!(e.contains("unknown function nosuch()"), "{e}");
8071
    let e = repo.revset("main &").unwrap_err().to_string();
8072
    assert!(e.contains("at character"), "{e}");
8073
    let e = repo.revset("zzzz").unwrap_err().to_string();
8074
    assert!(e.contains("no change matches"), "{e}");
8075
    let e = repo
8076
        .revset_with_budget("::main", std::time::Duration::ZERO)
8077
        .unwrap_err()
8078
        .to_string();
8079
    assert!(e.contains("budget"), "{e}");
8080
    // The log entries carry the bookmark's heads and the working copy.
8081
    let entries = repo.log_revset("::@").unwrap();
8082
    assert!(entries[0].is_working_copy && entries.iter().any(|e| e.is_head && e.hash == d));
8083
    // Trust predicates (§2.4): nothing is signed yet (core.sign = seal, no
8084
    // push); then a signed change, a tag, and a revocation.
8085
    assert_eq!(set("unsigned() & ::main"), sorted(&[a, b, c, d]));
8086
    assert_eq!(set("signed_by(me)"), vec![]);
8087
    repo.sign_change(&d).unwrap();
8088
    assert_eq!(set("signed_by(me)"), vec![d]);
8089
    assert_eq!(set("signed_by([email protected])"), vec![d]);
8090
    assert_eq!(set(&format!("signed_by({})", key.short(12))), vec![d]);
8091
    assert_eq!(set("unsigned() & ::main"), sorted(&[a, b, c]));
8092
    assert_eq!(set("delegated()"), vec![]);
8093
    assert_eq!(set("revoked()"), vec![]);
8094
    assert_eq!(set("attested(tag)"), vec![]);
8095
    repo.tag_create("v1", &[b], "first").unwrap();
8096
    assert_eq!(set("attested(tag)"), sorted(&[a, b]));
8097
    assert_eq!(set("attested(tag) & unsigned()"), sorted(&[a, b]));
8098
    assert_eq!(set("attested(receipt)"), vec![]);
8099
    assert_eq!(set("built(test)"), vec![]);
8100
    let e = repo.revset("attested(seal)").unwrap_err().to_string();
8101
    assert!(e.contains("tag, receipt or ref"), "{e}");
8102
    repo.revoke_identity(&key, "test").unwrap();
8103
    assert_eq!(set("revoked()"), vec![d]);
8104
    assert_eq!(set("signed_by(me) ~ revoked()"), vec![]);
8105
    // independent(X, IN): what could ship without X. c and d neither
8106
    // depend on b nor are depended on by it; a is below, the working copy
8107
    // above.
8108
    assert_eq!(
8109
        set(&format!("independent(#{}, ::@)", b.short(12))),
8110
        sorted(&[c, d])
8111
    );
8112
    assert_eq!(
8113
        set(&format!("independent(#{}, ::main)", a.short(12))),
8114
        vec![c]
8115
    );
8116
    // conflicts(S): nothing conflicts yet; then two edits of one line.
8117
    assert_eq!(set("conflicts()"), vec![]);
8118
    assert_eq!(set("conflicts(main)"), vec![]);
8119
    // (The saved revset above edited the user config under the root:
8120
    // discard it.)
8121
    repo.checkout(&[a], true, "checkout a").unwrap();
8122
    write(root, "src/a.rs", b"one\nTWO\n");
8123
    let e = repo
8124
        .commit("fifth: the other edit of line two", &[])
8125
        .unwrap();
8126
    repo.checkout(&repo.bookmark_heads().unwrap(), true, "checkout main")
8127
        .unwrap();
8128
    let conflicted = repo.revset("conflicts()").unwrap().hashes;
8129
    assert!(
8130
        conflicted.contains(&e) && conflicted.contains(&b),
8131
        "{conflicted:?} should hold b and e"
8132
    );
8133
    assert!(!conflicted.contains(&c));
8134
    assert_eq!(set("conflicts() & author(nobody)"), vec![]);
8135
}
8136
8137
#[test]
8138
fn a_rotation_is_recorded_wherever_the_old_key_was_named() {
8139
    let dir = tempfile::tempdir().unwrap();
8140
    let root = dir.path();
8141
    let home = root.join("home");
8142
    // Ada's identity lives in the user file; repository `a` pins the same
8143
    // key in its own file, repository `b` names none.
8144
    let mut a = Repo::init(&root.join("a")).unwrap().with_home(&home);
8145
    let (key, _) = a
8146
        .create_identity("Ada", "[email protected]", IdentityScope::User)
8147
        .unwrap();
8148
    a.config.set("author.key", &key.to_hex()).unwrap();
8149
    a.save_config().unwrap();
8150
    let agent = SecretKey::generate().identity("Agent", "[email protected]", 1);
8151
    let r = a
8152
        .delegate_add(agent.clone(), crate::identity::Scope::CHANGES, None)
8153
        .unwrap();
8154
    assert_eq!(
8155
        read_config_file(&home.join("config.toml")).unwrap()["author.key"],
8156
        r.new.to_hex(),
8157
        "the user file follows"
8158
    );
8159
    assert_eq!(
8160
        read_config_file(&root.join("a/.oxy/config")).unwrap()["author.key"],
8161
        r.new.to_hex(),
8162
        "the pinning repository follows"
8163
    );
8164
    let b = Repo::init(&root.join("b")).unwrap().with_home(&home);
8165
    assert_eq!(
8166
        b.config.author_key,
8167
        Some(r.new),
8168
        "a checkout without a pin follows the user file"
8169
    );
8170
    // A repository-scoped identity leaves the user file alone.
8171
    let other_home = root.join("home2");
8172
    let mut c = Repo::init(&root.join("c")).unwrap().with_home(&other_home);
8173
    let (ck, _) = c
8174
        .create_identity("Cy", "[email protected]", IdentityScope::Repo)
8175
        .unwrap();
8176
    assert!(!other_home.join("config.toml").exists());
8177
    let r2 = c.rotate_identity().unwrap();
8178
    assert_ne!(r2.new, ck);
8179
    assert_eq!(
8180
        read_config_file(&root.join("c/.oxy/config")).unwrap()["author.key"],
8181
        r2.new.to_hex()
8182
    );
8183
    assert!(
8184
        !other_home.join("config.toml").exists(),
8185
        "a repository-scoped identity stays repository-scoped"
8186
    );
8187
    // Several delegates in one rotation; a repeat is refused.
8188
    let (d1, d2) = (
8189
        SecretKey::generate().identity("D1", "d1@x", 1),
8190
        SecretKey::generate().identity("D2", "d2@x", 1),
8191
    );
8192
    let r3 = c
8193
        .delegate_add_many(vec![d1.clone(), d2], crate::identity::Scope::CHANGES, None)
8194
        .unwrap();
8195
    assert_eq!(r3.identity.delegates.len(), 2);
8196
    assert!(c
8197
        .delegate_add(d1, crate::identity::Scope::CHANGES, None)
8198
        .is_err());
8199
}
8200
8201
/// Two unrelated histories that both add the same file, joined by two
8202
/// independent merges on two branches, then those branches merged: Git
8203
/// merges identical additions cleanly, and the import must too (#71,
8204
/// found in VS Code's history).
8205
#[test]
8206
fn git_import_joins_unrelated_histories_that_add_the_same_file() {
8207
    // Batches of one: every merge renders apart from the state, where a
8208
    // file whose graph the state had built came out empty (#71).
8209
    crate::repo::git::set_merge_batch_for_tests(Some(1));
8210
    hermetic();
8211
    if std::process::Command::new("git")
8212
        .arg("--version")
8213
        .output()
8214
        .is_err()
8215
    {
8216
        eprintln!("git not installed; skipping");
8217
        return;
8218
    }
8219
    let dir = tempfile::tempdir().unwrap();
8220
    let root = dir.path();
8221
    let g = root.join("src.git");
8222
    fs::create_dir_all(&g).unwrap();
8223
    let git = |args: &[&str]| -> String {
8224
        let out = std::process::Command::new("git")
8225
            .arg("-C")
8226
            .arg(&g)
8227
            .args([
8228
                "-c",
8229
                "user.name=Grace",
8230
                "-c",
8231
                "[email protected]",
8232
                "-c",
8233
                "commit.gpgsign=false",
8234
            ])
8235
            .args(args)
8236
            .output()
8237
            .unwrap();
8238
        assert!(
8239
            out.status.success(),
8240
            "git {args:?}: {}",
8241
            String::from_utf8_lossy(&out.stderr)
8242
        );
8243
        String::from_utf8_lossy(&out.stdout).trim().to_string()
8244
    };
8245
    let text = b"/* header */\nconst a = 1;\nconst b = 2;\n";
8246
    // History A: main.
8247
    git(&["init", "-q", "-b", "main"]);
8248
    write(&g, "gulpfile.js", text);
8249
    write(&g, "a.txt", b"a\n");
8250
    git(&["add", "."]);
8251
    git(&["commit", "-q", "-m", "A root"]);
8252
    // History B: an unrelated root adding the same file, identical.
8253
    git(&["checkout", "-q", "--orphan", "fork"]);
8254
    git(&["rm", "-q", "-r", "--cached", "."]);
8255
    for f in ["gulpfile.js", "a.txt"] {
8256
        let _ = fs::remove_file(g.join(f));
8257
    }
8258
    write(&g, "gulpfile.js", text);
8259
    write(&g, "b.txt", b"b\n");
8260
    git(&["add", "."]);
8261
    git(&["commit", "-q", "-m", "B root"]);
8262
    // Two branches from main, each joining B on its own.
8263
    git(&["checkout", "-q", "-b", "one", "main"]);
8264
    git(&[
8265
        "merge",
8266
        "-q",
8267
        "--no-ff",
8268
        "--allow-unrelated-histories",
8269
        "-m",
8270
        "join on one",
8271
        "fork",
8272
    ]);
8273
    git(&["checkout", "-q", "-b", "two", "main"]);
8274
    write(&g, "a.txt", b"a\ntwo\n");
8275
    git(&["commit", "-q", "-am", "work on two"]);
8276
    git(&[
8277
        "merge",
8278
        "-q",
8279
        "--no-ff",
8280
        "--allow-unrelated-histories",
8281
        "-m",
8282
        "join on two",
8283
        "fork",
8284
    ]);
8285
    // Then the two joins meet, and the file is reformatted after.
8286
    git(&["checkout", "-q", "main"]);
8287
    git(&["merge", "-q", "--no-ff", "-m", "merge one", "one"]);
8288
    git(&["merge", "-q", "--no-ff", "-m", "merge two", "two"]);
8289
    write(
8290
        &g,
8291
        "gulpfile.js",
8292
        b"/* header */\nconst a = 1;\nconst b = 3;\n",
8293
    );
8294
    git(&["commit", "-q", "-am", "after"]);
8295
8296
    let dest = root.join("dest");
8297
    let repo = Repo::init(&dest).unwrap().with_home(root.join("home"));
8298
    repo.import_git(&g, "main").unwrap();
8299
    let v = repo.verify_git_import(&g, "main").unwrap();
8300
    assert!(v.mismatches.is_empty(), "{:?}", v.mismatches);
8301
    assert_eq!(
8302
        fs::read(dest.join("gulpfile.js")).unwrap(),
8303
        b"/* header */\nconst a = 1;\nconst b = 3;\n"
8304
    );
8305
}
8306
8307
/// As above, but the two joins keep different copies (each branch had a
8308
/// different version when it joined), and later work edits each copy:
8309
/// the shape of VS Code's c67ef57cda90 (#71).
8310
#[test]
8311
fn git_import_joins_where_each_join_kept_a_different_copy() {
8312
    // Batches of one: every merge renders apart from the state, where a
8313
    // file whose graph the state had built came out empty (#71).
8314
    crate::repo::git::set_merge_batch_for_tests(Some(1));
8315
    hermetic();
8316
    if std::process::Command::new("git")
8317
        .arg("--version")
8318
        .output()
8319
        .is_err()
8320
    {
8321
        eprintln!("git not installed; skipping");
8322
        return;
8323
    }
8324
    let dir = tempfile::tempdir().unwrap();
8325
    let root = dir.path();
8326
    let g = root.join("src.git");
8327
    fs::create_dir_all(&g).unwrap();
8328
    let run = |args: &[&str]| {
8329
        std::process::Command::new("git")
8330
            .arg("-C")
8331
            .arg(&g)
8332
            .args([
8333
                "-c",
8334
                "user.name=Grace",
8335
                "-c",
8336
                "[email protected]",
8337
                "-c",
8338
                "commit.gpgsign=false",
8339
            ])
8340
            .args(args)
8341
            .output()
8342
            .unwrap()
8343
    };
8344
    let git = |args: &[&str]| -> String {
8345
        let out = run(args);
8346
        assert!(
8347
            out.status.success(),
8348
            "git {args:?}: {}",
8349
            String::from_utf8_lossy(&out.stderr)
8350
        );
8351
        String::from_utf8_lossy(&out.stdout).trim().to_string()
8352
    };
8353
    git(&["init", "-q", "-b", "main"]);
8354
    write(
8355
        &g,
8356
        "gulpfile.js",
8357
        b"/* header */\nconst a = 1;\nconst b = 2;\n",
8358
    );
8359
    git(&["add", "."]);
8360
    git(&["commit", "-q", "-m", "A root"]);
8361
    write(
8362
        &g,
8363
        "gulpfile.js",
8364
        b"/* header */\nconst a = 1;\n\nconst b = 2;\n",
8365
    );
8366
    git(&["commit", "-q", "-am", "whitespace"]);
8367
    git(&["checkout", "-q", "--orphan", "fork"]);
8368
    git(&["rm", "-q", "-r", "--cached", "."]);
8369
    let _ = fs::remove_file(g.join("gulpfile.js"));
8370
    write(
8371
        &g,
8372
        "gulpfile.js",
8373
        b"/* header */\nconst a = 1;\nconst b = 2;\nconst c = 3;\n",
8374
    );
8375
    git(&["add", "."]);
8376
    git(&["commit", "-q", "-m", "B root"]);
8377
    // Branch one joins B keeping main's copy; branch two keeps B's.
8378
    for (branch, keep) in [("one", "ours"), ("two", "theirs")] {
8379
        git(&["checkout", "-q", "-b", branch, "main"]);
8380
        let _ = run(&[
8381
            "merge",
8382
            "-q",
8383
            "--no-ff",
8384
            "--allow-unrelated-histories",
8385
            "-m",
8386
            "join",
8387
            "fork",
8388
        ]);
8389
        git(&["checkout", &format!("--{keep}"), "gulpfile.js"]);
8390
        git(&["add", "gulpfile.js"]);
8391
        git(&["commit", "-q", "-m", &format!("join on {branch}")]);
8392
    }
8393
    // Each branch then edits its copy.
8394
    git(&["checkout", "-q", "one"]);
8395
    write(
8396
        &g,
8397
        "gulpfile.js",
8398
        b"/* header */\nconst a = 1;\n\nconst b = 2;\n// tslint\n",
8399
    );
8400
    git(&["commit", "-q", "-am", "tslint on one"]);
8401
    git(&["checkout", "-q", "two"]);
8402
    write(
8403
        &g,
8404
        "gulpfile.js",
8405
        b"/* header */\nconst a = 1;\nconst b = 2;\nconst c = 3;\n// fmt\n",
8406
    );
8407
    write(&g, "extra.txt", b"x\n");
8408
    write(&g, "more.txt", b"m\n");
8409
    git(&["add", "."]);
8410
    git(&["commit", "-q", "-am", "fmt on two"]);
8411
    // They meet: resolved by hand.
8412
    git(&["checkout", "-q", "one"]);
8413
    let _ = run(&["merge", "-q", "--no-ff", "-m", "merge two", "two"]);
8414
    write(
8415
        &g,
8416
        "gulpfile.js",
8417
        b"/* header */\nconst a = 1;\nconst b = 2;\nconst c = 3;\n// tslint\n// fmt\n",
8418
    );
8419
    git(&["add", "gulpfile.js"]);
8420
    git(&["commit", "-q", "-m", "merge two into one"]);
8421
8422
    let dest = root.join("dest");
8423
    let repo = Repo::init(&dest).unwrap().with_home(root.join("home"));
8424
    repo.import_git(&g, "one").unwrap();
8425
    let v = repo.verify_git_import(&g, "one").unwrap();
8426
    assert!(v.mismatches.is_empty(), "{:?}", v.mismatches);
8427
}
8428
8429
/// oxygen#68: on a store that is not this disk's directory, the operation
8430
/// head is the store's reference record, moved by compare-and-swap. Two
8431
/// handles recording from the same head both get through, merged; a swap
8432
/// from a stale version is refused; a second repository cannot start on a
8433
/// store that already holds one.
8434
#[test]
8435
fn over_a_store_the_operation_head_moves_by_compare_and_swap() {
8436
    use crate::strata::{MemoryStore, Store as _};
8437
    let backend = std::sync::Arc::new(MemoryStore::new());
8438
    crate::store::TEST_BACKEND.with(|t| *t.borrow_mut() = Some(backend.clone()));
8439
    let dir = tempfile::tempdir().unwrap();
8440
    let a = Repo::init(dir.path()).unwrap();
8441
    assert!(
8442
        !dir.path().join(".oxy/ops/head").exists(),
8443
        "the head is not a file"
8444
    );
8445
    let (h0, op0) = a.head_op().unwrap();
8446
    let record = backend
8447
        .read_ref(HEAD_RECORD)
8448
        .unwrap()
8449
        .expect("the head is the store's record");
8450
    assert_eq!(String::from_utf8(record.0).unwrap(), h0.to_hex());
8451
8452
    let b = Repo::open(dir.path()).unwrap();
8453
    let state = a.store.put_state(&StateObject::new(vec![])).unwrap();
8454
    let mut va = op0.view.clone();
8455
    va.bookmarks.insert("from-a".into(), state);
8456
    let mut vb = op0.view.clone();
8457
    vb.bookmarks.insert("from-b".into(), state);
8458
    let rb = b.record_op(&[h0], "bookmark from-b", vb).unwrap();
8459
    assert_eq!(b.head_ref().unwrap(), rb);
8460
    // a recorded from h0 too: the head moved, so the two are merged.
8461
    let ra = a.record_op(&[h0], "bookmark from-a", va).unwrap();
8462
    let (head, op) = Repo::open(dir.path()).unwrap().head_op().unwrap();
8463
    assert_eq!(head, ra);
8464
    assert!(
8465
        op.command.ends_with("(merged with a concurrent operation)"),
8466
        "{}",
8467
        op.command
8468
    );
8469
    assert_eq!(op.parents, vec![rb, op.parents[1]]);
8470
    assert!(op.view.bookmarks.contains_key("from-a") && op.view.bookmarks.contains_key("from-b"));
8471
8472
    // A swap from a version that is no longer current moves nothing.
8473
    let (h, v) = a.read_head().unwrap();
8474
    assert!(b.swap_head(&rb, v.as_ref()).unwrap());
8475
    assert!(!a.swap_head(&h, v.as_ref()).unwrap(), "stale");
8476
    a.refresh().unwrap();
8477
    assert_eq!(a.head_ref().unwrap(), rb);
8478
8479
    let other = tempfile::tempdir().unwrap();
8480
    let err = Repo::init(other.path())
8481
        .err()
8482
        .expect("the store already holds a log")
8483
        .to_string();
8484
    assert!(
8485
        err.contains("already holds a repository's operation log"),
8486
        "{err}"
8487
    );
8488
    crate::store::TEST_BACKEND.with(|t| *t.borrow_mut() = None);
8489
}
8490
8491
/// oxygen#68: a repository kept on a store (`storage.url`) holds its
8492
/// objects and operation head there, with `.oxy/cache` in front: it works
8493
/// as one on disk does, reopens, and survives losing its cache.
8494
#[test]
8495
fn a_repository_runs_on_a_store_with_a_cache_in_front() {
8496
    hermetic();
8497
    if std::env::var_os("OXY_STORE_BACKEND").is_some() {
8498
        return;
8499
    }
8500
    let dir = tempfile::tempdir().unwrap();
8501
    let (root, bucket) = (dir.path().join("work"), dir.path().join("bucket"));
8502
    let url = format!("dir://{}", bucket.display());
8503
    let repo = Repo::init_on(&root, [7; 16], Some(&url)).unwrap();
8504
    assert_eq!(repo.config.storage_url.as_deref(), Some(url.as_str()));
8505
    write(&root, "a.txt", b"one\n");
8506
    let h1 = repo.commit("First", &[]).unwrap();
8507
    write(&root, "a.txt", b"one\ntwo\n");
8508
    let h2 = repo.commit("Second", &[]).unwrap();
8509
    assert!(
8510
        !root.join(".oxy/ops/head").exists(),
8511
        "the head is in the store"
8512
    );
8513
    assert!(bucket.join("ops/head").is_file());
8514
    assert!(root.join(".oxy/cache").is_dir());
8515
    drop(repo);
8516
8517
    // Reopened, and again with no cache at all: everything comes from the store.
8518
    for drop_cache in [false, true] {
8519
        if drop_cache {
8520
            std::fs::remove_dir_all(root.join(".oxy/cache")).unwrap();
8521
        }
8522
        let repo = Repo::open(&root).unwrap();
8523
        let log: Vec<String> = repo
8524
            .op_log()
8525
            .unwrap()
8526
            .into_iter()
8527
            .map(|(_, op)| op.command)
8528
            .collect();
8529
        assert!(log.len() >= 3, "{log:?}");
8530
        assert_eq!(repo.store().get_change(&h1).unwrap().message, "First");
8531
        let heads = repo
8532
            .store()
8533
            .get_state(&repo.view().unwrap().bookmarks["main"])
8534
            .unwrap()
8535
            .heads;
8536
        assert_eq!(heads, vec![h2]);
8537
        assert_eq!(
8538
            repo.load_state(&heads).unwrap().materialize().files.len(),
8539
            1
8540
        );
8541
    }
8542
8543
    // A second repository cannot start on the same store.
8544
    let err = Repo::init_on(&dir.path().join("other"), [8; 16], Some(&url))
8545
        .err()
8546
        .unwrap()
8547
        .to_string();
8548
    assert!(
8549
        err.contains("already holds a repository's operation log"),
8550
        "{err}"
8551
    );
8552
    let err = Repo::init_on(&dir.path().join("third"), [9; 16], Some("nope://x"))
8553
        .err()
8554
        .unwrap()
8555
        .to_string();
8556
    assert!(err.contains("cannot open that kind of store"), "{err}");
8557
}
8558
8559
/// oxygen#75: the prompt's quick check agrees with status in a repository
8560
/// with a subrepo: clean after a commit, dirty when the subrepo moves to
8561
/// another state, clean again once that pin is committed. (It compared the
8562
/// subrepo's directory as if it were a file, so it was always dirty.)
8563
#[test]
8564
fn the_quick_dirty_check_compares_a_subrepo_by_its_pin() {
8565
    hermetic();
8566
    let dir = tempfile::tempdir().unwrap();
8567
    let root = dir.path();
8568
    let _lib_origin = Repo::init(&root.join("lib-origin")).unwrap();
8569
    let lib_url = root.join("lib-origin").to_string_lossy().to_string();
8570
    let lib = Repo::clone(&lib_url, &root.join("lib"))
8571
        .unwrap()
8572
        .with_home(root.join("home"));
8573
    write(&root.join("lib"), "lib.txt", b"v1\n");
8574
    lib.commit("lib v1", &[]).unwrap();
8575
    assert!(lib.push("origin", false).unwrap()[0].ok);
8576
    let app_dir = root.join("app");
8577
    let app = Repo::init(&app_dir).unwrap().with_home(root.join("home"));
8578
    write(&app_dir, "main.txt", b"app\n");
8579
    app.submodule_add(&lib_url, "libs/lib", None).unwrap();
8580
    app.commit("app with lib", &[]).unwrap();
8581
    // Out of the racy window, so the stat-only path decides.
8582
    std::thread::sleep(std::time::Duration::from_millis(2100));
8583
    let reopen = || Repo::open(&app_dir).unwrap();
8584
    assert_eq!(
8585
        reopen().quick_dirty().unwrap(),
8586
        Some(false),
8587
        "clean, as status says"
8588
    );
8589
    let nested = Repo::open(&app_dir.join("libs/lib")).unwrap();
8590
    write(&app_dir.join("libs/lib"), "lib.txt", b"v2\n");
8591
    nested.commit("lib v2", &[]).unwrap();
8592
    assert_eq!(
8593
        reopen().quick_dirty().unwrap(),
8594
        Some(true),
8595
        "the subrepo moved"
8596
    );
8597
    reopen().commit("pin lib v2", &[]).unwrap();
8598
    std::thread::sleep(std::time::Duration::from_millis(2100));
8599
    assert_eq!(
8600
        reopen().quick_dirty().unwrap(),
8601
        Some(false),
8602
        "the new pin is committed"
8603
    );
8604
}
8605
8606
#[test]
8607
fn a_module_entry_that_was_never_added_is_reported_as_unpinned() {
8608
    // oxygen#72: a .oxymodules section with no subrepo behind it.
8609
    hermetic();
8610
    let dir = tempfile::tempdir().unwrap();
8611
    let root = dir.path();
8612
    let _lib_origin = Repo::init(&root.join("lib-origin")).unwrap();
8613
    let lib_url = root.join("lib-origin").to_string_lossy().to_string();
8614
    let lib = Repo::clone(&lib_url, &root.join("lib"))
8615
        .unwrap()
8616
        .with_home(root.join("home"));
8617
    write(&root.join("lib"), "lib.txt", b"v1\n");
8618
    lib.commit("lib v1", &[]).unwrap();
8619
    assert!(lib.push("origin", false).unwrap()[0].ok);
8620
    let app_dir = root.join("app");
8621
    let app = Repo::init(&app_dir).unwrap().with_home(root.join("home"));
8622
    write(
8623
        &app_dir,
8624
        ".oxymodules",
8625
        format!("[libs/lib]\nurl = {lib_url}\n").as_bytes(),
8626
    );
8627
    let unpinned = app.unpinned_modules().unwrap();
8628
    assert_eq!(unpinned.len(), 1);
8629
    assert_eq!(unpinned[0].0, "libs/lib");
8630
    assert_eq!(unpinned[0].1.url, lib_url);
8631
    assert!(app.submodule_update(true, &[]).unwrap().is_empty());
8632
    app.submodule_add(&lib_url, "libs/lib", None).unwrap();
8633
    assert!(app.unpinned_modules().unwrap().is_empty(), "added now");
8634
}
8635
8636
#[test]
8637
fn the_bookmark_revset_function_names_only_bookmarks() {
8638
    // oxygen#73: bookmark(NAME) is a bookmark's heads, never a tag or prefix.
8639
    hermetic();
8640
    let dir = tempfile::tempdir().unwrap();
8641
    let repo = Repo::init(dir.path()).unwrap();
8642
    write(dir.path(), "a.txt", b"a\n");
8643
    let a = repo.commit("A", &[]).unwrap();
8644
    write(dir.path(), "b.txt", b"b\n");
8645
    let b = repo.commit("B", &[]).unwrap();
8646
    let mut heads = repo.revset("bookmark(main)").unwrap().hashes;
8647
    heads.sort();
8648
    let mut want = repo.bookmark_heads().unwrap();
8649
    want.sort();
8650
    assert_eq!(heads, want);
8651
    assert!(heads.contains(&b));
8652
    assert_eq!(repo.revset("main").unwrap().hashes.len(), heads.len());
8653
    // A change prefix is a symbol, not a bookmark.
8654
    let prefix = repo.store().get_change_meta(&a).unwrap().change_id.short(8);
8655
    assert!(repo.revset(&prefix).is_ok());
8656
    let e = repo
8657
        .revset(&format!("bookmark({prefix})"))
8658
        .unwrap_err()
8659
        .to_string();
8660
    assert!(e.contains("no such bookmark"), "{e}");
8661
}
8662
8663
#[test]
8664
fn carrying_work_over_a_subrepo_already_at_the_target_pin_is_no_conflict() {
8665
    // oxygen#74: a stale state with .oxymodules but no pin, a newer one
8666
    // pinning the subrepo, and the nested repository on disk at that pin.
8667
    hermetic();
8668
    let dir = tempfile::tempdir().unwrap();
8669
    let root = dir.path();
8670
    let _lib_origin = Repo::init(&root.join("lib-origin")).unwrap();
8671
    let lib_url = root.join("lib-origin").to_string_lossy().to_string();
8672
    let lib = Repo::clone(&lib_url, &root.join("lib"))
8673
        .unwrap()
8674
        .with_home(root.join("home"));
8675
    write(&root.join("lib"), "lib.txt", b"v1\n");
8676
    lib.commit("lib v1", &[]).unwrap();
8677
    assert!(lib.push("origin", false).unwrap()[0].ok);
8678
    let app_dir = root.join("app");
8679
    let app = Repo::init(&app_dir).unwrap().with_home(root.join("home"));
8680
    write(&app_dir, "main.txt", b"app\n");
8681
    app.submodule_add(&lib_url, "libs/lib", None).unwrap();
8682
    // The stale state: registered in .oxymodules, never pinned.
8683
    fs::rename(app_dir.join("libs/lib"), root.join("aside")).unwrap();
8684
    app.commit("initial", &[]).unwrap();
8685
    let stale = app.bookmark_heads().unwrap();
8686
    fs::rename(root.join("aside"), app_dir.join("libs/lib")).unwrap();
8687
    app.commit("pin lib", &[]).unwrap();
8688
    let newer = app.bookmark_heads().unwrap();
8689
    app.checkout(&stale, false, "test").unwrap();
8690
    write(&app_dir, "notes.txt", b"mine\n");
8691
    let (_, carried) = app.checkout_carry(&newer, "main", "test").unwrap();
8692
    assert_eq!(carried, vec!["notes.txt".to_string()]);
8693
    assert!(app_dir.join("notes.txt").exists());
8694
}
8695
8696
#[test]
8697
fn a_bookmark_only_behind_its_remote_catches_up() {
8698
    // oxygen#74: switch takes the remote's state rather than a stale one.
8699
    hermetic();
8700
    let dir = tempfile::tempdir().unwrap();
8701
    let root = dir.path();
8702
    let _origin = Repo::init(&root.join("origin")).unwrap();
8703
    let url = root.join("origin").to_string_lossy().to_string();
8704
    let one = Repo::clone(&url, &root.join("one"))
8705
        .unwrap()
8706
        .with_home(root.join("home"));
8707
    write(&root.join("one"), "a.txt", b"a\n");
8708
    one.commit("A", &[]).unwrap();
8709
    assert!(one.push("origin", false).unwrap()[0].ok);
8710
    let two = Repo::clone(&url, &root.join("two"))
8711
        .unwrap()
8712
        .with_home(root.join("home"));
8713
    write(&root.join("two"), "b.txt", b"b\n");
8714
    two.commit("B", &[]).unwrap();
8715
    assert!(two.push("origin", false).unwrap()[0].ok);
8716
    assert_eq!(one.catch_up_bookmark("main").unwrap(), None, "not fetched");
8717
    one.fetch("origin").unwrap();
8718
    assert_eq!(one.catch_up_bookmark("main").unwrap(), Some(1));
8719
    assert_eq!(one.bookmarks().unwrap()[0].behind, Some(0));
8720
    // Local work the remote lacks: left alone.
8721
    write(&root.join("one"), "c.txt", b"c\n");
8722
    one.commit("C", &[]).unwrap();
8723
    write(&root.join("two"), "d.txt", b"d\n");
8724
    two.commit("D", &[]).unwrap();
8725
    assert!(two.push("origin", false).unwrap()[0].ok);
8726
    one.fetch("origin").unwrap();
8727
    assert_eq!(one.catch_up_bookmark("main").unwrap(), None);
8728
}
8729
8730
#[test]
8731
fn a_bookmark_is_compared_with_a_remote_that_has_it_when_there_is_no_origin() {
8732
    // oxygen#83: remotes earth and gcs, origin removed.
8733
    hermetic();
8734
    let dir = tempfile::tempdir().unwrap();
8735
    let root = dir.path();
8736
    let _up = Repo::init(&root.join("up")).unwrap();
8737
    let url = root.join("up").to_string_lossy().to_string();
8738
    let other = Repo::clone(&url, &root.join("other"))
8739
        .unwrap()
8740
        .with_home(root.join("home"));
8741
    write(&root.join("other"), "a.txt", b"a\n");
8742
    other.commit("a", &[]).unwrap();
8743
    assert!(other.push("origin", false).unwrap()[0].ok);
8744
    let mut one = Repo::clone(&url, &root.join("one"))
8745
        .unwrap()
8746
        .with_home(root.join("home"));
8747
    one.config.set("remote.earth.url", &url).unwrap();
8748
    one.config.set("remote.gcs.url", &url).unwrap();
8749
    one.config.set("remote.origin.url", "").unwrap();
8750
    one.save_config().unwrap();
8751
    write(&root.join("other"), "b.txt", b"b\n");
8752
    other.commit("b", &[]).unwrap();
8753
    assert!(other.push("origin", false).unwrap()[0].ok);
8754
    one.fetch("earth").unwrap();
8755
    let b = one
8756
        .bookmarks()
8757
        .unwrap()
8758
        .into_iter()
8759
        .find(|b| b.name == "main")
8760
        .unwrap();
8761
    assert_eq!(
8762
        (b.remote.as_deref(), b.behind),
8763
        (Some("earth"), Some(1)),
8764
        "a stale origin copy is not used"
8765
    );
8766
    assert_eq!(
8767
        one.default_remote(),
8768
        "origin",
8769
        "no default chosen among several"
8770
    );
8771
    let e = one.pull(&one.default_remote()).unwrap_err().to_string();
8772
    assert!(e.contains("earth, gcs") && e.contains("core.remote"), "{e}");
8773
    one.config.set("core.remote", "earth").unwrap();
8774
    assert_eq!(one.default_remote(), "earth");
8775
}
8776
8777
#[test]
8778
fn a_missing_author_identity_says_how_to_fix_it() {
8779
    // oxygen#82: an agent home's author.key naming an identity the
8780
    // repository does not hold.
8781
    hermetic();
8782
    let dir = tempfile::tempdir().unwrap();
8783
    let mut repo = Repo::init(dir.path()).unwrap();
8784
    let missing = KeyId::from_hex(&"ab".repeat(32)).unwrap();
8785
    repo.config.set("author.key", &missing.to_hex()).unwrap();
8786
    let e = repo.identity(&missing).unwrap_err().to_string();
8787
    assert!(
8788
        e.contains("this repository has no identity") && e.contains("oxy config author.key"),
8789
        "{e}"
8790
    );
8791
    assert!(e.contains("this repository's config"), "{e}");
8792
}
8793
8794
#[test]
8795
fn a_working_copy_behind_its_bookmark_is_flagged_and_pull_brings_it_up() {
8796
    // oxygen#89 (supermarioland, 2026-10-09): the bookmark moved on without
8797
    // the working copy, a pull with nothing new left it there, and status
8798
    // said "clean".
8799
    hermetic();
8800
    let dir = tempfile::tempdir().unwrap();
8801
    let root = dir.path();
8802
    let _up = Repo::init(&root.join("up")).unwrap();
8803
    let url = root.join("up").to_string_lossy().to_string();
8804
    let other = Repo::clone(&url, &root.join("other"))
8805
        .unwrap()
8806
        .with_home(root.join("home"));
8807
    write(&root.join("other"), "a.txt", b"a\n");
8808
    other.commit("a", &[]).unwrap();
8809
    assert!(other.push("origin", false).unwrap()[0].ok);
8810
    let one = Repo::clone(&url, &root.join("one"))
8811
        .unwrap()
8812
        .with_home(root.join("home"));
8813
    write(&root.join("other"), "b.txt", b"b\n");
8814
    other.commit("b", &[]).unwrap();
8815
    assert!(other.push("origin", false).unwrap()[0].ok);
8816
    one.fetch("origin").unwrap();
8817
    // The bookmark moves; the working copy does not.
8818
    let theirs = one.resolve_heads("origin/main").unwrap();
8819
    one.bookmark_set("main", &theirs).unwrap();
8820
    assert!(!root.join("one/b.txt").exists());
8821
    assert_eq!(one.working_copy_behind().unwrap(), Some(1));
8822
    let r = one.pull("origin").unwrap();
8823
    assert!(
8824
        !r.changed && r.checked_out,
8825
        "nothing new, but the working copy caught up"
8826
    );
8827
    assert!(root.join("one/b.txt").exists());
8828
    assert_eq!(one.working_copy_behind().unwrap(), None);
8829
}
8830
8831
#[test]
8832
fn touched_nodes_cache_answers_as_the_changes_do() {
8833
    hermetic();
8834
    let dir = tempfile::tempdir().unwrap();
8835
    let repo = Repo::init(dir.path()).unwrap();
8836
    write(dir.path(), "a.txt", b"one\n");
8837
    write(dir.path(), "b.txt", b"x\n");
8838
    repo.snapshot("t").unwrap();
8839
    let c1 = repo.commit("first", &[]).unwrap();
8840
    write(dir.path(), "b.txt", b"y\n");
8841
    repo.snapshot("t").unwrap();
8842
    repo.commit("b only", &[]).unwrap();
8843
    fs::rename(dir.path().join("a.txt"), dir.path().join("c.txt")).unwrap();
8844
    write(dir.path(), "c.txt", b"one\ntwo\n");
8845
    repo.snapshot("t").unwrap();
8846
    let c3 = repo.commit("rename and edit", &[]).unwrap();
8847
    // Uncommitted work, so the working copy touches a file too.
8848
    write(dir.path(), "c.txt", b"one\ntwo\nthree\n");
8849
    repo.snapshot("t").unwrap();
8850
8851
    let path = dir.path().join(".oxy/index/touched");
8852
    let hashes = |es: Vec<LogEntry>| es.iter().map(|e| e.hash).collect::<Vec<_>>();
8853
    let cold = hashes(repo.log_for_path("c.txt").unwrap());
8854
    assert!(path.exists(), "the first query writes the cache");
8855
    let warm = hashes(repo.log_for_path("c.txt").unwrap());
8856
    assert_eq!(cold, warm, "the cache answers as the changes do");
8857
    let (wc, _) = repo.working_copy().unwrap();
8858
    assert_eq!(
8859
        cold,
8860
        vec![wc, c3, c1],
8861
        "renames followed, the working copy included"
8862
    );
8863
8864
    // Working-copy changes are not kept: they are replaced by every snapshot.
8865
    let cached = super::touched::read_touched_for_test(&fs::read(&path).unwrap()).unwrap();
8866
    assert!(!cached.contains(&wc), "a working-copy change is not cached");
8867
    assert!(cached.contains(&c1) && cached.contains(&c3));
8868
8869
    // A damaged cache is ignored, not trusted.
8870
    let mut bytes = fs::read(&path).unwrap();
8871
    let last = bytes.len() - 40;
8872
    bytes[last] ^= 1;
8873
    fs::write(&path, &bytes).unwrap();
8874
    assert_eq!(hashes(repo.log_for_path("c.txt").unwrap()), cold);
8875
    let touches = repo.log_revset("touches(\"c.txt\") ~ @").unwrap();
8876
    assert_eq!(hashes(touches), vec![c3, c1]);
8877
}
8878
8879
/// oxygen#88 (vscode 9ab2056393c8): two lines of history that each move a
8880
/// file back where it was leave two placements at one place, which the
8881
/// tree shows as one file. Removing it, and then its directory, retires
8882
/// both, so no copy is left under a directory that is gone.
8883
#[test]
8884
fn git_import_removes_every_copy_of_a_file_at_one_place() {
8885
    hermetic();
8886
    if std::process::Command::new("git")
8887
        .arg("--version")
8888
        .output()
8889
        .is_err()
8890
    {
8891
        eprintln!("git not installed; skipping");
8892
        return;
8893
    }
8894
    let dir = tempfile::tempdir().unwrap();
8895
    let root = dir.path();
8896
    let g = root.join("src.git");
8897
    fs::create_dir_all(&g).unwrap();
8898
    let git = |args: &[&str]| {
8899
        let out = std::process::Command::new("git")
8900
            .arg("-C")
8901
            .arg(&g)
8902
            .args([
8903
                "-c",
8904
                "user.name=Grace",
8905
                "-c",
8906
                "[email protected]",
8907
                "-c",
8908
                "commit.gpgsign=false",
8909
            ])
8910
            .args(args)
8911
            .output()
8912
            .unwrap();
8913
        assert!(
8914
            out.status.success(),
8915
            "git {args:?}: {}",
8916
            String::from_utf8_lossy(&out.stderr)
8917
        );
8918
    };
8919
    git(&["init", "-q", "-b", "main"]);
8920
    write(&g, "d/list.txt", b"one\ntwo\nthree\nfour\n");
8921
    write(&g, "keep.txt", b"k\n");
8922
    git(&["add", "."]);
8923
    git(&["commit", "-qm", "base"]);
8924
    fs::create_dir_all(g.join("d/sub")).unwrap();
8925
    git(&["mv", "d/list.txt", "d/sub/list.txt"]);
8926
    git(&["commit", "-qm", "into sub"]);
8927
    git(&["checkout", "-qb", "side"]);
8928
    git(&["mv", "d/sub/list.txt", "d/list.txt"]);
8929
    git(&["commit", "-qm", "back, on side"]);
8930
    git(&["checkout", "-q", "main"]);
8931
    git(&["mv", "d/sub/list.txt", "d/list.txt"]);
8932
    git(&["commit", "-qm", "back, on main"]);
8933
    git(&["merge", "-q", "--no-edit", "side"]);
8934
    git(&["rm", "-rq", "d"]);
8935
    git(&["commit", "-qm", "d goes"]);
8936
8937
    let repo = Repo::init(&root.join("o")).unwrap();
8938
    repo.import_git(&g, "main").unwrap();
8939
    let v = repo.verify_git_import(&g, "main").unwrap();
8940
    assert!(v.mismatches.is_empty(), "{:?}", v.mismatches);
8941
    let st = repo
8942
        .load_state_history(&repo.bookmark_heads().unwrap())
8943
        .unwrap();
8944
    let view = st.tree().view();
8945
    assert!(view.conflicts.is_empty(), "{:?}", view.conflicts);
8946
    assert_eq!(view.entries.keys().collect::<Vec<_>>(), vec!["keep.txt"]);
8947
}
8948
8949
/// oxygen#94: a state index's file histories are read, and checked by
8950
/// their own hashes, only when a file is built. One found damaged is an
8951
/// error that says so, the index is removed, and the next read rebuilds it.
8952
#[test]
8953
fn a_damaged_file_history_in_the_state_index_is_rebuilt() {
8954
    hermetic();
8955
    let dir = tempfile::tempdir().unwrap();
8956
    let repo = Repo::init(dir.path()).unwrap();
8957
    for i in 0..6 {
8958
        write(
8959
            dir.path(),
8960
            &format!("f{i}.txt"),
8961
            format!("one {i}\n").as_bytes(),
8962
        );
8963
    }
8964
    repo.snapshot("t").unwrap();
8965
    repo.commit("first", &[]).unwrap();
8966
    for i in 0..6 {
8967
        write(
8968
            dir.path(),
8969
            &format!("f{i}.txt"),
8970
            format!("one {i}\ntwo\n").as_bytes(),
8971
        );
8972
    }
8973
    repo.snapshot("t").unwrap();
8974
    repo.commit("second", &[]).unwrap();
8975
    let want: Vec<Vec<u8>> = (0..6)
8976
        .map(|i| format!("one {i}\ntwo\n").into_bytes())
8977
        .collect();
8978
    // The index of the working copy's base, holding every file's history
8979
    // (a few changes behind, an index is replayed onto, not rewritten).
8980
    let (_, wc) = repo.working_copy().unwrap();
8981
    let base = repo.load_state_history(&wc.deps).unwrap();
8982
    repo.write_state_index(&wc.deps, &base);
8983
    for (i, w) in want.iter().enumerate() {
8984
        assert_eq!(&repo.file_at(&format!("f{i}.txt"), None).unwrap(), w);
8985
    }
8986
    let index = repo.state_indexes();
8987
    assert!(!index.is_empty(), "a state index was written");
8988
    // The histories are last in the file: damage the last of them.
8989
    let mut bytes = fs::read(&index[0]).unwrap();
8990
    let last = bytes.len() - 1;
8991
    bytes[last] ^= 0x40;
8992
    fs::write(&index[0], &bytes).unwrap();
8993
8994
    let reads: Vec<_> = (0..6)
8995
        .map(|i| repo.file_at(&format!("f{i}.txt"), None))
8996
        .collect();
8997
    let damaged: Vec<String> = reads
8998
        .iter()
8999
        .filter_map(|r| r.as_ref().err().map(|e| e.to_string()))
9000
        .collect();
9001
    assert_eq!(damaged.len(), 1, "{damaged:?}");
9002
    assert!(
9003
        damaged[0].contains("state index was damaged")
9004
            && damaged[0].contains("run the command again"),
9005
        "{}",
9006
        damaged[0]
9007
    );
9008
    // Every file reads right again, from an index rebuilt from history.
9009
    for (i, w) in want.iter().enumerate() {
9010
        assert_eq!(&repo.file_at(&format!("f{i}.txt"), None).unwrap(), w);
9011
    }
9012
}
9013
9014
/// oxygen#95: a push longer than `push.batch-bytes` goes in parts, each
9015
/// objects alone and in dependency order, and the last moves the bookmark.
9016
/// The remote ends with every change and the same state, and says how each
9017
/// part went.
9018
#[test]
9019
fn a_long_push_goes_in_parts() {
9020
    hermetic();
9021
    let dir = tempfile::tempdir().unwrap();
9022
    let root = dir.path();
9023
    let origin = root.join("origin");
9024
    Repo::init_bare_unbound(&origin).unwrap();
9025
    let main = root.join("main");
9026
    let mut repo = Repo::init(&main).unwrap();
9027
    repo.config
9028
        .set("remote.origin.url", &origin.to_string_lossy())
9029
        .unwrap();
9030
    // One byte: every change is a part of its own.
9031
    repo.config.set("push.batch-bytes", "1").unwrap();
9032
    repo.save_config().unwrap();
9033
    for i in 0..6 {
9034
        write(
9035
            &main,
9036
            &format!("f{i}.txt"),
9037
            format!("file {i}\n").as_bytes(),
9038
        );
9039
        repo.commit(&format!("c{i}"), &[]).unwrap();
9040
    }
9041
    let mut parts = Vec::new();
9042
    let results = repo
9043
        .push_bookmark_with("origin", "main", false, &mut |m| parts.push(m.to_string()))
9044
        .unwrap();
9045
    assert!(
9046
        results.iter().any(|r| r.ok && r.name == "main"),
9047
        "{results:?}"
9048
    );
9049
    assert_eq!(parts.len(), 6, "{parts:?}");
9050
    assert_eq!(parts[0], "part 1 of 6: 1 changes");
9051
9052
    let remote = Repo::open(&origin).unwrap();
9053
    let heads = repo.bookmark_heads().unwrap();
9054
    assert_eq!(remote.bookmark_heads().unwrap(), heads);
9055
    assert_eq!(
9056
        remote.log_state(&heads).unwrap().len(),
9057
        repo.log_state(&heads).unwrap().len()
9058
    );
9059
    // A push of objects alone reports how it went, as `objects`.
9060
    let got = remote
9061
        .receive_push(Bundle::default(), vec![], None, vec![])
9062
        .unwrap();
9063
    assert_eq!(got.len(), 1);
9064
    assert!(got[0].ok && got[0].name == OBJECTS_RESULT, "{got:?}");
9065
}
9066
9067
/// oxygen#97: with `git.claim`, an import authors the importing identity's
9068
/// own commits (Git author email = its email, any case) with its key, and
9069
/// leaves anyone else's with the zero key; the history verifies as before.
9070
#[test]
9071
fn git_import_claims_your_own_commits() {
9072
    hermetic();
9073
    if std::process::Command::new("git")
9074
        .arg("--version")
9075
        .output()
9076
        .is_err()
9077
    {
9078
        eprintln!("git not installed; skipping");
9079
        return;
9080
    }
9081
    let dir = tempfile::tempdir().unwrap();
9082
    let root = dir.path();
9083
    let g = root.join("src.git");
9084
    fs::create_dir_all(&g).unwrap();
9085
    let git = |who: &str, args: &[&str]| {
9086
        let (name, email) = who.split_once(' ').unwrap();
9087
        let out = std::process::Command::new("git")
9088
            .arg("-C")
9089
            .arg(&g)
9090
            .args([
9091
                "-c",
9092
                &format!("user.name={name}"),
9093
                "-c",
9094
                &format!("user.email={email}"),
9095
                "-c",
9096
                "commit.gpgsign=false",
9097
            ])
9098
            .args(args)
9099
            .output()
9100
            .unwrap();
9101
        assert!(
9102
            out.status.success(),
9103
            "git {args:?}: {}",
9104
            String::from_utf8_lossy(&out.stderr)
9105
        );
9106
    };
9107
    git("Grace [email protected]", &["init", "-q", "-b", "main"]);
9108
    write(&g, "a.txt", b"a\n");
9109
    git("Grace [email protected]", &["add", "."]);
9110
    git("Grace [email protected]", &["commit", "-qm", "mine"]);
9111
    write(&g, "b.txt", b"b\n");
9112
    git("Ada [email protected]", &["add", "."]);
9113
    git("Ada [email protected]", &["commit", "-qm", "someone else's"]);
9114
9115
    let mut repo = Repo::init(&root.join("o")).unwrap();
9116
    let (key, _) = repo
9117
        .create_identity("Grace", "[email protected]", IdentityScope::Repo)
9118
        .unwrap();
9119
    repo.config.set("git.claim", "true").unwrap();
9120
    repo.save_config().unwrap();
9121
    let repo = Repo::open(&root.join("o")).unwrap();
9122
    repo.import_git(&g, "main").unwrap();
9123
    let v = repo.verify_git_import(&g, "main").unwrap();
9124
    assert!(v.mismatches.is_empty(), "{:?}", v.mismatches);
9125
    let heads = repo.bookmark_heads().unwrap();
9126
    let by_message: std::collections::HashMap<String, KeyId> = repo
9127
        .log_state(&heads)
9128
        .unwrap()
9129
        .into_iter()
9130
        .map(|e| {
9131
            (
9132
                e.change.message.lines().next().unwrap_or("").to_string(),
9133
                e.change.author,
9134
            )
9135
        })
9136
        .collect();
9137
    assert_eq!(by_message["mine"], key, "her own commit, any case of email");
9138
    assert_eq!(by_message["someone else's"], ObjectRef::ZERO, "not hers");
9139
}
9140
9141
/// oxygen#86: removing a remote removes all of it: every `remote.NAME.*`
9142
/// key (URL, token, CA), its tracking bookmarks, and nothing else.
9143
#[test]
9144
fn removing_a_remote_leaves_nothing_of_it() {
9145
    hermetic();
9146
    let dir = tempfile::tempdir().unwrap();
9147
    let origin = dir.path().join("origin");
9148
    Repo::init_bare_unbound(&origin).unwrap();
9149
    let main = dir.path().join("main");
9150
    let mut repo = Repo::init(&main).unwrap();
9151
    repo.config
9152
        .set("remote.origin.url", &origin.to_string_lossy())
9153
        .unwrap();
9154
    repo.config
9155
        .set("remote.origin.token", "secret-ish")
9156
        .unwrap();
9157
    repo.config
9158
        .set("remote.keep.url", &origin.to_string_lossy())
9159
        .unwrap();
9160
    repo.save_config().unwrap();
9161
    write(&main, "a.txt", b"a\n");
9162
    repo.commit("a", &[]).unwrap();
9163
    assert!(repo.push("origin", false).unwrap()[0].ok);
9164
    assert!(
9165
        repo.view().unwrap().remotes.contains_key("origin"),
9166
        "a tracking bookmark"
9167
    );
9168
9169
    repo.remove_remote("origin").unwrap();
9170
    let again = Repo::open(&main).unwrap();
9171
    assert!(
9172
        !again
9173
            .config
9174
            .repo_layer()
9175
            .keys()
9176
            .any(|k| k.starts_with("remote.origin.")),
9177
        "{:?}",
9178
        again.config.repo_layer()
9179
    );
9180
    assert!(!again.config.remotes.contains_key("origin"));
9181
    assert!(
9182
        !again.view().unwrap().remotes.contains_key("origin"),
9183
        "its tracking bookmarks go"
9184
    );
9185
    assert!(
9186
        again.config.remotes.contains_key("keep"),
9187
        "another remote stays"
9188
    );
9189
    let mut again = again;
9190
    assert!(
9191
        again.remove_remote("origin").is_err(),
9192
        "a second removal is refused"
9193
    );
9194
}
9195
9196
/// oxygenhub#126: a blob a host stored for itself (a job's artifact) is
9197
/// unreachable from history, so gc prunes it, unless the host names it:
9198
/// then it and its chunks stay, and it reads back whole.
9199
#[test]
9200
fn gc_keeps_the_blobs_a_host_names() {
9201
    hermetic();
9202
    let dir = tempfile::tempdir().unwrap();
9203
    let repo = Repo::init(dir.path()).unwrap();
9204
    write(dir.path(), "a.txt", b"a\n");
9205
    repo.commit("a", &[]).unwrap();
9206
    // Large enough to be several chunks.
9207
    let body: Vec<u8> = (0..400_000u32)
9208
        .flat_map(|i| (i.wrapping_mul(2654435761)).to_le_bytes())
9209
        .collect();
9210
    let kept = repo.store_blob(&body).unwrap();
9211
    let lost = repo.store_blob(b"an artifact nobody names").unwrap();
9212
    repo.gc_keeping(true, &[kept], &mut |_| {}).unwrap();
9213
    assert_eq!(repo.read_blob(&kept).unwrap(), body, "named: kept whole");
9214
    assert!(!repo.store().has(&lost), "not named: pruned");
9215
    repo.gc(true).unwrap();
9216
    assert!(!repo.store().has(&kept), "a plain gc prunes it");
9217
}
9218
9219
/// oxygen#99: undo in one workspace undoes that workspace's last command,
9220
/// never another workspace's, says what it undid, and goes further back
9221
/// when run again.
9222
#[test]
9223
fn undo_is_scoped_to_its_workspace() {
9224
    hermetic();
9225
    let dir = tempfile::tempdir().unwrap();
9226
    let root = dir.path().join("main");
9227
    let a = Repo::init(&root).unwrap();
9228
    write(&root, "base.txt", b"base\n");
9229
    let base = a.commit("base", &[]).unwrap();
9230
    a.bookmark_create("feature", None).unwrap();
9231
    let ws_dir = dir.path().join("ws");
9232
    let heads = a.resolve_heads("feature").unwrap();
9233
    let b = a
9234
        .workspace_add_on(&ws_dir, Some(&heads), Some("feature"))
9235
        .unwrap();
9236
9237
    // A commits on main, then B commits on feature: B's is the newest.
9238
    write(&root, "a.txt", b"a\n");
9239
    let ca = a.commit("from a", &[]).unwrap();
9240
    write(&ws_dir, "b.txt", b"b\n");
9241
    let cb = b.commit("from b", &[]).unwrap();
9242
9243
    // A's undo undoes A's commit and leaves B's.
9244
    let u = a.undo().unwrap();
9245
    assert_eq!(u.command, "oxy commit -m \"from a\"");
9246
    assert_eq!(u.others_kept, 1, "B's newer commit is left");
9247
    assert!(!u.changes.is_empty());
9248
    let view = a.view().unwrap();
9249
    // (Independent changes commute, so a bookmark's heads may hold base too.)
9250
    assert_eq!(a.heads_of(&view, "main").unwrap(), vec![base]);
9251
    assert!(
9252
        a.heads_of(&view, "feature").unwrap().contains(&cb),
9253
        "B's commit stands"
9254
    );
9255
    assert!(
9256
        a.store().get_change(&ca).is_ok(),
9257
        "the change itself is still in the store"
9258
    );
9259
    // A's working copy was clean, so its files followed; B's are untouched.
9260
    assert!(!root.join("a.txt").exists());
9261
    assert!(a.snapshot("oxy status").unwrap().statuses.is_empty());
9262
    assert!(ws_dir.join("b.txt").exists());
9263
9264
    // B's undo still finds B's own commit, under A's undo.
9265
    let u = b.undo().unwrap();
9266
    assert_eq!(u.command, "oxy commit -m \"from b\"");
9267
    assert!(!b
9268
        .heads_of(&b.view().unwrap(), "feature")
9269
        .unwrap()
9270
        .contains(&cb));
9271
    assert_eq!(
9272
        a.heads_of(&a.view().unwrap(), "main").unwrap(),
9273
        vec![base],
9274
        "A's undo stands"
9275
    );
9276
9277
    // A's next undo goes past the commit it already undid, to adding B's
9278
    // workspace: refused, since B has worked there since.
9279
    let e = a.undo().unwrap_err().to_string();
9280
    assert!(e.contains("the workspace at") && e.contains("ws"), "{e}");
9281
}
9282
9283
/// oxygen#99: two workspaces on one bookmark: an undo takes back only its
9284
/// own commit's head, and the other workspace's head stays.
9285
#[test]
9286
fn undo_on_a_shared_bookmark_keeps_the_other_workspaces_head() {
9287
    hermetic();
9288
    let dir = tempfile::tempdir().unwrap();
9289
    let root = dir.path().join("main");
9290
    let a = Repo::init(&root).unwrap();
9291
    write(&root, "base.txt", b"base\n");
9292
    a.commit("base", &[]).unwrap();
9293
    let ws_dir = dir.path().join("ws");
9294
    let b = a.workspace_add(&ws_dir, None).unwrap();
9295
    write(&root, "a.txt", b"a\n");
9296
    let ca = a.commit("from a", &[]).unwrap();
9297
    write(&ws_dir, "b.txt", b"b\n");
9298
    let cb = b.commit("from b", &[]).unwrap();
9299
    let u = a.undo().unwrap();
9300
    assert_eq!(u.command, "oxy commit -m \"from a\"");
9301
    let heads = a.heads_of(&a.view().unwrap(), "main").unwrap();
9302
    assert!(heads.contains(&cb) && !heads.contains(&ca), "{heads:?}");
9303
}
9304
9305
/// oxygen#99: an undo that would also take back what another workspace
9306
/// did since to the same bookmark is refused, naming it.
9307
#[test]
9308
fn undo_refuses_to_take_back_another_workspaces_work() {
9309
    hermetic();
9310
    let dir = tempfile::tempdir().unwrap();
9311
    let root = dir.path().join("main");
9312
    let a = Repo::init(&root).unwrap();
9313
    write(&root, "base.txt", b"base\n");
9314
    a.commit("base", &[]).unwrap();
9315
    let ws_dir = dir.path().join("ws");
9316
    let b = a.workspace_add(&ws_dir, None).unwrap();
9317
    // Both on main: A commits, then B builds on it, editing A's file.
9318
    write(&root, "a.txt", b"a\n");
9319
    a.commit("from a", &[]).unwrap();
9320
    b.refresh().unwrap();
9321
    let heads = b.resolve_heads("main").unwrap();
9322
    b.checkout(&heads, false, "oxy checkout").unwrap();
9323
    write(&ws_dir, "a.txt", b"a, then b\n");
9324
    b.commit("from b", &[]).unwrap();
9325
    let e = a.undo().unwrap_err().to_string();
9326
    assert!(
9327
        e.contains("bookmark main") && e.contains("builds on"),
9328
        "{e}"
9329
    );
9330
    assert!(e.contains("oxy op restore"), "{e}");
9331
}
9332
9333
/// oxygen#99: undoing a commit that was already pushed says so: the remote
9334
/// still has it.
9335
#[test]
9336
fn undo_says_when_the_commit_was_pushed() {
9337
    hermetic();
9338
    let dir = tempfile::tempdir().unwrap();
9339
    let root = dir.path();
9340
    Repo::init(&root.join("origin")).unwrap();
9341
    let url = root.join("origin").to_string_lossy().to_string();
9342
    let repo = Repo::clone(&url, &root.join("work"))
9343
        .unwrap()
9344
        .with_home(root.join("home"));
9345
    write(&root.join("work"), "a.txt", b"a\n");
9346
    repo.commit("a", &[]).unwrap();
9347
    assert!(repo.push("origin", false).unwrap()[0].ok);
9348
    // The push itself is passed over: the remote keeps what it was sent.
9349
    let u = repo.undo().unwrap();
9350
    assert_eq!(u.command, "oxy commit -m \"a\"");
9351
    assert_eq!(u.pushed, vec![("main".to_string(), "origin".to_string())]);
9352
}
9353
9354
/// oxygen#98: a new untracked file over snapshot.max-new-file-size is left
9355
/// out of the snapshot and named; tracked files and files already in the
9356
/// working copy are not.
9357
#[test]
9358
fn large_new_files_are_left_out_of_snapshots() {
9359
    hermetic();
9360
    let dir = tempfile::tempdir().unwrap();
9361
    let root = dir.path();
9362
    let mut repo = Repo::init(root).unwrap();
9363
    repo.config.max_new_file = 1024;
9364
    write(root, "small.txt", b"small\n");
9365
    write(root, "big.bin", &vec![0u8; 4096]);
9366
    let s = repo.snapshot("oxy status").unwrap();
9367
    let paths: Vec<_> = s.statuses.iter().map(|p| p.path.as_str()).collect();
9368
    assert_eq!(paths, ["small.txt"]);
9369
    assert_eq!(repo.skipped_large(), vec![("big.bin".to_string(), 4096)]);
9370
    repo.commit("small", &[]).unwrap();
9371
9372
    // A tracked file may grow past the limit.
9373
    write(root, "small.txt", &vec![b'x'; 4096]);
9374
    let s = repo.snapshot("oxy status").unwrap();
9375
    assert!(s.statuses.iter().any(|p| p.path == "small.txt"));
9376
    // With no limit the big file is taken in, and stays once it is.
9377
    repo.config.max_new_file = 0;
9378
    let s = repo.snapshot("oxy status").unwrap();
9379
    assert!(s.statuses.iter().any(|p| p.path == "big.bin"));
9380
    repo.config.max_new_file = 1024;
9381
    let s = repo.snapshot("oxy status").unwrap();
9382
    assert!(
9383
        s.statuses.iter().any(|p| p.path == "big.bin"),
9384
        "already in the working copy"
9385
    );
9386
    assert!(repo.skipped_large().is_empty());
9387
}
9388
9389
/// oxygen#98: a file only a past working-copy snapshot held is pruned once
9390
/// snapshots expire, and kept while they have not.
9391
#[test]
9392
fn gc_prunes_what_only_expired_snapshots_held() {
9393
    hermetic();
9394
    let dir = tempfile::tempdir().unwrap();
9395
    let root = dir.path();
9396
    let mut repo = Repo::init(root).unwrap();
9397
    repo.config.gc_grace_days = 0;
9398
    write(root, "a.txt", b"a\n");
9399
    repo.commit("a", &[]).unwrap();
9400
    let image: Vec<u8> = (0..200_000u32).map(|i| (i % 7) as u8).collect();
9401
    write(root, "image.tar", &image);
9402
    repo.snapshot("oxy status").unwrap();
9403
    std::fs::remove_file(root.join("image.tar")).unwrap();
9404
    repo.snapshot("oxy status").unwrap();
9405
    let blob = Repo::blob_ref(&image);
9406
    assert!(repo.store().has(&blob));
9407
    repo.gc(true).unwrap();
9408
    assert!(repo.store().has(&blob), "a recent snapshot keeps it");
9409
    repo.config.snapshot_retention_days = 0;
9410
    repo.gc(true).unwrap();
9411
    assert!(!repo.store().has(&blob), "an expired snapshot does not");
9412
    assert_eq!(
9413
        repo.file_at("a.txt", None).unwrap(),
9414
        b"a\n",
9415
        "committed files stay"
9416
    );
9417
}
9418
9419
/// oxygen#100: uncommitted work byte-for-byte what the bookmark switched to
9420
/// already has is no conflict: the switch goes through, nothing is lost,
9421
/// and other carried work still comes along.
9422
#[test]
9423
fn carrying_work_the_target_already_has_is_no_conflict() {
9424
    hermetic();
9425
    let dir = tempfile::tempdir().unwrap();
9426
    let root = dir.path();
9427
    let mut repo = Repo::init(root).unwrap();
9428
    write(root, "a.txt", b"one\n");
9429
    write(root, "b.txt", b"b\n");
9430
    repo.commit("one", &[]).unwrap();
9431
    repo.bookmark_create("landed", None).unwrap();
9432
    // On landed, a.txt becomes "two" (as a proposal landing would).
9433
    repo.bookmark_switch("landed", false).unwrap();
9434
    write(root, "a.txt", b"two\n");
9435
    repo.commit("two", &[]).unwrap();
9436
    repo.bookmark_switch("main", false).unwrap();
9437
    assert_eq!(std::fs::read(root.join("a.txt")).unwrap(), b"one\n");
9438
    // The same edit, uncommitted, on main; and another edit besides.
9439
    write(root, "a.txt", b"two\n");
9440
    write(root, "b.txt", b"b, edited\n");
9441
    let (_, carried) = repo.bookmark_switch_carry("landed").unwrap();
9442
    assert_eq!(
9443
        carried,
9444
        vec!["b.txt".to_string()],
9445
        "only the work landed lacks is carried"
9446
    );
9447
    assert_eq!(std::fs::read(root.join("a.txt")).unwrap(), b"two\n");
9448
    assert_eq!(std::fs::read(root.join("b.txt")).unwrap(), b"b, edited\n");
9449
    let s = repo.snapshot("oxy status").unwrap();
9450
    let paths: Vec<_> = s.statuses.iter().map(|p| p.path.as_str()).collect();
9451
    assert_eq!(paths, ["b.txt"]);
9452
9453
    // A real difference is still refused.
9454
    repo.bookmark_switch("main", true).unwrap();
9455
    write(root, "a.txt", b"three\n");
9456
    let e = repo
9457
        .bookmark_switch_carry("landed")
9458
        .unwrap_err()
9459
        .to_string();
9460
    assert!(e.contains("a.txt") && e.contains("--discard"), "{e}");
9461
}
9462
9463
/// oxygen#103: a full change hash as `--json` prints it, without `#`,
9464
/// resolves, so JSON output feeds back into commands.
9465
#[test]
9466
fn a_full_hash_resolves_without_its_hash_sign() {
9467
    hermetic();
9468
    let dir = tempfile::tempdir().unwrap();
9469
    let root = dir.path();
9470
    let repo = Repo::init(root).unwrap();
9471
    write(root, "a.txt", b"a\n");
9472
    let h = repo.commit("a", &[]).unwrap();
9473
    assert_eq!(repo.resolve_change(&h.to_hex()).unwrap(), h);
9474
    assert_eq!(repo.resolve_change(&format!("#{}", h.to_hex())).unwrap(), h);
9475
    assert!(repo
9476
        .resolve_change(&"0".repeat(64))
9477
        .unwrap_err()
9478
        .to_string()
9479
        .contains("no change matches"));
9480
}
9481
9482
#[test]
9483
fn a_pin_change_moves_only_the_pin() {
9484
    hermetic();
9485
    let dir = tempfile::tempdir().unwrap();
9486
    let root = dir.path();
9487
    let _lib_origin = Repo::init(&root.join("lib-origin")).unwrap();
9488
    let lib_url = root.join("lib-origin").to_string_lossy().to_string();
9489
    let lib = Repo::clone(&lib_url, &root.join("lib"))
9490
        .unwrap()
9491
        .with_home(root.join("home"));
9492
    write(&root.join("lib"), "lib.txt", b"v1\n");
9493
    lib.commit("lib v1", &[]).unwrap();
9494
    assert!(lib.push("origin", false).unwrap()[0].ok);
9495
    let _app_origin = Repo::init(&root.join("app-origin")).unwrap();
9496
    let app_dir = root.join("app");
9497
    let app = Repo::clone(&root.join("app-origin").to_string_lossy(), &app_dir)
9498
        .unwrap()
9499
        .with_home(root.join("home"));
9500
    write(&app_dir, "main.txt", b"app\n");
9501
    let pin1 = app.submodule_add(&lib_url, "libs/lib", None).unwrap();
9502
    let a1 = app.commit("app with lib", &[]).unwrap();
9503
    // The library moves on.
9504
    write(&root.join("lib"), "more.txt", b"v2\n");
9505
    let l2 = lib.commit("lib v2", &[]).unwrap();
9506
    let crate::subrepo::Pin::Oxy { repo, bookmark, .. } = pin1 else {
9507
        panic!("an Oxygen pin")
9508
    };
9509
    let pin2 = crate::subrepo::Pin::Oxy {
9510
        repo,
9511
        heads: vec![l2],
9512
        bookmark,
9513
    };
9514
    let author = app.store().get_change(&a1).unwrap().author;
9515
    let change = app
9516
        .build_pin_change(&[a1], "libs/lib", &pin2, "Move lib to v2", author)
9517
        .unwrap();
9518
    let mut state = app.load_state(&[a1]).unwrap();
9519
    state.add(change).unwrap();
9520
    let files = state.materialize().files;
9521
    assert_eq!(files["libs/lib"].kind, NodeKind::Subrepo);
9522
    let FileContent::Opaque { blobs } = &files["libs/lib"].content else {
9523
        panic!("a pin is opaque")
9524
    };
9525
    let read = crate::subrepo::Pin::decode(&app.read_blob(&blobs[0]).unwrap()).unwrap();
9526
    assert_eq!(read, pin2, "the new pin");
9527
    assert!(
9528
        matches!(&files["main.txt"].content, FileContent::Text { bytes, .. } if bytes.as_slice() == b"app\n"),
9529
        "nothing else changes"
9530
    );
9531
    // Only a subrepo's pin can be moved this way.
9532
    let e = app.build_pin_change(&[a1], "main.txt", &pin2, "x", author);
9533
    assert!(format!("{:?}", e.unwrap_err()).contains("not a subrepo"));
9534
    let e = app.build_pin_change(&[a1], "libs/none", &pin2, "x", author);
9535
    assert!(format!("{:?}", e.unwrap_err()).contains("does not exist"));
9536
}
9537
9538
/// oxygenhub#249: a handle reads the operation head once and keeps it,
9539
/// so one command or request never mixes two heads; another handle's
9540
/// operation shows only after `refresh`. Its own operations move it, and
9541
/// one recorded from the head it kept merges with what landed since, as
9542
/// any concurrent operation does.
9543
#[test]
9544
fn one_handle_keeps_one_head_until_it_refreshes() {
9545
    hermetic();
9546
    let dir = tempfile::tempdir().unwrap();
9547
    let root = dir.path();
9548
    let writer = Repo::init(root).unwrap();
9549
    write(root, "a.txt", b"one\n");
9550
    let h1 = writer.commit("one", &[]).unwrap();
9551
    let reader = Repo::open(root).unwrap();
9552
    let before = reader.view().unwrap();
9553
    assert_eq!(reader.bookmark_heads().unwrap(), vec![h1]);
9554
    write(root, "a.txt", b"two\n");
9555
    let h2 = writer.commit("two", &[]).unwrap();
9556
    assert_eq!(
9557
        writer.bookmark_heads().unwrap(),
9558
        vec![h2],
9559
        "its own operation"
9560
    );
9561
    assert_eq!(reader.view().unwrap(), before, "the head it read first");
9562
    assert_eq!(reader.bookmark_heads().unwrap(), vec![h1]);
9563
    reader.refresh().unwrap();
9564
    assert_eq!(reader.bookmark_heads().unwrap(), vec![h2]);
9565
9566
    // A handle recording from an older head merges with the newer one.
9567
    let stale = Repo::open(root).unwrap();
9568
    assert_eq!(stale.bookmark_heads().unwrap(), vec![h2]);
9569
    write(root, "a.txt", b"three\n");
9570
    let h3 = writer.commit("three", &[]).unwrap();
9571
    stale.bookmark_create("feature", Some(&[h1])).unwrap();
9572
    let view = stale.view().unwrap();
9573
    assert!(view.bookmarks.contains_key("feature"));
9574
    assert_eq!(
9575
        stale.bookmark_heads().unwrap(),
9576
        vec![h3],
9577
        "merged, not lost"
9578
    );
9579
    let fresh = Repo::open(root).unwrap();
9580
    assert_eq!(fresh.view().unwrap(), view);
9581
}
9582
9583
/// oxygenhub#249 over a store (a bucket's compare-and-swap): the same.
9584
#[test]
9585
fn over_a_store_one_handle_keeps_one_head() {
9586
    hermetic();
9587
    let backend = std::sync::Arc::new(crate::strata::MemoryStore::new());
9588
    crate::store::TEST_BACKEND.with(|t| *t.borrow_mut() = Some(backend.clone()));
9589
    let dir = tempfile::tempdir().unwrap();
9590
    let a = Repo::init(dir.path()).unwrap();
9591
    let (h0, _) = a.head_op().unwrap();
9592
    let b = Repo::open(dir.path()).unwrap();
9593
    assert_eq!(b.head_op().unwrap().0, h0);
9594
    let state = a.store.put_state(&StateObject::new(vec![])).unwrap();
9595
    let mut view = a.view().unwrap();
9596
    view.bookmarks.insert("x".into(), state);
9597
    let r = a.record_op(&[h0], "bookmark x", view).unwrap();
9598
    assert_eq!(a.head_op().unwrap().0, r);
9599
    assert_eq!(b.head_op().unwrap().0, h0, "b keeps its head");
9600
    b.refresh().unwrap();
9601
    assert_eq!(b.head_op().unwrap().0, r);
9602
    crate::store::TEST_BACKEND.with(|t| *t.borrow_mut() = None);
9603
}
9604
9605
/// oxygenhub#249: gc retires what it repacks rather than deleting it; a
9606
/// reader opened before reads on, then and after the next gc deletes the
9607
/// retired files once their hour is up. Younger ones are kept.
9608
#[test]
9609
fn gc_retires_and_a_later_gc_deletes_after_the_hour() {
9610
    hermetic();
9611
    let dir = tempfile::tempdir().unwrap();
9612
    let root = dir.path();
9613
    let repo = Repo::init(root).unwrap();
9614
    let mut heads = Vec::new();
9615
    for i in 0..4 {
9616
        write(root, &format!("f{i}.txt"), format!("{i}\n").as_bytes());
9617
        heads.push(repo.commit(&format!("c{i}"), &[]).unwrap());
9618
    }
9619
    let reader = Repo::open(root).unwrap();
9620
    assert_eq!(reader.log().unwrap().len(), 5);
9621
    let r = repo.gc(true).unwrap();
9622
    assert_eq!(r.retired, crate::store::RetiredReport::default());
9623
    assert_eq!(repo.store().loose_count().unwrap(), 0);
9624
    assert_eq!(reader.log().unwrap().len(), 5, "read on from what it had");
9625
    // Nothing is an hour old yet: a gc keeps it all.
9626
    let r = repo.gc(true).unwrap();
9627
    assert_eq!((r.retired.packs, r.retired.loose), (0, 0));
9628
    assert!(r.retired.kept > 0, "{r:?}");
9629
    write(root, "f9.txt", b"9\n");
9630
    heads.push(repo.commit("c9", &[]).unwrap());
9631
    crate::store::reader_tests::age_retired(
9632
        repo.store(),
9633
        crate::store::RETIRED_FOR + std::time::Duration::from_secs(60),
9634
    );
9635
    let r = repo.gc(true).unwrap();
9636
    assert!(r.retired.packs >= 1 && r.retired.loose > 0, "{r:?}");
9637
    assert_eq!(r.retired.kept, 0, "{r:?}");
9638
    let r = repo.gc(true).unwrap();
9639
    assert_eq!((r.retired.packs, r.retired.loose), (0, 0));
9640
    assert!(r.retired.kept > 0, "what the last gc retired is young");
9641
    // The reader opened before all of it still reads everything, from
9642
    // the packs it finds when what it loaded is gone.
9643
    assert_eq!(reader.log().unwrap().len(), 5);
9644
    for h in &heads[..4] {
9645
        reader.store().get_change(h).unwrap();
9646
    }
9647
    reader.refresh().unwrap();
9648
    assert_eq!(reader.log().unwrap().len(), 6);
9649
    let fresh = Repo::open(root).unwrap();
9650
    assert_eq!(
9651
        fresh.store().pack_count(),
9652
        1,
9653
        "retired packs are not loaded"
9654
    );
9655
}
9656
9657
/// oxygenhub#249: a repository opens when its store's pack listing names
9658
/// an index that is not there (deleted between the listing and the read).
9659
#[test]
9660
fn a_repository_opens_when_a_listed_index_is_gone() {
9661
    hermetic();
9662
    let backend = crate::store::reader_tests::racing(true);
9663
    let dyn_backend: std::sync::Arc<crate::store::Backend> = backend.clone();
9664
    crate::store::TEST_BACKEND.with(|t| *t.borrow_mut() = Some(dyn_backend));
9665
    let dir = tempfile::tempdir().unwrap();
9666
    let repo = Repo::init(dir.path()).unwrap();
9667
    write(dir.path(), "a.txt", b"a\n");
9668
    let h = repo.commit("a", &[]).unwrap();
9669
    repo.gc(true).unwrap();
9670
    let again = Repo::open(dir.path()).unwrap();
9671
    assert_eq!(again.store().pack_count(), 1);
9672
    assert_eq!(again.bookmark_heads().unwrap(), vec![h]);
9673
    // And when one is deleted between the listing and the read: a copy of
9674
    // the live pack, whose index goes as the store opens.
9675
    use crate::strata::Store as _;
9676
    let idx = backend
9677
        .list("pack-")
9678
        .unwrap()
9679
        .into_iter()
9680
        .map(|e| e.key)
9681
        .find(|k| k.ends_with(".idx") && k != "pack-0000.idx")
9682
        .unwrap();
9683
    let stem = idx.trim_end_matches(".idx");
9684
    for ext in ["pack", "idx"] {
9685
        let bytes = backend.get(&format!("{stem}.{ext}")).unwrap();
9686
        backend
9687
            .put_new(&format!("pack-copy.{ext}"), &bytes)
9688
            .unwrap();
9689
    }
9690
    *backend.doomed.lock().unwrap() = Some("pack-copy.idx".into());
9691
    let again = Repo::open(dir.path()).unwrap();
9692
    assert_eq!(again.store().pack_count(), 1);
9693
    assert_eq!(again.bookmark_heads().unwrap(), vec![h]);
9694
    assert!(!backend.has("pack-copy.idx").unwrap());
9695
    crate::store::TEST_BACKEND.with(|t| *t.borrow_mut() = None);
9696
}