OXYGENHUB
# e10ba80000e1 oxygen / crates / oxy-core / src / repo / tests.rs
338.2 KiB · Rust · last changed Fetch: carry attestation signers' identities; skip an unverifiable bookmark 17 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
                grant: None,
1046
            },
1047
            &hub,
1048
            &hub_sk,
1049
        );
1050
        r.store().put_identity(&hub).unwrap();
1051
        r.store().put_certificate(&cert).unwrap();
1052
        write(&root.join(name), &format!("{name}.txt"), b"agent work\n");
1053
        r.commit("work", &[]).unwrap();
1054
        r
1055
    };
1056
1057
    let claude = agent("claude", "agent:claude@ada", now - 60_000, now + 600_000);
1058
    let r = claude.push("origin", false).unwrap();
1059
    assert!(r.iter().all(|x| x.ok), "{r:?}");
1060
    // Ada's fetch accepts the bookmark the certified key attested.
1061
    a.pull("origin").unwrap();
1062
    assert!(a.bookmark_heads().unwrap().iter().any(|h| a
1063
        .store()
1064
        .get_change(h)
1065
        .map(|c| c.message == "work")
1066
        .unwrap_or(false)));
1067
1068
    // Step 4c: a host with an acceptor key records when it accepted the
1069
    // certified update and serves it; a fetch checks the certificate at
1070
    // that time only when the certificate's issuer signed it for exactly
1071
    // this attestation, else at the attestation's own time.
1072
    let host = Repo::open(&root.join("origin"))
1073
        .unwrap()
1074
        .with_acceptor(hub.clone(), hub_sk.clone());
1075
    let (attest_ref, sa) = host.latest_ref_attest("main").unwrap().unwrap();
1076
    host.record_acceptance(&attest_ref).unwrap();
1077
    let served = host.remote_refs().unwrap();
1078
    let acc = served
1079
        .refs
1080
        .iter()
1081
        .find(|r| r.name == "main")
1082
        .unwrap()
1083
        .accepted
1084
        .clone()
1085
        .expect("served with the refs");
1086
    let signer = sa.sigs[0].key;
1087
    assert_eq!(
1088
        a.certified_time(&signer, &sa, Some(&acc)),
1089
        acc.attest.hlc.wall_ms
1090
    );
1091
    assert_eq!(a.certified_time(&signer, &sa, None), sa.attest.hlc.wall_ms);
1092
    let stranger_sk = SecretKey::generate();
1093
    let stranger = stranger_sk.identity("stranger", "s@x", 1);
1094
    let mut forged = acc.clone();
1095
    forged.sigs = vec![stranger_sk.sign(Domain::Attest, &stranger.hash(), &acc.attest.hash())];
1096
    assert_eq!(
1097
        a.certified_time(&signer, &sa, Some(&forged)),
1098
        sa.attest.hlc.wall_ms,
1099
        "not the issuer's"
1100
    );
1101
    let mut elsewhere = acc.clone();
1102
    elsewhere.attest.body = AttestBody::Accepted {
1103
        attest: ObjectRef([7; 32]),
1104
    };
1105
    elsewhere.sigs = vec![hub_sk.sign(Domain::Attest, &hub.hash(), &elsewhere.attest.hash())];
1106
    assert_eq!(
1107
        a.certified_time(&signer, &sa, Some(&elsewhere)),
1108
        sa.attest.hlc.wall_ms,
1109
        "another attestation's"
1110
    );
1111
    a.pull("origin").unwrap();
1112
    // gc keeps the acceptance with the attestation.
1113
    host.gc(true).unwrap();
1114
    assert!(host.acceptance_of(&attest_ref).unwrap().is_some());
1115
1116
    let late = agent("late", "agent:claude@ada", now - 1_200_000, now - 600_000);
1117
    let r = late.push("origin", false).unwrap();
1118
    assert!(
1119
        !r[0].ok && r[0].reason.contains("may not update"),
1120
        "an expired certificate: {r:?}"
1121
    );
1122
    let other = agent("other", "agent:mallory@ada", now - 60_000, now + 600_000);
1123
    let r = other.push("origin", false).unwrap();
1124
    assert!(
1125
        !r[0].ok && r[0].reason.contains("may not update"),
1126
        "a subject not granted: {r:?}"
1127
    );
1128
}
1129
1130
/// oxygenhub#266: a short-lived key its issuer certified moves a bookmark
1131
/// and signs no change (a keyless agent naming a bookmark). A third
1132
/// party's clone gets the key's identity, its certificate and the
1133
/// issuer's identity with the fetch, so the policy's subject grant
1134
/// authorizes the move and the signature verifies.
1135
#[test]
1136
fn a_bookmark_moved_by_a_certified_key_alone_is_fetched() {
1137
    use crate::cert::{Certificate, SignedCertificate};
1138
    use crate::identity::Scope;
1139
    hermetic();
1140
    let dir = tempfile::tempdir().unwrap();
1141
    let root = dir.path();
1142
    let _origin = Repo::init(&root.join("origin")).unwrap();
1143
    let url = root.join("origin").to_string_lossy().to_string();
1144
    let mut a = Repo::clone(&url, &root.join("a"))
1145
        .unwrap()
1146
        .with_home(root.join("home-a"));
1147
    a.create_identity("Ada", "[email protected]", IdentityScope::User)
1148
        .unwrap();
1149
    write(&root.join("a"), "a.txt", b"a\n");
1150
    a.commit("a", &[]).unwrap();
1151
    a.policy_init().unwrap();
1152
    assert!(a.push("origin", false).unwrap().iter().all(|r| r.ok));
1153
    let hub_sk = SecretKey::generate();
1154
    let hub = hub_sk.identity("hub", "[email protected]", 1);
1155
    a.policy_grant_subject(
1156
        "agent:claude@ada",
1157
        hub.clone(),
1158
        Scope::CHANGES | Scope::REFS,
1159
        None,
1160
    )
1161
    .unwrap();
1162
    assert!(a.push("origin", false).unwrap().iter().all(|r| r.ok));
1163
1164
    let now = Hlc::now().wall_ms;
1165
    let mut agent = Repo::clone(&url, &root.join("agent"))
1166
        .unwrap()
1167
        .with_home(root.join("home-agent"));
1168
    let (key, id) = agent
1169
        .create_identity("claude", "[email protected]", IdentityScope::User)
1170
        .unwrap();
1171
    let cert = SignedCertificate::sign(
1172
        Certificate {
1173
            key: id,
1174
            issuer: hub.hash(),
1175
            subject: "agent:claude@ada".into(),
1176
            claims: vec![],
1177
            scope: Scope::CHANGES | Scope::REFS,
1178
            not_before: now - 60_000,
1179
            expires: now + 600_000,
1180
            grant: None,
1181
        },
1182
        &hub,
1183
        &hub_sk,
1184
    );
1185
    agent.store().put_identity(&hub).unwrap();
1186
    agent.store().put_certificate(&cert).unwrap();
1187
    let heads = agent.bookmark_heads().unwrap();
1188
    agent.bookmark_create("agent-work", Some(&heads)).unwrap();
1189
    let r = agent.push_bookmark("origin", "agent-work", false).unwrap();
1190
    assert!(r.iter().all(|x| x.ok), "{r:?}");
1191
    let host = Repo::open(&root.join("origin")).unwrap();
1192
    let (_, sa) = host.latest_ref_attest("agent-work").unwrap().unwrap();
1193
    assert_eq!(sa.sigs[0].key, key, "the certified key alone moved it");
1194
1195
    // A fetch naming no change brings the certificate and both identities.
1196
    let bundle = host.bundle_raw_for(&[], None).unwrap();
1197
    assert!(bundle.changes.is_empty() && bundle.raw_changes.is_empty());
1198
    assert_eq!(bundle.certificates.len(), 1);
1199
    for k in [key, hub.hash()] {
1200
        assert!(bundle
1201
            .objects
1202
            .iter()
1203
            .any(|(t, b)| *t == ObjectType::Identity && hash_object(*t, b) == k));
1204
    }
1205
1206
    let c = Repo::clone(&url, &root.join("c")).unwrap();
1207
    let tracked = c.view().unwrap().remotes["origin"].clone();
1208
    assert_eq!(
1209
        tracked.get("agent-work"),
1210
        host.view().unwrap().bookmarks.get("agent-work")
1211
    );
1212
    assert!(c.store().certificate_of(&key).unwrap().is_some());
1213
}
1214
1215
/// Trusted time (oxygenhub#240, spec §14.8): a fetched attestation by a
1216
/// short-lived key is judged at its integrated time, the earliest time a
1217
/// pinned witness cosigned a checkpoint holding it. A certificate valid
1218
/// then but expired now passes; a witness this user does not trust gives
1219
/// no time (the earlier rule, said so); a backdated attestation is noted;
1220
/// an answer without the new fields is judged as before.
1221
#[test]
1222
fn a_fetched_attestation_is_judged_at_its_integrated_time() {
1223
    use super::transparency::LogCheck;
1224
    use crate::cert::{Certificate, SignedCertificate};
1225
    use crate::identity::Scope;
1226
    use crate::protocol::{Integration, Logged, RefsResponse, RemoteRef};
1227
    use crate::tlog::{self, Checkpoint, Entry, Hash, Integrated, Note};
1228
    hermetic();
1229
    let dir = tempfile::tempdir().unwrap();
1230
    let root = dir.path();
1231
    let mut a = Repo::init(&root.join("a"))
1232
        .unwrap()
1233
        .with_home(root.join("home-a"));
1234
    a.create_identity("Ada", "[email protected]", IdentityScope::User)
1235
        .unwrap();
1236
    write(&root.join("a"), "a.txt", b"a\n");
1237
    a.commit("a", &[]).unwrap();
1238
    a.policy_init().unwrap();
1239
    let issuer_sk = SecretKey::generate();
1240
    let issuer = issuer_sk.identity("hub", "[email protected]", 1);
1241
    a.policy_grant_subject(
1242
        "agent:claude@ada",
1243
        issuer.clone(),
1244
        Scope::CHANGES | Scope::REFS,
1245
        None,
1246
    )
1247
    .unwrap();
1248
    let p = a.current_policy().unwrap().unwrap().1.policy;
1249
1250
    // An agent key the issuer certified for ten minutes two hours ago.
1251
    let now = Hlc::now().wall_ms;
1252
    let t0 = now - 2 * 3_600_000;
1253
    let agent_sk = SecretKey::generate();
1254
    let agent = agent_sk.identity("claude", "[email protected]", t0);
1255
    let cert = SignedCertificate::sign(
1256
        Certificate {
1257
            key: agent.clone(),
1258
            issuer: issuer.hash(),
1259
            subject: "agent:claude@ada".into(),
1260
            claims: vec![],
1261
            scope: Scope::CHANGES | Scope::REFS,
1262
            not_before: t0,
1263
            expires: t0 + 600_000,
1264
            grant: None,
1265
        },
1266
        &issuer,
1267
        &issuer_sk,
1268
    );
1269
    a.store().put_identity(&agent).unwrap();
1270
    a.store().put_certificate(&cert).unwrap();
1271
    let signer = agent.hash();
1272
    let attested = |claimed: u64| {
1273
        let attest = Attest {
1274
            repo: a.id().unwrap(),
1275
            hlc: Hlc {
1276
                wall_ms: claimed,
1277
                logical: 0,
1278
            },
1279
            body: AttestBody::Ref {
1280
                name: "main".into(),
1281
                old_state: ObjectRef([1; 32]),
1282
                new_state: ObjectRef([2; 32]),
1283
                serial: 1,
1284
            },
1285
        };
1286
        let sig = agent_sk.sign(Domain::Attest, &signer, &attest.hash());
1287
        SignedAttest {
1288
            attest,
1289
            sigs: vec![sig],
1290
        }
1291
    };
1292
1293
    // The hub's log: eight entries, the attestation's at 3, the latest
1294
    // checkpoint of 8, and one of 4 that witnesses cosigned.
1295
    let log_sk = SecretKey::generate();
1296
    let log_key = log_sk.identity("hub.example", "[email protected]", 1);
1297
    let origin = "hub.example/log";
1298
    let hub = "https://hub.example";
1299
    let url = "https://hub.example/ada/a";
1300
    let w_sk = SecretKey::generate();
1301
    let w = w_sk.identity("w", "[email protected]", 1);
1302
    let stranger_sk = SecretKey::generate();
1303
    let stranger = stranger_sk.identity("s", "[email protected]", 1);
1304
    let sa = attested(t0 + 300_000);
1305
    let entry_of = |i: u64| {
1306
        let (kind, object) = if i == 3 {
1307
            ("ref", sa.attest.hash())
1308
        } else {
1309
            ("seal", ObjectRef([i as u8; 32]))
1310
        };
1311
        Entry {
1312
            kind: kind.into(),
1313
            repo: sa.attest.repo,
1314
            object,
1315
            signers: vec![signer],
1316
            received: t0 + 300_000,
1317
        }
1318
        .encode()
1319
    };
1320
    let mut stored: Vec<Hash> = Vec::new();
1321
    for i in 0..8 {
1322
        let add = tlog::stored_hashes_for_leaf(i, tlog::leaf_hash(&entry_of(i)), &stored).unwrap();
1323
        stored.extend(add);
1324
    }
1325
    let note_of = |n: u64, cosigners: &[(&str, &Identity, &SecretKey, u64)]| {
1326
        let mut note = Checkpoint {
1327
            origin: origin.into(),
1328
            size: n,
1329
            root: tlog::tree_hash(n, &stored).unwrap(),
1330
            extensions: vec![],
1331
        }
1332
        .sign(&log_key, &log_sk)
1333
        .unwrap();
1334
        for (name, id, sk, t) in cosigners {
1335
            note.sigs
1336
                .extend(tlog::cosign(&note.text, name, id, sk, *t).unwrap());
1337
        }
1338
        note.encode()
1339
    };
1340
    let latest = note_of(8, &[]);
1341
    let witnessed_at = (t0 + 360_000) / 1000;
1342
    let cosigned = note_of(
1343
        4,
1344
        &[
1345
            ("w.example", &w, &w_sk, witnessed_at),
1346
            ("s.example", &stranger, &stranger_sk, 1),
1347
        ],
1348
    );
1349
    let answer = |integration: Vec<Integration>, witnesses: Vec<(String, Vec<u8>)>| RefsResponse {
1350
        refs: vec![RemoteRef {
1351
            name: "main".into(),
1352
            state: ObjectRef([2; 32]),
1353
            heads: vec![],
1354
            attestation: Some(sa.clone()),
1355
            last_serial: None,
1356
            accepted: None,
1357
            logged: Some(Logged {
1358
                index: 3,
1359
                entry: entry_of(3),
1360
                proof: tlog::prove_inclusion(8, 3, &stored).unwrap(),
1361
            }),
1362
            integration,
1363
        }],
1364
        log: Some(latest.clone()),
1365
        witnesses,
1366
        ..RefsResponse::default()
1367
    };
1368
    let proof4 = tlog::prove_inclusion(4, 3, &stored).unwrap();
1369
    let served = vec![Integration {
1370
        note: cosigned.clone(),
1371
        proof: proof4.clone(),
1372
    }];
1373
    let listed = vec![("w.example".to_string(), w.encode())];
1374
    // This user saw the hub's log before (pinned, so nothing is fetched).
1375
    a.remember_log(hub, &log_key, &Note::parse(&latest).unwrap())
1376
        .unwrap();
1377
1378
    // The witness is pinned on first sight, silently; the stranger's
1379
    // earlier cosignature counts for nothing.
1380
    let resp = answer(served.clone(), listed.clone());
1381
    let lc = a.check_log(url, None, &resp).unwrap();
1382
    assert!(lc.notes.is_empty(), "{:?}", lc.notes);
1383
    let t = lc.time_of("main").unwrap();
1384
    assert_eq!((t.time, t.witness.as_str()), (witnessed_at, "w.example"));
1385
    // The certificate expired an hour and fifty minutes ago, but covered
1386
    // the integrated time: accepted, and nothing to say.
1387
    assert!(cert.cert.expires < now);
1388
    let mut notes = Vec::new();
1389
    a.authorize_in_time(&p, "origin", &resp.refs[0], &sa, &signer, &lc, &mut notes)
1390
        .unwrap();
1391
    assert!(notes.is_empty(), "{notes:?}");
1392
1393
    // Only the stranger cosigned: no witnessed time, so the earlier rule
1394
    // (the attestation's own time, inside the window), said so.
1395
    let lonely = vec![Integration {
1396
        note: note_of(4, &[("s.example", &stranger, &stranger_sk, 1)]),
1397
        proof: proof4.clone(),
1398
    }];
1399
    let resp = answer(lonely, vec![]);
1400
    let lc = a.check_log(url, None, &resp).unwrap();
1401
    assert!(lc
1402
        .time_of("main")
1403
        .unwrap_err()
1404
        .contains("no witness this user trusts"));
1405
    let mut notes = Vec::new();
1406
    a.authorize_in_time(&p, "origin", &resp.refs[0], &sa, &signer, &lc, &mut notes)
1407
        .unwrap();
1408
    assert!(
1409
        notes.len() == 1 && notes[0].contains("not at a witnessed time"),
1410
        "{notes:?}"
1411
    );
1412
1413
    // A witness listed later under the pinned name with another key is
1414
    // pinned with a note, as a new log key is.
1415
    let resp = answer(
1416
        served.clone(),
1417
        vec![("w.example".into(), stranger.encode())],
1418
    );
1419
    let lc = a.check_log(url, None, &resp).unwrap();
1420
    assert!(
1421
        lc.notes.iter().any(|n| n.contains("another key")),
1422
        "{:?}",
1423
        lc.notes
1424
    );
1425
    assert!(
1426
        lc.time_of("main").is_err(),
1427
        "w's cosignature is by its old key"
1428
    );
1429
    a.check_log(url, None, &answer(served.clone(), listed.clone()))
1430
        .unwrap();
1431
1432
    // An old peer's answer: no log, no witnesses, no integration. Judged
1433
    // as before, silently.
1434
    let mut old = answer(vec![], vec![]);
1435
    old.log = None;
1436
    old.refs[0].logged = None;
1437
    let lc = a.check_log(url, None, &old).unwrap();
1438
    assert!(!lc.kept && lc.notes.is_empty());
1439
    let mut notes = Vec::new();
1440
    a.authorize_in_time(&p, "origin", &old.refs[0], &sa, &signer, &lc, &mut notes)
1441
        .unwrap();
1442
    assert!(notes.is_empty(), "{notes:?}");
1443
1444
    // Judged at given integrated times.
1445
    let at = |secs_after_t0: u64| {
1446
        let mut times = std::collections::HashMap::new();
1447
        times.insert(
1448
            "main".to_string(),
1449
            Ok(Integrated {
1450
                time: (t0 + secs_after_t0 * 1000) / 1000,
1451
                witness: "w.example".into(),
1452
                size: 4,
1453
            }),
1454
        );
1455
        LogCheck {
1456
            kept: true,
1457
            times,
1458
            ..LogCheck::default()
1459
        }
1460
    };
1461
    let judged = |sa: &SignedAttest, lc: &LogCheck| {
1462
        let mut notes = Vec::new();
1463
        a.authorize_in_time(&p, "origin", &old.refs[0], sa, &signer, lc, &mut notes)
1464
            .map(|_| notes)
1465
    };
1466
    // Claimed inside the window, first witnessed an hour later, after
1467
    // the certificate expired: backdated, or held back. Accepted by the
1468
    // earlier rule while logs are new, with both said.
1469
    let notes = judged(&sa, &at(3600)).unwrap();
1470
    assert!(
1471
        notes
1472
            .iter()
1473
            .any(|n| n.contains("had lapsed when witness w.example"))
1474
            && notes
1475
                .iter()
1476
                .any(|n| n.contains("55 minutes before witness")),
1477
        "{notes:?}"
1478
    );
1479
    // Claimed after the certificate expired, but witnessed inside its
1480
    // window: the clock the signer did not choose decides. The gap is
1481
    // still noted.
1482
    let fast = attested(now);
1483
    let notes = judged(&fast, &at(400)).unwrap();
1484
    assert!(
1485
        notes.len() == 1 && notes[0].contains("after witness w.example saw it"),
1486
        "{notes:?}"
1487
    );
1488
    // Claimed and witnessed after it expired: refused, as before.
1489
    assert!(judged(&fast, &at(3600)).is_err());
1490
    // A gap within ten minutes is nothing to note.
1491
    assert!(judged(&sa, &at(500)).unwrap().is_empty());
1492
}
1493
1494
/// Keyless step 5 (oxygenhub#241): an agent's fresh key, certified for a
1495
/// subject the author granted, seals changes in the author's name; with
1496
/// no grant, a stranger's, or one that had ended, it is neither the
1497
/// author nor a delegate.
1498
#[test]
1499
fn a_certified_key_acts_for_its_author_under_a_grant() {
1500
    use crate::cert::{Certificate, Grant, SignedCertificate, SignedGrant};
1501
    use crate::identity::{Identity, Scope};
1502
    hermetic();
1503
    let dir = tempfile::tempdir().unwrap();
1504
    let root = dir.path();
1505
    let _origin = Repo::init(&root.join("origin")).unwrap();
1506
    let url = root.join("origin").to_string_lossy().to_string();
1507
    let mut a = Repo::clone(&url, &root.join("a"))
1508
        .unwrap()
1509
        .with_home(root.join("home-a"));
1510
    let (ada, _) = a
1511
        .create_identity("Ada", "[email protected]", IdentityScope::User)
1512
        .unwrap();
1513
    write(&root.join("a"), "a.txt", b"a\n");
1514
    a.commit("a", &[]).unwrap();
1515
    a.policy_init().unwrap();
1516
    assert!(a.push("origin", false).unwrap().iter().all(|r| r.ok));
1517
    let hub_sk = SecretKey::generate();
1518
    let hub = hub_sk.identity("hub", "[email protected]", 1);
1519
    a.policy_grant_subject(
1520
        "agent:claude@ada",
1521
        hub.clone(),
1522
        Scope::CHANGES | Scope::REFS,
1523
        None,
1524
    )
1525
    .unwrap();
1526
    assert!(a.push("origin", false).unwrap().iter().all(|r| r.ok));
1527
    let (_, ada_sk) = a.secret_key().unwrap().unwrap();
1528
    let ada_id = a.identity(&ada).unwrap();
1529
1530
    let now = Hlc::now().wall_ms;
1531
    let grant = |by: &Identity, sk: &SecretKey, from: u64, to: u64| {
1532
        SignedGrant::sign(
1533
            Grant {
1534
                grantor: by.hash(),
1535
                subject: "agent:claude@ada".into(),
1536
                issuer: hub.hash(),
1537
                scope: Scope::CHANGES | Scope::SEAL,
1538
                not_before: from,
1539
                expires: to,
1540
            },
1541
            by,
1542
            sk,
1543
        )
1544
    };
1545
    // Ada's work as an agent runs it: Ada the author, a fresh key the hub
1546
    // certified (with `g` inside) the signer.
1547
    let agent = |name: &str, g: Option<SignedGrant>| {
1548
        let mut r = Repo::clone(&url, &root.join(name))
1549
            .unwrap()
1550
            .with_home(root.join(format!("home-{name}")));
1551
        let (key, id) = r
1552
            .create_identity(name, "[email protected]", IdentityScope::User)
1553
            .unwrap();
1554
        r.set_user_config("author.key", &ada.to_hex()).unwrap();
1555
        r.set_user_config("author.signer", &key.to_hex()).unwrap();
1556
        let cert = SignedCertificate::sign(
1557
            Certificate {
1558
                key: id,
1559
                issuer: hub.hash(),
1560
                subject: "agent:claude@ada".into(),
1561
                claims: vec![],
1562
                scope: Scope::CHANGES | Scope::REFS | Scope::SEAL,
1563
                not_before: now - 60_000,
1564
                expires: now + 600_000,
1565
                grant: g,
1566
            },
1567
            &hub,
1568
            &hub_sk,
1569
        );
1570
        r.store().put_identity(&hub).unwrap();
1571
        r.store().put_certificate(&cert).unwrap();
1572
        write(&root.join(name), &format!("{name}.txt"), b"agent work\n");
1573
        let h = r.commit("work", &[]).unwrap();
1574
        assert_eq!(r.store().get_change_meta(&h).unwrap().author, ada);
1575
        (r, key, h)
1576
    };
1577
1578
    let (claude, key, h) = agent(
1579
        "claude",
1580
        Some(grant(&ada_id, &ada_sk, now - 60_000, now + 86_400_000)),
1581
    );
1582
    let r = claude.push("origin", false).unwrap();
1583
    assert!(r.iter().all(|x| x.ok), "{r:?}");
1584
    let host = Repo::open(&root.join("origin")).unwrap();
1585
    assert!(matches!(
1586
        host.authenticate_change(&h).unwrap(),
1587
        SignatureStatus::Valid { key: k, sealed: true, .. } if k == key
1588
    ));
1589
    a.pull("origin").unwrap();
1590
    assert!(matches!(
1591
        a.authenticate_change(&h).unwrap(),
1592
        SignatureStatus::Valid { key: k, .. } if k == key
1593
    ));
1594
1595
    let (none, _, _) = agent("none", None);
1596
    let r = none.push("origin", false).unwrap();
1597
    assert!(r.iter().all(|x| !x.ok), "no grant: {r:?}");
1598
    let mallory_sk = SecretKey::generate();
1599
    let mallory = mallory_sk.identity("Mallory", "[email protected]", 1);
1600
    let (stranger, _, _) = agent(
1601
        "stranger",
1602
        Some(grant(&mallory, &mallory_sk, now - 60_000, now + 600_000)),
1603
    );
1604
    let r = stranger.push("origin", false).unwrap();
1605
    assert!(r.iter().all(|x| !x.ok), "a stranger's grant: {r:?}");
1606
    let (ended, _, eh) = agent(
1607
        "ended",
1608
        Some(grant(&ada_id, &ada_sk, now - 7_200_000, now - 3_600_000)),
1609
    );
1610
    let r = ended.push("origin", false).unwrap();
1611
    assert!(r.iter().all(|x| !x.ok), "an ended grant: {r:?}");
1612
    assert!(matches!(
1613
        ended.authenticate_change(&eh).unwrap(),
1614
        SignatureStatus::Invalid(e) if e.contains("grant did not cover")
1615
    ));
1616
}
1617
1618
#[test]
1619
fn trust_policy_governs_pushes_and_fetches() {
1620
    hermetic();
1621
    let dir = tempfile::tempdir().unwrap();
1622
    let root = dir.path();
1623
    let origin = Repo::init(&root.join("origin")).unwrap();
1624
    let url = root.join("origin").to_string_lossy().to_string();
1625
1626
    // A is the root. Before the policy, an unsigned push from B is fine.
1627
    let mut a = Repo::clone(&url, &root.join("a"))
1628
        .unwrap()
1629
        .with_home(root.join("home-a"));
1630
    let (key_a, _) = a
1631
        .create_identity("Ada", "[email protected]", IdentityScope::User)
1632
        .unwrap();
1633
    let mut b = Repo::clone(&url, &root.join("b"))
1634
        .unwrap()
1635
        .with_home(root.join("home-b"));
1636
    write(&root.join("b"), "b.txt", b"b\n");
1637
    b.commit("unsigned before policy", &[]).unwrap();
1638
    assert!(b.push("origin", false).unwrap()[0].ok);
1639
1640
    // A creates the policy and pushes it; origin now enforces it.
1641
    write(&root.join("a"), "a.txt", b"a\n");
1642
    a.commit("a", &[]).unwrap();
1643
    let sp = a.policy_init().unwrap();
1644
    assert_eq!(sp.policy.serial, 1);
1645
    a.pull("origin").unwrap();
1646
    let results = a.push("origin", false).unwrap();
1647
    assert!(results.iter().all(|r| r.ok), "{results:?}");
1648
    assert_eq!(origin.current_policy().unwrap().unwrap().1.policy.serial, 1);
1649
1650
    // B pulls the policy. Without an identity B cannot push at all.
1651
    b.pull("origin").unwrap();
1652
    assert!(
1653
        b.current_policy().unwrap().is_some(),
1654
        "the policy arrived with the fetch"
1655
    );
1656
    assert!(b.push("origin", false).is_err());
1657
    // With an identity the policy does not list, the push is rejected by origin.
1658
    let (key_b, id_b) = b
1659
        .create_identity("Bob", "[email protected]", IdentityScope::User)
1660
        .unwrap();
1661
    write(&root.join("b"), "b.txt", b"b2\n");
1662
    let h_b2 = b.commit("b2 as Bob", &[]).unwrap();
1663
    assert_eq!(b.store().get_change(&h_b2).unwrap().author, key_b);
1664
    let r = b.push("origin", false).unwrap();
1665
    assert!(
1666
        !r[0].ok && r[0].reason.contains("may not update"),
1667
        "{:?}",
1668
        r
1669
    );
1670
1671
    // A grants B (identity handed over as a file) and publishes the policy.
1672
    let sp = a.policy_grant(id_b.clone(), None).unwrap();
1673
    assert_eq!(sp.policy.serial, 2);
1674
    let r = a.push("origin", false).unwrap();
1675
    assert!(r.iter().any(|x| x.name == "policy" && x.ok), "{r:?}");
1676
    // B must fetch the new policy before pushing.
1677
    assert!(b
1678
        .push("origin", false)
1679
        .unwrap_or_else(|e| vec![RefResult {
1680
            name: "main".into(),
1681
            ok: false,
1682
            reason: e.to_string()
1683
        }])
1684
        .iter()
1685
        .all(|x| !x.ok));
1686
    b.pull("origin").unwrap();
1687
    assert_eq!(b.current_policy().unwrap().unwrap().1.policy.serial, 2);
1688
    let r = b.push("origin", false).unwrap();
1689
    assert!(r[0].ok, "{:?}", r);
1690
    // Origin verified B's change under the policy.
1691
    let heads = origin.bookmark_heads().unwrap();
1692
    for h in &heads {
1693
        let c = origin.store().get_change(h).unwrap();
1694
        if c.author == key_b {
1695
            origin
1696
                .change_allowed(
1697
                    h,
1698
                    &origin.current_policy().unwrap().unwrap().1.policy,
1699
                    "main",
1700
                )
1701
                .unwrap();
1702
        }
1703
    }
1704
1705
    // A policy signed by a non-root (B) is refused, as is a replayed serial.
1706
    let mut forged = b.current_policy().unwrap().unwrap().1.policy.clone();
1707
    forged.serial = 3;
1708
    forged.roots = vec![key_b];
1709
    let fh = forged.hash();
1710
    let (_, sk_b) = b.secret_key().unwrap().unwrap();
1711
    let forged = SignedPolicy {
1712
        policy: forged,
1713
        sigs: vec![sk_b.sign(Domain::Policy, &key_b, &fh)],
1714
    };
1715
    let r = origin
1716
        .receive_push(Bundle::default(), vec![], Some(forged), vec![])
1717
        .unwrap();
1718
    assert!(!r[0].ok && r[0].reason.contains("root"), "{:?}", r);
1719
    let stale = a.current_policy().unwrap().unwrap().1;
1720
    let mut old = stale.clone();
1721
    old.policy.serial = 1;
1722
    let r = origin
1723
        .receive_push(Bundle::default(), vec![], Some(old), vec![])
1724
        .unwrap();
1725
    assert!(!r[0].ok && r[0].reason.contains("serial"), "{:?}", r);
1726
1727
    // A revokes B; after B pulls the policy, B's pushes are refused again.
1728
    a.pull("origin").unwrap();
1729
    a.policy_revoke(&key_b).unwrap();
1730
    let r = a.push("origin", false).unwrap();
1731
    assert!(r.iter().any(|x| x.name == "policy" && x.ok), "{r:?}");
1732
    b.pull("origin").unwrap();
1733
    write(&root.join("b"), "b.txt", b"b3\n");
1734
    b.commit("b3", &[]).unwrap();
1735
    let r = b.push("origin", false).unwrap();
1736
    assert!(!r[0].ok, "{:?}", r);
1737
1738
    // A clone by a third party receives and verifies everything.
1739
    let c = Repo::clone(&url, &root.join("c"))
1740
        .unwrap()
1741
        .with_home(root.join("home-c"));
1742
    assert_eq!(c.current_policy().unwrap().unwrap().1.policy.serial, 3);
1743
    assert!(c
1744
        .current_policy()
1745
        .unwrap()
1746
        .unwrap()
1747
        .1
1748
        .policy
1749
        .roots
1750
        .contains(&key_a));
1751
    assert!(!c.snapshot("status").unwrap().changed);
1752
}
1753
1754
/// oxygen#66: a gc says what it is doing, phase by phase.
1755
#[test]
1756
fn gc_reports_its_phases() {
1757
    hermetic();
1758
    let dir = tempfile::tempdir().unwrap();
1759
    let repo = Repo::init(dir.path()).unwrap();
1760
    for i in 0..3 {
1761
        write(
1762
            dir.path(),
1763
            &format!("f{i}.txt"),
1764
            format!("{i}\n").as_bytes(),
1765
        );
1766
        repo.commit(&format!("c{i}"), &[]).unwrap();
1767
    }
1768
    let mut phases = Vec::new();
1769
    repo.gc_with(true, &mut |p| phases.push(p.to_string()))
1770
        .unwrap();
1771
    assert_eq!(phases[0], "finding what is reachable", "{phases:?}");
1772
    assert!(
1773
        phases.iter().any(|p| p.starts_with("pruning")),
1774
        "{phases:?}"
1775
    );
1776
    assert!(
1777
        phases.iter().any(|p| p.starts_with("packing 0 of ")),
1778
        "{phases:?}"
1779
    );
1780
    assert!(
1781
        phases
1782
            .iter()
1783
            .any(|p| p.starts_with("writing the index of ")),
1784
        "{phases:?}"
1785
    );
1786
}
1787
1788
#[test]
1789
fn gc_packs_objects_and_history_still_works() {
1790
    hermetic();
1791
    let dir = tempfile::tempdir().unwrap();
1792
    let root = dir.path();
1793
    let mut repo = Repo::init(root).unwrap().with_home(root.join("home"));
1794
    repo.create_identity("Ada", "a@b", IdentityScope::User)
1795
        .unwrap();
1796
    repo.set_user_config("core.sign", "change").unwrap();
1797
    write(root, "a.txt", b"one\n");
1798
    let h1 = repo.commit("one", &[]).unwrap();
1799
    write(root, "a.txt", b"two\n");
1800
    write(root, "big.bin", &vec![0u8; 100_000]);
1801
    let h2 = repo.commit("two", &[]).unwrap();
1802
    // Several snapshots leave superseded working-copy versions behind.
1803
    for i in 0..5 {
1804
        write(root, "a.txt", format!("two\n{i}\n").as_bytes());
1805
        repo.snapshot("status").unwrap();
1806
    }
1807
    write(root, "a.txt", b"two\n");
1808
    repo.snapshot("status").unwrap();
1809
    let before = repo.store().list().unwrap();
1810
    assert!(repo.store().loose_count().unwrap() > 0);
1811
1812
    // With the default retention every operation's view is a root: nothing prunes.
1813
    let r = repo.gc(true).unwrap();
1814
    assert_eq!(r.packed.objects, before.len());
1815
    assert_eq!(r.pruned.objects, 0);
1816
    assert_eq!(repo.store().loose_count().unwrap(), 0);
1817
    assert_eq!(repo.store().list().unwrap(), before);
1818
1819
    // With zero retention only the current view is a root: superseded
1820
    // working copies go, everything reachable stays.
1821
    repo.config.set("core.op-retention", "0").unwrap();
1822
    repo.save_config().unwrap();
1823
    let mut repo = Repo::open(root).unwrap().with_home(root.join("home"));
1824
    let r = repo.gc(true).unwrap();
1825
    assert!(r.pruned.objects >= 5, "{r:?}");
1826
    let after = repo.store().list().unwrap();
1827
    assert!(after.len() < before.len());
1828
    assert!(after.contains(&h1) && after.contains(&h2));
1829
    for (_, op) in repo.op_log().unwrap() {
1830
        assert!(!op.command.is_empty(), "operation objects are all kept");
1831
    }
1832
    // Everything still works from the pruned, packed store.
1833
    assert_eq!(repo.bookmark_heads().unwrap(), vec![h2]);
1834
    assert!(matches!(
1835
        repo.verify_change(&h2).unwrap(),
1836
        SignatureStatus::Valid { .. }
1837
    ));
1838
    assert_eq!(repo.log().unwrap().len(), 3);
1839
    repo.checkout(&[h1], false, "checkout").unwrap();
1840
    assert_eq!(fs::read(root.join("a.txt")).unwrap(), b"one\n");
1841
    repo.checkout(&[h2], false, "checkout").unwrap();
1842
    assert_eq!(fs::read(root.join("big.bin")).unwrap().len(), 100_000);
1843
    assert!(!repo.snapshot("status").unwrap().changed);
1844
    // Grace period defers pruning of young garbage.
1845
    write(root, "a.txt", b"three\n");
1846
    repo.commit("three", &[]).unwrap();
1847
    let r = repo.gc(false).unwrap();
1848
    assert_eq!(r.pruned.objects, 0);
1849
    assert!(r.pruned.deferred > 0);
1850
    let r = repo.gc(true).unwrap();
1851
    assert!(r.pruned.objects > 0);
1852
    assert_eq!(repo.log().unwrap().len(), 4);
1853
    // Restoring the default retention makes the old views roots again; the
1854
    // working copies they name were pruned, which gc tolerates.
1855
    repo.config.set("core.op-retention", "90").unwrap();
1856
    repo.save_config().unwrap();
1857
    let repo = Repo::open(root).unwrap().with_home(root.join("home"));
1858
    let r = repo.gc(false).unwrap();
1859
    assert_eq!(r.pruned.objects, 0);
1860
    assert_eq!(repo.log().unwrap().len(), 4);
1861
}
1862
1863
#[test]
1864
fn describe_amend_abandon_heads() {
1865
    hermetic();
1866
    let dir = tempfile::tempdir().unwrap();
1867
    let root = dir.path();
1868
    let mut repo = Repo::init(root).unwrap().with_home(root.join("home"));
1869
    repo.create_identity("Ada", "a@b", IdentityScope::User)
1870
        .unwrap();
1871
    repo.set_user_config("core.sign", "change").unwrap();
1872
    write(root, "a.txt", b"one\n");
1873
    let h1 = repo.commit("first", &[]).unwrap();
1874
    write(root, "a.txt", b"one\ntwo\n");
1875
    let h2 = repo.commit("secnod", &[]).unwrap();
1876
    let id2 = repo.store().get_change(&h2).unwrap().change_id;
1877
1878
    // describe: same ChangeId, new hash, bookmark and working copy follow.
1879
    let h2b = repo.describe(&h2, "second").unwrap();
1880
    assert_ne!(h2b, h2);
1881
    let c = repo.store().get_change(&h2b).unwrap();
1882
    assert_eq!(
1883
        (c.change_id, c.message.as_str(), c.deps.clone()),
1884
        (id2, "second", vec![h1])
1885
    );
1886
    assert_eq!(repo.bookmark_heads().unwrap(), vec![h2b]);
1887
    assert!(matches!(
1888
        repo.verify_change(&h2b).unwrap(),
1889
        SignatureStatus::Valid { .. }
1890
    ));
1891
    let s = repo.snapshot("status").unwrap();
1892
    assert!(s.statuses.is_empty(), "{:?}", s.statuses);
1893
    assert_eq!(
1894
        repo.resolve_change(&id2.short(8)).unwrap(),
1895
        h2b,
1896
        "the old object is no longer reachable from the log"
1897
    );
1898
    // Describing a non-head rewrites its dependents (h2b → h2c') and the working copy.
1899
    let h1b = repo.describe(&h1, "first, described").unwrap();
1900
    assert_ne!(h1b, h1);
1901
    let heads = repo.bookmark_heads().unwrap();
1902
    assert_eq!(heads.len(), 1);
1903
    let top = repo.store().get_change(&heads[0]).unwrap();
1904
    assert_eq!((top.change_id, top.deps.clone()), (id2, vec![h1b]));
1905
    assert!(
1906
        matches!(
1907
            repo.verify_change(&heads[0]).unwrap(),
1908
            SignatureStatus::Valid { .. }
1909
        ),
1910
        "rewritten own change is re-signed"
1911
    );
1912
    let (_, wc) = repo.working_copy().unwrap();
1913
    assert_eq!(
1914
        wc.deps,
1915
        vec![heads[0]],
1916
        "the working copy follows the rewrite"
1917
    );
1918
    assert!(!repo.snapshot("status").unwrap().changed);
1919
    let snap = repo.load_state(&heads).unwrap().materialize();
1920
    assert!(
1921
        matches!(&snap.files["a.txt"].content, FileContent::Text { bytes, .. } if bytes == b"one\ntwo\n")
1922
    );
1923
1924
    // amend: fold an edit into the head; the result is one change from h1.
1925
    write(root, "a.txt", b"one\ntwo\nthree\n");
1926
    write(root, "b.txt", b"b\n");
1927
    let h2c = repo.amend(None).unwrap();
1928
    let c = repo.store().get_change(&h2c).unwrap();
1929
    assert_eq!(c.change_id, id2);
1930
    assert_eq!(c.message, "second");
1931
    assert_eq!(repo.bookmark_heads().unwrap(), vec![h2c]);
1932
    assert_eq!(
1933
        repo.log().unwrap().len(),
1934
        3,
1935
        "working copy, amended head, first"
1936
    );
1937
    let snap = repo.load_state(&[h2c]).unwrap().materialize();
1938
    assert!(
1939
        matches!(&snap.files["a.txt"].content, FileContent::Text { bytes, .. } if bytes == b"one\ntwo\nthree\n")
1940
    );
1941
    assert!(snap.files.contains_key("b.txt"));
1942
    assert!(!repo.snapshot("status").unwrap().changed);
1943
    assert!(
1944
        repo.amend(None).is_err(),
1945
        "clean working copy and no message"
1946
    );
1947
    let h2d = repo.amend(Some("second, amended")).unwrap();
1948
    assert_eq!(
1949
        repo.store().get_change(&h2d).unwrap().message,
1950
        "second, amended"
1951
    );
1952
1953
    // abandon: the head goes, its content stays as uncommitted work.
1954
    repo.abandon(&h2d).unwrap();
1955
    assert_eq!(
1956
        repo.bookmark_heads().unwrap(),
1957
        vec![h1b],
1958
        "the described first change is the head again"
1959
    );
1960
    let s = repo.snapshot("status").unwrap();
1961
    let paths: Vec<_> = s
1962
        .statuses
1963
        .iter()
1964
        .map(|p| (p.path.as_str(), p.status))
1965
        .collect();
1966
    assert_eq!(
1967
        paths,
1968
        vec![
1969
            ("a.txt", ChangeStatus::Modified),
1970
            ("b.txt", ChangeStatus::Added)
1971
        ]
1972
    );
1973
    assert_eq!(fs::read(root.join("a.txt")).unwrap(), b"one\ntwo\nthree\n");
1974
    let h3 = repo.commit("recommitted", &[]).unwrap();
1975
    assert_eq!(repo.bookmark_heads().unwrap(), vec![h3]);
1976
    // undo brings the abandoned head back.
1977
    repo.undo().unwrap();
1978
    repo.undo().unwrap();
1979
    assert_eq!(repo.bookmark_heads().unwrap(), vec![h2d]);
1980
1981
    // Abandoning a non-head whose dependent references its atoms reifies
1982
    // the references (here: a.txt vanishes with it, so the dependent's edit
1983
    // of a.txt is dropped with a note) instead of refusing; undo restores it.
1984
    let base = repo.bookmark_heads().unwrap()[0];
1985
    let base_change = repo.store().get_change(&base).unwrap();
1986
    let h1_now = base_change.deps[0];
1987
    let notes = repo.abandon(&h1_now).unwrap();
1988
    assert!(
1989
        !notes.is_empty(),
1990
        "the dependent's edit of a.txt was reified"
1991
    );
1992
    let heads = repo.bookmark_heads().unwrap();
1993
    let after = repo.load_state(&heads).unwrap().materialize();
1994
    assert!(
1995
        !after.files.contains_key("a.txt") && after.files.contains_key("b.txt"),
1996
        "{:?}",
1997
        after.files.keys()
1998
    );
1999
    repo.undo().unwrap();
2000
    assert_eq!(repo.bookmark_heads().unwrap(), vec![base]);
2001
    write(root, "c.txt", b"c\n");
2002
    let hc = repo.commit("c", &[]).unwrap();
2003
    write(root, "d.txt", b"d\n");
2004
    let hd = repo.commit("d", &[hc]).unwrap();
2005
    assert_eq!(repo.store().get_change(&hd).unwrap().deps, vec![hc]);
2006
    repo.abandon(&hc).unwrap();
2007
    let heads: BTreeSet<_> = repo.bookmark_heads().unwrap().into_iter().collect();
2008
    assert!(!heads.contains(&hc));
2009
    let d_now = heads
2010
        .iter()
2011
        .find(|h| repo.store().get_change(h).unwrap().message == "d")
2012
        .copied()
2013
        .unwrap();
2014
    assert!(
2015
        repo.store().get_change(&d_now).unwrap().deps.is_empty(),
2016
        "d inherited c's (empty) dependencies"
2017
    );
2018
    let s = repo.snapshot("status").unwrap();
2019
    assert_eq!(
2020
        s.statuses
2021
            .iter()
2022
            .map(|p| p.path.as_str())
2023
            .collect::<Vec<_>>(),
2024
        vec!["c.txt"],
2025
        "c's content is now uncommitted work"
2026
    );
2027
}
2028
2029
#[test]
2030
fn git_export_mirrors_history() {
2031
    hermetic();
2032
    if std::process::Command::new("git")
2033
        .arg("--version")
2034
        .output()
2035
        .is_err()
2036
    {
2037
        eprintln!("git not installed; skipping");
2038
        return;
2039
    }
2040
    let dir = tempfile::tempdir().unwrap();
2041
    let root = dir.path();
2042
    let mut repo = Repo::init(&root.join("r"))
2043
        .unwrap()
2044
        .with_home(root.join("home"));
2045
    repo.create_identity("Ada Lovelace", "[email protected]", IdentityScope::User)
2046
        .unwrap();
2047
    let r = root.join("r");
2048
    write(&r, "README.md", b"hello\n");
2049
    write(&r, "src/main.rs", b"fn main() {}\n");
2050
    let h1 = repo.commit("first", &[]).unwrap();
2051
    write(&r, "src/main.rs", b"fn main() { run(); }\n");
2052
    write(&r, "logo.png", b"\x89PNG\0\0");
2053
    let h2 = repo.commit("second", &[]).unwrap();
2054
2055
    let git_dir = root.join("mirror.git");
2056
    let rep = repo.git_export(&git_dir).unwrap();
2057
    assert_eq!((rep.exported, rep.skipped, rep.heads), (2, 0, 1));
2058
    let git = |args: &[&str]| -> String {
2059
        let out = std::process::Command::new("git")
2060
            .arg("-C")
2061
            .arg(&git_dir)
2062
            .args(args)
2063
            .output()
2064
            .unwrap();
2065
        assert!(
2066
            out.status.success(),
2067
            "{}",
2068
            String::from_utf8_lossy(&out.stderr)
2069
        );
2070
        String::from_utf8_lossy(&out.stdout).trim().to_string()
2071
    };
2072
    assert_eq!(git(&["log", "--format=%s", "main"]), "second\nfirst");
2073
    assert_eq!(git(&["show", "main:src/main.rs"]), "fn main() { run(); }");
2074
    assert_eq!(git(&["show", "main:README.md"]), "hello");
2075
    let body = git(&["log", "-1", "--format=%B", "main"]);
2076
    assert!(
2077
        body.contains(&format!("Oxy-Hash: {}", h2.to_hex())),
2078
        "{body}"
2079
    );
2080
    assert!(body.contains("Change-Id: "), "{body}");
2081
    assert_eq!(
2082
        git(&["log", "-1", "--format=%an <%ae>", "main"]),
2083
        "Ada Lovelace <[email protected]>"
2084
    );
2085
    assert_eq!(
2086
        git(&["ls-tree", "--name-only", "main"]),
2087
        "README.md\nlogo.png\nsrc"
2088
    );
2089
2090
    // Re-export is incremental.
2091
    let rep = repo.git_export(&git_dir).unwrap();
2092
    assert_eq!((rep.exported, rep.skipped), (0, 2));
2093
2094
    // An independent change makes two heads; the next state is one more
2095
    // commit on the linear branch whose tree is the union.
2096
    repo.checkout(&[h1], false, "checkout").unwrap();
2097
    write(&r, "other.txt", b"o\n");
2098
    let h3 = repo.commit("third", &[]).unwrap();
2099
    let rep = repo.git_export(&git_dir).unwrap();
2100
    assert_eq!((rep.exported, rep.heads), (1, 2));
2101
    assert_eq!(git(&["log", "--format=%s", "main"]), "third\nsecond\nfirst");
2102
    let parents = git(&["rev-list", "--parents", "-1", "main"]);
2103
    assert_eq!(parents.split(' ').count(), 2, "one parent: {parents}");
2104
    assert_eq!(git(&["show", "main:other.txt"]), "o");
2105
    assert_eq!(git(&["show", "main:src/main.rs"]), "fn main() { run(); }");
2106
    assert_eq!(
2107
        git(&["ls-tree", "--name-only", "main"]),
2108
        "README.md\nlogo.png\nother.txt\nsrc"
2109
    );
2110
    let body = git(&["log", "-1", "--format=%B", "main"]);
2111
    assert!(
2112
        body.contains(&format!("Oxy-Hash: {}", h3.to_hex())) && body.contains("Oxy-State: "),
2113
        "{body}"
2114
    );
2115
    // A rewrite is a new state whose one new change is the rewritten one.
2116
    repo.describe(&h3, "third, described").unwrap();
2117
    let rep = repo.git_export(&git_dir).unwrap();
2118
    assert_eq!(rep.exported, 1);
2119
    assert_eq!(
2120
        git(&["log", "-1", "--format=%s", "main"]),
2121
        "third, described"
2122
    );
2123
    assert_eq!(git(&["log", "--format=%s", "main"]).lines().count(), 4);
2124
    let _ = h2;
2125
}
2126
2127
#[test]
2128
fn git_import_reproduces_trees() {
2129
    git_import_reproduces_trees_with(None);
2130
}
2131
2132
/// The same import with every merge rendered in batches of one file
2133
/// (oxygen#25): what a merge onto a base of thousands of files takes.
2134
#[test]
2135
fn git_import_reproduces_trees_in_batches() {
2136
    git_import_reproduces_trees_with(Some(1));
2137
}
2138
2139
fn git_import_reproduces_trees_with(batch: Option<usize>) {
2140
    crate::repo::git::set_merge_batch_for_tests(batch);
2141
    hermetic();
2142
    if std::process::Command::new("git")
2143
        .arg("--version")
2144
        .output()
2145
        .is_err()
2146
    {
2147
        eprintln!("git not installed; skipping");
2148
        return;
2149
    }
2150
    let dir = tempfile::tempdir().unwrap();
2151
    let root = dir.path();
2152
    let g = root.join("src.git");
2153
    fs::create_dir_all(&g).unwrap();
2154
    let git = |args: &[&str]| -> String {
2155
        let out = std::process::Command::new("git")
2156
            .arg("-C")
2157
            .arg(&g)
2158
            .args([
2159
                "-c",
2160
                "user.name=Grace",
2161
                "-c",
2162
                "[email protected]",
2163
                "-c",
2164
                "commit.gpgsign=false",
2165
            ])
2166
            .args(args)
2167
            .output()
2168
            .unwrap();
2169
        assert!(
2170
            out.status.success(),
2171
            "git {args:?}: {}",
2172
            String::from_utf8_lossy(&out.stderr)
2173
        );
2174
        String::from_utf8_lossy(&out.stdout).trim().to_string()
2175
    };
2176
    git(&["init", "-q", "-b", "main"]);
2177
    write(&g, "README.md", b"# Hi\n");
2178
    write(&g, "src/lib.rs", b"pub fn a() {}\n");
2179
    git(&["add", "."]);
2180
    git(&["commit", "-q", "-m", "initial"]);
2181
    write(&g, "src/lib.rs", b"pub fn a() {}\npub fn b() {}\n");
2182
    write(&g, "run.sh", b"#!/bin/sh\n");
2183
    #[cfg(unix)]
2184
    {
2185
        use std::os::unix::fs::PermissionsExt;
2186
        fs::set_permissions(g.join("run.sh"), fs::Permissions::from_mode(0o755)).unwrap();
2187
    }
2188
    write(&g, "logo.png", b"\x89PNG\0\0\x01");
2189
    git(&["add", "."]);
2190
    git(&[
2191
        "commit",
2192
        "-q",
2193
        "-m",
2194
        "second\n\nChange-Id: 0123456789abcdef0123456789abcdef",
2195
    ]);
2196
    // A branch that edits README, merged back with a conflict-free merge.
2197
    git(&["checkout", "-q", "-b", "topic", "HEAD~1"]);
2198
    write(&g, "README.md", b"# Hi\n\nMore.\n");
2199
    git(&["commit", "-q", "-am", "readme"]);
2200
    git(&["checkout", "-q", "main"]);
2201
    git(&["merge", "-q", "--no-ff", "-m", "merge topic", "topic"]);
2202
    // A branch from the initial commit inserting at the same place as
2203
    // "second": concurrent in Oxygen too, so the merge commit is a resolution.
2204
    let initial = git(&["rev-list", "--max-parents=0", "HEAD"]);
2205
    git(&["checkout", "-q", "-b", "clash", &initial]);
2206
    write(&g, "src/lib.rs", b"pub fn a() {}\npub fn c() {}\n");
2207
    git(&["commit", "-q", "-am", "clash"]);
2208
    git(&["checkout", "-q", "main"]);
2209
    let _ = std::process::Command::new("git")
2210
        .arg("-C")
2211
        .arg(&g)
2212
        .args(["merge", "-q", "clash"])
2213
        .output();
2214
    write(
2215
        &g,
2216
        "src/lib.rs",
2217
        b"pub fn a() {}\npub fn b() {}\npub fn c() {}\n",
2218
    );
2219
    git(&["add", "."]);
2220
    git(&["commit", "-q", "-m", "resolve clash"]);
2221
    git(&["rm", "-q", "logo.png"]);
2222
    git(&["commit", "-q", "-m", "drop logo"]);
2223
    // A rename with a small edit is imported as a move of the same node.
2224
    git(&["mv", "src/lib.rs", "src/lib2.rs"]);
2225
    write(
2226
        &g,
2227
        "src/lib2.rs",
2228
        b"pub fn a() {}\npub fn b() {}\npub fn c() {}\npub fn d() {}\n",
2229
    );
2230
    git(&["add", "."]);
2231
    git(&["commit", "-q", "-m", "rename lib"]);
2232
    // A branch that edits run.sh, merged keeping main's tree (`-s ours`):
2233
    // run.sh is the same as in the first parent's tree, but the merged
2234
    // change touched it, so the importer must compare it, not skip it.
2235
    git(&["checkout", "-q", "-b", "discarded"]);
2236
    write(&g, "run.sh", b"#!/bin/sh\necho discarded\n");
2237
    git(&["commit", "-q", "-am", "discarded edit"]);
2238
    git(&["checkout", "-q", "main"]);
2239
    git(&[
2240
        "merge",
2241
        "-q",
2242
        "-s",
2243
        "ours",
2244
        "-m",
2245
        "merge discarded, keeping ours",
2246
        "discarded",
2247
    ]);
2248
    let expected_count: usize = git(&["rev-list", "--count", "main"]).parse().unwrap();
2249
2250
    let dest = root.join("oxy");
2251
    let repo = Repo::init(&dest).unwrap().with_home(root.join("home"));
2252
    let rep = repo.import_git(&g, "main").unwrap();
2253
    assert_eq!(rep.commits, expected_count);
2254
    assert_eq!(rep.merges, 3);
2255
    assert_eq!(
2256
        fs::read(dest.join("run.sh")).unwrap(),
2257
        b"#!/bin/sh\n",
2258
        "the ours merge kept main's run.sh"
2259
    );
2260
    let v = repo.verify_git_import(&g, "main").unwrap();
2261
    assert_eq!(v.commits, expected_count, "every commit's tree reproduced");
2262
    assert!(v.mismatches.is_empty(), "{:?}", v.mismatches);
2263
    // The working copy equals the Git tree at main.
2264
    assert_eq!(
2265
        fs::read(dest.join("src/lib2.rs")).unwrap(),
2266
        b"pub fn a() {}\npub fn b() {}\npub fn c() {}\npub fn d() {}\n"
2267
    );
2268
    assert!(!dest.join("src/lib.rs").exists());
2269
    assert_eq!(
2270
        fs::read(dest.join("README.md")).unwrap(),
2271
        b"# Hi\n\nMore.\n"
2272
    );
2273
    assert!(!dest.join("logo.png").exists());
2274
    #[cfg(unix)]
2275
    {
2276
        use std::os::unix::fs::PermissionsExt;
2277
        assert!(
2278
            fs::metadata(dest.join("run.sh"))
2279
                .unwrap()
2280
                .permissions()
2281
                .mode()
2282
                & 0o111
2283
                != 0
2284
        );
2285
    }
2286
    assert!(
2287
        !repo.snapshot("status").unwrap().changed,
2288
        "clean after import"
2289
    );
2290
    let heads = repo.bookmark_heads().unwrap();
2291
    let st = repo.load_state(&heads).unwrap();
2292
    assert!(!st.materialize().is_conflicted());
2293
    assert_eq!(st.len(), expected_count);
2294
    let tip = repo
2295
        .log()
2296
        .unwrap()
2297
        .into_iter()
2298
        .find(|e| e.change.message.starts_with("rename lib"))
2299
        .unwrap();
2300
    let c = repo.store().get_change(&tip.hash).unwrap();
2301
    assert!(
2302
        c.tree_ops
2303
            .iter()
2304
            .any(|op| matches!(op, TreeOp::Move { name, .. } if name == "lib2.rs")),
2305
        "{:?}",
2306
        c.tree_ops
2307
    );
2308
    assert!(!c
2309
        .tree_ops
2310
        .iter()
2311
        .any(|op| matches!(op, TreeOp::AddNode { .. })));
2312
    // Messages carry Git trailers; the Change-Id trailer was honoured.
2313
    let log = repo.log().unwrap();
2314
    let second = log
2315
        .iter()
2316
        .find(|e| e.change.message.starts_with("second"))
2317
        .unwrap();
2318
    assert_eq!(
2319
        second.change.change_id,
2320
        ChangeId::from_hex("0123456789abcdef0123456789abcdef").unwrap()
2321
    );
2322
    assert!(second
2323
        .change
2324
        .message
2325
        .contains("Git-Author: Grace <[email protected]>"));
2326
    let resolve = log
2327
        .iter()
2328
        .find(|e| e.change.message.starts_with("resolve clash"))
2329
        .unwrap();
2330
    assert_eq!(
2331
        resolve.change.kind,
2332
        ChangeKind::Resolution,
2333
        "a conflicting Git merge becomes a resolution"
2334
    );
2335
    // Re-importing into another fresh repository gives the same ChangeIds.
2336
    let repo2 = Repo::init(&root.join("oxy2"))
2337
        .unwrap()
2338
        .with_home(root.join("home"));
2339
    repo2.import_git(&g, "main").unwrap();
2340
    // New nodes' identifiers derive from the commit (spec §23), so the
2341
    // re-import is not just the same ChangeIds but the same changes.
2342
    assert_eq!(
2343
        repo2.bookmark_heads().unwrap(),
2344
        repo.bookmark_heads().unwrap()
2345
    );
2346
    let ids: BTreeSet<ChangeId> = repo
2347
        .log()
2348
        .unwrap()
2349
        .iter()
2350
        .filter(|e| !e.is_working_copy)
2351
        .map(|e| e.change.change_id)
2352
        .collect();
2353
    let ids2: BTreeSet<ChangeId> = repo2
2354
        .log()
2355
        .unwrap()
2356
        .iter()
2357
        .filter(|e| !e.is_working_copy)
2358
        .map(|e| e.change.change_id)
2359
        .collect();
2360
    assert_eq!(ids, ids2);
2361
    // Round trip back out to Git reproduces the tip tree.
2362
    let mirror = root.join("mirror.git");
2363
    repo.git_export(&mirror).unwrap();
2364
    let out = std::process::Command::new("git")
2365
        .arg("-C")
2366
        .arg(&mirror)
2367
        .args(["show", "main:src/lib2.rs"])
2368
        .output()
2369
        .unwrap();
2370
    assert_eq!(
2371
        String::from_utf8_lossy(&out.stdout),
2372
        "pub fn a() {}\npub fn b() {}\npub fn c() {}\npub fn d() {}\n"
2373
    );
2374
    let out = std::process::Command::new("git")
2375
        .arg("-C")
2376
        .arg(&mirror)
2377
        .args(["show", "main:src/lib.rs"])
2378
        .output()
2379
        .unwrap();
2380
    assert!(
2381
        !out.status.success(),
2382
        "the old path is gone from the export"
2383
    );
2384
}
2385
2386
#[test]
2387
fn checkpoints_accelerate_loading_and_stay_correct() {
2388
    hermetic();
2389
    let dir = tempfile::tempdir().unwrap();
2390
    let root = dir.path();
2391
    let mut repo = Repo::init(root).unwrap().with_home(root.join("home"));
2392
    repo.config.set("core.checkpoint-interval", "5").unwrap();
2393
    repo.save_config().unwrap();
2394
    let repo = Repo::open(root).unwrap().with_home(root.join("home"));
2395
    let mut hashes = Vec::new();
2396
    for i in 0..12 {
2397
        write(
2398
            root,
2399
            "a.txt",
2400
            format!(
2401
                "{}\n",
2402
                (0..=i)
2403
                    .map(|k| k.to_string())
2404
                    .collect::<Vec<_>>()
2405
                    .join("\n")
2406
            )
2407
            .as_bytes(),
2408
        );
2409
        write(root, &format!("f{i}.txt"), b"x\n");
2410
        hashes.push(repo.commit(&format!("c{i}"), &[]).unwrap());
2411
    }
2412
    let (_, cp) = repo
2413
        .latest_checkpoint("main")
2414
        .unwrap()
2415
        .expect("automatic checkpoint");
2416
    assert!(cp.count >= 5 && cp.count <= 12, "{}", cp.count);
2417
    // Loading through the checkpoint equals loading everything.
2418
    let heads = repo.bookmark_heads().unwrap();
2419
    let fast = repo.load_state(&heads).unwrap();
2420
    let full = repo.load_state_full(&heads).unwrap();
2421
    assert_eq!(fast.len(), full.len());
2422
    assert_eq!(fast.heads(), full.heads());
2423
    let (a, b) = (fast.materialize(), full.materialize());
2424
    assert_eq!(
2425
        a.files.keys().collect::<Vec<_>>(),
2426
        b.files.keys().collect::<Vec<_>>()
2427
    );
2428
    for (p, f) in &a.files {
2429
        assert_eq!(f.content, b.files[p].content, "{p}");
2430
    }
2431
    assert!(repo.load_state_checkpointed(&heads).unwrap().is_some());
2432
    // A head set that does not contain the checkpoint's heads falls back.
2433
    assert!(repo
2434
        .load_state_checkpointed(&[hashes[0]])
2435
        .unwrap()
2436
        .is_none());
2437
    assert_eq!(repo.load_state(&[hashes[0]]).unwrap().len(), 1);
2438
    // Everything else keeps working on top of the checkpoint.
2439
    assert!(!repo.snapshot("status").unwrap().changed);
2440
    let h = repo.describe(&hashes[3], "c3 described").unwrap();
2441
    assert_eq!(repo.store().get_change(&h).unwrap().message, "c3 described");
2442
    let (r, n, bytes) = repo.checkpoint().unwrap();
2443
    assert!(n >= 12 && bytes > 0);
2444
    assert_eq!(repo.latest_checkpoint("main").unwrap().unwrap().0, r);
2445
    write(root, "a.txt", b"after\n");
2446
    let h_after = repo.commit("after", &[]).unwrap();
2447
    let st = repo.load_state(&repo.bookmark_heads().unwrap()).unwrap();
2448
    assert!(st.contains(&h_after));
2449
    assert!(
2450
        matches!(&st.materialize().files["a.txt"].content, FileContent::Text { bytes, .. } if bytes == b"after\n")
2451
    );
2452
    assert_eq!(repo.log().unwrap().len(), 14);
2453
    // Checkpoints survive gc.
2454
    repo.gc(true).unwrap();
2455
    assert!(repo.latest_checkpoint("main").unwrap().is_some());
2456
    assert!(repo
2457
        .load_state_checkpointed(&repo.bookmark_heads().unwrap())
2458
        .unwrap()
2459
        .is_some());
2460
}
2461
2462
#[test]
2463
fn quick_status_for_prompts() {
2464
    hermetic();
2465
    let dir = tempfile::tempdir().unwrap();
2466
    let root = dir.path();
2467
    let origin = Repo::init(&root.join("origin")).unwrap();
2468
    let url = root.join("origin").to_string_lossy().to_string();
2469
    let a = Repo::clone(&url, &root.join("a"))
2470
        .unwrap()
2471
        .with_home(root.join("home"));
2472
    let ops_before = a.op_log().unwrap().len();
2473
    let info = a.quick_status().unwrap();
2474
    assert_eq!(
2475
        (
2476
            info.bookmark.as_str(),
2477
            info.heads,
2478
            info.dirty,
2479
            info.conflicted,
2480
            info.ahead,
2481
            info.behind
2482
        ),
2483
        ("main", 0, false, false, Some(0), Some(0))
2484
    );
2485
    write(&root.join("a"), "f.txt", b"f\n");
2486
    assert!(a.quick_status().unwrap().dirty, "a new file is dirty");
2487
    assert_eq!(
2488
        a.op_log().unwrap().len(),
2489
        ops_before,
2490
        "quick_status records nothing"
2491
    );
2492
    // A snapshotted but uncommitted change is still dirty.
2493
    a.snapshot("status").unwrap();
2494
    assert!(a.quick_status().unwrap().dirty);
2495
    a.commit("f", &[]).unwrap();
2496
    let info = a.quick_status().unwrap();
2497
    assert!(!info.dirty, "clean right after a commit");
2498
    assert_eq!((info.ahead, info.behind), (Some(1), Some(0)));
2499
    assert_eq!(
2500
        info.format("%b %c%d%x%A%D"),
2501
        format!("main {}+1", info.change_id)
2502
    );
2503
    assert_eq!(info.format("[%h heads] %a/%B %%"), "[1 heads] 1/0 %");
2504
    // Touching a file without changing it is not dirty; changing content of
2505
    // the same size is.
2506
    let p = root.join("a/f.txt");
2507
    let content = fs::read(&p).unwrap();
2508
    fs::write(&p, &content).unwrap();
2509
    assert!(!a.quick_status().unwrap().dirty);
2510
    fs::write(&p, b"g\n").unwrap();
2511
    assert!(a.quick_status().unwrap().dirty);
2512
    fs::write(&p, b"f\n").unwrap();
2513
    // Push, then a second clone commits and pushes: we are behind.
2514
    assert!(a.push("origin", false).unwrap()[0].ok);
2515
    assert_eq!(a.quick_status().unwrap().ahead, Some(0));
2516
    let b = Repo::clone(&url, &root.join("b"))
2517
        .unwrap()
2518
        .with_home(root.join("home-b"));
2519
    write(&root.join("b"), "g.txt", b"g\n");
2520
    b.commit("g", &[]).unwrap();
2521
    b.push("origin", false).unwrap();
2522
    a.fetch("origin").unwrap();
2523
    let info = a.quick_status().unwrap();
2524
    assert_eq!((info.ahead, info.behind), (Some(0), Some(1)));
2525
    assert_eq!(info.format("%A%D"), "-1");
2526
    let _ = origin;
2527
}
2528
2529
#[test]
2530
fn lazy_blobs_are_fetched_on_first_read() {
2531
    hermetic();
2532
    let dir = tempfile::tempdir().unwrap();
2533
    let root = dir.path();
2534
    let origin_dir = root.join("origin");
2535
    let origin = Repo::init(&origin_dir)
2536
        .unwrap()
2537
        .with_home(root.join("home"));
2538
    let url = origin_dir.to_string_lossy().to_string();
2539
    let big: Vec<u8> = (0..200_000u32).map(|i| (i % 251) as u8).collect(); // has NUL bytes: opaque
2540
    write(&origin_dir, "big.bin", &big);
2541
    write(&origin_dir, "small.bin", &[0u8, 1, 2]);
2542
    write(&origin_dir, "t.txt", b"t\n");
2543
    let h = origin.commit("blobs", &[]).unwrap();
2544
    let big_ref = Repo::blob_ref(&big);
2545
2546
    // Fetch only (no checkout) with a filter: the big blob stays absent.
2547
    let a = Repo::init_with_id(&root.join("a"), origin.id().unwrap())
2548
        .unwrap()
2549
        .with_home(root.join("home"));
2550
    let a = {
2551
        let mut a = a;
2552
        a.config.set("remote.origin.url", &url).unwrap();
2553
        a.config.set("filter.max-blob", "100K").unwrap();
2554
        a.save_config().unwrap();
2555
        a
2556
    };
2557
    assert_eq!(a.config.max_blob, Some(100 * 1024));
2558
    a.fetch("origin").unwrap();
2559
    assert!(a.store().has(&h));
2560
    assert!(!a.store().has(&big_ref), "withheld");
2561
    assert!(
2562
        a.store().has(&Repo::blob_ref(&[0u8, 1, 2])),
2563
        "small blob came along"
2564
    );
2565
    assert_eq!(a.lazy_remote(&big_ref).as_deref(), Some("origin"));
2566
2567
    // status and commit do not need it: adopt the state, edit a text file, commit.
2568
    let (op_ref, op) = a.head_op().unwrap();
2569
    let mut view = op.view.clone();
2570
    view.bookmarks.insert(
2571
        "main".into(),
2572
        a.store().put_state(&StateObject::new(vec![h])).unwrap(),
2573
    );
2574
    a.record_op(&[op_ref], "adopt", view).unwrap();
2575
    // Checkout reads the blob lazily, which fetches it.
2576
    a.checkout(&[h], true, "checkout").unwrap();
2577
    assert!(a.store().has(&big_ref), "fetched on first read");
2578
    assert_eq!(fs::read(root.join("a/big.bin")).unwrap(), big);
2579
    assert!(a.lazy_remote(&big_ref).is_none(), "no longer registered");
2580
    write(&root.join("a"), "t.txt", b"t2\n");
2581
    a.commit("text edit", &[]).unwrap();
2582
2583
    // clone --max-blob records the filter; the checkout fetches lazily.
2584
    let b = Repo::clone_with(&url, &root.join("b"), Some(1024), &[]).unwrap();
2585
    assert_eq!(b.config.max_blob, Some(1024));
2586
    assert_eq!(fs::read(root.join("b/big.bin")).unwrap(), big);
2587
    assert_eq!(parse_size("2M").unwrap(), 2 << 20);
2588
    assert!(parse_size("lots").is_err());
2589
}
2590
2591
#[test]
2592
fn sparse_checkout_materializes_only_chosen_paths() {
2593
    hermetic();
2594
    let dir = tempfile::tempdir().unwrap();
2595
    let root = dir.path();
2596
    let origin_dir = root.join("origin");
2597
    let origin = Repo::init(&origin_dir)
2598
        .unwrap()
2599
        .with_home(root.join("home"));
2600
    write(&origin_dir, "src/main.rs", b"fn main() {}\n");
2601
    write(&origin_dir, "src/lib.rs", b"pub fn a() {}\n");
2602
    write(&origin_dir, "docs/guide.md", b"# guide\n");
2603
    let logo: Vec<u8> = (0..50_000u32).map(|i| (i % 7) as u8).collect();
2604
    write(&origin_dir, "docs/logo.png", &logo);
2605
    write(&origin_dir, "README.md", b"# top\n");
2606
    let h1 = origin.commit("tree", &[]).unwrap();
2607
    let url = origin_dir.to_string_lossy().to_string();
2608
2609
    let a = Repo::clone_with(&url, &root.join("a"), None, &["src".into()])
2610
        .unwrap()
2611
        .with_home(root.join("home"));
2612
    assert_eq!(a.config.sparse_paths, vec!["src"]);
2613
    assert_eq!(a.config.max_blob, Some(0), "sparse implies lazy blobs");
2614
    assert!(root.join("a/src/main.rs").exists());
2615
    assert!(!root.join("a/docs").exists() && !root.join("a/README.md").exists());
2616
    assert!(
2617
        !a.store().has(&Repo::blob_ref(&logo)),
2618
        "out-of-scope blob never fetched"
2619
    );
2620
    assert!(
2621
        !a.snapshot("status").unwrap().changed,
2622
        "out-of-scope files are not removals"
2623
    );
2624
    assert!(!a.quick_status().unwrap().dirty);
2625
2626
    // Edits in scope commit normally and keep the rest of the tree intact.
2627
    write(
2628
        &root.join("a"),
2629
        "src/lib.rs",
2630
        b"pub fn a() {}\npub fn b() {}\n",
2631
    );
2632
    let h2 = a.commit("edit lib", &[]).unwrap();
2633
    let st = a.load_state(&[h2]).unwrap().materialize();
2634
    assert!(
2635
        st.files.contains_key("docs/guide.md"),
2636
        "the state still has everything"
2637
    );
2638
    assert!(a.push("origin", false).unwrap()[0].ok);
2639
    // Files created outside the scope are ignored by status.
2640
    write(&root.join("a"), "docs/new.md", b"ignored\n");
2641
    assert!(a.snapshot("status").unwrap().statuses.is_empty());
2642
2643
    // Widening the filter checks out the rest; narrowing leaves stray files alone.
2644
    let mut a = a;
2645
    a.config.set("filter.paths", "src,docs").unwrap();
2646
    a.save_config().unwrap();
2647
    let r = a
2648
        .checkout(&a.bookmark_heads().unwrap(), true, "widen")
2649
        .unwrap();
2650
    assert!(r.written >= 2);
2651
    assert_eq!(
2652
        fs::read(root.join("a/docs/logo.png")).unwrap(),
2653
        logo,
2654
        "now fetched lazily"
2655
    );
2656
    assert!(!root.join("a/README.md").exists());
2657
    // Origin sees the change made under a sparse checkout with the full tree intact.
2658
    origin.pull("origin").err();
2659
    let full = origin
2660
        .load_state(&origin.bookmark_heads().unwrap())
2661
        .unwrap()
2662
        .materialize();
2663
    assert!(
2664
        matches!(&full.files["src/lib.rs"].content, FileContent::Text { bytes, .. } if bytes == b"pub fn a() {}\npub fn b() {}\n")
2665
    );
2666
    assert!(full.files.contains_key("README.md"));
2667
    let _ = h1;
2668
}
2669
2670
#[test]
2671
fn shallow_clone_and_deepen() {
2672
    hermetic();
2673
    let dir = tempfile::tempdir().unwrap();
2674
    let root = dir.path();
2675
    let origin_dir = root.join("origin");
2676
    let origin = Repo::init(&origin_dir)
2677
        .unwrap()
2678
        .with_home(root.join("home"));
2679
    let mut hashes = Vec::new();
2680
    for i in 0..8 {
2681
        write(
2682
            &origin_dir,
2683
            "a.txt",
2684
            format!(
2685
                "{}\n",
2686
                (0..=i)
2687
                    .map(|k| k.to_string())
2688
                    .collect::<Vec<_>>()
2689
                    .join("\n")
2690
            )
2691
            .as_bytes(),
2692
        );
2693
        hashes.push(origin.commit(&format!("c{i}"), &[]).unwrap());
2694
    }
2695
    let url = origin_dir.to_string_lossy().to_string();
2696
    let a = Repo::clone_shallow(&url, &root.join("a"), 3, None, &[])
2697
        .unwrap()
2698
        .with_home(root.join("home"));
2699
    assert!(a.is_shallow());
2700
    assert_eq!(
2701
        fs::read_to_string(root.join("a/a.txt")).unwrap(),
2702
        "0\n1\n2\n3\n4\n5\n6\n7\n"
2703
    );
2704
    assert!(
2705
        a.store().has(&hashes[7]) && a.store().has(&hashes[5]),
2706
        "three levels present"
2707
    );
2708
    assert!(!a.store().has(&hashes[4]), "beyond the depth is absent");
2709
    assert_eq!(a.boundary(), [hashes[4]].into_iter().collect());
2710
    assert_eq!(
2711
        a.log().unwrap().len(),
2712
        9,
2713
        "the log shows every change from the checkpoint's metadata"
2714
    );
2715
    assert!(!a.snapshot("status").unwrap().changed);
2716
    assert_eq!(a.quick_status().unwrap().heads, 1);
2717
2718
    // Work continues on top of the shallow history and pushes back.
2719
    write(&root.join("a"), "a.txt", b"0\n1\n2\n3\n4\n5\n6\n7\n8\n");
2720
    let h_new = a.commit("c8", &[]).unwrap();
2721
    assert!(a.push("origin", false).unwrap()[0].ok);
2722
    assert_eq!(origin.bookmark_heads().unwrap(), vec![h_new]);
2723
    // Fetching new work from origin into the shallow clone works too.
2724
    write(&origin_dir, "b.txt", b"b\n");
2725
    origin.pull("origin").err();
2726
    let (_, wc) = origin.working_copy().unwrap();
2727
    let _ = wc;
2728
    origin
2729
        .checkout(&origin.bookmark_heads().unwrap(), true, "co")
2730
        .unwrap();
2731
    write(&origin_dir, "b.txt", b"b\n");
2732
    let h_b = origin.commit("b", &[]).unwrap();
2733
    let pr = a.pull("origin").unwrap();
2734
    assert!(pr.changed);
2735
    assert!(a.store().has(&h_b));
2736
    assert!(root.join("a/b.txt").exists());
2737
2738
    // Deepening fetches older history until the boundary is gone.
2739
    // Every commit also depends on the change that created the file, so two
2740
    // levels below the boundary hold h4, h3, and the root.
2741
    assert!(a.deepen("origin", 2).unwrap() >= 2);
2742
    assert!(a.store().has(&hashes[3]));
2743
    assert!(a.is_shallow());
2744
    a.deepen("origin", 100).unwrap();
2745
    assert!(!a.is_shallow(), "boundary reached the root");
2746
    assert!(a.store().has(&hashes[0]));
2747
    assert_eq!(
2748
        a.load_state_full(&a.bookmark_heads().unwrap())
2749
            .unwrap()
2750
            .len(),
2751
        10
2752
    );
2753
}
2754
2755
#[test]
2756
fn tags_are_immutable_named_states_and_travel() {
2757
    hermetic();
2758
    let dir = tempfile::tempdir().unwrap();
2759
    let root = dir.path();
2760
    let origin = Repo::init(&root.join("origin")).unwrap();
2761
    let url = root.join("origin").to_string_lossy().to_string();
2762
    let mut a = Repo::clone(&url, &root.join("a"))
2763
        .unwrap()
2764
        .with_home(root.join("home-a"));
2765
    let (key_a, _) = a
2766
        .create_identity("Ada", "[email protected]", IdentityScope::User)
2767
        .unwrap();
2768
    write(&root.join("a"), "f.txt", b"1\n");
2769
    let h1 = a.commit("one", &[]).unwrap();
2770
    write(&root.join("a"), "f.txt", b"1\n2\n");
2771
    let h2 = a.commit("two", &[]).unwrap();
2772
2773
    let t = a.tag_create("v1", &[h1], "first release").unwrap();
2774
    assert_eq!(
2775
        (t.heads.clone(), t.signer.as_deref()),
2776
        (vec![h1], Some("Ada"))
2777
    );
2778
    assert!(a.tag_create("v1", &[h2], "").is_err(), "immutable");
2779
    assert!(a.tag_create("bad/name", &[h2], "").is_err());
2780
    assert_eq!(a.tag_heads("v1").unwrap(), Some(vec![h1]));
2781
    assert_eq!(a.resolve_heads("v1").unwrap(), vec![h1]);
2782
    assert_eq!(a.resolve_heads("main").unwrap(), vec![h2]);
2783
    let (_, sa) = a.tag_attest("v1").unwrap().unwrap();
2784
    assert_eq!(sa.sigs[0].key, key_a);
2785
    // Checkout by tag.
2786
    a.checkout(&a.resolve_heads("v1").unwrap(), false, "co")
2787
        .unwrap();
2788
    assert_eq!(fs::read(root.join("a/f.txt")).unwrap(), b"1\n");
2789
    a.checkout(&a.bookmark_heads().unwrap(), false, "co")
2790
        .unwrap();
2791
2792
    // Push carries the tag; a second attestation for the name is refused.
2793
    let r = a.push("origin", false).unwrap();
2794
    assert!(r.iter().any(|x| x.name == "tags/v1" && x.ok), "{r:?}");
2795
    assert_eq!(origin.tag_heads("v1").unwrap(), Some(vec![h1]));
2796
    let mut forged = a
2797
        .tag_refs()
2798
        .unwrap()
2799
        .into_iter()
2800
        .find(|t| t.name == "v1")
2801
        .unwrap();
2802
    forged.state = origin
2803
        .store()
2804
        .put_state(&StateObject::new(vec![h2]))
2805
        .unwrap();
2806
    forged.heads = vec![h2];
2807
    forged.attestation = None;
2808
    let r = origin
2809
        .receive_push(Bundle::default(), vec![], None, vec![forged])
2810
        .unwrap();
2811
    assert!(!r[0].ok && r[0].reason.contains("immutable"), "{r:?}");
2812
2813
    // A clone gets the tag; a later tag arrives on fetch.
2814
    let b = Repo::clone(&url, &root.join("b"))
2815
        .unwrap()
2816
        .with_home(root.join("home-b"));
2817
    assert_eq!(b.tag_heads("v1").unwrap(), Some(vec![h1]));
2818
    assert!(b.tags().unwrap()[0].signer.as_deref() == Some("Ada"));
2819
    a.tag_create("v2", &[h2], "second").unwrap();
2820
    a.push("origin", false).unwrap();
2821
    let rep = b.fetch("origin").unwrap();
2822
    assert_eq!(rep.new_tags, 1);
2823
    assert_eq!(b.tag_heads("v2").unwrap(), Some(vec![h2]));
2824
2825
    // Under a policy, an unattested tag is refused and an attested one by the root passes.
2826
    a.policy_init().unwrap();
2827
    a.push("origin", false).unwrap();
2828
    let unattested = crate::protocol::TagRef {
2829
        name: "v3".into(),
2830
        state: origin
2831
            .store()
2832
            .put_state(&StateObject::new(vec![h2]))
2833
            .unwrap(),
2834
        heads: vec![h2],
2835
        attestation: None,
2836
    };
2837
    let r = origin
2838
        .receive_push(Bundle::default(), vec![], None, vec![unattested])
2839
        .unwrap();
2840
    assert!(!r[0].ok && r[0].reason.contains("attestation"), "{r:?}");
2841
    a.tag_create("v3", &[h2], "").unwrap();
2842
    let r = a.push("origin", false).unwrap();
2843
    assert!(r.iter().any(|x| x.name == "tags/v3" && x.ok), "{r:?}");
2844
    assert!(a.gc(true).is_ok());
2845
    assert_eq!(a.tags().unwrap().len(), 3, "tags survive gc");
2846
}
2847
2848
#[test]
2849
fn multiple_workspaces_share_a_repository() {
2850
    hermetic();
2851
    let dir = tempfile::tempdir().unwrap();
2852
    let root = dir.path();
2853
    let main_dir = root.join("main");
2854
    let repo = Repo::init(&main_dir).unwrap().with_home(root.join("home"));
2855
    write(&main_dir, "a.txt", b"a\n");
2856
    let h1 = repo.commit("a", &[]).unwrap();
2857
    assert_eq!(repo.workspaces().unwrap().len(), 1);
2858
2859
    // A second workspace elsewhere, checked out on the bookmark.
2860
    let ws_dir = root.join("ws2");
2861
    let ws = repo.workspace_add(&ws_dir, None).unwrap();
2862
    assert!(ws_dir.join(".oxy").is_file());
2863
    assert_eq!(fs::read(ws_dir.join("a.txt")).unwrap(), b"a\n");
2864
    assert_ne!(ws.workspace(), repo.workspace());
2865
    let list = repo.workspaces().unwrap();
2866
    assert_eq!(list.len(), 2);
2867
    assert!(list
2868
        .iter()
2869
        .any(|w| w.id == ws.workspace() && w.path == ws_dir.canonicalize().unwrap() && !w.current));
2870
    assert!(!ws.snapshot("status").unwrap().changed);
2871
2872
    // Work in the second workspace: its own working copy, shared bookmark.
2873
    write(&ws_dir, "b.txt", b"b\n");
2874
    let s = ws.snapshot("status").unwrap();
2875
    assert_eq!(s.statuses.len(), 1);
2876
    assert!(
2877
        !repo.snapshot("status").unwrap().changed,
2878
        "the first workspace is untouched"
2879
    );
2880
    let h2 = ws.commit("b from ws2", &[]).unwrap();
2881
    let mut heads = repo.bookmark_heads().unwrap();
2882
    heads.sort();
2883
    let mut want = vec![h1, h2];
2884
    want.sort();
2885
    assert_eq!(heads, want, "both workspaces see the bookmark move");
2886
    assert!(!main_dir.join("b.txt").exists());
2887
    repo.checkout(&repo.bookmark_heads().unwrap(), false, "co")
2888
        .unwrap();
2889
    assert!(main_dir.join("b.txt").exists());
2890
2891
    // Reopening from inside the second workspace finds the shared repository.
2892
    let reopened = Repo::open(&ws_dir).unwrap();
2893
    assert_eq!(reopened.workspace(), ws.workspace());
2894
    assert_eq!(reopened.id().unwrap(), repo.id().unwrap());
2895
    assert_eq!(reopened.quick_status().unwrap().heads, 2);
2896
2897
    // Workspaces cannot nest; forget drops one from the view but keeps files.
2898
    assert!(repo.workspace_add(&main_dir.join("inner"), None).is_err());
2899
    assert!(repo.workspace_forget(&repo.workspace()).is_err());
2900
    repo.workspace_forget(&ws.workspace()).unwrap();
2901
    assert_eq!(repo.workspaces().unwrap().len(), 1);
2902
    assert!(ws_dir.join("b.txt").exists());
2903
    assert!(
2904
        ws.snapshot("status").is_err(),
2905
        "a forgotten workspace is no longer in the view"
2906
    );
2907
2908
    // The working-copy lock: re-entrant in a thread; a lock whose process
2909
    // is gone is taken over, and a live process's is not, however old.
2910
    let lock = repo.lock_snapshot().unwrap();
2911
    let again = repo.lock_working_copy().unwrap();
2912
    drop(again);
2913
    drop(lock);
2914
    let lock_path = main_dir
2915
        .join(".oxy/workspaces")
2916
        .join(repo.workspace().to_hex())
2917
        .join("lock");
2918
    let old = std::time::SystemTime::now() - std::time::Duration::from_secs(120);
2919
    let age = |p: &Path| fs::File::open(p).unwrap().set_modified(old).unwrap();
2920
    fs::write(&lock_path, std::process::id().to_string()).unwrap();
2921
    age(&lock_path);
2922
    assert!(
2923
        !super::workspace::lock_is_stale(&lock_path),
2924
        "a live process keeps its lock"
2925
    );
2926
    fs::write(&lock_path, "4294967295").unwrap();
2927
    age(&lock_path);
2928
    assert!(repo.lock_snapshot().is_ok(), "stale lock taken over");
2929
}
2930
2931
#[test]
2932
fn attributes_binary_eol_nocompress_lockable() {
2933
    hermetic();
2934
    let dir = tempfile::tempdir().unwrap();
2935
    let root = dir.path();
2936
    let repo = Repo::init(root).unwrap().with_home(root.join("home"));
2937
    write(
2938
        root,
2939
        ".oxyattributes",
2940
        b"*.dat binary nocompress\n*.txt eol=crlf\nassets/** lockable\n",
2941
    );
2942
    write(root, "plain.dat", b"no nul bytes here\n");
2943
    write(root, "notes.txt", b"one\r\ntwo\r\n");
2944
    write(root, "assets/model.bin", b"\0model");
2945
    let h = repo.commit("attrs", &[]).unwrap();
2946
    let snap = repo.load_state(&[h]).unwrap().materialize();
2947
    assert!(
2948
        snap.files["plain.dat"].mode.opaque,
2949
        "binary attribute forces opaque without NUL bytes"
2950
    );
2951
    assert!(
2952
        matches!(&snap.files["notes.txt"].content, FileContent::Text { bytes, .. } if bytes == b"one\ntwo\n"),
2953
        "stored with LF"
2954
    );
2955
    assert!(
2956
        !repo.snapshot("status").unwrap().changed,
2957
        "CRLF on disk equals LF in the state"
2958
    );
2959
    // nocompress chunks pack raw.
2960
    let r = repo.gc(true).unwrap();
2961
    assert!(r.packed.objects > 0);
2962
    // Checkout writes CRLF for eol=crlf and makes lockable files read-only.
2963
    fs::remove_file(root.join("notes.txt")).unwrap();
2964
    repo.checkout(&[h], true, "co").unwrap();
2965
    assert_eq!(fs::read(root.join("notes.txt")).unwrap(), b"one\r\ntwo\r\n");
2966
    assert!(fs::metadata(root.join("assets/model.bin"))
2967
        .unwrap()
2968
        .permissions()
2969
        .readonly());
2970
    assert!(repo.lock_path("plain.dat").is_err(), "not lockable");
2971
    repo.lock_path("assets/model.bin").unwrap();
2972
    assert!(!fs::metadata(root.join("assets/model.bin"))
2973
        .unwrap()
2974
        .permissions()
2975
        .readonly());
2976
    assert!(repo.is_locked("assets/model.bin"));
2977
    write(root, "assets/model.bin", b"\0model2");
2978
    repo.commit("edit model", &[]).unwrap();
2979
    repo.unlock_path("assets/model.bin").unwrap();
2980
    assert!(fs::metadata(root.join("assets/model.bin"))
2981
        .unwrap()
2982
        .permissions()
2983
        .readonly());
2984
    // A later checkout can still overwrite a read-only lockable file.
2985
    repo.checkout(&[h], true, "co").unwrap();
2986
    assert_eq!(fs::read(root.join("assets/model.bin")).unwrap(), b"\0model");
2987
}
2988
2989
#[cfg(unix)]
2990
#[test]
2991
fn hooks_can_veto_observe_and_add_dependencies() {
2992
    use std::os::unix::fs::PermissionsExt;
2993
    hermetic();
2994
    let dir = tempfile::tempdir().unwrap();
2995
    let root = dir.path();
2996
    let mut repo = Repo::init(root).unwrap().with_home(root.join("home"));
2997
    let hooks = root.join(".oxy/hooks");
2998
    fs::create_dir_all(&hooks).unwrap();
2999
    let hook = |name: &str, body: &str| {
3000
        let p = hooks.join(name);
3001
        fs::write(&p, format!("#!/bin/sh\n{body}\n")).unwrap();
3002
        fs::set_permissions(&p, fs::Permissions::from_mode(0o755)).unwrap();
3003
    };
3004
    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");
3005
    hook("post-commit", "cat > \"$OXY_ROOT/.last-post-commit\"");
3006
    hook("post-checkout", "cat > \"$OXY_ROOT/.last-post-checkout\"");
3007
    hook("pre-push", "echo pushing blocked >&2; exit 3");
3008
    write(root, ".oxyignore", b".last-*\n");
3009
    write(root, "a.txt", b"a\n");
3010
    let err = repo.commit("WIP: nope", &[]).unwrap_err().to_string();
3011
    assert!(err.contains("pre-commit refused: no WIP commits"), "{err}");
3012
    let h1 = repo.commit("first", &[]).unwrap();
3013
    let pre = fs::read_to_string(root.join(".last-pre-commit")).unwrap();
3014
    assert!(
3015
        pre.contains("\"event\":\"pre-commit\"")
3016
            && pre.contains("\"path\":\"a.txt\"")
3017
            && pre.contains("\"message\":\"first\""),
3018
        "{pre}"
3019
    );
3020
    let post = fs::read_to_string(root.join(".last-post-commit")).unwrap();
3021
    assert!(post.contains(&h1.to_hex()), "{post}");
3022
    repo.checkout(&[h1], false, "co").unwrap();
3023
    assert!(fs::read_to_string(root.join(".last-post-checkout"))
3024
        .unwrap()
3025
        .contains("post-checkout"));
3026
    repo.config.set("remote.origin.url", "/nowhere").unwrap();
3027
    repo.save_config().unwrap();
3028
    let err = repo.push("origin", false).unwrap_err().to_string();
3029
    assert!(err.contains("pre-push refused: pushing blocked"), "{err}");
3030
3031
    // semantic-deps: only when enabled; adds an explicit dependency.
3032
    write(root, "b.txt", b"b\n");
3033
    hook(
3034
        "semantic-deps",
3035
        &format!(
3036
            "cat > \"$OXY_ROOT/.last-semantic\"; echo '{{\"deps\": [\"{}\"]}}'",
3037
            h1.to_hex()
3038
        ),
3039
    );
3040
    let h2 = repo.commit("b without hook", &[]).unwrap();
3041
    assert!(
3042
        repo.store().get_change(&h2).unwrap().deps.is_empty(),
3043
        "hook disabled by default"
3044
    );
3045
    repo.config.set("hooks.semantic-deps", "true").unwrap();
3046
    repo.save_config().unwrap();
3047
    write(root, "c.txt", b"c\n");
3048
    let h3 = repo.commit("c with hook", &[]).unwrap();
3049
    assert_eq!(repo.store().get_change(&h3).unwrap().deps, vec![h1]);
3050
    let sem = fs::read_to_string(root.join(".last-semantic")).unwrap();
3051
    assert!(
3052
        sem.contains("\"touched_paths\":[\"c.txt\"]") && sem.contains("candidate_deps"),
3053
        "{sem}"
3054
    );
3055
    assert_eq!(json_str("a\"b\\c\n"), "\"a\\\"b\\\\c\\n\"");
3056
}
3057
3058
#[test]
3059
fn amend_into_older_change_and_split() {
3060
    hermetic();
3061
    let dir = tempfile::tempdir().unwrap();
3062
    let root = dir.path();
3063
    let mut repo = Repo::init(root).unwrap().with_home(root.join("home"));
3064
    repo.create_identity("Ada", "a@b", IdentityScope::User)
3065
        .unwrap();
3066
    repo.set_user_config("core.sign", "change").unwrap();
3067
    write(root, "a.txt", b"one\ntwo\n");
3068
    let h0 = repo.commit("base", &[]).unwrap();
3069
    write(root, "a.txt", b"one\nTWO\n");
3070
    let h1 = repo.commit("edit two", &[]).unwrap();
3071
    write(root, "a.txt", b"one\nTWO\nthree\n");
3072
    let h2 = repo.commit("add three", &[]).unwrap();
3073
    let id1 = repo.store().get_change(&h1).unwrap().change_id;
3074
3075
    // Fixing the line h1 introduced folds into h1; h2 is rewritten on top.
3076
    write(root, "a.txt", b"one\nTWO!\nthree\n");
3077
    let h1b = repo.amend_into(&h1, None).unwrap();
3078
    assert_ne!(h1b, h1);
3079
    let c1b = repo.store().get_change(&h1b).unwrap();
3080
    assert_eq!(c1b.change_id, id1);
3081
    assert_eq!(c1b.deps, vec![h0]);
3082
    assert!(matches!(
3083
        repo.verify_change(&h1b).unwrap(),
3084
        SignatureStatus::Valid { .. }
3085
    ));
3086
    let heads = repo.bookmark_heads().unwrap();
3087
    assert_eq!(heads.len(), 1);
3088
    let top = repo.store().get_change(&heads[0]).unwrap();
3089
    assert_eq!(top.message, "add three");
3090
    assert_eq!(
3091
        top.deps.iter().copied().collect::<BTreeSet<_>>(),
3092
        [h0, h1b].into_iter().collect(),
3093
        "depends on the file's creator and the rewritten line"
3094
    );
3095
    let snap = repo.load_state(&heads).unwrap().materialize();
3096
    assert!(
3097
        matches!(&snap.files["a.txt"].content, FileContent::Text { bytes, .. } if bytes == b"one\nTWO!\nthree\n")
3098
    );
3099
    assert!(
3100
        !repo.snapshot("status").unwrap().changed,
3101
        "the working copy is clean after folding"
3102
    );
3103
    // Only h1b's own state shows the fix without "three".
3104
    let only = repo.load_state(&[h1b]).unwrap().materialize();
3105
    assert!(
3106
        matches!(&only.files["a.txt"].content, FileContent::Text { bytes, .. } if bytes == b"one\nTWO!\n")
3107
    );
3108
    assert_eq!(repo.log().unwrap().len(), 4);
3109
3110
    // An edit to a line introduced by h2 cannot fold into h1.
3111
    write(root, "a.txt", b"one\nTWO!\nthree!\n");
3112
    let err = repo.amend_into(&h1b, None).unwrap_err().to_string();
3113
    assert!(err.contains("introduced after"), "{err}");
3114
    assert!(
3115
        repo.snapshot("status").unwrap().statuses.len() == 1,
3116
        "nothing was changed by the refusal"
3117
    );
3118
    write(root, "a.txt", b"one\nTWO!\nthree\n");
3119
3120
    // Split the head that touches two files.
3121
    write(root, "b.txt", b"b\n");
3122
    write(root, "c.txt", b"c\n");
3123
    let h3 = repo.commit("b and c", &[]).unwrap();
3124
    let id3 = repo.store().get_change(&h3).unwrap().change_id;
3125
    let (p1, p2) = repo.split(&h3, &["b.txt".into()]).unwrap();
3126
    let c_1 = repo.store().get_change(&p1).unwrap();
3127
    let c_2 = repo.store().get_change(&p2).unwrap();
3128
    assert!(c_1.message.contains("part 1: b.txt"));
3129
    assert_eq!(c_2.change_id, id3);
3130
    let heads: BTreeSet<_> = repo.bookmark_heads().unwrap().into_iter().collect();
3131
    assert!(
3132
        heads.contains(&p1) && heads.contains(&p2),
3133
        "independent parts are both heads"
3134
    );
3135
    let snap = repo
3136
        .load_state(&repo.bookmark_heads().unwrap())
3137
        .unwrap()
3138
        .materialize();
3139
    assert!(snap.files.contains_key("b.txt") && snap.files.contains_key("c.txt"));
3140
    let only1 = repo.load_state(&[p1]).unwrap().materialize();
3141
    assert!(only1.files.contains_key("b.txt") && !only1.files.contains_key("c.txt"));
3142
    assert!(!repo.snapshot("status").unwrap().changed);
3143
    assert!(repo.split(&p2, &["nope.txt".into()]).is_err());
3144
    let _ = h2;
3145
}
3146
3147
#[test]
3148
fn identity_lifecycle() {
3149
    hermetic();
3150
    let dir = tempfile::tempdir().unwrap();
3151
    let root = dir.path();
3152
    let origin = Repo::init(&root.join("origin")).unwrap();
3153
    let url = root.join("origin").to_string_lossy().to_string();
3154
    let mut a = Repo::clone(&url, &root.join("a"))
3155
        .unwrap()
3156
        .with_home(root.join("home-a"));
3157
    a.set_user_config("core.sign", "change").unwrap();
3158
    let (key_a, _) = a
3159
        .create_identity("Ada", "[email protected]", IdentityScope::User)
3160
        .unwrap();
3161
    write(&root.join("a"), "a.txt", b"a\n");
3162
    let h1 = a.commit("one", &[]).unwrap();
3163
    assert!(a.policy_init().unwrap().applied);
3164
    assert!(a.push("origin", false).unwrap().iter().all(|r| r.ok));
3165
3166
    // Expiry: an identity that had expired when the change was made does not authenticate it.
3167
    let mut e = Repo::init(&root.join("e"))
3168
        .unwrap()
3169
        .with_home(root.join("home-e"));
3170
    e.set_user_config("core.sign", "change").unwrap();
3171
    e.create_identity_with(
3172
        "Eve",
3173
        "[email protected]",
3174
        IdentityScope::User,
3175
        Some(Hlc::now().wall_ms - 1),
3176
    )
3177
    .unwrap();
3178
    write(&root.join("e"), "e.txt", b"e\n");
3179
    let he = e.commit("late", &[]).unwrap();
3180
    assert!(
3181
        matches!(e.verify_change(&he).unwrap(), SignatureStatus::Invalid(m) if m.contains("expired"))
3182
    );
3183
    // Renewal re-issues the identity (same keys, new KeyId) with a later expiry.
3184
    let r = e
3185
        .renew_identity(Some(Hlc::now().wall_ms + 86_400_000))
3186
        .unwrap();
3187
    assert_eq!(e.identity(&r.new).unwrap().previous, Some(r.old));
3188
    write(&root.join("e"), "e.txt", b"e2\n");
3189
    let he2 = e.commit("in time", &[]).unwrap();
3190
    assert!(
3191
        matches!(e.verify_change(&he2).unwrap(), SignatureStatus::Valid { key, .. } if key == r.new)
3192
    );
3193
3194
    // Rotation: a fresh key; the old change still verifies; the policy follows.
3195
    let r = a.rotate_identity().unwrap();
3196
    assert_eq!(r.old, key_a);
3197
    assert_eq!(a.config.author_key, Some(r.new));
3198
    assert_eq!(a.identity(&r.new).unwrap().previous, Some(key_a));
3199
    assert!(r.policy.as_ref().unwrap().applied);
3200
    let (_, sp) = a.current_policy().unwrap().unwrap();
3201
    assert_eq!(
3202
        (sp.policy.serial, sp.policy.roots.clone()),
3203
        (2, vec![r.new])
3204
    );
3205
    assert!(
3206
        !sp.policy.revoked.contains(&key_a) && sp.policy.authorizes(&r.new, "main"),
3207
        "superseded, not revoked"
3208
    );
3209
    assert!(sp.policy.succeeds(&r.new, &key_a) && !sp.policy.succeeds(&key_a, &r.new));
3210
    assert!(
3211
        matches!(a.verify_change(&h1).unwrap(), SignatureStatus::Valid { key, revoked: false, .. } if key == key_a)
3212
    );
3213
    write(&root.join("a"), "a.txt", b"a2\n");
3214
    let h2 = a.commit("two", &[]).unwrap();
3215
    assert!(
3216
        matches!(a.verify_change(&h2).unwrap(), SignatureStatus::Valid { key, revoked: false, .. } if key == r.new)
3217
    );
3218
    // Origin accepts the rotated policy (signed by the old root) and the new key's change.
3219
    let res = a.push("origin", false).unwrap();
3220
    assert!(res.iter().all(|x| x.ok), "{res:?}");
3221
    assert_eq!(origin.current_policy().unwrap().unwrap().1.policy.serial, 2);
3222
    let key_a = r.new;
3223
3224
    // Delegation: Bob may sign on Ada's behalf. Delegates live in the
3225
    // identity object, so Ada's KeyId changes while her keys stay the same.
3226
    let mut b = Repo::clone(&url, &root.join("b"))
3227
        .unwrap()
3228
        .with_home(root.join("home-b"));
3229
    let (key_b, id_b) = b
3230
        .create_identity("Bob", "[email protected]", IdentityScope::User)
3231
        .unwrap();
3232
    let r = a.delegate_add(id_b.clone(), Scope::ALL, None).unwrap();
3233
    assert_eq!(r.old, key_a);
3234
    let key_a2 = r.new;
3235
    assert_eq!(
3236
        a.identity(&key_a2).unwrap().delegates,
3237
        vec![Delegate::full(key_b)]
3238
    );
3239
    assert_eq!(
3240
        a.identity(&key_a2).unwrap().ed25519_pk,
3241
        a.identity(&key_a).unwrap().ed25519_pk
3242
    );
3243
    assert!(
3244
        a.delegate_add(id_b.clone(), Scope::ALL, None).is_err(),
3245
        "already a delegate"
3246
    );
3247
    assert!(a.push("origin", false).unwrap().iter().all(|x| x.ok));
3248
    write(&root.join("a"), "a.txt", b"a3\n");
3249
    let h3 = a.commit("three", &[]).unwrap();
3250
    assert!(
3251
        matches!(a.verify_change(&h3).unwrap(), SignatureStatus::Valid { key, .. } if key == key_a2),
3252
        "the same secret signs under the new KeyId"
3253
    );
3254
    // A change authored by Ada but signed only by Bob verifies through the delegation.
3255
    a.set_user_config("core.sign", "seal").unwrap();
3256
    write(&root.join("a"), "a.txt", b"a4\n");
3257
    let h4 = a.commit("four", &[]).unwrap();
3258
    assert_eq!(a.verify_change(&h4).unwrap(), SignatureStatus::Unsigned);
3259
    let (_, sk_b) = b.secret_key().unwrap().unwrap();
3260
    a.store()
3261
        .put_signature(&h4, &sk_b.sign(Domain::Change, &key_b, &h4))
3262
        .unwrap();
3263
    assert!(
3264
        matches!(a.verify_change(&h4).unwrap(), SignatureStatus::Valid { key, .. } if key == key_b)
3265
    );
3266
    a.set_user_config("core.sign", "change").unwrap();
3267
    // Withdrawing the delegation re-issues the identity again.
3268
    let r = a.delegate_remove(&key_b).unwrap();
3269
    assert!(a.identity(&r.new).unwrap().delegates.is_empty());
3270
    assert!(a.delegate_remove(&key_b).is_err());
3271
    let key_a3 = r.new;
3272
    let res = a.push("origin", false).unwrap();
3273
    assert!(res.iter().all(|x| x.ok), "{res:?}");
3274
3275
    // Multi-signer policy: Bob becomes a root and the threshold rises to 2,
3276
    // both applied under the old threshold of 1. A grant then needs Bob too.
3277
    assert!(a.policy_root_add(id_b.clone()).unwrap().applied);
3278
    assert!(a.policy_root_add(id_b.clone()).is_err());
3279
    assert!(a.policy_set_threshold(3).is_err());
3280
    assert!(a.policy_set_threshold(2).unwrap().applied);
3281
    assert!(a.push("origin", false).unwrap().iter().all(|x| x.ok));
3282
    b.pull("origin").unwrap();
3283
    assert_eq!(
3284
        b.current_policy().unwrap().unwrap().1.policy.root_threshold,
3285
        2
3286
    );
3287
    let mut c = Repo::init(&root.join("c"))
3288
        .unwrap()
3289
        .with_home(root.join("home-c"));
3290
    let (key_c, id_c) = c
3291
        .create_identity("Cy", "[email protected]", IdentityScope::User)
3292
        .unwrap();
3293
    let serial_before = a.current_policy().unwrap().unwrap().1.policy.serial;
3294
    let proposal = a.policy_grant(id_c, None).unwrap();
3295
    assert!(!proposal.applied && proposal.sigs.len() == 1);
3296
    assert_eq!(proposal.policy.serial, serial_before + 1);
3297
    assert_eq!(
3298
        a.current_policy().unwrap().unwrap().1.policy.serial,
3299
        serial_before,
3300
        "a proposal changes nothing yet"
3301
    );
3302
    // Bob signs the proposal, handed over as a file, and it applies for him.
3303
    let bytes = proposal.signed().encode();
3304
    let signed = b
3305
        .policy_sign(SignedPolicy::decode(&bytes).unwrap())
3306
        .unwrap();
3307
    assert!(signed.applied && signed.sigs.len() == 2);
3308
    assert!(b
3309
        .current_policy()
3310
        .unwrap()
3311
        .unwrap()
3312
        .1
3313
        .policy
3314
        .authorizes(&key_c, "main"));
3315
    assert!(
3316
        b.policy_sign(signed.signed()).is_err(),
3317
        "a stale proposal is refused"
3318
    );
3319
    // Bob publishes it and Ada picks it up.
3320
    assert!(b
3321
        .push("origin", false)
3322
        .unwrap()
3323
        .iter()
3324
        .any(|x| x.name == "policy" && x.ok));
3325
    a.pull("origin").unwrap();
3326
    assert_eq!(
3327
        a.current_policy().unwrap().unwrap().1.policy.serial,
3328
        serial_before + 1
3329
    );
3330
    // A root cannot revoke itself; revoking Cy needs both roots but is recorded locally at once.
3331
    assert!(a.policy_revoke(&key_a3).is_err());
3332
    let u = a
3333
        .revoke_identity(&key_c, "left the project")
3334
        .unwrap()
3335
        .unwrap();
3336
    assert!(!u.applied);
3337
    assert!(a.is_revoked(&key_c).unwrap());
3338
    assert!(!b.is_revoked(&key_c).unwrap());
3339
    let u = b.policy_sign(u.signed()).unwrap();
3340
    assert!(u.applied && u.policy.is_revoked(&key_c));
3341
    assert!(b.is_revoked(&key_c).unwrap());
3342
    // Bob can revoke Ada's root key, leaving himself as the only root (threshold 2 would be unmeetable).
3343
    assert!(
3344
        b.policy_revoke(&key_a3).is_err(),
3345
        "would leave one root for a threshold of 2"
3346
    );
3347
    // Revoking one's own key without a policy root works locally: a plain marker plus attestation.
3348
    let key_c_own = c.config.author_key.unwrap();
3349
    assert!(c
3350
        .revoke_identity(&key_c_own, "lost laptop")
3351
        .unwrap()
3352
        .is_none());
3353
    assert!(c.is_revoked(&key_c_own).unwrap());
3354
    assert_eq!(key_c_own, key_c);
3355
}
3356
3357
#[test]
3358
fn renames_are_detected_and_tracked_as_moves() {
3359
    hermetic();
3360
    let dir = tempfile::tempdir().unwrap();
3361
    let root = dir.path();
3362
    let repo = Repo::init(root).unwrap().with_home(root.join("home"));
3363
    write(
3364
        root,
3365
        "src/old.rs",
3366
        b"fn a() {}\nfn b() {}\nfn c() {}\nfn d() {}\n",
3367
    );
3368
    write(root, "img.bin", b"\x89PNG\0\0\x01\x02");
3369
    write(root, "tiny.txt", b"x\n");
3370
    let h1 = repo.commit("base", &[]).unwrap();
3371
    let node_old = repo.load_state(&[h1]).unwrap().materialize().files["src/old.rs"].node;
3372
    let node_img = repo.load_state(&[h1]).unwrap().materialize().files["img.bin"].node;
3373
3374
    // Rename with a small edit, a binary moved unchanged, and a rewrite
3375
    // that shares nothing with the removed file.
3376
    fs::remove_file(root.join("src/old.rs")).unwrap();
3377
    write(
3378
        root,
3379
        "lib/new.rs",
3380
        b"fn a() {}\nfn b() {}\nfn c() {}\nfn e() {}\n",
3381
    );
3382
    fs::remove_file(root.join("img.bin")).unwrap();
3383
    write(root, "assets/img.bin", b"\x89PNG\0\0\x01\x02");
3384
    fs::remove_file(root.join("tiny.txt")).unwrap();
3385
    write(root, "other.txt", b"completely different\n");
3386
    let snap = repo.snapshot("status").unwrap();
3387
    let statuses: Vec<(&str, ChangeStatus)> = snap
3388
        .statuses
3389
        .iter()
3390
        .map(|s| (s.path.as_str(), s.status))
3391
        .collect();
3392
    assert_eq!(
3393
        statuses,
3394
        vec![
3395
            ("assets/img.bin", ChangeStatus::Renamed),
3396
            ("lib/new.rs", ChangeStatus::Renamed),
3397
            ("other.txt", ChangeStatus::Added),
3398
            ("src", ChangeStatus::Removed),
3399
            ("tiny.txt", ChangeStatus::Removed)
3400
        ]
3401
    );
3402
    let h2 = repo.commit("move things", &[]).unwrap();
3403
    let c = repo.store().get_change(&h2).unwrap();
3404
    let moves: Vec<_> = c
3405
        .tree_ops
3406
        .iter()
3407
        .filter(|op| matches!(op, TreeOp::Move { .. }))
3408
        .collect();
3409
    assert_eq!(moves.len(), 2, "{:?}", c.tree_ops);
3410
    assert!(c.tree_ops.iter().any(
3411
        |op| matches!(op, TreeOp::Move { node, name, .. } if *node == node_old && name == "new.rs")
3412
    ));
3413
    assert!(c.tree_ops.iter().any(
3414
        |op| matches!(op, TreeOp::Move { node, name, .. } if *node == node_img && name == "img.bin")
3415
    ));
3416
    let snap = repo.load_state(&[h2]).unwrap().materialize();
3417
    assert_eq!(
3418
        snap.files["lib/new.rs"].node, node_old,
3419
        "the node survives the rename"
3420
    );
3421
    assert!(
3422
        matches!(&snap.files["lib/new.rs"].content, FileContent::Text { bytes, .. } if bytes == b"fn a() {}\nfn b() {}\nfn c() {}\nfn e() {}\n")
3423
    );
3424
    assert!(!snap.files.contains_key("src/old.rs") && !snap.files.contains_key("src"));
3425
    assert!(render_change(
3426
        &c,
3427
        &repo.load_state(&[h1]).unwrap(),
3428
        &repo.load_state(&[h1]).unwrap().materialize()
3429
    )
3430
    .contains("R "));
3431
    // A fresh checkout reproduces the tree.
3432
    let other = tempfile::tempdir().unwrap();
3433
    let clone = Repo::clone(&root.to_string_lossy(), other.path()).unwrap();
3434
    assert_eq!(
3435
        fs::read(other.path().join("lib/new.rs")).unwrap(),
3436
        b"fn a() {}\nfn b() {}\nfn c() {}\nfn e() {}\n"
3437
    );
3438
    assert!(!other.path().join("src").exists());
3439
    assert!(!clone.snapshot("status").unwrap().changed);
3440
    // Similarity is line based, byte weighted.
3441
    assert_eq!(similarity(b"a\nb\n", b"a\nb\n"), 100);
3442
    assert_eq!(similarity(b"a\nb\nc\nd\n", b"a\nb\nx\ny\n"), 50);
3443
    assert_eq!(similarity(b"hello\n", b"world\n"), 0);
3444
    assert_eq!(similarity(b"", b"x\n"), 0);
3445
}
3446
3447
#[test]
3448
fn git_fetch_and_push_round_trip() {
3449
    hermetic();
3450
    if std::process::Command::new("git")
3451
        .arg("--version")
3452
        .output()
3453
        .is_err()
3454
    {
3455
        eprintln!("git not installed; skipping");
3456
        return;
3457
    }
3458
    let dir = tempfile::tempdir().unwrap();
3459
    let root = dir.path();
3460
    let git_in = |d: &Path, args: &[&str]| -> String {
3461
        let out = std::process::Command::new("git")
3462
            .arg("-C")
3463
            .arg(d)
3464
            .args([
3465
                "-c",
3466
                "user.name=Grace",
3467
                "-c",
3468
                "[email protected]",
3469
                "-c",
3470
                "commit.gpgsign=false",
3471
            ])
3472
            .args(args)
3473
            .output()
3474
            .unwrap();
3475
        assert!(
3476
            out.status.success(),
3477
            "git {args:?}: {}",
3478
            String::from_utf8_lossy(&out.stderr)
3479
        );
3480
        String::from_utf8_lossy(&out.stdout).trim().to_string()
3481
    };
3482
    // A bare "remote" and a work tree that pushes to it.
3483
    let remote = root.join("remote.git");
3484
    fs::create_dir_all(&remote).unwrap();
3485
    git_in(&remote, &["init", "-q", "--bare", "-b", "main"]);
3486
    let work = root.join("work");
3487
    git_in(
3488
        root,
3489
        &[
3490
            "clone",
3491
            "-q",
3492
            remote.to_str().unwrap(),
3493
            work.to_str().unwrap(),
3494
        ],
3495
    );
3496
    git_in(&work, &["checkout", "-q", "-b", "main"]);
3497
    write(&work, "README.md", b"# Project\n");
3498
    write(&work, "src/lib.rs", b"pub fn a() {}\n");
3499
    git_in(&work, &["add", "."]);
3500
    git_in(&work, &["commit", "-q", "-m", "initial"]);
3501
    write(&work, "src/lib.rs", b"pub fn a() {}\npub fn b() {}\n");
3502
    git_in(&work, &["commit", "-q", "-am", "second"]);
3503
    git_in(&work, &["push", "-q", "origin", "main"]);
3504
    let tip1 = git_in(&work, &["rev-parse", "HEAD"]);
3505
3506
    // Fetch into a fresh oxy repository.
3507
    let o = root.join("oxy");
3508
    let mut repo = Repo::init(&o).unwrap().with_home(root.join("home"));
3509
    repo.create_identity("Ada", "[email protected]", IdentityScope::User)
3510
        .unwrap();
3511
    let url = remote.to_string_lossy().to_string();
3512
    let r = repo.git_fetch(&url, "main").unwrap();
3513
    assert_eq!((r.commits, r.heads), (2, 1));
3514
    assert_eq!(
3515
        fs::read(o.join("src/lib.rs")).unwrap(),
3516
        b"pub fn a() {}\npub fn b() {}\n"
3517
    );
3518
    assert!(!repo.snapshot("status").unwrap().changed);
3519
    assert_eq!(
3520
        repo.git_fetch(&url, "main").unwrap().commits,
3521
        0,
3522
        "nothing new"
3523
    );
3524
3525
    // An oxy change, pushed back: one commit on top of the Git tip.
3526
    write(
3527
        &o,
3528
        "src/lib.rs",
3529
        b"pub fn a() {}\npub fn b() {}\npub fn c() {}\n",
3530
    );
3531
    write(&o, "NOTES.md", b"from oxy\n");
3532
    let h_oxy = repo.commit("add c and notes", &[]).unwrap();
3533
    let r = repo.git_push(&url, "main").unwrap();
3534
    assert_eq!(r.exported, 1, "{r:?}");
3535
    git_in(&work, &["pull", "-q", "--ff-only", "origin", "main"]);
3536
    assert_eq!(
3537
        git_in(&work, &["log", "--format=%s", "main"]),
3538
        "add c and notes\nsecond\ninitial"
3539
    );
3540
    assert_eq!(git_in(&work, &["rev-parse", "HEAD~1"]), tip1);
3541
    assert_eq!(fs::read(work.join("NOTES.md")).unwrap(), b"from oxy\n");
3542
    assert_eq!(git_in(&work, &["log", "-1", "--format=%an", "main"]), "Ada");
3543
    assert!(git_in(&work, &["log", "-1", "--format=%B", "main"])
3544
        .contains(&format!("Oxy-Hash: {}", h_oxy.to_hex())));
3545
    assert_eq!(
3546
        repo.git_push(&url, "main").unwrap().exported,
3547
        0,
3548
        "already pushed"
3549
    );
3550
3551
    // Git moves on; pushing without fetching is refused, fetching brings
3552
    // the commit in and the working copy follows.
3553
    write(&work, "README.md", b"# Project\n\nMore.\n");
3554
    git_in(&work, &["commit", "-q", "-am", "readme from git"]);
3555
    git_in(&work, &["push", "-q", "origin", "main"]);
3556
    let tip2 = git_in(&work, &["rev-parse", "HEAD"]);
3557
    assert!(repo
3558
        .git_push(&url, "main")
3559
        .unwrap_err()
3560
        .to_string()
3561
        .contains("fetch"));
3562
    let r = repo.git_fetch(&url, "main").unwrap();
3563
    assert_eq!(
3564
        (r.commits, r.heads),
3565
        (1, 2),
3566
        "the Git change and the oxy change commute"
3567
    );
3568
    assert_eq!(
3569
        fs::read(o.join("README.md")).unwrap(),
3570
        b"# Project\n\nMore.\n"
3571
    );
3572
    assert_eq!(fs::read(o.join("NOTES.md")).unwrap(), b"from oxy\n");
3573
    assert!(!repo.snapshot("status").unwrap().changed);
3574
    // Another oxy change pushes on top of Git's newest commit.
3575
    write(&o, "NOTES.md", b"from oxy\nagain\n");
3576
    repo.commit("notes again", &[]).unwrap();
3577
    assert_eq!(repo.git_push(&url, "main").unwrap().exported, 1);
3578
    git_in(&work, &["pull", "-q", "--ff-only", "origin", "main"]);
3579
    assert_eq!(git_in(&work, &["rev-parse", "HEAD~1"]), tip2);
3580
    assert_eq!(
3581
        fs::read(work.join("NOTES.md")).unwrap(),
3582
        b"from oxy\nagain\n"
3583
    );
3584
    assert_eq!(
3585
        git_in(&work, &["log", "--format=%s", "main"])
3586
            .lines()
3587
            .count(),
3588
        5
3589
    );
3590
}
3591
3592
/// Benchmark, not a gate: `cargo test --release -p oxy-core --lib bench_one_gibibyte -- --ignored --nocapture`.
3593
/// Commits, stores, clones, and reads back a 1 GiB incompressible file.
3594
#[test]
3595
#[ignore]
3596
fn bench_one_gibibyte_file() {
3597
    hermetic();
3598
    // /tmp is often a small tmpfs; `OXY_BENCH_DIR` picks a roomier disk.
3599
    let dir = match std::env::var_os("OXY_BENCH_DIR") {
3600
        Some(d) => tempfile::tempdir_in(d).unwrap(),
3601
        None => tempfile::tempdir().unwrap(),
3602
    };
3603
    let root = dir.path();
3604
    let repo = Repo::init(&root.join("r"))
3605
        .unwrap()
3606
        .with_home(root.join("home"));
3607
    let size = 1usize << 30;
3608
    let mut data = vec![0u8; size];
3609
    let mut x = 0x9e3779b97f4a7c15u64;
3610
    for chunk in data.chunks_mut(8) {
3611
        x ^= x << 13;
3612
        x ^= x >> 7;
3613
        x ^= x << 17;
3614
        let b = x.to_le_bytes();
3615
        chunk.copy_from_slice(&b[..chunk.len()]);
3616
    }
3617
    let t = std::time::Instant::now();
3618
    write(&root.join("r"), "big.bin", &data);
3619
    eprintln!("write 1 GiB to disk: {:.2?}", t.elapsed());
3620
    let t = std::time::Instant::now();
3621
    let h = repo.commit("big", &[]).unwrap();
3622
    eprintln!("commit (chunk + hash + store): {:.2?}", t.elapsed());
3623
    let t = std::time::Instant::now();
3624
    assert!(!repo.snapshot("status").unwrap().changed);
3625
    eprintln!("status on a clean 1 GiB working copy: {:.2?}", t.elapsed());
3626
    let t = std::time::Instant::now();
3627
    let objects = repo.store().list().unwrap().len();
3628
    eprintln!("objects stored: {objects} ({:.2?} to list)", t.elapsed());
3629
    let t = std::time::Instant::now();
3630
    let g = repo.gc(true).unwrap();
3631
    eprintln!("gc (pack): {:.2?} {g:?}", t.elapsed());
3632
    let t = std::time::Instant::now();
3633
    let clone = Repo::clone(&root.join("r").to_string_lossy(), &root.join("c")).unwrap();
3634
    eprintln!("clone (fetch + checkout): {:.2?}", t.elapsed());
3635
    let t = std::time::Instant::now();
3636
    let back = fs::read(root.join("c/big.bin")).unwrap();
3637
    assert_eq!(blake3::hash(&back), blake3::hash(&data));
3638
    eprintln!("read back and verify: {:.2?}", t.elapsed());
3639
    assert_eq!(clone.bookmark_heads().unwrap(), vec![h]);
3640
    let store_bytes: u64 = walkdir_size(&root.join("r/.oxy/objects"));
3641
    eprintln!(
3642
        "store size: {:.1} MiB for 1 GiB of data",
3643
        store_bytes as f64 / (1024.0 * 1024.0)
3644
    );
3645
}
3646
3647
fn walkdir_size(p: &Path) -> u64 {
3648
    let mut total = 0;
3649
    if let Ok(rd) = fs::read_dir(p) {
3650
        for e in rd.flatten() {
3651
            let path = e.path();
3652
            if path.is_dir() {
3653
                total += walkdir_size(&path);
3654
            } else if let Ok(m) = fs::metadata(&path) {
3655
                total += m.len();
3656
            }
3657
        }
3658
    }
3659
    total
3660
}
3661
3662
/// An opaque file whose size and mtime match the manifest is not read on
3663
/// the next snapshot: its blob comes from the manifest's stat cache.
3664
#[cfg(unix)]
3665
#[test]
3666
fn stat_cache_skips_reading_unchanged_opaque_files() {
3667
    use std::os::unix::fs::PermissionsExt;
3668
    hermetic();
3669
    let dir = tempfile::tempdir().unwrap();
3670
    let root = dir.path();
3671
    let repo = Repo::init(root).unwrap().with_home(root.join("home"));
3672
    let mut big = vec![0u8; 300 * 1024];
3673
    for (i, b) in big.iter_mut().enumerate() {
3674
        *b = (i as u32).wrapping_mul(2654435761).to_le_bytes()[1];
3675
    }
3676
    big[0] = 0;
3677
    write(root, "big.bin", &big);
3678
    write(root, "a.txt", b"text\n");
3679
    let h1 = repo.commit("base", &[]).unwrap();
3680
    let (_, _, m) = repo.read_manifest().unwrap().unwrap();
3681
    assert!(
3682
        m.entries["big.bin"].blob.is_some(),
3683
        "opaque files record their blob"
3684
    );
3685
    assert!(m.entries["a.txt"].blob.is_none());
3686
    let blob = m.entries["big.bin"].blob.unwrap();
3687
    assert!(repo.store().has(&blob));
3688
3689
    // Files modified within two seconds of the manifest are racy and still
3690
    // read; age the file so the cache applies, then snapshot to record it.
3691
    let old = std::time::SystemTime::now() - std::time::Duration::from_secs(30);
3692
    fs::File::options()
3693
        .write(true)
3694
        .open(root.join("big.bin"))
3695
        .unwrap()
3696
        .set_modified(old)
3697
        .unwrap();
3698
    assert!(!repo.snapshot("status").unwrap().changed);
3699
    // Now the file cannot be read at all; the snapshot succeeds without it.
3700
    fs::set_permissions(root.join("big.bin"), fs::Permissions::from_mode(0o000)).unwrap();
3701
    let snap = repo.snapshot("status").unwrap();
3702
    assert!(
3703
        !snap.changed && snap.statuses.is_empty(),
3704
        "{:?}",
3705
        snap.statuses
3706
    );
3707
    fs::set_permissions(root.join("big.bin"), fs::Permissions::from_mode(0o644)).unwrap();
3708
    // A real change (new mtime, new content) is seen and committed correctly.
3709
    let mut big2 = big.clone();
3710
    big2[10] ^= 0xff;
3711
    write(root, "big.bin", &big2);
3712
    let snap = repo.snapshot("status").unwrap();
3713
    assert_eq!(
3714
        snap.statuses
3715
            .iter()
3716
            .map(|s| (s.path.as_str(), s.status))
3717
            .collect::<Vec<_>>(),
3718
        vec![("big.bin", ChangeStatus::Modified)]
3719
    );
3720
    let h2 = repo.commit("edit", &[]).unwrap();
3721
    let files = repo.load_state(&[h2]).unwrap().materialize().files;
3722
    assert_eq!(
3723
        files["big.bin"].content,
3724
        FileContent::Opaque {
3725
            blobs: vec![Repo::blob_ref(&big2)]
3726
        }
3727
    );
3728
    // Checkout writes a manifest with blobs too, so the next status is cached.
3729
    repo.checkout(&[h1], false, "checkout").unwrap();
3730
    let (_, _, m) = repo.read_manifest().unwrap().unwrap();
3731
    assert_eq!(m.entries["big.bin"].blob, Some(Repo::blob_ref(&big)));
3732
    assert!(!repo.snapshot("status").unwrap().changed);
3733
}
3734
3735
#[test]
3736
fn status_json_lists_conflicts_with_contributors() {
3737
    hermetic();
3738
    let dir = tempfile::tempdir().unwrap();
3739
    let root = dir.path();
3740
    let repo = Repo::init(root).unwrap().with_home(root.join("home"));
3741
    write(root, "a.txt", b"one\n");
3742
    let h1 = repo.commit("base", &[]).unwrap();
3743
    write(root, "a.txt", b"one\nleft\n");
3744
    let ha = repo.commit("left", &[]).unwrap();
3745
    repo.checkout(&[h1], true, "checkout").unwrap();
3746
    write(root, "a.txt", b"one\nright\n");
3747
    let hb = repo.commit("right", &[]).unwrap();
3748
    repo.checkout(&[ha, hb], true, "checkout").unwrap();
3749
    let snap = repo.snapshot("status").unwrap();
3750
    assert!(snap.base_snapshot.is_conflicted());
3751
    let json = repo.status_json(&snap).unwrap();
3752
    let ida = repo.store().get_change(&ha).unwrap().change_id.to_hex();
3753
    let idb = repo.store().get_change(&hb).unwrap().change_id.to_hex();
3754
    assert!(json.contains("\"conflicted\":true"), "{json}");
3755
    assert!(
3756
        json.contains("\"kind\":\"text\",\"path\":\"a.txt\""),
3757
        "{json}"
3758
    );
3759
    assert!(json.contains(&ida) && json.contains(&idb), "{json}");
3760
    assert!(json.contains("\"resolved\":false"), "{json}");
3761
    assert!(json.starts_with('{') && json.ends_with('}'));
3762
    // Resolve and the report says so; a clean copy has no conflicts.
3763
    write(root, "a.txt", b"one\nleft\nright\n");
3764
    let snap = repo.snapshot("status").unwrap();
3765
    let json = repo.status_json(&snap).unwrap();
3766
    assert!(json.contains("\"resolved\":true"), "{json}");
3767
    repo.commit("resolve", &[]).unwrap();
3768
    let snap = repo.snapshot("status").unwrap();
3769
    let json = repo.status_json(&snap).unwrap();
3770
    assert!(
3771
        json.contains("\"clean\":true,\"conflicted\":false,\"paths\":[],\"conflicts\":[]"),
3772
        "{json}"
3773
    );
3774
}
3775
3776
#[test]
3777
fn ignore_rules_do_not_untrack_files() {
3778
    hermetic();
3779
    let dir = tempfile::tempdir().unwrap();
3780
    let root = dir.path();
3781
    let repo = Repo::init(root).unwrap().with_home(root.join("home"));
3782
    write(root, "src.c", b"int x;\n");
3783
    write(root, "build/out.o", b"\0obj");
3784
    write(root, "sub/keep.log", b"keep\n");
3785
    write(root, "sub/junk.log", b"junk\n");
3786
    write(root, ".oxyignore", b"/build\n*.log\n!sub/keep.log\n");
3787
    let snap = repo.snapshot("status").unwrap();
3788
    let added: Vec<&str> = snap.statuses.iter().map(|s| s.path.as_str()).collect();
3789
    assert_eq!(
3790
        added,
3791
        vec![".oxyignore", "src.c", "sub/keep.log"],
3792
        "anchored, glob, and negated rules"
3793
    );
3794
    let h1 = repo.commit("base", &[]).unwrap();
3795
    // Ignoring a tracked file changes nothing about it.
3796
    write(root, ".oxyignore", b"/build\n*.log\n!sub/keep.log\nsrc.c\n");
3797
    let snap = repo.snapshot("status").unwrap();
3798
    assert_eq!(
3799
        snap.statuses
3800
            .iter()
3801
            .map(|s| s.path.as_str())
3802
            .collect::<Vec<_>>(),
3803
        vec![".oxyignore"]
3804
    );
3805
    let h2 = repo.commit("ignore src.c", &[]).unwrap();
3806
    assert!(repo
3807
        .load_state(&[h2])
3808
        .unwrap()
3809
        .materialize()
3810
        .files
3811
        .contains_key("src.c"));
3812
    // Its edits are still seen, by status and by the prompt.
3813
    assert_eq!(repo.quick_dirty().unwrap(), Some(false));
3814
    write(root, "src.c", b"int x, y;\n");
3815
    assert_eq!(repo.quick_dirty().unwrap(), Some(true));
3816
    let snap = repo.snapshot("status").unwrap();
3817
    assert_eq!(
3818
        snap.statuses
3819
            .iter()
3820
            .map(|s| (s.path.as_str(), s.status))
3821
            .collect::<Vec<_>>(),
3822
        vec![("src.c", ChangeStatus::Modified)]
3823
    );
3824
    let h3 = repo.commit("edit src.c", &[]).unwrap();
3825
    assert!(
3826
        matches!(&repo.load_state(&[h3]).unwrap().materialize().files["src.c"].content, FileContent::Text { bytes, .. } if bytes == b"int x, y;\n")
3827
    );
3828
    // Deleting it on disk removes it, ignored or not; a checkout brings it back.
3829
    fs::remove_file(root.join("src.c")).unwrap();
3830
    let snap = repo.snapshot("status").unwrap();
3831
    assert_eq!(
3832
        snap.statuses
3833
            .iter()
3834
            .map(|s| (s.path.as_str(), s.status))
3835
            .collect::<Vec<_>>(),
3836
        vec![("src.c", ChangeStatus::Removed)]
3837
    );
3838
    repo.checkout(&[h3], true, "checkout").unwrap();
3839
    assert_eq!(fs::read(root.join("src.c")).unwrap(), b"int x, y;\n");
3840
    assert!(!repo.snapshot("status").unwrap().changed);
3841
    let _ = h1;
3842
}
3843
3844
#[test]
3845
fn split_works_on_non_heads_by_node() {
3846
    hermetic();
3847
    let dir = tempfile::tempdir().unwrap();
3848
    let root = dir.path();
3849
    let repo = Repo::init(root).unwrap().with_home(root.join("home"));
3850
    write(root, "a.txt", b"one\n");
3851
    write(root, "junk/x.lock", b"lock\n");
3852
    let h1 = repo.commit("work plus junk", &[]).unwrap();
3853
    write(root, "a.txt", b"one\ntwo\n");
3854
    let h2 = repo.commit("more work", &[]).unwrap();
3855
    assert_eq!(repo.store().get_change(&h2).unwrap().deps, vec![h1]);
3856
    let id1 = repo.store().get_change(&h1).unwrap().change_id;
3857
    // h1 is not a head: split it by node.
3858
    let (hj, h1b) = repo.split(&h1, &["junk".into()]).unwrap();
3859
    assert_ne!(h1b, h1);
3860
    assert_eq!(
3861
        repo.store().get_change(&h1b).unwrap().change_id,
3862
        id1,
3863
        "the rest keeps the ChangeId"
3864
    );
3865
    let junk = repo.store().get_change(&hj).unwrap();
3866
    assert!(junk.tree_ops.iter().all(
3867
        |op| matches!(op, TreeOp::AddNode { name, .. } if name == "junk" || name == "x.lock")
3868
    ));
3869
    let heads = repo.bookmark_heads().unwrap();
3870
    assert!(
3871
        heads.contains(&hj),
3872
        "the split-off part is a head of its own"
3873
    );
3874
    let snap = repo.load_state(&heads).unwrap().materialize();
3875
    assert!(
3876
        matches!(&snap.files["a.txt"].content, FileContent::Text { bytes, .. } if bytes == b"one\ntwo\n"),
3877
        "the dependent was rewritten onto the new hash"
3878
    );
3879
    assert!(snap.files.contains_key("junk/x.lock"));
3880
    let h2b = heads
3881
        .iter()
3882
        .find(|h| repo.store().get_change(h).unwrap().message == "more work")
3883
        .copied()
3884
        .unwrap();
3885
    assert_eq!(repo.store().get_change(&h2b).unwrap().deps, vec![h1b]);
3886
    assert!(!repo.snapshot("status").unwrap().changed);
3887
    // Abandoning the split-off head removes the junk from history.
3888
    repo.abandon(&hj).unwrap();
3889
    let heads = repo.bookmark_heads().unwrap();
3890
    let snap = repo.load_state(&heads).unwrap().materialize();
3891
    assert!(!snap.files.contains_key("junk/x.lock") && !snap.files.contains_key("junk"));
3892
    assert!(snap.files.contains_key("a.txt"));
3893
    // A dependent that touches the split-off paths blocks the split.
3894
    write(root, "junk/y.lock", b"y\n");
3895
    let hb = repo.commit("junk base", &[]).unwrap();
3896
    write(root, "junk/y.lock", b"yy\n");
3897
    write(root, "b.txt", b"b\n");
3898
    repo.commit("touches junk", &[]).unwrap();
3899
    let err = repo.split(&hb, &["junk".into()]).unwrap_err().to_string();
3900
    assert!(err.contains("depends on the split-off paths"), "{err}");
3901
}
3902
3903
#[test]
3904
fn bookmarks_switch_merge_and_push() {
3905
    hermetic();
3906
    let dir = tempfile::tempdir().unwrap();
3907
    let root = dir.path();
3908
    let origin = Repo::init(&root.join("origin")).unwrap();
3909
    let url = root.join("origin").to_string_lossy().to_string();
3910
    let mut repo = Repo::clone(&url, &root.join("r"))
3911
        .unwrap()
3912
        .with_home(root.join("home"));
3913
    let r = root.join("r");
3914
    write(&r, "a.txt", b"a\n");
3915
    let h_a = repo.commit("a", &[]).unwrap();
3916
    assert!(repo.push("origin", false).unwrap()[0].ok);
3917
3918
    // A bookmark at the working copy's base, then work on it.
3919
    assert!(repo.bookmark_create("bad name..", None).is_err());
3920
    assert!(repo.bookmark_create("-x", None).is_err());
3921
    assert_eq!(repo.bookmark_create("feature", None).unwrap(), vec![h_a]);
3922
    assert!(repo.bookmark_create("feature", None).is_err(), "exists");
3923
    repo.bookmark_switch("feature", false).unwrap();
3924
    assert_eq!(repo.config.bookmark, "feature");
3925
    write(&r, "a.txt", b"a\nb\n");
3926
    write(&r, "b.txt", b"b\n");
3927
    let h_b = repo.commit("b on feature", &[]).unwrap();
3928
    assert_eq!(
3929
        repo.bookmark_heads().unwrap(),
3930
        vec![h_b],
3931
        "b edits a.txt, so it depends on a"
3932
    );
3933
    assert_eq!(
3934
        repo.resolve_heads("main").unwrap(),
3935
        vec![h_a],
3936
        "main is untouched"
3937
    );
3938
    assert_eq!(
3939
        repo.resolve_change("feature").unwrap(),
3940
        h_b,
3941
        "a one-head bookmark names its change"
3942
    );
3943
    // Reopening keeps the workspace's bookmark.
3944
    let reopened = Repo::open(&r).unwrap().with_home(root.join("home"));
3945
    assert_eq!(reopened.config.bookmark, "feature");
3946
    // Back to main: b.txt goes away; work there.
3947
    repo.bookmark_switch("main", false).unwrap();
3948
    assert!(!r.join("b.txt").exists());
3949
    assert_eq!(fs::read(r.join("a.txt")).unwrap(), b"a\n");
3950
    write(&r, "c.txt", b"c\n");
3951
    let h_c = repo.commit("c on main", &[]).unwrap();
3952
    let list = repo.bookmarks().unwrap();
3953
    assert_eq!(
3954
        list.iter()
3955
            .map(|b| (b.name.as_str(), b.current))
3956
            .collect::<Vec<_>>(),
3957
        vec![("feature", false), ("main", true)]
3958
    );
3959
    assert_eq!(
3960
        list.iter().find(|b| b.name == "main").unwrap().ahead,
3961
        Some(1),
3962
        "c is not on origin yet"
3963
    );
3964
    // Merge feature into main: the union, both heads, no merge change.
3965
    let m = repo.merge("feature").unwrap();
3966
    assert!(m.changed && m.checked_out);
3967
    let mut want = vec![h_b, h_c];
3968
    want.sort();
3969
    assert_eq!(m.heads, want);
3970
    assert_eq!(fs::read(r.join("b.txt")).unwrap(), b"b\n");
3971
    assert!(!repo.merge("feature").unwrap().changed, "already merged");
3972
    assert!(repo.merge("main").is_err());
3973
    // The other bookmark can be pushed by name and appears at origin.
3974
    assert!(repo.push_bookmark("origin", "feature", false).unwrap()[0].ok);
3975
    assert_eq!(origin.resolve_heads("feature").unwrap(), vec![h_b]);
3976
    assert!(repo.push("origin", false).unwrap()[0].ok);
3977
    assert_eq!(
3978
        repo.bookmarks()
3979
            .unwrap()
3980
            .iter()
3981
            .find(|b| b.name == "main")
3982
            .unwrap()
3983
            .ahead,
3984
        Some(0)
3985
    );
3986
    // A second workspace inherits the current bookmark and can switch independently.
3987
    let ws = repo.workspace_add(&root.join("ws"), None).unwrap();
3988
    assert_eq!(ws.config.bookmark, "main");
3989
    let mut ws = ws;
3990
    ws.bookmark_switch("feature", false).unwrap();
3991
    assert_eq!(
3992
        Repo::open(&r).unwrap().config.bookmark,
3993
        "main",
3994
        "the first workspace is unaffected"
3995
    );
3996
    assert!(
3997
        repo.bookmark_delete("feature").is_err(),
3998
        "current bookmark of another workspace"
3999
    );
4000
    ws.bookmark_switch("main", false).unwrap();
4001
    // Set and delete.
4002
    assert_eq!(repo.bookmark_set("feature", &[h_a]).unwrap(), vec![h_a]);
4003
    assert!(repo.bookmark_delete("main").is_err(), "current here");
4004
    repo.bookmark_delete("feature").unwrap();
4005
    assert!(repo.resolve_heads("feature").is_err());
4006
    assert!(repo.bookmark_set("feature", &[h_a]).is_err());
4007
    assert!(
4008
        repo.checkout(&[h_a], false, "checkout").is_ok(),
4009
        "changes of a deleted bookmark remain"
4010
    );
4011
}
4012
4013
#[test]
4014
fn oxygen_subrepos_pin_follow_and_update() {
4015
    hermetic();
4016
    let dir = tempfile::tempdir().unwrap();
4017
    let root = dir.path();
4018
    // A library repository with two commits, and a bare-ish origin for it.
4019
    let lib_origin = Repo::init(&root.join("lib-origin")).unwrap();
4020
    let lib_url = root.join("lib-origin").to_string_lossy().to_string();
4021
    let lib = Repo::clone(&lib_url, &root.join("lib"))
4022
        .unwrap()
4023
        .with_home(root.join("home"));
4024
    write(&root.join("lib"), "lib.txt", b"v1\n");
4025
    let l1 = lib.commit("lib v1", &[]).unwrap();
4026
    assert!(lib.push("origin", false).unwrap()[0].ok);
4027
    let _ = lib_origin;
4028
4029
    // The application (a clone of its own origin) adds it as a subrepo.
4030
    let app_origin = Repo::init(&root.join("app-origin")).unwrap();
4031
    let app_url = root.join("app-origin").to_string_lossy().to_string();
4032
    let _ = app_origin;
4033
    let app_dir = root.join("app");
4034
    let app = Repo::clone(&app_url, &app_dir)
4035
        .unwrap()
4036
        .with_home(root.join("home"));
4037
    write(&app_dir, "main.txt", b"app\n");
4038
    let pin = app.submodule_add(&lib_url, "libs/lib", None).unwrap();
4039
    assert!(matches!(&pin, crate::subrepo::Pin::Oxy { heads, .. } if heads == &vec![l1]));
4040
    assert!(app_dir.join(".oxymodules").exists() && app_dir.join("libs/lib/.oxy").is_dir());
4041
    let snap = app.snapshot("status").unwrap();
4042
    let paths: Vec<&str> = snap.statuses.iter().map(|s| s.path.as_str()).collect();
4043
    assert_eq!(
4044
        paths,
4045
        vec![".oxymodules", "libs/lib", "main.txt"],
4046
        "the nested files are not walked"
4047
    );
4048
    let a1 = app.commit("app with lib", &[]).unwrap();
4049
    let files = app.load_state(&[a1]).unwrap().materialize().files;
4050
    assert_eq!(files["libs/lib"].kind, NodeKind::Subrepo);
4051
    assert!(!files.contains_key("libs/lib/lib.txt"));
4052
    assert!(!app.snapshot("status").unwrap().changed);
4053
    let subs = app.subrepos().unwrap();
4054
    assert_eq!(subs.len(), 1);
4055
    assert_eq!(subs[0].actual.as_ref(), Some(&subs[0].pin));
4056
4057
    // Advance the nested repository: the parent sees a modified pin.
4058
    let nested = Repo::open(&app_dir.join("libs/lib"))
4059
        .unwrap()
4060
        .with_home(root.join("home"));
4061
    write(&app_dir.join("libs/lib"), "lib.txt", b"v2\n");
4062
    let l2 = nested.commit("lib v2", &[]).unwrap();
4063
    assert!(nested.push("origin", false).unwrap()[0].ok);
4064
    let snap = app.snapshot("status").unwrap();
4065
    assert_eq!(
4066
        snap.statuses
4067
            .iter()
4068
            .map(|s| (s.path.as_str(), s.status))
4069
            .collect::<Vec<_>>(),
4070
        vec![("libs/lib", ChangeStatus::Modified)]
4071
    );
4072
    let a2 = app.commit("bump lib", &[]).unwrap();
4073
    // Checking out the older app state brings the nested working copy back
4074
    // to the older pin, but never moves its bookmark backwards (oxygen#38).
4075
    let r = app.checkout(&[a1], false, "checkout").unwrap();
4076
    assert!(
4077
        r.notes.len() == 1 && r.notes[0].contains("keeps 1 newer change"),
4078
        "{:?}",
4079
        r.notes
4080
    );
4081
    assert_eq!(fs::read(app_dir.join("libs/lib/lib.txt")).unwrap(), b"v1\n");
4082
    let nested = Repo::open(&app_dir.join("libs/lib")).unwrap();
4083
    assert_eq!(nested.bookmark_heads().unwrap(), vec![l2]);
4084
    assert_eq!(nested.working_copy().unwrap().1.deps, vec![l1]);
4085
    assert!(!app.snapshot("status").unwrap().changed);
4086
    // A dirty nested repository is left alone and reported.
4087
    write(&app_dir.join("libs/lib"), "scratch.txt", b"wip\n");
4088
    let r = app.checkout(&[a2], false, "checkout").unwrap();
4089
    assert!(
4090
        r.notes.iter().any(|n| n.contains("uncommitted")),
4091
        "{:?}",
4092
        r.notes
4093
    );
4094
    assert_eq!(fs::read(app_dir.join("libs/lib/lib.txt")).unwrap(), b"v1\n");
4095
    fs::remove_file(app_dir.join("libs/lib/scratch.txt")).unwrap();
4096
    let r = app.submodule_update(false, &[]).unwrap();
4097
    assert_eq!(r, vec![("libs/lib".to_string(), SubrepoSync::Updated)]);
4098
    assert_eq!(fs::read(app_dir.join("libs/lib/lib.txt")).unwrap(), b"v2\n");
4099
    let _ = l2;
4100
4101
    // A fresh clone of the app has the pin but no nested repository until update --init.
4102
    assert!(app.push("origin", false).unwrap()[0].ok);
4103
    let clone_dir = root.join("app-clone");
4104
    let clone = Repo::clone(&app_url, &clone_dir)
4105
        .unwrap()
4106
        .with_home(root.join("home"));
4107
    assert!(!clone_dir.join("libs/lib/.oxy").exists());
4108
    assert_eq!(
4109
        clone.submodule_update(false, &[]).unwrap(),
4110
        vec![("libs/lib".to_string(), SubrepoSync::Missing)]
4111
    );
4112
    assert_eq!(
4113
        clone.submodule_update(true, &[]).unwrap(),
4114
        vec![("libs/lib".to_string(), SubrepoSync::Updated)]
4115
    );
4116
    assert_eq!(
4117
        fs::read(clone_dir.join("libs/lib/lib.txt")).unwrap(),
4118
        b"v2\n"
4119
    );
4120
    assert!(!clone.snapshot("status").unwrap().changed);
4121
    // Removing the subrepo leaves the directory and drops the node.
4122
    clone.submodule_remove("libs/lib").unwrap();
4123
    let snap = clone.snapshot("status").unwrap();
4124
    assert!(
4125
        snap.statuses
4126
            .iter()
4127
            .any(|s| s.path == "libs/lib" && s.status == ChangeStatus::Removed),
4128
        "{:?}",
4129
        snap.statuses
4130
    );
4131
    let c = clone.commit("drop lib", &[]).unwrap();
4132
    assert!(!clone
4133
        .load_state(&[c])
4134
        .unwrap()
4135
        .materialize()
4136
        .files
4137
        .contains_key("libs/lib"));
4138
    assert!(clone_dir.join("libs/lib/lib.txt").exists());
4139
    assert!(
4140
        !clone.snapshot("status").unwrap().changed,
4141
        "an unregistered nested repository is ignored"
4142
    );
4143
}
4144
4145
#[test]
4146
fn git_submodules_import_and_export_as_gitlinks() {
4147
    hermetic();
4148
    if std::process::Command::new("git")
4149
        .arg("--version")
4150
        .output()
4151
        .is_err()
4152
    {
4153
        eprintln!("git not installed; skipping");
4154
        return;
4155
    }
4156
    let dir = tempfile::tempdir().unwrap();
4157
    let root = dir.path();
4158
    let git_in = |d: &Path, args: &[&str]| -> String {
4159
        let out = std::process::Command::new("git")
4160
            .arg("-C")
4161
            .arg(d)
4162
            .args([
4163
                "-c",
4164
                "user.name=Grace",
4165
                "-c",
4166
                "[email protected]",
4167
                "-c",
4168
                "commit.gpgsign=false",
4169
                "-c",
4170
                "protocol.file.allow=always",
4171
            ])
4172
            .args(args)
4173
            .output()
4174
            .unwrap();
4175
        assert!(
4176
            out.status.success(),
4177
            "git {args:?}: {}",
4178
            String::from_utf8_lossy(&out.stderr)
4179
        );
4180
        String::from_utf8_lossy(&out.stdout).trim().to_string()
4181
    };
4182
    let sub = root.join("sub");
4183
    fs::create_dir_all(&sub).unwrap();
4184
    git_in(&sub, &["init", "-q", "-b", "main"]);
4185
    write(&sub, "s.txt", b"sub\n");
4186
    git_in(&sub, &["add", "."]);
4187
    git_in(&sub, &["commit", "-q", "-m", "sub initial"]);
4188
    let sub_sha = git_in(&sub, &["rev-parse", "HEAD"]);
4189
    let g = root.join("main.git");
4190
    fs::create_dir_all(&g).unwrap();
4191
    git_in(&g, &["init", "-q", "-b", "main"]);
4192
    write(&g, "README.md", b"# app\n");
4193
    git_in(&g, &["add", "."]);
4194
    git_in(&g, &["commit", "-q", "-m", "initial"]);
4195
    git_in(
4196
        &g,
4197
        &[
4198
            "submodule",
4199
            "add",
4200
            "-q",
4201
            sub.to_str().unwrap(),
4202
            "vendor/sub",
4203
        ],
4204
    );
4205
    git_in(&g, &["commit", "-q", "-m", "add submodule"]);
4206
4207
    let dest = root.join("oxy");
4208
    let repo = Repo::init(&dest).unwrap().with_home(root.join("home"));
4209
    let rep = repo.import_git(&g, "main").unwrap();
4210
    assert_eq!((rep.commits, rep.submodules), (2, 1));
4211
    let files = repo
4212
        .load_state(&repo.bookmark_heads().unwrap())
4213
        .unwrap()
4214
        .materialize()
4215
        .files;
4216
    assert_eq!(files["vendor/sub"].kind, NodeKind::Subrepo);
4217
    let FileContent::Opaque { blobs } = &files["vendor/sub"].content else {
4218
        panic!()
4219
    };
4220
    assert_eq!(
4221
        crate::subrepo::Pin::decode(&repo.read_blob(&blobs[0]).unwrap()).unwrap(),
4222
        crate::subrepo::Pin::Git {
4223
            sha: sub_sha.clone(),
4224
            branch: "HEAD".into()
4225
        }
4226
    );
4227
    let modules =
4228
        crate::subrepo::Modules::parse(&fs::read_to_string(dest.join(".oxymodules")).unwrap());
4229
    assert_eq!(modules.entries["vendor/sub"].url, sub.to_string_lossy());
4230
    assert!(modules.entries["vendor/sub"].git);
4231
    assert!(
4232
        files.contains_key(".gitmodules"),
4233
        "the Git file is kept for round trips"
4234
    );
4235
    assert!(
4236
        !dest.join("vendor/sub/.git").exists(),
4237
        "not cloned until update --init"
4238
    );
4239
    assert!(!repo.snapshot("status").unwrap().changed);
4240
    // update --init clones it at the pinned commit; status is unchanged.
4241
    assert_eq!(
4242
        repo.submodule_update(true, &[]).unwrap(),
4243
        vec![("vendor/sub".to_string(), SubrepoSync::Updated)]
4244
    );
4245
    assert_eq!(
4246
        git_in(&dest.join("vendor/sub"), &["rev-parse", "HEAD"]),
4247
        sub_sha
4248
    );
4249
    assert!(!repo.snapshot("status").unwrap().changed);
4250
    // Export writes the gitlink and .gitmodules back.
4251
    let mirror = root.join("mirror.git");
4252
    let rep = repo.git_export(&mirror).unwrap();
4253
    assert_eq!(rep.skipped_subrepos, 0);
4254
    let ls = git_in(&mirror, &["ls-tree", "main", "vendor/sub"]);
4255
    assert!(
4256
        ls.starts_with("160000 commit ") && ls.contains(&sub_sha),
4257
        "{ls}"
4258
    );
4259
    assert_eq!(
4260
        git_in(&mirror, &["ls-tree", "--name-only", "main"]),
4261
        ".gitmodules\nREADME.md\nvendor"
4262
    );
4263
    let orig_tree = git_in(&g, &["rev-parse", "main^{tree}"]);
4264
    assert_eq!(
4265
        git_in(&mirror, &["rev-parse", "main^{tree}"]),
4266
        orig_tree,
4267
        "tree round trip"
4268
    );
4269
}
4270
4271
#[test]
4272
fn partial_commits_by_path_and_by_hunk() {
4273
    hermetic();
4274
    let dir = tempfile::tempdir().unwrap();
4275
    let root = dir.path();
4276
    let repo = Repo::init(root).unwrap().with_home(root.join("home"));
4277
    write(root, "a.txt", b"1\n2\n3\n");
4278
    write(root, "b.txt", b"b\n");
4279
    let h0 = repo.commit("base", &[]).unwrap();
4280
    write(root, "a.txt", b"0\n1\n2\n3\n4\n");
4281
    write(root, "b.txt", b"b\nbb\n");
4282
    write(root, "c.txt", b"c\n");
4283
    // By path: only a.txt goes in; the rest stays on disk as uncommitted work.
4284
    let h1 = repo
4285
        .commit_selection("a only", &[], &Selection::Paths(vec!["a.txt".into()]))
4286
        .unwrap();
4287
    let c1 = repo.store().get_change(&h1).unwrap();
4288
    assert!(
4289
        c1.tree_ops.is_empty() && c1.edits.iter().all(|e| e.node() == c1.edits[0].node()),
4290
        "{:?}",
4291
        c1.tree_ops
4292
    );
4293
    assert_eq!(c1.deps, vec![h0]);
4294
    let files = repo.load_state(&[h1]).unwrap().materialize().files;
4295
    assert!(
4296
        matches!(&files["a.txt"].content, FileContent::Text { bytes, .. } if bytes == b"0\n1\n2\n3\n4\n")
4297
    );
4298
    assert!(matches!(&files["b.txt"].content, FileContent::Text { bytes, .. } if bytes == b"b\n"));
4299
    assert!(!files.contains_key("c.txt"));
4300
    let snap = repo.snapshot("status").unwrap();
4301
    assert_eq!(
4302
        snap.statuses
4303
            .iter()
4304
            .map(|s| (s.path.as_str(), s.status))
4305
            .collect::<Vec<_>>(),
4306
        vec![
4307
            ("b.txt", ChangeStatus::Modified),
4308
            ("c.txt", ChangeStatus::Added)
4309
        ]
4310
    );
4311
    assert_eq!(
4312
        fs::read(root.join("b.txt")).unwrap(),
4313
        b"b\nbb\n",
4314
        "disk untouched"
4315
    );
4316
    // By hunk: pick the b.txt insert; c.txt's addition is left.
4317
    let (_, hunks) = repo.hunks().unwrap();
4318
    let b_hunk = hunks
4319
        .iter()
4320
        .find(|h| h.path == "b.txt" && h.text.contains("+bb"))
4321
        .unwrap()
4322
        .index;
4323
    let h2 = repo
4324
        .commit_selection("b only", &[], &Selection::Hunks(vec![b_hunk]))
4325
        .unwrap();
4326
    let files = repo.load_state(&[h2]).unwrap().materialize().files;
4327
    assert!(
4328
        matches!(&files["b.txt"].content, FileContent::Text { bytes, .. } if bytes == b"b\nbb\n")
4329
    );
4330
    assert!(!files.contains_key("c.txt"));
4331
    let snap = repo.snapshot("status").unwrap();
4332
    assert_eq!(
4333
        snap.statuses
4334
            .iter()
4335
            .map(|s| s.path.as_str())
4336
            .collect::<Vec<_>>(),
4337
        vec!["c.txt"]
4338
    );
4339
    // Choosing only the content hunk of a file in a new directory pulls in
4340
    // the directory and file additions it needs.
4341
    write(root, "d/e.txt", b"e\n");
4342
    let (_, hunks) = repo.hunks().unwrap();
4343
    let e_insert = hunks
4344
        .iter()
4345
        .find(|h| h.path == "d/e.txt" && h.text.contains("+e"))
4346
        .unwrap()
4347
        .index;
4348
    let h3 = repo
4349
        .commit_selection("e only", &[], &Selection::Hunks(vec![e_insert]))
4350
        .unwrap();
4351
    let c3 = repo.store().get_change(&h3).unwrap();
4352
    assert_eq!(c3.tree_ops.len(), 2, "{:?}", c3.tree_ops);
4353
    let files = repo.load_state(&[h3]).unwrap().materialize().files;
4354
    assert!(files.contains_key("d/e.txt") && !files.contains_key("c.txt"));
4355
    // Choosing a new file's addition hunk brings its content along.
4356
    write(root, "f/g.txt", b"g\n");
4357
    let (_, hunks) = repo.hunks().unwrap();
4358
    let g_add = hunks
4359
        .iter()
4360
        .find(|h| h.path == "f/g.txt" && h.text.starts_with("A "))
4361
        .unwrap()
4362
        .index;
4363
    let h4 = repo
4364
        .commit_selection("g by addition", &[], &Selection::Hunks(vec![g_add]))
4365
        .unwrap();
4366
    let files = repo.load_state(&[h4]).unwrap().materialize().files;
4367
    assert!(
4368
        matches!(&files["f/g.txt"].content, FileContent::Text { bytes, .. } if bytes == b"g\n")
4369
    );
4370
    assert!(!repo
4371
        .snapshot("status")
4372
        .unwrap()
4373
        .statuses
4374
        .iter()
4375
        .any(|s| s.path == "f/g.txt"));
4376
    // Everything left commits normally; the working copy is then clean.
4377
    repo.commit("the rest", &[]).unwrap();
4378
    assert!(!repo.snapshot("status").unwrap().changed);
4379
    let files = repo
4380
        .load_state(&repo.bookmark_heads().unwrap())
4381
        .unwrap()
4382
        .materialize()
4383
        .files;
4384
    assert!(files.contains_key("c.txt"));
4385
}
4386
4387
#[test]
4388
fn blame_attributes_lines_to_introducing_changes_across_renames() {
4389
    hermetic();
4390
    let dir = tempfile::tempdir().unwrap();
4391
    let root = dir.path();
4392
    let mut repo = Repo::init(root).unwrap().with_home(root.join("home"));
4393
    repo.create_identity("Ada", "[email protected]", IdentityScope::User)
4394
        .unwrap();
4395
    write(root, "a.txt", b"one\n");
4396
    let h1 = repo.commit("first", &[]).unwrap();
4397
    write(root, "a.txt", b"one\ntwo\n");
4398
    let h2 = repo.commit("second", &[]).unwrap();
4399
    let b = repo.blame("a.txt").unwrap();
4400
    assert_eq!(
4401
        b.iter()
4402
            .map(|l| (l.line, l.hash, l.text.as_slice()))
4403
            .collect::<Vec<_>>(),
4404
        vec![(1, h1, b"one\n".as_slice()), (2, h2, b"two\n".as_slice())]
4405
    );
4406
    assert!(b.iter().all(|l| l.author == "Ada"));
4407
    assert_eq!(
4408
        b[0].change_id,
4409
        repo.store().get_change(&h1).unwrap().change_id
4410
    );
4411
    fs::rename(root.join("a.txt"), root.join("b.txt")).unwrap();
4412
    repo.commit("rename", &[]).unwrap();
4413
    let b = repo.blame("b.txt").unwrap();
4414
    assert_eq!(
4415
        b.iter().map(|l| l.hash).collect::<Vec<_>>(),
4416
        vec![h1, h2],
4417
        "the node survives the rename"
4418
    );
4419
    assert!(repo.blame("a.txt").is_err());
4420
}
4421
4422
#[test]
4423
fn bisect_finds_the_first_bad_change() {
4424
    hermetic();
4425
    let dir = tempfile::tempdir().unwrap();
4426
    let root = dir.path();
4427
    let repo = Repo::init(root).unwrap().with_home(root.join("home"));
4428
    let mut content = String::new();
4429
    let mut hashes = Vec::new();
4430
    for i in 1..=8 {
4431
        content.push_str(&format!("line {i}{}\n", if i == 5 { " bug" } else { "" }));
4432
        write(root, "f.txt", content.as_bytes());
4433
        hashes.push(repo.commit(&format!("step {i}"), &[]).unwrap());
4434
    }
4435
    // Each step appends after the previous line, so the chain is linear.
4436
    assert_eq!(repo.bookmark_heads().unwrap(), vec![hashes[7]]);
4437
    repo.bisect_start().unwrap();
4438
    assert!(matches!(
4439
        repo.bisect_mark(Some(true), &[hashes[0]]).unwrap(),
4440
        BisectStep::NeedMarks { good: 1, bad: 0 }
4441
    ));
4442
    let step = repo.bisect_mark(Some(false), &[hashes[7]]).unwrap();
4443
    assert!(
4444
        matches!(step, BisectStep::Testing { remaining: 7, .. }),
4445
        "{step:?}"
4446
    );
4447
    // Automated: bad when the bug line is present.
4448
    let step = repo
4449
        .bisect_run(&["sh".into(), "-c".into(), "! grep -q bug f.txt".into()])
4450
        .unwrap();
4451
    assert_eq!(step, BisectStep::Found { culprit: hashes[4] });
4452
    assert_eq!(
4453
        repo.bisect_status().unwrap(),
4454
        Some(BisectStep::Found { culprit: hashes[4] })
4455
    );
4456
    repo.bisect_reset().unwrap();
4457
    assert_eq!(fs::read_to_string(root.join("f.txt")).unwrap(), content);
4458
    assert!(repo.bisect_status().unwrap().is_none());
4459
    assert!(!repo.snapshot("status").unwrap().changed);
4460
    // Manual marks and a skip.
4461
    repo.bisect_start().unwrap();
4462
    repo.bisect_mark(Some(true), &[hashes[0]]).unwrap();
4463
    let mut step = repo.bisect_mark(Some(false), &[hashes[7]]).unwrap();
4464
    let mut skipped_once = false;
4465
    let mut guard = 0;
4466
    while let BisectStep::Testing { .. } = step {
4467
        guard += 1;
4468
        assert!(guard < 20);
4469
        let text = fs::read_to_string(root.join("f.txt")).unwrap();
4470
        if !skipped_once && text.contains("line 6") {
4471
            // An untestable state away from the boundary: the search routes around it.
4472
            skipped_once = true;
4473
            step = repo.bisect_mark(None, &[]).unwrap();
4474
            continue;
4475
        }
4476
        step = repo.bisect_mark(Some(!text.contains("bug")), &[]).unwrap();
4477
    }
4478
    assert!(skipped_once);
4479
    assert_eq!(step, BisectStep::Found { culprit: hashes[4] });
4480
    repo.bisect_reset().unwrap();
4481
    // Skipping the culprit itself leaves it among the candidates reported.
4482
    repo.bisect_start().unwrap();
4483
    repo.bisect_mark(Some(true), &[hashes[0]]).unwrap();
4484
    let mut step = repo.bisect_mark(Some(false), &[hashes[7]]).unwrap();
4485
    let mut guard = 0;
4486
    while let BisectStep::Testing { heads, .. } = &step {
4487
        guard += 1;
4488
        assert!(guard < 20);
4489
        let text = fs::read_to_string(root.join("f.txt")).unwrap();
4490
        let is_culprit_state =
4491
            heads.contains(&hashes[4]) && !heads.iter().any(|h| hashes[5..].contains(h));
4492
        step = if is_culprit_state {
4493
            repo.bisect_mark(None, &[]).unwrap()
4494
        } else {
4495
            repo.bisect_mark(Some(!text.contains("bug")), &[]).unwrap()
4496
        };
4497
    }
4498
    match step {
4499
        BisectStep::Inconclusive { candidates } => assert!(
4500
            candidates.contains(&hashes[4]) && candidates.len() <= 2,
4501
            "{candidates:?}"
4502
        ),
4503
        other => panic!("{other:?}"),
4504
    }
4505
    repo.bisect_reset().unwrap();
4506
}
4507
4508
#[test]
4509
fn squash_folds_a_change_into_its_dependency() {
4510
    hermetic();
4511
    let dir = tempfile::tempdir().unwrap();
4512
    let root = dir.path();
4513
    let repo = Repo::init(root).unwrap().with_home(root.join("home"));
4514
    write(root, "a.txt", b"1\n");
4515
    let a = repo.commit("A", &[]).unwrap();
4516
    write(root, "a.txt", b"1\n2\n");
4517
    let c = repo.commit("C", &[]).unwrap();
4518
    write(root, "a.txt", b"1\n2\n3\n");
4519
    let e = repo.commit("E", &[]).unwrap();
4520
    write(root, "b.txt", b"b\n");
4521
    let b = repo.commit("B", &[]).unwrap();
4522
    let id_a = repo.store().get_change(&a).unwrap().change_id;
4523
    let id_e = repo.store().get_change(&e).unwrap().change_id;
4524
    // E depends on C which A lacks: refused, naming it.
4525
    let err = repo.squash(&e, &a).unwrap_err().to_string();
4526
    assert!(err.contains(&c.short(12)), "{err}");
4527
    // C into A: A' has both, C is gone, E follows and still reads the same.
4528
    let a2 = repo.squash(&c, &a).unwrap();
4529
    let a2c = repo.store().get_change(&a2).unwrap();
4530
    assert_eq!(a2c.change_id, id_a);
4531
    assert!(a2c.deps.is_empty());
4532
    let heads = repo.bookmark_heads().unwrap();
4533
    let st = repo.load_state(&heads).unwrap();
4534
    assert!(!st.contains(&c) && !st.contains(&a) && !st.contains(&e));
4535
    let e2 = st
4536
        .changes()
4537
        .find(|(_, m)| m.change_id == id_e)
4538
        .map(|(h, _)| *h)
4539
        .unwrap();
4540
    assert_eq!(
4541
        repo.store().get_change(&e2).unwrap().deps,
4542
        vec![a2],
4543
        "E now depends on A' alone"
4544
    );
4545
    let files = st.materialize().files;
4546
    assert!(
4547
        matches!(&files["a.txt"].content, FileContent::Text { bytes, .. } if bytes == b"1\n2\n3\n")
4548
    );
4549
    assert!(files.contains_key("b.txt"));
4550
    assert!(st.contains(&b));
4551
    assert!(!repo.snapshot("status").unwrap().changed);
4552
    assert_eq!(repo.log().unwrap().len(), 4, "working copy, B, E', A'");
4553
    // Undo restores the three original changes.
4554
    repo.undo().unwrap();
4555
    repo.undo().unwrap();
4556
    let st = repo.load_state(&repo.bookmark_heads().unwrap()).unwrap();
4557
    assert!(st.contains(&c) && st.contains(&a) && st.contains(&e));
4558
}
4559
4560
#[test]
4561
fn rebase_re_expresses_a_change_against_another_base() {
4562
    hermetic();
4563
    let dir = tempfile::tempdir().unwrap();
4564
    let root = dir.path();
4565
    let repo = Repo::init(root).unwrap().with_home(root.join("home"));
4566
    write(root, "a.txt", b"1\n2\n");
4567
    let a = repo.commit("A", &[]).unwrap();
4568
    write(root, "a.txt", b"1\n2\n3\n");
4569
    let c = repo.commit("C: append 3", &[]).unwrap();
4570
    write(root, "a.txt", b"1\n2\n3\n4\n");
4571
    let e = repo.commit("E: append 4", &[]).unwrap();
4572
    // A different base: A plus a change that prepends a line.
4573
    repo.checkout(&[a], true, "checkout").unwrap();
4574
    write(root, "a.txt", b"0\n1\n2\n");
4575
    let d = repo.commit("D: prepend 0", &[]).unwrap();
4576
    let id_c = repo.store().get_change(&c).unwrap().change_id;
4577
    let id_e = repo.store().get_change(&e).unwrap().change_id;
4578
    // Rebase C onto D: its effect (append 3) re-derived against D's text.
4579
    let c2 = repo.rebase(&c, &[d]).unwrap();
4580
    let c2c = repo.store().get_change(&c2).unwrap();
4581
    assert_eq!(c2c.change_id, id_c);
4582
    assert!(c2c.deps.contains(&d), "{:?}", c2c.deps);
4583
    let heads = repo.bookmark_heads().unwrap();
4584
    let st = repo.load_state(&heads).unwrap();
4585
    assert!(!st.contains(&c) && st.contains(&d));
4586
    let e2 = st
4587
        .changes()
4588
        .find(|(_, m)| m.change_id == id_e)
4589
        .map(|(h, _)| *h)
4590
        .unwrap();
4591
    let e2deps = repo.store().get_change(&e2).unwrap().deps;
4592
    assert!(
4593
        e2deps.contains(&c2) && !e2deps.contains(&c) && e2deps.contains(&a),
4594
        "E follows C by content and still depends on A, which introduced the file: {e2deps:?}"
4595
    );
4596
    let files = st.materialize().files;
4597
    assert!(
4598
        matches!(&files["a.txt"].content, FileContent::Text { bytes, .. } if bytes == b"0\n1\n2\n3\n4\n"),
4599
        "{:?}",
4600
        files["a.txt"].content
4601
    );
4602
    assert!(!files["a.txt"].is_conflicted());
4603
    // Rebasing onto a state that already contains the change is refused.
4604
    assert!(repo.rebase(&c2, &[c2]).is_err());
4605
    let err = repo.rebase(&e2, &[d]).unwrap_err().to_string();
4606
    assert!(
4607
        err.contains("lacks dependencies"),
4608
        "E needs C, which D's state does not have: {err}"
4609
    );
4610
}
4611
4612
#[test]
4613
fn unsigned_tags_keep_their_message() {
4614
    hermetic();
4615
    let dir = tempfile::tempdir().unwrap();
4616
    let root = dir.path();
4617
    let repo = Repo::init(root).unwrap().with_home(root.join("home"));
4618
    write(root, "a.txt", b"a\n");
4619
    repo.commit("a", &[]).unwrap();
4620
    assert!(repo.secret_key().unwrap().is_none());
4621
    repo.tag_create("v1", &repo.bookmark_heads().unwrap(), "first release")
4622
        .unwrap();
4623
    let tags = repo.tags().unwrap();
4624
    assert_eq!(
4625
        (
4626
            tags[0].name.as_str(),
4627
            tags[0].message.as_str(),
4628
            tags[0].signer.as_deref()
4629
        ),
4630
        ("v1", "first release", None)
4631
    );
4632
    assert!(
4633
        repo.tag_refs().unwrap()[0].attestation.is_none(),
4634
        "an unsigned attestation is not advertised"
4635
    );
4636
}
4637
4638
#[test]
4639
fn fsck_passes_a_sound_repository_and_names_each_fault() {
4640
    // Files on disk are what this tests: tampering with them, and the
4641
    // directory store's crash points.
4642
    if std::env::var_os("OXY_STORE_BACKEND").is_some() {
4643
        return;
4644
    }
4645
    hermetic();
4646
    let dir = tempfile::tempdir().unwrap();
4647
    let root = dir.path();
4648
    let origin_path = root.join("origin");
4649
    let origin = Repo::init(&origin_path).unwrap();
4650
    let mut a = Repo::clone(&origin_path.to_string_lossy(), &root.join("a"))
4651
        .unwrap()
4652
        .with_home(root.join("home-a"));
4653
    a.create_identity("Ada", "[email protected]", IdentityScope::Repo)
4654
        .unwrap();
4655
    write(&root.join("a"), "f.txt", b"one\n");
4656
    write(&root.join("a"), "bin.dat", b"\0\x01\x02binary");
4657
    let h1 = a.commit("first", &[]).unwrap();
4658
    write(&root.join("a"), "f.txt", b"one\ntwo\n");
4659
    let h2 = a.commit("second", &[]).unwrap();
4660
    a.tag_create("v1", &[h2], "first release").unwrap();
4661
    a.checkpoint().unwrap();
4662
    assert!(a.push("origin", false).unwrap()[0].ok);
4663
4664
    // Sound: signed changes, a seal, a tag, a checkpoint, a ref attestation.
4665
    for repo in [&a, &origin] {
4666
        let rep = repo.fsck().unwrap();
4667
        assert_eq!(rep.problems, vec![], "{rep:?}");
4668
        // The two commits, plus the working copy's change in `a`.
4669
        assert!(rep.changes >= 2 && rep.signed >= 2, "{rep:?}");
4670
        assert!(rep.ops > 1 && rep.objects > 5);
4671
    }
4672
    assert!(origin.fsck().unwrap().attestations >= 1);
4673
4674
    // A flipped byte in a stored object is corruption, named by hash.
4675
    let c1 = a.store().path_for(&h1);
4676
    let pristine = fs::read(&c1).unwrap();
4677
    let mut bytes = pristine.clone();
4678
    *bytes.last_mut().unwrap() ^= 1;
4679
    fs::write(&c1, &bytes).unwrap();
4680
    let rep = a.fsck().unwrap();
4681
    assert!(rep.errors() >= 1);
4682
    assert!(
4683
        rep.problems
4684
            .iter()
4685
            .any(|p| p.object == Some(h1) && p.what.contains("unreadable")),
4686
        "{rep:?}"
4687
    );
4688
    fs::write(&c1, &pristine).unwrap();
4689
    assert_eq!(a.fsck().unwrap().errors(), 0);
4690
4691
    // A missing change is named with what needed it.
4692
    fs::remove_file(&c1).unwrap();
4693
    let rep = a.fsck().unwrap();
4694
    assert!(
4695
        rep.problems.iter().any(|p| p.severity == Severity::Error
4696
            && p.object == Some(h1)
4697
            && p.what.contains("change missing, needed by change")),
4698
        "{rep:?}"
4699
    );
4700
    fs::write(&c1, &pristine).unwrap();
4701
4702
    // A missing blob is an error in a full clone.
4703
    let c2 = a.store().get_change(&h1).unwrap();
4704
    let blob = c2
4705
        .edits
4706
        .iter()
4707
        .find_map(|e| match e {
4708
            Edit::Replace { new: Some(b), .. } => Some(*b),
4709
            _ => None,
4710
        })
4711
        .expect("the binary file is a blob");
4712
    let bp = a.store().path_for(&blob);
4713
    let blob_bytes = fs::read(&bp).unwrap();
4714
    fs::remove_file(&bp).unwrap();
4715
    let rep = a.fsck().unwrap();
4716
    assert!(
4717
        rep.problems
4718
            .iter()
4719
            .any(|p| p.object == Some(blob) && p.what.contains("blob missing")),
4720
        "{rep:?}"
4721
    );
4722
    fs::write(&bp, &blob_bytes).unwrap();
4723
4724
    // A broken op log head is reported, not a crash.
4725
    let head = root.join("a/.oxy/ops/head");
4726
    let saved = fs::read(&head).unwrap();
4727
    fs::write(&head, b"not a hash").unwrap();
4728
    let rep = a.fsck().unwrap();
4729
    assert!(
4730
        rep.problems.iter().any(|p| p.what.contains("ops/head")),
4731
        "{rep:?}"
4732
    );
4733
    fs::write(&head, saved).unwrap();
4734
    assert_eq!(a.fsck().unwrap().problems, vec![]);
4735
}
4736
4737
/// Copy a directory tree (for restoring a pristine repository).
4738
fn copy_tree(from: &Path, to: &Path) {
4739
    fs::create_dir_all(to).unwrap();
4740
    for e in fs::read_dir(from).unwrap() {
4741
        let e = e.unwrap();
4742
        let target = to.join(e.file_name());
4743
        if e.file_type().unwrap().is_dir() {
4744
            copy_tree(&e.path(), &target);
4745
        } else {
4746
            fs::copy(e.path(), &target).unwrap();
4747
        }
4748
    }
4749
}
4750
4751
/// Spec §13.6: stop `commit` and `push` at every durable step, as a crash
4752
/// would, and check that both repositories still open, pass `fsck`, and
4753
/// accept the same operation again.
4754
#[test]
4755
fn crash_at_every_step_of_commit_and_push_leaves_sound_repositories() {
4756
    // Files on disk are what this tests: tampering with them, and the
4757
    // directory store's crash points.
4758
    if std::env::var_os("OXY_STORE_BACKEND").is_some() {
4759
        return;
4760
    }
4761
    use crate::durable::failpoint;
4762
    hermetic();
4763
    let dir = tempfile::tempdir().unwrap();
4764
    let pristine = dir.path().join("pristine");
4765
    let origin_path = pristine.join("origin");
4766
    Repo::init(&origin_path).unwrap();
4767
    let mut a = Repo::clone(&origin_path.to_string_lossy(), &pristine.join("a"))
4768
        .unwrap()
4769
        .with_home(dir.path().join("home"));
4770
    a.create_identity("Ada", "[email protected]", IdentityScope::Repo)
4771
        .unwrap();
4772
    write(&pristine.join("a"), "f.txt", b"one\n");
4773
    a.commit("first", &[]).unwrap();
4774
    assert!(a.push("origin", false).unwrap()[0].ok);
4775
    drop(a);
4776
4777
    type Op = fn(&Repo) -> Result<()>;
4778
    let edit_and_commit: Op = |r| {
4779
        write(r.root(), "f.txt", b"one\ntwo\n");
4780
        write(r.root(), "big.bin", &vec![7u8; 300_000]);
4781
        r.commit("second", &[]).map(|_| ())
4782
    };
4783
    let push: Op = |r| {
4784
        let res = r.push("origin", false)?;
4785
        if res.iter().all(|x| x.ok) {
4786
            Ok(())
4787
        } else {
4788
            Err(RepoError::Msg(format!("{res:?}")))
4789
        }
4790
    };
4791
4792
    for (name, prepare, op) in [
4793
        ("commit", None, edit_and_commit),
4794
        ("push", Some(edit_and_commit), push),
4795
    ] {
4796
        let mut steps = 0;
4797
        for n in 1.. {
4798
            let run = dir.path().join(format!("{name}-{n}"));
4799
            copy_tree(&pristine, &run);
4800
            // Clones record their remote by path; point it at this copy.
4801
            let open = |p: &Path| {
4802
                let mut r = Repo::open(p).unwrap().with_home(dir.path().join("home"));
4803
                r.config
4804
                    .set("remote.origin.url", &run.join("origin").to_string_lossy())
4805
                    .unwrap();
4806
                r.save_config().unwrap();
4807
                r
4808
            };
4809
            let a = open(&run.join("a"));
4810
            if let Some(prep) = prepare {
4811
                prep(&a).unwrap();
4812
            }
4813
            failpoint::crash_after(n);
4814
            let outcome = op(&a);
4815
            let crashed = failpoint::disarm();
4816
            drop(a);
4817
            if !crashed {
4818
                outcome.unwrap_or_else(|e| panic!("{name} failed without a crash: {e}"));
4819
                steps = n - 1;
4820
                break;
4821
            }
4822
            assert!(
4823
                outcome.is_err(),
4824
                "{name}: a crash at step {n} was swallowed"
4825
            );
4826
            for repo in ["a", "origin"] {
4827
                let r = Repo::open(&run.join(repo)).unwrap_or_else(|e| {
4828
                    panic!("{name} crash at step {n}: {repo} no longer opens: {e}")
4829
                });
4830
                let rep = r.fsck().unwrap();
4831
                assert_eq!(
4832
                    rep.errors(),
4833
                    0,
4834
                    "{name} crash at step {n}: {repo} fails fsck: {:?}",
4835
                    rep.problems
4836
                );
4837
            }
4838
            // The interrupted operation can simply be run again.
4839
            let a = open(&run.join("a"));
4840
            // A crash after the commit point leaves the commit done.
4841
            let landed = a
4842
                .bookmark_heads()
4843
                .unwrap()
4844
                .iter()
4845
                .any(|h| a.store().get_change(h).unwrap().message == "second");
4846
            let again = match (name, landed) {
4847
                ("commit", true) => Ok(()),
4848
                ("commit", false) => a.commit("second", &[]).map(|_| ()),
4849
                _ => op(&a),
4850
            };
4851
            again.unwrap_or_else(|e| panic!("{name} crash at step {n}: retry failed: {e}"));
4852
            assert_eq!(a.fsck().unwrap().errors(), 0);
4853
            fs::remove_dir_all(&run).unwrap();
4854
        }
4855
        assert!(steps >= 3, "{name} has only {steps} durable steps?");
4856
    }
4857
}
4858
4859
/// Spec §12.1: commands in two workspaces of one repository, and pushes,
4860
/// running at the same time lose nothing: every commit ends up on the
4861
/// bookmark, locally and on the remote, and the repository passes fsck.
4862
#[test]
4863
fn concurrent_commits_in_two_workspaces_lose_nothing() {
4864
    hermetic();
4865
    let dir = tempfile::tempdir().unwrap();
4866
    let root = dir.path();
4867
    let origin = root.join("origin");
4868
    Repo::init_bare_unbound(&origin).unwrap();
4869
    let main = root.join("main");
4870
    let mut repo = Repo::init(&main).unwrap();
4871
    repo.config
4872
        .set("remote.origin.url", &origin.to_string_lossy())
4873
        .unwrap();
4874
    repo.save_config().unwrap();
4875
    write(&main, "seed.txt", b"seed\n");
4876
    repo.commit("seed", &[]).unwrap();
4877
    let second = root.join("second");
4878
    repo.workspace_add(&second, None).unwrap();
4879
    drop(repo);
4880
4881
    const EACH: usize = 15;
4882
    std::thread::scope(|s| {
4883
        for (tag, dir, push) in [("a", main.clone(), true), ("b", second.clone(), false)] {
4884
            s.spawn(move || {
4885
                let r = Repo::open(&dir).unwrap();
4886
                for i in 0..EACH {
4887
                    write(
4888
                        &dir,
4889
                        &format!("{tag}-{i}.txt"),
4890
                        format!("{tag} {i}\n").as_bytes(),
4891
                    );
4892
                    r.commit(&format!("{tag} {i}"), &[]).unwrap();
4893
                    if push && i % 5 == 4 {
4894
                        // A push may be refused while the other workspace moves the bookmark; nothing may be lost either way.
4895
                        let _ = r.push("origin", false);
4896
                    }
4897
                }
4898
            });
4899
        }
4900
    });
4901
4902
    let repo = Repo::open(&main).unwrap();
4903
    let heads = repo.bookmark_heads().unwrap();
4904
    let state = repo.load_state(&heads).unwrap();
4905
    let messages: BTreeSet<String> = state.changes().map(|(_, m)| m.message.clone()).collect();
4906
    for tag in ["a", "b"] {
4907
        for i in 0..EACH {
4908
            assert!(
4909
                messages.contains(&format!("{tag} {i}")),
4910
                "lost commit {tag} {i}; have {messages:?}"
4911
            );
4912
        }
4913
    }
4914
    let rep = repo.fsck().unwrap();
4915
    assert_eq!(rep.errors(), 0, "{:?}", rep.problems);
4916
    assert!(repo.push("origin", false).unwrap().iter().all(|r| r.ok));
4917
    let hosted = Repo::open(&origin).unwrap();
4918
    let hosted_heads = hosted.bookmark_heads().unwrap();
4919
    assert_eq!(
4920
        hosted.load_state(&hosted_heads).unwrap().len(),
4921
        state.len(),
4922
        "the remote has every commit"
4923
    );
4924
}
4925
4926
/// Two operations recorded from the same parent (what two processes do
4927
/// when they race) are merged: both bookmarks' heads survive, and a
4928
/// change made on one side only is kept.
4929
#[test]
4930
fn operations_from_the_same_parent_are_merged() {
4931
    hermetic();
4932
    let dir = tempfile::tempdir().unwrap();
4933
    let root = dir.path();
4934
    let repo = Repo::init(root).unwrap();
4935
    write(root, "a.txt", b"a\n");
4936
    let a = repo.commit("a", &[]).unwrap();
4937
    write(root, "b.txt", b"b\n");
4938
    let b = repo.commit("b", &[]).unwrap();
4939
    let (x, op) = repo.head_op().unwrap();
4940
    let state = |heads: Vec<ChangeHash>| repo.store().put_state(&StateObject::new(heads)).unwrap();
4941
4942
    // Side one moves main to just `a` and adds a bookmark; side two moves main to just `b`.
4943
    let mut one = op.view.clone();
4944
    one.bookmarks.insert("main".into(), state(vec![a]));
4945
    one.bookmarks.insert("topic".into(), state(vec![a]));
4946
    let mut two = op.view.clone();
4947
    two.bookmarks.insert("main".into(), state(vec![b]));
4948
    repo.record_op(&[x], "one", one).unwrap();
4949
    let merged = repo.record_op(&[x], "two", two).unwrap();
4950
4951
    let (head, op) = repo.head_op().unwrap();
4952
    assert_eq!(head, merged);
4953
    assert_eq!(op.parents.len(), 2, "a merge of the two operations");
4954
    assert!(op.command.contains("merged with a concurrent operation"));
4955
    let mut main = repo
4956
        .store()
4957
        .get_state(&op.view.bookmarks["main"])
4958
        .unwrap()
4959
        .heads;
4960
    main.sort();
4961
    let mut want = vec![a, b];
4962
    want.sort();
4963
    assert_eq!(main, want, "both sides' heads are kept");
4964
    assert!(
4965
        op.view.bookmarks.contains_key("topic"),
4966
        "a one-sided change survives"
4967
    );
4968
    assert_eq!(repo.fsck().unwrap().errors(), 0);
4969
}
4970
4971
#[test]
4972
fn failed_requests_come_with_a_next_step() {
4973
    use crate::protocol::hint_for;
4974
    assert!(hint_for("https://h/x/oxy/v1/push: HTTP 401: bad token")
4975
        .unwrap()
4976
        .contains("token"));
4977
    assert!(hint_for("…: HTTP 403: forbidden")
4978
        .unwrap()
4979
        .contains("repo:write"));
4980
    assert!(hint_for("…: HTTP 404: no such repository")
4981
        .unwrap()
4982
        .contains("owner and repository name"));
4983
    assert!(hint_for("invalid peer certificate: UnknownIssuer")
4984
        .unwrap()
4985
        .contains("oxyhub-ca.pem"));
4986
    assert!(hint_for("Connect error: Connection refused (os error 111)")
4987
        .unwrap()
4988
        .contains("running"));
4989
    assert!(hint_for("Dns Failed: failed to lookup address information")
4990
        .unwrap()
4991
        .contains("resolve"));
4992
    assert_eq!(hint_for("something else entirely"), None);
4993
}
4994
4995
#[test]
4996
fn doctor_names_problems_and_what_to_do() {
4997
    hermetic();
4998
    let dir = tempfile::tempdir().unwrap();
4999
    let root = dir.path();
5000
    let origin = root.join("origin");
5001
    Repo::init_bare_unbound(&origin).unwrap();
5002
    let mut repo = Repo::init(&root.join("r"))
5003
        .unwrap()
5004
        .with_home(root.join("home"));
5005
    let find = |r: &DoctorReport, area: &str, h: Health| {
5006
        r.checks
5007
            .iter()
5008
            .find(|c| c.area == area && c.health == h)
5009
            .cloned()
5010
    };
5011
5012
    let r = repo.doctor(true);
5013
    assert!(find(&r, "identity", Health::Warn)
5014
        .unwrap()
5015
        .hint
5016
        .unwrap()
5017
        .contains("oxy identity create"));
5018
    assert!(find(&r, "repository", Health::Ok).is_some());
5019
5020
    repo.create_identity("Ada", "[email protected]", IdentityScope::Repo)
5021
        .unwrap();
5022
    repo.config.set("author.name", "Ada").unwrap();
5023
    repo.config.set("author.email", "[email protected]").unwrap();
5024
    repo.config
5025
        .set("remote.origin.url", &origin.to_string_lossy())
5026
        .unwrap();
5027
    repo.config
5028
        .set("remote.down.url", "http://127.0.0.1:9/a/b")
5029
        .unwrap();
5030
    repo.config.set("remote.down.token", "t").unwrap();
5031
    repo.config
5032
        .set("remote.badca.url", "https://example.invalid/a/b")
5033
        .unwrap();
5034
    repo.config
5035
        .set(
5036
            "remote.badca.ca",
5037
            &root.join("missing.pem").to_string_lossy(),
5038
        )
5039
        .unwrap();
5040
    repo.save_config().unwrap();
5041
5042
    let r = repo.doctor(true);
5043
    assert!(find(&r, "identity", Health::Ok).is_some(), "{r:?}");
5044
    assert!(find(&r, "author", Health::Ok).is_some(), "{r:?}");
5045
    assert!(find(&r, "remote origin", Health::Ok)
5046
        .unwrap()
5047
        .message
5048
        .contains("first push binds it"));
5049
    let down = find(&r, "remote down", Health::Fail).unwrap();
5050
    assert!(
5051
        down.hint.as_deref().unwrap_or("").contains("running"),
5052
        "{down:?}"
5053
    );
5054
    let badca = find(&r, "remote badca", Health::Fail).unwrap();
5055
    assert!(
5056
        badca.hint.unwrap().contains("remote.badca.ca"),
5057
        "the remote's own name is in the hint"
5058
    );
5059
    assert_eq!(r.worst(), Health::Fail);
5060
5061
    // Offline, nothing is contacted.
5062
    let r = repo.doctor(false);
5063
    assert!(find(&r, "remote down", Health::Fail).is_none());
5064
    assert!(find(&r, "remote down", Health::Ok)
5065
        .unwrap()
5066
        .message
5067
        .contains("not contacted"));
5068
}
5069
5070
/// Spec §8.1: deleting a line depends on whoever inserted the lines right
5071
/// after it. Inserting after `b` and then deleting `b`, one commit after
5072
/// the other, must not leave a delete/insert conflict.
5073
#[test]
5074
fn deleting_a_line_after_an_insertion_below_it_is_not_a_conflict() {
5075
    hermetic();
5076
    let dir = tempfile::tempdir().unwrap();
5077
    let root = dir.path();
5078
    let repo = Repo::init(root).unwrap();
5079
    write(root, "f", b"a\nb\nc\n");
5080
    repo.commit("base", &[]).unwrap();
5081
    write(root, "f", b"a\nb\nx\nc\n");
5082
    let insert = repo.commit("insert x after b", &[]).unwrap();
5083
    write(root, "f", b"a\nx\nc\n");
5084
    let delete = repo.commit("delete b", &[]).unwrap();
5085
    assert!(
5086
        repo.store()
5087
            .get_change(&delete)
5088
            .unwrap()
5089
            .deps
5090
            .contains(&insert),
5091
        "the deletion depends on the insertion below the deleted line"
5092
    );
5093
    let heads = repo.bookmark_heads().unwrap();
5094
    assert_eq!(heads, vec![delete]);
5095
    let snap = repo.load_state(&heads).unwrap().materialize();
5096
    assert!(!snap.is_conflicted());
5097
    assert!(
5098
        matches!(&snap.files["f"].content, FileContent::Text { bytes, .. } if bytes == b"a\nx\nc\n")
5099
    );
5100
}
5101
5102
/// Spec §9.3: a binary file reverted to an earlier blob keeps it, and each
5103
/// replacement depends on the change that set the blob it replaces.
5104
#[test]
5105
fn a_binary_file_reverted_to_an_earlier_blob_keeps_it() {
5106
    hermetic();
5107
    let dir = tempfile::tempdir().unwrap();
5108
    let root = dir.path();
5109
    let repo = Repo::init(root).unwrap();
5110
    write(root, "bin", b"\0A");
5111
    let v1 = repo.commit("v1", &[]).unwrap();
5112
    write(root, "bin", b"\0B");
5113
    let v2 = repo.commit("v2", &[]).unwrap();
5114
    assert!(repo.store().get_change(&v2).unwrap().deps.contains(&v1));
5115
    write(root, "bin", b"\0A");
5116
    let v3 = repo.commit("back to A", &[]).unwrap();
5117
    assert!(repo.store().get_change(&v3).unwrap().deps.contains(&v2));
5118
    assert_eq!(repo.bookmark_heads().unwrap(), vec![v3]);
5119
    let state = repo.load_state(&[v3]).unwrap();
5120
    let snap = state.materialize();
5121
    let FileContent::Opaque { blobs } = &snap.files["bin"].content else {
5122
        panic!("opaque")
5123
    };
5124
    assert_eq!(blobs.len(), 1, "one live blob, not none and not two");
5125
    assert_eq!(repo.read_blob(&blobs[0]).unwrap(), b"\0A");
5126
}
5127
5128
/// Spec §23: a binary file changed on two branches and merged in Git to
5129
/// one side's version comes back as that version at the merge, and the
5130
/// import verifies commit by commit.
5131
#[test]
5132
fn git_import_resolves_a_binary_merged_in_git_and_verifies() {
5133
    hermetic();
5134
    if std::process::Command::new("git")
5135
        .arg("--version")
5136
        .output()
5137
        .is_err()
5138
    {
5139
        eprintln!("git not installed; skipping");
5140
        return;
5141
    }
5142
    let dir = tempfile::tempdir().unwrap();
5143
    let root = dir.path();
5144
    let g = root.join("src.git");
5145
    fs::create_dir_all(&g).unwrap();
5146
    let git = |args: &[&str]| -> String {
5147
        let out = std::process::Command::new("git")
5148
            .arg("-C")
5149
            .arg(&g)
5150
            .args([
5151
                "-c",
5152
                "user.name=Grace",
5153
                "-c",
5154
                "[email protected]",
5155
                "-c",
5156
                "commit.gpgsign=false",
5157
            ])
5158
            .args(args)
5159
            .output()
5160
            .unwrap();
5161
        assert!(
5162
            out.status.success(),
5163
            "git {args:?}: {}",
5164
            String::from_utf8_lossy(&out.stderr)
5165
        );
5166
        String::from_utf8_lossy(&out.stdout).trim().to_string()
5167
    };
5168
    git(&["init", "-q", "-b", "main"]);
5169
    write(&g, "logo.bin", b"\0base");
5170
    write(&g, "notes.txt", b"a\nb\nc\n");
5171
    git(&["add", "."]);
5172
    git(&["commit", "-qm", "base"]);
5173
    git(&["checkout", "-qb", "side"]);
5174
    write(&g, "logo.bin", b"\0side");
5175
    write(&g, "notes.txt", b"a\nb\nx\nc\n");
5176
    git(&["commit", "-qam", "side"]);
5177
    git(&["checkout", "-q", "main"]);
5178
    write(&g, "logo.bin", b"\0main");
5179
    git(&["commit", "-qam", "main"]);
5180
    // Git cannot merge the binary; the merge takes main's and keeps side's text.
5181
    let _ = std::process::Command::new("git")
5182
        .arg("-C")
5183
        .arg(&g)
5184
        .args([
5185
            "-c",
5186
            "user.name=G",
5187
            "-c",
5188
            "user.email=g@e",
5189
            "merge",
5190
            "-q",
5191
            "side",
5192
        ])
5193
        .output();
5194
    write(&g, "logo.bin", b"\0main");
5195
    git(&["add", "."]);
5196
    git(&["commit", "-qm", "merge side"]);
5197
    // Then a revert of the binary to its first version.
5198
    write(&g, "logo.bin", b"\0base");
5199
    git(&["commit", "-qam", "back to base"]);
5200
5201
    let repo = Repo::init(&root.join("o")).unwrap();
5202
    let rep = repo.import_git(&g, "main").unwrap();
5203
    assert_eq!(rep.merges, 1);
5204
    let v = repo.verify_git_import(&g, "main").unwrap();
5205
    assert!(v.mismatches.is_empty(), "{:?}", v.mismatches);
5206
    assert_eq!(v.commits, 5);
5207
    let snap = repo
5208
        .load_state(&repo.bookmark_heads().unwrap())
5209
        .unwrap()
5210
        .materialize();
5211
    assert!(!snap.is_conflicted());
5212
    let FileContent::Opaque { blobs } = &snap.files["logo.bin"].content else {
5213
        panic!("opaque")
5214
    };
5215
    assert_eq!(repo.read_blob(&blobs[0]).unwrap(), b"\0base");
5216
}
5217
5218
/// Spec §7.7 on a file system without executable bits or symlinks: the
5219
/// recorded bit is kept, and a symlink checked out as a plain file holding
5220
/// its target is still that symlink.
5221
#[cfg(unix)]
5222
#[test]
5223
fn windows_file_systems_keep_exec_bits_and_symlinks() {
5224
    use crate::portable::Platform;
5225
    use std::os::unix::fs::PermissionsExt;
5226
    hermetic();
5227
    let dir = tempfile::tempdir().unwrap();
5228
    let root = dir.path();
5229
    let repo = Repo::init(root).unwrap();
5230
    write(root, "run.sh", b"#!/bin/sh\n");
5231
    fs::set_permissions(root.join("run.sh"), fs::Permissions::from_mode(0o755)).unwrap();
5232
    std::os::unix::fs::symlink("run.sh", root.join("link")).unwrap();
5233
    repo.commit("script and link", &[]).unwrap();
5234
    drop(repo);
5235
5236
    // What checking out on Windows leaves: no exec bit, the link as a file.
5237
    fs::set_permissions(root.join("run.sh"), fs::Permissions::from_mode(0o644)).unwrap();
5238
    fs::remove_file(root.join("link")).unwrap();
5239
    write(root, "link", b"run.sh");
5240
    let win = Repo::open(root).unwrap().with_platform(Platform::windows());
5241
    let s = win.snapshot("oxy status").unwrap();
5242
    assert!(
5243
        s.statuses.is_empty(),
5244
        "nothing changed on Windows: {:?}",
5245
        statuses(&s)
5246
    );
5247
    // Editing the file is a content change, not a mode change; retargeting the link keeps it a link.
5248
    write(root, "run.sh", b"#!/bin/sh\necho hi\n");
5249
    write(root, "link", b"other");
5250
    let h = win.commit("edit on Windows", &[]).unwrap();
5251
    let snap = win.load_state(&[h]).unwrap().materialize();
5252
    assert!(snap.files["run.sh"].mode.exec, "the exec bit survives");
5253
    assert_eq!(snap.files["link"].kind, NodeKind::Symlink);
5254
    // The same working copy read as Linux sees the lost bit and the plain file.
5255
    let linux = Repo::open(root).unwrap();
5256
    assert!(!linux.snapshot("oxy status").unwrap().statuses.is_empty());
5257
}
5258
5259
/// Paths that collide on case-insensitive or Windows file systems are
5260
/// named at checkout there, and by doctor everywhere.
5261
#[test]
5262
fn paths_other_platforms_cannot_hold_are_reported() {
5263
    use crate::portable::Platform;
5264
    hermetic();
5265
    let dir = tempfile::tempdir().unwrap();
5266
    let root = dir.path();
5267
    let repo = Repo::init(root).unwrap();
5268
    write(root, "README.md", b"a\n");
5269
    write(root, "readme.md", b"b\n");
5270
    write(root, "src/aux.c", b"int x;\n");
5271
    let h = repo.commit("unportable", &[]).unwrap();
5272
    let r = repo.doctor(false);
5273
    let port = r.checks.iter().find(|c| c.area == "portability").unwrap();
5274
    assert_eq!(port.health, Health::Warn);
5275
    assert!(
5276
        port.message.contains("differ only in case") && port.message.contains("aux.c"),
5277
        "{}",
5278
        port.message
5279
    );
5280
    let mac = Repo::open(root).unwrap().with_platform(Platform::macos());
5281
    let rep = mac.checkout(&[h], true, "oxy checkout").unwrap();
5282
    assert!(
5283
        rep.notes
5284
            .iter()
5285
            .any(|n| n.contains("README.md and readme.md")),
5286
        "{:?}",
5287
        rep.notes
5288
    );
5289
    assert!(
5290
        !rep.notes.iter().any(|n| n.contains("aux.c")),
5291
        "macOS allows aux.c"
5292
    );
5293
}
5294
5295
#[test]
5296
fn history_and_blame_of_a_loaded_state_match_the_full_walk() {
5297
    hermetic();
5298
    let dir = tempfile::tempdir().unwrap();
5299
    let repo = Repo::init(dir.path()).unwrap();
5300
    write(dir.path(), "a.txt", b"one\n");
5301
    write(dir.path(), "other.txt", b"x\n");
5302
    write(dir.path(), "bin.dat", &[0u8, 1, 2, 0, 255]);
5303
    repo.snapshot("t").unwrap();
5304
    let c1 = repo.commit("first", &[]).unwrap();
5305
    write(dir.path(), "other.txt", b"y\n");
5306
    repo.snapshot("t").unwrap();
5307
    repo.commit("other only", &[]).unwrap();
5308
    write(dir.path(), "a.txt", b"one\ntwo\n");
5309
    repo.snapshot("t").unwrap();
5310
    let c3 = repo.commit("second line", &[]).unwrap();
5311
    write(dir.path(), "other.txt", b"z\n");
5312
    repo.snapshot("t").unwrap();
5313
    repo.commit("other again", &[]).unwrap();
5314
5315
    let heads = repo.bookmark_heads().unwrap();
5316
    let state = repo.load_state(&heads).unwrap();
5317
    let full: Vec<ChangeHash> = repo
5318
        .log_for_path_in("a.txt", &heads)
5319
        .unwrap()
5320
        .iter()
5321
        .map(|e| e.hash)
5322
        .collect();
5323
    assert_eq!(
5324
        full,
5325
        vec![c3, c1],
5326
        "newest first, only changes touching the path"
5327
    );
5328
    let newest: Vec<ChangeHash> = repo
5329
        .log_for_path_of(&state, "a.txt", Some(1))
5330
        .unwrap()
5331
        .iter()
5332
        .map(|e| e.hash)
5333
        .collect();
5334
    assert_eq!(newest, vec![c3], "stops at the first");
5335
    assert_eq!(
5336
        repo.log_for_path_of(&state, "a.txt", None).unwrap().len(),
5337
        2
5338
    );
5339
    assert!(repo
5340
        .log_for_path_of(&state, "missing.txt", Some(1))
5341
        .is_err());
5342
    assert_eq!(
5343
        repo.log_state(&heads).unwrap().len(),
5344
        repo.log_of(&state).len()
5345
    );
5346
5347
    let tree = state.tree().view();
5348
    let via_state = repo.blame_of(&state, &tree, "a.txt").unwrap();
5349
    let via_heads = repo.blame_in("a.txt", &heads).unwrap();
5350
    assert_eq!(
5351
        via_state
5352
            .iter()
5353
            .map(|l| (l.hash, l.text.clone()))
5354
            .collect::<Vec<_>>(),
5355
        via_heads
5356
            .iter()
5357
            .map(|l| (l.hash, l.text.clone()))
5358
            .collect::<Vec<_>>()
5359
    );
5360
    assert_eq!(
5361
        via_state.iter().map(|l| l.hash).collect::<Vec<_>>(),
5362
        vec![c1, c3]
5363
    );
5364
    assert!(repo.blame_of(&state, &tree, "missing.txt").is_err());
5365
}
5366
5367
/// A text file whose stat matches the manifest and whose recorded hash is
5368
/// the base's content is taken from the base without reading it; anything
5369
/// else is read, so no edit is missed (spec §12.3).
5370
#[cfg(unix)]
5371
#[test]
5372
fn stat_cache_takes_unchanged_text_from_the_base_and_misses_no_edit() {
5373
    use std::os::unix::fs::PermissionsExt;
5374
    hermetic();
5375
    let dir = tempfile::tempdir().unwrap();
5376
    let root = dir.path();
5377
    let repo = Repo::init(root).unwrap().with_home(root.join("home"));
5378
    write(root, "a.txt", b"one\ntwo\n");
5379
    write(root, "b.txt", b"bee\n");
5380
    repo.commit("base", &[]).unwrap();
5381
    let age = |p: &str| {
5382
        let old = std::time::SystemTime::now() - std::time::Duration::from_secs(30);
5383
        fs::File::options()
5384
            .write(true)
5385
            .open(root.join(p))
5386
            .unwrap()
5387
            .set_modified(old)
5388
            .unwrap();
5389
    };
5390
    age("a.txt");
5391
    age("b.txt");
5392
    assert!(
5393
        !repo.snapshot("status").unwrap().changed,
5394
        "records the aged stat"
5395
    );
5396
5397
    // Clean and equal to the base: not read at all.
5398
    fs::set_permissions(root.join("a.txt"), fs::Permissions::from_mode(0o000)).unwrap();
5399
    let snap = repo.snapshot("status").unwrap();
5400
    assert!(
5401
        !snap.changed && snap.statuses.is_empty(),
5402
        "{:?}",
5403
        snap.statuses
5404
    );
5405
    fs::set_permissions(root.join("a.txt"), fs::Permissions::from_mode(0o644)).unwrap();
5406
5407
    // An uncommitted edit that is older than the manifest: stat-clean, but
5408
    // its hash is not the base's, so it is read and stays visible.
5409
    write(root, "b.txt", b"bee edited\n");
5410
    age("b.txt");
5411
    let first = repo.snapshot("status").unwrap();
5412
    assert_eq!(
5413
        statuses(&first),
5414
        vec![("b.txt".to_string(), ChangeStatus::Modified)]
5415
    );
5416
    let again = repo.snapshot("status").unwrap();
5417
    assert_eq!(
5418
        statuses(&again),
5419
        vec![("b.txt".to_string(), ChangeStatus::Modified)],
5420
        "still seen once stat-clean"
5421
    );
5422
    assert!(!again.changed, "and the working copy hashes the same");
5423
    fs::set_permissions(root.join("b.txt"), fs::Permissions::from_mode(0o000)).unwrap();
5424
    assert!(
5425
        repo.snapshot("status").is_err(),
5426
        "an edited file must be read, never taken from the base"
5427
    );
5428
    fs::set_permissions(root.join("b.txt"), fs::Permissions::from_mode(0o644)).unwrap();
5429
5430
    // A same-size edit made just now is racy and read.
5431
    write(root, "a.txt", b"one\nTWO\n");
5432
    assert_eq!(
5433
        statuses(&repo.snapshot("status").unwrap()),
5434
        vec![
5435
            ("a.txt".to_string(), ChangeStatus::Modified),
5436
            ("b.txt".to_string(), ChangeStatus::Modified)
5437
        ]
5438
    );
5439
    // Committing makes the edits the base: both are clean and served from it again.
5440
    repo.commit("edits", &[]).unwrap();
5441
    age("a.txt");
5442
    age("b.txt");
5443
    assert!(repo.snapshot("status").unwrap().statuses.is_empty());
5444
    fs::set_permissions(root.join("a.txt"), fs::Permissions::from_mode(0o000)).unwrap();
5445
    fs::set_permissions(root.join("b.txt"), fs::Permissions::from_mode(0o000)).unwrap();
5446
    let snap = repo.snapshot("status").unwrap();
5447
    assert!(!snap.changed && snap.statuses.is_empty());
5448
    fs::set_permissions(root.join("a.txt"), fs::Permissions::from_mode(0o644)).unwrap();
5449
    fs::set_permissions(root.join("b.txt"), fs::Permissions::from_mode(0o644)).unwrap();
5450
}
5451
5452
/// Version 2 checkpoints (spec §11): a large file's graph is a blob of its
5453
/// own, kept by gc, checked by fsck, shared by the next checkpoint when the
5454
/// file is unchanged, and loading through the checkpoint equals a full load.
5455
#[test]
5456
fn checkpoints_keep_large_graphs_as_blobs_of_their_own() {
5457
    hermetic();
5458
    let dir = tempfile::tempdir().unwrap();
5459
    let root = dir.path();
5460
    let repo = Repo::init(root).unwrap().with_home(root.join("home"));
5461
    let long: String = (0..300)
5462
        .map(|i| format!("line {i} of a long file\n"))
5463
        .collect();
5464
    write(root, "long.txt", long.as_bytes());
5465
    write(root, "short.txt", b"short\n");
5466
    repo.commit("base", &[]).unwrap();
5467
    let (r1, _, _) = repo.checkpoint().unwrap();
5468
    let cp1 = crate::objects::Checkpoint::decode(
5469
        &repo.store().get_typed(&r1, ObjectType::Checkpoint).unwrap(),
5470
    )
5471
    .unwrap();
5472
    let graphs1 = repo.checkpoint_graph_blobs(&cp1).unwrap();
5473
    assert_eq!(graphs1.len(), 1, "only the long file's graph is a blob");
5474
5475
    // gc keeps the graph blob; fsck finds the checkpoint sound.
5476
    repo.gc(true).unwrap();
5477
    assert!(repo.store().has(&graphs1[0]));
5478
    let report = repo.fsck().unwrap();
5479
    assert_eq!(report.errors(), 0, "{:?}", report.problems);
5480
5481
    // Loading through the checkpoint equals a full load.
5482
    write(root, "short.txt", b"short, edited\n");
5483
    repo.commit("edit the short file", &[]).unwrap();
5484
    let heads = repo.bookmark_heads().unwrap();
5485
    let fast = repo.load_state(&heads).unwrap();
5486
    let full = repo.load_state_full(&heads).unwrap();
5487
    assert_eq!(fast.checkpoint_payload(), full.checkpoint_payload());
5488
5489
    // The next checkpoint shares the unchanged long file's graph.
5490
    let (r2, _, _) = repo.checkpoint().unwrap();
5491
    let cp2 = crate::objects::Checkpoint::decode(
5492
        &repo.store().get_typed(&r2, ObjectType::Checkpoint).unwrap(),
5493
    )
5494
    .unwrap();
5495
    assert_eq!(repo.checkpoint_graph_blobs(&cp2).unwrap(), graphs1);
5496
5497
    // A shallow clone's bundle carries the graph blob with the checkpoint.
5498
    let bundle = repo.checkpoint_bundle_for(&heads).unwrap();
5499
    assert!(bundle.objects.iter().any(|(t, body)| *t == ObjectType::Blob
5500
        && crate::hash::hash_object(ObjectType::Blob, body) == graphs1[0]));
5501
5502
    // A version 1 checkpoint written by an older oxy still loads.
5503
    let state = repo.load_state_full(&heads).unwrap();
5504
    let old = repo.store_blob(&state.checkpoint_payload()).unwrap();
5505
    let cp_old = crate::objects::Checkpoint {
5506
        heads: cp2.heads.clone(),
5507
        count: cp2.count,
5508
        payload: old,
5509
    };
5510
    let r_old = repo
5511
        .store()
5512
        .put(ObjectType::Checkpoint, &cp_old.encode())
5513
        .unwrap();
5514
    repo.install_checkpoint("main", &r_old).unwrap();
5515
    assert_eq!(
5516
        repo.load_state(&heads).unwrap().checkpoint_payload(),
5517
        full.checkpoint_payload()
5518
    );
5519
    assert_eq!(repo.fsck().unwrap().errors(), 0);
5520
5521
    // A lost graph blob fails the load loudly rather than dropping the
5522
    // file, and fsck reports it (a fresh repository, objects still loose).
5523
    let dir2 = tempfile::tempdir().unwrap();
5524
    let root2 = dir2.path();
5525
    let repo2 = Repo::init(root2).unwrap().with_home(root2.join("home"));
5526
    write(root2, "long.txt", long.as_bytes());
5527
    repo2.commit("base", &[]).unwrap();
5528
    let (r, _, _) = repo2.checkpoint().unwrap();
5529
    let cp = crate::objects::Checkpoint::decode(
5530
        &repo2.store().get_typed(&r, ObjectType::Checkpoint).unwrap(),
5531
    )
5532
    .unwrap();
5533
    let graph = repo2.checkpoint_graph_blobs(&cp).unwrap()[0];
5534
    repo2.store().remove_loose_for_test(&graph).unwrap();
5535
    assert!(repo2.load_state(&repo2.bookmark_heads().unwrap()).is_err());
5536
    assert!(repo2.fsck().unwrap().errors() > 0, "fsck reports it");
5537
}
5538
5539
/// A new repository has not stored the user's identity yet (that happens
5540
/// at the first signed change); looking it up falls back to the key
5541
/// directory, and a file there that does not hash to the key is refused.
5542
#[test]
5543
fn identity_is_found_in_the_key_directory_for_a_new_repository() {
5544
    hermetic();
5545
    let dir = tempfile::tempdir().unwrap();
5546
    let home = dir.path().join("home");
5547
    let mut first = Repo::init(&dir.path().join("a"))
5548
        .unwrap()
5549
        .with_home(home.clone());
5550
    let (key, _) = first
5551
        .create_identity("Ada", "[email protected]", IdentityScope::User)
5552
        .unwrap();
5553
    let fresh = Repo::init(&dir.path().join("b"))
5554
        .unwrap()
5555
        .with_home(home.clone());
5556
    assert!(!fresh.store().has(&key), "nothing stored yet");
5557
    let id = fresh.identity(&key).unwrap();
5558
    assert_eq!((id.name.as_str(), id.hash()), ("Ada", key));
5559
    // A key file that is not this identity is an error, not a wrong answer.
5560
    let keys = fresh.keys_dir.clone();
5561
    let (other, _) = first
5562
        .create_identity("Bob", "[email protected]", IdentityScope::User)
5563
        .unwrap();
5564
    fs::copy(
5565
        keys.join(format!("{}.identity", other.to_hex())),
5566
        keys.join(format!("{}.identity", key.to_hex())),
5567
    )
5568
    .unwrap();
5569
    assert!(fresh
5570
        .identity(&key)
5571
        .unwrap_err()
5572
        .to_string()
5573
        .contains("does not hold identity"));
5574
}
5575
5576
/// Status snapshots (spec §12.3): a text file whose stat matches the
5577
/// manifest, and whose base graph key is the one the manifest recorded it
5578
/// equal to, is neither read nor rendered; any edit, and any change to the
5579
/// file's graph in the base, brings it back.
5580
#[cfg(unix)]
5581
#[test]
5582
fn status_snapshots_skip_files_unchanged_since_the_manifest() {
5583
    use std::os::unix::fs::PermissionsExt;
5584
    hermetic();
5585
    let dir = tempfile::tempdir().unwrap();
5586
    let root = dir.path();
5587
    let repo = Repo::init(root).unwrap().with_home(root.join("home"));
5588
    for (p, c) in [("a.txt", "one\n"), ("b.txt", "bee\n"), ("d/c.txt", "sea\n")] {
5589
        write(root, p, c.as_bytes());
5590
    }
5591
    repo.commit("base", &[]).unwrap();
5592
    let age = |p: &str| {
5593
        let old = std::time::SystemTime::now() - std::time::Duration::from_secs(30);
5594
        fs::File::options()
5595
            .write(true)
5596
            .open(root.join(p))
5597
            .unwrap()
5598
            .set_modified(old)
5599
            .unwrap();
5600
    };
5601
    let lock = |p: &str, mode: u32| {
5602
        fs::set_permissions(root.join(p), fs::Permissions::from_mode(mode)).unwrap()
5603
    };
5604
    for p in ["a.txt", "b.txt", "d/c.txt"] {
5605
        age(p);
5606
    }
5607
    assert!(repo.snapshot("status").unwrap().statuses.is_empty());
5608
    let (_, _, m) = repo.read_manifest().unwrap().unwrap();
5609
    assert!(
5610
        m.entries.values().all(|e| e.graph.is_some()),
5611
        "keys recorded"
5612
    );
5613
5614
    // Unreadable files prove they are not read; the status snapshot does
5615
    // not render them either, and its base lacks their graphs.
5616
    lock("a.txt", 0o000);
5617
    lock("b.txt", 0o000);
5618
    let snap = repo.snapshot_status("status").unwrap();
5619
    assert!(!snap.changed && snap.statuses.is_empty());
5620
    assert_eq!(
5621
        snap.base_snapshot
5622
            .unrendered
5623
            .iter()
5624
            .cloned()
5625
            .collect::<Vec<_>>(),
5626
        vec!["a.txt", "b.txt", "d/c.txt"]
5627
    );
5628
    assert!(!snap.base.is_full());
5629
    assert!(!snap.base_snapshot.is_conflicted());
5630
    // A full snapshot does not read them either, but renders everything.
5631
    let full = repo.snapshot("status").unwrap();
5632
    assert!(full.statuses.is_empty() && full.base.is_full());
5633
    assert!(full.base_snapshot.unrendered.is_empty());
5634
    assert!(matches!(&full.base_snapshot.files["a.txt"].content,
5635
        FileContent::Text { bytes, .. } if bytes == b"one\n"));
5636
5637
    // An edit is seen; the file is rendered, the others still are not.
5638
    write(root, "d/c.txt", b"sea edited\n");
5639
    let snap = repo.snapshot_status("status").unwrap();
5640
    assert_eq!(
5641
        statuses(&snap),
5642
        vec![("d/c.txt".to_string(), ChangeStatus::Modified)]
5643
    );
5644
    assert!(!snap.base_snapshot.unrendered.contains("d/c.txt"));
5645
    // So is a mode change of an unread file.
5646
    lock("b.txt", 0o100);
5647
    assert_eq!(
5648
        statuses(&repo.snapshot_status("status").unwrap()),
5649
        vec![
5650
            ("b.txt".to_string(), ChangeStatus::ModeChanged),
5651
            ("d/c.txt".to_string(), ChangeStatus::Modified)
5652
        ]
5653
    );
5654
    lock("b.txt", 0o000);
5655
5656
    // Committing c.txt changes its graph in the base, not a.txt's: a.txt
5657
    // stays unread, c.txt is read once and then skipped too.
5658
    repo.commit_selection("edit c", &[], &Selection::Paths(vec!["d/c.txt".into()]))
5659
        .unwrap();
5660
    age("d/c.txt");
5661
    let snap = repo.snapshot_status("status").unwrap();
5662
    assert!(snap.statuses.is_empty(), "{:?}", snap.statuses);
5663
    assert!(snap.base_snapshot.unrendered.contains("a.txt"));
5664
    lock("d/c.txt", 0o000);
5665
    let snap = repo.snapshot_status("status").unwrap();
5666
    assert!(snap.statuses.is_empty());
5667
    assert!(snap.base_snapshot.unrendered.contains("d/c.txt"));
5668
    for p in ["a.txt", "b.txt", "d/c.txt"] {
5669
        lock(p, 0o644);
5670
    }
5671
}
5672
5673
/// Attributes decide how a file compares with the base, so a changed
5674
/// `.oxyattributes` makes every text file be compared again.
5675
#[cfg(unix)]
5676
#[test]
5677
fn a_changed_attributes_file_disables_skipping_unchanged_files() {
5678
    hermetic();
5679
    let dir = tempfile::tempdir().unwrap();
5680
    let root = dir.path();
5681
    let repo = Repo::init(root).unwrap().with_home(root.join("home"));
5682
    write(root, "a.txt", b"crlf\r\n");
5683
    repo.commit("base", &[]).unwrap();
5684
    let old = std::time::SystemTime::now() - std::time::Duration::from_secs(30);
5685
    fs::File::options()
5686
        .write(true)
5687
        .open(root.join("a.txt"))
5688
        .unwrap()
5689
        .set_modified(old)
5690
        .unwrap();
5691
    assert!(repo.snapshot_status("status").unwrap().statuses.is_empty());
5692
    assert!(repo
5693
        .snapshot_status("status")
5694
        .unwrap()
5695
        .base_snapshot
5696
        .unrendered
5697
        .contains("a.txt"));
5698
    // With eol=lf, a.txt as stored no longer equals the base.
5699
    write(root, ".oxyattributes", b"*.txt eol=lf\n");
5700
    let snap = repo.snapshot_status("status").unwrap();
5701
    assert_eq!(
5702
        statuses(&snap),
5703
        vec![
5704
            (".oxyattributes".to_string(), ChangeStatus::Added),
5705
            ("a.txt".to_string(), ChangeStatus::Modified)
5706
        ]
5707
    );
5708
}
5709
5710
/// Bookmarks with `/` in their names: pushing records their
5711
/// attestations, and checkpoints are kept for them, beside `feature`
5712
/// itself.
5713
#[test]
5714
fn bookmarks_with_slashes_push_and_checkpoint() {
5715
    hermetic();
5716
    let dir = tempfile::tempdir().unwrap();
5717
    let root = dir.path();
5718
    let origin = Repo::init(&root.join("origin")).unwrap();
5719
    let url = root.join("origin").to_string_lossy().to_string();
5720
    let mut repo = Repo::clone(&url, &root.join("r"))
5721
        .unwrap()
5722
        .with_home(root.join("home"));
5723
    // With an identity, pushes carry reference attestations: the case
5724
    // that failed, since the attestation is a file named after the bookmark.
5725
    repo.create_identity("Ada", "[email protected]", IdentityScope::Repo)
5726
        .unwrap();
5727
    let r = root.join("r");
5728
    write(&r, "a.txt", b"a\n");
5729
    let h_a = repo.commit("a", &[]).unwrap();
5730
    assert!(repo.push("origin", false).unwrap()[0].ok);
5731
    repo.bookmark_create("feature", None).unwrap();
5732
    repo.bookmark_create("feature/x", None).unwrap();
5733
    repo.bookmark_switch("feature/x", false).unwrap();
5734
    write(&r, "b.txt", b"b\n");
5735
    let h_b = repo.commit("b", &[]).unwrap();
5736
    for name in ["feature", "feature/x"] {
5737
        let res = repo.push_bookmark("origin", name, false).unwrap();
5738
        assert!(res[0].ok, "{name}: {res:?}");
5739
    }
5740
    assert_eq!(origin.resolve_heads("feature").unwrap(), vec![h_a]);
5741
    assert_eq!(
5742
        origin.resolve_heads("feature/x").unwrap(),
5743
        repo.resolve_heads("feature/x").unwrap()
5744
    );
5745
    assert!(origin.resolve_heads("feature/x").unwrap().contains(&h_b));
5746
    assert!(origin.latest_ref_attest("feature/x").unwrap().is_some());
5747
    assert!(origin.latest_ref_attest("feature").unwrap().is_some());
5748
5749
    // A checkpoint of feature/x is found again when loading its state.
5750
    let (cp, _, _) = repo.checkpoint().unwrap();
5751
    assert_eq!(repo.latest_checkpoint("feature/x").unwrap().unwrap().0, cp);
5752
    assert!(repo.latest_checkpoint("feature").unwrap().is_none());
5753
    let heads = repo.resolve_heads("feature/x").unwrap();
5754
    assert!(repo.load_state_checkpointed(&heads).unwrap().is_some());
5755
}
5756
5757
/// Deleting a bookmark on a remote (spec §16.4): attested like any update,
5758
/// never the remote's own bookmark, and a bookmark created again later is
5759
/// accepted although the deletion's attestation stays the latest.
5760
#[test]
5761
fn bookmarks_are_deleted_on_a_remote() {
5762
    hermetic();
5763
    let dir = tempfile::tempdir().unwrap();
5764
    let root = dir.path();
5765
    let origin = Repo::init(&root.join("origin")).unwrap();
5766
    let url = root.join("origin").to_string_lossy().to_string();
5767
    let mut repo = Repo::clone(&url, &root.join("r"))
5768
        .unwrap()
5769
        .with_home(root.join("home"));
5770
    repo.create_identity("Ada", "[email protected]", IdentityScope::Repo)
5771
        .unwrap();
5772
    let r = root.join("r");
5773
    write(&r, "a.txt", b"a\n");
5774
    repo.commit("a", &[]).unwrap();
5775
    assert!(repo.push("origin", false).unwrap()[0].ok);
5776
    repo.bookmark_create("feature/x", None).unwrap();
5777
    assert!(repo.push_bookmark("origin", "feature/x", false).unwrap()[0].ok);
5778
    assert!(origin.resolve_heads("feature/x").is_ok());
5779
5780
    let res = repo.push_delete("origin", "feature/x").unwrap();
5781
    assert!(res[0].ok, "{res:?}");
5782
    assert!(!origin.view().unwrap().bookmarks.contains_key("feature/x"));
5783
    let (_, att) = origin.latest_ref_attest("feature/x").unwrap().unwrap();
5784
    assert!(
5785
        matches!(att.attest.body, AttestBody::Ref { new_state, .. } if new_state.is_zero()),
5786
        "the deletion is attested"
5787
    );
5788
    assert!(
5789
        repo.view().unwrap().bookmarks.contains_key("feature/x"),
5790
        "the local bookmark stays"
5791
    );
5792
    assert!(!repo
5793
        .view()
5794
        .unwrap()
5795
        .remotes
5796
        .get("origin")
5797
        .is_some_and(|m| m.contains_key("feature/x")));
5798
5799
    // Pushing it again creates it again, past the deletion's serial.
5800
    let res = repo.push_bookmark("origin", "feature/x", false).unwrap();
5801
    assert!(res[0].ok, "{res:?}");
5802
    assert!(origin.view().unwrap().bookmarks.contains_key("feature/x"));
5803
5804
    // Nothing to delete, and never the remote's own bookmark.
5805
    assert!(repo.push_delete("origin", "nope").is_err());
5806
    let res = repo.push_delete("origin", "main").unwrap();
5807
    assert!(
5808
        !res[0].ok && res[0].reason.contains("default bookmark"),
5809
        "{res:?}"
5810
    );
5811
    assert!(origin.view().unwrap().bookmarks.contains_key("main"));
5812
}
5813
5814
/// `bookmark switch --carry` (spec §10.1): uncommitted work goes along
5815
/// when the target has the same versions of the files it touches, and is
5816
/// refused, untouched, when it has others.
5817
#[test]
5818
fn switching_bookmarks_carries_uncommitted_work() {
5819
    hermetic();
5820
    let dir = tempfile::tempdir().unwrap();
5821
    let root = dir.path();
5822
    let mut repo = Repo::init(root).unwrap().with_home(root.join("home"));
5823
    write(root, "a.txt", b"a\n");
5824
    write(root, "b.txt", b"b\n");
5825
    write(root, "gone.txt", b"gone\n");
5826
    repo.commit("base", &[]).unwrap();
5827
    repo.bookmark_create("feature", None).unwrap();
5828
    // Started on main, belongs on feature: edit, add, remove.
5829
    write(root, "a.txt", b"a\nmore\n");
5830
    write(root, "new.txt", b"new\n");
5831
    fs::remove_file(root.join("gone.txt")).unwrap();
5832
    let (_, carried) = repo.bookmark_switch_carry("feature").unwrap();
5833
    assert_eq!(carried, vec!["a.txt", "gone.txt", "new.txt"]);
5834
    assert_eq!(repo.config.bookmark, "feature");
5835
    assert_eq!(fs::read(root.join("a.txt")).unwrap(), b"a\nmore\n");
5836
    assert_eq!(fs::read(root.join("new.txt")).unwrap(), b"new\n");
5837
    assert!(!root.join("gone.txt").exists());
5838
    let snap = repo.snapshot("status").unwrap();
5839
    assert_eq!(
5840
        statuses(&snap),
5841
        vec![
5842
            ("a.txt".to_string(), ChangeStatus::Modified),
5843
            ("gone.txt".to_string(), ChangeStatus::Removed),
5844
            ("new.txt".to_string(), ChangeStatus::Added)
5845
        ]
5846
    );
5847
    repo.commit("the work", &[]).unwrap();
5848
    assert!(repo.resolve_heads("main").unwrap().len() == 1);
5849
5850
    // main moves b.txt on; work on feature touching b.txt cannot follow.
5851
    repo.bookmark_switch("main", false).unwrap();
5852
    write(root, "b.txt", b"b on main\n");
5853
    repo.commit("b on main", &[]).unwrap();
5854
    repo.bookmark_switch("feature", false).unwrap();
5855
    write(root, "b.txt", b"b edited\n");
5856
    let err = repo.bookmark_switch_carry("main").unwrap_err().to_string();
5857
    assert!(err.contains("b.txt") && err.contains("--discard"), "{err}");
5858
    assert_eq!(repo.config.bookmark, "feature", "nothing happened");
5859
    assert_eq!(fs::read(root.join("b.txt")).unwrap(), b"b edited\n");
5860
}
5861
5862
/// Merging and checking out (feedback 3): a working copy without changes
5863
/// follows a merge whichever state it sat on; a refused checkout names
5864
/// what is in the way; `checkout --carry` takes the work along.
5865
#[test]
5866
fn merges_move_clean_working_copies_and_checkouts_say_what_blocks_them() {
5867
    hermetic();
5868
    let dir = tempfile::tempdir().unwrap();
5869
    let root = dir.path();
5870
    let mut repo = Repo::init(root).unwrap().with_home(root.join("home"));
5871
    write(root, "a.txt", b"a\n");
5872
    let h1 = repo.commit("a", &[]).unwrap();
5873
    write(root, "b.txt", b"b\n");
5874
    repo.commit("b", &[]).unwrap();
5875
    repo.bookmark_create("feature", None).unwrap();
5876
    repo.bookmark_switch("feature", false).unwrap();
5877
    write(root, "c.txt", b"c\n");
5878
    repo.commit("c on feature", &[]).unwrap();
5879
    repo.bookmark_switch("main", false).unwrap();
5880
    // The working copy sits on an older state than main's heads.
5881
    repo.checkout(&[h1], false, "checkout").unwrap();
5882
    assert!(!root.join("b.txt").exists());
5883
    let m = repo.merge("feature").unwrap();
5884
    assert!(m.checked_out, "a clean working copy follows the merge");
5885
    for f in ["a.txt", "b.txt", "c.txt"] {
5886
        assert!(root.join(f).exists(), "{f}");
5887
    }
5888
5889
    // A refusal says which paths are in the way and what to do.
5890
    fs::remove_file(root.join("b.txt")).unwrap();
5891
    write(root, "a.txt", b"a edited\n");
5892
    let err = repo
5893
        .checkout(&[h1], false, "checkout")
5894
        .unwrap_err()
5895
        .to_string();
5896
    assert!(
5897
        err.contains("modified a.txt") && err.contains("removed b.txt") && err.contains("--carry"),
5898
        "{err}"
5899
    );
5900
    // --carry takes them along: h1 has a.txt as the base has it, and no b.txt
5901
    // is carried as absent (h1 has none either, so that is refused).
5902
    let err = repo
5903
        .checkout_carry(&[h1], "the first change", "checkout")
5904
        .unwrap_err()
5905
        .to_string();
5906
    assert!(
5907
        err.contains("b.txt") && err.contains("the first change"),
5908
        "{err}"
5909
    );
5910
    write(root, "b.txt", b"b\n");
5911
    let (_, carried) = repo
5912
        .checkout_carry(&[h1], "the first change", "checkout")
5913
        .unwrap();
5914
    assert_eq!(carried, vec!["a.txt"]);
5915
    assert_eq!(fs::read(root.join("a.txt")).unwrap(), b"a edited\n");
5916
    assert!(!root.join("b.txt").exists(), "h1 has no b.txt");
5917
}
5918
5919
/// Doctor and subrepos before the first commit (feedback 5 and 8): a
5920
/// user identity not stored in a new repository yet is fine while its
5921
/// secret key is there; an added subrepo is listed as not committed yet.
5922
#[test]
5923
fn a_new_repository_is_healthy_before_its_first_commit() {
5924
    hermetic();
5925
    let dir = tempfile::tempdir().unwrap();
5926
    let root = dir.path();
5927
    let home = root.join("home");
5928
    let mut first = Repo::init(&root.join("first"))
5929
        .unwrap()
5930
        .with_home(home.clone());
5931
    let (key, _) = first
5932
        .create_identity("Ada", "[email protected]", IdentityScope::User)
5933
        .unwrap();
5934
    let repo = Repo::init(&root.join("second"))
5935
        .unwrap()
5936
        .with_home(home.clone());
5937
    // Only the secret key: no identity object anywhere this repository sees.
5938
    let keys = repo.keys_dir.clone();
5939
    let _ = fs::remove_file(keys.join(format!("{}.identity", key.to_hex())));
5940
    assert!(keys.join(format!("{}.secret", key.to_hex())).is_file());
5941
    let r = repo.doctor(true);
5942
    let id = r.checks.iter().find(|c| c.area == "identity").unwrap();
5943
    assert_eq!(id.health, Health::Ok, "{}", id.message);
5944
    assert!(id.message.contains("first signed change"), "{}", id.message);
5945
5946
    // A subrepo added and not committed yet is listed, pinned where it is.
5947
    let lib = root.join("lib");
5948
    let l = Repo::init(&lib).unwrap().with_home(home.clone());
5949
    write(&lib, "x.txt", b"x\n");
5950
    l.commit("x", &[]).unwrap();
5951
    let second = root.join("second");
5952
    write(&second, "a.txt", b"a\n");
5953
    repo.submodule_add(&lib.to_string_lossy(), "deps/lib", None)
5954
        .unwrap();
5955
    let subs = repo.subrepos().unwrap();
5956
    assert_eq!(subs.len(), 1);
5957
    assert_eq!(
5958
        (subs[0].path.as_str(), subs[0].committed),
5959
        ("deps/lib", false)
5960
    );
5961
    assert_eq!(subs[0].actual.as_ref(), Some(&subs[0].pin));
5962
    repo.commit("add lib", &[]).unwrap();
5963
    let subs = repo.subrepos().unwrap();
5964
    assert!(subs[0].committed, "committed now");
5965
}
5966
5967
/// Commit, diff, hunks and discard use the partial snapshot: a file
5968
/// unchanged since the manifest is neither read nor rendered, and showing
5969
/// a change renders only what it edits, the same as from a full base.
5970
#[cfg(unix)]
5971
#[test]
5972
fn commits_and_diffs_leave_unchanged_files_alone() {
5973
    use std::os::unix::fs::PermissionsExt;
5974
    hermetic();
5975
    let dir = tempfile::tempdir().unwrap();
5976
    let root = dir.path();
5977
    let repo = Repo::init(root).unwrap().with_home(root.join("home"));
5978
    write(root, "big.txt", b"lots\nof\nlines\n");
5979
    write(root, "a.txt", b"one\ntwo\n");
5980
    repo.commit("base", &[]).unwrap();
5981
    let old = std::time::SystemTime::now() - std::time::Duration::from_secs(30);
5982
    for f in ["big.txt", "a.txt"] {
5983
        fs::File::options()
5984
            .write(true)
5985
            .open(root.join(f))
5986
            .unwrap()
5987
            .set_modified(old)
5988
            .unwrap();
5989
    }
5990
    assert!(repo.snapshot_status("status").unwrap().statuses.is_empty());
5991
    // big.txt cannot be read at all from here on.
5992
    fs::set_permissions(root.join("big.txt"), fs::Permissions::from_mode(0o000)).unwrap();
5993
5994
    write(root, "a.txt", b"one\nTWO\nthree\n");
5995
    let diff = repo.diff_files(None).unwrap();
5996
    assert_eq!(
5997
        diff.iter().map(|f| f.path.as_str()).collect::<Vec<_>>(),
5998
        ["a.txt"]
5999
    );
6000
    let (_, hunks) = repo.hunks().unwrap();
6001
    assert!(!hunks.is_empty() && hunks.iter().all(|h| h.path == "a.txt"));
6002
    let h = repo.commit("edit a", &[]).unwrap();
6003
6004
    // Showing the change needs only a.txt's graph, and renders as a full base does.
6005
    let c = repo.store().get_change(&h).unwrap();
6006
    let full = repo.load_state(&c.deps).unwrap();
6007
    let want = render_change(&c, &full, &full.materialize());
6008
    assert_eq!(repo.describe_change(&h).unwrap(), want);
6009
    let (base, snap) = repo.change_base(&c).unwrap();
6010
    assert!(!base.is_full() && snap.unrendered.contains("big.txt"));
6011
6012
    // Discarding works the same way.
6013
    write(root, "a.txt", b"scratch\n");
6014
    assert_eq!(repo.discard(&["a.txt".into()]).unwrap(), 1);
6015
    assert_eq!(fs::read(root.join("a.txt")).unwrap(), b"one\nTWO\nthree\n");
6016
    fs::set_permissions(root.join("big.txt"), fs::Permissions::from_mode(0o644)).unwrap();
6017
}
6018
6019
/// A replace conflict (spec §9.3) is settled by a change that writes one
6020
/// candidate, or new bytes, at the path when the caller names it; a plain
6021
/// snapshot of a checkout never settles it on its own.
6022
#[test]
6023
fn replace_conflicts_are_settled_when_asked() {
6024
    hermetic();
6025
    let dir = tempfile::tempdir().unwrap();
6026
    let root = dir.path();
6027
    let mut repo = Repo::init(root).unwrap().with_home(root.join("home"));
6028
    let blob = |n: u8| {
6029
        let mut v = vec![0u8; 64];
6030
        v[1] = n;
6031
        v
6032
    };
6033
    write(root, "img.bin", &blob(1));
6034
    repo.commit("add img", &[]).unwrap();
6035
    repo.bookmark_create("other", None).unwrap();
6036
    write(root, "img.bin", &blob(2));
6037
    repo.commit("img two", &[]).unwrap();
6038
    repo.bookmark_switch("other", false).unwrap();
6039
    write(root, "img.bin", &blob(3));
6040
    repo.commit("img three", &[]).unwrap();
6041
    repo.bookmark_switch("main", false).unwrap();
6042
    repo.merge("other").unwrap();
6043
    let heads = repo.bookmark_heads().unwrap();
6044
    let merged = repo.load_state(&heads).unwrap().materialize();
6045
    assert!(
6046
        matches!(&merged.files["img.bin"].content, FileContent::Opaque { blobs } if blobs.len() == 2),
6047
        "a replace conflict"
6048
    );
6049
    // A snapshot of the checkout records nothing.
6050
    assert!(repo
6051
        .snapshot("status")
6052
        .unwrap()
6053
        .statuses
6054
        .iter()
6055
        .all(|s| s.path != "img.bin"));
6056
6057
    // Keeping candidate 3 settles it.
6058
    let author = repo.author();
6059
    let edits = [FileEdit {
6060
        path: "img.bin".into(),
6061
        content: Some(blob(3)),
6062
    }];
6063
    let c = repo
6064
        .build_change(&heads, &edits, "keep three", author)
6065
        .unwrap();
6066
    assert_eq!(c.kind, ChangeKind::Resolution);
6067
    let mut st = repo.load_state(&heads).unwrap();
6068
    for d in &c.deps {
6069
        assert!(st.contains(d));
6070
    }
6071
    assert!(
6072
        heads.iter().all(|h| c.deps.contains(h)),
6073
        "depends on both contributors"
6074
    );
6075
    st.add(c).unwrap();
6076
    let after = st.materialize();
6077
    assert!(!after.is_conflicted());
6078
    assert_eq!(
6079
        after.files["img.bin"].content,
6080
        FileContent::Opaque {
6081
            blobs: vec![Repo::blob_ref(&blob(3))]
6082
        }
6083
    );
6084
6085
    // New bytes settle it too.
6086
    let edits = [FileEdit {
6087
        path: "img.bin".into(),
6088
        content: Some(blob(9)),
6089
    }];
6090
    let c = repo.build_change(&heads, &edits, "new", author).unwrap();
6091
    let mut st = repo.load_state(&heads).unwrap();
6092
    st.add(c).unwrap();
6093
    assert_eq!(
6094
        st.materialize().files["img.bin"].content,
6095
        FileContent::Opaque {
6096
            blobs: vec![Repo::blob_ref(&blob(9))]
6097
        }
6098
    );
6099
}
6100
6101
/// The history of a range of lines (spec §27): the changes that wrote
6102
/// or deleted its atoms, or deleted atoms from between them; edits outside
6103
/// the range and changes the range's lines survived are not in it.
6104
#[test]
6105
fn line_ranges_have_exact_histories() {
6106
    hermetic();
6107
    let dir = tempfile::tempdir().unwrap();
6108
    let root = dir.path();
6109
    let repo = Repo::init(root).unwrap().with_home(root.join("home"));
6110
    write(root, "f.rs", b"use x;\nfn a() {\n  one();\n  two();\n}\n");
6111
    let base = repo.commit("add f", &[]).unwrap();
6112
    write(root, "f.rs", b"use y;\nfn a() {\n  one();\n  two();\n}\n");
6113
    let outside = repo.commit("change the import", &[]).unwrap();
6114
    write(root, "f.rs", b"use y;\nfn a() {\n  ONE();\n  two();\n}\n");
6115
    let inside = repo.commit("edit a line of a", &[]).unwrap();
6116
    write(root, "f.rs", b"use y;\nfn a() {\n  ONE();\n}\n");
6117
    let deleted = repo.commit("delete a line of a", &[]).unwrap();
6118
    write(root, "f.rs", b"use y;\nfn a() {\n  ONE();\n}\nfn b() {}\n");
6119
    let after = repo.commit("add b after a", &[]).unwrap();
6120
    let heads = repo.bookmark_heads().unwrap();
6121
6122
    // Lines 2..4 are `fn a() {`, `ONE();`, `}` now.
6123
    let hist: Vec<ChangeHash> = repo
6124
        .line_history(&heads, "f.rs", 2, 4)
6125
        .unwrap()
6126
        .iter()
6127
        .map(|e| e.hash)
6128
        .collect();
6129
    for (h, what) in [
6130
        (base, "wrote it"),
6131
        (inside, "edited a line"),
6132
        (deleted, "deleted a line from inside"),
6133
    ] {
6134
        assert!(hist.contains(&h), "{what}");
6135
    }
6136
    for (h, what) in [(outside, "an edit above"), (after, "an addition below")] {
6137
        assert!(!hist.contains(&h), "{what}");
6138
    }
6139
    assert_eq!(hist[0], deleted, "newest first");
6140
    // One line: only what touched it.
6141
    let one: Vec<ChangeHash> = repo
6142
        .line_history(&heads, "f.rs", 1, 1)
6143
        .unwrap()
6144
        .iter()
6145
        .map(|e| e.hash)
6146
        .collect();
6147
    assert!(one.contains(&outside) && !one.contains(&inside));
6148
    assert!(repo.line_history(&heads, "f.rs", 3, 9).is_err());
6149
    assert!(repo.line_history(&heads, "f.rs", 0, 1).is_err());
6150
    assert!(repo.line_history(&heads, "nope.rs", 1, 1).is_err());
6151
}
6152
6153
#[test]
6154
fn receipts_are_kept_with_their_state_and_verified() {
6155
    use crate::receipt::{Receipt, SignedReceipt};
6156
    hermetic();
6157
    let dir = tempfile::tempdir().unwrap();
6158
    let root = dir.path();
6159
    let repo = Repo::init(root).unwrap().with_home(root.join("home"));
6160
    write(root, "a.txt", b"1\n");
6161
    repo.commit("A", &[]).unwrap();
6162
    let heads = repo.bookmark_heads().unwrap();
6163
    let state = repo
6164
        .store()
6165
        .put_state(&StateObject::new(heads.clone()))
6166
        .unwrap();
6167
    let out = repo.store_blob(b"built\n").unwrap();
6168
    let receipt = Receipt {
6169
        job_name: "build".into(),
6170
        pipeline_hash: ObjectRef([1; 32]),
6171
        scope_tree_hash: ObjectRef([2; 32]),
6172
        inputs: vec![],
6173
        environment: ObjectRef([3; 32]),
6174
        outputs: vec![out],
6175
        exit_code: 0,
6176
        duration_ms: 42,
6177
    };
6178
    let sk = SecretKey::generate();
6179
    let runner = sk.identity("earth-1", "runner@earth", 1);
6180
    let sr = SignedReceipt::sign(
6181
        receipt.clone(),
6182
        repo.id().unwrap(),
6183
        state,
6184
        "demo#1",
6185
        &runner,
6186
        &sk,
6187
    );
6188
6189
    let r = repo.add_receipt(&sr).unwrap();
6190
    let found = repo.receipts(&heads).unwrap();
6191
    assert_eq!(found.len(), 1);
6192
    assert_eq!(found[0].attest, r);
6193
    assert_eq!(found[0].signed, sr);
6194
    assert!(found[0].problem.is_none() && !found[0].revoked);
6195
    assert!(repo.receipts(&[ObjectRef([5; 32])]).unwrap().is_empty());
6196
6197
    // Another repository's receipt, or a forged one, is refused.
6198
    let elsewhere = SignedReceipt::sign(receipt.clone(), [0; 16], state, "x", &runner, &sk);
6199
    assert!(repo
6200
        .add_receipt(&elsewhere)
6201
        .unwrap_err()
6202
        .to_string()
6203
        .contains("another repository"));
6204
    let mut forged = sr.clone();
6205
    forged.receipt.exit_code = 1;
6206
    assert!(repo
6207
        .add_receipt(&forged)
6208
        .unwrap_err()
6209
        .to_string()
6210
        .contains("does not verify"));
6211
6212
    // A receipt signed by a short-lived key keeps its certificate and the
6213
    // issuer's identity, and reads back with them (oxygenhub#241).
6214
    let hub_sk = SecretKey::generate();
6215
    let hub = hub_sk.identity("oxygenhub.io", "[email protected]", 1);
6216
    let job_sk = SecretKey::generate();
6217
    let job = job_sk.identity("job 2 test", "[email protected]", 1);
6218
    let mut test_receipt = receipt.clone();
6219
    test_receipt.job_name = "test".into();
6220
    let plain = SignedReceipt::sign(
6221
        test_receipt,
6222
        repo.id().unwrap(),
6223
        state,
6224
        "demo#2",
6225
        &job,
6226
        &job_sk,
6227
    );
6228
    let now = plain.attest.hlc.wall_ms;
6229
    let cert = crate::cert::SignedCertificate::sign(
6230
        crate::cert::Certificate {
6231
            key: job.clone(),
6232
            issuer: hub.hash(),
6233
            subject: "repo:andy/demo:bookmark:main".into(),
6234
            claims: vec![],
6235
            scope: crate::identity::Scope::SEAL,
6236
            not_before: now - 1_000,
6237
            expires: now + 600_000,
6238
            grant: None,
6239
        },
6240
        &hub,
6241
        &hub_sk,
6242
    );
6243
    let certified = plain.with_certificate(cert, hub.clone());
6244
    repo.add_receipt(&certified).unwrap();
6245
    let found = repo.receipts(&heads).unwrap();
6246
    let got = found
6247
        .iter()
6248
        .find(|i| i.signed.receipt.job_name == "test")
6249
        .unwrap();
6250
    assert_eq!(got.signed, certified);
6251
    assert!(got.problem.is_none(), "{:?}", got.problem);
6252
6253
    // gc keeps the receipts, their runners, the certificate and its issuer,
6254
    // and the output while the state lives.
6255
    repo.gc(true).unwrap();
6256
    let found = repo.receipts(&heads).unwrap();
6257
    assert_eq!(found.len(), 2);
6258
    let got = found
6259
        .iter()
6260
        .find(|i| i.signed.receipt.job_name == "test")
6261
        .unwrap();
6262
    assert_eq!(got.signed, certified, "the certificate survives gc");
6263
    assert!(got.problem.is_none());
6264
    assert_eq!(repo.read_blob(&out).unwrap(), b"built\n");
6265
    assert!(repo.fsck().unwrap().problems.is_empty());
6266
}
6267
6268
#[test]
6269
fn status_leaves_an_unchanged_manifest_alone() {
6270
    hermetic();
6271
    let dir = tempfile::tempdir().unwrap();
6272
    let root = dir.path();
6273
    let repo = Repo::init(root).unwrap().with_home(root.join("home"));
6274
    write(root, "a.txt", b"1\n");
6275
    write(root, "b.txt", b"2\n");
6276
    repo.commit("A", &[]).unwrap();
6277
    // Files last touched well outside the racy window.
6278
    let old = std::time::SystemTime::now() - std::time::Duration::from_secs(60);
6279
    for f in ["a.txt", "b.txt"] {
6280
        fs::File::options()
6281
            .write(true)
6282
            .open(root.join(f))
6283
            .unwrap()
6284
            .set_modified(old)
6285
            .unwrap();
6286
    }
6287
    repo.snapshot_status("status").unwrap();
6288
    let path = repo.manifest_path();
6289
    let first = fs::read(&path).unwrap();
6290
    repo.snapshot_status("status").unwrap();
6291
    assert_eq!(
6292
        fs::read(&path).unwrap(),
6293
        first,
6294
        "an unchanged tree does not rewrite the manifest"
6295
    );
6296
    // A change rewrites it.
6297
    write(root, "a.txt", b"1\n2\n");
6298
    repo.snapshot_status("status").unwrap();
6299
    assert_ne!(fs::read(&path).unwrap(), first);
6300
}
6301
6302
#[test]
6303
fn large_text_files_travel_and_survive_gc_as_text_blobs() {
6304
    hermetic();
6305
    let dir = tempfile::tempdir().unwrap();
6306
    let root = dir.path();
6307
    let origin_path = root.join("origin");
6308
    Repo::init(&origin_path).unwrap();
6309
    let origin_url = origin_path.to_string_lossy().to_string();
6310
    let a = Repo::clone(&origin_url, &root.join("a")).unwrap();
6311
    let big: String = (0..5000).map(|i| format!("line {i}\n")).collect();
6312
    write(&root.join("a"), "big.txt", big.as_bytes());
6313
    write(&root.join("a"), "small.txt", b"small\n");
6314
    let h1 = a.commit("large", &[]).unwrap();
6315
    let (_, body) = a.store().get(&h1).unwrap();
6316
    assert!(body.len() < 2048, "the change is {} bytes", body.len());
6317
    assert!(a.push("origin", false).unwrap()[0].ok);
6318
6319
    // A clone reads the text from the blobs that came with the change.
6320
    let b = Repo::clone(&origin_url, &root.join("b")).unwrap();
6321
    assert_eq!(fs::read(root.join("b/big.txt")).unwrap(), big.as_bytes());
6322
    // An edit in the middle of the stored insert is an ordinary change.
6323
    let edited = big.replace("line 2500\n", "line 2500, edited\n");
6324
    write(&root.join("b"), "big.txt", edited.as_bytes());
6325
    let h2 = b.commit("edit", &[]).unwrap();
6326
    assert!(b.store().get_change(&h2).unwrap().edits.len() <= 2);
6327
    assert!(b.push("origin", false).unwrap()[0].ok);
6328
    assert!(a.pull("origin").unwrap().checked_out);
6329
    assert_eq!(fs::read(root.join("a/big.txt")).unwrap(), edited.as_bytes());
6330
    assert_eq!(
6331
        a.fsck().unwrap().errors(),
6332
        0,
6333
        "{:?}",
6334
        a.fsck().unwrap().problems
6335
    );
6336
6337
    // With zero retention gc keeps the text blobs of every kept change.
6338
    let mut a = Repo::open(&root.join("a")).unwrap();
6339
    a.config.set("core.op-retention", "0").unwrap();
6340
    a.save_config().unwrap();
6341
    let a = Repo::open(&root.join("a")).unwrap();
6342
    a.gc(true).unwrap();
6343
    let a = Repo::open(&root.join("a")).unwrap();
6344
    assert_eq!(a.store().get_change(&h1).unwrap().message, "large");
6345
    assert_eq!(
6346
        a.fsck().unwrap().errors(),
6347
        0,
6348
        "{:?}",
6349
        a.fsck().unwrap().problems
6350
    );
6351
    // And a clone of the packed repository reads them from its packs.
6352
    let c = Repo::clone(&root.join("a").to_string_lossy(), &root.join("c")).unwrap();
6353
    assert_eq!(fs::read(root.join("c/big.txt")).unwrap(), edited.as_bytes());
6354
    drop(c);
6355
}
6356
6357
#[test]
6358
fn operations_that_both_replace_a_working_copy_are_not_merged() {
6359
    hermetic();
6360
    let dir = tempfile::tempdir().unwrap();
6361
    let root = dir.path();
6362
    let repo = Repo::init(root).unwrap();
6363
    write(root, "a.txt", b"a\n");
6364
    let a = repo.commit("a", &[]).unwrap();
6365
    write(root, "b.txt", b"b\n");
6366
    repo.commit("b", &[]).unwrap();
6367
    let (x, op) = repo.head_op().unwrap();
6368
    let ws = *op.view.workspaces.keys().next().unwrap();
6369
    let mut one = op.view.clone();
6370
    one.workspaces.insert(ws, a);
6371
    let mut two = op.view.clone();
6372
    two.workspaces.insert(ws, ObjectRef([7; 32]));
6373
    let first = repo.record_op(&[x], "one", one).unwrap();
6374
    let e = repo.record_op(&[x], "two", two).unwrap_err();
6375
    assert!(
6376
        e.to_string()
6377
            .contains("changed this working copy at the same time"),
6378
        "{e}"
6379
    );
6380
    assert_eq!(
6381
        repo.head_op().unwrap().0,
6382
        first,
6383
        "the second is not recorded"
6384
    );
6385
}
6386
6387
/// Metalgear, 2026-09-29 (oxygen#36): a status run while a bookmark switch
6388
/// rewrote the working copy recorded the half-written files as edits, and
6389
/// its view replaced the switch's.
6390
#[test]
6391
fn a_snapshot_during_a_switch_never_records_the_switch_as_edits() {
6392
    hermetic();
6393
    let dir = tempfile::tempdir().unwrap();
6394
    let root = dir.path().to_path_buf();
6395
    let mut repo = Repo::init(&root).unwrap();
6396
    write(&root, "keep.txt", b"keep\n");
6397
    repo.commit("base", &[]).unwrap();
6398
    repo.bookmark_create("small", None).unwrap();
6399
    for i in 0..300 {
6400
        write(
6401
            &root,
6402
            &format!("many/f{i}.txt"),
6403
            format!("file {i}\n").as_bytes(),
6404
        );
6405
    }
6406
    repo.commit("many", &[]).unwrap();
6407
    let stop = std::sync::Arc::new(std::sync::atomic::AtomicBool::new(false));
6408
    let watcher = {
6409
        let (root, stop) = (root.clone(), stop.clone());
6410
        std::thread::spawn(move || {
6411
            let r = Repo::open(&root).unwrap();
6412
            let mut ran = 0;
6413
            while !stop.load(std::sync::atomic::Ordering::Relaxed) {
6414
                if r.snapshot_status("oxy status").is_ok() {
6415
                    ran += 1;
6416
                }
6417
            }
6418
            ran
6419
        })
6420
    };
6421
    for i in 0..20 {
6422
        let to = if i % 2 == 0 { "small" } else { "main" };
6423
        repo.bookmark_switch(to, false).unwrap();
6424
    }
6425
    stop.store(true, std::sync::atomic::Ordering::Relaxed);
6426
    assert!(watcher.join().unwrap() > 0, "the watcher snapshotted");
6427
    // Back on main, clean, with every file where main has it.
6428
    let repo = Repo::open(&root).unwrap();
6429
    let s = repo.snapshot_status("oxy status").unwrap();
6430
    assert!(s.statuses.is_empty(), "{:?}", statuses(&s));
6431
    assert!(s.wc.edits.is_empty() && s.wc.tree_ops.is_empty());
6432
    assert_eq!(s.wc.deps, repo.bookmark_heads().unwrap());
6433
    assert!(root.join("many/f299.txt").exists());
6434
}
6435
6436
/// Metalgear, 2026-09-29 (oxygen#38): a parent's `bookmark switch --carry`
6437
/// put a subrepo that was ahead of its pin back at the pin and moved the
6438
/// subrepo's own bookmark backwards.
6439
#[test]
6440
fn a_parent_switch_with_carry_leaves_a_subrepo_ahead_of_its_pin_alone() {
6441
    hermetic();
6442
    let dir = tempfile::tempdir().unwrap();
6443
    let root = dir.path();
6444
    Repo::init(&root.join("lib-origin")).unwrap();
6445
    let lib_url = root.join("lib-origin").to_string_lossy().to_string();
6446
    let lib = Repo::clone(&lib_url, &root.join("lib")).unwrap();
6447
    write(&root.join("lib"), "lib.txt", b"v1\n");
6448
    lib.commit("lib v1", &[]).unwrap();
6449
    assert!(lib.push("origin", false).unwrap()[0].ok);
6450
6451
    let app_dir = root.join("app");
6452
    let mut app = Repo::init(&app_dir).unwrap();
6453
    write(&app_dir, "main.txt", b"app\n");
6454
    app.submodule_add(&lib_url, "libs/lib", None).unwrap();
6455
    app.commit("app with lib", &[]).unwrap();
6456
    app.bookmark_create("feature", None).unwrap();
6457
6458
    // New work in the subrepo, not yet pinned by the parent.
6459
    let nested_dir = app_dir.join("libs/lib");
6460
    let nested = Repo::open(&nested_dir).unwrap();
6461
    write(&nested_dir, "new.txt", b"new\n");
6462
    let l2 = nested.commit("lib: new file", &[]).unwrap();
6463
    drop(nested);
6464
6465
    let (_, carried) = app.bookmark_switch_carry("feature").unwrap();
6466
    assert!(carried.contains(&"libs/lib".to_string()), "{carried:?}");
6467
    let nested = Repo::open(&nested_dir).unwrap();
6468
    assert!(
6469
        nested.bookmark_heads().unwrap().contains(&l2),
6470
        "its bookmark kept its work"
6471
    );
6472
    assert!(nested_dir.join("new.txt").exists(), "and its files");
6473
    let s = app.snapshot("status").unwrap();
6474
    assert_eq!(
6475
        statuses(&s),
6476
        vec![("libs/lib".to_string(), ChangeStatus::Modified)]
6477
    );
6478
}
6479
6480
/// oxygen#29 (metalgear, rstar-api): after a proposal landed on the hub,
6481
/// moving `main` to a change this clone had pushed on another bookmark,
6482
/// the first `pull` said "Already up to date" while `main` was behind.
6483
#[test]
6484
fn pull_takes_a_remote_move_to_changes_already_here() {
6485
    hermetic();
6486
    let dir = tempfile::tempdir().unwrap();
6487
    let root = dir.path();
6488
    let origin_path = root.join("origin");
6489
    let origin = Repo::init(&origin_path).unwrap();
6490
    let url = origin_path.to_string_lossy().to_string();
6491
    let mut b = Repo::clone(&url, &root.join("b")).unwrap();
6492
    write(&root.join("b"), "base.txt", b"base\n");
6493
    b.commit("base", &[]).unwrap();
6494
    assert!(b.push("origin", false).unwrap()[0].ok);
6495
6496
    // A feature bookmark with one change, pushed.
6497
    b.bookmark_create("feat", None).unwrap();
6498
    b.bookmark_switch("feat", false).unwrap();
6499
    write(&root.join("b"), "x.txt", b"x\n");
6500
    let x = b.commit("x", &[]).unwrap();
6501
    assert!(b.push("origin", false).unwrap()[0].ok);
6502
    b.bookmark_switch("main", false).unwrap();
6503
6504
    // The remote lands it: its main moves to the feature's state.
6505
    let feat = origin
6506
        .store()
6507
        .get_state(&origin.view().unwrap().bookmarks["feat"])
6508
        .unwrap()
6509
        .heads;
6510
    origin.bookmark_set("main", &feat).unwrap();
6511
6512
    let r = b.pull("origin").unwrap();
6513
    assert!(r.changed, "{r:?}");
6514
    assert!(r.heads.contains(&x) || b.load_state(&r.heads).unwrap().contains(&x));
6515
    let main = b
6516
        .bookmarks()
6517
        .unwrap()
6518
        .into_iter()
6519
        .find(|m| m.name == "main")
6520
        .unwrap();
6521
    assert_eq!(main.behind, Some(0), "{main:?}");
6522
}
6523
6524
/// oxygen#48: a remote's bookmarks are names here (`origin/NAME`); switching
6525
/// to one only the remote has makes a local bookmark from it; a pull moves
6526
/// every local bookmark the remote has too; a clone checks out the remote's
6527
/// default bookmark.
6528
#[test]
6529
fn remote_bookmarks_are_named_switched_to_pulled_and_cloned() {
6530
    hermetic();
6531
    let dir = tempfile::tempdir().unwrap();
6532
    let root = dir.path();
6533
    let origin_path = root.join("origin");
6534
    let mut origin = Repo::init(&origin_path).unwrap();
6535
    let url = origin_path.to_string_lossy().to_string();
6536
    let mut a = Repo::clone(&url, &root.join("a")).unwrap();
6537
    write(&root.join("a"), "base.txt", b"base\n");
6538
    a.commit("base", &[]).unwrap();
6539
    assert!(a.push("origin", false).unwrap()[0].ok);
6540
    a.bookmark_create("develop", None).unwrap();
6541
    a.bookmark_switch("develop", false).unwrap();
6542
    write(&root.join("a"), "base.txt", b"base\nd1\n");
6543
    let d1 = a.commit("d1", &[]).unwrap();
6544
    assert!(a.push("origin", false).unwrap()[0].ok);
6545
6546
    // A clone has main only; origin/develop is a name all the same.
6547
    let c_root = root.join("c");
6548
    let mut c = Repo::clone(&url, &c_root).unwrap();
6549
    assert_eq!(c.config.bookmark, "main");
6550
    assert!(!c.view().unwrap().bookmarks.contains_key("develop"));
6551
    assert_eq!(c.resolve_heads("origin/develop").unwrap(), vec![d1]);
6552
    assert_eq!(c.resolve_change("origin/develop").unwrap(), d1);
6553
    assert_eq!(c.remote_only_bookmarks().unwrap().len(), 1);
6554
6555
    // Switching makes the local bookmark from origin's.
6556
    c.bookmark_switch("develop", false).unwrap();
6557
    assert_eq!(c.config.bookmark, "develop");
6558
    assert_eq!(c.bookmark_heads().unwrap(), vec![d1]);
6559
    assert_eq!(fs::read(c_root.join("base.txt")).unwrap(), b"base\nd1\n");
6560
    assert!(c.remote_only_bookmarks().unwrap().is_empty());
6561
    assert!(c.bookmark_switch("nowhere", false).is_err());
6562
6563
    // Both bookmarks move on the remote; one pull takes both.
6564
    write(&root.join("a"), "base.txt", b"base\nd1\nd2\n");
6565
    let d2 = a.commit("d2", &[]).unwrap();
6566
    assert!(a.push("origin", false).unwrap()[0].ok);
6567
    a.bookmark_switch("main", false).unwrap();
6568
    write(&root.join("a"), "m.txt", b"m\n");
6569
    let m = a.commit("m", &[]).unwrap();
6570
    assert!(a.push("origin", false).unwrap()[0].ok);
6571
    let r = c.pull("origin").unwrap();
6572
    assert!(r.changed && r.checked_out, "{r:?}");
6573
    assert_eq!(r.heads, vec![d2]);
6574
    assert_eq!(r.others, vec!["main".to_string()]);
6575
    assert!(c.resolve_heads("main").unwrap().contains(&m));
6576
    assert_eq!(
6577
        fs::read(c_root.join("base.txt")).unwrap(),
6578
        b"base\nd1\nd2\n"
6579
    );
6580
    let again = c.pull("origin").unwrap();
6581
    assert!(!again.changed && again.others.is_empty(), "{again:?}");
6582
6583
    // A clone checks out the remote's default bookmark.
6584
    origin.config.set("workspace.bookmark", "develop").unwrap();
6585
    origin.save_config().unwrap();
6586
    let e = Repo::clone(&url, &root.join("e")).unwrap();
6587
    assert_eq!(e.config.bookmark, "develop");
6588
    assert_eq!(e.bookmark_heads().unwrap(), vec![d2]);
6589
    let reopened = Repo::open(&root.join("e")).unwrap();
6590
    assert_eq!(reopened.config.bookmark, "develop");
6591
    // REMOTE/NAME names the remote's bookmark to switch to.
6592
    let mut e = reopened;
6593
    e.bookmark_switch("origin/main", false).unwrap();
6594
    assert_eq!(e.config.bookmark, "main");
6595
    assert!(e.bookmark_heads().unwrap().contains(&m));
6596
}
6597
6598
/// oxygen#51, #52: --at-op reads an earlier view and refuses changes;
6599
/// op restore goes back to an operation, files included, and undo takes
6600
/// the restore back whole; op revert undoes one operation alone; each
6601
/// operation's changes are described from the views.
6602
#[test]
6603
fn operations_can_be_read_restored_and_reverted() {
6604
    hermetic();
6605
    let dir = tempfile::tempdir().unwrap();
6606
    let root = dir.path();
6607
    let repo = Repo::init(root).unwrap();
6608
    write(root, "a.txt", b"a\n");
6609
    let first = repo.commit("first", &[]).unwrap();
6610
    write(root, "a.txt", b"a\nb\n");
6611
    let second = repo.commit("second", &[]).unwrap();
6612
    let at_second = repo.head_op().unwrap().0.to_hex();
6613
    repo.bookmark_create("keep", None).unwrap();
6614
    let created = repo.head_op().unwrap().0.to_hex();
6615
    write(root, "n.txt", b"n\n");
6616
    let third = repo.commit("third", &[]).unwrap();
6617
6618
    // What each operation changed.
6619
    let ops = repo.op_log().unwrap();
6620
    let changes = repo.view_changes(&ops[1].1.view, &ops[0].1.view).unwrap();
6621
    assert!(
6622
        changes
6623
            .iter()
6624
            .any(|c| matches!(c, ViewChange::BookmarkMoved { name, .. } if name == "main")),
6625
        "{changes:?}"
6626
    );
6627
    assert!(changes
6628
        .iter()
6629
        .any(|c| matches!(c, ViewChange::WorkingCopy { .. })));
6630
6631
    // Reading at an earlier operation.
6632
    let old = Repo::open(root).unwrap().at_op(&at_second[..10]).unwrap();
6633
    assert_eq!(old.bookmark_heads().unwrap(), vec![second]);
6634
    assert!(!old.view().unwrap().bookmarks.contains_key("keep"));
6635
    write(root, "z.txt", b"z\n");
6636
    assert!(old.commit("refused", &[]).is_err(), "--at-op is read-only");
6637
    fs::remove_file(root.join("z.txt")).unwrap();
6638
    assert!(repo.resolve_op("zz").is_err());
6639
    assert_eq!(repo.resolve_op("@").unwrap().0, repo.head_op().unwrap().0);
6640
6641
    // Restore goes back, files and all; undo takes it back whole.
6642
    repo.op_restore(&at_second, false).unwrap();
6643
    assert_eq!(repo.bookmark_heads().unwrap(), vec![second]);
6644
    assert!(!root.join("n.txt").exists());
6645
    repo.undo().unwrap();
6646
    let mut heads = repo.bookmark_heads().unwrap();
6647
    heads.sort();
6648
    let mut want = vec![second, third];
6649
    want.sort();
6650
    assert_eq!(heads, want);
6651
    assert!(
6652
        root.join("n.txt").exists(),
6653
        "the files came back with the undo"
6654
    );
6655
6656
    // Revert the bookmark's creation alone: the commit after it stays.
6657
    let r = repo.op_revert(&created).unwrap();
6658
    assert_eq!(r.reverted, vec!["keep".to_string()]);
6659
    assert!(!repo.view().unwrap().bookmarks.contains_key("keep"));
6660
    assert!(repo
6661
        .load_state(&repo.bookmark_heads().unwrap())
6662
        .unwrap()
6663
        .contains(&third));
6664
    assert!(repo.op_revert(&created).is_err(), "nothing left to revert");
6665
    let _ = first;
6666
}
6667
6668
/// oxygen#41: with uncommitted work, a status after a snapshot is answered
6669
/// from the status cache while every file is as the snapshot left it, and
6670
/// from a snapshot again as soon as one is not.
6671
#[test]
6672
fn status_with_uncommitted_work_comes_from_the_cache_until_a_file_changes() {
6673
    hermetic();
6674
    let dir = tempfile::tempdir().unwrap();
6675
    let root = dir.path();
6676
    let repo = Repo::init(root).unwrap();
6677
    write(root, "a.txt", b"a\n");
6678
    write(root, "b.txt", b"b\n");
6679
    repo.commit("base", &[]).unwrap();
6680
    assert_eq!(repo.status_by_manifest().unwrap(), Some(vec![]), "clean");
6681
6682
    write(root, "a.txt", b"a\nmore\n");
6683
    assert_eq!(
6684
        repo.status_by_manifest().unwrap(),
6685
        None,
6686
        "no snapshot of the edit yet"
6687
    );
6688
    let snap = repo.snapshot_status("oxy status").unwrap();
6689
    assert_eq!(snap.statuses.len(), 1);
6690
    let cached = repo
6691
        .status_by_manifest()
6692
        .unwrap()
6693
        .expect("answered from the cache");
6694
    assert_eq!(cached.len(), 1);
6695
    assert_eq!(
6696
        (cached[0].path.as_str(), cached[0].status),
6697
        ("a.txt", ChangeStatus::Modified)
6698
    );
6699
6700
    // Any further change sends status back to a snapshot.
6701
    write(root, "a.txt", b"a\nmore\nand more\n");
6702
    assert_eq!(repo.status_by_manifest().unwrap(), None, "edited again");
6703
    repo.snapshot_status("oxy status").unwrap();
6704
    assert!(repo.status_by_manifest().unwrap().is_some());
6705
    write(root, "new.txt", b"n\n");
6706
    assert_eq!(repo.status_by_manifest().unwrap(), None, "a file added");
6707
    fs::remove_file(root.join("new.txt")).unwrap();
6708
    assert!(
6709
        repo.status_by_manifest().unwrap().is_some(),
6710
        "back as it was"
6711
    );
6712
    fs::remove_file(root.join("b.txt")).unwrap();
6713
    assert_eq!(repo.status_by_manifest().unwrap(), None, "a file removed");
6714
    write(root, "b.txt", b"b\n");
6715
6716
    // A commit leaves nothing uncommitted: clean again, no cache needed.
6717
    repo.snapshot_status("oxy status").unwrap();
6718
    repo.commit("more", &[]).unwrap();
6719
    assert_eq!(repo.status_by_manifest().unwrap(), Some(vec![]));
6720
}
6721
6722
/// oxygen#41: while the status cache holds, the working copy's diff is
6723
/// rendered from the stored working-copy change, and says exactly what a
6724
/// snapshot's diff says.
6725
#[test]
6726
fn the_working_copy_diff_from_the_cache_matches_a_snapshot() {
6727
    hermetic();
6728
    let dir = tempfile::tempdir().unwrap();
6729
    let root = dir.path();
6730
    let repo = Repo::init(root).unwrap();
6731
    write(root, "a.txt", b"one\ntwo\nthree\n");
6732
    write(root, "gone.txt", b"bye\n");
6733
    repo.commit("base", &[]).unwrap();
6734
    write(root, "a.txt", b"one\n2\nthree\nfour\n");
6735
    write(root, "new.txt", b"hello\n");
6736
    fs::remove_file(root.join("gone.txt")).unwrap();
6737
    let snap = repo.snapshot_status("oxy status").unwrap();
6738
    let slow = render_change(&snap.wc, &snap.base, &snap.base_snapshot);
6739
    assert!(
6740
        repo.status_by_manifest().unwrap().is_some(),
6741
        "the cache holds"
6742
    );
6743
    let (wc, base, snapshot) = repo.working_copy_with_base().unwrap();
6744
    assert_eq!(render_change(&wc, &base, &snapshot), slow);
6745
    assert_eq!(repo.diff_files(None).unwrap().len(), 3);
6746
}
6747
6748
/// oxygen#41: a manifest written from a walk keeps every directory's time;
6749
/// while none has moved, the check stats the tracked files without listing
6750
/// the tree, and a file added or removed anywhere moves its directory's
6751
/// time, so the tree is listed again.
6752
#[test]
6753
fn the_manifest_check_skips_listing_while_no_directory_changed() {
6754
    hermetic();
6755
    let dir = tempfile::tempdir().unwrap();
6756
    let root = dir.path();
6757
    let repo = Repo::init(root).unwrap();
6758
    write(root, "a.txt", b"a\n");
6759
    write(root, "sub/deep/b.txt", b"b\n");
6760
    repo.commit("base", &[]).unwrap();
6761
    // Out of the racy window: every file and directory a minute old.
6762
    let old = std::time::SystemTime::now() - std::time::Duration::from_secs(60);
6763
    for p in ["a.txt", "sub/deep/b.txt", "sub/deep", "sub", ""] {
6764
        fs::File::open(root.join(p))
6765
            .unwrap()
6766
            .set_modified(old)
6767
            .unwrap();
6768
    }
6769
    repo.snapshot_status("oxy status").unwrap();
6770
    repo.write_manifest(false, false).unwrap();
6771
    let m = repo.read_manifest().unwrap().unwrap().2;
6772
    assert!(m.dirs.iter().any(|(d, _)| d == "sub/deep"), "{:?}", m.dirs);
6773
    assert_eq!(
6774
        repo.disk_differs_by_dirs(&m),
6775
        Some(false),
6776
        "no listing needed"
6777
    );
6778
    assert_eq!(repo.status_by_manifest().unwrap(), Some(vec![]));
6779
6780
    // A same-size edit with a new time: found by its stat.
6781
    write(root, "sub/deep/b.txt", b"c\n");
6782
    assert_eq!(repo.disk_differs_by_dirs(&m), Some(true));
6783
    write(root, "sub/deep/b.txt", b"b\n");
6784
    fs::File::open(root.join("sub/deep/b.txt"))
6785
        .unwrap()
6786
        .set_modified(old)
6787
        .unwrap();
6788
    assert_eq!(repo.disk_differs_by_dirs(&m), Some(false));
6789
6790
    // A new file moves its directory's time: the tree must be listed.
6791
    write(root, "sub/deep/new.txt", b"n\n");
6792
    assert_eq!(repo.disk_differs_by_dirs(&m), None);
6793
    assert_eq!(repo.status_by_manifest().unwrap(), None);
6794
    fs::remove_file(root.join("sub/deep/new.txt")).unwrap();
6795
    // A removed one too.
6796
    fs::remove_file(root.join("a.txt")).unwrap();
6797
    assert_eq!(repo.disk_differs_by_dirs(&m), None);
6798
}
6799
6800
/// oxygen#41: a commit right after a status takes the snapshot the status
6801
/// left (the status cache holds) rather than walking again, and commits
6802
/// exactly what a snapshot would have.
6803
#[test]
6804
fn a_commit_after_a_status_uses_the_cached_snapshot() {
6805
    hermetic();
6806
    let dir = tempfile::tempdir().unwrap();
6807
    let root = dir.path();
6808
    let repo = Repo::init(root).unwrap();
6809
    write(root, "a.txt", b"a\nb\n");
6810
    write(root, ".oxyattributes", b"*.bin binary\n");
6811
    repo.commit("base", &[]).unwrap();
6812
    write(root, "a.txt", b"a\nB\n");
6813
    write(root, "new.txt", b"new\n");
6814
    let snap = repo.snapshot_status("oxy status").unwrap();
6815
    let cached = repo
6816
        .snapshot_from_cache()
6817
        .unwrap()
6818
        .expect("the cache holds");
6819
    assert_eq!(cached.wc_hash, snap.wc_hash);
6820
    assert_eq!(cached.statuses, snap.statuses);
6821
    assert!(
6822
        !cached.attributes.is_empty(),
6823
        "the .oxyattributes file was read"
6824
    );
6825
    let h = repo.commit("edit", &[]).unwrap();
6826
    let c = repo.store().get_change(&h).unwrap();
6827
    assert_eq!(
6828
        c.tree_ops.len() + c.edits.len(),
6829
        snap.wc.tree_ops.len() + snap.wc.edits.len()
6830
    );
6831
    assert_eq!(
6832
        repo.status_by_manifest().unwrap(),
6833
        Some(vec![]),
6834
        "clean after the commit"
6835
    );
6836
    assert_eq!(fs::read(root.join("a.txt")).unwrap(), b"a\nB\n");
6837
}
6838
6839
/// oxygen#41: a clean check that verified racy entries restamps the
6840
/// manifest, so later checks can trust them, and a same-size rewrite
6841
/// straight afterwards is still found: entries within two seconds of the
6842
/// new time stay racy.
6843
#[test]
6844
fn a_verified_clean_check_restamps_the_manifest_safely() {
6845
    hermetic();
6846
    let dir = tempfile::tempdir().unwrap();
6847
    let root = dir.path();
6848
    let repo = Repo::init(root).unwrap();
6849
    write(root, "a.txt", b"one\n");
6850
    repo.commit("one", &[]).unwrap();
6851
    let before = repo.read_manifest().unwrap().unwrap().2.written_ns;
6852
    assert!(repo.clean_by_manifest().unwrap());
6853
    let after = repo.read_manifest().unwrap().unwrap().2.written_ns;
6854
    assert!(after > before, "restamped");
6855
    write(root, "a.txt", b"two\n");
6856
    assert!(
6857
        !repo.clean_by_manifest().unwrap(),
6858
        "a same-size rewrite is still seen"
6859
    );
6860
}
6861
6862
/// oxygen#35: a history-only state keeps no inserted text. It reads a
6863
/// stored insert's text blob only when it builds that file's graph, and
6864
/// builds the same graph a full load does.
6865
#[test]
6866
fn history_only_states_read_text_only_for_the_graphs_they_build() {
6867
    hermetic();
6868
    let dir = tempfile::tempdir().unwrap();
6869
    let root = dir.path();
6870
    let repo = Repo::init(root).unwrap();
6871
    let big: String = (0..3000).map(|i| format!("big line {i}\n")).collect();
6872
    let other: String = (0..3000).map(|i| format!("other line {i}\n")).collect();
6873
    write(root, "big.txt", big.as_bytes());
6874
    write(root, "other.txt", other.as_bytes());
6875
    let h = repo.commit("two large files", &[]).unwrap();
6876
    write(root, "big.txt", format!("{big}one more\n").as_bytes());
6877
    let h2 = repo.commit("append", &[]).unwrap();
6878
6879
    let full = repo.load_state_full(&[h2]).unwrap().materialize();
6880
    let text = |snap: &crate::state::Snapshot, p: &str| match &snap.files[p].content {
6881
        FileContent::Text { bytes, .. } => bytes.clone(),
6882
        other => panic!("{other:?}"),
6883
    };
6884
    // Built on demand, every graph renders as the full load's.
6885
    let mut hist = repo.load_state_history(&[h2]).unwrap();
6886
    let big_node = full.files["big.txt"].node;
6887
    assert!(hist.graph_key(&big_node).is_some(), "not built yet");
6888
    repo.load_all_graphs(&mut hist).unwrap();
6889
    let rendered = hist.materialize();
6890
    for p in ["big.txt", "other.txt"] {
6891
        assert_eq!(text(&rendered, p), text(&full, p), "{p}");
6892
    }
6893
6894
    // Without other.txt's text blob, history still loads and big.txt still
6895
    // builds: nothing read the other text.
6896
    let (_, texts) = repo.store().get_change_lazy(&h).unwrap();
6897
    assert_eq!(texts.len(), 2);
6898
    let content = |r: &ObjectRef| -> Vec<u8> {
6899
        let blob = crate::objects::Blob::decode(&repo.store().get(r).unwrap().1).unwrap();
6900
        blob.chunks
6901
            .iter()
6902
            .flat_map(|c| repo.store().get(c).unwrap().1)
6903
            .collect()
6904
    };
6905
    let other_text = texts
6906
        .iter()
6907
        .filter_map(|t| match t {
6908
            crate::objects::TextRef::Blob(r, _, _) => Some(*r),
6909
            _ => None,
6910
        })
6911
        .find(|r| content(r).windows(12).any(|w| w == b"other line 1"))
6912
        .unwrap();
6913
    repo.store().remove_loose_for_test(&other_text).unwrap();
6914
    let mut hist = repo.load_state_history(&[h2]).unwrap();
6915
    repo.load_graphs_of(&mut hist, &[big_node]).unwrap();
6916
    assert!(repo
6917
        .load_graphs_of(&mut hist, &[full.files["other.txt"].node])
6918
        .is_err());
6919
}
6920
6921
/// oxygen#35: the first status after a commit read and rendered every
6922
/// file (79 s and more than 14 GB on the Linux tree), because the
6923
/// manifest had no graph keys for files the commit added.
6924
#[test]
6925
fn a_commit_leaves_a_manifest_the_next_status_trusts() {
6926
    use std::os::unix::fs::PermissionsExt;
6927
    hermetic();
6928
    let dir = tempfile::tempdir().unwrap();
6929
    let root = dir.path();
6930
    let repo = Repo::init(root).unwrap();
6931
    let files = ["a.txt", "b.txt", "d/c.txt"];
6932
    for p in files {
6933
        write(root, p, format!("{p}\n").as_bytes());
6934
        let old = std::time::SystemTime::now() - std::time::Duration::from_secs(30);
6935
        fs::File::options()
6936
            .write(true)
6937
            .open(root.join(p))
6938
            .unwrap()
6939
            .set_modified(old)
6940
            .unwrap();
6941
    }
6942
    repo.commit("added", &[]).unwrap();
6943
    let (_, _, m) = repo.read_manifest().unwrap().unwrap();
6944
    assert!(
6945
        m.entries.values().all(|e| e.graph.is_some()),
6946
        "keys recorded at commit"
6947
    );
6948
    // Unreadable files prove the next status reads none of them.
6949
    for p in files {
6950
        fs::set_permissions(root.join(p), fs::Permissions::from_mode(0o000)).unwrap();
6951
    }
6952
    let snap = repo.snapshot_status("status").unwrap();
6953
    for p in files {
6954
        fs::set_permissions(root.join(p), fs::Permissions::from_mode(0o644)).unwrap();
6955
    }
6956
    assert!(!snap.changed && snap.statuses.is_empty());
6957
    assert_eq!(snap.base_snapshot.unrendered.len(), files.len());
6958
}
6959
6960
/// oxygen#35: a checkout reads, renders and writes only the files whose
6961
/// graphs differ, and renders the rest a batch at a time.
6962
#[test]
6963
fn checkout_touches_only_what_differs_and_renders_in_batches() {
6964
    use std::os::unix::fs::PermissionsExt;
6965
    hermetic();
6966
    let dir = tempfile::tempdir().unwrap();
6967
    let root = dir.path();
6968
    let origin = root.join("origin");
6969
    let mut repo = Repo::init(&origin).unwrap();
6970
    // More files than one batch holds.
6971
    let n = 2100;
6972
    let old = std::time::SystemTime::now() - std::time::Duration::from_secs(30);
6973
    for i in 0..n {
6974
        let p = format!("f/{i:04}.txt");
6975
        write(&origin, &p, format!("file {i}\n").as_bytes());
6976
        fs::File::options()
6977
            .write(true)
6978
            .open(origin.join(&p))
6979
            .unwrap()
6980
            .set_modified(old)
6981
            .unwrap();
6982
    }
6983
    repo.commit("many", &[]).unwrap();
6984
    repo.bookmark_create("feature", None).unwrap();
6985
    repo.bookmark_switch("feature", false).unwrap();
6986
    write(&origin, "f/0007.txt", b"changed\n");
6987
    repo.commit("one change", &[]).unwrap();
6988
6989
    // Switching back to main must not read the unchanged files.
6990
    for i in 0..n {
6991
        if i != 7 {
6992
            let p = origin.join(format!("f/{i:04}.txt"));
6993
            fs::set_permissions(&p, fs::Permissions::from_mode(0o000)).unwrap();
6994
        }
6995
    }
6996
    let r = repo.bookmark_switch("main", false).unwrap();
6997
    for i in 0..n {
6998
        let p = origin.join(format!("f/{i:04}.txt"));
6999
        fs::set_permissions(&p, fs::Permissions::from_mode(0o644)).unwrap();
7000
    }
7001
    assert_eq!((r.written, r.removed), (1, 0), "{r:?}");
7002
    assert_eq!(fs::read(origin.join("f/0007.txt")).unwrap(), b"file 7\n");
7003
    assert!(repo.snapshot_status("status").unwrap().statuses.is_empty());
7004
7005
    // A clone renders every file, across batches.
7006
    let c = root.join("clone");
7007
    Repo::clone(&origin.to_string_lossy(), &c).unwrap();
7008
    for i in [0, 2047, 2048, n - 1] {
7009
        assert_eq!(
7010
            fs::read(c.join(format!("f/{i:04}.txt"))).unwrap(),
7011
            format!("file {i}\n").as_bytes()
7012
        );
7013
    }
7014
    let cloned = Repo::open(&c).unwrap();
7015
    assert!(cloned
7016
        .snapshot_status("status")
7017
        .unwrap()
7018
        .statuses
7019
        .is_empty());
7020
}
7021
7022
/// A file written just before the manifest (inside the racy window) is
7023
/// checked by its hash: trusted when equal, caught when edited in place
7024
/// with the same size and time.
7025
#[test]
7026
fn a_racy_manifest_entry_is_checked_by_hash() {
7027
    hermetic();
7028
    let dir = tempfile::tempdir().unwrap();
7029
    let root = dir.path();
7030
    let repo = Repo::init(root).unwrap();
7031
    write(root, "a.txt", b"one\n");
7032
    repo.commit("fresh", &[]).unwrap();
7033
    assert!(repo.clean_by_manifest().unwrap(), "fresh but equal");
7034
    let t = fs::metadata(root.join("a.txt"))
7035
        .unwrap()
7036
        .modified()
7037
        .unwrap();
7038
    write(root, "a.txt", b"two\n");
7039
    fs::File::options()
7040
        .write(true)
7041
        .open(root.join("a.txt"))
7042
        .unwrap()
7043
        .set_modified(t)
7044
        .unwrap();
7045
    assert!(
7046
        !repo.clean_by_manifest().unwrap(),
7047
        "same size and time, other bytes"
7048
    );
7049
    assert_eq!(
7050
        statuses(&repo.snapshot_status("status").unwrap()),
7051
        vec![("a.txt".to_string(), ChangeStatus::Modified)]
7052
    );
7053
}
7054
7055
/// A fetch on one machine moves changes as stored, text blobs among the
7056
/// objects; a change whose text blob did not come is refused, not stored.
7057
#[test]
7058
fn a_raw_bundle_without_a_changes_text_is_refused() {
7059
    hermetic();
7060
    let dir = tempfile::tempdir().unwrap();
7061
    let root = dir.path();
7062
    let a = Repo::init(&root.join("a")).unwrap();
7063
    let big: String = (0..3000).map(|i| format!("line {i}\n")).collect();
7064
    write(&root.join("a"), "big.txt", big.as_bytes());
7065
    let h = a.commit("big", &[]).unwrap();
7066
    let bundle = a.bundle_raw_for(&[h], None).unwrap();
7067
    assert_eq!(bundle.raw_changes.len(), 1);
7068
    assert!(bundle.changes.is_empty());
7069
    let b = Repo::init(&root.join("b")).unwrap();
7070
    let mut without = bundle.clone();
7071
    without.objects.retain(|(ty, _)| *ty != ObjectType::Blob);
7072
    let e = b.import_bundle(&without, false).unwrap_err();
7073
    assert!(e.to_string().contains("came without its text blob"), "{e}");
7074
    assert!(!b.store().has(&h));
7075
    assert_eq!(b.import_bundle(&bundle, false).unwrap(), vec![h]);
7076
    assert_eq!(b.store().get_change(&h).unwrap().message, "big");
7077
}
7078
7079
/// oxygen#30 (vscode): a directory deleted in one line of history and made
7080
/// again was a second node for one Git path, so a file moved into it on
7081
/// another line, where the first node still stood, ended up in two places.
7082
/// An import now brings the directory back rather than make a new one.
7083
#[test]
7084
fn git_import_brings_a_directory_back_rather_than_making_a_second() {
7085
    hermetic();
7086
    if std::process::Command::new("git")
7087
        .arg("--version")
7088
        .output()
7089
        .is_err()
7090
    {
7091
        eprintln!("git not installed; skipping");
7092
        return;
7093
    }
7094
    let dir = tempfile::tempdir().unwrap();
7095
    let root = dir.path();
7096
    let g = root.join("src.git");
7097
    fs::create_dir_all(&g).unwrap();
7098
    let git = |args: &[&str]| -> String {
7099
        let out = std::process::Command::new("git")
7100
            .arg("-C")
7101
            .arg(&g)
7102
            .args([
7103
                "-c",
7104
                "user.name=Grace",
7105
                "-c",
7106
                "[email protected]",
7107
                "-c",
7108
                "commit.gpgsign=false",
7109
            ])
7110
            .args(args)
7111
            .output()
7112
            .unwrap();
7113
        assert!(
7114
            out.status.success(),
7115
            "git {args:?}: {}",
7116
            String::from_utf8_lossy(&out.stderr)
7117
        );
7118
        String::from_utf8_lossy(&out.stdout).trim().to_string()
7119
    };
7120
    git(&["init", "-q", "-b", "main"]);
7121
    write(&g, "d/a.txt", b"a\n");
7122
    write(&g, "c/x.txt", b"x\n");
7123
    git(&["add", "."]);
7124
    git(&["commit", "-qm", "base"]);
7125
    // One line: move x into d while d still stands.
7126
    git(&["checkout", "-qb", "side"]);
7127
    git(&["mv", "c/x.txt", "d/x.txt"]);
7128
    git(&["commit", "-qm", "x into d"]);
7129
    // The other: d goes, comes back, and x moves into it too.
7130
    git(&["checkout", "-q", "main"]);
7131
    git(&["rm", "-q", "d/a.txt"]);
7132
    git(&["commit", "-qm", "d goes"]);
7133
    write(&g, "d/b.txt", b"b\n");
7134
    git(&["add", "."]);
7135
    git(&["commit", "-qm", "d comes back"]);
7136
    git(&["mv", "c/x.txt", "d/x.txt"]);
7137
    git(&["commit", "-qm", "x into d again"]);
7138
    git(&["merge", "-q", "--no-edit", "side"]);
7139
7140
    let repo = Repo::init(&root.join("o")).unwrap();
7141
    repo.import_git(&g, "main").unwrap();
7142
    let v = repo.verify_git_import(&g, "main").unwrap();
7143
    assert!(v.mismatches.is_empty(), "{:?}", v.mismatches);
7144
    let st = repo
7145
        .load_state_history(&repo.bookmark_heads().unwrap())
7146
        .unwrap();
7147
    let view = st.tree().view();
7148
    assert!(view.conflicts.is_empty(), "{:?}", view.conflicts);
7149
    // The directory is the one the first commit made.
7150
    // Commits made in one second tie on time: find the first by its message.
7151
    let first = repo
7152
        .log()
7153
        .unwrap()
7154
        .into_iter()
7155
        .find(|e| e.change.message.starts_with("base"))
7156
        .unwrap();
7157
    let base = repo
7158
        .load_state_history(&[first.hash])
7159
        .unwrap()
7160
        .tree()
7161
        .view();
7162
    assert_eq!(view.entries["d"].node, base.entries["d"].node);
7163
}
7164
7165
/// oxygen#30, the rest: a placement left under a directory another line
7166
/// removed is out of sight, so no diff reaches it; the merge that settles
7167
/// where the file is retires it.
7168
#[test]
7169
fn git_import_merge_retires_a_placement_under_a_removed_directory() {
7170
    hermetic();
7171
    if std::process::Command::new("git")
7172
        .arg("--version")
7173
        .output()
7174
        .is_err()
7175
    {
7176
        eprintln!("git not installed; skipping");
7177
        return;
7178
    }
7179
    let dir = tempfile::tempdir().unwrap();
7180
    let root = dir.path();
7181
    let g = root.join("src.git");
7182
    fs::create_dir_all(&g).unwrap();
7183
    let run = |args: &[&str]| {
7184
        std::process::Command::new("git")
7185
            .arg("-C")
7186
            .arg(&g)
7187
            .args([
7188
                "-c",
7189
                "user.name=Grace",
7190
                "-c",
7191
                "[email protected]",
7192
                "-c",
7193
                "commit.gpgsign=false",
7194
            ])
7195
            .args(args)
7196
            .output()
7197
            .unwrap()
7198
    };
7199
    let git = |args: &[&str]| {
7200
        let out = run(args);
7201
        assert!(
7202
            out.status.success(),
7203
            "git {args:?}: {}",
7204
            String::from_utf8_lossy(&out.stderr)
7205
        );
7206
    };
7207
    git(&["init", "-q", "-b", "main"]);
7208
    write(&g, "c/x.txt", b"x\n");
7209
    write(&g, "keep.txt", b"k\n");
7210
    git(&["add", "."]);
7211
    git(&["commit", "-qm", "base"]);
7212
    // One line renames the file within c; the other moves it out of c,
7213
    // which goes.
7214
    git(&["checkout", "-qb", "side"]);
7215
    git(&["mv", "c/x.txt", "c/y.txt"]);
7216
    git(&["commit", "-qm", "rename within c"]);
7217
    git(&["checkout", "-q", "main"]);
7218
    fs::create_dir_all(g.join("n")).unwrap();
7219
    git(&["mv", "c/x.txt", "n/x.txt"]);
7220
    git(&["commit", "-qm", "move out of c"]);
7221
    // Git cannot merge the two renames; the merge keeps n/x.txt.
7222
    let _ = run(&["merge", "-q", "side"]);
7223
    let _ = run(&[
7224
        "rm",
7225
        "-q",
7226
        "--cached",
7227
        "--ignore-unmatch",
7228
        "c/y.txt",
7229
        "c/x.txt",
7230
    ]);
7231
    let _ = std::fs::remove_dir_all(g.join("c"));
7232
    write(&g, "n/x.txt", b"x\n");
7233
    git(&["add", "-A"]);
7234
    git(&["commit", "-qm", "merge: keep n/x.txt"]);
7235
7236
    let repo = Repo::init(&root.join("o")).unwrap();
7237
    repo.import_git(&g, "main").unwrap();
7238
    let v = repo.verify_git_import(&g, "main").unwrap();
7239
    assert!(v.mismatches.is_empty(), "{:?}", v.mismatches);
7240
    let st = repo
7241
        .load_state_history(&repo.bookmark_heads().unwrap())
7242
        .unwrap();
7243
    let view = st.tree().view();
7244
    assert!(view.conflicts.is_empty(), "{:?}", view.conflicts);
7245
    assert!(view.entries.contains_key("n/x.txt"));
7246
}
7247
7248
/// oxygen#30, orphans: a file added on one line into a directory the other
7249
/// line removed is placed where the tree cannot show it; Git's merge keeps
7250
/// the file, and the import's merge leaves exactly one of it.
7251
#[test]
7252
fn git_import_merge_leaves_no_orphan_behind() {
7253
    hermetic();
7254
    if std::process::Command::new("git")
7255
        .arg("--version")
7256
        .output()
7257
        .is_err()
7258
    {
7259
        eprintln!("git not installed; skipping");
7260
        return;
7261
    }
7262
    let dir = tempfile::tempdir().unwrap();
7263
    let root = dir.path();
7264
    let g = root.join("src.git");
7265
    fs::create_dir_all(&g).unwrap();
7266
    let git = |args: &[&str]| {
7267
        let out = std::process::Command::new("git")
7268
            .arg("-C")
7269
            .arg(&g)
7270
            .args([
7271
                "-c",
7272
                "user.name=Grace",
7273
                "-c",
7274
                "[email protected]",
7275
                "-c",
7276
                "commit.gpgsign=false",
7277
            ])
7278
            .args(args)
7279
            .output()
7280
            .unwrap();
7281
        assert!(
7282
            out.status.success(),
7283
            "git {args:?}: {}",
7284
            String::from_utf8_lossy(&out.stderr)
7285
        );
7286
    };
7287
    git(&["init", "-q", "-b", "main"]);
7288
    write(&g, "d/f.txt", b"f\n");
7289
    write(&g, "keep.txt", b"k\n");
7290
    git(&["add", "."]);
7291
    git(&["commit", "-qm", "base"]);
7292
    git(&["checkout", "-qb", "side"]);
7293
    write(&g, "d/new.txt", b"new\n");
7294
    git(&["add", "."]);
7295
    git(&["commit", "-qm", "add into d"]);
7296
    git(&["checkout", "-q", "main"]);
7297
    git(&["rm", "-q", "d/f.txt"]);
7298
    git(&["commit", "-qm", "d goes"]);
7299
    git(&["merge", "-q", "--no-edit", "side"]);
7300
7301
    let repo = Repo::init(&root.join("o")).unwrap();
7302
    repo.import_git(&g, "main").unwrap();
7303
    let v = repo.verify_git_import(&g, "main").unwrap();
7304
    assert!(v.mismatches.is_empty(), "{:?}", v.mismatches);
7305
    let st = repo
7306
        .load_state_history(&repo.bookmark_heads().unwrap())
7307
        .unwrap();
7308
    let view = st.tree().view();
7309
    assert!(view.conflicts.is_empty(), "{:?}", view.conflicts);
7310
    assert!(view.entries.contains_key("d/new.txt"));
7311
}
7312
7313
/// fsck checks a change's text as the blobs it is stored in, without
7314
/// decoding it: a missing text blob is an error named for the change.
7315
#[test]
7316
fn fsck_names_a_missing_text_blob() {
7317
    hermetic();
7318
    let dir = tempfile::tempdir().unwrap();
7319
    let root = dir.path();
7320
    let repo = Repo::init(root).unwrap();
7321
    let big: String = (0..3000).map(|i| format!("line {i}\n")).collect();
7322
    write(root, "big.txt", big.as_bytes());
7323
    let h = repo.commit("big", &[]).unwrap();
7324
    assert_eq!(repo.fsck().unwrap().errors(), 0);
7325
    let (_, texts) = repo.store().get_change_lazy(&h).unwrap();
7326
    let Some(crate::objects::TextRef::Blob(b, _, _)) = texts.first().copied() else {
7327
        panic!("a stored text")
7328
    };
7329
    repo.store().remove_loose_for_test(&b).unwrap();
7330
    let rep = repo.fsck().unwrap();
7331
    assert!(rep.errors() > 0);
7332
    assert!(
7333
        rep.problems.iter().any(|p| p.what.contains(&h.short(12))),
7334
        "{:?}",
7335
        rep.problems
7336
    );
7337
}
7338
7339
/// oxygen#32: a subrepo on the same hub as one of the parent's remotes is
7340
/// reached with that remote's token and CA (a private subrepo then clones
7341
/// for anyone who can read the parent); another hub gets none of them.
7342
#[test]
7343
fn a_subrepo_on_the_parents_hub_borrows_its_credentials() {
7344
    hermetic();
7345
    let dir = tempfile::tempdir().unwrap();
7346
    let mut repo = Repo::init(dir.path()).unwrap();
7347
    repo.config
7348
        .set(
7349
            "remote.origin.url",
7350
            "https://Hub.example:7343/doomsdayone/metalgear",
7351
        )
7352
        .unwrap();
7353
    repo.config.set("remote.origin.token", "secret").unwrap();
7354
    repo.config
7355
        .set("remote.origin.ca", "/tmp/hub-ca.pem")
7356
        .unwrap();
7357
    let same = repo.credentials_for("https://hub.example:7343/doomsdayone/rstar-api");
7358
    assert_eq!(same.token.as_deref(), Some("secret"));
7359
    assert_eq!(same.ca.as_deref(), Some(Path::new("/tmp/hub-ca.pem")));
7360
    for other in [
7361
        "https://elsewhere.example:7343/doomsdayone/rstar-api",
7362
        "https://hub.example/doomsdayone/rstar-api",
7363
        "http://hub.example:7343/doomsdayone/rstar-api",
7364
    ] {
7365
        let o = repo.credentials_for(other);
7366
        assert_ne!(o.token.as_deref(), Some("secret"), "{other}");
7367
    }
7368
}
7369
7370
/// oxygen#47: a remote with no token of its own uses the user's credential
7371
/// store for its hub, and a nested checkout finds its parent's remote
7372
/// token there instead of keeping a copy.
7373
#[test]
7374
fn remotes_use_the_credential_store_and_the_enclosing_checkout() {
7375
    hermetic();
7376
    let home = tempfile::tempdir().unwrap();
7377
    let dir = tempfile::tempdir().unwrap();
7378
    let mut parent = Repo::init(dir.path()).unwrap().with_home(home.path());
7379
    parent
7380
        .config
7381
        .set("remote.origin.url", "https://hub.example/o/parent")
7382
        .unwrap();
7383
    parent.save_config().unwrap();
7384
    assert_eq!(parent.remote_options("origin").token, None);
7385
    crate::credentials::Credentials::at(home.path())
7386
        .save("https://hub.example", "stored", Some("andy"), None)
7387
        .unwrap();
7388
    assert_eq!(
7389
        parent.remote_options("origin").token.as_deref(),
7390
        Some("stored")
7391
    );
7392
7393
    let empty_home = tempfile::tempdir().unwrap();
7394
    let nested = dir.path().join("deps").join("child");
7395
    let mut child = Repo::init(&nested).unwrap().with_home(empty_home.path());
7396
    child
7397
        .config
7398
        .set("remote.origin.url", "https://hub.example/o/child")
7399
        .unwrap();
7400
    child.save_config().unwrap();
7401
    assert_eq!(child.remote_options("origin").token, None);
7402
    parent
7403
        .config
7404
        .set("remote.origin.token", "checkout")
7405
        .unwrap();
7406
    parent.save_config().unwrap();
7407
    assert_eq!(
7408
        child.remote_options("origin").token.as_deref(),
7409
        Some("checkout")
7410
    );
7411
    // Another hub's checkout token is not borrowed.
7412
    child
7413
        .config
7414
        .set("remote.origin.url", "https://other.example/o/child")
7415
        .unwrap();
7416
    assert_eq!(child.remote_options("origin").token, None);
7417
}
7418
7419
#[test]
7420
fn the_metadata_cache_survives_a_torn_tail() {
7421
    hermetic();
7422
    let dir = tempfile::tempdir().unwrap();
7423
    let root = dir.path();
7424
    let repo = Repo::init(root).unwrap();
7425
    write(root, "a.txt", b"1\n");
7426
    let h = repo.commit("first", &[]).unwrap();
7427
    let meta = repo.store().get_change_meta(&h).unwrap();
7428
    let cache = repo.store().dir().join("metas");
7429
    let len = fs::metadata(&cache).unwrap().len();
7430
    assert!(len > 0, "a change read is cached");
7431
    // A torn record at the end: the cache reads up to it and cuts it off.
7432
    fs::OpenOptions::new()
7433
        .append(true)
7434
        .open(&cache)
7435
        .unwrap()
7436
        .write_all(&[7; 20])
7437
        .unwrap();
7438
    let again = Repo::open(root).unwrap();
7439
    assert_eq!(again.store().get_change_meta(&h).unwrap(), meta);
7440
    assert_eq!(fs::metadata(&cache).unwrap().len(), len);
7441
}
7442
7443
#[test]
7444
fn a_manifest_that_does_not_check_reads_as_none() {
7445
    hermetic();
7446
    let dir = tempfile::tempdir().unwrap();
7447
    let root = dir.path();
7448
    let repo = Repo::init(root).unwrap();
7449
    write(root, "a.txt", b"1\n");
7450
    repo.commit("first", &[]).unwrap();
7451
    let path = repo.manifest_path();
7452
    let mut bytes = fs::read(&path).unwrap();
7453
    assert!(Repo::open(root).unwrap().read_manifest().unwrap().is_some());
7454
    let last = bytes.len() - 1;
7455
    bytes[last] ^= 1;
7456
    fs::write(&path, &bytes).unwrap();
7457
    assert!(Repo::open(root).unwrap().read_manifest().unwrap().is_none());
7458
    // The next status reads the files and writes it again.
7459
    let again = Repo::open(root).unwrap();
7460
    assert!(!again.snapshot("status").unwrap().changed);
7461
    assert!(again.read_manifest().unwrap().is_some());
7462
}
7463
7464
#[test]
7465
fn a_commit_leaves_a_manifest_that_proves_the_working_copy_clean() {
7466
    hermetic();
7467
    let dir = tempfile::tempdir().unwrap();
7468
    let root = dir.path();
7469
    let repo = Repo::init(root).unwrap();
7470
    write(root, "a.txt", b"1\n");
7471
    write(root, "b.txt", b"2\n");
7472
    // b.txt outside the racy window, so snapshots take it as unchanged.
7473
    let old = std::time::SystemTime::now() - std::time::Duration::from_secs(60);
7474
    fs::File::options()
7475
        .write(true)
7476
        .open(root.join("b.txt"))
7477
        .unwrap()
7478
        .set_modified(old)
7479
        .unwrap();
7480
    repo.commit("first", &[]).unwrap();
7481
    assert!(repo.clean_by_manifest().unwrap(), "after the first commit");
7482
    repo.snapshot_status("status").unwrap();
7483
    write(root, "a.txt", b"1\n2\n");
7484
    repo.commit("second", &[]).unwrap();
7485
    assert!(
7486
        repo.clean_by_manifest().unwrap(),
7487
        "after a commit of one file"
7488
    );
7489
    // Edited, seen by a status, edited again, then committed: the status
7490
    // left the first edit's stat, which the commit must not keep.
7491
    write(root, "a.txt", b"1\n2\n3\n");
7492
    repo.snapshot_status("status").unwrap();
7493
    write(root, "a.txt", b"1\n2\n3\n4\n5\n");
7494
    repo.commit("third", &[]).unwrap();
7495
    assert!(
7496
        repo.clean_by_manifest().unwrap(),
7497
        "after an edit a status saw"
7498
    );
7499
}
7500
7501
#[test]
7502
fn a_conflicted_rebase_can_be_resolved_in_the_working_copy() {
7503
    hermetic();
7504
    let dir = tempfile::tempdir().unwrap();
7505
    let root = dir.path();
7506
    let mut repo = Repo::init(root).unwrap().with_home(root.join("home"));
7507
    write(root, "a.txt", b"1\n2\n");
7508
    let a = repo.commit("A", &[]).unwrap();
7509
    repo.bookmark_create("develop", Some(&[a])).unwrap();
7510
    write(root, "a.txt", b"1\nX\n");
7511
    let c = repo.commit("C: 2 to X", &[]).unwrap();
7512
    repo.bookmark_switch("develop", false).unwrap();
7513
    write(root, "a.txt", b"1\nY\n");
7514
    let d = repo.commit("D: 2 to Y", &[]).unwrap();
7515
    repo.bookmark_switch("main", false).unwrap();
7516
7517
    let err = repo.rebase(&c, &[d]).unwrap_err();
7518
    assert!(matches!(err, RepoError::Conflicted(_)), "{err}");
7519
    let r = repo.rebase_into_working_copy(&c, &[d]).unwrap();
7520
    assert!(r.changed && r.checked_out);
7521
    let snap = repo.snapshot_status("status").unwrap();
7522
    assert!(
7523
        snap.base_snapshot.is_conflicted(),
7524
        "the conflict is in the working copy"
7525
    );
7526
    let text = fs::read_to_string(root.join("a.txt")).unwrap();
7527
    assert!(text.contains('X') && text.contains('Y'), "{text}");
7528
7529
    write(root, "a.txt", b"1\nXY\n");
7530
    repo.commit("Resolve", &[]).unwrap();
7531
    let st = repo.load_state(&repo.bookmark_heads().unwrap()).unwrap();
7532
    assert!(st.contains(&c) && st.contains(&d));
7533
    let files = st.materialize().files;
7534
    assert!(!files["a.txt"].is_conflicted());
7535
    assert!(
7536
        matches!(&files["a.txt"].content, FileContent::Text { bytes, .. } if bytes == b"1\nXY\n")
7537
    );
7538
7539
    // A change the current bookmark does not hold is refused.
7540
    repo.bookmark_switch("develop", false).unwrap();
7541
    write(root, "b.txt", b"b\n");
7542
    let e = repo.commit("E", &[]).unwrap();
7543
    repo.bookmark_switch("main", false).unwrap();
7544
    let err = repo.rebase_into_working_copy(&e, &[a]).unwrap_err();
7545
    assert!(
7546
        err.to_string().contains("not on the current bookmark"),
7547
        "{err}"
7548
    );
7549
}
7550
7551
#[test]
7552
fn an_ignore_rule_drops_an_added_file_but_not_a_tracked_one() {
7553
    hermetic();
7554
    let dir = tempfile::tempdir().unwrap();
7555
    let root = dir.path();
7556
    let repo = Repo::init(root).unwrap();
7557
    write(root, "a.txt", b"a\n");
7558
    write(root, "kept.log", b"tracked\n");
7559
    repo.commit("first", &[]).unwrap();
7560
    write(root, "build.log", b"made\n");
7561
    let snap = repo.snapshot_status("status").unwrap();
7562
    assert!(snap.statuses.iter().any(|s| s.path == "build.log"));
7563
    // A rule written afterwards leaves the added file out again, while the
7564
    // committed one stays tracked.
7565
    write(root, ".gitignore", b"*.log\n");
7566
    let snap = repo.snapshot_status("status").unwrap();
7567
    let paths: Vec<&str> = snap.statuses.iter().map(|s| s.path.as_str()).collect();
7568
    assert_eq!(paths, vec![".gitignore"], "{paths:?}");
7569
    write(root, "kept.log", b"tracked, edited\n");
7570
    let snap = repo.snapshot_status("status").unwrap();
7571
    assert!(snap.statuses.iter().any(|s| s.path == "kept.log"));
7572
}
7573
7574
#[test]
7575
fn shed_graphs_come_back_the_same() {
7576
    hermetic();
7577
    let dir = tempfile::tempdir().unwrap();
7578
    let root = dir.path();
7579
    let repo = Repo::init(root).unwrap();
7580
    write(root, "a.txt", b"1\n2\n3\n");
7581
    write(root, "b.txt", b"x\n");
7582
    repo.commit("first", &[]).unwrap();
7583
    write(root, "a.txt", b"1\ntwo\n3\n4\n");
7584
    repo.commit("second", &[]).unwrap();
7585
    let heads = repo.bookmark_heads().unwrap();
7586
    let mut st = repo.load_state_history(&heads).unwrap();
7587
    let view = st.tree().view();
7588
    let nodes: Vec<NodeId> = ["a.txt", "b.txt"]
7589
        .iter()
7590
        .map(|p| view.entries[*p].node)
7591
        .collect();
7592
    repo.load_graphs_of(&mut st, &nodes).unwrap();
7593
    let before: Vec<Vec<u8>> = nodes.iter().map(|n| st.render_file(n).0).collect();
7594
    assert_eq!(st.built_count(), 2);
7595
    let shed = st.shed_graphs(|b| repo.store_blob(b)).unwrap();
7596
    assert_eq!((shed, st.built_count()), (2, 0));
7597
    // A later change applies on top of the shed history.
7598
    write(root, "a.txt", b"1\ntwo\n3\n4\n5\n");
7599
    let h3 = repo.commit("third", &[]).unwrap();
7600
    let (skeleton, texts) = repo.store().get_change_lazy(&h3).unwrap();
7601
    st.add_known(h3, skeleton, texts);
7602
    repo.load_graphs_of(&mut st, &nodes).unwrap();
7603
    let after: Vec<Vec<u8>> = nodes.iter().map(|n| st.render_file(n).0).collect();
7604
    assert_eq!(after[1], before[1]);
7605
    assert_eq!(after[0], b"1\ntwo\n3\n4\n5\n");
7606
}
7607
7608
#[test]
7609
fn many_edited_files_diff_in_parallel() {
7610
    // Enough edited files that the builder diffs them in parallel; the
7611
    // commit must hold exactly what is on disk, and a second snapshot
7612
    // must find nothing left to commit.
7613
    hermetic();
7614
    let dir = tempfile::tempdir().unwrap();
7615
    let root = dir.path();
7616
    let repo = Repo::init(root).unwrap();
7617
    let text = |i: usize, round: usize| {
7618
        let mut s = String::new();
7619
        for line in 0..50 {
7620
            if round > 0 && line % 7 == i % 7 {
7621
                s.push_str(&format!("edited {round} {i} {line}\n"));
7622
            } else {
7623
                s.push_str(&format!("file {i} line {line}\n"));
7624
            }
7625
        }
7626
        if round > 0 && i.is_multiple_of(3) {
7627
            s.push_str("appended\n");
7628
        }
7629
        s
7630
    };
7631
    for i in 0..40 {
7632
        write(root, &format!("d/f{i}.txt"), text(i, 0).as_bytes());
7633
    }
7634
    repo.commit("first", &[]).unwrap();
7635
    for i in 0..40 {
7636
        write(root, &format!("d/f{i}.txt"), text(i, 1).as_bytes());
7637
    }
7638
    let h = repo.commit("edit every file", &[]).unwrap();
7639
    let snap = repo.load_state(&[h]).unwrap().materialize();
7640
    for i in 0..40 {
7641
        let want = text(i, 1);
7642
        assert!(
7643
            matches!(&snap.files[&format!("d/f{i}.txt")].content, FileContent::Text { bytes, .. } if bytes == want.as_bytes()),
7644
            "d/f{i}.txt as committed"
7645
        );
7646
    }
7647
    assert!(
7648
        repo.commit("nothing", &[]).is_err(),
7649
        "nothing left to commit"
7650
    );
7651
}
7652
7653
/// oxygen#56: after a fetch, how a bookmark stands against its remote copy
7654
/// is known (fetch printed "up to date" while main was behind), a change
7655
/// only fetched resolves and says where it is, and a checkout whose only
7656
/// remote is not `origin` uses that one.
7657
#[test]
7658
fn a_fetched_change_shows_as_behind_and_resolves() {
7659
    hermetic();
7660
    let dir = tempfile::tempdir().unwrap();
7661
    let root = dir.path();
7662
    let origin = Repo::init(&root.join("origin")).unwrap();
7663
    drop(origin);
7664
    let url = root.join("origin").to_string_lossy().to_string();
7665
    let a = Repo::clone(&url, &root.join("a"))
7666
        .unwrap()
7667
        .with_home(root.join("home-a"));
7668
    write(&root.join("a"), "f.txt", b"one\n");
7669
    a.commit("one", &[]).unwrap();
7670
    a.push("origin", false).unwrap();
7671
    let b = Repo::clone(&url, &root.join("b"))
7672
        .unwrap()
7673
        .with_home(root.join("home-b"));
7674
    assert_eq!(b.tracking("origin", "main").unwrap(), Some((0, 0)));
7675
7676
    write(&root.join("a"), "f.txt", b"one\ntwo\n");
7677
    let h2 = a.commit("two", &[]).unwrap();
7678
    a.push("origin", false).unwrap();
7679
    b.fetch("origin").unwrap();
7680
    // Fetched, not pulled: one behind, the change found and placed.
7681
    assert_eq!(b.tracking("origin", "main").unwrap(), Some((0, 1)));
7682
    assert_eq!(b.tracking("origin", "nope").unwrap(), None);
7683
    assert_eq!(
7684
        b.resolve_change(&format!("#{}", &h2.to_hex()[..12]))
7685
            .unwrap(),
7686
        h2
7687
    );
7688
    assert_eq!(
7689
        b.remote_only_location(&h2).unwrap().as_deref(),
7690
        Some("origin/main")
7691
    );
7692
    // Fetching again changes nothing: still behind, which is what the
7693
    // CLI now says rather than "up to date".
7694
    b.fetch("origin").unwrap();
7695
    assert_eq!(b.tracking("origin", "main").unwrap(), Some((0, 1)));
7696
    b.pull("origin").unwrap();
7697
    assert_eq!(b.tracking("origin", "main").unwrap(), Some((0, 0)));
7698
    assert_eq!(b.remote_only_location(&h2).unwrap(), None);
7699
7700
    // One remote, not called origin: it is the default.
7701
    let mut c = Repo::init(&root.join("c")).unwrap();
7702
    assert_eq!(c.default_remote(), "origin");
7703
    c.config.set("remote.earth.url", &url).unwrap();
7704
    assert_eq!(c.default_remote(), "earth");
7705
    c.config.set("remote.origin.url", &url).unwrap();
7706
    assert_eq!(c.default_remote(), "origin");
7707
}
7708
7709
/// oxygen#57: a clone from a relative local path records the remote as an
7710
/// absolute path, so fetch still finds it from inside the clone.
7711
#[test]
7712
fn a_clone_from_a_relative_path_records_it_absolute() {
7713
    hermetic();
7714
    let dir = tempfile::tempdir().unwrap();
7715
    let root = dir.path();
7716
    Repo::init(&root.join("origin")).unwrap();
7717
    let rel = crate::protocol::stored_url("relative/repo");
7718
    assert!(std::path::Path::new(&rel).is_absolute(), "{rel}");
7719
    assert_eq!(
7720
        crate::protocol::stored_url("https://hub.example/o/n"),
7721
        "https://hub.example/o/n"
7722
    );
7723
    assert!(crate::protocol::stored_url("file://x").starts_with("file:///"));
7724
    assert!(crate::protocol::stored_url("dir://x").starts_with("dir:///"));
7725
    // A bucket is kept as written: it is not a path.
7726
    assert_eq!(
7727
        crate::protocol::stored_url("s3://bucket/prefix?profile=p"),
7728
        "s3://bucket/prefix?profile=p"
7729
    );
7730
    let url = root.join("origin").to_string_lossy().to_string();
7731
    let b = Repo::clone(&url, &root.join("b")).unwrap();
7732
    assert_eq!(b.config.remotes["origin"], url);
7733
    b.fetch("origin").unwrap();
7734
}
7735
7736
/// oxygen#60 and #61: a workspace added on a bookmark is on that bookmark,
7737
/// and gets its subrepos at their pins from this workspace's copies, with
7738
/// their remotes pointing where the subrepos come from.
7739
#[test]
7740
fn a_workspace_added_on_a_bookmark_is_on_it_with_its_subrepos() {
7741
    hermetic();
7742
    let dir = tempfile::tempdir().unwrap();
7743
    let root = dir.path();
7744
    Repo::init(&root.join("lib-origin")).unwrap();
7745
    let lib_url = root.join("lib-origin").to_string_lossy().to_string();
7746
    let lib = Repo::clone(&lib_url, &root.join("lib"))
7747
        .unwrap()
7748
        .with_home(root.join("home"));
7749
    write(&root.join("lib"), "lib.txt", b"v1\n");
7750
    let l1 = lib.commit("lib v1", &[]).unwrap();
7751
    assert!(lib.push("origin", false).unwrap()[0].ok);
7752
7753
    let app_dir = root.join("app");
7754
    let app = Repo::init(&app_dir).unwrap().with_home(root.join("home"));
7755
    write(&app_dir, "main.txt", b"app\n");
7756
    app.submodule_add(&lib_url, "libs/lib", None).unwrap();
7757
    app.commit("app with lib", &[]).unwrap();
7758
    // A second bookmark, and the main workspace on another.
7759
    app.bookmark_create("develop", None).unwrap();
7760
    app.bookmark_create("feature", None).unwrap();
7761
    let mut app = app;
7762
    app.bookmark_switch("feature", false).unwrap();
7763
    assert_eq!(app.config.bookmark, "feature");
7764
7765
    // The library's origin goes away: the subrepo must come from here.
7766
    std::fs::rename(root.join("lib-origin"), root.join("lib-origin-gone")).unwrap();
7767
    let heads = app.resolve_heads("develop").unwrap();
7768
    let ws = app
7769
        .workspace_add_on(&root.join("ws"), Some(&heads), Some("develop"))
7770
        .unwrap();
7771
    assert_eq!(
7772
        ws.config.bookmark, "develop",
7773
        "the new workspace is on develop"
7774
    );
7775
    assert_eq!(
7776
        app.config.bookmark, "feature",
7777
        "and this one stays on its own"
7778
    );
7779
    let sub = Repo::open(&root.join("ws/libs/lib")).unwrap();
7780
    assert_eq!(
7781
        sub.config.remotes["origin"], lib_url,
7782
        "its origin is the subrepo's URL"
7783
    );
7784
    assert_eq!(sub.bookmark_heads().unwrap(), vec![l1], "at its pin");
7785
    assert_eq!(
7786
        std::fs::read(root.join("ws/libs/lib/lib.txt")).unwrap(),
7787
        b"v1\n"
7788
    );
7789
}
7790
7791
/// Revsets (docs/revset_query_language.md): symbols, relations, set
7792
/// operators and the predicates, over a small graph with two heads and
7793
/// a rename.
7794
#[test]
7795
fn revsets_select_changes_by_relation_author_text_date_and_path() {
7796
    hermetic();
7797
    let dir = tempfile::tempdir().unwrap();
7798
    let root = dir.path();
7799
    let mut repo = Repo::init(root).unwrap().with_home(root.join("home"));
7800
    repo.create_identity("Ada", "[email protected]", IdentityScope::User)
7801
        .unwrap();
7802
    write(root, "src/a.rs", b"one\n");
7803
    let a = repo.commit("first: add a", &[]).unwrap();
7804
    write(root, "src/a.rs", b"one\ntwo\n");
7805
    let b = repo.commit("second: grow a", &[]).unwrap();
7806
    // A second head, independent of b: a new file on top of a.
7807
    repo.checkout(&[a], false, "checkout a").unwrap();
7808
    write(root, "docs/notes.md", b"notes\n");
7809
    let c = repo.commit("third: notes", &[]).unwrap();
7810
    // Back to both heads, then rename a.rs: the node keeps its identity.
7811
    repo.checkout(&repo.bookmark_heads().unwrap(), false, "checkout main")
7812
        .unwrap();
7813
    fs::remove_file(root.join("src/a.rs")).unwrap();
7814
    write(root, "src/z.rs", b"one\ntwo\n");
7815
    let d = repo.commit("fourth: rename a to z", &[]).unwrap();
7816
    let wc = repo.working_copy().unwrap().0;
7817
    // A saved revset is checked when set.
7818
    repo.set_user_config("revset.mine", "author(me) & ::main")
7819
        .unwrap();
7820
    assert!(repo.set_user_config("revset.bad", "a &").is_err());
7821
    let set = |src: &str| -> Vec<ChangeHash> {
7822
        let mut v = repo.revset(src).unwrap().hashes;
7823
        v.sort();
7824
        v
7825
    };
7826
    let sorted = |hs: &[ChangeHash]| -> Vec<ChangeHash> {
7827
        let mut v = hs.to_vec();
7828
        v.sort();
7829
        v
7830
    };
7831
7832
    // Changes commute: a new file depends on nothing and the rename on the
7833
    // file's creation, so the graph is a, b->a, d->a, c, and the working
7834
    // copy on the three heads b, c, d.
7835
    let heads = sorted(&repo.bookmark_heads().unwrap());
7836
    let meta = |h: &ChangeHash| repo.store().get_change_meta(h).unwrap();
7837
    assert!(heads.contains(&d) && heads.contains(&c));
7838
    // Symbols and closures.
7839
    assert_eq!(set("main"), heads);
7840
    assert_eq!(set("::main"), sorted(&[a, b, c, d]));
7841
    assert_eq!(set("@"), vec![wc]);
7842
    assert_eq!(set("::@"), sorted(&[a, b, c, d, wc]));
7843
    assert_eq!(set(&format!("::#{}", b.short(12))), sorted(&[a, b]));
7844
    assert_eq!(set(&format!("#{}::", a.short(12))), sorted(&[a, b, d, wc]));
7845
    assert_eq!(
7846
        set(&format!("#{}::#{}", a.short(12), b.short(12))),
7847
        sorted(&[a, b])
7848
    );
7849
    // Ranges: what main has beyond b, and `..` forms.
7850
    assert_eq!(set(&format!("#{}..main", b.short(12))), sorted(&[c, d]));
7851
    assert_eq!(set(&format!("#{}..", c.short(12))), sorted(&[a, b, d, wc]));
7852
    assert_eq!(set("..main"), sorted(&[a, b, c, d]));
7853
    // Operators and precedence: ~ binds tighter than &, & than |.
7854
    assert_eq!(
7855
        set(&format!("::main ~ #{}", d.short(12))),
7856
        sorted(&[a, b, c])
7857
    );
7858
    assert_eq!(
7859
        set(&format!("::main & #{} | #{}", b.short(12), c.short(12))),
7860
        sorted(&[b, c])
7861
    );
7862
    assert_eq!(set("all() ~ ::main"), vec![wc]);
7863
    // Relations.
7864
    let mut head_deps: Vec<ChangeHash> = heads.iter().flat_map(|h| meta(h).deps).collect();
7865
    head_deps.sort();
7866
    head_deps.dedup();
7867
    assert_eq!(set("deps(main)"), head_deps);
7868
    let on_a: Vec<ChangeHash> = [b, c, d]
7869
        .into_iter()
7870
        .filter(|h| meta(h).deps.contains(&a))
7871
        .collect();
7872
    assert_eq!(set(&format!("dependents(#{})", a.short(12))), sorted(&on_a));
7873
    assert_eq!(set("heads(::main)"), heads);
7874
    assert_eq!(set("roots(::main)"), sorted(&[a, c]));
7875
    assert_eq!(
7876
        set(&format!(
7877
            "heads(#{} | #{} | #{})",
7878
            a.short(12),
7879
            b.short(12),
7880
            c.short(12)
7881
        )),
7882
        sorted(&[b, c])
7883
    );
7884
    assert_eq!(set("latest(::main, 1)"), vec![d]);
7885
    assert_eq!(set("kind(working-copy)"), vec![wc]);
7886
    assert_eq!(set("none()"), vec![]);
7887
    // Predicates: author by name, email, key prefix and `me`.
7888
    let key = repo.config.author_key.unwrap();
7889
    assert_eq!(set("author(ada) & ::main"), sorted(&[a, b, c, d]));
7890
    assert_eq!(set("author(\"[email protected]\") & ::main").len(), 4);
7891
    assert_eq!(set(&format!("author({}) & ::main", key.short(12))).len(), 4);
7892
    assert_eq!(set("author(me) & ::main").len(), 4);
7893
    assert_eq!(set("author(nobody)"), vec![]);
7894
    assert_eq!(set("description(notes)"), vec![c]);
7895
    assert_eq!(set("description(\"rename a\")"), vec![d]);
7896
    assert_eq!(set("date(-1h..) & ::main").len(), 4);
7897
    assert_eq!(set("date(..2000-01-01)"), vec![]);
7898
    // touches follows the node through the rename, in the current state.
7899
    assert_eq!(set("touches(\"src/z.rs\")"), sorted(&[a, b, d]));
7900
    assert_eq!(set("touches(\"src/**\") & ::main"), sorted(&[a, b, d]));
7901
    assert_eq!(set("touches(\"docs/*\")"), vec![c]);
7902
    assert_eq!(set("touches(\"nothing/*\")"), vec![]);
7903
    // Newest first in the result order.
7904
    assert_eq!(repo.revset("::main").unwrap().hashes[0], d);
7905
    // The saved revset, and errors that say what is wrong.
7906
    assert_eq!(set("mine()").len(), 4);
7907
    let e = repo.revset("nosuch()").unwrap_err().to_string();
7908
    assert!(e.contains("unknown function nosuch()"), "{e}");
7909
    let e = repo.revset("main &").unwrap_err().to_string();
7910
    assert!(e.contains("at character"), "{e}");
7911
    let e = repo.revset("zzzz").unwrap_err().to_string();
7912
    assert!(e.contains("no change matches"), "{e}");
7913
    let e = repo
7914
        .revset_with_budget("::main", std::time::Duration::ZERO)
7915
        .unwrap_err()
7916
        .to_string();
7917
    assert!(e.contains("budget"), "{e}");
7918
    // The log entries carry the bookmark's heads and the working copy.
7919
    let entries = repo.log_revset("::@").unwrap();
7920
    assert!(entries[0].is_working_copy && entries.iter().any(|e| e.is_head && e.hash == d));
7921
    // Trust predicates (§2.4): nothing is signed yet (core.sign = seal, no
7922
    // push); then a signed change, a tag, and a revocation.
7923
    assert_eq!(set("unsigned() & ::main"), sorted(&[a, b, c, d]));
7924
    assert_eq!(set("signed_by(me)"), vec![]);
7925
    repo.sign_change(&d).unwrap();
7926
    assert_eq!(set("signed_by(me)"), vec![d]);
7927
    assert_eq!(set("signed_by([email protected])"), vec![d]);
7928
    assert_eq!(set(&format!("signed_by({})", key.short(12))), vec![d]);
7929
    assert_eq!(set("unsigned() & ::main"), sorted(&[a, b, c]));
7930
    assert_eq!(set("delegated()"), vec![]);
7931
    assert_eq!(set("revoked()"), vec![]);
7932
    assert_eq!(set("attested(tag)"), vec![]);
7933
    repo.tag_create("v1", &[b], "first").unwrap();
7934
    assert_eq!(set("attested(tag)"), sorted(&[a, b]));
7935
    assert_eq!(set("attested(tag) & unsigned()"), sorted(&[a, b]));
7936
    assert_eq!(set("attested(receipt)"), vec![]);
7937
    assert_eq!(set("built(test)"), vec![]);
7938
    let e = repo.revset("attested(seal)").unwrap_err().to_string();
7939
    assert!(e.contains("tag, receipt or ref"), "{e}");
7940
    repo.revoke_identity(&key, "test").unwrap();
7941
    assert_eq!(set("revoked()"), vec![d]);
7942
    assert_eq!(set("signed_by(me) ~ revoked()"), vec![]);
7943
}
7944
7945
#[test]
7946
fn a_rotation_is_recorded_wherever_the_old_key_was_named() {
7947
    let dir = tempfile::tempdir().unwrap();
7948
    let root = dir.path();
7949
    let home = root.join("home");
7950
    // Ada's identity lives in the user file; repository `a` pins the same
7951
    // key in its own file, repository `b` names none.
7952
    let mut a = Repo::init(&root.join("a")).unwrap().with_home(&home);
7953
    let (key, _) = a
7954
        .create_identity("Ada", "[email protected]", IdentityScope::User)
7955
        .unwrap();
7956
    a.config.set("author.key", &key.to_hex()).unwrap();
7957
    a.save_config().unwrap();
7958
    let agent = SecretKey::generate().identity("Agent", "[email protected]", 1);
7959
    let r = a
7960
        .delegate_add(agent.clone(), crate::identity::Scope::CHANGES, None)
7961
        .unwrap();
7962
    assert_eq!(
7963
        read_config_file(&home.join("config.toml")).unwrap()["author.key"],
7964
        r.new.to_hex(),
7965
        "the user file follows"
7966
    );
7967
    assert_eq!(
7968
        read_config_file(&root.join("a/.oxy/config")).unwrap()["author.key"],
7969
        r.new.to_hex(),
7970
        "the pinning repository follows"
7971
    );
7972
    let b = Repo::init(&root.join("b")).unwrap().with_home(&home);
7973
    assert_eq!(
7974
        b.config.author_key,
7975
        Some(r.new),
7976
        "a checkout without a pin follows the user file"
7977
    );
7978
    // A repository-scoped identity leaves the user file alone.
7979
    let other_home = root.join("home2");
7980
    let mut c = Repo::init(&root.join("c")).unwrap().with_home(&other_home);
7981
    let (ck, _) = c
7982
        .create_identity("Cy", "[email protected]", IdentityScope::Repo)
7983
        .unwrap();
7984
    assert!(!other_home.join("config.toml").exists());
7985
    let r2 = c.rotate_identity().unwrap();
7986
    assert_ne!(r2.new, ck);
7987
    assert_eq!(
7988
        read_config_file(&root.join("c/.oxy/config")).unwrap()["author.key"],
7989
        r2.new.to_hex()
7990
    );
7991
    assert!(
7992
        !other_home.join("config.toml").exists(),
7993
        "a repository-scoped identity stays repository-scoped"
7994
    );
7995
    // Several delegates in one rotation; a repeat is refused.
7996
    let (d1, d2) = (
7997
        SecretKey::generate().identity("D1", "d1@x", 1),
7998
        SecretKey::generate().identity("D2", "d2@x", 1),
7999
    );
8000
    let r3 = c
8001
        .delegate_add_many(vec![d1.clone(), d2], crate::identity::Scope::CHANGES, None)
8002
        .unwrap();
8003
    assert_eq!(r3.identity.delegates.len(), 2);
8004
    assert!(c
8005
        .delegate_add(d1, crate::identity::Scope::CHANGES, None)
8006
        .is_err());
8007
}
8008
8009
/// Two unrelated histories that both add the same file, joined by two
8010
/// independent merges on two branches, then those branches merged: Git
8011
/// merges identical additions cleanly, and the import must too (#71,
8012
/// found in VS Code's history).
8013
#[test]
8014
fn git_import_joins_unrelated_histories_that_add_the_same_file() {
8015
    // Batches of one: every merge renders apart from the state, where a
8016
    // file whose graph the state had built came out empty (#71).
8017
    crate::repo::git::set_merge_batch_for_tests(Some(1));
8018
    hermetic();
8019
    if std::process::Command::new("git")
8020
        .arg("--version")
8021
        .output()
8022
        .is_err()
8023
    {
8024
        eprintln!("git not installed; skipping");
8025
        return;
8026
    }
8027
    let dir = tempfile::tempdir().unwrap();
8028
    let root = dir.path();
8029
    let g = root.join("src.git");
8030
    fs::create_dir_all(&g).unwrap();
8031
    let git = |args: &[&str]| -> String {
8032
        let out = std::process::Command::new("git")
8033
            .arg("-C")
8034
            .arg(&g)
8035
            .args([
8036
                "-c",
8037
                "user.name=Grace",
8038
                "-c",
8039
                "[email protected]",
8040
                "-c",
8041
                "commit.gpgsign=false",
8042
            ])
8043
            .args(args)
8044
            .output()
8045
            .unwrap();
8046
        assert!(
8047
            out.status.success(),
8048
            "git {args:?}: {}",
8049
            String::from_utf8_lossy(&out.stderr)
8050
        );
8051
        String::from_utf8_lossy(&out.stdout).trim().to_string()
8052
    };
8053
    let text = b"/* header */\nconst a = 1;\nconst b = 2;\n";
8054
    // History A: main.
8055
    git(&["init", "-q", "-b", "main"]);
8056
    write(&g, "gulpfile.js", text);
8057
    write(&g, "a.txt", b"a\n");
8058
    git(&["add", "."]);
8059
    git(&["commit", "-q", "-m", "A root"]);
8060
    // History B: an unrelated root adding the same file, identical.
8061
    git(&["checkout", "-q", "--orphan", "fork"]);
8062
    git(&["rm", "-q", "-r", "--cached", "."]);
8063
    for f in ["gulpfile.js", "a.txt"] {
8064
        let _ = fs::remove_file(g.join(f));
8065
    }
8066
    write(&g, "gulpfile.js", text);
8067
    write(&g, "b.txt", b"b\n");
8068
    git(&["add", "."]);
8069
    git(&["commit", "-q", "-m", "B root"]);
8070
    // Two branches from main, each joining B on its own.
8071
    git(&["checkout", "-q", "-b", "one", "main"]);
8072
    git(&[
8073
        "merge",
8074
        "-q",
8075
        "--no-ff",
8076
        "--allow-unrelated-histories",
8077
        "-m",
8078
        "join on one",
8079
        "fork",
8080
    ]);
8081
    git(&["checkout", "-q", "-b", "two", "main"]);
8082
    write(&g, "a.txt", b"a\ntwo\n");
8083
    git(&["commit", "-q", "-am", "work on two"]);
8084
    git(&[
8085
        "merge",
8086
        "-q",
8087
        "--no-ff",
8088
        "--allow-unrelated-histories",
8089
        "-m",
8090
        "join on two",
8091
        "fork",
8092
    ]);
8093
    // Then the two joins meet, and the file is reformatted after.
8094
    git(&["checkout", "-q", "main"]);
8095
    git(&["merge", "-q", "--no-ff", "-m", "merge one", "one"]);
8096
    git(&["merge", "-q", "--no-ff", "-m", "merge two", "two"]);
8097
    write(
8098
        &g,
8099
        "gulpfile.js",
8100
        b"/* header */\nconst a = 1;\nconst b = 3;\n",
8101
    );
8102
    git(&["commit", "-q", "-am", "after"]);
8103
8104
    let dest = root.join("dest");
8105
    let repo = Repo::init(&dest).unwrap().with_home(root.join("home"));
8106
    repo.import_git(&g, "main").unwrap();
8107
    let v = repo.verify_git_import(&g, "main").unwrap();
8108
    assert!(v.mismatches.is_empty(), "{:?}", v.mismatches);
8109
    assert_eq!(
8110
        fs::read(dest.join("gulpfile.js")).unwrap(),
8111
        b"/* header */\nconst a = 1;\nconst b = 3;\n"
8112
    );
8113
}
8114
8115
/// As above, but the two joins keep different copies (each branch had a
8116
/// different version when it joined), and later work edits each copy:
8117
/// the shape of VS Code's c67ef57cda90 (#71).
8118
#[test]
8119
fn git_import_joins_where_each_join_kept_a_different_copy() {
8120
    // Batches of one: every merge renders apart from the state, where a
8121
    // file whose graph the state had built came out empty (#71).
8122
    crate::repo::git::set_merge_batch_for_tests(Some(1));
8123
    hermetic();
8124
    if std::process::Command::new("git")
8125
        .arg("--version")
8126
        .output()
8127
        .is_err()
8128
    {
8129
        eprintln!("git not installed; skipping");
8130
        return;
8131
    }
8132
    let dir = tempfile::tempdir().unwrap();
8133
    let root = dir.path();
8134
    let g = root.join("src.git");
8135
    fs::create_dir_all(&g).unwrap();
8136
    let run = |args: &[&str]| {
8137
        std::process::Command::new("git")
8138
            .arg("-C")
8139
            .arg(&g)
8140
            .args([
8141
                "-c",
8142
                "user.name=Grace",
8143
                "-c",
8144
                "[email protected]",
8145
                "-c",
8146
                "commit.gpgsign=false",
8147
            ])
8148
            .args(args)
8149
            .output()
8150
            .unwrap()
8151
    };
8152
    let git = |args: &[&str]| -> String {
8153
        let out = run(args);
8154
        assert!(
8155
            out.status.success(),
8156
            "git {args:?}: {}",
8157
            String::from_utf8_lossy(&out.stderr)
8158
        );
8159
        String::from_utf8_lossy(&out.stdout).trim().to_string()
8160
    };
8161
    git(&["init", "-q", "-b", "main"]);
8162
    write(
8163
        &g,
8164
        "gulpfile.js",
8165
        b"/* header */\nconst a = 1;\nconst b = 2;\n",
8166
    );
8167
    git(&["add", "."]);
8168
    git(&["commit", "-q", "-m", "A root"]);
8169
    write(
8170
        &g,
8171
        "gulpfile.js",
8172
        b"/* header */\nconst a = 1;\n\nconst b = 2;\n",
8173
    );
8174
    git(&["commit", "-q", "-am", "whitespace"]);
8175
    git(&["checkout", "-q", "--orphan", "fork"]);
8176
    git(&["rm", "-q", "-r", "--cached", "."]);
8177
    let _ = fs::remove_file(g.join("gulpfile.js"));
8178
    write(
8179
        &g,
8180
        "gulpfile.js",
8181
        b"/* header */\nconst a = 1;\nconst b = 2;\nconst c = 3;\n",
8182
    );
8183
    git(&["add", "."]);
8184
    git(&["commit", "-q", "-m", "B root"]);
8185
    // Branch one joins B keeping main's copy; branch two keeps B's.
8186
    for (branch, keep) in [("one", "ours"), ("two", "theirs")] {
8187
        git(&["checkout", "-q", "-b", branch, "main"]);
8188
        let _ = run(&[
8189
            "merge",
8190
            "-q",
8191
            "--no-ff",
8192
            "--allow-unrelated-histories",
8193
            "-m",
8194
            "join",
8195
            "fork",
8196
        ]);
8197
        git(&["checkout", &format!("--{keep}"), "gulpfile.js"]);
8198
        git(&["add", "gulpfile.js"]);
8199
        git(&["commit", "-q", "-m", &format!("join on {branch}")]);
8200
    }
8201
    // Each branch then edits its copy.
8202
    git(&["checkout", "-q", "one"]);
8203
    write(
8204
        &g,
8205
        "gulpfile.js",
8206
        b"/* header */\nconst a = 1;\n\nconst b = 2;\n// tslint\n",
8207
    );
8208
    git(&["commit", "-q", "-am", "tslint on one"]);
8209
    git(&["checkout", "-q", "two"]);
8210
    write(
8211
        &g,
8212
        "gulpfile.js",
8213
        b"/* header */\nconst a = 1;\nconst b = 2;\nconst c = 3;\n// fmt\n",
8214
    );
8215
    write(&g, "extra.txt", b"x\n");
8216
    write(&g, "more.txt", b"m\n");
8217
    git(&["add", "."]);
8218
    git(&["commit", "-q", "-am", "fmt on two"]);
8219
    // They meet: resolved by hand.
8220
    git(&["checkout", "-q", "one"]);
8221
    let _ = run(&["merge", "-q", "--no-ff", "-m", "merge two", "two"]);
8222
    write(
8223
        &g,
8224
        "gulpfile.js",
8225
        b"/* header */\nconst a = 1;\nconst b = 2;\nconst c = 3;\n// tslint\n// fmt\n",
8226
    );
8227
    git(&["add", "gulpfile.js"]);
8228
    git(&["commit", "-q", "-m", "merge two into one"]);
8229
8230
    let dest = root.join("dest");
8231
    let repo = Repo::init(&dest).unwrap().with_home(root.join("home"));
8232
    repo.import_git(&g, "one").unwrap();
8233
    let v = repo.verify_git_import(&g, "one").unwrap();
8234
    assert!(v.mismatches.is_empty(), "{:?}", v.mismatches);
8235
}
8236
8237
/// oxygen#68: on a store that is not this disk's directory, the operation
8238
/// head is the store's reference record, moved by compare-and-swap. Two
8239
/// handles recording from the same head both get through, merged; a swap
8240
/// from a stale version is refused; a second repository cannot start on a
8241
/// store that already holds one.
8242
#[test]
8243
fn over_a_store_the_operation_head_moves_by_compare_and_swap() {
8244
    use crate::strata::{MemoryStore, Store as _};
8245
    let backend = std::sync::Arc::new(MemoryStore::new());
8246
    crate::store::TEST_BACKEND.with(|t| *t.borrow_mut() = Some(backend.clone()));
8247
    let dir = tempfile::tempdir().unwrap();
8248
    let a = Repo::init(dir.path()).unwrap();
8249
    assert!(
8250
        !dir.path().join(".oxy/ops/head").exists(),
8251
        "the head is not a file"
8252
    );
8253
    let (h0, op0) = a.head_op().unwrap();
8254
    let record = backend
8255
        .read_ref(HEAD_RECORD)
8256
        .unwrap()
8257
        .expect("the head is the store's record");
8258
    assert_eq!(String::from_utf8(record.0).unwrap(), h0.to_hex());
8259
8260
    let b = Repo::open(dir.path()).unwrap();
8261
    let state = a.store.put_state(&StateObject::new(vec![])).unwrap();
8262
    let mut va = op0.view.clone();
8263
    va.bookmarks.insert("from-a".into(), state);
8264
    let mut vb = op0.view.clone();
8265
    vb.bookmarks.insert("from-b".into(), state);
8266
    let rb = b.record_op(&[h0], "bookmark from-b", vb).unwrap();
8267
    assert_eq!(b.head_ref().unwrap(), rb);
8268
    // a recorded from h0 too: the head moved, so the two are merged.
8269
    let ra = a.record_op(&[h0], "bookmark from-a", va).unwrap();
8270
    let (head, op) = Repo::open(dir.path()).unwrap().head_op().unwrap();
8271
    assert_eq!(head, ra);
8272
    assert!(
8273
        op.command.ends_with("(merged with a concurrent operation)"),
8274
        "{}",
8275
        op.command
8276
    );
8277
    assert_eq!(op.parents, vec![rb, op.parents[1]]);
8278
    assert!(op.view.bookmarks.contains_key("from-a") && op.view.bookmarks.contains_key("from-b"));
8279
8280
    // A swap from a version that is no longer current moves nothing.
8281
    let (h, v) = a.read_head().unwrap();
8282
    assert!(b.swap_head(&rb, v.as_ref()).unwrap());
8283
    assert!(!a.swap_head(&h, v.as_ref()).unwrap(), "stale");
8284
    assert_eq!(a.head_ref().unwrap(), rb);
8285
8286
    let other = tempfile::tempdir().unwrap();
8287
    let err = Repo::init(other.path())
8288
        .err()
8289
        .expect("the store already holds a log")
8290
        .to_string();
8291
    assert!(
8292
        err.contains("already holds a repository's operation log"),
8293
        "{err}"
8294
    );
8295
    crate::store::TEST_BACKEND.with(|t| *t.borrow_mut() = None);
8296
}
8297
8298
/// oxygen#68: a repository kept on a store (`storage.url`) holds its
8299
/// objects and operation head there, with `.oxy/cache` in front: it works
8300
/// as one on disk does, reopens, and survives losing its cache.
8301
#[test]
8302
fn a_repository_runs_on_a_store_with_a_cache_in_front() {
8303
    hermetic();
8304
    if std::env::var_os("OXY_STORE_BACKEND").is_some() {
8305
        return;
8306
    }
8307
    let dir = tempfile::tempdir().unwrap();
8308
    let (root, bucket) = (dir.path().join("work"), dir.path().join("bucket"));
8309
    let url = format!("dir://{}", bucket.display());
8310
    let repo = Repo::init_on(&root, [7; 16], Some(&url)).unwrap();
8311
    assert_eq!(repo.config.storage_url.as_deref(), Some(url.as_str()));
8312
    write(&root, "a.txt", b"one\n");
8313
    let h1 = repo.commit("First", &[]).unwrap();
8314
    write(&root, "a.txt", b"one\ntwo\n");
8315
    let h2 = repo.commit("Second", &[]).unwrap();
8316
    assert!(
8317
        !root.join(".oxy/ops/head").exists(),
8318
        "the head is in the store"
8319
    );
8320
    assert!(bucket.join("ops/head").is_file());
8321
    assert!(root.join(".oxy/cache").is_dir());
8322
    drop(repo);
8323
8324
    // Reopened, and again with no cache at all: everything comes from the store.
8325
    for drop_cache in [false, true] {
8326
        if drop_cache {
8327
            std::fs::remove_dir_all(root.join(".oxy/cache")).unwrap();
8328
        }
8329
        let repo = Repo::open(&root).unwrap();
8330
        let log: Vec<String> = repo
8331
            .op_log()
8332
            .unwrap()
8333
            .into_iter()
8334
            .map(|(_, op)| op.command)
8335
            .collect();
8336
        assert!(log.len() >= 3, "{log:?}");
8337
        assert_eq!(repo.store().get_change(&h1).unwrap().message, "First");
8338
        let heads = repo
8339
            .store()
8340
            .get_state(&repo.view().unwrap().bookmarks["main"])
8341
            .unwrap()
8342
            .heads;
8343
        assert_eq!(heads, vec![h2]);
8344
        assert_eq!(
8345
            repo.load_state(&heads).unwrap().materialize().files.len(),
8346
            1
8347
        );
8348
    }
8349
8350
    // A second repository cannot start on the same store.
8351
    let err = Repo::init_on(&dir.path().join("other"), [8; 16], Some(&url))
8352
        .err()
8353
        .unwrap()
8354
        .to_string();
8355
    assert!(
8356
        err.contains("already holds a repository's operation log"),
8357
        "{err}"
8358
    );
8359
    let err = Repo::init_on(&dir.path().join("third"), [9; 16], Some("nope://x"))
8360
        .err()
8361
        .unwrap()
8362
        .to_string();
8363
    assert!(err.contains("cannot open that kind of store"), "{err}");
8364
}
8365
8366
/// oxygen#75: the prompt's quick check agrees with status in a repository
8367
/// with a subrepo: clean after a commit, dirty when the subrepo moves to
8368
/// another state, clean again once that pin is committed. (It compared the
8369
/// subrepo's directory as if it were a file, so it was always dirty.)
8370
#[test]
8371
fn the_quick_dirty_check_compares_a_subrepo_by_its_pin() {
8372
    hermetic();
8373
    let dir = tempfile::tempdir().unwrap();
8374
    let root = dir.path();
8375
    let _lib_origin = Repo::init(&root.join("lib-origin")).unwrap();
8376
    let lib_url = root.join("lib-origin").to_string_lossy().to_string();
8377
    let lib = Repo::clone(&lib_url, &root.join("lib"))
8378
        .unwrap()
8379
        .with_home(root.join("home"));
8380
    write(&root.join("lib"), "lib.txt", b"v1\n");
8381
    lib.commit("lib v1", &[]).unwrap();
8382
    assert!(lib.push("origin", false).unwrap()[0].ok);
8383
    let app_dir = root.join("app");
8384
    let app = Repo::init(&app_dir).unwrap().with_home(root.join("home"));
8385
    write(&app_dir, "main.txt", b"app\n");
8386
    app.submodule_add(&lib_url, "libs/lib", None).unwrap();
8387
    app.commit("app with lib", &[]).unwrap();
8388
    // Out of the racy window, so the stat-only path decides.
8389
    std::thread::sleep(std::time::Duration::from_millis(2100));
8390
    let reopen = || Repo::open(&app_dir).unwrap();
8391
    assert_eq!(
8392
        reopen().quick_dirty().unwrap(),
8393
        Some(false),
8394
        "clean, as status says"
8395
    );
8396
    let nested = Repo::open(&app_dir.join("libs/lib")).unwrap();
8397
    write(&app_dir.join("libs/lib"), "lib.txt", b"v2\n");
8398
    nested.commit("lib v2", &[]).unwrap();
8399
    assert_eq!(
8400
        reopen().quick_dirty().unwrap(),
8401
        Some(true),
8402
        "the subrepo moved"
8403
    );
8404
    reopen().commit("pin lib v2", &[]).unwrap();
8405
    std::thread::sleep(std::time::Duration::from_millis(2100));
8406
    assert_eq!(
8407
        reopen().quick_dirty().unwrap(),
8408
        Some(false),
8409
        "the new pin is committed"
8410
    );
8411
}
8412
8413
#[test]
8414
fn a_module_entry_that_was_never_added_is_reported_as_unpinned() {
8415
    // oxygen#72: a .oxymodules section with no subrepo behind it.
8416
    hermetic();
8417
    let dir = tempfile::tempdir().unwrap();
8418
    let root = dir.path();
8419
    let _lib_origin = Repo::init(&root.join("lib-origin")).unwrap();
8420
    let lib_url = root.join("lib-origin").to_string_lossy().to_string();
8421
    let lib = Repo::clone(&lib_url, &root.join("lib"))
8422
        .unwrap()
8423
        .with_home(root.join("home"));
8424
    write(&root.join("lib"), "lib.txt", b"v1\n");
8425
    lib.commit("lib v1", &[]).unwrap();
8426
    assert!(lib.push("origin", false).unwrap()[0].ok);
8427
    let app_dir = root.join("app");
8428
    let app = Repo::init(&app_dir).unwrap().with_home(root.join("home"));
8429
    write(
8430
        &app_dir,
8431
        ".oxymodules",
8432
        format!("[libs/lib]\nurl = {lib_url}\n").as_bytes(),
8433
    );
8434
    let unpinned = app.unpinned_modules().unwrap();
8435
    assert_eq!(unpinned.len(), 1);
8436
    assert_eq!(unpinned[0].0, "libs/lib");
8437
    assert_eq!(unpinned[0].1.url, lib_url);
8438
    assert!(app.submodule_update(true, &[]).unwrap().is_empty());
8439
    app.submodule_add(&lib_url, "libs/lib", None).unwrap();
8440
    assert!(app.unpinned_modules().unwrap().is_empty(), "added now");
8441
}
8442
8443
#[test]
8444
fn the_bookmark_revset_function_names_only_bookmarks() {
8445
    // oxygen#73: bookmark(NAME) is a bookmark's heads, never a tag or prefix.
8446
    hermetic();
8447
    let dir = tempfile::tempdir().unwrap();
8448
    let repo = Repo::init(dir.path()).unwrap();
8449
    write(dir.path(), "a.txt", b"a\n");
8450
    let a = repo.commit("A", &[]).unwrap();
8451
    write(dir.path(), "b.txt", b"b\n");
8452
    let b = repo.commit("B", &[]).unwrap();
8453
    let mut heads = repo.revset("bookmark(main)").unwrap().hashes;
8454
    heads.sort();
8455
    let mut want = repo.bookmark_heads().unwrap();
8456
    want.sort();
8457
    assert_eq!(heads, want);
8458
    assert!(heads.contains(&b));
8459
    assert_eq!(repo.revset("main").unwrap().hashes.len(), heads.len());
8460
    // A change prefix is a symbol, not a bookmark.
8461
    let prefix = repo.store().get_change_meta(&a).unwrap().change_id.short(8);
8462
    assert!(repo.revset(&prefix).is_ok());
8463
    let e = repo
8464
        .revset(&format!("bookmark({prefix})"))
8465
        .unwrap_err()
8466
        .to_string();
8467
    assert!(e.contains("no such bookmark"), "{e}");
8468
}
8469
8470
#[test]
8471
fn carrying_work_over_a_subrepo_already_at_the_target_pin_is_no_conflict() {
8472
    // oxygen#74: a stale state with .oxymodules but no pin, a newer one
8473
    // pinning the subrepo, and the nested repository on disk at that pin.
8474
    hermetic();
8475
    let dir = tempfile::tempdir().unwrap();
8476
    let root = dir.path();
8477
    let _lib_origin = Repo::init(&root.join("lib-origin")).unwrap();
8478
    let lib_url = root.join("lib-origin").to_string_lossy().to_string();
8479
    let lib = Repo::clone(&lib_url, &root.join("lib"))
8480
        .unwrap()
8481
        .with_home(root.join("home"));
8482
    write(&root.join("lib"), "lib.txt", b"v1\n");
8483
    lib.commit("lib v1", &[]).unwrap();
8484
    assert!(lib.push("origin", false).unwrap()[0].ok);
8485
    let app_dir = root.join("app");
8486
    let app = Repo::init(&app_dir).unwrap().with_home(root.join("home"));
8487
    write(&app_dir, "main.txt", b"app\n");
8488
    app.submodule_add(&lib_url, "libs/lib", None).unwrap();
8489
    // The stale state: registered in .oxymodules, never pinned.
8490
    fs::rename(app_dir.join("libs/lib"), root.join("aside")).unwrap();
8491
    app.commit("initial", &[]).unwrap();
8492
    let stale = app.bookmark_heads().unwrap();
8493
    fs::rename(root.join("aside"), app_dir.join("libs/lib")).unwrap();
8494
    app.commit("pin lib", &[]).unwrap();
8495
    let newer = app.bookmark_heads().unwrap();
8496
    app.checkout(&stale, false, "test").unwrap();
8497
    write(&app_dir, "notes.txt", b"mine\n");
8498
    let (_, carried) = app.checkout_carry(&newer, "main", "test").unwrap();
8499
    assert_eq!(carried, vec!["notes.txt".to_string()]);
8500
    assert!(app_dir.join("notes.txt").exists());
8501
}
8502
8503
#[test]
8504
fn a_bookmark_only_behind_its_remote_catches_up() {
8505
    // oxygen#74: switch takes the remote's state rather than a stale one.
8506
    hermetic();
8507
    let dir = tempfile::tempdir().unwrap();
8508
    let root = dir.path();
8509
    let _origin = Repo::init(&root.join("origin")).unwrap();
8510
    let url = root.join("origin").to_string_lossy().to_string();
8511
    let one = Repo::clone(&url, &root.join("one"))
8512
        .unwrap()
8513
        .with_home(root.join("home"));
8514
    write(&root.join("one"), "a.txt", b"a\n");
8515
    one.commit("A", &[]).unwrap();
8516
    assert!(one.push("origin", false).unwrap()[0].ok);
8517
    let two = Repo::clone(&url, &root.join("two"))
8518
        .unwrap()
8519
        .with_home(root.join("home"));
8520
    write(&root.join("two"), "b.txt", b"b\n");
8521
    two.commit("B", &[]).unwrap();
8522
    assert!(two.push("origin", false).unwrap()[0].ok);
8523
    assert_eq!(one.catch_up_bookmark("main").unwrap(), None, "not fetched");
8524
    one.fetch("origin").unwrap();
8525
    assert_eq!(one.catch_up_bookmark("main").unwrap(), Some(1));
8526
    assert_eq!(one.bookmarks().unwrap()[0].behind, Some(0));
8527
    // Local work the remote lacks: left alone.
8528
    write(&root.join("one"), "c.txt", b"c\n");
8529
    one.commit("C", &[]).unwrap();
8530
    write(&root.join("two"), "d.txt", b"d\n");
8531
    two.commit("D", &[]).unwrap();
8532
    assert!(two.push("origin", false).unwrap()[0].ok);
8533
    one.fetch("origin").unwrap();
8534
    assert_eq!(one.catch_up_bookmark("main").unwrap(), None);
8535
}
8536
8537
#[test]
8538
fn a_bookmark_is_compared_with_a_remote_that_has_it_when_there_is_no_origin() {
8539
    // oxygen#83: remotes earth and gcs, origin removed.
8540
    hermetic();
8541
    let dir = tempfile::tempdir().unwrap();
8542
    let root = dir.path();
8543
    let _up = Repo::init(&root.join("up")).unwrap();
8544
    let url = root.join("up").to_string_lossy().to_string();
8545
    let other = Repo::clone(&url, &root.join("other"))
8546
        .unwrap()
8547
        .with_home(root.join("home"));
8548
    write(&root.join("other"), "a.txt", b"a\n");
8549
    other.commit("a", &[]).unwrap();
8550
    assert!(other.push("origin", false).unwrap()[0].ok);
8551
    let mut one = Repo::clone(&url, &root.join("one"))
8552
        .unwrap()
8553
        .with_home(root.join("home"));
8554
    one.config.set("remote.earth.url", &url).unwrap();
8555
    one.config.set("remote.gcs.url", &url).unwrap();
8556
    one.config.set("remote.origin.url", "").unwrap();
8557
    one.save_config().unwrap();
8558
    write(&root.join("other"), "b.txt", b"b\n");
8559
    other.commit("b", &[]).unwrap();
8560
    assert!(other.push("origin", false).unwrap()[0].ok);
8561
    one.fetch("earth").unwrap();
8562
    let b = one
8563
        .bookmarks()
8564
        .unwrap()
8565
        .into_iter()
8566
        .find(|b| b.name == "main")
8567
        .unwrap();
8568
    assert_eq!(
8569
        (b.remote.as_deref(), b.behind),
8570
        (Some("earth"), Some(1)),
8571
        "a stale origin copy is not used"
8572
    );
8573
    assert_eq!(
8574
        one.default_remote(),
8575
        "origin",
8576
        "no default chosen among several"
8577
    );
8578
    let e = one.pull(&one.default_remote()).unwrap_err().to_string();
8579
    assert!(e.contains("earth, gcs") && e.contains("core.remote"), "{e}");
8580
    one.config.set("core.remote", "earth").unwrap();
8581
    assert_eq!(one.default_remote(), "earth");
8582
}
8583
8584
#[test]
8585
fn a_missing_author_identity_says_how_to_fix_it() {
8586
    // oxygen#82: an agent home's author.key naming an identity the
8587
    // repository does not hold.
8588
    hermetic();
8589
    let dir = tempfile::tempdir().unwrap();
8590
    let mut repo = Repo::init(dir.path()).unwrap();
8591
    let missing = KeyId::from_hex(&"ab".repeat(32)).unwrap();
8592
    repo.config.set("author.key", &missing.to_hex()).unwrap();
8593
    let e = repo.identity(&missing).unwrap_err().to_string();
8594
    assert!(
8595
        e.contains("this repository has no identity") && e.contains("oxy config author.key"),
8596
        "{e}"
8597
    );
8598
    assert!(e.contains("this repository's config"), "{e}");
8599
}
8600
8601
#[test]
8602
fn a_working_copy_behind_its_bookmark_is_flagged_and_pull_brings_it_up() {
8603
    // oxygen#89 (supermarioland, 2026-10-09): the bookmark moved on without
8604
    // the working copy, a pull with nothing new left it there, and status
8605
    // said "clean".
8606
    hermetic();
8607
    let dir = tempfile::tempdir().unwrap();
8608
    let root = dir.path();
8609
    let _up = Repo::init(&root.join("up")).unwrap();
8610
    let url = root.join("up").to_string_lossy().to_string();
8611
    let other = Repo::clone(&url, &root.join("other"))
8612
        .unwrap()
8613
        .with_home(root.join("home"));
8614
    write(&root.join("other"), "a.txt", b"a\n");
8615
    other.commit("a", &[]).unwrap();
8616
    assert!(other.push("origin", false).unwrap()[0].ok);
8617
    let one = Repo::clone(&url, &root.join("one"))
8618
        .unwrap()
8619
        .with_home(root.join("home"));
8620
    write(&root.join("other"), "b.txt", b"b\n");
8621
    other.commit("b", &[]).unwrap();
8622
    assert!(other.push("origin", false).unwrap()[0].ok);
8623
    one.fetch("origin").unwrap();
8624
    // The bookmark moves; the working copy does not.
8625
    let theirs = one.resolve_heads("origin/main").unwrap();
8626
    one.bookmark_set("main", &theirs).unwrap();
8627
    assert!(!root.join("one/b.txt").exists());
8628
    assert_eq!(one.working_copy_behind().unwrap(), Some(1));
8629
    let r = one.pull("origin").unwrap();
8630
    assert!(
8631
        !r.changed && r.checked_out,
8632
        "nothing new, but the working copy caught up"
8633
    );
8634
    assert!(root.join("one/b.txt").exists());
8635
    assert_eq!(one.working_copy_behind().unwrap(), None);
8636
}
8637
8638
#[test]
8639
fn touched_nodes_cache_answers_as_the_changes_do() {
8640
    hermetic();
8641
    let dir = tempfile::tempdir().unwrap();
8642
    let repo = Repo::init(dir.path()).unwrap();
8643
    write(dir.path(), "a.txt", b"one\n");
8644
    write(dir.path(), "b.txt", b"x\n");
8645
    repo.snapshot("t").unwrap();
8646
    let c1 = repo.commit("first", &[]).unwrap();
8647
    write(dir.path(), "b.txt", b"y\n");
8648
    repo.snapshot("t").unwrap();
8649
    repo.commit("b only", &[]).unwrap();
8650
    fs::rename(dir.path().join("a.txt"), dir.path().join("c.txt")).unwrap();
8651
    write(dir.path(), "c.txt", b"one\ntwo\n");
8652
    repo.snapshot("t").unwrap();
8653
    let c3 = repo.commit("rename and edit", &[]).unwrap();
8654
    // Uncommitted work, so the working copy touches a file too.
8655
    write(dir.path(), "c.txt", b"one\ntwo\nthree\n");
8656
    repo.snapshot("t").unwrap();
8657
8658
    let path = dir.path().join(".oxy/index/touched");
8659
    let hashes = |es: Vec<LogEntry>| es.iter().map(|e| e.hash).collect::<Vec<_>>();
8660
    let cold = hashes(repo.log_for_path("c.txt").unwrap());
8661
    assert!(path.exists(), "the first query writes the cache");
8662
    let warm = hashes(repo.log_for_path("c.txt").unwrap());
8663
    assert_eq!(cold, warm, "the cache answers as the changes do");
8664
    let (wc, _) = repo.working_copy().unwrap();
8665
    assert_eq!(
8666
        cold,
8667
        vec![wc, c3, c1],
8668
        "renames followed, the working copy included"
8669
    );
8670
8671
    // Working-copy changes are not kept: they are replaced by every snapshot.
8672
    let cached = super::touched::read_touched_for_test(&fs::read(&path).unwrap()).unwrap();
8673
    assert!(!cached.contains(&wc), "a working-copy change is not cached");
8674
    assert!(cached.contains(&c1) && cached.contains(&c3));
8675
8676
    // A damaged cache is ignored, not trusted.
8677
    let mut bytes = fs::read(&path).unwrap();
8678
    let last = bytes.len() - 40;
8679
    bytes[last] ^= 1;
8680
    fs::write(&path, &bytes).unwrap();
8681
    assert_eq!(hashes(repo.log_for_path("c.txt").unwrap()), cold);
8682
    let touches = repo.log_revset("touches(\"c.txt\") ~ @").unwrap();
8683
    assert_eq!(hashes(touches), vec![c3, c1]);
8684
}
8685
8686
/// oxygen#88 (vscode 9ab2056393c8): two lines of history that each move a
8687
/// file back where it was leave two placements at one place, which the
8688
/// tree shows as one file. Removing it, and then its directory, retires
8689
/// both, so no copy is left under a directory that is gone.
8690
#[test]
8691
fn git_import_removes_every_copy_of_a_file_at_one_place() {
8692
    hermetic();
8693
    if std::process::Command::new("git")
8694
        .arg("--version")
8695
        .output()
8696
        .is_err()
8697
    {
8698
        eprintln!("git not installed; skipping");
8699
        return;
8700
    }
8701
    let dir = tempfile::tempdir().unwrap();
8702
    let root = dir.path();
8703
    let g = root.join("src.git");
8704
    fs::create_dir_all(&g).unwrap();
8705
    let git = |args: &[&str]| {
8706
        let out = std::process::Command::new("git")
8707
            .arg("-C")
8708
            .arg(&g)
8709
            .args([
8710
                "-c",
8711
                "user.name=Grace",
8712
                "-c",
8713
                "[email protected]",
8714
                "-c",
8715
                "commit.gpgsign=false",
8716
            ])
8717
            .args(args)
8718
            .output()
8719
            .unwrap();
8720
        assert!(
8721
            out.status.success(),
8722
            "git {args:?}: {}",
8723
            String::from_utf8_lossy(&out.stderr)
8724
        );
8725
    };
8726
    git(&["init", "-q", "-b", "main"]);
8727
    write(&g, "d/list.txt", b"one\ntwo\nthree\nfour\n");
8728
    write(&g, "keep.txt", b"k\n");
8729
    git(&["add", "."]);
8730
    git(&["commit", "-qm", "base"]);
8731
    fs::create_dir_all(g.join("d/sub")).unwrap();
8732
    git(&["mv", "d/list.txt", "d/sub/list.txt"]);
8733
    git(&["commit", "-qm", "into sub"]);
8734
    git(&["checkout", "-qb", "side"]);
8735
    git(&["mv", "d/sub/list.txt", "d/list.txt"]);
8736
    git(&["commit", "-qm", "back, on side"]);
8737
    git(&["checkout", "-q", "main"]);
8738
    git(&["mv", "d/sub/list.txt", "d/list.txt"]);
8739
    git(&["commit", "-qm", "back, on main"]);
8740
    git(&["merge", "-q", "--no-edit", "side"]);
8741
    git(&["rm", "-rq", "d"]);
8742
    git(&["commit", "-qm", "d goes"]);
8743
8744
    let repo = Repo::init(&root.join("o")).unwrap();
8745
    repo.import_git(&g, "main").unwrap();
8746
    let v = repo.verify_git_import(&g, "main").unwrap();
8747
    assert!(v.mismatches.is_empty(), "{:?}", v.mismatches);
8748
    let st = repo
8749
        .load_state_history(&repo.bookmark_heads().unwrap())
8750
        .unwrap();
8751
    let view = st.tree().view();
8752
    assert!(view.conflicts.is_empty(), "{:?}", view.conflicts);
8753
    assert_eq!(view.entries.keys().collect::<Vec<_>>(), vec!["keep.txt"]);
8754
}
8755
8756
/// oxygen#94: a state index's file histories are read, and checked by
8757
/// their own hashes, only when a file is built. One found damaged is an
8758
/// error that says so, the index is removed, and the next read rebuilds it.
8759
#[test]
8760
fn a_damaged_file_history_in_the_state_index_is_rebuilt() {
8761
    hermetic();
8762
    let dir = tempfile::tempdir().unwrap();
8763
    let repo = Repo::init(dir.path()).unwrap();
8764
    for i in 0..6 {
8765
        write(
8766
            dir.path(),
8767
            &format!("f{i}.txt"),
8768
            format!("one {i}\n").as_bytes(),
8769
        );
8770
    }
8771
    repo.snapshot("t").unwrap();
8772
    repo.commit("first", &[]).unwrap();
8773
    for i in 0..6 {
8774
        write(
8775
            dir.path(),
8776
            &format!("f{i}.txt"),
8777
            format!("one {i}\ntwo\n").as_bytes(),
8778
        );
8779
    }
8780
    repo.snapshot("t").unwrap();
8781
    repo.commit("second", &[]).unwrap();
8782
    let want: Vec<Vec<u8>> = (0..6)
8783
        .map(|i| format!("one {i}\ntwo\n").into_bytes())
8784
        .collect();
8785
    // The index of the working copy's base, holding every file's history
8786
    // (a few changes behind, an index is replayed onto, not rewritten).
8787
    let (_, wc) = repo.working_copy().unwrap();
8788
    let base = repo.load_state_history(&wc.deps).unwrap();
8789
    repo.write_state_index(&wc.deps, &base);
8790
    for (i, w) in want.iter().enumerate() {
8791
        assert_eq!(&repo.file_at(&format!("f{i}.txt"), None).unwrap(), w);
8792
    }
8793
    let index = repo.state_indexes();
8794
    assert!(!index.is_empty(), "a state index was written");
8795
    // The histories are last in the file: damage the last of them.
8796
    let mut bytes = fs::read(&index[0]).unwrap();
8797
    let last = bytes.len() - 1;
8798
    bytes[last] ^= 0x40;
8799
    fs::write(&index[0], &bytes).unwrap();
8800
8801
    let reads: Vec<_> = (0..6)
8802
        .map(|i| repo.file_at(&format!("f{i}.txt"), None))
8803
        .collect();
8804
    let damaged: Vec<String> = reads
8805
        .iter()
8806
        .filter_map(|r| r.as_ref().err().map(|e| e.to_string()))
8807
        .collect();
8808
    assert_eq!(damaged.len(), 1, "{damaged:?}");
8809
    assert!(
8810
        damaged[0].contains("state index was damaged")
8811
            && damaged[0].contains("run the command again"),
8812
        "{}",
8813
        damaged[0]
8814
    );
8815
    // Every file reads right again, from an index rebuilt from history.
8816
    for (i, w) in want.iter().enumerate() {
8817
        assert_eq!(&repo.file_at(&format!("f{i}.txt"), None).unwrap(), w);
8818
    }
8819
}
8820
8821
/// oxygen#95: a push longer than `push.batch-bytes` goes in parts, each
8822
/// objects alone and in dependency order, and the last moves the bookmark.
8823
/// The remote ends with every change and the same state, and says how each
8824
/// part went.
8825
#[test]
8826
fn a_long_push_goes_in_parts() {
8827
    hermetic();
8828
    let dir = tempfile::tempdir().unwrap();
8829
    let root = dir.path();
8830
    let origin = root.join("origin");
8831
    Repo::init_bare_unbound(&origin).unwrap();
8832
    let main = root.join("main");
8833
    let mut repo = Repo::init(&main).unwrap();
8834
    repo.config
8835
        .set("remote.origin.url", &origin.to_string_lossy())
8836
        .unwrap();
8837
    // One byte: every change is a part of its own.
8838
    repo.config.set("push.batch-bytes", "1").unwrap();
8839
    repo.save_config().unwrap();
8840
    for i in 0..6 {
8841
        write(
8842
            &main,
8843
            &format!("f{i}.txt"),
8844
            format!("file {i}\n").as_bytes(),
8845
        );
8846
        repo.commit(&format!("c{i}"), &[]).unwrap();
8847
    }
8848
    let mut parts = Vec::new();
8849
    let results = repo
8850
        .push_bookmark_with("origin", "main", false, &mut |m| parts.push(m.to_string()))
8851
        .unwrap();
8852
    assert!(
8853
        results.iter().any(|r| r.ok && r.name == "main"),
8854
        "{results:?}"
8855
    );
8856
    assert_eq!(parts.len(), 6, "{parts:?}");
8857
    assert_eq!(parts[0], "part 1 of 6: 1 changes");
8858
8859
    let remote = Repo::open(&origin).unwrap();
8860
    let heads = repo.bookmark_heads().unwrap();
8861
    assert_eq!(remote.bookmark_heads().unwrap(), heads);
8862
    assert_eq!(
8863
        remote.log_state(&heads).unwrap().len(),
8864
        repo.log_state(&heads).unwrap().len()
8865
    );
8866
    // A push of objects alone reports how it went, as `objects`.
8867
    let got = remote
8868
        .receive_push(Bundle::default(), vec![], None, vec![])
8869
        .unwrap();
8870
    assert_eq!(got.len(), 1);
8871
    assert!(got[0].ok && got[0].name == OBJECTS_RESULT, "{got:?}");
8872
}
8873
8874
/// oxygen#97: with `git.claim`, an import authors the importing identity's
8875
/// own commits (Git author email = its email, any case) with its key, and
8876
/// leaves anyone else's with the zero key; the history verifies as before.
8877
#[test]
8878
fn git_import_claims_your_own_commits() {
8879
    hermetic();
8880
    if std::process::Command::new("git")
8881
        .arg("--version")
8882
        .output()
8883
        .is_err()
8884
    {
8885
        eprintln!("git not installed; skipping");
8886
        return;
8887
    }
8888
    let dir = tempfile::tempdir().unwrap();
8889
    let root = dir.path();
8890
    let g = root.join("src.git");
8891
    fs::create_dir_all(&g).unwrap();
8892
    let git = |who: &str, args: &[&str]| {
8893
        let (name, email) = who.split_once(' ').unwrap();
8894
        let out = std::process::Command::new("git")
8895
            .arg("-C")
8896
            .arg(&g)
8897
            .args([
8898
                "-c",
8899
                &format!("user.name={name}"),
8900
                "-c",
8901
                &format!("user.email={email}"),
8902
                "-c",
8903
                "commit.gpgsign=false",
8904
            ])
8905
            .args(args)
8906
            .output()
8907
            .unwrap();
8908
        assert!(
8909
            out.status.success(),
8910
            "git {args:?}: {}",
8911
            String::from_utf8_lossy(&out.stderr)
8912
        );
8913
    };
8914
    git("Grace [email protected]", &["init", "-q", "-b", "main"]);
8915
    write(&g, "a.txt", b"a\n");
8916
    git("Grace [email protected]", &["add", "."]);
8917
    git("Grace [email protected]", &["commit", "-qm", "mine"]);
8918
    write(&g, "b.txt", b"b\n");
8919
    git("Ada [email protected]", &["add", "."]);
8920
    git("Ada [email protected]", &["commit", "-qm", "someone else's"]);
8921
8922
    let mut repo = Repo::init(&root.join("o")).unwrap();
8923
    let (key, _) = repo
8924
        .create_identity("Grace", "[email protected]", IdentityScope::Repo)
8925
        .unwrap();
8926
    repo.config.set("git.claim", "true").unwrap();
8927
    repo.save_config().unwrap();
8928
    let repo = Repo::open(&root.join("o")).unwrap();
8929
    repo.import_git(&g, "main").unwrap();
8930
    let v = repo.verify_git_import(&g, "main").unwrap();
8931
    assert!(v.mismatches.is_empty(), "{:?}", v.mismatches);
8932
    let heads = repo.bookmark_heads().unwrap();
8933
    let by_message: std::collections::HashMap<String, KeyId> = repo
8934
        .log_state(&heads)
8935
        .unwrap()
8936
        .into_iter()
8937
        .map(|e| {
8938
            (
8939
                e.change.message.lines().next().unwrap_or("").to_string(),
8940
                e.change.author,
8941
            )
8942
        })
8943
        .collect();
8944
    assert_eq!(by_message["mine"], key, "her own commit, any case of email");
8945
    assert_eq!(by_message["someone else's"], ObjectRef::ZERO, "not hers");
8946
}
8947
8948
/// oxygen#86: removing a remote removes all of it: every `remote.NAME.*`
8949
/// key (URL, token, CA), its tracking bookmarks, and nothing else.
8950
#[test]
8951
fn removing_a_remote_leaves_nothing_of_it() {
8952
    hermetic();
8953
    let dir = tempfile::tempdir().unwrap();
8954
    let origin = dir.path().join("origin");
8955
    Repo::init_bare_unbound(&origin).unwrap();
8956
    let main = dir.path().join("main");
8957
    let mut repo = Repo::init(&main).unwrap();
8958
    repo.config
8959
        .set("remote.origin.url", &origin.to_string_lossy())
8960
        .unwrap();
8961
    repo.config
8962
        .set("remote.origin.token", "secret-ish")
8963
        .unwrap();
8964
    repo.config
8965
        .set("remote.keep.url", &origin.to_string_lossy())
8966
        .unwrap();
8967
    repo.save_config().unwrap();
8968
    write(&main, "a.txt", b"a\n");
8969
    repo.commit("a", &[]).unwrap();
8970
    assert!(repo.push("origin", false).unwrap()[0].ok);
8971
    assert!(
8972
        repo.view().unwrap().remotes.contains_key("origin"),
8973
        "a tracking bookmark"
8974
    );
8975
8976
    repo.remove_remote("origin").unwrap();
8977
    let again = Repo::open(&main).unwrap();
8978
    assert!(
8979
        !again
8980
            .config
8981
            .repo_layer()
8982
            .keys()
8983
            .any(|k| k.starts_with("remote.origin.")),
8984
        "{:?}",
8985
        again.config.repo_layer()
8986
    );
8987
    assert!(!again.config.remotes.contains_key("origin"));
8988
    assert!(
8989
        !again.view().unwrap().remotes.contains_key("origin"),
8990
        "its tracking bookmarks go"
8991
    );
8992
    assert!(
8993
        again.config.remotes.contains_key("keep"),
8994
        "another remote stays"
8995
    );
8996
    let mut again = again;
8997
    assert!(
8998
        again.remove_remote("origin").is_err(),
8999
        "a second removal is refused"
9000
    );
9001
}
9002
9003
/// oxygenhub#126: a blob a host stored for itself (a job's artifact) is
9004
/// unreachable from history, so gc prunes it, unless the host names it:
9005
/// then it and its chunks stay, and it reads back whole.
9006
#[test]
9007
fn gc_keeps_the_blobs_a_host_names() {
9008
    hermetic();
9009
    let dir = tempfile::tempdir().unwrap();
9010
    let repo = Repo::init(dir.path()).unwrap();
9011
    write(dir.path(), "a.txt", b"a\n");
9012
    repo.commit("a", &[]).unwrap();
9013
    // Large enough to be several chunks.
9014
    let body: Vec<u8> = (0..400_000u32)
9015
        .flat_map(|i| (i.wrapping_mul(2654435761)).to_le_bytes())
9016
        .collect();
9017
    let kept = repo.store_blob(&body).unwrap();
9018
    let lost = repo.store_blob(b"an artifact nobody names").unwrap();
9019
    repo.gc_keeping(true, &[kept], &mut |_| {}).unwrap();
9020
    assert_eq!(repo.read_blob(&kept).unwrap(), body, "named: kept whole");
9021
    assert!(!repo.store().has(&lost), "not named: pruned");
9022
    repo.gc(true).unwrap();
9023
    assert!(!repo.store().has(&kept), "a plain gc prunes it");
9024
}
9025
9026
/// oxygen#99: undo in one workspace undoes that workspace's last command,
9027
/// never another workspace's, says what it undid, and goes further back
9028
/// when run again.
9029
#[test]
9030
fn undo_is_scoped_to_its_workspace() {
9031
    hermetic();
9032
    let dir = tempfile::tempdir().unwrap();
9033
    let root = dir.path().join("main");
9034
    let a = Repo::init(&root).unwrap();
9035
    write(&root, "base.txt", b"base\n");
9036
    let base = a.commit("base", &[]).unwrap();
9037
    a.bookmark_create("feature", None).unwrap();
9038
    let ws_dir = dir.path().join("ws");
9039
    let heads = a.resolve_heads("feature").unwrap();
9040
    let b = a
9041
        .workspace_add_on(&ws_dir, Some(&heads), Some("feature"))
9042
        .unwrap();
9043
9044
    // A commits on main, then B commits on feature: B's is the newest.
9045
    write(&root, "a.txt", b"a\n");
9046
    let ca = a.commit("from a", &[]).unwrap();
9047
    write(&ws_dir, "b.txt", b"b\n");
9048
    let cb = b.commit("from b", &[]).unwrap();
9049
9050
    // A's undo undoes A's commit and leaves B's.
9051
    let u = a.undo().unwrap();
9052
    assert_eq!(u.command, "oxy commit -m \"from a\"");
9053
    assert_eq!(u.others_kept, 1, "B's newer commit is left");
9054
    assert!(!u.changes.is_empty());
9055
    let view = a.view().unwrap();
9056
    // (Independent changes commute, so a bookmark's heads may hold base too.)
9057
    assert_eq!(a.heads_of(&view, "main").unwrap(), vec![base]);
9058
    assert!(
9059
        a.heads_of(&view, "feature").unwrap().contains(&cb),
9060
        "B's commit stands"
9061
    );
9062
    assert!(
9063
        a.store().get_change(&ca).is_ok(),
9064
        "the change itself is still in the store"
9065
    );
9066
    // A's working copy was clean, so its files followed; B's are untouched.
9067
    assert!(!root.join("a.txt").exists());
9068
    assert!(a.snapshot("oxy status").unwrap().statuses.is_empty());
9069
    assert!(ws_dir.join("b.txt").exists());
9070
9071
    // B's undo still finds B's own commit, under A's undo.
9072
    let u = b.undo().unwrap();
9073
    assert_eq!(u.command, "oxy commit -m \"from b\"");
9074
    assert!(!b
9075
        .heads_of(&b.view().unwrap(), "feature")
9076
        .unwrap()
9077
        .contains(&cb));
9078
    assert_eq!(
9079
        a.heads_of(&a.view().unwrap(), "main").unwrap(),
9080
        vec![base],
9081
        "A's undo stands"
9082
    );
9083
9084
    // A's next undo goes past the commit it already undid, to adding B's
9085
    // workspace: refused, since B has worked there since.
9086
    let e = a.undo().unwrap_err().to_string();
9087
    assert!(e.contains("the workspace at") && e.contains("ws"), "{e}");
9088
}
9089
9090
/// oxygen#99: two workspaces on one bookmark: an undo takes back only its
9091
/// own commit's head, and the other workspace's head stays.
9092
#[test]
9093
fn undo_on_a_shared_bookmark_keeps_the_other_workspaces_head() {
9094
    hermetic();
9095
    let dir = tempfile::tempdir().unwrap();
9096
    let root = dir.path().join("main");
9097
    let a = Repo::init(&root).unwrap();
9098
    write(&root, "base.txt", b"base\n");
9099
    a.commit("base", &[]).unwrap();
9100
    let ws_dir = dir.path().join("ws");
9101
    let b = a.workspace_add(&ws_dir, None).unwrap();
9102
    write(&root, "a.txt", b"a\n");
9103
    let ca = a.commit("from a", &[]).unwrap();
9104
    write(&ws_dir, "b.txt", b"b\n");
9105
    let cb = b.commit("from b", &[]).unwrap();
9106
    let u = a.undo().unwrap();
9107
    assert_eq!(u.command, "oxy commit -m \"from a\"");
9108
    let heads = a.heads_of(&a.view().unwrap(), "main").unwrap();
9109
    assert!(heads.contains(&cb) && !heads.contains(&ca), "{heads:?}");
9110
}
9111
9112
/// oxygen#99: an undo that would also take back what another workspace
9113
/// did since to the same bookmark is refused, naming it.
9114
#[test]
9115
fn undo_refuses_to_take_back_another_workspaces_work() {
9116
    hermetic();
9117
    let dir = tempfile::tempdir().unwrap();
9118
    let root = dir.path().join("main");
9119
    let a = Repo::init(&root).unwrap();
9120
    write(&root, "base.txt", b"base\n");
9121
    a.commit("base", &[]).unwrap();
9122
    let ws_dir = dir.path().join("ws");
9123
    let b = a.workspace_add(&ws_dir, None).unwrap();
9124
    // Both on main: A commits, then B builds on it, editing A's file.
9125
    write(&root, "a.txt", b"a\n");
9126
    a.commit("from a", &[]).unwrap();
9127
    let heads = b.resolve_heads("main").unwrap();
9128
    b.checkout(&heads, false, "oxy checkout").unwrap();
9129
    write(&ws_dir, "a.txt", b"a, then b\n");
9130
    b.commit("from b", &[]).unwrap();
9131
    let e = a.undo().unwrap_err().to_string();
9132
    assert!(
9133
        e.contains("bookmark main") && e.contains("builds on"),
9134
        "{e}"
9135
    );
9136
    assert!(e.contains("oxy op restore"), "{e}");
9137
}
9138
9139
/// oxygen#99: undoing a commit that was already pushed says so: the remote
9140
/// still has it.
9141
#[test]
9142
fn undo_says_when_the_commit_was_pushed() {
9143
    hermetic();
9144
    let dir = tempfile::tempdir().unwrap();
9145
    let root = dir.path();
9146
    Repo::init(&root.join("origin")).unwrap();
9147
    let url = root.join("origin").to_string_lossy().to_string();
9148
    let repo = Repo::clone(&url, &root.join("work"))
9149
        .unwrap()
9150
        .with_home(root.join("home"));
9151
    write(&root.join("work"), "a.txt", b"a\n");
9152
    repo.commit("a", &[]).unwrap();
9153
    assert!(repo.push("origin", false).unwrap()[0].ok);
9154
    // The push itself is passed over: the remote keeps what it was sent.
9155
    let u = repo.undo().unwrap();
9156
    assert_eq!(u.command, "oxy commit -m \"a\"");
9157
    assert_eq!(u.pushed, vec![("main".to_string(), "origin".to_string())]);
9158
}