OXYGENHUB
# f3811eb20bea oxygen / crates / oxy-core / src / repo / tests.rs
373.9 KiB · Rust · last changed Depth 0 takes no change, and a checkpoint is gathered in parallel (refs #137) 11 days ago source blame history raw
1
//! Tests for the repository layer.
2
3
use super::*;
4
use crate::protocol::SignedPolicy;
5
use crate::repo::{BisectStep, Selection};
6
7
/// Point `$OXY_HOME` at a throwaway directory once per test process so no
8
/// test reads or writes the developer's real user configuration or keys.
9
fn hermetic() {
10
    static ONCE: std::sync::Once = std::sync::Once::new();
11
    static DIR: std::sync::OnceLock<tempfile::TempDir> = std::sync::OnceLock::new();
12
    ONCE.call_once(|| {
13
        let d = tempfile::tempdir().unwrap();
14
        std::env::set_var("OXY_HOME", d.path());
15
        DIR.set(d).ok();
16
    });
17
}
18
19
fn write(root: &Path, rel: &str, content: &[u8]) {
20
    let p = root.join(rel);
21
    fs::create_dir_all(p.parent().unwrap()).unwrap();
22
    fs::write(p, content).unwrap();
23
}
24
25
fn statuses(s: &SnapshotResult) -> Vec<(String, ChangeStatus)> {
26
    s.statuses
27
        .iter()
28
        .map(|p| (p.path.clone(), p.status))
29
        .collect()
30
}
31
32
#[test]
33
fn init_snapshot_commit_log_undo() {
34
    hermetic();
35
    let dir = tempfile::tempdir().unwrap();
36
    let root = dir.path();
37
    let repo = Repo::init(root).unwrap();
38
    assert!(Repo::init(root).is_err());
39
    let ops = repo.op_log().unwrap();
40
    assert_eq!(ops.len(), 1);
41
    assert_eq!(ops[0].1.command, "oxy init");
42
43
    // Empty working copy: snapshot records no operation (spec §12.3).
44
    let s = repo.snapshot("oxy status").unwrap();
45
    assert!(!s.changed);
46
    assert_eq!(repo.op_log().unwrap().len(), 1);
47
48
    write(root, "src/main.rs", b"fn main() {}\n");
49
    write(root, "README.md", b"# Hello\n");
50
    write(root, ".oxyignore", b"/target\n");
51
    write(root, "target/junk.o", b"\0\0\0");
52
    let s = repo.snapshot("oxy status").unwrap();
53
    assert!(s.changed);
54
    assert_eq!(
55
        statuses(&s),
56
        vec![
57
            (".oxyignore".into(), ChangeStatus::Added),
58
            ("README.md".into(), ChangeStatus::Added),
59
            ("src/main.rs".into(), ChangeStatus::Added),
60
        ]
61
    );
62
    assert_eq!(repo.op_log().unwrap().len(), 2);
63
    // Snapshotting again with nothing changed records no op.
64
    let s2 = repo.snapshot("oxy status").unwrap();
65
    assert!(!s2.changed);
66
    assert_eq!(s2.wc_hash, s.wc_hash);
67
    assert_eq!(repo.op_log().unwrap().len(), 2);
68
69
    let h1 = repo.commit("Initial import", &[]).unwrap();
70
    let c1 = repo.store().get_change(&h1).unwrap();
71
    assert_eq!(c1.kind, ChangeKind::Normal);
72
    assert!(c1.deps.is_empty(), "first change has nothing to depend on");
73
    assert_eq!(repo.bookmark_heads().unwrap(), vec![h1]);
74
    let (wc_hash, wc) = repo.working_copy().unwrap();
75
    assert_eq!(wc.deps, vec![h1]);
76
    assert!(wc.edits.is_empty());
77
    assert!(repo.commit("nothing", &[]).is_err());
78
79
    // Modify one file, remove another, add a binary file.
80
    write(
81
        root,
82
        "src/main.rs",
83
        b"fn main() {\n    println!(\"hi\");\n}\n",
84
    );
85
    fs::remove_file(root.join("README.md")).unwrap();
86
    write(root, "logo.png", b"\x89PNG\0\0\x01");
87
    let s = repo.snapshot("oxy status").unwrap();
88
    assert_eq!(
89
        statuses(&s),
90
        vec![
91
            ("README.md".into(), ChangeStatus::Removed),
92
            ("logo.png".into(), ChangeStatus::Added),
93
            ("src/main.rs".into(), ChangeStatus::Modified),
94
        ]
95
    );
96
    assert_ne!(s.wc_hash, wc_hash);
97
    // The rewritten working copy keeps its ChangeId and depends on h1.
98
    assert_eq!(s.wc.change_id, wc.change_id);
99
    assert!(s.wc.deps.contains(&h1));
100
101
    let h2 = repo.commit("Second", &[]).unwrap();
102
    let c2 = repo.store().get_change(&h2).unwrap();
103
    assert_eq!(
104
        c2.deps,
105
        vec![h1],
106
        "everything it touches was introduced by h1"
107
    );
108
    assert_eq!(repo.bookmark_heads().unwrap(), vec![h2]);
109
110
    // The materialized head state matches the working copy.
111
    let st = repo.load_state(&[h2]).unwrap();
112
    let snap = st.materialize();
113
    assert!(!snap.is_conflicted());
114
    assert_eq!(
115
        snap.files.keys().cloned().collect::<Vec<_>>(),
116
        [".oxyignore", "logo.png", "src", "src/main.rs"]
117
    );
118
    assert!(
119
        matches!(&snap.files["src/main.rs"].content, FileContent::Text { bytes, .. } if bytes == b"fn main() {\n    println!(\"hi\");\n}\n")
120
    );
121
    assert!(snap.files["logo.png"].mode.opaque);
122
    if let FileContent::Opaque { blobs } = &snap.files["logo.png"].content {
123
        assert_eq!(repo.read_blob(&blobs[0]).unwrap(), b"\x89PNG\0\0\x01");
124
    } else {
125
        panic!("logo should be opaque");
126
    }
127
128
    // Log: newest first, working copy included.
129
    let log = repo.log().unwrap();
130
    assert_eq!(log.len(), 3);
131
    assert!(log[0].is_working_copy);
132
    assert_eq!(log[1].hash, h2);
133
    assert!(log[1].is_head);
134
    assert_eq!(log[2].hash, h1);
135
    let d = repo.describe_change(&h2).unwrap();
136
    assert!(d.contains("D README.md"), "{d}");
137
    assert!(d.contains("+    println!(\"hi\");"), "{d}");
138
    assert!(d.contains("-fn main() {}"), "{d}");
139
140
    // Resolution by prefix.
141
    assert_eq!(repo.resolve_change(&c2.change_id.short(6)).unwrap(), h2);
142
    assert_eq!(
143
        repo.resolve_change(&format!("#{}", h1.short(8))).unwrap(),
144
        h1
145
    );
146
    assert!(repo.resolve_change("zzzz").is_err());
147
148
    // Undo the commit: bookmark and working copy go back.
149
    repo.undo().unwrap();
150
    assert_eq!(repo.bookmark_heads().unwrap(), vec![h1]);
151
    let s = repo.snapshot("oxy status").unwrap();
152
    assert!(
153
        !s.changed,
154
        "files on disk still match the pre-commit working copy"
155
    );
156
    assert_eq!(s.statuses.len(), 3);
157
}
158
159
/// Make `main` conflicted: two commits on the same base that edit the same line.
160
fn conflicted_repo() -> (tempfile::TempDir, Repo, ChangeHash, ChangeHash, ChangeHash) {
161
    let dir = tempfile::tempdir().unwrap();
162
    let root = dir.path();
163
    let repo = Repo::init(root).unwrap();
164
    write(root, "f.txt", b"a\nb\nc\n");
165
    let h1 = repo.commit("base", &[]).unwrap();
166
    write(root, "f.txt", b"a\nB\nc\n");
167
    let h2 = repo.commit("upper", &[]).unwrap();
168
    repo.checkout(&[h1], false, "checkout").unwrap();
169
    write(root, "f.txt", b"a\nX\nc\n");
170
    let h3 = repo.commit("ex", &[]).unwrap();
171
    (dir, repo, h1, h2, h3)
172
}
173
174
#[test]
175
fn concurrent_edits_conflict_and_can_be_resolved() {
176
    hermetic();
177
    let (dir, repo, h1, h2, h3) = conflicted_repo();
178
    let root = dir.path();
179
    let heads: BTreeSet<_> = repo.bookmark_heads().unwrap().into_iter().collect();
180
    assert_eq!(heads, [h2, h3].into_iter().collect());
181
    let st = repo.load_state(&[h2, h3]).unwrap();
182
    assert!(st.materialize().is_conflicted());
183
184
    // Checking out main writes markers.
185
    let r = repo
186
        .checkout(&repo.bookmark_heads().unwrap(), false, "checkout main")
187
        .unwrap();
188
    assert!(r.conflicted);
189
    let marked = fs::read_to_string(root.join("f.txt")).unwrap();
190
    assert!(
191
        marked.starts_with("a\n<<<<<<< oxy conflict 1 of 1"),
192
        "{marked}"
193
    );
194
    assert!(
195
        marked.contains("B\n") && marked.contains("X\n") && marked.ends_with("end\nc\n"),
196
        "{marked}"
197
    );
198
    assert!(has_conflict_markers(marked.as_bytes()));
199
    // Untouched markers: clean working copy; commit has nothing to do.
200
    let s = repo.snapshot("status").unwrap();
201
    assert!(s.statuses.is_empty());
202
    assert!(!s.resolves);
203
204
    // Partially edited file that still has markers cannot be committed.
205
    write(root, "f.txt", marked.replace("B\n", "BB\n").as_bytes());
206
    let s = repo.snapshot("status").unwrap();
207
    assert_eq!(
208
        statuses(&s),
209
        vec![("f.txt".into(), ChangeStatus::ConflictEdited)]
210
    );
211
    assert!(repo.commit("no", &[]).is_err());
212
213
    // Resolve by keeping one side and adding a line elsewhere.
214
    write(root, "f.txt", b"a\nX\nc\nd\n");
215
    let s = repo.snapshot("status").unwrap();
216
    assert_eq!(statuses(&s), vec![("f.txt".into(), ChangeStatus::Resolved)]);
217
    assert!(s.resolves);
218
    let h4 = repo.commit("resolve", &[]).unwrap();
219
    let c4 = repo.store().get_change(&h4).unwrap();
220
    assert_eq!(c4.kind, ChangeKind::Resolution);
221
    let mut want = vec![h1, h2, h3];
222
    want.sort();
223
    assert_eq!(
224
        c4.deps, want,
225
        "a resolution depends on exactly the contributors and what it references"
226
    );
227
    assert_eq!(repo.bookmark_heads().unwrap(), vec![h4]);
228
    let snap = repo.load_state(&[h4]).unwrap().materialize();
229
    assert!(!snap.is_conflicted());
230
    assert!(
231
        matches!(&snap.files["f.txt"].content, FileContent::Text { bytes, .. } if bytes == b"a\nX\nc\nd\n")
232
    );
233
    assert!(!repo.snapshot("status").unwrap().changed);
234
    // A peer holding only h2 and h3 and receiving h4 sees the same result,
235
    // whatever order the changes arrive in.
236
    let mut st = State::new();
237
    for h in [h4, h3, h1, h2] {
238
        st.add_unchecked(repo.store().get_change(&h).unwrap());
239
    }
240
    st.validate().unwrap();
241
    assert!(
242
        matches!(&st.materialize().files["f.txt"].content, FileContent::Text { bytes, .. } if bytes == b"a\nX\nc\nd\n")
243
    );
244
}
245
246
#[test]
247
fn resolution_may_keep_both_sides_or_neither() {
248
    hermetic();
249
    let (dir, repo, _h1, _h2, _h3) = conflicted_repo();
250
    let root = dir.path();
251
    repo.checkout(&repo.bookmark_heads().unwrap(), false, "checkout main")
252
        .unwrap();
253
    // Keep both sides in a chosen order.
254
    write(root, "f.txt", b"a\nX\nB\nc\n");
255
    let h = repo.commit("both", &[]).unwrap();
256
    let snap = repo.load_state(&[h]).unwrap().materialize();
257
    assert!(!snap.is_conflicted());
258
    assert!(
259
        matches!(&snap.files["f.txt"].content, FileContent::Text { bytes, .. } if bytes == b"a\nX\nB\nc\n")
260
    );
261
    // Undo and instead drop the whole region.
262
    repo.undo().unwrap();
263
    write(root, "f.txt", b"a\nc\n");
264
    let h = repo.commit("neither", &[]).unwrap();
265
    let snap = repo.load_state(&[h]).unwrap().materialize();
266
    assert!(!snap.is_conflicted());
267
    assert!(
268
        matches!(&snap.files["f.txt"].content, FileContent::Text { bytes, .. } if bytes == b"a\nc\n")
269
    );
270
}
271
272
#[test]
273
fn name_conflict_resolved_by_removing_a_candidate() {
274
    hermetic();
275
    let dir = tempfile::tempdir().unwrap();
276
    let root = dir.path();
277
    let repo = Repo::init(root).unwrap();
278
    write(root, "keep.txt", b"k\n");
279
    let h1 = repo.commit("base", &[]).unwrap();
280
    write(root, "new.txt", b"one\n");
281
    repo.commit("one", &[]).unwrap();
282
    repo.checkout(&[h1], false, "checkout").unwrap();
283
    write(root, "new.txt", b"two\n");
284
    repo.commit("two", &[]).unwrap();
285
    let r = repo
286
        .checkout(&repo.bookmark_heads().unwrap(), false, "checkout main")
287
        .unwrap();
288
    assert!(r.conflicted);
289
    assert!(
290
        root.join("new.txt.oxy-conflict-1").exists()
291
            && root.join("new.txt.oxy-conflict-2").exists()
292
    );
293
    assert!(!root.join("new.txt").exists());
294
    // Candidate numbering follows change-hash order, so pick by content:
295
    // keep the "two" candidate under the real name and drop the other.
296
    let (keep, drop) = if fs::read(root.join("new.txt.oxy-conflict-1")).unwrap() == b"two\n" {
297
        (1, 2)
298
    } else {
299
        (2, 1)
300
    };
301
    fs::remove_file(root.join(format!("new.txt.oxy-conflict-{drop}"))).unwrap();
302
    fs::rename(
303
        root.join(format!("new.txt.oxy-conflict-{keep}")),
304
        root.join("new.txt"),
305
    )
306
    .unwrap();
307
    let h = repo.commit("pick two", &[]).unwrap();
308
    assert_eq!(
309
        repo.store().get_change(&h).unwrap().kind,
310
        ChangeKind::Resolution
311
    );
312
    // The resolution does not touch keep.txt, so it does not depend on h1;
313
    // the bookmark keeps both as heads and their union is the state.
314
    let heads: BTreeSet<_> = repo.bookmark_heads().unwrap().into_iter().collect();
315
    assert_eq!(heads, [h1, h].into_iter().collect());
316
    let snap = repo
317
        .load_state(&repo.bookmark_heads().unwrap())
318
        .unwrap()
319
        .materialize();
320
    assert!(!snap.is_conflicted(), "{:?}", snap.tree.conflicts);
321
    assert_eq!(
322
        snap.files.keys().cloned().collect::<Vec<_>>(),
323
        ["keep.txt", "new.txt"]
324
    );
325
    assert!(
326
        matches!(&snap.files["new.txt"].content, FileContent::Text { bytes, .. } if bytes == b"two\n")
327
    );
328
}
329
330
#[test]
331
fn identities_and_signed_commits() {
332
    hermetic();
333
    let dir = tempfile::tempdir().unwrap();
334
    let root = dir.path();
335
    let mut repo = Repo::init(root).unwrap().with_home(root.join("home"));
336
    write(root, "a.txt", b"a\n");
337
    let h0 = repo.commit("unsigned", &[]).unwrap();
338
    assert_eq!(repo.verify_change(&h0).unwrap(), SignatureStatus::Unsigned);
339
    assert_eq!(
340
        repo.store().get_change(&h0).unwrap().author,
341
        ObjectRef::ZERO
342
    );
343
344
    let (key, id) = repo
345
        .create_identity("Ada", "[email protected]", IdentityScope::Repo)
346
        .unwrap();
347
    assert_eq!(id.hash(), key);
348
    assert_eq!(repo.config.author_key, Some(key));
349
    // Config survives reopen; the secret key is found again.
350
    let reopened = Repo::open(root).unwrap().with_home(root.join("home"));
351
    assert_eq!(reopened.config.author_key, Some(key));
352
    assert_eq!(reopened.secret_key().unwrap().unwrap().0, key);
353
354
    // Default core.sign = seal: commits carry the author but no signature.
355
    write(root, "a.txt", b"a\nb\n");
356
    let h1 = repo.commit("authored", &[]).unwrap();
357
    assert_eq!(repo.store().get_change(&h1).unwrap().author, key);
358
    assert_eq!(repo.verify_change(&h1).unwrap(), SignatureStatus::Unsigned);
359
    // Signing later works too.
360
    repo.sign_change(&h1).unwrap();
361
    assert!(
362
        matches!(repo.verify_change(&h1).unwrap(), SignatureStatus::Valid { key: k, .. } if k == key)
363
    );
364
365
    repo.config.set("core.sign", "change").unwrap();
366
    repo.save_config().unwrap();
367
    write(root, "a.txt", b"a\nb\nc\n");
368
    let h2 = repo.commit("signed", &[]).unwrap();
369
    assert_eq!(
370
        repo.verify_change(&h2).unwrap(),
371
        SignatureStatus::Valid {
372
            key,
373
            name: "Ada".into(),
374
            email: "[email protected]".into(),
375
            sealed: false,
376
            revoked: false
377
        }
378
    );
379
380
    // A signature by a key that is not the author or a delegate is rejected
381
    // when the change names an author; an anonymous change (made before any
382
    // identity, author zero) is adopted by whoever signs it (spec §14.4).
383
    let other = SecretKey::generate();
384
    let other_id = other.identity("Mallory", "[email protected]", 0);
385
    let other_key = repo.store().put_identity(&other_id).unwrap();
386
    write(root, "a.txt", b"a\nb\nc\nd\n");
387
    repo.config.set("core.sign", "seal").unwrap();
388
    let h3 = repo.commit("ada's, unsigned", &[]).unwrap();
389
    let forged = other.sign(Domain::Change, &other_key, &h3);
390
    repo.store().put_signature(&h3, &forged).unwrap();
391
    assert!(
392
        matches!(repo.verify_change(&h3).unwrap(), SignatureStatus::Invalid(m) if m.contains("neither the author"))
393
    );
394
    let adopted = other.sign(Domain::Change, &other_key, &h0);
395
    repo.store().put_signature(&h0, &adopted).unwrap();
396
    assert!(
397
        matches!(repo.verify_change(&h0).unwrap(), SignatureStatus::Valid { name, .. } if name == "Mallory")
398
    );
399
400
    // Tampering with the stored signature invalidates it.
401
    let mut sig = repo.store().signatures(&h2).unwrap().remove(0);
402
    sig.ed[0] ^= 1;
403
    repo.store().put_signature(&h2, &sig).unwrap();
404
    assert!(matches!(
405
        repo.verify_change(&h2).unwrap(),
406
        SignatureStatus::Invalid(_)
407
    ));
408
409
    // Without the secret key, signing at commit fails cleanly.
410
    let no_keys = Repo::open(root).unwrap().with_home(root.join("nowhere"));
411
    write(root, "a.txt", b"z\n");
412
    assert!(no_keys.commit("cannot sign", &[]).is_err());
413
}
414
415
#[test]
416
fn checkout_moves_the_working_copy() {
417
    hermetic();
418
    let dir = tempfile::tempdir().unwrap();
419
    let root = dir.path();
420
    let repo = Repo::init(root).unwrap();
421
    write(root, "a.txt", b"one\n");
422
    write(root, "sub/deep/b.txt", b"b\n");
423
    let h1 = repo.commit("first", &[]).unwrap();
424
    write(root, "a.txt", b"two\n");
425
    fs::remove_file(root.join("sub/deep/b.txt")).unwrap();
426
    write(root, "bin.dat", &[0, 1, 2, 3]);
427
    let h2 = repo.commit("second", &[]).unwrap();
428
429
    let r = repo.checkout(&[h1], false, "oxy checkout").unwrap();
430
    assert_eq!(
431
        r,
432
        CheckoutReport {
433
            written: 2,
434
            removed: 1,
435
            removed_paths: vec!["bin.dat".into()],
436
            conflicted: false,
437
            notes: vec![],
438
            lacks: 1,
439
        }
440
    );
441
    assert_eq!(fs::read(root.join("a.txt")).unwrap(), b"one\n");
442
    assert_eq!(fs::read(root.join("sub/deep/b.txt")).unwrap(), b"b\n");
443
    assert!(!root.join("bin.dat").exists());
444
    let (_, wc) = repo.working_copy().unwrap();
445
    assert_eq!(wc.deps, vec![h1]);
446
    assert!(
447
        !repo.snapshot("status").unwrap().changed,
448
        "checkout leaves a clean working copy"
449
    );
450
    // The bookmark still points at h2.
451
    assert_eq!(repo.bookmark_heads().unwrap(), vec![h2]);
452
453
    // Dirty working copy refuses without --discard.
454
    write(root, "a.txt", b"dirty\n");
455
    assert!(repo.checkout(&[h2], false, "oxy checkout").is_err());
456
    let r = repo
457
        .checkout(&[h2], true, "oxy checkout --discard")
458
        .unwrap();
459
    assert_eq!(fs::read(root.join("a.txt")).unwrap(), b"two\n");
460
    assert_eq!(fs::read(root.join("bin.dat")).unwrap(), [0, 1, 2, 3]);
461
    assert!(!root.join("sub").exists(), "empty directories are pruned");
462
    assert_eq!(r.removed, 1);
463
    assert!(!repo.snapshot("status").unwrap().changed);
464
465
    // Refuses to write through a symlinked directory.
466
    #[cfg(unix)]
467
    {
468
        fs::remove_dir_all(root.join("sub")).ok();
469
        std::os::unix::fs::symlink("/tmp", root.join("sub")).unwrap();
470
        assert!(repo.checkout(&[h1], true, "oxy checkout").is_err());
471
    }
472
}
473
474
#[test]
475
fn large_files_are_chunked_and_read_back() {
476
    hermetic();
477
    let dir = tempfile::tempdir().unwrap();
478
    let repo = Repo::init(dir.path()).unwrap();
479
    let mut big = vec![0u8; 700 * 1024];
480
    for (i, b) in big.iter_mut().enumerate() {
481
        *b = (i as u32).wrapping_mul(2654435761).to_le_bytes()[0];
482
    }
483
    let r = repo.store_blob(&big).unwrap();
484
    let blob = Blob::decode(&repo.store().get_typed(&r, ObjectType::Blob).unwrap()).unwrap();
485
    assert!(blob.chunks.len() >= 3, "{}", blob.chunks.len());
486
    assert_eq!(repo.read_blob(&r).unwrap(), big);
487
    assert_eq!(Repo::blob_ref(&big), r);
488
}
489
490
#[test]
491
fn clone_push_pull_with_seals_and_attestations() {
492
    hermetic();
493
    let dir = tempfile::tempdir().unwrap();
494
    let root = dir.path();
495
    let origin_path = root.join("origin");
496
    let origin = Repo::init(&origin_path).unwrap();
497
    let origin_url = origin_path.to_string_lossy().to_string();
498
499
    // A clones, creates an identity (default core.sign = seal), commits, pushes.
500
    let mut a = Repo::clone(&origin_url, &root.join("a"))
501
        .unwrap()
502
        .with_home(root.join("home-a"));
503
    assert_eq!(a.id().unwrap(), origin.id().unwrap());
504
    let (key_a, _) = a
505
        .create_identity("Ada", "[email protected]", IdentityScope::Repo)
506
        .unwrap();
507
    write(&root.join("a"), "f.txt", b"a\n");
508
    let h1 = a.commit("first", &[]).unwrap();
509
    let results = a.push("origin", false).unwrap();
510
    origin.refresh().unwrap();
511
    assert!(results[0].ok, "{}", results[0].reason);
512
    assert_eq!(origin.bookmark_heads().unwrap(), vec![h1]);
513
    // The change was sealed at push and the reference attested.
514
    assert!(
515
        matches!(origin.authenticate_change(&h1).unwrap(), SignatureStatus::Valid { key, sealed: true, .. } if key == key_a)
516
    );
517
    assert_eq!(
518
        origin.verify_change(&h1).unwrap(),
519
        SignatureStatus::Unsigned
520
    );
521
    let serial_of = |att: &SignedAttest| match att.attest.body {
522
        AttestBody::Ref { serial, .. } => serial,
523
        _ => unreachable!(),
524
    };
525
    let (_, att) = origin.latest_ref_attest("main").unwrap().unwrap();
526
    // A bookmark new to the remote starts at the clock (past any deleted
527
    // namesake's serial); later updates count up from there.
528
    let first = serial_of(&att);
529
    assert!(first > 1_000_000_000_000, "{first}");
530
    let again = a.push("origin", false).unwrap();
531
    origin.refresh().unwrap();
532
    assert!(again[0].ok && again[0].reason.contains("up to date"));
533
    let (_, att) = origin.latest_ref_attest("main").unwrap().unwrap();
534
    assert_eq!(serial_of(&att), first, "a no-op push does not attest again");
535
536
    // B clones and sees the file and the seal.
537
    let b = Repo::clone(&origin_url, &root.join("b")).unwrap();
538
    assert_eq!(fs::read(root.join("b/f.txt")).unwrap(), b"a\n");
539
    assert_eq!(b.bookmark_heads().unwrap(), vec![h1]);
540
    assert!(matches!(
541
        b.authenticate_change(&h1).unwrap(),
542
        SignatureStatus::Valid { sealed: true, .. }
543
    ));
544
545
    // B (no identity) commits and pushes unsigned; the unverified origin accepts.
546
    write(&root.join("b"), "f.txt", b"a\nb\n");
547
    let h2 = b.commit("second", &[]).unwrap();
548
    assert!(b.push("origin", false).unwrap()[0].ok);
549
    origin.refresh().unwrap();
550
    assert_eq!(origin.bookmark_heads().unwrap(), vec![h2]);
551
552
    // A commits an independent change; push is refused until A pulls.
553
    write(&root.join("a"), "g.txt", b"g\n");
554
    let h3 = a.commit("third", &[]).unwrap();
555
    assert!(a.push("origin", false).is_err());
556
    let pr = a.pull("origin").unwrap();
557
    assert!(pr.changed && pr.checked_out);
558
    let mut want = vec![h2, h3];
559
    want.sort();
560
    assert_eq!(pr.heads, want);
561
    assert_eq!(fs::read(root.join("a/f.txt")).unwrap(), b"a\nb\n");
562
    assert_eq!(fs::read(root.join("a/g.txt")).unwrap(), b"g\n");
563
    let results = a.push("origin", false).unwrap();
564
    origin.refresh().unwrap();
565
    assert!(results[0].ok, "{}", results[0].reason);
566
    let mut origin_heads = origin.bookmark_heads().unwrap();
567
    origin_heads.sort();
568
    assert_eq!(origin_heads, want);
569
    let (_, att) = origin.latest_ref_attest("main").unwrap().unwrap();
570
    assert_eq!(serial_of(&att), first + 1);
571
572
    // B pulls and ends up identical.
573
    let pr = b.pull("origin").unwrap();
574
    assert_eq!(pr.heads, want);
575
    assert_eq!(fs::read(root.join("b/g.txt")).unwrap(), b"g\n");
576
    assert!(!b.snapshot("status").unwrap().changed);
577
578
    // Concurrent edits of the same line: the union is a reified conflict.
579
    write(&root.join("a"), "f.txt", b"a\nA\n");
580
    a.commit("a-edit", &[]).unwrap();
581
    a.push("origin", false).unwrap();
582
    origin.refresh().unwrap();
583
    write(&root.join("b"), "f.txt", b"a\nB\n");
584
    b.commit("b-edit", &[]).unwrap();
585
    let pr = b.pull("origin").unwrap();
586
    assert!(pr.changed && pr.checked_out);
587
    let text = fs::read_to_string(root.join("b/f.txt")).unwrap();
588
    assert!(text.contains("<<<<<<< oxy conflict"), "{text}");
589
    write(&root.join("b"), "f.txt", b"a\nAB\n");
590
    let hr = b.commit("resolve", &[]).unwrap();
591
    assert_eq!(
592
        b.store().get_change(&hr).unwrap().kind,
593
        ChangeKind::Resolution
594
    );
595
    assert!(b.push("origin", false).unwrap()[0].ok);
596
    origin.refresh().unwrap();
597
    a.pull("origin").unwrap();
598
    assert_eq!(fs::read(root.join("a/f.txt")).unwrap(), b"a\nAB\n");
599
    // The resolution depends on the conflicting edits, but nothing depends
600
    // on "third" (it only added g.txt), so it stays a head beside it.
601
    let mut want = vec![hr, h3];
602
    want.sort();
603
    assert_eq!(a.bookmark_heads().unwrap(), want);
604
    assert!(!a.load_state(&want).unwrap().materialize().is_conflicted());
605
}
606
607
#[test]
608
fn receive_push_rejects_bad_updates() {
609
    hermetic();
610
    let dir = tempfile::tempdir().unwrap();
611
    let root = dir.path();
612
    let origin = Repo::init(&root.join("origin")).unwrap();
613
    let url = root.join("origin").to_string_lossy().to_string();
614
    let mut a = Repo::clone(&url, &root.join("a"))
615
        .unwrap()
616
        .with_home(root.join("home"));
617
    let (key, _) = a
618
        .create_identity("Ada", "a@b", IdentityScope::Repo)
619
        .unwrap();
620
    write(&root.join("a"), "f.txt", b"x\n");
621
    let h1 = a.commit("one", &[]).unwrap();
622
    assert!(a.push("origin", false).unwrap()[0].ok);
623
    let empty = origin.store().put_state(&StateObject::new(vec![])).unwrap();
624
    let s1 = origin
625
        .store()
626
        .put_state(&StateObject::new(vec![h1]))
627
        .unwrap();
628
629
    // Missing head.
630
    let ghost = origin
631
        .store()
632
        .put_state(&StateObject::new(vec![ObjectRef([9; 32])]))
633
        .unwrap();
634
    let r = origin
635
        .receive_push(
636
            Bundle::default(),
637
            vec![RefUpdate {
638
                name: "main".into(),
639
                old_state: s1,
640
                new_state: ghost,
641
                force: false,
642
                attestation: None,
643
            }],
644
            None,
645
            vec![],
646
        )
647
        .unwrap();
648
    assert!(
649
        !r[0].ok && r[0].reason.contains("missing"),
650
        "{}",
651
        r[0].reason
652
    );
653
654
    // Stale old_state.
655
    let r = origin
656
        .receive_push(
657
            Bundle::default(),
658
            vec![RefUpdate {
659
                name: "main".into(),
660
                old_state: empty,
661
                new_state: s1,
662
                force: false,
663
                attestation: None,
664
            }],
665
            None,
666
            vec![],
667
        )
668
        .unwrap();
669
    assert!(!r[0].ok && r[0].reason.contains("stale"), "{}", r[0].reason);
670
671
    // Non-fast-forward without force is refused; with force it passes.
672
    let r = origin
673
        .receive_push(
674
            Bundle::default(),
675
            vec![RefUpdate {
676
                name: "main".into(),
677
                old_state: s1,
678
                new_state: empty,
679
                force: false,
680
                attestation: None,
681
            }],
682
            None,
683
            vec![],
684
        )
685
        .unwrap();
686
    assert!(
687
        !r[0].ok && r[0].reason.contains("fast-forward"),
688
        "{}",
689
        r[0].reason
690
    );
691
    let r = origin
692
        .receive_push(
693
            Bundle::default(),
694
            vec![RefUpdate {
695
                name: "main".into(),
696
                old_state: s1,
697
                new_state: empty,
698
                force: true,
699
                attestation: None,
700
            }],
701
            None,
702
            vec![],
703
        )
704
        .unwrap();
705
    assert!(r[0].ok);
706
    assert_eq!(origin.bookmark_heads().unwrap(), vec![]);
707
708
    // Attestation with a stale serial is a rollback and is refused.
709
    let sa = a
710
        .sign_attest(&Attest {
711
            repo: a.id().unwrap(),
712
            hlc: Hlc::now(),
713
            body: AttestBody::Ref {
714
                name: "main".into(),
715
                old_state: empty,
716
                new_state: s1,
717
                serial: 1,
718
            },
719
        })
720
        .unwrap();
721
    let r = origin
722
        .receive_push(
723
            Bundle::default(),
724
            vec![RefUpdate {
725
                name: "main".into(),
726
                old_state: empty,
727
                new_state: s1,
728
                force: false,
729
                attestation: Some(sa.clone()),
730
            }],
731
            None,
732
            vec![],
733
        )
734
        .unwrap();
735
    assert!(
736
        !r[0].ok && r[0].reason.contains("serial"),
737
        "{}",
738
        r[0].reason
739
    );
740
    // An attestation for a different update is refused too.
741
    let sa2 = a
742
        .sign_attest(&Attest {
743
            repo: a.id().unwrap(),
744
            hlc: Hlc::now(),
745
            body: AttestBody::Ref {
746
                name: "main".into(),
747
                old_state: s1,
748
                new_state: empty,
749
                serial: 5,
750
            },
751
        })
752
        .unwrap();
753
    let r = origin
754
        .receive_push(
755
            Bundle::default(),
756
            vec![RefUpdate {
757
                name: "main".into(),
758
                old_state: empty,
759
                new_state: s1,
760
                force: false,
761
                attestation: Some(sa2),
762
            }],
763
            None,
764
            vec![],
765
        )
766
        .unwrap();
767
    assert!(
768
        !r[0].ok && r[0].reason.contains("describe"),
769
        "{}",
770
        r[0].reason
771
    );
772
    let _ = key;
773
}
774
775
#[test]
776
fn user_config_supplies_defaults_and_clones_sign() {
777
    hermetic();
778
    let dir = tempfile::tempdir().unwrap();
779
    let root = dir.path();
780
    let home = root.join("home");
781
    let origin = Repo::init(&root.join("origin")).unwrap();
782
    let url = root.join("origin").to_string_lossy().to_string();
783
784
    // Identity at user scope: the repository file stays free of author keys.
785
    let mut a = Repo::init(&root.join("a")).unwrap().with_home(&home);
786
    let (key, _) = a
787
        .create_identity("Ada", "[email protected]", IdentityScope::User)
788
        .unwrap();
789
    assert!(!a.config.repo_layer().contains_key("author.key"));
790
    assert_eq!(a.config.author_key, Some(key));
791
    assert!(home.join("config.toml").exists());
792
    a.set_user_config("core.sign", "change").unwrap();
793
    assert!(a.config.sign_changes);
794
795
    // Repository settings override user settings and are the only ones saved.
796
    a.config.set("core.sign", "seal").unwrap();
797
    a.save_config().unwrap();
798
    let again = Repo::open(&root.join("a")).unwrap().with_home(&home);
799
    assert!(!again.config.sign_changes);
800
    assert_eq!(again.config.author_key, Some(key));
801
    assert_eq!(
802
        read_config_file(&root.join("a/.oxy/config"))
803
            .unwrap()
804
            .get("core.sign")
805
            .map(String::as_str),
806
        Some("seal")
807
    );
808
809
    // A fresh clone made by this user signs with the user-level identity,
810
    // even though the clone's store has never seen the identity object.
811
    let b = Repo::clone(&url, &root.join("b")).unwrap().with_home(&home);
812
    assert!(b.config.sign_changes);
813
    write(&root.join("b"), "f.txt", b"f\n");
814
    let h = b.commit("signed from a clone", &[]).unwrap();
815
    assert!(
816
        matches!(b.verify_change(&h).unwrap(), SignatureStatus::Valid { key: k, .. } if k == key)
817
    );
818
    assert!(b.push("origin", false).unwrap()[0].ok);
819
    assert!(matches!(
820
        origin.verify_change(&h).unwrap(),
821
        SignatureStatus::Valid { .. }
822
    ));
823
}
824
825
#[test]
826
fn format1_repositories_are_migrated_on_open() {
827
    hermetic();
828
    use crate::oplog::{Format1Op, Format1View};
829
    let dir = tempfile::tempdir().unwrap();
830
    let root = dir.path();
831
    let repo = Repo::init(root).unwrap();
832
    write(root, "a.txt", b"a\n");
833
    let h1 = repo.commit("one", &[]).unwrap();
834
    let (wc_hash, _) = repo.working_copy().unwrap();
835
    // Rewrite the op log the way format 1 stored it: two ops, head lists.
836
    let mut v1 = Format1View::default();
837
    v1.bookmarks.insert("main".into(), vec![]);
838
    v1.workspaces.insert(repo.workspace(), wc_hash);
839
    let init = Format1Op {
840
        parents: vec![],
841
        hlc: Hlc::default(),
842
        command: "oxy init".into(),
843
        view: v1.clone(),
844
    };
845
    let init_ref = repo.store().put(ObjectType::Op, &init.encode()).unwrap();
846
    v1.bookmarks.insert("main".into(), vec![h1]);
847
    let commit = Format1Op {
848
        parents: vec![init_ref],
849
        hlc: Hlc::default(),
850
        command: "oxy commit".into(),
851
        view: v1,
852
    };
853
    let commit_ref = repo.store().put(ObjectType::Op, &commit.encode()).unwrap();
854
    write_atomic(&root.join(".oxy/ops/head"), commit_ref.to_hex().as_bytes()).unwrap();
855
    write_atomic(&root.join(".oxy/format"), FORMAT1_LINE.as_bytes()).unwrap();
856
    drop(repo);
857
858
    let repo = Repo::open(root).unwrap();
859
    assert_eq!(
860
        fs::read_to_string(root.join(".oxy/format")).unwrap(),
861
        FORMAT_LINE
862
    );
863
    assert_eq!(repo.bookmark_heads().unwrap(), vec![h1]);
864
    let ops = repo.op_log().unwrap();
865
    assert_eq!(
866
        ops.iter()
867
            .map(|(_, o)| o.command.as_str())
868
            .collect::<Vec<_>>(),
869
        ["oxy commit", "oxy init"]
870
    );
871
    assert_eq!(repo.heads_of(&ops[1].1.view, "main").unwrap(), vec![]);
872
    assert!(!repo.snapshot("status").unwrap().changed);
873
    // Reopening again is a no-op.
874
    assert_eq!(Repo::open(root).unwrap().op_log().unwrap().len(), 2);
875
}
876
877
#[test]
878
fn undo_skips_snapshot_operations() {
879
    hermetic();
880
    let dir = tempfile::tempdir().unwrap();
881
    let root = dir.path();
882
    let repo = Repo::init(root).unwrap();
883
    write(root, "a.txt", b"a\n");
884
    let h1 = repo.commit("a", &[]).unwrap();
885
    // A later command snapshots new edits on top of the commit.
886
    write(root, "b.txt", b"b\n");
887
    let s = repo.snapshot("oxy status").unwrap();
888
    assert!(s.changed);
889
    assert!(repo.head_op().unwrap().1.is_snapshot());
890
    assert_eq!(repo.last_command().unwrap().command, "oxy commit -m \"a\"");
891
    // Undo must undo the commit, not the snapshot.
892
    repo.undo().unwrap();
893
    assert_eq!(repo.bookmark_heads().unwrap(), vec![]);
894
    let s = repo.snapshot("oxy status").unwrap();
895
    let paths: Vec<_> = s.statuses.iter().map(|p| p.path.as_str()).collect();
896
    assert_eq!(
897
        paths,
898
        ["a.txt", "b.txt"],
899
        "both files are back in the working copy"
900
    );
901
    assert!(repo.store().get_change(&h1).unwrap().deps.is_empty());
902
    // Only snapshots remain above `init`, so there is nothing left to undo.
903
    assert_eq!(repo.last_command().unwrap().command, "oxy init");
904
    assert!(repo.undo().is_err());
905
}
906
907
#[test]
908
fn independent_changes_commute_and_make_multiple_heads() {
909
    hermetic();
910
    let dir = tempfile::tempdir().unwrap();
911
    let root = dir.path();
912
    let repo = Repo::init(root).unwrap();
913
    write(root, "a.txt", b"a\n");
914
    let h1 = repo.commit("a", &[]).unwrap();
915
    write(root, "b.txt", b"b\n");
916
    let h2 = repo.commit("b", &[]).unwrap();
917
    let c2 = repo.store().get_change(&h2).unwrap();
918
    assert!(c2.deps.is_empty(), "b.txt touches nothing from h1");
919
    let mut heads = repo.bookmark_heads().unwrap();
920
    heads.sort();
921
    let mut want = vec![h1, h2];
922
    want.sort();
923
    assert_eq!(heads, want);
924
    // Editing a.txt depends on h1 only.
925
    write(root, "a.txt", b"a\na2\n");
926
    let h3 = repo.commit("a2", &[]).unwrap();
927
    assert_eq!(repo.store().get_change(&h3).unwrap().deps, vec![h1]);
928
    let heads: BTreeSet<_> = repo.bookmark_heads().unwrap().into_iter().collect();
929
    assert_eq!(heads, [h2, h3].into_iter().collect());
930
    // Explicit dependency.
931
    write(root, "c.txt", b"c\n");
932
    let h4 = repo.commit("c", &[h2]).unwrap();
933
    assert_eq!(repo.store().get_change(&h4).unwrap().deps, vec![h2]);
934
}
935
936
#[test]
937
fn mode_change_and_text_binary_switch() {
938
    hermetic();
939
    let dir = tempfile::tempdir().unwrap();
940
    let root = dir.path();
941
    let repo = Repo::init(root).unwrap();
942
    write(root, "run.sh", b"#!/bin/sh\n");
943
    repo.commit("add script", &[]).unwrap();
944
    #[cfg(unix)]
945
    {
946
        use std::os::unix::fs::PermissionsExt;
947
        fs::set_permissions(root.join("run.sh"), fs::Permissions::from_mode(0o755)).unwrap();
948
        let s = repo.snapshot("status").unwrap();
949
        assert_eq!(
950
            statuses(&s),
951
            vec![("run.sh".into(), ChangeStatus::ModeChanged)]
952
        );
953
        let h = repo.commit("exec", &[]).unwrap();
954
        let snap = repo.load_state(&[h]).unwrap().materialize();
955
        assert!(snap.files["run.sh"].mode.exec);
956
    }
957
    // Text → binary → text.
958
    write(root, "run.sh", b"\0binary");
959
    let h = repo.commit("binary", &[]).unwrap();
960
    let snap = repo.load_state(&[h]).unwrap().materialize();
961
    assert!(snap.files["run.sh"].mode.opaque);
962
    write(root, "run.sh", b"text again\n");
963
    let h = repo.commit("text", &[]).unwrap();
964
    let snap = repo.load_state(&[h]).unwrap().materialize();
965
    assert!(!snap.files["run.sh"].mode.opaque);
966
    assert!(
967
        matches!(&snap.files["run.sh"].content, FileContent::Text { bytes, .. } if bytes == b"text again\n")
968
    );
969
    assert!(!snap.is_conflicted());
970
}
971
972
/// oxygen#87: a binary file given new contents and the executable bit in
973
/// one commit kept the contents and lost the bit.
974
#[cfg(unix)]
975
#[test]
976
fn a_binary_file_changed_and_made_executable_at_once_keeps_both() {
977
    use std::os::unix::fs::PermissionsExt;
978
    hermetic();
979
    let dir = tempfile::tempdir().unwrap();
980
    let root = dir.path();
981
    let repo = Repo::init(root).unwrap();
982
    write(root, "tool.exe", b"MZ\0one");
983
    repo.commit("add", &[]).unwrap();
984
    write(root, "tool.exe", b"MZ\0two");
985
    fs::set_permissions(root.join("tool.exe"), fs::Permissions::from_mode(0o755)).unwrap();
986
    let h = repo.commit("update and +x", &[]).unwrap();
987
    let snap = repo.load_state(&[h]).unwrap().materialize();
988
    let f = &snap.files["tool.exe"];
989
    assert!(f.mode.opaque && f.mode.exec, "{:?}", f.mode);
990
    assert!(
991
        repo.snapshot("status").unwrap().statuses.is_empty(),
992
        "nothing left to commit"
993
    );
994
}
995
996
/// Keyless step 4 (oxygenhub#241): an agent signing with a short-lived
997
/// key whose certificate an issuer gave pushes when the policy grants its
998
/// subject, and a fetch accepts what it attested; an expired certificate,
999
/// or a subject the policy does not grant, may not move the bookmark.
1000
#[test]
1001
fn a_certified_key_pushes_under_a_subject_grant() {
1002
    use crate::cert::{Certificate, SignedCertificate};
1003
    use crate::identity::Scope;
1004
    hermetic();
1005
    let dir = tempfile::tempdir().unwrap();
1006
    let root = dir.path();
1007
    let _origin = Repo::init(&root.join("origin")).unwrap();
1008
    let url = root.join("origin").to_string_lossy().to_string();
1009
    let mut a = Repo::clone(&url, &root.join("a"))
1010
        .unwrap()
1011
        .with_home(root.join("home-a"));
1012
    a.create_identity("Ada", "[email protected]", IdentityScope::User)
1013
        .unwrap();
1014
    write(&root.join("a"), "a.txt", b"a\n");
1015
    a.commit("a", &[]).unwrap();
1016
    a.policy_init().unwrap();
1017
    assert!(a.push("origin", false).unwrap().iter().all(|r| r.ok));
1018
    let hub_sk = SecretKey::generate();
1019
    let hub = hub_sk.identity("hub", "[email protected]", 1);
1020
    a.policy_grant_subject(
1021
        "agent:claude@ada",
1022
        hub.clone(),
1023
        Scope::CHANGES | Scope::REFS,
1024
        None,
1025
    )
1026
    .unwrap();
1027
    assert!(a
1028
        .push("origin", false)
1029
        .unwrap()
1030
        .iter()
1031
        .any(|r| r.name == "policy" && r.ok));
1032
1033
    let now = Hlc::now().wall_ms;
1034
    // An agent repository whose key the hub certified for `subject`, from
1035
    // `from` to `to`.
1036
    let agent = |name: &str, subject: &str, from: u64, to: u64| {
1037
        let mut r = Repo::clone(&url, &root.join(name))
1038
            .unwrap()
1039
            .with_home(root.join(format!("home-{name}")));
1040
        let (_, id) = r
1041
            .create_identity(name, "[email protected]", IdentityScope::User)
1042
            .unwrap();
1043
        let cert = SignedCertificate::sign(
1044
            Certificate {
1045
                key: id,
1046
                issuer: hub.hash(),
1047
                subject: subject.into(),
1048
                claims: vec![],
1049
                scope: Scope::CHANGES | Scope::REFS,
1050
                not_before: from,
1051
                expires: to,
1052
                grant: None,
1053
            },
1054
            &hub,
1055
            &hub_sk,
1056
        );
1057
        r.store().put_identity(&hub).unwrap();
1058
        r.store().put_certificate(&cert).unwrap();
1059
        write(&root.join(name), &format!("{name}.txt"), b"agent work\n");
1060
        r.commit("work", &[]).unwrap();
1061
        r
1062
    };
1063
1064
    let claude = agent("claude", "agent:claude@ada", now - 60_000, now + 600_000);
1065
    let r = claude.push("origin", false).unwrap();
1066
    assert!(r.iter().all(|x| x.ok), "{r:?}");
1067
    // Ada's fetch accepts the bookmark the certified key attested.
1068
    a.pull("origin").unwrap();
1069
    assert!(a.bookmark_heads().unwrap().iter().any(|h| a
1070
        .store()
1071
        .get_change(h)
1072
        .map(|c| c.message == "work")
1073
        .unwrap_or(false)));
1074
1075
    // Step 4c: a host with an acceptor key records when it accepted the
1076
    // certified update and serves it; a fetch checks the certificate at
1077
    // that time only when the certificate's issuer signed it for exactly
1078
    // this attestation, else at the attestation's own time.
1079
    let host = Repo::open(&root.join("origin"))
1080
        .unwrap()
1081
        .with_acceptor(hub.clone(), hub_sk.clone());
1082
    let (attest_ref, sa) = host.latest_ref_attest("main").unwrap().unwrap();
1083
    host.record_acceptance(&attest_ref).unwrap();
1084
    let served = host.remote_refs().unwrap();
1085
    let acc = served
1086
        .refs
1087
        .iter()
1088
        .find(|r| r.name == "main")
1089
        .unwrap()
1090
        .accepted
1091
        .clone()
1092
        .expect("served with the refs");
1093
    let signer = sa.sigs[0].key;
1094
    assert_eq!(
1095
        a.certified_time(&signer, &sa, Some(&acc)),
1096
        acc.attest.hlc.wall_ms
1097
    );
1098
    assert_eq!(a.certified_time(&signer, &sa, None), sa.attest.hlc.wall_ms);
1099
    let stranger_sk = SecretKey::generate();
1100
    let stranger = stranger_sk.identity("stranger", "s@x", 1);
1101
    let mut forged = acc.clone();
1102
    forged.sigs = vec![stranger_sk.sign(Domain::Attest, &stranger.hash(), &acc.attest.hash())];
1103
    assert_eq!(
1104
        a.certified_time(&signer, &sa, Some(&forged)),
1105
        sa.attest.hlc.wall_ms,
1106
        "not the issuer's"
1107
    );
1108
    let mut elsewhere = acc.clone();
1109
    elsewhere.attest.body = AttestBody::Accepted {
1110
        attest: ObjectRef([7; 32]),
1111
    };
1112
    elsewhere.sigs = vec![hub_sk.sign(Domain::Attest, &hub.hash(), &elsewhere.attest.hash())];
1113
    assert_eq!(
1114
        a.certified_time(&signer, &sa, Some(&elsewhere)),
1115
        sa.attest.hlc.wall_ms,
1116
        "another attestation's"
1117
    );
1118
    a.pull("origin").unwrap();
1119
    // gc keeps the acceptance with the attestation.
1120
    host.gc(true).unwrap();
1121
    assert!(host.acceptance_of(&attest_ref).unwrap().is_some());
1122
1123
    let late = agent("late", "agent:claude@ada", now - 1_200_000, now - 600_000);
1124
    let r = late.push("origin", false).unwrap();
1125
    assert!(
1126
        !r[0].ok && r[0].reason.contains("may not update"),
1127
        "an expired certificate: {r:?}"
1128
    );
1129
    let other = agent("other", "agent:mallory@ada", now - 60_000, now + 600_000);
1130
    let r = other.push("origin", false).unwrap();
1131
    assert!(
1132
        !r[0].ok && r[0].reason.contains("may not update"),
1133
        "a subject not granted: {r:?}"
1134
    );
1135
}
1136
1137
/// A tag made under one short-lived key and pushed under another: its
1138
/// signer travels with the push (identity and certificate), so a receiver
1139
/// that has never seen that key accepts it. A tag-only push by a keyless
1140
/// agent was refused "unknown key" (found releasing OxygenFlow 0.2.0).
1141
#[test]
1142
fn a_tag_signed_by_an_earlier_short_lived_key_is_pushed() {
1143
    use crate::cert::{Certificate, SignedCertificate};
1144
    use crate::identity::Scope;
1145
    hermetic();
1146
    let dir = tempfile::tempdir().unwrap();
1147
    let root = dir.path();
1148
    let _origin = Repo::init(&root.join("origin")).unwrap();
1149
    let url = root.join("origin").to_string_lossy().to_string();
1150
    let mut a = Repo::clone(&url, &root.join("a"))
1151
        .unwrap()
1152
        .with_home(root.join("home-a"));
1153
    a.create_identity("Ada", "[email protected]", IdentityScope::User)
1154
        .unwrap();
1155
    write(&root.join("a"), "a.txt", b"a\n");
1156
    a.commit("a", &[]).unwrap();
1157
    a.policy_init().unwrap();
1158
    assert!(a.push("origin", false).unwrap().iter().all(|r| r.ok));
1159
    let hub_sk = SecretKey::generate();
1160
    let hub = hub_sk.identity("hub", "[email protected]", 1);
1161
    a.policy_grant_subject(
1162
        "agent:claude@ada",
1163
        hub.clone(),
1164
        Scope::CHANGES | Scope::REFS,
1165
        Some("*"),
1166
    )
1167
    .unwrap();
1168
    assert!(a.push("origin", false).unwrap().iter().all(|r| r.ok));
1169
1170
    let now = Hlc::now().wall_ms;
1171
    let mut agent = Repo::clone(&url, &root.join("agent"))
1172
        .unwrap()
1173
        .with_home(root.join("home-agent"));
1174
    agent.store().put_identity(&hub).unwrap();
1175
    let certify = |agent: &Repo, id| {
1176
        let cert = SignedCertificate::sign(
1177
            Certificate {
1178
                key: id,
1179
                issuer: hub.hash(),
1180
                subject: "agent:claude@ada".into(),
1181
                claims: vec![],
1182
                scope: Scope::CHANGES | Scope::REFS,
1183
                not_before: now - 60_000,
1184
                expires: now + 600_000,
1185
                grant: None,
1186
            },
1187
            &hub,
1188
            &hub_sk,
1189
        );
1190
        agent.store().put_certificate(&cert).unwrap();
1191
    };
1192
    // The tag, under the first short-lived key.
1193
    let (first, first_id) = agent
1194
        .create_identity("claude", "[email protected]", IdentityScope::User)
1195
        .unwrap();
1196
    certify(&agent, first_id);
1197
    let heads = agent.bookmark_heads().unwrap();
1198
    agent.tag_create("v1", &heads, "first").unwrap();
1199
    // The push, under a second one (a later process's ten-minute key).
1200
    let (second, second_id) = agent
1201
        .create_identity("claude", "[email protected]", IdentityScope::User)
1202
        .unwrap();
1203
    assert_ne!(first, second);
1204
    certify(&agent, second_id);
1205
    agent
1206
        .set_user_config("author.signer", &second.to_hex())
1207
        .unwrap();
1208
    let host = Repo::open(&root.join("origin")).unwrap();
1209
    assert!(
1210
        host.store().get_identity(&first).is_err(),
1211
        "the host has never seen the tag's key"
1212
    );
1213
    let r = agent.push("origin", false).unwrap();
1214
    assert!(r.iter().all(|x| x.ok), "{r:?}");
1215
    let host = Repo::open(&root.join("origin")).unwrap();
1216
    assert!(
1217
        host.tag_refs().unwrap().iter().any(|t| t.name == "v1"),
1218
        "the tag arrived"
1219
    );
1220
}
1221
1222
/// oxygen#129: a short-lived key's tag is checked on a fetch at a time its
1223
/// signer did not choose, its issuer's acceptance, never at the time it
1224
/// claims nor at the fetch's (when the ten-minute certificate has long
1225
/// expired). Without an acceptance it is left out and said so; with one
1226
/// inside the certificate's window it is fetched however much later, and
1227
/// a host it is pushed on to keeps and serves the acceptance.
1228
#[test]
1229
fn a_short_lived_key_s_tag_is_fetched_at_its_issuer_s_acceptance() {
1230
    use crate::cert::{Certificate, SignedCertificate};
1231
    use crate::identity::Scope;
1232
    hermetic();
1233
    let dir = tempfile::tempdir().unwrap();
1234
    let root = dir.path();
1235
    let _origin = Repo::init(&root.join("origin")).unwrap();
1236
    let url = root.join("origin").to_string_lossy().to_string();
1237
    let mut a = Repo::clone(&url, &root.join("a"))
1238
        .unwrap()
1239
        .with_home(root.join("home-a"));
1240
    a.create_identity("Ada", "[email protected]", IdentityScope::User)
1241
        .unwrap();
1242
    write(&root.join("a"), "a.txt", b"a\n");
1243
    a.commit("a", &[]).unwrap();
1244
    a.policy_init().unwrap();
1245
    assert!(a.push("origin", false).unwrap().iter().all(|r| r.ok));
1246
    let hub_sk = SecretKey::generate();
1247
    let hub = hub_sk.identity("hub", "[email protected]", 1);
1248
    a.policy_grant_subject(
1249
        "agent:claude@ada",
1250
        hub.clone(),
1251
        Scope::CHANGES | Scope::REFS,
1252
        Some("*"),
1253
    )
1254
    .unwrap();
1255
    assert!(a.push("origin", false).unwrap().iter().all(|r| r.ok));
1256
1257
    let now = Hlc::now().wall_ms;
1258
    // An agent whose key the hub certified from `from` to `to`.
1259
    let agent = |name: &str, from: u64, to: u64| {
1260
        let mut r = Repo::clone(&url, &root.join(name))
1261
            .unwrap()
1262
            .with_home(root.join(format!("home-{name}")));
1263
        r.store().put_identity(&hub).unwrap();
1264
        let (_, id) = r
1265
            .create_identity(name, "[email protected]", IdentityScope::User)
1266
            .unwrap();
1267
        let cert = SignedCertificate::sign(
1268
            Certificate {
1269
                key: id,
1270
                issuer: hub.hash(),
1271
                subject: "agent:claude@ada".into(),
1272
                claims: vec![],
1273
                scope: Scope::CHANGES | Scope::REFS,
1274
                not_before: from,
1275
                expires: to,
1276
                grant: None,
1277
            },
1278
            &hub,
1279
            &hub_sk,
1280
        );
1281
        r.store().put_certificate(&cert).unwrap();
1282
        r
1283
    };
1284
1285
    // A tag by a key certified now, pushed to a host that records no
1286
    // acceptance (a path on disk): it lands, but a fetch has no time to
1287
    // check its certificate at, so it is left out and the fetch goes on.
1288
    let claude = agent("claude", now - 60_000, now + 600_000);
1289
    let heads = claude.bookmark_heads().unwrap();
1290
    claude.tag_create("v1", &heads, "one").unwrap();
1291
    let r = claude.push("origin", false).unwrap();
1292
    assert!(r.iter().all(|x| x.ok), "{r:?}");
1293
    let b = Repo::clone(&url, &root.join("b"))
1294
        .unwrap()
1295
        .with_home(root.join("home-b"));
1296
    let rep = b.fetch("origin").unwrap();
1297
    assert!(
1298
        rep.skipped
1299
            .iter()
1300
            .any(|(n, why)| n == "tags/v1" && why.contains("no time to check its certificate at")),
1301
        "{rep:?}"
1302
    );
1303
    assert_eq!(b.tag_heads("v1").unwrap(), None);
1304
1305
    // The host's acceptance, signed by the certificate's issuer, served
1306
    // with the tag: fetched.
1307
    let host = Repo::open(&root.join("origin"))
1308
        .unwrap()
1309
        .with_acceptor(hub.clone(), hub_sk.clone());
1310
    let (v1, _) = host.tag_attest("v1").unwrap().unwrap();
1311
    host.record_acceptance(&v1).unwrap();
1312
    let served = host.tag_refs().unwrap();
1313
    assert!(served
1314
        .iter()
1315
        .any(|t| t.name == "v1" && t.accepted.is_some()));
1316
    let rep = b.fetch("origin").unwrap();
1317
    assert!(rep.skipped.is_empty(), "{rep:?}");
1318
    assert_eq!(b.tag_heads("v1").unwrap(), Some(heads.clone()));
1319
    // gc keeps the acceptance with the tag.
1320
    host.gc(true).unwrap();
1321
    assert!(host.acceptance_of(&v1).unwrap().is_some());
1322
1323
    // Long after: a key whose certificate expired an hour ago may not
1324
    // create a tag now.
1325
    let late = agent("late", now - 7_200_000, now - 3_600_000);
1326
    late.tag_create("v2", &heads, "two").unwrap();
1327
    let r = late.push("origin", false).unwrap();
1328
    assert!(
1329
        r.iter()
1330
            .any(|x| x.name == "tags/v2" && !x.ok && x.reason.contains("may not create")),
1331
        "{r:?}"
1332
    );
1333
    // With its issuer's acceptance from inside the window (as a hub gave
1334
    // it then, passed on to another host), it is taken at that time: by
1335
    // the host it is pushed to, which keeps it, and by a fresh clone.
1336
    let (v2, _) = late.tag_attest("v2").unwrap().unwrap();
1337
    let acc = Attest {
1338
        repo: late.id().unwrap(),
1339
        hlc: Hlc {
1340
            wall_ms: now - 5_400_000,
1341
            logical: 0,
1342
        },
1343
        body: AttestBody::Accepted { attest: v2 },
1344
    };
1345
    let sig = hub_sk.sign(Domain::Attest, &hub.hash(), &acc.hash());
1346
    // One by any other key gives no time.
1347
    let stranger_sk = SecretKey::generate();
1348
    let stranger = stranger_sk.identity("stranger", "[email protected]", 1);
1349
    let forged = stranger_sk.sign(Domain::Attest, &stranger.hash(), &acc.hash());
1350
    late.keep_acceptance(
1351
        &v2,
1352
        &SignedAttest {
1353
            attest: acc.clone(),
1354
            sigs: vec![forged],
1355
        },
1356
    )
1357
    .unwrap();
1358
    let r = late.push("origin", false).unwrap();
1359
    assert!(
1360
        r.iter().any(|x| x.name == "tags/v2" && !x.ok),
1361
        "not the issuer's: {r:?}"
1362
    );
1363
    let theirs = SignedAttest {
1364
        attest: acc,
1365
        sigs: vec![sig],
1366
    };
1367
    // Kept beside the stranger's: the issuer's is the one sent.
1368
    late.keep_acceptance(&v2, &theirs).unwrap();
1369
    let r = late.push("origin", false).unwrap();
1370
    // (Its re-attestation of main is refused: an expired key moves no
1371
    // bookmark.)
1372
    assert!(r.iter().any(|x| x.name == "tags/v2" && x.ok), "{r:?}");
1373
    let host = Repo::open(&root.join("origin")).unwrap();
1374
    let (hv2, _) = host.tag_attest("v2").unwrap().unwrap();
1375
    assert_eq!(hv2, v2);
1376
    assert!(host
1377
        .store()
1378
        .index_get_pub("accepted", &v2)
1379
        .unwrap()
1380
        .contains(&theirs.attest.hash()));
1381
    let c = Repo::clone(&url, &root.join("c"))
1382
        .unwrap()
1383
        .with_home(root.join("home-c"));
1384
    assert_eq!(c.tag_heads("v2").unwrap(), Some(heads.clone()));
1385
    assert_eq!(c.tag_heads("v1").unwrap(), Some(heads));
1386
}
1387
1388
/// oxygenhub#266: a short-lived key its issuer certified moves a bookmark
1389
/// and signs no change (a keyless agent naming a bookmark). A third
1390
/// party's clone gets the key's identity, its certificate and the
1391
/// issuer's identity with the fetch, so the policy's subject grant
1392
/// authorizes the move and the signature verifies.
1393
#[test]
1394
fn a_bookmark_moved_by_a_certified_key_alone_is_fetched() {
1395
    use crate::cert::{Certificate, SignedCertificate};
1396
    use crate::identity::Scope;
1397
    hermetic();
1398
    let dir = tempfile::tempdir().unwrap();
1399
    let root = dir.path();
1400
    let _origin = Repo::init(&root.join("origin")).unwrap();
1401
    let url = root.join("origin").to_string_lossy().to_string();
1402
    let mut a = Repo::clone(&url, &root.join("a"))
1403
        .unwrap()
1404
        .with_home(root.join("home-a"));
1405
    a.create_identity("Ada", "[email protected]", IdentityScope::User)
1406
        .unwrap();
1407
    write(&root.join("a"), "a.txt", b"a\n");
1408
    a.commit("a", &[]).unwrap();
1409
    a.policy_init().unwrap();
1410
    assert!(a.push("origin", false).unwrap().iter().all(|r| r.ok));
1411
    let hub_sk = SecretKey::generate();
1412
    let hub = hub_sk.identity("hub", "[email protected]", 1);
1413
    a.policy_grant_subject(
1414
        "agent:claude@ada",
1415
        hub.clone(),
1416
        Scope::CHANGES | Scope::REFS,
1417
        None,
1418
    )
1419
    .unwrap();
1420
    assert!(a.push("origin", false).unwrap().iter().all(|r| r.ok));
1421
1422
    let now = Hlc::now().wall_ms;
1423
    let mut agent = Repo::clone(&url, &root.join("agent"))
1424
        .unwrap()
1425
        .with_home(root.join("home-agent"));
1426
    let (key, id) = agent
1427
        .create_identity("claude", "[email protected]", IdentityScope::User)
1428
        .unwrap();
1429
    let cert = SignedCertificate::sign(
1430
        Certificate {
1431
            key: id,
1432
            issuer: hub.hash(),
1433
            subject: "agent:claude@ada".into(),
1434
            claims: vec![],
1435
            scope: Scope::CHANGES | Scope::REFS,
1436
            not_before: now - 60_000,
1437
            expires: now + 600_000,
1438
            grant: None,
1439
        },
1440
        &hub,
1441
        &hub_sk,
1442
    );
1443
    agent.store().put_identity(&hub).unwrap();
1444
    agent.store().put_certificate(&cert).unwrap();
1445
    let heads = agent.bookmark_heads().unwrap();
1446
    agent.bookmark_create("agent-work", Some(&heads)).unwrap();
1447
    let r = agent.push_bookmark("origin", "agent-work", false).unwrap();
1448
    assert!(r.iter().all(|x| x.ok), "{r:?}");
1449
    let host = Repo::open(&root.join("origin")).unwrap();
1450
    let (_, sa) = host.latest_ref_attest("agent-work").unwrap().unwrap();
1451
    assert_eq!(sa.sigs[0].key, key, "the certified key alone moved it");
1452
1453
    // A fetch naming no change brings the certificate and both identities.
1454
    let bundle = host.bundle_raw_for(&[], None).unwrap();
1455
    assert!(bundle.changes.is_empty() && bundle.raw_changes.is_empty());
1456
    assert_eq!(bundle.certificates.len(), 1);
1457
    for k in [key, hub.hash()] {
1458
        assert!(bundle
1459
            .objects
1460
            .iter()
1461
            .any(|(t, b)| *t == ObjectType::Identity && hash_object(*t, b) == k));
1462
    }
1463
1464
    let c = Repo::clone(&url, &root.join("c")).unwrap();
1465
    let tracked = c.view().unwrap().remotes["origin"].clone();
1466
    assert_eq!(
1467
        tracked.get("agent-work"),
1468
        host.view().unwrap().bookmarks.get("agent-work")
1469
    );
1470
    assert!(c.store().certificate_of(&key).unwrap().is_some());
1471
}
1472
1473
/// Trusted time (oxygenhub#240, spec §14.8): a fetched attestation by a
1474
/// short-lived key is judged at its integrated time, the earliest time a
1475
/// pinned witness cosigned a checkpoint holding it. A certificate valid
1476
/// then but expired now passes; a witness this user does not trust gives
1477
/// no time (the earlier rule, said so); a backdated attestation is noted;
1478
/// an answer without the new fields is judged as before.
1479
#[test]
1480
fn a_fetched_attestation_is_judged_at_its_integrated_time() {
1481
    use super::transparency::LogCheck;
1482
    use crate::cert::{Certificate, SignedCertificate};
1483
    use crate::identity::Scope;
1484
    use crate::protocol::{Integration, Logged, RefsResponse, RemoteRef};
1485
    use crate::tlog::{self, Checkpoint, Entry, Hash, Integrated, Note};
1486
    hermetic();
1487
    let dir = tempfile::tempdir().unwrap();
1488
    let root = dir.path();
1489
    let mut a = Repo::init(&root.join("a"))
1490
        .unwrap()
1491
        .with_home(root.join("home-a"));
1492
    a.create_identity("Ada", "[email protected]", IdentityScope::User)
1493
        .unwrap();
1494
    write(&root.join("a"), "a.txt", b"a\n");
1495
    a.commit("a", &[]).unwrap();
1496
    a.policy_init().unwrap();
1497
    let issuer_sk = SecretKey::generate();
1498
    let issuer = issuer_sk.identity("hub", "[email protected]", 1);
1499
    a.policy_grant_subject(
1500
        "agent:claude@ada",
1501
        issuer.clone(),
1502
        Scope::CHANGES | Scope::REFS,
1503
        None,
1504
    )
1505
    .unwrap();
1506
    let p = a.current_policy().unwrap().unwrap().1.policy;
1507
1508
    // An agent key the issuer certified for ten minutes two hours ago.
1509
    let now = Hlc::now().wall_ms;
1510
    let t0 = now - 2 * 3_600_000;
1511
    let agent_sk = SecretKey::generate();
1512
    let agent = agent_sk.identity("claude", "[email protected]", t0);
1513
    let cert = SignedCertificate::sign(
1514
        Certificate {
1515
            key: agent.clone(),
1516
            issuer: issuer.hash(),
1517
            subject: "agent:claude@ada".into(),
1518
            claims: vec![],
1519
            scope: Scope::CHANGES | Scope::REFS,
1520
            not_before: t0,
1521
            expires: t0 + 600_000,
1522
            grant: None,
1523
        },
1524
        &issuer,
1525
        &issuer_sk,
1526
    );
1527
    a.store().put_identity(&agent).unwrap();
1528
    a.store().put_certificate(&cert).unwrap();
1529
    let signer = agent.hash();
1530
    let attested = |claimed: u64| {
1531
        let attest = Attest {
1532
            repo: a.id().unwrap(),
1533
            hlc: Hlc {
1534
                wall_ms: claimed,
1535
                logical: 0,
1536
            },
1537
            body: AttestBody::Ref {
1538
                name: "main".into(),
1539
                old_state: ObjectRef([1; 32]),
1540
                new_state: ObjectRef([2; 32]),
1541
                serial: 1,
1542
            },
1543
        };
1544
        let sig = agent_sk.sign(Domain::Attest, &signer, &attest.hash());
1545
        SignedAttest {
1546
            attest,
1547
            sigs: vec![sig],
1548
        }
1549
    };
1550
1551
    // The hub's log: eight entries, the attestation's at 3, the latest
1552
    // checkpoint of 8, and one of 4 that witnesses cosigned.
1553
    let log_sk = SecretKey::generate();
1554
    let log_key = log_sk.identity("hub.example", "[email protected]", 1);
1555
    let origin = "hub.example/log";
1556
    let hub = "https://hub.example";
1557
    let url = "https://hub.example/ada/a";
1558
    let w_sk = SecretKey::generate();
1559
    let w = w_sk.identity("w", "[email protected]", 1);
1560
    let stranger_sk = SecretKey::generate();
1561
    let stranger = stranger_sk.identity("s", "[email protected]", 1);
1562
    let sa = attested(t0 + 300_000);
1563
    let entry_of = |i: u64| {
1564
        let (kind, object) = if i == 3 {
1565
            ("ref", sa.attest.hash())
1566
        } else {
1567
            ("seal", ObjectRef([i as u8; 32]))
1568
        };
1569
        Entry {
1570
            kind: kind.into(),
1571
            repo: sa.attest.repo,
1572
            object,
1573
            signers: vec![signer],
1574
            received: t0 + 300_000,
1575
        }
1576
        .encode()
1577
    };
1578
    let mut stored: Vec<Hash> = Vec::new();
1579
    for i in 0..8 {
1580
        let add = tlog::stored_hashes_for_leaf(i, tlog::leaf_hash(&entry_of(i)), &stored).unwrap();
1581
        stored.extend(add);
1582
    }
1583
    let note_of = |n: u64, cosigners: &[(&str, &Identity, &SecretKey, u64)]| {
1584
        let mut note = Checkpoint {
1585
            origin: origin.into(),
1586
            size: n,
1587
            root: tlog::tree_hash(n, &stored).unwrap(),
1588
            extensions: vec![],
1589
        }
1590
        .sign(&log_key, &log_sk)
1591
        .unwrap();
1592
        for (name, id, sk, t) in cosigners {
1593
            note.sigs
1594
                .extend(tlog::cosign(&note.text, name, id, sk, *t).unwrap());
1595
        }
1596
        note.encode()
1597
    };
1598
    let latest = note_of(8, &[]);
1599
    let witnessed_at = (t0 + 360_000) / 1000;
1600
    let cosigned = note_of(
1601
        4,
1602
        &[
1603
            ("w.example", &w, &w_sk, witnessed_at),
1604
            ("s.example", &stranger, &stranger_sk, 1),
1605
        ],
1606
    );
1607
    let answer = |integration: Vec<Integration>, witnesses: Vec<(String, Vec<u8>)>| RefsResponse {
1608
        refs: vec![RemoteRef {
1609
            name: "main".into(),
1610
            state: ObjectRef([2; 32]),
1611
            heads: vec![],
1612
            attestation: Some(sa.clone()),
1613
            last_serial: None,
1614
            accepted: None,
1615
            logged: Some(Logged {
1616
                index: 3,
1617
                entry: entry_of(3),
1618
                proof: tlog::prove_inclusion(8, 3, &stored).unwrap(),
1619
            }),
1620
            integration,
1621
        }],
1622
        log: Some(latest.clone()),
1623
        witnesses,
1624
        ..RefsResponse::default()
1625
    };
1626
    let proof4 = tlog::prove_inclusion(4, 3, &stored).unwrap();
1627
    let served = vec![Integration {
1628
        note: cosigned.clone(),
1629
        proof: proof4.clone(),
1630
    }];
1631
    let listed = vec![("w.example".to_string(), w.encode())];
1632
    // This user saw the hub's log before (pinned, so nothing is fetched).
1633
    a.remember_log(hub, &log_key, &Note::parse(&latest).unwrap())
1634
        .unwrap();
1635
1636
    // The witness is pinned on first sight, silently; the stranger's
1637
    // earlier cosignature counts for nothing.
1638
    let resp = answer(served.clone(), listed.clone());
1639
    let lc = a.check_log(url, None, &resp).unwrap();
1640
    assert!(lc.notes.is_empty(), "{:?}", lc.notes);
1641
    let t = lc.time_of("main").unwrap();
1642
    assert_eq!((t.time, t.witness.as_str()), (witnessed_at, "w.example"));
1643
    // The certificate expired an hour and fifty minutes ago, but covered
1644
    // the integrated time: accepted, and nothing to say.
1645
    assert!(cert.cert.expires < now);
1646
    let mut notes = Vec::new();
1647
    a.authorize_in_time(&p, "origin", &resp.refs[0], &sa, &signer, &lc, &mut notes)
1648
        .unwrap();
1649
    assert!(notes.is_empty(), "{notes:?}");
1650
1651
    // Only the stranger cosigned: no witnessed time, so the earlier rule
1652
    // (the attestation's own time, inside the window), said so.
1653
    let lonely = vec![Integration {
1654
        note: note_of(4, &[("s.example", &stranger, &stranger_sk, 1)]),
1655
        proof: proof4.clone(),
1656
    }];
1657
    let resp = answer(lonely, vec![]);
1658
    let lc = a.check_log(url, None, &resp).unwrap();
1659
    assert!(lc
1660
        .time_of("main")
1661
        .unwrap_err()
1662
        .contains("no witness this user trusts"));
1663
    let mut notes = Vec::new();
1664
    a.authorize_in_time(&p, "origin", &resp.refs[0], &sa, &signer, &lc, &mut notes)
1665
        .unwrap();
1666
    assert!(
1667
        notes.len() == 1 && notes[0].contains("not at a witnessed time"),
1668
        "{notes:?}"
1669
    );
1670
1671
    // A witness listed later under the pinned name with another key is
1672
    // pinned with a note, as a new log key is.
1673
    let resp = answer(
1674
        served.clone(),
1675
        vec![("w.example".into(), stranger.encode())],
1676
    );
1677
    let lc = a.check_log(url, None, &resp).unwrap();
1678
    assert!(
1679
        lc.notes.iter().any(|n| n.contains("another key")),
1680
        "{:?}",
1681
        lc.notes
1682
    );
1683
    assert!(
1684
        lc.time_of("main").is_err(),
1685
        "w's cosignature is by its old key"
1686
    );
1687
    a.check_log(url, None, &answer(served.clone(), listed.clone()))
1688
        .unwrap();
1689
1690
    // An old peer's answer: no log, no witnesses, no integration. Judged
1691
    // as before, silently.
1692
    let mut old = answer(vec![], vec![]);
1693
    old.log = None;
1694
    old.refs[0].logged = None;
1695
    let lc = a.check_log(url, None, &old).unwrap();
1696
    assert!(!lc.kept && lc.notes.is_empty());
1697
    let mut notes = Vec::new();
1698
    a.authorize_in_time(&p, "origin", &old.refs[0], &sa, &signer, &lc, &mut notes)
1699
        .unwrap();
1700
    assert!(notes.is_empty(), "{notes:?}");
1701
1702
    // Judged at given integrated times.
1703
    let at = |secs_after_t0: u64| {
1704
        let mut times = std::collections::HashMap::new();
1705
        times.insert(
1706
            "main".to_string(),
1707
            Ok(Integrated {
1708
                time: (t0 + secs_after_t0 * 1000) / 1000,
1709
                witness: "w.example".into(),
1710
                size: 4,
1711
            }),
1712
        );
1713
        LogCheck {
1714
            kept: true,
1715
            times,
1716
            ..LogCheck::default()
1717
        }
1718
    };
1719
    let judged = |sa: &SignedAttest, lc: &LogCheck| {
1720
        let mut notes = Vec::new();
1721
        a.authorize_in_time(&p, "origin", &old.refs[0], sa, &signer, lc, &mut notes)
1722
            .map(|_| notes)
1723
    };
1724
    // Claimed inside the window, first witnessed an hour later, after
1725
    // the certificate expired: backdated, or held back. Accepted by the
1726
    // earlier rule while logs are new, with both said.
1727
    let notes = judged(&sa, &at(3600)).unwrap();
1728
    assert!(
1729
        notes
1730
            .iter()
1731
            .any(|n| n.contains("had lapsed when witness w.example"))
1732
            && notes
1733
                .iter()
1734
                .any(|n| n.contains("55 minutes before witness")),
1735
        "{notes:?}"
1736
    );
1737
    // Claimed after the certificate expired, but witnessed inside its
1738
    // window: the clock the signer did not choose decides. The gap is
1739
    // still noted.
1740
    let fast = attested(now);
1741
    let notes = judged(&fast, &at(400)).unwrap();
1742
    assert!(
1743
        notes.len() == 1 && notes[0].contains("after witness w.example saw it"),
1744
        "{notes:?}"
1745
    );
1746
    // Claimed and witnessed after it expired: refused, as before.
1747
    assert!(judged(&fast, &at(3600)).is_err());
1748
    // A gap within ten minutes is nothing to note.
1749
    assert!(judged(&sa, &at(500)).unwrap().is_empty());
1750
}
1751
1752
/// Keyless step 5 (oxygenhub#241): an agent's fresh key, certified for a
1753
/// subject the author granted, seals changes in the author's name; with
1754
/// no grant, a stranger's, or one that had ended, it is neither the
1755
/// author nor a delegate.
1756
/// oxygen#135: an owner renews or rotates with every delegation, and a
1757
/// repository may name the newest key as the author; the agent's grant by
1758
/// the earlier key still counts, but not one that key made after.
1759
#[test]
1760
fn a_grant_outlives_its_owner_s_rotation() {
1761
    use crate::cert::{Certificate, Grant, SignedCertificate, SignedGrant};
1762
    use crate::identity::Scope;
1763
    hermetic();
1764
    let dir = tempfile::tempdir().unwrap();
1765
    let root = dir.path();
1766
    let mut a = Repo::init(&root.join("a"))
1767
        .unwrap()
1768
        .with_home(root.join("home-a"));
1769
    let (old, _) = a
1770
        .create_identity("Ada", "[email protected]", IdentityScope::User)
1771
        .unwrap();
1772
    let (_, old_sk) = a.secret_key().unwrap().unwrap();
1773
    let old_id = a.identity(&old).unwrap();
1774
    let hub_sk = SecretKey::generate();
1775
    let hub = hub_sk.identity("hub", "[email protected]", 1);
1776
    let now = Hlc::now().wall_ms;
1777
    let grant = |from: u64| {
1778
        SignedGrant::sign(
1779
            Grant {
1780
                grantor: old,
1781
                subject: "agent:claude@ada".into(),
1782
                issuer: hub.hash(),
1783
                scope: Scope::CHANGES | Scope::SEAL,
1784
                not_before: from,
1785
                expires: now + 86_400_000,
1786
            },
1787
            &old_id,
1788
            &old_sk,
1789
        )
1790
    };
1791
    let before = grant(now - 60_000);
1792
    let after = grant(now + 60_000);
1793
    let rot = a.renew_identity(None).unwrap();
1794
    assert_ne!(rot.new, old);
1795
    let agent = |name: &str, g: SignedGrant| {
1796
        let mut r = Repo::init(&root.join(name))
1797
            .unwrap()
1798
            .with_home(root.join(format!("home-{name}")));
1799
        let (key, id) = r
1800
            .create_identity(name, "[email protected]", IdentityScope::User)
1801
            .unwrap();
1802
        for i in [&old_id, &rot.identity, &hub] {
1803
            r.store().put_identity(i).unwrap();
1804
        }
1805
        r.set_user_config("author.key", &rot.new.to_hex()).unwrap();
1806
        r.set_user_config("author.signer", &key.to_hex()).unwrap();
1807
        let cert = SignedCertificate::sign(
1808
            Certificate {
1809
                key: id,
1810
                issuer: hub.hash(),
1811
                subject: "agent:claude@ada".into(),
1812
                claims: vec![],
1813
                scope: Scope::CHANGES | Scope::REFS | Scope::SEAL,
1814
                not_before: now - 60_000,
1815
                expires: now + 600_000,
1816
                grant: Some(g),
1817
            },
1818
            &hub,
1819
            &hub_sk,
1820
        );
1821
        r.store().put_certificate(&cert).unwrap();
1822
        write(&root.join(name), "work.txt", b"agent work\n");
1823
        let h = r.commit("work", &[]).unwrap();
1824
        assert_eq!(r.store().get_change_meta(&h).unwrap().author, rot.new);
1825
        r.seal(&[h]).unwrap();
1826
        (r, h)
1827
    };
1828
    let (r, h) = agent("kept", before);
1829
    assert!(
1830
        matches!(
1831
            r.authenticate_change(&h).unwrap(),
1832
            SignatureStatus::Valid { .. }
1833
        ),
1834
        "{:?}",
1835
        r.authenticate_change(&h).unwrap()
1836
    );
1837
    let (r, h) = agent("late", after);
1838
    assert!(
1839
        matches!(r.authenticate_change(&h).unwrap(), SignatureStatus::Invalid(e) if e.contains("neither")),
1840
        "a grant the old key made after the rotation: {:?}",
1841
        r.authenticate_change(&h).unwrap()
1842
    );
1843
}
1844
1845
#[test]
1846
fn a_certified_key_acts_for_its_author_under_a_grant() {
1847
    use crate::cert::{Certificate, Grant, SignedCertificate, SignedGrant};
1848
    use crate::identity::{Identity, Scope};
1849
    hermetic();
1850
    let dir = tempfile::tempdir().unwrap();
1851
    let root = dir.path();
1852
    let _origin = Repo::init(&root.join("origin")).unwrap();
1853
    let url = root.join("origin").to_string_lossy().to_string();
1854
    let mut a = Repo::clone(&url, &root.join("a"))
1855
        .unwrap()
1856
        .with_home(root.join("home-a"));
1857
    let (ada, _) = a
1858
        .create_identity("Ada", "[email protected]", IdentityScope::User)
1859
        .unwrap();
1860
    write(&root.join("a"), "a.txt", b"a\n");
1861
    a.commit("a", &[]).unwrap();
1862
    a.policy_init().unwrap();
1863
    assert!(a.push("origin", false).unwrap().iter().all(|r| r.ok));
1864
    let hub_sk = SecretKey::generate();
1865
    let hub = hub_sk.identity("hub", "[email protected]", 1);
1866
    a.policy_grant_subject(
1867
        "agent:claude@ada",
1868
        hub.clone(),
1869
        Scope::CHANGES | Scope::REFS,
1870
        None,
1871
    )
1872
    .unwrap();
1873
    assert!(a.push("origin", false).unwrap().iter().all(|r| r.ok));
1874
    let (_, ada_sk) = a.secret_key().unwrap().unwrap();
1875
    let ada_id = a.identity(&ada).unwrap();
1876
1877
    let now = Hlc::now().wall_ms;
1878
    let grant = |by: &Identity, sk: &SecretKey, from: u64, to: u64| {
1879
        SignedGrant::sign(
1880
            Grant {
1881
                grantor: by.hash(),
1882
                subject: "agent:claude@ada".into(),
1883
                issuer: hub.hash(),
1884
                scope: Scope::CHANGES | Scope::SEAL,
1885
                not_before: from,
1886
                expires: to,
1887
            },
1888
            by,
1889
            sk,
1890
        )
1891
    };
1892
    // Ada's work as an agent runs it: Ada the author, a fresh key the hub
1893
    // certified (with `g` inside) the signer.
1894
    let agent = |name: &str, g: Option<SignedGrant>| {
1895
        let mut r = Repo::clone(&url, &root.join(name))
1896
            .unwrap()
1897
            .with_home(root.join(format!("home-{name}")));
1898
        let (key, id) = r
1899
            .create_identity(name, "[email protected]", IdentityScope::User)
1900
            .unwrap();
1901
        r.set_user_config("author.key", &ada.to_hex()).unwrap();
1902
        r.set_user_config("author.signer", &key.to_hex()).unwrap();
1903
        let cert = SignedCertificate::sign(
1904
            Certificate {
1905
                key: id,
1906
                issuer: hub.hash(),
1907
                subject: "agent:claude@ada".into(),
1908
                claims: vec![],
1909
                scope: Scope::CHANGES | Scope::REFS | Scope::SEAL,
1910
                not_before: now - 60_000,
1911
                expires: now + 600_000,
1912
                grant: g,
1913
            },
1914
            &hub,
1915
            &hub_sk,
1916
        );
1917
        r.store().put_identity(&hub).unwrap();
1918
        r.store().put_certificate(&cert).unwrap();
1919
        write(&root.join(name), &format!("{name}.txt"), b"agent work\n");
1920
        let h = r.commit("work", &[]).unwrap();
1921
        assert_eq!(r.store().get_change_meta(&h).unwrap().author, ada);
1922
        (r, key, h)
1923
    };
1924
1925
    let (claude, key, h) = agent(
1926
        "claude",
1927
        Some(grant(&ada_id, &ada_sk, now - 60_000, now + 86_400_000)),
1928
    );
1929
    let r = claude.push("origin", false).unwrap();
1930
    assert!(r.iter().all(|x| x.ok), "{r:?}");
1931
    let host = Repo::open(&root.join("origin")).unwrap();
1932
    assert!(
1933
        matches!(
1934
            host.authenticate_change(&h).unwrap(),
1935
            SignatureStatus::Valid { key: k, sealed: true, name, .. } if k == key && name == "agent:claude@ada"
1936
        ),
1937
        "named by its certificate's subject"
1938
    );
1939
    a.pull("origin").unwrap();
1940
    assert!(matches!(
1941
        a.authenticate_change(&h).unwrap(),
1942
        SignatureStatus::Valid { key: k, .. } if k == key
1943
    ));
1944
1945
    let (none, _, _) = agent("none", None);
1946
    let r = none.push("origin", false).unwrap();
1947
    assert!(r.iter().all(|x| !x.ok), "no grant: {r:?}");
1948
    let mallory_sk = SecretKey::generate();
1949
    let mallory = mallory_sk.identity("Mallory", "[email protected]", 1);
1950
    let (stranger, _, _) = agent(
1951
        "stranger",
1952
        Some(grant(&mallory, &mallory_sk, now - 60_000, now + 600_000)),
1953
    );
1954
    let r = stranger.push("origin", false).unwrap();
1955
    assert!(r.iter().all(|x| !x.ok), "a stranger's grant: {r:?}");
1956
    let (ended, _, eh) = agent(
1957
        "ended",
1958
        Some(grant(&ada_id, &ada_sk, now - 7_200_000, now - 3_600_000)),
1959
    );
1960
    let r = ended.push("origin", false).unwrap();
1961
    assert!(r.iter().all(|x| !x.ok), "an ended grant: {r:?}");
1962
    assert!(matches!(
1963
        ended.authenticate_change(&eh).unwrap(),
1964
        SignatureStatus::Invalid(e) if e.contains("grant did not cover")
1965
    ));
1966
}
1967
1968
#[test]
1969
fn trust_policy_governs_pushes_and_fetches() {
1970
    hermetic();
1971
    let dir = tempfile::tempdir().unwrap();
1972
    let root = dir.path();
1973
    let origin = Repo::init(&root.join("origin")).unwrap();
1974
    let url = root.join("origin").to_string_lossy().to_string();
1975
1976
    // A is the root. Before the policy, an unsigned push from B is fine.
1977
    let mut a = Repo::clone(&url, &root.join("a"))
1978
        .unwrap()
1979
        .with_home(root.join("home-a"));
1980
    let (key_a, _) = a
1981
        .create_identity("Ada", "[email protected]", IdentityScope::User)
1982
        .unwrap();
1983
    let mut b = Repo::clone(&url, &root.join("b"))
1984
        .unwrap()
1985
        .with_home(root.join("home-b"));
1986
    write(&root.join("b"), "b.txt", b"b\n");
1987
    b.commit("unsigned before policy", &[]).unwrap();
1988
    assert!(b.push("origin", false).unwrap()[0].ok);
1989
    origin.refresh().unwrap();
1990
1991
    // A creates the policy and pushes it; origin now enforces it.
1992
    write(&root.join("a"), "a.txt", b"a\n");
1993
    a.commit("a", &[]).unwrap();
1994
    let sp = a.policy_init().unwrap();
1995
    assert_eq!(sp.policy.serial, 1);
1996
    a.pull("origin").unwrap();
1997
    let results = a.push("origin", false).unwrap();
1998
    origin.refresh().unwrap();
1999
    assert!(results.iter().all(|r| r.ok), "{results:?}");
2000
    assert_eq!(origin.current_policy().unwrap().unwrap().1.policy.serial, 1);
2001
2002
    // B pulls the policy. Without an identity B cannot push at all.
2003
    b.pull("origin").unwrap();
2004
    assert!(
2005
        b.current_policy().unwrap().is_some(),
2006
        "the policy arrived with the fetch"
2007
    );
2008
    assert!(b.push("origin", false).is_err());
2009
    // With an identity the policy does not list, the push is rejected by origin.
2010
    let (key_b, id_b) = b
2011
        .create_identity("Bob", "[email protected]", IdentityScope::User)
2012
        .unwrap();
2013
    write(&root.join("b"), "b.txt", b"b2\n");
2014
    let h_b2 = b.commit("b2 as Bob", &[]).unwrap();
2015
    assert_eq!(b.store().get_change(&h_b2).unwrap().author, key_b);
2016
    let r = b.push("origin", false).unwrap();
2017
    origin.refresh().unwrap();
2018
    assert!(
2019
        !r[0].ok && r[0].reason.contains("may not update"),
2020
        "{:?}",
2021
        r
2022
    );
2023
2024
    // A grants B (identity handed over as a file) and publishes the policy.
2025
    let sp = a.policy_grant(id_b.clone(), None).unwrap();
2026
    assert_eq!(sp.policy.serial, 2);
2027
    let r = a.push("origin", false).unwrap();
2028
    origin.refresh().unwrap();
2029
    assert!(r.iter().any(|x| x.name == "policy" && x.ok), "{r:?}");
2030
    // B must fetch the new policy before pushing.
2031
    assert!(b
2032
        .push("origin", false)
2033
        .unwrap_or_else(|e| vec![RefResult {
2034
            name: "main".into(),
2035
            ok: false,
2036
            reason: e.to_string()
2037
        }])
2038
        .iter()
2039
        .all(|x| !x.ok));
2040
    b.pull("origin").unwrap();
2041
    assert_eq!(b.current_policy().unwrap().unwrap().1.policy.serial, 2);
2042
    let r = b.push("origin", false).unwrap();
2043
    origin.refresh().unwrap();
2044
    assert!(r[0].ok, "{:?}", r);
2045
    // Origin verified B's change under the policy.
2046
    let heads = origin.bookmark_heads().unwrap();
2047
    for h in &heads {
2048
        let c = origin.store().get_change(h).unwrap();
2049
        if c.author == key_b {
2050
            origin
2051
                .change_allowed(
2052
                    h,
2053
                    &origin.current_policy().unwrap().unwrap().1.policy,
2054
                    "main",
2055
                )
2056
                .unwrap();
2057
        }
2058
    }
2059
2060
    // A policy signed by a non-root (B) is refused, as is a replayed serial.
2061
    let mut forged = b.current_policy().unwrap().unwrap().1.policy.clone();
2062
    forged.serial = 3;
2063
    forged.roots = vec![key_b];
2064
    let fh = forged.hash();
2065
    let (_, sk_b) = b.secret_key().unwrap().unwrap();
2066
    let forged = SignedPolicy {
2067
        policy: forged,
2068
        sigs: vec![sk_b.sign(Domain::Policy, &key_b, &fh)],
2069
    };
2070
    let r = origin
2071
        .receive_push(Bundle::default(), vec![], Some(forged), vec![])
2072
        .unwrap();
2073
    assert!(!r[0].ok && r[0].reason.contains("root"), "{:?}", r);
2074
    let stale = a.current_policy().unwrap().unwrap().1;
2075
    let mut old = stale.clone();
2076
    old.policy.serial = 1;
2077
    let r = origin
2078
        .receive_push(Bundle::default(), vec![], Some(old), vec![])
2079
        .unwrap();
2080
    assert!(!r[0].ok && r[0].reason.contains("serial"), "{:?}", r);
2081
2082
    // A revokes B; after B pulls the policy, B's pushes are refused again.
2083
    a.pull("origin").unwrap();
2084
    a.policy_revoke(&key_b).unwrap();
2085
    let r = a.push("origin", false).unwrap();
2086
    origin.refresh().unwrap();
2087
    assert!(r.iter().any(|x| x.name == "policy" && x.ok), "{r:?}");
2088
    b.pull("origin").unwrap();
2089
    write(&root.join("b"), "b.txt", b"b3\n");
2090
    b.commit("b3", &[]).unwrap();
2091
    let r = b.push("origin", false).unwrap();
2092
    origin.refresh().unwrap();
2093
    assert!(!r[0].ok, "{:?}", r);
2094
2095
    // A clone by a third party receives and verifies everything.
2096
    let c = Repo::clone(&url, &root.join("c"))
2097
        .unwrap()
2098
        .with_home(root.join("home-c"));
2099
    assert_eq!(c.current_policy().unwrap().unwrap().1.policy.serial, 3);
2100
    assert!(c
2101
        .current_policy()
2102
        .unwrap()
2103
        .unwrap()
2104
        .1
2105
        .policy
2106
        .roots
2107
        .contains(&key_a));
2108
    assert!(!c.snapshot("status").unwrap().changed);
2109
}
2110
2111
/// oxygen#66: a gc says what it is doing, phase by phase.
2112
#[test]
2113
fn gc_reports_its_phases() {
2114
    hermetic();
2115
    let dir = tempfile::tempdir().unwrap();
2116
    let repo = Repo::init(dir.path()).unwrap();
2117
    for i in 0..3 {
2118
        write(
2119
            dir.path(),
2120
            &format!("f{i}.txt"),
2121
            format!("{i}\n").as_bytes(),
2122
        );
2123
        repo.commit(&format!("c{i}"), &[]).unwrap();
2124
    }
2125
    let mut phases = Vec::new();
2126
    repo.gc_with(true, &mut |p| phases.push(p.to_string()))
2127
        .unwrap();
2128
    assert_eq!(phases[0], "finding what is reachable", "{phases:?}");
2129
    assert!(
2130
        phases.iter().any(|p| p.starts_with("pruning")),
2131
        "{phases:?}"
2132
    );
2133
    assert!(
2134
        phases.iter().any(|p| p.starts_with("packing 0 of ")),
2135
        "{phases:?}"
2136
    );
2137
    assert!(
2138
        phases
2139
            .iter()
2140
            .any(|p| p.starts_with("writing the index of ")),
2141
        "{phases:?}"
2142
    );
2143
}
2144
2145
#[test]
2146
fn gc_packs_objects_and_history_still_works() {
2147
    hermetic();
2148
    let dir = tempfile::tempdir().unwrap();
2149
    let root = dir.path();
2150
    let mut repo = Repo::init(root).unwrap().with_home(root.join("home"));
2151
    repo.create_identity("Ada", "a@b", IdentityScope::User)
2152
        .unwrap();
2153
    repo.set_user_config("core.sign", "change").unwrap();
2154
    write(root, "a.txt", b"one\n");
2155
    let h1 = repo.commit("one", &[]).unwrap();
2156
    write(root, "a.txt", b"two\n");
2157
    write(root, "big.bin", &vec![0u8; 100_000]);
2158
    let h2 = repo.commit("two", &[]).unwrap();
2159
    // Several snapshots leave superseded working-copy versions behind.
2160
    for i in 0..5 {
2161
        write(root, "a.txt", format!("two\n{i}\n").as_bytes());
2162
        repo.snapshot("status").unwrap();
2163
    }
2164
    write(root, "a.txt", b"two\n");
2165
    repo.snapshot("status").unwrap();
2166
    let before = repo.store().list().unwrap();
2167
    assert!(repo.store().loose_count().unwrap() > 0);
2168
2169
    // With the default retention every operation's view is a root: nothing prunes.
2170
    let r = repo.gc(true).unwrap();
2171
    assert_eq!(r.packed.objects, before.len());
2172
    assert_eq!(r.pruned.objects, 0);
2173
    assert_eq!(repo.store().loose_count().unwrap(), 0);
2174
    assert_eq!(repo.store().list().unwrap(), before);
2175
2176
    // With zero retention only the current view is a root: superseded
2177
    // working copies go, everything reachable stays.
2178
    repo.config.set("core.op-retention", "0").unwrap();
2179
    repo.save_config().unwrap();
2180
    let mut repo = Repo::open(root).unwrap().with_home(root.join("home"));
2181
    let r = repo.gc(true).unwrap();
2182
    assert!(r.pruned.objects >= 5, "{r:?}");
2183
    let after = repo.store().list().unwrap();
2184
    assert!(after.len() < before.len());
2185
    assert!(after.contains(&h1) && after.contains(&h2));
2186
    for (_, op) in repo.op_log().unwrap() {
2187
        assert!(!op.command.is_empty(), "operation objects are all kept");
2188
    }
2189
    // Everything still works from the pruned, packed store.
2190
    assert_eq!(repo.bookmark_heads().unwrap(), vec![h2]);
2191
    assert!(matches!(
2192
        repo.verify_change(&h2).unwrap(),
2193
        SignatureStatus::Valid { .. }
2194
    ));
2195
    assert_eq!(repo.log().unwrap().len(), 3);
2196
    repo.checkout(&[h1], false, "checkout").unwrap();
2197
    assert_eq!(fs::read(root.join("a.txt")).unwrap(), b"one\n");
2198
    repo.checkout(&[h2], false, "checkout").unwrap();
2199
    assert_eq!(fs::read(root.join("big.bin")).unwrap().len(), 100_000);
2200
    assert!(!repo.snapshot("status").unwrap().changed);
2201
    // Grace period defers pruning of young garbage.
2202
    write(root, "a.txt", b"three\n");
2203
    repo.commit("three", &[]).unwrap();
2204
    let r = repo.gc(false).unwrap();
2205
    assert_eq!(r.pruned.objects, 0);
2206
    assert!(r.pruned.deferred > 0);
2207
    let r = repo.gc(true).unwrap();
2208
    assert!(r.pruned.objects > 0);
2209
    assert_eq!(repo.log().unwrap().len(), 4);
2210
    // Restoring the default retention makes the old views roots again; the
2211
    // working copies they name were pruned, which gc tolerates.
2212
    repo.config.set("core.op-retention", "90").unwrap();
2213
    repo.save_config().unwrap();
2214
    let repo = Repo::open(root).unwrap().with_home(root.join("home"));
2215
    let r = repo.gc(false).unwrap();
2216
    assert_eq!(r.pruned.objects, 0);
2217
    assert_eq!(repo.log().unwrap().len(), 4);
2218
}
2219
2220
#[test]
2221
fn describe_amend_abandon_heads() {
2222
    hermetic();
2223
    let dir = tempfile::tempdir().unwrap();
2224
    let root = dir.path();
2225
    let mut repo = Repo::init(root).unwrap().with_home(root.join("home"));
2226
    repo.create_identity("Ada", "a@b", IdentityScope::User)
2227
        .unwrap();
2228
    repo.set_user_config("core.sign", "change").unwrap();
2229
    write(root, "a.txt", b"one\n");
2230
    let h1 = repo.commit("first", &[]).unwrap();
2231
    write(root, "a.txt", b"one\ntwo\n");
2232
    let h2 = repo.commit("secnod", &[]).unwrap();
2233
    let id2 = repo.store().get_change(&h2).unwrap().change_id;
2234
2235
    // describe: same ChangeId, new hash, bookmark and working copy follow.
2236
    let h2b = repo.describe(&h2, "second").unwrap();
2237
    assert_ne!(h2b, h2);
2238
    let c = repo.store().get_change(&h2b).unwrap();
2239
    assert_eq!(
2240
        (c.change_id, c.message.as_str(), c.deps.clone()),
2241
        (id2, "second", vec![h1])
2242
    );
2243
    assert_eq!(repo.bookmark_heads().unwrap(), vec![h2b]);
2244
    assert!(matches!(
2245
        repo.verify_change(&h2b).unwrap(),
2246
        SignatureStatus::Valid { .. }
2247
    ));
2248
    let s = repo.snapshot("status").unwrap();
2249
    assert!(s.statuses.is_empty(), "{:?}", s.statuses);
2250
    assert_eq!(
2251
        repo.resolve_change(&id2.short(8)).unwrap(),
2252
        h2b,
2253
        "the old object is no longer reachable from the log"
2254
    );
2255
    // Describing a non-head rewrites its dependents (h2b → h2c') and the working copy.
2256
    let h1b = repo.describe(&h1, "first, described").unwrap();
2257
    assert_ne!(h1b, h1);
2258
    let heads = repo.bookmark_heads().unwrap();
2259
    assert_eq!(heads.len(), 1);
2260
    let top = repo.store().get_change(&heads[0]).unwrap();
2261
    assert_eq!((top.change_id, top.deps.clone()), (id2, vec![h1b]));
2262
    assert!(
2263
        matches!(
2264
            repo.verify_change(&heads[0]).unwrap(),
2265
            SignatureStatus::Valid { .. }
2266
        ),
2267
        "rewritten own change is re-signed"
2268
    );
2269
    let (_, wc) = repo.working_copy().unwrap();
2270
    assert_eq!(
2271
        wc.deps,
2272
        vec![heads[0]],
2273
        "the working copy follows the rewrite"
2274
    );
2275
    assert!(!repo.snapshot("status").unwrap().changed);
2276
    let snap = repo.load_state(&heads).unwrap().materialize();
2277
    assert!(
2278
        matches!(&snap.files["a.txt"].content, FileContent::Text { bytes, .. } if bytes == b"one\ntwo\n")
2279
    );
2280
2281
    // amend: fold an edit into the head; the result is one change from h1.
2282
    write(root, "a.txt", b"one\ntwo\nthree\n");
2283
    write(root, "b.txt", b"b\n");
2284
    let h2c = repo.amend(None).unwrap();
2285
    let c = repo.store().get_change(&h2c).unwrap();
2286
    assert_eq!(c.change_id, id2);
2287
    assert_eq!(c.message, "second");
2288
    assert_eq!(repo.bookmark_heads().unwrap(), vec![h2c]);
2289
    assert_eq!(
2290
        repo.log().unwrap().len(),
2291
        3,
2292
        "working copy, amended head, first"
2293
    );
2294
    let snap = repo.load_state(&[h2c]).unwrap().materialize();
2295
    assert!(
2296
        matches!(&snap.files["a.txt"].content, FileContent::Text { bytes, .. } if bytes == b"one\ntwo\nthree\n")
2297
    );
2298
    assert!(snap.files.contains_key("b.txt"));
2299
    assert!(!repo.snapshot("status").unwrap().changed);
2300
    assert!(
2301
        repo.amend(None).is_err(),
2302
        "clean working copy and no message"
2303
    );
2304
    let h2d = repo.amend(Some("second, amended")).unwrap();
2305
    assert_eq!(
2306
        repo.store().get_change(&h2d).unwrap().message,
2307
        "second, amended"
2308
    );
2309
2310
    // abandon: the head goes, its content stays as uncommitted work.
2311
    repo.abandon(&h2d).unwrap();
2312
    assert_eq!(
2313
        repo.bookmark_heads().unwrap(),
2314
        vec![h1b],
2315
        "the described first change is the head again"
2316
    );
2317
    let s = repo.snapshot("status").unwrap();
2318
    let paths: Vec<_> = s
2319
        .statuses
2320
        .iter()
2321
        .map(|p| (p.path.as_str(), p.status))
2322
        .collect();
2323
    assert_eq!(
2324
        paths,
2325
        vec![
2326
            ("a.txt", ChangeStatus::Modified),
2327
            ("b.txt", ChangeStatus::Added)
2328
        ]
2329
    );
2330
    assert_eq!(fs::read(root.join("a.txt")).unwrap(), b"one\ntwo\nthree\n");
2331
    let h3 = repo.commit("recommitted", &[]).unwrap();
2332
    assert_eq!(repo.bookmark_heads().unwrap(), vec![h3]);
2333
    // undo brings the abandoned head back.
2334
    repo.undo().unwrap();
2335
    repo.undo().unwrap();
2336
    assert_eq!(repo.bookmark_heads().unwrap(), vec![h2d]);
2337
2338
    // Abandoning a non-head whose dependent references its atoms reifies
2339
    // the references (here: a.txt vanishes with it, so the dependent's edit
2340
    // of a.txt is dropped with a note) instead of refusing; undo restores it.
2341
    let base = repo.bookmark_heads().unwrap()[0];
2342
    let base_change = repo.store().get_change(&base).unwrap();
2343
    let h1_now = base_change.deps[0];
2344
    let notes = repo.abandon(&h1_now).unwrap();
2345
    assert!(
2346
        !notes.is_empty(),
2347
        "the dependent's edit of a.txt was reified"
2348
    );
2349
    let heads = repo.bookmark_heads().unwrap();
2350
    let after = repo.load_state(&heads).unwrap().materialize();
2351
    assert!(
2352
        !after.files.contains_key("a.txt") && after.files.contains_key("b.txt"),
2353
        "{:?}",
2354
        after.files.keys()
2355
    );
2356
    repo.undo().unwrap();
2357
    assert_eq!(repo.bookmark_heads().unwrap(), vec![base]);
2358
    write(root, "c.txt", b"c\n");
2359
    let hc = repo.commit("c", &[]).unwrap();
2360
    write(root, "d.txt", b"d\n");
2361
    let hd = repo.commit("d", &[hc]).unwrap();
2362
    assert_eq!(repo.store().get_change(&hd).unwrap().deps, vec![hc]);
2363
    repo.abandon(&hc).unwrap();
2364
    let heads: BTreeSet<_> = repo.bookmark_heads().unwrap().into_iter().collect();
2365
    assert!(!heads.contains(&hc));
2366
    let d_now = heads
2367
        .iter()
2368
        .find(|h| repo.store().get_change(h).unwrap().message == "d")
2369
        .copied()
2370
        .unwrap();
2371
    assert!(
2372
        repo.store().get_change(&d_now).unwrap().deps.is_empty(),
2373
        "d inherited c's (empty) dependencies"
2374
    );
2375
    let s = repo.snapshot("status").unwrap();
2376
    assert_eq!(
2377
        s.statuses
2378
            .iter()
2379
            .map(|p| p.path.as_str())
2380
            .collect::<Vec<_>>(),
2381
        vec!["c.txt"],
2382
        "c's content is now uncommitted work"
2383
    );
2384
}
2385
2386
#[test]
2387
fn git_export_mirrors_history() {
2388
    hermetic();
2389
    if std::process::Command::new("git")
2390
        .arg("--version")
2391
        .output()
2392
        .is_err()
2393
    {
2394
        eprintln!("git not installed; skipping");
2395
        return;
2396
    }
2397
    let dir = tempfile::tempdir().unwrap();
2398
    let root = dir.path();
2399
    let mut repo = Repo::init(&root.join("r"))
2400
        .unwrap()
2401
        .with_home(root.join("home"));
2402
    repo.create_identity("Ada Lovelace", "[email protected]", IdentityScope::User)
2403
        .unwrap();
2404
    let r = root.join("r");
2405
    write(&r, "README.md", b"hello\n");
2406
    write(&r, "src/main.rs", b"fn main() {}\n");
2407
    let h1 = repo.commit("first", &[]).unwrap();
2408
    write(&r, "src/main.rs", b"fn main() { run(); }\n");
2409
    write(&r, "logo.png", b"\x89PNG\0\0");
2410
    let h2 = repo.commit("second", &[]).unwrap();
2411
2412
    let git_dir = root.join("mirror.git");
2413
    let rep = repo.git_export(&git_dir).unwrap();
2414
    assert_eq!((rep.exported, rep.skipped, rep.heads), (2, 0, 1));
2415
    let git = |args: &[&str]| -> String {
2416
        let out = std::process::Command::new("git")
2417
            .arg("-C")
2418
            .arg(&git_dir)
2419
            .args(args)
2420
            .output()
2421
            .unwrap();
2422
        assert!(
2423
            out.status.success(),
2424
            "{}",
2425
            String::from_utf8_lossy(&out.stderr)
2426
        );
2427
        String::from_utf8_lossy(&out.stdout).trim().to_string()
2428
    };
2429
    assert_eq!(git(&["log", "--format=%s", "main"]), "second\nfirst");
2430
    assert_eq!(git(&["show", "main:src/main.rs"]), "fn main() { run(); }");
2431
    assert_eq!(git(&["show", "main:README.md"]), "hello");
2432
    let body = git(&["log", "-1", "--format=%B", "main"]);
2433
    assert!(
2434
        body.contains(&format!("Oxy-Hash: {}", h2.to_hex())),
2435
        "{body}"
2436
    );
2437
    assert!(body.contains("Change-Id: "), "{body}");
2438
    assert_eq!(
2439
        git(&["log", "-1", "--format=%an <%ae>", "main"]),
2440
        "Ada Lovelace <[email protected]>"
2441
    );
2442
    assert_eq!(
2443
        git(&["ls-tree", "--name-only", "main"]),
2444
        "README.md\nlogo.png\nsrc"
2445
    );
2446
2447
    // Re-export is incremental.
2448
    let rep = repo.git_export(&git_dir).unwrap();
2449
    assert_eq!((rep.exported, rep.skipped), (0, 2));
2450
2451
    // An independent change makes two heads; the next state is one more
2452
    // commit on the linear branch whose tree is the union.
2453
    repo.checkout(&[h1], false, "checkout").unwrap();
2454
    write(&r, "other.txt", b"o\n");
2455
    let h3 = repo.commit("third", &[]).unwrap();
2456
    let rep = repo.git_export(&git_dir).unwrap();
2457
    assert_eq!((rep.exported, rep.heads), (1, 2));
2458
    assert_eq!(git(&["log", "--format=%s", "main"]), "third\nsecond\nfirst");
2459
    let parents = git(&["rev-list", "--parents", "-1", "main"]);
2460
    assert_eq!(parents.split(' ').count(), 2, "one parent: {parents}");
2461
    assert_eq!(git(&["show", "main:other.txt"]), "o");
2462
    assert_eq!(git(&["show", "main:src/main.rs"]), "fn main() { run(); }");
2463
    assert_eq!(
2464
        git(&["ls-tree", "--name-only", "main"]),
2465
        "README.md\nlogo.png\nother.txt\nsrc"
2466
    );
2467
    let body = git(&["log", "-1", "--format=%B", "main"]);
2468
    assert!(
2469
        body.contains(&format!("Oxy-Hash: {}", h3.to_hex())) && body.contains("Oxy-State: "),
2470
        "{body}"
2471
    );
2472
    // A rewrite is a new state whose one new change is the rewritten one.
2473
    repo.describe(&h3, "third, described").unwrap();
2474
    let rep = repo.git_export(&git_dir).unwrap();
2475
    assert_eq!(rep.exported, 1);
2476
    assert_eq!(
2477
        git(&["log", "-1", "--format=%s", "main"]),
2478
        "third, described"
2479
    );
2480
    assert_eq!(git(&["log", "--format=%s", "main"]).lines().count(), 4);
2481
    let _ = h2;
2482
}
2483
2484
#[test]
2485
fn git_import_reproduces_trees() {
2486
    git_import_reproduces_trees_with(None);
2487
}
2488
2489
/// The same import with every merge rendered in batches of one file
2490
/// (oxygen#25): what a merge onto a base of thousands of files takes.
2491
#[test]
2492
fn git_import_reproduces_trees_in_batches() {
2493
    git_import_reproduces_trees_with(Some(1));
2494
}
2495
2496
fn git_import_reproduces_trees_with(batch: Option<usize>) {
2497
    crate::repo::git::set_merge_batch_for_tests(batch);
2498
    hermetic();
2499
    if std::process::Command::new("git")
2500
        .arg("--version")
2501
        .output()
2502
        .is_err()
2503
    {
2504
        eprintln!("git not installed; skipping");
2505
        return;
2506
    }
2507
    let dir = tempfile::tempdir().unwrap();
2508
    let root = dir.path();
2509
    let g = root.join("src.git");
2510
    fs::create_dir_all(&g).unwrap();
2511
    let git = |args: &[&str]| -> String {
2512
        let out = std::process::Command::new("git")
2513
            .arg("-C")
2514
            .arg(&g)
2515
            .args([
2516
                "-c",
2517
                "user.name=Grace",
2518
                "-c",
2519
                "[email protected]",
2520
                "-c",
2521
                "commit.gpgsign=false",
2522
            ])
2523
            .args(args)
2524
            .output()
2525
            .unwrap();
2526
        assert!(
2527
            out.status.success(),
2528
            "git {args:?}: {}",
2529
            String::from_utf8_lossy(&out.stderr)
2530
        );
2531
        String::from_utf8_lossy(&out.stdout).trim().to_string()
2532
    };
2533
    git(&["init", "-q", "-b", "main"]);
2534
    write(&g, "README.md", b"# Hi\n");
2535
    write(&g, "src/lib.rs", b"pub fn a() {}\n");
2536
    git(&["add", "."]);
2537
    git(&["commit", "-q", "-m", "initial"]);
2538
    write(&g, "src/lib.rs", b"pub fn a() {}\npub fn b() {}\n");
2539
    write(&g, "run.sh", b"#!/bin/sh\n");
2540
    #[cfg(unix)]
2541
    {
2542
        use std::os::unix::fs::PermissionsExt;
2543
        fs::set_permissions(g.join("run.sh"), fs::Permissions::from_mode(0o755)).unwrap();
2544
    }
2545
    write(&g, "logo.png", b"\x89PNG\0\0\x01");
2546
    git(&["add", "."]);
2547
    git(&[
2548
        "commit",
2549
        "-q",
2550
        "-m",
2551
        "second\n\nChange-Id: 0123456789abcdef0123456789abcdef",
2552
    ]);
2553
    // A branch that edits README, merged back with a conflict-free merge.
2554
    git(&["checkout", "-q", "-b", "topic", "HEAD~1"]);
2555
    write(&g, "README.md", b"# Hi\n\nMore.\n");
2556
    git(&["commit", "-q", "-am", "readme"]);
2557
    git(&["checkout", "-q", "main"]);
2558
    git(&["merge", "-q", "--no-ff", "-m", "merge topic", "topic"]);
2559
    // A branch from the initial commit inserting at the same place as
2560
    // "second": concurrent in Oxygen too, so the merge commit is a resolution.
2561
    let initial = git(&["rev-list", "--max-parents=0", "HEAD"]);
2562
    git(&["checkout", "-q", "-b", "clash", &initial]);
2563
    write(&g, "src/lib.rs", b"pub fn a() {}\npub fn c() {}\n");
2564
    git(&["commit", "-q", "-am", "clash"]);
2565
    git(&["checkout", "-q", "main"]);
2566
    let _ = std::process::Command::new("git")
2567
        .arg("-C")
2568
        .arg(&g)
2569
        .args(["merge", "-q", "clash"])
2570
        .output();
2571
    write(
2572
        &g,
2573
        "src/lib.rs",
2574
        b"pub fn a() {}\npub fn b() {}\npub fn c() {}\n",
2575
    );
2576
    git(&["add", "."]);
2577
    git(&["commit", "-q", "-m", "resolve clash"]);
2578
    git(&["rm", "-q", "logo.png"]);
2579
    git(&["commit", "-q", "-m", "drop logo"]);
2580
    // A rename with a small edit is imported as a move of the same node.
2581
    git(&["mv", "src/lib.rs", "src/lib2.rs"]);
2582
    write(
2583
        &g,
2584
        "src/lib2.rs",
2585
        b"pub fn a() {}\npub fn b() {}\npub fn c() {}\npub fn d() {}\n",
2586
    );
2587
    git(&["add", "."]);
2588
    git(&["commit", "-q", "-m", "rename lib"]);
2589
    // A branch that edits run.sh, merged keeping main's tree (`-s ours`):
2590
    // run.sh is the same as in the first parent's tree, but the merged
2591
    // change touched it, so the importer must compare it, not skip it.
2592
    git(&["checkout", "-q", "-b", "discarded"]);
2593
    write(&g, "run.sh", b"#!/bin/sh\necho discarded\n");
2594
    git(&["commit", "-q", "-am", "discarded edit"]);
2595
    git(&["checkout", "-q", "main"]);
2596
    git(&[
2597
        "merge",
2598
        "-q",
2599
        "-s",
2600
        "ours",
2601
        "-m",
2602
        "merge discarded, keeping ours",
2603
        "discarded",
2604
    ]);
2605
    let expected_count: usize = git(&["rev-list", "--count", "main"]).parse().unwrap();
2606
2607
    let dest = root.join("oxy");
2608
    let repo = Repo::init(&dest).unwrap().with_home(root.join("home"));
2609
    let rep = repo.import_git(&g, "main").unwrap();
2610
    assert_eq!(rep.commits, expected_count);
2611
    assert_eq!(rep.merges, 3);
2612
    assert_eq!(
2613
        fs::read(dest.join("run.sh")).unwrap(),
2614
        b"#!/bin/sh\n",
2615
        "the ours merge kept main's run.sh"
2616
    );
2617
    let v = repo.verify_git_import(&g, "main").unwrap();
2618
    assert_eq!(v.commits, expected_count, "every commit's tree reproduced");
2619
    assert!(v.mismatches.is_empty(), "{:?}", v.mismatches);
2620
    // The working copy equals the Git tree at main.
2621
    assert_eq!(
2622
        fs::read(dest.join("src/lib2.rs")).unwrap(),
2623
        b"pub fn a() {}\npub fn b() {}\npub fn c() {}\npub fn d() {}\n"
2624
    );
2625
    assert!(!dest.join("src/lib.rs").exists());
2626
    assert_eq!(
2627
        fs::read(dest.join("README.md")).unwrap(),
2628
        b"# Hi\n\nMore.\n"
2629
    );
2630
    assert!(!dest.join("logo.png").exists());
2631
    #[cfg(unix)]
2632
    {
2633
        use std::os::unix::fs::PermissionsExt;
2634
        assert!(
2635
            fs::metadata(dest.join("run.sh"))
2636
                .unwrap()
2637
                .permissions()
2638
                .mode()
2639
                & 0o111
2640
                != 0
2641
        );
2642
    }
2643
    assert!(
2644
        !repo.snapshot("status").unwrap().changed,
2645
        "clean after import"
2646
    );
2647
    let heads = repo.bookmark_heads().unwrap();
2648
    let st = repo.load_state(&heads).unwrap();
2649
    assert!(!st.materialize().is_conflicted());
2650
    assert_eq!(st.len(), expected_count);
2651
    let tip = repo
2652
        .log()
2653
        .unwrap()
2654
        .into_iter()
2655
        .find(|e| e.change.message.starts_with("rename lib"))
2656
        .unwrap();
2657
    let c = repo.store().get_change(&tip.hash).unwrap();
2658
    assert!(
2659
        c.tree_ops
2660
            .iter()
2661
            .any(|op| matches!(op, TreeOp::Move { name, .. } if name == "lib2.rs")),
2662
        "{:?}",
2663
        c.tree_ops
2664
    );
2665
    assert!(!c
2666
        .tree_ops
2667
        .iter()
2668
        .any(|op| matches!(op, TreeOp::AddNode { .. })));
2669
    // Messages carry Git trailers; the Change-Id trailer was honoured.
2670
    let log = repo.log().unwrap();
2671
    let second = log
2672
        .iter()
2673
        .find(|e| e.change.message.starts_with("second"))
2674
        .unwrap();
2675
    assert_eq!(
2676
        second.change.change_id,
2677
        ChangeId::from_hex("0123456789abcdef0123456789abcdef").unwrap()
2678
    );
2679
    assert!(second
2680
        .change
2681
        .message
2682
        .contains("Git-Author: Grace <[email protected]>"));
2683
    let resolve = log
2684
        .iter()
2685
        .find(|e| e.change.message.starts_with("resolve clash"))
2686
        .unwrap();
2687
    assert_eq!(
2688
        resolve.change.kind,
2689
        ChangeKind::Resolution,
2690
        "a conflicting Git merge becomes a resolution"
2691
    );
2692
    // Re-importing into another fresh repository gives the same ChangeIds.
2693
    let repo2 = Repo::init(&root.join("oxy2"))
2694
        .unwrap()
2695
        .with_home(root.join("home"));
2696
    repo2.import_git(&g, "main").unwrap();
2697
    // New nodes' identifiers derive from the commit (spec §23), so the
2698
    // re-import is not just the same ChangeIds but the same changes.
2699
    assert_eq!(
2700
        repo2.bookmark_heads().unwrap(),
2701
        repo.bookmark_heads().unwrap()
2702
    );
2703
    let ids: BTreeSet<ChangeId> = repo
2704
        .log()
2705
        .unwrap()
2706
        .iter()
2707
        .filter(|e| !e.is_working_copy)
2708
        .map(|e| e.change.change_id)
2709
        .collect();
2710
    let ids2: BTreeSet<ChangeId> = repo2
2711
        .log()
2712
        .unwrap()
2713
        .iter()
2714
        .filter(|e| !e.is_working_copy)
2715
        .map(|e| e.change.change_id)
2716
        .collect();
2717
    assert_eq!(ids, ids2);
2718
    // Round trip back out to Git reproduces the tip tree.
2719
    let mirror = root.join("mirror.git");
2720
    repo.git_export(&mirror).unwrap();
2721
    let out = std::process::Command::new("git")
2722
        .arg("-C")
2723
        .arg(&mirror)
2724
        .args(["show", "main:src/lib2.rs"])
2725
        .output()
2726
        .unwrap();
2727
    assert_eq!(
2728
        String::from_utf8_lossy(&out.stdout),
2729
        "pub fn a() {}\npub fn b() {}\npub fn c() {}\npub fn d() {}\n"
2730
    );
2731
    let out = std::process::Command::new("git")
2732
        .arg("-C")
2733
        .arg(&mirror)
2734
        .args(["show", "main:src/lib.rs"])
2735
        .output()
2736
        .unwrap();
2737
    assert!(
2738
        !out.status.success(),
2739
        "the old path is gone from the export"
2740
    );
2741
}
2742
2743
#[test]
2744
fn checkpoints_accelerate_loading_and_stay_correct() {
2745
    hermetic();
2746
    let dir = tempfile::tempdir().unwrap();
2747
    let root = dir.path();
2748
    let mut repo = Repo::init(root).unwrap().with_home(root.join("home"));
2749
    repo.config.set("core.checkpoint-interval", "5").unwrap();
2750
    repo.save_config().unwrap();
2751
    let repo = Repo::open(root).unwrap().with_home(root.join("home"));
2752
    let mut hashes = Vec::new();
2753
    for i in 0..12 {
2754
        write(
2755
            root,
2756
            "a.txt",
2757
            format!(
2758
                "{}\n",
2759
                (0..=i)
2760
                    .map(|k| k.to_string())
2761
                    .collect::<Vec<_>>()
2762
                    .join("\n")
2763
            )
2764
            .as_bytes(),
2765
        );
2766
        write(root, &format!("f{i}.txt"), b"x\n");
2767
        hashes.push(repo.commit(&format!("c{i}"), &[]).unwrap());
2768
    }
2769
    let (_, cp) = repo
2770
        .latest_checkpoint("main")
2771
        .unwrap()
2772
        .expect("automatic checkpoint");
2773
    assert!(cp.count >= 5 && cp.count <= 12, "{}", cp.count);
2774
    // Loading through the checkpoint equals loading everything.
2775
    let heads = repo.bookmark_heads().unwrap();
2776
    let fast = repo.load_state(&heads).unwrap();
2777
    let full = repo.load_state_full(&heads).unwrap();
2778
    assert_eq!(fast.len(), full.len());
2779
    assert_eq!(fast.heads(), full.heads());
2780
    let (a, b) = (fast.materialize(), full.materialize());
2781
    assert_eq!(
2782
        a.files.keys().collect::<Vec<_>>(),
2783
        b.files.keys().collect::<Vec<_>>()
2784
    );
2785
    for (p, f) in &a.files {
2786
        assert_eq!(f.content, b.files[p].content, "{p}");
2787
    }
2788
    assert!(repo.load_state_checkpointed(&heads).unwrap().is_some());
2789
    // A head set that does not contain the checkpoint's heads falls back.
2790
    assert!(repo
2791
        .load_state_checkpointed(&[hashes[0]])
2792
        .unwrap()
2793
        .is_none());
2794
    assert_eq!(repo.load_state(&[hashes[0]]).unwrap().len(), 1);
2795
    // Everything else keeps working on top of the checkpoint.
2796
    assert!(!repo.snapshot("status").unwrap().changed);
2797
    let h = repo.describe(&hashes[3], "c3 described").unwrap();
2798
    assert_eq!(repo.store().get_change(&h).unwrap().message, "c3 described");
2799
    let (r, n, bytes) = repo.checkpoint().unwrap();
2800
    assert!(n >= 12 && bytes > 0);
2801
    assert_eq!(repo.latest_checkpoint("main").unwrap().unwrap().0, r);
2802
    write(root, "a.txt", b"after\n");
2803
    let h_after = repo.commit("after", &[]).unwrap();
2804
    let st = repo.load_state(&repo.bookmark_heads().unwrap()).unwrap();
2805
    assert!(st.contains(&h_after));
2806
    assert!(
2807
        matches!(&st.materialize().files["a.txt"].content, FileContent::Text { bytes, .. } if bytes == b"after\n")
2808
    );
2809
    assert_eq!(repo.log().unwrap().len(), 14);
2810
    // Checkpoints survive gc.
2811
    repo.gc(true).unwrap();
2812
    assert!(repo.latest_checkpoint("main").unwrap().is_some());
2813
    assert!(repo
2814
        .load_state_checkpointed(&repo.bookmark_heads().unwrap())
2815
        .unwrap()
2816
        .is_some());
2817
}
2818
2819
#[test]
2820
fn quick_status_for_prompts() {
2821
    hermetic();
2822
    let dir = tempfile::tempdir().unwrap();
2823
    let root = dir.path();
2824
    let origin = Repo::init(&root.join("origin")).unwrap();
2825
    let url = root.join("origin").to_string_lossy().to_string();
2826
    let a = Repo::clone(&url, &root.join("a"))
2827
        .unwrap()
2828
        .with_home(root.join("home"));
2829
    let ops_before = a.op_log().unwrap().len();
2830
    let info = a.quick_status().unwrap();
2831
    assert_eq!(
2832
        (
2833
            info.bookmark.as_str(),
2834
            info.heads,
2835
            info.dirty,
2836
            info.conflicted,
2837
            info.ahead,
2838
            info.behind
2839
        ),
2840
        ("main", 0, false, false, Some(0), Some(0))
2841
    );
2842
    write(&root.join("a"), "f.txt", b"f\n");
2843
    assert!(a.quick_status().unwrap().dirty, "a new file is dirty");
2844
    assert_eq!(
2845
        a.op_log().unwrap().len(),
2846
        ops_before,
2847
        "quick_status records nothing"
2848
    );
2849
    // A snapshotted but uncommitted change is still dirty.
2850
    a.snapshot("status").unwrap();
2851
    assert!(a.quick_status().unwrap().dirty);
2852
    a.commit("f", &[]).unwrap();
2853
    let info = a.quick_status().unwrap();
2854
    assert!(!info.dirty, "clean right after a commit");
2855
    assert_eq!((info.ahead, info.behind), (Some(1), Some(0)));
2856
    assert_eq!(
2857
        info.format("%b %c%d%x%A%D"),
2858
        format!("main {}+1", info.change_id)
2859
    );
2860
    assert_eq!(info.format("[%h heads] %a/%B %%"), "[1 heads] 1/0 %");
2861
    // Touching a file without changing it is not dirty; changing content of
2862
    // the same size is.
2863
    let p = root.join("a/f.txt");
2864
    let content = fs::read(&p).unwrap();
2865
    fs::write(&p, &content).unwrap();
2866
    assert!(!a.quick_status().unwrap().dirty);
2867
    fs::write(&p, b"g\n").unwrap();
2868
    assert!(a.quick_status().unwrap().dirty);
2869
    fs::write(&p, b"f\n").unwrap();
2870
    // Push, then a second clone commits and pushes: we are behind.
2871
    assert!(a.push("origin", false).unwrap()[0].ok);
2872
    assert_eq!(a.quick_status().unwrap().ahead, Some(0));
2873
    let b = Repo::clone(&url, &root.join("b"))
2874
        .unwrap()
2875
        .with_home(root.join("home-b"));
2876
    write(&root.join("b"), "g.txt", b"g\n");
2877
    b.commit("g", &[]).unwrap();
2878
    b.push("origin", false).unwrap();
2879
    a.fetch("origin").unwrap();
2880
    let info = a.quick_status().unwrap();
2881
    assert_eq!((info.ahead, info.behind), (Some(0), Some(1)));
2882
    assert_eq!(info.format("%A%D"), "-1");
2883
    let _ = origin;
2884
}
2885
2886
#[test]
2887
fn lazy_blobs_are_fetched_on_first_read() {
2888
    hermetic();
2889
    let dir = tempfile::tempdir().unwrap();
2890
    let root = dir.path();
2891
    let origin_dir = root.join("origin");
2892
    let origin = Repo::init(&origin_dir)
2893
        .unwrap()
2894
        .with_home(root.join("home"));
2895
    let url = origin_dir.to_string_lossy().to_string();
2896
    let big: Vec<u8> = (0..200_000u32).map(|i| (i % 251) as u8).collect(); // has NUL bytes: opaque
2897
    write(&origin_dir, "big.bin", &big);
2898
    write(&origin_dir, "small.bin", &[0u8, 1, 2]);
2899
    write(&origin_dir, "t.txt", b"t\n");
2900
    let h = origin.commit("blobs", &[]).unwrap();
2901
    let big_ref = Repo::blob_ref(&big);
2902
2903
    // Fetch only (no checkout) with a filter: the big blob stays absent.
2904
    let a = Repo::init_with_id(&root.join("a"), origin.id().unwrap())
2905
        .unwrap()
2906
        .with_home(root.join("home"));
2907
    let a = {
2908
        let mut a = a;
2909
        a.config.set("remote.origin.url", &url).unwrap();
2910
        a.config.set("filter.max-blob", "100K").unwrap();
2911
        a.save_config().unwrap();
2912
        a
2913
    };
2914
    assert_eq!(a.config.max_blob, Some(100 * 1024));
2915
    a.fetch("origin").unwrap();
2916
    assert!(a.store().has(&h));
2917
    assert!(!a.store().has(&big_ref), "withheld");
2918
    assert!(
2919
        a.store().has(&Repo::blob_ref(&[0u8, 1, 2])),
2920
        "small blob came along"
2921
    );
2922
    assert_eq!(a.lazy_remote(&big_ref).as_deref(), Some("origin"));
2923
2924
    // status and commit do not need it: adopt the state, edit a text file, commit.
2925
    let (op_ref, op) = a.head_op().unwrap();
2926
    let mut view = op.view.clone();
2927
    view.bookmarks.insert(
2928
        "main".into(),
2929
        a.store().put_state(&StateObject::new(vec![h])).unwrap(),
2930
    );
2931
    a.record_op(&[op_ref], "adopt", view).unwrap();
2932
    // Checkout reads the blob lazily, which fetches it.
2933
    a.checkout(&[h], true, "checkout").unwrap();
2934
    assert!(a.store().has(&big_ref), "fetched on first read");
2935
    assert_eq!(fs::read(root.join("a/big.bin")).unwrap(), big);
2936
    assert!(a.lazy_remote(&big_ref).is_none(), "no longer registered");
2937
    write(&root.join("a"), "t.txt", b"t2\n");
2938
    a.commit("text edit", &[]).unwrap();
2939
2940
    // clone --max-blob records the filter; the checkout fetches lazily.
2941
    let b = Repo::clone_with(&url, &root.join("b"), Some(1024), &[]).unwrap();
2942
    assert_eq!(b.config.max_blob, Some(1024));
2943
    assert_eq!(fs::read(root.join("b/big.bin")).unwrap(), big);
2944
    assert_eq!(parse_size("2M").unwrap(), 2 << 20);
2945
    assert!(parse_size("lots").is_err());
2946
}
2947
2948
#[test]
2949
fn sparse_checkout_materializes_only_chosen_paths() {
2950
    hermetic();
2951
    let dir = tempfile::tempdir().unwrap();
2952
    let root = dir.path();
2953
    let origin_dir = root.join("origin");
2954
    let origin = Repo::init(&origin_dir)
2955
        .unwrap()
2956
        .with_home(root.join("home"));
2957
    write(&origin_dir, "src/main.rs", b"fn main() {}\n");
2958
    write(&origin_dir, "src/lib.rs", b"pub fn a() {}\n");
2959
    write(&origin_dir, "docs/guide.md", b"# guide\n");
2960
    let logo: Vec<u8> = (0..50_000u32).map(|i| (i % 7) as u8).collect();
2961
    write(&origin_dir, "docs/logo.png", &logo);
2962
    write(&origin_dir, "README.md", b"# top\n");
2963
    let h1 = origin.commit("tree", &[]).unwrap();
2964
    let url = origin_dir.to_string_lossy().to_string();
2965
2966
    let a = Repo::clone_with(&url, &root.join("a"), None, &["src".into()])
2967
        .unwrap()
2968
        .with_home(root.join("home"));
2969
    assert_eq!(a.config.sparse_paths, vec!["src"]);
2970
    assert_eq!(a.config.max_blob, Some(0), "sparse implies lazy blobs");
2971
    assert!(root.join("a/src/main.rs").exists());
2972
    assert!(!root.join("a/docs").exists() && !root.join("a/README.md").exists());
2973
    assert!(
2974
        !a.store().has(&Repo::blob_ref(&logo)),
2975
        "out-of-scope blob never fetched"
2976
    );
2977
    assert!(
2978
        !a.snapshot("status").unwrap().changed,
2979
        "out-of-scope files are not removals"
2980
    );
2981
    assert!(!a.quick_status().unwrap().dirty);
2982
2983
    // Edits in scope commit normally and keep the rest of the tree intact.
2984
    write(
2985
        &root.join("a"),
2986
        "src/lib.rs",
2987
        b"pub fn a() {}\npub fn b() {}\n",
2988
    );
2989
    let h2 = a.commit("edit lib", &[]).unwrap();
2990
    let st = a.load_state(&[h2]).unwrap().materialize();
2991
    assert!(
2992
        st.files.contains_key("docs/guide.md"),
2993
        "the state still has everything"
2994
    );
2995
    assert!(a.push("origin", false).unwrap()[0].ok);
2996
    origin.refresh().unwrap();
2997
    // Files created outside the scope are ignored by status.
2998
    write(&root.join("a"), "docs/new.md", b"ignored\n");
2999
    assert!(a.snapshot("status").unwrap().statuses.is_empty());
3000
3001
    // Widening the filter checks out the rest; narrowing leaves stray files alone.
3002
    let mut a = a;
3003
    a.config.set("filter.paths", "src,docs").unwrap();
3004
    a.save_config().unwrap();
3005
    let r = a
3006
        .checkout(&a.bookmark_heads().unwrap(), true, "widen")
3007
        .unwrap();
3008
    assert!(r.written >= 2);
3009
    assert_eq!(
3010
        fs::read(root.join("a/docs/logo.png")).unwrap(),
3011
        logo,
3012
        "now fetched lazily"
3013
    );
3014
    assert!(!root.join("a/README.md").exists());
3015
    // Origin sees the change made under a sparse checkout with the full tree intact.
3016
    origin.pull("origin").err();
3017
    let full = origin
3018
        .load_state(&origin.bookmark_heads().unwrap())
3019
        .unwrap()
3020
        .materialize();
3021
    assert!(
3022
        matches!(&full.files["src/lib.rs"].content, FileContent::Text { bytes, .. } if bytes == b"pub fn a() {}\npub fn b() {}\n")
3023
    );
3024
    assert!(full.files.contains_key("README.md"));
3025
    let _ = h1;
3026
}
3027
3028
/// #137: a depth-0 clone takes no change, so the blobs of the state's
3029
/// binary files came with nothing and the checkout failed ("object … not
3030
/// found"); they are fetched with the checkpoint, or left lazy under
3031
/// `--max-blob`.
3032
#[test]
3033
fn a_depth_0_clone_brings_its_binary_files() {
3034
    hermetic();
3035
    let dir = tempfile::tempdir().unwrap();
3036
    let root = dir.path();
3037
    let origin_dir = root.join("origin");
3038
    let origin = Repo::init(&origin_dir)
3039
        .unwrap()
3040
        .with_home(root.join("home"));
3041
    let png: Vec<u8> = (0..4000u32)
3042
        .map(|i| (i * 7 % 251) as u8)
3043
        .chain([0, 0xff])
3044
        .collect();
3045
    // The logo comes with a.txt's first line, and the head edits that line,
3046
    // so the change that set the logo is below the head, not a head itself.
3047
    write(&origin_dir, "logo.png", &png);
3048
    write(&origin_dir, "a.txt", b"first\n");
3049
    origin.commit("logo", &[]).unwrap();
3050
    write(&origin_dir, "a.txt", b"later\n");
3051
    origin.commit("later", &[]).unwrap();
3052
    assert_eq!(origin.bookmark_heads().unwrap().len(), 1);
3053
    let url = origin_dir.to_string_lossy().to_string();
3054
    Repo::clone_shallow(&url, &root.join("a"), 0, None, &[]).unwrap();
3055
    assert_eq!(fs::read(root.join("a/logo.png")).unwrap(), png);
3056
    let lazy = Repo::clone_shallow(&url, &root.join("b"), 0, Some(0), &[]).unwrap();
3057
    assert_eq!(fs::read(root.join("b/a.txt")).unwrap(), b"later\n");
3058
    let blob = {
3059
        let heads = lazy.bookmark_heads().unwrap();
3060
        let st = lazy.load_state_history(&heads).unwrap();
3061
        st.opaque_nodes()
3062
            .iter()
3063
            .flat_map(|n| st.live_blobs(n))
3064
            .next()
3065
            .unwrap()
3066
    };
3067
    assert_eq!(lazy.read_blob(&blob).unwrap(), png, "fetched on read");
3068
    // Depth 0 takes no change: the head is the boundary; the log comes from
3069
    // the checkpoint; a change on top commits and pushes.
3070
    let mut a = Repo::open(&root.join("a"))
3071
        .unwrap()
3072
        .with_home(root.join("home"));
3073
    let head = origin.bookmark_heads().unwrap()[0];
3074
    assert!(!a.store().has(&head), "no change fetched");
3075
    assert!(a.boundary().contains(&head));
3076
    assert_eq!(
3077
        a.log()
3078
            .unwrap()
3079
            .iter()
3080
            .filter(|e| !e.is_working_copy)
3081
            .count(),
3082
        2,
3083
        "the log from the checkpoint"
3084
    );
3085
    write(&root.join("a"), "a.txt", b"later\nmine\n");
3086
    a.config.set("remote.origin.url", &url).unwrap();
3087
    a.save_config().unwrap();
3088
    let mine = a.commit("mine", &[]).unwrap();
3089
    assert!(a.push("origin", false).unwrap().iter().all(|r| r.ok));
3090
    origin.refresh().unwrap();
3091
    assert!(origin.store().has(&mine));
3092
    assert_eq!(origin.bookmark_heads().unwrap(), vec![mine]);
3093
    // And pulls what comes after.
3094
    origin
3095
        .checkout(&origin.bookmark_heads().unwrap(), false, "co")
3096
        .unwrap();
3097
    write(&origin_dir, "a.txt", b"later\nmine\ntheirs\n");
3098
    origin.snapshot("t").unwrap();
3099
    origin.commit("theirs", &[]).unwrap();
3100
    a.pull("origin").unwrap();
3101
    assert_eq!(
3102
        fs::read(root.join("a/a.txt")).unwrap(),
3103
        b"later\nmine\ntheirs\n"
3104
    );
3105
}
3106
3107
#[test]
3108
fn shallow_clone_and_deepen() {
3109
    hermetic();
3110
    let dir = tempfile::tempdir().unwrap();
3111
    let root = dir.path();
3112
    let origin_dir = root.join("origin");
3113
    let origin = Repo::init(&origin_dir)
3114
        .unwrap()
3115
        .with_home(root.join("home"));
3116
    let mut hashes = Vec::new();
3117
    for i in 0..8 {
3118
        write(
3119
            &origin_dir,
3120
            "a.txt",
3121
            format!(
3122
                "{}\n",
3123
                (0..=i)
3124
                    .map(|k| k.to_string())
3125
                    .collect::<Vec<_>>()
3126
                    .join("\n")
3127
            )
3128
            .as_bytes(),
3129
        );
3130
        hashes.push(origin.commit(&format!("c{i}"), &[]).unwrap());
3131
    }
3132
    let url = origin_dir.to_string_lossy().to_string();
3133
    let a = Repo::clone_shallow(&url, &root.join("a"), 3, None, &[])
3134
        .unwrap()
3135
        .with_home(root.join("home"));
3136
    assert!(a.is_shallow());
3137
    assert_eq!(
3138
        fs::read_to_string(root.join("a/a.txt")).unwrap(),
3139
        "0\n1\n2\n3\n4\n5\n6\n7\n"
3140
    );
3141
    assert!(
3142
        a.store().has(&hashes[7]) && a.store().has(&hashes[5]),
3143
        "three levels present"
3144
    );
3145
    assert!(!a.store().has(&hashes[4]), "beyond the depth is absent");
3146
    assert_eq!(a.boundary(), [hashes[4]].into_iter().collect());
3147
    assert_eq!(
3148
        a.log().unwrap().len(),
3149
        9,
3150
        "the log shows every change from the checkpoint's metadata"
3151
    );
3152
    assert!(!a.snapshot("status").unwrap().changed);
3153
    assert_eq!(a.quick_status().unwrap().heads, 1);
3154
3155
    // Work continues on top of the shallow history and pushes back.
3156
    write(&root.join("a"), "a.txt", b"0\n1\n2\n3\n4\n5\n6\n7\n8\n");
3157
    let h_new = a.commit("c8", &[]).unwrap();
3158
    assert!(a.push("origin", false).unwrap()[0].ok);
3159
    origin.refresh().unwrap();
3160
    assert_eq!(origin.bookmark_heads().unwrap(), vec![h_new]);
3161
    // Fetching new work from origin into the shallow clone works too.
3162
    write(&origin_dir, "b.txt", b"b\n");
3163
    origin.pull("origin").err();
3164
    let (_, wc) = origin.working_copy().unwrap();
3165
    let _ = wc;
3166
    origin
3167
        .checkout(&origin.bookmark_heads().unwrap(), true, "co")
3168
        .unwrap();
3169
    write(&origin_dir, "b.txt", b"b\n");
3170
    let h_b = origin.commit("b", &[]).unwrap();
3171
    let pr = a.pull("origin").unwrap();
3172
    assert!(pr.changed);
3173
    assert!(a.store().has(&h_b));
3174
    assert!(root.join("a/b.txt").exists());
3175
3176
    // Deepening fetches older history until the boundary is gone.
3177
    // Every commit also depends on the change that created the file, so two
3178
    // levels below the boundary hold h4, h3, and the root.
3179
    assert!(a.deepen("origin", 2).unwrap() >= 2);
3180
    assert!(a.store().has(&hashes[3]));
3181
    assert!(a.is_shallow());
3182
    a.deepen("origin", 100).unwrap();
3183
    assert!(!a.is_shallow(), "boundary reached the root");
3184
    assert!(a.store().has(&hashes[0]));
3185
    assert_eq!(
3186
        a.load_state_full(&a.bookmark_heads().unwrap())
3187
            .unwrap()
3188
            .len(),
3189
        10
3190
    );
3191
}
3192
3193
#[test]
3194
fn tags_are_immutable_named_states_and_travel() {
3195
    hermetic();
3196
    let dir = tempfile::tempdir().unwrap();
3197
    let root = dir.path();
3198
    let origin = Repo::init(&root.join("origin")).unwrap();
3199
    let url = root.join("origin").to_string_lossy().to_string();
3200
    let mut a = Repo::clone(&url, &root.join("a"))
3201
        .unwrap()
3202
        .with_home(root.join("home-a"));
3203
    let (key_a, _) = a
3204
        .create_identity("Ada", "[email protected]", IdentityScope::User)
3205
        .unwrap();
3206
    write(&root.join("a"), "f.txt", b"1\n");
3207
    let h1 = a.commit("one", &[]).unwrap();
3208
    write(&root.join("a"), "f.txt", b"1\n2\n");
3209
    let h2 = a.commit("two", &[]).unwrap();
3210
3211
    let t = a.tag_create("v1", &[h1], "first release").unwrap();
3212
    assert_eq!(
3213
        (t.heads.clone(), t.signer.as_deref()),
3214
        (vec![h1], Some("Ada"))
3215
    );
3216
    assert!(a.tag_create("v1", &[h2], "").is_err(), "immutable");
3217
    assert!(a.tag_create("bad/name", &[h2], "").is_err());
3218
    assert_eq!(a.tag_heads("v1").unwrap(), Some(vec![h1]));
3219
    assert_eq!(a.resolve_heads("v1").unwrap(), vec![h1]);
3220
    assert_eq!(a.resolve_heads("main").unwrap(), vec![h2]);
3221
    let (_, sa) = a.tag_attest("v1").unwrap().unwrap();
3222
    assert_eq!(sa.sigs[0].key, key_a);
3223
    // Without a policy every client is sent every tag, whatever features
3224
    // it declares (oxygen#131).
3225
    let mut refs = a.remote_refs().unwrap();
3226
    a.refs_for_client(&mut refs, None);
3227
    assert_eq!(refs.tags.len(), 1);
3228
    // Checkout by tag.
3229
    a.checkout(&a.resolve_heads("v1").unwrap(), false, "co")
3230
        .unwrap();
3231
    assert_eq!(fs::read(root.join("a/f.txt")).unwrap(), b"1\n");
3232
    a.checkout(&a.bookmark_heads().unwrap(), false, "co")
3233
        .unwrap();
3234
3235
    // Push carries the tag; a second attestation for the name is refused.
3236
    let r = a.push("origin", false).unwrap();
3237
    origin.refresh().unwrap();
3238
    assert!(r.iter().any(|x| x.name == "tags/v1" && x.ok), "{r:?}");
3239
    assert_eq!(origin.tag_heads("v1").unwrap(), Some(vec![h1]));
3240
    let mut forged = a
3241
        .tag_refs()
3242
        .unwrap()
3243
        .into_iter()
3244
        .find(|t| t.name == "v1")
3245
        .unwrap();
3246
    forged.state = origin
3247
        .store()
3248
        .put_state(&StateObject::new(vec![h2]))
3249
        .unwrap();
3250
    forged.heads = vec![h2];
3251
    forged.attestation = None;
3252
    let r = origin
3253
        .receive_push(Bundle::default(), vec![], None, vec![forged])
3254
        .unwrap();
3255
    assert!(!r[0].ok && r[0].reason.contains("immutable"), "{r:?}");
3256
3257
    // A clone gets the tag; a later tag arrives on fetch.
3258
    let b = Repo::clone(&url, &root.join("b"))
3259
        .unwrap()
3260
        .with_home(root.join("home-b"));
3261
    assert_eq!(b.tag_heads("v1").unwrap(), Some(vec![h1]));
3262
    assert!(b.tags().unwrap()[0].signer.as_deref() == Some("Ada"));
3263
    a.tag_create("v2", &[h2], "second").unwrap();
3264
    a.push("origin", false).unwrap();
3265
    origin.refresh().unwrap();
3266
    let rep = b.fetch("origin").unwrap();
3267
    assert_eq!(rep.new_tags, 1);
3268
    assert_eq!(b.tag_heads("v2").unwrap(), Some(vec![h2]));
3269
3270
    // Under a policy, an unattested tag is refused and an attested one by the root passes.
3271
    a.policy_init().unwrap();
3272
    a.push("origin", false).unwrap();
3273
    origin.refresh().unwrap();
3274
    let unattested = crate::protocol::TagRef::new(
3275
        "v3".into(),
3276
        origin
3277
            .store()
3278
            .put_state(&StateObject::new(vec![h2]))
3279
            .unwrap(),
3280
        vec![h2],
3281
        None,
3282
    );
3283
    let r = origin
3284
        .receive_push(Bundle::default(), vec![], None, vec![unattested])
3285
        .unwrap();
3286
    assert!(!r[0].ok && r[0].reason.contains("attestation"), "{r:?}");
3287
    a.tag_create("v3", &[h2], "").unwrap();
3288
    let r = a.push("origin", false).unwrap();
3289
    origin.refresh().unwrap();
3290
    assert!(r.iter().any(|x| x.name == "tags/v3" && x.ok), "{r:?}");
3291
    assert!(a.gc(true).is_ok());
3292
    assert_eq!(a.tags().unwrap().len(), 3, "tags survive gc");
3293
3294
    // After a rotation the policy names only the new key, yet a fresh clone
3295
    // still takes the tags the old key made before it; the old key makes
3296
    // nothing new.
3297
    let rot = a.rotate_identity().unwrap();
3298
    let r = a.push("origin", false).unwrap();
3299
    origin.refresh().unwrap();
3300
    assert!(r.iter().all(|x| x.ok), "{r:?}");
3301
    let c = Repo::clone(&url, &root.join("c"))
3302
        .unwrap()
3303
        .with_home(root.join("home-c"));
3304
    assert_eq!(c.tag_heads("v3").unwrap(), Some(vec![h2]));
3305
    let (_, sp) = c.current_policy().unwrap().unwrap();
3306
    assert!(!sp.policy.authorizes(&key_a, "tags/v9"));
3307
    let made = c.identity(&rot.new).unwrap().created;
3308
    assert!(c.predecessor_authorized(&sp.policy, &key_a, "tags/v9", made - 1));
3309
    assert!(!c.predecessor_authorized(&sp.policy, &key_a, "tags/v9", made));
3310
    assert!(!c.predecessor_authorized(&sp.policy, &rot.new, "tags/v9", 0));
3311
}
3312
3313
#[test]
3314
fn multiple_workspaces_share_a_repository() {
3315
    hermetic();
3316
    let dir = tempfile::tempdir().unwrap();
3317
    let root = dir.path();
3318
    let main_dir = root.join("main");
3319
    let repo = Repo::init(&main_dir).unwrap().with_home(root.join("home"));
3320
    write(&main_dir, "a.txt", b"a\n");
3321
    let h1 = repo.commit("a", &[]).unwrap();
3322
    assert_eq!(repo.workspaces().unwrap().len(), 1);
3323
3324
    // A second workspace elsewhere, checked out on the bookmark.
3325
    let ws_dir = root.join("ws2");
3326
    let ws = repo.workspace_add(&ws_dir, None).unwrap();
3327
    assert!(ws_dir.join(".oxy").is_file());
3328
    assert_eq!(fs::read(ws_dir.join("a.txt")).unwrap(), b"a\n");
3329
    assert_ne!(ws.workspace(), repo.workspace());
3330
    let list = repo.workspaces().unwrap();
3331
    assert_eq!(list.len(), 2);
3332
    assert!(list
3333
        .iter()
3334
        .any(|w| w.id == ws.workspace() && w.path == ws_dir.canonicalize().unwrap() && !w.current));
3335
    assert!(!ws.snapshot("status").unwrap().changed);
3336
3337
    // Work in the second workspace: its own working copy, shared bookmark.
3338
    write(&ws_dir, "b.txt", b"b\n");
3339
    let s = ws.snapshot("status").unwrap();
3340
    assert_eq!(s.statuses.len(), 1);
3341
    assert!(
3342
        !repo.snapshot("status").unwrap().changed,
3343
        "the first workspace is untouched"
3344
    );
3345
    let h2 = ws.commit("b from ws2", &[]).unwrap();
3346
    repo.refresh().unwrap();
3347
    let mut heads = repo.bookmark_heads().unwrap();
3348
    heads.sort();
3349
    let mut want = vec![h1, h2];
3350
    want.sort();
3351
    assert_eq!(heads, want, "both workspaces see the bookmark move");
3352
    assert!(!main_dir.join("b.txt").exists());
3353
    repo.checkout(&repo.bookmark_heads().unwrap(), false, "co")
3354
        .unwrap();
3355
    assert!(main_dir.join("b.txt").exists());
3356
3357
    // Reopening from inside the second workspace finds the shared repository.
3358
    let reopened = Repo::open(&ws_dir).unwrap();
3359
    assert_eq!(reopened.workspace(), ws.workspace());
3360
    assert_eq!(reopened.id().unwrap(), repo.id().unwrap());
3361
    assert_eq!(reopened.quick_status().unwrap().heads, 2);
3362
3363
    // Workspaces cannot nest; forget drops one from the view but keeps files.
3364
    assert!(repo.workspace_add(&main_dir.join("inner"), None).is_err());
3365
    assert!(repo.workspace_forget(&repo.workspace()).is_err());
3366
    repo.workspace_forget(&ws.workspace()).unwrap();
3367
    assert_eq!(repo.workspaces().unwrap().len(), 1);
3368
    assert!(ws_dir.join("b.txt").exists());
3369
    assert!(
3370
        ws.snapshot("status").is_err(),
3371
        "a forgotten workspace is no longer in the view"
3372
    );
3373
3374
    // The working-copy lock: re-entrant in a thread; a lock whose process
3375
    // is gone is taken over, and a live process's is not, however old.
3376
    let lock = repo.lock_snapshot().unwrap();
3377
    let again = repo.lock_working_copy().unwrap();
3378
    drop(again);
3379
    drop(lock);
3380
    let lock_path = main_dir
3381
        .join(".oxy/workspaces")
3382
        .join(repo.workspace().to_hex())
3383
        .join("lock");
3384
    let old = std::time::SystemTime::now() - std::time::Duration::from_secs(120);
3385
    let age = |p: &Path| fs::File::open(p).unwrap().set_modified(old).unwrap();
3386
    fs::write(&lock_path, std::process::id().to_string()).unwrap();
3387
    age(&lock_path);
3388
    assert!(
3389
        !super::workspace::lock_is_stale(&lock_path),
3390
        "a live process keeps its lock"
3391
    );
3392
    fs::write(&lock_path, "4294967295").unwrap();
3393
    age(&lock_path);
3394
    assert!(repo.lock_snapshot().is_ok(), "stale lock taken over");
3395
}
3396
3397
#[test]
3398
fn attributes_binary_eol_nocompress_lockable() {
3399
    hermetic();
3400
    let dir = tempfile::tempdir().unwrap();
3401
    let root = dir.path();
3402
    let repo = Repo::init(root).unwrap().with_home(root.join("home"));
3403
    write(
3404
        root,
3405
        ".oxyattributes",
3406
        b"*.dat binary nocompress\n*.txt eol=crlf\nassets/** lockable\n",
3407
    );
3408
    write(root, "plain.dat", b"no nul bytes here\n");
3409
    write(root, "notes.txt", b"one\r\ntwo\r\n");
3410
    write(root, "assets/model.bin", b"\0model");
3411
    let h = repo.commit("attrs", &[]).unwrap();
3412
    let snap = repo.load_state(&[h]).unwrap().materialize();
3413
    assert!(
3414
        snap.files["plain.dat"].mode.opaque,
3415
        "binary attribute forces opaque without NUL bytes"
3416
    );
3417
    assert!(
3418
        matches!(&snap.files["notes.txt"].content, FileContent::Text { bytes, .. } if bytes == b"one\ntwo\n"),
3419
        "stored with LF"
3420
    );
3421
    assert!(
3422
        !repo.snapshot("status").unwrap().changed,
3423
        "CRLF on disk equals LF in the state"
3424
    );
3425
    // nocompress chunks pack raw.
3426
    let r = repo.gc(true).unwrap();
3427
    assert!(r.packed.objects > 0);
3428
    // Checkout writes CRLF for eol=crlf and makes lockable files read-only.
3429
    fs::remove_file(root.join("notes.txt")).unwrap();
3430
    repo.checkout(&[h], true, "co").unwrap();
3431
    assert_eq!(fs::read(root.join("notes.txt")).unwrap(), b"one\r\ntwo\r\n");
3432
    assert!(fs::metadata(root.join("assets/model.bin"))
3433
        .unwrap()
3434
        .permissions()
3435
        .readonly());
3436
    assert!(repo.lock_path("plain.dat").is_err(), "not lockable");
3437
    repo.lock_path("assets/model.bin").unwrap();
3438
    assert!(!fs::metadata(root.join("assets/model.bin"))
3439
        .unwrap()
3440
        .permissions()
3441
        .readonly());
3442
    assert!(repo.is_locked("assets/model.bin"));
3443
    write(root, "assets/model.bin", b"\0model2");
3444
    repo.commit("edit model", &[]).unwrap();
3445
    repo.unlock_path("assets/model.bin").unwrap();
3446
    assert!(fs::metadata(root.join("assets/model.bin"))
3447
        .unwrap()
3448
        .permissions()
3449
        .readonly());
3450
    // A later checkout can still overwrite a read-only lockable file.
3451
    repo.checkout(&[h], true, "co").unwrap();
3452
    assert_eq!(fs::read(root.join("assets/model.bin")).unwrap(), b"\0model");
3453
}
3454
3455
#[cfg(unix)]
3456
#[test]
3457
fn hooks_can_veto_observe_and_add_dependencies() {
3458
    use std::os::unix::fs::PermissionsExt;
3459
    hermetic();
3460
    let dir = tempfile::tempdir().unwrap();
3461
    let root = dir.path();
3462
    let mut repo = Repo::init(root).unwrap().with_home(root.join("home"));
3463
    let hooks = root.join(".oxy/hooks");
3464
    fs::create_dir_all(&hooks).unwrap();
3465
    let hook = |name: &str, body: &str| {
3466
        let p = hooks.join(name);
3467
        fs::write(&p, format!("#!/bin/sh\n{body}\n")).unwrap();
3468
        fs::set_permissions(&p, fs::Permissions::from_mode(0o755)).unwrap();
3469
    };
3470
    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");
3471
    hook("post-commit", "cat > \"$OXY_ROOT/.last-post-commit\"");
3472
    hook("post-checkout", "cat > \"$OXY_ROOT/.last-post-checkout\"");
3473
    hook("pre-push", "echo pushing blocked >&2; exit 3");
3474
    write(root, ".oxyignore", b".last-*\n");
3475
    write(root, "a.txt", b"a\n");
3476
    let err = repo.commit("WIP: nope", &[]).unwrap_err().to_string();
3477
    assert!(err.contains("pre-commit refused: no WIP commits"), "{err}");
3478
    let h1 = repo.commit("first", &[]).unwrap();
3479
    let pre = fs::read_to_string(root.join(".last-pre-commit")).unwrap();
3480
    assert!(
3481
        pre.contains("\"event\":\"pre-commit\"")
3482
            && pre.contains("\"path\":\"a.txt\"")
3483
            && pre.contains("\"message\":\"first\""),
3484
        "{pre}"
3485
    );
3486
    let post = fs::read_to_string(root.join(".last-post-commit")).unwrap();
3487
    assert!(post.contains(&h1.to_hex()), "{post}");
3488
    repo.checkout(&[h1], false, "co").unwrap();
3489
    assert!(fs::read_to_string(root.join(".last-post-checkout"))
3490
        .unwrap()
3491
        .contains("post-checkout"));
3492
    repo.config.set("remote.origin.url", "/nowhere").unwrap();
3493
    repo.save_config().unwrap();
3494
    let err = repo.push("origin", false).unwrap_err().to_string();
3495
    assert!(err.contains("pre-push refused: pushing blocked"), "{err}");
3496
3497
    // semantic-deps: only when enabled; adds an explicit dependency.
3498
    write(root, "b.txt", b"b\n");
3499
    hook(
3500
        "semantic-deps",
3501
        &format!(
3502
            "cat > \"$OXY_ROOT/.last-semantic\"; echo '{{\"deps\": [\"{}\"]}}'",
3503
            h1.to_hex()
3504
        ),
3505
    );
3506
    let h2 = repo.commit("b without hook", &[]).unwrap();
3507
    assert!(
3508
        repo.store().get_change(&h2).unwrap().deps.is_empty(),
3509
        "hook disabled by default"
3510
    );
3511
    repo.config.set("hooks.semantic-deps", "true").unwrap();
3512
    repo.save_config().unwrap();
3513
    write(root, "c.txt", b"c\n");
3514
    let h3 = repo.commit("c with hook", &[]).unwrap();
3515
    assert_eq!(repo.store().get_change(&h3).unwrap().deps, vec![h1]);
3516
    let sem = fs::read_to_string(root.join(".last-semantic")).unwrap();
3517
    assert!(
3518
        sem.contains("\"touched_paths\":[\"c.txt\"]") && sem.contains("candidate_deps"),
3519
        "{sem}"
3520
    );
3521
    assert_eq!(json_str("a\"b\\c\n"), "\"a\\\"b\\\\c\\n\"");
3522
}
3523
3524
#[test]
3525
fn amend_into_older_change_and_split() {
3526
    hermetic();
3527
    let dir = tempfile::tempdir().unwrap();
3528
    let root = dir.path();
3529
    let mut repo = Repo::init(root).unwrap().with_home(root.join("home"));
3530
    repo.create_identity("Ada", "a@b", IdentityScope::User)
3531
        .unwrap();
3532
    repo.set_user_config("core.sign", "change").unwrap();
3533
    write(root, "a.txt", b"one\ntwo\n");
3534
    let h0 = repo.commit("base", &[]).unwrap();
3535
    write(root, "a.txt", b"one\nTWO\n");
3536
    let h1 = repo.commit("edit two", &[]).unwrap();
3537
    write(root, "a.txt", b"one\nTWO\nthree\n");
3538
    let h2 = repo.commit("add three", &[]).unwrap();
3539
    let id1 = repo.store().get_change(&h1).unwrap().change_id;
3540
3541
    // Fixing the line h1 introduced folds into h1; h2 is rewritten on top.
3542
    write(root, "a.txt", b"one\nTWO!\nthree\n");
3543
    let h1b = repo.amend_into(&h1, None).unwrap();
3544
    assert_ne!(h1b, h1);
3545
    let c1b = repo.store().get_change(&h1b).unwrap();
3546
    assert_eq!(c1b.change_id, id1);
3547
    assert_eq!(c1b.deps, vec![h0]);
3548
    assert!(matches!(
3549
        repo.verify_change(&h1b).unwrap(),
3550
        SignatureStatus::Valid { .. }
3551
    ));
3552
    let heads = repo.bookmark_heads().unwrap();
3553
    assert_eq!(heads.len(), 1);
3554
    let top = repo.store().get_change(&heads[0]).unwrap();
3555
    assert_eq!(top.message, "add three");
3556
    assert_eq!(
3557
        top.deps.iter().copied().collect::<BTreeSet<_>>(),
3558
        [h0, h1b].into_iter().collect(),
3559
        "depends on the file's creator and the rewritten line"
3560
    );
3561
    let snap = repo.load_state(&heads).unwrap().materialize();
3562
    assert!(
3563
        matches!(&snap.files["a.txt"].content, FileContent::Text { bytes, .. } if bytes == b"one\nTWO!\nthree\n")
3564
    );
3565
    assert!(
3566
        !repo.snapshot("status").unwrap().changed,
3567
        "the working copy is clean after folding"
3568
    );
3569
    // Only h1b's own state shows the fix without "three".
3570
    let only = repo.load_state(&[h1b]).unwrap().materialize();
3571
    assert!(
3572
        matches!(&only.files["a.txt"].content, FileContent::Text { bytes, .. } if bytes == b"one\nTWO!\n")
3573
    );
3574
    assert_eq!(repo.log().unwrap().len(), 4);
3575
3576
    // An edit to a line introduced by h2 cannot fold into h1.
3577
    write(root, "a.txt", b"one\nTWO!\nthree!\n");
3578
    let err = repo.amend_into(&h1b, None).unwrap_err().to_string();
3579
    assert!(err.contains("introduced after"), "{err}");
3580
    assert!(
3581
        repo.snapshot("status").unwrap().statuses.len() == 1,
3582
        "nothing was changed by the refusal"
3583
    );
3584
    write(root, "a.txt", b"one\nTWO!\nthree\n");
3585
3586
    // Split the head that touches two files.
3587
    write(root, "b.txt", b"b\n");
3588
    write(root, "c.txt", b"c\n");
3589
    let h3 = repo.commit("b and c", &[]).unwrap();
3590
    let id3 = repo.store().get_change(&h3).unwrap().change_id;
3591
    let (p1, p2) = repo.split(&h3, &["b.txt".into()]).unwrap();
3592
    let c_1 = repo.store().get_change(&p1).unwrap();
3593
    let c_2 = repo.store().get_change(&p2).unwrap();
3594
    assert!(c_1.message.contains("part 1: b.txt"));
3595
    assert_eq!(c_2.change_id, id3);
3596
    let heads: BTreeSet<_> = repo.bookmark_heads().unwrap().into_iter().collect();
3597
    assert!(
3598
        heads.contains(&p1) && heads.contains(&p2),
3599
        "independent parts are both heads"
3600
    );
3601
    let snap = repo
3602
        .load_state(&repo.bookmark_heads().unwrap())
3603
        .unwrap()
3604
        .materialize();
3605
    assert!(snap.files.contains_key("b.txt") && snap.files.contains_key("c.txt"));
3606
    let only1 = repo.load_state(&[p1]).unwrap().materialize();
3607
    assert!(only1.files.contains_key("b.txt") && !only1.files.contains_key("c.txt"));
3608
    assert!(!repo.snapshot("status").unwrap().changed);
3609
    assert!(repo.split(&p2, &["nope.txt".into()]).is_err());
3610
    let _ = h2;
3611
}
3612
3613
#[test]
3614
fn identity_lifecycle() {
3615
    hermetic();
3616
    let dir = tempfile::tempdir().unwrap();
3617
    let root = dir.path();
3618
    let origin = Repo::init(&root.join("origin")).unwrap();
3619
    let url = root.join("origin").to_string_lossy().to_string();
3620
    let mut a = Repo::clone(&url, &root.join("a"))
3621
        .unwrap()
3622
        .with_home(root.join("home-a"));
3623
    a.set_user_config("core.sign", "change").unwrap();
3624
    let (key_a, _) = a
3625
        .create_identity("Ada", "[email protected]", IdentityScope::User)
3626
        .unwrap();
3627
    write(&root.join("a"), "a.txt", b"a\n");
3628
    let h1 = a.commit("one", &[]).unwrap();
3629
    assert!(a.policy_init().unwrap().applied);
3630
    assert!(a.push("origin", false).unwrap().iter().all(|r| r.ok));
3631
    origin.refresh().unwrap();
3632
3633
    // Expiry: an identity that had expired when the change was made does not authenticate it.
3634
    let mut e = Repo::init(&root.join("e"))
3635
        .unwrap()
3636
        .with_home(root.join("home-e"));
3637
    e.set_user_config("core.sign", "change").unwrap();
3638
    e.create_identity_with(
3639
        "Eve",
3640
        "[email protected]",
3641
        IdentityScope::User,
3642
        Some(Hlc::now().wall_ms - 1),
3643
    )
3644
    .unwrap();
3645
    write(&root.join("e"), "e.txt", b"e\n");
3646
    let he = e.commit("late", &[]).unwrap();
3647
    assert!(
3648
        matches!(e.verify_change(&he).unwrap(), SignatureStatus::Invalid(m) if m.contains("expired"))
3649
    );
3650
    // Renewal re-issues the identity (same keys, new KeyId) with a later expiry.
3651
    let r = e
3652
        .renew_identity(Some(Hlc::now().wall_ms + 86_400_000))
3653
        .unwrap();
3654
    assert_eq!(e.identity(&r.new).unwrap().previous, Some(r.old));
3655
    write(&root.join("e"), "e.txt", b"e2\n");
3656
    let he2 = e.commit("in time", &[]).unwrap();
3657
    assert!(
3658
        matches!(e.verify_change(&he2).unwrap(), SignatureStatus::Valid { key, .. } if key == r.new)
3659
    );
3660
3661
    // Rotation: a fresh key; the old change still verifies; the policy follows.
3662
    let r = a.rotate_identity().unwrap();
3663
    assert_eq!(r.old, key_a);
3664
    assert_eq!(a.config.author_key, Some(r.new));
3665
    assert_eq!(a.identity(&r.new).unwrap().previous, Some(key_a));
3666
    assert!(r.policy.as_ref().unwrap().applied);
3667
    let (_, sp) = a.current_policy().unwrap().unwrap();
3668
    assert_eq!(
3669
        (sp.policy.serial, sp.policy.roots.clone()),
3670
        (2, vec![r.new])
3671
    );
3672
    assert!(
3673
        !sp.policy.revoked.contains(&key_a) && sp.policy.authorizes(&r.new, "main"),
3674
        "superseded, not revoked"
3675
    );
3676
    assert!(sp.policy.succeeds(&r.new, &key_a) && !sp.policy.succeeds(&key_a, &r.new));
3677
    assert!(
3678
        matches!(a.verify_change(&h1).unwrap(), SignatureStatus::Valid { key, revoked: false, .. } if key == key_a)
3679
    );
3680
    write(&root.join("a"), "a.txt", b"a2\n");
3681
    let h2 = a.commit("two", &[]).unwrap();
3682
    assert!(
3683
        matches!(a.verify_change(&h2).unwrap(), SignatureStatus::Valid { key, revoked: false, .. } if key == r.new)
3684
    );
3685
    // Origin accepts the rotated policy (signed by the old root) and the new key's change.
3686
    let res = a.push("origin", false).unwrap();
3687
    origin.refresh().unwrap();
3688
    assert!(res.iter().all(|x| x.ok), "{res:?}");
3689
    assert_eq!(origin.current_policy().unwrap().unwrap().1.policy.serial, 2);
3690
    let key_a = r.new;
3691
3692
    // Delegation: Bob may sign on Ada's behalf. Delegates live in the
3693
    // identity object, so Ada's KeyId changes while her keys stay the same.
3694
    let mut b = Repo::clone(&url, &root.join("b"))
3695
        .unwrap()
3696
        .with_home(root.join("home-b"));
3697
    let (key_b, id_b) = b
3698
        .create_identity("Bob", "[email protected]", IdentityScope::User)
3699
        .unwrap();
3700
    let r = a.delegate_add(id_b.clone(), Scope::ALL, None).unwrap();
3701
    assert_eq!(r.old, key_a);
3702
    let key_a2 = r.new;
3703
    assert_eq!(
3704
        a.identity(&key_a2).unwrap().delegates,
3705
        vec![Delegate::full(key_b)]
3706
    );
3707
    assert_eq!(
3708
        a.identity(&key_a2).unwrap().ed25519_pk,
3709
        a.identity(&key_a).unwrap().ed25519_pk
3710
    );
3711
    assert!(
3712
        a.delegate_add(id_b.clone(), Scope::ALL, None).is_err(),
3713
        "already a delegate"
3714
    );
3715
    assert!(a.push("origin", false).unwrap().iter().all(|x| x.ok));
3716
    origin.refresh().unwrap();
3717
    write(&root.join("a"), "a.txt", b"a3\n");
3718
    let h3 = a.commit("three", &[]).unwrap();
3719
    assert!(
3720
        matches!(a.verify_change(&h3).unwrap(), SignatureStatus::Valid { key, .. } if key == key_a2),
3721
        "the same secret signs under the new KeyId"
3722
    );
3723
    // A change authored by Ada but signed only by Bob verifies through the delegation.
3724
    a.set_user_config("core.sign", "seal").unwrap();
3725
    write(&root.join("a"), "a.txt", b"a4\n");
3726
    let h4 = a.commit("four", &[]).unwrap();
3727
    assert_eq!(a.verify_change(&h4).unwrap(), SignatureStatus::Unsigned);
3728
    let (_, sk_b) = b.secret_key().unwrap().unwrap();
3729
    a.store()
3730
        .put_signature(&h4, &sk_b.sign(Domain::Change, &key_b, &h4))
3731
        .unwrap();
3732
    assert!(
3733
        matches!(a.verify_change(&h4).unwrap(), SignatureStatus::Valid { key, .. } if key == key_b)
3734
    );
3735
    a.set_user_config("core.sign", "change").unwrap();
3736
    // Withdrawing the delegation re-issues the identity again.
3737
    let r = a.delegate_remove(&key_b).unwrap();
3738
    assert!(a.identity(&r.new).unwrap().delegates.is_empty());
3739
    assert!(a.delegate_remove(&key_b).is_err());
3740
    let key_a3 = r.new;
3741
    let res = a.push("origin", false).unwrap();
3742
    origin.refresh().unwrap();
3743
    assert!(res.iter().all(|x| x.ok), "{res:?}");
3744
3745
    // Multi-signer policy: Bob becomes a root and the threshold rises to 2,
3746
    // both applied under the old threshold of 1. A grant then needs Bob too.
3747
    assert!(a.policy_root_add(id_b.clone()).unwrap().applied);
3748
    assert!(a.policy_root_add(id_b.clone()).is_err());
3749
    assert!(a.policy_set_threshold(3).is_err());
3750
    assert!(a.policy_set_threshold(2).unwrap().applied);
3751
    assert!(a.push("origin", false).unwrap().iter().all(|x| x.ok));
3752
    origin.refresh().unwrap();
3753
    b.pull("origin").unwrap();
3754
    assert_eq!(
3755
        b.current_policy().unwrap().unwrap().1.policy.root_threshold,
3756
        2
3757
    );
3758
    let mut c = Repo::init(&root.join("c"))
3759
        .unwrap()
3760
        .with_home(root.join("home-c"));
3761
    let (key_c, id_c) = c
3762
        .create_identity("Cy", "[email protected]", IdentityScope::User)
3763
        .unwrap();
3764
    let serial_before = a.current_policy().unwrap().unwrap().1.policy.serial;
3765
    let proposal = a.policy_grant(id_c, None).unwrap();
3766
    assert!(!proposal.applied && proposal.sigs.len() == 1);
3767
    assert_eq!(proposal.policy.serial, serial_before + 1);
3768
    assert_eq!(
3769
        a.current_policy().unwrap().unwrap().1.policy.serial,
3770
        serial_before,
3771
        "a proposal changes nothing yet"
3772
    );
3773
    // Bob signs the proposal, handed over as a file, and it applies for him.
3774
    let bytes = proposal.signed().encode();
3775
    let signed = b
3776
        .policy_sign(SignedPolicy::decode(&bytes).unwrap())
3777
        .unwrap();
3778
    assert!(signed.applied && signed.sigs.len() == 2);
3779
    assert!(b
3780
        .current_policy()
3781
        .unwrap()
3782
        .unwrap()
3783
        .1
3784
        .policy
3785
        .authorizes(&key_c, "main"));
3786
    assert!(
3787
        b.policy_sign(signed.signed()).is_err(),
3788
        "a stale proposal is refused"
3789
    );
3790
    // Bob publishes it and Ada picks it up.
3791
    assert!(b
3792
        .push("origin", false)
3793
        .unwrap()
3794
        .iter()
3795
        .any(|x| x.name == "policy" && x.ok));
3796
    origin.refresh().unwrap();
3797
    a.pull("origin").unwrap();
3798
    assert_eq!(
3799
        a.current_policy().unwrap().unwrap().1.policy.serial,
3800
        serial_before + 1
3801
    );
3802
    // A root cannot revoke itself; revoking Cy needs both roots but is recorded locally at once.
3803
    assert!(a.policy_revoke(&key_a3).is_err());
3804
    let u = a
3805
        .revoke_identity(&key_c, "left the project")
3806
        .unwrap()
3807
        .unwrap();
3808
    assert!(!u.applied);
3809
    assert!(a.is_revoked(&key_c).unwrap());
3810
    assert!(!b.is_revoked(&key_c).unwrap());
3811
    let u = b.policy_sign(u.signed()).unwrap();
3812
    assert!(u.applied && u.policy.is_revoked(&key_c));
3813
    assert!(b.is_revoked(&key_c).unwrap());
3814
    // Bob can revoke Ada's root key, leaving himself as the only root (threshold 2 would be unmeetable).
3815
    assert!(
3816
        b.policy_revoke(&key_a3).is_err(),
3817
        "would leave one root for a threshold of 2"
3818
    );
3819
    // Revoking one's own key without a policy root works locally: a plain marker plus attestation.
3820
    let key_c_own = c.config.author_key.unwrap();
3821
    assert!(c
3822
        .revoke_identity(&key_c_own, "lost laptop")
3823
        .unwrap()
3824
        .is_none());
3825
    assert!(c.is_revoked(&key_c_own).unwrap());
3826
    assert_eq!(key_c_own, key_c);
3827
}
3828
3829
#[test]
3830
fn renames_are_detected_and_tracked_as_moves() {
3831
    hermetic();
3832
    let dir = tempfile::tempdir().unwrap();
3833
    let root = dir.path();
3834
    let repo = Repo::init(root).unwrap().with_home(root.join("home"));
3835
    write(
3836
        root,
3837
        "src/old.rs",
3838
        b"fn a() {}\nfn b() {}\nfn c() {}\nfn d() {}\n",
3839
    );
3840
    write(root, "img.bin", b"\x89PNG\0\0\x01\x02");
3841
    write(root, "tiny.txt", b"x\n");
3842
    let h1 = repo.commit("base", &[]).unwrap();
3843
    let node_old = repo.load_state(&[h1]).unwrap().materialize().files["src/old.rs"].node;
3844
    let node_img = repo.load_state(&[h1]).unwrap().materialize().files["img.bin"].node;
3845
3846
    // Rename with a small edit, a binary moved unchanged, and a rewrite
3847
    // that shares nothing with the removed file.
3848
    fs::remove_file(root.join("src/old.rs")).unwrap();
3849
    write(
3850
        root,
3851
        "lib/new.rs",
3852
        b"fn a() {}\nfn b() {}\nfn c() {}\nfn e() {}\n",
3853
    );
3854
    fs::remove_file(root.join("img.bin")).unwrap();
3855
    write(root, "assets/img.bin", b"\x89PNG\0\0\x01\x02");
3856
    fs::remove_file(root.join("tiny.txt")).unwrap();
3857
    write(root, "other.txt", b"completely different\n");
3858
    let snap = repo.snapshot("status").unwrap();
3859
    let statuses: Vec<(&str, ChangeStatus)> = snap
3860
        .statuses
3861
        .iter()
3862
        .map(|s| (s.path.as_str(), s.status))
3863
        .collect();
3864
    assert_eq!(
3865
        statuses,
3866
        vec![
3867
            ("assets/img.bin", ChangeStatus::Renamed),
3868
            ("lib/new.rs", ChangeStatus::Renamed),
3869
            ("other.txt", ChangeStatus::Added),
3870
            ("src", ChangeStatus::Removed),
3871
            ("tiny.txt", ChangeStatus::Removed)
3872
        ]
3873
    );
3874
    let h2 = repo.commit("move things", &[]).unwrap();
3875
    let c = repo.store().get_change(&h2).unwrap();
3876
    let moves: Vec<_> = c
3877
        .tree_ops
3878
        .iter()
3879
        .filter(|op| matches!(op, TreeOp::Move { .. }))
3880
        .collect();
3881
    assert_eq!(moves.len(), 2, "{:?}", c.tree_ops);
3882
    assert!(c.tree_ops.iter().any(
3883
        |op| matches!(op, TreeOp::Move { node, name, .. } if *node == node_old && name == "new.rs")
3884
    ));
3885
    assert!(c.tree_ops.iter().any(
3886
        |op| matches!(op, TreeOp::Move { node, name, .. } if *node == node_img && name == "img.bin")
3887
    ));
3888
    let snap = repo.load_state(&[h2]).unwrap().materialize();
3889
    assert_eq!(
3890
        snap.files["lib/new.rs"].node, node_old,
3891
        "the node survives the rename"
3892
    );
3893
    assert!(
3894
        matches!(&snap.files["lib/new.rs"].content, FileContent::Text { bytes, .. } if bytes == b"fn a() {}\nfn b() {}\nfn c() {}\nfn e() {}\n")
3895
    );
3896
    assert!(!snap.files.contains_key("src/old.rs") && !snap.files.contains_key("src"));
3897
    assert!(render_change(
3898
        &c,
3899
        &repo.load_state(&[h1]).unwrap(),
3900
        &repo.load_state(&[h1]).unwrap().materialize()
3901
    )
3902
    .contains("R "));
3903
    // A fresh checkout reproduces the tree.
3904
    let other = tempfile::tempdir().unwrap();
3905
    let clone = Repo::clone(&root.to_string_lossy(), other.path()).unwrap();
3906
    assert_eq!(
3907
        fs::read(other.path().join("lib/new.rs")).unwrap(),
3908
        b"fn a() {}\nfn b() {}\nfn c() {}\nfn e() {}\n"
3909
    );
3910
    assert!(!other.path().join("src").exists());
3911
    assert!(!clone.snapshot("status").unwrap().changed);
3912
    // Similarity is line based, byte weighted.
3913
    assert_eq!(similarity(b"a\nb\n", b"a\nb\n"), 100);
3914
    assert_eq!(similarity(b"a\nb\nc\nd\n", b"a\nb\nx\ny\n"), 50);
3915
    assert_eq!(similarity(b"hello\n", b"world\n"), 0);
3916
    assert_eq!(similarity(b"", b"x\n"), 0);
3917
}
3918
3919
#[test]
3920
fn git_fetch_and_push_round_trip() {
3921
    hermetic();
3922
    if std::process::Command::new("git")
3923
        .arg("--version")
3924
        .output()
3925
        .is_err()
3926
    {
3927
        eprintln!("git not installed; skipping");
3928
        return;
3929
    }
3930
    let dir = tempfile::tempdir().unwrap();
3931
    let root = dir.path();
3932
    let git_in = |d: &Path, args: &[&str]| -> String {
3933
        let out = std::process::Command::new("git")
3934
            .arg("-C")
3935
            .arg(d)
3936
            .args([
3937
                "-c",
3938
                "user.name=Grace",
3939
                "-c",
3940
                "[email protected]",
3941
                "-c",
3942
                "commit.gpgsign=false",
3943
            ])
3944
            .args(args)
3945
            .output()
3946
            .unwrap();
3947
        assert!(
3948
            out.status.success(),
3949
            "git {args:?}: {}",
3950
            String::from_utf8_lossy(&out.stderr)
3951
        );
3952
        String::from_utf8_lossy(&out.stdout).trim().to_string()
3953
    };
3954
    // A bare "remote" and a work tree that pushes to it.
3955
    let remote = root.join("remote.git");
3956
    fs::create_dir_all(&remote).unwrap();
3957
    git_in(&remote, &["init", "-q", "--bare", "-b", "main"]);
3958
    let work = root.join("work");
3959
    git_in(
3960
        root,
3961
        &[
3962
            "clone",
3963
            "-q",
3964
            remote.to_str().unwrap(),
3965
            work.to_str().unwrap(),
3966
        ],
3967
    );
3968
    git_in(&work, &["checkout", "-q", "-b", "main"]);
3969
    write(&work, "README.md", b"# Project\n");
3970
    write(&work, "src/lib.rs", b"pub fn a() {}\n");
3971
    git_in(&work, &["add", "."]);
3972
    git_in(&work, &["commit", "-q", "-m", "initial"]);
3973
    write(&work, "src/lib.rs", b"pub fn a() {}\npub fn b() {}\n");
3974
    git_in(&work, &["commit", "-q", "-am", "second"]);
3975
    git_in(&work, &["push", "-q", "origin", "main"]);
3976
    let tip1 = git_in(&work, &["rev-parse", "HEAD"]);
3977
3978
    // Fetch into a fresh oxy repository.
3979
    let o = root.join("oxy");
3980
    let mut repo = Repo::init(&o).unwrap().with_home(root.join("home"));
3981
    repo.create_identity("Ada", "[email protected]", IdentityScope::User)
3982
        .unwrap();
3983
    let url = remote.to_string_lossy().to_string();
3984
    let r = repo.git_fetch(&url, "main").unwrap();
3985
    assert_eq!((r.commits, r.heads), (2, 1));
3986
    assert_eq!(
3987
        fs::read(o.join("src/lib.rs")).unwrap(),
3988
        b"pub fn a() {}\npub fn b() {}\n"
3989
    );
3990
    assert!(!repo.snapshot("status").unwrap().changed);
3991
    assert_eq!(
3992
        repo.git_fetch(&url, "main").unwrap().commits,
3993
        0,
3994
        "nothing new"
3995
    );
3996
3997
    // An oxy change, pushed back: one commit on top of the Git tip.
3998
    write(
3999
        &o,
4000
        "src/lib.rs",
4001
        b"pub fn a() {}\npub fn b() {}\npub fn c() {}\n",
4002
    );
4003
    write(&o, "NOTES.md", b"from oxy\n");
4004
    let h_oxy = repo.commit("add c and notes", &[]).unwrap();
4005
    let r = repo.git_push(&url, "main").unwrap();
4006
    assert_eq!(r.exported, 1, "{r:?}");
4007
    git_in(&work, &["pull", "-q", "--ff-only", "origin", "main"]);
4008
    assert_eq!(
4009
        git_in(&work, &["log", "--format=%s", "main"]),
4010
        "add c and notes\nsecond\ninitial"
4011
    );
4012
    assert_eq!(git_in(&work, &["rev-parse", "HEAD~1"]), tip1);
4013
    assert_eq!(fs::read(work.join("NOTES.md")).unwrap(), b"from oxy\n");
4014
    assert_eq!(git_in(&work, &["log", "-1", "--format=%an", "main"]), "Ada");
4015
    assert!(git_in(&work, &["log", "-1", "--format=%B", "main"])
4016
        .contains(&format!("Oxy-Hash: {}", h_oxy.to_hex())));
4017
    assert_eq!(
4018
        repo.git_push(&url, "main").unwrap().exported,
4019
        0,
4020
        "already pushed"
4021
    );
4022
4023
    // Git moves on; pushing without fetching is refused, fetching brings
4024
    // the commit in and the working copy follows.
4025
    write(&work, "README.md", b"# Project\n\nMore.\n");
4026
    git_in(&work, &["commit", "-q", "-am", "readme from git"]);
4027
    git_in(&work, &["push", "-q", "origin", "main"]);
4028
    let tip2 = git_in(&work, &["rev-parse", "HEAD"]);
4029
    assert!(repo
4030
        .git_push(&url, "main")
4031
        .unwrap_err()
4032
        .to_string()
4033
        .contains("fetch"));
4034
    let r = repo.git_fetch(&url, "main").unwrap();
4035
    assert_eq!(
4036
        (r.commits, r.heads),
4037
        (1, 2),
4038
        "the Git change and the oxy change commute"
4039
    );
4040
    assert_eq!(
4041
        fs::read(o.join("README.md")).unwrap(),
4042
        b"# Project\n\nMore.\n"
4043
    );
4044
    assert_eq!(fs::read(o.join("NOTES.md")).unwrap(), b"from oxy\n");
4045
    assert!(!repo.snapshot("status").unwrap().changed);
4046
    // Another oxy change pushes on top of Git's newest commit.
4047
    write(&o, "NOTES.md", b"from oxy\nagain\n");
4048
    repo.commit("notes again", &[]).unwrap();
4049
    assert_eq!(repo.git_push(&url, "main").unwrap().exported, 1);
4050
    git_in(&work, &["pull", "-q", "--ff-only", "origin", "main"]);
4051
    assert_eq!(git_in(&work, &["rev-parse", "HEAD~1"]), tip2);
4052
    assert_eq!(
4053
        fs::read(work.join("NOTES.md")).unwrap(),
4054
        b"from oxy\nagain\n"
4055
    );
4056
    assert_eq!(
4057
        git_in(&work, &["log", "--format=%s", "main"])
4058
            .lines()
4059
            .count(),
4060
        5
4061
    );
4062
}
4063
4064
/// Benchmark, not a gate: `cargo test --release -p oxy-core --lib bench_one_gibibyte -- --ignored --nocapture`.
4065
/// Commits, stores, clones, and reads back a 1 GiB incompressible file.
4066
#[test]
4067
#[ignore]
4068
fn bench_one_gibibyte_file() {
4069
    hermetic();
4070
    // /tmp is often a small tmpfs; `OXY_BENCH_DIR` picks a roomier disk.
4071
    let dir = match std::env::var_os("OXY_BENCH_DIR") {
4072
        Some(d) => tempfile::tempdir_in(d).unwrap(),
4073
        None => tempfile::tempdir().unwrap(),
4074
    };
4075
    let root = dir.path();
4076
    let repo = Repo::init(&root.join("r"))
4077
        .unwrap()
4078
        .with_home(root.join("home"));
4079
    let size = 1usize << 30;
4080
    let mut data = vec![0u8; size];
4081
    let mut x = 0x9e3779b97f4a7c15u64;
4082
    for chunk in data.chunks_mut(8) {
4083
        x ^= x << 13;
4084
        x ^= x >> 7;
4085
        x ^= x << 17;
4086
        let b = x.to_le_bytes();
4087
        chunk.copy_from_slice(&b[..chunk.len()]);
4088
    }
4089
    let t = std::time::Instant::now();
4090
    write(&root.join("r"), "big.bin", &data);
4091
    eprintln!("write 1 GiB to disk: {:.2?}", t.elapsed());
4092
    let t = std::time::Instant::now();
4093
    let h = repo.commit("big", &[]).unwrap();
4094
    eprintln!("commit (chunk + hash + store): {:.2?}", t.elapsed());
4095
    let t = std::time::Instant::now();
4096
    assert!(!repo.snapshot("status").unwrap().changed);
4097
    eprintln!("status on a clean 1 GiB working copy: {:.2?}", t.elapsed());
4098
    let t = std::time::Instant::now();
4099
    let objects = repo.store().list().unwrap().len();
4100
    eprintln!("objects stored: {objects} ({:.2?} to list)", t.elapsed());
4101
    let t = std::time::Instant::now();
4102
    let g = repo.gc(true).unwrap();
4103
    eprintln!("gc (pack): {:.2?} {g:?}", t.elapsed());
4104
    let t = std::time::Instant::now();
4105
    let clone = Repo::clone(&root.join("r").to_string_lossy(), &root.join("c")).unwrap();
4106
    eprintln!("clone (fetch + checkout): {:.2?}", t.elapsed());
4107
    let t = std::time::Instant::now();
4108
    let back = fs::read(root.join("c/big.bin")).unwrap();
4109
    assert_eq!(blake3::hash(&back), blake3::hash(&data));
4110
    eprintln!("read back and verify: {:.2?}", t.elapsed());
4111
    assert_eq!(clone.bookmark_heads().unwrap(), vec![h]);
4112
    let store_bytes: u64 = walkdir_size(&root.join("r/.oxy/objects"));
4113
    eprintln!(
4114
        "store size: {:.1} MiB for 1 GiB of data",
4115
        store_bytes as f64 / (1024.0 * 1024.0)
4116
    );
4117
}
4118
4119
fn walkdir_size(p: &Path) -> u64 {
4120
    let mut total = 0;
4121
    if let Ok(rd) = fs::read_dir(p) {
4122
        for e in rd.flatten() {
4123
            let path = e.path();
4124
            if path.is_dir() {
4125
                total += walkdir_size(&path);
4126
            } else if let Ok(m) = fs::metadata(&path) {
4127
                total += m.len();
4128
            }
4129
        }
4130
    }
4131
    total
4132
}
4133
4134
/// An opaque file whose size and mtime match the manifest is not read on
4135
/// the next snapshot: its blob comes from the manifest's stat cache.
4136
#[cfg(unix)]
4137
#[test]
4138
fn stat_cache_skips_reading_unchanged_opaque_files() {
4139
    use std::os::unix::fs::PermissionsExt;
4140
    hermetic();
4141
    let dir = tempfile::tempdir().unwrap();
4142
    let root = dir.path();
4143
    let repo = Repo::init(root).unwrap().with_home(root.join("home"));
4144
    let mut big = vec![0u8; 300 * 1024];
4145
    for (i, b) in big.iter_mut().enumerate() {
4146
        *b = (i as u32).wrapping_mul(2654435761).to_le_bytes()[1];
4147
    }
4148
    big[0] = 0;
4149
    write(root, "big.bin", &big);
4150
    write(root, "a.txt", b"text\n");
4151
    let h1 = repo.commit("base", &[]).unwrap();
4152
    let (_, _, m) = repo.read_manifest().unwrap().unwrap();
4153
    assert!(
4154
        m.entries["big.bin"].blob.is_some(),
4155
        "opaque files record their blob"
4156
    );
4157
    assert!(m.entries["a.txt"].blob.is_none());
4158
    let blob = m.entries["big.bin"].blob.unwrap();
4159
    assert!(repo.store().has(&blob));
4160
4161
    // Files modified within two seconds of the manifest are racy and still
4162
    // read; age the file so the cache applies, then snapshot to record it.
4163
    let old = std::time::SystemTime::now() - std::time::Duration::from_secs(30);
4164
    fs::File::options()
4165
        .write(true)
4166
        .open(root.join("big.bin"))
4167
        .unwrap()
4168
        .set_modified(old)
4169
        .unwrap();
4170
    assert!(!repo.snapshot("status").unwrap().changed);
4171
    // Now the file cannot be read at all; the snapshot succeeds without it.
4172
    fs::set_permissions(root.join("big.bin"), fs::Permissions::from_mode(0o000)).unwrap();
4173
    let snap = repo.snapshot("status").unwrap();
4174
    assert!(
4175
        !snap.changed && snap.statuses.is_empty(),
4176
        "{:?}",
4177
        snap.statuses
4178
    );
4179
    fs::set_permissions(root.join("big.bin"), fs::Permissions::from_mode(0o644)).unwrap();
4180
    // A real change (new mtime, new content) is seen and committed correctly.
4181
    let mut big2 = big.clone();
4182
    big2[10] ^= 0xff;
4183
    write(root, "big.bin", &big2);
4184
    let snap = repo.snapshot("status").unwrap();
4185
    assert_eq!(
4186
        snap.statuses
4187
            .iter()
4188
            .map(|s| (s.path.as_str(), s.status))
4189
            .collect::<Vec<_>>(),
4190
        vec![("big.bin", ChangeStatus::Modified)]
4191
    );
4192
    let h2 = repo.commit("edit", &[]).unwrap();
4193
    let files = repo.load_state(&[h2]).unwrap().materialize().files;
4194
    assert_eq!(
4195
        files["big.bin"].content,
4196
        FileContent::Opaque {
4197
            blobs: vec![Repo::blob_ref(&big2)]
4198
        }
4199
    );
4200
    // Checkout writes a manifest with blobs too, so the next status is cached.
4201
    repo.checkout(&[h1], false, "checkout").unwrap();
4202
    let (_, _, m) = repo.read_manifest().unwrap().unwrap();
4203
    assert_eq!(m.entries["big.bin"].blob, Some(Repo::blob_ref(&big)));
4204
    assert!(!repo.snapshot("status").unwrap().changed);
4205
}
4206
4207
#[test]
4208
fn status_json_lists_conflicts_with_contributors() {
4209
    hermetic();
4210
    let dir = tempfile::tempdir().unwrap();
4211
    let root = dir.path();
4212
    let repo = Repo::init(root).unwrap().with_home(root.join("home"));
4213
    write(root, "a.txt", b"one\n");
4214
    let h1 = repo.commit("base", &[]).unwrap();
4215
    write(root, "a.txt", b"one\nleft\n");
4216
    let ha = repo.commit("left", &[]).unwrap();
4217
    repo.checkout(&[h1], true, "checkout").unwrap();
4218
    write(root, "a.txt", b"one\nright\n");
4219
    let hb = repo.commit("right", &[]).unwrap();
4220
    repo.checkout(&[ha, hb], true, "checkout").unwrap();
4221
    let snap = repo.snapshot("status").unwrap();
4222
    assert!(snap.base_snapshot.is_conflicted());
4223
    let json = repo.status_json(&snap).unwrap();
4224
    let ida = repo.store().get_change(&ha).unwrap().change_id.to_hex();
4225
    let idb = repo.store().get_change(&hb).unwrap().change_id.to_hex();
4226
    assert!(json.contains("\"conflicted\":true"), "{json}");
4227
    assert!(
4228
        json.contains("\"kind\":\"text\",\"path\":\"a.txt\""),
4229
        "{json}"
4230
    );
4231
    assert!(json.contains(&ida) && json.contains(&idb), "{json}");
4232
    assert!(json.contains("\"resolved\":false"), "{json}");
4233
    assert!(json.starts_with('{') && json.ends_with('}'));
4234
    // Resolve and the report says so; a clean copy has no conflicts.
4235
    write(root, "a.txt", b"one\nleft\nright\n");
4236
    let snap = repo.snapshot("status").unwrap();
4237
    let json = repo.status_json(&snap).unwrap();
4238
    assert!(json.contains("\"resolved\":true"), "{json}");
4239
    repo.commit("resolve", &[]).unwrap();
4240
    let snap = repo.snapshot("status").unwrap();
4241
    let json = repo.status_json(&snap).unwrap();
4242
    assert!(
4243
        json.contains("\"clean\":true,\"conflicted\":false,\"paths\":[],\"conflicts\":[]"),
4244
        "{json}"
4245
    );
4246
}
4247
4248
#[test]
4249
fn ignore_rules_do_not_untrack_files() {
4250
    hermetic();
4251
    let dir = tempfile::tempdir().unwrap();
4252
    let root = dir.path();
4253
    let repo = Repo::init(root).unwrap().with_home(root.join("home"));
4254
    write(root, "src.c", b"int x;\n");
4255
    write(root, "build/out.o", b"\0obj");
4256
    write(root, "sub/keep.log", b"keep\n");
4257
    write(root, "sub/junk.log", b"junk\n");
4258
    write(root, ".oxyignore", b"/build\n*.log\n!sub/keep.log\n");
4259
    let snap = repo.snapshot("status").unwrap();
4260
    let added: Vec<&str> = snap.statuses.iter().map(|s| s.path.as_str()).collect();
4261
    assert_eq!(
4262
        added,
4263
        vec![".oxyignore", "src.c", "sub/keep.log"],
4264
        "anchored, glob, and negated rules"
4265
    );
4266
    let h1 = repo.commit("base", &[]).unwrap();
4267
    // Ignoring a tracked file changes nothing about it.
4268
    write(root, ".oxyignore", b"/build\n*.log\n!sub/keep.log\nsrc.c\n");
4269
    let snap = repo.snapshot("status").unwrap();
4270
    assert_eq!(
4271
        snap.statuses
4272
            .iter()
4273
            .map(|s| s.path.as_str())
4274
            .collect::<Vec<_>>(),
4275
        vec![".oxyignore"]
4276
    );
4277
    let h2 = repo.commit("ignore src.c", &[]).unwrap();
4278
    assert!(repo
4279
        .load_state(&[h2])
4280
        .unwrap()
4281
        .materialize()
4282
        .files
4283
        .contains_key("src.c"));
4284
    // Its edits are still seen, by status and by the prompt.
4285
    assert_eq!(repo.quick_dirty().unwrap(), Some(false));
4286
    write(root, "src.c", b"int x, y;\n");
4287
    assert_eq!(repo.quick_dirty().unwrap(), Some(true));
4288
    let snap = repo.snapshot("status").unwrap();
4289
    assert_eq!(
4290
        snap.statuses
4291
            .iter()
4292
            .map(|s| (s.path.as_str(), s.status))
4293
            .collect::<Vec<_>>(),
4294
        vec![("src.c", ChangeStatus::Modified)]
4295
    );
4296
    let h3 = repo.commit("edit src.c", &[]).unwrap();
4297
    assert!(
4298
        matches!(&repo.load_state(&[h3]).unwrap().materialize().files["src.c"].content, FileContent::Text { bytes, .. } if bytes == b"int x, y;\n")
4299
    );
4300
    // Deleting it on disk removes it, ignored or not; a checkout brings it back.
4301
    fs::remove_file(root.join("src.c")).unwrap();
4302
    let snap = repo.snapshot("status").unwrap();
4303
    assert_eq!(
4304
        snap.statuses
4305
            .iter()
4306
            .map(|s| (s.path.as_str(), s.status))
4307
            .collect::<Vec<_>>(),
4308
        vec![("src.c", ChangeStatus::Removed)]
4309
    );
4310
    repo.checkout(&[h3], true, "checkout").unwrap();
4311
    assert_eq!(fs::read(root.join("src.c")).unwrap(), b"int x, y;\n");
4312
    assert!(!repo.snapshot("status").unwrap().changed);
4313
    let _ = h1;
4314
}
4315
4316
#[test]
4317
fn split_works_on_non_heads_by_node() {
4318
    hermetic();
4319
    let dir = tempfile::tempdir().unwrap();
4320
    let root = dir.path();
4321
    let repo = Repo::init(root).unwrap().with_home(root.join("home"));
4322
    write(root, "a.txt", b"one\n");
4323
    write(root, "junk/x.lock", b"lock\n");
4324
    let h1 = repo.commit("work plus junk", &[]).unwrap();
4325
    write(root, "a.txt", b"one\ntwo\n");
4326
    let h2 = repo.commit("more work", &[]).unwrap();
4327
    assert_eq!(repo.store().get_change(&h2).unwrap().deps, vec![h1]);
4328
    let id1 = repo.store().get_change(&h1).unwrap().change_id;
4329
    // h1 is not a head: split it by node.
4330
    let (hj, h1b) = repo.split(&h1, &["junk".into()]).unwrap();
4331
    assert_ne!(h1b, h1);
4332
    assert_eq!(
4333
        repo.store().get_change(&h1b).unwrap().change_id,
4334
        id1,
4335
        "the rest keeps the ChangeId"
4336
    );
4337
    let junk = repo.store().get_change(&hj).unwrap();
4338
    assert!(junk.tree_ops.iter().all(
4339
        |op| matches!(op, TreeOp::AddNode { name, .. } if name == "junk" || name == "x.lock")
4340
    ));
4341
    let heads = repo.bookmark_heads().unwrap();
4342
    assert!(
4343
        heads.contains(&hj),
4344
        "the split-off part is a head of its own"
4345
    );
4346
    let snap = repo.load_state(&heads).unwrap().materialize();
4347
    assert!(
4348
        matches!(&snap.files["a.txt"].content, FileContent::Text { bytes, .. } if bytes == b"one\ntwo\n"),
4349
        "the dependent was rewritten onto the new hash"
4350
    );
4351
    assert!(snap.files.contains_key("junk/x.lock"));
4352
    let h2b = heads
4353
        .iter()
4354
        .find(|h| repo.store().get_change(h).unwrap().message == "more work")
4355
        .copied()
4356
        .unwrap();
4357
    assert_eq!(repo.store().get_change(&h2b).unwrap().deps, vec![h1b]);
4358
    assert!(!repo.snapshot("status").unwrap().changed);
4359
    // Abandoning the split-off head removes the junk from history.
4360
    repo.abandon(&hj).unwrap();
4361
    let heads = repo.bookmark_heads().unwrap();
4362
    let snap = repo.load_state(&heads).unwrap().materialize();
4363
    assert!(!snap.files.contains_key("junk/x.lock") && !snap.files.contains_key("junk"));
4364
    assert!(snap.files.contains_key("a.txt"));
4365
    // A dependent that touches the split-off paths blocks the split.
4366
    write(root, "junk/y.lock", b"y\n");
4367
    let hb = repo.commit("junk base", &[]).unwrap();
4368
    write(root, "junk/y.lock", b"yy\n");
4369
    write(root, "b.txt", b"b\n");
4370
    repo.commit("touches junk", &[]).unwrap();
4371
    let err = repo.split(&hb, &["junk".into()]).unwrap_err().to_string();
4372
    assert!(err.contains("depends on the split-off paths"), "{err}");
4373
}
4374
4375
#[test]
4376
fn bookmarks_switch_merge_and_push() {
4377
    hermetic();
4378
    let dir = tempfile::tempdir().unwrap();
4379
    let root = dir.path();
4380
    let origin = Repo::init(&root.join("origin")).unwrap();
4381
    let url = root.join("origin").to_string_lossy().to_string();
4382
    let mut repo = Repo::clone(&url, &root.join("r"))
4383
        .unwrap()
4384
        .with_home(root.join("home"));
4385
    let r = root.join("r");
4386
    write(&r, "a.txt", b"a\n");
4387
    let h_a = repo.commit("a", &[]).unwrap();
4388
    assert!(repo.push("origin", false).unwrap()[0].ok);
4389
    origin.refresh().unwrap();
4390
4391
    // A bookmark at the working copy's base, then work on it.
4392
    assert!(repo.bookmark_create("bad name..", None).is_err());
4393
    assert!(repo.bookmark_create("-x", None).is_err());
4394
    assert_eq!(repo.bookmark_create("feature", None).unwrap(), vec![h_a]);
4395
    assert!(repo.bookmark_create("feature", None).is_err(), "exists");
4396
    repo.bookmark_switch("feature", false).unwrap();
4397
    assert_eq!(repo.config.bookmark, "feature");
4398
    write(&r, "a.txt", b"a\nb\n");
4399
    write(&r, "b.txt", b"b\n");
4400
    let h_b = repo.commit("b on feature", &[]).unwrap();
4401
    assert_eq!(
4402
        repo.bookmark_heads().unwrap(),
4403
        vec![h_b],
4404
        "b edits a.txt, so it depends on a"
4405
    );
4406
    assert_eq!(
4407
        repo.resolve_heads("main").unwrap(),
4408
        vec![h_a],
4409
        "main is untouched"
4410
    );
4411
    assert_eq!(
4412
        repo.resolve_change("feature").unwrap(),
4413
        h_b,
4414
        "a one-head bookmark names its change"
4415
    );
4416
    // Reopening keeps the workspace's bookmark.
4417
    let reopened = Repo::open(&r).unwrap().with_home(root.join("home"));
4418
    assert_eq!(reopened.config.bookmark, "feature");
4419
    // Back to main: b.txt goes away; work there.
4420
    repo.bookmark_switch("main", false).unwrap();
4421
    assert!(!r.join("b.txt").exists());
4422
    assert_eq!(fs::read(r.join("a.txt")).unwrap(), b"a\n");
4423
    write(&r, "c.txt", b"c\n");
4424
    let h_c = repo.commit("c on main", &[]).unwrap();
4425
    let list = repo.bookmarks().unwrap();
4426
    assert_eq!(
4427
        list.iter()
4428
            .map(|b| (b.name.as_str(), b.current))
4429
            .collect::<Vec<_>>(),
4430
        vec![("feature", false), ("main", true)]
4431
    );
4432
    assert_eq!(
4433
        list.iter().find(|b| b.name == "main").unwrap().ahead,
4434
        Some(1),
4435
        "c is not on origin yet"
4436
    );
4437
    // Merge feature into main: the union, both heads, no merge change.
4438
    let m = repo.merge("feature").unwrap();
4439
    assert!(m.changed && m.checked_out);
4440
    let mut want = vec![h_b, h_c];
4441
    want.sort();
4442
    assert_eq!(m.heads, want);
4443
    assert_eq!(fs::read(r.join("b.txt")).unwrap(), b"b\n");
4444
    assert!(!repo.merge("feature").unwrap().changed, "already merged");
4445
    assert!(repo.merge("main").is_err());
4446
    // The other bookmark can be pushed by name and appears at origin.
4447
    assert!(repo.push_bookmark("origin", "feature", false).unwrap()[0].ok);
4448
    origin.refresh().unwrap();
4449
    assert_eq!(origin.resolve_heads("feature").unwrap(), vec![h_b]);
4450
    assert!(repo.push("origin", false).unwrap()[0].ok);
4451
    origin.refresh().unwrap();
4452
    assert_eq!(
4453
        repo.bookmarks()
4454
            .unwrap()
4455
            .iter()
4456
            .find(|b| b.name == "main")
4457
            .unwrap()
4458
            .ahead,
4459
        Some(0)
4460
    );
4461
    // A second workspace inherits the current bookmark and can switch independently.
4462
    let ws = repo.workspace_add(&root.join("ws"), None).unwrap();
4463
    assert_eq!(ws.config.bookmark, "main");
4464
    let mut ws = ws;
4465
    ws.bookmark_switch("feature", false).unwrap();
4466
    assert_eq!(
4467
        Repo::open(&r).unwrap().config.bookmark,
4468
        "main",
4469
        "the first workspace is unaffected"
4470
    );
4471
    assert!(
4472
        repo.bookmark_delete("feature").is_err(),
4473
        "current bookmark of another workspace"
4474
    );
4475
    ws.bookmark_switch("main", false).unwrap();
4476
    // Set and delete.
4477
    assert_eq!(repo.bookmark_set("feature", &[h_a]).unwrap(), vec![h_a]);
4478
    assert!(repo.bookmark_delete("main").is_err(), "current here");
4479
    repo.bookmark_delete("feature").unwrap();
4480
    assert!(repo.resolve_heads("feature").is_err());
4481
    assert!(repo.bookmark_set("feature", &[h_a]).is_err());
4482
    assert!(
4483
        repo.checkout(&[h_a], false, "checkout").is_ok(),
4484
        "changes of a deleted bookmark remain"
4485
    );
4486
}
4487
4488
#[test]
4489
fn oxygen_subrepos_pin_follow_and_update() {
4490
    hermetic();
4491
    let dir = tempfile::tempdir().unwrap();
4492
    let root = dir.path();
4493
    // A library repository with two commits, and a bare-ish origin for it.
4494
    let lib_origin = Repo::init(&root.join("lib-origin")).unwrap();
4495
    let lib_url = root.join("lib-origin").to_string_lossy().to_string();
4496
    let lib = Repo::clone(&lib_url, &root.join("lib"))
4497
        .unwrap()
4498
        .with_home(root.join("home"));
4499
    write(&root.join("lib"), "lib.txt", b"v1\n");
4500
    let l1 = lib.commit("lib v1", &[]).unwrap();
4501
    assert!(lib.push("origin", false).unwrap()[0].ok);
4502
    let _ = lib_origin;
4503
4504
    // The application (a clone of its own origin) adds it as a subrepo.
4505
    let app_origin = Repo::init(&root.join("app-origin")).unwrap();
4506
    let app_url = root.join("app-origin").to_string_lossy().to_string();
4507
    let _ = app_origin;
4508
    let app_dir = root.join("app");
4509
    let app = Repo::clone(&app_url, &app_dir)
4510
        .unwrap()
4511
        .with_home(root.join("home"));
4512
    write(&app_dir, "main.txt", b"app\n");
4513
    let pin = app.submodule_add(&lib_url, "libs/lib", None).unwrap();
4514
    assert!(matches!(&pin, crate::subrepo::Pin::Oxy { heads, .. } if heads == &vec![l1]));
4515
    assert!(app_dir.join(".oxymodules").exists() && app_dir.join("libs/lib/.oxy").is_dir());
4516
    let snap = app.snapshot("status").unwrap();
4517
    let paths: Vec<&str> = snap.statuses.iter().map(|s| s.path.as_str()).collect();
4518
    assert_eq!(
4519
        paths,
4520
        vec![".oxymodules", "libs/lib", "main.txt"],
4521
        "the nested files are not walked"
4522
    );
4523
    let a1 = app.commit("app with lib", &[]).unwrap();
4524
    let files = app.load_state(&[a1]).unwrap().materialize().files;
4525
    assert_eq!(files["libs/lib"].kind, NodeKind::Subrepo);
4526
    assert!(!files.contains_key("libs/lib/lib.txt"));
4527
    assert!(!app.snapshot("status").unwrap().changed);
4528
    let subs = app.subrepos().unwrap();
4529
    assert_eq!(subs.len(), 1);
4530
    assert_eq!(subs[0].actual.as_ref(), Some(&subs[0].pin));
4531
4532
    // Advance the nested repository: the parent sees a modified pin.
4533
    let nested = Repo::open(&app_dir.join("libs/lib"))
4534
        .unwrap()
4535
        .with_home(root.join("home"));
4536
    write(&app_dir.join("libs/lib"), "lib.txt", b"v2\n");
4537
    let l2 = nested.commit("lib v2", &[]).unwrap();
4538
    assert!(nested.push("origin", false).unwrap()[0].ok);
4539
    let snap = app.snapshot("status").unwrap();
4540
    assert_eq!(
4541
        snap.statuses
4542
            .iter()
4543
            .map(|s| (s.path.as_str(), s.status))
4544
            .collect::<Vec<_>>(),
4545
        vec![("libs/lib", ChangeStatus::Modified)]
4546
    );
4547
    let a2 = app.commit("bump lib", &[]).unwrap();
4548
    // Checking out the older app state brings the nested working copy back
4549
    // to the older pin, but never moves its bookmark backwards (oxygen#38).
4550
    let r = app.checkout(&[a1], false, "checkout").unwrap();
4551
    assert!(
4552
        r.notes.len() == 1 && r.notes[0].contains("keeps 1 newer change"),
4553
        "{:?}",
4554
        r.notes
4555
    );
4556
    assert_eq!(fs::read(app_dir.join("libs/lib/lib.txt")).unwrap(), b"v1\n");
4557
    let nested = Repo::open(&app_dir.join("libs/lib")).unwrap();
4558
    assert_eq!(nested.bookmark_heads().unwrap(), vec![l2]);
4559
    assert_eq!(nested.working_copy().unwrap().1.deps, vec![l1]);
4560
    assert!(!app.snapshot("status").unwrap().changed);
4561
    // A dirty nested repository is left alone and reported.
4562
    write(&app_dir.join("libs/lib"), "scratch.txt", b"wip\n");
4563
    let r = app.checkout(&[a2], false, "checkout").unwrap();
4564
    assert!(
4565
        r.notes.iter().any(|n| n.contains("uncommitted")),
4566
        "{:?}",
4567
        r.notes
4568
    );
4569
    assert_eq!(fs::read(app_dir.join("libs/lib/lib.txt")).unwrap(), b"v1\n");
4570
    fs::remove_file(app_dir.join("libs/lib/scratch.txt")).unwrap();
4571
    let r = app.submodule_update(false, &[]).unwrap();
4572
    assert_eq!(r, vec![("libs/lib".to_string(), SubrepoSync::Updated)]);
4573
    assert_eq!(fs::read(app_dir.join("libs/lib/lib.txt")).unwrap(), b"v2\n");
4574
    let _ = l2;
4575
4576
    // A fresh clone of the app has the pin but no nested repository until update --init.
4577
    assert!(app.push("origin", false).unwrap()[0].ok);
4578
    let clone_dir = root.join("app-clone");
4579
    let clone = Repo::clone(&app_url, &clone_dir)
4580
        .unwrap()
4581
        .with_home(root.join("home"));
4582
    assert!(!clone_dir.join("libs/lib/.oxy").exists());
4583
    assert_eq!(
4584
        clone.submodule_update(false, &[]).unwrap(),
4585
        vec![("libs/lib".to_string(), SubrepoSync::Missing)]
4586
    );
4587
    assert_eq!(
4588
        clone.submodule_update(true, &[]).unwrap(),
4589
        vec![("libs/lib".to_string(), SubrepoSync::Updated)]
4590
    );
4591
    assert_eq!(
4592
        fs::read(clone_dir.join("libs/lib/lib.txt")).unwrap(),
4593
        b"v2\n"
4594
    );
4595
    assert!(!clone.snapshot("status").unwrap().changed);
4596
    // Removing the subrepo leaves the directory and drops the node.
4597
    clone.submodule_remove("libs/lib").unwrap();
4598
    let snap = clone.snapshot("status").unwrap();
4599
    assert!(
4600
        snap.statuses
4601
            .iter()
4602
            .any(|s| s.path == "libs/lib" && s.status == ChangeStatus::Removed),
4603
        "{:?}",
4604
        snap.statuses
4605
    );
4606
    let c = clone.commit("drop lib", &[]).unwrap();
4607
    assert!(!clone
4608
        .load_state(&[c])
4609
        .unwrap()
4610
        .materialize()
4611
        .files
4612
        .contains_key("libs/lib"));
4613
    assert!(clone_dir.join("libs/lib/lib.txt").exists());
4614
    assert!(
4615
        !clone.snapshot("status").unwrap().changed,
4616
        "an unregistered nested repository is ignored"
4617
    );
4618
}
4619
4620
#[test]
4621
fn git_submodules_import_and_export_as_gitlinks() {
4622
    hermetic();
4623
    if std::process::Command::new("git")
4624
        .arg("--version")
4625
        .output()
4626
        .is_err()
4627
    {
4628
        eprintln!("git not installed; skipping");
4629
        return;
4630
    }
4631
    let dir = tempfile::tempdir().unwrap();
4632
    let root = dir.path();
4633
    let git_in = |d: &Path, args: &[&str]| -> String {
4634
        let out = std::process::Command::new("git")
4635
            .arg("-C")
4636
            .arg(d)
4637
            .args([
4638
                "-c",
4639
                "user.name=Grace",
4640
                "-c",
4641
                "[email protected]",
4642
                "-c",
4643
                "commit.gpgsign=false",
4644
                "-c",
4645
                "protocol.file.allow=always",
4646
            ])
4647
            .args(args)
4648
            .output()
4649
            .unwrap();
4650
        assert!(
4651
            out.status.success(),
4652
            "git {args:?}: {}",
4653
            String::from_utf8_lossy(&out.stderr)
4654
        );
4655
        String::from_utf8_lossy(&out.stdout).trim().to_string()
4656
    };
4657
    let sub = root.join("sub");
4658
    fs::create_dir_all(&sub).unwrap();
4659
    git_in(&sub, &["init", "-q", "-b", "main"]);
4660
    write(&sub, "s.txt", b"sub\n");
4661
    git_in(&sub, &["add", "."]);
4662
    git_in(&sub, &["commit", "-q", "-m", "sub initial"]);
4663
    let sub_sha = git_in(&sub, &["rev-parse", "HEAD"]);
4664
    let g = root.join("main.git");
4665
    fs::create_dir_all(&g).unwrap();
4666
    git_in(&g, &["init", "-q", "-b", "main"]);
4667
    write(&g, "README.md", b"# app\n");
4668
    git_in(&g, &["add", "."]);
4669
    git_in(&g, &["commit", "-q", "-m", "initial"]);
4670
    git_in(
4671
        &g,
4672
        &[
4673
            "submodule",
4674
            "add",
4675
            "-q",
4676
            sub.to_str().unwrap(),
4677
            "vendor/sub",
4678
        ],
4679
    );
4680
    git_in(&g, &["commit", "-q", "-m", "add submodule"]);
4681
4682
    let dest = root.join("oxy");
4683
    let repo = Repo::init(&dest).unwrap().with_home(root.join("home"));
4684
    let rep = repo.import_git(&g, "main").unwrap();
4685
    assert_eq!((rep.commits, rep.submodules), (2, 1));
4686
    let files = repo
4687
        .load_state(&repo.bookmark_heads().unwrap())
4688
        .unwrap()
4689
        .materialize()
4690
        .files;
4691
    assert_eq!(files["vendor/sub"].kind, NodeKind::Subrepo);
4692
    let FileContent::Opaque { blobs } = &files["vendor/sub"].content else {
4693
        panic!()
4694
    };
4695
    assert_eq!(
4696
        crate::subrepo::Pin::decode(&repo.read_blob(&blobs[0]).unwrap()).unwrap(),
4697
        crate::subrepo::Pin::Git {
4698
            sha: sub_sha.clone(),
4699
            branch: "HEAD".into()
4700
        }
4701
    );
4702
    let modules =
4703
        crate::subrepo::Modules::parse(&fs::read_to_string(dest.join(".oxymodules")).unwrap());
4704
    assert_eq!(modules.entries["vendor/sub"].url, sub.to_string_lossy());
4705
    assert!(modules.entries["vendor/sub"].git);
4706
    assert!(
4707
        files.contains_key(".gitmodules"),
4708
        "the Git file is kept for round trips"
4709
    );
4710
    assert!(
4711
        !dest.join("vendor/sub/.git").exists(),
4712
        "not cloned until update --init"
4713
    );
4714
    assert!(!repo.snapshot("status").unwrap().changed);
4715
    // update --init clones it at the pinned commit; status is unchanged.
4716
    assert_eq!(
4717
        repo.submodule_update(true, &[]).unwrap(),
4718
        vec![("vendor/sub".to_string(), SubrepoSync::Updated)]
4719
    );
4720
    assert_eq!(
4721
        git_in(&dest.join("vendor/sub"), &["rev-parse", "HEAD"]),
4722
        sub_sha
4723
    );
4724
    assert!(!repo.snapshot("status").unwrap().changed);
4725
    // Export writes the gitlink and .gitmodules back.
4726
    let mirror = root.join("mirror.git");
4727
    let rep = repo.git_export(&mirror).unwrap();
4728
    assert_eq!(rep.skipped_subrepos, 0);
4729
    let ls = git_in(&mirror, &["ls-tree", "main", "vendor/sub"]);
4730
    assert!(
4731
        ls.starts_with("160000 commit ") && ls.contains(&sub_sha),
4732
        "{ls}"
4733
    );
4734
    assert_eq!(
4735
        git_in(&mirror, &["ls-tree", "--name-only", "main"]),
4736
        ".gitmodules\nREADME.md\nvendor"
4737
    );
4738
    let orig_tree = git_in(&g, &["rev-parse", "main^{tree}"]);
4739
    assert_eq!(
4740
        git_in(&mirror, &["rev-parse", "main^{tree}"]),
4741
        orig_tree,
4742
        "tree round trip"
4743
    );
4744
}
4745
4746
#[test]
4747
fn partial_commits_by_path_and_by_hunk() {
4748
    hermetic();
4749
    let dir = tempfile::tempdir().unwrap();
4750
    let root = dir.path();
4751
    let repo = Repo::init(root).unwrap().with_home(root.join("home"));
4752
    write(root, "a.txt", b"1\n2\n3\n");
4753
    write(root, "b.txt", b"b\n");
4754
    let h0 = repo.commit("base", &[]).unwrap();
4755
    write(root, "a.txt", b"0\n1\n2\n3\n4\n");
4756
    write(root, "b.txt", b"b\nbb\n");
4757
    write(root, "c.txt", b"c\n");
4758
    // By path: only a.txt goes in; the rest stays on disk as uncommitted work.
4759
    let h1 = repo
4760
        .commit_selection("a only", &[], &Selection::Paths(vec!["a.txt".into()]))
4761
        .unwrap();
4762
    let c1 = repo.store().get_change(&h1).unwrap();
4763
    assert!(
4764
        c1.tree_ops.is_empty() && c1.edits.iter().all(|e| e.node() == c1.edits[0].node()),
4765
        "{:?}",
4766
        c1.tree_ops
4767
    );
4768
    assert_eq!(c1.deps, vec![h0]);
4769
    let files = repo.load_state(&[h1]).unwrap().materialize().files;
4770
    assert!(
4771
        matches!(&files["a.txt"].content, FileContent::Text { bytes, .. } if bytes == b"0\n1\n2\n3\n4\n")
4772
    );
4773
    assert!(matches!(&files["b.txt"].content, FileContent::Text { bytes, .. } if bytes == b"b\n"));
4774
    assert!(!files.contains_key("c.txt"));
4775
    let snap = repo.snapshot("status").unwrap();
4776
    assert_eq!(
4777
        snap.statuses
4778
            .iter()
4779
            .map(|s| (s.path.as_str(), s.status))
4780
            .collect::<Vec<_>>(),
4781
        vec![
4782
            ("b.txt", ChangeStatus::Modified),
4783
            ("c.txt", ChangeStatus::Added)
4784
        ]
4785
    );
4786
    assert_eq!(
4787
        fs::read(root.join("b.txt")).unwrap(),
4788
        b"b\nbb\n",
4789
        "disk untouched"
4790
    );
4791
    // By hunk: pick the b.txt insert; c.txt's addition is left.
4792
    let (_, hunks) = repo.hunks().unwrap();
4793
    let b_hunk = hunks
4794
        .iter()
4795
        .find(|h| h.path == "b.txt" && h.text.contains("+bb"))
4796
        .unwrap()
4797
        .index;
4798
    let h2 = repo
4799
        .commit_selection("b only", &[], &Selection::Hunks(vec![b_hunk]))
4800
        .unwrap();
4801
    let files = repo.load_state(&[h2]).unwrap().materialize().files;
4802
    assert!(
4803
        matches!(&files["b.txt"].content, FileContent::Text { bytes, .. } if bytes == b"b\nbb\n")
4804
    );
4805
    assert!(!files.contains_key("c.txt"));
4806
    let snap = repo.snapshot("status").unwrap();
4807
    assert_eq!(
4808
        snap.statuses
4809
            .iter()
4810
            .map(|s| s.path.as_str())
4811
            .collect::<Vec<_>>(),
4812
        vec!["c.txt"]
4813
    );
4814
    // Choosing only the content hunk of a file in a new directory pulls in
4815
    // the directory and file additions it needs.
4816
    write(root, "d/e.txt", b"e\n");
4817
    let (_, hunks) = repo.hunks().unwrap();
4818
    let e_insert = hunks
4819
        .iter()
4820
        .find(|h| h.path == "d/e.txt" && h.text.contains("+e"))
4821
        .unwrap()
4822
        .index;
4823
    let h3 = repo
4824
        .commit_selection("e only", &[], &Selection::Hunks(vec![e_insert]))
4825
        .unwrap();
4826
    let c3 = repo.store().get_change(&h3).unwrap();
4827
    assert_eq!(c3.tree_ops.len(), 2, "{:?}", c3.tree_ops);
4828
    let files = repo.load_state(&[h3]).unwrap().materialize().files;
4829
    assert!(files.contains_key("d/e.txt") && !files.contains_key("c.txt"));
4830
    // Choosing a new file's addition hunk brings its content along.
4831
    write(root, "f/g.txt", b"g\n");
4832
    let (_, hunks) = repo.hunks().unwrap();
4833
    let g_add = hunks
4834
        .iter()
4835
        .find(|h| h.path == "f/g.txt" && h.text.starts_with("A "))
4836
        .unwrap()
4837
        .index;
4838
    let h4 = repo
4839
        .commit_selection("g by addition", &[], &Selection::Hunks(vec![g_add]))
4840
        .unwrap();
4841
    let files = repo.load_state(&[h4]).unwrap().materialize().files;
4842
    assert!(
4843
        matches!(&files["f/g.txt"].content, FileContent::Text { bytes, .. } if bytes == b"g\n")
4844
    );
4845
    assert!(!repo
4846
        .snapshot("status")
4847
        .unwrap()
4848
        .statuses
4849
        .iter()
4850
        .any(|s| s.path == "f/g.txt"));
4851
    // Everything left commits normally; the working copy is then clean.
4852
    repo.commit("the rest", &[]).unwrap();
4853
    assert!(!repo.snapshot("status").unwrap().changed);
4854
    let files = repo
4855
        .load_state(&repo.bookmark_heads().unwrap())
4856
        .unwrap()
4857
        .materialize()
4858
        .files;
4859
    assert!(files.contains_key("c.txt"));
4860
}
4861
4862
#[test]
4863
fn blame_attributes_lines_to_introducing_changes_across_renames() {
4864
    hermetic();
4865
    let dir = tempfile::tempdir().unwrap();
4866
    let root = dir.path();
4867
    let mut repo = Repo::init(root).unwrap().with_home(root.join("home"));
4868
    repo.create_identity("Ada", "[email protected]", IdentityScope::User)
4869
        .unwrap();
4870
    write(root, "a.txt", b"one\n");
4871
    let h1 = repo.commit("first", &[]).unwrap();
4872
    write(root, "a.txt", b"one\ntwo\n");
4873
    let h2 = repo.commit("second", &[]).unwrap();
4874
    let b = repo.blame("a.txt").unwrap();
4875
    assert_eq!(
4876
        b.iter()
4877
            .map(|l| (l.line, l.hash, l.text.as_slice()))
4878
            .collect::<Vec<_>>(),
4879
        vec![(1, h1, b"one\n".as_slice()), (2, h2, b"two\n".as_slice())]
4880
    );
4881
    assert!(b.iter().all(|l| l.author == "Ada"));
4882
    assert_eq!(
4883
        b[0].change_id,
4884
        repo.store().get_change(&h1).unwrap().change_id
4885
    );
4886
    fs::rename(root.join("a.txt"), root.join("b.txt")).unwrap();
4887
    repo.commit("rename", &[]).unwrap();
4888
    let b = repo.blame("b.txt").unwrap();
4889
    assert_eq!(
4890
        b.iter().map(|l| l.hash).collect::<Vec<_>>(),
4891
        vec![h1, h2],
4892
        "the node survives the rename"
4893
    );
4894
    assert!(repo.blame("a.txt").is_err());
4895
}
4896
4897
#[test]
4898
fn bisect_finds_the_first_bad_change() {
4899
    hermetic();
4900
    let dir = tempfile::tempdir().unwrap();
4901
    let root = dir.path();
4902
    let repo = Repo::init(root).unwrap().with_home(root.join("home"));
4903
    let mut content = String::new();
4904
    let mut hashes = Vec::new();
4905
    for i in 1..=8 {
4906
        content.push_str(&format!("line {i}{}\n", if i == 5 { " bug" } else { "" }));
4907
        write(root, "f.txt", content.as_bytes());
4908
        hashes.push(repo.commit(&format!("step {i}"), &[]).unwrap());
4909
    }
4910
    // Each step appends after the previous line, so the chain is linear.
4911
    assert_eq!(repo.bookmark_heads().unwrap(), vec![hashes[7]]);
4912
    repo.bisect_start().unwrap();
4913
    assert!(matches!(
4914
        repo.bisect_mark(Some(true), &[hashes[0]]).unwrap(),
4915
        BisectStep::NeedMarks { good: 1, bad: 0 }
4916
    ));
4917
    let step = repo.bisect_mark(Some(false), &[hashes[7]]).unwrap();
4918
    assert!(
4919
        matches!(step, BisectStep::Testing { remaining: 7, .. }),
4920
        "{step:?}"
4921
    );
4922
    // Automated: bad when the bug line is present.
4923
    let step = repo
4924
        .bisect_run(&["sh".into(), "-c".into(), "! grep -q bug f.txt".into()])
4925
        .unwrap();
4926
    assert_eq!(step, BisectStep::Found { culprit: hashes[4] });
4927
    assert_eq!(
4928
        repo.bisect_status().unwrap(),
4929
        Some(BisectStep::Found { culprit: hashes[4] })
4930
    );
4931
    repo.bisect_reset().unwrap();
4932
    assert_eq!(fs::read_to_string(root.join("f.txt")).unwrap(), content);
4933
    assert!(repo.bisect_status().unwrap().is_none());
4934
    assert!(!repo.snapshot("status").unwrap().changed);
4935
    // Manual marks and a skip.
4936
    repo.bisect_start().unwrap();
4937
    repo.bisect_mark(Some(true), &[hashes[0]]).unwrap();
4938
    let mut step = repo.bisect_mark(Some(false), &[hashes[7]]).unwrap();
4939
    let mut skipped_once = false;
4940
    let mut guard = 0;
4941
    while let BisectStep::Testing { .. } = step {
4942
        guard += 1;
4943
        assert!(guard < 20);
4944
        let text = fs::read_to_string(root.join("f.txt")).unwrap();
4945
        if !skipped_once && text.contains("line 6") {
4946
            // An untestable state away from the boundary: the search routes around it.
4947
            skipped_once = true;
4948
            step = repo.bisect_mark(None, &[]).unwrap();
4949
            continue;
4950
        }
4951
        step = repo.bisect_mark(Some(!text.contains("bug")), &[]).unwrap();
4952
    }
4953
    assert!(skipped_once);
4954
    assert_eq!(step, BisectStep::Found { culprit: hashes[4] });
4955
    repo.bisect_reset().unwrap();
4956
    // Skipping the culprit itself leaves it among the candidates reported.
4957
    repo.bisect_start().unwrap();
4958
    repo.bisect_mark(Some(true), &[hashes[0]]).unwrap();
4959
    let mut step = repo.bisect_mark(Some(false), &[hashes[7]]).unwrap();
4960
    let mut guard = 0;
4961
    while let BisectStep::Testing { heads, .. } = &step {
4962
        guard += 1;
4963
        assert!(guard < 20);
4964
        let text = fs::read_to_string(root.join("f.txt")).unwrap();
4965
        let is_culprit_state =
4966
            heads.contains(&hashes[4]) && !heads.iter().any(|h| hashes[5..].contains(h));
4967
        step = if is_culprit_state {
4968
            repo.bisect_mark(None, &[]).unwrap()
4969
        } else {
4970
            repo.bisect_mark(Some(!text.contains("bug")), &[]).unwrap()
4971
        };
4972
    }
4973
    match step {
4974
        BisectStep::Inconclusive { candidates } => assert!(
4975
            candidates.contains(&hashes[4]) && candidates.len() <= 2,
4976
            "{candidates:?}"
4977
        ),
4978
        other => panic!("{other:?}"),
4979
    }
4980
    repo.bisect_reset().unwrap();
4981
}
4982
4983
#[test]
4984
fn squash_folds_a_change_into_its_dependency() {
4985
    hermetic();
4986
    let dir = tempfile::tempdir().unwrap();
4987
    let root = dir.path();
4988
    let repo = Repo::init(root).unwrap().with_home(root.join("home"));
4989
    write(root, "a.txt", b"1\n");
4990
    let a = repo.commit("A", &[]).unwrap();
4991
    write(root, "a.txt", b"1\n2\n");
4992
    let c = repo.commit("C", &[]).unwrap();
4993
    write(root, "a.txt", b"1\n2\n3\n");
4994
    let e = repo.commit("E", &[]).unwrap();
4995
    write(root, "b.txt", b"b\n");
4996
    let b = repo.commit("B", &[]).unwrap();
4997
    let id_a = repo.store().get_change(&a).unwrap().change_id;
4998
    let id_e = repo.store().get_change(&e).unwrap().change_id;
4999
    // E depends on C which A lacks: refused, naming it.
5000
    let err = repo.squash(&e, &a).unwrap_err().to_string();
5001
    assert!(err.contains(&c.short(12)), "{err}");
5002
    // C into A: A' has both, C is gone, E follows and still reads the same.
5003
    let a2 = repo.squash(&c, &a).unwrap();
5004
    let a2c = repo.store().get_change(&a2).unwrap();
5005
    assert_eq!(a2c.change_id, id_a);
5006
    assert!(a2c.deps.is_empty());
5007
    let heads = repo.bookmark_heads().unwrap();
5008
    let st = repo.load_state(&heads).unwrap();
5009
    assert!(!st.contains(&c) && !st.contains(&a) && !st.contains(&e));
5010
    let e2 = st
5011
        .changes()
5012
        .find(|(_, m)| m.change_id == id_e)
5013
        .map(|(h, _)| *h)
5014
        .unwrap();
5015
    assert_eq!(
5016
        repo.store().get_change(&e2).unwrap().deps,
5017
        vec![a2],
5018
        "E now depends on A' alone"
5019
    );
5020
    let files = st.materialize().files;
5021
    assert!(
5022
        matches!(&files["a.txt"].content, FileContent::Text { bytes, .. } if bytes == b"1\n2\n3\n")
5023
    );
5024
    assert!(files.contains_key("b.txt"));
5025
    assert!(st.contains(&b));
5026
    assert!(!repo.snapshot("status").unwrap().changed);
5027
    assert_eq!(repo.log().unwrap().len(), 4, "working copy, B, E', A'");
5028
    // Undo restores the three original changes.
5029
    repo.undo().unwrap();
5030
    repo.undo().unwrap();
5031
    let st = repo.load_state(&repo.bookmark_heads().unwrap()).unwrap();
5032
    assert!(st.contains(&c) && st.contains(&a) && st.contains(&e));
5033
}
5034
5035
#[test]
5036
fn rebase_re_expresses_a_change_against_another_base() {
5037
    hermetic();
5038
    let dir = tempfile::tempdir().unwrap();
5039
    let root = dir.path();
5040
    let repo = Repo::init(root).unwrap().with_home(root.join("home"));
5041
    write(root, "a.txt", b"1\n2\n");
5042
    let a = repo.commit("A", &[]).unwrap();
5043
    write(root, "a.txt", b"1\n2\n3\n");
5044
    let c = repo.commit("C: append 3", &[]).unwrap();
5045
    write(root, "a.txt", b"1\n2\n3\n4\n");
5046
    let e = repo.commit("E: append 4", &[]).unwrap();
5047
    // A different base: A plus a change that prepends a line.
5048
    repo.checkout(&[a], true, "checkout").unwrap();
5049
    write(root, "a.txt", b"0\n1\n2\n");
5050
    let d = repo.commit("D: prepend 0", &[]).unwrap();
5051
    let id_c = repo.store().get_change(&c).unwrap().change_id;
5052
    let id_e = repo.store().get_change(&e).unwrap().change_id;
5053
    // Rebase C onto D: its effect (append 3) re-derived against D's text.
5054
    let c2 = repo.rebase(&c, &[d]).unwrap();
5055
    let c2c = repo.store().get_change(&c2).unwrap();
5056
    assert_eq!(c2c.change_id, id_c);
5057
    assert!(c2c.deps.contains(&d), "{:?}", c2c.deps);
5058
    let heads = repo.bookmark_heads().unwrap();
5059
    let st = repo.load_state(&heads).unwrap();
5060
    assert!(!st.contains(&c) && st.contains(&d));
5061
    let e2 = st
5062
        .changes()
5063
        .find(|(_, m)| m.change_id == id_e)
5064
        .map(|(h, _)| *h)
5065
        .unwrap();
5066
    let e2deps = repo.store().get_change(&e2).unwrap().deps;
5067
    assert!(
5068
        e2deps.contains(&c2) && !e2deps.contains(&c) && e2deps.contains(&a),
5069
        "E follows C by content and still depends on A, which introduced the file: {e2deps:?}"
5070
    );
5071
    let files = st.materialize().files;
5072
    assert!(
5073
        matches!(&files["a.txt"].content, FileContent::Text { bytes, .. } if bytes == b"0\n1\n2\n3\n4\n"),
5074
        "{:?}",
5075
        files["a.txt"].content
5076
    );
5077
    assert!(!files["a.txt"].is_conflicted());
5078
    // Rebasing onto a state that already contains the change is refused.
5079
    assert!(repo.rebase(&c2, &[c2]).is_err());
5080
    let err = repo.rebase(&e2, &[d]).unwrap_err().to_string();
5081
    assert!(
5082
        err.contains("lacks dependencies"),
5083
        "E needs C, which D's state does not have: {err}"
5084
    );
5085
}
5086
5087
#[test]
5088
fn unsigned_tags_keep_their_message() {
5089
    hermetic();
5090
    let dir = tempfile::tempdir().unwrap();
5091
    let root = dir.path();
5092
    let repo = Repo::init(root).unwrap().with_home(root.join("home"));
5093
    write(root, "a.txt", b"a\n");
5094
    repo.commit("a", &[]).unwrap();
5095
    assert!(repo.secret_key().unwrap().is_none());
5096
    repo.tag_create("v1", &repo.bookmark_heads().unwrap(), "first release")
5097
        .unwrap();
5098
    let tags = repo.tags().unwrap();
5099
    assert_eq!(
5100
        (
5101
            tags[0].name.as_str(),
5102
            tags[0].message.as_str(),
5103
            tags[0].signer.as_deref()
5104
        ),
5105
        ("v1", "first release", None)
5106
    );
5107
    assert!(
5108
        repo.tag_refs().unwrap()[0].attestation.is_none(),
5109
        "an unsigned attestation is not advertised"
5110
    );
5111
}
5112
5113
#[test]
5114
fn fsck_passes_a_sound_repository_and_names_each_fault() {
5115
    // Files on disk are what this tests: tampering with them, and the
5116
    // directory store's crash points.
5117
    if std::env::var_os("OXY_STORE_BACKEND").is_some() {
5118
        return;
5119
    }
5120
    hermetic();
5121
    let dir = tempfile::tempdir().unwrap();
5122
    let root = dir.path();
5123
    let origin_path = root.join("origin");
5124
    let origin = Repo::init(&origin_path).unwrap();
5125
    let mut a = Repo::clone(&origin_path.to_string_lossy(), &root.join("a"))
5126
        .unwrap()
5127
        .with_home(root.join("home-a"));
5128
    a.create_identity("Ada", "[email protected]", IdentityScope::Repo)
5129
        .unwrap();
5130
    write(&root.join("a"), "f.txt", b"one\n");
5131
    write(&root.join("a"), "bin.dat", b"\0\x01\x02binary");
5132
    let h1 = a.commit("first", &[]).unwrap();
5133
    write(&root.join("a"), "f.txt", b"one\ntwo\n");
5134
    let h2 = a.commit("second", &[]).unwrap();
5135
    a.tag_create("v1", &[h2], "first release").unwrap();
5136
    a.checkpoint().unwrap();
5137
    assert!(a.push("origin", false).unwrap()[0].ok);
5138
    origin.refresh().unwrap();
5139
5140
    // Sound: signed changes, a seal, a tag, a checkpoint, a ref attestation.
5141
    for repo in [&a, &origin] {
5142
        let rep = repo.fsck().unwrap();
5143
        assert_eq!(rep.problems, vec![], "{rep:?}");
5144
        // The two commits, plus the working copy's change in `a`.
5145
        assert!(rep.changes >= 2 && rep.signed >= 2, "{rep:?}");
5146
        assert!(rep.ops > 1 && rep.objects > 5);
5147
    }
5148
    assert!(origin.fsck().unwrap().attestations >= 1);
5149
5150
    // A flipped byte in a stored object is corruption, named by hash.
5151
    let c1 = a.store().path_for(&h1);
5152
    let pristine = fs::read(&c1).unwrap();
5153
    let mut bytes = pristine.clone();
5154
    *bytes.last_mut().unwrap() ^= 1;
5155
    fs::write(&c1, &bytes).unwrap();
5156
    let rep = a.fsck().unwrap();
5157
    assert!(rep.errors() >= 1);
5158
    assert!(
5159
        rep.problems
5160
            .iter()
5161
            .any(|p| p.object == Some(h1) && p.what.contains("unreadable")),
5162
        "{rep:?}"
5163
    );
5164
    fs::write(&c1, &pristine).unwrap();
5165
    assert_eq!(a.fsck().unwrap().errors(), 0);
5166
5167
    // A missing change is named with what needed it.
5168
    fs::remove_file(&c1).unwrap();
5169
    let rep = a.fsck().unwrap();
5170
    assert!(
5171
        rep.problems.iter().any(|p| p.severity == Severity::Error
5172
            && p.object == Some(h1)
5173
            && p.what.contains("change missing, needed by change")),
5174
        "{rep:?}"
5175
    );
5176
    fs::write(&c1, &pristine).unwrap();
5177
5178
    // A missing blob is an error in a full clone.
5179
    let c2 = a.store().get_change(&h1).unwrap();
5180
    let blob = c2
5181
        .edits
5182
        .iter()
5183
        .find_map(|e| match e {
5184
            Edit::Replace { new: Some(b), .. } => Some(*b),
5185
            _ => None,
5186
        })
5187
        .expect("the binary file is a blob");
5188
    let bp = a.store().path_for(&blob);
5189
    let blob_bytes = fs::read(&bp).unwrap();
5190
    fs::remove_file(&bp).unwrap();
5191
    let rep = a.fsck().unwrap();
5192
    assert!(
5193
        rep.problems
5194
            .iter()
5195
            .any(|p| p.object == Some(blob) && p.what.contains("blob missing")),
5196
        "{rep:?}"
5197
    );
5198
    fs::write(&bp, &blob_bytes).unwrap();
5199
5200
    // A broken op log head is reported, not a crash.
5201
    let head = root.join("a/.oxy/ops/head");
5202
    let saved = fs::read(&head).unwrap();
5203
    fs::write(&head, b"not a hash").unwrap();
5204
    let rep = a.fsck().unwrap();
5205
    assert!(
5206
        rep.problems.iter().any(|p| p.what.contains("ops/head")),
5207
        "{rep:?}"
5208
    );
5209
    fs::write(&head, saved).unwrap();
5210
    assert_eq!(a.fsck().unwrap().problems, vec![]);
5211
}
5212
5213
/// Copy a directory tree (for restoring a pristine repository).
5214
fn copy_tree(from: &Path, to: &Path) {
5215
    fs::create_dir_all(to).unwrap();
5216
    for e in fs::read_dir(from).unwrap() {
5217
        let e = e.unwrap();
5218
        let target = to.join(e.file_name());
5219
        if e.file_type().unwrap().is_dir() {
5220
            copy_tree(&e.path(), &target);
5221
        } else {
5222
            fs::copy(e.path(), &target).unwrap();
5223
        }
5224
    }
5225
}
5226
5227
/// Spec §13.6: stop `commit` and `push` at every durable step, as a crash
5228
/// would, and check that both repositories still open, pass `fsck`, and
5229
/// accept the same operation again.
5230
#[test]
5231
fn crash_at_every_step_of_commit_and_push_leaves_sound_repositories() {
5232
    // Files on disk are what this tests: tampering with them, and the
5233
    // directory store's crash points.
5234
    if std::env::var_os("OXY_STORE_BACKEND").is_some() {
5235
        return;
5236
    }
5237
    use crate::durable::failpoint;
5238
    hermetic();
5239
    let dir = tempfile::tempdir().unwrap();
5240
    let pristine = dir.path().join("pristine");
5241
    let origin_path = pristine.join("origin");
5242
    Repo::init(&origin_path).unwrap();
5243
    let mut a = Repo::clone(&origin_path.to_string_lossy(), &pristine.join("a"))
5244
        .unwrap()
5245
        .with_home(dir.path().join("home"));
5246
    a.create_identity("Ada", "[email protected]", IdentityScope::Repo)
5247
        .unwrap();
5248
    write(&pristine.join("a"), "f.txt", b"one\n");
5249
    a.commit("first", &[]).unwrap();
5250
    assert!(a.push("origin", false).unwrap()[0].ok);
5251
    drop(a);
5252
5253
    type Op = fn(&Repo) -> Result<()>;
5254
    let edit_and_commit: Op = |r| {
5255
        write(r.root(), "f.txt", b"one\ntwo\n");
5256
        write(r.root(), "big.bin", &vec![7u8; 300_000]);
5257
        r.commit("second", &[]).map(|_| ())
5258
    };
5259
    let push: Op = |r| {
5260
        let res = r.push("origin", false)?;
5261
        if res.iter().all(|x| x.ok) {
5262
            Ok(())
5263
        } else {
5264
            Err(RepoError::Msg(format!("{res:?}")))
5265
        }
5266
    };
5267
5268
    for (name, prepare, op) in [
5269
        ("commit", None, edit_and_commit),
5270
        ("push", Some(edit_and_commit), push),
5271
    ] {
5272
        let mut steps = 0;
5273
        for n in 1.. {
5274
            let run = dir.path().join(format!("{name}-{n}"));
5275
            copy_tree(&pristine, &run);
5276
            // Clones record their remote by path; point it at this copy.
5277
            let open = |p: &Path| {
5278
                let mut r = Repo::open(p).unwrap().with_home(dir.path().join("home"));
5279
                r.config
5280
                    .set("remote.origin.url", &run.join("origin").to_string_lossy())
5281
                    .unwrap();
5282
                r.save_config().unwrap();
5283
                r
5284
            };
5285
            let a = open(&run.join("a"));
5286
            if let Some(prep) = prepare {
5287
                prep(&a).unwrap();
5288
            }
5289
            failpoint::crash_after(n);
5290
            let outcome = op(&a);
5291
            let crashed = failpoint::disarm();
5292
            drop(a);
5293
            if !crashed {
5294
                outcome.unwrap_or_else(|e| panic!("{name} failed without a crash: {e}"));
5295
                steps = n - 1;
5296
                break;
5297
            }
5298
            assert!(
5299
                outcome.is_err(),
5300
                "{name}: a crash at step {n} was swallowed"
5301
            );
5302
            for repo in ["a", "origin"] {
5303
                let r = Repo::open(&run.join(repo)).unwrap_or_else(|e| {
5304
                    panic!("{name} crash at step {n}: {repo} no longer opens: {e}")
5305
                });
5306
                let rep = r.fsck().unwrap();
5307
                assert_eq!(
5308
                    rep.errors(),
5309
                    0,
5310
                    "{name} crash at step {n}: {repo} fails fsck: {:?}",
5311
                    rep.problems
5312
                );
5313
            }
5314
            // The interrupted operation can simply be run again.
5315
            let a = open(&run.join("a"));
5316
            // A crash after the commit point leaves the commit done.
5317
            let landed = a
5318
                .bookmark_heads()
5319
                .unwrap()
5320
                .iter()
5321
                .any(|h| a.store().get_change(h).unwrap().message == "second");
5322
            let again = match (name, landed) {
5323
                ("commit", true) => Ok(()),
5324
                ("commit", false) => a.commit("second", &[]).map(|_| ()),
5325
                _ => op(&a),
5326
            };
5327
            again.unwrap_or_else(|e| panic!("{name} crash at step {n}: retry failed: {e}"));
5328
            assert_eq!(a.fsck().unwrap().errors(), 0);
5329
            fs::remove_dir_all(&run).unwrap();
5330
        }
5331
        assert!(steps >= 3, "{name} has only {steps} durable steps?");
5332
    }
5333
}
5334
5335
/// Spec §12.1: commands in two workspaces of one repository, and pushes,
5336
/// running at the same time lose nothing: every commit ends up on the
5337
/// bookmark, locally and on the remote, and the repository passes fsck.
5338
#[test]
5339
fn concurrent_commits_in_two_workspaces_lose_nothing() {
5340
    hermetic();
5341
    let dir = tempfile::tempdir().unwrap();
5342
    let root = dir.path();
5343
    let origin = root.join("origin");
5344
    Repo::init_bare_unbound(&origin).unwrap();
5345
    let main = root.join("main");
5346
    let mut repo = Repo::init(&main).unwrap();
5347
    repo.config
5348
        .set("remote.origin.url", &origin.to_string_lossy())
5349
        .unwrap();
5350
    repo.save_config().unwrap();
5351
    write(&main, "seed.txt", b"seed\n");
5352
    repo.commit("seed", &[]).unwrap();
5353
    let second = root.join("second");
5354
    repo.workspace_add(&second, None).unwrap();
5355
    drop(repo);
5356
5357
    const EACH: usize = 15;
5358
    std::thread::scope(|s| {
5359
        for (tag, dir, push) in [("a", main.clone(), true), ("b", second.clone(), false)] {
5360
            s.spawn(move || {
5361
                let r = Repo::open(&dir).unwrap();
5362
                for i in 0..EACH {
5363
                    write(
5364
                        &dir,
5365
                        &format!("{tag}-{i}.txt"),
5366
                        format!("{tag} {i}\n").as_bytes(),
5367
                    );
5368
                    r.commit(&format!("{tag} {i}"), &[]).unwrap();
5369
                    if push && i % 5 == 4 {
5370
                        // A push may be refused while the other workspace moves the bookmark; nothing may be lost either way.
5371
                        let _ = r.push("origin", false);
5372
                    }
5373
                }
5374
            });
5375
        }
5376
    });
5377
5378
    let repo = Repo::open(&main).unwrap();
5379
    let heads = repo.bookmark_heads().unwrap();
5380
    let state = repo.load_state(&heads).unwrap();
5381
    let messages: BTreeSet<String> = state.changes().map(|(_, m)| m.message.clone()).collect();
5382
    for tag in ["a", "b"] {
5383
        for i in 0..EACH {
5384
            assert!(
5385
                messages.contains(&format!("{tag} {i}")),
5386
                "lost commit {tag} {i}; have {messages:?}"
5387
            );
5388
        }
5389
    }
5390
    let rep = repo.fsck().unwrap();
5391
    assert_eq!(rep.errors(), 0, "{:?}", rep.problems);
5392
    assert!(repo.push("origin", false).unwrap().iter().all(|r| r.ok));
5393
    let hosted = Repo::open(&origin).unwrap();
5394
    let hosted_heads = hosted.bookmark_heads().unwrap();
5395
    assert_eq!(
5396
        hosted.load_state(&hosted_heads).unwrap().len(),
5397
        state.len(),
5398
        "the remote has every commit"
5399
    );
5400
}
5401
5402
/// Two operations recorded from the same parent (what two processes do
5403
/// when they race) are merged: both bookmarks' heads survive, and a
5404
/// change made on one side only is kept.
5405
#[test]
5406
fn operations_from_the_same_parent_are_merged() {
5407
    hermetic();
5408
    let dir = tempfile::tempdir().unwrap();
5409
    let root = dir.path();
5410
    let repo = Repo::init(root).unwrap();
5411
    write(root, "a.txt", b"a\n");
5412
    let a = repo.commit("a", &[]).unwrap();
5413
    write(root, "b.txt", b"b\n");
5414
    let b = repo.commit("b", &[]).unwrap();
5415
    let (x, op) = repo.head_op().unwrap();
5416
    let state = |heads: Vec<ChangeHash>| repo.store().put_state(&StateObject::new(heads)).unwrap();
5417
5418
    // Side one moves main to just `a` and adds a bookmark; side two moves main to just `b`.
5419
    let mut one = op.view.clone();
5420
    one.bookmarks.insert("main".into(), state(vec![a]));
5421
    one.bookmarks.insert("topic".into(), state(vec![a]));
5422
    let mut two = op.view.clone();
5423
    two.bookmarks.insert("main".into(), state(vec![b]));
5424
    repo.record_op(&[x], "one", one).unwrap();
5425
    let merged = repo.record_op(&[x], "two", two).unwrap();
5426
5427
    let (head, op) = repo.head_op().unwrap();
5428
    assert_eq!(head, merged);
5429
    assert_eq!(op.parents.len(), 2, "a merge of the two operations");
5430
    assert!(op.command.contains("merged with a concurrent operation"));
5431
    let mut main = repo
5432
        .store()
5433
        .get_state(&op.view.bookmarks["main"])
5434
        .unwrap()
5435
        .heads;
5436
    main.sort();
5437
    let mut want = vec![a, b];
5438
    want.sort();
5439
    assert_eq!(main, want, "both sides' heads are kept");
5440
    assert!(
5441
        op.view.bookmarks.contains_key("topic"),
5442
        "a one-sided change survives"
5443
    );
5444
    assert_eq!(repo.fsck().unwrap().errors(), 0);
5445
}
5446
5447
#[test]
5448
fn failed_requests_come_with_a_next_step() {
5449
    use crate::protocol::hint_for;
5450
    assert!(hint_for("https://h/x/oxy/v1/push: HTTP 401: bad token")
5451
        .unwrap()
5452
        .contains("token"));
5453
    assert!(hint_for("…: HTTP 403: forbidden")
5454
        .unwrap()
5455
        .contains("repo:write"));
5456
    assert!(hint_for("…: HTTP 404: no such repository")
5457
        .unwrap()
5458
        .contains("owner and repository name"));
5459
    assert!(hint_for("invalid peer certificate: UnknownIssuer")
5460
        .unwrap()
5461
        .contains("oxyhub-ca.pem"));
5462
    assert!(hint_for("Connect error: Connection refused (os error 111)")
5463
        .unwrap()
5464
        .contains("running"));
5465
    assert!(hint_for("Dns Failed: failed to lookup address information")
5466
        .unwrap()
5467
        .contains("resolve"));
5468
    assert_eq!(hint_for("something else entirely"), None);
5469
}
5470
5471
#[test]
5472
fn doctor_names_problems_and_what_to_do() {
5473
    hermetic();
5474
    let dir = tempfile::tempdir().unwrap();
5475
    let root = dir.path();
5476
    let origin = root.join("origin");
5477
    Repo::init_bare_unbound(&origin).unwrap();
5478
    let mut repo = Repo::init(&root.join("r"))
5479
        .unwrap()
5480
        .with_home(root.join("home"));
5481
    let find = |r: &DoctorReport, area: &str, h: Health| {
5482
        r.checks
5483
            .iter()
5484
            .find(|c| c.area == area && c.health == h)
5485
            .cloned()
5486
    };
5487
5488
    let r = repo.doctor(true);
5489
    assert!(find(&r, "identity", Health::Warn)
5490
        .unwrap()
5491
        .hint
5492
        .unwrap()
5493
        .contains("oxy identity create"));
5494
    assert!(find(&r, "repository", Health::Ok).is_some());
5495
5496
    repo.create_identity("Ada", "[email protected]", IdentityScope::Repo)
5497
        .unwrap();
5498
    repo.config.set("author.name", "Ada").unwrap();
5499
    repo.config.set("author.email", "[email protected]").unwrap();
5500
    repo.config
5501
        .set("remote.origin.url", &origin.to_string_lossy())
5502
        .unwrap();
5503
    repo.config
5504
        .set("remote.down.url", "http://127.0.0.1:9/a/b")
5505
        .unwrap();
5506
    repo.config.set("remote.down.token", "t").unwrap();
5507
    repo.config
5508
        .set("remote.badca.url", "https://example.invalid/a/b")
5509
        .unwrap();
5510
    repo.config
5511
        .set(
5512
            "remote.badca.ca",
5513
            &root.join("missing.pem").to_string_lossy(),
5514
        )
5515
        .unwrap();
5516
    repo.save_config().unwrap();
5517
5518
    let r = repo.doctor(true);
5519
    assert!(find(&r, "identity", Health::Ok).is_some(), "{r:?}");
5520
    assert!(find(&r, "author", Health::Ok).is_some(), "{r:?}");
5521
    assert!(find(&r, "remote origin", Health::Ok)
5522
        .unwrap()
5523
        .message
5524
        .contains("first push binds it"));
5525
    let down = find(&r, "remote down", Health::Fail).unwrap();
5526
    assert!(
5527
        down.hint.as_deref().unwrap_or("").contains("running"),
5528
        "{down:?}"
5529
    );
5530
    let badca = find(&r, "remote badca", Health::Fail).unwrap();
5531
    assert!(
5532
        badca.hint.unwrap().contains("remote.badca.ca"),
5533
        "the remote's own name is in the hint"
5534
    );
5535
    assert_eq!(r.worst(), Health::Fail);
5536
5537
    // Offline, nothing is contacted.
5538
    let r = repo.doctor(false);
5539
    assert!(find(&r, "remote down", Health::Fail).is_none());
5540
    assert!(find(&r, "remote down", Health::Ok)
5541
        .unwrap()
5542
        .message
5543
        .contains("not contacted"));
5544
}
5545
5546
/// Spec §8.1: deleting a line depends on whoever inserted the lines right
5547
/// after it. Inserting after `b` and then deleting `b`, one commit after
5548
/// the other, must not leave a delete/insert conflict.
5549
#[test]
5550
fn deleting_a_line_after_an_insertion_below_it_is_not_a_conflict() {
5551
    hermetic();
5552
    let dir = tempfile::tempdir().unwrap();
5553
    let root = dir.path();
5554
    let repo = Repo::init(root).unwrap();
5555
    write(root, "f", b"a\nb\nc\n");
5556
    repo.commit("base", &[]).unwrap();
5557
    write(root, "f", b"a\nb\nx\nc\n");
5558
    let insert = repo.commit("insert x after b", &[]).unwrap();
5559
    write(root, "f", b"a\nx\nc\n");
5560
    let delete = repo.commit("delete b", &[]).unwrap();
5561
    assert!(
5562
        repo.store()
5563
            .get_change(&delete)
5564
            .unwrap()
5565
            .deps
5566
            .contains(&insert),
5567
        "the deletion depends on the insertion below the deleted line"
5568
    );
5569
    let heads = repo.bookmark_heads().unwrap();
5570
    assert_eq!(heads, vec![delete]);
5571
    let snap = repo.load_state(&heads).unwrap().materialize();
5572
    assert!(!snap.is_conflicted());
5573
    assert!(
5574
        matches!(&snap.files["f"].content, FileContent::Text { bytes, .. } if bytes == b"a\nx\nc\n")
5575
    );
5576
}
5577
5578
/// Spec §9.3: a binary file reverted to an earlier blob keeps it, and each
5579
/// replacement depends on the change that set the blob it replaces.
5580
#[test]
5581
fn a_binary_file_reverted_to_an_earlier_blob_keeps_it() {
5582
    hermetic();
5583
    let dir = tempfile::tempdir().unwrap();
5584
    let root = dir.path();
5585
    let repo = Repo::init(root).unwrap();
5586
    write(root, "bin", b"\0A");
5587
    let v1 = repo.commit("v1", &[]).unwrap();
5588
    write(root, "bin", b"\0B");
5589
    let v2 = repo.commit("v2", &[]).unwrap();
5590
    assert!(repo.store().get_change(&v2).unwrap().deps.contains(&v1));
5591
    write(root, "bin", b"\0A");
5592
    let v3 = repo.commit("back to A", &[]).unwrap();
5593
    assert!(repo.store().get_change(&v3).unwrap().deps.contains(&v2));
5594
    assert_eq!(repo.bookmark_heads().unwrap(), vec![v3]);
5595
    let state = repo.load_state(&[v3]).unwrap();
5596
    let snap = state.materialize();
5597
    let FileContent::Opaque { blobs } = &snap.files["bin"].content else {
5598
        panic!("opaque")
5599
    };
5600
    assert_eq!(blobs.len(), 1, "one live blob, not none and not two");
5601
    assert_eq!(repo.read_blob(&blobs[0]).unwrap(), b"\0A");
5602
}
5603
5604
/// Spec §23: a binary file changed on two branches and merged in Git to
5605
/// one side's version comes back as that version at the merge, and the
5606
/// import verifies commit by commit.
5607
#[test]
5608
fn git_import_resolves_a_binary_merged_in_git_and_verifies() {
5609
    hermetic();
5610
    if std::process::Command::new("git")
5611
        .arg("--version")
5612
        .output()
5613
        .is_err()
5614
    {
5615
        eprintln!("git not installed; skipping");
5616
        return;
5617
    }
5618
    let dir = tempfile::tempdir().unwrap();
5619
    let root = dir.path();
5620
    let g = root.join("src.git");
5621
    fs::create_dir_all(&g).unwrap();
5622
    let git = |args: &[&str]| -> String {
5623
        let out = std::process::Command::new("git")
5624
            .arg("-C")
5625
            .arg(&g)
5626
            .args([
5627
                "-c",
5628
                "user.name=Grace",
5629
                "-c",
5630
                "[email protected]",
5631
                "-c",
5632
                "commit.gpgsign=false",
5633
            ])
5634
            .args(args)
5635
            .output()
5636
            .unwrap();
5637
        assert!(
5638
            out.status.success(),
5639
            "git {args:?}: {}",
5640
            String::from_utf8_lossy(&out.stderr)
5641
        );
5642
        String::from_utf8_lossy(&out.stdout).trim().to_string()
5643
    };
5644
    git(&["init", "-q", "-b", "main"]);
5645
    write(&g, "logo.bin", b"\0base");
5646
    write(&g, "notes.txt", b"a\nb\nc\n");
5647
    git(&["add", "."]);
5648
    git(&["commit", "-qm", "base"]);
5649
    git(&["checkout", "-qb", "side"]);
5650
    write(&g, "logo.bin", b"\0side");
5651
    write(&g, "notes.txt", b"a\nb\nx\nc\n");
5652
    git(&["commit", "-qam", "side"]);
5653
    git(&["checkout", "-q", "main"]);
5654
    write(&g, "logo.bin", b"\0main");
5655
    git(&["commit", "-qam", "main"]);
5656
    // Git cannot merge the binary; the merge takes main's and keeps side's text.
5657
    let _ = std::process::Command::new("git")
5658
        .arg("-C")
5659
        .arg(&g)
5660
        .args([
5661
            "-c",
5662
            "user.name=G",
5663
            "-c",
5664
            "user.email=g@e",
5665
            "merge",
5666
            "-q",
5667
            "side",
5668
        ])
5669
        .output();
5670
    write(&g, "logo.bin", b"\0main");
5671
    git(&["add", "."]);
5672
    git(&["commit", "-qm", "merge side"]);
5673
    // Then a revert of the binary to its first version.
5674
    write(&g, "logo.bin", b"\0base");
5675
    git(&["commit", "-qam", "back to base"]);
5676
5677
    let repo = Repo::init(&root.join("o")).unwrap();
5678
    let rep = repo.import_git(&g, "main").unwrap();
5679
    assert_eq!(rep.merges, 1);
5680
    let v = repo.verify_git_import(&g, "main").unwrap();
5681
    assert!(v.mismatches.is_empty(), "{:?}", v.mismatches);
5682
    assert_eq!(v.commits, 5);
5683
    let snap = repo
5684
        .load_state(&repo.bookmark_heads().unwrap())
5685
        .unwrap()
5686
        .materialize();
5687
    assert!(!snap.is_conflicted());
5688
    let FileContent::Opaque { blobs } = &snap.files["logo.bin"].content else {
5689
        panic!("opaque")
5690
    };
5691
    assert_eq!(repo.read_blob(&blobs[0]).unwrap(), b"\0base");
5692
}
5693
5694
/// Spec §7.7 on a file system without executable bits or symlinks: the
5695
/// recorded bit is kept, and a symlink checked out as a plain file holding
5696
/// its target is still that symlink.
5697
#[cfg(unix)]
5698
#[test]
5699
fn windows_file_systems_keep_exec_bits_and_symlinks() {
5700
    use crate::portable::Platform;
5701
    use std::os::unix::fs::PermissionsExt;
5702
    hermetic();
5703
    let dir = tempfile::tempdir().unwrap();
5704
    let root = dir.path();
5705
    let repo = Repo::init(root).unwrap();
5706
    write(root, "run.sh", b"#!/bin/sh\n");
5707
    fs::set_permissions(root.join("run.sh"), fs::Permissions::from_mode(0o755)).unwrap();
5708
    std::os::unix::fs::symlink("run.sh", root.join("link")).unwrap();
5709
    repo.commit("script and link", &[]).unwrap();
5710
    drop(repo);
5711
5712
    // What checking out on Windows leaves: no exec bit, the link as a file.
5713
    fs::set_permissions(root.join("run.sh"), fs::Permissions::from_mode(0o644)).unwrap();
5714
    fs::remove_file(root.join("link")).unwrap();
5715
    write(root, "link", b"run.sh");
5716
    let win = Repo::open(root).unwrap().with_platform(Platform::windows());
5717
    let s = win.snapshot("oxy status").unwrap();
5718
    assert!(
5719
        s.statuses.is_empty(),
5720
        "nothing changed on Windows: {:?}",
5721
        statuses(&s)
5722
    );
5723
    // Editing the file is a content change, not a mode change; retargeting the link keeps it a link.
5724
    write(root, "run.sh", b"#!/bin/sh\necho hi\n");
5725
    write(root, "link", b"other");
5726
    let h = win.commit("edit on Windows", &[]).unwrap();
5727
    let snap = win.load_state(&[h]).unwrap().materialize();
5728
    assert!(snap.files["run.sh"].mode.exec, "the exec bit survives");
5729
    assert_eq!(snap.files["link"].kind, NodeKind::Symlink);
5730
    // The same working copy read as Linux sees the lost bit and the plain file.
5731
    let linux = Repo::open(root).unwrap();
5732
    assert!(!linux.snapshot("oxy status").unwrap().statuses.is_empty());
5733
}
5734
5735
/// Paths that collide on case-insensitive or Windows file systems are
5736
/// named at checkout there, and by doctor everywhere.
5737
#[test]
5738
fn paths_other_platforms_cannot_hold_are_reported() {
5739
    use crate::portable::Platform;
5740
    hermetic();
5741
    let dir = tempfile::tempdir().unwrap();
5742
    let root = dir.path();
5743
    let repo = Repo::init(root).unwrap();
5744
    write(root, "README.md", b"a\n");
5745
    write(root, "readme.md", b"b\n");
5746
    write(root, "src/aux.c", b"int x;\n");
5747
    let h = repo.commit("unportable", &[]).unwrap();
5748
    let r = repo.doctor(false);
5749
    let port = r.checks.iter().find(|c| c.area == "portability").unwrap();
5750
    assert_eq!(port.health, Health::Warn);
5751
    assert!(
5752
        port.message.contains("differ only in case") && port.message.contains("aux.c"),
5753
        "{}",
5754
        port.message
5755
    );
5756
    let mac = Repo::open(root).unwrap().with_platform(Platform::macos());
5757
    let rep = mac.checkout(&[h], true, "oxy checkout").unwrap();
5758
    assert!(
5759
        rep.notes
5760
            .iter()
5761
            .any(|n| n.contains("README.md and readme.md")),
5762
        "{:?}",
5763
        rep.notes
5764
    );
5765
    assert!(
5766
        !rep.notes.iter().any(|n| n.contains("aux.c")),
5767
        "macOS allows aux.c"
5768
    );
5769
}
5770
5771
#[test]
5772
fn history_and_blame_of_a_loaded_state_match_the_full_walk() {
5773
    hermetic();
5774
    let dir = tempfile::tempdir().unwrap();
5775
    let repo = Repo::init(dir.path()).unwrap();
5776
    write(dir.path(), "a.txt", b"one\n");
5777
    write(dir.path(), "other.txt", b"x\n");
5778
    write(dir.path(), "bin.dat", &[0u8, 1, 2, 0, 255]);
5779
    repo.snapshot("t").unwrap();
5780
    let c1 = repo.commit("first", &[]).unwrap();
5781
    write(dir.path(), "other.txt", b"y\n");
5782
    repo.snapshot("t").unwrap();
5783
    repo.commit("other only", &[]).unwrap();
5784
    write(dir.path(), "a.txt", b"one\ntwo\n");
5785
    repo.snapshot("t").unwrap();
5786
    let c3 = repo.commit("second line", &[]).unwrap();
5787
    write(dir.path(), "other.txt", b"z\n");
5788
    repo.snapshot("t").unwrap();
5789
    repo.commit("other again", &[]).unwrap();
5790
5791
    let heads = repo.bookmark_heads().unwrap();
5792
    let state = repo.load_state(&heads).unwrap();
5793
    let full: Vec<ChangeHash> = repo
5794
        .log_for_path_in("a.txt", &heads)
5795
        .unwrap()
5796
        .iter()
5797
        .map(|e| e.hash)
5798
        .collect();
5799
    assert_eq!(
5800
        full,
5801
        vec![c3, c1],
5802
        "newest first, only changes touching the path"
5803
    );
5804
    let newest: Vec<ChangeHash> = repo
5805
        .log_for_path_of(&state, "a.txt", Some(1))
5806
        .unwrap()
5807
        .iter()
5808
        .map(|e| e.hash)
5809
        .collect();
5810
    assert_eq!(newest, vec![c3], "stops at the first");
5811
    assert_eq!(
5812
        repo.log_for_path_of(&state, "a.txt", None).unwrap().len(),
5813
        2
5814
    );
5815
    assert!(repo
5816
        .log_for_path_of(&state, "missing.txt", Some(1))
5817
        .is_err());
5818
    assert_eq!(
5819
        repo.log_state(&heads).unwrap().len(),
5820
        repo.log_of(&state).len()
5821
    );
5822
5823
    let tree = state.tree().view();
5824
    let via_state = repo.blame_of(&state, &tree, "a.txt").unwrap();
5825
    let via_heads = repo.blame_in("a.txt", &heads).unwrap();
5826
    assert_eq!(
5827
        via_state
5828
            .iter()
5829
            .map(|l| (l.hash, l.text.clone()))
5830
            .collect::<Vec<_>>(),
5831
        via_heads
5832
            .iter()
5833
            .map(|l| (l.hash, l.text.clone()))
5834
            .collect::<Vec<_>>()
5835
    );
5836
    assert_eq!(
5837
        via_state.iter().map(|l| l.hash).collect::<Vec<_>>(),
5838
        vec![c1, c3]
5839
    );
5840
    assert!(repo.blame_of(&state, &tree, "missing.txt").is_err());
5841
}
5842
5843
/// A text file whose stat matches the manifest and whose recorded hash is
5844
/// the base's content is taken from the base without reading it; anything
5845
/// else is read, so no edit is missed (spec §12.3).
5846
#[cfg(unix)]
5847
#[test]
5848
fn stat_cache_takes_unchanged_text_from_the_base_and_misses_no_edit() {
5849
    use std::os::unix::fs::PermissionsExt;
5850
    hermetic();
5851
    let dir = tempfile::tempdir().unwrap();
5852
    let root = dir.path();
5853
    let repo = Repo::init(root).unwrap().with_home(root.join("home"));
5854
    write(root, "a.txt", b"one\ntwo\n");
5855
    write(root, "b.txt", b"bee\n");
5856
    repo.commit("base", &[]).unwrap();
5857
    let age = |p: &str| {
5858
        let old = std::time::SystemTime::now() - std::time::Duration::from_secs(30);
5859
        fs::File::options()
5860
            .write(true)
5861
            .open(root.join(p))
5862
            .unwrap()
5863
            .set_modified(old)
5864
            .unwrap();
5865
    };
5866
    age("a.txt");
5867
    age("b.txt");
5868
    assert!(
5869
        !repo.snapshot("status").unwrap().changed,
5870
        "records the aged stat"
5871
    );
5872
5873
    // Clean and equal to the base: not read at all.
5874
    fs::set_permissions(root.join("a.txt"), fs::Permissions::from_mode(0o000)).unwrap();
5875
    let snap = repo.snapshot("status").unwrap();
5876
    assert!(
5877
        !snap.changed && snap.statuses.is_empty(),
5878
        "{:?}",
5879
        snap.statuses
5880
    );
5881
    fs::set_permissions(root.join("a.txt"), fs::Permissions::from_mode(0o644)).unwrap();
5882
5883
    // An uncommitted edit that is older than the manifest: stat-clean, but
5884
    // its hash is not the base's, so it is read and stays visible.
5885
    write(root, "b.txt", b"bee edited\n");
5886
    age("b.txt");
5887
    let first = repo.snapshot("status").unwrap();
5888
    assert_eq!(
5889
        statuses(&first),
5890
        vec![("b.txt".to_string(), ChangeStatus::Modified)]
5891
    );
5892
    let again = repo.snapshot("status").unwrap();
5893
    assert_eq!(
5894
        statuses(&again),
5895
        vec![("b.txt".to_string(), ChangeStatus::Modified)],
5896
        "still seen once stat-clean"
5897
    );
5898
    assert!(!again.changed, "and the working copy hashes the same");
5899
    fs::set_permissions(root.join("b.txt"), fs::Permissions::from_mode(0o000)).unwrap();
5900
    assert!(
5901
        repo.snapshot("status").is_err(),
5902
        "an edited file must be read, never taken from the base"
5903
    );
5904
    fs::set_permissions(root.join("b.txt"), fs::Permissions::from_mode(0o644)).unwrap();
5905
5906
    // A same-size edit made just now is racy and read.
5907
    write(root, "a.txt", b"one\nTWO\n");
5908
    assert_eq!(
5909
        statuses(&repo.snapshot("status").unwrap()),
5910
        vec![
5911
            ("a.txt".to_string(), ChangeStatus::Modified),
5912
            ("b.txt".to_string(), ChangeStatus::Modified)
5913
        ]
5914
    );
5915
    // Committing makes the edits the base: both are clean and served from it again.
5916
    repo.commit("edits", &[]).unwrap();
5917
    age("a.txt");
5918
    age("b.txt");
5919
    assert!(repo.snapshot("status").unwrap().statuses.is_empty());
5920
    fs::set_permissions(root.join("a.txt"), fs::Permissions::from_mode(0o000)).unwrap();
5921
    fs::set_permissions(root.join("b.txt"), fs::Permissions::from_mode(0o000)).unwrap();
5922
    let snap = repo.snapshot("status").unwrap();
5923
    assert!(!snap.changed && snap.statuses.is_empty());
5924
    fs::set_permissions(root.join("a.txt"), fs::Permissions::from_mode(0o644)).unwrap();
5925
    fs::set_permissions(root.join("b.txt"), fs::Permissions::from_mode(0o644)).unwrap();
5926
}
5927
5928
/// Version 2 checkpoints (spec §11): a large file's graph is a blob of its
5929
/// own, kept by gc, checked by fsck, shared by the next checkpoint when the
5930
/// file is unchanged, and loading through the checkpoint equals a full load.
5931
#[test]
5932
fn checkpoints_keep_large_graphs_as_blobs_of_their_own() {
5933
    hermetic();
5934
    let dir = tempfile::tempdir().unwrap();
5935
    let root = dir.path();
5936
    let repo = Repo::init(root).unwrap().with_home(root.join("home"));
5937
    let long: String = (0..300)
5938
        .map(|i| format!("line {i} of a long file\n"))
5939
        .collect();
5940
    write(root, "long.txt", long.as_bytes());
5941
    write(root, "short.txt", b"short\n");
5942
    repo.commit("base", &[]).unwrap();
5943
    let (r1, _, _) = repo.checkpoint().unwrap();
5944
    let cp1 = crate::objects::Checkpoint::decode(
5945
        &repo.store().get_typed(&r1, ObjectType::Checkpoint).unwrap(),
5946
    )
5947
    .unwrap();
5948
    let graphs1 = repo.checkpoint_graph_blobs(&cp1).unwrap();
5949
    assert_eq!(graphs1.len(), 1, "only the long file's graph is a blob");
5950
5951
    // gc keeps the graph blob; fsck finds the checkpoint sound.
5952
    repo.gc(true).unwrap();
5953
    assert!(repo.store().has(&graphs1[0]));
5954
    let report = repo.fsck().unwrap();
5955
    assert_eq!(report.errors(), 0, "{:?}", report.problems);
5956
5957
    // Loading through the checkpoint equals a full load.
5958
    write(root, "short.txt", b"short, edited\n");
5959
    repo.commit("edit the short file", &[]).unwrap();
5960
    let heads = repo.bookmark_heads().unwrap();
5961
    let fast = repo.load_state(&heads).unwrap();
5962
    let full = repo.load_state_full(&heads).unwrap();
5963
    assert_eq!(fast.checkpoint_payload(), full.checkpoint_payload());
5964
5965
    // The next checkpoint shares the unchanged long file's graph.
5966
    let (r2, _, _) = repo.checkpoint().unwrap();
5967
    let cp2 = crate::objects::Checkpoint::decode(
5968
        &repo.store().get_typed(&r2, ObjectType::Checkpoint).unwrap(),
5969
    )
5970
    .unwrap();
5971
    assert_eq!(repo.checkpoint_graph_blobs(&cp2).unwrap(), graphs1);
5972
5973
    // A shallow clone's bundle carries the graph blob with the checkpoint.
5974
    let bundle = repo.checkpoint_bundle_for(&heads).unwrap();
5975
    assert!(bundle.objects.iter().any(|(t, body)| *t == ObjectType::Blob
5976
        && crate::hash::hash_object(ObjectType::Blob, body) == graphs1[0]));
5977
5978
    // A version 1 checkpoint written by an older oxy still loads.
5979
    let state = repo.load_state_full(&heads).unwrap();
5980
    let old = repo.store_blob(&state.checkpoint_payload()).unwrap();
5981
    let cp_old = crate::objects::Checkpoint {
5982
        heads: cp2.heads.clone(),
5983
        count: cp2.count,
5984
        payload: old,
5985
    };
5986
    let r_old = repo
5987
        .store()
5988
        .put(ObjectType::Checkpoint, &cp_old.encode())
5989
        .unwrap();
5990
    repo.install_checkpoint("main", &r_old).unwrap();
5991
    assert_eq!(
5992
        repo.load_state(&heads).unwrap().checkpoint_payload(),
5993
        full.checkpoint_payload()
5994
    );
5995
    assert_eq!(repo.fsck().unwrap().errors(), 0);
5996
5997
    // A lost graph blob fails the load loudly rather than dropping the
5998
    // file, and fsck reports it (a fresh repository, objects still loose).
5999
    let dir2 = tempfile::tempdir().unwrap();
6000
    let root2 = dir2.path();
6001
    let repo2 = Repo::init(root2).unwrap().with_home(root2.join("home"));
6002
    write(root2, "long.txt", long.as_bytes());
6003
    repo2.commit("base", &[]).unwrap();
6004
    let (r, _, _) = repo2.checkpoint().unwrap();
6005
    let cp = crate::objects::Checkpoint::decode(
6006
        &repo2.store().get_typed(&r, ObjectType::Checkpoint).unwrap(),
6007
    )
6008
    .unwrap();
6009
    let graph = repo2.checkpoint_graph_blobs(&cp).unwrap()[0];
6010
    repo2.store().remove_loose_for_test(&graph).unwrap();
6011
    assert!(repo2.load_state(&repo2.bookmark_heads().unwrap()).is_err());
6012
    assert!(repo2.fsck().unwrap().errors() > 0, "fsck reports it");
6013
}
6014
6015
/// A new repository has not stored the user's identity yet (that happens
6016
/// at the first signed change); looking it up falls back to the key
6017
/// directory, and a file there that does not hash to the key is refused.
6018
#[test]
6019
fn identity_is_found_in_the_key_directory_for_a_new_repository() {
6020
    hermetic();
6021
    let dir = tempfile::tempdir().unwrap();
6022
    let home = dir.path().join("home");
6023
    let mut first = Repo::init(&dir.path().join("a"))
6024
        .unwrap()
6025
        .with_home(home.clone());
6026
    let (key, _) = first
6027
        .create_identity("Ada", "[email protected]", IdentityScope::User)
6028
        .unwrap();
6029
    let fresh = Repo::init(&dir.path().join("b"))
6030
        .unwrap()
6031
        .with_home(home.clone());
6032
    assert!(!fresh.store().has(&key), "nothing stored yet");
6033
    let id = fresh.identity(&key).unwrap();
6034
    assert_eq!((id.name.as_str(), id.hash()), ("Ada", key));
6035
    // A key file that is not this identity is an error, not a wrong answer.
6036
    let keys = fresh.keys_dir.clone();
6037
    let (other, _) = first
6038
        .create_identity("Bob", "[email protected]", IdentityScope::User)
6039
        .unwrap();
6040
    fs::copy(
6041
        keys.join(format!("{}.identity", other.to_hex())),
6042
        keys.join(format!("{}.identity", key.to_hex())),
6043
    )
6044
    .unwrap();
6045
    assert!(fresh
6046
        .identity(&key)
6047
        .unwrap_err()
6048
        .to_string()
6049
        .contains("does not hold identity"));
6050
}
6051
6052
/// Status snapshots (spec §12.3): a text file whose stat matches the
6053
/// manifest, and whose base graph key is the one the manifest recorded it
6054
/// equal to, is neither read nor rendered; any edit, and any change to the
6055
/// file's graph in the base, brings it back.
6056
#[cfg(unix)]
6057
#[test]
6058
fn status_snapshots_skip_files_unchanged_since_the_manifest() {
6059
    use std::os::unix::fs::PermissionsExt;
6060
    hermetic();
6061
    let dir = tempfile::tempdir().unwrap();
6062
    let root = dir.path();
6063
    let repo = Repo::init(root).unwrap().with_home(root.join("home"));
6064
    for (p, c) in [("a.txt", "one\n"), ("b.txt", "bee\n"), ("d/c.txt", "sea\n")] {
6065
        write(root, p, c.as_bytes());
6066
    }
6067
    repo.commit("base", &[]).unwrap();
6068
    let age = |p: &str| {
6069
        let old = std::time::SystemTime::now() - std::time::Duration::from_secs(30);
6070
        fs::File::options()
6071
            .write(true)
6072
            .open(root.join(p))
6073
            .unwrap()
6074
            .set_modified(old)
6075
            .unwrap();
6076
    };
6077
    let lock = |p: &str, mode: u32| {
6078
        fs::set_permissions(root.join(p), fs::Permissions::from_mode(mode)).unwrap()
6079
    };
6080
    for p in ["a.txt", "b.txt", "d/c.txt"] {
6081
        age(p);
6082
    }
6083
    assert!(repo.snapshot("status").unwrap().statuses.is_empty());
6084
    let (_, _, m) = repo.read_manifest().unwrap().unwrap();
6085
    assert!(
6086
        m.entries.values().all(|e| e.graph.is_some()),
6087
        "keys recorded"
6088
    );
6089
6090
    // Unreadable files prove they are not read; the status snapshot does
6091
    // not render them either, and its base lacks their graphs.
6092
    lock("a.txt", 0o000);
6093
    lock("b.txt", 0o000);
6094
    let snap = repo.snapshot_status("status").unwrap();
6095
    assert!(!snap.changed && snap.statuses.is_empty());
6096
    assert_eq!(
6097
        snap.base_snapshot
6098
            .unrendered
6099
            .iter()
6100
            .cloned()
6101
            .collect::<Vec<_>>(),
6102
        vec!["a.txt", "b.txt", "d/c.txt"]
6103
    );
6104
    assert!(!snap.base.is_full());
6105
    assert!(!snap.base_snapshot.is_conflicted());
6106
    // A full snapshot does not read them either, but renders everything.
6107
    let full = repo.snapshot("status").unwrap();
6108
    assert!(full.statuses.is_empty() && full.base.is_full());
6109
    assert!(full.base_snapshot.unrendered.is_empty());
6110
    assert!(matches!(&full.base_snapshot.files["a.txt"].content,
6111
        FileContent::Text { bytes, .. } if bytes == b"one\n"));
6112
6113
    // An edit is seen; the file is rendered, the others still are not.
6114
    write(root, "d/c.txt", b"sea edited\n");
6115
    let snap = repo.snapshot_status("status").unwrap();
6116
    assert_eq!(
6117
        statuses(&snap),
6118
        vec![("d/c.txt".to_string(), ChangeStatus::Modified)]
6119
    );
6120
    assert!(!snap.base_snapshot.unrendered.contains("d/c.txt"));
6121
    // So is a mode change of an unread file.
6122
    lock("b.txt", 0o100);
6123
    assert_eq!(
6124
        statuses(&repo.snapshot_status("status").unwrap()),
6125
        vec![
6126
            ("b.txt".to_string(), ChangeStatus::ModeChanged),
6127
            ("d/c.txt".to_string(), ChangeStatus::Modified)
6128
        ]
6129
    );
6130
    lock("b.txt", 0o000);
6131
6132
    // Committing c.txt changes its graph in the base, not a.txt's: a.txt
6133
    // stays unread, c.txt is read once and then skipped too.
6134
    repo.commit_selection("edit c", &[], &Selection::Paths(vec!["d/c.txt".into()]))
6135
        .unwrap();
6136
    age("d/c.txt");
6137
    let snap = repo.snapshot_status("status").unwrap();
6138
    assert!(snap.statuses.is_empty(), "{:?}", snap.statuses);
6139
    assert!(snap.base_snapshot.unrendered.contains("a.txt"));
6140
    lock("d/c.txt", 0o000);
6141
    let snap = repo.snapshot_status("status").unwrap();
6142
    assert!(snap.statuses.is_empty());
6143
    assert!(snap.base_snapshot.unrendered.contains("d/c.txt"));
6144
    for p in ["a.txt", "b.txt", "d/c.txt"] {
6145
        lock(p, 0o644);
6146
    }
6147
}
6148
6149
/// Attributes decide how a file compares with the base, so a changed
6150
/// `.oxyattributes` makes every text file be compared again.
6151
#[cfg(unix)]
6152
#[test]
6153
fn a_changed_attributes_file_disables_skipping_unchanged_files() {
6154
    hermetic();
6155
    let dir = tempfile::tempdir().unwrap();
6156
    let root = dir.path();
6157
    let repo = Repo::init(root).unwrap().with_home(root.join("home"));
6158
    write(root, "a.txt", b"crlf\r\n");
6159
    repo.commit("base", &[]).unwrap();
6160
    let old = std::time::SystemTime::now() - std::time::Duration::from_secs(30);
6161
    fs::File::options()
6162
        .write(true)
6163
        .open(root.join("a.txt"))
6164
        .unwrap()
6165
        .set_modified(old)
6166
        .unwrap();
6167
    assert!(repo.snapshot_status("status").unwrap().statuses.is_empty());
6168
    assert!(repo
6169
        .snapshot_status("status")
6170
        .unwrap()
6171
        .base_snapshot
6172
        .unrendered
6173
        .contains("a.txt"));
6174
    // With eol=lf, a.txt as stored no longer equals the base.
6175
    write(root, ".oxyattributes", b"*.txt eol=lf\n");
6176
    let snap = repo.snapshot_status("status").unwrap();
6177
    assert_eq!(
6178
        statuses(&snap),
6179
        vec![
6180
            (".oxyattributes".to_string(), ChangeStatus::Added),
6181
            ("a.txt".to_string(), ChangeStatus::Modified)
6182
        ]
6183
    );
6184
}
6185
6186
/// Bookmarks with `/` in their names: pushing records their
6187
/// attestations, and checkpoints are kept for them, beside `feature`
6188
/// itself.
6189
#[test]
6190
fn bookmarks_with_slashes_push_and_checkpoint() {
6191
    hermetic();
6192
    let dir = tempfile::tempdir().unwrap();
6193
    let root = dir.path();
6194
    let origin = Repo::init(&root.join("origin")).unwrap();
6195
    let url = root.join("origin").to_string_lossy().to_string();
6196
    let mut repo = Repo::clone(&url, &root.join("r"))
6197
        .unwrap()
6198
        .with_home(root.join("home"));
6199
    // With an identity, pushes carry reference attestations: the case
6200
    // that failed, since the attestation is a file named after the bookmark.
6201
    repo.create_identity("Ada", "[email protected]", IdentityScope::Repo)
6202
        .unwrap();
6203
    let r = root.join("r");
6204
    write(&r, "a.txt", b"a\n");
6205
    let h_a = repo.commit("a", &[]).unwrap();
6206
    assert!(repo.push("origin", false).unwrap()[0].ok);
6207
    origin.refresh().unwrap();
6208
    repo.bookmark_create("feature", None).unwrap();
6209
    repo.bookmark_create("feature/x", None).unwrap();
6210
    repo.bookmark_switch("feature/x", false).unwrap();
6211
    write(&r, "b.txt", b"b\n");
6212
    let h_b = repo.commit("b", &[]).unwrap();
6213
    for name in ["feature", "feature/x"] {
6214
        let res = repo.push_bookmark("origin", name, false).unwrap();
6215
        origin.refresh().unwrap();
6216
        assert!(res[0].ok, "{name}: {res:?}");
6217
    }
6218
    assert_eq!(origin.resolve_heads("feature").unwrap(), vec![h_a]);
6219
    assert_eq!(
6220
        origin.resolve_heads("feature/x").unwrap(),
6221
        repo.resolve_heads("feature/x").unwrap()
6222
    );
6223
    assert!(origin.resolve_heads("feature/x").unwrap().contains(&h_b));
6224
    assert!(origin.latest_ref_attest("feature/x").unwrap().is_some());
6225
    assert!(origin.latest_ref_attest("feature").unwrap().is_some());
6226
6227
    // A checkpoint of feature/x is found again when loading its state.
6228
    let (cp, _, _) = repo.checkpoint().unwrap();
6229
    assert_eq!(repo.latest_checkpoint("feature/x").unwrap().unwrap().0, cp);
6230
    assert!(repo.latest_checkpoint("feature").unwrap().is_none());
6231
    let heads = repo.resolve_heads("feature/x").unwrap();
6232
    assert!(repo.load_state_checkpointed(&heads).unwrap().is_some());
6233
}
6234
6235
/// Deleting a bookmark on a remote (spec §16.4): attested like any update,
6236
/// never the remote's own bookmark, and a bookmark created again later is
6237
/// accepted although the deletion's attestation stays the latest.
6238
#[test]
6239
fn bookmarks_are_deleted_on_a_remote() {
6240
    hermetic();
6241
    let dir = tempfile::tempdir().unwrap();
6242
    let root = dir.path();
6243
    let origin = Repo::init(&root.join("origin")).unwrap();
6244
    let url = root.join("origin").to_string_lossy().to_string();
6245
    let mut repo = Repo::clone(&url, &root.join("r"))
6246
        .unwrap()
6247
        .with_home(root.join("home"));
6248
    repo.create_identity("Ada", "[email protected]", IdentityScope::Repo)
6249
        .unwrap();
6250
    let r = root.join("r");
6251
    write(&r, "a.txt", b"a\n");
6252
    repo.commit("a", &[]).unwrap();
6253
    assert!(repo.push("origin", false).unwrap()[0].ok);
6254
    origin.refresh().unwrap();
6255
    repo.bookmark_create("feature/x", None).unwrap();
6256
    assert!(repo.push_bookmark("origin", "feature/x", false).unwrap()[0].ok);
6257
    origin.refresh().unwrap();
6258
    assert!(origin.resolve_heads("feature/x").is_ok());
6259
6260
    let res = repo.push_delete("origin", "feature/x").unwrap();
6261
    origin.refresh().unwrap();
6262
    assert!(res[0].ok, "{res:?}");
6263
    assert!(!origin.view().unwrap().bookmarks.contains_key("feature/x"));
6264
    let (_, att) = origin.latest_ref_attest("feature/x").unwrap().unwrap();
6265
    assert!(
6266
        matches!(att.attest.body, AttestBody::Ref { new_state, .. } if new_state.is_zero()),
6267
        "the deletion is attested"
6268
    );
6269
    assert!(
6270
        repo.view().unwrap().bookmarks.contains_key("feature/x"),
6271
        "the local bookmark stays"
6272
    );
6273
    assert!(!repo
6274
        .view()
6275
        .unwrap()
6276
        .remotes
6277
        .get("origin")
6278
        .is_some_and(|m| m.contains_key("feature/x")));
6279
6280
    // Pushing it again creates it again, past the deletion's serial.
6281
    let res = repo.push_bookmark("origin", "feature/x", false).unwrap();
6282
    origin.refresh().unwrap();
6283
    assert!(res[0].ok, "{res:?}");
6284
    assert!(origin.view().unwrap().bookmarks.contains_key("feature/x"));
6285
6286
    // Nothing to delete, and never the remote's own bookmark.
6287
    assert!(repo.push_delete("origin", "nope").is_err());
6288
    let res = repo.push_delete("origin", "main").unwrap();
6289
    origin.refresh().unwrap();
6290
    assert!(
6291
        !res[0].ok && res[0].reason.contains("default bookmark"),
6292
        "{res:?}"
6293
    );
6294
    assert!(origin.view().unwrap().bookmarks.contains_key("main"));
6295
}
6296
6297
/// `bookmark switch --carry` (spec §10.1): uncommitted work goes along
6298
/// when the target has the same versions of the files it touches, and is
6299
/// refused, untouched, when it has others.
6300
#[test]
6301
fn switching_bookmarks_carries_uncommitted_work() {
6302
    hermetic();
6303
    let dir = tempfile::tempdir().unwrap();
6304
    let root = dir.path();
6305
    let mut repo = Repo::init(root).unwrap().with_home(root.join("home"));
6306
    write(root, "a.txt", b"a\n");
6307
    write(root, "b.txt", b"b\n");
6308
    write(root, "gone.txt", b"gone\n");
6309
    repo.commit("base", &[]).unwrap();
6310
    repo.bookmark_create("feature", None).unwrap();
6311
    // Started on main, belongs on feature: edit, add, remove.
6312
    write(root, "a.txt", b"a\nmore\n");
6313
    write(root, "new.txt", b"new\n");
6314
    fs::remove_file(root.join("gone.txt")).unwrap();
6315
    let (_, carried) = repo.bookmark_switch_carry("feature").unwrap();
6316
    assert_eq!(carried, vec!["a.txt", "gone.txt", "new.txt"]);
6317
    assert_eq!(repo.config.bookmark, "feature");
6318
    assert_eq!(fs::read(root.join("a.txt")).unwrap(), b"a\nmore\n");
6319
    assert_eq!(fs::read(root.join("new.txt")).unwrap(), b"new\n");
6320
    assert!(!root.join("gone.txt").exists());
6321
    let snap = repo.snapshot("status").unwrap();
6322
    assert_eq!(
6323
        statuses(&snap),
6324
        vec![
6325
            ("a.txt".to_string(), ChangeStatus::Modified),
6326
            ("gone.txt".to_string(), ChangeStatus::Removed),
6327
            ("new.txt".to_string(), ChangeStatus::Added)
6328
        ]
6329
    );
6330
    repo.commit("the work", &[]).unwrap();
6331
    assert!(repo.resolve_heads("main").unwrap().len() == 1);
6332
6333
    // main moves b.txt on; work on feature touching b.txt cannot follow.
6334
    repo.bookmark_switch("main", false).unwrap();
6335
    write(root, "b.txt", b"b on main\n");
6336
    repo.commit("b on main", &[]).unwrap();
6337
    repo.bookmark_switch("feature", false).unwrap();
6338
    write(root, "b.txt", b"b edited\n");
6339
    let err = repo.bookmark_switch_carry("main").unwrap_err().to_string();
6340
    assert!(err.contains("b.txt") && err.contains("--discard"), "{err}");
6341
    assert_eq!(repo.config.bookmark, "feature", "nothing happened");
6342
    assert_eq!(fs::read(root.join("b.txt")).unwrap(), b"b edited\n");
6343
}
6344
6345
/// Merging and checking out (feedback 3): a working copy without changes
6346
/// follows a merge whichever state it sat on; a refused checkout names
6347
/// what is in the way; `checkout --carry` takes the work along.
6348
#[test]
6349
fn merges_move_clean_working_copies_and_checkouts_say_what_blocks_them() {
6350
    hermetic();
6351
    let dir = tempfile::tempdir().unwrap();
6352
    let root = dir.path();
6353
    let mut repo = Repo::init(root).unwrap().with_home(root.join("home"));
6354
    write(root, "a.txt", b"a\n");
6355
    let h1 = repo.commit("a", &[]).unwrap();
6356
    write(root, "b.txt", b"b\n");
6357
    repo.commit("b", &[]).unwrap();
6358
    repo.bookmark_create("feature", None).unwrap();
6359
    repo.bookmark_switch("feature", false).unwrap();
6360
    write(root, "c.txt", b"c\n");
6361
    repo.commit("c on feature", &[]).unwrap();
6362
    repo.bookmark_switch("main", false).unwrap();
6363
    // The working copy sits on an older state than main's heads.
6364
    repo.checkout(&[h1], false, "checkout").unwrap();
6365
    assert!(!root.join("b.txt").exists());
6366
    let m = repo.merge("feature").unwrap();
6367
    assert!(m.checked_out, "a clean working copy follows the merge");
6368
    for f in ["a.txt", "b.txt", "c.txt"] {
6369
        assert!(root.join(f).exists(), "{f}");
6370
    }
6371
6372
    // A refusal says which paths are in the way and what to do.
6373
    fs::remove_file(root.join("b.txt")).unwrap();
6374
    write(root, "a.txt", b"a edited\n");
6375
    let err = repo
6376
        .checkout(&[h1], false, "checkout")
6377
        .unwrap_err()
6378
        .to_string();
6379
    assert!(
6380
        err.contains("modified a.txt") && err.contains("removed b.txt") && err.contains("--carry"),
6381
        "{err}"
6382
    );
6383
    // --carry takes them along: h1 has a.txt as the base has it, and the
6384
    // removed b.txt is already as h1 has it (none), so that is no conflict
6385
    // either (oxygen#100).
6386
    let (_, carried) = repo
6387
        .checkout_carry(&[h1], "the first change", "checkout")
6388
        .unwrap();
6389
    assert_eq!(carried, vec!["a.txt"]);
6390
    assert_eq!(fs::read(root.join("a.txt")).unwrap(), b"a edited\n");
6391
    assert!(!root.join("b.txt").exists(), "h1 has no b.txt");
6392
}
6393
6394
/// Doctor and subrepos before the first commit (feedback 5 and 8): a
6395
/// user identity not stored in a new repository yet is fine while its
6396
/// secret key is there; an added subrepo is listed as not committed yet.
6397
#[test]
6398
fn a_new_repository_is_healthy_before_its_first_commit() {
6399
    hermetic();
6400
    let dir = tempfile::tempdir().unwrap();
6401
    let root = dir.path();
6402
    let home = root.join("home");
6403
    let mut first = Repo::init(&root.join("first"))
6404
        .unwrap()
6405
        .with_home(home.clone());
6406
    let (key, _) = first
6407
        .create_identity("Ada", "[email protected]", IdentityScope::User)
6408
        .unwrap();
6409
    let repo = Repo::init(&root.join("second"))
6410
        .unwrap()
6411
        .with_home(home.clone());
6412
    // Only the secret key: no identity object anywhere this repository sees.
6413
    let keys = repo.keys_dir.clone();
6414
    let _ = fs::remove_file(keys.join(format!("{}.identity", key.to_hex())));
6415
    assert!(keys.join(format!("{}.secret", key.to_hex())).is_file());
6416
    let r = repo.doctor(true);
6417
    let id = r.checks.iter().find(|c| c.area == "identity").unwrap();
6418
    assert_eq!(id.health, Health::Ok, "{}", id.message);
6419
    assert!(id.message.contains("first signed change"), "{}", id.message);
6420
6421
    // A subrepo added and not committed yet is listed, pinned where it is.
6422
    let lib = root.join("lib");
6423
    let l = Repo::init(&lib).unwrap().with_home(home.clone());
6424
    write(&lib, "x.txt", b"x\n");
6425
    l.commit("x", &[]).unwrap();
6426
    let second = root.join("second");
6427
    write(&second, "a.txt", b"a\n");
6428
    repo.submodule_add(&lib.to_string_lossy(), "deps/lib", None)
6429
        .unwrap();
6430
    let subs = repo.subrepos().unwrap();
6431
    assert_eq!(subs.len(), 1);
6432
    assert_eq!(
6433
        (subs[0].path.as_str(), subs[0].committed),
6434
        ("deps/lib", false)
6435
    );
6436
    assert_eq!(subs[0].actual.as_ref(), Some(&subs[0].pin));
6437
    repo.commit("add lib", &[]).unwrap();
6438
    let subs = repo.subrepos().unwrap();
6439
    assert!(subs[0].committed, "committed now");
6440
}
6441
6442
/// Commit, diff, hunks and discard use the partial snapshot: a file
6443
/// unchanged since the manifest is neither read nor rendered, and showing
6444
/// a change renders only what it edits, the same as from a full base.
6445
#[cfg(unix)]
6446
#[test]
6447
fn commits_and_diffs_leave_unchanged_files_alone() {
6448
    use std::os::unix::fs::PermissionsExt;
6449
    hermetic();
6450
    let dir = tempfile::tempdir().unwrap();
6451
    let root = dir.path();
6452
    let repo = Repo::init(root).unwrap().with_home(root.join("home"));
6453
    write(root, "big.txt", b"lots\nof\nlines\n");
6454
    write(root, "a.txt", b"one\ntwo\n");
6455
    repo.commit("base", &[]).unwrap();
6456
    let old = std::time::SystemTime::now() - std::time::Duration::from_secs(30);
6457
    for f in ["big.txt", "a.txt"] {
6458
        fs::File::options()
6459
            .write(true)
6460
            .open(root.join(f))
6461
            .unwrap()
6462
            .set_modified(old)
6463
            .unwrap();
6464
    }
6465
    assert!(repo.snapshot_status("status").unwrap().statuses.is_empty());
6466
    // big.txt cannot be read at all from here on.
6467
    fs::set_permissions(root.join("big.txt"), fs::Permissions::from_mode(0o000)).unwrap();
6468
6469
    write(root, "a.txt", b"one\nTWO\nthree\n");
6470
    let diff = repo.diff_files(None).unwrap();
6471
    assert_eq!(
6472
        diff.iter().map(|f| f.path.as_str()).collect::<Vec<_>>(),
6473
        ["a.txt"]
6474
    );
6475
    let (_, hunks) = repo.hunks().unwrap();
6476
    assert!(!hunks.is_empty() && hunks.iter().all(|h| h.path == "a.txt"));
6477
    let h = repo.commit("edit a", &[]).unwrap();
6478
6479
    // Showing the change needs only a.txt's graph, and renders as a full base does.
6480
    let c = repo.store().get_change(&h).unwrap();
6481
    let full = repo.load_state(&c.deps).unwrap();
6482
    let want = render_change(&c, &full, &full.materialize());
6483
    assert_eq!(repo.describe_change(&h).unwrap(), want);
6484
    let (base, snap) = repo.change_base(&c).unwrap();
6485
    assert!(!base.is_full() && snap.unrendered.contains("big.txt"));
6486
6487
    // Discarding works the same way.
6488
    write(root, "a.txt", b"scratch\n");
6489
    assert_eq!(repo.discard(&["a.txt".into()]).unwrap(), 1);
6490
    assert_eq!(fs::read(root.join("a.txt")).unwrap(), b"one\nTWO\nthree\n");
6491
    fs::set_permissions(root.join("big.txt"), fs::Permissions::from_mode(0o644)).unwrap();
6492
}
6493
6494
/// A replace conflict (spec §9.3) is settled by a change that writes one
6495
/// candidate, or new bytes, at the path when the caller names it; a plain
6496
/// snapshot of a checkout never settles it on its own.
6497
#[test]
6498
fn replace_conflicts_are_settled_when_asked() {
6499
    hermetic();
6500
    let dir = tempfile::tempdir().unwrap();
6501
    let root = dir.path();
6502
    let mut repo = Repo::init(root).unwrap().with_home(root.join("home"));
6503
    let blob = |n: u8| {
6504
        let mut v = vec![0u8; 64];
6505
        v[1] = n;
6506
        v
6507
    };
6508
    write(root, "img.bin", &blob(1));
6509
    repo.commit("add img", &[]).unwrap();
6510
    repo.bookmark_create("other", None).unwrap();
6511
    write(root, "img.bin", &blob(2));
6512
    repo.commit("img two", &[]).unwrap();
6513
    repo.bookmark_switch("other", false).unwrap();
6514
    write(root, "img.bin", &blob(3));
6515
    repo.commit("img three", &[]).unwrap();
6516
    repo.bookmark_switch("main", false).unwrap();
6517
    repo.merge("other").unwrap();
6518
    let heads = repo.bookmark_heads().unwrap();
6519
    let merged = repo.load_state(&heads).unwrap().materialize();
6520
    assert!(
6521
        matches!(&merged.files["img.bin"].content, FileContent::Opaque { blobs } if blobs.len() == 2),
6522
        "a replace conflict"
6523
    );
6524
    // A snapshot of the checkout records nothing.
6525
    assert!(repo
6526
        .snapshot("status")
6527
        .unwrap()
6528
        .statuses
6529
        .iter()
6530
        .all(|s| s.path != "img.bin"));
6531
6532
    // Keeping candidate 3 settles it.
6533
    let author = repo.author();
6534
    let edits = [FileEdit {
6535
        path: "img.bin".into(),
6536
        content: Some(blob(3)),
6537
    }];
6538
    let c = repo
6539
        .build_change(&heads, &edits, "keep three", author)
6540
        .unwrap();
6541
    assert_eq!(c.kind, ChangeKind::Resolution);
6542
    let mut st = repo.load_state(&heads).unwrap();
6543
    for d in &c.deps {
6544
        assert!(st.contains(d));
6545
    }
6546
    assert!(
6547
        heads.iter().all(|h| c.deps.contains(h)),
6548
        "depends on both contributors"
6549
    );
6550
    st.add(c).unwrap();
6551
    let after = st.materialize();
6552
    assert!(!after.is_conflicted());
6553
    assert_eq!(
6554
        after.files["img.bin"].content,
6555
        FileContent::Opaque {
6556
            blobs: vec![Repo::blob_ref(&blob(3))]
6557
        }
6558
    );
6559
6560
    // New bytes settle it too.
6561
    let edits = [FileEdit {
6562
        path: "img.bin".into(),
6563
        content: Some(blob(9)),
6564
    }];
6565
    let c = repo.build_change(&heads, &edits, "new", author).unwrap();
6566
    let mut st = repo.load_state(&heads).unwrap();
6567
    st.add(c).unwrap();
6568
    assert_eq!(
6569
        st.materialize().files["img.bin"].content,
6570
        FileContent::Opaque {
6571
            blobs: vec![Repo::blob_ref(&blob(9))]
6572
        }
6573
    );
6574
}
6575
6576
/// The history of a range of lines (spec §27): the changes that wrote
6577
/// or deleted its atoms, or deleted atoms from between them; edits outside
6578
/// the range and changes the range's lines survived are not in it.
6579
#[test]
6580
fn line_ranges_have_exact_histories() {
6581
    hermetic();
6582
    let dir = tempfile::tempdir().unwrap();
6583
    let root = dir.path();
6584
    let repo = Repo::init(root).unwrap().with_home(root.join("home"));
6585
    write(root, "f.rs", b"use x;\nfn a() {\n  one();\n  two();\n}\n");
6586
    let base = repo.commit("add f", &[]).unwrap();
6587
    write(root, "f.rs", b"use y;\nfn a() {\n  one();\n  two();\n}\n");
6588
    let outside = repo.commit("change the import", &[]).unwrap();
6589
    write(root, "f.rs", b"use y;\nfn a() {\n  ONE();\n  two();\n}\n");
6590
    let inside = repo.commit("edit a line of a", &[]).unwrap();
6591
    write(root, "f.rs", b"use y;\nfn a() {\n  ONE();\n}\n");
6592
    let deleted = repo.commit("delete a line of a", &[]).unwrap();
6593
    write(root, "f.rs", b"use y;\nfn a() {\n  ONE();\n}\nfn b() {}\n");
6594
    let after = repo.commit("add b after a", &[]).unwrap();
6595
    let heads = repo.bookmark_heads().unwrap();
6596
6597
    // Lines 2..4 are `fn a() {`, `ONE();`, `}` now.
6598
    let hist: Vec<ChangeHash> = repo
6599
        .line_history(&heads, "f.rs", 2, 4)
6600
        .unwrap()
6601
        .iter()
6602
        .map(|e| e.hash)
6603
        .collect();
6604
    for (h, what) in [
6605
        (base, "wrote it"),
6606
        (inside, "edited a line"),
6607
        (deleted, "deleted a line from inside"),
6608
    ] {
6609
        assert!(hist.contains(&h), "{what}");
6610
    }
6611
    for (h, what) in [(outside, "an edit above"), (after, "an addition below")] {
6612
        assert!(!hist.contains(&h), "{what}");
6613
    }
6614
    assert_eq!(hist[0], deleted, "newest first");
6615
    // One line: only what touched it.
6616
    let one: Vec<ChangeHash> = repo
6617
        .line_history(&heads, "f.rs", 1, 1)
6618
        .unwrap()
6619
        .iter()
6620
        .map(|e| e.hash)
6621
        .collect();
6622
    assert!(one.contains(&outside) && !one.contains(&inside));
6623
    assert!(repo.line_history(&heads, "f.rs", 3, 9).is_err());
6624
    assert!(repo.line_history(&heads, "f.rs", 0, 1).is_err());
6625
    assert!(repo.line_history(&heads, "nope.rs", 1, 1).is_err());
6626
}
6627
6628
#[test]
6629
fn receipts_are_kept_with_their_state_and_verified() {
6630
    use crate::receipt::{Receipt, SignedReceipt};
6631
    hermetic();
6632
    let dir = tempfile::tempdir().unwrap();
6633
    let root = dir.path();
6634
    let repo = Repo::init(root).unwrap().with_home(root.join("home"));
6635
    write(root, "a.txt", b"1\n");
6636
    repo.commit("A", &[]).unwrap();
6637
    let heads = repo.bookmark_heads().unwrap();
6638
    let state = repo
6639
        .store()
6640
        .put_state(&StateObject::new(heads.clone()))
6641
        .unwrap();
6642
    let out = repo.store_blob(b"built\n").unwrap();
6643
    let receipt = Receipt {
6644
        job_name: "build".into(),
6645
        pipeline_hash: ObjectRef([1; 32]),
6646
        scope_tree_hash: ObjectRef([2; 32]),
6647
        inputs: vec![],
6648
        environment: ObjectRef([3; 32]),
6649
        outputs: vec![out],
6650
        exit_code: 0,
6651
        duration_ms: 42,
6652
    };
6653
    let sk = SecretKey::generate();
6654
    let runner = sk.identity("earth-1", "runner@earth", 1);
6655
    let sr = SignedReceipt::sign(
6656
        receipt.clone(),
6657
        repo.id().unwrap(),
6658
        state,
6659
        "demo#1",
6660
        &runner,
6661
        &sk,
6662
    );
6663
6664
    let r = repo.add_receipt(&sr).unwrap();
6665
    let found = repo.receipts(&heads).unwrap();
6666
    assert_eq!(found.len(), 1);
6667
    assert_eq!(found[0].attest, r);
6668
    assert_eq!(found[0].signed, sr);
6669
    assert!(found[0].problem.is_none() && !found[0].revoked);
6670
    assert!(repo.receipts(&[ObjectRef([5; 32])]).unwrap().is_empty());
6671
6672
    // Another repository's receipt, or a forged one, is refused.
6673
    let elsewhere = SignedReceipt::sign(receipt.clone(), [0; 16], state, "x", &runner, &sk);
6674
    assert!(repo
6675
        .add_receipt(&elsewhere)
6676
        .unwrap_err()
6677
        .to_string()
6678
        .contains("another repository"));
6679
    let mut forged = sr.clone();
6680
    forged.receipt.exit_code = 1;
6681
    assert!(repo
6682
        .add_receipt(&forged)
6683
        .unwrap_err()
6684
        .to_string()
6685
        .contains("does not verify"));
6686
6687
    // A receipt signed by a short-lived key keeps its certificate and the
6688
    // issuer's identity, and reads back with them (oxygenhub#241).
6689
    let hub_sk = SecretKey::generate();
6690
    let hub = hub_sk.identity("oxygenhub.io", "[email protected]", 1);
6691
    let job_sk = SecretKey::generate();
6692
    let job = job_sk.identity("job 2 test", "[email protected]", 1);
6693
    let mut test_receipt = receipt.clone();
6694
    test_receipt.job_name = "test".into();
6695
    let plain = SignedReceipt::sign(
6696
        test_receipt,
6697
        repo.id().unwrap(),
6698
        state,
6699
        "demo#2",
6700
        &job,
6701
        &job_sk,
6702
    );
6703
    let now = plain.attest.hlc.wall_ms;
6704
    let cert = crate::cert::SignedCertificate::sign(
6705
        crate::cert::Certificate {
6706
            key: job.clone(),
6707
            issuer: hub.hash(),
6708
            subject: "repo:andy/demo:bookmark:main".into(),
6709
            claims: vec![],
6710
            scope: crate::identity::Scope::SEAL,
6711
            not_before: now - 1_000,
6712
            expires: now + 600_000,
6713
            grant: None,
6714
        },
6715
        &hub,
6716
        &hub_sk,
6717
    );
6718
    let certified = plain.with_certificate(cert, hub.clone());
6719
    repo.add_receipt(&certified).unwrap();
6720
    let found = repo.receipts(&heads).unwrap();
6721
    let got = found
6722
        .iter()
6723
        .find(|i| i.signed.receipt.job_name == "test")
6724
        .unwrap();
6725
    assert_eq!(got.signed, certified);
6726
    assert!(got.problem.is_none(), "{:?}", got.problem);
6727
6728
    // gc keeps the receipts, their runners, the certificate and its issuer,
6729
    // and the output while the state lives.
6730
    repo.gc(true).unwrap();
6731
    let found = repo.receipts(&heads).unwrap();
6732
    assert_eq!(found.len(), 2);
6733
    let got = found
6734
        .iter()
6735
        .find(|i| i.signed.receipt.job_name == "test")
6736
        .unwrap();
6737
    assert_eq!(got.signed, certified, "the certificate survives gc");
6738
    assert!(got.problem.is_none());
6739
    assert_eq!(repo.read_blob(&out).unwrap(), b"built\n");
6740
    assert!(repo.fsck().unwrap().problems.is_empty());
6741
}
6742
6743
#[test]
6744
fn approvals_are_kept_with_their_state_and_survive_gc() {
6745
    hermetic();
6746
    let dir = tempfile::tempdir().unwrap();
6747
    let root = dir.path();
6748
    let repo = Repo::init(root).unwrap().with_home(root.join("home"));
6749
    write(root, "a.txt", b"1\n");
6750
    repo.commit("A", &[]).unwrap();
6751
    let heads = repo.bookmark_heads().unwrap();
6752
    let state = repo.store().put_state(&StateObject::new(heads)).unwrap();
6753
    let plan = repo.store_blob(b"the reviewed plan\n").unwrap();
6754
    let sk = SecretKey::generate();
6755
    let andy = sk.identity("Andy", "[email protected]", 1);
6756
    let statement = crate::approval::Statement {
6757
        repo: repo.id().unwrap(),
6758
        run: "https://hub.example/andy/infra/flow/8".into(),
6759
        job: "apply".into(),
6760
        job_hash: ObjectRef([1; 32]),
6761
        state,
6762
        inputs: vec![plan],
6763
        environment: "prod".into(),
6764
        approve: true,
6765
    };
6766
    let sa = crate::approval::SignedApproval::sign(&statement, &andy, &sk);
6767
    let r = repo.add_approval(&sa).unwrap();
6768
    assert_eq!(repo.store().approvals_for(&state).unwrap(), vec![r]);
6769
    // Another repository's approval, or a changed one, is refused.
6770
    let elsewhere = crate::approval::SignedApproval::sign(
6771
        &crate::approval::Statement {
6772
            repo: [0; 16],
6773
            ..statement.clone()
6774
        },
6775
        &andy,
6776
        &sk,
6777
    );
6778
    assert!(repo
6779
        .add_approval(&elsewhere)
6780
        .unwrap_err()
6781
        .to_string()
6782
        .contains("another repository"));
6783
    let mut forged = sa.clone();
6784
    if let AttestBody::Approval { environment, .. } = &mut forged.attest.body {
6785
        *environment = "dev".into();
6786
    }
6787
    assert!(repo
6788
        .add_approval(&forged)
6789
        .unwrap_err()
6790
        .to_string()
6791
        .contains("does not verify"));
6792
    // gc keeps it, its signature and its signer while the state lives.
6793
    repo.gc(true).unwrap();
6794
    assert_eq!(repo.store().approvals_for(&state).unwrap(), vec![r]);
6795
    assert_eq!(repo.store().get_attest(&r).unwrap(), sa.attest);
6796
    assert_eq!(repo.store().signatures(&r).unwrap(), sa.sigs);
6797
    assert!(repo.fsck().unwrap().problems.is_empty());
6798
}
6799
6800
#[test]
6801
fn status_leaves_an_unchanged_manifest_alone() {
6802
    hermetic();
6803
    let dir = tempfile::tempdir().unwrap();
6804
    let root = dir.path();
6805
    let repo = Repo::init(root).unwrap().with_home(root.join("home"));
6806
    write(root, "a.txt", b"1\n");
6807
    write(root, "b.txt", b"2\n");
6808
    repo.commit("A", &[]).unwrap();
6809
    // Files last touched well outside the racy window.
6810
    let old = std::time::SystemTime::now() - std::time::Duration::from_secs(60);
6811
    for f in ["a.txt", "b.txt"] {
6812
        fs::File::options()
6813
            .write(true)
6814
            .open(root.join(f))
6815
            .unwrap()
6816
            .set_modified(old)
6817
            .unwrap();
6818
    }
6819
    repo.snapshot_status("status").unwrap();
6820
    let path = repo.manifest_path();
6821
    let first = fs::read(&path).unwrap();
6822
    repo.snapshot_status("status").unwrap();
6823
    assert_eq!(
6824
        fs::read(&path).unwrap(),
6825
        first,
6826
        "an unchanged tree does not rewrite the manifest"
6827
    );
6828
    // A change rewrites it.
6829
    write(root, "a.txt", b"1\n2\n");
6830
    repo.snapshot_status("status").unwrap();
6831
    assert_ne!(fs::read(&path).unwrap(), first);
6832
}
6833
6834
#[test]
6835
fn large_text_files_travel_and_survive_gc_as_text_blobs() {
6836
    hermetic();
6837
    let dir = tempfile::tempdir().unwrap();
6838
    let root = dir.path();
6839
    let origin_path = root.join("origin");
6840
    Repo::init(&origin_path).unwrap();
6841
    let origin_url = origin_path.to_string_lossy().to_string();
6842
    let a = Repo::clone(&origin_url, &root.join("a")).unwrap();
6843
    let big: String = (0..5000).map(|i| format!("line {i}\n")).collect();
6844
    write(&root.join("a"), "big.txt", big.as_bytes());
6845
    write(&root.join("a"), "small.txt", b"small\n");
6846
    let h1 = a.commit("large", &[]).unwrap();
6847
    let (_, body) = a.store().get(&h1).unwrap();
6848
    assert!(body.len() < 2048, "the change is {} bytes", body.len());
6849
    assert!(a.push("origin", false).unwrap()[0].ok);
6850
6851
    // A clone reads the text from the blobs that came with the change.
6852
    let b = Repo::clone(&origin_url, &root.join("b")).unwrap();
6853
    assert_eq!(fs::read(root.join("b/big.txt")).unwrap(), big.as_bytes());
6854
    // An edit in the middle of the stored insert is an ordinary change.
6855
    let edited = big.replace("line 2500\n", "line 2500, edited\n");
6856
    write(&root.join("b"), "big.txt", edited.as_bytes());
6857
    let h2 = b.commit("edit", &[]).unwrap();
6858
    assert!(b.store().get_change(&h2).unwrap().edits.len() <= 2);
6859
    assert!(b.push("origin", false).unwrap()[0].ok);
6860
    assert!(a.pull("origin").unwrap().checked_out);
6861
    assert_eq!(fs::read(root.join("a/big.txt")).unwrap(), edited.as_bytes());
6862
    assert_eq!(
6863
        a.fsck().unwrap().errors(),
6864
        0,
6865
        "{:?}",
6866
        a.fsck().unwrap().problems
6867
    );
6868
6869
    // With zero retention gc keeps the text blobs of every kept change.
6870
    let mut a = Repo::open(&root.join("a")).unwrap();
6871
    a.config.set("core.op-retention", "0").unwrap();
6872
    a.save_config().unwrap();
6873
    let a = Repo::open(&root.join("a")).unwrap();
6874
    a.gc(true).unwrap();
6875
    let a = Repo::open(&root.join("a")).unwrap();
6876
    assert_eq!(a.store().get_change(&h1).unwrap().message, "large");
6877
    assert_eq!(
6878
        a.fsck().unwrap().errors(),
6879
        0,
6880
        "{:?}",
6881
        a.fsck().unwrap().problems
6882
    );
6883
    // And a clone of the packed repository reads them from its packs.
6884
    let c = Repo::clone(&root.join("a").to_string_lossy(), &root.join("c")).unwrap();
6885
    assert_eq!(fs::read(root.join("c/big.txt")).unwrap(), edited.as_bytes());
6886
    drop(c);
6887
}
6888
6889
#[test]
6890
fn operations_that_both_replace_a_working_copy_are_not_merged() {
6891
    hermetic();
6892
    let dir = tempfile::tempdir().unwrap();
6893
    let root = dir.path();
6894
    let repo = Repo::init(root).unwrap();
6895
    write(root, "a.txt", b"a\n");
6896
    let a = repo.commit("a", &[]).unwrap();
6897
    write(root, "b.txt", b"b\n");
6898
    repo.commit("b", &[]).unwrap();
6899
    let (x, op) = repo.head_op().unwrap();
6900
    let ws = *op.view.workspaces.keys().next().unwrap();
6901
    let mut one = op.view.clone();
6902
    one.workspaces.insert(ws, a);
6903
    let mut two = op.view.clone();
6904
    two.workspaces.insert(ws, ObjectRef([7; 32]));
6905
    let first = repo.record_op(&[x], "one", one).unwrap();
6906
    let e = repo.record_op(&[x], "two", two).unwrap_err();
6907
    assert!(
6908
        e.to_string()
6909
            .contains("changed this working copy at the same time"),
6910
        "{e}"
6911
    );
6912
    assert_eq!(
6913
        repo.head_op().unwrap().0,
6914
        first,
6915
        "the second is not recorded"
6916
    );
6917
}
6918
6919
/// Metalgear, 2026-09-29 (oxygen#36): a status run while a bookmark switch
6920
/// rewrote the working copy recorded the half-written files as edits, and
6921
/// its view replaced the switch's.
6922
#[test]
6923
fn a_snapshot_during_a_switch_never_records_the_switch_as_edits() {
6924
    hermetic();
6925
    let dir = tempfile::tempdir().unwrap();
6926
    let root = dir.path().to_path_buf();
6927
    let mut repo = Repo::init(&root).unwrap();
6928
    write(&root, "keep.txt", b"keep\n");
6929
    repo.commit("base", &[]).unwrap();
6930
    repo.bookmark_create("small", None).unwrap();
6931
    for i in 0..300 {
6932
        write(
6933
            &root,
6934
            &format!("many/f{i}.txt"),
6935
            format!("file {i}\n").as_bytes(),
6936
        );
6937
    }
6938
    repo.commit("many", &[]).unwrap();
6939
    let stop = std::sync::Arc::new(std::sync::atomic::AtomicBool::new(false));
6940
    let watcher = {
6941
        let (root, stop) = (root.clone(), stop.clone());
6942
        std::thread::spawn(move || {
6943
            let r = Repo::open(&root).unwrap();
6944
            let mut ran = 0;
6945
            while !stop.load(std::sync::atomic::Ordering::Relaxed) {
6946
                if r.snapshot_status("oxy status").is_ok() {
6947
                    ran += 1;
6948
                }
6949
            }
6950
            ran
6951
        })
6952
    };
6953
    for i in 0..20 {
6954
        let to = if i % 2 == 0 { "small" } else { "main" };
6955
        repo.bookmark_switch(to, false).unwrap();
6956
    }
6957
    stop.store(true, std::sync::atomic::Ordering::Relaxed);
6958
    assert!(watcher.join().unwrap() > 0, "the watcher snapshotted");
6959
    // Back on main, clean, with every file where main has it.
6960
    let repo = Repo::open(&root).unwrap();
6961
    let s = repo.snapshot_status("oxy status").unwrap();
6962
    assert!(s.statuses.is_empty(), "{:?}", statuses(&s));
6963
    assert!(s.wc.edits.is_empty() && s.wc.tree_ops.is_empty());
6964
    assert_eq!(s.wc.deps, repo.bookmark_heads().unwrap());
6965
    assert!(root.join("many/f299.txt").exists());
6966
}
6967
6968
/// Metalgear, 2026-09-29 (oxygen#38): a parent's `bookmark switch --carry`
6969
/// put a subrepo that was ahead of its pin back at the pin and moved the
6970
/// subrepo's own bookmark backwards.
6971
#[test]
6972
fn a_parent_switch_with_carry_leaves_a_subrepo_ahead_of_its_pin_alone() {
6973
    hermetic();
6974
    let dir = tempfile::tempdir().unwrap();
6975
    let root = dir.path();
6976
    Repo::init(&root.join("lib-origin")).unwrap();
6977
    let lib_url = root.join("lib-origin").to_string_lossy().to_string();
6978
    let lib = Repo::clone(&lib_url, &root.join("lib")).unwrap();
6979
    write(&root.join("lib"), "lib.txt", b"v1\n");
6980
    lib.commit("lib v1", &[]).unwrap();
6981
    assert!(lib.push("origin", false).unwrap()[0].ok);
6982
6983
    let app_dir = root.join("app");
6984
    let mut app = Repo::init(&app_dir).unwrap();
6985
    write(&app_dir, "main.txt", b"app\n");
6986
    app.submodule_add(&lib_url, "libs/lib", None).unwrap();
6987
    app.commit("app with lib", &[]).unwrap();
6988
    app.bookmark_create("feature", None).unwrap();
6989
6990
    // New work in the subrepo, not yet pinned by the parent.
6991
    let nested_dir = app_dir.join("libs/lib");
6992
    let nested = Repo::open(&nested_dir).unwrap();
6993
    write(&nested_dir, "new.txt", b"new\n");
6994
    let l2 = nested.commit("lib: new file", &[]).unwrap();
6995
    drop(nested);
6996
6997
    let (_, carried) = app.bookmark_switch_carry("feature").unwrap();
6998
    assert!(carried.contains(&"libs/lib".to_string()), "{carried:?}");
6999
    let nested = Repo::open(&nested_dir).unwrap();
7000
    assert!(
7001
        nested.bookmark_heads().unwrap().contains(&l2),
7002
        "its bookmark kept its work"
7003
    );
7004
    assert!(nested_dir.join("new.txt").exists(), "and its files");
7005
    let s = app.snapshot("status").unwrap();
7006
    assert_eq!(
7007
        statuses(&s),
7008
        vec![("libs/lib".to_string(), ChangeStatus::Modified)]
7009
    );
7010
}
7011
7012
/// oxygen#29 (metalgear, rstar-api): after a proposal landed on the hub,
7013
/// moving `main` to a change this clone had pushed on another bookmark,
7014
/// the first `pull` said "Already up to date" while `main` was behind.
7015
#[test]
7016
fn pull_takes_a_remote_move_to_changes_already_here() {
7017
    hermetic();
7018
    let dir = tempfile::tempdir().unwrap();
7019
    let root = dir.path();
7020
    let origin_path = root.join("origin");
7021
    let origin = Repo::init(&origin_path).unwrap();
7022
    let url = origin_path.to_string_lossy().to_string();
7023
    let mut b = Repo::clone(&url, &root.join("b")).unwrap();
7024
    write(&root.join("b"), "base.txt", b"base\n");
7025
    b.commit("base", &[]).unwrap();
7026
    assert!(b.push("origin", false).unwrap()[0].ok);
7027
    origin.refresh().unwrap();
7028
7029
    // A feature bookmark with one change, pushed.
7030
    b.bookmark_create("feat", None).unwrap();
7031
    b.bookmark_switch("feat", false).unwrap();
7032
    write(&root.join("b"), "x.txt", b"x\n");
7033
    let x = b.commit("x", &[]).unwrap();
7034
    assert!(b.push("origin", false).unwrap()[0].ok);
7035
    origin.refresh().unwrap();
7036
    b.bookmark_switch("main", false).unwrap();
7037
7038
    // The remote lands it: its main moves to the feature's state.
7039
    let feat = origin
7040
        .store()
7041
        .get_state(&origin.view().unwrap().bookmarks["feat"])
7042
        .unwrap()
7043
        .heads;
7044
    origin.bookmark_set("main", &feat).unwrap();
7045
7046
    let r = b.pull("origin").unwrap();
7047
    assert!(r.changed, "{r:?}");
7048
    assert!(r.heads.contains(&x) || b.load_state(&r.heads).unwrap().contains(&x));
7049
    let main = b
7050
        .bookmarks()
7051
        .unwrap()
7052
        .into_iter()
7053
        .find(|m| m.name == "main")
7054
        .unwrap();
7055
    assert_eq!(main.behind, Some(0), "{main:?}");
7056
}
7057
7058
/// oxygen#48: a remote's bookmarks are names here (`origin/NAME`); switching
7059
/// to one only the remote has makes a local bookmark from it; a pull moves
7060
/// every local bookmark the remote has too; a clone checks out the remote's
7061
/// default bookmark.
7062
#[test]
7063
fn remote_bookmarks_are_named_switched_to_pulled_and_cloned() {
7064
    hermetic();
7065
    let dir = tempfile::tempdir().unwrap();
7066
    let root = dir.path();
7067
    let origin_path = root.join("origin");
7068
    let mut origin = Repo::init(&origin_path).unwrap();
7069
    let url = origin_path.to_string_lossy().to_string();
7070
    let mut a = Repo::clone(&url, &root.join("a")).unwrap();
7071
    write(&root.join("a"), "base.txt", b"base\n");
7072
    a.commit("base", &[]).unwrap();
7073
    assert!(a.push("origin", false).unwrap()[0].ok);
7074
    a.bookmark_create("develop", None).unwrap();
7075
    a.bookmark_switch("develop", false).unwrap();
7076
    write(&root.join("a"), "base.txt", b"base\nd1\n");
7077
    let d1 = a.commit("d1", &[]).unwrap();
7078
    assert!(a.push("origin", false).unwrap()[0].ok);
7079
7080
    // A clone has main only; origin/develop is a name all the same.
7081
    let c_root = root.join("c");
7082
    let mut c = Repo::clone(&url, &c_root).unwrap();
7083
    assert_eq!(c.config.bookmark, "main");
7084
    assert!(!c.view().unwrap().bookmarks.contains_key("develop"));
7085
    assert_eq!(c.resolve_heads("origin/develop").unwrap(), vec![d1]);
7086
    assert_eq!(c.resolve_change("origin/develop").unwrap(), d1);
7087
    assert_eq!(c.remote_only_bookmarks().unwrap().len(), 1);
7088
7089
    // Switching makes the local bookmark from origin's.
7090
    c.bookmark_switch("develop", false).unwrap();
7091
    assert_eq!(c.config.bookmark, "develop");
7092
    assert_eq!(c.bookmark_heads().unwrap(), vec![d1]);
7093
    assert_eq!(fs::read(c_root.join("base.txt")).unwrap(), b"base\nd1\n");
7094
    assert!(c.remote_only_bookmarks().unwrap().is_empty());
7095
    assert!(c.bookmark_switch("nowhere", false).is_err());
7096
7097
    // Both bookmarks move on the remote; one pull takes both.
7098
    write(&root.join("a"), "base.txt", b"base\nd1\nd2\n");
7099
    let d2 = a.commit("d2", &[]).unwrap();
7100
    assert!(a.push("origin", false).unwrap()[0].ok);
7101
    a.bookmark_switch("main", false).unwrap();
7102
    write(&root.join("a"), "m.txt", b"m\n");
7103
    let m = a.commit("m", &[]).unwrap();
7104
    assert!(a.push("origin", false).unwrap()[0].ok);
7105
    let r = c.pull("origin").unwrap();
7106
    assert!(r.changed && r.checked_out, "{r:?}");
7107
    assert_eq!(r.heads, vec![d2]);
7108
    assert_eq!(r.others, vec!["main".to_string()]);
7109
    assert!(c.resolve_heads("main").unwrap().contains(&m));
7110
    assert_eq!(
7111
        fs::read(c_root.join("base.txt")).unwrap(),
7112
        b"base\nd1\nd2\n"
7113
    );
7114
    let again = c.pull("origin").unwrap();
7115
    assert!(!again.changed && again.others.is_empty(), "{again:?}");
7116
7117
    // A clone checks out the remote's default bookmark.
7118
    origin.config.set("workspace.bookmark", "develop").unwrap();
7119
    origin.save_config().unwrap();
7120
    let e = Repo::clone(&url, &root.join("e")).unwrap();
7121
    assert_eq!(e.config.bookmark, "develop");
7122
    assert_eq!(e.bookmark_heads().unwrap(), vec![d2]);
7123
    let reopened = Repo::open(&root.join("e")).unwrap();
7124
    assert_eq!(reopened.config.bookmark, "develop");
7125
    // REMOTE/NAME names the remote's bookmark to switch to.
7126
    let mut e = reopened;
7127
    e.bookmark_switch("origin/main", false).unwrap();
7128
    assert_eq!(e.config.bookmark, "main");
7129
    assert!(e.bookmark_heads().unwrap().contains(&m));
7130
}
7131
7132
/// oxygen#51, #52: --at-op reads an earlier view and refuses changes;
7133
/// op restore goes back to an operation, files included, and undo takes
7134
/// the restore back whole; op revert undoes one operation alone; each
7135
/// operation's changes are described from the views.
7136
#[test]
7137
fn operations_can_be_read_restored_and_reverted() {
7138
    hermetic();
7139
    let dir = tempfile::tempdir().unwrap();
7140
    let root = dir.path();
7141
    let repo = Repo::init(root).unwrap();
7142
    write(root, "a.txt", b"a\n");
7143
    let first = repo.commit("first", &[]).unwrap();
7144
    write(root, "a.txt", b"a\nb\n");
7145
    let second = repo.commit("second", &[]).unwrap();
7146
    let at_second = repo.head_op().unwrap().0.to_hex();
7147
    repo.bookmark_create("keep", None).unwrap();
7148
    let created = repo.head_op().unwrap().0.to_hex();
7149
    write(root, "n.txt", b"n\n");
7150
    let third = repo.commit("third", &[]).unwrap();
7151
7152
    // What each operation changed.
7153
    let ops = repo.op_log().unwrap();
7154
    let changes = repo.view_changes(&ops[1].1.view, &ops[0].1.view).unwrap();
7155
    assert!(
7156
        changes
7157
            .iter()
7158
            .any(|c| matches!(c, ViewChange::BookmarkMoved { name, .. } if name == "main")),
7159
        "{changes:?}"
7160
    );
7161
    assert!(changes
7162
        .iter()
7163
        .any(|c| matches!(c, ViewChange::WorkingCopy { .. })));
7164
7165
    // Reading at an earlier operation.
7166
    let old = Repo::open(root).unwrap().at_op(&at_second[..10]).unwrap();
7167
    assert_eq!(old.bookmark_heads().unwrap(), vec![second]);
7168
    assert!(!old.view().unwrap().bookmarks.contains_key("keep"));
7169
    write(root, "z.txt", b"z\n");
7170
    assert!(old.commit("refused", &[]).is_err(), "--at-op is read-only");
7171
    fs::remove_file(root.join("z.txt")).unwrap();
7172
    assert!(repo.resolve_op("zz").is_err());
7173
    assert_eq!(repo.resolve_op("@").unwrap().0, repo.head_op().unwrap().0);
7174
7175
    // Restore goes back, files and all; undo takes it back whole.
7176
    repo.op_restore(&at_second, false).unwrap();
7177
    assert_eq!(repo.bookmark_heads().unwrap(), vec![second]);
7178
    assert!(!root.join("n.txt").exists());
7179
    repo.undo().unwrap();
7180
    let mut heads = repo.bookmark_heads().unwrap();
7181
    heads.sort();
7182
    let mut want = vec![second, third];
7183
    want.sort();
7184
    assert_eq!(heads, want);
7185
    assert!(
7186
        root.join("n.txt").exists(),
7187
        "the files came back with the undo"
7188
    );
7189
7190
    // Revert the bookmark's creation alone: the commit after it stays.
7191
    let r = repo.op_revert(&created).unwrap();
7192
    assert_eq!(r.reverted, vec!["keep".to_string()]);
7193
    assert!(!repo.view().unwrap().bookmarks.contains_key("keep"));
7194
    assert!(repo
7195
        .load_state(&repo.bookmark_heads().unwrap())
7196
        .unwrap()
7197
        .contains(&third));
7198
    assert!(repo.op_revert(&created).is_err(), "nothing left to revert");
7199
    let _ = first;
7200
}
7201
7202
/// oxygen#41: with uncommitted work, a status after a snapshot is answered
7203
/// from the status cache while every file is as the snapshot left it, and
7204
/// from a snapshot again as soon as one is not.
7205
#[test]
7206
fn status_with_uncommitted_work_comes_from_the_cache_until_a_file_changes() {
7207
    hermetic();
7208
    let dir = tempfile::tempdir().unwrap();
7209
    let root = dir.path();
7210
    let repo = Repo::init(root).unwrap();
7211
    write(root, "a.txt", b"a\n");
7212
    write(root, "b.txt", b"b\n");
7213
    repo.commit("base", &[]).unwrap();
7214
    assert_eq!(repo.status_by_manifest().unwrap(), Some(vec![]), "clean");
7215
7216
    write(root, "a.txt", b"a\nmore\n");
7217
    assert_eq!(
7218
        repo.status_by_manifest().unwrap(),
7219
        None,
7220
        "no snapshot of the edit yet"
7221
    );
7222
    let snap = repo.snapshot_status("oxy status").unwrap();
7223
    assert_eq!(snap.statuses.len(), 1);
7224
    let cached = repo
7225
        .status_by_manifest()
7226
        .unwrap()
7227
        .expect("answered from the cache");
7228
    assert_eq!(cached.len(), 1);
7229
    assert_eq!(
7230
        (cached[0].path.as_str(), cached[0].status),
7231
        ("a.txt", ChangeStatus::Modified)
7232
    );
7233
7234
    // Any further change sends status back to a snapshot.
7235
    write(root, "a.txt", b"a\nmore\nand more\n");
7236
    assert_eq!(repo.status_by_manifest().unwrap(), None, "edited again");
7237
    repo.snapshot_status("oxy status").unwrap();
7238
    assert!(repo.status_by_manifest().unwrap().is_some());
7239
    write(root, "new.txt", b"n\n");
7240
    assert_eq!(repo.status_by_manifest().unwrap(), None, "a file added");
7241
    fs::remove_file(root.join("new.txt")).unwrap();
7242
    assert!(
7243
        repo.status_by_manifest().unwrap().is_some(),
7244
        "back as it was"
7245
    );
7246
    fs::remove_file(root.join("b.txt")).unwrap();
7247
    assert_eq!(repo.status_by_manifest().unwrap(), None, "a file removed");
7248
    write(root, "b.txt", b"b\n");
7249
7250
    // A commit leaves nothing uncommitted: clean again, no cache needed.
7251
    repo.snapshot_status("oxy status").unwrap();
7252
    repo.commit("more", &[]).unwrap();
7253
    assert_eq!(repo.status_by_manifest().unwrap(), Some(vec![]));
7254
}
7255
7256
/// oxygen#41: while the status cache holds, the working copy's diff is
7257
/// rendered from the stored working-copy change, and says exactly what a
7258
/// snapshot's diff says.
7259
#[test]
7260
fn the_working_copy_diff_from_the_cache_matches_a_snapshot() {
7261
    hermetic();
7262
    let dir = tempfile::tempdir().unwrap();
7263
    let root = dir.path();
7264
    let repo = Repo::init(root).unwrap();
7265
    write(root, "a.txt", b"one\ntwo\nthree\n");
7266
    write(root, "gone.txt", b"bye\n");
7267
    repo.commit("base", &[]).unwrap();
7268
    write(root, "a.txt", b"one\n2\nthree\nfour\n");
7269
    write(root, "new.txt", b"hello\n");
7270
    fs::remove_file(root.join("gone.txt")).unwrap();
7271
    let snap = repo.snapshot_status("oxy status").unwrap();
7272
    let slow = render_change(&snap.wc, &snap.base, &snap.base_snapshot);
7273
    assert!(
7274
        repo.status_by_manifest().unwrap().is_some(),
7275
        "the cache holds"
7276
    );
7277
    let (wc, base, snapshot) = repo.working_copy_with_base().unwrap();
7278
    assert_eq!(render_change(&wc, &base, &snapshot), slow);
7279
    assert_eq!(repo.diff_files(None).unwrap().len(), 3);
7280
}
7281
7282
/// oxygen#41: a manifest written from a walk keeps every directory's time;
7283
/// while none has moved, the check stats the tracked files without listing
7284
/// the tree, and a file added or removed anywhere moves its directory's
7285
/// time, so the tree is listed again.
7286
#[test]
7287
fn the_manifest_check_skips_listing_while_no_directory_changed() {
7288
    hermetic();
7289
    let dir = tempfile::tempdir().unwrap();
7290
    let root = dir.path();
7291
    let repo = Repo::init(root).unwrap();
7292
    write(root, "a.txt", b"a\n");
7293
    write(root, "sub/deep/b.txt", b"b\n");
7294
    repo.commit("base", &[]).unwrap();
7295
    // Out of the racy window: every file and directory a minute old.
7296
    let old = std::time::SystemTime::now() - std::time::Duration::from_secs(60);
7297
    for p in ["a.txt", "sub/deep/b.txt", "sub/deep", "sub", ""] {
7298
        fs::File::open(root.join(p))
7299
            .unwrap()
7300
            .set_modified(old)
7301
            .unwrap();
7302
    }
7303
    repo.snapshot_status("oxy status").unwrap();
7304
    repo.write_manifest(false, false).unwrap();
7305
    let m = repo.read_manifest().unwrap().unwrap().2;
7306
    assert!(m.dirs.iter().any(|(d, _)| d == "sub/deep"), "{:?}", m.dirs);
7307
    assert_eq!(
7308
        repo.disk_differs_by_dirs(&m),
7309
        Some(false),
7310
        "no listing needed"
7311
    );
7312
    assert_eq!(repo.status_by_manifest().unwrap(), Some(vec![]));
7313
7314
    // A same-size edit with a new time: found by its stat.
7315
    write(root, "sub/deep/b.txt", b"c\n");
7316
    assert_eq!(repo.disk_differs_by_dirs(&m), Some(true));
7317
    write(root, "sub/deep/b.txt", b"b\n");
7318
    fs::File::open(root.join("sub/deep/b.txt"))
7319
        .unwrap()
7320
        .set_modified(old)
7321
        .unwrap();
7322
    assert_eq!(repo.disk_differs_by_dirs(&m), Some(false));
7323
7324
    // A new file moves its directory's time: the tree must be listed.
7325
    write(root, "sub/deep/new.txt", b"n\n");
7326
    assert_eq!(repo.disk_differs_by_dirs(&m), None);
7327
    assert_eq!(repo.status_by_manifest().unwrap(), None);
7328
    fs::remove_file(root.join("sub/deep/new.txt")).unwrap();
7329
    // A removed one too.
7330
    fs::remove_file(root.join("a.txt")).unwrap();
7331
    assert_eq!(repo.disk_differs_by_dirs(&m), None);
7332
}
7333
7334
/// oxygen#41: a commit right after a status takes the snapshot the status
7335
/// left (the status cache holds) rather than walking again, and commits
7336
/// exactly what a snapshot would have.
7337
#[test]
7338
fn a_commit_after_a_status_uses_the_cached_snapshot() {
7339
    hermetic();
7340
    let dir = tempfile::tempdir().unwrap();
7341
    let root = dir.path();
7342
    let repo = Repo::init(root).unwrap();
7343
    write(root, "a.txt", b"a\nb\n");
7344
    write(root, ".oxyattributes", b"*.bin binary\n");
7345
    repo.commit("base", &[]).unwrap();
7346
    write(root, "a.txt", b"a\nB\n");
7347
    write(root, "new.txt", b"new\n");
7348
    let snap = repo.snapshot_status("oxy status").unwrap();
7349
    let cached = repo
7350
        .snapshot_from_cache()
7351
        .unwrap()
7352
        .expect("the cache holds");
7353
    assert_eq!(cached.wc_hash, snap.wc_hash);
7354
    assert_eq!(cached.statuses, snap.statuses);
7355
    assert!(
7356
        !cached.attributes.is_empty(),
7357
        "the .oxyattributes file was read"
7358
    );
7359
    let h = repo.commit("edit", &[]).unwrap();
7360
    let c = repo.store().get_change(&h).unwrap();
7361
    assert_eq!(
7362
        c.tree_ops.len() + c.edits.len(),
7363
        snap.wc.tree_ops.len() + snap.wc.edits.len()
7364
    );
7365
    assert_eq!(
7366
        repo.status_by_manifest().unwrap(),
7367
        Some(vec![]),
7368
        "clean after the commit"
7369
    );
7370
    assert_eq!(fs::read(root.join("a.txt")).unwrap(), b"a\nB\n");
7371
}
7372
7373
/// oxygen#41: a clean check that verified racy entries restamps the
7374
/// manifest, so later checks can trust them, and a same-size rewrite
7375
/// straight afterwards is still found: entries within two seconds of the
7376
/// new time stay racy.
7377
#[test]
7378
fn a_verified_clean_check_restamps_the_manifest_safely() {
7379
    hermetic();
7380
    let dir = tempfile::tempdir().unwrap();
7381
    let root = dir.path();
7382
    let repo = Repo::init(root).unwrap();
7383
    write(root, "a.txt", b"one\n");
7384
    repo.commit("one", &[]).unwrap();
7385
    let before = repo.read_manifest().unwrap().unwrap().2.written_ns;
7386
    assert!(repo.clean_by_manifest().unwrap());
7387
    let after = repo.read_manifest().unwrap().unwrap().2.written_ns;
7388
    assert!(after > before, "restamped");
7389
    write(root, "a.txt", b"two\n");
7390
    assert!(
7391
        !repo.clean_by_manifest().unwrap(),
7392
        "a same-size rewrite is still seen"
7393
    );
7394
}
7395
7396
/// oxygen#35: a history-only state keeps no inserted text. It reads a
7397
/// stored insert's text blob only when it builds that file's graph, and
7398
/// builds the same graph a full load does.
7399
#[test]
7400
fn history_only_states_read_text_only_for_the_graphs_they_build() {
7401
    hermetic();
7402
    let dir = tempfile::tempdir().unwrap();
7403
    let root = dir.path();
7404
    let repo = Repo::init(root).unwrap();
7405
    let big: String = (0..3000).map(|i| format!("big line {i}\n")).collect();
7406
    let other: String = (0..3000).map(|i| format!("other line {i}\n")).collect();
7407
    write(root, "big.txt", big.as_bytes());
7408
    write(root, "other.txt", other.as_bytes());
7409
    let h = repo.commit("two large files", &[]).unwrap();
7410
    write(root, "big.txt", format!("{big}one more\n").as_bytes());
7411
    let h2 = repo.commit("append", &[]).unwrap();
7412
7413
    let full = repo.load_state_full(&[h2]).unwrap().materialize();
7414
    let text = |snap: &crate::state::Snapshot, p: &str| match &snap.files[p].content {
7415
        FileContent::Text { bytes, .. } => bytes.clone(),
7416
        other => panic!("{other:?}"),
7417
    };
7418
    // Built on demand, every graph renders as the full load's.
7419
    let mut hist = repo.load_state_history(&[h2]).unwrap();
7420
    let big_node = full.files["big.txt"].node;
7421
    assert!(hist.graph_key(&big_node).is_some(), "not built yet");
7422
    repo.load_all_graphs(&mut hist).unwrap();
7423
    let rendered = hist.materialize();
7424
    for p in ["big.txt", "other.txt"] {
7425
        assert_eq!(text(&rendered, p), text(&full, p), "{p}");
7426
    }
7427
7428
    // Without other.txt's text blob, history still loads and big.txt still
7429
    // builds: nothing read the other text.
7430
    let (_, texts) = repo.store().get_change_lazy(&h).unwrap();
7431
    assert_eq!(texts.len(), 2);
7432
    let content = |r: &ObjectRef| -> Vec<u8> {
7433
        let blob = crate::objects::Blob::decode(&repo.store().get(r).unwrap().1).unwrap();
7434
        blob.chunks
7435
            .iter()
7436
            .flat_map(|c| repo.store().get(c).unwrap().1)
7437
            .collect()
7438
    };
7439
    let other_text = texts
7440
        .iter()
7441
        .filter_map(|t| match t {
7442
            crate::objects::TextRef::Blob(r, _, _) => Some(*r),
7443
            _ => None,
7444
        })
7445
        .find(|r| content(r).windows(12).any(|w| w == b"other line 1"))
7446
        .unwrap();
7447
    repo.store().remove_loose_for_test(&other_text).unwrap();
7448
    let mut hist = repo.load_state_history(&[h2]).unwrap();
7449
    repo.load_graphs_of(&mut hist, &[big_node]).unwrap();
7450
    assert!(repo
7451
        .load_graphs_of(&mut hist, &[full.files["other.txt"].node])
7452
        .is_err());
7453
}
7454
7455
/// oxygen#35: the first status after a commit read and rendered every
7456
/// file (79 s and more than 14 GB on the Linux tree), because the
7457
/// manifest had no graph keys for files the commit added.
7458
#[test]
7459
fn a_commit_leaves_a_manifest_the_next_status_trusts() {
7460
    use std::os::unix::fs::PermissionsExt;
7461
    hermetic();
7462
    let dir = tempfile::tempdir().unwrap();
7463
    let root = dir.path();
7464
    let repo = Repo::init(root).unwrap();
7465
    let files = ["a.txt", "b.txt", "d/c.txt"];
7466
    for p in files {
7467
        write(root, p, format!("{p}\n").as_bytes());
7468
        let old = std::time::SystemTime::now() - std::time::Duration::from_secs(30);
7469
        fs::File::options()
7470
            .write(true)
7471
            .open(root.join(p))
7472
            .unwrap()
7473
            .set_modified(old)
7474
            .unwrap();
7475
    }
7476
    repo.commit("added", &[]).unwrap();
7477
    let (_, _, m) = repo.read_manifest().unwrap().unwrap();
7478
    assert!(
7479
        m.entries.values().all(|e| e.graph.is_some()),
7480
        "keys recorded at commit"
7481
    );
7482
    // Unreadable files prove the next status reads none of them.
7483
    for p in files {
7484
        fs::set_permissions(root.join(p), fs::Permissions::from_mode(0o000)).unwrap();
7485
    }
7486
    let snap = repo.snapshot_status("status").unwrap();
7487
    for p in files {
7488
        fs::set_permissions(root.join(p), fs::Permissions::from_mode(0o644)).unwrap();
7489
    }
7490
    assert!(!snap.changed && snap.statuses.is_empty());
7491
    assert_eq!(snap.base_snapshot.unrendered.len(), files.len());
7492
}
7493
7494
/// oxygen#35: a checkout reads, renders and writes only the files whose
7495
/// graphs differ, and renders the rest a batch at a time.
7496
#[test]
7497
fn checkout_touches_only_what_differs_and_renders_in_batches() {
7498
    use std::os::unix::fs::PermissionsExt;
7499
    hermetic();
7500
    let dir = tempfile::tempdir().unwrap();
7501
    let root = dir.path();
7502
    let origin = root.join("origin");
7503
    let mut repo = Repo::init(&origin).unwrap();
7504
    // More files than one batch holds.
7505
    let n = 2100;
7506
    let old = std::time::SystemTime::now() - std::time::Duration::from_secs(30);
7507
    for i in 0..n {
7508
        let p = format!("f/{i:04}.txt");
7509
        write(&origin, &p, format!("file {i}\n").as_bytes());
7510
        fs::File::options()
7511
            .write(true)
7512
            .open(origin.join(&p))
7513
            .unwrap()
7514
            .set_modified(old)
7515
            .unwrap();
7516
    }
7517
    repo.commit("many", &[]).unwrap();
7518
    repo.bookmark_create("feature", None).unwrap();
7519
    repo.bookmark_switch("feature", false).unwrap();
7520
    write(&origin, "f/0007.txt", b"changed\n");
7521
    repo.commit("one change", &[]).unwrap();
7522
7523
    // Switching back to main must not read the unchanged files.
7524
    for i in 0..n {
7525
        if i != 7 {
7526
            let p = origin.join(format!("f/{i:04}.txt"));
7527
            fs::set_permissions(&p, fs::Permissions::from_mode(0o000)).unwrap();
7528
        }
7529
    }
7530
    let r = repo.bookmark_switch("main", false).unwrap();
7531
    for i in 0..n {
7532
        let p = origin.join(format!("f/{i:04}.txt"));
7533
        fs::set_permissions(&p, fs::Permissions::from_mode(0o644)).unwrap();
7534
    }
7535
    assert_eq!((r.written, r.removed), (1, 0), "{r:?}");
7536
    assert_eq!(fs::read(origin.join("f/0007.txt")).unwrap(), b"file 7\n");
7537
    assert!(repo.snapshot_status("status").unwrap().statuses.is_empty());
7538
7539
    // A clone renders every file, across batches.
7540
    let c = root.join("clone");
7541
    Repo::clone(&origin.to_string_lossy(), &c).unwrap();
7542
    for i in [0, 2047, 2048, n - 1] {
7543
        assert_eq!(
7544
            fs::read(c.join(format!("f/{i:04}.txt"))).unwrap(),
7545
            format!("file {i}\n").as_bytes()
7546
        );
7547
    }
7548
    let cloned = Repo::open(&c).unwrap();
7549
    assert!(cloned
7550
        .snapshot_status("status")
7551
        .unwrap()
7552
        .statuses
7553
        .is_empty());
7554
}
7555
7556
/// A file written just before the manifest (inside the racy window) is
7557
/// checked by its hash: trusted when equal, caught when edited in place
7558
/// with the same size and time.
7559
#[test]
7560
fn a_racy_manifest_entry_is_checked_by_hash() {
7561
    hermetic();
7562
    let dir = tempfile::tempdir().unwrap();
7563
    let root = dir.path();
7564
    let repo = Repo::init(root).unwrap();
7565
    write(root, "a.txt", b"one\n");
7566
    repo.commit("fresh", &[]).unwrap();
7567
    assert!(repo.clean_by_manifest().unwrap(), "fresh but equal");
7568
    let t = fs::metadata(root.join("a.txt"))
7569
        .unwrap()
7570
        .modified()
7571
        .unwrap();
7572
    write(root, "a.txt", b"two\n");
7573
    fs::File::options()
7574
        .write(true)
7575
        .open(root.join("a.txt"))
7576
        .unwrap()
7577
        .set_modified(t)
7578
        .unwrap();
7579
    assert!(
7580
        !repo.clean_by_manifest().unwrap(),
7581
        "same size and time, other bytes"
7582
    );
7583
    assert_eq!(
7584
        statuses(&repo.snapshot_status("status").unwrap()),
7585
        vec![("a.txt".to_string(), ChangeStatus::Modified)]
7586
    );
7587
}
7588
7589
/// A fetch on one machine moves changes as stored, text blobs among the
7590
/// objects; a change whose text blob did not come is refused, not stored.
7591
#[test]
7592
fn a_raw_bundle_without_a_changes_text_is_refused() {
7593
    hermetic();
7594
    let dir = tempfile::tempdir().unwrap();
7595
    let root = dir.path();
7596
    let a = Repo::init(&root.join("a")).unwrap();
7597
    let big: String = (0..3000).map(|i| format!("line {i}\n")).collect();
7598
    write(&root.join("a"), "big.txt", big.as_bytes());
7599
    let h = a.commit("big", &[]).unwrap();
7600
    let bundle = a.bundle_raw_for(&[h], None).unwrap();
7601
    assert_eq!(bundle.raw_changes.len(), 1);
7602
    assert!(bundle.changes.is_empty());
7603
    let b = Repo::init(&root.join("b")).unwrap();
7604
    let mut without = bundle.clone();
7605
    without.objects.retain(|(ty, _)| *ty != ObjectType::Blob);
7606
    let e = b.import_bundle(&without, false).unwrap_err();
7607
    assert!(e.to_string().contains("came without its text blob"), "{e}");
7608
    assert!(!b.store().has(&h));
7609
    assert_eq!(b.import_bundle(&bundle, false).unwrap(), vec![h]);
7610
    assert_eq!(b.store().get_change(&h).unwrap().message, "big");
7611
}
7612
7613
/// oxygen#30 (vscode): a directory deleted in one line of history and made
7614
/// again was a second node for one Git path, so a file moved into it on
7615
/// another line, where the first node still stood, ended up in two places.
7616
/// An import now brings the directory back rather than make a new one.
7617
#[test]
7618
fn git_import_brings_a_directory_back_rather_than_making_a_second() {
7619
    hermetic();
7620
    if std::process::Command::new("git")
7621
        .arg("--version")
7622
        .output()
7623
        .is_err()
7624
    {
7625
        eprintln!("git not installed; skipping");
7626
        return;
7627
    }
7628
    let dir = tempfile::tempdir().unwrap();
7629
    let root = dir.path();
7630
    let g = root.join("src.git");
7631
    fs::create_dir_all(&g).unwrap();
7632
    let git = |args: &[&str]| -> String {
7633
        let out = std::process::Command::new("git")
7634
            .arg("-C")
7635
            .arg(&g)
7636
            .args([
7637
                "-c",
7638
                "user.name=Grace",
7639
                "-c",
7640
                "[email protected]",
7641
                "-c",
7642
                "commit.gpgsign=false",
7643
            ])
7644
            .args(args)
7645
            .output()
7646
            .unwrap();
7647
        assert!(
7648
            out.status.success(),
7649
            "git {args:?}: {}",
7650
            String::from_utf8_lossy(&out.stderr)
7651
        );
7652
        String::from_utf8_lossy(&out.stdout).trim().to_string()
7653
    };
7654
    git(&["init", "-q", "-b", "main"]);
7655
    write(&g, "d/a.txt", b"a\n");
7656
    write(&g, "c/x.txt", b"x\n");
7657
    git(&["add", "."]);
7658
    git(&["commit", "-qm", "base"]);
7659
    // One line: move x into d while d still stands.
7660
    git(&["checkout", "-qb", "side"]);
7661
    git(&["mv", "c/x.txt", "d/x.txt"]);
7662
    git(&["commit", "-qm", "x into d"]);
7663
    // The other: d goes, comes back, and x moves into it too.
7664
    git(&["checkout", "-q", "main"]);
7665
    git(&["rm", "-q", "d/a.txt"]);
7666
    git(&["commit", "-qm", "d goes"]);
7667
    write(&g, "d/b.txt", b"b\n");
7668
    git(&["add", "."]);
7669
    git(&["commit", "-qm", "d comes back"]);
7670
    git(&["mv", "c/x.txt", "d/x.txt"]);
7671
    git(&["commit", "-qm", "x into d again"]);
7672
    git(&["merge", "-q", "--no-edit", "side"]);
7673
7674
    let repo = Repo::init(&root.join("o")).unwrap();
7675
    repo.import_git(&g, "main").unwrap();
7676
    let v = repo.verify_git_import(&g, "main").unwrap();
7677
    assert!(v.mismatches.is_empty(), "{:?}", v.mismatches);
7678
    let st = repo
7679
        .load_state_history(&repo.bookmark_heads().unwrap())
7680
        .unwrap();
7681
    let view = st.tree().view();
7682
    assert!(view.conflicts.is_empty(), "{:?}", view.conflicts);
7683
    // The directory is the one the first commit made.
7684
    // Commits made in one second tie on time: find the first by its message.
7685
    let first = repo
7686
        .log()
7687
        .unwrap()
7688
        .into_iter()
7689
        .find(|e| e.change.message.starts_with("base"))
7690
        .unwrap();
7691
    let base = repo
7692
        .load_state_history(&[first.hash])
7693
        .unwrap()
7694
        .tree()
7695
        .view();
7696
    assert_eq!(view.entries["d"].node, base.entries["d"].node);
7697
}
7698
7699
/// oxygen#30, the rest: a placement left under a directory another line
7700
/// removed is out of sight, so no diff reaches it; the merge that settles
7701
/// where the file is retires it.
7702
#[test]
7703
fn git_import_merge_retires_a_placement_under_a_removed_directory() {
7704
    hermetic();
7705
    if std::process::Command::new("git")
7706
        .arg("--version")
7707
        .output()
7708
        .is_err()
7709
    {
7710
        eprintln!("git not installed; skipping");
7711
        return;
7712
    }
7713
    let dir = tempfile::tempdir().unwrap();
7714
    let root = dir.path();
7715
    let g = root.join("src.git");
7716
    fs::create_dir_all(&g).unwrap();
7717
    let run = |args: &[&str]| {
7718
        std::process::Command::new("git")
7719
            .arg("-C")
7720
            .arg(&g)
7721
            .args([
7722
                "-c",
7723
                "user.name=Grace",
7724
                "-c",
7725
                "[email protected]",
7726
                "-c",
7727
                "commit.gpgsign=false",
7728
            ])
7729
            .args(args)
7730
            .output()
7731
            .unwrap()
7732
    };
7733
    let git = |args: &[&str]| {
7734
        let out = run(args);
7735
        assert!(
7736
            out.status.success(),
7737
            "git {args:?}: {}",
7738
            String::from_utf8_lossy(&out.stderr)
7739
        );
7740
    };
7741
    git(&["init", "-q", "-b", "main"]);
7742
    write(&g, "c/x.txt", b"x\n");
7743
    write(&g, "keep.txt", b"k\n");
7744
    git(&["add", "."]);
7745
    git(&["commit", "-qm", "base"]);
7746
    // One line renames the file within c; the other moves it out of c,
7747
    // which goes.
7748
    git(&["checkout", "-qb", "side"]);
7749
    git(&["mv", "c/x.txt", "c/y.txt"]);
7750
    git(&["commit", "-qm", "rename within c"]);
7751
    git(&["checkout", "-q", "main"]);
7752
    fs::create_dir_all(g.join("n")).unwrap();
7753
    git(&["mv", "c/x.txt", "n/x.txt"]);
7754
    git(&["commit", "-qm", "move out of c"]);
7755
    // Git cannot merge the two renames; the merge keeps n/x.txt.
7756
    let _ = run(&["merge", "-q", "side"]);
7757
    let _ = run(&[
7758
        "rm",
7759
        "-q",
7760
        "--cached",
7761
        "--ignore-unmatch",
7762
        "c/y.txt",
7763
        "c/x.txt",
7764
    ]);
7765
    let _ = std::fs::remove_dir_all(g.join("c"));
7766
    write(&g, "n/x.txt", b"x\n");
7767
    git(&["add", "-A"]);
7768
    git(&["commit", "-qm", "merge: keep n/x.txt"]);
7769
7770
    let repo = Repo::init(&root.join("o")).unwrap();
7771
    repo.import_git(&g, "main").unwrap();
7772
    let v = repo.verify_git_import(&g, "main").unwrap();
7773
    assert!(v.mismatches.is_empty(), "{:?}", v.mismatches);
7774
    let st = repo
7775
        .load_state_history(&repo.bookmark_heads().unwrap())
7776
        .unwrap();
7777
    let view = st.tree().view();
7778
    assert!(view.conflicts.is_empty(), "{:?}", view.conflicts);
7779
    assert!(view.entries.contains_key("n/x.txt"));
7780
}
7781
7782
/// oxygen#30, orphans: a file added on one line into a directory the other
7783
/// line removed is placed where the tree cannot show it; Git's merge keeps
7784
/// the file, and the import's merge leaves exactly one of it.
7785
#[test]
7786
fn git_import_merge_leaves_no_orphan_behind() {
7787
    hermetic();
7788
    if std::process::Command::new("git")
7789
        .arg("--version")
7790
        .output()
7791
        .is_err()
7792
    {
7793
        eprintln!("git not installed; skipping");
7794
        return;
7795
    }
7796
    let dir = tempfile::tempdir().unwrap();
7797
    let root = dir.path();
7798
    let g = root.join("src.git");
7799
    fs::create_dir_all(&g).unwrap();
7800
    let git = |args: &[&str]| {
7801
        let out = std::process::Command::new("git")
7802
            .arg("-C")
7803
            .arg(&g)
7804
            .args([
7805
                "-c",
7806
                "user.name=Grace",
7807
                "-c",
7808
                "[email protected]",
7809
                "-c",
7810
                "commit.gpgsign=false",
7811
            ])
7812
            .args(args)
7813
            .output()
7814
            .unwrap();
7815
        assert!(
7816
            out.status.success(),
7817
            "git {args:?}: {}",
7818
            String::from_utf8_lossy(&out.stderr)
7819
        );
7820
    };
7821
    git(&["init", "-q", "-b", "main"]);
7822
    write(&g, "d/f.txt", b"f\n");
7823
    write(&g, "keep.txt", b"k\n");
7824
    git(&["add", "."]);
7825
    git(&["commit", "-qm", "base"]);
7826
    git(&["checkout", "-qb", "side"]);
7827
    write(&g, "d/new.txt", b"new\n");
7828
    git(&["add", "."]);
7829
    git(&["commit", "-qm", "add into d"]);
7830
    git(&["checkout", "-q", "main"]);
7831
    git(&["rm", "-q", "d/f.txt"]);
7832
    git(&["commit", "-qm", "d goes"]);
7833
    git(&["merge", "-q", "--no-edit", "side"]);
7834
7835
    let repo = Repo::init(&root.join("o")).unwrap();
7836
    repo.import_git(&g, "main").unwrap();
7837
    let v = repo.verify_git_import(&g, "main").unwrap();
7838
    assert!(v.mismatches.is_empty(), "{:?}", v.mismatches);
7839
    let st = repo
7840
        .load_state_history(&repo.bookmark_heads().unwrap())
7841
        .unwrap();
7842
    let view = st.tree().view();
7843
    assert!(view.conflicts.is_empty(), "{:?}", view.conflicts);
7844
    assert!(view.entries.contains_key("d/new.txt"));
7845
}
7846
7847
/// fsck checks a change's text as the blobs it is stored in, without
7848
/// decoding it: a missing text blob is an error named for the change.
7849
#[test]
7850
fn fsck_names_a_missing_text_blob() {
7851
    hermetic();
7852
    let dir = tempfile::tempdir().unwrap();
7853
    let root = dir.path();
7854
    let repo = Repo::init(root).unwrap();
7855
    let big: String = (0..3000).map(|i| format!("line {i}\n")).collect();
7856
    write(root, "big.txt", big.as_bytes());
7857
    let h = repo.commit("big", &[]).unwrap();
7858
    assert_eq!(repo.fsck().unwrap().errors(), 0);
7859
    let (_, texts) = repo.store().get_change_lazy(&h).unwrap();
7860
    let Some(crate::objects::TextRef::Blob(b, _, _)) = texts.first().copied() else {
7861
        panic!("a stored text")
7862
    };
7863
    repo.store().remove_loose_for_test(&b).unwrap();
7864
    let rep = repo.fsck().unwrap();
7865
    assert!(rep.errors() > 0);
7866
    assert!(
7867
        rep.problems.iter().any(|p| p.what.contains(&h.short(12))),
7868
        "{:?}",
7869
        rep.problems
7870
    );
7871
}
7872
7873
/// oxygen#32: a subrepo on the same hub as one of the parent's remotes is
7874
/// reached with that remote's token and CA (a private subrepo then clones
7875
/// for anyone who can read the parent); another hub gets none of them.
7876
#[test]
7877
fn a_subrepo_on_the_parents_hub_borrows_its_credentials() {
7878
    hermetic();
7879
    let dir = tempfile::tempdir().unwrap();
7880
    let mut repo = Repo::init(dir.path()).unwrap();
7881
    repo.config
7882
        .set(
7883
            "remote.origin.url",
7884
            "https://Hub.example:7343/doomsdayone/metalgear",
7885
        )
7886
        .unwrap();
7887
    repo.config.set("remote.origin.token", "secret").unwrap();
7888
    repo.config
7889
        .set("remote.origin.ca", "/tmp/hub-ca.pem")
7890
        .unwrap();
7891
    let same = repo.credentials_for("https://hub.example:7343/doomsdayone/rstar-api");
7892
    assert_eq!(same.token.as_deref(), Some("secret"));
7893
    assert_eq!(same.ca.as_deref(), Some(Path::new("/tmp/hub-ca.pem")));
7894
    for other in [
7895
        "https://elsewhere.example:7343/doomsdayone/rstar-api",
7896
        "https://hub.example/doomsdayone/rstar-api",
7897
        "http://hub.example:7343/doomsdayone/rstar-api",
7898
    ] {
7899
        let o = repo.credentials_for(other);
7900
        assert_ne!(o.token.as_deref(), Some("secret"), "{other}");
7901
    }
7902
}
7903
7904
/// oxygen#47: a remote with no token of its own uses the user's credential
7905
/// store for its hub, and a nested checkout finds its parent's remote
7906
/// token there instead of keeping a copy.
7907
#[test]
7908
fn remotes_use_the_credential_store_and_the_enclosing_checkout() {
7909
    hermetic();
7910
    let home = tempfile::tempdir().unwrap();
7911
    let dir = tempfile::tempdir().unwrap();
7912
    let mut parent = Repo::init(dir.path()).unwrap().with_home(home.path());
7913
    parent
7914
        .config
7915
        .set("remote.origin.url", "https://hub.example/o/parent")
7916
        .unwrap();
7917
    parent.save_config().unwrap();
7918
    assert_eq!(parent.remote_options("origin").token, None);
7919
    crate::credentials::Credentials::at(home.path())
7920
        .save("https://hub.example", "stored", Some("andy"), None)
7921
        .unwrap();
7922
    assert_eq!(
7923
        parent.remote_options("origin").token.as_deref(),
7924
        Some("stored")
7925
    );
7926
7927
    let empty_home = tempfile::tempdir().unwrap();
7928
    let nested = dir.path().join("deps").join("child");
7929
    let mut child = Repo::init(&nested).unwrap().with_home(empty_home.path());
7930
    child
7931
        .config
7932
        .set("remote.origin.url", "https://hub.example/o/child")
7933
        .unwrap();
7934
    child.save_config().unwrap();
7935
    assert_eq!(child.remote_options("origin").token, None);
7936
    parent
7937
        .config
7938
        .set("remote.origin.token", "checkout")
7939
        .unwrap();
7940
    parent.save_config().unwrap();
7941
    assert_eq!(
7942
        child.remote_options("origin").token.as_deref(),
7943
        Some("checkout")
7944
    );
7945
    // Another hub's checkout token is not borrowed.
7946
    child
7947
        .config
7948
        .set("remote.origin.url", "https://other.example/o/child")
7949
        .unwrap();
7950
    assert_eq!(child.remote_options("origin").token, None);
7951
}
7952
7953
#[test]
7954
fn the_metadata_cache_survives_a_torn_tail() {
7955
    hermetic();
7956
    let dir = tempfile::tempdir().unwrap();
7957
    let root = dir.path();
7958
    let repo = Repo::init(root).unwrap();
7959
    write(root, "a.txt", b"1\n");
7960
    let h = repo.commit("first", &[]).unwrap();
7961
    let meta = repo.store().get_change_meta(&h).unwrap();
7962
    let cache = repo.store().dir().join("metas");
7963
    let len = fs::metadata(&cache).unwrap().len();
7964
    assert!(len > 0, "a change read is cached");
7965
    // A torn record at the end: the cache reads up to it and cuts it off.
7966
    fs::OpenOptions::new()
7967
        .append(true)
7968
        .open(&cache)
7969
        .unwrap()
7970
        .write_all(&[7; 20])
7971
        .unwrap();
7972
    let again = Repo::open(root).unwrap();
7973
    assert_eq!(again.store().get_change_meta(&h).unwrap(), meta);
7974
    assert_eq!(fs::metadata(&cache).unwrap().len(), len);
7975
}
7976
7977
#[test]
7978
fn a_manifest_that_does_not_check_reads_as_none() {
7979
    hermetic();
7980
    let dir = tempfile::tempdir().unwrap();
7981
    let root = dir.path();
7982
    let repo = Repo::init(root).unwrap();
7983
    write(root, "a.txt", b"1\n");
7984
    repo.commit("first", &[]).unwrap();
7985
    let path = repo.manifest_path();
7986
    let mut bytes = fs::read(&path).unwrap();
7987
    assert!(Repo::open(root).unwrap().read_manifest().unwrap().is_some());
7988
    let last = bytes.len() - 1;
7989
    bytes[last] ^= 1;
7990
    fs::write(&path, &bytes).unwrap();
7991
    assert!(Repo::open(root).unwrap().read_manifest().unwrap().is_none());
7992
    // The next status reads the files and writes it again.
7993
    let again = Repo::open(root).unwrap();
7994
    assert!(!again.snapshot("status").unwrap().changed);
7995
    assert!(again.read_manifest().unwrap().is_some());
7996
}
7997
7998
#[test]
7999
fn a_commit_leaves_a_manifest_that_proves_the_working_copy_clean() {
8000
    hermetic();
8001
    let dir = tempfile::tempdir().unwrap();
8002
    let root = dir.path();
8003
    let repo = Repo::init(root).unwrap();
8004
    write(root, "a.txt", b"1\n");
8005
    write(root, "b.txt", b"2\n");
8006
    // b.txt outside the racy window, so snapshots take it as unchanged.
8007
    let old = std::time::SystemTime::now() - std::time::Duration::from_secs(60);
8008
    fs::File::options()
8009
        .write(true)
8010
        .open(root.join("b.txt"))
8011
        .unwrap()
8012
        .set_modified(old)
8013
        .unwrap();
8014
    repo.commit("first", &[]).unwrap();
8015
    assert!(repo.clean_by_manifest().unwrap(), "after the first commit");
8016
    repo.snapshot_status("status").unwrap();
8017
    write(root, "a.txt", b"1\n2\n");
8018
    repo.commit("second", &[]).unwrap();
8019
    assert!(
8020
        repo.clean_by_manifest().unwrap(),
8021
        "after a commit of one file"
8022
    );
8023
    // Edited, seen by a status, edited again, then committed: the status
8024
    // left the first edit's stat, which the commit must not keep.
8025
    write(root, "a.txt", b"1\n2\n3\n");
8026
    repo.snapshot_status("status").unwrap();
8027
    write(root, "a.txt", b"1\n2\n3\n4\n5\n");
8028
    repo.commit("third", &[]).unwrap();
8029
    assert!(
8030
        repo.clean_by_manifest().unwrap(),
8031
        "after an edit a status saw"
8032
    );
8033
}
8034
8035
#[test]
8036
fn a_conflicted_rebase_can_be_resolved_in_the_working_copy() {
8037
    hermetic();
8038
    let dir = tempfile::tempdir().unwrap();
8039
    let root = dir.path();
8040
    let mut repo = Repo::init(root).unwrap().with_home(root.join("home"));
8041
    write(root, "a.txt", b"1\n2\n");
8042
    let a = repo.commit("A", &[]).unwrap();
8043
    repo.bookmark_create("develop", Some(&[a])).unwrap();
8044
    write(root, "a.txt", b"1\nX\n");
8045
    let c = repo.commit("C: 2 to X", &[]).unwrap();
8046
    repo.bookmark_switch("develop", false).unwrap();
8047
    write(root, "a.txt", b"1\nY\n");
8048
    let d = repo.commit("D: 2 to Y", &[]).unwrap();
8049
    repo.bookmark_switch("main", false).unwrap();
8050
8051
    let err = repo.rebase(&c, &[d]).unwrap_err();
8052
    assert!(matches!(err, RepoError::Conflicted(_)), "{err}");
8053
    let r = repo.rebase_into_working_copy(&c, &[d]).unwrap();
8054
    assert!(r.changed && r.checked_out);
8055
    let snap = repo.snapshot_status("status").unwrap();
8056
    assert!(
8057
        snap.base_snapshot.is_conflicted(),
8058
        "the conflict is in the working copy"
8059
    );
8060
    let text = fs::read_to_string(root.join("a.txt")).unwrap();
8061
    assert!(text.contains('X') && text.contains('Y'), "{text}");
8062
8063
    write(root, "a.txt", b"1\nXY\n");
8064
    repo.commit("Resolve", &[]).unwrap();
8065
    let st = repo.load_state(&repo.bookmark_heads().unwrap()).unwrap();
8066
    assert!(st.contains(&c) && st.contains(&d));
8067
    let files = st.materialize().files;
8068
    assert!(!files["a.txt"].is_conflicted());
8069
    assert!(
8070
        matches!(&files["a.txt"].content, FileContent::Text { bytes, .. } if bytes == b"1\nXY\n")
8071
    );
8072
8073
    // A change the current bookmark does not hold is refused.
8074
    repo.bookmark_switch("develop", false).unwrap();
8075
    write(root, "b.txt", b"b\n");
8076
    let e = repo.commit("E", &[]).unwrap();
8077
    repo.bookmark_switch("main", false).unwrap();
8078
    let err = repo.rebase_into_working_copy(&e, &[a]).unwrap_err();
8079
    assert!(
8080
        err.to_string().contains("not on the current bookmark"),
8081
        "{err}"
8082
    );
8083
}
8084
8085
#[test]
8086
fn an_ignore_rule_drops_an_added_file_but_not_a_tracked_one() {
8087
    hermetic();
8088
    let dir = tempfile::tempdir().unwrap();
8089
    let root = dir.path();
8090
    let repo = Repo::init(root).unwrap();
8091
    write(root, "a.txt", b"a\n");
8092
    write(root, "kept.log", b"tracked\n");
8093
    repo.commit("first", &[]).unwrap();
8094
    write(root, "build.log", b"made\n");
8095
    let snap = repo.snapshot_status("status").unwrap();
8096
    assert!(snap.statuses.iter().any(|s| s.path == "build.log"));
8097
    // A rule written afterwards leaves the added file out again, while the
8098
    // committed one stays tracked.
8099
    write(root, ".gitignore", b"*.log\n");
8100
    let snap = repo.snapshot_status("status").unwrap();
8101
    let paths: Vec<&str> = snap.statuses.iter().map(|s| s.path.as_str()).collect();
8102
    assert_eq!(paths, vec![".gitignore"], "{paths:?}");
8103
    write(root, "kept.log", b"tracked, edited\n");
8104
    let snap = repo.snapshot_status("status").unwrap();
8105
    assert!(snap.statuses.iter().any(|s| s.path == "kept.log"));
8106
}
8107
8108
#[test]
8109
fn shed_graphs_come_back_the_same() {
8110
    hermetic();
8111
    let dir = tempfile::tempdir().unwrap();
8112
    let root = dir.path();
8113
    let repo = Repo::init(root).unwrap();
8114
    write(root, "a.txt", b"1\n2\n3\n");
8115
    write(root, "b.txt", b"x\n");
8116
    repo.commit("first", &[]).unwrap();
8117
    write(root, "a.txt", b"1\ntwo\n3\n4\n");
8118
    repo.commit("second", &[]).unwrap();
8119
    let heads = repo.bookmark_heads().unwrap();
8120
    let mut st = repo.load_state_history(&heads).unwrap();
8121
    let view = st.tree().view();
8122
    let nodes: Vec<NodeId> = ["a.txt", "b.txt"]
8123
        .iter()
8124
        .map(|p| view.entries[*p].node)
8125
        .collect();
8126
    repo.load_graphs_of(&mut st, &nodes).unwrap();
8127
    let before: Vec<Vec<u8>> = nodes.iter().map(|n| st.render_file(n).0).collect();
8128
    assert_eq!(st.built_count(), 2);
8129
    let shed = st.shed_graphs(|b| repo.store_blob(b)).unwrap();
8130
    assert_eq!((shed, st.built_count()), (2, 0));
8131
    // A later change applies on top of the shed history.
8132
    write(root, "a.txt", b"1\ntwo\n3\n4\n5\n");
8133
    let h3 = repo.commit("third", &[]).unwrap();
8134
    let (skeleton, texts) = repo.store().get_change_lazy(&h3).unwrap();
8135
    st.add_known(h3, skeleton, texts);
8136
    repo.load_graphs_of(&mut st, &nodes).unwrap();
8137
    let after: Vec<Vec<u8>> = nodes.iter().map(|n| st.render_file(n).0).collect();
8138
    assert_eq!(after[1], before[1]);
8139
    assert_eq!(after[0], b"1\ntwo\n3\n4\n5\n");
8140
}
8141
8142
#[test]
8143
fn many_edited_files_diff_in_parallel() {
8144
    // Enough edited files that the builder diffs them in parallel; the
8145
    // commit must hold exactly what is on disk, and a second snapshot
8146
    // must find nothing left to commit.
8147
    hermetic();
8148
    let dir = tempfile::tempdir().unwrap();
8149
    let root = dir.path();
8150
    let repo = Repo::init(root).unwrap();
8151
    let text = |i: usize, round: usize| {
8152
        let mut s = String::new();
8153
        for line in 0..50 {
8154
            if round > 0 && line % 7 == i % 7 {
8155
                s.push_str(&format!("edited {round} {i} {line}\n"));
8156
            } else {
8157
                s.push_str(&format!("file {i} line {line}\n"));
8158
            }
8159
        }
8160
        if round > 0 && i.is_multiple_of(3) {
8161
            s.push_str("appended\n");
8162
        }
8163
        s
8164
    };
8165
    for i in 0..40 {
8166
        write(root, &format!("d/f{i}.txt"), text(i, 0).as_bytes());
8167
    }
8168
    repo.commit("first", &[]).unwrap();
8169
    for i in 0..40 {
8170
        write(root, &format!("d/f{i}.txt"), text(i, 1).as_bytes());
8171
    }
8172
    let h = repo.commit("edit every file", &[]).unwrap();
8173
    let snap = repo.load_state(&[h]).unwrap().materialize();
8174
    for i in 0..40 {
8175
        let want = text(i, 1);
8176
        assert!(
8177
            matches!(&snap.files[&format!("d/f{i}.txt")].content, FileContent::Text { bytes, .. } if bytes == want.as_bytes()),
8178
            "d/f{i}.txt as committed"
8179
        );
8180
    }
8181
    assert!(
8182
        repo.commit("nothing", &[]).is_err(),
8183
        "nothing left to commit"
8184
    );
8185
}
8186
8187
/// oxygen#56: after a fetch, how a bookmark stands against its remote copy
8188
/// is known (fetch printed "up to date" while main was behind), a change
8189
/// only fetched resolves and says where it is, and a checkout whose only
8190
/// remote is not `origin` uses that one.
8191
#[test]
8192
fn a_fetched_change_shows_as_behind_and_resolves() {
8193
    hermetic();
8194
    let dir = tempfile::tempdir().unwrap();
8195
    let root = dir.path();
8196
    let origin = Repo::init(&root.join("origin")).unwrap();
8197
    drop(origin);
8198
    let url = root.join("origin").to_string_lossy().to_string();
8199
    let a = Repo::clone(&url, &root.join("a"))
8200
        .unwrap()
8201
        .with_home(root.join("home-a"));
8202
    write(&root.join("a"), "f.txt", b"one\n");
8203
    a.commit("one", &[]).unwrap();
8204
    a.push("origin", false).unwrap();
8205
    let b = Repo::clone(&url, &root.join("b"))
8206
        .unwrap()
8207
        .with_home(root.join("home-b"));
8208
    assert_eq!(b.tracking("origin", "main").unwrap(), Some((0, 0)));
8209
8210
    write(&root.join("a"), "f.txt", b"one\ntwo\n");
8211
    let h2 = a.commit("two", &[]).unwrap();
8212
    a.push("origin", false).unwrap();
8213
    b.fetch("origin").unwrap();
8214
    // Fetched, not pulled: one behind, the change found and placed.
8215
    assert_eq!(b.tracking("origin", "main").unwrap(), Some((0, 1)));
8216
    assert_eq!(b.tracking("origin", "nope").unwrap(), None);
8217
    assert_eq!(
8218
        b.resolve_change(&format!("#{}", &h2.to_hex()[..12]))
8219
            .unwrap(),
8220
        h2
8221
    );
8222
    assert_eq!(
8223
        b.remote_only_location(&h2).unwrap().as_deref(),
8224
        Some("origin/main")
8225
    );
8226
    // Fetching again changes nothing: still behind, which is what the
8227
    // CLI now says rather than "up to date".
8228
    b.fetch("origin").unwrap();
8229
    assert_eq!(b.tracking("origin", "main").unwrap(), Some((0, 1)));
8230
    b.pull("origin").unwrap();
8231
    assert_eq!(b.tracking("origin", "main").unwrap(), Some((0, 0)));
8232
    assert_eq!(b.remote_only_location(&h2).unwrap(), None);
8233
8234
    // One remote, not called origin: it is the default.
8235
    let mut c = Repo::init(&root.join("c")).unwrap();
8236
    assert_eq!(c.default_remote(), "origin");
8237
    c.config.set("remote.earth.url", &url).unwrap();
8238
    assert_eq!(c.default_remote(), "earth");
8239
    c.config.set("remote.origin.url", &url).unwrap();
8240
    assert_eq!(c.default_remote(), "origin");
8241
}
8242
8243
/// oxygen#57: a clone from a relative local path records the remote as an
8244
/// absolute path, so fetch still finds it from inside the clone.
8245
#[test]
8246
fn a_clone_from_a_relative_path_records_it_absolute() {
8247
    hermetic();
8248
    let dir = tempfile::tempdir().unwrap();
8249
    let root = dir.path();
8250
    Repo::init(&root.join("origin")).unwrap();
8251
    let rel = crate::protocol::stored_url("relative/repo");
8252
    assert!(std::path::Path::new(&rel).is_absolute(), "{rel}");
8253
    assert_eq!(
8254
        crate::protocol::stored_url("https://hub.example/o/n"),
8255
        "https://hub.example/o/n"
8256
    );
8257
    assert!(crate::protocol::stored_url("file://x").starts_with("file:///"));
8258
    assert!(crate::protocol::stored_url("dir://x").starts_with("dir:///"));
8259
    // A bucket is kept as written: it is not a path.
8260
    assert_eq!(
8261
        crate::protocol::stored_url("s3://bucket/prefix?profile=p"),
8262
        "s3://bucket/prefix?profile=p"
8263
    );
8264
    let url = root.join("origin").to_string_lossy().to_string();
8265
    let b = Repo::clone(&url, &root.join("b")).unwrap();
8266
    assert_eq!(b.config.remotes["origin"], url);
8267
    b.fetch("origin").unwrap();
8268
}
8269
8270
/// oxygen#60 and #61: a workspace added on a bookmark is on that bookmark,
8271
/// and gets its subrepos at their pins from this workspace's copies, with
8272
/// their remotes pointing where the subrepos come from.
8273
#[test]
8274
fn a_workspace_added_on_a_bookmark_is_on_it_with_its_subrepos() {
8275
    hermetic();
8276
    let dir = tempfile::tempdir().unwrap();
8277
    let root = dir.path();
8278
    Repo::init(&root.join("lib-origin")).unwrap();
8279
    let lib_url = root.join("lib-origin").to_string_lossy().to_string();
8280
    let lib = Repo::clone(&lib_url, &root.join("lib"))
8281
        .unwrap()
8282
        .with_home(root.join("home"));
8283
    write(&root.join("lib"), "lib.txt", b"v1\n");
8284
    let l1 = lib.commit("lib v1", &[]).unwrap();
8285
    assert!(lib.push("origin", false).unwrap()[0].ok);
8286
8287
    let app_dir = root.join("app");
8288
    let app = Repo::init(&app_dir).unwrap().with_home(root.join("home"));
8289
    write(&app_dir, "main.txt", b"app\n");
8290
    app.submodule_add(&lib_url, "libs/lib", None).unwrap();
8291
    app.commit("app with lib", &[]).unwrap();
8292
    // A second bookmark, and the main workspace on another.
8293
    app.bookmark_create("develop", None).unwrap();
8294
    app.bookmark_create("feature", None).unwrap();
8295
    let mut app = app;
8296
    app.bookmark_switch("feature", false).unwrap();
8297
    assert_eq!(app.config.bookmark, "feature");
8298
8299
    // The library's origin goes away: the subrepo must come from here.
8300
    std::fs::rename(root.join("lib-origin"), root.join("lib-origin-gone")).unwrap();
8301
    let heads = app.resolve_heads("develop").unwrap();
8302
    let ws = app
8303
        .workspace_add_on(&root.join("ws"), Some(&heads), Some("develop"))
8304
        .unwrap();
8305
    assert_eq!(
8306
        ws.config.bookmark, "develop",
8307
        "the new workspace is on develop"
8308
    );
8309
    assert_eq!(
8310
        app.config.bookmark, "feature",
8311
        "and this one stays on its own"
8312
    );
8313
    let sub = Repo::open(&root.join("ws/libs/lib")).unwrap();
8314
    assert_eq!(
8315
        sub.config.remotes["origin"], lib_url,
8316
        "its origin is the subrepo's URL"
8317
    );
8318
    assert_eq!(sub.bookmark_heads().unwrap(), vec![l1], "at its pin");
8319
    assert_eq!(
8320
        std::fs::read(root.join("ws/libs/lib/lib.txt")).unwrap(),
8321
        b"v1\n"
8322
    );
8323
}
8324
8325
/// Revsets (docs/revset_query_language.md): symbols, relations, set
8326
/// operators and the predicates, over a small graph with two heads and
8327
/// a rename.
8328
#[test]
8329
fn revsets_select_changes_by_relation_author_text_date_and_path() {
8330
    hermetic();
8331
    let dir = tempfile::tempdir().unwrap();
8332
    let root = dir.path();
8333
    let mut repo = Repo::init(root).unwrap().with_home(root.join("home"));
8334
    repo.create_identity("Ada", "[email protected]", IdentityScope::User)
8335
        .unwrap();
8336
    write(root, "src/a.rs", b"one\n");
8337
    let a = repo.commit("first: add a", &[]).unwrap();
8338
    write(root, "src/a.rs", b"one\ntwo\n");
8339
    let b = repo.commit("second: grow a", &[]).unwrap();
8340
    // A second head, independent of b: a new file on top of a.
8341
    repo.checkout(&[a], false, "checkout a").unwrap();
8342
    write(root, "docs/notes.md", b"notes\n");
8343
    let c = repo.commit("third: notes", &[]).unwrap();
8344
    // Back to both heads, then rename a.rs: the node keeps its identity.
8345
    repo.checkout(&repo.bookmark_heads().unwrap(), false, "checkout main")
8346
        .unwrap();
8347
    fs::remove_file(root.join("src/a.rs")).unwrap();
8348
    write(root, "src/z.rs", b"one\ntwo\n");
8349
    let d = repo.commit("fourth: rename a to z", &[]).unwrap();
8350
    let wc = repo.working_copy().unwrap().0;
8351
    // A saved revset is checked when set.
8352
    repo.set_user_config("revset.mine", "author(me) & ::main")
8353
        .unwrap();
8354
    assert!(repo.set_user_config("revset.bad", "a &").is_err());
8355
    let set = |src: &str| -> Vec<ChangeHash> {
8356
        let mut v = repo.revset(src).unwrap().hashes;
8357
        v.sort();
8358
        v
8359
    };
8360
    let sorted = |hs: &[ChangeHash]| -> Vec<ChangeHash> {
8361
        let mut v = hs.to_vec();
8362
        v.sort();
8363
        v
8364
    };
8365
8366
    // Changes commute: a new file depends on nothing and the rename on the
8367
    // file's creation, so the graph is a, b->a, d->a, c, and the working
8368
    // copy on the three heads b, c, d.
8369
    let heads = sorted(&repo.bookmark_heads().unwrap());
8370
    let meta = |h: &ChangeHash| repo.store().get_change_meta(h).unwrap();
8371
    assert!(heads.contains(&d) && heads.contains(&c));
8372
    // Symbols and closures.
8373
    assert_eq!(set("main"), heads);
8374
    assert_eq!(set("::main"), sorted(&[a, b, c, d]));
8375
    assert_eq!(set("@"), vec![wc]);
8376
    assert_eq!(set("::@"), sorted(&[a, b, c, d, wc]));
8377
    assert_eq!(set(&format!("::#{}", b.short(12))), sorted(&[a, b]));
8378
    assert_eq!(set(&format!("#{}::", a.short(12))), sorted(&[a, b, d, wc]));
8379
    assert_eq!(
8380
        set(&format!("#{}::#{}", a.short(12), b.short(12))),
8381
        sorted(&[a, b])
8382
    );
8383
    // Ranges: what main has beyond b, and `..` forms.
8384
    assert_eq!(set(&format!("#{}..main", b.short(12))), sorted(&[c, d]));
8385
    assert_eq!(set(&format!("#{}..", c.short(12))), sorted(&[a, b, d, wc]));
8386
    assert_eq!(set("..main"), sorted(&[a, b, c, d]));
8387
    // Operators and precedence: ~ binds tighter than &, & than |.
8388
    assert_eq!(
8389
        set(&format!("::main ~ #{}", d.short(12))),
8390
        sorted(&[a, b, c])
8391
    );
8392
    assert_eq!(
8393
        set(&format!("::main & #{} | #{}", b.short(12), c.short(12))),
8394
        sorted(&[b, c])
8395
    );
8396
    assert_eq!(set("all() ~ ::main"), vec![wc]);
8397
    // Relations.
8398
    let mut head_deps: Vec<ChangeHash> = heads.iter().flat_map(|h| meta(h).deps).collect();
8399
    head_deps.sort();
8400
    head_deps.dedup();
8401
    assert_eq!(set("deps(main)"), head_deps);
8402
    let on_a: Vec<ChangeHash> = [b, c, d]
8403
        .into_iter()
8404
        .filter(|h| meta(h).deps.contains(&a))
8405
        .collect();
8406
    assert_eq!(set(&format!("dependents(#{})", a.short(12))), sorted(&on_a));
8407
    assert_eq!(set("heads(::main)"), heads);
8408
    assert_eq!(set("roots(::main)"), sorted(&[a, c]));
8409
    assert_eq!(
8410
        set(&format!(
8411
            "heads(#{} | #{} | #{})",
8412
            a.short(12),
8413
            b.short(12),
8414
            c.short(12)
8415
        )),
8416
        sorted(&[b, c])
8417
    );
8418
    assert_eq!(set("latest(::main, 1)"), vec![d]);
8419
    assert_eq!(set("kind(working-copy)"), vec![wc]);
8420
    assert_eq!(set("none()"), vec![]);
8421
    // Predicates: author by name, email, key prefix and `me`.
8422
    let key = repo.config.author_key.unwrap();
8423
    assert_eq!(set("author(ada) & ::main"), sorted(&[a, b, c, d]));
8424
    assert_eq!(set("author(\"[email protected]\") & ::main").len(), 4);
8425
    assert_eq!(set(&format!("author({}) & ::main", key.short(12))).len(), 4);
8426
    assert_eq!(set("author(me) & ::main").len(), 4);
8427
    assert_eq!(set("author(nobody)"), vec![]);
8428
    assert_eq!(set("description(notes)"), vec![c]);
8429
    assert_eq!(set("description(\"rename a\")"), vec![d]);
8430
    assert_eq!(set("date(-1h..) & ::main").len(), 4);
8431
    assert_eq!(set("date(..2000-01-01)"), vec![]);
8432
    // touches follows the node through the rename, in the current state.
8433
    assert_eq!(set("touches(\"src/z.rs\")"), sorted(&[a, b, d]));
8434
    assert_eq!(set("touches(\"src/**\") & ::main"), sorted(&[a, b, d]));
8435
    assert_eq!(set("touches(\"docs/*\")"), vec![c]);
8436
    assert_eq!(set("touches(\"nothing/*\")"), vec![]);
8437
    // Newest first in the result order.
8438
    assert_eq!(repo.revset("::main").unwrap().hashes[0], d);
8439
    // The saved revset, and errors that say what is wrong.
8440
    assert_eq!(set("mine()").len(), 4);
8441
    let e = repo.revset("nosuch()").unwrap_err().to_string();
8442
    assert!(e.contains("unknown function nosuch()"), "{e}");
8443
    let e = repo.revset("main &").unwrap_err().to_string();
8444
    assert!(e.contains("at character"), "{e}");
8445
    let e = repo.revset("zzzz").unwrap_err().to_string();
8446
    assert!(e.contains("no change matches"), "{e}");
8447
    let e = repo
8448
        .revset_with_budget("::main", std::time::Duration::ZERO)
8449
        .unwrap_err()
8450
        .to_string();
8451
    assert!(e.contains("budget"), "{e}");
8452
    // The log entries carry the bookmark's heads and the working copy.
8453
    let entries = repo.log_revset("::@").unwrap();
8454
    assert!(entries[0].is_working_copy && entries.iter().any(|e| e.is_head && e.hash == d));
8455
    // Trust predicates (§2.4): nothing is signed yet (core.sign = seal, no
8456
    // push); then a signed change, a tag, and a revocation.
8457
    assert_eq!(set("unsigned() & ::main"), sorted(&[a, b, c, d]));
8458
    assert_eq!(set("signed_by(me)"), vec![]);
8459
    repo.sign_change(&d).unwrap();
8460
    assert_eq!(set("signed_by(me)"), vec![d]);
8461
    assert_eq!(set("signed_by([email protected])"), vec![d]);
8462
    assert_eq!(set(&format!("signed_by({})", key.short(12))), vec![d]);
8463
    assert_eq!(set("unsigned() & ::main"), sorted(&[a, b, c]));
8464
    assert_eq!(set("delegated()"), vec![]);
8465
    assert_eq!(set("revoked()"), vec![]);
8466
    assert_eq!(set("attested(tag)"), vec![]);
8467
    repo.tag_create("v1", &[b], "first").unwrap();
8468
    assert_eq!(set("attested(tag)"), sorted(&[a, b]));
8469
    assert_eq!(set("attested(tag) & unsigned()"), sorted(&[a, b]));
8470
    assert_eq!(set("attested(receipt)"), vec![]);
8471
    assert_eq!(set("built(test)"), vec![]);
8472
    let e = repo.revset("attested(seal)").unwrap_err().to_string();
8473
    assert!(e.contains("tag, receipt or ref"), "{e}");
8474
    repo.revoke_identity(&key, "test").unwrap();
8475
    assert_eq!(set("revoked()"), vec![d]);
8476
    assert_eq!(set("signed_by(me) ~ revoked()"), vec![]);
8477
}
8478
8479
#[test]
8480
fn a_rotation_is_recorded_wherever_the_old_key_was_named() {
8481
    let dir = tempfile::tempdir().unwrap();
8482
    let root = dir.path();
8483
    let home = root.join("home");
8484
    // Ada's identity lives in the user file; repository `a` pins the same
8485
    // key in its own file, repository `b` names none.
8486
    let mut a = Repo::init(&root.join("a")).unwrap().with_home(&home);
8487
    let (key, _) = a
8488
        .create_identity("Ada", "[email protected]", IdentityScope::User)
8489
        .unwrap();
8490
    a.config.set("author.key", &key.to_hex()).unwrap();
8491
    a.save_config().unwrap();
8492
    let agent = SecretKey::generate().identity("Agent", "[email protected]", 1);
8493
    let r = a
8494
        .delegate_add(agent.clone(), crate::identity::Scope::CHANGES, None)
8495
        .unwrap();
8496
    assert_eq!(
8497
        read_config_file(&home.join("config.toml")).unwrap()["author.key"],
8498
        r.new.to_hex(),
8499
        "the user file follows"
8500
    );
8501
    assert_eq!(
8502
        read_config_file(&root.join("a/.oxy/config")).unwrap()["author.key"],
8503
        r.new.to_hex(),
8504
        "the pinning repository follows"
8505
    );
8506
    let b = Repo::init(&root.join("b")).unwrap().with_home(&home);
8507
    assert_eq!(
8508
        b.config.author_key,
8509
        Some(r.new),
8510
        "a checkout without a pin follows the user file"
8511
    );
8512
    // A repository-scoped identity leaves the user file alone.
8513
    let other_home = root.join("home2");
8514
    let mut c = Repo::init(&root.join("c")).unwrap().with_home(&other_home);
8515
    let (ck, _) = c
8516
        .create_identity("Cy", "[email protected]", IdentityScope::Repo)
8517
        .unwrap();
8518
    assert!(!other_home.join("config.toml").exists());
8519
    let r2 = c.rotate_identity().unwrap();
8520
    assert_ne!(r2.new, ck);
8521
    assert_eq!(
8522
        read_config_file(&root.join("c/.oxy/config")).unwrap()["author.key"],
8523
        r2.new.to_hex()
8524
    );
8525
    assert!(
8526
        !other_home.join("config.toml").exists(),
8527
        "a repository-scoped identity stays repository-scoped"
8528
    );
8529
    // Several delegates in one rotation; a repeat is refused.
8530
    let (d1, d2) = (
8531
        SecretKey::generate().identity("D1", "d1@x", 1),
8532
        SecretKey::generate().identity("D2", "d2@x", 1),
8533
    );
8534
    let r3 = c
8535
        .delegate_add_many(vec![d1.clone(), d2], crate::identity::Scope::CHANGES, None)
8536
        .unwrap();
8537
    assert_eq!(r3.identity.delegates.len(), 2);
8538
    assert!(c
8539
        .delegate_add(d1, crate::identity::Scope::CHANGES, None)
8540
        .is_err());
8541
}
8542
8543
/// Two unrelated histories that both add the same file, joined by two
8544
/// independent merges on two branches, then those branches merged: Git
8545
/// merges identical additions cleanly, and the import must too (#71,
8546
/// found in VS Code's history).
8547
#[test]
8548
fn git_import_joins_unrelated_histories_that_add_the_same_file() {
8549
    // Batches of one: every merge renders apart from the state, where a
8550
    // file whose graph the state had built came out empty (#71).
8551
    crate::repo::git::set_merge_batch_for_tests(Some(1));
8552
    hermetic();
8553
    if std::process::Command::new("git")
8554
        .arg("--version")
8555
        .output()
8556
        .is_err()
8557
    {
8558
        eprintln!("git not installed; skipping");
8559
        return;
8560
    }
8561
    let dir = tempfile::tempdir().unwrap();
8562
    let root = dir.path();
8563
    let g = root.join("src.git");
8564
    fs::create_dir_all(&g).unwrap();
8565
    let git = |args: &[&str]| -> String {
8566
        let out = std::process::Command::new("git")
8567
            .arg("-C")
8568
            .arg(&g)
8569
            .args([
8570
                "-c",
8571
                "user.name=Grace",
8572
                "-c",
8573
                "[email protected]",
8574
                "-c",
8575
                "commit.gpgsign=false",
8576
            ])
8577
            .args(args)
8578
            .output()
8579
            .unwrap();
8580
        assert!(
8581
            out.status.success(),
8582
            "git {args:?}: {}",
8583
            String::from_utf8_lossy(&out.stderr)
8584
        );
8585
        String::from_utf8_lossy(&out.stdout).trim().to_string()
8586
    };
8587
    let text = b"/* header */\nconst a = 1;\nconst b = 2;\n";
8588
    // History A: main.
8589
    git(&["init", "-q", "-b", "main"]);
8590
    write(&g, "gulpfile.js", text);
8591
    write(&g, "a.txt", b"a\n");
8592
    git(&["add", "."]);
8593
    git(&["commit", "-q", "-m", "A root"]);
8594
    // History B: an unrelated root adding the same file, identical.
8595
    git(&["checkout", "-q", "--orphan", "fork"]);
8596
    git(&["rm", "-q", "-r", "--cached", "."]);
8597
    for f in ["gulpfile.js", "a.txt"] {
8598
        let _ = fs::remove_file(g.join(f));
8599
    }
8600
    write(&g, "gulpfile.js", text);
8601
    write(&g, "b.txt", b"b\n");
8602
    git(&["add", "."]);
8603
    git(&["commit", "-q", "-m", "B root"]);
8604
    // Two branches from main, each joining B on its own.
8605
    git(&["checkout", "-q", "-b", "one", "main"]);
8606
    git(&[
8607
        "merge",
8608
        "-q",
8609
        "--no-ff",
8610
        "--allow-unrelated-histories",
8611
        "-m",
8612
        "join on one",
8613
        "fork",
8614
    ]);
8615
    git(&["checkout", "-q", "-b", "two", "main"]);
8616
    write(&g, "a.txt", b"a\ntwo\n");
8617
    git(&["commit", "-q", "-am", "work on two"]);
8618
    git(&[
8619
        "merge",
8620
        "-q",
8621
        "--no-ff",
8622
        "--allow-unrelated-histories",
8623
        "-m",
8624
        "join on two",
8625
        "fork",
8626
    ]);
8627
    // Then the two joins meet, and the file is reformatted after.
8628
    git(&["checkout", "-q", "main"]);
8629
    git(&["merge", "-q", "--no-ff", "-m", "merge one", "one"]);
8630
    git(&["merge", "-q", "--no-ff", "-m", "merge two", "two"]);
8631
    write(
8632
        &g,
8633
        "gulpfile.js",
8634
        b"/* header */\nconst a = 1;\nconst b = 3;\n",
8635
    );
8636
    git(&["commit", "-q", "-am", "after"]);
8637
8638
    let dest = root.join("dest");
8639
    let repo = Repo::init(&dest).unwrap().with_home(root.join("home"));
8640
    repo.import_git(&g, "main").unwrap();
8641
    let v = repo.verify_git_import(&g, "main").unwrap();
8642
    assert!(v.mismatches.is_empty(), "{:?}", v.mismatches);
8643
    assert_eq!(
8644
        fs::read(dest.join("gulpfile.js")).unwrap(),
8645
        b"/* header */\nconst a = 1;\nconst b = 3;\n"
8646
    );
8647
}
8648
8649
/// As above, but the two joins keep different copies (each branch had a
8650
/// different version when it joined), and later work edits each copy:
8651
/// the shape of VS Code's c67ef57cda90 (#71).
8652
#[test]
8653
fn git_import_joins_where_each_join_kept_a_different_copy() {
8654
    // Batches of one: every merge renders apart from the state, where a
8655
    // file whose graph the state had built came out empty (#71).
8656
    crate::repo::git::set_merge_batch_for_tests(Some(1));
8657
    hermetic();
8658
    if std::process::Command::new("git")
8659
        .arg("--version")
8660
        .output()
8661
        .is_err()
8662
    {
8663
        eprintln!("git not installed; skipping");
8664
        return;
8665
    }
8666
    let dir = tempfile::tempdir().unwrap();
8667
    let root = dir.path();
8668
    let g = root.join("src.git");
8669
    fs::create_dir_all(&g).unwrap();
8670
    let run = |args: &[&str]| {
8671
        std::process::Command::new("git")
8672
            .arg("-C")
8673
            .arg(&g)
8674
            .args([
8675
                "-c",
8676
                "user.name=Grace",
8677
                "-c",
8678
                "[email protected]",
8679
                "-c",
8680
                "commit.gpgsign=false",
8681
            ])
8682
            .args(args)
8683
            .output()
8684
            .unwrap()
8685
    };
8686
    let git = |args: &[&str]| -> String {
8687
        let out = run(args);
8688
        assert!(
8689
            out.status.success(),
8690
            "git {args:?}: {}",
8691
            String::from_utf8_lossy(&out.stderr)
8692
        );
8693
        String::from_utf8_lossy(&out.stdout).trim().to_string()
8694
    };
8695
    git(&["init", "-q", "-b", "main"]);
8696
    write(
8697
        &g,
8698
        "gulpfile.js",
8699
        b"/* header */\nconst a = 1;\nconst b = 2;\n",
8700
    );
8701
    git(&["add", "."]);
8702
    git(&["commit", "-q", "-m", "A root"]);
8703
    write(
8704
        &g,
8705
        "gulpfile.js",
8706
        b"/* header */\nconst a = 1;\n\nconst b = 2;\n",
8707
    );
8708
    git(&["commit", "-q", "-am", "whitespace"]);
8709
    git(&["checkout", "-q", "--orphan", "fork"]);
8710
    git(&["rm", "-q", "-r", "--cached", "."]);
8711
    let _ = fs::remove_file(g.join("gulpfile.js"));
8712
    write(
8713
        &g,
8714
        "gulpfile.js",
8715
        b"/* header */\nconst a = 1;\nconst b = 2;\nconst c = 3;\n",
8716
    );
8717
    git(&["add", "."]);
8718
    git(&["commit", "-q", "-m", "B root"]);
8719
    // Branch one joins B keeping main's copy; branch two keeps B's.
8720
    for (branch, keep) in [("one", "ours"), ("two", "theirs")] {
8721
        git(&["checkout", "-q", "-b", branch, "main"]);
8722
        let _ = run(&[
8723
            "merge",
8724
            "-q",
8725
            "--no-ff",
8726
            "--allow-unrelated-histories",
8727
            "-m",
8728
            "join",
8729
            "fork",
8730
        ]);
8731
        git(&["checkout", &format!("--{keep}"), "gulpfile.js"]);
8732
        git(&["add", "gulpfile.js"]);
8733
        git(&["commit", "-q", "-m", &format!("join on {branch}")]);
8734
    }
8735
    // Each branch then edits its copy.
8736
    git(&["checkout", "-q", "one"]);
8737
    write(
8738
        &g,
8739
        "gulpfile.js",
8740
        b"/* header */\nconst a = 1;\n\nconst b = 2;\n// tslint\n",
8741
    );
8742
    git(&["commit", "-q", "-am", "tslint on one"]);
8743
    git(&["checkout", "-q", "two"]);
8744
    write(
8745
        &g,
8746
        "gulpfile.js",
8747
        b"/* header */\nconst a = 1;\nconst b = 2;\nconst c = 3;\n// fmt\n",
8748
    );
8749
    write(&g, "extra.txt", b"x\n");
8750
    write(&g, "more.txt", b"m\n");
8751
    git(&["add", "."]);
8752
    git(&["commit", "-q", "-am", "fmt on two"]);
8753
    // They meet: resolved by hand.
8754
    git(&["checkout", "-q", "one"]);
8755
    let _ = run(&["merge", "-q", "--no-ff", "-m", "merge two", "two"]);
8756
    write(
8757
        &g,
8758
        "gulpfile.js",
8759
        b"/* header */\nconst a = 1;\nconst b = 2;\nconst c = 3;\n// tslint\n// fmt\n",
8760
    );
8761
    git(&["add", "gulpfile.js"]);
8762
    git(&["commit", "-q", "-m", "merge two into one"]);
8763
8764
    let dest = root.join("dest");
8765
    let repo = Repo::init(&dest).unwrap().with_home(root.join("home"));
8766
    repo.import_git(&g, "one").unwrap();
8767
    let v = repo.verify_git_import(&g, "one").unwrap();
8768
    assert!(v.mismatches.is_empty(), "{:?}", v.mismatches);
8769
}
8770
8771
/// oxygen#68: on a store that is not this disk's directory, the operation
8772
/// head is the store's reference record, moved by compare-and-swap. Two
8773
/// handles recording from the same head both get through, merged; a swap
8774
/// from a stale version is refused; a second repository cannot start on a
8775
/// store that already holds one.
8776
#[test]
8777
fn over_a_store_the_operation_head_moves_by_compare_and_swap() {
8778
    use crate::strata::{MemoryStore, Store as _};
8779
    let backend = std::sync::Arc::new(MemoryStore::new());
8780
    crate::store::TEST_BACKEND.with(|t| *t.borrow_mut() = Some(backend.clone()));
8781
    let dir = tempfile::tempdir().unwrap();
8782
    let a = Repo::init(dir.path()).unwrap();
8783
    assert!(
8784
        !dir.path().join(".oxy/ops/head").exists(),
8785
        "the head is not a file"
8786
    );
8787
    let (h0, op0) = a.head_op().unwrap();
8788
    let record = backend
8789
        .read_ref(HEAD_RECORD)
8790
        .unwrap()
8791
        .expect("the head is the store's record");
8792
    assert_eq!(String::from_utf8(record.0).unwrap(), h0.to_hex());
8793
8794
    let b = Repo::open(dir.path()).unwrap();
8795
    let state = a.store.put_state(&StateObject::new(vec![])).unwrap();
8796
    let mut va = op0.view.clone();
8797
    va.bookmarks.insert("from-a".into(), state);
8798
    let mut vb = op0.view.clone();
8799
    vb.bookmarks.insert("from-b".into(), state);
8800
    let rb = b.record_op(&[h0], "bookmark from-b", vb).unwrap();
8801
    assert_eq!(b.head_ref().unwrap(), rb);
8802
    // a recorded from h0 too: the head moved, so the two are merged.
8803
    let ra = a.record_op(&[h0], "bookmark from-a", va).unwrap();
8804
    let (head, op) = Repo::open(dir.path()).unwrap().head_op().unwrap();
8805
    assert_eq!(head, ra);
8806
    assert!(
8807
        op.command.ends_with("(merged with a concurrent operation)"),
8808
        "{}",
8809
        op.command
8810
    );
8811
    assert_eq!(op.parents, vec![rb, op.parents[1]]);
8812
    assert!(op.view.bookmarks.contains_key("from-a") && op.view.bookmarks.contains_key("from-b"));
8813
8814
    // A swap from a version that is no longer current moves nothing.
8815
    let (h, v) = a.read_head().unwrap();
8816
    assert!(b.swap_head(&rb, v.as_ref()).unwrap());
8817
    assert!(!a.swap_head(&h, v.as_ref()).unwrap(), "stale");
8818
    a.refresh().unwrap();
8819
    assert_eq!(a.head_ref().unwrap(), rb);
8820
8821
    let other = tempfile::tempdir().unwrap();
8822
    let err = Repo::init(other.path())
8823
        .err()
8824
        .expect("the store already holds a log")
8825
        .to_string();
8826
    assert!(
8827
        err.contains("already holds a repository's operation log"),
8828
        "{err}"
8829
    );
8830
    crate::store::TEST_BACKEND.with(|t| *t.borrow_mut() = None);
8831
}
8832
8833
/// oxygen#68: a repository kept on a store (`storage.url`) holds its
8834
/// objects and operation head there, with `.oxy/cache` in front: it works
8835
/// as one on disk does, reopens, and survives losing its cache.
8836
#[test]
8837
fn a_repository_runs_on_a_store_with_a_cache_in_front() {
8838
    hermetic();
8839
    if std::env::var_os("OXY_STORE_BACKEND").is_some() {
8840
        return;
8841
    }
8842
    let dir = tempfile::tempdir().unwrap();
8843
    let (root, bucket) = (dir.path().join("work"), dir.path().join("bucket"));
8844
    let url = format!("dir://{}", bucket.display());
8845
    let repo = Repo::init_on(&root, [7; 16], Some(&url)).unwrap();
8846
    assert_eq!(repo.config.storage_url.as_deref(), Some(url.as_str()));
8847
    write(&root, "a.txt", b"one\n");
8848
    let h1 = repo.commit("First", &[]).unwrap();
8849
    write(&root, "a.txt", b"one\ntwo\n");
8850
    let h2 = repo.commit("Second", &[]).unwrap();
8851
    assert!(
8852
        !root.join(".oxy/ops/head").exists(),
8853
        "the head is in the store"
8854
    );
8855
    assert!(bucket.join("ops/head").is_file());
8856
    assert!(root.join(".oxy/cache").is_dir());
8857
    drop(repo);
8858
8859
    // Reopened, and again with no cache at all: everything comes from the store.
8860
    for drop_cache in [false, true] {
8861
        if drop_cache {
8862
            std::fs::remove_dir_all(root.join(".oxy/cache")).unwrap();
8863
        }
8864
        let repo = Repo::open(&root).unwrap();
8865
        let log: Vec<String> = repo
8866
            .op_log()
8867
            .unwrap()
8868
            .into_iter()
8869
            .map(|(_, op)| op.command)
8870
            .collect();
8871
        assert!(log.len() >= 3, "{log:?}");
8872
        assert_eq!(repo.store().get_change(&h1).unwrap().message, "First");
8873
        let heads = repo
8874
            .store()
8875
            .get_state(&repo.view().unwrap().bookmarks["main"])
8876
            .unwrap()
8877
            .heads;
8878
        assert_eq!(heads, vec![h2]);
8879
        assert_eq!(
8880
            repo.load_state(&heads).unwrap().materialize().files.len(),
8881
            1
8882
        );
8883
    }
8884
8885
    // A second repository cannot start on the same store.
8886
    let err = Repo::init_on(&dir.path().join("other"), [8; 16], Some(&url))
8887
        .err()
8888
        .unwrap()
8889
        .to_string();
8890
    assert!(
8891
        err.contains("already holds a repository's operation log"),
8892
        "{err}"
8893
    );
8894
    let err = Repo::init_on(&dir.path().join("third"), [9; 16], Some("nope://x"))
8895
        .err()
8896
        .unwrap()
8897
        .to_string();
8898
    assert!(err.contains("cannot open that kind of store"), "{err}");
8899
}
8900
8901
/// oxygen#75: the prompt's quick check agrees with status in a repository
8902
/// with a subrepo: clean after a commit, dirty when the subrepo moves to
8903
/// another state, clean again once that pin is committed. (It compared the
8904
/// subrepo's directory as if it were a file, so it was always dirty.)
8905
#[test]
8906
fn the_quick_dirty_check_compares_a_subrepo_by_its_pin() {
8907
    hermetic();
8908
    let dir = tempfile::tempdir().unwrap();
8909
    let root = dir.path();
8910
    let _lib_origin = Repo::init(&root.join("lib-origin")).unwrap();
8911
    let lib_url = root.join("lib-origin").to_string_lossy().to_string();
8912
    let lib = Repo::clone(&lib_url, &root.join("lib"))
8913
        .unwrap()
8914
        .with_home(root.join("home"));
8915
    write(&root.join("lib"), "lib.txt", b"v1\n");
8916
    lib.commit("lib v1", &[]).unwrap();
8917
    assert!(lib.push("origin", false).unwrap()[0].ok);
8918
    let app_dir = root.join("app");
8919
    let app = Repo::init(&app_dir).unwrap().with_home(root.join("home"));
8920
    write(&app_dir, "main.txt", b"app\n");
8921
    app.submodule_add(&lib_url, "libs/lib", None).unwrap();
8922
    app.commit("app with lib", &[]).unwrap();
8923
    // Out of the racy window, so the stat-only path decides.
8924
    std::thread::sleep(std::time::Duration::from_millis(2100));
8925
    let reopen = || Repo::open(&app_dir).unwrap();
8926
    assert_eq!(
8927
        reopen().quick_dirty().unwrap(),
8928
        Some(false),
8929
        "clean, as status says"
8930
    );
8931
    let nested = Repo::open(&app_dir.join("libs/lib")).unwrap();
8932
    write(&app_dir.join("libs/lib"), "lib.txt", b"v2\n");
8933
    nested.commit("lib v2", &[]).unwrap();
8934
    assert_eq!(
8935
        reopen().quick_dirty().unwrap(),
8936
        Some(true),
8937
        "the subrepo moved"
8938
    );
8939
    reopen().commit("pin lib v2", &[]).unwrap();
8940
    std::thread::sleep(std::time::Duration::from_millis(2100));
8941
    assert_eq!(
8942
        reopen().quick_dirty().unwrap(),
8943
        Some(false),
8944
        "the new pin is committed"
8945
    );
8946
}
8947
8948
#[test]
8949
fn a_module_entry_that_was_never_added_is_reported_as_unpinned() {
8950
    // oxygen#72: a .oxymodules section with no subrepo behind it.
8951
    hermetic();
8952
    let dir = tempfile::tempdir().unwrap();
8953
    let root = dir.path();
8954
    let _lib_origin = Repo::init(&root.join("lib-origin")).unwrap();
8955
    let lib_url = root.join("lib-origin").to_string_lossy().to_string();
8956
    let lib = Repo::clone(&lib_url, &root.join("lib"))
8957
        .unwrap()
8958
        .with_home(root.join("home"));
8959
    write(&root.join("lib"), "lib.txt", b"v1\n");
8960
    lib.commit("lib v1", &[]).unwrap();
8961
    assert!(lib.push("origin", false).unwrap()[0].ok);
8962
    let app_dir = root.join("app");
8963
    let app = Repo::init(&app_dir).unwrap().with_home(root.join("home"));
8964
    write(
8965
        &app_dir,
8966
        ".oxymodules",
8967
        format!("[libs/lib]\nurl = {lib_url}\n").as_bytes(),
8968
    );
8969
    let unpinned = app.unpinned_modules().unwrap();
8970
    assert_eq!(unpinned.len(), 1);
8971
    assert_eq!(unpinned[0].0, "libs/lib");
8972
    assert_eq!(unpinned[0].1.url, lib_url);
8973
    assert!(app.submodule_update(true, &[]).unwrap().is_empty());
8974
    app.submodule_add(&lib_url, "libs/lib", None).unwrap();
8975
    assert!(app.unpinned_modules().unwrap().is_empty(), "added now");
8976
}
8977
8978
#[test]
8979
fn the_bookmark_revset_function_names_only_bookmarks() {
8980
    // oxygen#73: bookmark(NAME) is a bookmark's heads, never a tag or prefix.
8981
    hermetic();
8982
    let dir = tempfile::tempdir().unwrap();
8983
    let repo = Repo::init(dir.path()).unwrap();
8984
    write(dir.path(), "a.txt", b"a\n");
8985
    let a = repo.commit("A", &[]).unwrap();
8986
    write(dir.path(), "b.txt", b"b\n");
8987
    let b = repo.commit("B", &[]).unwrap();
8988
    let mut heads = repo.revset("bookmark(main)").unwrap().hashes;
8989
    heads.sort();
8990
    let mut want = repo.bookmark_heads().unwrap();
8991
    want.sort();
8992
    assert_eq!(heads, want);
8993
    assert!(heads.contains(&b));
8994
    assert_eq!(repo.revset("main").unwrap().hashes.len(), heads.len());
8995
    // A change prefix is a symbol, not a bookmark.
8996
    let prefix = repo.store().get_change_meta(&a).unwrap().change_id.short(8);
8997
    assert!(repo.revset(&prefix).is_ok());
8998
    let e = repo
8999
        .revset(&format!("bookmark({prefix})"))
9000
        .unwrap_err()
9001
        .to_string();
9002
    assert!(e.contains("no such bookmark"), "{e}");
9003
}
9004
9005
#[test]
9006
fn carrying_work_over_a_subrepo_already_at_the_target_pin_is_no_conflict() {
9007
    // oxygen#74: a stale state with .oxymodules but no pin, a newer one
9008
    // pinning the subrepo, and the nested repository on disk at that pin.
9009
    hermetic();
9010
    let dir = tempfile::tempdir().unwrap();
9011
    let root = dir.path();
9012
    let _lib_origin = Repo::init(&root.join("lib-origin")).unwrap();
9013
    let lib_url = root.join("lib-origin").to_string_lossy().to_string();
9014
    let lib = Repo::clone(&lib_url, &root.join("lib"))
9015
        .unwrap()
9016
        .with_home(root.join("home"));
9017
    write(&root.join("lib"), "lib.txt", b"v1\n");
9018
    lib.commit("lib v1", &[]).unwrap();
9019
    assert!(lib.push("origin", false).unwrap()[0].ok);
9020
    let app_dir = root.join("app");
9021
    let app = Repo::init(&app_dir).unwrap().with_home(root.join("home"));
9022
    write(&app_dir, "main.txt", b"app\n");
9023
    app.submodule_add(&lib_url, "libs/lib", None).unwrap();
9024
    // The stale state: registered in .oxymodules, never pinned.
9025
    fs::rename(app_dir.join("libs/lib"), root.join("aside")).unwrap();
9026
    app.commit("initial", &[]).unwrap();
9027
    let stale = app.bookmark_heads().unwrap();
9028
    fs::rename(root.join("aside"), app_dir.join("libs/lib")).unwrap();
9029
    app.commit("pin lib", &[]).unwrap();
9030
    let newer = app.bookmark_heads().unwrap();
9031
    app.checkout(&stale, false, "test").unwrap();
9032
    write(&app_dir, "notes.txt", b"mine\n");
9033
    let (_, carried) = app.checkout_carry(&newer, "main", "test").unwrap();
9034
    assert_eq!(carried, vec!["notes.txt".to_string()]);
9035
    assert!(app_dir.join("notes.txt").exists());
9036
}
9037
9038
#[test]
9039
fn a_bookmark_only_behind_its_remote_catches_up() {
9040
    // oxygen#74: switch takes the remote's state rather than a stale one.
9041
    hermetic();
9042
    let dir = tempfile::tempdir().unwrap();
9043
    let root = dir.path();
9044
    let _origin = Repo::init(&root.join("origin")).unwrap();
9045
    let url = root.join("origin").to_string_lossy().to_string();
9046
    let one = Repo::clone(&url, &root.join("one"))
9047
        .unwrap()
9048
        .with_home(root.join("home"));
9049
    write(&root.join("one"), "a.txt", b"a\n");
9050
    one.commit("A", &[]).unwrap();
9051
    assert!(one.push("origin", false).unwrap()[0].ok);
9052
    let two = Repo::clone(&url, &root.join("two"))
9053
        .unwrap()
9054
        .with_home(root.join("home"));
9055
    write(&root.join("two"), "b.txt", b"b\n");
9056
    two.commit("B", &[]).unwrap();
9057
    assert!(two.push("origin", false).unwrap()[0].ok);
9058
    assert_eq!(one.catch_up_bookmark("main").unwrap(), None, "not fetched");
9059
    one.fetch("origin").unwrap();
9060
    assert_eq!(one.catch_up_bookmark("main").unwrap(), Some(1));
9061
    assert_eq!(one.bookmarks().unwrap()[0].behind, Some(0));
9062
    // Local work the remote lacks: left alone.
9063
    write(&root.join("one"), "c.txt", b"c\n");
9064
    one.commit("C", &[]).unwrap();
9065
    write(&root.join("two"), "d.txt", b"d\n");
9066
    two.commit("D", &[]).unwrap();
9067
    assert!(two.push("origin", false).unwrap()[0].ok);
9068
    one.fetch("origin").unwrap();
9069
    assert_eq!(one.catch_up_bookmark("main").unwrap(), None);
9070
}
9071
9072
#[test]
9073
fn a_bookmark_is_compared_with_a_remote_that_has_it_when_there_is_no_origin() {
9074
    // oxygen#83: remotes earth and gcs, origin removed.
9075
    hermetic();
9076
    let dir = tempfile::tempdir().unwrap();
9077
    let root = dir.path();
9078
    let _up = Repo::init(&root.join("up")).unwrap();
9079
    let url = root.join("up").to_string_lossy().to_string();
9080
    let other = Repo::clone(&url, &root.join("other"))
9081
        .unwrap()
9082
        .with_home(root.join("home"));
9083
    write(&root.join("other"), "a.txt", b"a\n");
9084
    other.commit("a", &[]).unwrap();
9085
    assert!(other.push("origin", false).unwrap()[0].ok);
9086
    let mut one = Repo::clone(&url, &root.join("one"))
9087
        .unwrap()
9088
        .with_home(root.join("home"));
9089
    one.config.set("remote.earth.url", &url).unwrap();
9090
    one.config.set("remote.gcs.url", &url).unwrap();
9091
    one.config.set("remote.origin.url", "").unwrap();
9092
    one.save_config().unwrap();
9093
    write(&root.join("other"), "b.txt", b"b\n");
9094
    other.commit("b", &[]).unwrap();
9095
    assert!(other.push("origin", false).unwrap()[0].ok);
9096
    one.fetch("earth").unwrap();
9097
    let b = one
9098
        .bookmarks()
9099
        .unwrap()
9100
        .into_iter()
9101
        .find(|b| b.name == "main")
9102
        .unwrap();
9103
    assert_eq!(
9104
        (b.remote.as_deref(), b.behind),
9105
        (Some("earth"), Some(1)),
9106
        "a stale origin copy is not used"
9107
    );
9108
    assert_eq!(
9109
        one.default_remote(),
9110
        "origin",
9111
        "no default chosen among several"
9112
    );
9113
    let e = one.pull(&one.default_remote()).unwrap_err().to_string();
9114
    assert!(e.contains("earth, gcs") && e.contains("core.remote"), "{e}");
9115
    one.config.set("core.remote", "earth").unwrap();
9116
    assert_eq!(one.default_remote(), "earth");
9117
}
9118
9119
#[test]
9120
fn a_missing_author_identity_says_how_to_fix_it() {
9121
    // oxygen#82: an agent home's author.key naming an identity the
9122
    // repository does not hold.
9123
    hermetic();
9124
    let dir = tempfile::tempdir().unwrap();
9125
    let mut repo = Repo::init(dir.path()).unwrap();
9126
    let missing = KeyId::from_hex(&"ab".repeat(32)).unwrap();
9127
    repo.config.set("author.key", &missing.to_hex()).unwrap();
9128
    let e = repo.identity(&missing).unwrap_err().to_string();
9129
    assert!(
9130
        e.contains("this repository has no identity") && e.contains("oxy config author.key"),
9131
        "{e}"
9132
    );
9133
    assert!(e.contains("this repository's config"), "{e}");
9134
}
9135
9136
#[test]
9137
fn a_working_copy_behind_its_bookmark_is_flagged_and_pull_brings_it_up() {
9138
    // oxygen#89 (supermarioland, 2026-10-09): the bookmark moved on without
9139
    // the working copy, a pull with nothing new left it there, and status
9140
    // said "clean".
9141
    hermetic();
9142
    let dir = tempfile::tempdir().unwrap();
9143
    let root = dir.path();
9144
    let _up = Repo::init(&root.join("up")).unwrap();
9145
    let url = root.join("up").to_string_lossy().to_string();
9146
    let other = Repo::clone(&url, &root.join("other"))
9147
        .unwrap()
9148
        .with_home(root.join("home"));
9149
    write(&root.join("other"), "a.txt", b"a\n");
9150
    other.commit("a", &[]).unwrap();
9151
    assert!(other.push("origin", false).unwrap()[0].ok);
9152
    let one = Repo::clone(&url, &root.join("one"))
9153
        .unwrap()
9154
        .with_home(root.join("home"));
9155
    write(&root.join("other"), "b.txt", b"b\n");
9156
    other.commit("b", &[]).unwrap();
9157
    assert!(other.push("origin", false).unwrap()[0].ok);
9158
    one.fetch("origin").unwrap();
9159
    // The bookmark moves; the working copy does not.
9160
    let theirs = one.resolve_heads("origin/main").unwrap();
9161
    one.bookmark_set("main", &theirs).unwrap();
9162
    assert!(!root.join("one/b.txt").exists());
9163
    assert_eq!(one.working_copy_behind().unwrap(), Some(1));
9164
    let r = one.pull("origin").unwrap();
9165
    assert!(
9166
        !r.changed && r.checked_out,
9167
        "nothing new, but the working copy caught up"
9168
    );
9169
    assert!(root.join("one/b.txt").exists());
9170
    assert_eq!(one.working_copy_behind().unwrap(), None);
9171
}
9172
9173
#[test]
9174
fn touched_nodes_cache_answers_as_the_changes_do() {
9175
    hermetic();
9176
    let dir = tempfile::tempdir().unwrap();
9177
    let repo = Repo::init(dir.path()).unwrap();
9178
    write(dir.path(), "a.txt", b"one\n");
9179
    write(dir.path(), "b.txt", b"x\n");
9180
    repo.snapshot("t").unwrap();
9181
    let c1 = repo.commit("first", &[]).unwrap();
9182
    write(dir.path(), "b.txt", b"y\n");
9183
    repo.snapshot("t").unwrap();
9184
    repo.commit("b only", &[]).unwrap();
9185
    fs::rename(dir.path().join("a.txt"), dir.path().join("c.txt")).unwrap();
9186
    write(dir.path(), "c.txt", b"one\ntwo\n");
9187
    repo.snapshot("t").unwrap();
9188
    let c3 = repo.commit("rename and edit", &[]).unwrap();
9189
    // Uncommitted work, so the working copy touches a file too.
9190
    write(dir.path(), "c.txt", b"one\ntwo\nthree\n");
9191
    repo.snapshot("t").unwrap();
9192
9193
    let path = dir.path().join(".oxy/index/touched");
9194
    let hashes = |es: Vec<LogEntry>| es.iter().map(|e| e.hash).collect::<Vec<_>>();
9195
    let cold = hashes(repo.log_for_path("c.txt").unwrap());
9196
    assert!(path.exists(), "the first query writes the cache");
9197
    let warm = hashes(repo.log_for_path("c.txt").unwrap());
9198
    assert_eq!(cold, warm, "the cache answers as the changes do");
9199
    let (wc, _) = repo.working_copy().unwrap();
9200
    assert_eq!(
9201
        cold,
9202
        vec![wc, c3, c1],
9203
        "renames followed, the working copy included"
9204
    );
9205
9206
    // Working-copy changes are not kept: they are replaced by every snapshot.
9207
    let cached = super::touched::read_touched_for_test(&fs::read(&path).unwrap()).unwrap();
9208
    assert!(!cached.contains(&wc), "a working-copy change is not cached");
9209
    assert!(cached.contains(&c1) && cached.contains(&c3));
9210
9211
    // A damaged cache is ignored, not trusted.
9212
    let mut bytes = fs::read(&path).unwrap();
9213
    let last = bytes.len() - 40;
9214
    bytes[last] ^= 1;
9215
    fs::write(&path, &bytes).unwrap();
9216
    assert_eq!(hashes(repo.log_for_path("c.txt").unwrap()), cold);
9217
    let touches = repo.log_revset("touches(\"c.txt\") ~ @").unwrap();
9218
    assert_eq!(hashes(touches), vec![c3, c1]);
9219
}
9220
9221
/// oxygen#88 (vscode 9ab2056393c8): two lines of history that each move a
9222
/// file back where it was leave two placements at one place, which the
9223
/// tree shows as one file. Removing it, and then its directory, retires
9224
/// both, so no copy is left under a directory that is gone.
9225
#[test]
9226
fn git_import_removes_every_copy_of_a_file_at_one_place() {
9227
    hermetic();
9228
    if std::process::Command::new("git")
9229
        .arg("--version")
9230
        .output()
9231
        .is_err()
9232
    {
9233
        eprintln!("git not installed; skipping");
9234
        return;
9235
    }
9236
    let dir = tempfile::tempdir().unwrap();
9237
    let root = dir.path();
9238
    let g = root.join("src.git");
9239
    fs::create_dir_all(&g).unwrap();
9240
    let git = |args: &[&str]| {
9241
        let out = std::process::Command::new("git")
9242
            .arg("-C")
9243
            .arg(&g)
9244
            .args([
9245
                "-c",
9246
                "user.name=Grace",
9247
                "-c",
9248
                "[email protected]",
9249
                "-c",
9250
                "commit.gpgsign=false",
9251
            ])
9252
            .args(args)
9253
            .output()
9254
            .unwrap();
9255
        assert!(
9256
            out.status.success(),
9257
            "git {args:?}: {}",
9258
            String::from_utf8_lossy(&out.stderr)
9259
        );
9260
    };
9261
    git(&["init", "-q", "-b", "main"]);
9262
    write(&g, "d/list.txt", b"one\ntwo\nthree\nfour\n");
9263
    write(&g, "keep.txt", b"k\n");
9264
    git(&["add", "."]);
9265
    git(&["commit", "-qm", "base"]);
9266
    fs::create_dir_all(g.join("d/sub")).unwrap();
9267
    git(&["mv", "d/list.txt", "d/sub/list.txt"]);
9268
    git(&["commit", "-qm", "into sub"]);
9269
    git(&["checkout", "-qb", "side"]);
9270
    git(&["mv", "d/sub/list.txt", "d/list.txt"]);
9271
    git(&["commit", "-qm", "back, on side"]);
9272
    git(&["checkout", "-q", "main"]);
9273
    git(&["mv", "d/sub/list.txt", "d/list.txt"]);
9274
    git(&["commit", "-qm", "back, on main"]);
9275
    git(&["merge", "-q", "--no-edit", "side"]);
9276
    git(&["rm", "-rq", "d"]);
9277
    git(&["commit", "-qm", "d goes"]);
9278
9279
    let repo = Repo::init(&root.join("o")).unwrap();
9280
    repo.import_git(&g, "main").unwrap();
9281
    let v = repo.verify_git_import(&g, "main").unwrap();
9282
    assert!(v.mismatches.is_empty(), "{:?}", v.mismatches);
9283
    let st = repo
9284
        .load_state_history(&repo.bookmark_heads().unwrap())
9285
        .unwrap();
9286
    let view = st.tree().view();
9287
    assert!(view.conflicts.is_empty(), "{:?}", view.conflicts);
9288
    assert_eq!(view.entries.keys().collect::<Vec<_>>(), vec!["keep.txt"]);
9289
}
9290
9291
/// oxygen#94: a state index's file histories are read, and checked by
9292
/// their own hashes, only when a file is built. One found damaged is an
9293
/// error that says so, the index is removed, and the next read rebuilds it.
9294
#[test]
9295
fn a_damaged_file_history_in_the_state_index_is_rebuilt() {
9296
    hermetic();
9297
    let dir = tempfile::tempdir().unwrap();
9298
    let repo = Repo::init(dir.path()).unwrap();
9299
    for i in 0..6 {
9300
        write(
9301
            dir.path(),
9302
            &format!("f{i}.txt"),
9303
            format!("one {i}\n").as_bytes(),
9304
        );
9305
    }
9306
    repo.snapshot("t").unwrap();
9307
    repo.commit("first", &[]).unwrap();
9308
    for i in 0..6 {
9309
        write(
9310
            dir.path(),
9311
            &format!("f{i}.txt"),
9312
            format!("one {i}\ntwo\n").as_bytes(),
9313
        );
9314
    }
9315
    repo.snapshot("t").unwrap();
9316
    repo.commit("second", &[]).unwrap();
9317
    let want: Vec<Vec<u8>> = (0..6)
9318
        .map(|i| format!("one {i}\ntwo\n").into_bytes())
9319
        .collect();
9320
    // The index of the working copy's base, holding every file's history
9321
    // (a few changes behind, an index is replayed onto, not rewritten).
9322
    let (_, wc) = repo.working_copy().unwrap();
9323
    let base = repo.load_state_history(&wc.deps).unwrap();
9324
    repo.write_state_index(&wc.deps, &base);
9325
    for (i, w) in want.iter().enumerate() {
9326
        assert_eq!(&repo.file_at(&format!("f{i}.txt"), None).unwrap(), w);
9327
    }
9328
    let index = repo.state_indexes();
9329
    assert!(!index.is_empty(), "a state index was written");
9330
    // The histories are last in the file: damage the last of them.
9331
    let mut bytes = fs::read(&index[0]).unwrap();
9332
    let last = bytes.len() - 1;
9333
    bytes[last] ^= 0x40;
9334
    fs::write(&index[0], &bytes).unwrap();
9335
9336
    let reads: Vec<_> = (0..6)
9337
        .map(|i| repo.file_at(&format!("f{i}.txt"), None))
9338
        .collect();
9339
    let damaged: Vec<String> = reads
9340
        .iter()
9341
        .filter_map(|r| r.as_ref().err().map(|e| e.to_string()))
9342
        .collect();
9343
    assert_eq!(damaged.len(), 1, "{damaged:?}");
9344
    assert!(
9345
        damaged[0].contains("state index was damaged")
9346
            && damaged[0].contains("run the command again"),
9347
        "{}",
9348
        damaged[0]
9349
    );
9350
    // Every file reads right again, from an index rebuilt from history.
9351
    for (i, w) in want.iter().enumerate() {
9352
        assert_eq!(&repo.file_at(&format!("f{i}.txt"), None).unwrap(), w);
9353
    }
9354
}
9355
9356
/// oxygen#95: a push longer than `push.batch-bytes` goes in parts, each
9357
/// objects alone and in dependency order, and the last moves the bookmark.
9358
/// The remote ends with every change and the same state, and says how each
9359
/// part went.
9360
#[test]
9361
fn a_long_push_goes_in_parts() {
9362
    hermetic();
9363
    let dir = tempfile::tempdir().unwrap();
9364
    let root = dir.path();
9365
    let origin = root.join("origin");
9366
    Repo::init_bare_unbound(&origin).unwrap();
9367
    let main = root.join("main");
9368
    let mut repo = Repo::init(&main).unwrap();
9369
    repo.config
9370
        .set("remote.origin.url", &origin.to_string_lossy())
9371
        .unwrap();
9372
    // One byte: every change is a part of its own.
9373
    repo.config.set("push.batch-bytes", "1").unwrap();
9374
    repo.save_config().unwrap();
9375
    for i in 0..6 {
9376
        write(
9377
            &main,
9378
            &format!("f{i}.txt"),
9379
            format!("file {i}\n").as_bytes(),
9380
        );
9381
        repo.commit(&format!("c{i}"), &[]).unwrap();
9382
    }
9383
    let mut parts = Vec::new();
9384
    let results = repo
9385
        .push_bookmark_with("origin", "main", false, &mut |m| parts.push(m.to_string()))
9386
        .unwrap();
9387
    assert!(
9388
        results.iter().any(|r| r.ok && r.name == "main"),
9389
        "{results:?}"
9390
    );
9391
    assert_eq!(parts.len(), 6, "{parts:?}");
9392
    assert_eq!(parts[0], "part 1 of 6: 1 changes");
9393
9394
    let remote = Repo::open(&origin).unwrap();
9395
    let heads = repo.bookmark_heads().unwrap();
9396
    assert_eq!(remote.bookmark_heads().unwrap(), heads);
9397
    assert_eq!(
9398
        remote.log_state(&heads).unwrap().len(),
9399
        repo.log_state(&heads).unwrap().len()
9400
    );
9401
    // A push of objects alone reports how it went, as `objects`.
9402
    let got = remote
9403
        .receive_push(Bundle::default(), vec![], None, vec![])
9404
        .unwrap();
9405
    assert_eq!(got.len(), 1);
9406
    assert!(got[0].ok && got[0].name == OBJECTS_RESULT, "{got:?}");
9407
}
9408
9409
/// oxygen#133: one change whose blobs pass `push.batch-bytes` sends them
9410
/// first, in parts of objects alone, so no request is larger than about
9411
/// that (a proxy in front of a hub refuses one past 100 MB); the change
9412
/// and the bookmark follow, and a clone has every file.
9413
#[test]
9414
fn a_heavy_change_sends_its_blobs_in_parts() {
9415
    hermetic();
9416
    let dir = tempfile::tempdir().unwrap();
9417
    let root = dir.path();
9418
    let origin = root.join("origin");
9419
    Repo::init_bare_unbound(&origin).unwrap();
9420
    let main = root.join("main");
9421
    let mut repo = Repo::init(&main).unwrap();
9422
    repo.config
9423
        .set("remote.origin.url", &origin.to_string_lossy())
9424
        .unwrap();
9425
    repo.config.set("push.batch-bytes", "50000").unwrap();
9426
    repo.save_config().unwrap();
9427
    let mut x: u64 = 0x9e3779b97f4a7c15;
9428
    let mut noise = |n: usize| -> Vec<u8> {
9429
        (0..n)
9430
            .map(|_| {
9431
                x ^= x << 13;
9432
                x ^= x >> 7;
9433
                x ^= x << 17;
9434
                (x >> 24) as u8
9435
            })
9436
            .collect()
9437
    };
9438
    let files: Vec<Vec<u8>> = (0..4).map(|_| noise(40_000)).collect();
9439
    for (i, f) in files.iter().enumerate() {
9440
        write(&main, &format!("bin{i}.dat"), f);
9441
    }
9442
    repo.commit("four blobs", &[]).unwrap();
9443
    let mut parts = Vec::new();
9444
    let results = repo
9445
        .push_bookmark_with("origin", "main", false, &mut |m| parts.push(m.to_string()))
9446
        .unwrap();
9447
    assert!(
9448
        results.iter().any(|r| r.ok && r.name == "main"),
9449
        "{results:?}"
9450
    );
9451
    assert!(
9452
        parts.len() >= 3 && parts[0].starts_with("objects 1 of"),
9453
        "{parts:?}"
9454
    );
9455
    let back = Repo::clone(&origin.to_string_lossy(), &root.join("back")).unwrap();
9456
    for (i, f) in files.iter().enumerate() {
9457
        assert_eq!(&fs::read(root.join(format!("back/bin{i}.dat"))).unwrap(), f);
9458
    }
9459
    drop(back);
9460
}
9461
9462
/// oxygen#97: with `git.claim`, an import authors the importing identity's
9463
/// own commits (Git author email = its email, any case) with its key, and
9464
/// leaves anyone else's with the zero key; the history verifies as before.
9465
#[test]
9466
fn git_import_claims_your_own_commits() {
9467
    hermetic();
9468
    if std::process::Command::new("git")
9469
        .arg("--version")
9470
        .output()
9471
        .is_err()
9472
    {
9473
        eprintln!("git not installed; skipping");
9474
        return;
9475
    }
9476
    let dir = tempfile::tempdir().unwrap();
9477
    let root = dir.path();
9478
    let g = root.join("src.git");
9479
    fs::create_dir_all(&g).unwrap();
9480
    let git = |who: &str, args: &[&str]| {
9481
        let (name, email) = who.split_once(' ').unwrap();
9482
        let out = std::process::Command::new("git")
9483
            .arg("-C")
9484
            .arg(&g)
9485
            .args([
9486
                "-c",
9487
                &format!("user.name={name}"),
9488
                "-c",
9489
                &format!("user.email={email}"),
9490
                "-c",
9491
                "commit.gpgsign=false",
9492
            ])
9493
            .args(args)
9494
            .output()
9495
            .unwrap();
9496
        assert!(
9497
            out.status.success(),
9498
            "git {args:?}: {}",
9499
            String::from_utf8_lossy(&out.stderr)
9500
        );
9501
    };
9502
    git("Grace [email protected]", &["init", "-q", "-b", "main"]);
9503
    write(&g, "a.txt", b"a\n");
9504
    git("Grace [email protected]", &["add", "."]);
9505
    git("Grace [email protected]", &["commit", "-qm", "mine"]);
9506
    write(&g, "b.txt", b"b\n");
9507
    git("Ada [email protected]", &["add", "."]);
9508
    git("Ada [email protected]", &["commit", "-qm", "someone else's"]);
9509
9510
    let mut repo = Repo::init(&root.join("o")).unwrap();
9511
    let (key, _) = repo
9512
        .create_identity("Grace", "[email protected]", IdentityScope::Repo)
9513
        .unwrap();
9514
    repo.config.set("git.claim", "true").unwrap();
9515
    repo.save_config().unwrap();
9516
    let repo = Repo::open(&root.join("o")).unwrap();
9517
    repo.import_git(&g, "main").unwrap();
9518
    let v = repo.verify_git_import(&g, "main").unwrap();
9519
    assert!(v.mismatches.is_empty(), "{:?}", v.mismatches);
9520
    let heads = repo.bookmark_heads().unwrap();
9521
    let by_message: std::collections::HashMap<String, KeyId> = repo
9522
        .log_state(&heads)
9523
        .unwrap()
9524
        .into_iter()
9525
        .map(|e| {
9526
            (
9527
                e.change.message.lines().next().unwrap_or("").to_string(),
9528
                e.change.author,
9529
            )
9530
        })
9531
        .collect();
9532
    assert_eq!(by_message["mine"], key, "her own commit, any case of email");
9533
    assert_eq!(by_message["someone else's"], ObjectRef::ZERO, "not hers");
9534
}
9535
9536
/// oxygen#86: removing a remote removes all of it: every `remote.NAME.*`
9537
/// key (URL, token, CA), its tracking bookmarks, and nothing else.
9538
#[test]
9539
fn removing_a_remote_leaves_nothing_of_it() {
9540
    hermetic();
9541
    let dir = tempfile::tempdir().unwrap();
9542
    let origin = dir.path().join("origin");
9543
    Repo::init_bare_unbound(&origin).unwrap();
9544
    let main = dir.path().join("main");
9545
    let mut repo = Repo::init(&main).unwrap();
9546
    repo.config
9547
        .set("remote.origin.url", &origin.to_string_lossy())
9548
        .unwrap();
9549
    repo.config
9550
        .set("remote.origin.token", "secret-ish")
9551
        .unwrap();
9552
    repo.config
9553
        .set("remote.keep.url", &origin.to_string_lossy())
9554
        .unwrap();
9555
    repo.save_config().unwrap();
9556
    write(&main, "a.txt", b"a\n");
9557
    repo.commit("a", &[]).unwrap();
9558
    assert!(repo.push("origin", false).unwrap()[0].ok);
9559
    assert!(
9560
        repo.view().unwrap().remotes.contains_key("origin"),
9561
        "a tracking bookmark"
9562
    );
9563
9564
    repo.remove_remote("origin").unwrap();
9565
    let again = Repo::open(&main).unwrap();
9566
    assert!(
9567
        !again
9568
            .config
9569
            .repo_layer()
9570
            .keys()
9571
            .any(|k| k.starts_with("remote.origin.")),
9572
        "{:?}",
9573
        again.config.repo_layer()
9574
    );
9575
    assert!(!again.config.remotes.contains_key("origin"));
9576
    assert!(
9577
        !again.view().unwrap().remotes.contains_key("origin"),
9578
        "its tracking bookmarks go"
9579
    );
9580
    assert!(
9581
        again.config.remotes.contains_key("keep"),
9582
        "another remote stays"
9583
    );
9584
    let mut again = again;
9585
    assert!(
9586
        again.remove_remote("origin").is_err(),
9587
        "a second removal is refused"
9588
    );
9589
}
9590
9591
/// oxygenhub#126: a blob a host stored for itself (a job's artifact) is
9592
/// unreachable from history, so gc prunes it, unless the host names it:
9593
/// then it and its chunks stay, and it reads back whole.
9594
#[test]
9595
fn gc_keeps_the_blobs_a_host_names() {
9596
    hermetic();
9597
    let dir = tempfile::tempdir().unwrap();
9598
    let repo = Repo::init(dir.path()).unwrap();
9599
    write(dir.path(), "a.txt", b"a\n");
9600
    repo.commit("a", &[]).unwrap();
9601
    // Large enough to be several chunks.
9602
    let body: Vec<u8> = (0..400_000u32)
9603
        .flat_map(|i| (i.wrapping_mul(2654435761)).to_le_bytes())
9604
        .collect();
9605
    let kept = repo.store_blob(&body).unwrap();
9606
    let lost = repo.store_blob(b"an artifact nobody names").unwrap();
9607
    repo.gc_keeping(true, &[kept], &mut |_| {}).unwrap();
9608
    assert_eq!(repo.read_blob(&kept).unwrap(), body, "named: kept whole");
9609
    assert!(!repo.store().has(&lost), "not named: pruned");
9610
    repo.gc(true).unwrap();
9611
    assert!(!repo.store().has(&kept), "a plain gc prunes it");
9612
}
9613
9614
/// oxygen#99: undo in one workspace undoes that workspace's last command,
9615
/// never another workspace's, says what it undid, and goes further back
9616
/// when run again.
9617
#[test]
9618
fn undo_is_scoped_to_its_workspace() {
9619
    hermetic();
9620
    let dir = tempfile::tempdir().unwrap();
9621
    let root = dir.path().join("main");
9622
    let a = Repo::init(&root).unwrap();
9623
    write(&root, "base.txt", b"base\n");
9624
    let base = a.commit("base", &[]).unwrap();
9625
    a.bookmark_create("feature", None).unwrap();
9626
    let ws_dir = dir.path().join("ws");
9627
    let heads = a.resolve_heads("feature").unwrap();
9628
    let b = a
9629
        .workspace_add_on(&ws_dir, Some(&heads), Some("feature"))
9630
        .unwrap();
9631
9632
    // A commits on main, then B commits on feature: B's is the newest.
9633
    write(&root, "a.txt", b"a\n");
9634
    let ca = a.commit("from a", &[]).unwrap();
9635
    write(&ws_dir, "b.txt", b"b\n");
9636
    let cb = b.commit("from b", &[]).unwrap();
9637
9638
    // A's undo undoes A's commit and leaves B's.
9639
    let u = a.undo().unwrap();
9640
    assert_eq!(u.command, "oxy commit -m \"from a\"");
9641
    assert_eq!(u.others_kept, 1, "B's newer commit is left");
9642
    assert!(!u.changes.is_empty());
9643
    let view = a.view().unwrap();
9644
    // (Independent changes commute, so a bookmark's heads may hold base too.)
9645
    assert_eq!(a.heads_of(&view, "main").unwrap(), vec![base]);
9646
    assert!(
9647
        a.heads_of(&view, "feature").unwrap().contains(&cb),
9648
        "B's commit stands"
9649
    );
9650
    assert!(
9651
        a.store().get_change(&ca).is_ok(),
9652
        "the change itself is still in the store"
9653
    );
9654
    // A's working copy was clean, so its files followed; B's are untouched.
9655
    assert!(!root.join("a.txt").exists());
9656
    assert!(a.snapshot("oxy status").unwrap().statuses.is_empty());
9657
    assert!(ws_dir.join("b.txt").exists());
9658
9659
    // B's undo still finds B's own commit, under A's undo.
9660
    let u = b.undo().unwrap();
9661
    assert_eq!(u.command, "oxy commit -m \"from b\"");
9662
    assert!(!b
9663
        .heads_of(&b.view().unwrap(), "feature")
9664
        .unwrap()
9665
        .contains(&cb));
9666
    assert_eq!(
9667
        a.heads_of(&a.view().unwrap(), "main").unwrap(),
9668
        vec![base],
9669
        "A's undo stands"
9670
    );
9671
9672
    // A's next undo goes past the commit it already undid, to adding B's
9673
    // workspace: refused, since B has worked there since.
9674
    let e = a.undo().unwrap_err().to_string();
9675
    assert!(e.contains("the workspace at") && e.contains("ws"), "{e}");
9676
}
9677
9678
/// oxygen#99: two workspaces on one bookmark: an undo takes back only its
9679
/// own commit's head, and the other workspace's head stays.
9680
#[test]
9681
fn undo_on_a_shared_bookmark_keeps_the_other_workspaces_head() {
9682
    hermetic();
9683
    let dir = tempfile::tempdir().unwrap();
9684
    let root = dir.path().join("main");
9685
    let a = Repo::init(&root).unwrap();
9686
    write(&root, "base.txt", b"base\n");
9687
    a.commit("base", &[]).unwrap();
9688
    let ws_dir = dir.path().join("ws");
9689
    let b = a.workspace_add(&ws_dir, None).unwrap();
9690
    write(&root, "a.txt", b"a\n");
9691
    let ca = a.commit("from a", &[]).unwrap();
9692
    write(&ws_dir, "b.txt", b"b\n");
9693
    let cb = b.commit("from b", &[]).unwrap();
9694
    let u = a.undo().unwrap();
9695
    assert_eq!(u.command, "oxy commit -m \"from a\"");
9696
    let heads = a.heads_of(&a.view().unwrap(), "main").unwrap();
9697
    assert!(heads.contains(&cb) && !heads.contains(&ca), "{heads:?}");
9698
}
9699
9700
/// oxygen#99: an undo that would also take back what another workspace
9701
/// did since to the same bookmark is refused, naming it.
9702
#[test]
9703
fn undo_refuses_to_take_back_another_workspaces_work() {
9704
    hermetic();
9705
    let dir = tempfile::tempdir().unwrap();
9706
    let root = dir.path().join("main");
9707
    let a = Repo::init(&root).unwrap();
9708
    write(&root, "base.txt", b"base\n");
9709
    a.commit("base", &[]).unwrap();
9710
    let ws_dir = dir.path().join("ws");
9711
    let b = a.workspace_add(&ws_dir, None).unwrap();
9712
    // Both on main: A commits, then B builds on it, editing A's file.
9713
    write(&root, "a.txt", b"a\n");
9714
    a.commit("from a", &[]).unwrap();
9715
    b.refresh().unwrap();
9716
    let heads = b.resolve_heads("main").unwrap();
9717
    b.checkout(&heads, false, "oxy checkout").unwrap();
9718
    write(&ws_dir, "a.txt", b"a, then b\n");
9719
    b.commit("from b", &[]).unwrap();
9720
    let e = a.undo().unwrap_err().to_string();
9721
    assert!(
9722
        e.contains("bookmark main") && e.contains("builds on"),
9723
        "{e}"
9724
    );
9725
    assert!(e.contains("oxy op restore"), "{e}");
9726
}
9727
9728
/// oxygen#99: undoing a commit that was already pushed says so: the remote
9729
/// still has it.
9730
#[test]
9731
fn undo_says_when_the_commit_was_pushed() {
9732
    hermetic();
9733
    let dir = tempfile::tempdir().unwrap();
9734
    let root = dir.path();
9735
    Repo::init(&root.join("origin")).unwrap();
9736
    let url = root.join("origin").to_string_lossy().to_string();
9737
    let repo = Repo::clone(&url, &root.join("work"))
9738
        .unwrap()
9739
        .with_home(root.join("home"));
9740
    write(&root.join("work"), "a.txt", b"a\n");
9741
    repo.commit("a", &[]).unwrap();
9742
    assert!(repo.push("origin", false).unwrap()[0].ok);
9743
    // The push itself is passed over: the remote keeps what it was sent.
9744
    let u = repo.undo().unwrap();
9745
    assert_eq!(u.command, "oxy commit -m \"a\"");
9746
    assert_eq!(u.pushed, vec![("main".to_string(), "origin".to_string())]);
9747
}
9748
9749
/// oxygen#98: a new untracked file over snapshot.max-new-file-size is left
9750
/// out of the snapshot and named; tracked files and files already in the
9751
/// working copy are not.
9752
#[test]
9753
fn large_new_files_are_left_out_of_snapshots() {
9754
    hermetic();
9755
    let dir = tempfile::tempdir().unwrap();
9756
    let root = dir.path();
9757
    let mut repo = Repo::init(root).unwrap();
9758
    repo.config.max_new_file = 1024;
9759
    write(root, "small.txt", b"small\n");
9760
    write(root, "big.bin", &vec![0u8; 4096]);
9761
    let s = repo.snapshot("oxy status").unwrap();
9762
    let paths: Vec<_> = s.statuses.iter().map(|p| p.path.as_str()).collect();
9763
    assert_eq!(paths, ["small.txt"]);
9764
    assert_eq!(repo.skipped_large(), vec![("big.bin".to_string(), 4096)]);
9765
    repo.commit("small", &[]).unwrap();
9766
9767
    // A tracked file may grow past the limit.
9768
    write(root, "small.txt", &vec![b'x'; 4096]);
9769
    let s = repo.snapshot("oxy status").unwrap();
9770
    assert!(s.statuses.iter().any(|p| p.path == "small.txt"));
9771
    // With no limit the big file is taken in, and stays once it is.
9772
    repo.config.max_new_file = 0;
9773
    let s = repo.snapshot("oxy status").unwrap();
9774
    assert!(s.statuses.iter().any(|p| p.path == "big.bin"));
9775
    repo.config.max_new_file = 1024;
9776
    let s = repo.snapshot("oxy status").unwrap();
9777
    assert!(
9778
        s.statuses.iter().any(|p| p.path == "big.bin"),
9779
        "already in the working copy"
9780
    );
9781
    assert!(repo.skipped_large().is_empty());
9782
}
9783
9784
/// oxygen#98: a file only a past working-copy snapshot held is pruned once
9785
/// snapshots expire, and kept while they have not.
9786
#[test]
9787
fn gc_prunes_what_only_expired_snapshots_held() {
9788
    hermetic();
9789
    let dir = tempfile::tempdir().unwrap();
9790
    let root = dir.path();
9791
    let mut repo = Repo::init(root).unwrap();
9792
    repo.config.gc_grace_days = 0;
9793
    write(root, "a.txt", b"a\n");
9794
    repo.commit("a", &[]).unwrap();
9795
    let image: Vec<u8> = (0..200_000u32).map(|i| (i % 7) as u8).collect();
9796
    write(root, "image.tar", &image);
9797
    repo.snapshot("oxy status").unwrap();
9798
    std::fs::remove_file(root.join("image.tar")).unwrap();
9799
    repo.snapshot("oxy status").unwrap();
9800
    let blob = Repo::blob_ref(&image);
9801
    assert!(repo.store().has(&blob));
9802
    repo.gc(true).unwrap();
9803
    assert!(repo.store().has(&blob), "a recent snapshot keeps it");
9804
    repo.config.snapshot_retention_days = 0;
9805
    repo.gc(true).unwrap();
9806
    assert!(!repo.store().has(&blob), "an expired snapshot does not");
9807
    assert_eq!(
9808
        repo.file_at("a.txt", None).unwrap(),
9809
        b"a\n",
9810
        "committed files stay"
9811
    );
9812
}
9813
9814
/// oxygen#100: uncommitted work byte-for-byte what the bookmark switched to
9815
/// already has is no conflict: the switch goes through, nothing is lost,
9816
/// and other carried work still comes along.
9817
#[test]
9818
fn carrying_work_the_target_already_has_is_no_conflict() {
9819
    hermetic();
9820
    let dir = tempfile::tempdir().unwrap();
9821
    let root = dir.path();
9822
    let mut repo = Repo::init(root).unwrap();
9823
    write(root, "a.txt", b"one\n");
9824
    write(root, "b.txt", b"b\n");
9825
    repo.commit("one", &[]).unwrap();
9826
    repo.bookmark_create("landed", None).unwrap();
9827
    // On landed, a.txt becomes "two" (as a proposal landing would).
9828
    repo.bookmark_switch("landed", false).unwrap();
9829
    write(root, "a.txt", b"two\n");
9830
    repo.commit("two", &[]).unwrap();
9831
    repo.bookmark_switch("main", false).unwrap();
9832
    assert_eq!(std::fs::read(root.join("a.txt")).unwrap(), b"one\n");
9833
    // The same edit, uncommitted, on main; and another edit besides.
9834
    write(root, "a.txt", b"two\n");
9835
    write(root, "b.txt", b"b, edited\n");
9836
    let (_, carried) = repo.bookmark_switch_carry("landed").unwrap();
9837
    assert_eq!(
9838
        carried,
9839
        vec!["b.txt".to_string()],
9840
        "only the work landed lacks is carried"
9841
    );
9842
    assert_eq!(std::fs::read(root.join("a.txt")).unwrap(), b"two\n");
9843
    assert_eq!(std::fs::read(root.join("b.txt")).unwrap(), b"b, edited\n");
9844
    let s = repo.snapshot("oxy status").unwrap();
9845
    let paths: Vec<_> = s.statuses.iter().map(|p| p.path.as_str()).collect();
9846
    assert_eq!(paths, ["b.txt"]);
9847
9848
    // A real difference is still refused.
9849
    repo.bookmark_switch("main", true).unwrap();
9850
    write(root, "a.txt", b"three\n");
9851
    let e = repo
9852
        .bookmark_switch_carry("landed")
9853
        .unwrap_err()
9854
        .to_string();
9855
    assert!(e.contains("a.txt") && e.contains("--discard"), "{e}");
9856
}
9857
9858
/// oxygen#103: a full change hash as `--json` prints it, without `#`,
9859
/// resolves, so JSON output feeds back into commands.
9860
#[test]
9861
fn a_full_hash_resolves_without_its_hash_sign() {
9862
    hermetic();
9863
    let dir = tempfile::tempdir().unwrap();
9864
    let root = dir.path();
9865
    let repo = Repo::init(root).unwrap();
9866
    write(root, "a.txt", b"a\n");
9867
    let h = repo.commit("a", &[]).unwrap();
9868
    assert_eq!(repo.resolve_change(&h.to_hex()).unwrap(), h);
9869
    assert_eq!(repo.resolve_change(&format!("#{}", h.to_hex())).unwrap(), h);
9870
    assert!(repo
9871
        .resolve_change(&"0".repeat(64))
9872
        .unwrap_err()
9873
        .to_string()
9874
        .contains("no change matches"));
9875
}
9876
9877
#[test]
9878
fn a_pin_change_moves_only_the_pin() {
9879
    hermetic();
9880
    let dir = tempfile::tempdir().unwrap();
9881
    let root = dir.path();
9882
    let _lib_origin = Repo::init(&root.join("lib-origin")).unwrap();
9883
    let lib_url = root.join("lib-origin").to_string_lossy().to_string();
9884
    let lib = Repo::clone(&lib_url, &root.join("lib"))
9885
        .unwrap()
9886
        .with_home(root.join("home"));
9887
    write(&root.join("lib"), "lib.txt", b"v1\n");
9888
    lib.commit("lib v1", &[]).unwrap();
9889
    assert!(lib.push("origin", false).unwrap()[0].ok);
9890
    let _app_origin = Repo::init(&root.join("app-origin")).unwrap();
9891
    let app_dir = root.join("app");
9892
    let app = Repo::clone(&root.join("app-origin").to_string_lossy(), &app_dir)
9893
        .unwrap()
9894
        .with_home(root.join("home"));
9895
    write(&app_dir, "main.txt", b"app\n");
9896
    let pin1 = app.submodule_add(&lib_url, "libs/lib", None).unwrap();
9897
    let a1 = app.commit("app with lib", &[]).unwrap();
9898
    // The library moves on.
9899
    write(&root.join("lib"), "more.txt", b"v2\n");
9900
    let l2 = lib.commit("lib v2", &[]).unwrap();
9901
    let crate::subrepo::Pin::Oxy { repo, bookmark, .. } = pin1 else {
9902
        panic!("an Oxygen pin")
9903
    };
9904
    let pin2 = crate::subrepo::Pin::Oxy {
9905
        repo,
9906
        heads: vec![l2],
9907
        bookmark,
9908
    };
9909
    let author = app.store().get_change(&a1).unwrap().author;
9910
    let change = app
9911
        .build_pin_change(&[a1], "libs/lib", &pin2, "Move lib to v2", author)
9912
        .unwrap();
9913
    let mut state = app.load_state(&[a1]).unwrap();
9914
    state.add(change).unwrap();
9915
    let files = state.materialize().files;
9916
    assert_eq!(files["libs/lib"].kind, NodeKind::Subrepo);
9917
    let FileContent::Opaque { blobs } = &files["libs/lib"].content else {
9918
        panic!("a pin is opaque")
9919
    };
9920
    let read = crate::subrepo::Pin::decode(&app.read_blob(&blobs[0]).unwrap()).unwrap();
9921
    assert_eq!(read, pin2, "the new pin");
9922
    assert!(
9923
        matches!(&files["main.txt"].content, FileContent::Text { bytes, .. } if bytes.as_slice() == b"app\n"),
9924
        "nothing else changes"
9925
    );
9926
    // Only a subrepo's pin can be moved this way.
9927
    let e = app.build_pin_change(&[a1], "main.txt", &pin2, "x", author);
9928
    assert!(format!("{:?}", e.unwrap_err()).contains("not a subrepo"));
9929
    let e = app.build_pin_change(&[a1], "libs/none", &pin2, "x", author);
9930
    assert!(format!("{:?}", e.unwrap_err()).contains("does not exist"));
9931
}
9932
9933
/// oxygenhub#249: a handle reads the operation head once and keeps it,
9934
/// so one command or request never mixes two heads; another handle's
9935
/// operation shows only after `refresh`. Its own operations move it, and
9936
/// one recorded from the head it kept merges with what landed since, as
9937
/// any concurrent operation does.
9938
#[test]
9939
fn one_handle_keeps_one_head_until_it_refreshes() {
9940
    hermetic();
9941
    let dir = tempfile::tempdir().unwrap();
9942
    let root = dir.path();
9943
    let writer = Repo::init(root).unwrap();
9944
    write(root, "a.txt", b"one\n");
9945
    let h1 = writer.commit("one", &[]).unwrap();
9946
    let reader = Repo::open(root).unwrap();
9947
    let before = reader.view().unwrap();
9948
    assert_eq!(reader.bookmark_heads().unwrap(), vec![h1]);
9949
    write(root, "a.txt", b"two\n");
9950
    let h2 = writer.commit("two", &[]).unwrap();
9951
    assert_eq!(
9952
        writer.bookmark_heads().unwrap(),
9953
        vec![h2],
9954
        "its own operation"
9955
    );
9956
    assert_eq!(reader.view().unwrap(), before, "the head it read first");
9957
    assert_eq!(reader.bookmark_heads().unwrap(), vec![h1]);
9958
    reader.refresh().unwrap();
9959
    assert_eq!(reader.bookmark_heads().unwrap(), vec![h2]);
9960
9961
    // A handle recording from an older head merges with the newer one.
9962
    let stale = Repo::open(root).unwrap();
9963
    assert_eq!(stale.bookmark_heads().unwrap(), vec![h2]);
9964
    write(root, "a.txt", b"three\n");
9965
    let h3 = writer.commit("three", &[]).unwrap();
9966
    stale.bookmark_create("feature", Some(&[h1])).unwrap();
9967
    let view = stale.view().unwrap();
9968
    assert!(view.bookmarks.contains_key("feature"));
9969
    assert_eq!(
9970
        stale.bookmark_heads().unwrap(),
9971
        vec![h3],
9972
        "merged, not lost"
9973
    );
9974
    let fresh = Repo::open(root).unwrap();
9975
    assert_eq!(fresh.view().unwrap(), view);
9976
}
9977
9978
/// oxygenhub#249 over a store (a bucket's compare-and-swap): the same.
9979
#[test]
9980
fn over_a_store_one_handle_keeps_one_head() {
9981
    hermetic();
9982
    let backend = std::sync::Arc::new(crate::strata::MemoryStore::new());
9983
    crate::store::TEST_BACKEND.with(|t| *t.borrow_mut() = Some(backend.clone()));
9984
    let dir = tempfile::tempdir().unwrap();
9985
    let a = Repo::init(dir.path()).unwrap();
9986
    let (h0, _) = a.head_op().unwrap();
9987
    let b = Repo::open(dir.path()).unwrap();
9988
    assert_eq!(b.head_op().unwrap().0, h0);
9989
    let state = a.store.put_state(&StateObject::new(vec![])).unwrap();
9990
    let mut view = a.view().unwrap();
9991
    view.bookmarks.insert("x".into(), state);
9992
    let r = a.record_op(&[h0], "bookmark x", view).unwrap();
9993
    assert_eq!(a.head_op().unwrap().0, r);
9994
    assert_eq!(b.head_op().unwrap().0, h0, "b keeps its head");
9995
    b.refresh().unwrap();
9996
    assert_eq!(b.head_op().unwrap().0, r);
9997
    crate::store::TEST_BACKEND.with(|t| *t.borrow_mut() = None);
9998
}
9999
10000
/// oxygenhub#249: gc retires what it repacks rather than deleting it; a
10001
/// reader opened before reads on, then and after the next gc deletes the
10002
/// retired files once their hour is up. Younger ones are kept.
10003
#[test]
10004
fn gc_retires_and_a_later_gc_deletes_after_the_hour() {
10005
    hermetic();
10006
    let dir = tempfile::tempdir().unwrap();
10007
    let root = dir.path();
10008
    let repo = Repo::init(root).unwrap();
10009
    let mut heads = Vec::new();
10010
    for i in 0..4 {
10011
        write(root, &format!("f{i}.txt"), format!("{i}\n").as_bytes());
10012
        heads.push(repo.commit(&format!("c{i}"), &[]).unwrap());
10013
    }
10014
    let reader = Repo::open(root).unwrap();
10015
    assert_eq!(reader.log().unwrap().len(), 5);
10016
    let r = repo.gc(true).unwrap();
10017
    assert_eq!(r.retired, crate::store::RetiredReport::default());
10018
    assert_eq!(repo.store().loose_count().unwrap(), 0);
10019
    assert_eq!(reader.log().unwrap().len(), 5, "read on from what it had");
10020
    // Nothing is an hour old yet: a gc keeps it all.
10021
    let r = repo.gc(true).unwrap();
10022
    assert_eq!((r.retired.packs, r.retired.loose), (0, 0));
10023
    assert!(r.retired.kept > 0, "{r:?}");
10024
    write(root, "f9.txt", b"9\n");
10025
    heads.push(repo.commit("c9", &[]).unwrap());
10026
    crate::store::reader_tests::age_retired(
10027
        repo.store(),
10028
        crate::store::RETIRED_FOR + std::time::Duration::from_secs(60),
10029
    );
10030
    let r = repo.gc(true).unwrap();
10031
    assert!(r.retired.packs >= 1 && r.retired.loose > 0, "{r:?}");
10032
    assert_eq!(r.retired.kept, 0, "{r:?}");
10033
    let r = repo.gc(true).unwrap();
10034
    assert_eq!((r.retired.packs, r.retired.loose), (0, 0));
10035
    assert!(r.retired.kept > 0, "what the last gc retired is young");
10036
    // The reader opened before all of it still reads everything, from
10037
    // the packs it finds when what it loaded is gone.
10038
    assert_eq!(reader.log().unwrap().len(), 5);
10039
    for h in &heads[..4] {
10040
        reader.store().get_change(h).unwrap();
10041
    }
10042
    reader.refresh().unwrap();
10043
    assert_eq!(reader.log().unwrap().len(), 6);
10044
    let fresh = Repo::open(root).unwrap();
10045
    assert_eq!(
10046
        fresh.store().pack_count(),
10047
        1,
10048
        "retired packs are not loaded"
10049
    );
10050
}
10051
10052
/// oxygenhub#249: a repository opens when its store's pack listing names
10053
/// an index that is not there (deleted between the listing and the read).
10054
#[test]
10055
fn a_repository_opens_when_a_listed_index_is_gone() {
10056
    hermetic();
10057
    let backend = crate::store::reader_tests::racing(true);
10058
    let dyn_backend: std::sync::Arc<crate::store::Backend> = backend.clone();
10059
    crate::store::TEST_BACKEND.with(|t| *t.borrow_mut() = Some(dyn_backend));
10060
    let dir = tempfile::tempdir().unwrap();
10061
    let repo = Repo::init(dir.path()).unwrap();
10062
    write(dir.path(), "a.txt", b"a\n");
10063
    let h = repo.commit("a", &[]).unwrap();
10064
    repo.gc(true).unwrap();
10065
    let again = Repo::open(dir.path()).unwrap();
10066
    assert_eq!(again.store().pack_count(), 1);
10067
    assert_eq!(again.bookmark_heads().unwrap(), vec![h]);
10068
    // And when one is deleted between the listing and the read: a copy of
10069
    // the live pack, whose index goes as the store opens.
10070
    use crate::strata::Store as _;
10071
    let idx = backend
10072
        .list("pack-")
10073
        .unwrap()
10074
        .into_iter()
10075
        .map(|e| e.key)
10076
        .find(|k| k.ends_with(".idx") && k != "pack-0000.idx")
10077
        .unwrap();
10078
    let stem = idx.trim_end_matches(".idx");
10079
    for ext in ["pack", "idx"] {
10080
        let bytes = backend.get(&format!("{stem}.{ext}")).unwrap();
10081
        backend
10082
            .put_new(&format!("pack-copy.{ext}"), &bytes)
10083
            .unwrap();
10084
    }
10085
    *backend.doomed.lock().unwrap() = Some("pack-copy.idx".into());
10086
    let again = Repo::open(dir.path()).unwrap();
10087
    assert_eq!(again.store().pack_count(), 1);
10088
    assert_eq!(again.bookmark_heads().unwrap(), vec![h]);
10089
    assert!(!backend.has("pack-copy.idx").unwrap());
10090
    crate::store::TEST_BACKEND.with(|t| *t.borrow_mut() = None);
10091
}