OXYGENHUB
# b63fc7a77fc6 oxygen / crates / oxy-core / src / repo / tests.rs
369.1 KiB · Rust · last changed A tag can be withdrawn, by a signed withdrawal (oxygenhub#301) 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
#[test]
1757
fn a_certified_key_acts_for_its_author_under_a_grant() {
1758
    use crate::cert::{Certificate, Grant, SignedCertificate, SignedGrant};
1759
    use crate::identity::{Identity, Scope};
1760
    hermetic();
1761
    let dir = tempfile::tempdir().unwrap();
1762
    let root = dir.path();
1763
    let _origin = Repo::init(&root.join("origin")).unwrap();
1764
    let url = root.join("origin").to_string_lossy().to_string();
1765
    let mut a = Repo::clone(&url, &root.join("a"))
1766
        .unwrap()
1767
        .with_home(root.join("home-a"));
1768
    let (ada, _) = a
1769
        .create_identity("Ada", "[email protected]", IdentityScope::User)
1770
        .unwrap();
1771
    write(&root.join("a"), "a.txt", b"a\n");
1772
    a.commit("a", &[]).unwrap();
1773
    a.policy_init().unwrap();
1774
    assert!(a.push("origin", false).unwrap().iter().all(|r| r.ok));
1775
    let hub_sk = SecretKey::generate();
1776
    let hub = hub_sk.identity("hub", "[email protected]", 1);
1777
    a.policy_grant_subject(
1778
        "agent:claude@ada",
1779
        hub.clone(),
1780
        Scope::CHANGES | Scope::REFS,
1781
        None,
1782
    )
1783
    .unwrap();
1784
    assert!(a.push("origin", false).unwrap().iter().all(|r| r.ok));
1785
    let (_, ada_sk) = a.secret_key().unwrap().unwrap();
1786
    let ada_id = a.identity(&ada).unwrap();
1787
1788
    let now = Hlc::now().wall_ms;
1789
    let grant = |by: &Identity, sk: &SecretKey, from: u64, to: u64| {
1790
        SignedGrant::sign(
1791
            Grant {
1792
                grantor: by.hash(),
1793
                subject: "agent:claude@ada".into(),
1794
                issuer: hub.hash(),
1795
                scope: Scope::CHANGES | Scope::SEAL,
1796
                not_before: from,
1797
                expires: to,
1798
            },
1799
            by,
1800
            sk,
1801
        )
1802
    };
1803
    // Ada's work as an agent runs it: Ada the author, a fresh key the hub
1804
    // certified (with `g` inside) the signer.
1805
    let agent = |name: &str, g: Option<SignedGrant>| {
1806
        let mut r = Repo::clone(&url, &root.join(name))
1807
            .unwrap()
1808
            .with_home(root.join(format!("home-{name}")));
1809
        let (key, id) = r
1810
            .create_identity(name, "[email protected]", IdentityScope::User)
1811
            .unwrap();
1812
        r.set_user_config("author.key", &ada.to_hex()).unwrap();
1813
        r.set_user_config("author.signer", &key.to_hex()).unwrap();
1814
        let cert = SignedCertificate::sign(
1815
            Certificate {
1816
                key: id,
1817
                issuer: hub.hash(),
1818
                subject: "agent:claude@ada".into(),
1819
                claims: vec![],
1820
                scope: Scope::CHANGES | Scope::REFS | Scope::SEAL,
1821
                not_before: now - 60_000,
1822
                expires: now + 600_000,
1823
                grant: g,
1824
            },
1825
            &hub,
1826
            &hub_sk,
1827
        );
1828
        r.store().put_identity(&hub).unwrap();
1829
        r.store().put_certificate(&cert).unwrap();
1830
        write(&root.join(name), &format!("{name}.txt"), b"agent work\n");
1831
        let h = r.commit("work", &[]).unwrap();
1832
        assert_eq!(r.store().get_change_meta(&h).unwrap().author, ada);
1833
        (r, key, h)
1834
    };
1835
1836
    let (claude, key, h) = agent(
1837
        "claude",
1838
        Some(grant(&ada_id, &ada_sk, now - 60_000, now + 86_400_000)),
1839
    );
1840
    let r = claude.push("origin", false).unwrap();
1841
    assert!(r.iter().all(|x| x.ok), "{r:?}");
1842
    let host = Repo::open(&root.join("origin")).unwrap();
1843
    assert!(
1844
        matches!(
1845
            host.authenticate_change(&h).unwrap(),
1846
            SignatureStatus::Valid { key: k, sealed: true, name, .. } if k == key && name == "agent:claude@ada"
1847
        ),
1848
        "named by its certificate's subject"
1849
    );
1850
    a.pull("origin").unwrap();
1851
    assert!(matches!(
1852
        a.authenticate_change(&h).unwrap(),
1853
        SignatureStatus::Valid { key: k, .. } if k == key
1854
    ));
1855
1856
    let (none, _, _) = agent("none", None);
1857
    let r = none.push("origin", false).unwrap();
1858
    assert!(r.iter().all(|x| !x.ok), "no grant: {r:?}");
1859
    let mallory_sk = SecretKey::generate();
1860
    let mallory = mallory_sk.identity("Mallory", "[email protected]", 1);
1861
    let (stranger, _, _) = agent(
1862
        "stranger",
1863
        Some(grant(&mallory, &mallory_sk, now - 60_000, now + 600_000)),
1864
    );
1865
    let r = stranger.push("origin", false).unwrap();
1866
    assert!(r.iter().all(|x| !x.ok), "a stranger's grant: {r:?}");
1867
    let (ended, _, eh) = agent(
1868
        "ended",
1869
        Some(grant(&ada_id, &ada_sk, now - 7_200_000, now - 3_600_000)),
1870
    );
1871
    let r = ended.push("origin", false).unwrap();
1872
    assert!(r.iter().all(|x| !x.ok), "an ended grant: {r:?}");
1873
    assert!(matches!(
1874
        ended.authenticate_change(&eh).unwrap(),
1875
        SignatureStatus::Invalid(e) if e.contains("grant did not cover")
1876
    ));
1877
}
1878
1879
#[test]
1880
fn trust_policy_governs_pushes_and_fetches() {
1881
    hermetic();
1882
    let dir = tempfile::tempdir().unwrap();
1883
    let root = dir.path();
1884
    let origin = Repo::init(&root.join("origin")).unwrap();
1885
    let url = root.join("origin").to_string_lossy().to_string();
1886
1887
    // A is the root. Before the policy, an unsigned push from B is fine.
1888
    let mut a = Repo::clone(&url, &root.join("a"))
1889
        .unwrap()
1890
        .with_home(root.join("home-a"));
1891
    let (key_a, _) = a
1892
        .create_identity("Ada", "[email protected]", IdentityScope::User)
1893
        .unwrap();
1894
    let mut b = Repo::clone(&url, &root.join("b"))
1895
        .unwrap()
1896
        .with_home(root.join("home-b"));
1897
    write(&root.join("b"), "b.txt", b"b\n");
1898
    b.commit("unsigned before policy", &[]).unwrap();
1899
    assert!(b.push("origin", false).unwrap()[0].ok);
1900
    origin.refresh().unwrap();
1901
1902
    // A creates the policy and pushes it; origin now enforces it.
1903
    write(&root.join("a"), "a.txt", b"a\n");
1904
    a.commit("a", &[]).unwrap();
1905
    let sp = a.policy_init().unwrap();
1906
    assert_eq!(sp.policy.serial, 1);
1907
    a.pull("origin").unwrap();
1908
    let results = a.push("origin", false).unwrap();
1909
    origin.refresh().unwrap();
1910
    assert!(results.iter().all(|r| r.ok), "{results:?}");
1911
    assert_eq!(origin.current_policy().unwrap().unwrap().1.policy.serial, 1);
1912
1913
    // B pulls the policy. Without an identity B cannot push at all.
1914
    b.pull("origin").unwrap();
1915
    assert!(
1916
        b.current_policy().unwrap().is_some(),
1917
        "the policy arrived with the fetch"
1918
    );
1919
    assert!(b.push("origin", false).is_err());
1920
    // With an identity the policy does not list, the push is rejected by origin.
1921
    let (key_b, id_b) = b
1922
        .create_identity("Bob", "[email protected]", IdentityScope::User)
1923
        .unwrap();
1924
    write(&root.join("b"), "b.txt", b"b2\n");
1925
    let h_b2 = b.commit("b2 as Bob", &[]).unwrap();
1926
    assert_eq!(b.store().get_change(&h_b2).unwrap().author, key_b);
1927
    let r = b.push("origin", false).unwrap();
1928
    origin.refresh().unwrap();
1929
    assert!(
1930
        !r[0].ok && r[0].reason.contains("may not update"),
1931
        "{:?}",
1932
        r
1933
    );
1934
1935
    // A grants B (identity handed over as a file) and publishes the policy.
1936
    let sp = a.policy_grant(id_b.clone(), None).unwrap();
1937
    assert_eq!(sp.policy.serial, 2);
1938
    let r = a.push("origin", false).unwrap();
1939
    origin.refresh().unwrap();
1940
    assert!(r.iter().any(|x| x.name == "policy" && x.ok), "{r:?}");
1941
    // B must fetch the new policy before pushing.
1942
    assert!(b
1943
        .push("origin", false)
1944
        .unwrap_or_else(|e| vec![RefResult {
1945
            name: "main".into(),
1946
            ok: false,
1947
            reason: e.to_string()
1948
        }])
1949
        .iter()
1950
        .all(|x| !x.ok));
1951
    b.pull("origin").unwrap();
1952
    assert_eq!(b.current_policy().unwrap().unwrap().1.policy.serial, 2);
1953
    let r = b.push("origin", false).unwrap();
1954
    origin.refresh().unwrap();
1955
    assert!(r[0].ok, "{:?}", r);
1956
    // Origin verified B's change under the policy.
1957
    let heads = origin.bookmark_heads().unwrap();
1958
    for h in &heads {
1959
        let c = origin.store().get_change(h).unwrap();
1960
        if c.author == key_b {
1961
            origin
1962
                .change_allowed(
1963
                    h,
1964
                    &origin.current_policy().unwrap().unwrap().1.policy,
1965
                    "main",
1966
                )
1967
                .unwrap();
1968
        }
1969
    }
1970
1971
    // A policy signed by a non-root (B) is refused, as is a replayed serial.
1972
    let mut forged = b.current_policy().unwrap().unwrap().1.policy.clone();
1973
    forged.serial = 3;
1974
    forged.roots = vec![key_b];
1975
    let fh = forged.hash();
1976
    let (_, sk_b) = b.secret_key().unwrap().unwrap();
1977
    let forged = SignedPolicy {
1978
        policy: forged,
1979
        sigs: vec![sk_b.sign(Domain::Policy, &key_b, &fh)],
1980
    };
1981
    let r = origin
1982
        .receive_push(Bundle::default(), vec![], Some(forged), vec![])
1983
        .unwrap();
1984
    assert!(!r[0].ok && r[0].reason.contains("root"), "{:?}", r);
1985
    let stale = a.current_policy().unwrap().unwrap().1;
1986
    let mut old = stale.clone();
1987
    old.policy.serial = 1;
1988
    let r = origin
1989
        .receive_push(Bundle::default(), vec![], Some(old), vec![])
1990
        .unwrap();
1991
    assert!(!r[0].ok && r[0].reason.contains("serial"), "{:?}", r);
1992
1993
    // A revokes B; after B pulls the policy, B's pushes are refused again.
1994
    a.pull("origin").unwrap();
1995
    a.policy_revoke(&key_b).unwrap();
1996
    let r = a.push("origin", false).unwrap();
1997
    origin.refresh().unwrap();
1998
    assert!(r.iter().any(|x| x.name == "policy" && x.ok), "{r:?}");
1999
    b.pull("origin").unwrap();
2000
    write(&root.join("b"), "b.txt", b"b3\n");
2001
    b.commit("b3", &[]).unwrap();
2002
    let r = b.push("origin", false).unwrap();
2003
    origin.refresh().unwrap();
2004
    assert!(!r[0].ok, "{:?}", r);
2005
2006
    // A clone by a third party receives and verifies everything.
2007
    let c = Repo::clone(&url, &root.join("c"))
2008
        .unwrap()
2009
        .with_home(root.join("home-c"));
2010
    assert_eq!(c.current_policy().unwrap().unwrap().1.policy.serial, 3);
2011
    assert!(c
2012
        .current_policy()
2013
        .unwrap()
2014
        .unwrap()
2015
        .1
2016
        .policy
2017
        .roots
2018
        .contains(&key_a));
2019
    assert!(!c.snapshot("status").unwrap().changed);
2020
}
2021
2022
/// oxygen#66: a gc says what it is doing, phase by phase.
2023
#[test]
2024
fn gc_reports_its_phases() {
2025
    hermetic();
2026
    let dir = tempfile::tempdir().unwrap();
2027
    let repo = Repo::init(dir.path()).unwrap();
2028
    for i in 0..3 {
2029
        write(
2030
            dir.path(),
2031
            &format!("f{i}.txt"),
2032
            format!("{i}\n").as_bytes(),
2033
        );
2034
        repo.commit(&format!("c{i}"), &[]).unwrap();
2035
    }
2036
    let mut phases = Vec::new();
2037
    repo.gc_with(true, &mut |p| phases.push(p.to_string()))
2038
        .unwrap();
2039
    assert_eq!(phases[0], "finding what is reachable", "{phases:?}");
2040
    assert!(
2041
        phases.iter().any(|p| p.starts_with("pruning")),
2042
        "{phases:?}"
2043
    );
2044
    assert!(
2045
        phases.iter().any(|p| p.starts_with("packing 0 of ")),
2046
        "{phases:?}"
2047
    );
2048
    assert!(
2049
        phases
2050
            .iter()
2051
            .any(|p| p.starts_with("writing the index of ")),
2052
        "{phases:?}"
2053
    );
2054
}
2055
2056
#[test]
2057
fn gc_packs_objects_and_history_still_works() {
2058
    hermetic();
2059
    let dir = tempfile::tempdir().unwrap();
2060
    let root = dir.path();
2061
    let mut repo = Repo::init(root).unwrap().with_home(root.join("home"));
2062
    repo.create_identity("Ada", "a@b", IdentityScope::User)
2063
        .unwrap();
2064
    repo.set_user_config("core.sign", "change").unwrap();
2065
    write(root, "a.txt", b"one\n");
2066
    let h1 = repo.commit("one", &[]).unwrap();
2067
    write(root, "a.txt", b"two\n");
2068
    write(root, "big.bin", &vec![0u8; 100_000]);
2069
    let h2 = repo.commit("two", &[]).unwrap();
2070
    // Several snapshots leave superseded working-copy versions behind.
2071
    for i in 0..5 {
2072
        write(root, "a.txt", format!("two\n{i}\n").as_bytes());
2073
        repo.snapshot("status").unwrap();
2074
    }
2075
    write(root, "a.txt", b"two\n");
2076
    repo.snapshot("status").unwrap();
2077
    let before = repo.store().list().unwrap();
2078
    assert!(repo.store().loose_count().unwrap() > 0);
2079
2080
    // With the default retention every operation's view is a root: nothing prunes.
2081
    let r = repo.gc(true).unwrap();
2082
    assert_eq!(r.packed.objects, before.len());
2083
    assert_eq!(r.pruned.objects, 0);
2084
    assert_eq!(repo.store().loose_count().unwrap(), 0);
2085
    assert_eq!(repo.store().list().unwrap(), before);
2086
2087
    // With zero retention only the current view is a root: superseded
2088
    // working copies go, everything reachable stays.
2089
    repo.config.set("core.op-retention", "0").unwrap();
2090
    repo.save_config().unwrap();
2091
    let mut repo = Repo::open(root).unwrap().with_home(root.join("home"));
2092
    let r = repo.gc(true).unwrap();
2093
    assert!(r.pruned.objects >= 5, "{r:?}");
2094
    let after = repo.store().list().unwrap();
2095
    assert!(after.len() < before.len());
2096
    assert!(after.contains(&h1) && after.contains(&h2));
2097
    for (_, op) in repo.op_log().unwrap() {
2098
        assert!(!op.command.is_empty(), "operation objects are all kept");
2099
    }
2100
    // Everything still works from the pruned, packed store.
2101
    assert_eq!(repo.bookmark_heads().unwrap(), vec![h2]);
2102
    assert!(matches!(
2103
        repo.verify_change(&h2).unwrap(),
2104
        SignatureStatus::Valid { .. }
2105
    ));
2106
    assert_eq!(repo.log().unwrap().len(), 3);
2107
    repo.checkout(&[h1], false, "checkout").unwrap();
2108
    assert_eq!(fs::read(root.join("a.txt")).unwrap(), b"one\n");
2109
    repo.checkout(&[h2], false, "checkout").unwrap();
2110
    assert_eq!(fs::read(root.join("big.bin")).unwrap().len(), 100_000);
2111
    assert!(!repo.snapshot("status").unwrap().changed);
2112
    // Grace period defers pruning of young garbage.
2113
    write(root, "a.txt", b"three\n");
2114
    repo.commit("three", &[]).unwrap();
2115
    let r = repo.gc(false).unwrap();
2116
    assert_eq!(r.pruned.objects, 0);
2117
    assert!(r.pruned.deferred > 0);
2118
    let r = repo.gc(true).unwrap();
2119
    assert!(r.pruned.objects > 0);
2120
    assert_eq!(repo.log().unwrap().len(), 4);
2121
    // Restoring the default retention makes the old views roots again; the
2122
    // working copies they name were pruned, which gc tolerates.
2123
    repo.config.set("core.op-retention", "90").unwrap();
2124
    repo.save_config().unwrap();
2125
    let repo = Repo::open(root).unwrap().with_home(root.join("home"));
2126
    let r = repo.gc(false).unwrap();
2127
    assert_eq!(r.pruned.objects, 0);
2128
    assert_eq!(repo.log().unwrap().len(), 4);
2129
}
2130
2131
#[test]
2132
fn describe_amend_abandon_heads() {
2133
    hermetic();
2134
    let dir = tempfile::tempdir().unwrap();
2135
    let root = dir.path();
2136
    let mut repo = Repo::init(root).unwrap().with_home(root.join("home"));
2137
    repo.create_identity("Ada", "a@b", IdentityScope::User)
2138
        .unwrap();
2139
    repo.set_user_config("core.sign", "change").unwrap();
2140
    write(root, "a.txt", b"one\n");
2141
    let h1 = repo.commit("first", &[]).unwrap();
2142
    write(root, "a.txt", b"one\ntwo\n");
2143
    let h2 = repo.commit("secnod", &[]).unwrap();
2144
    let id2 = repo.store().get_change(&h2).unwrap().change_id;
2145
2146
    // describe: same ChangeId, new hash, bookmark and working copy follow.
2147
    let h2b = repo.describe(&h2, "second").unwrap();
2148
    assert_ne!(h2b, h2);
2149
    let c = repo.store().get_change(&h2b).unwrap();
2150
    assert_eq!(
2151
        (c.change_id, c.message.as_str(), c.deps.clone()),
2152
        (id2, "second", vec![h1])
2153
    );
2154
    assert_eq!(repo.bookmark_heads().unwrap(), vec![h2b]);
2155
    assert!(matches!(
2156
        repo.verify_change(&h2b).unwrap(),
2157
        SignatureStatus::Valid { .. }
2158
    ));
2159
    let s = repo.snapshot("status").unwrap();
2160
    assert!(s.statuses.is_empty(), "{:?}", s.statuses);
2161
    assert_eq!(
2162
        repo.resolve_change(&id2.short(8)).unwrap(),
2163
        h2b,
2164
        "the old object is no longer reachable from the log"
2165
    );
2166
    // Describing a non-head rewrites its dependents (h2b → h2c') and the working copy.
2167
    let h1b = repo.describe(&h1, "first, described").unwrap();
2168
    assert_ne!(h1b, h1);
2169
    let heads = repo.bookmark_heads().unwrap();
2170
    assert_eq!(heads.len(), 1);
2171
    let top = repo.store().get_change(&heads[0]).unwrap();
2172
    assert_eq!((top.change_id, top.deps.clone()), (id2, vec![h1b]));
2173
    assert!(
2174
        matches!(
2175
            repo.verify_change(&heads[0]).unwrap(),
2176
            SignatureStatus::Valid { .. }
2177
        ),
2178
        "rewritten own change is re-signed"
2179
    );
2180
    let (_, wc) = repo.working_copy().unwrap();
2181
    assert_eq!(
2182
        wc.deps,
2183
        vec![heads[0]],
2184
        "the working copy follows the rewrite"
2185
    );
2186
    assert!(!repo.snapshot("status").unwrap().changed);
2187
    let snap = repo.load_state(&heads).unwrap().materialize();
2188
    assert!(
2189
        matches!(&snap.files["a.txt"].content, FileContent::Text { bytes, .. } if bytes == b"one\ntwo\n")
2190
    );
2191
2192
    // amend: fold an edit into the head; the result is one change from h1.
2193
    write(root, "a.txt", b"one\ntwo\nthree\n");
2194
    write(root, "b.txt", b"b\n");
2195
    let h2c = repo.amend(None).unwrap();
2196
    let c = repo.store().get_change(&h2c).unwrap();
2197
    assert_eq!(c.change_id, id2);
2198
    assert_eq!(c.message, "second");
2199
    assert_eq!(repo.bookmark_heads().unwrap(), vec![h2c]);
2200
    assert_eq!(
2201
        repo.log().unwrap().len(),
2202
        3,
2203
        "working copy, amended head, first"
2204
    );
2205
    let snap = repo.load_state(&[h2c]).unwrap().materialize();
2206
    assert!(
2207
        matches!(&snap.files["a.txt"].content, FileContent::Text { bytes, .. } if bytes == b"one\ntwo\nthree\n")
2208
    );
2209
    assert!(snap.files.contains_key("b.txt"));
2210
    assert!(!repo.snapshot("status").unwrap().changed);
2211
    assert!(
2212
        repo.amend(None).is_err(),
2213
        "clean working copy and no message"
2214
    );
2215
    let h2d = repo.amend(Some("second, amended")).unwrap();
2216
    assert_eq!(
2217
        repo.store().get_change(&h2d).unwrap().message,
2218
        "second, amended"
2219
    );
2220
2221
    // abandon: the head goes, its content stays as uncommitted work.
2222
    repo.abandon(&h2d).unwrap();
2223
    assert_eq!(
2224
        repo.bookmark_heads().unwrap(),
2225
        vec![h1b],
2226
        "the described first change is the head again"
2227
    );
2228
    let s = repo.snapshot("status").unwrap();
2229
    let paths: Vec<_> = s
2230
        .statuses
2231
        .iter()
2232
        .map(|p| (p.path.as_str(), p.status))
2233
        .collect();
2234
    assert_eq!(
2235
        paths,
2236
        vec![
2237
            ("a.txt", ChangeStatus::Modified),
2238
            ("b.txt", ChangeStatus::Added)
2239
        ]
2240
    );
2241
    assert_eq!(fs::read(root.join("a.txt")).unwrap(), b"one\ntwo\nthree\n");
2242
    let h3 = repo.commit("recommitted", &[]).unwrap();
2243
    assert_eq!(repo.bookmark_heads().unwrap(), vec![h3]);
2244
    // undo brings the abandoned head back.
2245
    repo.undo().unwrap();
2246
    repo.undo().unwrap();
2247
    assert_eq!(repo.bookmark_heads().unwrap(), vec![h2d]);
2248
2249
    // Abandoning a non-head whose dependent references its atoms reifies
2250
    // the references (here: a.txt vanishes with it, so the dependent's edit
2251
    // of a.txt is dropped with a note) instead of refusing; undo restores it.
2252
    let base = repo.bookmark_heads().unwrap()[0];
2253
    let base_change = repo.store().get_change(&base).unwrap();
2254
    let h1_now = base_change.deps[0];
2255
    let notes = repo.abandon(&h1_now).unwrap();
2256
    assert!(
2257
        !notes.is_empty(),
2258
        "the dependent's edit of a.txt was reified"
2259
    );
2260
    let heads = repo.bookmark_heads().unwrap();
2261
    let after = repo.load_state(&heads).unwrap().materialize();
2262
    assert!(
2263
        !after.files.contains_key("a.txt") && after.files.contains_key("b.txt"),
2264
        "{:?}",
2265
        after.files.keys()
2266
    );
2267
    repo.undo().unwrap();
2268
    assert_eq!(repo.bookmark_heads().unwrap(), vec![base]);
2269
    write(root, "c.txt", b"c\n");
2270
    let hc = repo.commit("c", &[]).unwrap();
2271
    write(root, "d.txt", b"d\n");
2272
    let hd = repo.commit("d", &[hc]).unwrap();
2273
    assert_eq!(repo.store().get_change(&hd).unwrap().deps, vec![hc]);
2274
    repo.abandon(&hc).unwrap();
2275
    let heads: BTreeSet<_> = repo.bookmark_heads().unwrap().into_iter().collect();
2276
    assert!(!heads.contains(&hc));
2277
    let d_now = heads
2278
        .iter()
2279
        .find(|h| repo.store().get_change(h).unwrap().message == "d")
2280
        .copied()
2281
        .unwrap();
2282
    assert!(
2283
        repo.store().get_change(&d_now).unwrap().deps.is_empty(),
2284
        "d inherited c's (empty) dependencies"
2285
    );
2286
    let s = repo.snapshot("status").unwrap();
2287
    assert_eq!(
2288
        s.statuses
2289
            .iter()
2290
            .map(|p| p.path.as_str())
2291
            .collect::<Vec<_>>(),
2292
        vec!["c.txt"],
2293
        "c's content is now uncommitted work"
2294
    );
2295
}
2296
2297
#[test]
2298
fn git_export_mirrors_history() {
2299
    hermetic();
2300
    if std::process::Command::new("git")
2301
        .arg("--version")
2302
        .output()
2303
        .is_err()
2304
    {
2305
        eprintln!("git not installed; skipping");
2306
        return;
2307
    }
2308
    let dir = tempfile::tempdir().unwrap();
2309
    let root = dir.path();
2310
    let mut repo = Repo::init(&root.join("r"))
2311
        .unwrap()
2312
        .with_home(root.join("home"));
2313
    repo.create_identity("Ada Lovelace", "[email protected]", IdentityScope::User)
2314
        .unwrap();
2315
    let r = root.join("r");
2316
    write(&r, "README.md", b"hello\n");
2317
    write(&r, "src/main.rs", b"fn main() {}\n");
2318
    let h1 = repo.commit("first", &[]).unwrap();
2319
    write(&r, "src/main.rs", b"fn main() { run(); }\n");
2320
    write(&r, "logo.png", b"\x89PNG\0\0");
2321
    let h2 = repo.commit("second", &[]).unwrap();
2322
2323
    let git_dir = root.join("mirror.git");
2324
    let rep = repo.git_export(&git_dir).unwrap();
2325
    assert_eq!((rep.exported, rep.skipped, rep.heads), (2, 0, 1));
2326
    let git = |args: &[&str]| -> String {
2327
        let out = std::process::Command::new("git")
2328
            .arg("-C")
2329
            .arg(&git_dir)
2330
            .args(args)
2331
            .output()
2332
            .unwrap();
2333
        assert!(
2334
            out.status.success(),
2335
            "{}",
2336
            String::from_utf8_lossy(&out.stderr)
2337
        );
2338
        String::from_utf8_lossy(&out.stdout).trim().to_string()
2339
    };
2340
    assert_eq!(git(&["log", "--format=%s", "main"]), "second\nfirst");
2341
    assert_eq!(git(&["show", "main:src/main.rs"]), "fn main() { run(); }");
2342
    assert_eq!(git(&["show", "main:README.md"]), "hello");
2343
    let body = git(&["log", "-1", "--format=%B", "main"]);
2344
    assert!(
2345
        body.contains(&format!("Oxy-Hash: {}", h2.to_hex())),
2346
        "{body}"
2347
    );
2348
    assert!(body.contains("Change-Id: "), "{body}");
2349
    assert_eq!(
2350
        git(&["log", "-1", "--format=%an <%ae>", "main"]),
2351
        "Ada Lovelace <[email protected]>"
2352
    );
2353
    assert_eq!(
2354
        git(&["ls-tree", "--name-only", "main"]),
2355
        "README.md\nlogo.png\nsrc"
2356
    );
2357
2358
    // Re-export is incremental.
2359
    let rep = repo.git_export(&git_dir).unwrap();
2360
    assert_eq!((rep.exported, rep.skipped), (0, 2));
2361
2362
    // An independent change makes two heads; the next state is one more
2363
    // commit on the linear branch whose tree is the union.
2364
    repo.checkout(&[h1], false, "checkout").unwrap();
2365
    write(&r, "other.txt", b"o\n");
2366
    let h3 = repo.commit("third", &[]).unwrap();
2367
    let rep = repo.git_export(&git_dir).unwrap();
2368
    assert_eq!((rep.exported, rep.heads), (1, 2));
2369
    assert_eq!(git(&["log", "--format=%s", "main"]), "third\nsecond\nfirst");
2370
    let parents = git(&["rev-list", "--parents", "-1", "main"]);
2371
    assert_eq!(parents.split(' ').count(), 2, "one parent: {parents}");
2372
    assert_eq!(git(&["show", "main:other.txt"]), "o");
2373
    assert_eq!(git(&["show", "main:src/main.rs"]), "fn main() { run(); }");
2374
    assert_eq!(
2375
        git(&["ls-tree", "--name-only", "main"]),
2376
        "README.md\nlogo.png\nother.txt\nsrc"
2377
    );
2378
    let body = git(&["log", "-1", "--format=%B", "main"]);
2379
    assert!(
2380
        body.contains(&format!("Oxy-Hash: {}", h3.to_hex())) && body.contains("Oxy-State: "),
2381
        "{body}"
2382
    );
2383
    // A rewrite is a new state whose one new change is the rewritten one.
2384
    repo.describe(&h3, "third, described").unwrap();
2385
    let rep = repo.git_export(&git_dir).unwrap();
2386
    assert_eq!(rep.exported, 1);
2387
    assert_eq!(
2388
        git(&["log", "-1", "--format=%s", "main"]),
2389
        "third, described"
2390
    );
2391
    assert_eq!(git(&["log", "--format=%s", "main"]).lines().count(), 4);
2392
    let _ = h2;
2393
}
2394
2395
#[test]
2396
fn git_import_reproduces_trees() {
2397
    git_import_reproduces_trees_with(None);
2398
}
2399
2400
/// The same import with every merge rendered in batches of one file
2401
/// (oxygen#25): what a merge onto a base of thousands of files takes.
2402
#[test]
2403
fn git_import_reproduces_trees_in_batches() {
2404
    git_import_reproduces_trees_with(Some(1));
2405
}
2406
2407
fn git_import_reproduces_trees_with(batch: Option<usize>) {
2408
    crate::repo::git::set_merge_batch_for_tests(batch);
2409
    hermetic();
2410
    if std::process::Command::new("git")
2411
        .arg("--version")
2412
        .output()
2413
        .is_err()
2414
    {
2415
        eprintln!("git not installed; skipping");
2416
        return;
2417
    }
2418
    let dir = tempfile::tempdir().unwrap();
2419
    let root = dir.path();
2420
    let g = root.join("src.git");
2421
    fs::create_dir_all(&g).unwrap();
2422
    let git = |args: &[&str]| -> String {
2423
        let out = std::process::Command::new("git")
2424
            .arg("-C")
2425
            .arg(&g)
2426
            .args([
2427
                "-c",
2428
                "user.name=Grace",
2429
                "-c",
2430
                "[email protected]",
2431
                "-c",
2432
                "commit.gpgsign=false",
2433
            ])
2434
            .args(args)
2435
            .output()
2436
            .unwrap();
2437
        assert!(
2438
            out.status.success(),
2439
            "git {args:?}: {}",
2440
            String::from_utf8_lossy(&out.stderr)
2441
        );
2442
        String::from_utf8_lossy(&out.stdout).trim().to_string()
2443
    };
2444
    git(&["init", "-q", "-b", "main"]);
2445
    write(&g, "README.md", b"# Hi\n");
2446
    write(&g, "src/lib.rs", b"pub fn a() {}\n");
2447
    git(&["add", "."]);
2448
    git(&["commit", "-q", "-m", "initial"]);
2449
    write(&g, "src/lib.rs", b"pub fn a() {}\npub fn b() {}\n");
2450
    write(&g, "run.sh", b"#!/bin/sh\n");
2451
    #[cfg(unix)]
2452
    {
2453
        use std::os::unix::fs::PermissionsExt;
2454
        fs::set_permissions(g.join("run.sh"), fs::Permissions::from_mode(0o755)).unwrap();
2455
    }
2456
    write(&g, "logo.png", b"\x89PNG\0\0\x01");
2457
    git(&["add", "."]);
2458
    git(&[
2459
        "commit",
2460
        "-q",
2461
        "-m",
2462
        "second\n\nChange-Id: 0123456789abcdef0123456789abcdef",
2463
    ]);
2464
    // A branch that edits README, merged back with a conflict-free merge.
2465
    git(&["checkout", "-q", "-b", "topic", "HEAD~1"]);
2466
    write(&g, "README.md", b"# Hi\n\nMore.\n");
2467
    git(&["commit", "-q", "-am", "readme"]);
2468
    git(&["checkout", "-q", "main"]);
2469
    git(&["merge", "-q", "--no-ff", "-m", "merge topic", "topic"]);
2470
    // A branch from the initial commit inserting at the same place as
2471
    // "second": concurrent in Oxygen too, so the merge commit is a resolution.
2472
    let initial = git(&["rev-list", "--max-parents=0", "HEAD"]);
2473
    git(&["checkout", "-q", "-b", "clash", &initial]);
2474
    write(&g, "src/lib.rs", b"pub fn a() {}\npub fn c() {}\n");
2475
    git(&["commit", "-q", "-am", "clash"]);
2476
    git(&["checkout", "-q", "main"]);
2477
    let _ = std::process::Command::new("git")
2478
        .arg("-C")
2479
        .arg(&g)
2480
        .args(["merge", "-q", "clash"])
2481
        .output();
2482
    write(
2483
        &g,
2484
        "src/lib.rs",
2485
        b"pub fn a() {}\npub fn b() {}\npub fn c() {}\n",
2486
    );
2487
    git(&["add", "."]);
2488
    git(&["commit", "-q", "-m", "resolve clash"]);
2489
    git(&["rm", "-q", "logo.png"]);
2490
    git(&["commit", "-q", "-m", "drop logo"]);
2491
    // A rename with a small edit is imported as a move of the same node.
2492
    git(&["mv", "src/lib.rs", "src/lib2.rs"]);
2493
    write(
2494
        &g,
2495
        "src/lib2.rs",
2496
        b"pub fn a() {}\npub fn b() {}\npub fn c() {}\npub fn d() {}\n",
2497
    );
2498
    git(&["add", "."]);
2499
    git(&["commit", "-q", "-m", "rename lib"]);
2500
    // A branch that edits run.sh, merged keeping main's tree (`-s ours`):
2501
    // run.sh is the same as in the first parent's tree, but the merged
2502
    // change touched it, so the importer must compare it, not skip it.
2503
    git(&["checkout", "-q", "-b", "discarded"]);
2504
    write(&g, "run.sh", b"#!/bin/sh\necho discarded\n");
2505
    git(&["commit", "-q", "-am", "discarded edit"]);
2506
    git(&["checkout", "-q", "main"]);
2507
    git(&[
2508
        "merge",
2509
        "-q",
2510
        "-s",
2511
        "ours",
2512
        "-m",
2513
        "merge discarded, keeping ours",
2514
        "discarded",
2515
    ]);
2516
    let expected_count: usize = git(&["rev-list", "--count", "main"]).parse().unwrap();
2517
2518
    let dest = root.join("oxy");
2519
    let repo = Repo::init(&dest).unwrap().with_home(root.join("home"));
2520
    let rep = repo.import_git(&g, "main").unwrap();
2521
    assert_eq!(rep.commits, expected_count);
2522
    assert_eq!(rep.merges, 3);
2523
    assert_eq!(
2524
        fs::read(dest.join("run.sh")).unwrap(),
2525
        b"#!/bin/sh\n",
2526
        "the ours merge kept main's run.sh"
2527
    );
2528
    let v = repo.verify_git_import(&g, "main").unwrap();
2529
    assert_eq!(v.commits, expected_count, "every commit's tree reproduced");
2530
    assert!(v.mismatches.is_empty(), "{:?}", v.mismatches);
2531
    // The working copy equals the Git tree at main.
2532
    assert_eq!(
2533
        fs::read(dest.join("src/lib2.rs")).unwrap(),
2534
        b"pub fn a() {}\npub fn b() {}\npub fn c() {}\npub fn d() {}\n"
2535
    );
2536
    assert!(!dest.join("src/lib.rs").exists());
2537
    assert_eq!(
2538
        fs::read(dest.join("README.md")).unwrap(),
2539
        b"# Hi\n\nMore.\n"
2540
    );
2541
    assert!(!dest.join("logo.png").exists());
2542
    #[cfg(unix)]
2543
    {
2544
        use std::os::unix::fs::PermissionsExt;
2545
        assert!(
2546
            fs::metadata(dest.join("run.sh"))
2547
                .unwrap()
2548
                .permissions()
2549
                .mode()
2550
                & 0o111
2551
                != 0
2552
        );
2553
    }
2554
    assert!(
2555
        !repo.snapshot("status").unwrap().changed,
2556
        "clean after import"
2557
    );
2558
    let heads = repo.bookmark_heads().unwrap();
2559
    let st = repo.load_state(&heads).unwrap();
2560
    assert!(!st.materialize().is_conflicted());
2561
    assert_eq!(st.len(), expected_count);
2562
    let tip = repo
2563
        .log()
2564
        .unwrap()
2565
        .into_iter()
2566
        .find(|e| e.change.message.starts_with("rename lib"))
2567
        .unwrap();
2568
    let c = repo.store().get_change(&tip.hash).unwrap();
2569
    assert!(
2570
        c.tree_ops
2571
            .iter()
2572
            .any(|op| matches!(op, TreeOp::Move { name, .. } if name == "lib2.rs")),
2573
        "{:?}",
2574
        c.tree_ops
2575
    );
2576
    assert!(!c
2577
        .tree_ops
2578
        .iter()
2579
        .any(|op| matches!(op, TreeOp::AddNode { .. })));
2580
    // Messages carry Git trailers; the Change-Id trailer was honoured.
2581
    let log = repo.log().unwrap();
2582
    let second = log
2583
        .iter()
2584
        .find(|e| e.change.message.starts_with("second"))
2585
        .unwrap();
2586
    assert_eq!(
2587
        second.change.change_id,
2588
        ChangeId::from_hex("0123456789abcdef0123456789abcdef").unwrap()
2589
    );
2590
    assert!(second
2591
        .change
2592
        .message
2593
        .contains("Git-Author: Grace <[email protected]>"));
2594
    let resolve = log
2595
        .iter()
2596
        .find(|e| e.change.message.starts_with("resolve clash"))
2597
        .unwrap();
2598
    assert_eq!(
2599
        resolve.change.kind,
2600
        ChangeKind::Resolution,
2601
        "a conflicting Git merge becomes a resolution"
2602
    );
2603
    // Re-importing into another fresh repository gives the same ChangeIds.
2604
    let repo2 = Repo::init(&root.join("oxy2"))
2605
        .unwrap()
2606
        .with_home(root.join("home"));
2607
    repo2.import_git(&g, "main").unwrap();
2608
    // New nodes' identifiers derive from the commit (spec §23), so the
2609
    // re-import is not just the same ChangeIds but the same changes.
2610
    assert_eq!(
2611
        repo2.bookmark_heads().unwrap(),
2612
        repo.bookmark_heads().unwrap()
2613
    );
2614
    let ids: BTreeSet<ChangeId> = repo
2615
        .log()
2616
        .unwrap()
2617
        .iter()
2618
        .filter(|e| !e.is_working_copy)
2619
        .map(|e| e.change.change_id)
2620
        .collect();
2621
    let ids2: BTreeSet<ChangeId> = repo2
2622
        .log()
2623
        .unwrap()
2624
        .iter()
2625
        .filter(|e| !e.is_working_copy)
2626
        .map(|e| e.change.change_id)
2627
        .collect();
2628
    assert_eq!(ids, ids2);
2629
    // Round trip back out to Git reproduces the tip tree.
2630
    let mirror = root.join("mirror.git");
2631
    repo.git_export(&mirror).unwrap();
2632
    let out = std::process::Command::new("git")
2633
        .arg("-C")
2634
        .arg(&mirror)
2635
        .args(["show", "main:src/lib2.rs"])
2636
        .output()
2637
        .unwrap();
2638
    assert_eq!(
2639
        String::from_utf8_lossy(&out.stdout),
2640
        "pub fn a() {}\npub fn b() {}\npub fn c() {}\npub fn d() {}\n"
2641
    );
2642
    let out = std::process::Command::new("git")
2643
        .arg("-C")
2644
        .arg(&mirror)
2645
        .args(["show", "main:src/lib.rs"])
2646
        .output()
2647
        .unwrap();
2648
    assert!(
2649
        !out.status.success(),
2650
        "the old path is gone from the export"
2651
    );
2652
}
2653
2654
#[test]
2655
fn checkpoints_accelerate_loading_and_stay_correct() {
2656
    hermetic();
2657
    let dir = tempfile::tempdir().unwrap();
2658
    let root = dir.path();
2659
    let mut repo = Repo::init(root).unwrap().with_home(root.join("home"));
2660
    repo.config.set("core.checkpoint-interval", "5").unwrap();
2661
    repo.save_config().unwrap();
2662
    let repo = Repo::open(root).unwrap().with_home(root.join("home"));
2663
    let mut hashes = Vec::new();
2664
    for i in 0..12 {
2665
        write(
2666
            root,
2667
            "a.txt",
2668
            format!(
2669
                "{}\n",
2670
                (0..=i)
2671
                    .map(|k| k.to_string())
2672
                    .collect::<Vec<_>>()
2673
                    .join("\n")
2674
            )
2675
            .as_bytes(),
2676
        );
2677
        write(root, &format!("f{i}.txt"), b"x\n");
2678
        hashes.push(repo.commit(&format!("c{i}"), &[]).unwrap());
2679
    }
2680
    let (_, cp) = repo
2681
        .latest_checkpoint("main")
2682
        .unwrap()
2683
        .expect("automatic checkpoint");
2684
    assert!(cp.count >= 5 && cp.count <= 12, "{}", cp.count);
2685
    // Loading through the checkpoint equals loading everything.
2686
    let heads = repo.bookmark_heads().unwrap();
2687
    let fast = repo.load_state(&heads).unwrap();
2688
    let full = repo.load_state_full(&heads).unwrap();
2689
    assert_eq!(fast.len(), full.len());
2690
    assert_eq!(fast.heads(), full.heads());
2691
    let (a, b) = (fast.materialize(), full.materialize());
2692
    assert_eq!(
2693
        a.files.keys().collect::<Vec<_>>(),
2694
        b.files.keys().collect::<Vec<_>>()
2695
    );
2696
    for (p, f) in &a.files {
2697
        assert_eq!(f.content, b.files[p].content, "{p}");
2698
    }
2699
    assert!(repo.load_state_checkpointed(&heads).unwrap().is_some());
2700
    // A head set that does not contain the checkpoint's heads falls back.
2701
    assert!(repo
2702
        .load_state_checkpointed(&[hashes[0]])
2703
        .unwrap()
2704
        .is_none());
2705
    assert_eq!(repo.load_state(&[hashes[0]]).unwrap().len(), 1);
2706
    // Everything else keeps working on top of the checkpoint.
2707
    assert!(!repo.snapshot("status").unwrap().changed);
2708
    let h = repo.describe(&hashes[3], "c3 described").unwrap();
2709
    assert_eq!(repo.store().get_change(&h).unwrap().message, "c3 described");
2710
    let (r, n, bytes) = repo.checkpoint().unwrap();
2711
    assert!(n >= 12 && bytes > 0);
2712
    assert_eq!(repo.latest_checkpoint("main").unwrap().unwrap().0, r);
2713
    write(root, "a.txt", b"after\n");
2714
    let h_after = repo.commit("after", &[]).unwrap();
2715
    let st = repo.load_state(&repo.bookmark_heads().unwrap()).unwrap();
2716
    assert!(st.contains(&h_after));
2717
    assert!(
2718
        matches!(&st.materialize().files["a.txt"].content, FileContent::Text { bytes, .. } if bytes == b"after\n")
2719
    );
2720
    assert_eq!(repo.log().unwrap().len(), 14);
2721
    // Checkpoints survive gc.
2722
    repo.gc(true).unwrap();
2723
    assert!(repo.latest_checkpoint("main").unwrap().is_some());
2724
    assert!(repo
2725
        .load_state_checkpointed(&repo.bookmark_heads().unwrap())
2726
        .unwrap()
2727
        .is_some());
2728
}
2729
2730
#[test]
2731
fn quick_status_for_prompts() {
2732
    hermetic();
2733
    let dir = tempfile::tempdir().unwrap();
2734
    let root = dir.path();
2735
    let origin = Repo::init(&root.join("origin")).unwrap();
2736
    let url = root.join("origin").to_string_lossy().to_string();
2737
    let a = Repo::clone(&url, &root.join("a"))
2738
        .unwrap()
2739
        .with_home(root.join("home"));
2740
    let ops_before = a.op_log().unwrap().len();
2741
    let info = a.quick_status().unwrap();
2742
    assert_eq!(
2743
        (
2744
            info.bookmark.as_str(),
2745
            info.heads,
2746
            info.dirty,
2747
            info.conflicted,
2748
            info.ahead,
2749
            info.behind
2750
        ),
2751
        ("main", 0, false, false, Some(0), Some(0))
2752
    );
2753
    write(&root.join("a"), "f.txt", b"f\n");
2754
    assert!(a.quick_status().unwrap().dirty, "a new file is dirty");
2755
    assert_eq!(
2756
        a.op_log().unwrap().len(),
2757
        ops_before,
2758
        "quick_status records nothing"
2759
    );
2760
    // A snapshotted but uncommitted change is still dirty.
2761
    a.snapshot("status").unwrap();
2762
    assert!(a.quick_status().unwrap().dirty);
2763
    a.commit("f", &[]).unwrap();
2764
    let info = a.quick_status().unwrap();
2765
    assert!(!info.dirty, "clean right after a commit");
2766
    assert_eq!((info.ahead, info.behind), (Some(1), Some(0)));
2767
    assert_eq!(
2768
        info.format("%b %c%d%x%A%D"),
2769
        format!("main {}+1", info.change_id)
2770
    );
2771
    assert_eq!(info.format("[%h heads] %a/%B %%"), "[1 heads] 1/0 %");
2772
    // Touching a file without changing it is not dirty; changing content of
2773
    // the same size is.
2774
    let p = root.join("a/f.txt");
2775
    let content = fs::read(&p).unwrap();
2776
    fs::write(&p, &content).unwrap();
2777
    assert!(!a.quick_status().unwrap().dirty);
2778
    fs::write(&p, b"g\n").unwrap();
2779
    assert!(a.quick_status().unwrap().dirty);
2780
    fs::write(&p, b"f\n").unwrap();
2781
    // Push, then a second clone commits and pushes: we are behind.
2782
    assert!(a.push("origin", false).unwrap()[0].ok);
2783
    assert_eq!(a.quick_status().unwrap().ahead, Some(0));
2784
    let b = Repo::clone(&url, &root.join("b"))
2785
        .unwrap()
2786
        .with_home(root.join("home-b"));
2787
    write(&root.join("b"), "g.txt", b"g\n");
2788
    b.commit("g", &[]).unwrap();
2789
    b.push("origin", false).unwrap();
2790
    a.fetch("origin").unwrap();
2791
    let info = a.quick_status().unwrap();
2792
    assert_eq!((info.ahead, info.behind), (Some(0), Some(1)));
2793
    assert_eq!(info.format("%A%D"), "-1");
2794
    let _ = origin;
2795
}
2796
2797
#[test]
2798
fn lazy_blobs_are_fetched_on_first_read() {
2799
    hermetic();
2800
    let dir = tempfile::tempdir().unwrap();
2801
    let root = dir.path();
2802
    let origin_dir = root.join("origin");
2803
    let origin = Repo::init(&origin_dir)
2804
        .unwrap()
2805
        .with_home(root.join("home"));
2806
    let url = origin_dir.to_string_lossy().to_string();
2807
    let big: Vec<u8> = (0..200_000u32).map(|i| (i % 251) as u8).collect(); // has NUL bytes: opaque
2808
    write(&origin_dir, "big.bin", &big);
2809
    write(&origin_dir, "small.bin", &[0u8, 1, 2]);
2810
    write(&origin_dir, "t.txt", b"t\n");
2811
    let h = origin.commit("blobs", &[]).unwrap();
2812
    let big_ref = Repo::blob_ref(&big);
2813
2814
    // Fetch only (no checkout) with a filter: the big blob stays absent.
2815
    let a = Repo::init_with_id(&root.join("a"), origin.id().unwrap())
2816
        .unwrap()
2817
        .with_home(root.join("home"));
2818
    let a = {
2819
        let mut a = a;
2820
        a.config.set("remote.origin.url", &url).unwrap();
2821
        a.config.set("filter.max-blob", "100K").unwrap();
2822
        a.save_config().unwrap();
2823
        a
2824
    };
2825
    assert_eq!(a.config.max_blob, Some(100 * 1024));
2826
    a.fetch("origin").unwrap();
2827
    assert!(a.store().has(&h));
2828
    assert!(!a.store().has(&big_ref), "withheld");
2829
    assert!(
2830
        a.store().has(&Repo::blob_ref(&[0u8, 1, 2])),
2831
        "small blob came along"
2832
    );
2833
    assert_eq!(a.lazy_remote(&big_ref).as_deref(), Some("origin"));
2834
2835
    // status and commit do not need it: adopt the state, edit a text file, commit.
2836
    let (op_ref, op) = a.head_op().unwrap();
2837
    let mut view = op.view.clone();
2838
    view.bookmarks.insert(
2839
        "main".into(),
2840
        a.store().put_state(&StateObject::new(vec![h])).unwrap(),
2841
    );
2842
    a.record_op(&[op_ref], "adopt", view).unwrap();
2843
    // Checkout reads the blob lazily, which fetches it.
2844
    a.checkout(&[h], true, "checkout").unwrap();
2845
    assert!(a.store().has(&big_ref), "fetched on first read");
2846
    assert_eq!(fs::read(root.join("a/big.bin")).unwrap(), big);
2847
    assert!(a.lazy_remote(&big_ref).is_none(), "no longer registered");
2848
    write(&root.join("a"), "t.txt", b"t2\n");
2849
    a.commit("text edit", &[]).unwrap();
2850
2851
    // clone --max-blob records the filter; the checkout fetches lazily.
2852
    let b = Repo::clone_with(&url, &root.join("b"), Some(1024), &[]).unwrap();
2853
    assert_eq!(b.config.max_blob, Some(1024));
2854
    assert_eq!(fs::read(root.join("b/big.bin")).unwrap(), big);
2855
    assert_eq!(parse_size("2M").unwrap(), 2 << 20);
2856
    assert!(parse_size("lots").is_err());
2857
}
2858
2859
#[test]
2860
fn sparse_checkout_materializes_only_chosen_paths() {
2861
    hermetic();
2862
    let dir = tempfile::tempdir().unwrap();
2863
    let root = dir.path();
2864
    let origin_dir = root.join("origin");
2865
    let origin = Repo::init(&origin_dir)
2866
        .unwrap()
2867
        .with_home(root.join("home"));
2868
    write(&origin_dir, "src/main.rs", b"fn main() {}\n");
2869
    write(&origin_dir, "src/lib.rs", b"pub fn a() {}\n");
2870
    write(&origin_dir, "docs/guide.md", b"# guide\n");
2871
    let logo: Vec<u8> = (0..50_000u32).map(|i| (i % 7) as u8).collect();
2872
    write(&origin_dir, "docs/logo.png", &logo);
2873
    write(&origin_dir, "README.md", b"# top\n");
2874
    let h1 = origin.commit("tree", &[]).unwrap();
2875
    let url = origin_dir.to_string_lossy().to_string();
2876
2877
    let a = Repo::clone_with(&url, &root.join("a"), None, &["src".into()])
2878
        .unwrap()
2879
        .with_home(root.join("home"));
2880
    assert_eq!(a.config.sparse_paths, vec!["src"]);
2881
    assert_eq!(a.config.max_blob, Some(0), "sparse implies lazy blobs");
2882
    assert!(root.join("a/src/main.rs").exists());
2883
    assert!(!root.join("a/docs").exists() && !root.join("a/README.md").exists());
2884
    assert!(
2885
        !a.store().has(&Repo::blob_ref(&logo)),
2886
        "out-of-scope blob never fetched"
2887
    );
2888
    assert!(
2889
        !a.snapshot("status").unwrap().changed,
2890
        "out-of-scope files are not removals"
2891
    );
2892
    assert!(!a.quick_status().unwrap().dirty);
2893
2894
    // Edits in scope commit normally and keep the rest of the tree intact.
2895
    write(
2896
        &root.join("a"),
2897
        "src/lib.rs",
2898
        b"pub fn a() {}\npub fn b() {}\n",
2899
    );
2900
    let h2 = a.commit("edit lib", &[]).unwrap();
2901
    let st = a.load_state(&[h2]).unwrap().materialize();
2902
    assert!(
2903
        st.files.contains_key("docs/guide.md"),
2904
        "the state still has everything"
2905
    );
2906
    assert!(a.push("origin", false).unwrap()[0].ok);
2907
    origin.refresh().unwrap();
2908
    // Files created outside the scope are ignored by status.
2909
    write(&root.join("a"), "docs/new.md", b"ignored\n");
2910
    assert!(a.snapshot("status").unwrap().statuses.is_empty());
2911
2912
    // Widening the filter checks out the rest; narrowing leaves stray files alone.
2913
    let mut a = a;
2914
    a.config.set("filter.paths", "src,docs").unwrap();
2915
    a.save_config().unwrap();
2916
    let r = a
2917
        .checkout(&a.bookmark_heads().unwrap(), true, "widen")
2918
        .unwrap();
2919
    assert!(r.written >= 2);
2920
    assert_eq!(
2921
        fs::read(root.join("a/docs/logo.png")).unwrap(),
2922
        logo,
2923
        "now fetched lazily"
2924
    );
2925
    assert!(!root.join("a/README.md").exists());
2926
    // Origin sees the change made under a sparse checkout with the full tree intact.
2927
    origin.pull("origin").err();
2928
    let full = origin
2929
        .load_state(&origin.bookmark_heads().unwrap())
2930
        .unwrap()
2931
        .materialize();
2932
    assert!(
2933
        matches!(&full.files["src/lib.rs"].content, FileContent::Text { bytes, .. } if bytes == b"pub fn a() {}\npub fn b() {}\n")
2934
    );
2935
    assert!(full.files.contains_key("README.md"));
2936
    let _ = h1;
2937
}
2938
2939
#[test]
2940
fn shallow_clone_and_deepen() {
2941
    hermetic();
2942
    let dir = tempfile::tempdir().unwrap();
2943
    let root = dir.path();
2944
    let origin_dir = root.join("origin");
2945
    let origin = Repo::init(&origin_dir)
2946
        .unwrap()
2947
        .with_home(root.join("home"));
2948
    let mut hashes = Vec::new();
2949
    for i in 0..8 {
2950
        write(
2951
            &origin_dir,
2952
            "a.txt",
2953
            format!(
2954
                "{}\n",
2955
                (0..=i)
2956
                    .map(|k| k.to_string())
2957
                    .collect::<Vec<_>>()
2958
                    .join("\n")
2959
            )
2960
            .as_bytes(),
2961
        );
2962
        hashes.push(origin.commit(&format!("c{i}"), &[]).unwrap());
2963
    }
2964
    let url = origin_dir.to_string_lossy().to_string();
2965
    let a = Repo::clone_shallow(&url, &root.join("a"), 3, None, &[])
2966
        .unwrap()
2967
        .with_home(root.join("home"));
2968
    assert!(a.is_shallow());
2969
    assert_eq!(
2970
        fs::read_to_string(root.join("a/a.txt")).unwrap(),
2971
        "0\n1\n2\n3\n4\n5\n6\n7\n"
2972
    );
2973
    assert!(
2974
        a.store().has(&hashes[7]) && a.store().has(&hashes[5]),
2975
        "three levels present"
2976
    );
2977
    assert!(!a.store().has(&hashes[4]), "beyond the depth is absent");
2978
    assert_eq!(a.boundary(), [hashes[4]].into_iter().collect());
2979
    assert_eq!(
2980
        a.log().unwrap().len(),
2981
        9,
2982
        "the log shows every change from the checkpoint's metadata"
2983
    );
2984
    assert!(!a.snapshot("status").unwrap().changed);
2985
    assert_eq!(a.quick_status().unwrap().heads, 1);
2986
2987
    // Work continues on top of the shallow history and pushes back.
2988
    write(&root.join("a"), "a.txt", b"0\n1\n2\n3\n4\n5\n6\n7\n8\n");
2989
    let h_new = a.commit("c8", &[]).unwrap();
2990
    assert!(a.push("origin", false).unwrap()[0].ok);
2991
    origin.refresh().unwrap();
2992
    assert_eq!(origin.bookmark_heads().unwrap(), vec![h_new]);
2993
    // Fetching new work from origin into the shallow clone works too.
2994
    write(&origin_dir, "b.txt", b"b\n");
2995
    origin.pull("origin").err();
2996
    let (_, wc) = origin.working_copy().unwrap();
2997
    let _ = wc;
2998
    origin
2999
        .checkout(&origin.bookmark_heads().unwrap(), true, "co")
3000
        .unwrap();
3001
    write(&origin_dir, "b.txt", b"b\n");
3002
    let h_b = origin.commit("b", &[]).unwrap();
3003
    let pr = a.pull("origin").unwrap();
3004
    assert!(pr.changed);
3005
    assert!(a.store().has(&h_b));
3006
    assert!(root.join("a/b.txt").exists());
3007
3008
    // Deepening fetches older history until the boundary is gone.
3009
    // Every commit also depends on the change that created the file, so two
3010
    // levels below the boundary hold h4, h3, and the root.
3011
    assert!(a.deepen("origin", 2).unwrap() >= 2);
3012
    assert!(a.store().has(&hashes[3]));
3013
    assert!(a.is_shallow());
3014
    a.deepen("origin", 100).unwrap();
3015
    assert!(!a.is_shallow(), "boundary reached the root");
3016
    assert!(a.store().has(&hashes[0]));
3017
    assert_eq!(
3018
        a.load_state_full(&a.bookmark_heads().unwrap())
3019
            .unwrap()
3020
            .len(),
3021
        10
3022
    );
3023
}
3024
3025
#[test]
3026
fn a_tag_is_withdrawn_by_a_signed_withdrawal() {
3027
    hermetic();
3028
    let dir = tempfile::tempdir().unwrap();
3029
    let root = dir.path();
3030
    let origin = Repo::init(&root.join("origin")).unwrap();
3031
    let url = root.join("origin").to_string_lossy().to_string();
3032
    let mut a = Repo::clone(&url, &root.join("a"))
3033
        .unwrap()
3034
        .with_home(root.join("home-a"));
3035
    a.create_identity("Ada", "[email protected]", IdentityScope::User)
3036
        .unwrap();
3037
    write(&root.join("a"), "f.txt", b"1\n");
3038
    let h1 = a.commit("one", &[]).unwrap();
3039
    a.tag_create("v1", &[h1], "first release").unwrap();
3040
    a.tag_create("v2", &[h1], "").unwrap();
3041
    a.policy_init().unwrap();
3042
    a.push("origin", false).unwrap();
3043
    origin.refresh().unwrap();
3044
    let original = a
3045
        .tag_refs()
3046
        .unwrap()
3047
        .into_iter()
3048
        .find(|t| t.name == "v1")
3049
        .unwrap();
3050
    let b = Repo::clone(&url, &root.join("b"))
3051
        .unwrap()
3052
        .with_home(root.join("home-b"));
3053
    assert_eq!(b.tag_heads("v1").unwrap(), Some(vec![h1]));
3054
3055
    // A key the policy does not let create the tag may not withdraw it.
3056
    let mut c = Repo::clone(&url, &root.join("c"))
3057
        .unwrap()
3058
        .with_home(root.join("home-c"));
3059
    c.create_identity("Cy", "[email protected]", IdentityScope::User)
3060
        .unwrap();
3061
    let r = c.push_delete("origin", "tags/v1").unwrap();
3062
    assert!(
3063
        !r[0].ok && r[0].reason.contains("may not withdraw"),
3064
        "{r:?}"
3065
    );
3066
    assert_eq!(c.tag_heads("v1").unwrap(), None, "withdrawn there first");
3067
    origin.refresh().unwrap();
3068
    assert_eq!(origin.tag_heads("v1").unwrap(), Some(vec![h1]));
3069
3070
    // Its creator's key may: the tag goes, the withdrawal stays.
3071
    let r = a.push_delete("origin", "tags/v1").unwrap();
3072
    assert!(r[0].ok && r[0].reason == "withdrawn", "{r:?}");
3073
    origin.refresh().unwrap();
3074
    assert_eq!(origin.tag_heads("v1").unwrap(), None);
3075
    assert_eq!(a.tag_heads("v1").unwrap(), None);
3076
    assert!(origin.tag_withdrawal("v1").unwrap().is_some());
3077
    assert!(origin.tag_attest("v1").unwrap().is_some(), "kept beside it");
3078
    let refs = origin.remote_refs().unwrap();
3079
    assert!(refs.tags.iter().all(|t| t.name != "v1"));
3080
    assert_eq!(refs.withdrawn.len(), 1);
3081
    let r = a.push_delete("origin", "tags/v1").unwrap();
3082
    assert!(r[0].ok && r[0].reason == "already withdrawn", "{r:?}");
3083
3084
    // A fetch withdraws it too, and the name is never used again.
3085
    let rep = b.fetch("origin").unwrap();
3086
    assert_eq!(rep.withdrawn_tags, vec!["v1".to_string()]);
3087
    assert_eq!(b.tag_heads("v1").unwrap(), None);
3088
    assert!(b.tag_create("v1", &[h1], "").is_err());
3089
    let r = origin
3090
        .receive_push(Bundle::default(), vec![], None, vec![original])
3091
        .unwrap();
3092
    assert!(!r[0].ok && r[0].reason.contains("withdrawn"), "{r:?}");
3093
3094
    // `oxy tag delete`, then a plain push, sends it.
3095
    a.tag_delete("v2", "tagged too early").unwrap();
3096
    let r = a.push("origin", false).unwrap();
3097
    assert!(
3098
        r.iter()
3099
            .any(|x| x.name == "tags/v2" && x.ok && x.reason == "withdrawn"),
3100
        "{r:?}"
3101
    );
3102
    origin.refresh().unwrap();
3103
    assert_eq!(origin.tag_heads("v2").unwrap(), None);
3104
    let (_, w) = origin.tag_withdrawal("v2").unwrap().unwrap();
3105
    assert!(
3106
        matches!(&w.attest.body, AttestBody::Untag { reason, .. } if reason == "tagged too early")
3107
    );
3108
}
3109
3110
#[test]
3111
fn tags_are_immutable_named_states_and_travel() {
3112
    hermetic();
3113
    let dir = tempfile::tempdir().unwrap();
3114
    let root = dir.path();
3115
    let origin = Repo::init(&root.join("origin")).unwrap();
3116
    let url = root.join("origin").to_string_lossy().to_string();
3117
    let mut a = Repo::clone(&url, &root.join("a"))
3118
        .unwrap()
3119
        .with_home(root.join("home-a"));
3120
    let (key_a, _) = a
3121
        .create_identity("Ada", "[email protected]", IdentityScope::User)
3122
        .unwrap();
3123
    write(&root.join("a"), "f.txt", b"1\n");
3124
    let h1 = a.commit("one", &[]).unwrap();
3125
    write(&root.join("a"), "f.txt", b"1\n2\n");
3126
    let h2 = a.commit("two", &[]).unwrap();
3127
3128
    let t = a.tag_create("v1", &[h1], "first release").unwrap();
3129
    assert_eq!(
3130
        (t.heads.clone(), t.signer.as_deref()),
3131
        (vec![h1], Some("Ada"))
3132
    );
3133
    assert!(a.tag_create("v1", &[h2], "").is_err(), "immutable");
3134
    assert!(a.tag_create("bad/name", &[h2], "").is_err());
3135
    assert_eq!(a.tag_heads("v1").unwrap(), Some(vec![h1]));
3136
    assert_eq!(a.resolve_heads("v1").unwrap(), vec![h1]);
3137
    assert_eq!(a.resolve_heads("main").unwrap(), vec![h2]);
3138
    let (_, sa) = a.tag_attest("v1").unwrap().unwrap();
3139
    assert_eq!(sa.sigs[0].key, key_a);
3140
    // Without a policy every client is sent every tag, whatever features
3141
    // it declares (oxygen#131).
3142
    let mut refs = a.remote_refs().unwrap();
3143
    a.refs_for_client(&mut refs, None);
3144
    assert_eq!(refs.tags.len(), 1);
3145
    // Checkout by tag.
3146
    a.checkout(&a.resolve_heads("v1").unwrap(), false, "co")
3147
        .unwrap();
3148
    assert_eq!(fs::read(root.join("a/f.txt")).unwrap(), b"1\n");
3149
    a.checkout(&a.bookmark_heads().unwrap(), false, "co")
3150
        .unwrap();
3151
3152
    // Push carries the tag; a second attestation for the name is refused.
3153
    let r = a.push("origin", false).unwrap();
3154
    origin.refresh().unwrap();
3155
    assert!(r.iter().any(|x| x.name == "tags/v1" && x.ok), "{r:?}");
3156
    assert_eq!(origin.tag_heads("v1").unwrap(), Some(vec![h1]));
3157
    let mut forged = a
3158
        .tag_refs()
3159
        .unwrap()
3160
        .into_iter()
3161
        .find(|t| t.name == "v1")
3162
        .unwrap();
3163
    forged.state = origin
3164
        .store()
3165
        .put_state(&StateObject::new(vec![h2]))
3166
        .unwrap();
3167
    forged.heads = vec![h2];
3168
    forged.attestation = None;
3169
    let r = origin
3170
        .receive_push(Bundle::default(), vec![], None, vec![forged])
3171
        .unwrap();
3172
    assert!(!r[0].ok && r[0].reason.contains("immutable"), "{r:?}");
3173
3174
    // A clone gets the tag; a later tag arrives on fetch.
3175
    let b = Repo::clone(&url, &root.join("b"))
3176
        .unwrap()
3177
        .with_home(root.join("home-b"));
3178
    assert_eq!(b.tag_heads("v1").unwrap(), Some(vec![h1]));
3179
    assert!(b.tags().unwrap()[0].signer.as_deref() == Some("Ada"));
3180
    a.tag_create("v2", &[h2], "second").unwrap();
3181
    a.push("origin", false).unwrap();
3182
    origin.refresh().unwrap();
3183
    let rep = b.fetch("origin").unwrap();
3184
    assert_eq!(rep.new_tags, 1);
3185
    assert_eq!(b.tag_heads("v2").unwrap(), Some(vec![h2]));
3186
3187
    // Under a policy, an unattested tag is refused and an attested one by the root passes.
3188
    a.policy_init().unwrap();
3189
    a.push("origin", false).unwrap();
3190
    origin.refresh().unwrap();
3191
    let unattested = crate::protocol::TagRef::new(
3192
        "v3".into(),
3193
        origin
3194
            .store()
3195
            .put_state(&StateObject::new(vec![h2]))
3196
            .unwrap(),
3197
        vec![h2],
3198
        None,
3199
    );
3200
    let r = origin
3201
        .receive_push(Bundle::default(), vec![], None, vec![unattested])
3202
        .unwrap();
3203
    assert!(!r[0].ok && r[0].reason.contains("attestation"), "{r:?}");
3204
    a.tag_create("v3", &[h2], "").unwrap();
3205
    let r = a.push("origin", false).unwrap();
3206
    origin.refresh().unwrap();
3207
    assert!(r.iter().any(|x| x.name == "tags/v3" && x.ok), "{r:?}");
3208
    assert!(a.gc(true).is_ok());
3209
    assert_eq!(a.tags().unwrap().len(), 3, "tags survive gc");
3210
3211
    // After a rotation the policy names only the new key, yet a fresh clone
3212
    // still takes the tags the old key made before it; the old key makes
3213
    // nothing new.
3214
    let rot = a.rotate_identity().unwrap();
3215
    let r = a.push("origin", false).unwrap();
3216
    origin.refresh().unwrap();
3217
    assert!(r.iter().all(|x| x.ok), "{r:?}");
3218
    let c = Repo::clone(&url, &root.join("c"))
3219
        .unwrap()
3220
        .with_home(root.join("home-c"));
3221
    assert_eq!(c.tag_heads("v3").unwrap(), Some(vec![h2]));
3222
    let (_, sp) = c.current_policy().unwrap().unwrap();
3223
    assert!(!sp.policy.authorizes(&key_a, "tags/v9"));
3224
    let made = c.identity(&rot.new).unwrap().created;
3225
    assert!(c.predecessor_authorized(&sp.policy, &key_a, "tags/v9", made - 1));
3226
    assert!(!c.predecessor_authorized(&sp.policy, &key_a, "tags/v9", made));
3227
    assert!(!c.predecessor_authorized(&sp.policy, &rot.new, "tags/v9", 0));
3228
}
3229
3230
#[test]
3231
fn multiple_workspaces_share_a_repository() {
3232
    hermetic();
3233
    let dir = tempfile::tempdir().unwrap();
3234
    let root = dir.path();
3235
    let main_dir = root.join("main");
3236
    let repo = Repo::init(&main_dir).unwrap().with_home(root.join("home"));
3237
    write(&main_dir, "a.txt", b"a\n");
3238
    let h1 = repo.commit("a", &[]).unwrap();
3239
    assert_eq!(repo.workspaces().unwrap().len(), 1);
3240
3241
    // A second workspace elsewhere, checked out on the bookmark.
3242
    let ws_dir = root.join("ws2");
3243
    let ws = repo.workspace_add(&ws_dir, None).unwrap();
3244
    assert!(ws_dir.join(".oxy").is_file());
3245
    assert_eq!(fs::read(ws_dir.join("a.txt")).unwrap(), b"a\n");
3246
    assert_ne!(ws.workspace(), repo.workspace());
3247
    let list = repo.workspaces().unwrap();
3248
    assert_eq!(list.len(), 2);
3249
    assert!(list
3250
        .iter()
3251
        .any(|w| w.id == ws.workspace() && w.path == ws_dir.canonicalize().unwrap() && !w.current));
3252
    assert!(!ws.snapshot("status").unwrap().changed);
3253
3254
    // Work in the second workspace: its own working copy, shared bookmark.
3255
    write(&ws_dir, "b.txt", b"b\n");
3256
    let s = ws.snapshot("status").unwrap();
3257
    assert_eq!(s.statuses.len(), 1);
3258
    assert!(
3259
        !repo.snapshot("status").unwrap().changed,
3260
        "the first workspace is untouched"
3261
    );
3262
    let h2 = ws.commit("b from ws2", &[]).unwrap();
3263
    repo.refresh().unwrap();
3264
    let mut heads = repo.bookmark_heads().unwrap();
3265
    heads.sort();
3266
    let mut want = vec![h1, h2];
3267
    want.sort();
3268
    assert_eq!(heads, want, "both workspaces see the bookmark move");
3269
    assert!(!main_dir.join("b.txt").exists());
3270
    repo.checkout(&repo.bookmark_heads().unwrap(), false, "co")
3271
        .unwrap();
3272
    assert!(main_dir.join("b.txt").exists());
3273
3274
    // Reopening from inside the second workspace finds the shared repository.
3275
    let reopened = Repo::open(&ws_dir).unwrap();
3276
    assert_eq!(reopened.workspace(), ws.workspace());
3277
    assert_eq!(reopened.id().unwrap(), repo.id().unwrap());
3278
    assert_eq!(reopened.quick_status().unwrap().heads, 2);
3279
3280
    // Workspaces cannot nest; forget drops one from the view but keeps files.
3281
    assert!(repo.workspace_add(&main_dir.join("inner"), None).is_err());
3282
    assert!(repo.workspace_forget(&repo.workspace()).is_err());
3283
    repo.workspace_forget(&ws.workspace()).unwrap();
3284
    assert_eq!(repo.workspaces().unwrap().len(), 1);
3285
    assert!(ws_dir.join("b.txt").exists());
3286
    assert!(
3287
        ws.snapshot("status").is_err(),
3288
        "a forgotten workspace is no longer in the view"
3289
    );
3290
3291
    // The working-copy lock: re-entrant in a thread; a lock whose process
3292
    // is gone is taken over, and a live process's is not, however old.
3293
    let lock = repo.lock_snapshot().unwrap();
3294
    let again = repo.lock_working_copy().unwrap();
3295
    drop(again);
3296
    drop(lock);
3297
    let lock_path = main_dir
3298
        .join(".oxy/workspaces")
3299
        .join(repo.workspace().to_hex())
3300
        .join("lock");
3301
    let old = std::time::SystemTime::now() - std::time::Duration::from_secs(120);
3302
    let age = |p: &Path| fs::File::open(p).unwrap().set_modified(old).unwrap();
3303
    fs::write(&lock_path, std::process::id().to_string()).unwrap();
3304
    age(&lock_path);
3305
    assert!(
3306
        !super::workspace::lock_is_stale(&lock_path),
3307
        "a live process keeps its lock"
3308
    );
3309
    fs::write(&lock_path, "4294967295").unwrap();
3310
    age(&lock_path);
3311
    assert!(repo.lock_snapshot().is_ok(), "stale lock taken over");
3312
}
3313
3314
#[test]
3315
fn attributes_binary_eol_nocompress_lockable() {
3316
    hermetic();
3317
    let dir = tempfile::tempdir().unwrap();
3318
    let root = dir.path();
3319
    let repo = Repo::init(root).unwrap().with_home(root.join("home"));
3320
    write(
3321
        root,
3322
        ".oxyattributes",
3323
        b"*.dat binary nocompress\n*.txt eol=crlf\nassets/** lockable\n",
3324
    );
3325
    write(root, "plain.dat", b"no nul bytes here\n");
3326
    write(root, "notes.txt", b"one\r\ntwo\r\n");
3327
    write(root, "assets/model.bin", b"\0model");
3328
    let h = repo.commit("attrs", &[]).unwrap();
3329
    let snap = repo.load_state(&[h]).unwrap().materialize();
3330
    assert!(
3331
        snap.files["plain.dat"].mode.opaque,
3332
        "binary attribute forces opaque without NUL bytes"
3333
    );
3334
    assert!(
3335
        matches!(&snap.files["notes.txt"].content, FileContent::Text { bytes, .. } if bytes == b"one\ntwo\n"),
3336
        "stored with LF"
3337
    );
3338
    assert!(
3339
        !repo.snapshot("status").unwrap().changed,
3340
        "CRLF on disk equals LF in the state"
3341
    );
3342
    // nocompress chunks pack raw.
3343
    let r = repo.gc(true).unwrap();
3344
    assert!(r.packed.objects > 0);
3345
    // Checkout writes CRLF for eol=crlf and makes lockable files read-only.
3346
    fs::remove_file(root.join("notes.txt")).unwrap();
3347
    repo.checkout(&[h], true, "co").unwrap();
3348
    assert_eq!(fs::read(root.join("notes.txt")).unwrap(), b"one\r\ntwo\r\n");
3349
    assert!(fs::metadata(root.join("assets/model.bin"))
3350
        .unwrap()
3351
        .permissions()
3352
        .readonly());
3353
    assert!(repo.lock_path("plain.dat").is_err(), "not lockable");
3354
    repo.lock_path("assets/model.bin").unwrap();
3355
    assert!(!fs::metadata(root.join("assets/model.bin"))
3356
        .unwrap()
3357
        .permissions()
3358
        .readonly());
3359
    assert!(repo.is_locked("assets/model.bin"));
3360
    write(root, "assets/model.bin", b"\0model2");
3361
    repo.commit("edit model", &[]).unwrap();
3362
    repo.unlock_path("assets/model.bin").unwrap();
3363
    assert!(fs::metadata(root.join("assets/model.bin"))
3364
        .unwrap()
3365
        .permissions()
3366
        .readonly());
3367
    // A later checkout can still overwrite a read-only lockable file.
3368
    repo.checkout(&[h], true, "co").unwrap();
3369
    assert_eq!(fs::read(root.join("assets/model.bin")).unwrap(), b"\0model");
3370
}
3371
3372
#[cfg(unix)]
3373
#[test]
3374
fn hooks_can_veto_observe_and_add_dependencies() {
3375
    use std::os::unix::fs::PermissionsExt;
3376
    hermetic();
3377
    let dir = tempfile::tempdir().unwrap();
3378
    let root = dir.path();
3379
    let mut repo = Repo::init(root).unwrap().with_home(root.join("home"));
3380
    let hooks = root.join(".oxy/hooks");
3381
    fs::create_dir_all(&hooks).unwrap();
3382
    let hook = |name: &str, body: &str| {
3383
        let p = hooks.join(name);
3384
        fs::write(&p, format!("#!/bin/sh\n{body}\n")).unwrap();
3385
        fs::set_permissions(&p, fs::Permissions::from_mode(0o755)).unwrap();
3386
    };
3387
    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");
3388
    hook("post-commit", "cat > \"$OXY_ROOT/.last-post-commit\"");
3389
    hook("post-checkout", "cat > \"$OXY_ROOT/.last-post-checkout\"");
3390
    hook("pre-push", "echo pushing blocked >&2; exit 3");
3391
    write(root, ".oxyignore", b".last-*\n");
3392
    write(root, "a.txt", b"a\n");
3393
    let err = repo.commit("WIP: nope", &[]).unwrap_err().to_string();
3394
    assert!(err.contains("pre-commit refused: no WIP commits"), "{err}");
3395
    let h1 = repo.commit("first", &[]).unwrap();
3396
    let pre = fs::read_to_string(root.join(".last-pre-commit")).unwrap();
3397
    assert!(
3398
        pre.contains("\"event\":\"pre-commit\"")
3399
            && pre.contains("\"path\":\"a.txt\"")
3400
            && pre.contains("\"message\":\"first\""),
3401
        "{pre}"
3402
    );
3403
    let post = fs::read_to_string(root.join(".last-post-commit")).unwrap();
3404
    assert!(post.contains(&h1.to_hex()), "{post}");
3405
    repo.checkout(&[h1], false, "co").unwrap();
3406
    assert!(fs::read_to_string(root.join(".last-post-checkout"))
3407
        .unwrap()
3408
        .contains("post-checkout"));
3409
    repo.config.set("remote.origin.url", "/nowhere").unwrap();
3410
    repo.save_config().unwrap();
3411
    let err = repo.push("origin", false).unwrap_err().to_string();
3412
    assert!(err.contains("pre-push refused: pushing blocked"), "{err}");
3413
3414
    // semantic-deps: only when enabled; adds an explicit dependency.
3415
    write(root, "b.txt", b"b\n");
3416
    hook(
3417
        "semantic-deps",
3418
        &format!(
3419
            "cat > \"$OXY_ROOT/.last-semantic\"; echo '{{\"deps\": [\"{}\"]}}'",
3420
            h1.to_hex()
3421
        ),
3422
    );
3423
    let h2 = repo.commit("b without hook", &[]).unwrap();
3424
    assert!(
3425
        repo.store().get_change(&h2).unwrap().deps.is_empty(),
3426
        "hook disabled by default"
3427
    );
3428
    repo.config.set("hooks.semantic-deps", "true").unwrap();
3429
    repo.save_config().unwrap();
3430
    write(root, "c.txt", b"c\n");
3431
    let h3 = repo.commit("c with hook", &[]).unwrap();
3432
    assert_eq!(repo.store().get_change(&h3).unwrap().deps, vec![h1]);
3433
    let sem = fs::read_to_string(root.join(".last-semantic")).unwrap();
3434
    assert!(
3435
        sem.contains("\"touched_paths\":[\"c.txt\"]") && sem.contains("candidate_deps"),
3436
        "{sem}"
3437
    );
3438
    assert_eq!(json_str("a\"b\\c\n"), "\"a\\\"b\\\\c\\n\"");
3439
}
3440
3441
#[test]
3442
fn amend_into_older_change_and_split() {
3443
    hermetic();
3444
    let dir = tempfile::tempdir().unwrap();
3445
    let root = dir.path();
3446
    let mut repo = Repo::init(root).unwrap().with_home(root.join("home"));
3447
    repo.create_identity("Ada", "a@b", IdentityScope::User)
3448
        .unwrap();
3449
    repo.set_user_config("core.sign", "change").unwrap();
3450
    write(root, "a.txt", b"one\ntwo\n");
3451
    let h0 = repo.commit("base", &[]).unwrap();
3452
    write(root, "a.txt", b"one\nTWO\n");
3453
    let h1 = repo.commit("edit two", &[]).unwrap();
3454
    write(root, "a.txt", b"one\nTWO\nthree\n");
3455
    let h2 = repo.commit("add three", &[]).unwrap();
3456
    let id1 = repo.store().get_change(&h1).unwrap().change_id;
3457
3458
    // Fixing the line h1 introduced folds into h1; h2 is rewritten on top.
3459
    write(root, "a.txt", b"one\nTWO!\nthree\n");
3460
    let h1b = repo.amend_into(&h1, None).unwrap();
3461
    assert_ne!(h1b, h1);
3462
    let c1b = repo.store().get_change(&h1b).unwrap();
3463
    assert_eq!(c1b.change_id, id1);
3464
    assert_eq!(c1b.deps, vec![h0]);
3465
    assert!(matches!(
3466
        repo.verify_change(&h1b).unwrap(),
3467
        SignatureStatus::Valid { .. }
3468
    ));
3469
    let heads = repo.bookmark_heads().unwrap();
3470
    assert_eq!(heads.len(), 1);
3471
    let top = repo.store().get_change(&heads[0]).unwrap();
3472
    assert_eq!(top.message, "add three");
3473
    assert_eq!(
3474
        top.deps.iter().copied().collect::<BTreeSet<_>>(),
3475
        [h0, h1b].into_iter().collect(),
3476
        "depends on the file's creator and the rewritten line"
3477
    );
3478
    let snap = repo.load_state(&heads).unwrap().materialize();
3479
    assert!(
3480
        matches!(&snap.files["a.txt"].content, FileContent::Text { bytes, .. } if bytes == b"one\nTWO!\nthree\n")
3481
    );
3482
    assert!(
3483
        !repo.snapshot("status").unwrap().changed,
3484
        "the working copy is clean after folding"
3485
    );
3486
    // Only h1b's own state shows the fix without "three".
3487
    let only = repo.load_state(&[h1b]).unwrap().materialize();
3488
    assert!(
3489
        matches!(&only.files["a.txt"].content, FileContent::Text { bytes, .. } if bytes == b"one\nTWO!\n")
3490
    );
3491
    assert_eq!(repo.log().unwrap().len(), 4);
3492
3493
    // An edit to a line introduced by h2 cannot fold into h1.
3494
    write(root, "a.txt", b"one\nTWO!\nthree!\n");
3495
    let err = repo.amend_into(&h1b, None).unwrap_err().to_string();
3496
    assert!(err.contains("introduced after"), "{err}");
3497
    assert!(
3498
        repo.snapshot("status").unwrap().statuses.len() == 1,
3499
        "nothing was changed by the refusal"
3500
    );
3501
    write(root, "a.txt", b"one\nTWO!\nthree\n");
3502
3503
    // Split the head that touches two files.
3504
    write(root, "b.txt", b"b\n");
3505
    write(root, "c.txt", b"c\n");
3506
    let h3 = repo.commit("b and c", &[]).unwrap();
3507
    let id3 = repo.store().get_change(&h3).unwrap().change_id;
3508
    let (p1, p2) = repo.split(&h3, &["b.txt".into()]).unwrap();
3509
    let c_1 = repo.store().get_change(&p1).unwrap();
3510
    let c_2 = repo.store().get_change(&p2).unwrap();
3511
    assert!(c_1.message.contains("part 1: b.txt"));
3512
    assert_eq!(c_2.change_id, id3);
3513
    let heads: BTreeSet<_> = repo.bookmark_heads().unwrap().into_iter().collect();
3514
    assert!(
3515
        heads.contains(&p1) && heads.contains(&p2),
3516
        "independent parts are both heads"
3517
    );
3518
    let snap = repo
3519
        .load_state(&repo.bookmark_heads().unwrap())
3520
        .unwrap()
3521
        .materialize();
3522
    assert!(snap.files.contains_key("b.txt") && snap.files.contains_key("c.txt"));
3523
    let only1 = repo.load_state(&[p1]).unwrap().materialize();
3524
    assert!(only1.files.contains_key("b.txt") && !only1.files.contains_key("c.txt"));
3525
    assert!(!repo.snapshot("status").unwrap().changed);
3526
    assert!(repo.split(&p2, &["nope.txt".into()]).is_err());
3527
    let _ = h2;
3528
}
3529
3530
#[test]
3531
fn identity_lifecycle() {
3532
    hermetic();
3533
    let dir = tempfile::tempdir().unwrap();
3534
    let root = dir.path();
3535
    let origin = Repo::init(&root.join("origin")).unwrap();
3536
    let url = root.join("origin").to_string_lossy().to_string();
3537
    let mut a = Repo::clone(&url, &root.join("a"))
3538
        .unwrap()
3539
        .with_home(root.join("home-a"));
3540
    a.set_user_config("core.sign", "change").unwrap();
3541
    let (key_a, _) = a
3542
        .create_identity("Ada", "[email protected]", IdentityScope::User)
3543
        .unwrap();
3544
    write(&root.join("a"), "a.txt", b"a\n");
3545
    let h1 = a.commit("one", &[]).unwrap();
3546
    assert!(a.policy_init().unwrap().applied);
3547
    assert!(a.push("origin", false).unwrap().iter().all(|r| r.ok));
3548
    origin.refresh().unwrap();
3549
3550
    // Expiry: an identity that had expired when the change was made does not authenticate it.
3551
    let mut e = Repo::init(&root.join("e"))
3552
        .unwrap()
3553
        .with_home(root.join("home-e"));
3554
    e.set_user_config("core.sign", "change").unwrap();
3555
    e.create_identity_with(
3556
        "Eve",
3557
        "[email protected]",
3558
        IdentityScope::User,
3559
        Some(Hlc::now().wall_ms - 1),
3560
    )
3561
    .unwrap();
3562
    write(&root.join("e"), "e.txt", b"e\n");
3563
    let he = e.commit("late", &[]).unwrap();
3564
    assert!(
3565
        matches!(e.verify_change(&he).unwrap(), SignatureStatus::Invalid(m) if m.contains("expired"))
3566
    );
3567
    // Renewal re-issues the identity (same keys, new KeyId) with a later expiry.
3568
    let r = e
3569
        .renew_identity(Some(Hlc::now().wall_ms + 86_400_000))
3570
        .unwrap();
3571
    assert_eq!(e.identity(&r.new).unwrap().previous, Some(r.old));
3572
    write(&root.join("e"), "e.txt", b"e2\n");
3573
    let he2 = e.commit("in time", &[]).unwrap();
3574
    assert!(
3575
        matches!(e.verify_change(&he2).unwrap(), SignatureStatus::Valid { key, .. } if key == r.new)
3576
    );
3577
3578
    // Rotation: a fresh key; the old change still verifies; the policy follows.
3579
    let r = a.rotate_identity().unwrap();
3580
    assert_eq!(r.old, key_a);
3581
    assert_eq!(a.config.author_key, Some(r.new));
3582
    assert_eq!(a.identity(&r.new).unwrap().previous, Some(key_a));
3583
    assert!(r.policy.as_ref().unwrap().applied);
3584
    let (_, sp) = a.current_policy().unwrap().unwrap();
3585
    assert_eq!(
3586
        (sp.policy.serial, sp.policy.roots.clone()),
3587
        (2, vec![r.new])
3588
    );
3589
    assert!(
3590
        !sp.policy.revoked.contains(&key_a) && sp.policy.authorizes(&r.new, "main"),
3591
        "superseded, not revoked"
3592
    );
3593
    assert!(sp.policy.succeeds(&r.new, &key_a) && !sp.policy.succeeds(&key_a, &r.new));
3594
    assert!(
3595
        matches!(a.verify_change(&h1).unwrap(), SignatureStatus::Valid { key, revoked: false, .. } if key == key_a)
3596
    );
3597
    write(&root.join("a"), "a.txt", b"a2\n");
3598
    let h2 = a.commit("two", &[]).unwrap();
3599
    assert!(
3600
        matches!(a.verify_change(&h2).unwrap(), SignatureStatus::Valid { key, revoked: false, .. } if key == r.new)
3601
    );
3602
    // Origin accepts the rotated policy (signed by the old root) and the new key's change.
3603
    let res = a.push("origin", false).unwrap();
3604
    origin.refresh().unwrap();
3605
    assert!(res.iter().all(|x| x.ok), "{res:?}");
3606
    assert_eq!(origin.current_policy().unwrap().unwrap().1.policy.serial, 2);
3607
    let key_a = r.new;
3608
3609
    // Delegation: Bob may sign on Ada's behalf. Delegates live in the
3610
    // identity object, so Ada's KeyId changes while her keys stay the same.
3611
    let mut b = Repo::clone(&url, &root.join("b"))
3612
        .unwrap()
3613
        .with_home(root.join("home-b"));
3614
    let (key_b, id_b) = b
3615
        .create_identity("Bob", "[email protected]", IdentityScope::User)
3616
        .unwrap();
3617
    let r = a.delegate_add(id_b.clone(), Scope::ALL, None).unwrap();
3618
    assert_eq!(r.old, key_a);
3619
    let key_a2 = r.new;
3620
    assert_eq!(
3621
        a.identity(&key_a2).unwrap().delegates,
3622
        vec![Delegate::full(key_b)]
3623
    );
3624
    assert_eq!(
3625
        a.identity(&key_a2).unwrap().ed25519_pk,
3626
        a.identity(&key_a).unwrap().ed25519_pk
3627
    );
3628
    assert!(
3629
        a.delegate_add(id_b.clone(), Scope::ALL, None).is_err(),
3630
        "already a delegate"
3631
    );
3632
    assert!(a.push("origin", false).unwrap().iter().all(|x| x.ok));
3633
    origin.refresh().unwrap();
3634
    write(&root.join("a"), "a.txt", b"a3\n");
3635
    let h3 = a.commit("three", &[]).unwrap();
3636
    assert!(
3637
        matches!(a.verify_change(&h3).unwrap(), SignatureStatus::Valid { key, .. } if key == key_a2),
3638
        "the same secret signs under the new KeyId"
3639
    );
3640
    // A change authored by Ada but signed only by Bob verifies through the delegation.
3641
    a.set_user_config("core.sign", "seal").unwrap();
3642
    write(&root.join("a"), "a.txt", b"a4\n");
3643
    let h4 = a.commit("four", &[]).unwrap();
3644
    assert_eq!(a.verify_change(&h4).unwrap(), SignatureStatus::Unsigned);
3645
    let (_, sk_b) = b.secret_key().unwrap().unwrap();
3646
    a.store()
3647
        .put_signature(&h4, &sk_b.sign(Domain::Change, &key_b, &h4))
3648
        .unwrap();
3649
    assert!(
3650
        matches!(a.verify_change(&h4).unwrap(), SignatureStatus::Valid { key, .. } if key == key_b)
3651
    );
3652
    a.set_user_config("core.sign", "change").unwrap();
3653
    // Withdrawing the delegation re-issues the identity again.
3654
    let r = a.delegate_remove(&key_b).unwrap();
3655
    assert!(a.identity(&r.new).unwrap().delegates.is_empty());
3656
    assert!(a.delegate_remove(&key_b).is_err());
3657
    let key_a3 = r.new;
3658
    let res = a.push("origin", false).unwrap();
3659
    origin.refresh().unwrap();
3660
    assert!(res.iter().all(|x| x.ok), "{res:?}");
3661
3662
    // Multi-signer policy: Bob becomes a root and the threshold rises to 2,
3663
    // both applied under the old threshold of 1. A grant then needs Bob too.
3664
    assert!(a.policy_root_add(id_b.clone()).unwrap().applied);
3665
    assert!(a.policy_root_add(id_b.clone()).is_err());
3666
    assert!(a.policy_set_threshold(3).is_err());
3667
    assert!(a.policy_set_threshold(2).unwrap().applied);
3668
    assert!(a.push("origin", false).unwrap().iter().all(|x| x.ok));
3669
    origin.refresh().unwrap();
3670
    b.pull("origin").unwrap();
3671
    assert_eq!(
3672
        b.current_policy().unwrap().unwrap().1.policy.root_threshold,
3673
        2
3674
    );
3675
    let mut c = Repo::init(&root.join("c"))
3676
        .unwrap()
3677
        .with_home(root.join("home-c"));
3678
    let (key_c, id_c) = c
3679
        .create_identity("Cy", "[email protected]", IdentityScope::User)
3680
        .unwrap();
3681
    let serial_before = a.current_policy().unwrap().unwrap().1.policy.serial;
3682
    let proposal = a.policy_grant(id_c, None).unwrap();
3683
    assert!(!proposal.applied && proposal.sigs.len() == 1);
3684
    assert_eq!(proposal.policy.serial, serial_before + 1);
3685
    assert_eq!(
3686
        a.current_policy().unwrap().unwrap().1.policy.serial,
3687
        serial_before,
3688
        "a proposal changes nothing yet"
3689
    );
3690
    // Bob signs the proposal, handed over as a file, and it applies for him.
3691
    let bytes = proposal.signed().encode();
3692
    let signed = b
3693
        .policy_sign(SignedPolicy::decode(&bytes).unwrap())
3694
        .unwrap();
3695
    assert!(signed.applied && signed.sigs.len() == 2);
3696
    assert!(b
3697
        .current_policy()
3698
        .unwrap()
3699
        .unwrap()
3700
        .1
3701
        .policy
3702
        .authorizes(&key_c, "main"));
3703
    assert!(
3704
        b.policy_sign(signed.signed()).is_err(),
3705
        "a stale proposal is refused"
3706
    );
3707
    // Bob publishes it and Ada picks it up.
3708
    assert!(b
3709
        .push("origin", false)
3710
        .unwrap()
3711
        .iter()
3712
        .any(|x| x.name == "policy" && x.ok));
3713
    origin.refresh().unwrap();
3714
    a.pull("origin").unwrap();
3715
    assert_eq!(
3716
        a.current_policy().unwrap().unwrap().1.policy.serial,
3717
        serial_before + 1
3718
    );
3719
    // A root cannot revoke itself; revoking Cy needs both roots but is recorded locally at once.
3720
    assert!(a.policy_revoke(&key_a3).is_err());
3721
    let u = a
3722
        .revoke_identity(&key_c, "left the project")
3723
        .unwrap()
3724
        .unwrap();
3725
    assert!(!u.applied);
3726
    assert!(a.is_revoked(&key_c).unwrap());
3727
    assert!(!b.is_revoked(&key_c).unwrap());
3728
    let u = b.policy_sign(u.signed()).unwrap();
3729
    assert!(u.applied && u.policy.is_revoked(&key_c));
3730
    assert!(b.is_revoked(&key_c).unwrap());
3731
    // Bob can revoke Ada's root key, leaving himself as the only root (threshold 2 would be unmeetable).
3732
    assert!(
3733
        b.policy_revoke(&key_a3).is_err(),
3734
        "would leave one root for a threshold of 2"
3735
    );
3736
    // Revoking one's own key without a policy root works locally: a plain marker plus attestation.
3737
    let key_c_own = c.config.author_key.unwrap();
3738
    assert!(c
3739
        .revoke_identity(&key_c_own, "lost laptop")
3740
        .unwrap()
3741
        .is_none());
3742
    assert!(c.is_revoked(&key_c_own).unwrap());
3743
    assert_eq!(key_c_own, key_c);
3744
}
3745
3746
#[test]
3747
fn renames_are_detected_and_tracked_as_moves() {
3748
    hermetic();
3749
    let dir = tempfile::tempdir().unwrap();
3750
    let root = dir.path();
3751
    let repo = Repo::init(root).unwrap().with_home(root.join("home"));
3752
    write(
3753
        root,
3754
        "src/old.rs",
3755
        b"fn a() {}\nfn b() {}\nfn c() {}\nfn d() {}\n",
3756
    );
3757
    write(root, "img.bin", b"\x89PNG\0\0\x01\x02");
3758
    write(root, "tiny.txt", b"x\n");
3759
    let h1 = repo.commit("base", &[]).unwrap();
3760
    let node_old = repo.load_state(&[h1]).unwrap().materialize().files["src/old.rs"].node;
3761
    let node_img = repo.load_state(&[h1]).unwrap().materialize().files["img.bin"].node;
3762
3763
    // Rename with a small edit, a binary moved unchanged, and a rewrite
3764
    // that shares nothing with the removed file.
3765
    fs::remove_file(root.join("src/old.rs")).unwrap();
3766
    write(
3767
        root,
3768
        "lib/new.rs",
3769
        b"fn a() {}\nfn b() {}\nfn c() {}\nfn e() {}\n",
3770
    );
3771
    fs::remove_file(root.join("img.bin")).unwrap();
3772
    write(root, "assets/img.bin", b"\x89PNG\0\0\x01\x02");
3773
    fs::remove_file(root.join("tiny.txt")).unwrap();
3774
    write(root, "other.txt", b"completely different\n");
3775
    let snap = repo.snapshot("status").unwrap();
3776
    let statuses: Vec<(&str, ChangeStatus)> = snap
3777
        .statuses
3778
        .iter()
3779
        .map(|s| (s.path.as_str(), s.status))
3780
        .collect();
3781
    assert_eq!(
3782
        statuses,
3783
        vec![
3784
            ("assets/img.bin", ChangeStatus::Renamed),
3785
            ("lib/new.rs", ChangeStatus::Renamed),
3786
            ("other.txt", ChangeStatus::Added),
3787
            ("src", ChangeStatus::Removed),
3788
            ("tiny.txt", ChangeStatus::Removed)
3789
        ]
3790
    );
3791
    let h2 = repo.commit("move things", &[]).unwrap();
3792
    let c = repo.store().get_change(&h2).unwrap();
3793
    let moves: Vec<_> = c
3794
        .tree_ops
3795
        .iter()
3796
        .filter(|op| matches!(op, TreeOp::Move { .. }))
3797
        .collect();
3798
    assert_eq!(moves.len(), 2, "{:?}", c.tree_ops);
3799
    assert!(c.tree_ops.iter().any(
3800
        |op| matches!(op, TreeOp::Move { node, name, .. } if *node == node_old && name == "new.rs")
3801
    ));
3802
    assert!(c.tree_ops.iter().any(
3803
        |op| matches!(op, TreeOp::Move { node, name, .. } if *node == node_img && name == "img.bin")
3804
    ));
3805
    let snap = repo.load_state(&[h2]).unwrap().materialize();
3806
    assert_eq!(
3807
        snap.files["lib/new.rs"].node, node_old,
3808
        "the node survives the rename"
3809
    );
3810
    assert!(
3811
        matches!(&snap.files["lib/new.rs"].content, FileContent::Text { bytes, .. } if bytes == b"fn a() {}\nfn b() {}\nfn c() {}\nfn e() {}\n")
3812
    );
3813
    assert!(!snap.files.contains_key("src/old.rs") && !snap.files.contains_key("src"));
3814
    assert!(render_change(
3815
        &c,
3816
        &repo.load_state(&[h1]).unwrap(),
3817
        &repo.load_state(&[h1]).unwrap().materialize()
3818
    )
3819
    .contains("R "));
3820
    // A fresh checkout reproduces the tree.
3821
    let other = tempfile::tempdir().unwrap();
3822
    let clone = Repo::clone(&root.to_string_lossy(), other.path()).unwrap();
3823
    assert_eq!(
3824
        fs::read(other.path().join("lib/new.rs")).unwrap(),
3825
        b"fn a() {}\nfn b() {}\nfn c() {}\nfn e() {}\n"
3826
    );
3827
    assert!(!other.path().join("src").exists());
3828
    assert!(!clone.snapshot("status").unwrap().changed);
3829
    // Similarity is line based, byte weighted.
3830
    assert_eq!(similarity(b"a\nb\n", b"a\nb\n"), 100);
3831
    assert_eq!(similarity(b"a\nb\nc\nd\n", b"a\nb\nx\ny\n"), 50);
3832
    assert_eq!(similarity(b"hello\n", b"world\n"), 0);
3833
    assert_eq!(similarity(b"", b"x\n"), 0);
3834
}
3835
3836
#[test]
3837
fn git_fetch_and_push_round_trip() {
3838
    hermetic();
3839
    if std::process::Command::new("git")
3840
        .arg("--version")
3841
        .output()
3842
        .is_err()
3843
    {
3844
        eprintln!("git not installed; skipping");
3845
        return;
3846
    }
3847
    let dir = tempfile::tempdir().unwrap();
3848
    let root = dir.path();
3849
    let git_in = |d: &Path, args: &[&str]| -> String {
3850
        let out = std::process::Command::new("git")
3851
            .arg("-C")
3852
            .arg(d)
3853
            .args([
3854
                "-c",
3855
                "user.name=Grace",
3856
                "-c",
3857
                "[email protected]",
3858
                "-c",
3859
                "commit.gpgsign=false",
3860
            ])
3861
            .args(args)
3862
            .output()
3863
            .unwrap();
3864
        assert!(
3865
            out.status.success(),
3866
            "git {args:?}: {}",
3867
            String::from_utf8_lossy(&out.stderr)
3868
        );
3869
        String::from_utf8_lossy(&out.stdout).trim().to_string()
3870
    };
3871
    // A bare "remote" and a work tree that pushes to it.
3872
    let remote = root.join("remote.git");
3873
    fs::create_dir_all(&remote).unwrap();
3874
    git_in(&remote, &["init", "-q", "--bare", "-b", "main"]);
3875
    let work = root.join("work");
3876
    git_in(
3877
        root,
3878
        &[
3879
            "clone",
3880
            "-q",
3881
            remote.to_str().unwrap(),
3882
            work.to_str().unwrap(),
3883
        ],
3884
    );
3885
    git_in(&work, &["checkout", "-q", "-b", "main"]);
3886
    write(&work, "README.md", b"# Project\n");
3887
    write(&work, "src/lib.rs", b"pub fn a() {}\n");
3888
    git_in(&work, &["add", "."]);
3889
    git_in(&work, &["commit", "-q", "-m", "initial"]);
3890
    write(&work, "src/lib.rs", b"pub fn a() {}\npub fn b() {}\n");
3891
    git_in(&work, &["commit", "-q", "-am", "second"]);
3892
    git_in(&work, &["push", "-q", "origin", "main"]);
3893
    let tip1 = git_in(&work, &["rev-parse", "HEAD"]);
3894
3895
    // Fetch into a fresh oxy repository.
3896
    let o = root.join("oxy");
3897
    let mut repo = Repo::init(&o).unwrap().with_home(root.join("home"));
3898
    repo.create_identity("Ada", "[email protected]", IdentityScope::User)
3899
        .unwrap();
3900
    let url = remote.to_string_lossy().to_string();
3901
    let r = repo.git_fetch(&url, "main").unwrap();
3902
    assert_eq!((r.commits, r.heads), (2, 1));
3903
    assert_eq!(
3904
        fs::read(o.join("src/lib.rs")).unwrap(),
3905
        b"pub fn a() {}\npub fn b() {}\n"
3906
    );
3907
    assert!(!repo.snapshot("status").unwrap().changed);
3908
    assert_eq!(
3909
        repo.git_fetch(&url, "main").unwrap().commits,
3910
        0,
3911
        "nothing new"
3912
    );
3913
3914
    // An oxy change, pushed back: one commit on top of the Git tip.
3915
    write(
3916
        &o,
3917
        "src/lib.rs",
3918
        b"pub fn a() {}\npub fn b() {}\npub fn c() {}\n",
3919
    );
3920
    write(&o, "NOTES.md", b"from oxy\n");
3921
    let h_oxy = repo.commit("add c and notes", &[]).unwrap();
3922
    let r = repo.git_push(&url, "main").unwrap();
3923
    assert_eq!(r.exported, 1, "{r:?}");
3924
    git_in(&work, &["pull", "-q", "--ff-only", "origin", "main"]);
3925
    assert_eq!(
3926
        git_in(&work, &["log", "--format=%s", "main"]),
3927
        "add c and notes\nsecond\ninitial"
3928
    );
3929
    assert_eq!(git_in(&work, &["rev-parse", "HEAD~1"]), tip1);
3930
    assert_eq!(fs::read(work.join("NOTES.md")).unwrap(), b"from oxy\n");
3931
    assert_eq!(git_in(&work, &["log", "-1", "--format=%an", "main"]), "Ada");
3932
    assert!(git_in(&work, &["log", "-1", "--format=%B", "main"])
3933
        .contains(&format!("Oxy-Hash: {}", h_oxy.to_hex())));
3934
    assert_eq!(
3935
        repo.git_push(&url, "main").unwrap().exported,
3936
        0,
3937
        "already pushed"
3938
    );
3939
3940
    // Git moves on; pushing without fetching is refused, fetching brings
3941
    // the commit in and the working copy follows.
3942
    write(&work, "README.md", b"# Project\n\nMore.\n");
3943
    git_in(&work, &["commit", "-q", "-am", "readme from git"]);
3944
    git_in(&work, &["push", "-q", "origin", "main"]);
3945
    let tip2 = git_in(&work, &["rev-parse", "HEAD"]);
3946
    assert!(repo
3947
        .git_push(&url, "main")
3948
        .unwrap_err()
3949
        .to_string()
3950
        .contains("fetch"));
3951
    let r = repo.git_fetch(&url, "main").unwrap();
3952
    assert_eq!(
3953
        (r.commits, r.heads),
3954
        (1, 2),
3955
        "the Git change and the oxy change commute"
3956
    );
3957
    assert_eq!(
3958
        fs::read(o.join("README.md")).unwrap(),
3959
        b"# Project\n\nMore.\n"
3960
    );
3961
    assert_eq!(fs::read(o.join("NOTES.md")).unwrap(), b"from oxy\n");
3962
    assert!(!repo.snapshot("status").unwrap().changed);
3963
    // Another oxy change pushes on top of Git's newest commit.
3964
    write(&o, "NOTES.md", b"from oxy\nagain\n");
3965
    repo.commit("notes again", &[]).unwrap();
3966
    assert_eq!(repo.git_push(&url, "main").unwrap().exported, 1);
3967
    git_in(&work, &["pull", "-q", "--ff-only", "origin", "main"]);
3968
    assert_eq!(git_in(&work, &["rev-parse", "HEAD~1"]), tip2);
3969
    assert_eq!(
3970
        fs::read(work.join("NOTES.md")).unwrap(),
3971
        b"from oxy\nagain\n"
3972
    );
3973
    assert_eq!(
3974
        git_in(&work, &["log", "--format=%s", "main"])
3975
            .lines()
3976
            .count(),
3977
        5
3978
    );
3979
}
3980
3981
/// Benchmark, not a gate: `cargo test --release -p oxy-core --lib bench_one_gibibyte -- --ignored --nocapture`.
3982
/// Commits, stores, clones, and reads back a 1 GiB incompressible file.
3983
#[test]
3984
#[ignore]
3985
fn bench_one_gibibyte_file() {
3986
    hermetic();
3987
    // /tmp is often a small tmpfs; `OXY_BENCH_DIR` picks a roomier disk.
3988
    let dir = match std::env::var_os("OXY_BENCH_DIR") {
3989
        Some(d) => tempfile::tempdir_in(d).unwrap(),
3990
        None => tempfile::tempdir().unwrap(),
3991
    };
3992
    let root = dir.path();
3993
    let repo = Repo::init(&root.join("r"))
3994
        .unwrap()
3995
        .with_home(root.join("home"));
3996
    let size = 1usize << 30;
3997
    let mut data = vec![0u8; size];
3998
    let mut x = 0x9e3779b97f4a7c15u64;
3999
    for chunk in data.chunks_mut(8) {
4000
        x ^= x << 13;
4001
        x ^= x >> 7;
4002
        x ^= x << 17;
4003
        let b = x.to_le_bytes();
4004
        chunk.copy_from_slice(&b[..chunk.len()]);
4005
    }
4006
    let t = std::time::Instant::now();
4007
    write(&root.join("r"), "big.bin", &data);
4008
    eprintln!("write 1 GiB to disk: {:.2?}", t.elapsed());
4009
    let t = std::time::Instant::now();
4010
    let h = repo.commit("big", &[]).unwrap();
4011
    eprintln!("commit (chunk + hash + store): {:.2?}", t.elapsed());
4012
    let t = std::time::Instant::now();
4013
    assert!(!repo.snapshot("status").unwrap().changed);
4014
    eprintln!("status on a clean 1 GiB working copy: {:.2?}", t.elapsed());
4015
    let t = std::time::Instant::now();
4016
    let objects = repo.store().list().unwrap().len();
4017
    eprintln!("objects stored: {objects} ({:.2?} to list)", t.elapsed());
4018
    let t = std::time::Instant::now();
4019
    let g = repo.gc(true).unwrap();
4020
    eprintln!("gc (pack): {:.2?} {g:?}", t.elapsed());
4021
    let t = std::time::Instant::now();
4022
    let clone = Repo::clone(&root.join("r").to_string_lossy(), &root.join("c")).unwrap();
4023
    eprintln!("clone (fetch + checkout): {:.2?}", t.elapsed());
4024
    let t = std::time::Instant::now();
4025
    let back = fs::read(root.join("c/big.bin")).unwrap();
4026
    assert_eq!(blake3::hash(&back), blake3::hash(&data));
4027
    eprintln!("read back and verify: {:.2?}", t.elapsed());
4028
    assert_eq!(clone.bookmark_heads().unwrap(), vec![h]);
4029
    let store_bytes: u64 = walkdir_size(&root.join("r/.oxy/objects"));
4030
    eprintln!(
4031
        "store size: {:.1} MiB for 1 GiB of data",
4032
        store_bytes as f64 / (1024.0 * 1024.0)
4033
    );
4034
}
4035
4036
fn walkdir_size(p: &Path) -> u64 {
4037
    let mut total = 0;
4038
    if let Ok(rd) = fs::read_dir(p) {
4039
        for e in rd.flatten() {
4040
            let path = e.path();
4041
            if path.is_dir() {
4042
                total += walkdir_size(&path);
4043
            } else if let Ok(m) = fs::metadata(&path) {
4044
                total += m.len();
4045
            }
4046
        }
4047
    }
4048
    total
4049
}
4050
4051
/// An opaque file whose size and mtime match the manifest is not read on
4052
/// the next snapshot: its blob comes from the manifest's stat cache.
4053
#[cfg(unix)]
4054
#[test]
4055
fn stat_cache_skips_reading_unchanged_opaque_files() {
4056
    use std::os::unix::fs::PermissionsExt;
4057
    hermetic();
4058
    let dir = tempfile::tempdir().unwrap();
4059
    let root = dir.path();
4060
    let repo = Repo::init(root).unwrap().with_home(root.join("home"));
4061
    let mut big = vec![0u8; 300 * 1024];
4062
    for (i, b) in big.iter_mut().enumerate() {
4063
        *b = (i as u32).wrapping_mul(2654435761).to_le_bytes()[1];
4064
    }
4065
    big[0] = 0;
4066
    write(root, "big.bin", &big);
4067
    write(root, "a.txt", b"text\n");
4068
    let h1 = repo.commit("base", &[]).unwrap();
4069
    let (_, _, m) = repo.read_manifest().unwrap().unwrap();
4070
    assert!(
4071
        m.entries["big.bin"].blob.is_some(),
4072
        "opaque files record their blob"
4073
    );
4074
    assert!(m.entries["a.txt"].blob.is_none());
4075
    let blob = m.entries["big.bin"].blob.unwrap();
4076
    assert!(repo.store().has(&blob));
4077
4078
    // Files modified within two seconds of the manifest are racy and still
4079
    // read; age the file so the cache applies, then snapshot to record it.
4080
    let old = std::time::SystemTime::now() - std::time::Duration::from_secs(30);
4081
    fs::File::options()
4082
        .write(true)
4083
        .open(root.join("big.bin"))
4084
        .unwrap()
4085
        .set_modified(old)
4086
        .unwrap();
4087
    assert!(!repo.snapshot("status").unwrap().changed);
4088
    // Now the file cannot be read at all; the snapshot succeeds without it.
4089
    fs::set_permissions(root.join("big.bin"), fs::Permissions::from_mode(0o000)).unwrap();
4090
    let snap = repo.snapshot("status").unwrap();
4091
    assert!(
4092
        !snap.changed && snap.statuses.is_empty(),
4093
        "{:?}",
4094
        snap.statuses
4095
    );
4096
    fs::set_permissions(root.join("big.bin"), fs::Permissions::from_mode(0o644)).unwrap();
4097
    // A real change (new mtime, new content) is seen and committed correctly.
4098
    let mut big2 = big.clone();
4099
    big2[10] ^= 0xff;
4100
    write(root, "big.bin", &big2);
4101
    let snap = repo.snapshot("status").unwrap();
4102
    assert_eq!(
4103
        snap.statuses
4104
            .iter()
4105
            .map(|s| (s.path.as_str(), s.status))
4106
            .collect::<Vec<_>>(),
4107
        vec![("big.bin", ChangeStatus::Modified)]
4108
    );
4109
    let h2 = repo.commit("edit", &[]).unwrap();
4110
    let files = repo.load_state(&[h2]).unwrap().materialize().files;
4111
    assert_eq!(
4112
        files["big.bin"].content,
4113
        FileContent::Opaque {
4114
            blobs: vec![Repo::blob_ref(&big2)]
4115
        }
4116
    );
4117
    // Checkout writes a manifest with blobs too, so the next status is cached.
4118
    repo.checkout(&[h1], false, "checkout").unwrap();
4119
    let (_, _, m) = repo.read_manifest().unwrap().unwrap();
4120
    assert_eq!(m.entries["big.bin"].blob, Some(Repo::blob_ref(&big)));
4121
    assert!(!repo.snapshot("status").unwrap().changed);
4122
}
4123
4124
#[test]
4125
fn status_json_lists_conflicts_with_contributors() {
4126
    hermetic();
4127
    let dir = tempfile::tempdir().unwrap();
4128
    let root = dir.path();
4129
    let repo = Repo::init(root).unwrap().with_home(root.join("home"));
4130
    write(root, "a.txt", b"one\n");
4131
    let h1 = repo.commit("base", &[]).unwrap();
4132
    write(root, "a.txt", b"one\nleft\n");
4133
    let ha = repo.commit("left", &[]).unwrap();
4134
    repo.checkout(&[h1], true, "checkout").unwrap();
4135
    write(root, "a.txt", b"one\nright\n");
4136
    let hb = repo.commit("right", &[]).unwrap();
4137
    repo.checkout(&[ha, hb], true, "checkout").unwrap();
4138
    let snap = repo.snapshot("status").unwrap();
4139
    assert!(snap.base_snapshot.is_conflicted());
4140
    let json = repo.status_json(&snap).unwrap();
4141
    let ida = repo.store().get_change(&ha).unwrap().change_id.to_hex();
4142
    let idb = repo.store().get_change(&hb).unwrap().change_id.to_hex();
4143
    assert!(json.contains("\"conflicted\":true"), "{json}");
4144
    assert!(
4145
        json.contains("\"kind\":\"text\",\"path\":\"a.txt\""),
4146
        "{json}"
4147
    );
4148
    assert!(json.contains(&ida) && json.contains(&idb), "{json}");
4149
    assert!(json.contains("\"resolved\":false"), "{json}");
4150
    assert!(json.starts_with('{') && json.ends_with('}'));
4151
    // Resolve and the report says so; a clean copy has no conflicts.
4152
    write(root, "a.txt", b"one\nleft\nright\n");
4153
    let snap = repo.snapshot("status").unwrap();
4154
    let json = repo.status_json(&snap).unwrap();
4155
    assert!(json.contains("\"resolved\":true"), "{json}");
4156
    repo.commit("resolve", &[]).unwrap();
4157
    let snap = repo.snapshot("status").unwrap();
4158
    let json = repo.status_json(&snap).unwrap();
4159
    assert!(
4160
        json.contains("\"clean\":true,\"conflicted\":false,\"paths\":[],\"conflicts\":[]"),
4161
        "{json}"
4162
    );
4163
}
4164
4165
#[test]
4166
fn ignore_rules_do_not_untrack_files() {
4167
    hermetic();
4168
    let dir = tempfile::tempdir().unwrap();
4169
    let root = dir.path();
4170
    let repo = Repo::init(root).unwrap().with_home(root.join("home"));
4171
    write(root, "src.c", b"int x;\n");
4172
    write(root, "build/out.o", b"\0obj");
4173
    write(root, "sub/keep.log", b"keep\n");
4174
    write(root, "sub/junk.log", b"junk\n");
4175
    write(root, ".oxyignore", b"/build\n*.log\n!sub/keep.log\n");
4176
    let snap = repo.snapshot("status").unwrap();
4177
    let added: Vec<&str> = snap.statuses.iter().map(|s| s.path.as_str()).collect();
4178
    assert_eq!(
4179
        added,
4180
        vec![".oxyignore", "src.c", "sub/keep.log"],
4181
        "anchored, glob, and negated rules"
4182
    );
4183
    let h1 = repo.commit("base", &[]).unwrap();
4184
    // Ignoring a tracked file changes nothing about it.
4185
    write(root, ".oxyignore", b"/build\n*.log\n!sub/keep.log\nsrc.c\n");
4186
    let snap = repo.snapshot("status").unwrap();
4187
    assert_eq!(
4188
        snap.statuses
4189
            .iter()
4190
            .map(|s| s.path.as_str())
4191
            .collect::<Vec<_>>(),
4192
        vec![".oxyignore"]
4193
    );
4194
    let h2 = repo.commit("ignore src.c", &[]).unwrap();
4195
    assert!(repo
4196
        .load_state(&[h2])
4197
        .unwrap()
4198
        .materialize()
4199
        .files
4200
        .contains_key("src.c"));
4201
    // Its edits are still seen, by status and by the prompt.
4202
    assert_eq!(repo.quick_dirty().unwrap(), Some(false));
4203
    write(root, "src.c", b"int x, y;\n");
4204
    assert_eq!(repo.quick_dirty().unwrap(), Some(true));
4205
    let snap = repo.snapshot("status").unwrap();
4206
    assert_eq!(
4207
        snap.statuses
4208
            .iter()
4209
            .map(|s| (s.path.as_str(), s.status))
4210
            .collect::<Vec<_>>(),
4211
        vec![("src.c", ChangeStatus::Modified)]
4212
    );
4213
    let h3 = repo.commit("edit src.c", &[]).unwrap();
4214
    assert!(
4215
        matches!(&repo.load_state(&[h3]).unwrap().materialize().files["src.c"].content, FileContent::Text { bytes, .. } if bytes == b"int x, y;\n")
4216
    );
4217
    // Deleting it on disk removes it, ignored or not; a checkout brings it back.
4218
    fs::remove_file(root.join("src.c")).unwrap();
4219
    let snap = repo.snapshot("status").unwrap();
4220
    assert_eq!(
4221
        snap.statuses
4222
            .iter()
4223
            .map(|s| (s.path.as_str(), s.status))
4224
            .collect::<Vec<_>>(),
4225
        vec![("src.c", ChangeStatus::Removed)]
4226
    );
4227
    repo.checkout(&[h3], true, "checkout").unwrap();
4228
    assert_eq!(fs::read(root.join("src.c")).unwrap(), b"int x, y;\n");
4229
    assert!(!repo.snapshot("status").unwrap().changed);
4230
    let _ = h1;
4231
}
4232
4233
#[test]
4234
fn split_works_on_non_heads_by_node() {
4235
    hermetic();
4236
    let dir = tempfile::tempdir().unwrap();
4237
    let root = dir.path();
4238
    let repo = Repo::init(root).unwrap().with_home(root.join("home"));
4239
    write(root, "a.txt", b"one\n");
4240
    write(root, "junk/x.lock", b"lock\n");
4241
    let h1 = repo.commit("work plus junk", &[]).unwrap();
4242
    write(root, "a.txt", b"one\ntwo\n");
4243
    let h2 = repo.commit("more work", &[]).unwrap();
4244
    assert_eq!(repo.store().get_change(&h2).unwrap().deps, vec![h1]);
4245
    let id1 = repo.store().get_change(&h1).unwrap().change_id;
4246
    // h1 is not a head: split it by node.
4247
    let (hj, h1b) = repo.split(&h1, &["junk".into()]).unwrap();
4248
    assert_ne!(h1b, h1);
4249
    assert_eq!(
4250
        repo.store().get_change(&h1b).unwrap().change_id,
4251
        id1,
4252
        "the rest keeps the ChangeId"
4253
    );
4254
    let junk = repo.store().get_change(&hj).unwrap();
4255
    assert!(junk.tree_ops.iter().all(
4256
        |op| matches!(op, TreeOp::AddNode { name, .. } if name == "junk" || name == "x.lock")
4257
    ));
4258
    let heads = repo.bookmark_heads().unwrap();
4259
    assert!(
4260
        heads.contains(&hj),
4261
        "the split-off part is a head of its own"
4262
    );
4263
    let snap = repo.load_state(&heads).unwrap().materialize();
4264
    assert!(
4265
        matches!(&snap.files["a.txt"].content, FileContent::Text { bytes, .. } if bytes == b"one\ntwo\n"),
4266
        "the dependent was rewritten onto the new hash"
4267
    );
4268
    assert!(snap.files.contains_key("junk/x.lock"));
4269
    let h2b = heads
4270
        .iter()
4271
        .find(|h| repo.store().get_change(h).unwrap().message == "more work")
4272
        .copied()
4273
        .unwrap();
4274
    assert_eq!(repo.store().get_change(&h2b).unwrap().deps, vec![h1b]);
4275
    assert!(!repo.snapshot("status").unwrap().changed);
4276
    // Abandoning the split-off head removes the junk from history.
4277
    repo.abandon(&hj).unwrap();
4278
    let heads = repo.bookmark_heads().unwrap();
4279
    let snap = repo.load_state(&heads).unwrap().materialize();
4280
    assert!(!snap.files.contains_key("junk/x.lock") && !snap.files.contains_key("junk"));
4281
    assert!(snap.files.contains_key("a.txt"));
4282
    // A dependent that touches the split-off paths blocks the split.
4283
    write(root, "junk/y.lock", b"y\n");
4284
    let hb = repo.commit("junk base", &[]).unwrap();
4285
    write(root, "junk/y.lock", b"yy\n");
4286
    write(root, "b.txt", b"b\n");
4287
    repo.commit("touches junk", &[]).unwrap();
4288
    let err = repo.split(&hb, &["junk".into()]).unwrap_err().to_string();
4289
    assert!(err.contains("depends on the split-off paths"), "{err}");
4290
}
4291
4292
#[test]
4293
fn bookmarks_switch_merge_and_push() {
4294
    hermetic();
4295
    let dir = tempfile::tempdir().unwrap();
4296
    let root = dir.path();
4297
    let origin = Repo::init(&root.join("origin")).unwrap();
4298
    let url = root.join("origin").to_string_lossy().to_string();
4299
    let mut repo = Repo::clone(&url, &root.join("r"))
4300
        .unwrap()
4301
        .with_home(root.join("home"));
4302
    let r = root.join("r");
4303
    write(&r, "a.txt", b"a\n");
4304
    let h_a = repo.commit("a", &[]).unwrap();
4305
    assert!(repo.push("origin", false).unwrap()[0].ok);
4306
    origin.refresh().unwrap();
4307
4308
    // A bookmark at the working copy's base, then work on it.
4309
    assert!(repo.bookmark_create("bad name..", None).is_err());
4310
    assert!(repo.bookmark_create("-x", None).is_err());
4311
    assert_eq!(repo.bookmark_create("feature", None).unwrap(), vec![h_a]);
4312
    assert!(repo.bookmark_create("feature", None).is_err(), "exists");
4313
    repo.bookmark_switch("feature", false).unwrap();
4314
    assert_eq!(repo.config.bookmark, "feature");
4315
    write(&r, "a.txt", b"a\nb\n");
4316
    write(&r, "b.txt", b"b\n");
4317
    let h_b = repo.commit("b on feature", &[]).unwrap();
4318
    assert_eq!(
4319
        repo.bookmark_heads().unwrap(),
4320
        vec![h_b],
4321
        "b edits a.txt, so it depends on a"
4322
    );
4323
    assert_eq!(
4324
        repo.resolve_heads("main").unwrap(),
4325
        vec![h_a],
4326
        "main is untouched"
4327
    );
4328
    assert_eq!(
4329
        repo.resolve_change("feature").unwrap(),
4330
        h_b,
4331
        "a one-head bookmark names its change"
4332
    );
4333
    // Reopening keeps the workspace's bookmark.
4334
    let reopened = Repo::open(&r).unwrap().with_home(root.join("home"));
4335
    assert_eq!(reopened.config.bookmark, "feature");
4336
    // Back to main: b.txt goes away; work there.
4337
    repo.bookmark_switch("main", false).unwrap();
4338
    assert!(!r.join("b.txt").exists());
4339
    assert_eq!(fs::read(r.join("a.txt")).unwrap(), b"a\n");
4340
    write(&r, "c.txt", b"c\n");
4341
    let h_c = repo.commit("c on main", &[]).unwrap();
4342
    let list = repo.bookmarks().unwrap();
4343
    assert_eq!(
4344
        list.iter()
4345
            .map(|b| (b.name.as_str(), b.current))
4346
            .collect::<Vec<_>>(),
4347
        vec![("feature", false), ("main", true)]
4348
    );
4349
    assert_eq!(
4350
        list.iter().find(|b| b.name == "main").unwrap().ahead,
4351
        Some(1),
4352
        "c is not on origin yet"
4353
    );
4354
    // Merge feature into main: the union, both heads, no merge change.
4355
    let m = repo.merge("feature").unwrap();
4356
    assert!(m.changed && m.checked_out);
4357
    let mut want = vec![h_b, h_c];
4358
    want.sort();
4359
    assert_eq!(m.heads, want);
4360
    assert_eq!(fs::read(r.join("b.txt")).unwrap(), b"b\n");
4361
    assert!(!repo.merge("feature").unwrap().changed, "already merged");
4362
    assert!(repo.merge("main").is_err());
4363
    // The other bookmark can be pushed by name and appears at origin.
4364
    assert!(repo.push_bookmark("origin", "feature", false).unwrap()[0].ok);
4365
    origin.refresh().unwrap();
4366
    assert_eq!(origin.resolve_heads("feature").unwrap(), vec![h_b]);
4367
    assert!(repo.push("origin", false).unwrap()[0].ok);
4368
    origin.refresh().unwrap();
4369
    assert_eq!(
4370
        repo.bookmarks()
4371
            .unwrap()
4372
            .iter()
4373
            .find(|b| b.name == "main")
4374
            .unwrap()
4375
            .ahead,
4376
        Some(0)
4377
    );
4378
    // A second workspace inherits the current bookmark and can switch independently.
4379
    let ws = repo.workspace_add(&root.join("ws"), None).unwrap();
4380
    assert_eq!(ws.config.bookmark, "main");
4381
    let mut ws = ws;
4382
    ws.bookmark_switch("feature", false).unwrap();
4383
    assert_eq!(
4384
        Repo::open(&r).unwrap().config.bookmark,
4385
        "main",
4386
        "the first workspace is unaffected"
4387
    );
4388
    assert!(
4389
        repo.bookmark_delete("feature").is_err(),
4390
        "current bookmark of another workspace"
4391
    );
4392
    ws.bookmark_switch("main", false).unwrap();
4393
    // Set and delete.
4394
    assert_eq!(repo.bookmark_set("feature", &[h_a]).unwrap(), vec![h_a]);
4395
    assert!(repo.bookmark_delete("main").is_err(), "current here");
4396
    repo.bookmark_delete("feature").unwrap();
4397
    assert!(repo.resolve_heads("feature").is_err());
4398
    assert!(repo.bookmark_set("feature", &[h_a]).is_err());
4399
    assert!(
4400
        repo.checkout(&[h_a], false, "checkout").is_ok(),
4401
        "changes of a deleted bookmark remain"
4402
    );
4403
}
4404
4405
#[test]
4406
fn oxygen_subrepos_pin_follow_and_update() {
4407
    hermetic();
4408
    let dir = tempfile::tempdir().unwrap();
4409
    let root = dir.path();
4410
    // A library repository with two commits, and a bare-ish origin for it.
4411
    let lib_origin = Repo::init(&root.join("lib-origin")).unwrap();
4412
    let lib_url = root.join("lib-origin").to_string_lossy().to_string();
4413
    let lib = Repo::clone(&lib_url, &root.join("lib"))
4414
        .unwrap()
4415
        .with_home(root.join("home"));
4416
    write(&root.join("lib"), "lib.txt", b"v1\n");
4417
    let l1 = lib.commit("lib v1", &[]).unwrap();
4418
    assert!(lib.push("origin", false).unwrap()[0].ok);
4419
    let _ = lib_origin;
4420
4421
    // The application (a clone of its own origin) adds it as a subrepo.
4422
    let app_origin = Repo::init(&root.join("app-origin")).unwrap();
4423
    let app_url = root.join("app-origin").to_string_lossy().to_string();
4424
    let _ = app_origin;
4425
    let app_dir = root.join("app");
4426
    let app = Repo::clone(&app_url, &app_dir)
4427
        .unwrap()
4428
        .with_home(root.join("home"));
4429
    write(&app_dir, "main.txt", b"app\n");
4430
    let pin = app.submodule_add(&lib_url, "libs/lib", None).unwrap();
4431
    assert!(matches!(&pin, crate::subrepo::Pin::Oxy { heads, .. } if heads == &vec![l1]));
4432
    assert!(app_dir.join(".oxymodules").exists() && app_dir.join("libs/lib/.oxy").is_dir());
4433
    let snap = app.snapshot("status").unwrap();
4434
    let paths: Vec<&str> = snap.statuses.iter().map(|s| s.path.as_str()).collect();
4435
    assert_eq!(
4436
        paths,
4437
        vec![".oxymodules", "libs/lib", "main.txt"],
4438
        "the nested files are not walked"
4439
    );
4440
    let a1 = app.commit("app with lib", &[]).unwrap();
4441
    let files = app.load_state(&[a1]).unwrap().materialize().files;
4442
    assert_eq!(files["libs/lib"].kind, NodeKind::Subrepo);
4443
    assert!(!files.contains_key("libs/lib/lib.txt"));
4444
    assert!(!app.snapshot("status").unwrap().changed);
4445
    let subs = app.subrepos().unwrap();
4446
    assert_eq!(subs.len(), 1);
4447
    assert_eq!(subs[0].actual.as_ref(), Some(&subs[0].pin));
4448
4449
    // Advance the nested repository: the parent sees a modified pin.
4450
    let nested = Repo::open(&app_dir.join("libs/lib"))
4451
        .unwrap()
4452
        .with_home(root.join("home"));
4453
    write(&app_dir.join("libs/lib"), "lib.txt", b"v2\n");
4454
    let l2 = nested.commit("lib v2", &[]).unwrap();
4455
    assert!(nested.push("origin", false).unwrap()[0].ok);
4456
    let snap = app.snapshot("status").unwrap();
4457
    assert_eq!(
4458
        snap.statuses
4459
            .iter()
4460
            .map(|s| (s.path.as_str(), s.status))
4461
            .collect::<Vec<_>>(),
4462
        vec![("libs/lib", ChangeStatus::Modified)]
4463
    );
4464
    let a2 = app.commit("bump lib", &[]).unwrap();
4465
    // Checking out the older app state brings the nested working copy back
4466
    // to the older pin, but never moves its bookmark backwards (oxygen#38).
4467
    let r = app.checkout(&[a1], false, "checkout").unwrap();
4468
    assert!(
4469
        r.notes.len() == 1 && r.notes[0].contains("keeps 1 newer change"),
4470
        "{:?}",
4471
        r.notes
4472
    );
4473
    assert_eq!(fs::read(app_dir.join("libs/lib/lib.txt")).unwrap(), b"v1\n");
4474
    let nested = Repo::open(&app_dir.join("libs/lib")).unwrap();
4475
    assert_eq!(nested.bookmark_heads().unwrap(), vec![l2]);
4476
    assert_eq!(nested.working_copy().unwrap().1.deps, vec![l1]);
4477
    assert!(!app.snapshot("status").unwrap().changed);
4478
    // A dirty nested repository is left alone and reported.
4479
    write(&app_dir.join("libs/lib"), "scratch.txt", b"wip\n");
4480
    let r = app.checkout(&[a2], false, "checkout").unwrap();
4481
    assert!(
4482
        r.notes.iter().any(|n| n.contains("uncommitted")),
4483
        "{:?}",
4484
        r.notes
4485
    );
4486
    assert_eq!(fs::read(app_dir.join("libs/lib/lib.txt")).unwrap(), b"v1\n");
4487
    fs::remove_file(app_dir.join("libs/lib/scratch.txt")).unwrap();
4488
    let r = app.submodule_update(false, &[]).unwrap();
4489
    assert_eq!(r, vec![("libs/lib".to_string(), SubrepoSync::Updated)]);
4490
    assert_eq!(fs::read(app_dir.join("libs/lib/lib.txt")).unwrap(), b"v2\n");
4491
    let _ = l2;
4492
4493
    // A fresh clone of the app has the pin but no nested repository until update --init.
4494
    assert!(app.push("origin", false).unwrap()[0].ok);
4495
    let clone_dir = root.join("app-clone");
4496
    let clone = Repo::clone(&app_url, &clone_dir)
4497
        .unwrap()
4498
        .with_home(root.join("home"));
4499
    assert!(!clone_dir.join("libs/lib/.oxy").exists());
4500
    assert_eq!(
4501
        clone.submodule_update(false, &[]).unwrap(),
4502
        vec![("libs/lib".to_string(), SubrepoSync::Missing)]
4503
    );
4504
    assert_eq!(
4505
        clone.submodule_update(true, &[]).unwrap(),
4506
        vec![("libs/lib".to_string(), SubrepoSync::Updated)]
4507
    );
4508
    assert_eq!(
4509
        fs::read(clone_dir.join("libs/lib/lib.txt")).unwrap(),
4510
        b"v2\n"
4511
    );
4512
    assert!(!clone.snapshot("status").unwrap().changed);
4513
    // Removing the subrepo leaves the directory and drops the node.
4514
    clone.submodule_remove("libs/lib").unwrap();
4515
    let snap = clone.snapshot("status").unwrap();
4516
    assert!(
4517
        snap.statuses
4518
            .iter()
4519
            .any(|s| s.path == "libs/lib" && s.status == ChangeStatus::Removed),
4520
        "{:?}",
4521
        snap.statuses
4522
    );
4523
    let c = clone.commit("drop lib", &[]).unwrap();
4524
    assert!(!clone
4525
        .load_state(&[c])
4526
        .unwrap()
4527
        .materialize()
4528
        .files
4529
        .contains_key("libs/lib"));
4530
    assert!(clone_dir.join("libs/lib/lib.txt").exists());
4531
    assert!(
4532
        !clone.snapshot("status").unwrap().changed,
4533
        "an unregistered nested repository is ignored"
4534
    );
4535
}
4536
4537
#[test]
4538
fn git_submodules_import_and_export_as_gitlinks() {
4539
    hermetic();
4540
    if std::process::Command::new("git")
4541
        .arg("--version")
4542
        .output()
4543
        .is_err()
4544
    {
4545
        eprintln!("git not installed; skipping");
4546
        return;
4547
    }
4548
    let dir = tempfile::tempdir().unwrap();
4549
    let root = dir.path();
4550
    let git_in = |d: &Path, args: &[&str]| -> String {
4551
        let out = std::process::Command::new("git")
4552
            .arg("-C")
4553
            .arg(d)
4554
            .args([
4555
                "-c",
4556
                "user.name=Grace",
4557
                "-c",
4558
                "[email protected]",
4559
                "-c",
4560
                "commit.gpgsign=false",
4561
                "-c",
4562
                "protocol.file.allow=always",
4563
            ])
4564
            .args(args)
4565
            .output()
4566
            .unwrap();
4567
        assert!(
4568
            out.status.success(),
4569
            "git {args:?}: {}",
4570
            String::from_utf8_lossy(&out.stderr)
4571
        );
4572
        String::from_utf8_lossy(&out.stdout).trim().to_string()
4573
    };
4574
    let sub = root.join("sub");
4575
    fs::create_dir_all(&sub).unwrap();
4576
    git_in(&sub, &["init", "-q", "-b", "main"]);
4577
    write(&sub, "s.txt", b"sub\n");
4578
    git_in(&sub, &["add", "."]);
4579
    git_in(&sub, &["commit", "-q", "-m", "sub initial"]);
4580
    let sub_sha = git_in(&sub, &["rev-parse", "HEAD"]);
4581
    let g = root.join("main.git");
4582
    fs::create_dir_all(&g).unwrap();
4583
    git_in(&g, &["init", "-q", "-b", "main"]);
4584
    write(&g, "README.md", b"# app\n");
4585
    git_in(&g, &["add", "."]);
4586
    git_in(&g, &["commit", "-q", "-m", "initial"]);
4587
    git_in(
4588
        &g,
4589
        &[
4590
            "submodule",
4591
            "add",
4592
            "-q",
4593
            sub.to_str().unwrap(),
4594
            "vendor/sub",
4595
        ],
4596
    );
4597
    git_in(&g, &["commit", "-q", "-m", "add submodule"]);
4598
4599
    let dest = root.join("oxy");
4600
    let repo = Repo::init(&dest).unwrap().with_home(root.join("home"));
4601
    let rep = repo.import_git(&g, "main").unwrap();
4602
    assert_eq!((rep.commits, rep.submodules), (2, 1));
4603
    let files = repo
4604
        .load_state(&repo.bookmark_heads().unwrap())
4605
        .unwrap()
4606
        .materialize()
4607
        .files;
4608
    assert_eq!(files["vendor/sub"].kind, NodeKind::Subrepo);
4609
    let FileContent::Opaque { blobs } = &files["vendor/sub"].content else {
4610
        panic!()
4611
    };
4612
    assert_eq!(
4613
        crate::subrepo::Pin::decode(&repo.read_blob(&blobs[0]).unwrap()).unwrap(),
4614
        crate::subrepo::Pin::Git {
4615
            sha: sub_sha.clone(),
4616
            branch: "HEAD".into()
4617
        }
4618
    );
4619
    let modules =
4620
        crate::subrepo::Modules::parse(&fs::read_to_string(dest.join(".oxymodules")).unwrap());
4621
    assert_eq!(modules.entries["vendor/sub"].url, sub.to_string_lossy());
4622
    assert!(modules.entries["vendor/sub"].git);
4623
    assert!(
4624
        files.contains_key(".gitmodules"),
4625
        "the Git file is kept for round trips"
4626
    );
4627
    assert!(
4628
        !dest.join("vendor/sub/.git").exists(),
4629
        "not cloned until update --init"
4630
    );
4631
    assert!(!repo.snapshot("status").unwrap().changed);
4632
    // update --init clones it at the pinned commit; status is unchanged.
4633
    assert_eq!(
4634
        repo.submodule_update(true, &[]).unwrap(),
4635
        vec![("vendor/sub".to_string(), SubrepoSync::Updated)]
4636
    );
4637
    assert_eq!(
4638
        git_in(&dest.join("vendor/sub"), &["rev-parse", "HEAD"]),
4639
        sub_sha
4640
    );
4641
    assert!(!repo.snapshot("status").unwrap().changed);
4642
    // Export writes the gitlink and .gitmodules back.
4643
    let mirror = root.join("mirror.git");
4644
    let rep = repo.git_export(&mirror).unwrap();
4645
    assert_eq!(rep.skipped_subrepos, 0);
4646
    let ls = git_in(&mirror, &["ls-tree", "main", "vendor/sub"]);
4647
    assert!(
4648
        ls.starts_with("160000 commit ") && ls.contains(&sub_sha),
4649
        "{ls}"
4650
    );
4651
    assert_eq!(
4652
        git_in(&mirror, &["ls-tree", "--name-only", "main"]),
4653
        ".gitmodules\nREADME.md\nvendor"
4654
    );
4655
    let orig_tree = git_in(&g, &["rev-parse", "main^{tree}"]);
4656
    assert_eq!(
4657
        git_in(&mirror, &["rev-parse", "main^{tree}"]),
4658
        orig_tree,
4659
        "tree round trip"
4660
    );
4661
}
4662
4663
#[test]
4664
fn partial_commits_by_path_and_by_hunk() {
4665
    hermetic();
4666
    let dir = tempfile::tempdir().unwrap();
4667
    let root = dir.path();
4668
    let repo = Repo::init(root).unwrap().with_home(root.join("home"));
4669
    write(root, "a.txt", b"1\n2\n3\n");
4670
    write(root, "b.txt", b"b\n");
4671
    let h0 = repo.commit("base", &[]).unwrap();
4672
    write(root, "a.txt", b"0\n1\n2\n3\n4\n");
4673
    write(root, "b.txt", b"b\nbb\n");
4674
    write(root, "c.txt", b"c\n");
4675
    // By path: only a.txt goes in; the rest stays on disk as uncommitted work.
4676
    let h1 = repo
4677
        .commit_selection("a only", &[], &Selection::Paths(vec!["a.txt".into()]))
4678
        .unwrap();
4679
    let c1 = repo.store().get_change(&h1).unwrap();
4680
    assert!(
4681
        c1.tree_ops.is_empty() && c1.edits.iter().all(|e| e.node() == c1.edits[0].node()),
4682
        "{:?}",
4683
        c1.tree_ops
4684
    );
4685
    assert_eq!(c1.deps, vec![h0]);
4686
    let files = repo.load_state(&[h1]).unwrap().materialize().files;
4687
    assert!(
4688
        matches!(&files["a.txt"].content, FileContent::Text { bytes, .. } if bytes == b"0\n1\n2\n3\n4\n")
4689
    );
4690
    assert!(matches!(&files["b.txt"].content, FileContent::Text { bytes, .. } if bytes == b"b\n"));
4691
    assert!(!files.contains_key("c.txt"));
4692
    let snap = repo.snapshot("status").unwrap();
4693
    assert_eq!(
4694
        snap.statuses
4695
            .iter()
4696
            .map(|s| (s.path.as_str(), s.status))
4697
            .collect::<Vec<_>>(),
4698
        vec![
4699
            ("b.txt", ChangeStatus::Modified),
4700
            ("c.txt", ChangeStatus::Added)
4701
        ]
4702
    );
4703
    assert_eq!(
4704
        fs::read(root.join("b.txt")).unwrap(),
4705
        b"b\nbb\n",
4706
        "disk untouched"
4707
    );
4708
    // By hunk: pick the b.txt insert; c.txt's addition is left.
4709
    let (_, hunks) = repo.hunks().unwrap();
4710
    let b_hunk = hunks
4711
        .iter()
4712
        .find(|h| h.path == "b.txt" && h.text.contains("+bb"))
4713
        .unwrap()
4714
        .index;
4715
    let h2 = repo
4716
        .commit_selection("b only", &[], &Selection::Hunks(vec![b_hunk]))
4717
        .unwrap();
4718
    let files = repo.load_state(&[h2]).unwrap().materialize().files;
4719
    assert!(
4720
        matches!(&files["b.txt"].content, FileContent::Text { bytes, .. } if bytes == b"b\nbb\n")
4721
    );
4722
    assert!(!files.contains_key("c.txt"));
4723
    let snap = repo.snapshot("status").unwrap();
4724
    assert_eq!(
4725
        snap.statuses
4726
            .iter()
4727
            .map(|s| s.path.as_str())
4728
            .collect::<Vec<_>>(),
4729
        vec!["c.txt"]
4730
    );
4731
    // Choosing only the content hunk of a file in a new directory pulls in
4732
    // the directory and file additions it needs.
4733
    write(root, "d/e.txt", b"e\n");
4734
    let (_, hunks) = repo.hunks().unwrap();
4735
    let e_insert = hunks
4736
        .iter()
4737
        .find(|h| h.path == "d/e.txt" && h.text.contains("+e"))
4738
        .unwrap()
4739
        .index;
4740
    let h3 = repo
4741
        .commit_selection("e only", &[], &Selection::Hunks(vec![e_insert]))
4742
        .unwrap();
4743
    let c3 = repo.store().get_change(&h3).unwrap();
4744
    assert_eq!(c3.tree_ops.len(), 2, "{:?}", c3.tree_ops);
4745
    let files = repo.load_state(&[h3]).unwrap().materialize().files;
4746
    assert!(files.contains_key("d/e.txt") && !files.contains_key("c.txt"));
4747
    // Choosing a new file's addition hunk brings its content along.
4748
    write(root, "f/g.txt", b"g\n");
4749
    let (_, hunks) = repo.hunks().unwrap();
4750
    let g_add = hunks
4751
        .iter()
4752
        .find(|h| h.path == "f/g.txt" && h.text.starts_with("A "))
4753
        .unwrap()
4754
        .index;
4755
    let h4 = repo
4756
        .commit_selection("g by addition", &[], &Selection::Hunks(vec![g_add]))
4757
        .unwrap();
4758
    let files = repo.load_state(&[h4]).unwrap().materialize().files;
4759
    assert!(
4760
        matches!(&files["f/g.txt"].content, FileContent::Text { bytes, .. } if bytes == b"g\n")
4761
    );
4762
    assert!(!repo
4763
        .snapshot("status")
4764
        .unwrap()
4765
        .statuses
4766
        .iter()
4767
        .any(|s| s.path == "f/g.txt"));
4768
    // Everything left commits normally; the working copy is then clean.
4769
    repo.commit("the rest", &[]).unwrap();
4770
    assert!(!repo.snapshot("status").unwrap().changed);
4771
    let files = repo
4772
        .load_state(&repo.bookmark_heads().unwrap())
4773
        .unwrap()
4774
        .materialize()
4775
        .files;
4776
    assert!(files.contains_key("c.txt"));
4777
}
4778
4779
#[test]
4780
fn blame_attributes_lines_to_introducing_changes_across_renames() {
4781
    hermetic();
4782
    let dir = tempfile::tempdir().unwrap();
4783
    let root = dir.path();
4784
    let mut repo = Repo::init(root).unwrap().with_home(root.join("home"));
4785
    repo.create_identity("Ada", "[email protected]", IdentityScope::User)
4786
        .unwrap();
4787
    write(root, "a.txt", b"one\n");
4788
    let h1 = repo.commit("first", &[]).unwrap();
4789
    write(root, "a.txt", b"one\ntwo\n");
4790
    let h2 = repo.commit("second", &[]).unwrap();
4791
    let b = repo.blame("a.txt").unwrap();
4792
    assert_eq!(
4793
        b.iter()
4794
            .map(|l| (l.line, l.hash, l.text.as_slice()))
4795
            .collect::<Vec<_>>(),
4796
        vec![(1, h1, b"one\n".as_slice()), (2, h2, b"two\n".as_slice())]
4797
    );
4798
    assert!(b.iter().all(|l| l.author == "Ada"));
4799
    assert_eq!(
4800
        b[0].change_id,
4801
        repo.store().get_change(&h1).unwrap().change_id
4802
    );
4803
    fs::rename(root.join("a.txt"), root.join("b.txt")).unwrap();
4804
    repo.commit("rename", &[]).unwrap();
4805
    let b = repo.blame("b.txt").unwrap();
4806
    assert_eq!(
4807
        b.iter().map(|l| l.hash).collect::<Vec<_>>(),
4808
        vec![h1, h2],
4809
        "the node survives the rename"
4810
    );
4811
    assert!(repo.blame("a.txt").is_err());
4812
}
4813
4814
#[test]
4815
fn bisect_finds_the_first_bad_change() {
4816
    hermetic();
4817
    let dir = tempfile::tempdir().unwrap();
4818
    let root = dir.path();
4819
    let repo = Repo::init(root).unwrap().with_home(root.join("home"));
4820
    let mut content = String::new();
4821
    let mut hashes = Vec::new();
4822
    for i in 1..=8 {
4823
        content.push_str(&format!("line {i}{}\n", if i == 5 { " bug" } else { "" }));
4824
        write(root, "f.txt", content.as_bytes());
4825
        hashes.push(repo.commit(&format!("step {i}"), &[]).unwrap());
4826
    }
4827
    // Each step appends after the previous line, so the chain is linear.
4828
    assert_eq!(repo.bookmark_heads().unwrap(), vec![hashes[7]]);
4829
    repo.bisect_start().unwrap();
4830
    assert!(matches!(
4831
        repo.bisect_mark(Some(true), &[hashes[0]]).unwrap(),
4832
        BisectStep::NeedMarks { good: 1, bad: 0 }
4833
    ));
4834
    let step = repo.bisect_mark(Some(false), &[hashes[7]]).unwrap();
4835
    assert!(
4836
        matches!(step, BisectStep::Testing { remaining: 7, .. }),
4837
        "{step:?}"
4838
    );
4839
    // Automated: bad when the bug line is present.
4840
    let step = repo
4841
        .bisect_run(&["sh".into(), "-c".into(), "! grep -q bug f.txt".into()])
4842
        .unwrap();
4843
    assert_eq!(step, BisectStep::Found { culprit: hashes[4] });
4844
    assert_eq!(
4845
        repo.bisect_status().unwrap(),
4846
        Some(BisectStep::Found { culprit: hashes[4] })
4847
    );
4848
    repo.bisect_reset().unwrap();
4849
    assert_eq!(fs::read_to_string(root.join("f.txt")).unwrap(), content);
4850
    assert!(repo.bisect_status().unwrap().is_none());
4851
    assert!(!repo.snapshot("status").unwrap().changed);
4852
    // Manual marks and a skip.
4853
    repo.bisect_start().unwrap();
4854
    repo.bisect_mark(Some(true), &[hashes[0]]).unwrap();
4855
    let mut step = repo.bisect_mark(Some(false), &[hashes[7]]).unwrap();
4856
    let mut skipped_once = false;
4857
    let mut guard = 0;
4858
    while let BisectStep::Testing { .. } = step {
4859
        guard += 1;
4860
        assert!(guard < 20);
4861
        let text = fs::read_to_string(root.join("f.txt")).unwrap();
4862
        if !skipped_once && text.contains("line 6") {
4863
            // An untestable state away from the boundary: the search routes around it.
4864
            skipped_once = true;
4865
            step = repo.bisect_mark(None, &[]).unwrap();
4866
            continue;
4867
        }
4868
        step = repo.bisect_mark(Some(!text.contains("bug")), &[]).unwrap();
4869
    }
4870
    assert!(skipped_once);
4871
    assert_eq!(step, BisectStep::Found { culprit: hashes[4] });
4872
    repo.bisect_reset().unwrap();
4873
    // Skipping the culprit itself leaves it among the candidates reported.
4874
    repo.bisect_start().unwrap();
4875
    repo.bisect_mark(Some(true), &[hashes[0]]).unwrap();
4876
    let mut step = repo.bisect_mark(Some(false), &[hashes[7]]).unwrap();
4877
    let mut guard = 0;
4878
    while let BisectStep::Testing { heads, .. } = &step {
4879
        guard += 1;
4880
        assert!(guard < 20);
4881
        let text = fs::read_to_string(root.join("f.txt")).unwrap();
4882
        let is_culprit_state =
4883
            heads.contains(&hashes[4]) && !heads.iter().any(|h| hashes[5..].contains(h));
4884
        step = if is_culprit_state {
4885
            repo.bisect_mark(None, &[]).unwrap()
4886
        } else {
4887
            repo.bisect_mark(Some(!text.contains("bug")), &[]).unwrap()
4888
        };
4889
    }
4890
    match step {
4891
        BisectStep::Inconclusive { candidates } => assert!(
4892
            candidates.contains(&hashes[4]) && candidates.len() <= 2,
4893
            "{candidates:?}"
4894
        ),
4895
        other => panic!("{other:?}"),
4896
    }
4897
    repo.bisect_reset().unwrap();
4898
}
4899
4900
#[test]
4901
fn squash_folds_a_change_into_its_dependency() {
4902
    hermetic();
4903
    let dir = tempfile::tempdir().unwrap();
4904
    let root = dir.path();
4905
    let repo = Repo::init(root).unwrap().with_home(root.join("home"));
4906
    write(root, "a.txt", b"1\n");
4907
    let a = repo.commit("A", &[]).unwrap();
4908
    write(root, "a.txt", b"1\n2\n");
4909
    let c = repo.commit("C", &[]).unwrap();
4910
    write(root, "a.txt", b"1\n2\n3\n");
4911
    let e = repo.commit("E", &[]).unwrap();
4912
    write(root, "b.txt", b"b\n");
4913
    let b = repo.commit("B", &[]).unwrap();
4914
    let id_a = repo.store().get_change(&a).unwrap().change_id;
4915
    let id_e = repo.store().get_change(&e).unwrap().change_id;
4916
    // E depends on C which A lacks: refused, naming it.
4917
    let err = repo.squash(&e, &a).unwrap_err().to_string();
4918
    assert!(err.contains(&c.short(12)), "{err}");
4919
    // C into A: A' has both, C is gone, E follows and still reads the same.
4920
    let a2 = repo.squash(&c, &a).unwrap();
4921
    let a2c = repo.store().get_change(&a2).unwrap();
4922
    assert_eq!(a2c.change_id, id_a);
4923
    assert!(a2c.deps.is_empty());
4924
    let heads = repo.bookmark_heads().unwrap();
4925
    let st = repo.load_state(&heads).unwrap();
4926
    assert!(!st.contains(&c) && !st.contains(&a) && !st.contains(&e));
4927
    let e2 = st
4928
        .changes()
4929
        .find(|(_, m)| m.change_id == id_e)
4930
        .map(|(h, _)| *h)
4931
        .unwrap();
4932
    assert_eq!(
4933
        repo.store().get_change(&e2).unwrap().deps,
4934
        vec![a2],
4935
        "E now depends on A' alone"
4936
    );
4937
    let files = st.materialize().files;
4938
    assert!(
4939
        matches!(&files["a.txt"].content, FileContent::Text { bytes, .. } if bytes == b"1\n2\n3\n")
4940
    );
4941
    assert!(files.contains_key("b.txt"));
4942
    assert!(st.contains(&b));
4943
    assert!(!repo.snapshot("status").unwrap().changed);
4944
    assert_eq!(repo.log().unwrap().len(), 4, "working copy, B, E', A'");
4945
    // Undo restores the three original changes.
4946
    repo.undo().unwrap();
4947
    repo.undo().unwrap();
4948
    let st = repo.load_state(&repo.bookmark_heads().unwrap()).unwrap();
4949
    assert!(st.contains(&c) && st.contains(&a) && st.contains(&e));
4950
}
4951
4952
#[test]
4953
fn rebase_re_expresses_a_change_against_another_base() {
4954
    hermetic();
4955
    let dir = tempfile::tempdir().unwrap();
4956
    let root = dir.path();
4957
    let repo = Repo::init(root).unwrap().with_home(root.join("home"));
4958
    write(root, "a.txt", b"1\n2\n");
4959
    let a = repo.commit("A", &[]).unwrap();
4960
    write(root, "a.txt", b"1\n2\n3\n");
4961
    let c = repo.commit("C: append 3", &[]).unwrap();
4962
    write(root, "a.txt", b"1\n2\n3\n4\n");
4963
    let e = repo.commit("E: append 4", &[]).unwrap();
4964
    // A different base: A plus a change that prepends a line.
4965
    repo.checkout(&[a], true, "checkout").unwrap();
4966
    write(root, "a.txt", b"0\n1\n2\n");
4967
    let d = repo.commit("D: prepend 0", &[]).unwrap();
4968
    let id_c = repo.store().get_change(&c).unwrap().change_id;
4969
    let id_e = repo.store().get_change(&e).unwrap().change_id;
4970
    // Rebase C onto D: its effect (append 3) re-derived against D's text.
4971
    let c2 = repo.rebase(&c, &[d]).unwrap();
4972
    let c2c = repo.store().get_change(&c2).unwrap();
4973
    assert_eq!(c2c.change_id, id_c);
4974
    assert!(c2c.deps.contains(&d), "{:?}", c2c.deps);
4975
    let heads = repo.bookmark_heads().unwrap();
4976
    let st = repo.load_state(&heads).unwrap();
4977
    assert!(!st.contains(&c) && st.contains(&d));
4978
    let e2 = st
4979
        .changes()
4980
        .find(|(_, m)| m.change_id == id_e)
4981
        .map(|(h, _)| *h)
4982
        .unwrap();
4983
    let e2deps = repo.store().get_change(&e2).unwrap().deps;
4984
    assert!(
4985
        e2deps.contains(&c2) && !e2deps.contains(&c) && e2deps.contains(&a),
4986
        "E follows C by content and still depends on A, which introduced the file: {e2deps:?}"
4987
    );
4988
    let files = st.materialize().files;
4989
    assert!(
4990
        matches!(&files["a.txt"].content, FileContent::Text { bytes, .. } if bytes == b"0\n1\n2\n3\n4\n"),
4991
        "{:?}",
4992
        files["a.txt"].content
4993
    );
4994
    assert!(!files["a.txt"].is_conflicted());
4995
    // Rebasing onto a state that already contains the change is refused.
4996
    assert!(repo.rebase(&c2, &[c2]).is_err());
4997
    let err = repo.rebase(&e2, &[d]).unwrap_err().to_string();
4998
    assert!(
4999
        err.contains("lacks dependencies"),
5000
        "E needs C, which D's state does not have: {err}"
5001
    );
5002
}
5003
5004
#[test]
5005
fn unsigned_tags_keep_their_message() {
5006
    hermetic();
5007
    let dir = tempfile::tempdir().unwrap();
5008
    let root = dir.path();
5009
    let repo = Repo::init(root).unwrap().with_home(root.join("home"));
5010
    write(root, "a.txt", b"a\n");
5011
    repo.commit("a", &[]).unwrap();
5012
    assert!(repo.secret_key().unwrap().is_none());
5013
    repo.tag_create("v1", &repo.bookmark_heads().unwrap(), "first release")
5014
        .unwrap();
5015
    let tags = repo.tags().unwrap();
5016
    assert_eq!(
5017
        (
5018
            tags[0].name.as_str(),
5019
            tags[0].message.as_str(),
5020
            tags[0].signer.as_deref()
5021
        ),
5022
        ("v1", "first release", None)
5023
    );
5024
    assert!(
5025
        repo.tag_refs().unwrap()[0].attestation.is_none(),
5026
        "an unsigned attestation is not advertised"
5027
    );
5028
}
5029
5030
#[test]
5031
fn fsck_passes_a_sound_repository_and_names_each_fault() {
5032
    // Files on disk are what this tests: tampering with them, and the
5033
    // directory store's crash points.
5034
    if std::env::var_os("OXY_STORE_BACKEND").is_some() {
5035
        return;
5036
    }
5037
    hermetic();
5038
    let dir = tempfile::tempdir().unwrap();
5039
    let root = dir.path();
5040
    let origin_path = root.join("origin");
5041
    let origin = Repo::init(&origin_path).unwrap();
5042
    let mut a = Repo::clone(&origin_path.to_string_lossy(), &root.join("a"))
5043
        .unwrap()
5044
        .with_home(root.join("home-a"));
5045
    a.create_identity("Ada", "[email protected]", IdentityScope::Repo)
5046
        .unwrap();
5047
    write(&root.join("a"), "f.txt", b"one\n");
5048
    write(&root.join("a"), "bin.dat", b"\0\x01\x02binary");
5049
    let h1 = a.commit("first", &[]).unwrap();
5050
    write(&root.join("a"), "f.txt", b"one\ntwo\n");
5051
    let h2 = a.commit("second", &[]).unwrap();
5052
    a.tag_create("v1", &[h2], "first release").unwrap();
5053
    a.checkpoint().unwrap();
5054
    assert!(a.push("origin", false).unwrap()[0].ok);
5055
    origin.refresh().unwrap();
5056
5057
    // Sound: signed changes, a seal, a tag, a checkpoint, a ref attestation.
5058
    for repo in [&a, &origin] {
5059
        let rep = repo.fsck().unwrap();
5060
        assert_eq!(rep.problems, vec![], "{rep:?}");
5061
        // The two commits, plus the working copy's change in `a`.
5062
        assert!(rep.changes >= 2 && rep.signed >= 2, "{rep:?}");
5063
        assert!(rep.ops > 1 && rep.objects > 5);
5064
    }
5065
    assert!(origin.fsck().unwrap().attestations >= 1);
5066
5067
    // A flipped byte in a stored object is corruption, named by hash.
5068
    let c1 = a.store().path_for(&h1);
5069
    let pristine = fs::read(&c1).unwrap();
5070
    let mut bytes = pristine.clone();
5071
    *bytes.last_mut().unwrap() ^= 1;
5072
    fs::write(&c1, &bytes).unwrap();
5073
    let rep = a.fsck().unwrap();
5074
    assert!(rep.errors() >= 1);
5075
    assert!(
5076
        rep.problems
5077
            .iter()
5078
            .any(|p| p.object == Some(h1) && p.what.contains("unreadable")),
5079
        "{rep:?}"
5080
    );
5081
    fs::write(&c1, &pristine).unwrap();
5082
    assert_eq!(a.fsck().unwrap().errors(), 0);
5083
5084
    // A missing change is named with what needed it.
5085
    fs::remove_file(&c1).unwrap();
5086
    let rep = a.fsck().unwrap();
5087
    assert!(
5088
        rep.problems.iter().any(|p| p.severity == Severity::Error
5089
            && p.object == Some(h1)
5090
            && p.what.contains("change missing, needed by change")),
5091
        "{rep:?}"
5092
    );
5093
    fs::write(&c1, &pristine).unwrap();
5094
5095
    // A missing blob is an error in a full clone.
5096
    let c2 = a.store().get_change(&h1).unwrap();
5097
    let blob = c2
5098
        .edits
5099
        .iter()
5100
        .find_map(|e| match e {
5101
            Edit::Replace { new: Some(b), .. } => Some(*b),
5102
            _ => None,
5103
        })
5104
        .expect("the binary file is a blob");
5105
    let bp = a.store().path_for(&blob);
5106
    let blob_bytes = fs::read(&bp).unwrap();
5107
    fs::remove_file(&bp).unwrap();
5108
    let rep = a.fsck().unwrap();
5109
    assert!(
5110
        rep.problems
5111
            .iter()
5112
            .any(|p| p.object == Some(blob) && p.what.contains("blob missing")),
5113
        "{rep:?}"
5114
    );
5115
    fs::write(&bp, &blob_bytes).unwrap();
5116
5117
    // A broken op log head is reported, not a crash.
5118
    let head = root.join("a/.oxy/ops/head");
5119
    let saved = fs::read(&head).unwrap();
5120
    fs::write(&head, b"not a hash").unwrap();
5121
    let rep = a.fsck().unwrap();
5122
    assert!(
5123
        rep.problems.iter().any(|p| p.what.contains("ops/head")),
5124
        "{rep:?}"
5125
    );
5126
    fs::write(&head, saved).unwrap();
5127
    assert_eq!(a.fsck().unwrap().problems, vec![]);
5128
}
5129
5130
/// Copy a directory tree (for restoring a pristine repository).
5131
fn copy_tree(from: &Path, to: &Path) {
5132
    fs::create_dir_all(to).unwrap();
5133
    for e in fs::read_dir(from).unwrap() {
5134
        let e = e.unwrap();
5135
        let target = to.join(e.file_name());
5136
        if e.file_type().unwrap().is_dir() {
5137
            copy_tree(&e.path(), &target);
5138
        } else {
5139
            fs::copy(e.path(), &target).unwrap();
5140
        }
5141
    }
5142
}
5143
5144
/// Spec §13.6: stop `commit` and `push` at every durable step, as a crash
5145
/// would, and check that both repositories still open, pass `fsck`, and
5146
/// accept the same operation again.
5147
#[test]
5148
fn crash_at_every_step_of_commit_and_push_leaves_sound_repositories() {
5149
    // Files on disk are what this tests: tampering with them, and the
5150
    // directory store's crash points.
5151
    if std::env::var_os("OXY_STORE_BACKEND").is_some() {
5152
        return;
5153
    }
5154
    use crate::durable::failpoint;
5155
    hermetic();
5156
    let dir = tempfile::tempdir().unwrap();
5157
    let pristine = dir.path().join("pristine");
5158
    let origin_path = pristine.join("origin");
5159
    Repo::init(&origin_path).unwrap();
5160
    let mut a = Repo::clone(&origin_path.to_string_lossy(), &pristine.join("a"))
5161
        .unwrap()
5162
        .with_home(dir.path().join("home"));
5163
    a.create_identity("Ada", "[email protected]", IdentityScope::Repo)
5164
        .unwrap();
5165
    write(&pristine.join("a"), "f.txt", b"one\n");
5166
    a.commit("first", &[]).unwrap();
5167
    assert!(a.push("origin", false).unwrap()[0].ok);
5168
    drop(a);
5169
5170
    type Op = fn(&Repo) -> Result<()>;
5171
    let edit_and_commit: Op = |r| {
5172
        write(r.root(), "f.txt", b"one\ntwo\n");
5173
        write(r.root(), "big.bin", &vec![7u8; 300_000]);
5174
        r.commit("second", &[]).map(|_| ())
5175
    };
5176
    let push: Op = |r| {
5177
        let res = r.push("origin", false)?;
5178
        if res.iter().all(|x| x.ok) {
5179
            Ok(())
5180
        } else {
5181
            Err(RepoError::Msg(format!("{res:?}")))
5182
        }
5183
    };
5184
5185
    for (name, prepare, op) in [
5186
        ("commit", None, edit_and_commit),
5187
        ("push", Some(edit_and_commit), push),
5188
    ] {
5189
        let mut steps = 0;
5190
        for n in 1.. {
5191
            let run = dir.path().join(format!("{name}-{n}"));
5192
            copy_tree(&pristine, &run);
5193
            // Clones record their remote by path; point it at this copy.
5194
            let open = |p: &Path| {
5195
                let mut r = Repo::open(p).unwrap().with_home(dir.path().join("home"));
5196
                r.config
5197
                    .set("remote.origin.url", &run.join("origin").to_string_lossy())
5198
                    .unwrap();
5199
                r.save_config().unwrap();
5200
                r
5201
            };
5202
            let a = open(&run.join("a"));
5203
            if let Some(prep) = prepare {
5204
                prep(&a).unwrap();
5205
            }
5206
            failpoint::crash_after(n);
5207
            let outcome = op(&a);
5208
            let crashed = failpoint::disarm();
5209
            drop(a);
5210
            if !crashed {
5211
                outcome.unwrap_or_else(|e| panic!("{name} failed without a crash: {e}"));
5212
                steps = n - 1;
5213
                break;
5214
            }
5215
            assert!(
5216
                outcome.is_err(),
5217
                "{name}: a crash at step {n} was swallowed"
5218
            );
5219
            for repo in ["a", "origin"] {
5220
                let r = Repo::open(&run.join(repo)).unwrap_or_else(|e| {
5221
                    panic!("{name} crash at step {n}: {repo} no longer opens: {e}")
5222
                });
5223
                let rep = r.fsck().unwrap();
5224
                assert_eq!(
5225
                    rep.errors(),
5226
                    0,
5227
                    "{name} crash at step {n}: {repo} fails fsck: {:?}",
5228
                    rep.problems
5229
                );
5230
            }
5231
            // The interrupted operation can simply be run again.
5232
            let a = open(&run.join("a"));
5233
            // A crash after the commit point leaves the commit done.
5234
            let landed = a
5235
                .bookmark_heads()
5236
                .unwrap()
5237
                .iter()
5238
                .any(|h| a.store().get_change(h).unwrap().message == "second");
5239
            let again = match (name, landed) {
5240
                ("commit", true) => Ok(()),
5241
                ("commit", false) => a.commit("second", &[]).map(|_| ()),
5242
                _ => op(&a),
5243
            };
5244
            again.unwrap_or_else(|e| panic!("{name} crash at step {n}: retry failed: {e}"));
5245
            assert_eq!(a.fsck().unwrap().errors(), 0);
5246
            fs::remove_dir_all(&run).unwrap();
5247
        }
5248
        assert!(steps >= 3, "{name} has only {steps} durable steps?");
5249
    }
5250
}
5251
5252
/// Spec §12.1: commands in two workspaces of one repository, and pushes,
5253
/// running at the same time lose nothing: every commit ends up on the
5254
/// bookmark, locally and on the remote, and the repository passes fsck.
5255
#[test]
5256
fn concurrent_commits_in_two_workspaces_lose_nothing() {
5257
    hermetic();
5258
    let dir = tempfile::tempdir().unwrap();
5259
    let root = dir.path();
5260
    let origin = root.join("origin");
5261
    Repo::init_bare_unbound(&origin).unwrap();
5262
    let main = root.join("main");
5263
    let mut repo = Repo::init(&main).unwrap();
5264
    repo.config
5265
        .set("remote.origin.url", &origin.to_string_lossy())
5266
        .unwrap();
5267
    repo.save_config().unwrap();
5268
    write(&main, "seed.txt", b"seed\n");
5269
    repo.commit("seed", &[]).unwrap();
5270
    let second = root.join("second");
5271
    repo.workspace_add(&second, None).unwrap();
5272
    drop(repo);
5273
5274
    const EACH: usize = 15;
5275
    std::thread::scope(|s| {
5276
        for (tag, dir, push) in [("a", main.clone(), true), ("b", second.clone(), false)] {
5277
            s.spawn(move || {
5278
                let r = Repo::open(&dir).unwrap();
5279
                for i in 0..EACH {
5280
                    write(
5281
                        &dir,
5282
                        &format!("{tag}-{i}.txt"),
5283
                        format!("{tag} {i}\n").as_bytes(),
5284
                    );
5285
                    r.commit(&format!("{tag} {i}"), &[]).unwrap();
5286
                    if push && i % 5 == 4 {
5287
                        // A push may be refused while the other workspace moves the bookmark; nothing may be lost either way.
5288
                        let _ = r.push("origin", false);
5289
                    }
5290
                }
5291
            });
5292
        }
5293
    });
5294
5295
    let repo = Repo::open(&main).unwrap();
5296
    let heads = repo.bookmark_heads().unwrap();
5297
    let state = repo.load_state(&heads).unwrap();
5298
    let messages: BTreeSet<String> = state.changes().map(|(_, m)| m.message.clone()).collect();
5299
    for tag in ["a", "b"] {
5300
        for i in 0..EACH {
5301
            assert!(
5302
                messages.contains(&format!("{tag} {i}")),
5303
                "lost commit {tag} {i}; have {messages:?}"
5304
            );
5305
        }
5306
    }
5307
    let rep = repo.fsck().unwrap();
5308
    assert_eq!(rep.errors(), 0, "{:?}", rep.problems);
5309
    assert!(repo.push("origin", false).unwrap().iter().all(|r| r.ok));
5310
    let hosted = Repo::open(&origin).unwrap();
5311
    let hosted_heads = hosted.bookmark_heads().unwrap();
5312
    assert_eq!(
5313
        hosted.load_state(&hosted_heads).unwrap().len(),
5314
        state.len(),
5315
        "the remote has every commit"
5316
    );
5317
}
5318
5319
/// Two operations recorded from the same parent (what two processes do
5320
/// when they race) are merged: both bookmarks' heads survive, and a
5321
/// change made on one side only is kept.
5322
#[test]
5323
fn operations_from_the_same_parent_are_merged() {
5324
    hermetic();
5325
    let dir = tempfile::tempdir().unwrap();
5326
    let root = dir.path();
5327
    let repo = Repo::init(root).unwrap();
5328
    write(root, "a.txt", b"a\n");
5329
    let a = repo.commit("a", &[]).unwrap();
5330
    write(root, "b.txt", b"b\n");
5331
    let b = repo.commit("b", &[]).unwrap();
5332
    let (x, op) = repo.head_op().unwrap();
5333
    let state = |heads: Vec<ChangeHash>| repo.store().put_state(&StateObject::new(heads)).unwrap();
5334
5335
    // Side one moves main to just `a` and adds a bookmark; side two moves main to just `b`.
5336
    let mut one = op.view.clone();
5337
    one.bookmarks.insert("main".into(), state(vec![a]));
5338
    one.bookmarks.insert("topic".into(), state(vec![a]));
5339
    let mut two = op.view.clone();
5340
    two.bookmarks.insert("main".into(), state(vec![b]));
5341
    repo.record_op(&[x], "one", one).unwrap();
5342
    let merged = repo.record_op(&[x], "two", two).unwrap();
5343
5344
    let (head, op) = repo.head_op().unwrap();
5345
    assert_eq!(head, merged);
5346
    assert_eq!(op.parents.len(), 2, "a merge of the two operations");
5347
    assert!(op.command.contains("merged with a concurrent operation"));
5348
    let mut main = repo
5349
        .store()
5350
        .get_state(&op.view.bookmarks["main"])
5351
        .unwrap()
5352
        .heads;
5353
    main.sort();
5354
    let mut want = vec![a, b];
5355
    want.sort();
5356
    assert_eq!(main, want, "both sides' heads are kept");
5357
    assert!(
5358
        op.view.bookmarks.contains_key("topic"),
5359
        "a one-sided change survives"
5360
    );
5361
    assert_eq!(repo.fsck().unwrap().errors(), 0);
5362
}
5363
5364
#[test]
5365
fn failed_requests_come_with_a_next_step() {
5366
    use crate::protocol::hint_for;
5367
    assert!(hint_for("https://h/x/oxy/v1/push: HTTP 401: bad token")
5368
        .unwrap()
5369
        .contains("token"));
5370
    assert!(hint_for("…: HTTP 403: forbidden")
5371
        .unwrap()
5372
        .contains("repo:write"));
5373
    assert!(hint_for("…: HTTP 404: no such repository")
5374
        .unwrap()
5375
        .contains("owner and repository name"));
5376
    assert!(hint_for("invalid peer certificate: UnknownIssuer")
5377
        .unwrap()
5378
        .contains("oxyhub-ca.pem"));
5379
    assert!(hint_for("Connect error: Connection refused (os error 111)")
5380
        .unwrap()
5381
        .contains("running"));
5382
    assert!(hint_for("Dns Failed: failed to lookup address information")
5383
        .unwrap()
5384
        .contains("resolve"));
5385
    assert_eq!(hint_for("something else entirely"), None);
5386
}
5387
5388
#[test]
5389
fn doctor_names_problems_and_what_to_do() {
5390
    hermetic();
5391
    let dir = tempfile::tempdir().unwrap();
5392
    let root = dir.path();
5393
    let origin = root.join("origin");
5394
    Repo::init_bare_unbound(&origin).unwrap();
5395
    let mut repo = Repo::init(&root.join("r"))
5396
        .unwrap()
5397
        .with_home(root.join("home"));
5398
    let find = |r: &DoctorReport, area: &str, h: Health| {
5399
        r.checks
5400
            .iter()
5401
            .find(|c| c.area == area && c.health == h)
5402
            .cloned()
5403
    };
5404
5405
    let r = repo.doctor(true);
5406
    assert!(find(&r, "identity", Health::Warn)
5407
        .unwrap()
5408
        .hint
5409
        .unwrap()
5410
        .contains("oxy identity create"));
5411
    assert!(find(&r, "repository", Health::Ok).is_some());
5412
5413
    repo.create_identity("Ada", "[email protected]", IdentityScope::Repo)
5414
        .unwrap();
5415
    repo.config.set("author.name", "Ada").unwrap();
5416
    repo.config.set("author.email", "[email protected]").unwrap();
5417
    repo.config
5418
        .set("remote.origin.url", &origin.to_string_lossy())
5419
        .unwrap();
5420
    repo.config
5421
        .set("remote.down.url", "http://127.0.0.1:9/a/b")
5422
        .unwrap();
5423
    repo.config.set("remote.down.token", "t").unwrap();
5424
    repo.config
5425
        .set("remote.badca.url", "https://example.invalid/a/b")
5426
        .unwrap();
5427
    repo.config
5428
        .set(
5429
            "remote.badca.ca",
5430
            &root.join("missing.pem").to_string_lossy(),
5431
        )
5432
        .unwrap();
5433
    repo.save_config().unwrap();
5434
5435
    let r = repo.doctor(true);
5436
    assert!(find(&r, "identity", Health::Ok).is_some(), "{r:?}");
5437
    assert!(find(&r, "author", Health::Ok).is_some(), "{r:?}");
5438
    assert!(find(&r, "remote origin", Health::Ok)
5439
        .unwrap()
5440
        .message
5441
        .contains("first push binds it"));
5442
    let down = find(&r, "remote down", Health::Fail).unwrap();
5443
    assert!(
5444
        down.hint.as_deref().unwrap_or("").contains("running"),
5445
        "{down:?}"
5446
    );
5447
    let badca = find(&r, "remote badca", Health::Fail).unwrap();
5448
    assert!(
5449
        badca.hint.unwrap().contains("remote.badca.ca"),
5450
        "the remote's own name is in the hint"
5451
    );
5452
    assert_eq!(r.worst(), Health::Fail);
5453
5454
    // Offline, nothing is contacted.
5455
    let r = repo.doctor(false);
5456
    assert!(find(&r, "remote down", Health::Fail).is_none());
5457
    assert!(find(&r, "remote down", Health::Ok)
5458
        .unwrap()
5459
        .message
5460
        .contains("not contacted"));
5461
}
5462
5463
/// Spec §8.1: deleting a line depends on whoever inserted the lines right
5464
/// after it. Inserting after `b` and then deleting `b`, one commit after
5465
/// the other, must not leave a delete/insert conflict.
5466
#[test]
5467
fn deleting_a_line_after_an_insertion_below_it_is_not_a_conflict() {
5468
    hermetic();
5469
    let dir = tempfile::tempdir().unwrap();
5470
    let root = dir.path();
5471
    let repo = Repo::init(root).unwrap();
5472
    write(root, "f", b"a\nb\nc\n");
5473
    repo.commit("base", &[]).unwrap();
5474
    write(root, "f", b"a\nb\nx\nc\n");
5475
    let insert = repo.commit("insert x after b", &[]).unwrap();
5476
    write(root, "f", b"a\nx\nc\n");
5477
    let delete = repo.commit("delete b", &[]).unwrap();
5478
    assert!(
5479
        repo.store()
5480
            .get_change(&delete)
5481
            .unwrap()
5482
            .deps
5483
            .contains(&insert),
5484
        "the deletion depends on the insertion below the deleted line"
5485
    );
5486
    let heads = repo.bookmark_heads().unwrap();
5487
    assert_eq!(heads, vec![delete]);
5488
    let snap = repo.load_state(&heads).unwrap().materialize();
5489
    assert!(!snap.is_conflicted());
5490
    assert!(
5491
        matches!(&snap.files["f"].content, FileContent::Text { bytes, .. } if bytes == b"a\nx\nc\n")
5492
    );
5493
}
5494
5495
/// Spec §9.3: a binary file reverted to an earlier blob keeps it, and each
5496
/// replacement depends on the change that set the blob it replaces.
5497
#[test]
5498
fn a_binary_file_reverted_to_an_earlier_blob_keeps_it() {
5499
    hermetic();
5500
    let dir = tempfile::tempdir().unwrap();
5501
    let root = dir.path();
5502
    let repo = Repo::init(root).unwrap();
5503
    write(root, "bin", b"\0A");
5504
    let v1 = repo.commit("v1", &[]).unwrap();
5505
    write(root, "bin", b"\0B");
5506
    let v2 = repo.commit("v2", &[]).unwrap();
5507
    assert!(repo.store().get_change(&v2).unwrap().deps.contains(&v1));
5508
    write(root, "bin", b"\0A");
5509
    let v3 = repo.commit("back to A", &[]).unwrap();
5510
    assert!(repo.store().get_change(&v3).unwrap().deps.contains(&v2));
5511
    assert_eq!(repo.bookmark_heads().unwrap(), vec![v3]);
5512
    let state = repo.load_state(&[v3]).unwrap();
5513
    let snap = state.materialize();
5514
    let FileContent::Opaque { blobs } = &snap.files["bin"].content else {
5515
        panic!("opaque")
5516
    };
5517
    assert_eq!(blobs.len(), 1, "one live blob, not none and not two");
5518
    assert_eq!(repo.read_blob(&blobs[0]).unwrap(), b"\0A");
5519
}
5520
5521
/// Spec §23: a binary file changed on two branches and merged in Git to
5522
/// one side's version comes back as that version at the merge, and the
5523
/// import verifies commit by commit.
5524
#[test]
5525
fn git_import_resolves_a_binary_merged_in_git_and_verifies() {
5526
    hermetic();
5527
    if std::process::Command::new("git")
5528
        .arg("--version")
5529
        .output()
5530
        .is_err()
5531
    {
5532
        eprintln!("git not installed; skipping");
5533
        return;
5534
    }
5535
    let dir = tempfile::tempdir().unwrap();
5536
    let root = dir.path();
5537
    let g = root.join("src.git");
5538
    fs::create_dir_all(&g).unwrap();
5539
    let git = |args: &[&str]| -> String {
5540
        let out = std::process::Command::new("git")
5541
            .arg("-C")
5542
            .arg(&g)
5543
            .args([
5544
                "-c",
5545
                "user.name=Grace",
5546
                "-c",
5547
                "[email protected]",
5548
                "-c",
5549
                "commit.gpgsign=false",
5550
            ])
5551
            .args(args)
5552
            .output()
5553
            .unwrap();
5554
        assert!(
5555
            out.status.success(),
5556
            "git {args:?}: {}",
5557
            String::from_utf8_lossy(&out.stderr)
5558
        );
5559
        String::from_utf8_lossy(&out.stdout).trim().to_string()
5560
    };
5561
    git(&["init", "-q", "-b", "main"]);
5562
    write(&g, "logo.bin", b"\0base");
5563
    write(&g, "notes.txt", b"a\nb\nc\n");
5564
    git(&["add", "."]);
5565
    git(&["commit", "-qm", "base"]);
5566
    git(&["checkout", "-qb", "side"]);
5567
    write(&g, "logo.bin", b"\0side");
5568
    write(&g, "notes.txt", b"a\nb\nx\nc\n");
5569
    git(&["commit", "-qam", "side"]);
5570
    git(&["checkout", "-q", "main"]);
5571
    write(&g, "logo.bin", b"\0main");
5572
    git(&["commit", "-qam", "main"]);
5573
    // Git cannot merge the binary; the merge takes main's and keeps side's text.
5574
    let _ = std::process::Command::new("git")
5575
        .arg("-C")
5576
        .arg(&g)
5577
        .args([
5578
            "-c",
5579
            "user.name=G",
5580
            "-c",
5581
            "user.email=g@e",
5582
            "merge",
5583
            "-q",
5584
            "side",
5585
        ])
5586
        .output();
5587
    write(&g, "logo.bin", b"\0main");
5588
    git(&["add", "."]);
5589
    git(&["commit", "-qm", "merge side"]);
5590
    // Then a revert of the binary to its first version.
5591
    write(&g, "logo.bin", b"\0base");
5592
    git(&["commit", "-qam", "back to base"]);
5593
5594
    let repo = Repo::init(&root.join("o")).unwrap();
5595
    let rep = repo.import_git(&g, "main").unwrap();
5596
    assert_eq!(rep.merges, 1);
5597
    let v = repo.verify_git_import(&g, "main").unwrap();
5598
    assert!(v.mismatches.is_empty(), "{:?}", v.mismatches);
5599
    assert_eq!(v.commits, 5);
5600
    let snap = repo
5601
        .load_state(&repo.bookmark_heads().unwrap())
5602
        .unwrap()
5603
        .materialize();
5604
    assert!(!snap.is_conflicted());
5605
    let FileContent::Opaque { blobs } = &snap.files["logo.bin"].content else {
5606
        panic!("opaque")
5607
    };
5608
    assert_eq!(repo.read_blob(&blobs[0]).unwrap(), b"\0base");
5609
}
5610
5611
/// Spec §7.7 on a file system without executable bits or symlinks: the
5612
/// recorded bit is kept, and a symlink checked out as a plain file holding
5613
/// its target is still that symlink.
5614
#[cfg(unix)]
5615
#[test]
5616
fn windows_file_systems_keep_exec_bits_and_symlinks() {
5617
    use crate::portable::Platform;
5618
    use std::os::unix::fs::PermissionsExt;
5619
    hermetic();
5620
    let dir = tempfile::tempdir().unwrap();
5621
    let root = dir.path();
5622
    let repo = Repo::init(root).unwrap();
5623
    write(root, "run.sh", b"#!/bin/sh\n");
5624
    fs::set_permissions(root.join("run.sh"), fs::Permissions::from_mode(0o755)).unwrap();
5625
    std::os::unix::fs::symlink("run.sh", root.join("link")).unwrap();
5626
    repo.commit("script and link", &[]).unwrap();
5627
    drop(repo);
5628
5629
    // What checking out on Windows leaves: no exec bit, the link as a file.
5630
    fs::set_permissions(root.join("run.sh"), fs::Permissions::from_mode(0o644)).unwrap();
5631
    fs::remove_file(root.join("link")).unwrap();
5632
    write(root, "link", b"run.sh");
5633
    let win = Repo::open(root).unwrap().with_platform(Platform::windows());
5634
    let s = win.snapshot("oxy status").unwrap();
5635
    assert!(
5636
        s.statuses.is_empty(),
5637
        "nothing changed on Windows: {:?}",
5638
        statuses(&s)
5639
    );
5640
    // Editing the file is a content change, not a mode change; retargeting the link keeps it a link.
5641
    write(root, "run.sh", b"#!/bin/sh\necho hi\n");
5642
    write(root, "link", b"other");
5643
    let h = win.commit("edit on Windows", &[]).unwrap();
5644
    let snap = win.load_state(&[h]).unwrap().materialize();
5645
    assert!(snap.files["run.sh"].mode.exec, "the exec bit survives");
5646
    assert_eq!(snap.files["link"].kind, NodeKind::Symlink);
5647
    // The same working copy read as Linux sees the lost bit and the plain file.
5648
    let linux = Repo::open(root).unwrap();
5649
    assert!(!linux.snapshot("oxy status").unwrap().statuses.is_empty());
5650
}
5651
5652
/// Paths that collide on case-insensitive or Windows file systems are
5653
/// named at checkout there, and by doctor everywhere.
5654
#[test]
5655
fn paths_other_platforms_cannot_hold_are_reported() {
5656
    use crate::portable::Platform;
5657
    hermetic();
5658
    let dir = tempfile::tempdir().unwrap();
5659
    let root = dir.path();
5660
    let repo = Repo::init(root).unwrap();
5661
    write(root, "README.md", b"a\n");
5662
    write(root, "readme.md", b"b\n");
5663
    write(root, "src/aux.c", b"int x;\n");
5664
    let h = repo.commit("unportable", &[]).unwrap();
5665
    let r = repo.doctor(false);
5666
    let port = r.checks.iter().find(|c| c.area == "portability").unwrap();
5667
    assert_eq!(port.health, Health::Warn);
5668
    assert!(
5669
        port.message.contains("differ only in case") && port.message.contains("aux.c"),
5670
        "{}",
5671
        port.message
5672
    );
5673
    let mac = Repo::open(root).unwrap().with_platform(Platform::macos());
5674
    let rep = mac.checkout(&[h], true, "oxy checkout").unwrap();
5675
    assert!(
5676
        rep.notes
5677
            .iter()
5678
            .any(|n| n.contains("README.md and readme.md")),
5679
        "{:?}",
5680
        rep.notes
5681
    );
5682
    assert!(
5683
        !rep.notes.iter().any(|n| n.contains("aux.c")),
5684
        "macOS allows aux.c"
5685
    );
5686
}
5687
5688
#[test]
5689
fn history_and_blame_of_a_loaded_state_match_the_full_walk() {
5690
    hermetic();
5691
    let dir = tempfile::tempdir().unwrap();
5692
    let repo = Repo::init(dir.path()).unwrap();
5693
    write(dir.path(), "a.txt", b"one\n");
5694
    write(dir.path(), "other.txt", b"x\n");
5695
    write(dir.path(), "bin.dat", &[0u8, 1, 2, 0, 255]);
5696
    repo.snapshot("t").unwrap();
5697
    let c1 = repo.commit("first", &[]).unwrap();
5698
    write(dir.path(), "other.txt", b"y\n");
5699
    repo.snapshot("t").unwrap();
5700
    repo.commit("other only", &[]).unwrap();
5701
    write(dir.path(), "a.txt", b"one\ntwo\n");
5702
    repo.snapshot("t").unwrap();
5703
    let c3 = repo.commit("second line", &[]).unwrap();
5704
    write(dir.path(), "other.txt", b"z\n");
5705
    repo.snapshot("t").unwrap();
5706
    repo.commit("other again", &[]).unwrap();
5707
5708
    let heads = repo.bookmark_heads().unwrap();
5709
    let state = repo.load_state(&heads).unwrap();
5710
    let full: Vec<ChangeHash> = repo
5711
        .log_for_path_in("a.txt", &heads)
5712
        .unwrap()
5713
        .iter()
5714
        .map(|e| e.hash)
5715
        .collect();
5716
    assert_eq!(
5717
        full,
5718
        vec![c3, c1],
5719
        "newest first, only changes touching the path"
5720
    );
5721
    let newest: Vec<ChangeHash> = repo
5722
        .log_for_path_of(&state, "a.txt", Some(1))
5723
        .unwrap()
5724
        .iter()
5725
        .map(|e| e.hash)
5726
        .collect();
5727
    assert_eq!(newest, vec![c3], "stops at the first");
5728
    assert_eq!(
5729
        repo.log_for_path_of(&state, "a.txt", None).unwrap().len(),
5730
        2
5731
    );
5732
    assert!(repo
5733
        .log_for_path_of(&state, "missing.txt", Some(1))
5734
        .is_err());
5735
    assert_eq!(
5736
        repo.log_state(&heads).unwrap().len(),
5737
        repo.log_of(&state).len()
5738
    );
5739
5740
    let tree = state.tree().view();
5741
    let via_state = repo.blame_of(&state, &tree, "a.txt").unwrap();
5742
    let via_heads = repo.blame_in("a.txt", &heads).unwrap();
5743
    assert_eq!(
5744
        via_state
5745
            .iter()
5746
            .map(|l| (l.hash, l.text.clone()))
5747
            .collect::<Vec<_>>(),
5748
        via_heads
5749
            .iter()
5750
            .map(|l| (l.hash, l.text.clone()))
5751
            .collect::<Vec<_>>()
5752
    );
5753
    assert_eq!(
5754
        via_state.iter().map(|l| l.hash).collect::<Vec<_>>(),
5755
        vec![c1, c3]
5756
    );
5757
    assert!(repo.blame_of(&state, &tree, "missing.txt").is_err());
5758
}
5759
5760
/// A text file whose stat matches the manifest and whose recorded hash is
5761
/// the base's content is taken from the base without reading it; anything
5762
/// else is read, so no edit is missed (spec §12.3).
5763
#[cfg(unix)]
5764
#[test]
5765
fn stat_cache_takes_unchanged_text_from_the_base_and_misses_no_edit() {
5766
    use std::os::unix::fs::PermissionsExt;
5767
    hermetic();
5768
    let dir = tempfile::tempdir().unwrap();
5769
    let root = dir.path();
5770
    let repo = Repo::init(root).unwrap().with_home(root.join("home"));
5771
    write(root, "a.txt", b"one\ntwo\n");
5772
    write(root, "b.txt", b"bee\n");
5773
    repo.commit("base", &[]).unwrap();
5774
    let age = |p: &str| {
5775
        let old = std::time::SystemTime::now() - std::time::Duration::from_secs(30);
5776
        fs::File::options()
5777
            .write(true)
5778
            .open(root.join(p))
5779
            .unwrap()
5780
            .set_modified(old)
5781
            .unwrap();
5782
    };
5783
    age("a.txt");
5784
    age("b.txt");
5785
    assert!(
5786
        !repo.snapshot("status").unwrap().changed,
5787
        "records the aged stat"
5788
    );
5789
5790
    // Clean and equal to the base: not read at all.
5791
    fs::set_permissions(root.join("a.txt"), fs::Permissions::from_mode(0o000)).unwrap();
5792
    let snap = repo.snapshot("status").unwrap();
5793
    assert!(
5794
        !snap.changed && snap.statuses.is_empty(),
5795
        "{:?}",
5796
        snap.statuses
5797
    );
5798
    fs::set_permissions(root.join("a.txt"), fs::Permissions::from_mode(0o644)).unwrap();
5799
5800
    // An uncommitted edit that is older than the manifest: stat-clean, but
5801
    // its hash is not the base's, so it is read and stays visible.
5802
    write(root, "b.txt", b"bee edited\n");
5803
    age("b.txt");
5804
    let first = repo.snapshot("status").unwrap();
5805
    assert_eq!(
5806
        statuses(&first),
5807
        vec![("b.txt".to_string(), ChangeStatus::Modified)]
5808
    );
5809
    let again = repo.snapshot("status").unwrap();
5810
    assert_eq!(
5811
        statuses(&again),
5812
        vec![("b.txt".to_string(), ChangeStatus::Modified)],
5813
        "still seen once stat-clean"
5814
    );
5815
    assert!(!again.changed, "and the working copy hashes the same");
5816
    fs::set_permissions(root.join("b.txt"), fs::Permissions::from_mode(0o000)).unwrap();
5817
    assert!(
5818
        repo.snapshot("status").is_err(),
5819
        "an edited file must be read, never taken from the base"
5820
    );
5821
    fs::set_permissions(root.join("b.txt"), fs::Permissions::from_mode(0o644)).unwrap();
5822
5823
    // A same-size edit made just now is racy and read.
5824
    write(root, "a.txt", b"one\nTWO\n");
5825
    assert_eq!(
5826
        statuses(&repo.snapshot("status").unwrap()),
5827
        vec![
5828
            ("a.txt".to_string(), ChangeStatus::Modified),
5829
            ("b.txt".to_string(), ChangeStatus::Modified)
5830
        ]
5831
    );
5832
    // Committing makes the edits the base: both are clean and served from it again.
5833
    repo.commit("edits", &[]).unwrap();
5834
    age("a.txt");
5835
    age("b.txt");
5836
    assert!(repo.snapshot("status").unwrap().statuses.is_empty());
5837
    fs::set_permissions(root.join("a.txt"), fs::Permissions::from_mode(0o000)).unwrap();
5838
    fs::set_permissions(root.join("b.txt"), fs::Permissions::from_mode(0o000)).unwrap();
5839
    let snap = repo.snapshot("status").unwrap();
5840
    assert!(!snap.changed && snap.statuses.is_empty());
5841
    fs::set_permissions(root.join("a.txt"), fs::Permissions::from_mode(0o644)).unwrap();
5842
    fs::set_permissions(root.join("b.txt"), fs::Permissions::from_mode(0o644)).unwrap();
5843
}
5844
5845
/// Version 2 checkpoints (spec §11): a large file's graph is a blob of its
5846
/// own, kept by gc, checked by fsck, shared by the next checkpoint when the
5847
/// file is unchanged, and loading through the checkpoint equals a full load.
5848
#[test]
5849
fn checkpoints_keep_large_graphs_as_blobs_of_their_own() {
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
    let long: String = (0..300)
5855
        .map(|i| format!("line {i} of a long file\n"))
5856
        .collect();
5857
    write(root, "long.txt", long.as_bytes());
5858
    write(root, "short.txt", b"short\n");
5859
    repo.commit("base", &[]).unwrap();
5860
    let (r1, _, _) = repo.checkpoint().unwrap();
5861
    let cp1 = crate::objects::Checkpoint::decode(
5862
        &repo.store().get_typed(&r1, ObjectType::Checkpoint).unwrap(),
5863
    )
5864
    .unwrap();
5865
    let graphs1 = repo.checkpoint_graph_blobs(&cp1).unwrap();
5866
    assert_eq!(graphs1.len(), 1, "only the long file's graph is a blob");
5867
5868
    // gc keeps the graph blob; fsck finds the checkpoint sound.
5869
    repo.gc(true).unwrap();
5870
    assert!(repo.store().has(&graphs1[0]));
5871
    let report = repo.fsck().unwrap();
5872
    assert_eq!(report.errors(), 0, "{:?}", report.problems);
5873
5874
    // Loading through the checkpoint equals a full load.
5875
    write(root, "short.txt", b"short, edited\n");
5876
    repo.commit("edit the short file", &[]).unwrap();
5877
    let heads = repo.bookmark_heads().unwrap();
5878
    let fast = repo.load_state(&heads).unwrap();
5879
    let full = repo.load_state_full(&heads).unwrap();
5880
    assert_eq!(fast.checkpoint_payload(), full.checkpoint_payload());
5881
5882
    // The next checkpoint shares the unchanged long file's graph.
5883
    let (r2, _, _) = repo.checkpoint().unwrap();
5884
    let cp2 = crate::objects::Checkpoint::decode(
5885
        &repo.store().get_typed(&r2, ObjectType::Checkpoint).unwrap(),
5886
    )
5887
    .unwrap();
5888
    assert_eq!(repo.checkpoint_graph_blobs(&cp2).unwrap(), graphs1);
5889
5890
    // A shallow clone's bundle carries the graph blob with the checkpoint.
5891
    let bundle = repo.checkpoint_bundle_for(&heads).unwrap();
5892
    assert!(bundle.objects.iter().any(|(t, body)| *t == ObjectType::Blob
5893
        && crate::hash::hash_object(ObjectType::Blob, body) == graphs1[0]));
5894
5895
    // A version 1 checkpoint written by an older oxy still loads.
5896
    let state = repo.load_state_full(&heads).unwrap();
5897
    let old = repo.store_blob(&state.checkpoint_payload()).unwrap();
5898
    let cp_old = crate::objects::Checkpoint {
5899
        heads: cp2.heads.clone(),
5900
        count: cp2.count,
5901
        payload: old,
5902
    };
5903
    let r_old = repo
5904
        .store()
5905
        .put(ObjectType::Checkpoint, &cp_old.encode())
5906
        .unwrap();
5907
    repo.install_checkpoint("main", &r_old).unwrap();
5908
    assert_eq!(
5909
        repo.load_state(&heads).unwrap().checkpoint_payload(),
5910
        full.checkpoint_payload()
5911
    );
5912
    assert_eq!(repo.fsck().unwrap().errors(), 0);
5913
5914
    // A lost graph blob fails the load loudly rather than dropping the
5915
    // file, and fsck reports it (a fresh repository, objects still loose).
5916
    let dir2 = tempfile::tempdir().unwrap();
5917
    let root2 = dir2.path();
5918
    let repo2 = Repo::init(root2).unwrap().with_home(root2.join("home"));
5919
    write(root2, "long.txt", long.as_bytes());
5920
    repo2.commit("base", &[]).unwrap();
5921
    let (r, _, _) = repo2.checkpoint().unwrap();
5922
    let cp = crate::objects::Checkpoint::decode(
5923
        &repo2.store().get_typed(&r, ObjectType::Checkpoint).unwrap(),
5924
    )
5925
    .unwrap();
5926
    let graph = repo2.checkpoint_graph_blobs(&cp).unwrap()[0];
5927
    repo2.store().remove_loose_for_test(&graph).unwrap();
5928
    assert!(repo2.load_state(&repo2.bookmark_heads().unwrap()).is_err());
5929
    assert!(repo2.fsck().unwrap().errors() > 0, "fsck reports it");
5930
}
5931
5932
/// A new repository has not stored the user's identity yet (that happens
5933
/// at the first signed change); looking it up falls back to the key
5934
/// directory, and a file there that does not hash to the key is refused.
5935
#[test]
5936
fn identity_is_found_in_the_key_directory_for_a_new_repository() {
5937
    hermetic();
5938
    let dir = tempfile::tempdir().unwrap();
5939
    let home = dir.path().join("home");
5940
    let mut first = Repo::init(&dir.path().join("a"))
5941
        .unwrap()
5942
        .with_home(home.clone());
5943
    let (key, _) = first
5944
        .create_identity("Ada", "[email protected]", IdentityScope::User)
5945
        .unwrap();
5946
    let fresh = Repo::init(&dir.path().join("b"))
5947
        .unwrap()
5948
        .with_home(home.clone());
5949
    assert!(!fresh.store().has(&key), "nothing stored yet");
5950
    let id = fresh.identity(&key).unwrap();
5951
    assert_eq!((id.name.as_str(), id.hash()), ("Ada", key));
5952
    // A key file that is not this identity is an error, not a wrong answer.
5953
    let keys = fresh.keys_dir.clone();
5954
    let (other, _) = first
5955
        .create_identity("Bob", "[email protected]", IdentityScope::User)
5956
        .unwrap();
5957
    fs::copy(
5958
        keys.join(format!("{}.identity", other.to_hex())),
5959
        keys.join(format!("{}.identity", key.to_hex())),
5960
    )
5961
    .unwrap();
5962
    assert!(fresh
5963
        .identity(&key)
5964
        .unwrap_err()
5965
        .to_string()
5966
        .contains("does not hold identity"));
5967
}
5968
5969
/// Status snapshots (spec §12.3): a text file whose stat matches the
5970
/// manifest, and whose base graph key is the one the manifest recorded it
5971
/// equal to, is neither read nor rendered; any edit, and any change to the
5972
/// file's graph in the base, brings it back.
5973
#[cfg(unix)]
5974
#[test]
5975
fn status_snapshots_skip_files_unchanged_since_the_manifest() {
5976
    use std::os::unix::fs::PermissionsExt;
5977
    hermetic();
5978
    let dir = tempfile::tempdir().unwrap();
5979
    let root = dir.path();
5980
    let repo = Repo::init(root).unwrap().with_home(root.join("home"));
5981
    for (p, c) in [("a.txt", "one\n"), ("b.txt", "bee\n"), ("d/c.txt", "sea\n")] {
5982
        write(root, p, c.as_bytes());
5983
    }
5984
    repo.commit("base", &[]).unwrap();
5985
    let age = |p: &str| {
5986
        let old = std::time::SystemTime::now() - std::time::Duration::from_secs(30);
5987
        fs::File::options()
5988
            .write(true)
5989
            .open(root.join(p))
5990
            .unwrap()
5991
            .set_modified(old)
5992
            .unwrap();
5993
    };
5994
    let lock = |p: &str, mode: u32| {
5995
        fs::set_permissions(root.join(p), fs::Permissions::from_mode(mode)).unwrap()
5996
    };
5997
    for p in ["a.txt", "b.txt", "d/c.txt"] {
5998
        age(p);
5999
    }
6000
    assert!(repo.snapshot("status").unwrap().statuses.is_empty());
6001
    let (_, _, m) = repo.read_manifest().unwrap().unwrap();
6002
    assert!(
6003
        m.entries.values().all(|e| e.graph.is_some()),
6004
        "keys recorded"
6005
    );
6006
6007
    // Unreadable files prove they are not read; the status snapshot does
6008
    // not render them either, and its base lacks their graphs.
6009
    lock("a.txt", 0o000);
6010
    lock("b.txt", 0o000);
6011
    let snap = repo.snapshot_status("status").unwrap();
6012
    assert!(!snap.changed && snap.statuses.is_empty());
6013
    assert_eq!(
6014
        snap.base_snapshot
6015
            .unrendered
6016
            .iter()
6017
            .cloned()
6018
            .collect::<Vec<_>>(),
6019
        vec!["a.txt", "b.txt", "d/c.txt"]
6020
    );
6021
    assert!(!snap.base.is_full());
6022
    assert!(!snap.base_snapshot.is_conflicted());
6023
    // A full snapshot does not read them either, but renders everything.
6024
    let full = repo.snapshot("status").unwrap();
6025
    assert!(full.statuses.is_empty() && full.base.is_full());
6026
    assert!(full.base_snapshot.unrendered.is_empty());
6027
    assert!(matches!(&full.base_snapshot.files["a.txt"].content,
6028
        FileContent::Text { bytes, .. } if bytes == b"one\n"));
6029
6030
    // An edit is seen; the file is rendered, the others still are not.
6031
    write(root, "d/c.txt", b"sea edited\n");
6032
    let snap = repo.snapshot_status("status").unwrap();
6033
    assert_eq!(
6034
        statuses(&snap),
6035
        vec![("d/c.txt".to_string(), ChangeStatus::Modified)]
6036
    );
6037
    assert!(!snap.base_snapshot.unrendered.contains("d/c.txt"));
6038
    // So is a mode change of an unread file.
6039
    lock("b.txt", 0o100);
6040
    assert_eq!(
6041
        statuses(&repo.snapshot_status("status").unwrap()),
6042
        vec![
6043
            ("b.txt".to_string(), ChangeStatus::ModeChanged),
6044
            ("d/c.txt".to_string(), ChangeStatus::Modified)
6045
        ]
6046
    );
6047
    lock("b.txt", 0o000);
6048
6049
    // Committing c.txt changes its graph in the base, not a.txt's: a.txt
6050
    // stays unread, c.txt is read once and then skipped too.
6051
    repo.commit_selection("edit c", &[], &Selection::Paths(vec!["d/c.txt".into()]))
6052
        .unwrap();
6053
    age("d/c.txt");
6054
    let snap = repo.snapshot_status("status").unwrap();
6055
    assert!(snap.statuses.is_empty(), "{:?}", snap.statuses);
6056
    assert!(snap.base_snapshot.unrendered.contains("a.txt"));
6057
    lock("d/c.txt", 0o000);
6058
    let snap = repo.snapshot_status("status").unwrap();
6059
    assert!(snap.statuses.is_empty());
6060
    assert!(snap.base_snapshot.unrendered.contains("d/c.txt"));
6061
    for p in ["a.txt", "b.txt", "d/c.txt"] {
6062
        lock(p, 0o644);
6063
    }
6064
}
6065
6066
/// Attributes decide how a file compares with the base, so a changed
6067
/// `.oxyattributes` makes every text file be compared again.
6068
#[cfg(unix)]
6069
#[test]
6070
fn a_changed_attributes_file_disables_skipping_unchanged_files() {
6071
    hermetic();
6072
    let dir = tempfile::tempdir().unwrap();
6073
    let root = dir.path();
6074
    let repo = Repo::init(root).unwrap().with_home(root.join("home"));
6075
    write(root, "a.txt", b"crlf\r\n");
6076
    repo.commit("base", &[]).unwrap();
6077
    let old = std::time::SystemTime::now() - std::time::Duration::from_secs(30);
6078
    fs::File::options()
6079
        .write(true)
6080
        .open(root.join("a.txt"))
6081
        .unwrap()
6082
        .set_modified(old)
6083
        .unwrap();
6084
    assert!(repo.snapshot_status("status").unwrap().statuses.is_empty());
6085
    assert!(repo
6086
        .snapshot_status("status")
6087
        .unwrap()
6088
        .base_snapshot
6089
        .unrendered
6090
        .contains("a.txt"));
6091
    // With eol=lf, a.txt as stored no longer equals the base.
6092
    write(root, ".oxyattributes", b"*.txt eol=lf\n");
6093
    let snap = repo.snapshot_status("status").unwrap();
6094
    assert_eq!(
6095
        statuses(&snap),
6096
        vec![
6097
            (".oxyattributes".to_string(), ChangeStatus::Added),
6098
            ("a.txt".to_string(), ChangeStatus::Modified)
6099
        ]
6100
    );
6101
}
6102
6103
/// Bookmarks with `/` in their names: pushing records their
6104
/// attestations, and checkpoints are kept for them, beside `feature`
6105
/// itself.
6106
#[test]
6107
fn bookmarks_with_slashes_push_and_checkpoint() {
6108
    hermetic();
6109
    let dir = tempfile::tempdir().unwrap();
6110
    let root = dir.path();
6111
    let origin = Repo::init(&root.join("origin")).unwrap();
6112
    let url = root.join("origin").to_string_lossy().to_string();
6113
    let mut repo = Repo::clone(&url, &root.join("r"))
6114
        .unwrap()
6115
        .with_home(root.join("home"));
6116
    // With an identity, pushes carry reference attestations: the case
6117
    // that failed, since the attestation is a file named after the bookmark.
6118
    repo.create_identity("Ada", "[email protected]", IdentityScope::Repo)
6119
        .unwrap();
6120
    let r = root.join("r");
6121
    write(&r, "a.txt", b"a\n");
6122
    let h_a = repo.commit("a", &[]).unwrap();
6123
    assert!(repo.push("origin", false).unwrap()[0].ok);
6124
    origin.refresh().unwrap();
6125
    repo.bookmark_create("feature", None).unwrap();
6126
    repo.bookmark_create("feature/x", None).unwrap();
6127
    repo.bookmark_switch("feature/x", false).unwrap();
6128
    write(&r, "b.txt", b"b\n");
6129
    let h_b = repo.commit("b", &[]).unwrap();
6130
    for name in ["feature", "feature/x"] {
6131
        let res = repo.push_bookmark("origin", name, false).unwrap();
6132
        origin.refresh().unwrap();
6133
        assert!(res[0].ok, "{name}: {res:?}");
6134
    }
6135
    assert_eq!(origin.resolve_heads("feature").unwrap(), vec![h_a]);
6136
    assert_eq!(
6137
        origin.resolve_heads("feature/x").unwrap(),
6138
        repo.resolve_heads("feature/x").unwrap()
6139
    );
6140
    assert!(origin.resolve_heads("feature/x").unwrap().contains(&h_b));
6141
    assert!(origin.latest_ref_attest("feature/x").unwrap().is_some());
6142
    assert!(origin.latest_ref_attest("feature").unwrap().is_some());
6143
6144
    // A checkpoint of feature/x is found again when loading its state.
6145
    let (cp, _, _) = repo.checkpoint().unwrap();
6146
    assert_eq!(repo.latest_checkpoint("feature/x").unwrap().unwrap().0, cp);
6147
    assert!(repo.latest_checkpoint("feature").unwrap().is_none());
6148
    let heads = repo.resolve_heads("feature/x").unwrap();
6149
    assert!(repo.load_state_checkpointed(&heads).unwrap().is_some());
6150
}
6151
6152
/// Deleting a bookmark on a remote (spec §16.4): attested like any update,
6153
/// never the remote's own bookmark, and a bookmark created again later is
6154
/// accepted although the deletion's attestation stays the latest.
6155
#[test]
6156
fn bookmarks_are_deleted_on_a_remote() {
6157
    hermetic();
6158
    let dir = tempfile::tempdir().unwrap();
6159
    let root = dir.path();
6160
    let origin = Repo::init(&root.join("origin")).unwrap();
6161
    let url = root.join("origin").to_string_lossy().to_string();
6162
    let mut repo = Repo::clone(&url, &root.join("r"))
6163
        .unwrap()
6164
        .with_home(root.join("home"));
6165
    repo.create_identity("Ada", "[email protected]", IdentityScope::Repo)
6166
        .unwrap();
6167
    let r = root.join("r");
6168
    write(&r, "a.txt", b"a\n");
6169
    repo.commit("a", &[]).unwrap();
6170
    assert!(repo.push("origin", false).unwrap()[0].ok);
6171
    origin.refresh().unwrap();
6172
    repo.bookmark_create("feature/x", None).unwrap();
6173
    assert!(repo.push_bookmark("origin", "feature/x", false).unwrap()[0].ok);
6174
    origin.refresh().unwrap();
6175
    assert!(origin.resolve_heads("feature/x").is_ok());
6176
6177
    let res = repo.push_delete("origin", "feature/x").unwrap();
6178
    origin.refresh().unwrap();
6179
    assert!(res[0].ok, "{res:?}");
6180
    assert!(!origin.view().unwrap().bookmarks.contains_key("feature/x"));
6181
    let (_, att) = origin.latest_ref_attest("feature/x").unwrap().unwrap();
6182
    assert!(
6183
        matches!(att.attest.body, AttestBody::Ref { new_state, .. } if new_state.is_zero()),
6184
        "the deletion is attested"
6185
    );
6186
    assert!(
6187
        repo.view().unwrap().bookmarks.contains_key("feature/x"),
6188
        "the local bookmark stays"
6189
    );
6190
    assert!(!repo
6191
        .view()
6192
        .unwrap()
6193
        .remotes
6194
        .get("origin")
6195
        .is_some_and(|m| m.contains_key("feature/x")));
6196
6197
    // Pushing it again creates it again, past the deletion's serial.
6198
    let res = repo.push_bookmark("origin", "feature/x", false).unwrap();
6199
    origin.refresh().unwrap();
6200
    assert!(res[0].ok, "{res:?}");
6201
    assert!(origin.view().unwrap().bookmarks.contains_key("feature/x"));
6202
6203
    // Nothing to delete, and never the remote's own bookmark.
6204
    assert!(repo.push_delete("origin", "nope").is_err());
6205
    let res = repo.push_delete("origin", "main").unwrap();
6206
    origin.refresh().unwrap();
6207
    assert!(
6208
        !res[0].ok && res[0].reason.contains("default bookmark"),
6209
        "{res:?}"
6210
    );
6211
    assert!(origin.view().unwrap().bookmarks.contains_key("main"));
6212
}
6213
6214
/// `bookmark switch --carry` (spec §10.1): uncommitted work goes along
6215
/// when the target has the same versions of the files it touches, and is
6216
/// refused, untouched, when it has others.
6217
#[test]
6218
fn switching_bookmarks_carries_uncommitted_work() {
6219
    hermetic();
6220
    let dir = tempfile::tempdir().unwrap();
6221
    let root = dir.path();
6222
    let mut repo = Repo::init(root).unwrap().with_home(root.join("home"));
6223
    write(root, "a.txt", b"a\n");
6224
    write(root, "b.txt", b"b\n");
6225
    write(root, "gone.txt", b"gone\n");
6226
    repo.commit("base", &[]).unwrap();
6227
    repo.bookmark_create("feature", None).unwrap();
6228
    // Started on main, belongs on feature: edit, add, remove.
6229
    write(root, "a.txt", b"a\nmore\n");
6230
    write(root, "new.txt", b"new\n");
6231
    fs::remove_file(root.join("gone.txt")).unwrap();
6232
    let (_, carried) = repo.bookmark_switch_carry("feature").unwrap();
6233
    assert_eq!(carried, vec!["a.txt", "gone.txt", "new.txt"]);
6234
    assert_eq!(repo.config.bookmark, "feature");
6235
    assert_eq!(fs::read(root.join("a.txt")).unwrap(), b"a\nmore\n");
6236
    assert_eq!(fs::read(root.join("new.txt")).unwrap(), b"new\n");
6237
    assert!(!root.join("gone.txt").exists());
6238
    let snap = repo.snapshot("status").unwrap();
6239
    assert_eq!(
6240
        statuses(&snap),
6241
        vec![
6242
            ("a.txt".to_string(), ChangeStatus::Modified),
6243
            ("gone.txt".to_string(), ChangeStatus::Removed),
6244
            ("new.txt".to_string(), ChangeStatus::Added)
6245
        ]
6246
    );
6247
    repo.commit("the work", &[]).unwrap();
6248
    assert!(repo.resolve_heads("main").unwrap().len() == 1);
6249
6250
    // main moves b.txt on; work on feature touching b.txt cannot follow.
6251
    repo.bookmark_switch("main", false).unwrap();
6252
    write(root, "b.txt", b"b on main\n");
6253
    repo.commit("b on main", &[]).unwrap();
6254
    repo.bookmark_switch("feature", false).unwrap();
6255
    write(root, "b.txt", b"b edited\n");
6256
    let err = repo.bookmark_switch_carry("main").unwrap_err().to_string();
6257
    assert!(err.contains("b.txt") && err.contains("--discard"), "{err}");
6258
    assert_eq!(repo.config.bookmark, "feature", "nothing happened");
6259
    assert_eq!(fs::read(root.join("b.txt")).unwrap(), b"b edited\n");
6260
}
6261
6262
/// Merging and checking out (feedback 3): a working copy without changes
6263
/// follows a merge whichever state it sat on; a refused checkout names
6264
/// what is in the way; `checkout --carry` takes the work along.
6265
#[test]
6266
fn merges_move_clean_working_copies_and_checkouts_say_what_blocks_them() {
6267
    hermetic();
6268
    let dir = tempfile::tempdir().unwrap();
6269
    let root = dir.path();
6270
    let mut repo = Repo::init(root).unwrap().with_home(root.join("home"));
6271
    write(root, "a.txt", b"a\n");
6272
    let h1 = repo.commit("a", &[]).unwrap();
6273
    write(root, "b.txt", b"b\n");
6274
    repo.commit("b", &[]).unwrap();
6275
    repo.bookmark_create("feature", None).unwrap();
6276
    repo.bookmark_switch("feature", false).unwrap();
6277
    write(root, "c.txt", b"c\n");
6278
    repo.commit("c on feature", &[]).unwrap();
6279
    repo.bookmark_switch("main", false).unwrap();
6280
    // The working copy sits on an older state than main's heads.
6281
    repo.checkout(&[h1], false, "checkout").unwrap();
6282
    assert!(!root.join("b.txt").exists());
6283
    let m = repo.merge("feature").unwrap();
6284
    assert!(m.checked_out, "a clean working copy follows the merge");
6285
    for f in ["a.txt", "b.txt", "c.txt"] {
6286
        assert!(root.join(f).exists(), "{f}");
6287
    }
6288
6289
    // A refusal says which paths are in the way and what to do.
6290
    fs::remove_file(root.join("b.txt")).unwrap();
6291
    write(root, "a.txt", b"a edited\n");
6292
    let err = repo
6293
        .checkout(&[h1], false, "checkout")
6294
        .unwrap_err()
6295
        .to_string();
6296
    assert!(
6297
        err.contains("modified a.txt") && err.contains("removed b.txt") && err.contains("--carry"),
6298
        "{err}"
6299
    );
6300
    // --carry takes them along: h1 has a.txt as the base has it, and the
6301
    // removed b.txt is already as h1 has it (none), so that is no conflict
6302
    // either (oxygen#100).
6303
    let (_, carried) = repo
6304
        .checkout_carry(&[h1], "the first change", "checkout")
6305
        .unwrap();
6306
    assert_eq!(carried, vec!["a.txt"]);
6307
    assert_eq!(fs::read(root.join("a.txt")).unwrap(), b"a edited\n");
6308
    assert!(!root.join("b.txt").exists(), "h1 has no b.txt");
6309
}
6310
6311
/// Doctor and subrepos before the first commit (feedback 5 and 8): a
6312
/// user identity not stored in a new repository yet is fine while its
6313
/// secret key is there; an added subrepo is listed as not committed yet.
6314
#[test]
6315
fn a_new_repository_is_healthy_before_its_first_commit() {
6316
    hermetic();
6317
    let dir = tempfile::tempdir().unwrap();
6318
    let root = dir.path();
6319
    let home = root.join("home");
6320
    let mut first = Repo::init(&root.join("first"))
6321
        .unwrap()
6322
        .with_home(home.clone());
6323
    let (key, _) = first
6324
        .create_identity("Ada", "[email protected]", IdentityScope::User)
6325
        .unwrap();
6326
    let repo = Repo::init(&root.join("second"))
6327
        .unwrap()
6328
        .with_home(home.clone());
6329
    // Only the secret key: no identity object anywhere this repository sees.
6330
    let keys = repo.keys_dir.clone();
6331
    let _ = fs::remove_file(keys.join(format!("{}.identity", key.to_hex())));
6332
    assert!(keys.join(format!("{}.secret", key.to_hex())).is_file());
6333
    let r = repo.doctor(true);
6334
    let id = r.checks.iter().find(|c| c.area == "identity").unwrap();
6335
    assert_eq!(id.health, Health::Ok, "{}", id.message);
6336
    assert!(id.message.contains("first signed change"), "{}", id.message);
6337
6338
    // A subrepo added and not committed yet is listed, pinned where it is.
6339
    let lib = root.join("lib");
6340
    let l = Repo::init(&lib).unwrap().with_home(home.clone());
6341
    write(&lib, "x.txt", b"x\n");
6342
    l.commit("x", &[]).unwrap();
6343
    let second = root.join("second");
6344
    write(&second, "a.txt", b"a\n");
6345
    repo.submodule_add(&lib.to_string_lossy(), "deps/lib", None)
6346
        .unwrap();
6347
    let subs = repo.subrepos().unwrap();
6348
    assert_eq!(subs.len(), 1);
6349
    assert_eq!(
6350
        (subs[0].path.as_str(), subs[0].committed),
6351
        ("deps/lib", false)
6352
    );
6353
    assert_eq!(subs[0].actual.as_ref(), Some(&subs[0].pin));
6354
    repo.commit("add lib", &[]).unwrap();
6355
    let subs = repo.subrepos().unwrap();
6356
    assert!(subs[0].committed, "committed now");
6357
}
6358
6359
/// Commit, diff, hunks and discard use the partial snapshot: a file
6360
/// unchanged since the manifest is neither read nor rendered, and showing
6361
/// a change renders only what it edits, the same as from a full base.
6362
#[cfg(unix)]
6363
#[test]
6364
fn commits_and_diffs_leave_unchanged_files_alone() {
6365
    use std::os::unix::fs::PermissionsExt;
6366
    hermetic();
6367
    let dir = tempfile::tempdir().unwrap();
6368
    let root = dir.path();
6369
    let repo = Repo::init(root).unwrap().with_home(root.join("home"));
6370
    write(root, "big.txt", b"lots\nof\nlines\n");
6371
    write(root, "a.txt", b"one\ntwo\n");
6372
    repo.commit("base", &[]).unwrap();
6373
    let old = std::time::SystemTime::now() - std::time::Duration::from_secs(30);
6374
    for f in ["big.txt", "a.txt"] {
6375
        fs::File::options()
6376
            .write(true)
6377
            .open(root.join(f))
6378
            .unwrap()
6379
            .set_modified(old)
6380
            .unwrap();
6381
    }
6382
    assert!(repo.snapshot_status("status").unwrap().statuses.is_empty());
6383
    // big.txt cannot be read at all from here on.
6384
    fs::set_permissions(root.join("big.txt"), fs::Permissions::from_mode(0o000)).unwrap();
6385
6386
    write(root, "a.txt", b"one\nTWO\nthree\n");
6387
    let diff = repo.diff_files(None).unwrap();
6388
    assert_eq!(
6389
        diff.iter().map(|f| f.path.as_str()).collect::<Vec<_>>(),
6390
        ["a.txt"]
6391
    );
6392
    let (_, hunks) = repo.hunks().unwrap();
6393
    assert!(!hunks.is_empty() && hunks.iter().all(|h| h.path == "a.txt"));
6394
    let h = repo.commit("edit a", &[]).unwrap();
6395
6396
    // Showing the change needs only a.txt's graph, and renders as a full base does.
6397
    let c = repo.store().get_change(&h).unwrap();
6398
    let full = repo.load_state(&c.deps).unwrap();
6399
    let want = render_change(&c, &full, &full.materialize());
6400
    assert_eq!(repo.describe_change(&h).unwrap(), want);
6401
    let (base, snap) = repo.change_base(&c).unwrap();
6402
    assert!(!base.is_full() && snap.unrendered.contains("big.txt"));
6403
6404
    // Discarding works the same way.
6405
    write(root, "a.txt", b"scratch\n");
6406
    assert_eq!(repo.discard(&["a.txt".into()]).unwrap(), 1);
6407
    assert_eq!(fs::read(root.join("a.txt")).unwrap(), b"one\nTWO\nthree\n");
6408
    fs::set_permissions(root.join("big.txt"), fs::Permissions::from_mode(0o644)).unwrap();
6409
}
6410
6411
/// A replace conflict (spec §9.3) is settled by a change that writes one
6412
/// candidate, or new bytes, at the path when the caller names it; a plain
6413
/// snapshot of a checkout never settles it on its own.
6414
#[test]
6415
fn replace_conflicts_are_settled_when_asked() {
6416
    hermetic();
6417
    let dir = tempfile::tempdir().unwrap();
6418
    let root = dir.path();
6419
    let mut repo = Repo::init(root).unwrap().with_home(root.join("home"));
6420
    let blob = |n: u8| {
6421
        let mut v = vec![0u8; 64];
6422
        v[1] = n;
6423
        v
6424
    };
6425
    write(root, "img.bin", &blob(1));
6426
    repo.commit("add img", &[]).unwrap();
6427
    repo.bookmark_create("other", None).unwrap();
6428
    write(root, "img.bin", &blob(2));
6429
    repo.commit("img two", &[]).unwrap();
6430
    repo.bookmark_switch("other", false).unwrap();
6431
    write(root, "img.bin", &blob(3));
6432
    repo.commit("img three", &[]).unwrap();
6433
    repo.bookmark_switch("main", false).unwrap();
6434
    repo.merge("other").unwrap();
6435
    let heads = repo.bookmark_heads().unwrap();
6436
    let merged = repo.load_state(&heads).unwrap().materialize();
6437
    assert!(
6438
        matches!(&merged.files["img.bin"].content, FileContent::Opaque { blobs } if blobs.len() == 2),
6439
        "a replace conflict"
6440
    );
6441
    // A snapshot of the checkout records nothing.
6442
    assert!(repo
6443
        .snapshot("status")
6444
        .unwrap()
6445
        .statuses
6446
        .iter()
6447
        .all(|s| s.path != "img.bin"));
6448
6449
    // Keeping candidate 3 settles it.
6450
    let author = repo.author();
6451
    let edits = [FileEdit {
6452
        path: "img.bin".into(),
6453
        content: Some(blob(3)),
6454
    }];
6455
    let c = repo
6456
        .build_change(&heads, &edits, "keep three", author)
6457
        .unwrap();
6458
    assert_eq!(c.kind, ChangeKind::Resolution);
6459
    let mut st = repo.load_state(&heads).unwrap();
6460
    for d in &c.deps {
6461
        assert!(st.contains(d));
6462
    }
6463
    assert!(
6464
        heads.iter().all(|h| c.deps.contains(h)),
6465
        "depends on both contributors"
6466
    );
6467
    st.add(c).unwrap();
6468
    let after = st.materialize();
6469
    assert!(!after.is_conflicted());
6470
    assert_eq!(
6471
        after.files["img.bin"].content,
6472
        FileContent::Opaque {
6473
            blobs: vec![Repo::blob_ref(&blob(3))]
6474
        }
6475
    );
6476
6477
    // New bytes settle it too.
6478
    let edits = [FileEdit {
6479
        path: "img.bin".into(),
6480
        content: Some(blob(9)),
6481
    }];
6482
    let c = repo.build_change(&heads, &edits, "new", author).unwrap();
6483
    let mut st = repo.load_state(&heads).unwrap();
6484
    st.add(c).unwrap();
6485
    assert_eq!(
6486
        st.materialize().files["img.bin"].content,
6487
        FileContent::Opaque {
6488
            blobs: vec![Repo::blob_ref(&blob(9))]
6489
        }
6490
    );
6491
}
6492
6493
/// The history of a range of lines (spec §27): the changes that wrote
6494
/// or deleted its atoms, or deleted atoms from between them; edits outside
6495
/// the range and changes the range's lines survived are not in it.
6496
#[test]
6497
fn line_ranges_have_exact_histories() {
6498
    hermetic();
6499
    let dir = tempfile::tempdir().unwrap();
6500
    let root = dir.path();
6501
    let repo = Repo::init(root).unwrap().with_home(root.join("home"));
6502
    write(root, "f.rs", b"use x;\nfn a() {\n  one();\n  two();\n}\n");
6503
    let base = repo.commit("add f", &[]).unwrap();
6504
    write(root, "f.rs", b"use y;\nfn a() {\n  one();\n  two();\n}\n");
6505
    let outside = repo.commit("change the import", &[]).unwrap();
6506
    write(root, "f.rs", b"use y;\nfn a() {\n  ONE();\n  two();\n}\n");
6507
    let inside = repo.commit("edit a line of a", &[]).unwrap();
6508
    write(root, "f.rs", b"use y;\nfn a() {\n  ONE();\n}\n");
6509
    let deleted = repo.commit("delete a line of a", &[]).unwrap();
6510
    write(root, "f.rs", b"use y;\nfn a() {\n  ONE();\n}\nfn b() {}\n");
6511
    let after = repo.commit("add b after a", &[]).unwrap();
6512
    let heads = repo.bookmark_heads().unwrap();
6513
6514
    // Lines 2..4 are `fn a() {`, `ONE();`, `}` now.
6515
    let hist: Vec<ChangeHash> = repo
6516
        .line_history(&heads, "f.rs", 2, 4)
6517
        .unwrap()
6518
        .iter()
6519
        .map(|e| e.hash)
6520
        .collect();
6521
    for (h, what) in [
6522
        (base, "wrote it"),
6523
        (inside, "edited a line"),
6524
        (deleted, "deleted a line from inside"),
6525
    ] {
6526
        assert!(hist.contains(&h), "{what}");
6527
    }
6528
    for (h, what) in [(outside, "an edit above"), (after, "an addition below")] {
6529
        assert!(!hist.contains(&h), "{what}");
6530
    }
6531
    assert_eq!(hist[0], deleted, "newest first");
6532
    // One line: only what touched it.
6533
    let one: Vec<ChangeHash> = repo
6534
        .line_history(&heads, "f.rs", 1, 1)
6535
        .unwrap()
6536
        .iter()
6537
        .map(|e| e.hash)
6538
        .collect();
6539
    assert!(one.contains(&outside) && !one.contains(&inside));
6540
    assert!(repo.line_history(&heads, "f.rs", 3, 9).is_err());
6541
    assert!(repo.line_history(&heads, "f.rs", 0, 1).is_err());
6542
    assert!(repo.line_history(&heads, "nope.rs", 1, 1).is_err());
6543
}
6544
6545
#[test]
6546
fn receipts_are_kept_with_their_state_and_verified() {
6547
    use crate::receipt::{Receipt, SignedReceipt};
6548
    hermetic();
6549
    let dir = tempfile::tempdir().unwrap();
6550
    let root = dir.path();
6551
    let repo = Repo::init(root).unwrap().with_home(root.join("home"));
6552
    write(root, "a.txt", b"1\n");
6553
    repo.commit("A", &[]).unwrap();
6554
    let heads = repo.bookmark_heads().unwrap();
6555
    let state = repo
6556
        .store()
6557
        .put_state(&StateObject::new(heads.clone()))
6558
        .unwrap();
6559
    let out = repo.store_blob(b"built\n").unwrap();
6560
    let receipt = Receipt {
6561
        job_name: "build".into(),
6562
        pipeline_hash: ObjectRef([1; 32]),
6563
        scope_tree_hash: ObjectRef([2; 32]),
6564
        inputs: vec![],
6565
        environment: ObjectRef([3; 32]),
6566
        outputs: vec![out],
6567
        exit_code: 0,
6568
        duration_ms: 42,
6569
    };
6570
    let sk = SecretKey::generate();
6571
    let runner = sk.identity("earth-1", "runner@earth", 1);
6572
    let sr = SignedReceipt::sign(
6573
        receipt.clone(),
6574
        repo.id().unwrap(),
6575
        state,
6576
        "demo#1",
6577
        &runner,
6578
        &sk,
6579
    );
6580
6581
    let r = repo.add_receipt(&sr).unwrap();
6582
    let found = repo.receipts(&heads).unwrap();
6583
    assert_eq!(found.len(), 1);
6584
    assert_eq!(found[0].attest, r);
6585
    assert_eq!(found[0].signed, sr);
6586
    assert!(found[0].problem.is_none() && !found[0].revoked);
6587
    assert!(repo.receipts(&[ObjectRef([5; 32])]).unwrap().is_empty());
6588
6589
    // Another repository's receipt, or a forged one, is refused.
6590
    let elsewhere = SignedReceipt::sign(receipt.clone(), [0; 16], state, "x", &runner, &sk);
6591
    assert!(repo
6592
        .add_receipt(&elsewhere)
6593
        .unwrap_err()
6594
        .to_string()
6595
        .contains("another repository"));
6596
    let mut forged = sr.clone();
6597
    forged.receipt.exit_code = 1;
6598
    assert!(repo
6599
        .add_receipt(&forged)
6600
        .unwrap_err()
6601
        .to_string()
6602
        .contains("does not verify"));
6603
6604
    // A receipt signed by a short-lived key keeps its certificate and the
6605
    // issuer's identity, and reads back with them (oxygenhub#241).
6606
    let hub_sk = SecretKey::generate();
6607
    let hub = hub_sk.identity("oxygenhub.io", "[email protected]", 1);
6608
    let job_sk = SecretKey::generate();
6609
    let job = job_sk.identity("job 2 test", "[email protected]", 1);
6610
    let mut test_receipt = receipt.clone();
6611
    test_receipt.job_name = "test".into();
6612
    let plain = SignedReceipt::sign(
6613
        test_receipt,
6614
        repo.id().unwrap(),
6615
        state,
6616
        "demo#2",
6617
        &job,
6618
        &job_sk,
6619
    );
6620
    let now = plain.attest.hlc.wall_ms;
6621
    let cert = crate::cert::SignedCertificate::sign(
6622
        crate::cert::Certificate {
6623
            key: job.clone(),
6624
            issuer: hub.hash(),
6625
            subject: "repo:andy/demo:bookmark:main".into(),
6626
            claims: vec![],
6627
            scope: crate::identity::Scope::SEAL,
6628
            not_before: now - 1_000,
6629
            expires: now + 600_000,
6630
            grant: None,
6631
        },
6632
        &hub,
6633
        &hub_sk,
6634
    );
6635
    let certified = plain.with_certificate(cert, hub.clone());
6636
    repo.add_receipt(&certified).unwrap();
6637
    let found = repo.receipts(&heads).unwrap();
6638
    let got = found
6639
        .iter()
6640
        .find(|i| i.signed.receipt.job_name == "test")
6641
        .unwrap();
6642
    assert_eq!(got.signed, certified);
6643
    assert!(got.problem.is_none(), "{:?}", got.problem);
6644
6645
    // gc keeps the receipts, their runners, the certificate and its issuer,
6646
    // and the output while the state lives.
6647
    repo.gc(true).unwrap();
6648
    let found = repo.receipts(&heads).unwrap();
6649
    assert_eq!(found.len(), 2);
6650
    let got = found
6651
        .iter()
6652
        .find(|i| i.signed.receipt.job_name == "test")
6653
        .unwrap();
6654
    assert_eq!(got.signed, certified, "the certificate survives gc");
6655
    assert!(got.problem.is_none());
6656
    assert_eq!(repo.read_blob(&out).unwrap(), b"built\n");
6657
    assert!(repo.fsck().unwrap().problems.is_empty());
6658
}
6659
6660
#[test]
6661
fn approvals_are_kept_with_their_state_and_survive_gc() {
6662
    hermetic();
6663
    let dir = tempfile::tempdir().unwrap();
6664
    let root = dir.path();
6665
    let repo = Repo::init(root).unwrap().with_home(root.join("home"));
6666
    write(root, "a.txt", b"1\n");
6667
    repo.commit("A", &[]).unwrap();
6668
    let heads = repo.bookmark_heads().unwrap();
6669
    let state = repo.store().put_state(&StateObject::new(heads)).unwrap();
6670
    let plan = repo.store_blob(b"the reviewed plan\n").unwrap();
6671
    let sk = SecretKey::generate();
6672
    let andy = sk.identity("Andy", "[email protected]", 1);
6673
    let statement = crate::approval::Statement {
6674
        repo: repo.id().unwrap(),
6675
        run: "https://hub.example/andy/infra/flow/8".into(),
6676
        job: "apply".into(),
6677
        job_hash: ObjectRef([1; 32]),
6678
        state,
6679
        inputs: vec![plan],
6680
        environment: "prod".into(),
6681
        approve: true,
6682
    };
6683
    let sa = crate::approval::SignedApproval::sign(&statement, &andy, &sk);
6684
    let r = repo.add_approval(&sa).unwrap();
6685
    assert_eq!(repo.store().approvals_for(&state).unwrap(), vec![r]);
6686
    // Another repository's approval, or a changed one, is refused.
6687
    let elsewhere = crate::approval::SignedApproval::sign(
6688
        &crate::approval::Statement {
6689
            repo: [0; 16],
6690
            ..statement.clone()
6691
        },
6692
        &andy,
6693
        &sk,
6694
    );
6695
    assert!(repo
6696
        .add_approval(&elsewhere)
6697
        .unwrap_err()
6698
        .to_string()
6699
        .contains("another repository"));
6700
    let mut forged = sa.clone();
6701
    if let AttestBody::Approval { environment, .. } = &mut forged.attest.body {
6702
        *environment = "dev".into();
6703
    }
6704
    assert!(repo
6705
        .add_approval(&forged)
6706
        .unwrap_err()
6707
        .to_string()
6708
        .contains("does not verify"));
6709
    // gc keeps it, its signature and its signer while the state lives.
6710
    repo.gc(true).unwrap();
6711
    assert_eq!(repo.store().approvals_for(&state).unwrap(), vec![r]);
6712
    assert_eq!(repo.store().get_attest(&r).unwrap(), sa.attest);
6713
    assert_eq!(repo.store().signatures(&r).unwrap(), sa.sigs);
6714
    assert!(repo.fsck().unwrap().problems.is_empty());
6715
}
6716
6717
#[test]
6718
fn status_leaves_an_unchanged_manifest_alone() {
6719
    hermetic();
6720
    let dir = tempfile::tempdir().unwrap();
6721
    let root = dir.path();
6722
    let repo = Repo::init(root).unwrap().with_home(root.join("home"));
6723
    write(root, "a.txt", b"1\n");
6724
    write(root, "b.txt", b"2\n");
6725
    repo.commit("A", &[]).unwrap();
6726
    // Files last touched well outside the racy window.
6727
    let old = std::time::SystemTime::now() - std::time::Duration::from_secs(60);
6728
    for f in ["a.txt", "b.txt"] {
6729
        fs::File::options()
6730
            .write(true)
6731
            .open(root.join(f))
6732
            .unwrap()
6733
            .set_modified(old)
6734
            .unwrap();
6735
    }
6736
    repo.snapshot_status("status").unwrap();
6737
    let path = repo.manifest_path();
6738
    let first = fs::read(&path).unwrap();
6739
    repo.snapshot_status("status").unwrap();
6740
    assert_eq!(
6741
        fs::read(&path).unwrap(),
6742
        first,
6743
        "an unchanged tree does not rewrite the manifest"
6744
    );
6745
    // A change rewrites it.
6746
    write(root, "a.txt", b"1\n2\n");
6747
    repo.snapshot_status("status").unwrap();
6748
    assert_ne!(fs::read(&path).unwrap(), first);
6749
}
6750
6751
#[test]
6752
fn large_text_files_travel_and_survive_gc_as_text_blobs() {
6753
    hermetic();
6754
    let dir = tempfile::tempdir().unwrap();
6755
    let root = dir.path();
6756
    let origin_path = root.join("origin");
6757
    Repo::init(&origin_path).unwrap();
6758
    let origin_url = origin_path.to_string_lossy().to_string();
6759
    let a = Repo::clone(&origin_url, &root.join("a")).unwrap();
6760
    let big: String = (0..5000).map(|i| format!("line {i}\n")).collect();
6761
    write(&root.join("a"), "big.txt", big.as_bytes());
6762
    write(&root.join("a"), "small.txt", b"small\n");
6763
    let h1 = a.commit("large", &[]).unwrap();
6764
    let (_, body) = a.store().get(&h1).unwrap();
6765
    assert!(body.len() < 2048, "the change is {} bytes", body.len());
6766
    assert!(a.push("origin", false).unwrap()[0].ok);
6767
6768
    // A clone reads the text from the blobs that came with the change.
6769
    let b = Repo::clone(&origin_url, &root.join("b")).unwrap();
6770
    assert_eq!(fs::read(root.join("b/big.txt")).unwrap(), big.as_bytes());
6771
    // An edit in the middle of the stored insert is an ordinary change.
6772
    let edited = big.replace("line 2500\n", "line 2500, edited\n");
6773
    write(&root.join("b"), "big.txt", edited.as_bytes());
6774
    let h2 = b.commit("edit", &[]).unwrap();
6775
    assert!(b.store().get_change(&h2).unwrap().edits.len() <= 2);
6776
    assert!(b.push("origin", false).unwrap()[0].ok);
6777
    assert!(a.pull("origin").unwrap().checked_out);
6778
    assert_eq!(fs::read(root.join("a/big.txt")).unwrap(), edited.as_bytes());
6779
    assert_eq!(
6780
        a.fsck().unwrap().errors(),
6781
        0,
6782
        "{:?}",
6783
        a.fsck().unwrap().problems
6784
    );
6785
6786
    // With zero retention gc keeps the text blobs of every kept change.
6787
    let mut a = Repo::open(&root.join("a")).unwrap();
6788
    a.config.set("core.op-retention", "0").unwrap();
6789
    a.save_config().unwrap();
6790
    let a = Repo::open(&root.join("a")).unwrap();
6791
    a.gc(true).unwrap();
6792
    let a = Repo::open(&root.join("a")).unwrap();
6793
    assert_eq!(a.store().get_change(&h1).unwrap().message, "large");
6794
    assert_eq!(
6795
        a.fsck().unwrap().errors(),
6796
        0,
6797
        "{:?}",
6798
        a.fsck().unwrap().problems
6799
    );
6800
    // And a clone of the packed repository reads them from its packs.
6801
    let c = Repo::clone(&root.join("a").to_string_lossy(), &root.join("c")).unwrap();
6802
    assert_eq!(fs::read(root.join("c/big.txt")).unwrap(), edited.as_bytes());
6803
    drop(c);
6804
}
6805
6806
#[test]
6807
fn operations_that_both_replace_a_working_copy_are_not_merged() {
6808
    hermetic();
6809
    let dir = tempfile::tempdir().unwrap();
6810
    let root = dir.path();
6811
    let repo = Repo::init(root).unwrap();
6812
    write(root, "a.txt", b"a\n");
6813
    let a = repo.commit("a", &[]).unwrap();
6814
    write(root, "b.txt", b"b\n");
6815
    repo.commit("b", &[]).unwrap();
6816
    let (x, op) = repo.head_op().unwrap();
6817
    let ws = *op.view.workspaces.keys().next().unwrap();
6818
    let mut one = op.view.clone();
6819
    one.workspaces.insert(ws, a);
6820
    let mut two = op.view.clone();
6821
    two.workspaces.insert(ws, ObjectRef([7; 32]));
6822
    let first = repo.record_op(&[x], "one", one).unwrap();
6823
    let e = repo.record_op(&[x], "two", two).unwrap_err();
6824
    assert!(
6825
        e.to_string()
6826
            .contains("changed this working copy at the same time"),
6827
        "{e}"
6828
    );
6829
    assert_eq!(
6830
        repo.head_op().unwrap().0,
6831
        first,
6832
        "the second is not recorded"
6833
    );
6834
}
6835
6836
/// Metalgear, 2026-09-29 (oxygen#36): a status run while a bookmark switch
6837
/// rewrote the working copy recorded the half-written files as edits, and
6838
/// its view replaced the switch's.
6839
#[test]
6840
fn a_snapshot_during_a_switch_never_records_the_switch_as_edits() {
6841
    hermetic();
6842
    let dir = tempfile::tempdir().unwrap();
6843
    let root = dir.path().to_path_buf();
6844
    let mut repo = Repo::init(&root).unwrap();
6845
    write(&root, "keep.txt", b"keep\n");
6846
    repo.commit("base", &[]).unwrap();
6847
    repo.bookmark_create("small", None).unwrap();
6848
    for i in 0..300 {
6849
        write(
6850
            &root,
6851
            &format!("many/f{i}.txt"),
6852
            format!("file {i}\n").as_bytes(),
6853
        );
6854
    }
6855
    repo.commit("many", &[]).unwrap();
6856
    let stop = std::sync::Arc::new(std::sync::atomic::AtomicBool::new(false));
6857
    let watcher = {
6858
        let (root, stop) = (root.clone(), stop.clone());
6859
        std::thread::spawn(move || {
6860
            let r = Repo::open(&root).unwrap();
6861
            let mut ran = 0;
6862
            while !stop.load(std::sync::atomic::Ordering::Relaxed) {
6863
                if r.snapshot_status("oxy status").is_ok() {
6864
                    ran += 1;
6865
                }
6866
            }
6867
            ran
6868
        })
6869
    };
6870
    for i in 0..20 {
6871
        let to = if i % 2 == 0 { "small" } else { "main" };
6872
        repo.bookmark_switch(to, false).unwrap();
6873
    }
6874
    stop.store(true, std::sync::atomic::Ordering::Relaxed);
6875
    assert!(watcher.join().unwrap() > 0, "the watcher snapshotted");
6876
    // Back on main, clean, with every file where main has it.
6877
    let repo = Repo::open(&root).unwrap();
6878
    let s = repo.snapshot_status("oxy status").unwrap();
6879
    assert!(s.statuses.is_empty(), "{:?}", statuses(&s));
6880
    assert!(s.wc.edits.is_empty() && s.wc.tree_ops.is_empty());
6881
    assert_eq!(s.wc.deps, repo.bookmark_heads().unwrap());
6882
    assert!(root.join("many/f299.txt").exists());
6883
}
6884
6885
/// Metalgear, 2026-09-29 (oxygen#38): a parent's `bookmark switch --carry`
6886
/// put a subrepo that was ahead of its pin back at the pin and moved the
6887
/// subrepo's own bookmark backwards.
6888
#[test]
6889
fn a_parent_switch_with_carry_leaves_a_subrepo_ahead_of_its_pin_alone() {
6890
    hermetic();
6891
    let dir = tempfile::tempdir().unwrap();
6892
    let root = dir.path();
6893
    Repo::init(&root.join("lib-origin")).unwrap();
6894
    let lib_url = root.join("lib-origin").to_string_lossy().to_string();
6895
    let lib = Repo::clone(&lib_url, &root.join("lib")).unwrap();
6896
    write(&root.join("lib"), "lib.txt", b"v1\n");
6897
    lib.commit("lib v1", &[]).unwrap();
6898
    assert!(lib.push("origin", false).unwrap()[0].ok);
6899
6900
    let app_dir = root.join("app");
6901
    let mut app = Repo::init(&app_dir).unwrap();
6902
    write(&app_dir, "main.txt", b"app\n");
6903
    app.submodule_add(&lib_url, "libs/lib", None).unwrap();
6904
    app.commit("app with lib", &[]).unwrap();
6905
    app.bookmark_create("feature", None).unwrap();
6906
6907
    // New work in the subrepo, not yet pinned by the parent.
6908
    let nested_dir = app_dir.join("libs/lib");
6909
    let nested = Repo::open(&nested_dir).unwrap();
6910
    write(&nested_dir, "new.txt", b"new\n");
6911
    let l2 = nested.commit("lib: new file", &[]).unwrap();
6912
    drop(nested);
6913
6914
    let (_, carried) = app.bookmark_switch_carry("feature").unwrap();
6915
    assert!(carried.contains(&"libs/lib".to_string()), "{carried:?}");
6916
    let nested = Repo::open(&nested_dir).unwrap();
6917
    assert!(
6918
        nested.bookmark_heads().unwrap().contains(&l2),
6919
        "its bookmark kept its work"
6920
    );
6921
    assert!(nested_dir.join("new.txt").exists(), "and its files");
6922
    let s = app.snapshot("status").unwrap();
6923
    assert_eq!(
6924
        statuses(&s),
6925
        vec![("libs/lib".to_string(), ChangeStatus::Modified)]
6926
    );
6927
}
6928
6929
/// oxygen#29 (metalgear, rstar-api): after a proposal landed on the hub,
6930
/// moving `main` to a change this clone had pushed on another bookmark,
6931
/// the first `pull` said "Already up to date" while `main` was behind.
6932
#[test]
6933
fn pull_takes_a_remote_move_to_changes_already_here() {
6934
    hermetic();
6935
    let dir = tempfile::tempdir().unwrap();
6936
    let root = dir.path();
6937
    let origin_path = root.join("origin");
6938
    let origin = Repo::init(&origin_path).unwrap();
6939
    let url = origin_path.to_string_lossy().to_string();
6940
    let mut b = Repo::clone(&url, &root.join("b")).unwrap();
6941
    write(&root.join("b"), "base.txt", b"base\n");
6942
    b.commit("base", &[]).unwrap();
6943
    assert!(b.push("origin", false).unwrap()[0].ok);
6944
    origin.refresh().unwrap();
6945
6946
    // A feature bookmark with one change, pushed.
6947
    b.bookmark_create("feat", None).unwrap();
6948
    b.bookmark_switch("feat", false).unwrap();
6949
    write(&root.join("b"), "x.txt", b"x\n");
6950
    let x = b.commit("x", &[]).unwrap();
6951
    assert!(b.push("origin", false).unwrap()[0].ok);
6952
    origin.refresh().unwrap();
6953
    b.bookmark_switch("main", false).unwrap();
6954
6955
    // The remote lands it: its main moves to the feature's state.
6956
    let feat = origin
6957
        .store()
6958
        .get_state(&origin.view().unwrap().bookmarks["feat"])
6959
        .unwrap()
6960
        .heads;
6961
    origin.bookmark_set("main", &feat).unwrap();
6962
6963
    let r = b.pull("origin").unwrap();
6964
    assert!(r.changed, "{r:?}");
6965
    assert!(r.heads.contains(&x) || b.load_state(&r.heads).unwrap().contains(&x));
6966
    let main = b
6967
        .bookmarks()
6968
        .unwrap()
6969
        .into_iter()
6970
        .find(|m| m.name == "main")
6971
        .unwrap();
6972
    assert_eq!(main.behind, Some(0), "{main:?}");
6973
}
6974
6975
/// oxygen#48: a remote's bookmarks are names here (`origin/NAME`); switching
6976
/// to one only the remote has makes a local bookmark from it; a pull moves
6977
/// every local bookmark the remote has too; a clone checks out the remote's
6978
/// default bookmark.
6979
#[test]
6980
fn remote_bookmarks_are_named_switched_to_pulled_and_cloned() {
6981
    hermetic();
6982
    let dir = tempfile::tempdir().unwrap();
6983
    let root = dir.path();
6984
    let origin_path = root.join("origin");
6985
    let mut origin = Repo::init(&origin_path).unwrap();
6986
    let url = origin_path.to_string_lossy().to_string();
6987
    let mut a = Repo::clone(&url, &root.join("a")).unwrap();
6988
    write(&root.join("a"), "base.txt", b"base\n");
6989
    a.commit("base", &[]).unwrap();
6990
    assert!(a.push("origin", false).unwrap()[0].ok);
6991
    a.bookmark_create("develop", None).unwrap();
6992
    a.bookmark_switch("develop", false).unwrap();
6993
    write(&root.join("a"), "base.txt", b"base\nd1\n");
6994
    let d1 = a.commit("d1", &[]).unwrap();
6995
    assert!(a.push("origin", false).unwrap()[0].ok);
6996
6997
    // A clone has main only; origin/develop is a name all the same.
6998
    let c_root = root.join("c");
6999
    let mut c = Repo::clone(&url, &c_root).unwrap();
7000
    assert_eq!(c.config.bookmark, "main");
7001
    assert!(!c.view().unwrap().bookmarks.contains_key("develop"));
7002
    assert_eq!(c.resolve_heads("origin/develop").unwrap(), vec![d1]);
7003
    assert_eq!(c.resolve_change("origin/develop").unwrap(), d1);
7004
    assert_eq!(c.remote_only_bookmarks().unwrap().len(), 1);
7005
7006
    // Switching makes the local bookmark from origin's.
7007
    c.bookmark_switch("develop", false).unwrap();
7008
    assert_eq!(c.config.bookmark, "develop");
7009
    assert_eq!(c.bookmark_heads().unwrap(), vec![d1]);
7010
    assert_eq!(fs::read(c_root.join("base.txt")).unwrap(), b"base\nd1\n");
7011
    assert!(c.remote_only_bookmarks().unwrap().is_empty());
7012
    assert!(c.bookmark_switch("nowhere", false).is_err());
7013
7014
    // Both bookmarks move on the remote; one pull takes both.
7015
    write(&root.join("a"), "base.txt", b"base\nd1\nd2\n");
7016
    let d2 = a.commit("d2", &[]).unwrap();
7017
    assert!(a.push("origin", false).unwrap()[0].ok);
7018
    a.bookmark_switch("main", false).unwrap();
7019
    write(&root.join("a"), "m.txt", b"m\n");
7020
    let m = a.commit("m", &[]).unwrap();
7021
    assert!(a.push("origin", false).unwrap()[0].ok);
7022
    let r = c.pull("origin").unwrap();
7023
    assert!(r.changed && r.checked_out, "{r:?}");
7024
    assert_eq!(r.heads, vec![d2]);
7025
    assert_eq!(r.others, vec!["main".to_string()]);
7026
    assert!(c.resolve_heads("main").unwrap().contains(&m));
7027
    assert_eq!(
7028
        fs::read(c_root.join("base.txt")).unwrap(),
7029
        b"base\nd1\nd2\n"
7030
    );
7031
    let again = c.pull("origin").unwrap();
7032
    assert!(!again.changed && again.others.is_empty(), "{again:?}");
7033
7034
    // A clone checks out the remote's default bookmark.
7035
    origin.config.set("workspace.bookmark", "develop").unwrap();
7036
    origin.save_config().unwrap();
7037
    let e = Repo::clone(&url, &root.join("e")).unwrap();
7038
    assert_eq!(e.config.bookmark, "develop");
7039
    assert_eq!(e.bookmark_heads().unwrap(), vec![d2]);
7040
    let reopened = Repo::open(&root.join("e")).unwrap();
7041
    assert_eq!(reopened.config.bookmark, "develop");
7042
    // REMOTE/NAME names the remote's bookmark to switch to.
7043
    let mut e = reopened;
7044
    e.bookmark_switch("origin/main", false).unwrap();
7045
    assert_eq!(e.config.bookmark, "main");
7046
    assert!(e.bookmark_heads().unwrap().contains(&m));
7047
}
7048
7049
/// oxygen#51, #52: --at-op reads an earlier view and refuses changes;
7050
/// op restore goes back to an operation, files included, and undo takes
7051
/// the restore back whole; op revert undoes one operation alone; each
7052
/// operation's changes are described from the views.
7053
#[test]
7054
fn operations_can_be_read_restored_and_reverted() {
7055
    hermetic();
7056
    let dir = tempfile::tempdir().unwrap();
7057
    let root = dir.path();
7058
    let repo = Repo::init(root).unwrap();
7059
    write(root, "a.txt", b"a\n");
7060
    let first = repo.commit("first", &[]).unwrap();
7061
    write(root, "a.txt", b"a\nb\n");
7062
    let second = repo.commit("second", &[]).unwrap();
7063
    let at_second = repo.head_op().unwrap().0.to_hex();
7064
    repo.bookmark_create("keep", None).unwrap();
7065
    let created = repo.head_op().unwrap().0.to_hex();
7066
    write(root, "n.txt", b"n\n");
7067
    let third = repo.commit("third", &[]).unwrap();
7068
7069
    // What each operation changed.
7070
    let ops = repo.op_log().unwrap();
7071
    let changes = repo.view_changes(&ops[1].1.view, &ops[0].1.view).unwrap();
7072
    assert!(
7073
        changes
7074
            .iter()
7075
            .any(|c| matches!(c, ViewChange::BookmarkMoved { name, .. } if name == "main")),
7076
        "{changes:?}"
7077
    );
7078
    assert!(changes
7079
        .iter()
7080
        .any(|c| matches!(c, ViewChange::WorkingCopy { .. })));
7081
7082
    // Reading at an earlier operation.
7083
    let old = Repo::open(root).unwrap().at_op(&at_second[..10]).unwrap();
7084
    assert_eq!(old.bookmark_heads().unwrap(), vec![second]);
7085
    assert!(!old.view().unwrap().bookmarks.contains_key("keep"));
7086
    write(root, "z.txt", b"z\n");
7087
    assert!(old.commit("refused", &[]).is_err(), "--at-op is read-only");
7088
    fs::remove_file(root.join("z.txt")).unwrap();
7089
    assert!(repo.resolve_op("zz").is_err());
7090
    assert_eq!(repo.resolve_op("@").unwrap().0, repo.head_op().unwrap().0);
7091
7092
    // Restore goes back, files and all; undo takes it back whole.
7093
    repo.op_restore(&at_second, false).unwrap();
7094
    assert_eq!(repo.bookmark_heads().unwrap(), vec![second]);
7095
    assert!(!root.join("n.txt").exists());
7096
    repo.undo().unwrap();
7097
    let mut heads = repo.bookmark_heads().unwrap();
7098
    heads.sort();
7099
    let mut want = vec![second, third];
7100
    want.sort();
7101
    assert_eq!(heads, want);
7102
    assert!(
7103
        root.join("n.txt").exists(),
7104
        "the files came back with the undo"
7105
    );
7106
7107
    // Revert the bookmark's creation alone: the commit after it stays.
7108
    let r = repo.op_revert(&created).unwrap();
7109
    assert_eq!(r.reverted, vec!["keep".to_string()]);
7110
    assert!(!repo.view().unwrap().bookmarks.contains_key("keep"));
7111
    assert!(repo
7112
        .load_state(&repo.bookmark_heads().unwrap())
7113
        .unwrap()
7114
        .contains(&third));
7115
    assert!(repo.op_revert(&created).is_err(), "nothing left to revert");
7116
    let _ = first;
7117
}
7118
7119
/// oxygen#41: with uncommitted work, a status after a snapshot is answered
7120
/// from the status cache while every file is as the snapshot left it, and
7121
/// from a snapshot again as soon as one is not.
7122
#[test]
7123
fn status_with_uncommitted_work_comes_from_the_cache_until_a_file_changes() {
7124
    hermetic();
7125
    let dir = tempfile::tempdir().unwrap();
7126
    let root = dir.path();
7127
    let repo = Repo::init(root).unwrap();
7128
    write(root, "a.txt", b"a\n");
7129
    write(root, "b.txt", b"b\n");
7130
    repo.commit("base", &[]).unwrap();
7131
    assert_eq!(repo.status_by_manifest().unwrap(), Some(vec![]), "clean");
7132
7133
    write(root, "a.txt", b"a\nmore\n");
7134
    assert_eq!(
7135
        repo.status_by_manifest().unwrap(),
7136
        None,
7137
        "no snapshot of the edit yet"
7138
    );
7139
    let snap = repo.snapshot_status("oxy status").unwrap();
7140
    assert_eq!(snap.statuses.len(), 1);
7141
    let cached = repo
7142
        .status_by_manifest()
7143
        .unwrap()
7144
        .expect("answered from the cache");
7145
    assert_eq!(cached.len(), 1);
7146
    assert_eq!(
7147
        (cached[0].path.as_str(), cached[0].status),
7148
        ("a.txt", ChangeStatus::Modified)
7149
    );
7150
7151
    // Any further change sends status back to a snapshot.
7152
    write(root, "a.txt", b"a\nmore\nand more\n");
7153
    assert_eq!(repo.status_by_manifest().unwrap(), None, "edited again");
7154
    repo.snapshot_status("oxy status").unwrap();
7155
    assert!(repo.status_by_manifest().unwrap().is_some());
7156
    write(root, "new.txt", b"n\n");
7157
    assert_eq!(repo.status_by_manifest().unwrap(), None, "a file added");
7158
    fs::remove_file(root.join("new.txt")).unwrap();
7159
    assert!(
7160
        repo.status_by_manifest().unwrap().is_some(),
7161
        "back as it was"
7162
    );
7163
    fs::remove_file(root.join("b.txt")).unwrap();
7164
    assert_eq!(repo.status_by_manifest().unwrap(), None, "a file removed");
7165
    write(root, "b.txt", b"b\n");
7166
7167
    // A commit leaves nothing uncommitted: clean again, no cache needed.
7168
    repo.snapshot_status("oxy status").unwrap();
7169
    repo.commit("more", &[]).unwrap();
7170
    assert_eq!(repo.status_by_manifest().unwrap(), Some(vec![]));
7171
}
7172
7173
/// oxygen#41: while the status cache holds, the working copy's diff is
7174
/// rendered from the stored working-copy change, and says exactly what a
7175
/// snapshot's diff says.
7176
#[test]
7177
fn the_working_copy_diff_from_the_cache_matches_a_snapshot() {
7178
    hermetic();
7179
    let dir = tempfile::tempdir().unwrap();
7180
    let root = dir.path();
7181
    let repo = Repo::init(root).unwrap();
7182
    write(root, "a.txt", b"one\ntwo\nthree\n");
7183
    write(root, "gone.txt", b"bye\n");
7184
    repo.commit("base", &[]).unwrap();
7185
    write(root, "a.txt", b"one\n2\nthree\nfour\n");
7186
    write(root, "new.txt", b"hello\n");
7187
    fs::remove_file(root.join("gone.txt")).unwrap();
7188
    let snap = repo.snapshot_status("oxy status").unwrap();
7189
    let slow = render_change(&snap.wc, &snap.base, &snap.base_snapshot);
7190
    assert!(
7191
        repo.status_by_manifest().unwrap().is_some(),
7192
        "the cache holds"
7193
    );
7194
    let (wc, base, snapshot) = repo.working_copy_with_base().unwrap();
7195
    assert_eq!(render_change(&wc, &base, &snapshot), slow);
7196
    assert_eq!(repo.diff_files(None).unwrap().len(), 3);
7197
}
7198
7199
/// oxygen#41: a manifest written from a walk keeps every directory's time;
7200
/// while none has moved, the check stats the tracked files without listing
7201
/// the tree, and a file added or removed anywhere moves its directory's
7202
/// time, so the tree is listed again.
7203
#[test]
7204
fn the_manifest_check_skips_listing_while_no_directory_changed() {
7205
    hermetic();
7206
    let dir = tempfile::tempdir().unwrap();
7207
    let root = dir.path();
7208
    let repo = Repo::init(root).unwrap();
7209
    write(root, "a.txt", b"a\n");
7210
    write(root, "sub/deep/b.txt", b"b\n");
7211
    repo.commit("base", &[]).unwrap();
7212
    // Out of the racy window: every file and directory a minute old.
7213
    let old = std::time::SystemTime::now() - std::time::Duration::from_secs(60);
7214
    for p in ["a.txt", "sub/deep/b.txt", "sub/deep", "sub", ""] {
7215
        fs::File::open(root.join(p))
7216
            .unwrap()
7217
            .set_modified(old)
7218
            .unwrap();
7219
    }
7220
    repo.snapshot_status("oxy status").unwrap();
7221
    repo.write_manifest(false, false).unwrap();
7222
    let m = repo.read_manifest().unwrap().unwrap().2;
7223
    assert!(m.dirs.iter().any(|(d, _)| d == "sub/deep"), "{:?}", m.dirs);
7224
    assert_eq!(
7225
        repo.disk_differs_by_dirs(&m),
7226
        Some(false),
7227
        "no listing needed"
7228
    );
7229
    assert_eq!(repo.status_by_manifest().unwrap(), Some(vec![]));
7230
7231
    // A same-size edit with a new time: found by its stat.
7232
    write(root, "sub/deep/b.txt", b"c\n");
7233
    assert_eq!(repo.disk_differs_by_dirs(&m), Some(true));
7234
    write(root, "sub/deep/b.txt", b"b\n");
7235
    fs::File::open(root.join("sub/deep/b.txt"))
7236
        .unwrap()
7237
        .set_modified(old)
7238
        .unwrap();
7239
    assert_eq!(repo.disk_differs_by_dirs(&m), Some(false));
7240
7241
    // A new file moves its directory's time: the tree must be listed.
7242
    write(root, "sub/deep/new.txt", b"n\n");
7243
    assert_eq!(repo.disk_differs_by_dirs(&m), None);
7244
    assert_eq!(repo.status_by_manifest().unwrap(), None);
7245
    fs::remove_file(root.join("sub/deep/new.txt")).unwrap();
7246
    // A removed one too.
7247
    fs::remove_file(root.join("a.txt")).unwrap();
7248
    assert_eq!(repo.disk_differs_by_dirs(&m), None);
7249
}
7250
7251
/// oxygen#41: a commit right after a status takes the snapshot the status
7252
/// left (the status cache holds) rather than walking again, and commits
7253
/// exactly what a snapshot would have.
7254
#[test]
7255
fn a_commit_after_a_status_uses_the_cached_snapshot() {
7256
    hermetic();
7257
    let dir = tempfile::tempdir().unwrap();
7258
    let root = dir.path();
7259
    let repo = Repo::init(root).unwrap();
7260
    write(root, "a.txt", b"a\nb\n");
7261
    write(root, ".oxyattributes", b"*.bin binary\n");
7262
    repo.commit("base", &[]).unwrap();
7263
    write(root, "a.txt", b"a\nB\n");
7264
    write(root, "new.txt", b"new\n");
7265
    let snap = repo.snapshot_status("oxy status").unwrap();
7266
    let cached = repo
7267
        .snapshot_from_cache()
7268
        .unwrap()
7269
        .expect("the cache holds");
7270
    assert_eq!(cached.wc_hash, snap.wc_hash);
7271
    assert_eq!(cached.statuses, snap.statuses);
7272
    assert!(
7273
        !cached.attributes.is_empty(),
7274
        "the .oxyattributes file was read"
7275
    );
7276
    let h = repo.commit("edit", &[]).unwrap();
7277
    let c = repo.store().get_change(&h).unwrap();
7278
    assert_eq!(
7279
        c.tree_ops.len() + c.edits.len(),
7280
        snap.wc.tree_ops.len() + snap.wc.edits.len()
7281
    );
7282
    assert_eq!(
7283
        repo.status_by_manifest().unwrap(),
7284
        Some(vec![]),
7285
        "clean after the commit"
7286
    );
7287
    assert_eq!(fs::read(root.join("a.txt")).unwrap(), b"a\nB\n");
7288
}
7289
7290
/// oxygen#41: a clean check that verified racy entries restamps the
7291
/// manifest, so later checks can trust them, and a same-size rewrite
7292
/// straight afterwards is still found: entries within two seconds of the
7293
/// new time stay racy.
7294
#[test]
7295
fn a_verified_clean_check_restamps_the_manifest_safely() {
7296
    hermetic();
7297
    let dir = tempfile::tempdir().unwrap();
7298
    let root = dir.path();
7299
    let repo = Repo::init(root).unwrap();
7300
    write(root, "a.txt", b"one\n");
7301
    repo.commit("one", &[]).unwrap();
7302
    let before = repo.read_manifest().unwrap().unwrap().2.written_ns;
7303
    assert!(repo.clean_by_manifest().unwrap());
7304
    let after = repo.read_manifest().unwrap().unwrap().2.written_ns;
7305
    assert!(after > before, "restamped");
7306
    write(root, "a.txt", b"two\n");
7307
    assert!(
7308
        !repo.clean_by_manifest().unwrap(),
7309
        "a same-size rewrite is still seen"
7310
    );
7311
}
7312
7313
/// oxygen#35: a history-only state keeps no inserted text. It reads a
7314
/// stored insert's text blob only when it builds that file's graph, and
7315
/// builds the same graph a full load does.
7316
#[test]
7317
fn history_only_states_read_text_only_for_the_graphs_they_build() {
7318
    hermetic();
7319
    let dir = tempfile::tempdir().unwrap();
7320
    let root = dir.path();
7321
    let repo = Repo::init(root).unwrap();
7322
    let big: String = (0..3000).map(|i| format!("big line {i}\n")).collect();
7323
    let other: String = (0..3000).map(|i| format!("other line {i}\n")).collect();
7324
    write(root, "big.txt", big.as_bytes());
7325
    write(root, "other.txt", other.as_bytes());
7326
    let h = repo.commit("two large files", &[]).unwrap();
7327
    write(root, "big.txt", format!("{big}one more\n").as_bytes());
7328
    let h2 = repo.commit("append", &[]).unwrap();
7329
7330
    let full = repo.load_state_full(&[h2]).unwrap().materialize();
7331
    let text = |snap: &crate::state::Snapshot, p: &str| match &snap.files[p].content {
7332
        FileContent::Text { bytes, .. } => bytes.clone(),
7333
        other => panic!("{other:?}"),
7334
    };
7335
    // Built on demand, every graph renders as the full load's.
7336
    let mut hist = repo.load_state_history(&[h2]).unwrap();
7337
    let big_node = full.files["big.txt"].node;
7338
    assert!(hist.graph_key(&big_node).is_some(), "not built yet");
7339
    repo.load_all_graphs(&mut hist).unwrap();
7340
    let rendered = hist.materialize();
7341
    for p in ["big.txt", "other.txt"] {
7342
        assert_eq!(text(&rendered, p), text(&full, p), "{p}");
7343
    }
7344
7345
    // Without other.txt's text blob, history still loads and big.txt still
7346
    // builds: nothing read the other text.
7347
    let (_, texts) = repo.store().get_change_lazy(&h).unwrap();
7348
    assert_eq!(texts.len(), 2);
7349
    let content = |r: &ObjectRef| -> Vec<u8> {
7350
        let blob = crate::objects::Blob::decode(&repo.store().get(r).unwrap().1).unwrap();
7351
        blob.chunks
7352
            .iter()
7353
            .flat_map(|c| repo.store().get(c).unwrap().1)
7354
            .collect()
7355
    };
7356
    let other_text = texts
7357
        .iter()
7358
        .filter_map(|t| match t {
7359
            crate::objects::TextRef::Blob(r, _, _) => Some(*r),
7360
            _ => None,
7361
        })
7362
        .find(|r| content(r).windows(12).any(|w| w == b"other line 1"))
7363
        .unwrap();
7364
    repo.store().remove_loose_for_test(&other_text).unwrap();
7365
    let mut hist = repo.load_state_history(&[h2]).unwrap();
7366
    repo.load_graphs_of(&mut hist, &[big_node]).unwrap();
7367
    assert!(repo
7368
        .load_graphs_of(&mut hist, &[full.files["other.txt"].node])
7369
        .is_err());
7370
}
7371
7372
/// oxygen#35: the first status after a commit read and rendered every
7373
/// file (79 s and more than 14 GB on the Linux tree), because the
7374
/// manifest had no graph keys for files the commit added.
7375
#[test]
7376
fn a_commit_leaves_a_manifest_the_next_status_trusts() {
7377
    use std::os::unix::fs::PermissionsExt;
7378
    hermetic();
7379
    let dir = tempfile::tempdir().unwrap();
7380
    let root = dir.path();
7381
    let repo = Repo::init(root).unwrap();
7382
    let files = ["a.txt", "b.txt", "d/c.txt"];
7383
    for p in files {
7384
        write(root, p, format!("{p}\n").as_bytes());
7385
        let old = std::time::SystemTime::now() - std::time::Duration::from_secs(30);
7386
        fs::File::options()
7387
            .write(true)
7388
            .open(root.join(p))
7389
            .unwrap()
7390
            .set_modified(old)
7391
            .unwrap();
7392
    }
7393
    repo.commit("added", &[]).unwrap();
7394
    let (_, _, m) = repo.read_manifest().unwrap().unwrap();
7395
    assert!(
7396
        m.entries.values().all(|e| e.graph.is_some()),
7397
        "keys recorded at commit"
7398
    );
7399
    // Unreadable files prove the next status reads none of them.
7400
    for p in files {
7401
        fs::set_permissions(root.join(p), fs::Permissions::from_mode(0o000)).unwrap();
7402
    }
7403
    let snap = repo.snapshot_status("status").unwrap();
7404
    for p in files {
7405
        fs::set_permissions(root.join(p), fs::Permissions::from_mode(0o644)).unwrap();
7406
    }
7407
    assert!(!snap.changed && snap.statuses.is_empty());
7408
    assert_eq!(snap.base_snapshot.unrendered.len(), files.len());
7409
}
7410
7411
/// oxygen#35: a checkout reads, renders and writes only the files whose
7412
/// graphs differ, and renders the rest a batch at a time.
7413
#[test]
7414
fn checkout_touches_only_what_differs_and_renders_in_batches() {
7415
    use std::os::unix::fs::PermissionsExt;
7416
    hermetic();
7417
    let dir = tempfile::tempdir().unwrap();
7418
    let root = dir.path();
7419
    let origin = root.join("origin");
7420
    let mut repo = Repo::init(&origin).unwrap();
7421
    // More files than one batch holds.
7422
    let n = 2100;
7423
    let old = std::time::SystemTime::now() - std::time::Duration::from_secs(30);
7424
    for i in 0..n {
7425
        let p = format!("f/{i:04}.txt");
7426
        write(&origin, &p, format!("file {i}\n").as_bytes());
7427
        fs::File::options()
7428
            .write(true)
7429
            .open(origin.join(&p))
7430
            .unwrap()
7431
            .set_modified(old)
7432
            .unwrap();
7433
    }
7434
    repo.commit("many", &[]).unwrap();
7435
    repo.bookmark_create("feature", None).unwrap();
7436
    repo.bookmark_switch("feature", false).unwrap();
7437
    write(&origin, "f/0007.txt", b"changed\n");
7438
    repo.commit("one change", &[]).unwrap();
7439
7440
    // Switching back to main must not read the unchanged files.
7441
    for i in 0..n {
7442
        if i != 7 {
7443
            let p = origin.join(format!("f/{i:04}.txt"));
7444
            fs::set_permissions(&p, fs::Permissions::from_mode(0o000)).unwrap();
7445
        }
7446
    }
7447
    let r = repo.bookmark_switch("main", false).unwrap();
7448
    for i in 0..n {
7449
        let p = origin.join(format!("f/{i:04}.txt"));
7450
        fs::set_permissions(&p, fs::Permissions::from_mode(0o644)).unwrap();
7451
    }
7452
    assert_eq!((r.written, r.removed), (1, 0), "{r:?}");
7453
    assert_eq!(fs::read(origin.join("f/0007.txt")).unwrap(), b"file 7\n");
7454
    assert!(repo.snapshot_status("status").unwrap().statuses.is_empty());
7455
7456
    // A clone renders every file, across batches.
7457
    let c = root.join("clone");
7458
    Repo::clone(&origin.to_string_lossy(), &c).unwrap();
7459
    for i in [0, 2047, 2048, n - 1] {
7460
        assert_eq!(
7461
            fs::read(c.join(format!("f/{i:04}.txt"))).unwrap(),
7462
            format!("file {i}\n").as_bytes()
7463
        );
7464
    }
7465
    let cloned = Repo::open(&c).unwrap();
7466
    assert!(cloned
7467
        .snapshot_status("status")
7468
        .unwrap()
7469
        .statuses
7470
        .is_empty());
7471
}
7472
7473
/// A file written just before the manifest (inside the racy window) is
7474
/// checked by its hash: trusted when equal, caught when edited in place
7475
/// with the same size and time.
7476
#[test]
7477
fn a_racy_manifest_entry_is_checked_by_hash() {
7478
    hermetic();
7479
    let dir = tempfile::tempdir().unwrap();
7480
    let root = dir.path();
7481
    let repo = Repo::init(root).unwrap();
7482
    write(root, "a.txt", b"one\n");
7483
    repo.commit("fresh", &[]).unwrap();
7484
    assert!(repo.clean_by_manifest().unwrap(), "fresh but equal");
7485
    let t = fs::metadata(root.join("a.txt"))
7486
        .unwrap()
7487
        .modified()
7488
        .unwrap();
7489
    write(root, "a.txt", b"two\n");
7490
    fs::File::options()
7491
        .write(true)
7492
        .open(root.join("a.txt"))
7493
        .unwrap()
7494
        .set_modified(t)
7495
        .unwrap();
7496
    assert!(
7497
        !repo.clean_by_manifest().unwrap(),
7498
        "same size and time, other bytes"
7499
    );
7500
    assert_eq!(
7501
        statuses(&repo.snapshot_status("status").unwrap()),
7502
        vec![("a.txt".to_string(), ChangeStatus::Modified)]
7503
    );
7504
}
7505
7506
/// A fetch on one machine moves changes as stored, text blobs among the
7507
/// objects; a change whose text blob did not come is refused, not stored.
7508
#[test]
7509
fn a_raw_bundle_without_a_changes_text_is_refused() {
7510
    hermetic();
7511
    let dir = tempfile::tempdir().unwrap();
7512
    let root = dir.path();
7513
    let a = Repo::init(&root.join("a")).unwrap();
7514
    let big: String = (0..3000).map(|i| format!("line {i}\n")).collect();
7515
    write(&root.join("a"), "big.txt", big.as_bytes());
7516
    let h = a.commit("big", &[]).unwrap();
7517
    let bundle = a.bundle_raw_for(&[h], None).unwrap();
7518
    assert_eq!(bundle.raw_changes.len(), 1);
7519
    assert!(bundle.changes.is_empty());
7520
    let b = Repo::init(&root.join("b")).unwrap();
7521
    let mut without = bundle.clone();
7522
    without.objects.retain(|(ty, _)| *ty != ObjectType::Blob);
7523
    let e = b.import_bundle(&without, false).unwrap_err();
7524
    assert!(e.to_string().contains("came without its text blob"), "{e}");
7525
    assert!(!b.store().has(&h));
7526
    assert_eq!(b.import_bundle(&bundle, false).unwrap(), vec![h]);
7527
    assert_eq!(b.store().get_change(&h).unwrap().message, "big");
7528
}
7529
7530
/// oxygen#30 (vscode): a directory deleted in one line of history and made
7531
/// again was a second node for one Git path, so a file moved into it on
7532
/// another line, where the first node still stood, ended up in two places.
7533
/// An import now brings the directory back rather than make a new one.
7534
#[test]
7535
fn git_import_brings_a_directory_back_rather_than_making_a_second() {
7536
    hermetic();
7537
    if std::process::Command::new("git")
7538
        .arg("--version")
7539
        .output()
7540
        .is_err()
7541
    {
7542
        eprintln!("git not installed; skipping");
7543
        return;
7544
    }
7545
    let dir = tempfile::tempdir().unwrap();
7546
    let root = dir.path();
7547
    let g = root.join("src.git");
7548
    fs::create_dir_all(&g).unwrap();
7549
    let git = |args: &[&str]| -> String {
7550
        let out = std::process::Command::new("git")
7551
            .arg("-C")
7552
            .arg(&g)
7553
            .args([
7554
                "-c",
7555
                "user.name=Grace",
7556
                "-c",
7557
                "[email protected]",
7558
                "-c",
7559
                "commit.gpgsign=false",
7560
            ])
7561
            .args(args)
7562
            .output()
7563
            .unwrap();
7564
        assert!(
7565
            out.status.success(),
7566
            "git {args:?}: {}",
7567
            String::from_utf8_lossy(&out.stderr)
7568
        );
7569
        String::from_utf8_lossy(&out.stdout).trim().to_string()
7570
    };
7571
    git(&["init", "-q", "-b", "main"]);
7572
    write(&g, "d/a.txt", b"a\n");
7573
    write(&g, "c/x.txt", b"x\n");
7574
    git(&["add", "."]);
7575
    git(&["commit", "-qm", "base"]);
7576
    // One line: move x into d while d still stands.
7577
    git(&["checkout", "-qb", "side"]);
7578
    git(&["mv", "c/x.txt", "d/x.txt"]);
7579
    git(&["commit", "-qm", "x into d"]);
7580
    // The other: d goes, comes back, and x moves into it too.
7581
    git(&["checkout", "-q", "main"]);
7582
    git(&["rm", "-q", "d/a.txt"]);
7583
    git(&["commit", "-qm", "d goes"]);
7584
    write(&g, "d/b.txt", b"b\n");
7585
    git(&["add", "."]);
7586
    git(&["commit", "-qm", "d comes back"]);
7587
    git(&["mv", "c/x.txt", "d/x.txt"]);
7588
    git(&["commit", "-qm", "x into d again"]);
7589
    git(&["merge", "-q", "--no-edit", "side"]);
7590
7591
    let repo = Repo::init(&root.join("o")).unwrap();
7592
    repo.import_git(&g, "main").unwrap();
7593
    let v = repo.verify_git_import(&g, "main").unwrap();
7594
    assert!(v.mismatches.is_empty(), "{:?}", v.mismatches);
7595
    let st = repo
7596
        .load_state_history(&repo.bookmark_heads().unwrap())
7597
        .unwrap();
7598
    let view = st.tree().view();
7599
    assert!(view.conflicts.is_empty(), "{:?}", view.conflicts);
7600
    // The directory is the one the first commit made.
7601
    // Commits made in one second tie on time: find the first by its message.
7602
    let first = repo
7603
        .log()
7604
        .unwrap()
7605
        .into_iter()
7606
        .find(|e| e.change.message.starts_with("base"))
7607
        .unwrap();
7608
    let base = repo
7609
        .load_state_history(&[first.hash])
7610
        .unwrap()
7611
        .tree()
7612
        .view();
7613
    assert_eq!(view.entries["d"].node, base.entries["d"].node);
7614
}
7615
7616
/// oxygen#30, the rest: a placement left under a directory another line
7617
/// removed is out of sight, so no diff reaches it; the merge that settles
7618
/// where the file is retires it.
7619
#[test]
7620
fn git_import_merge_retires_a_placement_under_a_removed_directory() {
7621
    hermetic();
7622
    if std::process::Command::new("git")
7623
        .arg("--version")
7624
        .output()
7625
        .is_err()
7626
    {
7627
        eprintln!("git not installed; skipping");
7628
        return;
7629
    }
7630
    let dir = tempfile::tempdir().unwrap();
7631
    let root = dir.path();
7632
    let g = root.join("src.git");
7633
    fs::create_dir_all(&g).unwrap();
7634
    let run = |args: &[&str]| {
7635
        std::process::Command::new("git")
7636
            .arg("-C")
7637
            .arg(&g)
7638
            .args([
7639
                "-c",
7640
                "user.name=Grace",
7641
                "-c",
7642
                "[email protected]",
7643
                "-c",
7644
                "commit.gpgsign=false",
7645
            ])
7646
            .args(args)
7647
            .output()
7648
            .unwrap()
7649
    };
7650
    let git = |args: &[&str]| {
7651
        let out = run(args);
7652
        assert!(
7653
            out.status.success(),
7654
            "git {args:?}: {}",
7655
            String::from_utf8_lossy(&out.stderr)
7656
        );
7657
    };
7658
    git(&["init", "-q", "-b", "main"]);
7659
    write(&g, "c/x.txt", b"x\n");
7660
    write(&g, "keep.txt", b"k\n");
7661
    git(&["add", "."]);
7662
    git(&["commit", "-qm", "base"]);
7663
    // One line renames the file within c; the other moves it out of c,
7664
    // which goes.
7665
    git(&["checkout", "-qb", "side"]);
7666
    git(&["mv", "c/x.txt", "c/y.txt"]);
7667
    git(&["commit", "-qm", "rename within c"]);
7668
    git(&["checkout", "-q", "main"]);
7669
    fs::create_dir_all(g.join("n")).unwrap();
7670
    git(&["mv", "c/x.txt", "n/x.txt"]);
7671
    git(&["commit", "-qm", "move out of c"]);
7672
    // Git cannot merge the two renames; the merge keeps n/x.txt.
7673
    let _ = run(&["merge", "-q", "side"]);
7674
    let _ = run(&[
7675
        "rm",
7676
        "-q",
7677
        "--cached",
7678
        "--ignore-unmatch",
7679
        "c/y.txt",
7680
        "c/x.txt",
7681
    ]);
7682
    let _ = std::fs::remove_dir_all(g.join("c"));
7683
    write(&g, "n/x.txt", b"x\n");
7684
    git(&["add", "-A"]);
7685
    git(&["commit", "-qm", "merge: keep n/x.txt"]);
7686
7687
    let repo = Repo::init(&root.join("o")).unwrap();
7688
    repo.import_git(&g, "main").unwrap();
7689
    let v = repo.verify_git_import(&g, "main").unwrap();
7690
    assert!(v.mismatches.is_empty(), "{:?}", v.mismatches);
7691
    let st = repo
7692
        .load_state_history(&repo.bookmark_heads().unwrap())
7693
        .unwrap();
7694
    let view = st.tree().view();
7695
    assert!(view.conflicts.is_empty(), "{:?}", view.conflicts);
7696
    assert!(view.entries.contains_key("n/x.txt"));
7697
}
7698
7699
/// oxygen#30, orphans: a file added on one line into a directory the other
7700
/// line removed is placed where the tree cannot show it; Git's merge keeps
7701
/// the file, and the import's merge leaves exactly one of it.
7702
#[test]
7703
fn git_import_merge_leaves_no_orphan_behind() {
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 git = |args: &[&str]| {
7718
        let out = 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
        assert!(
7733
            out.status.success(),
7734
            "git {args:?}: {}",
7735
            String::from_utf8_lossy(&out.stderr)
7736
        );
7737
    };
7738
    git(&["init", "-q", "-b", "main"]);
7739
    write(&g, "d/f.txt", b"f\n");
7740
    write(&g, "keep.txt", b"k\n");
7741
    git(&["add", "."]);
7742
    git(&["commit", "-qm", "base"]);
7743
    git(&["checkout", "-qb", "side"]);
7744
    write(&g, "d/new.txt", b"new\n");
7745
    git(&["add", "."]);
7746
    git(&["commit", "-qm", "add into d"]);
7747
    git(&["checkout", "-q", "main"]);
7748
    git(&["rm", "-q", "d/f.txt"]);
7749
    git(&["commit", "-qm", "d goes"]);
7750
    git(&["merge", "-q", "--no-edit", "side"]);
7751
7752
    let repo = Repo::init(&root.join("o")).unwrap();
7753
    repo.import_git(&g, "main").unwrap();
7754
    let v = repo.verify_git_import(&g, "main").unwrap();
7755
    assert!(v.mismatches.is_empty(), "{:?}", v.mismatches);
7756
    let st = repo
7757
        .load_state_history(&repo.bookmark_heads().unwrap())
7758
        .unwrap();
7759
    let view = st.tree().view();
7760
    assert!(view.conflicts.is_empty(), "{:?}", view.conflicts);
7761
    assert!(view.entries.contains_key("d/new.txt"));
7762
}
7763
7764
/// fsck checks a change's text as the blobs it is stored in, without
7765
/// decoding it: a missing text blob is an error named for the change.
7766
#[test]
7767
fn fsck_names_a_missing_text_blob() {
7768
    hermetic();
7769
    let dir = tempfile::tempdir().unwrap();
7770
    let root = dir.path();
7771
    let repo = Repo::init(root).unwrap();
7772
    let big: String = (0..3000).map(|i| format!("line {i}\n")).collect();
7773
    write(root, "big.txt", big.as_bytes());
7774
    let h = repo.commit("big", &[]).unwrap();
7775
    assert_eq!(repo.fsck().unwrap().errors(), 0);
7776
    let (_, texts) = repo.store().get_change_lazy(&h).unwrap();
7777
    let Some(crate::objects::TextRef::Blob(b, _, _)) = texts.first().copied() else {
7778
        panic!("a stored text")
7779
    };
7780
    repo.store().remove_loose_for_test(&b).unwrap();
7781
    let rep = repo.fsck().unwrap();
7782
    assert!(rep.errors() > 0);
7783
    assert!(
7784
        rep.problems.iter().any(|p| p.what.contains(&h.short(12))),
7785
        "{:?}",
7786
        rep.problems
7787
    );
7788
}
7789
7790
/// oxygen#32: a subrepo on the same hub as one of the parent's remotes is
7791
/// reached with that remote's token and CA (a private subrepo then clones
7792
/// for anyone who can read the parent); another hub gets none of them.
7793
#[test]
7794
fn a_subrepo_on_the_parents_hub_borrows_its_credentials() {
7795
    hermetic();
7796
    let dir = tempfile::tempdir().unwrap();
7797
    let mut repo = Repo::init(dir.path()).unwrap();
7798
    repo.config
7799
        .set(
7800
            "remote.origin.url",
7801
            "https://Hub.example:7343/doomsdayone/metalgear",
7802
        )
7803
        .unwrap();
7804
    repo.config.set("remote.origin.token", "secret").unwrap();
7805
    repo.config
7806
        .set("remote.origin.ca", "/tmp/hub-ca.pem")
7807
        .unwrap();
7808
    let same = repo.credentials_for("https://hub.example:7343/doomsdayone/rstar-api");
7809
    assert_eq!(same.token.as_deref(), Some("secret"));
7810
    assert_eq!(same.ca.as_deref(), Some(Path::new("/tmp/hub-ca.pem")));
7811
    for other in [
7812
        "https://elsewhere.example:7343/doomsdayone/rstar-api",
7813
        "https://hub.example/doomsdayone/rstar-api",
7814
        "http://hub.example:7343/doomsdayone/rstar-api",
7815
    ] {
7816
        let o = repo.credentials_for(other);
7817
        assert_ne!(o.token.as_deref(), Some("secret"), "{other}");
7818
    }
7819
}
7820
7821
/// oxygen#47: a remote with no token of its own uses the user's credential
7822
/// store for its hub, and a nested checkout finds its parent's remote
7823
/// token there instead of keeping a copy.
7824
#[test]
7825
fn remotes_use_the_credential_store_and_the_enclosing_checkout() {
7826
    hermetic();
7827
    let home = tempfile::tempdir().unwrap();
7828
    let dir = tempfile::tempdir().unwrap();
7829
    let mut parent = Repo::init(dir.path()).unwrap().with_home(home.path());
7830
    parent
7831
        .config
7832
        .set("remote.origin.url", "https://hub.example/o/parent")
7833
        .unwrap();
7834
    parent.save_config().unwrap();
7835
    assert_eq!(parent.remote_options("origin").token, None);
7836
    crate::credentials::Credentials::at(home.path())
7837
        .save("https://hub.example", "stored", Some("andy"), None)
7838
        .unwrap();
7839
    assert_eq!(
7840
        parent.remote_options("origin").token.as_deref(),
7841
        Some("stored")
7842
    );
7843
7844
    let empty_home = tempfile::tempdir().unwrap();
7845
    let nested = dir.path().join("deps").join("child");
7846
    let mut child = Repo::init(&nested).unwrap().with_home(empty_home.path());
7847
    child
7848
        .config
7849
        .set("remote.origin.url", "https://hub.example/o/child")
7850
        .unwrap();
7851
    child.save_config().unwrap();
7852
    assert_eq!(child.remote_options("origin").token, None);
7853
    parent
7854
        .config
7855
        .set("remote.origin.token", "checkout")
7856
        .unwrap();
7857
    parent.save_config().unwrap();
7858
    assert_eq!(
7859
        child.remote_options("origin").token.as_deref(),
7860
        Some("checkout")
7861
    );
7862
    // Another hub's checkout token is not borrowed.
7863
    child
7864
        .config
7865
        .set("remote.origin.url", "https://other.example/o/child")
7866
        .unwrap();
7867
    assert_eq!(child.remote_options("origin").token, None);
7868
}
7869
7870
#[test]
7871
fn the_metadata_cache_survives_a_torn_tail() {
7872
    hermetic();
7873
    let dir = tempfile::tempdir().unwrap();
7874
    let root = dir.path();
7875
    let repo = Repo::init(root).unwrap();
7876
    write(root, "a.txt", b"1\n");
7877
    let h = repo.commit("first", &[]).unwrap();
7878
    let meta = repo.store().get_change_meta(&h).unwrap();
7879
    let cache = repo.store().dir().join("metas");
7880
    let len = fs::metadata(&cache).unwrap().len();
7881
    assert!(len > 0, "a change read is cached");
7882
    // A torn record at the end: the cache reads up to it and cuts it off.
7883
    fs::OpenOptions::new()
7884
        .append(true)
7885
        .open(&cache)
7886
        .unwrap()
7887
        .write_all(&[7; 20])
7888
        .unwrap();
7889
    let again = Repo::open(root).unwrap();
7890
    assert_eq!(again.store().get_change_meta(&h).unwrap(), meta);
7891
    assert_eq!(fs::metadata(&cache).unwrap().len(), len);
7892
}
7893
7894
#[test]
7895
fn a_manifest_that_does_not_check_reads_as_none() {
7896
    hermetic();
7897
    let dir = tempfile::tempdir().unwrap();
7898
    let root = dir.path();
7899
    let repo = Repo::init(root).unwrap();
7900
    write(root, "a.txt", b"1\n");
7901
    repo.commit("first", &[]).unwrap();
7902
    let path = repo.manifest_path();
7903
    let mut bytes = fs::read(&path).unwrap();
7904
    assert!(Repo::open(root).unwrap().read_manifest().unwrap().is_some());
7905
    let last = bytes.len() - 1;
7906
    bytes[last] ^= 1;
7907
    fs::write(&path, &bytes).unwrap();
7908
    assert!(Repo::open(root).unwrap().read_manifest().unwrap().is_none());
7909
    // The next status reads the files and writes it again.
7910
    let again = Repo::open(root).unwrap();
7911
    assert!(!again.snapshot("status").unwrap().changed);
7912
    assert!(again.read_manifest().unwrap().is_some());
7913
}
7914
7915
#[test]
7916
fn a_commit_leaves_a_manifest_that_proves_the_working_copy_clean() {
7917
    hermetic();
7918
    let dir = tempfile::tempdir().unwrap();
7919
    let root = dir.path();
7920
    let repo = Repo::init(root).unwrap();
7921
    write(root, "a.txt", b"1\n");
7922
    write(root, "b.txt", b"2\n");
7923
    // b.txt outside the racy window, so snapshots take it as unchanged.
7924
    let old = std::time::SystemTime::now() - std::time::Duration::from_secs(60);
7925
    fs::File::options()
7926
        .write(true)
7927
        .open(root.join("b.txt"))
7928
        .unwrap()
7929
        .set_modified(old)
7930
        .unwrap();
7931
    repo.commit("first", &[]).unwrap();
7932
    assert!(repo.clean_by_manifest().unwrap(), "after the first commit");
7933
    repo.snapshot_status("status").unwrap();
7934
    write(root, "a.txt", b"1\n2\n");
7935
    repo.commit("second", &[]).unwrap();
7936
    assert!(
7937
        repo.clean_by_manifest().unwrap(),
7938
        "after a commit of one file"
7939
    );
7940
    // Edited, seen by a status, edited again, then committed: the status
7941
    // left the first edit's stat, which the commit must not keep.
7942
    write(root, "a.txt", b"1\n2\n3\n");
7943
    repo.snapshot_status("status").unwrap();
7944
    write(root, "a.txt", b"1\n2\n3\n4\n5\n");
7945
    repo.commit("third", &[]).unwrap();
7946
    assert!(
7947
        repo.clean_by_manifest().unwrap(),
7948
        "after an edit a status saw"
7949
    );
7950
}
7951
7952
#[test]
7953
fn a_conflicted_rebase_can_be_resolved_in_the_working_copy() {
7954
    hermetic();
7955
    let dir = tempfile::tempdir().unwrap();
7956
    let root = dir.path();
7957
    let mut repo = Repo::init(root).unwrap().with_home(root.join("home"));
7958
    write(root, "a.txt", b"1\n2\n");
7959
    let a = repo.commit("A", &[]).unwrap();
7960
    repo.bookmark_create("develop", Some(&[a])).unwrap();
7961
    write(root, "a.txt", b"1\nX\n");
7962
    let c = repo.commit("C: 2 to X", &[]).unwrap();
7963
    repo.bookmark_switch("develop", false).unwrap();
7964
    write(root, "a.txt", b"1\nY\n");
7965
    let d = repo.commit("D: 2 to Y", &[]).unwrap();
7966
    repo.bookmark_switch("main", false).unwrap();
7967
7968
    let err = repo.rebase(&c, &[d]).unwrap_err();
7969
    assert!(matches!(err, RepoError::Conflicted(_)), "{err}");
7970
    let r = repo.rebase_into_working_copy(&c, &[d]).unwrap();
7971
    assert!(r.changed && r.checked_out);
7972
    let snap = repo.snapshot_status("status").unwrap();
7973
    assert!(
7974
        snap.base_snapshot.is_conflicted(),
7975
        "the conflict is in the working copy"
7976
    );
7977
    let text = fs::read_to_string(root.join("a.txt")).unwrap();
7978
    assert!(text.contains('X') && text.contains('Y'), "{text}");
7979
7980
    write(root, "a.txt", b"1\nXY\n");
7981
    repo.commit("Resolve", &[]).unwrap();
7982
    let st = repo.load_state(&repo.bookmark_heads().unwrap()).unwrap();
7983
    assert!(st.contains(&c) && st.contains(&d));
7984
    let files = st.materialize().files;
7985
    assert!(!files["a.txt"].is_conflicted());
7986
    assert!(
7987
        matches!(&files["a.txt"].content, FileContent::Text { bytes, .. } if bytes == b"1\nXY\n")
7988
    );
7989
7990
    // A change the current bookmark does not hold is refused.
7991
    repo.bookmark_switch("develop", false).unwrap();
7992
    write(root, "b.txt", b"b\n");
7993
    let e = repo.commit("E", &[]).unwrap();
7994
    repo.bookmark_switch("main", false).unwrap();
7995
    let err = repo.rebase_into_working_copy(&e, &[a]).unwrap_err();
7996
    assert!(
7997
        err.to_string().contains("not on the current bookmark"),
7998
        "{err}"
7999
    );
8000
}
8001
8002
#[test]
8003
fn an_ignore_rule_drops_an_added_file_but_not_a_tracked_one() {
8004
    hermetic();
8005
    let dir = tempfile::tempdir().unwrap();
8006
    let root = dir.path();
8007
    let repo = Repo::init(root).unwrap();
8008
    write(root, "a.txt", b"a\n");
8009
    write(root, "kept.log", b"tracked\n");
8010
    repo.commit("first", &[]).unwrap();
8011
    write(root, "build.log", b"made\n");
8012
    let snap = repo.snapshot_status("status").unwrap();
8013
    assert!(snap.statuses.iter().any(|s| s.path == "build.log"));
8014
    // A rule written afterwards leaves the added file out again, while the
8015
    // committed one stays tracked.
8016
    write(root, ".gitignore", b"*.log\n");
8017
    let snap = repo.snapshot_status("status").unwrap();
8018
    let paths: Vec<&str> = snap.statuses.iter().map(|s| s.path.as_str()).collect();
8019
    assert_eq!(paths, vec![".gitignore"], "{paths:?}");
8020
    write(root, "kept.log", b"tracked, edited\n");
8021
    let snap = repo.snapshot_status("status").unwrap();
8022
    assert!(snap.statuses.iter().any(|s| s.path == "kept.log"));
8023
}
8024
8025
#[test]
8026
fn shed_graphs_come_back_the_same() {
8027
    hermetic();
8028
    let dir = tempfile::tempdir().unwrap();
8029
    let root = dir.path();
8030
    let repo = Repo::init(root).unwrap();
8031
    write(root, "a.txt", b"1\n2\n3\n");
8032
    write(root, "b.txt", b"x\n");
8033
    repo.commit("first", &[]).unwrap();
8034
    write(root, "a.txt", b"1\ntwo\n3\n4\n");
8035
    repo.commit("second", &[]).unwrap();
8036
    let heads = repo.bookmark_heads().unwrap();
8037
    let mut st = repo.load_state_history(&heads).unwrap();
8038
    let view = st.tree().view();
8039
    let nodes: Vec<NodeId> = ["a.txt", "b.txt"]
8040
        .iter()
8041
        .map(|p| view.entries[*p].node)
8042
        .collect();
8043
    repo.load_graphs_of(&mut st, &nodes).unwrap();
8044
    let before: Vec<Vec<u8>> = nodes.iter().map(|n| st.render_file(n).0).collect();
8045
    assert_eq!(st.built_count(), 2);
8046
    let shed = st.shed_graphs(|b| repo.store_blob(b)).unwrap();
8047
    assert_eq!((shed, st.built_count()), (2, 0));
8048
    // A later change applies on top of the shed history.
8049
    write(root, "a.txt", b"1\ntwo\n3\n4\n5\n");
8050
    let h3 = repo.commit("third", &[]).unwrap();
8051
    let (skeleton, texts) = repo.store().get_change_lazy(&h3).unwrap();
8052
    st.add_known(h3, skeleton, texts);
8053
    repo.load_graphs_of(&mut st, &nodes).unwrap();
8054
    let after: Vec<Vec<u8>> = nodes.iter().map(|n| st.render_file(n).0).collect();
8055
    assert_eq!(after[1], before[1]);
8056
    assert_eq!(after[0], b"1\ntwo\n3\n4\n5\n");
8057
}
8058
8059
#[test]
8060
fn many_edited_files_diff_in_parallel() {
8061
    // Enough edited files that the builder diffs them in parallel; the
8062
    // commit must hold exactly what is on disk, and a second snapshot
8063
    // must find nothing left to commit.
8064
    hermetic();
8065
    let dir = tempfile::tempdir().unwrap();
8066
    let root = dir.path();
8067
    let repo = Repo::init(root).unwrap();
8068
    let text = |i: usize, round: usize| {
8069
        let mut s = String::new();
8070
        for line in 0..50 {
8071
            if round > 0 && line % 7 == i % 7 {
8072
                s.push_str(&format!("edited {round} {i} {line}\n"));
8073
            } else {
8074
                s.push_str(&format!("file {i} line {line}\n"));
8075
            }
8076
        }
8077
        if round > 0 && i.is_multiple_of(3) {
8078
            s.push_str("appended\n");
8079
        }
8080
        s
8081
    };
8082
    for i in 0..40 {
8083
        write(root, &format!("d/f{i}.txt"), text(i, 0).as_bytes());
8084
    }
8085
    repo.commit("first", &[]).unwrap();
8086
    for i in 0..40 {
8087
        write(root, &format!("d/f{i}.txt"), text(i, 1).as_bytes());
8088
    }
8089
    let h = repo.commit("edit every file", &[]).unwrap();
8090
    let snap = repo.load_state(&[h]).unwrap().materialize();
8091
    for i in 0..40 {
8092
        let want = text(i, 1);
8093
        assert!(
8094
            matches!(&snap.files[&format!("d/f{i}.txt")].content, FileContent::Text { bytes, .. } if bytes == want.as_bytes()),
8095
            "d/f{i}.txt as committed"
8096
        );
8097
    }
8098
    assert!(
8099
        repo.commit("nothing", &[]).is_err(),
8100
        "nothing left to commit"
8101
    );
8102
}
8103
8104
/// oxygen#56: after a fetch, how a bookmark stands against its remote copy
8105
/// is known (fetch printed "up to date" while main was behind), a change
8106
/// only fetched resolves and says where it is, and a checkout whose only
8107
/// remote is not `origin` uses that one.
8108
#[test]
8109
fn a_fetched_change_shows_as_behind_and_resolves() {
8110
    hermetic();
8111
    let dir = tempfile::tempdir().unwrap();
8112
    let root = dir.path();
8113
    let origin = Repo::init(&root.join("origin")).unwrap();
8114
    drop(origin);
8115
    let url = root.join("origin").to_string_lossy().to_string();
8116
    let a = Repo::clone(&url, &root.join("a"))
8117
        .unwrap()
8118
        .with_home(root.join("home-a"));
8119
    write(&root.join("a"), "f.txt", b"one\n");
8120
    a.commit("one", &[]).unwrap();
8121
    a.push("origin", false).unwrap();
8122
    let b = Repo::clone(&url, &root.join("b"))
8123
        .unwrap()
8124
        .with_home(root.join("home-b"));
8125
    assert_eq!(b.tracking("origin", "main").unwrap(), Some((0, 0)));
8126
8127
    write(&root.join("a"), "f.txt", b"one\ntwo\n");
8128
    let h2 = a.commit("two", &[]).unwrap();
8129
    a.push("origin", false).unwrap();
8130
    b.fetch("origin").unwrap();
8131
    // Fetched, not pulled: one behind, the change found and placed.
8132
    assert_eq!(b.tracking("origin", "main").unwrap(), Some((0, 1)));
8133
    assert_eq!(b.tracking("origin", "nope").unwrap(), None);
8134
    assert_eq!(
8135
        b.resolve_change(&format!("#{}", &h2.to_hex()[..12]))
8136
            .unwrap(),
8137
        h2
8138
    );
8139
    assert_eq!(
8140
        b.remote_only_location(&h2).unwrap().as_deref(),
8141
        Some("origin/main")
8142
    );
8143
    // Fetching again changes nothing: still behind, which is what the
8144
    // CLI now says rather than "up to date".
8145
    b.fetch("origin").unwrap();
8146
    assert_eq!(b.tracking("origin", "main").unwrap(), Some((0, 1)));
8147
    b.pull("origin").unwrap();
8148
    assert_eq!(b.tracking("origin", "main").unwrap(), Some((0, 0)));
8149
    assert_eq!(b.remote_only_location(&h2).unwrap(), None);
8150
8151
    // One remote, not called origin: it is the default.
8152
    let mut c = Repo::init(&root.join("c")).unwrap();
8153
    assert_eq!(c.default_remote(), "origin");
8154
    c.config.set("remote.earth.url", &url).unwrap();
8155
    assert_eq!(c.default_remote(), "earth");
8156
    c.config.set("remote.origin.url", &url).unwrap();
8157
    assert_eq!(c.default_remote(), "origin");
8158
}
8159
8160
/// oxygen#57: a clone from a relative local path records the remote as an
8161
/// absolute path, so fetch still finds it from inside the clone.
8162
#[test]
8163
fn a_clone_from_a_relative_path_records_it_absolute() {
8164
    hermetic();
8165
    let dir = tempfile::tempdir().unwrap();
8166
    let root = dir.path();
8167
    Repo::init(&root.join("origin")).unwrap();
8168
    let rel = crate::protocol::stored_url("relative/repo");
8169
    assert!(std::path::Path::new(&rel).is_absolute(), "{rel}");
8170
    assert_eq!(
8171
        crate::protocol::stored_url("https://hub.example/o/n"),
8172
        "https://hub.example/o/n"
8173
    );
8174
    assert!(crate::protocol::stored_url("file://x").starts_with("file:///"));
8175
    assert!(crate::protocol::stored_url("dir://x").starts_with("dir:///"));
8176
    // A bucket is kept as written: it is not a path.
8177
    assert_eq!(
8178
        crate::protocol::stored_url("s3://bucket/prefix?profile=p"),
8179
        "s3://bucket/prefix?profile=p"
8180
    );
8181
    let url = root.join("origin").to_string_lossy().to_string();
8182
    let b = Repo::clone(&url, &root.join("b")).unwrap();
8183
    assert_eq!(b.config.remotes["origin"], url);
8184
    b.fetch("origin").unwrap();
8185
}
8186
8187
/// oxygen#60 and #61: a workspace added on a bookmark is on that bookmark,
8188
/// and gets its subrepos at their pins from this workspace's copies, with
8189
/// their remotes pointing where the subrepos come from.
8190
#[test]
8191
fn a_workspace_added_on_a_bookmark_is_on_it_with_its_subrepos() {
8192
    hermetic();
8193
    let dir = tempfile::tempdir().unwrap();
8194
    let root = dir.path();
8195
    Repo::init(&root.join("lib-origin")).unwrap();
8196
    let lib_url = root.join("lib-origin").to_string_lossy().to_string();
8197
    let lib = Repo::clone(&lib_url, &root.join("lib"))
8198
        .unwrap()
8199
        .with_home(root.join("home"));
8200
    write(&root.join("lib"), "lib.txt", b"v1\n");
8201
    let l1 = lib.commit("lib v1", &[]).unwrap();
8202
    assert!(lib.push("origin", false).unwrap()[0].ok);
8203
8204
    let app_dir = root.join("app");
8205
    let app = Repo::init(&app_dir).unwrap().with_home(root.join("home"));
8206
    write(&app_dir, "main.txt", b"app\n");
8207
    app.submodule_add(&lib_url, "libs/lib", None).unwrap();
8208
    app.commit("app with lib", &[]).unwrap();
8209
    // A second bookmark, and the main workspace on another.
8210
    app.bookmark_create("develop", None).unwrap();
8211
    app.bookmark_create("feature", None).unwrap();
8212
    let mut app = app;
8213
    app.bookmark_switch("feature", false).unwrap();
8214
    assert_eq!(app.config.bookmark, "feature");
8215
8216
    // The library's origin goes away: the subrepo must come from here.
8217
    std::fs::rename(root.join("lib-origin"), root.join("lib-origin-gone")).unwrap();
8218
    let heads = app.resolve_heads("develop").unwrap();
8219
    let ws = app
8220
        .workspace_add_on(&root.join("ws"), Some(&heads), Some("develop"))
8221
        .unwrap();
8222
    assert_eq!(
8223
        ws.config.bookmark, "develop",
8224
        "the new workspace is on develop"
8225
    );
8226
    assert_eq!(
8227
        app.config.bookmark, "feature",
8228
        "and this one stays on its own"
8229
    );
8230
    let sub = Repo::open(&root.join("ws/libs/lib")).unwrap();
8231
    assert_eq!(
8232
        sub.config.remotes["origin"], lib_url,
8233
        "its origin is the subrepo's URL"
8234
    );
8235
    assert_eq!(sub.bookmark_heads().unwrap(), vec![l1], "at its pin");
8236
    assert_eq!(
8237
        std::fs::read(root.join("ws/libs/lib/lib.txt")).unwrap(),
8238
        b"v1\n"
8239
    );
8240
}
8241
8242
/// Revsets (docs/revset_query_language.md): symbols, relations, set
8243
/// operators and the predicates, over a small graph with two heads and
8244
/// a rename.
8245
#[test]
8246
fn revsets_select_changes_by_relation_author_text_date_and_path() {
8247
    hermetic();
8248
    let dir = tempfile::tempdir().unwrap();
8249
    let root = dir.path();
8250
    let mut repo = Repo::init(root).unwrap().with_home(root.join("home"));
8251
    repo.create_identity("Ada", "[email protected]", IdentityScope::User)
8252
        .unwrap();
8253
    write(root, "src/a.rs", b"one\n");
8254
    let a = repo.commit("first: add a", &[]).unwrap();
8255
    write(root, "src/a.rs", b"one\ntwo\n");
8256
    let b = repo.commit("second: grow a", &[]).unwrap();
8257
    // A second head, independent of b: a new file on top of a.
8258
    repo.checkout(&[a], false, "checkout a").unwrap();
8259
    write(root, "docs/notes.md", b"notes\n");
8260
    let c = repo.commit("third: notes", &[]).unwrap();
8261
    // Back to both heads, then rename a.rs: the node keeps its identity.
8262
    repo.checkout(&repo.bookmark_heads().unwrap(), false, "checkout main")
8263
        .unwrap();
8264
    fs::remove_file(root.join("src/a.rs")).unwrap();
8265
    write(root, "src/z.rs", b"one\ntwo\n");
8266
    let d = repo.commit("fourth: rename a to z", &[]).unwrap();
8267
    let wc = repo.working_copy().unwrap().0;
8268
    // A saved revset is checked when set.
8269
    repo.set_user_config("revset.mine", "author(me) & ::main")
8270
        .unwrap();
8271
    assert!(repo.set_user_config("revset.bad", "a &").is_err());
8272
    let set = |src: &str| -> Vec<ChangeHash> {
8273
        let mut v = repo.revset(src).unwrap().hashes;
8274
        v.sort();
8275
        v
8276
    };
8277
    let sorted = |hs: &[ChangeHash]| -> Vec<ChangeHash> {
8278
        let mut v = hs.to_vec();
8279
        v.sort();
8280
        v
8281
    };
8282
8283
    // Changes commute: a new file depends on nothing and the rename on the
8284
    // file's creation, so the graph is a, b->a, d->a, c, and the working
8285
    // copy on the three heads b, c, d.
8286
    let heads = sorted(&repo.bookmark_heads().unwrap());
8287
    let meta = |h: &ChangeHash| repo.store().get_change_meta(h).unwrap();
8288
    assert!(heads.contains(&d) && heads.contains(&c));
8289
    // Symbols and closures.
8290
    assert_eq!(set("main"), heads);
8291
    assert_eq!(set("::main"), sorted(&[a, b, c, d]));
8292
    assert_eq!(set("@"), vec![wc]);
8293
    assert_eq!(set("::@"), sorted(&[a, b, c, d, wc]));
8294
    assert_eq!(set(&format!("::#{}", b.short(12))), sorted(&[a, b]));
8295
    assert_eq!(set(&format!("#{}::", a.short(12))), sorted(&[a, b, d, wc]));
8296
    assert_eq!(
8297
        set(&format!("#{}::#{}", a.short(12), b.short(12))),
8298
        sorted(&[a, b])
8299
    );
8300
    // Ranges: what main has beyond b, and `..` forms.
8301
    assert_eq!(set(&format!("#{}..main", b.short(12))), sorted(&[c, d]));
8302
    assert_eq!(set(&format!("#{}..", c.short(12))), sorted(&[a, b, d, wc]));
8303
    assert_eq!(set("..main"), sorted(&[a, b, c, d]));
8304
    // Operators and precedence: ~ binds tighter than &, & than |.
8305
    assert_eq!(
8306
        set(&format!("::main ~ #{}", d.short(12))),
8307
        sorted(&[a, b, c])
8308
    );
8309
    assert_eq!(
8310
        set(&format!("::main & #{} | #{}", b.short(12), c.short(12))),
8311
        sorted(&[b, c])
8312
    );
8313
    assert_eq!(set("all() ~ ::main"), vec![wc]);
8314
    // Relations.
8315
    let mut head_deps: Vec<ChangeHash> = heads.iter().flat_map(|h| meta(h).deps).collect();
8316
    head_deps.sort();
8317
    head_deps.dedup();
8318
    assert_eq!(set("deps(main)"), head_deps);
8319
    let on_a: Vec<ChangeHash> = [b, c, d]
8320
        .into_iter()
8321
        .filter(|h| meta(h).deps.contains(&a))
8322
        .collect();
8323
    assert_eq!(set(&format!("dependents(#{})", a.short(12))), sorted(&on_a));
8324
    assert_eq!(set("heads(::main)"), heads);
8325
    assert_eq!(set("roots(::main)"), sorted(&[a, c]));
8326
    assert_eq!(
8327
        set(&format!(
8328
            "heads(#{} | #{} | #{})",
8329
            a.short(12),
8330
            b.short(12),
8331
            c.short(12)
8332
        )),
8333
        sorted(&[b, c])
8334
    );
8335
    assert_eq!(set("latest(::main, 1)"), vec![d]);
8336
    assert_eq!(set("kind(working-copy)"), vec![wc]);
8337
    assert_eq!(set("none()"), vec![]);
8338
    // Predicates: author by name, email, key prefix and `me`.
8339
    let key = repo.config.author_key.unwrap();
8340
    assert_eq!(set("author(ada) & ::main"), sorted(&[a, b, c, d]));
8341
    assert_eq!(set("author(\"[email protected]\") & ::main").len(), 4);
8342
    assert_eq!(set(&format!("author({}) & ::main", key.short(12))).len(), 4);
8343
    assert_eq!(set("author(me) & ::main").len(), 4);
8344
    assert_eq!(set("author(nobody)"), vec![]);
8345
    assert_eq!(set("description(notes)"), vec![c]);
8346
    assert_eq!(set("description(\"rename a\")"), vec![d]);
8347
    assert_eq!(set("date(-1h..) & ::main").len(), 4);
8348
    assert_eq!(set("date(..2000-01-01)"), vec![]);
8349
    // touches follows the node through the rename, in the current state.
8350
    assert_eq!(set("touches(\"src/z.rs\")"), sorted(&[a, b, d]));
8351
    assert_eq!(set("touches(\"src/**\") & ::main"), sorted(&[a, b, d]));
8352
    assert_eq!(set("touches(\"docs/*\")"), vec![c]);
8353
    assert_eq!(set("touches(\"nothing/*\")"), vec![]);
8354
    // Newest first in the result order.
8355
    assert_eq!(repo.revset("::main").unwrap().hashes[0], d);
8356
    // The saved revset, and errors that say what is wrong.
8357
    assert_eq!(set("mine()").len(), 4);
8358
    let e = repo.revset("nosuch()").unwrap_err().to_string();
8359
    assert!(e.contains("unknown function nosuch()"), "{e}");
8360
    let e = repo.revset("main &").unwrap_err().to_string();
8361
    assert!(e.contains("at character"), "{e}");
8362
    let e = repo.revset("zzzz").unwrap_err().to_string();
8363
    assert!(e.contains("no change matches"), "{e}");
8364
    let e = repo
8365
        .revset_with_budget("::main", std::time::Duration::ZERO)
8366
        .unwrap_err()
8367
        .to_string();
8368
    assert!(e.contains("budget"), "{e}");
8369
    // The log entries carry the bookmark's heads and the working copy.
8370
    let entries = repo.log_revset("::@").unwrap();
8371
    assert!(entries[0].is_working_copy && entries.iter().any(|e| e.is_head && e.hash == d));
8372
    // Trust predicates (§2.4): nothing is signed yet (core.sign = seal, no
8373
    // push); then a signed change, a tag, and a revocation.
8374
    assert_eq!(set("unsigned() & ::main"), sorted(&[a, b, c, d]));
8375
    assert_eq!(set("signed_by(me)"), vec![]);
8376
    repo.sign_change(&d).unwrap();
8377
    assert_eq!(set("signed_by(me)"), vec![d]);
8378
    assert_eq!(set("signed_by([email protected])"), vec![d]);
8379
    assert_eq!(set(&format!("signed_by({})", key.short(12))), vec![d]);
8380
    assert_eq!(set("unsigned() & ::main"), sorted(&[a, b, c]));
8381
    assert_eq!(set("delegated()"), vec![]);
8382
    assert_eq!(set("revoked()"), vec![]);
8383
    assert_eq!(set("attested(tag)"), vec![]);
8384
    repo.tag_create("v1", &[b], "first").unwrap();
8385
    assert_eq!(set("attested(tag)"), sorted(&[a, b]));
8386
    assert_eq!(set("attested(tag) & unsigned()"), sorted(&[a, b]));
8387
    assert_eq!(set("attested(receipt)"), vec![]);
8388
    assert_eq!(set("built(test)"), vec![]);
8389
    let e = repo.revset("attested(seal)").unwrap_err().to_string();
8390
    assert!(e.contains("tag, receipt or ref"), "{e}");
8391
    repo.revoke_identity(&key, "test").unwrap();
8392
    assert_eq!(set("revoked()"), vec![d]);
8393
    assert_eq!(set("signed_by(me) ~ revoked()"), vec![]);
8394
}
8395
8396
#[test]
8397
fn a_rotation_is_recorded_wherever_the_old_key_was_named() {
8398
    let dir = tempfile::tempdir().unwrap();
8399
    let root = dir.path();
8400
    let home = root.join("home");
8401
    // Ada's identity lives in the user file; repository `a` pins the same
8402
    // key in its own file, repository `b` names none.
8403
    let mut a = Repo::init(&root.join("a")).unwrap().with_home(&home);
8404
    let (key, _) = a
8405
        .create_identity("Ada", "[email protected]", IdentityScope::User)
8406
        .unwrap();
8407
    a.config.set("author.key", &key.to_hex()).unwrap();
8408
    a.save_config().unwrap();
8409
    let agent = SecretKey::generate().identity("Agent", "[email protected]", 1);
8410
    let r = a
8411
        .delegate_add(agent.clone(), crate::identity::Scope::CHANGES, None)
8412
        .unwrap();
8413
    assert_eq!(
8414
        read_config_file(&home.join("config.toml")).unwrap()["author.key"],
8415
        r.new.to_hex(),
8416
        "the user file follows"
8417
    );
8418
    assert_eq!(
8419
        read_config_file(&root.join("a/.oxy/config")).unwrap()["author.key"],
8420
        r.new.to_hex(),
8421
        "the pinning repository follows"
8422
    );
8423
    let b = Repo::init(&root.join("b")).unwrap().with_home(&home);
8424
    assert_eq!(
8425
        b.config.author_key,
8426
        Some(r.new),
8427
        "a checkout without a pin follows the user file"
8428
    );
8429
    // A repository-scoped identity leaves the user file alone.
8430
    let other_home = root.join("home2");
8431
    let mut c = Repo::init(&root.join("c")).unwrap().with_home(&other_home);
8432
    let (ck, _) = c
8433
        .create_identity("Cy", "[email protected]", IdentityScope::Repo)
8434
        .unwrap();
8435
    assert!(!other_home.join("config.toml").exists());
8436
    let r2 = c.rotate_identity().unwrap();
8437
    assert_ne!(r2.new, ck);
8438
    assert_eq!(
8439
        read_config_file(&root.join("c/.oxy/config")).unwrap()["author.key"],
8440
        r2.new.to_hex()
8441
    );
8442
    assert!(
8443
        !other_home.join("config.toml").exists(),
8444
        "a repository-scoped identity stays repository-scoped"
8445
    );
8446
    // Several delegates in one rotation; a repeat is refused.
8447
    let (d1, d2) = (
8448
        SecretKey::generate().identity("D1", "d1@x", 1),
8449
        SecretKey::generate().identity("D2", "d2@x", 1),
8450
    );
8451
    let r3 = c
8452
        .delegate_add_many(vec![d1.clone(), d2], crate::identity::Scope::CHANGES, None)
8453
        .unwrap();
8454
    assert_eq!(r3.identity.delegates.len(), 2);
8455
    assert!(c
8456
        .delegate_add(d1, crate::identity::Scope::CHANGES, None)
8457
        .is_err());
8458
}
8459
8460
/// Two unrelated histories that both add the same file, joined by two
8461
/// independent merges on two branches, then those branches merged: Git
8462
/// merges identical additions cleanly, and the import must too (#71,
8463
/// found in VS Code's history).
8464
#[test]
8465
fn git_import_joins_unrelated_histories_that_add_the_same_file() {
8466
    // Batches of one: every merge renders apart from the state, where a
8467
    // file whose graph the state had built came out empty (#71).
8468
    crate::repo::git::set_merge_batch_for_tests(Some(1));
8469
    hermetic();
8470
    if std::process::Command::new("git")
8471
        .arg("--version")
8472
        .output()
8473
        .is_err()
8474
    {
8475
        eprintln!("git not installed; skipping");
8476
        return;
8477
    }
8478
    let dir = tempfile::tempdir().unwrap();
8479
    let root = dir.path();
8480
    let g = root.join("src.git");
8481
    fs::create_dir_all(&g).unwrap();
8482
    let git = |args: &[&str]| -> String {
8483
        let out = std::process::Command::new("git")
8484
            .arg("-C")
8485
            .arg(&g)
8486
            .args([
8487
                "-c",
8488
                "user.name=Grace",
8489
                "-c",
8490
                "[email protected]",
8491
                "-c",
8492
                "commit.gpgsign=false",
8493
            ])
8494
            .args(args)
8495
            .output()
8496
            .unwrap();
8497
        assert!(
8498
            out.status.success(),
8499
            "git {args:?}: {}",
8500
            String::from_utf8_lossy(&out.stderr)
8501
        );
8502
        String::from_utf8_lossy(&out.stdout).trim().to_string()
8503
    };
8504
    let text = b"/* header */\nconst a = 1;\nconst b = 2;\n";
8505
    // History A: main.
8506
    git(&["init", "-q", "-b", "main"]);
8507
    write(&g, "gulpfile.js", text);
8508
    write(&g, "a.txt", b"a\n");
8509
    git(&["add", "."]);
8510
    git(&["commit", "-q", "-m", "A root"]);
8511
    // History B: an unrelated root adding the same file, identical.
8512
    git(&["checkout", "-q", "--orphan", "fork"]);
8513
    git(&["rm", "-q", "-r", "--cached", "."]);
8514
    for f in ["gulpfile.js", "a.txt"] {
8515
        let _ = fs::remove_file(g.join(f));
8516
    }
8517
    write(&g, "gulpfile.js", text);
8518
    write(&g, "b.txt", b"b\n");
8519
    git(&["add", "."]);
8520
    git(&["commit", "-q", "-m", "B root"]);
8521
    // Two branches from main, each joining B on its own.
8522
    git(&["checkout", "-q", "-b", "one", "main"]);
8523
    git(&[
8524
        "merge",
8525
        "-q",
8526
        "--no-ff",
8527
        "--allow-unrelated-histories",
8528
        "-m",
8529
        "join on one",
8530
        "fork",
8531
    ]);
8532
    git(&["checkout", "-q", "-b", "two", "main"]);
8533
    write(&g, "a.txt", b"a\ntwo\n");
8534
    git(&["commit", "-q", "-am", "work on two"]);
8535
    git(&[
8536
        "merge",
8537
        "-q",
8538
        "--no-ff",
8539
        "--allow-unrelated-histories",
8540
        "-m",
8541
        "join on two",
8542
        "fork",
8543
    ]);
8544
    // Then the two joins meet, and the file is reformatted after.
8545
    git(&["checkout", "-q", "main"]);
8546
    git(&["merge", "-q", "--no-ff", "-m", "merge one", "one"]);
8547
    git(&["merge", "-q", "--no-ff", "-m", "merge two", "two"]);
8548
    write(
8549
        &g,
8550
        "gulpfile.js",
8551
        b"/* header */\nconst a = 1;\nconst b = 3;\n",
8552
    );
8553
    git(&["commit", "-q", "-am", "after"]);
8554
8555
    let dest = root.join("dest");
8556
    let repo = Repo::init(&dest).unwrap().with_home(root.join("home"));
8557
    repo.import_git(&g, "main").unwrap();
8558
    let v = repo.verify_git_import(&g, "main").unwrap();
8559
    assert!(v.mismatches.is_empty(), "{:?}", v.mismatches);
8560
    assert_eq!(
8561
        fs::read(dest.join("gulpfile.js")).unwrap(),
8562
        b"/* header */\nconst a = 1;\nconst b = 3;\n"
8563
    );
8564
}
8565
8566
/// As above, but the two joins keep different copies (each branch had a
8567
/// different version when it joined), and later work edits each copy:
8568
/// the shape of VS Code's c67ef57cda90 (#71).
8569
#[test]
8570
fn git_import_joins_where_each_join_kept_a_different_copy() {
8571
    // Batches of one: every merge renders apart from the state, where a
8572
    // file whose graph the state had built came out empty (#71).
8573
    crate::repo::git::set_merge_batch_for_tests(Some(1));
8574
    hermetic();
8575
    if std::process::Command::new("git")
8576
        .arg("--version")
8577
        .output()
8578
        .is_err()
8579
    {
8580
        eprintln!("git not installed; skipping");
8581
        return;
8582
    }
8583
    let dir = tempfile::tempdir().unwrap();
8584
    let root = dir.path();
8585
    let g = root.join("src.git");
8586
    fs::create_dir_all(&g).unwrap();
8587
    let run = |args: &[&str]| {
8588
        std::process::Command::new("git")
8589
            .arg("-C")
8590
            .arg(&g)
8591
            .args([
8592
                "-c",
8593
                "user.name=Grace",
8594
                "-c",
8595
                "[email protected]",
8596
                "-c",
8597
                "commit.gpgsign=false",
8598
            ])
8599
            .args(args)
8600
            .output()
8601
            .unwrap()
8602
    };
8603
    let git = |args: &[&str]| -> String {
8604
        let out = run(args);
8605
        assert!(
8606
            out.status.success(),
8607
            "git {args:?}: {}",
8608
            String::from_utf8_lossy(&out.stderr)
8609
        );
8610
        String::from_utf8_lossy(&out.stdout).trim().to_string()
8611
    };
8612
    git(&["init", "-q", "-b", "main"]);
8613
    write(
8614
        &g,
8615
        "gulpfile.js",
8616
        b"/* header */\nconst a = 1;\nconst b = 2;\n",
8617
    );
8618
    git(&["add", "."]);
8619
    git(&["commit", "-q", "-m", "A root"]);
8620
    write(
8621
        &g,
8622
        "gulpfile.js",
8623
        b"/* header */\nconst a = 1;\n\nconst b = 2;\n",
8624
    );
8625
    git(&["commit", "-q", "-am", "whitespace"]);
8626
    git(&["checkout", "-q", "--orphan", "fork"]);
8627
    git(&["rm", "-q", "-r", "--cached", "."]);
8628
    let _ = fs::remove_file(g.join("gulpfile.js"));
8629
    write(
8630
        &g,
8631
        "gulpfile.js",
8632
        b"/* header */\nconst a = 1;\nconst b = 2;\nconst c = 3;\n",
8633
    );
8634
    git(&["add", "."]);
8635
    git(&["commit", "-q", "-m", "B root"]);
8636
    // Branch one joins B keeping main's copy; branch two keeps B's.
8637
    for (branch, keep) in [("one", "ours"), ("two", "theirs")] {
8638
        git(&["checkout", "-q", "-b", branch, "main"]);
8639
        let _ = run(&[
8640
            "merge",
8641
            "-q",
8642
            "--no-ff",
8643
            "--allow-unrelated-histories",
8644
            "-m",
8645
            "join",
8646
            "fork",
8647
        ]);
8648
        git(&["checkout", &format!("--{keep}"), "gulpfile.js"]);
8649
        git(&["add", "gulpfile.js"]);
8650
        git(&["commit", "-q", "-m", &format!("join on {branch}")]);
8651
    }
8652
    // Each branch then edits its copy.
8653
    git(&["checkout", "-q", "one"]);
8654
    write(
8655
        &g,
8656
        "gulpfile.js",
8657
        b"/* header */\nconst a = 1;\n\nconst b = 2;\n// tslint\n",
8658
    );
8659
    git(&["commit", "-q", "-am", "tslint on one"]);
8660
    git(&["checkout", "-q", "two"]);
8661
    write(
8662
        &g,
8663
        "gulpfile.js",
8664
        b"/* header */\nconst a = 1;\nconst b = 2;\nconst c = 3;\n// fmt\n",
8665
    );
8666
    write(&g, "extra.txt", b"x\n");
8667
    write(&g, "more.txt", b"m\n");
8668
    git(&["add", "."]);
8669
    git(&["commit", "-q", "-am", "fmt on two"]);
8670
    // They meet: resolved by hand.
8671
    git(&["checkout", "-q", "one"]);
8672
    let _ = run(&["merge", "-q", "--no-ff", "-m", "merge two", "two"]);
8673
    write(
8674
        &g,
8675
        "gulpfile.js",
8676
        b"/* header */\nconst a = 1;\nconst b = 2;\nconst c = 3;\n// tslint\n// fmt\n",
8677
    );
8678
    git(&["add", "gulpfile.js"]);
8679
    git(&["commit", "-q", "-m", "merge two into one"]);
8680
8681
    let dest = root.join("dest");
8682
    let repo = Repo::init(&dest).unwrap().with_home(root.join("home"));
8683
    repo.import_git(&g, "one").unwrap();
8684
    let v = repo.verify_git_import(&g, "one").unwrap();
8685
    assert!(v.mismatches.is_empty(), "{:?}", v.mismatches);
8686
}
8687
8688
/// oxygen#68: on a store that is not this disk's directory, the operation
8689
/// head is the store's reference record, moved by compare-and-swap. Two
8690
/// handles recording from the same head both get through, merged; a swap
8691
/// from a stale version is refused; a second repository cannot start on a
8692
/// store that already holds one.
8693
#[test]
8694
fn over_a_store_the_operation_head_moves_by_compare_and_swap() {
8695
    use crate::strata::{MemoryStore, Store as _};
8696
    let backend = std::sync::Arc::new(MemoryStore::new());
8697
    crate::store::TEST_BACKEND.with(|t| *t.borrow_mut() = Some(backend.clone()));
8698
    let dir = tempfile::tempdir().unwrap();
8699
    let a = Repo::init(dir.path()).unwrap();
8700
    assert!(
8701
        !dir.path().join(".oxy/ops/head").exists(),
8702
        "the head is not a file"
8703
    );
8704
    let (h0, op0) = a.head_op().unwrap();
8705
    let record = backend
8706
        .read_ref(HEAD_RECORD)
8707
        .unwrap()
8708
        .expect("the head is the store's record");
8709
    assert_eq!(String::from_utf8(record.0).unwrap(), h0.to_hex());
8710
8711
    let b = Repo::open(dir.path()).unwrap();
8712
    let state = a.store.put_state(&StateObject::new(vec![])).unwrap();
8713
    let mut va = op0.view.clone();
8714
    va.bookmarks.insert("from-a".into(), state);
8715
    let mut vb = op0.view.clone();
8716
    vb.bookmarks.insert("from-b".into(), state);
8717
    let rb = b.record_op(&[h0], "bookmark from-b", vb).unwrap();
8718
    assert_eq!(b.head_ref().unwrap(), rb);
8719
    // a recorded from h0 too: the head moved, so the two are merged.
8720
    let ra = a.record_op(&[h0], "bookmark from-a", va).unwrap();
8721
    let (head, op) = Repo::open(dir.path()).unwrap().head_op().unwrap();
8722
    assert_eq!(head, ra);
8723
    assert!(
8724
        op.command.ends_with("(merged with a concurrent operation)"),
8725
        "{}",
8726
        op.command
8727
    );
8728
    assert_eq!(op.parents, vec![rb, op.parents[1]]);
8729
    assert!(op.view.bookmarks.contains_key("from-a") && op.view.bookmarks.contains_key("from-b"));
8730
8731
    // A swap from a version that is no longer current moves nothing.
8732
    let (h, v) = a.read_head().unwrap();
8733
    assert!(b.swap_head(&rb, v.as_ref()).unwrap());
8734
    assert!(!a.swap_head(&h, v.as_ref()).unwrap(), "stale");
8735
    a.refresh().unwrap();
8736
    assert_eq!(a.head_ref().unwrap(), rb);
8737
8738
    let other = tempfile::tempdir().unwrap();
8739
    let err = Repo::init(other.path())
8740
        .err()
8741
        .expect("the store already holds a log")
8742
        .to_string();
8743
    assert!(
8744
        err.contains("already holds a repository's operation log"),
8745
        "{err}"
8746
    );
8747
    crate::store::TEST_BACKEND.with(|t| *t.borrow_mut() = None);
8748
}
8749
8750
/// oxygen#68: a repository kept on a store (`storage.url`) holds its
8751
/// objects and operation head there, with `.oxy/cache` in front: it works
8752
/// as one on disk does, reopens, and survives losing its cache.
8753
#[test]
8754
fn a_repository_runs_on_a_store_with_a_cache_in_front() {
8755
    hermetic();
8756
    if std::env::var_os("OXY_STORE_BACKEND").is_some() {
8757
        return;
8758
    }
8759
    let dir = tempfile::tempdir().unwrap();
8760
    let (root, bucket) = (dir.path().join("work"), dir.path().join("bucket"));
8761
    let url = format!("dir://{}", bucket.display());
8762
    let repo = Repo::init_on(&root, [7; 16], Some(&url)).unwrap();
8763
    assert_eq!(repo.config.storage_url.as_deref(), Some(url.as_str()));
8764
    write(&root, "a.txt", b"one\n");
8765
    let h1 = repo.commit("First", &[]).unwrap();
8766
    write(&root, "a.txt", b"one\ntwo\n");
8767
    let h2 = repo.commit("Second", &[]).unwrap();
8768
    assert!(
8769
        !root.join(".oxy/ops/head").exists(),
8770
        "the head is in the store"
8771
    );
8772
    assert!(bucket.join("ops/head").is_file());
8773
    assert!(root.join(".oxy/cache").is_dir());
8774
    drop(repo);
8775
8776
    // Reopened, and again with no cache at all: everything comes from the store.
8777
    for drop_cache in [false, true] {
8778
        if drop_cache {
8779
            std::fs::remove_dir_all(root.join(".oxy/cache")).unwrap();
8780
        }
8781
        let repo = Repo::open(&root).unwrap();
8782
        let log: Vec<String> = repo
8783
            .op_log()
8784
            .unwrap()
8785
            .into_iter()
8786
            .map(|(_, op)| op.command)
8787
            .collect();
8788
        assert!(log.len() >= 3, "{log:?}");
8789
        assert_eq!(repo.store().get_change(&h1).unwrap().message, "First");
8790
        let heads = repo
8791
            .store()
8792
            .get_state(&repo.view().unwrap().bookmarks["main"])
8793
            .unwrap()
8794
            .heads;
8795
        assert_eq!(heads, vec![h2]);
8796
        assert_eq!(
8797
            repo.load_state(&heads).unwrap().materialize().files.len(),
8798
            1
8799
        );
8800
    }
8801
8802
    // A second repository cannot start on the same store.
8803
    let err = Repo::init_on(&dir.path().join("other"), [8; 16], Some(&url))
8804
        .err()
8805
        .unwrap()
8806
        .to_string();
8807
    assert!(
8808
        err.contains("already holds a repository's operation log"),
8809
        "{err}"
8810
    );
8811
    let err = Repo::init_on(&dir.path().join("third"), [9; 16], Some("nope://x"))
8812
        .err()
8813
        .unwrap()
8814
        .to_string();
8815
    assert!(err.contains("cannot open that kind of store"), "{err}");
8816
}
8817
8818
/// oxygen#75: the prompt's quick check agrees with status in a repository
8819
/// with a subrepo: clean after a commit, dirty when the subrepo moves to
8820
/// another state, clean again once that pin is committed. (It compared the
8821
/// subrepo's directory as if it were a file, so it was always dirty.)
8822
#[test]
8823
fn the_quick_dirty_check_compares_a_subrepo_by_its_pin() {
8824
    hermetic();
8825
    let dir = tempfile::tempdir().unwrap();
8826
    let root = dir.path();
8827
    let _lib_origin = Repo::init(&root.join("lib-origin")).unwrap();
8828
    let lib_url = root.join("lib-origin").to_string_lossy().to_string();
8829
    let lib = Repo::clone(&lib_url, &root.join("lib"))
8830
        .unwrap()
8831
        .with_home(root.join("home"));
8832
    write(&root.join("lib"), "lib.txt", b"v1\n");
8833
    lib.commit("lib v1", &[]).unwrap();
8834
    assert!(lib.push("origin", false).unwrap()[0].ok);
8835
    let app_dir = root.join("app");
8836
    let app = Repo::init(&app_dir).unwrap().with_home(root.join("home"));
8837
    write(&app_dir, "main.txt", b"app\n");
8838
    app.submodule_add(&lib_url, "libs/lib", None).unwrap();
8839
    app.commit("app with lib", &[]).unwrap();
8840
    // Out of the racy window, so the stat-only path decides.
8841
    std::thread::sleep(std::time::Duration::from_millis(2100));
8842
    let reopen = || Repo::open(&app_dir).unwrap();
8843
    assert_eq!(
8844
        reopen().quick_dirty().unwrap(),
8845
        Some(false),
8846
        "clean, as status says"
8847
    );
8848
    let nested = Repo::open(&app_dir.join("libs/lib")).unwrap();
8849
    write(&app_dir.join("libs/lib"), "lib.txt", b"v2\n");
8850
    nested.commit("lib v2", &[]).unwrap();
8851
    assert_eq!(
8852
        reopen().quick_dirty().unwrap(),
8853
        Some(true),
8854
        "the subrepo moved"
8855
    );
8856
    reopen().commit("pin lib v2", &[]).unwrap();
8857
    std::thread::sleep(std::time::Duration::from_millis(2100));
8858
    assert_eq!(
8859
        reopen().quick_dirty().unwrap(),
8860
        Some(false),
8861
        "the new pin is committed"
8862
    );
8863
}
8864
8865
#[test]
8866
fn a_module_entry_that_was_never_added_is_reported_as_unpinned() {
8867
    // oxygen#72: a .oxymodules section with no subrepo behind it.
8868
    hermetic();
8869
    let dir = tempfile::tempdir().unwrap();
8870
    let root = dir.path();
8871
    let _lib_origin = Repo::init(&root.join("lib-origin")).unwrap();
8872
    let lib_url = root.join("lib-origin").to_string_lossy().to_string();
8873
    let lib = Repo::clone(&lib_url, &root.join("lib"))
8874
        .unwrap()
8875
        .with_home(root.join("home"));
8876
    write(&root.join("lib"), "lib.txt", b"v1\n");
8877
    lib.commit("lib v1", &[]).unwrap();
8878
    assert!(lib.push("origin", false).unwrap()[0].ok);
8879
    let app_dir = root.join("app");
8880
    let app = Repo::init(&app_dir).unwrap().with_home(root.join("home"));
8881
    write(
8882
        &app_dir,
8883
        ".oxymodules",
8884
        format!("[libs/lib]\nurl = {lib_url}\n").as_bytes(),
8885
    );
8886
    let unpinned = app.unpinned_modules().unwrap();
8887
    assert_eq!(unpinned.len(), 1);
8888
    assert_eq!(unpinned[0].0, "libs/lib");
8889
    assert_eq!(unpinned[0].1.url, lib_url);
8890
    assert!(app.submodule_update(true, &[]).unwrap().is_empty());
8891
    app.submodule_add(&lib_url, "libs/lib", None).unwrap();
8892
    assert!(app.unpinned_modules().unwrap().is_empty(), "added now");
8893
}
8894
8895
#[test]
8896
fn the_bookmark_revset_function_names_only_bookmarks() {
8897
    // oxygen#73: bookmark(NAME) is a bookmark's heads, never a tag or prefix.
8898
    hermetic();
8899
    let dir = tempfile::tempdir().unwrap();
8900
    let repo = Repo::init(dir.path()).unwrap();
8901
    write(dir.path(), "a.txt", b"a\n");
8902
    let a = repo.commit("A", &[]).unwrap();
8903
    write(dir.path(), "b.txt", b"b\n");
8904
    let b = repo.commit("B", &[]).unwrap();
8905
    let mut heads = repo.revset("bookmark(main)").unwrap().hashes;
8906
    heads.sort();
8907
    let mut want = repo.bookmark_heads().unwrap();
8908
    want.sort();
8909
    assert_eq!(heads, want);
8910
    assert!(heads.contains(&b));
8911
    assert_eq!(repo.revset("main").unwrap().hashes.len(), heads.len());
8912
    // A change prefix is a symbol, not a bookmark.
8913
    let prefix = repo.store().get_change_meta(&a).unwrap().change_id.short(8);
8914
    assert!(repo.revset(&prefix).is_ok());
8915
    let e = repo
8916
        .revset(&format!("bookmark({prefix})"))
8917
        .unwrap_err()
8918
        .to_string();
8919
    assert!(e.contains("no such bookmark"), "{e}");
8920
}
8921
8922
#[test]
8923
fn carrying_work_over_a_subrepo_already_at_the_target_pin_is_no_conflict() {
8924
    // oxygen#74: a stale state with .oxymodules but no pin, a newer one
8925
    // pinning the subrepo, and the nested repository on disk at that pin.
8926
    hermetic();
8927
    let dir = tempfile::tempdir().unwrap();
8928
    let root = dir.path();
8929
    let _lib_origin = Repo::init(&root.join("lib-origin")).unwrap();
8930
    let lib_url = root.join("lib-origin").to_string_lossy().to_string();
8931
    let lib = Repo::clone(&lib_url, &root.join("lib"))
8932
        .unwrap()
8933
        .with_home(root.join("home"));
8934
    write(&root.join("lib"), "lib.txt", b"v1\n");
8935
    lib.commit("lib v1", &[]).unwrap();
8936
    assert!(lib.push("origin", false).unwrap()[0].ok);
8937
    let app_dir = root.join("app");
8938
    let app = Repo::init(&app_dir).unwrap().with_home(root.join("home"));
8939
    write(&app_dir, "main.txt", b"app\n");
8940
    app.submodule_add(&lib_url, "libs/lib", None).unwrap();
8941
    // The stale state: registered in .oxymodules, never pinned.
8942
    fs::rename(app_dir.join("libs/lib"), root.join("aside")).unwrap();
8943
    app.commit("initial", &[]).unwrap();
8944
    let stale = app.bookmark_heads().unwrap();
8945
    fs::rename(root.join("aside"), app_dir.join("libs/lib")).unwrap();
8946
    app.commit("pin lib", &[]).unwrap();
8947
    let newer = app.bookmark_heads().unwrap();
8948
    app.checkout(&stale, false, "test").unwrap();
8949
    write(&app_dir, "notes.txt", b"mine\n");
8950
    let (_, carried) = app.checkout_carry(&newer, "main", "test").unwrap();
8951
    assert_eq!(carried, vec!["notes.txt".to_string()]);
8952
    assert!(app_dir.join("notes.txt").exists());
8953
}
8954
8955
#[test]
8956
fn a_bookmark_only_behind_its_remote_catches_up() {
8957
    // oxygen#74: switch takes the remote's state rather than a stale one.
8958
    hermetic();
8959
    let dir = tempfile::tempdir().unwrap();
8960
    let root = dir.path();
8961
    let _origin = Repo::init(&root.join("origin")).unwrap();
8962
    let url = root.join("origin").to_string_lossy().to_string();
8963
    let one = Repo::clone(&url, &root.join("one"))
8964
        .unwrap()
8965
        .with_home(root.join("home"));
8966
    write(&root.join("one"), "a.txt", b"a\n");
8967
    one.commit("A", &[]).unwrap();
8968
    assert!(one.push("origin", false).unwrap()[0].ok);
8969
    let two = Repo::clone(&url, &root.join("two"))
8970
        .unwrap()
8971
        .with_home(root.join("home"));
8972
    write(&root.join("two"), "b.txt", b"b\n");
8973
    two.commit("B", &[]).unwrap();
8974
    assert!(two.push("origin", false).unwrap()[0].ok);
8975
    assert_eq!(one.catch_up_bookmark("main").unwrap(), None, "not fetched");
8976
    one.fetch("origin").unwrap();
8977
    assert_eq!(one.catch_up_bookmark("main").unwrap(), Some(1));
8978
    assert_eq!(one.bookmarks().unwrap()[0].behind, Some(0));
8979
    // Local work the remote lacks: left alone.
8980
    write(&root.join("one"), "c.txt", b"c\n");
8981
    one.commit("C", &[]).unwrap();
8982
    write(&root.join("two"), "d.txt", b"d\n");
8983
    two.commit("D", &[]).unwrap();
8984
    assert!(two.push("origin", false).unwrap()[0].ok);
8985
    one.fetch("origin").unwrap();
8986
    assert_eq!(one.catch_up_bookmark("main").unwrap(), None);
8987
}
8988
8989
#[test]
8990
fn a_bookmark_is_compared_with_a_remote_that_has_it_when_there_is_no_origin() {
8991
    // oxygen#83: remotes earth and gcs, origin removed.
8992
    hermetic();
8993
    let dir = tempfile::tempdir().unwrap();
8994
    let root = dir.path();
8995
    let _up = Repo::init(&root.join("up")).unwrap();
8996
    let url = root.join("up").to_string_lossy().to_string();
8997
    let other = Repo::clone(&url, &root.join("other"))
8998
        .unwrap()
8999
        .with_home(root.join("home"));
9000
    write(&root.join("other"), "a.txt", b"a\n");
9001
    other.commit("a", &[]).unwrap();
9002
    assert!(other.push("origin", false).unwrap()[0].ok);
9003
    let mut one = Repo::clone(&url, &root.join("one"))
9004
        .unwrap()
9005
        .with_home(root.join("home"));
9006
    one.config.set("remote.earth.url", &url).unwrap();
9007
    one.config.set("remote.gcs.url", &url).unwrap();
9008
    one.config.set("remote.origin.url", "").unwrap();
9009
    one.save_config().unwrap();
9010
    write(&root.join("other"), "b.txt", b"b\n");
9011
    other.commit("b", &[]).unwrap();
9012
    assert!(other.push("origin", false).unwrap()[0].ok);
9013
    one.fetch("earth").unwrap();
9014
    let b = one
9015
        .bookmarks()
9016
        .unwrap()
9017
        .into_iter()
9018
        .find(|b| b.name == "main")
9019
        .unwrap();
9020
    assert_eq!(
9021
        (b.remote.as_deref(), b.behind),
9022
        (Some("earth"), Some(1)),
9023
        "a stale origin copy is not used"
9024
    );
9025
    assert_eq!(
9026
        one.default_remote(),
9027
        "origin",
9028
        "no default chosen among several"
9029
    );
9030
    let e = one.pull(&one.default_remote()).unwrap_err().to_string();
9031
    assert!(e.contains("earth, gcs") && e.contains("core.remote"), "{e}");
9032
    one.config.set("core.remote", "earth").unwrap();
9033
    assert_eq!(one.default_remote(), "earth");
9034
}
9035
9036
#[test]
9037
fn a_missing_author_identity_says_how_to_fix_it() {
9038
    // oxygen#82: an agent home's author.key naming an identity the
9039
    // repository does not hold.
9040
    hermetic();
9041
    let dir = tempfile::tempdir().unwrap();
9042
    let mut repo = Repo::init(dir.path()).unwrap();
9043
    let missing = KeyId::from_hex(&"ab".repeat(32)).unwrap();
9044
    repo.config.set("author.key", &missing.to_hex()).unwrap();
9045
    let e = repo.identity(&missing).unwrap_err().to_string();
9046
    assert!(
9047
        e.contains("this repository has no identity") && e.contains("oxy config author.key"),
9048
        "{e}"
9049
    );
9050
    assert!(e.contains("this repository's config"), "{e}");
9051
}
9052
9053
#[test]
9054
fn a_working_copy_behind_its_bookmark_is_flagged_and_pull_brings_it_up() {
9055
    // oxygen#89 (supermarioland, 2026-10-09): the bookmark moved on without
9056
    // the working copy, a pull with nothing new left it there, and status
9057
    // said "clean".
9058
    hermetic();
9059
    let dir = tempfile::tempdir().unwrap();
9060
    let root = dir.path();
9061
    let _up = Repo::init(&root.join("up")).unwrap();
9062
    let url = root.join("up").to_string_lossy().to_string();
9063
    let other = Repo::clone(&url, &root.join("other"))
9064
        .unwrap()
9065
        .with_home(root.join("home"));
9066
    write(&root.join("other"), "a.txt", b"a\n");
9067
    other.commit("a", &[]).unwrap();
9068
    assert!(other.push("origin", false).unwrap()[0].ok);
9069
    let one = Repo::clone(&url, &root.join("one"))
9070
        .unwrap()
9071
        .with_home(root.join("home"));
9072
    write(&root.join("other"), "b.txt", b"b\n");
9073
    other.commit("b", &[]).unwrap();
9074
    assert!(other.push("origin", false).unwrap()[0].ok);
9075
    one.fetch("origin").unwrap();
9076
    // The bookmark moves; the working copy does not.
9077
    let theirs = one.resolve_heads("origin/main").unwrap();
9078
    one.bookmark_set("main", &theirs).unwrap();
9079
    assert!(!root.join("one/b.txt").exists());
9080
    assert_eq!(one.working_copy_behind().unwrap(), Some(1));
9081
    let r = one.pull("origin").unwrap();
9082
    assert!(
9083
        !r.changed && r.checked_out,
9084
        "nothing new, but the working copy caught up"
9085
    );
9086
    assert!(root.join("one/b.txt").exists());
9087
    assert_eq!(one.working_copy_behind().unwrap(), None);
9088
}
9089
9090
#[test]
9091
fn touched_nodes_cache_answers_as_the_changes_do() {
9092
    hermetic();
9093
    let dir = tempfile::tempdir().unwrap();
9094
    let repo = Repo::init(dir.path()).unwrap();
9095
    write(dir.path(), "a.txt", b"one\n");
9096
    write(dir.path(), "b.txt", b"x\n");
9097
    repo.snapshot("t").unwrap();
9098
    let c1 = repo.commit("first", &[]).unwrap();
9099
    write(dir.path(), "b.txt", b"y\n");
9100
    repo.snapshot("t").unwrap();
9101
    repo.commit("b only", &[]).unwrap();
9102
    fs::rename(dir.path().join("a.txt"), dir.path().join("c.txt")).unwrap();
9103
    write(dir.path(), "c.txt", b"one\ntwo\n");
9104
    repo.snapshot("t").unwrap();
9105
    let c3 = repo.commit("rename and edit", &[]).unwrap();
9106
    // Uncommitted work, so the working copy touches a file too.
9107
    write(dir.path(), "c.txt", b"one\ntwo\nthree\n");
9108
    repo.snapshot("t").unwrap();
9109
9110
    let path = dir.path().join(".oxy/index/touched");
9111
    let hashes = |es: Vec<LogEntry>| es.iter().map(|e| e.hash).collect::<Vec<_>>();
9112
    let cold = hashes(repo.log_for_path("c.txt").unwrap());
9113
    assert!(path.exists(), "the first query writes the cache");
9114
    let warm = hashes(repo.log_for_path("c.txt").unwrap());
9115
    assert_eq!(cold, warm, "the cache answers as the changes do");
9116
    let (wc, _) = repo.working_copy().unwrap();
9117
    assert_eq!(
9118
        cold,
9119
        vec![wc, c3, c1],
9120
        "renames followed, the working copy included"
9121
    );
9122
9123
    // Working-copy changes are not kept: they are replaced by every snapshot.
9124
    let cached = super::touched::read_touched_for_test(&fs::read(&path).unwrap()).unwrap();
9125
    assert!(!cached.contains(&wc), "a working-copy change is not cached");
9126
    assert!(cached.contains(&c1) && cached.contains(&c3));
9127
9128
    // A damaged cache is ignored, not trusted.
9129
    let mut bytes = fs::read(&path).unwrap();
9130
    let last = bytes.len() - 40;
9131
    bytes[last] ^= 1;
9132
    fs::write(&path, &bytes).unwrap();
9133
    assert_eq!(hashes(repo.log_for_path("c.txt").unwrap()), cold);
9134
    let touches = repo.log_revset("touches(\"c.txt\") ~ @").unwrap();
9135
    assert_eq!(hashes(touches), vec![c3, c1]);
9136
}
9137
9138
/// oxygen#88 (vscode 9ab2056393c8): two lines of history that each move a
9139
/// file back where it was leave two placements at one place, which the
9140
/// tree shows as one file. Removing it, and then its directory, retires
9141
/// both, so no copy is left under a directory that is gone.
9142
#[test]
9143
fn git_import_removes_every_copy_of_a_file_at_one_place() {
9144
    hermetic();
9145
    if std::process::Command::new("git")
9146
        .arg("--version")
9147
        .output()
9148
        .is_err()
9149
    {
9150
        eprintln!("git not installed; skipping");
9151
        return;
9152
    }
9153
    let dir = tempfile::tempdir().unwrap();
9154
    let root = dir.path();
9155
    let g = root.join("src.git");
9156
    fs::create_dir_all(&g).unwrap();
9157
    let git = |args: &[&str]| {
9158
        let out = std::process::Command::new("git")
9159
            .arg("-C")
9160
            .arg(&g)
9161
            .args([
9162
                "-c",
9163
                "user.name=Grace",
9164
                "-c",
9165
                "[email protected]",
9166
                "-c",
9167
                "commit.gpgsign=false",
9168
            ])
9169
            .args(args)
9170
            .output()
9171
            .unwrap();
9172
        assert!(
9173
            out.status.success(),
9174
            "git {args:?}: {}",
9175
            String::from_utf8_lossy(&out.stderr)
9176
        );
9177
    };
9178
    git(&["init", "-q", "-b", "main"]);
9179
    write(&g, "d/list.txt", b"one\ntwo\nthree\nfour\n");
9180
    write(&g, "keep.txt", b"k\n");
9181
    git(&["add", "."]);
9182
    git(&["commit", "-qm", "base"]);
9183
    fs::create_dir_all(g.join("d/sub")).unwrap();
9184
    git(&["mv", "d/list.txt", "d/sub/list.txt"]);
9185
    git(&["commit", "-qm", "into sub"]);
9186
    git(&["checkout", "-qb", "side"]);
9187
    git(&["mv", "d/sub/list.txt", "d/list.txt"]);
9188
    git(&["commit", "-qm", "back, on side"]);
9189
    git(&["checkout", "-q", "main"]);
9190
    git(&["mv", "d/sub/list.txt", "d/list.txt"]);
9191
    git(&["commit", "-qm", "back, on main"]);
9192
    git(&["merge", "-q", "--no-edit", "side"]);
9193
    git(&["rm", "-rq", "d"]);
9194
    git(&["commit", "-qm", "d goes"]);
9195
9196
    let repo = Repo::init(&root.join("o")).unwrap();
9197
    repo.import_git(&g, "main").unwrap();
9198
    let v = repo.verify_git_import(&g, "main").unwrap();
9199
    assert!(v.mismatches.is_empty(), "{:?}", v.mismatches);
9200
    let st = repo
9201
        .load_state_history(&repo.bookmark_heads().unwrap())
9202
        .unwrap();
9203
    let view = st.tree().view();
9204
    assert!(view.conflicts.is_empty(), "{:?}", view.conflicts);
9205
    assert_eq!(view.entries.keys().collect::<Vec<_>>(), vec!["keep.txt"]);
9206
}
9207
9208
/// oxygen#94: a state index's file histories are read, and checked by
9209
/// their own hashes, only when a file is built. One found damaged is an
9210
/// error that says so, the index is removed, and the next read rebuilds it.
9211
#[test]
9212
fn a_damaged_file_history_in_the_state_index_is_rebuilt() {
9213
    hermetic();
9214
    let dir = tempfile::tempdir().unwrap();
9215
    let repo = Repo::init(dir.path()).unwrap();
9216
    for i in 0..6 {
9217
        write(
9218
            dir.path(),
9219
            &format!("f{i}.txt"),
9220
            format!("one {i}\n").as_bytes(),
9221
        );
9222
    }
9223
    repo.snapshot("t").unwrap();
9224
    repo.commit("first", &[]).unwrap();
9225
    for i in 0..6 {
9226
        write(
9227
            dir.path(),
9228
            &format!("f{i}.txt"),
9229
            format!("one {i}\ntwo\n").as_bytes(),
9230
        );
9231
    }
9232
    repo.snapshot("t").unwrap();
9233
    repo.commit("second", &[]).unwrap();
9234
    let want: Vec<Vec<u8>> = (0..6)
9235
        .map(|i| format!("one {i}\ntwo\n").into_bytes())
9236
        .collect();
9237
    // The index of the working copy's base, holding every file's history
9238
    // (a few changes behind, an index is replayed onto, not rewritten).
9239
    let (_, wc) = repo.working_copy().unwrap();
9240
    let base = repo.load_state_history(&wc.deps).unwrap();
9241
    repo.write_state_index(&wc.deps, &base);
9242
    for (i, w) in want.iter().enumerate() {
9243
        assert_eq!(&repo.file_at(&format!("f{i}.txt"), None).unwrap(), w);
9244
    }
9245
    let index = repo.state_indexes();
9246
    assert!(!index.is_empty(), "a state index was written");
9247
    // The histories are last in the file: damage the last of them.
9248
    let mut bytes = fs::read(&index[0]).unwrap();
9249
    let last = bytes.len() - 1;
9250
    bytes[last] ^= 0x40;
9251
    fs::write(&index[0], &bytes).unwrap();
9252
9253
    let reads: Vec<_> = (0..6)
9254
        .map(|i| repo.file_at(&format!("f{i}.txt"), None))
9255
        .collect();
9256
    let damaged: Vec<String> = reads
9257
        .iter()
9258
        .filter_map(|r| r.as_ref().err().map(|e| e.to_string()))
9259
        .collect();
9260
    assert_eq!(damaged.len(), 1, "{damaged:?}");
9261
    assert!(
9262
        damaged[0].contains("state index was damaged")
9263
            && damaged[0].contains("run the command again"),
9264
        "{}",
9265
        damaged[0]
9266
    );
9267
    // Every file reads right again, from an index rebuilt from history.
9268
    for (i, w) in want.iter().enumerate() {
9269
        assert_eq!(&repo.file_at(&format!("f{i}.txt"), None).unwrap(), w);
9270
    }
9271
}
9272
9273
/// oxygen#95: a push longer than `push.batch-bytes` goes in parts, each
9274
/// objects alone and in dependency order, and the last moves the bookmark.
9275
/// The remote ends with every change and the same state, and says how each
9276
/// part went.
9277
#[test]
9278
fn a_long_push_goes_in_parts() {
9279
    hermetic();
9280
    let dir = tempfile::tempdir().unwrap();
9281
    let root = dir.path();
9282
    let origin = root.join("origin");
9283
    Repo::init_bare_unbound(&origin).unwrap();
9284
    let main = root.join("main");
9285
    let mut repo = Repo::init(&main).unwrap();
9286
    repo.config
9287
        .set("remote.origin.url", &origin.to_string_lossy())
9288
        .unwrap();
9289
    // One byte: every change is a part of its own.
9290
    repo.config.set("push.batch-bytes", "1").unwrap();
9291
    repo.save_config().unwrap();
9292
    for i in 0..6 {
9293
        write(
9294
            &main,
9295
            &format!("f{i}.txt"),
9296
            format!("file {i}\n").as_bytes(),
9297
        );
9298
        repo.commit(&format!("c{i}"), &[]).unwrap();
9299
    }
9300
    let mut parts = Vec::new();
9301
    let results = repo
9302
        .push_bookmark_with("origin", "main", false, &mut |m| parts.push(m.to_string()))
9303
        .unwrap();
9304
    assert!(
9305
        results.iter().any(|r| r.ok && r.name == "main"),
9306
        "{results:?}"
9307
    );
9308
    assert_eq!(parts.len(), 6, "{parts:?}");
9309
    assert_eq!(parts[0], "part 1 of 6: 1 changes");
9310
9311
    let remote = Repo::open(&origin).unwrap();
9312
    let heads = repo.bookmark_heads().unwrap();
9313
    assert_eq!(remote.bookmark_heads().unwrap(), heads);
9314
    assert_eq!(
9315
        remote.log_state(&heads).unwrap().len(),
9316
        repo.log_state(&heads).unwrap().len()
9317
    );
9318
    // A push of objects alone reports how it went, as `objects`.
9319
    let got = remote
9320
        .receive_push(Bundle::default(), vec![], None, vec![])
9321
        .unwrap();
9322
    assert_eq!(got.len(), 1);
9323
    assert!(got[0].ok && got[0].name == OBJECTS_RESULT, "{got:?}");
9324
}
9325
9326
/// oxygen#97: with `git.claim`, an import authors the importing identity's
9327
/// own commits (Git author email = its email, any case) with its key, and
9328
/// leaves anyone else's with the zero key; the history verifies as before.
9329
#[test]
9330
fn git_import_claims_your_own_commits() {
9331
    hermetic();
9332
    if std::process::Command::new("git")
9333
        .arg("--version")
9334
        .output()
9335
        .is_err()
9336
    {
9337
        eprintln!("git not installed; skipping");
9338
        return;
9339
    }
9340
    let dir = tempfile::tempdir().unwrap();
9341
    let root = dir.path();
9342
    let g = root.join("src.git");
9343
    fs::create_dir_all(&g).unwrap();
9344
    let git = |who: &str, args: &[&str]| {
9345
        let (name, email) = who.split_once(' ').unwrap();
9346
        let out = std::process::Command::new("git")
9347
            .arg("-C")
9348
            .arg(&g)
9349
            .args([
9350
                "-c",
9351
                &format!("user.name={name}"),
9352
                "-c",
9353
                &format!("user.email={email}"),
9354
                "-c",
9355
                "commit.gpgsign=false",
9356
            ])
9357
            .args(args)
9358
            .output()
9359
            .unwrap();
9360
        assert!(
9361
            out.status.success(),
9362
            "git {args:?}: {}",
9363
            String::from_utf8_lossy(&out.stderr)
9364
        );
9365
    };
9366
    git("Grace [email protected]", &["init", "-q", "-b", "main"]);
9367
    write(&g, "a.txt", b"a\n");
9368
    git("Grace [email protected]", &["add", "."]);
9369
    git("Grace [email protected]", &["commit", "-qm", "mine"]);
9370
    write(&g, "b.txt", b"b\n");
9371
    git("Ada [email protected]", &["add", "."]);
9372
    git("Ada [email protected]", &["commit", "-qm", "someone else's"]);
9373
9374
    let mut repo = Repo::init(&root.join("o")).unwrap();
9375
    let (key, _) = repo
9376
        .create_identity("Grace", "[email protected]", IdentityScope::Repo)
9377
        .unwrap();
9378
    repo.config.set("git.claim", "true").unwrap();
9379
    repo.save_config().unwrap();
9380
    let repo = Repo::open(&root.join("o")).unwrap();
9381
    repo.import_git(&g, "main").unwrap();
9382
    let v = repo.verify_git_import(&g, "main").unwrap();
9383
    assert!(v.mismatches.is_empty(), "{:?}", v.mismatches);
9384
    let heads = repo.bookmark_heads().unwrap();
9385
    let by_message: std::collections::HashMap<String, KeyId> = repo
9386
        .log_state(&heads)
9387
        .unwrap()
9388
        .into_iter()
9389
        .map(|e| {
9390
            (
9391
                e.change.message.lines().next().unwrap_or("").to_string(),
9392
                e.change.author,
9393
            )
9394
        })
9395
        .collect();
9396
    assert_eq!(by_message["mine"], key, "her own commit, any case of email");
9397
    assert_eq!(by_message["someone else's"], ObjectRef::ZERO, "not hers");
9398
}
9399
9400
/// oxygen#86: removing a remote removes all of it: every `remote.NAME.*`
9401
/// key (URL, token, CA), its tracking bookmarks, and nothing else.
9402
#[test]
9403
fn removing_a_remote_leaves_nothing_of_it() {
9404
    hermetic();
9405
    let dir = tempfile::tempdir().unwrap();
9406
    let origin = dir.path().join("origin");
9407
    Repo::init_bare_unbound(&origin).unwrap();
9408
    let main = dir.path().join("main");
9409
    let mut repo = Repo::init(&main).unwrap();
9410
    repo.config
9411
        .set("remote.origin.url", &origin.to_string_lossy())
9412
        .unwrap();
9413
    repo.config
9414
        .set("remote.origin.token", "secret-ish")
9415
        .unwrap();
9416
    repo.config
9417
        .set("remote.keep.url", &origin.to_string_lossy())
9418
        .unwrap();
9419
    repo.save_config().unwrap();
9420
    write(&main, "a.txt", b"a\n");
9421
    repo.commit("a", &[]).unwrap();
9422
    assert!(repo.push("origin", false).unwrap()[0].ok);
9423
    assert!(
9424
        repo.view().unwrap().remotes.contains_key("origin"),
9425
        "a tracking bookmark"
9426
    );
9427
9428
    repo.remove_remote("origin").unwrap();
9429
    let again = Repo::open(&main).unwrap();
9430
    assert!(
9431
        !again
9432
            .config
9433
            .repo_layer()
9434
            .keys()
9435
            .any(|k| k.starts_with("remote.origin.")),
9436
        "{:?}",
9437
        again.config.repo_layer()
9438
    );
9439
    assert!(!again.config.remotes.contains_key("origin"));
9440
    assert!(
9441
        !again.view().unwrap().remotes.contains_key("origin"),
9442
        "its tracking bookmarks go"
9443
    );
9444
    assert!(
9445
        again.config.remotes.contains_key("keep"),
9446
        "another remote stays"
9447
    );
9448
    let mut again = again;
9449
    assert!(
9450
        again.remove_remote("origin").is_err(),
9451
        "a second removal is refused"
9452
    );
9453
}
9454
9455
/// oxygenhub#126: a blob a host stored for itself (a job's artifact) is
9456
/// unreachable from history, so gc prunes it, unless the host names it:
9457
/// then it and its chunks stay, and it reads back whole.
9458
#[test]
9459
fn gc_keeps_the_blobs_a_host_names() {
9460
    hermetic();
9461
    let dir = tempfile::tempdir().unwrap();
9462
    let repo = Repo::init(dir.path()).unwrap();
9463
    write(dir.path(), "a.txt", b"a\n");
9464
    repo.commit("a", &[]).unwrap();
9465
    // Large enough to be several chunks.
9466
    let body: Vec<u8> = (0..400_000u32)
9467
        .flat_map(|i| (i.wrapping_mul(2654435761)).to_le_bytes())
9468
        .collect();
9469
    let kept = repo.store_blob(&body).unwrap();
9470
    let lost = repo.store_blob(b"an artifact nobody names").unwrap();
9471
    repo.gc_keeping(true, &[kept], &mut |_| {}).unwrap();
9472
    assert_eq!(repo.read_blob(&kept).unwrap(), body, "named: kept whole");
9473
    assert!(!repo.store().has(&lost), "not named: pruned");
9474
    repo.gc(true).unwrap();
9475
    assert!(!repo.store().has(&kept), "a plain gc prunes it");
9476
}
9477
9478
/// oxygen#99: undo in one workspace undoes that workspace's last command,
9479
/// never another workspace's, says what it undid, and goes further back
9480
/// when run again.
9481
#[test]
9482
fn undo_is_scoped_to_its_workspace() {
9483
    hermetic();
9484
    let dir = tempfile::tempdir().unwrap();
9485
    let root = dir.path().join("main");
9486
    let a = Repo::init(&root).unwrap();
9487
    write(&root, "base.txt", b"base\n");
9488
    let base = a.commit("base", &[]).unwrap();
9489
    a.bookmark_create("feature", None).unwrap();
9490
    let ws_dir = dir.path().join("ws");
9491
    let heads = a.resolve_heads("feature").unwrap();
9492
    let b = a
9493
        .workspace_add_on(&ws_dir, Some(&heads), Some("feature"))
9494
        .unwrap();
9495
9496
    // A commits on main, then B commits on feature: B's is the newest.
9497
    write(&root, "a.txt", b"a\n");
9498
    let ca = a.commit("from a", &[]).unwrap();
9499
    write(&ws_dir, "b.txt", b"b\n");
9500
    let cb = b.commit("from b", &[]).unwrap();
9501
9502
    // A's undo undoes A's commit and leaves B's.
9503
    let u = a.undo().unwrap();
9504
    assert_eq!(u.command, "oxy commit -m \"from a\"");
9505
    assert_eq!(u.others_kept, 1, "B's newer commit is left");
9506
    assert!(!u.changes.is_empty());
9507
    let view = a.view().unwrap();
9508
    // (Independent changes commute, so a bookmark's heads may hold base too.)
9509
    assert_eq!(a.heads_of(&view, "main").unwrap(), vec![base]);
9510
    assert!(
9511
        a.heads_of(&view, "feature").unwrap().contains(&cb),
9512
        "B's commit stands"
9513
    );
9514
    assert!(
9515
        a.store().get_change(&ca).is_ok(),
9516
        "the change itself is still in the store"
9517
    );
9518
    // A's working copy was clean, so its files followed; B's are untouched.
9519
    assert!(!root.join("a.txt").exists());
9520
    assert!(a.snapshot("oxy status").unwrap().statuses.is_empty());
9521
    assert!(ws_dir.join("b.txt").exists());
9522
9523
    // B's undo still finds B's own commit, under A's undo.
9524
    let u = b.undo().unwrap();
9525
    assert_eq!(u.command, "oxy commit -m \"from b\"");
9526
    assert!(!b
9527
        .heads_of(&b.view().unwrap(), "feature")
9528
        .unwrap()
9529
        .contains(&cb));
9530
    assert_eq!(
9531
        a.heads_of(&a.view().unwrap(), "main").unwrap(),
9532
        vec![base],
9533
        "A's undo stands"
9534
    );
9535
9536
    // A's next undo goes past the commit it already undid, to adding B's
9537
    // workspace: refused, since B has worked there since.
9538
    let e = a.undo().unwrap_err().to_string();
9539
    assert!(e.contains("the workspace at") && e.contains("ws"), "{e}");
9540
}
9541
9542
/// oxygen#99: two workspaces on one bookmark: an undo takes back only its
9543
/// own commit's head, and the other workspace's head stays.
9544
#[test]
9545
fn undo_on_a_shared_bookmark_keeps_the_other_workspaces_head() {
9546
    hermetic();
9547
    let dir = tempfile::tempdir().unwrap();
9548
    let root = dir.path().join("main");
9549
    let a = Repo::init(&root).unwrap();
9550
    write(&root, "base.txt", b"base\n");
9551
    a.commit("base", &[]).unwrap();
9552
    let ws_dir = dir.path().join("ws");
9553
    let b = a.workspace_add(&ws_dir, None).unwrap();
9554
    write(&root, "a.txt", b"a\n");
9555
    let ca = a.commit("from a", &[]).unwrap();
9556
    write(&ws_dir, "b.txt", b"b\n");
9557
    let cb = b.commit("from b", &[]).unwrap();
9558
    let u = a.undo().unwrap();
9559
    assert_eq!(u.command, "oxy commit -m \"from a\"");
9560
    let heads = a.heads_of(&a.view().unwrap(), "main").unwrap();
9561
    assert!(heads.contains(&cb) && !heads.contains(&ca), "{heads:?}");
9562
}
9563
9564
/// oxygen#99: an undo that would also take back what another workspace
9565
/// did since to the same bookmark is refused, naming it.
9566
#[test]
9567
fn undo_refuses_to_take_back_another_workspaces_work() {
9568
    hermetic();
9569
    let dir = tempfile::tempdir().unwrap();
9570
    let root = dir.path().join("main");
9571
    let a = Repo::init(&root).unwrap();
9572
    write(&root, "base.txt", b"base\n");
9573
    a.commit("base", &[]).unwrap();
9574
    let ws_dir = dir.path().join("ws");
9575
    let b = a.workspace_add(&ws_dir, None).unwrap();
9576
    // Both on main: A commits, then B builds on it, editing A's file.
9577
    write(&root, "a.txt", b"a\n");
9578
    a.commit("from a", &[]).unwrap();
9579
    b.refresh().unwrap();
9580
    let heads = b.resolve_heads("main").unwrap();
9581
    b.checkout(&heads, false, "oxy checkout").unwrap();
9582
    write(&ws_dir, "a.txt", b"a, then b\n");
9583
    b.commit("from b", &[]).unwrap();
9584
    let e = a.undo().unwrap_err().to_string();
9585
    assert!(
9586
        e.contains("bookmark main") && e.contains("builds on"),
9587
        "{e}"
9588
    );
9589
    assert!(e.contains("oxy op restore"), "{e}");
9590
}
9591
9592
/// oxygen#99: undoing a commit that was already pushed says so: the remote
9593
/// still has it.
9594
#[test]
9595
fn undo_says_when_the_commit_was_pushed() {
9596
    hermetic();
9597
    let dir = tempfile::tempdir().unwrap();
9598
    let root = dir.path();
9599
    Repo::init(&root.join("origin")).unwrap();
9600
    let url = root.join("origin").to_string_lossy().to_string();
9601
    let repo = Repo::clone(&url, &root.join("work"))
9602
        .unwrap()
9603
        .with_home(root.join("home"));
9604
    write(&root.join("work"), "a.txt", b"a\n");
9605
    repo.commit("a", &[]).unwrap();
9606
    assert!(repo.push("origin", false).unwrap()[0].ok);
9607
    // The push itself is passed over: the remote keeps what it was sent.
9608
    let u = repo.undo().unwrap();
9609
    assert_eq!(u.command, "oxy commit -m \"a\"");
9610
    assert_eq!(u.pushed, vec![("main".to_string(), "origin".to_string())]);
9611
}
9612
9613
/// oxygen#98: a new untracked file over snapshot.max-new-file-size is left
9614
/// out of the snapshot and named; tracked files and files already in the
9615
/// working copy are not.
9616
#[test]
9617
fn large_new_files_are_left_out_of_snapshots() {
9618
    hermetic();
9619
    let dir = tempfile::tempdir().unwrap();
9620
    let root = dir.path();
9621
    let mut repo = Repo::init(root).unwrap();
9622
    repo.config.max_new_file = 1024;
9623
    write(root, "small.txt", b"small\n");
9624
    write(root, "big.bin", &vec![0u8; 4096]);
9625
    let s = repo.snapshot("oxy status").unwrap();
9626
    let paths: Vec<_> = s.statuses.iter().map(|p| p.path.as_str()).collect();
9627
    assert_eq!(paths, ["small.txt"]);
9628
    assert_eq!(repo.skipped_large(), vec![("big.bin".to_string(), 4096)]);
9629
    repo.commit("small", &[]).unwrap();
9630
9631
    // A tracked file may grow past the limit.
9632
    write(root, "small.txt", &vec![b'x'; 4096]);
9633
    let s = repo.snapshot("oxy status").unwrap();
9634
    assert!(s.statuses.iter().any(|p| p.path == "small.txt"));
9635
    // With no limit the big file is taken in, and stays once it is.
9636
    repo.config.max_new_file = 0;
9637
    let s = repo.snapshot("oxy status").unwrap();
9638
    assert!(s.statuses.iter().any(|p| p.path == "big.bin"));
9639
    repo.config.max_new_file = 1024;
9640
    let s = repo.snapshot("oxy status").unwrap();
9641
    assert!(
9642
        s.statuses.iter().any(|p| p.path == "big.bin"),
9643
        "already in the working copy"
9644
    );
9645
    assert!(repo.skipped_large().is_empty());
9646
}
9647
9648
/// oxygen#98: a file only a past working-copy snapshot held is pruned once
9649
/// snapshots expire, and kept while they have not.
9650
#[test]
9651
fn gc_prunes_what_only_expired_snapshots_held() {
9652
    hermetic();
9653
    let dir = tempfile::tempdir().unwrap();
9654
    let root = dir.path();
9655
    let mut repo = Repo::init(root).unwrap();
9656
    repo.config.gc_grace_days = 0;
9657
    write(root, "a.txt", b"a\n");
9658
    repo.commit("a", &[]).unwrap();
9659
    let image: Vec<u8> = (0..200_000u32).map(|i| (i % 7) as u8).collect();
9660
    write(root, "image.tar", &image);
9661
    repo.snapshot("oxy status").unwrap();
9662
    std::fs::remove_file(root.join("image.tar")).unwrap();
9663
    repo.snapshot("oxy status").unwrap();
9664
    let blob = Repo::blob_ref(&image);
9665
    assert!(repo.store().has(&blob));
9666
    repo.gc(true).unwrap();
9667
    assert!(repo.store().has(&blob), "a recent snapshot keeps it");
9668
    repo.config.snapshot_retention_days = 0;
9669
    repo.gc(true).unwrap();
9670
    assert!(!repo.store().has(&blob), "an expired snapshot does not");
9671
    assert_eq!(
9672
        repo.file_at("a.txt", None).unwrap(),
9673
        b"a\n",
9674
        "committed files stay"
9675
    );
9676
}
9677
9678
/// oxygen#100: uncommitted work byte-for-byte what the bookmark switched to
9679
/// already has is no conflict: the switch goes through, nothing is lost,
9680
/// and other carried work still comes along.
9681
#[test]
9682
fn carrying_work_the_target_already_has_is_no_conflict() {
9683
    hermetic();
9684
    let dir = tempfile::tempdir().unwrap();
9685
    let root = dir.path();
9686
    let mut repo = Repo::init(root).unwrap();
9687
    write(root, "a.txt", b"one\n");
9688
    write(root, "b.txt", b"b\n");
9689
    repo.commit("one", &[]).unwrap();
9690
    repo.bookmark_create("landed", None).unwrap();
9691
    // On landed, a.txt becomes "two" (as a proposal landing would).
9692
    repo.bookmark_switch("landed", false).unwrap();
9693
    write(root, "a.txt", b"two\n");
9694
    repo.commit("two", &[]).unwrap();
9695
    repo.bookmark_switch("main", false).unwrap();
9696
    assert_eq!(std::fs::read(root.join("a.txt")).unwrap(), b"one\n");
9697
    // The same edit, uncommitted, on main; and another edit besides.
9698
    write(root, "a.txt", b"two\n");
9699
    write(root, "b.txt", b"b, edited\n");
9700
    let (_, carried) = repo.bookmark_switch_carry("landed").unwrap();
9701
    assert_eq!(
9702
        carried,
9703
        vec!["b.txt".to_string()],
9704
        "only the work landed lacks is carried"
9705
    );
9706
    assert_eq!(std::fs::read(root.join("a.txt")).unwrap(), b"two\n");
9707
    assert_eq!(std::fs::read(root.join("b.txt")).unwrap(), b"b, edited\n");
9708
    let s = repo.snapshot("oxy status").unwrap();
9709
    let paths: Vec<_> = s.statuses.iter().map(|p| p.path.as_str()).collect();
9710
    assert_eq!(paths, ["b.txt"]);
9711
9712
    // A real difference is still refused.
9713
    repo.bookmark_switch("main", true).unwrap();
9714
    write(root, "a.txt", b"three\n");
9715
    let e = repo
9716
        .bookmark_switch_carry("landed")
9717
        .unwrap_err()
9718
        .to_string();
9719
    assert!(e.contains("a.txt") && e.contains("--discard"), "{e}");
9720
}
9721
9722
/// oxygen#103: a full change hash as `--json` prints it, without `#`,
9723
/// resolves, so JSON output feeds back into commands.
9724
#[test]
9725
fn a_full_hash_resolves_without_its_hash_sign() {
9726
    hermetic();
9727
    let dir = tempfile::tempdir().unwrap();
9728
    let root = dir.path();
9729
    let repo = Repo::init(root).unwrap();
9730
    write(root, "a.txt", b"a\n");
9731
    let h = repo.commit("a", &[]).unwrap();
9732
    assert_eq!(repo.resolve_change(&h.to_hex()).unwrap(), h);
9733
    assert_eq!(repo.resolve_change(&format!("#{}", h.to_hex())).unwrap(), h);
9734
    assert!(repo
9735
        .resolve_change(&"0".repeat(64))
9736
        .unwrap_err()
9737
        .to_string()
9738
        .contains("no change matches"));
9739
}
9740
9741
#[test]
9742
fn a_pin_change_moves_only_the_pin() {
9743
    hermetic();
9744
    let dir = tempfile::tempdir().unwrap();
9745
    let root = dir.path();
9746
    let _lib_origin = Repo::init(&root.join("lib-origin")).unwrap();
9747
    let lib_url = root.join("lib-origin").to_string_lossy().to_string();
9748
    let lib = Repo::clone(&lib_url, &root.join("lib"))
9749
        .unwrap()
9750
        .with_home(root.join("home"));
9751
    write(&root.join("lib"), "lib.txt", b"v1\n");
9752
    lib.commit("lib v1", &[]).unwrap();
9753
    assert!(lib.push("origin", false).unwrap()[0].ok);
9754
    let _app_origin = Repo::init(&root.join("app-origin")).unwrap();
9755
    let app_dir = root.join("app");
9756
    let app = Repo::clone(&root.join("app-origin").to_string_lossy(), &app_dir)
9757
        .unwrap()
9758
        .with_home(root.join("home"));
9759
    write(&app_dir, "main.txt", b"app\n");
9760
    let pin1 = app.submodule_add(&lib_url, "libs/lib", None).unwrap();
9761
    let a1 = app.commit("app with lib", &[]).unwrap();
9762
    // The library moves on.
9763
    write(&root.join("lib"), "more.txt", b"v2\n");
9764
    let l2 = lib.commit("lib v2", &[]).unwrap();
9765
    let crate::subrepo::Pin::Oxy { repo, bookmark, .. } = pin1 else {
9766
        panic!("an Oxygen pin")
9767
    };
9768
    let pin2 = crate::subrepo::Pin::Oxy {
9769
        repo,
9770
        heads: vec![l2],
9771
        bookmark,
9772
    };
9773
    let author = app.store().get_change(&a1).unwrap().author;
9774
    let change = app
9775
        .build_pin_change(&[a1], "libs/lib", &pin2, "Move lib to v2", author)
9776
        .unwrap();
9777
    let mut state = app.load_state(&[a1]).unwrap();
9778
    state.add(change).unwrap();
9779
    let files = state.materialize().files;
9780
    assert_eq!(files["libs/lib"].kind, NodeKind::Subrepo);
9781
    let FileContent::Opaque { blobs } = &files["libs/lib"].content else {
9782
        panic!("a pin is opaque")
9783
    };
9784
    let read = crate::subrepo::Pin::decode(&app.read_blob(&blobs[0]).unwrap()).unwrap();
9785
    assert_eq!(read, pin2, "the new pin");
9786
    assert!(
9787
        matches!(&files["main.txt"].content, FileContent::Text { bytes, .. } if bytes.as_slice() == b"app\n"),
9788
        "nothing else changes"
9789
    );
9790
    // Only a subrepo's pin can be moved this way.
9791
    let e = app.build_pin_change(&[a1], "main.txt", &pin2, "x", author);
9792
    assert!(format!("{:?}", e.unwrap_err()).contains("not a subrepo"));
9793
    let e = app.build_pin_change(&[a1], "libs/none", &pin2, "x", author);
9794
    assert!(format!("{:?}", e.unwrap_err()).contains("does not exist"));
9795
}
9796
9797
/// oxygenhub#249: a handle reads the operation head once and keeps it,
9798
/// so one command or request never mixes two heads; another handle's
9799
/// operation shows only after `refresh`. Its own operations move it, and
9800
/// one recorded from the head it kept merges with what landed since, as
9801
/// any concurrent operation does.
9802
#[test]
9803
fn one_handle_keeps_one_head_until_it_refreshes() {
9804
    hermetic();
9805
    let dir = tempfile::tempdir().unwrap();
9806
    let root = dir.path();
9807
    let writer = Repo::init(root).unwrap();
9808
    write(root, "a.txt", b"one\n");
9809
    let h1 = writer.commit("one", &[]).unwrap();
9810
    let reader = Repo::open(root).unwrap();
9811
    let before = reader.view().unwrap();
9812
    assert_eq!(reader.bookmark_heads().unwrap(), vec![h1]);
9813
    write(root, "a.txt", b"two\n");
9814
    let h2 = writer.commit("two", &[]).unwrap();
9815
    assert_eq!(
9816
        writer.bookmark_heads().unwrap(),
9817
        vec![h2],
9818
        "its own operation"
9819
    );
9820
    assert_eq!(reader.view().unwrap(), before, "the head it read first");
9821
    assert_eq!(reader.bookmark_heads().unwrap(), vec![h1]);
9822
    reader.refresh().unwrap();
9823
    assert_eq!(reader.bookmark_heads().unwrap(), vec![h2]);
9824
9825
    // A handle recording from an older head merges with the newer one.
9826
    let stale = Repo::open(root).unwrap();
9827
    assert_eq!(stale.bookmark_heads().unwrap(), vec![h2]);
9828
    write(root, "a.txt", b"three\n");
9829
    let h3 = writer.commit("three", &[]).unwrap();
9830
    stale.bookmark_create("feature", Some(&[h1])).unwrap();
9831
    let view = stale.view().unwrap();
9832
    assert!(view.bookmarks.contains_key("feature"));
9833
    assert_eq!(
9834
        stale.bookmark_heads().unwrap(),
9835
        vec![h3],
9836
        "merged, not lost"
9837
    );
9838
    let fresh = Repo::open(root).unwrap();
9839
    assert_eq!(fresh.view().unwrap(), view);
9840
}
9841
9842
/// oxygenhub#249 over a store (a bucket's compare-and-swap): the same.
9843
#[test]
9844
fn over_a_store_one_handle_keeps_one_head() {
9845
    hermetic();
9846
    let backend = std::sync::Arc::new(crate::strata::MemoryStore::new());
9847
    crate::store::TEST_BACKEND.with(|t| *t.borrow_mut() = Some(backend.clone()));
9848
    let dir = tempfile::tempdir().unwrap();
9849
    let a = Repo::init(dir.path()).unwrap();
9850
    let (h0, _) = a.head_op().unwrap();
9851
    let b = Repo::open(dir.path()).unwrap();
9852
    assert_eq!(b.head_op().unwrap().0, h0);
9853
    let state = a.store.put_state(&StateObject::new(vec![])).unwrap();
9854
    let mut view = a.view().unwrap();
9855
    view.bookmarks.insert("x".into(), state);
9856
    let r = a.record_op(&[h0], "bookmark x", view).unwrap();
9857
    assert_eq!(a.head_op().unwrap().0, r);
9858
    assert_eq!(b.head_op().unwrap().0, h0, "b keeps its head");
9859
    b.refresh().unwrap();
9860
    assert_eq!(b.head_op().unwrap().0, r);
9861
    crate::store::TEST_BACKEND.with(|t| *t.borrow_mut() = None);
9862
}
9863
9864
/// oxygenhub#249: gc retires what it repacks rather than deleting it; a
9865
/// reader opened before reads on, then and after the next gc deletes the
9866
/// retired files once their hour is up. Younger ones are kept.
9867
#[test]
9868
fn gc_retires_and_a_later_gc_deletes_after_the_hour() {
9869
    hermetic();
9870
    let dir = tempfile::tempdir().unwrap();
9871
    let root = dir.path();
9872
    let repo = Repo::init(root).unwrap();
9873
    let mut heads = Vec::new();
9874
    for i in 0..4 {
9875
        write(root, &format!("f{i}.txt"), format!("{i}\n").as_bytes());
9876
        heads.push(repo.commit(&format!("c{i}"), &[]).unwrap());
9877
    }
9878
    let reader = Repo::open(root).unwrap();
9879
    assert_eq!(reader.log().unwrap().len(), 5);
9880
    let r = repo.gc(true).unwrap();
9881
    assert_eq!(r.retired, crate::store::RetiredReport::default());
9882
    assert_eq!(repo.store().loose_count().unwrap(), 0);
9883
    assert_eq!(reader.log().unwrap().len(), 5, "read on from what it had");
9884
    // Nothing is an hour old yet: a gc keeps it all.
9885
    let r = repo.gc(true).unwrap();
9886
    assert_eq!((r.retired.packs, r.retired.loose), (0, 0));
9887
    assert!(r.retired.kept > 0, "{r:?}");
9888
    write(root, "f9.txt", b"9\n");
9889
    heads.push(repo.commit("c9", &[]).unwrap());
9890
    crate::store::reader_tests::age_retired(
9891
        repo.store(),
9892
        crate::store::RETIRED_FOR + std::time::Duration::from_secs(60),
9893
    );
9894
    let r = repo.gc(true).unwrap();
9895
    assert!(r.retired.packs >= 1 && r.retired.loose > 0, "{r:?}");
9896
    assert_eq!(r.retired.kept, 0, "{r:?}");
9897
    let r = repo.gc(true).unwrap();
9898
    assert_eq!((r.retired.packs, r.retired.loose), (0, 0));
9899
    assert!(r.retired.kept > 0, "what the last gc retired is young");
9900
    // The reader opened before all of it still reads everything, from
9901
    // the packs it finds when what it loaded is gone.
9902
    assert_eq!(reader.log().unwrap().len(), 5);
9903
    for h in &heads[..4] {
9904
        reader.store().get_change(h).unwrap();
9905
    }
9906
    reader.refresh().unwrap();
9907
    assert_eq!(reader.log().unwrap().len(), 6);
9908
    let fresh = Repo::open(root).unwrap();
9909
    assert_eq!(
9910
        fresh.store().pack_count(),
9911
        1,
9912
        "retired packs are not loaded"
9913
    );
9914
}
9915
9916
/// oxygenhub#249: a repository opens when its store's pack listing names
9917
/// an index that is not there (deleted between the listing and the read).
9918
#[test]
9919
fn a_repository_opens_when_a_listed_index_is_gone() {
9920
    hermetic();
9921
    let backend = crate::store::reader_tests::racing(true);
9922
    let dyn_backend: std::sync::Arc<crate::store::Backend> = backend.clone();
9923
    crate::store::TEST_BACKEND.with(|t| *t.borrow_mut() = Some(dyn_backend));
9924
    let dir = tempfile::tempdir().unwrap();
9925
    let repo = Repo::init(dir.path()).unwrap();
9926
    write(dir.path(), "a.txt", b"a\n");
9927
    let h = repo.commit("a", &[]).unwrap();
9928
    repo.gc(true).unwrap();
9929
    let again = Repo::open(dir.path()).unwrap();
9930
    assert_eq!(again.store().pack_count(), 1);
9931
    assert_eq!(again.bookmark_heads().unwrap(), vec![h]);
9932
    // And when one is deleted between the listing and the read: a copy of
9933
    // the live pack, whose index goes as the store opens.
9934
    use crate::strata::Store as _;
9935
    let idx = backend
9936
        .list("pack-")
9937
        .unwrap()
9938
        .into_iter()
9939
        .map(|e| e.key)
9940
        .find(|k| k.ends_with(".idx") && k != "pack-0000.idx")
9941
        .unwrap();
9942
    let stem = idx.trim_end_matches(".idx");
9943
    for ext in ["pack", "idx"] {
9944
        let bytes = backend.get(&format!("{stem}.{ext}")).unwrap();
9945
        backend
9946
            .put_new(&format!("pack-copy.{ext}"), &bytes)
9947
            .unwrap();
9948
    }
9949
    *backend.doomed.lock().unwrap() = Some("pack-copy.idx".into());
9950
    let again = Repo::open(dir.path()).unwrap();
9951
    assert_eq!(again.store().pack_count(), 1);
9952
    assert_eq!(again.bookmark_heads().unwrap(), vec![h]);
9953
    assert!(!backend.has("pack-copy.idx").unwrap());
9954
    crate::store::TEST_BACKEND.with(|t| *t.borrow_mut() = None);
9955
}