OXYGENHUB
# 2aa1854b0d13 oxygen / crates / oxy-core / src / repo / tests.rs
372.6 KiB · Rust · last changed A shallow clone of a big repository works, and quickly (closes #137) 11 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!(d.contains("+    println!(\"hi\");"), "{d}");
138
    assert!(d.contains("-fn main() {}"), "{d}");
139
140
    // Resolution by prefix.
141
    assert_eq!(repo.resolve_change(&c2.change_id.short(6)).unwrap(), h2);
142
    assert_eq!(
143
        repo.resolve_change(&format!("#{}", h1.short(8))).unwrap(),
144
        h1
145
    );
146
    assert!(repo.resolve_change("zzzz").is_err());
147
148
    // Undo the commit: bookmark and working copy go back.
149
    repo.undo().unwrap();
150
    assert_eq!(repo.bookmark_heads().unwrap(), vec![h1]);
151
    let s = repo.snapshot("oxy status").unwrap();
152
    assert!(
153
        !s.changed,
154
        "files on disk still match the pre-commit working copy"
155
    );
156
    assert_eq!(s.statuses.len(), 3);
157
}
158
159
/// Make `main` conflicted: two commits on the same base that edit the same line.
160
fn conflicted_repo() -> (tempfile::TempDir, Repo, ChangeHash, ChangeHash, ChangeHash) {
161
    let dir = tempfile::tempdir().unwrap();
162
    let root = dir.path();
163
    let repo = Repo::init(root).unwrap();
164
    write(root, "f.txt", b"a\nb\nc\n");
165
    let h1 = repo.commit("base", &[]).unwrap();
166
    write(root, "f.txt", b"a\nB\nc\n");
167
    let h2 = repo.commit("upper", &[]).unwrap();
168
    repo.checkout(&[h1], false, "checkout").unwrap();
169
    write(root, "f.txt", b"a\nX\nc\n");
170
    let h3 = repo.commit("ex", &[]).unwrap();
171
    (dir, repo, h1, h2, h3)
172
}
173
174
#[test]
175
fn concurrent_edits_conflict_and_can_be_resolved() {
176
    hermetic();
177
    let (dir, repo, h1, h2, h3) = conflicted_repo();
178
    let root = dir.path();
179
    let heads: BTreeSet<_> = repo.bookmark_heads().unwrap().into_iter().collect();
180
    assert_eq!(heads, [h2, h3].into_iter().collect());
181
    let st = repo.load_state(&[h2, h3]).unwrap();
182
    assert!(st.materialize().is_conflicted());
183
184
    // Checking out main writes markers.
185
    let r = repo
186
        .checkout(&repo.bookmark_heads().unwrap(), false, "checkout main")
187
        .unwrap();
188
    assert!(r.conflicted);
189
    let marked = fs::read_to_string(root.join("f.txt")).unwrap();
190
    assert!(
191
        marked.starts_with("a\n<<<<<<< oxy conflict 1 of 1"),
192
        "{marked}"
193
    );
194
    assert!(
195
        marked.contains("B\n") && marked.contains("X\n") && marked.ends_with("end\nc\n"),
196
        "{marked}"
197
    );
198
    assert!(has_conflict_markers(marked.as_bytes()));
199
    // Untouched markers: clean working copy; commit has nothing to do.
200
    let s = repo.snapshot("status").unwrap();
201
    assert!(s.statuses.is_empty());
202
    assert!(!s.resolves);
203
204
    // Partially edited file that still has markers cannot be committed.
205
    write(root, "f.txt", marked.replace("B\n", "BB\n").as_bytes());
206
    let s = repo.snapshot("status").unwrap();
207
    assert_eq!(
208
        statuses(&s),
209
        vec![("f.txt".into(), ChangeStatus::ConflictEdited)]
210
    );
211
    assert!(repo.commit("no", &[]).is_err());
212
213
    // Resolve by keeping one side and adding a line elsewhere.
214
    write(root, "f.txt", b"a\nX\nc\nd\n");
215
    let s = repo.snapshot("status").unwrap();
216
    assert_eq!(statuses(&s), vec![("f.txt".into(), ChangeStatus::Resolved)]);
217
    assert!(s.resolves);
218
    let h4 = repo.commit("resolve", &[]).unwrap();
219
    let c4 = repo.store().get_change(&h4).unwrap();
220
    assert_eq!(c4.kind, ChangeKind::Resolution);
221
    let mut want = vec![h1, h2, h3];
222
    want.sort();
223
    assert_eq!(
224
        c4.deps, want,
225
        "a resolution depends on exactly the contributors and what it references"
226
    );
227
    assert_eq!(repo.bookmark_heads().unwrap(), vec![h4]);
228
    let snap = repo.load_state(&[h4]).unwrap().materialize();
229
    assert!(!snap.is_conflicted());
230
    assert!(
231
        matches!(&snap.files["f.txt"].content, FileContent::Text { bytes, .. } if bytes == b"a\nX\nc\nd\n")
232
    );
233
    assert!(!repo.snapshot("status").unwrap().changed);
234
    // A peer holding only h2 and h3 and receiving h4 sees the same result,
235
    // whatever order the changes arrive in.
236
    let mut st = State::new();
237
    for h in [h4, h3, h1, h2] {
238
        st.add_unchecked(repo.store().get_change(&h).unwrap());
239
    }
240
    st.validate().unwrap();
241
    assert!(
242
        matches!(&st.materialize().files["f.txt"].content, FileContent::Text { bytes, .. } if bytes == b"a\nX\nc\nd\n")
243
    );
244
}
245
246
#[test]
247
fn resolution_may_keep_both_sides_or_neither() {
248
    hermetic();
249
    let (dir, repo, _h1, _h2, _h3) = conflicted_repo();
250
    let root = dir.path();
251
    repo.checkout(&repo.bookmark_heads().unwrap(), false, "checkout main")
252
        .unwrap();
253
    // Keep both sides in a chosen order.
254
    write(root, "f.txt", b"a\nX\nB\nc\n");
255
    let h = repo.commit("both", &[]).unwrap();
256
    let snap = repo.load_state(&[h]).unwrap().materialize();
257
    assert!(!snap.is_conflicted());
258
    assert!(
259
        matches!(&snap.files["f.txt"].content, FileContent::Text { bytes, .. } if bytes == b"a\nX\nB\nc\n")
260
    );
261
    // Undo and instead drop the whole region.
262
    repo.undo().unwrap();
263
    write(root, "f.txt", b"a\nc\n");
264
    let h = repo.commit("neither", &[]).unwrap();
265
    let snap = repo.load_state(&[h]).unwrap().materialize();
266
    assert!(!snap.is_conflicted());
267
    assert!(
268
        matches!(&snap.files["f.txt"].content, FileContent::Text { bytes, .. } if bytes == b"a\nc\n")
269
    );
270
}
271
272
#[test]
273
fn name_conflict_resolved_by_removing_a_candidate() {
274
    hermetic();
275
    let dir = tempfile::tempdir().unwrap();
276
    let root = dir.path();
277
    let repo = Repo::init(root).unwrap();
278
    write(root, "keep.txt", b"k\n");
279
    let h1 = repo.commit("base", &[]).unwrap();
280
    write(root, "new.txt", b"one\n");
281
    repo.commit("one", &[]).unwrap();
282
    repo.checkout(&[h1], false, "checkout").unwrap();
283
    write(root, "new.txt", b"two\n");
284
    repo.commit("two", &[]).unwrap();
285
    let r = repo
286
        .checkout(&repo.bookmark_heads().unwrap(), false, "checkout main")
287
        .unwrap();
288
    assert!(r.conflicted);
289
    assert!(
290
        root.join("new.txt.oxy-conflict-1").exists()
291
            && root.join("new.txt.oxy-conflict-2").exists()
292
    );
293
    assert!(!root.join("new.txt").exists());
294
    // Candidate numbering follows change-hash order, so pick by content:
295
    // keep the "two" candidate under the real name and drop the other.
296
    let (keep, drop) = if fs::read(root.join("new.txt.oxy-conflict-1")).unwrap() == b"two\n" {
297
        (1, 2)
298
    } else {
299
        (2, 1)
300
    };
301
    fs::remove_file(root.join(format!("new.txt.oxy-conflict-{drop}"))).unwrap();
302
    fs::rename(
303
        root.join(format!("new.txt.oxy-conflict-{keep}")),
304
        root.join("new.txt"),
305
    )
306
    .unwrap();
307
    let h = repo.commit("pick two", &[]).unwrap();
308
    assert_eq!(
309
        repo.store().get_change(&h).unwrap().kind,
310
        ChangeKind::Resolution
311
    );
312
    // The resolution does not touch keep.txt, so it does not depend on h1;
313
    // the bookmark keeps both as heads and their union is the state.
314
    let heads: BTreeSet<_> = repo.bookmark_heads().unwrap().into_iter().collect();
315
    assert_eq!(heads, [h1, h].into_iter().collect());
316
    let snap = repo
317
        .load_state(&repo.bookmark_heads().unwrap())
318
        .unwrap()
319
        .materialize();
320
    assert!(!snap.is_conflicted(), "{:?}", snap.tree.conflicts);
321
    assert_eq!(
322
        snap.files.keys().cloned().collect::<Vec<_>>(),
323
        ["keep.txt", "new.txt"]
324
    );
325
    assert!(
326
        matches!(&snap.files["new.txt"].content, FileContent::Text { bytes, .. } if bytes == b"two\n")
327
    );
328
}
329
330
#[test]
331
fn identities_and_signed_commits() {
332
    hermetic();
333
    let dir = tempfile::tempdir().unwrap();
334
    let root = dir.path();
335
    let mut repo = Repo::init(root).unwrap().with_home(root.join("home"));
336
    write(root, "a.txt", b"a\n");
337
    let h0 = repo.commit("unsigned", &[]).unwrap();
338
    assert_eq!(repo.verify_change(&h0).unwrap(), SignatureStatus::Unsigned);
339
    assert_eq!(
340
        repo.store().get_change(&h0).unwrap().author,
341
        ObjectRef::ZERO
342
    );
343
344
    let (key, id) = repo
345
        .create_identity("Ada", "[email protected]", IdentityScope::Repo)
346
        .unwrap();
347
    assert_eq!(id.hash(), key);
348
    assert_eq!(repo.config.author_key, Some(key));
349
    // Config survives reopen; the secret key is found again.
350
    let reopened = Repo::open(root).unwrap().with_home(root.join("home"));
351
    assert_eq!(reopened.config.author_key, Some(key));
352
    assert_eq!(reopened.secret_key().unwrap().unwrap().0, key);
353
354
    // Default core.sign = seal: commits carry the author but no signature.
355
    write(root, "a.txt", b"a\nb\n");
356
    let h1 = repo.commit("authored", &[]).unwrap();
357
    assert_eq!(repo.store().get_change(&h1).unwrap().author, key);
358
    assert_eq!(repo.verify_change(&h1).unwrap(), SignatureStatus::Unsigned);
359
    // Signing later works too.
360
    repo.sign_change(&h1).unwrap();
361
    assert!(
362
        matches!(repo.verify_change(&h1).unwrap(), SignatureStatus::Valid { key: k, .. } if k == key)
363
    );
364
365
    repo.config.set("core.sign", "change").unwrap();
366
    repo.save_config().unwrap();
367
    write(root, "a.txt", b"a\nb\nc\n");
368
    let h2 = repo.commit("signed", &[]).unwrap();
369
    assert_eq!(
370
        repo.verify_change(&h2).unwrap(),
371
        SignatureStatus::Valid {
372
            key,
373
            name: "Ada".into(),
374
            email: "[email protected]".into(),
375
            sealed: false,
376
            revoked: false
377
        }
378
    );
379
380
    // A signature by a key that is not the author or a delegate is rejected
381
    // when the change names an author; an anonymous change (made before any
382
    // identity, author zero) is adopted by whoever signs it (spec §14.4).
383
    let other = SecretKey::generate();
384
    let other_id = other.identity("Mallory", "[email protected]", 0);
385
    let other_key = repo.store().put_identity(&other_id).unwrap();
386
    write(root, "a.txt", b"a\nb\nc\nd\n");
387
    repo.config.set("core.sign", "seal").unwrap();
388
    let h3 = repo.commit("ada's, unsigned", &[]).unwrap();
389
    let forged = other.sign(Domain::Change, &other_key, &h3);
390
    repo.store().put_signature(&h3, &forged).unwrap();
391
    assert!(
392
        matches!(repo.verify_change(&h3).unwrap(), SignatureStatus::Invalid(m) if m.contains("neither the author"))
393
    );
394
    let adopted = other.sign(Domain::Change, &other_key, &h0);
395
    repo.store().put_signature(&h0, &adopted).unwrap();
396
    assert!(
397
        matches!(repo.verify_change(&h0).unwrap(), SignatureStatus::Valid { name, .. } if name == "Mallory")
398
    );
399
400
    // Tampering with the stored signature invalidates it.
401
    let mut sig = repo.store().signatures(&h2).unwrap().remove(0);
402
    sig.ed[0] ^= 1;
403
    repo.store().put_signature(&h2, &sig).unwrap();
404
    assert!(matches!(
405
        repo.verify_change(&h2).unwrap(),
406
        SignatureStatus::Invalid(_)
407
    ));
408
409
    // Without the secret key, signing at commit fails cleanly.
410
    let no_keys = Repo::open(root).unwrap().with_home(root.join("nowhere"));
411
    write(root, "a.txt", b"z\n");
412
    assert!(no_keys.commit("cannot sign", &[]).is_err());
413
}
414
415
#[test]
416
fn checkout_moves_the_working_copy() {
417
    hermetic();
418
    let dir = tempfile::tempdir().unwrap();
419
    let root = dir.path();
420
    let repo = Repo::init(root).unwrap();
421
    write(root, "a.txt", b"one\n");
422
    write(root, "sub/deep/b.txt", b"b\n");
423
    let h1 = repo.commit("first", &[]).unwrap();
424
    write(root, "a.txt", b"two\n");
425
    fs::remove_file(root.join("sub/deep/b.txt")).unwrap();
426
    write(root, "bin.dat", &[0, 1, 2, 3]);
427
    let h2 = repo.commit("second", &[]).unwrap();
428
429
    let r = repo.checkout(&[h1], false, "oxy checkout").unwrap();
430
    assert_eq!(
431
        r,
432
        CheckoutReport {
433
            written: 2,
434
            removed: 1,
435
            removed_paths: vec!["bin.dat".into()],
436
            conflicted: false,
437
            notes: vec![],
438
            lacks: 1,
439
        }
440
    );
441
    assert_eq!(fs::read(root.join("a.txt")).unwrap(), b"one\n");
442
    assert_eq!(fs::read(root.join("sub/deep/b.txt")).unwrap(), b"b\n");
443
    assert!(!root.join("bin.dat").exists());
444
    let (_, wc) = repo.working_copy().unwrap();
445
    assert_eq!(wc.deps, vec![h1]);
446
    assert!(
447
        !repo.snapshot("status").unwrap().changed,
448
        "checkout leaves a clean working copy"
449
    );
450
    // The bookmark still points at h2.
451
    assert_eq!(repo.bookmark_heads().unwrap(), vec![h2]);
452
453
    // Dirty working copy refuses without --discard.
454
    write(root, "a.txt", b"dirty\n");
455
    assert!(repo.checkout(&[h2], false, "oxy checkout").is_err());
456
    let r = repo
457
        .checkout(&[h2], true, "oxy checkout --discard")
458
        .unwrap();
459
    assert_eq!(fs::read(root.join("a.txt")).unwrap(), b"two\n");
460
    assert_eq!(fs::read(root.join("bin.dat")).unwrap(), [0, 1, 2, 3]);
461
    assert!(!root.join("sub").exists(), "empty directories are pruned");
462
    assert_eq!(r.removed, 1);
463
    assert!(!repo.snapshot("status").unwrap().changed);
464
465
    // Refuses to write through a symlinked directory.
466
    #[cfg(unix)]
467
    {
468
        fs::remove_dir_all(root.join("sub")).ok();
469
        std::os::unix::fs::symlink("/tmp", root.join("sub")).unwrap();
470
        assert!(repo.checkout(&[h1], true, "oxy checkout").is_err());
471
    }
472
}
473
474
#[test]
475
fn large_files_are_chunked_and_read_back() {
476
    hermetic();
477
    let dir = tempfile::tempdir().unwrap();
478
    let repo = Repo::init(dir.path()).unwrap();
479
    let mut big = vec![0u8; 700 * 1024];
480
    for (i, b) in big.iter_mut().enumerate() {
481
        *b = (i as u32).wrapping_mul(2654435761).to_le_bytes()[0];
482
    }
483
    let r = repo.store_blob(&big).unwrap();
484
    let blob = Blob::decode(&repo.store().get_typed(&r, ObjectType::Blob).unwrap()).unwrap();
485
    assert!(blob.chunks.len() >= 3, "{}", blob.chunks.len());
486
    assert_eq!(repo.read_blob(&r).unwrap(), big);
487
    assert_eq!(Repo::blob_ref(&big), r);
488
}
489
490
#[test]
491
fn clone_push_pull_with_seals_and_attestations() {
492
    hermetic();
493
    let dir = tempfile::tempdir().unwrap();
494
    let root = dir.path();
495
    let origin_path = root.join("origin");
496
    let origin = Repo::init(&origin_path).unwrap();
497
    let origin_url = origin_path.to_string_lossy().to_string();
498
499
    // A clones, creates an identity (default core.sign = seal), commits, pushes.
500
    let mut a = Repo::clone(&origin_url, &root.join("a"))
501
        .unwrap()
502
        .with_home(root.join("home-a"));
503
    assert_eq!(a.id().unwrap(), origin.id().unwrap());
504
    let (key_a, _) = a
505
        .create_identity("Ada", "[email protected]", IdentityScope::Repo)
506
        .unwrap();
507
    write(&root.join("a"), "f.txt", b"a\n");
508
    let h1 = a.commit("first", &[]).unwrap();
509
    let results = a.push("origin", false).unwrap();
510
    origin.refresh().unwrap();
511
    assert!(results[0].ok, "{}", results[0].reason);
512
    assert_eq!(origin.bookmark_heads().unwrap(), vec![h1]);
513
    // The change was sealed at push and the reference attested.
514
    assert!(
515
        matches!(origin.authenticate_change(&h1).unwrap(), SignatureStatus::Valid { key, sealed: true, .. } if key == key_a)
516
    );
517
    assert_eq!(
518
        origin.verify_change(&h1).unwrap(),
519
        SignatureStatus::Unsigned
520
    );
521
    let serial_of = |att: &SignedAttest| match att.attest.body {
522
        AttestBody::Ref { serial, .. } => serial,
523
        _ => unreachable!(),
524
    };
525
    let (_, att) = origin.latest_ref_attest("main").unwrap().unwrap();
526
    // A bookmark new to the remote starts at the clock (past any deleted
527
    // namesake's serial); later updates count up from there.
528
    let first = serial_of(&att);
529
    assert!(first > 1_000_000_000_000, "{first}");
530
    let again = a.push("origin", false).unwrap();
531
    origin.refresh().unwrap();
532
    assert!(again[0].ok && again[0].reason.contains("up to date"));
533
    let (_, att) = origin.latest_ref_attest("main").unwrap().unwrap();
534
    assert_eq!(serial_of(&att), first, "a no-op push does not attest again");
535
536
    // B clones and sees the file and the seal.
537
    let b = Repo::clone(&origin_url, &root.join("b")).unwrap();
538
    assert_eq!(fs::read(root.join("b/f.txt")).unwrap(), b"a\n");
539
    assert_eq!(b.bookmark_heads().unwrap(), vec![h1]);
540
    assert!(matches!(
541
        b.authenticate_change(&h1).unwrap(),
542
        SignatureStatus::Valid { sealed: true, .. }
543
    ));
544
545
    // B (no identity) commits and pushes unsigned; the unverified origin accepts.
546
    write(&root.join("b"), "f.txt", b"a\nb\n");
547
    let h2 = b.commit("second", &[]).unwrap();
548
    assert!(b.push("origin", false).unwrap()[0].ok);
549
    origin.refresh().unwrap();
550
    assert_eq!(origin.bookmark_heads().unwrap(), vec![h2]);
551
552
    // A commits an independent change; push is refused until A pulls.
553
    write(&root.join("a"), "g.txt", b"g\n");
554
    let h3 = a.commit("third", &[]).unwrap();
555
    assert!(a.push("origin", false).is_err());
556
    let pr = a.pull("origin").unwrap();
557
    assert!(pr.changed && pr.checked_out);
558
    let mut want = vec![h2, h3];
559
    want.sort();
560
    assert_eq!(pr.heads, want);
561
    assert_eq!(fs::read(root.join("a/f.txt")).unwrap(), b"a\nb\n");
562
    assert_eq!(fs::read(root.join("a/g.txt")).unwrap(), b"g\n");
563
    let results = a.push("origin", false).unwrap();
564
    origin.refresh().unwrap();
565
    assert!(results[0].ok, "{}", results[0].reason);
566
    let mut origin_heads = origin.bookmark_heads().unwrap();
567
    origin_heads.sort();
568
    assert_eq!(origin_heads, want);
569
    let (_, att) = origin.latest_ref_attest("main").unwrap().unwrap();
570
    assert_eq!(serial_of(&att), first + 1);
571
572
    // B pulls and ends up identical.
573
    let pr = b.pull("origin").unwrap();
574
    assert_eq!(pr.heads, want);
575
    assert_eq!(fs::read(root.join("b/g.txt")).unwrap(), b"g\n");
576
    assert!(!b.snapshot("status").unwrap().changed);
577
578
    // Concurrent edits of the same line: the union is a reified conflict.
579
    write(&root.join("a"), "f.txt", b"a\nA\n");
580
    a.commit("a-edit", &[]).unwrap();
581
    a.push("origin", false).unwrap();
582
    origin.refresh().unwrap();
583
    write(&root.join("b"), "f.txt", b"a\nB\n");
584
    b.commit("b-edit", &[]).unwrap();
585
    let pr = b.pull("origin").unwrap();
586
    assert!(pr.changed && pr.checked_out);
587
    let text = fs::read_to_string(root.join("b/f.txt")).unwrap();
588
    assert!(text.contains("<<<<<<< oxy conflict"), "{text}");
589
    write(&root.join("b"), "f.txt", b"a\nAB\n");
590
    let hr = b.commit("resolve", &[]).unwrap();
591
    assert_eq!(
592
        b.store().get_change(&hr).unwrap().kind,
593
        ChangeKind::Resolution
594
    );
595
    assert!(b.push("origin", false).unwrap()[0].ok);
596
    origin.refresh().unwrap();
597
    a.pull("origin").unwrap();
598
    assert_eq!(fs::read(root.join("a/f.txt")).unwrap(), b"a\nAB\n");
599
    // The resolution depends on the conflicting edits, but nothing depends
600
    // on "third" (it only added g.txt), so it stays a head beside it.
601
    let mut want = vec![hr, h3];
602
    want.sort();
603
    assert_eq!(a.bookmark_heads().unwrap(), want);
604
    assert!(!a.load_state(&want).unwrap().materialize().is_conflicted());
605
}
606
607
#[test]
608
fn receive_push_rejects_bad_updates() {
609
    hermetic();
610
    let dir = tempfile::tempdir().unwrap();
611
    let root = dir.path();
612
    let origin = Repo::init(&root.join("origin")).unwrap();
613
    let url = root.join("origin").to_string_lossy().to_string();
614
    let mut a = Repo::clone(&url, &root.join("a"))
615
        .unwrap()
616
        .with_home(root.join("home"));
617
    let (key, _) = a
618
        .create_identity("Ada", "a@b", IdentityScope::Repo)
619
        .unwrap();
620
    write(&root.join("a"), "f.txt", b"x\n");
621
    let h1 = a.commit("one", &[]).unwrap();
622
    assert!(a.push("origin", false).unwrap()[0].ok);
623
    let empty = origin.store().put_state(&StateObject::new(vec![])).unwrap();
624
    let s1 = origin
625
        .store()
626
        .put_state(&StateObject::new(vec![h1]))
627
        .unwrap();
628
629
    // Missing head.
630
    let ghost = origin
631
        .store()
632
        .put_state(&StateObject::new(vec![ObjectRef([9; 32])]))
633
        .unwrap();
634
    let r = origin
635
        .receive_push(
636
            Bundle::default(),
637
            vec![RefUpdate {
638
                name: "main".into(),
639
                old_state: s1,
640
                new_state: ghost,
641
                force: false,
642
                attestation: None,
643
            }],
644
            None,
645
            vec![],
646
        )
647
        .unwrap();
648
    assert!(
649
        !r[0].ok && r[0].reason.contains("missing"),
650
        "{}",
651
        r[0].reason
652
    );
653
654
    // Stale old_state.
655
    let r = origin
656
        .receive_push(
657
            Bundle::default(),
658
            vec![RefUpdate {
659
                name: "main".into(),
660
                old_state: empty,
661
                new_state: s1,
662
                force: false,
663
                attestation: None,
664
            }],
665
            None,
666
            vec![],
667
        )
668
        .unwrap();
669
    assert!(!r[0].ok && r[0].reason.contains("stale"), "{}", r[0].reason);
670
671
    // Non-fast-forward without force is refused; with force it passes.
672
    let r = origin
673
        .receive_push(
674
            Bundle::default(),
675
            vec![RefUpdate {
676
                name: "main".into(),
677
                old_state: s1,
678
                new_state: empty,
679
                force: false,
680
                attestation: None,
681
            }],
682
            None,
683
            vec![],
684
        )
685
        .unwrap();
686
    assert!(
687
        !r[0].ok && r[0].reason.contains("fast-forward"),
688
        "{}",
689
        r[0].reason
690
    );
691
    let r = origin
692
        .receive_push(
693
            Bundle::default(),
694
            vec![RefUpdate {
695
                name: "main".into(),
696
                old_state: s1,
697
                new_state: empty,
698
                force: true,
699
                attestation: None,
700
            }],
701
            None,
702
            vec![],
703
        )
704
        .unwrap();
705
    assert!(r[0].ok);
706
    assert_eq!(origin.bookmark_heads().unwrap(), vec![]);
707
708
    // Attestation with a stale serial is a rollback and is refused.
709
    let sa = a
710
        .sign_attest(&Attest {
711
            repo: a.id().unwrap(),
712
            hlc: Hlc::now(),
713
            body: AttestBody::Ref {
714
                name: "main".into(),
715
                old_state: empty,
716
                new_state: s1,
717
                serial: 1,
718
            },
719
        })
720
        .unwrap();
721
    let r = origin
722
        .receive_push(
723
            Bundle::default(),
724
            vec![RefUpdate {
725
                name: "main".into(),
726
                old_state: empty,
727
                new_state: s1,
728
                force: false,
729
                attestation: Some(sa.clone()),
730
            }],
731
            None,
732
            vec![],
733
        )
734
        .unwrap();
735
    assert!(
736
        !r[0].ok && r[0].reason.contains("serial"),
737
        "{}",
738
        r[0].reason
739
    );
740
    // An attestation for a different update is refused too.
741
    let sa2 = a
742
        .sign_attest(&Attest {
743
            repo: a.id().unwrap(),
744
            hlc: Hlc::now(),
745
            body: AttestBody::Ref {
746
                name: "main".into(),
747
                old_state: s1,
748
                new_state: empty,
749
                serial: 5,
750
            },
751
        })
752
        .unwrap();
753
    let r = origin
754
        .receive_push(
755
            Bundle::default(),
756
            vec![RefUpdate {
757
                name: "main".into(),
758
                old_state: empty,
759
                new_state: s1,
760
                force: false,
761
                attestation: Some(sa2),
762
            }],
763
            None,
764
            vec![],
765
        )
766
        .unwrap();
767
    assert!(
768
        !r[0].ok && r[0].reason.contains("describe"),
769
        "{}",
770
        r[0].reason
771
    );
772
    let _ = key;
773
}
774
775
#[test]
776
fn user_config_supplies_defaults_and_clones_sign() {
777
    hermetic();
778
    let dir = tempfile::tempdir().unwrap();
779
    let root = dir.path();
780
    let home = root.join("home");
781
    let origin = Repo::init(&root.join("origin")).unwrap();
782
    let url = root.join("origin").to_string_lossy().to_string();
783
784
    // Identity at user scope: the repository file stays free of author keys.
785
    let mut a = Repo::init(&root.join("a")).unwrap().with_home(&home);
786
    let (key, _) = a
787
        .create_identity("Ada", "[email protected]", IdentityScope::User)
788
        .unwrap();
789
    assert!(!a.config.repo_layer().contains_key("author.key"));
790
    assert_eq!(a.config.author_key, Some(key));
791
    assert!(home.join("config.toml").exists());
792
    a.set_user_config("core.sign", "change").unwrap();
793
    assert!(a.config.sign_changes);
794
795
    // Repository settings override user settings and are the only ones saved.
796
    a.config.set("core.sign", "seal").unwrap();
797
    a.save_config().unwrap();
798
    let again = Repo::open(&root.join("a")).unwrap().with_home(&home);
799
    assert!(!again.config.sign_changes);
800
    assert_eq!(again.config.author_key, Some(key));
801
    assert_eq!(
802
        read_config_file(&root.join("a/.oxy/config"))
803
            .unwrap()
804
            .get("core.sign")
805
            .map(String::as_str),
806
        Some("seal")
807
    );
808
809
    // A fresh clone made by this user signs with the user-level identity,
810
    // even though the clone's store has never seen the identity object.
811
    let b = Repo::clone(&url, &root.join("b")).unwrap().with_home(&home);
812
    assert!(b.config.sign_changes);
813
    write(&root.join("b"), "f.txt", b"f\n");
814
    let h = b.commit("signed from a clone", &[]).unwrap();
815
    assert!(
816
        matches!(b.verify_change(&h).unwrap(), SignatureStatus::Valid { key: k, .. } if k == key)
817
    );
818
    assert!(b.push("origin", false).unwrap()[0].ok);
819
    assert!(matches!(
820
        origin.verify_change(&h).unwrap(),
821
        SignatureStatus::Valid { .. }
822
    ));
823
}
824
825
#[test]
826
fn format1_repositories_are_migrated_on_open() {
827
    hermetic();
828
    use crate::oplog::{Format1Op, Format1View};
829
    let dir = tempfile::tempdir().unwrap();
830
    let root = dir.path();
831
    let repo = Repo::init(root).unwrap();
832
    write(root, "a.txt", b"a\n");
833
    let h1 = repo.commit("one", &[]).unwrap();
834
    let (wc_hash, _) = repo.working_copy().unwrap();
835
    // Rewrite the op log the way format 1 stored it: two ops, head lists.
836
    let mut v1 = Format1View::default();
837
    v1.bookmarks.insert("main".into(), vec![]);
838
    v1.workspaces.insert(repo.workspace(), wc_hash);
839
    let init = Format1Op {
840
        parents: vec![],
841
        hlc: Hlc::default(),
842
        command: "oxy init".into(),
843
        view: v1.clone(),
844
    };
845
    let init_ref = repo.store().put(ObjectType::Op, &init.encode()).unwrap();
846
    v1.bookmarks.insert("main".into(), vec![h1]);
847
    let commit = Format1Op {
848
        parents: vec![init_ref],
849
        hlc: Hlc::default(),
850
        command: "oxy commit".into(),
851
        view: v1,
852
    };
853
    let commit_ref = repo.store().put(ObjectType::Op, &commit.encode()).unwrap();
854
    write_atomic(&root.join(".oxy/ops/head"), commit_ref.to_hex().as_bytes()).unwrap();
855
    write_atomic(&root.join(".oxy/format"), FORMAT1_LINE.as_bytes()).unwrap();
856
    drop(repo);
857
858
    let repo = Repo::open(root).unwrap();
859
    assert_eq!(
860
        fs::read_to_string(root.join(".oxy/format")).unwrap(),
861
        FORMAT_LINE
862
    );
863
    assert_eq!(repo.bookmark_heads().unwrap(), vec![h1]);
864
    let ops = repo.op_log().unwrap();
865
    assert_eq!(
866
        ops.iter()
867
            .map(|(_, o)| o.command.as_str())
868
            .collect::<Vec<_>>(),
869
        ["oxy commit", "oxy init"]
870
    );
871
    assert_eq!(repo.heads_of(&ops[1].1.view, "main").unwrap(), vec![]);
872
    assert!(!repo.snapshot("status").unwrap().changed);
873
    // Reopening again is a no-op.
874
    assert_eq!(Repo::open(root).unwrap().op_log().unwrap().len(), 2);
875
}
876
877
#[test]
878
fn undo_skips_snapshot_operations() {
879
    hermetic();
880
    let dir = tempfile::tempdir().unwrap();
881
    let root = dir.path();
882
    let repo = Repo::init(root).unwrap();
883
    write(root, "a.txt", b"a\n");
884
    let h1 = repo.commit("a", &[]).unwrap();
885
    // A later command snapshots new edits on top of the commit.
886
    write(root, "b.txt", b"b\n");
887
    let s = repo.snapshot("oxy status").unwrap();
888
    assert!(s.changed);
889
    assert!(repo.head_op().unwrap().1.is_snapshot());
890
    assert_eq!(repo.last_command().unwrap().command, "oxy commit -m \"a\"");
891
    // Undo must undo the commit, not the snapshot.
892
    repo.undo().unwrap();
893
    assert_eq!(repo.bookmark_heads().unwrap(), vec![]);
894
    let s = repo.snapshot("oxy status").unwrap();
895
    let paths: Vec<_> = s.statuses.iter().map(|p| p.path.as_str()).collect();
896
    assert_eq!(
897
        paths,
898
        ["a.txt", "b.txt"],
899
        "both files are back in the working copy"
900
    );
901
    assert!(repo.store().get_change(&h1).unwrap().deps.is_empty());
902
    // Only snapshots remain above `init`, so there is nothing left to undo.
903
    assert_eq!(repo.last_command().unwrap().command, "oxy init");
904
    assert!(repo.undo().is_err());
905
}
906
907
#[test]
908
fn independent_changes_commute_and_make_multiple_heads() {
909
    hermetic();
910
    let dir = tempfile::tempdir().unwrap();
911
    let root = dir.path();
912
    let repo = Repo::init(root).unwrap();
913
    write(root, "a.txt", b"a\n");
914
    let h1 = repo.commit("a", &[]).unwrap();
915
    write(root, "b.txt", b"b\n");
916
    let h2 = repo.commit("b", &[]).unwrap();
917
    let c2 = repo.store().get_change(&h2).unwrap();
918
    assert!(c2.deps.is_empty(), "b.txt touches nothing from h1");
919
    let mut heads = repo.bookmark_heads().unwrap();
920
    heads.sort();
921
    let mut want = vec![h1, h2];
922
    want.sort();
923
    assert_eq!(heads, want);
924
    // Editing a.txt depends on h1 only.
925
    write(root, "a.txt", b"a\na2\n");
926
    let h3 = repo.commit("a2", &[]).unwrap();
927
    assert_eq!(repo.store().get_change(&h3).unwrap().deps, vec![h1]);
928
    let heads: BTreeSet<_> = repo.bookmark_heads().unwrap().into_iter().collect();
929
    assert_eq!(heads, [h2, h3].into_iter().collect());
930
    // Explicit dependency.
931
    write(root, "c.txt", b"c\n");
932
    let h4 = repo.commit("c", &[h2]).unwrap();
933
    assert_eq!(repo.store().get_change(&h4).unwrap().deps, vec![h2]);
934
}
935
936
#[test]
937
fn mode_change_and_text_binary_switch() {
938
    hermetic();
939
    let dir = tempfile::tempdir().unwrap();
940
    let root = dir.path();
941
    let repo = Repo::init(root).unwrap();
942
    write(root, "run.sh", b"#!/bin/sh\n");
943
    repo.commit("add script", &[]).unwrap();
944
    #[cfg(unix)]
945
    {
946
        use std::os::unix::fs::PermissionsExt;
947
        fs::set_permissions(root.join("run.sh"), fs::Permissions::from_mode(0o755)).unwrap();
948
        let s = repo.snapshot("status").unwrap();
949
        assert_eq!(
950
            statuses(&s),
951
            vec![("run.sh".into(), ChangeStatus::ModeChanged)]
952
        );
953
        let h = repo.commit("exec", &[]).unwrap();
954
        let snap = repo.load_state(&[h]).unwrap().materialize();
955
        assert!(snap.files["run.sh"].mode.exec);
956
    }
957
    // Text → binary → text.
958
    write(root, "run.sh", b"\0binary");
959
    let h = repo.commit("binary", &[]).unwrap();
960
    let snap = repo.load_state(&[h]).unwrap().materialize();
961
    assert!(snap.files["run.sh"].mode.opaque);
962
    write(root, "run.sh", b"text again\n");
963
    let h = repo.commit("text", &[]).unwrap();
964
    let snap = repo.load_state(&[h]).unwrap().materialize();
965
    assert!(!snap.files["run.sh"].mode.opaque);
966
    assert!(
967
        matches!(&snap.files["run.sh"].content, FileContent::Text { bytes, .. } if bytes == b"text again\n")
968
    );
969
    assert!(!snap.is_conflicted());
970
}
971
972
/// oxygen#87: a binary file given new contents and the executable bit in
973
/// one commit kept the contents and lost the bit.
974
#[cfg(unix)]
975
#[test]
976
fn a_binary_file_changed_and_made_executable_at_once_keeps_both() {
977
    use std::os::unix::fs::PermissionsExt;
978
    hermetic();
979
    let dir = tempfile::tempdir().unwrap();
980
    let root = dir.path();
981
    let repo = Repo::init(root).unwrap();
982
    write(root, "tool.exe", b"MZ\0one");
983
    repo.commit("add", &[]).unwrap();
984
    write(root, "tool.exe", b"MZ\0two");
985
    fs::set_permissions(root.join("tool.exe"), fs::Permissions::from_mode(0o755)).unwrap();
986
    let h = repo.commit("update and +x", &[]).unwrap();
987
    let snap = repo.load_state(&[h]).unwrap().materialize();
988
    let f = &snap.files["tool.exe"];
989
    assert!(f.mode.opaque && f.mode.exec, "{:?}", f.mode);
990
    assert!(
991
        repo.snapshot("status").unwrap().statuses.is_empty(),
992
        "nothing left to commit"
993
    );
994
}
995
996
/// Keyless step 4 (oxygenhub#241): an agent signing with a short-lived
997
/// key whose certificate an issuer gave pushes when the policy grants its
998
/// subject, and a fetch accepts what it attested; an expired certificate,
999
/// or a subject the policy does not grant, may not move the bookmark.
1000
#[test]
1001
fn a_certified_key_pushes_under_a_subject_grant() {
1002
    use crate::cert::{Certificate, SignedCertificate};
1003
    use crate::identity::Scope;
1004
    hermetic();
1005
    let dir = tempfile::tempdir().unwrap();
1006
    let root = dir.path();
1007
    let _origin = Repo::init(&root.join("origin")).unwrap();
1008
    let url = root.join("origin").to_string_lossy().to_string();
1009
    let mut a = Repo::clone(&url, &root.join("a"))
1010
        .unwrap()
1011
        .with_home(root.join("home-a"));
1012
    a.create_identity("Ada", "[email protected]", IdentityScope::User)
1013
        .unwrap();
1014
    write(&root.join("a"), "a.txt", b"a\n");
1015
    a.commit("a", &[]).unwrap();
1016
    a.policy_init().unwrap();
1017
    assert!(a.push("origin", false).unwrap().iter().all(|r| r.ok));
1018
    let hub_sk = SecretKey::generate();
1019
    let hub = hub_sk.identity("hub", "[email protected]", 1);
1020
    a.policy_grant_subject(
1021
        "agent:claude@ada",
1022
        hub.clone(),
1023
        Scope::CHANGES | Scope::REFS,
1024
        None,
1025
    )
1026
    .unwrap();
1027
    assert!(a
1028
        .push("origin", false)
1029
        .unwrap()
1030
        .iter()
1031
        .any(|r| r.name == "policy" && r.ok));
1032
1033
    let now = Hlc::now().wall_ms;
1034
    // An agent repository whose key the hub certified for `subject`, from
1035
    // `from` to `to`.
1036
    let agent = |name: &str, subject: &str, from: u64, to: u64| {
1037
        let mut r = Repo::clone(&url, &root.join(name))
1038
            .unwrap()
1039
            .with_home(root.join(format!("home-{name}")));
1040
        let (_, id) = r
1041
            .create_identity(name, "[email protected]", IdentityScope::User)
1042
            .unwrap();
1043
        let cert = SignedCertificate::sign(
1044
            Certificate {
1045
                key: id,
1046
                issuer: hub.hash(),
1047
                subject: subject.into(),
1048
                claims: vec![],
1049
                scope: Scope::CHANGES | Scope::REFS,
1050
                not_before: from,
1051
                expires: to,
1052
                grant: None,
1053
            },
1054
            &hub,
1055
            &hub_sk,
1056
        );
1057
        r.store().put_identity(&hub).unwrap();
1058
        r.store().put_certificate(&cert).unwrap();
1059
        write(&root.join(name), &format!("{name}.txt"), b"agent work\n");
1060
        r.commit("work", &[]).unwrap();
1061
        r
1062
    };
1063
1064
    let claude = agent("claude", "agent:claude@ada", now - 60_000, now + 600_000);
1065
    let r = claude.push("origin", false).unwrap();
1066
    assert!(r.iter().all(|x| x.ok), "{r:?}");
1067
    // Ada's fetch accepts the bookmark the certified key attested.
1068
    a.pull("origin").unwrap();
1069
    assert!(a.bookmark_heads().unwrap().iter().any(|h| a
1070
        .store()
1071
        .get_change(h)
1072
        .map(|c| c.message == "work")
1073
        .unwrap_or(false)));
1074
1075
    // Step 4c: a host with an acceptor key records when it accepted the
1076
    // certified update and serves it; a fetch checks the certificate at
1077
    // that time only when the certificate's issuer signed it for exactly
1078
    // this attestation, else at the attestation's own time.
1079
    let host = Repo::open(&root.join("origin"))
1080
        .unwrap()
1081
        .with_acceptor(hub.clone(), hub_sk.clone());
1082
    let (attest_ref, sa) = host.latest_ref_attest("main").unwrap().unwrap();
1083
    host.record_acceptance(&attest_ref).unwrap();
1084
    let served = host.remote_refs().unwrap();
1085
    let acc = served
1086
        .refs
1087
        .iter()
1088
        .find(|r| r.name == "main")
1089
        .unwrap()
1090
        .accepted
1091
        .clone()
1092
        .expect("served with the refs");
1093
    let signer = sa.sigs[0].key;
1094
    assert_eq!(
1095
        a.certified_time(&signer, &sa, Some(&acc)),
1096
        acc.attest.hlc.wall_ms
1097
    );
1098
    assert_eq!(a.certified_time(&signer, &sa, None), sa.attest.hlc.wall_ms);
1099
    let stranger_sk = SecretKey::generate();
1100
    let stranger = stranger_sk.identity("stranger", "s@x", 1);
1101
    let mut forged = acc.clone();
1102
    forged.sigs = vec![stranger_sk.sign(Domain::Attest, &stranger.hash(), &acc.attest.hash())];
1103
    assert_eq!(
1104
        a.certified_time(&signer, &sa, Some(&forged)),
1105
        sa.attest.hlc.wall_ms,
1106
        "not the issuer's"
1107
    );
1108
    let mut elsewhere = acc.clone();
1109
    elsewhere.attest.body = AttestBody::Accepted {
1110
        attest: ObjectRef([7; 32]),
1111
    };
1112
    elsewhere.sigs = vec![hub_sk.sign(Domain::Attest, &hub.hash(), &elsewhere.attest.hash())];
1113
    assert_eq!(
1114
        a.certified_time(&signer, &sa, Some(&elsewhere)),
1115
        sa.attest.hlc.wall_ms,
1116
        "another attestation's"
1117
    );
1118
    a.pull("origin").unwrap();
1119
    // gc keeps the acceptance with the attestation.
1120
    host.gc(true).unwrap();
1121
    assert!(host.acceptance_of(&attest_ref).unwrap().is_some());
1122
1123
    let late = agent("late", "agent:claude@ada", now - 1_200_000, now - 600_000);
1124
    let r = late.push("origin", false).unwrap();
1125
    assert!(
1126
        !r[0].ok && r[0].reason.contains("may not update"),
1127
        "an expired certificate: {r:?}"
1128
    );
1129
    let other = agent("other", "agent:mallory@ada", now - 60_000, now + 600_000);
1130
    let r = other.push("origin", false).unwrap();
1131
    assert!(
1132
        !r[0].ok && r[0].reason.contains("may not update"),
1133
        "a subject not granted: {r:?}"
1134
    );
1135
}
1136
1137
/// A tag made under one short-lived key and pushed under another: its
1138
/// signer travels with the push (identity and certificate), so a receiver
1139
/// that has never seen that key accepts it. A tag-only push by a keyless
1140
/// agent was refused "unknown key" (found releasing OxygenFlow 0.2.0).
1141
#[test]
1142
fn a_tag_signed_by_an_earlier_short_lived_key_is_pushed() {
1143
    use crate::cert::{Certificate, SignedCertificate};
1144
    use crate::identity::Scope;
1145
    hermetic();
1146
    let dir = tempfile::tempdir().unwrap();
1147
    let root = dir.path();
1148
    let _origin = Repo::init(&root.join("origin")).unwrap();
1149
    let url = root.join("origin").to_string_lossy().to_string();
1150
    let mut a = Repo::clone(&url, &root.join("a"))
1151
        .unwrap()
1152
        .with_home(root.join("home-a"));
1153
    a.create_identity("Ada", "[email protected]", IdentityScope::User)
1154
        .unwrap();
1155
    write(&root.join("a"), "a.txt", b"a\n");
1156
    a.commit("a", &[]).unwrap();
1157
    a.policy_init().unwrap();
1158
    assert!(a.push("origin", false).unwrap().iter().all(|r| r.ok));
1159
    let hub_sk = SecretKey::generate();
1160
    let hub = hub_sk.identity("hub", "[email protected]", 1);
1161
    a.policy_grant_subject(
1162
        "agent:claude@ada",
1163
        hub.clone(),
1164
        Scope::CHANGES | Scope::REFS,
1165
        Some("*"),
1166
    )
1167
    .unwrap();
1168
    assert!(a.push("origin", false).unwrap().iter().all(|r| r.ok));
1169
1170
    let now = Hlc::now().wall_ms;
1171
    let mut agent = Repo::clone(&url, &root.join("agent"))
1172
        .unwrap()
1173
        .with_home(root.join("home-agent"));
1174
    agent.store().put_identity(&hub).unwrap();
1175
    let certify = |agent: &Repo, id| {
1176
        let cert = SignedCertificate::sign(
1177
            Certificate {
1178
                key: id,
1179
                issuer: hub.hash(),
1180
                subject: "agent:claude@ada".into(),
1181
                claims: vec![],
1182
                scope: Scope::CHANGES | Scope::REFS,
1183
                not_before: now - 60_000,
1184
                expires: now + 600_000,
1185
                grant: None,
1186
            },
1187
            &hub,
1188
            &hub_sk,
1189
        );
1190
        agent.store().put_certificate(&cert).unwrap();
1191
    };
1192
    // The tag, under the first short-lived key.
1193
    let (first, first_id) = agent
1194
        .create_identity("claude", "[email protected]", IdentityScope::User)
1195
        .unwrap();
1196
    certify(&agent, first_id);
1197
    let heads = agent.bookmark_heads().unwrap();
1198
    agent.tag_create("v1", &heads, "first").unwrap();
1199
    // The push, under a second one (a later process's ten-minute key).
1200
    let (second, second_id) = agent
1201
        .create_identity("claude", "[email protected]", IdentityScope::User)
1202
        .unwrap();
1203
    assert_ne!(first, second);
1204
    certify(&agent, second_id);
1205
    agent
1206
        .set_user_config("author.signer", &second.to_hex())
1207
        .unwrap();
1208
    let host = Repo::open(&root.join("origin")).unwrap();
1209
    assert!(
1210
        host.store().get_identity(&first).is_err(),
1211
        "the host has never seen the tag's key"
1212
    );
1213
    let r = agent.push("origin", false).unwrap();
1214
    assert!(r.iter().all(|x| x.ok), "{r:?}");
1215
    let host = Repo::open(&root.join("origin")).unwrap();
1216
    assert!(
1217
        host.tag_refs().unwrap().iter().any(|t| t.name == "v1"),
1218
        "the tag arrived"
1219
    );
1220
}
1221
1222
/// oxygen#129: a short-lived key's tag is checked on a fetch at a time its
1223
/// signer did not choose, its issuer's acceptance, never at the time it
1224
/// claims nor at the fetch's (when the ten-minute certificate has long
1225
/// expired). Without an acceptance it is left out and said so; with one
1226
/// inside the certificate's window it is fetched however much later, and
1227
/// a host it is pushed on to keeps and serves the acceptance.
1228
#[test]
1229
fn a_short_lived_key_s_tag_is_fetched_at_its_issuer_s_acceptance() {
1230
    use crate::cert::{Certificate, SignedCertificate};
1231
    use crate::identity::Scope;
1232
    hermetic();
1233
    let dir = tempfile::tempdir().unwrap();
1234
    let root = dir.path();
1235
    let _origin = Repo::init(&root.join("origin")).unwrap();
1236
    let url = root.join("origin").to_string_lossy().to_string();
1237
    let mut a = Repo::clone(&url, &root.join("a"))
1238
        .unwrap()
1239
        .with_home(root.join("home-a"));
1240
    a.create_identity("Ada", "[email protected]", IdentityScope::User)
1241
        .unwrap();
1242
    write(&root.join("a"), "a.txt", b"a\n");
1243
    a.commit("a", &[]).unwrap();
1244
    a.policy_init().unwrap();
1245
    assert!(a.push("origin", false).unwrap().iter().all(|r| r.ok));
1246
    let hub_sk = SecretKey::generate();
1247
    let hub = hub_sk.identity("hub", "[email protected]", 1);
1248
    a.policy_grant_subject(
1249
        "agent:claude@ada",
1250
        hub.clone(),
1251
        Scope::CHANGES | Scope::REFS,
1252
        Some("*"),
1253
    )
1254
    .unwrap();
1255
    assert!(a.push("origin", false).unwrap().iter().all(|r| r.ok));
1256
1257
    let now = Hlc::now().wall_ms;
1258
    // An agent whose key the hub certified from `from` to `to`.
1259
    let agent = |name: &str, from: u64, to: u64| {
1260
        let mut r = Repo::clone(&url, &root.join(name))
1261
            .unwrap()
1262
            .with_home(root.join(format!("home-{name}")));
1263
        r.store().put_identity(&hub).unwrap();
1264
        let (_, id) = r
1265
            .create_identity(name, "[email protected]", IdentityScope::User)
1266
            .unwrap();
1267
        let cert = SignedCertificate::sign(
1268
            Certificate {
1269
                key: id,
1270
                issuer: hub.hash(),
1271
                subject: "agent:claude@ada".into(),
1272
                claims: vec![],
1273
                scope: Scope::CHANGES | Scope::REFS,
1274
                not_before: from,
1275
                expires: to,
1276
                grant: None,
1277
            },
1278
            &hub,
1279
            &hub_sk,
1280
        );
1281
        r.store().put_certificate(&cert).unwrap();
1282
        r
1283
    };
1284
1285
    // A tag by a key certified now, pushed to a host that records no
1286
    // acceptance (a path on disk): it lands, but a fetch has no time to
1287
    // check its certificate at, so it is left out and the fetch goes on.
1288
    let claude = agent("claude", now - 60_000, now + 600_000);
1289
    let heads = claude.bookmark_heads().unwrap();
1290
    claude.tag_create("v1", &heads, "one").unwrap();
1291
    let r = claude.push("origin", false).unwrap();
1292
    assert!(r.iter().all(|x| x.ok), "{r:?}");
1293
    let b = Repo::clone(&url, &root.join("b"))
1294
        .unwrap()
1295
        .with_home(root.join("home-b"));
1296
    let rep = b.fetch("origin").unwrap();
1297
    assert!(
1298
        rep.skipped
1299
            .iter()
1300
            .any(|(n, why)| n == "tags/v1" && why.contains("no time to check its certificate at")),
1301
        "{rep:?}"
1302
    );
1303
    assert_eq!(b.tag_heads("v1").unwrap(), None);
1304
1305
    // The host's acceptance, signed by the certificate's issuer, served
1306
    // with the tag: fetched.
1307
    let host = Repo::open(&root.join("origin"))
1308
        .unwrap()
1309
        .with_acceptor(hub.clone(), hub_sk.clone());
1310
    let (v1, _) = host.tag_attest("v1").unwrap().unwrap();
1311
    host.record_acceptance(&v1).unwrap();
1312
    let served = host.tag_refs().unwrap();
1313
    assert!(served
1314
        .iter()
1315
        .any(|t| t.name == "v1" && t.accepted.is_some()));
1316
    let rep = b.fetch("origin").unwrap();
1317
    assert!(rep.skipped.is_empty(), "{rep:?}");
1318
    assert_eq!(b.tag_heads("v1").unwrap(), Some(heads.clone()));
1319
    // gc keeps the acceptance with the tag.
1320
    host.gc(true).unwrap();
1321
    assert!(host.acceptance_of(&v1).unwrap().is_some());
1322
1323
    // Long after: a key whose certificate expired an hour ago may not
1324
    // create a tag now.
1325
    let late = agent("late", now - 7_200_000, now - 3_600_000);
1326
    late.tag_create("v2", &heads, "two").unwrap();
1327
    let r = late.push("origin", false).unwrap();
1328
    assert!(
1329
        r.iter()
1330
            .any(|x| x.name == "tags/v2" && !x.ok && x.reason.contains("may not create")),
1331
        "{r:?}"
1332
    );
1333
    // With its issuer's acceptance from inside the window (as a hub gave
1334
    // it then, passed on to another host), it is taken at that time: by
1335
    // the host it is pushed to, which keeps it, and by a fresh clone.
1336
    let (v2, _) = late.tag_attest("v2").unwrap().unwrap();
1337
    let acc = Attest {
1338
        repo: late.id().unwrap(),
1339
        hlc: Hlc {
1340
            wall_ms: now - 5_400_000,
1341
            logical: 0,
1342
        },
1343
        body: AttestBody::Accepted { attest: v2 },
1344
    };
1345
    let sig = hub_sk.sign(Domain::Attest, &hub.hash(), &acc.hash());
1346
    // One by any other key gives no time.
1347
    let stranger_sk = SecretKey::generate();
1348
    let stranger = stranger_sk.identity("stranger", "[email protected]", 1);
1349
    let forged = stranger_sk.sign(Domain::Attest, &stranger.hash(), &acc.hash());
1350
    late.keep_acceptance(
1351
        &v2,
1352
        &SignedAttest {
1353
            attest: acc.clone(),
1354
            sigs: vec![forged],
1355
        },
1356
    )
1357
    .unwrap();
1358
    let r = late.push("origin", false).unwrap();
1359
    assert!(
1360
        r.iter().any(|x| x.name == "tags/v2" && !x.ok),
1361
        "not the issuer's: {r:?}"
1362
    );
1363
    let theirs = SignedAttest {
1364
        attest: acc,
1365
        sigs: vec![sig],
1366
    };
1367
    // Kept beside the stranger's: the issuer's is the one sent.
1368
    late.keep_acceptance(&v2, &theirs).unwrap();
1369
    let r = late.push("origin", false).unwrap();
1370
    // (Its re-attestation of main is refused: an expired key moves no
1371
    // bookmark.)
1372
    assert!(r.iter().any(|x| x.name == "tags/v2" && x.ok), "{r:?}");
1373
    let host = Repo::open(&root.join("origin")).unwrap();
1374
    let (hv2, _) = host.tag_attest("v2").unwrap().unwrap();
1375
    assert_eq!(hv2, v2);
1376
    assert!(host
1377
        .store()
1378
        .index_get_pub("accepted", &v2)
1379
        .unwrap()
1380
        .contains(&theirs.attest.hash()));
1381
    let c = Repo::clone(&url, &root.join("c"))
1382
        .unwrap()
1383
        .with_home(root.join("home-c"));
1384
    assert_eq!(c.tag_heads("v2").unwrap(), Some(heads.clone()));
1385
    assert_eq!(c.tag_heads("v1").unwrap(), Some(heads));
1386
}
1387
1388
/// oxygenhub#266: a short-lived key its issuer certified moves a bookmark
1389
/// and signs no change (a keyless agent naming a bookmark). A third
1390
/// party's clone gets the key's identity, its certificate and the
1391
/// issuer's identity with the fetch, so the policy's subject grant
1392
/// authorizes the move and the signature verifies.
1393
#[test]
1394
fn a_bookmark_moved_by_a_certified_key_alone_is_fetched() {
1395
    use crate::cert::{Certificate, SignedCertificate};
1396
    use crate::identity::Scope;
1397
    hermetic();
1398
    let dir = tempfile::tempdir().unwrap();
1399
    let root = dir.path();
1400
    let _origin = Repo::init(&root.join("origin")).unwrap();
1401
    let url = root.join("origin").to_string_lossy().to_string();
1402
    let mut a = Repo::clone(&url, &root.join("a"))
1403
        .unwrap()
1404
        .with_home(root.join("home-a"));
1405
    a.create_identity("Ada", "[email protected]", IdentityScope::User)
1406
        .unwrap();
1407
    write(&root.join("a"), "a.txt", b"a\n");
1408
    a.commit("a", &[]).unwrap();
1409
    a.policy_init().unwrap();
1410
    assert!(a.push("origin", false).unwrap().iter().all(|r| r.ok));
1411
    let hub_sk = SecretKey::generate();
1412
    let hub = hub_sk.identity("hub", "[email protected]", 1);
1413
    a.policy_grant_subject(
1414
        "agent:claude@ada",
1415
        hub.clone(),
1416
        Scope::CHANGES | Scope::REFS,
1417
        None,
1418
    )
1419
    .unwrap();
1420
    assert!(a.push("origin", false).unwrap().iter().all(|r| r.ok));
1421
1422
    let now = Hlc::now().wall_ms;
1423
    let mut agent = Repo::clone(&url, &root.join("agent"))
1424
        .unwrap()
1425
        .with_home(root.join("home-agent"));
1426
    let (key, id) = agent
1427
        .create_identity("claude", "[email protected]", IdentityScope::User)
1428
        .unwrap();
1429
    let cert = SignedCertificate::sign(
1430
        Certificate {
1431
            key: id,
1432
            issuer: hub.hash(),
1433
            subject: "agent:claude@ada".into(),
1434
            claims: vec![],
1435
            scope: Scope::CHANGES | Scope::REFS,
1436
            not_before: now - 60_000,
1437
            expires: now + 600_000,
1438
            grant: None,
1439
        },
1440
        &hub,
1441
        &hub_sk,
1442
    );
1443
    agent.store().put_identity(&hub).unwrap();
1444
    agent.store().put_certificate(&cert).unwrap();
1445
    let heads = agent.bookmark_heads().unwrap();
1446
    agent.bookmark_create("agent-work", Some(&heads)).unwrap();
1447
    let r = agent.push_bookmark("origin", "agent-work", false).unwrap();
1448
    assert!(r.iter().all(|x| x.ok), "{r:?}");
1449
    let host = Repo::open(&root.join("origin")).unwrap();
1450
    let (_, sa) = host.latest_ref_attest("agent-work").unwrap().unwrap();
1451
    assert_eq!(sa.sigs[0].key, key, "the certified key alone moved it");
1452
1453
    // A fetch naming no change brings the certificate and both identities.
1454
    let bundle = host.bundle_raw_for(&[], None).unwrap();
1455
    assert!(bundle.changes.is_empty() && bundle.raw_changes.is_empty());
1456
    assert_eq!(bundle.certificates.len(), 1);
1457
    for k in [key, hub.hash()] {
1458
        assert!(bundle
1459
            .objects
1460
            .iter()
1461
            .any(|(t, b)| *t == ObjectType::Identity && hash_object(*t, b) == k));
1462
    }
1463
1464
    let c = Repo::clone(&url, &root.join("c")).unwrap();
1465
    let tracked = c.view().unwrap().remotes["origin"].clone();
1466
    assert_eq!(
1467
        tracked.get("agent-work"),
1468
        host.view().unwrap().bookmarks.get("agent-work")
1469
    );
1470
    assert!(c.store().certificate_of(&key).unwrap().is_some());
1471
}
1472
1473
/// Trusted time (oxygenhub#240, spec §14.8): a fetched attestation by a
1474
/// short-lived key is judged at its integrated time, the earliest time a
1475
/// pinned witness cosigned a checkpoint holding it. A certificate valid
1476
/// then but expired now passes; a witness this user does not trust gives
1477
/// no time (the earlier rule, said so); a backdated attestation is noted;
1478
/// an answer without the new fields is judged as before.
1479
#[test]
1480
fn a_fetched_attestation_is_judged_at_its_integrated_time() {
1481
    use super::transparency::LogCheck;
1482
    use crate::cert::{Certificate, SignedCertificate};
1483
    use crate::identity::Scope;
1484
    use crate::protocol::{Integration, Logged, RefsResponse, RemoteRef};
1485
    use crate::tlog::{self, Checkpoint, Entry, Hash, Integrated, Note};
1486
    hermetic();
1487
    let dir = tempfile::tempdir().unwrap();
1488
    let root = dir.path();
1489
    let mut a = Repo::init(&root.join("a"))
1490
        .unwrap()
1491
        .with_home(root.join("home-a"));
1492
    a.create_identity("Ada", "[email protected]", IdentityScope::User)
1493
        .unwrap();
1494
    write(&root.join("a"), "a.txt", b"a\n");
1495
    a.commit("a", &[]).unwrap();
1496
    a.policy_init().unwrap();
1497
    let issuer_sk = SecretKey::generate();
1498
    let issuer = issuer_sk.identity("hub", "[email protected]", 1);
1499
    a.policy_grant_subject(
1500
        "agent:claude@ada",
1501
        issuer.clone(),
1502
        Scope::CHANGES | Scope::REFS,
1503
        None,
1504
    )
1505
    .unwrap();
1506
    let p = a.current_policy().unwrap().unwrap().1.policy;
1507
1508
    // An agent key the issuer certified for ten minutes two hours ago.
1509
    let now = Hlc::now().wall_ms;
1510
    let t0 = now - 2 * 3_600_000;
1511
    let agent_sk = SecretKey::generate();
1512
    let agent = agent_sk.identity("claude", "[email protected]", t0);
1513
    let cert = SignedCertificate::sign(
1514
        Certificate {
1515
            key: agent.clone(),
1516
            issuer: issuer.hash(),
1517
            subject: "agent:claude@ada".into(),
1518
            claims: vec![],
1519
            scope: Scope::CHANGES | Scope::REFS,
1520
            not_before: t0,
1521
            expires: t0 + 600_000,
1522
            grant: None,
1523
        },
1524
        &issuer,
1525
        &issuer_sk,
1526
    );
1527
    a.store().put_identity(&agent).unwrap();
1528
    a.store().put_certificate(&cert).unwrap();
1529
    let signer = agent.hash();
1530
    let attested = |claimed: u64| {
1531
        let attest = Attest {
1532
            repo: a.id().unwrap(),
1533
            hlc: Hlc {
1534
                wall_ms: claimed,
1535
                logical: 0,
1536
            },
1537
            body: AttestBody::Ref {
1538
                name: "main".into(),
1539
                old_state: ObjectRef([1; 32]),
1540
                new_state: ObjectRef([2; 32]),
1541
                serial: 1,
1542
            },
1543
        };
1544
        let sig = agent_sk.sign(Domain::Attest, &signer, &attest.hash());
1545
        SignedAttest {
1546
            attest,
1547
            sigs: vec![sig],
1548
        }
1549
    };
1550
1551
    // The hub's log: eight entries, the attestation's at 3, the latest
1552
    // checkpoint of 8, and one of 4 that witnesses cosigned.
1553
    let log_sk = SecretKey::generate();
1554
    let log_key = log_sk.identity("hub.example", "[email protected]", 1);
1555
    let origin = "hub.example/log";
1556
    let hub = "https://hub.example";
1557
    let url = "https://hub.example/ada/a";
1558
    let w_sk = SecretKey::generate();
1559
    let w = w_sk.identity("w", "[email protected]", 1);
1560
    let stranger_sk = SecretKey::generate();
1561
    let stranger = stranger_sk.identity("s", "[email protected]", 1);
1562
    let sa = attested(t0 + 300_000);
1563
    let entry_of = |i: u64| {
1564
        let (kind, object) = if i == 3 {
1565
            ("ref", sa.attest.hash())
1566
        } else {
1567
            ("seal", ObjectRef([i as u8; 32]))
1568
        };
1569
        Entry {
1570
            kind: kind.into(),
1571
            repo: sa.attest.repo,
1572
            object,
1573
            signers: vec![signer],
1574
            received: t0 + 300_000,
1575
        }
1576
        .encode()
1577
    };
1578
    let mut stored: Vec<Hash> = Vec::new();
1579
    for i in 0..8 {
1580
        let add = tlog::stored_hashes_for_leaf(i, tlog::leaf_hash(&entry_of(i)), &stored).unwrap();
1581
        stored.extend(add);
1582
    }
1583
    let note_of = |n: u64, cosigners: &[(&str, &Identity, &SecretKey, u64)]| {
1584
        let mut note = Checkpoint {
1585
            origin: origin.into(),
1586
            size: n,
1587
            root: tlog::tree_hash(n, &stored).unwrap(),
1588
            extensions: vec![],
1589
        }
1590
        .sign(&log_key, &log_sk)
1591
        .unwrap();
1592
        for (name, id, sk, t) in cosigners {
1593
            note.sigs
1594
                .extend(tlog::cosign(&note.text, name, id, sk, *t).unwrap());
1595
        }
1596
        note.encode()
1597
    };
1598
    let latest = note_of(8, &[]);
1599
    let witnessed_at = (t0 + 360_000) / 1000;
1600
    let cosigned = note_of(
1601
        4,
1602
        &[
1603
            ("w.example", &w, &w_sk, witnessed_at),
1604
            ("s.example", &stranger, &stranger_sk, 1),
1605
        ],
1606
    );
1607
    let answer = |integration: Vec<Integration>, witnesses: Vec<(String, Vec<u8>)>| RefsResponse {
1608
        refs: vec![RemoteRef {
1609
            name: "main".into(),
1610
            state: ObjectRef([2; 32]),
1611
            heads: vec![],
1612
            attestation: Some(sa.clone()),
1613
            last_serial: None,
1614
            accepted: None,
1615
            logged: Some(Logged {
1616
                index: 3,
1617
                entry: entry_of(3),
1618
                proof: tlog::prove_inclusion(8, 3, &stored).unwrap(),
1619
            }),
1620
            integration,
1621
        }],
1622
        log: Some(latest.clone()),
1623
        witnesses,
1624
        ..RefsResponse::default()
1625
    };
1626
    let proof4 = tlog::prove_inclusion(4, 3, &stored).unwrap();
1627
    let served = vec![Integration {
1628
        note: cosigned.clone(),
1629
        proof: proof4.clone(),
1630
    }];
1631
    let listed = vec![("w.example".to_string(), w.encode())];
1632
    // This user saw the hub's log before (pinned, so nothing is fetched).
1633
    a.remember_log(hub, &log_key, &Note::parse(&latest).unwrap())
1634
        .unwrap();
1635
1636
    // The witness is pinned on first sight, silently; the stranger's
1637
    // earlier cosignature counts for nothing.
1638
    let resp = answer(served.clone(), listed.clone());
1639
    let lc = a.check_log(url, None, &resp).unwrap();
1640
    assert!(lc.notes.is_empty(), "{:?}", lc.notes);
1641
    let t = lc.time_of("main").unwrap();
1642
    assert_eq!((t.time, t.witness.as_str()), (witnessed_at, "w.example"));
1643
    // The certificate expired an hour and fifty minutes ago, but covered
1644
    // the integrated time: accepted, and nothing to say.
1645
    assert!(cert.cert.expires < now);
1646
    let mut notes = Vec::new();
1647
    a.authorize_in_time(&p, "origin", &resp.refs[0], &sa, &signer, &lc, &mut notes)
1648
        .unwrap();
1649
    assert!(notes.is_empty(), "{notes:?}");
1650
1651
    // Only the stranger cosigned: no witnessed time, so the earlier rule
1652
    // (the attestation's own time, inside the window), said so.
1653
    let lonely = vec![Integration {
1654
        note: note_of(4, &[("s.example", &stranger, &stranger_sk, 1)]),
1655
        proof: proof4.clone(),
1656
    }];
1657
    let resp = answer(lonely, vec![]);
1658
    let lc = a.check_log(url, None, &resp).unwrap();
1659
    assert!(lc
1660
        .time_of("main")
1661
        .unwrap_err()
1662
        .contains("no witness this user trusts"));
1663
    let mut notes = Vec::new();
1664
    a.authorize_in_time(&p, "origin", &resp.refs[0], &sa, &signer, &lc, &mut notes)
1665
        .unwrap();
1666
    assert!(
1667
        notes.len() == 1 && notes[0].contains("not at a witnessed time"),
1668
        "{notes:?}"
1669
    );
1670
1671
    // A witness listed later under the pinned name with another key is
1672
    // pinned with a note, as a new log key is.
1673
    let resp = answer(
1674
        served.clone(),
1675
        vec![("w.example".into(), stranger.encode())],
1676
    );
1677
    let lc = a.check_log(url, None, &resp).unwrap();
1678
    assert!(
1679
        lc.notes.iter().any(|n| n.contains("another key")),
1680
        "{:?}",
1681
        lc.notes
1682
    );
1683
    assert!(
1684
        lc.time_of("main").is_err(),
1685
        "w's cosignature is by its old key"
1686
    );
1687
    a.check_log(url, None, &answer(served.clone(), listed.clone()))
1688
        .unwrap();
1689
1690
    // An old peer's answer: no log, no witnesses, no integration. Judged
1691
    // as before, silently.
1692
    let mut old = answer(vec![], vec![]);
1693
    old.log = None;
1694
    old.refs[0].logged = None;
1695
    let lc = a.check_log(url, None, &old).unwrap();
1696
    assert!(!lc.kept && lc.notes.is_empty());
1697
    let mut notes = Vec::new();
1698
    a.authorize_in_time(&p, "origin", &old.refs[0], &sa, &signer, &lc, &mut notes)
1699
        .unwrap();
1700
    assert!(notes.is_empty(), "{notes:?}");
1701
1702
    // Judged at given integrated times.
1703
    let at = |secs_after_t0: u64| {
1704
        let mut times = std::collections::HashMap::new();
1705
        times.insert(
1706
            "main".to_string(),
1707
            Ok(Integrated {
1708
                time: (t0 + secs_after_t0 * 1000) / 1000,
1709
                witness: "w.example".into(),
1710
                size: 4,
1711
            }),
1712
        );
1713
        LogCheck {
1714
            kept: true,
1715
            times,
1716
            ..LogCheck::default()
1717
        }
1718
    };
1719
    let judged = |sa: &SignedAttest, lc: &LogCheck| {
1720
        let mut notes = Vec::new();
1721
        a.authorize_in_time(&p, "origin", &old.refs[0], sa, &signer, lc, &mut notes)
1722
            .map(|_| notes)
1723
    };
1724
    // Claimed inside the window, first witnessed an hour later, after
1725
    // the certificate expired: backdated, or held back. Accepted by the
1726
    // earlier rule while logs are new, with both said.
1727
    let notes = judged(&sa, &at(3600)).unwrap();
1728
    assert!(
1729
        notes
1730
            .iter()
1731
            .any(|n| n.contains("had lapsed when witness w.example"))
1732
            && notes
1733
                .iter()
1734
                .any(|n| n.contains("55 minutes before witness")),
1735
        "{notes:?}"
1736
    );
1737
    // Claimed after the certificate expired, but witnessed inside its
1738
    // window: the clock the signer did not choose decides. The gap is
1739
    // still noted.
1740
    let fast = attested(now);
1741
    let notes = judged(&fast, &at(400)).unwrap();
1742
    assert!(
1743
        notes.len() == 1 && notes[0].contains("after witness w.example saw it"),
1744
        "{notes:?}"
1745
    );
1746
    // Claimed and witnessed after it expired: refused, as before.
1747
    assert!(judged(&fast, &at(3600)).is_err());
1748
    // A gap within ten minutes is nothing to note.
1749
    assert!(judged(&sa, &at(500)).unwrap().is_empty());
1750
}
1751
1752
/// Keyless step 5 (oxygenhub#241): an agent's fresh key, certified for a
1753
/// subject the author granted, seals changes in the author's name; with
1754
/// no grant, a stranger's, or one that had ended, it is neither the
1755
/// author nor a delegate.
1756
/// oxygen#135: an owner renews or rotates with every delegation, and a
1757
/// repository may name the newest key as the author; the agent's grant by
1758
/// the earlier key still counts, but not one that key made after.
1759
#[test]
1760
fn a_grant_outlives_its_owner_s_rotation() {
1761
    use crate::cert::{Certificate, Grant, SignedCertificate, SignedGrant};
1762
    use crate::identity::Scope;
1763
    hermetic();
1764
    let dir = tempfile::tempdir().unwrap();
1765
    let root = dir.path();
1766
    let mut a = Repo::init(&root.join("a"))
1767
        .unwrap()
1768
        .with_home(root.join("home-a"));
1769
    let (old, _) = a
1770
        .create_identity("Ada", "[email protected]", IdentityScope::User)
1771
        .unwrap();
1772
    let (_, old_sk) = a.secret_key().unwrap().unwrap();
1773
    let old_id = a.identity(&old).unwrap();
1774
    let hub_sk = SecretKey::generate();
1775
    let hub = hub_sk.identity("hub", "[email protected]", 1);
1776
    let now = Hlc::now().wall_ms;
1777
    let grant = |from: u64| {
1778
        SignedGrant::sign(
1779
            Grant {
1780
                grantor: old,
1781
                subject: "agent:claude@ada".into(),
1782
                issuer: hub.hash(),
1783
                scope: Scope::CHANGES | Scope::SEAL,
1784
                not_before: from,
1785
                expires: now + 86_400_000,
1786
            },
1787
            &old_id,
1788
            &old_sk,
1789
        )
1790
    };
1791
    let before = grant(now - 60_000);
1792
    let after = grant(now + 60_000);
1793
    let rot = a.renew_identity(None).unwrap();
1794
    assert_ne!(rot.new, old);
1795
    let agent = |name: &str, g: SignedGrant| {
1796
        let mut r = Repo::init(&root.join(name))
1797
            .unwrap()
1798
            .with_home(root.join(format!("home-{name}")));
1799
        let (key, id) = r
1800
            .create_identity(name, "[email protected]", IdentityScope::User)
1801
            .unwrap();
1802
        for i in [&old_id, &rot.identity, &hub] {
1803
            r.store().put_identity(i).unwrap();
1804
        }
1805
        r.set_user_config("author.key", &rot.new.to_hex()).unwrap();
1806
        r.set_user_config("author.signer", &key.to_hex()).unwrap();
1807
        let cert = SignedCertificate::sign(
1808
            Certificate {
1809
                key: id,
1810
                issuer: hub.hash(),
1811
                subject: "agent:claude@ada".into(),
1812
                claims: vec![],
1813
                scope: Scope::CHANGES | Scope::REFS | Scope::SEAL,
1814
                not_before: now - 60_000,
1815
                expires: now + 600_000,
1816
                grant: Some(g),
1817
            },
1818
            &hub,
1819
            &hub_sk,
1820
        );
1821
        r.store().put_certificate(&cert).unwrap();
1822
        write(&root.join(name), "work.txt", b"agent work\n");
1823
        let h = r.commit("work", &[]).unwrap();
1824
        assert_eq!(r.store().get_change_meta(&h).unwrap().author, rot.new);
1825
        r.seal(&[h]).unwrap();
1826
        (r, h)
1827
    };
1828
    let (r, h) = agent("kept", before);
1829
    assert!(
1830
        matches!(
1831
            r.authenticate_change(&h).unwrap(),
1832
            SignatureStatus::Valid { .. }
1833
        ),
1834
        "{:?}",
1835
        r.authenticate_change(&h).unwrap()
1836
    );
1837
    let (r, h) = agent("late", after);
1838
    assert!(
1839
        matches!(r.authenticate_change(&h).unwrap(), SignatureStatus::Invalid(e) if e.contains("neither")),
1840
        "a grant the old key made after the rotation: {:?}",
1841
        r.authenticate_change(&h).unwrap()
1842
    );
1843
}
1844
1845
#[test]
1846
fn a_certified_key_acts_for_its_author_under_a_grant() {
1847
    use crate::cert::{Certificate, Grant, SignedCertificate, SignedGrant};
1848
    use crate::identity::{Identity, Scope};
1849
    hermetic();
1850
    let dir = tempfile::tempdir().unwrap();
1851
    let root = dir.path();
1852
    let _origin = Repo::init(&root.join("origin")).unwrap();
1853
    let url = root.join("origin").to_string_lossy().to_string();
1854
    let mut a = Repo::clone(&url, &root.join("a"))
1855
        .unwrap()
1856
        .with_home(root.join("home-a"));
1857
    let (ada, _) = a
1858
        .create_identity("Ada", "[email protected]", IdentityScope::User)
1859
        .unwrap();
1860
    write(&root.join("a"), "a.txt", b"a\n");
1861
    a.commit("a", &[]).unwrap();
1862
    a.policy_init().unwrap();
1863
    assert!(a.push("origin", false).unwrap().iter().all(|r| r.ok));
1864
    let hub_sk = SecretKey::generate();
1865
    let hub = hub_sk.identity("hub", "[email protected]", 1);
1866
    a.policy_grant_subject(
1867
        "agent:claude@ada",
1868
        hub.clone(),
1869
        Scope::CHANGES | Scope::REFS,
1870
        None,
1871
    )
1872
    .unwrap();
1873
    assert!(a.push("origin", false).unwrap().iter().all(|r| r.ok));
1874
    let (_, ada_sk) = a.secret_key().unwrap().unwrap();
1875
    let ada_id = a.identity(&ada).unwrap();
1876
1877
    let now = Hlc::now().wall_ms;
1878
    let grant = |by: &Identity, sk: &SecretKey, from: u64, to: u64| {
1879
        SignedGrant::sign(
1880
            Grant {
1881
                grantor: by.hash(),
1882
                subject: "agent:claude@ada".into(),
1883
                issuer: hub.hash(),
1884
                scope: Scope::CHANGES | Scope::SEAL,
1885
                not_before: from,
1886
                expires: to,
1887
            },
1888
            by,
1889
            sk,
1890
        )
1891
    };
1892
    // Ada's work as an agent runs it: Ada the author, a fresh key the hub
1893
    // certified (with `g` inside) the signer.
1894
    let agent = |name: &str, g: Option<SignedGrant>| {
1895
        let mut r = Repo::clone(&url, &root.join(name))
1896
            .unwrap()
1897
            .with_home(root.join(format!("home-{name}")));
1898
        let (key, id) = r
1899
            .create_identity(name, "[email protected]", IdentityScope::User)
1900
            .unwrap();
1901
        r.set_user_config("author.key", &ada.to_hex()).unwrap();
1902
        r.set_user_config("author.signer", &key.to_hex()).unwrap();
1903
        let cert = SignedCertificate::sign(
1904
            Certificate {
1905
                key: id,
1906
                issuer: hub.hash(),
1907
                subject: "agent:claude@ada".into(),
1908
                claims: vec![],
1909
                scope: Scope::CHANGES | Scope::REFS | Scope::SEAL,
1910
                not_before: now - 60_000,
1911
                expires: now + 600_000,
1912
                grant: g,
1913
            },
1914
            &hub,
1915
            &hub_sk,
1916
        );
1917
        r.store().put_identity(&hub).unwrap();
1918
        r.store().put_certificate(&cert).unwrap();
1919
        write(&root.join(name), &format!("{name}.txt"), b"agent work\n");
1920
        let h = r.commit("work", &[]).unwrap();
1921
        assert_eq!(r.store().get_change_meta(&h).unwrap().author, ada);
1922
        (r, key, h)
1923
    };
1924
1925
    let (claude, key, h) = agent(
1926
        "claude",
1927
        Some(grant(&ada_id, &ada_sk, now - 60_000, now + 86_400_000)),
1928
    );
1929
    let r = claude.push("origin", false).unwrap();
1930
    assert!(r.iter().all(|x| x.ok), "{r:?}");
1931
    let host = Repo::open(&root.join("origin")).unwrap();
1932
    assert!(
1933
        matches!(
1934
            host.authenticate_change(&h).unwrap(),
1935
            SignatureStatus::Valid { key: k, sealed: true, name, .. } if k == key && name == "agent:claude@ada"
1936
        ),
1937
        "named by its certificate's subject"
1938
    );
1939
    a.pull("origin").unwrap();
1940
    assert!(matches!(
1941
        a.authenticate_change(&h).unwrap(),
1942
        SignatureStatus::Valid { key: k, .. } if k == key
1943
    ));
1944
1945
    let (none, _, _) = agent("none", None);
1946
    let r = none.push("origin", false).unwrap();
1947
    assert!(r.iter().all(|x| !x.ok), "no grant: {r:?}");
1948
    let mallory_sk = SecretKey::generate();
1949
    let mallory = mallory_sk.identity("Mallory", "[email protected]", 1);
1950
    let (stranger, _, _) = agent(
1951
        "stranger",
1952
        Some(grant(&mallory, &mallory_sk, now - 60_000, now + 600_000)),
1953
    );
1954
    let r = stranger.push("origin", false).unwrap();
1955
    assert!(r.iter().all(|x| !x.ok), "a stranger's grant: {r:?}");
1956
    let (ended, _, eh) = agent(
1957
        "ended",
1958
        Some(grant(&ada_id, &ada_sk, now - 7_200_000, now - 3_600_000)),
1959
    );
1960
    let r = ended.push("origin", false).unwrap();
1961
    assert!(r.iter().all(|x| !x.ok), "an ended grant: {r:?}");
1962
    assert!(matches!(
1963
        ended.authenticate_change(&eh).unwrap(),
1964
        SignatureStatus::Invalid(e) if e.contains("grant did not cover")
1965
    ));
1966
}
1967
1968
#[test]
1969
fn trust_policy_governs_pushes_and_fetches() {
1970
    hermetic();
1971
    let dir = tempfile::tempdir().unwrap();
1972
    let root = dir.path();
1973
    let origin = Repo::init(&root.join("origin")).unwrap();
1974
    let url = root.join("origin").to_string_lossy().to_string();
1975
1976
    // A is the root. Before the policy, an unsigned push from B is fine.
1977
    let mut a = Repo::clone(&url, &root.join("a"))
1978
        .unwrap()
1979
        .with_home(root.join("home-a"));
1980
    let (key_a, _) = a
1981
        .create_identity("Ada", "[email protected]", IdentityScope::User)
1982
        .unwrap();
1983
    let mut b = Repo::clone(&url, &root.join("b"))
1984
        .unwrap()
1985
        .with_home(root.join("home-b"));
1986
    write(&root.join("b"), "b.txt", b"b\n");
1987
    b.commit("unsigned before policy", &[]).unwrap();
1988
    assert!(b.push("origin", false).unwrap()[0].ok);
1989
    origin.refresh().unwrap();
1990
1991
    // A creates the policy and pushes it; origin now enforces it.
1992
    write(&root.join("a"), "a.txt", b"a\n");
1993
    a.commit("a", &[]).unwrap();
1994
    let sp = a.policy_init().unwrap();
1995
    assert_eq!(sp.policy.serial, 1);
1996
    a.pull("origin").unwrap();
1997
    let results = a.push("origin", false).unwrap();
1998
    origin.refresh().unwrap();
1999
    assert!(results.iter().all(|r| r.ok), "{results:?}");
2000
    assert_eq!(origin.current_policy().unwrap().unwrap().1.policy.serial, 1);
2001
2002
    // B pulls the policy. Without an identity B cannot push at all.
2003
    b.pull("origin").unwrap();
2004
    assert!(
2005
        b.current_policy().unwrap().is_some(),
2006
        "the policy arrived with the fetch"
2007
    );
2008
    assert!(b.push("origin", false).is_err());
2009
    // With an identity the policy does not list, the push is rejected by origin.
2010
    let (key_b, id_b) = b
2011
        .create_identity("Bob", "[email protected]", IdentityScope::User)
2012
        .unwrap();
2013
    write(&root.join("b"), "b.txt", b"b2\n");
2014
    let h_b2 = b.commit("b2 as Bob", &[]).unwrap();
2015
    assert_eq!(b.store().get_change(&h_b2).unwrap().author, key_b);
2016
    let r = b.push("origin", false).unwrap();
2017
    origin.refresh().unwrap();
2018
    assert!(
2019
        !r[0].ok && r[0].reason.contains("may not update"),
2020
        "{:?}",
2021
        r
2022
    );
2023
2024
    // A grants B (identity handed over as a file) and publishes the policy.
2025
    let sp = a.policy_grant(id_b.clone(), None).unwrap();
2026
    assert_eq!(sp.policy.serial, 2);
2027
    let r = a.push("origin", false).unwrap();
2028
    origin.refresh().unwrap();
2029
    assert!(r.iter().any(|x| x.name == "policy" && x.ok), "{r:?}");
2030
    // B must fetch the new policy before pushing.
2031
    assert!(b
2032
        .push("origin", false)
2033
        .unwrap_or_else(|e| vec![RefResult {
2034
            name: "main".into(),
2035
            ok: false,
2036
            reason: e.to_string()
2037
        }])
2038
        .iter()
2039
        .all(|x| !x.ok));
2040
    b.pull("origin").unwrap();
2041
    assert_eq!(b.current_policy().unwrap().unwrap().1.policy.serial, 2);
2042
    let r = b.push("origin", false).unwrap();
2043
    origin.refresh().unwrap();
2044
    assert!(r[0].ok, "{:?}", r);
2045
    // Origin verified B's change under the policy.
2046
    let heads = origin.bookmark_heads().unwrap();
2047
    for h in &heads {
2048
        let c = origin.store().get_change(h).unwrap();
2049
        if c.author == key_b {
2050
            origin
2051
                .change_allowed(
2052
                    h,
2053
                    &origin.current_policy().unwrap().unwrap().1.policy,
2054
                    "main",
2055
                )
2056
                .unwrap();
2057
        }
2058
    }
2059
2060
    // A policy signed by a non-root (B) is refused, as is a replayed serial.
2061
    let mut forged = b.current_policy().unwrap().unwrap().1.policy.clone();
2062
    forged.serial = 3;
2063
    forged.roots = vec![key_b];
2064
    let fh = forged.hash();
2065
    let (_, sk_b) = b.secret_key().unwrap().unwrap();
2066
    let forged = SignedPolicy {
2067
        policy: forged,
2068
        sigs: vec![sk_b.sign(Domain::Policy, &key_b, &fh)],
2069
    };
2070
    let r = origin
2071
        .receive_push(Bundle::default(), vec![], Some(forged), vec![])
2072
        .unwrap();
2073
    assert!(!r[0].ok && r[0].reason.contains("root"), "{:?}", r);
2074
    let stale = a.current_policy().unwrap().unwrap().1;
2075
    let mut old = stale.clone();
2076
    old.policy.serial = 1;
2077
    let r = origin
2078
        .receive_push(Bundle::default(), vec![], Some(old), vec![])
2079
        .unwrap();
2080
    assert!(!r[0].ok && r[0].reason.contains("serial"), "{:?}", r);
2081
2082
    // A revokes B; after B pulls the policy, B's pushes are refused again.
2083
    a.pull("origin").unwrap();
2084
    a.policy_revoke(&key_b).unwrap();
2085
    let r = a.push("origin", false).unwrap();
2086
    origin.refresh().unwrap();
2087
    assert!(r.iter().any(|x| x.name == "policy" && x.ok), "{r:?}");
2088
    b.pull("origin").unwrap();
2089
    write(&root.join("b"), "b.txt", b"b3\n");
2090
    b.commit("b3", &[]).unwrap();
2091
    let r = b.push("origin", false).unwrap();
2092
    origin.refresh().unwrap();
2093
    assert!(!r[0].ok, "{:?}", r);
2094
2095
    // A clone by a third party receives and verifies everything.
2096
    let c = Repo::clone(&url, &root.join("c"))
2097
        .unwrap()
2098
        .with_home(root.join("home-c"));
2099
    assert_eq!(c.current_policy().unwrap().unwrap().1.policy.serial, 3);
2100
    assert!(c
2101
        .current_policy()
2102
        .unwrap()
2103
        .unwrap()
2104
        .1
2105
        .policy
2106
        .roots
2107
        .contains(&key_a));
2108
    assert!(!c.snapshot("status").unwrap().changed);
2109
}
2110
2111
/// oxygen#66: a gc says what it is doing, phase by phase.
2112
#[test]
2113
fn gc_reports_its_phases() {
2114
    hermetic();
2115
    let dir = tempfile::tempdir().unwrap();
2116
    let repo = Repo::init(dir.path()).unwrap();
2117
    for i in 0..3 {
2118
        write(
2119
            dir.path(),
2120
            &format!("f{i}.txt"),
2121
            format!("{i}\n").as_bytes(),
2122
        );
2123
        repo.commit(&format!("c{i}"), &[]).unwrap();
2124
    }
2125
    let mut phases = Vec::new();
2126
    repo.gc_with(true, &mut |p| phases.push(p.to_string()))
2127
        .unwrap();
2128
    assert_eq!(phases[0], "finding what is reachable", "{phases:?}");
2129
    assert!(
2130
        phases.iter().any(|p| p.starts_with("pruning")),
2131
        "{phases:?}"
2132
    );
2133
    assert!(
2134
        phases.iter().any(|p| p.starts_with("packing 0 of ")),
2135
        "{phases:?}"
2136
    );
2137
    assert!(
2138
        phases
2139
            .iter()
2140
            .any(|p| p.starts_with("writing the index of ")),
2141
        "{phases:?}"
2142
    );
2143
}
2144
2145
#[test]
2146
fn gc_packs_objects_and_history_still_works() {
2147
    hermetic();
2148
    let dir = tempfile::tempdir().unwrap();
2149
    let root = dir.path();
2150
    let mut repo = Repo::init(root).unwrap().with_home(root.join("home"));
2151
    repo.create_identity("Ada", "a@b", IdentityScope::User)
2152
        .unwrap();
2153
    repo.set_user_config("core.sign", "change").unwrap();
2154
    write(root, "a.txt", b"one\n");
2155
    let h1 = repo.commit("one", &[]).unwrap();
2156
    write(root, "a.txt", b"two\n");
2157
    write(root, "big.bin", &vec![0u8; 100_000]);
2158
    let h2 = repo.commit("two", &[]).unwrap();
2159
    // Several snapshots leave superseded working-copy versions behind.
2160
    for i in 0..5 {
2161
        write(root, "a.txt", format!("two\n{i}\n").as_bytes());
2162
        repo.snapshot("status").unwrap();
2163
    }
2164
    write(root, "a.txt", b"two\n");
2165
    repo.snapshot("status").unwrap();
2166
    let before = repo.store().list().unwrap();
2167
    assert!(repo.store().loose_count().unwrap() > 0);
2168
2169
    // With the default retention every operation's view is a root: nothing prunes.
2170
    let r = repo.gc(true).unwrap();
2171
    assert_eq!(r.packed.objects, before.len());
2172
    assert_eq!(r.pruned.objects, 0);
2173
    assert_eq!(repo.store().loose_count().unwrap(), 0);
2174
    assert_eq!(repo.store().list().unwrap(), before);
2175
2176
    // With zero retention only the current view is a root: superseded
2177
    // working copies go, everything reachable stays.
2178
    repo.config.set("core.op-retention", "0").unwrap();
2179
    repo.save_config().unwrap();
2180
    let mut repo = Repo::open(root).unwrap().with_home(root.join("home"));
2181
    let r = repo.gc(true).unwrap();
2182
    assert!(r.pruned.objects >= 5, "{r:?}");
2183
    let after = repo.store().list().unwrap();
2184
    assert!(after.len() < before.len());
2185
    assert!(after.contains(&h1) && after.contains(&h2));
2186
    for (_, op) in repo.op_log().unwrap() {
2187
        assert!(!op.command.is_empty(), "operation objects are all kept");
2188
    }
2189
    // Everything still works from the pruned, packed store.
2190
    assert_eq!(repo.bookmark_heads().unwrap(), vec![h2]);
2191
    assert!(matches!(
2192
        repo.verify_change(&h2).unwrap(),
2193
        SignatureStatus::Valid { .. }
2194
    ));
2195
    assert_eq!(repo.log().unwrap().len(), 3);
2196
    repo.checkout(&[h1], false, "checkout").unwrap();
2197
    assert_eq!(fs::read(root.join("a.txt")).unwrap(), b"one\n");
2198
    repo.checkout(&[h2], false, "checkout").unwrap();
2199
    assert_eq!(fs::read(root.join("big.bin")).unwrap().len(), 100_000);
2200
    assert!(!repo.snapshot("status").unwrap().changed);
2201
    // Grace period defers pruning of young garbage.
2202
    write(root, "a.txt", b"three\n");
2203
    repo.commit("three", &[]).unwrap();
2204
    let r = repo.gc(false).unwrap();
2205
    assert_eq!(r.pruned.objects, 0);
2206
    assert!(r.pruned.deferred > 0);
2207
    let r = repo.gc(true).unwrap();
2208
    assert!(r.pruned.objects > 0);
2209
    assert_eq!(repo.log().unwrap().len(), 4);
2210
    // Restoring the default retention makes the old views roots again; the
2211
    // working copies they name were pruned, which gc tolerates.
2212
    repo.config.set("core.op-retention", "90").unwrap();
2213
    repo.save_config().unwrap();
2214
    let repo = Repo::open(root).unwrap().with_home(root.join("home"));
2215
    let r = repo.gc(false).unwrap();
2216
    assert_eq!(r.pruned.objects, 0);
2217
    assert_eq!(repo.log().unwrap().len(), 4);
2218
}
2219
2220
#[test]
2221
fn describe_amend_abandon_heads() {
2222
    hermetic();
2223
    let dir = tempfile::tempdir().unwrap();
2224
    let root = dir.path();
2225
    let mut repo = Repo::init(root).unwrap().with_home(root.join("home"));
2226
    repo.create_identity("Ada", "a@b", IdentityScope::User)
2227
        .unwrap();
2228
    repo.set_user_config("core.sign", "change").unwrap();
2229
    write(root, "a.txt", b"one\n");
2230
    let h1 = repo.commit("first", &[]).unwrap();
2231
    write(root, "a.txt", b"one\ntwo\n");
2232
    let h2 = repo.commit("secnod", &[]).unwrap();
2233
    let id2 = repo.store().get_change(&h2).unwrap().change_id;
2234
2235
    // describe: same ChangeId, new hash, bookmark and working copy follow.
2236
    let h2b = repo.describe(&h2, "second").unwrap();
2237
    assert_ne!(h2b, h2);
2238
    let c = repo.store().get_change(&h2b).unwrap();
2239
    assert_eq!(
2240
        (c.change_id, c.message.as_str(), c.deps.clone()),
2241
        (id2, "second", vec![h1])
2242
    );
2243
    assert_eq!(repo.bookmark_heads().unwrap(), vec![h2b]);
2244
    assert!(matches!(
2245
        repo.verify_change(&h2b).unwrap(),
2246
        SignatureStatus::Valid { .. }
2247
    ));
2248
    let s = repo.snapshot("status").unwrap();
2249
    assert!(s.statuses.is_empty(), "{:?}", s.statuses);
2250
    assert_eq!(
2251
        repo.resolve_change(&id2.short(8)).unwrap(),
2252
        h2b,
2253
        "the old object is no longer reachable from the log"
2254
    );
2255
    // Describing a non-head rewrites its dependents (h2b → h2c') and the working copy.
2256
    let h1b = repo.describe(&h1, "first, described").unwrap();
2257
    assert_ne!(h1b, h1);
2258
    let heads = repo.bookmark_heads().unwrap();
2259
    assert_eq!(heads.len(), 1);
2260
    let top = repo.store().get_change(&heads[0]).unwrap();
2261
    assert_eq!((top.change_id, top.deps.clone()), (id2, vec![h1b]));
2262
    assert!(
2263
        matches!(
2264
            repo.verify_change(&heads[0]).unwrap(),
2265
            SignatureStatus::Valid { .. }
2266
        ),
2267
        "rewritten own change is re-signed"
2268
    );
2269
    let (_, wc) = repo.working_copy().unwrap();
2270
    assert_eq!(
2271
        wc.deps,
2272
        vec![heads[0]],
2273
        "the working copy follows the rewrite"
2274
    );
2275
    assert!(!repo.snapshot("status").unwrap().changed);
2276
    let snap = repo.load_state(&heads).unwrap().materialize();
2277
    assert!(
2278
        matches!(&snap.files["a.txt"].content, FileContent::Text { bytes, .. } if bytes == b"one\ntwo\n")
2279
    );
2280
2281
    // amend: fold an edit into the head; the result is one change from h1.
2282
    write(root, "a.txt", b"one\ntwo\nthree\n");
2283
    write(root, "b.txt", b"b\n");
2284
    let h2c = repo.amend(None).unwrap();
2285
    let c = repo.store().get_change(&h2c).unwrap();
2286
    assert_eq!(c.change_id, id2);
2287
    assert_eq!(c.message, "second");
2288
    assert_eq!(repo.bookmark_heads().unwrap(), vec![h2c]);
2289
    assert_eq!(
2290
        repo.log().unwrap().len(),
2291
        3,
2292
        "working copy, amended head, first"
2293
    );
2294
    let snap = repo.load_state(&[h2c]).unwrap().materialize();
2295
    assert!(
2296
        matches!(&snap.files["a.txt"].content, FileContent::Text { bytes, .. } if bytes == b"one\ntwo\nthree\n")
2297
    );
2298
    assert!(snap.files.contains_key("b.txt"));
2299
    assert!(!repo.snapshot("status").unwrap().changed);
2300
    assert!(
2301
        repo.amend(None).is_err(),
2302
        "clean working copy and no message"
2303
    );
2304
    let h2d = repo.amend(Some("second, amended")).unwrap();
2305
    assert_eq!(
2306
        repo.store().get_change(&h2d).unwrap().message,
2307
        "second, amended"
2308
    );
2309
2310
    // abandon: the head goes, its content stays as uncommitted work.
2311
    repo.abandon(&h2d).unwrap();
2312
    assert_eq!(
2313
        repo.bookmark_heads().unwrap(),
2314
        vec![h1b],
2315
        "the described first change is the head again"
2316
    );
2317
    let s = repo.snapshot("status").unwrap();
2318
    let paths: Vec<_> = s
2319
        .statuses
2320
        .iter()
2321
        .map(|p| (p.path.as_str(), p.status))
2322
        .collect();
2323
    assert_eq!(
2324
        paths,
2325
        vec![
2326
            ("a.txt", ChangeStatus::Modified),
2327
            ("b.txt", ChangeStatus::Added)
2328
        ]
2329
    );
2330
    assert_eq!(fs::read(root.join("a.txt")).unwrap(), b"one\ntwo\nthree\n");
2331
    let h3 = repo.commit("recommitted", &[]).unwrap();
2332
    assert_eq!(repo.bookmark_heads().unwrap(), vec![h3]);
2333
    // undo brings the abandoned head back.
2334
    repo.undo().unwrap();
2335
    repo.undo().unwrap();
2336
    assert_eq!(repo.bookmark_heads().unwrap(), vec![h2d]);
2337
2338
    // Abandoning a non-head whose dependent references its atoms reifies
2339
    // the references (here: a.txt vanishes with it, so the dependent's edit
2340
    // of a.txt is dropped with a note) instead of refusing; undo restores it.
2341
    let base = repo.bookmark_heads().unwrap()[0];
2342
    let base_change = repo.store().get_change(&base).unwrap();
2343
    let h1_now = base_change.deps[0];
2344
    let notes = repo.abandon(&h1_now).unwrap();
2345
    assert!(
2346
        !notes.is_empty(),
2347
        "the dependent's edit of a.txt was reified"
2348
    );
2349
    let heads = repo.bookmark_heads().unwrap();
2350
    let after = repo.load_state(&heads).unwrap().materialize();
2351
    assert!(
2352
        !after.files.contains_key("a.txt") && after.files.contains_key("b.txt"),
2353
        "{:?}",
2354
        after.files.keys()
2355
    );
2356
    repo.undo().unwrap();
2357
    assert_eq!(repo.bookmark_heads().unwrap(), vec![base]);
2358
    write(root, "c.txt", b"c\n");
2359
    let hc = repo.commit("c", &[]).unwrap();
2360
    write(root, "d.txt", b"d\n");
2361
    let hd = repo.commit("d", &[hc]).unwrap();
2362
    assert_eq!(repo.store().get_change(&hd).unwrap().deps, vec![hc]);
2363
    repo.abandon(&hc).unwrap();
2364
    let heads: BTreeSet<_> = repo.bookmark_heads().unwrap().into_iter().collect();
2365
    assert!(!heads.contains(&hc));
2366
    let d_now = heads
2367
        .iter()
2368
        .find(|h| repo.store().get_change(h).unwrap().message == "d")
2369
        .copied()
2370
        .unwrap();
2371
    assert!(
2372
        repo.store().get_change(&d_now).unwrap().deps.is_empty(),
2373
        "d inherited c's (empty) dependencies"
2374
    );
2375
    let s = repo.snapshot("status").unwrap();
2376
    assert_eq!(
2377
        s.statuses
2378
            .iter()
2379
            .map(|p| p.path.as_str())
2380
            .collect::<Vec<_>>(),
2381
        vec!["c.txt"],
2382
        "c's content is now uncommitted work"
2383
    );
2384
}
2385
2386
#[test]
2387
fn git_export_mirrors_history() {
2388
    hermetic();
2389
    if std::process::Command::new("git")
2390
        .arg("--version")
2391
        .output()
2392
        .is_err()
2393
    {
2394
        eprintln!("git not installed; skipping");
2395
        return;
2396
    }
2397
    let dir = tempfile::tempdir().unwrap();
2398
    let root = dir.path();
2399
    let mut repo = Repo::init(&root.join("r"))
2400
        .unwrap()
2401
        .with_home(root.join("home"));
2402
    repo.create_identity("Ada Lovelace", "[email protected]", IdentityScope::User)
2403
        .unwrap();
2404
    let r = root.join("r");
2405
    write(&r, "README.md", b"hello\n");
2406
    write(&r, "src/main.rs", b"fn main() {}\n");
2407
    let h1 = repo.commit("first", &[]).unwrap();
2408
    write(&r, "src/main.rs", b"fn main() { run(); }\n");
2409
    write(&r, "logo.png", b"\x89PNG\0\0");
2410
    let h2 = repo.commit("second", &[]).unwrap();
2411
2412
    let git_dir = root.join("mirror.git");
2413
    let rep = repo.git_export(&git_dir).unwrap();
2414
    assert_eq!((rep.exported, rep.skipped, rep.heads), (2, 0, 1));
2415
    let git = |args: &[&str]| -> String {
2416
        let out = std::process::Command::new("git")
2417
            .arg("-C")
2418
            .arg(&git_dir)
2419
            .args(args)
2420
            .output()
2421
            .unwrap();
2422
        assert!(
2423
            out.status.success(),
2424
            "{}",
2425
            String::from_utf8_lossy(&out.stderr)
2426
        );
2427
        String::from_utf8_lossy(&out.stdout).trim().to_string()
2428
    };
2429
    assert_eq!(git(&["log", "--format=%s", "main"]), "second\nfirst");
2430
    assert_eq!(git(&["show", "main:src/main.rs"]), "fn main() { run(); }");
2431
    assert_eq!(git(&["show", "main:README.md"]), "hello");
2432
    let body = git(&["log", "-1", "--format=%B", "main"]);
2433
    assert!(
2434
        body.contains(&format!("Oxy-Hash: {}", h2.to_hex())),
2435
        "{body}"
2436
    );
2437
    assert!(body.contains("Change-Id: "), "{body}");
2438
    assert_eq!(
2439
        git(&["log", "-1", "--format=%an <%ae>", "main"]),
2440
        "Ada Lovelace <[email protected]>"
2441
    );
2442
    assert_eq!(
2443
        git(&["ls-tree", "--name-only", "main"]),
2444
        "README.md\nlogo.png\nsrc"
2445
    );
2446
2447
    // Re-export is incremental.
2448
    let rep = repo.git_export(&git_dir).unwrap();
2449
    assert_eq!((rep.exported, rep.skipped), (0, 2));
2450
2451
    // An independent change makes two heads; the next state is one more
2452
    // commit on the linear branch whose tree is the union.
2453
    repo.checkout(&[h1], false, "checkout").unwrap();
2454
    write(&r, "other.txt", b"o\n");
2455
    let h3 = repo.commit("third", &[]).unwrap();
2456
    let rep = repo.git_export(&git_dir).unwrap();
2457
    assert_eq!((rep.exported, rep.heads), (1, 2));
2458
    assert_eq!(git(&["log", "--format=%s", "main"]), "third\nsecond\nfirst");
2459
    let parents = git(&["rev-list", "--parents", "-1", "main"]);
2460
    assert_eq!(parents.split(' ').count(), 2, "one parent: {parents}");
2461
    assert_eq!(git(&["show", "main:other.txt"]), "o");
2462
    assert_eq!(git(&["show", "main:src/main.rs"]), "fn main() { run(); }");
2463
    assert_eq!(
2464
        git(&["ls-tree", "--name-only", "main"]),
2465
        "README.md\nlogo.png\nother.txt\nsrc"
2466
    );
2467
    let body = git(&["log", "-1", "--format=%B", "main"]);
2468
    assert!(
2469
        body.contains(&format!("Oxy-Hash: {}", h3.to_hex())) && body.contains("Oxy-State: "),
2470
        "{body}"
2471
    );
2472
    // A rewrite is a new state whose one new change is the rewritten one.
2473
    repo.describe(&h3, "third, described").unwrap();
2474
    let rep = repo.git_export(&git_dir).unwrap();
2475
    assert_eq!(rep.exported, 1);
2476
    assert_eq!(
2477
        git(&["log", "-1", "--format=%s", "main"]),
2478
        "third, described"
2479
    );
2480
    assert_eq!(git(&["log", "--format=%s", "main"]).lines().count(), 4);
2481
    let _ = h2;
2482
}
2483
2484
#[test]
2485
fn git_import_reproduces_trees() {
2486
    git_import_reproduces_trees_with(None);
2487
}
2488
2489
/// The same import with every merge rendered in batches of one file
2490
/// (oxygen#25): what a merge onto a base of thousands of files takes.
2491
#[test]
2492
fn git_import_reproduces_trees_in_batches() {
2493
    git_import_reproduces_trees_with(Some(1));
2494
}
2495
2496
fn git_import_reproduces_trees_with(batch: Option<usize>) {
2497
    crate::repo::git::set_merge_batch_for_tests(batch);
2498
    hermetic();
2499
    if std::process::Command::new("git")
2500
        .arg("--version")
2501
        .output()
2502
        .is_err()
2503
    {
2504
        eprintln!("git not installed; skipping");
2505
        return;
2506
    }
2507
    let dir = tempfile::tempdir().unwrap();
2508
    let root = dir.path();
2509
    let g = root.join("src.git");
2510
    fs::create_dir_all(&g).unwrap();
2511
    let git = |args: &[&str]| -> String {
2512
        let out = std::process::Command::new("git")
2513
            .arg("-C")
2514
            .arg(&g)
2515
            .args([
2516
                "-c",
2517
                "user.name=Grace",
2518
                "-c",
2519
                "[email protected]",
2520
                "-c",
2521
                "commit.gpgsign=false",
2522
            ])
2523
            .args(args)
2524
            .output()
2525
            .unwrap();
2526
        assert!(
2527
            out.status.success(),
2528
            "git {args:?}: {}",
2529
            String::from_utf8_lossy(&out.stderr)
2530
        );
2531
        String::from_utf8_lossy(&out.stdout).trim().to_string()
2532
    };
2533
    git(&["init", "-q", "-b", "main"]);
2534
    write(&g, "README.md", b"# Hi\n");
2535
    write(&g, "src/lib.rs", b"pub fn a() {}\n");
2536
    git(&["add", "."]);
2537
    git(&["commit", "-q", "-m", "initial"]);
2538
    write(&g, "src/lib.rs", b"pub fn a() {}\npub fn b() {}\n");
2539
    write(&g, "run.sh", b"#!/bin/sh\n");
2540
    #[cfg(unix)]
2541
    {
2542
        use std::os::unix::fs::PermissionsExt;
2543
        fs::set_permissions(g.join("run.sh"), fs::Permissions::from_mode(0o755)).unwrap();
2544
    }
2545
    write(&g, "logo.png", b"\x89PNG\0\0\x01");
2546
    git(&["add", "."]);
2547
    git(&[
2548
        "commit",
2549
        "-q",
2550
        "-m",
2551
        "second\n\nChange-Id: 0123456789abcdef0123456789abcdef",
2552
    ]);
2553
    // A branch that edits README, merged back with a conflict-free merge.
2554
    git(&["checkout", "-q", "-b", "topic", "HEAD~1"]);
2555
    write(&g, "README.md", b"# Hi\n\nMore.\n");
2556
    git(&["commit", "-q", "-am", "readme"]);
2557
    git(&["checkout", "-q", "main"]);
2558
    git(&["merge", "-q", "--no-ff", "-m", "merge topic", "topic"]);
2559
    // A branch from the initial commit inserting at the same place as
2560
    // "second": concurrent in Oxygen too, so the merge commit is a resolution.
2561
    let initial = git(&["rev-list", "--max-parents=0", "HEAD"]);
2562
    git(&["checkout", "-q", "-b", "clash", &initial]);
2563
    write(&g, "src/lib.rs", b"pub fn a() {}\npub fn c() {}\n");
2564
    git(&["commit", "-q", "-am", "clash"]);
2565
    git(&["checkout", "-q", "main"]);
2566
    let _ = std::process::Command::new("git")
2567
        .arg("-C")
2568
        .arg(&g)
2569
        .args(["merge", "-q", "clash"])
2570
        .output();
2571
    write(
2572
        &g,
2573
        "src/lib.rs",
2574
        b"pub fn a() {}\npub fn b() {}\npub fn c() {}\n",
2575
    );
2576
    git(&["add", "."]);
2577
    git(&["commit", "-q", "-m", "resolve clash"]);
2578
    git(&["rm", "-q", "logo.png"]);
2579
    git(&["commit", "-q", "-m", "drop logo"]);
2580
    // A rename with a small edit is imported as a move of the same node.
2581
    git(&["mv", "src/lib.rs", "src/lib2.rs"]);
2582
    write(
2583
        &g,
2584
        "src/lib2.rs",
2585
        b"pub fn a() {}\npub fn b() {}\npub fn c() {}\npub fn d() {}\n",
2586
    );
2587
    git(&["add", "."]);
2588
    git(&["commit", "-q", "-m", "rename lib"]);
2589
    // A branch that edits run.sh, merged keeping main's tree (`-s ours`):
2590
    // run.sh is the same as in the first parent's tree, but the merged
2591
    // change touched it, so the importer must compare it, not skip it.
2592
    git(&["checkout", "-q", "-b", "discarded"]);
2593
    write(&g, "run.sh", b"#!/bin/sh\necho discarded\n");
2594
    git(&["commit", "-q", "-am", "discarded edit"]);
2595
    git(&["checkout", "-q", "main"]);
2596
    git(&[
2597
        "merge",
2598
        "-q",
2599
        "-s",
2600
        "ours",
2601
        "-m",
2602
        "merge discarded, keeping ours",
2603
        "discarded",
2604
    ]);
2605
    let expected_count: usize = git(&["rev-list", "--count", "main"]).parse().unwrap();
2606
2607
    let dest = root.join("oxy");
2608
    let repo = Repo::init(&dest).unwrap().with_home(root.join("home"));
2609
    let rep = repo.import_git(&g, "main").unwrap();
2610
    assert_eq!(rep.commits, expected_count);
2611
    assert_eq!(rep.merges, 3);
2612
    assert_eq!(
2613
        fs::read(dest.join("run.sh")).unwrap(),
2614
        b"#!/bin/sh\n",
2615
        "the ours merge kept main's run.sh"
2616
    );
2617
    let v = repo.verify_git_import(&g, "main").unwrap();
2618
    assert_eq!(v.commits, expected_count, "every commit's tree reproduced");
2619
    assert!(v.mismatches.is_empty(), "{:?}", v.mismatches);
2620
    // The working copy equals the Git tree at main.
2621
    assert_eq!(
2622
        fs::read(dest.join("src/lib2.rs")).unwrap(),
2623
        b"pub fn a() {}\npub fn b() {}\npub fn c() {}\npub fn d() {}\n"
2624
    );
2625
    assert!(!dest.join("src/lib.rs").exists());
2626
    assert_eq!(
2627
        fs::read(dest.join("README.md")).unwrap(),
2628
        b"# Hi\n\nMore.\n"
2629
    );
2630
    assert!(!dest.join("logo.png").exists());
2631
    #[cfg(unix)]
2632
    {
2633
        use std::os::unix::fs::PermissionsExt;
2634
        assert!(
2635
            fs::metadata(dest.join("run.sh"))
2636
                .unwrap()
2637
                .permissions()
2638
                .mode()
2639
                & 0o111
2640
                != 0
2641
        );
2642
    }
2643
    assert!(
2644
        !repo.snapshot("status").unwrap().changed,
2645
        "clean after import"
2646
    );
2647
    let heads = repo.bookmark_heads().unwrap();
2648
    let st = repo.load_state(&heads).unwrap();
2649
    assert!(!st.materialize().is_conflicted());
2650
    assert_eq!(st.len(), expected_count);
2651
    let tip = repo
2652
        .log()
2653
        .unwrap()
2654
        .into_iter()
2655
        .find(|e| e.change.message.starts_with("rename lib"))
2656
        .unwrap();
2657
    let c = repo.store().get_change(&tip.hash).unwrap();
2658
    assert!(
2659
        c.tree_ops
2660
            .iter()
2661
            .any(|op| matches!(op, TreeOp::Move { name, .. } if name == "lib2.rs")),
2662
        "{:?}",
2663
        c.tree_ops
2664
    );
2665
    assert!(!c
2666
        .tree_ops
2667
        .iter()
2668
        .any(|op| matches!(op, TreeOp::AddNode { .. })));
2669
    // Messages carry Git trailers; the Change-Id trailer was honoured.
2670
    let log = repo.log().unwrap();
2671
    let second = log
2672
        .iter()
2673
        .find(|e| e.change.message.starts_with("second"))
2674
        .unwrap();
2675
    assert_eq!(
2676
        second.change.change_id,
2677
        ChangeId::from_hex("0123456789abcdef0123456789abcdef").unwrap()
2678
    );
2679
    assert!(second
2680
        .change
2681
        .message
2682
        .contains("Git-Author: Grace <[email protected]>"));
2683
    let resolve = log
2684
        .iter()
2685
        .find(|e| e.change.message.starts_with("resolve clash"))
2686
        .unwrap();
2687
    assert_eq!(
2688
        resolve.change.kind,
2689
        ChangeKind::Resolution,
2690
        "a conflicting Git merge becomes a resolution"
2691
    );
2692
    // Re-importing into another fresh repository gives the same ChangeIds.
2693
    let repo2 = Repo::init(&root.join("oxy2"))
2694
        .unwrap()
2695
        .with_home(root.join("home"));
2696
    repo2.import_git(&g, "main").unwrap();
2697
    // New nodes' identifiers derive from the commit (spec §23), so the
2698
    // re-import is not just the same ChangeIds but the same changes.
2699
    assert_eq!(
2700
        repo2.bookmark_heads().unwrap(),
2701
        repo.bookmark_heads().unwrap()
2702
    );
2703
    let ids: BTreeSet<ChangeId> = repo
2704
        .log()
2705
        .unwrap()
2706
        .iter()
2707
        .filter(|e| !e.is_working_copy)
2708
        .map(|e| e.change.change_id)
2709
        .collect();
2710
    let ids2: BTreeSet<ChangeId> = repo2
2711
        .log()
2712
        .unwrap()
2713
        .iter()
2714
        .filter(|e| !e.is_working_copy)
2715
        .map(|e| e.change.change_id)
2716
        .collect();
2717
    assert_eq!(ids, ids2);
2718
    // Round trip back out to Git reproduces the tip tree.
2719
    let mirror = root.join("mirror.git");
2720
    repo.git_export(&mirror).unwrap();
2721
    let out = std::process::Command::new("git")
2722
        .arg("-C")
2723
        .arg(&mirror)
2724
        .args(["show", "main:src/lib2.rs"])
2725
        .output()
2726
        .unwrap();
2727
    assert_eq!(
2728
        String::from_utf8_lossy(&out.stdout),
2729
        "pub fn a() {}\npub fn b() {}\npub fn c() {}\npub fn d() {}\n"
2730
    );
2731
    let out = std::process::Command::new("git")
2732
        .arg("-C")
2733
        .arg(&mirror)
2734
        .args(["show", "main:src/lib.rs"])
2735
        .output()
2736
        .unwrap();
2737
    assert!(
2738
        !out.status.success(),
2739
        "the old path is gone from the export"
2740
    );
2741
}
2742
2743
#[test]
2744
fn checkpoints_accelerate_loading_and_stay_correct() {
2745
    hermetic();
2746
    let dir = tempfile::tempdir().unwrap();
2747
    let root = dir.path();
2748
    let mut repo = Repo::init(root).unwrap().with_home(root.join("home"));
2749
    repo.config.set("core.checkpoint-interval", "5").unwrap();
2750
    repo.save_config().unwrap();
2751
    let repo = Repo::open(root).unwrap().with_home(root.join("home"));
2752
    let mut hashes = Vec::new();
2753
    for i in 0..12 {
2754
        write(
2755
            root,
2756
            "a.txt",
2757
            format!(
2758
                "{}\n",
2759
                (0..=i)
2760
                    .map(|k| k.to_string())
2761
                    .collect::<Vec<_>>()
2762
                    .join("\n")
2763
            )
2764
            .as_bytes(),
2765
        );
2766
        write(root, &format!("f{i}.txt"), b"x\n");
2767
        hashes.push(repo.commit(&format!("c{i}"), &[]).unwrap());
2768
    }
2769
    let (_, cp) = repo
2770
        .latest_checkpoint("main")
2771
        .unwrap()
2772
        .expect("automatic checkpoint");
2773
    assert!(cp.count >= 5 && cp.count <= 12, "{}", cp.count);
2774
    // Loading through the checkpoint equals loading everything.
2775
    let heads = repo.bookmark_heads().unwrap();
2776
    let fast = repo.load_state(&heads).unwrap();
2777
    let full = repo.load_state_full(&heads).unwrap();
2778
    assert_eq!(fast.len(), full.len());
2779
    assert_eq!(fast.heads(), full.heads());
2780
    let (a, b) = (fast.materialize(), full.materialize());
2781
    assert_eq!(
2782
        a.files.keys().collect::<Vec<_>>(),
2783
        b.files.keys().collect::<Vec<_>>()
2784
    );
2785
    for (p, f) in &a.files {
2786
        assert_eq!(f.content, b.files[p].content, "{p}");
2787
    }
2788
    assert!(repo.load_state_checkpointed(&heads).unwrap().is_some());
2789
    // A head set that does not contain the checkpoint's heads falls back.
2790
    assert!(repo
2791
        .load_state_checkpointed(&[hashes[0]])
2792
        .unwrap()
2793
        .is_none());
2794
    assert_eq!(repo.load_state(&[hashes[0]]).unwrap().len(), 1);
2795
    // Everything else keeps working on top of the checkpoint.
2796
    assert!(!repo.snapshot("status").unwrap().changed);
2797
    let h = repo.describe(&hashes[3], "c3 described").unwrap();
2798
    assert_eq!(repo.store().get_change(&h).unwrap().message, "c3 described");
2799
    let (r, n, bytes) = repo.checkpoint().unwrap();
2800
    assert!(n >= 12 && bytes > 0);
2801
    assert_eq!(repo.latest_checkpoint("main").unwrap().unwrap().0, r);
2802
    write(root, "a.txt", b"after\n");
2803
    let h_after = repo.commit("after", &[]).unwrap();
2804
    let st = repo.load_state(&repo.bookmark_heads().unwrap()).unwrap();
2805
    assert!(st.contains(&h_after));
2806
    assert!(
2807
        matches!(&st.materialize().files["a.txt"].content, FileContent::Text { bytes, .. } if bytes == b"after\n")
2808
    );
2809
    assert_eq!(repo.log().unwrap().len(), 14);
2810
    // Checkpoints survive gc.
2811
    repo.gc(true).unwrap();
2812
    assert!(repo.latest_checkpoint("main").unwrap().is_some());
2813
    assert!(repo
2814
        .load_state_checkpointed(&repo.bookmark_heads().unwrap())
2815
        .unwrap()
2816
        .is_some());
2817
}
2818
2819
#[test]
2820
fn quick_status_for_prompts() {
2821
    hermetic();
2822
    let dir = tempfile::tempdir().unwrap();
2823
    let root = dir.path();
2824
    let origin = Repo::init(&root.join("origin")).unwrap();
2825
    let url = root.join("origin").to_string_lossy().to_string();
2826
    let a = Repo::clone(&url, &root.join("a"))
2827
        .unwrap()
2828
        .with_home(root.join("home"));
2829
    let ops_before = a.op_log().unwrap().len();
2830
    let info = a.quick_status().unwrap();
2831
    assert_eq!(
2832
        (
2833
            info.bookmark.as_str(),
2834
            info.heads,
2835
            info.dirty,
2836
            info.conflicted,
2837
            info.ahead,
2838
            info.behind
2839
        ),
2840
        ("main", 0, false, false, Some(0), Some(0))
2841
    );
2842
    write(&root.join("a"), "f.txt", b"f\n");
2843
    assert!(a.quick_status().unwrap().dirty, "a new file is dirty");
2844
    assert_eq!(
2845
        a.op_log().unwrap().len(),
2846
        ops_before,
2847
        "quick_status records nothing"
2848
    );
2849
    // A snapshotted but uncommitted change is still dirty.
2850
    a.snapshot("status").unwrap();
2851
    assert!(a.quick_status().unwrap().dirty);
2852
    a.commit("f", &[]).unwrap();
2853
    let info = a.quick_status().unwrap();
2854
    assert!(!info.dirty, "clean right after a commit");
2855
    assert_eq!((info.ahead, info.behind), (Some(1), Some(0)));
2856
    assert_eq!(
2857
        info.format("%b %c%d%x%A%D"),
2858
        format!("main {}+1", info.change_id)
2859
    );
2860
    assert_eq!(info.format("[%h heads] %a/%B %%"), "[1 heads] 1/0 %");
2861
    // Touching a file without changing it is not dirty; changing content of
2862
    // the same size is.
2863
    let p = root.join("a/f.txt");
2864
    let content = fs::read(&p).unwrap();
2865
    fs::write(&p, &content).unwrap();
2866
    assert!(!a.quick_status().unwrap().dirty);
2867
    fs::write(&p, b"g\n").unwrap();
2868
    assert!(a.quick_status().unwrap().dirty);
2869
    fs::write(&p, b"f\n").unwrap();
2870
    // Push, then a second clone commits and pushes: we are behind.
2871
    assert!(a.push("origin", false).unwrap()[0].ok);
2872
    assert_eq!(a.quick_status().unwrap().ahead, Some(0));
2873
    let b = Repo::clone(&url, &root.join("b"))
2874
        .unwrap()
2875
        .with_home(root.join("home-b"));
2876
    write(&root.join("b"), "g.txt", b"g\n");
2877
    b.commit("g", &[]).unwrap();
2878
    b.push("origin", false).unwrap();
2879
    a.fetch("origin").unwrap();
2880
    let info = a.quick_status().unwrap();
2881
    assert_eq!((info.ahead, info.behind), (Some(0), Some(1)));
2882
    assert_eq!(info.format("%A%D"), "-1");
2883
    let _ = origin;
2884
}
2885
2886
#[test]
2887
fn lazy_blobs_are_fetched_on_first_read() {
2888
    hermetic();
2889
    let dir = tempfile::tempdir().unwrap();
2890
    let root = dir.path();
2891
    let origin_dir = root.join("origin");
2892
    let origin = Repo::init(&origin_dir)
2893
        .unwrap()
2894
        .with_home(root.join("home"));
2895
    let url = origin_dir.to_string_lossy().to_string();
2896
    let big: Vec<u8> = (0..200_000u32).map(|i| (i % 251) as u8).collect(); // has NUL bytes: opaque
2897
    write(&origin_dir, "big.bin", &big);
2898
    write(&origin_dir, "small.bin", &[0u8, 1, 2]);
2899
    write(&origin_dir, "t.txt", b"t\n");
2900
    let h = origin.commit("blobs", &[]).unwrap();
2901
    let big_ref = Repo::blob_ref(&big);
2902
2903
    // Fetch only (no checkout) with a filter: the big blob stays absent.
2904
    let a = Repo::init_with_id(&root.join("a"), origin.id().unwrap())
2905
        .unwrap()
2906
        .with_home(root.join("home"));
2907
    let a = {
2908
        let mut a = a;
2909
        a.config.set("remote.origin.url", &url).unwrap();
2910
        a.config.set("filter.max-blob", "100K").unwrap();
2911
        a.save_config().unwrap();
2912
        a
2913
    };
2914
    assert_eq!(a.config.max_blob, Some(100 * 1024));
2915
    a.fetch("origin").unwrap();
2916
    assert!(a.store().has(&h));
2917
    assert!(!a.store().has(&big_ref), "withheld");
2918
    assert!(
2919
        a.store().has(&Repo::blob_ref(&[0u8, 1, 2])),
2920
        "small blob came along"
2921
    );
2922
    assert_eq!(a.lazy_remote(&big_ref).as_deref(), Some("origin"));
2923
2924
    // status and commit do not need it: adopt the state, edit a text file, commit.
2925
    let (op_ref, op) = a.head_op().unwrap();
2926
    let mut view = op.view.clone();
2927
    view.bookmarks.insert(
2928
        "main".into(),
2929
        a.store().put_state(&StateObject::new(vec![h])).unwrap(),
2930
    );
2931
    a.record_op(&[op_ref], "adopt", view).unwrap();
2932
    // Checkout reads the blob lazily, which fetches it.
2933
    a.checkout(&[h], true, "checkout").unwrap();
2934
    assert!(a.store().has(&big_ref), "fetched on first read");
2935
    assert_eq!(fs::read(root.join("a/big.bin")).unwrap(), big);
2936
    assert!(a.lazy_remote(&big_ref).is_none(), "no longer registered");
2937
    write(&root.join("a"), "t.txt", b"t2\n");
2938
    a.commit("text edit", &[]).unwrap();
2939
2940
    // clone --max-blob records the filter; the checkout fetches lazily.
2941
    let b = Repo::clone_with(&url, &root.join("b"), Some(1024), &[]).unwrap();
2942
    assert_eq!(b.config.max_blob, Some(1024));
2943
    assert_eq!(fs::read(root.join("b/big.bin")).unwrap(), big);
2944
    assert_eq!(parse_size("2M").unwrap(), 2 << 20);
2945
    assert!(parse_size("lots").is_err());
2946
}
2947
2948
#[test]
2949
fn sparse_checkout_materializes_only_chosen_paths() {
2950
    hermetic();
2951
    let dir = tempfile::tempdir().unwrap();
2952
    let root = dir.path();
2953
    let origin_dir = root.join("origin");
2954
    let origin = Repo::init(&origin_dir)
2955
        .unwrap()
2956
        .with_home(root.join("home"));
2957
    write(&origin_dir, "src/main.rs", b"fn main() {}\n");
2958
    write(&origin_dir, "src/lib.rs", b"pub fn a() {}\n");
2959
    write(&origin_dir, "docs/guide.md", b"# guide\n");
2960
    let logo: Vec<u8> = (0..50_000u32).map(|i| (i % 7) as u8).collect();
2961
    write(&origin_dir, "docs/logo.png", &logo);
2962
    write(&origin_dir, "README.md", b"# top\n");
2963
    let h1 = origin.commit("tree", &[]).unwrap();
2964
    let url = origin_dir.to_string_lossy().to_string();
2965
2966
    let a = Repo::clone_with(&url, &root.join("a"), None, &["src".into()])
2967
        .unwrap()
2968
        .with_home(root.join("home"));
2969
    assert_eq!(a.config.sparse_paths, vec!["src"]);
2970
    assert_eq!(a.config.max_blob, Some(0), "sparse implies lazy blobs");
2971
    assert!(root.join("a/src/main.rs").exists());
2972
    assert!(!root.join("a/docs").exists() && !root.join("a/README.md").exists());
2973
    assert!(
2974
        !a.store().has(&Repo::blob_ref(&logo)),
2975
        "out-of-scope blob never fetched"
2976
    );
2977
    assert!(
2978
        !a.snapshot("status").unwrap().changed,
2979
        "out-of-scope files are not removals"
2980
    );
2981
    assert!(!a.quick_status().unwrap().dirty);
2982
2983
    // Edits in scope commit normally and keep the rest of the tree intact.
2984
    write(
2985
        &root.join("a"),
2986
        "src/lib.rs",
2987
        b"pub fn a() {}\npub fn b() {}\n",
2988
    );
2989
    let h2 = a.commit("edit lib", &[]).unwrap();
2990
    let st = a.load_state(&[h2]).unwrap().materialize();
2991
    assert!(
2992
        st.files.contains_key("docs/guide.md"),
2993
        "the state still has everything"
2994
    );
2995
    assert!(a.push("origin", false).unwrap()[0].ok);
2996
    origin.refresh().unwrap();
2997
    // Files created outside the scope are ignored by status.
2998
    write(&root.join("a"), "docs/new.md", b"ignored\n");
2999
    assert!(a.snapshot("status").unwrap().statuses.is_empty());
3000
3001
    // Widening the filter checks out the rest; narrowing leaves stray files alone.
3002
    let mut a = a;
3003
    a.config.set("filter.paths", "src,docs").unwrap();
3004
    a.save_config().unwrap();
3005
    let r = a
3006
        .checkout(&a.bookmark_heads().unwrap(), true, "widen")
3007
        .unwrap();
3008
    assert!(r.written >= 2);
3009
    assert_eq!(
3010
        fs::read(root.join("a/docs/logo.png")).unwrap(),
3011
        logo,
3012
        "now fetched lazily"
3013
    );
3014
    assert!(!root.join("a/README.md").exists());
3015
    // Origin sees the change made under a sparse checkout with the full tree intact.
3016
    origin.pull("origin").err();
3017
    let full = origin
3018
        .load_state(&origin.bookmark_heads().unwrap())
3019
        .unwrap()
3020
        .materialize();
3021
    assert!(
3022
        matches!(&full.files["src/lib.rs"].content, FileContent::Text { bytes, .. } if bytes == b"pub fn a() {}\npub fn b() {}\n")
3023
    );
3024
    assert!(full.files.contains_key("README.md"));
3025
    let _ = h1;
3026
}
3027
3028
/// #137: a depth-0 clone takes no change, so the blobs of the state's
3029
/// binary files came with nothing and the checkout failed ("object … not
3030
/// found"); they are fetched with the checkpoint, or left lazy under
3031
/// `--max-blob`.
3032
#[test]
3033
fn a_depth_0_clone_brings_its_binary_files() {
3034
    hermetic();
3035
    let dir = tempfile::tempdir().unwrap();
3036
    let root = dir.path();
3037
    let origin_dir = root.join("origin");
3038
    let origin = Repo::init(&origin_dir)
3039
        .unwrap()
3040
        .with_home(root.join("home"));
3041
    let png: Vec<u8> = (0..4000u32)
3042
        .map(|i| (i * 7 % 251) as u8)
3043
        .chain([0, 0xff])
3044
        .collect();
3045
    // The logo comes with a.txt's first line, and the head edits that line,
3046
    // so the change that set the logo is below the head, not a head itself.
3047
    write(&origin_dir, "logo.png", &png);
3048
    write(&origin_dir, "a.txt", b"first\n");
3049
    origin.commit("logo", &[]).unwrap();
3050
    write(&origin_dir, "a.txt", b"later\n");
3051
    origin.commit("later", &[]).unwrap();
3052
    assert_eq!(origin.bookmark_heads().unwrap().len(), 1);
3053
    let url = origin_dir.to_string_lossy().to_string();
3054
    Repo::clone_shallow(&url, &root.join("a"), 0, None, &[]).unwrap();
3055
    assert_eq!(fs::read(root.join("a/logo.png")).unwrap(), png);
3056
    let lazy = Repo::clone_shallow(&url, &root.join("b"), 0, Some(0), &[]).unwrap();
3057
    assert_eq!(fs::read(root.join("b/a.txt")).unwrap(), b"later\n");
3058
    let blob = {
3059
        let heads = lazy.bookmark_heads().unwrap();
3060
        let st = lazy.load_state_history(&heads).unwrap();
3061
        st.opaque_nodes()
3062
            .iter()
3063
            .flat_map(|n| st.live_blobs(n))
3064
            .next()
3065
            .unwrap()
3066
    };
3067
    assert_eq!(lazy.read_blob(&blob).unwrap(), png, "fetched on read");
3068
}
3069
3070
#[test]
3071
fn shallow_clone_and_deepen() {
3072
    hermetic();
3073
    let dir = tempfile::tempdir().unwrap();
3074
    let root = dir.path();
3075
    let origin_dir = root.join("origin");
3076
    let origin = Repo::init(&origin_dir)
3077
        .unwrap()
3078
        .with_home(root.join("home"));
3079
    let mut hashes = Vec::new();
3080
    for i in 0..8 {
3081
        write(
3082
            &origin_dir,
3083
            "a.txt",
3084
            format!(
3085
                "{}\n",
3086
                (0..=i)
3087
                    .map(|k| k.to_string())
3088
                    .collect::<Vec<_>>()
3089
                    .join("\n")
3090
            )
3091
            .as_bytes(),
3092
        );
3093
        hashes.push(origin.commit(&format!("c{i}"), &[]).unwrap());
3094
    }
3095
    let url = origin_dir.to_string_lossy().to_string();
3096
    let a = Repo::clone_shallow(&url, &root.join("a"), 3, None, &[])
3097
        .unwrap()
3098
        .with_home(root.join("home"));
3099
    assert!(a.is_shallow());
3100
    assert_eq!(
3101
        fs::read_to_string(root.join("a/a.txt")).unwrap(),
3102
        "0\n1\n2\n3\n4\n5\n6\n7\n"
3103
    );
3104
    assert!(
3105
        a.store().has(&hashes[7]) && a.store().has(&hashes[5]),
3106
        "three levels present"
3107
    );
3108
    assert!(!a.store().has(&hashes[4]), "beyond the depth is absent");
3109
    assert_eq!(a.boundary(), [hashes[4]].into_iter().collect());
3110
    assert_eq!(
3111
        a.log().unwrap().len(),
3112
        9,
3113
        "the log shows every change from the checkpoint's metadata"
3114
    );
3115
    assert!(!a.snapshot("status").unwrap().changed);
3116
    assert_eq!(a.quick_status().unwrap().heads, 1);
3117
3118
    // Work continues on top of the shallow history and pushes back.
3119
    write(&root.join("a"), "a.txt", b"0\n1\n2\n3\n4\n5\n6\n7\n8\n");
3120
    let h_new = a.commit("c8", &[]).unwrap();
3121
    assert!(a.push("origin", false).unwrap()[0].ok);
3122
    origin.refresh().unwrap();
3123
    assert_eq!(origin.bookmark_heads().unwrap(), vec![h_new]);
3124
    // Fetching new work from origin into the shallow clone works too.
3125
    write(&origin_dir, "b.txt", b"b\n");
3126
    origin.pull("origin").err();
3127
    let (_, wc) = origin.working_copy().unwrap();
3128
    let _ = wc;
3129
    origin
3130
        .checkout(&origin.bookmark_heads().unwrap(), true, "co")
3131
        .unwrap();
3132
    write(&origin_dir, "b.txt", b"b\n");
3133
    let h_b = origin.commit("b", &[]).unwrap();
3134
    let pr = a.pull("origin").unwrap();
3135
    assert!(pr.changed);
3136
    assert!(a.store().has(&h_b));
3137
    assert!(root.join("a/b.txt").exists());
3138
3139
    // Deepening fetches older history until the boundary is gone.
3140
    // Every commit also depends on the change that created the file, so two
3141
    // levels below the boundary hold h4, h3, and the root.
3142
    assert!(a.deepen("origin", 2).unwrap() >= 2);
3143
    assert!(a.store().has(&hashes[3]));
3144
    assert!(a.is_shallow());
3145
    a.deepen("origin", 100).unwrap();
3146
    assert!(!a.is_shallow(), "boundary reached the root");
3147
    assert!(a.store().has(&hashes[0]));
3148
    assert_eq!(
3149
        a.load_state_full(&a.bookmark_heads().unwrap())
3150
            .unwrap()
3151
            .len(),
3152
        10
3153
    );
3154
}
3155
3156
#[test]
3157
fn tags_are_immutable_named_states_and_travel() {
3158
    hermetic();
3159
    let dir = tempfile::tempdir().unwrap();
3160
    let root = dir.path();
3161
    let origin = Repo::init(&root.join("origin")).unwrap();
3162
    let url = root.join("origin").to_string_lossy().to_string();
3163
    let mut a = Repo::clone(&url, &root.join("a"))
3164
        .unwrap()
3165
        .with_home(root.join("home-a"));
3166
    let (key_a, _) = a
3167
        .create_identity("Ada", "[email protected]", IdentityScope::User)
3168
        .unwrap();
3169
    write(&root.join("a"), "f.txt", b"1\n");
3170
    let h1 = a.commit("one", &[]).unwrap();
3171
    write(&root.join("a"), "f.txt", b"1\n2\n");
3172
    let h2 = a.commit("two", &[]).unwrap();
3173
3174
    let t = a.tag_create("v1", &[h1], "first release").unwrap();
3175
    assert_eq!(
3176
        (t.heads.clone(), t.signer.as_deref()),
3177
        (vec![h1], Some("Ada"))
3178
    );
3179
    assert!(a.tag_create("v1", &[h2], "").is_err(), "immutable");
3180
    assert!(a.tag_create("bad/name", &[h2], "").is_err());
3181
    assert_eq!(a.tag_heads("v1").unwrap(), Some(vec![h1]));
3182
    assert_eq!(a.resolve_heads("v1").unwrap(), vec![h1]);
3183
    assert_eq!(a.resolve_heads("main").unwrap(), vec![h2]);
3184
    let (_, sa) = a.tag_attest("v1").unwrap().unwrap();
3185
    assert_eq!(sa.sigs[0].key, key_a);
3186
    // Without a policy every client is sent every tag, whatever features
3187
    // it declares (oxygen#131).
3188
    let mut refs = a.remote_refs().unwrap();
3189
    a.refs_for_client(&mut refs, None);
3190
    assert_eq!(refs.tags.len(), 1);
3191
    // Checkout by tag.
3192
    a.checkout(&a.resolve_heads("v1").unwrap(), false, "co")
3193
        .unwrap();
3194
    assert_eq!(fs::read(root.join("a/f.txt")).unwrap(), b"1\n");
3195
    a.checkout(&a.bookmark_heads().unwrap(), false, "co")
3196
        .unwrap();
3197
3198
    // Push carries the tag; a second attestation for the name is refused.
3199
    let r = a.push("origin", false).unwrap();
3200
    origin.refresh().unwrap();
3201
    assert!(r.iter().any(|x| x.name == "tags/v1" && x.ok), "{r:?}");
3202
    assert_eq!(origin.tag_heads("v1").unwrap(), Some(vec![h1]));
3203
    let mut forged = a
3204
        .tag_refs()
3205
        .unwrap()
3206
        .into_iter()
3207
        .find(|t| t.name == "v1")
3208
        .unwrap();
3209
    forged.state = origin
3210
        .store()
3211
        .put_state(&StateObject::new(vec![h2]))
3212
        .unwrap();
3213
    forged.heads = vec![h2];
3214
    forged.attestation = None;
3215
    let r = origin
3216
        .receive_push(Bundle::default(), vec![], None, vec![forged])
3217
        .unwrap();
3218
    assert!(!r[0].ok && r[0].reason.contains("immutable"), "{r:?}");
3219
3220
    // A clone gets the tag; a later tag arrives on fetch.
3221
    let b = Repo::clone(&url, &root.join("b"))
3222
        .unwrap()
3223
        .with_home(root.join("home-b"));
3224
    assert_eq!(b.tag_heads("v1").unwrap(), Some(vec![h1]));
3225
    assert!(b.tags().unwrap()[0].signer.as_deref() == Some("Ada"));
3226
    a.tag_create("v2", &[h2], "second").unwrap();
3227
    a.push("origin", false).unwrap();
3228
    origin.refresh().unwrap();
3229
    let rep = b.fetch("origin").unwrap();
3230
    assert_eq!(rep.new_tags, 1);
3231
    assert_eq!(b.tag_heads("v2").unwrap(), Some(vec![h2]));
3232
3233
    // Under a policy, an unattested tag is refused and an attested one by the root passes.
3234
    a.policy_init().unwrap();
3235
    a.push("origin", false).unwrap();
3236
    origin.refresh().unwrap();
3237
    let unattested = crate::protocol::TagRef::new(
3238
        "v3".into(),
3239
        origin
3240
            .store()
3241
            .put_state(&StateObject::new(vec![h2]))
3242
            .unwrap(),
3243
        vec![h2],
3244
        None,
3245
    );
3246
    let r = origin
3247
        .receive_push(Bundle::default(), vec![], None, vec![unattested])
3248
        .unwrap();
3249
    assert!(!r[0].ok && r[0].reason.contains("attestation"), "{r:?}");
3250
    a.tag_create("v3", &[h2], "").unwrap();
3251
    let r = a.push("origin", false).unwrap();
3252
    origin.refresh().unwrap();
3253
    assert!(r.iter().any(|x| x.name == "tags/v3" && x.ok), "{r:?}");
3254
    assert!(a.gc(true).is_ok());
3255
    assert_eq!(a.tags().unwrap().len(), 3, "tags survive gc");
3256
3257
    // After a rotation the policy names only the new key, yet a fresh clone
3258
    // still takes the tags the old key made before it; the old key makes
3259
    // nothing new.
3260
    let rot = a.rotate_identity().unwrap();
3261
    let r = a.push("origin", false).unwrap();
3262
    origin.refresh().unwrap();
3263
    assert!(r.iter().all(|x| x.ok), "{r:?}");
3264
    let c = Repo::clone(&url, &root.join("c"))
3265
        .unwrap()
3266
        .with_home(root.join("home-c"));
3267
    assert_eq!(c.tag_heads("v3").unwrap(), Some(vec![h2]));
3268
    let (_, sp) = c.current_policy().unwrap().unwrap();
3269
    assert!(!sp.policy.authorizes(&key_a, "tags/v9"));
3270
    let made = c.identity(&rot.new).unwrap().created;
3271
    assert!(c.predecessor_authorized(&sp.policy, &key_a, "tags/v9", made - 1));
3272
    assert!(!c.predecessor_authorized(&sp.policy, &key_a, "tags/v9", made));
3273
    assert!(!c.predecessor_authorized(&sp.policy, &rot.new, "tags/v9", 0));
3274
}
3275
3276
#[test]
3277
fn multiple_workspaces_share_a_repository() {
3278
    hermetic();
3279
    let dir = tempfile::tempdir().unwrap();
3280
    let root = dir.path();
3281
    let main_dir = root.join("main");
3282
    let repo = Repo::init(&main_dir).unwrap().with_home(root.join("home"));
3283
    write(&main_dir, "a.txt", b"a\n");
3284
    let h1 = repo.commit("a", &[]).unwrap();
3285
    assert_eq!(repo.workspaces().unwrap().len(), 1);
3286
3287
    // A second workspace elsewhere, checked out on the bookmark.
3288
    let ws_dir = root.join("ws2");
3289
    let ws = repo.workspace_add(&ws_dir, None).unwrap();
3290
    assert!(ws_dir.join(".oxy").is_file());
3291
    assert_eq!(fs::read(ws_dir.join("a.txt")).unwrap(), b"a\n");
3292
    assert_ne!(ws.workspace(), repo.workspace());
3293
    let list = repo.workspaces().unwrap();
3294
    assert_eq!(list.len(), 2);
3295
    assert!(list
3296
        .iter()
3297
        .any(|w| w.id == ws.workspace() && w.path == ws_dir.canonicalize().unwrap() && !w.current));
3298
    assert!(!ws.snapshot("status").unwrap().changed);
3299
3300
    // Work in the second workspace: its own working copy, shared bookmark.
3301
    write(&ws_dir, "b.txt", b"b\n");
3302
    let s = ws.snapshot("status").unwrap();
3303
    assert_eq!(s.statuses.len(), 1);
3304
    assert!(
3305
        !repo.snapshot("status").unwrap().changed,
3306
        "the first workspace is untouched"
3307
    );
3308
    let h2 = ws.commit("b from ws2", &[]).unwrap();
3309
    repo.refresh().unwrap();
3310
    let mut heads = repo.bookmark_heads().unwrap();
3311
    heads.sort();
3312
    let mut want = vec![h1, h2];
3313
    want.sort();
3314
    assert_eq!(heads, want, "both workspaces see the bookmark move");
3315
    assert!(!main_dir.join("b.txt").exists());
3316
    repo.checkout(&repo.bookmark_heads().unwrap(), false, "co")
3317
        .unwrap();
3318
    assert!(main_dir.join("b.txt").exists());
3319
3320
    // Reopening from inside the second workspace finds the shared repository.
3321
    let reopened = Repo::open(&ws_dir).unwrap();
3322
    assert_eq!(reopened.workspace(), ws.workspace());
3323
    assert_eq!(reopened.id().unwrap(), repo.id().unwrap());
3324
    assert_eq!(reopened.quick_status().unwrap().heads, 2);
3325
3326
    // Workspaces cannot nest; forget drops one from the view but keeps files.
3327
    assert!(repo.workspace_add(&main_dir.join("inner"), None).is_err());
3328
    assert!(repo.workspace_forget(&repo.workspace()).is_err());
3329
    repo.workspace_forget(&ws.workspace()).unwrap();
3330
    assert_eq!(repo.workspaces().unwrap().len(), 1);
3331
    assert!(ws_dir.join("b.txt").exists());
3332
    assert!(
3333
        ws.snapshot("status").is_err(),
3334
        "a forgotten workspace is no longer in the view"
3335
    );
3336
3337
    // The working-copy lock: re-entrant in a thread; a lock whose process
3338
    // is gone is taken over, and a live process's is not, however old.
3339
    let lock = repo.lock_snapshot().unwrap();
3340
    let again = repo.lock_working_copy().unwrap();
3341
    drop(again);
3342
    drop(lock);
3343
    let lock_path = main_dir
3344
        .join(".oxy/workspaces")
3345
        .join(repo.workspace().to_hex())
3346
        .join("lock");
3347
    let old = std::time::SystemTime::now() - std::time::Duration::from_secs(120);
3348
    let age = |p: &Path| fs::File::open(p).unwrap().set_modified(old).unwrap();
3349
    fs::write(&lock_path, std::process::id().to_string()).unwrap();
3350
    age(&lock_path);
3351
    assert!(
3352
        !super::workspace::lock_is_stale(&lock_path),
3353
        "a live process keeps its lock"
3354
    );
3355
    fs::write(&lock_path, "4294967295").unwrap();
3356
    age(&lock_path);
3357
    assert!(repo.lock_snapshot().is_ok(), "stale lock taken over");
3358
}
3359
3360
#[test]
3361
fn attributes_binary_eol_nocompress_lockable() {
3362
    hermetic();
3363
    let dir = tempfile::tempdir().unwrap();
3364
    let root = dir.path();
3365
    let repo = Repo::init(root).unwrap().with_home(root.join("home"));
3366
    write(
3367
        root,
3368
        ".oxyattributes",
3369
        b"*.dat binary nocompress\n*.txt eol=crlf\nassets/** lockable\n",
3370
    );
3371
    write(root, "plain.dat", b"no nul bytes here\n");
3372
    write(root, "notes.txt", b"one\r\ntwo\r\n");
3373
    write(root, "assets/model.bin", b"\0model");
3374
    let h = repo.commit("attrs", &[]).unwrap();
3375
    let snap = repo.load_state(&[h]).unwrap().materialize();
3376
    assert!(
3377
        snap.files["plain.dat"].mode.opaque,
3378
        "binary attribute forces opaque without NUL bytes"
3379
    );
3380
    assert!(
3381
        matches!(&snap.files["notes.txt"].content, FileContent::Text { bytes, .. } if bytes == b"one\ntwo\n"),
3382
        "stored with LF"
3383
    );
3384
    assert!(
3385
        !repo.snapshot("status").unwrap().changed,
3386
        "CRLF on disk equals LF in the state"
3387
    );
3388
    // nocompress chunks pack raw.
3389
    let r = repo.gc(true).unwrap();
3390
    assert!(r.packed.objects > 0);
3391
    // Checkout writes CRLF for eol=crlf and makes lockable files read-only.
3392
    fs::remove_file(root.join("notes.txt")).unwrap();
3393
    repo.checkout(&[h], true, "co").unwrap();
3394
    assert_eq!(fs::read(root.join("notes.txt")).unwrap(), b"one\r\ntwo\r\n");
3395
    assert!(fs::metadata(root.join("assets/model.bin"))
3396
        .unwrap()
3397
        .permissions()
3398
        .readonly());
3399
    assert!(repo.lock_path("plain.dat").is_err(), "not lockable");
3400
    repo.lock_path("assets/model.bin").unwrap();
3401
    assert!(!fs::metadata(root.join("assets/model.bin"))
3402
        .unwrap()
3403
        .permissions()
3404
        .readonly());
3405
    assert!(repo.is_locked("assets/model.bin"));
3406
    write(root, "assets/model.bin", b"\0model2");
3407
    repo.commit("edit model", &[]).unwrap();
3408
    repo.unlock_path("assets/model.bin").unwrap();
3409
    assert!(fs::metadata(root.join("assets/model.bin"))
3410
        .unwrap()
3411
        .permissions()
3412
        .readonly());
3413
    // A later checkout can still overwrite a read-only lockable file.
3414
    repo.checkout(&[h], true, "co").unwrap();
3415
    assert_eq!(fs::read(root.join("assets/model.bin")).unwrap(), b"\0model");
3416
}
3417
3418
#[cfg(unix)]
3419
#[test]
3420
fn hooks_can_veto_observe_and_add_dependencies() {
3421
    use std::os::unix::fs::PermissionsExt;
3422
    hermetic();
3423
    let dir = tempfile::tempdir().unwrap();
3424
    let root = dir.path();
3425
    let mut repo = Repo::init(root).unwrap().with_home(root.join("home"));
3426
    let hooks = root.join(".oxy/hooks");
3427
    fs::create_dir_all(&hooks).unwrap();
3428
    let hook = |name: &str, body: &str| {
3429
        let p = hooks.join(name);
3430
        fs::write(&p, format!("#!/bin/sh\n{body}\n")).unwrap();
3431
        fs::set_permissions(&p, fs::Permissions::from_mode(0o755)).unwrap();
3432
    };
3433
    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");
3434
    hook("post-commit", "cat > \"$OXY_ROOT/.last-post-commit\"");
3435
    hook("post-checkout", "cat > \"$OXY_ROOT/.last-post-checkout\"");
3436
    hook("pre-push", "echo pushing blocked >&2; exit 3");
3437
    write(root, ".oxyignore", b".last-*\n");
3438
    write(root, "a.txt", b"a\n");
3439
    let err = repo.commit("WIP: nope", &[]).unwrap_err().to_string();
3440
    assert!(err.contains("pre-commit refused: no WIP commits"), "{err}");
3441
    let h1 = repo.commit("first", &[]).unwrap();
3442
    let pre = fs::read_to_string(root.join(".last-pre-commit")).unwrap();
3443
    assert!(
3444
        pre.contains("\"event\":\"pre-commit\"")
3445
            && pre.contains("\"path\":\"a.txt\"")
3446
            && pre.contains("\"message\":\"first\""),
3447
        "{pre}"
3448
    );
3449
    let post = fs::read_to_string(root.join(".last-post-commit")).unwrap();
3450
    assert!(post.contains(&h1.to_hex()), "{post}");
3451
    repo.checkout(&[h1], false, "co").unwrap();
3452
    assert!(fs::read_to_string(root.join(".last-post-checkout"))
3453
        .unwrap()
3454
        .contains("post-checkout"));
3455
    repo.config.set("remote.origin.url", "/nowhere").unwrap();
3456
    repo.save_config().unwrap();
3457
    let err = repo.push("origin", false).unwrap_err().to_string();
3458
    assert!(err.contains("pre-push refused: pushing blocked"), "{err}");
3459
3460
    // semantic-deps: only when enabled; adds an explicit dependency.
3461
    write(root, "b.txt", b"b\n");
3462
    hook(
3463
        "semantic-deps",
3464
        &format!(
3465
            "cat > \"$OXY_ROOT/.last-semantic\"; echo '{{\"deps\": [\"{}\"]}}'",
3466
            h1.to_hex()
3467
        ),
3468
    );
3469
    let h2 = repo.commit("b without hook", &[]).unwrap();
3470
    assert!(
3471
        repo.store().get_change(&h2).unwrap().deps.is_empty(),
3472
        "hook disabled by default"
3473
    );
3474
    repo.config.set("hooks.semantic-deps", "true").unwrap();
3475
    repo.save_config().unwrap();
3476
    write(root, "c.txt", b"c\n");
3477
    let h3 = repo.commit("c with hook", &[]).unwrap();
3478
    assert_eq!(repo.store().get_change(&h3).unwrap().deps, vec![h1]);
3479
    let sem = fs::read_to_string(root.join(".last-semantic")).unwrap();
3480
    assert!(
3481
        sem.contains("\"touched_paths\":[\"c.txt\"]") && sem.contains("candidate_deps"),
3482
        "{sem}"
3483
    );
3484
    assert_eq!(json_str("a\"b\\c\n"), "\"a\\\"b\\\\c\\n\"");
3485
}
3486
3487
#[test]
3488
fn amend_into_older_change_and_split() {
3489
    hermetic();
3490
    let dir = tempfile::tempdir().unwrap();
3491
    let root = dir.path();
3492
    let mut repo = Repo::init(root).unwrap().with_home(root.join("home"));
3493
    repo.create_identity("Ada", "a@b", IdentityScope::User)
3494
        .unwrap();
3495
    repo.set_user_config("core.sign", "change").unwrap();
3496
    write(root, "a.txt", b"one\ntwo\n");
3497
    let h0 = repo.commit("base", &[]).unwrap();
3498
    write(root, "a.txt", b"one\nTWO\n");
3499
    let h1 = repo.commit("edit two", &[]).unwrap();
3500
    write(root, "a.txt", b"one\nTWO\nthree\n");
3501
    let h2 = repo.commit("add three", &[]).unwrap();
3502
    let id1 = repo.store().get_change(&h1).unwrap().change_id;
3503
3504
    // Fixing the line h1 introduced folds into h1; h2 is rewritten on top.
3505
    write(root, "a.txt", b"one\nTWO!\nthree\n");
3506
    let h1b = repo.amend_into(&h1, None).unwrap();
3507
    assert_ne!(h1b, h1);
3508
    let c1b = repo.store().get_change(&h1b).unwrap();
3509
    assert_eq!(c1b.change_id, id1);
3510
    assert_eq!(c1b.deps, vec![h0]);
3511
    assert!(matches!(
3512
        repo.verify_change(&h1b).unwrap(),
3513
        SignatureStatus::Valid { .. }
3514
    ));
3515
    let heads = repo.bookmark_heads().unwrap();
3516
    assert_eq!(heads.len(), 1);
3517
    let top = repo.store().get_change(&heads[0]).unwrap();
3518
    assert_eq!(top.message, "add three");
3519
    assert_eq!(
3520
        top.deps.iter().copied().collect::<BTreeSet<_>>(),
3521
        [h0, h1b].into_iter().collect(),
3522
        "depends on the file's creator and the rewritten line"
3523
    );
3524
    let snap = repo.load_state(&heads).unwrap().materialize();
3525
    assert!(
3526
        matches!(&snap.files["a.txt"].content, FileContent::Text { bytes, .. } if bytes == b"one\nTWO!\nthree\n")
3527
    );
3528
    assert!(
3529
        !repo.snapshot("status").unwrap().changed,
3530
        "the working copy is clean after folding"
3531
    );
3532
    // Only h1b's own state shows the fix without "three".
3533
    let only = repo.load_state(&[h1b]).unwrap().materialize();
3534
    assert!(
3535
        matches!(&only.files["a.txt"].content, FileContent::Text { bytes, .. } if bytes == b"one\nTWO!\n")
3536
    );
3537
    assert_eq!(repo.log().unwrap().len(), 4);
3538
3539
    // An edit to a line introduced by h2 cannot fold into h1.
3540
    write(root, "a.txt", b"one\nTWO!\nthree!\n");
3541
    let err = repo.amend_into(&h1b, None).unwrap_err().to_string();
3542
    assert!(err.contains("introduced after"), "{err}");
3543
    assert!(
3544
        repo.snapshot("status").unwrap().statuses.len() == 1,
3545
        "nothing was changed by the refusal"
3546
    );
3547
    write(root, "a.txt", b"one\nTWO!\nthree\n");
3548
3549
    // Split the head that touches two files.
3550
    write(root, "b.txt", b"b\n");
3551
    write(root, "c.txt", b"c\n");
3552
    let h3 = repo.commit("b and c", &[]).unwrap();
3553
    let id3 = repo.store().get_change(&h3).unwrap().change_id;
3554
    let (p1, p2) = repo.split(&h3, &["b.txt".into()]).unwrap();
3555
    let c_1 = repo.store().get_change(&p1).unwrap();
3556
    let c_2 = repo.store().get_change(&p2).unwrap();
3557
    assert!(c_1.message.contains("part 1: b.txt"));
3558
    assert_eq!(c_2.change_id, id3);
3559
    let heads: BTreeSet<_> = repo.bookmark_heads().unwrap().into_iter().collect();
3560
    assert!(
3561
        heads.contains(&p1) && heads.contains(&p2),
3562
        "independent parts are both heads"
3563
    );
3564
    let snap = repo
3565
        .load_state(&repo.bookmark_heads().unwrap())
3566
        .unwrap()
3567
        .materialize();
3568
    assert!(snap.files.contains_key("b.txt") && snap.files.contains_key("c.txt"));
3569
    let only1 = repo.load_state(&[p1]).unwrap().materialize();
3570
    assert!(only1.files.contains_key("b.txt") && !only1.files.contains_key("c.txt"));
3571
    assert!(!repo.snapshot("status").unwrap().changed);
3572
    assert!(repo.split(&p2, &["nope.txt".into()]).is_err());
3573
    let _ = h2;
3574
}
3575
3576
#[test]
3577
fn identity_lifecycle() {
3578
    hermetic();
3579
    let dir = tempfile::tempdir().unwrap();
3580
    let root = dir.path();
3581
    let origin = Repo::init(&root.join("origin")).unwrap();
3582
    let url = root.join("origin").to_string_lossy().to_string();
3583
    let mut a = Repo::clone(&url, &root.join("a"))
3584
        .unwrap()
3585
        .with_home(root.join("home-a"));
3586
    a.set_user_config("core.sign", "change").unwrap();
3587
    let (key_a, _) = a
3588
        .create_identity("Ada", "[email protected]", IdentityScope::User)
3589
        .unwrap();
3590
    write(&root.join("a"), "a.txt", b"a\n");
3591
    let h1 = a.commit("one", &[]).unwrap();
3592
    assert!(a.policy_init().unwrap().applied);
3593
    assert!(a.push("origin", false).unwrap().iter().all(|r| r.ok));
3594
    origin.refresh().unwrap();
3595
3596
    // Expiry: an identity that had expired when the change was made does not authenticate it.
3597
    let mut e = Repo::init(&root.join("e"))
3598
        .unwrap()
3599
        .with_home(root.join("home-e"));
3600
    e.set_user_config("core.sign", "change").unwrap();
3601
    e.create_identity_with(
3602
        "Eve",
3603
        "[email protected]",
3604
        IdentityScope::User,
3605
        Some(Hlc::now().wall_ms - 1),
3606
    )
3607
    .unwrap();
3608
    write(&root.join("e"), "e.txt", b"e\n");
3609
    let he = e.commit("late", &[]).unwrap();
3610
    assert!(
3611
        matches!(e.verify_change(&he).unwrap(), SignatureStatus::Invalid(m) if m.contains("expired"))
3612
    );
3613
    // Renewal re-issues the identity (same keys, new KeyId) with a later expiry.
3614
    let r = e
3615
        .renew_identity(Some(Hlc::now().wall_ms + 86_400_000))
3616
        .unwrap();
3617
    assert_eq!(e.identity(&r.new).unwrap().previous, Some(r.old));
3618
    write(&root.join("e"), "e.txt", b"e2\n");
3619
    let he2 = e.commit("in time", &[]).unwrap();
3620
    assert!(
3621
        matches!(e.verify_change(&he2).unwrap(), SignatureStatus::Valid { key, .. } if key == r.new)
3622
    );
3623
3624
    // Rotation: a fresh key; the old change still verifies; the policy follows.
3625
    let r = a.rotate_identity().unwrap();
3626
    assert_eq!(r.old, key_a);
3627
    assert_eq!(a.config.author_key, Some(r.new));
3628
    assert_eq!(a.identity(&r.new).unwrap().previous, Some(key_a));
3629
    assert!(r.policy.as_ref().unwrap().applied);
3630
    let (_, sp) = a.current_policy().unwrap().unwrap();
3631
    assert_eq!(
3632
        (sp.policy.serial, sp.policy.roots.clone()),
3633
        (2, vec![r.new])
3634
    );
3635
    assert!(
3636
        !sp.policy.revoked.contains(&key_a) && sp.policy.authorizes(&r.new, "main"),
3637
        "superseded, not revoked"
3638
    );
3639
    assert!(sp.policy.succeeds(&r.new, &key_a) && !sp.policy.succeeds(&key_a, &r.new));
3640
    assert!(
3641
        matches!(a.verify_change(&h1).unwrap(), SignatureStatus::Valid { key, revoked: false, .. } if key == key_a)
3642
    );
3643
    write(&root.join("a"), "a.txt", b"a2\n");
3644
    let h2 = a.commit("two", &[]).unwrap();
3645
    assert!(
3646
        matches!(a.verify_change(&h2).unwrap(), SignatureStatus::Valid { key, revoked: false, .. } if key == r.new)
3647
    );
3648
    // Origin accepts the rotated policy (signed by the old root) and the new key's change.
3649
    let res = a.push("origin", false).unwrap();
3650
    origin.refresh().unwrap();
3651
    assert!(res.iter().all(|x| x.ok), "{res:?}");
3652
    assert_eq!(origin.current_policy().unwrap().unwrap().1.policy.serial, 2);
3653
    let key_a = r.new;
3654
3655
    // Delegation: Bob may sign on Ada's behalf. Delegates live in the
3656
    // identity object, so Ada's KeyId changes while her keys stay the same.
3657
    let mut b = Repo::clone(&url, &root.join("b"))
3658
        .unwrap()
3659
        .with_home(root.join("home-b"));
3660
    let (key_b, id_b) = b
3661
        .create_identity("Bob", "[email protected]", IdentityScope::User)
3662
        .unwrap();
3663
    let r = a.delegate_add(id_b.clone(), Scope::ALL, None).unwrap();
3664
    assert_eq!(r.old, key_a);
3665
    let key_a2 = r.new;
3666
    assert_eq!(
3667
        a.identity(&key_a2).unwrap().delegates,
3668
        vec![Delegate::full(key_b)]
3669
    );
3670
    assert_eq!(
3671
        a.identity(&key_a2).unwrap().ed25519_pk,
3672
        a.identity(&key_a).unwrap().ed25519_pk
3673
    );
3674
    assert!(
3675
        a.delegate_add(id_b.clone(), Scope::ALL, None).is_err(),
3676
        "already a delegate"
3677
    );
3678
    assert!(a.push("origin", false).unwrap().iter().all(|x| x.ok));
3679
    origin.refresh().unwrap();
3680
    write(&root.join("a"), "a.txt", b"a3\n");
3681
    let h3 = a.commit("three", &[]).unwrap();
3682
    assert!(
3683
        matches!(a.verify_change(&h3).unwrap(), SignatureStatus::Valid { key, .. } if key == key_a2),
3684
        "the same secret signs under the new KeyId"
3685
    );
3686
    // A change authored by Ada but signed only by Bob verifies through the delegation.
3687
    a.set_user_config("core.sign", "seal").unwrap();
3688
    write(&root.join("a"), "a.txt", b"a4\n");
3689
    let h4 = a.commit("four", &[]).unwrap();
3690
    assert_eq!(a.verify_change(&h4).unwrap(), SignatureStatus::Unsigned);
3691
    let (_, sk_b) = b.secret_key().unwrap().unwrap();
3692
    a.store()
3693
        .put_signature(&h4, &sk_b.sign(Domain::Change, &key_b, &h4))
3694
        .unwrap();
3695
    assert!(
3696
        matches!(a.verify_change(&h4).unwrap(), SignatureStatus::Valid { key, .. } if key == key_b)
3697
    );
3698
    a.set_user_config("core.sign", "change").unwrap();
3699
    // Withdrawing the delegation re-issues the identity again.
3700
    let r = a.delegate_remove(&key_b).unwrap();
3701
    assert!(a.identity(&r.new).unwrap().delegates.is_empty());
3702
    assert!(a.delegate_remove(&key_b).is_err());
3703
    let key_a3 = r.new;
3704
    let res = a.push("origin", false).unwrap();
3705
    origin.refresh().unwrap();
3706
    assert!(res.iter().all(|x| x.ok), "{res:?}");
3707
3708
    // Multi-signer policy: Bob becomes a root and the threshold rises to 2,
3709
    // both applied under the old threshold of 1. A grant then needs Bob too.
3710
    assert!(a.policy_root_add(id_b.clone()).unwrap().applied);
3711
    assert!(a.policy_root_add(id_b.clone()).is_err());
3712
    assert!(a.policy_set_threshold(3).is_err());
3713
    assert!(a.policy_set_threshold(2).unwrap().applied);
3714
    assert!(a.push("origin", false).unwrap().iter().all(|x| x.ok));
3715
    origin.refresh().unwrap();
3716
    b.pull("origin").unwrap();
3717
    assert_eq!(
3718
        b.current_policy().unwrap().unwrap().1.policy.root_threshold,
3719
        2
3720
    );
3721
    let mut c = Repo::init(&root.join("c"))
3722
        .unwrap()
3723
        .with_home(root.join("home-c"));
3724
    let (key_c, id_c) = c
3725
        .create_identity("Cy", "[email protected]", IdentityScope::User)
3726
        .unwrap();
3727
    let serial_before = a.current_policy().unwrap().unwrap().1.policy.serial;
3728
    let proposal = a.policy_grant(id_c, None).unwrap();
3729
    assert!(!proposal.applied && proposal.sigs.len() == 1);
3730
    assert_eq!(proposal.policy.serial, serial_before + 1);
3731
    assert_eq!(
3732
        a.current_policy().unwrap().unwrap().1.policy.serial,
3733
        serial_before,
3734
        "a proposal changes nothing yet"
3735
    );
3736
    // Bob signs the proposal, handed over as a file, and it applies for him.
3737
    let bytes = proposal.signed().encode();
3738
    let signed = b
3739
        .policy_sign(SignedPolicy::decode(&bytes).unwrap())
3740
        .unwrap();
3741
    assert!(signed.applied && signed.sigs.len() == 2);
3742
    assert!(b
3743
        .current_policy()
3744
        .unwrap()
3745
        .unwrap()
3746
        .1
3747
        .policy
3748
        .authorizes(&key_c, "main"));
3749
    assert!(
3750
        b.policy_sign(signed.signed()).is_err(),
3751
        "a stale proposal is refused"
3752
    );
3753
    // Bob publishes it and Ada picks it up.
3754
    assert!(b
3755
        .push("origin", false)
3756
        .unwrap()
3757
        .iter()
3758
        .any(|x| x.name == "policy" && x.ok));
3759
    origin.refresh().unwrap();
3760
    a.pull("origin").unwrap();
3761
    assert_eq!(
3762
        a.current_policy().unwrap().unwrap().1.policy.serial,
3763
        serial_before + 1
3764
    );
3765
    // A root cannot revoke itself; revoking Cy needs both roots but is recorded locally at once.
3766
    assert!(a.policy_revoke(&key_a3).is_err());
3767
    let u = a
3768
        .revoke_identity(&key_c, "left the project")
3769
        .unwrap()
3770
        .unwrap();
3771
    assert!(!u.applied);
3772
    assert!(a.is_revoked(&key_c).unwrap());
3773
    assert!(!b.is_revoked(&key_c).unwrap());
3774
    let u = b.policy_sign(u.signed()).unwrap();
3775
    assert!(u.applied && u.policy.is_revoked(&key_c));
3776
    assert!(b.is_revoked(&key_c).unwrap());
3777
    // Bob can revoke Ada's root key, leaving himself as the only root (threshold 2 would be unmeetable).
3778
    assert!(
3779
        b.policy_revoke(&key_a3).is_err(),
3780
        "would leave one root for a threshold of 2"
3781
    );
3782
    // Revoking one's own key without a policy root works locally: a plain marker plus attestation.
3783
    let key_c_own = c.config.author_key.unwrap();
3784
    assert!(c
3785
        .revoke_identity(&key_c_own, "lost laptop")
3786
        .unwrap()
3787
        .is_none());
3788
    assert!(c.is_revoked(&key_c_own).unwrap());
3789
    assert_eq!(key_c_own, key_c);
3790
}
3791
3792
#[test]
3793
fn renames_are_detected_and_tracked_as_moves() {
3794
    hermetic();
3795
    let dir = tempfile::tempdir().unwrap();
3796
    let root = dir.path();
3797
    let repo = Repo::init(root).unwrap().with_home(root.join("home"));
3798
    write(
3799
        root,
3800
        "src/old.rs",
3801
        b"fn a() {}\nfn b() {}\nfn c() {}\nfn d() {}\n",
3802
    );
3803
    write(root, "img.bin", b"\x89PNG\0\0\x01\x02");
3804
    write(root, "tiny.txt", b"x\n");
3805
    let h1 = repo.commit("base", &[]).unwrap();
3806
    let node_old = repo.load_state(&[h1]).unwrap().materialize().files["src/old.rs"].node;
3807
    let node_img = repo.load_state(&[h1]).unwrap().materialize().files["img.bin"].node;
3808
3809
    // Rename with a small edit, a binary moved unchanged, and a rewrite
3810
    // that shares nothing with the removed file.
3811
    fs::remove_file(root.join("src/old.rs")).unwrap();
3812
    write(
3813
        root,
3814
        "lib/new.rs",
3815
        b"fn a() {}\nfn b() {}\nfn c() {}\nfn e() {}\n",
3816
    );
3817
    fs::remove_file(root.join("img.bin")).unwrap();
3818
    write(root, "assets/img.bin", b"\x89PNG\0\0\x01\x02");
3819
    fs::remove_file(root.join("tiny.txt")).unwrap();
3820
    write(root, "other.txt", b"completely different\n");
3821
    let snap = repo.snapshot("status").unwrap();
3822
    let statuses: Vec<(&str, ChangeStatus)> = snap
3823
        .statuses
3824
        .iter()
3825
        .map(|s| (s.path.as_str(), s.status))
3826
        .collect();
3827
    assert_eq!(
3828
        statuses,
3829
        vec![
3830
            ("assets/img.bin", ChangeStatus::Renamed),
3831
            ("lib/new.rs", ChangeStatus::Renamed),
3832
            ("other.txt", ChangeStatus::Added),
3833
            ("src", ChangeStatus::Removed),
3834
            ("tiny.txt", ChangeStatus::Removed)
3835
        ]
3836
    );
3837
    let h2 = repo.commit("move things", &[]).unwrap();
3838
    let c = repo.store().get_change(&h2).unwrap();
3839
    let moves: Vec<_> = c
3840
        .tree_ops
3841
        .iter()
3842
        .filter(|op| matches!(op, TreeOp::Move { .. }))
3843
        .collect();
3844
    assert_eq!(moves.len(), 2, "{:?}", c.tree_ops);
3845
    assert!(c.tree_ops.iter().any(
3846
        |op| matches!(op, TreeOp::Move { node, name, .. } if *node == node_old && name == "new.rs")
3847
    ));
3848
    assert!(c.tree_ops.iter().any(
3849
        |op| matches!(op, TreeOp::Move { node, name, .. } if *node == node_img && name == "img.bin")
3850
    ));
3851
    let snap = repo.load_state(&[h2]).unwrap().materialize();
3852
    assert_eq!(
3853
        snap.files["lib/new.rs"].node, node_old,
3854
        "the node survives the rename"
3855
    );
3856
    assert!(
3857
        matches!(&snap.files["lib/new.rs"].content, FileContent::Text { bytes, .. } if bytes == b"fn a() {}\nfn b() {}\nfn c() {}\nfn e() {}\n")
3858
    );
3859
    assert!(!snap.files.contains_key("src/old.rs") && !snap.files.contains_key("src"));
3860
    assert!(render_change(
3861
        &c,
3862
        &repo.load_state(&[h1]).unwrap(),
3863
        &repo.load_state(&[h1]).unwrap().materialize()
3864
    )
3865
    .contains("R "));
3866
    // A fresh checkout reproduces the tree.
3867
    let other = tempfile::tempdir().unwrap();
3868
    let clone = Repo::clone(&root.to_string_lossy(), other.path()).unwrap();
3869
    assert_eq!(
3870
        fs::read(other.path().join("lib/new.rs")).unwrap(),
3871
        b"fn a() {}\nfn b() {}\nfn c() {}\nfn e() {}\n"
3872
    );
3873
    assert!(!other.path().join("src").exists());
3874
    assert!(!clone.snapshot("status").unwrap().changed);
3875
    // Similarity is line based, byte weighted.
3876
    assert_eq!(similarity(b"a\nb\n", b"a\nb\n"), 100);
3877
    assert_eq!(similarity(b"a\nb\nc\nd\n", b"a\nb\nx\ny\n"), 50);
3878
    assert_eq!(similarity(b"hello\n", b"world\n"), 0);
3879
    assert_eq!(similarity(b"", b"x\n"), 0);
3880
}
3881
3882
#[test]
3883
fn git_fetch_and_push_round_trip() {
3884
    hermetic();
3885
    if std::process::Command::new("git")
3886
        .arg("--version")
3887
        .output()
3888
        .is_err()
3889
    {
3890
        eprintln!("git not installed; skipping");
3891
        return;
3892
    }
3893
    let dir = tempfile::tempdir().unwrap();
3894
    let root = dir.path();
3895
    let git_in = |d: &Path, args: &[&str]| -> String {
3896
        let out = std::process::Command::new("git")
3897
            .arg("-C")
3898
            .arg(d)
3899
            .args([
3900
                "-c",
3901
                "user.name=Grace",
3902
                "-c",
3903
                "[email protected]",
3904
                "-c",
3905
                "commit.gpgsign=false",
3906
            ])
3907
            .args(args)
3908
            .output()
3909
            .unwrap();
3910
        assert!(
3911
            out.status.success(),
3912
            "git {args:?}: {}",
3913
            String::from_utf8_lossy(&out.stderr)
3914
        );
3915
        String::from_utf8_lossy(&out.stdout).trim().to_string()
3916
    };
3917
    // A bare "remote" and a work tree that pushes to it.
3918
    let remote = root.join("remote.git");
3919
    fs::create_dir_all(&remote).unwrap();
3920
    git_in(&remote, &["init", "-q", "--bare", "-b", "main"]);
3921
    let work = root.join("work");
3922
    git_in(
3923
        root,
3924
        &[
3925
            "clone",
3926
            "-q",
3927
            remote.to_str().unwrap(),
3928
            work.to_str().unwrap(),
3929
        ],
3930
    );
3931
    git_in(&work, &["checkout", "-q", "-b", "main"]);
3932
    write(&work, "README.md", b"# Project\n");
3933
    write(&work, "src/lib.rs", b"pub fn a() {}\n");
3934
    git_in(&work, &["add", "."]);
3935
    git_in(&work, &["commit", "-q", "-m", "initial"]);
3936
    write(&work, "src/lib.rs", b"pub fn a() {}\npub fn b() {}\n");
3937
    git_in(&work, &["commit", "-q", "-am", "second"]);
3938
    git_in(&work, &["push", "-q", "origin", "main"]);
3939
    let tip1 = git_in(&work, &["rev-parse", "HEAD"]);
3940
3941
    // Fetch into a fresh oxy repository.
3942
    let o = root.join("oxy");
3943
    let mut repo = Repo::init(&o).unwrap().with_home(root.join("home"));
3944
    repo.create_identity("Ada", "[email protected]", IdentityScope::User)
3945
        .unwrap();
3946
    let url = remote.to_string_lossy().to_string();
3947
    let r = repo.git_fetch(&url, "main").unwrap();
3948
    assert_eq!((r.commits, r.heads), (2, 1));
3949
    assert_eq!(
3950
        fs::read(o.join("src/lib.rs")).unwrap(),
3951
        b"pub fn a() {}\npub fn b() {}\n"
3952
    );
3953
    assert!(!repo.snapshot("status").unwrap().changed);
3954
    assert_eq!(
3955
        repo.git_fetch(&url, "main").unwrap().commits,
3956
        0,
3957
        "nothing new"
3958
    );
3959
3960
    // An oxy change, pushed back: one commit on top of the Git tip.
3961
    write(
3962
        &o,
3963
        "src/lib.rs",
3964
        b"pub fn a() {}\npub fn b() {}\npub fn c() {}\n",
3965
    );
3966
    write(&o, "NOTES.md", b"from oxy\n");
3967
    let h_oxy = repo.commit("add c and notes", &[]).unwrap();
3968
    let r = repo.git_push(&url, "main").unwrap();
3969
    assert_eq!(r.exported, 1, "{r:?}");
3970
    git_in(&work, &["pull", "-q", "--ff-only", "origin", "main"]);
3971
    assert_eq!(
3972
        git_in(&work, &["log", "--format=%s", "main"]),
3973
        "add c and notes\nsecond\ninitial"
3974
    );
3975
    assert_eq!(git_in(&work, &["rev-parse", "HEAD~1"]), tip1);
3976
    assert_eq!(fs::read(work.join("NOTES.md")).unwrap(), b"from oxy\n");
3977
    assert_eq!(git_in(&work, &["log", "-1", "--format=%an", "main"]), "Ada");
3978
    assert!(git_in(&work, &["log", "-1", "--format=%B", "main"])
3979
        .contains(&format!("Oxy-Hash: {}", h_oxy.to_hex())));
3980
    assert_eq!(
3981
        repo.git_push(&url, "main").unwrap().exported,
3982
        0,
3983
        "already pushed"
3984
    );
3985
3986
    // Git moves on; pushing without fetching is refused, fetching brings
3987
    // the commit in and the working copy follows.
3988
    write(&work, "README.md", b"# Project\n\nMore.\n");
3989
    git_in(&work, &["commit", "-q", "-am", "readme from git"]);
3990
    git_in(&work, &["push", "-q", "origin", "main"]);
3991
    let tip2 = git_in(&work, &["rev-parse", "HEAD"]);
3992
    assert!(repo
3993
        .git_push(&url, "main")
3994
        .unwrap_err()
3995
        .to_string()
3996
        .contains("fetch"));
3997
    let r = repo.git_fetch(&url, "main").unwrap();
3998
    assert_eq!(
3999
        (r.commits, r.heads),
4000
        (1, 2),
4001
        "the Git change and the oxy change commute"
4002
    );
4003
    assert_eq!(
4004
        fs::read(o.join("README.md")).unwrap(),
4005
        b"# Project\n\nMore.\n"
4006
    );
4007
    assert_eq!(fs::read(o.join("NOTES.md")).unwrap(), b"from oxy\n");
4008
    assert!(!repo.snapshot("status").unwrap().changed);
4009
    // Another oxy change pushes on top of Git's newest commit.
4010
    write(&o, "NOTES.md", b"from oxy\nagain\n");
4011
    repo.commit("notes again", &[]).unwrap();
4012
    assert_eq!(repo.git_push(&url, "main").unwrap().exported, 1);
4013
    git_in(&work, &["pull", "-q", "--ff-only", "origin", "main"]);
4014
    assert_eq!(git_in(&work, &["rev-parse", "HEAD~1"]), tip2);
4015
    assert_eq!(
4016
        fs::read(work.join("NOTES.md")).unwrap(),
4017
        b"from oxy\nagain\n"
4018
    );
4019
    assert_eq!(
4020
        git_in(&work, &["log", "--format=%s", "main"])
4021
            .lines()
4022
            .count(),
4023
        5
4024
    );
4025
}
4026
4027
/// Benchmark, not a gate: `cargo test --release -p oxy-core --lib bench_one_gibibyte -- --ignored --nocapture`.
4028
/// Commits, stores, clones, and reads back a 1 GiB incompressible file.
4029
#[test]
4030
#[ignore]
4031
fn bench_one_gibibyte_file() {
4032
    hermetic();
4033
    // /tmp is often a small tmpfs; `OXY_BENCH_DIR` picks a roomier disk.
4034
    let dir = match std::env::var_os("OXY_BENCH_DIR") {
4035
        Some(d) => tempfile::tempdir_in(d).unwrap(),
4036
        None => tempfile::tempdir().unwrap(),
4037
    };
4038
    let root = dir.path();
4039
    let repo = Repo::init(&root.join("r"))
4040
        .unwrap()
4041
        .with_home(root.join("home"));
4042
    let size = 1usize << 30;
4043
    let mut data = vec![0u8; size];
4044
    let mut x = 0x9e3779b97f4a7c15u64;
4045
    for chunk in data.chunks_mut(8) {
4046
        x ^= x << 13;
4047
        x ^= x >> 7;
4048
        x ^= x << 17;
4049
        let b = x.to_le_bytes();
4050
        chunk.copy_from_slice(&b[..chunk.len()]);
4051
    }
4052
    let t = std::time::Instant::now();
4053
    write(&root.join("r"), "big.bin", &data);
4054
    eprintln!("write 1 GiB to disk: {:.2?}", t.elapsed());
4055
    let t = std::time::Instant::now();
4056
    let h = repo.commit("big", &[]).unwrap();
4057
    eprintln!("commit (chunk + hash + store): {:.2?}", t.elapsed());
4058
    let t = std::time::Instant::now();
4059
    assert!(!repo.snapshot("status").unwrap().changed);
4060
    eprintln!("status on a clean 1 GiB working copy: {:.2?}", t.elapsed());
4061
    let t = std::time::Instant::now();
4062
    let objects = repo.store().list().unwrap().len();
4063
    eprintln!("objects stored: {objects} ({:.2?} to list)", t.elapsed());
4064
    let t = std::time::Instant::now();
4065
    let g = repo.gc(true).unwrap();
4066
    eprintln!("gc (pack): {:.2?} {g:?}", t.elapsed());
4067
    let t = std::time::Instant::now();
4068
    let clone = Repo::clone(&root.join("r").to_string_lossy(), &root.join("c")).unwrap();
4069
    eprintln!("clone (fetch + checkout): {:.2?}", t.elapsed());
4070
    let t = std::time::Instant::now();
4071
    let back = fs::read(root.join("c/big.bin")).unwrap();
4072
    assert_eq!(blake3::hash(&back), blake3::hash(&data));
4073
    eprintln!("read back and verify: {:.2?}", t.elapsed());
4074
    assert_eq!(clone.bookmark_heads().unwrap(), vec![h]);
4075
    let store_bytes: u64 = walkdir_size(&root.join("r/.oxy/objects"));
4076
    eprintln!(
4077
        "store size: {:.1} MiB for 1 GiB of data",
4078
        store_bytes as f64 / (1024.0 * 1024.0)
4079
    );
4080
}
4081
4082
fn walkdir_size(p: &Path) -> u64 {
4083
    let mut total = 0;
4084
    if let Ok(rd) = fs::read_dir(p) {
4085
        for e in rd.flatten() {
4086
            let path = e.path();
4087
            if path.is_dir() {
4088
                total += walkdir_size(&path);
4089
            } else if let Ok(m) = fs::metadata(&path) {
4090
                total += m.len();
4091
            }
4092
        }
4093
    }
4094
    total
4095
}
4096
4097
/// An opaque file whose size and mtime match the manifest is not read on
4098
/// the next snapshot: its blob comes from the manifest's stat cache.
4099
#[cfg(unix)]
4100
#[test]
4101
fn stat_cache_skips_reading_unchanged_opaque_files() {
4102
    use std::os::unix::fs::PermissionsExt;
4103
    hermetic();
4104
    let dir = tempfile::tempdir().unwrap();
4105
    let root = dir.path();
4106
    let repo = Repo::init(root).unwrap().with_home(root.join("home"));
4107
    let mut big = vec![0u8; 300 * 1024];
4108
    for (i, b) in big.iter_mut().enumerate() {
4109
        *b = (i as u32).wrapping_mul(2654435761).to_le_bytes()[1];
4110
    }
4111
    big[0] = 0;
4112
    write(root, "big.bin", &big);
4113
    write(root, "a.txt", b"text\n");
4114
    let h1 = repo.commit("base", &[]).unwrap();
4115
    let (_, _, m) = repo.read_manifest().unwrap().unwrap();
4116
    assert!(
4117
        m.entries["big.bin"].blob.is_some(),
4118
        "opaque files record their blob"
4119
    );
4120
    assert!(m.entries["a.txt"].blob.is_none());
4121
    let blob = m.entries["big.bin"].blob.unwrap();
4122
    assert!(repo.store().has(&blob));
4123
4124
    // Files modified within two seconds of the manifest are racy and still
4125
    // read; age the file so the cache applies, then snapshot to record it.
4126
    let old = std::time::SystemTime::now() - std::time::Duration::from_secs(30);
4127
    fs::File::options()
4128
        .write(true)
4129
        .open(root.join("big.bin"))
4130
        .unwrap()
4131
        .set_modified(old)
4132
        .unwrap();
4133
    assert!(!repo.snapshot("status").unwrap().changed);
4134
    // Now the file cannot be read at all; the snapshot succeeds without it.
4135
    fs::set_permissions(root.join("big.bin"), fs::Permissions::from_mode(0o000)).unwrap();
4136
    let snap = repo.snapshot("status").unwrap();
4137
    assert!(
4138
        !snap.changed && snap.statuses.is_empty(),
4139
        "{:?}",
4140
        snap.statuses
4141
    );
4142
    fs::set_permissions(root.join("big.bin"), fs::Permissions::from_mode(0o644)).unwrap();
4143
    // A real change (new mtime, new content) is seen and committed correctly.
4144
    let mut big2 = big.clone();
4145
    big2[10] ^= 0xff;
4146
    write(root, "big.bin", &big2);
4147
    let snap = repo.snapshot("status").unwrap();
4148
    assert_eq!(
4149
        snap.statuses
4150
            .iter()
4151
            .map(|s| (s.path.as_str(), s.status))
4152
            .collect::<Vec<_>>(),
4153
        vec![("big.bin", ChangeStatus::Modified)]
4154
    );
4155
    let h2 = repo.commit("edit", &[]).unwrap();
4156
    let files = repo.load_state(&[h2]).unwrap().materialize().files;
4157
    assert_eq!(
4158
        files["big.bin"].content,
4159
        FileContent::Opaque {
4160
            blobs: vec![Repo::blob_ref(&big2)]
4161
        }
4162
    );
4163
    // Checkout writes a manifest with blobs too, so the next status is cached.
4164
    repo.checkout(&[h1], false, "checkout").unwrap();
4165
    let (_, _, m) = repo.read_manifest().unwrap().unwrap();
4166
    assert_eq!(m.entries["big.bin"].blob, Some(Repo::blob_ref(&big)));
4167
    assert!(!repo.snapshot("status").unwrap().changed);
4168
}
4169
4170
#[test]
4171
fn status_json_lists_conflicts_with_contributors() {
4172
    hermetic();
4173
    let dir = tempfile::tempdir().unwrap();
4174
    let root = dir.path();
4175
    let repo = Repo::init(root).unwrap().with_home(root.join("home"));
4176
    write(root, "a.txt", b"one\n");
4177
    let h1 = repo.commit("base", &[]).unwrap();
4178
    write(root, "a.txt", b"one\nleft\n");
4179
    let ha = repo.commit("left", &[]).unwrap();
4180
    repo.checkout(&[h1], true, "checkout").unwrap();
4181
    write(root, "a.txt", b"one\nright\n");
4182
    let hb = repo.commit("right", &[]).unwrap();
4183
    repo.checkout(&[ha, hb], true, "checkout").unwrap();
4184
    let snap = repo.snapshot("status").unwrap();
4185
    assert!(snap.base_snapshot.is_conflicted());
4186
    let json = repo.status_json(&snap).unwrap();
4187
    let ida = repo.store().get_change(&ha).unwrap().change_id.to_hex();
4188
    let idb = repo.store().get_change(&hb).unwrap().change_id.to_hex();
4189
    assert!(json.contains("\"conflicted\":true"), "{json}");
4190
    assert!(
4191
        json.contains("\"kind\":\"text\",\"path\":\"a.txt\""),
4192
        "{json}"
4193
    );
4194
    assert!(json.contains(&ida) && json.contains(&idb), "{json}");
4195
    assert!(json.contains("\"resolved\":false"), "{json}");
4196
    assert!(json.starts_with('{') && json.ends_with('}'));
4197
    // Resolve and the report says so; a clean copy has no conflicts.
4198
    write(root, "a.txt", b"one\nleft\nright\n");
4199
    let snap = repo.snapshot("status").unwrap();
4200
    let json = repo.status_json(&snap).unwrap();
4201
    assert!(json.contains("\"resolved\":true"), "{json}");
4202
    repo.commit("resolve", &[]).unwrap();
4203
    let snap = repo.snapshot("status").unwrap();
4204
    let json = repo.status_json(&snap).unwrap();
4205
    assert!(
4206
        json.contains("\"clean\":true,\"conflicted\":false,\"paths\":[],\"conflicts\":[]"),
4207
        "{json}"
4208
    );
4209
}
4210
4211
#[test]
4212
fn ignore_rules_do_not_untrack_files() {
4213
    hermetic();
4214
    let dir = tempfile::tempdir().unwrap();
4215
    let root = dir.path();
4216
    let repo = Repo::init(root).unwrap().with_home(root.join("home"));
4217
    write(root, "src.c", b"int x;\n");
4218
    write(root, "build/out.o", b"\0obj");
4219
    write(root, "sub/keep.log", b"keep\n");
4220
    write(root, "sub/junk.log", b"junk\n");
4221
    write(root, ".oxyignore", b"/build\n*.log\n!sub/keep.log\n");
4222
    let snap = repo.snapshot("status").unwrap();
4223
    let added: Vec<&str> = snap.statuses.iter().map(|s| s.path.as_str()).collect();
4224
    assert_eq!(
4225
        added,
4226
        vec![".oxyignore", "src.c", "sub/keep.log"],
4227
        "anchored, glob, and negated rules"
4228
    );
4229
    let h1 = repo.commit("base", &[]).unwrap();
4230
    // Ignoring a tracked file changes nothing about it.
4231
    write(root, ".oxyignore", b"/build\n*.log\n!sub/keep.log\nsrc.c\n");
4232
    let snap = repo.snapshot("status").unwrap();
4233
    assert_eq!(
4234
        snap.statuses
4235
            .iter()
4236
            .map(|s| s.path.as_str())
4237
            .collect::<Vec<_>>(),
4238
        vec![".oxyignore"]
4239
    );
4240
    let h2 = repo.commit("ignore src.c", &[]).unwrap();
4241
    assert!(repo
4242
        .load_state(&[h2])
4243
        .unwrap()
4244
        .materialize()
4245
        .files
4246
        .contains_key("src.c"));
4247
    // Its edits are still seen, by status and by the prompt.
4248
    assert_eq!(repo.quick_dirty().unwrap(), Some(false));
4249
    write(root, "src.c", b"int x, y;\n");
4250
    assert_eq!(repo.quick_dirty().unwrap(), Some(true));
4251
    let snap = repo.snapshot("status").unwrap();
4252
    assert_eq!(
4253
        snap.statuses
4254
            .iter()
4255
            .map(|s| (s.path.as_str(), s.status))
4256
            .collect::<Vec<_>>(),
4257
        vec![("src.c", ChangeStatus::Modified)]
4258
    );
4259
    let h3 = repo.commit("edit src.c", &[]).unwrap();
4260
    assert!(
4261
        matches!(&repo.load_state(&[h3]).unwrap().materialize().files["src.c"].content, FileContent::Text { bytes, .. } if bytes == b"int x, y;\n")
4262
    );
4263
    // Deleting it on disk removes it, ignored or not; a checkout brings it back.
4264
    fs::remove_file(root.join("src.c")).unwrap();
4265
    let snap = repo.snapshot("status").unwrap();
4266
    assert_eq!(
4267
        snap.statuses
4268
            .iter()
4269
            .map(|s| (s.path.as_str(), s.status))
4270
            .collect::<Vec<_>>(),
4271
        vec![("src.c", ChangeStatus::Removed)]
4272
    );
4273
    repo.checkout(&[h3], true, "checkout").unwrap();
4274
    assert_eq!(fs::read(root.join("src.c")).unwrap(), b"int x, y;\n");
4275
    assert!(!repo.snapshot("status").unwrap().changed);
4276
    let _ = h1;
4277
}
4278
4279
#[test]
4280
fn split_works_on_non_heads_by_node() {
4281
    hermetic();
4282
    let dir = tempfile::tempdir().unwrap();
4283
    let root = dir.path();
4284
    let repo = Repo::init(root).unwrap().with_home(root.join("home"));
4285
    write(root, "a.txt", b"one\n");
4286
    write(root, "junk/x.lock", b"lock\n");
4287
    let h1 = repo.commit("work plus junk", &[]).unwrap();
4288
    write(root, "a.txt", b"one\ntwo\n");
4289
    let h2 = repo.commit("more work", &[]).unwrap();
4290
    assert_eq!(repo.store().get_change(&h2).unwrap().deps, vec![h1]);
4291
    let id1 = repo.store().get_change(&h1).unwrap().change_id;
4292
    // h1 is not a head: split it by node.
4293
    let (hj, h1b) = repo.split(&h1, &["junk".into()]).unwrap();
4294
    assert_ne!(h1b, h1);
4295
    assert_eq!(
4296
        repo.store().get_change(&h1b).unwrap().change_id,
4297
        id1,
4298
        "the rest keeps the ChangeId"
4299
    );
4300
    let junk = repo.store().get_change(&hj).unwrap();
4301
    assert!(junk.tree_ops.iter().all(
4302
        |op| matches!(op, TreeOp::AddNode { name, .. } if name == "junk" || name == "x.lock")
4303
    ));
4304
    let heads = repo.bookmark_heads().unwrap();
4305
    assert!(
4306
        heads.contains(&hj),
4307
        "the split-off part is a head of its own"
4308
    );
4309
    let snap = repo.load_state(&heads).unwrap().materialize();
4310
    assert!(
4311
        matches!(&snap.files["a.txt"].content, FileContent::Text { bytes, .. } if bytes == b"one\ntwo\n"),
4312
        "the dependent was rewritten onto the new hash"
4313
    );
4314
    assert!(snap.files.contains_key("junk/x.lock"));
4315
    let h2b = heads
4316
        .iter()
4317
        .find(|h| repo.store().get_change(h).unwrap().message == "more work")
4318
        .copied()
4319
        .unwrap();
4320
    assert_eq!(repo.store().get_change(&h2b).unwrap().deps, vec![h1b]);
4321
    assert!(!repo.snapshot("status").unwrap().changed);
4322
    // Abandoning the split-off head removes the junk from history.
4323
    repo.abandon(&hj).unwrap();
4324
    let heads = repo.bookmark_heads().unwrap();
4325
    let snap = repo.load_state(&heads).unwrap().materialize();
4326
    assert!(!snap.files.contains_key("junk/x.lock") && !snap.files.contains_key("junk"));
4327
    assert!(snap.files.contains_key("a.txt"));
4328
    // A dependent that touches the split-off paths blocks the split.
4329
    write(root, "junk/y.lock", b"y\n");
4330
    let hb = repo.commit("junk base", &[]).unwrap();
4331
    write(root, "junk/y.lock", b"yy\n");
4332
    write(root, "b.txt", b"b\n");
4333
    repo.commit("touches junk", &[]).unwrap();
4334
    let err = repo.split(&hb, &["junk".into()]).unwrap_err().to_string();
4335
    assert!(err.contains("depends on the split-off paths"), "{err}");
4336
}
4337
4338
#[test]
4339
fn bookmarks_switch_merge_and_push() {
4340
    hermetic();
4341
    let dir = tempfile::tempdir().unwrap();
4342
    let root = dir.path();
4343
    let origin = Repo::init(&root.join("origin")).unwrap();
4344
    let url = root.join("origin").to_string_lossy().to_string();
4345
    let mut repo = Repo::clone(&url, &root.join("r"))
4346
        .unwrap()
4347
        .with_home(root.join("home"));
4348
    let r = root.join("r");
4349
    write(&r, "a.txt", b"a\n");
4350
    let h_a = repo.commit("a", &[]).unwrap();
4351
    assert!(repo.push("origin", false).unwrap()[0].ok);
4352
    origin.refresh().unwrap();
4353
4354
    // A bookmark at the working copy's base, then work on it.
4355
    assert!(repo.bookmark_create("bad name..", None).is_err());
4356
    assert!(repo.bookmark_create("-x", None).is_err());
4357
    assert_eq!(repo.bookmark_create("feature", None).unwrap(), vec![h_a]);
4358
    assert!(repo.bookmark_create("feature", None).is_err(), "exists");
4359
    repo.bookmark_switch("feature", false).unwrap();
4360
    assert_eq!(repo.config.bookmark, "feature");
4361
    write(&r, "a.txt", b"a\nb\n");
4362
    write(&r, "b.txt", b"b\n");
4363
    let h_b = repo.commit("b on feature", &[]).unwrap();
4364
    assert_eq!(
4365
        repo.bookmark_heads().unwrap(),
4366
        vec![h_b],
4367
        "b edits a.txt, so it depends on a"
4368
    );
4369
    assert_eq!(
4370
        repo.resolve_heads("main").unwrap(),
4371
        vec![h_a],
4372
        "main is untouched"
4373
    );
4374
    assert_eq!(
4375
        repo.resolve_change("feature").unwrap(),
4376
        h_b,
4377
        "a one-head bookmark names its change"
4378
    );
4379
    // Reopening keeps the workspace's bookmark.
4380
    let reopened = Repo::open(&r).unwrap().with_home(root.join("home"));
4381
    assert_eq!(reopened.config.bookmark, "feature");
4382
    // Back to main: b.txt goes away; work there.
4383
    repo.bookmark_switch("main", false).unwrap();
4384
    assert!(!r.join("b.txt").exists());
4385
    assert_eq!(fs::read(r.join("a.txt")).unwrap(), b"a\n");
4386
    write(&r, "c.txt", b"c\n");
4387
    let h_c = repo.commit("c on main", &[]).unwrap();
4388
    let list = repo.bookmarks().unwrap();
4389
    assert_eq!(
4390
        list.iter()
4391
            .map(|b| (b.name.as_str(), b.current))
4392
            .collect::<Vec<_>>(),
4393
        vec![("feature", false), ("main", true)]
4394
    );
4395
    assert_eq!(
4396
        list.iter().find(|b| b.name == "main").unwrap().ahead,
4397
        Some(1),
4398
        "c is not on origin yet"
4399
    );
4400
    // Merge feature into main: the union, both heads, no merge change.
4401
    let m = repo.merge("feature").unwrap();
4402
    assert!(m.changed && m.checked_out);
4403
    let mut want = vec![h_b, h_c];
4404
    want.sort();
4405
    assert_eq!(m.heads, want);
4406
    assert_eq!(fs::read(r.join("b.txt")).unwrap(), b"b\n");
4407
    assert!(!repo.merge("feature").unwrap().changed, "already merged");
4408
    assert!(repo.merge("main").is_err());
4409
    // The other bookmark can be pushed by name and appears at origin.
4410
    assert!(repo.push_bookmark("origin", "feature", false).unwrap()[0].ok);
4411
    origin.refresh().unwrap();
4412
    assert_eq!(origin.resolve_heads("feature").unwrap(), vec![h_b]);
4413
    assert!(repo.push("origin", false).unwrap()[0].ok);
4414
    origin.refresh().unwrap();
4415
    assert_eq!(
4416
        repo.bookmarks()
4417
            .unwrap()
4418
            .iter()
4419
            .find(|b| b.name == "main")
4420
            .unwrap()
4421
            .ahead,
4422
        Some(0)
4423
    );
4424
    // A second workspace inherits the current bookmark and can switch independently.
4425
    let ws = repo.workspace_add(&root.join("ws"), None).unwrap();
4426
    assert_eq!(ws.config.bookmark, "main");
4427
    let mut ws = ws;
4428
    ws.bookmark_switch("feature", false).unwrap();
4429
    assert_eq!(
4430
        Repo::open(&r).unwrap().config.bookmark,
4431
        "main",
4432
        "the first workspace is unaffected"
4433
    );
4434
    assert!(
4435
        repo.bookmark_delete("feature").is_err(),
4436
        "current bookmark of another workspace"
4437
    );
4438
    ws.bookmark_switch("main", false).unwrap();
4439
    // Set and delete.
4440
    assert_eq!(repo.bookmark_set("feature", &[h_a]).unwrap(), vec![h_a]);
4441
    assert!(repo.bookmark_delete("main").is_err(), "current here");
4442
    repo.bookmark_delete("feature").unwrap();
4443
    assert!(repo.resolve_heads("feature").is_err());
4444
    assert!(repo.bookmark_set("feature", &[h_a]).is_err());
4445
    assert!(
4446
        repo.checkout(&[h_a], false, "checkout").is_ok(),
4447
        "changes of a deleted bookmark remain"
4448
    );
4449
}
4450
4451
#[test]
4452
fn oxygen_subrepos_pin_follow_and_update() {
4453
    hermetic();
4454
    let dir = tempfile::tempdir().unwrap();
4455
    let root = dir.path();
4456
    // A library repository with two commits, and a bare-ish origin for it.
4457
    let lib_origin = Repo::init(&root.join("lib-origin")).unwrap();
4458
    let lib_url = root.join("lib-origin").to_string_lossy().to_string();
4459
    let lib = Repo::clone(&lib_url, &root.join("lib"))
4460
        .unwrap()
4461
        .with_home(root.join("home"));
4462
    write(&root.join("lib"), "lib.txt", b"v1\n");
4463
    let l1 = lib.commit("lib v1", &[]).unwrap();
4464
    assert!(lib.push("origin", false).unwrap()[0].ok);
4465
    let _ = lib_origin;
4466
4467
    // The application (a clone of its own origin) adds it as a subrepo.
4468
    let app_origin = Repo::init(&root.join("app-origin")).unwrap();
4469
    let app_url = root.join("app-origin").to_string_lossy().to_string();
4470
    let _ = app_origin;
4471
    let app_dir = root.join("app");
4472
    let app = Repo::clone(&app_url, &app_dir)
4473
        .unwrap()
4474
        .with_home(root.join("home"));
4475
    write(&app_dir, "main.txt", b"app\n");
4476
    let pin = app.submodule_add(&lib_url, "libs/lib", None).unwrap();
4477
    assert!(matches!(&pin, crate::subrepo::Pin::Oxy { heads, .. } if heads == &vec![l1]));
4478
    assert!(app_dir.join(".oxymodules").exists() && app_dir.join("libs/lib/.oxy").is_dir());
4479
    let snap = app.snapshot("status").unwrap();
4480
    let paths: Vec<&str> = snap.statuses.iter().map(|s| s.path.as_str()).collect();
4481
    assert_eq!(
4482
        paths,
4483
        vec![".oxymodules", "libs/lib", "main.txt"],
4484
        "the nested files are not walked"
4485
    );
4486
    let a1 = app.commit("app with lib", &[]).unwrap();
4487
    let files = app.load_state(&[a1]).unwrap().materialize().files;
4488
    assert_eq!(files["libs/lib"].kind, NodeKind::Subrepo);
4489
    assert!(!files.contains_key("libs/lib/lib.txt"));
4490
    assert!(!app.snapshot("status").unwrap().changed);
4491
    let subs = app.subrepos().unwrap();
4492
    assert_eq!(subs.len(), 1);
4493
    assert_eq!(subs[0].actual.as_ref(), Some(&subs[0].pin));
4494
4495
    // Advance the nested repository: the parent sees a modified pin.
4496
    let nested = Repo::open(&app_dir.join("libs/lib"))
4497
        .unwrap()
4498
        .with_home(root.join("home"));
4499
    write(&app_dir.join("libs/lib"), "lib.txt", b"v2\n");
4500
    let l2 = nested.commit("lib v2", &[]).unwrap();
4501
    assert!(nested.push("origin", false).unwrap()[0].ok);
4502
    let snap = app.snapshot("status").unwrap();
4503
    assert_eq!(
4504
        snap.statuses
4505
            .iter()
4506
            .map(|s| (s.path.as_str(), s.status))
4507
            .collect::<Vec<_>>(),
4508
        vec![("libs/lib", ChangeStatus::Modified)]
4509
    );
4510
    let a2 = app.commit("bump lib", &[]).unwrap();
4511
    // Checking out the older app state brings the nested working copy back
4512
    // to the older pin, but never moves its bookmark backwards (oxygen#38).
4513
    let r = app.checkout(&[a1], false, "checkout").unwrap();
4514
    assert!(
4515
        r.notes.len() == 1 && r.notes[0].contains("keeps 1 newer change"),
4516
        "{:?}",
4517
        r.notes
4518
    );
4519
    assert_eq!(fs::read(app_dir.join("libs/lib/lib.txt")).unwrap(), b"v1\n");
4520
    let nested = Repo::open(&app_dir.join("libs/lib")).unwrap();
4521
    assert_eq!(nested.bookmark_heads().unwrap(), vec![l2]);
4522
    assert_eq!(nested.working_copy().unwrap().1.deps, vec![l1]);
4523
    assert!(!app.snapshot("status").unwrap().changed);
4524
    // A dirty nested repository is left alone and reported.
4525
    write(&app_dir.join("libs/lib"), "scratch.txt", b"wip\n");
4526
    let r = app.checkout(&[a2], false, "checkout").unwrap();
4527
    assert!(
4528
        r.notes.iter().any(|n| n.contains("uncommitted")),
4529
        "{:?}",
4530
        r.notes
4531
    );
4532
    assert_eq!(fs::read(app_dir.join("libs/lib/lib.txt")).unwrap(), b"v1\n");
4533
    fs::remove_file(app_dir.join("libs/lib/scratch.txt")).unwrap();
4534
    let r = app.submodule_update(false, &[]).unwrap();
4535
    assert_eq!(r, vec![("libs/lib".to_string(), SubrepoSync::Updated)]);
4536
    assert_eq!(fs::read(app_dir.join("libs/lib/lib.txt")).unwrap(), b"v2\n");
4537
    let _ = l2;
4538
4539
    // A fresh clone of the app has the pin but no nested repository until update --init.
4540
    assert!(app.push("origin", false).unwrap()[0].ok);
4541
    let clone_dir = root.join("app-clone");
4542
    let clone = Repo::clone(&app_url, &clone_dir)
4543
        .unwrap()
4544
        .with_home(root.join("home"));
4545
    assert!(!clone_dir.join("libs/lib/.oxy").exists());
4546
    assert_eq!(
4547
        clone.submodule_update(false, &[]).unwrap(),
4548
        vec![("libs/lib".to_string(), SubrepoSync::Missing)]
4549
    );
4550
    assert_eq!(
4551
        clone.submodule_update(true, &[]).unwrap(),
4552
        vec![("libs/lib".to_string(), SubrepoSync::Updated)]
4553
    );
4554
    assert_eq!(
4555
        fs::read(clone_dir.join("libs/lib/lib.txt")).unwrap(),
4556
        b"v2\n"
4557
    );
4558
    assert!(!clone.snapshot("status").unwrap().changed);
4559
    // Removing the subrepo leaves the directory and drops the node.
4560
    clone.submodule_remove("libs/lib").unwrap();
4561
    let snap = clone.snapshot("status").unwrap();
4562
    assert!(
4563
        snap.statuses
4564
            .iter()
4565
            .any(|s| s.path == "libs/lib" && s.status == ChangeStatus::Removed),
4566
        "{:?}",
4567
        snap.statuses
4568
    );
4569
    let c = clone.commit("drop lib", &[]).unwrap();
4570
    assert!(!clone
4571
        .load_state(&[c])
4572
        .unwrap()
4573
        .materialize()
4574
        .files
4575
        .contains_key("libs/lib"));
4576
    assert!(clone_dir.join("libs/lib/lib.txt").exists());
4577
    assert!(
4578
        !clone.snapshot("status").unwrap().changed,
4579
        "an unregistered nested repository is ignored"
4580
    );
4581
}
4582
4583
#[test]
4584
fn git_submodules_import_and_export_as_gitlinks() {
4585
    hermetic();
4586
    if std::process::Command::new("git")
4587
        .arg("--version")
4588
        .output()
4589
        .is_err()
4590
    {
4591
        eprintln!("git not installed; skipping");
4592
        return;
4593
    }
4594
    let dir = tempfile::tempdir().unwrap();
4595
    let root = dir.path();
4596
    let git_in = |d: &Path, args: &[&str]| -> String {
4597
        let out = std::process::Command::new("git")
4598
            .arg("-C")
4599
            .arg(d)
4600
            .args([
4601
                "-c",
4602
                "user.name=Grace",
4603
                "-c",
4604
                "[email protected]",
4605
                "-c",
4606
                "commit.gpgsign=false",
4607
                "-c",
4608
                "protocol.file.allow=always",
4609
            ])
4610
            .args(args)
4611
            .output()
4612
            .unwrap();
4613
        assert!(
4614
            out.status.success(),
4615
            "git {args:?}: {}",
4616
            String::from_utf8_lossy(&out.stderr)
4617
        );
4618
        String::from_utf8_lossy(&out.stdout).trim().to_string()
4619
    };
4620
    let sub = root.join("sub");
4621
    fs::create_dir_all(&sub).unwrap();
4622
    git_in(&sub, &["init", "-q", "-b", "main"]);
4623
    write(&sub, "s.txt", b"sub\n");
4624
    git_in(&sub, &["add", "."]);
4625
    git_in(&sub, &["commit", "-q", "-m", "sub initial"]);
4626
    let sub_sha = git_in(&sub, &["rev-parse", "HEAD"]);
4627
    let g = root.join("main.git");
4628
    fs::create_dir_all(&g).unwrap();
4629
    git_in(&g, &["init", "-q", "-b", "main"]);
4630
    write(&g, "README.md", b"# app\n");
4631
    git_in(&g, &["add", "."]);
4632
    git_in(&g, &["commit", "-q", "-m", "initial"]);
4633
    git_in(
4634
        &g,
4635
        &[
4636
            "submodule",
4637
            "add",
4638
            "-q",
4639
            sub.to_str().unwrap(),
4640
            "vendor/sub",
4641
        ],
4642
    );
4643
    git_in(&g, &["commit", "-q", "-m", "add submodule"]);
4644
4645
    let dest = root.join("oxy");
4646
    let repo = Repo::init(&dest).unwrap().with_home(root.join("home"));
4647
    let rep = repo.import_git(&g, "main").unwrap();
4648
    assert_eq!((rep.commits, rep.submodules), (2, 1));
4649
    let files = repo
4650
        .load_state(&repo.bookmark_heads().unwrap())
4651
        .unwrap()
4652
        .materialize()
4653
        .files;
4654
    assert_eq!(files["vendor/sub"].kind, NodeKind::Subrepo);
4655
    let FileContent::Opaque { blobs } = &files["vendor/sub"].content else {
4656
        panic!()
4657
    };
4658
    assert_eq!(
4659
        crate::subrepo::Pin::decode(&repo.read_blob(&blobs[0]).unwrap()).unwrap(),
4660
        crate::subrepo::Pin::Git {
4661
            sha: sub_sha.clone(),
4662
            branch: "HEAD".into()
4663
        }
4664
    );
4665
    let modules =
4666
        crate::subrepo::Modules::parse(&fs::read_to_string(dest.join(".oxymodules")).unwrap());
4667
    assert_eq!(modules.entries["vendor/sub"].url, sub.to_string_lossy());
4668
    assert!(modules.entries["vendor/sub"].git);
4669
    assert!(
4670
        files.contains_key(".gitmodules"),
4671
        "the Git file is kept for round trips"
4672
    );
4673
    assert!(
4674
        !dest.join("vendor/sub/.git").exists(),
4675
        "not cloned until update --init"
4676
    );
4677
    assert!(!repo.snapshot("status").unwrap().changed);
4678
    // update --init clones it at the pinned commit; status is unchanged.
4679
    assert_eq!(
4680
        repo.submodule_update(true, &[]).unwrap(),
4681
        vec![("vendor/sub".to_string(), SubrepoSync::Updated)]
4682
    );
4683
    assert_eq!(
4684
        git_in(&dest.join("vendor/sub"), &["rev-parse", "HEAD"]),
4685
        sub_sha
4686
    );
4687
    assert!(!repo.snapshot("status").unwrap().changed);
4688
    // Export writes the gitlink and .gitmodules back.
4689
    let mirror = root.join("mirror.git");
4690
    let rep = repo.git_export(&mirror).unwrap();
4691
    assert_eq!(rep.skipped_subrepos, 0);
4692
    let ls = git_in(&mirror, &["ls-tree", "main", "vendor/sub"]);
4693
    assert!(
4694
        ls.starts_with("160000 commit ") && ls.contains(&sub_sha),
4695
        "{ls}"
4696
    );
4697
    assert_eq!(
4698
        git_in(&mirror, &["ls-tree", "--name-only", "main"]),
4699
        ".gitmodules\nREADME.md\nvendor"
4700
    );
4701
    let orig_tree = git_in(&g, &["rev-parse", "main^{tree}"]);
4702
    assert_eq!(
4703
        git_in(&mirror, &["rev-parse", "main^{tree}"]),
4704
        orig_tree,
4705
        "tree round trip"
4706
    );
4707
}
4708
4709
#[test]
4710
fn partial_commits_by_path_and_by_hunk() {
4711
    hermetic();
4712
    let dir = tempfile::tempdir().unwrap();
4713
    let root = dir.path();
4714
    let repo = Repo::init(root).unwrap().with_home(root.join("home"));
4715
    write(root, "a.txt", b"1\n2\n3\n");
4716
    write(root, "b.txt", b"b\n");
4717
    let h0 = repo.commit("base", &[]).unwrap();
4718
    write(root, "a.txt", b"0\n1\n2\n3\n4\n");
4719
    write(root, "b.txt", b"b\nbb\n");
4720
    write(root, "c.txt", b"c\n");
4721
    // By path: only a.txt goes in; the rest stays on disk as uncommitted work.
4722
    let h1 = repo
4723
        .commit_selection("a only", &[], &Selection::Paths(vec!["a.txt".into()]))
4724
        .unwrap();
4725
    let c1 = repo.store().get_change(&h1).unwrap();
4726
    assert!(
4727
        c1.tree_ops.is_empty() && c1.edits.iter().all(|e| e.node() == c1.edits[0].node()),
4728
        "{:?}",
4729
        c1.tree_ops
4730
    );
4731
    assert_eq!(c1.deps, vec![h0]);
4732
    let files = repo.load_state(&[h1]).unwrap().materialize().files;
4733
    assert!(
4734
        matches!(&files["a.txt"].content, FileContent::Text { bytes, .. } if bytes == b"0\n1\n2\n3\n4\n")
4735
    );
4736
    assert!(matches!(&files["b.txt"].content, FileContent::Text { bytes, .. } if bytes == b"b\n"));
4737
    assert!(!files.contains_key("c.txt"));
4738
    let snap = repo.snapshot("status").unwrap();
4739
    assert_eq!(
4740
        snap.statuses
4741
            .iter()
4742
            .map(|s| (s.path.as_str(), s.status))
4743
            .collect::<Vec<_>>(),
4744
        vec![
4745
            ("b.txt", ChangeStatus::Modified),
4746
            ("c.txt", ChangeStatus::Added)
4747
        ]
4748
    );
4749
    assert_eq!(
4750
        fs::read(root.join("b.txt")).unwrap(),
4751
        b"b\nbb\n",
4752
        "disk untouched"
4753
    );
4754
    // By hunk: pick the b.txt insert; c.txt's addition is left.
4755
    let (_, hunks) = repo.hunks().unwrap();
4756
    let b_hunk = hunks
4757
        .iter()
4758
        .find(|h| h.path == "b.txt" && h.text.contains("+bb"))
4759
        .unwrap()
4760
        .index;
4761
    let h2 = repo
4762
        .commit_selection("b only", &[], &Selection::Hunks(vec![b_hunk]))
4763
        .unwrap();
4764
    let files = repo.load_state(&[h2]).unwrap().materialize().files;
4765
    assert!(
4766
        matches!(&files["b.txt"].content, FileContent::Text { bytes, .. } if bytes == b"b\nbb\n")
4767
    );
4768
    assert!(!files.contains_key("c.txt"));
4769
    let snap = repo.snapshot("status").unwrap();
4770
    assert_eq!(
4771
        snap.statuses
4772
            .iter()
4773
            .map(|s| s.path.as_str())
4774
            .collect::<Vec<_>>(),
4775
        vec!["c.txt"]
4776
    );
4777
    // Choosing only the content hunk of a file in a new directory pulls in
4778
    // the directory and file additions it needs.
4779
    write(root, "d/e.txt", b"e\n");
4780
    let (_, hunks) = repo.hunks().unwrap();
4781
    let e_insert = hunks
4782
        .iter()
4783
        .find(|h| h.path == "d/e.txt" && h.text.contains("+e"))
4784
        .unwrap()
4785
        .index;
4786
    let h3 = repo
4787
        .commit_selection("e only", &[], &Selection::Hunks(vec![e_insert]))
4788
        .unwrap();
4789
    let c3 = repo.store().get_change(&h3).unwrap();
4790
    assert_eq!(c3.tree_ops.len(), 2, "{:?}", c3.tree_ops);
4791
    let files = repo.load_state(&[h3]).unwrap().materialize().files;
4792
    assert!(files.contains_key("d/e.txt") && !files.contains_key("c.txt"));
4793
    // Choosing a new file's addition hunk brings its content along.
4794
    write(root, "f/g.txt", b"g\n");
4795
    let (_, hunks) = repo.hunks().unwrap();
4796
    let g_add = hunks
4797
        .iter()
4798
        .find(|h| h.path == "f/g.txt" && h.text.starts_with("A "))
4799
        .unwrap()
4800
        .index;
4801
    let h4 = repo
4802
        .commit_selection("g by addition", &[], &Selection::Hunks(vec![g_add]))
4803
        .unwrap();
4804
    let files = repo.load_state(&[h4]).unwrap().materialize().files;
4805
    assert!(
4806
        matches!(&files["f/g.txt"].content, FileContent::Text { bytes, .. } if bytes == b"g\n")
4807
    );
4808
    assert!(!repo
4809
        .snapshot("status")
4810
        .unwrap()
4811
        .statuses
4812
        .iter()
4813
        .any(|s| s.path == "f/g.txt"));
4814
    // Everything left commits normally; the working copy is then clean.
4815
    repo.commit("the rest", &[]).unwrap();
4816
    assert!(!repo.snapshot("status").unwrap().changed);
4817
    let files = repo
4818
        .load_state(&repo.bookmark_heads().unwrap())
4819
        .unwrap()
4820
        .materialize()
4821
        .files;
4822
    assert!(files.contains_key("c.txt"));
4823
}
4824
4825
#[test]
4826
fn blame_attributes_lines_to_introducing_changes_across_renames() {
4827
    hermetic();
4828
    let dir = tempfile::tempdir().unwrap();
4829
    let root = dir.path();
4830
    let mut repo = Repo::init(root).unwrap().with_home(root.join("home"));
4831
    repo.create_identity("Ada", "[email protected]", IdentityScope::User)
4832
        .unwrap();
4833
    write(root, "a.txt", b"one\n");
4834
    let h1 = repo.commit("first", &[]).unwrap();
4835
    write(root, "a.txt", b"one\ntwo\n");
4836
    let h2 = repo.commit("second", &[]).unwrap();
4837
    let b = repo.blame("a.txt").unwrap();
4838
    assert_eq!(
4839
        b.iter()
4840
            .map(|l| (l.line, l.hash, l.text.as_slice()))
4841
            .collect::<Vec<_>>(),
4842
        vec![(1, h1, b"one\n".as_slice()), (2, h2, b"two\n".as_slice())]
4843
    );
4844
    assert!(b.iter().all(|l| l.author == "Ada"));
4845
    assert_eq!(
4846
        b[0].change_id,
4847
        repo.store().get_change(&h1).unwrap().change_id
4848
    );
4849
    fs::rename(root.join("a.txt"), root.join("b.txt")).unwrap();
4850
    repo.commit("rename", &[]).unwrap();
4851
    let b = repo.blame("b.txt").unwrap();
4852
    assert_eq!(
4853
        b.iter().map(|l| l.hash).collect::<Vec<_>>(),
4854
        vec![h1, h2],
4855
        "the node survives the rename"
4856
    );
4857
    assert!(repo.blame("a.txt").is_err());
4858
}
4859
4860
#[test]
4861
fn bisect_finds_the_first_bad_change() {
4862
    hermetic();
4863
    let dir = tempfile::tempdir().unwrap();
4864
    let root = dir.path();
4865
    let repo = Repo::init(root).unwrap().with_home(root.join("home"));
4866
    let mut content = String::new();
4867
    let mut hashes = Vec::new();
4868
    for i in 1..=8 {
4869
        content.push_str(&format!("line {i}{}\n", if i == 5 { " bug" } else { "" }));
4870
        write(root, "f.txt", content.as_bytes());
4871
        hashes.push(repo.commit(&format!("step {i}"), &[]).unwrap());
4872
    }
4873
    // Each step appends after the previous line, so the chain is linear.
4874
    assert_eq!(repo.bookmark_heads().unwrap(), vec![hashes[7]]);
4875
    repo.bisect_start().unwrap();
4876
    assert!(matches!(
4877
        repo.bisect_mark(Some(true), &[hashes[0]]).unwrap(),
4878
        BisectStep::NeedMarks { good: 1, bad: 0 }
4879
    ));
4880
    let step = repo.bisect_mark(Some(false), &[hashes[7]]).unwrap();
4881
    assert!(
4882
        matches!(step, BisectStep::Testing { remaining: 7, .. }),
4883
        "{step:?}"
4884
    );
4885
    // Automated: bad when the bug line is present.
4886
    let step = repo
4887
        .bisect_run(&["sh".into(), "-c".into(), "! grep -q bug f.txt".into()])
4888
        .unwrap();
4889
    assert_eq!(step, BisectStep::Found { culprit: hashes[4] });
4890
    assert_eq!(
4891
        repo.bisect_status().unwrap(),
4892
        Some(BisectStep::Found { culprit: hashes[4] })
4893
    );
4894
    repo.bisect_reset().unwrap();
4895
    assert_eq!(fs::read_to_string(root.join("f.txt")).unwrap(), content);
4896
    assert!(repo.bisect_status().unwrap().is_none());
4897
    assert!(!repo.snapshot("status").unwrap().changed);
4898
    // Manual marks and a skip.
4899
    repo.bisect_start().unwrap();
4900
    repo.bisect_mark(Some(true), &[hashes[0]]).unwrap();
4901
    let mut step = repo.bisect_mark(Some(false), &[hashes[7]]).unwrap();
4902
    let mut skipped_once = false;
4903
    let mut guard = 0;
4904
    while let BisectStep::Testing { .. } = step {
4905
        guard += 1;
4906
        assert!(guard < 20);
4907
        let text = fs::read_to_string(root.join("f.txt")).unwrap();
4908
        if !skipped_once && text.contains("line 6") {
4909
            // An untestable state away from the boundary: the search routes around it.
4910
            skipped_once = true;
4911
            step = repo.bisect_mark(None, &[]).unwrap();
4912
            continue;
4913
        }
4914
        step = repo.bisect_mark(Some(!text.contains("bug")), &[]).unwrap();
4915
    }
4916
    assert!(skipped_once);
4917
    assert_eq!(step, BisectStep::Found { culprit: hashes[4] });
4918
    repo.bisect_reset().unwrap();
4919
    // Skipping the culprit itself leaves it among the candidates reported.
4920
    repo.bisect_start().unwrap();
4921
    repo.bisect_mark(Some(true), &[hashes[0]]).unwrap();
4922
    let mut step = repo.bisect_mark(Some(false), &[hashes[7]]).unwrap();
4923
    let mut guard = 0;
4924
    while let BisectStep::Testing { heads, .. } = &step {
4925
        guard += 1;
4926
        assert!(guard < 20);
4927
        let text = fs::read_to_string(root.join("f.txt")).unwrap();
4928
        let is_culprit_state =
4929
            heads.contains(&hashes[4]) && !heads.iter().any(|h| hashes[5..].contains(h));
4930
        step = if is_culprit_state {
4931
            repo.bisect_mark(None, &[]).unwrap()
4932
        } else {
4933
            repo.bisect_mark(Some(!text.contains("bug")), &[]).unwrap()
4934
        };
4935
    }
4936
    match step {
4937
        BisectStep::Inconclusive { candidates } => assert!(
4938
            candidates.contains(&hashes[4]) && candidates.len() <= 2,
4939
            "{candidates:?}"
4940
        ),
4941
        other => panic!("{other:?}"),
4942
    }
4943
    repo.bisect_reset().unwrap();
4944
}
4945
4946
#[test]
4947
fn squash_folds_a_change_into_its_dependency() {
4948
    hermetic();
4949
    let dir = tempfile::tempdir().unwrap();
4950
    let root = dir.path();
4951
    let repo = Repo::init(root).unwrap().with_home(root.join("home"));
4952
    write(root, "a.txt", b"1\n");
4953
    let a = repo.commit("A", &[]).unwrap();
4954
    write(root, "a.txt", b"1\n2\n");
4955
    let c = repo.commit("C", &[]).unwrap();
4956
    write(root, "a.txt", b"1\n2\n3\n");
4957
    let e = repo.commit("E", &[]).unwrap();
4958
    write(root, "b.txt", b"b\n");
4959
    let b = repo.commit("B", &[]).unwrap();
4960
    let id_a = repo.store().get_change(&a).unwrap().change_id;
4961
    let id_e = repo.store().get_change(&e).unwrap().change_id;
4962
    // E depends on C which A lacks: refused, naming it.
4963
    let err = repo.squash(&e, &a).unwrap_err().to_string();
4964
    assert!(err.contains(&c.short(12)), "{err}");
4965
    // C into A: A' has both, C is gone, E follows and still reads the same.
4966
    let a2 = repo.squash(&c, &a).unwrap();
4967
    let a2c = repo.store().get_change(&a2).unwrap();
4968
    assert_eq!(a2c.change_id, id_a);
4969
    assert!(a2c.deps.is_empty());
4970
    let heads = repo.bookmark_heads().unwrap();
4971
    let st = repo.load_state(&heads).unwrap();
4972
    assert!(!st.contains(&c) && !st.contains(&a) && !st.contains(&e));
4973
    let e2 = st
4974
        .changes()
4975
        .find(|(_, m)| m.change_id == id_e)
4976
        .map(|(h, _)| *h)
4977
        .unwrap();
4978
    assert_eq!(
4979
        repo.store().get_change(&e2).unwrap().deps,
4980
        vec![a2],
4981
        "E now depends on A' alone"
4982
    );
4983
    let files = st.materialize().files;
4984
    assert!(
4985
        matches!(&files["a.txt"].content, FileContent::Text { bytes, .. } if bytes == b"1\n2\n3\n")
4986
    );
4987
    assert!(files.contains_key("b.txt"));
4988
    assert!(st.contains(&b));
4989
    assert!(!repo.snapshot("status").unwrap().changed);
4990
    assert_eq!(repo.log().unwrap().len(), 4, "working copy, B, E', A'");
4991
    // Undo restores the three original changes.
4992
    repo.undo().unwrap();
4993
    repo.undo().unwrap();
4994
    let st = repo.load_state(&repo.bookmark_heads().unwrap()).unwrap();
4995
    assert!(st.contains(&c) && st.contains(&a) && st.contains(&e));
4996
}
4997
4998
#[test]
4999
fn rebase_re_expresses_a_change_against_another_base() {
5000
    hermetic();
5001
    let dir = tempfile::tempdir().unwrap();
5002
    let root = dir.path();
5003
    let repo = Repo::init(root).unwrap().with_home(root.join("home"));
5004
    write(root, "a.txt", b"1\n2\n");
5005
    let a = repo.commit("A", &[]).unwrap();
5006
    write(root, "a.txt", b"1\n2\n3\n");
5007
    let c = repo.commit("C: append 3", &[]).unwrap();
5008
    write(root, "a.txt", b"1\n2\n3\n4\n");
5009
    let e = repo.commit("E: append 4", &[]).unwrap();
5010
    // A different base: A plus a change that prepends a line.
5011
    repo.checkout(&[a], true, "checkout").unwrap();
5012
    write(root, "a.txt", b"0\n1\n2\n");
5013
    let d = repo.commit("D: prepend 0", &[]).unwrap();
5014
    let id_c = repo.store().get_change(&c).unwrap().change_id;
5015
    let id_e = repo.store().get_change(&e).unwrap().change_id;
5016
    // Rebase C onto D: its effect (append 3) re-derived against D's text.
5017
    let c2 = repo.rebase(&c, &[d]).unwrap();
5018
    let c2c = repo.store().get_change(&c2).unwrap();
5019
    assert_eq!(c2c.change_id, id_c);
5020
    assert!(c2c.deps.contains(&d), "{:?}", c2c.deps);
5021
    let heads = repo.bookmark_heads().unwrap();
5022
    let st = repo.load_state(&heads).unwrap();
5023
    assert!(!st.contains(&c) && st.contains(&d));
5024
    let e2 = st
5025
        .changes()
5026
        .find(|(_, m)| m.change_id == id_e)
5027
        .map(|(h, _)| *h)
5028
        .unwrap();
5029
    let e2deps = repo.store().get_change(&e2).unwrap().deps;
5030
    assert!(
5031
        e2deps.contains(&c2) && !e2deps.contains(&c) && e2deps.contains(&a),
5032
        "E follows C by content and still depends on A, which introduced the file: {e2deps:?}"
5033
    );
5034
    let files = st.materialize().files;
5035
    assert!(
5036
        matches!(&files["a.txt"].content, FileContent::Text { bytes, .. } if bytes == b"0\n1\n2\n3\n4\n"),
5037
        "{:?}",
5038
        files["a.txt"].content
5039
    );
5040
    assert!(!files["a.txt"].is_conflicted());
5041
    // Rebasing onto a state that already contains the change is refused.
5042
    assert!(repo.rebase(&c2, &[c2]).is_err());
5043
    let err = repo.rebase(&e2, &[d]).unwrap_err().to_string();
5044
    assert!(
5045
        err.contains("lacks dependencies"),
5046
        "E needs C, which D's state does not have: {err}"
5047
    );
5048
}
5049
5050
#[test]
5051
fn unsigned_tags_keep_their_message() {
5052
    hermetic();
5053
    let dir = tempfile::tempdir().unwrap();
5054
    let root = dir.path();
5055
    let repo = Repo::init(root).unwrap().with_home(root.join("home"));
5056
    write(root, "a.txt", b"a\n");
5057
    repo.commit("a", &[]).unwrap();
5058
    assert!(repo.secret_key().unwrap().is_none());
5059
    repo.tag_create("v1", &repo.bookmark_heads().unwrap(), "first release")
5060
        .unwrap();
5061
    let tags = repo.tags().unwrap();
5062
    assert_eq!(
5063
        (
5064
            tags[0].name.as_str(),
5065
            tags[0].message.as_str(),
5066
            tags[0].signer.as_deref()
5067
        ),
5068
        ("v1", "first release", None)
5069
    );
5070
    assert!(
5071
        repo.tag_refs().unwrap()[0].attestation.is_none(),
5072
        "an unsigned attestation is not advertised"
5073
    );
5074
}
5075
5076
#[test]
5077
fn fsck_passes_a_sound_repository_and_names_each_fault() {
5078
    // Files on disk are what this tests: tampering with them, and the
5079
    // directory store's crash points.
5080
    if std::env::var_os("OXY_STORE_BACKEND").is_some() {
5081
        return;
5082
    }
5083
    hermetic();
5084
    let dir = tempfile::tempdir().unwrap();
5085
    let root = dir.path();
5086
    let origin_path = root.join("origin");
5087
    let origin = Repo::init(&origin_path).unwrap();
5088
    let mut a = Repo::clone(&origin_path.to_string_lossy(), &root.join("a"))
5089
        .unwrap()
5090
        .with_home(root.join("home-a"));
5091
    a.create_identity("Ada", "[email protected]", IdentityScope::Repo)
5092
        .unwrap();
5093
    write(&root.join("a"), "f.txt", b"one\n");
5094
    write(&root.join("a"), "bin.dat", b"\0\x01\x02binary");
5095
    let h1 = a.commit("first", &[]).unwrap();
5096
    write(&root.join("a"), "f.txt", b"one\ntwo\n");
5097
    let h2 = a.commit("second", &[]).unwrap();
5098
    a.tag_create("v1", &[h2], "first release").unwrap();
5099
    a.checkpoint().unwrap();
5100
    assert!(a.push("origin", false).unwrap()[0].ok);
5101
    origin.refresh().unwrap();
5102
5103
    // Sound: signed changes, a seal, a tag, a checkpoint, a ref attestation.
5104
    for repo in [&a, &origin] {
5105
        let rep = repo.fsck().unwrap();
5106
        assert_eq!(rep.problems, vec![], "{rep:?}");
5107
        // The two commits, plus the working copy's change in `a`.
5108
        assert!(rep.changes >= 2 && rep.signed >= 2, "{rep:?}");
5109
        assert!(rep.ops > 1 && rep.objects > 5);
5110
    }
5111
    assert!(origin.fsck().unwrap().attestations >= 1);
5112
5113
    // A flipped byte in a stored object is corruption, named by hash.
5114
    let c1 = a.store().path_for(&h1);
5115
    let pristine = fs::read(&c1).unwrap();
5116
    let mut bytes = pristine.clone();
5117
    *bytes.last_mut().unwrap() ^= 1;
5118
    fs::write(&c1, &bytes).unwrap();
5119
    let rep = a.fsck().unwrap();
5120
    assert!(rep.errors() >= 1);
5121
    assert!(
5122
        rep.problems
5123
            .iter()
5124
            .any(|p| p.object == Some(h1) && p.what.contains("unreadable")),
5125
        "{rep:?}"
5126
    );
5127
    fs::write(&c1, &pristine).unwrap();
5128
    assert_eq!(a.fsck().unwrap().errors(), 0);
5129
5130
    // A missing change is named with what needed it.
5131
    fs::remove_file(&c1).unwrap();
5132
    let rep = a.fsck().unwrap();
5133
    assert!(
5134
        rep.problems.iter().any(|p| p.severity == Severity::Error
5135
            && p.object == Some(h1)
5136
            && p.what.contains("change missing, needed by change")),
5137
        "{rep:?}"
5138
    );
5139
    fs::write(&c1, &pristine).unwrap();
5140
5141
    // A missing blob is an error in a full clone.
5142
    let c2 = a.store().get_change(&h1).unwrap();
5143
    let blob = c2
5144
        .edits
5145
        .iter()
5146
        .find_map(|e| match e {
5147
            Edit::Replace { new: Some(b), .. } => Some(*b),
5148
            _ => None,
5149
        })
5150
        .expect("the binary file is a blob");
5151
    let bp = a.store().path_for(&blob);
5152
    let blob_bytes = fs::read(&bp).unwrap();
5153
    fs::remove_file(&bp).unwrap();
5154
    let rep = a.fsck().unwrap();
5155
    assert!(
5156
        rep.problems
5157
            .iter()
5158
            .any(|p| p.object == Some(blob) && p.what.contains("blob missing")),
5159
        "{rep:?}"
5160
    );
5161
    fs::write(&bp, &blob_bytes).unwrap();
5162
5163
    // A broken op log head is reported, not a crash.
5164
    let head = root.join("a/.oxy/ops/head");
5165
    let saved = fs::read(&head).unwrap();
5166
    fs::write(&head, b"not a hash").unwrap();
5167
    let rep = a.fsck().unwrap();
5168
    assert!(
5169
        rep.problems.iter().any(|p| p.what.contains("ops/head")),
5170
        "{rep:?}"
5171
    );
5172
    fs::write(&head, saved).unwrap();
5173
    assert_eq!(a.fsck().unwrap().problems, vec![]);
5174
}
5175
5176
/// Copy a directory tree (for restoring a pristine repository).
5177
fn copy_tree(from: &Path, to: &Path) {
5178
    fs::create_dir_all(to).unwrap();
5179
    for e in fs::read_dir(from).unwrap() {
5180
        let e = e.unwrap();
5181
        let target = to.join(e.file_name());
5182
        if e.file_type().unwrap().is_dir() {
5183
            copy_tree(&e.path(), &target);
5184
        } else {
5185
            fs::copy(e.path(), &target).unwrap();
5186
        }
5187
    }
5188
}
5189
5190
/// Spec §13.6: stop `commit` and `push` at every durable step, as a crash
5191
/// would, and check that both repositories still open, pass `fsck`, and
5192
/// accept the same operation again.
5193
#[test]
5194
fn crash_at_every_step_of_commit_and_push_leaves_sound_repositories() {
5195
    // Files on disk are what this tests: tampering with them, and the
5196
    // directory store's crash points.
5197
    if std::env::var_os("OXY_STORE_BACKEND").is_some() {
5198
        return;
5199
    }
5200
    use crate::durable::failpoint;
5201
    hermetic();
5202
    let dir = tempfile::tempdir().unwrap();
5203
    let pristine = dir.path().join("pristine");
5204
    let origin_path = pristine.join("origin");
5205
    Repo::init(&origin_path).unwrap();
5206
    let mut a = Repo::clone(&origin_path.to_string_lossy(), &pristine.join("a"))
5207
        .unwrap()
5208
        .with_home(dir.path().join("home"));
5209
    a.create_identity("Ada", "[email protected]", IdentityScope::Repo)
5210
        .unwrap();
5211
    write(&pristine.join("a"), "f.txt", b"one\n");
5212
    a.commit("first", &[]).unwrap();
5213
    assert!(a.push("origin", false).unwrap()[0].ok);
5214
    drop(a);
5215
5216
    type Op = fn(&Repo) -> Result<()>;
5217
    let edit_and_commit: Op = |r| {
5218
        write(r.root(), "f.txt", b"one\ntwo\n");
5219
        write(r.root(), "big.bin", &vec![7u8; 300_000]);
5220
        r.commit("second", &[]).map(|_| ())
5221
    };
5222
    let push: Op = |r| {
5223
        let res = r.push("origin", false)?;
5224
        if res.iter().all(|x| x.ok) {
5225
            Ok(())
5226
        } else {
5227
            Err(RepoError::Msg(format!("{res:?}")))
5228
        }
5229
    };
5230
5231
    for (name, prepare, op) in [
5232
        ("commit", None, edit_and_commit),
5233
        ("push", Some(edit_and_commit), push),
5234
    ] {
5235
        let mut steps = 0;
5236
        for n in 1.. {
5237
            let run = dir.path().join(format!("{name}-{n}"));
5238
            copy_tree(&pristine, &run);
5239
            // Clones record their remote by path; point it at this copy.
5240
            let open = |p: &Path| {
5241
                let mut r = Repo::open(p).unwrap().with_home(dir.path().join("home"));
5242
                r.config
5243
                    .set("remote.origin.url", &run.join("origin").to_string_lossy())
5244
                    .unwrap();
5245
                r.save_config().unwrap();
5246
                r
5247
            };
5248
            let a = open(&run.join("a"));
5249
            if let Some(prep) = prepare {
5250
                prep(&a).unwrap();
5251
            }
5252
            failpoint::crash_after(n);
5253
            let outcome = op(&a);
5254
            let crashed = failpoint::disarm();
5255
            drop(a);
5256
            if !crashed {
5257
                outcome.unwrap_or_else(|e| panic!("{name} failed without a crash: {e}"));
5258
                steps = n - 1;
5259
                break;
5260
            }
5261
            assert!(
5262
                outcome.is_err(),
5263
                "{name}: a crash at step {n} was swallowed"
5264
            );
5265
            for repo in ["a", "origin"] {
5266
                let r = Repo::open(&run.join(repo)).unwrap_or_else(|e| {
5267
                    panic!("{name} crash at step {n}: {repo} no longer opens: {e}")
5268
                });
5269
                let rep = r.fsck().unwrap();
5270
                assert_eq!(
5271
                    rep.errors(),
5272
                    0,
5273
                    "{name} crash at step {n}: {repo} fails fsck: {:?}",
5274
                    rep.problems
5275
                );
5276
            }
5277
            // The interrupted operation can simply be run again.
5278
            let a = open(&run.join("a"));
5279
            // A crash after the commit point leaves the commit done.
5280
            let landed = a
5281
                .bookmark_heads()
5282
                .unwrap()
5283
                .iter()
5284
                .any(|h| a.store().get_change(h).unwrap().message == "second");
5285
            let again = match (name, landed) {
5286
                ("commit", true) => Ok(()),
5287
                ("commit", false) => a.commit("second", &[]).map(|_| ()),
5288
                _ => op(&a),
5289
            };
5290
            again.unwrap_or_else(|e| panic!("{name} crash at step {n}: retry failed: {e}"));
5291
            assert_eq!(a.fsck().unwrap().errors(), 0);
5292
            fs::remove_dir_all(&run).unwrap();
5293
        }
5294
        assert!(steps >= 3, "{name} has only {steps} durable steps?");
5295
    }
5296
}
5297
5298
/// Spec §12.1: commands in two workspaces of one repository, and pushes,
5299
/// running at the same time lose nothing: every commit ends up on the
5300
/// bookmark, locally and on the remote, and the repository passes fsck.
5301
#[test]
5302
fn concurrent_commits_in_two_workspaces_lose_nothing() {
5303
    hermetic();
5304
    let dir = tempfile::tempdir().unwrap();
5305
    let root = dir.path();
5306
    let origin = root.join("origin");
5307
    Repo::init_bare_unbound(&origin).unwrap();
5308
    let main = root.join("main");
5309
    let mut repo = Repo::init(&main).unwrap();
5310
    repo.config
5311
        .set("remote.origin.url", &origin.to_string_lossy())
5312
        .unwrap();
5313
    repo.save_config().unwrap();
5314
    write(&main, "seed.txt", b"seed\n");
5315
    repo.commit("seed", &[]).unwrap();
5316
    let second = root.join("second");
5317
    repo.workspace_add(&second, None).unwrap();
5318
    drop(repo);
5319
5320
    const EACH: usize = 15;
5321
    std::thread::scope(|s| {
5322
        for (tag, dir, push) in [("a", main.clone(), true), ("b", second.clone(), false)] {
5323
            s.spawn(move || {
5324
                let r = Repo::open(&dir).unwrap();
5325
                for i in 0..EACH {
5326
                    write(
5327
                        &dir,
5328
                        &format!("{tag}-{i}.txt"),
5329
                        format!("{tag} {i}\n").as_bytes(),
5330
                    );
5331
                    r.commit(&format!("{tag} {i}"), &[]).unwrap();
5332
                    if push && i % 5 == 4 {
5333
                        // A push may be refused while the other workspace moves the bookmark; nothing may be lost either way.
5334
                        let _ = r.push("origin", false);
5335
                    }
5336
                }
5337
            });
5338
        }
5339
    });
5340
5341
    let repo = Repo::open(&main).unwrap();
5342
    let heads = repo.bookmark_heads().unwrap();
5343
    let state = repo.load_state(&heads).unwrap();
5344
    let messages: BTreeSet<String> = state.changes().map(|(_, m)| m.message.clone()).collect();
5345
    for tag in ["a", "b"] {
5346
        for i in 0..EACH {
5347
            assert!(
5348
                messages.contains(&format!("{tag} {i}")),
5349
                "lost commit {tag} {i}; have {messages:?}"
5350
            );
5351
        }
5352
    }
5353
    let rep = repo.fsck().unwrap();
5354
    assert_eq!(rep.errors(), 0, "{:?}", rep.problems);
5355
    assert!(repo.push("origin", false).unwrap().iter().all(|r| r.ok));
5356
    let hosted = Repo::open(&origin).unwrap();
5357
    let hosted_heads = hosted.bookmark_heads().unwrap();
5358
    assert_eq!(
5359
        hosted.load_state(&hosted_heads).unwrap().len(),
5360
        state.len(),
5361
        "the remote has every commit"
5362
    );
5363
}
5364
5365
/// Two operations recorded from the same parent (what two processes do
5366
/// when they race) are merged: both bookmarks' heads survive, and a
5367
/// change made on one side only is kept.
5368
#[test]
5369
fn operations_from_the_same_parent_are_merged() {
5370
    hermetic();
5371
    let dir = tempfile::tempdir().unwrap();
5372
    let root = dir.path();
5373
    let repo = Repo::init(root).unwrap();
5374
    write(root, "a.txt", b"a\n");
5375
    let a = repo.commit("a", &[]).unwrap();
5376
    write(root, "b.txt", b"b\n");
5377
    let b = repo.commit("b", &[]).unwrap();
5378
    let (x, op) = repo.head_op().unwrap();
5379
    let state = |heads: Vec<ChangeHash>| repo.store().put_state(&StateObject::new(heads)).unwrap();
5380
5381
    // Side one moves main to just `a` and adds a bookmark; side two moves main to just `b`.
5382
    let mut one = op.view.clone();
5383
    one.bookmarks.insert("main".into(), state(vec![a]));
5384
    one.bookmarks.insert("topic".into(), state(vec![a]));
5385
    let mut two = op.view.clone();
5386
    two.bookmarks.insert("main".into(), state(vec![b]));
5387
    repo.record_op(&[x], "one", one).unwrap();
5388
    let merged = repo.record_op(&[x], "two", two).unwrap();
5389
5390
    let (head, op) = repo.head_op().unwrap();
5391
    assert_eq!(head, merged);
5392
    assert_eq!(op.parents.len(), 2, "a merge of the two operations");
5393
    assert!(op.command.contains("merged with a concurrent operation"));
5394
    let mut main = repo
5395
        .store()
5396
        .get_state(&op.view.bookmarks["main"])
5397
        .unwrap()
5398
        .heads;
5399
    main.sort();
5400
    let mut want = vec![a, b];
5401
    want.sort();
5402
    assert_eq!(main, want, "both sides' heads are kept");
5403
    assert!(
5404
        op.view.bookmarks.contains_key("topic"),
5405
        "a one-sided change survives"
5406
    );
5407
    assert_eq!(repo.fsck().unwrap().errors(), 0);
5408
}
5409
5410
#[test]
5411
fn failed_requests_come_with_a_next_step() {
5412
    use crate::protocol::hint_for;
5413
    assert!(hint_for("https://h/x/oxy/v1/push: HTTP 401: bad token")
5414
        .unwrap()
5415
        .contains("token"));
5416
    assert!(hint_for("…: HTTP 403: forbidden")
5417
        .unwrap()
5418
        .contains("repo:write"));
5419
    assert!(hint_for("…: HTTP 404: no such repository")
5420
        .unwrap()
5421
        .contains("owner and repository name"));
5422
    assert!(hint_for("invalid peer certificate: UnknownIssuer")
5423
        .unwrap()
5424
        .contains("oxyhub-ca.pem"));
5425
    assert!(hint_for("Connect error: Connection refused (os error 111)")
5426
        .unwrap()
5427
        .contains("running"));
5428
    assert!(hint_for("Dns Failed: failed to lookup address information")
5429
        .unwrap()
5430
        .contains("resolve"));
5431
    assert_eq!(hint_for("something else entirely"), None);
5432
}
5433
5434
#[test]
5435
fn doctor_names_problems_and_what_to_do() {
5436
    hermetic();
5437
    let dir = tempfile::tempdir().unwrap();
5438
    let root = dir.path();
5439
    let origin = root.join("origin");
5440
    Repo::init_bare_unbound(&origin).unwrap();
5441
    let mut repo = Repo::init(&root.join("r"))
5442
        .unwrap()
5443
        .with_home(root.join("home"));
5444
    let find = |r: &DoctorReport, area: &str, h: Health| {
5445
        r.checks
5446
            .iter()
5447
            .find(|c| c.area == area && c.health == h)
5448
            .cloned()
5449
    };
5450
5451
    let r = repo.doctor(true);
5452
    assert!(find(&r, "identity", Health::Warn)
5453
        .unwrap()
5454
        .hint
5455
        .unwrap()
5456
        .contains("oxy identity create"));
5457
    assert!(find(&r, "repository", Health::Ok).is_some());
5458
5459
    repo.create_identity("Ada", "[email protected]", IdentityScope::Repo)
5460
        .unwrap();
5461
    repo.config.set("author.name", "Ada").unwrap();
5462
    repo.config.set("author.email", "[email protected]").unwrap();
5463
    repo.config
5464
        .set("remote.origin.url", &origin.to_string_lossy())
5465
        .unwrap();
5466
    repo.config
5467
        .set("remote.down.url", "http://127.0.0.1:9/a/b")
5468
        .unwrap();
5469
    repo.config.set("remote.down.token", "t").unwrap();
5470
    repo.config
5471
        .set("remote.badca.url", "https://example.invalid/a/b")
5472
        .unwrap();
5473
    repo.config
5474
        .set(
5475
            "remote.badca.ca",
5476
            &root.join("missing.pem").to_string_lossy(),
5477
        )
5478
        .unwrap();
5479
    repo.save_config().unwrap();
5480
5481
    let r = repo.doctor(true);
5482
    assert!(find(&r, "identity", Health::Ok).is_some(), "{r:?}");
5483
    assert!(find(&r, "author", Health::Ok).is_some(), "{r:?}");
5484
    assert!(find(&r, "remote origin", Health::Ok)
5485
        .unwrap()
5486
        .message
5487
        .contains("first push binds it"));
5488
    let down = find(&r, "remote down", Health::Fail).unwrap();
5489
    assert!(
5490
        down.hint.as_deref().unwrap_or("").contains("running"),
5491
        "{down:?}"
5492
    );
5493
    let badca = find(&r, "remote badca", Health::Fail).unwrap();
5494
    assert!(
5495
        badca.hint.unwrap().contains("remote.badca.ca"),
5496
        "the remote's own name is in the hint"
5497
    );
5498
    assert_eq!(r.worst(), Health::Fail);
5499
5500
    // Offline, nothing is contacted.
5501
    let r = repo.doctor(false);
5502
    assert!(find(&r, "remote down", Health::Fail).is_none());
5503
    assert!(find(&r, "remote down", Health::Ok)
5504
        .unwrap()
5505
        .message
5506
        .contains("not contacted"));
5507
}
5508
5509
/// Spec §8.1: deleting a line depends on whoever inserted the lines right
5510
/// after it. Inserting after `b` and then deleting `b`, one commit after
5511
/// the other, must not leave a delete/insert conflict.
5512
#[test]
5513
fn deleting_a_line_after_an_insertion_below_it_is_not_a_conflict() {
5514
    hermetic();
5515
    let dir = tempfile::tempdir().unwrap();
5516
    let root = dir.path();
5517
    let repo = Repo::init(root).unwrap();
5518
    write(root, "f", b"a\nb\nc\n");
5519
    repo.commit("base", &[]).unwrap();
5520
    write(root, "f", b"a\nb\nx\nc\n");
5521
    let insert = repo.commit("insert x after b", &[]).unwrap();
5522
    write(root, "f", b"a\nx\nc\n");
5523
    let delete = repo.commit("delete b", &[]).unwrap();
5524
    assert!(
5525
        repo.store()
5526
            .get_change(&delete)
5527
            .unwrap()
5528
            .deps
5529
            .contains(&insert),
5530
        "the deletion depends on the insertion below the deleted line"
5531
    );
5532
    let heads = repo.bookmark_heads().unwrap();
5533
    assert_eq!(heads, vec![delete]);
5534
    let snap = repo.load_state(&heads).unwrap().materialize();
5535
    assert!(!snap.is_conflicted());
5536
    assert!(
5537
        matches!(&snap.files["f"].content, FileContent::Text { bytes, .. } if bytes == b"a\nx\nc\n")
5538
    );
5539
}
5540
5541
/// Spec §9.3: a binary file reverted to an earlier blob keeps it, and each
5542
/// replacement depends on the change that set the blob it replaces.
5543
#[test]
5544
fn a_binary_file_reverted_to_an_earlier_blob_keeps_it() {
5545
    hermetic();
5546
    let dir = tempfile::tempdir().unwrap();
5547
    let root = dir.path();
5548
    let repo = Repo::init(root).unwrap();
5549
    write(root, "bin", b"\0A");
5550
    let v1 = repo.commit("v1", &[]).unwrap();
5551
    write(root, "bin", b"\0B");
5552
    let v2 = repo.commit("v2", &[]).unwrap();
5553
    assert!(repo.store().get_change(&v2).unwrap().deps.contains(&v1));
5554
    write(root, "bin", b"\0A");
5555
    let v3 = repo.commit("back to A", &[]).unwrap();
5556
    assert!(repo.store().get_change(&v3).unwrap().deps.contains(&v2));
5557
    assert_eq!(repo.bookmark_heads().unwrap(), vec![v3]);
5558
    let state = repo.load_state(&[v3]).unwrap();
5559
    let snap = state.materialize();
5560
    let FileContent::Opaque { blobs } = &snap.files["bin"].content else {
5561
        panic!("opaque")
5562
    };
5563
    assert_eq!(blobs.len(), 1, "one live blob, not none and not two");
5564
    assert_eq!(repo.read_blob(&blobs[0]).unwrap(), b"\0A");
5565
}
5566
5567
/// Spec §23: a binary file changed on two branches and merged in Git to
5568
/// one side's version comes back as that version at the merge, and the
5569
/// import verifies commit by commit.
5570
#[test]
5571
fn git_import_resolves_a_binary_merged_in_git_and_verifies() {
5572
    hermetic();
5573
    if std::process::Command::new("git")
5574
        .arg("--version")
5575
        .output()
5576
        .is_err()
5577
    {
5578
        eprintln!("git not installed; skipping");
5579
        return;
5580
    }
5581
    let dir = tempfile::tempdir().unwrap();
5582
    let root = dir.path();
5583
    let g = root.join("src.git");
5584
    fs::create_dir_all(&g).unwrap();
5585
    let git = |args: &[&str]| -> String {
5586
        let out = std::process::Command::new("git")
5587
            .arg("-C")
5588
            .arg(&g)
5589
            .args([
5590
                "-c",
5591
                "user.name=Grace",
5592
                "-c",
5593
                "[email protected]",
5594
                "-c",
5595
                "commit.gpgsign=false",
5596
            ])
5597
            .args(args)
5598
            .output()
5599
            .unwrap();
5600
        assert!(
5601
            out.status.success(),
5602
            "git {args:?}: {}",
5603
            String::from_utf8_lossy(&out.stderr)
5604
        );
5605
        String::from_utf8_lossy(&out.stdout).trim().to_string()
5606
    };
5607
    git(&["init", "-q", "-b", "main"]);
5608
    write(&g, "logo.bin", b"\0base");
5609
    write(&g, "notes.txt", b"a\nb\nc\n");
5610
    git(&["add", "."]);
5611
    git(&["commit", "-qm", "base"]);
5612
    git(&["checkout", "-qb", "side"]);
5613
    write(&g, "logo.bin", b"\0side");
5614
    write(&g, "notes.txt", b"a\nb\nx\nc\n");
5615
    git(&["commit", "-qam", "side"]);
5616
    git(&["checkout", "-q", "main"]);
5617
    write(&g, "logo.bin", b"\0main");
5618
    git(&["commit", "-qam", "main"]);
5619
    // Git cannot merge the binary; the merge takes main's and keeps side's text.
5620
    let _ = std::process::Command::new("git")
5621
        .arg("-C")
5622
        .arg(&g)
5623
        .args([
5624
            "-c",
5625
            "user.name=G",
5626
            "-c",
5627
            "user.email=g@e",
5628
            "merge",
5629
            "-q",
5630
            "side",
5631
        ])
5632
        .output();
5633
    write(&g, "logo.bin", b"\0main");
5634
    git(&["add", "."]);
5635
    git(&["commit", "-qm", "merge side"]);
5636
    // Then a revert of the binary to its first version.
5637
    write(&g, "logo.bin", b"\0base");
5638
    git(&["commit", "-qam", "back to base"]);
5639
5640
    let repo = Repo::init(&root.join("o")).unwrap();
5641
    let rep = repo.import_git(&g, "main").unwrap();
5642
    assert_eq!(rep.merges, 1);
5643
    let v = repo.verify_git_import(&g, "main").unwrap();
5644
    assert!(v.mismatches.is_empty(), "{:?}", v.mismatches);
5645
    assert_eq!(v.commits, 5);
5646
    let snap = repo
5647
        .load_state(&repo.bookmark_heads().unwrap())
5648
        .unwrap()
5649
        .materialize();
5650
    assert!(!snap.is_conflicted());
5651
    let FileContent::Opaque { blobs } = &snap.files["logo.bin"].content else {
5652
        panic!("opaque")
5653
    };
5654
    assert_eq!(repo.read_blob(&blobs[0]).unwrap(), b"\0base");
5655
}
5656
5657
/// Spec §7.7 on a file system without executable bits or symlinks: the
5658
/// recorded bit is kept, and a symlink checked out as a plain file holding
5659
/// its target is still that symlink.
5660
#[cfg(unix)]
5661
#[test]
5662
fn windows_file_systems_keep_exec_bits_and_symlinks() {
5663
    use crate::portable::Platform;
5664
    use std::os::unix::fs::PermissionsExt;
5665
    hermetic();
5666
    let dir = tempfile::tempdir().unwrap();
5667
    let root = dir.path();
5668
    let repo = Repo::init(root).unwrap();
5669
    write(root, "run.sh", b"#!/bin/sh\n");
5670
    fs::set_permissions(root.join("run.sh"), fs::Permissions::from_mode(0o755)).unwrap();
5671
    std::os::unix::fs::symlink("run.sh", root.join("link")).unwrap();
5672
    repo.commit("script and link", &[]).unwrap();
5673
    drop(repo);
5674
5675
    // What checking out on Windows leaves: no exec bit, the link as a file.
5676
    fs::set_permissions(root.join("run.sh"), fs::Permissions::from_mode(0o644)).unwrap();
5677
    fs::remove_file(root.join("link")).unwrap();
5678
    write(root, "link", b"run.sh");
5679
    let win = Repo::open(root).unwrap().with_platform(Platform::windows());
5680
    let s = win.snapshot("oxy status").unwrap();
5681
    assert!(
5682
        s.statuses.is_empty(),
5683
        "nothing changed on Windows: {:?}",
5684
        statuses(&s)
5685
    );
5686
    // Editing the file is a content change, not a mode change; retargeting the link keeps it a link.
5687
    write(root, "run.sh", b"#!/bin/sh\necho hi\n");
5688
    write(root, "link", b"other");
5689
    let h = win.commit("edit on Windows", &[]).unwrap();
5690
    let snap = win.load_state(&[h]).unwrap().materialize();
5691
    assert!(snap.files["run.sh"].mode.exec, "the exec bit survives");
5692
    assert_eq!(snap.files["link"].kind, NodeKind::Symlink);
5693
    // The same working copy read as Linux sees the lost bit and the plain file.
5694
    let linux = Repo::open(root).unwrap();
5695
    assert!(!linux.snapshot("oxy status").unwrap().statuses.is_empty());
5696
}
5697
5698
/// Paths that collide on case-insensitive or Windows file systems are
5699
/// named at checkout there, and by doctor everywhere.
5700
#[test]
5701
fn paths_other_platforms_cannot_hold_are_reported() {
5702
    use crate::portable::Platform;
5703
    hermetic();
5704
    let dir = tempfile::tempdir().unwrap();
5705
    let root = dir.path();
5706
    let repo = Repo::init(root).unwrap();
5707
    write(root, "README.md", b"a\n");
5708
    write(root, "readme.md", b"b\n");
5709
    write(root, "src/aux.c", b"int x;\n");
5710
    let h = repo.commit("unportable", &[]).unwrap();
5711
    let r = repo.doctor(false);
5712
    let port = r.checks.iter().find(|c| c.area == "portability").unwrap();
5713
    assert_eq!(port.health, Health::Warn);
5714
    assert!(
5715
        port.message.contains("differ only in case") && port.message.contains("aux.c"),
5716
        "{}",
5717
        port.message
5718
    );
5719
    let mac = Repo::open(root).unwrap().with_platform(Platform::macos());
5720
    let rep = mac.checkout(&[h], true, "oxy checkout").unwrap();
5721
    assert!(
5722
        rep.notes
5723
            .iter()
5724
            .any(|n| n.contains("README.md and readme.md")),
5725
        "{:?}",
5726
        rep.notes
5727
    );
5728
    assert!(
5729
        !rep.notes.iter().any(|n| n.contains("aux.c")),
5730
        "macOS allows aux.c"
5731
    );
5732
}
5733
5734
#[test]
5735
fn history_and_blame_of_a_loaded_state_match_the_full_walk() {
5736
    hermetic();
5737
    let dir = tempfile::tempdir().unwrap();
5738
    let repo = Repo::init(dir.path()).unwrap();
5739
    write(dir.path(), "a.txt", b"one\n");
5740
    write(dir.path(), "other.txt", b"x\n");
5741
    write(dir.path(), "bin.dat", &[0u8, 1, 2, 0, 255]);
5742
    repo.snapshot("t").unwrap();
5743
    let c1 = repo.commit("first", &[]).unwrap();
5744
    write(dir.path(), "other.txt", b"y\n");
5745
    repo.snapshot("t").unwrap();
5746
    repo.commit("other only", &[]).unwrap();
5747
    write(dir.path(), "a.txt", b"one\ntwo\n");
5748
    repo.snapshot("t").unwrap();
5749
    let c3 = repo.commit("second line", &[]).unwrap();
5750
    write(dir.path(), "other.txt", b"z\n");
5751
    repo.snapshot("t").unwrap();
5752
    repo.commit("other again", &[]).unwrap();
5753
5754
    let heads = repo.bookmark_heads().unwrap();
5755
    let state = repo.load_state(&heads).unwrap();
5756
    let full: Vec<ChangeHash> = repo
5757
        .log_for_path_in("a.txt", &heads)
5758
        .unwrap()
5759
        .iter()
5760
        .map(|e| e.hash)
5761
        .collect();
5762
    assert_eq!(
5763
        full,
5764
        vec![c3, c1],
5765
        "newest first, only changes touching the path"
5766
    );
5767
    let newest: Vec<ChangeHash> = repo
5768
        .log_for_path_of(&state, "a.txt", Some(1))
5769
        .unwrap()
5770
        .iter()
5771
        .map(|e| e.hash)
5772
        .collect();
5773
    assert_eq!(newest, vec![c3], "stops at the first");
5774
    assert_eq!(
5775
        repo.log_for_path_of(&state, "a.txt", None).unwrap().len(),
5776
        2
5777
    );
5778
    assert!(repo
5779
        .log_for_path_of(&state, "missing.txt", Some(1))
5780
        .is_err());
5781
    assert_eq!(
5782
        repo.log_state(&heads).unwrap().len(),
5783
        repo.log_of(&state).len()
5784
    );
5785
5786
    let tree = state.tree().view();
5787
    let via_state = repo.blame_of(&state, &tree, "a.txt").unwrap();
5788
    let via_heads = repo.blame_in("a.txt", &heads).unwrap();
5789
    assert_eq!(
5790
        via_state
5791
            .iter()
5792
            .map(|l| (l.hash, l.text.clone()))
5793
            .collect::<Vec<_>>(),
5794
        via_heads
5795
            .iter()
5796
            .map(|l| (l.hash, l.text.clone()))
5797
            .collect::<Vec<_>>()
5798
    );
5799
    assert_eq!(
5800
        via_state.iter().map(|l| l.hash).collect::<Vec<_>>(),
5801
        vec![c1, c3]
5802
    );
5803
    assert!(repo.blame_of(&state, &tree, "missing.txt").is_err());
5804
}
5805
5806
/// A text file whose stat matches the manifest and whose recorded hash is
5807
/// the base's content is taken from the base without reading it; anything
5808
/// else is read, so no edit is missed (spec §12.3).
5809
#[cfg(unix)]
5810
#[test]
5811
fn stat_cache_takes_unchanged_text_from_the_base_and_misses_no_edit() {
5812
    use std::os::unix::fs::PermissionsExt;
5813
    hermetic();
5814
    let dir = tempfile::tempdir().unwrap();
5815
    let root = dir.path();
5816
    let repo = Repo::init(root).unwrap().with_home(root.join("home"));
5817
    write(root, "a.txt", b"one\ntwo\n");
5818
    write(root, "b.txt", b"bee\n");
5819
    repo.commit("base", &[]).unwrap();
5820
    let age = |p: &str| {
5821
        let old = std::time::SystemTime::now() - std::time::Duration::from_secs(30);
5822
        fs::File::options()
5823
            .write(true)
5824
            .open(root.join(p))
5825
            .unwrap()
5826
            .set_modified(old)
5827
            .unwrap();
5828
    };
5829
    age("a.txt");
5830
    age("b.txt");
5831
    assert!(
5832
        !repo.snapshot("status").unwrap().changed,
5833
        "records the aged stat"
5834
    );
5835
5836
    // Clean and equal to the base: not read at all.
5837
    fs::set_permissions(root.join("a.txt"), fs::Permissions::from_mode(0o000)).unwrap();
5838
    let snap = repo.snapshot("status").unwrap();
5839
    assert!(
5840
        !snap.changed && snap.statuses.is_empty(),
5841
        "{:?}",
5842
        snap.statuses
5843
    );
5844
    fs::set_permissions(root.join("a.txt"), fs::Permissions::from_mode(0o644)).unwrap();
5845
5846
    // An uncommitted edit that is older than the manifest: stat-clean, but
5847
    // its hash is not the base's, so it is read and stays visible.
5848
    write(root, "b.txt", b"bee edited\n");
5849
    age("b.txt");
5850
    let first = repo.snapshot("status").unwrap();
5851
    assert_eq!(
5852
        statuses(&first),
5853
        vec![("b.txt".to_string(), ChangeStatus::Modified)]
5854
    );
5855
    let again = repo.snapshot("status").unwrap();
5856
    assert_eq!(
5857
        statuses(&again),
5858
        vec![("b.txt".to_string(), ChangeStatus::Modified)],
5859
        "still seen once stat-clean"
5860
    );
5861
    assert!(!again.changed, "and the working copy hashes the same");
5862
    fs::set_permissions(root.join("b.txt"), fs::Permissions::from_mode(0o000)).unwrap();
5863
    assert!(
5864
        repo.snapshot("status").is_err(),
5865
        "an edited file must be read, never taken from the base"
5866
    );
5867
    fs::set_permissions(root.join("b.txt"), fs::Permissions::from_mode(0o644)).unwrap();
5868
5869
    // A same-size edit made just now is racy and read.
5870
    write(root, "a.txt", b"one\nTWO\n");
5871
    assert_eq!(
5872
        statuses(&repo.snapshot("status").unwrap()),
5873
        vec![
5874
            ("a.txt".to_string(), ChangeStatus::Modified),
5875
            ("b.txt".to_string(), ChangeStatus::Modified)
5876
        ]
5877
    );
5878
    // Committing makes the edits the base: both are clean and served from it again.
5879
    repo.commit("edits", &[]).unwrap();
5880
    age("a.txt");
5881
    age("b.txt");
5882
    assert!(repo.snapshot("status").unwrap().statuses.is_empty());
5883
    fs::set_permissions(root.join("a.txt"), fs::Permissions::from_mode(0o000)).unwrap();
5884
    fs::set_permissions(root.join("b.txt"), fs::Permissions::from_mode(0o000)).unwrap();
5885
    let snap = repo.snapshot("status").unwrap();
5886
    assert!(!snap.changed && snap.statuses.is_empty());
5887
    fs::set_permissions(root.join("a.txt"), fs::Permissions::from_mode(0o644)).unwrap();
5888
    fs::set_permissions(root.join("b.txt"), fs::Permissions::from_mode(0o644)).unwrap();
5889
}
5890
5891
/// Version 2 checkpoints (spec §11): a large file's graph is a blob of its
5892
/// own, kept by gc, checked by fsck, shared by the next checkpoint when the
5893
/// file is unchanged, and loading through the checkpoint equals a full load.
5894
#[test]
5895
fn checkpoints_keep_large_graphs_as_blobs_of_their_own() {
5896
    hermetic();
5897
    let dir = tempfile::tempdir().unwrap();
5898
    let root = dir.path();
5899
    let repo = Repo::init(root).unwrap().with_home(root.join("home"));
5900
    let long: String = (0..300)
5901
        .map(|i| format!("line {i} of a long file\n"))
5902
        .collect();
5903
    write(root, "long.txt", long.as_bytes());
5904
    write(root, "short.txt", b"short\n");
5905
    repo.commit("base", &[]).unwrap();
5906
    let (r1, _, _) = repo.checkpoint().unwrap();
5907
    let cp1 = crate::objects::Checkpoint::decode(
5908
        &repo.store().get_typed(&r1, ObjectType::Checkpoint).unwrap(),
5909
    )
5910
    .unwrap();
5911
    let graphs1 = repo.checkpoint_graph_blobs(&cp1).unwrap();
5912
    assert_eq!(graphs1.len(), 1, "only the long file's graph is a blob");
5913
5914
    // gc keeps the graph blob; fsck finds the checkpoint sound.
5915
    repo.gc(true).unwrap();
5916
    assert!(repo.store().has(&graphs1[0]));
5917
    let report = repo.fsck().unwrap();
5918
    assert_eq!(report.errors(), 0, "{:?}", report.problems);
5919
5920
    // Loading through the checkpoint equals a full load.
5921
    write(root, "short.txt", b"short, edited\n");
5922
    repo.commit("edit the short file", &[]).unwrap();
5923
    let heads = repo.bookmark_heads().unwrap();
5924
    let fast = repo.load_state(&heads).unwrap();
5925
    let full = repo.load_state_full(&heads).unwrap();
5926
    assert_eq!(fast.checkpoint_payload(), full.checkpoint_payload());
5927
5928
    // The next checkpoint shares the unchanged long file's graph.
5929
    let (r2, _, _) = repo.checkpoint().unwrap();
5930
    let cp2 = crate::objects::Checkpoint::decode(
5931
        &repo.store().get_typed(&r2, ObjectType::Checkpoint).unwrap(),
5932
    )
5933
    .unwrap();
5934
    assert_eq!(repo.checkpoint_graph_blobs(&cp2).unwrap(), graphs1);
5935
5936
    // A shallow clone's bundle carries the graph blob with the checkpoint.
5937
    let bundle = repo.checkpoint_bundle_for(&heads).unwrap();
5938
    assert!(bundle.objects.iter().any(|(t, body)| *t == ObjectType::Blob
5939
        && crate::hash::hash_object(ObjectType::Blob, body) == graphs1[0]));
5940
5941
    // A version 1 checkpoint written by an older oxy still loads.
5942
    let state = repo.load_state_full(&heads).unwrap();
5943
    let old = repo.store_blob(&state.checkpoint_payload()).unwrap();
5944
    let cp_old = crate::objects::Checkpoint {
5945
        heads: cp2.heads.clone(),
5946
        count: cp2.count,
5947
        payload: old,
5948
    };
5949
    let r_old = repo
5950
        .store()
5951
        .put(ObjectType::Checkpoint, &cp_old.encode())
5952
        .unwrap();
5953
    repo.install_checkpoint("main", &r_old).unwrap();
5954
    assert_eq!(
5955
        repo.load_state(&heads).unwrap().checkpoint_payload(),
5956
        full.checkpoint_payload()
5957
    );
5958
    assert_eq!(repo.fsck().unwrap().errors(), 0);
5959
5960
    // A lost graph blob fails the load loudly rather than dropping the
5961
    // file, and fsck reports it (a fresh repository, objects still loose).
5962
    let dir2 = tempfile::tempdir().unwrap();
5963
    let root2 = dir2.path();
5964
    let repo2 = Repo::init(root2).unwrap().with_home(root2.join("home"));
5965
    write(root2, "long.txt", long.as_bytes());
5966
    repo2.commit("base", &[]).unwrap();
5967
    let (r, _, _) = repo2.checkpoint().unwrap();
5968
    let cp = crate::objects::Checkpoint::decode(
5969
        &repo2.store().get_typed(&r, ObjectType::Checkpoint).unwrap(),
5970
    )
5971
    .unwrap();
5972
    let graph = repo2.checkpoint_graph_blobs(&cp).unwrap()[0];
5973
    repo2.store().remove_loose_for_test(&graph).unwrap();
5974
    assert!(repo2.load_state(&repo2.bookmark_heads().unwrap()).is_err());
5975
    assert!(repo2.fsck().unwrap().errors() > 0, "fsck reports it");
5976
}
5977
5978
/// A new repository has not stored the user's identity yet (that happens
5979
/// at the first signed change); looking it up falls back to the key
5980
/// directory, and a file there that does not hash to the key is refused.
5981
#[test]
5982
fn identity_is_found_in_the_key_directory_for_a_new_repository() {
5983
    hermetic();
5984
    let dir = tempfile::tempdir().unwrap();
5985
    let home = dir.path().join("home");
5986
    let mut first = Repo::init(&dir.path().join("a"))
5987
        .unwrap()
5988
        .with_home(home.clone());
5989
    let (key, _) = first
5990
        .create_identity("Ada", "[email protected]", IdentityScope::User)
5991
        .unwrap();
5992
    let fresh = Repo::init(&dir.path().join("b"))
5993
        .unwrap()
5994
        .with_home(home.clone());
5995
    assert!(!fresh.store().has(&key), "nothing stored yet");
5996
    let id = fresh.identity(&key).unwrap();
5997
    assert_eq!((id.name.as_str(), id.hash()), ("Ada", key));
5998
    // A key file that is not this identity is an error, not a wrong answer.
5999
    let keys = fresh.keys_dir.clone();
6000
    let (other, _) = first
6001
        .create_identity("Bob", "[email protected]", IdentityScope::User)
6002
        .unwrap();
6003
    fs::copy(
6004
        keys.join(format!("{}.identity", other.to_hex())),
6005
        keys.join(format!("{}.identity", key.to_hex())),
6006
    )
6007
    .unwrap();
6008
    assert!(fresh
6009
        .identity(&key)
6010
        .unwrap_err()
6011
        .to_string()
6012
        .contains("does not hold identity"));
6013
}
6014
6015
/// Status snapshots (spec §12.3): a text file whose stat matches the
6016
/// manifest, and whose base graph key is the one the manifest recorded it
6017
/// equal to, is neither read nor rendered; any edit, and any change to the
6018
/// file's graph in the base, brings it back.
6019
#[cfg(unix)]
6020
#[test]
6021
fn status_snapshots_skip_files_unchanged_since_the_manifest() {
6022
    use std::os::unix::fs::PermissionsExt;
6023
    hermetic();
6024
    let dir = tempfile::tempdir().unwrap();
6025
    let root = dir.path();
6026
    let repo = Repo::init(root).unwrap().with_home(root.join("home"));
6027
    for (p, c) in [("a.txt", "one\n"), ("b.txt", "bee\n"), ("d/c.txt", "sea\n")] {
6028
        write(root, p, c.as_bytes());
6029
    }
6030
    repo.commit("base", &[]).unwrap();
6031
    let age = |p: &str| {
6032
        let old = std::time::SystemTime::now() - std::time::Duration::from_secs(30);
6033
        fs::File::options()
6034
            .write(true)
6035
            .open(root.join(p))
6036
            .unwrap()
6037
            .set_modified(old)
6038
            .unwrap();
6039
    };
6040
    let lock = |p: &str, mode: u32| {
6041
        fs::set_permissions(root.join(p), fs::Permissions::from_mode(mode)).unwrap()
6042
    };
6043
    for p in ["a.txt", "b.txt", "d/c.txt"] {
6044
        age(p);
6045
    }
6046
    assert!(repo.snapshot("status").unwrap().statuses.is_empty());
6047
    let (_, _, m) = repo.read_manifest().unwrap().unwrap();
6048
    assert!(
6049
        m.entries.values().all(|e| e.graph.is_some()),
6050
        "keys recorded"
6051
    );
6052
6053
    // Unreadable files prove they are not read; the status snapshot does
6054
    // not render them either, and its base lacks their graphs.
6055
    lock("a.txt", 0o000);
6056
    lock("b.txt", 0o000);
6057
    let snap = repo.snapshot_status("status").unwrap();
6058
    assert!(!snap.changed && snap.statuses.is_empty());
6059
    assert_eq!(
6060
        snap.base_snapshot
6061
            .unrendered
6062
            .iter()
6063
            .cloned()
6064
            .collect::<Vec<_>>(),
6065
        vec!["a.txt", "b.txt", "d/c.txt"]
6066
    );
6067
    assert!(!snap.base.is_full());
6068
    assert!(!snap.base_snapshot.is_conflicted());
6069
    // A full snapshot does not read them either, but renders everything.
6070
    let full = repo.snapshot("status").unwrap();
6071
    assert!(full.statuses.is_empty() && full.base.is_full());
6072
    assert!(full.base_snapshot.unrendered.is_empty());
6073
    assert!(matches!(&full.base_snapshot.files["a.txt"].content,
6074
        FileContent::Text { bytes, .. } if bytes == b"one\n"));
6075
6076
    // An edit is seen; the file is rendered, the others still are not.
6077
    write(root, "d/c.txt", b"sea edited\n");
6078
    let snap = repo.snapshot_status("status").unwrap();
6079
    assert_eq!(
6080
        statuses(&snap),
6081
        vec![("d/c.txt".to_string(), ChangeStatus::Modified)]
6082
    );
6083
    assert!(!snap.base_snapshot.unrendered.contains("d/c.txt"));
6084
    // So is a mode change of an unread file.
6085
    lock("b.txt", 0o100);
6086
    assert_eq!(
6087
        statuses(&repo.snapshot_status("status").unwrap()),
6088
        vec![
6089
            ("b.txt".to_string(), ChangeStatus::ModeChanged),
6090
            ("d/c.txt".to_string(), ChangeStatus::Modified)
6091
        ]
6092
    );
6093
    lock("b.txt", 0o000);
6094
6095
    // Committing c.txt changes its graph in the base, not a.txt's: a.txt
6096
    // stays unread, c.txt is read once and then skipped too.
6097
    repo.commit_selection("edit c", &[], &Selection::Paths(vec!["d/c.txt".into()]))
6098
        .unwrap();
6099
    age("d/c.txt");
6100
    let snap = repo.snapshot_status("status").unwrap();
6101
    assert!(snap.statuses.is_empty(), "{:?}", snap.statuses);
6102
    assert!(snap.base_snapshot.unrendered.contains("a.txt"));
6103
    lock("d/c.txt", 0o000);
6104
    let snap = repo.snapshot_status("status").unwrap();
6105
    assert!(snap.statuses.is_empty());
6106
    assert!(snap.base_snapshot.unrendered.contains("d/c.txt"));
6107
    for p in ["a.txt", "b.txt", "d/c.txt"] {
6108
        lock(p, 0o644);
6109
    }
6110
}
6111
6112
/// Attributes decide how a file compares with the base, so a changed
6113
/// `.oxyattributes` makes every text file be compared again.
6114
#[cfg(unix)]
6115
#[test]
6116
fn a_changed_attributes_file_disables_skipping_unchanged_files() {
6117
    hermetic();
6118
    let dir = tempfile::tempdir().unwrap();
6119
    let root = dir.path();
6120
    let repo = Repo::init(root).unwrap().with_home(root.join("home"));
6121
    write(root, "a.txt", b"crlf\r\n");
6122
    repo.commit("base", &[]).unwrap();
6123
    let old = std::time::SystemTime::now() - std::time::Duration::from_secs(30);
6124
    fs::File::options()
6125
        .write(true)
6126
        .open(root.join("a.txt"))
6127
        .unwrap()
6128
        .set_modified(old)
6129
        .unwrap();
6130
    assert!(repo.snapshot_status("status").unwrap().statuses.is_empty());
6131
    assert!(repo
6132
        .snapshot_status("status")
6133
        .unwrap()
6134
        .base_snapshot
6135
        .unrendered
6136
        .contains("a.txt"));
6137
    // With eol=lf, a.txt as stored no longer equals the base.
6138
    write(root, ".oxyattributes", b"*.txt eol=lf\n");
6139
    let snap = repo.snapshot_status("status").unwrap();
6140
    assert_eq!(
6141
        statuses(&snap),
6142
        vec![
6143
            (".oxyattributes".to_string(), ChangeStatus::Added),
6144
            ("a.txt".to_string(), ChangeStatus::Modified)
6145
        ]
6146
    );
6147
}
6148
6149
/// Bookmarks with `/` in their names: pushing records their
6150
/// attestations, and checkpoints are kept for them, beside `feature`
6151
/// itself.
6152
#[test]
6153
fn bookmarks_with_slashes_push_and_checkpoint() {
6154
    hermetic();
6155
    let dir = tempfile::tempdir().unwrap();
6156
    let root = dir.path();
6157
    let origin = Repo::init(&root.join("origin")).unwrap();
6158
    let url = root.join("origin").to_string_lossy().to_string();
6159
    let mut repo = Repo::clone(&url, &root.join("r"))
6160
        .unwrap()
6161
        .with_home(root.join("home"));
6162
    // With an identity, pushes carry reference attestations: the case
6163
    // that failed, since the attestation is a file named after the bookmark.
6164
    repo.create_identity("Ada", "[email protected]", IdentityScope::Repo)
6165
        .unwrap();
6166
    let r = root.join("r");
6167
    write(&r, "a.txt", b"a\n");
6168
    let h_a = repo.commit("a", &[]).unwrap();
6169
    assert!(repo.push("origin", false).unwrap()[0].ok);
6170
    origin.refresh().unwrap();
6171
    repo.bookmark_create("feature", None).unwrap();
6172
    repo.bookmark_create("feature/x", None).unwrap();
6173
    repo.bookmark_switch("feature/x", false).unwrap();
6174
    write(&r, "b.txt", b"b\n");
6175
    let h_b = repo.commit("b", &[]).unwrap();
6176
    for name in ["feature", "feature/x"] {
6177
        let res = repo.push_bookmark("origin", name, false).unwrap();
6178
        origin.refresh().unwrap();
6179
        assert!(res[0].ok, "{name}: {res:?}");
6180
    }
6181
    assert_eq!(origin.resolve_heads("feature").unwrap(), vec![h_a]);
6182
    assert_eq!(
6183
        origin.resolve_heads("feature/x").unwrap(),
6184
        repo.resolve_heads("feature/x").unwrap()
6185
    );
6186
    assert!(origin.resolve_heads("feature/x").unwrap().contains(&h_b));
6187
    assert!(origin.latest_ref_attest("feature/x").unwrap().is_some());
6188
    assert!(origin.latest_ref_attest("feature").unwrap().is_some());
6189
6190
    // A checkpoint of feature/x is found again when loading its state.
6191
    let (cp, _, _) = repo.checkpoint().unwrap();
6192
    assert_eq!(repo.latest_checkpoint("feature/x").unwrap().unwrap().0, cp);
6193
    assert!(repo.latest_checkpoint("feature").unwrap().is_none());
6194
    let heads = repo.resolve_heads("feature/x").unwrap();
6195
    assert!(repo.load_state_checkpointed(&heads).unwrap().is_some());
6196
}
6197
6198
/// Deleting a bookmark on a remote (spec §16.4): attested like any update,
6199
/// never the remote's own bookmark, and a bookmark created again later is
6200
/// accepted although the deletion's attestation stays the latest.
6201
#[test]
6202
fn bookmarks_are_deleted_on_a_remote() {
6203
    hermetic();
6204
    let dir = tempfile::tempdir().unwrap();
6205
    let root = dir.path();
6206
    let origin = Repo::init(&root.join("origin")).unwrap();
6207
    let url = root.join("origin").to_string_lossy().to_string();
6208
    let mut repo = Repo::clone(&url, &root.join("r"))
6209
        .unwrap()
6210
        .with_home(root.join("home"));
6211
    repo.create_identity("Ada", "[email protected]", IdentityScope::Repo)
6212
        .unwrap();
6213
    let r = root.join("r");
6214
    write(&r, "a.txt", b"a\n");
6215
    repo.commit("a", &[]).unwrap();
6216
    assert!(repo.push("origin", false).unwrap()[0].ok);
6217
    origin.refresh().unwrap();
6218
    repo.bookmark_create("feature/x", None).unwrap();
6219
    assert!(repo.push_bookmark("origin", "feature/x", false).unwrap()[0].ok);
6220
    origin.refresh().unwrap();
6221
    assert!(origin.resolve_heads("feature/x").is_ok());
6222
6223
    let res = repo.push_delete("origin", "feature/x").unwrap();
6224
    origin.refresh().unwrap();
6225
    assert!(res[0].ok, "{res:?}");
6226
    assert!(!origin.view().unwrap().bookmarks.contains_key("feature/x"));
6227
    let (_, att) = origin.latest_ref_attest("feature/x").unwrap().unwrap();
6228
    assert!(
6229
        matches!(att.attest.body, AttestBody::Ref { new_state, .. } if new_state.is_zero()),
6230
        "the deletion is attested"
6231
    );
6232
    assert!(
6233
        repo.view().unwrap().bookmarks.contains_key("feature/x"),
6234
        "the local bookmark stays"
6235
    );
6236
    assert!(!repo
6237
        .view()
6238
        .unwrap()
6239
        .remotes
6240
        .get("origin")
6241
        .is_some_and(|m| m.contains_key("feature/x")));
6242
6243
    // Pushing it again creates it again, past the deletion's serial.
6244
    let res = repo.push_bookmark("origin", "feature/x", false).unwrap();
6245
    origin.refresh().unwrap();
6246
    assert!(res[0].ok, "{res:?}");
6247
    assert!(origin.view().unwrap().bookmarks.contains_key("feature/x"));
6248
6249
    // Nothing to delete, and never the remote's own bookmark.
6250
    assert!(repo.push_delete("origin", "nope").is_err());
6251
    let res = repo.push_delete("origin", "main").unwrap();
6252
    origin.refresh().unwrap();
6253
    assert!(
6254
        !res[0].ok && res[0].reason.contains("default bookmark"),
6255
        "{res:?}"
6256
    );
6257
    assert!(origin.view().unwrap().bookmarks.contains_key("main"));
6258
}
6259
6260
/// `bookmark switch --carry` (spec §10.1): uncommitted work goes along
6261
/// when the target has the same versions of the files it touches, and is
6262
/// refused, untouched, when it has others.
6263
#[test]
6264
fn switching_bookmarks_carries_uncommitted_work() {
6265
    hermetic();
6266
    let dir = tempfile::tempdir().unwrap();
6267
    let root = dir.path();
6268
    let mut repo = Repo::init(root).unwrap().with_home(root.join("home"));
6269
    write(root, "a.txt", b"a\n");
6270
    write(root, "b.txt", b"b\n");
6271
    write(root, "gone.txt", b"gone\n");
6272
    repo.commit("base", &[]).unwrap();
6273
    repo.bookmark_create("feature", None).unwrap();
6274
    // Started on main, belongs on feature: edit, add, remove.
6275
    write(root, "a.txt", b"a\nmore\n");
6276
    write(root, "new.txt", b"new\n");
6277
    fs::remove_file(root.join("gone.txt")).unwrap();
6278
    let (_, carried) = repo.bookmark_switch_carry("feature").unwrap();
6279
    assert_eq!(carried, vec!["a.txt", "gone.txt", "new.txt"]);
6280
    assert_eq!(repo.config.bookmark, "feature");
6281
    assert_eq!(fs::read(root.join("a.txt")).unwrap(), b"a\nmore\n");
6282
    assert_eq!(fs::read(root.join("new.txt")).unwrap(), b"new\n");
6283
    assert!(!root.join("gone.txt").exists());
6284
    let snap = repo.snapshot("status").unwrap();
6285
    assert_eq!(
6286
        statuses(&snap),
6287
        vec![
6288
            ("a.txt".to_string(), ChangeStatus::Modified),
6289
            ("gone.txt".to_string(), ChangeStatus::Removed),
6290
            ("new.txt".to_string(), ChangeStatus::Added)
6291
        ]
6292
    );
6293
    repo.commit("the work", &[]).unwrap();
6294
    assert!(repo.resolve_heads("main").unwrap().len() == 1);
6295
6296
    // main moves b.txt on; work on feature touching b.txt cannot follow.
6297
    repo.bookmark_switch("main", false).unwrap();
6298
    write(root, "b.txt", b"b on main\n");
6299
    repo.commit("b on main", &[]).unwrap();
6300
    repo.bookmark_switch("feature", false).unwrap();
6301
    write(root, "b.txt", b"b edited\n");
6302
    let err = repo.bookmark_switch_carry("main").unwrap_err().to_string();
6303
    assert!(err.contains("b.txt") && err.contains("--discard"), "{err}");
6304
    assert_eq!(repo.config.bookmark, "feature", "nothing happened");
6305
    assert_eq!(fs::read(root.join("b.txt")).unwrap(), b"b edited\n");
6306
}
6307
6308
/// Merging and checking out (feedback 3): a working copy without changes
6309
/// follows a merge whichever state it sat on; a refused checkout names
6310
/// what is in the way; `checkout --carry` takes the work along.
6311
#[test]
6312
fn merges_move_clean_working_copies_and_checkouts_say_what_blocks_them() {
6313
    hermetic();
6314
    let dir = tempfile::tempdir().unwrap();
6315
    let root = dir.path();
6316
    let mut repo = Repo::init(root).unwrap().with_home(root.join("home"));
6317
    write(root, "a.txt", b"a\n");
6318
    let h1 = repo.commit("a", &[]).unwrap();
6319
    write(root, "b.txt", b"b\n");
6320
    repo.commit("b", &[]).unwrap();
6321
    repo.bookmark_create("feature", None).unwrap();
6322
    repo.bookmark_switch("feature", false).unwrap();
6323
    write(root, "c.txt", b"c\n");
6324
    repo.commit("c on feature", &[]).unwrap();
6325
    repo.bookmark_switch("main", false).unwrap();
6326
    // The working copy sits on an older state than main's heads.
6327
    repo.checkout(&[h1], false, "checkout").unwrap();
6328
    assert!(!root.join("b.txt").exists());
6329
    let m = repo.merge("feature").unwrap();
6330
    assert!(m.checked_out, "a clean working copy follows the merge");
6331
    for f in ["a.txt", "b.txt", "c.txt"] {
6332
        assert!(root.join(f).exists(), "{f}");
6333
    }
6334
6335
    // A refusal says which paths are in the way and what to do.
6336
    fs::remove_file(root.join("b.txt")).unwrap();
6337
    write(root, "a.txt", b"a edited\n");
6338
    let err = repo
6339
        .checkout(&[h1], false, "checkout")
6340
        .unwrap_err()
6341
        .to_string();
6342
    assert!(
6343
        err.contains("modified a.txt") && err.contains("removed b.txt") && err.contains("--carry"),
6344
        "{err}"
6345
    );
6346
    // --carry takes them along: h1 has a.txt as the base has it, and the
6347
    // removed b.txt is already as h1 has it (none), so that is no conflict
6348
    // either (oxygen#100).
6349
    let (_, carried) = repo
6350
        .checkout_carry(&[h1], "the first change", "checkout")
6351
        .unwrap();
6352
    assert_eq!(carried, vec!["a.txt"]);
6353
    assert_eq!(fs::read(root.join("a.txt")).unwrap(), b"a edited\n");
6354
    assert!(!root.join("b.txt").exists(), "h1 has no b.txt");
6355
}
6356
6357
/// Doctor and subrepos before the first commit (feedback 5 and 8): a
6358
/// user identity not stored in a new repository yet is fine while its
6359
/// secret key is there; an added subrepo is listed as not committed yet.
6360
#[test]
6361
fn a_new_repository_is_healthy_before_its_first_commit() {
6362
    hermetic();
6363
    let dir = tempfile::tempdir().unwrap();
6364
    let root = dir.path();
6365
    let home = root.join("home");
6366
    let mut first = Repo::init(&root.join("first"))
6367
        .unwrap()
6368
        .with_home(home.clone());
6369
    let (key, _) = first
6370
        .create_identity("Ada", "[email protected]", IdentityScope::User)
6371
        .unwrap();
6372
    let repo = Repo::init(&root.join("second"))
6373
        .unwrap()
6374
        .with_home(home.clone());
6375
    // Only the secret key: no identity object anywhere this repository sees.
6376
    let keys = repo.keys_dir.clone();
6377
    let _ = fs::remove_file(keys.join(format!("{}.identity", key.to_hex())));
6378
    assert!(keys.join(format!("{}.secret", key.to_hex())).is_file());
6379
    let r = repo.doctor(true);
6380
    let id = r.checks.iter().find(|c| c.area == "identity").unwrap();
6381
    assert_eq!(id.health, Health::Ok, "{}", id.message);
6382
    assert!(id.message.contains("first signed change"), "{}", id.message);
6383
6384
    // A subrepo added and not committed yet is listed, pinned where it is.
6385
    let lib = root.join("lib");
6386
    let l = Repo::init(&lib).unwrap().with_home(home.clone());
6387
    write(&lib, "x.txt", b"x\n");
6388
    l.commit("x", &[]).unwrap();
6389
    let second = root.join("second");
6390
    write(&second, "a.txt", b"a\n");
6391
    repo.submodule_add(&lib.to_string_lossy(), "deps/lib", None)
6392
        .unwrap();
6393
    let subs = repo.subrepos().unwrap();
6394
    assert_eq!(subs.len(), 1);
6395
    assert_eq!(
6396
        (subs[0].path.as_str(), subs[0].committed),
6397
        ("deps/lib", false)
6398
    );
6399
    assert_eq!(subs[0].actual.as_ref(), Some(&subs[0].pin));
6400
    repo.commit("add lib", &[]).unwrap();
6401
    let subs = repo.subrepos().unwrap();
6402
    assert!(subs[0].committed, "committed now");
6403
}
6404
6405
/// Commit, diff, hunks and discard use the partial snapshot: a file
6406
/// unchanged since the manifest is neither read nor rendered, and showing
6407
/// a change renders only what it edits, the same as from a full base.
6408
#[cfg(unix)]
6409
#[test]
6410
fn commits_and_diffs_leave_unchanged_files_alone() {
6411
    use std::os::unix::fs::PermissionsExt;
6412
    hermetic();
6413
    let dir = tempfile::tempdir().unwrap();
6414
    let root = dir.path();
6415
    let repo = Repo::init(root).unwrap().with_home(root.join("home"));
6416
    write(root, "big.txt", b"lots\nof\nlines\n");
6417
    write(root, "a.txt", b"one\ntwo\n");
6418
    repo.commit("base", &[]).unwrap();
6419
    let old = std::time::SystemTime::now() - std::time::Duration::from_secs(30);
6420
    for f in ["big.txt", "a.txt"] {
6421
        fs::File::options()
6422
            .write(true)
6423
            .open(root.join(f))
6424
            .unwrap()
6425
            .set_modified(old)
6426
            .unwrap();
6427
    }
6428
    assert!(repo.snapshot_status("status").unwrap().statuses.is_empty());
6429
    // big.txt cannot be read at all from here on.
6430
    fs::set_permissions(root.join("big.txt"), fs::Permissions::from_mode(0o000)).unwrap();
6431
6432
    write(root, "a.txt", b"one\nTWO\nthree\n");
6433
    let diff = repo.diff_files(None).unwrap();
6434
    assert_eq!(
6435
        diff.iter().map(|f| f.path.as_str()).collect::<Vec<_>>(),
6436
        ["a.txt"]
6437
    );
6438
    let (_, hunks) = repo.hunks().unwrap();
6439
    assert!(!hunks.is_empty() && hunks.iter().all(|h| h.path == "a.txt"));
6440
    let h = repo.commit("edit a", &[]).unwrap();
6441
6442
    // Showing the change needs only a.txt's graph, and renders as a full base does.
6443
    let c = repo.store().get_change(&h).unwrap();
6444
    let full = repo.load_state(&c.deps).unwrap();
6445
    let want = render_change(&c, &full, &full.materialize());
6446
    assert_eq!(repo.describe_change(&h).unwrap(), want);
6447
    let (base, snap) = repo.change_base(&c).unwrap();
6448
    assert!(!base.is_full() && snap.unrendered.contains("big.txt"));
6449
6450
    // Discarding works the same way.
6451
    write(root, "a.txt", b"scratch\n");
6452
    assert_eq!(repo.discard(&["a.txt".into()]).unwrap(), 1);
6453
    assert_eq!(fs::read(root.join("a.txt")).unwrap(), b"one\nTWO\nthree\n");
6454
    fs::set_permissions(root.join("big.txt"), fs::Permissions::from_mode(0o644)).unwrap();
6455
}
6456
6457
/// A replace conflict (spec §9.3) is settled by a change that writes one
6458
/// candidate, or new bytes, at the path when the caller names it; a plain
6459
/// snapshot of a checkout never settles it on its own.
6460
#[test]
6461
fn replace_conflicts_are_settled_when_asked() {
6462
    hermetic();
6463
    let dir = tempfile::tempdir().unwrap();
6464
    let root = dir.path();
6465
    let mut repo = Repo::init(root).unwrap().with_home(root.join("home"));
6466
    let blob = |n: u8| {
6467
        let mut v = vec![0u8; 64];
6468
        v[1] = n;
6469
        v
6470
    };
6471
    write(root, "img.bin", &blob(1));
6472
    repo.commit("add img", &[]).unwrap();
6473
    repo.bookmark_create("other", None).unwrap();
6474
    write(root, "img.bin", &blob(2));
6475
    repo.commit("img two", &[]).unwrap();
6476
    repo.bookmark_switch("other", false).unwrap();
6477
    write(root, "img.bin", &blob(3));
6478
    repo.commit("img three", &[]).unwrap();
6479
    repo.bookmark_switch("main", false).unwrap();
6480
    repo.merge("other").unwrap();
6481
    let heads = repo.bookmark_heads().unwrap();
6482
    let merged = repo.load_state(&heads).unwrap().materialize();
6483
    assert!(
6484
        matches!(&merged.files["img.bin"].content, FileContent::Opaque { blobs } if blobs.len() == 2),
6485
        "a replace conflict"
6486
    );
6487
    // A snapshot of the checkout records nothing.
6488
    assert!(repo
6489
        .snapshot("status")
6490
        .unwrap()
6491
        .statuses
6492
        .iter()
6493
        .all(|s| s.path != "img.bin"));
6494
6495
    // Keeping candidate 3 settles it.
6496
    let author = repo.author();
6497
    let edits = [FileEdit {
6498
        path: "img.bin".into(),
6499
        content: Some(blob(3)),
6500
    }];
6501
    let c = repo
6502
        .build_change(&heads, &edits, "keep three", author)
6503
        .unwrap();
6504
    assert_eq!(c.kind, ChangeKind::Resolution);
6505
    let mut st = repo.load_state(&heads).unwrap();
6506
    for d in &c.deps {
6507
        assert!(st.contains(d));
6508
    }
6509
    assert!(
6510
        heads.iter().all(|h| c.deps.contains(h)),
6511
        "depends on both contributors"
6512
    );
6513
    st.add(c).unwrap();
6514
    let after = st.materialize();
6515
    assert!(!after.is_conflicted());
6516
    assert_eq!(
6517
        after.files["img.bin"].content,
6518
        FileContent::Opaque {
6519
            blobs: vec![Repo::blob_ref(&blob(3))]
6520
        }
6521
    );
6522
6523
    // New bytes settle it too.
6524
    let edits = [FileEdit {
6525
        path: "img.bin".into(),
6526
        content: Some(blob(9)),
6527
    }];
6528
    let c = repo.build_change(&heads, &edits, "new", author).unwrap();
6529
    let mut st = repo.load_state(&heads).unwrap();
6530
    st.add(c).unwrap();
6531
    assert_eq!(
6532
        st.materialize().files["img.bin"].content,
6533
        FileContent::Opaque {
6534
            blobs: vec![Repo::blob_ref(&blob(9))]
6535
        }
6536
    );
6537
}
6538
6539
/// The history of a range of lines (spec §27): the changes that wrote
6540
/// or deleted its atoms, or deleted atoms from between them; edits outside
6541
/// the range and changes the range's lines survived are not in it.
6542
#[test]
6543
fn line_ranges_have_exact_histories() {
6544
    hermetic();
6545
    let dir = tempfile::tempdir().unwrap();
6546
    let root = dir.path();
6547
    let repo = Repo::init(root).unwrap().with_home(root.join("home"));
6548
    write(root, "f.rs", b"use x;\nfn a() {\n  one();\n  two();\n}\n");
6549
    let base = repo.commit("add f", &[]).unwrap();
6550
    write(root, "f.rs", b"use y;\nfn a() {\n  one();\n  two();\n}\n");
6551
    let outside = repo.commit("change the import", &[]).unwrap();
6552
    write(root, "f.rs", b"use y;\nfn a() {\n  ONE();\n  two();\n}\n");
6553
    let inside = repo.commit("edit a line of a", &[]).unwrap();
6554
    write(root, "f.rs", b"use y;\nfn a() {\n  ONE();\n}\n");
6555
    let deleted = repo.commit("delete a line of a", &[]).unwrap();
6556
    write(root, "f.rs", b"use y;\nfn a() {\n  ONE();\n}\nfn b() {}\n");
6557
    let after = repo.commit("add b after a", &[]).unwrap();
6558
    let heads = repo.bookmark_heads().unwrap();
6559
6560
    // Lines 2..4 are `fn a() {`, `ONE();`, `}` now.
6561
    let hist: Vec<ChangeHash> = repo
6562
        .line_history(&heads, "f.rs", 2, 4)
6563
        .unwrap()
6564
        .iter()
6565
        .map(|e| e.hash)
6566
        .collect();
6567
    for (h, what) in [
6568
        (base, "wrote it"),
6569
        (inside, "edited a line"),
6570
        (deleted, "deleted a line from inside"),
6571
    ] {
6572
        assert!(hist.contains(&h), "{what}");
6573
    }
6574
    for (h, what) in [(outside, "an edit above"), (after, "an addition below")] {
6575
        assert!(!hist.contains(&h), "{what}");
6576
    }
6577
    assert_eq!(hist[0], deleted, "newest first");
6578
    // One line: only what touched it.
6579
    let one: Vec<ChangeHash> = repo
6580
        .line_history(&heads, "f.rs", 1, 1)
6581
        .unwrap()
6582
        .iter()
6583
        .map(|e| e.hash)
6584
        .collect();
6585
    assert!(one.contains(&outside) && !one.contains(&inside));
6586
    assert!(repo.line_history(&heads, "f.rs", 3, 9).is_err());
6587
    assert!(repo.line_history(&heads, "f.rs", 0, 1).is_err());
6588
    assert!(repo.line_history(&heads, "nope.rs", 1, 1).is_err());
6589
}
6590
6591
#[test]
6592
fn receipts_are_kept_with_their_state_and_verified() {
6593
    use crate::receipt::{Receipt, SignedReceipt};
6594
    hermetic();
6595
    let dir = tempfile::tempdir().unwrap();
6596
    let root = dir.path();
6597
    let repo = Repo::init(root).unwrap().with_home(root.join("home"));
6598
    write(root, "a.txt", b"1\n");
6599
    repo.commit("A", &[]).unwrap();
6600
    let heads = repo.bookmark_heads().unwrap();
6601
    let state = repo
6602
        .store()
6603
        .put_state(&StateObject::new(heads.clone()))
6604
        .unwrap();
6605
    let out = repo.store_blob(b"built\n").unwrap();
6606
    let receipt = Receipt {
6607
        job_name: "build".into(),
6608
        pipeline_hash: ObjectRef([1; 32]),
6609
        scope_tree_hash: ObjectRef([2; 32]),
6610
        inputs: vec![],
6611
        environment: ObjectRef([3; 32]),
6612
        outputs: vec![out],
6613
        exit_code: 0,
6614
        duration_ms: 42,
6615
    };
6616
    let sk = SecretKey::generate();
6617
    let runner = sk.identity("earth-1", "runner@earth", 1);
6618
    let sr = SignedReceipt::sign(
6619
        receipt.clone(),
6620
        repo.id().unwrap(),
6621
        state,
6622
        "demo#1",
6623
        &runner,
6624
        &sk,
6625
    );
6626
6627
    let r = repo.add_receipt(&sr).unwrap();
6628
    let found = repo.receipts(&heads).unwrap();
6629
    assert_eq!(found.len(), 1);
6630
    assert_eq!(found[0].attest, r);
6631
    assert_eq!(found[0].signed, sr);
6632
    assert!(found[0].problem.is_none() && !found[0].revoked);
6633
    assert!(repo.receipts(&[ObjectRef([5; 32])]).unwrap().is_empty());
6634
6635
    // Another repository's receipt, or a forged one, is refused.
6636
    let elsewhere = SignedReceipt::sign(receipt.clone(), [0; 16], state, "x", &runner, &sk);
6637
    assert!(repo
6638
        .add_receipt(&elsewhere)
6639
        .unwrap_err()
6640
        .to_string()
6641
        .contains("another repository"));
6642
    let mut forged = sr.clone();
6643
    forged.receipt.exit_code = 1;
6644
    assert!(repo
6645
        .add_receipt(&forged)
6646
        .unwrap_err()
6647
        .to_string()
6648
        .contains("does not verify"));
6649
6650
    // A receipt signed by a short-lived key keeps its certificate and the
6651
    // issuer's identity, and reads back with them (oxygenhub#241).
6652
    let hub_sk = SecretKey::generate();
6653
    let hub = hub_sk.identity("oxygenhub.io", "[email protected]", 1);
6654
    let job_sk = SecretKey::generate();
6655
    let job = job_sk.identity("job 2 test", "[email protected]", 1);
6656
    let mut test_receipt = receipt.clone();
6657
    test_receipt.job_name = "test".into();
6658
    let plain = SignedReceipt::sign(
6659
        test_receipt,
6660
        repo.id().unwrap(),
6661
        state,
6662
        "demo#2",
6663
        &job,
6664
        &job_sk,
6665
    );
6666
    let now = plain.attest.hlc.wall_ms;
6667
    let cert = crate::cert::SignedCertificate::sign(
6668
        crate::cert::Certificate {
6669
            key: job.clone(),
6670
            issuer: hub.hash(),
6671
            subject: "repo:andy/demo:bookmark:main".into(),
6672
            claims: vec![],
6673
            scope: crate::identity::Scope::SEAL,
6674
            not_before: now - 1_000,
6675
            expires: now + 600_000,
6676
            grant: None,
6677
        },
6678
        &hub,
6679
        &hub_sk,
6680
    );
6681
    let certified = plain.with_certificate(cert, hub.clone());
6682
    repo.add_receipt(&certified).unwrap();
6683
    let found = repo.receipts(&heads).unwrap();
6684
    let got = found
6685
        .iter()
6686
        .find(|i| i.signed.receipt.job_name == "test")
6687
        .unwrap();
6688
    assert_eq!(got.signed, certified);
6689
    assert!(got.problem.is_none(), "{:?}", got.problem);
6690
6691
    // gc keeps the receipts, their runners, the certificate and its issuer,
6692
    // and the output while the state lives.
6693
    repo.gc(true).unwrap();
6694
    let found = repo.receipts(&heads).unwrap();
6695
    assert_eq!(found.len(), 2);
6696
    let got = found
6697
        .iter()
6698
        .find(|i| i.signed.receipt.job_name == "test")
6699
        .unwrap();
6700
    assert_eq!(got.signed, certified, "the certificate survives gc");
6701
    assert!(got.problem.is_none());
6702
    assert_eq!(repo.read_blob(&out).unwrap(), b"built\n");
6703
    assert!(repo.fsck().unwrap().problems.is_empty());
6704
}
6705
6706
#[test]
6707
fn approvals_are_kept_with_their_state_and_survive_gc() {
6708
    hermetic();
6709
    let dir = tempfile::tempdir().unwrap();
6710
    let root = dir.path();
6711
    let repo = Repo::init(root).unwrap().with_home(root.join("home"));
6712
    write(root, "a.txt", b"1\n");
6713
    repo.commit("A", &[]).unwrap();
6714
    let heads = repo.bookmark_heads().unwrap();
6715
    let state = repo.store().put_state(&StateObject::new(heads)).unwrap();
6716
    let plan = repo.store_blob(b"the reviewed plan\n").unwrap();
6717
    let sk = SecretKey::generate();
6718
    let andy = sk.identity("Andy", "[email protected]", 1);
6719
    let statement = crate::approval::Statement {
6720
        repo: repo.id().unwrap(),
6721
        run: "https://hub.example/andy/infra/flow/8".into(),
6722
        job: "apply".into(),
6723
        job_hash: ObjectRef([1; 32]),
6724
        state,
6725
        inputs: vec![plan],
6726
        environment: "prod".into(),
6727
        approve: true,
6728
    };
6729
    let sa = crate::approval::SignedApproval::sign(&statement, &andy, &sk);
6730
    let r = repo.add_approval(&sa).unwrap();
6731
    assert_eq!(repo.store().approvals_for(&state).unwrap(), vec![r]);
6732
    // Another repository's approval, or a changed one, is refused.
6733
    let elsewhere = crate::approval::SignedApproval::sign(
6734
        &crate::approval::Statement {
6735
            repo: [0; 16],
6736
            ..statement.clone()
6737
        },
6738
        &andy,
6739
        &sk,
6740
    );
6741
    assert!(repo
6742
        .add_approval(&elsewhere)
6743
        .unwrap_err()
6744
        .to_string()
6745
        .contains("another repository"));
6746
    let mut forged = sa.clone();
6747
    if let AttestBody::Approval { environment, .. } = &mut forged.attest.body {
6748
        *environment = "dev".into();
6749
    }
6750
    assert!(repo
6751
        .add_approval(&forged)
6752
        .unwrap_err()
6753
        .to_string()
6754
        .contains("does not verify"));
6755
    // gc keeps it, its signature and its signer while the state lives.
6756
    repo.gc(true).unwrap();
6757
    assert_eq!(repo.store().approvals_for(&state).unwrap(), vec![r]);
6758
    assert_eq!(repo.store().get_attest(&r).unwrap(), sa.attest);
6759
    assert_eq!(repo.store().signatures(&r).unwrap(), sa.sigs);
6760
    assert!(repo.fsck().unwrap().problems.is_empty());
6761
}
6762
6763
#[test]
6764
fn status_leaves_an_unchanged_manifest_alone() {
6765
    hermetic();
6766
    let dir = tempfile::tempdir().unwrap();
6767
    let root = dir.path();
6768
    let repo = Repo::init(root).unwrap().with_home(root.join("home"));
6769
    write(root, "a.txt", b"1\n");
6770
    write(root, "b.txt", b"2\n");
6771
    repo.commit("A", &[]).unwrap();
6772
    // Files last touched well outside the racy window.
6773
    let old = std::time::SystemTime::now() - std::time::Duration::from_secs(60);
6774
    for f in ["a.txt", "b.txt"] {
6775
        fs::File::options()
6776
            .write(true)
6777
            .open(root.join(f))
6778
            .unwrap()
6779
            .set_modified(old)
6780
            .unwrap();
6781
    }
6782
    repo.snapshot_status("status").unwrap();
6783
    let path = repo.manifest_path();
6784
    let first = fs::read(&path).unwrap();
6785
    repo.snapshot_status("status").unwrap();
6786
    assert_eq!(
6787
        fs::read(&path).unwrap(),
6788
        first,
6789
        "an unchanged tree does not rewrite the manifest"
6790
    );
6791
    // A change rewrites it.
6792
    write(root, "a.txt", b"1\n2\n");
6793
    repo.snapshot_status("status").unwrap();
6794
    assert_ne!(fs::read(&path).unwrap(), first);
6795
}
6796
6797
#[test]
6798
fn large_text_files_travel_and_survive_gc_as_text_blobs() {
6799
    hermetic();
6800
    let dir = tempfile::tempdir().unwrap();
6801
    let root = dir.path();
6802
    let origin_path = root.join("origin");
6803
    Repo::init(&origin_path).unwrap();
6804
    let origin_url = origin_path.to_string_lossy().to_string();
6805
    let a = Repo::clone(&origin_url, &root.join("a")).unwrap();
6806
    let big: String = (0..5000).map(|i| format!("line {i}\n")).collect();
6807
    write(&root.join("a"), "big.txt", big.as_bytes());
6808
    write(&root.join("a"), "small.txt", b"small\n");
6809
    let h1 = a.commit("large", &[]).unwrap();
6810
    let (_, body) = a.store().get(&h1).unwrap();
6811
    assert!(body.len() < 2048, "the change is {} bytes", body.len());
6812
    assert!(a.push("origin", false).unwrap()[0].ok);
6813
6814
    // A clone reads the text from the blobs that came with the change.
6815
    let b = Repo::clone(&origin_url, &root.join("b")).unwrap();
6816
    assert_eq!(fs::read(root.join("b/big.txt")).unwrap(), big.as_bytes());
6817
    // An edit in the middle of the stored insert is an ordinary change.
6818
    let edited = big.replace("line 2500\n", "line 2500, edited\n");
6819
    write(&root.join("b"), "big.txt", edited.as_bytes());
6820
    let h2 = b.commit("edit", &[]).unwrap();
6821
    assert!(b.store().get_change(&h2).unwrap().edits.len() <= 2);
6822
    assert!(b.push("origin", false).unwrap()[0].ok);
6823
    assert!(a.pull("origin").unwrap().checked_out);
6824
    assert_eq!(fs::read(root.join("a/big.txt")).unwrap(), edited.as_bytes());
6825
    assert_eq!(
6826
        a.fsck().unwrap().errors(),
6827
        0,
6828
        "{:?}",
6829
        a.fsck().unwrap().problems
6830
    );
6831
6832
    // With zero retention gc keeps the text blobs of every kept change.
6833
    let mut a = Repo::open(&root.join("a")).unwrap();
6834
    a.config.set("core.op-retention", "0").unwrap();
6835
    a.save_config().unwrap();
6836
    let a = Repo::open(&root.join("a")).unwrap();
6837
    a.gc(true).unwrap();
6838
    let a = Repo::open(&root.join("a")).unwrap();
6839
    assert_eq!(a.store().get_change(&h1).unwrap().message, "large");
6840
    assert_eq!(
6841
        a.fsck().unwrap().errors(),
6842
        0,
6843
        "{:?}",
6844
        a.fsck().unwrap().problems
6845
    );
6846
    // And a clone of the packed repository reads them from its packs.
6847
    let c = Repo::clone(&root.join("a").to_string_lossy(), &root.join("c")).unwrap();
6848
    assert_eq!(fs::read(root.join("c/big.txt")).unwrap(), edited.as_bytes());
6849
    drop(c);
6850
}
6851
6852
#[test]
6853
fn operations_that_both_replace_a_working_copy_are_not_merged() {
6854
    hermetic();
6855
    let dir = tempfile::tempdir().unwrap();
6856
    let root = dir.path();
6857
    let repo = Repo::init(root).unwrap();
6858
    write(root, "a.txt", b"a\n");
6859
    let a = repo.commit("a", &[]).unwrap();
6860
    write(root, "b.txt", b"b\n");
6861
    repo.commit("b", &[]).unwrap();
6862
    let (x, op) = repo.head_op().unwrap();
6863
    let ws = *op.view.workspaces.keys().next().unwrap();
6864
    let mut one = op.view.clone();
6865
    one.workspaces.insert(ws, a);
6866
    let mut two = op.view.clone();
6867
    two.workspaces.insert(ws, ObjectRef([7; 32]));
6868
    let first = repo.record_op(&[x], "one", one).unwrap();
6869
    let e = repo.record_op(&[x], "two", two).unwrap_err();
6870
    assert!(
6871
        e.to_string()
6872
            .contains("changed this working copy at the same time"),
6873
        "{e}"
6874
    );
6875
    assert_eq!(
6876
        repo.head_op().unwrap().0,
6877
        first,
6878
        "the second is not recorded"
6879
    );
6880
}
6881
6882
/// Metalgear, 2026-09-29 (oxygen#36): a status run while a bookmark switch
6883
/// rewrote the working copy recorded the half-written files as edits, and
6884
/// its view replaced the switch's.
6885
#[test]
6886
fn a_snapshot_during_a_switch_never_records_the_switch_as_edits() {
6887
    hermetic();
6888
    let dir = tempfile::tempdir().unwrap();
6889
    let root = dir.path().to_path_buf();
6890
    let mut repo = Repo::init(&root).unwrap();
6891
    write(&root, "keep.txt", b"keep\n");
6892
    repo.commit("base", &[]).unwrap();
6893
    repo.bookmark_create("small", None).unwrap();
6894
    for i in 0..300 {
6895
        write(
6896
            &root,
6897
            &format!("many/f{i}.txt"),
6898
            format!("file {i}\n").as_bytes(),
6899
        );
6900
    }
6901
    repo.commit("many", &[]).unwrap();
6902
    let stop = std::sync::Arc::new(std::sync::atomic::AtomicBool::new(false));
6903
    let watcher = {
6904
        let (root, stop) = (root.clone(), stop.clone());
6905
        std::thread::spawn(move || {
6906
            let r = Repo::open(&root).unwrap();
6907
            let mut ran = 0;
6908
            while !stop.load(std::sync::atomic::Ordering::Relaxed) {
6909
                if r.snapshot_status("oxy status").is_ok() {
6910
                    ran += 1;
6911
                }
6912
            }
6913
            ran
6914
        })
6915
    };
6916
    for i in 0..20 {
6917
        let to = if i % 2 == 0 { "small" } else { "main" };
6918
        repo.bookmark_switch(to, false).unwrap();
6919
    }
6920
    stop.store(true, std::sync::atomic::Ordering::Relaxed);
6921
    assert!(watcher.join().unwrap() > 0, "the watcher snapshotted");
6922
    // Back on main, clean, with every file where main has it.
6923
    let repo = Repo::open(&root).unwrap();
6924
    let s = repo.snapshot_status("oxy status").unwrap();
6925
    assert!(s.statuses.is_empty(), "{:?}", statuses(&s));
6926
    assert!(s.wc.edits.is_empty() && s.wc.tree_ops.is_empty());
6927
    assert_eq!(s.wc.deps, repo.bookmark_heads().unwrap());
6928
    assert!(root.join("many/f299.txt").exists());
6929
}
6930
6931
/// Metalgear, 2026-09-29 (oxygen#38): a parent's `bookmark switch --carry`
6932
/// put a subrepo that was ahead of its pin back at the pin and moved the
6933
/// subrepo's own bookmark backwards.
6934
#[test]
6935
fn a_parent_switch_with_carry_leaves_a_subrepo_ahead_of_its_pin_alone() {
6936
    hermetic();
6937
    let dir = tempfile::tempdir().unwrap();
6938
    let root = dir.path();
6939
    Repo::init(&root.join("lib-origin")).unwrap();
6940
    let lib_url = root.join("lib-origin").to_string_lossy().to_string();
6941
    let lib = Repo::clone(&lib_url, &root.join("lib")).unwrap();
6942
    write(&root.join("lib"), "lib.txt", b"v1\n");
6943
    lib.commit("lib v1", &[]).unwrap();
6944
    assert!(lib.push("origin", false).unwrap()[0].ok);
6945
6946
    let app_dir = root.join("app");
6947
    let mut app = Repo::init(&app_dir).unwrap();
6948
    write(&app_dir, "main.txt", b"app\n");
6949
    app.submodule_add(&lib_url, "libs/lib", None).unwrap();
6950
    app.commit("app with lib", &[]).unwrap();
6951
    app.bookmark_create("feature", None).unwrap();
6952
6953
    // New work in the subrepo, not yet pinned by the parent.
6954
    let nested_dir = app_dir.join("libs/lib");
6955
    let nested = Repo::open(&nested_dir).unwrap();
6956
    write(&nested_dir, "new.txt", b"new\n");
6957
    let l2 = nested.commit("lib: new file", &[]).unwrap();
6958
    drop(nested);
6959
6960
    let (_, carried) = app.bookmark_switch_carry("feature").unwrap();
6961
    assert!(carried.contains(&"libs/lib".to_string()), "{carried:?}");
6962
    let nested = Repo::open(&nested_dir).unwrap();
6963
    assert!(
6964
        nested.bookmark_heads().unwrap().contains(&l2),
6965
        "its bookmark kept its work"
6966
    );
6967
    assert!(nested_dir.join("new.txt").exists(), "and its files");
6968
    let s = app.snapshot("status").unwrap();
6969
    assert_eq!(
6970
        statuses(&s),
6971
        vec![("libs/lib".to_string(), ChangeStatus::Modified)]
6972
    );
6973
}
6974
6975
/// oxygen#29 (metalgear, rstar-api): after a proposal landed on the hub,
6976
/// moving `main` to a change this clone had pushed on another bookmark,
6977
/// the first `pull` said "Already up to date" while `main` was behind.
6978
#[test]
6979
fn pull_takes_a_remote_move_to_changes_already_here() {
6980
    hermetic();
6981
    let dir = tempfile::tempdir().unwrap();
6982
    let root = dir.path();
6983
    let origin_path = root.join("origin");
6984
    let origin = Repo::init(&origin_path).unwrap();
6985
    let url = origin_path.to_string_lossy().to_string();
6986
    let mut b = Repo::clone(&url, &root.join("b")).unwrap();
6987
    write(&root.join("b"), "base.txt", b"base\n");
6988
    b.commit("base", &[]).unwrap();
6989
    assert!(b.push("origin", false).unwrap()[0].ok);
6990
    origin.refresh().unwrap();
6991
6992
    // A feature bookmark with one change, pushed.
6993
    b.bookmark_create("feat", None).unwrap();
6994
    b.bookmark_switch("feat", false).unwrap();
6995
    write(&root.join("b"), "x.txt", b"x\n");
6996
    let x = b.commit("x", &[]).unwrap();
6997
    assert!(b.push("origin", false).unwrap()[0].ok);
6998
    origin.refresh().unwrap();
6999
    b.bookmark_switch("main", false).unwrap();
7000
7001
    // The remote lands it: its main moves to the feature's state.
7002
    let feat = origin
7003
        .store()
7004
        .get_state(&origin.view().unwrap().bookmarks["feat"])
7005
        .unwrap()
7006
        .heads;
7007
    origin.bookmark_set("main", &feat).unwrap();
7008
7009
    let r = b.pull("origin").unwrap();
7010
    assert!(r.changed, "{r:?}");
7011
    assert!(r.heads.contains(&x) || b.load_state(&r.heads).unwrap().contains(&x));
7012
    let main = b
7013
        .bookmarks()
7014
        .unwrap()
7015
        .into_iter()
7016
        .find(|m| m.name == "main")
7017
        .unwrap();
7018
    assert_eq!(main.behind, Some(0), "{main:?}");
7019
}
7020
7021
/// oxygen#48: a remote's bookmarks are names here (`origin/NAME`); switching
7022
/// to one only the remote has makes a local bookmark from it; a pull moves
7023
/// every local bookmark the remote has too; a clone checks out the remote's
7024
/// default bookmark.
7025
#[test]
7026
fn remote_bookmarks_are_named_switched_to_pulled_and_cloned() {
7027
    hermetic();
7028
    let dir = tempfile::tempdir().unwrap();
7029
    let root = dir.path();
7030
    let origin_path = root.join("origin");
7031
    let mut origin = Repo::init(&origin_path).unwrap();
7032
    let url = origin_path.to_string_lossy().to_string();
7033
    let mut a = Repo::clone(&url, &root.join("a")).unwrap();
7034
    write(&root.join("a"), "base.txt", b"base\n");
7035
    a.commit("base", &[]).unwrap();
7036
    assert!(a.push("origin", false).unwrap()[0].ok);
7037
    a.bookmark_create("develop", None).unwrap();
7038
    a.bookmark_switch("develop", false).unwrap();
7039
    write(&root.join("a"), "base.txt", b"base\nd1\n");
7040
    let d1 = a.commit("d1", &[]).unwrap();
7041
    assert!(a.push("origin", false).unwrap()[0].ok);
7042
7043
    // A clone has main only; origin/develop is a name all the same.
7044
    let c_root = root.join("c");
7045
    let mut c = Repo::clone(&url, &c_root).unwrap();
7046
    assert_eq!(c.config.bookmark, "main");
7047
    assert!(!c.view().unwrap().bookmarks.contains_key("develop"));
7048
    assert_eq!(c.resolve_heads("origin/develop").unwrap(), vec![d1]);
7049
    assert_eq!(c.resolve_change("origin/develop").unwrap(), d1);
7050
    assert_eq!(c.remote_only_bookmarks().unwrap().len(), 1);
7051
7052
    // Switching makes the local bookmark from origin's.
7053
    c.bookmark_switch("develop", false).unwrap();
7054
    assert_eq!(c.config.bookmark, "develop");
7055
    assert_eq!(c.bookmark_heads().unwrap(), vec![d1]);
7056
    assert_eq!(fs::read(c_root.join("base.txt")).unwrap(), b"base\nd1\n");
7057
    assert!(c.remote_only_bookmarks().unwrap().is_empty());
7058
    assert!(c.bookmark_switch("nowhere", false).is_err());
7059
7060
    // Both bookmarks move on the remote; one pull takes both.
7061
    write(&root.join("a"), "base.txt", b"base\nd1\nd2\n");
7062
    let d2 = a.commit("d2", &[]).unwrap();
7063
    assert!(a.push("origin", false).unwrap()[0].ok);
7064
    a.bookmark_switch("main", false).unwrap();
7065
    write(&root.join("a"), "m.txt", b"m\n");
7066
    let m = a.commit("m", &[]).unwrap();
7067
    assert!(a.push("origin", false).unwrap()[0].ok);
7068
    let r = c.pull("origin").unwrap();
7069
    assert!(r.changed && r.checked_out, "{r:?}");
7070
    assert_eq!(r.heads, vec![d2]);
7071
    assert_eq!(r.others, vec!["main".to_string()]);
7072
    assert!(c.resolve_heads("main").unwrap().contains(&m));
7073
    assert_eq!(
7074
        fs::read(c_root.join("base.txt")).unwrap(),
7075
        b"base\nd1\nd2\n"
7076
    );
7077
    let again = c.pull("origin").unwrap();
7078
    assert!(!again.changed && again.others.is_empty(), "{again:?}");
7079
7080
    // A clone checks out the remote's default bookmark.
7081
    origin.config.set("workspace.bookmark", "develop").unwrap();
7082
    origin.save_config().unwrap();
7083
    let e = Repo::clone(&url, &root.join("e")).unwrap();
7084
    assert_eq!(e.config.bookmark, "develop");
7085
    assert_eq!(e.bookmark_heads().unwrap(), vec![d2]);
7086
    let reopened = Repo::open(&root.join("e")).unwrap();
7087
    assert_eq!(reopened.config.bookmark, "develop");
7088
    // REMOTE/NAME names the remote's bookmark to switch to.
7089
    let mut e = reopened;
7090
    e.bookmark_switch("origin/main", false).unwrap();
7091
    assert_eq!(e.config.bookmark, "main");
7092
    assert!(e.bookmark_heads().unwrap().contains(&m));
7093
}
7094
7095
/// oxygen#51, #52: --at-op reads an earlier view and refuses changes;
7096
/// op restore goes back to an operation, files included, and undo takes
7097
/// the restore back whole; op revert undoes one operation alone; each
7098
/// operation's changes are described from the views.
7099
#[test]
7100
fn operations_can_be_read_restored_and_reverted() {
7101
    hermetic();
7102
    let dir = tempfile::tempdir().unwrap();
7103
    let root = dir.path();
7104
    let repo = Repo::init(root).unwrap();
7105
    write(root, "a.txt", b"a\n");
7106
    let first = repo.commit("first", &[]).unwrap();
7107
    write(root, "a.txt", b"a\nb\n");
7108
    let second = repo.commit("second", &[]).unwrap();
7109
    let at_second = repo.head_op().unwrap().0.to_hex();
7110
    repo.bookmark_create("keep", None).unwrap();
7111
    let created = repo.head_op().unwrap().0.to_hex();
7112
    write(root, "n.txt", b"n\n");
7113
    let third = repo.commit("third", &[]).unwrap();
7114
7115
    // What each operation changed.
7116
    let ops = repo.op_log().unwrap();
7117
    let changes = repo.view_changes(&ops[1].1.view, &ops[0].1.view).unwrap();
7118
    assert!(
7119
        changes
7120
            .iter()
7121
            .any(|c| matches!(c, ViewChange::BookmarkMoved { name, .. } if name == "main")),
7122
        "{changes:?}"
7123
    );
7124
    assert!(changes
7125
        .iter()
7126
        .any(|c| matches!(c, ViewChange::WorkingCopy { .. })));
7127
7128
    // Reading at an earlier operation.
7129
    let old = Repo::open(root).unwrap().at_op(&at_second[..10]).unwrap();
7130
    assert_eq!(old.bookmark_heads().unwrap(), vec![second]);
7131
    assert!(!old.view().unwrap().bookmarks.contains_key("keep"));
7132
    write(root, "z.txt", b"z\n");
7133
    assert!(old.commit("refused", &[]).is_err(), "--at-op is read-only");
7134
    fs::remove_file(root.join("z.txt")).unwrap();
7135
    assert!(repo.resolve_op("zz").is_err());
7136
    assert_eq!(repo.resolve_op("@").unwrap().0, repo.head_op().unwrap().0);
7137
7138
    // Restore goes back, files and all; undo takes it back whole.
7139
    repo.op_restore(&at_second, false).unwrap();
7140
    assert_eq!(repo.bookmark_heads().unwrap(), vec![second]);
7141
    assert!(!root.join("n.txt").exists());
7142
    repo.undo().unwrap();
7143
    let mut heads = repo.bookmark_heads().unwrap();
7144
    heads.sort();
7145
    let mut want = vec![second, third];
7146
    want.sort();
7147
    assert_eq!(heads, want);
7148
    assert!(
7149
        root.join("n.txt").exists(),
7150
        "the files came back with the undo"
7151
    );
7152
7153
    // Revert the bookmark's creation alone: the commit after it stays.
7154
    let r = repo.op_revert(&created).unwrap();
7155
    assert_eq!(r.reverted, vec!["keep".to_string()]);
7156
    assert!(!repo.view().unwrap().bookmarks.contains_key("keep"));
7157
    assert!(repo
7158
        .load_state(&repo.bookmark_heads().unwrap())
7159
        .unwrap()
7160
        .contains(&third));
7161
    assert!(repo.op_revert(&created).is_err(), "nothing left to revert");
7162
    let _ = first;
7163
}
7164
7165
/// oxygen#41: with uncommitted work, a status after a snapshot is answered
7166
/// from the status cache while every file is as the snapshot left it, and
7167
/// from a snapshot again as soon as one is not.
7168
#[test]
7169
fn status_with_uncommitted_work_comes_from_the_cache_until_a_file_changes() {
7170
    hermetic();
7171
    let dir = tempfile::tempdir().unwrap();
7172
    let root = dir.path();
7173
    let repo = Repo::init(root).unwrap();
7174
    write(root, "a.txt", b"a\n");
7175
    write(root, "b.txt", b"b\n");
7176
    repo.commit("base", &[]).unwrap();
7177
    assert_eq!(repo.status_by_manifest().unwrap(), Some(vec![]), "clean");
7178
7179
    write(root, "a.txt", b"a\nmore\n");
7180
    assert_eq!(
7181
        repo.status_by_manifest().unwrap(),
7182
        None,
7183
        "no snapshot of the edit yet"
7184
    );
7185
    let snap = repo.snapshot_status("oxy status").unwrap();
7186
    assert_eq!(snap.statuses.len(), 1);
7187
    let cached = repo
7188
        .status_by_manifest()
7189
        .unwrap()
7190
        .expect("answered from the cache");
7191
    assert_eq!(cached.len(), 1);
7192
    assert_eq!(
7193
        (cached[0].path.as_str(), cached[0].status),
7194
        ("a.txt", ChangeStatus::Modified)
7195
    );
7196
7197
    // Any further change sends status back to a snapshot.
7198
    write(root, "a.txt", b"a\nmore\nand more\n");
7199
    assert_eq!(repo.status_by_manifest().unwrap(), None, "edited again");
7200
    repo.snapshot_status("oxy status").unwrap();
7201
    assert!(repo.status_by_manifest().unwrap().is_some());
7202
    write(root, "new.txt", b"n\n");
7203
    assert_eq!(repo.status_by_manifest().unwrap(), None, "a file added");
7204
    fs::remove_file(root.join("new.txt")).unwrap();
7205
    assert!(
7206
        repo.status_by_manifest().unwrap().is_some(),
7207
        "back as it was"
7208
    );
7209
    fs::remove_file(root.join("b.txt")).unwrap();
7210
    assert_eq!(repo.status_by_manifest().unwrap(), None, "a file removed");
7211
    write(root, "b.txt", b"b\n");
7212
7213
    // A commit leaves nothing uncommitted: clean again, no cache needed.
7214
    repo.snapshot_status("oxy status").unwrap();
7215
    repo.commit("more", &[]).unwrap();
7216
    assert_eq!(repo.status_by_manifest().unwrap(), Some(vec![]));
7217
}
7218
7219
/// oxygen#41: while the status cache holds, the working copy's diff is
7220
/// rendered from the stored working-copy change, and says exactly what a
7221
/// snapshot's diff says.
7222
#[test]
7223
fn the_working_copy_diff_from_the_cache_matches_a_snapshot() {
7224
    hermetic();
7225
    let dir = tempfile::tempdir().unwrap();
7226
    let root = dir.path();
7227
    let repo = Repo::init(root).unwrap();
7228
    write(root, "a.txt", b"one\ntwo\nthree\n");
7229
    write(root, "gone.txt", b"bye\n");
7230
    repo.commit("base", &[]).unwrap();
7231
    write(root, "a.txt", b"one\n2\nthree\nfour\n");
7232
    write(root, "new.txt", b"hello\n");
7233
    fs::remove_file(root.join("gone.txt")).unwrap();
7234
    let snap = repo.snapshot_status("oxy status").unwrap();
7235
    let slow = render_change(&snap.wc, &snap.base, &snap.base_snapshot);
7236
    assert!(
7237
        repo.status_by_manifest().unwrap().is_some(),
7238
        "the cache holds"
7239
    );
7240
    let (wc, base, snapshot) = repo.working_copy_with_base().unwrap();
7241
    assert_eq!(render_change(&wc, &base, &snapshot), slow);
7242
    assert_eq!(repo.diff_files(None).unwrap().len(), 3);
7243
}
7244
7245
/// oxygen#41: a manifest written from a walk keeps every directory's time;
7246
/// while none has moved, the check stats the tracked files without listing
7247
/// the tree, and a file added or removed anywhere moves its directory's
7248
/// time, so the tree is listed again.
7249
#[test]
7250
fn the_manifest_check_skips_listing_while_no_directory_changed() {
7251
    hermetic();
7252
    let dir = tempfile::tempdir().unwrap();
7253
    let root = dir.path();
7254
    let repo = Repo::init(root).unwrap();
7255
    write(root, "a.txt", b"a\n");
7256
    write(root, "sub/deep/b.txt", b"b\n");
7257
    repo.commit("base", &[]).unwrap();
7258
    // Out of the racy window: every file and directory a minute old.
7259
    let old = std::time::SystemTime::now() - std::time::Duration::from_secs(60);
7260
    for p in ["a.txt", "sub/deep/b.txt", "sub/deep", "sub", ""] {
7261
        fs::File::open(root.join(p))
7262
            .unwrap()
7263
            .set_modified(old)
7264
            .unwrap();
7265
    }
7266
    repo.snapshot_status("oxy status").unwrap();
7267
    repo.write_manifest(false, false).unwrap();
7268
    let m = repo.read_manifest().unwrap().unwrap().2;
7269
    assert!(m.dirs.iter().any(|(d, _)| d == "sub/deep"), "{:?}", m.dirs);
7270
    assert_eq!(
7271
        repo.disk_differs_by_dirs(&m),
7272
        Some(false),
7273
        "no listing needed"
7274
    );
7275
    assert_eq!(repo.status_by_manifest().unwrap(), Some(vec![]));
7276
7277
    // A same-size edit with a new time: found by its stat.
7278
    write(root, "sub/deep/b.txt", b"c\n");
7279
    assert_eq!(repo.disk_differs_by_dirs(&m), Some(true));
7280
    write(root, "sub/deep/b.txt", b"b\n");
7281
    fs::File::open(root.join("sub/deep/b.txt"))
7282
        .unwrap()
7283
        .set_modified(old)
7284
        .unwrap();
7285
    assert_eq!(repo.disk_differs_by_dirs(&m), Some(false));
7286
7287
    // A new file moves its directory's time: the tree must be listed.
7288
    write(root, "sub/deep/new.txt", b"n\n");
7289
    assert_eq!(repo.disk_differs_by_dirs(&m), None);
7290
    assert_eq!(repo.status_by_manifest().unwrap(), None);
7291
    fs::remove_file(root.join("sub/deep/new.txt")).unwrap();
7292
    // A removed one too.
7293
    fs::remove_file(root.join("a.txt")).unwrap();
7294
    assert_eq!(repo.disk_differs_by_dirs(&m), None);
7295
}
7296
7297
/// oxygen#41: a commit right after a status takes the snapshot the status
7298
/// left (the status cache holds) rather than walking again, and commits
7299
/// exactly what a snapshot would have.
7300
#[test]
7301
fn a_commit_after_a_status_uses_the_cached_snapshot() {
7302
    hermetic();
7303
    let dir = tempfile::tempdir().unwrap();
7304
    let root = dir.path();
7305
    let repo = Repo::init(root).unwrap();
7306
    write(root, "a.txt", b"a\nb\n");
7307
    write(root, ".oxyattributes", b"*.bin binary\n");
7308
    repo.commit("base", &[]).unwrap();
7309
    write(root, "a.txt", b"a\nB\n");
7310
    write(root, "new.txt", b"new\n");
7311
    let snap = repo.snapshot_status("oxy status").unwrap();
7312
    let cached = repo
7313
        .snapshot_from_cache()
7314
        .unwrap()
7315
        .expect("the cache holds");
7316
    assert_eq!(cached.wc_hash, snap.wc_hash);
7317
    assert_eq!(cached.statuses, snap.statuses);
7318
    assert!(
7319
        !cached.attributes.is_empty(),
7320
        "the .oxyattributes file was read"
7321
    );
7322
    let h = repo.commit("edit", &[]).unwrap();
7323
    let c = repo.store().get_change(&h).unwrap();
7324
    assert_eq!(
7325
        c.tree_ops.len() + c.edits.len(),
7326
        snap.wc.tree_ops.len() + snap.wc.edits.len()
7327
    );
7328
    assert_eq!(
7329
        repo.status_by_manifest().unwrap(),
7330
        Some(vec![]),
7331
        "clean after the commit"
7332
    );
7333
    assert_eq!(fs::read(root.join("a.txt")).unwrap(), b"a\nB\n");
7334
}
7335
7336
/// oxygen#41: a clean check that verified racy entries restamps the
7337
/// manifest, so later checks can trust them, and a same-size rewrite
7338
/// straight afterwards is still found: entries within two seconds of the
7339
/// new time stay racy.
7340
#[test]
7341
fn a_verified_clean_check_restamps_the_manifest_safely() {
7342
    hermetic();
7343
    let dir = tempfile::tempdir().unwrap();
7344
    let root = dir.path();
7345
    let repo = Repo::init(root).unwrap();
7346
    write(root, "a.txt", b"one\n");
7347
    repo.commit("one", &[]).unwrap();
7348
    let before = repo.read_manifest().unwrap().unwrap().2.written_ns;
7349
    assert!(repo.clean_by_manifest().unwrap());
7350
    let after = repo.read_manifest().unwrap().unwrap().2.written_ns;
7351
    assert!(after > before, "restamped");
7352
    write(root, "a.txt", b"two\n");
7353
    assert!(
7354
        !repo.clean_by_manifest().unwrap(),
7355
        "a same-size rewrite is still seen"
7356
    );
7357
}
7358
7359
/// oxygen#35: a history-only state keeps no inserted text. It reads a
7360
/// stored insert's text blob only when it builds that file's graph, and
7361
/// builds the same graph a full load does.
7362
#[test]
7363
fn history_only_states_read_text_only_for_the_graphs_they_build() {
7364
    hermetic();
7365
    let dir = tempfile::tempdir().unwrap();
7366
    let root = dir.path();
7367
    let repo = Repo::init(root).unwrap();
7368
    let big: String = (0..3000).map(|i| format!("big line {i}\n")).collect();
7369
    let other: String = (0..3000).map(|i| format!("other line {i}\n")).collect();
7370
    write(root, "big.txt", big.as_bytes());
7371
    write(root, "other.txt", other.as_bytes());
7372
    let h = repo.commit("two large files", &[]).unwrap();
7373
    write(root, "big.txt", format!("{big}one more\n").as_bytes());
7374
    let h2 = repo.commit("append", &[]).unwrap();
7375
7376
    let full = repo.load_state_full(&[h2]).unwrap().materialize();
7377
    let text = |snap: &crate::state::Snapshot, p: &str| match &snap.files[p].content {
7378
        FileContent::Text { bytes, .. } => bytes.clone(),
7379
        other => panic!("{other:?}"),
7380
    };
7381
    // Built on demand, every graph renders as the full load's.
7382
    let mut hist = repo.load_state_history(&[h2]).unwrap();
7383
    let big_node = full.files["big.txt"].node;
7384
    assert!(hist.graph_key(&big_node).is_some(), "not built yet");
7385
    repo.load_all_graphs(&mut hist).unwrap();
7386
    let rendered = hist.materialize();
7387
    for p in ["big.txt", "other.txt"] {
7388
        assert_eq!(text(&rendered, p), text(&full, p), "{p}");
7389
    }
7390
7391
    // Without other.txt's text blob, history still loads and big.txt still
7392
    // builds: nothing read the other text.
7393
    let (_, texts) = repo.store().get_change_lazy(&h).unwrap();
7394
    assert_eq!(texts.len(), 2);
7395
    let content = |r: &ObjectRef| -> Vec<u8> {
7396
        let blob = crate::objects::Blob::decode(&repo.store().get(r).unwrap().1).unwrap();
7397
        blob.chunks
7398
            .iter()
7399
            .flat_map(|c| repo.store().get(c).unwrap().1)
7400
            .collect()
7401
    };
7402
    let other_text = texts
7403
        .iter()
7404
        .filter_map(|t| match t {
7405
            crate::objects::TextRef::Blob(r, _, _) => Some(*r),
7406
            _ => None,
7407
        })
7408
        .find(|r| content(r).windows(12).any(|w| w == b"other line 1"))
7409
        .unwrap();
7410
    repo.store().remove_loose_for_test(&other_text).unwrap();
7411
    let mut hist = repo.load_state_history(&[h2]).unwrap();
7412
    repo.load_graphs_of(&mut hist, &[big_node]).unwrap();
7413
    assert!(repo
7414
        .load_graphs_of(&mut hist, &[full.files["other.txt"].node])
7415
        .is_err());
7416
}
7417
7418
/// oxygen#35: the first status after a commit read and rendered every
7419
/// file (79 s and more than 14 GB on the Linux tree), because the
7420
/// manifest had no graph keys for files the commit added.
7421
#[test]
7422
fn a_commit_leaves_a_manifest_the_next_status_trusts() {
7423
    use std::os::unix::fs::PermissionsExt;
7424
    hermetic();
7425
    let dir = tempfile::tempdir().unwrap();
7426
    let root = dir.path();
7427
    let repo = Repo::init(root).unwrap();
7428
    let files = ["a.txt", "b.txt", "d/c.txt"];
7429
    for p in files {
7430
        write(root, p, format!("{p}\n").as_bytes());
7431
        let old = std::time::SystemTime::now() - std::time::Duration::from_secs(30);
7432
        fs::File::options()
7433
            .write(true)
7434
            .open(root.join(p))
7435
            .unwrap()
7436
            .set_modified(old)
7437
            .unwrap();
7438
    }
7439
    repo.commit("added", &[]).unwrap();
7440
    let (_, _, m) = repo.read_manifest().unwrap().unwrap();
7441
    assert!(
7442
        m.entries.values().all(|e| e.graph.is_some()),
7443
        "keys recorded at commit"
7444
    );
7445
    // Unreadable files prove the next status reads none of them.
7446
    for p in files {
7447
        fs::set_permissions(root.join(p), fs::Permissions::from_mode(0o000)).unwrap();
7448
    }
7449
    let snap = repo.snapshot_status("status").unwrap();
7450
    for p in files {
7451
        fs::set_permissions(root.join(p), fs::Permissions::from_mode(0o644)).unwrap();
7452
    }
7453
    assert!(!snap.changed && snap.statuses.is_empty());
7454
    assert_eq!(snap.base_snapshot.unrendered.len(), files.len());
7455
}
7456
7457
/// oxygen#35: a checkout reads, renders and writes only the files whose
7458
/// graphs differ, and renders the rest a batch at a time.
7459
#[test]
7460
fn checkout_touches_only_what_differs_and_renders_in_batches() {
7461
    use std::os::unix::fs::PermissionsExt;
7462
    hermetic();
7463
    let dir = tempfile::tempdir().unwrap();
7464
    let root = dir.path();
7465
    let origin = root.join("origin");
7466
    let mut repo = Repo::init(&origin).unwrap();
7467
    // More files than one batch holds.
7468
    let n = 2100;
7469
    let old = std::time::SystemTime::now() - std::time::Duration::from_secs(30);
7470
    for i in 0..n {
7471
        let p = format!("f/{i:04}.txt");
7472
        write(&origin, &p, format!("file {i}\n").as_bytes());
7473
        fs::File::options()
7474
            .write(true)
7475
            .open(origin.join(&p))
7476
            .unwrap()
7477
            .set_modified(old)
7478
            .unwrap();
7479
    }
7480
    repo.commit("many", &[]).unwrap();
7481
    repo.bookmark_create("feature", None).unwrap();
7482
    repo.bookmark_switch("feature", false).unwrap();
7483
    write(&origin, "f/0007.txt", b"changed\n");
7484
    repo.commit("one change", &[]).unwrap();
7485
7486
    // Switching back to main must not read the unchanged files.
7487
    for i in 0..n {
7488
        if i != 7 {
7489
            let p = origin.join(format!("f/{i:04}.txt"));
7490
            fs::set_permissions(&p, fs::Permissions::from_mode(0o000)).unwrap();
7491
        }
7492
    }
7493
    let r = repo.bookmark_switch("main", false).unwrap();
7494
    for i in 0..n {
7495
        let p = origin.join(format!("f/{i:04}.txt"));
7496
        fs::set_permissions(&p, fs::Permissions::from_mode(0o644)).unwrap();
7497
    }
7498
    assert_eq!((r.written, r.removed), (1, 0), "{r:?}");
7499
    assert_eq!(fs::read(origin.join("f/0007.txt")).unwrap(), b"file 7\n");
7500
    assert!(repo.snapshot_status("status").unwrap().statuses.is_empty());
7501
7502
    // A clone renders every file, across batches.
7503
    let c = root.join("clone");
7504
    Repo::clone(&origin.to_string_lossy(), &c).unwrap();
7505
    for i in [0, 2047, 2048, n - 1] {
7506
        assert_eq!(
7507
            fs::read(c.join(format!("f/{i:04}.txt"))).unwrap(),
7508
            format!("file {i}\n").as_bytes()
7509
        );
7510
    }
7511
    let cloned = Repo::open(&c).unwrap();
7512
    assert!(cloned
7513
        .snapshot_status("status")
7514
        .unwrap()
7515
        .statuses
7516
        .is_empty());
7517
}
7518
7519
/// A file written just before the manifest (inside the racy window) is
7520
/// checked by its hash: trusted when equal, caught when edited in place
7521
/// with the same size and time.
7522
#[test]
7523
fn a_racy_manifest_entry_is_checked_by_hash() {
7524
    hermetic();
7525
    let dir = tempfile::tempdir().unwrap();
7526
    let root = dir.path();
7527
    let repo = Repo::init(root).unwrap();
7528
    write(root, "a.txt", b"one\n");
7529
    repo.commit("fresh", &[]).unwrap();
7530
    assert!(repo.clean_by_manifest().unwrap(), "fresh but equal");
7531
    let t = fs::metadata(root.join("a.txt"))
7532
        .unwrap()
7533
        .modified()
7534
        .unwrap();
7535
    write(root, "a.txt", b"two\n");
7536
    fs::File::options()
7537
        .write(true)
7538
        .open(root.join("a.txt"))
7539
        .unwrap()
7540
        .set_modified(t)
7541
        .unwrap();
7542
    assert!(
7543
        !repo.clean_by_manifest().unwrap(),
7544
        "same size and time, other bytes"
7545
    );
7546
    assert_eq!(
7547
        statuses(&repo.snapshot_status("status").unwrap()),
7548
        vec![("a.txt".to_string(), ChangeStatus::Modified)]
7549
    );
7550
}
7551
7552
/// A fetch on one machine moves changes as stored, text blobs among the
7553
/// objects; a change whose text blob did not come is refused, not stored.
7554
#[test]
7555
fn a_raw_bundle_without_a_changes_text_is_refused() {
7556
    hermetic();
7557
    let dir = tempfile::tempdir().unwrap();
7558
    let root = dir.path();
7559
    let a = Repo::init(&root.join("a")).unwrap();
7560
    let big: String = (0..3000).map(|i| format!("line {i}\n")).collect();
7561
    write(&root.join("a"), "big.txt", big.as_bytes());
7562
    let h = a.commit("big", &[]).unwrap();
7563
    let bundle = a.bundle_raw_for(&[h], None).unwrap();
7564
    assert_eq!(bundle.raw_changes.len(), 1);
7565
    assert!(bundle.changes.is_empty());
7566
    let b = Repo::init(&root.join("b")).unwrap();
7567
    let mut without = bundle.clone();
7568
    without.objects.retain(|(ty, _)| *ty != ObjectType::Blob);
7569
    let e = b.import_bundle(&without, false).unwrap_err();
7570
    assert!(e.to_string().contains("came without its text blob"), "{e}");
7571
    assert!(!b.store().has(&h));
7572
    assert_eq!(b.import_bundle(&bundle, false).unwrap(), vec![h]);
7573
    assert_eq!(b.store().get_change(&h).unwrap().message, "big");
7574
}
7575
7576
/// oxygen#30 (vscode): a directory deleted in one line of history and made
7577
/// again was a second node for one Git path, so a file moved into it on
7578
/// another line, where the first node still stood, ended up in two places.
7579
/// An import now brings the directory back rather than make a new one.
7580
#[test]
7581
fn git_import_brings_a_directory_back_rather_than_making_a_second() {
7582
    hermetic();
7583
    if std::process::Command::new("git")
7584
        .arg("--version")
7585
        .output()
7586
        .is_err()
7587
    {
7588
        eprintln!("git not installed; skipping");
7589
        return;
7590
    }
7591
    let dir = tempfile::tempdir().unwrap();
7592
    let root = dir.path();
7593
    let g = root.join("src.git");
7594
    fs::create_dir_all(&g).unwrap();
7595
    let git = |args: &[&str]| -> String {
7596
        let out = std::process::Command::new("git")
7597
            .arg("-C")
7598
            .arg(&g)
7599
            .args([
7600
                "-c",
7601
                "user.name=Grace",
7602
                "-c",
7603
                "[email protected]",
7604
                "-c",
7605
                "commit.gpgsign=false",
7606
            ])
7607
            .args(args)
7608
            .output()
7609
            .unwrap();
7610
        assert!(
7611
            out.status.success(),
7612
            "git {args:?}: {}",
7613
            String::from_utf8_lossy(&out.stderr)
7614
        );
7615
        String::from_utf8_lossy(&out.stdout).trim().to_string()
7616
    };
7617
    git(&["init", "-q", "-b", "main"]);
7618
    write(&g, "d/a.txt", b"a\n");
7619
    write(&g, "c/x.txt", b"x\n");
7620
    git(&["add", "."]);
7621
    git(&["commit", "-qm", "base"]);
7622
    // One line: move x into d while d still stands.
7623
    git(&["checkout", "-qb", "side"]);
7624
    git(&["mv", "c/x.txt", "d/x.txt"]);
7625
    git(&["commit", "-qm", "x into d"]);
7626
    // The other: d goes, comes back, and x moves into it too.
7627
    git(&["checkout", "-q", "main"]);
7628
    git(&["rm", "-q", "d/a.txt"]);
7629
    git(&["commit", "-qm", "d goes"]);
7630
    write(&g, "d/b.txt", b"b\n");
7631
    git(&["add", "."]);
7632
    git(&["commit", "-qm", "d comes back"]);
7633
    git(&["mv", "c/x.txt", "d/x.txt"]);
7634
    git(&["commit", "-qm", "x into d again"]);
7635
    git(&["merge", "-q", "--no-edit", "side"]);
7636
7637
    let repo = Repo::init(&root.join("o")).unwrap();
7638
    repo.import_git(&g, "main").unwrap();
7639
    let v = repo.verify_git_import(&g, "main").unwrap();
7640
    assert!(v.mismatches.is_empty(), "{:?}", v.mismatches);
7641
    let st = repo
7642
        .load_state_history(&repo.bookmark_heads().unwrap())
7643
        .unwrap();
7644
    let view = st.tree().view();
7645
    assert!(view.conflicts.is_empty(), "{:?}", view.conflicts);
7646
    // The directory is the one the first commit made.
7647
    // Commits made in one second tie on time: find the first by its message.
7648
    let first = repo
7649
        .log()
7650
        .unwrap()
7651
        .into_iter()
7652
        .find(|e| e.change.message.starts_with("base"))
7653
        .unwrap();
7654
    let base = repo
7655
        .load_state_history(&[first.hash])
7656
        .unwrap()
7657
        .tree()
7658
        .view();
7659
    assert_eq!(view.entries["d"].node, base.entries["d"].node);
7660
}
7661
7662
/// oxygen#30, the rest: a placement left under a directory another line
7663
/// removed is out of sight, so no diff reaches it; the merge that settles
7664
/// where the file is retires it.
7665
#[test]
7666
fn git_import_merge_retires_a_placement_under_a_removed_directory() {
7667
    hermetic();
7668
    if std::process::Command::new("git")
7669
        .arg("--version")
7670
        .output()
7671
        .is_err()
7672
    {
7673
        eprintln!("git not installed; skipping");
7674
        return;
7675
    }
7676
    let dir = tempfile::tempdir().unwrap();
7677
    let root = dir.path();
7678
    let g = root.join("src.git");
7679
    fs::create_dir_all(&g).unwrap();
7680
    let run = |args: &[&str]| {
7681
        std::process::Command::new("git")
7682
            .arg("-C")
7683
            .arg(&g)
7684
            .args([
7685
                "-c",
7686
                "user.name=Grace",
7687
                "-c",
7688
                "[email protected]",
7689
                "-c",
7690
                "commit.gpgsign=false",
7691
            ])
7692
            .args(args)
7693
            .output()
7694
            .unwrap()
7695
    };
7696
    let git = |args: &[&str]| {
7697
        let out = run(args);
7698
        assert!(
7699
            out.status.success(),
7700
            "git {args:?}: {}",
7701
            String::from_utf8_lossy(&out.stderr)
7702
        );
7703
    };
7704
    git(&["init", "-q", "-b", "main"]);
7705
    write(&g, "c/x.txt", b"x\n");
7706
    write(&g, "keep.txt", b"k\n");
7707
    git(&["add", "."]);
7708
    git(&["commit", "-qm", "base"]);
7709
    // One line renames the file within c; the other moves it out of c,
7710
    // which goes.
7711
    git(&["checkout", "-qb", "side"]);
7712
    git(&["mv", "c/x.txt", "c/y.txt"]);
7713
    git(&["commit", "-qm", "rename within c"]);
7714
    git(&["checkout", "-q", "main"]);
7715
    fs::create_dir_all(g.join("n")).unwrap();
7716
    git(&["mv", "c/x.txt", "n/x.txt"]);
7717
    git(&["commit", "-qm", "move out of c"]);
7718
    // Git cannot merge the two renames; the merge keeps n/x.txt.
7719
    let _ = run(&["merge", "-q", "side"]);
7720
    let _ = run(&[
7721
        "rm",
7722
        "-q",
7723
        "--cached",
7724
        "--ignore-unmatch",
7725
        "c/y.txt",
7726
        "c/x.txt",
7727
    ]);
7728
    let _ = std::fs::remove_dir_all(g.join("c"));
7729
    write(&g, "n/x.txt", b"x\n");
7730
    git(&["add", "-A"]);
7731
    git(&["commit", "-qm", "merge: keep n/x.txt"]);
7732
7733
    let repo = Repo::init(&root.join("o")).unwrap();
7734
    repo.import_git(&g, "main").unwrap();
7735
    let v = repo.verify_git_import(&g, "main").unwrap();
7736
    assert!(v.mismatches.is_empty(), "{:?}", v.mismatches);
7737
    let st = repo
7738
        .load_state_history(&repo.bookmark_heads().unwrap())
7739
        .unwrap();
7740
    let view = st.tree().view();
7741
    assert!(view.conflicts.is_empty(), "{:?}", view.conflicts);
7742
    assert!(view.entries.contains_key("n/x.txt"));
7743
}
7744
7745
/// oxygen#30, orphans: a file added on one line into a directory the other
7746
/// line removed is placed where the tree cannot show it; Git's merge keeps
7747
/// the file, and the import's merge leaves exactly one of it.
7748
#[test]
7749
fn git_import_merge_leaves_no_orphan_behind() {
7750
    hermetic();
7751
    if std::process::Command::new("git")
7752
        .arg("--version")
7753
        .output()
7754
        .is_err()
7755
    {
7756
        eprintln!("git not installed; skipping");
7757
        return;
7758
    }
7759
    let dir = tempfile::tempdir().unwrap();
7760
    let root = dir.path();
7761
    let g = root.join("src.git");
7762
    fs::create_dir_all(&g).unwrap();
7763
    let git = |args: &[&str]| {
7764
        let out = std::process::Command::new("git")
7765
            .arg("-C")
7766
            .arg(&g)
7767
            .args([
7768
                "-c",
7769
                "user.name=Grace",
7770
                "-c",
7771
                "[email protected]",
7772
                "-c",
7773
                "commit.gpgsign=false",
7774
            ])
7775
            .args(args)
7776
            .output()
7777
            .unwrap();
7778
        assert!(
7779
            out.status.success(),
7780
            "git {args:?}: {}",
7781
            String::from_utf8_lossy(&out.stderr)
7782
        );
7783
    };
7784
    git(&["init", "-q", "-b", "main"]);
7785
    write(&g, "d/f.txt", b"f\n");
7786
    write(&g, "keep.txt", b"k\n");
7787
    git(&["add", "."]);
7788
    git(&["commit", "-qm", "base"]);
7789
    git(&["checkout", "-qb", "side"]);
7790
    write(&g, "d/new.txt", b"new\n");
7791
    git(&["add", "."]);
7792
    git(&["commit", "-qm", "add into d"]);
7793
    git(&["checkout", "-q", "main"]);
7794
    git(&["rm", "-q", "d/f.txt"]);
7795
    git(&["commit", "-qm", "d goes"]);
7796
    git(&["merge", "-q", "--no-edit", "side"]);
7797
7798
    let repo = Repo::init(&root.join("o")).unwrap();
7799
    repo.import_git(&g, "main").unwrap();
7800
    let v = repo.verify_git_import(&g, "main").unwrap();
7801
    assert!(v.mismatches.is_empty(), "{:?}", v.mismatches);
7802
    let st = repo
7803
        .load_state_history(&repo.bookmark_heads().unwrap())
7804
        .unwrap();
7805
    let view = st.tree().view();
7806
    assert!(view.conflicts.is_empty(), "{:?}", view.conflicts);
7807
    assert!(view.entries.contains_key("d/new.txt"));
7808
}
7809
7810
/// fsck checks a change's text as the blobs it is stored in, without
7811
/// decoding it: a missing text blob is an error named for the change.
7812
#[test]
7813
fn fsck_names_a_missing_text_blob() {
7814
    hermetic();
7815
    let dir = tempfile::tempdir().unwrap();
7816
    let root = dir.path();
7817
    let repo = Repo::init(root).unwrap();
7818
    let big: String = (0..3000).map(|i| format!("line {i}\n")).collect();
7819
    write(root, "big.txt", big.as_bytes());
7820
    let h = repo.commit("big", &[]).unwrap();
7821
    assert_eq!(repo.fsck().unwrap().errors(), 0);
7822
    let (_, texts) = repo.store().get_change_lazy(&h).unwrap();
7823
    let Some(crate::objects::TextRef::Blob(b, _, _)) = texts.first().copied() else {
7824
        panic!("a stored text")
7825
    };
7826
    repo.store().remove_loose_for_test(&b).unwrap();
7827
    let rep = repo.fsck().unwrap();
7828
    assert!(rep.errors() > 0);
7829
    assert!(
7830
        rep.problems.iter().any(|p| p.what.contains(&h.short(12))),
7831
        "{:?}",
7832
        rep.problems
7833
    );
7834
}
7835
7836
/// oxygen#32: a subrepo on the same hub as one of the parent's remotes is
7837
/// reached with that remote's token and CA (a private subrepo then clones
7838
/// for anyone who can read the parent); another hub gets none of them.
7839
#[test]
7840
fn a_subrepo_on_the_parents_hub_borrows_its_credentials() {
7841
    hermetic();
7842
    let dir = tempfile::tempdir().unwrap();
7843
    let mut repo = Repo::init(dir.path()).unwrap();
7844
    repo.config
7845
        .set(
7846
            "remote.origin.url",
7847
            "https://Hub.example:7343/doomsdayone/metalgear",
7848
        )
7849
        .unwrap();
7850
    repo.config.set("remote.origin.token", "secret").unwrap();
7851
    repo.config
7852
        .set("remote.origin.ca", "/tmp/hub-ca.pem")
7853
        .unwrap();
7854
    let same = repo.credentials_for("https://hub.example:7343/doomsdayone/rstar-api");
7855
    assert_eq!(same.token.as_deref(), Some("secret"));
7856
    assert_eq!(same.ca.as_deref(), Some(Path::new("/tmp/hub-ca.pem")));
7857
    for other in [
7858
        "https://elsewhere.example:7343/doomsdayone/rstar-api",
7859
        "https://hub.example/doomsdayone/rstar-api",
7860
        "http://hub.example:7343/doomsdayone/rstar-api",
7861
    ] {
7862
        let o = repo.credentials_for(other);
7863
        assert_ne!(o.token.as_deref(), Some("secret"), "{other}");
7864
    }
7865
}
7866
7867
/// oxygen#47: a remote with no token of its own uses the user's credential
7868
/// store for its hub, and a nested checkout finds its parent's remote
7869
/// token there instead of keeping a copy.
7870
#[test]
7871
fn remotes_use_the_credential_store_and_the_enclosing_checkout() {
7872
    hermetic();
7873
    let home = tempfile::tempdir().unwrap();
7874
    let dir = tempfile::tempdir().unwrap();
7875
    let mut parent = Repo::init(dir.path()).unwrap().with_home(home.path());
7876
    parent
7877
        .config
7878
        .set("remote.origin.url", "https://hub.example/o/parent")
7879
        .unwrap();
7880
    parent.save_config().unwrap();
7881
    assert_eq!(parent.remote_options("origin").token, None);
7882
    crate::credentials::Credentials::at(home.path())
7883
        .save("https://hub.example", "stored", Some("andy"), None)
7884
        .unwrap();
7885
    assert_eq!(
7886
        parent.remote_options("origin").token.as_deref(),
7887
        Some("stored")
7888
    );
7889
7890
    let empty_home = tempfile::tempdir().unwrap();
7891
    let nested = dir.path().join("deps").join("child");
7892
    let mut child = Repo::init(&nested).unwrap().with_home(empty_home.path());
7893
    child
7894
        .config
7895
        .set("remote.origin.url", "https://hub.example/o/child")
7896
        .unwrap();
7897
    child.save_config().unwrap();
7898
    assert_eq!(child.remote_options("origin").token, None);
7899
    parent
7900
        .config
7901
        .set("remote.origin.token", "checkout")
7902
        .unwrap();
7903
    parent.save_config().unwrap();
7904
    assert_eq!(
7905
        child.remote_options("origin").token.as_deref(),
7906
        Some("checkout")
7907
    );
7908
    // Another hub's checkout token is not borrowed.
7909
    child
7910
        .config
7911
        .set("remote.origin.url", "https://other.example/o/child")
7912
        .unwrap();
7913
    assert_eq!(child.remote_options("origin").token, None);
7914
}
7915
7916
#[test]
7917
fn the_metadata_cache_survives_a_torn_tail() {
7918
    hermetic();
7919
    let dir = tempfile::tempdir().unwrap();
7920
    let root = dir.path();
7921
    let repo = Repo::init(root).unwrap();
7922
    write(root, "a.txt", b"1\n");
7923
    let h = repo.commit("first", &[]).unwrap();
7924
    let meta = repo.store().get_change_meta(&h).unwrap();
7925
    let cache = repo.store().dir().join("metas");
7926
    let len = fs::metadata(&cache).unwrap().len();
7927
    assert!(len > 0, "a change read is cached");
7928
    // A torn record at the end: the cache reads up to it and cuts it off.
7929
    fs::OpenOptions::new()
7930
        .append(true)
7931
        .open(&cache)
7932
        .unwrap()
7933
        .write_all(&[7; 20])
7934
        .unwrap();
7935
    let again = Repo::open(root).unwrap();
7936
    assert_eq!(again.store().get_change_meta(&h).unwrap(), meta);
7937
    assert_eq!(fs::metadata(&cache).unwrap().len(), len);
7938
}
7939
7940
#[test]
7941
fn a_manifest_that_does_not_check_reads_as_none() {
7942
    hermetic();
7943
    let dir = tempfile::tempdir().unwrap();
7944
    let root = dir.path();
7945
    let repo = Repo::init(root).unwrap();
7946
    write(root, "a.txt", b"1\n");
7947
    repo.commit("first", &[]).unwrap();
7948
    let path = repo.manifest_path();
7949
    let mut bytes = fs::read(&path).unwrap();
7950
    assert!(Repo::open(root).unwrap().read_manifest().unwrap().is_some());
7951
    let last = bytes.len() - 1;
7952
    bytes[last] ^= 1;
7953
    fs::write(&path, &bytes).unwrap();
7954
    assert!(Repo::open(root).unwrap().read_manifest().unwrap().is_none());
7955
    // The next status reads the files and writes it again.
7956
    let again = Repo::open(root).unwrap();
7957
    assert!(!again.snapshot("status").unwrap().changed);
7958
    assert!(again.read_manifest().unwrap().is_some());
7959
}
7960
7961
#[test]
7962
fn a_commit_leaves_a_manifest_that_proves_the_working_copy_clean() {
7963
    hermetic();
7964
    let dir = tempfile::tempdir().unwrap();
7965
    let root = dir.path();
7966
    let repo = Repo::init(root).unwrap();
7967
    write(root, "a.txt", b"1\n");
7968
    write(root, "b.txt", b"2\n");
7969
    // b.txt outside the racy window, so snapshots take it as unchanged.
7970
    let old = std::time::SystemTime::now() - std::time::Duration::from_secs(60);
7971
    fs::File::options()
7972
        .write(true)
7973
        .open(root.join("b.txt"))
7974
        .unwrap()
7975
        .set_modified(old)
7976
        .unwrap();
7977
    repo.commit("first", &[]).unwrap();
7978
    assert!(repo.clean_by_manifest().unwrap(), "after the first commit");
7979
    repo.snapshot_status("status").unwrap();
7980
    write(root, "a.txt", b"1\n2\n");
7981
    repo.commit("second", &[]).unwrap();
7982
    assert!(
7983
        repo.clean_by_manifest().unwrap(),
7984
        "after a commit of one file"
7985
    );
7986
    // Edited, seen by a status, edited again, then committed: the status
7987
    // left the first edit's stat, which the commit must not keep.
7988
    write(root, "a.txt", b"1\n2\n3\n");
7989
    repo.snapshot_status("status").unwrap();
7990
    write(root, "a.txt", b"1\n2\n3\n4\n5\n");
7991
    repo.commit("third", &[]).unwrap();
7992
    assert!(
7993
        repo.clean_by_manifest().unwrap(),
7994
        "after an edit a status saw"
7995
    );
7996
}
7997
7998
#[test]
7999
fn a_conflicted_rebase_can_be_resolved_in_the_working_copy() {
8000
    hermetic();
8001
    let dir = tempfile::tempdir().unwrap();
8002
    let root = dir.path();
8003
    let mut repo = Repo::init(root).unwrap().with_home(root.join("home"));
8004
    write(root, "a.txt", b"1\n2\n");
8005
    let a = repo.commit("A", &[]).unwrap();
8006
    repo.bookmark_create("develop", Some(&[a])).unwrap();
8007
    write(root, "a.txt", b"1\nX\n");
8008
    let c = repo.commit("C: 2 to X", &[]).unwrap();
8009
    repo.bookmark_switch("develop", false).unwrap();
8010
    write(root, "a.txt", b"1\nY\n");
8011
    let d = repo.commit("D: 2 to Y", &[]).unwrap();
8012
    repo.bookmark_switch("main", false).unwrap();
8013
8014
    let err = repo.rebase(&c, &[d]).unwrap_err();
8015
    assert!(matches!(err, RepoError::Conflicted(_)), "{err}");
8016
    let r = repo.rebase_into_working_copy(&c, &[d]).unwrap();
8017
    assert!(r.changed && r.checked_out);
8018
    let snap = repo.snapshot_status("status").unwrap();
8019
    assert!(
8020
        snap.base_snapshot.is_conflicted(),
8021
        "the conflict is in the working copy"
8022
    );
8023
    let text = fs::read_to_string(root.join("a.txt")).unwrap();
8024
    assert!(text.contains('X') && text.contains('Y'), "{text}");
8025
8026
    write(root, "a.txt", b"1\nXY\n");
8027
    repo.commit("Resolve", &[]).unwrap();
8028
    let st = repo.load_state(&repo.bookmark_heads().unwrap()).unwrap();
8029
    assert!(st.contains(&c) && st.contains(&d));
8030
    let files = st.materialize().files;
8031
    assert!(!files["a.txt"].is_conflicted());
8032
    assert!(
8033
        matches!(&files["a.txt"].content, FileContent::Text { bytes, .. } if bytes == b"1\nXY\n")
8034
    );
8035
8036
    // A change the current bookmark does not hold is refused.
8037
    repo.bookmark_switch("develop", false).unwrap();
8038
    write(root, "b.txt", b"b\n");
8039
    let e = repo.commit("E", &[]).unwrap();
8040
    repo.bookmark_switch("main", false).unwrap();
8041
    let err = repo.rebase_into_working_copy(&e, &[a]).unwrap_err();
8042
    assert!(
8043
        err.to_string().contains("not on the current bookmark"),
8044
        "{err}"
8045
    );
8046
}
8047
8048
#[test]
8049
fn an_ignore_rule_drops_an_added_file_but_not_a_tracked_one() {
8050
    hermetic();
8051
    let dir = tempfile::tempdir().unwrap();
8052
    let root = dir.path();
8053
    let repo = Repo::init(root).unwrap();
8054
    write(root, "a.txt", b"a\n");
8055
    write(root, "kept.log", b"tracked\n");
8056
    repo.commit("first", &[]).unwrap();
8057
    write(root, "build.log", b"made\n");
8058
    let snap = repo.snapshot_status("status").unwrap();
8059
    assert!(snap.statuses.iter().any(|s| s.path == "build.log"));
8060
    // A rule written afterwards leaves the added file out again, while the
8061
    // committed one stays tracked.
8062
    write(root, ".gitignore", b"*.log\n");
8063
    let snap = repo.snapshot_status("status").unwrap();
8064
    let paths: Vec<&str> = snap.statuses.iter().map(|s| s.path.as_str()).collect();
8065
    assert_eq!(paths, vec![".gitignore"], "{paths:?}");
8066
    write(root, "kept.log", b"tracked, edited\n");
8067
    let snap = repo.snapshot_status("status").unwrap();
8068
    assert!(snap.statuses.iter().any(|s| s.path == "kept.log"));
8069
}
8070
8071
#[test]
8072
fn shed_graphs_come_back_the_same() {
8073
    hermetic();
8074
    let dir = tempfile::tempdir().unwrap();
8075
    let root = dir.path();
8076
    let repo = Repo::init(root).unwrap();
8077
    write(root, "a.txt", b"1\n2\n3\n");
8078
    write(root, "b.txt", b"x\n");
8079
    repo.commit("first", &[]).unwrap();
8080
    write(root, "a.txt", b"1\ntwo\n3\n4\n");
8081
    repo.commit("second", &[]).unwrap();
8082
    let heads = repo.bookmark_heads().unwrap();
8083
    let mut st = repo.load_state_history(&heads).unwrap();
8084
    let view = st.tree().view();
8085
    let nodes: Vec<NodeId> = ["a.txt", "b.txt"]
8086
        .iter()
8087
        .map(|p| view.entries[*p].node)
8088
        .collect();
8089
    repo.load_graphs_of(&mut st, &nodes).unwrap();
8090
    let before: Vec<Vec<u8>> = nodes.iter().map(|n| st.render_file(n).0).collect();
8091
    assert_eq!(st.built_count(), 2);
8092
    let shed = st.shed_graphs(|b| repo.store_blob(b)).unwrap();
8093
    assert_eq!((shed, st.built_count()), (2, 0));
8094
    // A later change applies on top of the shed history.
8095
    write(root, "a.txt", b"1\ntwo\n3\n4\n5\n");
8096
    let h3 = repo.commit("third", &[]).unwrap();
8097
    let (skeleton, texts) = repo.store().get_change_lazy(&h3).unwrap();
8098
    st.add_known(h3, skeleton, texts);
8099
    repo.load_graphs_of(&mut st, &nodes).unwrap();
8100
    let after: Vec<Vec<u8>> = nodes.iter().map(|n| st.render_file(n).0).collect();
8101
    assert_eq!(after[1], before[1]);
8102
    assert_eq!(after[0], b"1\ntwo\n3\n4\n5\n");
8103
}
8104
8105
#[test]
8106
fn many_edited_files_diff_in_parallel() {
8107
    // Enough edited files that the builder diffs them in parallel; the
8108
    // commit must hold exactly what is on disk, and a second snapshot
8109
    // must find nothing left to commit.
8110
    hermetic();
8111
    let dir = tempfile::tempdir().unwrap();
8112
    let root = dir.path();
8113
    let repo = Repo::init(root).unwrap();
8114
    let text = |i: usize, round: usize| {
8115
        let mut s = String::new();
8116
        for line in 0..50 {
8117
            if round > 0 && line % 7 == i % 7 {
8118
                s.push_str(&format!("edited {round} {i} {line}\n"));
8119
            } else {
8120
                s.push_str(&format!("file {i} line {line}\n"));
8121
            }
8122
        }
8123
        if round > 0 && i.is_multiple_of(3) {
8124
            s.push_str("appended\n");
8125
        }
8126
        s
8127
    };
8128
    for i in 0..40 {
8129
        write(root, &format!("d/f{i}.txt"), text(i, 0).as_bytes());
8130
    }
8131
    repo.commit("first", &[]).unwrap();
8132
    for i in 0..40 {
8133
        write(root, &format!("d/f{i}.txt"), text(i, 1).as_bytes());
8134
    }
8135
    let h = repo.commit("edit every file", &[]).unwrap();
8136
    let snap = repo.load_state(&[h]).unwrap().materialize();
8137
    for i in 0..40 {
8138
        let want = text(i, 1);
8139
        assert!(
8140
            matches!(&snap.files[&format!("d/f{i}.txt")].content, FileContent::Text { bytes, .. } if bytes == want.as_bytes()),
8141
            "d/f{i}.txt as committed"
8142
        );
8143
    }
8144
    assert!(
8145
        repo.commit("nothing", &[]).is_err(),
8146
        "nothing left to commit"
8147
    );
8148
}
8149
8150
/// oxygen#56: after a fetch, how a bookmark stands against its remote copy
8151
/// is known (fetch printed "up to date" while main was behind), a change
8152
/// only fetched resolves and says where it is, and a checkout whose only
8153
/// remote is not `origin` uses that one.
8154
#[test]
8155
fn a_fetched_change_shows_as_behind_and_resolves() {
8156
    hermetic();
8157
    let dir = tempfile::tempdir().unwrap();
8158
    let root = dir.path();
8159
    let origin = Repo::init(&root.join("origin")).unwrap();
8160
    drop(origin);
8161
    let url = root.join("origin").to_string_lossy().to_string();
8162
    let a = Repo::clone(&url, &root.join("a"))
8163
        .unwrap()
8164
        .with_home(root.join("home-a"));
8165
    write(&root.join("a"), "f.txt", b"one\n");
8166
    a.commit("one", &[]).unwrap();
8167
    a.push("origin", false).unwrap();
8168
    let b = Repo::clone(&url, &root.join("b"))
8169
        .unwrap()
8170
        .with_home(root.join("home-b"));
8171
    assert_eq!(b.tracking("origin", "main").unwrap(), Some((0, 0)));
8172
8173
    write(&root.join("a"), "f.txt", b"one\ntwo\n");
8174
    let h2 = a.commit("two", &[]).unwrap();
8175
    a.push("origin", false).unwrap();
8176
    b.fetch("origin").unwrap();
8177
    // Fetched, not pulled: one behind, the change found and placed.
8178
    assert_eq!(b.tracking("origin", "main").unwrap(), Some((0, 1)));
8179
    assert_eq!(b.tracking("origin", "nope").unwrap(), None);
8180
    assert_eq!(
8181
        b.resolve_change(&format!("#{}", &h2.to_hex()[..12]))
8182
            .unwrap(),
8183
        h2
8184
    );
8185
    assert_eq!(
8186
        b.remote_only_location(&h2).unwrap().as_deref(),
8187
        Some("origin/main")
8188
    );
8189
    // Fetching again changes nothing: still behind, which is what the
8190
    // CLI now says rather than "up to date".
8191
    b.fetch("origin").unwrap();
8192
    assert_eq!(b.tracking("origin", "main").unwrap(), Some((0, 1)));
8193
    b.pull("origin").unwrap();
8194
    assert_eq!(b.tracking("origin", "main").unwrap(), Some((0, 0)));
8195
    assert_eq!(b.remote_only_location(&h2).unwrap(), None);
8196
8197
    // One remote, not called origin: it is the default.
8198
    let mut c = Repo::init(&root.join("c")).unwrap();
8199
    assert_eq!(c.default_remote(), "origin");
8200
    c.config.set("remote.earth.url", &url).unwrap();
8201
    assert_eq!(c.default_remote(), "earth");
8202
    c.config.set("remote.origin.url", &url).unwrap();
8203
    assert_eq!(c.default_remote(), "origin");
8204
}
8205
8206
/// oxygen#57: a clone from a relative local path records the remote as an
8207
/// absolute path, so fetch still finds it from inside the clone.
8208
#[test]
8209
fn a_clone_from_a_relative_path_records_it_absolute() {
8210
    hermetic();
8211
    let dir = tempfile::tempdir().unwrap();
8212
    let root = dir.path();
8213
    Repo::init(&root.join("origin")).unwrap();
8214
    let rel = crate::protocol::stored_url("relative/repo");
8215
    assert!(std::path::Path::new(&rel).is_absolute(), "{rel}");
8216
    assert_eq!(
8217
        crate::protocol::stored_url("https://hub.example/o/n"),
8218
        "https://hub.example/o/n"
8219
    );
8220
    assert!(crate::protocol::stored_url("file://x").starts_with("file:///"));
8221
    assert!(crate::protocol::stored_url("dir://x").starts_with("dir:///"));
8222
    // A bucket is kept as written: it is not a path.
8223
    assert_eq!(
8224
        crate::protocol::stored_url("s3://bucket/prefix?profile=p"),
8225
        "s3://bucket/prefix?profile=p"
8226
    );
8227
    let url = root.join("origin").to_string_lossy().to_string();
8228
    let b = Repo::clone(&url, &root.join("b")).unwrap();
8229
    assert_eq!(b.config.remotes["origin"], url);
8230
    b.fetch("origin").unwrap();
8231
}
8232
8233
/// oxygen#60 and #61: a workspace added on a bookmark is on that bookmark,
8234
/// and gets its subrepos at their pins from this workspace's copies, with
8235
/// their remotes pointing where the subrepos come from.
8236
#[test]
8237
fn a_workspace_added_on_a_bookmark_is_on_it_with_its_subrepos() {
8238
    hermetic();
8239
    let dir = tempfile::tempdir().unwrap();
8240
    let root = dir.path();
8241
    Repo::init(&root.join("lib-origin")).unwrap();
8242
    let lib_url = root.join("lib-origin").to_string_lossy().to_string();
8243
    let lib = Repo::clone(&lib_url, &root.join("lib"))
8244
        .unwrap()
8245
        .with_home(root.join("home"));
8246
    write(&root.join("lib"), "lib.txt", b"v1\n");
8247
    let l1 = lib.commit("lib v1", &[]).unwrap();
8248
    assert!(lib.push("origin", false).unwrap()[0].ok);
8249
8250
    let app_dir = root.join("app");
8251
    let app = Repo::init(&app_dir).unwrap().with_home(root.join("home"));
8252
    write(&app_dir, "main.txt", b"app\n");
8253
    app.submodule_add(&lib_url, "libs/lib", None).unwrap();
8254
    app.commit("app with lib", &[]).unwrap();
8255
    // A second bookmark, and the main workspace on another.
8256
    app.bookmark_create("develop", None).unwrap();
8257
    app.bookmark_create("feature", None).unwrap();
8258
    let mut app = app;
8259
    app.bookmark_switch("feature", false).unwrap();
8260
    assert_eq!(app.config.bookmark, "feature");
8261
8262
    // The library's origin goes away: the subrepo must come from here.
8263
    std::fs::rename(root.join("lib-origin"), root.join("lib-origin-gone")).unwrap();
8264
    let heads = app.resolve_heads("develop").unwrap();
8265
    let ws = app
8266
        .workspace_add_on(&root.join("ws"), Some(&heads), Some("develop"))
8267
        .unwrap();
8268
    assert_eq!(
8269
        ws.config.bookmark, "develop",
8270
        "the new workspace is on develop"
8271
    );
8272
    assert_eq!(
8273
        app.config.bookmark, "feature",
8274
        "and this one stays on its own"
8275
    );
8276
    let sub = Repo::open(&root.join("ws/libs/lib")).unwrap();
8277
    assert_eq!(
8278
        sub.config.remotes["origin"], lib_url,
8279
        "its origin is the subrepo's URL"
8280
    );
8281
    assert_eq!(sub.bookmark_heads().unwrap(), vec![l1], "at its pin");
8282
    assert_eq!(
8283
        std::fs::read(root.join("ws/libs/lib/lib.txt")).unwrap(),
8284
        b"v1\n"
8285
    );
8286
}
8287
8288
/// Revsets (docs/revset_query_language.md): symbols, relations, set
8289
/// operators and the predicates, over a small graph with two heads and
8290
/// a rename.
8291
#[test]
8292
fn revsets_select_changes_by_relation_author_text_date_and_path() {
8293
    hermetic();
8294
    let dir = tempfile::tempdir().unwrap();
8295
    let root = dir.path();
8296
    let mut repo = Repo::init(root).unwrap().with_home(root.join("home"));
8297
    repo.create_identity("Ada", "[email protected]", IdentityScope::User)
8298
        .unwrap();
8299
    write(root, "src/a.rs", b"one\n");
8300
    let a = repo.commit("first: add a", &[]).unwrap();
8301
    write(root, "src/a.rs", b"one\ntwo\n");
8302
    let b = repo.commit("second: grow a", &[]).unwrap();
8303
    // A second head, independent of b: a new file on top of a.
8304
    repo.checkout(&[a], false, "checkout a").unwrap();
8305
    write(root, "docs/notes.md", b"notes\n");
8306
    let c = repo.commit("third: notes", &[]).unwrap();
8307
    // Back to both heads, then rename a.rs: the node keeps its identity.
8308
    repo.checkout(&repo.bookmark_heads().unwrap(), false, "checkout main")
8309
        .unwrap();
8310
    fs::remove_file(root.join("src/a.rs")).unwrap();
8311
    write(root, "src/z.rs", b"one\ntwo\n");
8312
    let d = repo.commit("fourth: rename a to z", &[]).unwrap();
8313
    let wc = repo.working_copy().unwrap().0;
8314
    // A saved revset is checked when set.
8315
    repo.set_user_config("revset.mine", "author(me) & ::main")
8316
        .unwrap();
8317
    assert!(repo.set_user_config("revset.bad", "a &").is_err());
8318
    let set = |src: &str| -> Vec<ChangeHash> {
8319
        let mut v = repo.revset(src).unwrap().hashes;
8320
        v.sort();
8321
        v
8322
    };
8323
    let sorted = |hs: &[ChangeHash]| -> Vec<ChangeHash> {
8324
        let mut v = hs.to_vec();
8325
        v.sort();
8326
        v
8327
    };
8328
8329
    // Changes commute: a new file depends on nothing and the rename on the
8330
    // file's creation, so the graph is a, b->a, d->a, c, and the working
8331
    // copy on the three heads b, c, d.
8332
    let heads = sorted(&repo.bookmark_heads().unwrap());
8333
    let meta = |h: &ChangeHash| repo.store().get_change_meta(h).unwrap();
8334
    assert!(heads.contains(&d) && heads.contains(&c));
8335
    // Symbols and closures.
8336
    assert_eq!(set("main"), heads);
8337
    assert_eq!(set("::main"), sorted(&[a, b, c, d]));
8338
    assert_eq!(set("@"), vec![wc]);
8339
    assert_eq!(set("::@"), sorted(&[a, b, c, d, wc]));
8340
    assert_eq!(set(&format!("::#{}", b.short(12))), sorted(&[a, b]));
8341
    assert_eq!(set(&format!("#{}::", a.short(12))), sorted(&[a, b, d, wc]));
8342
    assert_eq!(
8343
        set(&format!("#{}::#{}", a.short(12), b.short(12))),
8344
        sorted(&[a, b])
8345
    );
8346
    // Ranges: what main has beyond b, and `..` forms.
8347
    assert_eq!(set(&format!("#{}..main", b.short(12))), sorted(&[c, d]));
8348
    assert_eq!(set(&format!("#{}..", c.short(12))), sorted(&[a, b, d, wc]));
8349
    assert_eq!(set("..main"), sorted(&[a, b, c, d]));
8350
    // Operators and precedence: ~ binds tighter than &, & than |.
8351
    assert_eq!(
8352
        set(&format!("::main ~ #{}", d.short(12))),
8353
        sorted(&[a, b, c])
8354
    );
8355
    assert_eq!(
8356
        set(&format!("::main & #{} | #{}", b.short(12), c.short(12))),
8357
        sorted(&[b, c])
8358
    );
8359
    assert_eq!(set("all() ~ ::main"), vec![wc]);
8360
    // Relations.
8361
    let mut head_deps: Vec<ChangeHash> = heads.iter().flat_map(|h| meta(h).deps).collect();
8362
    head_deps.sort();
8363
    head_deps.dedup();
8364
    assert_eq!(set("deps(main)"), head_deps);
8365
    let on_a: Vec<ChangeHash> = [b, c, d]
8366
        .into_iter()
8367
        .filter(|h| meta(h).deps.contains(&a))
8368
        .collect();
8369
    assert_eq!(set(&format!("dependents(#{})", a.short(12))), sorted(&on_a));
8370
    assert_eq!(set("heads(::main)"), heads);
8371
    assert_eq!(set("roots(::main)"), sorted(&[a, c]));
8372
    assert_eq!(
8373
        set(&format!(
8374
            "heads(#{} | #{} | #{})",
8375
            a.short(12),
8376
            b.short(12),
8377
            c.short(12)
8378
        )),
8379
        sorted(&[b, c])
8380
    );
8381
    assert_eq!(set("latest(::main, 1)"), vec![d]);
8382
    assert_eq!(set("kind(working-copy)"), vec![wc]);
8383
    assert_eq!(set("none()"), vec![]);
8384
    // Predicates: author by name, email, key prefix and `me`.
8385
    let key = repo.config.author_key.unwrap();
8386
    assert_eq!(set("author(ada) & ::main"), sorted(&[a, b, c, d]));
8387
    assert_eq!(set("author(\"[email protected]\") & ::main").len(), 4);
8388
    assert_eq!(set(&format!("author({}) & ::main", key.short(12))).len(), 4);
8389
    assert_eq!(set("author(me) & ::main").len(), 4);
8390
    assert_eq!(set("author(nobody)"), vec![]);
8391
    assert_eq!(set("description(notes)"), vec![c]);
8392
    assert_eq!(set("description(\"rename a\")"), vec![d]);
8393
    assert_eq!(set("date(-1h..) & ::main").len(), 4);
8394
    assert_eq!(set("date(..2000-01-01)"), vec![]);
8395
    // touches follows the node through the rename, in the current state.
8396
    assert_eq!(set("touches(\"src/z.rs\")"), sorted(&[a, b, d]));
8397
    assert_eq!(set("touches(\"src/**\") & ::main"), sorted(&[a, b, d]));
8398
    assert_eq!(set("touches(\"docs/*\")"), vec![c]);
8399
    assert_eq!(set("touches(\"nothing/*\")"), vec![]);
8400
    // Newest first in the result order.
8401
    assert_eq!(repo.revset("::main").unwrap().hashes[0], d);
8402
    // The saved revset, and errors that say what is wrong.
8403
    assert_eq!(set("mine()").len(), 4);
8404
    let e = repo.revset("nosuch()").unwrap_err().to_string();
8405
    assert!(e.contains("unknown function nosuch()"), "{e}");
8406
    let e = repo.revset("main &").unwrap_err().to_string();
8407
    assert!(e.contains("at character"), "{e}");
8408
    let e = repo.revset("zzzz").unwrap_err().to_string();
8409
    assert!(e.contains("no change matches"), "{e}");
8410
    let e = repo
8411
        .revset_with_budget("::main", std::time::Duration::ZERO)
8412
        .unwrap_err()
8413
        .to_string();
8414
    assert!(e.contains("budget"), "{e}");
8415
    // The log entries carry the bookmark's heads and the working copy.
8416
    let entries = repo.log_revset("::@").unwrap();
8417
    assert!(entries[0].is_working_copy && entries.iter().any(|e| e.is_head && e.hash == d));
8418
    // Trust predicates (§2.4): nothing is signed yet (core.sign = seal, no
8419
    // push); then a signed change, a tag, and a revocation.
8420
    assert_eq!(set("unsigned() & ::main"), sorted(&[a, b, c, d]));
8421
    assert_eq!(set("signed_by(me)"), vec![]);
8422
    repo.sign_change(&d).unwrap();
8423
    assert_eq!(set("signed_by(me)"), vec![d]);
8424
    assert_eq!(set("signed_by([email protected])"), vec![d]);
8425
    assert_eq!(set(&format!("signed_by({})", key.short(12))), vec![d]);
8426
    assert_eq!(set("unsigned() & ::main"), sorted(&[a, b, c]));
8427
    assert_eq!(set("delegated()"), vec![]);
8428
    assert_eq!(set("revoked()"), vec![]);
8429
    assert_eq!(set("attested(tag)"), vec![]);
8430
    repo.tag_create("v1", &[b], "first").unwrap();
8431
    assert_eq!(set("attested(tag)"), sorted(&[a, b]));
8432
    assert_eq!(set("attested(tag) & unsigned()"), sorted(&[a, b]));
8433
    assert_eq!(set("attested(receipt)"), vec![]);
8434
    assert_eq!(set("built(test)"), vec![]);
8435
    let e = repo.revset("attested(seal)").unwrap_err().to_string();
8436
    assert!(e.contains("tag, receipt or ref"), "{e}");
8437
    repo.revoke_identity(&key, "test").unwrap();
8438
    assert_eq!(set("revoked()"), vec![d]);
8439
    assert_eq!(set("signed_by(me) ~ revoked()"), vec![]);
8440
}
8441
8442
#[test]
8443
fn a_rotation_is_recorded_wherever_the_old_key_was_named() {
8444
    let dir = tempfile::tempdir().unwrap();
8445
    let root = dir.path();
8446
    let home = root.join("home");
8447
    // Ada's identity lives in the user file; repository `a` pins the same
8448
    // key in its own file, repository `b` names none.
8449
    let mut a = Repo::init(&root.join("a")).unwrap().with_home(&home);
8450
    let (key, _) = a
8451
        .create_identity("Ada", "[email protected]", IdentityScope::User)
8452
        .unwrap();
8453
    a.config.set("author.key", &key.to_hex()).unwrap();
8454
    a.save_config().unwrap();
8455
    let agent = SecretKey::generate().identity("Agent", "[email protected]", 1);
8456
    let r = a
8457
        .delegate_add(agent.clone(), crate::identity::Scope::CHANGES, None)
8458
        .unwrap();
8459
    assert_eq!(
8460
        read_config_file(&home.join("config.toml")).unwrap()["author.key"],
8461
        r.new.to_hex(),
8462
        "the user file follows"
8463
    );
8464
    assert_eq!(
8465
        read_config_file(&root.join("a/.oxy/config")).unwrap()["author.key"],
8466
        r.new.to_hex(),
8467
        "the pinning repository follows"
8468
    );
8469
    let b = Repo::init(&root.join("b")).unwrap().with_home(&home);
8470
    assert_eq!(
8471
        b.config.author_key,
8472
        Some(r.new),
8473
        "a checkout without a pin follows the user file"
8474
    );
8475
    // A repository-scoped identity leaves the user file alone.
8476
    let other_home = root.join("home2");
8477
    let mut c = Repo::init(&root.join("c")).unwrap().with_home(&other_home);
8478
    let (ck, _) = c
8479
        .create_identity("Cy", "[email protected]", IdentityScope::Repo)
8480
        .unwrap();
8481
    assert!(!other_home.join("config.toml").exists());
8482
    let r2 = c.rotate_identity().unwrap();
8483
    assert_ne!(r2.new, ck);
8484
    assert_eq!(
8485
        read_config_file(&root.join("c/.oxy/config")).unwrap()["author.key"],
8486
        r2.new.to_hex()
8487
    );
8488
    assert!(
8489
        !other_home.join("config.toml").exists(),
8490
        "a repository-scoped identity stays repository-scoped"
8491
    );
8492
    // Several delegates in one rotation; a repeat is refused.
8493
    let (d1, d2) = (
8494
        SecretKey::generate().identity("D1", "d1@x", 1),
8495
        SecretKey::generate().identity("D2", "d2@x", 1),
8496
    );
8497
    let r3 = c
8498
        .delegate_add_many(vec![d1.clone(), d2], crate::identity::Scope::CHANGES, None)
8499
        .unwrap();
8500
    assert_eq!(r3.identity.delegates.len(), 2);
8501
    assert!(c
8502
        .delegate_add(d1, crate::identity::Scope::CHANGES, None)
8503
        .is_err());
8504
}
8505
8506
/// Two unrelated histories that both add the same file, joined by two
8507
/// independent merges on two branches, then those branches merged: Git
8508
/// merges identical additions cleanly, and the import must too (#71,
8509
/// found in VS Code's history).
8510
#[test]
8511
fn git_import_joins_unrelated_histories_that_add_the_same_file() {
8512
    // Batches of one: every merge renders apart from the state, where a
8513
    // file whose graph the state had built came out empty (#71).
8514
    crate::repo::git::set_merge_batch_for_tests(Some(1));
8515
    hermetic();
8516
    if std::process::Command::new("git")
8517
        .arg("--version")
8518
        .output()
8519
        .is_err()
8520
    {
8521
        eprintln!("git not installed; skipping");
8522
        return;
8523
    }
8524
    let dir = tempfile::tempdir().unwrap();
8525
    let root = dir.path();
8526
    let g = root.join("src.git");
8527
    fs::create_dir_all(&g).unwrap();
8528
    let git = |args: &[&str]| -> String {
8529
        let out = std::process::Command::new("git")
8530
            .arg("-C")
8531
            .arg(&g)
8532
            .args([
8533
                "-c",
8534
                "user.name=Grace",
8535
                "-c",
8536
                "[email protected]",
8537
                "-c",
8538
                "commit.gpgsign=false",
8539
            ])
8540
            .args(args)
8541
            .output()
8542
            .unwrap();
8543
        assert!(
8544
            out.status.success(),
8545
            "git {args:?}: {}",
8546
            String::from_utf8_lossy(&out.stderr)
8547
        );
8548
        String::from_utf8_lossy(&out.stdout).trim().to_string()
8549
    };
8550
    let text = b"/* header */\nconst a = 1;\nconst b = 2;\n";
8551
    // History A: main.
8552
    git(&["init", "-q", "-b", "main"]);
8553
    write(&g, "gulpfile.js", text);
8554
    write(&g, "a.txt", b"a\n");
8555
    git(&["add", "."]);
8556
    git(&["commit", "-q", "-m", "A root"]);
8557
    // History B: an unrelated root adding the same file, identical.
8558
    git(&["checkout", "-q", "--orphan", "fork"]);
8559
    git(&["rm", "-q", "-r", "--cached", "."]);
8560
    for f in ["gulpfile.js", "a.txt"] {
8561
        let _ = fs::remove_file(g.join(f));
8562
    }
8563
    write(&g, "gulpfile.js", text);
8564
    write(&g, "b.txt", b"b\n");
8565
    git(&["add", "."]);
8566
    git(&["commit", "-q", "-m", "B root"]);
8567
    // Two branches from main, each joining B on its own.
8568
    git(&["checkout", "-q", "-b", "one", "main"]);
8569
    git(&[
8570
        "merge",
8571
        "-q",
8572
        "--no-ff",
8573
        "--allow-unrelated-histories",
8574
        "-m",
8575
        "join on one",
8576
        "fork",
8577
    ]);
8578
    git(&["checkout", "-q", "-b", "two", "main"]);
8579
    write(&g, "a.txt", b"a\ntwo\n");
8580
    git(&["commit", "-q", "-am", "work on two"]);
8581
    git(&[
8582
        "merge",
8583
        "-q",
8584
        "--no-ff",
8585
        "--allow-unrelated-histories",
8586
        "-m",
8587
        "join on two",
8588
        "fork",
8589
    ]);
8590
    // Then the two joins meet, and the file is reformatted after.
8591
    git(&["checkout", "-q", "main"]);
8592
    git(&["merge", "-q", "--no-ff", "-m", "merge one", "one"]);
8593
    git(&["merge", "-q", "--no-ff", "-m", "merge two", "two"]);
8594
    write(
8595
        &g,
8596
        "gulpfile.js",
8597
        b"/* header */\nconst a = 1;\nconst b = 3;\n",
8598
    );
8599
    git(&["commit", "-q", "-am", "after"]);
8600
8601
    let dest = root.join("dest");
8602
    let repo = Repo::init(&dest).unwrap().with_home(root.join("home"));
8603
    repo.import_git(&g, "main").unwrap();
8604
    let v = repo.verify_git_import(&g, "main").unwrap();
8605
    assert!(v.mismatches.is_empty(), "{:?}", v.mismatches);
8606
    assert_eq!(
8607
        fs::read(dest.join("gulpfile.js")).unwrap(),
8608
        b"/* header */\nconst a = 1;\nconst b = 3;\n"
8609
    );
8610
}
8611
8612
/// As above, but the two joins keep different copies (each branch had a
8613
/// different version when it joined), and later work edits each copy:
8614
/// the shape of VS Code's c67ef57cda90 (#71).
8615
#[test]
8616
fn git_import_joins_where_each_join_kept_a_different_copy() {
8617
    // Batches of one: every merge renders apart from the state, where a
8618
    // file whose graph the state had built came out empty (#71).
8619
    crate::repo::git::set_merge_batch_for_tests(Some(1));
8620
    hermetic();
8621
    if std::process::Command::new("git")
8622
        .arg("--version")
8623
        .output()
8624
        .is_err()
8625
    {
8626
        eprintln!("git not installed; skipping");
8627
        return;
8628
    }
8629
    let dir = tempfile::tempdir().unwrap();
8630
    let root = dir.path();
8631
    let g = root.join("src.git");
8632
    fs::create_dir_all(&g).unwrap();
8633
    let run = |args: &[&str]| {
8634
        std::process::Command::new("git")
8635
            .arg("-C")
8636
            .arg(&g)
8637
            .args([
8638
                "-c",
8639
                "user.name=Grace",
8640
                "-c",
8641
                "[email protected]",
8642
                "-c",
8643
                "commit.gpgsign=false",
8644
            ])
8645
            .args(args)
8646
            .output()
8647
            .unwrap()
8648
    };
8649
    let git = |args: &[&str]| -> String {
8650
        let out = run(args);
8651
        assert!(
8652
            out.status.success(),
8653
            "git {args:?}: {}",
8654
            String::from_utf8_lossy(&out.stderr)
8655
        );
8656
        String::from_utf8_lossy(&out.stdout).trim().to_string()
8657
    };
8658
    git(&["init", "-q", "-b", "main"]);
8659
    write(
8660
        &g,
8661
        "gulpfile.js",
8662
        b"/* header */\nconst a = 1;\nconst b = 2;\n",
8663
    );
8664
    git(&["add", "."]);
8665
    git(&["commit", "-q", "-m", "A root"]);
8666
    write(
8667
        &g,
8668
        "gulpfile.js",
8669
        b"/* header */\nconst a = 1;\n\nconst b = 2;\n",
8670
    );
8671
    git(&["commit", "-q", "-am", "whitespace"]);
8672
    git(&["checkout", "-q", "--orphan", "fork"]);
8673
    git(&["rm", "-q", "-r", "--cached", "."]);
8674
    let _ = fs::remove_file(g.join("gulpfile.js"));
8675
    write(
8676
        &g,
8677
        "gulpfile.js",
8678
        b"/* header */\nconst a = 1;\nconst b = 2;\nconst c = 3;\n",
8679
    );
8680
    git(&["add", "."]);
8681
    git(&["commit", "-q", "-m", "B root"]);
8682
    // Branch one joins B keeping main's copy; branch two keeps B's.
8683
    for (branch, keep) in [("one", "ours"), ("two", "theirs")] {
8684
        git(&["checkout", "-q", "-b", branch, "main"]);
8685
        let _ = run(&[
8686
            "merge",
8687
            "-q",
8688
            "--no-ff",
8689
            "--allow-unrelated-histories",
8690
            "-m",
8691
            "join",
8692
            "fork",
8693
        ]);
8694
        git(&["checkout", &format!("--{keep}"), "gulpfile.js"]);
8695
        git(&["add", "gulpfile.js"]);
8696
        git(&["commit", "-q", "-m", &format!("join on {branch}")]);
8697
    }
8698
    // Each branch then edits its copy.
8699
    git(&["checkout", "-q", "one"]);
8700
    write(
8701
        &g,
8702
        "gulpfile.js",
8703
        b"/* header */\nconst a = 1;\n\nconst b = 2;\n// tslint\n",
8704
    );
8705
    git(&["commit", "-q", "-am", "tslint on one"]);
8706
    git(&["checkout", "-q", "two"]);
8707
    write(
8708
        &g,
8709
        "gulpfile.js",
8710
        b"/* header */\nconst a = 1;\nconst b = 2;\nconst c = 3;\n// fmt\n",
8711
    );
8712
    write(&g, "extra.txt", b"x\n");
8713
    write(&g, "more.txt", b"m\n");
8714
    git(&["add", "."]);
8715
    git(&["commit", "-q", "-am", "fmt on two"]);
8716
    // They meet: resolved by hand.
8717
    git(&["checkout", "-q", "one"]);
8718
    let _ = run(&["merge", "-q", "--no-ff", "-m", "merge two", "two"]);
8719
    write(
8720
        &g,
8721
        "gulpfile.js",
8722
        b"/* header */\nconst a = 1;\nconst b = 2;\nconst c = 3;\n// tslint\n// fmt\n",
8723
    );
8724
    git(&["add", "gulpfile.js"]);
8725
    git(&["commit", "-q", "-m", "merge two into one"]);
8726
8727
    let dest = root.join("dest");
8728
    let repo = Repo::init(&dest).unwrap().with_home(root.join("home"));
8729
    repo.import_git(&g, "one").unwrap();
8730
    let v = repo.verify_git_import(&g, "one").unwrap();
8731
    assert!(v.mismatches.is_empty(), "{:?}", v.mismatches);
8732
}
8733
8734
/// oxygen#68: on a store that is not this disk's directory, the operation
8735
/// head is the store's reference record, moved by compare-and-swap. Two
8736
/// handles recording from the same head both get through, merged; a swap
8737
/// from a stale version is refused; a second repository cannot start on a
8738
/// store that already holds one.
8739
#[test]
8740
fn over_a_store_the_operation_head_moves_by_compare_and_swap() {
8741
    use crate::strata::{MemoryStore, Store as _};
8742
    let backend = std::sync::Arc::new(MemoryStore::new());
8743
    crate::store::TEST_BACKEND.with(|t| *t.borrow_mut() = Some(backend.clone()));
8744
    let dir = tempfile::tempdir().unwrap();
8745
    let a = Repo::init(dir.path()).unwrap();
8746
    assert!(
8747
        !dir.path().join(".oxy/ops/head").exists(),
8748
        "the head is not a file"
8749
    );
8750
    let (h0, op0) = a.head_op().unwrap();
8751
    let record = backend
8752
        .read_ref(HEAD_RECORD)
8753
        .unwrap()
8754
        .expect("the head is the store's record");
8755
    assert_eq!(String::from_utf8(record.0).unwrap(), h0.to_hex());
8756
8757
    let b = Repo::open(dir.path()).unwrap();
8758
    let state = a.store.put_state(&StateObject::new(vec![])).unwrap();
8759
    let mut va = op0.view.clone();
8760
    va.bookmarks.insert("from-a".into(), state);
8761
    let mut vb = op0.view.clone();
8762
    vb.bookmarks.insert("from-b".into(), state);
8763
    let rb = b.record_op(&[h0], "bookmark from-b", vb).unwrap();
8764
    assert_eq!(b.head_ref().unwrap(), rb);
8765
    // a recorded from h0 too: the head moved, so the two are merged.
8766
    let ra = a.record_op(&[h0], "bookmark from-a", va).unwrap();
8767
    let (head, op) = Repo::open(dir.path()).unwrap().head_op().unwrap();
8768
    assert_eq!(head, ra);
8769
    assert!(
8770
        op.command.ends_with("(merged with a concurrent operation)"),
8771
        "{}",
8772
        op.command
8773
    );
8774
    assert_eq!(op.parents, vec![rb, op.parents[1]]);
8775
    assert!(op.view.bookmarks.contains_key("from-a") && op.view.bookmarks.contains_key("from-b"));
8776
8777
    // A swap from a version that is no longer current moves nothing.
8778
    let (h, v) = a.read_head().unwrap();
8779
    assert!(b.swap_head(&rb, v.as_ref()).unwrap());
8780
    assert!(!a.swap_head(&h, v.as_ref()).unwrap(), "stale");
8781
    a.refresh().unwrap();
8782
    assert_eq!(a.head_ref().unwrap(), rb);
8783
8784
    let other = tempfile::tempdir().unwrap();
8785
    let err = Repo::init(other.path())
8786
        .err()
8787
        .expect("the store already holds a log")
8788
        .to_string();
8789
    assert!(
8790
        err.contains("already holds a repository's operation log"),
8791
        "{err}"
8792
    );
8793
    crate::store::TEST_BACKEND.with(|t| *t.borrow_mut() = None);
8794
}
8795
8796
/// oxygen#68: a repository kept on a store (`storage.url`) holds its
8797
/// objects and operation head there, with `.oxy/cache` in front: it works
8798
/// as one on disk does, reopens, and survives losing its cache.
8799
#[test]
8800
fn a_repository_runs_on_a_store_with_a_cache_in_front() {
8801
    hermetic();
8802
    if std::env::var_os("OXY_STORE_BACKEND").is_some() {
8803
        return;
8804
    }
8805
    let dir = tempfile::tempdir().unwrap();
8806
    let (root, bucket) = (dir.path().join("work"), dir.path().join("bucket"));
8807
    let url = format!("dir://{}", bucket.display());
8808
    let repo = Repo::init_on(&root, [7; 16], Some(&url)).unwrap();
8809
    assert_eq!(repo.config.storage_url.as_deref(), Some(url.as_str()));
8810
    write(&root, "a.txt", b"one\n");
8811
    let h1 = repo.commit("First", &[]).unwrap();
8812
    write(&root, "a.txt", b"one\ntwo\n");
8813
    let h2 = repo.commit("Second", &[]).unwrap();
8814
    assert!(
8815
        !root.join(".oxy/ops/head").exists(),
8816
        "the head is in the store"
8817
    );
8818
    assert!(bucket.join("ops/head").is_file());
8819
    assert!(root.join(".oxy/cache").is_dir());
8820
    drop(repo);
8821
8822
    // Reopened, and again with no cache at all: everything comes from the store.
8823
    for drop_cache in [false, true] {
8824
        if drop_cache {
8825
            std::fs::remove_dir_all(root.join(".oxy/cache")).unwrap();
8826
        }
8827
        let repo = Repo::open(&root).unwrap();
8828
        let log: Vec<String> = repo
8829
            .op_log()
8830
            .unwrap()
8831
            .into_iter()
8832
            .map(|(_, op)| op.command)
8833
            .collect();
8834
        assert!(log.len() >= 3, "{log:?}");
8835
        assert_eq!(repo.store().get_change(&h1).unwrap().message, "First");
8836
        let heads = repo
8837
            .store()
8838
            .get_state(&repo.view().unwrap().bookmarks["main"])
8839
            .unwrap()
8840
            .heads;
8841
        assert_eq!(heads, vec![h2]);
8842
        assert_eq!(
8843
            repo.load_state(&heads).unwrap().materialize().files.len(),
8844
            1
8845
        );
8846
    }
8847
8848
    // A second repository cannot start on the same store.
8849
    let err = Repo::init_on(&dir.path().join("other"), [8; 16], Some(&url))
8850
        .err()
8851
        .unwrap()
8852
        .to_string();
8853
    assert!(
8854
        err.contains("already holds a repository's operation log"),
8855
        "{err}"
8856
    );
8857
    let err = Repo::init_on(&dir.path().join("third"), [9; 16], Some("nope://x"))
8858
        .err()
8859
        .unwrap()
8860
        .to_string();
8861
    assert!(err.contains("cannot open that kind of store"), "{err}");
8862
}
8863
8864
/// oxygen#75: the prompt's quick check agrees with status in a repository
8865
/// with a subrepo: clean after a commit, dirty when the subrepo moves to
8866
/// another state, clean again once that pin is committed. (It compared the
8867
/// subrepo's directory as if it were a file, so it was always dirty.)
8868
#[test]
8869
fn the_quick_dirty_check_compares_a_subrepo_by_its_pin() {
8870
    hermetic();
8871
    let dir = tempfile::tempdir().unwrap();
8872
    let root = dir.path();
8873
    let _lib_origin = Repo::init(&root.join("lib-origin")).unwrap();
8874
    let lib_url = root.join("lib-origin").to_string_lossy().to_string();
8875
    let lib = Repo::clone(&lib_url, &root.join("lib"))
8876
        .unwrap()
8877
        .with_home(root.join("home"));
8878
    write(&root.join("lib"), "lib.txt", b"v1\n");
8879
    lib.commit("lib v1", &[]).unwrap();
8880
    assert!(lib.push("origin", false).unwrap()[0].ok);
8881
    let app_dir = root.join("app");
8882
    let app = Repo::init(&app_dir).unwrap().with_home(root.join("home"));
8883
    write(&app_dir, "main.txt", b"app\n");
8884
    app.submodule_add(&lib_url, "libs/lib", None).unwrap();
8885
    app.commit("app with lib", &[]).unwrap();
8886
    // Out of the racy window, so the stat-only path decides.
8887
    std::thread::sleep(std::time::Duration::from_millis(2100));
8888
    let reopen = || Repo::open(&app_dir).unwrap();
8889
    assert_eq!(
8890
        reopen().quick_dirty().unwrap(),
8891
        Some(false),
8892
        "clean, as status says"
8893
    );
8894
    let nested = Repo::open(&app_dir.join("libs/lib")).unwrap();
8895
    write(&app_dir.join("libs/lib"), "lib.txt", b"v2\n");
8896
    nested.commit("lib v2", &[]).unwrap();
8897
    assert_eq!(
8898
        reopen().quick_dirty().unwrap(),
8899
        Some(true),
8900
        "the subrepo moved"
8901
    );
8902
    reopen().commit("pin lib v2", &[]).unwrap();
8903
    std::thread::sleep(std::time::Duration::from_millis(2100));
8904
    assert_eq!(
8905
        reopen().quick_dirty().unwrap(),
8906
        Some(false),
8907
        "the new pin is committed"
8908
    );
8909
}
8910
8911
#[test]
8912
fn a_module_entry_that_was_never_added_is_reported_as_unpinned() {
8913
    // oxygen#72: a .oxymodules section with no subrepo behind it.
8914
    hermetic();
8915
    let dir = tempfile::tempdir().unwrap();
8916
    let root = dir.path();
8917
    let _lib_origin = Repo::init(&root.join("lib-origin")).unwrap();
8918
    let lib_url = root.join("lib-origin").to_string_lossy().to_string();
8919
    let lib = Repo::clone(&lib_url, &root.join("lib"))
8920
        .unwrap()
8921
        .with_home(root.join("home"));
8922
    write(&root.join("lib"), "lib.txt", b"v1\n");
8923
    lib.commit("lib v1", &[]).unwrap();
8924
    assert!(lib.push("origin", false).unwrap()[0].ok);
8925
    let app_dir = root.join("app");
8926
    let app = Repo::init(&app_dir).unwrap().with_home(root.join("home"));
8927
    write(
8928
        &app_dir,
8929
        ".oxymodules",
8930
        format!("[libs/lib]\nurl = {lib_url}\n").as_bytes(),
8931
    );
8932
    let unpinned = app.unpinned_modules().unwrap();
8933
    assert_eq!(unpinned.len(), 1);
8934
    assert_eq!(unpinned[0].0, "libs/lib");
8935
    assert_eq!(unpinned[0].1.url, lib_url);
8936
    assert!(app.submodule_update(true, &[]).unwrap().is_empty());
8937
    app.submodule_add(&lib_url, "libs/lib", None).unwrap();
8938
    assert!(app.unpinned_modules().unwrap().is_empty(), "added now");
8939
}
8940
8941
#[test]
8942
fn the_bookmark_revset_function_names_only_bookmarks() {
8943
    // oxygen#73: bookmark(NAME) is a bookmark's heads, never a tag or prefix.
8944
    hermetic();
8945
    let dir = tempfile::tempdir().unwrap();
8946
    let repo = Repo::init(dir.path()).unwrap();
8947
    write(dir.path(), "a.txt", b"a\n");
8948
    let a = repo.commit("A", &[]).unwrap();
8949
    write(dir.path(), "b.txt", b"b\n");
8950
    let b = repo.commit("B", &[]).unwrap();
8951
    let mut heads = repo.revset("bookmark(main)").unwrap().hashes;
8952
    heads.sort();
8953
    let mut want = repo.bookmark_heads().unwrap();
8954
    want.sort();
8955
    assert_eq!(heads, want);
8956
    assert!(heads.contains(&b));
8957
    assert_eq!(repo.revset("main").unwrap().hashes.len(), heads.len());
8958
    // A change prefix is a symbol, not a bookmark.
8959
    let prefix = repo.store().get_change_meta(&a).unwrap().change_id.short(8);
8960
    assert!(repo.revset(&prefix).is_ok());
8961
    let e = repo
8962
        .revset(&format!("bookmark({prefix})"))
8963
        .unwrap_err()
8964
        .to_string();
8965
    assert!(e.contains("no such bookmark"), "{e}");
8966
}
8967
8968
#[test]
8969
fn carrying_work_over_a_subrepo_already_at_the_target_pin_is_no_conflict() {
8970
    // oxygen#74: a stale state with .oxymodules but no pin, a newer one
8971
    // pinning the subrepo, and the nested repository on disk at that pin.
8972
    hermetic();
8973
    let dir = tempfile::tempdir().unwrap();
8974
    let root = dir.path();
8975
    let _lib_origin = Repo::init(&root.join("lib-origin")).unwrap();
8976
    let lib_url = root.join("lib-origin").to_string_lossy().to_string();
8977
    let lib = Repo::clone(&lib_url, &root.join("lib"))
8978
        .unwrap()
8979
        .with_home(root.join("home"));
8980
    write(&root.join("lib"), "lib.txt", b"v1\n");
8981
    lib.commit("lib v1", &[]).unwrap();
8982
    assert!(lib.push("origin", false).unwrap()[0].ok);
8983
    let app_dir = root.join("app");
8984
    let app = Repo::init(&app_dir).unwrap().with_home(root.join("home"));
8985
    write(&app_dir, "main.txt", b"app\n");
8986
    app.submodule_add(&lib_url, "libs/lib", None).unwrap();
8987
    // The stale state: registered in .oxymodules, never pinned.
8988
    fs::rename(app_dir.join("libs/lib"), root.join("aside")).unwrap();
8989
    app.commit("initial", &[]).unwrap();
8990
    let stale = app.bookmark_heads().unwrap();
8991
    fs::rename(root.join("aside"), app_dir.join("libs/lib")).unwrap();
8992
    app.commit("pin lib", &[]).unwrap();
8993
    let newer = app.bookmark_heads().unwrap();
8994
    app.checkout(&stale, false, "test").unwrap();
8995
    write(&app_dir, "notes.txt", b"mine\n");
8996
    let (_, carried) = app.checkout_carry(&newer, "main", "test").unwrap();
8997
    assert_eq!(carried, vec!["notes.txt".to_string()]);
8998
    assert!(app_dir.join("notes.txt").exists());
8999
}
9000
9001
#[test]
9002
fn a_bookmark_only_behind_its_remote_catches_up() {
9003
    // oxygen#74: switch takes the remote's state rather than a stale one.
9004
    hermetic();
9005
    let dir = tempfile::tempdir().unwrap();
9006
    let root = dir.path();
9007
    let _origin = Repo::init(&root.join("origin")).unwrap();
9008
    let url = root.join("origin").to_string_lossy().to_string();
9009
    let one = Repo::clone(&url, &root.join("one"))
9010
        .unwrap()
9011
        .with_home(root.join("home"));
9012
    write(&root.join("one"), "a.txt", b"a\n");
9013
    one.commit("A", &[]).unwrap();
9014
    assert!(one.push("origin", false).unwrap()[0].ok);
9015
    let two = Repo::clone(&url, &root.join("two"))
9016
        .unwrap()
9017
        .with_home(root.join("home"));
9018
    write(&root.join("two"), "b.txt", b"b\n");
9019
    two.commit("B", &[]).unwrap();
9020
    assert!(two.push("origin", false).unwrap()[0].ok);
9021
    assert_eq!(one.catch_up_bookmark("main").unwrap(), None, "not fetched");
9022
    one.fetch("origin").unwrap();
9023
    assert_eq!(one.catch_up_bookmark("main").unwrap(), Some(1));
9024
    assert_eq!(one.bookmarks().unwrap()[0].behind, Some(0));
9025
    // Local work the remote lacks: left alone.
9026
    write(&root.join("one"), "c.txt", b"c\n");
9027
    one.commit("C", &[]).unwrap();
9028
    write(&root.join("two"), "d.txt", b"d\n");
9029
    two.commit("D", &[]).unwrap();
9030
    assert!(two.push("origin", false).unwrap()[0].ok);
9031
    one.fetch("origin").unwrap();
9032
    assert_eq!(one.catch_up_bookmark("main").unwrap(), None);
9033
}
9034
9035
#[test]
9036
fn a_bookmark_is_compared_with_a_remote_that_has_it_when_there_is_no_origin() {
9037
    // oxygen#83: remotes earth and gcs, origin removed.
9038
    hermetic();
9039
    let dir = tempfile::tempdir().unwrap();
9040
    let root = dir.path();
9041
    let _up = Repo::init(&root.join("up")).unwrap();
9042
    let url = root.join("up").to_string_lossy().to_string();
9043
    let other = Repo::clone(&url, &root.join("other"))
9044
        .unwrap()
9045
        .with_home(root.join("home"));
9046
    write(&root.join("other"), "a.txt", b"a\n");
9047
    other.commit("a", &[]).unwrap();
9048
    assert!(other.push("origin", false).unwrap()[0].ok);
9049
    let mut one = Repo::clone(&url, &root.join("one"))
9050
        .unwrap()
9051
        .with_home(root.join("home"));
9052
    one.config.set("remote.earth.url", &url).unwrap();
9053
    one.config.set("remote.gcs.url", &url).unwrap();
9054
    one.config.set("remote.origin.url", "").unwrap();
9055
    one.save_config().unwrap();
9056
    write(&root.join("other"), "b.txt", b"b\n");
9057
    other.commit("b", &[]).unwrap();
9058
    assert!(other.push("origin", false).unwrap()[0].ok);
9059
    one.fetch("earth").unwrap();
9060
    let b = one
9061
        .bookmarks()
9062
        .unwrap()
9063
        .into_iter()
9064
        .find(|b| b.name == "main")
9065
        .unwrap();
9066
    assert_eq!(
9067
        (b.remote.as_deref(), b.behind),
9068
        (Some("earth"), Some(1)),
9069
        "a stale origin copy is not used"
9070
    );
9071
    assert_eq!(
9072
        one.default_remote(),
9073
        "origin",
9074
        "no default chosen among several"
9075
    );
9076
    let e = one.pull(&one.default_remote()).unwrap_err().to_string();
9077
    assert!(e.contains("earth, gcs") && e.contains("core.remote"), "{e}");
9078
    one.config.set("core.remote", "earth").unwrap();
9079
    assert_eq!(one.default_remote(), "earth");
9080
}
9081
9082
#[test]
9083
fn a_missing_author_identity_says_how_to_fix_it() {
9084
    // oxygen#82: an agent home's author.key naming an identity the
9085
    // repository does not hold.
9086
    hermetic();
9087
    let dir = tempfile::tempdir().unwrap();
9088
    let mut repo = Repo::init(dir.path()).unwrap();
9089
    let missing = KeyId::from_hex(&"ab".repeat(32)).unwrap();
9090
    repo.config.set("author.key", &missing.to_hex()).unwrap();
9091
    let e = repo.identity(&missing).unwrap_err().to_string();
9092
    assert!(
9093
        e.contains("this repository has no identity") && e.contains("oxy config author.key"),
9094
        "{e}"
9095
    );
9096
    assert!(e.contains("this repository's config"), "{e}");
9097
}
9098
9099
#[test]
9100
fn a_working_copy_behind_its_bookmark_is_flagged_and_pull_brings_it_up() {
9101
    // oxygen#89 (supermarioland, 2026-10-09): the bookmark moved on without
9102
    // the working copy, a pull with nothing new left it there, and status
9103
    // said "clean".
9104
    hermetic();
9105
    let dir = tempfile::tempdir().unwrap();
9106
    let root = dir.path();
9107
    let _up = Repo::init(&root.join("up")).unwrap();
9108
    let url = root.join("up").to_string_lossy().to_string();
9109
    let other = Repo::clone(&url, &root.join("other"))
9110
        .unwrap()
9111
        .with_home(root.join("home"));
9112
    write(&root.join("other"), "a.txt", b"a\n");
9113
    other.commit("a", &[]).unwrap();
9114
    assert!(other.push("origin", false).unwrap()[0].ok);
9115
    let one = Repo::clone(&url, &root.join("one"))
9116
        .unwrap()
9117
        .with_home(root.join("home"));
9118
    write(&root.join("other"), "b.txt", b"b\n");
9119
    other.commit("b", &[]).unwrap();
9120
    assert!(other.push("origin", false).unwrap()[0].ok);
9121
    one.fetch("origin").unwrap();
9122
    // The bookmark moves; the working copy does not.
9123
    let theirs = one.resolve_heads("origin/main").unwrap();
9124
    one.bookmark_set("main", &theirs).unwrap();
9125
    assert!(!root.join("one/b.txt").exists());
9126
    assert_eq!(one.working_copy_behind().unwrap(), Some(1));
9127
    let r = one.pull("origin").unwrap();
9128
    assert!(
9129
        !r.changed && r.checked_out,
9130
        "nothing new, but the working copy caught up"
9131
    );
9132
    assert!(root.join("one/b.txt").exists());
9133
    assert_eq!(one.working_copy_behind().unwrap(), None);
9134
}
9135
9136
#[test]
9137
fn touched_nodes_cache_answers_as_the_changes_do() {
9138
    hermetic();
9139
    let dir = tempfile::tempdir().unwrap();
9140
    let repo = Repo::init(dir.path()).unwrap();
9141
    write(dir.path(), "a.txt", b"one\n");
9142
    write(dir.path(), "b.txt", b"x\n");
9143
    repo.snapshot("t").unwrap();
9144
    let c1 = repo.commit("first", &[]).unwrap();
9145
    write(dir.path(), "b.txt", b"y\n");
9146
    repo.snapshot("t").unwrap();
9147
    repo.commit("b only", &[]).unwrap();
9148
    fs::rename(dir.path().join("a.txt"), dir.path().join("c.txt")).unwrap();
9149
    write(dir.path(), "c.txt", b"one\ntwo\n");
9150
    repo.snapshot("t").unwrap();
9151
    let c3 = repo.commit("rename and edit", &[]).unwrap();
9152
    // Uncommitted work, so the working copy touches a file too.
9153
    write(dir.path(), "c.txt", b"one\ntwo\nthree\n");
9154
    repo.snapshot("t").unwrap();
9155
9156
    let path = dir.path().join(".oxy/index/touched");
9157
    let hashes = |es: Vec<LogEntry>| es.iter().map(|e| e.hash).collect::<Vec<_>>();
9158
    let cold = hashes(repo.log_for_path("c.txt").unwrap());
9159
    assert!(path.exists(), "the first query writes the cache");
9160
    let warm = hashes(repo.log_for_path("c.txt").unwrap());
9161
    assert_eq!(cold, warm, "the cache answers as the changes do");
9162
    let (wc, _) = repo.working_copy().unwrap();
9163
    assert_eq!(
9164
        cold,
9165
        vec![wc, c3, c1],
9166
        "renames followed, the working copy included"
9167
    );
9168
9169
    // Working-copy changes are not kept: they are replaced by every snapshot.
9170
    let cached = super::touched::read_touched_for_test(&fs::read(&path).unwrap()).unwrap();
9171
    assert!(!cached.contains(&wc), "a working-copy change is not cached");
9172
    assert!(cached.contains(&c1) && cached.contains(&c3));
9173
9174
    // A damaged cache is ignored, not trusted.
9175
    let mut bytes = fs::read(&path).unwrap();
9176
    let last = bytes.len() - 40;
9177
    bytes[last] ^= 1;
9178
    fs::write(&path, &bytes).unwrap();
9179
    assert_eq!(hashes(repo.log_for_path("c.txt").unwrap()), cold);
9180
    let touches = repo.log_revset("touches(\"c.txt\") ~ @").unwrap();
9181
    assert_eq!(hashes(touches), vec![c3, c1]);
9182
}
9183
9184
/// oxygen#88 (vscode 9ab2056393c8): two lines of history that each move a
9185
/// file back where it was leave two placements at one place, which the
9186
/// tree shows as one file. Removing it, and then its directory, retires
9187
/// both, so no copy is left under a directory that is gone.
9188
#[test]
9189
fn git_import_removes_every_copy_of_a_file_at_one_place() {
9190
    hermetic();
9191
    if std::process::Command::new("git")
9192
        .arg("--version")
9193
        .output()
9194
        .is_err()
9195
    {
9196
        eprintln!("git not installed; skipping");
9197
        return;
9198
    }
9199
    let dir = tempfile::tempdir().unwrap();
9200
    let root = dir.path();
9201
    let g = root.join("src.git");
9202
    fs::create_dir_all(&g).unwrap();
9203
    let git = |args: &[&str]| {
9204
        let out = std::process::Command::new("git")
9205
            .arg("-C")
9206
            .arg(&g)
9207
            .args([
9208
                "-c",
9209
                "user.name=Grace",
9210
                "-c",
9211
                "[email protected]",
9212
                "-c",
9213
                "commit.gpgsign=false",
9214
            ])
9215
            .args(args)
9216
            .output()
9217
            .unwrap();
9218
        assert!(
9219
            out.status.success(),
9220
            "git {args:?}: {}",
9221
            String::from_utf8_lossy(&out.stderr)
9222
        );
9223
    };
9224
    git(&["init", "-q", "-b", "main"]);
9225
    write(&g, "d/list.txt", b"one\ntwo\nthree\nfour\n");
9226
    write(&g, "keep.txt", b"k\n");
9227
    git(&["add", "."]);
9228
    git(&["commit", "-qm", "base"]);
9229
    fs::create_dir_all(g.join("d/sub")).unwrap();
9230
    git(&["mv", "d/list.txt", "d/sub/list.txt"]);
9231
    git(&["commit", "-qm", "into sub"]);
9232
    git(&["checkout", "-qb", "side"]);
9233
    git(&["mv", "d/sub/list.txt", "d/list.txt"]);
9234
    git(&["commit", "-qm", "back, on side"]);
9235
    git(&["checkout", "-q", "main"]);
9236
    git(&["mv", "d/sub/list.txt", "d/list.txt"]);
9237
    git(&["commit", "-qm", "back, on main"]);
9238
    git(&["merge", "-q", "--no-edit", "side"]);
9239
    git(&["rm", "-rq", "d"]);
9240
    git(&["commit", "-qm", "d goes"]);
9241
9242
    let repo = Repo::init(&root.join("o")).unwrap();
9243
    repo.import_git(&g, "main").unwrap();
9244
    let v = repo.verify_git_import(&g, "main").unwrap();
9245
    assert!(v.mismatches.is_empty(), "{:?}", v.mismatches);
9246
    let st = repo
9247
        .load_state_history(&repo.bookmark_heads().unwrap())
9248
        .unwrap();
9249
    let view = st.tree().view();
9250
    assert!(view.conflicts.is_empty(), "{:?}", view.conflicts);
9251
    assert_eq!(view.entries.keys().collect::<Vec<_>>(), vec!["keep.txt"]);
9252
}
9253
9254
/// oxygen#94: a state index's file histories are read, and checked by
9255
/// their own hashes, only when a file is built. One found damaged is an
9256
/// error that says so, the index is removed, and the next read rebuilds it.
9257
#[test]
9258
fn a_damaged_file_history_in_the_state_index_is_rebuilt() {
9259
    hermetic();
9260
    let dir = tempfile::tempdir().unwrap();
9261
    let repo = Repo::init(dir.path()).unwrap();
9262
    for i in 0..6 {
9263
        write(
9264
            dir.path(),
9265
            &format!("f{i}.txt"),
9266
            format!("one {i}\n").as_bytes(),
9267
        );
9268
    }
9269
    repo.snapshot("t").unwrap();
9270
    repo.commit("first", &[]).unwrap();
9271
    for i in 0..6 {
9272
        write(
9273
            dir.path(),
9274
            &format!("f{i}.txt"),
9275
            format!("one {i}\ntwo\n").as_bytes(),
9276
        );
9277
    }
9278
    repo.snapshot("t").unwrap();
9279
    repo.commit("second", &[]).unwrap();
9280
    let want: Vec<Vec<u8>> = (0..6)
9281
        .map(|i| format!("one {i}\ntwo\n").into_bytes())
9282
        .collect();
9283
    // The index of the working copy's base, holding every file's history
9284
    // (a few changes behind, an index is replayed onto, not rewritten).
9285
    let (_, wc) = repo.working_copy().unwrap();
9286
    let base = repo.load_state_history(&wc.deps).unwrap();
9287
    repo.write_state_index(&wc.deps, &base);
9288
    for (i, w) in want.iter().enumerate() {
9289
        assert_eq!(&repo.file_at(&format!("f{i}.txt"), None).unwrap(), w);
9290
    }
9291
    let index = repo.state_indexes();
9292
    assert!(!index.is_empty(), "a state index was written");
9293
    // The histories are last in the file: damage the last of them.
9294
    let mut bytes = fs::read(&index[0]).unwrap();
9295
    let last = bytes.len() - 1;
9296
    bytes[last] ^= 0x40;
9297
    fs::write(&index[0], &bytes).unwrap();
9298
9299
    let reads: Vec<_> = (0..6)
9300
        .map(|i| repo.file_at(&format!("f{i}.txt"), None))
9301
        .collect();
9302
    let damaged: Vec<String> = reads
9303
        .iter()
9304
        .filter_map(|r| r.as_ref().err().map(|e| e.to_string()))
9305
        .collect();
9306
    assert_eq!(damaged.len(), 1, "{damaged:?}");
9307
    assert!(
9308
        damaged[0].contains("state index was damaged")
9309
            && damaged[0].contains("run the command again"),
9310
        "{}",
9311
        damaged[0]
9312
    );
9313
    // Every file reads right again, from an index rebuilt from history.
9314
    for (i, w) in want.iter().enumerate() {
9315
        assert_eq!(&repo.file_at(&format!("f{i}.txt"), None).unwrap(), w);
9316
    }
9317
}
9318
9319
/// oxygen#95: a push longer than `push.batch-bytes` goes in parts, each
9320
/// objects alone and in dependency order, and the last moves the bookmark.
9321
/// The remote ends with every change and the same state, and says how each
9322
/// part went.
9323
#[test]
9324
fn a_long_push_goes_in_parts() {
9325
    hermetic();
9326
    let dir = tempfile::tempdir().unwrap();
9327
    let root = dir.path();
9328
    let origin = root.join("origin");
9329
    Repo::init_bare_unbound(&origin).unwrap();
9330
    let main = root.join("main");
9331
    let mut repo = Repo::init(&main).unwrap();
9332
    repo.config
9333
        .set("remote.origin.url", &origin.to_string_lossy())
9334
        .unwrap();
9335
    // One byte: every change is a part of its own.
9336
    repo.config.set("push.batch-bytes", "1").unwrap();
9337
    repo.save_config().unwrap();
9338
    for i in 0..6 {
9339
        write(
9340
            &main,
9341
            &format!("f{i}.txt"),
9342
            format!("file {i}\n").as_bytes(),
9343
        );
9344
        repo.commit(&format!("c{i}"), &[]).unwrap();
9345
    }
9346
    let mut parts = Vec::new();
9347
    let results = repo
9348
        .push_bookmark_with("origin", "main", false, &mut |m| parts.push(m.to_string()))
9349
        .unwrap();
9350
    assert!(
9351
        results.iter().any(|r| r.ok && r.name == "main"),
9352
        "{results:?}"
9353
    );
9354
    assert_eq!(parts.len(), 6, "{parts:?}");
9355
    assert_eq!(parts[0], "part 1 of 6: 1 changes");
9356
9357
    let remote = Repo::open(&origin).unwrap();
9358
    let heads = repo.bookmark_heads().unwrap();
9359
    assert_eq!(remote.bookmark_heads().unwrap(), heads);
9360
    assert_eq!(
9361
        remote.log_state(&heads).unwrap().len(),
9362
        repo.log_state(&heads).unwrap().len()
9363
    );
9364
    // A push of objects alone reports how it went, as `objects`.
9365
    let got = remote
9366
        .receive_push(Bundle::default(), vec![], None, vec![])
9367
        .unwrap();
9368
    assert_eq!(got.len(), 1);
9369
    assert!(got[0].ok && got[0].name == OBJECTS_RESULT, "{got:?}");
9370
}
9371
9372
/// oxygen#133: one change whose blobs pass `push.batch-bytes` sends them
9373
/// first, in parts of objects alone, so no request is larger than about
9374
/// that (a proxy in front of a hub refuses one past 100 MB); the change
9375
/// and the bookmark follow, and a clone has every file.
9376
#[test]
9377
fn a_heavy_change_sends_its_blobs_in_parts() {
9378
    hermetic();
9379
    let dir = tempfile::tempdir().unwrap();
9380
    let root = dir.path();
9381
    let origin = root.join("origin");
9382
    Repo::init_bare_unbound(&origin).unwrap();
9383
    let main = root.join("main");
9384
    let mut repo = Repo::init(&main).unwrap();
9385
    repo.config
9386
        .set("remote.origin.url", &origin.to_string_lossy())
9387
        .unwrap();
9388
    repo.config.set("push.batch-bytes", "50000").unwrap();
9389
    repo.save_config().unwrap();
9390
    let mut x: u64 = 0x9e3779b97f4a7c15;
9391
    let mut noise = |n: usize| -> Vec<u8> {
9392
        (0..n)
9393
            .map(|_| {
9394
                x ^= x << 13;
9395
                x ^= x >> 7;
9396
                x ^= x << 17;
9397
                (x >> 24) as u8
9398
            })
9399
            .collect()
9400
    };
9401
    let files: Vec<Vec<u8>> = (0..4).map(|_| noise(40_000)).collect();
9402
    for (i, f) in files.iter().enumerate() {
9403
        write(&main, &format!("bin{i}.dat"), f);
9404
    }
9405
    repo.commit("four blobs", &[]).unwrap();
9406
    let mut parts = Vec::new();
9407
    let results = repo
9408
        .push_bookmark_with("origin", "main", false, &mut |m| parts.push(m.to_string()))
9409
        .unwrap();
9410
    assert!(
9411
        results.iter().any(|r| r.ok && r.name == "main"),
9412
        "{results:?}"
9413
    );
9414
    assert!(
9415
        parts.len() >= 3 && parts[0].starts_with("objects 1 of"),
9416
        "{parts:?}"
9417
    );
9418
    let back = Repo::clone(&origin.to_string_lossy(), &root.join("back")).unwrap();
9419
    for (i, f) in files.iter().enumerate() {
9420
        assert_eq!(&fs::read(root.join(format!("back/bin{i}.dat"))).unwrap(), f);
9421
    }
9422
    drop(back);
9423
}
9424
9425
/// oxygen#97: with `git.claim`, an import authors the importing identity's
9426
/// own commits (Git author email = its email, any case) with its key, and
9427
/// leaves anyone else's with the zero key; the history verifies as before.
9428
#[test]
9429
fn git_import_claims_your_own_commits() {
9430
    hermetic();
9431
    if std::process::Command::new("git")
9432
        .arg("--version")
9433
        .output()
9434
        .is_err()
9435
    {
9436
        eprintln!("git not installed; skipping");
9437
        return;
9438
    }
9439
    let dir = tempfile::tempdir().unwrap();
9440
    let root = dir.path();
9441
    let g = root.join("src.git");
9442
    fs::create_dir_all(&g).unwrap();
9443
    let git = |who: &str, args: &[&str]| {
9444
        let (name, email) = who.split_once(' ').unwrap();
9445
        let out = std::process::Command::new("git")
9446
            .arg("-C")
9447
            .arg(&g)
9448
            .args([
9449
                "-c",
9450
                &format!("user.name={name}"),
9451
                "-c",
9452
                &format!("user.email={email}"),
9453
                "-c",
9454
                "commit.gpgsign=false",
9455
            ])
9456
            .args(args)
9457
            .output()
9458
            .unwrap();
9459
        assert!(
9460
            out.status.success(),
9461
            "git {args:?}: {}",
9462
            String::from_utf8_lossy(&out.stderr)
9463
        );
9464
    };
9465
    git("Grace [email protected]", &["init", "-q", "-b", "main"]);
9466
    write(&g, "a.txt", b"a\n");
9467
    git("Grace [email protected]", &["add", "."]);
9468
    git("Grace [email protected]", &["commit", "-qm", "mine"]);
9469
    write(&g, "b.txt", b"b\n");
9470
    git("Ada [email protected]", &["add", "."]);
9471
    git("Ada [email protected]", &["commit", "-qm", "someone else's"]);
9472
9473
    let mut repo = Repo::init(&root.join("o")).unwrap();
9474
    let (key, _) = repo
9475
        .create_identity("Grace", "[email protected]", IdentityScope::Repo)
9476
        .unwrap();
9477
    repo.config.set("git.claim", "true").unwrap();
9478
    repo.save_config().unwrap();
9479
    let repo = Repo::open(&root.join("o")).unwrap();
9480
    repo.import_git(&g, "main").unwrap();
9481
    let v = repo.verify_git_import(&g, "main").unwrap();
9482
    assert!(v.mismatches.is_empty(), "{:?}", v.mismatches);
9483
    let heads = repo.bookmark_heads().unwrap();
9484
    let by_message: std::collections::HashMap<String, KeyId> = repo
9485
        .log_state(&heads)
9486
        .unwrap()
9487
        .into_iter()
9488
        .map(|e| {
9489
            (
9490
                e.change.message.lines().next().unwrap_or("").to_string(),
9491
                e.change.author,
9492
            )
9493
        })
9494
        .collect();
9495
    assert_eq!(by_message["mine"], key, "her own commit, any case of email");
9496
    assert_eq!(by_message["someone else's"], ObjectRef::ZERO, "not hers");
9497
}
9498
9499
/// oxygen#86: removing a remote removes all of it: every `remote.NAME.*`
9500
/// key (URL, token, CA), its tracking bookmarks, and nothing else.
9501
#[test]
9502
fn removing_a_remote_leaves_nothing_of_it() {
9503
    hermetic();
9504
    let dir = tempfile::tempdir().unwrap();
9505
    let origin = dir.path().join("origin");
9506
    Repo::init_bare_unbound(&origin).unwrap();
9507
    let main = dir.path().join("main");
9508
    let mut repo = Repo::init(&main).unwrap();
9509
    repo.config
9510
        .set("remote.origin.url", &origin.to_string_lossy())
9511
        .unwrap();
9512
    repo.config
9513
        .set("remote.origin.token", "secret-ish")
9514
        .unwrap();
9515
    repo.config
9516
        .set("remote.keep.url", &origin.to_string_lossy())
9517
        .unwrap();
9518
    repo.save_config().unwrap();
9519
    write(&main, "a.txt", b"a\n");
9520
    repo.commit("a", &[]).unwrap();
9521
    assert!(repo.push("origin", false).unwrap()[0].ok);
9522
    assert!(
9523
        repo.view().unwrap().remotes.contains_key("origin"),
9524
        "a tracking bookmark"
9525
    );
9526
9527
    repo.remove_remote("origin").unwrap();
9528
    let again = Repo::open(&main).unwrap();
9529
    assert!(
9530
        !again
9531
            .config
9532
            .repo_layer()
9533
            .keys()
9534
            .any(|k| k.starts_with("remote.origin.")),
9535
        "{:?}",
9536
        again.config.repo_layer()
9537
    );
9538
    assert!(!again.config.remotes.contains_key("origin"));
9539
    assert!(
9540
        !again.view().unwrap().remotes.contains_key("origin"),
9541
        "its tracking bookmarks go"
9542
    );
9543
    assert!(
9544
        again.config.remotes.contains_key("keep"),
9545
        "another remote stays"
9546
    );
9547
    let mut again = again;
9548
    assert!(
9549
        again.remove_remote("origin").is_err(),
9550
        "a second removal is refused"
9551
    );
9552
}
9553
9554
/// oxygenhub#126: a blob a host stored for itself (a job's artifact) is
9555
/// unreachable from history, so gc prunes it, unless the host names it:
9556
/// then it and its chunks stay, and it reads back whole.
9557
#[test]
9558
fn gc_keeps_the_blobs_a_host_names() {
9559
    hermetic();
9560
    let dir = tempfile::tempdir().unwrap();
9561
    let repo = Repo::init(dir.path()).unwrap();
9562
    write(dir.path(), "a.txt", b"a\n");
9563
    repo.commit("a", &[]).unwrap();
9564
    // Large enough to be several chunks.
9565
    let body: Vec<u8> = (0..400_000u32)
9566
        .flat_map(|i| (i.wrapping_mul(2654435761)).to_le_bytes())
9567
        .collect();
9568
    let kept = repo.store_blob(&body).unwrap();
9569
    let lost = repo.store_blob(b"an artifact nobody names").unwrap();
9570
    repo.gc_keeping(true, &[kept], &mut |_| {}).unwrap();
9571
    assert_eq!(repo.read_blob(&kept).unwrap(), body, "named: kept whole");
9572
    assert!(!repo.store().has(&lost), "not named: pruned");
9573
    repo.gc(true).unwrap();
9574
    assert!(!repo.store().has(&kept), "a plain gc prunes it");
9575
}
9576
9577
/// oxygen#99: undo in one workspace undoes that workspace's last command,
9578
/// never another workspace's, says what it undid, and goes further back
9579
/// when run again.
9580
#[test]
9581
fn undo_is_scoped_to_its_workspace() {
9582
    hermetic();
9583
    let dir = tempfile::tempdir().unwrap();
9584
    let root = dir.path().join("main");
9585
    let a = Repo::init(&root).unwrap();
9586
    write(&root, "base.txt", b"base\n");
9587
    let base = a.commit("base", &[]).unwrap();
9588
    a.bookmark_create("feature", None).unwrap();
9589
    let ws_dir = dir.path().join("ws");
9590
    let heads = a.resolve_heads("feature").unwrap();
9591
    let b = a
9592
        .workspace_add_on(&ws_dir, Some(&heads), Some("feature"))
9593
        .unwrap();
9594
9595
    // A commits on main, then B commits on feature: B's is the newest.
9596
    write(&root, "a.txt", b"a\n");
9597
    let ca = a.commit("from a", &[]).unwrap();
9598
    write(&ws_dir, "b.txt", b"b\n");
9599
    let cb = b.commit("from b", &[]).unwrap();
9600
9601
    // A's undo undoes A's commit and leaves B's.
9602
    let u = a.undo().unwrap();
9603
    assert_eq!(u.command, "oxy commit -m \"from a\"");
9604
    assert_eq!(u.others_kept, 1, "B's newer commit is left");
9605
    assert!(!u.changes.is_empty());
9606
    let view = a.view().unwrap();
9607
    // (Independent changes commute, so a bookmark's heads may hold base too.)
9608
    assert_eq!(a.heads_of(&view, "main").unwrap(), vec![base]);
9609
    assert!(
9610
        a.heads_of(&view, "feature").unwrap().contains(&cb),
9611
        "B's commit stands"
9612
    );
9613
    assert!(
9614
        a.store().get_change(&ca).is_ok(),
9615
        "the change itself is still in the store"
9616
    );
9617
    // A's working copy was clean, so its files followed; B's are untouched.
9618
    assert!(!root.join("a.txt").exists());
9619
    assert!(a.snapshot("oxy status").unwrap().statuses.is_empty());
9620
    assert!(ws_dir.join("b.txt").exists());
9621
9622
    // B's undo still finds B's own commit, under A's undo.
9623
    let u = b.undo().unwrap();
9624
    assert_eq!(u.command, "oxy commit -m \"from b\"");
9625
    assert!(!b
9626
        .heads_of(&b.view().unwrap(), "feature")
9627
        .unwrap()
9628
        .contains(&cb));
9629
    assert_eq!(
9630
        a.heads_of(&a.view().unwrap(), "main").unwrap(),
9631
        vec![base],
9632
        "A's undo stands"
9633
    );
9634
9635
    // A's next undo goes past the commit it already undid, to adding B's
9636
    // workspace: refused, since B has worked there since.
9637
    let e = a.undo().unwrap_err().to_string();
9638
    assert!(e.contains("the workspace at") && e.contains("ws"), "{e}");
9639
}
9640
9641
/// oxygen#99: two workspaces on one bookmark: an undo takes back only its
9642
/// own commit's head, and the other workspace's head stays.
9643
#[test]
9644
fn undo_on_a_shared_bookmark_keeps_the_other_workspaces_head() {
9645
    hermetic();
9646
    let dir = tempfile::tempdir().unwrap();
9647
    let root = dir.path().join("main");
9648
    let a = Repo::init(&root).unwrap();
9649
    write(&root, "base.txt", b"base\n");
9650
    a.commit("base", &[]).unwrap();
9651
    let ws_dir = dir.path().join("ws");
9652
    let b = a.workspace_add(&ws_dir, None).unwrap();
9653
    write(&root, "a.txt", b"a\n");
9654
    let ca = a.commit("from a", &[]).unwrap();
9655
    write(&ws_dir, "b.txt", b"b\n");
9656
    let cb = b.commit("from b", &[]).unwrap();
9657
    let u = a.undo().unwrap();
9658
    assert_eq!(u.command, "oxy commit -m \"from a\"");
9659
    let heads = a.heads_of(&a.view().unwrap(), "main").unwrap();
9660
    assert!(heads.contains(&cb) && !heads.contains(&ca), "{heads:?}");
9661
}
9662
9663
/// oxygen#99: an undo that would also take back what another workspace
9664
/// did since to the same bookmark is refused, naming it.
9665
#[test]
9666
fn undo_refuses_to_take_back_another_workspaces_work() {
9667
    hermetic();
9668
    let dir = tempfile::tempdir().unwrap();
9669
    let root = dir.path().join("main");
9670
    let a = Repo::init(&root).unwrap();
9671
    write(&root, "base.txt", b"base\n");
9672
    a.commit("base", &[]).unwrap();
9673
    let ws_dir = dir.path().join("ws");
9674
    let b = a.workspace_add(&ws_dir, None).unwrap();
9675
    // Both on main: A commits, then B builds on it, editing A's file.
9676
    write(&root, "a.txt", b"a\n");
9677
    a.commit("from a", &[]).unwrap();
9678
    b.refresh().unwrap();
9679
    let heads = b.resolve_heads("main").unwrap();
9680
    b.checkout(&heads, false, "oxy checkout").unwrap();
9681
    write(&ws_dir, "a.txt", b"a, then b\n");
9682
    b.commit("from b", &[]).unwrap();
9683
    let e = a.undo().unwrap_err().to_string();
9684
    assert!(
9685
        e.contains("bookmark main") && e.contains("builds on"),
9686
        "{e}"
9687
    );
9688
    assert!(e.contains("oxy op restore"), "{e}");
9689
}
9690
9691
/// oxygen#99: undoing a commit that was already pushed says so: the remote
9692
/// still has it.
9693
#[test]
9694
fn undo_says_when_the_commit_was_pushed() {
9695
    hermetic();
9696
    let dir = tempfile::tempdir().unwrap();
9697
    let root = dir.path();
9698
    Repo::init(&root.join("origin")).unwrap();
9699
    let url = root.join("origin").to_string_lossy().to_string();
9700
    let repo = Repo::clone(&url, &root.join("work"))
9701
        .unwrap()
9702
        .with_home(root.join("home"));
9703
    write(&root.join("work"), "a.txt", b"a\n");
9704
    repo.commit("a", &[]).unwrap();
9705
    assert!(repo.push("origin", false).unwrap()[0].ok);
9706
    // The push itself is passed over: the remote keeps what it was sent.
9707
    let u = repo.undo().unwrap();
9708
    assert_eq!(u.command, "oxy commit -m \"a\"");
9709
    assert_eq!(u.pushed, vec![("main".to_string(), "origin".to_string())]);
9710
}
9711
9712
/// oxygen#98: a new untracked file over snapshot.max-new-file-size is left
9713
/// out of the snapshot and named; tracked files and files already in the
9714
/// working copy are not.
9715
#[test]
9716
fn large_new_files_are_left_out_of_snapshots() {
9717
    hermetic();
9718
    let dir = tempfile::tempdir().unwrap();
9719
    let root = dir.path();
9720
    let mut repo = Repo::init(root).unwrap();
9721
    repo.config.max_new_file = 1024;
9722
    write(root, "small.txt", b"small\n");
9723
    write(root, "big.bin", &vec![0u8; 4096]);
9724
    let s = repo.snapshot("oxy status").unwrap();
9725
    let paths: Vec<_> = s.statuses.iter().map(|p| p.path.as_str()).collect();
9726
    assert_eq!(paths, ["small.txt"]);
9727
    assert_eq!(repo.skipped_large(), vec![("big.bin".to_string(), 4096)]);
9728
    repo.commit("small", &[]).unwrap();
9729
9730
    // A tracked file may grow past the limit.
9731
    write(root, "small.txt", &vec![b'x'; 4096]);
9732
    let s = repo.snapshot("oxy status").unwrap();
9733
    assert!(s.statuses.iter().any(|p| p.path == "small.txt"));
9734
    // With no limit the big file is taken in, and stays once it is.
9735
    repo.config.max_new_file = 0;
9736
    let s = repo.snapshot("oxy status").unwrap();
9737
    assert!(s.statuses.iter().any(|p| p.path == "big.bin"));
9738
    repo.config.max_new_file = 1024;
9739
    let s = repo.snapshot("oxy status").unwrap();
9740
    assert!(
9741
        s.statuses.iter().any(|p| p.path == "big.bin"),
9742
        "already in the working copy"
9743
    );
9744
    assert!(repo.skipped_large().is_empty());
9745
}
9746
9747
/// oxygen#98: a file only a past working-copy snapshot held is pruned once
9748
/// snapshots expire, and kept while they have not.
9749
#[test]
9750
fn gc_prunes_what_only_expired_snapshots_held() {
9751
    hermetic();
9752
    let dir = tempfile::tempdir().unwrap();
9753
    let root = dir.path();
9754
    let mut repo = Repo::init(root).unwrap();
9755
    repo.config.gc_grace_days = 0;
9756
    write(root, "a.txt", b"a\n");
9757
    repo.commit("a", &[]).unwrap();
9758
    let image: Vec<u8> = (0..200_000u32).map(|i| (i % 7) as u8).collect();
9759
    write(root, "image.tar", &image);
9760
    repo.snapshot("oxy status").unwrap();
9761
    std::fs::remove_file(root.join("image.tar")).unwrap();
9762
    repo.snapshot("oxy status").unwrap();
9763
    let blob = Repo::blob_ref(&image);
9764
    assert!(repo.store().has(&blob));
9765
    repo.gc(true).unwrap();
9766
    assert!(repo.store().has(&blob), "a recent snapshot keeps it");
9767
    repo.config.snapshot_retention_days = 0;
9768
    repo.gc(true).unwrap();
9769
    assert!(!repo.store().has(&blob), "an expired snapshot does not");
9770
    assert_eq!(
9771
        repo.file_at("a.txt", None).unwrap(),
9772
        b"a\n",
9773
        "committed files stay"
9774
    );
9775
}
9776
9777
/// oxygen#100: uncommitted work byte-for-byte what the bookmark switched to
9778
/// already has is no conflict: the switch goes through, nothing is lost,
9779
/// and other carried work still comes along.
9780
#[test]
9781
fn carrying_work_the_target_already_has_is_no_conflict() {
9782
    hermetic();
9783
    let dir = tempfile::tempdir().unwrap();
9784
    let root = dir.path();
9785
    let mut repo = Repo::init(root).unwrap();
9786
    write(root, "a.txt", b"one\n");
9787
    write(root, "b.txt", b"b\n");
9788
    repo.commit("one", &[]).unwrap();
9789
    repo.bookmark_create("landed", None).unwrap();
9790
    // On landed, a.txt becomes "two" (as a proposal landing would).
9791
    repo.bookmark_switch("landed", false).unwrap();
9792
    write(root, "a.txt", b"two\n");
9793
    repo.commit("two", &[]).unwrap();
9794
    repo.bookmark_switch("main", false).unwrap();
9795
    assert_eq!(std::fs::read(root.join("a.txt")).unwrap(), b"one\n");
9796
    // The same edit, uncommitted, on main; and another edit besides.
9797
    write(root, "a.txt", b"two\n");
9798
    write(root, "b.txt", b"b, edited\n");
9799
    let (_, carried) = repo.bookmark_switch_carry("landed").unwrap();
9800
    assert_eq!(
9801
        carried,
9802
        vec!["b.txt".to_string()],
9803
        "only the work landed lacks is carried"
9804
    );
9805
    assert_eq!(std::fs::read(root.join("a.txt")).unwrap(), b"two\n");
9806
    assert_eq!(std::fs::read(root.join("b.txt")).unwrap(), b"b, edited\n");
9807
    let s = repo.snapshot("oxy status").unwrap();
9808
    let paths: Vec<_> = s.statuses.iter().map(|p| p.path.as_str()).collect();
9809
    assert_eq!(paths, ["b.txt"]);
9810
9811
    // A real difference is still refused.
9812
    repo.bookmark_switch("main", true).unwrap();
9813
    write(root, "a.txt", b"three\n");
9814
    let e = repo
9815
        .bookmark_switch_carry("landed")
9816
        .unwrap_err()
9817
        .to_string();
9818
    assert!(e.contains("a.txt") && e.contains("--discard"), "{e}");
9819
}
9820
9821
/// oxygen#103: a full change hash as `--json` prints it, without `#`,
9822
/// resolves, so JSON output feeds back into commands.
9823
#[test]
9824
fn a_full_hash_resolves_without_its_hash_sign() {
9825
    hermetic();
9826
    let dir = tempfile::tempdir().unwrap();
9827
    let root = dir.path();
9828
    let repo = Repo::init(root).unwrap();
9829
    write(root, "a.txt", b"a\n");
9830
    let h = repo.commit("a", &[]).unwrap();
9831
    assert_eq!(repo.resolve_change(&h.to_hex()).unwrap(), h);
9832
    assert_eq!(repo.resolve_change(&format!("#{}", h.to_hex())).unwrap(), h);
9833
    assert!(repo
9834
        .resolve_change(&"0".repeat(64))
9835
        .unwrap_err()
9836
        .to_string()
9837
        .contains("no change matches"));
9838
}
9839
9840
#[test]
9841
fn a_pin_change_moves_only_the_pin() {
9842
    hermetic();
9843
    let dir = tempfile::tempdir().unwrap();
9844
    let root = dir.path();
9845
    let _lib_origin = Repo::init(&root.join("lib-origin")).unwrap();
9846
    let lib_url = root.join("lib-origin").to_string_lossy().to_string();
9847
    let lib = Repo::clone(&lib_url, &root.join("lib"))
9848
        .unwrap()
9849
        .with_home(root.join("home"));
9850
    write(&root.join("lib"), "lib.txt", b"v1\n");
9851
    lib.commit("lib v1", &[]).unwrap();
9852
    assert!(lib.push("origin", false).unwrap()[0].ok);
9853
    let _app_origin = Repo::init(&root.join("app-origin")).unwrap();
9854
    let app_dir = root.join("app");
9855
    let app = Repo::clone(&root.join("app-origin").to_string_lossy(), &app_dir)
9856
        .unwrap()
9857
        .with_home(root.join("home"));
9858
    write(&app_dir, "main.txt", b"app\n");
9859
    let pin1 = app.submodule_add(&lib_url, "libs/lib", None).unwrap();
9860
    let a1 = app.commit("app with lib", &[]).unwrap();
9861
    // The library moves on.
9862
    write(&root.join("lib"), "more.txt", b"v2\n");
9863
    let l2 = lib.commit("lib v2", &[]).unwrap();
9864
    let crate::subrepo::Pin::Oxy { repo, bookmark, .. } = pin1 else {
9865
        panic!("an Oxygen pin")
9866
    };
9867
    let pin2 = crate::subrepo::Pin::Oxy {
9868
        repo,
9869
        heads: vec![l2],
9870
        bookmark,
9871
    };
9872
    let author = app.store().get_change(&a1).unwrap().author;
9873
    let change = app
9874
        .build_pin_change(&[a1], "libs/lib", &pin2, "Move lib to v2", author)
9875
        .unwrap();
9876
    let mut state = app.load_state(&[a1]).unwrap();
9877
    state.add(change).unwrap();
9878
    let files = state.materialize().files;
9879
    assert_eq!(files["libs/lib"].kind, NodeKind::Subrepo);
9880
    let FileContent::Opaque { blobs } = &files["libs/lib"].content else {
9881
        panic!("a pin is opaque")
9882
    };
9883
    let read = crate::subrepo::Pin::decode(&app.read_blob(&blobs[0]).unwrap()).unwrap();
9884
    assert_eq!(read, pin2, "the new pin");
9885
    assert!(
9886
        matches!(&files["main.txt"].content, FileContent::Text { bytes, .. } if bytes.as_slice() == b"app\n"),
9887
        "nothing else changes"
9888
    );
9889
    // Only a subrepo's pin can be moved this way.
9890
    let e = app.build_pin_change(&[a1], "main.txt", &pin2, "x", author);
9891
    assert!(format!("{:?}", e.unwrap_err()).contains("not a subrepo"));
9892
    let e = app.build_pin_change(&[a1], "libs/none", &pin2, "x", author);
9893
    assert!(format!("{:?}", e.unwrap_err()).contains("does not exist"));
9894
}
9895
9896
/// oxygenhub#249: a handle reads the operation head once and keeps it,
9897
/// so one command or request never mixes two heads; another handle's
9898
/// operation shows only after `refresh`. Its own operations move it, and
9899
/// one recorded from the head it kept merges with what landed since, as
9900
/// any concurrent operation does.
9901
#[test]
9902
fn one_handle_keeps_one_head_until_it_refreshes() {
9903
    hermetic();
9904
    let dir = tempfile::tempdir().unwrap();
9905
    let root = dir.path();
9906
    let writer = Repo::init(root).unwrap();
9907
    write(root, "a.txt", b"one\n");
9908
    let h1 = writer.commit("one", &[]).unwrap();
9909
    let reader = Repo::open(root).unwrap();
9910
    let before = reader.view().unwrap();
9911
    assert_eq!(reader.bookmark_heads().unwrap(), vec![h1]);
9912
    write(root, "a.txt", b"two\n");
9913
    let h2 = writer.commit("two", &[]).unwrap();
9914
    assert_eq!(
9915
        writer.bookmark_heads().unwrap(),
9916
        vec![h2],
9917
        "its own operation"
9918
    );
9919
    assert_eq!(reader.view().unwrap(), before, "the head it read first");
9920
    assert_eq!(reader.bookmark_heads().unwrap(), vec![h1]);
9921
    reader.refresh().unwrap();
9922
    assert_eq!(reader.bookmark_heads().unwrap(), vec![h2]);
9923
9924
    // A handle recording from an older head merges with the newer one.
9925
    let stale = Repo::open(root).unwrap();
9926
    assert_eq!(stale.bookmark_heads().unwrap(), vec![h2]);
9927
    write(root, "a.txt", b"three\n");
9928
    let h3 = writer.commit("three", &[]).unwrap();
9929
    stale.bookmark_create("feature", Some(&[h1])).unwrap();
9930
    let view = stale.view().unwrap();
9931
    assert!(view.bookmarks.contains_key("feature"));
9932
    assert_eq!(
9933
        stale.bookmark_heads().unwrap(),
9934
        vec![h3],
9935
        "merged, not lost"
9936
    );
9937
    let fresh = Repo::open(root).unwrap();
9938
    assert_eq!(fresh.view().unwrap(), view);
9939
}
9940
9941
/// oxygenhub#249 over a store (a bucket's compare-and-swap): the same.
9942
#[test]
9943
fn over_a_store_one_handle_keeps_one_head() {
9944
    hermetic();
9945
    let backend = std::sync::Arc::new(crate::strata::MemoryStore::new());
9946
    crate::store::TEST_BACKEND.with(|t| *t.borrow_mut() = Some(backend.clone()));
9947
    let dir = tempfile::tempdir().unwrap();
9948
    let a = Repo::init(dir.path()).unwrap();
9949
    let (h0, _) = a.head_op().unwrap();
9950
    let b = Repo::open(dir.path()).unwrap();
9951
    assert_eq!(b.head_op().unwrap().0, h0);
9952
    let state = a.store.put_state(&StateObject::new(vec![])).unwrap();
9953
    let mut view = a.view().unwrap();
9954
    view.bookmarks.insert("x".into(), state);
9955
    let r = a.record_op(&[h0], "bookmark x", view).unwrap();
9956
    assert_eq!(a.head_op().unwrap().0, r);
9957
    assert_eq!(b.head_op().unwrap().0, h0, "b keeps its head");
9958
    b.refresh().unwrap();
9959
    assert_eq!(b.head_op().unwrap().0, r);
9960
    crate::store::TEST_BACKEND.with(|t| *t.borrow_mut() = None);
9961
}
9962
9963
/// oxygenhub#249: gc retires what it repacks rather than deleting it; a
9964
/// reader opened before reads on, then and after the next gc deletes the
9965
/// retired files once their hour is up. Younger ones are kept.
9966
#[test]
9967
fn gc_retires_and_a_later_gc_deletes_after_the_hour() {
9968
    hermetic();
9969
    let dir = tempfile::tempdir().unwrap();
9970
    let root = dir.path();
9971
    let repo = Repo::init(root).unwrap();
9972
    let mut heads = Vec::new();
9973
    for i in 0..4 {
9974
        write(root, &format!("f{i}.txt"), format!("{i}\n").as_bytes());
9975
        heads.push(repo.commit(&format!("c{i}"), &[]).unwrap());
9976
    }
9977
    let reader = Repo::open(root).unwrap();
9978
    assert_eq!(reader.log().unwrap().len(), 5);
9979
    let r = repo.gc(true).unwrap();
9980
    assert_eq!(r.retired, crate::store::RetiredReport::default());
9981
    assert_eq!(repo.store().loose_count().unwrap(), 0);
9982
    assert_eq!(reader.log().unwrap().len(), 5, "read on from what it had");
9983
    // Nothing is an hour old yet: a gc keeps it all.
9984
    let r = repo.gc(true).unwrap();
9985
    assert_eq!((r.retired.packs, r.retired.loose), (0, 0));
9986
    assert!(r.retired.kept > 0, "{r:?}");
9987
    write(root, "f9.txt", b"9\n");
9988
    heads.push(repo.commit("c9", &[]).unwrap());
9989
    crate::store::reader_tests::age_retired(
9990
        repo.store(),
9991
        crate::store::RETIRED_FOR + std::time::Duration::from_secs(60),
9992
    );
9993
    let r = repo.gc(true).unwrap();
9994
    assert!(r.retired.packs >= 1 && r.retired.loose > 0, "{r:?}");
9995
    assert_eq!(r.retired.kept, 0, "{r:?}");
9996
    let r = repo.gc(true).unwrap();
9997
    assert_eq!((r.retired.packs, r.retired.loose), (0, 0));
9998
    assert!(r.retired.kept > 0, "what the last gc retired is young");
9999
    // The reader opened before all of it still reads everything, from
10000
    // the packs it finds when what it loaded is gone.
10001
    assert_eq!(reader.log().unwrap().len(), 5);
10002
    for h in &heads[..4] {
10003
        reader.store().get_change(h).unwrap();
10004
    }
10005
    reader.refresh().unwrap();
10006
    assert_eq!(reader.log().unwrap().len(), 6);
10007
    let fresh = Repo::open(root).unwrap();
10008
    assert_eq!(
10009
        fresh.store().pack_count(),
10010
        1,
10011
        "retired packs are not loaded"
10012
    );
10013
}
10014
10015
/// oxygenhub#249: a repository opens when its store's pack listing names
10016
/// an index that is not there (deleted between the listing and the read).
10017
#[test]
10018
fn a_repository_opens_when_a_listed_index_is_gone() {
10019
    hermetic();
10020
    let backend = crate::store::reader_tests::racing(true);
10021
    let dyn_backend: std::sync::Arc<crate::store::Backend> = backend.clone();
10022
    crate::store::TEST_BACKEND.with(|t| *t.borrow_mut() = Some(dyn_backend));
10023
    let dir = tempfile::tempdir().unwrap();
10024
    let repo = Repo::init(dir.path()).unwrap();
10025
    write(dir.path(), "a.txt", b"a\n");
10026
    let h = repo.commit("a", &[]).unwrap();
10027
    repo.gc(true).unwrap();
10028
    let again = Repo::open(dir.path()).unwrap();
10029
    assert_eq!(again.store().pack_count(), 1);
10030
    assert_eq!(again.bookmark_heads().unwrap(), vec![h]);
10031
    // And when one is deleted between the listing and the read: a copy of
10032
    // the live pack, whose index goes as the store opens.
10033
    use crate::strata::Store as _;
10034
    let idx = backend
10035
        .list("pack-")
10036
        .unwrap()
10037
        .into_iter()
10038
        .map(|e| e.key)
10039
        .find(|k| k.ends_with(".idx") && k != "pack-0000.idx")
10040
        .unwrap();
10041
    let stem = idx.trim_end_matches(".idx");
10042
    for ext in ["pack", "idx"] {
10043
        let bytes = backend.get(&format!("{stem}.{ext}")).unwrap();
10044
        backend
10045
            .put_new(&format!("pack-copy.{ext}"), &bytes)
10046
            .unwrap();
10047
    }
10048
    *backend.doomed.lock().unwrap() = Some("pack-copy.idx".into());
10049
    let again = Repo::open(dir.path()).unwrap();
10050
    assert_eq!(again.store().pack_count(), 1);
10051
    assert_eq!(again.bookmark_heads().unwrap(), vec![h]);
10052
    assert!(!backend.has("pack-copy.idx").unwrap());
10053
    crate::store::TEST_BACKEND.with(|t| *t.borrow_mut() = None);
10054
}