OXYGENHUB
# 8b276e0106d1 oxygen / crates / oxy-core / src / repo / tests.rs
218.4 KiB · Rust · last changed Check out only what differs, a batch at a time 1 month 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
        }
438
    );
439
    assert_eq!(fs::read(root.join("a.txt")).unwrap(), b"one\n");
440
    assert_eq!(fs::read(root.join("sub/deep/b.txt")).unwrap(), b"b\n");
441
    assert!(!root.join("bin.dat").exists());
442
    let (_, wc) = repo.working_copy().unwrap();
443
    assert_eq!(wc.deps, vec![h1]);
444
    assert!(
445
        !repo.snapshot("status").unwrap().changed,
446
        "checkout leaves a clean working copy"
447
    );
448
    // The bookmark still points at h2.
449
    assert_eq!(repo.bookmark_heads().unwrap(), vec![h2]);
450
451
    // Dirty working copy refuses without --discard.
452
    write(root, "a.txt", b"dirty\n");
453
    assert!(repo.checkout(&[h2], false, "oxy checkout").is_err());
454
    let r = repo
455
        .checkout(&[h2], true, "oxy checkout --discard")
456
        .unwrap();
457
    assert_eq!(fs::read(root.join("a.txt")).unwrap(), b"two\n");
458
    assert_eq!(fs::read(root.join("bin.dat")).unwrap(), [0, 1, 2, 3]);
459
    assert!(!root.join("sub").exists(), "empty directories are pruned");
460
    assert_eq!(r.removed, 1);
461
    assert!(!repo.snapshot("status").unwrap().changed);
462
463
    // Refuses to write through a symlinked directory.
464
    #[cfg(unix)]
465
    {
466
        fs::remove_dir_all(root.join("sub")).ok();
467
        std::os::unix::fs::symlink("/tmp", root.join("sub")).unwrap();
468
        assert!(repo.checkout(&[h1], true, "oxy checkout").is_err());
469
    }
