OXYGENHUB
# d3b270909c78 oxygen / crates / oxy-core / src / repo / tests.rs
370.9 KiB · Rust · last changed A push no longer passes a proxy's request limit (closes #133) 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
#[test]
3029
fn shallow_clone_and_deepen() {
3030
    hermetic();
3031
    let dir = tempfile::tempdir().unwrap();
3032
    let root = dir.path();
3033
    let origin_dir = root.join("origin");
3034
    let origin = Repo::init(&origin_dir)
3035
        .unwrap()
3036
        .with_home(root.join("home"));
3037
    let mut hashes = Vec::new();
3038
    for i in 0..8 {
3039
        write(
3040
            &origin_dir,
3041
            "a.txt",
3042
            format!(
3043
                "{}\n",
3044
                (0..=i)
3045
                    .map(|k| k.to_string())
3046
                    .collect::<Vec<_>>()
3047
                    .join("\n")
3048
            )
3049
            .as_bytes(),
3050
        );
3051
        hashes.push(origin.commit(&format!("c{i}"), &[]).unwrap());
3052
    }
3053
    let url = origin_dir.to_string_lossy().to_string();
3054
    let a = Repo::clone_shallow(&url, &root.join("a"), 3, None, &[])
3055
        .unwrap()
3056
        .with_home(root.join("home"));
3057
    assert!(a.is_shallow());
3058
    assert_eq!(
3059
        fs::read_to_string(root.join("a/a.txt")).unwrap(),
3060
        "0\n1\n2\n3\n4\n5\n6\n7\n"
3061
    );
3062
    assert!(
3063
        a.store().has(&hashes[7]) && a.store().has(&hashes[5]),
3064
        "three levels present"
3065
    );
3066
    assert!(!a.store().has(&hashes[4]), "beyond the depth is absent");
3067
    assert_eq!(a.boundary(), [hashes[4]].into_iter().collect());
3068
    assert_eq!(
3069
        a.log().unwrap().len(),
3070
        9,
3071
        "the log shows every change from the checkpoint's metadata"
3072
    );
3073
    assert!(!a.snapshot("status").unwrap().changed);
3074
    assert_eq!(a.quick_status().unwrap().heads, 1);
3075
3076
    // Work continues on top of the shallow history and pushes back.
3077
    write(&root.join("a"), "a.txt", b"0\n1\n2\n3\n4\n5\n6\n7\n8\n");
3078
    let h_new = a.commit("c8", &[]).unwrap();
3079
    assert!(a.push("origin", false).unwrap()[0].ok);
3080
    origin.refresh().unwrap();
3081
    assert_eq!(origin.bookmark_heads().unwrap(), vec![h_new]);
3082
    // Fetching new work from origin into the shallow clone works too.
3083
    write(&origin_dir, "b.txt", b"b\n");
3084
    origin.pull("origin").err();
3085
    let (_, wc) = origin.working_copy().unwrap();
3086
    let _ = wc;
3087
    origin
3088
        .checkout(&origin.bookmark_heads().unwrap(), true, "co")
3089
        .unwrap();
3090
    write(&origin_dir, "b.txt", b"b\n");
3091
    let h_b = origin.commit("b", &[]).unwrap();
3092
    let pr = a.pull("origin").unwrap();
3093
    assert!(pr.changed);
3094
    assert!(a.store().has(&h_b));
3095
    assert!(root.join("a/b.txt").exists());
3096
3097
    // Deepening fetches older history until the boundary is gone.
3098
    // Every commit also depends on the change that created the file, so two
3099
    // levels below the boundary hold h4, h3, and the root.
3100
    assert!(a.deepen("origin", 2).unwrap() >= 2);
3101
    assert!(a.store().has(&hashes[3]));
3102
    assert!(a.is_shallow());
3103
    a.deepen("origin", 100).unwrap();
3104
    assert!(!a.is_shallow(), "boundary reached the root");
3105
    assert!(a.store().has(&hashes[0]));
3106
    assert_eq!(
3107
        a.load_state_full(&a.bookmark_heads().unwrap())
3108
            .unwrap()
3109
            .len(),
3110
        10
3111
    );
3112
}
3113
3114
#[test]
3115
fn tags_are_immutable_named_states_and_travel() {
3116
    hermetic();
3117
    let dir = tempfile::tempdir().unwrap();
3118
    let root = dir.path();
3119
    let origin = Repo::init(&root.join("origin")).unwrap();
3120
    let url = root.join("origin").to_string_lossy().to_string();
3121
    let mut a = Repo::clone(&url, &root.join("a"))
3122
        .unwrap()
3123
        .with_home(root.join("home-a"));
3124
    let (key_a, _) = a
3125
        .create_identity("Ada", "[email protected]", IdentityScope::User)
3126
        .unwrap();
3127
    write(&root.join("a"), "f.txt", b"1\n");
3128
    let h1 = a.commit("one", &[]).unwrap();
3129
    write(&root.join("a"), "f.txt", b"1\n2\n");
3130
    let h2 = a.commit("two", &[]).unwrap();
3131
3132
    let t = a.tag_create("v1", &[h1], "first release").unwrap();
3133
    assert_eq!(
3134
        (t.heads.clone(), t.signer.as_deref()),
3135
        (vec![h1], Some("Ada"))
3136
    );
3137
    assert!(a.tag_create("v1", &[h2], "").is_err(), "immutable");
3138
    assert!(a.tag_create("bad/name", &[h2], "").is_err());
3139
    assert_eq!(a.tag_heads("v1").unwrap(), Some(vec![h1]));
3140
    assert_eq!(a.resolve_heads("v1").unwrap(), vec![h1]);
3141
    assert_eq!(a.resolve_heads("main").unwrap(), vec![h2]);
3142
    let (_, sa) = a.tag_attest("v1").unwrap().unwrap();
3143
    assert_eq!(sa.sigs[0].key, key_a);
3144
    // Without a policy every client is sent every tag, whatever features
3145
    // it declares (oxygen#131).
3146
    let mut refs = a.remote_refs().unwrap();
3147
    a.refs_for_client(&mut refs, None);
3148
    assert_eq!(refs.tags.len(), 1);
3149
    // Checkout by tag.
3150
    a.checkout(&a.resolve_heads("v1").unwrap(), false, "co")
3151
        .unwrap();
3152
    assert_eq!(fs::read(root.join("a/f.txt")).unwrap(), b"1\n");
3153
    a.checkout(&a.bookmark_heads().unwrap(), false, "co")
3154
        .unwrap();
3155
3156
    // Push carries the tag; a second attestation for the name is refused.
3157
    let r = a.push("origin", false).unwrap();
3158
    origin.refresh().unwrap();
3159
    assert!(r.iter().any(|x| x.name == "tags/v1" && x.ok), "{r:?}");
3160
    assert_eq!(origin.tag_heads("v1").unwrap(), Some(vec![h1]));
3161
    let mut forged = a
3162
        .tag_refs()
3163
        .unwrap()
3164
        .into_iter()
3165
        .find(|t| t.name == "v1")
3166
        .unwrap();
3167
    forged.state = origin
3168
        .store()
3169
        .put_state(&StateObject::new(vec![h2]))
3170
        .unwrap();
3171
    forged.heads = vec![h2];
3172
    forged.attestation = None;
3173
    let r = origin
3174
        .receive_push(Bundle::default(), vec![], None, vec![forged])
3175
        .unwrap();
3176
    assert!(!r[0].ok && r[0].reason.contains("immutable"), "{r:?}");
3177
3178
    // A clone gets the tag; a later tag arrives on fetch.
3179
    let b = Repo::clone(&url, &root.join("b"))
3180
        .unwrap()
3181
        .with_home(root.join("home-b"));
3182
    assert_eq!(b.tag_heads("v1").unwrap(), Some(vec![h1]));
3183
    assert!(b.tags().unwrap()[0].signer.as_deref() == Some("Ada"));
3184
    a.tag_create("v2", &[h2], "second").unwrap();
3185
    a.push("origin", false).unwrap();
3186
    origin.refresh().unwrap();
3187
    let rep = b.fetch("origin").unwrap();
3188
    assert_eq!(rep.new_tags, 1);
3189
    assert_eq!(b.tag_heads("v2").unwrap(), Some(vec![h2]));
3190
3191
    // Under a policy, an unattested tag is refused and an attested one by the root passes.
3192
    a.policy_init().unwrap();
3193
    a.push("origin", false).unwrap();
3194
    origin.refresh().unwrap();
3195
    let unattested = crate::protocol::TagRef::new(
3196
        "v3".into(),
3197
        origin
3198
            .store()
3199
            .put_state(&StateObject::new(vec![h2]))
3200
            .unwrap(),
3201
        vec![h2],
3202
        None,
3203
    );
3204
    let r = origin
3205
        .receive_push(Bundle::default(), vec![], None, vec![unattested])
3206
        .unwrap();
3207
    assert!(!r[0].ok && r[0].reason.contains("attestation"), "{r:?}");
3208
    a.tag_create("v3", &[h2], "").unwrap();
3209
    let r = a.push("origin", false).unwrap();
3210
    origin.refresh().unwrap();
3211
    assert!(r.iter().any(|x| x.name == "tags/v3" && x.ok), "{r:?}");
3212
    assert!(a.gc(true).is_ok());
3213
    assert_eq!(a.tags().unwrap().len(), 3, "tags survive gc");
3214
3215
    // After a rotation the policy names only the new key, yet a fresh clone
3216
    // still takes the tags the old key made before it; the old key makes
3217
    // nothing new.
3218
    let rot = a.rotate_identity().unwrap();
3219
    let r = a.push("origin", false).unwrap();
3220
    origin.refresh().unwrap();
3221
    assert!(r.iter().all(|x| x.ok), "{r:?}");
3222
    let c = Repo::clone(&url, &root.join("c"))
3223
        .unwrap()
3224
        .with_home(root.join("home-c"));
3225
    assert_eq!(c.tag_heads("v3").unwrap(), Some(vec![h2]));
3226
    let (_, sp) = c.current_policy().unwrap().unwrap();
3227
    assert!(!sp.policy.authorizes(&key_a, "tags/v9"));
3228
    let made = c.identity(&rot.new).unwrap().created;
3229
    assert!(c.predecessor_authorized(&sp.policy, &key_a, "tags/v9", made - 1));
3230
    assert!(!c.predecessor_authorized(&sp.policy, &key_a, "tags/v9", made));
3231
    assert!(!c.predecessor_authorized(&sp.policy, &rot.new, "tags/v9", 0));
3232
}
3233
3234
#[test]
3235
fn multiple_workspaces_share_a_repository() {
3236
    hermetic();
3237
    let dir = tempfile::tempdir().unwrap();
3238
    let root = dir.path();
3239
    let main_dir = root.join("main");
3240
    let repo = Repo::init(&main_dir).unwrap().with_home(root.join("home"));
3241
    write(&main_dir, "a.txt", b"a\n");
3242
    let h1 = repo.commit("a", &[]).unwrap();
3243
    assert_eq!(repo.workspaces().unwrap().len(), 1);
3244
3245
    // A second workspace elsewhere, checked out on the bookmark.
3246
    let ws_dir = root.join("ws2");
3247
    let ws = repo.workspace_add(&ws_dir, None).unwrap();
3248
    assert!(ws_dir.join(".oxy").is_file());
3249
    assert_eq!(fs::read(ws_dir.join("a.txt")).unwrap(), b"a\n");
3250
    assert_ne!(ws.workspace(), repo.workspace());
3251
    let list = repo.workspaces().unwrap();
3252
    assert_eq!(list.len(), 2);
3253
    assert!(list
3254
        .iter()
3255
        .any(|w| w.id == ws.workspace() && w.path == ws_dir.canonicalize().unwrap() && !w.current));
3256
    assert!(!ws.snapshot("status").unwrap().changed);
3257
3258
    // Work in the second workspace: its own working copy, shared bookmark.
3259
    write(&ws_dir, "b.txt", b"b\n");
3260
    let s = ws.snapshot("status").unwrap();
3261
    assert_eq!(s.statuses.len(), 1);
3262
    assert!(
3263
        !repo.snapshot("status").unwrap().changed,
3264
        "the first workspace is untouched"
3265
    );
3266
    let h2 = ws.commit("b from ws2", &[]).unwrap();
3267
    repo.refresh().unwrap();
3268
    let mut heads = repo.bookmark_heads().unwrap();
3269
    heads.sort();
3270
    let mut want = vec![h1, h2];
3271
    want.sort();
3272
    assert_eq!(heads, want, "both workspaces see the bookmark move");
3273
    assert!(!main_dir.join("b.txt").exists());
3274
    repo.checkout(&repo.bookmark_heads().unwrap(), false, "co")
3275
        .unwrap();
3276
    assert!(main_dir.join("b.txt").exists());
3277
3278
    // Reopening from inside the second workspace finds the shared repository.
3279
    let reopened = Repo::open(&ws_dir).unwrap();
3280
    assert_eq!(reopened.workspace(), ws.workspace());
3281
    assert_eq!(reopened.id().unwrap(), repo.id().unwrap());
3282
    assert_eq!(reopened.quick_status().unwrap().heads, 2);
3283
3284
    // Workspaces cannot nest; forget drops one from the view but keeps files.
3285
    assert!(repo.workspace_add(&main_dir.join("inner"), None).is_err());
3286
    assert!(repo.workspace_forget(&repo.workspace()).is_err());
3287
    repo.workspace_forget(&ws.workspace()).unwrap();
3288
    assert_eq!(repo.workspaces().unwrap().len(), 1);
3289
    assert!(ws_dir.join("b.txt").exists());
3290
    assert!(
3291
        ws.snapshot("status").is_err(),
3292
        "a forgotten workspace is no longer in the view"
3293
    );
3294
3295
    // The working-copy lock: re-entrant in a thread; a lock whose process
3296
    // is gone is taken over, and a live process's is not, however old.
3297
    let lock = repo.lock_snapshot().unwrap();
3298
    let again = repo.lock_working_copy().unwrap();
3299
    drop(again);
3300
    drop(lock);
3301
    let lock_path = main_dir
3302
        .join(".oxy/workspaces")
3303
        .join(repo.workspace().to_hex())
3304
        .join("lock");
3305
    let old = std::time::SystemTime::now() - std::time::Duration::from_secs(120);
3306
    let age = |p: &Path| fs::File::open(p).unwrap().set_modified(old).unwrap();
3307
    fs::write(&lock_path, std::process::id().to_string()).unwrap();
3308
    age(&lock_path);
3309
    assert!(
3310
        !super::workspace::lock_is_stale(&lock_path),
3311
        "a live process keeps its lock"
3312
    );
3313
    fs::write(&lock_path, "4294967295").unwrap();
3314
    age(&lock_path);
3315
    assert!(repo.lock_snapshot().is_ok(), "stale lock taken over");
3316
}
3317
3318
#[test]
3319
fn attributes_binary_eol_nocompress_lockable() {
3320
    hermetic();
3321
    let dir = tempfile::tempdir().unwrap();
3322
    let root = dir.path();
3323
    let repo = Repo::init(root).unwrap().with_home(root.join("home"));
3324
    write(
3325
        root,
3326
        ".oxyattributes",
3327
        b"*.dat binary nocompress\n*.txt eol=crlf\nassets/** lockable\n",
3328
    );
3329
    write(root, "plain.dat", b"no nul bytes here\n");
3330
    write(root, "notes.txt", b"one\r\ntwo\r\n");
3331
    write(root, "assets/model.bin", b"\0model");
3332
    let h = repo.commit("attrs", &[]).unwrap();
3333
    let snap = repo.load_state(&[h]).unwrap().materialize();
3334
    assert!(
3335
        snap.files["plain.dat"].mode.opaque,
3336
        "binary attribute forces opaque without NUL bytes"
3337
    );
3338
    assert!(
3339
        matches!(&snap.files["notes.txt"].content, FileContent::Text { bytes, .. } if bytes == b"one\ntwo\n"),
3340
        "stored with LF"
3341
    );
3342
    assert!(
3343
        !repo.snapshot("status").unwrap().changed,
3344
        "CRLF on disk equals LF in the state"
3345
    );
3346
    // nocompress chunks pack raw.
3347
    let r = repo.gc(true).unwrap();
3348
    assert!(r.packed.objects > 0);
3349
    // Checkout writes CRLF for eol=crlf and makes lockable files read-only.
3350
    fs::remove_file(root.join("notes.txt")).unwrap();
3351
    repo.checkout(&[h], true, "co").unwrap();
3352
    assert_eq!(fs::read(root.join("notes.txt")).unwrap(), b"one\r\ntwo\r\n");
3353
    assert!(fs::metadata(root.join("assets/model.bin"))
3354
        .unwrap()
3355
        .permissions()
3356
        .readonly());
3357
    assert!(repo.lock_path("plain.dat").is_err(), "not lockable");
3358
    repo.lock_path("assets/model.bin").unwrap();
3359
    assert!(!fs::metadata(root.join("assets/model.bin"))
3360
        .unwrap()
3361
        .permissions()
3362
        .readonly());
3363
    assert!(repo.is_locked("assets/model.bin"));
3364
    write(root, "assets/model.bin", b"\0model2");
3365
    repo.commit("edit model", &[]).unwrap();
3366
    repo.unlock_path("assets/model.bin").unwrap();
3367
    assert!(fs::metadata(root.join("assets/model.bin"))
3368
        .unwrap()
3369
        .permissions()
3370
        .readonly());
3371
    // A later checkout can still overwrite a read-only lockable file.
3372
    repo.checkout(&[h], true, "co").unwrap();
3373
    assert_eq!(fs::read(root.join("assets/model.bin")).unwrap(), b"\0model");
3374
}
3375
3376
#[cfg(unix)]
3377
#[test]
3378
fn hooks_can_veto_observe_and_add_dependencies() {
3379
    use std::os::unix::fs::PermissionsExt;
3380
    hermetic();
3381
    let dir = tempfile::tempdir().unwrap();
3382
    let root = dir.path();
3383
    let mut repo = Repo::init(root).unwrap().with_home(root.join("home"));
3384
    let hooks = root.join(".oxy/hooks");
3385
    fs::create_dir_all(&hooks).unwrap();
3386
    let hook = |name: &str, body: &str| {
3387
        let p = hooks.join(name);
3388
        fs::write(&p, format!("#!/bin/sh\n{body}\n")).unwrap();
3389
        fs::set_permissions(&p, fs::Permissions::from_mode(0o755)).unwrap();
3390
    };
3391
    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");
3392
    hook("post-commit", "cat > \"$OXY_ROOT/.last-post-commit\"");
3393
    hook("post-checkout", "cat > \"$OXY_ROOT/.last-post-checkout\"");
3394
    hook("pre-push", "echo pushing blocked >&2; exit 3");
3395
    write(root, ".oxyignore", b".last-*\n");
3396
    write(root, "a.txt", b"a\n");
3397
    let err = repo.commit("WIP: nope", &[]).unwrap_err().to_string();
3398
    assert!(err.contains("pre-commit refused: no WIP commits"), "{err}");
3399
    let h1 = repo.commit("first", &[]).unwrap();
3400
    let pre = fs::read_to_string(root.join(".last-pre-commit")).unwrap();
3401
    assert!(
3402
        pre.contains("\"event\":\"pre-commit\"")
3403
            && pre.contains("\"path\":\"a.txt\"")
3404
            && pre.contains("\"message\":\"first\""),
3405
        "{pre}"
3406
    );
3407
    let post = fs::read_to_string(root.join(".last-post-commit")).unwrap();
3408
    assert!(post.contains(&h1.to_hex()), "{post}");
3409
    repo.checkout(&[h1], false, "co").unwrap();
3410
    assert!(fs::read_to_string(root.join(".last-post-checkout"))
3411
        .unwrap()
3412
        .contains("post-checkout"));
3413
    repo.config.set("remote.origin.url", "/nowhere").unwrap();
3414
    repo.save_config().unwrap();
3415
    let err = repo.push("origin", false).unwrap_err().to_string();
3416
    assert!(err.contains("pre-push refused: pushing blocked"), "{err}");
3417
3418
    // semantic-deps: only when enabled; adds an explicit dependency.
3419
    write(root, "b.txt", b"b\n");
3420
    hook(
3421
        "semantic-deps",
3422
        &format!(
3423
            "cat > \"$OXY_ROOT/.last-semantic\"; echo '{{\"deps\": [\"{}\"]}}'",
3424
            h1.to_hex()
3425
        ),
3426
    );
3427
    let h2 = repo.commit("b without hook", &[]).unwrap();
3428
    assert!(
3429
        repo.store().get_change(&h2).unwrap().deps.is_empty(),
3430
        "hook disabled by default"
3431
    );
3432
    repo.config.set("hooks.semantic-deps", "true").unwrap();
3433
    repo.save_config().unwrap();
3434
    write(root, "c.txt", b"c\n");
3435
    let h3 = repo.commit("c with hook", &[]).unwrap();
3436
    assert_eq!(repo.store().get_change(&h3).unwrap().deps, vec![h1]);
3437
    let sem = fs::read_to_string(root.join(".last-semantic")).unwrap();
3438
    assert!(
3439
        sem.contains("\"touched_paths\":[\"c.txt\"]") && sem.contains("candidate_deps"),
3440
        "{sem}"
3441
    );
3442
    assert_eq!(json_str("a\"b\\c\n"), "\"a\\\"b\\\\c\\n\"");
3443
}
3444
3445
#[test]
3446
fn amend_into_older_change_and_split() {
3447
    hermetic();
3448
    let dir = tempfile::tempdir().unwrap();
3449
    let root = dir.path();
3450
    let mut repo = Repo::init(root).unwrap().with_home(root.join("home"));
3451
    repo.create_identity("Ada", "a@b", IdentityScope::User)
3452
        .unwrap();
3453
    repo.set_user_config("core.sign", "change").unwrap();
3454
    write(root, "a.txt", b"one\ntwo\n");
3455
    let h0 = repo.commit("base", &[]).unwrap();
3456
    write(root, "a.txt", b"one\nTWO\n");
3457
    let h1 = repo.commit("edit two", &[]).unwrap();
3458
    write(root, "a.txt", b"one\nTWO\nthree\n");
3459
    let h2 = repo.commit("add three", &[]).unwrap();
3460
    let id1 = repo.store().get_change(&h1).unwrap().change_id;
3461
3462
    // Fixing the line h1 introduced folds into h1; h2 is rewritten on top.
3463
    write(root, "a.txt", b"one\nTWO!\nthree\n");
3464
    let h1b = repo.amend_into(&h1, None).unwrap();
3465
    assert_ne!(h1b, h1);
3466
    let c1b = repo.store().get_change(&h1b).unwrap();
3467
    assert_eq!(c1b.change_id, id1);
3468
    assert_eq!(c1b.deps, vec![h0]);
3469
    assert!(matches!(
3470
        repo.verify_change(&h1b).unwrap(),
3471
        SignatureStatus::Valid { .. }
3472
    ));
3473
    let heads = repo.bookmark_heads().unwrap();
3474
    assert_eq!(heads.len(), 1);
3475
    let top = repo.store().get_change(&heads[0]).unwrap();
3476
    assert_eq!(top.message, "add three");
3477
    assert_eq!(
3478
        top.deps.iter().copied().collect::<BTreeSet<_>>(),
3479
        [h0, h1b].into_iter().collect(),
3480
        "depends on the file's creator and the rewritten line"
3481
    );
3482
    let snap = repo.load_state(&heads).unwrap().materialize();
3483
    assert!(
3484
        matches!(&snap.files["a.txt"].content, FileContent::Text { bytes, .. } if bytes == b"one\nTWO!\nthree\n")
3485
    );
3486
    assert!(
3487
        !repo.snapshot("status").unwrap().changed,
3488
        "the working copy is clean after folding"
3489
    );
3490
    // Only h1b's own state shows the fix without "three".
3491
    let only = repo.load_state(&[h1b]).unwrap().materialize();
3492
    assert!(
3493
        matches!(&only.files["a.txt"].content, FileContent::Text { bytes, .. } if bytes == b"one\nTWO!\n")
3494
    );
3495
    assert_eq!(repo.log().unwrap().len(), 4);
3496
3497
    // An edit to a line introduced by h2 cannot fold into h1.
3498
    write(root, "a.txt", b"one\nTWO!\nthree!\n");
3499
    let err = repo.amend_into(&h1b, None).unwrap_err().to_string();
3500
    assert!(err.contains("introduced after"), "{err}");
3501
    assert!(
3502
        repo.snapshot("status").unwrap().statuses.len() == 1,
3503
        "nothing was changed by the refusal"
3504
    );
3505
    write(root, "a.txt", b"one\nTWO!\nthree\n");
3506
3507
    // Split the head that touches two files.
3508
    write(root, "b.txt", b"b\n");
3509
    write(root, "c.txt", b"c\n");
3510
    let h3 = repo.commit("b and c", &[]).unwrap();
3511
    let id3 = repo.store().get_change(&h3).unwrap().change_id;
3512
    let (p1, p2) = repo.split(&h3, &["b.txt".into()]).unwrap();
3513
    let c_1 = repo.store().get_change(&p1).unwrap();
3514
    let c_2 = repo.store().get_change(&p2).unwrap();
3515
    assert!(c_1.message.contains("part 1: b.txt"));
3516
    assert_eq!(c_2.change_id, id3);
3517
    let heads: BTreeSet<_> = repo.bookmark_heads().unwrap().into_iter().collect();
3518
    assert!(
3519
        heads.contains(&p1) && heads.contains(&p2),
3520
        "independent parts are both heads"
3521
    );
3522
    let snap = repo
3523
        .load_state(&repo.bookmark_heads().unwrap())
3524
        .unwrap()
3525
        .materialize();
3526
    assert!(snap.files.contains_key("b.txt") && snap.files.contains_key("c.txt"));
3527
    let only1 = repo.load_state(&[p1]).unwrap().materialize();
3528
    assert!(only1.files.contains_key("b.txt") && !only1.files.contains_key("c.txt"));
3529
    assert!(!repo.snapshot("status").unwrap().changed);
3530
    assert!(repo.split(&p2, &["nope.txt".into()]).is_err());
3531
    let _ = h2;
3532
}
3533
3534
#[test]
3535
fn identity_lifecycle() {
3536
    hermetic();
3537
    let dir = tempfile::tempdir().unwrap();
3538
    let root = dir.path();
3539
    let origin = Repo::init(&root.join("origin")).unwrap();
3540
    let url = root.join("origin").to_string_lossy().to_string();
3541
    let mut a = Repo::clone(&url, &root.join("a"))
3542
        .unwrap()
3543
        .with_home(root.join("home-a"));
3544
    a.set_user_config("core.sign", "change").unwrap();
3545
    let (key_a, _) = a
3546
        .create_identity("Ada", "[email protected]", IdentityScope::User)
3547
        .unwrap();
3548
    write(&root.join("a"), "a.txt", b"a\n");
3549
    let h1 = a.commit("one", &[]).unwrap();
3550
    assert!(a.policy_init().unwrap().applied);
3551
    assert!(a.push("origin", false).unwrap().iter().all(|r| r.ok));
3552
    origin.refresh().unwrap();
3553
3554
    // Expiry: an identity that had expired when the change was made does not authenticate it.
3555
    let mut e = Repo::init(&root.join("e"))
3556
        .unwrap()
3557
        .with_home(root.join("home-e"));
3558
    e.set_user_config("core.sign", "change").unwrap();
3559
    e.create_identity_with(
3560
        "Eve",
3561
        "[email protected]",
3562
        IdentityScope::User,
3563
        Some(Hlc::now().wall_ms - 1),
3564
    )
3565
    .unwrap();
3566
    write(&root.join("e"), "e.txt", b"e\n");
3567
    let he = e.commit("late", &[]).unwrap();
3568
    assert!(
3569
        matches!(e.verify_change(&he).unwrap(), SignatureStatus::Invalid(m) if m.contains("expired"))
3570
    );
3571
    // Renewal re-issues the identity (same keys, new KeyId) with a later expiry.
3572
    let r = e
3573
        .renew_identity(Some(Hlc::now().wall_ms + 86_400_000))
3574
        .unwrap();
3575
    assert_eq!(e.identity(&r.new).unwrap().previous, Some(r.old));
3576
    write(&root.join("e"), "e.txt", b"e2\n");
3577
    let he2 = e.commit("in time", &[]).unwrap();
3578
    assert!(
3579
        matches!(e.verify_change(&he2).unwrap(), SignatureStatus::Valid { key, .. } if key == r.new)
3580
    );
3581
3582
    // Rotation: a fresh key; the old change still verifies; the policy follows.
3583
    let r = a.rotate_identity().unwrap();
3584
    assert_eq!(r.old, key_a);
3585
    assert_eq!(a.config.author_key, Some(r.new));
3586
    assert_eq!(a.identity(&r.new).unwrap().previous, Some(key_a));
3587
    assert!(r.policy.as_ref().unwrap().applied);
3588
    let (_, sp) = a.current_policy().unwrap().unwrap();
3589
    assert_eq!(
3590
        (sp.policy.serial, sp.policy.roots.clone()),
3591
        (2, vec![r.new])
3592
    );
3593
    assert!(
3594
        !sp.policy.revoked.contains(&key_a) && sp.policy.authorizes(&r.new, "main"),
3595
        "superseded, not revoked"
3596
    );
3597
    assert!(sp.policy.succeeds(&r.new, &key_a) && !sp.policy.succeeds(&key_a, &r.new));
3598
    assert!(
3599
        matches!(a.verify_change(&h1).unwrap(), SignatureStatus::Valid { key, revoked: false, .. } if key == key_a)
3600
    );
3601
    write(&root.join("a"), "a.txt", b"a2\n");
3602
    let h2 = a.commit("two", &[]).unwrap();
3603
    assert!(
3604
        matches!(a.verify_change(&h2).unwrap(), SignatureStatus::Valid { key, revoked: false, .. } if key == r.new)
3605
    );
3606
    // Origin accepts the rotated policy (signed by the old root) and the new key's change.
3607
    let res = a.push("origin", false).unwrap();
3608
    origin.refresh().unwrap();
3609
    assert!(res.iter().all(|x| x.ok), "{res:?}");
3610
    assert_eq!(origin.current_policy().unwrap().unwrap().1.policy.serial, 2);
3611
    let key_a = r.new;
3612
3613
    // Delegation: Bob may sign on Ada's behalf. Delegates live in the
3614
    // identity object, so Ada's KeyId changes while her keys stay the same.
3615
    let mut b = Repo::clone(&url, &root.join("b"))
3616
        .unwrap()
3617
        .with_home(root.join("home-b"));
3618
    let (key_b, id_b) = b
3619
        .create_identity("Bob", "[email protected]", IdentityScope::User)
3620
        .unwrap();
3621
    let r = a.delegate_add(id_b.clone(), Scope::ALL, None).unwrap();
3622
    assert_eq!(r.old, key_a);
3623
    let key_a2 = r.new;
3624
    assert_eq!(
3625
        a.identity(&key_a2).unwrap().delegates,
3626
        vec![Delegate::full(key_b)]
3627
    );
3628
    assert_eq!(
3629
        a.identity(&key_a2).unwrap().ed25519_pk,
3630
        a.identity(&key_a).unwrap().ed25519_pk
3631
    );
3632
    assert!(
3633
        a.delegate_add(id_b.clone(), Scope::ALL, None).is_err(),
3634
        "already a delegate"
3635
    );
3636
    assert!(a.push("origin", false).unwrap().iter().all(|x| x.ok));
3637
    origin.refresh().unwrap();
3638
    write(&root.join("a"), "a.txt", b"a3\n");
3639
    let h3 = a.commit("three", &[]).unwrap();
3640
    assert!(
3641
        matches!(a.verify_change(&h3).unwrap(), SignatureStatus::Valid { key, .. } if key == key_a2),
3642
        "the same secret signs under the new KeyId"
3643
    );
3644
    // A change authored by Ada but signed only by Bob verifies through the delegation.
3645
    a.set_user_config("core.sign", "seal").unwrap();
3646
    write(&root.join("a"), "a.txt", b"a4\n");
3647
    let h4 = a.commit("four", &[]).unwrap();
3648
    assert_eq!(a.verify_change(&h4).unwrap(), SignatureStatus::Unsigned);
3649
    let (_, sk_b) = b.secret_key().unwrap().unwrap();
3650
    a.store()
3651
        .put_signature(&h4, &sk_b.sign(Domain::Change, &key_b, &h4))
3652
        .unwrap();
3653
    assert!(
3654
        matches!(a.verify_change(&h4).unwrap(), SignatureStatus::Valid { key, .. } if key == key_b)
3655
    );
3656
    a.set_user_config("core.sign", "change").unwrap();
3657
    // Withdrawing the delegation re-issues the identity again.
3658
    let r = a.delegate_remove(&key_b).unwrap();
3659
    assert!(a.identity(&r.new).unwrap().delegates.is_empty());
3660
    assert!(a.delegate_remove(&key_b).is_err());
3661
    let key_a3 = r.new;
3662
    let res = a.push("origin", false).unwrap();
3663
    origin.refresh().unwrap();
3664
    assert!(res.iter().all(|x| x.ok), "{res:?}");
3665
3666
    // Multi-signer policy: Bob becomes a root and the threshold rises to 2,
3667
    // both applied under the old threshold of 1. A grant then needs Bob too.
3668
    assert!(a.policy_root_add(id_b.clone()).unwrap().applied);
3669
    assert!(a.policy_root_add(id_b.clone()).is_err());
3670
    assert!(a.policy_set_threshold(3).is_err());
3671
    assert!(a.policy_set_threshold(2).unwrap().applied);
3672
    assert!(a.push("origin", false).unwrap().iter().all(|x| x.ok));
3673
    origin.refresh().unwrap();
3674
    b.pull("origin").unwrap();
3675
    assert_eq!(
3676
        b.current_policy().unwrap().unwrap().1.policy.root_threshold,
3677
        2
3678
    );
3679
    let mut c = Repo::init(&root.join("c"))
3680
        .unwrap()
3681
        .with_home(root.join("home-c"));
3682
    let (key_c, id_c) = c
3683
        .create_identity("Cy", "[email protected]", IdentityScope::User)
3684
        .unwrap();
3685
    let serial_before = a.current_policy().unwrap().unwrap().1.policy.serial;
3686
    let proposal = a.policy_grant(id_c, None).unwrap();
3687
    assert!(!proposal.applied && proposal.sigs.len() == 1);
3688
    assert_eq!(proposal.policy.serial, serial_before + 1);
3689
    assert_eq!(
3690
        a.current_policy().unwrap().unwrap().1.policy.serial,
3691
        serial_before,
3692
        "a proposal changes nothing yet"
3693
    );
3694
    // Bob signs the proposal, handed over as a file, and it applies for him.
3695
    let bytes = proposal.signed().encode();
3696
    let signed = b
3697
        .policy_sign(SignedPolicy::decode(&bytes).unwrap())
3698
        .unwrap();
3699
    assert!(signed.applied && signed.sigs.len() == 2);
3700
    assert!(b
3701
        .current_policy()
3702
        .unwrap()
3703
        .unwrap()
3704
        .1
3705
        .policy
3706
        .authorizes(&key_c, "main"));
3707
    assert!(
3708
        b.policy_sign(signed.signed()).is_err(),
3709
        "a stale proposal is refused"
3710
    );
3711
    // Bob publishes it and Ada picks it up.
3712
    assert!(b
3713
        .push("origin", false)
3714
        .unwrap()
3715
        .iter()
3716
        .any(|x| x.name == "policy" && x.ok));
3717
    origin.refresh().unwrap();
3718
    a.pull("origin").unwrap();
3719
    assert_eq!(
3720
        a.current_policy().unwrap().unwrap().1.policy.serial,
3721
        serial_before + 1
3722
    );
3723
    // A root cannot revoke itself; revoking Cy needs both roots but is recorded locally at once.
3724
    assert!(a.policy_revoke(&key_a3).is_err());
3725
    let u = a
3726
        .revoke_identity(&key_c, "left the project")
3727
        .unwrap()
3728
        .unwrap();
3729
    assert!(!u.applied);
3730
    assert!(a.is_revoked(&key_c).unwrap());
3731
    assert!(!b.is_revoked(&key_c).unwrap());
3732
    let u = b.policy_sign(u.signed()).unwrap();
3733
    assert!(u.applied && u.policy.is_revoked(&key_c));
3734
    assert!(b.is_revoked(&key_c).unwrap());
3735
    // Bob can revoke Ada's root key, leaving himself as the only root (threshold 2 would be unmeetable).
3736
    assert!(
3737
        b.policy_revoke(&key_a3).is_err(),
3738
        "would leave one root for a threshold of 2"
3739
    );
3740
    // Revoking one's own key without a policy root works locally: a plain marker plus attestation.
3741
    let key_c_own = c.config.author_key.unwrap();
3742
    assert!(c
3743
        .revoke_identity(&key_c_own, "lost laptop")
3744
        .unwrap()
3745
        .is_none());
3746
    assert!(c.is_revoked(&key_c_own).unwrap());
3747
    assert_eq!(key_c_own, key_c);
3748
}
3749
3750
#[test]
3751
fn renames_are_detected_and_tracked_as_moves() {
3752
    hermetic();
3753
    let dir = tempfile::tempdir().unwrap();
3754
    let root = dir.path();
3755
    let repo = Repo::init(root).unwrap().with_home(root.join("home"));
3756
    write(
3757
        root,
3758
        "src/old.rs",
3759
        b"fn a() {}\nfn b() {}\nfn c() {}\nfn d() {}\n",
3760
    );
3761
    write(root, "img.bin", b"\x89PNG\0\0\x01\x02");
3762
    write(root, "tiny.txt", b"x\n");
3763
    let h1 = repo.commit("base", &[]).unwrap();
3764
    let node_old = repo.load_state(&[h1]).unwrap().materialize().files["src/old.rs"].node;
3765
    let node_img = repo.load_state(&[h1]).unwrap().materialize().files["img.bin"].node;
3766
3767
    // Rename with a small edit, a binary moved unchanged, and a rewrite
3768
    // that shares nothing with the removed file.
3769
    fs::remove_file(root.join("src/old.rs")).unwrap();
3770
    write(
3771
        root,
3772
        "lib/new.rs",
3773
        b"fn a() {}\nfn b() {}\nfn c() {}\nfn e() {}\n",
3774
    );
3775
    fs::remove_file(root.join("img.bin")).unwrap();
3776
    write(root, "assets/img.bin", b"\x89PNG\0\0\x01\x02");
3777
    fs::remove_file(root.join("tiny.txt")).unwrap();
3778
    write(root, "other.txt", b"completely different\n");
3779
    let snap = repo.snapshot("status").unwrap();
3780
    let statuses: Vec<(&str, ChangeStatus)> = snap
3781
        .statuses
3782
        .iter()
3783
        .map(|s| (s.path.as_str(), s.status))
3784
        .collect();
3785
    assert_eq!(
3786
        statuses,
3787
        vec![
3788
            ("assets/img.bin", ChangeStatus::Renamed),
3789
            ("lib/new.rs", ChangeStatus::Renamed),
3790
            ("other.txt", ChangeStatus::Added),
3791
            ("src", ChangeStatus::Removed),
3792
            ("tiny.txt", ChangeStatus::Removed)
3793
        ]
3794
    );
3795
    let h2 = repo.commit("move things", &[]).unwrap();
3796
    let c = repo.store().get_change(&h2).unwrap();
3797
    let moves: Vec<_> = c
3798
        .tree_ops
3799
        .iter()
3800
        .filter(|op| matches!(op, TreeOp::Move { .. }))
3801
        .collect();
3802
    assert_eq!(moves.len(), 2, "{:?}", c.tree_ops);
3803
    assert!(c.tree_ops.iter().any(
3804
        |op| matches!(op, TreeOp::Move { node, name, .. } if *node == node_old && name == "new.rs")
3805
    ));
3806
    assert!(c.tree_ops.iter().any(
3807
        |op| matches!(op, TreeOp::Move { node, name, .. } if *node == node_img && name == "img.bin")
3808
    ));
3809
    let snap = repo.load_state(&[h2]).unwrap().materialize();
3810
    assert_eq!(
3811
        snap.files["lib/new.rs"].node, node_old,
3812
        "the node survives the rename"
3813
    );
3814
    assert!(
3815
        matches!(&snap.files["lib/new.rs"].content, FileContent::Text { bytes, .. } if bytes == b"fn a() {}\nfn b() {}\nfn c() {}\nfn e() {}\n")
3816
    );
3817
    assert!(!snap.files.contains_key("src/old.rs") && !snap.files.contains_key("src"));
3818
    assert!(render_change(
3819
        &c,
3820
        &repo.load_state(&[h1]).unwrap(),
3821
        &repo.load_state(&[h1]).unwrap().materialize()
3822
    )
3823
    .contains("R "));
3824
    // A fresh checkout reproduces the tree.
3825
    let other = tempfile::tempdir().unwrap();
3826
    let clone = Repo::clone(&root.to_string_lossy(), other.path()).unwrap();
3827
    assert_eq!(
3828
        fs::read(other.path().join("lib/new.rs")).unwrap(),
3829
        b"fn a() {}\nfn b() {}\nfn c() {}\nfn e() {}\n"
3830
    );
3831
    assert!(!other.path().join("src").exists());
3832
    assert!(!clone.snapshot("status").unwrap().changed);
3833
    // Similarity is line based, byte weighted.
3834
    assert_eq!(similarity(b"a\nb\n", b"a\nb\n"), 100);
3835
    assert_eq!(similarity(b"a\nb\nc\nd\n", b"a\nb\nx\ny\n"), 50);
3836
    assert_eq!(similarity(b"hello\n", b"world\n"), 0);
3837
    assert_eq!(similarity(b"", b"x\n"), 0);
3838
}
3839
3840
#[test]
3841
fn git_fetch_and_push_round_trip() {
3842
    hermetic();
3843
    if std::process::Command::new("git")
3844
        .arg("--version")
3845
        .output()
3846
        .is_err()
3847
    {
3848
        eprintln!("git not installed; skipping");
3849
        return;
3850
    }
3851
    let dir = tempfile::tempdir().unwrap();
3852
    let root = dir.path();
3853
    let git_in = |d: &Path, args: &[&str]| -> String {
3854
        let out = std::process::Command::new("git")
3855
            .arg("-C")
3856
            .arg(d)
3857
            .args([
3858
                "-c",
3859
                "user.name=Grace",
3860
                "-c",
3861
                "[email protected]",
3862
                "-c",
3863
                "commit.gpgsign=false",
3864
            ])
3865
            .args(args)
3866
            .output()
3867
            .unwrap();
3868
        assert!(
3869
            out.status.success(),
3870
            "git {args:?}: {}",
3871
            String::from_utf8_lossy(&out.stderr)
3872
        );
3873
        String::from_utf8_lossy(&out.stdout).trim().to_string()
3874
    };
3875
    // A bare "remote" and a work tree that pushes to it.
3876
    let remote = root.join("remote.git");
3877
    fs::create_dir_all(&remote).unwrap();
3878
    git_in(&remote, &["init", "-q", "--bare", "-b", "main"]);
3879
    let work = root.join("work");
3880
    git_in(
3881
        root,
3882
        &[
3883
            "clone",
3884
            "-q",
3885
            remote.to_str().unwrap(),
3886
            work.to_str().unwrap(),
3887
        ],
3888
    );
3889
    git_in(&work, &["checkout", "-q", "-b", "main"]);
3890
    write(&work, "README.md", b"# Project\n");
3891
    write(&work, "src/lib.rs", b"pub fn a() {}\n");
3892
    git_in(&work, &["add", "."]);
3893
    git_in(&work, &["commit", "-q", "-m", "initial"]);
3894
    write(&work, "src/lib.rs", b"pub fn a() {}\npub fn b() {}\n");
3895
    git_in(&work, &["commit", "-q", "-am", "second"]);
3896
    git_in(&work, &["push", "-q", "origin", "main"]);
3897
    let tip1 = git_in(&work, &["rev-parse", "HEAD"]);
3898
3899
    // Fetch into a fresh oxy repository.
3900
    let o = root.join("oxy");
3901
    let mut repo = Repo::init(&o).unwrap().with_home(root.join("home"));
3902
    repo.create_identity("Ada", "[email protected]", IdentityScope::User)
3903
        .unwrap();
3904
    let url = remote.to_string_lossy().to_string();
3905
    let r = repo.git_fetch(&url, "main").unwrap();
3906
    assert_eq!((r.commits, r.heads), (2, 1));
3907
    assert_eq!(
3908
        fs::read(o.join("src/lib.rs")).unwrap(),
3909
        b"pub fn a() {}\npub fn b() {}\n"
3910
    );
3911
    assert!(!repo.snapshot("status").unwrap().changed);
3912
    assert_eq!(
3913
        repo.git_fetch(&url, "main").unwrap().commits,
3914
        0,
3915
        "nothing new"
3916
    );
3917
3918
    // An oxy change, pushed back: one commit on top of the Git tip.
3919
    write(
3920
        &o,
3921
        "src/lib.rs",
3922
        b"pub fn a() {}\npub fn b() {}\npub fn c() {}\n",
3923
    );
3924
    write(&o, "NOTES.md", b"from oxy\n");
3925
    let h_oxy = repo.commit("add c and notes", &[]).unwrap();
3926
    let r = repo.git_push(&url, "main").unwrap();
3927
    assert_eq!(r.exported, 1, "{r:?}");
3928
    git_in(&work, &["pull", "-q", "--ff-only", "origin", "main"]);
3929
    assert_eq!(
3930
        git_in(&work, &["log", "--format=%s", "main"]),
3931
        "add c and notes\nsecond\ninitial"
3932
    );
3933
    assert_eq!(git_in(&work, &["rev-parse", "HEAD~1"]), tip1);
3934
    assert_eq!(fs::read(work.join("NOTES.md")).unwrap(), b"from oxy\n");
3935
    assert_eq!(git_in(&work, &["log", "-1", "--format=%an", "main"]), "Ada");
3936
    assert!(git_in(&work, &["log", "-1", "--format=%B", "main"])
3937
        .contains(&format!("Oxy-Hash: {}", h_oxy.to_hex())));
3938
    assert_eq!(
3939
        repo.git_push(&url, "main").unwrap().exported,
3940
        0,
3941
        "already pushed"
3942
    );
3943
3944
    // Git moves on; pushing without fetching is refused, fetching brings
3945
    // the commit in and the working copy follows.
3946
    write(&work, "README.md", b"# Project\n\nMore.\n");
3947
    git_in(&work, &["commit", "-q", "-am", "readme from git"]);
3948
    git_in(&work, &["push", "-q", "origin", "main"]);
3949
    let tip2 = git_in(&work, &["rev-parse", "HEAD"]);
3950
    assert!(repo
3951
        .git_push(&url, "main")
3952
        .unwrap_err()
3953
        .to_string()
3954
        .contains("fetch"));
3955
    let r = repo.git_fetch(&url, "main").unwrap();
3956
    assert_eq!(
3957
        (r.commits, r.heads),
3958
        (1, 2),
3959
        "the Git change and the oxy change commute"
3960
    );
3961
    assert_eq!(
3962
        fs::read(o.join("README.md")).unwrap(),
3963
        b"# Project\n\nMore.\n"
3964
    );
3965
    assert_eq!(fs::read(o.join("NOTES.md")).unwrap(), b"from oxy\n");
3966
    assert!(!repo.snapshot("status").unwrap().changed);
3967
    // Another oxy change pushes on top of Git's newest commit.
3968
    write(&o, "NOTES.md", b"from oxy\nagain\n");
3969
    repo.commit("notes again", &[]).unwrap();
3970
    assert_eq!(repo.git_push(&url, "main").unwrap().exported, 1);
3971
    git_in(&work, &["pull", "-q", "--ff-only", "origin", "main"]);
3972
    assert_eq!(git_in(&work, &["rev-parse", "HEAD~1"]), tip2);
3973
    assert_eq!(
3974
        fs::read(work.join("NOTES.md")).unwrap(),
3975
        b"from oxy\nagain\n"
3976
    );
3977
    assert_eq!(
3978
        git_in(&work, &["log", "--format=%s", "main"])
3979
            .lines()
3980
            .count(),
3981
        5
3982
    );
3983
}
3984
3985
/// Benchmark, not a gate: `cargo test --release -p oxy-core --lib bench_one_gibibyte -- --ignored --nocapture`.
3986
/// Commits, stores, clones, and reads back a 1 GiB incompressible file.
3987
#[test]
3988
#[ignore]
3989
fn bench_one_gibibyte_file() {
3990
    hermetic();
3991
    // /tmp is often a small tmpfs; `OXY_BENCH_DIR` picks a roomier disk.
3992
    let dir = match std::env::var_os("OXY_BENCH_DIR") {
3993
        Some(d) => tempfile::tempdir_in(d).unwrap(),
3994
        None => tempfile::tempdir().unwrap(),
3995
    };
3996
    let root = dir.path();
3997
    let repo = Repo::init(&root.join("r"))
3998
        .unwrap()
3999
        .with_home(root.join("home"));
4000
    let size = 1usize << 30;
4001
    let mut data = vec![0u8; size];
4002
    let mut x = 0x9e3779b97f4a7c15u64;
4003
    for chunk in data.chunks_mut(8) {
4004
        x ^= x << 13;
4005
        x ^= x >> 7;
4006
        x ^= x << 17;
4007
        let b = x.to_le_bytes();
4008
        chunk.copy_from_slice(&b[..chunk.len()]);
4009
    }
4010
    let t = std::time::Instant::now();
4011
    write(&root.join("r"), "big.bin", &data);
4012
    eprintln!("write 1 GiB to disk: {:.2?}", t.elapsed());
4013
    let t = std::time::Instant::now();
4014
    let h = repo.commit("big", &[]).unwrap();
4015
    eprintln!("commit (chunk + hash + store): {:.2?}", t.elapsed());
4016
    let t = std::time::Instant::now();
4017
    assert!(!repo.snapshot("status").unwrap().changed);
4018
    eprintln!("status on a clean 1 GiB working copy: {:.2?}", t.elapsed());
4019
    let t = std::time::Instant::now();
4020
    let objects = repo.store().list().unwrap().len();
4021
    eprintln!("objects stored: {objects} ({:.2?} to list)", t.elapsed());
4022
    let t = std::time::Instant::now();
4023
    let g = repo.gc(true).unwrap();
4024
    eprintln!("gc (pack): {:.2?} {g:?}", t.elapsed());
4025
    let t = std::time::Instant::now();
4026
    let clone = Repo::clone(&root.join("r").to_string_lossy(), &root.join("c")).unwrap();
4027
    eprintln!("clone (fetch + checkout): {:.2?}", t.elapsed());
4028
    let t = std::time::Instant::now();
4029
    let back = fs::read(root.join("c/big.bin")).unwrap();
4030
    assert_eq!(blake3::hash(&back), blake3::hash(&data));
4031
    eprintln!("read back and verify: {:.2?}", t.elapsed());
4032
    assert_eq!(clone.bookmark_heads().unwrap(), vec![h]);
4033
    let store_bytes: u64 = walkdir_size(&root.join("r/.oxy/objects"));
4034
    eprintln!(
4035
        "store size: {:.1} MiB for 1 GiB of data",
4036
        store_bytes as f64 / (1024.0 * 1024.0)
4037
    );
4038
}
4039
4040
fn walkdir_size(p: &Path) -> u64 {
4041
    let mut total = 0;
4042
    if let Ok(rd) = fs::read_dir(p) {
4043
        for e in rd.flatten() {
4044
            let path = e.path();
4045
            if path.is_dir() {
4046
                total += walkdir_size(&path);
4047
            } else if let Ok(m) = fs::metadata(&path) {
4048
                total += m.len();
4049
            }
4050
        }
4051
    }
4052
    total
4053
}
4054
4055
/// An opaque file whose size and mtime match the manifest is not read on
4056
/// the next snapshot: its blob comes from the manifest's stat cache.
4057
#[cfg(unix)]
4058
#[test]
4059
fn stat_cache_skips_reading_unchanged_opaque_files() {
4060
    use std::os::unix::fs::PermissionsExt;
4061
    hermetic();
4062
    let dir = tempfile::tempdir().unwrap();
4063
    let root = dir.path();
4064
    let repo = Repo::init(root).unwrap().with_home(root.join("home"));
4065
    let mut big = vec![0u8; 300 * 1024];
4066
    for (i, b) in big.iter_mut().enumerate() {
4067
        *b = (i as u32).wrapping_mul(2654435761).to_le_bytes()[1];
4068
    }
4069
    big[0] = 0;
4070
    write(root, "big.bin", &big);
4071
    write(root, "a.txt", b"text\n");
4072
    let h1 = repo.commit("base", &[]).unwrap();
4073
    let (_, _, m) = repo.read_manifest().unwrap().unwrap();
4074
    assert!(
4075
        m.entries["big.bin"].blob.is_some(),
4076
        "opaque files record their blob"
4077
    );
4078
    assert!(m.entries["a.txt"].blob.is_none());
4079
    let blob = m.entries["big.bin"].blob.unwrap();
4080
    assert!(repo.store().has(&blob));
4081
4082
    // Files modified within two seconds of the manifest are racy and still
4083
    // read; age the file so the cache applies, then snapshot to record it.
4084
    let old = std::time::SystemTime::now() - std::time::Duration::from_secs(30);
4085
    fs::File::options()
4086
        .write(true)
4087
        .open(root.join("big.bin"))
4088
        .unwrap()
4089
        .set_modified(old)
4090
        .unwrap();
4091
    assert!(!repo.snapshot("status").unwrap().changed);
4092
    // Now the file cannot be read at all; the snapshot succeeds without it.
4093
    fs::set_permissions(root.join("big.bin"), fs::Permissions::from_mode(0o000)).unwrap();
4094
    let snap = repo.snapshot("status").unwrap();
4095
    assert!(
4096
        !snap.changed && snap.statuses.is_empty(),
4097
        "{:?}",
4098
        snap.statuses
4099
    );
4100
    fs::set_permissions(root.join("big.bin"), fs::Permissions::from_mode(0o644)).unwrap();
4101
    // A real change (new mtime, new content) is seen and committed correctly.
4102
    let mut big2 = big.clone();
4103
    big2[10] ^= 0xff;
4104
    write(root, "big.bin", &big2);
4105
    let snap = repo.snapshot("status").unwrap();
4106
    assert_eq!(
4107
        snap.statuses
4108
            .iter()
4109
            .map(|s| (s.path.as_str(), s.status))
4110
            .collect::<Vec<_>>(),
4111
        vec![("big.bin", ChangeStatus::Modified)]
4112
    );
4113
    let h2 = repo.commit("edit", &[]).unwrap();
4114
    let files = repo.load_state(&[h2]).unwrap().materialize().files;
4115
    assert_eq!(
4116
        files["big.bin"].content,
4117
        FileContent::Opaque {
4118
            blobs: vec![Repo::blob_ref(&big2)]
4119
        }
4120
    );
4121
    // Checkout writes a manifest with blobs too, so the next status is cached.
4122
    repo.checkout(&[h1], false, "checkout").unwrap();
4123
    let (_, _, m) = repo.read_manifest().unwrap().unwrap();
4124
    assert_eq!(m.entries["big.bin"].blob, Some(Repo::blob_ref(&big)));
4125
    assert!(!repo.snapshot("status").unwrap().changed);
4126
}
4127
4128
#[test]
4129
fn status_json_lists_conflicts_with_contributors() {
4130
    hermetic();
4131
    let dir = tempfile::tempdir().unwrap();
4132
    let root = dir.path();
4133
    let repo = Repo::init(root).unwrap().with_home(root.join("home"));
4134
    write(root, "a.txt", b"one\n");
4135
    let h1 = repo.commit("base", &[]).unwrap();
4136
    write(root, "a.txt", b"one\nleft\n");
4137
    let ha = repo.commit("left", &[]).unwrap();
4138
    repo.checkout(&[h1], true, "checkout").unwrap();
4139
    write(root, "a.txt", b"one\nright\n");
4140
    let hb = repo.commit("right", &[]).unwrap();
4141
    repo.checkout(&[ha, hb], true, "checkout").unwrap();
4142
    let snap = repo.snapshot("status").unwrap();
4143
    assert!(snap.base_snapshot.is_conflicted());
4144
    let json = repo.status_json(&snap).unwrap();
4145
    let ida = repo.store().get_change(&ha).unwrap().change_id.to_hex();
4146
    let idb = repo.store().get_change(&hb).unwrap().change_id.to_hex();
4147
    assert!(json.contains("\"conflicted\":true"), "{json}");
4148
    assert!(
4149
        json.contains("\"kind\":\"text\",\"path\":\"a.txt\""),
4150
        "{json}"
4151
    );
4152
    assert!(json.contains(&ida) && json.contains(&idb), "{json}");
4153
    assert!(json.contains("\"resolved\":false"), "{json}");
4154
    assert!(json.starts_with('{') && json.ends_with('}'));
4155
    // Resolve and the report says so; a clean copy has no conflicts.
4156
    write(root, "a.txt", b"one\nleft\nright\n");
4157
    let snap = repo.snapshot("status").unwrap();
4158
    let json = repo.status_json(&snap).unwrap();
4159
    assert!(json.contains("\"resolved\":true"), "{json}");
4160
    repo.commit("resolve", &[]).unwrap();
4161
    let snap = repo.snapshot("status").unwrap();
4162
    let json = repo.status_json(&snap).unwrap();
4163
    assert!(
4164
        json.contains("\"clean\":true,\"conflicted\":false,\"paths\":[],\"conflicts\":[]"),
4165
        "{json}"
4166
    );
4167
}
4168
4169
#[test]
4170
fn ignore_rules_do_not_untrack_files() {
4171
    hermetic();
4172
    let dir = tempfile::tempdir().unwrap();
4173
    let root = dir.path();
4174
    let repo = Repo::init(root).unwrap().with_home(root.join("home"));
4175
    write(root, "src.c", b"int x;\n");
4176
    write(root, "build/out.o", b"\0obj");
4177
    write(root, "sub/keep.log", b"keep\n");
4178
    write(root, "sub/junk.log", b"junk\n");
4179
    write(root, ".oxyignore", b"/build\n*.log\n!sub/keep.log\n");
4180
    let snap = repo.snapshot("status").unwrap();
4181
    let added: Vec<&str> = snap.statuses.iter().map(|s| s.path.as_str()).collect();
4182
    assert_eq!(
4183
        added,
4184
        vec![".oxyignore", "src.c", "sub/keep.log"],
4185
        "anchored, glob, and negated rules"
4186
    );
4187
    let h1 = repo.commit("base", &[]).unwrap();
4188
    // Ignoring a tracked file changes nothing about it.
4189
    write(root, ".oxyignore", b"/build\n*.log\n!sub/keep.log\nsrc.c\n");
4190
    let snap = repo.snapshot("status").unwrap();
4191
    assert_eq!(
4192
        snap.statuses
4193
            .iter()
4194
            .map(|s| s.path.as_str())
4195
            .collect::<Vec<_>>(),
4196
        vec![".oxyignore"]
4197
    );
4198
    let h2 = repo.commit("ignore src.c", &[]).unwrap();
4199
    assert!(repo
4200
        .load_state(&[h2])
4201
        .unwrap()
4202
        .materialize()
4203
        .files
4204
        .contains_key("src.c"));
4205
    // Its edits are still seen, by status and by the prompt.
4206
    assert_eq!(repo.quick_dirty().unwrap(), Some(false));
4207
    write(root, "src.c", b"int x, y;\n");
4208
    assert_eq!(repo.quick_dirty().unwrap(), Some(true));
4209
    let snap = repo.snapshot("status").unwrap();
4210
    assert_eq!(
4211
        snap.statuses
4212
            .iter()
4213
            .map(|s| (s.path.as_str(), s.status))
4214
            .collect::<Vec<_>>(),
4215
        vec![("src.c", ChangeStatus::Modified)]
4216
    );
4217
    let h3 = repo.commit("edit src.c", &[]).unwrap();
4218
    assert!(
4219
        matches!(&repo.load_state(&[h3]).unwrap().materialize().files["src.c"].content, FileContent::Text { bytes, .. } if bytes == b"int x, y;\n")
4220
    );
4221
    // Deleting it on disk removes it, ignored or not; a checkout brings it back.
4222
    fs::remove_file(root.join("src.c")).unwrap();
4223
    let snap = repo.snapshot("status").unwrap();
4224
    assert_eq!(
4225
        snap.statuses
4226
            .iter()
4227
            .map(|s| (s.path.as_str(), s.status))
4228
            .collect::<Vec<_>>(),
4229
        vec![("src.c", ChangeStatus::Removed)]
4230
    );
4231
    repo.checkout(&[h3], true, "checkout").unwrap();
4232
    assert_eq!(fs::read(root.join("src.c")).unwrap(), b"int x, y;\n");
4233
    assert!(!repo.snapshot("status").unwrap().changed);
4234
    let _ = h1;
4235
}
4236
4237
#[test]
4238
fn split_works_on_non_heads_by_node() {
4239
    hermetic();
4240
    let dir = tempfile::tempdir().unwrap();
4241
    let root = dir.path();
4242
    let repo = Repo::init(root).unwrap().with_home(root.join("home"));
4243
    write(root, "a.txt", b"one\n");
4244
    write(root, "junk/x.lock", b"lock\n");
4245
    let h1 = repo.commit("work plus junk", &[]).unwrap();
4246
    write(root, "a.txt", b"one\ntwo\n");
4247
    let h2 = repo.commit("more work", &[]).unwrap();
4248
    assert_eq!(repo.store().get_change(&h2).unwrap().deps, vec![h1]);
4249
    let id1 = repo.store().get_change(&h1).unwrap().change_id;
4250
    // h1 is not a head: split it by node.
4251
    let (hj, h1b) = repo.split(&h1, &["junk".into()]).unwrap();
4252
    assert_ne!(h1b, h1);
4253
    assert_eq!(
4254
        repo.store().get_change(&h1b).unwrap().change_id,
4255
        id1,
4256
        "the rest keeps the ChangeId"
4257
    );
4258
    let junk = repo.store().get_change(&hj).unwrap();
4259
    assert!(junk.tree_ops.iter().all(
4260
        |op| matches!(op, TreeOp::AddNode { name, .. } if name == "junk" || name == "x.lock")
4261
    ));
4262
    let heads = repo.bookmark_heads().unwrap();
4263
    assert!(
4264
        heads.contains(&hj),
4265
        "the split-off part is a head of its own"
4266
    );
4267
    let snap = repo.load_state(&heads).unwrap().materialize();
4268
    assert!(
4269
        matches!(&snap.files["a.txt"].content, FileContent::Text { bytes, .. } if bytes == b"one\ntwo\n"),
4270
        "the dependent was rewritten onto the new hash"
4271
    );
4272
    assert!(snap.files.contains_key("junk/x.lock"));
4273
    let h2b = heads
4274
        .iter()
4275
        .find(|h| repo.store().get_change(h).unwrap().message == "more work")
4276
        .copied()
4277
        .unwrap();
4278
    assert_eq!(repo.store().get_change(&h2b).unwrap().deps, vec![h1b]);
4279
    assert!(!repo.snapshot("status").unwrap().changed);
4280
    // Abandoning the split-off head removes the junk from history.
4281
    repo.abandon(&hj).unwrap();
4282
    let heads = repo.bookmark_heads().unwrap();
4283
    let snap = repo.load_state(&heads).unwrap().materialize();
4284
    assert!(!snap.files.contains_key("junk/x.lock") && !snap.files.contains_key("junk"));
4285
    assert!(snap.files.contains_key("a.txt"));
4286
    // A dependent that touches the split-off paths blocks the split.
4287
    write(root, "junk/y.lock", b"y\n");
4288
    let hb = repo.commit("junk base", &[]).unwrap();
4289
    write(root, "junk/y.lock", b"yy\n");
4290
    write(root, "b.txt", b"b\n");
4291
    repo.commit("touches junk", &[]).unwrap();
4292
    let err = repo.split(&hb, &["junk".into()]).unwrap_err().to_string();
4293
    assert!(err.contains("depends on the split-off paths"), "{err}");
4294
}
4295
4296
#[test]
4297
fn bookmarks_switch_merge_and_push() {
4298
    hermetic();
4299
    let dir = tempfile::tempdir().unwrap();
4300
    let root = dir.path();
4301
    let origin = Repo::init(&root.join("origin")).unwrap();
4302
    let url = root.join("origin").to_string_lossy().to_string();
4303
    let mut repo = Repo::clone(&url, &root.join("r"))
4304
        .unwrap()
4305
        .with_home(root.join("home"));
4306
    let r = root.join("r");
4307
    write(&r, "a.txt", b"a\n");
4308
    let h_a = repo.commit("a", &[]).unwrap();
4309
    assert!(repo.push("origin", false).unwrap()[0].ok);
4310
    origin.refresh().unwrap();
4311
4312
    // A bookmark at the working copy's base, then work on it.
4313
    assert!(repo.bookmark_create("bad name..", None).is_err());
4314
    assert!(repo.bookmark_create("-x", None).is_err());
4315
    assert_eq!(repo.bookmark_create("feature", None).unwrap(), vec![h_a]);
4316
    assert!(repo.bookmark_create("feature", None).is_err(), "exists");
4317
    repo.bookmark_switch("feature", false).unwrap();
4318
    assert_eq!(repo.config.bookmark, "feature");
4319
    write(&r, "a.txt", b"a\nb\n");
4320
    write(&r, "b.txt", b"b\n");
4321
    let h_b = repo.commit("b on feature", &[]).unwrap();
4322
    assert_eq!(
4323
        repo.bookmark_heads().unwrap(),
4324
        vec![h_b],
4325
        "b edits a.txt, so it depends on a"
4326
    );
4327
    assert_eq!(
4328
        repo.resolve_heads("main").unwrap(),
4329
        vec![h_a],
4330
        "main is untouched"
4331
    );
4332
    assert_eq!(
4333
        repo.resolve_change("feature").unwrap(),
4334
        h_b,
4335
        "a one-head bookmark names its change"
4336
    );
4337
    // Reopening keeps the workspace's bookmark.
4338
    let reopened = Repo::open(&r).unwrap().with_home(root.join("home"));
4339
    assert_eq!(reopened.config.bookmark, "feature");
4340
    // Back to main: b.txt goes away; work there.
4341
    repo.bookmark_switch("main", false).unwrap();
4342
    assert!(!r.join("b.txt").exists());
4343
    assert_eq!(fs::read(r.join("a.txt")).unwrap(), b"a\n");
4344
    write(&r, "c.txt", b"c\n");
4345
    let h_c = repo.commit("c on main", &[]).unwrap();
4346
    let list = repo.bookmarks().unwrap();
4347
    assert_eq!(
4348
        list.iter()
4349
            .map(|b| (b.name.as_str(), b.current))
4350
            .collect::<Vec<_>>(),
4351
        vec![("feature", false), ("main", true)]
4352
    );
4353
    assert_eq!(
4354
        list.iter().find(|b| b.name == "main").unwrap().ahead,
4355
        Some(1),
4356
        "c is not on origin yet"
4357
    );
4358
    // Merge feature into main: the union, both heads, no merge change.
4359
    let m = repo.merge("feature").unwrap();
4360
    assert!(m.changed && m.checked_out);
4361
    let mut want = vec![h_b, h_c];
4362
    want.sort();
4363
    assert_eq!(m.heads, want);
4364
    assert_eq!(fs::read(r.join("b.txt")).unwrap(), b"b\n");
4365
    assert!(!repo.merge("feature").unwrap().changed, "already merged");
4366
    assert!(repo.merge("main").is_err());
4367
    // The other bookmark can be pushed by name and appears at origin.
4368
    assert!(repo.push_bookmark("origin", "feature", false).unwrap()[0].ok);
4369
    origin.refresh().unwrap();
4370
    assert_eq!(origin.resolve_heads("feature").unwrap(), vec![h_b]);
4371
    assert!(repo.push("origin", false).unwrap()[0].ok);
4372
    origin.refresh().unwrap();
4373
    assert_eq!(
4374
        repo.bookmarks()
4375
            .unwrap()
4376
            .iter()
4377
            .find(|b| b.name == "main")
4378
            .unwrap()
4379
            .ahead,
4380
        Some(0)
4381
    );
4382
    // A second workspace inherits the current bookmark and can switch independently.
4383
    let ws = repo.workspace_add(&root.join("ws"), None).unwrap();
4384
    assert_eq!(ws.config.bookmark, "main");
4385
    let mut ws = ws;
4386
    ws.bookmark_switch("feature", false).unwrap();
4387
    assert_eq!(
4388
        Repo::open(&r).unwrap().config.bookmark,
4389
        "main",
4390
        "the first workspace is unaffected"
4391
    );
4392
    assert!(
4393
        repo.bookmark_delete("feature").is_err(),
4394
        "current bookmark of another workspace"
4395
    );
4396
    ws.bookmark_switch("main", false).unwrap();
4397
    // Set and delete.
4398
    assert_eq!(repo.bookmark_set("feature", &[h_a]).unwrap(), vec![h_a]);
4399
    assert!(repo.bookmark_delete("main").is_err(), "current here");
4400
    repo.bookmark_delete("feature").unwrap();
4401
    assert!(repo.resolve_heads("feature").is_err());
4402
    assert!(repo.bookmark_set("feature", &[h_a]).is_err());
4403
    assert!(
4404
        repo.checkout(&[h_a], false, "checkout").is_ok(),
4405
        "changes of a deleted bookmark remain"
4406
    );
4407
}
4408
4409
#[test]
4410
fn oxygen_subrepos_pin_follow_and_update() {
4411
    hermetic();
4412
    let dir = tempfile::tempdir().unwrap();
4413
    let root = dir.path();
4414
    // A library repository with two commits, and a bare-ish origin for it.
4415
    let lib_origin = Repo::init(&root.join("lib-origin")).unwrap();
4416
    let lib_url = root.join("lib-origin").to_string_lossy().to_string();
4417
    let lib = Repo::clone(&lib_url, &root.join("lib"))
4418
        .unwrap()
4419
        .with_home(root.join("home"));
4420
    write(&root.join("lib"), "lib.txt", b"v1\n");
4421
    let l1 = lib.commit("lib v1", &[]).unwrap();
4422
    assert!(lib.push("origin", false).unwrap()[0].ok);
4423
    let _ = lib_origin;
4424
4425
    // The application (a clone of its own origin) adds it as a subrepo.
4426
    let app_origin = Repo::init(&root.join("app-origin")).unwrap();
4427
    let app_url = root.join("app-origin").to_string_lossy().to_string();
4428
    let _ = app_origin;
4429
    let app_dir = root.join("app");
4430
    let app = Repo::clone(&app_url, &app_dir)
4431
        .unwrap()
4432
        .with_home(root.join("home"));
4433
    write(&app_dir, "main.txt", b"app\n");
4434
    let pin = app.submodule_add(&lib_url, "libs/lib", None).unwrap();
4435
    assert!(matches!(&pin, crate::subrepo::Pin::Oxy { heads, .. } if heads == &vec![l1]));
4436
    assert!(app_dir.join(".oxymodules").exists() && app_dir.join("libs/lib/.oxy").is_dir());
4437
    let snap = app.snapshot("status").unwrap();
4438
    let paths: Vec<&str> = snap.statuses.iter().map(|s| s.path.as_str()).collect();
4439
    assert_eq!(
4440
        paths,
4441
        vec![".oxymodules", "libs/lib", "main.txt"],
4442
        "the nested files are not walked"
4443
    );
4444
    let a1 = app.commit("app with lib", &[]).unwrap();
4445
    let files = app.load_state(&[a1]).unwrap().materialize().files;
4446
    assert_eq!(files["libs/lib"].kind, NodeKind::Subrepo);
4447
    assert!(!files.contains_key("libs/lib/lib.txt"));
4448
    assert!(!app.snapshot("status").unwrap().changed);
4449
    let subs = app.subrepos().unwrap();
4450
    assert_eq!(subs.len(), 1);
4451
    assert_eq!(subs[0].actual.as_ref(), Some(&subs[0].pin));
4452
4453
    // Advance the nested repository: the parent sees a modified pin.
4454
    let nested = Repo::open(&app_dir.join("libs/lib"))
4455
        .unwrap()
4456
        .with_home(root.join("home"));
4457
    write(&app_dir.join("libs/lib"), "lib.txt", b"v2\n");
4458
    let l2 = nested.commit("lib v2", &[]).unwrap();
4459
    assert!(nested.push("origin", false).unwrap()[0].ok);
4460
    let snap = app.snapshot("status").unwrap();
4461
    assert_eq!(
4462
        snap.statuses
4463
            .iter()
4464
            .map(|s| (s.path.as_str(), s.status))
4465
            .collect::<Vec<_>>(),
4466
        vec![("libs/lib", ChangeStatus::Modified)]
4467
    );
4468
    let a2 = app.commit("bump lib", &[]).unwrap();
4469
    // Checking out the older app state brings the nested working copy back
4470
    // to the older pin, but never moves its bookmark backwards (oxygen#38).
4471
    let r = app.checkout(&[a1], false, "checkout").unwrap();
4472
    assert!(
4473
        r.notes.len() == 1 && r.notes[0].contains("keeps 1 newer change"),
4474
        "{:?}",
4475
        r.notes
4476
    );
4477
    assert_eq!(fs::read(app_dir.join("libs/lib/lib.txt")).unwrap(), b"v1\n");
4478
    let nested = Repo::open(&app_dir.join("libs/lib")).unwrap();
4479
    assert_eq!(nested.bookmark_heads().unwrap(), vec![l2]);
4480
    assert_eq!(nested.working_copy().unwrap().1.deps, vec![l1]);
4481
    assert!(!app.snapshot("status").unwrap().changed);
4482
    // A dirty nested repository is left alone and reported.
4483
    write(&app_dir.join("libs/lib"), "scratch.txt", b"wip\n");
4484
    let r = app.checkout(&[a2], false, "checkout").unwrap();
4485
    assert!(
4486
        r.notes.iter().any(|n| n.contains("uncommitted")),
4487
        "{:?}",
4488
        r.notes
4489
    );
4490
    assert_eq!(fs::read(app_dir.join("libs/lib/lib.txt")).unwrap(), b"v1\n");
4491
    fs::remove_file(app_dir.join("libs/lib/scratch.txt")).unwrap();
4492
    let r = app.submodule_update(false, &[]).unwrap();
4493
    assert_eq!(r, vec![("libs/lib".to_string(), SubrepoSync::Updated)]);
4494
    assert_eq!(fs::read(app_dir.join("libs/lib/lib.txt")).unwrap(), b"v2\n");
4495
    let _ = l2;
4496
4497
    // A fresh clone of the app has the pin but no nested repository until update --init.
4498
    assert!(app.push("origin", false).unwrap()[0].ok);
4499
    let clone_dir = root.join("app-clone");
4500
    let clone = Repo::clone(&app_url, &clone_dir)
4501
        .unwrap()
4502
        .with_home(root.join("home"));
4503
    assert!(!clone_dir.join("libs/lib/.oxy").exists());
4504
    assert_eq!(
4505
        clone.submodule_update(false, &[]).unwrap(),
4506
        vec![("libs/lib".to_string(), SubrepoSync::Missing)]
4507
    );
4508
    assert_eq!(
4509
        clone.submodule_update(true, &[]).unwrap(),
4510
        vec![("libs/lib".to_string(), SubrepoSync::Updated)]
4511
    );
4512
    assert_eq!(
4513
        fs::read(clone_dir.join("libs/lib/lib.txt")).unwrap(),
4514
        b"v2\n"
4515
    );
4516
    assert!(!clone.snapshot("status").unwrap().changed);
4517
    // Removing the subrepo leaves the directory and drops the node.
4518
    clone.submodule_remove("libs/lib").unwrap();
4519
    let snap = clone.snapshot("status").unwrap();
4520
    assert!(
4521
        snap.statuses
4522
            .iter()
4523
            .any(|s| s.path == "libs/lib" && s.status == ChangeStatus::Removed),
4524
        "{:?}",
4525
        snap.statuses
4526
    );
4527
    let c = clone.commit("drop lib", &[]).unwrap();
4528
    assert!(!clone
4529
        .load_state(&[c])
4530
        .unwrap()
4531
        .materialize()
4532
        .files
4533
        .contains_key("libs/lib"));
4534
    assert!(clone_dir.join("libs/lib/lib.txt").exists());
4535
    assert!(
4536
        !clone.snapshot("status").unwrap().changed,
4537
        "an unregistered nested repository is ignored"
4538
    );
4539
}
4540
4541
#[test]
4542
fn git_submodules_import_and_export_as_gitlinks() {
4543
    hermetic();
4544
    if std::process::Command::new("git")
4545
        .arg("--version")
4546
        .output()
4547
        .is_err()
4548
    {
4549
        eprintln!("git not installed; skipping");
4550
        return;
4551
    }
4552
    let dir = tempfile::tempdir().unwrap();
4553
    let root = dir.path();
4554
    let git_in = |d: &Path, args: &[&str]| -> String {
4555
        let out = std::process::Command::new("git")
4556
            .arg("-C")
4557
            .arg(d)
4558
            .args([
4559
                "-c",
4560
                "user.name=Grace",
4561
                "-c",
4562
                "[email protected]",
4563
                "-c",
4564
                "commit.gpgsign=false",
4565
                "-c",
4566
                "protocol.file.allow=always",
4567
            ])
4568
            .args(args)
4569
            .output()
4570
            .unwrap();
4571
        assert!(
4572
            out.status.success(),
4573
            "git {args:?}: {}",
4574
            String::from_utf8_lossy(&out.stderr)
4575
        );
4576
        String::from_utf8_lossy(&out.stdout).trim().to_string()
4577
    };
4578
    let sub = root.join("sub");
4579
    fs::create_dir_all(&sub).unwrap();
4580
    git_in(&sub, &["init", "-q", "-b", "main"]);
4581
    write(&sub, "s.txt", b"sub\n");
4582
    git_in(&sub, &["add", "."]);
4583
    git_in(&sub, &["commit", "-q", "-m", "sub initial"]);
4584
    let sub_sha = git_in(&sub, &["rev-parse", "HEAD"]);
4585
    let g = root.join("main.git");
4586
    fs::create_dir_all(&g).unwrap();
4587
    git_in(&g, &["init", "-q", "-b", "main"]);
4588
    write(&g, "README.md", b"# app\n");
4589
    git_in(&g, &["add", "."]);
4590
    git_in(&g, &["commit", "-q", "-m", "initial"]);
4591
    git_in(
4592
        &g,
4593
        &[
4594
            "submodule",
4595
            "add",
4596
            "-q",
4597
            sub.to_str().unwrap(),
4598
            "vendor/sub",
4599
        ],
4600
    );
4601
    git_in(&g, &["commit", "-q", "-m", "add submodule"]);
4602
4603
    let dest = root.join("oxy");
4604
    let repo = Repo::init(&dest).unwrap().with_home(root.join("home"));
4605
    let rep = repo.import_git(&g, "main").unwrap();
4606
    assert_eq!((rep.commits, rep.submodules), (2, 1));
4607
    let files = repo
4608
        .load_state(&repo.bookmark_heads().unwrap())
4609
        .unwrap()
4610
        .materialize()
4611
        .files;
4612
    assert_eq!(files["vendor/sub"].kind, NodeKind::Subrepo);
4613
    let FileContent::Opaque { blobs } = &files["vendor/sub"].content else {
4614
        panic!()
4615
    };
4616
    assert_eq!(
4617
        crate::subrepo::Pin::decode(&repo.read_blob(&blobs[0]).unwrap()).unwrap(),
4618
        crate::subrepo::Pin::Git {
4619
            sha: sub_sha.clone(),
4620
            branch: "HEAD".into()
4621
        }
4622
    );
4623
    let modules =
4624
        crate::subrepo::Modules::parse(&fs::read_to_string(dest.join(".oxymodules")).unwrap());
4625
    assert_eq!(modules.entries["vendor/sub"].url, sub.to_string_lossy());
4626
    assert!(modules.entries["vendor/sub"].git);
4627
    assert!(
4628
        files.contains_key(".gitmodules"),
4629
        "the Git file is kept for round trips"
4630
    );
4631
    assert!(
4632
        !dest.join("vendor/sub/.git").exists(),
4633
        "not cloned until update --init"
4634
    );
4635
    assert!(!repo.snapshot("status").unwrap().changed);
4636
    // update --init clones it at the pinned commit; status is unchanged.
4637
    assert_eq!(
4638
        repo.submodule_update(true, &[]).unwrap(),
4639
        vec![("vendor/sub".to_string(), SubrepoSync::Updated)]
4640
    );
4641
    assert_eq!(
4642
        git_in(&dest.join("vendor/sub"), &["rev-parse", "HEAD"]),
4643
        sub_sha
4644
    );
4645
    assert!(!repo.snapshot("status").unwrap().changed);
4646
    // Export writes the gitlink and .gitmodules back.
4647
    let mirror = root.join("mirror.git");
4648
    let rep = repo.git_export(&mirror).unwrap();
4649
    assert_eq!(rep.skipped_subrepos, 0);
4650
    let ls = git_in(&mirror, &["ls-tree", "main", "vendor/sub"]);
4651
    assert!(
4652
        ls.starts_with("160000 commit ") && ls.contains(&sub_sha),
4653
        "{ls}"
4654
    );
4655
    assert_eq!(
4656
        git_in(&mirror, &["ls-tree", "--name-only", "main"]),
4657
        ".gitmodules\nREADME.md\nvendor"
4658
    );
4659
    let orig_tree = git_in(&g, &["rev-parse", "main^{tree}"]);
4660
    assert_eq!(
4661
        git_in(&mirror, &["rev-parse", "main^{tree}"]),
4662
        orig_tree,
4663
        "tree round trip"
4664
    );
4665
}
4666
4667
#[test]
4668
fn partial_commits_by_path_and_by_hunk() {
4669
    hermetic();
4670
    let dir = tempfile::tempdir().unwrap();
4671
    let root = dir.path();
4672
    let repo = Repo::init(root).unwrap().with_home(root.join("home"));
4673
    write(root, "a.txt", b"1\n2\n3\n");
4674
    write(root, "b.txt", b"b\n");
4675
    let h0 = repo.commit("base", &[]).unwrap();
4676
    write(root, "a.txt", b"0\n1\n2\n3\n4\n");
4677
    write(root, "b.txt", b"b\nbb\n");
4678
    write(root, "c.txt", b"c\n");
4679
    // By path: only a.txt goes in; the rest stays on disk as uncommitted work.
4680
    let h1 = repo
4681
        .commit_selection("a only", &[], &Selection::Paths(vec!["a.txt".into()]))
4682
        .unwrap();
4683
    let c1 = repo.store().get_change(&h1).unwrap();
4684
    assert!(
4685
        c1.tree_ops.is_empty() && c1.edits.iter().all(|e| e.node() == c1.edits[0].node()),
4686
        "{:?}",
4687
        c1.tree_ops
4688
    );
4689
    assert_eq!(c1.deps, vec![h0]);
4690
    let files = repo.load_state(&[h1]).unwrap().materialize().files;
4691
    assert!(
4692
        matches!(&files["a.txt"].content, FileContent::Text { bytes, .. } if bytes == b"0\n1\n2\n3\n4\n")
4693
    );
4694
    assert!(matches!(&files["b.txt"].content, FileContent::Text { bytes, .. } if bytes == b"b\n"));
4695
    assert!(!files.contains_key("c.txt"));
4696
    let snap = repo.snapshot("status").unwrap();
4697
    assert_eq!(
4698
        snap.statuses
4699
            .iter()
4700
            .map(|s| (s.path.as_str(), s.status))
4701
            .collect::<Vec<_>>(),
4702
        vec![
4703
            ("b.txt", ChangeStatus::Modified),
4704
            ("c.txt", ChangeStatus::Added)
4705
        ]
4706
    );
4707
    assert_eq!(
4708
        fs::read(root.join("b.txt")).unwrap(),
4709
        b"b\nbb\n",
4710
        "disk untouched"
4711
    );
4712
    // By hunk: pick the b.txt insert; c.txt's addition is left.
4713
    let (_, hunks) = repo.hunks().unwrap();
4714
    let b_hunk = hunks
4715
        .iter()
4716
        .find(|h| h.path == "b.txt" && h.text.contains("+bb"))
4717
        .unwrap()
4718
        .index;
4719
    let h2 = repo
4720
        .commit_selection("b only", &[], &Selection::Hunks(vec![b_hunk]))
4721
        .unwrap();
4722
    let files = repo.load_state(&[h2]).unwrap().materialize().files;
4723
    assert!(
4724
        matches!(&files["b.txt"].content, FileContent::Text { bytes, .. } if bytes == b"b\nbb\n")
4725
    );
4726
    assert!(!files.contains_key("c.txt"));
4727
    let snap = repo.snapshot("status").unwrap();
4728
    assert_eq!(
4729
        snap.statuses
4730
            .iter()
4731
            .map(|s| s.path.as_str())
4732
            .collect::<Vec<_>>(),
4733
        vec!["c.txt"]
4734
    );
4735
    // Choosing only the content hunk of a file in a new directory pulls in
4736
    // the directory and file additions it needs.
4737
    write(root, "d/e.txt", b"e\n");
4738
    let (_, hunks) = repo.hunks().unwrap();
4739
    let e_insert = hunks
4740
        .iter()
4741
        .find(|h| h.path == "d/e.txt" && h.text.contains("+e"))
4742
        .unwrap()
4743
        .index;
4744
    let h3 = repo
4745
        .commit_selection("e only", &[], &Selection::Hunks(vec![e_insert]))
4746
        .unwrap();
4747
    let c3 = repo.store().get_change(&h3).unwrap();
4748
    assert_eq!(c3.tree_ops.len(), 2, "{:?}", c3.tree_ops);
4749
    let files = repo.load_state(&[h3]).unwrap().materialize().files;
4750
    assert!(files.contains_key("d/e.txt") && !files.contains_key("c.txt"));
4751
    // Choosing a new file's addition hunk brings its content along.
4752
    write(root, "f/g.txt", b"g\n");
4753
    let (_, hunks) = repo.hunks().unwrap();
4754
    let g_add = hunks
4755
        .iter()
4756
        .find(|h| h.path == "f/g.txt" && h.text.starts_with("A "))
4757
        .unwrap()
4758
        .index;
4759
    let h4 = repo
4760
        .commit_selection("g by addition", &[], &Selection::Hunks(vec![g_add]))
4761
        .unwrap();
4762
    let files = repo.load_state(&[h4]).unwrap().materialize().files;
4763
    assert!(
4764
        matches!(&files["f/g.txt"].content, FileContent::Text { bytes, .. } if bytes == b"g\n")
4765
    );
4766
    assert!(!repo
4767
        .snapshot("status")
4768
        .unwrap()
4769
        .statuses
4770
        .iter()
4771
        .any(|s| s.path == "f/g.txt"));
4772
    // Everything left commits normally; the working copy is then clean.
4773
    repo.commit("the rest", &[]).unwrap();
4774
    assert!(!repo.snapshot("status").unwrap().changed);
4775
    let files = repo
4776
        .load_state(&repo.bookmark_heads().unwrap())
4777
        .unwrap()
4778
        .materialize()
4779
        .files;
4780
    assert!(files.contains_key("c.txt"));
4781
}
4782
4783
#[test]
4784
fn blame_attributes_lines_to_introducing_changes_across_renames() {
4785
    hermetic();
4786
    let dir = tempfile::tempdir().unwrap();
4787
    let root = dir.path();
4788
    let mut repo = Repo::init(root).unwrap().with_home(root.join("home"));
4789
    repo.create_identity("Ada", "[email protected]", IdentityScope::User)
4790
        .unwrap();
4791
    write(root, "a.txt", b"one\n");
4792
    let h1 = repo.commit("first", &[]).unwrap();
4793
    write(root, "a.txt", b"one\ntwo\n");
4794
    let h2 = repo.commit("second", &[]).unwrap();
4795
    let b = repo.blame("a.txt").unwrap();
4796
    assert_eq!(
4797
        b.iter()
4798
            .map(|l| (l.line, l.hash, l.text.as_slice()))
4799
            .collect::<Vec<_>>(),
4800
        vec![(1, h1, b"one\n".as_slice()), (2, h2, b"two\n".as_slice())]
4801
    );
4802
    assert!(b.iter().all(|l| l.author == "Ada"));
4803
    assert_eq!(
4804
        b[0].change_id,
4805
        repo.store().get_change(&h1).unwrap().change_id
4806
    );
4807
    fs::rename(root.join("a.txt"), root.join("b.txt")).unwrap();
4808
    repo.commit("rename", &[]).unwrap();
4809
    let b = repo.blame("b.txt").unwrap();
4810
    assert_eq!(
4811
        b.iter().map(|l| l.hash).collect::<Vec<_>>(),
4812
        vec![h1, h2],
4813
        "the node survives the rename"
4814
    );
4815
    assert!(repo.blame("a.txt").is_err());
4816
}
4817
4818
#[test]
4819
fn bisect_finds_the_first_bad_change() {
4820
    hermetic();
4821
    let dir = tempfile::tempdir().unwrap();
4822
    let root = dir.path();
4823
    let repo = Repo::init(root).unwrap().with_home(root.join("home"));
4824
    let mut content = String::new();
4825
    let mut hashes = Vec::new();
4826
    for i in 1..=8 {
4827
        content.push_str(&format!("line {i}{}\n", if i == 5 { " bug" } else { "" }));
4828
        write(root, "f.txt", content.as_bytes());
4829
        hashes.push(repo.commit(&format!("step {i}"), &[]).unwrap());
4830
    }
4831
    // Each step appends after the previous line, so the chain is linear.
4832
    assert_eq!(repo.bookmark_heads().unwrap(), vec![hashes[7]]);
4833
    repo.bisect_start().unwrap();
4834
    assert!(matches!(
4835
        repo.bisect_mark(Some(true), &[hashes[0]]).unwrap(),
4836
        BisectStep::NeedMarks { good: 1, bad: 0 }
4837
    ));
4838
    let step = repo.bisect_mark(Some(false), &[hashes[7]]).unwrap();
4839
    assert!(
4840
        matches!(step, BisectStep::Testing { remaining: 7, .. }),
4841
        "{step:?}"
4842
    );
4843
    // Automated: bad when the bug line is present.
4844
    let step = repo
4845
        .bisect_run(&["sh".into(), "-c".into(), "! grep -q bug f.txt".into()])
4846
        .unwrap();
4847
    assert_eq!(step, BisectStep::Found { culprit: hashes[4] });
4848
    assert_eq!(
4849
        repo.bisect_status().unwrap(),
4850
        Some(BisectStep::Found { culprit: hashes[4] })
4851
    );
4852
    repo.bisect_reset().unwrap();
4853
    assert_eq!(fs::read_to_string(root.join("f.txt")).unwrap(), content);
4854
    assert!(repo.bisect_status().unwrap().is_none());
4855
    assert!(!repo.snapshot("status").unwrap().changed);
4856
    // Manual marks and a skip.
4857
    repo.bisect_start().unwrap();
4858
    repo.bisect_mark(Some(true), &[hashes[0]]).unwrap();
4859
    let mut step = repo.bisect_mark(Some(false), &[hashes[7]]).unwrap();
4860
    let mut skipped_once = false;
4861
    let mut guard = 0;
4862
    while let BisectStep::Testing { .. } = step {
4863
        guard += 1;
4864
        assert!(guard < 20);
4865
        let text = fs::read_to_string(root.join("f.txt")).unwrap();
4866
        if !skipped_once && text.contains("line 6") {
4867
            // An untestable state away from the boundary: the search routes around it.
4868
            skipped_once = true;
4869
            step = repo.bisect_mark(None, &[]).unwrap();
4870
            continue;
4871
        }
4872
        step = repo.bisect_mark(Some(!text.contains("bug")), &[]).unwrap();
4873
    }
4874
    assert!(skipped_once);
4875
    assert_eq!(step, BisectStep::Found { culprit: hashes[4] });
4876
    repo.bisect_reset().unwrap();
4877
    // Skipping the culprit itself leaves it among the candidates reported.
4878
    repo.bisect_start().unwrap();
4879
    repo.bisect_mark(Some(true), &[hashes[0]]).unwrap();
4880
    let mut step = repo.bisect_mark(Some(false), &[hashes[7]]).unwrap();
4881
    let mut guard = 0;
4882
    while let BisectStep::Testing { heads, .. } = &step {
4883
        guard += 1;
4884
        assert!(guard < 20);
4885
        let text = fs::read_to_string(root.join("f.txt")).unwrap();
4886
        let is_culprit_state =
4887
            heads.contains(&hashes[4]) && !heads.iter().any(|h| hashes[5..].contains(h));
4888
        step = if is_culprit_state {
4889
            repo.bisect_mark(None, &[]).unwrap()
4890
        } else {
4891
            repo.bisect_mark(Some(!text.contains("bug")), &[]).unwrap()
4892
        };
4893
    }
4894
    match step {
4895
        BisectStep::Inconclusive { candidates } => assert!(
4896
            candidates.contains(&hashes[4]) && candidates.len() <= 2,
4897
            "{candidates:?}"
4898
        ),
4899
        other => panic!("{other:?}"),
4900
    }
4901
    repo.bisect_reset().unwrap();
4902
}
4903
4904
#[test]
4905
fn squash_folds_a_change_into_its_dependency() {
4906
    hermetic();
4907
    let dir = tempfile::tempdir().unwrap();
4908
    let root = dir.path();
4909
    let repo = Repo::init(root).unwrap().with_home(root.join("home"));
4910
    write(root, "a.txt", b"1\n");
4911
    let a = repo.commit("A", &[]).unwrap();
4912
    write(root, "a.txt", b"1\n2\n");
4913
    let c = repo.commit("C", &[]).unwrap();
4914
    write(root, "a.txt", b"1\n2\n3\n");
4915
    let e = repo.commit("E", &[]).unwrap();
4916
    write(root, "b.txt", b"b\n");
4917
    let b = repo.commit("B", &[]).unwrap();
4918
    let id_a = repo.store().get_change(&a).unwrap().change_id;
4919
    let id_e = repo.store().get_change(&e).unwrap().change_id;
4920
    // E depends on C which A lacks: refused, naming it.
4921
    let err = repo.squash(&e, &a).unwrap_err().to_string();
4922
    assert!(err.contains(&c.short(12)), "{err}");
4923
    // C into A: A' has both, C is gone, E follows and still reads the same.
4924
    let a2 = repo.squash(&c, &a).unwrap();
4925
    let a2c = repo.store().get_change(&a2).unwrap();
4926
    assert_eq!(a2c.change_id, id_a);
4927
    assert!(a2c.deps.is_empty());
4928
    let heads = repo.bookmark_heads().unwrap();
4929
    let st = repo.load_state(&heads).unwrap();
4930
    assert!(!st.contains(&c) && !st.contains(&a) && !st.contains(&e));
4931
    let e2 = st
4932
        .changes()
4933
        .find(|(_, m)| m.change_id == id_e)
4934
        .map(|(h, _)| *h)
4935
        .unwrap();
4936
    assert_eq!(
4937
        repo.store().get_change(&e2).unwrap().deps,
4938
        vec![a2],
4939
        "E now depends on A' alone"
4940
    );
4941
    let files = st.materialize().files;
4942
    assert!(
4943
        matches!(&files["a.txt"].content, FileContent::Text { bytes, .. } if bytes == b"1\n2\n3\n")
4944
    );
4945
    assert!(files.contains_key("b.txt"));
4946
    assert!(st.contains(&b));
4947
    assert!(!repo.snapshot("status").unwrap().changed);
4948
    assert_eq!(repo.log().unwrap().len(), 4, "working copy, B, E', A'");
4949
    // Undo restores the three original changes.
4950
    repo.undo().unwrap();
4951
    repo.undo().unwrap();
4952
    let st = repo.load_state(&repo.bookmark_heads().unwrap()).unwrap();
4953
    assert!(st.contains(&c) && st.contains(&a) && st.contains(&e));
4954
}
4955
4956
#[test]
4957
fn rebase_re_expresses_a_change_against_another_base() {
4958
    hermetic();
4959
    let dir = tempfile::tempdir().unwrap();
4960
    let root = dir.path();
4961
    let repo = Repo::init(root).unwrap().with_home(root.join("home"));
4962
    write(root, "a.txt", b"1\n2\n");
4963
    let a = repo.commit("A", &[]).unwrap();
4964
    write(root, "a.txt", b"1\n2\n3\n");
4965
    let c = repo.commit("C: append 3", &[]).unwrap();
4966
    write(root, "a.txt", b"1\n2\n3\n4\n");
4967
    let e = repo.commit("E: append 4", &[]).unwrap();
4968
    // A different base: A plus a change that prepends a line.
4969
    repo.checkout(&[a], true, "checkout").unwrap();
4970
    write(root, "a.txt", b"0\n1\n2\n");
4971
    let d = repo.commit("D: prepend 0", &[]).unwrap();
4972
    let id_c = repo.store().get_change(&c).unwrap().change_id;
4973
    let id_e = repo.store().get_change(&e).unwrap().change_id;
4974
    // Rebase C onto D: its effect (append 3) re-derived against D's text.
4975
    let c2 = repo.rebase(&c, &[d]).unwrap();
4976
    let c2c = repo.store().get_change(&c2).unwrap();
4977
    assert_eq!(c2c.change_id, id_c);
4978
    assert!(c2c.deps.contains(&d), "{:?}", c2c.deps);
4979
    let heads = repo.bookmark_heads().unwrap();
4980
    let st = repo.load_state(&heads).unwrap();
4981
    assert!(!st.contains(&c) && st.contains(&d));
4982
    let e2 = st
4983
        .changes()
4984
        .find(|(_, m)| m.change_id == id_e)
4985
        .map(|(h, _)| *h)
4986
        .unwrap();
4987
    let e2deps = repo.store().get_change(&e2).unwrap().deps;
4988
    assert!(
4989
        e2deps.contains(&c2) && !e2deps.contains(&c) && e2deps.contains(&a),
4990
        "E follows C by content and still depends on A, which introduced the file: {e2deps:?}"
4991
    );
4992
    let files = st.materialize().files;
4993
    assert!(
4994
        matches!(&files["a.txt"].content, FileContent::Text { bytes, .. } if bytes == b"0\n1\n2\n3\n4\n"),
4995
        "{:?}",
4996
        files["a.txt"].content
4997
    );
4998
    assert!(!files["a.txt"].is_conflicted());
4999
    // Rebasing onto a state that already contains the change is refused.
5000
    assert!(repo.rebase(&c2, &[c2]).is_err());
5001
    let err = repo.rebase(&e2, &[d]).unwrap_err().to_string();
5002
    assert!(
5003
        err.contains("lacks dependencies"),
5004
        "E needs C, which D's state does not have: {err}"
5005
    );
5006
}
5007
5008
#[test]
5009
fn unsigned_tags_keep_their_message() {
5010
    hermetic();
5011
    let dir = tempfile::tempdir().unwrap();
5012
    let root = dir.path();
5013
    let repo = Repo::init(root).unwrap().with_home(root.join("home"));
5014
    write(root, "a.txt", b"a\n");
5015
    repo.commit("a", &[]).unwrap();
5016
    assert!(repo.secret_key().unwrap().is_none());
5017
    repo.tag_create("v1", &repo.bookmark_heads().unwrap(), "first release")
5018
        .unwrap();
5019
    let tags = repo.tags().unwrap();
5020
    assert_eq!(
5021
        (
5022
            tags[0].name.as_str(),
5023
            tags[0].message.as_str(),
5024
            tags[0].signer.as_deref()
5025
        ),
5026
        ("v1", "first release", None)
5027
    );
5028
    assert!(
5029
        repo.tag_refs().unwrap()[0].attestation.is_none(),
5030
        "an unsigned attestation is not advertised"
5031
    );
5032
}
5033
5034
#[test]
5035
fn fsck_passes_a_sound_repository_and_names_each_fault() {
5036
    // Files on disk are what this tests: tampering with them, and the
5037
    // directory store's crash points.
5038
    if std::env::var_os("OXY_STORE_BACKEND").is_some() {
5039
        return;
5040
    }
5041
    hermetic();
5042
    let dir = tempfile::tempdir().unwrap();
5043
    let root = dir.path();
5044
    let origin_path = root.join("origin");
5045
    let origin = Repo::init(&origin_path).unwrap();
5046
    let mut a = Repo::clone(&origin_path.to_string_lossy(), &root.join("a"))
5047
        .unwrap()
5048
        .with_home(root.join("home-a"));
5049
    a.create_identity("Ada", "[email protected]", IdentityScope::Repo)
5050
        .unwrap();
5051
    write(&root.join("a"), "f.txt", b"one\n");
5052
    write(&root.join("a"), "bin.dat", b"\0\x01\x02binary");
5053
    let h1 = a.commit("first", &[]).unwrap();
5054
    write(&root.join("a"), "f.txt", b"one\ntwo\n");
5055
    let h2 = a.commit("second", &[]).unwrap();
5056
    a.tag_create("v1", &[h2], "first release").unwrap();
5057
    a.checkpoint().unwrap();
5058
    assert!(a.push("origin", false).unwrap()[0].ok);
5059
    origin.refresh().unwrap();
5060
5061
    // Sound: signed changes, a seal, a tag, a checkpoint, a ref attestation.
5062
    for repo in [&a, &origin] {
5063
        let rep = repo.fsck().unwrap();
5064
        assert_eq!(rep.problems, vec![], "{rep:?}");
5065
        // The two commits, plus the working copy's change in `a`.
5066
        assert!(rep.changes >= 2 && rep.signed >= 2, "{rep:?}");
5067
        assert!(rep.ops > 1 && rep.objects > 5);
5068
    }
5069
    assert!(origin.fsck().unwrap().attestations >= 1);
5070
5071
    // A flipped byte in a stored object is corruption, named by hash.
5072
    let c1 = a.store().path_for(&h1);
5073
    let pristine = fs::read(&c1).unwrap();
5074
    let mut bytes = pristine.clone();
5075
    *bytes.last_mut().unwrap() ^= 1;
5076
    fs::write(&c1, &bytes).unwrap();
5077
    let rep = a.fsck().unwrap();
5078
    assert!(rep.errors() >= 1);
5079
    assert!(
5080
        rep.problems
5081
            .iter()
5082
            .any(|p| p.object == Some(h1) && p.what.contains("unreadable")),
5083
        "{rep:?}"
5084
    );
5085
    fs::write(&c1, &pristine).unwrap();
5086
    assert_eq!(a.fsck().unwrap().errors(), 0);
5087
5088
    // A missing change is named with what needed it.
5089
    fs::remove_file(&c1).unwrap();
5090
    let rep = a.fsck().unwrap();
5091
    assert!(
5092
        rep.problems.iter().any(|p| p.severity == Severity::Error
5093
            && p.object == Some(h1)
5094
            && p.what.contains("change missing, needed by change")),
5095
        "{rep:?}"
5096
    );
5097
    fs::write(&c1, &pristine).unwrap();
5098
5099
    // A missing blob is an error in a full clone.
5100
    let c2 = a.store().get_change(&h1).unwrap();
5101
    let blob = c2
5102
        .edits
5103
        .iter()
5104
        .find_map(|e| match e {
5105
            Edit::Replace { new: Some(b), .. } => Some(*b),
5106
            _ => None,
5107
        })
5108
        .expect("the binary file is a blob");
5109
    let bp = a.store().path_for(&blob);
5110
    let blob_bytes = fs::read(&bp).unwrap();
5111
    fs::remove_file(&bp).unwrap();
5112
    let rep = a.fsck().unwrap();
5113
    assert!(
5114
        rep.problems
5115
            .iter()
5116
            .any(|p| p.object == Some(blob) && p.what.contains("blob missing")),
5117
        "{rep:?}"
5118
    );
5119
    fs::write(&bp, &blob_bytes).unwrap();
5120
5121
    // A broken op log head is reported, not a crash.
5122
    let head = root.join("a/.oxy/ops/head");
5123
    let saved = fs::read(&head).unwrap();
5124
    fs::write(&head, b"not a hash").unwrap();
5125
    let rep = a.fsck().unwrap();
5126
    assert!(
5127
        rep.problems.iter().any(|p| p.what.contains("ops/head")),
5128
        "{rep:?}"
5129
    );
5130
    fs::write(&head, saved).unwrap();
5131
    assert_eq!(a.fsck().unwrap().problems, vec![]);
5132
}
5133
5134
/// Copy a directory tree (for restoring a pristine repository).
5135
fn copy_tree(from: &Path, to: &Path) {
5136
    fs::create_dir_all(to).unwrap();
5137
    for e in fs::read_dir(from).unwrap() {
5138
        let e = e.unwrap();
5139
        let target = to.join(e.file_name());
5140
        if e.file_type().unwrap().is_dir() {
5141
            copy_tree(&e.path(), &target);
5142
        } else {
5143
            fs::copy(e.path(), &target).unwrap();
5144
        }
5145
    }
5146
}
5147
5148
/// Spec §13.6: stop `commit` and `push` at every durable step, as a crash
5149
/// would, and check that both repositories still open, pass `fsck`, and
5150
/// accept the same operation again.
5151
#[test]
5152
fn crash_at_every_step_of_commit_and_push_leaves_sound_repositories() {
5153
    // Files on disk are what this tests: tampering with them, and the
5154
    // directory store's crash points.
5155
    if std::env::var_os("OXY_STORE_BACKEND").is_some() {
5156
        return;
5157
    }
5158
    use crate::durable::failpoint;
5159
    hermetic();
5160
    let dir = tempfile::tempdir().unwrap();
5161
    let pristine = dir.path().join("pristine");
5162
    let origin_path = pristine.join("origin");
5163
    Repo::init(&origin_path).unwrap();
5164
    let mut a = Repo::clone(&origin_path.to_string_lossy(), &pristine.join("a"))
5165
        .unwrap()
5166
        .with_home(dir.path().join("home"));
5167
    a.create_identity("Ada", "[email protected]", IdentityScope::Repo)
5168
        .unwrap();
5169
    write(&pristine.join("a"), "f.txt", b"one\n");
5170
    a.commit("first", &[]).unwrap();
5171
    assert!(a.push("origin", false).unwrap()[0].ok);
5172
    drop(a);
5173
5174
    type Op = fn(&Repo) -> Result<()>;
5175
    let edit_and_commit: Op = |r| {
5176
        write(r.root(), "f.txt", b"one\ntwo\n");
5177
        write(r.root(), "big.bin", &vec![7u8; 300_000]);
5178
        r.commit("second", &[]).map(|_| ())
5179
    };
5180
    let push: Op = |r| {
5181
        let res = r.push("origin", false)?;
5182
        if res.iter().all(|x| x.ok) {
5183
            Ok(())
5184
        } else {
5185
            Err(RepoError::Msg(format!("{res:?}")))
5186
        }
5187
    };
5188
5189
    for (name, prepare, op) in [
5190
        ("commit", None, edit_and_commit),
5191
        ("push", Some(edit_and_commit), push),
5192
    ] {
5193
        let mut steps = 0;
5194
        for n in 1.. {
5195
            let run = dir.path().join(format!("{name}-{n}"));
5196
            copy_tree(&pristine, &run);
5197
            // Clones record their remote by path; point it at this copy.
5198
            let open = |p: &Path| {
5199
                let mut r = Repo::open(p).unwrap().with_home(dir.path().join("home"));
5200
                r.config
5201
                    .set("remote.origin.url", &run.join("origin").to_string_lossy())
5202
                    .unwrap();
5203
                r.save_config().unwrap();
5204
                r
5205
            };
5206
            let a = open(&run.join("a"));
5207
            if let Some(prep) = prepare {
5208
                prep(&a).unwrap();
5209
            }
5210
            failpoint::crash_after(n);
5211
            let outcome = op(&a);
5212
            let crashed = failpoint::disarm();
5213
            drop(a);
5214
            if !crashed {
5215
                outcome.unwrap_or_else(|e| panic!("{name} failed without a crash: {e}"));
5216
                steps = n - 1;
5217
                break;
5218
            }
5219
            assert!(
5220
                outcome.is_err(),
5221
                "{name}: a crash at step {n} was swallowed"
5222
            );
5223
            for repo in ["a", "origin"] {
5224
                let r = Repo::open(&run.join(repo)).unwrap_or_else(|e| {
5225
                    panic!("{name} crash at step {n}: {repo} no longer opens: {e}")
5226
                });
5227
                let rep = r.fsck().unwrap();
5228
                assert_eq!(
5229
                    rep.errors(),
5230
                    0,
5231
                    "{name} crash at step {n}: {repo} fails fsck: {:?}",
5232
                    rep.problems
5233
                );
5234
            }
5235
            // The interrupted operation can simply be run again.
5236
            let a = open(&run.join("a"));
5237
            // A crash after the commit point leaves the commit done.
5238
            let landed = a
5239
                .bookmark_heads()
5240
                .unwrap()
5241
                .iter()
5242
                .any(|h| a.store().get_change(h).unwrap().message == "second");
5243
            let again = match (name, landed) {
5244
                ("commit", true) => Ok(()),
5245
                ("commit", false) => a.commit("second", &[]).map(|_| ()),
5246
                _ => op(&a),
5247
            };
5248
            again.unwrap_or_else(|e| panic!("{name} crash at step {n}: retry failed: {e}"));
5249
            assert_eq!(a.fsck().unwrap().errors(), 0);
5250
            fs::remove_dir_all(&run).unwrap();
5251
        }
5252
        assert!(steps >= 3, "{name} has only {steps} durable steps?");
5253
    }
5254
}
5255
5256
/// Spec §12.1: commands in two workspaces of one repository, and pushes,
5257
/// running at the same time lose nothing: every commit ends up on the
5258
/// bookmark, locally and on the remote, and the repository passes fsck.
5259
#[test]
5260
fn concurrent_commits_in_two_workspaces_lose_nothing() {
5261
    hermetic();
5262
    let dir = tempfile::tempdir().unwrap();
5263
    let root = dir.path();
5264
    let origin = root.join("origin");
5265
    Repo::init_bare_unbound(&origin).unwrap();
5266
    let main = root.join("main");
5267
    let mut repo = Repo::init(&main).unwrap();
5268
    repo.config
5269
        .set("remote.origin.url", &origin.to_string_lossy())
5270
        .unwrap();
5271
    repo.save_config().unwrap();
5272
    write(&main, "seed.txt", b"seed\n");
5273
    repo.commit("seed", &[]).unwrap();
5274
    let second = root.join("second");
5275
    repo.workspace_add(&second, None).unwrap();
5276
    drop(repo);
5277
5278
    const EACH: usize = 15;
5279
    std::thread::scope(|s| {
5280
        for (tag, dir, push) in [("a", main.clone(), true), ("b", second.clone(), false)] {
5281
            s.spawn(move || {
5282
                let r = Repo::open(&dir).unwrap();
5283
                for i in 0..EACH {
5284
                    write(
5285
                        &dir,
5286
                        &format!("{tag}-{i}.txt"),
5287
                        format!("{tag} {i}\n").as_bytes(),
5288
                    );
5289
                    r.commit(&format!("{tag} {i}"), &[]).unwrap();
5290
                    if push && i % 5 == 4 {
5291
                        // A push may be refused while the other workspace moves the bookmark; nothing may be lost either way.
5292
                        let _ = r.push("origin", false);
5293
                    }
5294
                }
5295
            });
5296
        }
5297
    });
5298
5299
    let repo = Repo::open(&main).unwrap();
5300
    let heads = repo.bookmark_heads().unwrap();
5301
    let state = repo.load_state(&heads).unwrap();
5302
    let messages: BTreeSet<String> = state.changes().map(|(_, m)| m.message.clone()).collect();
5303
    for tag in ["a", "b"] {
5304
        for i in 0..EACH {
5305
            assert!(
5306
                messages.contains(&format!("{tag} {i}")),
5307
                "lost commit {tag} {i}; have {messages:?}"
5308
            );
5309
        }
5310
    }
5311
    let rep = repo.fsck().unwrap();
5312
    assert_eq!(rep.errors(), 0, "{:?}", rep.problems);
5313
    assert!(repo.push("origin", false).unwrap().iter().all(|r| r.ok));
5314
    let hosted = Repo::open(&origin).unwrap();
5315
    let hosted_heads = hosted.bookmark_heads().unwrap();
5316
    assert_eq!(
5317
        hosted.load_state(&hosted_heads).unwrap().len(),
5318
        state.len(),
5319
        "the remote has every commit"
5320
    );
5321
}
5322
5323
/// Two operations recorded from the same parent (what two processes do
5324
/// when they race) are merged: both bookmarks' heads survive, and a
5325
/// change made on one side only is kept.
5326
#[test]
5327
fn operations_from_the_same_parent_are_merged() {
5328
    hermetic();
5329
    let dir = tempfile::tempdir().unwrap();
5330
    let root = dir.path();
5331
    let repo = Repo::init(root).unwrap();
5332
    write(root, "a.txt", b"a\n");
5333
    let a = repo.commit("a", &[]).unwrap();
5334
    write(root, "b.txt", b"b\n");
5335
    let b = repo.commit("b", &[]).unwrap();
5336
    let (x, op) = repo.head_op().unwrap();
5337
    let state = |heads: Vec<ChangeHash>| repo.store().put_state(&StateObject::new(heads)).unwrap();
5338
5339
    // Side one moves main to just `a` and adds a bookmark; side two moves main to just `b`.
5340
    let mut one = op.view.clone();
5341
    one.bookmarks.insert("main".into(), state(vec![a]));
5342
    one.bookmarks.insert("topic".into(), state(vec![a]));
5343
    let mut two = op.view.clone();
5344
    two.bookmarks.insert("main".into(), state(vec![b]));
5345
    repo.record_op(&[x], "one", one).unwrap();
5346
    let merged = repo.record_op(&[x], "two", two).unwrap();
5347
5348
    let (head, op) = repo.head_op().unwrap();
5349
    assert_eq!(head, merged);
5350
    assert_eq!(op.parents.len(), 2, "a merge of the two operations");
5351
    assert!(op.command.contains("merged with a concurrent operation"));
5352
    let mut main = repo
5353
        .store()
5354
        .get_state(&op.view.bookmarks["main"])
5355
        .unwrap()
5356
        .heads;
5357
    main.sort();
5358
    let mut want = vec![a, b];
5359
    want.sort();
5360
    assert_eq!(main, want, "both sides' heads are kept");
5361
    assert!(
5362
        op.view.bookmarks.contains_key("topic"),
5363
        "a one-sided change survives"
5364
    );
5365
    assert_eq!(repo.fsck().unwrap().errors(), 0);
5366
}
5367
5368
#[test]
5369
fn failed_requests_come_with_a_next_step() {
5370
    use crate::protocol::hint_for;
5371
    assert!(hint_for("https://h/x/oxy/v1/push: HTTP 401: bad token")
5372
        .unwrap()
5373
        .contains("token"));
5374
    assert!(hint_for("…: HTTP 403: forbidden")
5375
        .unwrap()
5376
        .contains("repo:write"));
5377
    assert!(hint_for("…: HTTP 404: no such repository")
5378
        .unwrap()
5379
        .contains("owner and repository name"));
5380
    assert!(hint_for("invalid peer certificate: UnknownIssuer")
5381
        .unwrap()
5382
        .contains("oxyhub-ca.pem"));
5383
    assert!(hint_for("Connect error: Connection refused (os error 111)")
5384
        .unwrap()
5385
        .contains("running"));
5386
    assert!(hint_for("Dns Failed: failed to lookup address information")
5387
        .unwrap()
5388
        .contains("resolve"));
5389
    assert_eq!(hint_for("something else entirely"), None);
5390
}
5391
5392
#[test]
5393
fn doctor_names_problems_and_what_to_do() {
5394
    hermetic();
5395
    let dir = tempfile::tempdir().unwrap();
5396
    let root = dir.path();
5397
    let origin = root.join("origin");
5398
    Repo::init_bare_unbound(&origin).unwrap();
5399
    let mut repo = Repo::init(&root.join("r"))
5400
        .unwrap()
5401
        .with_home(root.join("home"));
5402
    let find = |r: &DoctorReport, area: &str, h: Health| {
5403
        r.checks
5404
            .iter()
5405
            .find(|c| c.area == area && c.health == h)
5406
            .cloned()
5407
    };
5408
5409
    let r = repo.doctor(true);
5410
    assert!(find(&r, "identity", Health::Warn)
5411
        .unwrap()
5412
        .hint
5413
        .unwrap()
5414
        .contains("oxy identity create"));
5415
    assert!(find(&r, "repository", Health::Ok).is_some());
5416
5417
    repo.create_identity("Ada", "[email protected]", IdentityScope::Repo)
5418
        .unwrap();
5419
    repo.config.set("author.name", "Ada").unwrap();
5420
    repo.config.set("author.email", "[email protected]").unwrap();
5421
    repo.config
5422
        .set("remote.origin.url", &origin.to_string_lossy())
5423
        .unwrap();
5424
    repo.config
5425
        .set("remote.down.url", "http://127.0.0.1:9/a/b")
5426
        .unwrap();
5427
    repo.config.set("remote.down.token", "t").unwrap();
5428
    repo.config
5429
        .set("remote.badca.url", "https://example.invalid/a/b")
5430
        .unwrap();
5431
    repo.config
5432
        .set(
5433
            "remote.badca.ca",
5434
            &root.join("missing.pem").to_string_lossy(),
5435
        )
5436
        .unwrap();
5437
    repo.save_config().unwrap();
5438
5439
    let r = repo.doctor(true);
5440
    assert!(find(&r, "identity", Health::Ok).is_some(), "{r:?}");
5441
    assert!(find(&r, "author", Health::Ok).is_some(), "{r:?}");
5442
    assert!(find(&r, "remote origin", Health::Ok)
5443
        .unwrap()
5444
        .message
5445
        .contains("first push binds it"));
5446
    let down = find(&r, "remote down", Health::Fail).unwrap();
5447
    assert!(
5448
        down.hint.as_deref().unwrap_or("").contains("running"),
5449
        "{down:?}"
5450
    );
5451
    let badca = find(&r, "remote badca", Health::Fail).unwrap();
5452
    assert!(
5453
        badca.hint.unwrap().contains("remote.badca.ca"),
5454
        "the remote's own name is in the hint"
5455
    );
5456
    assert_eq!(r.worst(), Health::Fail);
5457
5458
    // Offline, nothing is contacted.
5459
    let r = repo.doctor(false);
5460
    assert!(find(&r, "remote down", Health::Fail).is_none());
5461
    assert!(find(&r, "remote down", Health::Ok)
5462
        .unwrap()
5463
        .message
5464
        .contains("not contacted"));
5465
}
5466
5467
/// Spec §8.1: deleting a line depends on whoever inserted the lines right
5468
/// after it. Inserting after `b` and then deleting `b`, one commit after
5469
/// the other, must not leave a delete/insert conflict.
5470
#[test]
5471
fn deleting_a_line_after_an_insertion_below_it_is_not_a_conflict() {
5472
    hermetic();
5473
    let dir = tempfile::tempdir().unwrap();
5474
    let root = dir.path();
5475
    let repo = Repo::init(root).unwrap();
5476
    write(root, "f", b"a\nb\nc\n");
5477
    repo.commit("base", &[]).unwrap();
5478
    write(root, "f", b"a\nb\nx\nc\n");
5479
    let insert = repo.commit("insert x after b", &[]).unwrap();
5480
    write(root, "f", b"a\nx\nc\n");
5481
    let delete = repo.commit("delete b", &[]).unwrap();
5482
    assert!(
5483
        repo.store()
5484
            .get_change(&delete)
5485
            .unwrap()
5486
            .deps
5487
            .contains(&insert),
5488
        "the deletion depends on the insertion below the deleted line"
5489
    );
5490
    let heads = repo.bookmark_heads().unwrap();
5491
    assert_eq!(heads, vec![delete]);
5492
    let snap = repo.load_state(&heads).unwrap().materialize();
5493
    assert!(!snap.is_conflicted());
5494
    assert!(
5495
        matches!(&snap.files["f"].content, FileContent::Text { bytes, .. } if bytes == b"a\nx\nc\n")
5496
    );
5497
}
5498
5499
/// Spec §9.3: a binary file reverted to an earlier blob keeps it, and each
5500
/// replacement depends on the change that set the blob it replaces.
5501
#[test]
5502
fn a_binary_file_reverted_to_an_earlier_blob_keeps_it() {
5503
    hermetic();
5504
    let dir = tempfile::tempdir().unwrap();
5505
    let root = dir.path();
5506
    let repo = Repo::init(root).unwrap();
5507
    write(root, "bin", b"\0A");
5508
    let v1 = repo.commit("v1", &[]).unwrap();
5509
    write(root, "bin", b"\0B");
5510
    let v2 = repo.commit("v2", &[]).unwrap();
5511
    assert!(repo.store().get_change(&v2).unwrap().deps.contains(&v1));
5512
    write(root, "bin", b"\0A");
5513
    let v3 = repo.commit("back to A", &[]).unwrap();
5514
    assert!(repo.store().get_change(&v3).unwrap().deps.contains(&v2));
5515
    assert_eq!(repo.bookmark_heads().unwrap(), vec![v3]);
5516
    let state = repo.load_state(&[v3]).unwrap();
5517
    let snap = state.materialize();
5518
    let FileContent::Opaque { blobs } = &snap.files["bin"].content else {
5519
        panic!("opaque")
5520
    };
5521
    assert_eq!(blobs.len(), 1, "one live blob, not none and not two");
5522
    assert_eq!(repo.read_blob(&blobs[0]).unwrap(), b"\0A");
5523
}
5524
5525
/// Spec §23: a binary file changed on two branches and merged in Git to
5526
/// one side's version comes back as that version at the merge, and the
5527
/// import verifies commit by commit.
5528
#[test]
5529
fn git_import_resolves_a_binary_merged_in_git_and_verifies() {
5530
    hermetic();
5531
    if std::process::Command::new("git")
5532
        .arg("--version")
5533
        .output()
5534
        .is_err()
5535
    {
5536
        eprintln!("git not installed; skipping");
5537
        return;
5538
    }
5539
    let dir = tempfile::tempdir().unwrap();
5540
    let root = dir.path();
5541
    let g = root.join("src.git");
5542
    fs::create_dir_all(&g).unwrap();
5543
    let git = |args: &[&str]| -> String {
5544
        let out = std::process::Command::new("git")
5545
            .arg("-C")
5546
            .arg(&g)
5547
            .args([
5548
                "-c",
5549
                "user.name=Grace",
5550
                "-c",
5551
                "[email protected]",
5552
                "-c",
5553
                "commit.gpgsign=false",
5554
            ])
5555
            .args(args)
5556
            .output()
5557
            .unwrap();
5558
        assert!(
5559
            out.status.success(),
5560
            "git {args:?}: {}",
5561
            String::from_utf8_lossy(&out.stderr)
5562
        );
5563
        String::from_utf8_lossy(&out.stdout).trim().to_string()
5564
    };
5565
    git(&["init", "-q", "-b", "main"]);
5566
    write(&g, "logo.bin", b"\0base");
5567
    write(&g, "notes.txt", b"a\nb\nc\n");
5568
    git(&["add", "."]);
5569
    git(&["commit", "-qm", "base"]);
5570
    git(&["checkout", "-qb", "side"]);
5571
    write(&g, "logo.bin", b"\0side");
5572
    write(&g, "notes.txt", b"a\nb\nx\nc\n");
5573
    git(&["commit", "-qam", "side"]);
5574
    git(&["checkout", "-q", "main"]);
5575
    write(&g, "logo.bin", b"\0main");
5576
    git(&["commit", "-qam", "main"]);
5577
    // Git cannot merge the binary; the merge takes main's and keeps side's text.
5578
    let _ = std::process::Command::new("git")
5579
        .arg("-C")
5580
        .arg(&g)
5581
        .args([
5582
            "-c",
5583
            "user.name=G",
5584
            "-c",
5585
            "user.email=g@e",
5586
            "merge",
5587
            "-q",
5588
            "side",
5589
        ])
5590
        .output();
5591
    write(&g, "logo.bin", b"\0main");
5592
    git(&["add", "."]);
5593
    git(&["commit", "-qm", "merge side"]);
5594
    // Then a revert of the binary to its first version.
5595
    write(&g, "logo.bin", b"\0base");
5596
    git(&["commit", "-qam", "back to base"]);
5597
5598
    let repo = Repo::init(&root.join("o")).unwrap();
5599
    let rep = repo.import_git(&g, "main").unwrap();
5600
    assert_eq!(rep.merges, 1);
5601
    let v = repo.verify_git_import(&g, "main").unwrap();
5602
    assert!(v.mismatches.is_empty(), "{:?}", v.mismatches);
5603
    assert_eq!(v.commits, 5);
5604
    let snap = repo
5605
        .load_state(&repo.bookmark_heads().unwrap())
5606
        .unwrap()
5607
        .materialize();
5608
    assert!(!snap.is_conflicted());
5609
    let FileContent::Opaque { blobs } = &snap.files["logo.bin"].content else {
5610
        panic!("opaque")
5611
    };
5612
    assert_eq!(repo.read_blob(&blobs[0]).unwrap(), b"\0base");
5613
}
5614
5615
/// Spec §7.7 on a file system without executable bits or symlinks: the
5616
/// recorded bit is kept, and a symlink checked out as a plain file holding
5617
/// its target is still that symlink.
5618
#[cfg(unix)]
5619
#[test]
5620
fn windows_file_systems_keep_exec_bits_and_symlinks() {
5621
    use crate::portable::Platform;
5622
    use std::os::unix::fs::PermissionsExt;
5623
    hermetic();
5624
    let dir = tempfile::tempdir().unwrap();
5625
    let root = dir.path();
5626
    let repo = Repo::init(root).unwrap();
5627
    write(root, "run.sh", b"#!/bin/sh\n");
5628
    fs::set_permissions(root.join("run.sh"), fs::Permissions::from_mode(0o755)).unwrap();
5629
    std::os::unix::fs::symlink("run.sh", root.join("link")).unwrap();
5630
    repo.commit("script and link", &[]).unwrap();
5631
    drop(repo);
5632
5633
    // What checking out on Windows leaves: no exec bit, the link as a file.
5634
    fs::set_permissions(root.join("run.sh"), fs::Permissions::from_mode(0o644)).unwrap();
5635
    fs::remove_file(root.join("link")).unwrap();
5636
    write(root, "link", b"run.sh");
5637
    let win = Repo::open(root).unwrap().with_platform(Platform::windows());
5638
    let s = win.snapshot("oxy status").unwrap();
5639
    assert!(
5640
        s.statuses.is_empty(),
5641
        "nothing changed on Windows: {:?}",
5642
        statuses(&s)
5643
    );
5644
    // Editing the file is a content change, not a mode change; retargeting the link keeps it a link.
5645
    write(root, "run.sh", b"#!/bin/sh\necho hi\n");
5646
    write(root, "link", b"other");
5647
    let h = win.commit("edit on Windows", &[]).unwrap();
5648
    let snap = win.load_state(&[h]).unwrap().materialize();
5649
    assert!(snap.files["run.sh"].mode.exec, "the exec bit survives");
5650
    assert_eq!(snap.files["link"].kind, NodeKind::Symlink);
5651
    // The same working copy read as Linux sees the lost bit and the plain file.
5652
    let linux = Repo::open(root).unwrap();
5653
    assert!(!linux.snapshot("oxy status").unwrap().statuses.is_empty());
5654
}
5655
5656
/// Paths that collide on case-insensitive or Windows file systems are
5657
/// named at checkout there, and by doctor everywhere.
5658
#[test]
5659
fn paths_other_platforms_cannot_hold_are_reported() {
5660
    use crate::portable::Platform;
5661
    hermetic();
5662
    let dir = tempfile::tempdir().unwrap();
5663
    let root = dir.path();
5664
    let repo = Repo::init(root).unwrap();
5665
    write(root, "README.md", b"a\n");
5666
    write(root, "readme.md", b"b\n");
5667
    write(root, "src/aux.c", b"int x;\n");
5668
    let h = repo.commit("unportable", &[]).unwrap();
5669
    let r = repo.doctor(false);
5670
    let port = r.checks.iter().find(|c| c.area == "portability").unwrap();
5671
    assert_eq!(port.health, Health::Warn);
5672
    assert!(
5673
        port.message.contains("differ only in case") && port.message.contains("aux.c"),
5674
        "{}",
5675
        port.message
5676
    );
5677
    let mac = Repo::open(root).unwrap().with_platform(Platform::macos());
5678
    let rep = mac.checkout(&[h], true, "oxy checkout").unwrap();
5679
    assert!(
5680
        rep.notes
5681
            .iter()
5682
            .any(|n| n.contains("README.md and readme.md")),
5683
        "{:?}",
5684
        rep.notes
5685
    );
5686
    assert!(
5687
        !rep.notes.iter().any(|n| n.contains("aux.c")),
5688
        "macOS allows aux.c"
5689
    );
5690
}
5691
5692
#[test]
5693
fn history_and_blame_of_a_loaded_state_match_the_full_walk() {
5694
    hermetic();
5695
    let dir = tempfile::tempdir().unwrap();
5696
    let repo = Repo::init(dir.path()).unwrap();
5697
    write(dir.path(), "a.txt", b"one\n");
5698
    write(dir.path(), "other.txt", b"x\n");
5699
    write(dir.path(), "bin.dat", &[0u8, 1, 2, 0, 255]);
5700
    repo.snapshot("t").unwrap();
5701
    let c1 = repo.commit("first", &[]).unwrap();
5702
    write(dir.path(), "other.txt", b"y\n");
5703
    repo.snapshot("t").unwrap();
5704
    repo.commit("other only", &[]).unwrap();
5705
    write(dir.path(), "a.txt", b"one\ntwo\n");
5706
    repo.snapshot("t").unwrap();
5707
    let c3 = repo.commit("second line", &[]).unwrap();
5708
    write(dir.path(), "other.txt", b"z\n");
5709
    repo.snapshot("t").unwrap();
5710
    repo.commit("other again", &[]).unwrap();
5711
5712
    let heads = repo.bookmark_heads().unwrap();
5713
    let state = repo.load_state(&heads).unwrap();
5714
    let full: Vec<ChangeHash> = repo
5715
        .log_for_path_in("a.txt", &heads)
5716
        .unwrap()
5717
        .iter()
5718
        .map(|e| e.hash)
5719
        .collect();
5720
    assert_eq!(
5721
        full,
5722
        vec![c3, c1],
5723
        "newest first, only changes touching the path"
5724
    );
5725
    let newest: Vec<ChangeHash> = repo
5726
        .log_for_path_of(&state, "a.txt", Some(1))
5727
        .unwrap()
5728
        .iter()
5729
        .map(|e| e.hash)
5730
        .collect();
5731
    assert_eq!(newest, vec![c3], "stops at the first");
5732
    assert_eq!(
5733
        repo.log_for_path_of(&state, "a.txt", None).unwrap().len(),
5734
        2
5735
    );
5736
    assert!(repo
5737
        .log_for_path_of(&state, "missing.txt", Some(1))
5738
        .is_err());
5739
    assert_eq!(
5740
        repo.log_state(&heads).unwrap().len(),
5741
        repo.log_of(&state).len()
5742
    );
5743
5744
    let tree = state.tree().view();
5745
    let via_state = repo.blame_of(&state, &tree, "a.txt").unwrap();
5746
    let via_heads = repo.blame_in("a.txt", &heads).unwrap();
5747
    assert_eq!(
5748
        via_state
5749
            .iter()
5750
            .map(|l| (l.hash, l.text.clone()))
5751
            .collect::<Vec<_>>(),
5752
        via_heads
5753
            .iter()
5754
            .map(|l| (l.hash, l.text.clone()))
5755
            .collect::<Vec<_>>()
5756
    );
5757
    assert_eq!(
5758
        via_state.iter().map(|l| l.hash).collect::<Vec<_>>(),
5759
        vec![c1, c3]
5760
    );
5761
    assert!(repo.blame_of(&state, &tree, "missing.txt").is_err());
5762
}
5763
5764
/// A text file whose stat matches the manifest and whose recorded hash is
5765
/// the base's content is taken from the base without reading it; anything
5766
/// else is read, so no edit is missed (spec §12.3).
5767
#[cfg(unix)]
5768
#[test]
5769
fn stat_cache_takes_unchanged_text_from_the_base_and_misses_no_edit() {
5770
    use std::os::unix::fs::PermissionsExt;
5771
    hermetic();
5772
    let dir = tempfile::tempdir().unwrap();
5773
    let root = dir.path();
5774
    let repo = Repo::init(root).unwrap().with_home(root.join("home"));
5775
    write(root, "a.txt", b"one\ntwo\n");
5776
    write(root, "b.txt", b"bee\n");
5777
    repo.commit("base", &[]).unwrap();
5778
    let age = |p: &str| {
5779
        let old = std::time::SystemTime::now() - std::time::Duration::from_secs(30);
5780
        fs::File::options()
5781
            .write(true)
5782
            .open(root.join(p))
5783
            .unwrap()
5784
            .set_modified(old)
5785
            .unwrap();
5786
    };
5787
    age("a.txt");
5788
    age("b.txt");
5789
    assert!(
5790
        !repo.snapshot("status").unwrap().changed,
5791
        "records the aged stat"
5792
    );
5793
5794
    // Clean and equal to the base: not read at all.
5795
    fs::set_permissions(root.join("a.txt"), fs::Permissions::from_mode(0o000)).unwrap();
5796
    let snap = repo.snapshot("status").unwrap();
5797
    assert!(
5798
        !snap.changed && snap.statuses.is_empty(),
5799
        "{:?}",
5800
        snap.statuses
5801
    );
5802
    fs::set_permissions(root.join("a.txt"), fs::Permissions::from_mode(0o644)).unwrap();
5803
5804
    // An uncommitted edit that is older than the manifest: stat-clean, but
5805
    // its hash is not the base's, so it is read and stays visible.
5806
    write(root, "b.txt", b"bee edited\n");
5807
    age("b.txt");
5808
    let first = repo.snapshot("status").unwrap();
5809
    assert_eq!(
5810
        statuses(&first),
5811
        vec![("b.txt".to_string(), ChangeStatus::Modified)]
5812
    );
5813
    let again = repo.snapshot("status").unwrap();
5814
    assert_eq!(
5815
        statuses(&again),
5816
        vec![("b.txt".to_string(), ChangeStatus::Modified)],
5817
        "still seen once stat-clean"
5818
    );
5819
    assert!(!again.changed, "and the working copy hashes the same");
5820
    fs::set_permissions(root.join("b.txt"), fs::Permissions::from_mode(0o000)).unwrap();
5821
    assert!(
5822
        repo.snapshot("status").is_err(),
5823
        "an edited file must be read, never taken from the base"
5824
    );
5825
    fs::set_permissions(root.join("b.txt"), fs::Permissions::from_mode(0o644)).unwrap();
5826
5827
    // A same-size edit made just now is racy and read.
5828
    write(root, "a.txt", b"one\nTWO\n");
5829
    assert_eq!(
5830
        statuses(&repo.snapshot("status").unwrap()),
5831
        vec![
5832
            ("a.txt".to_string(), ChangeStatus::Modified),
5833
            ("b.txt".to_string(), ChangeStatus::Modified)
5834
        ]
5835
    );
5836
    // Committing makes the edits the base: both are clean and served from it again.
5837
    repo.commit("edits", &[]).unwrap();
5838
    age("a.txt");
5839
    age("b.txt");
5840
    assert!(repo.snapshot("status").unwrap().statuses.is_empty());
5841
    fs::set_permissions(root.join("a.txt"), fs::Permissions::from_mode(0o000)).unwrap();
5842
    fs::set_permissions(root.join("b.txt"), fs::Permissions::from_mode(0o000)).unwrap();
5843
    let snap = repo.snapshot("status").unwrap();
5844
    assert!(!snap.changed && snap.statuses.is_empty());
5845
    fs::set_permissions(root.join("a.txt"), fs::Permissions::from_mode(0o644)).unwrap();
5846
    fs::set_permissions(root.join("b.txt"), fs::Permissions::from_mode(0o644)).unwrap();
5847
}
5848
5849
/// Version 2 checkpoints (spec §11): a large file's graph is a blob of its
5850
/// own, kept by gc, checked by fsck, shared by the next checkpoint when the
5851
/// file is unchanged, and loading through the checkpoint equals a full load.
5852
#[test]
5853
fn checkpoints_keep_large_graphs_as_blobs_of_their_own() {
5854
    hermetic();
5855
    let dir = tempfile::tempdir().unwrap();
5856
    let root = dir.path();
5857
    let repo = Repo::init(root).unwrap().with_home(root.join("home"));
5858
    let long: String = (0..300)
5859
        .map(|i| format!("line {i} of a long file\n"))
5860
        .collect();
5861
    write(root, "long.txt", long.as_bytes());
5862
    write(root, "short.txt", b"short\n");
5863
    repo.commit("base", &[]).unwrap();
5864
    let (r1, _, _) = repo.checkpoint().unwrap();
5865
    let cp1 = crate::objects::Checkpoint::decode(
5866
        &repo.store().get_typed(&r1, ObjectType::Checkpoint).unwrap(),
5867
    )
5868
    .unwrap();
5869
    let graphs1 = repo.checkpoint_graph_blobs(&cp1).unwrap();
5870
    assert_eq!(graphs1.len(), 1, "only the long file's graph is a blob");
5871
5872
    // gc keeps the graph blob; fsck finds the checkpoint sound.
5873
    repo.gc(true).unwrap();
5874
    assert!(repo.store().has(&graphs1[0]));
5875
    let report = repo.fsck().unwrap();
5876
    assert_eq!(report.errors(), 0, "{:?}", report.problems);
5877
5878
    // Loading through the checkpoint equals a full load.
5879
    write(root, "short.txt", b"short, edited\n");
5880
    repo.commit("edit the short file", &[]).unwrap();
5881
    let heads = repo.bookmark_heads().unwrap();
5882
    let fast = repo.load_state(&heads).unwrap();
5883
    let full = repo.load_state_full(&heads).unwrap();
5884
    assert_eq!(fast.checkpoint_payload(), full.checkpoint_payload());
5885
5886
    // The next checkpoint shares the unchanged long file's graph.
5887
    let (r2, _, _) = repo.checkpoint().unwrap();
5888
    let cp2 = crate::objects::Checkpoint::decode(
5889
        &repo.store().get_typed(&r2, ObjectType::Checkpoint).unwrap(),
5890
    )
5891
    .unwrap();
5892
    assert_eq!(repo.checkpoint_graph_blobs(&cp2).unwrap(), graphs1);
5893
5894
    // A shallow clone's bundle carries the graph blob with the checkpoint.
5895
    let bundle = repo.checkpoint_bundle_for(&heads).unwrap();
5896
    assert!(bundle.objects.iter().any(|(t, body)| *t == ObjectType::Blob
5897
        && crate::hash::hash_object(ObjectType::Blob, body) == graphs1[0]));
5898
5899
    // A version 1 checkpoint written by an older oxy still loads.
5900
    let state = repo.load_state_full(&heads).unwrap();
5901
    let old = repo.store_blob(&state.checkpoint_payload()).unwrap();
5902
    let cp_old = crate::objects::Checkpoint {
5903
        heads: cp2.heads.clone(),
5904
        count: cp2.count,
5905
        payload: old,
5906
    };
5907
    let r_old = repo
5908
        .store()
5909
        .put(ObjectType::Checkpoint, &cp_old.encode())
5910
        .unwrap();
5911
    repo.install_checkpoint("main", &r_old).unwrap();
5912
    assert_eq!(
5913
        repo.load_state(&heads).unwrap().checkpoint_payload(),
5914
        full.checkpoint_payload()
5915
    );
5916
    assert_eq!(repo.fsck().unwrap().errors(), 0);
5917
5918
    // A lost graph blob fails the load loudly rather than dropping the
5919
    // file, and fsck reports it (a fresh repository, objects still loose).
5920
    let dir2 = tempfile::tempdir().unwrap();
5921
    let root2 = dir2.path();
5922
    let repo2 = Repo::init(root2).unwrap().with_home(root2.join("home"));
5923
    write(root2, "long.txt", long.as_bytes());
5924
    repo2.commit("base", &[]).unwrap();
5925
    let (r, _, _) = repo2.checkpoint().unwrap();
5926
    let cp = crate::objects::Checkpoint::decode(
5927
        &repo2.store().get_typed(&r, ObjectType::Checkpoint).unwrap(),
5928
    )
5929
    .unwrap();
5930
    let graph = repo2.checkpoint_graph_blobs(&cp).unwrap()[0];
5931
    repo2.store().remove_loose_for_test(&graph).unwrap();
5932
    assert!(repo2.load_state(&repo2.bookmark_heads().unwrap()).is_err());
5933
    assert!(repo2.fsck().unwrap().errors() > 0, "fsck reports it");
5934
}
5935
5936
/// A new repository has not stored the user's identity yet (that happens
5937
/// at the first signed change); looking it up falls back to the key
5938
/// directory, and a file there that does not hash to the key is refused.
5939
#[test]
5940
fn identity_is_found_in_the_key_directory_for_a_new_repository() {
5941
    hermetic();
5942
    let dir = tempfile::tempdir().unwrap();
5943
    let home = dir.path().join("home");
5944
    let mut first = Repo::init(&dir.path().join("a"))
5945
        .unwrap()
5946
        .with_home(home.clone());
5947
    let (key, _) = first
5948
        .create_identity("Ada", "[email protected]", IdentityScope::User)
5949
        .unwrap();
5950
    let fresh = Repo::init(&dir.path().join("b"))
5951
        .unwrap()
5952
        .with_home(home.clone());
5953
    assert!(!fresh.store().has(&key), "nothing stored yet");
5954
    let id = fresh.identity(&key).unwrap();
5955
    assert_eq!((id.name.as_str(), id.hash()), ("Ada", key));
5956
    // A key file that is not this identity is an error, not a wrong answer.
5957
    let keys = fresh.keys_dir.clone();
5958
    let (other, _) = first
5959
        .create_identity("Bob", "[email protected]", IdentityScope::User)
5960
        .unwrap();
5961
    fs::copy(
5962
        keys.join(format!("{}.identity", other.to_hex())),
5963
        keys.join(format!("{}.identity", key.to_hex())),
5964
    )
5965
    .unwrap();
5966
    assert!(fresh
5967
        .identity(&key)
5968
        .unwrap_err()
5969
        .to_string()
5970
        .contains("does not hold identity"));
5971
}
5972
5973
/// Status snapshots (spec §12.3): a text file whose stat matches the
5974
/// manifest, and whose base graph key is the one the manifest recorded it
5975
/// equal to, is neither read nor rendered; any edit, and any change to the
5976
/// file's graph in the base, brings it back.
5977
#[cfg(unix)]
5978
#[test]
5979
fn status_snapshots_skip_files_unchanged_since_the_manifest() {
5980
    use std::os::unix::fs::PermissionsExt;
5981
    hermetic();
5982
    let dir = tempfile::tempdir().unwrap();
5983
    let root = dir.path();
5984
    let repo = Repo::init(root).unwrap().with_home(root.join("home"));
5985
    for (p, c) in [("a.txt", "one\n"), ("b.txt", "bee\n"), ("d/c.txt", "sea\n")] {
5986
        write(root, p, c.as_bytes());
5987
    }
5988
    repo.commit("base", &[]).unwrap();
5989
    let age = |p: &str| {
5990
        let old = std::time::SystemTime::now() - std::time::Duration::from_secs(30);
5991
        fs::File::options()
5992
            .write(true)
5993
            .open(root.join(p))
5994
            .unwrap()
5995
            .set_modified(old)
5996
            .unwrap();
5997
    };
5998
    let lock = |p: &str, mode: u32| {
5999
        fs::set_permissions(root.join(p), fs::Permissions::from_mode(mode)).unwrap()
6000
    };
6001
    for p in ["a.txt", "b.txt", "d/c.txt"] {
6002
        age(p);
6003
    }
6004
    assert!(repo.snapshot("status").unwrap().statuses.is_empty());
6005
    let (_, _, m) = repo.read_manifest().unwrap().unwrap();
6006
    assert!(
6007
        m.entries.values().all(|e| e.graph.is_some()),
6008
        "keys recorded"
6009
    );
6010
6011
    // Unreadable files prove they are not read; the status snapshot does
6012
    // not render them either, and its base lacks their graphs.
6013
    lock("a.txt", 0o000);
6014
    lock("b.txt", 0o000);
6015
    let snap = repo.snapshot_status("status").unwrap();
6016
    assert!(!snap.changed && snap.statuses.is_empty());
6017
    assert_eq!(
6018
        snap.base_snapshot
6019
            .unrendered
6020
            .iter()
6021
            .cloned()
6022
            .collect::<Vec<_>>(),
6023
        vec!["a.txt", "b.txt", "d/c.txt"]
6024
    );
6025
    assert!(!snap.base.is_full());
6026
    assert!(!snap.base_snapshot.is_conflicted());
6027
    // A full snapshot does not read them either, but renders everything.
6028
    let full = repo.snapshot("status").unwrap();
6029
    assert!(full.statuses.is_empty() && full.base.is_full());
6030
    assert!(full.base_snapshot.unrendered.is_empty());
6031
    assert!(matches!(&full.base_snapshot.files["a.txt"].content,
6032
        FileContent::Text { bytes, .. } if bytes == b"one\n"));
6033
6034
    // An edit is seen; the file is rendered, the others still are not.
6035
    write(root, "d/c.txt", b"sea edited\n");
6036
    let snap = repo.snapshot_status("status").unwrap();
6037
    assert_eq!(
6038
        statuses(&snap),
6039
        vec![("d/c.txt".to_string(), ChangeStatus::Modified)]
6040
    );
6041
    assert!(!snap.base_snapshot.unrendered.contains("d/c.txt"));
6042
    // So is a mode change of an unread file.
6043
    lock("b.txt", 0o100);
6044
    assert_eq!(
6045
        statuses(&repo.snapshot_status("status").unwrap()),
6046
        vec![
6047
            ("b.txt".to_string(), ChangeStatus::ModeChanged),
6048
            ("d/c.txt".to_string(), ChangeStatus::Modified)
6049
        ]
6050
    );
6051
    lock("b.txt", 0o000);
6052
6053
    // Committing c.txt changes its graph in the base, not a.txt's: a.txt
6054
    // stays unread, c.txt is read once and then skipped too.
6055
    repo.commit_selection("edit c", &[], &Selection::Paths(vec!["d/c.txt".into()]))
6056
        .unwrap();
6057
    age("d/c.txt");
6058
    let snap = repo.snapshot_status("status").unwrap();
6059
    assert!(snap.statuses.is_empty(), "{:?}", snap.statuses);
6060
    assert!(snap.base_snapshot.unrendered.contains("a.txt"));
6061
    lock("d/c.txt", 0o000);
6062
    let snap = repo.snapshot_status("status").unwrap();
6063
    assert!(snap.statuses.is_empty());
6064
    assert!(snap.base_snapshot.unrendered.contains("d/c.txt"));
6065
    for p in ["a.txt", "b.txt", "d/c.txt"] {
6066
        lock(p, 0o644);
6067
    }
6068
}
6069
6070
/// Attributes decide how a file compares with the base, so a changed
6071
/// `.oxyattributes` makes every text file be compared again.
6072
#[cfg(unix)]
6073
#[test]
6074
fn a_changed_attributes_file_disables_skipping_unchanged_files() {
6075
    hermetic();
6076
    let dir = tempfile::tempdir().unwrap();
6077
    let root = dir.path();
6078
    let repo = Repo::init(root).unwrap().with_home(root.join("home"));
6079
    write(root, "a.txt", b"crlf\r\n");
6080
    repo.commit("base", &[]).unwrap();
6081
    let old = std::time::SystemTime::now() - std::time::Duration::from_secs(30);
6082
    fs::File::options()
6083
        .write(true)
6084
        .open(root.join("a.txt"))
6085
        .unwrap()
6086
        .set_modified(old)
6087
        .unwrap();
6088
    assert!(repo.snapshot_status("status").unwrap().statuses.is_empty());
6089
    assert!(repo
6090
        .snapshot_status("status")
6091
        .unwrap()
6092
        .base_snapshot
6093
        .unrendered
6094
        .contains("a.txt"));
6095
    // With eol=lf, a.txt as stored no longer equals the base.
6096
    write(root, ".oxyattributes", b"*.txt eol=lf\n");
6097
    let snap = repo.snapshot_status("status").unwrap();
6098
    assert_eq!(
6099
        statuses(&snap),
6100
        vec![
6101
            (".oxyattributes".to_string(), ChangeStatus::Added),
6102
            ("a.txt".to_string(), ChangeStatus::Modified)
6103
        ]
6104
    );
6105
}
6106
6107
/// Bookmarks with `/` in their names: pushing records their
6108
/// attestations, and checkpoints are kept for them, beside `feature`
6109
/// itself.
6110
#[test]
6111
fn bookmarks_with_slashes_push_and_checkpoint() {
6112
    hermetic();
6113
    let dir = tempfile::tempdir().unwrap();
6114
    let root = dir.path();
6115
    let origin = Repo::init(&root.join("origin")).unwrap();
6116
    let url = root.join("origin").to_string_lossy().to_string();
6117
    let mut repo = Repo::clone(&url, &root.join("r"))
6118
        .unwrap()
6119
        .with_home(root.join("home"));
6120
    // With an identity, pushes carry reference attestations: the case
6121
    // that failed, since the attestation is a file named after the bookmark.
6122
    repo.create_identity("Ada", "[email protected]", IdentityScope::Repo)
6123
        .unwrap();
6124
    let r = root.join("r");
6125
    write(&r, "a.txt", b"a\n");
6126
    let h_a = repo.commit("a", &[]).unwrap();
6127
    assert!(repo.push("origin", false).unwrap()[0].ok);
6128
    origin.refresh().unwrap();
6129
    repo.bookmark_create("feature", None).unwrap();
6130
    repo.bookmark_create("feature/x", None).unwrap();
6131
    repo.bookmark_switch("feature/x", false).unwrap();
6132
    write(&r, "b.txt", b"b\n");
6133
    let h_b = repo.commit("b", &[]).unwrap();
6134
    for name in ["feature", "feature/x"] {
6135
        let res = repo.push_bookmark("origin", name, false).unwrap();
6136
        origin.refresh().unwrap();
6137
        assert!(res[0].ok, "{name}: {res:?}");
6138
    }
6139
    assert_eq!(origin.resolve_heads("feature").unwrap(), vec![h_a]);
6140
    assert_eq!(
6141
        origin.resolve_heads("feature/x").unwrap(),
6142
        repo.resolve_heads("feature/x").unwrap()
6143
    );
6144
    assert!(origin.resolve_heads("feature/x").unwrap().contains(&h_b));
6145
    assert!(origin.latest_ref_attest("feature/x").unwrap().is_some());
6146
    assert!(origin.latest_ref_attest("feature").unwrap().is_some());
6147
6148
    // A checkpoint of feature/x is found again when loading its state.
6149
    let (cp, _, _) = repo.checkpoint().unwrap();
6150
    assert_eq!(repo.latest_checkpoint("feature/x").unwrap().unwrap().0, cp);
6151
    assert!(repo.latest_checkpoint("feature").unwrap().is_none());
6152
    let heads = repo.resolve_heads("feature/x").unwrap();
6153
    assert!(repo.load_state_checkpointed(&heads).unwrap().is_some());
6154
}
6155
6156
/// Deleting a bookmark on a remote (spec §16.4): attested like any update,
6157
/// never the remote's own bookmark, and a bookmark created again later is
6158
/// accepted although the deletion's attestation stays the latest.
6159
#[test]
6160
fn bookmarks_are_deleted_on_a_remote() {
6161
    hermetic();
6162
    let dir = tempfile::tempdir().unwrap();
6163
    let root = dir.path();
6164
    let origin = Repo::init(&root.join("origin")).unwrap();
6165
    let url = root.join("origin").to_string_lossy().to_string();
6166
    let mut repo = Repo::clone(&url, &root.join("r"))
6167
        .unwrap()
6168
        .with_home(root.join("home"));
6169
    repo.create_identity("Ada", "[email protected]", IdentityScope::Repo)
6170
        .unwrap();
6171
    let r = root.join("r");
6172
    write(&r, "a.txt", b"a\n");
6173
    repo.commit("a", &[]).unwrap();
6174
    assert!(repo.push("origin", false).unwrap()[0].ok);
6175
    origin.refresh().unwrap();
6176
    repo.bookmark_create("feature/x", None).unwrap();
6177
    assert!(repo.push_bookmark("origin", "feature/x", false).unwrap()[0].ok);
6178
    origin.refresh().unwrap();
6179
    assert!(origin.resolve_heads("feature/x").is_ok());
6180
6181
    let res = repo.push_delete("origin", "feature/x").unwrap();
6182
    origin.refresh().unwrap();
6183
    assert!(res[0].ok, "{res:?}");
6184
    assert!(!origin.view().unwrap().bookmarks.contains_key("feature/x"));
6185
    let (_, att) = origin.latest_ref_attest("feature/x").unwrap().unwrap();
6186
    assert!(
6187
        matches!(att.attest.body, AttestBody::Ref { new_state, .. } if new_state.is_zero()),
6188
        "the deletion is attested"
6189
    );
6190
    assert!(
6191
        repo.view().unwrap().bookmarks.contains_key("feature/x"),
6192
        "the local bookmark stays"
6193
    );
6194
    assert!(!repo
6195
        .view()
6196
        .unwrap()
6197
        .remotes
6198
        .get("origin")
6199
        .is_some_and(|m| m.contains_key("feature/x")));
6200
6201
    // Pushing it again creates it again, past the deletion's serial.
6202
    let res = repo.push_bookmark("origin", "feature/x", false).unwrap();
6203
    origin.refresh().unwrap();
6204
    assert!(res[0].ok, "{res:?}");
6205
    assert!(origin.view().unwrap().bookmarks.contains_key("feature/x"));
6206
6207
    // Nothing to delete, and never the remote's own bookmark.
6208
    assert!(repo.push_delete("origin", "nope").is_err());
6209
    let res = repo.push_delete("origin", "main").unwrap();
6210
    origin.refresh().unwrap();
6211
    assert!(
6212
        !res[0].ok && res[0].reason.contains("default bookmark"),
6213
        "{res:?}"
6214
    );
6215
    assert!(origin.view().unwrap().bookmarks.contains_key("main"));
6216
}
6217
6218
/// `bookmark switch --carry` (spec §10.1): uncommitted work goes along
6219
/// when the target has the same versions of the files it touches, and is
6220
/// refused, untouched, when it has others.
6221
#[test]
6222
fn switching_bookmarks_carries_uncommitted_work() {
6223
    hermetic();
6224
    let dir = tempfile::tempdir().unwrap();
6225
    let root = dir.path();
6226
    let mut repo = Repo::init(root).unwrap().with_home(root.join("home"));
6227
    write(root, "a.txt", b"a\n");
6228
    write(root, "b.txt", b"b\n");
6229
    write(root, "gone.txt", b"gone\n");
6230
    repo.commit("base", &[]).unwrap();
6231
    repo.bookmark_create("feature", None).unwrap();
6232
    // Started on main, belongs on feature: edit, add, remove.
6233
    write(root, "a.txt", b"a\nmore\n");
6234
    write(root, "new.txt", b"new\n");
6235
    fs::remove_file(root.join("gone.txt")).unwrap();
6236
    let (_, carried) = repo.bookmark_switch_carry("feature").unwrap();
6237
    assert_eq!(carried, vec!["a.txt", "gone.txt", "new.txt"]);
6238
    assert_eq!(repo.config.bookmark, "feature");
6239
    assert_eq!(fs::read(root.join("a.txt")).unwrap(), b"a\nmore\n");
6240
    assert_eq!(fs::read(root.join("new.txt")).unwrap(), b"new\n");
6241
    assert!(!root.join("gone.txt").exists());
6242
    let snap = repo.snapshot("status").unwrap();
6243
    assert_eq!(
6244
        statuses(&snap),
6245
        vec![
6246
            ("a.txt".to_string(), ChangeStatus::Modified),
6247
            ("gone.txt".to_string(), ChangeStatus::Removed),
6248
            ("new.txt".to_string(), ChangeStatus::Added)
6249
        ]
6250
    );
6251
    repo.commit("the work", &[]).unwrap();
6252
    assert!(repo.resolve_heads("main").unwrap().len() == 1);
6253
6254
    // main moves b.txt on; work on feature touching b.txt cannot follow.
6255
    repo.bookmark_switch("main", false).unwrap();
6256
    write(root, "b.txt", b"b on main\n");
6257
    repo.commit("b on main", &[]).unwrap();
6258
    repo.bookmark_switch("feature", false).unwrap();
6259
    write(root, "b.txt", b"b edited\n");
6260
    let err = repo.bookmark_switch_carry("main").unwrap_err().to_string();
6261
    assert!(err.contains("b.txt") && err.contains("--discard"), "{err}");
6262
    assert_eq!(repo.config.bookmark, "feature", "nothing happened");
6263
    assert_eq!(fs::read(root.join("b.txt")).unwrap(), b"b edited\n");
6264
}
6265
6266
/// Merging and checking out (feedback 3): a working copy without changes
6267
/// follows a merge whichever state it sat on; a refused checkout names
6268
/// what is in the way; `checkout --carry` takes the work along.
6269
#[test]
6270
fn merges_move_clean_working_copies_and_checkouts_say_what_blocks_them() {
6271
    hermetic();
6272
    let dir = tempfile::tempdir().unwrap();
6273
    let root = dir.path();
6274
    let mut repo = Repo::init(root).unwrap().with_home(root.join("home"));
6275
    write(root, "a.txt", b"a\n");
6276
    let h1 = repo.commit("a", &[]).unwrap();
6277
    write(root, "b.txt", b"b\n");
6278
    repo.commit("b", &[]).unwrap();
6279
    repo.bookmark_create("feature", None).unwrap();
6280
    repo.bookmark_switch("feature", false).unwrap();
6281
    write(root, "c.txt", b"c\n");
6282
    repo.commit("c on feature", &[]).unwrap();
6283
    repo.bookmark_switch("main", false).unwrap();
6284
    // The working copy sits on an older state than main's heads.
6285
    repo.checkout(&[h1], false, "checkout").unwrap();
6286
    assert!(!root.join("b.txt").exists());
6287
    let m = repo.merge("feature").unwrap();
6288
    assert!(m.checked_out, "a clean working copy follows the merge");
6289
    for f in ["a.txt", "b.txt", "c.txt"] {
6290
        assert!(root.join(f).exists(), "{f}");
6291
    }
6292
6293
    // A refusal says which paths are in the way and what to do.
6294
    fs::remove_file(root.join("b.txt")).unwrap();
6295
    write(root, "a.txt", b"a edited\n");
6296
    let err = repo
6297
        .checkout(&[h1], false, "checkout")
6298
        .unwrap_err()
6299
        .to_string();
6300
    assert!(
6301
        err.contains("modified a.txt") && err.contains("removed b.txt") && err.contains("--carry"),
6302
        "{err}"
6303
    );
6304
    // --carry takes them along: h1 has a.txt as the base has it, and the
6305
    // removed b.txt is already as h1 has it (none), so that is no conflict
6306
    // either (oxygen#100).
6307
    let (_, carried) = repo
6308
        .checkout_carry(&[h1], "the first change", "checkout")
6309
        .unwrap();
6310
    assert_eq!(carried, vec!["a.txt"]);
6311
    assert_eq!(fs::read(root.join("a.txt")).unwrap(), b"a edited\n");
6312
    assert!(!root.join("b.txt").exists(), "h1 has no b.txt");
6313
}
6314
6315
/// Doctor and subrepos before the first commit (feedback 5 and 8): a
6316
/// user identity not stored in a new repository yet is fine while its
6317
/// secret key is there; an added subrepo is listed as not committed yet.
6318
#[test]
6319
fn a_new_repository_is_healthy_before_its_first_commit() {
6320
    hermetic();
6321
    let dir = tempfile::tempdir().unwrap();
6322
    let root = dir.path();
6323
    let home = root.join("home");
6324
    let mut first = Repo::init(&root.join("first"))
6325
        .unwrap()
6326
        .with_home(home.clone());
6327
    let (key, _) = first
6328
        .create_identity("Ada", "[email protected]", IdentityScope::User)
6329
        .unwrap();
6330
    let repo = Repo::init(&root.join("second"))
6331
        .unwrap()
6332
        .with_home(home.clone());
6333
    // Only the secret key: no identity object anywhere this repository sees.
6334
    let keys = repo.keys_dir.clone();
6335
    let _ = fs::remove_file(keys.join(format!("{}.identity", key.to_hex())));
6336
    assert!(keys.join(format!("{}.secret", key.to_hex())).is_file());
6337
    let r = repo.doctor(true);
6338
    let id = r.checks.iter().find(|c| c.area == "identity").unwrap();
6339
    assert_eq!(id.health, Health::Ok, "{}", id.message);
6340
    assert!(id.message.contains("first signed change"), "{}", id.message);
6341
6342
    // A subrepo added and not committed yet is listed, pinned where it is.
6343
    let lib = root.join("lib");
6344
    let l = Repo::init(&lib).unwrap().with_home(home.clone());
6345
    write(&lib, "x.txt", b"x\n");
6346
    l.commit("x", &[]).unwrap();
6347
    let second = root.join("second");
6348
    write(&second, "a.txt", b"a\n");
6349
    repo.submodule_add(&lib.to_string_lossy(), "deps/lib", None)
6350
        .unwrap();
6351
    let subs = repo.subrepos().unwrap();
6352
    assert_eq!(subs.len(), 1);
6353
    assert_eq!(
6354
        (subs[0].path.as_str(), subs[0].committed),
6355
        ("deps/lib", false)
6356
    );
6357
    assert_eq!(subs[0].actual.as_ref(), Some(&subs[0].pin));
6358
    repo.commit("add lib", &[]).unwrap();
6359
    let subs = repo.subrepos().unwrap();
6360
    assert!(subs[0].committed, "committed now");
6361
}
6362
6363
/// Commit, diff, hunks and discard use the partial snapshot: a file
6364
/// unchanged since the manifest is neither read nor rendered, and showing
6365
/// a change renders only what it edits, the same as from a full base.
6366
#[cfg(unix)]
6367
#[test]
6368
fn commits_and_diffs_leave_unchanged_files_alone() {
6369
    use std::os::unix::fs::PermissionsExt;
6370
    hermetic();
6371
    let dir = tempfile::tempdir().unwrap();
6372
    let root = dir.path();
6373
    let repo = Repo::init(root).unwrap().with_home(root.join("home"));
6374
    write(root, "big.txt", b"lots\nof\nlines\n");
6375
    write(root, "a.txt", b"one\ntwo\n");
6376
    repo.commit("base", &[]).unwrap();
6377
    let old = std::time::SystemTime::now() - std::time::Duration::from_secs(30);
6378
    for f in ["big.txt", "a.txt"] {
6379
        fs::File::options()
6380
            .write(true)
6381
            .open(root.join(f))
6382
            .unwrap()
6383
            .set_modified(old)
6384
            .unwrap();
6385
    }
6386
    assert!(repo.snapshot_status("status").unwrap().statuses.is_empty());
6387
    // big.txt cannot be read at all from here on.
6388
    fs::set_permissions(root.join("big.txt"), fs::Permissions::from_mode(0o000)).unwrap();
6389
6390
    write(root, "a.txt", b"one\nTWO\nthree\n");
6391
    let diff = repo.diff_files(None).unwrap();
6392
    assert_eq!(
6393
        diff.iter().map(|f| f.path.as_str()).collect::<Vec<_>>(),
6394
        ["a.txt"]
6395
    );
6396
    let (_, hunks) = repo.hunks().unwrap();
6397
    assert!(!hunks.is_empty() && hunks.iter().all(|h| h.path == "a.txt"));
6398
    let h = repo.commit("edit a", &[]).unwrap();
6399
6400
    // Showing the change needs only a.txt's graph, and renders as a full base does.
6401
    let c = repo.store().get_change(&h).unwrap();
6402
    let full = repo.load_state(&c.deps).unwrap();
6403
    let want = render_change(&c, &full, &full.materialize());
6404
    assert_eq!(repo.describe_change(&h).unwrap(), want);
6405
    let (base, snap) = repo.change_base(&c).unwrap();
6406
    assert!(!base.is_full() && snap.unrendered.contains("big.txt"));
6407
6408
    // Discarding works the same way.
6409
    write(root, "a.txt", b"scratch\n");
6410
    assert_eq!(repo.discard(&["a.txt".into()]).unwrap(), 1);
6411
    assert_eq!(fs::read(root.join("a.txt")).unwrap(), b"one\nTWO\nthree\n");
6412
    fs::set_permissions(root.join("big.txt"), fs::Permissions::from_mode(0o644)).unwrap();
6413
}
6414
6415
/// A replace conflict (spec §9.3) is settled by a change that writes one
6416
/// candidate, or new bytes, at the path when the caller names it; a plain
6417
/// snapshot of a checkout never settles it on its own.
6418
#[test]
6419
fn replace_conflicts_are_settled_when_asked() {
6420
    hermetic();
6421
    let dir = tempfile::tempdir().unwrap();
6422
    let root = dir.path();
6423
    let mut repo = Repo::init(root).unwrap().with_home(root.join("home"));
6424
    let blob = |n: u8| {
6425
        let mut v = vec![0u8; 64];
6426
        v[1] = n;
6427
        v
6428
    };
6429
    write(root, "img.bin", &blob(1));
6430
    repo.commit("add img", &[]).unwrap();
6431
    repo.bookmark_create("other", None).unwrap();
6432
    write(root, "img.bin", &blob(2));
6433
    repo.commit("img two", &[]).unwrap();
6434
    repo.bookmark_switch("other", false).unwrap();
6435
    write(root, "img.bin", &blob(3));
6436
    repo.commit("img three", &[]).unwrap();
6437
    repo.bookmark_switch("main", false).unwrap();
6438
    repo.merge("other").unwrap();
6439
    let heads = repo.bookmark_heads().unwrap();
6440
    let merged = repo.load_state(&heads).unwrap().materialize();
6441
    assert!(
6442
        matches!(&merged.files["img.bin"].content, FileContent::Opaque { blobs } if blobs.len() == 2),
6443
        "a replace conflict"
6444
    );
6445
    // A snapshot of the checkout records nothing.
6446
    assert!(repo
6447
        .snapshot("status")
6448
        .unwrap()
6449
        .statuses
6450
        .iter()
6451
        .all(|s| s.path != "img.bin"));
6452
6453
    // Keeping candidate 3 settles it.
6454
    let author = repo.author();
6455
    let edits = [FileEdit {
6456
        path: "img.bin".into(),
6457
        content: Some(blob(3)),
6458
    }];
6459
    let c = repo
6460
        .build_change(&heads, &edits, "keep three", author)
6461
        .unwrap();
6462
    assert_eq!(c.kind, ChangeKind::Resolution);
6463
    let mut st = repo.load_state(&heads).unwrap();
6464
    for d in &c.deps {
6465
        assert!(st.contains(d));
6466
    }
6467
    assert!(
6468
        heads.iter().all(|h| c.deps.contains(h)),
6469
        "depends on both contributors"
6470
    );
6471
    st.add(c).unwrap();
6472
    let after = st.materialize();
6473
    assert!(!after.is_conflicted());
6474
    assert_eq!(
6475
        after.files["img.bin"].content,
6476
        FileContent::Opaque {
6477
            blobs: vec![Repo::blob_ref(&blob(3))]
6478
        }
6479
    );
6480
6481
    // New bytes settle it too.
6482
    let edits = [FileEdit {
6483
        path: "img.bin".into(),
6484
        content: Some(blob(9)),
6485
    }];
6486
    let c = repo.build_change(&heads, &edits, "new", author).unwrap();
6487
    let mut st = repo.load_state(&heads).unwrap();
6488
    st.add(c).unwrap();
6489
    assert_eq!(
6490
        st.materialize().files["img.bin"].content,
6491
        FileContent::Opaque {
6492
            blobs: vec![Repo::blob_ref(&blob(9))]
6493
        }
6494
    );
6495
}
6496
6497
/// The history of a range of lines (spec §27): the changes that wrote
6498
/// or deleted its atoms, or deleted atoms from between them; edits outside
6499
/// the range and changes the range's lines survived are not in it.
6500
#[test]
6501
fn line_ranges_have_exact_histories() {
6502
    hermetic();
6503
    let dir = tempfile::tempdir().unwrap();
6504
    let root = dir.path();
6505
    let repo = Repo::init(root).unwrap().with_home(root.join("home"));
6506
    write(root, "f.rs", b"use x;\nfn a() {\n  one();\n  two();\n}\n");
6507
    let base = repo.commit("add f", &[]).unwrap();
6508
    write(root, "f.rs", b"use y;\nfn a() {\n  one();\n  two();\n}\n");
6509
    let outside = repo.commit("change the import", &[]).unwrap();
6510
    write(root, "f.rs", b"use y;\nfn a() {\n  ONE();\n  two();\n}\n");
6511
    let inside = repo.commit("edit a line of a", &[]).unwrap();
6512
    write(root, "f.rs", b"use y;\nfn a() {\n  ONE();\n}\n");
6513
    let deleted = repo.commit("delete a line of a", &[]).unwrap();
6514
    write(root, "f.rs", b"use y;\nfn a() {\n  ONE();\n}\nfn b() {}\n");
6515
    let after = repo.commit("add b after a", &[]).unwrap();
6516
    let heads = repo.bookmark_heads().unwrap();
6517
6518
    // Lines 2..4 are `fn a() {`, `ONE();`, `}` now.
6519
    let hist: Vec<ChangeHash> = repo
6520
        .line_history(&heads, "f.rs", 2, 4)
6521
        .unwrap()
6522
        .iter()
6523
        .map(|e| e.hash)
6524
        .collect();
6525
    for (h, what) in [
6526
        (base, "wrote it"),
6527
        (inside, "edited a line"),
6528
        (deleted, "deleted a line from inside"),
6529
    ] {
6530
        assert!(hist.contains(&h), "{what}");
6531
    }
6532
    for (h, what) in [(outside, "an edit above"), (after, "an addition below")] {
6533
        assert!(!hist.contains(&h), "{what}");
6534
    }
6535
    assert_eq!(hist[0], deleted, "newest first");
6536
    // One line: only what touched it.
6537
    let one: Vec<ChangeHash> = repo
6538
        .line_history(&heads, "f.rs", 1, 1)
6539
        .unwrap()
6540
        .iter()
6541
        .map(|e| e.hash)
6542
        .collect();
6543
    assert!(one.contains(&outside) && !one.contains(&inside));
6544
    assert!(repo.line_history(&heads, "f.rs", 3, 9).is_err());
6545
    assert!(repo.line_history(&heads, "f.rs", 0, 1).is_err());
6546
    assert!(repo.line_history(&heads, "nope.rs", 1, 1).is_err());
6547
}
6548
6549
#[test]
6550
fn receipts_are_kept_with_their_state_and_verified() {
6551
    use crate::receipt::{Receipt, SignedReceipt};
6552
    hermetic();
6553
    let dir = tempfile::tempdir().unwrap();
6554
    let root = dir.path();
6555
    let repo = Repo::init(root).unwrap().with_home(root.join("home"));
6556
    write(root, "a.txt", b"1\n");
6557
    repo.commit("A", &[]).unwrap();
6558
    let heads = repo.bookmark_heads().unwrap();
6559
    let state = repo
6560
        .store()
6561
        .put_state(&StateObject::new(heads.clone()))
6562
        .unwrap();
6563
    let out = repo.store_blob(b"built\n").unwrap();
6564
    let receipt = Receipt {
6565
        job_name: "build".into(),
6566
        pipeline_hash: ObjectRef([1; 32]),
6567
        scope_tree_hash: ObjectRef([2; 32]),
6568
        inputs: vec![],
6569
        environment: ObjectRef([3; 32]),
6570
        outputs: vec![out],
6571
        exit_code: 0,
6572
        duration_ms: 42,
6573
    };
6574
    let sk = SecretKey::generate();
6575
    let runner = sk.identity("earth-1", "runner@earth", 1);
6576
    let sr = SignedReceipt::sign(
6577
        receipt.clone(),
6578
        repo.id().unwrap(),
6579
        state,
6580
        "demo#1",
6581
        &runner,
6582
        &sk,
6583
    );
6584
6585
    let r = repo.add_receipt(&sr).unwrap();
6586
    let found = repo.receipts(&heads).unwrap();
6587
    assert_eq!(found.len(), 1);
6588
    assert_eq!(found[0].attest, r);
6589
    assert_eq!(found[0].signed, sr);
6590
    assert!(found[0].problem.is_none() && !found[0].revoked);
6591
    assert!(repo.receipts(&[ObjectRef([5; 32])]).unwrap().is_empty());
6592
6593
    // Another repository's receipt, or a forged one, is refused.
6594
    let elsewhere = SignedReceipt::sign(receipt.clone(), [0; 16], state, "x", &runner, &sk);
6595
    assert!(repo
6596
        .add_receipt(&elsewhere)
6597
        .unwrap_err()
6598
        .to_string()
6599
        .contains("another repository"));
6600
    let mut forged = sr.clone();
6601
    forged.receipt.exit_code = 1;
6602
    assert!(repo
6603
        .add_receipt(&forged)
6604
        .unwrap_err()
6605
        .to_string()
6606
        .contains("does not verify"));
6607
6608
    // A receipt signed by a short-lived key keeps its certificate and the
6609
    // issuer's identity, and reads back with them (oxygenhub#241).
6610
    let hub_sk = SecretKey::generate();
6611
    let hub = hub_sk.identity("oxygenhub.io", "[email protected]", 1);
6612
    let job_sk = SecretKey::generate();
6613
    let job = job_sk.identity("job 2 test", "[email protected]", 1);
6614
    let mut test_receipt = receipt.clone();
6615
    test_receipt.job_name = "test".into();
6616
    let plain = SignedReceipt::sign(
6617
        test_receipt,
6618
        repo.id().unwrap(),
6619
        state,
6620
        "demo#2",
6621
        &job,
6622
        &job_sk,
6623
    );
6624
    let now = plain.attest.hlc.wall_ms;
6625
    let cert = crate::cert::SignedCertificate::sign(
6626
        crate::cert::Certificate {
6627
            key: job.clone(),
6628
            issuer: hub.hash(),
6629
            subject: "repo:andy/demo:bookmark:main".into(),
6630
            claims: vec![],
6631
            scope: crate::identity::Scope::SEAL,
6632
            not_before: now - 1_000,
6633
            expires: now + 600_000,
6634
            grant: None,
6635
        },
6636
        &hub,
6637
        &hub_sk,
6638
    );
6639
    let certified = plain.with_certificate(cert, hub.clone());
6640
    repo.add_receipt(&certified).unwrap();
6641
    let found = repo.receipts(&heads).unwrap();
6642
    let got = found
6643
        .iter()
6644
        .find(|i| i.signed.receipt.job_name == "test")
6645
        .unwrap();
6646
    assert_eq!(got.signed, certified);
6647
    assert!(got.problem.is_none(), "{:?}", got.problem);
6648
6649
    // gc keeps the receipts, their runners, the certificate and its issuer,
6650
    // and the output while the state lives.
6651
    repo.gc(true).unwrap();
6652
    let found = repo.receipts(&heads).unwrap();
6653
    assert_eq!(found.len(), 2);
6654
    let got = found
6655
        .iter()
6656
        .find(|i| i.signed.receipt.job_name == "test")
6657
        .unwrap();
6658
    assert_eq!(got.signed, certified, "the certificate survives gc");
6659
    assert!(got.problem.is_none());
6660
    assert_eq!(repo.read_blob(&out).unwrap(), b"built\n");
6661
    assert!(repo.fsck().unwrap().problems.is_empty());
6662
}
6663
6664
#[test]
6665
fn approvals_are_kept_with_their_state_and_survive_gc() {
6666
    hermetic();
6667
    let dir = tempfile::tempdir().unwrap();
6668
    let root = dir.path();
6669
    let repo = Repo::init(root).unwrap().with_home(root.join("home"));
6670
    write(root, "a.txt", b"1\n");
6671
    repo.commit("A", &[]).unwrap();
6672
    let heads = repo.bookmark_heads().unwrap();
6673
    let state = repo.store().put_state(&StateObject::new(heads)).unwrap();
6674
    let plan = repo.store_blob(b"the reviewed plan\n").unwrap();
6675
    let sk = SecretKey::generate();
6676
    let andy = sk.identity("Andy", "[email protected]", 1);
6677
    let statement = crate::approval::Statement {
6678
        repo: repo.id().unwrap(),
6679
        run: "https://hub.example/andy/infra/flow/8".into(),
6680
        job: "apply".into(),
6681
        job_hash: ObjectRef([1; 32]),
6682
        state,
6683
        inputs: vec![plan],
6684
        environment: "prod".into(),
6685
        approve: true,
6686
    };
6687
    let sa = crate::approval::SignedApproval::sign(&statement, &andy, &sk);
6688
    let r = repo.add_approval(&sa).unwrap();
6689
    assert_eq!(repo.store().approvals_for(&state).unwrap(), vec![r]);
6690
    // Another repository's approval, or a changed one, is refused.
6691
    let elsewhere = crate::approval::SignedApproval::sign(
6692
        &crate::approval::Statement {
6693
            repo: [0; 16],
6694
            ..statement.clone()
6695
        },
6696
        &andy,
6697
        &sk,
6698
    );
6699
    assert!(repo
6700
        .add_approval(&elsewhere)
6701
        .unwrap_err()
6702
        .to_string()
6703
        .contains("another repository"));
6704
    let mut forged = sa.clone();
6705
    if let AttestBody::Approval { environment, .. } = &mut forged.attest.body {
6706
        *environment = "dev".into();
6707
    }
6708
    assert!(repo
6709
        .add_approval(&forged)
6710
        .unwrap_err()
6711
        .to_string()
6712
        .contains("does not verify"));
6713
    // gc keeps it, its signature and its signer while the state lives.
6714
    repo.gc(true).unwrap();
6715
    assert_eq!(repo.store().approvals_for(&state).unwrap(), vec![r]);
6716
    assert_eq!(repo.store().get_attest(&r).unwrap(), sa.attest);
6717
    assert_eq!(repo.store().signatures(&r).unwrap(), sa.sigs);
6718
    assert!(repo.fsck().unwrap().problems.is_empty());
6719
}
6720
6721
#[test]
6722
fn status_leaves_an_unchanged_manifest_alone() {
6723
    hermetic();
6724
    let dir = tempfile::tempdir().unwrap();
6725
    let root = dir.path();
6726
    let repo = Repo::init(root).unwrap().with_home(root.join("home"));
6727
    write(root, "a.txt", b"1\n");
6728
    write(root, "b.txt", b"2\n");
6729
    repo.commit("A", &[]).unwrap();
6730
    // Files last touched well outside the racy window.
6731
    let old = std::time::SystemTime::now() - std::time::Duration::from_secs(60);
6732
    for f in ["a.txt", "b.txt"] {
6733
        fs::File::options()
6734
            .write(true)
6735
            .open(root.join(f))
6736
            .unwrap()
6737
            .set_modified(old)
6738
            .unwrap();
6739
    }
6740
    repo.snapshot_status("status").unwrap();
6741
    let path = repo.manifest_path();
6742
    let first = fs::read(&path).unwrap();
6743
    repo.snapshot_status("status").unwrap();
6744
    assert_eq!(
6745
        fs::read(&path).unwrap(),
6746
        first,
6747
        "an unchanged tree does not rewrite the manifest"
6748
    );
6749
    // A change rewrites it.
6750
    write(root, "a.txt", b"1\n2\n");
6751
    repo.snapshot_status("status").unwrap();
6752
    assert_ne!(fs::read(&path).unwrap(), first);
6753
}
6754
6755
#[test]
6756
fn large_text_files_travel_and_survive_gc_as_text_blobs() {
6757
    hermetic();
6758
    let dir = tempfile::tempdir().unwrap();
6759
    let root = dir.path();
6760
    let origin_path = root.join("origin");
6761
    Repo::init(&origin_path).unwrap();
6762
    let origin_url = origin_path.to_string_lossy().to_string();
6763
    let a = Repo::clone(&origin_url, &root.join("a")).unwrap();
6764
    let big: String = (0..5000).map(|i| format!("line {i}\n")).collect();
6765
    write(&root.join("a"), "big.txt", big.as_bytes());
6766
    write(&root.join("a"), "small.txt", b"small\n");
6767
    let h1 = a.commit("large", &[]).unwrap();
6768
    let (_, body) = a.store().get(&h1).unwrap();
6769
    assert!(body.len() < 2048, "the change is {} bytes", body.len());
6770
    assert!(a.push("origin", false).unwrap()[0].ok);
6771
6772
    // A clone reads the text from the blobs that came with the change.
6773
    let b = Repo::clone(&origin_url, &root.join("b")).unwrap();
6774
    assert_eq!(fs::read(root.join("b/big.txt")).unwrap(), big.as_bytes());
6775
    // An edit in the middle of the stored insert is an ordinary change.
6776
    let edited = big.replace("line 2500\n", "line 2500, edited\n");
6777
    write(&root.join("b"), "big.txt", edited.as_bytes());
6778
    let h2 = b.commit("edit", &[]).unwrap();
6779
    assert!(b.store().get_change(&h2).unwrap().edits.len() <= 2);
6780
    assert!(b.push("origin", false).unwrap()[0].ok);
6781
    assert!(a.pull("origin").unwrap().checked_out);
6782
    assert_eq!(fs::read(root.join("a/big.txt")).unwrap(), edited.as_bytes());
6783
    assert_eq!(
6784
        a.fsck().unwrap().errors(),
6785
        0,
6786
        "{:?}",
6787
        a.fsck().unwrap().problems
6788
    );
6789
6790
    // With zero retention gc keeps the text blobs of every kept change.
6791
    let mut a = Repo::open(&root.join("a")).unwrap();
6792
    a.config.set("core.op-retention", "0").unwrap();
6793
    a.save_config().unwrap();
6794
    let a = Repo::open(&root.join("a")).unwrap();
6795
    a.gc(true).unwrap();
6796
    let a = Repo::open(&root.join("a")).unwrap();
6797
    assert_eq!(a.store().get_change(&h1).unwrap().message, "large");
6798
    assert_eq!(
6799
        a.fsck().unwrap().errors(),
6800
        0,
6801
        "{:?}",
6802
        a.fsck().unwrap().problems
6803
    );
6804
    // And a clone of the packed repository reads them from its packs.
6805
    let c = Repo::clone(&root.join("a").to_string_lossy(), &root.join("c")).unwrap();
6806
    assert_eq!(fs::read(root.join("c/big.txt")).unwrap(), edited.as_bytes());
6807
    drop(c);
6808
}
6809
6810
#[test]
6811
fn operations_that_both_replace_a_working_copy_are_not_merged() {
6812
    hermetic();
6813
    let dir = tempfile::tempdir().unwrap();
6814
    let root = dir.path();
6815
    let repo = Repo::init(root).unwrap();
6816
    write(root, "a.txt", b"a\n");
6817
    let a = repo.commit("a", &[]).unwrap();
6818
    write(root, "b.txt", b"b\n");
6819
    repo.commit("b", &[]).unwrap();
6820
    let (x, op) = repo.head_op().unwrap();
6821
    let ws = *op.view.workspaces.keys().next().unwrap();
6822
    let mut one = op.view.clone();
6823
    one.workspaces.insert(ws, a);
6824
    let mut two = op.view.clone();
6825
    two.workspaces.insert(ws, ObjectRef([7; 32]));
6826
    let first = repo.record_op(&[x], "one", one).unwrap();
6827
    let e = repo.record_op(&[x], "two", two).unwrap_err();
6828
    assert!(
6829
        e.to_string()
6830
            .contains("changed this working copy at the same time"),
6831
        "{e}"
6832
    );
6833
    assert_eq!(
6834
        repo.head_op().unwrap().0,
6835
        first,
6836
        "the second is not recorded"
6837
    );
6838
}
6839
6840
/// Metalgear, 2026-09-29 (oxygen#36): a status run while a bookmark switch
6841
/// rewrote the working copy recorded the half-written files as edits, and
6842
/// its view replaced the switch's.
6843
#[test]
6844
fn a_snapshot_during_a_switch_never_records_the_switch_as_edits() {
6845
    hermetic();
6846
    let dir = tempfile::tempdir().unwrap();
6847
    let root = dir.path().to_path_buf();
6848
    let mut repo = Repo::init(&root).unwrap();
6849
    write(&root, "keep.txt", b"keep\n");
6850
    repo.commit("base", &[]).unwrap();
6851
    repo.bookmark_create("small", None).unwrap();
6852
    for i in 0..300 {
6853
        write(
6854
            &root,
6855
            &format!("many/f{i}.txt"),
6856
            format!("file {i}\n").as_bytes(),
6857
        );
6858
    }
6859
    repo.commit("many", &[]).unwrap();
6860
    let stop = std::sync::Arc::new(std::sync::atomic::AtomicBool::new(false));
6861
    let watcher = {
6862
        let (root, stop) = (root.clone(), stop.clone());
6863
        std::thread::spawn(move || {
6864
            let r = Repo::open(&root).unwrap();
6865
            let mut ran = 0;
6866
            while !stop.load(std::sync::atomic::Ordering::Relaxed) {
6867
                if r.snapshot_status("oxy status").is_ok() {
6868
                    ran += 1;
6869
                }
6870
            }
6871
            ran
6872
        })
6873
    };
6874
    for i in 0..20 {
6875
        let to = if i % 2 == 0 { "small" } else { "main" };
6876
        repo.bookmark_switch(to, false).unwrap();
6877
    }
6878
    stop.store(true, std::sync::atomic::Ordering::Relaxed);
6879
    assert!(watcher.join().unwrap() > 0, "the watcher snapshotted");
6880
    // Back on main, clean, with every file where main has it.
6881
    let repo = Repo::open(&root).unwrap();
6882
    let s = repo.snapshot_status("oxy status").unwrap();
6883
    assert!(s.statuses.is_empty(), "{:?}", statuses(&s));
6884
    assert!(s.wc.edits.is_empty() && s.wc.tree_ops.is_empty());
6885
    assert_eq!(s.wc.deps, repo.bookmark_heads().unwrap());
6886
    assert!(root.join("many/f299.txt").exists());
6887
}
6888
6889
/// Metalgear, 2026-09-29 (oxygen#38): a parent's `bookmark switch --carry`
6890
/// put a subrepo that was ahead of its pin back at the pin and moved the
6891
/// subrepo's own bookmark backwards.
6892
#[test]
6893
fn a_parent_switch_with_carry_leaves_a_subrepo_ahead_of_its_pin_alone() {
6894
    hermetic();
6895
    let dir = tempfile::tempdir().unwrap();
6896
    let root = dir.path();
6897
    Repo::init(&root.join("lib-origin")).unwrap();
6898
    let lib_url = root.join("lib-origin").to_string_lossy().to_string();
6899
    let lib = Repo::clone(&lib_url, &root.join("lib")).unwrap();
6900
    write(&root.join("lib"), "lib.txt", b"v1\n");
6901
    lib.commit("lib v1", &[]).unwrap();
6902
    assert!(lib.push("origin", false).unwrap()[0].ok);
6903
6904
    let app_dir = root.join("app");
6905
    let mut app = Repo::init(&app_dir).unwrap();
6906
    write(&app_dir, "main.txt", b"app\n");
6907
    app.submodule_add(&lib_url, "libs/lib", None).unwrap();
6908
    app.commit("app with lib", &[]).unwrap();
6909
    app.bookmark_create("feature", None).unwrap();
6910
6911
    // New work in the subrepo, not yet pinned by the parent.
6912
    let nested_dir = app_dir.join("libs/lib");
6913
    let nested = Repo::open(&nested_dir).unwrap();
6914
    write(&nested_dir, "new.txt", b"new\n");
6915
    let l2 = nested.commit("lib: new file", &[]).unwrap();
6916
    drop(nested);
6917
6918
    let (_, carried) = app.bookmark_switch_carry("feature").unwrap();
6919
    assert!(carried.contains(&"libs/lib".to_string()), "{carried:?}");
6920
    let nested = Repo::open(&nested_dir).unwrap();
6921
    assert!(
6922
        nested.bookmark_heads().unwrap().contains(&l2),
6923
        "its bookmark kept its work"
6924
    );
6925
    assert!(nested_dir.join("new.txt").exists(), "and its files");
6926
    let s = app.snapshot("status").unwrap();
6927
    assert_eq!(
6928
        statuses(&s),
6929
        vec![("libs/lib".to_string(), ChangeStatus::Modified)]
6930
    );
6931
}
6932
6933
/// oxygen#29 (metalgear, rstar-api): after a proposal landed on the hub,
6934
/// moving `main` to a change this clone had pushed on another bookmark,
6935
/// the first `pull` said "Already up to date" while `main` was behind.
6936
#[test]
6937
fn pull_takes_a_remote_move_to_changes_already_here() {
6938
    hermetic();
6939
    let dir = tempfile::tempdir().unwrap();
6940
    let root = dir.path();
6941
    let origin_path = root.join("origin");
6942
    let origin = Repo::init(&origin_path).unwrap();
6943
    let url = origin_path.to_string_lossy().to_string();
6944
    let mut b = Repo::clone(&url, &root.join("b")).unwrap();
6945
    write(&root.join("b"), "base.txt", b"base\n");
6946
    b.commit("base", &[]).unwrap();
6947
    assert!(b.push("origin", false).unwrap()[0].ok);
6948
    origin.refresh().unwrap();
6949
6950
    // A feature bookmark with one change, pushed.
6951
    b.bookmark_create("feat", None).unwrap();
6952
    b.bookmark_switch("feat", false).unwrap();
6953
    write(&root.join("b"), "x.txt", b"x\n");
6954
    let x = b.commit("x", &[]).unwrap();
6955
    assert!(b.push("origin", false).unwrap()[0].ok);
6956
    origin.refresh().unwrap();
6957
    b.bookmark_switch("main", false).unwrap();
6958
6959
    // The remote lands it: its main moves to the feature's state.
6960
    let feat = origin
6961
        .store()
6962
        .get_state(&origin.view().unwrap().bookmarks["feat"])
6963
        .unwrap()
6964
        .heads;
6965
    origin.bookmark_set("main", &feat).unwrap();
6966
6967
    let r = b.pull("origin").unwrap();
6968
    assert!(r.changed, "{r:?}");
6969
    assert!(r.heads.contains(&x) || b.load_state(&r.heads).unwrap().contains(&x));
6970
    let main = b
6971
        .bookmarks()
6972
        .unwrap()
6973
        .into_iter()
6974
        .find(|m| m.name == "main")
6975
        .unwrap();
6976
    assert_eq!(main.behind, Some(0), "{main:?}");
6977
}
6978
6979
/// oxygen#48: a remote's bookmarks are names here (`origin/NAME`); switching
6980
/// to one only the remote has makes a local bookmark from it; a pull moves
6981
/// every local bookmark the remote has too; a clone checks out the remote's
6982
/// default bookmark.
6983
#[test]
6984
fn remote_bookmarks_are_named_switched_to_pulled_and_cloned() {
6985
    hermetic();
6986
    let dir = tempfile::tempdir().unwrap();
6987
    let root = dir.path();
6988
    let origin_path = root.join("origin");
6989
    let mut origin = Repo::init(&origin_path).unwrap();
6990
    let url = origin_path.to_string_lossy().to_string();
6991
    let mut a = Repo::clone(&url, &root.join("a")).unwrap();
6992
    write(&root.join("a"), "base.txt", b"base\n");
6993
    a.commit("base", &[]).unwrap();
6994
    assert!(a.push("origin", false).unwrap()[0].ok);
6995
    a.bookmark_create("develop", None).unwrap();
6996
    a.bookmark_switch("develop", false).unwrap();
6997
    write(&root.join("a"), "base.txt", b"base\nd1\n");
6998
    let d1 = a.commit("d1", &[]).unwrap();
6999
    assert!(a.push("origin", false).unwrap()[0].ok);
7000
7001
    // A clone has main only; origin/develop is a name all the same.
7002
    let c_root = root.join("c");
7003
    let mut c = Repo::clone(&url, &c_root).unwrap();
7004
    assert_eq!(c.config.bookmark, "main");
7005
    assert!(!c.view().unwrap().bookmarks.contains_key("develop"));
7006
    assert_eq!(c.resolve_heads("origin/develop").unwrap(), vec![d1]);
7007
    assert_eq!(c.resolve_change("origin/develop").unwrap(), d1);
7008
    assert_eq!(c.remote_only_bookmarks().unwrap().len(), 1);
7009
7010
    // Switching makes the local bookmark from origin's.
7011
    c.bookmark_switch("develop", false).unwrap();
7012
    assert_eq!(c.config.bookmark, "develop");
7013
    assert_eq!(c.bookmark_heads().unwrap(), vec![d1]);
7014
    assert_eq!(fs::read(c_root.join("base.txt")).unwrap(), b"base\nd1\n");
7015
    assert!(c.remote_only_bookmarks().unwrap().is_empty());
7016
    assert!(c.bookmark_switch("nowhere", false).is_err());
7017
7018
    // Both bookmarks move on the remote; one pull takes both.
7019
    write(&root.join("a"), "base.txt", b"base\nd1\nd2\n");
7020
    let d2 = a.commit("d2", &[]).unwrap();
7021
    assert!(a.push("origin", false).unwrap()[0].ok);
7022
    a.bookmark_switch("main", false).unwrap();
7023
    write(&root.join("a"), "m.txt", b"m\n");
7024
    let m = a.commit("m", &[]).unwrap();
7025
    assert!(a.push("origin", false).unwrap()[0].ok);
7026
    let r = c.pull("origin").unwrap();
7027
    assert!(r.changed && r.checked_out, "{r:?}");
7028
    assert_eq!(r.heads, vec![d2]);
7029
    assert_eq!(r.others, vec!["main".to_string()]);
7030
    assert!(c.resolve_heads("main").unwrap().contains(&m));
7031
    assert_eq!(
7032
        fs::read(c_root.join("base.txt")).unwrap(),
7033
        b"base\nd1\nd2\n"
7034
    );
7035
    let again = c.pull("origin").unwrap();
7036
    assert!(!again.changed && again.others.is_empty(), "{again:?}");
7037
7038
    // A clone checks out the remote's default bookmark.
7039
    origin.config.set("workspace.bookmark", "develop").unwrap();
7040
    origin.save_config().unwrap();
7041
    let e = Repo::clone(&url, &root.join("e")).unwrap();
7042
    assert_eq!(e.config.bookmark, "develop");
7043
    assert_eq!(e.bookmark_heads().unwrap(), vec![d2]);
7044
    let reopened = Repo::open(&root.join("e")).unwrap();
7045
    assert_eq!(reopened.config.bookmark, "develop");
7046
    // REMOTE/NAME names the remote's bookmark to switch to.
7047
    let mut e = reopened;
7048
    e.bookmark_switch("origin/main", false).unwrap();
7049
    assert_eq!(e.config.bookmark, "main");
7050
    assert!(e.bookmark_heads().unwrap().contains(&m));
7051
}
7052
7053
/// oxygen#51, #52: --at-op reads an earlier view and refuses changes;
7054
/// op restore goes back to an operation, files included, and undo takes
7055
/// the restore back whole; op revert undoes one operation alone; each
7056
/// operation's changes are described from the views.
7057
#[test]
7058
fn operations_can_be_read_restored_and_reverted() {
7059
    hermetic();
7060
    let dir = tempfile::tempdir().unwrap();
7061
    let root = dir.path();
7062
    let repo = Repo::init(root).unwrap();
7063
    write(root, "a.txt", b"a\n");
7064
    let first = repo.commit("first", &[]).unwrap();
7065
    write(root, "a.txt", b"a\nb\n");
7066
    let second = repo.commit("second", &[]).unwrap();
7067
    let at_second = repo.head_op().unwrap().0.to_hex();
7068
    repo.bookmark_create("keep", None).unwrap();
7069
    let created = repo.head_op().unwrap().0.to_hex();
7070
    write(root, "n.txt", b"n\n");
7071
    let third = repo.commit("third", &[]).unwrap();
7072
7073
    // What each operation changed.
7074
    let ops = repo.op_log().unwrap();
7075
    let changes = repo.view_changes(&ops[1].1.view, &ops[0].1.view).unwrap();
7076
    assert!(
7077
        changes
7078
            .iter()
7079
            .any(|c| matches!(c, ViewChange::BookmarkMoved { name, .. } if name == "main")),
7080
        "{changes:?}"
7081
    );
7082
    assert!(changes
7083
        .iter()
7084
        .any(|c| matches!(c, ViewChange::WorkingCopy { .. })));
7085
7086
    // Reading at an earlier operation.
7087
    let old = Repo::open(root).unwrap().at_op(&at_second[..10]).unwrap();
7088
    assert_eq!(old.bookmark_heads().unwrap(), vec![second]);
7089
    assert!(!old.view().unwrap().bookmarks.contains_key("keep"));
7090
    write(root, "z.txt", b"z\n");
7091
    assert!(old.commit("refused", &[]).is_err(), "--at-op is read-only");
7092
    fs::remove_file(root.join("z.txt")).unwrap();
7093
    assert!(repo.resolve_op("zz").is_err());
7094
    assert_eq!(repo.resolve_op("@").unwrap().0, repo.head_op().unwrap().0);
7095
7096
    // Restore goes back, files and all; undo takes it back whole.
7097
    repo.op_restore(&at_second, false).unwrap();
7098
    assert_eq!(repo.bookmark_heads().unwrap(), vec![second]);
7099
    assert!(!root.join("n.txt").exists());
7100
    repo.undo().unwrap();
7101
    let mut heads = repo.bookmark_heads().unwrap();
7102
    heads.sort();
7103
    let mut want = vec![second, third];
7104
    want.sort();
7105
    assert_eq!(heads, want);
7106
    assert!(
7107
        root.join("n.txt").exists(),
7108
        "the files came back with the undo"
7109
    );
7110
7111
    // Revert the bookmark's creation alone: the commit after it stays.
7112
    let r = repo.op_revert(&created).unwrap();
7113
    assert_eq!(r.reverted, vec!["keep".to_string()]);
7114
    assert!(!repo.view().unwrap().bookmarks.contains_key("keep"));
7115
    assert!(repo
7116
        .load_state(&repo.bookmark_heads().unwrap())
7117
        .unwrap()
7118
        .contains(&third));
7119
    assert!(repo.op_revert(&created).is_err(), "nothing left to revert");
7120
    let _ = first;
7121
}
7122
7123
/// oxygen#41: with uncommitted work, a status after a snapshot is answered
7124
/// from the status cache while every file is as the snapshot left it, and
7125
/// from a snapshot again as soon as one is not.
7126
#[test]
7127
fn status_with_uncommitted_work_comes_from_the_cache_until_a_file_changes() {
7128
    hermetic();
7129
    let dir = tempfile::tempdir().unwrap();
7130
    let root = dir.path();
7131
    let repo = Repo::init(root).unwrap();
7132
    write(root, "a.txt", b"a\n");
7133
    write(root, "b.txt", b"b\n");
7134
    repo.commit("base", &[]).unwrap();
7135
    assert_eq!(repo.status_by_manifest().unwrap(), Some(vec![]), "clean");
7136
7137
    write(root, "a.txt", b"a\nmore\n");
7138
    assert_eq!(
7139
        repo.status_by_manifest().unwrap(),
7140
        None,
7141
        "no snapshot of the edit yet"
7142
    );
7143
    let snap = repo.snapshot_status("oxy status").unwrap();
7144
    assert_eq!(snap.statuses.len(), 1);
7145
    let cached = repo
7146
        .status_by_manifest()
7147
        .unwrap()
7148
        .expect("answered from the cache");
7149
    assert_eq!(cached.len(), 1);
7150
    assert_eq!(
7151
        (cached[0].path.as_str(), cached[0].status),
7152
        ("a.txt", ChangeStatus::Modified)
7153
    );
7154
7155
    // Any further change sends status back to a snapshot.
7156
    write(root, "a.txt", b"a\nmore\nand more\n");
7157
    assert_eq!(repo.status_by_manifest().unwrap(), None, "edited again");
7158
    repo.snapshot_status("oxy status").unwrap();
7159
    assert!(repo.status_by_manifest().unwrap().is_some());
7160
    write(root, "new.txt", b"n\n");
7161
    assert_eq!(repo.status_by_manifest().unwrap(), None, "a file added");
7162
    fs::remove_file(root.join("new.txt")).unwrap();
7163
    assert!(
7164
        repo.status_by_manifest().unwrap().is_some(),
7165
        "back as it was"
7166
    );
7167
    fs::remove_file(root.join("b.txt")).unwrap();
7168
    assert_eq!(repo.status_by_manifest().unwrap(), None, "a file removed");
7169
    write(root, "b.txt", b"b\n");
7170
7171
    // A commit leaves nothing uncommitted: clean again, no cache needed.
7172
    repo.snapshot_status("oxy status").unwrap();
7173
    repo.commit("more", &[]).unwrap();
7174
    assert_eq!(repo.status_by_manifest().unwrap(), Some(vec![]));
7175
}
7176
7177
/// oxygen#41: while the status cache holds, the working copy's diff is
7178
/// rendered from the stored working-copy change, and says exactly what a
7179
/// snapshot's diff says.
7180
#[test]
7181
fn the_working_copy_diff_from_the_cache_matches_a_snapshot() {
7182
    hermetic();
7183
    let dir = tempfile::tempdir().unwrap();
7184
    let root = dir.path();
7185
    let repo = Repo::init(root).unwrap();
7186
    write(root, "a.txt", b"one\ntwo\nthree\n");
7187
    write(root, "gone.txt", b"bye\n");
7188
    repo.commit("base", &[]).unwrap();
7189
    write(root, "a.txt", b"one\n2\nthree\nfour\n");
7190
    write(root, "new.txt", b"hello\n");
7191
    fs::remove_file(root.join("gone.txt")).unwrap();
7192
    let snap = repo.snapshot_status("oxy status").unwrap();
7193
    let slow = render_change(&snap.wc, &snap.base, &snap.base_snapshot);
7194
    assert!(
7195
        repo.status_by_manifest().unwrap().is_some(),
7196
        "the cache holds"
7197
    );
7198
    let (wc, base, snapshot) = repo.working_copy_with_base().unwrap();
7199
    assert_eq!(render_change(&wc, &base, &snapshot), slow);
7200
    assert_eq!(repo.diff_files(None).unwrap().len(), 3);
7201
}
7202
7203
/// oxygen#41: a manifest written from a walk keeps every directory's time;
7204
/// while none has moved, the check stats the tracked files without listing
7205
/// the tree, and a file added or removed anywhere moves its directory's
7206
/// time, so the tree is listed again.
7207
#[test]
7208
fn the_manifest_check_skips_listing_while_no_directory_changed() {
7209
    hermetic();
7210
    let dir = tempfile::tempdir().unwrap();
7211
    let root = dir.path();
7212
    let repo = Repo::init(root).unwrap();
7213
    write(root, "a.txt", b"a\n");
7214
    write(root, "sub/deep/b.txt", b"b\n");
7215
    repo.commit("base", &[]).unwrap();
7216
    // Out of the racy window: every file and directory a minute old.
7217
    let old = std::time::SystemTime::now() - std::time::Duration::from_secs(60);
7218
    for p in ["a.txt", "sub/deep/b.txt", "sub/deep", "sub", ""] {
7219
        fs::File::open(root.join(p))
7220
            .unwrap()
7221
            .set_modified(old)
7222
            .unwrap();
7223
    }
7224
    repo.snapshot_status("oxy status").unwrap();
7225
    repo.write_manifest(false, false).unwrap();
7226
    let m = repo.read_manifest().unwrap().unwrap().2;
7227
    assert!(m.dirs.iter().any(|(d, _)| d == "sub/deep"), "{:?}", m.dirs);
7228
    assert_eq!(
7229
        repo.disk_differs_by_dirs(&m),
7230
        Some(false),
7231
        "no listing needed"
7232
    );
7233
    assert_eq!(repo.status_by_manifest().unwrap(), Some(vec![]));
7234
7235
    // A same-size edit with a new time: found by its stat.
7236
    write(root, "sub/deep/b.txt", b"c\n");
7237
    assert_eq!(repo.disk_differs_by_dirs(&m), Some(true));
7238
    write(root, "sub/deep/b.txt", b"b\n");
7239
    fs::File::open(root.join("sub/deep/b.txt"))
7240
        .unwrap()
7241
        .set_modified(old)
7242
        .unwrap();
7243
    assert_eq!(repo.disk_differs_by_dirs(&m), Some(false));
7244
7245
    // A new file moves its directory's time: the tree must be listed.
7246
    write(root, "sub/deep/new.txt", b"n\n");
7247
    assert_eq!(repo.disk_differs_by_dirs(&m), None);
7248
    assert_eq!(repo.status_by_manifest().unwrap(), None);
7249
    fs::remove_file(root.join("sub/deep/new.txt")).unwrap();
7250
    // A removed one too.
7251
    fs::remove_file(root.join("a.txt")).unwrap();
7252
    assert_eq!(repo.disk_differs_by_dirs(&m), None);
7253
}
7254
7255
/// oxygen#41: a commit right after a status takes the snapshot the status
7256
/// left (the status cache holds) rather than walking again, and commits
7257
/// exactly what a snapshot would have.
7258
#[test]
7259
fn a_commit_after_a_status_uses_the_cached_snapshot() {
7260
    hermetic();
7261
    let dir = tempfile::tempdir().unwrap();
7262
    let root = dir.path();
7263
    let repo = Repo::init(root).unwrap();
7264
    write(root, "a.txt", b"a\nb\n");
7265
    write(root, ".oxyattributes", b"*.bin binary\n");
7266
    repo.commit("base", &[]).unwrap();
7267
    write(root, "a.txt", b"a\nB\n");
7268
    write(root, "new.txt", b"new\n");
7269
    let snap = repo.snapshot_status("oxy status").unwrap();
7270
    let cached = repo
7271
        .snapshot_from_cache()
7272
        .unwrap()
7273
        .expect("the cache holds");
7274
    assert_eq!(cached.wc_hash, snap.wc_hash);
7275
    assert_eq!(cached.statuses, snap.statuses);
7276
    assert!(
7277
        !cached.attributes.is_empty(),
7278
        "the .oxyattributes file was read"
7279
    );
7280
    let h = repo.commit("edit", &[]).unwrap();
7281
    let c = repo.store().get_change(&h).unwrap();
7282
    assert_eq!(
7283
        c.tree_ops.len() + c.edits.len(),
7284
        snap.wc.tree_ops.len() + snap.wc.edits.len()
7285
    );
7286
    assert_eq!(
7287
        repo.status_by_manifest().unwrap(),
7288
        Some(vec![]),
7289
        "clean after the commit"
7290
    );
7291
    assert_eq!(fs::read(root.join("a.txt")).unwrap(), b"a\nB\n");
7292
}
7293
7294
/// oxygen#41: a clean check that verified racy entries restamps the
7295
/// manifest, so later checks can trust them, and a same-size rewrite
7296
/// straight afterwards is still found: entries within two seconds of the
7297
/// new time stay racy.
7298
#[test]
7299
fn a_verified_clean_check_restamps_the_manifest_safely() {
7300
    hermetic();
7301
    let dir = tempfile::tempdir().unwrap();
7302
    let root = dir.path();
7303
    let repo = Repo::init(root).unwrap();
7304
    write(root, "a.txt", b"one\n");
7305
    repo.commit("one", &[]).unwrap();
7306
    let before = repo.read_manifest().unwrap().unwrap().2.written_ns;
7307
    assert!(repo.clean_by_manifest().unwrap());
7308
    let after = repo.read_manifest().unwrap().unwrap().2.written_ns;
7309
    assert!(after > before, "restamped");
7310
    write(root, "a.txt", b"two\n");
7311
    assert!(
7312
        !repo.clean_by_manifest().unwrap(),
7313
        "a same-size rewrite is still seen"
7314
    );
7315
}
7316
7317
/// oxygen#35: a history-only state keeps no inserted text. It reads a
7318
/// stored insert's text blob only when it builds that file's graph, and
7319
/// builds the same graph a full load does.
7320
#[test]
7321
fn history_only_states_read_text_only_for_the_graphs_they_build() {
7322
    hermetic();
7323
    let dir = tempfile::tempdir().unwrap();
7324
    let root = dir.path();
7325
    let repo = Repo::init(root).unwrap();
7326
    let big: String = (0..3000).map(|i| format!("big line {i}\n")).collect();
7327
    let other: String = (0..3000).map(|i| format!("other line {i}\n")).collect();
7328
    write(root, "big.txt", big.as_bytes());
7329
    write(root, "other.txt", other.as_bytes());
7330
    let h = repo.commit("two large files", &[]).unwrap();
7331
    write(root, "big.txt", format!("{big}one more\n").as_bytes());
7332
    let h2 = repo.commit("append", &[]).unwrap();
7333
7334
    let full = repo.load_state_full(&[h2]).unwrap().materialize();
7335
    let text = |snap: &crate::state::Snapshot, p: &str| match &snap.files[p].content {
7336
        FileContent::Text { bytes, .. } => bytes.clone(),
7337
        other => panic!("{other:?}"),
7338
    };
7339
    // Built on demand, every graph renders as the full load's.
7340
    let mut hist = repo.load_state_history(&[h2]).unwrap();
7341
    let big_node = full.files["big.txt"].node;
7342
    assert!(hist.graph_key(&big_node).is_some(), "not built yet");
7343
    repo.load_all_graphs(&mut hist).unwrap();
7344
    let rendered = hist.materialize();
7345
    for p in ["big.txt", "other.txt"] {
7346
        assert_eq!(text(&rendered, p), text(&full, p), "{p}");
7347
    }
7348
7349
    // Without other.txt's text blob, history still loads and big.txt still
7350
    // builds: nothing read the other text.
7351
    let (_, texts) = repo.store().get_change_lazy(&h).unwrap();
7352
    assert_eq!(texts.len(), 2);
7353
    let content = |r: &ObjectRef| -> Vec<u8> {
7354
        let blob = crate::objects::Blob::decode(&repo.store().get(r).unwrap().1).unwrap();
7355
        blob.chunks
7356
            .iter()
7357
            .flat_map(|c| repo.store().get(c).unwrap().1)
7358
            .collect()
7359
    };
7360
    let other_text = texts
7361
        .iter()
7362
        .filter_map(|t| match t {
7363
            crate::objects::TextRef::Blob(r, _, _) => Some(*r),
7364
            _ => None,
7365
        })
7366
        .find(|r| content(r).windows(12).any(|w| w == b"other line 1"))
7367
        .unwrap();
7368
    repo.store().remove_loose_for_test(&other_text).unwrap();
7369
    let mut hist = repo.load_state_history(&[h2]).unwrap();
7370
    repo.load_graphs_of(&mut hist, &[big_node]).unwrap();
7371
    assert!(repo
7372
        .load_graphs_of(&mut hist, &[full.files["other.txt"].node])
7373
        .is_err());
7374
}
7375
7376
/// oxygen#35: the first status after a commit read and rendered every
7377
/// file (79 s and more than 14 GB on the Linux tree), because the
7378
/// manifest had no graph keys for files the commit added.
7379
#[test]
7380
fn a_commit_leaves_a_manifest_the_next_status_trusts() {
7381
    use std::os::unix::fs::PermissionsExt;
7382
    hermetic();
7383
    let dir = tempfile::tempdir().unwrap();
7384
    let root = dir.path();
7385
    let repo = Repo::init(root).unwrap();
7386
    let files = ["a.txt", "b.txt", "d/c.txt"];
7387
    for p in files {
7388
        write(root, p, format!("{p}\n").as_bytes());
7389
        let old = std::time::SystemTime::now() - std::time::Duration::from_secs(30);
7390
        fs::File::options()
7391
            .write(true)
7392
            .open(root.join(p))
7393
            .unwrap()
7394
            .set_modified(old)
7395
            .unwrap();
7396
    }
7397
    repo.commit("added", &[]).unwrap();
7398
    let (_, _, m) = repo.read_manifest().unwrap().unwrap();
7399
    assert!(
7400
        m.entries.values().all(|e| e.graph.is_some()),
7401
        "keys recorded at commit"
7402
    );
7403
    // Unreadable files prove the next status reads none of them.
7404
    for p in files {
7405
        fs::set_permissions(root.join(p), fs::Permissions::from_mode(0o000)).unwrap();
7406
    }
7407
    let snap = repo.snapshot_status("status").unwrap();
7408
    for p in files {
7409
        fs::set_permissions(root.join(p), fs::Permissions::from_mode(0o644)).unwrap();
7410
    }
7411
    assert!(!snap.changed && snap.statuses.is_empty());
7412
    assert_eq!(snap.base_snapshot.unrendered.len(), files.len());
7413
}
7414
7415
/// oxygen#35: a checkout reads, renders and writes only the files whose
7416
/// graphs differ, and renders the rest a batch at a time.
7417
#[test]
7418
fn checkout_touches_only_what_differs_and_renders_in_batches() {
7419
    use std::os::unix::fs::PermissionsExt;
7420
    hermetic();
7421
    let dir = tempfile::tempdir().unwrap();
7422
    let root = dir.path();
7423
    let origin = root.join("origin");
7424
    let mut repo = Repo::init(&origin).unwrap();
7425
    // More files than one batch holds.
7426
    let n = 2100;
7427
    let old = std::time::SystemTime::now() - std::time::Duration::from_secs(30);
7428
    for i in 0..n {
7429
        let p = format!("f/{i:04}.txt");
7430
        write(&origin, &p, format!("file {i}\n").as_bytes());
7431
        fs::File::options()
7432
            .write(true)
7433
            .open(origin.join(&p))
7434
            .unwrap()
7435
            .set_modified(old)
7436
            .unwrap();
7437
    }
7438
    repo.commit("many", &[]).unwrap();
7439
    repo.bookmark_create("feature", None).unwrap();
7440
    repo.bookmark_switch("feature", false).unwrap();
7441
    write(&origin, "f/0007.txt", b"changed\n");
7442
    repo.commit("one change", &[]).unwrap();
7443
7444
    // Switching back to main must not read the unchanged files.
7445
    for i in 0..n {
7446
        if i != 7 {
7447
            let p = origin.join(format!("f/{i:04}.txt"));
7448
            fs::set_permissions(&p, fs::Permissions::from_mode(0o000)).unwrap();
7449
        }
7450
    }
7451
    let r = repo.bookmark_switch("main", false).unwrap();
7452
    for i in 0..n {
7453
        let p = origin.join(format!("f/{i:04}.txt"));
7454
        fs::set_permissions(&p, fs::Permissions::from_mode(0o644)).unwrap();
7455
    }
7456
    assert_eq!((r.written, r.removed), (1, 0), "{r:?}");
7457
    assert_eq!(fs::read(origin.join("f/0007.txt")).unwrap(), b"file 7\n");
7458
    assert!(repo.snapshot_status("status").unwrap().statuses.is_empty());
7459
7460
    // A clone renders every file, across batches.
7461
    let c = root.join("clone");
7462
    Repo::clone(&origin.to_string_lossy(), &c).unwrap();
7463
    for i in [0, 2047, 2048, n - 1] {
7464
        assert_eq!(
7465
            fs::read(c.join(format!("f/{i:04}.txt"))).unwrap(),
7466
            format!("file {i}\n").as_bytes()
7467
        );
7468
    }
7469
    let cloned = Repo::open(&c).unwrap();
7470
    assert!(cloned
7471
        .snapshot_status("status")
7472
        .unwrap()
7473
        .statuses
7474
        .is_empty());
7475
}
7476
7477
/// A file written just before the manifest (inside the racy window) is
7478
/// checked by its hash: trusted when equal, caught when edited in place
7479
/// with the same size and time.
7480
#[test]
7481
fn a_racy_manifest_entry_is_checked_by_hash() {
7482
    hermetic();
7483
    let dir = tempfile::tempdir().unwrap();
7484
    let root = dir.path();
7485
    let repo = Repo::init(root).unwrap();
7486
    write(root, "a.txt", b"one\n");
7487
    repo.commit("fresh", &[]).unwrap();
7488
    assert!(repo.clean_by_manifest().unwrap(), "fresh but equal");
7489
    let t = fs::metadata(root.join("a.txt"))
7490
        .unwrap()
7491
        .modified()
7492
        .unwrap();
7493
    write(root, "a.txt", b"two\n");
7494
    fs::File::options()
7495
        .write(true)
7496
        .open(root.join("a.txt"))
7497
        .unwrap()
7498
        .set_modified(t)
7499
        .unwrap();
7500
    assert!(
7501
        !repo.clean_by_manifest().unwrap(),
7502
        "same size and time, other bytes"
7503
    );
7504
    assert_eq!(
7505
        statuses(&repo.snapshot_status("status").unwrap()),
7506
        vec![("a.txt".to_string(), ChangeStatus::Modified)]
7507
    );
7508
}
7509
7510
/// A fetch on one machine moves changes as stored, text blobs among the
7511
/// objects; a change whose text blob did not come is refused, not stored.
7512
#[test]
7513
fn a_raw_bundle_without_a_changes_text_is_refused() {
7514
    hermetic();
7515
    let dir = tempfile::tempdir().unwrap();
7516
    let root = dir.path();
7517
    let a = Repo::init(&root.join("a")).unwrap();
7518
    let big: String = (0..3000).map(|i| format!("line {i}\n")).collect();
7519
    write(&root.join("a"), "big.txt", big.as_bytes());
7520
    let h = a.commit("big", &[]).unwrap();
7521
    let bundle = a.bundle_raw_for(&[h], None).unwrap();
7522
    assert_eq!(bundle.raw_changes.len(), 1);
7523
    assert!(bundle.changes.is_empty());
7524
    let b = Repo::init(&root.join("b")).unwrap();
7525
    let mut without = bundle.clone();
7526
    without.objects.retain(|(ty, _)| *ty != ObjectType::Blob);
7527
    let e = b.import_bundle(&without, false).unwrap_err();
7528
    assert!(e.to_string().contains("came without its text blob"), "{e}");
7529
    assert!(!b.store().has(&h));
7530
    assert_eq!(b.import_bundle(&bundle, false).unwrap(), vec![h]);
7531
    assert_eq!(b.store().get_change(&h).unwrap().message, "big");
7532
}
7533
7534
/// oxygen#30 (vscode): a directory deleted in one line of history and made
7535
/// again was a second node for one Git path, so a file moved into it on
7536
/// another line, where the first node still stood, ended up in two places.
7537
/// An import now brings the directory back rather than make a new one.
7538
#[test]
7539
fn git_import_brings_a_directory_back_rather_than_making_a_second() {
7540
    hermetic();
7541
    if std::process::Command::new("git")
7542
        .arg("--version")
7543
        .output()
7544
        .is_err()
7545
    {
7546
        eprintln!("git not installed; skipping");
7547
        return;
7548
    }
7549
    let dir = tempfile::tempdir().unwrap();
7550
    let root = dir.path();
7551
    let g = root.join("src.git");
7552
    fs::create_dir_all(&g).unwrap();
7553
    let git = |args: &[&str]| -> String {
7554
        let out = std::process::Command::new("git")
7555
            .arg("-C")
7556
            .arg(&g)
7557
            .args([
7558
                "-c",
7559
                "user.name=Grace",
7560
                "-c",
7561
                "[email protected]",
7562
                "-c",
7563
                "commit.gpgsign=false",
7564
            ])
7565
            .args(args)
7566
            .output()
7567
            .unwrap();
7568
        assert!(
7569
            out.status.success(),
7570
            "git {args:?}: {}",
7571
            String::from_utf8_lossy(&out.stderr)
7572
        );
7573
        String::from_utf8_lossy(&out.stdout).trim().to_string()
7574
    };
7575
    git(&["init", "-q", "-b", "main"]);
7576
    write(&g, "d/a.txt", b"a\n");
7577
    write(&g, "c/x.txt", b"x\n");
7578
    git(&["add", "."]);
7579
    git(&["commit", "-qm", "base"]);
7580
    // One line: move x into d while d still stands.
7581
    git(&["checkout", "-qb", "side"]);
7582
    git(&["mv", "c/x.txt", "d/x.txt"]);
7583
    git(&["commit", "-qm", "x into d"]);
7584
    // The other: d goes, comes back, and x moves into it too.
7585
    git(&["checkout", "-q", "main"]);
7586
    git(&["rm", "-q", "d/a.txt"]);
7587
    git(&["commit", "-qm", "d goes"]);
7588
    write(&g, "d/b.txt", b"b\n");
7589
    git(&["add", "."]);
7590
    git(&["commit", "-qm", "d comes back"]);
7591
    git(&["mv", "c/x.txt", "d/x.txt"]);
7592
    git(&["commit", "-qm", "x into d again"]);
7593
    git(&["merge", "-q", "--no-edit", "side"]);
7594
7595
    let repo = Repo::init(&root.join("o")).unwrap();
7596
    repo.import_git(&g, "main").unwrap();
7597
    let v = repo.verify_git_import(&g, "main").unwrap();
7598
    assert!(v.mismatches.is_empty(), "{:?}", v.mismatches);
7599
    let st = repo
7600
        .load_state_history(&repo.bookmark_heads().unwrap())
7601
        .unwrap();
7602
    let view = st.tree().view();
7603
    assert!(view.conflicts.is_empty(), "{:?}", view.conflicts);
7604
    // The directory is the one the first commit made.
7605
    // Commits made in one second tie on time: find the first by its message.
7606
    let first = repo
7607
        .log()
7608
        .unwrap()
7609
        .into_iter()
7610
        .find(|e| e.change.message.starts_with("base"))
7611
        .unwrap();
7612
    let base = repo
7613
        .load_state_history(&[first.hash])
7614
        .unwrap()
7615
        .tree()
7616
        .view();
7617
    assert_eq!(view.entries["d"].node, base.entries["d"].node);
7618
}
7619
7620
/// oxygen#30, the rest: a placement left under a directory another line
7621
/// removed is out of sight, so no diff reaches it; the merge that settles
7622
/// where the file is retires it.
7623
#[test]
7624
fn git_import_merge_retires_a_placement_under_a_removed_directory() {
7625
    hermetic();
7626
    if std::process::Command::new("git")
7627
        .arg("--version")
7628
        .output()
7629
        .is_err()
7630
    {
7631
        eprintln!("git not installed; skipping");
7632
        return;
7633
    }
7634
    let dir = tempfile::tempdir().unwrap();
7635
    let root = dir.path();
7636
    let g = root.join("src.git");
7637
    fs::create_dir_all(&g).unwrap();
7638
    let run = |args: &[&str]| {
7639
        std::process::Command::new("git")
7640
            .arg("-C")
7641
            .arg(&g)
7642
            .args([
7643
                "-c",
7644
                "user.name=Grace",
7645
                "-c",
7646
                "[email protected]",
7647
                "-c",
7648
                "commit.gpgsign=false",
7649
            ])
7650
            .args(args)
7651
            .output()
7652
            .unwrap()
7653
    };
7654
    let git = |args: &[&str]| {
7655
        let out = run(args);
7656
        assert!(
7657
            out.status.success(),
7658
            "git {args:?}: {}",
7659
            String::from_utf8_lossy(&out.stderr)
7660
        );
7661
    };
7662
    git(&["init", "-q", "-b", "main"]);
7663
    write(&g, "c/x.txt", b"x\n");
7664
    write(&g, "keep.txt", b"k\n");
7665
    git(&["add", "."]);
7666
    git(&["commit", "-qm", "base"]);
7667
    // One line renames the file within c; the other moves it out of c,
7668
    // which goes.
7669
    git(&["checkout", "-qb", "side"]);
7670
    git(&["mv", "c/x.txt", "c/y.txt"]);
7671
    git(&["commit", "-qm", "rename within c"]);
7672
    git(&["checkout", "-q", "main"]);
7673
    fs::create_dir_all(g.join("n")).unwrap();
7674
    git(&["mv", "c/x.txt", "n/x.txt"]);
7675
    git(&["commit", "-qm", "move out of c"]);
7676
    // Git cannot merge the two renames; the merge keeps n/x.txt.
7677
    let _ = run(&["merge", "-q", "side"]);
7678
    let _ = run(&[
7679
        "rm",
7680
        "-q",
7681
        "--cached",
7682
        "--ignore-unmatch",
7683
        "c/y.txt",
7684
        "c/x.txt",
7685
    ]);
7686
    let _ = std::fs::remove_dir_all(g.join("c"));
7687
    write(&g, "n/x.txt", b"x\n");
7688
    git(&["add", "-A"]);
7689
    git(&["commit", "-qm", "merge: keep n/x.txt"]);
7690
7691
    let repo = Repo::init(&root.join("o")).unwrap();
7692
    repo.import_git(&g, "main").unwrap();
7693
    let v = repo.verify_git_import(&g, "main").unwrap();
7694
    assert!(v.mismatches.is_empty(), "{:?}", v.mismatches);
7695
    let st = repo
7696
        .load_state_history(&repo.bookmark_heads().unwrap())
7697
        .unwrap();
7698
    let view = st.tree().view();
7699
    assert!(view.conflicts.is_empty(), "{:?}", view.conflicts);
7700
    assert!(view.entries.contains_key("n/x.txt"));
7701
}
7702
7703
/// oxygen#30, orphans: a file added on one line into a directory the other
7704
/// line removed is placed where the tree cannot show it; Git's merge keeps
7705
/// the file, and the import's merge leaves exactly one of it.
7706
#[test]
7707
fn git_import_merge_leaves_no_orphan_behind() {
7708
    hermetic();
7709
    if std::process::Command::new("git")
7710
        .arg("--version")
7711
        .output()
7712
        .is_err()
7713
    {
7714
        eprintln!("git not installed; skipping");
7715
        return;
7716
    }
7717
    let dir = tempfile::tempdir().unwrap();
7718
    let root = dir.path();
7719
    let g = root.join("src.git");
7720
    fs::create_dir_all(&g).unwrap();
7721
    let git = |args: &[&str]| {
7722
        let out = std::process::Command::new("git")
7723
            .arg("-C")
7724
            .arg(&g)
7725
            .args([
7726
                "-c",
7727
                "user.name=Grace",
7728
                "-c",
7729
                "[email protected]",
7730
                "-c",
7731
                "commit.gpgsign=false",
7732
            ])
7733
            .args(args)
7734
            .output()
7735
            .unwrap();
7736
        assert!(
7737
            out.status.success(),
7738
            "git {args:?}: {}",
7739
            String::from_utf8_lossy(&out.stderr)
7740
        );
7741
    };
7742
    git(&["init", "-q", "-b", "main"]);
7743
    write(&g, "d/f.txt", b"f\n");
7744
    write(&g, "keep.txt", b"k\n");
7745
    git(&["add", "."]);
7746
    git(&["commit", "-qm", "base"]);
7747
    git(&["checkout", "-qb", "side"]);
7748
    write(&g, "d/new.txt", b"new\n");
7749
    git(&["add", "."]);
7750
    git(&["commit", "-qm", "add into d"]);
7751
    git(&["checkout", "-q", "main"]);
7752
    git(&["rm", "-q", "d/f.txt"]);
7753
    git(&["commit", "-qm", "d goes"]);
7754
    git(&["merge", "-q", "--no-edit", "side"]);
7755
7756
    let repo = Repo::init(&root.join("o")).unwrap();
7757
    repo.import_git(&g, "main").unwrap();
7758
    let v = repo.verify_git_import(&g, "main").unwrap();
7759
    assert!(v.mismatches.is_empty(), "{:?}", v.mismatches);
7760
    let st = repo
7761
        .load_state_history(&repo.bookmark_heads().unwrap())
7762
        .unwrap();
7763
    let view = st.tree().view();
7764
    assert!(view.conflicts.is_empty(), "{:?}", view.conflicts);
7765
    assert!(view.entries.contains_key("d/new.txt"));
7766
}
7767
7768
/// fsck checks a change's text as the blobs it is stored in, without
7769
/// decoding it: a missing text blob is an error named for the change.
7770
#[test]
7771
fn fsck_names_a_missing_text_blob() {
7772
    hermetic();
7773
    let dir = tempfile::tempdir().unwrap();
7774
    let root = dir.path();
7775
    let repo = Repo::init(root).unwrap();
7776
    let big: String = (0..3000).map(|i| format!("line {i}\n")).collect();
7777
    write(root, "big.txt", big.as_bytes());
7778
    let h = repo.commit("big", &[]).unwrap();
7779
    assert_eq!(repo.fsck().unwrap().errors(), 0);
7780
    let (_, texts) = repo.store().get_change_lazy(&h).unwrap();
7781
    let Some(crate::objects::TextRef::Blob(b, _, _)) = texts.first().copied() else {
7782
        panic!("a stored text")
7783
    };
7784
    repo.store().remove_loose_for_test(&b).unwrap();
7785
    let rep = repo.fsck().unwrap();
7786
    assert!(rep.errors() > 0);
7787
    assert!(
7788
        rep.problems.iter().any(|p| p.what.contains(&h.short(12))),
7789
        "{:?}",
7790
        rep.problems
7791
    );
7792
}
7793
7794
/// oxygen#32: a subrepo on the same hub as one of the parent's remotes is
7795
/// reached with that remote's token and CA (a private subrepo then clones
7796
/// for anyone who can read the parent); another hub gets none of them.
7797
#[test]
7798
fn a_subrepo_on_the_parents_hub_borrows_its_credentials() {
7799
    hermetic();
7800
    let dir = tempfile::tempdir().unwrap();
7801
    let mut repo = Repo::init(dir.path()).unwrap();
7802
    repo.config
7803
        .set(
7804
            "remote.origin.url",
7805
            "https://Hub.example:7343/doomsdayone/metalgear",
7806
        )
7807
        .unwrap();
7808
    repo.config.set("remote.origin.token", "secret").unwrap();
7809
    repo.config
7810
        .set("remote.origin.ca", "/tmp/hub-ca.pem")
7811
        .unwrap();
7812
    let same = repo.credentials_for("https://hub.example:7343/doomsdayone/rstar-api");
7813
    assert_eq!(same.token.as_deref(), Some("secret"));
7814
    assert_eq!(same.ca.as_deref(), Some(Path::new("/tmp/hub-ca.pem")));
7815
    for other in [
7816
        "https://elsewhere.example:7343/doomsdayone/rstar-api",
7817
        "https://hub.example/doomsdayone/rstar-api",
7818
        "http://hub.example:7343/doomsdayone/rstar-api",
7819
    ] {
7820
        let o = repo.credentials_for(other);
7821
        assert_ne!(o.token.as_deref(), Some("secret"), "{other}");
7822
    }
7823
}
7824
7825
/// oxygen#47: a remote with no token of its own uses the user's credential
7826
/// store for its hub, and a nested checkout finds its parent's remote
7827
/// token there instead of keeping a copy.
7828
#[test]
7829
fn remotes_use_the_credential_store_and_the_enclosing_checkout() {
7830
    hermetic();
7831
    let home = tempfile::tempdir().unwrap();
7832
    let dir = tempfile::tempdir().unwrap();
7833
    let mut parent = Repo::init(dir.path()).unwrap().with_home(home.path());
7834
    parent
7835
        .config
7836
        .set("remote.origin.url", "https://hub.example/o/parent")
7837
        .unwrap();
7838
    parent.save_config().unwrap();
7839
    assert_eq!(parent.remote_options("origin").token, None);
7840
    crate::credentials::Credentials::at(home.path())
7841
        .save("https://hub.example", "stored", Some("andy"), None)
7842
        .unwrap();
7843
    assert_eq!(
7844
        parent.remote_options("origin").token.as_deref(),
7845
        Some("stored")
7846
    );
7847
7848
    let empty_home = tempfile::tempdir().unwrap();
7849
    let nested = dir.path().join("deps").join("child");
7850
    let mut child = Repo::init(&nested).unwrap().with_home(empty_home.path());
7851
    child
7852
        .config
7853
        .set("remote.origin.url", "https://hub.example/o/child")
7854
        .unwrap();
7855
    child.save_config().unwrap();
7856
    assert_eq!(child.remote_options("origin").token, None);
7857
    parent
7858
        .config
7859
        .set("remote.origin.token", "checkout")
7860
        .unwrap();
7861
    parent.save_config().unwrap();
7862
    assert_eq!(
7863
        child.remote_options("origin").token.as_deref(),
7864
        Some("checkout")
7865
    );
7866
    // Another hub's checkout token is not borrowed.
7867
    child
7868
        .config
7869
        .set("remote.origin.url", "https://other.example/o/child")
7870
        .unwrap();
7871
    assert_eq!(child.remote_options("origin").token, None);
7872
}
7873
7874
#[test]
7875
fn the_metadata_cache_survives_a_torn_tail() {
7876
    hermetic();
7877
    let dir = tempfile::tempdir().unwrap();
7878
    let root = dir.path();
7879
    let repo = Repo::init(root).unwrap();
7880
    write(root, "a.txt", b"1\n");
7881
    let h = repo.commit("first", &[]).unwrap();
7882
    let meta = repo.store().get_change_meta(&h).unwrap();
7883
    let cache = repo.store().dir().join("metas");
7884
    let len = fs::metadata(&cache).unwrap().len();
7885
    assert!(len > 0, "a change read is cached");
7886
    // A torn record at the end: the cache reads up to it and cuts it off.
7887
    fs::OpenOptions::new()
7888
        .append(true)
7889
        .open(&cache)
7890
        .unwrap()
7891
        .write_all(&[7; 20])
7892
        .unwrap();
7893
    let again = Repo::open(root).unwrap();
7894
    assert_eq!(again.store().get_change_meta(&h).unwrap(), meta);
7895
    assert_eq!(fs::metadata(&cache).unwrap().len(), len);
7896
}
7897
7898
#[test]
7899
fn a_manifest_that_does_not_check_reads_as_none() {
7900
    hermetic();
7901
    let dir = tempfile::tempdir().unwrap();
7902
    let root = dir.path();
7903
    let repo = Repo::init(root).unwrap();
7904
    write(root, "a.txt", b"1\n");
7905
    repo.commit("first", &[]).unwrap();
7906
    let path = repo.manifest_path();
7907
    let mut bytes = fs::read(&path).unwrap();
7908
    assert!(Repo::open(root).unwrap().read_manifest().unwrap().is_some());
7909
    let last = bytes.len() - 1;
7910
    bytes[last] ^= 1;
7911
    fs::write(&path, &bytes).unwrap();
7912
    assert!(Repo::open(root).unwrap().read_manifest().unwrap().is_none());
7913
    // The next status reads the files and writes it again.
7914
    let again = Repo::open(root).unwrap();
7915
    assert!(!again.snapshot("status").unwrap().changed);
7916
    assert!(again.read_manifest().unwrap().is_some());
7917
}
7918
7919
#[test]
7920
fn a_commit_leaves_a_manifest_that_proves_the_working_copy_clean() {
7921
    hermetic();
7922
    let dir = tempfile::tempdir().unwrap();
7923
    let root = dir.path();
7924
    let repo = Repo::init(root).unwrap();
7925
    write(root, "a.txt", b"1\n");
7926
    write(root, "b.txt", b"2\n");
7927
    // b.txt outside the racy window, so snapshots take it as unchanged.
7928
    let old = std::time::SystemTime::now() - std::time::Duration::from_secs(60);
7929
    fs::File::options()
7930
        .write(true)
7931
        .open(root.join("b.txt"))
7932
        .unwrap()
7933
        .set_modified(old)
7934
        .unwrap();
7935
    repo.commit("first", &[]).unwrap();
7936
    assert!(repo.clean_by_manifest().unwrap(), "after the first commit");
7937
    repo.snapshot_status("status").unwrap();
7938
    write(root, "a.txt", b"1\n2\n");
7939
    repo.commit("second", &[]).unwrap();
7940
    assert!(
7941
        repo.clean_by_manifest().unwrap(),
7942
        "after a commit of one file"
7943
    );
7944
    // Edited, seen by a status, edited again, then committed: the status
7945
    // left the first edit's stat, which the commit must not keep.
7946
    write(root, "a.txt", b"1\n2\n3\n");
7947
    repo.snapshot_status("status").unwrap();
7948
    write(root, "a.txt", b"1\n2\n3\n4\n5\n");
7949
    repo.commit("third", &[]).unwrap();
7950
    assert!(
7951
        repo.clean_by_manifest().unwrap(),
7952
        "after an edit a status saw"
7953
    );
7954
}
7955
7956
#[test]
7957
fn a_conflicted_rebase_can_be_resolved_in_the_working_copy() {
7958
    hermetic();
7959
    let dir = tempfile::tempdir().unwrap();
7960
    let root = dir.path();
7961
    let mut repo = Repo::init(root).unwrap().with_home(root.join("home"));
7962
    write(root, "a.txt", b"1\n2\n");
7963
    let a = repo.commit("A", &[]).unwrap();
7964
    repo.bookmark_create("develop", Some(&[a])).unwrap();
7965
    write(root, "a.txt", b"1\nX\n");
7966
    let c = repo.commit("C: 2 to X", &[]).unwrap();
7967
    repo.bookmark_switch("develop", false).unwrap();
7968
    write(root, "a.txt", b"1\nY\n");
7969
    let d = repo.commit("D: 2 to Y", &[]).unwrap();
7970
    repo.bookmark_switch("main", false).unwrap();
7971
7972
    let err = repo.rebase(&c, &[d]).unwrap_err();
7973
    assert!(matches!(err, RepoError::Conflicted(_)), "{err}");
7974
    let r = repo.rebase_into_working_copy(&c, &[d]).unwrap();
7975
    assert!(r.changed && r.checked_out);
7976
    let snap = repo.snapshot_status("status").unwrap();
7977
    assert!(
7978
        snap.base_snapshot.is_conflicted(),
7979
        "the conflict is in the working copy"
7980
    );
7981
    let text = fs::read_to_string(root.join("a.txt")).unwrap();
7982
    assert!(text.contains('X') && text.contains('Y'), "{text}");
7983
7984
    write(root, "a.txt", b"1\nXY\n");
7985
    repo.commit("Resolve", &[]).unwrap();
7986
    let st = repo.load_state(&repo.bookmark_heads().unwrap()).unwrap();
7987
    assert!(st.contains(&c) && st.contains(&d));
7988
    let files = st.materialize().files;
7989
    assert!(!files["a.txt"].is_conflicted());
7990
    assert!(
7991
        matches!(&files["a.txt"].content, FileContent::Text { bytes, .. } if bytes == b"1\nXY\n")
7992
    );
7993
7994
    // A change the current bookmark does not hold is refused.
7995
    repo.bookmark_switch("develop", false).unwrap();
7996
    write(root, "b.txt", b"b\n");
7997
    let e = repo.commit("E", &[]).unwrap();
7998
    repo.bookmark_switch("main", false).unwrap();
7999
    let err = repo.rebase_into_working_copy(&e, &[a]).unwrap_err();
8000
    assert!(
8001
        err.to_string().contains("not on the current bookmark"),
8002
        "{err}"
8003
    );
8004
}
8005
8006
#[test]
8007
fn an_ignore_rule_drops_an_added_file_but_not_a_tracked_one() {
8008
    hermetic();
8009
    let dir = tempfile::tempdir().unwrap();
8010
    let root = dir.path();
8011
    let repo = Repo::init(root).unwrap();
8012
    write(root, "a.txt", b"a\n");
8013
    write(root, "kept.log", b"tracked\n");
8014
    repo.commit("first", &[]).unwrap();
8015
    write(root, "build.log", b"made\n");
8016
    let snap = repo.snapshot_status("status").unwrap();
8017
    assert!(snap.statuses.iter().any(|s| s.path == "build.log"));
8018
    // A rule written afterwards leaves the added file out again, while the
8019
    // committed one stays tracked.
8020
    write(root, ".gitignore", b"*.log\n");
8021
    let snap = repo.snapshot_status("status").unwrap();
8022
    let paths: Vec<&str> = snap.statuses.iter().map(|s| s.path.as_str()).collect();
8023
    assert_eq!(paths, vec![".gitignore"], "{paths:?}");
8024
    write(root, "kept.log", b"tracked, edited\n");
8025
    let snap = repo.snapshot_status("status").unwrap();
8026
    assert!(snap.statuses.iter().any(|s| s.path == "kept.log"));
8027
}
8028
8029
#[test]
8030
fn shed_graphs_come_back_the_same() {
8031
    hermetic();
8032
    let dir = tempfile::tempdir().unwrap();
8033
    let root = dir.path();
8034
    let repo = Repo::init(root).unwrap();
8035
    write(root, "a.txt", b"1\n2\n3\n");
8036
    write(root, "b.txt", b"x\n");
8037
    repo.commit("first", &[]).unwrap();
8038
    write(root, "a.txt", b"1\ntwo\n3\n4\n");
8039
    repo.commit("second", &[]).unwrap();
8040
    let heads = repo.bookmark_heads().unwrap();
8041
    let mut st = repo.load_state_history(&heads).unwrap();
8042
    let view = st.tree().view();
8043
    let nodes: Vec<NodeId> = ["a.txt", "b.txt"]
8044
        .iter()
8045
        .map(|p| view.entries[*p].node)
8046
        .collect();
8047
    repo.load_graphs_of(&mut st, &nodes).unwrap();
8048
    let before: Vec<Vec<u8>> = nodes.iter().map(|n| st.render_file(n).0).collect();
8049
    assert_eq!(st.built_count(), 2);
8050
    let shed = st.shed_graphs(|b| repo.store_blob(b)).unwrap();
8051
    assert_eq!((shed, st.built_count()), (2, 0));
8052
    // A later change applies on top of the shed history.
8053
    write(root, "a.txt", b"1\ntwo\n3\n4\n5\n");
8054
    let h3 = repo.commit("third", &[]).unwrap();
8055
    let (skeleton, texts) = repo.store().get_change_lazy(&h3).unwrap();
8056
    st.add_known(h3, skeleton, texts);
8057
    repo.load_graphs_of(&mut st, &nodes).unwrap();
8058
    let after: Vec<Vec<u8>> = nodes.iter().map(|n| st.render_file(n).0).collect();
8059
    assert_eq!(after[1], before[1]);
8060
    assert_eq!(after[0], b"1\ntwo\n3\n4\n5\n");
8061
}
8062
8063
#[test]
8064
fn many_edited_files_diff_in_parallel() {
8065
    // Enough edited files that the builder diffs them in parallel; the
8066
    // commit must hold exactly what is on disk, and a second snapshot
8067
    // must find nothing left to commit.
8068
    hermetic();
8069
    let dir = tempfile::tempdir().unwrap();
8070
    let root = dir.path();
8071
    let repo = Repo::init(root).unwrap();
8072
    let text = |i: usize, round: usize| {
8073
        let mut s = String::new();
8074
        for line in 0..50 {
8075
            if round > 0 && line % 7 == i % 7 {
8076
                s.push_str(&format!("edited {round} {i} {line}\n"));
8077
            } else {
8078
                s.push_str(&format!("file {i} line {line}\n"));
8079
            }
8080
        }
8081
        if round > 0 && i.is_multiple_of(3) {
8082
            s.push_str("appended\n");
8083
        }
8084
        s
8085
    };
8086
    for i in 0..40 {
8087
        write(root, &format!("d/f{i}.txt"), text(i, 0).as_bytes());
8088
    }
8089
    repo.commit("first", &[]).unwrap();
8090
    for i in 0..40 {
8091
        write(root, &format!("d/f{i}.txt"), text(i, 1).as_bytes());
8092
    }
8093
    let h = repo.commit("edit every file", &[]).unwrap();
8094
    let snap = repo.load_state(&[h]).unwrap().materialize();
8095
    for i in 0..40 {
8096
        let want = text(i, 1);
8097
        assert!(
8098
            matches!(&snap.files[&format!("d/f{i}.txt")].content, FileContent::Text { bytes, .. } if bytes == want.as_bytes()),
8099
            "d/f{i}.txt as committed"
8100
        );
8101
    }
8102
    assert!(
8103
        repo.commit("nothing", &[]).is_err(),
8104
        "nothing left to commit"
8105
    );
8106
}
8107
8108
/// oxygen#56: after a fetch, how a bookmark stands against its remote copy
8109
/// is known (fetch printed "up to date" while main was behind), a change
8110
/// only fetched resolves and says where it is, and a checkout whose only
8111
/// remote is not `origin` uses that one.
8112
#[test]
8113
fn a_fetched_change_shows_as_behind_and_resolves() {
8114
    hermetic();
8115
    let dir = tempfile::tempdir().unwrap();
8116
    let root = dir.path();
8117
    let origin = Repo::init(&root.join("origin")).unwrap();
8118
    drop(origin);
8119
    let url = root.join("origin").to_string_lossy().to_string();
8120
    let a = Repo::clone(&url, &root.join("a"))
8121
        .unwrap()
8122
        .with_home(root.join("home-a"));
8123
    write(&root.join("a"), "f.txt", b"one\n");
8124
    a.commit("one", &[]).unwrap();
8125
    a.push("origin", false).unwrap();
8126
    let b = Repo::clone(&url, &root.join("b"))
8127
        .unwrap()
8128
        .with_home(root.join("home-b"));
8129
    assert_eq!(b.tracking("origin", "main").unwrap(), Some((0, 0)));
8130
8131
    write(&root.join("a"), "f.txt", b"one\ntwo\n");
8132
    let h2 = a.commit("two", &[]).unwrap();
8133
    a.push("origin", false).unwrap();
8134
    b.fetch("origin").unwrap();
8135
    // Fetched, not pulled: one behind, the change found and placed.
8136
    assert_eq!(b.tracking("origin", "main").unwrap(), Some((0, 1)));
8137
    assert_eq!(b.tracking("origin", "nope").unwrap(), None);
8138
    assert_eq!(
8139
        b.resolve_change(&format!("#{}", &h2.to_hex()[..12]))
8140
            .unwrap(),
8141
        h2
8142
    );
8143
    assert_eq!(
8144
        b.remote_only_location(&h2).unwrap().as_deref(),
8145
        Some("origin/main")
8146
    );
8147
    // Fetching again changes nothing: still behind, which is what the
8148
    // CLI now says rather than "up to date".
8149
    b.fetch("origin").unwrap();
8150
    assert_eq!(b.tracking("origin", "main").unwrap(), Some((0, 1)));
8151
    b.pull("origin").unwrap();
8152
    assert_eq!(b.tracking("origin", "main").unwrap(), Some((0, 0)));
8153
    assert_eq!(b.remote_only_location(&h2).unwrap(), None);
8154
8155
    // One remote, not called origin: it is the default.
8156
    let mut c = Repo::init(&root.join("c")).unwrap();
8157
    assert_eq!(c.default_remote(), "origin");
8158
    c.config.set("remote.earth.url", &url).unwrap();
8159
    assert_eq!(c.default_remote(), "earth");
8160
    c.config.set("remote.origin.url", &url).unwrap();
8161
    assert_eq!(c.default_remote(), "origin");
8162
}
8163
8164
/// oxygen#57: a clone from a relative local path records the remote as an
8165
/// absolute path, so fetch still finds it from inside the clone.
8166
#[test]
8167
fn a_clone_from_a_relative_path_records_it_absolute() {
8168
    hermetic();
8169
    let dir = tempfile::tempdir().unwrap();
8170
    let root = dir.path();
8171
    Repo::init(&root.join("origin")).unwrap();
8172
    let rel = crate::protocol::stored_url("relative/repo");
8173
    assert!(std::path::Path::new(&rel).is_absolute(), "{rel}");
8174
    assert_eq!(
8175
        crate::protocol::stored_url("https://hub.example/o/n"),
8176
        "https://hub.example/o/n"
8177
    );
8178
    assert!(crate::protocol::stored_url("file://x").starts_with("file:///"));
8179
    assert!(crate::protocol::stored_url("dir://x").starts_with("dir:///"));
8180
    // A bucket is kept as written: it is not a path.
8181
    assert_eq!(
8182
        crate::protocol::stored_url("s3://bucket/prefix?profile=p"),
8183
        "s3://bucket/prefix?profile=p"
8184
    );
8185
    let url = root.join("origin").to_string_lossy().to_string();
8186
    let b = Repo::clone(&url, &root.join("b")).unwrap();
8187
    assert_eq!(b.config.remotes["origin"], url);
8188
    b.fetch("origin").unwrap();
8189
}
8190
8191
/// oxygen#60 and #61: a workspace added on a bookmark is on that bookmark,
8192
/// and gets its subrepos at their pins from this workspace's copies, with
8193
/// their remotes pointing where the subrepos come from.
8194
#[test]
8195
fn a_workspace_added_on_a_bookmark_is_on_it_with_its_subrepos() {
8196
    hermetic();
8197
    let dir = tempfile::tempdir().unwrap();
8198
    let root = dir.path();
8199
    Repo::init(&root.join("lib-origin")).unwrap();
8200
    let lib_url = root.join("lib-origin").to_string_lossy().to_string();
8201
    let lib = Repo::clone(&lib_url, &root.join("lib"))
8202
        .unwrap()
8203
        .with_home(root.join("home"));
8204
    write(&root.join("lib"), "lib.txt", b"v1\n");
8205
    let l1 = lib.commit("lib v1", &[]).unwrap();
8206
    assert!(lib.push("origin", false).unwrap()[0].ok);
8207
8208
    let app_dir = root.join("app");
8209
    let app = Repo::init(&app_dir).unwrap().with_home(root.join("home"));
8210
    write(&app_dir, "main.txt", b"app\n");
8211
    app.submodule_add(&lib_url, "libs/lib", None).unwrap();
8212
    app.commit("app with lib", &[]).unwrap();
8213
    // A second bookmark, and the main workspace on another.
8214
    app.bookmark_create("develop", None).unwrap();
8215
    app.bookmark_create("feature", None).unwrap();
8216
    let mut app = app;
8217
    app.bookmark_switch("feature", false).unwrap();
8218
    assert_eq!(app.config.bookmark, "feature");
8219
8220
    // The library's origin goes away: the subrepo must come from here.
8221
    std::fs::rename(root.join("lib-origin"), root.join("lib-origin-gone")).unwrap();
8222
    let heads = app.resolve_heads("develop").unwrap();
8223
    let ws = app
8224
        .workspace_add_on(&root.join("ws"), Some(&heads), Some("develop"))
8225
        .unwrap();
8226
    assert_eq!(
8227
        ws.config.bookmark, "develop",
8228
        "the new workspace is on develop"
8229
    );
8230
    assert_eq!(
8231
        app.config.bookmark, "feature",
8232
        "and this one stays on its own"
8233
    );
8234
    let sub = Repo::open(&root.join("ws/libs/lib")).unwrap();
8235
    assert_eq!(
8236
        sub.config.remotes["origin"], lib_url,
8237
        "its origin is the subrepo's URL"
8238
    );
8239
    assert_eq!(sub.bookmark_heads().unwrap(), vec![l1], "at its pin");
8240
    assert_eq!(
8241
        std::fs::read(root.join("ws/libs/lib/lib.txt")).unwrap(),
8242
        b"v1\n"
8243
    );
8244
}
8245
8246
/// Revsets (docs/revset_query_language.md): symbols, relations, set
8247
/// operators and the predicates, over a small graph with two heads and
8248
/// a rename.
8249
#[test]
8250
fn revsets_select_changes_by_relation_author_text_date_and_path() {
8251
    hermetic();
8252
    let dir = tempfile::tempdir().unwrap();
8253
    let root = dir.path();
8254
    let mut repo = Repo::init(root).unwrap().with_home(root.join("home"));
8255
    repo.create_identity("Ada", "[email protected]", IdentityScope::User)
8256
        .unwrap();
8257
    write(root, "src/a.rs", b"one\n");
8258
    let a = repo.commit("first: add a", &[]).unwrap();
8259
    write(root, "src/a.rs", b"one\ntwo\n");
8260
    let b = repo.commit("second: grow a", &[]).unwrap();
8261
    // A second head, independent of b: a new file on top of a.
8262
    repo.checkout(&[a], false, "checkout a").unwrap();
8263
    write(root, "docs/notes.md", b"notes\n");
8264
    let c = repo.commit("third: notes", &[]).unwrap();
8265
    // Back to both heads, then rename a.rs: the node keeps its identity.
8266
    repo.checkout(&repo.bookmark_heads().unwrap(), false, "checkout main")
8267
        .unwrap();
8268
    fs::remove_file(root.join("src/a.rs")).unwrap();
8269
    write(root, "src/z.rs", b"one\ntwo\n");
8270
    let d = repo.commit("fourth: rename a to z", &[]).unwrap();
8271
    let wc = repo.working_copy().unwrap().0;
8272
    // A saved revset is checked when set.
8273
    repo.set_user_config("revset.mine", "author(me) & ::main")
8274
        .unwrap();
8275
    assert!(repo.set_user_config("revset.bad", "a &").is_err());
8276
    let set = |src: &str| -> Vec<ChangeHash> {
8277
        let mut v = repo.revset(src).unwrap().hashes;
8278
        v.sort();
8279
        v
8280
    };
8281
    let sorted = |hs: &[ChangeHash]| -> Vec<ChangeHash> {
8282
        let mut v = hs.to_vec();
8283
        v.sort();
8284
        v
8285
    };
8286
8287
    // Changes commute: a new file depends on nothing and the rename on the
8288
    // file's creation, so the graph is a, b->a, d->a, c, and the working
8289
    // copy on the three heads b, c, d.
8290
    let heads = sorted(&repo.bookmark_heads().unwrap());
8291
    let meta = |h: &ChangeHash| repo.store().get_change_meta(h).unwrap();
8292
    assert!(heads.contains(&d) && heads.contains(&c));
8293
    // Symbols and closures.
8294
    assert_eq!(set("main"), heads);
8295
    assert_eq!(set("::main"), sorted(&[a, b, c, d]));
8296
    assert_eq!(set("@"), vec![wc]);
8297
    assert_eq!(set("::@"), sorted(&[a, b, c, d, wc]));
8298
    assert_eq!(set(&format!("::#{}", b.short(12))), sorted(&[a, b]));
8299
    assert_eq!(set(&format!("#{}::", a.short(12))), sorted(&[a, b, d, wc]));
8300
    assert_eq!(
8301
        set(&format!("#{}::#{}", a.short(12), b.short(12))),
8302
        sorted(&[a, b])
8303
    );
8304
    // Ranges: what main has beyond b, and `..` forms.
8305
    assert_eq!(set(&format!("#{}..main", b.short(12))), sorted(&[c, d]));
8306
    assert_eq!(set(&format!("#{}..", c.short(12))), sorted(&[a, b, d, wc]));
8307
    assert_eq!(set("..main"), sorted(&[a, b, c, d]));
8308
    // Operators and precedence: ~ binds tighter than &, & than |.
8309
    assert_eq!(
8310
        set(&format!("::main ~ #{}", d.short(12))),
8311
        sorted(&[a, b, c])
8312
    );
8313
    assert_eq!(
8314
        set(&format!("::main & #{} | #{}", b.short(12), c.short(12))),
8315
        sorted(&[b, c])
8316
    );
8317
    assert_eq!(set("all() ~ ::main"), vec![wc]);
8318
    // Relations.
8319
    let mut head_deps: Vec<ChangeHash> = heads.iter().flat_map(|h| meta(h).deps).collect();
8320
    head_deps.sort();
8321
    head_deps.dedup();
8322
    assert_eq!(set("deps(main)"), head_deps);
8323
    let on_a: Vec<ChangeHash> = [b, c, d]
8324
        .into_iter()
8325
        .filter(|h| meta(h).deps.contains(&a))
8326
        .collect();
8327
    assert_eq!(set(&format!("dependents(#{})", a.short(12))), sorted(&on_a));
8328
    assert_eq!(set("heads(::main)"), heads);
8329
    assert_eq!(set("roots(::main)"), sorted(&[a, c]));
8330
    assert_eq!(
8331
        set(&format!(
8332
            "heads(#{} | #{} | #{})",
8333
            a.short(12),
8334
            b.short(12),
8335
            c.short(12)
8336
        )),
8337
        sorted(&[b, c])
8338
    );
8339
    assert_eq!(set("latest(::main, 1)"), vec![d]);
8340
    assert_eq!(set("kind(working-copy)"), vec![wc]);
8341
    assert_eq!(set("none()"), vec![]);
8342
    // Predicates: author by name, email, key prefix and `me`.
8343
    let key = repo.config.author_key.unwrap();
8344
    assert_eq!(set("author(ada) & ::main"), sorted(&[a, b, c, d]));
8345
    assert_eq!(set("author(\"[email protected]\") & ::main").len(), 4);
8346
    assert_eq!(set(&format!("author({}) & ::main", key.short(12))).len(), 4);
8347
    assert_eq!(set("author(me) & ::main").len(), 4);
8348
    assert_eq!(set("author(nobody)"), vec![]);
8349
    assert_eq!(set("description(notes)"), vec![c]);
8350
    assert_eq!(set("description(\"rename a\")"), vec![d]);
8351
    assert_eq!(set("date(-1h..) & ::main").len(), 4);
8352
    assert_eq!(set("date(..2000-01-01)"), vec![]);
8353
    // touches follows the node through the rename, in the current state.
8354
    assert_eq!(set("touches(\"src/z.rs\")"), sorted(&[a, b, d]));
8355
    assert_eq!(set("touches(\"src/**\") & ::main"), sorted(&[a, b, d]));
8356
    assert_eq!(set("touches(\"docs/*\")"), vec![c]);
8357
    assert_eq!(set("touches(\"nothing/*\")"), vec![]);
8358
    // Newest first in the result order.
8359
    assert_eq!(repo.revset("::main").unwrap().hashes[0], d);
8360
    // The saved revset, and errors that say what is wrong.
8361
    assert_eq!(set("mine()").len(), 4);
8362
    let e = repo.revset("nosuch()").unwrap_err().to_string();
8363
    assert!(e.contains("unknown function nosuch()"), "{e}");
8364
    let e = repo.revset("main &").unwrap_err().to_string();
8365
    assert!(e.contains("at character"), "{e}");
8366
    let e = repo.revset("zzzz").unwrap_err().to_string();
8367
    assert!(e.contains("no change matches"), "{e}");
8368
    let e = repo
8369
        .revset_with_budget("::main", std::time::Duration::ZERO)
8370
        .unwrap_err()
8371
        .to_string();
8372
    assert!(e.contains("budget"), "{e}");
8373
    // The log entries carry the bookmark's heads and the working copy.
8374
    let entries = repo.log_revset("::@").unwrap();
8375
    assert!(entries[0].is_working_copy && entries.iter().any(|e| e.is_head && e.hash == d));
8376
    // Trust predicates (§2.4): nothing is signed yet (core.sign = seal, no
8377
    // push); then a signed change, a tag, and a revocation.
8378
    assert_eq!(set("unsigned() & ::main"), sorted(&[a, b, c, d]));
8379
    assert_eq!(set("signed_by(me)"), vec![]);
8380
    repo.sign_change(&d).unwrap();
8381
    assert_eq!(set("signed_by(me)"), vec![d]);
8382
    assert_eq!(set("signed_by([email protected])"), vec![d]);
8383
    assert_eq!(set(&format!("signed_by({})", key.short(12))), vec![d]);
8384
    assert_eq!(set("unsigned() & ::main"), sorted(&[a, b, c]));
8385
    assert_eq!(set("delegated()"), vec![]);
8386
    assert_eq!(set("revoked()"), vec![]);
8387
    assert_eq!(set("attested(tag)"), vec![]);
8388
    repo.tag_create("v1", &[b], "first").unwrap();
8389
    assert_eq!(set("attested(tag)"), sorted(&[a, b]));
8390
    assert_eq!(set("attested(tag) & unsigned()"), sorted(&[a, b]));
8391
    assert_eq!(set("attested(receipt)"), vec![]);
8392
    assert_eq!(set("built(test)"), vec![]);
8393
    let e = repo.revset("attested(seal)").unwrap_err().to_string();
8394
    assert!(e.contains("tag, receipt or ref"), "{e}");
8395
    repo.revoke_identity(&key, "test").unwrap();
8396
    assert_eq!(set("revoked()"), vec![d]);
8397
    assert_eq!(set("signed_by(me) ~ revoked()"), vec![]);
8398
}
8399
8400
#[test]
8401
fn a_rotation_is_recorded_wherever_the_old_key_was_named() {
8402
    let dir = tempfile::tempdir().unwrap();
8403
    let root = dir.path();
8404
    let home = root.join("home");
8405
    // Ada's identity lives in the user file; repository `a` pins the same
8406
    // key in its own file, repository `b` names none.
8407
    let mut a = Repo::init(&root.join("a")).unwrap().with_home(&home);
8408
    let (key, _) = a
8409
        .create_identity("Ada", "[email protected]", IdentityScope::User)
8410
        .unwrap();
8411
    a.config.set("author.key", &key.to_hex()).unwrap();
8412
    a.save_config().unwrap();
8413
    let agent = SecretKey::generate().identity("Agent", "[email protected]", 1);
8414
    let r = a
8415
        .delegate_add(agent.clone(), crate::identity::Scope::CHANGES, None)
8416
        .unwrap();
8417
    assert_eq!(
8418
        read_config_file(&home.join("config.toml")).unwrap()["author.key"],
8419
        r.new.to_hex(),
8420
        "the user file follows"
8421
    );
8422
    assert_eq!(
8423
        read_config_file(&root.join("a/.oxy/config")).unwrap()["author.key"],
8424
        r.new.to_hex(),
8425
        "the pinning repository follows"
8426
    );
8427
    let b = Repo::init(&root.join("b")).unwrap().with_home(&home);
8428
    assert_eq!(
8429
        b.config.author_key,
8430
        Some(r.new),
8431
        "a checkout without a pin follows the user file"
8432
    );
8433
    // A repository-scoped identity leaves the user file alone.
8434
    let other_home = root.join("home2");
8435
    let mut c = Repo::init(&root.join("c")).unwrap().with_home(&other_home);
8436
    let (ck, _) = c
8437
        .create_identity("Cy", "[email protected]", IdentityScope::Repo)
8438
        .unwrap();
8439
    assert!(!other_home.join("config.toml").exists());
8440
    let r2 = c.rotate_identity().unwrap();
8441
    assert_ne!(r2.new, ck);
8442
    assert_eq!(
8443
        read_config_file(&root.join("c/.oxy/config")).unwrap()["author.key"],
8444
        r2.new.to_hex()
8445
    );
8446
    assert!(
8447
        !other_home.join("config.toml").exists(),
8448
        "a repository-scoped identity stays repository-scoped"
8449
    );
8450
    // Several delegates in one rotation; a repeat is refused.
8451
    let (d1, d2) = (
8452
        SecretKey::generate().identity("D1", "d1@x", 1),
8453
        SecretKey::generate().identity("D2", "d2@x", 1),
8454
    );
8455
    let r3 = c
8456
        .delegate_add_many(vec![d1.clone(), d2], crate::identity::Scope::CHANGES, None)
8457
        .unwrap();
8458
    assert_eq!(r3.identity.delegates.len(), 2);
8459
    assert!(c
8460
        .delegate_add(d1, crate::identity::Scope::CHANGES, None)
8461
        .is_err());
8462
}
8463
8464
/// Two unrelated histories that both add the same file, joined by two
8465
/// independent merges on two branches, then those branches merged: Git
8466
/// merges identical additions cleanly, and the import must too (#71,
8467
/// found in VS Code's history).
8468
#[test]
8469
fn git_import_joins_unrelated_histories_that_add_the_same_file() {
8470
    // Batches of one: every merge renders apart from the state, where a
8471
    // file whose graph the state had built came out empty (#71).
8472
    crate::repo::git::set_merge_batch_for_tests(Some(1));
8473
    hermetic();
8474
    if std::process::Command::new("git")
8475
        .arg("--version")
8476
        .output()
8477
        .is_err()
8478
    {
8479
        eprintln!("git not installed; skipping");
8480
        return;
8481
    }
8482
    let dir = tempfile::tempdir().unwrap();
8483
    let root = dir.path();
8484
    let g = root.join("src.git");
8485
    fs::create_dir_all(&g).unwrap();
8486
    let git = |args: &[&str]| -> String {
8487
        let out = std::process::Command::new("git")
8488
            .arg("-C")
8489
            .arg(&g)
8490
            .args([
8491
                "-c",
8492
                "user.name=Grace",
8493
                "-c",
8494
                "[email protected]",
8495
                "-c",
8496
                "commit.gpgsign=false",
8497
            ])
8498
            .args(args)
8499
            .output()
8500
            .unwrap();
8501
        assert!(
8502
            out.status.success(),
8503
            "git {args:?}: {}",
8504
            String::from_utf8_lossy(&out.stderr)
8505
        );
8506
        String::from_utf8_lossy(&out.stdout).trim().to_string()
8507
    };
8508
    let text = b"/* header */\nconst a = 1;\nconst b = 2;\n";
8509
    // History A: main.
8510
    git(&["init", "-q", "-b", "main"]);
8511
    write(&g, "gulpfile.js", text);
8512
    write(&g, "a.txt", b"a\n");
8513
    git(&["add", "."]);
8514
    git(&["commit", "-q", "-m", "A root"]);
8515
    // History B: an unrelated root adding the same file, identical.
8516
    git(&["checkout", "-q", "--orphan", "fork"]);
8517
    git(&["rm", "-q", "-r", "--cached", "."]);
8518
    for f in ["gulpfile.js", "a.txt"] {
8519
        let _ = fs::remove_file(g.join(f));
8520
    }
8521
    write(&g, "gulpfile.js", text);
8522
    write(&g, "b.txt", b"b\n");
8523
    git(&["add", "."]);
8524
    git(&["commit", "-q", "-m", "B root"]);
8525
    // Two branches from main, each joining B on its own.
8526
    git(&["checkout", "-q", "-b", "one", "main"]);
8527
    git(&[
8528
        "merge",
8529
        "-q",
8530
        "--no-ff",
8531
        "--allow-unrelated-histories",
8532
        "-m",
8533
        "join on one",
8534
        "fork",
8535
    ]);
8536
    git(&["checkout", "-q", "-b", "two", "main"]);
8537
    write(&g, "a.txt", b"a\ntwo\n");
8538
    git(&["commit", "-q", "-am", "work on two"]);
8539
    git(&[
8540
        "merge",
8541
        "-q",
8542
        "--no-ff",
8543
        "--allow-unrelated-histories",
8544
        "-m",
8545
        "join on two",
8546
        "fork",
8547
    ]);
8548
    // Then the two joins meet, and the file is reformatted after.
8549
    git(&["checkout", "-q", "main"]);
8550
    git(&["merge", "-q", "--no-ff", "-m", "merge one", "one"]);
8551
    git(&["merge", "-q", "--no-ff", "-m", "merge two", "two"]);
8552
    write(
8553
        &g,
8554
        "gulpfile.js",
8555
        b"/* header */\nconst a = 1;\nconst b = 3;\n",
8556
    );
8557
    git(&["commit", "-q", "-am", "after"]);
8558
8559
    let dest = root.join("dest");
8560
    let repo = Repo::init(&dest).unwrap().with_home(root.join("home"));
8561
    repo.import_git(&g, "main").unwrap();
8562
    let v = repo.verify_git_import(&g, "main").unwrap();
8563
    assert!(v.mismatches.is_empty(), "{:?}", v.mismatches);
8564
    assert_eq!(
8565
        fs::read(dest.join("gulpfile.js")).unwrap(),
8566
        b"/* header */\nconst a = 1;\nconst b = 3;\n"
8567
    );
8568
}
8569
8570
/// As above, but the two joins keep different copies (each branch had a
8571
/// different version when it joined), and later work edits each copy:
8572
/// the shape of VS Code's c67ef57cda90 (#71).
8573
#[test]
8574
fn git_import_joins_where_each_join_kept_a_different_copy() {
8575
    // Batches of one: every merge renders apart from the state, where a
8576
    // file whose graph the state had built came out empty (#71).
8577
    crate::repo::git::set_merge_batch_for_tests(Some(1));
8578
    hermetic();
8579
    if std::process::Command::new("git")
8580
        .arg("--version")
8581
        .output()
8582
        .is_err()
8583
    {
8584
        eprintln!("git not installed; skipping");
8585
        return;
8586
    }
8587
    let dir = tempfile::tempdir().unwrap();
8588
    let root = dir.path();
8589
    let g = root.join("src.git");
8590
    fs::create_dir_all(&g).unwrap();
8591
    let run = |args: &[&str]| {
8592
        std::process::Command::new("git")
8593
            .arg("-C")
8594
            .arg(&g)
8595
            .args([
8596
                "-c",
8597
                "user.name=Grace",
8598
                "-c",
8599
                "[email protected]",
8600
                "-c",
8601
                "commit.gpgsign=false",
8602
            ])
8603
            .args(args)
8604
            .output()
8605
            .unwrap()
8606
    };
8607
    let git = |args: &[&str]| -> String {
8608
        let out = run(args);
8609
        assert!(
8610
            out.status.success(),
8611
            "git {args:?}: {}",
8612
            String::from_utf8_lossy(&out.stderr)
8613
        );
8614
        String::from_utf8_lossy(&out.stdout).trim().to_string()
8615
    };
8616
    git(&["init", "-q", "-b", "main"]);
8617
    write(
8618
        &g,
8619
        "gulpfile.js",
8620
        b"/* header */\nconst a = 1;\nconst b = 2;\n",
8621
    );
8622
    git(&["add", "."]);
8623
    git(&["commit", "-q", "-m", "A root"]);
8624
    write(
8625
        &g,
8626
        "gulpfile.js",
8627
        b"/* header */\nconst a = 1;\n\nconst b = 2;\n",
8628
    );
8629
    git(&["commit", "-q", "-am", "whitespace"]);
8630
    git(&["checkout", "-q", "--orphan", "fork"]);
8631
    git(&["rm", "-q", "-r", "--cached", "."]);
8632
    let _ = fs::remove_file(g.join("gulpfile.js"));
8633
    write(
8634
        &g,
8635
        "gulpfile.js",
8636
        b"/* header */\nconst a = 1;\nconst b = 2;\nconst c = 3;\n",
8637
    );
8638
    git(&["add", "."]);
8639
    git(&["commit", "-q", "-m", "B root"]);
8640
    // Branch one joins B keeping main's copy; branch two keeps B's.
8641
    for (branch, keep) in [("one", "ours"), ("two", "theirs")] {
8642
        git(&["checkout", "-q", "-b", branch, "main"]);
8643
        let _ = run(&[
8644
            "merge",
8645
            "-q",
8646
            "--no-ff",
8647
            "--allow-unrelated-histories",
8648
            "-m",
8649
            "join",
8650
            "fork",
8651
        ]);
8652
        git(&["checkout", &format!("--{keep}"), "gulpfile.js"]);
8653
        git(&["add", "gulpfile.js"]);
8654
        git(&["commit", "-q", "-m", &format!("join on {branch}")]);
8655
    }
8656
    // Each branch then edits its copy.
8657
    git(&["checkout", "-q", "one"]);
8658
    write(
8659
        &g,
8660
        "gulpfile.js",
8661
        b"/* header */\nconst a = 1;\n\nconst b = 2;\n// tslint\n",
8662
    );
8663
    git(&["commit", "-q", "-am", "tslint on one"]);
8664
    git(&["checkout", "-q", "two"]);
8665
    write(
8666
        &g,
8667
        "gulpfile.js",
8668
        b"/* header */\nconst a = 1;\nconst b = 2;\nconst c = 3;\n// fmt\n",
8669
    );
8670
    write(&g, "extra.txt", b"x\n");
8671
    write(&g, "more.txt", b"m\n");
8672
    git(&["add", "."]);
8673
    git(&["commit", "-q", "-am", "fmt on two"]);
8674
    // They meet: resolved by hand.
8675
    git(&["checkout", "-q", "one"]);
8676
    let _ = run(&["merge", "-q", "--no-ff", "-m", "merge two", "two"]);
8677
    write(
8678
        &g,
8679
        "gulpfile.js",
8680
        b"/* header */\nconst a = 1;\nconst b = 2;\nconst c = 3;\n// tslint\n// fmt\n",
8681
    );
8682
    git(&["add", "gulpfile.js"]);
8683
    git(&["commit", "-q", "-m", "merge two into one"]);
8684
8685
    let dest = root.join("dest");
8686
    let repo = Repo::init(&dest).unwrap().with_home(root.join("home"));
8687
    repo.import_git(&g, "one").unwrap();
8688
    let v = repo.verify_git_import(&g, "one").unwrap();
8689
    assert!(v.mismatches.is_empty(), "{:?}", v.mismatches);
8690
}
8691
8692
/// oxygen#68: on a store that is not this disk's directory, the operation
8693
/// head is the store's reference record, moved by compare-and-swap. Two
8694
/// handles recording from the same head both get through, merged; a swap
8695
/// from a stale version is refused; a second repository cannot start on a
8696
/// store that already holds one.
8697
#[test]
8698
fn over_a_store_the_operation_head_moves_by_compare_and_swap() {
8699
    use crate::strata::{MemoryStore, Store as _};
8700
    let backend = std::sync::Arc::new(MemoryStore::new());
8701
    crate::store::TEST_BACKEND.with(|t| *t.borrow_mut() = Some(backend.clone()));
8702
    let dir = tempfile::tempdir().unwrap();
8703
    let a = Repo::init(dir.path()).unwrap();
8704
    assert!(
8705
        !dir.path().join(".oxy/ops/head").exists(),
8706
        "the head is not a file"
8707
    );
8708
    let (h0, op0) = a.head_op().unwrap();
8709
    let record = backend
8710
        .read_ref(HEAD_RECORD)
8711
        .unwrap()
8712
        .expect("the head is the store's record");
8713
    assert_eq!(String::from_utf8(record.0).unwrap(), h0.to_hex());
8714
8715
    let b = Repo::open(dir.path()).unwrap();
8716
    let state = a.store.put_state(&StateObject::new(vec![])).unwrap();
8717
    let mut va = op0.view.clone();
8718
    va.bookmarks.insert("from-a".into(), state);
8719
    let mut vb = op0.view.clone();
8720
    vb.bookmarks.insert("from-b".into(), state);
8721
    let rb = b.record_op(&[h0], "bookmark from-b", vb).unwrap();
8722
    assert_eq!(b.head_ref().unwrap(), rb);
8723
    // a recorded from h0 too: the head moved, so the two are merged.
8724
    let ra = a.record_op(&[h0], "bookmark from-a", va).unwrap();
8725
    let (head, op) = Repo::open(dir.path()).unwrap().head_op().unwrap();
8726
    assert_eq!(head, ra);
8727
    assert!(
8728
        op.command.ends_with("(merged with a concurrent operation)"),
8729
        "{}",
8730
        op.command
8731
    );
8732
    assert_eq!(op.parents, vec![rb, op.parents[1]]);
8733
    assert!(op.view.bookmarks.contains_key("from-a") && op.view.bookmarks.contains_key("from-b"));
8734
8735
    // A swap from a version that is no longer current moves nothing.
8736
    let (h, v) = a.read_head().unwrap();
8737
    assert!(b.swap_head(&rb, v.as_ref()).unwrap());
8738
    assert!(!a.swap_head(&h, v.as_ref()).unwrap(), "stale");
8739
    a.refresh().unwrap();
8740
    assert_eq!(a.head_ref().unwrap(), rb);
8741
8742
    let other = tempfile::tempdir().unwrap();
8743
    let err = Repo::init(other.path())
8744
        .err()
8745
        .expect("the store already holds a log")
8746
        .to_string();
8747
    assert!(
8748
        err.contains("already holds a repository's operation log"),
8749
        "{err}"
8750
    );
8751
    crate::store::TEST_BACKEND.with(|t| *t.borrow_mut() = None);
8752
}
8753
8754
/// oxygen#68: a repository kept on a store (`storage.url`) holds its
8755
/// objects and operation head there, with `.oxy/cache` in front: it works
8756
/// as one on disk does, reopens, and survives losing its cache.
8757
#[test]
8758
fn a_repository_runs_on_a_store_with_a_cache_in_front() {
8759
    hermetic();
8760
    if std::env::var_os("OXY_STORE_BACKEND").is_some() {
8761
        return;
8762
    }
8763
    let dir = tempfile::tempdir().unwrap();
8764
    let (root, bucket) = (dir.path().join("work"), dir.path().join("bucket"));
8765
    let url = format!("dir://{}", bucket.display());
8766
    let repo = Repo::init_on(&root, [7; 16], Some(&url)).unwrap();
8767
    assert_eq!(repo.config.storage_url.as_deref(), Some(url.as_str()));
8768
    write(&root, "a.txt", b"one\n");
8769
    let h1 = repo.commit("First", &[]).unwrap();
8770
    write(&root, "a.txt", b"one\ntwo\n");
8771
    let h2 = repo.commit("Second", &[]).unwrap();
8772
    assert!(
8773
        !root.join(".oxy/ops/head").exists(),
8774
        "the head is in the store"
8775
    );
8776
    assert!(bucket.join("ops/head").is_file());
8777
    assert!(root.join(".oxy/cache").is_dir());
8778
    drop(repo);
8779
8780
    // Reopened, and again with no cache at all: everything comes from the store.
8781
    for drop_cache in [false, true] {
8782
        if drop_cache {
8783
            std::fs::remove_dir_all(root.join(".oxy/cache")).unwrap();
8784
        }
8785
        let repo = Repo::open(&root).unwrap();
8786
        let log: Vec<String> = repo
8787
            .op_log()
8788
            .unwrap()
8789
            .into_iter()
8790
            .map(|(_, op)| op.command)
8791
            .collect();
8792
        assert!(log.len() >= 3, "{log:?}");
8793
        assert_eq!(repo.store().get_change(&h1).unwrap().message, "First");
8794
        let heads = repo
8795
            .store()
8796
            .get_state(&repo.view().unwrap().bookmarks["main"])
8797
            .unwrap()
8798
            .heads;
8799
        assert_eq!(heads, vec![h2]);
8800
        assert_eq!(
8801
            repo.load_state(&heads).unwrap().materialize().files.len(),
8802
            1
8803
        );
8804
    }
8805
8806
    // A second repository cannot start on the same store.
8807
    let err = Repo::init_on(&dir.path().join("other"), [8; 16], Some(&url))
8808
        .err()
8809
        .unwrap()
8810
        .to_string();
8811
    assert!(
8812
        err.contains("already holds a repository's operation log"),
8813
        "{err}"
8814
    );
8815
    let err = Repo::init_on(&dir.path().join("third"), [9; 16], Some("nope://x"))
8816
        .err()
8817
        .unwrap()
8818
        .to_string();
8819
    assert!(err.contains("cannot open that kind of store"), "{err}");
8820
}
8821
8822
/// oxygen#75: the prompt's quick check agrees with status in a repository
8823
/// with a subrepo: clean after a commit, dirty when the subrepo moves to
8824
/// another state, clean again once that pin is committed. (It compared the
8825
/// subrepo's directory as if it were a file, so it was always dirty.)
8826
#[test]
8827
fn the_quick_dirty_check_compares_a_subrepo_by_its_pin() {
8828
    hermetic();
8829
    let dir = tempfile::tempdir().unwrap();
8830
    let root = dir.path();
8831
    let _lib_origin = Repo::init(&root.join("lib-origin")).unwrap();
8832
    let lib_url = root.join("lib-origin").to_string_lossy().to_string();
8833
    let lib = Repo::clone(&lib_url, &root.join("lib"))
8834
        .unwrap()
8835
        .with_home(root.join("home"));
8836
    write(&root.join("lib"), "lib.txt", b"v1\n");
8837
    lib.commit("lib v1", &[]).unwrap();
8838
    assert!(lib.push("origin", false).unwrap()[0].ok);
8839
    let app_dir = root.join("app");
8840
    let app = Repo::init(&app_dir).unwrap().with_home(root.join("home"));
8841
    write(&app_dir, "main.txt", b"app\n");
8842
    app.submodule_add(&lib_url, "libs/lib", None).unwrap();
8843
    app.commit("app with lib", &[]).unwrap();
8844
    // Out of the racy window, so the stat-only path decides.
8845
    std::thread::sleep(std::time::Duration::from_millis(2100));
8846
    let reopen = || Repo::open(&app_dir).unwrap();
8847
    assert_eq!(
8848
        reopen().quick_dirty().unwrap(),
8849
        Some(false),
8850
        "clean, as status says"
8851
    );
8852
    let nested = Repo::open(&app_dir.join("libs/lib")).unwrap();
8853
    write(&app_dir.join("libs/lib"), "lib.txt", b"v2\n");
8854
    nested.commit("lib v2", &[]).unwrap();
8855
    assert_eq!(
8856
        reopen().quick_dirty().unwrap(),
8857
        Some(true),
8858
        "the subrepo moved"
8859
    );
8860
    reopen().commit("pin lib v2", &[]).unwrap();
8861
    std::thread::sleep(std::time::Duration::from_millis(2100));
8862
    assert_eq!(
8863
        reopen().quick_dirty().unwrap(),
8864
        Some(false),
8865
        "the new pin is committed"
8866
    );
8867
}
8868
8869
#[test]
8870
fn a_module_entry_that_was_never_added_is_reported_as_unpinned() {
8871
    // oxygen#72: a .oxymodules section with no subrepo behind it.
8872
    hermetic();
8873
    let dir = tempfile::tempdir().unwrap();
8874
    let root = dir.path();
8875
    let _lib_origin = Repo::init(&root.join("lib-origin")).unwrap();
8876
    let lib_url = root.join("lib-origin").to_string_lossy().to_string();
8877
    let lib = Repo::clone(&lib_url, &root.join("lib"))
8878
        .unwrap()
8879
        .with_home(root.join("home"));
8880
    write(&root.join("lib"), "lib.txt", b"v1\n");
8881
    lib.commit("lib v1", &[]).unwrap();
8882
    assert!(lib.push("origin", false).unwrap()[0].ok);
8883
    let app_dir = root.join("app");
8884
    let app = Repo::init(&app_dir).unwrap().with_home(root.join("home"));
8885
    write(
8886
        &app_dir,
8887
        ".oxymodules",
8888
        format!("[libs/lib]\nurl = {lib_url}\n").as_bytes(),
8889
    );
8890
    let unpinned = app.unpinned_modules().unwrap();
8891
    assert_eq!(unpinned.len(), 1);
8892
    assert_eq!(unpinned[0].0, "libs/lib");
8893
    assert_eq!(unpinned[0].1.url, lib_url);
8894
    assert!(app.submodule_update(true, &[]).unwrap().is_empty());
8895
    app.submodule_add(&lib_url, "libs/lib", None).unwrap();
8896
    assert!(app.unpinned_modules().unwrap().is_empty(), "added now");
8897
}
8898
8899
#[test]
8900
fn the_bookmark_revset_function_names_only_bookmarks() {
8901
    // oxygen#73: bookmark(NAME) is a bookmark's heads, never a tag or prefix.
8902
    hermetic();
8903
    let dir = tempfile::tempdir().unwrap();
8904
    let repo = Repo::init(dir.path()).unwrap();
8905
    write(dir.path(), "a.txt", b"a\n");
8906
    let a = repo.commit("A", &[]).unwrap();
8907
    write(dir.path(), "b.txt", b"b\n");
8908
    let b = repo.commit("B", &[]).unwrap();
8909
    let mut heads = repo.revset("bookmark(main)").unwrap().hashes;
8910
    heads.sort();
8911
    let mut want = repo.bookmark_heads().unwrap();
8912
    want.sort();
8913
    assert_eq!(heads, want);
8914
    assert!(heads.contains(&b));
8915
    assert_eq!(repo.revset("main").unwrap().hashes.len(), heads.len());
8916
    // A change prefix is a symbol, not a bookmark.
8917
    let prefix = repo.store().get_change_meta(&a).unwrap().change_id.short(8);
8918
    assert!(repo.revset(&prefix).is_ok());
8919
    let e = repo
8920
        .revset(&format!("bookmark({prefix})"))
8921
        .unwrap_err()
8922
        .to_string();
8923
    assert!(e.contains("no such bookmark"), "{e}");
8924
}
8925
8926
#[test]
8927
fn carrying_work_over_a_subrepo_already_at_the_target_pin_is_no_conflict() {
8928
    // oxygen#74: a stale state with .oxymodules but no pin, a newer one
8929
    // pinning the subrepo, and the nested repository on disk at that pin.
8930
    hermetic();
8931
    let dir = tempfile::tempdir().unwrap();
8932
    let root = dir.path();
8933
    let _lib_origin = Repo::init(&root.join("lib-origin")).unwrap();
8934
    let lib_url = root.join("lib-origin").to_string_lossy().to_string();
8935
    let lib = Repo::clone(&lib_url, &root.join("lib"))
8936
        .unwrap()
8937
        .with_home(root.join("home"));
8938
    write(&root.join("lib"), "lib.txt", b"v1\n");
8939
    lib.commit("lib v1", &[]).unwrap();
8940
    assert!(lib.push("origin", false).unwrap()[0].ok);
8941
    let app_dir = root.join("app");
8942
    let app = Repo::init(&app_dir).unwrap().with_home(root.join("home"));
8943
    write(&app_dir, "main.txt", b"app\n");
8944
    app.submodule_add(&lib_url, "libs/lib", None).unwrap();
8945
    // The stale state: registered in .oxymodules, never pinned.
8946
    fs::rename(app_dir.join("libs/lib"), root.join("aside")).unwrap();
8947
    app.commit("initial", &[]).unwrap();
8948
    let stale = app.bookmark_heads().unwrap();
8949
    fs::rename(root.join("aside"), app_dir.join("libs/lib")).unwrap();
8950
    app.commit("pin lib", &[]).unwrap();
8951
    let newer = app.bookmark_heads().unwrap();
8952
    app.checkout(&stale, false, "test").unwrap();
8953
    write(&app_dir, "notes.txt", b"mine\n");
8954
    let (_, carried) = app.checkout_carry(&newer, "main", "test").unwrap();
8955
    assert_eq!(carried, vec!["notes.txt".to_string()]);
8956
    assert!(app_dir.join("notes.txt").exists());
8957
}
8958
8959
#[test]
8960
fn a_bookmark_only_behind_its_remote_catches_up() {
8961
    // oxygen#74: switch takes the remote's state rather than a stale one.
8962
    hermetic();
8963
    let dir = tempfile::tempdir().unwrap();
8964
    let root = dir.path();
8965
    let _origin = Repo::init(&root.join("origin")).unwrap();
8966
    let url = root.join("origin").to_string_lossy().to_string();
8967
    let one = Repo::clone(&url, &root.join("one"))
8968
        .unwrap()
8969
        .with_home(root.join("home"));
8970
    write(&root.join("one"), "a.txt", b"a\n");
8971
    one.commit("A", &[]).unwrap();
8972
    assert!(one.push("origin", false).unwrap()[0].ok);
8973
    let two = Repo::clone(&url, &root.join("two"))
8974
        .unwrap()
8975
        .with_home(root.join("home"));
8976
    write(&root.join("two"), "b.txt", b"b\n");
8977
    two.commit("B", &[]).unwrap();
8978
    assert!(two.push("origin", false).unwrap()[0].ok);
8979
    assert_eq!(one.catch_up_bookmark("main").unwrap(), None, "not fetched");
8980
    one.fetch("origin").unwrap();
8981
    assert_eq!(one.catch_up_bookmark("main").unwrap(), Some(1));
8982
    assert_eq!(one.bookmarks().unwrap()[0].behind, Some(0));
8983
    // Local work the remote lacks: left alone.
8984
    write(&root.join("one"), "c.txt", b"c\n");
8985
    one.commit("C", &[]).unwrap();
8986
    write(&root.join("two"), "d.txt", b"d\n");
8987
    two.commit("D", &[]).unwrap();
8988
    assert!(two.push("origin", false).unwrap()[0].ok);
8989
    one.fetch("origin").unwrap();
8990
    assert_eq!(one.catch_up_bookmark("main").unwrap(), None);
8991
}
8992
8993
#[test]
8994
fn a_bookmark_is_compared_with_a_remote_that_has_it_when_there_is_no_origin() {
8995
    // oxygen#83: remotes earth and gcs, origin removed.
8996
    hermetic();
8997
    let dir = tempfile::tempdir().unwrap();
8998
    let root = dir.path();
8999
    let _up = Repo::init(&root.join("up")).unwrap();
9000
    let url = root.join("up").to_string_lossy().to_string();
9001
    let other = Repo::clone(&url, &root.join("other"))
9002
        .unwrap()
9003
        .with_home(root.join("home"));
9004
    write(&root.join("other"), "a.txt", b"a\n");
9005
    other.commit("a", &[]).unwrap();
9006
    assert!(other.push("origin", false).unwrap()[0].ok);
9007
    let mut one = Repo::clone(&url, &root.join("one"))
9008
        .unwrap()
9009
        .with_home(root.join("home"));
9010
    one.config.set("remote.earth.url", &url).unwrap();
9011
    one.config.set("remote.gcs.url", &url).unwrap();
9012
    one.config.set("remote.origin.url", "").unwrap();
9013
    one.save_config().unwrap();
9014
    write(&root.join("other"), "b.txt", b"b\n");
9015
    other.commit("b", &[]).unwrap();
9016
    assert!(other.push("origin", false).unwrap()[0].ok);
9017
    one.fetch("earth").unwrap();
9018
    let b = one
9019
        .bookmarks()
9020
        .unwrap()
9021
        .into_iter()
9022
        .find(|b| b.name == "main")
9023
        .unwrap();
9024
    assert_eq!(
9025
        (b.remote.as_deref(), b.behind),
9026
        (Some("earth"), Some(1)),
9027
        "a stale origin copy is not used"
9028
    );
9029
    assert_eq!(
9030
        one.default_remote(),
9031
        "origin",
9032
        "no default chosen among several"
9033
    );
9034
    let e = one.pull(&one.default_remote()).unwrap_err().to_string();
9035
    assert!(e.contains("earth, gcs") && e.contains("core.remote"), "{e}");
9036
    one.config.set("core.remote", "earth").unwrap();
9037
    assert_eq!(one.default_remote(), "earth");
9038
}
9039
9040
#[test]
9041
fn a_missing_author_identity_says_how_to_fix_it() {
9042
    // oxygen#82: an agent home's author.key naming an identity the
9043
    // repository does not hold.
9044
    hermetic();
9045
    let dir = tempfile::tempdir().unwrap();
9046
    let mut repo = Repo::init(dir.path()).unwrap();
9047
    let missing = KeyId::from_hex(&"ab".repeat(32)).unwrap();
9048
    repo.config.set("author.key", &missing.to_hex()).unwrap();
9049
    let e = repo.identity(&missing).unwrap_err().to_string();
9050
    assert!(
9051
        e.contains("this repository has no identity") && e.contains("oxy config author.key"),
9052
        "{e}"
9053
    );
9054
    assert!(e.contains("this repository's config"), "{e}");
9055
}
9056
9057
#[test]
9058
fn a_working_copy_behind_its_bookmark_is_flagged_and_pull_brings_it_up() {
9059
    // oxygen#89 (supermarioland, 2026-10-09): the bookmark moved on without
9060
    // the working copy, a pull with nothing new left it there, and status
9061
    // said "clean".
9062
    hermetic();
9063
    let dir = tempfile::tempdir().unwrap();
9064
    let root = dir.path();
9065
    let _up = Repo::init(&root.join("up")).unwrap();
9066
    let url = root.join("up").to_string_lossy().to_string();
9067
    let other = Repo::clone(&url, &root.join("other"))
9068
        .unwrap()
9069
        .with_home(root.join("home"));
9070
    write(&root.join("other"), "a.txt", b"a\n");
9071
    other.commit("a", &[]).unwrap();
9072
    assert!(other.push("origin", false).unwrap()[0].ok);
9073
    let one = Repo::clone(&url, &root.join("one"))
9074
        .unwrap()
9075
        .with_home(root.join("home"));
9076
    write(&root.join("other"), "b.txt", b"b\n");
9077
    other.commit("b", &[]).unwrap();
9078
    assert!(other.push("origin", false).unwrap()[0].ok);
9079
    one.fetch("origin").unwrap();
9080
    // The bookmark moves; the working copy does not.
9081
    let theirs = one.resolve_heads("origin/main").unwrap();
9082
    one.bookmark_set("main", &theirs).unwrap();
9083
    assert!(!root.join("one/b.txt").exists());
9084
    assert_eq!(one.working_copy_behind().unwrap(), Some(1));
9085
    let r = one.pull("origin").unwrap();
9086
    assert!(
9087
        !r.changed && r.checked_out,
9088
        "nothing new, but the working copy caught up"
9089
    );
9090
    assert!(root.join("one/b.txt").exists());
9091
    assert_eq!(one.working_copy_behind().unwrap(), None);
9092
}
9093
9094
#[test]
9095
fn touched_nodes_cache_answers_as_the_changes_do() {
9096
    hermetic();
9097
    let dir = tempfile::tempdir().unwrap();
9098
    let repo = Repo::init(dir.path()).unwrap();
9099
    write(dir.path(), "a.txt", b"one\n");
9100
    write(dir.path(), "b.txt", b"x\n");
9101
    repo.snapshot("t").unwrap();
9102
    let c1 = repo.commit("first", &[]).unwrap();
9103
    write(dir.path(), "b.txt", b"y\n");
9104
    repo.snapshot("t").unwrap();
9105
    repo.commit("b only", &[]).unwrap();
9106
    fs::rename(dir.path().join("a.txt"), dir.path().join("c.txt")).unwrap();
9107
    write(dir.path(), "c.txt", b"one\ntwo\n");
9108
    repo.snapshot("t").unwrap();
9109
    let c3 = repo.commit("rename and edit", &[]).unwrap();
9110
    // Uncommitted work, so the working copy touches a file too.
9111
    write(dir.path(), "c.txt", b"one\ntwo\nthree\n");
9112
    repo.snapshot("t").unwrap();
9113
9114
    let path = dir.path().join(".oxy/index/touched");
9115
    let hashes = |es: Vec<LogEntry>| es.iter().map(|e| e.hash).collect::<Vec<_>>();
9116
    let cold = hashes(repo.log_for_path("c.txt").unwrap());
9117
    assert!(path.exists(), "the first query writes the cache");
9118
    let warm = hashes(repo.log_for_path("c.txt").unwrap());
9119
    assert_eq!(cold, warm, "the cache answers as the changes do");
9120
    let (wc, _) = repo.working_copy().unwrap();
9121
    assert_eq!(
9122
        cold,
9123
        vec![wc, c3, c1],
9124
        "renames followed, the working copy included"
9125
    );
9126
9127
    // Working-copy changes are not kept: they are replaced by every snapshot.
9128
    let cached = super::touched::read_touched_for_test(&fs::read(&path).unwrap()).unwrap();
9129
    assert!(!cached.contains(&wc), "a working-copy change is not cached");
9130
    assert!(cached.contains(&c1) && cached.contains(&c3));
9131
9132
    // A damaged cache is ignored, not trusted.
9133
    let mut bytes = fs::read(&path).unwrap();
9134
    let last = bytes.len() - 40;
9135
    bytes[last] ^= 1;
9136
    fs::write(&path, &bytes).unwrap();
9137
    assert_eq!(hashes(repo.log_for_path("c.txt").unwrap()), cold);
9138
    let touches = repo.log_revset("touches(\"c.txt\") ~ @").unwrap();
9139
    assert_eq!(hashes(touches), vec![c3, c1]);
9140
}
9141
9142
/// oxygen#88 (vscode 9ab2056393c8): two lines of history that each move a
9143
/// file back where it was leave two placements at one place, which the
9144
/// tree shows as one file. Removing it, and then its directory, retires
9145
/// both, so no copy is left under a directory that is gone.
9146
#[test]
9147
fn git_import_removes_every_copy_of_a_file_at_one_place() {
9148
    hermetic();
9149
    if std::process::Command::new("git")
9150
        .arg("--version")
9151
        .output()
9152
        .is_err()
9153
    {
9154
        eprintln!("git not installed; skipping");
9155
        return;
9156
    }
9157
    let dir = tempfile::tempdir().unwrap();
9158
    let root = dir.path();
9159
    let g = root.join("src.git");
9160
    fs::create_dir_all(&g).unwrap();
9161
    let git = |args: &[&str]| {
9162
        let out = std::process::Command::new("git")
9163
            .arg("-C")
9164
            .arg(&g)
9165
            .args([
9166
                "-c",
9167
                "user.name=Grace",
9168
                "-c",
9169
                "[email protected]",
9170
                "-c",
9171
                "commit.gpgsign=false",
9172
            ])
9173
            .args(args)
9174
            .output()
9175
            .unwrap();
9176
        assert!(
9177
            out.status.success(),
9178
            "git {args:?}: {}",
9179
            String::from_utf8_lossy(&out.stderr)
9180
        );
9181
    };
9182
    git(&["init", "-q", "-b", "main"]);
9183
    write(&g, "d/list.txt", b"one\ntwo\nthree\nfour\n");
9184
    write(&g, "keep.txt", b"k\n");
9185
    git(&["add", "."]);
9186
    git(&["commit", "-qm", "base"]);
9187
    fs::create_dir_all(g.join("d/sub")).unwrap();
9188
    git(&["mv", "d/list.txt", "d/sub/list.txt"]);
9189
    git(&["commit", "-qm", "into sub"]);
9190
    git(&["checkout", "-qb", "side"]);
9191
    git(&["mv", "d/sub/list.txt", "d/list.txt"]);
9192
    git(&["commit", "-qm", "back, on side"]);
9193
    git(&["checkout", "-q", "main"]);
9194
    git(&["mv", "d/sub/list.txt", "d/list.txt"]);
9195
    git(&["commit", "-qm", "back, on main"]);
9196
    git(&["merge", "-q", "--no-edit", "side"]);
9197
    git(&["rm", "-rq", "d"]);
9198
    git(&["commit", "-qm", "d goes"]);
9199
9200
    let repo = Repo::init(&root.join("o")).unwrap();
9201
    repo.import_git(&g, "main").unwrap();
9202
    let v = repo.verify_git_import(&g, "main").unwrap();
9203
    assert!(v.mismatches.is_empty(), "{:?}", v.mismatches);
9204
    let st = repo
9205
        .load_state_history(&repo.bookmark_heads().unwrap())
9206
        .unwrap();
9207
    let view = st.tree().view();
9208
    assert!(view.conflicts.is_empty(), "{:?}", view.conflicts);
9209
    assert_eq!(view.entries.keys().collect::<Vec<_>>(), vec!["keep.txt"]);
9210
}
9211
9212
/// oxygen#94: a state index's file histories are read, and checked by
9213
/// their own hashes, only when a file is built. One found damaged is an
9214
/// error that says so, the index is removed, and the next read rebuilds it.
9215
#[test]
9216
fn a_damaged_file_history_in_the_state_index_is_rebuilt() {
9217
    hermetic();
9218
    let dir = tempfile::tempdir().unwrap();
9219
    let repo = Repo::init(dir.path()).unwrap();
9220
    for i in 0..6 {
9221
        write(
9222
            dir.path(),
9223
            &format!("f{i}.txt"),
9224
            format!("one {i}\n").as_bytes(),
9225
        );
9226
    }
9227
    repo.snapshot("t").unwrap();
9228
    repo.commit("first", &[]).unwrap();
9229
    for i in 0..6 {
9230
        write(
9231
            dir.path(),
9232
            &format!("f{i}.txt"),
9233
            format!("one {i}\ntwo\n").as_bytes(),
9234
        );
9235
    }
9236
    repo.snapshot("t").unwrap();
9237
    repo.commit("second", &[]).unwrap();
9238
    let want: Vec<Vec<u8>> = (0..6)
9239
        .map(|i| format!("one {i}\ntwo\n").into_bytes())
9240
        .collect();
9241
    // The index of the working copy's base, holding every file's history
9242
    // (a few changes behind, an index is replayed onto, not rewritten).
9243
    let (_, wc) = repo.working_copy().unwrap();
9244
    let base = repo.load_state_history(&wc.deps).unwrap();
9245
    repo.write_state_index(&wc.deps, &base);
9246
    for (i, w) in want.iter().enumerate() {
9247
        assert_eq!(&repo.file_at(&format!("f{i}.txt"), None).unwrap(), w);
9248
    }
9249
    let index = repo.state_indexes();
9250
    assert!(!index.is_empty(), "a state index was written");
9251
    // The histories are last in the file: damage the last of them.
9252
    let mut bytes = fs::read(&index[0]).unwrap();
9253
    let last = bytes.len() - 1;
9254
    bytes[last] ^= 0x40;
9255
    fs::write(&index[0], &bytes).unwrap();
9256
9257
    let reads: Vec<_> = (0..6)
9258
        .map(|i| repo.file_at(&format!("f{i}.txt"), None))
9259
        .collect();
9260
    let damaged: Vec<String> = reads
9261
        .iter()
9262
        .filter_map(|r| r.as_ref().err().map(|e| e.to_string()))
9263
        .collect();
9264
    assert_eq!(damaged.len(), 1, "{damaged:?}");
9265
    assert!(
9266
        damaged[0].contains("state index was damaged")
9267
            && damaged[0].contains("run the command again"),
9268
        "{}",
9269
        damaged[0]
9270
    );
9271
    // Every file reads right again, from an index rebuilt from history.
9272
    for (i, w) in want.iter().enumerate() {
9273
        assert_eq!(&repo.file_at(&format!("f{i}.txt"), None).unwrap(), w);
9274
    }
9275
}
9276
9277
/// oxygen#95: a push longer than `push.batch-bytes` goes in parts, each
9278
/// objects alone and in dependency order, and the last moves the bookmark.
9279
/// The remote ends with every change and the same state, and says how each
9280
/// part went.
9281
#[test]
9282
fn a_long_push_goes_in_parts() {
9283
    hermetic();
9284
    let dir = tempfile::tempdir().unwrap();
9285
    let root = dir.path();
9286
    let origin = root.join("origin");
9287
    Repo::init_bare_unbound(&origin).unwrap();
9288
    let main = root.join("main");
9289
    let mut repo = Repo::init(&main).unwrap();
9290
    repo.config
9291
        .set("remote.origin.url", &origin.to_string_lossy())
9292
        .unwrap();
9293
    // One byte: every change is a part of its own.
9294
    repo.config.set("push.batch-bytes", "1").unwrap();
9295
    repo.save_config().unwrap();
9296
    for i in 0..6 {
9297
        write(
9298
            &main,
9299
            &format!("f{i}.txt"),
9300
            format!("file {i}\n").as_bytes(),
9301
        );
9302
        repo.commit(&format!("c{i}"), &[]).unwrap();
9303
    }
9304
    let mut parts = Vec::new();
9305
    let results = repo
9306
        .push_bookmark_with("origin", "main", false, &mut |m| parts.push(m.to_string()))
9307
        .unwrap();
9308
    assert!(
9309
        results.iter().any(|r| r.ok && r.name == "main"),
9310
        "{results:?}"
9311
    );
9312
    assert_eq!(parts.len(), 6, "{parts:?}");
9313
    assert_eq!(parts[0], "part 1 of 6: 1 changes");
9314
9315
    let remote = Repo::open(&origin).unwrap();
9316
    let heads = repo.bookmark_heads().unwrap();
9317
    assert_eq!(remote.bookmark_heads().unwrap(), heads);
9318
    assert_eq!(
9319
        remote.log_state(&heads).unwrap().len(),
9320
        repo.log_state(&heads).unwrap().len()
9321
    );
9322
    // A push of objects alone reports how it went, as `objects`.
9323
    let got = remote
9324
        .receive_push(Bundle::default(), vec![], None, vec![])
9325
        .unwrap();
9326
    assert_eq!(got.len(), 1);
9327
    assert!(got[0].ok && got[0].name == OBJECTS_RESULT, "{got:?}");
9328
}
9329
9330
/// oxygen#133: one change whose blobs pass `push.batch-bytes` sends them
9331
/// first, in parts of objects alone, so no request is larger than about
9332
/// that (a proxy in front of a hub refuses one past 100 MB); the change
9333
/// and the bookmark follow, and a clone has every file.
9334
#[test]
9335
fn a_heavy_change_sends_its_blobs_in_parts() {
9336
    hermetic();
9337
    let dir = tempfile::tempdir().unwrap();
9338
    let root = dir.path();
9339
    let origin = root.join("origin");
9340
    Repo::init_bare_unbound(&origin).unwrap();
9341
    let main = root.join("main");
9342
    let mut repo = Repo::init(&main).unwrap();
9343
    repo.config
9344
        .set("remote.origin.url", &origin.to_string_lossy())
9345
        .unwrap();
9346
    repo.config.set("push.batch-bytes", "50000").unwrap();
9347
    repo.save_config().unwrap();
9348
    let mut x: u64 = 0x9e3779b97f4a7c15;
9349
    let mut noise = |n: usize| -> Vec<u8> {
9350
        (0..n)
9351
            .map(|_| {
9352
                x ^= x << 13;
9353
                x ^= x >> 7;
9354
                x ^= x << 17;
9355
                (x >> 24) as u8
9356
            })
9357
            .collect()
9358
    };
9359
    let files: Vec<Vec<u8>> = (0..4).map(|_| noise(40_000)).collect();
9360
    for (i, f) in files.iter().enumerate() {
9361
        write(&main, &format!("bin{i}.dat"), f);
9362
    }
9363
    repo.commit("four blobs", &[]).unwrap();
9364
    let mut parts = Vec::new();
9365
    let results = repo
9366
        .push_bookmark_with("origin", "main", false, &mut |m| parts.push(m.to_string()))
9367
        .unwrap();
9368
    assert!(
9369
        results.iter().any(|r| r.ok && r.name == "main"),
9370
        "{results:?}"
9371
    );
9372
    assert!(
9373
        parts.len() >= 3 && parts[0].starts_with("objects 1 of"),
9374
        "{parts:?}"
9375
    );
9376
    let back = Repo::clone(&origin.to_string_lossy(), &root.join("back")).unwrap();
9377
    for (i, f) in files.iter().enumerate() {
9378
        assert_eq!(&fs::read(root.join(format!("back/bin{i}.dat"))).unwrap(), f);
9379
    }
9380
    drop(back);
9381
}
9382
9383
/// oxygen#97: with `git.claim`, an import authors the importing identity's
9384
/// own commits (Git author email = its email, any case) with its key, and
9385
/// leaves anyone else's with the zero key; the history verifies as before.
9386
#[test]
9387
fn git_import_claims_your_own_commits() {
9388
    hermetic();
9389
    if std::process::Command::new("git")
9390
        .arg("--version")
9391
        .output()
9392
        .is_err()
9393
    {
9394
        eprintln!("git not installed; skipping");
9395
        return;
9396
    }
9397
    let dir = tempfile::tempdir().unwrap();
9398
    let root = dir.path();
9399
    let g = root.join("src.git");
9400
    fs::create_dir_all(&g).unwrap();
9401
    let git = |who: &str, args: &[&str]| {
9402
        let (name, email) = who.split_once(' ').unwrap();
9403
        let out = std::process::Command::new("git")
9404
            .arg("-C")
9405
            .arg(&g)
9406
            .args([
9407
                "-c",
9408
                &format!("user.name={name}"),
9409
                "-c",
9410
                &format!("user.email={email}"),
9411
                "-c",
9412
                "commit.gpgsign=false",
9413
            ])
9414
            .args(args)
9415
            .output()
9416
            .unwrap();
9417
        assert!(
9418
            out.status.success(),
9419
            "git {args:?}: {}",
9420
            String::from_utf8_lossy(&out.stderr)
9421
        );
9422
    };
9423
    git("Grace [email protected]", &["init", "-q", "-b", "main"]);
9424
    write(&g, "a.txt", b"a\n");
9425
    git("Grace [email protected]", &["add", "."]);
9426
    git("Grace [email protected]", &["commit", "-qm", "mine"]);
9427
    write(&g, "b.txt", b"b\n");
9428
    git("Ada [email protected]", &["add", "."]);
9429
    git("Ada [email protected]", &["commit", "-qm", "someone else's"]);
9430
9431
    let mut repo = Repo::init(&root.join("o")).unwrap();
9432
    let (key, _) = repo
9433
        .create_identity("Grace", "[email protected]", IdentityScope::Repo)
9434
        .unwrap();
9435
    repo.config.set("git.claim", "true").unwrap();
9436
    repo.save_config().unwrap();
9437
    let repo = Repo::open(&root.join("o")).unwrap();
9438
    repo.import_git(&g, "main").unwrap();
9439
    let v = repo.verify_git_import(&g, "main").unwrap();
9440
    assert!(v.mismatches.is_empty(), "{:?}", v.mismatches);
9441
    let heads = repo.bookmark_heads().unwrap();
9442
    let by_message: std::collections::HashMap<String, KeyId> = repo
9443
        .log_state(&heads)
9444
        .unwrap()
9445
        .into_iter()
9446
        .map(|e| {
9447
            (
9448
                e.change.message.lines().next().unwrap_or("").to_string(),
9449
                e.change.author,
9450
            )
9451
        })
9452
        .collect();
9453
    assert_eq!(by_message["mine"], key, "her own commit, any case of email");
9454
    assert_eq!(by_message["someone else's"], ObjectRef::ZERO, "not hers");
9455
}
9456
9457
/// oxygen#86: removing a remote removes all of it: every `remote.NAME.*`
9458
/// key (URL, token, CA), its tracking bookmarks, and nothing else.
9459
#[test]
9460
fn removing_a_remote_leaves_nothing_of_it() {
9461
    hermetic();
9462
    let dir = tempfile::tempdir().unwrap();
9463
    let origin = dir.path().join("origin");
9464
    Repo::init_bare_unbound(&origin).unwrap();
9465
    let main = dir.path().join("main");
9466
    let mut repo = Repo::init(&main).unwrap();
9467
    repo.config
9468
        .set("remote.origin.url", &origin.to_string_lossy())
9469
        .unwrap();
9470
    repo.config
9471
        .set("remote.origin.token", "secret-ish")
9472
        .unwrap();
9473
    repo.config
9474
        .set("remote.keep.url", &origin.to_string_lossy())
9475
        .unwrap();
9476
    repo.save_config().unwrap();
9477
    write(&main, "a.txt", b"a\n");
9478
    repo.commit("a", &[]).unwrap();
9479
    assert!(repo.push("origin", false).unwrap()[0].ok);
9480
    assert!(
9481
        repo.view().unwrap().remotes.contains_key("origin"),
9482
        "a tracking bookmark"
9483
    );
9484
9485
    repo.remove_remote("origin").unwrap();
9486
    let again = Repo::open(&main).unwrap();
9487
    assert!(
9488
        !again
9489
            .config
9490
            .repo_layer()
9491
            .keys()
9492
            .any(|k| k.starts_with("remote.origin.")),
9493
        "{:?}",
9494
        again.config.repo_layer()
9495
    );
9496
    assert!(!again.config.remotes.contains_key("origin"));
9497
    assert!(
9498
        !again.view().unwrap().remotes.contains_key("origin"),
9499
        "its tracking bookmarks go"
9500
    );
9501
    assert!(
9502
        again.config.remotes.contains_key("keep"),
9503
        "another remote stays"
9504
    );
9505
    let mut again = again;
9506
    assert!(
9507
        again.remove_remote("origin").is_err(),
9508
        "a second removal is refused"
9509
    );
9510
}
9511
9512
/// oxygenhub#126: a blob a host stored for itself (a job's artifact) is
9513
/// unreachable from history, so gc prunes it, unless the host names it:
9514
/// then it and its chunks stay, and it reads back whole.
9515
#[test]
9516
fn gc_keeps_the_blobs_a_host_names() {
9517
    hermetic();
9518
    let dir = tempfile::tempdir().unwrap();
9519
    let repo = Repo::init(dir.path()).unwrap();
9520
    write(dir.path(), "a.txt", b"a\n");
9521
    repo.commit("a", &[]).unwrap();
9522
    // Large enough to be several chunks.
9523
    let body: Vec<u8> = (0..400_000u32)
9524
        .flat_map(|i| (i.wrapping_mul(2654435761)).to_le_bytes())
9525
        .collect();
9526
    let kept = repo.store_blob(&body).unwrap();
9527
    let lost = repo.store_blob(b"an artifact nobody names").unwrap();
9528
    repo.gc_keeping(true, &[kept], &mut |_| {}).unwrap();
9529
    assert_eq!(repo.read_blob(&kept).unwrap(), body, "named: kept whole");
9530
    assert!(!repo.store().has(&lost), "not named: pruned");
9531
    repo.gc(true).unwrap();
9532
    assert!(!repo.store().has(&kept), "a plain gc prunes it");
9533
}
9534
9535
/// oxygen#99: undo in one workspace undoes that workspace's last command,
9536
/// never another workspace's, says what it undid, and goes further back
9537
/// when run again.
9538
#[test]
9539
fn undo_is_scoped_to_its_workspace() {
9540
    hermetic();
9541
    let dir = tempfile::tempdir().unwrap();
9542
    let root = dir.path().join("main");
9543
    let a = Repo::init(&root).unwrap();
9544
    write(&root, "base.txt", b"base\n");
9545
    let base = a.commit("base", &[]).unwrap();
9546
    a.bookmark_create("feature", None).unwrap();
9547
    let ws_dir = dir.path().join("ws");
9548
    let heads = a.resolve_heads("feature").unwrap();
9549
    let b = a
9550
        .workspace_add_on(&ws_dir, Some(&heads), Some("feature"))
9551
        .unwrap();
9552
9553
    // A commits on main, then B commits on feature: B's is the newest.
9554
    write(&root, "a.txt", b"a\n");
9555
    let ca = a.commit("from a", &[]).unwrap();
9556
    write(&ws_dir, "b.txt", b"b\n");
9557
    let cb = b.commit("from b", &[]).unwrap();
9558
9559
    // A's undo undoes A's commit and leaves B's.
9560
    let u = a.undo().unwrap();
9561
    assert_eq!(u.command, "oxy commit -m \"from a\"");
9562
    assert_eq!(u.others_kept, 1, "B's newer commit is left");
9563
    assert!(!u.changes.is_empty());
9564
    let view = a.view().unwrap();
9565
    // (Independent changes commute, so a bookmark's heads may hold base too.)
9566
    assert_eq!(a.heads_of(&view, "main").unwrap(), vec![base]);
9567
    assert!(
9568
        a.heads_of(&view, "feature").unwrap().contains(&cb),
9569
        "B's commit stands"
9570
    );
9571
    assert!(
9572
        a.store().get_change(&ca).is_ok(),
9573
        "the change itself is still in the store"
9574
    );
9575
    // A's working copy was clean, so its files followed; B's are untouched.
9576
    assert!(!root.join("a.txt").exists());
9577
    assert!(a.snapshot("oxy status").unwrap().statuses.is_empty());
9578
    assert!(ws_dir.join("b.txt").exists());
9579
9580
    // B's undo still finds B's own commit, under A's undo.
9581
    let u = b.undo().unwrap();
9582
    assert_eq!(u.command, "oxy commit -m \"from b\"");
9583
    assert!(!b
9584
        .heads_of(&b.view().unwrap(), "feature")
9585
        .unwrap()
9586
        .contains(&cb));
9587
    assert_eq!(
9588
        a.heads_of(&a.view().unwrap(), "main").unwrap(),
9589
        vec![base],
9590
        "A's undo stands"
9591
    );
9592
9593
    // A's next undo goes past the commit it already undid, to adding B's
9594
    // workspace: refused, since B has worked there since.
9595
    let e = a.undo().unwrap_err().to_string();
9596
    assert!(e.contains("the workspace at") && e.contains("ws"), "{e}");
9597
}
9598
9599
/// oxygen#99: two workspaces on one bookmark: an undo takes back only its
9600
/// own commit's head, and the other workspace's head stays.
9601
#[test]
9602
fn undo_on_a_shared_bookmark_keeps_the_other_workspaces_head() {
9603
    hermetic();
9604
    let dir = tempfile::tempdir().unwrap();
9605
    let root = dir.path().join("main");
9606
    let a = Repo::init(&root).unwrap();
9607
    write(&root, "base.txt", b"base\n");
9608
    a.commit("base", &[]).unwrap();
9609
    let ws_dir = dir.path().join("ws");
9610
    let b = a.workspace_add(&ws_dir, None).unwrap();
9611
    write(&root, "a.txt", b"a\n");
9612
    let ca = a.commit("from a", &[]).unwrap();
9613
    write(&ws_dir, "b.txt", b"b\n");
9614
    let cb = b.commit("from b", &[]).unwrap();
9615
    let u = a.undo().unwrap();
9616
    assert_eq!(u.command, "oxy commit -m \"from a\"");
9617
    let heads = a.heads_of(&a.view().unwrap(), "main").unwrap();
9618
    assert!(heads.contains(&cb) && !heads.contains(&ca), "{heads:?}");
9619
}
9620
9621
/// oxygen#99: an undo that would also take back what another workspace
9622
/// did since to the same bookmark is refused, naming it.
9623
#[test]
9624
fn undo_refuses_to_take_back_another_workspaces_work() {
9625
    hermetic();
9626
    let dir = tempfile::tempdir().unwrap();
9627
    let root = dir.path().join("main");
9628
    let a = Repo::init(&root).unwrap();
9629
    write(&root, "base.txt", b"base\n");
9630
    a.commit("base", &[]).unwrap();
9631
    let ws_dir = dir.path().join("ws");
9632
    let b = a.workspace_add(&ws_dir, None).unwrap();
9633
    // Both on main: A commits, then B builds on it, editing A's file.
9634
    write(&root, "a.txt", b"a\n");
9635
    a.commit("from a", &[]).unwrap();
9636
    b.refresh().unwrap();
9637
    let heads = b.resolve_heads("main").unwrap();
9638
    b.checkout(&heads, false, "oxy checkout").unwrap();
9639
    write(&ws_dir, "a.txt", b"a, then b\n");
9640
    b.commit("from b", &[]).unwrap();
9641
    let e = a.undo().unwrap_err().to_string();
9642
    assert!(
9643
        e.contains("bookmark main") && e.contains("builds on"),
9644
        "{e}"
9645
    );
9646
    assert!(e.contains("oxy op restore"), "{e}");
9647
}
9648
9649
/// oxygen#99: undoing a commit that was already pushed says so: the remote
9650
/// still has it.
9651
#[test]
9652
fn undo_says_when_the_commit_was_pushed() {
9653
    hermetic();
9654
    let dir = tempfile::tempdir().unwrap();
9655
    let root = dir.path();
9656
    Repo::init(&root.join("origin")).unwrap();
9657
    let url = root.join("origin").to_string_lossy().to_string();
9658
    let repo = Repo::clone(&url, &root.join("work"))
9659
        .unwrap()
9660
        .with_home(root.join("home"));
9661
    write(&root.join("work"), "a.txt", b"a\n");
9662
    repo.commit("a", &[]).unwrap();
9663
    assert!(repo.push("origin", false).unwrap()[0].ok);
9664
    // The push itself is passed over: the remote keeps what it was sent.
9665
    let u = repo.undo().unwrap();
9666
    assert_eq!(u.command, "oxy commit -m \"a\"");
9667
    assert_eq!(u.pushed, vec![("main".to_string(), "origin".to_string())]);
9668
}
9669
9670
/// oxygen#98: a new untracked file over snapshot.max-new-file-size is left
9671
/// out of the snapshot and named; tracked files and files already in the
9672
/// working copy are not.
9673
#[test]
9674
fn large_new_files_are_left_out_of_snapshots() {
9675
    hermetic();
9676
    let dir = tempfile::tempdir().unwrap();
9677
    let root = dir.path();
9678
    let mut repo = Repo::init(root).unwrap();
9679
    repo.config.max_new_file = 1024;
9680
    write(root, "small.txt", b"small\n");
9681
    write(root, "big.bin", &vec![0u8; 4096]);
9682
    let s = repo.snapshot("oxy status").unwrap();
9683
    let paths: Vec<_> = s.statuses.iter().map(|p| p.path.as_str()).collect();
9684
    assert_eq!(paths, ["small.txt"]);
9685
    assert_eq!(repo.skipped_large(), vec![("big.bin".to_string(), 4096)]);
9686
    repo.commit("small", &[]).unwrap();
9687
9688
    // A tracked file may grow past the limit.
9689
    write(root, "small.txt", &vec![b'x'; 4096]);
9690
    let s = repo.snapshot("oxy status").unwrap();
9691
    assert!(s.statuses.iter().any(|p| p.path == "small.txt"));
9692
    // With no limit the big file is taken in, and stays once it is.
9693
    repo.config.max_new_file = 0;
9694
    let s = repo.snapshot("oxy status").unwrap();
9695
    assert!(s.statuses.iter().any(|p| p.path == "big.bin"));
9696
    repo.config.max_new_file = 1024;
9697
    let s = repo.snapshot("oxy status").unwrap();
9698
    assert!(
9699
        s.statuses.iter().any(|p| p.path == "big.bin"),
9700
        "already in the working copy"
9701
    );
9702
    assert!(repo.skipped_large().is_empty());
9703
}
9704
9705
/// oxygen#98: a file only a past working-copy snapshot held is pruned once
9706
/// snapshots expire, and kept while they have not.
9707
#[test]
9708
fn gc_prunes_what_only_expired_snapshots_held() {
9709
    hermetic();
9710
    let dir = tempfile::tempdir().unwrap();
9711
    let root = dir.path();
9712
    let mut repo = Repo::init(root).unwrap();
9713
    repo.config.gc_grace_days = 0;
9714
    write(root, "a.txt", b"a\n");
9715
    repo.commit("a", &[]).unwrap();
9716
    let image: Vec<u8> = (0..200_000u32).map(|i| (i % 7) as u8).collect();
9717
    write(root, "image.tar", &image);
9718
    repo.snapshot("oxy status").unwrap();
9719
    std::fs::remove_file(root.join("image.tar")).unwrap();
9720
    repo.snapshot("oxy status").unwrap();
9721
    let blob = Repo::blob_ref(&image);
9722
    assert!(repo.store().has(&blob));
9723
    repo.gc(true).unwrap();
9724
    assert!(repo.store().has(&blob), "a recent snapshot keeps it");
9725
    repo.config.snapshot_retention_days = 0;
9726
    repo.gc(true).unwrap();
9727
    assert!(!repo.store().has(&blob), "an expired snapshot does not");
9728
    assert_eq!(
9729
        repo.file_at("a.txt", None).unwrap(),
9730
        b"a\n",
9731
        "committed files stay"
9732
    );
9733
}
9734
9735
/// oxygen#100: uncommitted work byte-for-byte what the bookmark switched to
9736
/// already has is no conflict: the switch goes through, nothing is lost,
9737
/// and other carried work still comes along.
9738
#[test]
9739
fn carrying_work_the_target_already_has_is_no_conflict() {
9740
    hermetic();
9741
    let dir = tempfile::tempdir().unwrap();
9742
    let root = dir.path();
9743
    let mut repo = Repo::init(root).unwrap();
9744
    write(root, "a.txt", b"one\n");
9745
    write(root, "b.txt", b"b\n");
9746
    repo.commit("one", &[]).unwrap();
9747
    repo.bookmark_create("landed", None).unwrap();
9748
    // On landed, a.txt becomes "two" (as a proposal landing would).
9749
    repo.bookmark_switch("landed", false).unwrap();
9750
    write(root, "a.txt", b"two\n");
9751
    repo.commit("two", &[]).unwrap();
9752
    repo.bookmark_switch("main", false).unwrap();
9753
    assert_eq!(std::fs::read(root.join("a.txt")).unwrap(), b"one\n");
9754
    // The same edit, uncommitted, on main; and another edit besides.
9755
    write(root, "a.txt", b"two\n");
9756
    write(root, "b.txt", b"b, edited\n");
9757
    let (_, carried) = repo.bookmark_switch_carry("landed").unwrap();
9758
    assert_eq!(
9759
        carried,
9760
        vec!["b.txt".to_string()],
9761
        "only the work landed lacks is carried"
9762
    );
9763
    assert_eq!(std::fs::read(root.join("a.txt")).unwrap(), b"two\n");
9764
    assert_eq!(std::fs::read(root.join("b.txt")).unwrap(), b"b, edited\n");
9765
    let s = repo.snapshot("oxy status").unwrap();
9766
    let paths: Vec<_> = s.statuses.iter().map(|p| p.path.as_str()).collect();
9767
    assert_eq!(paths, ["b.txt"]);
9768
9769
    // A real difference is still refused.
9770
    repo.bookmark_switch("main", true).unwrap();
9771
    write(root, "a.txt", b"three\n");
9772
    let e = repo
9773
        .bookmark_switch_carry("landed")
9774
        .unwrap_err()
9775
        .to_string();
9776
    assert!(e.contains("a.txt") && e.contains("--discard"), "{e}");
9777
}
9778
9779
/// oxygen#103: a full change hash as `--json` prints it, without `#`,
9780
/// resolves, so JSON output feeds back into commands.
9781
#[test]
9782
fn a_full_hash_resolves_without_its_hash_sign() {
9783
    hermetic();
9784
    let dir = tempfile::tempdir().unwrap();
9785
    let root = dir.path();
9786
    let repo = Repo::init(root).unwrap();
9787
    write(root, "a.txt", b"a\n");
9788
    let h = repo.commit("a", &[]).unwrap();
9789
    assert_eq!(repo.resolve_change(&h.to_hex()).unwrap(), h);
9790
    assert_eq!(repo.resolve_change(&format!("#{}", h.to_hex())).unwrap(), h);
9791
    assert!(repo
9792
        .resolve_change(&"0".repeat(64))
9793
        .unwrap_err()
9794
        .to_string()
9795
        .contains("no change matches"));
9796
}
9797
9798
#[test]
9799
fn a_pin_change_moves_only_the_pin() {
9800
    hermetic();
9801
    let dir = tempfile::tempdir().unwrap();
9802
    let root = dir.path();
9803
    let _lib_origin = Repo::init(&root.join("lib-origin")).unwrap();
9804
    let lib_url = root.join("lib-origin").to_string_lossy().to_string();
9805
    let lib = Repo::clone(&lib_url, &root.join("lib"))
9806
        .unwrap()
9807
        .with_home(root.join("home"));
9808
    write(&root.join("lib"), "lib.txt", b"v1\n");
9809
    lib.commit("lib v1", &[]).unwrap();
9810
    assert!(lib.push("origin", false).unwrap()[0].ok);
9811
    let _app_origin = Repo::init(&root.join("app-origin")).unwrap();
9812
    let app_dir = root.join("app");
9813
    let app = Repo::clone(&root.join("app-origin").to_string_lossy(), &app_dir)
9814
        .unwrap()
9815
        .with_home(root.join("home"));
9816
    write(&app_dir, "main.txt", b"app\n");
9817
    let pin1 = app.submodule_add(&lib_url, "libs/lib", None).unwrap();
9818
    let a1 = app.commit("app with lib", &[]).unwrap();
9819
    // The library moves on.
9820
    write(&root.join("lib"), "more.txt", b"v2\n");
9821
    let l2 = lib.commit("lib v2", &[]).unwrap();
9822
    let crate::subrepo::Pin::Oxy { repo, bookmark, .. } = pin1 else {
9823
        panic!("an Oxygen pin")
9824
    };
9825
    let pin2 = crate::subrepo::Pin::Oxy {
9826
        repo,
9827
        heads: vec![l2],
9828
        bookmark,
9829
    };
9830
    let author = app.store().get_change(&a1).unwrap().author;
9831
    let change = app
9832
        .build_pin_change(&[a1], "libs/lib", &pin2, "Move lib to v2", author)
9833
        .unwrap();
9834
    let mut state = app.load_state(&[a1]).unwrap();
9835
    state.add(change).unwrap();
9836
    let files = state.materialize().files;
9837
    assert_eq!(files["libs/lib"].kind, NodeKind::Subrepo);
9838
    let FileContent::Opaque { blobs } = &files["libs/lib"].content else {
9839
        panic!("a pin is opaque")
9840
    };
9841
    let read = crate::subrepo::Pin::decode(&app.read_blob(&blobs[0]).unwrap()).unwrap();
9842
    assert_eq!(read, pin2, "the new pin");
9843
    assert!(
9844
        matches!(&files["main.txt"].content, FileContent::Text { bytes, .. } if bytes.as_slice() == b"app\n"),
9845
        "nothing else changes"
9846
    );
9847
    // Only a subrepo's pin can be moved this way.
9848
    let e = app.build_pin_change(&[a1], "main.txt", &pin2, "x", author);
9849
    assert!(format!("{:?}", e.unwrap_err()).contains("not a subrepo"));
9850
    let e = app.build_pin_change(&[a1], "libs/none", &pin2, "x", author);
9851
    assert!(format!("{:?}", e.unwrap_err()).contains("does not exist"));
9852
}
9853
9854
/// oxygenhub#249: a handle reads the operation head once and keeps it,
9855
/// so one command or request never mixes two heads; another handle's
9856
/// operation shows only after `refresh`. Its own operations move it, and
9857
/// one recorded from the head it kept merges with what landed since, as
9858
/// any concurrent operation does.
9859
#[test]
9860
fn one_handle_keeps_one_head_until_it_refreshes() {
9861
    hermetic();
9862
    let dir = tempfile::tempdir().unwrap();
9863
    let root = dir.path();
9864
    let writer = Repo::init(root).unwrap();
9865
    write(root, "a.txt", b"one\n");
9866
    let h1 = writer.commit("one", &[]).unwrap();
9867
    let reader = Repo::open(root).unwrap();
9868
    let before = reader.view().unwrap();
9869
    assert_eq!(reader.bookmark_heads().unwrap(), vec![h1]);
9870
    write(root, "a.txt", b"two\n");
9871
    let h2 = writer.commit("two", &[]).unwrap();
9872
    assert_eq!(
9873
        writer.bookmark_heads().unwrap(),
9874
        vec![h2],
9875
        "its own operation"
9876
    );
9877
    assert_eq!(reader.view().unwrap(), before, "the head it read first");
9878
    assert_eq!(reader.bookmark_heads().unwrap(), vec![h1]);
9879
    reader.refresh().unwrap();
9880
    assert_eq!(reader.bookmark_heads().unwrap(), vec![h2]);
9881
9882
    // A handle recording from an older head merges with the newer one.
9883
    let stale = Repo::open(root).unwrap();
9884
    assert_eq!(stale.bookmark_heads().unwrap(), vec![h2]);
9885
    write(root, "a.txt", b"three\n");
9886
    let h3 = writer.commit("three", &[]).unwrap();
9887
    stale.bookmark_create("feature", Some(&[h1])).unwrap();
9888
    let view = stale.view().unwrap();
9889
    assert!(view.bookmarks.contains_key("feature"));
9890
    assert_eq!(
9891
        stale.bookmark_heads().unwrap(),
9892
        vec![h3],
9893
        "merged, not lost"
9894
    );
9895
    let fresh = Repo::open(root).unwrap();
9896
    assert_eq!(fresh.view().unwrap(), view);
9897
}
9898
9899
/// oxygenhub#249 over a store (a bucket's compare-and-swap): the same.
9900
#[test]
9901
fn over_a_store_one_handle_keeps_one_head() {
9902
    hermetic();
9903
    let backend = std::sync::Arc::new(crate::strata::MemoryStore::new());
9904
    crate::store::TEST_BACKEND.with(|t| *t.borrow_mut() = Some(backend.clone()));
9905
    let dir = tempfile::tempdir().unwrap();
9906
    let a = Repo::init(dir.path()).unwrap();
9907
    let (h0, _) = a.head_op().unwrap();
9908
    let b = Repo::open(dir.path()).unwrap();
9909
    assert_eq!(b.head_op().unwrap().0, h0);
9910
    let state = a.store.put_state(&StateObject::new(vec![])).unwrap();
9911
    let mut view = a.view().unwrap();
9912
    view.bookmarks.insert("x".into(), state);
9913
    let r = a.record_op(&[h0], "bookmark x", view).unwrap();
9914
    assert_eq!(a.head_op().unwrap().0, r);
9915
    assert_eq!(b.head_op().unwrap().0, h0, "b keeps its head");
9916
    b.refresh().unwrap();
9917
    assert_eq!(b.head_op().unwrap().0, r);
9918
    crate::store::TEST_BACKEND.with(|t| *t.borrow_mut() = None);
9919
}
9920
9921
/// oxygenhub#249: gc retires what it repacks rather than deleting it; a
9922
/// reader opened before reads on, then and after the next gc deletes the
9923
/// retired files once their hour is up. Younger ones are kept.
9924
#[test]
9925
fn gc_retires_and_a_later_gc_deletes_after_the_hour() {
9926
    hermetic();
9927
    let dir = tempfile::tempdir().unwrap();
9928
    let root = dir.path();
9929
    let repo = Repo::init(root).unwrap();
9930
    let mut heads = Vec::new();
9931
    for i in 0..4 {
9932
        write(root, &format!("f{i}.txt"), format!("{i}\n").as_bytes());
9933
        heads.push(repo.commit(&format!("c{i}"), &[]).unwrap());
9934
    }
9935
    let reader = Repo::open(root).unwrap();
9936
    assert_eq!(reader.log().unwrap().len(), 5);
9937
    let r = repo.gc(true).unwrap();
9938
    assert_eq!(r.retired, crate::store::RetiredReport::default());
9939
    assert_eq!(repo.store().loose_count().unwrap(), 0);
9940
    assert_eq!(reader.log().unwrap().len(), 5, "read on from what it had");
9941
    // Nothing is an hour old yet: a gc keeps it all.
9942
    let r = repo.gc(true).unwrap();
9943
    assert_eq!((r.retired.packs, r.retired.loose), (0, 0));
9944
    assert!(r.retired.kept > 0, "{r:?}");
9945
    write(root, "f9.txt", b"9\n");
9946
    heads.push(repo.commit("c9", &[]).unwrap());
9947
    crate::store::reader_tests::age_retired(
9948
        repo.store(),
9949
        crate::store::RETIRED_FOR + std::time::Duration::from_secs(60),
9950
    );
9951
    let r = repo.gc(true).unwrap();
9952
    assert!(r.retired.packs >= 1 && r.retired.loose > 0, "{r:?}");
9953
    assert_eq!(r.retired.kept, 0, "{r:?}");
9954
    let r = repo.gc(true).unwrap();
9955
    assert_eq!((r.retired.packs, r.retired.loose), (0, 0));
9956
    assert!(r.retired.kept > 0, "what the last gc retired is young");
9957
    // The reader opened before all of it still reads everything, from
9958
    // the packs it finds when what it loaded is gone.
9959
    assert_eq!(reader.log().unwrap().len(), 5);
9960
    for h in &heads[..4] {
9961
        reader.store().get_change(h).unwrap();
9962
    }
9963
    reader.refresh().unwrap();
9964
    assert_eq!(reader.log().unwrap().len(), 6);
9965
    let fresh = Repo::open(root).unwrap();
9966
    assert_eq!(
9967
        fresh.store().pack_count(),
9968
        1,
9969
        "retired packs are not loaded"
9970
    );
9971
}
9972
9973
/// oxygenhub#249: a repository opens when its store's pack listing names
9974
/// an index that is not there (deleted between the listing and the read).
9975
#[test]
9976
fn a_repository_opens_when_a_listed_index_is_gone() {
9977
    hermetic();
9978
    let backend = crate::store::reader_tests::racing(true);
9979
    let dyn_backend: std::sync::Arc<crate::store::Backend> = backend.clone();
9980
    crate::store::TEST_BACKEND.with(|t| *t.borrow_mut() = Some(dyn_backend));
9981
    let dir = tempfile::tempdir().unwrap();
9982
    let repo = Repo::init(dir.path()).unwrap();
9983
    write(dir.path(), "a.txt", b"a\n");
9984
    let h = repo.commit("a", &[]).unwrap();
9985
    repo.gc(true).unwrap();
9986
    let again = Repo::open(dir.path()).unwrap();
9987
    assert_eq!(again.store().pack_count(), 1);
9988
    assert_eq!(again.bookmark_heads().unwrap(), vec![h]);
9989
    // And when one is deleted between the listing and the read: a copy of
9990
    // the live pack, whose index goes as the store opens.
9991
    use crate::strata::Store as _;
9992
    let idx = backend
9993
        .list("pack-")
9994
        .unwrap()
9995
        .into_iter()
9996
        .map(|e| e.key)
9997
        .find(|k| k.ends_with(".idx") && k != "pack-0000.idx")
9998
        .unwrap();
9999
    let stem = idx.trim_end_matches(".idx");
10000
    for ext in ["pack", "idx"] {
10001
        let bytes = backend.get(&format!("{stem}.{ext}")).unwrap();
10002
        backend
10003
            .put_new(&format!("pack-copy.{ext}"), &bytes)
10004
            .unwrap();
10005
    }
10006
    *backend.doomed.lock().unwrap() = Some("pack-copy.idx".into());
10007
    let again = Repo::open(dir.path()).unwrap();
10008
    assert_eq!(again.store().pack_count(), 1);
10009
    assert_eq!(again.bookmark_heads().unwrap(), vec![h]);
10010
    assert!(!backend.has("pack-copy.idx").unwrap());
10011
    crate::store::TEST_BACKEND.with(|t| *t.borrow_mut() = None);
10012
}