OXYGENHUB
# 67a4fe1aa2d5 oxygen / crates / oxy-core / src / repo / tests.rs
310.1 KiB · Rust · last changed The issuer countersigns when it accepted a certified update (keyless step 4c) 19 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
            conflicted: false,
436
            notes: vec![],
437
            lacks: 1,
438
        }
439
    );
440
    assert_eq!(fs::read(root.join("a.txt")).unwrap(), b"one\n");
441
    assert_eq!(fs::read(root.join("sub/deep/b.txt")).unwrap(), b"b\n");
442
    assert!(!root.join("bin.dat").exists());
443
    let (_, wc) = repo.working_copy().unwrap();
444
    assert_eq!(wc.deps, vec![h1]);
445
    assert!(
446
        !repo.snapshot("status").unwrap().changed,
447
        "checkout leaves a clean working copy"
448
    );
449
    // The bookmark still points at h2.
450
    assert_eq!(repo.bookmark_heads().unwrap(), vec![h2]);
451
452
    // Dirty working copy refuses without --discard.
453
    write(root, "a.txt", b"dirty\n");
454
    assert!(repo.checkout(&[h2], false, "oxy checkout").is_err());
455
    let r = repo
456
        .checkout(&[h2], true, "oxy checkout --discard")
457
        .unwrap();
458
    assert_eq!(fs::read(root.join("a.txt")).unwrap(), b"two\n");
459
    assert_eq!(fs::read(root.join("bin.dat")).unwrap(), [0, 1, 2, 3]);
460
    assert!(!root.join("sub").exists(), "empty directories are pruned");
461
    assert_eq!(r.removed, 1);
462
    assert!(!repo.snapshot("status").unwrap().changed);
463
464
    // Refuses to write through a symlinked directory.
465
    #[cfg(unix)]
466
    {
467
        fs::remove_dir_all(root.join("sub")).ok();
468
        std::os::unix::fs::symlink("/tmp", root.join("sub")).unwrap();
469
        assert!(repo.checkout(&[h1], true, "oxy checkout").is_err());
470
    }
471
}
472
473
#[test]
474
fn large_files_are_chunked_and_read_back() {
475
    hermetic();
476
    let dir = tempfile::tempdir().unwrap();
477
    let repo = Repo::init(dir.path()).unwrap();
478
    let mut big = vec![0u8; 700 * 1024];
479
    for (i, b) in big.iter_mut().enumerate() {
480
        *b = (i as u32).wrapping_mul(2654435761).to_le_bytes()[0];
481
    }
482
    let r = repo.store_blob(&big).unwrap();
483
    let blob = Blob::decode(&repo.store().get_typed(&r, ObjectType::Blob).unwrap()).unwrap();
484
    assert!(blob.chunks.len() >= 3, "{}", blob.chunks.len());
485
    assert_eq!(repo.read_blob(&r).unwrap(), big);
486
    assert_eq!(Repo::blob_ref(&big), r);
487
}
488
489
#[test]
490
fn clone_push_pull_with_seals_and_attestations() {
491
    hermetic();
492
    let dir = tempfile::tempdir().unwrap();
493
    let root = dir.path();
494
    let origin_path = root.join("origin");
495
    let origin = Repo::init(&origin_path).unwrap();
496
    let origin_url = origin_path.to_string_lossy().to_string();
497
498
    // A clones, creates an identity (default core.sign = seal), commits, pushes.
499
    let mut a = Repo::clone(&origin_url, &root.join("a"))
500
        .unwrap()
501
        .with_home(root.join("home-a"));
502
    assert_eq!(a.id().unwrap(), origin.id().unwrap());
503
    let (key_a, _) = a
504
        .create_identity("Ada", "[email protected]", IdentityScope::Repo)
505
        .unwrap();
506
    write(&root.join("a"), "f.txt", b"a\n");
507
    let h1 = a.commit("first", &[]).unwrap();
508
    let results = a.push("origin", false).unwrap();
509
    assert!(results[0].ok, "{}", results[0].reason);
510
    assert_eq!(origin.bookmark_heads().unwrap(), vec![h1]);
511
    // The change was sealed at push and the reference attested.
512
    assert!(
513
        matches!(origin.authenticate_change(&h1).unwrap(), SignatureStatus::Valid { key, sealed: true, .. } if key == key_a)
514
    );
515
    assert_eq!(
516
        origin.verify_change(&h1).unwrap(),
517
        SignatureStatus::Unsigned
518
    );
519
    let serial_of = |att: &SignedAttest| match att.attest.body {
520
        AttestBody::Ref { serial, .. } => serial,
521
        _ => unreachable!(),
522
    };
523
    let (_, att) = origin.latest_ref_attest("main").unwrap().unwrap();
524
    // A bookmark new to the remote starts at the clock (past any deleted
525
    // namesake's serial); later updates count up from there.
526
    let first = serial_of(&att);
527
    assert!(first > 1_000_000_000_000, "{first}");
528
    let again = a.push("origin", false).unwrap();
529
    assert!(again[0].ok && again[0].reason.contains("up to date"));
530
    let (_, att) = origin.latest_ref_attest("main").unwrap().unwrap();
531
    assert_eq!(serial_of(&att), first, "a no-op push does not attest again");
532
533
    // B clones and sees the file and the seal.
534
    let b = Repo::clone(&origin_url, &root.join("b")).unwrap();
535
    assert_eq!(fs::read(root.join("b/f.txt")).unwrap(), b"a\n");
536
    assert_eq!(b.bookmark_heads().unwrap(), vec![h1]);
537
    assert!(matches!(
538
        b.authenticate_change(&h1).unwrap(),
539
        SignatureStatus::Valid { sealed: true, .. }
540
    ));
541
542
    // B (no identity) commits and pushes unsigned; the unverified origin accepts.
543
    write(&root.join("b"), "f.txt", b"a\nb\n");
544
    let h2 = b.commit("second", &[]).unwrap();
545
    assert!(b.push("origin", false).unwrap()[0].ok);
546
    assert_eq!(origin.bookmark_heads().unwrap(), vec![h2]);
547
548
    // A commits an independent change; push is refused until A pulls.
549
    write(&root.join("a"), "g.txt", b"g\n");
550
    let h3 = a.commit("third", &[]).unwrap();
551
    assert!(a.push("origin", false).is_err());
552
    let pr = a.pull("origin").unwrap();
553
    assert!(pr.changed && pr.checked_out);
554
    let mut want = vec![h2, h3];
555
    want.sort();
556
    assert_eq!(pr.heads, want);
557
    assert_eq!(fs::read(root.join("a/f.txt")).unwrap(), b"a\nb\n");
558
    assert_eq!(fs::read(root.join("a/g.txt")).unwrap(), b"g\n");
559
    let results = a.push("origin", false).unwrap();
560
    assert!(results[0].ok, "{}", results[0].reason);
561
    let mut origin_heads = origin.bookmark_heads().unwrap();
562
    origin_heads.sort();
563
    assert_eq!(origin_heads, want);
564
    let (_, att) = origin.latest_ref_attest("main").unwrap().unwrap();
565
    assert_eq!(serial_of(&att), first + 1);
566
567
    // B pulls and ends up identical.
568
    let pr = b.pull("origin").unwrap();
569
    assert_eq!(pr.heads, want);
570
    assert_eq!(fs::read(root.join("b/g.txt")).unwrap(), b"g\n");
571
    assert!(!b.snapshot("status").unwrap().changed);
572
573
    // Concurrent edits of the same line: the union is a reified conflict.
574
    write(&root.join("a"), "f.txt", b"a\nA\n");
575
    a.commit("a-edit", &[]).unwrap();
576
    a.push("origin", false).unwrap();
577
    write(&root.join("b"), "f.txt", b"a\nB\n");
578
    b.commit("b-edit", &[]).unwrap();
579
    let pr = b.pull("origin").unwrap();
580
    assert!(pr.changed && pr.checked_out);
581
    let text = fs::read_to_string(root.join("b/f.txt")).unwrap();
582
    assert!(text.contains("<<<<<<< oxy conflict"), "{text}");
583
    write(&root.join("b"), "f.txt", b"a\nAB\n");
584
    let hr = b.commit("resolve", &[]).unwrap();
585
    assert_eq!(
586
        b.store().get_change(&hr).unwrap().kind,
587
        ChangeKind::Resolution
588
    );
589
    assert!(b.push("origin", false).unwrap()[0].ok);
590
    a.pull("origin").unwrap();
591
    assert_eq!(fs::read(root.join("a/f.txt")).unwrap(), b"a\nAB\n");
592
    // The resolution depends on the conflicting edits, but nothing depends
593
    // on "third" (it only added g.txt), so it stays a head beside it.
594
    let mut want = vec![hr, h3];
595
    want.sort();
596
    assert_eq!(a.bookmark_heads().unwrap(), want);
597
    assert!(!a.load_state(&want).unwrap().materialize().is_conflicted());
598
}
599
600
#[test]
601
fn receive_push_rejects_bad_updates() {
602
    hermetic();
603
    let dir = tempfile::tempdir().unwrap();
604
    let root = dir.path();
605
    let origin = Repo::init(&root.join("origin")).unwrap();
606
    let url = root.join("origin").to_string_lossy().to_string();
607
    let mut a = Repo::clone(&url, &root.join("a"))
608
        .unwrap()
609
        .with_home(root.join("home"));
610
    let (key, _) = a
611
        .create_identity("Ada", "a@b", IdentityScope::Repo)
612
        .unwrap();
613
    write(&root.join("a"), "f.txt", b"x\n");
614
    let h1 = a.commit("one", &[]).unwrap();
615
    assert!(a.push("origin", false).unwrap()[0].ok);
616
    let empty = origin.store().put_state(&StateObject::new(vec![])).unwrap();
617
    let s1 = origin
618
        .store()
619
        .put_state(&StateObject::new(vec![h1]))
620
        .unwrap();
621
622
    // Missing head.
623
    let ghost = origin
624
        .store()
625
        .put_state(&StateObject::new(vec![ObjectRef([9; 32])]))
626
        .unwrap();
627
    let r = origin
628
        .receive_push(
629
            Bundle::default(),
630
            vec![RefUpdate {
631
                name: "main".into(),
632
                old_state: s1,
633
                new_state: ghost,
634
                force: false,
635
                attestation: None,
636
            }],
637
            None,
638
            vec![],
639
        )
640
        .unwrap();
641
    assert!(
642
        !r[0].ok && r[0].reason.contains("missing"),
643
        "{}",
644
        r[0].reason
645
    );
646
647
    // Stale old_state.
648
    let r = origin
649
        .receive_push(
650
            Bundle::default(),
651
            vec![RefUpdate {
652
                name: "main".into(),
653
                old_state: empty,
654
                new_state: s1,
655
                force: false,
656
                attestation: None,
657
            }],
658
            None,
659
            vec![],
660
        )
661
        .unwrap();
662
    assert!(!r[0].ok && r[0].reason.contains("stale"), "{}", r[0].reason);
663
664
    // Non-fast-forward without force is refused; with force it passes.
665
    let r = origin
666
        .receive_push(
667
            Bundle::default(),
668
            vec![RefUpdate {
669
                name: "main".into(),
670
                old_state: s1,
671
                new_state: empty,
672
                force: false,
673
                attestation: None,
674
            }],
675
            None,
676
            vec![],
677
        )
678
        .unwrap();
679
    assert!(
680
        !r[0].ok && r[0].reason.contains("fast-forward"),
681
        "{}",
682
        r[0].reason
683
    );
684
    let r = origin
685
        .receive_push(
686
            Bundle::default(),
687
            vec![RefUpdate {
688
                name: "main".into(),
689
                old_state: s1,
690
                new_state: empty,
691
                force: true,
692
                attestation: None,
693
            }],
694
            None,
695
            vec![],
696
        )
697
        .unwrap();
698
    assert!(r[0].ok);
699
    assert_eq!(origin.bookmark_heads().unwrap(), vec![]);
700
701
    // Attestation with a stale serial is a rollback and is refused.
702
    let sa = a
703
        .sign_attest(&Attest {
704
            repo: a.id().unwrap(),
705
            hlc: Hlc::now(),
706
            body: AttestBody::Ref {
707
                name: "main".into(),
708
                old_state: empty,
709
                new_state: s1,
710
                serial: 1,
711
            },
712
        })
713
        .unwrap();
714
    let r = origin
715
        .receive_push(
716
            Bundle::default(),
717
            vec![RefUpdate {
718
                name: "main".into(),
719
                old_state: empty,
720
                new_state: s1,
721
                force: false,
722
                attestation: Some(sa.clone()),
723
            }],
724
            None,
725
            vec![],
726
        )
727
        .unwrap();
728
    assert!(
729
        !r[0].ok && r[0].reason.contains("serial"),
730
        "{}",
731
        r[0].reason
732
    );
733
    // An attestation for a different update is refused too.
734
    let sa2 = a
735
        .sign_attest(&Attest {
736
            repo: a.id().unwrap(),
737
            hlc: Hlc::now(),
738
            body: AttestBody::Ref {
739
                name: "main".into(),
740
                old_state: s1,
741
                new_state: empty,
742
                serial: 5,
743
            },
744
        })
745
        .unwrap();
746
    let r = origin
747
        .receive_push(
748
            Bundle::default(),
749
            vec![RefUpdate {
750
                name: "main".into(),
751
                old_state: empty,
752
                new_state: s1,
753
                force: false,
754
                attestation: Some(sa2),
755
            }],
756
            None,
757
            vec![],
758
        )
759
        .unwrap();
760
    assert!(
761
        !r[0].ok && r[0].reason.contains("describe"),
762
        "{}",
763
        r[0].reason
764
    );
765
    let _ = key;
766
}
767
768
#[test]
769
fn user_config_supplies_defaults_and_clones_sign() {
770
    hermetic();
771
    let dir = tempfile::tempdir().unwrap();
772
    let root = dir.path();
773
    let home = root.join("home");
774
    let origin = Repo::init(&root.join("origin")).unwrap();
775
    let url = root.join("origin").to_string_lossy().to_string();
776
777
    // Identity at user scope: the repository file stays free of author keys.
778
    let mut a = Repo::init(&root.join("a")).unwrap().with_home(&home);
779
    let (key, _) = a
780
        .create_identity("Ada", "[email protected]", IdentityScope::User)
781
        .unwrap();
782
    assert!(!a.config.repo_layer().contains_key("author.key"));
783
    assert_eq!(a.config.author_key, Some(key));
784
    assert!(home.join("config.toml").exists());
785
    a.set_user_config("core.sign", "change").unwrap();
786
    assert!(a.config.sign_changes);
787
788
    // Repository settings override user settings and are the only ones saved.
789
    a.config.set("core.sign", "seal").unwrap();
790
    a.save_config().unwrap();
791
    let again = Repo::open(&root.join("a")).unwrap().with_home(&home);
792
    assert!(!again.config.sign_changes);
793
    assert_eq!(again.config.author_key, Some(key));
794
    assert_eq!(
795
        read_config_file(&root.join("a/.oxy/config"))
796
            .unwrap()
797
            .get("core.sign")
798
            .map(String::as_str),
799
        Some("seal")
800
    );
801
802
    // A fresh clone made by this user signs with the user-level identity,
803
    // even though the clone's store has never seen the identity object.
804
    let b = Repo::clone(&url, &root.join("b")).unwrap().with_home(&home);
805
    assert!(b.config.sign_changes);
806
    write(&root.join("b"), "f.txt", b"f\n");
807
    let h = b.commit("signed from a clone", &[]).unwrap();
808
    assert!(
809
        matches!(b.verify_change(&h).unwrap(), SignatureStatus::Valid { key: k, .. } if k == key)
810
    );
811
    assert!(b.push("origin", false).unwrap()[0].ok);
812
    assert!(matches!(
813
        origin.verify_change(&h).unwrap(),
814
        SignatureStatus::Valid { .. }
815
    ));
816
}
817
818
#[test]
819
fn format1_repositories_are_migrated_on_open() {
820
    hermetic();
821
    use crate::oplog::{Format1Op, Format1View};
822
    let dir = tempfile::tempdir().unwrap();
823
    let root = dir.path();
824
    let repo = Repo::init(root).unwrap();
825
    write(root, "a.txt", b"a\n");
826
    let h1 = repo.commit("one", &[]).unwrap();
827
    let (wc_hash, _) = repo.working_copy().unwrap();
828
    // Rewrite the op log the way format 1 stored it: two ops, head lists.
829
    let mut v1 = Format1View::default();
830
    v1.bookmarks.insert("main".into(), vec![]);
831
    v1.workspaces.insert(repo.workspace(), wc_hash);
832
    let init = Format1Op {
833
        parents: vec![],
834
        hlc: Hlc::default(),
835
        command: "oxy init".into(),
836
        view: v1.clone(),
837
    };
838
    let init_ref = repo.store().put(ObjectType::Op, &init.encode()).unwrap();
839
    v1.bookmarks.insert("main".into(), vec![h1]);
840
    let commit = Format1Op {
841
        parents: vec![init_ref],
842
        hlc: Hlc::default(),
843
        command: "oxy commit".into(),
844
        view: v1,
845
    };
846
    let commit_ref = repo.store().put(ObjectType::Op, &commit.encode()).unwrap();
847
    write_atomic(&root.join(".oxy/ops/head"), commit_ref.to_hex().as_bytes()).unwrap();
848
    write_atomic(&root.join(".oxy/format"), FORMAT1_LINE.as_bytes()).unwrap();
849
    drop(repo);
850
851
    let repo = Repo::open(root).unwrap();
852
    assert_eq!(
853
        fs::read_to_string(root.join(".oxy/format")).unwrap(),
854
        FORMAT_LINE
855
    );
856
    assert_eq!(repo.bookmark_heads().unwrap(), vec![h1]);
857
    let ops = repo.op_log().unwrap();
858
    assert_eq!(
859
        ops.iter()
860
            .map(|(_, o)| o.command.as_str())
861
            .collect::<Vec<_>>(),
862
        ["oxy commit", "oxy init"]
863
    );
864
    assert_eq!(repo.heads_of(&ops[1].1.view, "main").unwrap(), vec![]);
865
    assert!(!repo.snapshot("status").unwrap().changed);
866
    // Reopening again is a no-op.
867
    assert_eq!(Repo::open(root).unwrap().op_log().unwrap().len(), 2);
868
}
869
870
#[test]
871
fn undo_skips_snapshot_operations() {
872
    hermetic();
873
    let dir = tempfile::tempdir().unwrap();
874
    let root = dir.path();
875
    let repo = Repo::init(root).unwrap();
876
    write(root, "a.txt", b"a\n");
877
    let h1 = repo.commit("a", &[]).unwrap();
878
    // A later command snapshots new edits on top of the commit.
879
    write(root, "b.txt", b"b\n");
880
    let s = repo.snapshot("oxy status").unwrap();
881
    assert!(s.changed);
882
    assert!(repo.head_op().unwrap().1.is_snapshot());
883
    assert_eq!(repo.last_command().unwrap().command, "oxy commit -m \"a\"");
884
    // Undo must undo the commit, not the snapshot.
885
    repo.undo().unwrap();
886
    assert_eq!(repo.bookmark_heads().unwrap(), vec![]);
887
    let s = repo.snapshot("oxy status").unwrap();
888
    let paths: Vec<_> = s.statuses.iter().map(|p| p.path.as_str()).collect();
889
    assert_eq!(
890
        paths,
891
        ["a.txt", "b.txt"],
892
        "both files are back in the working copy"
893
    );
894
    assert!(repo.store().get_change(&h1).unwrap().deps.is_empty());
895
    // Only snapshots remain above `init`, so there is nothing left to undo.
896
    assert_eq!(repo.last_command().unwrap().command, "oxy init");
897
    assert!(repo.undo().is_err());
898
}
899
900
#[test]
901
fn independent_changes_commute_and_make_multiple_heads() {
902
    hermetic();
903
    let dir = tempfile::tempdir().unwrap();
904
    let root = dir.path();
905
    let repo = Repo::init(root).unwrap();
906
    write(root, "a.txt", b"a\n");
907
    let h1 = repo.commit("a", &[]).unwrap();
908
    write(root, "b.txt", b"b\n");
909
    let h2 = repo.commit("b", &[]).unwrap();
910
    let c2 = repo.store().get_change(&h2).unwrap();
911
    assert!(c2.deps.is_empty(), "b.txt touches nothing from h1");
912
    let mut heads = repo.bookmark_heads().unwrap();
913
    heads.sort();
914
    let mut want = vec![h1, h2];
915
    want.sort();
916
    assert_eq!(heads, want);
917
    // Editing a.txt depends on h1 only.
918
    write(root, "a.txt", b"a\na2\n");
919
    let h3 = repo.commit("a2", &[]).unwrap();
920
    assert_eq!(repo.store().get_change(&h3).unwrap().deps, vec![h1]);
921
    let heads: BTreeSet<_> = repo.bookmark_heads().unwrap().into_iter().collect();
922
    assert_eq!(heads, [h2, h3].into_iter().collect());
923
    // Explicit dependency.
924
    write(root, "c.txt", b"c\n");
925
    let h4 = repo.commit("c", &[h2]).unwrap();
926
    assert_eq!(repo.store().get_change(&h4).unwrap().deps, vec![h2]);
927
}
928
929
#[test]
930
fn mode_change_and_text_binary_switch() {
931
    hermetic();
932
    let dir = tempfile::tempdir().unwrap();
933
    let root = dir.path();
934
    let repo = Repo::init(root).unwrap();
935
    write(root, "run.sh", b"#!/bin/sh\n");
936
    repo.commit("add script", &[]).unwrap();
937
    #[cfg(unix)]
938
    {
939
        use std::os::unix::fs::PermissionsExt;
940
        fs::set_permissions(root.join("run.sh"), fs::Permissions::from_mode(0o755)).unwrap();
941
        let s = repo.snapshot("status").unwrap();
942
        assert_eq!(
943
            statuses(&s),
944
            vec![("run.sh".into(), ChangeStatus::ModeChanged)]
945
        );
946
        let h = repo.commit("exec", &[]).unwrap();
947
        let snap = repo.load_state(&[h]).unwrap().materialize();
948
        assert!(snap.files["run.sh"].mode.exec);
949
    }
950
    // Text → binary → text.
951
    write(root, "run.sh", b"\0binary");
952
    let h = repo.commit("binary", &[]).unwrap();
953
    let snap = repo.load_state(&[h]).unwrap().materialize();
954
    assert!(snap.files["run.sh"].mode.opaque);
955
    write(root, "run.sh", b"text again\n");
956
    let h = repo.commit("text", &[]).unwrap();
957
    let snap = repo.load_state(&[h]).unwrap().materialize();
958
    assert!(!snap.files["run.sh"].mode.opaque);
959
    assert!(
960
        matches!(&snap.files["run.sh"].content, FileContent::Text { bytes, .. } if bytes == b"text again\n")
961
    );
962
    assert!(!snap.is_conflicted());
963
}
964
965
/// oxygen#87: a binary file given new contents and the executable bit in
966
/// one commit kept the contents and lost the bit.
967
#[cfg(unix)]
968
#[test]
969
fn a_binary_file_changed_and_made_executable_at_once_keeps_both() {
970
    use std::os::unix::fs::PermissionsExt;
971
    hermetic();
972
    let dir = tempfile::tempdir().unwrap();
973
    let root = dir.path();
974
    let repo = Repo::init(root).unwrap();
975
    write(root, "tool.exe", b"MZ\0one");
976
    repo.commit("add", &[]).unwrap();
977
    write(root, "tool.exe", b"MZ\0two");
978
    fs::set_permissions(root.join("tool.exe"), fs::Permissions::from_mode(0o755)).unwrap();
979
    let h = repo.commit("update and +x", &[]).unwrap();
980
    let snap = repo.load_state(&[h]).unwrap().materialize();
981
    let f = &snap.files["tool.exe"];
982
    assert!(f.mode.opaque && f.mode.exec, "{:?}", f.mode);
983
    assert!(
984
        repo.snapshot("status").unwrap().statuses.is_empty(),
985
        "nothing left to commit"
986
    );
987
}
988
989
/// Keyless step 4 (oxygenhub#241): an agent signing with a short-lived
990
/// key whose certificate an issuer gave pushes when the policy grants its
991
/// subject, and a fetch accepts what it attested; an expired certificate,
992
/// or a subject the policy does not grant, may not move the bookmark.
993
#[test]
994
fn a_certified_key_pushes_under_a_subject_grant() {
995
    use crate::cert::{Certificate, SignedCertificate};
996
    use crate::identity::Scope;
997
    hermetic();
998
    let dir = tempfile::tempdir().unwrap();
999
    let root = dir.path();
1000
    let _origin = Repo::init(&root.join("origin")).unwrap();
1001
    let url = root.join("origin").to_string_lossy().to_string();
1002
    let mut a = Repo::clone(&url, &root.join("a"))
1003
        .unwrap()
1004
        .with_home(root.join("home-a"));
1005
    a.create_identity("Ada", "[email protected]", IdentityScope::User)
1006
        .unwrap();
1007
    write(&root.join("a"), "a.txt", b"a\n");
1008
    a.commit("a", &[]).unwrap();
1009
    a.policy_init().unwrap();
1010
    assert!(a.push("origin", false).unwrap().iter().all(|r| r.ok));
1011
    let hub_sk = SecretKey::generate();
1012
    let hub = hub_sk.identity("hub", "[email protected]", 1);
1013
    a.policy_grant_subject(
1014
        "agent:claude@ada",
1015
        hub.clone(),
1016
        Scope::CHANGES | Scope::REFS,
1017
        None,
1018
    )
1019
    .unwrap();
1020
    assert!(a
1021
        .push("origin", false)
1022
        .unwrap()
1023
        .iter()
1024
        .any(|r| r.name == "policy" && r.ok));
1025
1026
    let now = Hlc::now().wall_ms;
1027
    // An agent repository whose key the hub certified for `subject`, from
1028
    // `from` to `to`.
1029
    let agent = |name: &str, subject: &str, from: u64, to: u64| {
1030
        let mut r = Repo::clone(&url, &root.join(name))
1031
            .unwrap()
1032
            .with_home(root.join(format!("home-{name}")));
1033
        let (_, id) = r
1034
            .create_identity(name, "[email protected]", IdentityScope::User)
1035
            .unwrap();
1036
        let cert = SignedCertificate::sign(
1037
            Certificate {
1038
                key: id,
1039
                issuer: hub.hash(),
1040
                subject: subject.into(),
1041
                claims: vec![],
1042
                scope: Scope::CHANGES | Scope::REFS,
1043
                not_before: from,
1044
                expires: to,
1045
            },
1046
            &hub,
1047
            &hub_sk,
1048
        );
1049
        r.store().put_identity(&hub).unwrap();
1050
        r.store().put_certificate(&cert).unwrap();
1051
        write(&root.join(name), &format!("{name}.txt"), b"agent work\n");
1052
        r.commit("work", &[]).unwrap();
1053
        r
1054
    };
1055
1056
    let claude = agent("claude", "agent:claude@ada", now - 60_000, now + 600_000);
1057
    let r = claude.push("origin", false).unwrap();
1058
    assert!(r.iter().all(|x| x.ok), "{r:?}");
1059
    // Ada's fetch accepts the bookmark the certified key attested.
1060
    a.pull("origin").unwrap();
1061
    assert!(a.bookmark_heads().unwrap().iter().any(|h| a
1062
        .store()
1063
        .get_change(h)
1064
        .map(|c| c.message == "work")
1065
        .unwrap_or(false)));
1066
1067
    // Step 4c: a host with an acceptor key records when it accepted the
1068
    // certified update and serves it; a fetch checks the certificate at
1069
    // that time only when the certificate's issuer signed it for exactly
1070
    // this attestation, else at the attestation's own time.
1071
    let host = Repo::open(&root.join("origin"))
1072
        .unwrap()
1073
        .with_acceptor(hub.clone(), hub_sk.clone());
1074
    let (attest_ref, sa) = host.latest_ref_attest("main").unwrap().unwrap();
1075
    host.record_acceptance(&attest_ref).unwrap();
1076
    let served = host.remote_refs().unwrap();
1077
    let acc = served
1078
        .refs
1079
        .iter()
1080
        .find(|r| r.name == "main")
1081
        .unwrap()
1082
        .accepted
1083
        .clone()
1084
        .expect("served with the refs");
1085
    let signer = sa.sigs[0].key;
1086
    assert_eq!(
1087
        a.certified_time(&signer, &sa, Some(&acc)),
1088
        acc.attest.hlc.wall_ms
1089
    );
1090
    assert_eq!(a.certified_time(&signer, &sa, None), sa.attest.hlc.wall_ms);
1091
    let stranger_sk = SecretKey::generate();
1092
    let stranger = stranger_sk.identity("stranger", "s@x", 1);
1093
    let mut forged = acc.clone();
1094
    forged.sigs = vec![stranger_sk.sign(Domain::Attest, &stranger.hash(), &acc.attest.hash())];
1095
    assert_eq!(
1096
        a.certified_time(&signer, &sa, Some(&forged)),
1097
        sa.attest.hlc.wall_ms,
1098
        "not the issuer's"
1099
    );
1100
    let mut elsewhere = acc.clone();
1101
    elsewhere.attest.body = AttestBody::Accepted {
1102
        attest: ObjectRef([7; 32]),
1103
    };
1104
    elsewhere.sigs = vec![hub_sk.sign(Domain::Attest, &hub.hash(), &elsewhere.attest.hash())];
1105
    assert_eq!(
1106
        a.certified_time(&signer, &sa, Some(&elsewhere)),
1107
        sa.attest.hlc.wall_ms,
1108
        "another attestation's"
1109
    );
1110
    a.pull("origin").unwrap();
1111
    // gc keeps the acceptance with the attestation.
1112
    host.gc(true).unwrap();
1113
    assert!(host.acceptance_of(&attest_ref).unwrap().is_some());
1114
1115
    let late = agent("late", "agent:claude@ada", now - 1_200_000, now - 600_000);
1116
    let r = late.push("origin", false).unwrap();
1117
    assert!(
1118
        !r[0].ok && r[0].reason.contains("may not update"),
1119
        "an expired certificate: {r:?}"
1120
    );
1121
    let other = agent("other", "agent:mallory@ada", now - 60_000, now + 600_000);
1122
    let r = other.push("origin", false).unwrap();
1123
    assert!(
1124
        !r[0].ok && r[0].reason.contains("may not update"),
1125
        "a subject not granted: {r:?}"
1126
    );
1127
}
1128
1129
#[test]
1130
fn trust_policy_governs_pushes_and_fetches() {
1131
    hermetic();
1132
    let dir = tempfile::tempdir().unwrap();
1133
    let root = dir.path();
1134
    let origin = Repo::init(&root.join("origin")).unwrap();
1135
    let url = root.join("origin").to_string_lossy().to_string();
1136
1137
    // A is the root. Before the policy, an unsigned push from B is fine.
1138
    let mut a = Repo::clone(&url, &root.join("a"))
1139
        .unwrap()
1140
        .with_home(root.join("home-a"));
1141
    let (key_a, _) = a
1142
        .create_identity("Ada", "[email protected]", IdentityScope::User)
1143
        .unwrap();
1144
    let mut b = Repo::clone(&url, &root.join("b"))
1145
        .unwrap()
1146
        .with_home(root.join("home-b"));
1147
    write(&root.join("b"), "b.txt", b"b\n");
1148
    b.commit("unsigned before policy", &[]).unwrap();
1149
    assert!(b.push("origin", false).unwrap()[0].ok);
1150
1151
    // A creates the policy and pushes it; origin now enforces it.
1152
    write(&root.join("a"), "a.txt", b"a\n");
1153
    a.commit("a", &[]).unwrap();
1154
    let sp = a.policy_init().unwrap();
1155
    assert_eq!(sp.policy.serial, 1);
1156
    a.pull("origin").unwrap();
1157
    let results = a.push("origin", false).unwrap();
1158
    assert!(results.iter().all(|r| r.ok), "{results:?}");
1159
    assert_eq!(origin.current_policy().unwrap().unwrap().1.policy.serial, 1);
1160
1161
    // B pulls the policy. Without an identity B cannot push at all.
1162
    b.pull("origin").unwrap();
1163
    assert!(
1164
        b.current_policy().unwrap().is_some(),
1165
        "the policy arrived with the fetch"
1166
    );
1167
    assert!(b.push("origin", false).is_err());
1168
    // With an identity the policy does not list, the push is rejected by origin.
1169
    let (key_b, id_b) = b
1170
        .create_identity("Bob", "[email protected]", IdentityScope::User)
1171
        .unwrap();
1172
    write(&root.join("b"), "b.txt", b"b2\n");
1173
    let h_b2 = b.commit("b2 as Bob", &[]).unwrap();
1174
    assert_eq!(b.store().get_change(&h_b2).unwrap().author, key_b);
1175
    let r = b.push("origin", false).unwrap();
1176
    assert!(
1177
        !r[0].ok && r[0].reason.contains("may not update"),
1178
        "{:?}",
1179
        r
1180
    );
1181
1182
    // A grants B (identity handed over as a file) and publishes the policy.
1183
    let sp = a.policy_grant(id_b.clone(), None).unwrap();
1184
    assert_eq!(sp.policy.serial, 2);
1185
    let r = a.push("origin", false).unwrap();
1186
    assert!(r.iter().any(|x| x.name == "policy" && x.ok), "{r:?}");
1187
    // B must fetch the new policy before pushing.
1188
    assert!(b
1189
        .push("origin", false)
1190
        .unwrap_or_else(|e| vec![RefResult {
1191
            name: "main".into(),
1192
            ok: false,
1193
            reason: e.to_string()
1194
        }])
1195
        .iter()
1196
        .all(|x| !x.ok));
1197
    b.pull("origin").unwrap();
1198
    assert_eq!(b.current_policy().unwrap().unwrap().1.policy.serial, 2);
1199
    let r = b.push("origin", false).unwrap();
1200
    assert!(r[0].ok, "{:?}", r);
1201
    // Origin verified B's change under the policy.
1202
    let heads = origin.bookmark_heads().unwrap();
1203
    for h in &heads {
1204
        let c = origin.store().get_change(h).unwrap();
1205
        if c.author == key_b {
1206
            origin
1207
                .change_allowed(
1208
                    h,
1209
                    &origin.current_policy().unwrap().unwrap().1.policy,
1210
                    "main",
1211
                )
1212
                .unwrap();
1213
        }
1214
    }
1215
1216
    // A policy signed by a non-root (B) is refused, as is a replayed serial.
1217
    let mut forged = b.current_policy().unwrap().unwrap().1.policy.clone();
1218
    forged.serial = 3;
1219
    forged.roots = vec![key_b];
1220
    let fh = forged.hash();
1221
    let (_, sk_b) = b.secret_key().unwrap().unwrap();
1222
    let forged = SignedPolicy {
1223
        policy: forged,
1224
        sigs: vec![sk_b.sign(Domain::Policy, &key_b, &fh)],
1225
    };
1226
    let r = origin
1227
        .receive_push(Bundle::default(), vec![], Some(forged), vec![])
1228
        .unwrap();
1229
    assert!(!r[0].ok && r[0].reason.contains("root"), "{:?}", r);
1230
    let stale = a.current_policy().unwrap().unwrap().1;
1231
    let mut old = stale.clone();
1232
    old.policy.serial = 1;
1233
    let r = origin
1234
        .receive_push(Bundle::default(), vec![], Some(old), vec![])
1235
        .unwrap();
1236
    assert!(!r[0].ok && r[0].reason.contains("serial"), "{:?}", r);
1237
1238
    // A revokes B; after B pulls the policy, B's pushes are refused again.
1239
    a.pull("origin").unwrap();
1240
    a.policy_revoke(&key_b).unwrap();
1241
    let r = a.push("origin", false).unwrap();
1242
    assert!(r.iter().any(|x| x.name == "policy" && x.ok), "{r:?}");
1243
    b.pull("origin").unwrap();
1244
    write(&root.join("b"), "b.txt", b"b3\n");
1245
    b.commit("b3", &[]).unwrap();
1246
    let r = b.push("origin", false).unwrap();
1247
    assert!(!r[0].ok, "{:?}", r);
1248
1249
    // A clone by a third party receives and verifies everything.
1250
    let c = Repo::clone(&url, &root.join("c"))
1251
        .unwrap()
1252
        .with_home(root.join("home-c"));
1253
    assert_eq!(c.current_policy().unwrap().unwrap().1.policy.serial, 3);
1254
    assert!(c
1255
        .current_policy()
1256
        .unwrap()
1257
        .unwrap()
1258
        .1
1259
        .policy
1260
        .roots
1261
        .contains(&key_a));
1262
    assert!(!c.snapshot("status").unwrap().changed);
1263
}
1264
1265
/// oxygen#66: a gc says what it is doing, phase by phase.
1266
#[test]
1267
fn gc_reports_its_phases() {
1268
    hermetic();
1269
    let dir = tempfile::tempdir().unwrap();
1270
    let repo = Repo::init(dir.path()).unwrap();
1271
    for i in 0..3 {
1272
        write(
1273
            dir.path(),
1274
            &format!("f{i}.txt"),
1275
            format!("{i}\n").as_bytes(),
1276
        );
1277
        repo.commit(&format!("c{i}"), &[]).unwrap();
1278
    }
1279
    let mut phases = Vec::new();
1280
    repo.gc_with(true, &mut |p| phases.push(p.to_string()))
1281
        .unwrap();
1282
    assert_eq!(phases[0], "finding what is reachable", "{phases:?}");
1283
    assert!(
1284
        phases.iter().any(|p| p.starts_with("pruning")),
1285
        "{phases:?}"
1286
    );
1287
    assert!(
1288
        phases.iter().any(|p| p.starts_with("packing 0 of ")),
1289
        "{phases:?}"
1290
    );
1291
    assert!(
1292
        phases
1293
            .iter()
1294
            .any(|p| p.starts_with("writing the index of ")),
1295
        "{phases:?}"
1296
    );
1297
}
1298
1299
#[test]
1300
fn gc_packs_objects_and_history_still_works() {
1301
    hermetic();
1302
    let dir = tempfile::tempdir().unwrap();
1303
    let root = dir.path();
1304
    let mut repo = Repo::init(root).unwrap().with_home(root.join("home"));
1305
    repo.create_identity("Ada", "a@b", IdentityScope::User)
1306
        .unwrap();
1307
    repo.set_user_config("core.sign", "change").unwrap();
1308
    write(root, "a.txt", b"one\n");
1309
    let h1 = repo.commit("one", &[]).unwrap();
1310
    write(root, "a.txt", b"two\n");
1311
    write(root, "big.bin", &vec![0u8; 100_000]);
1312
    let h2 = repo.commit("two", &[]).unwrap();
1313
    // Several snapshots leave superseded working-copy versions behind.
1314
    for i in 0..5 {
1315
        write(root, "a.txt", format!("two\n{i}\n").as_bytes());
1316
        repo.snapshot("status").unwrap();
1317
    }
1318
    write(root, "a.txt", b"two\n");
1319
    repo.snapshot("status").unwrap();
1320
    let before = repo.store().list().unwrap();
1321
    assert!(repo.store().loose_count().unwrap() > 0);
1322
1323
    // With the default retention every operation's view is a root: nothing prunes.
1324
    let r = repo.gc(true).unwrap();
1325
    assert_eq!(r.packed.objects, before.len());
1326
    assert_eq!(r.pruned.objects, 0);
1327
    assert_eq!(repo.store().loose_count().unwrap(), 0);
1328
    assert_eq!(repo.store().list().unwrap(), before);
1329
1330
    // With zero retention only the current view is a root: superseded
1331
    // working copies go, everything reachable stays.
1332
    repo.config.set("core.op-retention", "0").unwrap();
1333
    repo.save_config().unwrap();
1334
    let mut repo = Repo::open(root).unwrap().with_home(root.join("home"));
1335
    let r = repo.gc(true).unwrap();
1336
    assert!(r.pruned.objects >= 5, "{r:?}");
1337
    let after = repo.store().list().unwrap();
1338
    assert!(after.len() < before.len());
1339
    assert!(after.contains(&h1) && after.contains(&h2));
1340
    for (_, op) in repo.op_log().unwrap() {
1341
        assert!(!op.command.is_empty(), "operation objects are all kept");
1342
    }
1343
    // Everything still works from the pruned, packed store.
1344
    assert_eq!(repo.bookmark_heads().unwrap(), vec![h2]);
1345
    assert!(matches!(
1346
        repo.verify_change(&h2).unwrap(),
1347
        SignatureStatus::Valid { .. }
1348
    ));
1349
    assert_eq!(repo.log().unwrap().len(), 3);
1350
    repo.checkout(&[h1], false, "checkout").unwrap();
1351
    assert_eq!(fs::read(root.join("a.txt")).unwrap(), b"one\n");
1352
    repo.checkout(&[h2], false, "checkout").unwrap();
1353
    assert_eq!(fs::read(root.join("big.bin")).unwrap().len(), 100_000);
1354
    assert!(!repo.snapshot("status").unwrap().changed);
1355
    // Grace period defers pruning of young garbage.
1356
    write(root, "a.txt", b"three\n");
1357
    repo.commit("three", &[]).unwrap();
1358
    let r = repo.gc(false).unwrap();
1359
    assert_eq!(r.pruned.objects, 0);
1360
    assert!(r.pruned.deferred > 0);
1361
    let r = repo.gc(true).unwrap();
1362
    assert!(r.pruned.objects > 0);
1363
    assert_eq!(repo.log().unwrap().len(), 4);
1364
    // Restoring the default retention makes the old views roots again; the
1365
    // working copies they name were pruned, which gc tolerates.
1366
    repo.config.set("core.op-retention", "90").unwrap();
1367
    repo.save_config().unwrap();
1368
    let repo = Repo::open(root).unwrap().with_home(root.join("home"));
1369
    let r = repo.gc(false).unwrap();
1370
    assert_eq!(r.pruned.objects, 0);
1371
    assert_eq!(repo.log().unwrap().len(), 4);
1372
}
1373
1374
#[test]
1375
fn describe_amend_abandon_heads() {
1376
    hermetic();
1377
    let dir = tempfile::tempdir().unwrap();
1378
    let root = dir.path();
1379
    let mut repo = Repo::init(root).unwrap().with_home(root.join("home"));
1380
    repo.create_identity("Ada", "a@b", IdentityScope::User)
1381
        .unwrap();
1382
    repo.set_user_config("core.sign", "change").unwrap();
1383
    write(root, "a.txt", b"one\n");
1384
    let h1 = repo.commit("first", &[]).unwrap();
1385
    write(root, "a.txt", b"one\ntwo\n");
1386
    let h2 = repo.commit("secnod", &[]).unwrap();
1387
    let id2 = repo.store().get_change(&h2).unwrap().change_id;
1388
1389
    // describe: same ChangeId, new hash, bookmark and working copy follow.
1390
    let h2b = repo.describe(&h2, "second").unwrap();
1391
    assert_ne!(h2b, h2);
1392
    let c = repo.store().get_change(&h2b).unwrap();
1393
    assert_eq!(
1394
        (c.change_id, c.message.as_str(), c.deps.clone()),
1395
        (id2, "second", vec![h1])
1396
    );
1397
    assert_eq!(repo.bookmark_heads().unwrap(), vec![h2b]);
1398
    assert!(matches!(
1399
        repo.verify_change(&h2b).unwrap(),
1400
        SignatureStatus::Valid { .. }
1401
    ));
1402
    let s = repo.snapshot("status").unwrap();
1403
    assert!(s.statuses.is_empty(), "{:?}", s.statuses);
1404
    assert_eq!(
1405
        repo.resolve_change(&id2.short(8)).unwrap(),
1406
        h2b,
1407
        "the old object is no longer reachable from the log"
1408
    );
1409
    // Describing a non-head rewrites its dependents (h2b → h2c') and the working copy.
1410
    let h1b = repo.describe(&h1, "first, described").unwrap();
1411
    assert_ne!(h1b, h1);
1412
    let heads = repo.bookmark_heads().unwrap();
1413
    assert_eq!(heads.len(), 1);
1414
    let top = repo.store().get_change(&heads[0]).unwrap();
1415
    assert_eq!((top.change_id, top.deps.clone()), (id2, vec![h1b]));
1416
    assert!(
1417
        matches!(
1418
            repo.verify_change(&heads[0]).unwrap(),
1419
            SignatureStatus::Valid { .. }
1420
        ),
1421
        "rewritten own change is re-signed"
1422
    );
1423
    let (_, wc) = repo.working_copy().unwrap();
1424
    assert_eq!(
1425
        wc.deps,
1426
        vec![heads[0]],
1427
        "the working copy follows the rewrite"
1428
    );
1429
    assert!(!repo.snapshot("status").unwrap().changed);
1430
    let snap = repo.load_state(&heads).unwrap().materialize();
1431
    assert!(
1432
        matches!(&snap.files["a.txt"].content, FileContent::Text { bytes, .. } if bytes == b"one\ntwo\n")
1433
    );
1434
1435
    // amend: fold an edit into the head; the result is one change from h1.
1436
    write(root, "a.txt", b"one\ntwo\nthree\n");
1437
    write(root, "b.txt", b"b\n");
1438
    let h2c = repo.amend(None).unwrap();
1439
    let c = repo.store().get_change(&h2c).unwrap();
1440
    assert_eq!(c.change_id, id2);
1441
    assert_eq!(c.message, "second");
1442
    assert_eq!(repo.bookmark_heads().unwrap(), vec![h2c]);
1443
    assert_eq!(
1444
        repo.log().unwrap().len(),
1445
        3,
1446
        "working copy, amended head, first"
1447
    );
1448
    let snap = repo.load_state(&[h2c]).unwrap().materialize();
1449
    assert!(
1450
        matches!(&snap.files["a.txt"].content, FileContent::Text { bytes, .. } if bytes == b"one\ntwo\nthree\n")
1451
    );
1452
    assert!(snap.files.contains_key("b.txt"));
1453
    assert!(!repo.snapshot("status").unwrap().changed);
1454
    assert!(
1455
        repo.amend(None).is_err(),
1456
        "clean working copy and no message"
1457
    );
1458
    let h2d = repo.amend(Some("second, amended")).unwrap();
1459
    assert_eq!(
1460
        repo.store().get_change(&h2d).unwrap().message,
1461
        "second, amended"
1462
    );
1463
1464
    // abandon: the head goes, its content stays as uncommitted work.
1465
    repo.abandon(&h2d).unwrap();
1466
    assert_eq!(
1467
        repo.bookmark_heads().unwrap(),
1468
        vec![h1b],
1469
        "the described first change is the head again"
1470
    );
1471
    let s = repo.snapshot("status").unwrap();
1472
    let paths: Vec<_> = s
1473
        .statuses
1474
        .iter()
1475
        .map(|p| (p.path.as_str(), p.status))
1476
        .collect();
1477
    assert_eq!(
1478
        paths,
1479
        vec![
1480
            ("a.txt", ChangeStatus::Modified),
1481
            ("b.txt", ChangeStatus::Added)
1482
        ]
1483
    );
1484
    assert_eq!(fs::read(root.join("a.txt")).unwrap(), b"one\ntwo\nthree\n");
1485
    let h3 = repo.commit("recommitted", &[]).unwrap();
1486
    assert_eq!(repo.bookmark_heads().unwrap(), vec![h3]);
1487
    // undo brings the abandoned head back.
1488
    repo.undo().unwrap();
1489
    repo.undo().unwrap();
1490
    assert_eq!(repo.bookmark_heads().unwrap(), vec![h2d]);
1491
1492
    // Abandoning a non-head whose dependent references its atoms reifies
1493
    // the references (here: a.txt vanishes with it, so the dependent's edit
1494
    // of a.txt is dropped with a note) instead of refusing; undo restores it.
1495
    let base = repo.bookmark_heads().unwrap()[0];
1496
    let base_change = repo.store().get_change(&base).unwrap();
1497
    let h1_now = base_change.deps[0];
1498
    let notes = repo.abandon(&h1_now).unwrap();
1499
    assert!(
1500
        !notes.is_empty(),
1501
        "the dependent's edit of a.txt was reified"
1502
    );
1503
    let heads = repo.bookmark_heads().unwrap();
1504
    let after = repo.load_state(&heads).unwrap().materialize();
1505
    assert!(
1506
        !after.files.contains_key("a.txt") && after.files.contains_key("b.txt"),
1507
        "{:?}",
1508
        after.files.keys()
1509
    );
1510
    repo.undo().unwrap();
1511
    assert_eq!(repo.bookmark_heads().unwrap(), vec![base]);
1512
    write(root, "c.txt", b"c\n");
1513
    let hc = repo.commit("c", &[]).unwrap();
1514
    write(root, "d.txt", b"d\n");
1515
    let hd = repo.commit("d", &[hc]).unwrap();
1516
    assert_eq!(repo.store().get_change(&hd).unwrap().deps, vec![hc]);
1517
    repo.abandon(&hc).unwrap();
1518
    let heads: BTreeSet<_> = repo.bookmark_heads().unwrap().into_iter().collect();
1519
    assert!(!heads.contains(&hc));
1520
    let d_now = heads
1521
        .iter()
1522
        .find(|h| repo.store().get_change(h).unwrap().message == "d")
1523
        .copied()
1524
        .unwrap();
1525
    assert!(
1526
        repo.store().get_change(&d_now).unwrap().deps.is_empty(),
1527
        "d inherited c's (empty) dependencies"
1528
    );
1529
    let s = repo.snapshot("status").unwrap();
1530
    assert_eq!(
1531
        s.statuses
1532
            .iter()
1533
            .map(|p| p.path.as_str())
1534
            .collect::<Vec<_>>(),
1535
        vec!["c.txt"],
1536
        "c's content is now uncommitted work"
1537
    );
1538
}
1539
1540
#[test]
1541
fn git_export_mirrors_history() {
1542
    hermetic();
1543
    if std::process::Command::new("git")
1544
        .arg("--version")
1545
        .output()
1546
        .is_err()
1547
    {
1548
        eprintln!("git not installed; skipping");
1549
        return;
1550
    }
1551
    let dir = tempfile::tempdir().unwrap();
1552
    let root = dir.path();
1553
    let mut repo = Repo::init(&root.join("r"))
1554
        .unwrap()
1555
        .with_home(root.join("home"));
1556
    repo.create_identity("Ada Lovelace", "[email protected]", IdentityScope::User)
1557
        .unwrap();
1558
    let r = root.join("r");
1559
    write(&r, "README.md", b"hello\n");
1560
    write(&r, "src/main.rs", b"fn main() {}\n");
1561
    let h1 = repo.commit("first", &[]).unwrap();
1562
    write(&r, "src/main.rs", b"fn main() { run(); }\n");
1563
    write(&r, "logo.png", b"\x89PNG\0\0");
1564
    let h2 = repo.commit("second", &[]).unwrap();
1565
1566
    let git_dir = root.join("mirror.git");
1567
    let rep = repo.git_export(&git_dir).unwrap();
1568
    assert_eq!((rep.exported, rep.skipped, rep.heads), (2, 0, 1));
1569
    let git = |args: &[&str]| -> String {
1570
        let out = std::process::Command::new("git")
1571
            .arg("-C")
1572
            .arg(&git_dir)
1573
            .args(args)
1574
            .output()
1575
            .unwrap();
1576
        assert!(
1577
            out.status.success(),
1578
            "{}",
1579
            String::from_utf8_lossy(&out.stderr)
1580
        );
1581
        String::from_utf8_lossy(&out.stdout).trim().to_string()
1582
    };
1583
    assert_eq!(git(&["log", "--format=%s", "main"]), "second\nfirst");
1584
    assert_eq!(git(&["show", "main:src/main.rs"]), "fn main() { run(); }");
1585
    assert_eq!(git(&["show", "main:README.md"]), "hello");
1586
    let body = git(&["log", "-1", "--format=%B", "main"]);
1587
    assert!(
1588
        body.contains(&format!("Oxy-Hash: {}", h2.to_hex())),
1589
        "{body}"
1590
    );
1591
    assert!(body.contains("Change-Id: "), "{body}");
1592
    assert_eq!(
1593
        git(&["log", "-1", "--format=%an <%ae>", "main"]),
1594
        "Ada Lovelace <[email protected]>"
1595
    );
1596
    assert_eq!(
1597
        git(&["ls-tree", "--name-only", "main"]),
1598
        "README.md\nlogo.png\nsrc"
1599
    );
1600
1601
    // Re-export is incremental.
1602
    let rep = repo.git_export(&git_dir).unwrap();
1603
    assert_eq!((rep.exported, rep.skipped), (0, 2));
1604
1605
    // An independent change makes two heads; the next state is one more
1606
    // commit on the linear branch whose tree is the union.
1607
    repo.checkout(&[h1], false, "checkout").unwrap();
1608
    write(&r, "other.txt", b"o\n");
1609
    let h3 = repo.commit("third", &[]).unwrap();
1610
    let rep = repo.git_export(&git_dir).unwrap();
1611
    assert_eq!((rep.exported, rep.heads), (1, 2));
1612
    assert_eq!(git(&["log", "--format=%s", "main"]), "third\nsecond\nfirst");
1613
    let parents = git(&["rev-list", "--parents", "-1", "main"]);
1614
    assert_eq!(parents.split(' ').count(), 2, "one parent: {parents}");
1615
    assert_eq!(git(&["show", "main:other.txt"]), "o");
1616
    assert_eq!(git(&["show", "main:src/main.rs"]), "fn main() { run(); }");
1617
    assert_eq!(
1618
        git(&["ls-tree", "--name-only", "main"]),
1619
        "README.md\nlogo.png\nother.txt\nsrc"
1620
    );
1621
    let body = git(&["log", "-1", "--format=%B", "main"]);
1622
    assert!(
1623
        body.contains(&format!("Oxy-Hash: {}", h3.to_hex())) && body.contains("Oxy-State: "),
1624
        "{body}"
1625
    );
1626
    // A rewrite is a new state whose one new change is the rewritten one.
1627
    repo.describe(&h3, "third, described").unwrap();
1628
    let rep = repo.git_export(&git_dir).unwrap();
1629
    assert_eq!(rep.exported, 1);
1630
    assert_eq!(
1631
        git(&["log", "-1", "--format=%s", "main"]),
1632
        "third, described"
1633
    );
1634
    assert_eq!(git(&["log", "--format=%s", "main"]).lines().count(), 4);
1635
    let _ = h2;
1636
}
1637
1638
#[test]
1639
fn git_import_reproduces_trees() {
1640
    git_import_reproduces_trees_with(None);
1641
}
1642
1643
/// The same import with every merge rendered in batches of one file
1644
/// (oxygen#25): what a merge onto a base of thousands of files takes.
1645
#[test]
1646
fn git_import_reproduces_trees_in_batches() {
1647
    git_import_reproduces_trees_with(Some(1));
1648
}
1649
1650
fn git_import_reproduces_trees_with(batch: Option<usize>) {
1651
    crate::repo::git::set_merge_batch_for_tests(batch);
1652
    hermetic();
1653
    if std::process::Command::new("git")
1654
        .arg("--version")
1655
        .output()
1656
        .is_err()
1657
    {
1658
        eprintln!("git not installed; skipping");
1659
        return;
1660
    }
1661
    let dir = tempfile::tempdir().unwrap();
1662
    let root = dir.path();
1663
    let g = root.join("src.git");
1664
    fs::create_dir_all(&g).unwrap();
1665
    let git = |args: &[&str]| -> String {
1666
        let out = std::process::Command::new("git")
1667
            .arg("-C")
1668
            .arg(&g)
1669
            .args([
1670
                "-c",
1671
                "user.name=Grace",
1672
                "-c",
1673
                "[email protected]",
1674
                "-c",
1675
                "commit.gpgsign=false",
1676
            ])
1677
            .args(args)
1678
            .output()
1679
            .unwrap();
1680
        assert!(
1681
            out.status.success(),
1682
            "git {args:?}: {}",
1683
            String::from_utf8_lossy(&out.stderr)
1684
        );
1685
        String::from_utf8_lossy(&out.stdout).trim().to_string()
1686
    };
1687
    git(&["init", "-q", "-b", "main"]);
1688
    write(&g, "README.md", b"# Hi\n");
1689
    write(&g, "src/lib.rs", b"pub fn a() {}\n");
1690
    git(&["add", "."]);
1691
    git(&["commit", "-q", "-m", "initial"]);
1692
    write(&g, "src/lib.rs", b"pub fn a() {}\npub fn b() {}\n");
1693
    write(&g, "run.sh", b"#!/bin/sh\n");
1694
    #[cfg(unix)]
1695
    {
1696
        use std::os::unix::fs::PermissionsExt;
1697
        fs::set_permissions(g.join("run.sh"), fs::Permissions::from_mode(0o755)).unwrap();
1698
    }
1699
    write(&g, "logo.png", b"\x89PNG\0\0\x01");
1700
    git(&["add", "."]);
1701
    git(&[
1702
        "commit",
1703
        "-q",
1704
        "-m",
1705
        "second\n\nChange-Id: 0123456789abcdef0123456789abcdef",
1706
    ]);
1707
    // A branch that edits README, merged back with a conflict-free merge.
1708
    git(&["checkout", "-q", "-b", "topic", "HEAD~1"]);
1709
    write(&g, "README.md", b"# Hi\n\nMore.\n");
1710
    git(&["commit", "-q", "-am", "readme"]);
1711
    git(&["checkout", "-q", "main"]);
1712
    git(&["merge", "-q", "--no-ff", "-m", "merge topic", "topic"]);
1713
    // A branch from the initial commit inserting at the same place as
1714
    // "second": concurrent in Oxygen too, so the merge commit is a resolution.
1715
    let initial = git(&["rev-list", "--max-parents=0", "HEAD"]);
1716
    git(&["checkout", "-q", "-b", "clash", &initial]);
1717
    write(&g, "src/lib.rs", b"pub fn a() {}\npub fn c() {}\n");
1718
    git(&["commit", "-q", "-am", "clash"]);
1719
    git(&["checkout", "-q", "main"]);
1720
    let _ = std::process::Command::new("git")
1721
        .arg("-C")
1722
        .arg(&g)
1723
        .args(["merge", "-q", "clash"])
1724
        .output();
1725
    write(
1726
        &g,
1727
        "src/lib.rs",
1728
        b"pub fn a() {}\npub fn b() {}\npub fn c() {}\n",
1729
    );
1730
    git(&["add", "."]);
1731
    git(&["commit", "-q", "-m", "resolve clash"]);
1732
    git(&["rm", "-q", "logo.png"]);
1733
    git(&["commit", "-q", "-m", "drop logo"]);
1734
    // A rename with a small edit is imported as a move of the same node.
1735
    git(&["mv", "src/lib.rs", "src/lib2.rs"]);
1736
    write(
1737
        &g,
1738
        "src/lib2.rs",
1739
        b"pub fn a() {}\npub fn b() {}\npub fn c() {}\npub fn d() {}\n",
1740
    );
1741
    git(&["add", "."]);
1742
    git(&["commit", "-q", "-m", "rename lib"]);
1743
    // A branch that edits run.sh, merged keeping main's tree (`-s ours`):
1744
    // run.sh is the same as in the first parent's tree, but the merged
1745
    // change touched it, so the importer must compare it, not skip it.
1746
    git(&["checkout", "-q", "-b", "discarded"]);
1747
    write(&g, "run.sh", b"#!/bin/sh\necho discarded\n");
1748
    git(&["commit", "-q", "-am", "discarded edit"]);
1749
    git(&["checkout", "-q", "main"]);
1750
    git(&[
1751
        "merge",
1752
        "-q",
1753
        "-s",
1754
        "ours",
1755
        "-m",
1756
        "merge discarded, keeping ours",
1757
        "discarded",
1758
    ]);
1759
    let expected_count: usize = git(&["rev-list", "--count", "main"]).parse().unwrap();
1760
1761
    let dest = root.join("oxy");
1762
    let repo = Repo::init(&dest).unwrap().with_home(root.join("home"));
1763
    let rep = repo.import_git(&g, "main").unwrap();
1764
    assert_eq!(rep.commits, expected_count);
1765
    assert_eq!(rep.merges, 3);
1766
    assert_eq!(
1767
        fs::read(dest.join("run.sh")).unwrap(),
1768
        b"#!/bin/sh\n",
1769
        "the ours merge kept main's run.sh"
1770
    );
1771
    let v = repo.verify_git_import(&g, "main").unwrap();
1772
    assert_eq!(v.commits, expected_count, "every commit's tree reproduced");
1773
    assert!(v.mismatches.is_empty(), "{:?}", v.mismatches);
1774
    // The working copy equals the Git tree at main.
1775
    assert_eq!(
1776
        fs::read(dest.join("src/lib2.rs")).unwrap(),
1777
        b"pub fn a() {}\npub fn b() {}\npub fn c() {}\npub fn d() {}\n"
1778
    );
1779
    assert!(!dest.join("src/lib.rs").exists());
1780
    assert_eq!(
1781
        fs::read(dest.join("README.md")).unwrap(),
1782
        b"# Hi\n\nMore.\n"
1783
    );
1784
    assert!(!dest.join("logo.png").exists());
1785
    #[cfg(unix)]
1786
    {
1787
        use std::os::unix::fs::PermissionsExt;
1788
        assert!(
1789
            fs::metadata(dest.join("run.sh"))
1790
                .unwrap()
1791
                .permissions()
1792
                .mode()
1793
                & 0o111
1794
                != 0
1795
        );
1796
    }
1797
    assert!(
1798
        !repo.snapshot("status").unwrap().changed,
1799
        "clean after import"
1800
    );
1801
    let heads = repo.bookmark_heads().unwrap();
1802
    let st = repo.load_state(&heads).unwrap();
1803
    assert!(!st.materialize().is_conflicted());
1804
    assert_eq!(st.len(), expected_count);
1805
    let tip = repo
1806
        .log()
1807
        .unwrap()
1808
        .into_iter()
1809
        .find(|e| e.change.message.starts_with("rename lib"))
1810
        .unwrap();
1811
    let c = repo.store().get_change(&tip.hash).unwrap();
1812
    assert!(
1813
        c.tree_ops
1814
            .iter()
1815
            .any(|op| matches!(op, TreeOp::Move { name, .. } if name == "lib2.rs")),
1816
        "{:?}",
1817
        c.tree_ops
1818
    );
1819
    assert!(!c
1820
        .tree_ops
1821
        .iter()
1822
        .any(|op| matches!(op, TreeOp::AddNode { .. })));
1823
    // Messages carry Git trailers; the Change-Id trailer was honoured.
1824
    let log = repo.log().unwrap();
1825
    let second = log
1826
        .iter()
1827
        .find(|e| e.change.message.starts_with("second"))
1828
        .unwrap();
1829
    assert_eq!(
1830
        second.change.change_id,
1831
        ChangeId::from_hex("0123456789abcdef0123456789abcdef").unwrap()
1832
    );
1833
    assert!(second
1834
        .change
1835
        .message
1836
        .contains("Git-Author: Grace <[email protected]>"));
1837
    let resolve = log
1838
        .iter()
1839
        .find(|e| e.change.message.starts_with("resolve clash"))
1840
        .unwrap();
1841
    assert_eq!(
1842
        resolve.change.kind,
1843
        ChangeKind::Resolution,
1844
        "a conflicting Git merge becomes a resolution"
1845
    );
1846
    // Re-importing into another fresh repository gives the same ChangeIds.
1847
    let repo2 = Repo::init(&root.join("oxy2"))
1848
        .unwrap()
1849
        .with_home(root.join("home"));
1850
    repo2.import_git(&g, "main").unwrap();
1851
    // New nodes' identifiers derive from the commit (spec §23), so the
1852
    // re-import is not just the same ChangeIds but the same changes.
1853
    assert_eq!(
1854
        repo2.bookmark_heads().unwrap(),
1855
        repo.bookmark_heads().unwrap()
1856
    );
1857
    let ids: BTreeSet<ChangeId> = repo
1858
        .log()
1859
        .unwrap()
1860
        .iter()
1861
        .filter(|e| !e.is_working_copy)
1862
        .map(|e| e.change.change_id)
1863
        .collect();
1864
    let ids2: BTreeSet<ChangeId> = repo2
1865
        .log()
1866
        .unwrap()
1867
        .iter()
1868
        .filter(|e| !e.is_working_copy)
1869
        .map(|e| e.change.change_id)
1870
        .collect();
1871
    assert_eq!(ids, ids2);
1872
    // Round trip back out to Git reproduces the tip tree.
1873
    let mirror = root.join("mirror.git");
1874
    repo.git_export(&mirror).unwrap();
1875
    let out = std::process::Command::new("git")
1876
        .arg("-C")
1877
        .arg(&mirror)
1878
        .args(["show", "main:src/lib2.rs"])
1879
        .output()
1880
        .unwrap();
1881
    assert_eq!(
1882
        String::from_utf8_lossy(&out.stdout),
1883
        "pub fn a() {}\npub fn b() {}\npub fn c() {}\npub fn d() {}\n"
1884
    );
1885
    let out = std::process::Command::new("git")
1886
        .arg("-C")
1887
        .arg(&mirror)
1888
        .args(["show", "main:src/lib.rs"])
1889
        .output()
1890
        .unwrap();
1891
    assert!(
1892
        !out.status.success(),
1893
        "the old path is gone from the export"
1894
    );
1895
}
1896
1897
#[test]
1898
fn checkpoints_accelerate_loading_and_stay_correct() {
1899
    hermetic();
1900
    let dir = tempfile::tempdir().unwrap();
1901
    let root = dir.path();
1902
    let mut repo = Repo::init(root).unwrap().with_home(root.join("home"));
1903
    repo.config.set("core.checkpoint-interval", "5").unwrap();
1904
    repo.save_config().unwrap();
1905
    let repo = Repo::open(root).unwrap().with_home(root.join("home"));
1906
    let mut hashes = Vec::new();
1907
    for i in 0..12 {
1908
        write(
1909
            root,
1910
            "a.txt",
1911
            format!(
1912
                "{}\n",
1913
                (0..=i)
1914
                    .map(|k| k.to_string())
1915
                    .collect::<Vec<_>>()
1916
                    .join("\n")
1917
            )
1918
            .as_bytes(),
1919
        );
1920
        write(root, &format!("f{i}.txt"), b"x\n");
1921
        hashes.push(repo.commit(&format!("c{i}"), &[]).unwrap());
1922
    }
1923
    let (_, cp) = repo
1924
        .latest_checkpoint("main")
1925
        .unwrap()
1926
        .expect("automatic checkpoint");
1927
    assert!(cp.count >= 5 && cp.count <= 12, "{}", cp.count);
1928
    // Loading through the checkpoint equals loading everything.
1929
    let heads = repo.bookmark_heads().unwrap();
1930
    let fast = repo.load_state(&heads).unwrap();
1931
    let full = repo.load_state_full(&heads).unwrap();
1932
    assert_eq!(fast.len(), full.len());
1933
    assert_eq!(fast.heads(), full.heads());
1934
    let (a, b) = (fast.materialize(), full.materialize());
1935
    assert_eq!(
1936
        a.files.keys().collect::<Vec<_>>(),
1937
        b.files.keys().collect::<Vec<_>>()
1938
    );
1939
    for (p, f) in &a.files {
1940
        assert_eq!(f.content, b.files[p].content, "{p}");
1941
    }
1942
    assert!(repo.load_state_checkpointed(&heads).unwrap().is_some());
1943
    // A head set that does not contain the checkpoint's heads falls back.
1944
    assert!(repo
1945
        .load_state_checkpointed(&[hashes[0]])
1946
        .unwrap()
1947
        .is_none());
1948
    assert_eq!(repo.load_state(&[hashes[0]]).unwrap().len(), 1);
1949
    // Everything else keeps working on top of the checkpoint.
1950
    assert!(!repo.snapshot("status").unwrap().changed);
1951
    let h = repo.describe(&hashes[3], "c3 described").unwrap();
1952
    assert_eq!(repo.store().get_change(&h).unwrap().message, "c3 described");
1953
    let (r, n, bytes) = repo.checkpoint().unwrap();
1954
    assert!(n >= 12 && bytes > 0);
1955
    assert_eq!(repo.latest_checkpoint("main").unwrap().unwrap().0, r);
1956
    write(root, "a.txt", b"after\n");
1957
    let h_after = repo.commit("after", &[]).unwrap();
1958
    let st = repo.load_state(&repo.bookmark_heads().unwrap()).unwrap();
1959
    assert!(st.contains(&h_after));
1960
    assert!(
1961
        matches!(&st.materialize().files["a.txt"].content, FileContent::Text { bytes, .. } if bytes == b"after\n")
1962
    );
1963
    assert_eq!(repo.log().unwrap().len(), 14);
1964
    // Checkpoints survive gc.
1965
    repo.gc(true).unwrap();
1966
    assert!(repo.latest_checkpoint("main").unwrap().is_some());
1967
    assert!(repo
1968
        .load_state_checkpointed(&repo.bookmark_heads().unwrap())
1969
        .unwrap()
1970
        .is_some());
1971
}
1972
1973
#[test]
1974
fn quick_status_for_prompts() {
1975
    hermetic();
1976
    let dir = tempfile::tempdir().unwrap();
1977
    let root = dir.path();
1978
    let origin = Repo::init(&root.join("origin")).unwrap();
1979
    let url = root.join("origin").to_string_lossy().to_string();
1980
    let a = Repo::clone(&url, &root.join("a"))
1981
        .unwrap()
1982
        .with_home(root.join("home"));
1983
    let ops_before = a.op_log().unwrap().len();
1984
    let info = a.quick_status().unwrap();
1985
    assert_eq!(
1986
        (
1987
            info.bookmark.as_str(),
1988
            info.heads,
1989
            info.dirty,
1990
            info.conflicted,
1991
            info.ahead,
1992
            info.behind
1993
        ),
1994
        ("main", 0, false, false, Some(0), Some(0))
1995
    );
1996
    write(&root.join("a"), "f.txt", b"f\n");
1997
    assert!(a.quick_status().unwrap().dirty, "a new file is dirty");
1998
    assert_eq!(
1999
        a.op_log().unwrap().len(),
2000
        ops_before,
2001
        "quick_status records nothing"
2002
    );
2003
    // A snapshotted but uncommitted change is still dirty.
2004
    a.snapshot("status").unwrap();
2005
    assert!(a.quick_status().unwrap().dirty);
2006
    a.commit("f", &[]).unwrap();
2007
    let info = a.quick_status().unwrap();
2008
    assert!(!info.dirty, "clean right after a commit");
2009
    assert_eq!((info.ahead, info.behind), (Some(1), Some(0)));
2010
    assert_eq!(
2011
        info.format("%b %c%d%x%A%D"),
2012
        format!("main {}+1", info.change_id)
2013
    );
2014
    assert_eq!(info.format("[%h heads] %a/%B %%"), "[1 heads] 1/0 %");
2015
    // Touching a file without changing it is not dirty; changing content of
2016
    // the same size is.
2017
    let p = root.join("a/f.txt");
2018
    let content = fs::read(&p).unwrap();
2019
    fs::write(&p, &content).unwrap();
2020
    assert!(!a.quick_status().unwrap().dirty);
2021
    fs::write(&p, b"g\n").unwrap();
2022
    assert!(a.quick_status().unwrap().dirty);
2023
    fs::write(&p, b"f\n").unwrap();
2024
    // Push, then a second clone commits and pushes: we are behind.
2025
    assert!(a.push("origin", false).unwrap()[0].ok);
2026
    assert_eq!(a.quick_status().unwrap().ahead, Some(0));
2027
    let b = Repo::clone(&url, &root.join("b"))
2028
        .unwrap()
2029
        .with_home(root.join("home-b"));
2030
    write(&root.join("b"), "g.txt", b"g\n");
2031
    b.commit("g", &[]).unwrap();
2032
    b.push("origin", false).unwrap();
2033
    a.fetch("origin").unwrap();
2034
    let info = a.quick_status().unwrap();
2035
    assert_eq!((info.ahead, info.behind), (Some(0), Some(1)));
2036
    assert_eq!(info.format("%A%D"), "-1");
2037
    let _ = origin;
2038
}
2039
2040
#[test]
2041
fn lazy_blobs_are_fetched_on_first_read() {
2042
    hermetic();
2043
    let dir = tempfile::tempdir().unwrap();
2044
    let root = dir.path();
2045
    let origin_dir = root.join("origin");
2046
    let origin = Repo::init(&origin_dir)
2047
        .unwrap()
2048
        .with_home(root.join("home"));
2049
    let url = origin_dir.to_string_lossy().to_string();
2050
    let big: Vec<u8> = (0..200_000u32).map(|i| (i % 251) as u8).collect(); // has NUL bytes: opaque
2051
    write(&origin_dir, "big.bin", &big);
2052
    write(&origin_dir, "small.bin", &[0u8, 1, 2]);
2053
    write(&origin_dir, "t.txt", b"t\n");
2054
    let h = origin.commit("blobs", &[]).unwrap();
2055
    let big_ref = Repo::blob_ref(&big);
2056
2057
    // Fetch only (no checkout) with a filter: the big blob stays absent.
2058
    let a = Repo::init_with_id(&root.join("a"), origin.id().unwrap())
2059
        .unwrap()
2060
        .with_home(root.join("home"));
2061
    let a = {
2062
        let mut a = a;
2063
        a.config.set("remote.origin.url", &url).unwrap();
2064
        a.config.set("filter.max-blob", "100K").unwrap();
2065
        a.save_config().unwrap();
2066
        a
2067
    };
2068
    assert_eq!(a.config.max_blob, Some(100 * 1024));
2069
    a.fetch("origin").unwrap();
2070
    assert!(a.store().has(&h));
2071
    assert!(!a.store().has(&big_ref), "withheld");
2072
    assert!(
2073
        a.store().has(&Repo::blob_ref(&[0u8, 1, 2])),
2074
        "small blob came along"
2075
    );
2076
    assert_eq!(a.lazy_remote(&big_ref).as_deref(), Some("origin"));
2077
2078
    // status and commit do not need it: adopt the state, edit a text file, commit.
2079
    let (op_ref, op) = a.head_op().unwrap();
2080
    let mut view = op.view.clone();
2081
    view.bookmarks.insert(
2082
        "main".into(),
2083
        a.store().put_state(&StateObject::new(vec![h])).unwrap(),
2084
    );
2085
    a.record_op(&[op_ref], "adopt", view).unwrap();
2086
    // Checkout reads the blob lazily, which fetches it.
2087
    a.checkout(&[h], true, "checkout").unwrap();
2088
    assert!(a.store().has(&big_ref), "fetched on first read");
2089
    assert_eq!(fs::read(root.join("a/big.bin")).unwrap(), big);
2090
    assert!(a.lazy_remote(&big_ref).is_none(), "no longer registered");
2091
    write(&root.join("a"), "t.txt", b"t2\n");
2092
    a.commit("text edit", &[]).unwrap();
2093
2094
    // clone --max-blob records the filter; the checkout fetches lazily.
2095
    let b = Repo::clone_with(&url, &root.join("b"), Some(1024), &[]).unwrap();
2096
    assert_eq!(b.config.max_blob, Some(1024));
2097
    assert_eq!(fs::read(root.join("b/big.bin")).unwrap(), big);
2098
    assert_eq!(parse_size("2M").unwrap(), 2 << 20);
2099
    assert!(parse_size("lots").is_err());
2100
}
2101
2102
#[test]
2103
fn sparse_checkout_materializes_only_chosen_paths() {
2104
    hermetic();
2105
    let dir = tempfile::tempdir().unwrap();
2106
    let root = dir.path();
2107
    let origin_dir = root.join("origin");
2108
    let origin = Repo::init(&origin_dir)
2109
        .unwrap()
2110
        .with_home(root.join("home"));
2111
    write(&origin_dir, "src/main.rs", b"fn main() {}\n");
2112
    write(&origin_dir, "src/lib.rs", b"pub fn a() {}\n");
2113
    write(&origin_dir, "docs/guide.md", b"# guide\n");
2114
    let logo: Vec<u8> = (0..50_000u32).map(|i| (i % 7) as u8).collect();
2115
    write(&origin_dir, "docs/logo.png", &logo);
2116
    write(&origin_dir, "README.md", b"# top\n");
2117
    let h1 = origin.commit("tree", &[]).unwrap();
2118
    let url = origin_dir.to_string_lossy().to_string();
2119
2120
    let a = Repo::clone_with(&url, &root.join("a"), None, &["src".into()])
2121
        .unwrap()
2122
        .with_home(root.join("home"));
2123
    assert_eq!(a.config.sparse_paths, vec!["src"]);
2124
    assert_eq!(a.config.max_blob, Some(0), "sparse implies lazy blobs");
2125
    assert!(root.join("a/src/main.rs").exists());
2126
    assert!(!root.join("a/docs").exists() && !root.join("a/README.md").exists());
2127
    assert!(
2128
        !a.store().has(&Repo::blob_ref(&logo)),
2129
        "out-of-scope blob never fetched"
2130
    );
2131
    assert!(
2132
        !a.snapshot("status").unwrap().changed,
2133
        "out-of-scope files are not removals"
2134
    );
2135
    assert!(!a.quick_status().unwrap().dirty);
2136
2137
    // Edits in scope commit normally and keep the rest of the tree intact.
2138
    write(
2139
        &root.join("a"),
2140
        "src/lib.rs",
2141
        b"pub fn a() {}\npub fn b() {}\n",
2142
    );
2143
    let h2 = a.commit("edit lib", &[]).unwrap();
2144
    let st = a.load_state(&[h2]).unwrap().materialize();
2145
    assert!(
2146
        st.files.contains_key("docs/guide.md"),
2147
        "the state still has everything"
2148
    );
2149
    assert!(a.push("origin", false).unwrap()[0].ok);
2150
    // Files created outside the scope are ignored by status.
2151
    write(&root.join("a"), "docs/new.md", b"ignored\n");
2152
    assert!(a.snapshot("status").unwrap().statuses.is_empty());
2153
2154
    // Widening the filter checks out the rest; narrowing leaves stray files alone.
2155
    let mut a = a;
2156
    a.config.set("filter.paths", "src,docs").unwrap();
2157
    a.save_config().unwrap();
2158
    let r = a
2159
        .checkout(&a.bookmark_heads().unwrap(), true, "widen")
2160
        .unwrap();
2161
    assert!(r.written >= 2);
2162
    assert_eq!(
2163
        fs::read(root.join("a/docs/logo.png")).unwrap(),
2164
        logo,
2165
        "now fetched lazily"
2166
    );
2167
    assert!(!root.join("a/README.md").exists());
2168
    // Origin sees the change made under a sparse checkout with the full tree intact.
2169
    origin.pull("origin").err();
2170
    let full = origin
2171
        .load_state(&origin.bookmark_heads().unwrap())
2172
        .unwrap()
2173
        .materialize();
2174
    assert!(
2175
        matches!(&full.files["src/lib.rs"].content, FileContent::Text { bytes, .. } if bytes == b"pub fn a() {}\npub fn b() {}\n")
2176
    );
2177
    assert!(full.files.contains_key("README.md"));
2178
    let _ = h1;
2179
}
2180
2181
#[test]
2182
fn shallow_clone_and_deepen() {
2183
    hermetic();
2184
    let dir = tempfile::tempdir().unwrap();
2185
    let root = dir.path();
2186
    let origin_dir = root.join("origin");
2187
    let origin = Repo::init(&origin_dir)
2188
        .unwrap()
2189
        .with_home(root.join("home"));
2190
    let mut hashes = Vec::new();
2191
    for i in 0..8 {
2192
        write(
2193
            &origin_dir,
2194
            "a.txt",
2195
            format!(
2196
                "{}\n",
2197
                (0..=i)
2198
                    .map(|k| k.to_string())
2199
                    .collect::<Vec<_>>()
2200
                    .join("\n")
2201
            )
2202
            .as_bytes(),
2203
        );
2204
        hashes.push(origin.commit(&format!("c{i}"), &[]).unwrap());
2205
    }
2206
    let url = origin_dir.to_string_lossy().to_string();
2207
    let a = Repo::clone_shallow(&url, &root.join("a"), 3, None, &[])
2208
        .unwrap()
2209
        .with_home(root.join("home"));
2210
    assert!(a.is_shallow());
2211
    assert_eq!(
2212
        fs::read_to_string(root.join("a/a.txt")).unwrap(),
2213
        "0\n1\n2\n3\n4\n5\n6\n7\n"
2214
    );
2215
    assert!(
2216
        a.store().has(&hashes[7]) && a.store().has(&hashes[5]),
2217
        "three levels present"
2218
    );
2219
    assert!(!a.store().has(&hashes[4]), "beyond the depth is absent");
2220
    assert_eq!(a.boundary(), [hashes[4]].into_iter().collect());
2221
    assert_eq!(
2222
        a.log().unwrap().len(),
2223
        9,
2224
        "the log shows every change from the checkpoint's metadata"
2225
    );
2226
    assert!(!a.snapshot("status").unwrap().changed);
2227
    assert_eq!(a.quick_status().unwrap().heads, 1);
2228
2229
    // Work continues on top of the shallow history and pushes back.
2230
    write(&root.join("a"), "a.txt", b"0\n1\n2\n3\n4\n5\n6\n7\n8\n");
2231
    let h_new = a.commit("c8", &[]).unwrap();
2232
    assert!(a.push("origin", false).unwrap()[0].ok);
2233
    assert_eq!(origin.bookmark_heads().unwrap(), vec![h_new]);
2234
    // Fetching new work from origin into the shallow clone works too.
2235
    write(&origin_dir, "b.txt", b"b\n");
2236
    origin.pull("origin").err();
2237
    let (_, wc) = origin.working_copy().unwrap();
2238
    let _ = wc;
2239
    origin
2240
        .checkout(&origin.bookmark_heads().unwrap(), true, "co")
2241
        .unwrap();
2242
    write(&origin_dir, "b.txt", b"b\n");
2243
    let h_b = origin.commit("b", &[]).unwrap();
2244
    let pr = a.pull("origin").unwrap();
2245
    assert!(pr.changed);
2246
    assert!(a.store().has(&h_b));
2247
    assert!(root.join("a/b.txt").exists());
2248
2249
    // Deepening fetches older history until the boundary is gone.
2250
    // Every commit also depends on the change that created the file, so two
2251
    // levels below the boundary hold h4, h3, and the root.
2252
    assert!(a.deepen("origin", 2).unwrap() >= 2);
2253
    assert!(a.store().has(&hashes[3]));
2254
    assert!(a.is_shallow());
2255
    a.deepen("origin", 100).unwrap();
2256
    assert!(!a.is_shallow(), "boundary reached the root");
2257
    assert!(a.store().has(&hashes[0]));
2258
    assert_eq!(
2259
        a.load_state_full(&a.bookmark_heads().unwrap())
2260
            .unwrap()
2261
            .len(),
2262
        10
2263
    );
2264
}
2265
2266
#[test]
2267
fn tags_are_immutable_named_states_and_travel() {
2268
    hermetic();
2269
    let dir = tempfile::tempdir().unwrap();
2270
    let root = dir.path();
2271
    let origin = Repo::init(&root.join("origin")).unwrap();
2272
    let url = root.join("origin").to_string_lossy().to_string();
2273
    let mut a = Repo::clone(&url, &root.join("a"))
2274
        .unwrap()
2275
        .with_home(root.join("home-a"));
2276
    let (key_a, _) = a
2277
        .create_identity("Ada", "[email protected]", IdentityScope::User)
2278
        .unwrap();
2279
    write(&root.join("a"), "f.txt", b"1\n");
2280
    let h1 = a.commit("one", &[]).unwrap();
2281
    write(&root.join("a"), "f.txt", b"1\n2\n");
2282
    let h2 = a.commit("two", &[]).unwrap();
2283
2284
    let t = a.tag_create("v1", &[h1], "first release").unwrap();
2285
    assert_eq!(
2286
        (t.heads.clone(), t.signer.as_deref()),
2287
        (vec![h1], Some("Ada"))
2288
    );
2289
    assert!(a.tag_create("v1", &[h2], "").is_err(), "immutable");
2290
    assert!(a.tag_create("bad/name", &[h2], "").is_err());
2291
    assert_eq!(a.tag_heads("v1").unwrap(), Some(vec![h1]));
2292
    assert_eq!(a.resolve_heads("v1").unwrap(), vec![h1]);
2293
    assert_eq!(a.resolve_heads("main").unwrap(), vec![h2]);
2294
    let (_, sa) = a.tag_attest("v1").unwrap().unwrap();
2295
    assert_eq!(sa.sigs[0].key, key_a);
2296
    // Checkout by tag.
2297
    a.checkout(&a.resolve_heads("v1").unwrap(), false, "co")
2298
        .unwrap();
2299
    assert_eq!(fs::read(root.join("a/f.txt")).unwrap(), b"1\n");
2300
    a.checkout(&a.bookmark_heads().unwrap(), false, "co")
2301
        .unwrap();
2302
2303
    // Push carries the tag; a second attestation for the name is refused.
2304
    let r = a.push("origin", false).unwrap();
2305
    assert!(r.iter().any(|x| x.name == "tags/v1" && x.ok), "{r:?}");
2306
    assert_eq!(origin.tag_heads("v1").unwrap(), Some(vec![h1]));
2307
    let mut forged = a
2308
        .tag_refs()
2309
        .unwrap()
2310
        .into_iter()
2311
        .find(|t| t.name == "v1")
2312
        .unwrap();
2313
    forged.state = origin
2314
        .store()
2315
        .put_state(&StateObject::new(vec![h2]))
2316
        .unwrap();
2317
    forged.heads = vec![h2];
2318
    forged.attestation = None;
2319
    let r = origin
2320
        .receive_push(Bundle::default(), vec![], None, vec![forged])
2321
        .unwrap();
2322
    assert!(!r[0].ok && r[0].reason.contains("immutable"), "{r:?}");
2323
2324
    // A clone gets the tag; a later tag arrives on fetch.
2325
    let b = Repo::clone(&url, &root.join("b"))
2326
        .unwrap()
2327
        .with_home(root.join("home-b"));
2328
    assert_eq!(b.tag_heads("v1").unwrap(), Some(vec![h1]));
2329
    assert!(b.tags().unwrap()[0].signer.as_deref() == Some("Ada"));
2330
    a.tag_create("v2", &[h2], "second").unwrap();
2331
    a.push("origin", false).unwrap();
2332
    let rep = b.fetch("origin").unwrap();
2333
    assert_eq!(rep.new_tags, 1);
2334
    assert_eq!(b.tag_heads("v2").unwrap(), Some(vec![h2]));
2335
2336
    // Under a policy, an unattested tag is refused and an attested one by the root passes.
2337
    a.policy_init().unwrap();
2338
    a.push("origin", false).unwrap();
2339
    let unattested = crate::protocol::TagRef {
2340
        name: "v3".into(),
2341
        state: origin
2342
            .store()
2343
            .put_state(&StateObject::new(vec![h2]))
2344
            .unwrap(),
2345
        heads: vec![h2],
2346
        attestation: None,
2347
    };
2348
    let r = origin
2349
        .receive_push(Bundle::default(), vec![], None, vec![unattested])
2350
        .unwrap();
2351
    assert!(!r[0].ok && r[0].reason.contains("attestation"), "{r:?}");
2352
    a.tag_create("v3", &[h2], "").unwrap();
2353
    let r = a.push("origin", false).unwrap();
2354
    assert!(r.iter().any(|x| x.name == "tags/v3" && x.ok), "{r:?}");
2355
    assert!(a.gc(true).is_ok());
2356
    assert_eq!(a.tags().unwrap().len(), 3, "tags survive gc");
2357
}
2358
2359
#[test]
2360
fn multiple_workspaces_share_a_repository() {
2361
    hermetic();
2362
    let dir = tempfile::tempdir().unwrap();
2363
    let root = dir.path();
2364
    let main_dir = root.join("main");
2365
    let repo = Repo::init(&main_dir).unwrap().with_home(root.join("home"));
2366
    write(&main_dir, "a.txt", b"a\n");
2367
    let h1 = repo.commit("a", &[]).unwrap();
2368
    assert_eq!(repo.workspaces().unwrap().len(), 1);
2369
2370
    // A second workspace elsewhere, checked out on the bookmark.
2371
    let ws_dir = root.join("ws2");
2372
    let ws = repo.workspace_add(&ws_dir, None).unwrap();
2373
    assert!(ws_dir.join(".oxy").is_file());
2374
    assert_eq!(fs::read(ws_dir.join("a.txt")).unwrap(), b"a\n");
2375
    assert_ne!(ws.workspace(), repo.workspace());
2376
    let list = repo.workspaces().unwrap();
2377
    assert_eq!(list.len(), 2);
2378
    assert!(list
2379
        .iter()
2380
        .any(|w| w.id == ws.workspace() && w.path == ws_dir.canonicalize().unwrap() && !w.current));
2381
    assert!(!ws.snapshot("status").unwrap().changed);
2382
2383
    // Work in the second workspace: its own working copy, shared bookmark.
2384
    write(&ws_dir, "b.txt", b"b\n");
2385
    let s = ws.snapshot("status").unwrap();
2386
    assert_eq!(s.statuses.len(), 1);
2387
    assert!(
2388
        !repo.snapshot("status").unwrap().changed,
2389
        "the first workspace is untouched"
2390
    );
2391
    let h2 = ws.commit("b from ws2", &[]).unwrap();
2392
    let mut heads = repo.bookmark_heads().unwrap();
2393
    heads.sort();
2394
    let mut want = vec![h1, h2];
2395
    want.sort();
2396
    assert_eq!(heads, want, "both workspaces see the bookmark move");
2397
    assert!(!main_dir.join("b.txt").exists());
2398
    repo.checkout(&repo.bookmark_heads().unwrap(), false, "co")
2399
        .unwrap();
2400
    assert!(main_dir.join("b.txt").exists());
2401
2402
    // Reopening from inside the second workspace finds the shared repository.
2403
    let reopened = Repo::open(&ws_dir).unwrap();
2404
    assert_eq!(reopened.workspace(), ws.workspace());
2405
    assert_eq!(reopened.id().unwrap(), repo.id().unwrap());
2406
    assert_eq!(reopened.quick_status().unwrap().heads, 2);
2407
2408
    // Workspaces cannot nest; forget drops one from the view but keeps files.
2409
    assert!(repo.workspace_add(&main_dir.join("inner"), None).is_err());
2410
    assert!(repo.workspace_forget(&repo.workspace()).is_err());
2411
    repo.workspace_forget(&ws.workspace()).unwrap();
2412
    assert_eq!(repo.workspaces().unwrap().len(), 1);
2413
    assert!(ws_dir.join("b.txt").exists());
2414
    assert!(
2415
        ws.snapshot("status").is_err(),
2416
        "a forgotten workspace is no longer in the view"
2417
    );
2418
2419
    // The working-copy lock: re-entrant in a thread; a lock whose process
2420
    // is gone is taken over, and a live process's is not, however old.
2421
    let lock = repo.lock_snapshot().unwrap();
2422
    let again = repo.lock_working_copy().unwrap();
2423
    drop(again);
2424
    drop(lock);
2425
    let lock_path = main_dir
2426
        .join(".oxy/workspaces")
2427
        .join(repo.workspace().to_hex())
2428
        .join("lock");
2429
    let old = std::time::SystemTime::now() - std::time::Duration::from_secs(120);
2430
    let age = |p: &Path| fs::File::open(p).unwrap().set_modified(old).unwrap();
2431
    fs::write(&lock_path, std::process::id().to_string()).unwrap();
2432
    age(&lock_path);
2433
    assert!(
2434
        !super::workspace::lock_is_stale(&lock_path),
2435
        "a live process keeps its lock"
2436
    );
2437
    fs::write(&lock_path, "4294967295").unwrap();
2438
    age(&lock_path);
2439
    assert!(repo.lock_snapshot().is_ok(), "stale lock taken over");
2440
}
2441
2442
#[test]
2443
fn attributes_binary_eol_nocompress_lockable() {
2444
    hermetic();
2445
    let dir = tempfile::tempdir().unwrap();
2446
    let root = dir.path();
2447
    let repo = Repo::init(root).unwrap().with_home(root.join("home"));
2448
    write(
2449
        root,
2450
        ".oxyattributes",
2451
        b"*.dat binary nocompress\n*.txt eol=crlf\nassets/** lockable\n",
2452
    );
2453
    write(root, "plain.dat", b"no nul bytes here\n");
2454
    write(root, "notes.txt", b"one\r\ntwo\r\n");
2455
    write(root, "assets/model.bin", b"\0model");
2456
    let h = repo.commit("attrs", &[]).unwrap();
2457
    let snap = repo.load_state(&[h]).unwrap().materialize();
2458
    assert!(
2459
        snap.files["plain.dat"].mode.opaque,
2460
        "binary attribute forces opaque without NUL bytes"
2461
    );
2462
    assert!(
2463
        matches!(&snap.files["notes.txt"].content, FileContent::Text { bytes, .. } if bytes == b"one\ntwo\n"),
2464
        "stored with LF"
2465
    );
2466
    assert!(
2467
        !repo.snapshot("status").unwrap().changed,
2468
        "CRLF on disk equals LF in the state"
2469
    );
2470
    // nocompress chunks pack raw.
2471
    let r = repo.gc(true).unwrap();
2472
    assert!(r.packed.objects > 0);
2473
    // Checkout writes CRLF for eol=crlf and makes lockable files read-only.
2474
    fs::remove_file(root.join("notes.txt")).unwrap();
2475
    repo.checkout(&[h], true, "co").unwrap();
2476
    assert_eq!(fs::read(root.join("notes.txt")).unwrap(), b"one\r\ntwo\r\n");
2477
    assert!(fs::metadata(root.join("assets/model.bin"))
2478
        .unwrap()
2479
        .permissions()
2480
        .readonly());
2481
    assert!(repo.lock_path("plain.dat").is_err(), "not lockable");
2482
    repo.lock_path("assets/model.bin").unwrap();
2483
    assert!(!fs::metadata(root.join("assets/model.bin"))
2484
        .unwrap()
2485
        .permissions()
2486
        .readonly());
2487
    assert!(repo.is_locked("assets/model.bin"));
2488
    write(root, "assets/model.bin", b"\0model2");
2489
    repo.commit("edit model", &[]).unwrap();
2490
    repo.unlock_path("assets/model.bin").unwrap();
2491
    assert!(fs::metadata(root.join("assets/model.bin"))
2492
        .unwrap()
2493
        .permissions()
2494
        .readonly());
2495
    // A later checkout can still overwrite a read-only lockable file.
2496
    repo.checkout(&[h], true, "co").unwrap();
2497
    assert_eq!(fs::read(root.join("assets/model.bin")).unwrap(), b"\0model");
2498
}
2499
2500
#[cfg(unix)]
2501
#[test]
2502
fn hooks_can_veto_observe_and_add_dependencies() {
2503
    use std::os::unix::fs::PermissionsExt;
2504
    hermetic();
2505
    let dir = tempfile::tempdir().unwrap();
2506
    let root = dir.path();
2507
    let mut repo = Repo::init(root).unwrap().with_home(root.join("home"));
2508
    let hooks = root.join(".oxy/hooks");
2509
    fs::create_dir_all(&hooks).unwrap();
2510
    let hook = |name: &str, body: &str| {
2511
        let p = hooks.join(name);
2512
        fs::write(&p, format!("#!/bin/sh\n{body}\n")).unwrap();
2513
        fs::set_permissions(&p, fs::Permissions::from_mode(0o755)).unwrap();
2514
    };
2515
    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");
2516
    hook("post-commit", "cat > \"$OXY_ROOT/.last-post-commit\"");
2517
    hook("post-checkout", "cat > \"$OXY_ROOT/.last-post-checkout\"");
2518
    hook("pre-push", "echo pushing blocked >&2; exit 3");
2519
    write(root, ".oxyignore", b".last-*\n");
2520
    write(root, "a.txt", b"a\n");
2521
    let err = repo.commit("WIP: nope", &[]).unwrap_err().to_string();
2522
    assert!(err.contains("pre-commit refused: no WIP commits"), "{err}");
2523
    let h1 = repo.commit("first", &[]).unwrap();
2524
    let pre = fs::read_to_string(root.join(".last-pre-commit")).unwrap();
2525
    assert!(
2526
        pre.contains("\"event\":\"pre-commit\"")
2527
            && pre.contains("\"path\":\"a.txt\"")
2528
            && pre.contains("\"message\":\"first\""),
2529
        "{pre}"
2530
    );
2531
    let post = fs::read_to_string(root.join(".last-post-commit")).unwrap();
2532
    assert!(post.contains(&h1.to_hex()), "{post}");
2533
    repo.checkout(&[h1], false, "co").unwrap();
2534
    assert!(fs::read_to_string(root.join(".last-post-checkout"))
2535
        .unwrap()
2536
        .contains("post-checkout"));
2537
    repo.config.set("remote.origin.url", "/nowhere").unwrap();
2538
    repo.save_config().unwrap();
2539
    let err = repo.push("origin", false).unwrap_err().to_string();
2540
    assert!(err.contains("pre-push refused: pushing blocked"), "{err}");
2541
2542
    // semantic-deps: only when enabled; adds an explicit dependency.
2543
    write(root, "b.txt", b"b\n");
2544
    hook(
2545
        "semantic-deps",
2546
        &format!(
2547
            "cat > \"$OXY_ROOT/.last-semantic\"; echo '{{\"deps\": [\"{}\"]}}'",
2548
            h1.to_hex()
2549
        ),
2550
    );
2551
    let h2 = repo.commit("b without hook", &[]).unwrap();
2552
    assert!(
2553
        repo.store().get_change(&h2).unwrap().deps.is_empty(),
2554
        "hook disabled by default"
2555
    );
2556
    repo.config.set("hooks.semantic-deps", "true").unwrap();
2557
    repo.save_config().unwrap();
2558
    write(root, "c.txt", b"c\n");
2559
    let h3 = repo.commit("c with hook", &[]).unwrap();
2560
    assert_eq!(repo.store().get_change(&h3).unwrap().deps, vec![h1]);
2561
    let sem = fs::read_to_string(root.join(".last-semantic")).unwrap();
2562
    assert!(
2563
        sem.contains("\"touched_paths\":[\"c.txt\"]") && sem.contains("candidate_deps"),
2564
        "{sem}"
2565
    );
2566
    assert_eq!(json_str("a\"b\\c\n"), "\"a\\\"b\\\\c\\n\"");
2567
}
2568
2569
#[test]
2570
fn amend_into_older_change_and_split() {
2571
    hermetic();
2572
    let dir = tempfile::tempdir().unwrap();
2573
    let root = dir.path();
2574
    let mut repo = Repo::init(root).unwrap().with_home(root.join("home"));
2575
    repo.create_identity("Ada", "a@b", IdentityScope::User)
2576
        .unwrap();
2577
    repo.set_user_config("core.sign", "change").unwrap();
2578
    write(root, "a.txt", b"one\ntwo\n");
2579
    let h0 = repo.commit("base", &[]).unwrap();
2580
    write(root, "a.txt", b"one\nTWO\n");
2581
    let h1 = repo.commit("edit two", &[]).unwrap();
2582
    write(root, "a.txt", b"one\nTWO\nthree\n");
2583
    let h2 = repo.commit("add three", &[]).unwrap();
2584
    let id1 = repo.store().get_change(&h1).unwrap().change_id;
2585
2586
    // Fixing the line h1 introduced folds into h1; h2 is rewritten on top.
2587
    write(root, "a.txt", b"one\nTWO!\nthree\n");
2588
    let h1b = repo.amend_into(&h1, None).unwrap();
2589
    assert_ne!(h1b, h1);
2590
    let c1b = repo.store().get_change(&h1b).unwrap();
2591
    assert_eq!(c1b.change_id, id1);
2592
    assert_eq!(c1b.deps, vec![h0]);
2593
    assert!(matches!(
2594
        repo.verify_change(&h1b).unwrap(),
2595
        SignatureStatus::Valid { .. }
2596
    ));
2597
    let heads = repo.bookmark_heads().unwrap();
2598
    assert_eq!(heads.len(), 1);
2599
    let top = repo.store().get_change(&heads[0]).unwrap();
2600
    assert_eq!(top.message, "add three");
2601
    assert_eq!(
2602
        top.deps.iter().copied().collect::<BTreeSet<_>>(),
2603
        [h0, h1b].into_iter().collect(),
2604
        "depends on the file's creator and the rewritten line"
2605
    );
2606
    let snap = repo.load_state(&heads).unwrap().materialize();
2607
    assert!(
2608
        matches!(&snap.files["a.txt"].content, FileContent::Text { bytes, .. } if bytes == b"one\nTWO!\nthree\n")
2609
    );
2610
    assert!(
2611
        !repo.snapshot("status").unwrap().changed,
2612
        "the working copy is clean after folding"
2613
    );
2614
    // Only h1b's own state shows the fix without "three".
2615
    let only = repo.load_state(&[h1b]).unwrap().materialize();
2616
    assert!(
2617
        matches!(&only.files["a.txt"].content, FileContent::Text { bytes, .. } if bytes == b"one\nTWO!\n")
2618
    );
2619
    assert_eq!(repo.log().unwrap().len(), 4);
2620
2621
    // An edit to a line introduced by h2 cannot fold into h1.
2622
    write(root, "a.txt", b"one\nTWO!\nthree!\n");
2623
    let err = repo.amend_into(&h1b, None).unwrap_err().to_string();
2624
    assert!(err.contains("introduced after"), "{err}");
2625
    assert!(
2626
        repo.snapshot("status").unwrap().statuses.len() == 1,
2627
        "nothing was changed by the refusal"
2628
    );
2629
    write(root, "a.txt", b"one\nTWO!\nthree\n");
2630
2631
    // Split the head that touches two files.
2632
    write(root, "b.txt", b"b\n");
2633
    write(root, "c.txt", b"c\n");
2634
    let h3 = repo.commit("b and c", &[]).unwrap();
2635
    let id3 = repo.store().get_change(&h3).unwrap().change_id;
2636
    let (p1, p2) = repo.split(&h3, &["b.txt".into()]).unwrap();
2637
    let c_1 = repo.store().get_change(&p1).unwrap();
2638
    let c_2 = repo.store().get_change(&p2).unwrap();
2639
    assert!(c_1.message.contains("part 1: b.txt"));
2640
    assert_eq!(c_2.change_id, id3);
2641
    let heads: BTreeSet<_> = repo.bookmark_heads().unwrap().into_iter().collect();
2642
    assert!(
2643
        heads.contains(&p1) && heads.contains(&p2),
2644
        "independent parts are both heads"
2645
    );
2646
    let snap = repo
2647
        .load_state(&repo.bookmark_heads().unwrap())
2648
        .unwrap()
2649
        .materialize();
2650
    assert!(snap.files.contains_key("b.txt") && snap.files.contains_key("c.txt"));
2651
    let only1 = repo.load_state(&[p1]).unwrap().materialize();
2652
    assert!(only1.files.contains_key("b.txt") && !only1.files.contains_key("c.txt"));
2653
    assert!(!repo.snapshot("status").unwrap().changed);
2654
    assert!(repo.split(&p2, &["nope.txt".into()]).is_err());
2655
    let _ = h2;
2656
}
2657
2658
#[test]
2659
fn identity_lifecycle() {
2660
    hermetic();
2661
    let dir = tempfile::tempdir().unwrap();
2662
    let root = dir.path();
2663
    let origin = Repo::init(&root.join("origin")).unwrap();
2664
    let url = root.join("origin").to_string_lossy().to_string();
2665
    let mut a = Repo::clone(&url, &root.join("a"))
2666
        .unwrap()
2667
        .with_home(root.join("home-a"));
2668
    a.set_user_config("core.sign", "change").unwrap();
2669
    let (key_a, _) = a
2670
        .create_identity("Ada", "[email protected]", IdentityScope::User)
2671
        .unwrap();
2672
    write(&root.join("a"), "a.txt", b"a\n");
2673
    let h1 = a.commit("one", &[]).unwrap();
2674
    assert!(a.policy_init().unwrap().applied);
2675
    assert!(a.push("origin", false).unwrap().iter().all(|r| r.ok));
2676
2677
    // Expiry: an identity that had expired when the change was made does not authenticate it.
2678
    let mut e = Repo::init(&root.join("e"))
2679
        .unwrap()
2680
        .with_home(root.join("home-e"));
2681
    e.set_user_config("core.sign", "change").unwrap();
2682
    e.create_identity_with(
2683
        "Eve",
2684
        "[email protected]",
2685
        IdentityScope::User,
2686
        Some(Hlc::now().wall_ms - 1),
2687
    )
2688
    .unwrap();
2689
    write(&root.join("e"), "e.txt", b"e\n");
2690
    let he = e.commit("late", &[]).unwrap();
2691
    assert!(
2692
        matches!(e.verify_change(&he).unwrap(), SignatureStatus::Invalid(m) if m.contains("expired"))
2693
    );
2694
    // Renewal re-issues the identity (same keys, new KeyId) with a later expiry.
2695
    let r = e
2696
        .renew_identity(Some(Hlc::now().wall_ms + 86_400_000))
2697
        .unwrap();
2698
    assert_eq!(e.identity(&r.new).unwrap().previous, Some(r.old));
2699
    write(&root.join("e"), "e.txt", b"e2\n");
2700
    let he2 = e.commit("in time", &[]).unwrap();
2701
    assert!(
2702
        matches!(e.verify_change(&he2).unwrap(), SignatureStatus::Valid { key, .. } if key == r.new)
2703
    );
2704
2705
    // Rotation: a fresh key; the old change still verifies; the policy follows.
2706
    let r = a.rotate_identity().unwrap();
2707
    assert_eq!(r.old, key_a);
2708
    assert_eq!(a.config.author_key, Some(r.new));
2709
    assert_eq!(a.identity(&r.new).unwrap().previous, Some(key_a));
2710
    assert!(r.policy.as_ref().unwrap().applied);
2711
    let (_, sp) = a.current_policy().unwrap().unwrap();
2712
    assert_eq!(
2713
        (sp.policy.serial, sp.policy.roots.clone()),
2714
        (2, vec![r.new])
2715
    );
2716
    assert!(
2717
        !sp.policy.revoked.contains(&key_a) && sp.policy.authorizes(&r.new, "main"),
2718
        "superseded, not revoked"
2719
    );
2720
    assert!(sp.policy.succeeds(&r.new, &key_a) && !sp.policy.succeeds(&key_a, &r.new));
2721
    assert!(
2722
        matches!(a.verify_change(&h1).unwrap(), SignatureStatus::Valid { key, revoked: false, .. } if key == key_a)
2723
    );
2724
    write(&root.join("a"), "a.txt", b"a2\n");
2725
    let h2 = a.commit("two", &[]).unwrap();
2726
    assert!(
2727
        matches!(a.verify_change(&h2).unwrap(), SignatureStatus::Valid { key, revoked: false, .. } if key == r.new)
2728
    );
2729
    // Origin accepts the rotated policy (signed by the old root) and the new key's change.
2730
    let res = a.push("origin", false).unwrap();
2731
    assert!(res.iter().all(|x| x.ok), "{res:?}");
2732
    assert_eq!(origin.current_policy().unwrap().unwrap().1.policy.serial, 2);
2733
    let key_a = r.new;
2734
2735
    // Delegation: Bob may sign on Ada's behalf. Delegates live in the
2736
    // identity object, so Ada's KeyId changes while her keys stay the same.
2737
    let mut b = Repo::clone(&url, &root.join("b"))
2738
        .unwrap()
2739
        .with_home(root.join("home-b"));
2740
    let (key_b, id_b) = b
2741
        .create_identity("Bob", "[email protected]", IdentityScope::User)
2742
        .unwrap();
2743
    let r = a.delegate_add(id_b.clone(), Scope::ALL, None).unwrap();
2744
    assert_eq!(r.old, key_a);
2745
    let key_a2 = r.new;
2746
    assert_eq!(
2747
        a.identity(&key_a2).unwrap().delegates,
2748
        vec![Delegate::full(key_b)]
2749
    );
2750
    assert_eq!(
2751
        a.identity(&key_a2).unwrap().ed25519_pk,
2752
        a.identity(&key_a).unwrap().ed25519_pk
2753
    );
2754
    assert!(
2755
        a.delegate_add(id_b.clone(), Scope::ALL, None).is_err(),
2756
        "already a delegate"
2757
    );
2758
    assert!(a.push("origin", false).unwrap().iter().all(|x| x.ok));
2759
    write(&root.join("a"), "a.txt", b"a3\n");
2760
    let h3 = a.commit("three", &[]).unwrap();
2761
    assert!(
2762
        matches!(a.verify_change(&h3).unwrap(), SignatureStatus::Valid { key, .. } if key == key_a2),
2763
        "the same secret signs under the new KeyId"
2764
    );
2765
    // A change authored by Ada but signed only by Bob verifies through the delegation.
2766
    a.set_user_config("core.sign", "seal").unwrap();
2767
    write(&root.join("a"), "a.txt", b"a4\n");
2768
    let h4 = a.commit("four", &[]).unwrap();
2769
    assert_eq!(a.verify_change(&h4).unwrap(), SignatureStatus::Unsigned);
2770
    let (_, sk_b) = b.secret_key().unwrap().unwrap();
2771
    a.store()
2772
        .put_signature(&h4, &sk_b.sign(Domain::Change, &key_b, &h4))
2773
        .unwrap();
2774
    assert!(
2775
        matches!(a.verify_change(&h4).unwrap(), SignatureStatus::Valid { key, .. } if key == key_b)
2776
    );
2777
    a.set_user_config("core.sign", "change").unwrap();
2778
    // Withdrawing the delegation re-issues the identity again.
2779
    let r = a.delegate_remove(&key_b).unwrap();
2780
    assert!(a.identity(&r.new).unwrap().delegates.is_empty());
2781
    assert!(a.delegate_remove(&key_b).is_err());
2782
    let key_a3 = r.new;
2783
    let res = a.push("origin", false).unwrap();
2784
    assert!(res.iter().all(|x| x.ok), "{res:?}");
2785
2786
    // Multi-signer policy: Bob becomes a root and the threshold rises to 2,
2787
    // both applied under the old threshold of 1. A grant then needs Bob too.
2788
    assert!(a.policy_root_add(id_b.clone()).unwrap().applied);
2789
    assert!(a.policy_root_add(id_b.clone()).is_err());
2790
    assert!(a.policy_set_threshold(3).is_err());
2791
    assert!(a.policy_set_threshold(2).unwrap().applied);
2792
    assert!(a.push("origin", false).unwrap().iter().all(|x| x.ok));
2793
    b.pull("origin").unwrap();
2794
    assert_eq!(
2795
        b.current_policy().unwrap().unwrap().1.policy.root_threshold,
2796
        2
2797
    );
2798
    let mut c = Repo::init(&root.join("c"))
2799
        .unwrap()
2800
        .with_home(root.join("home-c"));
2801
    let (key_c, id_c) = c
2802
        .create_identity("Cy", "[email protected]", IdentityScope::User)
2803
        .unwrap();
2804
    let serial_before = a.current_policy().unwrap().unwrap().1.policy.serial;
2805
    let proposal = a.policy_grant(id_c, None).unwrap();
2806
    assert!(!proposal.applied && proposal.sigs.len() == 1);
2807
    assert_eq!(proposal.policy.serial, serial_before + 1);
2808
    assert_eq!(
2809
        a.current_policy().unwrap().unwrap().1.policy.serial,
2810
        serial_before,
2811
        "a proposal changes nothing yet"
2812
    );
2813
    // Bob signs the proposal, handed over as a file, and it applies for him.
2814
    let bytes = proposal.signed().encode();
2815
    let signed = b
2816
        .policy_sign(SignedPolicy::decode(&bytes).unwrap())
2817
        .unwrap();
2818
    assert!(signed.applied && signed.sigs.len() == 2);
2819
    assert!(b
2820
        .current_policy()
2821
        .unwrap()
2822
        .unwrap()
2823
        .1
2824
        .policy
2825
        .authorizes(&key_c, "main"));
2826
    assert!(
2827
        b.policy_sign(signed.signed()).is_err(),
2828
        "a stale proposal is refused"
2829
    );
2830
    // Bob publishes it and Ada picks it up.
2831
    assert!(b
2832
        .push("origin", false)
2833
        .unwrap()
2834
        .iter()
2835
        .any(|x| x.name == "policy" && x.ok));
2836
    a.pull("origin").unwrap();
2837
    assert_eq!(
2838
        a.current_policy().unwrap().unwrap().1.policy.serial,
2839
        serial_before + 1
2840
    );
2841
    // A root cannot revoke itself; revoking Cy needs both roots but is recorded locally at once.
2842
    assert!(a.policy_revoke(&key_a3).is_err());
2843
    let u = a
2844
        .revoke_identity(&key_c, "left the project")
2845
        .unwrap()
2846
        .unwrap();
2847
    assert!(!u.applied);
2848
    assert!(a.is_revoked(&key_c).unwrap());
2849
    assert!(!b.is_revoked(&key_c).unwrap());
2850
    let u = b.policy_sign(u.signed()).unwrap();
2851
    assert!(u.applied && u.policy.is_revoked(&key_c));
2852
    assert!(b.is_revoked(&key_c).unwrap());
2853
    // Bob can revoke Ada's root key, leaving himself as the only root (threshold 2 would be unmeetable).
2854
    assert!(
2855
        b.policy_revoke(&key_a3).is_err(),
2856
        "would leave one root for a threshold of 2"
2857
    );
2858
    // Revoking one's own key without a policy root works locally: a plain marker plus attestation.
2859
    let key_c_own = c.config.author_key.unwrap();
2860
    assert!(c
2861
        .revoke_identity(&key_c_own, "lost laptop")
2862
        .unwrap()
2863
        .is_none());
2864
    assert!(c.is_revoked(&key_c_own).unwrap());
2865
    assert_eq!(key_c_own, key_c);
2866
}
2867
2868
#[test]
2869
fn renames_are_detected_and_tracked_as_moves() {
2870
    hermetic();
2871
    let dir = tempfile::tempdir().unwrap();
2872
    let root = dir.path();
2873
    let repo = Repo::init(root).unwrap().with_home(root.join("home"));
2874
    write(
2875
        root,
2876
        "src/old.rs",
2877
        b"fn a() {}\nfn b() {}\nfn c() {}\nfn d() {}\n",
2878
    );
2879
    write(root, "img.bin", b"\x89PNG\0\0\x01\x02");
2880
    write(root, "tiny.txt", b"x\n");
2881
    let h1 = repo.commit("base", &[]).unwrap();
2882
    let node_old = repo.load_state(&[h1]).unwrap().materialize().files["src/old.rs"].node;
2883
    let node_img = repo.load_state(&[h1]).unwrap().materialize().files["img.bin"].node;
2884
2885
    // Rename with a small edit, a binary moved unchanged, and a rewrite
2886
    // that shares nothing with the removed file.
2887
    fs::remove_file(root.join("src/old.rs")).unwrap();
2888
    write(
2889
        root,
2890
        "lib/new.rs",
2891
        b"fn a() {}\nfn b() {}\nfn c() {}\nfn e() {}\n",
2892
    );
2893
    fs::remove_file(root.join("img.bin")).unwrap();
2894
    write(root, "assets/img.bin", b"\x89PNG\0\0\x01\x02");
2895
    fs::remove_file(root.join("tiny.txt")).unwrap();
2896
    write(root, "other.txt", b"completely different\n");
2897
    let snap = repo.snapshot("status").unwrap();
2898
    let statuses: Vec<(&str, ChangeStatus)> = snap
2899
        .statuses
2900
        .iter()
2901
        .map(|s| (s.path.as_str(), s.status))
2902
        .collect();
2903
    assert_eq!(
2904
        statuses,
2905
        vec![
2906
            ("assets/img.bin", ChangeStatus::Renamed),
2907
            ("lib/new.rs", ChangeStatus::Renamed),
2908
            ("other.txt", ChangeStatus::Added),
2909
            ("src", ChangeStatus::Removed),
2910
            ("tiny.txt", ChangeStatus::Removed)
2911
        ]
2912
    );
2913
    let h2 = repo.commit("move things", &[]).unwrap();
2914
    let c = repo.store().get_change(&h2).unwrap();
2915
    let moves: Vec<_> = c
2916
        .tree_ops
2917
        .iter()
2918
        .filter(|op| matches!(op, TreeOp::Move { .. }))
2919
        .collect();
2920
    assert_eq!(moves.len(), 2, "{:?}", c.tree_ops);
2921
    assert!(c.tree_ops.iter().any(
2922
        |op| matches!(op, TreeOp::Move { node, name, .. } if *node == node_old && name == "new.rs")
2923
    ));
2924
    assert!(c.tree_ops.iter().any(
2925
        |op| matches!(op, TreeOp::Move { node, name, .. } if *node == node_img && name == "img.bin")
2926
    ));
2927
    let snap = repo.load_state(&[h2]).unwrap().materialize();
2928
    assert_eq!(
2929
        snap.files["lib/new.rs"].node, node_old,
2930
        "the node survives the rename"
2931
    );
2932
    assert!(
2933
        matches!(&snap.files["lib/new.rs"].content, FileContent::Text { bytes, .. } if bytes == b"fn a() {}\nfn b() {}\nfn c() {}\nfn e() {}\n")
2934
    );
2935
    assert!(!snap.files.contains_key("src/old.rs") && !snap.files.contains_key("src"));
2936
    assert!(render_change(
2937
        &c,
2938
        &repo.load_state(&[h1]).unwrap(),
2939
        &repo.load_state(&[h1]).unwrap().materialize()
2940
    )
2941
    .contains("R "));
2942
    // A fresh checkout reproduces the tree.
2943
    let other = tempfile::tempdir().unwrap();
2944
    let clone = Repo::clone(&root.to_string_lossy(), other.path()).unwrap();
2945
    assert_eq!(
2946
        fs::read(other.path().join("lib/new.rs")).unwrap(),
2947
        b"fn a() {}\nfn b() {}\nfn c() {}\nfn e() {}\n"
2948
    );
2949
    assert!(!other.path().join("src").exists());
2950
    assert!(!clone.snapshot("status").unwrap().changed);
2951
    // Similarity is line based, byte weighted.
2952
    assert_eq!(similarity(b"a\nb\n", b"a\nb\n"), 100);
2953
    assert_eq!(similarity(b"a\nb\nc\nd\n", b"a\nb\nx\ny\n"), 50);
2954
    assert_eq!(similarity(b"hello\n", b"world\n"), 0);
2955
    assert_eq!(similarity(b"", b"x\n"), 0);
2956
}
2957
2958
#[test]
2959
fn git_fetch_and_push_round_trip() {
2960
    hermetic();
2961
    if std::process::Command::new("git")
2962
        .arg("--version")
2963
        .output()
2964
        .is_err()
2965
    {
2966
        eprintln!("git not installed; skipping");
2967
        return;
2968
    }
2969
    let dir = tempfile::tempdir().unwrap();
2970
    let root = dir.path();
2971
    let git_in = |d: &Path, args: &[&str]| -> String {
2972
        let out = std::process::Command::new("git")
2973
            .arg("-C")
2974
            .arg(d)
2975
            .args([
2976
                "-c",
2977
                "user.name=Grace",
2978
                "-c",
2979
                "[email protected]",
2980
                "-c",
2981
                "commit.gpgsign=false",
2982
            ])
2983
            .args(args)
2984
            .output()
2985
            .unwrap();
2986
        assert!(
2987
            out.status.success(),
2988
            "git {args:?}: {}",
2989
            String::from_utf8_lossy(&out.stderr)
2990
        );
2991
        String::from_utf8_lossy(&out.stdout).trim().to_string()
2992
    };
2993
    // A bare "remote" and a work tree that pushes to it.
2994
    let remote = root.join("remote.git");
2995
    fs::create_dir_all(&remote).unwrap();
2996
    git_in(&remote, &["init", "-q", "--bare", "-b", "main"]);
2997
    let work = root.join("work");
2998
    git_in(
2999
        root,
3000
        &[
3001
            "clone",
3002
            "-q",
3003
            remote.to_str().unwrap(),
3004
            work.to_str().unwrap(),
3005
        ],
3006
    );
3007
    git_in(&work, &["checkout", "-q", "-b", "main"]);
3008
    write(&work, "README.md", b"# Project\n");
3009
    write(&work, "src/lib.rs", b"pub fn a() {}\n");
3010
    git_in(&work, &["add", "."]);
3011
    git_in(&work, &["commit", "-q", "-m", "initial"]);
3012
    write(&work, "src/lib.rs", b"pub fn a() {}\npub fn b() {}\n");
3013
    git_in(&work, &["commit", "-q", "-am", "second"]);
3014
    git_in(&work, &["push", "-q", "origin", "main"]);
3015
    let tip1 = git_in(&work, &["rev-parse", "HEAD"]);
3016
3017
    // Fetch into a fresh oxy repository.
3018
    let o = root.join("oxy");
3019
    let mut repo = Repo::init(&o).unwrap().with_home(root.join("home"));
3020
    repo.create_identity("Ada", "[email protected]", IdentityScope::User)
3021
        .unwrap();
3022
    let url = remote.to_string_lossy().to_string();
3023
    let r = repo.git_fetch(&url, "main").unwrap();
3024
    assert_eq!((r.commits, r.heads), (2, 1));
3025
    assert_eq!(
3026
        fs::read(o.join("src/lib.rs")).unwrap(),
3027
        b"pub fn a() {}\npub fn b() {}\n"
3028
    );
3029
    assert!(!repo.snapshot("status").unwrap().changed);
3030
    assert_eq!(
3031
        repo.git_fetch(&url, "main").unwrap().commits,
3032
        0,
3033
        "nothing new"
3034
    );
3035
3036
    // An oxy change, pushed back: one commit on top of the Git tip.
3037
    write(
3038
        &o,
3039
        "src/lib.rs",
3040
        b"pub fn a() {}\npub fn b() {}\npub fn c() {}\n",
3041
    );
3042
    write(&o, "NOTES.md", b"from oxy\n");
3043
    let h_oxy = repo.commit("add c and notes", &[]).unwrap();
3044
    let r = repo.git_push(&url, "main").unwrap();
3045
    assert_eq!(r.exported, 1, "{r:?}");
3046
    git_in(&work, &["pull", "-q", "--ff-only", "origin", "main"]);
3047
    assert_eq!(
3048
        git_in(&work, &["log", "--format=%s", "main"]),
3049
        "add c and notes\nsecond\ninitial"
3050
    );
3051
    assert_eq!(git_in(&work, &["rev-parse", "HEAD~1"]), tip1);
3052
    assert_eq!(fs::read(work.join("NOTES.md")).unwrap(), b"from oxy\n");
3053
    assert_eq!(git_in(&work, &["log", "-1", "--format=%an", "main"]), "Ada");
3054
    assert!(git_in(&work, &["log", "-1", "--format=%B", "main"])
3055
        .contains(&format!("Oxy-Hash: {}", h_oxy.to_hex())));
3056
    assert_eq!(
3057
        repo.git_push(&url, "main").unwrap().exported,
3058
        0,
3059
        "already pushed"
3060
    );
3061
3062
    // Git moves on; pushing without fetching is refused, fetching brings
3063
    // the commit in and the working copy follows.
3064
    write(&work, "README.md", b"# Project\n\nMore.\n");
3065
    git_in(&work, &["commit", "-q", "-am", "readme from git"]);
3066
    git_in(&work, &["push", "-q", "origin", "main"]);
3067
    let tip2 = git_in(&work, &["rev-parse", "HEAD"]);
3068
    assert!(repo
3069
        .git_push(&url, "main")
3070
        .unwrap_err()
3071
        .to_string()
3072
        .contains("fetch"));
3073
    let r = repo.git_fetch(&url, "main").unwrap();
3074
    assert_eq!(
3075
        (r.commits, r.heads),
3076
        (1, 2),
3077
        "the Git change and the oxy change commute"
3078
    );
3079
    assert_eq!(
3080
        fs::read(o.join("README.md")).unwrap(),
3081
        b"# Project\n\nMore.\n"
3082
    );
3083
    assert_eq!(fs::read(o.join("NOTES.md")).unwrap(), b"from oxy\n");
3084
    assert!(!repo.snapshot("status").unwrap().changed);
3085
    // Another oxy change pushes on top of Git's newest commit.
3086
    write(&o, "NOTES.md", b"from oxy\nagain\n");
3087
    repo.commit("notes again", &[]).unwrap();
3088
    assert_eq!(repo.git_push(&url, "main").unwrap().exported, 1);
3089
    git_in(&work, &["pull", "-q", "--ff-only", "origin", "main"]);
3090
    assert_eq!(git_in(&work, &["rev-parse", "HEAD~1"]), tip2);
3091
    assert_eq!(
3092
        fs::read(work.join("NOTES.md")).unwrap(),
3093
        b"from oxy\nagain\n"
3094
    );
3095
    assert_eq!(
3096
        git_in(&work, &["log", "--format=%s", "main"])
3097
            .lines()
3098
            .count(),
3099
        5
3100
    );
3101
}
3102
3103
/// Benchmark, not a gate: `cargo test --release -p oxy-core --lib bench_one_gibibyte -- --ignored --nocapture`.
3104
/// Commits, stores, clones, and reads back a 1 GiB incompressible file.
3105
#[test]
3106
#[ignore]
3107
fn bench_one_gibibyte_file() {
3108
    hermetic();
3109
    // /tmp is often a small tmpfs; `OXY_BENCH_DIR` picks a roomier disk.
3110
    let dir = match std::env::var_os("OXY_BENCH_DIR") {
3111
        Some(d) => tempfile::tempdir_in(d).unwrap(),
3112
        None => tempfile::tempdir().unwrap(),
3113
    };
3114
    let root = dir.path();
3115
    let repo = Repo::init(&root.join("r"))
3116
        .unwrap()
3117
        .with_home(root.join("home"));
3118
    let size = 1usize << 30;
3119
    let mut data = vec![0u8; size];
3120
    let mut x = 0x9e3779b97f4a7c15u64;
3121
    for chunk in data.chunks_mut(8) {
3122
        x ^= x << 13;
3123
        x ^= x >> 7;
3124
        x ^= x << 17;
3125
        let b = x.to_le_bytes();
3126
        chunk.copy_from_slice(&b[..chunk.len()]);
3127
    }
3128
    let t = std::time::Instant::now();
3129
    write(&root.join("r"), "big.bin", &data);
3130
    eprintln!("write 1 GiB to disk: {:.2?}", t.elapsed());
3131
    let t = std::time::Instant::now();
3132
    let h = repo.commit("big", &[]).unwrap();
3133
    eprintln!("commit (chunk + hash + store): {:.2?}", t.elapsed());
3134
    let t = std::time::Instant::now();
3135
    assert!(!repo.snapshot("status").unwrap().changed);
3136
    eprintln!("status on a clean 1 GiB working copy: {:.2?}", t.elapsed());
3137
    let t = std::time::Instant::now();
3138
    let objects = repo.store().list().unwrap().len();
3139
    eprintln!("objects stored: {objects} ({:.2?} to list)", t.elapsed());
3140
    let t = std::time::Instant::now();
3141
    let g = repo.gc(true).unwrap();
3142
    eprintln!("gc (pack): {:.2?} {g:?}", t.elapsed());
3143
    let t = std::time::Instant::now();
3144
    let clone = Repo::clone(&root.join("r").to_string_lossy(), &root.join("c")).unwrap();
3145
    eprintln!("clone (fetch + checkout): {:.2?}", t.elapsed());
3146
    let t = std::time::Instant::now();
3147
    let back = fs::read(root.join("c/big.bin")).unwrap();
3148
    assert_eq!(blake3::hash(&back), blake3::hash(&data));
3149
    eprintln!("read back and verify: {:.2?}", t.elapsed());
3150
    assert_eq!(clone.bookmark_heads().unwrap(), vec![h]);
3151
    let store_bytes: u64 = walkdir_size(&root.join("r/.oxy/objects"));
3152
    eprintln!(
3153
        "store size: {:.1} MiB for 1 GiB of data",
3154
        store_bytes as f64 / (1024.0 * 1024.0)
3155
    );
3156
}
3157
3158
fn walkdir_size(p: &Path) -> u64 {
3159
    let mut total = 0;
3160
    if let Ok(rd) = fs::read_dir(p) {
3161
        for e in rd.flatten() {
3162
            let path = e.path();
3163
            if path.is_dir() {
3164
                total += walkdir_size(&path);
3165
            } else if let Ok(m) = fs::metadata(&path) {
3166
                total += m.len();
3167
            }
3168
        }
3169
    }
3170
    total
3171
}
3172
3173
/// An opaque file whose size and mtime match the manifest is not read on
3174
/// the next snapshot: its blob comes from the manifest's stat cache.
3175
#[cfg(unix)]
3176
#[test]
3177
fn stat_cache_skips_reading_unchanged_opaque_files() {
3178
    use std::os::unix::fs::PermissionsExt;
3179
    hermetic();
3180
    let dir = tempfile::tempdir().unwrap();
3181
    let root = dir.path();
3182
    let repo = Repo::init(root).unwrap().with_home(root.join("home"));
3183
    let mut big = vec![0u8; 300 * 1024];
3184
    for (i, b) in big.iter_mut().enumerate() {
3185
        *b = (i as u32).wrapping_mul(2654435761).to_le_bytes()[1];
3186
    }
3187
    big[0] = 0;
3188
    write(root, "big.bin", &big);
3189
    write(root, "a.txt", b"text\n");
3190
    let h1 = repo.commit("base", &[]).unwrap();
3191
    let (_, _, m) = repo.read_manifest().unwrap().unwrap();
3192
    assert!(
3193
        m.entries["big.bin"].blob.is_some(),
3194
        "opaque files record their blob"
3195
    );
3196
    assert!(m.entries["a.txt"].blob.is_none());
3197
    let blob = m.entries["big.bin"].blob.unwrap();
3198
    assert!(repo.store().has(&blob));
3199
3200
    // Files modified within two seconds of the manifest are racy and still
3201
    // read; age the file so the cache applies, then snapshot to record it.
3202
    let old = std::time::SystemTime::now() - std::time::Duration::from_secs(30);
3203
    fs::File::options()
3204
        .write(true)
3205
        .open(root.join("big.bin"))
3206
        .unwrap()
3207
        .set_modified(old)
3208
        .unwrap();
3209
    assert!(!repo.snapshot("status").unwrap().changed);
3210
    // Now the file cannot be read at all; the snapshot succeeds without it.
3211
    fs::set_permissions(root.join("big.bin"), fs::Permissions::from_mode(0o000)).unwrap();
3212
    let snap = repo.snapshot("status").unwrap();
3213
    assert!(
3214
        !snap.changed && snap.statuses.is_empty(),
3215
        "{:?}",
3216
        snap.statuses
3217
    );
3218
    fs::set_permissions(root.join("big.bin"), fs::Permissions::from_mode(0o644)).unwrap();
3219
    // A real change (new mtime, new content) is seen and committed correctly.
3220
    let mut big2 = big.clone();
3221
    big2[10] ^= 0xff;
3222
    write(root, "big.bin", &big2);
3223
    let snap = repo.snapshot("status").unwrap();
3224
    assert_eq!(
3225
        snap.statuses
3226
            .iter()
3227
            .map(|s| (s.path.as_str(), s.status))
3228
            .collect::<Vec<_>>(),
3229
        vec![("big.bin", ChangeStatus::Modified)]
3230
    );
3231
    let h2 = repo.commit("edit", &[]).unwrap();
3232
    let files = repo.load_state(&[h2]).unwrap().materialize().files;
3233
    assert_eq!(
3234
        files["big.bin"].content,
3235
        FileContent::Opaque {
3236
            blobs: vec![Repo::blob_ref(&big2)]
3237
        }
3238
    );
3239
    // Checkout writes a manifest with blobs too, so the next status is cached.
3240
    repo.checkout(&[h1], false, "checkout").unwrap();
3241
    let (_, _, m) = repo.read_manifest().unwrap().unwrap();
3242
    assert_eq!(m.entries["big.bin"].blob, Some(Repo::blob_ref(&big)));
3243
    assert!(!repo.snapshot("status").unwrap().changed);
3244
}
3245
3246
#[test]
3247
fn status_json_lists_conflicts_with_contributors() {
3248
    hermetic();
3249
    let dir = tempfile::tempdir().unwrap();
3250
    let root = dir.path();
3251
    let repo = Repo::init(root).unwrap().with_home(root.join("home"));
3252
    write(root, "a.txt", b"one\n");
3253
    let h1 = repo.commit("base", &[]).unwrap();
3254
    write(root, "a.txt", b"one\nleft\n");
3255
    let ha = repo.commit("left", &[]).unwrap();
3256
    repo.checkout(&[h1], true, "checkout").unwrap();
3257
    write(root, "a.txt", b"one\nright\n");
3258
    let hb = repo.commit("right", &[]).unwrap();
3259
    repo.checkout(&[ha, hb], true, "checkout").unwrap();
3260
    let snap = repo.snapshot("status").unwrap();
3261
    assert!(snap.base_snapshot.is_conflicted());
3262
    let json = repo.status_json(&snap).unwrap();
3263
    let ida = repo.store().get_change(&ha).unwrap().change_id.to_hex();
3264
    let idb = repo.store().get_change(&hb).unwrap().change_id.to_hex();
3265
    assert!(json.contains("\"conflicted\":true"), "{json}");
3266
    assert!(
3267
        json.contains("\"kind\":\"text\",\"path\":\"a.txt\""),
3268
        "{json}"
3269
    );
3270
    assert!(json.contains(&ida) && json.contains(&idb), "{json}");
3271
    assert!(json.contains("\"resolved\":false"), "{json}");
3272
    assert!(json.starts_with('{') && json.ends_with('}'));
3273
    // Resolve and the report says so; a clean copy has no conflicts.
3274
    write(root, "a.txt", b"one\nleft\nright\n");
3275
    let snap = repo.snapshot("status").unwrap();
3276
    let json = repo.status_json(&snap).unwrap();
3277
    assert!(json.contains("\"resolved\":true"), "{json}");
3278
    repo.commit("resolve", &[]).unwrap();
3279
    let snap = repo.snapshot("status").unwrap();
3280
    let json = repo.status_json(&snap).unwrap();
3281
    assert!(
3282
        json.contains("\"clean\":true,\"conflicted\":false,\"paths\":[],\"conflicts\":[]"),
3283
        "{json}"
3284
    );
3285
}
3286
3287
#[test]
3288
fn ignore_rules_do_not_untrack_files() {
3289
    hermetic();
3290
    let dir = tempfile::tempdir().unwrap();
3291
    let root = dir.path();
3292
    let repo = Repo::init(root).unwrap().with_home(root.join("home"));
3293
    write(root, "src.c", b"int x;\n");
3294
    write(root, "build/out.o", b"\0obj");
3295
    write(root, "sub/keep.log", b"keep\n");
3296
    write(root, "sub/junk.log", b"junk\n");
3297
    write(root, ".oxyignore", b"/build\n*.log\n!sub/keep.log\n");
3298
    let snap = repo.snapshot("status").unwrap();
3299
    let added: Vec<&str> = snap.statuses.iter().map(|s| s.path.as_str()).collect();
3300
    assert_eq!(
3301
        added,
3302
        vec![".oxyignore", "src.c", "sub/keep.log"],
3303
        "anchored, glob, and negated rules"
3304
    );
3305
    let h1 = repo.commit("base", &[]).unwrap();
3306
    // Ignoring a tracked file changes nothing about it.
3307
    write(root, ".oxyignore", b"/build\n*.log\n!sub/keep.log\nsrc.c\n");
3308
    let snap = repo.snapshot("status").unwrap();
3309
    assert_eq!(
3310
        snap.statuses
3311
            .iter()
3312
            .map(|s| s.path.as_str())
3313
            .collect::<Vec<_>>(),
3314
        vec![".oxyignore"]
3315
    );
3316
    let h2 = repo.commit("ignore src.c", &[]).unwrap();
3317
    assert!(repo
3318
        .load_state(&[h2])
3319
        .unwrap()
3320
        .materialize()
3321
        .files
3322
        .contains_key("src.c"));
3323
    // Its edits are still seen, by status and by the prompt.
3324
    assert_eq!(repo.quick_dirty().unwrap(), Some(false));
3325
    write(root, "src.c", b"int x, y;\n");
3326
    assert_eq!(repo.quick_dirty().unwrap(), Some(true));
3327
    let snap = repo.snapshot("status").unwrap();
3328
    assert_eq!(
3329
        snap.statuses
3330
            .iter()
3331
            .map(|s| (s.path.as_str(), s.status))
3332
            .collect::<Vec<_>>(),
3333
        vec![("src.c", ChangeStatus::Modified)]
3334
    );
3335
    let h3 = repo.commit("edit src.c", &[]).unwrap();
3336
    assert!(
3337
        matches!(&repo.load_state(&[h3]).unwrap().materialize().files["src.c"].content, FileContent::Text { bytes, .. } if bytes == b"int x, y;\n")
3338
    );
3339
    // Deleting it on disk removes it, ignored or not; a checkout brings it back.
3340
    fs::remove_file(root.join("src.c")).unwrap();
3341
    let snap = repo.snapshot("status").unwrap();
3342
    assert_eq!(
3343
        snap.statuses
3344
            .iter()
3345
            .map(|s| (s.path.as_str(), s.status))
3346
            .collect::<Vec<_>>(),
3347
        vec![("src.c", ChangeStatus::Removed)]
3348
    );
3349
    repo.checkout(&[h3], true, "checkout").unwrap();
3350
    assert_eq!(fs::read(root.join("src.c")).unwrap(), b"int x, y;\n");
3351
    assert!(!repo.snapshot("status").unwrap().changed);
3352
    let _ = h1;
3353
}
3354
3355
#[test]
3356
fn split_works_on_non_heads_by_node() {
3357
    hermetic();
3358
    let dir = tempfile::tempdir().unwrap();
3359
    let root = dir.path();
3360
    let repo = Repo::init(root).unwrap().with_home(root.join("home"));
3361
    write(root, "a.txt", b"one\n");
3362
    write(root, "junk/x.lock", b"lock\n");
3363
    let h1 = repo.commit("work plus junk", &[]).unwrap();
3364
    write(root, "a.txt", b"one\ntwo\n");
3365
    let h2 = repo.commit("more work", &[]).unwrap();
3366
    assert_eq!(repo.store().get_change(&h2).unwrap().deps, vec![h1]);
3367
    let id1 = repo.store().get_change(&h1).unwrap().change_id;
3368
    // h1 is not a head: split it by node.
3369
    let (hj, h1b) = repo.split(&h1, &["junk".into()]).unwrap();
3370
    assert_ne!(h1b, h1);
3371
    assert_eq!(
3372
        repo.store().get_change(&h1b).unwrap().change_id,
3373
        id1,
3374
        "the rest keeps the ChangeId"
3375
    );
3376
    let junk = repo.store().get_change(&hj).unwrap();
3377
    assert!(junk.tree_ops.iter().all(
3378
        |op| matches!(op, TreeOp::AddNode { name, .. } if name == "junk" || name == "x.lock")
3379
    ));
3380
    let heads = repo.bookmark_heads().unwrap();
3381
    assert!(
3382
        heads.contains(&hj),
3383
        "the split-off part is a head of its own"
3384
    );
3385
    let snap = repo.load_state(&heads).unwrap().materialize();
3386
    assert!(
3387
        matches!(&snap.files["a.txt"].content, FileContent::Text { bytes, .. } if bytes == b"one\ntwo\n"),
3388
        "the dependent was rewritten onto the new hash"
3389
    );
3390
    assert!(snap.files.contains_key("junk/x.lock"));
3391
    let h2b = heads
3392
        .iter()
3393
        .find(|h| repo.store().get_change(h).unwrap().message == "more work")
3394
        .copied()
3395
        .unwrap();
3396
    assert_eq!(repo.store().get_change(&h2b).unwrap().deps, vec![h1b]);
3397
    assert!(!repo.snapshot("status").unwrap().changed);
3398
    // Abandoning the split-off head removes the junk from history.
3399
    repo.abandon(&hj).unwrap();
3400
    let heads = repo.bookmark_heads().unwrap();
3401
    let snap = repo.load_state(&heads).unwrap().materialize();
3402
    assert!(!snap.files.contains_key("junk/x.lock") && !snap.files.contains_key("junk"));
3403
    assert!(snap.files.contains_key("a.txt"));
3404
    // A dependent that touches the split-off paths blocks the split.
3405
    write(root, "junk/y.lock", b"y\n");
3406
    let hb = repo.commit("junk base", &[]).unwrap();
3407
    write(root, "junk/y.lock", b"yy\n");
3408
    write(root, "b.txt", b"b\n");
3409
    repo.commit("touches junk", &[]).unwrap();
3410
    let err = repo.split(&hb, &["junk".into()]).unwrap_err().to_string();
3411
    assert!(err.contains("depends on the split-off paths"), "{err}");
3412
}
3413
3414
#[test]
3415
fn bookmarks_switch_merge_and_push() {
3416
    hermetic();
3417
    let dir = tempfile::tempdir().unwrap();
3418
    let root = dir.path();
3419
    let origin = Repo::init(&root.join("origin")).unwrap();
3420
    let url = root.join("origin").to_string_lossy().to_string();
3421
    let mut repo = Repo::clone(&url, &root.join("r"))
3422
        .unwrap()
3423
        .with_home(root.join("home"));
3424
    let r = root.join("r");
3425
    write(&r, "a.txt", b"a\n");
3426
    let h_a = repo.commit("a", &[]).unwrap();
3427
    assert!(repo.push("origin", false).unwrap()[0].ok);
3428
3429
    // A bookmark at the working copy's base, then work on it.
3430
    assert!(repo.bookmark_create("bad name..", None).is_err());
3431
    assert!(repo.bookmark_create("-x", None).is_err());
3432
    assert_eq!(repo.bookmark_create("feature", None).unwrap(), vec![h_a]);
3433
    assert!(repo.bookmark_create("feature", None).is_err(), "exists");
3434
    repo.bookmark_switch("feature", false).unwrap();
3435
    assert_eq!(repo.config.bookmark, "feature");
3436
    write(&r, "a.txt", b"a\nb\n");
3437
    write(&r, "b.txt", b"b\n");
3438
    let h_b = repo.commit("b on feature", &[]).unwrap();
3439
    assert_eq!(
3440
        repo.bookmark_heads().unwrap(),
3441
        vec![h_b],
3442
        "b edits a.txt, so it depends on a"
3443
    );
3444
    assert_eq!(
3445
        repo.resolve_heads("main").unwrap(),
3446
        vec![h_a],
3447
        "main is untouched"
3448
    );
3449
    assert_eq!(
3450
        repo.resolve_change("feature").unwrap(),
3451
        h_b,
3452
        "a one-head bookmark names its change"
3453
    );
3454
    // Reopening keeps the workspace's bookmark.
3455
    let reopened = Repo::open(&r).unwrap().with_home(root.join("home"));
3456
    assert_eq!(reopened.config.bookmark, "feature");
3457
    // Back to main: b.txt goes away; work there.
3458
    repo.bookmark_switch("main", false).unwrap();
3459
    assert!(!r.join("b.txt").exists());
3460
    assert_eq!(fs::read(r.join("a.txt")).unwrap(), b"a\n");
3461
    write(&r, "c.txt", b"c\n");
3462
    let h_c = repo.commit("c on main", &[]).unwrap();
3463
    let list = repo.bookmarks().unwrap();
3464
    assert_eq!(
3465
        list.iter()
3466
            .map(|b| (b.name.as_str(), b.current))
3467
            .collect::<Vec<_>>(),
3468
        vec![("feature", false), ("main", true)]
3469
    );
3470
    assert_eq!(
3471
        list.iter().find(|b| b.name == "main").unwrap().ahead,
3472
        Some(1),
3473
        "c is not on origin yet"
3474
    );
3475
    // Merge feature into main: the union, both heads, no merge change.
3476
    let m = repo.merge("feature").unwrap();
3477
    assert!(m.changed && m.checked_out);
3478
    let mut want = vec![h_b, h_c];
3479
    want.sort();
3480
    assert_eq!(m.heads, want);
3481
    assert_eq!(fs::read(r.join("b.txt")).unwrap(), b"b\n");
3482
    assert!(!repo.merge("feature").unwrap().changed, "already merged");
3483
    assert!(repo.merge("main").is_err());
3484
    // The other bookmark can be pushed by name and appears at origin.
3485
    assert!(repo.push_bookmark("origin", "feature", false).unwrap()[0].ok);
3486
    assert_eq!(origin.resolve_heads("feature").unwrap(), vec![h_b]);
3487
    assert!(repo.push("origin", false).unwrap()[0].ok);
3488
    assert_eq!(
3489
        repo.bookmarks()
3490
            .unwrap()
3491
            .iter()
3492
            .find(|b| b.name == "main")
3493
            .unwrap()
3494
            .ahead,
3495
        Some(0)
3496
    );
3497
    // A second workspace inherits the current bookmark and can switch independently.
3498
    let ws = repo.workspace_add(&root.join("ws"), None).unwrap();
3499
    assert_eq!(ws.config.bookmark, "main");
3500
    let mut ws = ws;
3501
    ws.bookmark_switch("feature", false).unwrap();
3502
    assert_eq!(
3503
        Repo::open(&r).unwrap().config.bookmark,
3504
        "main",
3505
        "the first workspace is unaffected"
3506
    );
3507
    assert!(
3508
        repo.bookmark_delete("feature").is_err(),
3509
        "current bookmark of another workspace"
3510
    );
3511
    ws.bookmark_switch("main", false).unwrap();
3512
    // Set and delete.
3513
    assert_eq!(repo.bookmark_set("feature", &[h_a]).unwrap(), vec![h_a]);
3514
    assert!(repo.bookmark_delete("main").is_err(), "current here");
3515
    repo.bookmark_delete("feature").unwrap();
3516
    assert!(repo.resolve_heads("feature").is_err());
3517
    assert!(repo.bookmark_set("feature", &[h_a]).is_err());
3518
    assert!(
3519
        repo.checkout(&[h_a], false, "checkout").is_ok(),
3520
        "changes of a deleted bookmark remain"
3521
    );
3522
}
3523
3524
#[test]
3525
fn oxygen_subrepos_pin_follow_and_update() {
3526
    hermetic();
3527
    let dir = tempfile::tempdir().unwrap();
3528
    let root = dir.path();
3529
    // A library repository with two commits, and a bare-ish origin for it.
3530
    let lib_origin = Repo::init(&root.join("lib-origin")).unwrap();
3531
    let lib_url = root.join("lib-origin").to_string_lossy().to_string();
3532
    let lib = Repo::clone(&lib_url, &root.join("lib"))
3533
        .unwrap()
3534
        .with_home(root.join("home"));
3535
    write(&root.join("lib"), "lib.txt", b"v1\n");
3536
    let l1 = lib.commit("lib v1", &[]).unwrap();
3537
    assert!(lib.push("origin", false).unwrap()[0].ok);
3538
    let _ = lib_origin;
3539
3540
    // The application (a clone of its own origin) adds it as a subrepo.
3541
    let app_origin = Repo::init(&root.join("app-origin")).unwrap();
3542
    let app_url = root.join("app-origin").to_string_lossy().to_string();
3543
    let _ = app_origin;
3544
    let app_dir = root.join("app");
3545
    let app = Repo::clone(&app_url, &app_dir)
3546
        .unwrap()
3547
        .with_home(root.join("home"));
3548
    write(&app_dir, "main.txt", b"app\n");
3549
    let pin = app.submodule_add(&lib_url, "libs/lib", None).unwrap();
3550
    assert!(matches!(&pin, crate::subrepo::Pin::Oxy { heads, .. } if heads == &vec![l1]));
3551
    assert!(app_dir.join(".oxymodules").exists() && app_dir.join("libs/lib/.oxy").is_dir());
3552
    let snap = app.snapshot("status").unwrap();
3553
    let paths: Vec<&str> = snap.statuses.iter().map(|s| s.path.as_str()).collect();
3554
    assert_eq!(
3555
        paths,
3556
        vec![".oxymodules", "libs/lib", "main.txt"],
3557
        "the nested files are not walked"
3558
    );
3559
    let a1 = app.commit("app with lib", &[]).unwrap();
3560
    let files = app.load_state(&[a1]).unwrap().materialize().files;
3561
    assert_eq!(files["libs/lib"].kind, NodeKind::Subrepo);
3562
    assert!(!files.contains_key("libs/lib/lib.txt"));
3563
    assert!(!app.snapshot("status").unwrap().changed);
3564
    let subs = app.subrepos().unwrap();
3565
    assert_eq!(subs.len(), 1);
3566
    assert_eq!(subs[0].actual.as_ref(), Some(&subs[0].pin));
3567
3568
    // Advance the nested repository: the parent sees a modified pin.
3569
    let nested = Repo::open(&app_dir.join("libs/lib"))
3570
        .unwrap()
3571
        .with_home(root.join("home"));
3572
    write(&app_dir.join("libs/lib"), "lib.txt", b"v2\n");
3573
    let l2 = nested.commit("lib v2", &[]).unwrap();
3574
    assert!(nested.push("origin", false).unwrap()[0].ok);
3575
    let snap = app.snapshot("status").unwrap();
3576
    assert_eq!(
3577
        snap.statuses
3578
            .iter()
3579
            .map(|s| (s.path.as_str(), s.status))
3580
            .collect::<Vec<_>>(),
3581
        vec![("libs/lib", ChangeStatus::Modified)]
3582
    );
3583
    let a2 = app.commit("bump lib", &[]).unwrap();
3584
    // Checking out the older app state brings the nested working copy back
3585
    // to the older pin, but never moves its bookmark backwards (oxygen#38).
3586
    let r = app.checkout(&[a1], false, "checkout").unwrap();
3587
    assert!(
3588
        r.notes.len() == 1 && r.notes[0].contains("keeps 1 newer change"),
3589
        "{:?}",
3590
        r.notes
3591
    );
3592
    assert_eq!(fs::read(app_dir.join("libs/lib/lib.txt")).unwrap(), b"v1\n");
3593
    let nested = Repo::open(&app_dir.join("libs/lib")).unwrap();
3594
    assert_eq!(nested.bookmark_heads().unwrap(), vec![l2]);
3595
    assert_eq!(nested.working_copy().unwrap().1.deps, vec![l1]);
3596
    assert!(!app.snapshot("status").unwrap().changed);
3597
    // A dirty nested repository is left alone and reported.
3598
    write(&app_dir.join("libs/lib"), "scratch.txt", b"wip\n");
3599
    let r = app.checkout(&[a2], false, "checkout").unwrap();
3600
    assert!(
3601
        r.notes.iter().any(|n| n.contains("uncommitted")),
3602
        "{:?}",
3603
        r.notes
3604
    );
3605
    assert_eq!(fs::read(app_dir.join("libs/lib/lib.txt")).unwrap(), b"v1\n");
3606
    fs::remove_file(app_dir.join("libs/lib/scratch.txt")).unwrap();
3607
    let r = app.submodule_update(false, &[]).unwrap();
3608
    assert_eq!(r, vec![("libs/lib".to_string(), SubrepoSync::Updated)]);
3609
    assert_eq!(fs::read(app_dir.join("libs/lib/lib.txt")).unwrap(), b"v2\n");
3610
    let _ = l2;
3611
3612
    // A fresh clone of the app has the pin but no nested repository until update --init.
3613
    assert!(app.push("origin", false).unwrap()[0].ok);
3614
    let clone_dir = root.join("app-clone");
3615
    let clone = Repo::clone(&app_url, &clone_dir)
3616
        .unwrap()
3617
        .with_home(root.join("home"));
3618
    assert!(!clone_dir.join("libs/lib/.oxy").exists());
3619
    assert_eq!(
3620
        clone.submodule_update(false, &[]).unwrap(),
3621
        vec![("libs/lib".to_string(), SubrepoSync::Missing)]
3622
    );
3623
    assert_eq!(
3624
        clone.submodule_update(true, &[]).unwrap(),
3625
        vec![("libs/lib".to_string(), SubrepoSync::Updated)]
3626
    );
3627
    assert_eq!(
3628
        fs::read(clone_dir.join("libs/lib/lib.txt")).unwrap(),
3629
        b"v2\n"
3630
    );
3631
    assert!(!clone.snapshot("status").unwrap().changed);
3632
    // Removing the subrepo leaves the directory and drops the node.
3633
    clone.submodule_remove("libs/lib").unwrap();
3634
    let snap = clone.snapshot("status").unwrap();
3635
    assert!(
3636
        snap.statuses
3637
            .iter()
3638
            .any(|s| s.path == "libs/lib" && s.status == ChangeStatus::Removed),
3639
        "{:?}",
3640
        snap.statuses
3641
    );
3642
    let c = clone.commit("drop lib", &[]).unwrap();
3643
    assert!(!clone
3644
        .load_state(&[c])
3645
        .unwrap()
3646
        .materialize()
3647
        .files
3648
        .contains_key("libs/lib"));
3649
    assert!(clone_dir.join("libs/lib/lib.txt").exists());
3650
    assert!(
3651
        !clone.snapshot("status").unwrap().changed,
3652
        "an unregistered nested repository is ignored"
3653
    );
3654
}
3655
3656
#[test]
3657
fn git_submodules_import_and_export_as_gitlinks() {
3658
    hermetic();
3659
    if std::process::Command::new("git")
3660
        .arg("--version")
3661
        .output()
3662
        .is_err()
3663
    {
3664
        eprintln!("git not installed; skipping");
3665
        return;
3666
    }
3667
    let dir = tempfile::tempdir().unwrap();
3668
    let root = dir.path();
3669
    let git_in = |d: &Path, args: &[&str]| -> String {
3670
        let out = std::process::Command::new("git")
3671
            .arg("-C")
3672
            .arg(d)
3673
            .args([
3674
                "-c",
3675
                "user.name=Grace",
3676
                "-c",
3677
                "[email protected]",
3678
                "-c",
3679
                "commit.gpgsign=false",
3680
                "-c",
3681
                "protocol.file.allow=always",
3682
            ])
3683
            .args(args)
3684
            .output()
3685
            .unwrap();
3686
        assert!(
3687
            out.status.success(),
3688
            "git {args:?}: {}",
3689
            String::from_utf8_lossy(&out.stderr)
3690
        );
3691
        String::from_utf8_lossy(&out.stdout).trim().to_string()
3692
    };
3693
    let sub = root.join("sub");
3694
    fs::create_dir_all(&sub).unwrap();
3695
    git_in(&sub, &["init", "-q", "-b", "main"]);
3696
    write(&sub, "s.txt", b"sub\n");
3697
    git_in(&sub, &["add", "."]);
3698
    git_in(&sub, &["commit", "-q", "-m", "sub initial"]);
3699
    let sub_sha = git_in(&sub, &["rev-parse", "HEAD"]);
3700
    let g = root.join("main.git");
3701
    fs::create_dir_all(&g).unwrap();
3702
    git_in(&g, &["init", "-q", "-b", "main"]);
3703
    write(&g, "README.md", b"# app\n");
3704
    git_in(&g, &["add", "."]);
3705
    git_in(&g, &["commit", "-q", "-m", "initial"]);
3706
    git_in(
3707
        &g,
3708
        &[
3709
            "submodule",
3710
            "add",
3711
            "-q",
3712
            sub.to_str().unwrap(),
3713
            "vendor/sub",
3714
        ],
3715
    );
3716
    git_in(&g, &["commit", "-q", "-m", "add submodule"]);
3717
3718
    let dest = root.join("oxy");
3719
    let repo = Repo::init(&dest).unwrap().with_home(root.join("home"));
3720
    let rep = repo.import_git(&g, "main").unwrap();
3721
    assert_eq!((rep.commits, rep.submodules), (2, 1));
3722
    let files = repo
3723
        .load_state(&repo.bookmark_heads().unwrap())
3724
        .unwrap()
3725
        .materialize()
3726
        .files;
3727
    assert_eq!(files["vendor/sub"].kind, NodeKind::Subrepo);
3728
    let FileContent::Opaque { blobs } = &files["vendor/sub"].content else {
3729
        panic!()
3730
    };
3731
    assert_eq!(
3732
        crate::subrepo::Pin::decode(&repo.read_blob(&blobs[0]).unwrap()).unwrap(),
3733
        crate::subrepo::Pin::Git {
3734
            sha: sub_sha.clone(),
3735
            branch: "HEAD".into()
3736
        }
3737
    );
3738
    let modules =
3739
        crate::subrepo::Modules::parse(&fs::read_to_string(dest.join(".oxymodules")).unwrap());
3740
    assert_eq!(modules.entries["vendor/sub"].url, sub.to_string_lossy());
3741
    assert!(modules.entries["vendor/sub"].git);
3742
    assert!(
3743
        files.contains_key(".gitmodules"),
3744
        "the Git file is kept for round trips"
3745
    );
3746
    assert!(
3747
        !dest.join("vendor/sub/.git").exists(),
3748
        "not cloned until update --init"
3749
    );
3750
    assert!(!repo.snapshot("status").unwrap().changed);
3751
    // update --init clones it at the pinned commit; status is unchanged.
3752
    assert_eq!(
3753
        repo.submodule_update(true, &[]).unwrap(),
3754
        vec![("vendor/sub".to_string(), SubrepoSync::Updated)]
3755
    );
3756
    assert_eq!(
3757
        git_in(&dest.join("vendor/sub"), &["rev-parse", "HEAD"]),
3758
        sub_sha
3759
    );
3760
    assert!(!repo.snapshot("status").unwrap().changed);
3761
    // Export writes the gitlink and .gitmodules back.
3762
    let mirror = root.join("mirror.git");
3763
    let rep = repo.git_export(&mirror).unwrap();
3764
    assert_eq!(rep.skipped_subrepos, 0);
3765
    let ls = git_in(&mirror, &["ls-tree", "main", "vendor/sub"]);
3766
    assert!(
3767
        ls.starts_with("160000 commit ") && ls.contains(&sub_sha),
3768
        "{ls}"
3769
    );
3770
    assert_eq!(
3771
        git_in(&mirror, &["ls-tree", "--name-only", "main"]),
3772
        ".gitmodules\nREADME.md\nvendor"
3773
    );
3774
    let orig_tree = git_in(&g, &["rev-parse", "main^{tree}"]);
3775
    assert_eq!(
3776
        git_in(&mirror, &["rev-parse", "main^{tree}"]),
3777
        orig_tree,
3778
        "tree round trip"
3779
    );
3780
}
3781
3782
#[test]
3783
fn partial_commits_by_path_and_by_hunk() {
3784
    hermetic();
3785
    let dir = tempfile::tempdir().unwrap();
3786
    let root = dir.path();
3787
    let repo = Repo::init(root).unwrap().with_home(root.join("home"));
3788
    write(root, "a.txt", b"1\n2\n3\n");
3789
    write(root, "b.txt", b"b\n");
3790
    let h0 = repo.commit("base", &[]).unwrap();
3791
    write(root, "a.txt", b"0\n1\n2\n3\n4\n");
3792
    write(root, "b.txt", b"b\nbb\n");
3793
    write(root, "c.txt", b"c\n");
3794
    // By path: only a.txt goes in; the rest stays on disk as uncommitted work.
3795
    let h1 = repo
3796
        .commit_selection("a only", &[], &Selection::Paths(vec!["a.txt".into()]))
3797
        .unwrap();
3798
    let c1 = repo.store().get_change(&h1).unwrap();
3799
    assert!(
3800
        c1.tree_ops.is_empty() && c1.edits.iter().all(|e| e.node() == c1.edits[0].node()),
3801
        "{:?}",
3802
        c1.tree_ops
3803
    );
3804
    assert_eq!(c1.deps, vec![h0]);
3805
    let files = repo.load_state(&[h1]).unwrap().materialize().files;
3806
    assert!(
3807
        matches!(&files["a.txt"].content, FileContent::Text { bytes, .. } if bytes == b"0\n1\n2\n3\n4\n")
3808
    );
3809
    assert!(matches!(&files["b.txt"].content, FileContent::Text { bytes, .. } if bytes == b"b\n"));
3810
    assert!(!files.contains_key("c.txt"));
3811
    let snap = repo.snapshot("status").unwrap();
3812
    assert_eq!(
3813
        snap.statuses
3814
            .iter()
3815
            .map(|s| (s.path.as_str(), s.status))
3816
            .collect::<Vec<_>>(),
3817
        vec![
3818
            ("b.txt", ChangeStatus::Modified),
3819
            ("c.txt", ChangeStatus::Added)
3820
        ]
3821
    );
3822
    assert_eq!(
3823
        fs::read(root.join("b.txt")).unwrap(),
3824
        b"b\nbb\n",
3825
        "disk untouched"
3826
    );
3827
    // By hunk: pick the b.txt insert; c.txt's addition is left.
3828
    let (_, hunks) = repo.hunks().unwrap();
3829
    let b_hunk = hunks
3830
        .iter()
3831
        .find(|h| h.path == "b.txt" && h.text.contains("+bb"))
3832
        .unwrap()
3833
        .index;
3834
    let h2 = repo
3835
        .commit_selection("b only", &[], &Selection::Hunks(vec![b_hunk]))
3836
        .unwrap();
3837
    let files = repo.load_state(&[h2]).unwrap().materialize().files;
3838
    assert!(
3839
        matches!(&files["b.txt"].content, FileContent::Text { bytes, .. } if bytes == b"b\nbb\n")
3840
    );
3841
    assert!(!files.contains_key("c.txt"));
3842
    let snap = repo.snapshot("status").unwrap();
3843
    assert_eq!(
3844
        snap.statuses
3845
            .iter()
3846
            .map(|s| s.path.as_str())
3847
            .collect::<Vec<_>>(),
3848
        vec!["c.txt"]
3849
    );
3850
    // Choosing only the content hunk of a file in a new directory pulls in
3851
    // the directory and file additions it needs.
3852
    write(root, "d/e.txt", b"e\n");
3853
    let (_, hunks) = repo.hunks().unwrap();
3854
    let e_insert = hunks
3855
        .iter()
3856
        .find(|h| h.path == "d/e.txt" && h.text.contains("+e"))
3857
        .unwrap()
3858
        .index;
3859
    let h3 = repo
3860
        .commit_selection("e only", &[], &Selection::Hunks(vec![e_insert]))
3861
        .unwrap();
3862
    let c3 = repo.store().get_change(&h3).unwrap();
3863
    assert_eq!(c3.tree_ops.len(), 2, "{:?}", c3.tree_ops);
3864
    let files = repo.load_state(&[h3]).unwrap().materialize().files;
3865
    assert!(files.contains_key("d/e.txt") && !files.contains_key("c.txt"));
3866
    // Choosing a new file's addition hunk brings its content along.
3867
    write(root, "f/g.txt", b"g\n");
3868
    let (_, hunks) = repo.hunks().unwrap();
3869
    let g_add = hunks
3870
        .iter()
3871
        .find(|h| h.path == "f/g.txt" && h.text.starts_with("A "))
3872
        .unwrap()
3873
        .index;
3874
    let h4 = repo
3875
        .commit_selection("g by addition", &[], &Selection::Hunks(vec![g_add]))
3876
        .unwrap();
3877
    let files = repo.load_state(&[h4]).unwrap().materialize().files;
3878
    assert!(
3879
        matches!(&files["f/g.txt"].content, FileContent::Text { bytes, .. } if bytes == b"g\n")
3880
    );
3881
    assert!(!repo
3882
        .snapshot("status")
3883
        .unwrap()
3884
        .statuses
3885
        .iter()
3886
        .any(|s| s.path == "f/g.txt"));
3887
    // Everything left commits normally; the working copy is then clean.
3888
    repo.commit("the rest", &[]).unwrap();
3889
    assert!(!repo.snapshot("status").unwrap().changed);
3890
    let files = repo
3891
        .load_state(&repo.bookmark_heads().unwrap())
3892
        .unwrap()
3893
        .materialize()
3894
        .files;
3895
    assert!(files.contains_key("c.txt"));
3896
}
3897
3898
#[test]
3899
fn blame_attributes_lines_to_introducing_changes_across_renames() {
3900
    hermetic();
3901
    let dir = tempfile::tempdir().unwrap();
3902
    let root = dir.path();
3903
    let mut repo = Repo::init(root).unwrap().with_home(root.join("home"));
3904
    repo.create_identity("Ada", "[email protected]", IdentityScope::User)
3905
        .unwrap();
3906
    write(root, "a.txt", b"one\n");
3907
    let h1 = repo.commit("first", &[]).unwrap();
3908
    write(root, "a.txt", b"one\ntwo\n");
3909
    let h2 = repo.commit("second", &[]).unwrap();
3910
    let b = repo.blame("a.txt").unwrap();
3911
    assert_eq!(
3912
        b.iter()
3913
            .map(|l| (l.line, l.hash, l.text.as_slice()))
3914
            .collect::<Vec<_>>(),
3915
        vec![(1, h1, b"one\n".as_slice()), (2, h2, b"two\n".as_slice())]
3916
    );
3917
    assert!(b.iter().all(|l| l.author == "Ada"));
3918
    assert_eq!(
3919
        b[0].change_id,
3920
        repo.store().get_change(&h1).unwrap().change_id
3921
    );
3922
    fs::rename(root.join("a.txt"), root.join("b.txt")).unwrap();
3923
    repo.commit("rename", &[]).unwrap();
3924
    let b = repo.blame("b.txt").unwrap();
3925
    assert_eq!(
3926
        b.iter().map(|l| l.hash).collect::<Vec<_>>(),
3927
        vec![h1, h2],
3928
        "the node survives the rename"
3929
    );
3930
    assert!(repo.blame("a.txt").is_err());
3931
}
3932
3933
#[test]
3934
fn bisect_finds_the_first_bad_change() {
3935
    hermetic();
3936
    let dir = tempfile::tempdir().unwrap();
3937
    let root = dir.path();
3938
    let repo = Repo::init(root).unwrap().with_home(root.join("home"));
3939
    let mut content = String::new();
3940
    let mut hashes = Vec::new();
3941
    for i in 1..=8 {
3942
        content.push_str(&format!("line {i}{}\n", if i == 5 { " bug" } else { "" }));
3943
        write(root, "f.txt", content.as_bytes());
3944
        hashes.push(repo.commit(&format!("step {i}"), &[]).unwrap());
3945
    }
3946
    // Each step appends after the previous line, so the chain is linear.
3947
    assert_eq!(repo.bookmark_heads().unwrap(), vec![hashes[7]]);
3948
    repo.bisect_start().unwrap();
3949
    assert!(matches!(
3950
        repo.bisect_mark(Some(true), &[hashes[0]]).unwrap(),
3951
        BisectStep::NeedMarks { good: 1, bad: 0 }
3952
    ));
3953
    let step = repo.bisect_mark(Some(false), &[hashes[7]]).unwrap();
3954
    assert!(
3955
        matches!(step, BisectStep::Testing { remaining: 7, .. }),
3956
        "{step:?}"
3957
    );
3958
    // Automated: bad when the bug line is present.
3959
    let step = repo
3960
        .bisect_run(&["sh".into(), "-c".into(), "! grep -q bug f.txt".into()])
3961
        .unwrap();
3962
    assert_eq!(step, BisectStep::Found { culprit: hashes[4] });
3963
    assert_eq!(
3964
        repo.bisect_status().unwrap(),
3965
        Some(BisectStep::Found { culprit: hashes[4] })
3966
    );
3967
    repo.bisect_reset().unwrap();
3968
    assert_eq!(fs::read_to_string(root.join("f.txt")).unwrap(), content);
3969
    assert!(repo.bisect_status().unwrap().is_none());
3970
    assert!(!repo.snapshot("status").unwrap().changed);
3971
    // Manual marks and a skip.
3972
    repo.bisect_start().unwrap();
3973
    repo.bisect_mark(Some(true), &[hashes[0]]).unwrap();
3974
    let mut step = repo.bisect_mark(Some(false), &[hashes[7]]).unwrap();
3975
    let mut skipped_once = false;
3976
    let mut guard = 0;
3977
    while let BisectStep::Testing { .. } = step {
3978
        guard += 1;
3979
        assert!(guard < 20);
3980
        let text = fs::read_to_string(root.join("f.txt")).unwrap();
3981
        if !skipped_once && text.contains("line 6") {
3982
            // An untestable state away from the boundary: the search routes around it.
3983
            skipped_once = true;
3984
            step = repo.bisect_mark(None, &[]).unwrap();
3985
            continue;
3986
        }
3987
        step = repo.bisect_mark(Some(!text.contains("bug")), &[]).unwrap();
3988
    }
3989
    assert!(skipped_once);
3990
    assert_eq!(step, BisectStep::Found { culprit: hashes[4] });
3991
    repo.bisect_reset().unwrap();
3992
    // Skipping the culprit itself leaves it among the candidates reported.
3993
    repo.bisect_start().unwrap();
3994
    repo.bisect_mark(Some(true), &[hashes[0]]).unwrap();
3995
    let mut step = repo.bisect_mark(Some(false), &[hashes[7]]).unwrap();
3996
    let mut guard = 0;
3997
    while let BisectStep::Testing { heads, .. } = &step {
3998
        guard += 1;
3999
        assert!(guard < 20);
4000
        let text = fs::read_to_string(root.join("f.txt")).unwrap();
4001
        let is_culprit_state =
4002
            heads.contains(&hashes[4]) && !heads.iter().any(|h| hashes[5..].contains(h));
4003
        step = if is_culprit_state {
4004
            repo.bisect_mark(None, &[]).unwrap()
4005
        } else {
4006
            repo.bisect_mark(Some(!text.contains("bug")), &[]).unwrap()
4007
        };
4008
    }
4009
    match step {
4010
        BisectStep::Inconclusive { candidates } => assert!(
4011
            candidates.contains(&hashes[4]) && candidates.len() <= 2,
4012
            "{candidates:?}"
4013
        ),
4014
        other => panic!("{other:?}"),
4015
    }
4016
    repo.bisect_reset().unwrap();
4017
}
4018
4019
#[test]
4020
fn squash_folds_a_change_into_its_dependency() {
4021
    hermetic();
4022
    let dir = tempfile::tempdir().unwrap();
4023
    let root = dir.path();
4024
    let repo = Repo::init(root).unwrap().with_home(root.join("home"));
4025
    write(root, "a.txt", b"1\n");
4026
    let a = repo.commit("A", &[]).unwrap();
4027
    write(root, "a.txt", b"1\n2\n");
4028
    let c = repo.commit("C", &[]).unwrap();
4029
    write(root, "a.txt", b"1\n2\n3\n");
4030
    let e = repo.commit("E", &[]).unwrap();
4031
    write(root, "b.txt", b"b\n");
4032
    let b = repo.commit("B", &[]).unwrap();
4033
    let id_a = repo.store().get_change(&a).unwrap().change_id;
4034
    let id_e = repo.store().get_change(&e).unwrap().change_id;
4035
    // E depends on C which A lacks: refused, naming it.
4036
    let err = repo.squash(&e, &a).unwrap_err().to_string();
4037
    assert!(err.contains(&c.short(12)), "{err}");
4038
    // C into A: A' has both, C is gone, E follows and still reads the same.
4039
    let a2 = repo.squash(&c, &a).unwrap();
4040
    let a2c = repo.store().get_change(&a2).unwrap();
4041
    assert_eq!(a2c.change_id, id_a);
4042
    assert!(a2c.deps.is_empty());
4043
    let heads = repo.bookmark_heads().unwrap();
4044
    let st = repo.load_state(&heads).unwrap();
4045
    assert!(!st.contains(&c) && !st.contains(&a) && !st.contains(&e));
4046
    let e2 = st
4047
        .changes()
4048
        .find(|(_, m)| m.change_id == id_e)
4049
        .map(|(h, _)| *h)
4050
        .unwrap();
4051
    assert_eq!(
4052
        repo.store().get_change(&e2).unwrap().deps,
4053
        vec![a2],
4054
        "E now depends on A' alone"
4055
    );
4056
    let files = st.materialize().files;
4057
    assert!(
4058
        matches!(&files["a.txt"].content, FileContent::Text { bytes, .. } if bytes == b"1\n2\n3\n")
4059
    );
4060
    assert!(files.contains_key("b.txt"));
4061
    assert!(st.contains(&b));
4062
    assert!(!repo.snapshot("status").unwrap().changed);
4063
    assert_eq!(repo.log().unwrap().len(), 4, "working copy, B, E', A'");
4064
    // Undo restores the three original changes.
4065
    repo.undo().unwrap();
4066
    repo.undo().unwrap();
4067
    let st = repo.load_state(&repo.bookmark_heads().unwrap()).unwrap();
4068
    assert!(st.contains(&c) && st.contains(&a) && st.contains(&e));
4069
}
4070
4071
#[test]
4072
fn rebase_re_expresses_a_change_against_another_base() {
4073
    hermetic();
4074
    let dir = tempfile::tempdir().unwrap();
4075
    let root = dir.path();
4076
    let repo = Repo::init(root).unwrap().with_home(root.join("home"));
4077
    write(root, "a.txt", b"1\n2\n");
4078
    let a = repo.commit("A", &[]).unwrap();
4079
    write(root, "a.txt", b"1\n2\n3\n");
4080
    let c = repo.commit("C: append 3", &[]).unwrap();
4081
    write(root, "a.txt", b"1\n2\n3\n4\n");
4082
    let e = repo.commit("E: append 4", &[]).unwrap();
4083
    // A different base: A plus a change that prepends a line.
4084
    repo.checkout(&[a], true, "checkout").unwrap();
4085
    write(root, "a.txt", b"0\n1\n2\n");
4086
    let d = repo.commit("D: prepend 0", &[]).unwrap();
4087
    let id_c = repo.store().get_change(&c).unwrap().change_id;
4088
    let id_e = repo.store().get_change(&e).unwrap().change_id;
4089
    // Rebase C onto D: its effect (append 3) re-derived against D's text.
4090
    let c2 = repo.rebase(&c, &[d]).unwrap();
4091
    let c2c = repo.store().get_change(&c2).unwrap();
4092
    assert_eq!(c2c.change_id, id_c);
4093
    assert!(c2c.deps.contains(&d), "{:?}", c2c.deps);
4094
    let heads = repo.bookmark_heads().unwrap();
4095
    let st = repo.load_state(&heads).unwrap();
4096
    assert!(!st.contains(&c) && st.contains(&d));
4097
    let e2 = st
4098
        .changes()
4099
        .find(|(_, m)| m.change_id == id_e)
4100
        .map(|(h, _)| *h)
4101
        .unwrap();
4102
    let e2deps = repo.store().get_change(&e2).unwrap().deps;
4103
    assert!(
4104
        e2deps.contains(&c2) && !e2deps.contains(&c) && e2deps.contains(&a),
4105
        "E follows C by content and still depends on A, which introduced the file: {e2deps:?}"
4106
    );
4107
    let files = st.materialize().files;
4108
    assert!(
4109
        matches!(&files["a.txt"].content, FileContent::Text { bytes, .. } if bytes == b"0\n1\n2\n3\n4\n"),
4110
        "{:?}",
4111
        files["a.txt"].content
4112
    );
4113
    assert!(!files["a.txt"].is_conflicted());
4114
    // Rebasing onto a state that already contains the change is refused.
4115
    assert!(repo.rebase(&c2, &[c2]).is_err());
4116
    let err = repo.rebase(&e2, &[d]).unwrap_err().to_string();
4117
    assert!(
4118
        err.contains("lacks dependencies"),
4119
        "E needs C, which D's state does not have: {err}"
4120
    );
4121
}
4122
4123
#[test]
4124
fn unsigned_tags_keep_their_message() {
4125
    hermetic();
4126
    let dir = tempfile::tempdir().unwrap();
4127
    let root = dir.path();
4128
    let repo = Repo::init(root).unwrap().with_home(root.join("home"));
4129
    write(root, "a.txt", b"a\n");
4130
    repo.commit("a", &[]).unwrap();
4131
    assert!(repo.secret_key().unwrap().is_none());
4132
    repo.tag_create("v1", &repo.bookmark_heads().unwrap(), "first release")
4133
        .unwrap();
4134
    let tags = repo.tags().unwrap();
4135
    assert_eq!(
4136
        (
4137
            tags[0].name.as_str(),
4138
            tags[0].message.as_str(),
4139
            tags[0].signer.as_deref()
4140
        ),
4141
        ("v1", "first release", None)
4142
    );
4143
    assert!(
4144
        repo.tag_refs().unwrap()[0].attestation.is_none(),
4145
        "an unsigned attestation is not advertised"
4146
    );
4147
}
4148
4149
#[test]
4150
fn fsck_passes_a_sound_repository_and_names_each_fault() {
4151
    // Files on disk are what this tests: tampering with them, and the
4152
    // directory store's crash points.
4153
    if std::env::var_os("OXY_STORE_BACKEND").is_some() {
4154
        return;
4155
    }
4156
    hermetic();
4157
    let dir = tempfile::tempdir().unwrap();
4158
    let root = dir.path();
4159
    let origin_path = root.join("origin");
4160
    let origin = Repo::init(&origin_path).unwrap();
4161
    let mut a = Repo::clone(&origin_path.to_string_lossy(), &root.join("a"))
4162
        .unwrap()
4163
        .with_home(root.join("home-a"));
4164
    a.create_identity("Ada", "[email protected]", IdentityScope::Repo)
4165
        .unwrap();
4166
    write(&root.join("a"), "f.txt", b"one\n");
4167
    write(&root.join("a"), "bin.dat", b"\0\x01\x02binary");
4168
    let h1 = a.commit("first", &[]).unwrap();
4169
    write(&root.join("a"), "f.txt", b"one\ntwo\n");
4170
    let h2 = a.commit("second", &[]).unwrap();
4171
    a.tag_create("v1", &[h2], "first release").unwrap();
4172
    a.checkpoint().unwrap();
4173
    assert!(a.push("origin", false).unwrap()[0].ok);
4174
4175
    // Sound: signed changes, a seal, a tag, a checkpoint, a ref attestation.
4176
    for repo in [&a, &origin] {
4177
        let rep = repo.fsck().unwrap();
4178
        assert_eq!(rep.problems, vec![], "{rep:?}");
4179
        // The two commits, plus the working copy's change in `a`.
4180
        assert!(rep.changes >= 2 && rep.signed >= 2, "{rep:?}");
4181
        assert!(rep.ops > 1 && rep.objects > 5);
4182
    }
4183
    assert!(origin.fsck().unwrap().attestations >= 1);
4184
4185
    // A flipped byte in a stored object is corruption, named by hash.
4186
    let c1 = a.store().path_for(&h1);
4187
    let pristine = fs::read(&c1).unwrap();
4188
    let mut bytes = pristine.clone();
4189
    *bytes.last_mut().unwrap() ^= 1;
4190
    fs::write(&c1, &bytes).unwrap();
4191
    let rep = a.fsck().unwrap();
4192
    assert!(rep.errors() >= 1);
4193
    assert!(
4194
        rep.problems
4195
            .iter()
4196
            .any(|p| p.object == Some(h1) && p.what.contains("unreadable")),
4197
        "{rep:?}"
4198
    );
4199
    fs::write(&c1, &pristine).unwrap();
4200
    assert_eq!(a.fsck().unwrap().errors(), 0);
4201
4202
    // A missing change is named with what needed it.
4203
    fs::remove_file(&c1).unwrap();
4204
    let rep = a.fsck().unwrap();
4205
    assert!(
4206
        rep.problems.iter().any(|p| p.severity == Severity::Error
4207
            && p.object == Some(h1)
4208
            && p.what.contains("change missing, needed by change")),
4209
        "{rep:?}"
4210
    );
4211
    fs::write(&c1, &pristine).unwrap();
4212
4213
    // A missing blob is an error in a full clone.
4214
    let c2 = a.store().get_change(&h1).unwrap();
4215
    let blob = c2
4216
        .edits
4217
        .iter()
4218
        .find_map(|e| match e {
4219
            Edit::Replace { new: Some(b), .. } => Some(*b),
4220
            _ => None,
4221
        })
4222
        .expect("the binary file is a blob");
4223
    let bp = a.store().path_for(&blob);
4224
    let blob_bytes = fs::read(&bp).unwrap();
4225
    fs::remove_file(&bp).unwrap();
4226
    let rep = a.fsck().unwrap();
4227
    assert!(
4228
        rep.problems
4229
            .iter()
4230
            .any(|p| p.object == Some(blob) && p.what.contains("blob missing")),
4231
        "{rep:?}"
4232
    );
4233
    fs::write(&bp, &blob_bytes).unwrap();
4234
4235
    // A broken op log head is reported, not a crash.
4236
    let head = root.join("a/.oxy/ops/head");
4237
    let saved = fs::read(&head).unwrap();
4238
    fs::write(&head, b"not a hash").unwrap();
4239
    let rep = a.fsck().unwrap();
4240
    assert!(
4241
        rep.problems.iter().any(|p| p.what.contains("ops/head")),
4242
        "{rep:?}"
4243
    );
4244
    fs::write(&head, saved).unwrap();
4245
    assert_eq!(a.fsck().unwrap().problems, vec![]);
4246
}
4247
4248
/// Copy a directory tree (for restoring a pristine repository).
4249
fn copy_tree(from: &Path, to: &Path) {
4250
    fs::create_dir_all(to).unwrap();
4251
    for e in fs::read_dir(from).unwrap() {
4252
        let e = e.unwrap();
4253
        let target = to.join(e.file_name());
4254
        if e.file_type().unwrap().is_dir() {
4255
            copy_tree(&e.path(), &target);
4256
        } else {
4257
            fs::copy(e.path(), &target).unwrap();
4258
        }
4259
    }
4260
}
4261
4262
/// Spec §13.6: stop `commit` and `push` at every durable step, as a crash
4263
/// would, and check that both repositories still open, pass `fsck`, and
4264
/// accept the same operation again.
4265
#[test]
4266
fn crash_at_every_step_of_commit_and_push_leaves_sound_repositories() {
4267
    // Files on disk are what this tests: tampering with them, and the
4268
    // directory store's crash points.
4269
    if std::env::var_os("OXY_STORE_BACKEND").is_some() {
4270
        return;
4271
    }
4272
    use crate::durable::failpoint;
4273
    hermetic();
4274
    let dir = tempfile::tempdir().unwrap();
4275
    let pristine = dir.path().join("pristine");
4276
    let origin_path = pristine.join("origin");
4277
    Repo::init(&origin_path).unwrap();
4278
    let mut a = Repo::clone(&origin_path.to_string_lossy(), &pristine.join("a"))
4279
        .unwrap()
4280
        .with_home(dir.path().join("home"));
4281
    a.create_identity("Ada", "[email protected]", IdentityScope::Repo)
4282
        .unwrap();
4283
    write(&pristine.join("a"), "f.txt", b"one\n");
4284
    a.commit("first", &[]).unwrap();
4285
    assert!(a.push("origin", false).unwrap()[0].ok);
4286
    drop(a);
4287
4288
    type Op = fn(&Repo) -> Result<()>;
4289
    let edit_and_commit: Op = |r| {
4290
        write(r.root(), "f.txt", b"one\ntwo\n");
4291
        write(r.root(), "big.bin", &vec![7u8; 300_000]);
4292
        r.commit("second", &[]).map(|_| ())
4293
    };
4294
    let push: Op = |r| {
4295
        let res = r.push("origin", false)?;
4296
        if res.iter().all(|x| x.ok) {
4297
            Ok(())
4298
        } else {
4299
            Err(RepoError::Msg(format!("{res:?}")))
4300
        }
4301
    };
4302
4303
    for (name, prepare, op) in [
4304
        ("commit", None, edit_and_commit),
4305
        ("push", Some(edit_and_commit), push),
4306
    ] {
4307
        let mut steps = 0;
4308
        for n in 1.. {
4309
            let run = dir.path().join(format!("{name}-{n}"));
4310
            copy_tree(&pristine, &run);
4311
            // Clones record their remote by path; point it at this copy.
4312
            let open = |p: &Path| {
4313
                let mut r = Repo::open(p).unwrap().with_home(dir.path().join("home"));
4314
                r.config
4315
                    .set("remote.origin.url", &run.join("origin").to_string_lossy())
4316
                    .unwrap();
4317
                r.save_config().unwrap();
4318
                r
4319
            };
4320
            let a = open(&run.join("a"));
4321
            if let Some(prep) = prepare {
4322
                prep(&a).unwrap();
4323
            }
4324
            failpoint::crash_after(n);
4325
            let outcome = op(&a);
4326
            let crashed = failpoint::disarm();
4327
            drop(a);
4328
            if !crashed {
4329
                outcome.unwrap_or_else(|e| panic!("{name} failed without a crash: {e}"));
4330
                steps = n - 1;
4331
                break;
4332
            }
4333
            assert!(
4334
                outcome.is_err(),
4335
                "{name}: a crash at step {n} was swallowed"
4336
            );
4337
            for repo in ["a", "origin"] {
4338
                let r = Repo::open(&run.join(repo)).unwrap_or_else(|e| {
4339
                    panic!("{name} crash at step {n}: {repo} no longer opens: {e}")
4340
                });
4341
                let rep = r.fsck().unwrap();
4342
                assert_eq!(
4343
                    rep.errors(),
4344
                    0,
4345
                    "{name} crash at step {n}: {repo} fails fsck: {:?}",
4346
                    rep.problems
4347
                );
4348
            }
4349
            // The interrupted operation can simply be run again.
4350
            let a = open(&run.join("a"));
4351
            // A crash after the commit point leaves the commit done.
4352
            let landed = a
4353
                .bookmark_heads()
4354
                .unwrap()
4355
                .iter()
4356
                .any(|h| a.store().get_change(h).unwrap().message == "second");
4357
            let again = match (name, landed) {
4358
                ("commit", true) => Ok(()),
4359
                ("commit", false) => a.commit("second", &[]).map(|_| ()),
4360
                _ => op(&a),
4361
            };
4362
            again.unwrap_or_else(|e| panic!("{name} crash at step {n}: retry failed: {e}"));
4363
            assert_eq!(a.fsck().unwrap().errors(), 0);
4364
            fs::remove_dir_all(&run).unwrap();
4365
        }
4366
        assert!(steps >= 3, "{name} has only {steps} durable steps?");
4367
    }
4368
}
4369
4370
/// Spec §12.1: commands in two workspaces of one repository, and pushes,
4371
/// running at the same time lose nothing: every commit ends up on the
4372
/// bookmark, locally and on the remote, and the repository passes fsck.
4373
#[test]
4374
fn concurrent_commits_in_two_workspaces_lose_nothing() {
4375
    hermetic();
4376
    let dir = tempfile::tempdir().unwrap();
4377
    let root = dir.path();
4378
    let origin = root.join("origin");
4379
    Repo::init_bare_unbound(&origin).unwrap();
4380
    let main = root.join("main");
4381
    let mut repo = Repo::init(&main).unwrap();
4382
    repo.config
4383
        .set("remote.origin.url", &origin.to_string_lossy())
4384
        .unwrap();
4385
    repo.save_config().unwrap();
4386
    write(&main, "seed.txt", b"seed\n");
4387
    repo.commit("seed", &[]).unwrap();
4388
    let second = root.join("second");
4389
    repo.workspace_add(&second, None).unwrap();
4390
    drop(repo);
4391
4392
    const EACH: usize = 15;
4393
    std::thread::scope(|s| {
4394
        for (tag, dir, push) in [("a", main.clone(), true), ("b", second.clone(), false)] {
4395
            s.spawn(move || {
4396
                let r = Repo::open(&dir).unwrap();
4397
                for i in 0..EACH {
4398
                    write(
4399
                        &dir,
4400
                        &format!("{tag}-{i}.txt"),
4401
                        format!("{tag} {i}\n").as_bytes(),
4402
                    );
4403
                    r.commit(&format!("{tag} {i}"), &[]).unwrap();
4404
                    if push && i % 5 == 4 {
4405
                        // A push may be refused while the other workspace moves the bookmark; nothing may be lost either way.
4406
                        let _ = r.push("origin", false);
4407
                    }
4408
                }
4409
            });
4410
        }
4411
    });
4412
4413
    let repo = Repo::open(&main).unwrap();
4414
    let heads = repo.bookmark_heads().unwrap();
4415
    let state = repo.load_state(&heads).unwrap();
4416
    let messages: BTreeSet<String> = state.changes().map(|(_, m)| m.message.clone()).collect();
4417
    for tag in ["a", "b"] {
4418
        for i in 0..EACH {
4419
            assert!(
4420
                messages.contains(&format!("{tag} {i}")),
4421
                "lost commit {tag} {i}; have {messages:?}"
4422
            );
4423
        }
4424
    }
4425
    let rep = repo.fsck().unwrap();
4426
    assert_eq!(rep.errors(), 0, "{:?}", rep.problems);
4427
    assert!(repo.push("origin", false).unwrap().iter().all(|r| r.ok));
4428
    let hosted = Repo::open(&origin).unwrap();
4429
    let hosted_heads = hosted.bookmark_heads().unwrap();
4430
    assert_eq!(
4431
        hosted.load_state(&hosted_heads).unwrap().len(),
4432
        state.len(),
4433
        "the remote has every commit"
4434
    );
4435
}
4436
4437
/// Two operations recorded from the same parent (what two processes do
4438
/// when they race) are merged: both bookmarks' heads survive, and a
4439
/// change made on one side only is kept.
4440
#[test]
4441
fn operations_from_the_same_parent_are_merged() {
4442
    hermetic();
4443
    let dir = tempfile::tempdir().unwrap();
4444
    let root = dir.path();
4445
    let repo = Repo::init(root).unwrap();
4446
    write(root, "a.txt", b"a\n");
4447
    let a = repo.commit("a", &[]).unwrap();
4448
    write(root, "b.txt", b"b\n");
4449
    let b = repo.commit("b", &[]).unwrap();
4450
    let (x, op) = repo.head_op().unwrap();
4451
    let state = |heads: Vec<ChangeHash>| repo.store().put_state(&StateObject::new(heads)).unwrap();
4452
4453
    // Side one moves main to just `a` and adds a bookmark; side two moves main to just `b`.
4454
    let mut one = op.view.clone();
4455
    one.bookmarks.insert("main".into(), state(vec![a]));
4456
    one.bookmarks.insert("topic".into(), state(vec![a]));
4457
    let mut two = op.view.clone();
4458
    two.bookmarks.insert("main".into(), state(vec![b]));
4459
    repo.record_op(&[x], "one", one).unwrap();
4460
    let merged = repo.record_op(&[x], "two", two).unwrap();
4461
4462
    let (head, op) = repo.head_op().unwrap();
4463
    assert_eq!(head, merged);
4464
    assert_eq!(op.parents.len(), 2, "a merge of the two operations");
4465
    assert!(op.command.contains("merged with a concurrent operation"));
4466
    let mut main = repo
4467
        .store()
4468
        .get_state(&op.view.bookmarks["main"])
4469
        .unwrap()
4470
        .heads;
4471
    main.sort();
4472
    let mut want = vec![a, b];
4473
    want.sort();
4474
    assert_eq!(main, want, "both sides' heads are kept");
4475
    assert!(
4476
        op.view.bookmarks.contains_key("topic"),
4477
        "a one-sided change survives"
4478
    );
4479
    assert_eq!(repo.fsck().unwrap().errors(), 0);
4480
}
4481
4482
#[test]
4483
fn failed_requests_come_with_a_next_step() {
4484
    use crate::protocol::hint_for;
4485
    assert!(hint_for("https://h/x/oxy/v1/push: HTTP 401: bad token")
4486
        .unwrap()
4487
        .contains("token"));
4488
    assert!(hint_for("…: HTTP 403: forbidden")
4489
        .unwrap()
4490
        .contains("repo:write"));
4491
    assert!(hint_for("…: HTTP 404: no such repository")
4492
        .unwrap()
4493
        .contains("owner and repository name"));
4494
    assert!(hint_for("invalid peer certificate: UnknownIssuer")
4495
        .unwrap()
4496
        .contains("oxyhub-ca.pem"));
4497
    assert!(hint_for("Connect error: Connection refused (os error 111)")
4498
        .unwrap()
4499
        .contains("running"));
4500
    assert!(hint_for("Dns Failed: failed to lookup address information")
4501
        .unwrap()
4502
        .contains("resolve"));
4503
    assert_eq!(hint_for("something else entirely"), None);
4504
}
4505
4506
#[test]
4507
fn doctor_names_problems_and_what_to_do() {
4508
    hermetic();
4509
    let dir = tempfile::tempdir().unwrap();
4510
    let root = dir.path();
4511
    let origin = root.join("origin");
4512
    Repo::init_bare_unbound(&origin).unwrap();
4513
    let mut repo = Repo::init(&root.join("r"))
4514
        .unwrap()
4515
        .with_home(root.join("home"));
4516
    let find = |r: &DoctorReport, area: &str, h: Health| {
4517
        r.checks
4518
            .iter()
4519
            .find(|c| c.area == area && c.health == h)
4520
            .cloned()
4521
    };
4522
4523
    let r = repo.doctor(true);
4524
    assert!(find(&r, "identity", Health::Warn)
4525
        .unwrap()
4526
        .hint
4527
        .unwrap()
4528
        .contains("oxy identity create"));
4529
    assert!(find(&r, "repository", Health::Ok).is_some());
4530
4531
    repo.create_identity("Ada", "[email protected]", IdentityScope::Repo)
4532
        .unwrap();
4533
    repo.config.set("author.name", "Ada").unwrap();
4534
    repo.config.set("author.email", "[email protected]").unwrap();
4535
    repo.config
4536
        .set("remote.origin.url", &origin.to_string_lossy())
4537
        .unwrap();
4538
    repo.config
4539
        .set("remote.down.url", "http://127.0.0.1:9/a/b")
4540
        .unwrap();
4541
    repo.config.set("remote.down.token", "t").unwrap();
4542
    repo.config
4543
        .set("remote.badca.url", "https://example.invalid/a/b")
4544
        .unwrap();
4545
    repo.config
4546
        .set(
4547
            "remote.badca.ca",
4548
            &root.join("missing.pem").to_string_lossy(),
4549
        )
4550
        .unwrap();
4551
    repo.save_config().unwrap();
4552
4553
    let r = repo.doctor(true);
4554
    assert!(find(&r, "identity", Health::Ok).is_some(), "{r:?}");
4555
    assert!(find(&r, "author", Health::Ok).is_some(), "{r:?}");
4556
    assert!(find(&r, "remote origin", Health::Ok)
4557
        .unwrap()
4558
        .message
4559
        .contains("first push binds it"));
4560
    let down = find(&r, "remote down", Health::Fail).unwrap();
4561
    assert!(
4562
        down.hint.as_deref().unwrap_or("").contains("running"),
4563
        "{down:?}"
4564
    );
4565
    let badca = find(&r, "remote badca", Health::Fail).unwrap();
4566
    assert!(
4567
        badca.hint.unwrap().contains("remote.badca.ca"),
4568
        "the remote's own name is in the hint"
4569
    );
4570
    assert_eq!(r.worst(), Health::Fail);
4571
4572
    // Offline, nothing is contacted.
4573
    let r = repo.doctor(false);
4574
    assert!(find(&r, "remote down", Health::Fail).is_none());
4575
    assert!(find(&r, "remote down", Health::Ok)
4576
        .unwrap()
4577
        .message
4578
        .contains("not contacted"));
4579
}
4580
4581
/// Spec §8.1: deleting a line depends on whoever inserted the lines right
4582
/// after it. Inserting after `b` and then deleting `b`, one commit after
4583
/// the other, must not leave a delete/insert conflict.
4584
#[test]
4585
fn deleting_a_line_after_an_insertion_below_it_is_not_a_conflict() {
4586
    hermetic();
4587
    let dir = tempfile::tempdir().unwrap();
4588
    let root = dir.path();
4589
    let repo = Repo::init(root).unwrap();
4590
    write(root, "f", b"a\nb\nc\n");
4591
    repo.commit("base", &[]).unwrap();
4592
    write(root, "f", b"a\nb\nx\nc\n");
4593
    let insert = repo.commit("insert x after b", &[]).unwrap();
4594
    write(root, "f", b"a\nx\nc\n");
4595
    let delete = repo.commit("delete b", &[]).unwrap();
4596
    assert!(
4597
        repo.store()
4598
            .get_change(&delete)
4599
            .unwrap()
4600
            .deps
4601
            .contains(&insert),
4602
        "the deletion depends on the insertion below the deleted line"
4603
    );
4604
    let heads = repo.bookmark_heads().unwrap();
4605
    assert_eq!(heads, vec![delete]);
4606
    let snap = repo.load_state(&heads).unwrap().materialize();
4607
    assert!(!snap.is_conflicted());
4608
    assert!(
4609
        matches!(&snap.files["f"].content, FileContent::Text { bytes, .. } if bytes == b"a\nx\nc\n")
4610
    );
4611
}
4612
4613
/// Spec §9.3: a binary file reverted to an earlier blob keeps it, and each
4614
/// replacement depends on the change that set the blob it replaces.
4615
#[test]
4616
fn a_binary_file_reverted_to_an_earlier_blob_keeps_it() {
4617
    hermetic();
4618
    let dir = tempfile::tempdir().unwrap();
4619
    let root = dir.path();
4620
    let repo = Repo::init(root).unwrap();
4621
    write(root, "bin", b"\0A");
4622
    let v1 = repo.commit("v1", &[]).unwrap();
4623
    write(root, "bin", b"\0B");
4624
    let v2 = repo.commit("v2", &[]).unwrap();
4625
    assert!(repo.store().get_change(&v2).unwrap().deps.contains(&v1));
4626
    write(root, "bin", b"\0A");
4627
    let v3 = repo.commit("back to A", &[]).unwrap();
4628
    assert!(repo.store().get_change(&v3).unwrap().deps.contains(&v2));
4629
    assert_eq!(repo.bookmark_heads().unwrap(), vec![v3]);
4630
    let state = repo.load_state(&[v3]).unwrap();
4631
    let snap = state.materialize();
4632
    let FileContent::Opaque { blobs } = &snap.files["bin"].content else {
4633
        panic!("opaque")
4634
    };
4635
    assert_eq!(blobs.len(), 1, "one live blob, not none and not two");
4636
    assert_eq!(repo.read_blob(&blobs[0]).unwrap(), b"\0A");
4637
}
4638
4639
/// Spec §23: a binary file changed on two branches and merged in Git to
4640
/// one side's version comes back as that version at the merge, and the
4641
/// import verifies commit by commit.
4642
#[test]
4643
fn git_import_resolves_a_binary_merged_in_git_and_verifies() {
4644
    hermetic();
4645
    if std::process::Command::new("git")
4646
        .arg("--version")
4647
        .output()
4648
        .is_err()
4649
    {
4650
        eprintln!("git not installed; skipping");
4651
        return;
4652
    }
4653
    let dir = tempfile::tempdir().unwrap();
4654
    let root = dir.path();
4655
    let g = root.join("src.git");
4656
    fs::create_dir_all(&g).unwrap();
4657
    let git = |args: &[&str]| -> String {
4658
        let out = std::process::Command::new("git")
4659
            .arg("-C")
4660
            .arg(&g)
4661
            .args([
4662
                "-c",
4663
                "user.name=Grace",
4664
                "-c",
4665
                "[email protected]",
4666
                "-c",
4667
                "commit.gpgsign=false",
4668
            ])
4669
            .args(args)
4670
            .output()
4671
            .unwrap();
4672
        assert!(
4673
            out.status.success(),
4674
            "git {args:?}: {}",
4675
            String::from_utf8_lossy(&out.stderr)
4676
        );
4677
        String::from_utf8_lossy(&out.stdout).trim().to_string()
4678
    };
4679
    git(&["init", "-q", "-b", "main"]);
4680
    write(&g, "logo.bin", b"\0base");
4681
    write(&g, "notes.txt", b"a\nb\nc\n");
4682
    git(&["add", "."]);
4683
    git(&["commit", "-qm", "base"]);
4684
    git(&["checkout", "-qb", "side"]);
4685
    write(&g, "logo.bin", b"\0side");
4686
    write(&g, "notes.txt", b"a\nb\nx\nc\n");
4687
    git(&["commit", "-qam", "side"]);
4688
    git(&["checkout", "-q", "main"]);
4689
    write(&g, "logo.bin", b"\0main");
4690
    git(&["commit", "-qam", "main"]);
4691
    // Git cannot merge the binary; the merge takes main's and keeps side's text.
4692
    let _ = std::process::Command::new("git")
4693
        .arg("-C")
4694
        .arg(&g)
4695
        .args([
4696
            "-c",
4697
            "user.name=G",
4698
            "-c",
4699
            "user.email=g@e",
4700
            "merge",
4701
            "-q",
4702
            "side",
4703
        ])
4704
        .output();
4705
    write(&g, "logo.bin", b"\0main");
4706
    git(&["add", "."]);
4707
    git(&["commit", "-qm", "merge side"]);
4708
    // Then a revert of the binary to its first version.
4709
    write(&g, "logo.bin", b"\0base");
4710
    git(&["commit", "-qam", "back to base"]);
4711
4712
    let repo = Repo::init(&root.join("o")).unwrap();
4713
    let rep = repo.import_git(&g, "main").unwrap();
4714
    assert_eq!(rep.merges, 1);
4715
    let v = repo.verify_git_import(&g, "main").unwrap();
4716
    assert!(v.mismatches.is_empty(), "{:?}", v.mismatches);
4717
    assert_eq!(v.commits, 5);
4718
    let snap = repo
4719
        .load_state(&repo.bookmark_heads().unwrap())
4720
        .unwrap()
4721
        .materialize();
4722
    assert!(!snap.is_conflicted());
4723
    let FileContent::Opaque { blobs } = &snap.files["logo.bin"].content else {
4724
        panic!("opaque")
4725
    };
4726
    assert_eq!(repo.read_blob(&blobs[0]).unwrap(), b"\0base");
4727
}
4728
4729
/// Spec §7.7 on a file system without executable bits or symlinks: the
4730
/// recorded bit is kept, and a symlink checked out as a plain file holding
4731
/// its target is still that symlink.
4732
#[cfg(unix)]
4733
#[test]
4734
fn windows_file_systems_keep_exec_bits_and_symlinks() {
4735
    use crate::portable::Platform;
4736
    use std::os::unix::fs::PermissionsExt;
4737
    hermetic();
4738
    let dir = tempfile::tempdir().unwrap();
4739
    let root = dir.path();
4740
    let repo = Repo::init(root).unwrap();
4741
    write(root, "run.sh", b"#!/bin/sh\n");
4742
    fs::set_permissions(root.join("run.sh"), fs::Permissions::from_mode(0o755)).unwrap();
4743
    std::os::unix::fs::symlink("run.sh", root.join("link")).unwrap();
4744
    repo.commit("script and link", &[]).unwrap();
4745
    drop(repo);
4746
4747
    // What checking out on Windows leaves: no exec bit, the link as a file.
4748
    fs::set_permissions(root.join("run.sh"), fs::Permissions::from_mode(0o644)).unwrap();
4749
    fs::remove_file(root.join("link")).unwrap();
4750
    write(root, "link", b"run.sh");
4751
    let win = Repo::open(root).unwrap().with_platform(Platform::windows());
4752
    let s = win.snapshot("oxy status").unwrap();
4753
    assert!(
4754
        s.statuses.is_empty(),
4755
        "nothing changed on Windows: {:?}",
4756
        statuses(&s)
4757
    );
4758
    // Editing the file is a content change, not a mode change; retargeting the link keeps it a link.
4759
    write(root, "run.sh", b"#!/bin/sh\necho hi\n");
4760
    write(root, "link", b"other");
4761
    let h = win.commit("edit on Windows", &[]).unwrap();
4762
    let snap = win.load_state(&[h]).unwrap().materialize();
4763
    assert!(snap.files["run.sh"].mode.exec, "the exec bit survives");
4764
    assert_eq!(snap.files["link"].kind, NodeKind::Symlink);
4765
    // The same working copy read as Linux sees the lost bit and the plain file.
4766
    let linux = Repo::open(root).unwrap();
4767
    assert!(!linux.snapshot("oxy status").unwrap().statuses.is_empty());
4768
}
4769
4770
/// Paths that collide on case-insensitive or Windows file systems are
4771
/// named at checkout there, and by doctor everywhere.
4772
#[test]
4773
fn paths_other_platforms_cannot_hold_are_reported() {
4774
    use crate::portable::Platform;
4775
    hermetic();
4776
    let dir = tempfile::tempdir().unwrap();
4777
    let root = dir.path();
4778
    let repo = Repo::init(root).unwrap();
4779
    write(root, "README.md", b"a\n");
4780
    write(root, "readme.md", b"b\n");
4781
    write(root, "src/aux.c", b"int x;\n");
4782
    let h = repo.commit("unportable", &[]).unwrap();
4783
    let r = repo.doctor(false);
4784
    let port = r.checks.iter().find(|c| c.area == "portability").unwrap();
4785
    assert_eq!(port.health, Health::Warn);
4786
    assert!(
4787
        port.message.contains("differ only in case") && port.message.contains("aux.c"),
4788
        "{}",
4789
        port.message
4790
    );
4791
    let mac = Repo::open(root).unwrap().with_platform(Platform::macos());
4792
    let rep = mac.checkout(&[h], true, "oxy checkout").unwrap();
4793
    assert!(
4794
        rep.notes
4795
            .iter()
4796
            .any(|n| n.contains("README.md and readme.md")),
4797
        "{:?}",
4798
        rep.notes
4799
    );
4800
    assert!(
4801
        !rep.notes.iter().any(|n| n.contains("aux.c")),
4802
        "macOS allows aux.c"
4803
    );
4804
}
4805
4806
#[test]
4807
fn history_and_blame_of_a_loaded_state_match_the_full_walk() {
4808
    hermetic();
4809
    let dir = tempfile::tempdir().unwrap();
4810
    let repo = Repo::init(dir.path()).unwrap();
4811
    write(dir.path(), "a.txt", b"one\n");
4812
    write(dir.path(), "other.txt", b"x\n");
4813
    write(dir.path(), "bin.dat", &[0u8, 1, 2, 0, 255]);
4814
    repo.snapshot("t").unwrap();
4815
    let c1 = repo.commit("first", &[]).unwrap();
4816
    write(dir.path(), "other.txt", b"y\n");
4817
    repo.snapshot("t").unwrap();
4818
    repo.commit("other only", &[]).unwrap();
4819
    write(dir.path(), "a.txt", b"one\ntwo\n");
4820
    repo.snapshot("t").unwrap();
4821
    let c3 = repo.commit("second line", &[]).unwrap();
4822
    write(dir.path(), "other.txt", b"z\n");
4823
    repo.snapshot("t").unwrap();
4824
    repo.commit("other again", &[]).unwrap();
4825
4826
    let heads = repo.bookmark_heads().unwrap();
4827
    let state = repo.load_state(&heads).unwrap();
4828
    let full: Vec<ChangeHash> = repo
4829
        .log_for_path_in("a.txt", &heads)
4830
        .unwrap()
4831
        .iter()
4832
        .map(|e| e.hash)
4833
        .collect();
4834
    assert_eq!(
4835
        full,
4836
        vec![c3, c1],
4837
        "newest first, only changes touching the path"
4838
    );
4839
    let newest: Vec<ChangeHash> = repo
4840
        .log_for_path_of(&state, "a.txt", Some(1))
4841
        .unwrap()
4842
        .iter()
4843
        .map(|e| e.hash)
4844
        .collect();
4845
    assert_eq!(newest, vec![c3], "stops at the first");
4846
    assert_eq!(
4847
        repo.log_for_path_of(&state, "a.txt", None).unwrap().len(),
4848
        2
4849
    );
4850
    assert!(repo
4851
        .log_for_path_of(&state, "missing.txt", Some(1))
4852
        .is_err());
4853
    assert_eq!(
4854
        repo.log_state(&heads).unwrap().len(),
4855
        repo.log_of(&state).len()
4856
    );
4857
4858
    let tree = state.tree().view();
4859
    let via_state = repo.blame_of(&state, &tree, "a.txt").unwrap();
4860
    let via_heads = repo.blame_in("a.txt", &heads).unwrap();
4861
    assert_eq!(
4862
        via_state
4863
            .iter()
4864
            .map(|l| (l.hash, l.text.clone()))
4865
            .collect::<Vec<_>>(),
4866
        via_heads
4867
            .iter()
4868
            .map(|l| (l.hash, l.text.clone()))
4869
            .collect::<Vec<_>>()
4870
    );
4871
    assert_eq!(
4872
        via_state.iter().map(|l| l.hash).collect::<Vec<_>>(),
4873
        vec![c1, c3]
4874
    );
4875
    assert!(repo.blame_of(&state, &tree, "missing.txt").is_err());
4876
}
4877
4878
/// A text file whose stat matches the manifest and whose recorded hash is
4879
/// the base's content is taken from the base without reading it; anything
4880
/// else is read, so no edit is missed (spec §12.3).
4881
#[cfg(unix)]
4882
#[test]
4883
fn stat_cache_takes_unchanged_text_from_the_base_and_misses_no_edit() {
4884
    use std::os::unix::fs::PermissionsExt;
4885
    hermetic();
4886
    let dir = tempfile::tempdir().unwrap();
4887
    let root = dir.path();
4888
    let repo = Repo::init(root).unwrap().with_home(root.join("home"));
4889
    write(root, "a.txt", b"one\ntwo\n");
4890
    write(root, "b.txt", b"bee\n");
4891
    repo.commit("base", &[]).unwrap();
4892
    let age = |p: &str| {
4893
        let old = std::time::SystemTime::now() - std::time::Duration::from_secs(30);
4894
        fs::File::options()
4895
            .write(true)
4896
            .open(root.join(p))
4897
            .unwrap()
4898
            .set_modified(old)
4899
            .unwrap();
4900
    };
4901
    age("a.txt");
4902
    age("b.txt");
4903
    assert!(
4904
        !repo.snapshot("status").unwrap().changed,
4905
        "records the aged stat"
4906
    );
4907
4908
    // Clean and equal to the base: not read at all.
4909
    fs::set_permissions(root.join("a.txt"), fs::Permissions::from_mode(0o000)).unwrap();
4910
    let snap = repo.snapshot("status").unwrap();
4911
    assert!(
4912
        !snap.changed && snap.statuses.is_empty(),
4913
        "{:?}",
4914
        snap.statuses
4915
    );
4916
    fs::set_permissions(root.join("a.txt"), fs::Permissions::from_mode(0o644)).unwrap();
4917
4918
    // An uncommitted edit that is older than the manifest: stat-clean, but
4919
    // its hash is not the base's, so it is read and stays visible.
4920
    write(root, "b.txt", b"bee edited\n");
4921
    age("b.txt");
4922
    let first = repo.snapshot("status").unwrap();
4923
    assert_eq!(
4924
        statuses(&first),
4925
        vec![("b.txt".to_string(), ChangeStatus::Modified)]
4926
    );
4927
    let again = repo.snapshot("status").unwrap();
4928
    assert_eq!(
4929
        statuses(&again),
4930
        vec![("b.txt".to_string(), ChangeStatus::Modified)],
4931
        "still seen once stat-clean"
4932
    );
4933
    assert!(!again.changed, "and the working copy hashes the same");
4934
    fs::set_permissions(root.join("b.txt"), fs::Permissions::from_mode(0o000)).unwrap();
4935
    assert!(
4936
        repo.snapshot("status").is_err(),
4937
        "an edited file must be read, never taken from the base"
4938
    );
4939
    fs::set_permissions(root.join("b.txt"), fs::Permissions::from_mode(0o644)).unwrap();
4940
4941
    // A same-size edit made just now is racy and read.
4942
    write(root, "a.txt", b"one\nTWO\n");
4943
    assert_eq!(
4944
        statuses(&repo.snapshot("status").unwrap()),
4945
        vec![
4946
            ("a.txt".to_string(), ChangeStatus::Modified),
4947
            ("b.txt".to_string(), ChangeStatus::Modified)
4948
        ]
4949
    );
4950
    // Committing makes the edits the base: both are clean and served from it again.
4951
    repo.commit("edits", &[]).unwrap();
4952
    age("a.txt");
4953
    age("b.txt");
4954
    assert!(repo.snapshot("status").unwrap().statuses.is_empty());
4955
    fs::set_permissions(root.join("a.txt"), fs::Permissions::from_mode(0o000)).unwrap();
4956
    fs::set_permissions(root.join("b.txt"), fs::Permissions::from_mode(0o000)).unwrap();
4957
    let snap = repo.snapshot("status").unwrap();
4958
    assert!(!snap.changed && snap.statuses.is_empty());
4959
    fs::set_permissions(root.join("a.txt"), fs::Permissions::from_mode(0o644)).unwrap();
4960
    fs::set_permissions(root.join("b.txt"), fs::Permissions::from_mode(0o644)).unwrap();
4961
}
4962
4963
/// Version 2 checkpoints (spec §11): a large file's graph is a blob of its
4964
/// own, kept by gc, checked by fsck, shared by the next checkpoint when the
4965
/// file is unchanged, and loading through the checkpoint equals a full load.
4966
#[test]
4967
fn checkpoints_keep_large_graphs_as_blobs_of_their_own() {
4968
    hermetic();
4969
    let dir = tempfile::tempdir().unwrap();
4970
    let root = dir.path();
4971
    let repo = Repo::init(root).unwrap().with_home(root.join("home"));
4972
    let long: String = (0..300)
4973
        .map(|i| format!("line {i} of a long file\n"))
4974
        .collect();
4975
    write(root, "long.txt", long.as_bytes());
4976
    write(root, "short.txt", b"short\n");
4977
    repo.commit("base", &[]).unwrap();
4978
    let (r1, _, _) = repo.checkpoint().unwrap();
4979
    let cp1 = crate::objects::Checkpoint::decode(
4980
        &repo.store().get_typed(&r1, ObjectType::Checkpoint).unwrap(),
4981
    )
4982
    .unwrap();
4983
    let graphs1 = repo.checkpoint_graph_blobs(&cp1).unwrap();
4984
    assert_eq!(graphs1.len(), 1, "only the long file's graph is a blob");
4985
4986
    // gc keeps the graph blob; fsck finds the checkpoint sound.
4987
    repo.gc(true).unwrap();
4988
    assert!(repo.store().has(&graphs1[0]));
4989
    let report = repo.fsck().unwrap();
4990
    assert_eq!(report.errors(), 0, "{:?}", report.problems);
4991
4992
    // Loading through the checkpoint equals a full load.
4993
    write(root, "short.txt", b"short, edited\n");
4994
    repo.commit("edit the short file", &[]).unwrap();
4995
    let heads = repo.bookmark_heads().unwrap();
4996
    let fast = repo.load_state(&heads).unwrap();
4997
    let full = repo.load_state_full(&heads).unwrap();
4998
    assert_eq!(fast.checkpoint_payload(), full.checkpoint_payload());
4999
5000
    // The next checkpoint shares the unchanged long file's graph.
5001
    let (r2, _, _) = repo.checkpoint().unwrap();
5002
    let cp2 = crate::objects::Checkpoint::decode(
5003
        &repo.store().get_typed(&r2, ObjectType::Checkpoint).unwrap(),
5004
    )
5005
    .unwrap();
5006
    assert_eq!(repo.checkpoint_graph_blobs(&cp2).unwrap(), graphs1);
5007
5008
    // A shallow clone's bundle carries the graph blob with the checkpoint.
5009
    let bundle = repo.checkpoint_bundle_for(&heads).unwrap();
5010
    assert!(bundle.objects.iter().any(|(t, body)| *t == ObjectType::Blob
5011
        && crate::hash::hash_object(ObjectType::Blob, body) == graphs1[0]));
5012
5013
    // A version 1 checkpoint written by an older oxy still loads.
5014
    let state = repo.load_state_full(&heads).unwrap();
5015
    let old = repo.store_blob(&state.checkpoint_payload()).unwrap();
5016
    let cp_old = crate::objects::Checkpoint {
5017
        heads: cp2.heads.clone(),
5018
        count: cp2.count,
5019
        payload: old,
5020
    };
5021
    let r_old = repo
5022
        .store()
5023
        .put(ObjectType::Checkpoint, &cp_old.encode())
5024
        .unwrap();
5025
    repo.install_checkpoint("main", &r_old).unwrap();
5026
    assert_eq!(
5027
        repo.load_state(&heads).unwrap().checkpoint_payload(),
5028
        full.checkpoint_payload()
5029
    );
5030
    assert_eq!(repo.fsck().unwrap().errors(), 0);
5031
5032
    // A lost graph blob fails the load loudly rather than dropping the
5033
    // file, and fsck reports it (a fresh repository, objects still loose).
5034
    let dir2 = tempfile::tempdir().unwrap();
5035
    let root2 = dir2.path();
5036
    let repo2 = Repo::init(root2).unwrap().with_home(root2.join("home"));
5037
    write(root2, "long.txt", long.as_bytes());
5038
    repo2.commit("base", &[]).unwrap();
5039
    let (r, _, _) = repo2.checkpoint().unwrap();
5040
    let cp = crate::objects::Checkpoint::decode(
5041
        &repo2.store().get_typed(&r, ObjectType::Checkpoint).unwrap(),
5042
    )
5043
    .unwrap();
5044
    let graph = repo2.checkpoint_graph_blobs(&cp).unwrap()[0];
5045
    repo2.store().remove_loose_for_test(&graph).unwrap();
5046
    assert!(repo2.load_state(&repo2.bookmark_heads().unwrap()).is_err());
5047
    assert!(repo2.fsck().unwrap().errors() > 0, "fsck reports it");
5048
}
5049
5050
/// A new repository has not stored the user's identity yet (that happens
5051
/// at the first signed change); looking it up falls back to the key
5052
/// directory, and a file there that does not hash to the key is refused.
5053
#[test]
5054
fn identity_is_found_in_the_key_directory_for_a_new_repository() {
5055
    hermetic();
5056
    let dir = tempfile::tempdir().unwrap();
5057
    let home = dir.path().join("home");
5058
    let mut first = Repo::init(&dir.path().join("a"))
5059
        .unwrap()
5060
        .with_home(home.clone());
5061
    let (key, _) = first
5062
        .create_identity("Ada", "[email protected]", IdentityScope::User)
5063
        .unwrap();
5064
    let fresh = Repo::init(&dir.path().join("b"))
5065
        .unwrap()
5066
        .with_home(home.clone());
5067
    assert!(!fresh.store().has(&key), "nothing stored yet");
5068
    let id = fresh.identity(&key).unwrap();
5069
    assert_eq!((id.name.as_str(), id.hash()), ("Ada", key));
5070
    // A key file that is not this identity is an error, not a wrong answer.
5071
    let keys = fresh.keys_dir.clone();
5072
    let (other, _) = first
5073
        .create_identity("Bob", "[email protected]", IdentityScope::User)
5074
        .unwrap();
5075
    fs::copy(
5076
        keys.join(format!("{}.identity", other.to_hex())),
5077
        keys.join(format!("{}.identity", key.to_hex())),
5078
    )
5079
    .unwrap();
5080
    assert!(fresh
5081
        .identity(&key)
5082
        .unwrap_err()
5083
        .to_string()
5084
        .contains("does not hold identity"));
5085
}
5086
5087
/// Status snapshots (spec §12.3): a text file whose stat matches the
5088
/// manifest, and whose base graph key is the one the manifest recorded it
5089
/// equal to, is neither read nor rendered; any edit, and any change to the
5090
/// file's graph in the base, brings it back.
5091
#[cfg(unix)]
5092
#[test]
5093
fn status_snapshots_skip_files_unchanged_since_the_manifest() {
5094
    use std::os::unix::fs::PermissionsExt;
5095
    hermetic();
5096
    let dir = tempfile::tempdir().unwrap();
5097
    let root = dir.path();
5098
    let repo = Repo::init(root).unwrap().with_home(root.join("home"));
5099
    for (p, c) in [("a.txt", "one\n"), ("b.txt", "bee\n"), ("d/c.txt", "sea\n")] {
5100
        write(root, p, c.as_bytes());
5101
    }
5102
    repo.commit("base", &[]).unwrap();
5103
    let age = |p: &str| {
5104
        let old = std::time::SystemTime::now() - std::time::Duration::from_secs(30);
5105
        fs::File::options()
5106
            .write(true)
5107
            .open(root.join(p))
5108
            .unwrap()
5109
            .set_modified(old)
5110
            .unwrap();
5111
    };
5112
    let lock = |p: &str, mode: u32| {
5113
        fs::set_permissions(root.join(p), fs::Permissions::from_mode(mode)).unwrap()
5114
    };
5115
    for p in ["a.txt", "b.txt", "d/c.txt"] {
5116
        age(p);
5117
    }
5118
    assert!(repo.snapshot("status").unwrap().statuses.is_empty());
5119
    let (_, _, m) = repo.read_manifest().unwrap().unwrap();
5120
    assert!(
5121
        m.entries.values().all(|e| e.graph.is_some()),
5122
        "keys recorded"
5123
    );
5124
5125
    // Unreadable files prove they are not read; the status snapshot does
5126
    // not render them either, and its base lacks their graphs.
5127
    lock("a.txt", 0o000);
5128
    lock("b.txt", 0o000);
5129
    let snap = repo.snapshot_status("status").unwrap();
5130
    assert!(!snap.changed && snap.statuses.is_empty());
5131
    assert_eq!(
5132
        snap.base_snapshot
5133
            .unrendered
5134
            .iter()
5135
            .cloned()
5136
            .collect::<Vec<_>>(),
5137
        vec!["a.txt", "b.txt", "d/c.txt"]
5138
    );
5139
    assert!(!snap.base.is_full());
5140
    assert!(!snap.base_snapshot.is_conflicted());
5141
    // A full snapshot does not read them either, but renders everything.
5142
    let full = repo.snapshot("status").unwrap();
5143
    assert!(full.statuses.is_empty() && full.base.is_full());
5144
    assert!(full.base_snapshot.unrendered.is_empty());
5145
    assert!(matches!(&full.base_snapshot.files["a.txt"].content,
5146
        FileContent::Text { bytes, .. } if bytes == b"one\n"));
5147
5148
    // An edit is seen; the file is rendered, the others still are not.
5149
    write(root, "d/c.txt", b"sea edited\n");
5150
    let snap = repo.snapshot_status("status").unwrap();
5151
    assert_eq!(
5152
        statuses(&snap),
5153
        vec![("d/c.txt".to_string(), ChangeStatus::Modified)]
5154
    );
5155
    assert!(!snap.base_snapshot.unrendered.contains("d/c.txt"));
5156
    // So is a mode change of an unread file.
5157
    lock("b.txt", 0o100);
5158
    assert_eq!(
5159
        statuses(&repo.snapshot_status("status").unwrap()),
5160
        vec![
5161
            ("b.txt".to_string(), ChangeStatus::ModeChanged),
5162
            ("d/c.txt".to_string(), ChangeStatus::Modified)
5163
        ]
5164
    );
5165
    lock("b.txt", 0o000);
5166
5167
    // Committing c.txt changes its graph in the base, not a.txt's: a.txt
5168
    // stays unread, c.txt is read once and then skipped too.
5169
    repo.commit_selection("edit c", &[], &Selection::Paths(vec!["d/c.txt".into()]))
5170
        .unwrap();
5171
    age("d/c.txt");
5172
    let snap = repo.snapshot_status("status").unwrap();
5173
    assert!(snap.statuses.is_empty(), "{:?}", snap.statuses);
5174
    assert!(snap.base_snapshot.unrendered.contains("a.txt"));
5175
    lock("d/c.txt", 0o000);
5176
    let snap = repo.snapshot_status("status").unwrap();
5177
    assert!(snap.statuses.is_empty());
5178
    assert!(snap.base_snapshot.unrendered.contains("d/c.txt"));
5179
    for p in ["a.txt", "b.txt", "d/c.txt"] {
5180
        lock(p, 0o644);
5181
    }
5182
}
5183
5184
/// Attributes decide how a file compares with the base, so a changed
5185
/// `.oxyattributes` makes every text file be compared again.
5186
#[cfg(unix)]
5187
#[test]
5188
fn a_changed_attributes_file_disables_skipping_unchanged_files() {
5189
    hermetic();
5190
    let dir = tempfile::tempdir().unwrap();
5191
    let root = dir.path();
5192
    let repo = Repo::init(root).unwrap().with_home(root.join("home"));
5193
    write(root, "a.txt", b"crlf\r\n");
5194
    repo.commit("base", &[]).unwrap();
5195
    let old = std::time::SystemTime::now() - std::time::Duration::from_secs(30);
5196
    fs::File::options()
5197
        .write(true)
5198
        .open(root.join("a.txt"))
5199
        .unwrap()
5200
        .set_modified(old)
5201
        .unwrap();
5202
    assert!(repo.snapshot_status("status").unwrap().statuses.is_empty());
5203
    assert!(repo
5204
        .snapshot_status("status")
5205
        .unwrap()
5206
        .base_snapshot
5207
        .unrendered
5208
        .contains("a.txt"));
5209
    // With eol=lf, a.txt as stored no longer equals the base.
5210
    write(root, ".oxyattributes", b"*.txt eol=lf\n");
5211
    let snap = repo.snapshot_status("status").unwrap();
5212
    assert_eq!(
5213
        statuses(&snap),
5214
        vec![
5215
            (".oxyattributes".to_string(), ChangeStatus::Added),
5216
            ("a.txt".to_string(), ChangeStatus::Modified)
5217
        ]
5218
    );
5219
}
5220
5221
/// Bookmarks with `/` in their names: pushing records their
5222
/// attestations, and checkpoints are kept for them, beside `feature`
5223
/// itself.
5224
#[test]
5225
fn bookmarks_with_slashes_push_and_checkpoint() {
5226
    hermetic();
5227
    let dir = tempfile::tempdir().unwrap();
5228
    let root = dir.path();
5229
    let origin = Repo::init(&root.join("origin")).unwrap();
5230
    let url = root.join("origin").to_string_lossy().to_string();
5231
    let mut repo = Repo::clone(&url, &root.join("r"))
5232
        .unwrap()
5233
        .with_home(root.join("home"));
5234
    // With an identity, pushes carry reference attestations: the case
5235
    // that failed, since the attestation is a file named after the bookmark.
5236
    repo.create_identity("Ada", "[email protected]", IdentityScope::Repo)
5237
        .unwrap();
5238
    let r = root.join("r");
5239
    write(&r, "a.txt", b"a\n");
5240
    let h_a = repo.commit("a", &[]).unwrap();
5241
    assert!(repo.push("origin", false).unwrap()[0].ok);
5242
    repo.bookmark_create("feature", None).unwrap();
5243
    repo.bookmark_create("feature/x", None).unwrap();
5244
    repo.bookmark_switch("feature/x", false).unwrap();
5245
    write(&r, "b.txt", b"b\n");
5246
    let h_b = repo.commit("b", &[]).unwrap();
5247
    for name in ["feature", "feature/x"] {
5248
        let res = repo.push_bookmark("origin", name, false).unwrap();
5249
        assert!(res[0].ok, "{name}: {res:?}");
5250
    }
5251
    assert_eq!(origin.resolve_heads("feature").unwrap(), vec![h_a]);
5252
    assert_eq!(
5253
        origin.resolve_heads("feature/x").unwrap(),
5254
        repo.resolve_heads("feature/x").unwrap()
5255
    );
5256
    assert!(origin.resolve_heads("feature/x").unwrap().contains(&h_b));
5257
    assert!(origin.latest_ref_attest("feature/x").unwrap().is_some());
5258
    assert!(origin.latest_ref_attest("feature").unwrap().is_some());
5259
5260
    // A checkpoint of feature/x is found again when loading its state.
5261
    let (cp, _, _) = repo.checkpoint().unwrap();
5262
    assert_eq!(repo.latest_checkpoint("feature/x").unwrap().unwrap().0, cp);
5263
    assert!(repo.latest_checkpoint("feature").unwrap().is_none());
5264
    let heads = repo.resolve_heads("feature/x").unwrap();
5265
    assert!(repo.load_state_checkpointed(&heads).unwrap().is_some());
5266
}
5267
5268
/// Deleting a bookmark on a remote (spec §16.4): attested like any update,
5269
/// never the remote's own bookmark, and a bookmark created again later is
5270
/// accepted although the deletion's attestation stays the latest.
5271
#[test]
5272
fn bookmarks_are_deleted_on_a_remote() {
5273
    hermetic();
5274
    let dir = tempfile::tempdir().unwrap();
5275
    let root = dir.path();
5276
    let origin = Repo::init(&root.join("origin")).unwrap();
5277
    let url = root.join("origin").to_string_lossy().to_string();
5278
    let mut repo = Repo::clone(&url, &root.join("r"))
5279
        .unwrap()
5280
        .with_home(root.join("home"));
5281
    repo.create_identity("Ada", "[email protected]", IdentityScope::Repo)
5282
        .unwrap();
5283
    let r = root.join("r");
5284
    write(&r, "a.txt", b"a\n");
5285
    repo.commit("a", &[]).unwrap();
5286
    assert!(repo.push("origin", false).unwrap()[0].ok);
5287
    repo.bookmark_create("feature/x", None).unwrap();
5288
    assert!(repo.push_bookmark("origin", "feature/x", false).unwrap()[0].ok);
5289
    assert!(origin.resolve_heads("feature/x").is_ok());
5290
5291
    let res = repo.push_delete("origin", "feature/x").unwrap();
5292
    assert!(res[0].ok, "{res:?}");
5293
    assert!(!origin.view().unwrap().bookmarks.contains_key("feature/x"));
5294
    let (_, att) = origin.latest_ref_attest("feature/x").unwrap().unwrap();
5295
    assert!(
5296
        matches!(att.attest.body, AttestBody::Ref { new_state, .. } if new_state.is_zero()),
5297
        "the deletion is attested"
5298
    );
5299
    assert!(
5300
        repo.view().unwrap().bookmarks.contains_key("feature/x"),
5301
        "the local bookmark stays"
5302
    );
5303
    assert!(!repo
5304
        .view()
5305
        .unwrap()
5306
        .remotes
5307
        .get("origin")
5308
        .is_some_and(|m| m.contains_key("feature/x")));
5309
5310
    // Pushing it again creates it again, past the deletion's serial.
5311
    let res = repo.push_bookmark("origin", "feature/x", false).unwrap();
5312
    assert!(res[0].ok, "{res:?}");
5313
    assert!(origin.view().unwrap().bookmarks.contains_key("feature/x"));
5314
5315
    // Nothing to delete, and never the remote's own bookmark.
5316
    assert!(repo.push_delete("origin", "nope").is_err());
5317
    let res = repo.push_delete("origin", "main").unwrap();
5318
    assert!(
5319
        !res[0].ok && res[0].reason.contains("default bookmark"),
5320
        "{res:?}"
5321
    );
5322
    assert!(origin.view().unwrap().bookmarks.contains_key("main"));
5323
}
5324
5325
/// `bookmark switch --carry` (spec §10.1): uncommitted work goes along
5326
/// when the target has the same versions of the files it touches, and is
5327
/// refused, untouched, when it has others.
5328
#[test]
5329
fn switching_bookmarks_carries_uncommitted_work() {
5330
    hermetic();
5331
    let dir = tempfile::tempdir().unwrap();
5332
    let root = dir.path();
5333
    let mut repo = Repo::init(root).unwrap().with_home(root.join("home"));
5334
    write(root, "a.txt", b"a\n");
5335
    write(root, "b.txt", b"b\n");
5336
    write(root, "gone.txt", b"gone\n");
5337
    repo.commit("base", &[]).unwrap();
5338
    repo.bookmark_create("feature", None).unwrap();
5339
    // Started on main, belongs on feature: edit, add, remove.
5340
    write(root, "a.txt", b"a\nmore\n");
5341
    write(root, "new.txt", b"new\n");
5342
    fs::remove_file(root.join("gone.txt")).unwrap();
5343
    let (_, carried) = repo.bookmark_switch_carry("feature").unwrap();
5344
    assert_eq!(carried, vec!["a.txt", "gone.txt", "new.txt"]);
5345
    assert_eq!(repo.config.bookmark, "feature");
5346
    assert_eq!(fs::read(root.join("a.txt")).unwrap(), b"a\nmore\n");
5347
    assert_eq!(fs::read(root.join("new.txt")).unwrap(), b"new\n");
5348
    assert!(!root.join("gone.txt").exists());
5349
    let snap = repo.snapshot("status").unwrap();
5350
    assert_eq!(
5351
        statuses(&snap),
5352
        vec![
5353
            ("a.txt".to_string(), ChangeStatus::Modified),
5354
            ("gone.txt".to_string(), ChangeStatus::Removed),
5355
            ("new.txt".to_string(), ChangeStatus::Added)
5356
        ]
5357
    );
5358
    repo.commit("the work", &[]).unwrap();
5359
    assert!(repo.resolve_heads("main").unwrap().len() == 1);
5360
5361
    // main moves b.txt on; work on feature touching b.txt cannot follow.
5362
    repo.bookmark_switch("main", false).unwrap();
5363
    write(root, "b.txt", b"b on main\n");
5364
    repo.commit("b on main", &[]).unwrap();
5365
    repo.bookmark_switch("feature", false).unwrap();
5366
    write(root, "b.txt", b"b edited\n");
5367
    let err = repo.bookmark_switch_carry("main").unwrap_err().to_string();
5368
    assert!(err.contains("b.txt") && err.contains("--discard"), "{err}");
5369
    assert_eq!(repo.config.bookmark, "feature", "nothing happened");
5370
    assert_eq!(fs::read(root.join("b.txt")).unwrap(), b"b edited\n");
5371
}
5372
5373
/// Merging and checking out (feedback 3): a working copy without changes
5374
/// follows a merge whichever state it sat on; a refused checkout names
5375
/// what is in the way; `checkout --carry` takes the work along.
5376
#[test]
5377
fn merges_move_clean_working_copies_and_checkouts_say_what_blocks_them() {
5378
    hermetic();
5379
    let dir = tempfile::tempdir().unwrap();
5380
    let root = dir.path();
5381
    let mut repo = Repo::init(root).unwrap().with_home(root.join("home"));
5382
    write(root, "a.txt", b"a\n");
5383
    let h1 = repo.commit("a", &[]).unwrap();
5384
    write(root, "b.txt", b"b\n");
5385
    repo.commit("b", &[]).unwrap();
5386
    repo.bookmark_create("feature", None).unwrap();
5387
    repo.bookmark_switch("feature", false).unwrap();
5388
    write(root, "c.txt", b"c\n");
5389
    repo.commit("c on feature", &[]).unwrap();
5390
    repo.bookmark_switch("main", false).unwrap();
5391
    // The working copy sits on an older state than main's heads.
5392
    repo.checkout(&[h1], false, "checkout").unwrap();
5393
    assert!(!root.join("b.txt").exists());
5394
    let m = repo.merge("feature").unwrap();
5395
    assert!(m.checked_out, "a clean working copy follows the merge");
5396
    for f in ["a.txt", "b.txt", "c.txt"] {
5397
        assert!(root.join(f).exists(), "{f}");
5398
    }
5399
5400
    // A refusal says which paths are in the way and what to do.
5401
    fs::remove_file(root.join("b.txt")).unwrap();
5402
    write(root, "a.txt", b"a edited\n");
5403
    let err = repo
5404
        .checkout(&[h1], false, "checkout")
5405
        .unwrap_err()
5406
        .to_string();
5407
    assert!(
5408
        err.contains("modified a.txt") && err.contains("removed b.txt") && err.contains("--carry"),
5409
        "{err}"
5410
    );
5411
    // --carry takes them along: h1 has a.txt as the base has it, and no b.txt
5412
    // is carried as absent (h1 has none either, so that is refused).
5413
    let err = repo
5414
        .checkout_carry(&[h1], "the first change", "checkout")
5415
        .unwrap_err()
5416
        .to_string();
5417
    assert!(
5418
        err.contains("b.txt") && err.contains("the first change"),
5419
        "{err}"
5420
    );
5421
    write(root, "b.txt", b"b\n");
5422
    let (_, carried) = repo
5423
        .checkout_carry(&[h1], "the first change", "checkout")
5424
        .unwrap();
5425
    assert_eq!(carried, vec!["a.txt"]);
5426
    assert_eq!(fs::read(root.join("a.txt")).unwrap(), b"a edited\n");
5427
    assert!(!root.join("b.txt").exists(), "h1 has no b.txt");
5428
}
5429
5430
/// Doctor and subrepos before the first commit (feedback 5 and 8): a
5431
/// user identity not stored in a new repository yet is fine while its
5432
/// secret key is there; an added subrepo is listed as not committed yet.
5433
#[test]
5434
fn a_new_repository_is_healthy_before_its_first_commit() {
5435
    hermetic();
5436
    let dir = tempfile::tempdir().unwrap();
5437
    let root = dir.path();
5438
    let home = root.join("home");
5439
    let mut first = Repo::init(&root.join("first"))
5440
        .unwrap()
5441
        .with_home(home.clone());
5442
    let (key, _) = first
5443
        .create_identity("Ada", "[email protected]", IdentityScope::User)
5444
        .unwrap();
5445
    let repo = Repo::init(&root.join("second"))
5446
        .unwrap()
5447
        .with_home(home.clone());
5448
    // Only the secret key: no identity object anywhere this repository sees.
5449
    let keys = repo.keys_dir.clone();
5450
    let _ = fs::remove_file(keys.join(format!("{}.identity", key.to_hex())));
5451
    assert!(keys.join(format!("{}.secret", key.to_hex())).is_file());
5452
    let r = repo.doctor(true);
5453
    let id = r.checks.iter().find(|c| c.area == "identity").unwrap();
5454
    assert_eq!(id.health, Health::Ok, "{}", id.message);
5455
    assert!(id.message.contains("first signed change"), "{}", id.message);
5456
5457
    // A subrepo added and not committed yet is listed, pinned where it is.
5458
    let lib = root.join("lib");
5459
    let l = Repo::init(&lib).unwrap().with_home(home.clone());
5460
    write(&lib, "x.txt", b"x\n");
5461
    l.commit("x", &[]).unwrap();
5462
    let second = root.join("second");
5463
    write(&second, "a.txt", b"a\n");
5464
    repo.submodule_add(&lib.to_string_lossy(), "deps/lib", None)
5465
        .unwrap();
5466
    let subs = repo.subrepos().unwrap();
5467
    assert_eq!(subs.len(), 1);
5468
    assert_eq!(
5469
        (subs[0].path.as_str(), subs[0].committed),
5470
        ("deps/lib", false)
5471
    );
5472
    assert_eq!(subs[0].actual.as_ref(), Some(&subs[0].pin));
5473
    repo.commit("add lib", &[]).unwrap();
5474
    let subs = repo.subrepos().unwrap();
5475
    assert!(subs[0].committed, "committed now");
5476
}
5477
5478
/// Commit, diff, hunks and discard use the partial snapshot: a file
5479
/// unchanged since the manifest is neither read nor rendered, and showing
5480
/// a change renders only what it edits, the same as from a full base.
5481
#[cfg(unix)]
5482
#[test]
5483
fn commits_and_diffs_leave_unchanged_files_alone() {
5484
    use std::os::unix::fs::PermissionsExt;
5485
    hermetic();
5486
    let dir = tempfile::tempdir().unwrap();
5487
    let root = dir.path();
5488
    let repo = Repo::init(root).unwrap().with_home(root.join("home"));
5489
    write(root, "big.txt", b"lots\nof\nlines\n");
5490
    write(root, "a.txt", b"one\ntwo\n");
5491
    repo.commit("base", &[]).unwrap();
5492
    let old = std::time::SystemTime::now() - std::time::Duration::from_secs(30);
5493
    for f in ["big.txt", "a.txt"] {
5494
        fs::File::options()
5495
            .write(true)
5496
            .open(root.join(f))
5497
            .unwrap()
5498
            .set_modified(old)
5499
            .unwrap();
5500
    }
5501
    assert!(repo.snapshot_status("status").unwrap().statuses.is_empty());
5502
    // big.txt cannot be read at all from here on.
5503
    fs::set_permissions(root.join("big.txt"), fs::Permissions::from_mode(0o000)).unwrap();
5504
5505
    write(root, "a.txt", b"one\nTWO\nthree\n");
5506
    let diff = repo.diff_files(None).unwrap();
5507
    assert_eq!(
5508
        diff.iter().map(|f| f.path.as_str()).collect::<Vec<_>>(),
5509
        ["a.txt"]
5510
    );
5511
    let (_, hunks) = repo.hunks().unwrap();
5512
    assert!(!hunks.is_empty() && hunks.iter().all(|h| h.path == "a.txt"));
5513
    let h = repo.commit("edit a", &[]).unwrap();
5514
5515
    // Showing the change needs only a.txt's graph, and renders as a full base does.
5516
    let c = repo.store().get_change(&h).unwrap();
5517
    let full = repo.load_state(&c.deps).unwrap();
5518
    let want = render_change(&c, &full, &full.materialize());
5519
    assert_eq!(repo.describe_change(&h).unwrap(), want);
5520
    let (base, snap) = repo.change_base(&c).unwrap();
5521
    assert!(!base.is_full() && snap.unrendered.contains("big.txt"));
5522
5523
    // Discarding works the same way.
5524
    write(root, "a.txt", b"scratch\n");
5525
    assert_eq!(repo.discard(&["a.txt".into()]).unwrap(), 1);
5526
    assert_eq!(fs::read(root.join("a.txt")).unwrap(), b"one\nTWO\nthree\n");
5527
    fs::set_permissions(root.join("big.txt"), fs::Permissions::from_mode(0o644)).unwrap();
5528
}
5529
5530
/// A replace conflict (spec §9.3) is settled by a change that writes one
5531
/// candidate, or new bytes, at the path when the caller names it; a plain
5532
/// snapshot of a checkout never settles it on its own.
5533
#[test]
5534
fn replace_conflicts_are_settled_when_asked() {
5535
    hermetic();
5536
    let dir = tempfile::tempdir().unwrap();
5537
    let root = dir.path();
5538
    let mut repo = Repo::init(root).unwrap().with_home(root.join("home"));
5539
    let blob = |n: u8| {
5540
        let mut v = vec![0u8; 64];
5541
        v[1] = n;
5542
        v
5543
    };
5544
    write(root, "img.bin", &blob(1));
5545
    repo.commit("add img", &[]).unwrap();
5546
    repo.bookmark_create("other", None).unwrap();
5547
    write(root, "img.bin", &blob(2));
5548
    repo.commit("img two", &[]).unwrap();
5549
    repo.bookmark_switch("other", false).unwrap();
5550
    write(root, "img.bin", &blob(3));
5551
    repo.commit("img three", &[]).unwrap();
5552
    repo.bookmark_switch("main", false).unwrap();
5553
    repo.merge("other").unwrap();
5554
    let heads = repo.bookmark_heads().unwrap();
5555
    let merged = repo.load_state(&heads).unwrap().materialize();
5556
    assert!(
5557
        matches!(&merged.files["img.bin"].content, FileContent::Opaque { blobs } if blobs.len() == 2),
5558
        "a replace conflict"
5559
    );
5560
    // A snapshot of the checkout records nothing.
5561
    assert!(repo
5562
        .snapshot("status")
5563
        .unwrap()
5564
        .statuses
5565
        .iter()
5566
        .all(|s| s.path != "img.bin"));
5567
5568
    // Keeping candidate 3 settles it.
5569
    let author = repo.author();
5570
    let edits = [FileEdit {
5571
        path: "img.bin".into(),
5572
        content: Some(blob(3)),
5573
    }];
5574
    let c = repo
5575
        .build_change(&heads, &edits, "keep three", author)
5576
        .unwrap();
5577
    assert_eq!(c.kind, ChangeKind::Resolution);
5578
    let mut st = repo.load_state(&heads).unwrap();
5579
    for d in &c.deps {
5580
        assert!(st.contains(d));
5581
    }
5582
    assert!(
5583
        heads.iter().all(|h| c.deps.contains(h)),
5584
        "depends on both contributors"
5585
    );
5586
    st.add(c).unwrap();
5587
    let after = st.materialize();
5588
    assert!(!after.is_conflicted());
5589
    assert_eq!(
5590
        after.files["img.bin"].content,
5591
        FileContent::Opaque {
5592
            blobs: vec![Repo::blob_ref(&blob(3))]
5593
        }
5594
    );
5595
5596
    // New bytes settle it too.
5597
    let edits = [FileEdit {
5598
        path: "img.bin".into(),
5599
        content: Some(blob(9)),
5600
    }];
5601
    let c = repo.build_change(&heads, &edits, "new", author).unwrap();
5602
    let mut st = repo.load_state(&heads).unwrap();
5603
    st.add(c).unwrap();
5604
    assert_eq!(
5605
        st.materialize().files["img.bin"].content,
5606
        FileContent::Opaque {
5607
            blobs: vec![Repo::blob_ref(&blob(9))]
5608
        }
5609
    );
5610
}
5611
5612
/// The history of a range of lines (spec §27): the changes that wrote
5613
/// or deleted its atoms, or deleted atoms from between them; edits outside
5614
/// the range and changes the range's lines survived are not in it.
5615
#[test]
5616
fn line_ranges_have_exact_histories() {
5617
    hermetic();
5618
    let dir = tempfile::tempdir().unwrap();
5619
    let root = dir.path();
5620
    let repo = Repo::init(root).unwrap().with_home(root.join("home"));
5621
    write(root, "f.rs", b"use x;\nfn a() {\n  one();\n  two();\n}\n");
5622
    let base = repo.commit("add f", &[]).unwrap();
5623
    write(root, "f.rs", b"use y;\nfn a() {\n  one();\n  two();\n}\n");
5624
    let outside = repo.commit("change the import", &[]).unwrap();
5625
    write(root, "f.rs", b"use y;\nfn a() {\n  ONE();\n  two();\n}\n");
5626
    let inside = repo.commit("edit a line of a", &[]).unwrap();
5627
    write(root, "f.rs", b"use y;\nfn a() {\n  ONE();\n}\n");
5628
    let deleted = repo.commit("delete a line of a", &[]).unwrap();
5629
    write(root, "f.rs", b"use y;\nfn a() {\n  ONE();\n}\nfn b() {}\n");
5630
    let after = repo.commit("add b after a", &[]).unwrap();
5631
    let heads = repo.bookmark_heads().unwrap();
5632
5633
    // Lines 2..4 are `fn a() {`, `ONE();`, `}` now.
5634
    let hist: Vec<ChangeHash> = repo
5635
        .line_history(&heads, "f.rs", 2, 4)
5636
        .unwrap()
5637
        .iter()
5638
        .map(|e| e.hash)
5639
        .collect();
5640
    for (h, what) in [
5641
        (base, "wrote it"),
5642
        (inside, "edited a line"),
5643
        (deleted, "deleted a line from inside"),
5644
    ] {
5645
        assert!(hist.contains(&h), "{what}");
5646
    }
5647
    for (h, what) in [(outside, "an edit above"), (after, "an addition below")] {
5648
        assert!(!hist.contains(&h), "{what}");
5649
    }
5650
    assert_eq!(hist[0], deleted, "newest first");
5651
    // One line: only what touched it.
5652
    let one: Vec<ChangeHash> = repo
5653
        .line_history(&heads, "f.rs", 1, 1)
5654
        .unwrap()
5655
        .iter()
5656
        .map(|e| e.hash)
5657
        .collect();
5658
    assert!(one.contains(&outside) && !one.contains(&inside));
5659
    assert!(repo.line_history(&heads, "f.rs", 3, 9).is_err());
5660
    assert!(repo.line_history(&heads, "f.rs", 0, 1).is_err());
5661
    assert!(repo.line_history(&heads, "nope.rs", 1, 1).is_err());
5662
}
5663
5664
#[test]
5665
fn receipts_are_kept_with_their_state_and_verified() {
5666
    use crate::receipt::{Receipt, SignedReceipt};
5667
    hermetic();
5668
    let dir = tempfile::tempdir().unwrap();
5669
    let root = dir.path();
5670
    let repo = Repo::init(root).unwrap().with_home(root.join("home"));
5671
    write(root, "a.txt", b"1\n");
5672
    repo.commit("A", &[]).unwrap();
5673
    let heads = repo.bookmark_heads().unwrap();
5674
    let state = repo
5675
        .store()
5676
        .put_state(&StateObject::new(heads.clone()))
5677
        .unwrap();
5678
    let out = repo.store_blob(b"built\n").unwrap();
5679
    let receipt = Receipt {
5680
        job_name: "build".into(),
5681
        pipeline_hash: ObjectRef([1; 32]),
5682
        scope_tree_hash: ObjectRef([2; 32]),
5683
        inputs: vec![],
5684
        environment: ObjectRef([3; 32]),
5685
        outputs: vec![out],
5686
        exit_code: 0,
5687
        duration_ms: 42,
5688
    };
5689
    let sk = SecretKey::generate();
5690
    let runner = sk.identity("earth-1", "runner@earth", 1);
5691
    let sr = SignedReceipt::sign(
5692
        receipt.clone(),
5693
        repo.id().unwrap(),
5694
        state,
5695
        "demo#1",
5696
        &runner,
5697
        &sk,
5698
    );
5699
5700
    let r = repo.add_receipt(&sr).unwrap();
5701
    let found = repo.receipts(&heads).unwrap();
5702
    assert_eq!(found.len(), 1);
5703
    assert_eq!(found[0].attest, r);
5704
    assert_eq!(found[0].signed, sr);
5705
    assert!(found[0].problem.is_none() && !found[0].revoked);
5706
    assert!(repo.receipts(&[ObjectRef([5; 32])]).unwrap().is_empty());
5707
5708
    // Another repository's receipt, or a forged one, is refused.
5709
    let elsewhere = SignedReceipt::sign(receipt.clone(), [0; 16], state, "x", &runner, &sk);
5710
    assert!(repo
5711
        .add_receipt(&elsewhere)
5712
        .unwrap_err()
5713
        .to_string()
5714
        .contains("another repository"));
5715
    let mut forged = sr.clone();
5716
    forged.receipt.exit_code = 1;
5717
    assert!(repo
5718
        .add_receipt(&forged)
5719
        .unwrap_err()
5720
        .to_string()
5721
        .contains("does not verify"));
5722
5723
    // A receipt signed by a short-lived key keeps its certificate and the
5724
    // issuer's identity, and reads back with them (oxygenhub#241).
5725
    let hub_sk = SecretKey::generate();
5726
    let hub = hub_sk.identity("oxygenhub.io", "[email protected]", 1);
5727
    let job_sk = SecretKey::generate();
5728
    let job = job_sk.identity("job 2 test", "[email protected]", 1);
5729
    let mut test_receipt = receipt.clone();
5730
    test_receipt.job_name = "test".into();
5731
    let plain = SignedReceipt::sign(
5732
        test_receipt,
5733
        repo.id().unwrap(),
5734
        state,
5735
        "demo#2",
5736
        &job,
5737
        &job_sk,
5738
    );
5739
    let now = plain.attest.hlc.wall_ms;
5740
    let cert = crate::cert::SignedCertificate::sign(
5741
        crate::cert::Certificate {
5742
            key: job.clone(),
5743
            issuer: hub.hash(),
5744
            subject: "repo:andy/demo:bookmark:main".into(),
5745
            claims: vec![],
5746
            scope: crate::identity::Scope::SEAL,
5747
            not_before: now - 1_000,
5748
            expires: now + 600_000,
5749
        },
5750
        &hub,
5751
        &hub_sk,
5752
    );
5753
    let certified = plain.with_certificate(cert, hub.clone());
5754
    repo.add_receipt(&certified).unwrap();
5755
    let found = repo.receipts(&heads).unwrap();
5756
    let got = found
5757
        .iter()
5758
        .find(|i| i.signed.receipt.job_name == "test")
5759
        .unwrap();
5760
    assert_eq!(got.signed, certified);
5761
    assert!(got.problem.is_none(), "{:?}", got.problem);
5762
5763
    // gc keeps the receipts, their runners, the certificate and its issuer,
5764
    // and the output while the state lives.
5765
    repo.gc(true).unwrap();
5766
    let found = repo.receipts(&heads).unwrap();
5767
    assert_eq!(found.len(), 2);
5768
    let got = found
5769
        .iter()
5770
        .find(|i| i.signed.receipt.job_name == "test")
5771
        .unwrap();
5772
    assert_eq!(got.signed, certified, "the certificate survives gc");
5773
    assert!(got.problem.is_none());
5774
    assert_eq!(repo.read_blob(&out).unwrap(), b"built\n");
5775
    assert!(repo.fsck().unwrap().problems.is_empty());
5776
}
5777
5778
#[test]
5779
fn status_leaves_an_unchanged_manifest_alone() {
5780
    hermetic();
5781
    let dir = tempfile::tempdir().unwrap();
5782
    let root = dir.path();
5783
    let repo = Repo::init(root).unwrap().with_home(root.join("home"));
5784
    write(root, "a.txt", b"1\n");
5785
    write(root, "b.txt", b"2\n");
5786
    repo.commit("A", &[]).unwrap();
5787
    // Files last touched well outside the racy window.
5788
    let old = std::time::SystemTime::now() - std::time::Duration::from_secs(60);
5789
    for f in ["a.txt", "b.txt"] {
5790
        fs::File::options()
5791
            .write(true)
5792
            .open(root.join(f))
5793
            .unwrap()
5794
            .set_modified(old)
5795
            .unwrap();
5796
    }
5797
    repo.snapshot_status("status").unwrap();
5798
    let path = repo.manifest_path();
5799
    let first = fs::read(&path).unwrap();
5800
    repo.snapshot_status("status").unwrap();
5801
    assert_eq!(
5802
        fs::read(&path).unwrap(),
5803
        first,
5804
        "an unchanged tree does not rewrite the manifest"
5805
    );
5806
    // A change rewrites it.
5807
    write(root, "a.txt", b"1\n2\n");
5808
    repo.snapshot_status("status").unwrap();
5809
    assert_ne!(fs::read(&path).unwrap(), first);
5810
}
5811
5812
#[test]
5813
fn large_text_files_travel_and_survive_gc_as_text_blobs() {
5814
    hermetic();
5815
    let dir = tempfile::tempdir().unwrap();
5816
    let root = dir.path();
5817
    let origin_path = root.join("origin");
5818
    Repo::init(&origin_path).unwrap();
5819
    let origin_url = origin_path.to_string_lossy().to_string();
5820
    let a = Repo::clone(&origin_url, &root.join("a")).unwrap();
5821
    let big: String = (0..5000).map(|i| format!("line {i}\n")).collect();
5822
    write(&root.join("a"), "big.txt", big.as_bytes());
5823
    write(&root.join("a"), "small.txt", b"small\n");
5824
    let h1 = a.commit("large", &[]).unwrap();
5825
    let (_, body) = a.store().get(&h1).unwrap();
5826
    assert!(body.len() < 2048, "the change is {} bytes", body.len());
5827
    assert!(a.push("origin", false).unwrap()[0].ok);
5828
5829
    // A clone reads the text from the blobs that came with the change.
5830
    let b = Repo::clone(&origin_url, &root.join("b")).unwrap();
5831
    assert_eq!(fs::read(root.join("b/big.txt")).unwrap(), big.as_bytes());
5832
    // An edit in the middle of the stored insert is an ordinary change.
5833
    let edited = big.replace("line 2500\n", "line 2500, edited\n");
5834
    write(&root.join("b"), "big.txt", edited.as_bytes());
5835
    let h2 = b.commit("edit", &[]).unwrap();
5836
    assert!(b.store().get_change(&h2).unwrap().edits.len() <= 2);
5837
    assert!(b.push("origin", false).unwrap()[0].ok);
5838
    assert!(a.pull("origin").unwrap().checked_out);
5839
    assert_eq!(fs::read(root.join("a/big.txt")).unwrap(), edited.as_bytes());
5840
    assert_eq!(
5841
        a.fsck().unwrap().errors(),
5842
        0,
5843
        "{:?}",
5844
        a.fsck().unwrap().problems
5845
    );
5846
5847
    // With zero retention gc keeps the text blobs of every kept change.
5848
    let mut a = Repo::open(&root.join("a")).unwrap();
5849
    a.config.set("core.op-retention", "0").unwrap();
5850
    a.save_config().unwrap();
5851
    let a = Repo::open(&root.join("a")).unwrap();
5852
    a.gc(true).unwrap();
5853
    let a = Repo::open(&root.join("a")).unwrap();
5854
    assert_eq!(a.store().get_change(&h1).unwrap().message, "large");
5855
    assert_eq!(
5856
        a.fsck().unwrap().errors(),
5857
        0,
5858
        "{:?}",
5859
        a.fsck().unwrap().problems
5860
    );
5861
    // And a clone of the packed repository reads them from its packs.
5862
    let c = Repo::clone(&root.join("a").to_string_lossy(), &root.join("c")).unwrap();
5863
    assert_eq!(fs::read(root.join("c/big.txt")).unwrap(), edited.as_bytes());
5864
    drop(c);
5865
}
5866
5867
#[test]
5868
fn operations_that_both_replace_a_working_copy_are_not_merged() {
5869
    hermetic();
5870
    let dir = tempfile::tempdir().unwrap();
5871
    let root = dir.path();
5872
    let repo = Repo::init(root).unwrap();
5873
    write(root, "a.txt", b"a\n");
5874
    let a = repo.commit("a", &[]).unwrap();
5875
    write(root, "b.txt", b"b\n");
5876
    repo.commit("b", &[]).unwrap();
5877
    let (x, op) = repo.head_op().unwrap();
5878
    let ws = *op.view.workspaces.keys().next().unwrap();
5879
    let mut one = op.view.clone();
5880
    one.workspaces.insert(ws, a);
5881
    let mut two = op.view.clone();
5882
    two.workspaces.insert(ws, ObjectRef([7; 32]));
5883
    let first = repo.record_op(&[x], "one", one).unwrap();
5884
    let e = repo.record_op(&[x], "two", two).unwrap_err();
5885
    assert!(
5886
        e.to_string()
5887
            .contains("changed this working copy at the same time"),
5888
        "{e}"
5889
    );
5890
    assert_eq!(
5891
        repo.head_op().unwrap().0,
5892
        first,
5893
        "the second is not recorded"
5894
    );
5895
}
5896
5897
/// Metalgear, 2026-09-29 (oxygen#36): a status run while a bookmark switch
5898
/// rewrote the working copy recorded the half-written files as edits, and
5899
/// its view replaced the switch's.
5900
#[test]
5901
fn a_snapshot_during_a_switch_never_records_the_switch_as_edits() {
5902
    hermetic();
5903
    let dir = tempfile::tempdir().unwrap();
5904
    let root = dir.path().to_path_buf();
5905
    let mut repo = Repo::init(&root).unwrap();
5906
    write(&root, "keep.txt", b"keep\n");
5907
    repo.commit("base", &[]).unwrap();
5908
    repo.bookmark_create("small", None).unwrap();
5909
    for i in 0..300 {
5910
        write(
5911
            &root,
5912
            &format!("many/f{i}.txt"),
5913
            format!("file {i}\n").as_bytes(),
5914
        );
5915
    }
5916
    repo.commit("many", &[]).unwrap();
5917
    let stop = std::sync::Arc::new(std::sync::atomic::AtomicBool::new(false));
5918
    let watcher = {
5919
        let (root, stop) = (root.clone(), stop.clone());
5920
        std::thread::spawn(move || {
5921
            let r = Repo::open(&root).unwrap();
5922
            let mut ran = 0;
5923
            while !stop.load(std::sync::atomic::Ordering::Relaxed) {
5924
                if r.snapshot_status("oxy status").is_ok() {
5925
                    ran += 1;
5926
                }
5927
            }
5928
            ran
5929
        })
5930
    };
5931
    for i in 0..20 {
5932
        let to = if i % 2 == 0 { "small" } else { "main" };
5933
        repo.bookmark_switch(to, false).unwrap();
5934
    }
5935
    stop.store(true, std::sync::atomic::Ordering::Relaxed);
5936
    assert!(watcher.join().unwrap() > 0, "the watcher snapshotted");
5937
    // Back on main, clean, with every file where main has it.
5938
    let repo = Repo::open(&root).unwrap();
5939
    let s = repo.snapshot_status("oxy status").unwrap();
5940
    assert!(s.statuses.is_empty(), "{:?}", statuses(&s));
5941
    assert!(s.wc.edits.is_empty() && s.wc.tree_ops.is_empty());
5942
    assert_eq!(s.wc.deps, repo.bookmark_heads().unwrap());
5943
    assert!(root.join("many/f299.txt").exists());
5944
}
5945
5946
/// Metalgear, 2026-09-29 (oxygen#38): a parent's `bookmark switch --carry`
5947
/// put a subrepo that was ahead of its pin back at the pin and moved the
5948
/// subrepo's own bookmark backwards.
5949
#[test]
5950
fn a_parent_switch_with_carry_leaves_a_subrepo_ahead_of_its_pin_alone() {
5951
    hermetic();
5952
    let dir = tempfile::tempdir().unwrap();
5953
    let root = dir.path();
5954
    Repo::init(&root.join("lib-origin")).unwrap();
5955
    let lib_url = root.join("lib-origin").to_string_lossy().to_string();
5956
    let lib = Repo::clone(&lib_url, &root.join("lib")).unwrap();
5957
    write(&root.join("lib"), "lib.txt", b"v1\n");
5958
    lib.commit("lib v1", &[]).unwrap();
5959
    assert!(lib.push("origin", false).unwrap()[0].ok);
5960
5961
    let app_dir = root.join("app");
5962
    let mut app = Repo::init(&app_dir).unwrap();
5963
    write(&app_dir, "main.txt", b"app\n");
5964
    app.submodule_add(&lib_url, "libs/lib", None).unwrap();
5965
    app.commit("app with lib", &[]).unwrap();
5966
    app.bookmark_create("feature", None).unwrap();
5967
5968
    // New work in the subrepo, not yet pinned by the parent.
5969
    let nested_dir = app_dir.join("libs/lib");
5970
    let nested = Repo::open(&nested_dir).unwrap();
5971
    write(&nested_dir, "new.txt", b"new\n");
5972
    let l2 = nested.commit("lib: new file", &[]).unwrap();
5973
    drop(nested);
5974
5975
    let (_, carried) = app.bookmark_switch_carry("feature").unwrap();
5976
    assert!(carried.contains(&"libs/lib".to_string()), "{carried:?}");
5977
    let nested = Repo::open(&nested_dir).unwrap();
5978
    assert!(
5979
        nested.bookmark_heads().unwrap().contains(&l2),
5980
        "its bookmark kept its work"
5981
    );
5982
    assert!(nested_dir.join("new.txt").exists(), "and its files");
5983
    let s = app.snapshot("status").unwrap();
5984
    assert_eq!(
5985
        statuses(&s),
5986
        vec![("libs/lib".to_string(), ChangeStatus::Modified)]
5987
    );
5988
}
5989
5990
/// oxygen#29 (metalgear, rstar-api): after a proposal landed on the hub,
5991
/// moving `main` to a change this clone had pushed on another bookmark,
5992
/// the first `pull` said "Already up to date" while `main` was behind.
5993
#[test]
5994
fn pull_takes_a_remote_move_to_changes_already_here() {
5995
    hermetic();
5996
    let dir = tempfile::tempdir().unwrap();
5997
    let root = dir.path();
5998
    let origin_path = root.join("origin");
5999
    let origin = Repo::init(&origin_path).unwrap();
6000
    let url = origin_path.to_string_lossy().to_string();
6001
    let mut b = Repo::clone(&url, &root.join("b")).unwrap();
6002
    write(&root.join("b"), "base.txt", b"base\n");
6003
    b.commit("base", &[]).unwrap();
6004
    assert!(b.push("origin", false).unwrap()[0].ok);
6005
6006
    // A feature bookmark with one change, pushed.
6007
    b.bookmark_create("feat", None).unwrap();
6008
    b.bookmark_switch("feat", false).unwrap();
6009
    write(&root.join("b"), "x.txt", b"x\n");
6010
    let x = b.commit("x", &[]).unwrap();
6011
    assert!(b.push("origin", false).unwrap()[0].ok);
6012
    b.bookmark_switch("main", false).unwrap();
6013
6014
    // The remote lands it: its main moves to the feature's state.
6015
    let feat = origin
6016
        .store()
6017
        .get_state(&origin.view().unwrap().bookmarks["feat"])
6018
        .unwrap()
6019
        .heads;
6020
    origin.bookmark_set("main", &feat).unwrap();
6021
6022
    let r = b.pull("origin").unwrap();
6023
    assert!(r.changed, "{r:?}");
6024
    assert!(r.heads.contains(&x) || b.load_state(&r.heads).unwrap().contains(&x));
6025
    let main = b
6026
        .bookmarks()
6027
        .unwrap()
6028
        .into_iter()
6029
        .find(|m| m.name == "main")
6030
        .unwrap();
6031
    assert_eq!(main.behind, Some(0), "{main:?}");
6032
}
6033
6034
/// oxygen#48: a remote's bookmarks are names here (`origin/NAME`); switching
6035
/// to one only the remote has makes a local bookmark from it; a pull moves
6036
/// every local bookmark the remote has too; a clone checks out the remote's
6037
/// default bookmark.
6038
#[test]
6039
fn remote_bookmarks_are_named_switched_to_pulled_and_cloned() {
6040
    hermetic();
6041
    let dir = tempfile::tempdir().unwrap();
6042
    let root = dir.path();
6043
    let origin_path = root.join("origin");
6044
    let mut origin = Repo::init(&origin_path).unwrap();
6045
    let url = origin_path.to_string_lossy().to_string();
6046
    let mut a = Repo::clone(&url, &root.join("a")).unwrap();
6047
    write(&root.join("a"), "base.txt", b"base\n");
6048
    a.commit("base", &[]).unwrap();
6049
    assert!(a.push("origin", false).unwrap()[0].ok);
6050
    a.bookmark_create("develop", None).unwrap();
6051
    a.bookmark_switch("develop", false).unwrap();
6052
    write(&root.join("a"), "base.txt", b"base\nd1\n");
6053
    let d1 = a.commit("d1", &[]).unwrap();
6054
    assert!(a.push("origin", false).unwrap()[0].ok);
6055
6056
    // A clone has main only; origin/develop is a name all the same.
6057
    let c_root = root.join("c");
6058
    let mut c = Repo::clone(&url, &c_root).unwrap();
6059
    assert_eq!(c.config.bookmark, "main");
6060
    assert!(!c.view().unwrap().bookmarks.contains_key("develop"));
6061
    assert_eq!(c.resolve_heads("origin/develop").unwrap(), vec![d1]);
6062
    assert_eq!(c.resolve_change("origin/develop").unwrap(), d1);
6063
    assert_eq!(c.remote_only_bookmarks().unwrap().len(), 1);
6064
6065
    // Switching makes the local bookmark from origin's.
6066
    c.bookmark_switch("develop", false).unwrap();
6067
    assert_eq!(c.config.bookmark, "develop");
6068
    assert_eq!(c.bookmark_heads().unwrap(), vec![d1]);
6069
    assert_eq!(fs::read(c_root.join("base.txt")).unwrap(), b"base\nd1\n");
6070
    assert!(c.remote_only_bookmarks().unwrap().is_empty());
6071
    assert!(c.bookmark_switch("nowhere", false).is_err());
6072
6073
    // Both bookmarks move on the remote; one pull takes both.
6074
    write(&root.join("a"), "base.txt", b"base\nd1\nd2\n");
6075
    let d2 = a.commit("d2", &[]).unwrap();
6076
    assert!(a.push("origin", false).unwrap()[0].ok);
6077
    a.bookmark_switch("main", false).unwrap();
6078
    write(&root.join("a"), "m.txt", b"m\n");
6079
    let m = a.commit("m", &[]).unwrap();
6080
    assert!(a.push("origin", false).unwrap()[0].ok);
6081
    let r = c.pull("origin").unwrap();
6082
    assert!(r.changed && r.checked_out, "{r:?}");
6083
    assert_eq!(r.heads, vec![d2]);
6084
    assert_eq!(r.others, vec!["main".to_string()]);
6085
    assert!(c.resolve_heads("main").unwrap().contains(&m));
6086
    assert_eq!(
6087
        fs::read(c_root.join("base.txt")).unwrap(),
6088
        b"base\nd1\nd2\n"
6089
    );
6090
    let again = c.pull("origin").unwrap();
6091
    assert!(!again.changed && again.others.is_empty(), "{again:?}");
6092
6093
    // A clone checks out the remote's default bookmark.
6094
    origin.config.set("workspace.bookmark", "develop").unwrap();
6095
    origin.save_config().unwrap();
6096
    let e = Repo::clone(&url, &root.join("e")).unwrap();
6097
    assert_eq!(e.config.bookmark, "develop");
6098
    assert_eq!(e.bookmark_heads().unwrap(), vec![d2]);
6099
    let reopened = Repo::open(&root.join("e")).unwrap();
6100
    assert_eq!(reopened.config.bookmark, "develop");
6101
    // REMOTE/NAME names the remote's bookmark to switch to.
6102
    let mut e = reopened;
6103
    e.bookmark_switch("origin/main", false).unwrap();
6104
    assert_eq!(e.config.bookmark, "main");
6105
    assert!(e.bookmark_heads().unwrap().contains(&m));
6106
}
6107
6108
/// oxygen#51, #52: --at-op reads an earlier view and refuses changes;
6109
/// op restore goes back to an operation, files included, and undo takes
6110
/// the restore back whole; op revert undoes one operation alone; each
6111
/// operation's changes are described from the views.
6112
#[test]
6113
fn operations_can_be_read_restored_and_reverted() {
6114
    hermetic();
6115
    let dir = tempfile::tempdir().unwrap();
6116
    let root = dir.path();
6117
    let repo = Repo::init(root).unwrap();
6118
    write(root, "a.txt", b"a\n");
6119
    let first = repo.commit("first", &[]).unwrap();
6120
    write(root, "a.txt", b"a\nb\n");
6121
    let second = repo.commit("second", &[]).unwrap();
6122
    let at_second = repo.head_op().unwrap().0.to_hex();
6123
    repo.bookmark_create("keep", None).unwrap();
6124
    let created = repo.head_op().unwrap().0.to_hex();
6125
    write(root, "n.txt", b"n\n");
6126
    let third = repo.commit("third", &[]).unwrap();
6127
6128
    // What each operation changed.
6129
    let ops = repo.op_log().unwrap();
6130
    let changes = repo.view_changes(&ops[1].1.view, &ops[0].1.view).unwrap();
6131
    assert!(
6132
        changes
6133
            .iter()
6134
            .any(|c| matches!(c, ViewChange::BookmarkMoved { name, .. } if name == "main")),
6135
        "{changes:?}"
6136
    );
6137
    assert!(changes
6138
        .iter()
6139
        .any(|c| matches!(c, ViewChange::WorkingCopy { .. })));
6140
6141
    // Reading at an earlier operation.
6142
    let old = Repo::open(root).unwrap().at_op(&at_second[..10]).unwrap();
6143
    assert_eq!(old.bookmark_heads().unwrap(), vec![second]);
6144
    assert!(!old.view().unwrap().bookmarks.contains_key("keep"));
6145
    write(root, "z.txt", b"z\n");
6146
    assert!(old.commit("refused", &[]).is_err(), "--at-op is read-only");
6147
    fs::remove_file(root.join("z.txt")).unwrap();
6148
    assert!(repo.resolve_op("zz").is_err());
6149
    assert_eq!(repo.resolve_op("@").unwrap().0, repo.head_op().unwrap().0);
6150
6151
    // Restore goes back, files and all; undo takes it back whole.
6152
    repo.op_restore(&at_second, false).unwrap();
6153
    assert_eq!(repo.bookmark_heads().unwrap(), vec![second]);
6154
    assert!(!root.join("n.txt").exists());
6155
    repo.undo().unwrap();
6156
    let mut heads = repo.bookmark_heads().unwrap();
6157
    heads.sort();
6158
    let mut want = vec![second, third];
6159
    want.sort();
6160
    assert_eq!(heads, want);
6161
    assert!(
6162
        root.join("n.txt").exists(),
6163
        "the files came back with the undo"
6164
    );
6165
6166
    // Revert the bookmark's creation alone: the commit after it stays.
6167
    let r = repo.op_revert(&created).unwrap();
6168
    assert_eq!(r.reverted, vec!["keep".to_string()]);
6169
    assert!(!repo.view().unwrap().bookmarks.contains_key("keep"));
6170
    assert!(repo
6171
        .load_state(&repo.bookmark_heads().unwrap())
6172
        .unwrap()
6173
        .contains(&third));
6174
    assert!(repo.op_revert(&created).is_err(), "nothing left to revert");
6175
    let _ = first;
6176
}
6177
6178
/// oxygen#41: with uncommitted work, a status after a snapshot is answered
6179
/// from the status cache while every file is as the snapshot left it, and
6180
/// from a snapshot again as soon as one is not.
6181
#[test]
6182
fn status_with_uncommitted_work_comes_from_the_cache_until_a_file_changes() {
6183
    hermetic();
6184
    let dir = tempfile::tempdir().unwrap();
6185
    let root = dir.path();
6186
    let repo = Repo::init(root).unwrap();
6187
    write(root, "a.txt", b"a\n");
6188
    write(root, "b.txt", b"b\n");
6189
    repo.commit("base", &[]).unwrap();
6190
    assert_eq!(repo.status_by_manifest().unwrap(), Some(vec![]), "clean");
6191
6192
    write(root, "a.txt", b"a\nmore\n");
6193
    assert_eq!(
6194
        repo.status_by_manifest().unwrap(),
6195
        None,
6196
        "no snapshot of the edit yet"
6197
    );
6198
    let snap = repo.snapshot_status("oxy status").unwrap();
6199
    assert_eq!(snap.statuses.len(), 1);
6200
    let cached = repo
6201
        .status_by_manifest()
6202
        .unwrap()
6203
        .expect("answered from the cache");
6204
    assert_eq!(cached.len(), 1);
6205
    assert_eq!(
6206
        (cached[0].path.as_str(), cached[0].status),
6207
        ("a.txt", ChangeStatus::Modified)
6208
    );
6209
6210
    // Any further change sends status back to a snapshot.
6211
    write(root, "a.txt", b"a\nmore\nand more\n");
6212
    assert_eq!(repo.status_by_manifest().unwrap(), None, "edited again");
6213
    repo.snapshot_status("oxy status").unwrap();
6214
    assert!(repo.status_by_manifest().unwrap().is_some());
6215
    write(root, "new.txt", b"n\n");
6216
    assert_eq!(repo.status_by_manifest().unwrap(), None, "a file added");
6217
    fs::remove_file(root.join("new.txt")).unwrap();
6218
    assert!(
6219
        repo.status_by_manifest().unwrap().is_some(),
6220
        "back as it was"
6221
    );
6222
    fs::remove_file(root.join("b.txt")).unwrap();
6223
    assert_eq!(repo.status_by_manifest().unwrap(), None, "a file removed");
6224
    write(root, "b.txt", b"b\n");
6225
6226
    // A commit leaves nothing uncommitted: clean again, no cache needed.
6227
    repo.snapshot_status("oxy status").unwrap();
6228
    repo.commit("more", &[]).unwrap();
6229
    assert_eq!(repo.status_by_manifest().unwrap(), Some(vec![]));
6230
}
6231
6232
/// oxygen#41: while the status cache holds, the working copy's diff is
6233
/// rendered from the stored working-copy change, and says exactly what a
6234
/// snapshot's diff says.
6235
#[test]
6236
fn the_working_copy_diff_from_the_cache_matches_a_snapshot() {
6237
    hermetic();
6238
    let dir = tempfile::tempdir().unwrap();
6239
    let root = dir.path();
6240
    let repo = Repo::init(root).unwrap();
6241
    write(root, "a.txt", b"one\ntwo\nthree\n");
6242
    write(root, "gone.txt", b"bye\n");
6243
    repo.commit("base", &[]).unwrap();
6244
    write(root, "a.txt", b"one\n2\nthree\nfour\n");
6245
    write(root, "new.txt", b"hello\n");
6246
    fs::remove_file(root.join("gone.txt")).unwrap();
6247
    let snap = repo.snapshot_status("oxy status").unwrap();
6248
    let slow = render_change(&snap.wc, &snap.base, &snap.base_snapshot);
6249
    assert!(
6250
        repo.status_by_manifest().unwrap().is_some(),
6251
        "the cache holds"
6252
    );
6253
    let (wc, base, snapshot) = repo.working_copy_with_base().unwrap();
6254
    assert_eq!(render_change(&wc, &base, &snapshot), slow);
6255
    assert_eq!(repo.diff_files(None).unwrap().len(), 3);
6256
}
6257
6258
/// oxygen#41: a manifest written from a walk keeps every directory's time;
6259
/// while none has moved, the check stats the tracked files without listing
6260
/// the tree, and a file added or removed anywhere moves its directory's
6261
/// time, so the tree is listed again.
6262
#[test]
6263
fn the_manifest_check_skips_listing_while_no_directory_changed() {
6264
    hermetic();
6265
    let dir = tempfile::tempdir().unwrap();
6266
    let root = dir.path();
6267
    let repo = Repo::init(root).unwrap();
6268
    write(root, "a.txt", b"a\n");
6269
    write(root, "sub/deep/b.txt", b"b\n");
6270
    repo.commit("base", &[]).unwrap();
6271
    // Out of the racy window: every file and directory a minute old.
6272
    let old = std::time::SystemTime::now() - std::time::Duration::from_secs(60);
6273
    for p in ["a.txt", "sub/deep/b.txt", "sub/deep", "sub", ""] {
6274
        fs::File::open(root.join(p))
6275
            .unwrap()
6276
            .set_modified(old)
6277
            .unwrap();
6278
    }
6279
    repo.snapshot_status("oxy status").unwrap();
6280
    repo.write_manifest(false, false).unwrap();
6281
    let m = repo.read_manifest().unwrap().unwrap().2;
6282
    assert!(m.dirs.iter().any(|(d, _)| d == "sub/deep"), "{:?}", m.dirs);
6283
    assert_eq!(
6284
        repo.disk_differs_by_dirs(&m),
6285
        Some(false),
6286
        "no listing needed"
6287
    );
6288
    assert_eq!(repo.status_by_manifest().unwrap(), Some(vec![]));
6289
6290
    // A same-size edit with a new time: found by its stat.
6291
    write(root, "sub/deep/b.txt", b"c\n");
6292
    assert_eq!(repo.disk_differs_by_dirs(&m), Some(true));
6293
    write(root, "sub/deep/b.txt", b"b\n");
6294
    fs::File::open(root.join("sub/deep/b.txt"))
6295
        .unwrap()
6296
        .set_modified(old)
6297
        .unwrap();
6298
    assert_eq!(repo.disk_differs_by_dirs(&m), Some(false));
6299
6300
    // A new file moves its directory's time: the tree must be listed.
6301
    write(root, "sub/deep/new.txt", b"n\n");
6302
    assert_eq!(repo.disk_differs_by_dirs(&m), None);
6303
    assert_eq!(repo.status_by_manifest().unwrap(), None);
6304
    fs::remove_file(root.join("sub/deep/new.txt")).unwrap();
6305
    // A removed one too.
6306
    fs::remove_file(root.join("a.txt")).unwrap();
6307
    assert_eq!(repo.disk_differs_by_dirs(&m), None);
6308
}
6309
6310
/// oxygen#41: a commit right after a status takes the snapshot the status
6311
/// left (the status cache holds) rather than walking again, and commits
6312
/// exactly what a snapshot would have.
6313
#[test]
6314
fn a_commit_after_a_status_uses_the_cached_snapshot() {
6315
    hermetic();
6316
    let dir = tempfile::tempdir().unwrap();
6317
    let root = dir.path();
6318
    let repo = Repo::init(root).unwrap();
6319
    write(root, "a.txt", b"a\nb\n");
6320
    write(root, ".oxyattributes", b"*.bin binary\n");
6321
    repo.commit("base", &[]).unwrap();
6322
    write(root, "a.txt", b"a\nB\n");
6323
    write(root, "new.txt", b"new\n");
6324
    let snap = repo.snapshot_status("oxy status").unwrap();
6325
    let cached = repo
6326
        .snapshot_from_cache()
6327
        .unwrap()
6328
        .expect("the cache holds");
6329
    assert_eq!(cached.wc_hash, snap.wc_hash);
6330
    assert_eq!(cached.statuses, snap.statuses);
6331
    assert!(
6332
        !cached.attributes.is_empty(),
6333
        "the .oxyattributes file was read"
6334
    );
6335
    let h = repo.commit("edit", &[]).unwrap();
6336
    let c = repo.store().get_change(&h).unwrap();
6337
    assert_eq!(
6338
        c.tree_ops.len() + c.edits.len(),
6339
        snap.wc.tree_ops.len() + snap.wc.edits.len()
6340
    );
6341
    assert_eq!(
6342
        repo.status_by_manifest().unwrap(),
6343
        Some(vec![]),
6344
        "clean after the commit"
6345
    );
6346
    assert_eq!(fs::read(root.join("a.txt")).unwrap(), b"a\nB\n");
6347
}
6348
6349
/// oxygen#41: a clean check that verified racy entries restamps the
6350
/// manifest, so later checks can trust them, and a same-size rewrite
6351
/// straight afterwards is still found: entries within two seconds of the
6352
/// new time stay racy.
6353
#[test]
6354
fn a_verified_clean_check_restamps_the_manifest_safely() {
6355
    hermetic();
6356
    let dir = tempfile::tempdir().unwrap();
6357
    let root = dir.path();
6358
    let repo = Repo::init(root).unwrap();
6359
    write(root, "a.txt", b"one\n");
6360
    repo.commit("one", &[]).unwrap();
6361
    let before = repo.read_manifest().unwrap().unwrap().2.written_ns;
6362
    assert!(repo.clean_by_manifest().unwrap());
6363
    let after = repo.read_manifest().unwrap().unwrap().2.written_ns;
6364
    assert!(after > before, "restamped");
6365
    write(root, "a.txt", b"two\n");
6366
    assert!(
6367
        !repo.clean_by_manifest().unwrap(),
6368
        "a same-size rewrite is still seen"
6369
    );
6370
}
6371
6372
/// oxygen#35: a history-only state keeps no inserted text. It reads a
6373
/// stored insert's text blob only when it builds that file's graph, and
6374
/// builds the same graph a full load does.
6375
#[test]
6376
fn history_only_states_read_text_only_for_the_graphs_they_build() {
6377
    hermetic();
6378
    let dir = tempfile::tempdir().unwrap();
6379
    let root = dir.path();
6380
    let repo = Repo::init(root).unwrap();
6381
    let big: String = (0..3000).map(|i| format!("big line {i}\n")).collect();
6382
    let other: String = (0..3000).map(|i| format!("other line {i}\n")).collect();
6383
    write(root, "big.txt", big.as_bytes());
6384
    write(root, "other.txt", other.as_bytes());
6385
    let h = repo.commit("two large files", &[]).unwrap();
6386
    write(root, "big.txt", format!("{big}one more\n").as_bytes());
6387
    let h2 = repo.commit("append", &[]).unwrap();
6388
6389
    let full = repo.load_state_full(&[h2]).unwrap().materialize();
6390
    let text = |snap: &crate::state::Snapshot, p: &str| match &snap.files[p].content {
6391
        FileContent::Text { bytes, .. } => bytes.clone(),
6392
        other => panic!("{other:?}"),
6393
    };
6394
    // Built on demand, every graph renders as the full load's.
6395
    let mut hist = repo.load_state_history(&[h2]).unwrap();
6396
    let big_node = full.files["big.txt"].node;
6397
    assert!(hist.graph_key(&big_node).is_some(), "not built yet");
6398
    repo.load_all_graphs(&mut hist).unwrap();
6399
    let rendered = hist.materialize();
6400
    for p in ["big.txt", "other.txt"] {
6401
        assert_eq!(text(&rendered, p), text(&full, p), "{p}");
6402
    }
6403
6404
    // Without other.txt's text blob, history still loads and big.txt still
6405
    // builds: nothing read the other text.
6406
    let (_, texts) = repo.store().get_change_lazy(&h).unwrap();
6407
    assert_eq!(texts.len(), 2);
6408
    let content = |r: &ObjectRef| -> Vec<u8> {
6409
        let blob = crate::objects::Blob::decode(&repo.store().get(r).unwrap().1).unwrap();
6410
        blob.chunks
6411
            .iter()
6412
            .flat_map(|c| repo.store().get(c).unwrap().1)
6413
            .collect()
6414
    };
6415
    let other_text = texts
6416
        .iter()
6417
        .filter_map(|t| match t {
6418
            crate::objects::TextRef::Blob(r, _, _) => Some(*r),
6419
            _ => None,
6420
        })
6421
        .find(|r| content(r).windows(12).any(|w| w == b"other line 1"))
6422
        .unwrap();
6423
    repo.store().remove_loose_for_test(&other_text).unwrap();
6424
    let mut hist = repo.load_state_history(&[h2]).unwrap();
6425
    repo.load_graphs_of(&mut hist, &[big_node]).unwrap();
6426
    assert!(repo
6427
        .load_graphs_of(&mut hist, &[full.files["other.txt"].node])
6428
        .is_err());
6429
}
6430
6431
/// oxygen#35: the first status after a commit read and rendered every
6432
/// file (79 s and more than 14 GB on the Linux tree), because the
6433
/// manifest had no graph keys for files the commit added.
6434
#[test]
6435
fn a_commit_leaves_a_manifest_the_next_status_trusts() {
6436
    use std::os::unix::fs::PermissionsExt;
6437
    hermetic();
6438
    let dir = tempfile::tempdir().unwrap();
6439
    let root = dir.path();
6440
    let repo = Repo::init(root).unwrap();
6441
    let files = ["a.txt", "b.txt", "d/c.txt"];
6442
    for p in files {
6443
        write(root, p, format!("{p}\n").as_bytes());
6444
        let old = std::time::SystemTime::now() - std::time::Duration::from_secs(30);
6445
        fs::File::options()
6446
            .write(true)
6447
            .open(root.join(p))
6448
            .unwrap()
6449
            .set_modified(old)
6450
            .unwrap();
6451
    }
6452
    repo.commit("added", &[]).unwrap();
6453
    let (_, _, m) = repo.read_manifest().unwrap().unwrap();
6454
    assert!(
6455
        m.entries.values().all(|e| e.graph.is_some()),
6456
        "keys recorded at commit"
6457
    );
6458
    // Unreadable files prove the next status reads none of them.
6459
    for p in files {
6460
        fs::set_permissions(root.join(p), fs::Permissions::from_mode(0o000)).unwrap();
6461
    }
6462
    let snap = repo.snapshot_status("status").unwrap();
6463
    for p in files {
6464
        fs::set_permissions(root.join(p), fs::Permissions::from_mode(0o644)).unwrap();
6465
    }
6466
    assert!(!snap.changed && snap.statuses.is_empty());
6467
    assert_eq!(snap.base_snapshot.unrendered.len(), files.len());
6468
}
6469
6470
/// oxygen#35: a checkout reads, renders and writes only the files whose
6471
/// graphs differ, and renders the rest a batch at a time.
6472
#[test]
6473
fn checkout_touches_only_what_differs_and_renders_in_batches() {
6474
    use std::os::unix::fs::PermissionsExt;
6475
    hermetic();
6476
    let dir = tempfile::tempdir().unwrap();
6477
    let root = dir.path();
6478
    let origin = root.join("origin");
6479
    let mut repo = Repo::init(&origin).unwrap();
6480
    // More files than one batch holds.
6481
    let n = 2100;
6482
    let old = std::time::SystemTime::now() - std::time::Duration::from_secs(30);
6483
    for i in 0..n {
6484
        let p = format!("f/{i:04}.txt");
6485
        write(&origin, &p, format!("file {i}\n").as_bytes());
6486
        fs::File::options()
6487
            .write(true)
6488
            .open(origin.join(&p))
6489
            .unwrap()
6490
            .set_modified(old)
6491
            .unwrap();
6492
    }
6493
    repo.commit("many", &[]).unwrap();
6494
    repo.bookmark_create("feature", None).unwrap();
6495
    repo.bookmark_switch("feature", false).unwrap();
6496
    write(&origin, "f/0007.txt", b"changed\n");
6497
    repo.commit("one change", &[]).unwrap();
6498
6499
    // Switching back to main must not read the unchanged files.
6500
    for i in 0..n {
6501
        if i != 7 {
6502
            let p = origin.join(format!("f/{i:04}.txt"));
6503
            fs::set_permissions(&p, fs::Permissions::from_mode(0o000)).unwrap();
6504
        }
6505
    }
6506
    let r = repo.bookmark_switch("main", false).unwrap();
6507
    for i in 0..n {
6508
        let p = origin.join(format!("f/{i:04}.txt"));
6509
        fs::set_permissions(&p, fs::Permissions::from_mode(0o644)).unwrap();
6510
    }
6511
    assert_eq!((r.written, r.removed), (1, 0), "{r:?}");
6512
    assert_eq!(fs::read(origin.join("f/0007.txt")).unwrap(), b"file 7\n");
6513
    assert!(repo.snapshot_status("status").unwrap().statuses.is_empty());
6514
6515
    // A clone renders every file, across batches.
6516
    let c = root.join("clone");
6517
    Repo::clone(&origin.to_string_lossy(), &c).unwrap();
6518
    for i in [0, 2047, 2048, n - 1] {
6519
        assert_eq!(
6520
            fs::read(c.join(format!("f/{i:04}.txt"))).unwrap(),
6521
            format!("file {i}\n").as_bytes()
6522
        );
6523
    }
6524
    let cloned = Repo::open(&c).unwrap();
6525
    assert!(cloned
6526
        .snapshot_status("status")
6527
        .unwrap()
6528
        .statuses
6529
        .is_empty());
6530
}
6531
6532
/// A file written just before the manifest (inside the racy window) is
6533
/// checked by its hash: trusted when equal, caught when edited in place
6534
/// with the same size and time.
6535
#[test]
6536
fn a_racy_manifest_entry_is_checked_by_hash() {
6537
    hermetic();
6538
    let dir = tempfile::tempdir().unwrap();
6539
    let root = dir.path();
6540
    let repo = Repo::init(root).unwrap();
6541
    write(root, "a.txt", b"one\n");
6542
    repo.commit("fresh", &[]).unwrap();
6543
    assert!(repo.clean_by_manifest().unwrap(), "fresh but equal");
6544
    let t = fs::metadata(root.join("a.txt"))
6545
        .unwrap()
6546
        .modified()
6547
        .unwrap();
6548
    write(root, "a.txt", b"two\n");
6549
    fs::File::options()
6550
        .write(true)
6551
        .open(root.join("a.txt"))
6552
        .unwrap()
6553
        .set_modified(t)
6554
        .unwrap();
6555
    assert!(
6556
        !repo.clean_by_manifest().unwrap(),
6557
        "same size and time, other bytes"
6558
    );
6559
    assert_eq!(
6560
        statuses(&repo.snapshot_status("status").unwrap()),
6561
        vec![("a.txt".to_string(), ChangeStatus::Modified)]
6562
    );
6563
}
6564
6565
/// A fetch on one machine moves changes as stored, text blobs among the
6566
/// objects; a change whose text blob did not come is refused, not stored.
6567
#[test]
6568
fn a_raw_bundle_without_a_changes_text_is_refused() {
6569
    hermetic();
6570
    let dir = tempfile::tempdir().unwrap();
6571
    let root = dir.path();
6572
    let a = Repo::init(&root.join("a")).unwrap();
6573
    let big: String = (0..3000).map(|i| format!("line {i}\n")).collect();
6574
    write(&root.join("a"), "big.txt", big.as_bytes());
6575
    let h = a.commit("big", &[]).unwrap();
6576
    let bundle = a.bundle_raw_for(&[h], None).unwrap();
6577
    assert_eq!(bundle.raw_changes.len(), 1);
6578
    assert!(bundle.changes.is_empty());
6579
    let b = Repo::init(&root.join("b")).unwrap();
6580
    let mut without = bundle.clone();
6581
    without.objects.retain(|(ty, _)| *ty != ObjectType::Blob);
6582
    let e = b.import_bundle(&without, false).unwrap_err();
6583
    assert!(e.to_string().contains("came without its text blob"), "{e}");
6584
    assert!(!b.store().has(&h));
6585
    assert_eq!(b.import_bundle(&bundle, false).unwrap(), vec![h]);
6586
    assert_eq!(b.store().get_change(&h).unwrap().message, "big");
6587
}
6588
6589
/// oxygen#30 (vscode): a directory deleted in one line of history and made
6590
/// again was a second node for one Git path, so a file moved into it on
6591
/// another line, where the first node still stood, ended up in two places.
6592
/// An import now brings the directory back rather than make a new one.
6593
#[test]
6594
fn git_import_brings_a_directory_back_rather_than_making_a_second() {
6595
    hermetic();
6596
    if std::process::Command::new("git")
6597
        .arg("--version")
6598
        .output()
6599
        .is_err()
6600
    {
6601
        eprintln!("git not installed; skipping");
6602
        return;
6603
    }
6604
    let dir = tempfile::tempdir().unwrap();
6605
    let root = dir.path();
6606
    let g = root.join("src.git");
6607
    fs::create_dir_all(&g).unwrap();
6608
    let git = |args: &[&str]| -> String {
6609
        let out = std::process::Command::new("git")
6610
            .arg("-C")
6611
            .arg(&g)
6612
            .args([
6613
                "-c",
6614
                "user.name=Grace",
6615
                "-c",
6616
                "[email protected]",
6617
                "-c",
6618
                "commit.gpgsign=false",
6619
            ])
6620
            .args(args)
6621
            .output()
6622
            .unwrap();
6623
        assert!(
6624
            out.status.success(),
6625
            "git {args:?}: {}",
6626
            String::from_utf8_lossy(&out.stderr)
6627
        );
6628
        String::from_utf8_lossy(&out.stdout).trim().to_string()
6629
    };
6630
    git(&["init", "-q", "-b", "main"]);
6631
    write(&g, "d/a.txt", b"a\n");
6632
    write(&g, "c/x.txt", b"x\n");
6633
    git(&["add", "."]);
6634
    git(&["commit", "-qm", "base"]);
6635
    // One line: move x into d while d still stands.
6636
    git(&["checkout", "-qb", "side"]);
6637
    git(&["mv", "c/x.txt", "d/x.txt"]);
6638
    git(&["commit", "-qm", "x into d"]);
6639
    // The other: d goes, comes back, and x moves into it too.
6640
    git(&["checkout", "-q", "main"]);
6641
    git(&["rm", "-q", "d/a.txt"]);
6642
    git(&["commit", "-qm", "d goes"]);
6643
    write(&g, "d/b.txt", b"b\n");
6644
    git(&["add", "."]);
6645
    git(&["commit", "-qm", "d comes back"]);
6646
    git(&["mv", "c/x.txt", "d/x.txt"]);
6647
    git(&["commit", "-qm", "x into d again"]);
6648
    git(&["merge", "-q", "--no-edit", "side"]);
6649
6650
    let repo = Repo::init(&root.join("o")).unwrap();
6651
    repo.import_git(&g, "main").unwrap();
6652
    let v = repo.verify_git_import(&g, "main").unwrap();
6653
    assert!(v.mismatches.is_empty(), "{:?}", v.mismatches);
6654
    let st = repo
6655
        .load_state_history(&repo.bookmark_heads().unwrap())
6656
        .unwrap();
6657
    let view = st.tree().view();
6658
    assert!(view.conflicts.is_empty(), "{:?}", view.conflicts);
6659
    // The directory is the one the first commit made.
6660
    // Commits made in one second tie on time: find the first by its message.
6661
    let first = repo
6662
        .log()
6663
        .unwrap()
6664
        .into_iter()
6665
        .find(|e| e.change.message.starts_with("base"))
6666
        .unwrap();
6667
    let base = repo
6668
        .load_state_history(&[first.hash])
6669
        .unwrap()
6670
        .tree()
6671
        .view();
6672
    assert_eq!(view.entries["d"].node, base.entries["d"].node);
6673
}
6674
6675
/// oxygen#30, the rest: a placement left under a directory another line
6676
/// removed is out of sight, so no diff reaches it; the merge that settles
6677
/// where the file is retires it.
6678
#[test]
6679
fn git_import_merge_retires_a_placement_under_a_removed_directory() {
6680
    hermetic();
6681
    if std::process::Command::new("git")
6682
        .arg("--version")
6683
        .output()
6684
        .is_err()
6685
    {
6686
        eprintln!("git not installed; skipping");
6687
        return;
6688
    }
6689
    let dir = tempfile::tempdir().unwrap();
6690
    let root = dir.path();
6691
    let g = root.join("src.git");
6692
    fs::create_dir_all(&g).unwrap();
6693
    let run = |args: &[&str]| {
6694
        std::process::Command::new("git")
6695
            .arg("-C")
6696
            .arg(&g)
6697
            .args([
6698
                "-c",
6699
                "user.name=Grace",
6700
                "-c",
6701
                "[email protected]",
6702
                "-c",
6703
                "commit.gpgsign=false",
6704
            ])
6705
            .args(args)
6706
            .output()
6707
            .unwrap()
6708
    };
6709
    let git = |args: &[&str]| {
6710
        let out = run(args);
6711
        assert!(
6712
            out.status.success(),
6713
            "git {args:?}: {}",
6714
            String::from_utf8_lossy(&out.stderr)
6715
        );
6716
    };
6717
    git(&["init", "-q", "-b", "main"]);
6718
    write(&g, "c/x.txt", b"x\n");
6719
    write(&g, "keep.txt", b"k\n");
6720
    git(&["add", "."]);
6721
    git(&["commit", "-qm", "base"]);
6722
    // One line renames the file within c; the other moves it out of c,
6723
    // which goes.
6724
    git(&["checkout", "-qb", "side"]);
6725
    git(&["mv", "c/x.txt", "c/y.txt"]);
6726
    git(&["commit", "-qm", "rename within c"]);
6727
    git(&["checkout", "-q", "main"]);
6728
    fs::create_dir_all(g.join("n")).unwrap();
6729
    git(&["mv", "c/x.txt", "n/x.txt"]);
6730
    git(&["commit", "-qm", "move out of c"]);
6731
    // Git cannot merge the two renames; the merge keeps n/x.txt.
6732
    let _ = run(&["merge", "-q", "side"]);
6733
    let _ = run(&[
6734
        "rm",
6735
        "-q",
6736
        "--cached",
6737
        "--ignore-unmatch",
6738
        "c/y.txt",
6739
        "c/x.txt",
6740
    ]);
6741
    let _ = std::fs::remove_dir_all(g.join("c"));
6742
    write(&g, "n/x.txt", b"x\n");
6743
    git(&["add", "-A"]);
6744
    git(&["commit", "-qm", "merge: keep n/x.txt"]);
6745
6746
    let repo = Repo::init(&root.join("o")).unwrap();
6747
    repo.import_git(&g, "main").unwrap();
6748
    let v = repo.verify_git_import(&g, "main").unwrap();
6749
    assert!(v.mismatches.is_empty(), "{:?}", v.mismatches);
6750
    let st = repo
6751
        .load_state_history(&repo.bookmark_heads().unwrap())
6752
        .unwrap();
6753
    let view = st.tree().view();
6754
    assert!(view.conflicts.is_empty(), "{:?}", view.conflicts);
6755
    assert!(view.entries.contains_key("n/x.txt"));
6756
}
6757
6758
/// oxygen#30, orphans: a file added on one line into a directory the other
6759
/// line removed is placed where the tree cannot show it; Git's merge keeps
6760
/// the file, and the import's merge leaves exactly one of it.
6761
#[test]
6762
fn git_import_merge_leaves_no_orphan_behind() {
6763
    hermetic();
6764
    if std::process::Command::new("git")
6765
        .arg("--version")
6766
        .output()
6767
        .is_err()
6768
    {
6769
        eprintln!("git not installed; skipping");
6770
        return;
6771
    }
6772
    let dir = tempfile::tempdir().unwrap();
6773
    let root = dir.path();
6774
    let g = root.join("src.git");
6775
    fs::create_dir_all(&g).unwrap();
6776
    let git = |args: &[&str]| {
6777
        let out = std::process::Command::new("git")
6778
            .arg("-C")
6779
            .arg(&g)
6780
            .args([
6781
                "-c",
6782
                "user.name=Grace",
6783
                "-c",
6784
                "[email protected]",
6785
                "-c",
6786
                "commit.gpgsign=false",
6787
            ])
6788
            .args(args)
6789
            .output()
6790
            .unwrap();
6791
        assert!(
6792
            out.status.success(),
6793
            "git {args:?}: {}",
6794
            String::from_utf8_lossy(&out.stderr)
6795
        );
6796
    };
6797
    git(&["init", "-q", "-b", "main"]);
6798
    write(&g, "d/f.txt", b"f\n");
6799
    write(&g, "keep.txt", b"k\n");
6800
    git(&["add", "."]);
6801
    git(&["commit", "-qm", "base"]);
6802
    git(&["checkout", "-qb", "side"]);
6803
    write(&g, "d/new.txt", b"new\n");
6804
    git(&["add", "."]);
6805
    git(&["commit", "-qm", "add into d"]);
6806
    git(&["checkout", "-q", "main"]);
6807
    git(&["rm", "-q", "d/f.txt"]);
6808
    git(&["commit", "-qm", "d goes"]);
6809
    git(&["merge", "-q", "--no-edit", "side"]);
6810
6811
    let repo = Repo::init(&root.join("o")).unwrap();
6812
    repo.import_git(&g, "main").unwrap();
6813
    let v = repo.verify_git_import(&g, "main").unwrap();
6814
    assert!(v.mismatches.is_empty(), "{:?}", v.mismatches);
6815
    let st = repo
6816
        .load_state_history(&repo.bookmark_heads().unwrap())
6817
        .unwrap();
6818
    let view = st.tree().view();
6819
    assert!(view.conflicts.is_empty(), "{:?}", view.conflicts);
6820
    assert!(view.entries.contains_key("d/new.txt"));
6821
}
6822
6823
/// fsck checks a change's text as the blobs it is stored in, without
6824
/// decoding it: a missing text blob is an error named for the change.
6825
#[test]
6826
fn fsck_names_a_missing_text_blob() {
6827
    hermetic();
6828
    let dir = tempfile::tempdir().unwrap();
6829
    let root = dir.path();
6830
    let repo = Repo::init(root).unwrap();
6831
    let big: String = (0..3000).map(|i| format!("line {i}\n")).collect();
6832
    write(root, "big.txt", big.as_bytes());
6833
    let h = repo.commit("big", &[]).unwrap();
6834
    assert_eq!(repo.fsck().unwrap().errors(), 0);
6835
    let (_, texts) = repo.store().get_change_lazy(&h).unwrap();
6836
    let Some(crate::objects::TextRef::Blob(b, _, _)) = texts.first().copied() else {
6837
        panic!("a stored text")
6838
    };
6839
    repo.store().remove_loose_for_test(&b).unwrap();
6840
    let rep = repo.fsck().unwrap();
6841
    assert!(rep.errors() > 0);
6842
    assert!(
6843
        rep.problems.iter().any(|p| p.what.contains(&h.short(12))),
6844
        "{:?}",
6845
        rep.problems
6846
    );
6847
}
6848
6849
/// oxygen#32: a subrepo on the same hub as one of the parent's remotes is
6850
/// reached with that remote's token and CA (a private subrepo then clones
6851
/// for anyone who can read the parent); another hub gets none of them.
6852
#[test]
6853
fn a_subrepo_on_the_parents_hub_borrows_its_credentials() {
6854
    hermetic();
6855
    let dir = tempfile::tempdir().unwrap();
6856
    let mut repo = Repo::init(dir.path()).unwrap();
6857
    repo.config
6858
        .set(
6859
            "remote.origin.url",
6860
            "https://Hub.example:7343/doomsdayone/metalgear",
6861
        )
6862
        .unwrap();
6863
    repo.config.set("remote.origin.token", "secret").unwrap();
6864
    repo.config
6865
        .set("remote.origin.ca", "/tmp/hub-ca.pem")
6866
        .unwrap();
6867
    let same = repo.credentials_for("https://hub.example:7343/doomsdayone/rstar-api");
6868
    assert_eq!(same.token.as_deref(), Some("secret"));
6869
    assert_eq!(same.ca.as_deref(), Some(Path::new("/tmp/hub-ca.pem")));
6870
    for other in [
6871
        "https://elsewhere.example:7343/doomsdayone/rstar-api",
6872
        "https://hub.example/doomsdayone/rstar-api",
6873
        "http://hub.example:7343/doomsdayone/rstar-api",
6874
    ] {
6875
        let o = repo.credentials_for(other);
6876
        assert_ne!(o.token.as_deref(), Some("secret"), "{other}");
6877
    }
6878
}
6879
6880
/// oxygen#47: a remote with no token of its own uses the user's credential
6881
/// store for its hub, and a nested checkout finds its parent's remote
6882
/// token there instead of keeping a copy.
6883
#[test]
6884
fn remotes_use_the_credential_store_and_the_enclosing_checkout() {
6885
    hermetic();
6886
    let home = tempfile::tempdir().unwrap();
6887
    let dir = tempfile::tempdir().unwrap();
6888
    let mut parent = Repo::init(dir.path()).unwrap().with_home(home.path());
6889
    parent
6890
        .config
6891
        .set("remote.origin.url", "https://hub.example/o/parent")
6892
        .unwrap();
6893
    parent.save_config().unwrap();
6894
    assert_eq!(parent.remote_options("origin").token, None);
6895
    crate::credentials::Credentials::at(home.path())
6896
        .save("https://hub.example", "stored", Some("andy"), None)
6897
        .unwrap();
6898
    assert_eq!(
6899
        parent.remote_options("origin").token.as_deref(),
6900
        Some("stored")
6901
    );
6902
6903
    let empty_home = tempfile::tempdir().unwrap();
6904
    let nested = dir.path().join("deps").join("child");
6905
    let mut child = Repo::init(&nested).unwrap().with_home(empty_home.path());
6906
    child
6907
        .config
6908
        .set("remote.origin.url", "https://hub.example/o/child")
6909
        .unwrap();
6910
    child.save_config().unwrap();
6911
    assert_eq!(child.remote_options("origin").token, None);
6912
    parent
6913
        .config
6914
        .set("remote.origin.token", "checkout")
6915
        .unwrap();
6916
    parent.save_config().unwrap();
6917
    assert_eq!(
6918
        child.remote_options("origin").token.as_deref(),
6919
        Some("checkout")
6920
    );
6921
    // Another hub's checkout token is not borrowed.
6922
    child
6923
        .config
6924
        .set("remote.origin.url", "https://other.example/o/child")
6925
        .unwrap();
6926
    assert_eq!(child.remote_options("origin").token, None);
6927
}
6928
6929
#[test]
6930
fn the_metadata_cache_survives_a_torn_tail() {
6931
    hermetic();
6932
    let dir = tempfile::tempdir().unwrap();
6933
    let root = dir.path();
6934
    let repo = Repo::init(root).unwrap();
6935
    write(root, "a.txt", b"1\n");
6936
    let h = repo.commit("first", &[]).unwrap();
6937
    let meta = repo.store().get_change_meta(&h).unwrap();
6938
    let cache = repo.store().dir().join("metas");
6939
    let len = fs::metadata(&cache).unwrap().len();
6940
    assert!(len > 0, "a change read is cached");
6941
    // A torn record at the end: the cache reads up to it and cuts it off.
6942
    fs::OpenOptions::new()
6943
        .append(true)
6944
        .open(&cache)
6945
        .unwrap()
6946
        .write_all(&[7; 20])
6947
        .unwrap();
6948
    let again = Repo::open(root).unwrap();
6949
    assert_eq!(again.store().get_change_meta(&h).unwrap(), meta);
6950
    assert_eq!(fs::metadata(&cache).unwrap().len(), len);
6951
}
6952
6953
#[test]
6954
fn a_manifest_that_does_not_check_reads_as_none() {
6955
    hermetic();
6956
    let dir = tempfile::tempdir().unwrap();
6957
    let root = dir.path();
6958
    let repo = Repo::init(root).unwrap();
6959
    write(root, "a.txt", b"1\n");
6960
    repo.commit("first", &[]).unwrap();
6961
    let path = repo.manifest_path();
6962
    let mut bytes = fs::read(&path).unwrap();
6963
    assert!(Repo::open(root).unwrap().read_manifest().unwrap().is_some());
6964
    let last = bytes.len() - 1;
6965
    bytes[last] ^= 1;
6966
    fs::write(&path, &bytes).unwrap();
6967
    assert!(Repo::open(root).unwrap().read_manifest().unwrap().is_none());
6968
    // The next status reads the files and writes it again.
6969
    let again = Repo::open(root).unwrap();
6970
    assert!(!again.snapshot("status").unwrap().changed);
6971
    assert!(again.read_manifest().unwrap().is_some());
6972
}
6973
6974
#[test]
6975
fn a_commit_leaves_a_manifest_that_proves_the_working_copy_clean() {
6976
    hermetic();
6977
    let dir = tempfile::tempdir().unwrap();
6978
    let root = dir.path();
6979
    let repo = Repo::init(root).unwrap();
6980
    write(root, "a.txt", b"1\n");
6981
    write(root, "b.txt", b"2\n");
6982
    // b.txt outside the racy window, so snapshots take it as unchanged.
6983
    let old = std::time::SystemTime::now() - std::time::Duration::from_secs(60);
6984
    fs::File::options()
6985
        .write(true)
6986
        .open(root.join("b.txt"))
6987
        .unwrap()
6988
        .set_modified(old)
6989
        .unwrap();
6990
    repo.commit("first", &[]).unwrap();
6991
    assert!(repo.clean_by_manifest().unwrap(), "after the first commit");
6992
    repo.snapshot_status("status").unwrap();
6993
    write(root, "a.txt", b"1\n2\n");
6994
    repo.commit("second", &[]).unwrap();
6995
    assert!(
6996
        repo.clean_by_manifest().unwrap(),
6997
        "after a commit of one file"
6998
    );
6999
    // Edited, seen by a status, edited again, then committed: the status
7000
    // left the first edit's stat, which the commit must not keep.
7001
    write(root, "a.txt", b"1\n2\n3\n");
7002
    repo.snapshot_status("status").unwrap();
7003
    write(root, "a.txt", b"1\n2\n3\n4\n5\n");
7004
    repo.commit("third", &[]).unwrap();
7005
    assert!(
7006
        repo.clean_by_manifest().unwrap(),
7007
        "after an edit a status saw"
7008
    );
7009
}
7010
7011
#[test]
7012
fn a_conflicted_rebase_can_be_resolved_in_the_working_copy() {
7013
    hermetic();
7014
    let dir = tempfile::tempdir().unwrap();
7015
    let root = dir.path();
7016
    let mut repo = Repo::init(root).unwrap().with_home(root.join("home"));
7017
    write(root, "a.txt", b"1\n2\n");
7018
    let a = repo.commit("A", &[]).unwrap();
7019
    repo.bookmark_create("develop", Some(&[a])).unwrap();
7020
    write(root, "a.txt", b"1\nX\n");
7021
    let c = repo.commit("C: 2 to X", &[]).unwrap();
7022
    repo.bookmark_switch("develop", false).unwrap();
7023
    write(root, "a.txt", b"1\nY\n");
7024
    let d = repo.commit("D: 2 to Y", &[]).unwrap();
7025
    repo.bookmark_switch("main", false).unwrap();
7026
7027
    let err = repo.rebase(&c, &[d]).unwrap_err();
7028
    assert!(matches!(err, RepoError::Conflicted(_)), "{err}");
7029
    let r = repo.rebase_into_working_copy(&c, &[d]).unwrap();
7030
    assert!(r.changed && r.checked_out);
7031
    let snap = repo.snapshot_status("status").unwrap();
7032
    assert!(
7033
        snap.base_snapshot.is_conflicted(),
7034
        "the conflict is in the working copy"
7035
    );
7036
    let text = fs::read_to_string(root.join("a.txt")).unwrap();
7037
    assert!(text.contains('X') && text.contains('Y'), "{text}");
7038
7039
    write(root, "a.txt", b"1\nXY\n");
7040
    repo.commit("Resolve", &[]).unwrap();
7041
    let st = repo.load_state(&repo.bookmark_heads().unwrap()).unwrap();
7042
    assert!(st.contains(&c) && st.contains(&d));
7043
    let files = st.materialize().files;
7044
    assert!(!files["a.txt"].is_conflicted());
7045
    assert!(
7046
        matches!(&files["a.txt"].content, FileContent::Text { bytes, .. } if bytes == b"1\nXY\n")
7047
    );
7048
7049
    // A change the current bookmark does not hold is refused.
7050
    repo.bookmark_switch("develop", false).unwrap();
7051
    write(root, "b.txt", b"b\n");
7052
    let e = repo.commit("E", &[]).unwrap();
7053
    repo.bookmark_switch("main", false).unwrap();
7054
    let err = repo.rebase_into_working_copy(&e, &[a]).unwrap_err();
7055
    assert!(
7056
        err.to_string().contains("not on the current bookmark"),
7057
        "{err}"
7058
    );
7059
}
7060
7061
#[test]
7062
fn an_ignore_rule_drops_an_added_file_but_not_a_tracked_one() {
7063
    hermetic();
7064
    let dir = tempfile::tempdir().unwrap();
7065
    let root = dir.path();
7066
    let repo = Repo::init(root).unwrap();
7067
    write(root, "a.txt", b"a\n");
7068
    write(root, "kept.log", b"tracked\n");
7069
    repo.commit("first", &[]).unwrap();
7070
    write(root, "build.log", b"made\n");
7071
    let snap = repo.snapshot_status("status").unwrap();
7072
    assert!(snap.statuses.iter().any(|s| s.path == "build.log"));
7073
    // A rule written afterwards leaves the added file out again, while the
7074
    // committed one stays tracked.
7075
    write(root, ".gitignore", b"*.log\n");
7076
    let snap = repo.snapshot_status("status").unwrap();
7077
    let paths: Vec<&str> = snap.statuses.iter().map(|s| s.path.as_str()).collect();
7078
    assert_eq!(paths, vec![".gitignore"], "{paths:?}");
7079
    write(root, "kept.log", b"tracked, edited\n");
7080
    let snap = repo.snapshot_status("status").unwrap();
7081
    assert!(snap.statuses.iter().any(|s| s.path == "kept.log"));
7082
}
7083
7084
#[test]
7085
fn shed_graphs_come_back_the_same() {
7086
    hermetic();
7087
    let dir = tempfile::tempdir().unwrap();
7088
    let root = dir.path();
7089
    let repo = Repo::init(root).unwrap();
7090
    write(root, "a.txt", b"1\n2\n3\n");
7091
    write(root, "b.txt", b"x\n");
7092
    repo.commit("first", &[]).unwrap();
7093
    write(root, "a.txt", b"1\ntwo\n3\n4\n");
7094
    repo.commit("second", &[]).unwrap();
7095
    let heads = repo.bookmark_heads().unwrap();
7096
    let mut st = repo.load_state_history(&heads).unwrap();
7097
    let view = st.tree().view();
7098
    let nodes: Vec<NodeId> = ["a.txt", "b.txt"]
7099
        .iter()
7100
        .map(|p| view.entries[*p].node)
7101
        .collect();
7102
    repo.load_graphs_of(&mut st, &nodes).unwrap();
7103
    let before: Vec<Vec<u8>> = nodes.iter().map(|n| st.render_file(n).0).collect();
7104
    assert_eq!(st.built_count(), 2);
7105
    let shed = st.shed_graphs(|b| repo.store_blob(b)).unwrap();
7106
    assert_eq!((shed, st.built_count()), (2, 0));
7107
    // A later change applies on top of the shed history.
7108
    write(root, "a.txt", b"1\ntwo\n3\n4\n5\n");
7109
    let h3 = repo.commit("third", &[]).unwrap();
7110
    let (skeleton, texts) = repo.store().get_change_lazy(&h3).unwrap();
7111
    st.add_known(h3, skeleton, texts);
7112
    repo.load_graphs_of(&mut st, &nodes).unwrap();
7113
    let after: Vec<Vec<u8>> = nodes.iter().map(|n| st.render_file(n).0).collect();
7114
    assert_eq!(after[1], before[1]);
7115
    assert_eq!(after[0], b"1\ntwo\n3\n4\n5\n");
7116
}
7117
7118
#[test]
7119
fn many_edited_files_diff_in_parallel() {
7120
    // Enough edited files that the builder diffs them in parallel; the
7121
    // commit must hold exactly what is on disk, and a second snapshot
7122
    // must find nothing left to commit.
7123
    hermetic();
7124
    let dir = tempfile::tempdir().unwrap();
7125
    let root = dir.path();
7126
    let repo = Repo::init(root).unwrap();
7127
    let text = |i: usize, round: usize| {
7128
        let mut s = String::new();
7129
        for line in 0..50 {
7130
            if round > 0 && line % 7 == i % 7 {
7131
                s.push_str(&format!("edited {round} {i} {line}\n"));
7132
            } else {
7133
                s.push_str(&format!("file {i} line {line}\n"));
7134
            }
7135
        }
7136
        if round > 0 && i.is_multiple_of(3) {
7137
            s.push_str("appended\n");
7138
        }
7139
        s
7140
    };
7141
    for i in 0..40 {
7142
        write(root, &format!("d/f{i}.txt"), text(i, 0).as_bytes());
7143
    }
7144
    repo.commit("first", &[]).unwrap();
7145
    for i in 0..40 {
7146
        write(root, &format!("d/f{i}.txt"), text(i, 1).as_bytes());
7147
    }
7148
    let h = repo.commit("edit every file", &[]).unwrap();
7149
    let snap = repo.load_state(&[h]).unwrap().materialize();
7150
    for i in 0..40 {
7151
        let want = text(i, 1);
7152
        assert!(
7153
            matches!(&snap.files[&format!("d/f{i}.txt")].content, FileContent::Text { bytes, .. } if bytes == want.as_bytes()),
7154
            "d/f{i}.txt as committed"
7155
        );
7156
    }
7157
    assert!(
7158
        repo.commit("nothing", &[]).is_err(),
7159
        "nothing left to commit"
7160
    );
7161
}
7162
7163
/// oxygen#56: after a fetch, how a bookmark stands against its remote copy
7164
/// is known (fetch printed "up to date" while main was behind), a change
7165
/// only fetched resolves and says where it is, and a checkout whose only
7166
/// remote is not `origin` uses that one.
7167
#[test]
7168
fn a_fetched_change_shows_as_behind_and_resolves() {
7169
    hermetic();
7170
    let dir = tempfile::tempdir().unwrap();
7171
    let root = dir.path();
7172
    let origin = Repo::init(&root.join("origin")).unwrap();
7173
    drop(origin);
7174
    let url = root.join("origin").to_string_lossy().to_string();
7175
    let a = Repo::clone(&url, &root.join("a"))
7176
        .unwrap()
7177
        .with_home(root.join("home-a"));
7178
    write(&root.join("a"), "f.txt", b"one\n");
7179
    a.commit("one", &[]).unwrap();
7180
    a.push("origin", false).unwrap();
7181
    let b = Repo::clone(&url, &root.join("b"))
7182
        .unwrap()
7183
        .with_home(root.join("home-b"));
7184
    assert_eq!(b.tracking("origin", "main").unwrap(), Some((0, 0)));
7185
7186
    write(&root.join("a"), "f.txt", b"one\ntwo\n");
7187
    let h2 = a.commit("two", &[]).unwrap();
7188
    a.push("origin", false).unwrap();
7189
    b.fetch("origin").unwrap();
7190
    // Fetched, not pulled: one behind, the change found and placed.
7191
    assert_eq!(b.tracking("origin", "main").unwrap(), Some((0, 1)));
7192
    assert_eq!(b.tracking("origin", "nope").unwrap(), None);
7193
    assert_eq!(
7194
        b.resolve_change(&format!("#{}", &h2.to_hex()[..12]))
7195
            .unwrap(),
7196
        h2
7197
    );
7198
    assert_eq!(
7199
        b.remote_only_location(&h2).unwrap().as_deref(),
7200
        Some("origin/main")
7201
    );
7202
    // Fetching again changes nothing: still behind, which is what the
7203
    // CLI now says rather than "up to date".
7204
    b.fetch("origin").unwrap();
7205
    assert_eq!(b.tracking("origin", "main").unwrap(), Some((0, 1)));
7206
    b.pull("origin").unwrap();
7207
    assert_eq!(b.tracking("origin", "main").unwrap(), Some((0, 0)));
7208
    assert_eq!(b.remote_only_location(&h2).unwrap(), None);
7209
7210
    // One remote, not called origin: it is the default.
7211
    let mut c = Repo::init(&root.join("c")).unwrap();
7212
    assert_eq!(c.default_remote(), "origin");
7213
    c.config.set("remote.earth.url", &url).unwrap();
7214
    assert_eq!(c.default_remote(), "earth");
7215
    c.config.set("remote.origin.url", &url).unwrap();
7216
    assert_eq!(c.default_remote(), "origin");
7217
}
7218
7219
/// oxygen#57: a clone from a relative local path records the remote as an
7220
/// absolute path, so fetch still finds it from inside the clone.
7221
#[test]
7222
fn a_clone_from_a_relative_path_records_it_absolute() {
7223
    hermetic();
7224
    let dir = tempfile::tempdir().unwrap();
7225
    let root = dir.path();
7226
    Repo::init(&root.join("origin")).unwrap();
7227
    let rel = crate::protocol::stored_url("relative/repo");
7228
    assert!(std::path::Path::new(&rel).is_absolute(), "{rel}");
7229
    assert_eq!(
7230
        crate::protocol::stored_url("https://hub.example/o/n"),
7231
        "https://hub.example/o/n"
7232
    );
7233
    assert!(crate::protocol::stored_url("file://x").starts_with("file:///"));
7234
    assert!(crate::protocol::stored_url("dir://x").starts_with("dir:///"));
7235
    // A bucket is kept as written: it is not a path.
7236
    assert_eq!(
7237
        crate::protocol::stored_url("s3://bucket/prefix?profile=p"),
7238
        "s3://bucket/prefix?profile=p"
7239
    );
7240
    let url = root.join("origin").to_string_lossy().to_string();
7241
    let b = Repo::clone(&url, &root.join("b")).unwrap();
7242
    assert_eq!(b.config.remotes["origin"], url);
7243
    b.fetch("origin").unwrap();
7244
}
7245
7246
/// oxygen#60 and #61: a workspace added on a bookmark is on that bookmark,
7247
/// and gets its subrepos at their pins from this workspace's copies, with
7248
/// their remotes pointing where the subrepos come from.
7249
#[test]
7250
fn a_workspace_added_on_a_bookmark_is_on_it_with_its_subrepos() {
7251
    hermetic();
7252
    let dir = tempfile::tempdir().unwrap();
7253
    let root = dir.path();
7254
    Repo::init(&root.join("lib-origin")).unwrap();
7255
    let lib_url = root.join("lib-origin").to_string_lossy().to_string();
7256
    let lib = Repo::clone(&lib_url, &root.join("lib"))
7257
        .unwrap()
7258
        .with_home(root.join("home"));
7259
    write(&root.join("lib"), "lib.txt", b"v1\n");
7260
    let l1 = lib.commit("lib v1", &[]).unwrap();
7261
    assert!(lib.push("origin", false).unwrap()[0].ok);
7262
7263
    let app_dir = root.join("app");
7264
    let app = Repo::init(&app_dir).unwrap().with_home(root.join("home"));
7265
    write(&app_dir, "main.txt", b"app\n");
7266
    app.submodule_add(&lib_url, "libs/lib", None).unwrap();
7267
    app.commit("app with lib", &[]).unwrap();
7268
    // A second bookmark, and the main workspace on another.
7269
    app.bookmark_create("develop", None).unwrap();
7270
    app.bookmark_create("feature", None).unwrap();
7271
    let mut app = app;
7272
    app.bookmark_switch("feature", false).unwrap();
7273
    assert_eq!(app.config.bookmark, "feature");
7274
7275
    // The library's origin goes away: the subrepo must come from here.
7276
    std::fs::rename(root.join("lib-origin"), root.join("lib-origin-gone")).unwrap();
7277
    let heads = app.resolve_heads("develop").unwrap();
7278
    let ws = app
7279
        .workspace_add_on(&root.join("ws"), Some(&heads), Some("develop"))
7280
        .unwrap();
7281
    assert_eq!(
7282
        ws.config.bookmark, "develop",
7283
        "the new workspace is on develop"
7284
    );
7285
    assert_eq!(
7286
        app.config.bookmark, "feature",
7287
        "and this one stays on its own"
7288
    );
7289
    let sub = Repo::open(&root.join("ws/libs/lib")).unwrap();
7290
    assert_eq!(
7291
        sub.config.remotes["origin"], lib_url,
7292
        "its origin is the subrepo's URL"
7293
    );
7294
    assert_eq!(sub.bookmark_heads().unwrap(), vec![l1], "at its pin");
7295
    assert_eq!(
7296
        std::fs::read(root.join("ws/libs/lib/lib.txt")).unwrap(),
7297
        b"v1\n"
7298
    );
7299
}
7300
7301
/// Revsets (docs/revset_query_language.md): symbols, relations, set
7302
/// operators and the predicates, over a small graph with two heads and
7303
/// a rename.
7304
#[test]
7305
fn revsets_select_changes_by_relation_author_text_date_and_path() {
7306
    hermetic();
7307
    let dir = tempfile::tempdir().unwrap();
7308
    let root = dir.path();
7309
    let mut repo = Repo::init(root).unwrap().with_home(root.join("home"));
7310
    repo.create_identity("Ada", "[email protected]", IdentityScope::User)
7311
        .unwrap();
7312
    write(root, "src/a.rs", b"one\n");
7313
    let a = repo.commit("first: add a", &[]).unwrap();
7314
    write(root, "src/a.rs", b"one\ntwo\n");
7315
    let b = repo.commit("second: grow a", &[]).unwrap();
7316
    // A second head, independent of b: a new file on top of a.
7317
    repo.checkout(&[a], false, "checkout a").unwrap();
7318
    write(root, "docs/notes.md", b"notes\n");
7319
    let c = repo.commit("third: notes", &[]).unwrap();
7320
    // Back to both heads, then rename a.rs: the node keeps its identity.
7321
    repo.checkout(&repo.bookmark_heads().unwrap(), false, "checkout main")
7322
        .unwrap();
7323
    fs::remove_file(root.join("src/a.rs")).unwrap();
7324
    write(root, "src/z.rs", b"one\ntwo\n");
7325
    let d = repo.commit("fourth: rename a to z", &[]).unwrap();
7326
    let wc = repo.working_copy().unwrap().0;
7327
    // A saved revset is checked when set.
7328
    repo.set_user_config("revset.mine", "author(me) & ::main")
7329
        .unwrap();
7330
    assert!(repo.set_user_config("revset.bad", "a &").is_err());
7331
    let set = |src: &str| -> Vec<ChangeHash> {
7332
        let mut v = repo.revset(src).unwrap().hashes;
7333
        v.sort();
7334
        v
7335
    };
7336
    let sorted = |hs: &[ChangeHash]| -> Vec<ChangeHash> {
7337
        let mut v = hs.to_vec();
7338
        v.sort();
7339
        v
7340
    };
7341
7342
    // Changes commute: a new file depends on nothing and the rename on the
7343
    // file's creation, so the graph is a, b->a, d->a, c, and the working
7344
    // copy on the three heads b, c, d.
7345
    let heads = sorted(&repo.bookmark_heads().unwrap());
7346
    let meta = |h: &ChangeHash| repo.store().get_change_meta(h).unwrap();
7347
    assert!(heads.contains(&d) && heads.contains(&c));
7348
    // Symbols and closures.
7349
    assert_eq!(set("main"), heads);
7350
    assert_eq!(set("::main"), sorted(&[a, b, c, d]));
7351
    assert_eq!(set("@"), vec![wc]);
7352
    assert_eq!(set("::@"), sorted(&[a, b, c, d, wc]));
7353
    assert_eq!(set(&format!("::#{}", b.short(12))), sorted(&[a, b]));
7354
    assert_eq!(set(&format!("#{}::", a.short(12))), sorted(&[a, b, d, wc]));
7355
    assert_eq!(
7356
        set(&format!("#{}::#{}", a.short(12), b.short(12))),
7357
        sorted(&[a, b])
7358
    );
7359
    // Ranges: what main has beyond b, and `..` forms.
7360
    assert_eq!(set(&format!("#{}..main", b.short(12))), sorted(&[c, d]));
7361
    assert_eq!(set(&format!("#{}..", c.short(12))), sorted(&[a, b, d, wc]));
7362
    assert_eq!(set("..main"), sorted(&[a, b, c, d]));
7363
    // Operators and precedence: ~ binds tighter than &, & than |.
7364
    assert_eq!(
7365
        set(&format!("::main ~ #{}", d.short(12))),
7366
        sorted(&[a, b, c])
7367
    );
7368
    assert_eq!(
7369
        set(&format!("::main & #{} | #{}", b.short(12), c.short(12))),
7370
        sorted(&[b, c])
7371
    );
7372
    assert_eq!(set("all() ~ ::main"), vec![wc]);
7373
    // Relations.
7374
    let mut head_deps: Vec<ChangeHash> = heads.iter().flat_map(|h| meta(h).deps).collect();
7375
    head_deps.sort();
7376
    head_deps.dedup();
7377
    assert_eq!(set("deps(main)"), head_deps);
7378
    let on_a: Vec<ChangeHash> = [b, c, d]
7379
        .into_iter()
7380
        .filter(|h| meta(h).deps.contains(&a))
7381
        .collect();
7382
    assert_eq!(set(&format!("dependents(#{})", a.short(12))), sorted(&on_a));
7383
    assert_eq!(set("heads(::main)"), heads);
7384
    assert_eq!(set("roots(::main)"), sorted(&[a, c]));
7385
    assert_eq!(
7386
        set(&format!(
7387
            "heads(#{} | #{} | #{})",
7388
            a.short(12),
7389
            b.short(12),
7390
            c.short(12)
7391
        )),
7392
        sorted(&[b, c])
7393
    );
7394
    assert_eq!(set("latest(::main, 1)"), vec![d]);
7395
    assert_eq!(set("kind(working-copy)"), vec![wc]);
7396
    assert_eq!(set("none()"), vec![]);
7397
    // Predicates: author by name, email, key prefix and `me`.
7398
    let key = repo.config.author_key.unwrap();
7399
    assert_eq!(set("author(ada) & ::main"), sorted(&[a, b, c, d]));
7400
    assert_eq!(set("author(\"[email protected]\") & ::main").len(), 4);
7401
    assert_eq!(set(&format!("author({}) & ::main", key.short(12))).len(), 4);
7402
    assert_eq!(set("author(me) & ::main").len(), 4);
7403
    assert_eq!(set("author(nobody)"), vec![]);
7404
    assert_eq!(set("description(notes)"), vec![c]);
7405
    assert_eq!(set("description(\"rename a\")"), vec![d]);
7406
    assert_eq!(set("date(-1h..) & ::main").len(), 4);
7407
    assert_eq!(set("date(..2000-01-01)"), vec![]);
7408
    // touches follows the node through the rename, in the current state.
7409
    assert_eq!(set("touches(\"src/z.rs\")"), sorted(&[a, b, d]));
7410
    assert_eq!(set("touches(\"src/**\") & ::main"), sorted(&[a, b, d]));
7411
    assert_eq!(set("touches(\"docs/*\")"), vec![c]);
7412
    assert_eq!(set("touches(\"nothing/*\")"), vec![]);
7413
    // Newest first in the result order.
7414
    assert_eq!(repo.revset("::main").unwrap().hashes[0], d);
7415
    // The saved revset, and errors that say what is wrong.
7416
    assert_eq!(set("mine()").len(), 4);
7417
    let e = repo.revset("nosuch()").unwrap_err().to_string();
7418
    assert!(e.contains("unknown function nosuch()"), "{e}");
7419
    let e = repo.revset("main &").unwrap_err().to_string();
7420
    assert!(e.contains("at character"), "{e}");
7421
    let e = repo.revset("zzzz").unwrap_err().to_string();
7422
    assert!(e.contains("no change matches"), "{e}");
7423
    let e = repo
7424
        .revset_with_budget("::main", std::time::Duration::ZERO)
7425
        .unwrap_err()
7426
        .to_string();
7427
    assert!(e.contains("budget"), "{e}");
7428
    // The log entries carry the bookmark's heads and the working copy.
7429
    let entries = repo.log_revset("::@").unwrap();
7430
    assert!(entries[0].is_working_copy && entries.iter().any(|e| e.is_head && e.hash == d));
7431
    // Trust predicates (§2.4): nothing is signed yet (core.sign = seal, no
7432
    // push); then a signed change, a tag, and a revocation.
7433
    assert_eq!(set("unsigned() & ::main"), sorted(&[a, b, c, d]));
7434
    assert_eq!(set("signed_by(me)"), vec![]);
7435
    repo.sign_change(&d).unwrap();
7436
    assert_eq!(set("signed_by(me)"), vec![d]);
7437
    assert_eq!(set("signed_by([email protected])"), vec![d]);
7438
    assert_eq!(set(&format!("signed_by({})", key.short(12))), vec![d]);
7439
    assert_eq!(set("unsigned() & ::main"), sorted(&[a, b, c]));
7440
    assert_eq!(set("delegated()"), vec![]);
7441
    assert_eq!(set("revoked()"), vec![]);
7442
    assert_eq!(set("attested(tag)"), vec![]);
7443
    repo.tag_create("v1", &[b], "first").unwrap();
7444
    assert_eq!(set("attested(tag)"), sorted(&[a, b]));
7445
    assert_eq!(set("attested(tag) & unsigned()"), sorted(&[a, b]));
7446
    assert_eq!(set("attested(receipt)"), vec![]);
7447
    assert_eq!(set("built(test)"), vec![]);
7448
    let e = repo.revset("attested(seal)").unwrap_err().to_string();
7449
    assert!(e.contains("tag, receipt or ref"), "{e}");
7450
    repo.revoke_identity(&key, "test").unwrap();
7451
    assert_eq!(set("revoked()"), vec![d]);
7452
    assert_eq!(set("signed_by(me) ~ revoked()"), vec![]);
7453
}
7454
7455
#[test]
7456
fn a_rotation_is_recorded_wherever_the_old_key_was_named() {
7457
    let dir = tempfile::tempdir().unwrap();
7458
    let root = dir.path();
7459
    let home = root.join("home");
7460
    // Ada's identity lives in the user file; repository `a` pins the same
7461
    // key in its own file, repository `b` names none.
7462
    let mut a = Repo::init(&root.join("a")).unwrap().with_home(&home);
7463
    let (key, _) = a
7464
        .create_identity("Ada", "[email protected]", IdentityScope::User)
7465
        .unwrap();
7466
    a.config.set("author.key", &key.to_hex()).unwrap();
7467
    a.save_config().unwrap();
7468
    let agent = SecretKey::generate().identity("Agent", "[email protected]", 1);
7469
    let r = a
7470
        .delegate_add(agent.clone(), crate::identity::Scope::CHANGES, None)
7471
        .unwrap();
7472
    assert_eq!(
7473
        read_config_file(&home.join("config.toml")).unwrap()["author.key"],
7474
        r.new.to_hex(),
7475
        "the user file follows"
7476
    );
7477
    assert_eq!(
7478
        read_config_file(&root.join("a/.oxy/config")).unwrap()["author.key"],
7479
        r.new.to_hex(),
7480
        "the pinning repository follows"
7481
    );
7482
    let b = Repo::init(&root.join("b")).unwrap().with_home(&home);
7483
    assert_eq!(
7484
        b.config.author_key,
7485
        Some(r.new),
7486
        "a checkout without a pin follows the user file"
7487
    );
7488
    // A repository-scoped identity leaves the user file alone.
7489
    let other_home = root.join("home2");
7490
    let mut c = Repo::init(&root.join("c")).unwrap().with_home(&other_home);
7491
    let (ck, _) = c
7492
        .create_identity("Cy", "[email protected]", IdentityScope::Repo)
7493
        .unwrap();
7494
    assert!(!other_home.join("config.toml").exists());
7495
    let r2 = c.rotate_identity().unwrap();
7496
    assert_ne!(r2.new, ck);
7497
    assert_eq!(
7498
        read_config_file(&root.join("c/.oxy/config")).unwrap()["author.key"],
7499
        r2.new.to_hex()
7500
    );
7501
    assert!(
7502
        !other_home.join("config.toml").exists(),
7503
        "a repository-scoped identity stays repository-scoped"
7504
    );
7505
    // Several delegates in one rotation; a repeat is refused.
7506
    let (d1, d2) = (
7507
        SecretKey::generate().identity("D1", "d1@x", 1),
7508
        SecretKey::generate().identity("D2", "d2@x", 1),
7509
    );
7510
    let r3 = c
7511
        .delegate_add_many(vec![d1.clone(), d2], crate::identity::Scope::CHANGES, None)
7512
        .unwrap();
7513
    assert_eq!(r3.identity.delegates.len(), 2);
7514
    assert!(c
7515
        .delegate_add(d1, crate::identity::Scope::CHANGES, None)
7516
        .is_err());
7517
}
7518
7519
/// Two unrelated histories that both add the same file, joined by two
7520
/// independent merges on two branches, then those branches merged: Git
7521
/// merges identical additions cleanly, and the import must too (#71,
7522
/// found in VS Code's history).
7523
#[test]
7524
fn git_import_joins_unrelated_histories_that_add_the_same_file() {
7525
    // Batches of one: every merge renders apart from the state, where a
7526
    // file whose graph the state had built came out empty (#71).
7527
    crate::repo::git::set_merge_batch_for_tests(Some(1));
7528
    hermetic();
7529
    if std::process::Command::new("git")
7530
        .arg("--version")
7531
        .output()
7532
        .is_err()
7533
    {
7534
        eprintln!("git not installed; skipping");
7535
        return;
7536
    }
7537
    let dir = tempfile::tempdir().unwrap();
7538
    let root = dir.path();
7539
    let g = root.join("src.git");
7540
    fs::create_dir_all(&g).unwrap();
7541
    let git = |args: &[&str]| -> String {
7542
        let out = std::process::Command::new("git")
7543
            .arg("-C")
7544
            .arg(&g)
7545
            .args([
7546
                "-c",
7547
                "user.name=Grace",
7548
                "-c",
7549
                "[email protected]",
7550
                "-c",
7551
                "commit.gpgsign=false",
7552
            ])
7553
            .args(args)
7554
            .output()
7555
            .unwrap();
7556
        assert!(
7557
            out.status.success(),
7558
            "git {args:?}: {}",
7559
            String::from_utf8_lossy(&out.stderr)
7560
        );
7561
        String::from_utf8_lossy(&out.stdout).trim().to_string()
7562
    };
7563
    let text = b"/* header */\nconst a = 1;\nconst b = 2;\n";
7564
    // History A: main.
7565
    git(&["init", "-q", "-b", "main"]);
7566
    write(&g, "gulpfile.js", text);
7567
    write(&g, "a.txt", b"a\n");
7568
    git(&["add", "."]);
7569
    git(&["commit", "-q", "-m", "A root"]);
7570
    // History B: an unrelated root adding the same file, identical.
7571
    git(&["checkout", "-q", "--orphan", "fork"]);
7572
    git(&["rm", "-q", "-r", "--cached", "."]);
7573
    for f in ["gulpfile.js", "a.txt"] {
7574
        let _ = fs::remove_file(g.join(f));
7575
    }
7576
    write(&g, "gulpfile.js", text);
7577
    write(&g, "b.txt", b"b\n");
7578
    git(&["add", "."]);
7579
    git(&["commit", "-q", "-m", "B root"]);
7580
    // Two branches from main, each joining B on its own.
7581
    git(&["checkout", "-q", "-b", "one", "main"]);
7582
    git(&[
7583
        "merge",
7584
        "-q",
7585
        "--no-ff",
7586
        "--allow-unrelated-histories",
7587
        "-m",
7588
        "join on one",
7589
        "fork",
7590
    ]);
7591
    git(&["checkout", "-q", "-b", "two", "main"]);
7592
    write(&g, "a.txt", b"a\ntwo\n");
7593
    git(&["commit", "-q", "-am", "work on two"]);
7594
    git(&[
7595
        "merge",
7596
        "-q",
7597
        "--no-ff",
7598
        "--allow-unrelated-histories",
7599
        "-m",
7600
        "join on two",
7601
        "fork",
7602
    ]);
7603
    // Then the two joins meet, and the file is reformatted after.
7604
    git(&["checkout", "-q", "main"]);
7605
    git(&["merge", "-q", "--no-ff", "-m", "merge one", "one"]);
7606
    git(&["merge", "-q", "--no-ff", "-m", "merge two", "two"]);
7607
    write(
7608
        &g,
7609
        "gulpfile.js",
7610
        b"/* header */\nconst a = 1;\nconst b = 3;\n",
7611
    );
7612
    git(&["commit", "-q", "-am", "after"]);
7613
7614
    let dest = root.join("dest");
7615
    let repo = Repo::init(&dest).unwrap().with_home(root.join("home"));
7616
    repo.import_git(&g, "main").unwrap();
7617
    let v = repo.verify_git_import(&g, "main").unwrap();
7618
    assert!(v.mismatches.is_empty(), "{:?}", v.mismatches);
7619
    assert_eq!(
7620
        fs::read(dest.join("gulpfile.js")).unwrap(),
7621
        b"/* header */\nconst a = 1;\nconst b = 3;\n"
7622
    );
7623
}
7624
7625
/// As above, but the two joins keep different copies (each branch had a
7626
/// different version when it joined), and later work edits each copy:
7627
/// the shape of VS Code's c67ef57cda90 (#71).
7628
#[test]
7629
fn git_import_joins_where_each_join_kept_a_different_copy() {
7630
    // Batches of one: every merge renders apart from the state, where a
7631
    // file whose graph the state had built came out empty (#71).
7632
    crate::repo::git::set_merge_batch_for_tests(Some(1));
7633
    hermetic();
7634
    if std::process::Command::new("git")
7635
        .arg("--version")
7636
        .output()
7637
        .is_err()
7638
    {
7639
        eprintln!("git not installed; skipping");
7640
        return;
7641
    }
7642
    let dir = tempfile::tempdir().unwrap();
7643
    let root = dir.path();
7644
    let g = root.join("src.git");
7645
    fs::create_dir_all(&g).unwrap();
7646
    let run = |args: &[&str]| {
7647
        std::process::Command::new("git")
7648
            .arg("-C")
7649
            .arg(&g)
7650
            .args([
7651
                "-c",
7652
                "user.name=Grace",
7653
                "-c",
7654
                "[email protected]",
7655
                "-c",
7656
                "commit.gpgsign=false",
7657
            ])
7658
            .args(args)
7659
            .output()
7660
            .unwrap()
7661
    };
7662
    let git = |args: &[&str]| -> String {
7663
        let out = run(args);
7664
        assert!(
7665
            out.status.success(),
7666
            "git {args:?}: {}",
7667
            String::from_utf8_lossy(&out.stderr)
7668
        );
7669
        String::from_utf8_lossy(&out.stdout).trim().to_string()
7670
    };
7671
    git(&["init", "-q", "-b", "main"]);
7672
    write(
7673
        &g,
7674
        "gulpfile.js",
7675
        b"/* header */\nconst a = 1;\nconst b = 2;\n",
7676
    );
7677
    git(&["add", "."]);
7678
    git(&["commit", "-q", "-m", "A root"]);
7679
    write(
7680
        &g,
7681
        "gulpfile.js",
7682
        b"/* header */\nconst a = 1;\n\nconst b = 2;\n",
7683
    );
7684
    git(&["commit", "-q", "-am", "whitespace"]);
7685
    git(&["checkout", "-q", "--orphan", "fork"]);
7686
    git(&["rm", "-q", "-r", "--cached", "."]);
7687
    let _ = fs::remove_file(g.join("gulpfile.js"));
7688
    write(
7689
        &g,
7690
        "gulpfile.js",
7691
        b"/* header */\nconst a = 1;\nconst b = 2;\nconst c = 3;\n",
7692
    );
7693
    git(&["add", "."]);
7694
    git(&["commit", "-q", "-m", "B root"]);
7695
    // Branch one joins B keeping main's copy; branch two keeps B's.
7696
    for (branch, keep) in [("one", "ours"), ("two", "theirs")] {
7697
        git(&["checkout", "-q", "-b", branch, "main"]);
7698
        let _ = run(&[
7699
            "merge",
7700
            "-q",
7701
            "--no-ff",
7702
            "--allow-unrelated-histories",
7703
            "-m",
7704
            "join",
7705
            "fork",
7706
        ]);
7707
        git(&["checkout", &format!("--{keep}"), "gulpfile.js"]);
7708
        git(&["add", "gulpfile.js"]);
7709
        git(&["commit", "-q", "-m", &format!("join on {branch}")]);
7710
    }
7711
    // Each branch then edits its copy.
7712
    git(&["checkout", "-q", "one"]);
7713
    write(
7714
        &g,
7715
        "gulpfile.js",
7716
        b"/* header */\nconst a = 1;\n\nconst b = 2;\n// tslint\n",
7717
    );
7718
    git(&["commit", "-q", "-am", "tslint on one"]);
7719
    git(&["checkout", "-q", "two"]);
7720
    write(
7721
        &g,
7722
        "gulpfile.js",
7723
        b"/* header */\nconst a = 1;\nconst b = 2;\nconst c = 3;\n// fmt\n",
7724
    );
7725
    write(&g, "extra.txt", b"x\n");
7726
    write(&g, "more.txt", b"m\n");
7727
    git(&["add", "."]);
7728
    git(&["commit", "-q", "-am", "fmt on two"]);
7729
    // They meet: resolved by hand.
7730
    git(&["checkout", "-q", "one"]);
7731
    let _ = run(&["merge", "-q", "--no-ff", "-m", "merge two", "two"]);
7732
    write(
7733
        &g,
7734
        "gulpfile.js",
7735
        b"/* header */\nconst a = 1;\nconst b = 2;\nconst c = 3;\n// tslint\n// fmt\n",
7736
    );
7737
    git(&["add", "gulpfile.js"]);
7738
    git(&["commit", "-q", "-m", "merge two into one"]);
7739
7740
    let dest = root.join("dest");
7741
    let repo = Repo::init(&dest).unwrap().with_home(root.join("home"));
7742
    repo.import_git(&g, "one").unwrap();
7743
    let v = repo.verify_git_import(&g, "one").unwrap();
7744
    assert!(v.mismatches.is_empty(), "{:?}", v.mismatches);
7745
}
7746
7747
/// oxygen#68: on a store that is not this disk's directory, the operation
7748
/// head is the store's reference record, moved by compare-and-swap. Two
7749
/// handles recording from the same head both get through, merged; a swap
7750
/// from a stale version is refused; a second repository cannot start on a
7751
/// store that already holds one.
7752
#[test]
7753
fn over_a_store_the_operation_head_moves_by_compare_and_swap() {
7754
    use crate::strata::{MemoryStore, Store as _};
7755
    let backend = std::sync::Arc::new(MemoryStore::new());
7756
    crate::store::TEST_BACKEND.with(|t| *t.borrow_mut() = Some(backend.clone()));
7757
    let dir = tempfile::tempdir().unwrap();
7758
    let a = Repo::init(dir.path()).unwrap();
7759
    assert!(
7760
        !dir.path().join(".oxy/ops/head").exists(),
7761
        "the head is not a file"
7762
    );
7763
    let (h0, op0) = a.head_op().unwrap();
7764
    let record = backend
7765
        .read_ref(HEAD_RECORD)
7766
        .unwrap()
7767
        .expect("the head is the store's record");
7768
    assert_eq!(String::from_utf8(record.0).unwrap(), h0.to_hex());
7769
7770
    let b = Repo::open(dir.path()).unwrap();
7771
    let state = a.store.put_state(&StateObject::new(vec![])).unwrap();
7772
    let mut va = op0.view.clone();
7773
    va.bookmarks.insert("from-a".into(), state);
7774
    let mut vb = op0.view.clone();
7775
    vb.bookmarks.insert("from-b".into(), state);
7776
    let rb = b.record_op(&[h0], "bookmark from-b", vb).unwrap();
7777
    assert_eq!(b.head_ref().unwrap(), rb);
7778
    // a recorded from h0 too: the head moved, so the two are merged.
7779
    let ra = a.record_op(&[h0], "bookmark from-a", va).unwrap();
7780
    let (head, op) = Repo::open(dir.path()).unwrap().head_op().unwrap();
7781
    assert_eq!(head, ra);
7782
    assert!(
7783
        op.command.ends_with("(merged with a concurrent operation)"),
7784
        "{}",
7785
        op.command
7786
    );
7787
    assert_eq!(op.parents, vec![rb, op.parents[1]]);
7788
    assert!(op.view.bookmarks.contains_key("from-a") && op.view.bookmarks.contains_key("from-b"));
7789
7790
    // A swap from a version that is no longer current moves nothing.
7791
    let (h, v) = a.read_head().unwrap();
7792
    assert!(b.swap_head(&rb, v.as_ref()).unwrap());
7793
    assert!(!a.swap_head(&h, v.as_ref()).unwrap(), "stale");
7794
    assert_eq!(a.head_ref().unwrap(), rb);
7795
7796
    let other = tempfile::tempdir().unwrap();
7797
    let err = Repo::init(other.path())
7798
        .err()
7799
        .expect("the store already holds a log")
7800
        .to_string();
7801
    assert!(
7802
        err.contains("already holds a repository's operation log"),
7803
        "{err}"
7804
    );
7805
    crate::store::TEST_BACKEND.with(|t| *t.borrow_mut() = None);
7806
}
7807
7808
/// oxygen#68: a repository kept on a store (`storage.url`) holds its
7809
/// objects and operation head there, with `.oxy/cache` in front: it works
7810
/// as one on disk does, reopens, and survives losing its cache.
7811
#[test]
7812
fn a_repository_runs_on_a_store_with_a_cache_in_front() {
7813
    hermetic();
7814
    if std::env::var_os("OXY_STORE_BACKEND").is_some() {
7815
        return;
7816
    }
7817
    let dir = tempfile::tempdir().unwrap();
7818
    let (root, bucket) = (dir.path().join("work"), dir.path().join("bucket"));
7819
    let url = format!("dir://{}", bucket.display());
7820
    let repo = Repo::init_on(&root, [7; 16], Some(&url)).unwrap();
7821
    assert_eq!(repo.config.storage_url.as_deref(), Some(url.as_str()));
7822
    write(&root, "a.txt", b"one\n");
7823
    let h1 = repo.commit("First", &[]).unwrap();
7824
    write(&root, "a.txt", b"one\ntwo\n");
7825
    let h2 = repo.commit("Second", &[]).unwrap();
7826
    assert!(
7827
        !root.join(".oxy/ops/head").exists(),
7828
        "the head is in the store"
7829
    );
7830
    assert!(bucket.join("ops/head").is_file());
7831
    assert!(root.join(".oxy/cache").is_dir());
7832
    drop(repo);
7833
7834
    // Reopened, and again with no cache at all: everything comes from the store.
7835
    for drop_cache in [false, true] {
7836
        if drop_cache {
7837
            std::fs::remove_dir_all(root.join(".oxy/cache")).unwrap();
7838
        }
7839
        let repo = Repo::open(&root).unwrap();
7840
        let log: Vec<String> = repo
7841
            .op_log()
7842
            .unwrap()
7843
            .into_iter()
7844
            .map(|(_, op)| op.command)
7845
            .collect();
7846
        assert!(log.len() >= 3, "{log:?}");
7847
        assert_eq!(repo.store().get_change(&h1).unwrap().message, "First");
7848
        let heads = repo
7849
            .store()
7850
            .get_state(&repo.view().unwrap().bookmarks["main"])
7851
            .unwrap()
7852
            .heads;
7853
        assert_eq!(heads, vec![h2]);
7854
        assert_eq!(
7855
            repo.load_state(&heads).unwrap().materialize().files.len(),
7856
            1
7857
        );
7858
    }
7859
7860
    // A second repository cannot start on the same store.
7861
    let err = Repo::init_on(&dir.path().join("other"), [8; 16], Some(&url))
7862
        .err()
7863
        .unwrap()
7864
        .to_string();
7865
    assert!(
7866
        err.contains("already holds a repository's operation log"),
7867
        "{err}"
7868
    );
7869
    let err = Repo::init_on(&dir.path().join("third"), [9; 16], Some("nope://x"))
7870
        .err()
7871
        .unwrap()
7872
        .to_string();
7873
    assert!(err.contains("cannot open that kind of store"), "{err}");
7874
}
7875
7876
/// oxygen#75: the prompt's quick check agrees with status in a repository
7877
/// with a subrepo: clean after a commit, dirty when the subrepo moves to
7878
/// another state, clean again once that pin is committed. (It compared the
7879
/// subrepo's directory as if it were a file, so it was always dirty.)
7880
#[test]
7881
fn the_quick_dirty_check_compares_a_subrepo_by_its_pin() {
7882
    hermetic();
7883
    let dir = tempfile::tempdir().unwrap();
7884
    let root = dir.path();
7885
    let _lib_origin = Repo::init(&root.join("lib-origin")).unwrap();
7886
    let lib_url = root.join("lib-origin").to_string_lossy().to_string();
7887
    let lib = Repo::clone(&lib_url, &root.join("lib"))
7888
        .unwrap()
7889
        .with_home(root.join("home"));
7890
    write(&root.join("lib"), "lib.txt", b"v1\n");
7891
    lib.commit("lib v1", &[]).unwrap();
7892
    assert!(lib.push("origin", false).unwrap()[0].ok);
7893
    let app_dir = root.join("app");
7894
    let app = Repo::init(&app_dir).unwrap().with_home(root.join("home"));
7895
    write(&app_dir, "main.txt", b"app\n");
7896
    app.submodule_add(&lib_url, "libs/lib", None).unwrap();
7897
    app.commit("app with lib", &[]).unwrap();
7898
    // Out of the racy window, so the stat-only path decides.
7899
    std::thread::sleep(std::time::Duration::from_millis(2100));
7900
    let reopen = || Repo::open(&app_dir).unwrap();
7901
    assert_eq!(
7902
        reopen().quick_dirty().unwrap(),
7903
        Some(false),
7904
        "clean, as status says"
7905
    );
7906
    let nested = Repo::open(&app_dir.join("libs/lib")).unwrap();
7907
    write(&app_dir.join("libs/lib"), "lib.txt", b"v2\n");
7908
    nested.commit("lib v2", &[]).unwrap();
7909
    assert_eq!(
7910
        reopen().quick_dirty().unwrap(),
7911
        Some(true),
7912
        "the subrepo moved"
7913
    );
7914
    reopen().commit("pin lib v2", &[]).unwrap();
7915
    std::thread::sleep(std::time::Duration::from_millis(2100));
7916
    assert_eq!(
7917
        reopen().quick_dirty().unwrap(),
7918
        Some(false),
7919
        "the new pin is committed"
7920
    );
7921
}
7922
7923
#[test]
7924
fn a_module_entry_that_was_never_added_is_reported_as_unpinned() {
7925
    // oxygen#72: a .oxymodules section with no subrepo behind it.
7926
    hermetic();
7927
    let dir = tempfile::tempdir().unwrap();
7928
    let root = dir.path();
7929
    let _lib_origin = Repo::init(&root.join("lib-origin")).unwrap();
7930
    let lib_url = root.join("lib-origin").to_string_lossy().to_string();
7931
    let lib = Repo::clone(&lib_url, &root.join("lib"))
7932
        .unwrap()
7933
        .with_home(root.join("home"));
7934
    write(&root.join("lib"), "lib.txt", b"v1\n");
7935
    lib.commit("lib v1", &[]).unwrap();
7936
    assert!(lib.push("origin", false).unwrap()[0].ok);
7937
    let app_dir = root.join("app");
7938
    let app = Repo::init(&app_dir).unwrap().with_home(root.join("home"));
7939
    write(
7940
        &app_dir,
7941
        ".oxymodules",
7942
        format!("[libs/lib]\nurl = {lib_url}\n").as_bytes(),
7943
    );
7944
    let unpinned = app.unpinned_modules().unwrap();
7945
    assert_eq!(unpinned.len(), 1);
7946
    assert_eq!(unpinned[0].0, "libs/lib");
7947
    assert_eq!(unpinned[0].1.url, lib_url);
7948
    assert!(app.submodule_update(true, &[]).unwrap().is_empty());
7949
    app.submodule_add(&lib_url, "libs/lib", None).unwrap();
7950
    assert!(app.unpinned_modules().unwrap().is_empty(), "added now");
7951
}
7952
7953
#[test]
7954
fn the_bookmark_revset_function_names_only_bookmarks() {
7955
    // oxygen#73: bookmark(NAME) is a bookmark's heads, never a tag or prefix.
7956
    hermetic();
7957
    let dir = tempfile::tempdir().unwrap();
7958
    let repo = Repo::init(dir.path()).unwrap();
7959
    write(dir.path(), "a.txt", b"a\n");
7960
    let a = repo.commit("A", &[]).unwrap();
7961
    write(dir.path(), "b.txt", b"b\n");
7962
    let b = repo.commit("B", &[]).unwrap();
7963
    let mut heads = repo.revset("bookmark(main)").unwrap().hashes;
7964
    heads.sort();
7965
    let mut want = repo.bookmark_heads().unwrap();
7966
    want.sort();
7967
    assert_eq!(heads, want);
7968
    assert!(heads.contains(&b));
7969
    assert_eq!(repo.revset("main").unwrap().hashes.len(), heads.len());
7970
    // A change prefix is a symbol, not a bookmark.
7971
    let prefix = repo.store().get_change_meta(&a).unwrap().change_id.short(8);
7972
    assert!(repo.revset(&prefix).is_ok());
7973
    let e = repo
7974
        .revset(&format!("bookmark({prefix})"))
7975
        .unwrap_err()
7976
        .to_string();
7977
    assert!(e.contains("no such bookmark"), "{e}");
7978
}
7979
7980
#[test]
7981
fn carrying_work_over_a_subrepo_already_at_the_target_pin_is_no_conflict() {
7982
    // oxygen#74: a stale state with .oxymodules but no pin, a newer one
7983
    // pinning the subrepo, and the nested repository on disk at that pin.
7984
    hermetic();
7985
    let dir = tempfile::tempdir().unwrap();
7986
    let root = dir.path();
7987
    let _lib_origin = Repo::init(&root.join("lib-origin")).unwrap();
7988
    let lib_url = root.join("lib-origin").to_string_lossy().to_string();
7989
    let lib = Repo::clone(&lib_url, &root.join("lib"))
7990
        .unwrap()
7991
        .with_home(root.join("home"));
7992
    write(&root.join("lib"), "lib.txt", b"v1\n");
7993
    lib.commit("lib v1", &[]).unwrap();
7994
    assert!(lib.push("origin", false).unwrap()[0].ok);
7995
    let app_dir = root.join("app");
7996
    let app = Repo::init(&app_dir).unwrap().with_home(root.join("home"));
7997
    write(&app_dir, "main.txt", b"app\n");
7998
    app.submodule_add(&lib_url, "libs/lib", None).unwrap();
7999
    // The stale state: registered in .oxymodules, never pinned.
8000
    fs::rename(app_dir.join("libs/lib"), root.join("aside")).unwrap();
8001
    app.commit("initial", &[]).unwrap();
8002
    let stale = app.bookmark_heads().unwrap();
8003
    fs::rename(root.join("aside"), app_dir.join("libs/lib")).unwrap();
8004
    app.commit("pin lib", &[]).unwrap();
8005
    let newer = app.bookmark_heads().unwrap();
8006
    app.checkout(&stale, false, "test").unwrap();
8007
    write(&app_dir, "notes.txt", b"mine\n");
8008
    let (_, carried) = app.checkout_carry(&newer, "main", "test").unwrap();
8009
    assert_eq!(carried, vec!["notes.txt".to_string()]);
8010
    assert!(app_dir.join("notes.txt").exists());
8011
}
8012
8013
#[test]
8014
fn a_bookmark_only_behind_its_remote_catches_up() {
8015
    // oxygen#74: switch takes the remote's state rather than a stale one.
8016
    hermetic();
8017
    let dir = tempfile::tempdir().unwrap();
8018
    let root = dir.path();
8019
    let _origin = Repo::init(&root.join("origin")).unwrap();
8020
    let url = root.join("origin").to_string_lossy().to_string();
8021
    let one = Repo::clone(&url, &root.join("one"))
8022
        .unwrap()
8023
        .with_home(root.join("home"));
8024
    write(&root.join("one"), "a.txt", b"a\n");
8025
    one.commit("A", &[]).unwrap();
8026
    assert!(one.push("origin", false).unwrap()[0].ok);
8027
    let two = Repo::clone(&url, &root.join("two"))
8028
        .unwrap()
8029
        .with_home(root.join("home"));
8030
    write(&root.join("two"), "b.txt", b"b\n");
8031
    two.commit("B", &[]).unwrap();
8032
    assert!(two.push("origin", false).unwrap()[0].ok);
8033
    assert_eq!(one.catch_up_bookmark("main").unwrap(), None, "not fetched");
8034
    one.fetch("origin").unwrap();
8035
    assert_eq!(one.catch_up_bookmark("main").unwrap(), Some(1));
8036
    assert_eq!(one.bookmarks().unwrap()[0].behind, Some(0));
8037
    // Local work the remote lacks: left alone.
8038
    write(&root.join("one"), "c.txt", b"c\n");
8039
    one.commit("C", &[]).unwrap();
8040
    write(&root.join("two"), "d.txt", b"d\n");
8041
    two.commit("D", &[]).unwrap();
8042
    assert!(two.push("origin", false).unwrap()[0].ok);
8043
    one.fetch("origin").unwrap();
8044
    assert_eq!(one.catch_up_bookmark("main").unwrap(), None);
8045
}
8046
8047
#[test]
8048
fn a_bookmark_is_compared_with_a_remote_that_has_it_when_there_is_no_origin() {
8049
    // oxygen#83: remotes earth and gcs, origin removed.
8050
    hermetic();
8051
    let dir = tempfile::tempdir().unwrap();
8052
    let root = dir.path();
8053
    let _up = Repo::init(&root.join("up")).unwrap();
8054
    let url = root.join("up").to_string_lossy().to_string();
8055
    let other = Repo::clone(&url, &root.join("other"))
8056
        .unwrap()
8057
        .with_home(root.join("home"));
8058
    write(&root.join("other"), "a.txt", b"a\n");
8059
    other.commit("a", &[]).unwrap();
8060
    assert!(other.push("origin", false).unwrap()[0].ok);
8061
    let mut one = Repo::clone(&url, &root.join("one"))
8062
        .unwrap()
8063
        .with_home(root.join("home"));
8064
    one.config.set("remote.earth.url", &url).unwrap();
8065
    one.config.set("remote.gcs.url", &url).unwrap();
8066
    one.config.set("remote.origin.url", "").unwrap();
8067
    one.save_config().unwrap();
8068
    write(&root.join("other"), "b.txt", b"b\n");
8069
    other.commit("b", &[]).unwrap();
8070
    assert!(other.push("origin", false).unwrap()[0].ok);
8071
    one.fetch("earth").unwrap();
8072
    let b = one
8073
        .bookmarks()
8074
        .unwrap()
8075
        .into_iter()
8076
        .find(|b| b.name == "main")
8077
        .unwrap();
8078
    assert_eq!(
8079
        (b.remote.as_deref(), b.behind),
8080
        (Some("earth"), Some(1)),
8081
        "a stale origin copy is not used"
8082
    );
8083
    assert_eq!(
8084
        one.default_remote(),
8085
        "origin",
8086
        "no default chosen among several"
8087
    );
8088
    let e = one.pull(&one.default_remote()).unwrap_err().to_string();
8089
    assert!(e.contains("earth, gcs") && e.contains("core.remote"), "{e}");
8090
    one.config.set("core.remote", "earth").unwrap();
8091
    assert_eq!(one.default_remote(), "earth");
8092
}
8093
8094
#[test]
8095
fn a_missing_author_identity_says_how_to_fix_it() {
8096
    // oxygen#82: an agent home's author.key naming an identity the
8097
    // repository does not hold.
8098
    hermetic();
8099
    let dir = tempfile::tempdir().unwrap();
8100
    let mut repo = Repo::init(dir.path()).unwrap();
8101
    let missing = KeyId::from_hex(&"ab".repeat(32)).unwrap();
8102
    repo.config.set("author.key", &missing.to_hex()).unwrap();
8103
    let e = repo.identity(&missing).unwrap_err().to_string();
8104
    assert!(
8105
        e.contains("this repository has no identity") && e.contains("oxy config author.key"),
8106
        "{e}"
8107
    );
8108
    assert!(e.contains("this repository's config"), "{e}");
8109
}
8110
8111
#[test]
8112
fn a_working_copy_behind_its_bookmark_is_flagged_and_pull_brings_it_up() {
8113
    // oxygen#89 (supermarioland, 2026-10-09): the bookmark moved on without
8114
    // the working copy, a pull with nothing new left it there, and status
8115
    // said "clean".
8116
    hermetic();
8117
    let dir = tempfile::tempdir().unwrap();
8118
    let root = dir.path();
8119
    let _up = Repo::init(&root.join("up")).unwrap();
8120
    let url = root.join("up").to_string_lossy().to_string();
8121
    let other = Repo::clone(&url, &root.join("other"))
8122
        .unwrap()
8123
        .with_home(root.join("home"));
8124
    write(&root.join("other"), "a.txt", b"a\n");
8125
    other.commit("a", &[]).unwrap();
8126
    assert!(other.push("origin", false).unwrap()[0].ok);
8127
    let one = Repo::clone(&url, &root.join("one"))
8128
        .unwrap()
8129
        .with_home(root.join("home"));
8130
    write(&root.join("other"), "b.txt", b"b\n");
8131
    other.commit("b", &[]).unwrap();
8132
    assert!(other.push("origin", false).unwrap()[0].ok);
8133
    one.fetch("origin").unwrap();
8134
    // The bookmark moves; the working copy does not.
8135
    let theirs = one.resolve_heads("origin/main").unwrap();
8136
    one.bookmark_set("main", &theirs).unwrap();
8137
    assert!(!root.join("one/b.txt").exists());
8138
    assert_eq!(one.working_copy_behind().unwrap(), Some(1));
8139
    let r = one.pull("origin").unwrap();
8140
    assert!(
8141
        !r.changed && r.checked_out,
8142
        "nothing new, but the working copy caught up"
8143
    );
8144
    assert!(root.join("one/b.txt").exists());
8145
    assert_eq!(one.working_copy_behind().unwrap(), None);
8146
}
8147
8148
#[test]
8149
fn touched_nodes_cache_answers_as_the_changes_do() {
8150
    hermetic();
8151
    let dir = tempfile::tempdir().unwrap();
8152
    let repo = Repo::init(dir.path()).unwrap();
8153
    write(dir.path(), "a.txt", b"one\n");
8154
    write(dir.path(), "b.txt", b"x\n");
8155
    repo.snapshot("t").unwrap();
8156
    let c1 = repo.commit("first", &[]).unwrap();
8157
    write(dir.path(), "b.txt", b"y\n");
8158
    repo.snapshot("t").unwrap();
8159
    repo.commit("b only", &[]).unwrap();
8160
    fs::rename(dir.path().join("a.txt"), dir.path().join("c.txt")).unwrap();
8161
    write(dir.path(), "c.txt", b"one\ntwo\n");
8162
    repo.snapshot("t").unwrap();
8163
    let c3 = repo.commit("rename and edit", &[]).unwrap();
8164
    // Uncommitted work, so the working copy touches a file too.
8165
    write(dir.path(), "c.txt", b"one\ntwo\nthree\n");
8166
    repo.snapshot("t").unwrap();
8167
8168
    let path = dir.path().join(".oxy/index/touched");
8169
    let hashes = |es: Vec<LogEntry>| es.iter().map(|e| e.hash).collect::<Vec<_>>();
8170
    let cold = hashes(repo.log_for_path("c.txt").unwrap());
8171
    assert!(path.exists(), "the first query writes the cache");
8172
    let warm = hashes(repo.log_for_path("c.txt").unwrap());
8173
    assert_eq!(cold, warm, "the cache answers as the changes do");
8174
    let (wc, _) = repo.working_copy().unwrap();
8175
    assert_eq!(
8176
        cold,
8177
        vec![wc, c3, c1],
8178
        "renames followed, the working copy included"
8179
    );
8180
8181
    // Working-copy changes are not kept: they are replaced by every snapshot.
8182
    let cached = super::touched::read_touched_for_test(&fs::read(&path).unwrap()).unwrap();
8183
    assert!(!cached.contains(&wc), "a working-copy change is not cached");
8184
    assert!(cached.contains(&c1) && cached.contains(&c3));
8185
8186
    // A damaged cache is ignored, not trusted.
8187
    let mut bytes = fs::read(&path).unwrap();
8188
    let last = bytes.len() - 40;
8189
    bytes[last] ^= 1;
8190
    fs::write(&path, &bytes).unwrap();
8191
    assert_eq!(hashes(repo.log_for_path("c.txt").unwrap()), cold);
8192
    let touches = repo.log_revset("touches(\"c.txt\") ~ @").unwrap();
8193
    assert_eq!(hashes(touches), vec![c3, c1]);
8194
}
8195
8196
/// oxygen#88 (vscode 9ab2056393c8): two lines of history that each move a
8197
/// file back where it was leave two placements at one place, which the
8198
/// tree shows as one file. Removing it, and then its directory, retires
8199
/// both, so no copy is left under a directory that is gone.
8200
#[test]
8201
fn git_import_removes_every_copy_of_a_file_at_one_place() {
8202
    hermetic();
8203
    if std::process::Command::new("git")
8204
        .arg("--version")
8205
        .output()
8206
        .is_err()
8207
    {
8208
        eprintln!("git not installed; skipping");
8209
        return;
8210
    }
8211
    let dir = tempfile::tempdir().unwrap();
8212
    let root = dir.path();
8213
    let g = root.join("src.git");
8214
    fs::create_dir_all(&g).unwrap();
8215
    let git = |args: &[&str]| {
8216
        let out = std::process::Command::new("git")
8217
            .arg("-C")
8218
            .arg(&g)
8219
            .args([
8220
                "-c",
8221
                "user.name=Grace",
8222
                "-c",
8223
                "[email protected]",
8224
                "-c",
8225
                "commit.gpgsign=false",
8226
            ])
8227
            .args(args)
8228
            .output()
8229
            .unwrap();
8230
        assert!(
8231
            out.status.success(),
8232
            "git {args:?}: {}",
8233
            String::from_utf8_lossy(&out.stderr)
8234
        );
8235
    };
8236
    git(&["init", "-q", "-b", "main"]);
8237
    write(&g, "d/list.txt", b"one\ntwo\nthree\nfour\n");
8238
    write(&g, "keep.txt", b"k\n");
8239
    git(&["add", "."]);
8240
    git(&["commit", "-qm", "base"]);
8241
    fs::create_dir_all(g.join("d/sub")).unwrap();
8242
    git(&["mv", "d/list.txt", "d/sub/list.txt"]);
8243
    git(&["commit", "-qm", "into sub"]);
8244
    git(&["checkout", "-qb", "side"]);
8245
    git(&["mv", "d/sub/list.txt", "d/list.txt"]);
8246
    git(&["commit", "-qm", "back, on side"]);
8247
    git(&["checkout", "-q", "main"]);
8248
    git(&["mv", "d/sub/list.txt", "d/list.txt"]);
8249
    git(&["commit", "-qm", "back, on main"]);
8250
    git(&["merge", "-q", "--no-edit", "side"]);
8251
    git(&["rm", "-rq", "d"]);
8252
    git(&["commit", "-qm", "d goes"]);
8253
8254
    let repo = Repo::init(&root.join("o")).unwrap();
8255
    repo.import_git(&g, "main").unwrap();
8256
    let v = repo.verify_git_import(&g, "main").unwrap();
8257
    assert!(v.mismatches.is_empty(), "{:?}", v.mismatches);
8258
    let st = repo
8259
        .load_state_history(&repo.bookmark_heads().unwrap())
8260
        .unwrap();
8261
    let view = st.tree().view();
8262
    assert!(view.conflicts.is_empty(), "{:?}", view.conflicts);
8263
    assert_eq!(view.entries.keys().collect::<Vec<_>>(), vec!["keep.txt"]);
8264
}
8265
8266
/// oxygen#94: a state index's file histories are read, and checked by
8267
/// their own hashes, only when a file is built. One found damaged is an
8268
/// error that says so, the index is removed, and the next read rebuilds it.
8269
#[test]
8270
fn a_damaged_file_history_in_the_state_index_is_rebuilt() {
8271
    hermetic();
8272
    let dir = tempfile::tempdir().unwrap();
8273
    let repo = Repo::init(dir.path()).unwrap();
8274
    for i in 0..6 {
8275
        write(
8276
            dir.path(),
8277
            &format!("f{i}.txt"),
8278
            format!("one {i}\n").as_bytes(),
8279
        );
8280
    }
8281
    repo.snapshot("t").unwrap();
8282
    repo.commit("first", &[]).unwrap();
8283
    for i in 0..6 {
8284
        write(
8285
            dir.path(),
8286
            &format!("f{i}.txt"),
8287
            format!("one {i}\ntwo\n").as_bytes(),
8288
        );
8289
    }
8290
    repo.snapshot("t").unwrap();
8291
    repo.commit("second", &[]).unwrap();
8292
    let want: Vec<Vec<u8>> = (0..6)
8293
        .map(|i| format!("one {i}\ntwo\n").into_bytes())
8294
        .collect();
8295
    // The index of the working copy's base, holding every file's history
8296
    // (a few changes behind, an index is replayed onto, not rewritten).
8297
    let (_, wc) = repo.working_copy().unwrap();
8298
    let base = repo.load_state_history(&wc.deps).unwrap();
8299
    repo.write_state_index(&wc.deps, &base);
8300
    for (i, w) in want.iter().enumerate() {
8301
        assert_eq!(&repo.file_at(&format!("f{i}.txt"), None).unwrap(), w);
8302
    }
8303
    let index = repo.state_indexes();
8304
    assert!(!index.is_empty(), "a state index was written");
8305
    // The histories are last in the file: damage the last of them.
8306
    let mut bytes = fs::read(&index[0]).unwrap();
8307
    let last = bytes.len() - 1;
8308
    bytes[last] ^= 0x40;
8309
    fs::write(&index[0], &bytes).unwrap();
8310
8311
    let reads: Vec<_> = (0..6)
8312
        .map(|i| repo.file_at(&format!("f{i}.txt"), None))
8313
        .collect();
8314
    let damaged: Vec<String> = reads
8315
        .iter()
8316
        .filter_map(|r| r.as_ref().err().map(|e| e.to_string()))
8317
        .collect();
8318
    assert_eq!(damaged.len(), 1, "{damaged:?}");
8319
    assert!(
8320
        damaged[0].contains("state index was damaged")
8321
            && damaged[0].contains("run the command again"),
8322
        "{}",
8323
        damaged[0]
8324
    );
8325
    // Every file reads right again, from an index rebuilt from history.
8326
    for (i, w) in want.iter().enumerate() {
8327
        assert_eq!(&repo.file_at(&format!("f{i}.txt"), None).unwrap(), w);
8328
    }
8329
}
8330
8331
/// oxygen#95: a push longer than `push.batch-bytes` goes in parts, each
8332
/// objects alone and in dependency order, and the last moves the bookmark.
8333
/// The remote ends with every change and the same state, and says how each
8334
/// part went.
8335
#[test]
8336
fn a_long_push_goes_in_parts() {
8337
    hermetic();
8338
    let dir = tempfile::tempdir().unwrap();
8339
    let root = dir.path();
8340
    let origin = root.join("origin");
8341
    Repo::init_bare_unbound(&origin).unwrap();
8342
    let main = root.join("main");
8343
    let mut repo = Repo::init(&main).unwrap();
8344
    repo.config
8345
        .set("remote.origin.url", &origin.to_string_lossy())
8346
        .unwrap();
8347
    // One byte: every change is a part of its own.
8348
    repo.config.set("push.batch-bytes", "1").unwrap();
8349
    repo.save_config().unwrap();
8350
    for i in 0..6 {
8351
        write(
8352
            &main,
8353
            &format!("f{i}.txt"),
8354
            format!("file {i}\n").as_bytes(),
8355
        );
8356
        repo.commit(&format!("c{i}"), &[]).unwrap();
8357
    }
8358
    let mut parts = Vec::new();
8359
    let results = repo
8360
        .push_bookmark_with("origin", "main", false, &mut |m| parts.push(m.to_string()))
8361
        .unwrap();
8362
    assert!(
8363
        results.iter().any(|r| r.ok && r.name == "main"),
8364
        "{results:?}"
8365
    );
8366
    assert_eq!(parts.len(), 6, "{parts:?}");
8367
    assert_eq!(parts[0], "part 1 of 6: 1 changes");
8368
8369
    let remote = Repo::open(&origin).unwrap();
8370
    let heads = repo.bookmark_heads().unwrap();
8371
    assert_eq!(remote.bookmark_heads().unwrap(), heads);
8372
    assert_eq!(
8373
        remote.log_state(&heads).unwrap().len(),
8374
        repo.log_state(&heads).unwrap().len()
8375
    );
8376
    // A push of objects alone reports how it went, as `objects`.
8377
    let got = remote
8378
        .receive_push(Bundle::default(), vec![], None, vec![])
8379
        .unwrap();
8380
    assert_eq!(got.len(), 1);
8381
    assert!(got[0].ok && got[0].name == OBJECTS_RESULT, "{got:?}");
8382
}