470
}
471
472
#[test]
473
fn large_files_are_chunked_and_read_back() {
474
    hermetic();
475
    let dir = tempfile::tempdir().unwrap();
476
    let repo = Repo::init(dir.path()).unwrap();
477
    let mut big = vec![0u8; 700 * 1024];
478
    for (i, b) in big.iter_mut().enumerate() {
479
        *b = (i as u32).wrapping_mul(2654435761).to_le_bytes()[0];
480
    }
481
    let r = repo.store_blob(&big).unwrap();
482
    let blob = Blob::decode(&repo.store().get_typed(&r, ObjectType::Blob).unwrap()).unwrap();
483
    assert!(blob.chunks.len() >= 3, "{}", blob.chunks.len());
484
    assert_eq!(repo.read_blob(&r).unwrap(), big);
485
    assert_eq!(Repo::blob_ref(&big), r);
486
}
487
488
#[test]
489
fn clone_push_pull_with_seals_and_attestations() {
490
    hermetic();
491
    let dir = tempfile::tempdir().unwrap();
492
    let root = dir.path();
493
    let origin_path = root.join("origin");
494
    let origin = Repo::init(&origin_path).unwrap();
495
    let origin_url = origin_path.to_string_lossy().to_string();
496
497
    // A clones, creates an identity (default core.sign = seal), commits, pushes.
498
    let mut a = Repo::clone(&origin_url, &root.join("a"))
499
        .unwrap()
500
        .with_home(root.join("home-a"));
501
    assert_eq!(a.id().unwrap(), origin.id().unwrap());
502
    let (key_a, _) = a
503
        .create_identity("Ada", "[email protected]", IdentityScope::Repo)
504
        .unwrap();
505
    write(&root.join("a"), "f.txt", b"a\n");
506
    let h1 = a.commit("first", &[]).unwrap();
507
    let results = a.push("origin", false).unwrap();
508
    assert!(results[0].ok, "{}", results[0].reason);
509
    assert_eq!(origin.bookmark_heads().unwrap(), vec![h1]);
510
    // The change was sealed at push and the reference attested.
511
    assert!(
512
        matches!(origin.authenticate_change(&h1).unwrap(), SignatureStatus::Valid { key, sealed: true, .. } if key == key_a)
513
    );
514
    assert_eq!(
515
        origin.verify_change(&h1).unwrap(),
516
        SignatureStatus::Unsigned
517
    );
518
    let serial_of = |att: &SignedAttest| match att.attest.body {
519
        AttestBody::Ref { serial, .. } => serial,
520
        _ => unreachable!(),
521
    };
522
    let (_, att) = origin.latest_ref_attest("main").unwrap().unwrap();
523
    // A bookmark new to the remote starts at the clock (past any deleted
524
    // namesake's serial); later updates count up from there.
525
    let first = serial_of(&att);
526
    assert!(first > 1_000_000_000_000, "{first}");
527
    let again = a.push("origin", false).unwrap();
528
    assert!(again[0].ok && again[0].reason.contains("up to date"));
529
    let (_, att) = origin.latest_ref_attest("main").unwrap().unwrap();
530
    assert_eq!(serial_of(&att), first, "a no-op push does not attest again");
531
532
    // B clones and sees the file and the seal.
533
    let b = Repo::clone(&origin_url, &root.join("b")).unwrap();
534
    assert_eq!(fs::read(root.join("b/f.txt")).unwrap(), b"a\n");
535
    assert_eq!(b.bookmark_heads().unwrap(), vec![h1]);
536
    assert!(matches!(
537
        b.authenticate_change(&h1).unwrap(),
538
        SignatureStatus::Valid { sealed: true, .. }
539
    ));
540
541
    // B (no identity) commits and pushes unsigned; the unverified origin accepts.
542
    write(&root.join("b"), "f.txt", b"a\nb\n");
543
    let h2 = b.commit("second", &[]).unwrap();
544
    assert!(b.push("origin", false).unwrap()[0].ok);
545
    assert_eq!(origin.bookmark_heads().unwrap(), vec![h2]);
546
547
    // A commits an independent change; push is refused until A pulls.
548
    write(&root.join("a"), "g.txt", b"g\n");
549
    let h3 = a.commit("third", &[]).unwrap();
550
    assert!(a.push("origin", false).is_err());
551
    let pr = a.pull("origin").unwrap();
552
    assert!(pr.changed && pr.checked_out);
553
    let mut want = vec![h2, h3];
554
    want.sort();
555
    assert_eq!(pr.heads, want);
556
    assert_eq!(fs::read(root.join("a/f.txt")).unwrap(), b"a\nb\n");
557
    assert_eq!(fs::read(root.join("a/g.txt")).unwrap(), b"g\n");
558
    let results = a.push("origin", false).unwrap();
559
    assert!(results[0].ok, "{}", results[0].reason);
560
    let mut origin_heads = origin.bookmark_heads().unwrap();
561
    origin_heads.sort();
562
    assert_eq!(origin_heads, want);
563
    let (_, att) = origin.latest_ref_attest("main").unwrap().unwrap();
564
    assert_eq!(serial_of(&att), first + 1);
565
566
    // B pulls and ends up identical.
567
    let pr = b.pull("origin").unwrap();
568
    assert_eq!(pr.heads, want);
569
    assert_eq!(fs::read(root.join("b/g.txt")).unwrap(), b"g\n");
570
    assert!(!b.snapshot("status").unwrap().changed);
571
572
    // Concurrent edits of the same line: the union is a reified conflict.
573
    write(&root.join("a"), "f.txt", b"a\nA\n");
574
    a.commit("a-edit", &[]).unwrap();
575
    a.push("origin", false).unwrap();
576
    write(&root.join("b"), "f.txt", b"a\nB\n");
577
    b.commit("b-edit", &[]).unwrap();
578
    let pr = b.pull("origin").unwrap();
579
    assert!(pr.changed && pr.checked_out);
580
    let text = fs::read_to_string(root.join("b/f.txt")).unwrap();
581
    assert!(text.contains("<<<<<<< oxy conflict"), "{text}");
582
    write(&root.join("b"), "f.txt", b"a\nAB\n");
583
    let hr = b.commit("resolve", &[]).unwrap();
584
    assert_eq!(
585
        b.store().get_change(&hr).unwrap().kind,
586
        ChangeKind::Resolution
587
    );
588
    assert!(b.push("origin", false).unwrap()[0].ok);
589
    a.pull("origin").unwrap();
590
    assert_eq!(fs::read(root.join("a/f.txt")).unwrap(), b"a\nAB\n");
591
    // The resolution depends on the conflicting edits, but nothing depends
592
    // on "third" (it only added g.txt), so it stays a head beside it.
593
    let mut want = vec![hr, h3];
594
    want.sort();
595
    assert_eq!(a.bookmark_heads().unwrap(), want);
596
    assert!(!a.load_state(&want).unwrap().materialize().is_conflicted());
597
}
598
599
#[test]
600
fn receive_push_rejects_bad_updates() {
601
    hermetic();
602
    let dir = tempfile::tempdir().unwrap();
603
    let root = dir.path();
604
    let origin = Repo::init(&root.join("origin")).unwrap();
605
    let url = root.join("origin").to_string_lossy().to_string();
606
    let mut a = Repo::clone(&url, &root.join("a"))
607
        .unwrap()
608
        .with_home(root.join("home"));
609
    let (key, _) = a
610
        .create_identity("Ada", "a@b", IdentityScope::Repo)
611
        .unwrap();
612
    write(&root.join("a"), "f.txt", b"x\n");
613
    let h1 = a.commit("one", &[]).unwrap();
614
    assert!(a.push("origin", false).unwrap()[0].ok);
615
    let empty = origin.store().put_state(&StateObject::new(vec![])).unwrap();
616
    let s1 = origin
617
        .store()
618
        .put_state(&StateObject::new(vec![h1]))
619
        .unwrap();
620
621
    // Missing head.
622
    let ghost = origin
623
        .store()
624
        .put_state(&StateObject::new(vec![ObjectRef([9; 32])]))
625
        .unwrap();
626
    let r = origin
627
        .receive_push(
628
            Bundle::default(),
629
            vec![RefUpdate {
630
                name: "main".into(),
631
                old_state: s1,
632
                new_state: ghost,
633
                force: false,
634
                attestation: None,
635
            }],
636
            None,
637
            vec![],
638
        )
639
        .unwrap();
640
    assert!(
641
        !r[0].ok && r[0].reason.contains("missing"),
642
        "{}",
643
        r[0].reason
644
    );
645
646
    // Stale old_state.
647
    let r = origin
648
        .receive_push(
649
            Bundle::default(),
650
            vec![RefUpdate {
651
                name: "main".into(),
652
                old_state: empty,
653
                new_state: s1,
654
                force: false,
655
                attestation: None,
656
            }],
657
            None,
658
            vec![],
659
        )
660
        .unwrap();
661
    assert!(!r[0].ok && r[0].reason.contains("stale"), "{}", r[0].reason);
662
663
    // Non-fast-forward without force is refused; with force it passes.
664
    let r = origin
665
        .receive_push(
666
            Bundle::default(),
667
            vec![RefUpdate {
668
                name: "main".into(),
669
                old_state: s1,
670
                new_state: empty,
671
                force: false,
672
                attestation: None,
673
            }],
674
            None,
675
            vec![],
676
        )
677
        .unwrap();
678
    assert!(
679
        !r[0].ok && r[0].reason.contains("fast-forward"),
680
        "{}",
681
        r[0].reason
682
    );
683
    let r = origin
684
        .receive_push(
685
            Bundle::default(),
686
            vec![RefUpdate {
687
                name: "main".into(),
688
                old_state: s1,
689
                new_state: empty,
690
                force: true,
691
                attestation: None,
692
            }],
693
            None,
694
            vec![],
695
        )
696
        .unwrap();
697
    assert!(r[0].ok);
698
    assert_eq!(origin.bookmark_heads().unwrap(), vec![]);
699
700
    // Attestation with a stale serial is a rollback and is refused.
701
    let sa = a
702
        .sign_attest(&Attest {
703
            repo: a.id().unwrap(),
704
            hlc: Hlc::now(),
705
            body: AttestBody::Ref {
706
                name: "main".into(),
707
                old_state: empty,
708
                new_state: s1,
709
                serial: 1,
710
            },
711
        })
712
        .unwrap();
713
    let r = origin
714
        .receive_push(
715
            Bundle::default(),
716
            vec![RefUpdate {
717
                name: "main".into(),
718
                old_state: empty,
719
                new_state: s1,
720
                force: false,
721
                attestation: Some(sa.clone()),
722
            }],
723
            None,
724
            vec![],
725
        )
726
        .unwrap();
727
    assert!(
728
        !r[0].ok && r[0].reason.contains("serial"),
729
        "{}",
730
        r[0].reason
731
    );
732
    // An attestation for a different update is refused too.
733
    let sa2 = a
734
        .sign_attest(&Attest {
735
            repo: a.id().unwrap(),
736
            hlc: Hlc::now(),
737
            body: AttestBody::Ref {
738
                name: "main".into(),
739
                old_state: s1,
740
                new_state: empty,
741
                serial: 5,
742
            },
743
        })
744
        .unwrap();
745
    let r = origin
746
        .receive_push(
747
            Bundle::default(),
748
            vec![RefUpdate {
749
                name: "main".into(),
750
                old_state: empty,
751
                new_state: s1,
752
                force: false,
753
                attestation: Some(sa2),
754
            }],
755
            None,
756
            vec![],
757
        )
758
        .unwrap();
759
    assert!(
760
        !r[0].ok && r[0].reason.contains("describe"),
761
        "{}",
762
        r[0].reason
763
    );
764
    let _ = key;
765
}
766
767
#[test]
768
fn user_config_supplies_defaults_and_clones_sign() {
769
    hermetic();
770
    let dir = tempfile::tempdir().unwrap();
771
    let root = dir.path();
772
    let home = root.join("home");
773
    let origin = Repo::init(&root.join("origin")).unwrap();
774
    let url = root.join("origin").to_string_lossy().to_string();
775
776
    // Identity at user scope: the repository file stays free of author keys.
777
    let mut a = Repo::init(&root.join("a")).unwrap().with_home(&home);
778
    let (key, _) = a
779
        .create_identity("Ada", "[email protected]", IdentityScope::User)
780
        .unwrap();
781
    assert!(!a.config.repo_layer().contains_key("author.key"));
782
    assert_eq!(a.config.author_key, Some(key));
783
    assert!(home.join("config.toml").exists());
784
    a.set_user_config("core.sign", "change").unwrap();
785
    assert!(a.config.sign_changes);
786
787
    // Repository settings override user settings and are the only ones saved.
788
    a.config.set("core.sign", "seal").unwrap();
789
    a.save_config().unwrap();
790
    let again = Repo::open(&root.join("a")).unwrap().with_home(&home);
791
    assert!(!again.config.sign_changes);
792
    assert_eq!(again.config.author_key, Some(key));
793
    assert_eq!(
794
        read_config_file(&root.join("a/.oxy/config"))
795
            .unwrap()
796
            .get("core.sign")
797
            .map(String::as_str),
798
        Some("seal")
799
    );
800
801
    // A fresh clone made by this user signs with the user-level identity,
802
    // even though the clone's store has never seen the identity object.
803
    let b = Repo::clone(&url, &root.join("b")).unwrap().with_home(&home);
804
    assert!(b.config.sign_changes);
805
    write(&root.join("b"), "f.txt", b"f\n");
806
    let h = b.commit("signed from a clone", &[]).unwrap();
807
    assert!(
808
        matches!(b.verify_change(&h).unwrap(), SignatureStatus::Valid { key: k, .. } if k == key)
809
    );
810
    assert!(b.push("origin", false).unwrap()[0].ok);
811
    assert!(matches!(
812
        origin.verify_change(&h).unwrap(),
813
        SignatureStatus::Valid { .. }
814
    ));
815
}
816
817
#[test]
818
fn format1_repositories_are_migrated_on_open() {
819
    hermetic();
820
    use crate::oplog::{Format1Op, Format1View};
821
    let dir = tempfile::tempdir().unwrap();
822
    let root = dir.path();
823
    let repo = Repo::init(root).unwrap();
824
    write(root, "a.txt", b"a\n");
825
    let h1 = repo.commit("one", &[]).unwrap();
826
    let (wc_hash, _) = repo.working_copy().unwrap();
827
    // Rewrite the op log the way format 1 stored it: two ops, head lists.
828
    let mut v1 = Format1View::default();
829
    v1.bookmarks.insert("main".into(), vec![]);
830
    v1.workspaces.insert(repo.workspace(), wc_hash);
831
    let init = Format1Op {
832
        parents: vec![],
833
        hlc: Hlc::default(),
834
        command: "oxy init".into(),
835
        view: v1.clone(),
836
    };
837
    let init_ref = repo.store().put(ObjectType::Op, &init.encode()).unwrap();
838
    v1.bookmarks.insert("main".into(), vec![h1]);
839
    let commit = Format1Op {
840
        parents: vec![init_ref],
841
        hlc: Hlc::default(),
842
        command: "oxy commit".into(),
843
        view: v1,
844
    };
845
    let commit_ref = repo.store().put(ObjectType::Op, &commit.encode()).unwrap();
846
    write_atomic(&root.join(".oxy/ops/head"), commit_ref.to_hex().as_bytes()).unwrap();
847
    write_atomic(&root.join(".oxy/format"), FORMAT1_LINE.as_bytes()).unwrap();
848
    drop(repo);
849
850
    let repo = Repo::open(root).unwrap();
851
    assert_eq!(
852
        fs::read_to_string(root.join(".oxy/format")).unwrap(),
853
        FORMAT_LINE
854
    );
855
    assert_eq!(repo.bookmark_heads().unwrap(), vec![h1]);
856
    let ops = repo.op_log().unwrap();
857
    assert_eq!(
858
        ops.iter()
859
            .map(|(_, o)| o.command.as_str())
860
            .collect::<Vec<_>>(),
861
        ["oxy commit", "oxy init"]
862
    );
863
    assert_eq!(repo.heads_of(&ops[1].1.view, "main").unwrap(), vec![]);
864
    assert!(!repo.snapshot("status").unwrap().changed);
865
    // Reopening again is a no-op.
866
    assert_eq!(Repo::open(root).unwrap().op_log().unwrap().len(), 2);
867
}
868
869
#[test]
870
fn undo_skips_snapshot_operations() {
871
    hermetic();
872
    let dir = tempfile::tempdir().unwrap();
873
    let root = dir.path();
874
    let repo = Repo::init(root).unwrap();
875
    write(root, "a.txt", b"a\n");
876
    let h1 = repo.commit("a", &[]).unwrap();
877
    // A later command snapshots new edits on top of the commit.
878
    write(root, "b.txt", b"b\n");
879
    let s = repo.snapshot("oxy status").unwrap();
880
    assert!(s.changed);
881
    assert!(repo.head_op().unwrap().1.is_snapshot());
882
    assert_eq!(repo.last_command().unwrap().command, "oxy commit -m \"a\"");
883
    // Undo must undo the commit, not the snapshot.
884
    repo.undo().unwrap();
885
    assert_eq!(repo.bookmark_heads().unwrap(), vec![]);
886
    let s = repo.snapshot("oxy status").unwrap();
887
    let paths: Vec<_> = s.statuses.iter().map(|p| p.path.as_str()).collect();
888
    assert_eq!(
889
        paths,
890
        ["a.txt", "b.txt"],
891
        "both files are back in the working copy"
892
    );
893
    assert!(repo.store().get_change(&h1).unwrap().deps.is_empty());
894
    // Only snapshots remain above `init`, so there is nothing left to undo.
895
    assert_eq!(repo.last_command().unwrap().command, "oxy init");
896
    assert!(repo.undo().is_err());
897
}
898
899
#[test]
900
fn independent_changes_commute_and_make_multiple_heads() {
901
    hermetic();
902
    let dir = tempfile::tempdir().unwrap();
903
    let root = dir.path();
904
    let repo = Repo::init(root).unwrap();
905
    write(root, "a.txt", b"a\n");
906
    let h1 = repo.commit("a", &[]).unwrap();
907
    write(root, "b.txt", b"b\n");
908
    let h2 = repo.commit("b", &[]).unwrap();
909
    let c2 = repo.store().get_change(&h2).unwrap();
910
    assert!(c2.deps.is_empty(), "b.txt touches nothing from h1");
911
    let mut heads = repo.bookmark_heads().unwrap();
912
    heads.sort();
913
    let mut want = vec![h1, h2];
914
    want.sort();
915
    assert_eq!(heads, want);
916
    // Editing a.txt depends on h1 only.
917
    write(root, "a.txt", b"a\na2\n");
918
    let h3 = repo.commit("a2", &[]).unwrap();
919
    assert_eq!(repo.store().get_change(&h3).unwrap().deps, vec![h1]);
920
    let heads: BTreeSet<_> = repo.bookmark_heads().unwrap().into_iter().collect();
921
    assert_eq!(heads, [h2, h3].into_iter().collect());
922
    // Explicit dependency.
923
    write(root, "c.txt", b"c\n");
924
    let h4 = repo.commit("c", &[h2]).unwrap();
925
    assert_eq!(repo.store().get_change(&h4).unwrap().deps, vec![h2]);
926
}
927
928
#[test]
929
fn mode_change_and_text_binary_switch() {
930
    hermetic();
931
    let dir = tempfile::tempdir().unwrap();
932
    let root = dir.path();
933
    let repo = Repo::init(root).unwrap();
934
    write(root, "run.sh", b"#!/bin/sh\n");
935
    repo.commit("add script", &[]).unwrap();
936
    #[cfg(unix)]
937
    {
938
        use std::os::unix::fs::PermissionsExt;
939
        fs::set_permissions(root.join("run.sh"), fs::Permissions::from_mode(0o755)).unwrap();
940
        let s = repo.snapshot("status").unwrap();
941
        assert_eq!(
942
            statuses(&s),
943
            vec![("run.sh".into(), ChangeStatus::ModeChanged)]
944
        );
945
        let h = repo.commit("exec", &[]).unwrap();
946
        let snap = repo.load_state(&[h]).unwrap().materialize();
947
        assert!(snap.files["run.sh"].mode.exec);
948
    }
949
    // Text → binary → text.
950
    write(root, "run.sh", b"\0binary");
951
    let h = repo.commit("binary", &[]).unwrap();
952
    let snap = repo.load_state(&[h]).unwrap().materialize();
953
    assert!(snap.files["run.sh"].mode.opaque);
954
    write(root, "run.sh", b"text again\n");
955
    let h = repo.commit("text", &[]).unwrap();
956
    let snap = repo.load_state(&[h]).unwrap().materialize();
957
    assert!(!snap.files["run.sh"].mode.opaque);
958
    assert!(
959
        matches!(&snap.files["run.sh"].content, FileContent::Text { bytes, .. } if bytes == b"text again\n")
960
    );
961
    assert!(!snap.is_conflicted());
962
}
963
964
#[test]
965
fn trust_policy_governs_pushes_and_fetches() {
966
    hermetic();
967
    let dir = tempfile::tempdir().unwrap();
968
    let root = dir.path();
969
    let origin = Repo::init(&root.join("origin")).unwrap();
970
    let url = root.join("origin").to_string_lossy().to_string();
971
972
    // A is the root. Before the policy, an unsigned push from B is fine.
973
    let mut a = Repo::clone(&url, &root.join("a"))
974
        .unwrap()
975
        .with_home(root.join("home-a"));
976
    let (key_a, _) = a
977
        .create_identity("Ada", "[email protected]", IdentityScope::User)
978
        .unwrap();
979
    let mut b = Repo::clone(&url, &root.join("b"))
980
        .unwrap()
981
        .with_home(root.join("home-b"));
982
    write(&root.join("b"), "b.txt", b"b\n");
983
    b.commit("unsigned before policy", &[]).unwrap();
984
    assert!(b.push("origin", false).unwrap()[0].ok);
985
986
    // A creates the policy and pushes it; origin now enforces it.
987
    write(&root.join("a"), "a.txt", b"a\n");
988
    a.commit("a", &[]).unwrap();
989
    let sp = a.policy_init().unwrap();
990
    assert_eq!(sp.policy.serial, 1);
991
    a.pull("origin").unwrap();
992
    let results = a.push("origin", false).unwrap();
993
    assert!(results.iter().all(|r| r.ok), "{results:?}");
994
    assert_eq!(origin.current_policy().unwrap().unwrap().1.policy.serial, 1);
995
996
    // B pulls the policy. Without an identity B cannot push at all.
997
    b.pull("origin").unwrap();
998
    assert!(
999
        b.current_policy().unwrap().is_some(),
1000
        "the policy arrived with the fetch"
1001
    );
1002
    assert!(b.push("origin", false).is_err());
1003
    // With an identity the policy does not list, the push is rejected by origin.
1004
    let (key_b, id_b) = b
1005
        .create_identity("Bob", "[email protected]", IdentityScope::User)
1006
        .unwrap();
1007
    write(&root.join("b"), "b.txt", b"b2\n");
1008
    let h_b2 = b.commit("b2 as Bob", &[]).unwrap();
1009
    assert_eq!(b.store().get_change(&h_b2).unwrap().author, key_b);
1010
    let r = b.push("origin", false).unwrap();
1011
    assert!(
1012
        !r[0].ok && r[0].reason.contains("may not update"),
1013
        "{:?}",
1014
        r
1015
    );
1016
1017
    // A grants B (identity handed over as a file) and publishes the policy.
1018
    let sp = a.policy_grant(id_b.clone(), None).unwrap();
1019
    assert_eq!(sp.policy.serial, 2);
1020
    let r = a.push("origin", false).unwrap();
1021
    assert!(r.iter().any(|x| x.name == "policy" && x.ok), "{r:?}");
1022
    // B must fetch the new policy before pushing.
1023
    assert!(b
1024
        .push("origin", false)
1025
        .unwrap_or_else(|e| vec![RefResult {
1026
            name: "main".into(),
1027
            ok: false,
1028
            reason: e.to_string()
1029
        }])
1030
        .iter()
1031
        .all(|x| !x.ok));
1032
    b.pull("origin").unwrap();
1033
    assert_eq!(b.current_policy().unwrap().unwrap().1.policy.serial, 2);
1034
    let r = b.push("origin", false).unwrap();
1035
    assert!(r[0].ok, "{:?}", r);
1036
    // Origin verified B's change under the policy.
1037
    let heads = origin.bookmark_heads().unwrap();
1038
    for h in &heads {
1039
        let c = origin.store().get_change(h).unwrap();
1040
        if c.author == key_b {
1041
            origin
1042
                .change_allowed(
1043
                    h,
1044
                    &origin.current_policy().unwrap().unwrap().1.policy,
1045
                    "main",
1046
                )
1047
                .unwrap();
1048
        }
1049
    }
1050
1051
    // A policy signed by a non-root (B) is refused, as is a replayed serial.
1052
    let mut forged = b.current_policy().unwrap().unwrap().1.policy.clone();
1053
    forged.serial = 3;
1054
    forged.roots = vec![key_b];
1055
    let fh = forged.hash();
1056
    let (_, sk_b) = b.secret_key().unwrap().unwrap();
1057
    let forged = SignedPolicy {
1058
        policy: forged,
1059
        sigs: vec![sk_b.sign(Domain::Policy, &key_b, &fh)],
1060
    };
1061
    let r = origin
1062
        .receive_push(Bundle::default(), vec![], Some(forged), vec![])
1063
        .unwrap();
1064
    assert!(!r[0].ok && r[0].reason.contains("root"), "{:?}", r);
1065
    let stale = a.current_policy().unwrap().unwrap().1;
1066
    let mut old = stale.clone();
1067
    old.policy.serial = 1;
1068
    let r = origin
1069
        .receive_push(Bundle::default(), vec![], Some(old), vec![])
1070
        .unwrap();
1071
    assert!(!r[0].ok && r[0].reason.contains("serial"), "{:?}", r);
1072
1073
    // A revokes B; after B pulls the policy, B's pushes are refused again.
1074
    a.pull("origin").unwrap();
1075
    a.policy_revoke(&key_b).unwrap();
1076
    let r = a.push("origin", false).unwrap();
1077
    assert!(r.iter().any(|x| x.name == "policy" && x.ok), "{r:?}");
1078
    b.pull("origin").unwrap();
1079
    write(&root.join("b"), "b.txt", b"b3\n");
1080
    b.commit("b3", &[]).unwrap();
1081
    let r = b.push("origin", false).unwrap();
1082
    assert!(!r[0].ok, "{:?}", r);
1083
1084
    // A clone by a third party receives and verifies everything.
1085
    let c = Repo::clone(&url, &root.join("c"))
1086
        .unwrap()
1087
        .with_home(root.join("home-c"));
1088
    assert_eq!(c.current_policy().unwrap().unwrap().1.policy.serial, 3);
1089
    assert!(c
1090
        .current_policy()
1091
        .unwrap()
1092
        .unwrap()
1093
        .1
1094
        .policy
1095
        .roots
1096
        .contains(&key_a));
1097
    assert!(!c.snapshot("status").unwrap().changed);
1098
}
1099
1100
#[test]
1101
fn gc_packs_objects_and_history_still_works() {
1102
    hermetic();
1103
    let dir = tempfile::tempdir().unwrap();
1104
    let root = dir.path();
1105
    let mut repo = Repo::init(root).unwrap().with_home(root.join("home"));
1106
    repo.create_identity("Ada", "a@b", IdentityScope::User)
1107
        .unwrap();
1108
    repo.set_user_config("core.sign", "change").unwrap();
1109
    write(root, "a.txt", b"one\n");
1110
    let h1 = repo.commit("one", &[]).unwrap();
1111
    write(root, "a.txt", b"two\n");
1112
    write(root, "big.bin", &vec![0u8; 100_000]);
1113
    let h2 = repo.commit("two", &[]).unwrap();
1114
    // Several snapshots leave superseded working-copy versions behind.
1115
    for i in 0..5 {
1116
        write(root, "a.txt", format!("two\n{i}\n").as_bytes());
1117
        repo.snapshot("status").unwrap();
1118
    }
1119
    write(root, "a.txt", b"two\n");
1120
    repo.snapshot("status").unwrap();
1121
    let before = repo.store().list().unwrap();
1122
    assert!(repo.store().loose_count().unwrap() > 0);
1123
1124
    // With the default retention every operation's view is a root: nothing prunes.
1125
    let r = repo.gc(true).unwrap();
1126
    assert_eq!(r.packed.objects, before.len());
1127
    assert_eq!(r.pruned.objects, 0);
1128
    assert_eq!(repo.store().loose_count().unwrap(), 0);
1129
    assert_eq!(repo.store().list().unwrap(), before);
1130
1131
    // With zero retention only the current view is a root: superseded
1132
    // working copies go, everything reachable stays.
1133
    repo.config.set("core.op-retention", "0").unwrap();
1134
    repo.save_config().unwrap();
1135
    let mut repo = Repo::open(root).unwrap().with_home(root.join("home"));
1136
    let r = repo.gc(true).unwrap();
1137
    assert!(r.pruned.objects >= 5, "{r:?}");
1138
    let after = repo.store().list().unwrap();
1139
    assert!(after.len() < before.len());
1140
    assert!(after.contains(&h1) && after.contains(&h2));
1141
    for (_, op) in repo.op_log().unwrap() {
1142
        assert!(!op.command.is_empty(), "operation objects are all kept");
1143
    }
1144
    // Everything still works from the pruned, packed store.
1145
    assert_eq!(repo.bookmark_heads().unwrap(), vec![h2]);
1146
    assert!(matches!(
1147
        repo.verify_change(&h2).unwrap(),
1148
        SignatureStatus::Valid { .. }
1149
    ));
1150
    assert_eq!(repo.log().unwrap().len(), 3);
1151
    repo.checkout(&[h1], false, "checkout").unwrap();
1152
    assert_eq!(fs::read(root.join("a.txt")).unwrap(), b"one\n");
1153
    repo.checkout(&[h2], false, "checkout").unwrap();
1154
    assert_eq!(fs::read(root.join("big.bin")).unwrap().len(), 100_000);
1155
    assert!(!repo.snapshot("status").unwrap().changed);
1156
    // Grace period defers pruning of young garbage.
1157
    write(root, "a.txt", b"three\n");
1158
    repo.commit("three", &[]).unwrap();
1159
    let r = repo.gc(false).unwrap();
1160
    assert_eq!(r.pruned.objects, 0);
1161
    assert!(r.pruned.deferred > 0);
1162
    let r = repo.gc(true).unwrap();
1163
    assert!(r.pruned.objects > 0);
1164
    assert_eq!(repo.log().unwrap().len(), 4);
1165
    // Restoring the default retention makes the old views roots again; the
1166
    // working copies they name were pruned, which gc tolerates.
1167
    repo.config.set("core.op-retention", "90").unwrap();
1168
    repo.save_config().unwrap();
1169
    let repo = Repo::open(root).unwrap().with_home(root.join("home"));
1170
    let r = repo.gc(false).unwrap();
1171
    assert_eq!(r.pruned.objects, 0);
1172
    assert_eq!(repo.log().unwrap().len(), 4);
1173
}
1174
1175
#[test]
1176
fn describe_amend_abandon_heads() {
1177
    hermetic();
1178
    let dir = tempfile::tempdir().unwrap();
1179
    let root = dir.path();
1180
    let mut repo = Repo::init(root).unwrap().with_home(root.join("home"));
1181
    repo.create_identity("Ada", "a@b", IdentityScope::User)
1182
        .unwrap();
1183
    repo.set_user_config("core.sign", "change").unwrap();
1184
    write(root, "a.txt", b"one\n");
1185
    let h1 = repo.commit("first", &[]).unwrap();
1186
    write(root, "a.txt", b"one\ntwo\n");
1187
    let h2 = repo.commit("secnod", &[]).unwrap();
1188
    let id2 = repo.store().get_change(&h2).unwrap().change_id;
1189
1190
    // describe: same ChangeId, new hash, bookmark and working copy follow.
1191
    let h2b = repo.describe(&h2, "second").unwrap();
1192
    assert_ne!(h2b, h2);
1193
    let c = repo.store().get_change(&h2b).unwrap();
1194
    assert_eq!(
1195
        (c.change_id, c.message.as_str(), c.deps.clone()),
1196
        (id2, "second", vec![h1])
1197
    );
1198
    assert_eq!(repo.bookmark_heads().unwrap(), vec![h2b]);
1199
    assert!(matches!(
1200
        repo.verify_change(&h2b).unwrap(),
1201
        SignatureStatus::Valid { .. }
1202
    ));
1203
    let s = repo.snapshot("status").unwrap();
1204
    assert!(s.statuses.is_empty(), "{:?}", s.statuses);
1205
    assert_eq!(
1206
        repo.resolve_change(&id2.short(8)).unwrap(),
1207
        h2b,
1208
        "the old object is no longer reachable from the log"
1209
    );
1210
    // Describing a non-head rewrites its dependents (h2b → h2c') and the working copy.
1211
    let h1b = repo.describe(&h1, "first, described").unwrap();
1212
    assert_ne!(h1b, h1);
1213
    let heads = repo.bookmark_heads().unwrap();
1214
    assert_eq!(heads.len(), 1);
1215
    let top = repo.store().get_change(&heads[0]).unwrap();
1216
    assert_eq!((top.change_id, top.deps.clone()), (id2, vec![h1b]));
1217
    assert!(
1218
        matches!(
1219
            repo.verify_change(&heads[0]).unwrap(),
1220
            SignatureStatus::Valid { .. }
1221
        ),
1222
        "rewritten own change is re-signed"
1223
    );
1224
    let (_, wc) = repo.working_copy().unwrap();
1225
    assert_eq!(
1226
        wc.deps,
1227
        vec![heads[0]],
1228
        "the working copy follows the rewrite"
1229
    );
1230
    assert!(!repo.snapshot("status").unwrap().changed);
1231
    let snap = repo.load_state(&heads).unwrap().materialize();
1232
    assert!(
1233
        matches!(&snap.files["a.txt"].content, FileContent::Text { bytes, .. } if bytes == b"one\ntwo\n")
1234
    );
1235
1236
    // amend: fold an edit into the head; the result is one change from h1.
1237
    write(root, "a.txt", b"one\ntwo\nthree\n");
1238
    write(root, "b.txt", b"b\n");
1239
    let h2c = repo.amend(None).unwrap();
1240
    let c = repo.store().get_change(&h2c).unwrap();
1241
    assert_eq!(c.change_id, id2);
1242
    assert_eq!(c.message, "second");
1243
    assert_eq!(repo.bookmark_heads().unwrap(), vec![h2c]);
1244
    assert_eq!(
1245
        repo.log().unwrap().len(),
1246
        3,
1247
        "working copy, amended head, first"
1248
    );
1249
    let snap = repo.load_state(&[h2c]).unwrap().materialize();
1250
    assert!(
1251
        matches!(&snap.files["a.txt"].content, FileContent::Text { bytes, .. } if bytes == b"one\ntwo\nthree\n")
1252
    );
1253
    assert!(snap.files.contains_key("b.txt"));
1254
    assert!(!repo.snapshot("status").unwrap().changed);
1255
    assert!(
1256
        repo.amend(None).is_err(),
1257
        "clean working copy and no message"
1258
    );
1259
    let h2d = repo.amend(Some("second, amended")).unwrap();
1260
    assert_eq!(
1261
        repo.store().get_change(&h2d).unwrap().message,
1262
        "second, amended"
1263
    );
1264
1265
    // abandon: the head goes, its content stays as uncommitted work.
1266
    repo.abandon(&h2d).unwrap();
1267
    assert_eq!(
1268
        repo.bookmark_heads().unwrap(),
1269
        vec![h1b],
1270
        "the described first change is the head again"
1271
    );
1272
    let s = repo.snapshot("status").unwrap();
1273
    let paths: Vec<_> = s
1274
        .statuses
1275
        .iter()
1276
        .map(|p| (p.path.as_str(), p.status))
1277
        .collect();
1278
    assert_eq!(
1279
        paths,
1280
        vec![
1281
            ("a.txt", ChangeStatus::Modified),
1282
            ("b.txt", ChangeStatus::Added)
1283
        ]
1284
    );
1285
    assert_eq!(fs::read(root.join("a.txt")).unwrap(), b"one\ntwo\nthree\n");
1286
    let h3 = repo.commit("recommitted", &[]).unwrap();
1287
    assert_eq!(repo.bookmark_heads().unwrap(), vec![h3]);
1288
    // undo brings the abandoned head back.
1289
    repo.undo().unwrap();
1290
    repo.undo().unwrap();
1291
    assert_eq!(repo.bookmark_heads().unwrap(), vec![h2d]);
1292
1293
    // Abandoning a non-head whose dependent references its atoms reifies
1294
    // the references (here: a.txt vanishes with it, so the dependent's edit
1295
    // of a.txt is dropped with a note) instead of refusing; undo restores it.
1296
    let base = repo.bookmark_heads().unwrap()[0];
1297
    let base_change = repo.store().get_change(&base).unwrap();
1298
    let h1_now = base_change.deps[0];
1299
    let notes = repo.abandon(&h1_now).unwrap();
1300
    assert!(
1301
        !notes.is_empty(),
1302
        "the dependent's edit of a.txt was reified"
1303
    );
1304
    let heads = repo.bookmark_heads().unwrap();
1305
    let after = repo.load_state(&heads).unwrap().materialize();
1306
    assert!(
1307
        !after.files.contains_key("a.txt") && after.files.contains_key("b.txt"),
1308
        "{:?}",
1309
        after.files.keys()
1310
    );
1311
    repo.undo().unwrap();
1312
    assert_eq!(repo.bookmark_heads().unwrap(), vec![base]);
1313
    write(root, "c.txt", b"c\n");
1314
    let hc = repo.commit("c", &[]).unwrap();
1315
    write(root, "d.txt", b"d\n");
1316
    let hd = repo.commit("d", &[hc]).unwrap();
1317
    assert_eq!(repo.store().get_change(&hd).unwrap().deps, vec![hc]);
1318
    repo.abandon(&hc).unwrap();
1319
    let heads: BTreeSet<_> = repo.bookmark_heads().unwrap().into_iter().collect();
1320
    assert!(!heads.contains(&hc));
1321
    let d_now = heads
1322
        .iter()
1323
        .find(|h| repo.store().get_change(h).unwrap().message == "d")
1324
        .copied()
1325
        .unwrap();
1326
    assert!(
1327
        repo.store().get_change(&d_now).unwrap().deps.is_empty(),
1328
        "d inherited c's (empty) dependencies"
1329
    );
1330
    let s = repo.snapshot("status").unwrap();
1331
    assert_eq!(
1332
        s.statuses
1333
            .iter()
1334
            .map(|p| p.path.as_str())
1335
            .collect::<Vec<_>>(),
1336
        vec!["c.txt"],
1337
        "c's content is now uncommitted work"
1338
    );
1339
}
1340
1341
#[test]
1342
fn git_export_mirrors_history() {
1343
    hermetic();
1344
    if std::process::Command::new("git")
1345
        .arg("--version")
1346
        .output()
1347
        .is_err()
1348
    {
1349
        eprintln!("git not installed; skipping");
1350
        return;
1351
    }
1352
    let dir = tempfile::tempdir().unwrap();
1353
    let root = dir.path();
1354
    let mut repo = Repo::init(&root.join("r"))
1355
        .unwrap()
1356
        .with_home(root.join("home"));
1357
    repo.create_identity("Ada Lovelace", "[email protected]", IdentityScope::User)
1358
        .unwrap();
1359
    let r = root.join("r");
1360
    write(&r, "README.md", b"hello\n");
1361
    write(&r, "src/main.rs", b"fn main() {}\n");
1362
    let h1 = repo.commit("first", &[]).unwrap();
1363
    write(&r, "src/main.rs", b"fn main() { run(); }\n");
1364
    write(&r, "logo.png", b"\x89PNG\0\0");
1365
    let h2 = repo.commit("second", &[]).unwrap();
1366
1367
    let git_dir = root.join("mirror.git");
1368
    let rep = repo.git_export(&git_dir).unwrap();
1369
    assert_eq!((rep.exported, rep.skipped, rep.heads), (2, 0, 1));
1370
    let git = |args: &[&str]| -> String {
1371
        let out = std::process::Command::new("git")
1372
            .arg("-C")
1373
            .arg(&git_dir)
1374
            .args(args)
1375
            .output()
1376
            .unwrap();
1377
        assert!(
1378
            out.status.success(),
1379
            "{}",
1380
            String::from_utf8_lossy(&out.stderr)
1381
        );
1382
        String::from_utf8_lossy(&out.stdout).trim().to_string()
1383
    };
1384
    assert_eq!(git(&["log", "--format=%s", "main"]), "second\nfirst");
1385
    assert_eq!(git(&["show", "main:src/main.rs"]), "fn main() { run(); }");
1386
    assert_eq!(git(&["show", "main:README.md"]), "hello");
1387
    let body = git(&["log", "-1", "--format=%B", "main"]);
1388
    assert!(
1389
        body.contains(&format!("Oxy-Hash: {}", h2.to_hex())),
1390
        "{body}"
1391
    );
1392
    assert!(body.contains("Change-Id: "), "{body}");
1393
    assert_eq!(
1394
        git(&["log", "-1", "--format=%an <%ae>", "main"]),
1395
        "Ada Lovelace <[email protected]>"
1396
    );
1397
    assert_eq!(
1398
        git(&["ls-tree", "--name-only", "main"]),
1399
        "README.md\nlogo.png\nsrc"
1400
    );
1401
1402
    // Re-export is incremental.
1403
    let rep = repo.git_export(&git_dir).unwrap();
1404
    assert_eq!((rep.exported, rep.skipped), (0, 2));
1405
1406
    // An independent change makes two heads; the next state is one more
1407
    // commit on the linear branch whose tree is the union.
1408
    repo.checkout(&[h1], false, "checkout").unwrap();
1409
    write(&r, "other.txt", b"o\n");
1410
    let h3 = repo.commit("third", &[]).unwrap();
1411
    let rep = repo.git_export(&git_dir).unwrap();
1412
    assert_eq!((rep.exported, rep.heads), (1, 2));
1413
    assert_eq!(git(&["log", "--format=%s", "main"]), "third\nsecond\nfirst");
1414
    let parents = git(&["rev-list", "--parents", "-1", "main"]);
1415
    assert_eq!(parents.split(' ').count(), 2, "one parent: {parents}");
1416
    assert_eq!(git(&["show", "main:other.txt"]), "o");
1417
    assert_eq!(git(&["show", "main:src/main.rs"]), "fn main() { run(); }");
1418
    assert_eq!(
1419
        git(&["ls-tree", "--name-only", "main"]),
1420
        "README.md\nlogo.png\nother.txt\nsrc"
1421
    );
1422
    let body = git(&["log", "-1", "--format=%B", "main"]);
1423
    assert!(
1424
        body.contains(&format!("Oxy-Hash: {}", h3.to_hex())) && body.contains("Oxy-State: "),
1425
        "{body}"
1426
    );
1427
    // A rewrite is a new state whose one new change is the rewritten one.
1428
    repo.describe(&h3, "third, described").unwrap();
1429
    let rep = repo.git_export(&git_dir).unwrap();
1430
    assert_eq!(rep.exported, 1);
1431
    assert_eq!(
1432
        git(&["log", "-1", "--format=%s", "main"]),
1433
        "third, described"
1434
    );
1435
    assert_eq!(git(&["log", "--format=%s", "main"]).lines().count(), 4);
1436
    let _ = h2;
1437
}
1438
1439
#[test]
1440
fn git_import_reproduces_trees() {
1441
    hermetic();
1442
    if std::process::Command::new("git")
1443
        .arg("--version")
1444
        .output()
1445
        .is_err()
1446
    {
1447
        eprintln!("git not installed; skipping");
1448
        return;
1449
    }
1450
    let dir = tempfile::tempdir().unwrap();
1451
    let root = dir.path();
1452
    let g = root.join("src.git");
1453
    fs::create_dir_all(&g).unwrap();
1454
    let git = |args: &[&str]| -> String {
1455
        let out = std::process::Command::new("git")
1456
            .arg("-C")
1457
            .arg(&g)
1458
            .args([
1459
                "-c",
1460
                "user.name=Grace",
1461
                "-c",
1462
                "[email protected]",
1463
                "-c",
1464
                "commit.gpgsign=false",
1465
            ])
1466
            .args(args)
1467
            .output()
1468
            .unwrap();
1469
        assert!(
1470
            out.status.success(),
1471
            "git {args:?}: {}",
1472
            String::from_utf8_lossy(&out.stderr)
1473
        );
1474
        String::from_utf8_lossy(&out.stdout).trim().to_string()
1475
    };
1476
    git(&["init", "-q", "-b", "main"]);
1477
    write(&g, "README.md", b"# Hi\n");
1478
    write(&g, "src/lib.rs", b"pub fn a() {}\n");
1479
    git(&["add", "."]);
1480
    git(&["commit", "-q", "-m", "initial"]);
1481
    write(&g, "src/lib.rs", b"pub fn a() {}\npub fn b() {}\n");
1482
    write(&g, "run.sh", b"#!/bin/sh\n");
1483
    #[cfg(unix)]
1484
    {
1485
        use std::os::unix::fs::PermissionsExt;
1486
        fs::set_permissions(g.join("run.sh"), fs::Permissions::from_mode(0o755)).unwrap();
1487
    }
1488
    write(&g, "logo.png", b"\x89PNG\0\0\x01");
1489
    git(&["add", "."]);
1490
    git(&[
1491
        "commit",
1492
        "-q",
1493
        "-m",
1494
        "second\n\nChange-Id: 0123456789abcdef0123456789abcdef",
1495
    ]);
1496
    // A branch that edits README, merged back with a conflict-free merge.
1497
    git(&["checkout", "-q", "-b", "topic", "HEAD~1"]);
1498
    write(&g, "README.md", b"# Hi\n\nMore.\n");
1499
    git(&["commit", "-q", "-am", "readme"]);
1500
    git(&["checkout", "-q", "main"]);
1501
    git(&["merge", "-q", "--no-ff", "-m", "merge topic", "topic"]);
1502
    // A branch from the initial commit inserting at the same place as
1503
    // "second": concurrent in Oxygen too, so the merge commit is a resolution.
1504
    let initial = git(&["rev-list", "--max-parents=0", "HEAD"]);
1505
    git(&["checkout", "-q", "-b", "clash", &initial]);
1506
    write(&g, "src/lib.rs", b"pub fn a() {}\npub fn c() {}\n");
1507
    git(&["commit", "-q", "-am", "clash"]);
1508
    git(&["checkout", "-q", "main"]);
1509
    let _ = std::process::Command::new("git")
1510
        .arg("-C")
1511
        .arg(&g)
1512
        .args(["merge", "-q", "clash"])
1513
        .output();
1514
    write(
1515
        &g,
1516
        "src/lib.rs",
1517
        b"pub fn a() {}\npub fn b() {}\npub fn c() {}\n",
1518
    );
1519
    git(&["add", "."]);
1520
    git(&["commit", "-q", "-m", "resolve clash"]);
1521
    git(&["rm", "-q", "logo.png"]);
1522
    git(&["commit", "-q", "-m", "drop logo"]);
1523
    // A rename with a small edit is imported as a move of the same node.
1524
    git(&["mv", "src/lib.rs", "src/lib2.rs"]);
1525
    write(
1526
        &g,
1527
        "src/lib2.rs",
1528
        b"pub fn a() {}\npub fn b() {}\npub fn c() {}\npub fn d() {}\n",
1529
    );
1530
    git(&["add", "."]);
1531
    git(&["commit", "-q", "-m", "rename lib"]);
1532
    // A branch that edits run.sh, merged keeping main's tree (`-s ours`):
1533
    // run.sh is the same as in the first parent's tree, but the merged
1534
    // change touched it, so the importer must compare it, not skip it.
1535
    git(&["checkout", "-q", "-b", "discarded"]);
1536
    write(&g, "run.sh", b"#!/bin/sh\necho discarded\n");
1537
    git(&["commit", "-q", "-am", "discarded edit"]);
1538
    git(&["checkout", "-q", "main"]);
1539
    git(&[
1540
        "merge",
1541
        "-q",
1542
        "-s",
1543
        "ours",
1544
        "-m",
1545
        "merge discarded, keeping ours",
1546
        "discarded",
1547
    ]);
1548
    let expected_count: usize = git(&["rev-list", "--count", "main"]).parse().unwrap();
1549
1550
    let dest = root.join("oxy");
1551
    let repo = Repo::init(&dest).unwrap().with_home(root.join("home"));
1552
    let rep = repo.import_git(&g, "main").unwrap();
1553
    assert_eq!(rep.commits, expected_count);
1554
    assert_eq!(rep.merges, 3);
1555
    assert_eq!(
1556
        fs::read(dest.join("run.sh")).unwrap(),
1557
        b"#!/bin/sh\n",
1558
        "the ours merge kept main's run.sh"
1559
    );
1560
    let v = repo.verify_git_import(&g, "main").unwrap();
1561
    assert_eq!(v.commits, expected_count, "every commit's tree reproduced");
1562
    assert!(v.mismatches.is_empty(), "{:?}", v.mismatches);
1563
    // The working copy equals the Git tree at main.
1564
    assert_eq!(
1565
        fs::read(dest.join("src/lib2.rs")).unwrap(),
1566
        b"pub fn a() {}\npub fn b() {}\npub fn c() {}\npub fn d() {}\n"
1567
    );
1568
    assert!(!dest.join("src/lib.rs").exists());
1569
    assert_eq!(
1570
        fs::read(dest.join("README.md")).unwrap(),
1571
        b"# Hi\n\nMore.\n"
1572
    );
1573
    assert!(!dest.join("logo.png").exists());
1574
    #[cfg(unix)]
1575
    {
1576
        use std::os::unix::fs::PermissionsExt;
1577
        assert!(
1578
            fs::metadata(dest.join("run.sh"))
1579
                .unwrap()
1580
                .permissions()
1581
                .mode()
1582
                & 0o111
1583
                != 0
1584
        );
1585
    }
1586
    assert!(
1587
        !repo.snapshot("status").unwrap().changed,
1588
        "clean after import"
1589
    );
1590
    let heads = repo.bookmark_heads().unwrap();
1591
    let st = repo.load_state(&heads).unwrap();
1592
    assert!(!st.materialize().is_conflicted());
1593
    assert_eq!(st.len(), expected_count);
1594
    let tip = repo
1595
        .log()
1596
        .unwrap()
1597
        .into_iter()
1598
        .find(|e| e.change.message.starts_with("rename lib"))
1599
        .unwrap();
1600
    let c = repo.store().get_change(&tip.hash).unwrap();
1601
    assert!(
1602
        c.tree_ops
1603
            .iter()
1604
            .any(|op| matches!(op, TreeOp::Move { name, .. } if name == "lib2.rs")),
1605
        "{:?}",
1606
        c.tree_ops
1607
    );
1608
    assert!(!c
1609
        .tree_ops
1610
        .iter()
1611
        .any(|op| matches!(op, TreeOp::AddNode { .. })));
1612
    // Messages carry Git trailers; the Change-Id trailer was honoured.
1613
    let log = repo.log().unwrap();
1614
    let second = log
1615
        .iter()
1616
        .find(|e| e.change.message.starts_with("second"))
1617
        .unwrap();
1618
    assert_eq!(
1619
        second.change.change_id,
1620
        ChangeId::from_hex("0123456789abcdef0123456789abcdef").unwrap()
1621
    );
1622
    assert!(second
1623
        .change
1624
        .message
1625
        .contains("Git-Author: Grace <[email protected]>"));
1626
    let resolve = log
1627
        .iter()
1628
        .find(|e| e.change.message.starts_with("resolve clash"))
1629
        .unwrap();
1630
    assert_eq!(
1631
        resolve.change.kind,
1632
        ChangeKind::Resolution,
1633
        "a conflicting Git merge becomes a resolution"
1634
    );
1635
    // Re-importing into another fresh repository gives the same ChangeIds.
1636
    let repo2 = Repo::init(&root.join("oxy2"))
1637
        .unwrap()
1638
        .with_home(root.join("home"));
1639
    repo2.import_git(&g, "main").unwrap();
1640
    // New nodes' identifiers derive from the commit (spec §23), so the
1641
    // re-import is not just the same ChangeIds but the same changes.
1642
    assert_eq!(
1643
        repo2.bookmark_heads().unwrap(),
1644
        repo.bookmark_heads().unwrap()
1645
    );
1646
    let ids: BTreeSet<ChangeId> = repo
1647
        .log()
1648
        .unwrap()
1649
        .iter()
1650
        .filter(|e| !e.is_working_copy)
1651
        .map(|e| e.change.change_id)
1652
        .collect();
1653
    let ids2: BTreeSet<ChangeId> = repo2
1654
        .log()
1655
        .unwrap()
1656
        .iter()
1657
        .filter(|e| !e.is_working_copy)
1658
        .map(|e| e.change.change_id)
1659
        .collect();
1660
    assert_eq!(ids, ids2);
1661
    // Round trip back out to Git reproduces the tip tree.
1662
    let mirror = root.join("mirror.git");
1663
    repo.git_export(&mirror).unwrap();
1664
    let out = std::process::Command::new("git")
1665
        .arg("-C")
1666
        .arg(&mirror)
1667
        .args(["show", "main:src/lib2.rs"])
1668
        .output()
1669
        .unwrap();
1670
    assert_eq!(
1671
        String::from_utf8_lossy(&out.stdout),
1672
        "pub fn a() {}\npub fn b() {}\npub fn c() {}\npub fn d() {}\n"
1673
    );
1674
    let out = std::process::Command::new("git")
1675
        .arg("-C")
1676
        .arg(&mirror)
1677
        .args(["show", "main:src/lib.rs"])
1678
        .output()
1679
        .unwrap();
1680
    assert!(
1681
        !out.status.success(),
1682
        "the old path is gone from the export"
1683
    );
1684
}
1685
1686
#[test]
1687
fn checkpoints_accelerate_loading_and_stay_correct() {
1688
    hermetic();
1689
    let dir = tempfile::tempdir().unwrap();
1690
    let root = dir.path();
1691
    let mut repo = Repo::init(root).unwrap().with_home(root.join("home"));
1692
    repo.config.set("core.checkpoint-interval", "5").unwrap();
1693
    repo.save_config().unwrap();
1694
    let repo = Repo::open(root).unwrap().with_home(root.join("home"));
1695
    let mut hashes = Vec::new();
1696
    for i in 0..12 {
1697
        write(
1698
            root,
1699
            "a.txt",
1700
            format!(
1701
                "{}\n",
1702
                (0..=i)
1703
                    .map(|k| k.to_string())
1704
                    .collect::<Vec<_>>()
1705
                    .join("\n")
1706
            )
1707
            .as_bytes(),
1708
        );
1709
        write(root, &format!("f{i}.txt"), b"x\n");
1710
        hashes.push(repo.commit(&format!("c{i}"), &[]).unwrap());
1711
    }
1712
    let (_, cp) = repo
1713
        .latest_checkpoint("main")
1714
        .unwrap()
1715
        .expect("automatic checkpoint");
1716
    assert!(cp.count >= 5 && cp.count <= 12, "{}", cp.count);
1717
    // Loading through the checkpoint equals loading everything.
1718
    let heads = repo.bookmark_heads().unwrap();
1719
    let fast = repo.load_state(&heads).unwrap();
1720
    let full = repo.load_state_full(&heads).unwrap();
1721
    assert_eq!(fast.len(), full.len());
1722
    assert_eq!(fast.heads(), full.heads());
1723
    let (a, b) = (fast.materialize(), full.materialize());
1724
    assert_eq!(
1725
        a.files.keys().collect::<Vec<_>>(),
1726
        b.files.keys().collect::<Vec<_>>()
1727
    );
1728
    for (p, f) in &a.files {
1729
        assert_eq!(f.content, b.files[p].content, "{p}");
1730
    }
1731
    assert!(repo.load_state_checkpointed(&heads).unwrap().is_some());
1732
    // A head set that does not contain the checkpoint's heads falls back.
1733
    assert!(repo
1734
        .load_state_checkpointed(&[hashes[0]])
1735
        .unwrap()
1736
        .is_none());
1737
    assert_eq!(repo.load_state(&[hashes[0]]).unwrap().len(), 1);
1738
    // Everything else keeps working on top of the checkpoint.
1739
    assert!(!repo.snapshot("status").unwrap().changed);
1740
    let h = repo.describe(&hashes[3], "c3 described").unwrap();
1741
    assert_eq!(repo.store().get_change(&h).unwrap().message, "c3 described");
1742
    let (r, n, bytes) = repo.checkpoint().unwrap();
1743
    assert!(n >= 12 && bytes > 0);
1744
    assert_eq!(repo.latest_checkpoint("main").unwrap().unwrap().0, r);
1745
    write(root, "a.txt", b"after\n");
1746
    let h_after = repo.commit("after", &[]).unwrap();
1747
    let st = repo.load_state(&repo.bookmark_heads().unwrap()).unwrap();
1748
    assert!(st.contains(&h_after));
1749
    assert!(
1750
        matches!(&st.materialize().files["a.txt"].content, FileContent::Text { bytes, .. } if bytes == b"after\n")
1751
    );
1752
    assert_eq!(repo.log().unwrap().len(), 14);
1753
    // Checkpoints survive gc.
1754
    repo.gc(true).unwrap();
1755
    assert!(repo.latest_checkpoint("main").unwrap().is_some());
1756
    assert!(repo
1757
        .load_state_checkpointed(&repo.bookmark_heads().unwrap())
1758
        .unwrap()
1759
        .is_some());
1760
}
1761
1762
#[test]
1763
fn quick_status_for_prompts() {
1764
    hermetic();
1765
    let dir = tempfile::tempdir().unwrap();
1766
    let root = dir.path();
1767
    let origin = Repo::init(&root.join("origin")).unwrap();
1768
    let url = root.join("origin").to_string_lossy().to_string();
1769
    let a = Repo::clone(&url, &root.join("a"))
1770
        .unwrap()
1771
        .with_home(root.join("home"));
1772
    let ops_before = a.op_log().unwrap().len();
1773
    let info = a.quick_status().unwrap();
1774
    assert_eq!(
1775
        (
1776
            info.bookmark.as_str(),
1777
            info.heads,
1778
            info.dirty,
1779
            info.conflicted,
1780
            info.ahead,
1781
            info.behind
1782
        ),
1783
        ("main", 0, false, false, Some(0), Some(0))
1784
    );
1785
    write(&root.join("a"), "f.txt", b"f\n");
1786
    assert!(a.quick_status().unwrap().dirty, "a new file is dirty");
1787
    assert_eq!(
1788
        a.op_log().unwrap().len(),
1789
        ops_before,
1790
        "quick_status records nothing"
1791
    );
1792
    // A snapshotted but uncommitted change is still dirty.
1793
    a.snapshot("status").unwrap();
1794
    assert!(a.quick_status().unwrap().dirty);
1795
    a.commit("f", &[]).unwrap();
1796
    let info = a.quick_status().unwrap();
1797
    assert!(!info.dirty, "clean right after a commit");
1798
    assert_eq!((info.ahead, info.behind), (Some(1), Some(0)));
1799
    assert_eq!(
1800
        info.format("%b %c%d%x%A%D"),
1801
        format!("main {}+1", info.change_id)
1802
    );
1803
    assert_eq!(info.format("[%h heads] %a/%B %%"), "[1 heads] 1/0 %");
1804
    // Touching a file without changing it is not dirty; changing content of
1805
    // the same size is.
1806
    let p = root.join("a/f.txt");
1807
    let content = fs::read(&p).unwrap();
1808
    fs::write(&p, &content).unwrap();
1809
    assert!(!a.quick_status().unwrap().dirty);
1810
    fs::write(&p, b"g\n").unwrap();
1811
    assert!(a.quick_status().unwrap().dirty);
1812
    fs::write(&p, b"f\n").unwrap();
1813
    // Push, then a second clone commits and pushes: we are behind.
1814
    assert!(a.push("origin", false).unwrap()[0].ok);
1815
    assert_eq!(a.quick_status().unwrap().ahead, Some(0));
1816
    let b = Repo::clone(&url, &root.join("b"))
1817
        .unwrap()
1818
        .with_home(root.join("home-b"));
1819
    write(&root.join("b"), "g.txt", b"g\n");
1820
    b.commit("g", &[]).unwrap();
1821
    b.push("origin", false).unwrap();
1822
    a.fetch("origin").unwrap();
1823
    let info = a.quick_status().unwrap();
1824
    assert_eq!((info.ahead, info.behind), (Some(0), Some(1)));
1825
    assert_eq!(info.format("%A%D"), "-1");
1826
    let _ = origin;
1827
}
1828
1829
#[test]
1830
fn lazy_blobs_are_fetched_on_first_read() {
1831
    hermetic();
1832
    let dir = tempfile::tempdir().unwrap();
1833
    let root = dir.path();
1834
    let origin_dir = root.join("origin");
1835
    let origin = Repo::init(&origin_dir)
1836
        .unwrap()
1837
        .with_home(root.join("home"));
1838
    let url = origin_dir.to_string_lossy().to_string();
1839
    let big: Vec<u8> = (0..200_000u32).map(|i| (i % 251) as u8).collect(); // has NUL bytes: opaque
1840
    write(&origin_dir, "big.bin", &big);
1841
    write(&origin_dir, "small.bin", &[0u8, 1, 2]);
1842
    write(&origin_dir, "t.txt", b"t\n");
1843
    let h = origin.commit("blobs", &[]).unwrap();
1844
    let big_ref = Repo::blob_ref(&big);
1845
1846
    // Fetch only (no checkout) with a filter: the big blob stays absent.
1847
    let a = Repo::init_with_id(&root.join("a"), origin.id().unwrap())
1848
        .unwrap()
1849
        .with_home(root.join("home"));
1850
    let a = {
1851
        let mut a = a;
1852
        a.config.set("remote.origin.url", &url).unwrap();
1853
        a.config.set("filter.max-blob", "100K").unwrap();
1854
        a.save_config().unwrap();
1855
        a
1856
    };
1857
    assert_eq!(a.config.max_blob, Some(100 * 1024));
1858
    a.fetch("origin").unwrap();
1859
    assert!(a.store().has(&h));
1860
    assert!(!a.store().has(&big_ref), "withheld");
1861
    assert!(
1862
        a.store().has(&Repo::blob_ref(&[0u8, 1, 2])),
1863
        "small blob came along"
1864
    );
1865
    assert_eq!(a.lazy_remote(&big_ref).as_deref(), Some("origin"));
1866
1867
    // status and commit do not need it: adopt the state, edit a text file, commit.
1868
    let (op_ref, op) = a.head_op().unwrap();
1869
    let mut view = op.view.clone();
1870
    view.bookmarks.insert(
1871
        "main".into(),
1872
        a.store().put_state(&StateObject::new(vec![h])).unwrap(),
1873
    );
1874
    a.record_op(&[op_ref], "adopt", view).unwrap();
1875
    // Checkout reads the blob lazily, which fetches it.
1876
    a.checkout(&[h], true, "checkout").unwrap();
1877
    assert!(a.store().has(&big_ref), "fetched on first read");
1878
    assert_eq!(fs::read(root.join("a/big.bin")).unwrap(), big);
1879
    assert!(a.lazy_remote(&big_ref).is_none(), "no longer registered");
1880
    write(&root.join("a"), "t.txt", b"t2\n");
1881
    a.commit("text edit", &[]).unwrap();
1882
1883
    // clone --max-blob records the filter; the checkout fetches lazily.
1884
    let b = Repo::clone_with(&url, &root.join("b"), Some(1024), &[]).unwrap();
1885
    assert_eq!(b.config.max_blob, Some(1024));
1886
    assert_eq!(fs::read(root.join("b/big.bin")).unwrap(), big);
1887
    assert_eq!(parse_size("2M").unwrap(), 2 << 20);
1888
    assert!(parse_size("lots").is_err());
1889
}
1890
1891
#[test]
1892
fn sparse_checkout_materializes_only_chosen_paths() {
1893
    hermetic();
1894
    let dir = tempfile::tempdir().unwrap();
1895
    let root = dir.path();
1896
    let origin_dir = root.join("origin");
1897
    let origin = Repo::init(&origin_dir)
1898
        .unwrap()
1899
        .with_home(root.join("home"));
1900
    write(&origin_dir, "src/main.rs", b"fn main() {}\n");
1901
    write(&origin_dir, "src/lib.rs", b"pub fn a() {}\n");
1902
    write(&origin_dir, "docs/guide.md", b"# guide\n");
1903
    let logo: Vec<u8> = (0..50_000u32).map(|i| (i % 7) as u8).collect();
1904
    write(&origin_dir, "docs/logo.png", &logo);
1905
    write(&origin_dir, "README.md", b"# top\n");
1906
    let h1 = origin.commit("tree", &[]).unwrap();
1907
    let url = origin_dir.to_string_lossy().to_string();
1908
1909
    let a = Repo::clone_with(&url, &root.join("a"), None, &["src".into()])
1910
        .unwrap()
1911
        .with_home(root.join("home"));
1912
    assert_eq!(a.config.sparse_paths, vec!["src"]);
1913
    assert_eq!(a.config.max_blob, Some(0), "sparse implies lazy blobs");
1914
    assert!(root.join("a/src/main.rs").exists());
1915
    assert!(!root.join("a/docs").exists() && !root.join("a/README.md").exists());
1916
    assert!(
1917
        !a.store().has(&Repo::blob_ref(&logo)),
1918
        "out-of-scope blob never fetched"
1919
    );
1920
    assert!(
1921
        !a.snapshot("status").unwrap().changed,
1922
        "out-of-scope files are not removals"
1923
    );
1924
    assert!(!a.quick_status().unwrap().dirty);
1925
1926
    // Edits in scope commit normally and keep the rest of the tree intact.
1927
    write(
1928
        &root.join("a"),
1929
        "src/lib.rs",
1930
        b"pub fn a() {}\npub fn b() {}\n",
1931
    );
1932
    let h2 = a.commit("edit lib", &[]).unwrap();
1933
    let st = a.load_state(&[h2]).unwrap().materialize();
1934
    assert!(
1935
        st.files.contains_key("docs/guide.md"),
1936
        "the state still has everything"
1937
    );
1938
    assert!(a.push("origin", false).unwrap()[0].ok);
1939
    // Files created outside the scope are ignored by status.
1940
    write(&root.join("a"), "docs/new.md", b"ignored\n");
1941
    assert!(a.snapshot("status").unwrap().statuses.is_empty());
1942
1943
    // Widening the filter checks out the rest; narrowing leaves stray files alone.
1944
    let mut a = a;
1945
    a.config.set("filter.paths", "src,docs").unwrap();
1946
    a.save_config().unwrap();
1947
    let r = a
1948
        .checkout(&a.bookmark_heads().unwrap(), true, "widen")
1949
        .unwrap();
1950
    assert!(r.written >= 2);
1951
    assert_eq!(
1952
        fs::read(root.join("a/docs/logo.png")).unwrap(),
1953
        logo,
1954
        "now fetched lazily"
1955
    );
1956
    assert!(!root.join("a/README.md").exists());
1957
    // Origin sees the change made under a sparse checkout with the full tree intact.
1958
    origin.pull("origin").err();
1959
    let full = origin
1960
        .load_state(&origin.bookmark_heads().unwrap())
1961
        .unwrap()
1962
        .materialize();
1963
    assert!(
1964
        matches!(&full.files["src/lib.rs"].content, FileContent::Text { bytes, .. } if bytes == b"pub fn a() {}\npub fn b() {}\n")
1965
    );
1966
    assert!(full.files.contains_key("README.md"));
1967
    let _ = h1;
1968
}
1969
1970
#[test]
1971
fn shallow_clone_and_deepen() {
1972
    hermetic();
1973
    let dir = tempfile::tempdir().unwrap();
1974
    let root = dir.path();
1975
    let origin_dir = root.join("origin");
1976
    let origin = Repo::init(&origin_dir)
1977
        .unwrap()
1978
        .with_home(root.join("home"));
1979
    let mut hashes = Vec::new();
1980
    for i in 0..8 {
1981
        write(
1982
            &origin_dir,
1983
            "a.txt",
1984
            format!(
1985
                "{}\n",
1986
                (0..=i)
1987
                    .map(|k| k.to_string())
1988
                    .collect::<Vec<_>>()
1989
                    .join("\n")
1990
            )
1991
            .as_bytes(),
1992
        );
1993
        hashes.push(origin.commit(&format!("c{i}"), &[]).unwrap());
1994
    }
1995
    let url = origin_dir.to_string_lossy().to_string();
1996
    let a = Repo::clone_shallow(&url, &root.join("a"), 3, None, &[])
1997
        .unwrap()
1998
        .with_home(root.join("home"));
1999
    assert!(a.is_shallow());
2000
    assert_eq!(
2001
        fs::read_to_string(root.join("a/a.txt")).unwrap(),
2002
        "0\n1\n2\n3\n4\n5\n6\n7\n"
2003
    );
2004
    assert!(
2005
        a.store().has(&hashes[7]) && a.store().has(&hashes[5]),
2006
        "three levels present"
2007
    );
2008
    assert!(!a.store().has(&hashes[4]), "beyond the depth is absent");
2009
    assert_eq!(a.boundary(), [hashes[4]].into_iter().collect());
2010
    assert_eq!(
2011
        a.log().unwrap().len(),
2012
        9,
2013
        "the log shows every change from the checkpoint's metadata"
2014
    );
2015
    assert!(!a.snapshot("status").unwrap().changed);
2016
    assert_eq!(a.quick_status().unwrap().heads, 1);
2017
2018
    // Work continues on top of the shallow history and pushes back.
2019
    write(&root.join("a"), "a.txt", b"0\n1\n2\n3\n4\n5\n6\n7\n8\n");
2020
    let h_new = a.commit("c8", &[]).unwrap();
2021
    assert!(a.push("origin", false).unwrap()[0].ok);
2022
    assert_eq!(origin.bookmark_heads().unwrap(), vec![h_new]);
2023
    // Fetching new work from origin into the shallow clone works too.
2024
    write(&origin_dir, "b.txt", b"b\n");
2025
    origin.pull("origin").err();
2026
    let (_, wc) = origin.working_copy().unwrap();
2027
    let _ = wc;
2028
    origin
2029
        .checkout(&origin.bookmark_heads().unwrap(), true, "co")
2030
        .unwrap();
2031
    write(&origin_dir, "b.txt", b"b\n");
2032
    let h_b = origin.commit("b", &[]).unwrap();
2033
    let pr = a.pull("origin").unwrap();
2034
    assert!(pr.changed);
2035
    assert!(a.store().has(&h_b));
2036
    assert!(root.join("a/b.txt").exists());
2037
2038
    // Deepening fetches older history until the boundary is gone.
2039
    // Every commit also depends on the change that created the file, so two
2040
    // levels below the boundary hold h4, h3, and the root.
2041
    assert!(a.deepen("origin", 2).unwrap() >= 2);
2042
    assert!(a.store().has(&hashes[3]));
2043
    assert!(a.is_shallow());
2044
    a.deepen("origin", 100).unwrap();
2045
    assert!(!a.is_shallow(), "boundary reached the root");
2046
    assert!(a.store().has(&hashes[0]));
2047
    assert_eq!(
2048
        a.load_state_full(&a.bookmark_heads().unwrap())
2049
            .unwrap()
2050
            .len(),
2051
        10
2052
    );
2053
}
2054
2055
#[test]
2056
fn tags_are_immutable_named_states_and_travel() {
2057
    hermetic();
2058
    let dir = tempfile::tempdir().unwrap();
2059
    let root = dir.path();
2060
    let origin = Repo::init(&root.join("origin")).unwrap();
2061
    let url = root.join("origin").to_string_lossy().to_string();
2062
    let mut a = Repo::clone(&url, &root.join("a"))
2063
        .unwrap()
2064
        .with_home(root.join("home-a"));
2065
    let (key_a, _) = a
2066
        .create_identity("Ada", "[email protected]", IdentityScope::User)
2067
        .unwrap();
2068
    write(&root.join("a"), "f.txt", b"1\n");
2069
    let h1 = a.commit("one", &[]).unwrap();
2070
    write(&root.join("a"), "f.txt", b"1\n2\n");
2071
    let h2 = a.commit("two", &[]).unwrap();
2072
2073
    let t = a.tag_create("v1", &[h1], "first release").unwrap();
2074
    assert_eq!(
2075
        (t.heads.clone(), t.signer.as_deref()),
2076
        (vec![h1], Some("Ada"))
2077
    );
2078
    assert!(a.tag_create("v1", &[h2], "").is_err(), "immutable");
2079
    assert!(a.tag_create("bad/name", &[h2], "").is_err());
2080
    assert_eq!(a.tag_heads("v1").unwrap(), Some(vec![h1]));
2081
    assert_eq!(a.resolve_heads("v1").unwrap(), vec![h1]);
2082
    assert_eq!(a.resolve_heads("main").unwrap(), vec![h2]);
2083
    let (_, sa) = a.tag_attest("v1").unwrap().unwrap();
2084
    assert_eq!(sa.sigs[0].key, key_a);
2085
    // Checkout by tag.
2086
    a.checkout(&a.resolve_heads("v1").unwrap(), false, "co")
2087
        .unwrap();
2088
    assert_eq!(fs::read(root.join("a/f.txt")).unwrap(), b"1\n");
2089
    a.checkout(&a.bookmark_heads().unwrap(), false, "co")
2090
        .unwrap();
2091
2092
    // Push carries the tag; a second attestation for the name is refused.
2093
    let r = a.push("origin", false).unwrap();
2094
    assert!(r.iter().any(|x| x.name == "tags/v1" && x.ok), "{r:?}");
2095
    assert_eq!(origin.tag_heads("v1").unwrap(), Some(vec![h1]));
2096
    let mut forged = a
2097
        .tag_refs()
2098
        .unwrap()
2099
        .into_iter()
2100
        .find(|t| t.name == "v1")
2101
        .unwrap();
2102
    forged.state = origin
2103
        .store()
2104
        .put_state(&StateObject::new(vec![h2]))
2105
        .unwrap();
2106
    forged.heads = vec![h2];
2107
    forged.attestation = None;
2108
    let r = origin
2109
        .receive_push(Bundle::default(), vec![], None, vec![forged])
2110
        .unwrap();
2111
    assert!(!r[0].ok && r[0].reason.contains("immutable"), "{r:?}");
2112
2113
    // A clone gets the tag; a later tag arrives on fetch.
2114
    let b = Repo::clone(&url, &root.join("b"))
2115
        .unwrap()
2116
        .with_home(root.join("home-b"));
2117
    assert_eq!(b.tag_heads("v1").unwrap(), Some(vec![h1]));
2118
    assert!(b.tags().unwrap()[0].signer.as_deref() == Some("Ada"));
2119
    a.tag_create("v2", &[h2], "second").unwrap();
2120
    a.push("origin", false).unwrap();
2121
    let rep = b.fetch("origin").unwrap();
2122
    assert_eq!(rep.new_tags, 1);
2123
    assert_eq!(b.tag_heads("v2").unwrap(), Some(vec![h2]));
2124
2125
    // Under a policy, an unattested tag is refused and an attested one by the root passes.
2126
    a.policy_init().unwrap();
2127
    a.push("origin", false).unwrap();
2128
    let unattested = crate::protocol::TagRef {
2129
        name: "v3".into(),
2130
        state: origin
2131
            .store()
2132
            .put_state(&StateObject::new(vec![h2]))
2133
            .unwrap(),
2134
        heads: vec![h2],
2135
        attestation: None,
2136
    };
2137
    let r = origin
2138
        .receive_push(Bundle::default(), vec![], None, vec![unattested])
2139
        .unwrap();
2140
    assert!(!r[0].ok && r[0].reason.contains("attestation"), "{r:?}");
2141
    a.tag_create("v3", &[h2], "").unwrap();
2142
    let r = a.push("origin", false).unwrap();
2143
    assert!(r.iter().any(|x| x.name == "tags/v3" && x.ok), "{r:?}");
2144
    assert!(a.gc(true).is_ok());
2145
    assert_eq!(a.tags().unwrap().len(), 3, "tags survive gc");
2146
}
2147
2148
#[test]
2149
fn multiple_workspaces_share_a_repository() {
2150
    hermetic();
2151
    let dir = tempfile::tempdir().unwrap();
2152
    let root = dir.path();
2153
    let main_dir = root.join("main");
2154
    let repo = Repo::init(&main_dir).unwrap().with_home(root.join("home"));
2155
    write(&main_dir, "a.txt", b"a\n");
2156
    let h1 = repo.commit("a", &[]).unwrap();
2157
    assert_eq!(repo.workspaces().unwrap().len(), 1);
2158
2159
    // A second workspace elsewhere, checked out on the bookmark.
2160
    let ws_dir = root.join("ws2");
2161
    let ws = repo.workspace_add(&ws_dir, None).unwrap();
2162
    assert!(ws_dir.join(".oxy").is_file());
2163
    assert_eq!(fs::read(ws_dir.join("a.txt")).unwrap(), b"a\n");
2164
    assert_ne!(ws.workspace(), repo.workspace());
2165
    let list = repo.workspaces().unwrap();
2166
    assert_eq!(list.len(), 2);
2167
    assert!(list
2168
        .iter()
2169
        .any(|w| w.id == ws.workspace() && w.path == ws_dir.canonicalize().unwrap() && !w.current));
2170
    assert!(!ws.snapshot("status").unwrap().changed);
2171
2172
    // Work in the second workspace: its own working copy, shared bookmark.
2173
    write(&ws_dir, "b.txt", b"b\n");
2174
    let s = ws.snapshot("status").unwrap();
2175
    assert_eq!(s.statuses.len(), 1);
2176
    assert!(
2177
        !repo.snapshot("status").unwrap().changed,
2178
        "the first workspace is untouched"
2179
    );
2180
    let h2 = ws.commit("b from ws2", &[]).unwrap();
2181
    let mut heads = repo.bookmark_heads().unwrap();
2182
    heads.sort();
2183
    let mut want = vec![h1, h2];
2184
    want.sort();
2185
    assert_eq!(heads, want, "both workspaces see the bookmark move");
2186
    assert!(!main_dir.join("b.txt").exists());
2187
    repo.checkout(&repo.bookmark_heads().unwrap(), false, "co")
2188
        .unwrap();
2189
    assert!(main_dir.join("b.txt").exists());
2190
2191
    // Reopening from inside the second workspace finds the shared repository.
2192
    let reopened = Repo::open(&ws_dir).unwrap();
2193
    assert_eq!(reopened.workspace(), ws.workspace());
2194
    assert_eq!(reopened.id().unwrap(), repo.id().unwrap());
2195
    assert_eq!(reopened.quick_status().unwrap().heads, 2);
2196
2197
    // Workspaces cannot nest; forget drops one from the view but keeps files.
2198
    assert!(repo.workspace_add(&main_dir.join("inner"), None).is_err());
2199
    assert!(repo.workspace_forget(&repo.workspace()).is_err());
2200
    repo.workspace_forget(&ws.workspace()).unwrap();
2201
    assert_eq!(repo.workspaces().unwrap().len(), 1);
2202
    assert!(ws_dir.join("b.txt").exists());
2203
    assert!(
2204
        ws.snapshot("status").is_err(),
2205
        "a forgotten workspace is no longer in the view"
2206
    );
2207
2208
    // The working-copy lock: re-entrant in a thread; a lock whose process
2209
    // is gone is taken over, and a live process's is not, however old.
2210
    let lock = repo.lock_snapshot().unwrap();
2211
    let again = repo.lock_working_copy().unwrap();
2212
    drop(again);
2213
    drop(lock);
2214
    let lock_path = main_dir
2215
        .join(".oxy/workspaces")
2216
        .join(repo.workspace().to_hex())
2217
        .join("lock");
2218
    let old = std::time::SystemTime::now() - std::time::Duration::from_secs(120);
2219
    let age = |p: &Path| fs::File::open(p).unwrap().set_modified(old).unwrap();
2220
    fs::write(&lock_path, std::process::id().to_string()).unwrap();
2221
    age(&lock_path);
2222
    assert!(
2223
        !super::workspace::lock_is_stale(&lock_path),
2224
        "a live process keeps its lock"
2225
    );
2226
    fs::write(&lock_path, "4294967295").unwrap();
2227
    age(&lock_path);
2228
    assert!(repo.lock_snapshot().is_ok(), "stale lock taken over");
2229
}
2230
2231
#[test]
2232
fn attributes_binary_eol_nocompress_lockable() {
2233
    hermetic();
2234
    let dir = tempfile::tempdir().unwrap();
2235
    let root = dir.path();
2236
    let repo = Repo::init(root).unwrap().with_home(root.join("home"));
2237
    write(
2238
        root,
2239
        ".oxyattributes",
2240
        b"*.dat binary nocompress\n*.txt eol=crlf\nassets/** lockable\n",
2241
    );
2242
    write(root, "plain.dat", b"no nul bytes here\n");
2243
    write(root, "notes.txt", b"one\r\ntwo\r\n");
2244
    write(root, "assets/model.bin", b"\0model");
2245
    let h = repo.commit("attrs", &[]).unwrap();
2246
    let snap = repo.load_state(&[h]).unwrap().materialize();
2247
    assert!(
2248
        snap.files["plain.dat"].mode.opaque,
2249
        "binary attribute forces opaque without NUL bytes"
2250
    );
2251
    assert!(
2252
        matches!(&snap.files["notes.txt"].content, FileContent::Text { bytes, .. } if bytes == b"one\ntwo\n"),
2253
        "stored with LF"
2254
    );
2255
    assert!(
2256
        !repo.snapshot("status").unwrap().changed,
2257
        "CRLF on disk equals LF in the state"
2258
    );
2259
    // nocompress chunks pack raw.
2260
    let r = repo.gc(true).unwrap();
2261
    assert!(r.packed.objects > 0);
2262
    // Checkout writes CRLF for eol=crlf and makes lockable files read-only.
2263
    fs::remove_file(root.join("notes.txt")).unwrap();
2264
    repo.checkout(&[h], true, "co").unwrap();
2265
    assert_eq!(fs::read(root.join("notes.txt")).unwrap(), b"one\r\ntwo\r\n");
2266
    assert!(fs::metadata(root.join("assets/model.bin"))
2267
        .unwrap()
2268
        .permissions()
2269
        .readonly());
2270
    assert!(repo.lock_path("plain.dat").is_err(), "not lockable");
2271
    repo.lock_path("assets/model.bin").unwrap();
2272
    assert!(!fs::metadata(root.join("assets/model.bin"))
2273
        .unwrap()
2274
        .permissions()
2275
        .readonly());
2276
    assert!(repo.is_locked("assets/model.bin"));
2277
    write(root, "assets/model.bin", b"\0model2");
2278
    repo.commit("edit model", &[]).unwrap();
2279
    repo.unlock_path("assets/model.bin").unwrap();
2280
    assert!(fs::metadata(root.join("assets/model.bin"))
2281
        .unwrap()
2282
        .permissions()
2283
        .readonly());
2284
    // A later checkout can still overwrite a read-only lockable file.
2285
    repo.checkout(&[h], true, "co").unwrap();
2286
    assert_eq!(fs::read(root.join("assets/model.bin")).unwrap(), b"\0model");
2287
}
2288
2289
#[cfg(unix)]
2290
#[test]
2291
fn hooks_can_veto_observe_and_add_dependencies() {
2292
    use std::os::unix::fs::PermissionsExt;
2293
    hermetic();
2294
    let dir = tempfile::tempdir().unwrap();
2295
    let root = dir.path();
2296
    let mut repo = Repo::init(root).unwrap().with_home(root.join("home"));
2297
    let hooks = root.join(".oxy/hooks");
2298
    fs::create_dir_all(&hooks).unwrap();
2299
    let hook = |name: &str, body: &str| {
2300
        let p = hooks.join(name);
2301
        fs::write(&p, format!("#!/bin/sh\n{body}\n")).unwrap();
2302
        fs::set_permissions(&p, fs::Permissions::from_mode(0o755)).unwrap();
2303
    };
2304
    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");
2305
    hook("post-commit", "cat > \"$OXY_ROOT/.last-post-commit\"");
2306
    hook("post-checkout", "cat > \"$OXY_ROOT/.last-post-checkout\"");
2307
    hook("pre-push", "echo pushing blocked >&2; exit 3");
2308
    write(root, ".oxyignore", b".last-*\n");
2309
    write(root, "a.txt", b"a\n");
2310
    let err = repo.commit("WIP: nope", &[]).unwrap_err().to_string();
2311
    assert!(err.contains("pre-commit refused: no WIP commits"), "{err}");
2312
    let h1 = repo.commit("first", &[]).unwrap();
2313
    let pre = fs::read_to_string(root.join(".last-pre-commit")).unwrap();
2314
    assert!(
2315
        pre.contains("\"event\":\"pre-commit\"")
2316
            && pre.contains("\"path\":\"a.txt\"")
2317
            && pre.contains("\"message\":\"first\""),
2318
        "{pre}"
2319
    );
2320
    let post = fs::read_to_string(root.join(".last-post-commit")).unwrap();
2321
    assert!(post.contains(&h1.to_hex()), "{post}");
2322
    repo.checkout(&[h1], false, "co").unwrap();
2323
    assert!(fs::read_to_string(root.join(".last-post-checkout"))
2324
        .unwrap()
2325
        .contains("post-checkout"));
2326
    repo.config.set("remote.origin.url", "/nowhere").unwrap();
2327
    repo.save_config().unwrap();
2328
    let err = repo.push("origin", false).unwrap_err().to_string();
2329
    assert!(err.contains("pre-push refused: pushing blocked"), "{err}");
2330
2331
    // semantic-deps: only when enabled; adds an explicit dependency.
2332
    write(root, "b.txt", b"b\n");
2333
    hook(
2334
        "semantic-deps",
2335
        &format!(
2336
            "cat > \"$OXY_ROOT/.last-semantic\"; echo '{{\"deps\": [\"{}\"]}}'",
2337
            h1.to_hex()
2338
        ),
2339
    );
2340
    let h2 = repo.commit("b without hook", &[]).unwrap();
2341
    assert!(
2342
        repo.store().get_change(&h2).unwrap().deps.is_empty(),
2343
        "hook disabled by default"
2344
    );
2345
    repo.config.set("hooks.semantic-deps", "true").unwrap();
2346
    repo.save_config().unwrap();
2347
    write(root, "c.txt", b"c\n");
2348
    let h3 = repo.commit("c with hook", &[]).unwrap();
2349
    assert_eq!(repo.store().get_change(&h3).unwrap().deps, vec![h1]);
2350
    let sem = fs::read_to_string(root.join(".last-semantic")).unwrap();
2351
    assert!(
2352
        sem.contains("\"touched_paths\":[\"c.txt\"]") && sem.contains("candidate_deps"),
2353
        "{sem}"
2354
    );
2355
    assert_eq!(json_str("a\"b\\c\n"), "\"a\\\"b\\\\c\\n\"");
2356
}
2357
2358
#[test]
2359
fn amend_into_older_change_and_split() {
2360
    hermetic();
2361
    let dir = tempfile::tempdir().unwrap();
2362
    let root = dir.path();
2363
    let mut repo = Repo::init(root).unwrap().with_home(root.join("home"));
2364
    repo.create_identity("Ada", "a@b", IdentityScope::User)
2365
        .unwrap();
2366
    repo.set_user_config("core.sign", "change").unwrap();
2367
    write(root, "a.txt", b"one\ntwo\n");
2368
    let h0 = repo.commit("base", &[]).unwrap();
2369
    write(root, "a.txt", b"one\nTWO\n");
2370
    let h1 = repo.commit("edit two", &[]).unwrap();
2371
    write(root, "a.txt", b"one\nTWO\nthree\n");
2372
    let h2 = repo.commit("add three", &[]).unwrap();
2373
    let id1 = repo.store().get_change(&h1).unwrap().change_id;
2374
2375
    // Fixing the line h1 introduced folds into h1; h2 is rewritten on top.
2376
    write(root, "a.txt", b"one\nTWO!\nthree\n");
2377
    let h1b = repo.amend_into(&h1, None).unwrap();
2378
    assert_ne!(h1b, h1);
2379
    let c1b = repo.store().get_change(&h1b).unwrap();
2380
    assert_eq!(c1b.change_id, id1);
2381
    assert_eq!(c1b.deps, vec![h0]);
2382
    assert!(matches!(
2383
        repo.verify_change(&h1b).unwrap(),
2384
        SignatureStatus::Valid { .. }
2385
    ));
2386
    let heads = repo.bookmark_heads().unwrap();
2387
    assert_eq!(heads.len(), 1);
2388
    let top = repo.store().get_change(&heads[0]).unwrap();
2389
    assert_eq!(top.message, "add three");
2390
    assert_eq!(
2391
        top.deps.iter().copied().collect::<BTreeSet<_>>(),
2392
        [h0, h1b].into_iter().collect(),
2393
        "depends on the file's creator and the rewritten line"
2394
    );
2395
    let snap = repo.load_state(&heads).unwrap().materialize();
2396
    assert!(
2397
        matches!(&snap.files["a.txt"].content, FileContent::Text { bytes, .. } if bytes == b"one\nTWO!\nthree\n")
2398
    );
2399
    assert!(
2400
        !repo.snapshot("status").unwrap().changed,
2401
        "the working copy is clean after folding"
2402
    );
2403
    // Only h1b's own state shows the fix without "three".
2404
    let only = repo.load_state(&[h1b]).unwrap().materialize();
2405
    assert!(
2406
        matches!(&only.files["a.txt"].content, FileContent::Text { bytes, .. } if bytes == b"one\nTWO!\n")
2407
    );
2408
    assert_eq!(repo.log().unwrap().len(), 4);
2409
2410
    // An edit to a line introduced by h2 cannot fold into h1.
2411
    write(root, "a.txt", b"one\nTWO!\nthree!\n");
2412
    let err = repo.amend_into(&h1b, None).unwrap_err().to_string();
2413
    assert!(err.contains("introduced after"), "{err}");
2414
    assert!(
2415
        repo.snapshot("status").unwrap().statuses.len() == 1,
2416
        "nothing was changed by the refusal"
2417
    );
2418
    write(root, "a.txt", b"one\nTWO!\nthree\n");
2419
2420
    // Split the head that touches two files.
2421
    write(root, "b.txt", b"b\n");
2422
    write(root, "c.txt", b"c\n");
2423
    let h3 = repo.commit("b and c", &[]).unwrap();
2424
    let id3 = repo.store().get_change(&h3).unwrap().change_id;
2425
    let (p1, p2) = repo.split(&h3, &["b.txt".into()]).unwrap();
2426
    let c_1 = repo.store().get_change(&p1).unwrap();
2427
    let c_2 = repo.store().get_change(&p2).unwrap();
2428
    assert!(c_1.message.contains("part 1: b.txt"));
2429
    assert_eq!(c_2.change_id, id3);
2430
    let heads: BTreeSet<_> = repo.bookmark_heads().unwrap().into_iter().collect();
2431
    assert!(
2432
        heads.contains(&p1) && heads.contains(&p2),
2433
        "independent parts are both heads"
2434
    );
2435
    let snap = repo
2436
        .load_state(&repo.bookmark_heads().unwrap())
2437
        .unwrap()
2438
        .materialize();
2439
    assert!(snap.files.contains_key("b.txt") && snap.files.contains_key("c.txt"));
2440
    let only1 = repo.load_state(&[p1]).unwrap().materialize();
2441
    assert!(only1.files.contains_key("b.txt") && !only1.files.contains_key("c.txt"));
2442
    assert!(!repo.snapshot("status").unwrap().changed);
2443
    assert!(repo.split(&p2, &["nope.txt".into()]).is_err());
2444
    let _ = h2;
2445
}
2446
2447
#[test]
2448
fn identity_lifecycle() {
2449
    hermetic();
2450
    let dir = tempfile::tempdir().unwrap();
2451
    let root = dir.path();
2452
    let origin = Repo::init(&root.join("origin")).unwrap();
2453
    let url = root.join("origin").to_string_lossy().to_string();
2454
    let mut a = Repo::clone(&url, &root.join("a"))
2455
        .unwrap()
2456
        .with_home(root.join("home-a"));
2457
    a.set_user_config("core.sign", "change").unwrap();
2458
    let (key_a, _) = a
2459
        .create_identity("Ada", "[email protected]", IdentityScope::User)
2460
        .unwrap();
2461
    write(&root.join("a"), "a.txt", b"a\n");
2462
    let h1 = a.commit("one", &[]).unwrap();
2463
    assert!(a.policy_init().unwrap().applied);
2464
    assert!(a.push("origin", false).unwrap().iter().all(|r| r.ok));
2465
2466
    // Expiry: an identity that had expired when the change was made does not authenticate it.
2467
    let mut e = Repo::init(&root.join("e"))
2468
        .unwrap()
2469
        .with_home(root.join("home-e"));
2470
    e.set_user_config("core.sign", "change").unwrap();
2471
    e.create_identity_with(
2472
        "Eve",
2473
        "[email protected]",
2474
        IdentityScope::User,
2475
        Some(Hlc::now().wall_ms - 1),
2476
    )
2477
    .unwrap();
2478
    write(&root.join("e"), "e.txt", b"e\n");
2479
    let he = e.commit("late", &[]).unwrap();
2480
    assert!(
2481
        matches!(e.verify_change(&he).unwrap(), SignatureStatus::Invalid(m) if m.contains("expired"))
2482
    );
2483
    // Renewal re-issues the identity (same keys, new KeyId) with a later expiry.
2484
    let r = e
2485
        .renew_identity(Some(Hlc::now().wall_ms + 86_400_000))
2486
        .unwrap();
2487
    assert_eq!(e.identity(&r.new).unwrap().previous, Some(r.old));
2488
    write(&root.join("e"), "e.txt", b"e2\n");
2489
    let he2 = e.commit("in time", &[]).unwrap();
2490
    assert!(
2491
        matches!(e.verify_change(&he2).unwrap(), SignatureStatus::Valid { key, .. } if key == r.new)
2492
    );
2493
2494
    // Rotation: a fresh key; the old change still verifies; the policy follows.
2495
    let r = a.rotate_identity().unwrap();
2496
    assert_eq!(r.old, key_a);
2497
    assert_eq!(a.config.author_key, Some(r.new));
2498
    assert_eq!(a.identity(&r.new).unwrap().previous, Some(key_a));
2499
    assert!(r.policy.as_ref().unwrap().applied);
2500
    let (_, sp) = a.current_policy().unwrap().unwrap();
2501
    assert_eq!(
2502
        (sp.policy.serial, sp.policy.roots.clone()),
2503
        (2, vec![r.new])
2504
    );
2505
    assert!(
2506
        !sp.policy.revoked.contains(&key_a) && sp.policy.authorizes(&r.new, "main"),
2507
        "superseded, not revoked"
2508
    );
2509
    assert!(sp.policy.succeeds(&r.new, &key_a) && !sp.policy.succeeds(&key_a, &r.new));
2510
    assert!(
2511
        matches!(a.verify_change(&h1).unwrap(), SignatureStatus::Valid { key, revoked: false, .. } if key == key_a)
2512
    );
2513
    write(&root.join("a"), "a.txt", b"a2\n");
2514
    let h2 = a.commit("two", &[]).unwrap();
2515
    assert!(
2516
        matches!(a.verify_change(&h2).unwrap(), SignatureStatus::Valid { key, revoked: false, .. } if key == r.new)
2517
    );
2518
    // Origin accepts the rotated policy (signed by the old root) and the new key's change.
2519
    let res = a.push("origin", false).unwrap();
2520
    assert!(res.iter().all(|x| x.ok), "{res:?}");
2521
    assert_eq!(origin.current_policy().unwrap().unwrap().1.policy.serial, 2);
2522
    let key_a = r.new;
2523
2524
    // Delegation: Bob may sign on Ada's behalf. Delegates live in the
2525
    // identity object, so Ada's KeyId changes while her keys stay the same.
2526
    let mut b = Repo::clone(&url, &root.join("b"))
2527
        .unwrap()
2528
        .with_home(root.join("home-b"));
2529
    let (key_b, id_b) = b
2530
        .create_identity("Bob", "[email protected]", IdentityScope::User)
2531
        .unwrap();
2532
    let r = a.delegate_add(id_b.clone()).unwrap();
2533
    assert_eq!(r.old, key_a);
2534
    let key_a2 = r.new;
2535
    assert_eq!(a.identity(&key_a2).unwrap().delegates, vec![key_b]);
2536
    assert_eq!(
2537
        a.identity(&key_a2).unwrap().ed25519_pk,
2538
        a.identity(&key_a).unwrap().ed25519_pk
2539
    );
2540
    assert!(a.delegate_add(id_b.clone()).is_err(), "already a delegate");
2541
    assert!(a.push("origin", false).unwrap().iter().all(|x| x.ok));
2542
    write(&root.join("a"), "a.txt", b"a3\n");
2543
    let h3 = a.commit("three", &[]).unwrap();
2544
    assert!(
2545
        matches!(a.verify_change(&h3).unwrap(), SignatureStatus::Valid { key, .. } if key == key_a2),
2546
        "the same secret signs under the new KeyId"
2547
    );
2548
    // A change authored by Ada but signed only by Bob verifies through the delegation.
2549
    a.set_user_config("core.sign", "seal").unwrap();
2550
    write(&root.join("a"), "a.txt", b"a4\n");
2551
    let h4 = a.commit("four", &[]).unwrap();
2552
    assert_eq!(a.verify_change(&h4).unwrap(), SignatureStatus::Unsigned);
2553
    let (_, sk_b) = b.secret_key().unwrap().unwrap();
2554
    a.store()
2555
        .put_signature(&h4, &sk_b.sign(Domain::Change, &key_b, &h4))
2556
        .unwrap();
2557
    assert!(
2558
        matches!(a.verify_change(&h4).unwrap(), SignatureStatus::Valid { key, .. } if key == key_b)
2559
    );
2560
    a.set_user_config("core.sign", "change").unwrap();
2561
    // Withdrawing the delegation re-issues the identity again.
2562
    let r = a.delegate_remove(&key_b).unwrap();
2563
    assert!(a.identity(&r.new).unwrap().delegates.is_empty());
2564
    assert!(a.delegate_remove(&key_b).is_err());
2565
    let key_a3 = r.new;
2566
    let res = a.push("origin", false).unwrap();
2567
    assert!(res.iter().all(|x| x.ok), "{res:?}");
2568
2569
    // Multi-signer policy: Bob becomes a root and the threshold rises to 2,
2570
    // both applied under the old threshold of 1. A grant then needs Bob too.
2571
    assert!(a.policy_root_add(id_b.clone()).unwrap().applied);
2572
    assert!(a.policy_root_add(id_b.clone()).is_err());
2573
    assert!(a.policy_set_threshold(3).is_err());
2574
    assert!(a.policy_set_threshold(2).unwrap().applied);
2575
    assert!(a.push("origin", false).unwrap().iter().all(|x| x.ok));
2576
    b.pull("origin").unwrap();
2577
    assert_eq!(
2578
        b.current_policy().unwrap().unwrap().1.policy.root_threshold,
2579
        2
2580
    );
2581
    let mut c = Repo::init(&root.join("c"))
2582
        .unwrap()
2583
        .with_home(root.join("home-c"));
2584
    let (key_c, id_c) = c
2585
        .create_identity("Cy", "[email protected]", IdentityScope::User)
2586
        .unwrap();
2587
    let serial_before = a.current_policy().unwrap().unwrap().1.policy.serial;
2588
    let proposal = a.policy_grant(id_c, None).unwrap();
2589
    assert!(!proposal.applied && proposal.sigs.len() == 1);
2590
    assert_eq!(proposal.policy.serial, serial_before + 1);
2591
    assert_eq!(
2592
        a.current_policy().unwrap().unwrap().1.policy.serial,
2593
        serial_before,
2594
        "a proposal changes nothing yet"
2595
    );
2596
    // Bob signs the proposal, handed over as a file, and it applies for him.
2597
    let bytes = proposal.signed().encode();
2598
    let signed = b
2599
        .policy_sign(SignedPolicy::decode(&bytes).unwrap())
2600
        .unwrap();
2601
    assert!(signed.applied && signed.sigs.len() == 2);
2602
    assert!(b
2603
        .current_policy()
2604
        .unwrap()
2605
        .unwrap()
2606
        .1
2607
        .policy
2608
        .authorizes(&key_c, "main"));
2609
    assert!(
2610
        b.policy_sign(signed.signed()).is_err(),
2611
        "a stale proposal is refused"
2612
    );
2613
    // Bob publishes it and Ada picks it up.
2614
    assert!(b
2615
        .push("origin", false)
2616
        .unwrap()
2617
        .iter()
2618
        .any(|x| x.name == "policy" && x.ok));
2619
    a.pull("origin").unwrap();
2620
    assert_eq!(
2621
        a.current_policy().unwrap().unwrap().1.policy.serial,
2622
        serial_before + 1
2623
    );
2624
    // A root cannot revoke itself; revoking Cy needs both roots but is recorded locally at once.
2625
    assert!(a.policy_revoke(&key_a3).is_err());
2626
    let u = a
2627
        .revoke_identity(&key_c, "left the project")
2628
        .unwrap()
2629
        .unwrap();
2630
    assert!(!u.applied);
2631
    assert!(a.is_revoked(&key_c).unwrap());
2632
    assert!(!b.is_revoked(&key_c).unwrap());
2633
    let u = b.policy_sign(u.signed()).unwrap();
2634
    assert!(u.applied && u.policy.is_revoked(&key_c));
2635
    assert!(b.is_revoked(&key_c).unwrap());
2636
    // Bob can revoke Ada's root key, leaving himself as the only root (threshold 2 would be unmeetable).
2637
    assert!(
2638
        b.policy_revoke(&key_a3).is_err(),
2639
        "would leave one root for a threshold of 2"
2640
    );
2641
    // Revoking one's own key without a policy root works locally: a plain marker plus attestation.
2642
    let key_c_own = c.config.author_key.unwrap();
2643
    assert!(c
2644
        .revoke_identity(&key_c_own, "lost laptop")
2645
        .unwrap()
2646
        .is_none());
2647
    assert!(c.is_revoked(&key_c_own).unwrap());
2648
    assert_eq!(key_c_own, key_c);
2649
}
2650
2651
#[test]
2652
fn renames_are_detected_and_tracked_as_moves() {
2653
    hermetic();
2654
    let dir = tempfile::tempdir().unwrap();
2655
    let root = dir.path();
2656
    let repo = Repo::init(root).unwrap().with_home(root.join("home"));
2657
    write(
2658
        root,
2659
        "src/old.rs",
2660
        b"fn a() {}\nfn b() {}\nfn c() {}\nfn d() {}\n",
2661
    );
2662
    write(root, "img.bin", b"\x89PNG\0\0\x01\x02");
2663
    write(root, "tiny.txt", b"x\n");
2664
    let h1 = repo.commit("base", &[]).unwrap();
2665
    let node_old = repo.load_state(&[h1]).unwrap().materialize().files["src/old.rs"].node;
2666
    let node_img = repo.load_state(&[h1]).unwrap().materialize().files["img.bin"].node;
2667
2668
    // Rename with a small edit, a binary moved unchanged, and a rewrite
2669
    // that shares nothing with the removed file.
2670
    fs::remove_file(root.join("src/old.rs")).unwrap();
2671
    write(
2672
        root,
2673
        "lib/new.rs",
2674
        b"fn a() {}\nfn b() {}\nfn c() {}\nfn e() {}\n",
2675
    );
2676
    fs::remove_file(root.join("img.bin")).unwrap();
2677
    write(root, "assets/img.bin", b"\x89PNG\0\0\x01\x02");
2678
    fs::remove_file(root.join("tiny.txt")).unwrap();
2679
    write(root, "other.txt", b"completely different\n");
2680
    let snap = repo.snapshot("status").unwrap();
2681
    let statuses: Vec<(&str, ChangeStatus)> = snap
2682
        .statuses
2683
        .iter()
2684
        .map(|s| (s.path.as_str(), s.status))
2685
        .collect();
2686
    assert_eq!(
2687
        statuses,
2688
        vec![
2689
            ("assets/img.bin", ChangeStatus::Renamed),
2690
            ("lib/new.rs", ChangeStatus::Renamed),
2691
            ("other.txt", ChangeStatus::Added),
2692
            ("src", ChangeStatus::Removed),
2693
            ("tiny.txt", ChangeStatus::Removed)
2694
        ]
2695
    );
2696
    let h2 = repo.commit("move things", &[]).unwrap();
2697
    let c = repo.store().get_change(&h2).unwrap();
2698
    let moves: Vec<_> = c
2699
        .tree_ops
2700
        .iter()
2701
        .filter(|op| matches!(op, TreeOp::Move { .. }))
2702
        .collect();
2703
    assert_eq!(moves.len(), 2, "{:?}", c.tree_ops);
2704
    assert!(c.tree_ops.iter().any(
2705
        |op| matches!(op, TreeOp::Move { node, name, .. } if *node == node_old && name == "new.rs")
2706
    ));
2707
    assert!(c.tree_ops.iter().any(
2708
        |op| matches!(op, TreeOp::Move { node, name, .. } if *node == node_img && name == "img.bin")
2709
    ));
2710
    let snap = repo.load_state(&[h2]).unwrap().materialize();
2711
    assert_eq!(
2712
        snap.files["lib/new.rs"].node, node_old,
2713
        "the node survives the rename"
2714
    );
2715
    assert!(
2716
        matches!(&snap.files["lib/new.rs"].content, FileContent::Text { bytes, .. } if bytes == b"fn a() {}\nfn b() {}\nfn c() {}\nfn e() {}\n")
2717
    );
2718
    assert!(!snap.files.contains_key("src/old.rs") && !snap.files.contains_key("src"));
2719
    assert!(render_change(
2720
        &c,
2721
        &repo.load_state(&[h1]).unwrap(),
2722
        &repo.load_state(&[h1]).unwrap().materialize()
2723
    )
2724
    .contains("R "));
2725
    // A fresh checkout reproduces the tree.
2726
    let other = tempfile::tempdir().unwrap();
2727
    let clone = Repo::clone(&root.to_string_lossy(), other.path()).unwrap();
2728
    assert_eq!(
2729
        fs::read(other.path().join("lib/new.rs")).unwrap(),
2730
        b"fn a() {}\nfn b() {}\nfn c() {}\nfn e() {}\n"
2731
    );
2732
    assert!(!other.path().join("src").exists());
2733
    assert!(!clone.snapshot("status").unwrap().changed);
2734
    // Similarity is line based, byte weighted.
2735
    assert_eq!(similarity(b"a\nb\n", b"a\nb\n"), 100);
2736
    assert_eq!(similarity(b"a\nb\nc\nd\n", b"a\nb\nx\ny\n"), 50);
2737
    assert_eq!(similarity(b"hello\n", b"world\n"), 0);
2738
    assert_eq!(similarity(b"", b"x\n"), 0);
2739
}
2740
2741
#[test]
2742
fn git_fetch_and_push_round_trip() {
2743
    hermetic();
2744
    if std::process::Command::new("git")
2745
        .arg("--version")
2746
        .output()
2747
        .is_err()
2748
    {
2749
        eprintln!("git not installed; skipping");
2750
        return;
2751
    }
2752
    let dir = tempfile::tempdir().unwrap();
2753
    let root = dir.path();
2754
    let git_in = |d: &Path, args: &[&str]| -> String {
2755
        let out = std::process::Command::new("git")
2756
            .arg("-C")
2757
            .arg(d)
2758
            .args([
2759
                "-c",
2760
                "user.name=Grace",
2761
                "-c",
2762
                "[email protected]",
2763
                "-c",
2764
                "commit.gpgsign=false",
2765
            ])
2766
            .args(args)
2767
            .output()
2768
            .unwrap();
2769
        assert!(
2770
            out.status.success(),
2771
            "git {args:?}: {}",
2772
            String::from_utf8_lossy(&out.stderr)
2773
        );
2774
        String::from_utf8_lossy(&out.stdout).trim().to_string()
2775
    };
2776
    // A bare "remote" and a work tree that pushes to it.
2777
    let remote = root.join("remote.git");
2778
    fs::create_dir_all(&remote).unwrap();
2779
    git_in(&remote, &["init", "-q", "--bare", "-b", "main"]);
2780
    let work = root.join("work");
2781
    git_in(
2782
        root,
2783
        &[
2784
            "clone",
2785
            "-q",
2786
            remote.to_str().unwrap(),
2787
            work.to_str().unwrap(),
2788
        ],
2789
    );
2790
    git_in(&work, &["checkout", "-q", "-b", "main"]);
2791
    write(&work, "README.md", b"# Project\n");
2792
    write(&work, "src/lib.rs", b"pub fn a() {}\n");
2793
    git_in(&work, &["add", "."]);
2794
    git_in(&work, &["commit", "-q", "-m", "initial"]);
2795
    write(&work, "src/lib.rs", b"pub fn a() {}\npub fn b() {}\n");
2796
    git_in(&work, &["commit", "-q", "-am", "second"]);
2797
    git_in(&work, &["push", "-q", "origin", "main"]);
2798
    let tip1 = git_in(&work, &["rev-parse", "HEAD"]);
2799
2800
    // Fetch into a fresh oxy repository.
2801
    let o = root.join("oxy");
2802
    let mut repo = Repo::init(&o).unwrap().with_home(root.join("home"));
2803
    repo.create_identity("Ada", "[email protected]", IdentityScope::User)
2804
        .unwrap();
2805
    let url = remote.to_string_lossy().to_string();
2806
    let r = repo.git_fetch(&url, "main").unwrap();
2807
    assert_eq!((r.commits, r.heads), (2, 1));
2808
    assert_eq!(
2809
        fs::read(o.join("src/lib.rs")).unwrap(),
2810
        b"pub fn a() {}\npub fn b() {}\n"
2811
    );
2812
    assert!(!repo.snapshot("status").unwrap().changed);
2813
    assert_eq!(
2814
        repo.git_fetch(&url, "main").unwrap().commits,
2815
        0,
2816
        "nothing new"
2817
    );
2818
2819
    // An oxy change, pushed back: one commit on top of the Git tip.
2820
    write(
2821
        &o,
2822
        "src/lib.rs",
2823
        b"pub fn a() {}\npub fn b() {}\npub fn c() {}\n",
2824
    );
2825
    write(&o, "NOTES.md", b"from oxy\n");
2826
    let h_oxy = repo.commit("add c and notes", &[]).unwrap();
2827
    let r = repo.git_push(&url, "main").unwrap();
2828
    assert_eq!(r.exported, 1, "{r:?}");
2829
    git_in(&work, &["pull", "-q", "--ff-only", "origin", "main"]);
2830
    assert_eq!(
2831
        git_in(&work, &["log", "--format=%s", "main"]),
2832
        "add c and notes\nsecond\ninitial"
2833
    );
2834
    assert_eq!(git_in(&work, &["rev-parse", "HEAD~1"]), tip1);
2835
    assert_eq!(fs::read(work.join("NOTES.md")).unwrap(), b"from oxy\n");
2836
    assert_eq!(git_in(&work, &["log", "-1", "--format=%an", "main"]), "Ada");
2837
    assert!(git_in(&work, &["log", "-1", "--format=%B", "main"])
2838
        .contains(&format!("Oxy-Hash: {}", h_oxy.to_hex())));
2839
    assert_eq!(
2840
        repo.git_push(&url, "main").unwrap().exported,
2841
        0,
2842
        "already pushed"
2843
    );
2844
2845
    // Git moves on; pushing without fetching is refused, fetching brings
2846
    // the commit in and the working copy follows.
2847
    write(&work, "README.md", b"# Project\n\nMore.\n");
2848
    git_in(&work, &["commit", "-q", "-am", "readme from git"]);
2849
    git_in(&work, &["push", "-q", "origin", "main"]);
2850
    let tip2 = git_in(&work, &["rev-parse", "HEAD"]);
2851
    assert!(repo
2852
        .git_push(&url, "main")
2853
        .unwrap_err()
2854
        .to_string()
2855
        .contains("fetch"));
2856
    let r = repo.git_fetch(&url, "main").unwrap();
2857
    assert_eq!(
2858
        (r.commits, r.heads),
2859
        (1, 2),
2860
        "the Git change and the oxy change commute"
2861
    );
2862
    assert_eq!(
2863
        fs::read(o.join("README.md")).unwrap(),
2864
        b"# Project\n\nMore.\n"
2865
    );
2866
    assert_eq!(fs::read(o.join("NOTES.md")).unwrap(), b"from oxy\n");
2867
    assert!(!repo.snapshot("status").unwrap().changed);
2868
    // Another oxy change pushes on top of Git's newest commit.
2869
    write(&o, "NOTES.md", b"from oxy\nagain\n");
2870
    repo.commit("notes again", &[]).unwrap();
2871
    assert_eq!(repo.git_push(&url, "main").unwrap().exported, 1);
2872
    git_in(&work, &["pull", "-q", "--ff-only", "origin", "main"]);
2873
    assert_eq!(git_in(&work, &["rev-parse", "HEAD~1"]), tip2);
2874
    assert_eq!(
2875
        fs::read(work.join("NOTES.md")).unwrap(),
2876
        b"from oxy\nagain\n"
2877
    );
2878
    assert_eq!(
2879
        git_in(&work, &["log", "--format=%s", "main"])
2880
            .lines()
2881
            .count(),
2882
        5
2883
    );
2884
}
2885
2886
/// Benchmark, not a gate: `cargo test --release -p oxy-core --lib bench_one_gibibyte -- --ignored --nocapture`.
2887
/// Commits, stores, clones, and reads back a 1 GiB incompressible file.
2888
#[test]
2889
#[ignore]
2890
fn bench_one_gibibyte_file() {
2891
    hermetic();
2892
    // /tmp is often a small tmpfs; `OXY_BENCH_DIR` picks a roomier disk.
2893
    let dir = match std::env::var_os("OXY_BENCH_DIR") {
2894
        Some(d) => tempfile::tempdir_in(d).unwrap(),
2895
        None => tempfile::tempdir().unwrap(),
2896
    };
2897
    let root = dir.path();
2898
    let repo = Repo::init(&root.join("r"))
2899
        .unwrap()
2900
        .with_home(root.join("home"));
2901
    let size = 1usize << 30;
2902
    let mut data = vec![0u8; size];
2903
    let mut x = 0x9e3779b97f4a7c15u64;
2904
    for chunk in data.chunks_mut(8) {
2905
        x ^= x << 13;
2906
        x ^= x >> 7;
2907
        x ^= x << 17;
2908
        let b = x.to_le_bytes();
2909
        chunk.copy_from_slice(&b[..chunk.len()]);
2910
    }
2911
    let t = std::time::Instant::now();
2912
    write(&root.join("r"), "big.bin", &data);
2913
    eprintln!("write 1 GiB to disk: {:.2?}", t.elapsed());
2914
    let t = std::time::Instant::now();
2915
    let h = repo.commit("big", &[]).unwrap();
2916
    eprintln!("commit (chunk + hash + store): {:.2?}", t.elapsed());
2917
    let t = std::time::Instant::now();
2918
    assert!(!repo.snapshot("status").unwrap().changed);
2919
    eprintln!("status on a clean 1 GiB working copy: {:.2?}", t.elapsed());
2920
    let t = std::time::Instant::now();
2921
    let objects = repo.store().list().unwrap().len();
2922
    eprintln!("objects stored: {objects} ({:.2?} to list)", t.elapsed());
2923
    let t = std::time::Instant::now();
2924
    let g = repo.gc(true).unwrap();
2925
    eprintln!("gc (pack): {:.2?} {g:?}", t.elapsed());
2926
    let t = std::time::Instant::now();
2927
    let clone = Repo::clone(&root.join("r").to_string_lossy(), &root.join("c")).unwrap();
2928
    eprintln!("clone (fetch + checkout): {:.2?}", t.elapsed());
2929
    let t = std::time::Instant::now();
2930
    let back = fs::read(root.join("c/big.bin")).unwrap();
2931
    assert_eq!(blake3::hash(&back), blake3::hash(&data));
2932
    eprintln!("read back and verify: {:.2?}", t.elapsed());
2933
    assert_eq!(clone.bookmark_heads().unwrap(), vec![h]);
2934
    let store_bytes: u64 = walkdir_size(&root.join("r/.oxy/objects"));
2935
    eprintln!(
2936
        "store size: {:.1} MiB for 1 GiB of data",
2937
        store_bytes as f64 / (1024.0 * 1024.0)
2938
    );
2939
}
2940
2941
fn walkdir_size(p: &Path) -> u64 {
2942
    let mut total = 0;
2943
    if let Ok(rd) = fs::read_dir(p) {
2944
        for e in rd.flatten() {
2945
            let path = e.path();
2946
            if path.is_dir() {
2947
                total += walkdir_size(&path);
2948
            } else if let Ok(m) = fs::metadata(&path) {
2949
                total += m.len();
2950
            }
2951
        }
2952
    }
2953
    total
2954
}
2955
2956
/// An opaque file whose size and mtime match the manifest is not read on
2957
/// the next snapshot: its blob comes from the manifest's stat cache.
2958
#[cfg(unix)]
2959
#[test]
2960
fn stat_cache_skips_reading_unchanged_opaque_files() {
2961
    use std::os::unix::fs::PermissionsExt;
2962
    hermetic();
2963
    let dir = tempfile::tempdir().unwrap();
2964
    let root = dir.path();
2965
    let repo = Repo::init(root).unwrap().with_home(root.join("home"));
2966
    let mut big = vec![0u8; 300 * 1024];
2967
    for (i, b) in big.iter_mut().enumerate() {
2968
        *b = (i as u32).wrapping_mul(2654435761).to_le_bytes()[1];
2969
    }
2970
    big[0] = 0;
2971
    write(root, "big.bin", &big);
2972
    write(root, "a.txt", b"text\n");
2973
    let h1 = repo.commit("base", &[]).unwrap();
2974
    let (_, _, m) = repo.read_manifest().unwrap().unwrap();
2975
    assert!(
2976
        m.entries["big.bin"].blob.is_some(),
2977
        "opaque files record their blob"
2978
    );
2979
    assert!(m.entries["a.txt"].blob.is_none());
2980
    let blob = m.entries["big.bin"].blob.unwrap();
2981
    assert!(repo.store().has(&blob));
2982
2983
    // Files modified within two seconds of the manifest are racy and still
2984
    // read; age the file so the cache applies, then snapshot to record it.
2985
    let old = std::time::SystemTime::now() - std::time::Duration::from_secs(30);
2986
    fs::File::options()
2987
        .write(true)
2988
        .open(root.join("big.bin"))
2989
        .unwrap()
2990
        .set_modified(old)
2991
        .unwrap();
2992
    assert!(!repo.snapshot("status").unwrap().changed);
2993
    // Now the file cannot be read at all; the snapshot succeeds without it.
2994
    fs::set_permissions(root.join("big.bin"), fs::Permissions::from_mode(0o000)).unwrap();
2995
    let snap = repo.snapshot("status").unwrap();
2996
    assert!(
2997
        !snap.changed && snap.statuses.is_empty(),
2998
        "{:?}",
2999
        snap.statuses
3000
    );
3001
    fs::set_permissions(root.join("big.bin"), fs::Permissions::from_mode(0o644)).unwrap();
3002
    // A real change (new mtime, new content) is seen and committed correctly.
3003
    let mut big2 = big.clone();
3004
    big2[10] ^= 0xff;
3005
    write(root, "big.bin", &big2);
3006
    let snap = repo.snapshot("status").unwrap();
3007
    assert_eq!(
3008
        snap.statuses
3009
            .iter()
3010
            .map(|s| (s.path.as_str(), s.status))
3011
            .collect::<Vec<_>>(),
3012
        vec![("big.bin", ChangeStatus::Modified)]
3013
    );
3014
    let h2 = repo.commit("edit", &[]).unwrap();
3015
    let files = repo.load_state(&[h2]).unwrap().materialize().files;
3016
    assert_eq!(
3017
        files["big.bin"].content,
3018
        FileContent::Opaque {
3019
            blobs: vec![Repo::blob_ref(&big2)]
3020
        }
3021
    );
3022
    // Checkout writes a manifest with blobs too, so the next status is cached.
3023
    repo.checkout(&[h1], false, "checkout").unwrap();
3024
    let (_, _, m) = repo.read_manifest().unwrap().unwrap();
3025
    assert_eq!(m.entries["big.bin"].blob, Some(Repo::blob_ref(&big)));
3026
    assert!(!repo.snapshot("status").unwrap().changed);
3027
}
3028
3029
#[test]
3030
fn status_json_lists_conflicts_with_contributors() {
3031
    hermetic();
3032
    let dir = tempfile::tempdir().unwrap();
3033
    let root = dir.path();
3034
    let repo = Repo::init(root).unwrap().with_home(root.join("home"));
3035
    write(root, "a.txt", b"one\n");
3036
    let h1 = repo.commit("base", &[]).unwrap();
3037
    write(root, "a.txt", b"one\nleft\n");
3038
    let ha = repo.commit("left", &[]).unwrap();
3039
    repo.checkout(&[h1], true, "checkout").unwrap();
3040
    write(root, "a.txt", b"one\nright\n");
3041
    let hb = repo.commit("right", &[]).unwrap();
3042
    repo.checkout(&[ha, hb], true, "checkout").unwrap();
3043
    let snap = repo.snapshot("status").unwrap();
3044
    assert!(snap.base_snapshot.is_conflicted());
3045
    let json = repo.status_json(&snap).unwrap();
3046
    let ida = repo.store().get_change(&ha).unwrap().change_id.to_hex();
3047
    let idb = repo.store().get_change(&hb).unwrap().change_id.to_hex();
3048
    assert!(json.contains("\"conflicted\":true"), "{json}");
3049
    assert!(
3050
        json.contains("\"kind\":\"text\",\"path\":\"a.txt\""),
3051
        "{json}"
3052
    );
3053
    assert!(json.contains(&ida) && json.contains(&idb), "{json}");
3054
    assert!(json.contains("\"resolved\":false"), "{json}");
3055
    assert!(json.starts_with('{') && json.ends_with('}'));
3056
    // Resolve and the report says so; a clean copy has no conflicts.
3057
    write(root, "a.txt", b"one\nleft\nright\n");
3058
    let snap = repo.snapshot("status").unwrap();
3059
    let json = repo.status_json(&snap).unwrap();
3060
    assert!(json.contains("\"resolved\":true"), "{json}");
3061
    repo.commit("resolve", &[]).unwrap();
3062
    let snap = repo.snapshot("status").unwrap();
3063
    let json = repo.status_json(&snap).unwrap();
3064
    assert!(
3065
        json.contains("\"clean\":true,\"conflicted\":false,\"paths\":[],\"conflicts\":[]"),
3066
        "{json}"
3067
    );
3068
}
3069
3070
#[test]
3071
fn ignore_rules_do_not_untrack_files() {
3072
    hermetic();
3073
    let dir = tempfile::tempdir().unwrap();
3074
    let root = dir.path();
3075
    let repo = Repo::init(root).unwrap().with_home(root.join("home"));
3076
    write(root, "src.c", b"int x;\n");
3077
    write(root, "build/out.o", b"\0obj");
3078
    write(root, "sub/keep.log", b"keep\n");
3079
    write(root, "sub/junk.log", b"junk\n");
3080
    write(root, ".oxyignore", b"/build\n*.log\n!sub/keep.log\n");
3081
    let snap = repo.snapshot("status").unwrap();
3082
    let added: Vec<&str> = snap.statuses.iter().map(|s| s.path.as_str()).collect();
3083
    assert_eq!(
3084
        added,
3085
        vec![".oxyignore", "src.c", "sub/keep.log"],
3086
        "anchored, glob, and negated rules"
3087
    );
3088
    let h1 = repo.commit("base", &[]).unwrap();
3089
    // Ignoring a tracked file changes nothing about it.
3090
    write(root, ".oxyignore", b"/build\n*.log\n!sub/keep.log\nsrc.c\n");
3091
    let snap = repo.snapshot("status").unwrap();
3092
    assert_eq!(
3093
        snap.statuses
3094
            .iter()
3095
            .map(|s| s.path.as_str())
3096
            .collect::<Vec<_>>(),
3097
        vec![".oxyignore"]
3098
    );
3099
    let h2 = repo.commit("ignore src.c", &[]).unwrap();
3100
    assert!(repo
3101
        .load_state(&[h2])
3102
        .unwrap()
3103
        .materialize()
3104
        .files
3105
        .contains_key("src.c"));
3106
    // Its edits are still seen, by status and by the prompt.
3107
    assert_eq!(repo.quick_dirty().unwrap(), Some(false));
3108
    write(root, "src.c", b"int x, y;\n");
3109
    assert_eq!(repo.quick_dirty().unwrap(), Some(true));
3110
    let snap = repo.snapshot("status").unwrap();
3111
    assert_eq!(
3112
        snap.statuses
3113
            .iter()
3114
            .map(|s| (s.path.as_str(), s.status))
3115
            .collect::<Vec<_>>(),
3116
        vec![("src.c", ChangeStatus::Modified)]
3117
    );
3118
    let h3 = repo.commit("edit src.c", &[]).unwrap();
3119
    assert!(
3120
        matches!(&repo.load_state(&[h3]).unwrap().materialize().files["src.c"].content, FileContent::Text { bytes, .. } if bytes == b"int x, y;\n")
3121
    );
3122
    // Deleting it on disk removes it, ignored or not; a checkout brings it back.
3123
    fs::remove_file(root.join("src.c")).unwrap();
3124
    let snap = repo.snapshot("status").unwrap();
3125
    assert_eq!(
3126
        snap.statuses
3127
            .iter()
3128
            .map(|s| (s.path.as_str(), s.status))
3129
            .collect::<Vec<_>>(),
3130
        vec![("src.c", ChangeStatus::Removed)]
3131
    );
3132
    repo.checkout(&[h3], true, "checkout").unwrap();
3133
    assert_eq!(fs::read(root.join("src.c")).unwrap(), b"int x, y;\n");
3134
    assert!(!repo.snapshot("status").unwrap().changed);
3135
    let _ = h1;
3136
}
3137
3138
#[test]
3139
fn split_works_on_non_heads_by_node() {
3140
    hermetic();
3141
    let dir = tempfile::tempdir().unwrap();
3142
    let root = dir.path();
3143
    let repo = Repo::init(root).unwrap().with_home(root.join("home"));
3144
    write(root, "a.txt", b"one\n");
3145
    write(root, "junk/x.lock", b"lock\n");
3146
    let h1 = repo.commit("work plus junk", &[]).unwrap();
3147
    write(root, "a.txt", b"one\ntwo\n");
3148
    let h2 = repo.commit("more work", &[]).unwrap();
3149
    assert_eq!(repo.store().get_change(&h2).unwrap().deps, vec![h1]);
3150
    let id1 = repo.store().get_change(&h1).unwrap().change_id;
3151
    // h1 is not a head: split it by node.
3152
    let (hj, h1b) = repo.split(&h1, &["junk".into()]).unwrap();
3153
    assert_ne!(h1b, h1);
3154
    assert_eq!(
3155
        repo.store().get_change(&h1b).unwrap().change_id,
3156
        id1,
3157
        "the rest keeps the ChangeId"
3158
    );
3159
    let junk = repo.store().get_change(&hj).unwrap();
3160
    assert!(junk.tree_ops.iter().all(
3161
        |op| matches!(op, TreeOp::AddNode { name, .. } if name == "junk" || name == "x.lock")
3162
    ));
3163
    let heads = repo.bookmark_heads().unwrap();
3164
    assert!(
3165
        heads.contains(&hj),
3166
        "the split-off part is a head of its own"
3167
    );
3168
    let snap = repo.load_state(&heads).unwrap().materialize();
3169
    assert!(
3170
        matches!(&snap.files["a.txt"].content, FileContent::Text { bytes, .. } if bytes == b"one\ntwo\n"),
3171
        "the dependent was rewritten onto the new hash"
3172
    );
3173
    assert!(snap.files.contains_key("junk/x.lock"));
3174
    let h2b = heads
3175
        .iter()
3176
        .find(|h| repo.store().get_change(h).unwrap().message == "more work")
3177
        .copied()
3178
        .unwrap();
3179
    assert_eq!(repo.store().get_change(&h2b).unwrap().deps, vec![h1b]);
3180
    assert!(!repo.snapshot("status").unwrap().changed);
3181
    // Abandoning the split-off head removes the junk from history.
3182
    repo.abandon(&hj).unwrap();
3183
    let heads = repo.bookmark_heads().unwrap();
3184
    let snap = repo.load_state(&heads).unwrap().materialize();
3185
    assert!(!snap.files.contains_key("junk/x.lock") && !snap.files.contains_key("junk"));
3186
    assert!(snap.files.contains_key("a.txt"));
3187
    // A dependent that touches the split-off paths blocks the split.
3188
    write(root, "junk/y.lock", b"y\n");
3189
    let hb = repo.commit("junk base", &[]).unwrap();
3190
    write(root, "junk/y.lock", b"yy\n");
3191
    write(root, "b.txt", b"b\n");
3192
    repo.commit("touches junk", &[]).unwrap();
3193
    let err = repo.split(&hb, &["junk".into()]).unwrap_err().to_string();
3194
    assert!(err.contains("depends on the split-off paths"), "{err}");
3195
}
3196
3197
#[test]
3198
fn bookmarks_switch_merge_and_push() {
3199
    hermetic();
3200
    let dir = tempfile::tempdir().unwrap();
3201
    let root = dir.path();
3202
    let origin = Repo::init(&root.join("origin")).unwrap();
3203
    let url = root.join("origin").to_string_lossy().to_string();
3204
    let mut repo = Repo::clone(&url, &root.join("r"))
3205
        .unwrap()
3206
        .with_home(root.join("home"));
3207
    let r = root.join("r");
3208
    write(&r, "a.txt", b"a\n");
3209
    let h_a = repo.commit("a", &[]).unwrap();
3210
    assert!(repo.push("origin", false).unwrap()[0].ok);
3211
3212
    // A bookmark at the working copy's base, then work on it.
3213
    assert!(repo.bookmark_create("bad name..", None).is_err());
3214
    assert!(repo.bookmark_create("-x", None).is_err());
3215
    assert_eq!(repo.bookmark_create("feature", None).unwrap(), vec![h_a]);
3216
    assert!(repo.bookmark_create("feature", None).is_err(), "exists");
3217
    repo.bookmark_switch("feature", false).unwrap();
3218
    assert_eq!(repo.config.bookmark, "feature");
3219
    write(&r, "a.txt", b"a\nb\n");
3220
    write(&r, "b.txt", b"b\n");
3221
    let h_b = repo.commit("b on feature", &[]).unwrap();
3222
    assert_eq!(
3223
        repo.bookmark_heads().unwrap(),
3224
        vec![h_b],
3225
        "b edits a.txt, so it depends on a"
3226
    );
3227
    assert_eq!(
3228
        repo.resolve_heads("main").unwrap(),
3229
        vec![h_a],
3230
        "main is untouched"
3231
    );
3232
    assert_eq!(
3233
        repo.resolve_change("feature").unwrap(),
3234
        h_b,
3235
        "a one-head bookmark names its change"
3236
    );
3237
    // Reopening keeps the workspace's bookmark.
3238
    let reopened = Repo::open(&r).unwrap().with_home(root.join("home"));
3239
    assert_eq!(reopened.config.bookmark, "feature");
3240
    // Back to main: b.txt goes away; work there.
3241
    repo.bookmark_switch("main", false).unwrap();
3242
    assert!(!r.join("b.txt").exists());
3243
    assert_eq!(fs::read(r.join("a.txt")).unwrap(), b"a\n");
3244
    write(&r, "c.txt", b"c\n");
3245
    let h_c = repo.commit("c on main", &[]).unwrap();
3246
    let list = repo.bookmarks().unwrap();
3247
    assert_eq!(
3248
        list.iter()
3249
            .map(|b| (b.name.as_str(), b.current))
3250
            .collect::<Vec<_>>(),
3251
        vec![("feature", false), ("main", true)]
3252
    );
3253
    assert_eq!(
3254
        list.iter().find(|b| b.name == "main").unwrap().ahead,
3255
        Some(1),
3256
        "c is not on origin yet"
3257
    );
3258
    // Merge feature into main: the union, both heads, no merge change.
3259
    let m = repo.merge("feature").unwrap();
3260
    assert!(m.changed && m.checked_out);
3261
    let mut want = vec![h_b, h_c];
3262
    want.sort();
3263
    assert_eq!(m.heads, want);
3264
    assert_eq!(fs::read(r.join("b.txt")).unwrap(), b"b\n");
3265
    assert!(!repo.merge("feature").unwrap().changed, "already merged");
3266
    assert!(repo.merge("main").is_err());
3267
    // The other bookmark can be pushed by name and appears at origin.
3268
    assert!(repo.push_bookmark("origin", "feature", false).unwrap()[0].ok);
3269
    assert_eq!(origin.resolve_heads("feature").unwrap(), vec![h_b]);
3270
    assert!(repo.push("origin", false).unwrap()[0].ok);
3271
    assert_eq!(
3272
        repo.bookmarks()
3273
            .unwrap()
3274
            .iter()
3275
            .find(|b| b.name == "main")
3276
            .unwrap()
3277
            .ahead,
3278
        Some(0)
3279
    );
3280
    // A second workspace inherits the current bookmark and can switch independently.
3281
    let ws = repo.workspace_add(&root.join("ws"), None).unwrap();
3282
    assert_eq!(ws.config.bookmark, "main");
3283
    let mut ws = ws;
3284
    ws.bookmark_switch("feature", false).unwrap();
3285
    assert_eq!(
3286
        Repo::open(&r).unwrap().config.bookmark,
3287
        "main",
3288
        "the first workspace is unaffected"
3289
    );
3290
    assert!(
3291
        repo.bookmark_delete("feature").is_err(),
3292
        "current bookmark of another workspace"
3293
    );
3294
    ws.bookmark_switch("main", false).unwrap();
3295
    // Set and delete.
3296
    assert_eq!(repo.bookmark_set("feature", &[h_a]).unwrap(), vec![h_a]);
3297
    assert!(repo.bookmark_delete("main").is_err(), "current here");
3298
    repo.bookmark_delete("feature").unwrap();
3299
    assert!(repo.resolve_heads("feature").is_err());
3300
    assert!(repo.bookmark_set("feature", &[h_a]).is_err());
3301
    assert!(
3302
        repo.checkout(&[h_a], false, "checkout").is_ok(),
3303
        "changes of a deleted bookmark remain"
3304
    );
3305
}
3306
3307
#[test]
3308
fn oxygen_subrepos_pin_follow_and_update() {
3309
    hermetic();
3310
    let dir = tempfile::tempdir().unwrap();
3311
    let root = dir.path();
3312
    // A library repository with two commits, and a bare-ish origin for it.
3313
    let lib_origin = Repo::init(&root.join("lib-origin")).unwrap();
3314
    let lib_url = root.join("lib-origin").to_string_lossy().to_string();
3315
    let lib = Repo::clone(&lib_url, &root.join("lib"))
3316
        .unwrap()
3317
        .with_home(root.join("home"));
3318
    write(&root.join("lib"), "lib.txt", b"v1\n");
3319
    let l1 = lib.commit("lib v1", &[]).unwrap();
3320
    assert!(lib.push("origin", false).unwrap()[0].ok);
3321
    let _ = lib_origin;
3322
3323
    // The application (a clone of its own origin) adds it as a subrepo.
3324
    let app_origin = Repo::init(&root.join("app-origin")).unwrap();
3325
    let app_url = root.join("app-origin").to_string_lossy().to_string();
3326
    let _ = app_origin;
3327
    let app_dir = root.join("app");
3328
    let app = Repo::clone(&app_url, &app_dir)
3329
        .unwrap()
3330
        .with_home(root.join("home"));
3331
    write(&app_dir, "main.txt", b"app\n");
3332
    let pin = app.submodule_add(&lib_url, "libs/lib", None).unwrap();
3333
    assert!(matches!(&pin, crate::subrepo::Pin::Oxy { heads, .. } if heads == &vec![l1]));
3334
    assert!(app_dir.join(".oxymodules").exists() && app_dir.join("libs/lib/.oxy").is_dir());
3335
    let snap = app.snapshot("status").unwrap();
3336
    let paths: Vec<&str> = snap.statuses.iter().map(|s| s.path.as_str()).collect();
3337
    assert_eq!(
3338
        paths,
3339
        vec![".oxymodules", "libs/lib", "main.txt"],
3340
        "the nested files are not walked"
3341
    );
3342
    let a1 = app.commit("app with lib", &[]).unwrap();
3343
    let files = app.load_state(&[a1]).unwrap().materialize().files;
3344
    assert_eq!(files["libs/lib"].kind, NodeKind::Subrepo);
3345
    assert!(!files.contains_key("libs/lib/lib.txt"));
3346
    assert!(!app.snapshot("status").unwrap().changed);
3347
    let subs = app.subrepos().unwrap();
3348
    assert_eq!(subs.len(), 1);
3349
    assert_eq!(subs[0].actual.as_ref(), Some(&subs[0].pin));
3350
3351
    // Advance the nested repository: the parent sees a modified pin.
3352
    let nested = Repo::open(&app_dir.join("libs/lib"))
3353
        .unwrap()
3354
        .with_home(root.join("home"));
3355
    write(&app_dir.join("libs/lib"), "lib.txt", b"v2\n");
3356
    let l2 = nested.commit("lib v2", &[]).unwrap();
3357
    assert!(nested.push("origin", false).unwrap()[0].ok);
3358
    let snap = app.snapshot("status").unwrap();
3359
    assert_eq!(
3360
        snap.statuses
3361
            .iter()
3362
            .map(|s| (s.path.as_str(), s.status))
3363
            .collect::<Vec<_>>(),
3364
        vec![("libs/lib", ChangeStatus::Modified)]
3365
    );
3366
    let a2 = app.commit("bump lib", &[]).unwrap();
3367
    // Checking out the older app state brings the nested working copy back
3368
    // to the older pin, but never moves its bookmark backwards (oxygen#38).
3369
    let r = app.checkout(&[a1], false, "checkout").unwrap();
3370
    assert!(
3371
        r.notes.len() == 1 && r.notes[0].contains("keeps 1 newer change"),
3372
        "{:?}",
3373
        r.notes
3374
    );
3375
    assert_eq!(fs::read(app_dir.join("libs/lib/lib.txt")).unwrap(), b"v1\n");
3376
    let nested = Repo::open(&app_dir.join("libs/lib")).unwrap();
3377
    assert_eq!(nested.bookmark_heads().unwrap(), vec![l2]);
3378
    assert_eq!(nested.working_copy().unwrap().1.deps, vec![l1]);
3379
    assert!(!app.snapshot("status").unwrap().changed);
3380
    // A dirty nested repository is left alone and reported.
3381
    write(&app_dir.join("libs/lib"), "scratch.txt", b"wip\n");
3382
    let r = app.checkout(&[a2], false, "checkout").unwrap();
3383
    assert!(
3384
        r.notes.iter().any(|n| n.contains("uncommitted")),
3385
        "{:?}",
3386
        r.notes
3387
    );
3388
    assert_eq!(fs::read(app_dir.join("libs/lib/lib.txt")).unwrap(), b"v1\n");
3389
    fs::remove_file(app_dir.join("libs/lib/scratch.txt")).unwrap();
3390
    let r = app.submodule_update(false, &[]).unwrap();
3391
    assert_eq!(r, vec![("libs/lib".to_string(), SubrepoSync::Updated)]);
3392
    assert_eq!(fs::read(app_dir.join("libs/lib/lib.txt")).unwrap(), b"v2\n");
3393
    let _ = l2;
3394
3395
    // A fresh clone of the app has the pin but no nested repository until update --init.
3396
    assert!(app.push("origin", false).unwrap()[0].ok);
3397
    let clone_dir = root.join("app-clone");
3398
    let clone = Repo::clone(&app_url, &clone_dir)
3399
        .unwrap()
3400
        .with_home(root.join("home"));
3401
    assert!(!clone_dir.join("libs/lib/.oxy").exists());
3402
    assert_eq!(
3403
        clone.submodule_update(false, &[]).unwrap(),
3404
        vec![("libs/lib".to_string(), SubrepoSync::Missing)]
3405
    );
3406
    assert_eq!(
3407
        clone.submodule_update(true, &[]).unwrap(),
3408
        vec![("libs/lib".to_string(), SubrepoSync::Updated)]
3409
    );
3410
    assert_eq!(
3411
        fs::read(clone_dir.join("libs/lib/lib.txt")).unwrap(),
3412
        b"v2\n"
3413
    );
3414
    assert!(!clone.snapshot("status").unwrap().changed);
3415
    // Removing the subrepo leaves the directory and drops the node.
3416
    clone.submodule_remove("libs/lib").unwrap();
3417
    let snap = clone.snapshot("status").unwrap();
3418
    assert!(
3419
        snap.statuses
3420
            .iter()
3421
            .any(|s| s.path == "libs/lib" && s.status == ChangeStatus::Removed),
3422
        "{:?}",
3423
        snap.statuses
3424
    );
3425
    let c = clone.commit("drop lib", &[]).unwrap();
3426
    assert!(!clone
3427
        .load_state(&[c])
3428
        .unwrap()
3429
        .materialize()
3430
        .files
3431
        .contains_key("libs/lib"));
3432
    assert!(clone_dir.join("libs/lib/lib.txt").exists());
3433
    assert!(
3434
        !clone.snapshot("status").unwrap().changed,
3435
        "an unregistered nested repository is ignored"
3436
    );
3437
}
3438
3439
#[test]
3440
fn git_submodules_import_and_export_as_gitlinks() {
3441
    hermetic();
3442
    if std::process::Command::new("git")
3443
        .arg("--version")
3444
        .output()
3445
        .is_err()
3446
    {
3447
        eprintln!("git not installed; skipping");
3448
        return;
3449
    }
3450
    let dir = tempfile::tempdir().unwrap();
3451
    let root = dir.path();
3452
    let git_in = |d: &Path, args: &[&str]| -> String {
3453
        let out = std::process::Command::new("git")
3454
            .arg("-C")
3455
            .arg(d)
3456
            .args([
3457
                "-c",
3458
                "user.name=Grace",
3459
                "-c",
3460
                "[email protected]",
3461
                "-c",
3462
                "commit.gpgsign=false",
3463
                "-c",
3464
                "protocol.file.allow=always",
3465
            ])
3466
            .args(args)
3467
            .output()
3468
            .unwrap();
3469
        assert!(
3470
            out.status.success(),
3471
            "git {args:?}: {}",
3472
            String::from_utf8_lossy(&out.stderr)
3473
        );
3474
        String::from_utf8_lossy(&out.stdout).trim().to_string()
3475
    };
3476
    let sub = root.join("sub");
3477
    fs::create_dir_all(&sub).unwrap();
3478
    git_in(&sub, &["init", "-q", "-b", "main"]);
3479
    write(&sub, "s.txt", b"sub\n");
3480
    git_in(&sub, &["add", "."]);
3481
    git_in(&sub, &["commit", "-q", "-m", "sub initial"]);
3482
    let sub_sha = git_in(&sub, &["rev-parse", "HEAD"]);
3483
    let g = root.join("main.git");
3484
    fs::create_dir_all(&g).unwrap();
3485
    git_in(&g, &["init", "-q", "-b", "main"]);
3486
    write(&g, "README.md", b"# app\n");
3487
    git_in(&g, &["add", "."]);
3488
    git_in(&g, &["commit", "-q", "-m", "initial"]);
3489
    git_in(
3490
        &g,
3491
        &[
3492
            "submodule",
3493
            "add",
3494
            "-q",
3495
            sub.to_str().unwrap(),
3496
            "vendor/sub",
3497
        ],
3498
    );
3499
    git_in(&g, &["commit", "-q", "-m", "add submodule"]);
3500
3501
    let dest = root.join("oxy");
3502
    let repo = Repo::init(&dest).unwrap().with_home(root.join("home"));
3503
    let rep = repo.import_git(&g, "main").unwrap();
3504
    assert_eq!((rep.commits, rep.submodules), (2, 1));
3505
    let files = repo
3506
        .load_state(&repo.bookmark_heads().unwrap())
3507
        .unwrap()
3508
        .materialize()
3509
        .files;
3510
    assert_eq!(files["vendor/sub"].kind, NodeKind::Subrepo);
3511
    let FileContent::Opaque { blobs } = &files["vendor/sub"].content else {
3512
        panic!()
3513
    };
3514
    assert_eq!(
3515
        crate::subrepo::Pin::decode(&repo.read_blob(&blobs[0]).unwrap()).unwrap(),
3516
        crate::subrepo::Pin::Git {
3517
            sha: sub_sha.clone(),
3518
            branch: "HEAD".into()
3519
        }
3520
    );
3521
    let modules =
3522
        crate::subrepo::Modules::parse(&fs::read_to_string(dest.join(".oxymodules")).unwrap());
3523
    assert_eq!(modules.entries["vendor/sub"].url, sub.to_string_lossy());
3524
    assert!(modules.entries["vendor/sub"].git);
3525
    assert!(
3526
        files.contains_key(".gitmodules"),
3527
        "the Git file is kept for round trips"
3528
    );
3529
    assert!(
3530
        !dest.join("vendor/sub/.git").exists(),
3531
        "not cloned until update --init"
3532
    );
3533
    assert!(!repo.snapshot("status").unwrap().changed);
3534
    // update --init clones it at the pinned commit; status is unchanged.
3535
    assert_eq!(
3536
        repo.submodule_update(true, &[]).unwrap(),
3537
        vec![("vendor/sub".to_string(), SubrepoSync::Updated)]
3538
    );
3539
    assert_eq!(
3540
        git_in(&dest.join("vendor/sub"), &["rev-parse", "HEAD"]),
3541
        sub_sha
3542
    );
3543
    assert!(!repo.snapshot("status").unwrap().changed);
3544
    // Export writes the gitlink and .gitmodules back.
3545
    let mirror = root.join("mirror.git");
3546
    let rep = repo.git_export(&mirror).unwrap();
3547
    assert_eq!(rep.skipped_subrepos, 0);
3548
    let ls = git_in(&mirror, &["ls-tree", "main", "vendor/sub"]);
3549
    assert!(
3550
        ls.starts_with("160000 commit ") && ls.contains(&sub_sha),
3551
        "{ls}"
3552
    );
3553
    assert_eq!(
3554
        git_in(&mirror, &["ls-tree", "--name-only", "main"]),
3555
        ".gitmodules\nREADME.md\nvendor"
3556
    );
3557
    let orig_tree = git_in(&g, &["rev-parse", "main^{tree}"]);
3558
    assert_eq!(
3559
        git_in(&mirror, &["rev-parse", "main^{tree}"]),
3560
        orig_tree,
3561
        "tree round trip"
3562
    );
3563
}
3564
3565
#[test]
3566
fn partial_commits_by_path_and_by_hunk() {
3567
    hermetic();
3568
    let dir = tempfile::tempdir().unwrap();
3569
    let root = dir.path();
3570
    let repo = Repo::init(root).unwrap().with_home(root.join("home"));
3571
    write(root, "a.txt", b"1\n2\n3\n");
3572
    write(root, "b.txt", b"b\n");
3573
    let h0 = repo.commit("base", &[]).unwrap();
3574
    write(root, "a.txt", b"0\n1\n2\n3\n4\n");
3575
    write(root, "b.txt", b"b\nbb\n");
3576
    write(root, "c.txt", b"c\n");
3577
    // By path: only a.txt goes in; the rest stays on disk as uncommitted work.
3578
    let h1 = repo
3579
        .commit_selection("a only", &[], &Selection::Paths(vec!["a.txt".into()]))
3580
        .unwrap();
3581
    let c1 = repo.store().get_change(&h1).unwrap();
3582
    assert!(
3583
        c1.tree_ops.is_empty() && c1.edits.iter().all(|e| e.node() == c1.edits[0].node()),
3584
        "{:?}",
3585
        c1.tree_ops
3586
    );
3587
    assert_eq!(c1.deps, vec![h0]);
3588
    let files = repo.load_state(&[h1]).unwrap().materialize().files;
3589
    assert!(
3590
        matches!(&files["a.txt"].content, FileContent::Text { bytes, .. } if bytes == b"0\n1\n2\n3\n4\n")
3591
    );
3592
    assert!(matches!(&files["b.txt"].content, FileContent::Text { bytes, .. } if bytes == b"b\n"));
3593
    assert!(!files.contains_key("c.txt"));
3594
    let snap = repo.snapshot("status").unwrap();
3595
    assert_eq!(
3596
        snap.statuses
3597
            .iter()
3598
            .map(|s| (s.path.as_str(), s.status))
3599
            .collect::<Vec<_>>(),
3600
        vec![
3601
            ("b.txt", ChangeStatus::Modified),
3602
            ("c.txt", ChangeStatus::Added)
3603
        ]
3604
    );
3605
    assert_eq!(
3606
        fs::read(root.join("b.txt")).unwrap(),
3607
        b"b\nbb\n",
3608
        "disk untouched"
3609
    );
3610
    // By hunk: pick the b.txt insert; c.txt's addition is left.
3611
    let (_, hunks) = repo.hunks().unwrap();
3612
    let b_hunk = hunks
3613
        .iter()
3614
        .find(|h| h.path == "b.txt" && h.text.contains("+bb"))
3615
        .unwrap()
3616
        .index;
3617
    let h2 = repo
3618
        .commit_selection("b only", &[], &Selection::Hunks(vec![b_hunk]))
3619
        .unwrap();
3620
    let files = repo.load_state(&[h2]).unwrap().materialize().files;
3621
    assert!(
3622
        matches!(&files["b.txt"].content, FileContent::Text { bytes, .. } if bytes == b"b\nbb\n")
3623
    );
3624
    assert!(!files.contains_key("c.txt"));
3625
    let snap = repo.snapshot("status").unwrap();
3626
    assert_eq!(
3627
        snap.statuses
3628
            .iter()
3629
            .map(|s| s.path.as_str())
3630
            .collect::<Vec<_>>(),
3631
        vec!["c.txt"]
3632
    );
3633
    // Choosing only the content hunk of a file in a new directory pulls in
3634
    // the directory and file additions it needs.
3635
    write(root, "d/e.txt", b"e\n");
3636
    let (_, hunks) = repo.hunks().unwrap();
3637
    let e_insert = hunks
3638
        .iter()
3639
        .find(|h| h.path == "d/e.txt" && h.text.contains("+e"))
3640
        .unwrap()
3641
        .index;
3642
    let h3 = repo
3643
        .commit_selection("e only", &[], &Selection::Hunks(vec![e_insert]))
3644
        .unwrap();
3645
    let c3 = repo.store().get_change(&h3).unwrap();
3646
    assert_eq!(c3.tree_ops.len(), 2, "{:?}", c3.tree_ops);
3647
    let files = repo.load_state(&[h3]).unwrap().materialize().files;
3648
    assert!(files.contains_key("d/e.txt") && !files.contains_key("c.txt"));
3649
    // Choosing a new file's addition hunk brings its content along.
3650
    write(root, "f/g.txt", b"g\n");
3651
    let (_, hunks) = repo.hunks().unwrap();
3652
    let g_add = hunks
3653
        .iter()
3654
        .find(|h| h.path == "f/g.txt" && h.text.starts_with("A "))
3655
        .unwrap()
3656
        .index;
3657
    let h4 = repo
3658
        .commit_selection("g by addition", &[], &Selection::Hunks(vec![g_add]))
3659
        .unwrap();
3660
    let files = repo.load_state(&[h4]).unwrap().materialize().files;
3661
    assert!(
3662
        matches!(&files["f/g.txt"].content, FileContent::Text { bytes, .. } if bytes == b"g\n")
3663
    );
3664
    assert!(!repo
3665
        .snapshot("status")
3666
        .unwrap()
3667
        .statuses
3668
        .iter()
3669
        .any(|s| s.path == "f/g.txt"));
3670
    // Everything left commits normally; the working copy is then clean.
3671
    repo.commit("the rest", &[]).unwrap();
3672
    assert!(!repo.snapshot("status").unwrap().changed);
3673
    let files = repo
3674
        .load_state(&repo.bookmark_heads().unwrap())
3675
        .unwrap()
3676
        .materialize()
3677
        .files;
3678
    assert!(files.contains_key("c.txt"));
3679
}
3680
3681
#[test]
3682
fn blame_attributes_lines_to_introducing_changes_across_renames() {
3683
    hermetic();
3684
    let dir = tempfile::tempdir().unwrap();
3685
    let root = dir.path();
3686
    let mut repo = Repo::init(root).unwrap().with_home(root.join("home"));
3687
    repo.create_identity("Ada", "[email protected]", IdentityScope::User)
3688
        .unwrap();
3689
    write(root, "a.txt", b"one\n");
3690
    let h1 = repo.commit("first", &[]).unwrap();
3691
    write(root, "a.txt", b"one\ntwo\n");
3692
    let h2 = repo.commit("second", &[]).unwrap();
3693
    let b = repo.blame("a.txt").unwrap();
3694
    assert_eq!(
3695
        b.iter()
3696
            .map(|l| (l.line, l.hash, l.text.as_slice()))
3697
            .collect::<Vec<_>>(),
3698
        vec![(1, h1, b"one\n".as_slice()), (2, h2, b"two\n".as_slice())]
3699
    );
3700
    assert!(b.iter().all(|l| l.author == "Ada"));
3701
    assert_eq!(
3702
        b[0].change_id,
3703
        repo.store().get_change(&h1).unwrap().change_id
3704
    );
3705
    fs::rename(root.join("a.txt"), root.join("b.txt")).unwrap();
3706
    repo.commit("rename", &[]).unwrap();
3707
    let b = repo.blame("b.txt").unwrap();
3708
    assert_eq!(
3709
        b.iter().map(|l| l.hash).collect::<Vec<_>>(),
3710
        vec![h1, h2],
3711
        "the node survives the rename"
3712
    );
3713
    assert!(repo.blame("a.txt").is_err());
3714
}
3715
3716
#[test]
3717
fn bisect_finds_the_first_bad_change() {
3718
    hermetic();
3719
    let dir = tempfile::tempdir().unwrap();
3720
    let root = dir.path();
3721
    let repo = Repo::init(root).unwrap().with_home(root.join("home"));
3722
    let mut content = String::new();
3723
    let mut hashes = Vec::new();
3724
    for i in 1..=8 {
3725
        content.push_str(&format!("line {i}{}\n", if i == 5 { " bug" } else { "" }));
3726
        write(root, "f.txt", content.as_bytes());
3727
        hashes.push(repo.commit(&format!("step {i}"), &[]).unwrap());
3728
    }
3729
    // Each step appends after the previous line, so the chain is linear.
3730
    assert_eq!(repo.bookmark_heads().unwrap(), vec![hashes[7]]);
3731
    repo.bisect_start().unwrap();
3732
    assert!(matches!(
3733
        repo.bisect_mark(Some(true), &[hashes[0]]).unwrap(),
3734
        BisectStep::NeedMarks { good: 1, bad: 0 }
3735
    ));
3736
    let step = repo.bisect_mark(Some(false), &[hashes[7]]).unwrap();
3737
    assert!(
3738
        matches!(step, BisectStep::Testing { remaining: 7, .. }),
3739
        "{step:?}"
3740
    );
3741
    // Automated: bad when the bug line is present.
3742
    let step = repo
3743
        .bisect_run(&["sh".into(), "-c".into(), "! grep -q bug f.txt".into()])
3744
        .unwrap();
3745
    assert_eq!(step, BisectStep::Found { culprit: hashes[4] });
3746
    assert_eq!(
3747
        repo.bisect_status().unwrap(),
3748
        Some(BisectStep::Found { culprit: hashes[4] })
3749
    );
3750
    repo.bisect_reset().unwrap();
3751
    assert_eq!(fs::read_to_string(root.join("f.txt")).unwrap(), content);
3752
    assert!(repo.bisect_status().unwrap().is_none());
3753
    assert!(!repo.snapshot("status").unwrap().changed);
3754
    // Manual marks and a skip.
3755
    repo.bisect_start().unwrap();
3756
    repo.bisect_mark(Some(true), &[hashes[0]]).unwrap();
3757
    let mut step = repo.bisect_mark(Some(false), &[hashes[7]]).unwrap();
3758
    let mut skipped_once = false;
3759
    let mut guard = 0;
3760
    while let BisectStep::Testing { .. } = step {
3761
        guard += 1;
3762
        assert!(guard < 20);
3763
        let text = fs::read_to_string(root.join("f.txt")).unwrap();
3764
        if !skipped_once && text.contains("line 6") {
3765
            // An untestable state away from the boundary: the search routes around it.
3766
            skipped_once = true;
3767
            step = repo.bisect_mark(None, &[]).unwrap();
3768
            continue;
3769
        }
3770
        step = repo.bisect_mark(Some(!text.contains("bug")), &[]).unwrap();
3771
    }
3772
    assert!(skipped_once);
3773
    assert_eq!(step, BisectStep::Found { culprit: hashes[4] });
3774
    repo.bisect_reset().unwrap();
3775
    // Skipping the culprit itself leaves it among the candidates reported.
3776
    repo.bisect_start().unwrap();
3777
    repo.bisect_mark(Some(true), &[hashes[0]]).unwrap();
3778
    let mut step = repo.bisect_mark(Some(false), &[hashes[7]]).unwrap();
3779
    let mut guard = 0;
3780
    while let BisectStep::Testing { heads, .. } = &step {
3781
        guard += 1;
3782
        assert!(guard < 20);
3783
        let text = fs::read_to_string(root.join("f.txt")).unwrap();
3784
        let is_culprit_state =
3785
            heads.contains(&hashes[4]) && !heads.iter().any(|h| hashes[5..].contains(h));
3786
        step = if is_culprit_state {
3787
            repo.bisect_mark(None, &[]).unwrap()
3788
        } else {
3789
            repo.bisect_mark(Some(!text.contains("bug")), &[]).unwrap()
3790
        };
3791
    }
3792
    match step {
3793
        BisectStep::Inconclusive { candidates } => assert!(
3794
            candidates.contains(&hashes[4]) && candidates.len() <= 2,
3795
            "{candidates:?}"
3796
        ),
3797
        other => panic!("{other:?}"),
3798
    }
3799
    repo.bisect_reset().unwrap();
3800
}
3801
3802
#[test]
3803
fn squash_folds_a_change_into_its_dependency() {
3804
    hermetic();
3805
    let dir = tempfile::tempdir().unwrap();
3806
    let root = dir.path();
3807
    let repo = Repo::init(root).unwrap().with_home(root.join("home"));
3808
    write(root, "a.txt", b"1\n");
3809
    let a = repo.commit("A", &[]).unwrap();
3810
    write(root, "a.txt", b"1\n2\n");
3811
    let c = repo.commit("C", &[]).unwrap();
3812
    write(root, "a.txt", b"1\n2\n3\n");
3813
    let e = repo.commit("E", &[]).unwrap();
3814
    write(root, "b.txt", b"b\n");
3815
    let b = repo.commit("B", &[]).unwrap();
3816
    let id_a = repo.store().get_change(&a).unwrap().change_id;
3817
    let id_e = repo.store().get_change(&e).unwrap().change_id;
3818
    // E depends on C which A lacks: refused, naming it.
3819
    let err = repo.squash(&e, &a).unwrap_err().to_string();
3820
    assert!(err.contains(&c.short(12)), "{err}");
3821
    // C into A: A' has both, C is gone, E follows and still reads the same.
3822
    let a2 = repo.squash(&c, &a).unwrap();
3823
    let a2c = repo.store().get_change(&a2).unwrap();
3824
    assert_eq!(a2c.change_id, id_a);
3825
    assert!(a2c.deps.is_empty());
3826
    let heads = repo.bookmark_heads().unwrap();
3827
    let st = repo.load_state(&heads).unwrap();
3828
    assert!(!st.contains(&c) && !st.contains(&a) && !st.contains(&e));
3829
    let e2 = st
3830
        .changes()
3831
        .find(|(_, m)| m.change_id == id_e)
3832
        .map(|(h, _)| *h)
3833
        .unwrap();
3834
    assert_eq!(
3835
        repo.store().get_change(&e2).unwrap().deps,
3836
        vec![a2],
3837
        "E now depends on A' alone"
3838
    );
3839
    let files = st.materialize().files;
3840
    assert!(
3841
        matches!(&files["a.txt"].content, FileContent::Text { bytes, .. } if bytes == b"1\n2\n3\n")
3842
    );
3843
    assert!(files.contains_key("b.txt"));
3844
    assert!(st.contains(&b));
3845
    assert!(!repo.snapshot("status").unwrap().changed);
3846
    assert_eq!(repo.log().unwrap().len(), 4, "working copy, B, E', A'");
3847
    // Undo restores the three original changes.
3848
    repo.undo().unwrap();
3849
    repo.undo().unwrap();
3850
    let st = repo.load_state(&repo.bookmark_heads().unwrap()).unwrap();
3851
    assert!(st.contains(&c) && st.contains(&a) && st.contains(&e));
3852
}
3853
3854
#[test]
3855
fn rebase_re_expresses_a_change_against_another_base() {
3856
    hermetic();
3857
    let dir = tempfile::tempdir().unwrap();
3858
    let root = dir.path();
3859
    let repo = Repo::init(root).unwrap().with_home(root.join("home"));
3860
    write(root, "a.txt", b"1\n2\n");
3861
    let a = repo.commit("A", &[]).unwrap();
3862
    write(root, "a.txt", b"1\n2\n3\n");
3863
    let c = repo.commit("C: append 3", &[]).unwrap();
3864
    write(root, "a.txt", b"1\n2\n3\n4\n");
3865
    let e = repo.commit("E: append 4", &[]).unwrap();
3866
    // A different base: A plus a change that prepends a line.
3867
    repo.checkout(&[a], true, "checkout").unwrap();
3868
    write(root, "a.txt", b"0\n1\n2\n");
3869
    let d = repo.commit("D: prepend 0", &[]).unwrap();
3870
    let id_c = repo.store().get_change(&c).unwrap().change_id;
3871
    let id_e = repo.store().get_change(&e).unwrap().change_id;
3872
    // Rebase C onto D: its effect (append 3) re-derived against D's text.
3873
    let c2 = repo.rebase(&c, &[d]).unwrap();
3874
    let c2c = repo.store().get_change(&c2).unwrap();
3875
    assert_eq!(c2c.change_id, id_c);
3876
    assert!(c2c.deps.contains(&d), "{:?}", c2c.deps);
3877
    let heads = repo.bookmark_heads().unwrap();
3878
    let st = repo.load_state(&heads).unwrap();
3879
    assert!(!st.contains(&c) && st.contains(&d));
3880
    let e2 = st
3881
        .changes()
3882
        .find(|(_, m)| m.change_id == id_e)
3883
        .map(|(h, _)| *h)
3884
        .unwrap();
3885
    let e2deps = repo.store().get_change(&e2).unwrap().deps;
3886
    assert!(
3887
        e2deps.contains(&c2) && !e2deps.contains(&c) && e2deps.contains(&a),
3888
        "E follows C by content and still depends on A, which introduced the file: {e2deps:?}"
3889
    );
3890
    let files = st.materialize().files;
3891
    assert!(
3892
        matches!(&files["a.txt"].content, FileContent::Text { bytes, .. } if bytes == b"0\n1\n2\n3\n4\n"),
3893
        "{:?}",
3894
        files["a.txt"].content
3895
    );
3896
    assert!(!files["a.txt"].is_conflicted());
3897
    // Rebasing onto a state that already contains the change is refused.
3898
    assert!(repo.rebase(&c2, &[c2]).is_err());
3899
    let err = repo.rebase(&e2, &[d]).unwrap_err().to_string();
3900
    assert!(
3901
        err.contains("lacks dependencies"),
3902
        "E needs C, which D's state does not have: {err}"
3903
    );
3904
}
3905
3906
#[test]
3907
fn unsigned_tags_keep_their_message() {
3908
    hermetic();
3909
    let dir = tempfile::tempdir().unwrap();
3910
    let root = dir.path();
3911
    let repo = Repo::init(root).unwrap().with_home(root.join("home"));
3912
    write(root, "a.txt", b"a\n");
3913
    repo.commit("a", &[]).unwrap();
3914
    assert!(repo.secret_key().unwrap().is_none());
3915
    repo.tag_create("v1", &repo.bookmark_heads().unwrap(), "first release")
3916
        .unwrap();
3917
    let tags = repo.tags().unwrap();
3918
    assert_eq!(
3919
        (
3920
            tags[0].name.as_str(),
3921
            tags[0].message.as_str(),
3922
            tags[0].signer.as_deref()
3923
        ),
3924
        ("v1", "first release", None)
3925
    );
3926
    assert!(
3927
        repo.tag_refs().unwrap()[0].attestation.is_none(),
3928
        "an unsigned attestation is not advertised"
3929
    );
3930
}
3931
3932
#[test]
3933
fn fsck_passes_a_sound_repository_and_names_each_fault() {
3934
    hermetic();
3935
    let dir = tempfile::tempdir().unwrap();
3936
    let root = dir.path();
3937
    let origin_path = root.join("origin");
3938
    let origin = Repo::init(&origin_path).unwrap();
3939
    let mut a = Repo::clone(&origin_path.to_string_lossy(), &root.join("a"))
3940
        .unwrap()
3941
        .with_home(root.join("home-a"));
3942
    a.create_identity("Ada", "[email protected]", IdentityScope::Repo)
3943
        .unwrap();
3944
    write(&root.join("a"), "f.txt", b"one\n");
3945
    write(&root.join("a"), "bin.dat", b"\0\x01\x02binary");
3946
    let h1 = a.commit("first", &[]).unwrap();
3947
    write(&root.join("a"), "f.txt", b"one\ntwo\n");
3948
    let h2 = a.commit("second", &[]).unwrap();
3949
    a.tag_create("v1", &[h2], "first release").unwrap();
3950
    a.checkpoint().unwrap();
3951
    assert!(a.push("origin", false).unwrap()[0].ok);
3952
3953
    // Sound: signed changes, a seal, a tag, a checkpoint, a ref attestation.
3954
    for repo in [&a, &origin] {
3955
        let rep = repo.fsck().unwrap();
3956
        assert_eq!(rep.problems, vec![], "{rep:?}");
3957
        // The two commits, plus the working copy's change in `a`.
3958
        assert!(rep.changes >= 2 && rep.signed >= 2, "{rep:?}");
3959
        assert!(rep.ops > 1 && rep.objects > 5);
3960
    }
3961
    assert!(origin.fsck().unwrap().attestations >= 1);
3962
3963
    // A flipped byte in a stored object is corruption, named by hash.
3964
    let c1 = a.store().path_for(&h1);
3965
    let pristine = fs::read(&c1).unwrap();
3966
    let mut bytes = pristine.clone();
3967
    *bytes.last_mut().unwrap() ^= 1;
3968
    fs::write(&c1, &bytes).unwrap();
3969
    let rep = a.fsck().unwrap();
3970
    assert!(rep.errors() >= 1);
3971
    assert!(
3972
        rep.problems
3973
            .iter()
3974
            .any(|p| p.object == Some(h1) && p.what.contains("unreadable")),
3975
        "{rep:?}"
3976
    );
3977
    fs::write(&c1, &pristine).unwrap();
3978
    assert_eq!(a.fsck().unwrap().errors(), 0);
3979
3980
    // A missing change is named with what needed it.
3981
    fs::remove_file(&c1).unwrap();
3982
    let rep = a.fsck().unwrap();
3983
    assert!(
3984
        rep.problems.iter().any(|p| p.severity == Severity::Error
3985
            && p.object == Some(h1)
3986
            && p.what.contains("change missing, needed by change")),
3987
        "{rep:?}"
3988
    );
3989
    fs::write(&c1, &pristine).unwrap();
3990
3991
    // A missing blob is an error in a full clone.
3992
    let c2 = a.store().get_change(&h1).unwrap();
3993
    let blob = c2
3994
        .edits
3995
        .iter()
3996
        .find_map(|e| match e {
3997
            Edit::Replace { new: Some(b), .. } => Some(*b),
3998
            _ => None,
3999
        })
4000
        .expect("the binary file is a blob");
4001
    let bp = a.store().path_for(&blob);
4002
    let blob_bytes = fs::read(&bp).unwrap();
4003
    fs::remove_file(&bp).unwrap();
4004
    let rep = a.fsck().unwrap();
4005
    assert!(
4006
        rep.problems
4007
            .iter()
4008
            .any(|p| p.object == Some(blob) && p.what.contains("blob missing")),
4009
        "{rep:?}"
4010
    );
4011
    fs::write(&bp, &blob_bytes).unwrap();
4012
4013
    // A broken op log head is reported, not a crash.
4014
    let head = root.join("a/.oxy/ops/head");
4015
    let saved = fs::read(&head).unwrap();
4016
    fs::write(&head, b"not a hash").unwrap();
4017
    let rep = a.fsck().unwrap();
4018
    assert!(
4019
        rep.problems.iter().any(|p| p.what.contains("ops/head")),
4020
        "{rep:?}"
4021
    );
4022
    fs::write(&head, saved).unwrap();
4023
    assert_eq!(a.fsck().unwrap().problems, vec![]);
4024
}
4025
4026
/// Copy a directory tree (for restoring a pristine repository).
4027
fn copy_tree(from: &Path, to: &Path) {
4028
    fs::create_dir_all(to).unwrap();
4029
    for e in fs::read_dir(from).unwrap() {
4030
        let e = e.unwrap();
4031
        let target = to.join(e.file_name());
4032
        if e.file_type().unwrap().is_dir() {
4033
            copy_tree(&e.path(), &target);
4034
        } else {
4035
            fs::copy(e.path(), &target).unwrap();
4036
        }
4037
    }
4038
}
4039
4040
/// Spec §13.6: stop `commit` and `push` at every durable step, as a crash
4041
/// would, and check that both repositories still open, pass `fsck`, and
4042
/// accept the same operation again.
4043
#[test]
4044
fn crash_at_every_step_of_commit_and_push_leaves_sound_repositories() {
4045
    use crate::durable::failpoint;
4046
    hermetic();
4047
    let dir = tempfile::tempdir().unwrap();
4048
    let pristine = dir.path().join("pristine");
4049
    let origin_path = pristine.join("origin");
4050
    Repo::init(&origin_path).unwrap();
4051
    let mut a = Repo::clone(&origin_path.to_string_lossy(), &pristine.join("a"))
4052
        .unwrap()
4053
        .with_home(dir.path().join("home"));
4054
    a.create_identity("Ada", "[email protected]", IdentityScope::Repo)
4055
        .unwrap();
4056
    write(&pristine.join("a"), "f.txt", b"one\n");
4057
    a.commit("first", &[]).unwrap();
4058
    assert!(a.push("origin", false).unwrap()[0].ok);
4059
    drop(a);
4060
4061
    type Op = fn(&Repo) -> Result<()>;
4062
    let edit_and_commit: Op = |r| {
4063
        write(r.root(), "f.txt", b"one\ntwo\n");
4064
        write(r.root(), "big.bin", &vec![7u8; 300_000]);
4065
        r.commit("second", &[]).map(|_| ())
4066
    };
4067
    let push: Op = |r| {
4068
        let res = r.push("origin", false)?;
4069
        if res.iter().all(|x| x.ok) {
4070
            Ok(())
4071
        } else {
4072
            Err(RepoError::Msg(format!("{res:?}")))
4073
        }
4074
    };
4075
4076
    for (name, prepare, op) in [
4077
        ("commit", None, edit_and_commit),
4078
        ("push", Some(edit_and_commit), push),
4079
    ] {
4080
        let mut steps = 0;
4081
        for n in 1.. {
4082
            let run = dir.path().join(format!("{name}-{n}"));
4083
            copy_tree(&pristine, &run);
4084
            // Clones record their remote by path; point it at this copy.
4085
            let open = |p: &Path| {
4086
                let mut r = Repo::open(p).unwrap().with_home(dir.path().join("home"));
4087
                r.config
4088
                    .set("remote.origin.url", &run.join("origin").to_string_lossy())
4089
                    .unwrap();
4090
                r.save_config().unwrap();
4091
                r
4092
            };
4093
            let a = open(&run.join("a"));
4094
            if let Some(prep) = prepare {
4095
                prep(&a).unwrap();
4096
            }
4097
            failpoint::crash_after(n);
4098
            let outcome = op(&a);
4099
            let crashed = failpoint::disarm();
4100
            drop(a);
4101
            if !crashed {
4102
                outcome.unwrap_or_else(|e| panic!("{name} failed without a crash: {e}"));
4103
                steps = n - 1;
4104
                break;
4105
            }
4106
            assert!(
4107
                outcome.is_err(),
4108
                "{name}: a crash at step {n} was swallowed"
4109
            );
4110
            for repo in ["a", "origin"] {
4111
                let r = Repo::open(&run.join(repo)).unwrap_or_else(|e| {
4112
                    panic!("{name} crash at step {n}: {repo} no longer opens: {e}")
4113
                });
4114
                let rep = r.fsck().unwrap();
4115
                assert_eq!(
4116
                    rep.errors(),
4117
                    0,
4118
                    "{name} crash at step {n}: {repo} fails fsck: {:?}",
4119
                    rep.problems
4120
                );
4121
            }
4122
            // The interrupted operation can simply be run again.
4123
            let a = open(&run.join("a"));
4124
            // A crash after the commit point leaves the commit done.
4125
            let landed = a
4126
                .bookmark_heads()
4127
                .unwrap()
4128
                .iter()
4129
                .any(|h| a.store().get_change(h).unwrap().message == "second");
4130
            let again = match (name, landed) {
4131
                ("commit", true) => Ok(()),
4132
                ("commit", false) => a.commit("second", &[]).map(|_| ()),
4133
                _ => op(&a),
4134
            };
4135
            again.unwrap_or_else(|e| panic!("{name} crash at step {n}: retry failed: {e}"));
4136
            assert_eq!(a.fsck().unwrap().errors(), 0);
4137
            fs::remove_dir_all(&run).unwrap();
4138
        }
4139
        assert!(steps >= 3, "{name} has only {steps} durable steps?");
4140
    }
4141
}
4142
4143
/// Spec §12.1: commands in two workspaces of one repository, and pushes,
4144
/// running at the same time lose nothing: every commit ends up on the
4145
/// bookmark, locally and on the remote, and the repository passes fsck.
4146
#[test]
4147
fn concurrent_commits_in_two_workspaces_lose_nothing() {
4148
    hermetic();
4149
    let dir = tempfile::tempdir().unwrap();
4150
    let root = dir.path();
4151
    let origin = root.join("origin");
4152
    Repo::init_bare_unbound(&origin).unwrap();
4153
    let main = root.join("main");
4154
    let mut repo = Repo::init(&main).unwrap();
4155
    repo.config
4156
        .set("remote.origin.url", &origin.to_string_lossy())
4157
        .unwrap();
4158
    repo.save_config().unwrap();
4159
    write(&main, "seed.txt", b"seed\n");
4160
    repo.commit("seed", &[]).unwrap();
4161
    let second = root.join("second");
4162
    repo.workspace_add(&second, None).unwrap();
4163
    drop(repo);
4164
4165
    const EACH: usize = 15;
4166
    std::thread::scope(|s| {
4167
        for (tag, dir, push) in [("a", main.clone(), true), ("b", second.clone(), false)] {
4168
            s.spawn(move || {
4169
                let r = Repo::open(&dir).unwrap();
4170
                for i in 0..EACH {
4171
                    write(
4172
                        &dir,
4173
                        &format!("{tag}-{i}.txt"),
4174
                        format!("{tag} {i}\n").as_bytes(),
4175
                    );
4176
                    r.commit(&format!("{tag} {i}"), &[]).unwrap();
4177
                    if push && i % 5 == 4 {
4178
                        // A push may be refused while the other workspace moves the bookmark; nothing may be lost either way.
4179
                        let _ = r.push("origin", false);
4180
                    }
4181
                }
4182
            });
4183
        }
4184
    });
4185
4186
    let repo = Repo::open(&main).unwrap();
4187
    let heads = repo.bookmark_heads().unwrap();
4188
    let state = repo.load_state(&heads).unwrap();
4189
    let messages: BTreeSet<String> = state.changes().map(|(_, m)| m.message.clone()).collect();
4190
    for tag in ["a", "b"] {
4191
        for i in 0..EACH {
4192
            assert!(
4193
                messages.contains(&format!("{tag} {i}")),
4194
                "lost commit {tag} {i}; have {messages:?}"
4195
            );
4196
        }
4197
    }
4198
    let rep = repo.fsck().unwrap();
4199
    assert_eq!(rep.errors(), 0, "{:?}", rep.problems);
4200
    assert!(repo.push("origin", false).unwrap().iter().all(|r| r.ok));
4201
    let hosted = Repo::open(&origin).unwrap();
4202
    let hosted_heads = hosted.bookmark_heads().unwrap();
4203
    assert_eq!(
4204
        hosted.load_state(&hosted_heads).unwrap().len(),
4205
        state.len(),
4206
        "the remote has every commit"
4207
    );
4208
}
4209
4210
/// Two operations recorded from the same parent (what two processes do
4211
/// when they race) are merged: both bookmarks' heads survive, and a
4212
/// change made on one side only is kept.
4213
#[test]
4214
fn operations_from_the_same_parent_are_merged() {
4215
    hermetic();
4216
    let dir = tempfile::tempdir().unwrap();
4217
    let root = dir.path();
4218
    let repo = Repo::init(root).unwrap();
4219
    write(root, "a.txt", b"a\n");
4220
    let a = repo.commit("a", &[]).unwrap();
4221
    write(root, "b.txt", b"b\n");
4222
    let b = repo.commit("b", &[]).unwrap();
4223
    let (x, op) = repo.head_op().unwrap();
4224
    let state = |heads: Vec<ChangeHash>| repo.store().put_state(&StateObject::new(heads)).unwrap();
4225
4226
    // Side one moves main to just `a` and adds a bookmark; side two moves main to just `b`.
4227
    let mut one = op.view.clone();
4228
    one.bookmarks.insert("main".into(), state(vec![a]));
4229
    one.bookmarks.insert("topic".into(), state(vec![a]));
4230
    let mut two = op.view.clone();
4231
    two.bookmarks.insert("main".into(), state(vec![b]));
4232
    repo.record_op(&[x], "one", one).unwrap();
4233
    let merged = repo.record_op(&[x], "two", two).unwrap();
4234
4235
    let (head, op) = repo.head_op().unwrap();
4236
    assert_eq!(head, merged);
4237
    assert_eq!(op.parents.len(), 2, "a merge of the two operations");
4238
    assert!(op.command.contains("merged with a concurrent operation"));
4239
    let mut main = repo
4240
        .store()
4241
        .get_state(&op.view.bookmarks["main"])
4242
        .unwrap()
4243
        .heads;
4244
    main.sort();
4245
    let mut want = vec![a, b];
4246
    want.sort();
4247
    assert_eq!(main, want, "both sides' heads are kept");
4248
    assert!(
4249
        op.view.bookmarks.contains_key("topic"),
4250
        "a one-sided change survives"
4251
    );
4252
    assert_eq!(repo.fsck().unwrap().errors(), 0);
4253
}
4254
4255
#[test]
4256
fn failed_requests_come_with_a_next_step() {
4257
    use crate::protocol::hint_for;
4258
    assert!(hint_for("https://h/x/oxy/v1/push: HTTP 401: bad token")
4259
        .unwrap()
4260
        .contains("token"));
4261
    assert!(hint_for("…: HTTP 403: forbidden")
4262
        .unwrap()
4263
        .contains("repo:write"));
4264
    assert!(hint_for("…: HTTP 404: no such repository")
4265
        .unwrap()
4266
        .contains("owner and repository name"));
4267
    assert!(hint_for("invalid peer certificate: UnknownIssuer")
4268
        .unwrap()
4269
        .contains("oxyhub-ca.pem"));
4270
    assert!(hint_for("Connect error: Connection refused (os error 111)")
4271
        .unwrap()
4272
        .contains("running"));
4273
    assert!(hint_for("Dns Failed: failed to lookup address information")
4274
        .unwrap()
4275
        .contains("resolve"));
4276
    assert_eq!(hint_for("something else entirely"), None);
4277
}
4278
4279
#[test]
4280
fn doctor_names_problems_and_what_to_do() {
4281
    hermetic();
4282
    let dir = tempfile::tempdir().unwrap();
4283
    let root = dir.path();
4284
    let origin = root.join("origin");
4285
    Repo::init_bare_unbound(&origin).unwrap();
4286
    let mut repo = Repo::init(&root.join("r"))
4287
        .unwrap()
4288
        .with_home(root.join("home"));
4289
    let find = |r: &DoctorReport, area: &str, h: Health| {
4290
        r.checks
4291
            .iter()
4292
            .find(|c| c.area == area && c.health == h)
4293
            .cloned()
4294
    };
4295
4296
    let r = repo.doctor(true);
4297
    assert!(find(&r, "identity", Health::Warn)
4298
        .unwrap()
4299
        .hint
4300
        .unwrap()
4301
        .contains("oxy identity create"));
4302
    assert!(find(&r, "repository", Health::Ok).is_some());
4303
4304
    repo.create_identity("Ada", "[email protected]", IdentityScope::Repo)
4305
        .unwrap();
4306
    repo.config.set("author.name", "Ada").unwrap();
4307
    repo.config.set("author.email", "[email protected]").unwrap();
4308
    repo.config
4309
        .set("remote.origin.url", &origin.to_string_lossy())
4310
        .unwrap();
4311
    repo.config
4312
        .set("remote.down.url", "http://127.0.0.1:9/a/b")
4313
        .unwrap();
4314
    repo.config.set("remote.down.token", "t").unwrap();
4315
    repo.config
4316
        .set("remote.badca.url", "https://example.invalid/a/b")
4317
        .unwrap();
4318
    repo.config
4319
        .set(
4320
            "remote.badca.ca",
4321
            &root.join("missing.pem").to_string_lossy(),
4322
        )
4323
        .unwrap();
4324
    repo.save_config().unwrap();
4325
4326
    let r = repo.doctor(true);
4327
    assert!(find(&r, "identity", Health::Ok).is_some(), "{r:?}");
4328
    assert!(find(&r, "author", Health::Ok).is_some(), "{r:?}");
4329
    assert!(find(&r, "remote origin", Health::Ok)
4330
        .unwrap()
4331
        .message
4332
        .contains("first push binds it"));
4333
    let down = find(&r, "remote down", Health::Fail).unwrap();
4334
    assert!(
4335
        down.hint.as_deref().unwrap_or("").contains("running"),
4336
        "{down:?}"
4337
    );
4338
    let badca = find(&r, "remote badca", Health::Fail).unwrap();
4339
    assert!(
4340
        badca.hint.unwrap().contains("remote.badca.ca"),
4341
        "the remote's own name is in the hint"
4342
    );
4343
    assert_eq!(r.worst(), Health::Fail);
4344
4345
    // Offline, nothing is contacted.
4346
    let r = repo.doctor(false);
4347
    assert!(find(&r, "remote down", Health::Fail).is_none());
4348
    assert!(find(&r, "remote down", Health::Ok)
4349
        .unwrap()
4350
        .message
4351
        .contains("not contacted"));
4352
}
4353
4354
/// Spec §8.1: deleting a line depends on whoever inserted the lines right
4355
/// after it. Inserting after `b` and then deleting `b`, one commit after
4356
/// the other, must not leave a delete/insert conflict.
4357
#[test]
4358
fn deleting_a_line_after_an_insertion_below_it_is_not_a_conflict() {
4359
    hermetic();
4360
    let dir = tempfile::tempdir().unwrap();
4361
    let root = dir.path();
4362
    let repo = Repo::init(root).unwrap();
4363
    write(root, "f", b"a\nb\nc\n");
4364
    repo.commit("base", &[]).unwrap();
4365
    write(root, "f", b"a\nb\nx\nc\n");
4366
    let insert = repo.commit("insert x after b", &[]).unwrap();
4367
    write(root, "f", b"a\nx\nc\n");
4368
    let delete = repo.commit("delete b", &[]).unwrap();
4369
    assert!(
4370
        repo.store()
4371
            .get_change(&delete)
4372
            .unwrap()
4373
            .deps
4374
            .contains(&insert),
4375
        "the deletion depends on the insertion below the deleted line"
4376
    );
4377
    let heads = repo.bookmark_heads().unwrap();
4378
    assert_eq!(heads, vec![delete]);
4379
    let snap = repo.load_state(&heads).unwrap().materialize();
4380
    assert!(!snap.is_conflicted());
4381
    assert!(
4382
        matches!(&snap.files["f"].content, FileContent::Text { bytes, .. } if bytes == b"a\nx\nc\n")
4383
    );
4384
}
4385
4386
/// Spec §9.3: a binary file reverted to an earlier blob keeps it, and each
4387
/// replacement depends on the change that set the blob it replaces.
4388
#[test]
4389
fn a_binary_file_reverted_to_an_earlier_blob_keeps_it() {
4390
    hermetic();
4391
    let dir = tempfile::tempdir().unwrap();
4392
    let root = dir.path();
4393
    let repo = Repo::init(root).unwrap();
4394
    write(root, "bin", b"\0A");
4395
    let v1 = repo.commit("v1", &[]).unwrap();
4396
    write(root, "bin", b"\0B");
4397
    let v2 = repo.commit("v2", &[]).unwrap();
4398
    assert!(repo.store().get_change(&v2).unwrap().deps.contains(&v1));
4399
    write(root, "bin", b"\0A");
4400
    let v3 = repo.commit("back to A", &[]).unwrap();
4401
    assert!(repo.store().get_change(&v3).unwrap().deps.contains(&v2));
4402
    assert_eq!(repo.bookmark_heads().unwrap(), vec![v3]);
4403
    let state = repo.load_state(&[v3]).unwrap();
4404
    let snap = state.materialize();
4405
    let FileContent::Opaque { blobs } = &snap.files["bin"].content else {
4406
        panic!("opaque")
4407
    };
4408
    assert_eq!(blobs.len(), 1, "one live blob, not none and not two");
4409
    assert_eq!(repo.read_blob(&blobs[0]).unwrap(), b"\0A");
4410
}
4411
4412
/// Spec §23: a binary file changed on two branches and merged in Git to
4413
/// one side's version comes back as that version at the merge, and the
4414
/// import verifies commit by commit.
4415
#[test]
4416
fn git_import_resolves_a_binary_merged_in_git_and_verifies() {
4417
    hermetic();
4418
    if std::process::Command::new("git")
4419
        .arg("--version")
4420
        .output()
4421
        .is_err()
4422
    {
4423
        eprintln!("git not installed; skipping");
4424
        return;
4425
    }
4426
    let dir = tempfile::tempdir().unwrap();
4427
    let root = dir.path();
4428
    let g = root.join("src.git");
4429
    fs::create_dir_all(&g).unwrap();
4430
    let git = |args: &[&str]| -> String {
4431
        let out = std::process::Command::new("git")
4432
            .arg("-C")
4433
            .arg(&g)
4434
            .args([
4435
                "-c",
4436
                "user.name=Grace",
4437
                "-c",
4438
                "[email protected]",
4439
                "-c",
4440
                "commit.gpgsign=false",
4441
            ])
4442
            .args(args)
4443
            .output()
4444
            .unwrap();
4445
        assert!(
4446
            out.status.success(),
4447
            "git {args:?}: {}",
4448
            String::from_utf8_lossy(&out.stderr)
4449
        );
4450
        String::from_utf8_lossy(&out.stdout).trim().to_string()
4451
    };
4452
    git(&["init", "-q", "-b", "main"]);
4453
    write(&g, "logo.bin", b"\0base");
4454
    write(&g, "notes.txt", b"a\nb\nc\n");
4455
    git(&["add", "."]);
4456
    git(&["commit", "-qm", "base"]);
4457
    git(&["checkout", "-qb", "side"]);
4458
    write(&g, "logo.bin", b"\0side");
4459
    write(&g, "notes.txt", b"a\nb\nx\nc\n");
4460
    git(&["commit", "-qam", "side"]);
4461
    git(&["checkout", "-q", "main"]);
4462
    write(&g, "logo.bin", b"\0main");
4463
    git(&["commit", "-qam", "main"]);
4464
    // Git cannot merge the binary; the merge takes main's and keeps side's text.
4465
    let _ = std::process::Command::new("git")
4466
        .arg("-C")
4467
        .arg(&g)
4468
        .args([
4469
            "-c",
4470
            "user.name=G",
4471
            "-c",
4472
            "user.email=g@e",
4473
            "merge",
4474
            "-q",
4475
            "side",
4476
        ])
4477
        .output();
4478
    write(&g, "logo.bin", b"\0main");
4479
    git(&["add", "."]);
4480
    git(&["commit", "-qm", "merge side"]);
4481
    // Then a revert of the binary to its first version.
4482
    write(&g, "logo.bin", b"\0base");
4483
    git(&["commit", "-qam", "back to base"]);
4484
4485
    let repo = Repo::init(&root.join("o")).unwrap();
4486
    let rep = repo.import_git(&g, "main").unwrap();
4487
    assert_eq!(rep.merges, 1);
4488
    let v = repo.verify_git_import(&g, "main").unwrap();
4489
    assert!(v.mismatches.is_empty(), "{:?}", v.mismatches);
4490
    assert_eq!(v.commits, 5);
4491
    let snap = repo
4492
        .load_state(&repo.bookmark_heads().unwrap())
4493
        .unwrap()
4494
        .materialize();
4495
    assert!(!snap.is_conflicted());
4496
    let FileContent::Opaque { blobs } = &snap.files["logo.bin"].content else {
4497
        panic!("opaque")
4498
    };
4499
    assert_eq!(repo.read_blob(&blobs[0]).unwrap(), b"\0base");
4500
}
4501
4502
/// Spec §7.7 on a file system without executable bits or symlinks: the
4503
/// recorded bit is kept, and a symlink checked out as a plain file holding
4504
/// its target is still that symlink.
4505
#[cfg(unix)]
4506
#[test]
4507
fn windows_file_systems_keep_exec_bits_and_symlinks() {
4508
    use crate::portable::Platform;
4509
    use std::os::unix::fs::PermissionsExt;
4510
    hermetic();
4511
    let dir = tempfile::tempdir().unwrap();
4512
    let root = dir.path();
4513
    let repo = Repo::init(root).unwrap();
4514
    write(root, "run.sh", b"#!/bin/sh\n");
4515
    fs::set_permissions(root.join("run.sh"), fs::Permissions::from_mode(0o755)).unwrap();
4516
    std::os::unix::fs::symlink("run.sh", root.join("link")).unwrap();
4517
    repo.commit("script and link", &[]).unwrap();
4518
    drop(repo);
4519
4520
    // What checking out on Windows leaves: no exec bit, the link as a file.
4521
    fs::set_permissions(root.join("run.sh"), fs::Permissions::from_mode(0o644)).unwrap();
4522
    fs::remove_file(root.join("link")).unwrap();
4523
    write(root, "link", b"run.sh");
4524
    let win = Repo::open(root).unwrap().with_platform(Platform::windows());
4525
    let s = win.snapshot("oxy status").unwrap();
4526
    assert!(
4527
        s.statuses.is_empty(),
4528
        "nothing changed on Windows: {:?}",
4529
        statuses(&s)
4530
    );
4531
    // Editing the file is a content change, not a mode change; retargeting the link keeps it a link.
4532
    write(root, "run.sh", b"#!/bin/sh\necho hi\n");
4533
    write(root, "link", b"other");
4534
    let h = win.commit("edit on Windows", &[]).unwrap();
4535
    let snap = win.load_state(&[h]).unwrap().materialize();
4536
    assert!(snap.files["run.sh"].mode.exec, "the exec bit survives");
4537
    assert_eq!(snap.files["link"].kind, NodeKind::Symlink);
4538
    // The same working copy read as Linux sees the lost bit and the plain file.
4539
    let linux = Repo::open(root).unwrap();
4540
    assert!(!linux.snapshot("oxy status").unwrap().statuses.is_empty());
4541
}
4542
4543
/// Paths that collide on case-insensitive or Windows file systems are
4544
/// named at checkout there, and by doctor everywhere.
4545
#[test]
4546
fn paths_other_platforms_cannot_hold_are_reported() {
4547
    use crate::portable::Platform;
4548
    hermetic();
4549
    let dir = tempfile::tempdir().unwrap();
4550
    let root = dir.path();
4551
    let repo = Repo::init(root).unwrap();
4552
    write(root, "README.md", b"a\n");
4553
    write(root, "readme.md", b"b\n");
4554
    write(root, "src/aux.c", b"int x;\n");
4555
    let h = repo.commit("unportable", &[]).unwrap();
4556
    let r = repo.doctor(false);
4557
    let port = r.checks.iter().find(|c| c.area == "portability").unwrap();
4558
    assert_eq!(port.health, Health::Warn);
4559
    assert!(
4560
        port.message.contains("differ only in case") && port.message.contains("aux.c"),
4561
        "{}",
4562
        port.message
4563
    );
4564
    let mac = Repo::open(root).unwrap().with_platform(Platform::macos());
4565
    let rep = mac.checkout(&[h], true, "oxy checkout").unwrap();
4566
    assert!(
4567
        rep.notes
4568
            .iter()
4569
            .any(|n| n.contains("README.md and readme.md")),
4570
        "{:?}",
4571
        rep.notes
4572
    );
4573
    assert!(
4574
        !rep.notes.iter().any(|n| n.contains("aux.c")),
4575
        "macOS allows aux.c"
4576
    );
4577
}
4578
4579
#[test]
4580
fn history_and_blame_of_a_loaded_state_match_the_full_walk() {
4581
    hermetic();
4582
    let dir = tempfile::tempdir().unwrap();
4583
    let repo = Repo::init(dir.path()).unwrap();
4584
    write(dir.path(), "a.txt", b"one\n");
4585
    write(dir.path(), "other.txt", b"x\n");
4586
    write(dir.path(), "bin.dat", &[0u8, 1, 2, 0, 255]);
4587
    repo.snapshot("t").unwrap();
4588
    let c1 = repo.commit("first", &[]).unwrap();
4589
    write(dir.path(), "other.txt", b"y\n");
4590
    repo.snapshot("t").unwrap();
4591
    repo.commit("other only", &[]).unwrap();
4592
    write(dir.path(), "a.txt", b"one\ntwo\n");
4593
    repo.snapshot("t").unwrap();
4594
    let c3 = repo.commit("second line", &[]).unwrap();
4595
    write(dir.path(), "other.txt", b"z\n");
4596
    repo.snapshot("t").unwrap();
4597
    repo.commit("other again", &[]).unwrap();
4598
4599
    let heads = repo.bookmark_heads().unwrap();
4600
    let state = repo.load_state(&heads).unwrap();
4601
    let full: Vec<ChangeHash> = repo
4602
        .log_for_path_in("a.txt", &heads)
4603
        .unwrap()
4604
        .iter()
4605
        .map(|e| e.hash)
4606
        .collect();
4607
    assert_eq!(
4608
        full,
4609
        vec![c3, c1],
4610
        "newest first, only changes touching the path"
4611
    );
4612
    let newest: Vec<ChangeHash> = repo
4613
        .log_for_path_of(&state, "a.txt", Some(1))
4614
        .unwrap()
4615
        .iter()
4616
        .map(|e| e.hash)
4617
        .collect();
4618
    assert_eq!(newest, vec![c3], "stops at the first");
4619
    assert_eq!(
4620
        repo.log_for_path_of(&state, "a.txt", None).unwrap().len(),
4621
        2
4622
    );
4623
    assert!(repo
4624
        .log_for_path_of(&state, "missing.txt", Some(1))
4625
        .is_err());
4626
    assert_eq!(
4627
        repo.log_state(&heads).unwrap().len(),
4628
        repo.log_of(&state).len()
4629
    );
4630
4631
    let tree = state.tree().view();
4632
    let via_state = repo.blame_of(&state, &tree, "a.txt").unwrap();
4633
    let via_heads = repo.blame_in("a.txt", &heads).unwrap();
4634
    assert_eq!(
4635
        via_state
4636
            .iter()
4637
            .map(|l| (l.hash, l.text.clone()))
4638
            .collect::<Vec<_>>(),
4639
        via_heads
4640
            .iter()
4641
            .map(|l| (l.hash, l.text.clone()))
4642
            .collect::<Vec<_>>()
4643
    );
4644
    assert_eq!(
4645
        via_state.iter().map(|l| l.hash).collect::<Vec<_>>(),
4646
        vec![c1, c3]
4647
    );
4648
    assert!(repo.blame_of(&state, &tree, "missing.txt").is_err());
4649
}
4650
4651
/// A text file whose stat matches the manifest and whose recorded hash is
4652
/// the base's content is taken from the base without reading it; anything
4653
/// else is read, so no edit is missed (spec §12.3).
4654
#[cfg(unix)]
4655
#[test]
4656
fn stat_cache_takes_unchanged_text_from_the_base_and_misses_no_edit() {
4657
    use std::os::unix::fs::PermissionsExt;
4658
    hermetic();
4659
    let dir = tempfile::tempdir().unwrap();
4660
    let root = dir.path();
4661
    let repo = Repo::init(root).unwrap().with_home(root.join("home"));
4662
    write(root, "a.txt", b"one\ntwo\n");
4663
    write(root, "b.txt", b"bee\n");
4664
    repo.commit("base", &[]).unwrap();
4665
    let age = |p: &str| {
4666
        let old = std::time::SystemTime::now() - std::time::Duration::from_secs(30);
4667
        fs::File::options()
4668
            .write(true)
4669
            .open(root.join(p))
4670
            .unwrap()
4671
            .set_modified(old)
4672
            .unwrap();
4673
    };
4674
    age("a.txt");
4675
    age("b.txt");
4676
    assert!(
4677
        !repo.snapshot("status").unwrap().changed,
4678
        "records the aged stat"
4679
    );
4680
4681
    // Clean and equal to the base: not read at all.
4682
    fs::set_permissions(root.join("a.txt"), fs::Permissions::from_mode(0o000)).unwrap();
4683
    let snap = repo.snapshot("status").unwrap();
4684
    assert!(
4685
        !snap.changed && snap.statuses.is_empty(),
4686
        "{:?}",
4687
        snap.statuses
4688
    );
4689
    fs::set_permissions(root.join("a.txt"), fs::Permissions::from_mode(0o644)).unwrap();
4690
4691
    // An uncommitted edit that is older than the manifest: stat-clean, but
4692
    // its hash is not the base's, so it is read and stays visible.
4693
    write(root, "b.txt", b"bee edited\n");
4694
    age("b.txt");
4695
    let first = repo.snapshot("status").unwrap();
4696
    assert_eq!(
4697
        statuses(&first),
4698
        vec![("b.txt".to_string(), ChangeStatus::Modified)]
4699
    );
4700
    let again = repo.snapshot("status").unwrap();
4701
    assert_eq!(
4702
        statuses(&again),
4703
        vec![("b.txt".to_string(), ChangeStatus::Modified)],
4704
        "still seen once stat-clean"
4705
    );
4706
    assert!(!again.changed, "and the working copy hashes the same");
4707
    fs::set_permissions(root.join("b.txt"), fs::Permissions::from_mode(0o000)).unwrap();
4708
    assert!(
4709
        repo.snapshot("status").is_err(),
4710
        "an edited file must be read, never taken from the base"
4711
    );
4712
    fs::set_permissions(root.join("b.txt"), fs::Permissions::from_mode(0o644)).unwrap();
4713
4714
    // A same-size edit made just now is racy and read.
4715
    write(root, "a.txt", b"one\nTWO\n");
4716
    assert_eq!(
4717
        statuses(&repo.snapshot("status").unwrap()),
4718
        vec![
4719
            ("a.txt".to_string(), ChangeStatus::Modified),
4720
            ("b.txt".to_string(), ChangeStatus::Modified)
4721
        ]
4722
    );
4723
    // Committing makes the edits the base: both are clean and served from it again.
4724
    repo.commit("edits", &[]).unwrap();
4725
    age("a.txt");
4726
    age("b.txt");
4727
    assert!(repo.snapshot("status").unwrap().statuses.is_empty());
4728
    fs::set_permissions(root.join("a.txt"), fs::Permissions::from_mode(0o000)).unwrap();
4729
    fs::set_permissions(root.join("b.txt"), fs::Permissions::from_mode(0o000)).unwrap();
4730
    let snap = repo.snapshot("status").unwrap();
4731
    assert!(!snap.changed && snap.statuses.is_empty());
4732
    fs::set_permissions(root.join("a.txt"), fs::Permissions::from_mode(0o644)).unwrap();
4733
    fs::set_permissions(root.join("b.txt"), fs::Permissions::from_mode(0o644)).unwrap();
4734
}
4735
4736
/// Version 2 checkpoints (spec §11): a large file's graph is a blob of its
4737
/// own, kept by gc, checked by fsck, shared by the next checkpoint when the
4738
/// file is unchanged, and loading through the checkpoint equals a full load.
4739
#[test]
4740
fn checkpoints_keep_large_graphs_as_blobs_of_their_own() {
4741
    hermetic();
4742
    let dir = tempfile::tempdir().unwrap();
4743
    let root = dir.path();
4744
    let repo = Repo::init(root).unwrap().with_home(root.join("home"));
4745
    let long: String = (0..300)
4746
        .map(|i| format!("line {i} of a long file\n"))
4747
        .collect();
4748
    write(root, "long.txt", long.as_bytes());
4749
    write(root, "short.txt", b"short\n");
4750
    repo.commit("base", &[]).unwrap();
4751
    let (r1, _, _) = repo.checkpoint().unwrap();
4752
    let cp1 = crate::objects::Checkpoint::decode(
4753
        &repo.store().get_typed(&r1, ObjectType::Checkpoint).unwrap(),
4754
    )
4755
    .unwrap();
4756
    let graphs1 = repo.checkpoint_graph_blobs(&cp1).unwrap();
4757
    assert_eq!(graphs1.len(), 1, "only the long file's graph is a blob");
4758
4759
    // gc keeps the graph blob; fsck finds the checkpoint sound.
4760
    repo.gc(true).unwrap();
4761
    assert!(repo.store().has(&graphs1[0]));
4762
    let report = repo.fsck().unwrap();
4763
    assert_eq!(report.errors(), 0, "{:?}", report.problems);
4764
4765
    // Loading through the checkpoint equals a full load.
4766
    write(root, "short.txt", b"short, edited\n");
4767
    repo.commit("edit the short file", &[]).unwrap();
4768
    let heads = repo.bookmark_heads().unwrap();
4769
    let fast = repo.load_state(&heads).unwrap();
4770
    let full = repo.load_state_full(&heads).unwrap();
4771
    assert_eq!(fast.checkpoint_payload(), full.checkpoint_payload());
4772
4773
    // The next checkpoint shares the unchanged long file's graph.
4774
    let (r2, _, _) = repo.checkpoint().unwrap();
4775
    let cp2 = crate::objects::Checkpoint::decode(
4776
        &repo.store().get_typed(&r2, ObjectType::Checkpoint).unwrap(),
4777
    )
4778
    .unwrap();
4779
    assert_eq!(repo.checkpoint_graph_blobs(&cp2).unwrap(), graphs1);
4780
4781
    // A shallow clone's bundle carries the graph blob with the checkpoint.
4782
    let bundle = repo.checkpoint_bundle_for(&heads).unwrap();
4783
    assert!(bundle.objects.iter().any(|(t, body)| *t == ObjectType::Blob
4784
        && crate::hash::hash_object(ObjectType::Blob, body) == graphs1[0]));
4785
4786
    // A version 1 checkpoint written by an older oxy still loads.
4787
    let state = repo.load_state_full(&heads).unwrap();
4788
    let old = repo.store_blob(&state.checkpoint_payload()).unwrap();
4789
    let cp_old = crate::objects::Checkpoint {
4790
        heads: cp2.heads.clone(),
4791
        count: cp2.count,
4792
        payload: old,
4793
    };
4794
    let r_old = repo
4795
        .store()
4796
        .put(ObjectType::Checkpoint, &cp_old.encode())
4797
        .unwrap();
4798
    repo.install_checkpoint("main", &r_old).unwrap();
4799
    assert_eq!(
4800
        repo.load_state(&heads).unwrap().checkpoint_payload(),
4801
        full.checkpoint_payload()
4802
    );
4803
    assert_eq!(repo.fsck().unwrap().errors(), 0);
4804
4805
    // A lost graph blob fails the load loudly rather than dropping the
4806
    // file, and fsck reports it (a fresh repository, objects still loose).
4807
    let dir2 = tempfile::tempdir().unwrap();
4808
    let root2 = dir2.path();
4809
    let repo2 = Repo::init(root2).unwrap().with_home(root2.join("home"));
4810
    write(root2, "long.txt", long.as_bytes());
4811
    repo2.commit("base", &[]).unwrap();
4812
    let (r, _, _) = repo2.checkpoint().unwrap();
4813
    let cp = crate::objects::Checkpoint::decode(
4814
        &repo2.store().get_typed(&r, ObjectType::Checkpoint).unwrap(),
4815
    )
4816
    .unwrap();
4817
    let graph = repo2.checkpoint_graph_blobs(&cp).unwrap()[0];
4818
    fs::remove_file(repo2.store().path_for(&graph)).unwrap();
4819
    assert!(repo2.load_state(&repo2.bookmark_heads().unwrap()).is_err());
4820
    assert!(repo2.fsck().unwrap().errors() > 0, "fsck reports it");
4821
}
4822
4823
/// A new repository has not stored the user's identity yet (that happens
4824
/// at the first signed change); looking it up falls back to the key
4825
/// directory, and a file there that does not hash to the key is refused.
4826
#[test]
4827
fn identity_is_found_in_the_key_directory_for_a_new_repository() {
4828
    hermetic();
4829
    let dir = tempfile::tempdir().unwrap();
4830
    let home = dir.path().join("home");
4831
    let mut first = Repo::init(&dir.path().join("a"))
4832
        .unwrap()
4833
        .with_home(home.clone());
4834
    let (key, _) = first
4835
        .create_identity("Ada", "[email protected]", IdentityScope::User)
4836
        .unwrap();
4837
    let fresh = Repo::init(&dir.path().join("b"))
4838
        .unwrap()
4839
        .with_home(home.clone());
4840
    assert!(!fresh.store().has(&key), "nothing stored yet");
4841
    let id = fresh.identity(&key).unwrap();
4842
    assert_eq!((id.name.as_str(), id.hash()), ("Ada", key));
4843
    // A key file that is not this identity is an error, not a wrong answer.
4844
    let keys = fresh.keys_dir.clone();
4845
    let (other, _) = first
4846
        .create_identity("Bob", "[email protected]", IdentityScope::User)
4847
        .unwrap();
4848
    fs::copy(
4849
        keys.join(format!("{}.identity", other.to_hex())),
4850
        keys.join(format!("{}.identity", key.to_hex())),
4851
    )
4852
    .unwrap();
4853
    assert!(fresh
4854
        .identity(&key)
4855
        .unwrap_err()
4856
        .to_string()
4857
        .contains("does not hold identity"));
4858
}
4859
4860
/// Status snapshots (spec §12.3): a text file whose stat matches the
4861
/// manifest, and whose base graph key is the one the manifest recorded it
4862
/// equal to, is neither read nor rendered; any edit, and any change to the
4863
/// file's graph in the base, brings it back.
4864
#[cfg(unix)]
4865
#[test]
4866
fn status_snapshots_skip_files_unchanged_since_the_manifest() {
4867
    use std::os::unix::fs::PermissionsExt;
4868
    hermetic();
4869
    let dir = tempfile::tempdir().unwrap();
4870
    let root = dir.path();
4871
    let repo = Repo::init(root).unwrap().with_home(root.join("home"));
4872
    for (p, c) in [("a.txt", "one\n"), ("b.txt", "bee\n"), ("d/c.txt", "sea\n")] {
4873
        write(root, p, c.as_bytes());
4874
    }
4875
    repo.commit("base", &[]).unwrap();
4876
    let age = |p: &str| {
4877
        let old = std::time::SystemTime::now() - std::time::Duration::from_secs(30);
4878
        fs::File::options()
4879
            .write(true)
4880
            .open(root.join(p))
4881
            .unwrap()
4882
            .set_modified(old)
4883
            .unwrap();
4884
    };
4885
    let lock = |p: &str, mode: u32| {
4886
        fs::set_permissions(root.join(p), fs::Permissions::from_mode(mode)).unwrap()
4887
    };
4888
    for p in ["a.txt", "b.txt", "d/c.txt"] {
4889
        age(p);
4890
    }
4891
    assert!(repo.snapshot("status").unwrap().statuses.is_empty());
4892
    let (_, _, m) = repo.read_manifest().unwrap().unwrap();
4893
    assert!(
4894
        m.entries.values().all(|e| e.graph.is_some()),
4895
        "keys recorded"
4896
    );
4897
4898
    // Unreadable files prove they are not read; the status snapshot does
4899
    // not render them either, and its base lacks their graphs.
4900
    lock("a.txt", 0o000);
4901
    lock("b.txt", 0o000);
4902
    let snap = repo.snapshot_status("status").unwrap();
4903
    assert!(!snap.changed && snap.statuses.is_empty());
4904
    assert_eq!(
4905
        snap.base_snapshot
4906
            .unrendered
4907
            .iter()
4908
            .cloned()
4909
            .collect::<Vec<_>>(),
4910
        vec!["a.txt", "b.txt", "d/c.txt"]
4911
    );
4912
    assert!(!snap.base.is_full());
4913
    assert!(!snap.base_snapshot.is_conflicted());
4914
    // A full snapshot does not read them either, but renders everything.
4915
    let full = repo.snapshot("status").unwrap();
4916
    assert!(full.statuses.is_empty() && full.base.is_full());
4917
    assert!(full.base_snapshot.unrendered.is_empty());
4918
    assert!(matches!(&full.base_snapshot.files["a.txt"].content,
4919
        FileContent::Text { bytes, .. } if bytes == b"one\n"));
4920
4921
    // An edit is seen; the file is rendered, the others still are not.
4922
    write(root, "d/c.txt", b"sea edited\n");
4923
    let snap = repo.snapshot_status("status").unwrap();
4924
    assert_eq!(
4925
        statuses(&snap),
4926
        vec![("d/c.txt".to_string(), ChangeStatus::Modified)]
4927
    );
4928
    assert!(!snap.base_snapshot.unrendered.contains("d/c.txt"));
4929
    // So is a mode change of an unread file.
4930
    lock("b.txt", 0o100);
4931
    assert_eq!(
4932
        statuses(&repo.snapshot_status("status").unwrap()),
4933
        vec![
4934
            ("b.txt".to_string(), ChangeStatus::ModeChanged),
4935
            ("d/c.txt".to_string(), ChangeStatus::Modified)
4936
        ]
4937
    );
4938
    lock("b.txt", 0o000);
4939
4940
    // Committing c.txt changes its graph in the base, not a.txt's: a.txt
4941
    // stays unread, c.txt is read once and then skipped too.
4942
    repo.commit_selection("edit c", &[], &Selection::Paths(vec!["d/c.txt".into()]))
4943
        .unwrap();
4944
    age("d/c.txt");
4945
    let snap = repo.snapshot_status("status").unwrap();
4946
    assert!(snap.statuses.is_empty(), "{:?}", snap.statuses);
4947
    assert!(snap.base_snapshot.unrendered.contains("a.txt"));
4948
    lock("d/c.txt", 0o000);
4949
    let snap = repo.snapshot_status("status").unwrap();
4950
    assert!(snap.statuses.is_empty());
4951
    assert!(snap.base_snapshot.unrendered.contains("d/c.txt"));
4952
    for p in ["a.txt", "b.txt", "d/c.txt"] {
4953
        lock(p, 0o644);
4954
    }
4955
}
4956
4957
/// Attributes decide how a file compares with the base, so a changed
4958
/// `.oxyattributes` makes every text file be compared again.
4959
#[cfg(unix)]
4960
#[test]
4961
fn a_changed_attributes_file_disables_skipping_unchanged_files() {
4962
    hermetic();
4963
    let dir = tempfile::tempdir().unwrap();
4964
    let root = dir.path();
4965
    let repo = Repo::init(root).unwrap().with_home(root.join("home"));
4966
    write(root, "a.txt", b"crlf\r\n");
4967
    repo.commit("base", &[]).unwrap();
4968
    let old = std::time::SystemTime::now() - std::time::Duration::from_secs(30);
4969
    fs::File::options()
4970
        .write(true)
4971
        .open(root.join("a.txt"))
4972
        .unwrap()
4973
        .set_modified(old)
4974
        .unwrap();
4975
    assert!(repo.snapshot_status("status").unwrap().statuses.is_empty());
4976
    assert!(repo
4977
        .snapshot_status("status")
4978
        .unwrap()
4979
        .base_snapshot
4980
        .unrendered
4981
        .contains("a.txt"));
4982
    // With eol=lf, a.txt as stored no longer equals the base.
4983
    write(root, ".oxyattributes", b"*.txt eol=lf\n");
4984
    let snap = repo.snapshot_status("status").unwrap();
4985
    assert_eq!(
4986
        statuses(&snap),
4987
        vec![
4988
            (".oxyattributes".to_string(), ChangeStatus::Added),
4989
            ("a.txt".to_string(), ChangeStatus::Modified)
4990
        ]
4991
    );
4992
}
4993
4994
/// Bookmarks with `/` in their names: pushing records their
4995
/// attestations, and checkpoints are kept for them, beside `feature`
4996
/// itself.
4997
#[test]
4998
fn bookmarks_with_slashes_push_and_checkpoint() {
4999
    hermetic();
5000
    let dir = tempfile::tempdir().unwrap();
5001
    let root = dir.path();
5002
    let origin = Repo::init(&root.join("origin")).unwrap();
5003
    let url = root.join("origin").to_string_lossy().to_string();
5004
    let mut repo = Repo::clone(&url, &root.join("r"))
5005
        .unwrap()
5006
        .with_home(root.join("home"));
5007
    // With an identity, pushes carry reference attestations: the case
5008
    // that failed, since the attestation is a file named after the bookmark.
5009
    repo.create_identity("Ada", "[email protected]", IdentityScope::Repo)
5010
        .unwrap();
5011
    let r = root.join("r");
5012
    write(&r, "a.txt", b"a\n");
5013
    let h_a = repo.commit("a", &[]).unwrap();
5014
    assert!(repo.push("origin", false).unwrap()[0].ok);
5015
    repo.bookmark_create("feature", None).unwrap();
5016
    repo.bookmark_create("feature/x", None).unwrap();
5017
    repo.bookmark_switch("feature/x", false).unwrap();
5018
    write(&r, "b.txt", b"b\n");
5019
    let h_b = repo.commit("b", &[]).unwrap();
5020
    for name in ["feature", "feature/x"] {
5021
        let res = repo.push_bookmark("origin", name, false).unwrap();
5022
        assert!(res[0].ok, "{name}: {res:?}");
5023
    }
5024
    assert_eq!(origin.resolve_heads("feature").unwrap(), vec![h_a]);
5025
    assert_eq!(
5026
        origin.resolve_heads("feature/x").unwrap(),
5027
        repo.resolve_heads("feature/x").unwrap()
5028
    );
5029
    assert!(origin.resolve_heads("feature/x").unwrap().contains(&h_b));
5030
    assert!(origin.latest_ref_attest("feature/x").unwrap().is_some());
5031
    assert!(origin.latest_ref_attest("feature").unwrap().is_some());
5032
5033
    // A checkpoint of feature/x is found again when loading its state.
5034
    let (cp, _, _) = repo.checkpoint().unwrap();
5035
    assert_eq!(repo.latest_checkpoint("feature/x").unwrap().unwrap().0, cp);
5036
    assert!(repo.latest_checkpoint("feature").unwrap().is_none());
5037
    let heads = repo.resolve_heads("feature/x").unwrap();
5038
    assert!(repo.load_state_checkpointed(&heads).unwrap().is_some());
5039
}
5040
5041
/// Deleting a bookmark on a remote (spec §16.4): attested like any update,
5042
/// never the remote's own bookmark, and a bookmark created again later is
5043
/// accepted although the deletion's attestation stays the latest.
5044
#[test]
5045
fn bookmarks_are_deleted_on_a_remote() {
5046
    hermetic();
5047
    let dir = tempfile::tempdir().unwrap();
5048
    let root = dir.path();
5049
    let origin = Repo::init(&root.join("origin")).unwrap();
5050
    let url = root.join("origin").to_string_lossy().to_string();
5051
    let mut repo = Repo::clone(&url, &root.join("r"))
5052
        .unwrap()
5053
        .with_home(root.join("home"));
5054
    repo.create_identity("Ada", "[email protected]", IdentityScope::Repo)
5055
        .unwrap();
5056
    let r = root.join("r");
5057
    write(&r, "a.txt", b"a\n");
5058
    repo.commit("a", &[]).unwrap();
5059
    assert!(repo.push("origin", false).unwrap()[0].ok);
5060
    repo.bookmark_create("feature/x", None).unwrap();
5061
    assert!(repo.push_bookmark("origin", "feature/x", false).unwrap()[0].ok);
5062
    assert!(origin.resolve_heads("feature/x").is_ok());
5063
5064
    let res = repo.push_delete("origin", "feature/x").unwrap();
5065
    assert!(res[0].ok, "{res:?}");
5066
    assert!(!origin.view().unwrap().bookmarks.contains_key("feature/x"));
5067
    let (_, att) = origin.latest_ref_attest("feature/x").unwrap().unwrap();
5068
    assert!(
5069
        matches!(att.attest.body, AttestBody::Ref { new_state, .. } if new_state.is_zero()),
5070
        "the deletion is attested"
5071
    );
5072
    assert!(
5073
        repo.view().unwrap().bookmarks.contains_key("feature/x"),
5074
        "the local bookmark stays"
5075
    );
5076
    assert!(!repo
5077
        .view()
5078
        .unwrap()
5079
        .remotes
5080
        .get("origin")
5081
        .is_some_and(|m| m.contains_key("feature/x")));
5082
5083
    // Pushing it again creates it again, past the deletion's serial.
5084
    let res = repo.push_bookmark("origin", "feature/x", false).unwrap();
5085
    assert!(res[0].ok, "{res:?}");
5086
    assert!(origin.view().unwrap().bookmarks.contains_key("feature/x"));
5087
5088
    // Nothing to delete, and never the remote's own bookmark.
5089
    assert!(repo.push_delete("origin", "nope").is_err());
5090
    let res = repo.push_delete("origin", "main").unwrap();
5091
    assert!(
5092
        !res[0].ok && res[0].reason.contains("default bookmark"),
5093
        "{res:?}"
5094
    );
5095
    assert!(origin.view().unwrap().bookmarks.contains_key("main"));
5096
}
5097
5098
/// `bookmark switch --carry` (spec §10.1): uncommitted work goes along
5099
/// when the target has the same versions of the files it touches, and is
5100
/// refused, untouched, when it has others.
5101
#[test]
5102
fn switching_bookmarks_carries_uncommitted_work() {
5103
    hermetic();
5104
    let dir = tempfile::tempdir().unwrap();
5105
    let root = dir.path();
5106
    let mut repo = Repo::init(root).unwrap().with_home(root.join("home"));
5107
    write(root, "a.txt", b"a\n");
5108
    write(root, "b.txt", b"b\n");
5109
    write(root, "gone.txt", b"gone\n");
5110
    repo.commit("base", &[]).unwrap();
5111
    repo.bookmark_create("feature", None).unwrap();
5112
    // Started on main, belongs on feature: edit, add, remove.
5113
    write(root, "a.txt", b"a\nmore\n");
5114
    write(root, "new.txt", b"new\n");
5115
    fs::remove_file(root.join("gone.txt")).unwrap();
5116
    let (_, carried) = repo.bookmark_switch_carry("feature").unwrap();
5117
    assert_eq!(carried, vec!["a.txt", "gone.txt", "new.txt"]);
5118
    assert_eq!(repo.config.bookmark, "feature");
5119
    assert_eq!(fs::read(root.join("a.txt")).unwrap(), b"a\nmore\n");
5120
    assert_eq!(fs::read(root.join("new.txt")).unwrap(), b"new\n");
5121
    assert!(!root.join("gone.txt").exists());
5122
    let snap = repo.snapshot("status").unwrap();
5123
    assert_eq!(
5124
        statuses(&snap),
5125
        vec![
5126
            ("a.txt".to_string(), ChangeStatus::Modified),
5127
            ("gone.txt".to_string(), ChangeStatus::Removed),
5128
            ("new.txt".to_string(), ChangeStatus::Added)
5129
        ]
5130
    );
5131
    repo.commit("the work", &[]).unwrap();
5132
    assert!(repo.resolve_heads("main").unwrap().len() == 1);
5133
5134
    // main moves b.txt on; work on feature touching b.txt cannot follow.
5135
    repo.bookmark_switch("main", false).unwrap();
5136
    write(root, "b.txt", b"b on main\n");
5137
    repo.commit("b on main", &[]).unwrap();
5138
    repo.bookmark_switch("feature", false).unwrap();
5139
    write(root, "b.txt", b"b edited\n");
5140
    let err = repo.bookmark_switch_carry("main").unwrap_err().to_string();
5141
    assert!(err.contains("b.txt") && err.contains("--discard"), "{err}");
5142
    assert_eq!(repo.config.bookmark, "feature", "nothing happened");
5143
    assert_eq!(fs::read(root.join("b.txt")).unwrap(), b"b edited\n");
5144
}
5145
5146
/// Merging and checking out (feedback 3): a working copy without changes
5147
/// follows a merge whichever state it sat on; a refused checkout names
5148
/// what is in the way; `checkout --carry` takes the work along.
5149
#[test]
5150
fn merges_move_clean_working_copies_and_checkouts_say_what_blocks_them() {
5151
    hermetic();
5152
    let dir = tempfile::tempdir().unwrap();
5153
    let root = dir.path();
5154
    let mut repo = Repo::init(root).unwrap().with_home(root.join("home"));
5155
    write(root, "a.txt", b"a\n");
5156
    let h1 = repo.commit("a", &[]).unwrap();
5157
    write(root, "b.txt", b"b\n");
5158
    repo.commit("b", &[]).unwrap();
5159
    repo.bookmark_create("feature", None).unwrap();
5160
    repo.bookmark_switch("feature", false).unwrap();
5161
    write(root, "c.txt", b"c\n");
5162
    repo.commit("c on feature", &[]).unwrap();
5163
    repo.bookmark_switch("main", false).unwrap();
5164
    // The working copy sits on an older state than main's heads.
5165
    repo.checkout(&[h1], false, "checkout").unwrap();
5166
    assert!(!root.join("b.txt").exists());
5167
    let m = repo.merge("feature").unwrap();
5168
    assert!(m.checked_out, "a clean working copy follows the merge");
5169
    for f in ["a.txt", "b.txt", "c.txt"] {
5170
        assert!(root.join(f).exists(), "{f}");
5171
    }
5172
5173
    // A refusal says which paths are in the way and what to do.
5174
    fs::remove_file(root.join("b.txt")).unwrap();
5175
    write(root, "a.txt", b"a edited\n");
5176
    let err = repo
5177
        .checkout(&[h1], false, "checkout")
5178
        .unwrap_err()
5179
        .to_string();
5180
    assert!(
5181
        err.contains("modified a.txt") && err.contains("removed b.txt") && err.contains("--carry"),
5182
        "{err}"
5183
    );
5184
    // --carry takes them along: h1 has a.txt as the base has it, and no b.txt
5185
    // is carried as absent (h1 has none either, so that is refused).
5186
    let err = repo
5187
        .checkout_carry(&[h1], "the first change", "checkout")
5188
        .unwrap_err()
5189
        .to_string();
5190
    assert!(
5191
        err.contains("b.txt") && err.contains("the first change"),
5192
        "{err}"
5193
    );
5194
    write(root, "b.txt", b"b\n");
5195
    let (_, carried) = repo
5196
        .checkout_carry(&[h1], "the first change", "checkout")
5197
        .unwrap();
5198
    assert_eq!(carried, vec!["a.txt"]);
5199
    assert_eq!(fs::read(root.join("a.txt")).unwrap(), b"a edited\n");
5200
    assert!(!root.join("b.txt").exists(), "h1 has no b.txt");
5201
}
5202
5203
/// Doctor and subrepos before the first commit (feedback 5 and 8): a
5204
/// user identity not stored in a new repository yet is fine while its
5205
/// secret key is there; an added subrepo is listed as not committed yet.
5206
#[test]
5207
fn a_new_repository_is_healthy_before_its_first_commit() {
5208
    hermetic();
5209
    let dir = tempfile::tempdir().unwrap();
5210
    let root = dir.path();
5211
    let home = root.join("home");
5212
    let mut first = Repo::init(&root.join("first"))
5213
        .unwrap()
5214
        .with_home(home.clone());
5215
    let (key, _) = first
5216
        .create_identity("Ada", "[email protected]", IdentityScope::User)
5217
        .unwrap();
5218
    let repo = Repo::init(&root.join("second"))
5219
        .unwrap()
5220
        .with_home(home.clone());
5221
    // Only the secret key: no identity object anywhere this repository sees.
5222
    let keys = repo.keys_dir.clone();
5223
    let _ = fs::remove_file(keys.join(format!("{}.identity", key.to_hex())));
5224
    assert!(keys.join(format!("{}.secret", key.to_hex())).is_file());
5225
    let r = repo.doctor(true);
5226
    let id = r.checks.iter().find(|c| c.area == "identity").unwrap();
5227
    assert_eq!(id.health, Health::Ok, "{}", id.message);
5228
    assert!(id.message.contains("first signed change"), "{}", id.message);
5229
5230
    // A subrepo added and not committed yet is listed, pinned where it is.
5231
    let lib = root.join("lib");
5232
    let l = Repo::init(&lib).unwrap().with_home(home.clone());
5233
    write(&lib, "x.txt", b"x\n");
5234
    l.commit("x", &[]).unwrap();
5235
    let second = root.join("second");
5236
    write(&second, "a.txt", b"a\n");
5237
    repo.submodule_add(&lib.to_string_lossy(), "deps/lib", None)
5238
        .unwrap();
5239
    let subs = repo.subrepos().unwrap();
5240
    assert_eq!(subs.len(), 1);
5241
    assert_eq!(
5242
        (subs[0].path.as_str(), subs[0].committed),
5243
        ("deps/lib", false)
5244
    );
5245
    assert_eq!(subs[0].actual.as_ref(), Some(&subs[0].pin));
5246
    repo.commit("add lib", &[]).unwrap();
5247
    let subs = repo.subrepos().unwrap();
5248
    assert!(subs[0].committed, "committed now");
5249
}
5250
5251
/// Commit, diff, hunks and discard use the partial snapshot: a file
5252
/// unchanged since the manifest is neither read nor rendered, and showing
5253
/// a change renders only what it edits, the same as from a full base.
5254
#[cfg(unix)]
5255
#[test]
5256
fn commits_and_diffs_leave_unchanged_files_alone() {
5257
    use std::os::unix::fs::PermissionsExt;
5258
    hermetic();
5259
    let dir = tempfile::tempdir().unwrap();
5260
    let root = dir.path();
5261
    let repo = Repo::init(root).unwrap().with_home(root.join("home"));
5262
    write(root, "big.txt", b"lots\nof\nlines\n");
5263
    write(root, "a.txt", b"one\ntwo\n");
5264
    repo.commit("base", &[]).unwrap();
5265
    let old = std::time::SystemTime::now() - std::time::Duration::from_secs(30);
5266
    for f in ["big.txt", "a.txt"] {
5267
        fs::File::options()
5268
            .write(true)
5269
            .open(root.join(f))
5270
            .unwrap()
5271
            .set_modified(old)
5272
            .unwrap();
5273
    }
5274
    assert!(repo.snapshot_status("status").unwrap().statuses.is_empty());
5275
    // big.txt cannot be read at all from here on.
5276
    fs::set_permissions(root.join("big.txt"), fs::Permissions::from_mode(0o000)).unwrap();
5277
5278
    write(root, "a.txt", b"one\nTWO\nthree\n");
5279
    let diff = repo.diff_files(None).unwrap();
5280
    assert_eq!(
5281
        diff.iter().map(|f| f.path.as_str()).collect::<Vec<_>>(),
5282
        ["a.txt"]
5283
    );
5284
    let (_, hunks) = repo.hunks().unwrap();
5285
    assert!(!hunks.is_empty() && hunks.iter().all(|h| h.path == "a.txt"));
5286
    let h = repo.commit("edit a", &[]).unwrap();
5287
5288
    // Showing the change needs only a.txt's graph, and renders as a full base does.
5289
    let c = repo.store().get_change(&h).unwrap();
5290
    let full = repo.load_state(&c.deps).unwrap();
5291
    let want = render_change(&c, &full, &full.materialize());
5292
    assert_eq!(repo.describe_change(&h).unwrap(), want);
5293
    let (base, snap) = repo.change_base(&c).unwrap();
5294
    assert!(!base.is_full() && snap.unrendered.contains("big.txt"));
5295
5296
    // Discarding works the same way.
5297
    write(root, "a.txt", b"scratch\n");
5298
    assert_eq!(repo.discard(&["a.txt".into()]).unwrap(), 1);
5299
    assert_eq!(fs::read(root.join("a.txt")).unwrap(), b"one\nTWO\nthree\n");
5300
    fs::set_permissions(root.join("big.txt"), fs::Permissions::from_mode(0o644)).unwrap();
5301
}
5302
5303
/// A replace conflict (spec §9.3) is settled by a change that writes one
5304
/// candidate, or new bytes, at the path when the caller names it; a plain
5305
/// snapshot of a checkout never settles it on its own.
5306
#[test]
5307
fn replace_conflicts_are_settled_when_asked() {
5308
    hermetic();
5309
    let dir = tempfile::tempdir().unwrap();
5310
    let root = dir.path();
5311
    let mut repo = Repo::init(root).unwrap().with_home(root.join("home"));
5312
    let blob = |n: u8| {
5313
        let mut v = vec![0u8; 64];
5314
        v[1] = n;
5315
        v
5316
    };
5317
    write(root, "img.bin", &blob(1));
5318
    repo.commit("add img", &[]).unwrap();
5319
    repo.bookmark_create("other", None).unwrap();
5320
    write(root, "img.bin", &blob(2));
5321
    repo.commit("img two", &[]).unwrap();
5322
    repo.bookmark_switch("other", false).unwrap();
5323
    write(root, "img.bin", &blob(3));
5324
    repo.commit("img three", &[]).unwrap();
5325
    repo.bookmark_switch("main", false).unwrap();
5326
    repo.merge("other").unwrap();
5327
    let heads = repo.bookmark_heads().unwrap();
5328
    let merged = repo.load_state(&heads).unwrap().materialize();
5329
    assert!(
5330
        matches!(&merged.files["img.bin"].content, FileContent::Opaque { blobs } if blobs.len() == 2),
5331
        "a replace conflict"
5332
    );
5333
    // A snapshot of the checkout records nothing.
5334
    assert!(repo
5335
        .snapshot("status")
5336
        .unwrap()
5337
        .statuses
5338
        .iter()
5339
        .all(|s| s.path != "img.bin"));
5340
5341
    // Keeping candidate 3 settles it.
5342
    let author = repo.author();
5343
    let edits = [FileEdit {
5344
        path: "img.bin".into(),
5345
        content: Some(blob(3)),
5346
    }];
5347
    let c = repo
5348
        .build_change(&heads, &edits, "keep three", author)
5349
        .unwrap();
5350
    assert_eq!(c.kind, ChangeKind::Resolution);
5351
    let mut st = repo.load_state(&heads).unwrap();
5352
    for d in &c.deps {
5353
        assert!(st.contains(d));
5354
    }
5355
    assert!(
5356
        heads.iter().all(|h| c.deps.contains(h)),
5357
        "depends on both contributors"
5358
    );
5359
    st.add(c).unwrap();
5360
    let after = st.materialize();
5361
    assert!(!after.is_conflicted());
5362
    assert_eq!(
5363
        after.files["img.bin"].content,
5364
        FileContent::Opaque {
5365
            blobs: vec![Repo::blob_ref(&blob(3))]
5366
        }
5367
    );
5368
5369
    // New bytes settle it too.
5370
    let edits = [FileEdit {
5371
        path: "img.bin".into(),
5372
        content: Some(blob(9)),
5373
    }];
5374
    let c = repo.build_change(&heads, &edits, "new", author).unwrap();
5375
    let mut st = repo.load_state(&heads).unwrap();
5376
    st.add(c).unwrap();
5377
    assert_eq!(
5378
        st.materialize().files["img.bin"].content,
5379
        FileContent::Opaque {
5380
            blobs: vec![Repo::blob_ref(&blob(9))]
5381
        }
5382
    );
5383
}
5384
5385
/// The history of a range of lines (spec §27): the changes that wrote
5386
/// or deleted its atoms, or deleted atoms from between them; edits outside
5387
/// the range and changes the range's lines survived are not in it.
5388
#[test]
5389
fn line_ranges_have_exact_histories() {
5390
    hermetic();
5391
    let dir = tempfile::tempdir().unwrap();
5392
    let root = dir.path();
5393
    let repo = Repo::init(root).unwrap().with_home(root.join("home"));
5394
    write(root, "f.rs", b"use x;\nfn a() {\n  one();\n  two();\n}\n");
5395
    let base = repo.commit("add f", &[]).unwrap();
5396
    write(root, "f.rs", b"use y;\nfn a() {\n  one();\n  two();\n}\n");
5397
    let outside = repo.commit("change the import", &[]).unwrap();
5398
    write(root, "f.rs", b"use y;\nfn a() {\n  ONE();\n  two();\n}\n");
5399
    let inside = repo.commit("edit a line of a", &[]).unwrap();
5400
    write(root, "f.rs", b"use y;\nfn a() {\n  ONE();\n}\n");
5401
    let deleted = repo.commit("delete a line of a", &[]).unwrap();
5402
    write(root, "f.rs", b"use y;\nfn a() {\n  ONE();\n}\nfn b() {}\n");
5403
    let after = repo.commit("add b after a", &[]).unwrap();
5404
    let heads = repo.bookmark_heads().unwrap();
5405
5406
    // Lines 2..4 are `fn a() {`, `ONE();`, `}` now.
5407
    let hist: Vec<ChangeHash> = repo
5408
        .line_history(&heads, "f.rs", 2, 4)
5409
        .unwrap()
5410
        .iter()
5411
        .map(|e| e.hash)
5412
        .collect();
5413
    for (h, what) in [
5414
        (base, "wrote it"),
5415
        (inside, "edited a line"),
5416
        (deleted, "deleted a line from inside"),
5417
    ] {
5418
        assert!(hist.contains(&h), "{what}");
5419
    }
5420
    for (h, what) in [(outside, "an edit above"), (after, "an addition below")] {
5421
        assert!(!hist.contains(&h), "{what}");
5422
    }
5423
    assert_eq!(hist[0], deleted, "newest first");
5424
    // One line: only what touched it.
5425
    let one: Vec<ChangeHash> = repo
5426
        .line_history(&heads, "f.rs", 1, 1)
5427
        .unwrap()
5428
        .iter()
5429
        .map(|e| e.hash)
5430
        .collect();
5431
    assert!(one.contains(&outside) && !one.contains(&inside));
5432
    assert!(repo.line_history(&heads, "f.rs", 3, 9).is_err());
5433
    assert!(repo.line_history(&heads, "f.rs", 0, 1).is_err());
5434
    assert!(repo.line_history(&heads, "nope.rs", 1, 1).is_err());
5435
}
5436
5437
#[test]
5438
fn receipts_are_kept_with_their_state_and_verified() {
5439
    use crate::receipt::{Receipt, SignedReceipt};
5440
    hermetic();
5441
    let dir = tempfile::tempdir().unwrap();
5442
    let root = dir.path();
5443
    let repo = Repo::init(root).unwrap().with_home(root.join("home"));
5444
    write(root, "a.txt", b"1\n");
5445
    repo.commit("A", &[]).unwrap();
5446
    let heads = repo.bookmark_heads().unwrap();
5447
    let state = repo
5448
        .store()
5449
        .put_state(&StateObject::new(heads.clone()))
5450
        .unwrap();
5451
    let out = repo.store_blob(b"built\n").unwrap();
5452
    let receipt = Receipt {
5453
        job_name: "build".into(),
5454
        pipeline_hash: ObjectRef([1; 32]),
5455
        scope_tree_hash: ObjectRef([2; 32]),
5456
        inputs: vec![],
5457
        environment: ObjectRef([3; 32]),
5458
        outputs: vec![out],
5459
        exit_code: 0,
5460
        duration_ms: 42,
5461
    };
5462
    let sk = SecretKey::generate();
5463
    let runner = sk.identity("earth-1", "runner@earth", 1);
5464
    let sr = SignedReceipt::sign(
5465
        receipt.clone(),
5466
        repo.id().unwrap(),
5467
        state,
5468
        "demo#1",
5469
        &runner,
5470
        &sk,
5471
    );
5472
5473
    let r = repo.add_receipt(&sr).unwrap();
5474
    let found = repo.receipts(&heads).unwrap();
5475
    assert_eq!(found.len(), 1);
5476
    assert_eq!(found[0].attest, r);
5477
    assert_eq!(found[0].signed, sr);
5478
    assert!(found[0].problem.is_none() && !found[0].revoked);
5479
    assert!(repo.receipts(&[ObjectRef([5; 32])]).unwrap().is_empty());
5480
5481
    // Another repository's receipt, or a forged one, is refused.
5482
    let elsewhere = SignedReceipt::sign(receipt.clone(), [0; 16], state, "x", &runner, &sk);
5483
    assert!(repo
5484
        .add_receipt(&elsewhere)
5485
        .unwrap_err()
5486
        .to_string()
5487
        .contains("another repository"));
5488
    let mut forged = sr.clone();
5489
    forged.receipt.exit_code = 1;
5490
    assert!(repo
5491
        .add_receipt(&forged)
5492
        .unwrap_err()
5493
        .to_string()
5494
        .contains("does not verify"));
5495
5496
    // gc keeps the receipt, its runner and its output while the state lives.
5497
    repo.gc(true).unwrap();
5498
    assert_eq!(repo.receipts(&heads).unwrap().len(), 1);
5499
    assert_eq!(repo.read_blob(&out).unwrap(), b"built\n");
5500
    assert!(repo.fsck().unwrap().problems.is_empty());
5501
}
5502
5503
#[test]
5504
fn status_leaves_an_unchanged_manifest_alone() {
5505
    hermetic();
5506
    let dir = tempfile::tempdir().unwrap();
5507
    let root = dir.path();
5508
    let repo = Repo::init(root).unwrap().with_home(root.join("home"));
5509
    write(root, "a.txt", b"1\n");
5510
    write(root, "b.txt", b"2\n");
5511
    repo.commit("A", &[]).unwrap();
5512
    // Files last touched well outside the racy window.
5513
    let old = std::time::SystemTime::now() - std::time::Duration::from_secs(60);
5514
    for f in ["a.txt", "b.txt"] {
5515
        fs::File::options()
5516
            .write(true)
5517
            .open(root.join(f))
5518
            .unwrap()
5519
            .set_modified(old)
5520
            .unwrap();
5521
    }
5522
    repo.snapshot_status("status").unwrap();
5523
    let path = repo.manifest_path();
5524
    let first = fs::read(&path).unwrap();
5525
    repo.snapshot_status("status").unwrap();
5526
    assert_eq!(
5527
        fs::read(&path).unwrap(),
5528
        first,
5529
        "an unchanged tree does not rewrite the manifest"
5530
    );
5531
    // A change rewrites it.
5532
    write(root, "a.txt", b"1\n2\n");
5533
    repo.snapshot_status("status").unwrap();
5534
    assert_ne!(fs::read(&path).unwrap(), first);
5535
}
5536
5537
#[test]
5538
fn large_text_files_travel_and_survive_gc_as_text_blobs() {
5539
    hermetic();
5540
    let dir = tempfile::tempdir().unwrap();
5541
    let root = dir.path();
5542
    let origin_path = root.join("origin");
5543
    Repo::init(&origin_path).unwrap();
5544
    let origin_url = origin_path.to_string_lossy().to_string();
5545
    let a = Repo::clone(&origin_url, &root.join("a")).unwrap();
5546
    let big: String = (0..5000).map(|i| format!("line {i}\n")).collect();
5547
    write(&root.join("a"), "big.txt", big.as_bytes());
5548
    write(&root.join("a"), "small.txt", b"small\n");
5549
    let h1 = a.commit("large", &[]).unwrap();
5550
    let (_, body) = a.store().get(&h1).unwrap();
5551
    assert!(body.len() < 2048, "the change is {} bytes", body.len());
5552
    assert!(a.push("origin", false).unwrap()[0].ok);
5553
5554
    // A clone reads the text from the blobs that came with the change.
5555
    let b = Repo::clone(&origin_url, &root.join("b")).unwrap();
5556
    assert_eq!(fs::read(root.join("b/big.txt")).unwrap(), big.as_bytes());
5557
    // An edit in the middle of the stored insert is an ordinary change.
5558
    let edited = big.replace("line 2500\n", "line 2500, edited\n");
5559
    write(&root.join("b"), "big.txt", edited.as_bytes());
5560
    let h2 = b.commit("edit", &[]).unwrap();
5561
    assert!(b.store().get_change(&h2).unwrap().edits.len() <= 2);
5562
    assert!(b.push("origin", false).unwrap()[0].ok);
5563
    assert!(a.pull("origin").unwrap().checked_out);
5564
    assert_eq!(fs::read(root.join("a/big.txt")).unwrap(), edited.as_bytes());
5565
    assert_eq!(
5566
        a.fsck().unwrap().errors(),
5567
        0,
5568
        "{:?}",
5569
        a.fsck().unwrap().problems
5570
    );
5571
5572
    // With zero retention gc keeps the text blobs of every kept change.
5573
    let mut a = Repo::open(&root.join("a")).unwrap();
5574
    a.config.set("core.op-retention", "0").unwrap();
5575
    a.save_config().unwrap();
5576
    let a = Repo::open(&root.join("a")).unwrap();
5577
    a.gc(true).unwrap();
5578
    let a = Repo::open(&root.join("a")).unwrap();
5579
    assert_eq!(a.store().get_change(&h1).unwrap().message, "large");
5580
    assert_eq!(
5581
        a.fsck().unwrap().errors(),
5582
        0,
5583
        "{:?}",
5584
        a.fsck().unwrap().problems
5585
    );
5586
    // And a clone of the packed repository reads them from its packs.
5587
    let c = Repo::clone(&root.join("a").to_string_lossy(), &root.join("c")).unwrap();
5588
    assert_eq!(fs::read(root.join("c/big.txt")).unwrap(), edited.as_bytes());
5589
    drop(c);
5590
}
5591
5592
#[test]
5593
fn operations_that_both_replace_a_working_copy_are_not_merged() {
5594
    hermetic();
5595
    let dir = tempfile::tempdir().unwrap();
5596
    let root = dir.path();
5597
    let repo = Repo::init(root).unwrap();
5598
    write(root, "a.txt", b"a\n");
5599
    let a = repo.commit("a", &[]).unwrap();
5600
    write(root, "b.txt", b"b\n");
5601
    repo.commit("b", &[]).unwrap();
5602
    let (x, op) = repo.head_op().unwrap();
5603
    let ws = *op.view.workspaces.keys().next().unwrap();
5604
    let mut one = op.view.clone();
5605
    one.workspaces.insert(ws, a);
5606
    let mut two = op.view.clone();
5607
    two.workspaces.insert(ws, ObjectRef([7; 32]));
5608
    let first = repo.record_op(&[x], "one", one).unwrap();
5609
    let e = repo.record_op(&[x], "two", two).unwrap_err();
5610
    assert!(
5611
        e.to_string()
5612
            .contains("changed this working copy at the same time"),
5613
        "{e}"
5614
    );
5615
    assert_eq!(
5616
        repo.head_op().unwrap().0,
5617
        first,
5618
        "the second is not recorded"
5619
    );
5620
}
5621
5622
/// Metalgear, 2026-09-29 (oxygen#36): a status run while a bookmark switch
5623
/// rewrote the working copy recorded the half-written files as edits, and
5624
/// its view replaced the switch's.
5625
#[test]
5626
fn a_snapshot_during_a_switch_never_records_the_switch_as_edits() {
5627
    hermetic();
5628
    let dir = tempfile::tempdir().unwrap();
5629
    let root = dir.path().to_path_buf();
5630
    let mut repo = Repo::init(&root).unwrap();
5631
    write(&root, "keep.txt", b"keep\n");
5632
    repo.commit("base", &[]).unwrap();
5633
    repo.bookmark_create("small", None).unwrap();
5634
    for i in 0..300 {
5635
        write(
5636
            &root,
5637
            &format!("many/f{i}.txt"),
5638
            format!("file {i}\n").as_bytes(),
5639
        );
5640
    }
5641
    repo.commit("many", &[]).unwrap();
5642
    let stop = std::sync::Arc::new(std::sync::atomic::AtomicBool::new(false));
5643
    let watcher = {
5644
        let (root, stop) = (root.clone(), stop.clone());
5645
        std::thread::spawn(move || {
5646
            let r = Repo::open(&root).unwrap();
5647
            let mut ran = 0;
5648
            while !stop.load(std::sync::atomic::Ordering::Relaxed) {
5649
                if r.snapshot_status("oxy status").is_ok() {
5650
                    ran += 1;
5651
                }
5652
            }
5653
            ran
5654
        })
5655
    };
5656
    for i in 0..20 {
5657
        let to = if i % 2 == 0 { "small" } else { "main" };
5658
        repo.bookmark_switch(to, false).unwrap();
5659
    }
5660
    stop.store(true, std::sync::atomic::Ordering::Relaxed);
5661
    assert!(watcher.join().unwrap() > 0, "the watcher snapshotted");
5662
    // Back on main, clean, with every file where main has it.
5663
    let repo = Repo::open(&root).unwrap();
5664
    let s = repo.snapshot_status("oxy status").unwrap();
5665
    assert!(s.statuses.is_empty(), "{:?}", statuses(&s));
5666
    assert!(s.wc.edits.is_empty() && s.wc.tree_ops.is_empty());
5667
    assert_eq!(s.wc.deps, repo.bookmark_heads().unwrap());
5668
    assert!(root.join("many/f299.txt").exists());
5669
}
5670
5671
/// Metalgear, 2026-09-29 (oxygen#38): a parent's `bookmark switch --carry`
5672
/// put a subrepo that was ahead of its pin back at the pin and moved the
5673
/// subrepo's own bookmark backwards.
5674
#[test]
5675
fn a_parent_switch_with_carry_leaves_a_subrepo_ahead_of_its_pin_alone() {
5676
    hermetic();
5677
    let dir = tempfile::tempdir().unwrap();
5678
    let root = dir.path();
5679
    Repo::init(&root.join("lib-origin")).unwrap();
5680
    let lib_url = root.join("lib-origin").to_string_lossy().to_string();
5681
    let lib = Repo::clone(&lib_url, &root.join("lib")).unwrap();
5682
    write(&root.join("lib"), "lib.txt", b"v1\n");
5683
    lib.commit("lib v1", &[]).unwrap();
5684
    assert!(lib.push("origin", false).unwrap()[0].ok);
5685
5686
    let app_dir = root.join("app");
5687
    let mut app = Repo::init(&app_dir).unwrap();
5688
    write(&app_dir, "main.txt", b"app\n");
5689
    app.submodule_add(&lib_url, "libs/lib", None).unwrap();
5690
    app.commit("app with lib", &[]).unwrap();
5691
    app.bookmark_create("feature", None).unwrap();
5692
5693
    // New work in the subrepo, not yet pinned by the parent.
5694
    let nested_dir = app_dir.join("libs/lib");
5695
    let nested = Repo::open(&nested_dir).unwrap();
5696
    write(&nested_dir, "new.txt", b"new\n");
5697
    let l2 = nested.commit("lib: new file", &[]).unwrap();
5698
    drop(nested);
5699
5700
    let (_, carried) = app.bookmark_switch_carry("feature").unwrap();
5701
    assert!(carried.contains(&"libs/lib".to_string()), "{carried:?}");
5702
    let nested = Repo::open(&nested_dir).unwrap();
5703
    assert!(
5704
        nested.bookmark_heads().unwrap().contains(&l2),
5705
        "its bookmark kept its work"
5706
    );
5707
    assert!(nested_dir.join("new.txt").exists(), "and its files");
5708
    let s = app.snapshot("status").unwrap();
5709
    assert_eq!(
5710
        statuses(&s),
5711
        vec![("libs/lib".to_string(), ChangeStatus::Modified)]
5712
    );
5713
}
5714
5715
/// oxygen#29 (metalgear, rstar-api): after a proposal landed on the hub,
5716
/// moving `main` to a change this clone had pushed on another bookmark,
5717
/// the first `pull` said "Already up to date" while `main` was behind.
5718
#[test]
5719
fn pull_takes_a_remote_move_to_changes_already_here() {
5720
    hermetic();
5721
    let dir = tempfile::tempdir().unwrap();
5722
    let root = dir.path();
5723
    let origin_path = root.join("origin");
5724
    let origin = Repo::init(&origin_path).unwrap();
5725
    let url = origin_path.to_string_lossy().to_string();
5726
    let mut b = Repo::clone(&url, &root.join("b")).unwrap();
5727
    write(&root.join("b"), "base.txt", b"base\n");
5728
    b.commit("base", &[]).unwrap();
5729
    assert!(b.push("origin", false).unwrap()[0].ok);
5730
5731
    // A feature bookmark with one change, pushed.
5732
    b.bookmark_create("feat", None).unwrap();
5733
    b.bookmark_switch("feat", false).unwrap();
5734
    write(&root.join("b"), "x.txt", b"x\n");
5735
    let x = b.commit("x", &[]).unwrap();
5736
    assert!(b.push("origin", false).unwrap()[0].ok);
5737
    b.bookmark_switch("main", false).unwrap();
5738
5739
    // The remote lands it: its main moves to the feature's state.
5740
    let feat = origin
5741
        .store()
5742
        .get_state(&origin.view().unwrap().bookmarks["feat"])
5743
        .unwrap()
5744
        .heads;
5745
    origin.bookmark_set("main", &feat).unwrap();
5746
5747
    let r = b.pull("origin").unwrap();
5748
    assert!(r.changed, "{r:?}");
5749
    assert!(r.heads.contains(&x) || b.load_state(&r.heads).unwrap().contains(&x));
5750
    let main = b
5751
        .bookmarks()
5752
        .unwrap()
5753
        .into_iter()
5754
        .find(|m| m.name == "main")
5755
        .unwrap();
5756
    assert_eq!(main.behind, Some(0), "{main:?}");
5757
}
5758
5759
/// oxygen#35: a history-only state keeps no inserted text. It reads a
5760
/// stored insert's text blob only when it builds that file's graph, and
5761
/// builds the same graph a full load does.
5762
#[test]
5763
fn history_only_states_read_text_only_for_the_graphs_they_build() {
5764
    hermetic();
5765
    let dir = tempfile::tempdir().unwrap();
5766
    let root = dir.path();
5767
    let repo = Repo::init(root).unwrap();
5768
    let big: String = (0..3000).map(|i| format!("big line {i}\n")).collect();
5769
    let other: String = (0..3000).map(|i| format!("other line {i}\n")).collect();
5770
    write(root, "big.txt", big.as_bytes());
5771
    write(root, "other.txt", other.as_bytes());
5772
    let h = repo.commit("two large files", &[]).unwrap();
5773
    write(root, "big.txt", format!("{big}one more\n").as_bytes());
5774
    let h2 = repo.commit("append", &[]).unwrap();
5775
5776
    let full = repo.load_state_full(&[h2]).unwrap().materialize();
5777
    let text = |snap: &crate::state::Snapshot, p: &str| match &snap.files[p].content {
5778
        FileContent::Text { bytes, .. } => bytes.clone(),
5779
        other => panic!("{other:?}"),
5780
    };
5781
    // Built on demand, every graph renders as the full load's.
5782
    let mut hist = repo.load_state_history(&[h2]).unwrap();
5783
    let big_node = full.files["big.txt"].node;
5784
    assert!(hist.graph_key(&big_node).is_some(), "not built yet");
5785
    repo.load_all_graphs(&mut hist).unwrap();
5786
    let rendered = hist.materialize();
5787
    for p in ["big.txt", "other.txt"] {
5788
        assert_eq!(text(&rendered, p), text(&full, p), "{p}");
5789
    }
5790
5791
    // Without other.txt's text blob, history still loads and big.txt still
5792
    // builds: nothing read the other text.
5793
    let (_, texts) = repo.store().get_change_lazy(&h).unwrap();
5794
    assert_eq!(texts.len(), 2);
5795
    let content = |r: &ObjectRef| -> Vec<u8> {
5796
        let blob = crate::objects::Blob::decode(&repo.store().get(r).unwrap().1).unwrap();
5797
        blob.chunks
5798
            .iter()
5799
            .flat_map(|c| repo.store().get(c).unwrap().1)
5800
            .collect()
5801
    };
5802
    let other_text = texts
5803
        .iter()
5804
        .map(|(r, _)| *r)
5805
        .find(|r| content(r).windows(12).any(|w| w == b"other line 1"))
5806
        .unwrap();
5807
    fs::remove_file(repo.store().path_for(&other_text)).unwrap();
5808
    let mut hist = repo.load_state_history(&[h2]).unwrap();
5809
    repo.load_graphs_of(&mut hist, &[big_node]).unwrap();
5810
    assert!(repo
5811
        .load_graphs_of(&mut hist, &[full.files["other.txt"].node])
5812
        .is_err());
5813
}
5814
5815
/// oxygen#35: the first status after a commit read and rendered every
5816
/// file (79 s and more than 14 GB on the Linux tree), because the
5817
/// manifest had no graph keys for files the commit added.
5818
#[test]
5819
fn a_commit_leaves_a_manifest_the_next_status_trusts() {
5820
    use std::os::unix::fs::PermissionsExt;
5821
    hermetic();
5822
    let dir = tempfile::tempdir().unwrap();
5823
    let root = dir.path();
5824
    let repo = Repo::init(root).unwrap();
5825
    let files = ["a.txt", "b.txt", "d/c.txt"];
5826
    for p in files {
5827
        write(root, p, format!("{p}\n").as_bytes());
5828
        let old = std::time::SystemTime::now() - std::time::Duration::from_secs(30);
5829
        fs::File::options()
5830
            .write(true)
5831
            .open(root.join(p))
5832
            .unwrap()
5833
            .set_modified(old)
5834
            .unwrap();
5835
    }
5836
    repo.commit("added", &[]).unwrap();
5837
    let (_, _, m) = repo.read_manifest().unwrap().unwrap();
5838
    assert!(
5839
        m.entries.values().all(|e| e.graph.is_some()),
5840
        "keys recorded at commit"
5841
    );
5842
    // Unreadable files prove the next status reads none of them.
5843
    for p in files {
5844
        fs::set_permissions(root.join(p), fs::Permissions::from_mode(0o000)).unwrap();
5845
    }
5846
    let snap = repo.snapshot_status("status").unwrap();
5847
    for p in files {
5848
        fs::set_permissions(root.join(p), fs::Permissions::from_mode(0o644)).unwrap();
5849
    }
5850
    assert!(!snap.changed && snap.statuses.is_empty());
5851
    assert_eq!(snap.base_snapshot.unrendered.len(), files.len());
5852
}
5853
5854
/// oxygen#35: a checkout reads, renders and writes only the files whose
5855
/// graphs differ, and renders the rest a batch at a time.
5856
#[test]
5857
fn checkout_touches_only_what_differs_and_renders_in_batches() {
5858
    use std::os::unix::fs::PermissionsExt;
5859
    hermetic();
5860
    let dir = tempfile::tempdir().unwrap();
5861
    let root = dir.path();
5862
    let origin = root.join("origin");
5863
    let mut repo = Repo::init(&origin).unwrap();
5864
    // More files than one batch holds.
5865
    let n = 2100;
5866
    let old = std::time::SystemTime::now() - std::time::Duration::from_secs(30);
5867
    for i in 0..n {
5868
        let p = format!("f/{i:04}.txt");
5869
        write(&origin, &p, format!("file {i}\n").as_bytes());
5870
        fs::File::options()
5871
            .write(true)
5872
            .open(origin.join(&p))
5873
            .unwrap()
5874
            .set_modified(old)
5875
            .unwrap();
5876
    }
5877
    repo.commit("many", &[]).unwrap();
5878
    repo.bookmark_create("feature", None).unwrap();
5879
    repo.bookmark_switch("feature", false).unwrap();
5880
    write(&origin, "f/0007.txt", b"changed\n");
5881
    repo.commit("one change", &[]).unwrap();
5882
5883
    // Switching back to main must not read the unchanged files.
5884
    for i in 0..n {
5885
        if i != 7 {
5886
            let p = origin.join(format!("f/{i:04}.txt"));
5887
            fs::set_permissions(&p, fs::Permissions::from_mode(0o000)).unwrap();
5888
        }
5889
    }
5890
    let r = repo.bookmark_switch("main", false).unwrap();
5891
    for i in 0..n {
5892
        let p = origin.join(format!("f/{i:04}.txt"));
5893
        fs::set_permissions(&p, fs::Permissions::from_mode(0o644)).unwrap();
5894
    }
5895
    assert_eq!((r.written, r.removed), (1, 0), "{r:?}");
5896
    assert_eq!(fs::read(origin.join("f/0007.txt")).unwrap(), b"file 7\n");
5897
    assert!(repo.snapshot_status("status").unwrap().statuses.is_empty());
5898
5899
    // A clone renders every file, across batches.
5900
    let c = root.join("clone");
5901
    Repo::clone(&origin.to_string_lossy(), &c).unwrap();
5902
    for i in [0, 2047, 2048, n - 1] {
5903
        assert_eq!(
5904
            fs::read(c.join(format!("f/{i:04}.txt"))).unwrap(),
5905
            format!("file {i}\n").as_bytes()
5906
        );
5907
    }
5908
    let cloned = Repo::open(&c).unwrap();
5909
    assert!(cloned
5910
        .snapshot_status("status")
5911
        .unwrap()
5912
        .statuses
5913
        .is_empty());
5914
}