OXYGENHUB
# 1ec6fdbc6bcb oxygen / crates / oxy-core / src / repo / tests.rs
365.6 KiB · Rust · last changed Keyless agents create release tags: receive and fetch authorize certified tag keys 16 days ago source blame history raw
1
//! Tests for the repository layer.
2
3
use super::*;
4
use crate::protocol::SignedPolicy;
5
use crate::repo::{BisectStep, Selection};
6
7
/// Point `$OXY_HOME` at a throwaway directory once per test process so no
8
/// test reads or writes the developer's real user configuration or keys.
9
fn hermetic() {
10
    static ONCE: std::sync::Once = std::sync::Once::new();
11
    static DIR: std::sync::OnceLock<tempfile::TempDir> = std::sync::OnceLock::new();
12
    ONCE.call_once(|| {
13
        let d = tempfile::tempdir().unwrap();
14
        std::env::set_var("OXY_HOME", d.path());
15
        DIR.set(d).ok();
16
    });
17
}
18
19
fn write(root: &Path, rel: &str, content: &[u8]) {
20
    let p = root.join(rel);
21
    fs::create_dir_all(p.parent().unwrap()).unwrap();
22
    fs::write(p, content).unwrap();
23
}
24
25
fn statuses(s: &SnapshotResult) -> Vec<(String, ChangeStatus)> {
26
    s.statuses
27
        .iter()
28
        .map(|p| (p.path.clone(), p.status))
29
        .collect()
30
}
31
32
#[test]
33
fn init_snapshot_commit_log_undo() {
34
    hermetic();
35
    let dir = tempfile::tempdir().unwrap();
36
    let root = dir.path();
37
    let repo = Repo::init(root).unwrap();
38
    assert!(Repo::init(root).is_err());
39
    let ops = repo.op_log().unwrap();
40
    assert_eq!(ops.len(), 1);
41
    assert_eq!(ops[0].1.command, "oxy init");
42
43
    // Empty working copy: snapshot records no operation (spec §12.3).
44
    let s = repo.snapshot("oxy status").unwrap();
45
    assert!(!s.changed);
46
    assert_eq!(repo.op_log().unwrap().len(), 1);
47
48
    write(root, "src/main.rs", b"fn main() {}\n");
49
    write(root, "README.md", b"# Hello\n");
50
    write(root, ".oxyignore", b"/target\n");
51
    write(root, "target/junk.o", b"\0\0\0");
52
    let s = repo.snapshot("oxy status").unwrap();
53
    assert!(s.changed);
54
    assert_eq!(
55
        statuses(&s),
56
        vec![
57
            (".oxyignore".into(), ChangeStatus::Added),
58
            ("README.md".into(), ChangeStatus::Added),
59
            ("src/main.rs".into(), ChangeStatus::Added),
60
        ]
61
    );
62
    assert_eq!(repo.op_log().unwrap().len(), 2);
63
    // Snapshotting again with nothing changed records no op.
64
    let s2 = repo.snapshot("oxy status").unwrap();
65
    assert!(!s2.changed);
66
    assert_eq!(s2.wc_hash, s.wc_hash);
67
    assert_eq!(repo.op_log().unwrap().len(), 2);
68
69
    let h1 = repo.commit("Initial import", &[]).unwrap();
70
    let c1 = repo.store().get_change(&h1).unwrap();
71
    assert_eq!(c1.kind, ChangeKind::Normal);
72
    assert!(c1.deps.is_empty(), "first change has nothing to depend on");
73
    assert_eq!(repo.bookmark_heads().unwrap(), vec![h1]);
74
    let (wc_hash, wc) = repo.working_copy().unwrap();
75
    assert_eq!(wc.deps, vec![h1]);
76
    assert!(wc.edits.is_empty());
77
    assert!(repo.commit("nothing", &[]).is_err());
78
79
    // Modify one file, remove another, add a binary file.
80
    write(
81
        root,
82
        "src/main.rs",
83
        b"fn main() {\n    println!(\"hi\");\n}\n",
84
    );
85
    fs::remove_file(root.join("README.md")).unwrap();
86
    write(root, "logo.png", b"\x89PNG\0\0\x01");
87
    let s = repo.snapshot("oxy status").unwrap();
88
    assert_eq!(
89
        statuses(&s),
90
        vec![
91
            ("README.md".into(), ChangeStatus::Removed),
92
            ("logo.png".into(), ChangeStatus::Added),
93
            ("src/main.rs".into(), ChangeStatus::Modified),
94
        ]
95
    );
96
    assert_ne!(s.wc_hash, wc_hash);
97
    // The rewritten working copy keeps its ChangeId and depends on h1.
98
    assert_eq!(s.wc.change_id, wc.change_id);
99
    assert!(s.wc.deps.contains(&h1));
100
101
    let h2 = repo.commit("Second", &[]).unwrap();
102
    let c2 = repo.store().get_change(&h2).unwrap();
103
    assert_eq!(
104
        c2.deps,
105
        vec![h1],
106
        "everything it touches was introduced by h1"
107
    );
108
    assert_eq!(repo.bookmark_heads().unwrap(), vec![h2]);
109
110
    // The materialized head state matches the working copy.
111
    let st = repo.load_state(&[h2]).unwrap();
112
    let snap = st.materialize();
113
    assert!(!snap.is_conflicted());
114
    assert_eq!(
115
        snap.files.keys().cloned().collect::<Vec<_>>(),
116
        [".oxyignore", "logo.png", "src", "src/main.rs"]
117
    );
118
    assert!(
119
        matches!(&snap.files["src/main.rs"].content, FileContent::Text { bytes, .. } if bytes == b"fn main() {\n    println!(\"hi\");\n}\n")
120
    );
121
    assert!(snap.files["logo.png"].mode.opaque);
122
    if let FileContent::Opaque { blobs } = &snap.files["logo.png"].content {
123
        assert_eq!(repo.read_blob(&blobs[0]).unwrap(), b"\x89PNG\0\0\x01");
124
    } else {
125
        panic!("logo should be opaque");
126
    }
127
128
    // Log: newest first, working copy included.
129
    let log = repo.log().unwrap();
130
    assert_eq!(log.len(), 3);
131
    assert!(log[0].is_working_copy);
132
    assert_eq!(log[1].hash, h2);
133
    assert!(log[1].is_head);
134
    assert_eq!(log[2].hash, h1);
135
    let d = repo.describe_change(&h2).unwrap();
136
    assert!(d.contains("D README.md"), "{d}");
137
    assert!(d.contains("+    println!(\"hi\");"), "{d}");
138
    assert!(d.contains("-fn main() {}"), "{d}");
139
140
    // Resolution by prefix.
141
    assert_eq!(repo.resolve_change(&c2.change_id.short(6)).unwrap(), h2);
142
    assert_eq!(
143
        repo.resolve_change(&format!("#{}", h1.short(8))).unwrap(),
144
        h1
145
    );
146
    assert!(repo.resolve_change("zzzz").is_err());
147
148
    // Undo the commit: bookmark and working copy go back.
149
    repo.undo().unwrap();
150
    assert_eq!(repo.bookmark_heads().unwrap(), vec![h1]);
151
    let s = repo.snapshot("oxy status").unwrap();
152
    assert!(
153
        !s.changed,
154
        "files on disk still match the pre-commit working copy"
155
    );
156
    assert_eq!(s.statuses.len(), 3);
157
}
158
159
/// Make `main` conflicted: two commits on the same base that edit the same line.
160
fn conflicted_repo() -> (tempfile::TempDir, Repo, ChangeHash, ChangeHash, ChangeHash) {
161
    let dir = tempfile::tempdir().unwrap();
162
    let root = dir.path();
163
    let repo = Repo::init(root).unwrap();
164
    write(root, "f.txt", b"a\nb\nc\n");
165
    let h1 = repo.commit("base", &[]).unwrap();
166
    write(root, "f.txt", b"a\nB\nc\n");
167
    let h2 = repo.commit("upper", &[]).unwrap();
168
    repo.checkout(&[h1], false, "checkout").unwrap();
169
    write(root, "f.txt", b"a\nX\nc\n");
170
    let h3 = repo.commit("ex", &[]).unwrap();
171
    (dir, repo, h1, h2, h3)
172
}
173
174
#[test]
175
fn concurrent_edits_conflict_and_can_be_resolved() {
176
    hermetic();
177
    let (dir, repo, h1, h2, h3) = conflicted_repo();
178
    let root = dir.path();
179
    let heads: BTreeSet<_> = repo.bookmark_heads().unwrap().into_iter().collect();
180
    assert_eq!(heads, [h2, h3].into_iter().collect());
181
    let st = repo.load_state(&[h2, h3]).unwrap();
182
    assert!(st.materialize().is_conflicted());
183
184
    // Checking out main writes markers.
185
    let r = repo
186
        .checkout(&repo.bookmark_heads().unwrap(), false, "checkout main")
187
        .unwrap();
188
    assert!(r.conflicted);
189
    let marked = fs::read_to_string(root.join("f.txt")).unwrap();
190
    assert!(
191
        marked.starts_with("a\n<<<<<<< oxy conflict 1 of 1"),
192
        "{marked}"
193
    );
194
    assert!(
195
        marked.contains("B\n") && marked.contains("X\n") && marked.ends_with("end\nc\n"),
196
        "{marked}"
197
    );
198
    assert!(has_conflict_markers(marked.as_bytes()));
199
    // Untouched markers: clean working copy; commit has nothing to do.
200
    let s = repo.snapshot("status").unwrap();
201
    assert!(s.statuses.is_empty());
202
    assert!(!s.resolves);
203
204
    // Partially edited file that still has markers cannot be committed.
205
    write(root, "f.txt", marked.replace("B\n", "BB\n").as_bytes());
206
    let s = repo.snapshot("status").unwrap();
207
    assert_eq!(
208
        statuses(&s),
209
        vec![("f.txt".into(), ChangeStatus::ConflictEdited)]
210
    );
211
    assert!(repo.commit("no", &[]).is_err());
212
213
    // Resolve by keeping one side and adding a line elsewhere.
214
    write(root, "f.txt", b"a\nX\nc\nd\n");
215
    let s = repo.snapshot("status").unwrap();
216
    assert_eq!(statuses(&s), vec![("f.txt".into(), ChangeStatus::Resolved)]);
217
    assert!(s.resolves);
218
    let h4 = repo.commit("resolve", &[]).unwrap();
219
    let c4 = repo.store().get_change(&h4).unwrap();
220
    assert_eq!(c4.kind, ChangeKind::Resolution);
221
    let mut want = vec![h1, h2, h3];
222
    want.sort();
223
    assert_eq!(
224
        c4.deps, want,
225
        "a resolution depends on exactly the contributors and what it references"
226
    );
227
    assert_eq!(repo.bookmark_heads().unwrap(), vec![h4]);
228
    let snap = repo.load_state(&[h4]).unwrap().materialize();
229
    assert!(!snap.is_conflicted());
230
    assert!(
231
        matches!(&snap.files["f.txt"].content, FileContent::Text { bytes, .. } if bytes == b"a\nX\nc\nd\n")
232
    );
233
    assert!(!repo.snapshot("status").unwrap().changed);
234
    // A peer holding only h2 and h3 and receiving h4 sees the same result,
235
    // whatever order the changes arrive in.
236
    let mut st = State::new();
237
    for h in [h4, h3, h1, h2] {
238
        st.add_unchecked(repo.store().get_change(&h).unwrap());
239
    }
240
    st.validate().unwrap();
241
    assert!(
242
        matches!(&st.materialize().files["f.txt"].content, FileContent::Text { bytes, .. } if bytes == b"a\nX\nc\nd\n")
243
    );
244
}
245
246
#[test]
247
fn resolution_may_keep_both_sides_or_neither() {
248
    hermetic();
249
    let (dir, repo, _h1, _h2, _h3) = conflicted_repo();
250
    let root = dir.path();
251
    repo.checkout(&repo.bookmark_heads().unwrap(), false, "checkout main")
252
        .unwrap();
253
    // Keep both sides in a chosen order.
254
    write(root, "f.txt", b"a\nX\nB\nc\n");
255
    let h = repo.commit("both", &[]).unwrap();
256
    let snap = repo.load_state(&[h]).unwrap().materialize();
257
    assert!(!snap.is_conflicted());
258
    assert!(
259
        matches!(&snap.files["f.txt"].content, FileContent::Text { bytes, .. } if bytes == b"a\nX\nB\nc\n")
260
    );
261
    // Undo and instead drop the whole region.
262
    repo.undo().unwrap();
263
    write(root, "f.txt", b"a\nc\n");
264
    let h = repo.commit("neither", &[]).unwrap();
265
    let snap = repo.load_state(&[h]).unwrap().materialize();
266
    assert!(!snap.is_conflicted());
267
    assert!(
268
        matches!(&snap.files["f.txt"].content, FileContent::Text { bytes, .. } if bytes == b"a\nc\n")
269
    );
270
}
271
272
#[test]
273
fn name_conflict_resolved_by_removing_a_candidate() {
274
    hermetic();
275
    let dir = tempfile::tempdir().unwrap();
276
    let root = dir.path();
277
    let repo = Repo::init(root).unwrap();
278
    write(root, "keep.txt", b"k\n");
279
    let h1 = repo.commit("base", &[]).unwrap();
280
    write(root, "new.txt", b"one\n");
281
    repo.commit("one", &[]).unwrap();
282
    repo.checkout(&[h1], false, "checkout").unwrap();
283
    write(root, "new.txt", b"two\n");
284
    repo.commit("two", &[]).unwrap();
285
    let r = repo
286
        .checkout(&repo.bookmark_heads().unwrap(), false, "checkout main")
287
        .unwrap();
288
    assert!(r.conflicted);
289
    assert!(
290
        root.join("new.txt.oxy-conflict-1").exists()
291
            && root.join("new.txt.oxy-conflict-2").exists()
292
    );
293
    assert!(!root.join("new.txt").exists());
294
    // Candidate numbering follows change-hash order, so pick by content:
295
    // keep the "two" candidate under the real name and drop the other.
296
    let (keep, drop) = if fs::read(root.join("new.txt.oxy-conflict-1")).unwrap() == b"two\n" {
297
        (1, 2)
298
    } else {
299
        (2, 1)
300
    };
301
    fs::remove_file(root.join(format!("new.txt.oxy-conflict-{drop}"))).unwrap();
302
    fs::rename(
303
        root.join(format!("new.txt.oxy-conflict-{keep}")),
304
        root.join("new.txt"),
305
    )
306
    .unwrap();
307
    let h = repo.commit("pick two", &[]).unwrap();
308
    assert_eq!(
309
        repo.store().get_change(&h).unwrap().kind,
310
        ChangeKind::Resolution
311
    );
312
    // The resolution does not touch keep.txt, so it does not depend on h1;
313
    // the bookmark keeps both as heads and their union is the state.
314
    let heads: BTreeSet<_> = repo.bookmark_heads().unwrap().into_iter().collect();
315
    assert_eq!(heads, [h1, h].into_iter().collect());
316
    let snap = repo
317
        .load_state(&repo.bookmark_heads().unwrap())
318
        .unwrap()
319
        .materialize();
320
    assert!(!snap.is_conflicted(), "{:?}", snap.tree.conflicts);
321
    assert_eq!(
322
        snap.files.keys().cloned().collect::<Vec<_>>(),
323
        ["keep.txt", "new.txt"]
324
    );
325
    assert!(
326
        matches!(&snap.files["new.txt"].content, FileContent::Text { bytes, .. } if bytes == b"two\n")
327
    );
328
}
329
330
#[test]
331
fn identities_and_signed_commits() {
332
    hermetic();
333
    let dir = tempfile::tempdir().unwrap();
334
    let root = dir.path();
335
    let mut repo = Repo::init(root).unwrap().with_home(root.join("home"));
336
    write(root, "a.txt", b"a\n");
337
    let h0 = repo.commit("unsigned", &[]).unwrap();
338
    assert_eq!(repo.verify_change(&h0).unwrap(), SignatureStatus::Unsigned);
339
    assert_eq!(
340
        repo.store().get_change(&h0).unwrap().author,
341
        ObjectRef::ZERO
342
    );
343
344
    let (key, id) = repo
345
        .create_identity("Ada", "[email protected]", IdentityScope::Repo)
346
        .unwrap();
347
    assert_eq!(id.hash(), key);
348
    assert_eq!(repo.config.author_key, Some(key));
349
    // Config survives reopen; the secret key is found again.
350
    let reopened = Repo::open(root).unwrap().with_home(root.join("home"));
351
    assert_eq!(reopened.config.author_key, Some(key));
352
    assert_eq!(reopened.secret_key().unwrap().unwrap().0, key);
353
354
    // Default core.sign = seal: commits carry the author but no signature.
355
    write(root, "a.txt", b"a\nb\n");
356
    let h1 = repo.commit("authored", &[]).unwrap();
357
    assert_eq!(repo.store().get_change(&h1).unwrap().author, key);
358
    assert_eq!(repo.verify_change(&h1).unwrap(), SignatureStatus::Unsigned);
359
    // Signing later works too.
360
    repo.sign_change(&h1).unwrap();
361
    assert!(
362
        matches!(repo.verify_change(&h1).unwrap(), SignatureStatus::Valid { key: k, .. } if k == key)
363
    );
364
365
    repo.config.set("core.sign", "change").unwrap();
366
    repo.save_config().unwrap();
367
    write(root, "a.txt", b"a\nb\nc\n");
368
    let h2 = repo.commit("signed", &[]).unwrap();
369
    assert_eq!(
370
        repo.verify_change(&h2).unwrap(),
371
        SignatureStatus::Valid {
372
            key,
373
            name: "Ada".into(),
374
            email: "[email protected]".into(),
375
            sealed: false,
376
            revoked: false
377
        }
378
    );
379
380
    // A signature by a key that is not the author or a delegate is rejected
381
    // when the change names an author; an anonymous change (made before any
382
    // identity, author zero) is adopted by whoever signs it (spec §14.4).
383
    let other = SecretKey::generate();
384
    let other_id = other.identity("Mallory", "[email protected]", 0);
385
    let other_key = repo.store().put_identity(&other_id).unwrap();
386
    write(root, "a.txt", b"a\nb\nc\nd\n");
387
    repo.config.set("core.sign", "seal").unwrap();
388
    let h3 = repo.commit("ada's, unsigned", &[]).unwrap();
389
    let forged = other.sign(Domain::Change, &other_key, &h3);
390
    repo.store().put_signature(&h3, &forged).unwrap();
391
    assert!(
392
        matches!(repo.verify_change(&h3).unwrap(), SignatureStatus::Invalid(m) if m.contains("neither the author"))
393
    );
394
    let adopted = other.sign(Domain::Change, &other_key, &h0);
395
    repo.store().put_signature(&h0, &adopted).unwrap();
396
    assert!(
397
        matches!(repo.verify_change(&h0).unwrap(), SignatureStatus::Valid { name, .. } if name == "Mallory")
398
    );
399
400
    // Tampering with the stored signature invalidates it.
401
    let mut sig = repo.store().signatures(&h2).unwrap().remove(0);
402
    sig.ed[0] ^= 1;
403
    repo.store().put_signature(&h2, &sig).unwrap();
404
    assert!(matches!(
405
        repo.verify_change(&h2).unwrap(),
406
        SignatureStatus::Invalid(_)
407
    ));
408
409
    // Without the secret key, signing at commit fails cleanly.
410
    let no_keys = Repo::open(root).unwrap().with_home(root.join("nowhere"));
411
    write(root, "a.txt", b"z\n");
412
    assert!(no_keys.commit("cannot sign", &[]).is_err());
413
}
414
415
#[test]
416
fn checkout_moves_the_working_copy() {
417
    hermetic();
418
    let dir = tempfile::tempdir().unwrap();
419
    let root = dir.path();
420
    let repo = Repo::init(root).unwrap();
421
    write(root, "a.txt", b"one\n");
422
    write(root, "sub/deep/b.txt", b"b\n");
423
    let h1 = repo.commit("first", &[]).unwrap();
424
    write(root, "a.txt", b"two\n");
425
    fs::remove_file(root.join("sub/deep/b.txt")).unwrap();
426
    write(root, "bin.dat", &[0, 1, 2, 3]);
427
    let h2 = repo.commit("second", &[]).unwrap();
428
429
    let r = repo.checkout(&[h1], false, "oxy checkout").unwrap();
430
    assert_eq!(
431
        r,
432
        CheckoutReport {
433
            written: 2,
434
            removed: 1,
435
            removed_paths: vec!["bin.dat".into()],
436
            conflicted: false,
437
            notes: vec![],
438
            lacks: 1,
439
        }
440
    );
441
    assert_eq!(fs::read(root.join("a.txt")).unwrap(), b"one\n");
442
    assert_eq!(fs::read(root.join("sub/deep/b.txt")).unwrap(), b"b\n");
443
    assert!(!root.join("bin.dat").exists());
444
    let (_, wc) = repo.working_copy().unwrap();
445
    assert_eq!(wc.deps, vec![h1]);
446
    assert!(
447
        !repo.snapshot("status").unwrap().changed,
448
        "checkout leaves a clean working copy"
449
    );
450
    // The bookmark still points at h2.
451
    assert_eq!(repo.bookmark_heads().unwrap(), vec![h2]);
452
453
    // Dirty working copy refuses without --discard.
454
    write(root, "a.txt", b"dirty\n");
455
    assert!(repo.checkout(&[h2], false, "oxy checkout").is_err());
456
    let r = repo
457
        .checkout(&[h2], true, "oxy checkout --discard")
458
        .unwrap();
459
    assert_eq!(fs::read(root.join("a.txt")).unwrap(), b"two\n");
460
    assert_eq!(fs::read(root.join("bin.dat")).unwrap(), [0, 1, 2, 3]);
461
    assert!(!root.join("sub").exists(), "empty directories are pruned");
462
    assert_eq!(r.removed, 1);
463
    assert!(!repo.snapshot("status").unwrap().changed);
464
465
    // Refuses to write through a symlinked directory.
466
    #[cfg(unix)]
467
    {
468
        fs::remove_dir_all(root.join("sub")).ok();
469
        std::os::unix::fs::symlink("/tmp", root.join("sub")).unwrap();
470
        assert!(repo.checkout(&[h1], true, "oxy checkout").is_err());
471
    }
472
}
473
474
#[test]
475
fn large_files_are_chunked_and_read_back() {
476
    hermetic();
477
    let dir = tempfile::tempdir().unwrap();
478
    let repo = Repo::init(dir.path()).unwrap();
479
    let mut big = vec![0u8; 700 * 1024];
480
    for (i, b) in big.iter_mut().enumerate() {
481
        *b = (i as u32).wrapping_mul(2654435761).to_le_bytes()[0];
482
    }
483
    let r = repo.store_blob(&big).unwrap();
484
    let blob = Blob::decode(&repo.store().get_typed(&r, ObjectType::Blob).unwrap()).unwrap();
485
    assert!(blob.chunks.len() >= 3, "{}", blob.chunks.len());
486
    assert_eq!(repo.read_blob(&r).unwrap(), big);
487
    assert_eq!(Repo::blob_ref(&big), r);
488
}
489
490
#[test]
491
fn clone_push_pull_with_seals_and_attestations() {
492
    hermetic();
493
    let dir = tempfile::tempdir().unwrap();
494
    let root = dir.path();
495
    let origin_path = root.join("origin");
496
    let origin = Repo::init(&origin_path).unwrap();
497
    let origin_url = origin_path.to_string_lossy().to_string();
498
499
    // A clones, creates an identity (default core.sign = seal), commits, pushes.
500
    let mut a = Repo::clone(&origin_url, &root.join("a"))
501
        .unwrap()
502
        .with_home(root.join("home-a"));
503
    assert_eq!(a.id().unwrap(), origin.id().unwrap());
504
    let (key_a, _) = a
505
        .create_identity("Ada", "[email protected]", IdentityScope::Repo)
506
        .unwrap();
507
    write(&root.join("a"), "f.txt", b"a\n");
508
    let h1 = a.commit("first", &[]).unwrap();
509
    let results = a.push("origin", false).unwrap();
510
    origin.refresh().unwrap();
511
    assert!(results[0].ok, "{}", results[0].reason);
512
    assert_eq!(origin.bookmark_heads().unwrap(), vec![h1]);
513
    // The change was sealed at push and the reference attested.
514
    assert!(
515
        matches!(origin.authenticate_change(&h1).unwrap(), SignatureStatus::Valid { key, sealed: true, .. } if key == key_a)
516
    );
517
    assert_eq!(
518
        origin.verify_change(&h1).unwrap(),
519
        SignatureStatus::Unsigned
520
    );
521
    let serial_of = |att: &SignedAttest| match att.attest.body {
522
        AttestBody::Ref { serial, .. } => serial,
523
        _ => unreachable!(),
524
    };
525
    let (_, att) = origin.latest_ref_attest("main").unwrap().unwrap();
526
    // A bookmark new to the remote starts at the clock (past any deleted
527
    // namesake's serial); later updates count up from there.
528
    let first = serial_of(&att);
529
    assert!(first > 1_000_000_000_000, "{first}");
530
    let again = a.push("origin", false).unwrap();
531
    origin.refresh().unwrap();
532
    assert!(again[0].ok && again[0].reason.contains("up to date"));
533
    let (_, att) = origin.latest_ref_attest("main").unwrap().unwrap();
534
    assert_eq!(serial_of(&att), first, "a no-op push does not attest again");
535
536
    // B clones and sees the file and the seal.
537
    let b = Repo::clone(&origin_url, &root.join("b")).unwrap();
538
    assert_eq!(fs::read(root.join("b/f.txt")).unwrap(), b"a\n");
539
    assert_eq!(b.bookmark_heads().unwrap(), vec![h1]);
540
    assert!(matches!(
541
        b.authenticate_change(&h1).unwrap(),
542
        SignatureStatus::Valid { sealed: true, .. }
543
    ));
544
545
    // B (no identity) commits and pushes unsigned; the unverified origin accepts.
546
    write(&root.join("b"), "f.txt", b"a\nb\n");
547
    let h2 = b.commit("second", &[]).unwrap();
548
    assert!(b.push("origin", false).unwrap()[0].ok);
549
    origin.refresh().unwrap();
550
    assert_eq!(origin.bookmark_heads().unwrap(), vec![h2]);
551
552
    // A commits an independent change; push is refused until A pulls.
553
    write(&root.join("a"), "g.txt", b"g\n");
554
    let h3 = a.commit("third", &[]).unwrap();
555
    assert!(a.push("origin", false).is_err());
556
    let pr = a.pull("origin").unwrap();
557
    assert!(pr.changed && pr.checked_out);
558
    let mut want = vec![h2, h3];
559
    want.sort();
560
    assert_eq!(pr.heads, want);
561
    assert_eq!(fs::read(root.join("a/f.txt")).unwrap(), b"a\nb\n");
562
    assert_eq!(fs::read(root.join("a/g.txt")).unwrap(), b"g\n");
563
    let results = a.push("origin", false).unwrap();
564
    origin.refresh().unwrap();
565
    assert!(results[0].ok, "{}", results[0].reason);
566
    let mut origin_heads = origin.bookmark_heads().unwrap();
567
    origin_heads.sort();
568
    assert_eq!(origin_heads, want);
569
    let (_, att) = origin.latest_ref_attest("main").unwrap().unwrap();
570
    assert_eq!(serial_of(&att), first + 1);
571
572
    // B pulls and ends up identical.
573
    let pr = b.pull("origin").unwrap();
574
    assert_eq!(pr.heads, want);
575
    assert_eq!(fs::read(root.join("b/g.txt")).unwrap(), b"g\n");
576
    assert!(!b.snapshot("status").unwrap().changed);
577
578
    // Concurrent edits of the same line: the union is a reified conflict.
579
    write(&root.join("a"), "f.txt", b"a\nA\n");
580
    a.commit("a-edit", &[]).unwrap();
581
    a.push("origin", false).unwrap();
582
    origin.refresh().unwrap();
583
    write(&root.join("b"), "f.txt", b"a\nB\n");
584
    b.commit("b-edit", &[]).unwrap();
585
    let pr = b.pull("origin").unwrap();
586
    assert!(pr.changed && pr.checked_out);
587
    let text = fs::read_to_string(root.join("b/f.txt")).unwrap();
588
    assert!(text.contains("<<<<<<< oxy conflict"), "{text}");
589
    write(&root.join("b"), "f.txt", b"a\nAB\n");
590
    let hr = b.commit("resolve", &[]).unwrap();
591
    assert_eq!(
592
        b.store().get_change(&hr).unwrap().kind,
593
        ChangeKind::Resolution
594
    );
595
    assert!(b.push("origin", false).unwrap()[0].ok);
596
    origin.refresh().unwrap();
597
    a.pull("origin").unwrap();
598
    assert_eq!(fs::read(root.join("a/f.txt")).unwrap(), b"a\nAB\n");
599
    // The resolution depends on the conflicting edits, but nothing depends
600
    // on "third" (it only added g.txt), so it stays a head beside it.
601
    let mut want = vec![hr, h3];
602
    want.sort();
603
    assert_eq!(a.bookmark_heads().unwrap(), want);
604
    assert!(!a.load_state(&want).unwrap().materialize().is_conflicted());
605
}
606
607
#[test]
608
fn receive_push_rejects_bad_updates() {
609
    hermetic();
610
    let dir = tempfile::tempdir().unwrap();
611
    let root = dir.path();
612
    let origin = Repo::init(&root.join("origin")).unwrap();
613
    let url = root.join("origin").to_string_lossy().to_string();
614
    let mut a = Repo::clone(&url, &root.join("a"))
615
        .unwrap()
616
        .with_home(root.join("home"));
617
    let (key, _) = a
618
        .create_identity("Ada", "a@b", IdentityScope::Repo)
619
        .unwrap();
620
    write(&root.join("a"), "f.txt", b"x\n");
621
    let h1 = a.commit("one", &[]).unwrap();
622
    assert!(a.push("origin", false).unwrap()[0].ok);
623
    let empty = origin.store().put_state(&StateObject::new(vec![])).unwrap();
624
    let s1 = origin
625
        .store()
626
        .put_state(&StateObject::new(vec![h1]))
627
        .unwrap();
628
629
    // Missing head.
630
    let ghost = origin
631
        .store()
632
        .put_state(&StateObject::new(vec![ObjectRef([9; 32])]))
633
        .unwrap();
634
    let r = origin
635
        .receive_push(
636
            Bundle::default(),
637
            vec![RefUpdate {
638
                name: "main".into(),
639
                old_state: s1,
640
                new_state: ghost,
641
                force: false,
642
                attestation: None,
643
            }],
644
            None,
645
            vec![],
646
        )
647
        .unwrap();
648
    assert!(
649
        !r[0].ok && r[0].reason.contains("missing"),
650
        "{}",
651
        r[0].reason
652
    );
653
654
    // Stale old_state.
655
    let r = origin
656
        .receive_push(
657
            Bundle::default(),
658
            vec![RefUpdate {
659
                name: "main".into(),
660
                old_state: empty,
661
                new_state: s1,
662
                force: false,
663
                attestation: None,
664
            }],
665
            None,
666
            vec![],
667
        )
668
        .unwrap();
669
    assert!(!r[0].ok && r[0].reason.contains("stale"), "{}", r[0].reason);
670
671
    // Non-fast-forward without force is refused; with force it passes.
672
    let r = origin
673
        .receive_push(
674
            Bundle::default(),
675
            vec![RefUpdate {
676
                name: "main".into(),
677
                old_state: s1,
678
                new_state: empty,
679
                force: false,
680
                attestation: None,
681
            }],
682
            None,
683
            vec![],
684
        )
685
        .unwrap();
686
    assert!(
687
        !r[0].ok && r[0].reason.contains("fast-forward"),
688
        "{}",
689
        r[0].reason
690
    );
691
    let r = origin
692
        .receive_push(
693
            Bundle::default(),
694
            vec![RefUpdate {
695
                name: "main".into(),
696
                old_state: s1,
697
                new_state: empty,
698
                force: true,
699
                attestation: None,
700
            }],
701
            None,
702
            vec![],
703
        )
704
        .unwrap();
705
    assert!(r[0].ok);
706
    assert_eq!(origin.bookmark_heads().unwrap(), vec![]);
707
708
    // Attestation with a stale serial is a rollback and is refused.
709
    let sa = a
710
        .sign_attest(&Attest {
711
            repo: a.id().unwrap(),
712
            hlc: Hlc::now(),
713
            body: AttestBody::Ref {
714
                name: "main".into(),
715
                old_state: empty,
716
                new_state: s1,
717
                serial: 1,
718
            },
719
        })
720
        .unwrap();
721
    let r = origin
722
        .receive_push(
723
            Bundle::default(),
724
            vec![RefUpdate {
725
                name: "main".into(),
726
                old_state: empty,
727
                new_state: s1,
728
                force: false,
729
                attestation: Some(sa.clone()),
730
            }],
731
            None,
732
            vec![],
733
        )
734
        .unwrap();
735
    assert!(
736
        !r[0].ok && r[0].reason.contains("serial"),
737
        "{}",
738
        r[0].reason
739
    );
740
    // An attestation for a different update is refused too.
741
    let sa2 = a
742
        .sign_attest(&Attest {
743
            repo: a.id().unwrap(),
744
            hlc: Hlc::now(),
745
            body: AttestBody::Ref {
746
                name: "main".into(),
747
                old_state: s1,
748
                new_state: empty,
749
                serial: 5,
750
            },
751
        })
752
        .unwrap();
753
    let r = origin
754
        .receive_push(
755
            Bundle::default(),
756
            vec![RefUpdate {
757
                name: "main".into(),
758
                old_state: empty,
759
                new_state: s1,
760
                force: false,
761
                attestation: Some(sa2),
762
            }],
763
            None,
764
            vec![],
765
        )
766
        .unwrap();
767
    assert!(
768
        !r[0].ok && r[0].reason.contains("describe"),
769
        "{}",
770
        r[0].reason
771
    );
772
    let _ = key;
773
}
774
775
#[test]
776
fn user_config_supplies_defaults_and_clones_sign() {
777
    hermetic();
778
    let dir = tempfile::tempdir().unwrap();
779
    let root = dir.path();
780
    let home = root.join("home");
781
    let origin = Repo::init(&root.join("origin")).unwrap();
782
    let url = root.join("origin").to_string_lossy().to_string();
783
784
    // Identity at user scope: the repository file stays free of author keys.
785
    let mut a = Repo::init(&root.join("a")).unwrap().with_home(&home);
786
    let (key, _) = a
787
        .create_identity("Ada", "[email protected]", IdentityScope::User)
788
        .unwrap();
789
    assert!(!a.config.repo_layer().contains_key("author.key"));
790
    assert_eq!(a.config.author_key, Some(key));
791
    assert!(home.join("config.toml").exists());
792
    a.set_user_config("core.sign", "change").unwrap();
793
    assert!(a.config.sign_changes);
794
795
    // Repository settings override user settings and are the only ones saved.
796
    a.config.set("core.sign", "seal").unwrap();
797
    a.save_config().unwrap();
798
    let again = Repo::open(&root.join("a")).unwrap().with_home(&home);
799
    assert!(!again.config.sign_changes);
800
    assert_eq!(again.config.author_key, Some(key));
801
    assert_eq!(
802
        read_config_file(&root.join("a/.oxy/config"))
803
            .unwrap()
804
            .get("core.sign")
805
            .map(String::as_str),
806
        Some("seal")
807
    );
808
809
    // A fresh clone made by this user signs with the user-level identity,
810
    // even though the clone's store has never seen the identity object.
811
    let b = Repo::clone(&url, &root.join("b")).unwrap().with_home(&home);
812
    assert!(b.config.sign_changes);
813
    write(&root.join("b"), "f.txt", b"f\n");
814
    let h = b.commit("signed from a clone", &[]).unwrap();
815
    assert!(
816
        matches!(b.verify_change(&h).unwrap(), SignatureStatus::Valid { key: k, .. } if k == key)
817
    );
818
    assert!(b.push("origin", false).unwrap()[0].ok);
819
    assert!(matches!(
820
        origin.verify_change(&h).unwrap(),
821
        SignatureStatus::Valid { .. }
822
    ));
823
}
824
825
#[test]
826
fn format1_repositories_are_migrated_on_open() {
827
    hermetic();
828
    use crate::oplog::{Format1Op, Format1View};
829
    let dir = tempfile::tempdir().unwrap();
830
    let root = dir.path();
831
    let repo = Repo::init(root).unwrap();
832
    write(root, "a.txt", b"a\n");
833
    let h1 = repo.commit("one", &[]).unwrap();
834
    let (wc_hash, _) = repo.working_copy().unwrap();
835
    // Rewrite the op log the way format 1 stored it: two ops, head lists.
836
    let mut v1 = Format1View::default();
837
    v1.bookmarks.insert("main".into(), vec![]);
838
    v1.workspaces.insert(repo.workspace(), wc_hash);
839
    let init = Format1Op {
840
        parents: vec![],
841
        hlc: Hlc::default(),
842
        command: "oxy init".into(),
843
        view: v1.clone(),
844
    };
845
    let init_ref = repo.store().put(ObjectType::Op, &init.encode()).unwrap();
846
    v1.bookmarks.insert("main".into(), vec![h1]);
847
    let commit = Format1Op {
848
        parents: vec![init_ref],
849
        hlc: Hlc::default(),
850
        command: "oxy commit".into(),
851
        view: v1,
852
    };
853
    let commit_ref = repo.store().put(ObjectType::Op, &commit.encode()).unwrap();
854
    write_atomic(&root.join(".oxy/ops/head"), commit_ref.to_hex().as_bytes()).unwrap();
855
    write_atomic(&root.join(".oxy/format"), FORMAT1_LINE.as_bytes()).unwrap();
856
    drop(repo);
857
858
    let repo = Repo::open(root).unwrap();
859
    assert_eq!(
860
        fs::read_to_string(root.join(".oxy/format")).unwrap(),
861
        FORMAT_LINE
862
    );
863
    assert_eq!(repo.bookmark_heads().unwrap(), vec![h1]);
864
    let ops = repo.op_log().unwrap();
865
    assert_eq!(
866
        ops.iter()
867
            .map(|(_, o)| o.command.as_str())
868
            .collect::<Vec<_>>(),
869
        ["oxy commit", "oxy init"]
870
    );
871
    assert_eq!(repo.heads_of(&ops[1].1.view, "main").unwrap(), vec![]);
872
    assert!(!repo.snapshot("status").unwrap().changed);
873
    // Reopening again is a no-op.
874
    assert_eq!(Repo::open(root).unwrap().op_log().unwrap().len(), 2);
875
}
876
877
#[test]
878
fn undo_skips_snapshot_operations() {
879
    hermetic();
880
    let dir = tempfile::tempdir().unwrap();
881
    let root = dir.path();
882
    let repo = Repo::init(root).unwrap();
883
    write(root, "a.txt", b"a\n");
884
    let h1 = repo.commit("a", &[]).unwrap();
885
    // A later command snapshots new edits on top of the commit.
886
    write(root, "b.txt", b"b\n");
887
    let s = repo.snapshot("oxy status").unwrap();
888
    assert!(s.changed);
889
    assert!(repo.head_op().unwrap().1.is_snapshot());
890
    assert_eq!(repo.last_command().unwrap().command, "oxy commit -m \"a\"");
891
    // Undo must undo the commit, not the snapshot.
892
    repo.undo().unwrap();
893
    assert_eq!(repo.bookmark_heads().unwrap(), vec![]);
894
    let s = repo.snapshot("oxy status").unwrap();
895
    let paths: Vec<_> = s.statuses.iter().map(|p| p.path.as_str()).collect();
896
    assert_eq!(
897
        paths,
898
        ["a.txt", "b.txt"],
899
        "both files are back in the working copy"
900
    );
901
    assert!(repo.store().get_change(&h1).unwrap().deps.is_empty());
902
    // Only snapshots remain above `init`, so there is nothing left to undo.
903
    assert_eq!(repo.last_command().unwrap().command, "oxy init");
904
    assert!(repo.undo().is_err());
905
}
906
907
#[test]
908
fn independent_changes_commute_and_make_multiple_heads() {
909
    hermetic();
910
    let dir = tempfile::tempdir().unwrap();
911
    let root = dir.path();
912
    let repo = Repo::init(root).unwrap();
913
    write(root, "a.txt", b"a\n");
914
    let h1 = repo.commit("a", &[]).unwrap();
915
    write(root, "b.txt", b"b\n");
916
    let h2 = repo.commit("b", &[]).unwrap();
917
    let c2 = repo.store().get_change(&h2).unwrap();
918
    assert!(c2.deps.is_empty(), "b.txt touches nothing from h1");
919
    let mut heads = repo.bookmark_heads().unwrap();
920
    heads.sort();
921
    let mut want = vec![h1, h2];
922
    want.sort();
923
    assert_eq!(heads, want);
924
    // Editing a.txt depends on h1 only.
925
    write(root, "a.txt", b"a\na2\n");
926
    let h3 = repo.commit("a2", &[]).unwrap();
927
    assert_eq!(repo.store().get_change(&h3).unwrap().deps, vec![h1]);
928
    let heads: BTreeSet<_> = repo.bookmark_heads().unwrap().into_iter().collect();
929
    assert_eq!(heads, [h2, h3].into_iter().collect());
930
    // Explicit dependency.
931
    write(root, "c.txt", b"c\n");
932
    let h4 = repo.commit("c", &[h2]).unwrap();
933
    assert_eq!(repo.store().get_change(&h4).unwrap().deps, vec![h2]);
934
}
935
936
#[test]
937
fn mode_change_and_text_binary_switch() {
938
    hermetic();
939
    let dir = tempfile::tempdir().unwrap();
940
    let root = dir.path();
941
    let repo = Repo::init(root).unwrap();
942
    write(root, "run.sh", b"#!/bin/sh\n");
943
    repo.commit("add script", &[]).unwrap();
944
    #[cfg(unix)]
945
    {
946
        use std::os::unix::fs::PermissionsExt;
947
        fs::set_permissions(root.join("run.sh"), fs::Permissions::from_mode(0o755)).unwrap();
948
        let s = repo.snapshot("status").unwrap();
949
        assert_eq!(
950
            statuses(&s),
951
            vec![("run.sh".into(), ChangeStatus::ModeChanged)]
952
        );
953
        let h = repo.commit("exec", &[]).unwrap();
954
        let snap = repo.load_state(&[h]).unwrap().materialize();
955
        assert!(snap.files["run.sh"].mode.exec);
956
    }
957
    // Text → binary → text.
958
    write(root, "run.sh", b"\0binary");
959
    let h = repo.commit("binary", &[]).unwrap();
960
    let snap = repo.load_state(&[h]).unwrap().materialize();
961
    assert!(snap.files["run.sh"].mode.opaque);
962
    write(root, "run.sh", b"text again\n");
963
    let h = repo.commit("text", &[]).unwrap();
964
    let snap = repo.load_state(&[h]).unwrap().materialize();
965
    assert!(!snap.files["run.sh"].mode.opaque);
966
    assert!(
967
        matches!(&snap.files["run.sh"].content, FileContent::Text { bytes, .. } if bytes == b"text again\n")
968
    );
969
    assert!(!snap.is_conflicted());
970
}
971
972
/// oxygen#87: a binary file given new contents and the executable bit in
973
/// one commit kept the contents and lost the bit.
974
#[cfg(unix)]
975
#[test]
976
fn a_binary_file_changed_and_made_executable_at_once_keeps_both() {
977
    use std::os::unix::fs::PermissionsExt;
978
    hermetic();
979
    let dir = tempfile::tempdir().unwrap();
980
    let root = dir.path();
981
    let repo = Repo::init(root).unwrap();
982
    write(root, "tool.exe", b"MZ\0one");
983
    repo.commit("add", &[]).unwrap();
984
    write(root, "tool.exe", b"MZ\0two");
985
    fs::set_permissions(root.join("tool.exe"), fs::Permissions::from_mode(0o755)).unwrap();
986
    let h = repo.commit("update and +x", &[]).unwrap();
987
    let snap = repo.load_state(&[h]).unwrap().materialize();
988
    let f = &snap.files["tool.exe"];
989
    assert!(f.mode.opaque && f.mode.exec, "{:?}", f.mode);
990
    assert!(
991
        repo.snapshot("status").unwrap().statuses.is_empty(),
992
        "nothing left to commit"
993
    );
994
}
995
996
/// Keyless step 4 (oxygenhub#241): an agent signing with a short-lived
997
/// key whose certificate an issuer gave pushes when the policy grants its
998
/// subject, and a fetch accepts what it attested; an expired certificate,
999
/// or a subject the policy does not grant, may not move the bookmark.
1000
#[test]
1001
fn a_certified_key_pushes_under_a_subject_grant() {
1002
    use crate::cert::{Certificate, SignedCertificate};
1003
    use crate::identity::Scope;
1004
    hermetic();
1005
    let dir = tempfile::tempdir().unwrap();
1006
    let root = dir.path();
1007
    let _origin = Repo::init(&root.join("origin")).unwrap();
1008
    let url = root.join("origin").to_string_lossy().to_string();
1009
    let mut a = Repo::clone(&url, &root.join("a"))
1010
        .unwrap()
1011
        .with_home(root.join("home-a"));
1012
    a.create_identity("Ada", "[email protected]", IdentityScope::User)
1013
        .unwrap();
1014
    write(&root.join("a"), "a.txt", b"a\n");
1015
    a.commit("a", &[]).unwrap();
1016
    a.policy_init().unwrap();
1017
    assert!(a.push("origin", false).unwrap().iter().all(|r| r.ok));
1018
    let hub_sk = SecretKey::generate();
1019
    let hub = hub_sk.identity("hub", "[email protected]", 1);
1020
    a.policy_grant_subject(
1021
        "agent:claude@ada",
1022
        hub.clone(),
1023
        Scope::CHANGES | Scope::REFS,
1024
        None,
1025
    )
1026
    .unwrap();
1027
    assert!(a
1028
        .push("origin", false)
1029
        .unwrap()
1030
        .iter()
1031
        .any(|r| r.name == "policy" && r.ok));
1032
1033
    let now = Hlc::now().wall_ms;
1034
    // An agent repository whose key the hub certified for `subject`, from
1035
    // `from` to `to`.
1036
    let agent = |name: &str, subject: &str, from: u64, to: u64| {
1037
        let mut r = Repo::clone(&url, &root.join(name))
1038
            .unwrap()
1039
            .with_home(root.join(format!("home-{name}")));
1040
        let (_, id) = r
1041
            .create_identity(name, "[email protected]", IdentityScope::User)
1042
            .unwrap();
1043
        let cert = SignedCertificate::sign(
1044
            Certificate {
1045
                key: id,
1046
                issuer: hub.hash(),
1047
                subject: subject.into(),
1048
                claims: vec![],
1049
                scope: Scope::CHANGES | Scope::REFS,
1050
                not_before: from,
1051
                expires: to,
1052
                grant: None,
1053
            },
1054
            &hub,
1055
            &hub_sk,
1056
        );
1057
        r.store().put_identity(&hub).unwrap();
1058
        r.store().put_certificate(&cert).unwrap();
1059
        write(&root.join(name), &format!("{name}.txt"), b"agent work\n");
1060
        r.commit("work", &[]).unwrap();
1061
        r
1062
    };
1063
1064
    let claude = agent("claude", "agent:claude@ada", now - 60_000, now + 600_000);
1065
    let r = claude.push("origin", false).unwrap();
1066
    assert!(r.iter().all(|x| x.ok), "{r:?}");
1067
    // Ada's fetch accepts the bookmark the certified key attested.
1068
    a.pull("origin").unwrap();
1069
    assert!(a.bookmark_heads().unwrap().iter().any(|h| a
1070
        .store()
1071
        .get_change(h)
1072
        .map(|c| c.message == "work")
1073
        .unwrap_or(false)));
1074
1075
    // Step 4c: a host with an acceptor key records when it accepted the
1076
    // certified update and serves it; a fetch checks the certificate at
1077
    // that time only when the certificate's issuer signed it for exactly
1078
    // this attestation, else at the attestation's own time.
1079
    let host = Repo::open(&root.join("origin"))
1080
        .unwrap()
1081
        .with_acceptor(hub.clone(), hub_sk.clone());
1082
    let (attest_ref, sa) = host.latest_ref_attest("main").unwrap().unwrap();
1083
    host.record_acceptance(&attest_ref).unwrap();
1084
    let served = host.remote_refs().unwrap();
1085
    let acc = served
1086
        .refs
1087
        .iter()
1088
        .find(|r| r.name == "main")
1089
        .unwrap()
1090
        .accepted
1091
        .clone()
1092
        .expect("served with the refs");
1093
    let signer = sa.sigs[0].key;
1094
    assert_eq!(
1095
        a.certified_time(&signer, &sa, Some(&acc)),
1096
        acc.attest.hlc.wall_ms
1097
    );
1098
    assert_eq!(a.certified_time(&signer, &sa, None), sa.attest.hlc.wall_ms);
1099
    let stranger_sk = SecretKey::generate();
1100
    let stranger = stranger_sk.identity("stranger", "s@x", 1);
1101
    let mut forged = acc.clone();
1102
    forged.sigs = vec![stranger_sk.sign(Domain::Attest, &stranger.hash(), &acc.attest.hash())];
1103
    assert_eq!(
1104
        a.certified_time(&signer, &sa, Some(&forged)),
1105
        sa.attest.hlc.wall_ms,
1106
        "not the issuer's"
1107
    );
1108
    let mut elsewhere = acc.clone();
1109
    elsewhere.attest.body = AttestBody::Accepted {
1110
        attest: ObjectRef([7; 32]),
1111
    };
1112
    elsewhere.sigs = vec![hub_sk.sign(Domain::Attest, &hub.hash(), &elsewhere.attest.hash())];
1113
    assert_eq!(
1114
        a.certified_time(&signer, &sa, Some(&elsewhere)),
1115
        sa.attest.hlc.wall_ms,
1116
        "another attestation's"
1117
    );
1118
    a.pull("origin").unwrap();
1119
    // gc keeps the acceptance with the attestation.
1120
    host.gc(true).unwrap();
1121
    assert!(host.acceptance_of(&attest_ref).unwrap().is_some());
1122
1123
    let late = agent("late", "agent:claude@ada", now - 1_200_000, now - 600_000);
1124
    let r = late.push("origin", false).unwrap();
1125
    assert!(
1126
        !r[0].ok && r[0].reason.contains("may not update"),
1127
        "an expired certificate: {r:?}"
1128
    );
1129
    let other = agent("other", "agent:mallory@ada", now - 60_000, now + 600_000);
1130
    let r = other.push("origin", false).unwrap();
1131
    assert!(
1132
        !r[0].ok && r[0].reason.contains("may not update"),
1133
        "a subject not granted: {r:?}"
1134
    );
1135
}
1136
1137
/// A tag made under one short-lived key and pushed under another: its
1138
/// signer travels with the push (identity and certificate), so a receiver
1139
/// that has never seen that key accepts it. A tag-only push by a keyless
1140
/// agent was refused "unknown key" (found releasing OxygenFlow 0.2.0).
1141
#[test]
1142
fn a_tag_signed_by_an_earlier_short_lived_key_is_pushed() {
1143
    use crate::cert::{Certificate, SignedCertificate};
1144
    use crate::identity::Scope;
1145
    hermetic();
1146
    let dir = tempfile::tempdir().unwrap();
1147
    let root = dir.path();
1148
    let _origin = Repo::init(&root.join("origin")).unwrap();
1149
    let url = root.join("origin").to_string_lossy().to_string();
1150
    let mut a = Repo::clone(&url, &root.join("a"))
1151
        .unwrap()
1152
        .with_home(root.join("home-a"));
1153
    a.create_identity("Ada", "[email protected]", IdentityScope::User)
1154
        .unwrap();
1155
    write(&root.join("a"), "a.txt", b"a\n");
1156
    a.commit("a", &[]).unwrap();
1157
    a.policy_init().unwrap();
1158
    assert!(a.push("origin", false).unwrap().iter().all(|r| r.ok));
1159
    let hub_sk = SecretKey::generate();
1160
    let hub = hub_sk.identity("hub", "[email protected]", 1);
1161
    a.policy_grant_subject(
1162
        "agent:claude@ada",
1163
        hub.clone(),
1164
        Scope::CHANGES | Scope::REFS,
1165
        Some("*"),
1166
    )
1167
    .unwrap();
1168
    assert!(a.push("origin", false).unwrap().iter().all(|r| r.ok));
1169
1170
    let now = Hlc::now().wall_ms;
1171
    let mut agent = Repo::clone(&url, &root.join("agent"))
1172
        .unwrap()
1173
        .with_home(root.join("home-agent"));
1174
    agent.store().put_identity(&hub).unwrap();
1175
    let certify = |agent: &Repo, id| {
1176
        let cert = SignedCertificate::sign(
1177
            Certificate {
1178
                key: id,
1179
                issuer: hub.hash(),
1180
                subject: "agent:claude@ada".into(),
1181
                claims: vec![],
1182
                scope: Scope::CHANGES | Scope::REFS,
1183
                not_before: now - 60_000,
1184
                expires: now + 600_000,
1185
                grant: None,
1186
            },
1187
            &hub,
1188
            &hub_sk,
1189
        );
1190
        agent.store().put_certificate(&cert).unwrap();
1191
    };
1192
    // The tag, under the first short-lived key.
1193
    let (first, first_id) = agent
1194
        .create_identity("claude", "[email protected]", IdentityScope::User)
1195
        .unwrap();
1196
    certify(&agent, first_id);
1197
    let heads = agent.bookmark_heads().unwrap();
1198
    agent.tag_create("v1", &heads, "first").unwrap();
1199
    // The push, under a second one (a later process's ten-minute key).
1200
    let (second, second_id) = agent
1201
        .create_identity("claude", "[email protected]", IdentityScope::User)
1202
        .unwrap();
1203
    assert_ne!(first, second);
1204
    certify(&agent, second_id);
1205
    agent
1206
        .set_user_config("author.signer", &second.to_hex())
1207
        .unwrap();
1208
    let host = Repo::open(&root.join("origin")).unwrap();
1209
    assert!(
1210
        host.store().get_identity(&first).is_err(),
1211
        "the host has never seen the tag's key"
1212
    );
1213
    let r = agent.push("origin", false).unwrap();
1214
    assert!(r.iter().all(|x| x.ok), "{r:?}");
1215
    let host = Repo::open(&root.join("origin")).unwrap();
1216
    assert!(
1217
        host.tag_refs().unwrap().iter().any(|t| t.name == "v1"),
1218
        "the tag arrived"
1219
    );
1220
}
1221
1222
/// oxygen#129: a short-lived key's tag is checked on a fetch at a time its
1223
/// signer did not choose, its issuer's acceptance, never at the time it
1224
/// claims nor at the fetch's (when the ten-minute certificate has long
1225
/// expired). Without an acceptance it is left out and said so; with one
1226
/// inside the certificate's window it is fetched however much later, and
1227
/// a host it is pushed on to keeps and serves the acceptance.
1228
#[test]
1229
fn a_short_lived_key_s_tag_is_fetched_at_its_issuer_s_acceptance() {
1230
    use crate::cert::{Certificate, SignedCertificate};
1231
    use crate::identity::Scope;
1232
    hermetic();
1233
    let dir = tempfile::tempdir().unwrap();
1234
    let root = dir.path();
1235
    let _origin = Repo::init(&root.join("origin")).unwrap();
1236
    let url = root.join("origin").to_string_lossy().to_string();
1237
    let mut a = Repo::clone(&url, &root.join("a"))
1238
        .unwrap()
1239
        .with_home(root.join("home-a"));
1240
    a.create_identity("Ada", "[email protected]", IdentityScope::User)
1241
        .unwrap();
1242
    write(&root.join("a"), "a.txt", b"a\n");
1243
    a.commit("a", &[]).unwrap();
1244
    a.policy_init().unwrap();
1245
    assert!(a.push("origin", false).unwrap().iter().all(|r| r.ok));
1246
    let hub_sk = SecretKey::generate();
1247
    let hub = hub_sk.identity("hub", "[email protected]", 1);
1248
    a.policy_grant_subject(
1249
        "agent:claude@ada",
1250
        hub.clone(),
1251
        Scope::CHANGES | Scope::REFS,
1252
        Some("*"),
1253
    )
1254
    .unwrap();
1255
    assert!(a.push("origin", false).unwrap().iter().all(|r| r.ok));
1256
1257
    let now = Hlc::now().wall_ms;
1258
    // An agent whose key the hub certified from `from` to `to`.
1259
    let agent = |name: &str, from: u64, to: u64| {
1260
        let mut r = Repo::clone(&url, &root.join(name))
1261
            .unwrap()
1262
            .with_home(root.join(format!("home-{name}")));
1263
        r.store().put_identity(&hub).unwrap();
1264
        let (_, id) = r
1265
            .create_identity(name, "[email protected]", IdentityScope::User)
1266
            .unwrap();
1267
        let cert = SignedCertificate::sign(
1268
            Certificate {
1269
                key: id,
1270
                issuer: hub.hash(),
1271
                subject: "agent:claude@ada".into(),
1272
                claims: vec![],
1273
                scope: Scope::CHANGES | Scope::REFS,
1274
                not_before: from,
1275
                expires: to,
1276
                grant: None,
1277
            },
1278
            &hub,
1279
            &hub_sk,
1280
        );
1281
        r.store().put_certificate(&cert).unwrap();
1282
        r
1283
    };
1284
1285
    // A tag by a key certified now, pushed to a host that records no
1286
    // acceptance (a path on disk): it lands, but a fetch has no time to
1287
    // check its certificate at, so it is left out and the fetch goes on.
1288
    let claude = agent("claude", now - 60_000, now + 600_000);
1289
    let heads = claude.bookmark_heads().unwrap();
1290
    claude.tag_create("v1", &heads, "one").unwrap();
1291
    let r = claude.push("origin", false).unwrap();
1292
    assert!(r.iter().all(|x| x.ok), "{r:?}");
1293
    let b = Repo::clone(&url, &root.join("b"))
1294
        .unwrap()
1295
        .with_home(root.join("home-b"));
1296
    let rep = b.fetch("origin").unwrap();
1297
    assert!(
1298
        rep.skipped
1299
            .iter()
1300
            .any(|(n, why)| n == "tags/v1" && why.contains("no time to check its certificate at")),
1301
        "{rep:?}"
1302
    );
1303
    assert_eq!(b.tag_heads("v1").unwrap(), None);
1304
1305
    // The host's acceptance, signed by the certificate's issuer, served
1306
    // with the tag: fetched.
1307
    let host = Repo::open(&root.join("origin"))
1308
        .unwrap()
1309
        .with_acceptor(hub.clone(), hub_sk.clone());
1310
    let (v1, _) = host.tag_attest("v1").unwrap().unwrap();
1311
    host.record_acceptance(&v1).unwrap();
1312
    let served = host.tag_refs().unwrap();
1313
    assert!(served
1314
        .iter()
1315
        .any(|t| t.name == "v1" && t.accepted.is_some()));
1316
    let rep = b.fetch("origin").unwrap();
1317
    assert!(rep.skipped.is_empty(), "{rep:?}");
1318
    assert_eq!(b.tag_heads("v1").unwrap(), Some(heads.clone()));
1319
    // gc keeps the acceptance with the tag.
1320
    host.gc(true).unwrap();
1321
    assert!(host.acceptance_of(&v1).unwrap().is_some());
1322
1323
    // Long after: a key whose certificate expired an hour ago may not
1324
    // create a tag now.
1325
    let late = agent("late", now - 7_200_000, now - 3_600_000);
1326
    late.tag_create("v2", &heads, "two").unwrap();
1327
    let r = late.push("origin", false).unwrap();
1328
    assert!(
1329
        r.iter()
1330
            .any(|x| x.name == "tags/v2" && !x.ok && x.reason.contains("may not create")),
1331
        "{r:?}"
1332
    );
1333
    // With its issuer's acceptance from inside the window (as a hub gave
1334
    // it then, passed on to another host), it is taken at that time: by
1335
    // the host it is pushed to, which keeps it, and by a fresh clone.
1336
    let (v2, _) = late.tag_attest("v2").unwrap().unwrap();
1337
    let acc = Attest {
1338
        repo: late.id().unwrap(),
1339
        hlc: Hlc {
1340
            wall_ms: now - 5_400_000,
1341
            logical: 0,
1342
        },
1343
        body: AttestBody::Accepted { attest: v2 },
1344
    };
1345
    let sig = hub_sk.sign(Domain::Attest, &hub.hash(), &acc.hash());
1346
    // One by any other key gives no time.
1347
    let stranger_sk = SecretKey::generate();
1348
    let stranger = stranger_sk.identity("stranger", "[email protected]", 1);
1349
    let forged = stranger_sk.sign(Domain::Attest, &stranger.hash(), &acc.hash());
1350
    late.keep_acceptance(
1351
        &v2,
1352
        &SignedAttest {
1353
            attest: acc.clone(),
1354
            sigs: vec![forged],
1355
        },
1356
    )
1357
    .unwrap();
1358
    let r = late.push("origin", false).unwrap();
1359
    assert!(
1360
        r.iter().any(|x| x.name == "tags/v2" && !x.ok),
1361
        "not the issuer's: {r:?}"
1362
    );
1363
    let theirs = SignedAttest {
1364
        attest: acc,
1365
        sigs: vec![sig],
1366
    };
1367
    // Kept beside the stranger's: the issuer's is the one sent.
1368
    late.keep_acceptance(&v2, &theirs).unwrap();
1369
    let r = late.push("origin", false).unwrap();
1370
    // (Its re-attestation of main is refused: an expired key moves no
1371
    // bookmark.)
1372
    assert!(r.iter().any(|x| x.name == "tags/v2" && x.ok), "{r:?}");
1373
    let host = Repo::open(&root.join("origin")).unwrap();
1374
    let (hv2, _) = host.tag_attest("v2").unwrap().unwrap();
1375
    assert_eq!(hv2, v2);
1376
    assert!(host
1377
        .store()
1378
        .index_get_pub("accepted", &v2)
1379
        .unwrap()
1380
        .contains(&theirs.attest.hash()));
1381
    let c = Repo::clone(&url, &root.join("c"))
1382
        .unwrap()
1383
        .with_home(root.join("home-c"));
1384
    assert_eq!(c.tag_heads("v2").unwrap(), Some(heads.clone()));
1385
    assert_eq!(c.tag_heads("v1").unwrap(), Some(heads));
1386
}
1387
1388
/// oxygenhub#266: a short-lived key its issuer certified moves a bookmark
1389
/// and signs no change (a keyless agent naming a bookmark). A third
1390
/// party's clone gets the key's identity, its certificate and the
1391
/// issuer's identity with the fetch, so the policy's subject grant
1392
/// authorizes the move and the signature verifies.
1393
#[test]
1394
fn a_bookmark_moved_by_a_certified_key_alone_is_fetched() {
1395
    use crate::cert::{Certificate, SignedCertificate};
1396
    use crate::identity::Scope;
1397
    hermetic();
1398
    let dir = tempfile::tempdir().unwrap();
1399
    let root = dir.path();
1400
    let _origin = Repo::init(&root.join("origin")).unwrap();
1401
    let url = root.join("origin").to_string_lossy().to_string();
1402
    let mut a = Repo::clone(&url, &root.join("a"))
1403
        .unwrap()
1404
        .with_home(root.join("home-a"));
1405
    a.create_identity("Ada", "[email protected]", IdentityScope::User)
1406
        .unwrap();
1407
    write(&root.join("a"), "a.txt", b"a\n");
1408
    a.commit("a", &[]).unwrap();
1409
    a.policy_init().unwrap();
1410
    assert!(a.push("origin", false).unwrap().iter().all(|r| r.ok));
1411
    let hub_sk = SecretKey::generate();
1412
    let hub = hub_sk.identity("hub", "[email protected]", 1);
1413
    a.policy_grant_subject(
1414
        "agent:claude@ada",
1415
        hub.clone(),
1416
        Scope::CHANGES | Scope::REFS,
1417
        None,
1418
    )
1419
    .unwrap();
1420
    assert!(a.push("origin", false).unwrap().iter().all(|r| r.ok));
1421
1422
    let now = Hlc::now().wall_ms;
1423
    let mut agent = Repo::clone(&url, &root.join("agent"))
1424
        .unwrap()
1425
        .with_home(root.join("home-agent"));
1426
    let (key, id) = agent
1427
        .create_identity("claude", "[email protected]", IdentityScope::User)
1428
        .unwrap();
1429
    let cert = SignedCertificate::sign(
1430
        Certificate {
1431
            key: id,
1432
            issuer: hub.hash(),
1433
            subject: "agent:claude@ada".into(),
1434
            claims: vec![],
1435
            scope: Scope::CHANGES | Scope::REFS,
1436
            not_before: now - 60_000,
1437
            expires: now + 600_000,
1438
            grant: None,
1439
        },
1440
        &hub,
1441
        &hub_sk,
1442
    );
1443
    agent.store().put_identity(&hub).unwrap();
1444
    agent.store().put_certificate(&cert).unwrap();
1445
    let heads = agent.bookmark_heads().unwrap();
1446
    agent.bookmark_create("agent-work", Some(&heads)).unwrap();
1447
    let r = agent.push_bookmark("origin", "agent-work", false).unwrap();
1448
    assert!(r.iter().all(|x| x.ok), "{r:?}");
1449
    let host = Repo::open(&root.join("origin")).unwrap();
1450
    let (_, sa) = host.latest_ref_attest("agent-work").unwrap().unwrap();
1451
    assert_eq!(sa.sigs[0].key, key, "the certified key alone moved it");
1452
1453
    // A fetch naming no change brings the certificate and both identities.
1454
    let bundle = host.bundle_raw_for(&[], None).unwrap();
1455
    assert!(bundle.changes.is_empty() && bundle.raw_changes.is_empty());
1456
    assert_eq!(bundle.certificates.len(), 1);
1457
    for k in [key, hub.hash()] {
1458
        assert!(bundle
1459
            .objects
1460
            .iter()
1461
            .any(|(t, b)| *t == ObjectType::Identity && hash_object(*t, b) == k));
1462
    }
1463
1464
    let c = Repo::clone(&url, &root.join("c")).unwrap();
1465
    let tracked = c.view().unwrap().remotes["origin"].clone();
1466
    assert_eq!(
1467
        tracked.get("agent-work"),
1468
        host.view().unwrap().bookmarks.get("agent-work")
1469
    );
1470
    assert!(c.store().certificate_of(&key).unwrap().is_some());
1471
}
1472
1473
/// Trusted time (oxygenhub#240, spec §14.8): a fetched attestation by a
1474
/// short-lived key is judged at its integrated time, the earliest time a
1475
/// pinned witness cosigned a checkpoint holding it. A certificate valid
1476
/// then but expired now passes; a witness this user does not trust gives
1477
/// no time (the earlier rule, said so); a backdated attestation is noted;
1478
/// an answer without the new fields is judged as before.
1479
#[test]
1480
fn a_fetched_attestation_is_judged_at_its_integrated_time() {
1481
    use super::transparency::LogCheck;
1482
    use crate::cert::{Certificate, SignedCertificate};
1483
    use crate::identity::Scope;
1484
    use crate::protocol::{Integration, Logged, RefsResponse, RemoteRef};
1485
    use crate::tlog::{self, Checkpoint, Entry, Hash, Integrated, Note};
1486
    hermetic();
1487
    let dir = tempfile::tempdir().unwrap();
1488
    let root = dir.path();
1489
    let mut a = Repo::init(&root.join("a"))
1490
        .unwrap()
1491
        .with_home(root.join("home-a"));
1492
    a.create_identity("Ada", "[email protected]", IdentityScope::User)
1493
        .unwrap();
1494
    write(&root.join("a"), "a.txt", b"a\n");
1495
    a.commit("a", &[]).unwrap();
1496
    a.policy_init().unwrap();
1497
    let issuer_sk = SecretKey::generate();
1498
    let issuer = issuer_sk.identity("hub", "[email protected]", 1);
1499
    a.policy_grant_subject(
1500
        "agent:claude@ada",
1501
        issuer.clone(),
1502
        Scope::CHANGES | Scope::REFS,
1503
        None,
1504
    )
1505
    .unwrap();
1506
    let p = a.current_policy().unwrap().unwrap().1.policy;
1507
1508
    // An agent key the issuer certified for ten minutes two hours ago.
1509
    let now = Hlc::now().wall_ms;
1510
    let t0 = now - 2 * 3_600_000;
1511
    let agent_sk = SecretKey::generate();
1512
    let agent = agent_sk.identity("claude", "[email protected]", t0);
1513
    let cert = SignedCertificate::sign(
1514
        Certificate {
1515
            key: agent.clone(),
1516
            issuer: issuer.hash(),
1517
            subject: "agent:claude@ada".into(),
1518
            claims: vec![],
1519
            scope: Scope::CHANGES | Scope::REFS,
1520
            not_before: t0,
1521
            expires: t0 + 600_000,
1522
            grant: None,
1523
        },
1524
        &issuer,
1525
        &issuer_sk,
1526
    );
1527
    a.store().put_identity(&agent).unwrap();
1528
    a.store().put_certificate(&cert).unwrap();
1529
    let signer = agent.hash();
1530
    let attested = |claimed: u64| {
1531
        let attest = Attest {
1532
            repo: a.id().unwrap(),
1533
            hlc: Hlc {
1534
                wall_ms: claimed,
1535
                logical: 0,
1536
            },
1537
            body: AttestBody::Ref {
1538
                name: "main".into(),
1539
                old_state: ObjectRef([1; 32]),
1540
                new_state: ObjectRef([2; 32]),
1541
                serial: 1,
1542
            },
1543
        };
1544
        let sig = agent_sk.sign(Domain::Attest, &signer, &attest.hash());
1545
        SignedAttest {
1546
            attest,
1547
            sigs: vec![sig],
1548
        }
1549
    };
1550
1551
    // The hub's log: eight entries, the attestation's at 3, the latest
1552
    // checkpoint of 8, and one of 4 that witnesses cosigned.
1553
    let log_sk = SecretKey::generate();
1554
    let log_key = log_sk.identity("hub.example", "[email protected]", 1);
1555
    let origin = "hub.example/log";
1556
    let hub = "https://hub.example";
1557
    let url = "https://hub.example/ada/a";
1558
    let w_sk = SecretKey::generate();
1559
    let w = w_sk.identity("w", "[email protected]", 1);
1560
    let stranger_sk = SecretKey::generate();
1561
    let stranger = stranger_sk.identity("s", "[email protected]", 1);
1562
    let sa = attested(t0 + 300_000);
1563
    let entry_of = |i: u64| {
1564
        let (kind, object) = if i == 3 {
1565
            ("ref", sa.attest.hash())
1566
        } else {
1567
            ("seal", ObjectRef([i as u8; 32]))
1568
        };
1569
        Entry {
1570
            kind: kind.into(),
1571
            repo: sa.attest.repo,
1572
            object,
1573
            signers: vec![signer],
1574
            received: t0 + 300_000,
1575
        }
1576
        .encode()
1577
    };
1578
    let mut stored: Vec<Hash> = Vec::new();
1579
    for i in 0..8 {
1580
        let add = tlog::stored_hashes_for_leaf(i, tlog::leaf_hash(&entry_of(i)), &stored).unwrap();
1581
        stored.extend(add);
1582
    }
1583
    let note_of = |n: u64, cosigners: &[(&str, &Identity, &SecretKey, u64)]| {
1584
        let mut note = Checkpoint {
1585
            origin: origin.into(),
1586
            size: n,
1587
            root: tlog::tree_hash(n, &stored).unwrap(),
1588
            extensions: vec![],
1589
        }
1590
        .sign(&log_key, &log_sk)
1591
        .unwrap();
1592
        for (name, id, sk, t) in cosigners {
1593
            note.sigs
1594
                .extend(tlog::cosign(&note.text, name, id, sk, *t).unwrap());
1595
        }
1596
        note.encode()
1597
    };
1598
    let latest = note_of(8, &[]);
1599
    let witnessed_at = (t0 + 360_000) / 1000;
1600
    let cosigned = note_of(
1601
        4,
1602
        &[
1603
            ("w.example", &w, &w_sk, witnessed_at),
1604
            ("s.example", &stranger, &stranger_sk, 1),
1605
        ],
1606
    );
1607
    let answer = |integration: Vec<Integration>, witnesses: Vec<(String, Vec<u8>)>| RefsResponse {
1608
        refs: vec![RemoteRef {
1609
            name: "main".into(),
1610
            state: ObjectRef([2; 32]),
1611
            heads: vec![],
1612
            attestation: Some(sa.clone()),
1613
            last_serial: None,
1614
            accepted: None,
1615
            logged: Some(Logged {
1616
                index: 3,
1617
                entry: entry_of(3),
1618
                proof: tlog::prove_inclusion(8, 3, &stored).unwrap(),
1619
            }),
1620
            integration,
1621
        }],
1622
        log: Some(latest.clone()),
1623
        witnesses,
1624
        ..RefsResponse::default()
1625
    };
1626
    let proof4 = tlog::prove_inclusion(4, 3, &stored).unwrap();
1627
    let served = vec![Integration {
1628
        note: cosigned.clone(),
1629
        proof: proof4.clone(),
1630
    }];
1631
    let listed = vec![("w.example".to_string(), w.encode())];
1632
    // This user saw the hub's log before (pinned, so nothing is fetched).
1633
    a.remember_log(hub, &log_key, &Note::parse(&latest).unwrap())
1634
        .unwrap();
1635
1636
    // The witness is pinned on first sight, silently; the stranger's
1637
    // earlier cosignature counts for nothing.
1638
    let resp = answer(served.clone(), listed.clone());
1639
    let lc = a.check_log(url, None, &resp).unwrap();
1640
    assert!(lc.notes.is_empty(), "{:?}", lc.notes);
1641
    let t = lc.time_of("main").unwrap();
1642
    assert_eq!((t.time, t.witness.as_str()), (witnessed_at, "w.example"));
1643
    // The certificate expired an hour and fifty minutes ago, but covered
1644
    // the integrated time: accepted, and nothing to say.
1645
    assert!(cert.cert.expires < now);
1646
    let mut notes = Vec::new();
1647
    a.authorize_in_time(&p, "origin", &resp.refs[0], &sa, &signer, &lc, &mut notes)
1648
        .unwrap();
1649
    assert!(notes.is_empty(), "{notes:?}");
1650
1651
    // Only the stranger cosigned: no witnessed time, so the earlier rule
1652
    // (the attestation's own time, inside the window), said so.
1653
    let lonely = vec![Integration {
1654
        note: note_of(4, &[("s.example", &stranger, &stranger_sk, 1)]),
1655
        proof: proof4.clone(),
1656
    }];
1657
    let resp = answer(lonely, vec![]);
1658
    let lc = a.check_log(url, None, &resp).unwrap();
1659
    assert!(lc
1660
        .time_of("main")
1661
        .unwrap_err()
1662
        .contains("no witness this user trusts"));
1663
    let mut notes = Vec::new();
1664
    a.authorize_in_time(&p, "origin", &resp.refs[0], &sa, &signer, &lc, &mut notes)
1665
        .unwrap();
1666
    assert!(
1667
        notes.len() == 1 && notes[0].contains("not at a witnessed time"),
1668
        "{notes:?}"
1669
    );
1670
1671
    // A witness listed later under the pinned name with another key is
1672
    // pinned with a note, as a new log key is.
1673
    let resp = answer(
1674
        served.clone(),
1675
        vec![("w.example".into(), stranger.encode())],
1676
    );
1677
    let lc = a.check_log(url, None, &resp).unwrap();
1678
    assert!(
1679
        lc.notes.iter().any(|n| n.contains("another key")),
1680
        "{:?}",
1681
        lc.notes
1682
    );
1683
    assert!(
1684
        lc.time_of("main").is_err(),
1685
        "w's cosignature is by its old key"
1686
    );
1687
    a.check_log(url, None, &answer(served.clone(), listed.clone()))
1688
        .unwrap();
1689
1690
    // An old peer's answer: no log, no witnesses, no integration. Judged
1691
    // as before, silently.
1692
    let mut old = answer(vec![], vec![]);
1693
    old.log = None;
1694
    old.refs[0].logged = None;
1695
    let lc = a.check_log(url, None, &old).unwrap();
1696
    assert!(!lc.kept && lc.notes.is_empty());
1697
    let mut notes = Vec::new();
1698
    a.authorize_in_time(&p, "origin", &old.refs[0], &sa, &signer, &lc, &mut notes)
1699
        .unwrap();
1700
    assert!(notes.is_empty(), "{notes:?}");
1701
1702
    // Judged at given integrated times.
1703
    let at = |secs_after_t0: u64| {
1704
        let mut times = std::collections::HashMap::new();
1705
        times.insert(
1706
            "main".to_string(),
1707
            Ok(Integrated {
1708
                time: (t0 + secs_after_t0 * 1000) / 1000,
1709
                witness: "w.example".into(),
1710
                size: 4,
1711
            }),
1712
        );
1713
        LogCheck {
1714
            kept: true,
1715
            times,
1716
            ..LogCheck::default()
1717
        }
1718
    };
1719
    let judged = |sa: &SignedAttest, lc: &LogCheck| {
1720
        let mut notes = Vec::new();
1721
        a.authorize_in_time(&p, "origin", &old.refs[0], sa, &signer, lc, &mut notes)
1722
            .map(|_| notes)
1723
    };
1724
    // Claimed inside the window, first witnessed an hour later, after
1725
    // the certificate expired: backdated, or held back. Accepted by the
1726
    // earlier rule while logs are new, with both said.
1727
    let notes = judged(&sa, &at(3600)).unwrap();
1728
    assert!(
1729
        notes
1730
            .iter()
1731
            .any(|n| n.contains("had lapsed when witness w.example"))
1732
            && notes
1733
                .iter()
1734
                .any(|n| n.contains("55 minutes before witness")),
1735
        "{notes:?}"
1736
    );
1737
    // Claimed after the certificate expired, but witnessed inside its
1738
    // window: the clock the signer did not choose decides. The gap is
1739
    // still noted.
1740
    let fast = attested(now);
1741
    let notes = judged(&fast, &at(400)).unwrap();
1742
    assert!(
1743
        notes.len() == 1 && notes[0].contains("after witness w.example saw it"),
1744
        "{notes:?}"
1745
    );
1746
    // Claimed and witnessed after it expired: refused, as before.
1747
    assert!(judged(&fast, &at(3600)).is_err());
1748
    // A gap within ten minutes is nothing to note.
1749
    assert!(judged(&sa, &at(500)).unwrap().is_empty());
1750
}
1751
1752
/// Keyless step 5 (oxygenhub#241): an agent's fresh key, certified for a
1753
/// subject the author granted, seals changes in the author's name; with
1754
/// no grant, a stranger's, or one that had ended, it is neither the
1755
/// author nor a delegate.
1756
#[test]
1757
fn a_certified_key_acts_for_its_author_under_a_grant() {
1758
    use crate::cert::{Certificate, Grant, SignedCertificate, SignedGrant};
1759
    use crate::identity::{Identity, Scope};
1760
    hermetic();
1761
    let dir = tempfile::tempdir().unwrap();
1762
    let root = dir.path();
1763
    let _origin = Repo::init(&root.join("origin")).unwrap();
1764
    let url = root.join("origin").to_string_lossy().to_string();
1765
    let mut a = Repo::clone(&url, &root.join("a"))
1766
        .unwrap()
1767
        .with_home(root.join("home-a"));
1768
    let (ada, _) = a
1769
        .create_identity("Ada", "[email protected]", IdentityScope::User)
1770
        .unwrap();
1771
    write(&root.join("a"), "a.txt", b"a\n");
1772
    a.commit("a", &[]).unwrap();
1773
    a.policy_init().unwrap();
1774
    assert!(a.push("origin", false).unwrap().iter().all(|r| r.ok));
1775
    let hub_sk = SecretKey::generate();
1776
    let hub = hub_sk.identity("hub", "[email protected]", 1);
1777
    a.policy_grant_subject(
1778
        "agent:claude@ada",
1779
        hub.clone(),
1780
        Scope::CHANGES | Scope::REFS,
1781
        None,
1782
    )
1783
    .unwrap();
1784
    assert!(a.push("origin", false).unwrap().iter().all(|r| r.ok));
1785
    let (_, ada_sk) = a.secret_key().unwrap().unwrap();
1786
    let ada_id = a.identity(&ada).unwrap();
1787
1788
    let now = Hlc::now().wall_ms;
1789
    let grant = |by: &Identity, sk: &SecretKey, from: u64, to: u64| {
1790
        SignedGrant::sign(
1791
            Grant {
1792
                grantor: by.hash(),
1793
                subject: "agent:claude@ada".into(),
1794
                issuer: hub.hash(),
1795
                scope: Scope::CHANGES | Scope::SEAL,
1796
                not_before: from,
1797
                expires: to,
1798
            },
1799
            by,
1800
            sk,
1801
        )
1802
    };
1803
    // Ada's work as an agent runs it: Ada the author, a fresh key the hub
1804
    // certified (with `g` inside) the signer.
1805
    let agent = |name: &str, g: Option<SignedGrant>| {
1806
        let mut r = Repo::clone(&url, &root.join(name))
1807
            .unwrap()
1808
            .with_home(root.join(format!("home-{name}")));
1809
        let (key, id) = r
1810
            .create_identity(name, "[email protected]", IdentityScope::User)
1811
            .unwrap();
1812
        r.set_user_config("author.key", &ada.to_hex()).unwrap();
1813
        r.set_user_config("author.signer", &key.to_hex()).unwrap();
1814
        let cert = SignedCertificate::sign(
1815
            Certificate {
1816
                key: id,
1817
                issuer: hub.hash(),
1818
                subject: "agent:claude@ada".into(),
1819
                claims: vec![],
1820
                scope: Scope::CHANGES | Scope::REFS | Scope::SEAL,
1821
                not_before: now - 60_000,
1822
                expires: now + 600_000,
1823
                grant: g,
1824
            },
1825
            &hub,
1826
            &hub_sk,
1827
        );
1828
        r.store().put_identity(&hub).unwrap();
1829
        r.store().put_certificate(&cert).unwrap();
1830
        write(&root.join(name), &format!("{name}.txt"), b"agent work\n");
1831
        let h = r.commit("work", &[]).unwrap();
1832
        assert_eq!(r.store().get_change_meta(&h).unwrap().author, ada);
1833
        (r, key, h)
1834
    };
1835
1836
    let (claude, key, h) = agent(
1837
        "claude",
1838
        Some(grant(&ada_id, &ada_sk, now - 60_000, now + 86_400_000)),
1839
    );
1840
    let r = claude.push("origin", false).unwrap();
1841
    assert!(r.iter().all(|x| x.ok), "{r:?}");
1842
    let host = Repo::open(&root.join("origin")).unwrap();
1843
    assert!(
1844
        matches!(
1845
            host.authenticate_change(&h).unwrap(),
1846
            SignatureStatus::Valid { key: k, sealed: true, name, .. } if k == key && name == "agent:claude@ada"
1847
        ),
1848
        "named by its certificate's subject"
1849
    );
1850
    a.pull("origin").unwrap();
1851
    assert!(matches!(
1852
        a.authenticate_change(&h).unwrap(),
1853
        SignatureStatus::Valid { key: k, .. } if k == key
1854
    ));
1855
1856
    let (none, _, _) = agent("none", None);
1857
    let r = none.push("origin", false).unwrap();
1858
    assert!(r.iter().all(|x| !x.ok), "no grant: {r:?}");
1859
    let mallory_sk = SecretKey::generate();
1860
    let mallory = mallory_sk.identity("Mallory", "[email protected]", 1);
1861
    let (stranger, _, _) = agent(
1862
        "stranger",
1863
        Some(grant(&mallory, &mallory_sk, now - 60_000, now + 600_000)),
1864
    );
1865
    let r = stranger.push("origin", false).unwrap();
1866
    assert!(r.iter().all(|x| !x.ok), "a stranger's grant: {r:?}");
1867
    let (ended, _, eh) = agent(
1868
        "ended",
1869
        Some(grant(&ada_id, &ada_sk, now - 7_200_000, now - 3_600_000)),
1870
    );
1871
    let r = ended.push("origin", false).unwrap();
1872
    assert!(r.iter().all(|x| !x.ok), "an ended grant: {r:?}");
1873
    assert!(matches!(
1874
        ended.authenticate_change(&eh).unwrap(),
1875
        SignatureStatus::Invalid(e) if e.contains("grant did not cover")
1876
    ));
1877
}
1878
1879
#[test]
1880
fn trust_policy_governs_pushes_and_fetches() {
1881
    hermetic();
1882
    let dir = tempfile::tempdir().unwrap();
1883
    let root = dir.path();
1884
    let origin = Repo::init(&root.join("origin")).unwrap();
1885
    let url = root.join("origin").to_string_lossy().to_string();
1886
1887
    // A is the root. Before the policy, an unsigned push from B is fine.
1888
    let mut a = Repo::clone(&url, &root.join("a"))
1889
        .unwrap()
1890
        .with_home(root.join("home-a"));
1891
    let (key_a, _) = a
1892
        .create_identity("Ada", "[email protected]", IdentityScope::User)
1893
        .unwrap();
1894
    let mut b = Repo::clone(&url, &root.join("b"))
1895
        .unwrap()
1896
        .with_home(root.join("home-b"));
1897
    write(&root.join("b"), "b.txt", b"b\n");
1898
    b.commit("unsigned before policy", &[]).unwrap();
1899
    assert!(b.push("origin", false).unwrap()[0].ok);
1900
    origin.refresh().unwrap();
1901
1902
    // A creates the policy and pushes it; origin now enforces it.
1903
    write(&root.join("a"), "a.txt", b"a\n");
1904
    a.commit("a", &[]).unwrap();
1905
    let sp = a.policy_init().unwrap();
1906
    assert_eq!(sp.policy.serial, 1);
1907
    a.pull("origin").unwrap();
1908
    let results = a.push("origin", false).unwrap();
1909
    origin.refresh().unwrap();
1910
    assert!(results.iter().all(|r| r.ok), "{results:?}");
1911
    assert_eq!(origin.current_policy().unwrap().unwrap().1.policy.serial, 1);
1912
1913
    // B pulls the policy. Without an identity B cannot push at all.
1914
    b.pull("origin").unwrap();
1915
    assert!(
1916
        b.current_policy().unwrap().is_some(),
1917
        "the policy arrived with the fetch"
1918
    );
1919
    assert!(b.push("origin", false).is_err());
1920
    // With an identity the policy does not list, the push is rejected by origin.
1921
    let (key_b, id_b) = b
1922
        .create_identity("Bob", "[email protected]", IdentityScope::User)
1923
        .unwrap();
1924
    write(&root.join("b"), "b.txt", b"b2\n");
1925
    let h_b2 = b.commit("b2 as Bob", &[]).unwrap();
1926
    assert_eq!(b.store().get_change(&h_b2).unwrap().author, key_b);
1927
    let r = b.push("origin", false).unwrap();
1928
    origin.refresh().unwrap();
1929
    assert!(
1930
        !r[0].ok && r[0].reason.contains("may not update"),
1931
        "{:?}",
1932
        r
1933
    );
1934
1935
    // A grants B (identity handed over as a file) and publishes the policy.
1936
    let sp = a.policy_grant(id_b.clone(), None).unwrap();
1937
    assert_eq!(sp.policy.serial, 2);
1938
    let r = a.push("origin", false).unwrap();
1939
    origin.refresh().unwrap();
1940
    assert!(r.iter().any(|x| x.name == "policy" && x.ok), "{r:?}");
1941
    // B must fetch the new policy before pushing.
1942
    assert!(b
1943
        .push("origin", false)
1944
        .unwrap_or_else(|e| vec![RefResult {
1945
            name: "main".into(),
1946
            ok: false,
1947
            reason: e.to_string()
1948
        }])
1949
        .iter()
1950
        .all(|x| !x.ok));
1951
    b.pull("origin").unwrap();
1952
    assert_eq!(b.current_policy().unwrap().unwrap().1.policy.serial, 2);
1953
    let r = b.push("origin", false).unwrap();
1954
    origin.refresh().unwrap();
1955
    assert!(r[0].ok, "{:?}", r);
1956
    // Origin verified B's change under the policy.
1957
    let heads = origin.bookmark_heads().unwrap();
1958
    for h in &heads {
1959
        let c = origin.store().get_change(h).unwrap();
1960
        if c.author == key_b {
1961
            origin
1962
                .change_allowed(
1963
                    h,
1964
                    &origin.current_policy().unwrap().unwrap().1.policy,
1965
                    "main",
1966
                )
1967
                .unwrap();
1968
        }
1969
    }
1970
1971
    // A policy signed by a non-root (B) is refused, as is a replayed serial.
1972
    let mut forged = b.current_policy().unwrap().unwrap().1.policy.clone();
1973
    forged.serial = 3;
1974
    forged.roots = vec![key_b];
1975
    let fh = forged.hash();
1976
    let (_, sk_b) = b.secret_key().unwrap().unwrap();
1977
    let forged = SignedPolicy {
1978
        policy: forged,
1979
        sigs: vec![sk_b.sign(Domain::Policy, &key_b, &fh)],
1980
    };
1981
    let r = origin
1982
        .receive_push(Bundle::default(), vec![], Some(forged), vec![])
1983
        .unwrap();
1984
    assert!(!r[0].ok && r[0].reason.contains("root"), "{:?}", r);
1985
    let stale = a.current_policy().unwrap().unwrap().1;
1986
    let mut old = stale.clone();
1987
    old.policy.serial = 1;
1988
    let r = origin
1989
        .receive_push(Bundle::default(), vec![], Some(old), vec![])
1990
        .unwrap();
1991
    assert!(!r[0].ok && r[0].reason.contains("serial"), "{:?}", r);
1992
1993
    // A revokes B; after B pulls the policy, B's pushes are refused again.
1994
    a.pull("origin").unwrap();
1995
    a.policy_revoke(&key_b).unwrap();
1996
    let r = a.push("origin", false).unwrap();
1997
    origin.refresh().unwrap();
1998
    assert!(r.iter().any(|x| x.name == "policy" && x.ok), "{r:?}");
1999
    b.pull("origin").unwrap();
2000
    write(&root.join("b"), "b.txt", b"b3\n");
2001
    b.commit("b3", &[]).unwrap();
2002
    let r = b.push("origin", false).unwrap();
2003
    origin.refresh().unwrap();
2004
    assert!(!r[0].ok, "{:?}", r);
2005
2006
    // A clone by a third party receives and verifies everything.
2007
    let c = Repo::clone(&url, &root.join("c"))
2008
        .unwrap()
2009
        .with_home(root.join("home-c"));
2010
    assert_eq!(c.current_policy().unwrap().unwrap().1.policy.serial, 3);
2011
    assert!(c
2012
        .current_policy()
2013
        .unwrap()
2014
        .unwrap()
2015
        .1
2016
        .policy
2017
        .roots
2018
        .contains(&key_a));
2019
    assert!(!c.snapshot("status").unwrap().changed);
2020
}
2021
2022
/// oxygen#66: a gc says what it is doing, phase by phase.
2023
#[test]
2024
fn gc_reports_its_phases() {
2025
    hermetic();
2026
    let dir = tempfile::tempdir().unwrap();
2027
    let repo = Repo::init(dir.path()).unwrap();
2028
    for i in 0..3 {
2029
        write(
2030
            dir.path(),
2031
            &format!("f{i}.txt"),
2032
            format!("{i}\n").as_bytes(),
2033
        );
2034
        repo.commit(&format!("c{i}"), &[]).unwrap();
2035
    }
2036
    let mut phases = Vec::new();
2037
    repo.gc_with(true, &mut |p| phases.push(p.to_string()))
2038
        .unwrap();
2039
    assert_eq!(phases[0], "finding what is reachable", "{phases:?}");
2040
    assert!(
2041
        phases.iter().any(|p| p.starts_with("pruning")),
2042
        "{phases:?}"
2043
    );
2044
    assert!(
2045
        phases.iter().any(|p| p.starts_with("packing 0 of ")),
2046
        "{phases:?}"
2047
    );
2048
    assert!(
2049
        phases
2050
            .iter()
2051
            .any(|p| p.starts_with("writing the index of ")),
2052
        "{phases:?}"
2053
    );
2054
}
2055
2056
#[test]
2057
fn gc_packs_objects_and_history_still_works() {
2058
    hermetic();
2059
    let dir = tempfile::tempdir().unwrap();
2060
    let root = dir.path();
2061
    let mut repo = Repo::init(root).unwrap().with_home(root.join("home"));
2062
    repo.create_identity("Ada", "a@b", IdentityScope::User)
2063
        .unwrap();
2064
    repo.set_user_config("core.sign", "change").unwrap();
2065
    write(root, "a.txt", b"one\n");
2066
    let h1 = repo.commit("one", &[]).unwrap();
2067
    write(root, "a.txt", b"two\n");
2068
    write(root, "big.bin", &vec![0u8; 100_000]);
2069
    let h2 = repo.commit("two", &[]).unwrap();
2070
    // Several snapshots leave superseded working-copy versions behind.
2071
    for i in 0..5 {
2072
        write(root, "a.txt", format!("two\n{i}\n").as_bytes());
2073
        repo.snapshot("status").unwrap();
2074
    }
2075
    write(root, "a.txt", b"two\n");
2076
    repo.snapshot("status").unwrap();
2077
    let before = repo.store().list().unwrap();
2078
    assert!(repo.store().loose_count().unwrap() > 0);
2079
2080
    // With the default retention every operation's view is a root: nothing prunes.
2081
    let r = repo.gc(true).unwrap();
2082
    assert_eq!(r.packed.objects, before.len());
2083
    assert_eq!(r.pruned.objects, 0);
2084
    assert_eq!(repo.store().loose_count().unwrap(), 0);
2085
    assert_eq!(repo.store().list().unwrap(), before);
2086
2087
    // With zero retention only the current view is a root: superseded
2088
    // working copies go, everything reachable stays.
2089
    repo.config.set("core.op-retention", "0").unwrap();
2090
    repo.save_config().unwrap();
2091
    let mut repo = Repo::open(root).unwrap().with_home(root.join("home"));
2092
    let r = repo.gc(true).unwrap();
2093
    assert!(r.pruned.objects >= 5, "{r:?}");
2094
    let after = repo.store().list().unwrap();
2095
    assert!(after.len() < before.len());
2096
    assert!(after.contains(&h1) && after.contains(&h2));
2097
    for (_, op) in repo.op_log().unwrap() {
2098
        assert!(!op.command.is_empty(), "operation objects are all kept");
2099
    }
2100
    // Everything still works from the pruned, packed store.
2101
    assert_eq!(repo.bookmark_heads().unwrap(), vec![h2]);
2102
    assert!(matches!(
2103
        repo.verify_change(&h2).unwrap(),
2104
        SignatureStatus::Valid { .. }
2105
    ));
2106
    assert_eq!(repo.log().unwrap().len(), 3);
2107
    repo.checkout(&[h1], false, "checkout").unwrap();
2108
    assert_eq!(fs::read(root.join("a.txt")).unwrap(), b"one\n");
2109
    repo.checkout(&[h2], false, "checkout").unwrap();
2110
    assert_eq!(fs::read(root.join("big.bin")).unwrap().len(), 100_000);
2111
    assert!(!repo.snapshot("status").unwrap().changed);
2112
    // Grace period defers pruning of young garbage.
2113
    write(root, "a.txt", b"three\n");
2114
    repo.commit("three", &[]).unwrap();
2115
    let r = repo.gc(false).unwrap();
2116
    assert_eq!(r.pruned.objects, 0);
2117
    assert!(r.pruned.deferred > 0);
2118
    let r = repo.gc(true).unwrap();
2119
    assert!(r.pruned.objects > 0);
2120
    assert_eq!(repo.log().unwrap().len(), 4);
2121
    // Restoring the default retention makes the old views roots again; the
2122
    // working copies they name were pruned, which gc tolerates.
2123
    repo.config.set("core.op-retention", "90").unwrap();
2124
    repo.save_config().unwrap();
2125
    let repo = Repo::open(root).unwrap().with_home(root.join("home"));
2126
    let r = repo.gc(false).unwrap();
2127
    assert_eq!(r.pruned.objects, 0);
2128
    assert_eq!(repo.log().unwrap().len(), 4);
2129
}
2130
2131
#[test]
2132
fn describe_amend_abandon_heads() {
2133
    hermetic();
2134
    let dir = tempfile::tempdir().unwrap();
2135
    let root = dir.path();
2136
    let mut repo = Repo::init(root).unwrap().with_home(root.join("home"));
2137
    repo.create_identity("Ada", "a@b", IdentityScope::User)
2138
        .unwrap();
2139
    repo.set_user_config("core.sign", "change").unwrap();
2140
    write(root, "a.txt", b"one\n");
2141
    let h1 = repo.commit("first", &[]).unwrap();
2142
    write(root, "a.txt", b"one\ntwo\n");
2143
    let h2 = repo.commit("secnod", &[]).unwrap();
2144
    let id2 = repo.store().get_change(&h2).unwrap().change_id;
2145
2146
    // describe: same ChangeId, new hash, bookmark and working copy follow.
2147
    let h2b = repo.describe(&h2, "second").unwrap();
2148
    assert_ne!(h2b, h2);
2149
    let c = repo.store().get_change(&h2b).unwrap();
2150
    assert_eq!(
2151
        (c.change_id, c.message.as_str(), c.deps.clone()),
2152
        (id2, "second", vec![h1])
2153
    );
2154
    assert_eq!(repo.bookmark_heads().unwrap(), vec![h2b]);
2155
    assert!(matches!(
2156
        repo.verify_change(&h2b).unwrap(),
2157
        SignatureStatus::Valid { .. }
2158
    ));
2159
    let s = repo.snapshot("status").unwrap();
2160
    assert!(s.statuses.is_empty(), "{:?}", s.statuses);
2161
    assert_eq!(
2162
        repo.resolve_change(&id2.short(8)).unwrap(),
2163
        h2b,
2164
        "the old object is no longer reachable from the log"
2165
    );
2166
    // Describing a non-head rewrites its dependents (h2b → h2c') and the working copy.
2167
    let h1b = repo.describe(&h1, "first, described").unwrap();
2168
    assert_ne!(h1b, h1);
2169
    let heads = repo.bookmark_heads().unwrap();
2170
    assert_eq!(heads.len(), 1);
2171
    let top = repo.store().get_change(&heads[0]).unwrap();
2172
    assert_eq!((top.change_id, top.deps.clone()), (id2, vec![h1b]));
2173
    assert!(
2174
        matches!(
2175
            repo.verify_change(&heads[0]).unwrap(),
2176
            SignatureStatus::Valid { .. }
2177
        ),
2178
        "rewritten own change is re-signed"
2179
    );
2180
    let (_, wc) = repo.working_copy().unwrap();
2181
    assert_eq!(
2182
        wc.deps,
2183
        vec![heads[0]],
2184
        "the working copy follows the rewrite"
2185
    );
2186
    assert!(!repo.snapshot("status").unwrap().changed);
2187
    let snap = repo.load_state(&heads).unwrap().materialize();
2188
    assert!(
2189
        matches!(&snap.files["a.txt"].content, FileContent::Text { bytes, .. } if bytes == b"one\ntwo\n")
2190
    );
2191
2192
    // amend: fold an edit into the head; the result is one change from h1.
2193
    write(root, "a.txt", b"one\ntwo\nthree\n");
2194
    write(root, "b.txt", b"b\n");
2195
    let h2c = repo.amend(None).unwrap();
2196
    let c = repo.store().get_change(&h2c).unwrap();
2197
    assert_eq!(c.change_id, id2);
2198
    assert_eq!(c.message, "second");
2199
    assert_eq!(repo.bookmark_heads().unwrap(), vec![h2c]);
2200
    assert_eq!(
2201
        repo.log().unwrap().len(),
2202
        3,
2203
        "working copy, amended head, first"
2204
    );
2205
    let snap = repo.load_state(&[h2c]).unwrap().materialize();
2206
    assert!(
2207
        matches!(&snap.files["a.txt"].content, FileContent::Text { bytes, .. } if bytes == b"one\ntwo\nthree\n")
2208
    );
2209
    assert!(snap.files.contains_key("b.txt"));
2210
    assert!(!repo.snapshot("status").unwrap().changed);
2211
    assert!(
2212
        repo.amend(None).is_err(),
2213
        "clean working copy and no message"
2214
    );
2215
    let h2d = repo.amend(Some("second, amended")).unwrap();
2216
    assert_eq!(
2217
        repo.store().get_change(&h2d).unwrap().message,
2218
        "second, amended"
2219
    );
2220
2221
    // abandon: the head goes, its content stays as uncommitted work.
2222
    repo.abandon(&h2d).unwrap();
2223
    assert_eq!(
2224
        repo.bookmark_heads().unwrap(),
2225
        vec![h1b],
2226
        "the described first change is the head again"
2227
    );
2228
    let s = repo.snapshot("status").unwrap();
2229
    let paths: Vec<_> = s
2230
        .statuses
2231
        .iter()
2232
        .map(|p| (p.path.as_str(), p.status))
2233
        .collect();
2234
    assert_eq!(
2235
        paths,
2236
        vec![
2237
            ("a.txt", ChangeStatus::Modified),
2238
            ("b.txt", ChangeStatus::Added)
2239
        ]
2240
    );
2241
    assert_eq!(fs::read(root.join("a.txt")).unwrap(), b"one\ntwo\nthree\n");
2242
    let h3 = repo.commit("recommitted", &[]).unwrap();
2243
    assert_eq!(repo.bookmark_heads().unwrap(), vec![h3]);
2244
    // undo brings the abandoned head back.
2245
    repo.undo().unwrap();
2246
    repo.undo().unwrap();
2247
    assert_eq!(repo.bookmark_heads().unwrap(), vec![h2d]);
2248
2249
    // Abandoning a non-head whose dependent references its atoms reifies
2250
    // the references (here: a.txt vanishes with it, so the dependent's edit
2251
    // of a.txt is dropped with a note) instead of refusing; undo restores it.
2252
    let base = repo.bookmark_heads().unwrap()[0];
2253
    let base_change = repo.store().get_change(&base).unwrap();
2254
    let h1_now = base_change.deps[0];
2255
    let notes = repo.abandon(&h1_now).unwrap();
2256
    assert!(
2257
        !notes.is_empty(),
2258
        "the dependent's edit of a.txt was reified"
2259
    );
2260
    let heads = repo.bookmark_heads().unwrap();
2261
    let after = repo.load_state(&heads).unwrap().materialize();
2262
    assert!(
2263
        !after.files.contains_key("a.txt") && after.files.contains_key("b.txt"),
2264
        "{:?}",
2265
        after.files.keys()
2266
    );
2267
    repo.undo().unwrap();
2268
    assert_eq!(repo.bookmark_heads().unwrap(), vec![base]);
2269
    write(root, "c.txt", b"c\n");
2270
    let hc = repo.commit("c", &[]).unwrap();
2271
    write(root, "d.txt", b"d\n");
2272
    let hd = repo.commit("d", &[hc]).unwrap();
2273
    assert_eq!(repo.store().get_change(&hd).unwrap().deps, vec![hc]);
2274
    repo.abandon(&hc).unwrap();
2275
    let heads: BTreeSet<_> = repo.bookmark_heads().unwrap().into_iter().collect();
2276
    assert!(!heads.contains(&hc));
2277
    let d_now = heads
2278
        .iter()
2279
        .find(|h| repo.store().get_change(h).unwrap().message == "d")
2280
        .copied()
2281
        .unwrap();
2282
    assert!(
2283
        repo.store().get_change(&d_now).unwrap().deps.is_empty(),
2284
        "d inherited c's (empty) dependencies"
2285
    );
2286
    let s = repo.snapshot("status").unwrap();
2287
    assert_eq!(
2288
        s.statuses
2289
            .iter()
2290
            .map(|p| p.path.as_str())
2291
            .collect::<Vec<_>>(),
2292
        vec!["c.txt"],
2293
        "c's content is now uncommitted work"
2294
    );
2295
}
2296
2297
#[test]
2298
fn git_export_mirrors_history() {
2299
    hermetic();
2300
    if std::process::Command::new("git")
2301
        .arg("--version")
2302
        .output()
2303
        .is_err()
2304
    {
2305
        eprintln!("git not installed; skipping");
2306
        return;
2307
    }
2308
    let dir = tempfile::tempdir().unwrap();
2309
    let root = dir.path();
2310
    let mut repo = Repo::init(&root.join("r"))
2311
        .unwrap()
2312
        .with_home(root.join("home"));
2313
    repo.create_identity("Ada Lovelace", "[email protected]", IdentityScope::User)
2314
        .unwrap();
2315
    let r = root.join("r");
2316
    write(&r, "README.md", b"hello\n");
2317
    write(&r, "src/main.rs", b"fn main() {}\n");
2318
    let h1 = repo.commit("first", &[]).unwrap();
2319
    write(&r, "src/main.rs", b"fn main() { run(); }\n");
2320
    write(&r, "logo.png", b"\x89PNG\0\0");
2321
    let h2 = repo.commit("second", &[]).unwrap();
2322
2323
    let git_dir = root.join("mirror.git");
2324
    let rep = repo.git_export(&git_dir).unwrap();
2325
    assert_eq!((rep.exported, rep.skipped, rep.heads), (2, 0, 1));
2326
    let git = |args: &[&str]| -> String {
2327
        let out = std::process::Command::new("git")
2328
            .arg("-C")
2329
            .arg(&git_dir)
2330
            .args(args)
2331
            .output()
2332
            .unwrap();
2333
        assert!(
2334
            out.status.success(),
2335
            "{}",
2336
            String::from_utf8_lossy(&out.stderr)
2337
        );
2338
        String::from_utf8_lossy(&out.stdout).trim().to_string()
2339
    };
2340
    assert_eq!(git(&["log", "--format=%s", "main"]), "second\nfirst");
2341
    assert_eq!(git(&["show", "main:src/main.rs"]), "fn main() { run(); }");
2342
    assert_eq!(git(&["show", "main:README.md"]), "hello");
2343
    let body = git(&["log", "-1", "--format=%B", "main"]);
2344
    assert!(
2345
        body.contains(&format!("Oxy-Hash: {}", h2.to_hex())),
2346
        "{body}"
2347
    );
2348
    assert!(body.contains("Change-Id: "), "{body}");
2349
    assert_eq!(
2350
        git(&["log", "-1", "--format=%an <%ae>", "main"]),
2351
        "Ada Lovelace <[email protected]>"
2352
    );
2353
    assert_eq!(
2354
        git(&["ls-tree", "--name-only", "main"]),
2355
        "README.md\nlogo.png\nsrc"
2356
    );
2357
2358
    // Re-export is incremental.
2359
    let rep = repo.git_export(&git_dir).unwrap();
2360
    assert_eq!((rep.exported, rep.skipped), (0, 2));
2361
2362
    // An independent change makes two heads; the next state is one more
2363
    // commit on the linear branch whose tree is the union.
2364
    repo.checkout(&[h1], false, "checkout").unwrap();
2365
    write(&r, "other.txt", b"o\n");
2366
    let h3 = repo.commit("third", &[]).unwrap();
2367
    let rep = repo.git_export(&git_dir).unwrap();
2368
    assert_eq!((rep.exported, rep.heads), (1, 2));
2369
    assert_eq!(git(&["log", "--format=%s", "main"]), "third\nsecond\nfirst");
2370
    let parents = git(&["rev-list", "--parents", "-1", "main"]);
2371
    assert_eq!(parents.split(' ').count(), 2, "one parent: {parents}");
2372
    assert_eq!(git(&["show", "main:other.txt"]), "o");
2373
    assert_eq!(git(&["show", "main:src/main.rs"]), "fn main() { run(); }");
2374
    assert_eq!(
2375
        git(&["ls-tree", "--name-only", "main"]),
2376
        "README.md\nlogo.png\nother.txt\nsrc"
2377
    );
2378
    let body = git(&["log", "-1", "--format=%B", "main"]);
2379
    assert!(
2380
        body.contains(&format!("Oxy-Hash: {}", h3.to_hex())) && body.contains("Oxy-State: "),
2381
        "{body}"
2382
    );
2383
    // A rewrite is a new state whose one new change is the rewritten one.
2384
    repo.describe(&h3, "third, described").unwrap();
2385
    let rep = repo.git_export(&git_dir).unwrap();
2386
    assert_eq!(rep.exported, 1);
2387
    assert_eq!(
2388
        git(&["log", "-1", "--format=%s", "main"]),
2389
        "third, described"
2390
    );
2391
    assert_eq!(git(&["log", "--format=%s", "main"]).lines().count(), 4);
2392
    let _ = h2;
2393
}
2394
2395
#[test]
2396
fn git_import_reproduces_trees() {
2397
    git_import_reproduces_trees_with(None);
2398
}
2399
2400
/// The same import with every merge rendered in batches of one file
2401
/// (oxygen#25): what a merge onto a base of thousands of files takes.
2402
#[test]
2403
fn git_import_reproduces_trees_in_batches() {
2404
    git_import_reproduces_trees_with(Some(1));
2405
}
2406
2407
fn git_import_reproduces_trees_with(batch: Option<usize>) {
2408
    crate::repo::git::set_merge_batch_for_tests(batch);
2409
    hermetic();
2410
    if std::process::Command::new("git")
2411
        .arg("--version")
2412
        .output()
2413
        .is_err()
2414
    {
2415
        eprintln!("git not installed; skipping");
2416
        return;
2417
    }
2418
    let dir = tempfile::tempdir().unwrap();
2419
    let root = dir.path();
2420
    let g = root.join("src.git");
2421
    fs::create_dir_all(&g).unwrap();
2422
    let git = |args: &[&str]| -> String {
2423
        let out = std::process::Command::new("git")
2424
            .arg("-C")
2425
            .arg(&g)
2426
            .args([
2427
                "-c",
2428
                "user.name=Grace",
2429
                "-c",
2430
                "[email protected]",
2431
                "-c",
2432
                "commit.gpgsign=false",
2433
            ])
2434
            .args(args)
2435
            .output()
2436
            .unwrap();
2437
        assert!(
2438
            out.status.success(),
2439
            "git {args:?}: {}",
2440
            String::from_utf8_lossy(&out.stderr)
2441
        );
2442
        String::from_utf8_lossy(&out.stdout).trim().to_string()
2443
    };
2444
    git(&["init", "-q", "-b", "main"]);
2445
    write(&g, "README.md", b"# Hi\n");
2446
    write(&g, "src/lib.rs", b"pub fn a() {}\n");
2447
    git(&["add", "."]);
2448
    git(&["commit", "-q", "-m", "initial"]);
2449
    write(&g, "src/lib.rs", b"pub fn a() {}\npub fn b() {}\n");
2450
    write(&g, "run.sh", b"#!/bin/sh\n");
2451
    #[cfg(unix)]
2452
    {
2453
        use std::os::unix::fs::PermissionsExt;
2454
        fs::set_permissions(g.join("run.sh"), fs::Permissions::from_mode(0o755)).unwrap();
2455
    }
2456
    write(&g, "logo.png", b"\x89PNG\0\0\x01");
2457
    git(&["add", "."]);
2458
    git(&[
2459
        "commit",
2460
        "-q",
2461
        "-m",
2462
        "second\n\nChange-Id: 0123456789abcdef0123456789abcdef",
2463
    ]);
2464
    // A branch that edits README, merged back with a conflict-free merge.
2465
    git(&["checkout", "-q", "-b", "topic", "HEAD~1"]);
2466
    write(&g, "README.md", b"# Hi\n\nMore.\n");
2467
    git(&["commit", "-q", "-am", "readme"]);
2468
    git(&["checkout", "-q", "main"]);
2469
    git(&["merge", "-q", "--no-ff", "-m", "merge topic", "topic"]);
2470
    // A branch from the initial commit inserting at the same place as
2471
    // "second": concurrent in Oxygen too, so the merge commit is a resolution.
2472
    let initial = git(&["rev-list", "--max-parents=0", "HEAD"]);
2473
    git(&["checkout", "-q", "-b", "clash", &initial]);
2474
    write(&g, "src/lib.rs", b"pub fn a() {}\npub fn c() {}\n");
2475
    git(&["commit", "-q", "-am", "clash"]);
2476
    git(&["checkout", "-q", "main"]);
2477
    let _ = std::process::Command::new("git")
2478
        .arg("-C")
2479
        .arg(&g)
2480
        .args(["merge", "-q", "clash"])
2481
        .output();
2482
    write(
2483
        &g,
2484
        "src/lib.rs",
2485
        b"pub fn a() {}\npub fn b() {}\npub fn c() {}\n",
2486
    );
2487
    git(&["add", "."]);
2488
    git(&["commit", "-q", "-m", "resolve clash"]);
2489
    git(&["rm", "-q", "logo.png"]);
2490
    git(&["commit", "-q", "-m", "drop logo"]);
2491
    // A rename with a small edit is imported as a move of the same node.
2492
    git(&["mv", "src/lib.rs", "src/lib2.rs"]);
2493
    write(
2494
        &g,
2495
        "src/lib2.rs",
2496
        b"pub fn a() {}\npub fn b() {}\npub fn c() {}\npub fn d() {}\n",
2497
    );
2498
    git(&["add", "."]);
2499
    git(&["commit", "-q", "-m", "rename lib"]);
2500
    // A branch that edits run.sh, merged keeping main's tree (`-s ours`):
2501
    // run.sh is the same as in the first parent's tree, but the merged
2502
    // change touched it, so the importer must compare it, not skip it.
2503
    git(&["checkout", "-q", "-b", "discarded"]);
2504
    write(&g, "run.sh", b"#!/bin/sh\necho discarded\n");
2505
    git(&["commit", "-q", "-am", "discarded edit"]);
2506
    git(&["checkout", "-q", "main"]);
2507
    git(&[
2508
        "merge",
2509
        "-q",
2510
        "-s",
2511
        "ours",
2512
        "-m",
2513
        "merge discarded, keeping ours",
2514
        "discarded",
2515
    ]);
2516
    let expected_count: usize = git(&["rev-list", "--count", "main"]).parse().unwrap();
2517
2518
    let dest = root.join("oxy");
2519
    let repo = Repo::init(&dest).unwrap().with_home(root.join("home"));
2520
    let rep = repo.import_git(&g, "main").unwrap();
2521
    assert_eq!(rep.commits, expected_count);
2522
    assert_eq!(rep.merges, 3);
2523
    assert_eq!(
2524
        fs::read(dest.join("run.sh")).unwrap(),
2525
        b"#!/bin/sh\n",
2526
        "the ours merge kept main's run.sh"
2527
    );
2528
    let v = repo.verify_git_import(&g, "main").unwrap();
2529
    assert_eq!(v.commits, expected_count, "every commit's tree reproduced");
2530
    assert!(v.mismatches.is_empty(), "{:?}", v.mismatches);
2531
    // The working copy equals the Git tree at main.
2532
    assert_eq!(
2533
        fs::read(dest.join("src/lib2.rs")).unwrap(),
2534
        b"pub fn a() {}\npub fn b() {}\npub fn c() {}\npub fn d() {}\n"
2535
    );
2536
    assert!(!dest.join("src/lib.rs").exists());
2537
    assert_eq!(
2538
        fs::read(dest.join("README.md")).unwrap(),
2539
        b"# Hi\n\nMore.\n"
2540
    );
2541
    assert!(!dest.join("logo.png").exists());
2542
    #[cfg(unix)]
2543
    {
2544
        use std::os::unix::fs::PermissionsExt;
2545
        assert!(
2546
            fs::metadata(dest.join("run.sh"))
2547
                .unwrap()
2548
                .permissions()
2549
                .mode()
2550
                & 0o111
2551
                != 0
2552
        );
2553
    }
2554
    assert!(
2555
        !repo.snapshot("status").unwrap().changed,
2556
        "clean after import"
2557
    );
2558
    let heads = repo.bookmark_heads().unwrap();
2559
    let st = repo.load_state(&heads).unwrap();
2560
    assert!(!st.materialize().is_conflicted());
2561
    assert_eq!(st.len(), expected_count);
2562
    let tip = repo
2563
        .log()
2564
        .unwrap()
2565
        .into_iter()
2566
        .find(|e| e.change.message.starts_with("rename lib"))
2567
        .unwrap();
2568
    let c = repo.store().get_change(&tip.hash).unwrap();
2569
    assert!(
2570
        c.tree_ops
2571
            .iter()
2572
            .any(|op| matches!(op, TreeOp::Move { name, .. } if name == "lib2.rs")),
2573
        "{:?}",
2574
        c.tree_ops
2575
    );
2576
    assert!(!c
2577
        .tree_ops
2578
        .iter()
2579
        .any(|op| matches!(op, TreeOp::AddNode { .. })));
2580
    // Messages carry Git trailers; the Change-Id trailer was honoured.
2581
    let log = repo.log().unwrap();
2582
    let second = log
2583
        .iter()
2584
        .find(|e| e.change.message.starts_with("second"))
2585
        .unwrap();
2586
    assert_eq!(
2587
        second.change.change_id,
2588
        ChangeId::from_hex("0123456789abcdef0123456789abcdef").unwrap()
2589
    );
2590
    assert!(second
2591
        .change
2592
        .message
2593
        .contains("Git-Author: Grace <[email protected]>"));
2594
    let resolve = log
2595
        .iter()
2596
        .find(|e| e.change.message.starts_with("resolve clash"))
2597
        .unwrap();
2598
    assert_eq!(
2599
        resolve.change.kind,
2600
        ChangeKind::Resolution,
2601
        "a conflicting Git merge becomes a resolution"
2602
    );
2603
    // Re-importing into another fresh repository gives the same ChangeIds.
2604
    let repo2 = Repo::init(&root.join("oxy2"))
2605
        .unwrap()
2606
        .with_home(root.join("home"));
2607
    repo2.import_git(&g, "main").unwrap();
2608
    // New nodes' identifiers derive from the commit (spec §23), so the
2609
    // re-import is not just the same ChangeIds but the same changes.
2610
    assert_eq!(
2611
        repo2.bookmark_heads().unwrap(),
2612
        repo.bookmark_heads().unwrap()
2613
    );
2614
    let ids: BTreeSet<ChangeId> = repo
2615
        .log()
2616
        .unwrap()
2617
        .iter()
2618
        .filter(|e| !e.is_working_copy)
2619
        .map(|e| e.change.change_id)
2620
        .collect();
2621
    let ids2: BTreeSet<ChangeId> = repo2
2622
        .log()
2623
        .unwrap()
2624
        .iter()
2625
        .filter(|e| !e.is_working_copy)
2626
        .map(|e| e.change.change_id)
2627
        .collect();
2628
    assert_eq!(ids, ids2);
2629
    // Round trip back out to Git reproduces the tip tree.
2630
    let mirror = root.join("mirror.git");
2631
    repo.git_export(&mirror).unwrap();
2632
    let out = std::process::Command::new("git")
2633
        .arg("-C")
2634
        .arg(&mirror)
2635
        .args(["show", "main:src/lib2.rs"])
2636
        .output()
2637
        .unwrap();
2638
    assert_eq!(
2639
        String::from_utf8_lossy(&out.stdout),
2640
        "pub fn a() {}\npub fn b() {}\npub fn c() {}\npub fn d() {}\n"
2641
    );
2642
    let out = std::process::Command::new("git")
2643
        .arg("-C")
2644
        .arg(&mirror)
2645
        .args(["show", "main:src/lib.rs"])
2646
        .output()
2647
        .unwrap();
2648
    assert!(
2649
        !out.status.success(),
2650
        "the old path is gone from the export"
2651
    );
2652
}
2653
2654
#[test]
2655
fn checkpoints_accelerate_loading_and_stay_correct() {
2656
    hermetic();
2657
    let dir = tempfile::tempdir().unwrap();
2658
    let root = dir.path();
2659
    let mut repo = Repo::init(root).unwrap().with_home(root.join("home"));
2660
    repo.config.set("core.checkpoint-interval", "5").unwrap();
2661
    repo.save_config().unwrap();
2662
    let repo = Repo::open(root).unwrap().with_home(root.join("home"));
2663
    let mut hashes = Vec::new();
2664
    for i in 0..12 {
2665
        write(
2666
            root,
2667
            "a.txt",
2668
            format!(
2669
                "{}\n",
2670
                (0..=i)
2671
                    .map(|k| k.to_string())
2672
                    .collect::<Vec<_>>()
2673
                    .join("\n")
2674
            )
2675
            .as_bytes(),
2676
        );
2677
        write(root, &format!("f{i}.txt"), b"x\n");
2678
        hashes.push(repo.commit(&format!("c{i}"), &[]).unwrap());
2679
    }
2680
    let (_, cp) = repo
2681
        .latest_checkpoint("main")
2682
        .unwrap()
2683
        .expect("automatic checkpoint");
2684
    assert!(cp.count >= 5 && cp.count <= 12, "{}", cp.count);
2685
    // Loading through the checkpoint equals loading everything.
2686
    let heads = repo.bookmark_heads().unwrap();
2687
    let fast = repo.load_state(&heads).unwrap();
2688
    let full = repo.load_state_full(&heads).unwrap();
2689
    assert_eq!(fast.len(), full.len());
2690
    assert_eq!(fast.heads(), full.heads());
2691
    let (a, b) = (fast.materialize(), full.materialize());
2692
    assert_eq!(
2693
        a.files.keys().collect::<Vec<_>>(),
2694
        b.files.keys().collect::<Vec<_>>()
2695
    );
2696
    for (p, f) in &a.files {
2697
        assert_eq!(f.content, b.files[p].content, "{p}");
2698
    }
2699
    assert!(repo.load_state_checkpointed(&heads).unwrap().is_some());
2700
    // A head set that does not contain the checkpoint's heads falls back.
2701
    assert!(repo
2702
        .load_state_checkpointed(&[hashes[0]])
2703
        .unwrap()
2704
        .is_none());
2705
    assert_eq!(repo.load_state(&[hashes[0]]).unwrap().len(), 1);
2706
    // Everything else keeps working on top of the checkpoint.
2707
    assert!(!repo.snapshot("status").unwrap().changed);
2708
    let h = repo.describe(&hashes[3], "c3 described").unwrap();
2709
    assert_eq!(repo.store().get_change(&h).unwrap().message, "c3 described");
2710
    let (r, n, bytes) = repo.checkpoint().unwrap();
2711
    assert!(n >= 12 && bytes > 0);
2712
    assert_eq!(repo.latest_checkpoint("main").unwrap().unwrap().0, r);
2713
    write(root, "a.txt", b"after\n");
2714
    let h_after = repo.commit("after", &[]).unwrap();
2715
    let st = repo.load_state(&repo.bookmark_heads().unwrap()).unwrap();
2716
    assert!(st.contains(&h_after));
2717
    assert!(
2718
        matches!(&st.materialize().files["a.txt"].content, FileContent::Text { bytes, .. } if bytes == b"after\n")
2719
    );
2720
    assert_eq!(repo.log().unwrap().len(), 14);
2721
    // Checkpoints survive gc.
2722
    repo.gc(true).unwrap();
2723
    assert!(repo.latest_checkpoint("main").unwrap().is_some());
2724
    assert!(repo
2725
        .load_state_checkpointed(&repo.bookmark_heads().unwrap())
2726
        .unwrap()
2727
        .is_some());
2728
}
2729
2730
#[test]
2731
fn quick_status_for_prompts() {
2732
    hermetic();
2733
    let dir = tempfile::tempdir().unwrap();
2734
    let root = dir.path();
2735
    let origin = Repo::init(&root.join("origin")).unwrap();
2736
    let url = root.join("origin").to_string_lossy().to_string();
2737
    let a = Repo::clone(&url, &root.join("a"))
2738
        .unwrap()
2739
        .with_home(root.join("home"));
2740
    let ops_before = a.op_log().unwrap().len();
2741
    let info = a.quick_status().unwrap();
2742
    assert_eq!(
2743
        (
2744
            info.bookmark.as_str(),
2745
            info.heads,
2746
            info.dirty,
2747
            info.conflicted,
2748
            info.ahead,
2749
            info.behind
2750
        ),
2751
        ("main", 0, false, false, Some(0), Some(0))
2752
    );
2753
    write(&root.join("a"), "f.txt", b"f\n");
2754
    assert!(a.quick_status().unwrap().dirty, "a new file is dirty");
2755
    assert_eq!(
2756
        a.op_log().unwrap().len(),
2757
        ops_before,
2758
        "quick_status records nothing"
2759
    );
2760
    // A snapshotted but uncommitted change is still dirty.
2761
    a.snapshot("status").unwrap();
2762
    assert!(a.quick_status().unwrap().dirty);
2763
    a.commit("f", &[]).unwrap();
2764
    let info = a.quick_status().unwrap();
2765
    assert!(!info.dirty, "clean right after a commit");
2766
    assert_eq!((info.ahead, info.behind), (Some(1), Some(0)));
2767
    assert_eq!(
2768
        info.format("%b %c%d%x%A%D"),
2769
        format!("main {}+1", info.change_id)
2770
    );
2771
    assert_eq!(info.format("[%h heads] %a/%B %%"), "[1 heads] 1/0 %");
2772
    // Touching a file without changing it is not dirty; changing content of
2773
    // the same size is.
2774
    let p = root.join("a/f.txt");
2775
    let content = fs::read(&p).unwrap();
2776
    fs::write(&p, &content).unwrap();
2777
    assert!(!a.quick_status().unwrap().dirty);
2778
    fs::write(&p, b"g\n").unwrap();
2779
    assert!(a.quick_status().unwrap().dirty);
2780
    fs::write(&p, b"f\n").unwrap();
2781
    // Push, then a second clone commits and pushes: we are behind.
2782
    assert!(a.push("origin", false).unwrap()[0].ok);
2783
    assert_eq!(a.quick_status().unwrap().ahead, Some(0));
2784
    let b = Repo::clone(&url, &root.join("b"))
2785
        .unwrap()
2786
        .with_home(root.join("home-b"));
2787
    write(&root.join("b"), "g.txt", b"g\n");
2788
    b.commit("g", &[]).unwrap();
2789
    b.push("origin", false).unwrap();
2790
    a.fetch("origin").unwrap();
2791
    let info = a.quick_status().unwrap();
2792
    assert_eq!((info.ahead, info.behind), (Some(0), Some(1)));
2793
    assert_eq!(info.format("%A%D"), "-1");
2794
    let _ = origin;
2795
}
2796
2797
#[test]
2798
fn lazy_blobs_are_fetched_on_first_read() {
2799
    hermetic();
2800
    let dir = tempfile::tempdir().unwrap();
2801
    let root = dir.path();
2802
    let origin_dir = root.join("origin");
2803
    let origin = Repo::init(&origin_dir)
2804
        .unwrap()
2805
        .with_home(root.join("home"));
2806
    let url = origin_dir.to_string_lossy().to_string();
2807
    let big: Vec<u8> = (0..200_000u32).map(|i| (i % 251) as u8).collect(); // has NUL bytes: opaque
2808
    write(&origin_dir, "big.bin", &big);
2809
    write(&origin_dir, "small.bin", &[0u8, 1, 2]);
2810
    write(&origin_dir, "t.txt", b"t\n");
2811
    let h = origin.commit("blobs", &[]).unwrap();
2812
    let big_ref = Repo::blob_ref(&big);
2813
2814
    // Fetch only (no checkout) with a filter: the big blob stays absent.
2815
    let a = Repo::init_with_id(&root.join("a"), origin.id().unwrap())
2816
        .unwrap()
2817
        .with_home(root.join("home"));
2818
    let a = {
2819
        let mut a = a;
2820
        a.config.set("remote.origin.url", &url).unwrap();
2821
        a.config.set("filter.max-blob", "100K").unwrap();
2822
        a.save_config().unwrap();
2823
        a
2824
    };
2825
    assert_eq!(a.config.max_blob, Some(100 * 1024));
2826
    a.fetch("origin").unwrap();
2827
    assert!(a.store().has(&h));
2828
    assert!(!a.store().has(&big_ref), "withheld");
2829
    assert!(
2830
        a.store().has(&Repo::blob_ref(&[0u8, 1, 2])),
2831
        "small blob came along"
2832
    );
2833
    assert_eq!(a.lazy_remote(&big_ref).as_deref(), Some("origin"));
2834
2835
    // status and commit do not need it: adopt the state, edit a text file, commit.
2836
    let (op_ref, op) = a.head_op().unwrap();
2837
    let mut view = op.view.clone();
2838
    view.bookmarks.insert(
2839
        "main".into(),
2840
        a.store().put_state(&StateObject::new(vec![h])).unwrap(),
2841
    );
2842
    a.record_op(&[op_ref], "adopt", view).unwrap();
2843
    // Checkout reads the blob lazily, which fetches it.
2844
    a.checkout(&[h], true, "checkout").unwrap();
2845
    assert!(a.store().has(&big_ref), "fetched on first read");
2846
    assert_eq!(fs::read(root.join("a/big.bin")).unwrap(), big);
2847
    assert!(a.lazy_remote(&big_ref).is_none(), "no longer registered");
2848
    write(&root.join("a"), "t.txt", b"t2\n");
2849
    a.commit("text edit", &[]).unwrap();
2850
2851
    // clone --max-blob records the filter; the checkout fetches lazily.
2852
    let b = Repo::clone_with(&url, &root.join("b"), Some(1024), &[]).unwrap();
2853
    assert_eq!(b.config.max_blob, Some(1024));
2854
    assert_eq!(fs::read(root.join("b/big.bin")).unwrap(), big);
2855
    assert_eq!(parse_size("2M").unwrap(), 2 << 20);
2856
    assert!(parse_size("lots").is_err());
2857
}
2858
2859
#[test]
2860
fn sparse_checkout_materializes_only_chosen_paths() {
2861
    hermetic();
2862
    let dir = tempfile::tempdir().unwrap();
2863
    let root = dir.path();
2864
    let origin_dir = root.join("origin");
2865
    let origin = Repo::init(&origin_dir)
2866
        .unwrap()
2867
        .with_home(root.join("home"));
2868
    write(&origin_dir, "src/main.rs", b"fn main() {}\n");
2869
    write(&origin_dir, "src/lib.rs", b"pub fn a() {}\n");
2870
    write(&origin_dir, "docs/guide.md", b"# guide\n");
2871
    let logo: Vec<u8> = (0..50_000u32).map(|i| (i % 7) as u8).collect();
2872
    write(&origin_dir, "docs/logo.png", &logo);
2873
    write(&origin_dir, "README.md", b"# top\n");
2874
    let h1 = origin.commit("tree", &[]).unwrap();
2875
    let url = origin_dir.to_string_lossy().to_string();
2876
2877
    let a = Repo::clone_with(&url, &root.join("a"), None, &["src".into()])
2878
        .unwrap()
2879
        .with_home(root.join("home"));
2880
    assert_eq!(a.config.sparse_paths, vec!["src"]);
2881
    assert_eq!(a.config.max_blob, Some(0), "sparse implies lazy blobs");
2882
    assert!(root.join("a/src/main.rs").exists());
2883
    assert!(!root.join("a/docs").exists() && !root.join("a/README.md").exists());
2884
    assert!(
2885
        !a.store().has(&Repo::blob_ref(&logo)),
2886
        "out-of-scope blob never fetched"
2887
    );
2888
    assert!(
2889
        !a.snapshot("status").unwrap().changed,
2890
        "out-of-scope files are not removals"
2891
    );
2892
    assert!(!a.quick_status().unwrap().dirty);
2893
2894
    // Edits in scope commit normally and keep the rest of the tree intact.
2895
    write(
2896
        &root.join("a"),
2897
        "src/lib.rs",
2898
        b"pub fn a() {}\npub fn b() {}\n",
2899
    );
2900
    let h2 = a.commit("edit lib", &[]).unwrap();
2901
    let st = a.load_state(&[h2]).unwrap().materialize();
2902
    assert!(
2903
        st.files.contains_key("docs/guide.md"),
2904
        "the state still has everything"
2905
    );
2906
    assert!(a.push("origin", false).unwrap()[0].ok);
2907
    origin.refresh().unwrap();
2908
    // Files created outside the scope are ignored by status.
2909
    write(&root.join("a"), "docs/new.md", b"ignored\n");
2910
    assert!(a.snapshot("status").unwrap().statuses.is_empty());
2911
2912
    // Widening the filter checks out the rest; narrowing leaves stray files alone.
2913
    let mut a = a;
2914
    a.config.set("filter.paths", "src,docs").unwrap();
2915
    a.save_config().unwrap();
2916
    let r = a
2917
        .checkout(&a.bookmark_heads().unwrap(), true, "widen")
2918
        .unwrap();
2919
    assert!(r.written >= 2);
2920
    assert_eq!(
2921
        fs::read(root.join("a/docs/logo.png")).unwrap(),
2922
        logo,
2923
        "now fetched lazily"
2924
    );
2925
    assert!(!root.join("a/README.md").exists());
2926
    // Origin sees the change made under a sparse checkout with the full tree intact.
2927
    origin.pull("origin").err();
2928
    let full = origin
2929
        .load_state(&origin.bookmark_heads().unwrap())
2930
        .unwrap()
2931
        .materialize();
2932
    assert!(
2933
        matches!(&full.files["src/lib.rs"].content, FileContent::Text { bytes, .. } if bytes == b"pub fn a() {}\npub fn b() {}\n")
2934
    );
2935
    assert!(full.files.contains_key("README.md"));
2936
    let _ = h1;
2937
}
2938
2939
#[test]
2940
fn shallow_clone_and_deepen() {
2941
    hermetic();
2942
    let dir = tempfile::tempdir().unwrap();
2943
    let root = dir.path();
2944
    let origin_dir = root.join("origin");
2945
    let origin = Repo::init(&origin_dir)
2946
        .unwrap()
2947
        .with_home(root.join("home"));
2948
    let mut hashes = Vec::new();
2949
    for i in 0..8 {
2950
        write(
2951
            &origin_dir,
2952
            "a.txt",
2953
            format!(
2954
                "{}\n",
2955
                (0..=i)
2956
                    .map(|k| k.to_string())
2957
                    .collect::<Vec<_>>()
2958
                    .join("\n")
2959
            )
2960
            .as_bytes(),
2961
        );
2962
        hashes.push(origin.commit(&format!("c{i}"), &[]).unwrap());
2963
    }
2964
    let url = origin_dir.to_string_lossy().to_string();
2965
    let a = Repo::clone_shallow(&url, &root.join("a"), 3, None, &[])
2966
        .unwrap()
2967
        .with_home(root.join("home"));
2968
    assert!(a.is_shallow());
2969
    assert_eq!(
2970
        fs::read_to_string(root.join("a/a.txt")).unwrap(),
2971
        "0\n1\n2\n3\n4\n5\n6\n7\n"
2972
    );
2973
    assert!(
2974
        a.store().has(&hashes[7]) && a.store().has(&hashes[5]),
2975
        "three levels present"
2976
    );
2977
    assert!(!a.store().has(&hashes[4]), "beyond the depth is absent");
2978
    assert_eq!(a.boundary(), [hashes[4]].into_iter().collect());
2979
    assert_eq!(
2980
        a.log().unwrap().len(),
2981
        9,
2982
        "the log shows every change from the checkpoint's metadata"
2983
    );
2984
    assert!(!a.snapshot("status").unwrap().changed);
2985
    assert_eq!(a.quick_status().unwrap().heads, 1);
2986
2987
    // Work continues on top of the shallow history and pushes back.
2988
    write(&root.join("a"), "a.txt", b"0\n1\n2\n3\n4\n5\n6\n7\n8\n");
2989
    let h_new = a.commit("c8", &[]).unwrap();
2990
    assert!(a.push("origin", false).unwrap()[0].ok);
2991
    origin.refresh().unwrap();
2992
    assert_eq!(origin.bookmark_heads().unwrap(), vec![h_new]);
2993
    // Fetching new work from origin into the shallow clone works too.
2994
    write(&origin_dir, "b.txt", b"b\n");
2995
    origin.pull("origin").err();
2996
    let (_, wc) = origin.working_copy().unwrap();
2997
    let _ = wc;
2998
    origin
2999
        .checkout(&origin.bookmark_heads().unwrap(), true, "co")
3000
        .unwrap();
3001
    write(&origin_dir, "b.txt", b"b\n");
3002
    let h_b = origin.commit("b", &[]).unwrap();
3003
    let pr = a.pull("origin").unwrap();
3004
    assert!(pr.changed);
3005
    assert!(a.store().has(&h_b));
3006
    assert!(root.join("a/b.txt").exists());
3007
3008
    // Deepening fetches older history until the boundary is gone.
3009
    // Every commit also depends on the change that created the file, so two
3010
    // levels below the boundary hold h4, h3, and the root.
3011
    assert!(a.deepen("origin", 2).unwrap() >= 2);
3012
    assert!(a.store().has(&hashes[3]));
3013
    assert!(a.is_shallow());
3014
    a.deepen("origin", 100).unwrap();
3015
    assert!(!a.is_shallow(), "boundary reached the root");
3016
    assert!(a.store().has(&hashes[0]));
3017
    assert_eq!(
3018
        a.load_state_full(&a.bookmark_heads().unwrap())
3019
            .unwrap()
3020
            .len(),
3021
        10
3022
    );
3023
}
3024
3025
#[test]
3026
fn tags_are_immutable_named_states_and_travel() {
3027
    hermetic();
3028
    let dir = tempfile::tempdir().unwrap();
3029
    let root = dir.path();
3030
    let origin = Repo::init(&root.join("origin")).unwrap();
3031
    let url = root.join("origin").to_string_lossy().to_string();
3032
    let mut a = Repo::clone(&url, &root.join("a"))
3033
        .unwrap()
3034
        .with_home(root.join("home-a"));
3035
    let (key_a, _) = a
3036
        .create_identity("Ada", "[email protected]", IdentityScope::User)
3037
        .unwrap();
3038
    write(&root.join("a"), "f.txt", b"1\n");
3039
    let h1 = a.commit("one", &[]).unwrap();
3040
    write(&root.join("a"), "f.txt", b"1\n2\n");
3041
    let h2 = a.commit("two", &[]).unwrap();
3042
3043
    let t = a.tag_create("v1", &[h1], "first release").unwrap();
3044
    assert_eq!(
3045
        (t.heads.clone(), t.signer.as_deref()),
3046
        (vec![h1], Some("Ada"))
3047
    );
3048
    assert!(a.tag_create("v1", &[h2], "").is_err(), "immutable");
3049
    assert!(a.tag_create("bad/name", &[h2], "").is_err());
3050
    assert_eq!(a.tag_heads("v1").unwrap(), Some(vec![h1]));
3051
    assert_eq!(a.resolve_heads("v1").unwrap(), vec![h1]);
3052
    assert_eq!(a.resolve_heads("main").unwrap(), vec![h2]);
3053
    let (_, sa) = a.tag_attest("v1").unwrap().unwrap();
3054
    assert_eq!(sa.sigs[0].key, key_a);
3055
    // Checkout by tag.
3056
    a.checkout(&a.resolve_heads("v1").unwrap(), false, "co")
3057
        .unwrap();
3058
    assert_eq!(fs::read(root.join("a/f.txt")).unwrap(), b"1\n");
3059
    a.checkout(&a.bookmark_heads().unwrap(), false, "co")
3060
        .unwrap();
3061
3062
    // Push carries the tag; a second attestation for the name is refused.
3063
    let r = a.push("origin", false).unwrap();
3064
    origin.refresh().unwrap();
3065
    assert!(r.iter().any(|x| x.name == "tags/v1" && x.ok), "{r:?}");
3066
    assert_eq!(origin.tag_heads("v1").unwrap(), Some(vec![h1]));
3067
    let mut forged = a
3068
        .tag_refs()
3069
        .unwrap()
3070
        .into_iter()
3071
        .find(|t| t.name == "v1")
3072
        .unwrap();
3073
    forged.state = origin
3074
        .store()
3075
        .put_state(&StateObject::new(vec![h2]))
3076
        .unwrap();
3077
    forged.heads = vec![h2];
3078
    forged.attestation = None;
3079
    let r = origin
3080
        .receive_push(Bundle::default(), vec![], None, vec![forged])
3081
        .unwrap();
3082
    assert!(!r[0].ok && r[0].reason.contains("immutable"), "{r:?}");
3083
3084
    // A clone gets the tag; a later tag arrives on fetch.
3085
    let b = Repo::clone(&url, &root.join("b"))
3086
        .unwrap()
3087
        .with_home(root.join("home-b"));
3088
    assert_eq!(b.tag_heads("v1").unwrap(), Some(vec![h1]));
3089
    assert!(b.tags().unwrap()[0].signer.as_deref() == Some("Ada"));
3090
    a.tag_create("v2", &[h2], "second").unwrap();
3091
    a.push("origin", false).unwrap();
3092
    origin.refresh().unwrap();
3093
    let rep = b.fetch("origin").unwrap();
3094
    assert_eq!(rep.new_tags, 1);
3095
    assert_eq!(b.tag_heads("v2").unwrap(), Some(vec![h2]));
3096
3097
    // Under a policy, an unattested tag is refused and an attested one by the root passes.
3098
    a.policy_init().unwrap();
3099
    a.push("origin", false).unwrap();
3100
    origin.refresh().unwrap();
3101
    let unattested = crate::protocol::TagRef::new(
3102
        "v3".into(),
3103
        origin
3104
            .store()
3105
            .put_state(&StateObject::new(vec![h2]))
3106
            .unwrap(),
3107
        vec![h2],
3108
        None,
3109
    );
3110
    let r = origin
3111
        .receive_push(Bundle::default(), vec![], None, vec![unattested])
3112
        .unwrap();
3113
    assert!(!r[0].ok && r[0].reason.contains("attestation"), "{r:?}");
3114
    a.tag_create("v3", &[h2], "").unwrap();
3115
    let r = a.push("origin", false).unwrap();
3116
    origin.refresh().unwrap();
3117
    assert!(r.iter().any(|x| x.name == "tags/v3" && x.ok), "{r:?}");
3118
    assert!(a.gc(true).is_ok());
3119
    assert_eq!(a.tags().unwrap().len(), 3, "tags survive gc");
3120
3121
    // After a rotation the policy names only the new key, yet a fresh clone
3122
    // still takes the tags the old key made before it; the old key makes
3123
    // nothing new.
3124
    let rot = a.rotate_identity().unwrap();
3125
    let r = a.push("origin", false).unwrap();
3126
    origin.refresh().unwrap();
3127
    assert!(r.iter().all(|x| x.ok), "{r:?}");
3128
    let c = Repo::clone(&url, &root.join("c"))
3129
        .unwrap()
3130
        .with_home(root.join("home-c"));
3131
    assert_eq!(c.tag_heads("v3").unwrap(), Some(vec![h2]));
3132
    let (_, sp) = c.current_policy().unwrap().unwrap();
3133
    assert!(!sp.policy.authorizes(&key_a, "tags/v9"));
3134
    let made = c.identity(&rot.new).unwrap().created;
3135
    assert!(c.predecessor_authorized(&sp.policy, &key_a, "tags/v9", made - 1));
3136
    assert!(!c.predecessor_authorized(&sp.policy, &key_a, "tags/v9", made));
3137
    assert!(!c.predecessor_authorized(&sp.policy, &rot.new, "tags/v9", 0));
3138
}
3139
3140
#[test]
3141
fn multiple_workspaces_share_a_repository() {
3142
    hermetic();
3143
    let dir = tempfile::tempdir().unwrap();
3144
    let root = dir.path();
3145
    let main_dir = root.join("main");
3146
    let repo = Repo::init(&main_dir).unwrap().with_home(root.join("home"));
3147
    write(&main_dir, "a.txt", b"a\n");
3148
    let h1 = repo.commit("a", &[]).unwrap();
3149
    assert_eq!(repo.workspaces().unwrap().len(), 1);
3150
3151
    // A second workspace elsewhere, checked out on the bookmark.
3152
    let ws_dir = root.join("ws2");
3153
    let ws = repo.workspace_add(&ws_dir, None).unwrap();
3154
    assert!(ws_dir.join(".oxy").is_file());
3155
    assert_eq!(fs::read(ws_dir.join("a.txt")).unwrap(), b"a\n");
3156
    assert_ne!(ws.workspace(), repo.workspace());
3157
    let list = repo.workspaces().unwrap();
3158
    assert_eq!(list.len(), 2);
3159
    assert!(list
3160
        .iter()
3161
        .any(|w| w.id == ws.workspace() && w.path == ws_dir.canonicalize().unwrap() && !w.current));
3162
    assert!(!ws.snapshot("status").unwrap().changed);
3163
3164
    // Work in the second workspace: its own working copy, shared bookmark.
3165
    write(&ws_dir, "b.txt", b"b\n");
3166
    let s = ws.snapshot("status").unwrap();
3167
    assert_eq!(s.statuses.len(), 1);
3168
    assert!(
3169
        !repo.snapshot("status").unwrap().changed,
3170
        "the first workspace is untouched"
3171
    );
3172
    let h2 = ws.commit("b from ws2", &[]).unwrap();
3173
    repo.refresh().unwrap();
3174
    let mut heads = repo.bookmark_heads().unwrap();
3175
    heads.sort();
3176
    let mut want = vec![h1, h2];
3177
    want.sort();
3178
    assert_eq!(heads, want, "both workspaces see the bookmark move");
3179
    assert!(!main_dir.join("b.txt").exists());
3180
    repo.checkout(&repo.bookmark_heads().unwrap(), false, "co")
3181
        .unwrap();
3182
    assert!(main_dir.join("b.txt").exists());
3183
3184
    // Reopening from inside the second workspace finds the shared repository.
3185
    let reopened = Repo::open(&ws_dir).unwrap();
3186
    assert_eq!(reopened.workspace(), ws.workspace());
3187
    assert_eq!(reopened.id().unwrap(), repo.id().unwrap());
3188
    assert_eq!(reopened.quick_status().unwrap().heads, 2);
3189
3190
    // Workspaces cannot nest; forget drops one from the view but keeps files.
3191
    assert!(repo.workspace_add(&main_dir.join("inner"), None).is_err());
3192
    assert!(repo.workspace_forget(&repo.workspace()).is_err());
3193
    repo.workspace_forget(&ws.workspace()).unwrap();
3194
    assert_eq!(repo.workspaces().unwrap().len(), 1);
3195
    assert!(ws_dir.join("b.txt").exists());
3196
    assert!(
3197
        ws.snapshot("status").is_err(),
3198
        "a forgotten workspace is no longer in the view"
3199
    );
3200
3201
    // The working-copy lock: re-entrant in a thread; a lock whose process
3202
    // is gone is taken over, and a live process's is not, however old.
3203
    let lock = repo.lock_snapshot().unwrap();
3204
    let again = repo.lock_working_copy().unwrap();
3205
    drop(again);
3206
    drop(lock);
3207
    let lock_path = main_dir
3208
        .join(".oxy/workspaces")
3209
        .join(repo.workspace().to_hex())
3210
        .join("lock");
3211
    let old = std::time::SystemTime::now() - std::time::Duration::from_secs(120);
3212
    let age = |p: &Path| fs::File::open(p).unwrap().set_modified(old).unwrap();
3213
    fs::write(&lock_path, std::process::id().to_string()).unwrap();
3214
    age(&lock_path);
3215
    assert!(
3216
        !super::workspace::lock_is_stale(&lock_path),
3217
        "a live process keeps its lock"
3218
    );
3219
    fs::write(&lock_path, "4294967295").unwrap();
3220
    age(&lock_path);
3221
    assert!(repo.lock_snapshot().is_ok(), "stale lock taken over");
3222
}
3223
3224
#[test]
3225
fn attributes_binary_eol_nocompress_lockable() {
3226
    hermetic();
3227
    let dir = tempfile::tempdir().unwrap();
3228
    let root = dir.path();
3229
    let repo = Repo::init(root).unwrap().with_home(root.join("home"));
3230
    write(
3231
        root,
3232
        ".oxyattributes",
3233
        b"*.dat binary nocompress\n*.txt eol=crlf\nassets/** lockable\n",
3234
    );
3235
    write(root, "plain.dat", b"no nul bytes here\n");
3236
    write(root, "notes.txt", b"one\r\ntwo\r\n");
3237
    write(root, "assets/model.bin", b"\0model");
3238
    let h = repo.commit("attrs", &[]).unwrap();
3239
    let snap = repo.load_state(&[h]).unwrap().materialize();
3240
    assert!(
3241
        snap.files["plain.dat"].mode.opaque,
3242
        "binary attribute forces opaque without NUL bytes"
3243
    );
3244
    assert!(
3245
        matches!(&snap.files["notes.txt"].content, FileContent::Text { bytes, .. } if bytes == b"one\ntwo\n"),
3246
        "stored with LF"
3247
    );
3248
    assert!(
3249
        !repo.snapshot("status").unwrap().changed,
3250
        "CRLF on disk equals LF in the state"
3251
    );
3252
    // nocompress chunks pack raw.
3253
    let r = repo.gc(true).unwrap();
3254
    assert!(r.packed.objects > 0);
3255
    // Checkout writes CRLF for eol=crlf and makes lockable files read-only.
3256
    fs::remove_file(root.join("notes.txt")).unwrap();
3257
    repo.checkout(&[h], true, "co").unwrap();
3258
    assert_eq!(fs::read(root.join("notes.txt")).unwrap(), b"one\r\ntwo\r\n");
3259
    assert!(fs::metadata(root.join("assets/model.bin"))
3260
        .unwrap()
3261
        .permissions()
3262
        .readonly());
3263
    assert!(repo.lock_path("plain.dat").is_err(), "not lockable");
3264
    repo.lock_path("assets/model.bin").unwrap();
3265
    assert!(!fs::metadata(root.join("assets/model.bin"))
3266
        .unwrap()
3267
        .permissions()
3268
        .readonly());
3269
    assert!(repo.is_locked("assets/model.bin"));
3270
    write(root, "assets/model.bin", b"\0model2");
3271
    repo.commit("edit model", &[]).unwrap();
3272
    repo.unlock_path("assets/model.bin").unwrap();
3273
    assert!(fs::metadata(root.join("assets/model.bin"))
3274
        .unwrap()
3275
        .permissions()
3276
        .readonly());
3277
    // A later checkout can still overwrite a read-only lockable file.
3278
    repo.checkout(&[h], true, "co").unwrap();
3279
    assert_eq!(fs::read(root.join("assets/model.bin")).unwrap(), b"\0model");
3280
}
3281
3282
#[cfg(unix)]
3283
#[test]
3284
fn hooks_can_veto_observe_and_add_dependencies() {
3285
    use std::os::unix::fs::PermissionsExt;
3286
    hermetic();
3287
    let dir = tempfile::tempdir().unwrap();
3288
    let root = dir.path();
3289
    let mut repo = Repo::init(root).unwrap().with_home(root.join("home"));
3290
    let hooks = root.join(".oxy/hooks");
3291
    fs::create_dir_all(&hooks).unwrap();
3292
    let hook = |name: &str, body: &str| {
3293
        let p = hooks.join(name);
3294
        fs::write(&p, format!("#!/bin/sh\n{body}\n")).unwrap();
3295
        fs::set_permissions(&p, fs::Permissions::from_mode(0o755)).unwrap();
3296
    };
3297
    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");
3298
    hook("post-commit", "cat > \"$OXY_ROOT/.last-post-commit\"");
3299
    hook("post-checkout", "cat > \"$OXY_ROOT/.last-post-checkout\"");
3300
    hook("pre-push", "echo pushing blocked >&2; exit 3");
3301
    write(root, ".oxyignore", b".last-*\n");
3302
    write(root, "a.txt", b"a\n");
3303
    let err = repo.commit("WIP: nope", &[]).unwrap_err().to_string();
3304
    assert!(err.contains("pre-commit refused: no WIP commits"), "{err}");
3305
    let h1 = repo.commit("first", &[]).unwrap();
3306
    let pre = fs::read_to_string(root.join(".last-pre-commit")).unwrap();
3307
    assert!(
3308
        pre.contains("\"event\":\"pre-commit\"")
3309
            && pre.contains("\"path\":\"a.txt\"")
3310
            && pre.contains("\"message\":\"first\""),
3311
        "{pre}"
3312
    );
3313
    let post = fs::read_to_string(root.join(".last-post-commit")).unwrap();
3314
    assert!(post.contains(&h1.to_hex()), "{post}");
3315
    repo.checkout(&[h1], false, "co").unwrap();
3316
    assert!(fs::read_to_string(root.join(".last-post-checkout"))
3317
        .unwrap()
3318
        .contains("post-checkout"));
3319
    repo.config.set("remote.origin.url", "/nowhere").unwrap();
3320
    repo.save_config().unwrap();
3321
    let err = repo.push("origin", false).unwrap_err().to_string();
3322
    assert!(err.contains("pre-push refused: pushing blocked"), "{err}");
3323
3324
    // semantic-deps: only when enabled; adds an explicit dependency.
3325
    write(root, "b.txt", b"b\n");
3326
    hook(
3327
        "semantic-deps",
3328
        &format!(
3329
            "cat > \"$OXY_ROOT/.last-semantic\"; echo '{{\"deps\": [\"{}\"]}}'",
3330
            h1.to_hex()
3331
        ),
3332
    );
3333
    let h2 = repo.commit("b without hook", &[]).unwrap();
3334
    assert!(
3335
        repo.store().get_change(&h2).unwrap().deps.is_empty(),
3336
        "hook disabled by default"
3337
    );
3338
    repo.config.set("hooks.semantic-deps", "true").unwrap();
3339
    repo.save_config().unwrap();
3340
    write(root, "c.txt", b"c\n");
3341
    let h3 = repo.commit("c with hook", &[]).unwrap();
3342
    assert_eq!(repo.store().get_change(&h3).unwrap().deps, vec![h1]);
3343
    let sem = fs::read_to_string(root.join(".last-semantic")).unwrap();
3344
    assert!(
3345
        sem.contains("\"touched_paths\":[\"c.txt\"]") && sem.contains("candidate_deps"),
3346
        "{sem}"
3347
    );
3348
    assert_eq!(json_str("a\"b\\c\n"), "\"a\\\"b\\\\c\\n\"");
3349
}
3350
3351
#[test]
3352
fn amend_into_older_change_and_split() {
3353
    hermetic();
3354
    let dir = tempfile::tempdir().unwrap();
3355
    let root = dir.path();
3356
    let mut repo = Repo::init(root).unwrap().with_home(root.join("home"));
3357
    repo.create_identity("Ada", "a@b", IdentityScope::User)
3358
        .unwrap();
3359
    repo.set_user_config("core.sign", "change").unwrap();
3360
    write(root, "a.txt", b"one\ntwo\n");
3361
    let h0 = repo.commit("base", &[]).unwrap();
3362
    write(root, "a.txt", b"one\nTWO\n");
3363
    let h1 = repo.commit("edit two", &[]).unwrap();
3364
    write(root, "a.txt", b"one\nTWO\nthree\n");
3365
    let h2 = repo.commit("add three", &[]).unwrap();
3366
    let id1 = repo.store().get_change(&h1).unwrap().change_id;
3367
3368
    // Fixing the line h1 introduced folds into h1; h2 is rewritten on top.
3369
    write(root, "a.txt", b"one\nTWO!\nthree\n");
3370
    let h1b = repo.amend_into(&h1, None).unwrap();
3371
    assert_ne!(h1b, h1);
3372
    let c1b = repo.store().get_change(&h1b).unwrap();
3373
    assert_eq!(c1b.change_id, id1);
3374
    assert_eq!(c1b.deps, vec![h0]);
3375
    assert!(matches!(
3376
        repo.verify_change(&h1b).unwrap(),
3377
        SignatureStatus::Valid { .. }
3378
    ));
3379
    let heads = repo.bookmark_heads().unwrap();
3380
    assert_eq!(heads.len(), 1);
3381
    let top = repo.store().get_change(&heads[0]).unwrap();
3382
    assert_eq!(top.message, "add three");
3383
    assert_eq!(
3384
        top.deps.iter().copied().collect::<BTreeSet<_>>(),
3385
        [h0, h1b].into_iter().collect(),
3386
        "depends on the file's creator and the rewritten line"
3387
    );
3388
    let snap = repo.load_state(&heads).unwrap().materialize();
3389
    assert!(
3390
        matches!(&snap.files["a.txt"].content, FileContent::Text { bytes, .. } if bytes == b"one\nTWO!\nthree\n")
3391
    );
3392
    assert!(
3393
        !repo.snapshot("status").unwrap().changed,
3394
        "the working copy is clean after folding"
3395
    );
3396
    // Only h1b's own state shows the fix without "three".
3397
    let only = repo.load_state(&[h1b]).unwrap().materialize();
3398
    assert!(
3399
        matches!(&only.files["a.txt"].content, FileContent::Text { bytes, .. } if bytes == b"one\nTWO!\n")
3400
    );
3401
    assert_eq!(repo.log().unwrap().len(), 4);
3402
3403
    // An edit to a line introduced by h2 cannot fold into h1.
3404
    write(root, "a.txt", b"one\nTWO!\nthree!\n");
3405
    let err = repo.amend_into(&h1b, None).unwrap_err().to_string();
3406
    assert!(err.contains("introduced after"), "{err}");
3407
    assert!(
3408
        repo.snapshot("status").unwrap().statuses.len() == 1,
3409
        "nothing was changed by the refusal"
3410
    );
3411
    write(root, "a.txt", b"one\nTWO!\nthree\n");
3412
3413
    // Split the head that touches two files.
3414
    write(root, "b.txt", b"b\n");
3415
    write(root, "c.txt", b"c\n");
3416
    let h3 = repo.commit("b and c", &[]).unwrap();
3417
    let id3 = repo.store().get_change(&h3).unwrap().change_id;
3418
    let (p1, p2) = repo.split(&h3, &["b.txt".into()]).unwrap();
3419
    let c_1 = repo.store().get_change(&p1).unwrap();
3420
    let c_2 = repo.store().get_change(&p2).unwrap();
3421
    assert!(c_1.message.contains("part 1: b.txt"));
3422
    assert_eq!(c_2.change_id, id3);
3423
    let heads: BTreeSet<_> = repo.bookmark_heads().unwrap().into_iter().collect();
3424
    assert!(
3425
        heads.contains(&p1) && heads.contains(&p2),
3426
        "independent parts are both heads"
3427
    );
3428
    let snap = repo
3429
        .load_state(&repo.bookmark_heads().unwrap())
3430
        .unwrap()
3431
        .materialize();
3432
    assert!(snap.files.contains_key("b.txt") && snap.files.contains_key("c.txt"));
3433
    let only1 = repo.load_state(&[p1]).unwrap().materialize();
3434
    assert!(only1.files.contains_key("b.txt") && !only1.files.contains_key("c.txt"));
3435
    assert!(!repo.snapshot("status").unwrap().changed);
3436
    assert!(repo.split(&p2, &["nope.txt".into()]).is_err());
3437
    let _ = h2;
3438
}
3439
3440
#[test]
3441
fn identity_lifecycle() {
3442
    hermetic();
3443
    let dir = tempfile::tempdir().unwrap();
3444
    let root = dir.path();
3445
    let origin = Repo::init(&root.join("origin")).unwrap();
3446
    let url = root.join("origin").to_string_lossy().to_string();
3447
    let mut a = Repo::clone(&url, &root.join("a"))
3448
        .unwrap()
3449
        .with_home(root.join("home-a"));
3450
    a.set_user_config("core.sign", "change").unwrap();
3451
    let (key_a, _) = a
3452
        .create_identity("Ada", "[email protected]", IdentityScope::User)
3453
        .unwrap();
3454
    write(&root.join("a"), "a.txt", b"a\n");
3455
    let h1 = a.commit("one", &[]).unwrap();
3456
    assert!(a.policy_init().unwrap().applied);
3457
    assert!(a.push("origin", false).unwrap().iter().all(|r| r.ok));
3458
    origin.refresh().unwrap();
3459
3460
    // Expiry: an identity that had expired when the change was made does not authenticate it.
3461
    let mut e = Repo::init(&root.join("e"))
3462
        .unwrap()
3463
        .with_home(root.join("home-e"));
3464
    e.set_user_config("core.sign", "change").unwrap();
3465
    e.create_identity_with(
3466
        "Eve",
3467
        "[email protected]",
3468
        IdentityScope::User,
3469
        Some(Hlc::now().wall_ms - 1),
3470
    )
3471
    .unwrap();
3472
    write(&root.join("e"), "e.txt", b"e\n");
3473
    let he = e.commit("late", &[]).unwrap();
3474
    assert!(
3475
        matches!(e.verify_change(&he).unwrap(), SignatureStatus::Invalid(m) if m.contains("expired"))
3476
    );
3477
    // Renewal re-issues the identity (same keys, new KeyId) with a later expiry.
3478
    let r = e
3479
        .renew_identity(Some(Hlc::now().wall_ms + 86_400_000))
3480
        .unwrap();
3481
    assert_eq!(e.identity(&r.new).unwrap().previous, Some(r.old));
3482
    write(&root.join("e"), "e.txt", b"e2\n");
3483
    let he2 = e.commit("in time", &[]).unwrap();
3484
    assert!(
3485
        matches!(e.verify_change(&he2).unwrap(), SignatureStatus::Valid { key, .. } if key == r.new)
3486
    );
3487
3488
    // Rotation: a fresh key; the old change still verifies; the policy follows.
3489
    let r = a.rotate_identity().unwrap();
3490
    assert_eq!(r.old, key_a);
3491
    assert_eq!(a.config.author_key, Some(r.new));
3492
    assert_eq!(a.identity(&r.new).unwrap().previous, Some(key_a));
3493
    assert!(r.policy.as_ref().unwrap().applied);
3494
    let (_, sp) = a.current_policy().unwrap().unwrap();
3495
    assert_eq!(
3496
        (sp.policy.serial, sp.policy.roots.clone()),
3497
        (2, vec![r.new])
3498
    );
3499
    assert!(
3500
        !sp.policy.revoked.contains(&key_a) && sp.policy.authorizes(&r.new, "main"),
3501
        "superseded, not revoked"
3502
    );
3503
    assert!(sp.policy.succeeds(&r.new, &key_a) && !sp.policy.succeeds(&key_a, &r.new));
3504
    assert!(
3505
        matches!(a.verify_change(&h1).unwrap(), SignatureStatus::Valid { key, revoked: false, .. } if key == key_a)
3506
    );
3507
    write(&root.join("a"), "a.txt", b"a2\n");
3508
    let h2 = a.commit("two", &[]).unwrap();
3509
    assert!(
3510
        matches!(a.verify_change(&h2).unwrap(), SignatureStatus::Valid { key, revoked: false, .. } if key == r.new)
3511
    );
3512
    // Origin accepts the rotated policy (signed by the old root) and the new key's change.
3513
    let res = a.push("origin", false).unwrap();
3514
    origin.refresh().unwrap();
3515
    assert!(res.iter().all(|x| x.ok), "{res:?}");
3516
    assert_eq!(origin.current_policy().unwrap().unwrap().1.policy.serial, 2);
3517
    let key_a = r.new;
3518
3519
    // Delegation: Bob may sign on Ada's behalf. Delegates live in the
3520
    // identity object, so Ada's KeyId changes while her keys stay the same.
3521
    let mut b = Repo::clone(&url, &root.join("b"))
3522
        .unwrap()
3523
        .with_home(root.join("home-b"));
3524
    let (key_b, id_b) = b
3525
        .create_identity("Bob", "[email protected]", IdentityScope::User)
3526
        .unwrap();
3527
    let r = a.delegate_add(id_b.clone(), Scope::ALL, None).unwrap();
3528
    assert_eq!(r.old, key_a);
3529
    let key_a2 = r.new;
3530
    assert_eq!(
3531
        a.identity(&key_a2).unwrap().delegates,
3532
        vec![Delegate::full(key_b)]
3533
    );
3534
    assert_eq!(
3535
        a.identity(&key_a2).unwrap().ed25519_pk,
3536
        a.identity(&key_a).unwrap().ed25519_pk
3537
    );
3538
    assert!(
3539
        a.delegate_add(id_b.clone(), Scope::ALL, None).is_err(),
3540
        "already a delegate"
3541
    );
3542
    assert!(a.push("origin", false).unwrap().iter().all(|x| x.ok));
3543
    origin.refresh().unwrap();
3544
    write(&root.join("a"), "a.txt", b"a3\n");
3545
    let h3 = a.commit("three", &[]).unwrap();
3546
    assert!(
3547
        matches!(a.verify_change(&h3).unwrap(), SignatureStatus::Valid { key, .. } if key == key_a2),
3548
        "the same secret signs under the new KeyId"
3549
    );
3550
    // A change authored by Ada but signed only by Bob verifies through the delegation.
3551
    a.set_user_config("core.sign", "seal").unwrap();
3552
    write(&root.join("a"), "a.txt", b"a4\n");
3553
    let h4 = a.commit("four", &[]).unwrap();
3554
    assert_eq!(a.verify_change(&h4).unwrap(), SignatureStatus::Unsigned);
3555
    let (_, sk_b) = b.secret_key().unwrap().unwrap();
3556
    a.store()
3557
        .put_signature(&h4, &sk_b.sign(Domain::Change, &key_b, &h4))
3558
        .unwrap();
3559
    assert!(
3560
        matches!(a.verify_change(&h4).unwrap(), SignatureStatus::Valid { key, .. } if key == key_b)
3561
    );
3562
    a.set_user_config("core.sign", "change").unwrap();
3563
    // Withdrawing the delegation re-issues the identity again.
3564
    let r = a.delegate_remove(&key_b).unwrap();
3565
    assert!(a.identity(&r.new).unwrap().delegates.is_empty());
3566
    assert!(a.delegate_remove(&key_b).is_err());
3567
    let key_a3 = r.new;
3568
    let res = a.push("origin", false).unwrap();
3569
    origin.refresh().unwrap();
3570
    assert!(res.iter().all(|x| x.ok), "{res:?}");
3571
3572
    // Multi-signer policy: Bob becomes a root and the threshold rises to 2,
3573
    // both applied under the old threshold of 1. A grant then needs Bob too.
3574
    assert!(a.policy_root_add(id_b.clone()).unwrap().applied);
3575
    assert!(a.policy_root_add(id_b.clone()).is_err());
3576
    assert!(a.policy_set_threshold(3).is_err());
3577
    assert!(a.policy_set_threshold(2).unwrap().applied);
3578
    assert!(a.push("origin", false).unwrap().iter().all(|x| x.ok));
3579
    origin.refresh().unwrap();
3580
    b.pull("origin").unwrap();
3581
    assert_eq!(
3582
        b.current_policy().unwrap().unwrap().1.policy.root_threshold,
3583
        2
3584
    );
3585
    let mut c = Repo::init(&root.join("c"))
3586
        .unwrap()
3587
        .with_home(root.join("home-c"));
3588
    let (key_c, id_c) = c
3589
        .create_identity("Cy", "[email protected]", IdentityScope::User)
3590
        .unwrap();
3591
    let serial_before = a.current_policy().unwrap().unwrap().1.policy.serial;
3592
    let proposal = a.policy_grant(id_c, None).unwrap();
3593
    assert!(!proposal.applied && proposal.sigs.len() == 1);
3594
    assert_eq!(proposal.policy.serial, serial_before + 1);
3595
    assert_eq!(
3596
        a.current_policy().unwrap().unwrap().1.policy.serial,
3597
        serial_before,
3598
        "a proposal changes nothing yet"
3599
    );
3600
    // Bob signs the proposal, handed over as a file, and it applies for him.
3601
    let bytes = proposal.signed().encode();
3602
    let signed = b
3603
        .policy_sign(SignedPolicy::decode(&bytes).unwrap())
3604
        .unwrap();
3605
    assert!(signed.applied && signed.sigs.len() == 2);
3606
    assert!(b
3607
        .current_policy()
3608
        .unwrap()
3609
        .unwrap()
3610
        .1
3611
        .policy
3612
        .authorizes(&key_c, "main"));
3613
    assert!(
3614
        b.policy_sign(signed.signed()).is_err(),
3615
        "a stale proposal is refused"
3616
    );
3617
    // Bob publishes it and Ada picks it up.
3618
    assert!(b
3619
        .push("origin", false)
3620
        .unwrap()
3621
        .iter()
3622
        .any(|x| x.name == "policy" && x.ok));
3623
    origin.refresh().unwrap();
3624
    a.pull("origin").unwrap();
3625
    assert_eq!(
3626
        a.current_policy().unwrap().unwrap().1.policy.serial,
3627
        serial_before + 1
3628
    );
3629
    // A root cannot revoke itself; revoking Cy needs both roots but is recorded locally at once.
3630
    assert!(a.policy_revoke(&key_a3).is_err());
3631
    let u = a
3632
        .revoke_identity(&key_c, "left the project")
3633
        .unwrap()
3634
        .unwrap();
3635
    assert!(!u.applied);
3636
    assert!(a.is_revoked(&key_c).unwrap());
3637
    assert!(!b.is_revoked(&key_c).unwrap());
3638
    let u = b.policy_sign(u.signed()).unwrap();
3639
    assert!(u.applied && u.policy.is_revoked(&key_c));
3640
    assert!(b.is_revoked(&key_c).unwrap());
3641
    // Bob can revoke Ada's root key, leaving himself as the only root (threshold 2 would be unmeetable).
3642
    assert!(
3643
        b.policy_revoke(&key_a3).is_err(),
3644
        "would leave one root for a threshold of 2"
3645
    );
3646
    // Revoking one's own key without a policy root works locally: a plain marker plus attestation.
3647
    let key_c_own = c.config.author_key.unwrap();
3648
    assert!(c
3649
        .revoke_identity(&key_c_own, "lost laptop")
3650
        .unwrap()
3651
        .is_none());
3652
    assert!(c.is_revoked(&key_c_own).unwrap());
3653
    assert_eq!(key_c_own, key_c);
3654
}
3655
3656
#[test]
3657
fn renames_are_detected_and_tracked_as_moves() {
3658
    hermetic();
3659
    let dir = tempfile::tempdir().unwrap();
3660
    let root = dir.path();
3661
    let repo = Repo::init(root).unwrap().with_home(root.join("home"));
3662
    write(
3663
        root,
3664
        "src/old.rs",
3665
        b"fn a() {}\nfn b() {}\nfn c() {}\nfn d() {}\n",
3666
    );
3667
    write(root, "img.bin", b"\x89PNG\0\0\x01\x02");
3668
    write(root, "tiny.txt", b"x\n");
3669
    let h1 = repo.commit("base", &[]).unwrap();
3670
    let node_old = repo.load_state(&[h1]).unwrap().materialize().files["src/old.rs"].node;
3671
    let node_img = repo.load_state(&[h1]).unwrap().materialize().files["img.bin"].node;
3672
3673
    // Rename with a small edit, a binary moved unchanged, and a rewrite
3674
    // that shares nothing with the removed file.
3675
    fs::remove_file(root.join("src/old.rs")).unwrap();
3676
    write(
3677
        root,
3678
        "lib/new.rs",
3679
        b"fn a() {}\nfn b() {}\nfn c() {}\nfn e() {}\n",
3680
    );
3681
    fs::remove_file(root.join("img.bin")).unwrap();
3682
    write(root, "assets/img.bin", b"\x89PNG\0\0\x01\x02");
3683
    fs::remove_file(root.join("tiny.txt")).unwrap();
3684
    write(root, "other.txt", b"completely different\n");
3685
    let snap = repo.snapshot("status").unwrap();
3686
    let statuses: Vec<(&str, ChangeStatus)> = snap
3687
        .statuses
3688
        .iter()
3689
        .map(|s| (s.path.as_str(), s.status))
3690
        .collect();
3691
    assert_eq!(
3692
        statuses,
3693
        vec![
3694
            ("assets/img.bin", ChangeStatus::Renamed),
3695
            ("lib/new.rs", ChangeStatus::Renamed),
3696
            ("other.txt", ChangeStatus::Added),
3697
            ("src", ChangeStatus::Removed),
3698
            ("tiny.txt", ChangeStatus::Removed)
3699
        ]
3700
    );
3701
    let h2 = repo.commit("move things", &[]).unwrap();
3702
    let c = repo.store().get_change(&h2).unwrap();
3703
    let moves: Vec<_> = c
3704
        .tree_ops
3705
        .iter()
3706
        .filter(|op| matches!(op, TreeOp::Move { .. }))
3707
        .collect();
3708
    assert_eq!(moves.len(), 2, "{:?}", c.tree_ops);
3709
    assert!(c.tree_ops.iter().any(
3710
        |op| matches!(op, TreeOp::Move { node, name, .. } if *node == node_old && name == "new.rs")
3711
    ));
3712
    assert!(c.tree_ops.iter().any(
3713
        |op| matches!(op, TreeOp::Move { node, name, .. } if *node == node_img && name == "img.bin")
3714
    ));
3715
    let snap = repo.load_state(&[h2]).unwrap().materialize();
3716
    assert_eq!(
3717
        snap.files["lib/new.rs"].node, node_old,
3718
        "the node survives the rename"
3719
    );
3720
    assert!(
3721
        matches!(&snap.files["lib/new.rs"].content, FileContent::Text { bytes, .. } if bytes == b"fn a() {}\nfn b() {}\nfn c() {}\nfn e() {}\n")
3722
    );
3723
    assert!(!snap.files.contains_key("src/old.rs") && !snap.files.contains_key("src"));
3724
    assert!(render_change(
3725
        &c,
3726
        &repo.load_state(&[h1]).unwrap(),
3727
        &repo.load_state(&[h1]).unwrap().materialize()
3728
    )
3729
    .contains("R "));
3730
    // A fresh checkout reproduces the tree.
3731
    let other = tempfile::tempdir().unwrap();
3732
    let clone = Repo::clone(&root.to_string_lossy(), other.path()).unwrap();
3733
    assert_eq!(
3734
        fs::read(other.path().join("lib/new.rs")).unwrap(),
3735
        b"fn a() {}\nfn b() {}\nfn c() {}\nfn e() {}\n"
3736
    );
3737
    assert!(!other.path().join("src").exists());
3738
    assert!(!clone.snapshot("status").unwrap().changed);
3739
    // Similarity is line based, byte weighted.
3740
    assert_eq!(similarity(b"a\nb\n", b"a\nb\n"), 100);
3741
    assert_eq!(similarity(b"a\nb\nc\nd\n", b"a\nb\nx\ny\n"), 50);
3742
    assert_eq!(similarity(b"hello\n", b"world\n"), 0);
3743
    assert_eq!(similarity(b"", b"x\n"), 0);
3744
}
3745
3746
#[test]
3747
fn git_fetch_and_push_round_trip() {
3748
    hermetic();
3749
    if std::process::Command::new("git")
3750
        .arg("--version")
3751
        .output()
3752
        .is_err()
3753
    {
3754
        eprintln!("git not installed; skipping");
3755
        return;
3756
    }
3757
    let dir = tempfile::tempdir().unwrap();
3758
    let root = dir.path();
3759
    let git_in = |d: &Path, args: &[&str]| -> String {
3760
        let out = std::process::Command::new("git")
3761
            .arg("-C")
3762
            .arg(d)
3763
            .args([
3764
                "-c",
3765
                "user.name=Grace",
3766
                "-c",
3767
                "[email protected]",
3768
                "-c",
3769
                "commit.gpgsign=false",
3770
            ])
3771
            .args(args)
3772
            .output()
3773
            .unwrap();
3774
        assert!(
3775
            out.status.success(),
3776
            "git {args:?}: {}",
3777
            String::from_utf8_lossy(&out.stderr)
3778
        );
3779
        String::from_utf8_lossy(&out.stdout).trim().to_string()
3780
    };
3781
    // A bare "remote" and a work tree that pushes to it.
3782
    let remote = root.join("remote.git");
3783
    fs::create_dir_all(&remote).unwrap();
3784
    git_in(&remote, &["init", "-q", "--bare", "-b", "main"]);
3785
    let work = root.join("work");
3786
    git_in(
3787
        root,
3788
        &[
3789
            "clone",
3790
            "-q",
3791
            remote.to_str().unwrap(),
3792
            work.to_str().unwrap(),
3793
        ],
3794
    );
3795
    git_in(&work, &["checkout", "-q", "-b", "main"]);
3796
    write(&work, "README.md", b"# Project\n");
3797
    write(&work, "src/lib.rs", b"pub fn a() {}\n");
3798
    git_in(&work, &["add", "."]);
3799
    git_in(&work, &["commit", "-q", "-m", "initial"]);
3800
    write(&work, "src/lib.rs", b"pub fn a() {}\npub fn b() {}\n");
3801
    git_in(&work, &["commit", "-q", "-am", "second"]);
3802
    git_in(&work, &["push", "-q", "origin", "main"]);
3803
    let tip1 = git_in(&work, &["rev-parse", "HEAD"]);
3804
3805
    // Fetch into a fresh oxy repository.
3806
    let o = root.join("oxy");
3807
    let mut repo = Repo::init(&o).unwrap().with_home(root.join("home"));
3808
    repo.create_identity("Ada", "[email protected]", IdentityScope::User)
3809
        .unwrap();
3810
    let url = remote.to_string_lossy().to_string();
3811
    let r = repo.git_fetch(&url, "main").unwrap();
3812
    assert_eq!((r.commits, r.heads), (2, 1));
3813
    assert_eq!(
3814
        fs::read(o.join("src/lib.rs")).unwrap(),
3815
        b"pub fn a() {}\npub fn b() {}\n"
3816
    );
3817
    assert!(!repo.snapshot("status").unwrap().changed);
3818
    assert_eq!(
3819
        repo.git_fetch(&url, "main").unwrap().commits,
3820
        0,
3821
        "nothing new"
3822
    );
3823
3824
    // An oxy change, pushed back: one commit on top of the Git tip.
3825
    write(
3826
        &o,
3827
        "src/lib.rs",
3828
        b"pub fn a() {}\npub fn b() {}\npub fn c() {}\n",
3829
    );
3830
    write(&o, "NOTES.md", b"from oxy\n");
3831
    let h_oxy = repo.commit("add c and notes", &[]).unwrap();
3832
    let r = repo.git_push(&url, "main").unwrap();
3833
    assert_eq!(r.exported, 1, "{r:?}");
3834
    git_in(&work, &["pull", "-q", "--ff-only", "origin", "main"]);
3835
    assert_eq!(
3836
        git_in(&work, &["log", "--format=%s", "main"]),
3837
        "add c and notes\nsecond\ninitial"
3838
    );
3839
    assert_eq!(git_in(&work, &["rev-parse", "HEAD~1"]), tip1);
3840
    assert_eq!(fs::read(work.join("NOTES.md")).unwrap(), b"from oxy\n");
3841
    assert_eq!(git_in(&work, &["log", "-1", "--format=%an", "main"]), "Ada");
3842
    assert!(git_in(&work, &["log", "-1", "--format=%B", "main"])
3843
        .contains(&format!("Oxy-Hash: {}", h_oxy.to_hex())));
3844
    assert_eq!(
3845
        repo.git_push(&url, "main").unwrap().exported,
3846
        0,
3847
        "already pushed"
3848
    );
3849
3850
    // Git moves on; pushing without fetching is refused, fetching brings
3851
    // the commit in and the working copy follows.
3852
    write(&work, "README.md", b"# Project\n\nMore.\n");
3853
    git_in(&work, &["commit", "-q", "-am", "readme from git"]);
3854
    git_in(&work, &["push", "-q", "origin", "main"]);
3855
    let tip2 = git_in(&work, &["rev-parse", "HEAD"]);
3856
    assert!(repo
3857
        .git_push(&url, "main")
3858
        .unwrap_err()
3859
        .to_string()
3860
        .contains("fetch"));
3861
    let r = repo.git_fetch(&url, "main").unwrap();
3862
    assert_eq!(
3863
        (r.commits, r.heads),
3864
        (1, 2),
3865
        "the Git change and the oxy change commute"
3866
    );
3867
    assert_eq!(
3868
        fs::read(o.join("README.md")).unwrap(),
3869
        b"# Project\n\nMore.\n"
3870
    );
3871
    assert_eq!(fs::read(o.join("NOTES.md")).unwrap(), b"from oxy\n");
3872
    assert!(!repo.snapshot("status").unwrap().changed);
3873
    // Another oxy change pushes on top of Git's newest commit.
3874
    write(&o, "NOTES.md", b"from oxy\nagain\n");
3875
    repo.commit("notes again", &[]).unwrap();
3876
    assert_eq!(repo.git_push(&url, "main").unwrap().exported, 1);
3877
    git_in(&work, &["pull", "-q", "--ff-only", "origin", "main"]);
3878
    assert_eq!(git_in(&work, &["rev-parse", "HEAD~1"]), tip2);
3879
    assert_eq!(
3880
        fs::read(work.join("NOTES.md")).unwrap(),
3881
        b"from oxy\nagain\n"
3882
    );
3883
    assert_eq!(
3884
        git_in(&work, &["log", "--format=%s", "main"])
3885
            .lines()
3886
            .count(),
3887
        5
3888
    );
3889
}
3890
3891
/// Benchmark, not a gate: `cargo test --release -p oxy-core --lib bench_one_gibibyte -- --ignored --nocapture`.
3892
/// Commits, stores, clones, and reads back a 1 GiB incompressible file.
3893
#[test]
3894
#[ignore]
3895
fn bench_one_gibibyte_file() {
3896
    hermetic();
3897
    // /tmp is often a small tmpfs; `OXY_BENCH_DIR` picks a roomier disk.
3898
    let dir = match std::env::var_os("OXY_BENCH_DIR") {
3899
        Some(d) => tempfile::tempdir_in(d).unwrap(),
3900
        None => tempfile::tempdir().unwrap(),
3901
    };
3902
    let root = dir.path();
3903
    let repo = Repo::init(&root.join("r"))
3904
        .unwrap()
3905
        .with_home(root.join("home"));
3906
    let size = 1usize << 30;
3907
    let mut data = vec![0u8; size];
3908
    let mut x = 0x9e3779b97f4a7c15u64;
3909
    for chunk in data.chunks_mut(8) {
3910
        x ^= x << 13;
3911
        x ^= x >> 7;
3912
        x ^= x << 17;
3913
        let b = x.to_le_bytes();
3914
        chunk.copy_from_slice(&b[..chunk.len()]);
3915
    }
3916
    let t = std::time::Instant::now();
3917
    write(&root.join("r"), "big.bin", &data);
3918
    eprintln!("write 1 GiB to disk: {:.2?}", t.elapsed());
3919
    let t = std::time::Instant::now();
3920
    let h = repo.commit("big", &[]).unwrap();
3921
    eprintln!("commit (chunk + hash + store): {:.2?}", t.elapsed());
3922
    let t = std::time::Instant::now();
3923
    assert!(!repo.snapshot("status").unwrap().changed);
3924
    eprintln!("status on a clean 1 GiB working copy: {:.2?}", t.elapsed());
3925
    let t = std::time::Instant::now();
3926
    let objects = repo.store().list().unwrap().len();
3927
    eprintln!("objects stored: {objects} ({:.2?} to list)", t.elapsed());
3928
    let t = std::time::Instant::now();
3929
    let g = repo.gc(true).unwrap();
3930
    eprintln!("gc (pack): {:.2?} {g:?}", t.elapsed());
3931
    let t = std::time::Instant::now();
3932
    let clone = Repo::clone(&root.join("r").to_string_lossy(), &root.join("c")).unwrap();
3933
    eprintln!("clone (fetch + checkout): {:.2?}", t.elapsed());
3934
    let t = std::time::Instant::now();
3935
    let back = fs::read(root.join("c/big.bin")).unwrap();
3936
    assert_eq!(blake3::hash(&back), blake3::hash(&data));
3937
    eprintln!("read back and verify: {:.2?}", t.elapsed());
3938
    assert_eq!(clone.bookmark_heads().unwrap(), vec![h]);
3939
    let store_bytes: u64 = walkdir_size(&root.join("r/.oxy/objects"));
3940
    eprintln!(
3941
        "store size: {:.1} MiB for 1 GiB of data",
3942
        store_bytes as f64 / (1024.0 * 1024.0)
3943
    );
3944
}
3945
3946
fn walkdir_size(p: &Path) -> u64 {
3947
    let mut total = 0;
3948
    if let Ok(rd) = fs::read_dir(p) {
3949
        for e in rd.flatten() {
3950
            let path = e.path();
3951
            if path.is_dir() {
3952
                total += walkdir_size(&path);
3953
            } else if let Ok(m) = fs::metadata(&path) {
3954
                total += m.len();
3955
            }
3956
        }
3957
    }
3958
    total
3959
}
3960
3961
/// An opaque file whose size and mtime match the manifest is not read on
3962
/// the next snapshot: its blob comes from the manifest's stat cache.
3963
#[cfg(unix)]
3964
#[test]
3965
fn stat_cache_skips_reading_unchanged_opaque_files() {
3966
    use std::os::unix::fs::PermissionsExt;
3967
    hermetic();
3968
    let dir = tempfile::tempdir().unwrap();
3969
    let root = dir.path();
3970
    let repo = Repo::init(root).unwrap().with_home(root.join("home"));
3971
    let mut big = vec![0u8; 300 * 1024];
3972
    for (i, b) in big.iter_mut().enumerate() {
3973
        *b = (i as u32).wrapping_mul(2654435761).to_le_bytes()[1];
3974
    }
3975
    big[0] = 0;
3976
    write(root, "big.bin", &big);
3977
    write(root, "a.txt", b"text\n");
3978
    let h1 = repo.commit("base", &[]).unwrap();
3979
    let (_, _, m) = repo.read_manifest().unwrap().unwrap();
3980
    assert!(
3981
        m.entries["big.bin"].blob.is_some(),
3982
        "opaque files record their blob"
3983
    );
3984
    assert!(m.entries["a.txt"].blob.is_none());
3985
    let blob = m.entries["big.bin"].blob.unwrap();
3986
    assert!(repo.store().has(&blob));
3987
3988
    // Files modified within two seconds of the manifest are racy and still
3989
    // read; age the file so the cache applies, then snapshot to record it.
3990
    let old = std::time::SystemTime::now() - std::time::Duration::from_secs(30);
3991
    fs::File::options()
3992
        .write(true)
3993
        .open(root.join("big.bin"))
3994
        .unwrap()
3995
        .set_modified(old)
3996
        .unwrap();
3997
    assert!(!repo.snapshot("status").unwrap().changed);
3998
    // Now the file cannot be read at all; the snapshot succeeds without it.
3999
    fs::set_permissions(root.join("big.bin"), fs::Permissions::from_mode(0o000)).unwrap();
4000
    let snap = repo.snapshot("status").unwrap();
4001
    assert!(
4002
        !snap.changed && snap.statuses.is_empty(),
4003
        "{:?}",
4004
        snap.statuses
4005
    );
4006
    fs::set_permissions(root.join("big.bin"), fs::Permissions::from_mode(0o644)).unwrap();
4007
    // A real change (new mtime, new content) is seen and committed correctly.
4008
    let mut big2 = big.clone();
4009
    big2[10] ^= 0xff;
4010
    write(root, "big.bin", &big2);
4011
    let snap = repo.snapshot("status").unwrap();
4012
    assert_eq!(
4013
        snap.statuses
4014
            .iter()
4015
            .map(|s| (s.path.as_str(), s.status))
4016
            .collect::<Vec<_>>(),
4017
        vec![("big.bin", ChangeStatus::Modified)]
4018
    );
4019
    let h2 = repo.commit("edit", &[]).unwrap();
4020
    let files = repo.load_state(&[h2]).unwrap().materialize().files;
4021
    assert_eq!(
4022
        files["big.bin"].content,
4023
        FileContent::Opaque {
4024
            blobs: vec![Repo::blob_ref(&big2)]
4025
        }
4026
    );
4027
    // Checkout writes a manifest with blobs too, so the next status is cached.
4028
    repo.checkout(&[h1], false, "checkout").unwrap();
4029
    let (_, _, m) = repo.read_manifest().unwrap().unwrap();
4030
    assert_eq!(m.entries["big.bin"].blob, Some(Repo::blob_ref(&big)));
4031
    assert!(!repo.snapshot("status").unwrap().changed);
4032
}
4033
4034
#[test]
4035
fn status_json_lists_conflicts_with_contributors() {
4036
    hermetic();
4037
    let dir = tempfile::tempdir().unwrap();
4038
    let root = dir.path();
4039
    let repo = Repo::init(root).unwrap().with_home(root.join("home"));
4040
    write(root, "a.txt", b"one\n");
4041
    let h1 = repo.commit("base", &[]).unwrap();
4042
    write(root, "a.txt", b"one\nleft\n");
4043
    let ha = repo.commit("left", &[]).unwrap();
4044
    repo.checkout(&[h1], true, "checkout").unwrap();
4045
    write(root, "a.txt", b"one\nright\n");
4046
    let hb = repo.commit("right", &[]).unwrap();
4047
    repo.checkout(&[ha, hb], true, "checkout").unwrap();
4048
    let snap = repo.snapshot("status").unwrap();
4049
    assert!(snap.base_snapshot.is_conflicted());
4050
    let json = repo.status_json(&snap).unwrap();
4051
    let ida = repo.store().get_change(&ha).unwrap().change_id.to_hex();
4052
    let idb = repo.store().get_change(&hb).unwrap().change_id.to_hex();
4053
    assert!(json.contains("\"conflicted\":true"), "{json}");
4054
    assert!(
4055
        json.contains("\"kind\":\"text\",\"path\":\"a.txt\""),
4056
        "{json}"
4057
    );
4058
    assert!(json.contains(&ida) && json.contains(&idb), "{json}");
4059
    assert!(json.contains("\"resolved\":false"), "{json}");
4060
    assert!(json.starts_with('{') && json.ends_with('}'));
4061
    // Resolve and the report says so; a clean copy has no conflicts.
4062
    write(root, "a.txt", b"one\nleft\nright\n");
4063
    let snap = repo.snapshot("status").unwrap();
4064
    let json = repo.status_json(&snap).unwrap();
4065
    assert!(json.contains("\"resolved\":true"), "{json}");
4066
    repo.commit("resolve", &[]).unwrap();
4067
    let snap = repo.snapshot("status").unwrap();
4068
    let json = repo.status_json(&snap).unwrap();
4069
    assert!(
4070
        json.contains("\"clean\":true,\"conflicted\":false,\"paths\":[],\"conflicts\":[]"),
4071
        "{json}"
4072
    );
4073
}
4074
4075
#[test]
4076
fn ignore_rules_do_not_untrack_files() {
4077
    hermetic();
4078
    let dir = tempfile::tempdir().unwrap();
4079
    let root = dir.path();
4080
    let repo = Repo::init(root).unwrap().with_home(root.join("home"));
4081
    write(root, "src.c", b"int x;\n");
4082
    write(root, "build/out.o", b"\0obj");
4083
    write(root, "sub/keep.log", b"keep\n");
4084
    write(root, "sub/junk.log", b"junk\n");
4085
    write(root, ".oxyignore", b"/build\n*.log\n!sub/keep.log\n");
4086
    let snap = repo.snapshot("status").unwrap();
4087
    let added: Vec<&str> = snap.statuses.iter().map(|s| s.path.as_str()).collect();
4088
    assert_eq!(
4089
        added,
4090
        vec![".oxyignore", "src.c", "sub/keep.log"],
4091
        "anchored, glob, and negated rules"
4092
    );
4093
    let h1 = repo.commit("base", &[]).unwrap();
4094
    // Ignoring a tracked file changes nothing about it.
4095
    write(root, ".oxyignore", b"/build\n*.log\n!sub/keep.log\nsrc.c\n");
4096
    let snap = repo.snapshot("status").unwrap();
4097
    assert_eq!(
4098
        snap.statuses
4099
            .iter()
4100
            .map(|s| s.path.as_str())
4101
            .collect::<Vec<_>>(),
4102
        vec![".oxyignore"]
4103
    );
4104
    let h2 = repo.commit("ignore src.c", &[]).unwrap();
4105
    assert!(repo
4106
        .load_state(&[h2])
4107
        .unwrap()
4108
        .materialize()
4109
        .files
4110
        .contains_key("src.c"));
4111
    // Its edits are still seen, by status and by the prompt.
4112
    assert_eq!(repo.quick_dirty().unwrap(), Some(false));
4113
    write(root, "src.c", b"int x, y;\n");
4114
    assert_eq!(repo.quick_dirty().unwrap(), Some(true));
4115
    let snap = repo.snapshot("status").unwrap();
4116
    assert_eq!(
4117
        snap.statuses
4118
            .iter()
4119
            .map(|s| (s.path.as_str(), s.status))
4120
            .collect::<Vec<_>>(),
4121
        vec![("src.c", ChangeStatus::Modified)]
4122
    );
4123
    let h3 = repo.commit("edit src.c", &[]).unwrap();
4124
    assert!(
4125
        matches!(&repo.load_state(&[h3]).unwrap().materialize().files["src.c"].content, FileContent::Text { bytes, .. } if bytes == b"int x, y;\n")
4126
    );
4127
    // Deleting it on disk removes it, ignored or not; a checkout brings it back.
4128
    fs::remove_file(root.join("src.c")).unwrap();
4129
    let snap = repo.snapshot("status").unwrap();
4130
    assert_eq!(
4131
        snap.statuses
4132
            .iter()
4133
            .map(|s| (s.path.as_str(), s.status))
4134
            .collect::<Vec<_>>(),
4135
        vec![("src.c", ChangeStatus::Removed)]
4136
    );
4137
    repo.checkout(&[h3], true, "checkout").unwrap();
4138
    assert_eq!(fs::read(root.join("src.c")).unwrap(), b"int x, y;\n");
4139
    assert!(!repo.snapshot("status").unwrap().changed);
4140
    let _ = h1;
4141
}
4142
4143
#[test]
4144
fn split_works_on_non_heads_by_node() {
4145
    hermetic();
4146
    let dir = tempfile::tempdir().unwrap();
4147
    let root = dir.path();
4148
    let repo = Repo::init(root).unwrap().with_home(root.join("home"));
4149
    write(root, "a.txt", b"one\n");
4150
    write(root, "junk/x.lock", b"lock\n");
4151
    let h1 = repo.commit("work plus junk", &[]).unwrap();
4152
    write(root, "a.txt", b"one\ntwo\n");
4153
    let h2 = repo.commit("more work", &[]).unwrap();
4154
    assert_eq!(repo.store().get_change(&h2).unwrap().deps, vec![h1]);
4155
    let id1 = repo.store().get_change(&h1).unwrap().change_id;
4156
    // h1 is not a head: split it by node.
4157
    let (hj, h1b) = repo.split(&h1, &["junk".into()]).unwrap();
4158
    assert_ne!(h1b, h1);
4159
    assert_eq!(
4160
        repo.store().get_change(&h1b).unwrap().change_id,
4161
        id1,
4162
        "the rest keeps the ChangeId"
4163
    );
4164
    let junk = repo.store().get_change(&hj).unwrap();
4165
    assert!(junk.tree_ops.iter().all(
4166
        |op| matches!(op, TreeOp::AddNode { name, .. } if name == "junk" || name == "x.lock")
4167
    ));
4168
    let heads = repo.bookmark_heads().unwrap();
4169
    assert!(
4170
        heads.contains(&hj),
4171
        "the split-off part is a head of its own"
4172
    );
4173
    let snap = repo.load_state(&heads).unwrap().materialize();
4174
    assert!(
4175
        matches!(&snap.files["a.txt"].content, FileContent::Text { bytes, .. } if bytes == b"one\ntwo\n"),
4176
        "the dependent was rewritten onto the new hash"
4177
    );
4178
    assert!(snap.files.contains_key("junk/x.lock"));
4179
    let h2b = heads
4180
        .iter()
4181
        .find(|h| repo.store().get_change(h).unwrap().message == "more work")
4182
        .copied()
4183
        .unwrap();
4184
    assert_eq!(repo.store().get_change(&h2b).unwrap().deps, vec![h1b]);
4185
    assert!(!repo.snapshot("status").unwrap().changed);
4186
    // Abandoning the split-off head removes the junk from history.
4187
    repo.abandon(&hj).unwrap();
4188
    let heads = repo.bookmark_heads().unwrap();
4189
    let snap = repo.load_state(&heads).unwrap().materialize();
4190
    assert!(!snap.files.contains_key("junk/x.lock") && !snap.files.contains_key("junk"));
4191
    assert!(snap.files.contains_key("a.txt"));
4192
    // A dependent that touches the split-off paths blocks the split.
4193
    write(root, "junk/y.lock", b"y\n");
4194
    let hb = repo.commit("junk base", &[]).unwrap();
4195
    write(root, "junk/y.lock", b"yy\n");
4196
    write(root, "b.txt", b"b\n");
4197
    repo.commit("touches junk", &[]).unwrap();
4198
    let err = repo.split(&hb, &["junk".into()]).unwrap_err().to_string();
4199
    assert!(err.contains("depends on the split-off paths"), "{err}");
4200
}
4201
4202
#[test]
4203
fn bookmarks_switch_merge_and_push() {
4204
    hermetic();
4205
    let dir = tempfile::tempdir().unwrap();
4206
    let root = dir.path();
4207
    let origin = Repo::init(&root.join("origin")).unwrap();
4208
    let url = root.join("origin").to_string_lossy().to_string();
4209
    let mut repo = Repo::clone(&url, &root.join("r"))
4210
        .unwrap()
4211
        .with_home(root.join("home"));
4212
    let r = root.join("r");
4213
    write(&r, "a.txt", b"a\n");
4214
    let h_a = repo.commit("a", &[]).unwrap();
4215
    assert!(repo.push("origin", false).unwrap()[0].ok);
4216
    origin.refresh().unwrap();
4217
4218
    // A bookmark at the working copy's base, then work on it.
4219
    assert!(repo.bookmark_create("bad name..", None).is_err());
4220
    assert!(repo.bookmark_create("-x", None).is_err());
4221
    assert_eq!(repo.bookmark_create("feature", None).unwrap(), vec![h_a]);
4222
    assert!(repo.bookmark_create("feature", None).is_err(), "exists");
4223
    repo.bookmark_switch("feature", false).unwrap();
4224
    assert_eq!(repo.config.bookmark, "feature");
4225
    write(&r, "a.txt", b"a\nb\n");
4226
    write(&r, "b.txt", b"b\n");
4227
    let h_b = repo.commit("b on feature", &[]).unwrap();
4228
    assert_eq!(
4229
        repo.bookmark_heads().unwrap(),
4230
        vec![h_b],
4231
        "b edits a.txt, so it depends on a"
4232
    );
4233
    assert_eq!(
4234
        repo.resolve_heads("main").unwrap(),
4235
        vec![h_a],
4236
        "main is untouched"
4237
    );
4238
    assert_eq!(
4239
        repo.resolve_change("feature").unwrap(),
4240
        h_b,
4241
        "a one-head bookmark names its change"
4242
    );
4243
    // Reopening keeps the workspace's bookmark.
4244
    let reopened = Repo::open(&r).unwrap().with_home(root.join("home"));
4245
    assert_eq!(reopened.config.bookmark, "feature");
4246
    // Back to main: b.txt goes away; work there.
4247
    repo.bookmark_switch("main", false).unwrap();
4248
    assert!(!r.join("b.txt").exists());
4249
    assert_eq!(fs::read(r.join("a.txt")).unwrap(), b"a\n");
4250
    write(&r, "c.txt", b"c\n");
4251
    let h_c = repo.commit("c on main", &[]).unwrap();
4252
    let list = repo.bookmarks().unwrap();
4253
    assert_eq!(
4254
        list.iter()
4255
            .map(|b| (b.name.as_str(), b.current))
4256
            .collect::<Vec<_>>(),
4257
        vec![("feature", false), ("main", true)]
4258
    );
4259
    assert_eq!(
4260
        list.iter().find(|b| b.name == "main").unwrap().ahead,
4261
        Some(1),
4262
        "c is not on origin yet"
4263
    );
4264
    // Merge feature into main: the union, both heads, no merge change.
4265
    let m = repo.merge("feature").unwrap();
4266
    assert!(m.changed && m.checked_out);
4267
    let mut want = vec![h_b, h_c];
4268
    want.sort();
4269
    assert_eq!(m.heads, want);
4270
    assert_eq!(fs::read(r.join("b.txt")).unwrap(), b"b\n");
4271
    assert!(!repo.merge("feature").unwrap().changed, "already merged");
4272
    assert!(repo.merge("main").is_err());
4273
    // The other bookmark can be pushed by name and appears at origin.
4274
    assert!(repo.push_bookmark("origin", "feature", false).unwrap()[0].ok);
4275
    origin.refresh().unwrap();
4276
    assert_eq!(origin.resolve_heads("feature").unwrap(), vec![h_b]);
4277
    assert!(repo.push("origin", false).unwrap()[0].ok);
4278
    origin.refresh().unwrap();
4279
    assert_eq!(
4280
        repo.bookmarks()
4281
            .unwrap()
4282
            .iter()
4283
            .find(|b| b.name == "main")
4284
            .unwrap()
4285
            .ahead,
4286
        Some(0)
4287
    );
4288
    // A second workspace inherits the current bookmark and can switch independently.
4289
    let ws = repo.workspace_add(&root.join("ws"), None).unwrap();
4290
    assert_eq!(ws.config.bookmark, "main");
4291
    let mut ws = ws;
4292
    ws.bookmark_switch("feature", false).unwrap();
4293
    assert_eq!(
4294
        Repo::open(&r).unwrap().config.bookmark,
4295
        "main",
4296
        "the first workspace is unaffected"
4297
    );
4298
    assert!(
4299
        repo.bookmark_delete("feature").is_err(),
4300
        "current bookmark of another workspace"
4301
    );
4302
    ws.bookmark_switch("main", false).unwrap();
4303
    // Set and delete.
4304
    assert_eq!(repo.bookmark_set("feature", &[h_a]).unwrap(), vec![h_a]);
4305
    assert!(repo.bookmark_delete("main").is_err(), "current here");
4306
    repo.bookmark_delete("feature").unwrap();
4307
    assert!(repo.resolve_heads("feature").is_err());
4308
    assert!(repo.bookmark_set("feature", &[h_a]).is_err());
4309
    assert!(
4310
        repo.checkout(&[h_a], false, "checkout").is_ok(),
4311
        "changes of a deleted bookmark remain"
4312
    );
4313
}
4314
4315
#[test]
4316
fn oxygen_subrepos_pin_follow_and_update() {
4317
    hermetic();
4318
    let dir = tempfile::tempdir().unwrap();
4319
    let root = dir.path();
4320
    // A library repository with two commits, and a bare-ish origin for it.
4321
    let lib_origin = Repo::init(&root.join("lib-origin")).unwrap();
4322
    let lib_url = root.join("lib-origin").to_string_lossy().to_string();
4323
    let lib = Repo::clone(&lib_url, &root.join("lib"))
4324
        .unwrap()
4325
        .with_home(root.join("home"));
4326
    write(&root.join("lib"), "lib.txt", b"v1\n");
4327
    let l1 = lib.commit("lib v1", &[]).unwrap();
4328
    assert!(lib.push("origin", false).unwrap()[0].ok);
4329
    let _ = lib_origin;
4330
4331
    // The application (a clone of its own origin) adds it as a subrepo.
4332
    let app_origin = Repo::init(&root.join("app-origin")).unwrap();
4333
    let app_url = root.join("app-origin").to_string_lossy().to_string();
4334
    let _ = app_origin;
4335
    let app_dir = root.join("app");
4336
    let app = Repo::clone(&app_url, &app_dir)
4337
        .unwrap()
4338
        .with_home(root.join("home"));
4339
    write(&app_dir, "main.txt", b"app\n");
4340
    let pin = app.submodule_add(&lib_url, "libs/lib", None).unwrap();
4341
    assert!(matches!(&pin, crate::subrepo::Pin::Oxy { heads, .. } if heads == &vec![l1]));
4342
    assert!(app_dir.join(".oxymodules").exists() && app_dir.join("libs/lib/.oxy").is_dir());
4343
    let snap = app.snapshot("status").unwrap();
4344
    let paths: Vec<&str> = snap.statuses.iter().map(|s| s.path.as_str()).collect();
4345
    assert_eq!(
4346
        paths,
4347
        vec![".oxymodules", "libs/lib", "main.txt"],
4348
        "the nested files are not walked"
4349
    );
4350
    let a1 = app.commit("app with lib", &[]).unwrap();
4351
    let files = app.load_state(&[a1]).unwrap().materialize().files;
4352
    assert_eq!(files["libs/lib"].kind, NodeKind::Subrepo);
4353
    assert!(!files.contains_key("libs/lib/lib.txt"));
4354
    assert!(!app.snapshot("status").unwrap().changed);
4355
    let subs = app.subrepos().unwrap();
4356
    assert_eq!(subs.len(), 1);
4357
    assert_eq!(subs[0].actual.as_ref(), Some(&subs[0].pin));
4358
4359
    // Advance the nested repository: the parent sees a modified pin.
4360
    let nested = Repo::open(&app_dir.join("libs/lib"))
4361
        .unwrap()
4362
        .with_home(root.join("home"));
4363
    write(&app_dir.join("libs/lib"), "lib.txt", b"v2\n");
4364
    let l2 = nested.commit("lib v2", &[]).unwrap();
4365
    assert!(nested.push("origin", false).unwrap()[0].ok);
4366
    let snap = app.snapshot("status").unwrap();
4367
    assert_eq!(
4368
        snap.statuses
4369
            .iter()
4370
            .map(|s| (s.path.as_str(), s.status))
4371
            .collect::<Vec<_>>(),
4372
        vec![("libs/lib", ChangeStatus::Modified)]
4373
    );
4374
    let a2 = app.commit("bump lib", &[]).unwrap();
4375
    // Checking out the older app state brings the nested working copy back
4376
    // to the older pin, but never moves its bookmark backwards (oxygen#38).
4377
    let r = app.checkout(&[a1], false, "checkout").unwrap();
4378
    assert!(
4379
        r.notes.len() == 1 && r.notes[0].contains("keeps 1 newer change"),
4380
        "{:?}",
4381
        r.notes
4382
    );
4383
    assert_eq!(fs::read(app_dir.join("libs/lib/lib.txt")).unwrap(), b"v1\n");
4384
    let nested = Repo::open(&app_dir.join("libs/lib")).unwrap();
4385
    assert_eq!(nested.bookmark_heads().unwrap(), vec![l2]);
4386
    assert_eq!(nested.working_copy().unwrap().1.deps, vec![l1]);
4387
    assert!(!app.snapshot("status").unwrap().changed);
4388
    // A dirty nested repository is left alone and reported.
4389
    write(&app_dir.join("libs/lib"), "scratch.txt", b"wip\n");
4390
    let r = app.checkout(&[a2], false, "checkout").unwrap();
4391
    assert!(
4392
        r.notes.iter().any(|n| n.contains("uncommitted")),
4393
        "{:?}",
4394
        r.notes
4395
    );
4396
    assert_eq!(fs::read(app_dir.join("libs/lib/lib.txt")).unwrap(), b"v1\n");
4397
    fs::remove_file(app_dir.join("libs/lib/scratch.txt")).unwrap();
4398
    let r = app.submodule_update(false, &[]).unwrap();
4399
    assert_eq!(r, vec![("libs/lib".to_string(), SubrepoSync::Updated)]);
4400
    assert_eq!(fs::read(app_dir.join("libs/lib/lib.txt")).unwrap(), b"v2\n");
4401
    let _ = l2;
4402
4403
    // A fresh clone of the app has the pin but no nested repository until update --init.
4404
    assert!(app.push("origin", false).unwrap()[0].ok);
4405
    let clone_dir = root.join("app-clone");
4406
    let clone = Repo::clone(&app_url, &clone_dir)
4407
        .unwrap()
4408
        .with_home(root.join("home"));
4409
    assert!(!clone_dir.join("libs/lib/.oxy").exists());
4410
    assert_eq!(
4411
        clone.submodule_update(false, &[]).unwrap(),
4412
        vec![("libs/lib".to_string(), SubrepoSync::Missing)]
4413
    );
4414
    assert_eq!(
4415
        clone.submodule_update(true, &[]).unwrap(),
4416
        vec![("libs/lib".to_string(), SubrepoSync::Updated)]
4417
    );
4418
    assert_eq!(
4419
        fs::read(clone_dir.join("libs/lib/lib.txt")).unwrap(),
4420
        b"v2\n"
4421
    );
4422
    assert!(!clone.snapshot("status").unwrap().changed);
4423
    // Removing the subrepo leaves the directory and drops the node.
4424
    clone.submodule_remove("libs/lib").unwrap();
4425
    let snap = clone.snapshot("status").unwrap();
4426
    assert!(
4427
        snap.statuses
4428
            .iter()
4429
            .any(|s| s.path == "libs/lib" && s.status == ChangeStatus::Removed),
4430
        "{:?}",
4431
        snap.statuses
4432
    );
4433
    let c = clone.commit("drop lib", &[]).unwrap();
4434
    assert!(!clone
4435
        .load_state(&[c])
4436
        .unwrap()
4437
        .materialize()
4438
        .files
4439
        .contains_key("libs/lib"));
4440
    assert!(clone_dir.join("libs/lib/lib.txt").exists());
4441
    assert!(
4442
        !clone.snapshot("status").unwrap().changed,
4443
        "an unregistered nested repository is ignored"
4444
    );
4445
}
4446
4447
#[test]
4448
fn git_submodules_import_and_export_as_gitlinks() {
4449
    hermetic();
4450
    if std::process::Command::new("git")
4451
        .arg("--version")
4452
        .output()
4453
        .is_err()
4454
    {
4455
        eprintln!("git not installed; skipping");
4456
        return;
4457
    }
4458
    let dir = tempfile::tempdir().unwrap();
4459
    let root = dir.path();
4460
    let git_in = |d: &Path, args: &[&str]| -> String {
4461
        let out = std::process::Command::new("git")
4462
            .arg("-C")
4463
            .arg(d)
4464
            .args([
4465
                "-c",
4466
                "user.name=Grace",
4467
                "-c",
4468
                "[email protected]",
4469
                "-c",
4470
                "commit.gpgsign=false",
4471
                "-c",
4472
                "protocol.file.allow=always",
4473
            ])
4474
            .args(args)
4475
            .output()
4476
            .unwrap();
4477
        assert!(
4478
            out.status.success(),
4479
            "git {args:?}: {}",
4480
            String::from_utf8_lossy(&out.stderr)
4481
        );
4482
        String::from_utf8_lossy(&out.stdout).trim().to_string()
4483
    };
4484
    let sub = root.join("sub");
4485
    fs::create_dir_all(&sub).unwrap();
4486
    git_in(&sub, &["init", "-q", "-b", "main"]);
4487
    write(&sub, "s.txt", b"sub\n");
4488
    git_in(&sub, &["add", "."]);
4489
    git_in(&sub, &["commit", "-q", "-m", "sub initial"]);
4490
    let sub_sha = git_in(&sub, &["rev-parse", "HEAD"]);
4491
    let g = root.join("main.git");
4492
    fs::create_dir_all(&g).unwrap();
4493
    git_in(&g, &["init", "-q", "-b", "main"]);
4494
    write(&g, "README.md", b"# app\n");
4495
    git_in(&g, &["add", "."]);
4496
    git_in(&g, &["commit", "-q", "-m", "initial"]);
4497
    git_in(
4498
        &g,
4499
        &[
4500
            "submodule",
4501
            "add",
4502
            "-q",
4503
            sub.to_str().unwrap(),
4504
            "vendor/sub",
4505
        ],
4506
    );
4507
    git_in(&g, &["commit", "-q", "-m", "add submodule"]);
4508
4509
    let dest = root.join("oxy");
4510
    let repo = Repo::init(&dest).unwrap().with_home(root.join("home"));
4511
    let rep = repo.import_git(&g, "main").unwrap();
4512
    assert_eq!((rep.commits, rep.submodules), (2, 1));
4513
    let files = repo
4514
        .load_state(&repo.bookmark_heads().unwrap())
4515
        .unwrap()
4516
        .materialize()
4517
        .files;
4518
    assert_eq!(files["vendor/sub"].kind, NodeKind::Subrepo);
4519
    let FileContent::Opaque { blobs } = &files["vendor/sub"].content else {
4520
        panic!()
4521
    };
4522
    assert_eq!(
4523
        crate::subrepo::Pin::decode(&repo.read_blob(&blobs[0]).unwrap()).unwrap(),
4524
        crate::subrepo::Pin::Git {
4525
            sha: sub_sha.clone(),
4526
            branch: "HEAD".into()
4527
        }
4528
    );
4529
    let modules =
4530
        crate::subrepo::Modules::parse(&fs::read_to_string(dest.join(".oxymodules")).unwrap());
4531
    assert_eq!(modules.entries["vendor/sub"].url, sub.to_string_lossy());
4532
    assert!(modules.entries["vendor/sub"].git);
4533
    assert!(
4534
        files.contains_key(".gitmodules"),
4535
        "the Git file is kept for round trips"
4536
    );
4537
    assert!(
4538
        !dest.join("vendor/sub/.git").exists(),
4539
        "not cloned until update --init"
4540
    );
4541
    assert!(!repo.snapshot("status").unwrap().changed);
4542
    // update --init clones it at the pinned commit; status is unchanged.
4543
    assert_eq!(
4544
        repo.submodule_update(true, &[]).unwrap(),
4545
        vec![("vendor/sub".to_string(), SubrepoSync::Updated)]
4546
    );
4547
    assert_eq!(
4548
        git_in(&dest.join("vendor/sub"), &["rev-parse", "HEAD"]),
4549
        sub_sha
4550
    );
4551
    assert!(!repo.snapshot("status").unwrap().changed);
4552
    // Export writes the gitlink and .gitmodules back.
4553
    let mirror = root.join("mirror.git");
4554
    let rep = repo.git_export(&mirror).unwrap();
4555
    assert_eq!(rep.skipped_subrepos, 0);
4556
    let ls = git_in(&mirror, &["ls-tree", "main", "vendor/sub"]);
4557
    assert!(
4558
        ls.starts_with("160000 commit ") && ls.contains(&sub_sha),
4559
        "{ls}"
4560
    );
4561
    assert_eq!(
4562
        git_in(&mirror, &["ls-tree", "--name-only", "main"]),
4563
        ".gitmodules\nREADME.md\nvendor"
4564
    );
4565
    let orig_tree = git_in(&g, &["rev-parse", "main^{tree}"]);
4566
    assert_eq!(
4567
        git_in(&mirror, &["rev-parse", "main^{tree}"]),
4568
        orig_tree,
4569
        "tree round trip"
4570
    );
4571
}
4572
4573
#[test]
4574
fn partial_commits_by_path_and_by_hunk() {
4575
    hermetic();
4576
    let dir = tempfile::tempdir().unwrap();
4577
    let root = dir.path();
4578
    let repo = Repo::init(root).unwrap().with_home(root.join("home"));
4579
    write(root, "a.txt", b"1\n2\n3\n");
4580
    write(root, "b.txt", b"b\n");
4581
    let h0 = repo.commit("base", &[]).unwrap();
4582
    write(root, "a.txt", b"0\n1\n2\n3\n4\n");
4583
    write(root, "b.txt", b"b\nbb\n");
4584
    write(root, "c.txt", b"c\n");
4585
    // By path: only a.txt goes in; the rest stays on disk as uncommitted work.
4586
    let h1 = repo
4587
        .commit_selection("a only", &[], &Selection::Paths(vec!["a.txt".into()]))
4588
        .unwrap();
4589
    let c1 = repo.store().get_change(&h1).unwrap();
4590
    assert!(
4591
        c1.tree_ops.is_empty() && c1.edits.iter().all(|e| e.node() == c1.edits[0].node()),
4592
        "{:?}",
4593
        c1.tree_ops
4594
    );
4595
    assert_eq!(c1.deps, vec![h0]);
4596
    let files = repo.load_state(&[h1]).unwrap().materialize().files;
4597
    assert!(
4598
        matches!(&files["a.txt"].content, FileContent::Text { bytes, .. } if bytes == b"0\n1\n2\n3\n4\n")
4599
    );
4600
    assert!(matches!(&files["b.txt"].content, FileContent::Text { bytes, .. } if bytes == b"b\n"));
4601
    assert!(!files.contains_key("c.txt"));
4602
    let snap = repo.snapshot("status").unwrap();
4603
    assert_eq!(
4604
        snap.statuses
4605
            .iter()
4606
            .map(|s| (s.path.as_str(), s.status))
4607
            .collect::<Vec<_>>(),
4608
        vec![
4609
            ("b.txt", ChangeStatus::Modified),
4610
            ("c.txt", ChangeStatus::Added)
4611
        ]
4612
    );
4613
    assert_eq!(
4614
        fs::read(root.join("b.txt")).unwrap(),
4615
        b"b\nbb\n",
4616
        "disk untouched"
4617
    );
4618
    // By hunk: pick the b.txt insert; c.txt's addition is left.
4619
    let (_, hunks) = repo.hunks().unwrap();
4620
    let b_hunk = hunks
4621
        .iter()
4622
        .find(|h| h.path == "b.txt" && h.text.contains("+bb"))
4623
        .unwrap()
4624
        .index;
4625
    let h2 = repo
4626
        .commit_selection("b only", &[], &Selection::Hunks(vec![b_hunk]))
4627
        .unwrap();
4628
    let files = repo.load_state(&[h2]).unwrap().materialize().files;
4629
    assert!(
4630
        matches!(&files["b.txt"].content, FileContent::Text { bytes, .. } if bytes == b"b\nbb\n")
4631
    );
4632
    assert!(!files.contains_key("c.txt"));
4633
    let snap = repo.snapshot("status").unwrap();
4634
    assert_eq!(
4635
        snap.statuses
4636
            .iter()
4637
            .map(|s| s.path.as_str())
4638
            .collect::<Vec<_>>(),
4639
        vec!["c.txt"]
4640
    );
4641
    // Choosing only the content hunk of a file in a new directory pulls in
4642
    // the directory and file additions it needs.
4643
    write(root, "d/e.txt", b"e\n");
4644
    let (_, hunks) = repo.hunks().unwrap();
4645
    let e_insert = hunks
4646
        .iter()
4647
        .find(|h| h.path == "d/e.txt" && h.text.contains("+e"))
4648
        .unwrap()
4649
        .index;
4650
    let h3 = repo
4651
        .commit_selection("e only", &[], &Selection::Hunks(vec![e_insert]))
4652
        .unwrap();
4653
    let c3 = repo.store().get_change(&h3).unwrap();
4654
    assert_eq!(c3.tree_ops.len(), 2, "{:?}", c3.tree_ops);
4655
    let files = repo.load_state(&[h3]).unwrap().materialize().files;
4656
    assert!(files.contains_key("d/e.txt") && !files.contains_key("c.txt"));
4657
    // Choosing a new file's addition hunk brings its content along.
4658
    write(root, "f/g.txt", b"g\n");
4659
    let (_, hunks) = repo.hunks().unwrap();
4660
    let g_add = hunks
4661
        .iter()
4662
        .find(|h| h.path == "f/g.txt" && h.text.starts_with("A "))
4663
        .unwrap()
4664
        .index;
4665
    let h4 = repo
4666
        .commit_selection("g by addition", &[], &Selection::Hunks(vec![g_add]))
4667
        .unwrap();
4668
    let files = repo.load_state(&[h4]).unwrap().materialize().files;
4669
    assert!(
4670
        matches!(&files["f/g.txt"].content, FileContent::Text { bytes, .. } if bytes == b"g\n")
4671
    );
4672
    assert!(!repo
4673
        .snapshot("status")
4674
        .unwrap()
4675
        .statuses
4676
        .iter()
4677
        .any(|s| s.path == "f/g.txt"));
4678
    // Everything left commits normally; the working copy is then clean.
4679
    repo.commit("the rest", &[]).unwrap();
4680
    assert!(!repo.snapshot("status").unwrap().changed);
4681
    let files = repo
4682
        .load_state(&repo.bookmark_heads().unwrap())
4683
        .unwrap()
4684
        .materialize()
4685
        .files;
4686
    assert!(files.contains_key("c.txt"));
4687
}
4688
4689
#[test]
4690
fn blame_attributes_lines_to_introducing_changes_across_renames() {
4691
    hermetic();
4692
    let dir = tempfile::tempdir().unwrap();
4693
    let root = dir.path();
4694
    let mut repo = Repo::init(root).unwrap().with_home(root.join("home"));
4695
    repo.create_identity("Ada", "[email protected]", IdentityScope::User)
4696
        .unwrap();
4697
    write(root, "a.txt", b"one\n");
4698
    let h1 = repo.commit("first", &[]).unwrap();
4699
    write(root, "a.txt", b"one\ntwo\n");
4700
    let h2 = repo.commit("second", &[]).unwrap();
4701
    let b = repo.blame("a.txt").unwrap();
4702
    assert_eq!(
4703
        b.iter()
4704
            .map(|l| (l.line, l.hash, l.text.as_slice()))
4705
            .collect::<Vec<_>>(),
4706
        vec![(1, h1, b"one\n".as_slice()), (2, h2, b"two\n".as_slice())]
4707
    );
4708
    assert!(b.iter().all(|l| l.author == "Ada"));
4709
    assert_eq!(
4710
        b[0].change_id,
4711
        repo.store().get_change(&h1).unwrap().change_id
4712
    );
4713
    fs::rename(root.join("a.txt"), root.join("b.txt")).unwrap();
4714
    repo.commit("rename", &[]).unwrap();
4715
    let b = repo.blame("b.txt").unwrap();
4716
    assert_eq!(
4717
        b.iter().map(|l| l.hash).collect::<Vec<_>>(),
4718
        vec![h1, h2],
4719
        "the node survives the rename"
4720
    );
4721
    assert!(repo.blame("a.txt").is_err());
4722
}
4723
4724
#[test]
4725
fn bisect_finds_the_first_bad_change() {
4726
    hermetic();
4727
    let dir = tempfile::tempdir().unwrap();
4728
    let root = dir.path();
4729
    let repo = Repo::init(root).unwrap().with_home(root.join("home"));
4730
    let mut content = String::new();
4731
    let mut hashes = Vec::new();
4732
    for i in 1..=8 {
4733
        content.push_str(&format!("line {i}{}\n", if i == 5 { " bug" } else { "" }));
4734
        write(root, "f.txt", content.as_bytes());
4735
        hashes.push(repo.commit(&format!("step {i}"), &[]).unwrap());
4736
    }
4737
    // Each step appends after the previous line, so the chain is linear.
4738
    assert_eq!(repo.bookmark_heads().unwrap(), vec![hashes[7]]);
4739
    repo.bisect_start().unwrap();
4740
    assert!(matches!(
4741
        repo.bisect_mark(Some(true), &[hashes[0]]).unwrap(),
4742
        BisectStep::NeedMarks { good: 1, bad: 0 }
4743
    ));
4744
    let step = repo.bisect_mark(Some(false), &[hashes[7]]).unwrap();
4745
    assert!(
4746
        matches!(step, BisectStep::Testing { remaining: 7, .. }),
4747
        "{step:?}"
4748
    );
4749
    // Automated: bad when the bug line is present.
4750
    let step = repo
4751
        .bisect_run(&["sh".into(), "-c".into(), "! grep -q bug f.txt".into()])
4752
        .unwrap();
4753
    assert_eq!(step, BisectStep::Found { culprit: hashes[4] });
4754
    assert_eq!(
4755
        repo.bisect_status().unwrap(),
4756
        Some(BisectStep::Found { culprit: hashes[4] })
4757
    );
4758
    repo.bisect_reset().unwrap();
4759
    assert_eq!(fs::read_to_string(root.join("f.txt")).unwrap(), content);
4760
    assert!(repo.bisect_status().unwrap().is_none());
4761
    assert!(!repo.snapshot("status").unwrap().changed);
4762
    // Manual marks and a skip.
4763
    repo.bisect_start().unwrap();
4764
    repo.bisect_mark(Some(true), &[hashes[0]]).unwrap();
4765
    let mut step = repo.bisect_mark(Some(false), &[hashes[7]]).unwrap();
4766
    let mut skipped_once = false;
4767
    let mut guard = 0;
4768
    while let BisectStep::Testing { .. } = step {
4769
        guard += 1;
4770
        assert!(guard < 20);
4771
        let text = fs::read_to_string(root.join("f.txt")).unwrap();
4772
        if !skipped_once && text.contains("line 6") {
4773
            // An untestable state away from the boundary: the search routes around it.
4774
            skipped_once = true;
4775
            step = repo.bisect_mark(None, &[]).unwrap();
4776
            continue;
4777
        }
4778
        step = repo.bisect_mark(Some(!text.contains("bug")), &[]).unwrap();
4779
    }
4780
    assert!(skipped_once);
4781
    assert_eq!(step, BisectStep::Found { culprit: hashes[4] });
4782
    repo.bisect_reset().unwrap();
4783
    // Skipping the culprit itself leaves it among the candidates reported.
4784
    repo.bisect_start().unwrap();
4785
    repo.bisect_mark(Some(true), &[hashes[0]]).unwrap();
4786
    let mut step = repo.bisect_mark(Some(false), &[hashes[7]]).unwrap();
4787
    let mut guard = 0;
4788
    while let BisectStep::Testing { heads, .. } = &step {
4789
        guard += 1;
4790
        assert!(guard < 20);
4791
        let text = fs::read_to_string(root.join("f.txt")).unwrap();
4792
        let is_culprit_state =
4793
            heads.contains(&hashes[4]) && !heads.iter().any(|h| hashes[5..].contains(h));
4794
        step = if is_culprit_state {
4795
            repo.bisect_mark(None, &[]).unwrap()
4796
        } else {
4797
            repo.bisect_mark(Some(!text.contains("bug")), &[]).unwrap()
4798
        };
4799
    }
4800
    match step {
4801
        BisectStep::Inconclusive { candidates } => assert!(
4802
            candidates.contains(&hashes[4]) && candidates.len() <= 2,
4803
            "{candidates:?}"
4804
        ),
4805
        other => panic!("{other:?}"),
4806
    }
4807
    repo.bisect_reset().unwrap();
4808
}
4809
4810
#[test]
4811
fn squash_folds_a_change_into_its_dependency() {
4812
    hermetic();
4813
    let dir = tempfile::tempdir().unwrap();
4814
    let root = dir.path();
4815
    let repo = Repo::init(root).unwrap().with_home(root.join("home"));
4816
    write(root, "a.txt", b"1\n");
4817
    let a = repo.commit("A", &[]).unwrap();
4818
    write(root, "a.txt", b"1\n2\n");
4819
    let c = repo.commit("C", &[]).unwrap();
4820
    write(root, "a.txt", b"1\n2\n3\n");
4821
    let e = repo.commit("E", &[]).unwrap();
4822
    write(root, "b.txt", b"b\n");
4823
    let b = repo.commit("B", &[]).unwrap();
4824
    let id_a = repo.store().get_change(&a).unwrap().change_id;
4825
    let id_e = repo.store().get_change(&e).unwrap().change_id;
4826
    // E depends on C which A lacks: refused, naming it.
4827
    let err = repo.squash(&e, &a).unwrap_err().to_string();
4828
    assert!(err.contains(&c.short(12)), "{err}");
4829
    // C into A: A' has both, C is gone, E follows and still reads the same.
4830
    let a2 = repo.squash(&c, &a).unwrap();
4831
    let a2c = repo.store().get_change(&a2).unwrap();
4832
    assert_eq!(a2c.change_id, id_a);
4833
    assert!(a2c.deps.is_empty());
4834
    let heads = repo.bookmark_heads().unwrap();
4835
    let st = repo.load_state(&heads).unwrap();
4836
    assert!(!st.contains(&c) && !st.contains(&a) && !st.contains(&e));
4837
    let e2 = st
4838
        .changes()
4839
        .find(|(_, m)| m.change_id == id_e)
4840
        .map(|(h, _)| *h)
4841
        .unwrap();
4842
    assert_eq!(
4843
        repo.store().get_change(&e2).unwrap().deps,
4844
        vec![a2],
4845
        "E now depends on A' alone"
4846
    );
4847
    let files = st.materialize().files;
4848
    assert!(
4849
        matches!(&files["a.txt"].content, FileContent::Text { bytes, .. } if bytes == b"1\n2\n3\n")
4850
    );
4851
    assert!(files.contains_key("b.txt"));
4852
    assert!(st.contains(&b));
4853
    assert!(!repo.snapshot("status").unwrap().changed);
4854
    assert_eq!(repo.log().unwrap().len(), 4, "working copy, B, E', A'");
4855
    // Undo restores the three original changes.
4856
    repo.undo().unwrap();
4857
    repo.undo().unwrap();
4858
    let st = repo.load_state(&repo.bookmark_heads().unwrap()).unwrap();
4859
    assert!(st.contains(&c) && st.contains(&a) && st.contains(&e));
4860
}
4861
4862
#[test]
4863
fn rebase_re_expresses_a_change_against_another_base() {
4864
    hermetic();
4865
    let dir = tempfile::tempdir().unwrap();
4866
    let root = dir.path();
4867
    let repo = Repo::init(root).unwrap().with_home(root.join("home"));
4868
    write(root, "a.txt", b"1\n2\n");
4869
    let a = repo.commit("A", &[]).unwrap();
4870
    write(root, "a.txt", b"1\n2\n3\n");
4871
    let c = repo.commit("C: append 3", &[]).unwrap();
4872
    write(root, "a.txt", b"1\n2\n3\n4\n");
4873
    let e = repo.commit("E: append 4", &[]).unwrap();
4874
    // A different base: A plus a change that prepends a line.
4875
    repo.checkout(&[a], true, "checkout").unwrap();
4876
    write(root, "a.txt", b"0\n1\n2\n");
4877
    let d = repo.commit("D: prepend 0", &[]).unwrap();
4878
    let id_c = repo.store().get_change(&c).unwrap().change_id;
4879
    let id_e = repo.store().get_change(&e).unwrap().change_id;
4880
    // Rebase C onto D: its effect (append 3) re-derived against D's text.
4881
    let c2 = repo.rebase(&c, &[d]).unwrap();
4882
    let c2c = repo.store().get_change(&c2).unwrap();
4883
    assert_eq!(c2c.change_id, id_c);
4884
    assert!(c2c.deps.contains(&d), "{:?}", c2c.deps);
4885
    let heads = repo.bookmark_heads().unwrap();
4886
    let st = repo.load_state(&heads).unwrap();
4887
    assert!(!st.contains(&c) && st.contains(&d));
4888
    let e2 = st
4889
        .changes()
4890
        .find(|(_, m)| m.change_id == id_e)
4891
        .map(|(h, _)| *h)
4892
        .unwrap();
4893
    let e2deps = repo.store().get_change(&e2).unwrap().deps;
4894
    assert!(
4895
        e2deps.contains(&c2) && !e2deps.contains(&c) && e2deps.contains(&a),
4896
        "E follows C by content and still depends on A, which introduced the file: {e2deps:?}"
4897
    );
4898
    let files = st.materialize().files;
4899
    assert!(
4900
        matches!(&files["a.txt"].content, FileContent::Text { bytes, .. } if bytes == b"0\n1\n2\n3\n4\n"),
4901
        "{:?}",
4902
        files["a.txt"].content
4903
    );
4904
    assert!(!files["a.txt"].is_conflicted());
4905
    // Rebasing onto a state that already contains the change is refused.
4906
    assert!(repo.rebase(&c2, &[c2]).is_err());
4907
    let err = repo.rebase(&e2, &[d]).unwrap_err().to_string();
4908
    assert!(
4909
        err.contains("lacks dependencies"),
4910
        "E needs C, which D's state does not have: {err}"
4911
    );
4912
}
4913
4914
#[test]
4915
fn unsigned_tags_keep_their_message() {
4916
    hermetic();
4917
    let dir = tempfile::tempdir().unwrap();
4918
    let root = dir.path();
4919
    let repo = Repo::init(root).unwrap().with_home(root.join("home"));
4920
    write(root, "a.txt", b"a\n");
4921
    repo.commit("a", &[]).unwrap();
4922
    assert!(repo.secret_key().unwrap().is_none());
4923
    repo.tag_create("v1", &repo.bookmark_heads().unwrap(), "first release")
4924
        .unwrap();
4925
    let tags = repo.tags().unwrap();
4926
    assert_eq!(
4927
        (
4928
            tags[0].name.as_str(),
4929
            tags[0].message.as_str(),
4930
            tags[0].signer.as_deref()
4931
        ),
4932
        ("v1", "first release", None)
4933
    );
4934
    assert!(
4935
        repo.tag_refs().unwrap()[0].attestation.is_none(),
4936
        "an unsigned attestation is not advertised"
4937
    );
4938
}
4939
4940
#[test]
4941
fn fsck_passes_a_sound_repository_and_names_each_fault() {
4942
    // Files on disk are what this tests: tampering with them, and the
4943
    // directory store's crash points.
4944
    if std::env::var_os("OXY_STORE_BACKEND").is_some() {
4945
        return;
4946
    }
4947
    hermetic();
4948
    let dir = tempfile::tempdir().unwrap();
4949
    let root = dir.path();
4950
    let origin_path = root.join("origin");
4951
    let origin = Repo::init(&origin_path).unwrap();
4952
    let mut a = Repo::clone(&origin_path.to_string_lossy(), &root.join("a"))
4953
        .unwrap()
4954
        .with_home(root.join("home-a"));
4955
    a.create_identity("Ada", "[email protected]", IdentityScope::Repo)
4956
        .unwrap();
4957
    write(&root.join("a"), "f.txt", b"one\n");
4958
    write(&root.join("a"), "bin.dat", b"\0\x01\x02binary");
4959
    let h1 = a.commit("first", &[]).unwrap();
4960
    write(&root.join("a"), "f.txt", b"one\ntwo\n");
4961
    let h2 = a.commit("second", &[]).unwrap();
4962
    a.tag_create("v1", &[h2], "first release").unwrap();
4963
    a.checkpoint().unwrap();
4964
    assert!(a.push("origin", false).unwrap()[0].ok);
4965
    origin.refresh().unwrap();
4966
4967
    // Sound: signed changes, a seal, a tag, a checkpoint, a ref attestation.
4968
    for repo in [&a, &origin] {
4969
        let rep = repo.fsck().unwrap();
4970
        assert_eq!(rep.problems, vec![], "{rep:?}");
4971
        // The two commits, plus the working copy's change in `a`.
4972
        assert!(rep.changes >= 2 && rep.signed >= 2, "{rep:?}");
4973
        assert!(rep.ops > 1 && rep.objects > 5);
4974
    }
4975
    assert!(origin.fsck().unwrap().attestations >= 1);
4976
4977
    // A flipped byte in a stored object is corruption, named by hash.
4978
    let c1 = a.store().path_for(&h1);
4979
    let pristine = fs::read(&c1).unwrap();
4980
    let mut bytes = pristine.clone();
4981
    *bytes.last_mut().unwrap() ^= 1;
4982
    fs::write(&c1, &bytes).unwrap();
4983
    let rep = a.fsck().unwrap();
4984
    assert!(rep.errors() >= 1);
4985
    assert!(
4986
        rep.problems
4987
            .iter()
4988
            .any(|p| p.object == Some(h1) && p.what.contains("unreadable")),
4989
        "{rep:?}"
4990
    );
4991
    fs::write(&c1, &pristine).unwrap();
4992
    assert_eq!(a.fsck().unwrap().errors(), 0);
4993
4994
    // A missing change is named with what needed it.
4995
    fs::remove_file(&c1).unwrap();
4996
    let rep = a.fsck().unwrap();
4997
    assert!(
4998
        rep.problems.iter().any(|p| p.severity == Severity::Error
4999
            && p.object == Some(h1)
5000
            && p.what.contains("change missing, needed by change")),
5001
        "{rep:?}"
5002
    );
5003
    fs::write(&c1, &pristine).unwrap();
5004
5005
    // A missing blob is an error in a full clone.
5006
    let c2 = a.store().get_change(&h1).unwrap();
5007
    let blob = c2
5008
        .edits
5009
        .iter()
5010
        .find_map(|e| match e {
5011
            Edit::Replace { new: Some(b), .. } => Some(*b),
5012
            _ => None,
5013
        })
5014
        .expect("the binary file is a blob");
5015
    let bp = a.store().path_for(&blob);
5016
    let blob_bytes = fs::read(&bp).unwrap();
5017
    fs::remove_file(&bp).unwrap();
5018
    let rep = a.fsck().unwrap();
5019
    assert!(
5020
        rep.problems
5021
            .iter()
5022
            .any(|p| p.object == Some(blob) && p.what.contains("blob missing")),
5023
        "{rep:?}"
5024
    );
5025
    fs::write(&bp, &blob_bytes).unwrap();
5026
5027
    // A broken op log head is reported, not a crash.
5028
    let head = root.join("a/.oxy/ops/head");
5029
    let saved = fs::read(&head).unwrap();
5030
    fs::write(&head, b"not a hash").unwrap();
5031
    let rep = a.fsck().unwrap();
5032
    assert!(
5033
        rep.problems.iter().any(|p| p.what.contains("ops/head")),
5034
        "{rep:?}"
5035
    );
5036
    fs::write(&head, saved).unwrap();
5037
    assert_eq!(a.fsck().unwrap().problems, vec![]);
5038
}
5039
5040
/// Copy a directory tree (for restoring a pristine repository).
5041
fn copy_tree(from: &Path, to: &Path) {
5042
    fs::create_dir_all(to).unwrap();
5043
    for e in fs::read_dir(from).unwrap() {
5044
        let e = e.unwrap();
5045
        let target = to.join(e.file_name());
5046
        if e.file_type().unwrap().is_dir() {
5047
            copy_tree(&e.path(), &target);
5048
        } else {
5049
            fs::copy(e.path(), &target).unwrap();
5050
        }
5051
    }
5052
}
5053
5054
/// Spec §13.6: stop `commit` and `push` at every durable step, as a crash
5055
/// would, and check that both repositories still open, pass `fsck`, and
5056
/// accept the same operation again.
5057
#[test]
5058
fn crash_at_every_step_of_commit_and_push_leaves_sound_repositories() {
5059
    // Files on disk are what this tests: tampering with them, and the
5060
    // directory store's crash points.
5061
    if std::env::var_os("OXY_STORE_BACKEND").is_some() {
5062
        return;
5063
    }
5064
    use crate::durable::failpoint;
5065
    hermetic();
5066
    let dir = tempfile::tempdir().unwrap();
5067
    let pristine = dir.path().join("pristine");
5068
    let origin_path = pristine.join("origin");
5069
    Repo::init(&origin_path).unwrap();
5070
    let mut a = Repo::clone(&origin_path.to_string_lossy(), &pristine.join("a"))
5071
        .unwrap()
5072
        .with_home(dir.path().join("home"));
5073
    a.create_identity("Ada", "[email protected]", IdentityScope::Repo)
5074
        .unwrap();
5075
    write(&pristine.join("a"), "f.txt", b"one\n");
5076
    a.commit("first", &[]).unwrap();
5077
    assert!(a.push("origin", false).unwrap()[0].ok);
5078
    drop(a);
5079
5080
    type Op = fn(&Repo) -> Result<()>;
5081
    let edit_and_commit: Op = |r| {
5082
        write(r.root(), "f.txt", b"one\ntwo\n");
5083
        write(r.root(), "big.bin", &vec![7u8; 300_000]);
5084
        r.commit("second", &[]).map(|_| ())
5085
    };
5086
    let push: Op = |r| {
5087
        let res = r.push("origin", false)?;
5088
        if res.iter().all(|x| x.ok) {
5089
            Ok(())
5090
        } else {
5091
            Err(RepoError::Msg(format!("{res:?}")))
5092
        }
5093
    };
5094
5095
    for (name, prepare, op) in [
5096
        ("commit", None, edit_and_commit),
5097
        ("push", Some(edit_and_commit), push),
5098
    ] {
5099
        let mut steps = 0;
5100
        for n in 1.. {
5101
            let run = dir.path().join(format!("{name}-{n}"));
5102
            copy_tree(&pristine, &run);
5103
            // Clones record their remote by path; point it at this copy.
5104
            let open = |p: &Path| {
5105
                let mut r = Repo::open(p).unwrap().with_home(dir.path().join("home"));
5106
                r.config
5107
                    .set("remote.origin.url", &run.join("origin").to_string_lossy())
5108
                    .unwrap();
5109
                r.save_config().unwrap();
5110
                r
5111
            };
5112
            let a = open(&run.join("a"));
5113
            if let Some(prep) = prepare {
5114
                prep(&a).unwrap();
5115
            }
5116
            failpoint::crash_after(n);
5117
            let outcome = op(&a);
5118
            let crashed = failpoint::disarm();
5119
            drop(a);
5120
            if !crashed {
5121
                outcome.unwrap_or_else(|e| panic!("{name} failed without a crash: {e}"));
5122
                steps = n - 1;
5123
                break;
5124
            }
5125
            assert!(
5126
                outcome.is_err(),
5127
                "{name}: a crash at step {n} was swallowed"
5128
            );
5129
            for repo in ["a", "origin"] {
5130
                let r = Repo::open(&run.join(repo)).unwrap_or_else(|e| {
5131
                    panic!("{name} crash at step {n}: {repo} no longer opens: {e}")
5132
                });
5133
                let rep = r.fsck().unwrap();
5134
                assert_eq!(
5135
                    rep.errors(),
5136
                    0,
5137
                    "{name} crash at step {n}: {repo} fails fsck: {:?}",
5138
                    rep.problems
5139
                );
5140
            }
5141
            // The interrupted operation can simply be run again.
5142
            let a = open(&run.join("a"));
5143
            // A crash after the commit point leaves the commit done.
5144
            let landed = a
5145
                .bookmark_heads()
5146
                .unwrap()
5147
                .iter()
5148
                .any(|h| a.store().get_change(h).unwrap().message == "second");
5149
            let again = match (name, landed) {
5150
                ("commit", true) => Ok(()),
5151
                ("commit", false) => a.commit("second", &[]).map(|_| ()),
5152
                _ => op(&a),
5153
            };
5154
            again.unwrap_or_else(|e| panic!("{name} crash at step {n}: retry failed: {e}"));
5155
            assert_eq!(a.fsck().unwrap().errors(), 0);
5156
            fs::remove_dir_all(&run).unwrap();
5157
        }
5158
        assert!(steps >= 3, "{name} has only {steps} durable steps?");
5159
    }
5160
}
5161
5162
/// Spec §12.1: commands in two workspaces of one repository, and pushes,
5163
/// running at the same time lose nothing: every commit ends up on the
5164
/// bookmark, locally and on the remote, and the repository passes fsck.
5165
#[test]
5166
fn concurrent_commits_in_two_workspaces_lose_nothing() {
5167
    hermetic();
5168
    let dir = tempfile::tempdir().unwrap();
5169
    let root = dir.path();
5170
    let origin = root.join("origin");
5171
    Repo::init_bare_unbound(&origin).unwrap();
5172
    let main = root.join("main");
5173
    let mut repo = Repo::init(&main).unwrap();
5174
    repo.config
5175
        .set("remote.origin.url", &origin.to_string_lossy())
5176
        .unwrap();
5177
    repo.save_config().unwrap();
5178
    write(&main, "seed.txt", b"seed\n");
5179
    repo.commit("seed", &[]).unwrap();
5180
    let second = root.join("second");
5181
    repo.workspace_add(&second, None).unwrap();
5182
    drop(repo);
5183
5184
    const EACH: usize = 15;
5185
    std::thread::scope(|s| {
5186
        for (tag, dir, push) in [("a", main.clone(), true), ("b", second.clone(), false)] {
5187
            s.spawn(move || {
5188
                let r = Repo::open(&dir).unwrap();
5189
                for i in 0..EACH {
5190
                    write(
5191
                        &dir,
5192
                        &format!("{tag}-{i}.txt"),
5193
                        format!("{tag} {i}\n").as_bytes(),
5194
                    );
5195
                    r.commit(&format!("{tag} {i}"), &[]).unwrap();
5196
                    if push && i % 5 == 4 {
5197
                        // A push may be refused while the other workspace moves the bookmark; nothing may be lost either way.
5198
                        let _ = r.push("origin", false);
5199
                    }
5200
                }
5201
            });
5202
        }
5203
    });
5204
5205
    let repo = Repo::open(&main).unwrap();
5206
    let heads = repo.bookmark_heads().unwrap();
5207
    let state = repo.load_state(&heads).unwrap();
5208
    let messages: BTreeSet<String> = state.changes().map(|(_, m)| m.message.clone()).collect();
5209
    for tag in ["a", "b"] {
5210
        for i in 0..EACH {
5211
            assert!(
5212
                messages.contains(&format!("{tag} {i}")),
5213
                "lost commit {tag} {i}; have {messages:?}"
5214
            );
5215
        }
5216
    }
5217
    let rep = repo.fsck().unwrap();
5218
    assert_eq!(rep.errors(), 0, "{:?}", rep.problems);
5219
    assert!(repo.push("origin", false).unwrap().iter().all(|r| r.ok));
5220
    let hosted = Repo::open(&origin).unwrap();
5221
    let hosted_heads = hosted.bookmark_heads().unwrap();
5222
    assert_eq!(
5223
        hosted.load_state(&hosted_heads).unwrap().len(),
5224
        state.len(),
5225
        "the remote has every commit"
5226
    );
5227
}
5228
5229
/// Two operations recorded from the same parent (what two processes do
5230
/// when they race) are merged: both bookmarks' heads survive, and a
5231
/// change made on one side only is kept.
5232
#[test]
5233
fn operations_from_the_same_parent_are_merged() {
5234
    hermetic();
5235
    let dir = tempfile::tempdir().unwrap();
5236
    let root = dir.path();
5237
    let repo = Repo::init(root).unwrap();
5238
    write(root, "a.txt", b"a\n");
5239
    let a = repo.commit("a", &[]).unwrap();
5240
    write(root, "b.txt", b"b\n");
5241
    let b = repo.commit("b", &[]).unwrap();
5242
    let (x, op) = repo.head_op().unwrap();
5243
    let state = |heads: Vec<ChangeHash>| repo.store().put_state(&StateObject::new(heads)).unwrap();
5244
5245
    // Side one moves main to just `a` and adds a bookmark; side two moves main to just `b`.
5246
    let mut one = op.view.clone();
5247
    one.bookmarks.insert("main".into(), state(vec![a]));
5248
    one.bookmarks.insert("topic".into(), state(vec![a]));
5249
    let mut two = op.view.clone();
5250
    two.bookmarks.insert("main".into(), state(vec![b]));
5251
    repo.record_op(&[x], "one", one).unwrap();
5252
    let merged = repo.record_op(&[x], "two", two).unwrap();
5253
5254
    let (head, op) = repo.head_op().unwrap();
5255
    assert_eq!(head, merged);
5256
    assert_eq!(op.parents.len(), 2, "a merge of the two operations");
5257
    assert!(op.command.contains("merged with a concurrent operation"));
5258
    let mut main = repo
5259
        .store()
5260
        .get_state(&op.view.bookmarks["main"])
5261
        .unwrap()
5262
        .heads;
5263
    main.sort();
5264
    let mut want = vec![a, b];
5265
    want.sort();
5266
    assert_eq!(main, want, "both sides' heads are kept");
5267
    assert!(
5268
        op.view.bookmarks.contains_key("topic"),
5269
        "a one-sided change survives"
5270
    );
5271
    assert_eq!(repo.fsck().unwrap().errors(), 0);
5272
}
5273
5274
#[test]
5275
fn failed_requests_come_with_a_next_step() {
5276
    use crate::protocol::hint_for;
5277
    assert!(hint_for("https://h/x/oxy/v1/push: HTTP 401: bad token")
5278
        .unwrap()
5279
        .contains("token"));
5280
    assert!(hint_for("…: HTTP 403: forbidden")
5281
        .unwrap()
5282
        .contains("repo:write"));
5283
    assert!(hint_for("…: HTTP 404: no such repository")
5284
        .unwrap()
5285
        .contains("owner and repository name"));
5286
    assert!(hint_for("invalid peer certificate: UnknownIssuer")
5287
        .unwrap()
5288
        .contains("oxyhub-ca.pem"));
5289
    assert!(hint_for("Connect error: Connection refused (os error 111)")
5290
        .unwrap()
5291
        .contains("running"));
5292
    assert!(hint_for("Dns Failed: failed to lookup address information")
5293
        .unwrap()
5294
        .contains("resolve"));
5295
    assert_eq!(hint_for("something else entirely"), None);
5296
}
5297
5298
#[test]
5299
fn doctor_names_problems_and_what_to_do() {
5300
    hermetic();
5301
    let dir = tempfile::tempdir().unwrap();
5302
    let root = dir.path();
5303
    let origin = root.join("origin");
5304
    Repo::init_bare_unbound(&origin).unwrap();
5305
    let mut repo = Repo::init(&root.join("r"))
5306
        .unwrap()
5307
        .with_home(root.join("home"));
5308
    let find = |r: &DoctorReport, area: &str, h: Health| {
5309
        r.checks
5310
            .iter()
5311
            .find(|c| c.area == area && c.health == h)
5312
            .cloned()
5313
    };
5314
5315
    let r = repo.doctor(true);
5316
    assert!(find(&r, "identity", Health::Warn)
5317
        .unwrap()
5318
        .hint
5319
        .unwrap()
5320
        .contains("oxy identity create"));
5321
    assert!(find(&r, "repository", Health::Ok).is_some());
5322
5323
    repo.create_identity("Ada", "[email protected]", IdentityScope::Repo)
5324
        .unwrap();
5325
    repo.config.set("author.name", "Ada").unwrap();
5326
    repo.config.set("author.email", "[email protected]").unwrap();
5327
    repo.config
5328
        .set("remote.origin.url", &origin.to_string_lossy())
5329
        .unwrap();
5330
    repo.config
5331
        .set("remote.down.url", "http://127.0.0.1:9/a/b")
5332
        .unwrap();
5333
    repo.config.set("remote.down.token", "t").unwrap();
5334
    repo.config
5335
        .set("remote.badca.url", "https://example.invalid/a/b")
5336
        .unwrap();
5337
    repo.config
5338
        .set(
5339
            "remote.badca.ca",
5340
            &root.join("missing.pem").to_string_lossy(),
5341
        )
5342
        .unwrap();
5343
    repo.save_config().unwrap();
5344
5345
    let r = repo.doctor(true);
5346
    assert!(find(&r, "identity", Health::Ok).is_some(), "{r:?}");
5347
    assert!(find(&r, "author", Health::Ok).is_some(), "{r:?}");
5348
    assert!(find(&r, "remote origin", Health::Ok)
5349
        .unwrap()
5350
        .message
5351
        .contains("first push binds it"));
5352
    let down = find(&r, "remote down", Health::Fail).unwrap();
5353
    assert!(
5354
        down.hint.as_deref().unwrap_or("").contains("running"),
5355
        "{down:?}"
5356
    );
5357
    let badca = find(&r, "remote badca", Health::Fail).unwrap();
5358
    assert!(
5359
        badca.hint.unwrap().contains("remote.badca.ca"),
5360
        "the remote's own name is in the hint"
5361
    );
5362
    assert_eq!(r.worst(), Health::Fail);
5363
5364
    // Offline, nothing is contacted.
5365
    let r = repo.doctor(false);
5366
    assert!(find(&r, "remote down", Health::Fail).is_none());
5367
    assert!(find(&r, "remote down", Health::Ok)
5368
        .unwrap()
5369
        .message
5370
        .contains("not contacted"));
5371
}
5372
5373
/// Spec §8.1: deleting a line depends on whoever inserted the lines right
5374
/// after it. Inserting after `b` and then deleting `b`, one commit after
5375
/// the other, must not leave a delete/insert conflict.
5376
#[test]
5377
fn deleting_a_line_after_an_insertion_below_it_is_not_a_conflict() {
5378
    hermetic();
5379
    let dir = tempfile::tempdir().unwrap();
5380
    let root = dir.path();
5381
    let repo = Repo::init(root).unwrap();
5382
    write(root, "f", b"a\nb\nc\n");
5383
    repo.commit("base", &[]).unwrap();
5384
    write(root, "f", b"a\nb\nx\nc\n");
5385
    let insert = repo.commit("insert x after b", &[]).unwrap();
5386
    write(root, "f", b"a\nx\nc\n");
5387
    let delete = repo.commit("delete b", &[]).unwrap();
5388
    assert!(
5389
        repo.store()
5390
            .get_change(&delete)
5391
            .unwrap()
5392
            .deps
5393
            .contains(&insert),
5394
        "the deletion depends on the insertion below the deleted line"
5395
    );
5396
    let heads = repo.bookmark_heads().unwrap();
5397
    assert_eq!(heads, vec![delete]);
5398
    let snap = repo.load_state(&heads).unwrap().materialize();
5399
    assert!(!snap.is_conflicted());
5400
    assert!(
5401
        matches!(&snap.files["f"].content, FileContent::Text { bytes, .. } if bytes == b"a\nx\nc\n")
5402
    );
5403
}
5404
5405
/// Spec §9.3: a binary file reverted to an earlier blob keeps it, and each
5406
/// replacement depends on the change that set the blob it replaces.
5407
#[test]
5408
fn a_binary_file_reverted_to_an_earlier_blob_keeps_it() {
5409
    hermetic();
5410
    let dir = tempfile::tempdir().unwrap();
5411
    let root = dir.path();
5412
    let repo = Repo::init(root).unwrap();
5413
    write(root, "bin", b"\0A");
5414
    let v1 = repo.commit("v1", &[]).unwrap();
5415
    write(root, "bin", b"\0B");
5416
    let v2 = repo.commit("v2", &[]).unwrap();
5417
    assert!(repo.store().get_change(&v2).unwrap().deps.contains(&v1));
5418
    write(root, "bin", b"\0A");
5419
    let v3 = repo.commit("back to A", &[]).unwrap();
5420
    assert!(repo.store().get_change(&v3).unwrap().deps.contains(&v2));
5421
    assert_eq!(repo.bookmark_heads().unwrap(), vec![v3]);
5422
    let state = repo.load_state(&[v3]).unwrap();
5423
    let snap = state.materialize();
5424
    let FileContent::Opaque { blobs } = &snap.files["bin"].content else {
5425
        panic!("opaque")
5426
    };
5427
    assert_eq!(blobs.len(), 1, "one live blob, not none and not two");
5428
    assert_eq!(repo.read_blob(&blobs[0]).unwrap(), b"\0A");
5429
}
5430
5431
/// Spec §23: a binary file changed on two branches and merged in Git to
5432
/// one side's version comes back as that version at the merge, and the
5433
/// import verifies commit by commit.
5434
#[test]
5435
fn git_import_resolves_a_binary_merged_in_git_and_verifies() {
5436
    hermetic();
5437
    if std::process::Command::new("git")
5438
        .arg("--version")
5439
        .output()
5440
        .is_err()
5441
    {
5442
        eprintln!("git not installed; skipping");
5443
        return;
5444
    }
5445
    let dir = tempfile::tempdir().unwrap();
5446
    let root = dir.path();
5447
    let g = root.join("src.git");
5448
    fs::create_dir_all(&g).unwrap();
5449
    let git = |args: &[&str]| -> String {
5450
        let out = std::process::Command::new("git")
5451
            .arg("-C")
5452
            .arg(&g)
5453
            .args([
5454
                "-c",
5455
                "user.name=Grace",
5456
                "-c",
5457
                "[email protected]",
5458
                "-c",
5459
                "commit.gpgsign=false",
5460
            ])
5461
            .args(args)
5462
            .output()
5463
            .unwrap();
5464
        assert!(
5465
            out.status.success(),
5466
            "git {args:?}: {}",
5467
            String::from_utf8_lossy(&out.stderr)
5468
        );
5469
        String::from_utf8_lossy(&out.stdout).trim().to_string()
5470
    };
5471
    git(&["init", "-q", "-b", "main"]);
5472
    write(&g, "logo.bin", b"\0base");
5473
    write(&g, "notes.txt", b"a\nb\nc\n");
5474
    git(&["add", "."]);
5475
    git(&["commit", "-qm", "base"]);
5476
    git(&["checkout", "-qb", "side"]);
5477
    write(&g, "logo.bin", b"\0side");
5478
    write(&g, "notes.txt", b"a\nb\nx\nc\n");
5479
    git(&["commit", "-qam", "side"]);
5480
    git(&["checkout", "-q", "main"]);
5481
    write(&g, "logo.bin", b"\0main");
5482
    git(&["commit", "-qam", "main"]);
5483
    // Git cannot merge the binary; the merge takes main's and keeps side's text.
5484
    let _ = std::process::Command::new("git")
5485
        .arg("-C")
5486
        .arg(&g)
5487
        .args([
5488
            "-c",
5489
            "user.name=G",
5490
            "-c",
5491
            "user.email=g@e",
5492
            "merge",
5493
            "-q",
5494
            "side",
5495
        ])
5496
        .output();
5497
    write(&g, "logo.bin", b"\0main");
5498
    git(&["add", "."]);
5499
    git(&["commit", "-qm", "merge side"]);
5500
    // Then a revert of the binary to its first version.
5501
    write(&g, "logo.bin", b"\0base");
5502
    git(&["commit", "-qam", "back to base"]);
5503
5504
    let repo = Repo::init(&root.join("o")).unwrap();
5505
    let rep = repo.import_git(&g, "main").unwrap();
5506
    assert_eq!(rep.merges, 1);
5507
    let v = repo.verify_git_import(&g, "main").unwrap();
5508
    assert!(v.mismatches.is_empty(), "{:?}", v.mismatches);
5509
    assert_eq!(v.commits, 5);
5510
    let snap = repo
5511
        .load_state(&repo.bookmark_heads().unwrap())
5512
        .unwrap()
5513
        .materialize();
5514
    assert!(!snap.is_conflicted());
5515
    let FileContent::Opaque { blobs } = &snap.files["logo.bin"].content else {
5516
        panic!("opaque")
5517
    };
5518
    assert_eq!(repo.read_blob(&blobs[0]).unwrap(), b"\0base");
5519
}
5520
5521
/// Spec §7.7 on a file system without executable bits or symlinks: the
5522
/// recorded bit is kept, and a symlink checked out as a plain file holding
5523
/// its target is still that symlink.
5524
#[cfg(unix)]
5525
#[test]
5526
fn windows_file_systems_keep_exec_bits_and_symlinks() {
5527
    use crate::portable::Platform;
5528
    use std::os::unix::fs::PermissionsExt;
5529
    hermetic();
5530
    let dir = tempfile::tempdir().unwrap();
5531
    let root = dir.path();
5532
    let repo = Repo::init(root).unwrap();
5533
    write(root, "run.sh", b"#!/bin/sh\n");
5534
    fs::set_permissions(root.join("run.sh"), fs::Permissions::from_mode(0o755)).unwrap();
5535
    std::os::unix::fs::symlink("run.sh", root.join("link")).unwrap();
5536
    repo.commit("script and link", &[]).unwrap();
5537
    drop(repo);
5538
5539
    // What checking out on Windows leaves: no exec bit, the link as a file.
5540
    fs::set_permissions(root.join("run.sh"), fs::Permissions::from_mode(0o644)).unwrap();
5541
    fs::remove_file(root.join("link")).unwrap();
5542
    write(root, "link", b"run.sh");
5543
    let win = Repo::open(root).unwrap().with_platform(Platform::windows());
5544
    let s = win.snapshot("oxy status").unwrap();
5545
    assert!(
5546
        s.statuses.is_empty(),
5547
        "nothing changed on Windows: {:?}",
5548
        statuses(&s)
5549
    );
5550
    // Editing the file is a content change, not a mode change; retargeting the link keeps it a link.
5551
    write(root, "run.sh", b"#!/bin/sh\necho hi\n");
5552
    write(root, "link", b"other");
5553
    let h = win.commit("edit on Windows", &[]).unwrap();
5554
    let snap = win.load_state(&[h]).unwrap().materialize();
5555
    assert!(snap.files["run.sh"].mode.exec, "the exec bit survives");
5556
    assert_eq!(snap.files["link"].kind, NodeKind::Symlink);
5557
    // The same working copy read as Linux sees the lost bit and the plain file.
5558
    let linux = Repo::open(root).unwrap();
5559
    assert!(!linux.snapshot("oxy status").unwrap().statuses.is_empty());
5560
}
5561
5562
/// Paths that collide on case-insensitive or Windows file systems are
5563
/// named at checkout there, and by doctor everywhere.
5564
#[test]
5565
fn paths_other_platforms_cannot_hold_are_reported() {
5566
    use crate::portable::Platform;
5567
    hermetic();
5568
    let dir = tempfile::tempdir().unwrap();
5569
    let root = dir.path();
5570
    let repo = Repo::init(root).unwrap();
5571
    write(root, "README.md", b"a\n");
5572
    write(root, "readme.md", b"b\n");
5573
    write(root, "src/aux.c", b"int x;\n");
5574
    let h = repo.commit("unportable", &[]).unwrap();
5575
    let r = repo.doctor(false);
5576
    let port = r.checks.iter().find(|c| c.area == "portability").unwrap();
5577
    assert_eq!(port.health, Health::Warn);
5578
    assert!(
5579
        port.message.contains("differ only in case") && port.message.contains("aux.c"),
5580
        "{}",
5581
        port.message
5582
    );
5583
    let mac = Repo::open(root).unwrap().with_platform(Platform::macos());
5584
    let rep = mac.checkout(&[h], true, "oxy checkout").unwrap();
5585
    assert!(
5586
        rep.notes
5587
            .iter()
5588
            .any(|n| n.contains("README.md and readme.md")),
5589
        "{:?}",
5590
        rep.notes
5591
    );
5592
    assert!(
5593
        !rep.notes.iter().any(|n| n.contains("aux.c")),
5594
        "macOS allows aux.c"
5595
    );
5596
}
5597
5598
#[test]
5599
fn history_and_blame_of_a_loaded_state_match_the_full_walk() {
5600
    hermetic();
5601
    let dir = tempfile::tempdir().unwrap();
5602
    let repo = Repo::init(dir.path()).unwrap();
5603
    write(dir.path(), "a.txt", b"one\n");
5604
    write(dir.path(), "other.txt", b"x\n");
5605
    write(dir.path(), "bin.dat", &[0u8, 1, 2, 0, 255]);
5606
    repo.snapshot("t").unwrap();
5607
    let c1 = repo.commit("first", &[]).unwrap();
5608
    write(dir.path(), "other.txt", b"y\n");
5609
    repo.snapshot("t").unwrap();
5610
    repo.commit("other only", &[]).unwrap();
5611
    write(dir.path(), "a.txt", b"one\ntwo\n");
5612
    repo.snapshot("t").unwrap();
5613
    let c3 = repo.commit("second line", &[]).unwrap();
5614
    write(dir.path(), "other.txt", b"z\n");
5615
    repo.snapshot("t").unwrap();
5616
    repo.commit("other again", &[]).unwrap();
5617
5618
    let heads = repo.bookmark_heads().unwrap();
5619
    let state = repo.load_state(&heads).unwrap();
5620
    let full: Vec<ChangeHash> = repo
5621
        .log_for_path_in("a.txt", &heads)
5622
        .unwrap()
5623
        .iter()
5624
        .map(|e| e.hash)
5625
        .collect();
5626
    assert_eq!(
5627
        full,
5628
        vec![c3, c1],
5629
        "newest first, only changes touching the path"
5630
    );
5631
    let newest: Vec<ChangeHash> = repo
5632
        .log_for_path_of(&state, "a.txt", Some(1))
5633
        .unwrap()
5634
        .iter()
5635
        .map(|e| e.hash)
5636
        .collect();
5637
    assert_eq!(newest, vec![c3], "stops at the first");
5638
    assert_eq!(
5639
        repo.log_for_path_of(&state, "a.txt", None).unwrap().len(),
5640
        2
5641
    );
5642
    assert!(repo
5643
        .log_for_path_of(&state, "missing.txt", Some(1))
5644
        .is_err());
5645
    assert_eq!(
5646
        repo.log_state(&heads).unwrap().len(),
5647
        repo.log_of(&state).len()
5648
    );
5649
5650
    let tree = state.tree().view();
5651
    let via_state = repo.blame_of(&state, &tree, "a.txt").unwrap();
5652
    let via_heads = repo.blame_in("a.txt", &heads).unwrap();
5653
    assert_eq!(
5654
        via_state
5655
            .iter()
5656
            .map(|l| (l.hash, l.text.clone()))
5657
            .collect::<Vec<_>>(),
5658
        via_heads
5659
            .iter()
5660
            .map(|l| (l.hash, l.text.clone()))
5661
            .collect::<Vec<_>>()
5662
    );
5663
    assert_eq!(
5664
        via_state.iter().map(|l| l.hash).collect::<Vec<_>>(),
5665
        vec![c1, c3]
5666
    );
5667
    assert!(repo.blame_of(&state, &tree, "missing.txt").is_err());
5668
}
5669
5670
/// A text file whose stat matches the manifest and whose recorded hash is
5671
/// the base's content is taken from the base without reading it; anything
5672
/// else is read, so no edit is missed (spec §12.3).
5673
#[cfg(unix)]
5674
#[test]
5675
fn stat_cache_takes_unchanged_text_from_the_base_and_misses_no_edit() {
5676
    use std::os::unix::fs::PermissionsExt;
5677
    hermetic();
5678
    let dir = tempfile::tempdir().unwrap();
5679
    let root = dir.path();
5680
    let repo = Repo::init(root).unwrap().with_home(root.join("home"));
5681
    write(root, "a.txt", b"one\ntwo\n");
5682
    write(root, "b.txt", b"bee\n");
5683
    repo.commit("base", &[]).unwrap();
5684
    let age = |p: &str| {
5685
        let old = std::time::SystemTime::now() - std::time::Duration::from_secs(30);
5686
        fs::File::options()
5687
            .write(true)
5688
            .open(root.join(p))
5689
            .unwrap()
5690
            .set_modified(old)
5691
            .unwrap();
5692
    };
5693
    age("a.txt");
5694
    age("b.txt");
5695
    assert!(
5696
        !repo.snapshot("status").unwrap().changed,
5697
        "records the aged stat"
5698
    );
5699
5700
    // Clean and equal to the base: not read at all.
5701
    fs::set_permissions(root.join("a.txt"), fs::Permissions::from_mode(0o000)).unwrap();
5702
    let snap = repo.snapshot("status").unwrap();
5703
    assert!(
5704
        !snap.changed && snap.statuses.is_empty(),
5705
        "{:?}",
5706
        snap.statuses
5707
    );
5708
    fs::set_permissions(root.join("a.txt"), fs::Permissions::from_mode(0o644)).unwrap();
5709
5710
    // An uncommitted edit that is older than the manifest: stat-clean, but
5711
    // its hash is not the base's, so it is read and stays visible.
5712
    write(root, "b.txt", b"bee edited\n");
5713
    age("b.txt");
5714
    let first = repo.snapshot("status").unwrap();
5715
    assert_eq!(
5716
        statuses(&first),
5717
        vec![("b.txt".to_string(), ChangeStatus::Modified)]
5718
    );
5719
    let again = repo.snapshot("status").unwrap();
5720
    assert_eq!(
5721
        statuses(&again),
5722
        vec![("b.txt".to_string(), ChangeStatus::Modified)],
5723
        "still seen once stat-clean"
5724
    );
5725
    assert!(!again.changed, "and the working copy hashes the same");
5726
    fs::set_permissions(root.join("b.txt"), fs::Permissions::from_mode(0o000)).unwrap();
5727
    assert!(
5728
        repo.snapshot("status").is_err(),
5729
        "an edited file must be read, never taken from the base"
5730
    );
5731
    fs::set_permissions(root.join("b.txt"), fs::Permissions::from_mode(0o644)).unwrap();
5732
5733
    // A same-size edit made just now is racy and read.
5734
    write(root, "a.txt", b"one\nTWO\n");
5735
    assert_eq!(
5736
        statuses(&repo.snapshot("status").unwrap()),
5737
        vec![
5738
            ("a.txt".to_string(), ChangeStatus::Modified),
5739
            ("b.txt".to_string(), ChangeStatus::Modified)
5740
        ]
5741
    );
5742
    // Committing makes the edits the base: both are clean and served from it again.
5743
    repo.commit("edits", &[]).unwrap();
5744
    age("a.txt");
5745
    age("b.txt");
5746
    assert!(repo.snapshot("status").unwrap().statuses.is_empty());
5747
    fs::set_permissions(root.join("a.txt"), fs::Permissions::from_mode(0o000)).unwrap();
5748
    fs::set_permissions(root.join("b.txt"), fs::Permissions::from_mode(0o000)).unwrap();
5749
    let snap = repo.snapshot("status").unwrap();
5750
    assert!(!snap.changed && snap.statuses.is_empty());
5751
    fs::set_permissions(root.join("a.txt"), fs::Permissions::from_mode(0o644)).unwrap();
5752
    fs::set_permissions(root.join("b.txt"), fs::Permissions::from_mode(0o644)).unwrap();
5753
}
5754
5755
/// Version 2 checkpoints (spec §11): a large file's graph is a blob of its
5756
/// own, kept by gc, checked by fsck, shared by the next checkpoint when the
5757
/// file is unchanged, and loading through the checkpoint equals a full load.
5758
#[test]
5759
fn checkpoints_keep_large_graphs_as_blobs_of_their_own() {
5760
    hermetic();
5761
    let dir = tempfile::tempdir().unwrap();
5762
    let root = dir.path();
5763
    let repo = Repo::init(root).unwrap().with_home(root.join("home"));
5764
    let long: String = (0..300)
5765
        .map(|i| format!("line {i} of a long file\n"))
5766
        .collect();
5767
    write(root, "long.txt", long.as_bytes());
5768
    write(root, "short.txt", b"short\n");
5769
    repo.commit("base", &[]).unwrap();
5770
    let (r1, _, _) = repo.checkpoint().unwrap();
5771
    let cp1 = crate::objects::Checkpoint::decode(
5772
        &repo.store().get_typed(&r1, ObjectType::Checkpoint).unwrap(),
5773
    )
5774
    .unwrap();
5775
    let graphs1 = repo.checkpoint_graph_blobs(&cp1).unwrap();
5776
    assert_eq!(graphs1.len(), 1, "only the long file's graph is a blob");
5777
5778
    // gc keeps the graph blob; fsck finds the checkpoint sound.
5779
    repo.gc(true).unwrap();
5780
    assert!(repo.store().has(&graphs1[0]));
5781
    let report = repo.fsck().unwrap();
5782
    assert_eq!(report.errors(), 0, "{:?}", report.problems);
5783
5784
    // Loading through the checkpoint equals a full load.
5785
    write(root, "short.txt", b"short, edited\n");
5786
    repo.commit("edit the short file", &[]).unwrap();
5787
    let heads = repo.bookmark_heads().unwrap();
5788
    let fast = repo.load_state(&heads).unwrap();
5789
    let full = repo.load_state_full(&heads).unwrap();
5790
    assert_eq!(fast.checkpoint_payload(), full.checkpoint_payload());
5791
5792
    // The next checkpoint shares the unchanged long file's graph.
5793
    let (r2, _, _) = repo.checkpoint().unwrap();
5794
    let cp2 = crate::objects::Checkpoint::decode(
5795
        &repo.store().get_typed(&r2, ObjectType::Checkpoint).unwrap(),
5796
    )
5797
    .unwrap();
5798
    assert_eq!(repo.checkpoint_graph_blobs(&cp2).unwrap(), graphs1);
5799
5800
    // A shallow clone's bundle carries the graph blob with the checkpoint.
5801
    let bundle = repo.checkpoint_bundle_for(&heads).unwrap();
5802
    assert!(bundle.objects.iter().any(|(t, body)| *t == ObjectType::Blob
5803
        && crate::hash::hash_object(ObjectType::Blob, body) == graphs1[0]));
5804
5805
    // A version 1 checkpoint written by an older oxy still loads.
5806
    let state = repo.load_state_full(&heads).unwrap();
5807
    let old = repo.store_blob(&state.checkpoint_payload()).unwrap();
5808
    let cp_old = crate::objects::Checkpoint {
5809
        heads: cp2.heads.clone(),
5810
        count: cp2.count,
5811
        payload: old,
5812
    };
5813
    let r_old = repo
5814
        .store()
5815
        .put(ObjectType::Checkpoint, &cp_old.encode())
5816
        .unwrap();
5817
    repo.install_checkpoint("main", &r_old).unwrap();
5818
    assert_eq!(
5819
        repo.load_state(&heads).unwrap().checkpoint_payload(),
5820
        full.checkpoint_payload()
5821
    );
5822
    assert_eq!(repo.fsck().unwrap().errors(), 0);
5823
5824
    // A lost graph blob fails the load loudly rather than dropping the
5825
    // file, and fsck reports it (a fresh repository, objects still loose).
5826
    let dir2 = tempfile::tempdir().unwrap();
5827
    let root2 = dir2.path();
5828
    let repo2 = Repo::init(root2).unwrap().with_home(root2.join("home"));
5829
    write(root2, "long.txt", long.as_bytes());
5830
    repo2.commit("base", &[]).unwrap();
5831
    let (r, _, _) = repo2.checkpoint().unwrap();
5832
    let cp = crate::objects::Checkpoint::decode(
5833
        &repo2.store().get_typed(&r, ObjectType::Checkpoint).unwrap(),
5834
    )
5835
    .unwrap();
5836
    let graph = repo2.checkpoint_graph_blobs(&cp).unwrap()[0];
5837
    repo2.store().remove_loose_for_test(&graph).unwrap();
5838
    assert!(repo2.load_state(&repo2.bookmark_heads().unwrap()).is_err());
5839
    assert!(repo2.fsck().unwrap().errors() > 0, "fsck reports it");
5840
}
5841
5842
/// A new repository has not stored the user's identity yet (that happens
5843
/// at the first signed change); looking it up falls back to the key
5844
/// directory, and a file there that does not hash to the key is refused.
5845
#[test]
5846
fn identity_is_found_in_the_key_directory_for_a_new_repository() {
5847
    hermetic();
5848
    let dir = tempfile::tempdir().unwrap();
5849
    let home = dir.path().join("home");
5850
    let mut first = Repo::init(&dir.path().join("a"))
5851
        .unwrap()
5852
        .with_home(home.clone());
5853
    let (key, _) = first
5854
        .create_identity("Ada", "[email protected]", IdentityScope::User)
5855
        .unwrap();
5856
    let fresh = Repo::init(&dir.path().join("b"))
5857
        .unwrap()
5858
        .with_home(home.clone());
5859
    assert!(!fresh.store().has(&key), "nothing stored yet");
5860
    let id = fresh.identity(&key).unwrap();
5861
    assert_eq!((id.name.as_str(), id.hash()), ("Ada", key));
5862
    // A key file that is not this identity is an error, not a wrong answer.
5863
    let keys = fresh.keys_dir.clone();
5864
    let (other, _) = first
5865
        .create_identity("Bob", "[email protected]", IdentityScope::User)
5866
        .unwrap();
5867
    fs::copy(
5868
        keys.join(format!("{}.identity", other.to_hex())),
5869
        keys.join(format!("{}.identity", key.to_hex())),
5870
    )
5871
    .unwrap();
5872
    assert!(fresh
5873
        .identity(&key)
5874
        .unwrap_err()
5875
        .to_string()
5876
        .contains("does not hold identity"));
5877
}
5878
5879
/// Status snapshots (spec §12.3): a text file whose stat matches the
5880
/// manifest, and whose base graph key is the one the manifest recorded it
5881
/// equal to, is neither read nor rendered; any edit, and any change to the
5882
/// file's graph in the base, brings it back.
5883
#[cfg(unix)]
5884
#[test]
5885
fn status_snapshots_skip_files_unchanged_since_the_manifest() {
5886
    use std::os::unix::fs::PermissionsExt;
5887
    hermetic();
5888
    let dir = tempfile::tempdir().unwrap();
5889
    let root = dir.path();
5890
    let repo = Repo::init(root).unwrap().with_home(root.join("home"));
5891
    for (p, c) in [("a.txt", "one\n"), ("b.txt", "bee\n"), ("d/c.txt", "sea\n")] {
5892
        write(root, p, c.as_bytes());
5893
    }
5894
    repo.commit("base", &[]).unwrap();
5895
    let age = |p: &str| {
5896
        let old = std::time::SystemTime::now() - std::time::Duration::from_secs(30);
5897
        fs::File::options()
5898
            .write(true)
5899
            .open(root.join(p))
5900
            .unwrap()
5901
            .set_modified(old)
5902
            .unwrap();
5903
    };
5904
    let lock = |p: &str, mode: u32| {
5905
        fs::set_permissions(root.join(p), fs::Permissions::from_mode(mode)).unwrap()
5906
    };
5907
    for p in ["a.txt", "b.txt", "d/c.txt"] {
5908
        age(p);
5909
    }
5910
    assert!(repo.snapshot("status").unwrap().statuses.is_empty());
5911
    let (_, _, m) = repo.read_manifest().unwrap().unwrap();
5912
    assert!(
5913
        m.entries.values().all(|e| e.graph.is_some()),
5914
        "keys recorded"
5915
    );
5916
5917
    // Unreadable files prove they are not read; the status snapshot does
5918
    // not render them either, and its base lacks their graphs.
5919
    lock("a.txt", 0o000);
5920
    lock("b.txt", 0o000);
5921
    let snap = repo.snapshot_status("status").unwrap();
5922
    assert!(!snap.changed && snap.statuses.is_empty());
5923
    assert_eq!(
5924
        snap.base_snapshot
5925
            .unrendered
5926
            .iter()
5927
            .cloned()
5928
            .collect::<Vec<_>>(),
5929
        vec!["a.txt", "b.txt", "d/c.txt"]
5930
    );
5931
    assert!(!snap.base.is_full());
5932
    assert!(!snap.base_snapshot.is_conflicted());
5933
    // A full snapshot does not read them either, but renders everything.
5934
    let full = repo.snapshot("status").unwrap();
5935
    assert!(full.statuses.is_empty() && full.base.is_full());
5936
    assert!(full.base_snapshot.unrendered.is_empty());
5937
    assert!(matches!(&full.base_snapshot.files["a.txt"].content,
5938
        FileContent::Text { bytes, .. } if bytes == b"one\n"));
5939
5940
    // An edit is seen; the file is rendered, the others still are not.
5941
    write(root, "d/c.txt", b"sea edited\n");
5942
    let snap = repo.snapshot_status("status").unwrap();
5943
    assert_eq!(
5944
        statuses(&snap),
5945
        vec![("d/c.txt".to_string(), ChangeStatus::Modified)]
5946
    );
5947
    assert!(!snap.base_snapshot.unrendered.contains("d/c.txt"));
5948
    // So is a mode change of an unread file.
5949
    lock("b.txt", 0o100);
5950
    assert_eq!(
5951
        statuses(&repo.snapshot_status("status").unwrap()),
5952
        vec![
5953
            ("b.txt".to_string(), ChangeStatus::ModeChanged),
5954
            ("d/c.txt".to_string(), ChangeStatus::Modified)
5955
        ]
5956
    );
5957
    lock("b.txt", 0o000);
5958
5959
    // Committing c.txt changes its graph in the base, not a.txt's: a.txt
5960
    // stays unread, c.txt is read once and then skipped too.
5961
    repo.commit_selection("edit c", &[], &Selection::Paths(vec!["d/c.txt".into()]))
5962
        .unwrap();
5963
    age("d/c.txt");
5964
    let snap = repo.snapshot_status("status").unwrap();
5965
    assert!(snap.statuses.is_empty(), "{:?}", snap.statuses);
5966
    assert!(snap.base_snapshot.unrendered.contains("a.txt"));
5967
    lock("d/c.txt", 0o000);
5968
    let snap = repo.snapshot_status("status").unwrap();
5969
    assert!(snap.statuses.is_empty());
5970
    assert!(snap.base_snapshot.unrendered.contains("d/c.txt"));
5971
    for p in ["a.txt", "b.txt", "d/c.txt"] {
5972
        lock(p, 0o644);
5973
    }
5974
}
5975
5976
/// Attributes decide how a file compares with the base, so a changed
5977
/// `.oxyattributes` makes every text file be compared again.
5978
#[cfg(unix)]
5979
#[test]
5980
fn a_changed_attributes_file_disables_skipping_unchanged_files() {
5981
    hermetic();
5982
    let dir = tempfile::tempdir().unwrap();
5983
    let root = dir.path();
5984
    let repo = Repo::init(root).unwrap().with_home(root.join("home"));
5985
    write(root, "a.txt", b"crlf\r\n");
5986
    repo.commit("base", &[]).unwrap();
5987
    let old = std::time::SystemTime::now() - std::time::Duration::from_secs(30);
5988
    fs::File::options()
5989
        .write(true)
5990
        .open(root.join("a.txt"))
5991
        .unwrap()
5992
        .set_modified(old)
5993
        .unwrap();
5994
    assert!(repo.snapshot_status("status").unwrap().statuses.is_empty());
5995
    assert!(repo
5996
        .snapshot_status("status")
5997
        .unwrap()
5998
        .base_snapshot
5999
        .unrendered
6000
        .contains("a.txt"));
6001
    // With eol=lf, a.txt as stored no longer equals the base.
6002
    write(root, ".oxyattributes", b"*.txt eol=lf\n");
6003
    let snap = repo.snapshot_status("status").unwrap();
6004
    assert_eq!(
6005
        statuses(&snap),
6006
        vec![
6007
            (".oxyattributes".to_string(), ChangeStatus::Added),
6008
            ("a.txt".to_string(), ChangeStatus::Modified)
6009
        ]
6010
    );
6011
}
6012
6013
/// Bookmarks with `/` in their names: pushing records their
6014
/// attestations, and checkpoints are kept for them, beside `feature`
6015
/// itself.
6016
#[test]
6017
fn bookmarks_with_slashes_push_and_checkpoint() {
6018
    hermetic();
6019
    let dir = tempfile::tempdir().unwrap();
6020
    let root = dir.path();
6021
    let origin = Repo::init(&root.join("origin")).unwrap();
6022
    let url = root.join("origin").to_string_lossy().to_string();
6023
    let mut repo = Repo::clone(&url, &root.join("r"))
6024
        .unwrap()
6025
        .with_home(root.join("home"));
6026
    // With an identity, pushes carry reference attestations: the case
6027
    // that failed, since the attestation is a file named after the bookmark.
6028
    repo.create_identity("Ada", "[email protected]", IdentityScope::Repo)
6029
        .unwrap();
6030
    let r = root.join("r");
6031
    write(&r, "a.txt", b"a\n");
6032
    let h_a = repo.commit("a", &[]).unwrap();
6033
    assert!(repo.push("origin", false).unwrap()[0].ok);
6034
    origin.refresh().unwrap();
6035
    repo.bookmark_create("feature", None).unwrap();
6036
    repo.bookmark_create("feature/x", None).unwrap();
6037
    repo.bookmark_switch("feature/x", false).unwrap();
6038
    write(&r, "b.txt", b"b\n");
6039
    let h_b = repo.commit("b", &[]).unwrap();
6040
    for name in ["feature", "feature/x"] {
6041
        let res = repo.push_bookmark("origin", name, false).unwrap();
6042
        origin.refresh().unwrap();
6043
        assert!(res[0].ok, "{name}: {res:?}");
6044
    }
6045
    assert_eq!(origin.resolve_heads("feature").unwrap(), vec![h_a]);
6046
    assert_eq!(
6047
        origin.resolve_heads("feature/x").unwrap(),
6048
        repo.resolve_heads("feature/x").unwrap()
6049
    );
6050
    assert!(origin.resolve_heads("feature/x").unwrap().contains(&h_b));
6051
    assert!(origin.latest_ref_attest("feature/x").unwrap().is_some());
6052
    assert!(origin.latest_ref_attest("feature").unwrap().is_some());
6053
6054
    // A checkpoint of feature/x is found again when loading its state.
6055
    let (cp, _, _) = repo.checkpoint().unwrap();
6056
    assert_eq!(repo.latest_checkpoint("feature/x").unwrap().unwrap().0, cp);
6057
    assert!(repo.latest_checkpoint("feature").unwrap().is_none());
6058
    let heads = repo.resolve_heads("feature/x").unwrap();
6059
    assert!(repo.load_state_checkpointed(&heads).unwrap().is_some());
6060
}
6061
6062
/// Deleting a bookmark on a remote (spec §16.4): attested like any update,
6063
/// never the remote's own bookmark, and a bookmark created again later is
6064
/// accepted although the deletion's attestation stays the latest.
6065
#[test]
6066
fn bookmarks_are_deleted_on_a_remote() {
6067
    hermetic();
6068
    let dir = tempfile::tempdir().unwrap();
6069
    let root = dir.path();
6070
    let origin = Repo::init(&root.join("origin")).unwrap();
6071
    let url = root.join("origin").to_string_lossy().to_string();
6072
    let mut repo = Repo::clone(&url, &root.join("r"))
6073
        .unwrap()
6074
        .with_home(root.join("home"));
6075
    repo.create_identity("Ada", "[email protected]", IdentityScope::Repo)
6076
        .unwrap();
6077
    let r = root.join("r");
6078
    write(&r, "a.txt", b"a\n");
6079
    repo.commit("a", &[]).unwrap();
6080
    assert!(repo.push("origin", false).unwrap()[0].ok);
6081
    origin.refresh().unwrap();
6082
    repo.bookmark_create("feature/x", None).unwrap();
6083
    assert!(repo.push_bookmark("origin", "feature/x", false).unwrap()[0].ok);
6084
    origin.refresh().unwrap();
6085
    assert!(origin.resolve_heads("feature/x").is_ok());
6086
6087
    let res = repo.push_delete("origin", "feature/x").unwrap();
6088
    origin.refresh().unwrap();
6089
    assert!(res[0].ok, "{res:?}");
6090
    assert!(!origin.view().unwrap().bookmarks.contains_key("feature/x"));
6091
    let (_, att) = origin.latest_ref_attest("feature/x").unwrap().unwrap();
6092
    assert!(
6093
        matches!(att.attest.body, AttestBody::Ref { new_state, .. } if new_state.is_zero()),
6094
        "the deletion is attested"
6095
    );
6096
    assert!(
6097
        repo.view().unwrap().bookmarks.contains_key("feature/x"),
6098
        "the local bookmark stays"
6099
    );
6100
    assert!(!repo
6101
        .view()
6102
        .unwrap()
6103
        .remotes
6104
        .get("origin")
6105
        .is_some_and(|m| m.contains_key("feature/x")));
6106
6107
    // Pushing it again creates it again, past the deletion's serial.
6108
    let res = repo.push_bookmark("origin", "feature/x", false).unwrap();
6109
    origin.refresh().unwrap();
6110
    assert!(res[0].ok, "{res:?}");
6111
    assert!(origin.view().unwrap().bookmarks.contains_key("feature/x"));
6112
6113
    // Nothing to delete, and never the remote's own bookmark.
6114
    assert!(repo.push_delete("origin", "nope").is_err());
6115
    let res = repo.push_delete("origin", "main").unwrap();
6116
    origin.refresh().unwrap();
6117
    assert!(
6118
        !res[0].ok && res[0].reason.contains("default bookmark"),
6119
        "{res:?}"
6120
    );
6121
    assert!(origin.view().unwrap().bookmarks.contains_key("main"));
6122
}
6123
6124
/// `bookmark switch --carry` (spec §10.1): uncommitted work goes along
6125
/// when the target has the same versions of the files it touches, and is
6126
/// refused, untouched, when it has others.
6127
#[test]
6128
fn switching_bookmarks_carries_uncommitted_work() {
6129
    hermetic();
6130
    let dir = tempfile::tempdir().unwrap();
6131
    let root = dir.path();
6132
    let mut repo = Repo::init(root).unwrap().with_home(root.join("home"));
6133
    write(root, "a.txt", b"a\n");
6134
    write(root, "b.txt", b"b\n");
6135
    write(root, "gone.txt", b"gone\n");
6136
    repo.commit("base", &[]).unwrap();
6137
    repo.bookmark_create("feature", None).unwrap();
6138
    // Started on main, belongs on feature: edit, add, remove.
6139
    write(root, "a.txt", b"a\nmore\n");
6140
    write(root, "new.txt", b"new\n");
6141
    fs::remove_file(root.join("gone.txt")).unwrap();
6142
    let (_, carried) = repo.bookmark_switch_carry("feature").unwrap();
6143
    assert_eq!(carried, vec!["a.txt", "gone.txt", "new.txt"]);
6144
    assert_eq!(repo.config.bookmark, "feature");
6145
    assert_eq!(fs::read(root.join("a.txt")).unwrap(), b"a\nmore\n");
6146
    assert_eq!(fs::read(root.join("new.txt")).unwrap(), b"new\n");
6147
    assert!(!root.join("gone.txt").exists());
6148
    let snap = repo.snapshot("status").unwrap();
6149
    assert_eq!(
6150
        statuses(&snap),
6151
        vec![
6152
            ("a.txt".to_string(), ChangeStatus::Modified),
6153
            ("gone.txt".to_string(), ChangeStatus::Removed),
6154
            ("new.txt".to_string(), ChangeStatus::Added)
6155
        ]
6156
    );
6157
    repo.commit("the work", &[]).unwrap();
6158
    assert!(repo.resolve_heads("main").unwrap().len() == 1);
6159
6160
    // main moves b.txt on; work on feature touching b.txt cannot follow.
6161
    repo.bookmark_switch("main", false).unwrap();
6162
    write(root, "b.txt", b"b on main\n");
6163
    repo.commit("b on main", &[]).unwrap();
6164
    repo.bookmark_switch("feature", false).unwrap();
6165
    write(root, "b.txt", b"b edited\n");
6166
    let err = repo.bookmark_switch_carry("main").unwrap_err().to_string();
6167
    assert!(err.contains("b.txt") && err.contains("--discard"), "{err}");
6168
    assert_eq!(repo.config.bookmark, "feature", "nothing happened");
6169
    assert_eq!(fs::read(root.join("b.txt")).unwrap(), b"b edited\n");
6170
}
6171
6172
/// Merging and checking out (feedback 3): a working copy without changes
6173
/// follows a merge whichever state it sat on; a refused checkout names
6174
/// what is in the way; `checkout --carry` takes the work along.
6175
#[test]
6176
fn merges_move_clean_working_copies_and_checkouts_say_what_blocks_them() {
6177
    hermetic();
6178
    let dir = tempfile::tempdir().unwrap();
6179
    let root = dir.path();
6180
    let mut repo = Repo::init(root).unwrap().with_home(root.join("home"));
6181
    write(root, "a.txt", b"a\n");
6182
    let h1 = repo.commit("a", &[]).unwrap();
6183
    write(root, "b.txt", b"b\n");
6184
    repo.commit("b", &[]).unwrap();
6185
    repo.bookmark_create("feature", None).unwrap();
6186
    repo.bookmark_switch("feature", false).unwrap();
6187
    write(root, "c.txt", b"c\n");
6188
    repo.commit("c on feature", &[]).unwrap();
6189
    repo.bookmark_switch("main", false).unwrap();
6190
    // The working copy sits on an older state than main's heads.
6191
    repo.checkout(&[h1], false, "checkout").unwrap();
6192
    assert!(!root.join("b.txt").exists());
6193
    let m = repo.merge("feature").unwrap();
6194
    assert!(m.checked_out, "a clean working copy follows the merge");
6195
    for f in ["a.txt", "b.txt", "c.txt"] {
6196
        assert!(root.join(f).exists(), "{f}");
6197
    }
6198
6199
    // A refusal says which paths are in the way and what to do.
6200
    fs::remove_file(root.join("b.txt")).unwrap();
6201
    write(root, "a.txt", b"a edited\n");
6202
    let err = repo
6203
        .checkout(&[h1], false, "checkout")
6204
        .unwrap_err()
6205
        .to_string();
6206
    assert!(
6207
        err.contains("modified a.txt") && err.contains("removed b.txt") && err.contains("--carry"),
6208
        "{err}"
6209
    );
6210
    // --carry takes them along: h1 has a.txt as the base has it, and the
6211
    // removed b.txt is already as h1 has it (none), so that is no conflict
6212
    // either (oxygen#100).
6213
    let (_, carried) = repo
6214
        .checkout_carry(&[h1], "the first change", "checkout")
6215
        .unwrap();
6216
    assert_eq!(carried, vec!["a.txt"]);
6217
    assert_eq!(fs::read(root.join("a.txt")).unwrap(), b"a edited\n");
6218
    assert!(!root.join("b.txt").exists(), "h1 has no b.txt");
6219
}
6220
6221
/// Doctor and subrepos before the first commit (feedback 5 and 8): a
6222
/// user identity not stored in a new repository yet is fine while its
6223
/// secret key is there; an added subrepo is listed as not committed yet.
6224
#[test]
6225
fn a_new_repository_is_healthy_before_its_first_commit() {
6226
    hermetic();
6227
    let dir = tempfile::tempdir().unwrap();
6228
    let root = dir.path();
6229
    let home = root.join("home");
6230
    let mut first = Repo::init(&root.join("first"))
6231
        .unwrap()
6232
        .with_home(home.clone());
6233
    let (key, _) = first
6234
        .create_identity("Ada", "[email protected]", IdentityScope::User)
6235
        .unwrap();
6236
    let repo = Repo::init(&root.join("second"))
6237
        .unwrap()
6238
        .with_home(home.clone());
6239
    // Only the secret key: no identity object anywhere this repository sees.
6240
    let keys = repo.keys_dir.clone();
6241
    let _ = fs::remove_file(keys.join(format!("{}.identity", key.to_hex())));
6242
    assert!(keys.join(format!("{}.secret", key.to_hex())).is_file());
6243
    let r = repo.doctor(true);
6244
    let id = r.checks.iter().find(|c| c.area == "identity").unwrap();
6245
    assert_eq!(id.health, Health::Ok, "{}", id.message);
6246
    assert!(id.message.contains("first signed change"), "{}", id.message);
6247
6248
    // A subrepo added and not committed yet is listed, pinned where it is.
6249
    let lib = root.join("lib");
6250
    let l = Repo::init(&lib).unwrap().with_home(home.clone());
6251
    write(&lib, "x.txt", b"x\n");
6252
    l.commit("x", &[]).unwrap();
6253
    let second = root.join("second");
6254
    write(&second, "a.txt", b"a\n");
6255
    repo.submodule_add(&lib.to_string_lossy(), "deps/lib", None)
6256
        .unwrap();
6257
    let subs = repo.subrepos().unwrap();
6258
    assert_eq!(subs.len(), 1);
6259
    assert_eq!(
6260
        (subs[0].path.as_str(), subs[0].committed),
6261
        ("deps/lib", false)
6262
    );
6263
    assert_eq!(subs[0].actual.as_ref(), Some(&subs[0].pin));
6264
    repo.commit("add lib", &[]).unwrap();
6265
    let subs = repo.subrepos().unwrap();
6266
    assert!(subs[0].committed, "committed now");
6267
}
6268
6269
/// Commit, diff, hunks and discard use the partial snapshot: a file
6270
/// unchanged since the manifest is neither read nor rendered, and showing
6271
/// a change renders only what it edits, the same as from a full base.
6272
#[cfg(unix)]
6273
#[test]
6274
fn commits_and_diffs_leave_unchanged_files_alone() {
6275
    use std::os::unix::fs::PermissionsExt;
6276
    hermetic();
6277
    let dir = tempfile::tempdir().unwrap();
6278
    let root = dir.path();
6279
    let repo = Repo::init(root).unwrap().with_home(root.join("home"));
6280
    write(root, "big.txt", b"lots\nof\nlines\n");
6281
    write(root, "a.txt", b"one\ntwo\n");
6282
    repo.commit("base", &[]).unwrap();
6283
    let old = std::time::SystemTime::now() - std::time::Duration::from_secs(30);
6284
    for f in ["big.txt", "a.txt"] {
6285
        fs::File::options()
6286
            .write(true)
6287
            .open(root.join(f))
6288
            .unwrap()
6289
            .set_modified(old)
6290
            .unwrap();
6291
    }
6292
    assert!(repo.snapshot_status("status").unwrap().statuses.is_empty());
6293
    // big.txt cannot be read at all from here on.
6294
    fs::set_permissions(root.join("big.txt"), fs::Permissions::from_mode(0o000)).unwrap();
6295
6296
    write(root, "a.txt", b"one\nTWO\nthree\n");
6297
    let diff = repo.diff_files(None).unwrap();
6298
    assert_eq!(
6299
        diff.iter().map(|f| f.path.as_str()).collect::<Vec<_>>(),
6300
        ["a.txt"]
6301
    );
6302
    let (_, hunks) = repo.hunks().unwrap();
6303
    assert!(!hunks.is_empty() && hunks.iter().all(|h| h.path == "a.txt"));
6304
    let h = repo.commit("edit a", &[]).unwrap();
6305
6306
    // Showing the change needs only a.txt's graph, and renders as a full base does.
6307
    let c = repo.store().get_change(&h).unwrap();
6308
    let full = repo.load_state(&c.deps).unwrap();
6309
    let want = render_change(&c, &full, &full.materialize());
6310
    assert_eq!(repo.describe_change(&h).unwrap(), want);
6311
    let (base, snap) = repo.change_base(&c).unwrap();
6312
    assert!(!base.is_full() && snap.unrendered.contains("big.txt"));
6313
6314
    // Discarding works the same way.
6315
    write(root, "a.txt", b"scratch\n");
6316
    assert_eq!(repo.discard(&["a.txt".into()]).unwrap(), 1);
6317
    assert_eq!(fs::read(root.join("a.txt")).unwrap(), b"one\nTWO\nthree\n");
6318
    fs::set_permissions(root.join("big.txt"), fs::Permissions::from_mode(0o644)).unwrap();
6319
}
6320
6321
/// A replace conflict (spec §9.3) is settled by a change that writes one
6322
/// candidate, or new bytes, at the path when the caller names it; a plain
6323
/// snapshot of a checkout never settles it on its own.
6324
#[test]
6325
fn replace_conflicts_are_settled_when_asked() {
6326
    hermetic();
6327
    let dir = tempfile::tempdir().unwrap();
6328
    let root = dir.path();
6329
    let mut repo = Repo::init(root).unwrap().with_home(root.join("home"));
6330
    let blob = |n: u8| {
6331
        let mut v = vec![0u8; 64];
6332
        v[1] = n;
6333
        v
6334
    };
6335
    write(root, "img.bin", &blob(1));
6336
    repo.commit("add img", &[]).unwrap();
6337
    repo.bookmark_create("other", None).unwrap();
6338
    write(root, "img.bin", &blob(2));
6339
    repo.commit("img two", &[]).unwrap();
6340
    repo.bookmark_switch("other", false).unwrap();
6341
    write(root, "img.bin", &blob(3));
6342
    repo.commit("img three", &[]).unwrap();
6343
    repo.bookmark_switch("main", false).unwrap();
6344
    repo.merge("other").unwrap();
6345
    let heads = repo.bookmark_heads().unwrap();
6346
    let merged = repo.load_state(&heads).unwrap().materialize();
6347
    assert!(
6348
        matches!(&merged.files["img.bin"].content, FileContent::Opaque { blobs } if blobs.len() == 2),
6349
        "a replace conflict"
6350
    );
6351
    // A snapshot of the checkout records nothing.
6352
    assert!(repo
6353
        .snapshot("status")
6354
        .unwrap()
6355
        .statuses
6356
        .iter()
6357
        .all(|s| s.path != "img.bin"));
6358
6359
    // Keeping candidate 3 settles it.
6360
    let author = repo.author();
6361
    let edits = [FileEdit {
6362
        path: "img.bin".into(),
6363
        content: Some(blob(3)),
6364
    }];
6365
    let c = repo
6366
        .build_change(&heads, &edits, "keep three", author)
6367
        .unwrap();
6368
    assert_eq!(c.kind, ChangeKind::Resolution);
6369
    let mut st = repo.load_state(&heads).unwrap();
6370
    for d in &c.deps {
6371
        assert!(st.contains(d));
6372
    }
6373
    assert!(
6374
        heads.iter().all(|h| c.deps.contains(h)),
6375
        "depends on both contributors"
6376
    );
6377
    st.add(c).unwrap();
6378
    let after = st.materialize();
6379
    assert!(!after.is_conflicted());
6380
    assert_eq!(
6381
        after.files["img.bin"].content,
6382
        FileContent::Opaque {
6383
            blobs: vec![Repo::blob_ref(&blob(3))]
6384
        }
6385
    );
6386
6387
    // New bytes settle it too.
6388
    let edits = [FileEdit {
6389
        path: "img.bin".into(),
6390
        content: Some(blob(9)),
6391
    }];
6392
    let c = repo.build_change(&heads, &edits, "new", author).unwrap();
6393
    let mut st = repo.load_state(&heads).unwrap();
6394
    st.add(c).unwrap();
6395
    assert_eq!(
6396
        st.materialize().files["img.bin"].content,
6397
        FileContent::Opaque {
6398
            blobs: vec![Repo::blob_ref(&blob(9))]
6399
        }
6400
    );
6401
}
6402
6403
/// The history of a range of lines (spec §27): the changes that wrote
6404
/// or deleted its atoms, or deleted atoms from between them; edits outside
6405
/// the range and changes the range's lines survived are not in it.
6406
#[test]
6407
fn line_ranges_have_exact_histories() {
6408
    hermetic();
6409
    let dir = tempfile::tempdir().unwrap();
6410
    let root = dir.path();
6411
    let repo = Repo::init(root).unwrap().with_home(root.join("home"));
6412
    write(root, "f.rs", b"use x;\nfn a() {\n  one();\n  two();\n}\n");
6413
    let base = repo.commit("add f", &[]).unwrap();
6414
    write(root, "f.rs", b"use y;\nfn a() {\n  one();\n  two();\n}\n");
6415
    let outside = repo.commit("change the import", &[]).unwrap();
6416
    write(root, "f.rs", b"use y;\nfn a() {\n  ONE();\n  two();\n}\n");
6417
    let inside = repo.commit("edit a line of a", &[]).unwrap();
6418
    write(root, "f.rs", b"use y;\nfn a() {\n  ONE();\n}\n");
6419
    let deleted = repo.commit("delete a line of a", &[]).unwrap();
6420
    write(root, "f.rs", b"use y;\nfn a() {\n  ONE();\n}\nfn b() {}\n");
6421
    let after = repo.commit("add b after a", &[]).unwrap();
6422
    let heads = repo.bookmark_heads().unwrap();
6423
6424
    // Lines 2..4 are `fn a() {`, `ONE();`, `}` now.
6425
    let hist: Vec<ChangeHash> = repo
6426
        .line_history(&heads, "f.rs", 2, 4)
6427
        .unwrap()
6428
        .iter()
6429
        .map(|e| e.hash)
6430
        .collect();
6431
    for (h, what) in [
6432
        (base, "wrote it"),
6433
        (inside, "edited a line"),
6434
        (deleted, "deleted a line from inside"),
6435
    ] {
6436
        assert!(hist.contains(&h), "{what}");
6437
    }
6438
    for (h, what) in [(outside, "an edit above"), (after, "an addition below")] {
6439
        assert!(!hist.contains(&h), "{what}");
6440
    }
6441
    assert_eq!(hist[0], deleted, "newest first");
6442
    // One line: only what touched it.
6443
    let one: Vec<ChangeHash> = repo
6444
        .line_history(&heads, "f.rs", 1, 1)
6445
        .unwrap()
6446
        .iter()
6447
        .map(|e| e.hash)
6448
        .collect();
6449
    assert!(one.contains(&outside) && !one.contains(&inside));
6450
    assert!(repo.line_history(&heads, "f.rs", 3, 9).is_err());
6451
    assert!(repo.line_history(&heads, "f.rs", 0, 1).is_err());
6452
    assert!(repo.line_history(&heads, "nope.rs", 1, 1).is_err());
6453
}
6454
6455
#[test]
6456
fn receipts_are_kept_with_their_state_and_verified() {
6457
    use crate::receipt::{Receipt, SignedReceipt};
6458
    hermetic();
6459
    let dir = tempfile::tempdir().unwrap();
6460
    let root = dir.path();
6461
    let repo = Repo::init(root).unwrap().with_home(root.join("home"));
6462
    write(root, "a.txt", b"1\n");
6463
    repo.commit("A", &[]).unwrap();
6464
    let heads = repo.bookmark_heads().unwrap();
6465
    let state = repo
6466
        .store()
6467
        .put_state(&StateObject::new(heads.clone()))
6468
        .unwrap();
6469
    let out = repo.store_blob(b"built\n").unwrap();
6470
    let receipt = Receipt {
6471
        job_name: "build".into(),
6472
        pipeline_hash: ObjectRef([1; 32]),
6473
        scope_tree_hash: ObjectRef([2; 32]),
6474
        inputs: vec![],
6475
        environment: ObjectRef([3; 32]),
6476
        outputs: vec![out],
6477
        exit_code: 0,
6478
        duration_ms: 42,
6479
    };
6480
    let sk = SecretKey::generate();
6481
    let runner = sk.identity("earth-1", "runner@earth", 1);
6482
    let sr = SignedReceipt::sign(
6483
        receipt.clone(),
6484
        repo.id().unwrap(),
6485
        state,
6486
        "demo#1",
6487
        &runner,
6488
        &sk,
6489
    );
6490
6491
    let r = repo.add_receipt(&sr).unwrap();
6492
    let found = repo.receipts(&heads).unwrap();
6493
    assert_eq!(found.len(), 1);
6494
    assert_eq!(found[0].attest, r);
6495
    assert_eq!(found[0].signed, sr);
6496
    assert!(found[0].problem.is_none() && !found[0].revoked);
6497
    assert!(repo.receipts(&[ObjectRef([5; 32])]).unwrap().is_empty());
6498
6499
    // Another repository's receipt, or a forged one, is refused.
6500
    let elsewhere = SignedReceipt::sign(receipt.clone(), [0; 16], state, "x", &runner, &sk);
6501
    assert!(repo
6502
        .add_receipt(&elsewhere)
6503
        .unwrap_err()
6504
        .to_string()
6505
        .contains("another repository"));
6506
    let mut forged = sr.clone();
6507
    forged.receipt.exit_code = 1;
6508
    assert!(repo
6509
        .add_receipt(&forged)
6510
        .unwrap_err()
6511
        .to_string()
6512
        .contains("does not verify"));
6513
6514
    // A receipt signed by a short-lived key keeps its certificate and the
6515
    // issuer's identity, and reads back with them (oxygenhub#241).
6516
    let hub_sk = SecretKey::generate();
6517
    let hub = hub_sk.identity("oxygenhub.io", "[email protected]", 1);
6518
    let job_sk = SecretKey::generate();
6519
    let job = job_sk.identity("job 2 test", "[email protected]", 1);
6520
    let mut test_receipt = receipt.clone();
6521
    test_receipt.job_name = "test".into();
6522
    let plain = SignedReceipt::sign(
6523
        test_receipt,
6524
        repo.id().unwrap(),
6525
        state,
6526
        "demo#2",
6527
        &job,
6528
        &job_sk,
6529
    );
6530
    let now = plain.attest.hlc.wall_ms;
6531
    let cert = crate::cert::SignedCertificate::sign(
6532
        crate::cert::Certificate {
6533
            key: job.clone(),
6534
            issuer: hub.hash(),
6535
            subject: "repo:andy/demo:bookmark:main".into(),
6536
            claims: vec![],
6537
            scope: crate::identity::Scope::SEAL,
6538
            not_before: now - 1_000,
6539
            expires: now + 600_000,
6540
            grant: None,
6541
        },
6542
        &hub,
6543
        &hub_sk,
6544
    );
6545
    let certified = plain.with_certificate(cert, hub.clone());
6546
    repo.add_receipt(&certified).unwrap();
6547
    let found = repo.receipts(&heads).unwrap();
6548
    let got = found
6549
        .iter()
6550
        .find(|i| i.signed.receipt.job_name == "test")
6551
        .unwrap();
6552
    assert_eq!(got.signed, certified);
6553
    assert!(got.problem.is_none(), "{:?}", got.problem);
6554
6555
    // gc keeps the receipts, their runners, the certificate and its issuer,
6556
    // and the output while the state lives.
6557
    repo.gc(true).unwrap();
6558
    let found = repo.receipts(&heads).unwrap();
6559
    assert_eq!(found.len(), 2);
6560
    let got = found
6561
        .iter()
6562
        .find(|i| i.signed.receipt.job_name == "test")
6563
        .unwrap();
6564
    assert_eq!(got.signed, certified, "the certificate survives gc");
6565
    assert!(got.problem.is_none());
6566
    assert_eq!(repo.read_blob(&out).unwrap(), b"built\n");
6567
    assert!(repo.fsck().unwrap().problems.is_empty());
6568
}
6569
6570
#[test]
6571
fn approvals_are_kept_with_their_state_and_survive_gc() {
6572
    hermetic();
6573
    let dir = tempfile::tempdir().unwrap();
6574
    let root = dir.path();
6575
    let repo = Repo::init(root).unwrap().with_home(root.join("home"));
6576
    write(root, "a.txt", b"1\n");
6577
    repo.commit("A", &[]).unwrap();
6578
    let heads = repo.bookmark_heads().unwrap();
6579
    let state = repo.store().put_state(&StateObject::new(heads)).unwrap();
6580
    let plan = repo.store_blob(b"the reviewed plan\n").unwrap();
6581
    let sk = SecretKey::generate();
6582
    let andy = sk.identity("Andy", "[email protected]", 1);
6583
    let statement = crate::approval::Statement {
6584
        repo: repo.id().unwrap(),
6585
        run: "https://hub.example/andy/infra/flow/8".into(),
6586
        job: "apply".into(),
6587
        job_hash: ObjectRef([1; 32]),
6588
        state,
6589
        inputs: vec![plan],
6590
        environment: "prod".into(),
6591
        approve: true,
6592
    };
6593
    let sa = crate::approval::SignedApproval::sign(&statement, &andy, &sk);
6594
    let r = repo.add_approval(&sa).unwrap();
6595
    assert_eq!(repo.store().approvals_for(&state).unwrap(), vec![r]);
6596
    // Another repository's approval, or a changed one, is refused.
6597
    let elsewhere = crate::approval::SignedApproval::sign(
6598
        &crate::approval::Statement {
6599
            repo: [0; 16],
6600
            ..statement.clone()
6601
        },
6602
        &andy,
6603
        &sk,
6604
    );
6605
    assert!(repo
6606
        .add_approval(&elsewhere)
6607
        .unwrap_err()
6608
        .to_string()
6609
        .contains("another repository"));
6610
    let mut forged = sa.clone();
6611
    if let AttestBody::Approval { environment, .. } = &mut forged.attest.body {
6612
        *environment = "dev".into();
6613
    }
6614
    assert!(repo
6615
        .add_approval(&forged)
6616
        .unwrap_err()
6617
        .to_string()
6618
        .contains("does not verify"));
6619
    // gc keeps it, its signature and its signer while the state lives.
6620
    repo.gc(true).unwrap();
6621
    assert_eq!(repo.store().approvals_for(&state).unwrap(), vec![r]);
6622
    assert_eq!(repo.store().get_attest(&r).unwrap(), sa.attest);
6623
    assert_eq!(repo.store().signatures(&r).unwrap(), sa.sigs);
6624
    assert!(repo.fsck().unwrap().problems.is_empty());
6625
}
6626
6627
#[test]
6628
fn status_leaves_an_unchanged_manifest_alone() {
6629
    hermetic();
6630
    let dir = tempfile::tempdir().unwrap();
6631
    let root = dir.path();
6632
    let repo = Repo::init(root).unwrap().with_home(root.join("home"));
6633
    write(root, "a.txt", b"1\n");
6634
    write(root, "b.txt", b"2\n");
6635
    repo.commit("A", &[]).unwrap();
6636
    // Files last touched well outside the racy window.
6637
    let old = std::time::SystemTime::now() - std::time::Duration::from_secs(60);
6638
    for f in ["a.txt", "b.txt"] {
6639
        fs::File::options()
6640
            .write(true)
6641
            .open(root.join(f))
6642
            .unwrap()
6643
            .set_modified(old)
6644
            .unwrap();
6645
    }
6646
    repo.snapshot_status("status").unwrap();
6647
    let path = repo.manifest_path();
6648
    let first = fs::read(&path).unwrap();
6649
    repo.snapshot_status("status").unwrap();
6650
    assert_eq!(
6651
        fs::read(&path).unwrap(),
6652
        first,
6653
        "an unchanged tree does not rewrite the manifest"
6654
    );
6655
    // A change rewrites it.
6656
    write(root, "a.txt", b"1\n2\n");
6657
    repo.snapshot_status("status").unwrap();
6658
    assert_ne!(fs::read(&path).unwrap(), first);
6659
}
6660
6661
#[test]
6662
fn large_text_files_travel_and_survive_gc_as_text_blobs() {
6663
    hermetic();
6664
    let dir = tempfile::tempdir().unwrap();
6665
    let root = dir.path();
6666
    let origin_path = root.join("origin");
6667
    Repo::init(&origin_path).unwrap();
6668
    let origin_url = origin_path.to_string_lossy().to_string();
6669
    let a = Repo::clone(&origin_url, &root.join("a")).unwrap();
6670
    let big: String = (0..5000).map(|i| format!("line {i}\n")).collect();
6671
    write(&root.join("a"), "big.txt", big.as_bytes());
6672
    write(&root.join("a"), "small.txt", b"small\n");
6673
    let h1 = a.commit("large", &[]).unwrap();
6674
    let (_, body) = a.store().get(&h1).unwrap();
6675
    assert!(body.len() < 2048, "the change is {} bytes", body.len());
6676
    assert!(a.push("origin", false).unwrap()[0].ok);
6677
6678
    // A clone reads the text from the blobs that came with the change.
6679
    let b = Repo::clone(&origin_url, &root.join("b")).unwrap();
6680
    assert_eq!(fs::read(root.join("b/big.txt")).unwrap(), big.as_bytes());
6681
    // An edit in the middle of the stored insert is an ordinary change.
6682
    let edited = big.replace("line 2500\n", "line 2500, edited\n");
6683
    write(&root.join("b"), "big.txt", edited.as_bytes());
6684
    let h2 = b.commit("edit", &[]).unwrap();
6685
    assert!(b.store().get_change(&h2).unwrap().edits.len() <= 2);
6686
    assert!(b.push("origin", false).unwrap()[0].ok);
6687
    assert!(a.pull("origin").unwrap().checked_out);
6688
    assert_eq!(fs::read(root.join("a/big.txt")).unwrap(), edited.as_bytes());
6689
    assert_eq!(
6690
        a.fsck().unwrap().errors(),
6691
        0,
6692
        "{:?}",
6693
        a.fsck().unwrap().problems
6694
    );
6695
6696
    // With zero retention gc keeps the text blobs of every kept change.
6697
    let mut a = Repo::open(&root.join("a")).unwrap();
6698
    a.config.set("core.op-retention", "0").unwrap();
6699
    a.save_config().unwrap();
6700
    let a = Repo::open(&root.join("a")).unwrap();
6701
    a.gc(true).unwrap();
6702
    let a = Repo::open(&root.join("a")).unwrap();
6703
    assert_eq!(a.store().get_change(&h1).unwrap().message, "large");
6704
    assert_eq!(
6705
        a.fsck().unwrap().errors(),
6706
        0,
6707
        "{:?}",
6708
        a.fsck().unwrap().problems
6709
    );
6710
    // And a clone of the packed repository reads them from its packs.
6711
    let c = Repo::clone(&root.join("a").to_string_lossy(), &root.join("c")).unwrap();
6712
    assert_eq!(fs::read(root.join("c/big.txt")).unwrap(), edited.as_bytes());
6713
    drop(c);
6714
}
6715
6716
#[test]
6717
fn operations_that_both_replace_a_working_copy_are_not_merged() {
6718
    hermetic();
6719
    let dir = tempfile::tempdir().unwrap();
6720
    let root = dir.path();
6721
    let repo = Repo::init(root).unwrap();
6722
    write(root, "a.txt", b"a\n");
6723
    let a = repo.commit("a", &[]).unwrap();
6724
    write(root, "b.txt", b"b\n");
6725
    repo.commit("b", &[]).unwrap();
6726
    let (x, op) = repo.head_op().unwrap();
6727
    let ws = *op.view.workspaces.keys().next().unwrap();
6728
    let mut one = op.view.clone();
6729
    one.workspaces.insert(ws, a);
6730
    let mut two = op.view.clone();
6731
    two.workspaces.insert(ws, ObjectRef([7; 32]));
6732
    let first = repo.record_op(&[x], "one", one).unwrap();
6733
    let e = repo.record_op(&[x], "two", two).unwrap_err();
6734
    assert!(
6735
        e.to_string()
6736
            .contains("changed this working copy at the same time"),
6737
        "{e}"
6738
    );
6739
    assert_eq!(
6740
        repo.head_op().unwrap().0,
6741
        first,
6742
        "the second is not recorded"
6743
    );
6744
}
6745
6746
/// Metalgear, 2026-09-29 (oxygen#36): a status run while a bookmark switch
6747
/// rewrote the working copy recorded the half-written files as edits, and
6748
/// its view replaced the switch's.
6749
#[test]
6750
fn a_snapshot_during_a_switch_never_records_the_switch_as_edits() {
6751
    hermetic();
6752
    let dir = tempfile::tempdir().unwrap();
6753
    let root = dir.path().to_path_buf();
6754
    let mut repo = Repo::init(&root).unwrap();
6755
    write(&root, "keep.txt", b"keep\n");
6756
    repo.commit("base", &[]).unwrap();
6757
    repo.bookmark_create("small", None).unwrap();
6758
    for i in 0..300 {
6759
        write(
6760
            &root,
6761
            &format!("many/f{i}.txt"),
6762
            format!("file {i}\n").as_bytes(),
6763
        );
6764
    }
6765
    repo.commit("many", &[]).unwrap();
6766
    let stop = std::sync::Arc::new(std::sync::atomic::AtomicBool::new(false));
6767
    let watcher = {
6768
        let (root, stop) = (root.clone(), stop.clone());
6769
        std::thread::spawn(move || {
6770
            let r = Repo::open(&root).unwrap();
6771
            let mut ran = 0;
6772
            while !stop.load(std::sync::atomic::Ordering::Relaxed) {
6773
                if r.snapshot_status("oxy status").is_ok() {
6774
                    ran += 1;
6775
                }
6776
            }
6777
            ran
6778
        })
6779
    };
6780
    for i in 0..20 {
6781
        let to = if i % 2 == 0 { "small" } else { "main" };
6782
        repo.bookmark_switch(to, false).unwrap();
6783
    }
6784
    stop.store(true, std::sync::atomic::Ordering::Relaxed);
6785
    assert!(watcher.join().unwrap() > 0, "the watcher snapshotted");
6786
    // Back on main, clean, with every file where main has it.
6787
    let repo = Repo::open(&root).unwrap();
6788
    let s = repo.snapshot_status("oxy status").unwrap();
6789
    assert!(s.statuses.is_empty(), "{:?}", statuses(&s));
6790
    assert!(s.wc.edits.is_empty() && s.wc.tree_ops.is_empty());
6791
    assert_eq!(s.wc.deps, repo.bookmark_heads().unwrap());
6792
    assert!(root.join("many/f299.txt").exists());
6793
}
6794
6795
/// Metalgear, 2026-09-29 (oxygen#38): a parent's `bookmark switch --carry`
6796
/// put a subrepo that was ahead of its pin back at the pin and moved the
6797
/// subrepo's own bookmark backwards.
6798
#[test]
6799
fn a_parent_switch_with_carry_leaves_a_subrepo_ahead_of_its_pin_alone() {
6800
    hermetic();
6801
    let dir = tempfile::tempdir().unwrap();
6802
    let root = dir.path();
6803
    Repo::init(&root.join("lib-origin")).unwrap();
6804
    let lib_url = root.join("lib-origin").to_string_lossy().to_string();
6805
    let lib = Repo::clone(&lib_url, &root.join("lib")).unwrap();
6806
    write(&root.join("lib"), "lib.txt", b"v1\n");
6807
    lib.commit("lib v1", &[]).unwrap();
6808
    assert!(lib.push("origin", false).unwrap()[0].ok);
6809
6810
    let app_dir = root.join("app");
6811
    let mut app = Repo::init(&app_dir).unwrap();
6812
    write(&app_dir, "main.txt", b"app\n");
6813
    app.submodule_add(&lib_url, "libs/lib", None).unwrap();
6814
    app.commit("app with lib", &[]).unwrap();
6815
    app.bookmark_create("feature", None).unwrap();
6816
6817
    // New work in the subrepo, not yet pinned by the parent.
6818
    let nested_dir = app_dir.join("libs/lib");
6819
    let nested = Repo::open(&nested_dir).unwrap();
6820
    write(&nested_dir, "new.txt", b"new\n");
6821
    let l2 = nested.commit("lib: new file", &[]).unwrap();
6822
    drop(nested);
6823
6824
    let (_, carried) = app.bookmark_switch_carry("feature").unwrap();
6825
    assert!(carried.contains(&"libs/lib".to_string()), "{carried:?}");
6826
    let nested = Repo::open(&nested_dir).unwrap();
6827
    assert!(
6828
        nested.bookmark_heads().unwrap().contains(&l2),
6829
        "its bookmark kept its work"
6830
    );
6831
    assert!(nested_dir.join("new.txt").exists(), "and its files");
6832
    let s = app.snapshot("status").unwrap();
6833
    assert_eq!(
6834
        statuses(&s),
6835
        vec![("libs/lib".to_string(), ChangeStatus::Modified)]
6836
    );
6837
}
6838
6839
/// oxygen#29 (metalgear, rstar-api): after a proposal landed on the hub,
6840
/// moving `main` to a change this clone had pushed on another bookmark,
6841
/// the first `pull` said "Already up to date" while `main` was behind.
6842
#[test]
6843
fn pull_takes_a_remote_move_to_changes_already_here() {
6844
    hermetic();
6845
    let dir = tempfile::tempdir().unwrap();
6846
    let root = dir.path();
6847
    let origin_path = root.join("origin");
6848
    let origin = Repo::init(&origin_path).unwrap();
6849
    let url = origin_path.to_string_lossy().to_string();
6850
    let mut b = Repo::clone(&url, &root.join("b")).unwrap();
6851
    write(&root.join("b"), "base.txt", b"base\n");
6852
    b.commit("base", &[]).unwrap();
6853
    assert!(b.push("origin", false).unwrap()[0].ok);
6854
    origin.refresh().unwrap();
6855
6856
    // A feature bookmark with one change, pushed.
6857
    b.bookmark_create("feat", None).unwrap();
6858
    b.bookmark_switch("feat", false).unwrap();
6859
    write(&root.join("b"), "x.txt", b"x\n");
6860
    let x = b.commit("x", &[]).unwrap();
6861
    assert!(b.push("origin", false).unwrap()[0].ok);
6862
    origin.refresh().unwrap();
6863
    b.bookmark_switch("main", false).unwrap();
6864
6865
    // The remote lands it: its main moves to the feature's state.
6866
    let feat = origin
6867
        .store()
6868
        .get_state(&origin.view().unwrap().bookmarks["feat"])
6869
        .unwrap()
6870
        .heads;
6871
    origin.bookmark_set("main", &feat).unwrap();
6872
6873
    let r = b.pull("origin").unwrap();
6874
    assert!(r.changed, "{r:?}");
6875
    assert!(r.heads.contains(&x) || b.load_state(&r.heads).unwrap().contains(&x));
6876
    let main = b
6877
        .bookmarks()
6878
        .unwrap()
6879
        .into_iter()
6880
        .find(|m| m.name == "main")
6881
        .unwrap();
6882
    assert_eq!(main.behind, Some(0), "{main:?}");
6883
}
6884
6885
/// oxygen#48: a remote's bookmarks are names here (`origin/NAME`); switching
6886
/// to one only the remote has makes a local bookmark from it; a pull moves
6887
/// every local bookmark the remote has too; a clone checks out the remote's
6888
/// default bookmark.
6889
#[test]
6890
fn remote_bookmarks_are_named_switched_to_pulled_and_cloned() {
6891
    hermetic();
6892
    let dir = tempfile::tempdir().unwrap();
6893
    let root = dir.path();
6894
    let origin_path = root.join("origin");
6895
    let mut origin = Repo::init(&origin_path).unwrap();
6896
    let url = origin_path.to_string_lossy().to_string();
6897
    let mut a = Repo::clone(&url, &root.join("a")).unwrap();
6898
    write(&root.join("a"), "base.txt", b"base\n");
6899
    a.commit("base", &[]).unwrap();
6900
    assert!(a.push("origin", false).unwrap()[0].ok);
6901
    a.bookmark_create("develop", None).unwrap();
6902
    a.bookmark_switch("develop", false).unwrap();
6903
    write(&root.join("a"), "base.txt", b"base\nd1\n");
6904
    let d1 = a.commit("d1", &[]).unwrap();
6905
    assert!(a.push("origin", false).unwrap()[0].ok);
6906
6907
    // A clone has main only; origin/develop is a name all the same.
6908
    let c_root = root.join("c");
6909
    let mut c = Repo::clone(&url, &c_root).unwrap();
6910
    assert_eq!(c.config.bookmark, "main");
6911
    assert!(!c.view().unwrap().bookmarks.contains_key("develop"));
6912
    assert_eq!(c.resolve_heads("origin/develop").unwrap(), vec![d1]);
6913
    assert_eq!(c.resolve_change("origin/develop").unwrap(), d1);
6914
    assert_eq!(c.remote_only_bookmarks().unwrap().len(), 1);
6915
6916
    // Switching makes the local bookmark from origin's.
6917
    c.bookmark_switch("develop", false).unwrap();
6918
    assert_eq!(c.config.bookmark, "develop");
6919
    assert_eq!(c.bookmark_heads().unwrap(), vec![d1]);
6920
    assert_eq!(fs::read(c_root.join("base.txt")).unwrap(), b"base\nd1\n");
6921
    assert!(c.remote_only_bookmarks().unwrap().is_empty());
6922
    assert!(c.bookmark_switch("nowhere", false).is_err());
6923
6924
    // Both bookmarks move on the remote; one pull takes both.
6925
    write(&root.join("a"), "base.txt", b"base\nd1\nd2\n");
6926
    let d2 = a.commit("d2", &[]).unwrap();
6927
    assert!(a.push("origin", false).unwrap()[0].ok);
6928
    a.bookmark_switch("main", false).unwrap();
6929
    write(&root.join("a"), "m.txt", b"m\n");
6930
    let m = a.commit("m", &[]).unwrap();
6931
    assert!(a.push("origin", false).unwrap()[0].ok);
6932
    let r = c.pull("origin").unwrap();
6933
    assert!(r.changed && r.checked_out, "{r:?}");
6934
    assert_eq!(r.heads, vec![d2]);
6935
    assert_eq!(r.others, vec!["main".to_string()]);
6936
    assert!(c.resolve_heads("main").unwrap().contains(&m));
6937
    assert_eq!(
6938
        fs::read(c_root.join("base.txt")).unwrap(),
6939
        b"base\nd1\nd2\n"
6940
    );
6941
    let again = c.pull("origin").unwrap();
6942
    assert!(!again.changed && again.others.is_empty(), "{again:?}");
6943
6944
    // A clone checks out the remote's default bookmark.
6945
    origin.config.set("workspace.bookmark", "develop").unwrap();
6946
    origin.save_config().unwrap();
6947
    let e = Repo::clone(&url, &root.join("e")).unwrap();
6948
    assert_eq!(e.config.bookmark, "develop");
6949
    assert_eq!(e.bookmark_heads().unwrap(), vec![d2]);
6950
    let reopened = Repo::open(&root.join("e")).unwrap();
6951
    assert_eq!(reopened.config.bookmark, "develop");
6952
    // REMOTE/NAME names the remote's bookmark to switch to.
6953
    let mut e = reopened;
6954
    e.bookmark_switch("origin/main", false).unwrap();
6955
    assert_eq!(e.config.bookmark, "main");
6956
    assert!(e.bookmark_heads().unwrap().contains(&m));
6957
}
6958
6959
/// oxygen#51, #52: --at-op reads an earlier view and refuses changes;
6960
/// op restore goes back to an operation, files included, and undo takes
6961
/// the restore back whole; op revert undoes one operation alone; each
6962
/// operation's changes are described from the views.
6963
#[test]
6964
fn operations_can_be_read_restored_and_reverted() {
6965
    hermetic();
6966
    let dir = tempfile::tempdir().unwrap();
6967
    let root = dir.path();
6968
    let repo = Repo::init(root).unwrap();
6969
    write(root, "a.txt", b"a\n");
6970
    let first = repo.commit("first", &[]).unwrap();
6971
    write(root, "a.txt", b"a\nb\n");
6972
    let second = repo.commit("second", &[]).unwrap();
6973
    let at_second = repo.head_op().unwrap().0.to_hex();
6974
    repo.bookmark_create("keep", None).unwrap();
6975
    let created = repo.head_op().unwrap().0.to_hex();
6976
    write(root, "n.txt", b"n\n");
6977
    let third = repo.commit("third", &[]).unwrap();
6978
6979
    // What each operation changed.
6980
    let ops = repo.op_log().unwrap();
6981
    let changes = repo.view_changes(&ops[1].1.view, &ops[0].1.view).unwrap();
6982
    assert!(
6983
        changes
6984
            .iter()
6985
            .any(|c| matches!(c, ViewChange::BookmarkMoved { name, .. } if name == "main")),
6986
        "{changes:?}"
6987
    );
6988
    assert!(changes
6989
        .iter()
6990
        .any(|c| matches!(c, ViewChange::WorkingCopy { .. })));
6991
6992
    // Reading at an earlier operation.
6993
    let old = Repo::open(root).unwrap().at_op(&at_second[..10]).unwrap();
6994
    assert_eq!(old.bookmark_heads().unwrap(), vec![second]);
6995
    assert!(!old.view().unwrap().bookmarks.contains_key("keep"));
6996
    write(root, "z.txt", b"z\n");
6997
    assert!(old.commit("refused", &[]).is_err(), "--at-op is read-only");
6998
    fs::remove_file(root.join("z.txt")).unwrap();
6999
    assert!(repo.resolve_op("zz").is_err());
7000
    assert_eq!(repo.resolve_op("@").unwrap().0, repo.head_op().unwrap().0);
7001
7002
    // Restore goes back, files and all; undo takes it back whole.
7003
    repo.op_restore(&at_second, false).unwrap();
7004
    assert_eq!(repo.bookmark_heads().unwrap(), vec![second]);
7005
    assert!(!root.join("n.txt").exists());
7006
    repo.undo().unwrap();
7007
    let mut heads = repo.bookmark_heads().unwrap();
7008
    heads.sort();
7009
    let mut want = vec![second, third];
7010
    want.sort();
7011
    assert_eq!(heads, want);
7012
    assert!(
7013
        root.join("n.txt").exists(),
7014
        "the files came back with the undo"
7015
    );
7016
7017
    // Revert the bookmark's creation alone: the commit after it stays.
7018
    let r = repo.op_revert(&created).unwrap();
7019
    assert_eq!(r.reverted, vec!["keep".to_string()]);
7020
    assert!(!repo.view().unwrap().bookmarks.contains_key("keep"));
7021
    assert!(repo
7022
        .load_state(&repo.bookmark_heads().unwrap())
7023
        .unwrap()
7024
        .contains(&third));
7025
    assert!(repo.op_revert(&created).is_err(), "nothing left to revert");
7026
    let _ = first;
7027
}
7028
7029
/// oxygen#41: with uncommitted work, a status after a snapshot is answered
7030
/// from the status cache while every file is as the snapshot left it, and
7031
/// from a snapshot again as soon as one is not.
7032
#[test]
7033
fn status_with_uncommitted_work_comes_from_the_cache_until_a_file_changes() {
7034
    hermetic();
7035
    let dir = tempfile::tempdir().unwrap();
7036
    let root = dir.path();
7037
    let repo = Repo::init(root).unwrap();
7038
    write(root, "a.txt", b"a\n");
7039
    write(root, "b.txt", b"b\n");
7040
    repo.commit("base", &[]).unwrap();
7041
    assert_eq!(repo.status_by_manifest().unwrap(), Some(vec![]), "clean");
7042
7043
    write(root, "a.txt", b"a\nmore\n");
7044
    assert_eq!(
7045
        repo.status_by_manifest().unwrap(),
7046
        None,
7047
        "no snapshot of the edit yet"
7048
    );
7049
    let snap = repo.snapshot_status("oxy status").unwrap();
7050
    assert_eq!(snap.statuses.len(), 1);
7051
    let cached = repo
7052
        .status_by_manifest()
7053
        .unwrap()
7054
        .expect("answered from the cache");
7055
    assert_eq!(cached.len(), 1);
7056
    assert_eq!(
7057
        (cached[0].path.as_str(), cached[0].status),
7058
        ("a.txt", ChangeStatus::Modified)
7059
    );
7060
7061
    // Any further change sends status back to a snapshot.
7062
    write(root, "a.txt", b"a\nmore\nand more\n");
7063
    assert_eq!(repo.status_by_manifest().unwrap(), None, "edited again");
7064
    repo.snapshot_status("oxy status").unwrap();
7065
    assert!(repo.status_by_manifest().unwrap().is_some());
7066
    write(root, "new.txt", b"n\n");
7067
    assert_eq!(repo.status_by_manifest().unwrap(), None, "a file added");
7068
    fs::remove_file(root.join("new.txt")).unwrap();
7069
    assert!(
7070
        repo.status_by_manifest().unwrap().is_some(),
7071
        "back as it was"
7072
    );
7073
    fs::remove_file(root.join("b.txt")).unwrap();
7074
    assert_eq!(repo.status_by_manifest().unwrap(), None, "a file removed");
7075
    write(root, "b.txt", b"b\n");
7076
7077
    // A commit leaves nothing uncommitted: clean again, no cache needed.
7078
    repo.snapshot_status("oxy status").unwrap();
7079
    repo.commit("more", &[]).unwrap();
7080
    assert_eq!(repo.status_by_manifest().unwrap(), Some(vec![]));
7081
}
7082
7083
/// oxygen#41: while the status cache holds, the working copy's diff is
7084
/// rendered from the stored working-copy change, and says exactly what a
7085
/// snapshot's diff says.
7086
#[test]
7087
fn the_working_copy_diff_from_the_cache_matches_a_snapshot() {
7088
    hermetic();
7089
    let dir = tempfile::tempdir().unwrap();
7090
    let root = dir.path();
7091
    let repo = Repo::init(root).unwrap();
7092
    write(root, "a.txt", b"one\ntwo\nthree\n");
7093
    write(root, "gone.txt", b"bye\n");
7094
    repo.commit("base", &[]).unwrap();
7095
    write(root, "a.txt", b"one\n2\nthree\nfour\n");
7096
    write(root, "new.txt", b"hello\n");
7097
    fs::remove_file(root.join("gone.txt")).unwrap();
7098
    let snap = repo.snapshot_status("oxy status").unwrap();
7099
    let slow = render_change(&snap.wc, &snap.base, &snap.base_snapshot);
7100
    assert!(
7101
        repo.status_by_manifest().unwrap().is_some(),
7102
        "the cache holds"
7103
    );
7104
    let (wc, base, snapshot) = repo.working_copy_with_base().unwrap();
7105
    assert_eq!(render_change(&wc, &base, &snapshot), slow);
7106
    assert_eq!(repo.diff_files(None).unwrap().len(), 3);
7107
}
7108
7109
/// oxygen#41: a manifest written from a walk keeps every directory's time;
7110
/// while none has moved, the check stats the tracked files without listing
7111
/// the tree, and a file added or removed anywhere moves its directory's
7112
/// time, so the tree is listed again.
7113
#[test]
7114
fn the_manifest_check_skips_listing_while_no_directory_changed() {
7115
    hermetic();
7116
    let dir = tempfile::tempdir().unwrap();
7117
    let root = dir.path();
7118
    let repo = Repo::init(root).unwrap();
7119
    write(root, "a.txt", b"a\n");
7120
    write(root, "sub/deep/b.txt", b"b\n");
7121
    repo.commit("base", &[]).unwrap();
7122
    // Out of the racy window: every file and directory a minute old.
7123
    let old = std::time::SystemTime::now() - std::time::Duration::from_secs(60);
7124
    for p in ["a.txt", "sub/deep/b.txt", "sub/deep", "sub", ""] {
7125
        fs::File::open(root.join(p))
7126
            .unwrap()
7127
            .set_modified(old)
7128
            .unwrap();
7129
    }
7130
    repo.snapshot_status("oxy status").unwrap();
7131
    repo.write_manifest(false, false).unwrap();
7132
    let m = repo.read_manifest().unwrap().unwrap().2;
7133
    assert!(m.dirs.iter().any(|(d, _)| d == "sub/deep"), "{:?}", m.dirs);
7134
    assert_eq!(
7135
        repo.disk_differs_by_dirs(&m),
7136
        Some(false),
7137
        "no listing needed"
7138
    );
7139
    assert_eq!(repo.status_by_manifest().unwrap(), Some(vec![]));
7140
7141
    // A same-size edit with a new time: found by its stat.
7142
    write(root, "sub/deep/b.txt", b"c\n");
7143
    assert_eq!(repo.disk_differs_by_dirs(&m), Some(true));
7144
    write(root, "sub/deep/b.txt", b"b\n");
7145
    fs::File::open(root.join("sub/deep/b.txt"))
7146
        .unwrap()
7147
        .set_modified(old)
7148
        .unwrap();
7149
    assert_eq!(repo.disk_differs_by_dirs(&m), Some(false));
7150
7151
    // A new file moves its directory's time: the tree must be listed.
7152
    write(root, "sub/deep/new.txt", b"n\n");
7153
    assert_eq!(repo.disk_differs_by_dirs(&m), None);
7154
    assert_eq!(repo.status_by_manifest().unwrap(), None);
7155
    fs::remove_file(root.join("sub/deep/new.txt")).unwrap();
7156
    // A removed one too.
7157
    fs::remove_file(root.join("a.txt")).unwrap();
7158
    assert_eq!(repo.disk_differs_by_dirs(&m), None);
7159
}
7160
7161
/// oxygen#41: a commit right after a status takes the snapshot the status
7162
/// left (the status cache holds) rather than walking again, and commits
7163
/// exactly what a snapshot would have.
7164
#[test]
7165
fn a_commit_after_a_status_uses_the_cached_snapshot() {
7166
    hermetic();
7167
    let dir = tempfile::tempdir().unwrap();
7168
    let root = dir.path();
7169
    let repo = Repo::init(root).unwrap();
7170
    write(root, "a.txt", b"a\nb\n");
7171
    write(root, ".oxyattributes", b"*.bin binary\n");
7172
    repo.commit("base", &[]).unwrap();
7173
    write(root, "a.txt", b"a\nB\n");
7174
    write(root, "new.txt", b"new\n");
7175
    let snap = repo.snapshot_status("oxy status").unwrap();
7176
    let cached = repo
7177
        .snapshot_from_cache()
7178
        .unwrap()
7179
        .expect("the cache holds");
7180
    assert_eq!(cached.wc_hash, snap.wc_hash);
7181
    assert_eq!(cached.statuses, snap.statuses);
7182
    assert!(
7183
        !cached.attributes.is_empty(),
7184
        "the .oxyattributes file was read"
7185
    );
7186
    let h = repo.commit("edit", &[]).unwrap();
7187
    let c = repo.store().get_change(&h).unwrap();
7188
    assert_eq!(
7189
        c.tree_ops.len() + c.edits.len(),
7190
        snap.wc.tree_ops.len() + snap.wc.edits.len()
7191
    );
7192
    assert_eq!(
7193
        repo.status_by_manifest().unwrap(),
7194
        Some(vec![]),
7195
        "clean after the commit"
7196
    );
7197
    assert_eq!(fs::read(root.join("a.txt")).unwrap(), b"a\nB\n");
7198
}
7199
7200
/// oxygen#41: a clean check that verified racy entries restamps the
7201
/// manifest, so later checks can trust them, and a same-size rewrite
7202
/// straight afterwards is still found: entries within two seconds of the
7203
/// new time stay racy.
7204
#[test]
7205
fn a_verified_clean_check_restamps_the_manifest_safely() {
7206
    hermetic();
7207
    let dir = tempfile::tempdir().unwrap();
7208
    let root = dir.path();
7209
    let repo = Repo::init(root).unwrap();
7210
    write(root, "a.txt", b"one\n");
7211
    repo.commit("one", &[]).unwrap();
7212
    let before = repo.read_manifest().unwrap().unwrap().2.written_ns;
7213
    assert!(repo.clean_by_manifest().unwrap());
7214
    let after = repo.read_manifest().unwrap().unwrap().2.written_ns;
7215
    assert!(after > before, "restamped");
7216
    write(root, "a.txt", b"two\n");
7217
    assert!(
7218
        !repo.clean_by_manifest().unwrap(),
7219
        "a same-size rewrite is still seen"
7220
    );
7221
}
7222
7223
/// oxygen#35: a history-only state keeps no inserted text. It reads a
7224
/// stored insert's text blob only when it builds that file's graph, and
7225
/// builds the same graph a full load does.
7226
#[test]
7227
fn history_only_states_read_text_only_for_the_graphs_they_build() {
7228
    hermetic();
7229
    let dir = tempfile::tempdir().unwrap();
7230
    let root = dir.path();
7231
    let repo = Repo::init(root).unwrap();
7232
    let big: String = (0..3000).map(|i| format!("big line {i}\n")).collect();
7233
    let other: String = (0..3000).map(|i| format!("other line {i}\n")).collect();
7234
    write(root, "big.txt", big.as_bytes());
7235
    write(root, "other.txt", other.as_bytes());
7236
    let h = repo.commit("two large files", &[]).unwrap();
7237
    write(root, "big.txt", format!("{big}one more\n").as_bytes());
7238
    let h2 = repo.commit("append", &[]).unwrap();
7239
7240
    let full = repo.load_state_full(&[h2]).unwrap().materialize();
7241
    let text = |snap: &crate::state::Snapshot, p: &str| match &snap.files[p].content {
7242
        FileContent::Text { bytes, .. } => bytes.clone(),
7243
        other => panic!("{other:?}"),
7244
    };
7245
    // Built on demand, every graph renders as the full load's.
7246
    let mut hist = repo.load_state_history(&[h2]).unwrap();
7247
    let big_node = full.files["big.txt"].node;
7248
    assert!(hist.graph_key(&big_node).is_some(), "not built yet");
7249
    repo.load_all_graphs(&mut hist).unwrap();
7250
    let rendered = hist.materialize();
7251
    for p in ["big.txt", "other.txt"] {
7252
        assert_eq!(text(&rendered, p), text(&full, p), "{p}");
7253
    }
7254
7255
    // Without other.txt's text blob, history still loads and big.txt still
7256
    // builds: nothing read the other text.
7257
    let (_, texts) = repo.store().get_change_lazy(&h).unwrap();
7258
    assert_eq!(texts.len(), 2);
7259
    let content = |r: &ObjectRef| -> Vec<u8> {
7260
        let blob = crate::objects::Blob::decode(&repo.store().get(r).unwrap().1).unwrap();
7261
        blob.chunks
7262
            .iter()
7263
            .flat_map(|c| repo.store().get(c).unwrap().1)
7264
            .collect()
7265
    };
7266
    let other_text = texts
7267
        .iter()
7268
        .filter_map(|t| match t {
7269
            crate::objects::TextRef::Blob(r, _, _) => Some(*r),
7270
            _ => None,
7271
        })
7272
        .find(|r| content(r).windows(12).any(|w| w == b"other line 1"))
7273
        .unwrap();
7274
    repo.store().remove_loose_for_test(&other_text).unwrap();
7275
    let mut hist = repo.load_state_history(&[h2]).unwrap();
7276
    repo.load_graphs_of(&mut hist, &[big_node]).unwrap();
7277
    assert!(repo
7278
        .load_graphs_of(&mut hist, &[full.files["other.txt"].node])
7279
        .is_err());
7280
}
7281
7282
/// oxygen#35: the first status after a commit read and rendered every
7283
/// file (79 s and more than 14 GB on the Linux tree), because the
7284
/// manifest had no graph keys for files the commit added.
7285
#[test]
7286
fn a_commit_leaves_a_manifest_the_next_status_trusts() {
7287
    use std::os::unix::fs::PermissionsExt;
7288
    hermetic();
7289
    let dir = tempfile::tempdir().unwrap();
7290
    let root = dir.path();
7291
    let repo = Repo::init(root).unwrap();
7292
    let files = ["a.txt", "b.txt", "d/c.txt"];
7293
    for p in files {
7294
        write(root, p, format!("{p}\n").as_bytes());
7295
        let old = std::time::SystemTime::now() - std::time::Duration::from_secs(30);
7296
        fs::File::options()
7297
            .write(true)
7298
            .open(root.join(p))
7299
            .unwrap()
7300
            .set_modified(old)
7301
            .unwrap();
7302
    }
7303
    repo.commit("added", &[]).unwrap();
7304
    let (_, _, m) = repo.read_manifest().unwrap().unwrap();
7305
    assert!(
7306
        m.entries.values().all(|e| e.graph.is_some()),
7307
        "keys recorded at commit"
7308
    );
7309
    // Unreadable files prove the next status reads none of them.
7310
    for p in files {
7311
        fs::set_permissions(root.join(p), fs::Permissions::from_mode(0o000)).unwrap();
7312
    }
7313
    let snap = repo.snapshot_status("status").unwrap();
7314
    for p in files {
7315
        fs::set_permissions(root.join(p), fs::Permissions::from_mode(0o644)).unwrap();
7316
    }
7317
    assert!(!snap.changed && snap.statuses.is_empty());
7318
    assert_eq!(snap.base_snapshot.unrendered.len(), files.len());
7319
}
7320
7321
/// oxygen#35: a checkout reads, renders and writes only the files whose
7322
/// graphs differ, and renders the rest a batch at a time.
7323
#[test]
7324
fn checkout_touches_only_what_differs_and_renders_in_batches() {
7325
    use std::os::unix::fs::PermissionsExt;
7326
    hermetic();
7327
    let dir = tempfile::tempdir().unwrap();
7328
    let root = dir.path();
7329
    let origin = root.join("origin");
7330
    let mut repo = Repo::init(&origin).unwrap();
7331
    // More files than one batch holds.
7332
    let n = 2100;
7333
    let old = std::time::SystemTime::now() - std::time::Duration::from_secs(30);
7334
    for i in 0..n {
7335
        let p = format!("f/{i:04}.txt");
7336
        write(&origin, &p, format!("file {i}\n").as_bytes());
7337
        fs::File::options()
7338
            .write(true)
7339
            .open(origin.join(&p))
7340
            .unwrap()
7341
            .set_modified(old)
7342
            .unwrap();
7343
    }
7344
    repo.commit("many", &[]).unwrap();
7345
    repo.bookmark_create("feature", None).unwrap();
7346
    repo.bookmark_switch("feature", false).unwrap();
7347
    write(&origin, "f/0007.txt", b"changed\n");
7348
    repo.commit("one change", &[]).unwrap();
7349
7350
    // Switching back to main must not read the unchanged files.
7351
    for i in 0..n {
7352
        if i != 7 {
7353
            let p = origin.join(format!("f/{i:04}.txt"));
7354
            fs::set_permissions(&p, fs::Permissions::from_mode(0o000)).unwrap();
7355
        }
7356
    }
7357
    let r = repo.bookmark_switch("main", false).unwrap();
7358
    for i in 0..n {
7359
        let p = origin.join(format!("f/{i:04}.txt"));
7360
        fs::set_permissions(&p, fs::Permissions::from_mode(0o644)).unwrap();
7361
    }
7362
    assert_eq!((r.written, r.removed), (1, 0), "{r:?}");
7363
    assert_eq!(fs::read(origin.join("f/0007.txt")).unwrap(), b"file 7\n");
7364
    assert!(repo.snapshot_status("status").unwrap().statuses.is_empty());
7365
7366
    // A clone renders every file, across batches.
7367
    let c = root.join("clone");
7368
    Repo::clone(&origin.to_string_lossy(), &c).unwrap();
7369
    for i in [0, 2047, 2048, n - 1] {
7370
        assert_eq!(
7371
            fs::read(c.join(format!("f/{i:04}.txt"))).unwrap(),
7372
            format!("file {i}\n").as_bytes()
7373
        );
7374
    }
7375
    let cloned = Repo::open(&c).unwrap();
7376
    assert!(cloned
7377
        .snapshot_status("status")
7378
        .unwrap()
7379
        .statuses
7380
        .is_empty());
7381
}
7382
7383
/// A file written just before the manifest (inside the racy window) is
7384
/// checked by its hash: trusted when equal, caught when edited in place
7385
/// with the same size and time.
7386
#[test]
7387
fn a_racy_manifest_entry_is_checked_by_hash() {
7388
    hermetic();
7389
    let dir = tempfile::tempdir().unwrap();
7390
    let root = dir.path();
7391
    let repo = Repo::init(root).unwrap();
7392
    write(root, "a.txt", b"one\n");
7393
    repo.commit("fresh", &[]).unwrap();
7394
    assert!(repo.clean_by_manifest().unwrap(), "fresh but equal");
7395
    let t = fs::metadata(root.join("a.txt"))
7396
        .unwrap()
7397
        .modified()
7398
        .unwrap();
7399
    write(root, "a.txt", b"two\n");
7400
    fs::File::options()
7401
        .write(true)
7402
        .open(root.join("a.txt"))
7403
        .unwrap()
7404
        .set_modified(t)
7405
        .unwrap();
7406
    assert!(
7407
        !repo.clean_by_manifest().unwrap(),
7408
        "same size and time, other bytes"
7409
    );
7410
    assert_eq!(
7411
        statuses(&repo.snapshot_status("status").unwrap()),
7412
        vec![("a.txt".to_string(), ChangeStatus::Modified)]
7413
    );
7414
}
7415
7416
/// A fetch on one machine moves changes as stored, text blobs among the
7417
/// objects; a change whose text blob did not come is refused, not stored.
7418
#[test]
7419
fn a_raw_bundle_without_a_changes_text_is_refused() {
7420
    hermetic();
7421
    let dir = tempfile::tempdir().unwrap();
7422
    let root = dir.path();
7423
    let a = Repo::init(&root.join("a")).unwrap();
7424
    let big: String = (0..3000).map(|i| format!("line {i}\n")).collect();
7425
    write(&root.join("a"), "big.txt", big.as_bytes());
7426
    let h = a.commit("big", &[]).unwrap();
7427
    let bundle = a.bundle_raw_for(&[h], None).unwrap();
7428
    assert_eq!(bundle.raw_changes.len(), 1);
7429
    assert!(bundle.changes.is_empty());
7430
    let b = Repo::init(&root.join("b")).unwrap();
7431
    let mut without = bundle.clone();
7432
    without.objects.retain(|(ty, _)| *ty != ObjectType::Blob);
7433
    let e = b.import_bundle(&without, false).unwrap_err();
7434
    assert!(e.to_string().contains("came without its text blob"), "{e}");
7435
    assert!(!b.store().has(&h));
7436
    assert_eq!(b.import_bundle(&bundle, false).unwrap(), vec![h]);
7437
    assert_eq!(b.store().get_change(&h).unwrap().message, "big");
7438
}
7439
7440
/// oxygen#30 (vscode): a directory deleted in one line of history and made
7441
/// again was a second node for one Git path, so a file moved into it on
7442
/// another line, where the first node still stood, ended up in two places.
7443
/// An import now brings the directory back rather than make a new one.
7444
#[test]
7445
fn git_import_brings_a_directory_back_rather_than_making_a_second() {
7446
    hermetic();
7447
    if std::process::Command::new("git")
7448
        .arg("--version")
7449
        .output()
7450
        .is_err()
7451
    {
7452
        eprintln!("git not installed; skipping");
7453
        return;
7454
    }
7455
    let dir = tempfile::tempdir().unwrap();
7456
    let root = dir.path();
7457
    let g = root.join("src.git");
7458
    fs::create_dir_all(&g).unwrap();
7459
    let git = |args: &[&str]| -> String {
7460
        let out = std::process::Command::new("git")
7461
            .arg("-C")
7462
            .arg(&g)
7463
            .args([
7464
                "-c",
7465
                "user.name=Grace",
7466
                "-c",
7467
                "[email protected]",
7468
                "-c",
7469
                "commit.gpgsign=false",
7470
            ])
7471
            .args(args)
7472
            .output()
7473
            .unwrap();
7474
        assert!(
7475
            out.status.success(),
7476
            "git {args:?}: {}",
7477
            String::from_utf8_lossy(&out.stderr)
7478
        );
7479
        String::from_utf8_lossy(&out.stdout).trim().to_string()
7480
    };
7481
    git(&["init", "-q", "-b", "main"]);
7482
    write(&g, "d/a.txt", b"a\n");
7483
    write(&g, "c/x.txt", b"x\n");
7484
    git(&["add", "."]);
7485
    git(&["commit", "-qm", "base"]);
7486
    // One line: move x into d while d still stands.
7487
    git(&["checkout", "-qb", "side"]);
7488
    git(&["mv", "c/x.txt", "d/x.txt"]);
7489
    git(&["commit", "-qm", "x into d"]);
7490
    // The other: d goes, comes back, and x moves into it too.
7491
    git(&["checkout", "-q", "main"]);
7492
    git(&["rm", "-q", "d/a.txt"]);
7493
    git(&["commit", "-qm", "d goes"]);
7494
    write(&g, "d/b.txt", b"b\n");
7495
    git(&["add", "."]);
7496
    git(&["commit", "-qm", "d comes back"]);
7497
    git(&["mv", "c/x.txt", "d/x.txt"]);
7498
    git(&["commit", "-qm", "x into d again"]);
7499
    git(&["merge", "-q", "--no-edit", "side"]);
7500
7501
    let repo = Repo::init(&root.join("o")).unwrap();
7502
    repo.import_git(&g, "main").unwrap();
7503
    let v = repo.verify_git_import(&g, "main").unwrap();
7504
    assert!(v.mismatches.is_empty(), "{:?}", v.mismatches);
7505
    let st = repo
7506
        .load_state_history(&repo.bookmark_heads().unwrap())
7507
        .unwrap();
7508
    let view = st.tree().view();
7509
    assert!(view.conflicts.is_empty(), "{:?}", view.conflicts);
7510
    // The directory is the one the first commit made.
7511
    // Commits made in one second tie on time: find the first by its message.
7512
    let first = repo
7513
        .log()
7514
        .unwrap()
7515
        .into_iter()
7516
        .find(|e| e.change.message.starts_with("base"))
7517
        .unwrap();
7518
    let base = repo
7519
        .load_state_history(&[first.hash])
7520
        .unwrap()
7521
        .tree()
7522
        .view();
7523
    assert_eq!(view.entries["d"].node, base.entries["d"].node);
7524
}
7525
7526
/// oxygen#30, the rest: a placement left under a directory another line
7527
/// removed is out of sight, so no diff reaches it; the merge that settles
7528
/// where the file is retires it.
7529
#[test]
7530
fn git_import_merge_retires_a_placement_under_a_removed_directory() {
7531
    hermetic();
7532
    if std::process::Command::new("git")
7533
        .arg("--version")
7534
        .output()
7535
        .is_err()
7536
    {
7537
        eprintln!("git not installed; skipping");
7538
        return;
7539
    }
7540
    let dir = tempfile::tempdir().unwrap();
7541
    let root = dir.path();
7542
    let g = root.join("src.git");
7543
    fs::create_dir_all(&g).unwrap();
7544
    let run = |args: &[&str]| {
7545
        std::process::Command::new("git")
7546
            .arg("-C")
7547
            .arg(&g)
7548
            .args([
7549
                "-c",
7550
                "user.name=Grace",
7551
                "-c",
7552
                "[email protected]",
7553
                "-c",
7554
                "commit.gpgsign=false",
7555
            ])
7556
            .args(args)
7557
            .output()
7558
            .unwrap()
7559
    };
7560
    let git = |args: &[&str]| {
7561
        let out = run(args);
7562
        assert!(
7563
            out.status.success(),
7564
            "git {args:?}: {}",
7565
            String::from_utf8_lossy(&out.stderr)
7566
        );
7567
    };
7568
    git(&["init", "-q", "-b", "main"]);
7569
    write(&g, "c/x.txt", b"x\n");
7570
    write(&g, "keep.txt", b"k\n");
7571
    git(&["add", "."]);
7572
    git(&["commit", "-qm", "base"]);
7573
    // One line renames the file within c; the other moves it out of c,
7574
    // which goes.
7575
    git(&["checkout", "-qb", "side"]);
7576
    git(&["mv", "c/x.txt", "c/y.txt"]);
7577
    git(&["commit", "-qm", "rename within c"]);
7578
    git(&["checkout", "-q", "main"]);
7579
    fs::create_dir_all(g.join("n")).unwrap();
7580
    git(&["mv", "c/x.txt", "n/x.txt"]);
7581
    git(&["commit", "-qm", "move out of c"]);
7582
    // Git cannot merge the two renames; the merge keeps n/x.txt.
7583
    let _ = run(&["merge", "-q", "side"]);
7584
    let _ = run(&[
7585
        "rm",
7586
        "-q",
7587
        "--cached",
7588
        "--ignore-unmatch",
7589
        "c/y.txt",
7590
        "c/x.txt",
7591
    ]);
7592
    let _ = std::fs::remove_dir_all(g.join("c"));
7593
    write(&g, "n/x.txt", b"x\n");
7594
    git(&["add", "-A"]);
7595
    git(&["commit", "-qm", "merge: keep n/x.txt"]);
7596
7597
    let repo = Repo::init(&root.join("o")).unwrap();
7598
    repo.import_git(&g, "main").unwrap();
7599
    let v = repo.verify_git_import(&g, "main").unwrap();
7600
    assert!(v.mismatches.is_empty(), "{:?}", v.mismatches);
7601
    let st = repo
7602
        .load_state_history(&repo.bookmark_heads().unwrap())
7603
        .unwrap();
7604
    let view = st.tree().view();
7605
    assert!(view.conflicts.is_empty(), "{:?}", view.conflicts);
7606
    assert!(view.entries.contains_key("n/x.txt"));
7607
}
7608
7609
/// oxygen#30, orphans: a file added on one line into a directory the other
7610
/// line removed is placed where the tree cannot show it; Git's merge keeps
7611
/// the file, and the import's merge leaves exactly one of it.
7612
#[test]
7613
fn git_import_merge_leaves_no_orphan_behind() {
7614
    hermetic();
7615
    if std::process::Command::new("git")
7616
        .arg("--version")
7617
        .output()
7618
        .is_err()
7619
    {
7620
        eprintln!("git not installed; skipping");
7621
        return;
7622
    }
7623
    let dir = tempfile::tempdir().unwrap();
7624
    let root = dir.path();
7625
    let g = root.join("src.git");
7626
    fs::create_dir_all(&g).unwrap();
7627
    let git = |args: &[&str]| {
7628
        let out = std::process::Command::new("git")
7629
            .arg("-C")
7630
            .arg(&g)
7631
            .args([
7632
                "-c",
7633
                "user.name=Grace",
7634
                "-c",
7635
                "[email protected]",
7636
                "-c",
7637
                "commit.gpgsign=false",
7638
            ])
7639
            .args(args)
7640
            .output()
7641
            .unwrap();
7642
        assert!(
7643
            out.status.success(),
7644
            "git {args:?}: {}",
7645
            String::from_utf8_lossy(&out.stderr)
7646
        );
7647
    };
7648
    git(&["init", "-q", "-b", "main"]);
7649
    write(&g, "d/f.txt", b"f\n");
7650
    write(&g, "keep.txt", b"k\n");
7651
    git(&["add", "."]);
7652
    git(&["commit", "-qm", "base"]);
7653
    git(&["checkout", "-qb", "side"]);
7654
    write(&g, "d/new.txt", b"new\n");
7655
    git(&["add", "."]);
7656
    git(&["commit", "-qm", "add into d"]);
7657
    git(&["checkout", "-q", "main"]);
7658
    git(&["rm", "-q", "d/f.txt"]);
7659
    git(&["commit", "-qm", "d goes"]);
7660
    git(&["merge", "-q", "--no-edit", "side"]);
7661
7662
    let repo = Repo::init(&root.join("o")).unwrap();
7663
    repo.import_git(&g, "main").unwrap();
7664
    let v = repo.verify_git_import(&g, "main").unwrap();
7665
    assert!(v.mismatches.is_empty(), "{:?}", v.mismatches);
7666
    let st = repo
7667
        .load_state_history(&repo.bookmark_heads().unwrap())
7668
        .unwrap();
7669
    let view = st.tree().view();
7670
    assert!(view.conflicts.is_empty(), "{:?}", view.conflicts);
7671
    assert!(view.entries.contains_key("d/new.txt"));
7672
}
7673
7674
/// fsck checks a change's text as the blobs it is stored in, without
7675
/// decoding it: a missing text blob is an error named for the change.
7676
#[test]
7677
fn fsck_names_a_missing_text_blob() {
7678
    hermetic();
7679
    let dir = tempfile::tempdir().unwrap();
7680
    let root = dir.path();
7681
    let repo = Repo::init(root).unwrap();
7682
    let big: String = (0..3000).map(|i| format!("line {i}\n")).collect();
7683
    write(root, "big.txt", big.as_bytes());
7684
    let h = repo.commit("big", &[]).unwrap();
7685
    assert_eq!(repo.fsck().unwrap().errors(), 0);
7686
    let (_, texts) = repo.store().get_change_lazy(&h).unwrap();
7687
    let Some(crate::objects::TextRef::Blob(b, _, _)) = texts.first().copied() else {
7688
        panic!("a stored text")
7689
    };
7690
    repo.store().remove_loose_for_test(&b).unwrap();
7691
    let rep = repo.fsck().unwrap();
7692
    assert!(rep.errors() > 0);
7693
    assert!(
7694
        rep.problems.iter().any(|p| p.what.contains(&h.short(12))),
7695
        "{:?}",
7696
        rep.problems
7697
    );
7698
}
7699
7700
/// oxygen#32: a subrepo on the same hub as one of the parent's remotes is
7701
/// reached with that remote's token and CA (a private subrepo then clones
7702
/// for anyone who can read the parent); another hub gets none of them.
7703
#[test]
7704
fn a_subrepo_on_the_parents_hub_borrows_its_credentials() {
7705
    hermetic();
7706
    let dir = tempfile::tempdir().unwrap();
7707
    let mut repo = Repo::init(dir.path()).unwrap();
7708
    repo.config
7709
        .set(
7710
            "remote.origin.url",
7711
            "https://Hub.example:7343/doomsdayone/metalgear",
7712
        )
7713
        .unwrap();
7714
    repo.config.set("remote.origin.token", "secret").unwrap();
7715
    repo.config
7716
        .set("remote.origin.ca", "/tmp/hub-ca.pem")
7717
        .unwrap();
7718
    let same = repo.credentials_for("https://hub.example:7343/doomsdayone/rstar-api");
7719
    assert_eq!(same.token.as_deref(), Some("secret"));
7720
    assert_eq!(same.ca.as_deref(), Some(Path::new("/tmp/hub-ca.pem")));
7721
    for other in [
7722
        "https://elsewhere.example:7343/doomsdayone/rstar-api",
7723
        "https://hub.example/doomsdayone/rstar-api",
7724
        "http://hub.example:7343/doomsdayone/rstar-api",
7725
    ] {
7726
        let o = repo.credentials_for(other);
7727
        assert_ne!(o.token.as_deref(), Some("secret"), "{other}");
7728
    }
7729
}
7730
7731
/// oxygen#47: a remote with no token of its own uses the user's credential
7732
/// store for its hub, and a nested checkout finds its parent's remote
7733
/// token there instead of keeping a copy.
7734
#[test]
7735
fn remotes_use_the_credential_store_and_the_enclosing_checkout() {
7736
    hermetic();
7737
    let home = tempfile::tempdir().unwrap();
7738
    let dir = tempfile::tempdir().unwrap();
7739
    let mut parent = Repo::init(dir.path()).unwrap().with_home(home.path());
7740
    parent
7741
        .config
7742
        .set("remote.origin.url", "https://hub.example/o/parent")
7743
        .unwrap();
7744
    parent.save_config().unwrap();
7745
    assert_eq!(parent.remote_options("origin").token, None);
7746
    crate::credentials::Credentials::at(home.path())
7747
        .save("https://hub.example", "stored", Some("andy"), None)
7748
        .unwrap();
7749
    assert_eq!(
7750
        parent.remote_options("origin").token.as_deref(),
7751
        Some("stored")
7752
    );
7753
7754
    let empty_home = tempfile::tempdir().unwrap();
7755
    let nested = dir.path().join("deps").join("child");
7756
    let mut child = Repo::init(&nested).unwrap().with_home(empty_home.path());
7757
    child
7758
        .config
7759
        .set("remote.origin.url", "https://hub.example/o/child")
7760
        .unwrap();
7761
    child.save_config().unwrap();
7762
    assert_eq!(child.remote_options("origin").token, None);
7763
    parent
7764
        .config
7765
        .set("remote.origin.token", "checkout")
7766
        .unwrap();
7767
    parent.save_config().unwrap();
7768
    assert_eq!(
7769
        child.remote_options("origin").token.as_deref(),
7770
        Some("checkout")
7771
    );
7772
    // Another hub's checkout token is not borrowed.
7773
    child
7774
        .config
7775
        .set("remote.origin.url", "https://other.example/o/child")
7776
        .unwrap();
7777
    assert_eq!(child.remote_options("origin").token, None);
7778
}
7779
7780
#[test]
7781
fn the_metadata_cache_survives_a_torn_tail() {
7782
    hermetic();
7783
    let dir = tempfile::tempdir().unwrap();
7784
    let root = dir.path();
7785
    let repo = Repo::init(root).unwrap();
7786
    write(root, "a.txt", b"1\n");
7787
    let h = repo.commit("first", &[]).unwrap();
7788
    let meta = repo.store().get_change_meta(&h).unwrap();
7789
    let cache = repo.store().dir().join("metas");
7790
    let len = fs::metadata(&cache).unwrap().len();
7791
    assert!(len > 0, "a change read is cached");
7792
    // A torn record at the end: the cache reads up to it and cuts it off.
7793
    fs::OpenOptions::new()
7794
        .append(true)
7795
        .open(&cache)
7796
        .unwrap()
7797
        .write_all(&[7; 20])
7798
        .unwrap();
7799
    let again = Repo::open(root).unwrap();
7800
    assert_eq!(again.store().get_change_meta(&h).unwrap(), meta);
7801
    assert_eq!(fs::metadata(&cache).unwrap().len(), len);
7802
}
7803
7804
#[test]
7805
fn a_manifest_that_does_not_check_reads_as_none() {
7806
    hermetic();
7807
    let dir = tempfile::tempdir().unwrap();
7808
    let root = dir.path();
7809
    let repo = Repo::init(root).unwrap();
7810
    write(root, "a.txt", b"1\n");
7811
    repo.commit("first", &[]).unwrap();
7812
    let path = repo.manifest_path();
7813
    let mut bytes = fs::read(&path).unwrap();
7814
    assert!(Repo::open(root).unwrap().read_manifest().unwrap().is_some());
7815
    let last = bytes.len() - 1;
7816
    bytes[last] ^= 1;
7817
    fs::write(&path, &bytes).unwrap();
7818
    assert!(Repo::open(root).unwrap().read_manifest().unwrap().is_none());
7819
    // The next status reads the files and writes it again.
7820
    let again = Repo::open(root).unwrap();
7821
    assert!(!again.snapshot("status").unwrap().changed);
7822
    assert!(again.read_manifest().unwrap().is_some());
7823
}
7824
7825
#[test]
7826
fn a_commit_leaves_a_manifest_that_proves_the_working_copy_clean() {
7827
    hermetic();
7828
    let dir = tempfile::tempdir().unwrap();
7829
    let root = dir.path();
7830
    let repo = Repo::init(root).unwrap();
7831
    write(root, "a.txt", b"1\n");
7832
    write(root, "b.txt", b"2\n");
7833
    // b.txt outside the racy window, so snapshots take it as unchanged.
7834
    let old = std::time::SystemTime::now() - std::time::Duration::from_secs(60);
7835
    fs::File::options()
7836
        .write(true)
7837
        .open(root.join("b.txt"))
7838
        .unwrap()
7839
        .set_modified(old)
7840
        .unwrap();
7841
    repo.commit("first", &[]).unwrap();
7842
    assert!(repo.clean_by_manifest().unwrap(), "after the first commit");
7843
    repo.snapshot_status("status").unwrap();
7844
    write(root, "a.txt", b"1\n2\n");
7845
    repo.commit("second", &[]).unwrap();
7846
    assert!(
7847
        repo.clean_by_manifest().unwrap(),
7848
        "after a commit of one file"
7849
    );
7850
    // Edited, seen by a status, edited again, then committed: the status
7851
    // left the first edit's stat, which the commit must not keep.
7852
    write(root, "a.txt", b"1\n2\n3\n");
7853
    repo.snapshot_status("status").unwrap();
7854
    write(root, "a.txt", b"1\n2\n3\n4\n5\n");
7855
    repo.commit("third", &[]).unwrap();
7856
    assert!(
7857
        repo.clean_by_manifest().unwrap(),
7858
        "after an edit a status saw"
7859
    );
7860
}
7861
7862
#[test]
7863
fn a_conflicted_rebase_can_be_resolved_in_the_working_copy() {
7864
    hermetic();
7865
    let dir = tempfile::tempdir().unwrap();
7866
    let root = dir.path();
7867
    let mut repo = Repo::init(root).unwrap().with_home(root.join("home"));
7868
    write(root, "a.txt", b"1\n2\n");
7869
    let a = repo.commit("A", &[]).unwrap();
7870
    repo.bookmark_create("develop", Some(&[a])).unwrap();
7871
    write(root, "a.txt", b"1\nX\n");
7872
    let c = repo.commit("C: 2 to X", &[]).unwrap();
7873
    repo.bookmark_switch("develop", false).unwrap();
7874
    write(root, "a.txt", b"1\nY\n");
7875
    let d = repo.commit("D: 2 to Y", &[]).unwrap();
7876
    repo.bookmark_switch("main", false).unwrap();
7877
7878
    let err = repo.rebase(&c, &[d]).unwrap_err();
7879
    assert!(matches!(err, RepoError::Conflicted(_)), "{err}");
7880
    let r = repo.rebase_into_working_copy(&c, &[d]).unwrap();
7881
    assert!(r.changed && r.checked_out);
7882
    let snap = repo.snapshot_status("status").unwrap();
7883
    assert!(
7884
        snap.base_snapshot.is_conflicted(),
7885
        "the conflict is in the working copy"
7886
    );
7887
    let text = fs::read_to_string(root.join("a.txt")).unwrap();
7888
    assert!(text.contains('X') && text.contains('Y'), "{text}");
7889
7890
    write(root, "a.txt", b"1\nXY\n");
7891
    repo.commit("Resolve", &[]).unwrap();
7892
    let st = repo.load_state(&repo.bookmark_heads().unwrap()).unwrap();
7893
    assert!(st.contains(&c) && st.contains(&d));
7894
    let files = st.materialize().files;
7895
    assert!(!files["a.txt"].is_conflicted());
7896
    assert!(
7897
        matches!(&files["a.txt"].content, FileContent::Text { bytes, .. } if bytes == b"1\nXY\n")
7898
    );
7899
7900
    // A change the current bookmark does not hold is refused.
7901
    repo.bookmark_switch("develop", false).unwrap();
7902
    write(root, "b.txt", b"b\n");
7903
    let e = repo.commit("E", &[]).unwrap();
7904
    repo.bookmark_switch("main", false).unwrap();
7905
    let err = repo.rebase_into_working_copy(&e, &[a]).unwrap_err();
7906
    assert!(
7907
        err.to_string().contains("not on the current bookmark"),
7908
        "{err}"
7909
    );
7910
}
7911
7912
#[test]
7913
fn an_ignore_rule_drops_an_added_file_but_not_a_tracked_one() {
7914
    hermetic();
7915
    let dir = tempfile::tempdir().unwrap();
7916
    let root = dir.path();
7917
    let repo = Repo::init(root).unwrap();
7918
    write(root, "a.txt", b"a\n");
7919
    write(root, "kept.log", b"tracked\n");
7920
    repo.commit("first", &[]).unwrap();
7921
    write(root, "build.log", b"made\n");
7922
    let snap = repo.snapshot_status("status").unwrap();
7923
    assert!(snap.statuses.iter().any(|s| s.path == "build.log"));
7924
    // A rule written afterwards leaves the added file out again, while the
7925
    // committed one stays tracked.
7926
    write(root, ".gitignore", b"*.log\n");
7927
    let snap = repo.snapshot_status("status").unwrap();
7928
    let paths: Vec<&str> = snap.statuses.iter().map(|s| s.path.as_str()).collect();
7929
    assert_eq!(paths, vec![".gitignore"], "{paths:?}");
7930
    write(root, "kept.log", b"tracked, edited\n");
7931
    let snap = repo.snapshot_status("status").unwrap();
7932
    assert!(snap.statuses.iter().any(|s| s.path == "kept.log"));
7933
}
7934
7935
#[test]
7936
fn shed_graphs_come_back_the_same() {
7937
    hermetic();
7938
    let dir = tempfile::tempdir().unwrap();
7939
    let root = dir.path();
7940
    let repo = Repo::init(root).unwrap();
7941
    write(root, "a.txt", b"1\n2\n3\n");
7942
    write(root, "b.txt", b"x\n");
7943
    repo.commit("first", &[]).unwrap();
7944
    write(root, "a.txt", b"1\ntwo\n3\n4\n");
7945
    repo.commit("second", &[]).unwrap();
7946
    let heads = repo.bookmark_heads().unwrap();
7947
    let mut st = repo.load_state_history(&heads).unwrap();
7948
    let view = st.tree().view();
7949
    let nodes: Vec<NodeId> = ["a.txt", "b.txt"]
7950
        .iter()
7951
        .map(|p| view.entries[*p].node)
7952
        .collect();
7953
    repo.load_graphs_of(&mut st, &nodes).unwrap();
7954
    let before: Vec<Vec<u8>> = nodes.iter().map(|n| st.render_file(n).0).collect();
7955
    assert_eq!(st.built_count(), 2);
7956
    let shed = st.shed_graphs(|b| repo.store_blob(b)).unwrap();
7957
    assert_eq!((shed, st.built_count()), (2, 0));
7958
    // A later change applies on top of the shed history.
7959
    write(root, "a.txt", b"1\ntwo\n3\n4\n5\n");
7960
    let h3 = repo.commit("third", &[]).unwrap();
7961
    let (skeleton, texts) = repo.store().get_change_lazy(&h3).unwrap();
7962
    st.add_known(h3, skeleton, texts);
7963
    repo.load_graphs_of(&mut st, &nodes).unwrap();
7964
    let after: Vec<Vec<u8>> = nodes.iter().map(|n| st.render_file(n).0).collect();
7965
    assert_eq!(after[1], before[1]);
7966
    assert_eq!(after[0], b"1\ntwo\n3\n4\n5\n");
7967
}
7968
7969
#[test]
7970
fn many_edited_files_diff_in_parallel() {
7971
    // Enough edited files that the builder diffs them in parallel; the
7972
    // commit must hold exactly what is on disk, and a second snapshot
7973
    // must find nothing left to commit.
7974
    hermetic();
7975
    let dir = tempfile::tempdir().unwrap();
7976
    let root = dir.path();
7977
    let repo = Repo::init(root).unwrap();
7978
    let text = |i: usize, round: usize| {
7979
        let mut s = String::new();
7980
        for line in 0..50 {
7981
            if round > 0 && line % 7 == i % 7 {
7982
                s.push_str(&format!("edited {round} {i} {line}\n"));
7983
            } else {
7984
                s.push_str(&format!("file {i} line {line}\n"));
7985
            }
7986
        }
7987
        if round > 0 && i.is_multiple_of(3) {
7988
            s.push_str("appended\n");
7989
        }
7990
        s
7991
    };
7992
    for i in 0..40 {
7993
        write(root, &format!("d/f{i}.txt"), text(i, 0).as_bytes());
7994
    }
7995
    repo.commit("first", &[]).unwrap();
7996
    for i in 0..40 {
7997
        write(root, &format!("d/f{i}.txt"), text(i, 1).as_bytes());
7998
    }
7999
    let h = repo.commit("edit every file", &[]).unwrap();
8000
    let snap = repo.load_state(&[h]).unwrap().materialize();
8001
    for i in 0..40 {
8002
        let want = text(i, 1);
8003
        assert!(
8004
            matches!(&snap.files[&format!("d/f{i}.txt")].content, FileContent::Text { bytes, .. } if bytes == want.as_bytes()),
8005
            "d/f{i}.txt as committed"
8006
        );
8007
    }
8008
    assert!(
8009
        repo.commit("nothing", &[]).is_err(),
8010
        "nothing left to commit"
8011
    );
8012
}
8013
8014
/// oxygen#56: after a fetch, how a bookmark stands against its remote copy
8015
/// is known (fetch printed "up to date" while main was behind), a change
8016
/// only fetched resolves and says where it is, and a checkout whose only
8017
/// remote is not `origin` uses that one.
8018
#[test]
8019
fn a_fetched_change_shows_as_behind_and_resolves() {
8020
    hermetic();
8021
    let dir = tempfile::tempdir().unwrap();
8022
    let root = dir.path();
8023
    let origin = Repo::init(&root.join("origin")).unwrap();
8024
    drop(origin);
8025
    let url = root.join("origin").to_string_lossy().to_string();
8026
    let a = Repo::clone(&url, &root.join("a"))
8027
        .unwrap()
8028
        .with_home(root.join("home-a"));
8029
    write(&root.join("a"), "f.txt", b"one\n");
8030
    a.commit("one", &[]).unwrap();
8031
    a.push("origin", false).unwrap();
8032
    let b = Repo::clone(&url, &root.join("b"))
8033
        .unwrap()
8034
        .with_home(root.join("home-b"));
8035
    assert_eq!(b.tracking("origin", "main").unwrap(), Some((0, 0)));
8036
8037
    write(&root.join("a"), "f.txt", b"one\ntwo\n");
8038
    let h2 = a.commit("two", &[]).unwrap();
8039
    a.push("origin", false).unwrap();
8040
    b.fetch("origin").unwrap();
8041
    // Fetched, not pulled: one behind, the change found and placed.
8042
    assert_eq!(b.tracking("origin", "main").unwrap(), Some((0, 1)));
8043
    assert_eq!(b.tracking("origin", "nope").unwrap(), None);
8044
    assert_eq!(
8045
        b.resolve_change(&format!("#{}", &h2.to_hex()[..12]))
8046
            .unwrap(),
8047
        h2
8048
    );
8049
    assert_eq!(
8050
        b.remote_only_location(&h2).unwrap().as_deref(),
8051
        Some("origin/main")
8052
    );
8053
    // Fetching again changes nothing: still behind, which is what the
8054
    // CLI now says rather than "up to date".
8055
    b.fetch("origin").unwrap();
8056
    assert_eq!(b.tracking("origin", "main").unwrap(), Some((0, 1)));
8057
    b.pull("origin").unwrap();
8058
    assert_eq!(b.tracking("origin", "main").unwrap(), Some((0, 0)));
8059
    assert_eq!(b.remote_only_location(&h2).unwrap(), None);
8060
8061
    // One remote, not called origin: it is the default.
8062
    let mut c = Repo::init(&root.join("c")).unwrap();
8063
    assert_eq!(c.default_remote(), "origin");
8064
    c.config.set("remote.earth.url", &url).unwrap();
8065
    assert_eq!(c.default_remote(), "earth");
8066
    c.config.set("remote.origin.url", &url).unwrap();
8067
    assert_eq!(c.default_remote(), "origin");
8068
}
8069
8070
/// oxygen#57: a clone from a relative local path records the remote as an
8071
/// absolute path, so fetch still finds it from inside the clone.
8072
#[test]
8073
fn a_clone_from_a_relative_path_records_it_absolute() {
8074
    hermetic();
8075
    let dir = tempfile::tempdir().unwrap();
8076
    let root = dir.path();
8077
    Repo::init(&root.join("origin")).unwrap();
8078
    let rel = crate::protocol::stored_url("relative/repo");
8079
    assert!(std::path::Path::new(&rel).is_absolute(), "{rel}");
8080
    assert_eq!(
8081
        crate::protocol::stored_url("https://hub.example/o/n"),
8082
        "https://hub.example/o/n"
8083
    );
8084
    assert!(crate::protocol::stored_url("file://x").starts_with("file:///"));
8085
    assert!(crate::protocol::stored_url("dir://x").starts_with("dir:///"));
8086
    // A bucket is kept as written: it is not a path.
8087
    assert_eq!(
8088
        crate::protocol::stored_url("s3://bucket/prefix?profile=p"),
8089
        "s3://bucket/prefix?profile=p"
8090
    );
8091
    let url = root.join("origin").to_string_lossy().to_string();
8092
    let b = Repo::clone(&url, &root.join("b")).unwrap();
8093
    assert_eq!(b.config.remotes["origin"], url);
8094
    b.fetch("origin").unwrap();
8095
}
8096
8097
/// oxygen#60 and #61: a workspace added on a bookmark is on that bookmark,
8098
/// and gets its subrepos at their pins from this workspace's copies, with
8099
/// their remotes pointing where the subrepos come from.
8100
#[test]
8101
fn a_workspace_added_on_a_bookmark_is_on_it_with_its_subrepos() {
8102
    hermetic();
8103
    let dir = tempfile::tempdir().unwrap();
8104
    let root = dir.path();
8105
    Repo::init(&root.join("lib-origin")).unwrap();
8106
    let lib_url = root.join("lib-origin").to_string_lossy().to_string();
8107
    let lib = Repo::clone(&lib_url, &root.join("lib"))
8108
        .unwrap()
8109
        .with_home(root.join("home"));
8110
    write(&root.join("lib"), "lib.txt", b"v1\n");
8111
    let l1 = lib.commit("lib v1", &[]).unwrap();
8112
    assert!(lib.push("origin", false).unwrap()[0].ok);
8113
8114
    let app_dir = root.join("app");
8115
    let app = Repo::init(&app_dir).unwrap().with_home(root.join("home"));
8116
    write(&app_dir, "main.txt", b"app\n");
8117
    app.submodule_add(&lib_url, "libs/lib", None).unwrap();
8118
    app.commit("app with lib", &[]).unwrap();
8119
    // A second bookmark, and the main workspace on another.
8120
    app.bookmark_create("develop", None).unwrap();
8121
    app.bookmark_create("feature", None).unwrap();
8122
    let mut app = app;
8123
    app.bookmark_switch("feature", false).unwrap();
8124
    assert_eq!(app.config.bookmark, "feature");
8125
8126
    // The library's origin goes away: the subrepo must come from here.
8127
    std::fs::rename(root.join("lib-origin"), root.join("lib-origin-gone")).unwrap();
8128
    let heads = app.resolve_heads("develop").unwrap();
8129
    let ws = app
8130
        .workspace_add_on(&root.join("ws"), Some(&heads), Some("develop"))
8131
        .unwrap();
8132
    assert_eq!(
8133
        ws.config.bookmark, "develop",
8134
        "the new workspace is on develop"
8135
    );
8136
    assert_eq!(
8137
        app.config.bookmark, "feature",
8138
        "and this one stays on its own"
8139
    );
8140
    let sub = Repo::open(&root.join("ws/libs/lib")).unwrap();
8141
    assert_eq!(
8142
        sub.config.remotes["origin"], lib_url,
8143
        "its origin is the subrepo's URL"
8144
    );
8145
    assert_eq!(sub.bookmark_heads().unwrap(), vec![l1], "at its pin");
8146
    assert_eq!(
8147
        std::fs::read(root.join("ws/libs/lib/lib.txt")).unwrap(),
8148
        b"v1\n"
8149
    );
8150
}
8151
8152
/// Revsets (docs/revset_query_language.md): symbols, relations, set
8153
/// operators and the predicates, over a small graph with two heads and
8154
/// a rename.
8155
#[test]
8156
fn revsets_select_changes_by_relation_author_text_date_and_path() {
8157
    hermetic();
8158
    let dir = tempfile::tempdir().unwrap();
8159
    let root = dir.path();
8160
    let mut repo = Repo::init(root).unwrap().with_home(root.join("home"));
8161
    repo.create_identity("Ada", "[email protected]", IdentityScope::User)
8162
        .unwrap();
8163
    write(root, "src/a.rs", b"one\n");
8164
    let a = repo.commit("first: add a", &[]).unwrap();
8165
    write(root, "src/a.rs", b"one\ntwo\n");
8166
    let b = repo.commit("second: grow a", &[]).unwrap();
8167
    // A second head, independent of b: a new file on top of a.
8168
    repo.checkout(&[a], false, "checkout a").unwrap();
8169
    write(root, "docs/notes.md", b"notes\n");
8170
    let c = repo.commit("third: notes", &[]).unwrap();
8171
    // Back to both heads, then rename a.rs: the node keeps its identity.
8172
    repo.checkout(&repo.bookmark_heads().unwrap(), false, "checkout main")
8173
        .unwrap();
8174
    fs::remove_file(root.join("src/a.rs")).unwrap();
8175
    write(root, "src/z.rs", b"one\ntwo\n");
8176
    let d = repo.commit("fourth: rename a to z", &[]).unwrap();
8177
    let wc = repo.working_copy().unwrap().0;
8178
    // A saved revset is checked when set.
8179
    repo.set_user_config("revset.mine", "author(me) & ::main")
8180
        .unwrap();
8181
    assert!(repo.set_user_config("revset.bad", "a &").is_err());
8182
    let set = |src: &str| -> Vec<ChangeHash> {
8183
        let mut v = repo.revset(src).unwrap().hashes;
8184
        v.sort();
8185
        v
8186
    };
8187
    let sorted = |hs: &[ChangeHash]| -> Vec<ChangeHash> {
8188
        let mut v = hs.to_vec();
8189
        v.sort();
8190
        v
8191
    };
8192
8193
    // Changes commute: a new file depends on nothing and the rename on the
8194
    // file's creation, so the graph is a, b->a, d->a, c, and the working
8195
    // copy on the three heads b, c, d.
8196
    let heads = sorted(&repo.bookmark_heads().unwrap());
8197
    let meta = |h: &ChangeHash| repo.store().get_change_meta(h).unwrap();
8198
    assert!(heads.contains(&d) && heads.contains(&c));
8199
    // Symbols and closures.
8200
    assert_eq!(set("main"), heads);
8201
    assert_eq!(set("::main"), sorted(&[a, b, c, d]));
8202
    assert_eq!(set("@"), vec![wc]);
8203
    assert_eq!(set("::@"), sorted(&[a, b, c, d, wc]));
8204
    assert_eq!(set(&format!("::#{}", b.short(12))), sorted(&[a, b]));
8205
    assert_eq!(set(&format!("#{}::", a.short(12))), sorted(&[a, b, d, wc]));
8206
    assert_eq!(
8207
        set(&format!("#{}::#{}", a.short(12), b.short(12))),
8208
        sorted(&[a, b])
8209
    );
8210
    // Ranges: what main has beyond b, and `..` forms.
8211
    assert_eq!(set(&format!("#{}..main", b.short(12))), sorted(&[c, d]));
8212
    assert_eq!(set(&format!("#{}..", c.short(12))), sorted(&[a, b, d, wc]));
8213
    assert_eq!(set("..main"), sorted(&[a, b, c, d]));
8214
    // Operators and precedence: ~ binds tighter than &, & than |.
8215
    assert_eq!(
8216
        set(&format!("::main ~ #{}", d.short(12))),
8217
        sorted(&[a, b, c])
8218
    );
8219
    assert_eq!(
8220
        set(&format!("::main & #{} | #{}", b.short(12), c.short(12))),
8221
        sorted(&[b, c])
8222
    );
8223
    assert_eq!(set("all() ~ ::main"), vec![wc]);
8224
    // Relations.
8225
    let mut head_deps: Vec<ChangeHash> = heads.iter().flat_map(|h| meta(h).deps).collect();
8226
    head_deps.sort();
8227
    head_deps.dedup();
8228
    assert_eq!(set("deps(main)"), head_deps);
8229
    let on_a: Vec<ChangeHash> = [b, c, d]
8230
        .into_iter()
8231
        .filter(|h| meta(h).deps.contains(&a))
8232
        .collect();
8233
    assert_eq!(set(&format!("dependents(#{})", a.short(12))), sorted(&on_a));
8234
    assert_eq!(set("heads(::main)"), heads);
8235
    assert_eq!(set("roots(::main)"), sorted(&[a, c]));
8236
    assert_eq!(
8237
        set(&format!(
8238
            "heads(#{} | #{} | #{})",
8239
            a.short(12),
8240
            b.short(12),
8241
            c.short(12)
8242
        )),
8243
        sorted(&[b, c])
8244
    );
8245
    assert_eq!(set("latest(::main, 1)"), vec![d]);
8246
    assert_eq!(set("kind(working-copy)"), vec![wc]);
8247
    assert_eq!(set("none()"), vec![]);
8248
    // Predicates: author by name, email, key prefix and `me`.
8249
    let key = repo.config.author_key.unwrap();
8250
    assert_eq!(set("author(ada) & ::main"), sorted(&[a, b, c, d]));
8251
    assert_eq!(set("author(\"[email protected]\") & ::main").len(), 4);
8252
    assert_eq!(set(&format!("author({}) & ::main", key.short(12))).len(), 4);
8253
    assert_eq!(set("author(me) & ::main").len(), 4);
8254
    assert_eq!(set("author(nobody)"), vec![]);
8255
    assert_eq!(set("description(notes)"), vec![c]);
8256
    assert_eq!(set("description(\"rename a\")"), vec![d]);
8257
    assert_eq!(set("date(-1h..) & ::main").len(), 4);
8258
    assert_eq!(set("date(..2000-01-01)"), vec![]);
8259
    // touches follows the node through the rename, in the current state.
8260
    assert_eq!(set("touches(\"src/z.rs\")"), sorted(&[a, b, d]));
8261
    assert_eq!(set("touches(\"src/**\") & ::main"), sorted(&[a, b, d]));
8262
    assert_eq!(set("touches(\"docs/*\")"), vec![c]);
8263
    assert_eq!(set("touches(\"nothing/*\")"), vec![]);
8264
    // Newest first in the result order.
8265
    assert_eq!(repo.revset("::main").unwrap().hashes[0], d);
8266
    // The saved revset, and errors that say what is wrong.
8267
    assert_eq!(set("mine()").len(), 4);
8268
    let e = repo.revset("nosuch()").unwrap_err().to_string();
8269
    assert!(e.contains("unknown function nosuch()"), "{e}");
8270
    let e = repo.revset("main &").unwrap_err().to_string();
8271
    assert!(e.contains("at character"), "{e}");
8272
    let e = repo.revset("zzzz").unwrap_err().to_string();
8273
    assert!(e.contains("no change matches"), "{e}");
8274
    let e = repo
8275
        .revset_with_budget("::main", std::time::Duration::ZERO)
8276
        .unwrap_err()
8277
        .to_string();
8278
    assert!(e.contains("budget"), "{e}");
8279
    // The log entries carry the bookmark's heads and the working copy.
8280
    let entries = repo.log_revset("::@").unwrap();
8281
    assert!(entries[0].is_working_copy && entries.iter().any(|e| e.is_head && e.hash == d));
8282
    // Trust predicates (§2.4): nothing is signed yet (core.sign = seal, no
8283
    // push); then a signed change, a tag, and a revocation.
8284
    assert_eq!(set("unsigned() & ::main"), sorted(&[a, b, c, d]));
8285
    assert_eq!(set("signed_by(me)"), vec![]);
8286
    repo.sign_change(&d).unwrap();
8287
    assert_eq!(set("signed_by(me)"), vec![d]);
8288
    assert_eq!(set("signed_by([email protected])"), vec![d]);
8289
    assert_eq!(set(&format!("signed_by({})", key.short(12))), vec![d]);
8290
    assert_eq!(set("unsigned() & ::main"), sorted(&[a, b, c]));
8291
    assert_eq!(set("delegated()"), vec![]);
8292
    assert_eq!(set("revoked()"), vec![]);
8293
    assert_eq!(set("attested(tag)"), vec![]);
8294
    repo.tag_create("v1", &[b], "first").unwrap();
8295
    assert_eq!(set("attested(tag)"), sorted(&[a, b]));
8296
    assert_eq!(set("attested(tag) & unsigned()"), sorted(&[a, b]));
8297
    assert_eq!(set("attested(receipt)"), vec![]);
8298
    assert_eq!(set("built(test)"), vec![]);
8299
    let e = repo.revset("attested(seal)").unwrap_err().to_string();
8300
    assert!(e.contains("tag, receipt or ref"), "{e}");
8301
    repo.revoke_identity(&key, "test").unwrap();
8302
    assert_eq!(set("revoked()"), vec![d]);
8303
    assert_eq!(set("signed_by(me) ~ revoked()"), vec![]);
8304
}
8305
8306
#[test]
8307
fn a_rotation_is_recorded_wherever_the_old_key_was_named() {
8308
    let dir = tempfile::tempdir().unwrap();
8309
    let root = dir.path();
8310
    let home = root.join("home");
8311
    // Ada's identity lives in the user file; repository `a` pins the same
8312
    // key in its own file, repository `b` names none.
8313
    let mut a = Repo::init(&root.join("a")).unwrap().with_home(&home);
8314
    let (key, _) = a
8315
        .create_identity("Ada", "[email protected]", IdentityScope::User)
8316
        .unwrap();
8317
    a.config.set("author.key", &key.to_hex()).unwrap();
8318
    a.save_config().unwrap();
8319
    let agent = SecretKey::generate().identity("Agent", "[email protected]", 1);
8320
    let r = a
8321
        .delegate_add(agent.clone(), crate::identity::Scope::CHANGES, None)
8322
        .unwrap();
8323
    assert_eq!(
8324
        read_config_file(&home.join("config.toml")).unwrap()["author.key"],
8325
        r.new.to_hex(),
8326
        "the user file follows"
8327
    );
8328
    assert_eq!(
8329
        read_config_file(&root.join("a/.oxy/config")).unwrap()["author.key"],
8330
        r.new.to_hex(),
8331
        "the pinning repository follows"
8332
    );
8333
    let b = Repo::init(&root.join("b")).unwrap().with_home(&home);
8334
    assert_eq!(
8335
        b.config.author_key,
8336
        Some(r.new),
8337
        "a checkout without a pin follows the user file"
8338
    );
8339
    // A repository-scoped identity leaves the user file alone.
8340
    let other_home = root.join("home2");
8341
    let mut c = Repo::init(&root.join("c")).unwrap().with_home(&other_home);
8342
    let (ck, _) = c
8343
        .create_identity("Cy", "[email protected]", IdentityScope::Repo)
8344
        .unwrap();
8345
    assert!(!other_home.join("config.toml").exists());
8346
    let r2 = c.rotate_identity().unwrap();
8347
    assert_ne!(r2.new, ck);
8348
    assert_eq!(
8349
        read_config_file(&root.join("c/.oxy/config")).unwrap()["author.key"],
8350
        r2.new.to_hex()
8351
    );
8352
    assert!(
8353
        !other_home.join("config.toml").exists(),
8354
        "a repository-scoped identity stays repository-scoped"
8355
    );
8356
    // Several delegates in one rotation; a repeat is refused.
8357
    let (d1, d2) = (
8358
        SecretKey::generate().identity("D1", "d1@x", 1),
8359
        SecretKey::generate().identity("D2", "d2@x", 1),
8360
    );
8361
    let r3 = c
8362
        .delegate_add_many(vec![d1.clone(), d2], crate::identity::Scope::CHANGES, None)
8363
        .unwrap();
8364
    assert_eq!(r3.identity.delegates.len(), 2);
8365
    assert!(c
8366
        .delegate_add(d1, crate::identity::Scope::CHANGES, None)
8367
        .is_err());
8368
}
8369
8370
/// Two unrelated histories that both add the same file, joined by two
8371
/// independent merges on two branches, then those branches merged: Git
8372
/// merges identical additions cleanly, and the import must too (#71,
8373
/// found in VS Code's history).
8374
#[test]
8375
fn git_import_joins_unrelated_histories_that_add_the_same_file() {
8376
    // Batches of one: every merge renders apart from the state, where a
8377
    // file whose graph the state had built came out empty (#71).
8378
    crate::repo::git::set_merge_batch_for_tests(Some(1));
8379
    hermetic();
8380
    if std::process::Command::new("git")
8381
        .arg("--version")
8382
        .output()
8383
        .is_err()
8384
    {
8385
        eprintln!("git not installed; skipping");
8386
        return;
8387
    }
8388
    let dir = tempfile::tempdir().unwrap();
8389
    let root = dir.path();
8390
    let g = root.join("src.git");
8391
    fs::create_dir_all(&g).unwrap();
8392
    let git = |args: &[&str]| -> String {
8393
        let out = std::process::Command::new("git")
8394
            .arg("-C")
8395
            .arg(&g)
8396
            .args([
8397
                "-c",
8398
                "user.name=Grace",
8399
                "-c",
8400
                "[email protected]",
8401
                "-c",
8402
                "commit.gpgsign=false",
8403
            ])
8404
            .args(args)
8405
            .output()
8406
            .unwrap();
8407
        assert!(
8408
            out.status.success(),
8409
            "git {args:?}: {}",
8410
            String::from_utf8_lossy(&out.stderr)
8411
        );
8412
        String::from_utf8_lossy(&out.stdout).trim().to_string()
8413
    };
8414
    let text = b"/* header */\nconst a = 1;\nconst b = 2;\n";
8415
    // History A: main.
8416
    git(&["init", "-q", "-b", "main"]);
8417
    write(&g, "gulpfile.js", text);
8418
    write(&g, "a.txt", b"a\n");
8419
    git(&["add", "."]);
8420
    git(&["commit", "-q", "-m", "A root"]);
8421
    // History B: an unrelated root adding the same file, identical.
8422
    git(&["checkout", "-q", "--orphan", "fork"]);
8423
    git(&["rm", "-q", "-r", "--cached", "."]);
8424
    for f in ["gulpfile.js", "a.txt"] {
8425
        let _ = fs::remove_file(g.join(f));
8426
    }
8427
    write(&g, "gulpfile.js", text);
8428
    write(&g, "b.txt", b"b\n");
8429
    git(&["add", "."]);
8430
    git(&["commit", "-q", "-m", "B root"]);
8431
    // Two branches from main, each joining B on its own.
8432
    git(&["checkout", "-q", "-b", "one", "main"]);
8433
    git(&[
8434
        "merge",
8435
        "-q",
8436
        "--no-ff",
8437
        "--allow-unrelated-histories",
8438
        "-m",
8439
        "join on one",
8440
        "fork",
8441
    ]);
8442
    git(&["checkout", "-q", "-b", "two", "main"]);
8443
    write(&g, "a.txt", b"a\ntwo\n");
8444
    git(&["commit", "-q", "-am", "work on two"]);
8445
    git(&[
8446
        "merge",
8447
        "-q",
8448
        "--no-ff",
8449
        "--allow-unrelated-histories",
8450
        "-m",
8451
        "join on two",
8452
        "fork",
8453
    ]);
8454
    // Then the two joins meet, and the file is reformatted after.
8455
    git(&["checkout", "-q", "main"]);
8456
    git(&["merge", "-q", "--no-ff", "-m", "merge one", "one"]);
8457
    git(&["merge", "-q", "--no-ff", "-m", "merge two", "two"]);
8458
    write(
8459
        &g,
8460
        "gulpfile.js",
8461
        b"/* header */\nconst a = 1;\nconst b = 3;\n",
8462
    );
8463
    git(&["commit", "-q", "-am", "after"]);
8464
8465
    let dest = root.join("dest");
8466
    let repo = Repo::init(&dest).unwrap().with_home(root.join("home"));
8467
    repo.import_git(&g, "main").unwrap();
8468
    let v = repo.verify_git_import(&g, "main").unwrap();
8469
    assert!(v.mismatches.is_empty(), "{:?}", v.mismatches);
8470
    assert_eq!(
8471
        fs::read(dest.join("gulpfile.js")).unwrap(),
8472
        b"/* header */\nconst a = 1;\nconst b = 3;\n"
8473
    );
8474
}
8475
8476
/// As above, but the two joins keep different copies (each branch had a
8477
/// different version when it joined), and later work edits each copy:
8478
/// the shape of VS Code's c67ef57cda90 (#71).
8479
#[test]
8480
fn git_import_joins_where_each_join_kept_a_different_copy() {
8481
    // Batches of one: every merge renders apart from the state, where a
8482
    // file whose graph the state had built came out empty (#71).
8483
    crate::repo::git::set_merge_batch_for_tests(Some(1));
8484
    hermetic();
8485
    if std::process::Command::new("git")
8486
        .arg("--version")
8487
        .output()
8488
        .is_err()
8489
    {
8490
        eprintln!("git not installed; skipping");
8491
        return;
8492
    }
8493
    let dir = tempfile::tempdir().unwrap();
8494
    let root = dir.path();
8495
    let g = root.join("src.git");
8496
    fs::create_dir_all(&g).unwrap();
8497
    let run = |args: &[&str]| {
8498
        std::process::Command::new("git")
8499
            .arg("-C")
8500
            .arg(&g)
8501
            .args([
8502
                "-c",
8503
                "user.name=Grace",
8504
                "-c",
8505
                "[email protected]",
8506
                "-c",
8507
                "commit.gpgsign=false",
8508
            ])
8509
            .args(args)
8510
            .output()
8511
            .unwrap()
8512
    };
8513
    let git = |args: &[&str]| -> String {
8514
        let out = run(args);
8515
        assert!(
8516
            out.status.success(),
8517
            "git {args:?}: {}",
8518
            String::from_utf8_lossy(&out.stderr)
8519
        );
8520
        String::from_utf8_lossy(&out.stdout).trim().to_string()
8521
    };
8522
    git(&["init", "-q", "-b", "main"]);
8523
    write(
8524
        &g,
8525
        "gulpfile.js",
8526
        b"/* header */\nconst a = 1;\nconst b = 2;\n",
8527
    );
8528
    git(&["add", "."]);
8529
    git(&["commit", "-q", "-m", "A root"]);
8530
    write(
8531
        &g,
8532
        "gulpfile.js",
8533
        b"/* header */\nconst a = 1;\n\nconst b = 2;\n",
8534
    );
8535
    git(&["commit", "-q", "-am", "whitespace"]);
8536
    git(&["checkout", "-q", "--orphan", "fork"]);
8537
    git(&["rm", "-q", "-r", "--cached", "."]);
8538
    let _ = fs::remove_file(g.join("gulpfile.js"));
8539
    write(
8540
        &g,
8541
        "gulpfile.js",
8542
        b"/* header */\nconst a = 1;\nconst b = 2;\nconst c = 3;\n",
8543
    );
8544
    git(&["add", "."]);
8545
    git(&["commit", "-q", "-m", "B root"]);
8546
    // Branch one joins B keeping main's copy; branch two keeps B's.
8547
    for (branch, keep) in [("one", "ours"), ("two", "theirs")] {
8548
        git(&["checkout", "-q", "-b", branch, "main"]);
8549
        let _ = run(&[
8550
            "merge",
8551
            "-q",
8552
            "--no-ff",
8553
            "--allow-unrelated-histories",
8554
            "-m",
8555
            "join",
8556
            "fork",
8557
        ]);
8558
        git(&["checkout", &format!("--{keep}"), "gulpfile.js"]);
8559
        git(&["add", "gulpfile.js"]);
8560
        git(&["commit", "-q", "-m", &format!("join on {branch}")]);
8561
    }
8562
    // Each branch then edits its copy.
8563
    git(&["checkout", "-q", "one"]);
8564
    write(
8565
        &g,
8566
        "gulpfile.js",
8567
        b"/* header */\nconst a = 1;\n\nconst b = 2;\n// tslint\n",
8568
    );
8569
    git(&["commit", "-q", "-am", "tslint on one"]);
8570
    git(&["checkout", "-q", "two"]);
8571
    write(
8572
        &g,
8573
        "gulpfile.js",
8574
        b"/* header */\nconst a = 1;\nconst b = 2;\nconst c = 3;\n// fmt\n",
8575
    );
8576
    write(&g, "extra.txt", b"x\n");
8577
    write(&g, "more.txt", b"m\n");
8578
    git(&["add", "."]);
8579
    git(&["commit", "-q", "-am", "fmt on two"]);
8580
    // They meet: resolved by hand.
8581
    git(&["checkout", "-q", "one"]);
8582
    let _ = run(&["merge", "-q", "--no-ff", "-m", "merge two", "two"]);
8583
    write(
8584
        &g,
8585
        "gulpfile.js",
8586
        b"/* header */\nconst a = 1;\nconst b = 2;\nconst c = 3;\n// tslint\n// fmt\n",
8587
    );
8588
    git(&["add", "gulpfile.js"]);
8589
    git(&["commit", "-q", "-m", "merge two into one"]);
8590
8591
    let dest = root.join("dest");
8592
    let repo = Repo::init(&dest).unwrap().with_home(root.join("home"));
8593
    repo.import_git(&g, "one").unwrap();
8594
    let v = repo.verify_git_import(&g, "one").unwrap();
8595
    assert!(v.mismatches.is_empty(), "{:?}", v.mismatches);
8596
}
8597
8598
/// oxygen#68: on a store that is not this disk's directory, the operation
8599
/// head is the store's reference record, moved by compare-and-swap. Two
8600
/// handles recording from the same head both get through, merged; a swap
8601
/// from a stale version is refused; a second repository cannot start on a
8602
/// store that already holds one.
8603
#[test]
8604
fn over_a_store_the_operation_head_moves_by_compare_and_swap() {
8605
    use crate::strata::{MemoryStore, Store as _};
8606
    let backend = std::sync::Arc::new(MemoryStore::new());
8607
    crate::store::TEST_BACKEND.with(|t| *t.borrow_mut() = Some(backend.clone()));
8608
    let dir = tempfile::tempdir().unwrap();
8609
    let a = Repo::init(dir.path()).unwrap();
8610
    assert!(
8611
        !dir.path().join(".oxy/ops/head").exists(),
8612
        "the head is not a file"
8613
    );
8614
    let (h0, op0) = a.head_op().unwrap();
8615
    let record = backend
8616
        .read_ref(HEAD_RECORD)
8617
        .unwrap()
8618
        .expect("the head is the store's record");
8619
    assert_eq!(String::from_utf8(record.0).unwrap(), h0.to_hex());
8620
8621
    let b = Repo::open(dir.path()).unwrap();
8622
    let state = a.store.put_state(&StateObject::new(vec![])).unwrap();
8623
    let mut va = op0.view.clone();
8624
    va.bookmarks.insert("from-a".into(), state);
8625
    let mut vb = op0.view.clone();
8626
    vb.bookmarks.insert("from-b".into(), state);
8627
    let rb = b.record_op(&[h0], "bookmark from-b", vb).unwrap();
8628
    assert_eq!(b.head_ref().unwrap(), rb);
8629
    // a recorded from h0 too: the head moved, so the two are merged.
8630
    let ra = a.record_op(&[h0], "bookmark from-a", va).unwrap();
8631
    let (head, op) = Repo::open(dir.path()).unwrap().head_op().unwrap();
8632
    assert_eq!(head, ra);
8633
    assert!(
8634
        op.command.ends_with("(merged with a concurrent operation)"),
8635
        "{}",
8636
        op.command
8637
    );
8638
    assert_eq!(op.parents, vec![rb, op.parents[1]]);
8639
    assert!(op.view.bookmarks.contains_key("from-a") && op.view.bookmarks.contains_key("from-b"));
8640
8641
    // A swap from a version that is no longer current moves nothing.
8642
    let (h, v) = a.read_head().unwrap();
8643
    assert!(b.swap_head(&rb, v.as_ref()).unwrap());
8644
    assert!(!a.swap_head(&h, v.as_ref()).unwrap(), "stale");
8645
    a.refresh().unwrap();
8646
    assert_eq!(a.head_ref().unwrap(), rb);
8647
8648
    let other = tempfile::tempdir().unwrap();
8649
    let err = Repo::init(other.path())
8650
        .err()
8651
        .expect("the store already holds a log")
8652
        .to_string();
8653
    assert!(
8654
        err.contains("already holds a repository's operation log"),
8655
        "{err}"
8656
    );
8657
    crate::store::TEST_BACKEND.with(|t| *t.borrow_mut() = None);
8658
}
8659
8660
/// oxygen#68: a repository kept on a store (`storage.url`) holds its
8661
/// objects and operation head there, with `.oxy/cache` in front: it works
8662
/// as one on disk does, reopens, and survives losing its cache.
8663
#[test]
8664
fn a_repository_runs_on_a_store_with_a_cache_in_front() {
8665
    hermetic();
8666
    if std::env::var_os("OXY_STORE_BACKEND").is_some() {
8667
        return;
8668
    }
8669
    let dir = tempfile::tempdir().unwrap();
8670
    let (root, bucket) = (dir.path().join("work"), dir.path().join("bucket"));
8671
    let url = format!("dir://{}", bucket.display());
8672
    let repo = Repo::init_on(&root, [7; 16], Some(&url)).unwrap();
8673
    assert_eq!(repo.config.storage_url.as_deref(), Some(url.as_str()));
8674
    write(&root, "a.txt", b"one\n");
8675
    let h1 = repo.commit("First", &[]).unwrap();
8676
    write(&root, "a.txt", b"one\ntwo\n");
8677
    let h2 = repo.commit("Second", &[]).unwrap();
8678
    assert!(
8679
        !root.join(".oxy/ops/head").exists(),
8680
        "the head is in the store"
8681
    );
8682
    assert!(bucket.join("ops/head").is_file());
8683
    assert!(root.join(".oxy/cache").is_dir());
8684
    drop(repo);
8685
8686
    // Reopened, and again with no cache at all: everything comes from the store.
8687
    for drop_cache in [false, true] {
8688
        if drop_cache {
8689
            std::fs::remove_dir_all(root.join(".oxy/cache")).unwrap();
8690
        }
8691
        let repo = Repo::open(&root).unwrap();
8692
        let log: Vec<String> = repo
8693
            .op_log()
8694
            .unwrap()
8695
            .into_iter()
8696
            .map(|(_, op)| op.command)
8697
            .collect();
8698
        assert!(log.len() >= 3, "{log:?}");
8699
        assert_eq!(repo.store().get_change(&h1).unwrap().message, "First");
8700
        let heads = repo
8701
            .store()
8702
            .get_state(&repo.view().unwrap().bookmarks["main"])
8703
            .unwrap()
8704
            .heads;
8705
        assert_eq!(heads, vec![h2]);
8706
        assert_eq!(
8707
            repo.load_state(&heads).unwrap().materialize().files.len(),
8708
            1
8709
        );
8710
    }
8711
8712
    // A second repository cannot start on the same store.
8713
    let err = Repo::init_on(&dir.path().join("other"), [8; 16], Some(&url))
8714
        .err()
8715
        .unwrap()
8716
        .to_string();
8717
    assert!(
8718
        err.contains("already holds a repository's operation log"),
8719
        "{err}"
8720
    );
8721
    let err = Repo::init_on(&dir.path().join("third"), [9; 16], Some("nope://x"))
8722
        .err()
8723
        .unwrap()
8724
        .to_string();
8725
    assert!(err.contains("cannot open that kind of store"), "{err}");
8726
}
8727
8728
/// oxygen#75: the prompt's quick check agrees with status in a repository
8729
/// with a subrepo: clean after a commit, dirty when the subrepo moves to
8730
/// another state, clean again once that pin is committed. (It compared the
8731
/// subrepo's directory as if it were a file, so it was always dirty.)
8732
#[test]
8733
fn the_quick_dirty_check_compares_a_subrepo_by_its_pin() {
8734
    hermetic();
8735
    let dir = tempfile::tempdir().unwrap();
8736
    let root = dir.path();
8737
    let _lib_origin = Repo::init(&root.join("lib-origin")).unwrap();
8738
    let lib_url = root.join("lib-origin").to_string_lossy().to_string();
8739
    let lib = Repo::clone(&lib_url, &root.join("lib"))
8740
        .unwrap()
8741
        .with_home(root.join("home"));
8742
    write(&root.join("lib"), "lib.txt", b"v1\n");
8743
    lib.commit("lib v1", &[]).unwrap();
8744
    assert!(lib.push("origin", false).unwrap()[0].ok);
8745
    let app_dir = root.join("app");
8746
    let app = Repo::init(&app_dir).unwrap().with_home(root.join("home"));
8747
    write(&app_dir, "main.txt", b"app\n");
8748
    app.submodule_add(&lib_url, "libs/lib", None).unwrap();
8749
    app.commit("app with lib", &[]).unwrap();
8750
    // Out of the racy window, so the stat-only path decides.
8751
    std::thread::sleep(std::time::Duration::from_millis(2100));
8752
    let reopen = || Repo::open(&app_dir).unwrap();
8753
    assert_eq!(
8754
        reopen().quick_dirty().unwrap(),
8755
        Some(false),
8756
        "clean, as status says"
8757
    );
8758
    let nested = Repo::open(&app_dir.join("libs/lib")).unwrap();
8759
    write(&app_dir.join("libs/lib"), "lib.txt", b"v2\n");
8760
    nested.commit("lib v2", &[]).unwrap();
8761
    assert_eq!(
8762
        reopen().quick_dirty().unwrap(),
8763
        Some(true),
8764
        "the subrepo moved"
8765
    );
8766
    reopen().commit("pin lib v2", &[]).unwrap();
8767
    std::thread::sleep(std::time::Duration::from_millis(2100));
8768
    assert_eq!(
8769
        reopen().quick_dirty().unwrap(),
8770
        Some(false),
8771
        "the new pin is committed"
8772
    );
8773
}
8774
8775
#[test]
8776
fn a_module_entry_that_was_never_added_is_reported_as_unpinned() {
8777
    // oxygen#72: a .oxymodules section with no subrepo behind it.
8778
    hermetic();
8779
    let dir = tempfile::tempdir().unwrap();
8780
    let root = dir.path();
8781
    let _lib_origin = Repo::init(&root.join("lib-origin")).unwrap();
8782
    let lib_url = root.join("lib-origin").to_string_lossy().to_string();
8783
    let lib = Repo::clone(&lib_url, &root.join("lib"))
8784
        .unwrap()
8785
        .with_home(root.join("home"));
8786
    write(&root.join("lib"), "lib.txt", b"v1\n");
8787
    lib.commit("lib v1", &[]).unwrap();
8788
    assert!(lib.push("origin", false).unwrap()[0].ok);
8789
    let app_dir = root.join("app");
8790
    let app = Repo::init(&app_dir).unwrap().with_home(root.join("home"));
8791
    write(
8792
        &app_dir,
8793
        ".oxymodules",
8794
        format!("[libs/lib]\nurl = {lib_url}\n").as_bytes(),
8795
    );
8796
    let unpinned = app.unpinned_modules().unwrap();
8797
    assert_eq!(unpinned.len(), 1);
8798
    assert_eq!(unpinned[0].0, "libs/lib");
8799
    assert_eq!(unpinned[0].1.url, lib_url);
8800
    assert!(app.submodule_update(true, &[]).unwrap().is_empty());
8801
    app.submodule_add(&lib_url, "libs/lib", None).unwrap();
8802
    assert!(app.unpinned_modules().unwrap().is_empty(), "added now");
8803
}
8804
8805
#[test]
8806
fn the_bookmark_revset_function_names_only_bookmarks() {
8807
    // oxygen#73: bookmark(NAME) is a bookmark's heads, never a tag or prefix.
8808
    hermetic();
8809
    let dir = tempfile::tempdir().unwrap();
8810
    let repo = Repo::init(dir.path()).unwrap();
8811
    write(dir.path(), "a.txt", b"a\n");
8812
    let a = repo.commit("A", &[]).unwrap();
8813
    write(dir.path(), "b.txt", b"b\n");
8814
    let b = repo.commit("B", &[]).unwrap();
8815
    let mut heads = repo.revset("bookmark(main)").unwrap().hashes;
8816
    heads.sort();
8817
    let mut want = repo.bookmark_heads().unwrap();
8818
    want.sort();
8819
    assert_eq!(heads, want);
8820
    assert!(heads.contains(&b));
8821
    assert_eq!(repo.revset("main").unwrap().hashes.len(), heads.len());
8822
    // A change prefix is a symbol, not a bookmark.
8823
    let prefix = repo.store().get_change_meta(&a).unwrap().change_id.short(8);
8824
    assert!(repo.revset(&prefix).is_ok());
8825
    let e = repo
8826
        .revset(&format!("bookmark({prefix})"))
8827
        .unwrap_err()
8828
        .to_string();
8829
    assert!(e.contains("no such bookmark"), "{e}");
8830
}
8831
8832
#[test]
8833
fn carrying_work_over_a_subrepo_already_at_the_target_pin_is_no_conflict() {
8834
    // oxygen#74: a stale state with .oxymodules but no pin, a newer one
8835
    // pinning the subrepo, and the nested repository on disk at that pin.
8836
    hermetic();
8837
    let dir = tempfile::tempdir().unwrap();
8838
    let root = dir.path();
8839
    let _lib_origin = Repo::init(&root.join("lib-origin")).unwrap();
8840
    let lib_url = root.join("lib-origin").to_string_lossy().to_string();
8841
    let lib = Repo::clone(&lib_url, &root.join("lib"))
8842
        .unwrap()
8843
        .with_home(root.join("home"));
8844
    write(&root.join("lib"), "lib.txt", b"v1\n");
8845
    lib.commit("lib v1", &[]).unwrap();
8846
    assert!(lib.push("origin", false).unwrap()[0].ok);
8847
    let app_dir = root.join("app");
8848
    let app = Repo::init(&app_dir).unwrap().with_home(root.join("home"));
8849
    write(&app_dir, "main.txt", b"app\n");
8850
    app.submodule_add(&lib_url, "libs/lib", None).unwrap();
8851
    // The stale state: registered in .oxymodules, never pinned.
8852
    fs::rename(app_dir.join("libs/lib"), root.join("aside")).unwrap();
8853
    app.commit("initial", &[]).unwrap();
8854
    let stale = app.bookmark_heads().unwrap();
8855
    fs::rename(root.join("aside"), app_dir.join("libs/lib")).unwrap();
8856
    app.commit("pin lib", &[]).unwrap();
8857
    let newer = app.bookmark_heads().unwrap();
8858
    app.checkout(&stale, false, "test").unwrap();
8859
    write(&app_dir, "notes.txt", b"mine\n");
8860
    let (_, carried) = app.checkout_carry(&newer, "main", "test").unwrap();
8861
    assert_eq!(carried, vec!["notes.txt".to_string()]);
8862
    assert!(app_dir.join("notes.txt").exists());
8863
}
8864
8865
#[test]
8866
fn a_bookmark_only_behind_its_remote_catches_up() {
8867
    // oxygen#74: switch takes the remote's state rather than a stale one.
8868
    hermetic();
8869
    let dir = tempfile::tempdir().unwrap();
8870
    let root = dir.path();
8871
    let _origin = Repo::init(&root.join("origin")).unwrap();
8872
    let url = root.join("origin").to_string_lossy().to_string();
8873
    let one = Repo::clone(&url, &root.join("one"))
8874
        .unwrap()
8875
        .with_home(root.join("home"));
8876
    write(&root.join("one"), "a.txt", b"a\n");
8877
    one.commit("A", &[]).unwrap();
8878
    assert!(one.push("origin", false).unwrap()[0].ok);
8879
    let two = Repo::clone(&url, &root.join("two"))
8880
        .unwrap()
8881
        .with_home(root.join("home"));
8882
    write(&root.join("two"), "b.txt", b"b\n");
8883
    two.commit("B", &[]).unwrap();
8884
    assert!(two.push("origin", false).unwrap()[0].ok);
8885
    assert_eq!(one.catch_up_bookmark("main").unwrap(), None, "not fetched");
8886
    one.fetch("origin").unwrap();
8887
    assert_eq!(one.catch_up_bookmark("main").unwrap(), Some(1));
8888
    assert_eq!(one.bookmarks().unwrap()[0].behind, Some(0));
8889
    // Local work the remote lacks: left alone.
8890
    write(&root.join("one"), "c.txt", b"c\n");
8891
    one.commit("C", &[]).unwrap();
8892
    write(&root.join("two"), "d.txt", b"d\n");
8893
    two.commit("D", &[]).unwrap();
8894
    assert!(two.push("origin", false).unwrap()[0].ok);
8895
    one.fetch("origin").unwrap();
8896
    assert_eq!(one.catch_up_bookmark("main").unwrap(), None);
8897
}
8898
8899
#[test]
8900
fn a_bookmark_is_compared_with_a_remote_that_has_it_when_there_is_no_origin() {
8901
    // oxygen#83: remotes earth and gcs, origin removed.
8902
    hermetic();
8903
    let dir = tempfile::tempdir().unwrap();
8904
    let root = dir.path();
8905
    let _up = Repo::init(&root.join("up")).unwrap();
8906
    let url = root.join("up").to_string_lossy().to_string();
8907
    let other = Repo::clone(&url, &root.join("other"))
8908
        .unwrap()
8909
        .with_home(root.join("home"));
8910
    write(&root.join("other"), "a.txt", b"a\n");
8911
    other.commit("a", &[]).unwrap();
8912
    assert!(other.push("origin", false).unwrap()[0].ok);
8913
    let mut one = Repo::clone(&url, &root.join("one"))
8914
        .unwrap()
8915
        .with_home(root.join("home"));
8916
    one.config.set("remote.earth.url", &url).unwrap();
8917
    one.config.set("remote.gcs.url", &url).unwrap();
8918
    one.config.set("remote.origin.url", "").unwrap();
8919
    one.save_config().unwrap();
8920
    write(&root.join("other"), "b.txt", b"b\n");
8921
    other.commit("b", &[]).unwrap();
8922
    assert!(other.push("origin", false).unwrap()[0].ok);
8923
    one.fetch("earth").unwrap();
8924
    let b = one
8925
        .bookmarks()
8926
        .unwrap()
8927
        .into_iter()
8928
        .find(|b| b.name == "main")
8929
        .unwrap();
8930
    assert_eq!(
8931
        (b.remote.as_deref(), b.behind),
8932
        (Some("earth"), Some(1)),
8933
        "a stale origin copy is not used"
8934
    );
8935
    assert_eq!(
8936
        one.default_remote(),
8937
        "origin",
8938
        "no default chosen among several"
8939
    );
8940
    let e = one.pull(&one.default_remote()).unwrap_err().to_string();
8941
    assert!(e.contains("earth, gcs") && e.contains("core.remote"), "{e}");
8942
    one.config.set("core.remote", "earth").unwrap();
8943
    assert_eq!(one.default_remote(), "earth");
8944
}
8945
8946
#[test]
8947
fn a_missing_author_identity_says_how_to_fix_it() {
8948
    // oxygen#82: an agent home's author.key naming an identity the
8949
    // repository does not hold.
8950
    hermetic();
8951
    let dir = tempfile::tempdir().unwrap();
8952
    let mut repo = Repo::init(dir.path()).unwrap();
8953
    let missing = KeyId::from_hex(&"ab".repeat(32)).unwrap();
8954
    repo.config.set("author.key", &missing.to_hex()).unwrap();
8955
    let e = repo.identity(&missing).unwrap_err().to_string();
8956
    assert!(
8957
        e.contains("this repository has no identity") && e.contains("oxy config author.key"),
8958
        "{e}"
8959
    );
8960
    assert!(e.contains("this repository's config"), "{e}");
8961
}
8962
8963
#[test]
8964
fn a_working_copy_behind_its_bookmark_is_flagged_and_pull_brings_it_up() {
8965
    // oxygen#89 (supermarioland, 2026-10-09): the bookmark moved on without
8966
    // the working copy, a pull with nothing new left it there, and status
8967
    // said "clean".
8968
    hermetic();
8969
    let dir = tempfile::tempdir().unwrap();
8970
    let root = dir.path();
8971
    let _up = Repo::init(&root.join("up")).unwrap();
8972
    let url = root.join("up").to_string_lossy().to_string();
8973
    let other = Repo::clone(&url, &root.join("other"))
8974
        .unwrap()
8975
        .with_home(root.join("home"));
8976
    write(&root.join("other"), "a.txt", b"a\n");
8977
    other.commit("a", &[]).unwrap();
8978
    assert!(other.push("origin", false).unwrap()[0].ok);
8979
    let one = Repo::clone(&url, &root.join("one"))
8980
        .unwrap()
8981
        .with_home(root.join("home"));
8982
    write(&root.join("other"), "b.txt", b"b\n");
8983
    other.commit("b", &[]).unwrap();
8984
    assert!(other.push("origin", false).unwrap()[0].ok);
8985
    one.fetch("origin").unwrap();
8986
    // The bookmark moves; the working copy does not.
8987
    let theirs = one.resolve_heads("origin/main").unwrap();
8988
    one.bookmark_set("main", &theirs).unwrap();
8989
    assert!(!root.join("one/b.txt").exists());
8990
    assert_eq!(one.working_copy_behind().unwrap(), Some(1));
8991
    let r = one.pull("origin").unwrap();
8992
    assert!(
8993
        !r.changed && r.checked_out,
8994
        "nothing new, but the working copy caught up"
8995
    );
8996
    assert!(root.join("one/b.txt").exists());
8997
    assert_eq!(one.working_copy_behind().unwrap(), None);
8998
}
8999
9000
#[test]
9001
fn touched_nodes_cache_answers_as_the_changes_do() {
9002
    hermetic();
9003
    let dir = tempfile::tempdir().unwrap();
9004
    let repo = Repo::init(dir.path()).unwrap();
9005
    write(dir.path(), "a.txt", b"one\n");
9006
    write(dir.path(), "b.txt", b"x\n");
9007
    repo.snapshot("t").unwrap();
9008
    let c1 = repo.commit("first", &[]).unwrap();
9009
    write(dir.path(), "b.txt", b"y\n");
9010
    repo.snapshot("t").unwrap();
9011
    repo.commit("b only", &[]).unwrap();
9012
    fs::rename(dir.path().join("a.txt"), dir.path().join("c.txt")).unwrap();
9013
    write(dir.path(), "c.txt", b"one\ntwo\n");
9014
    repo.snapshot("t").unwrap();
9015
    let c3 = repo.commit("rename and edit", &[]).unwrap();
9016
    // Uncommitted work, so the working copy touches a file too.
9017
    write(dir.path(), "c.txt", b"one\ntwo\nthree\n");
9018
    repo.snapshot("t").unwrap();
9019
9020
    let path = dir.path().join(".oxy/index/touched");
9021
    let hashes = |es: Vec<LogEntry>| es.iter().map(|e| e.hash).collect::<Vec<_>>();
9022
    let cold = hashes(repo.log_for_path("c.txt").unwrap());
9023
    assert!(path.exists(), "the first query writes the cache");
9024
    let warm = hashes(repo.log_for_path("c.txt").unwrap());
9025
    assert_eq!(cold, warm, "the cache answers as the changes do");
9026
    let (wc, _) = repo.working_copy().unwrap();
9027
    assert_eq!(
9028
        cold,
9029
        vec![wc, c3, c1],
9030
        "renames followed, the working copy included"
9031
    );
9032
9033
    // Working-copy changes are not kept: they are replaced by every snapshot.
9034
    let cached = super::touched::read_touched_for_test(&fs::read(&path).unwrap()).unwrap();
9035
    assert!(!cached.contains(&wc), "a working-copy change is not cached");
9036
    assert!(cached.contains(&c1) && cached.contains(&c3));
9037
9038
    // A damaged cache is ignored, not trusted.
9039
    let mut bytes = fs::read(&path).unwrap();
9040
    let last = bytes.len() - 40;
9041
    bytes[last] ^= 1;
9042
    fs::write(&path, &bytes).unwrap();
9043
    assert_eq!(hashes(repo.log_for_path("c.txt").unwrap()), cold);
9044
    let touches = repo.log_revset("touches(\"c.txt\") ~ @").unwrap();
9045
    assert_eq!(hashes(touches), vec![c3, c1]);
9046
}
9047
9048
/// oxygen#88 (vscode 9ab2056393c8): two lines of history that each move a
9049
/// file back where it was leave two placements at one place, which the
9050
/// tree shows as one file. Removing it, and then its directory, retires
9051
/// both, so no copy is left under a directory that is gone.
9052
#[test]
9053
fn git_import_removes_every_copy_of_a_file_at_one_place() {
9054
    hermetic();
9055
    if std::process::Command::new("git")
9056
        .arg("--version")
9057
        .output()
9058
        .is_err()
9059
    {
9060
        eprintln!("git not installed; skipping");
9061
        return;
9062
    }
9063
    let dir = tempfile::tempdir().unwrap();
9064
    let root = dir.path();
9065
    let g = root.join("src.git");
9066
    fs::create_dir_all(&g).unwrap();
9067
    let git = |args: &[&str]| {
9068
        let out = std::process::Command::new("git")
9069
            .arg("-C")
9070
            .arg(&g)
9071
            .args([
9072
                "-c",
9073
                "user.name=Grace",
9074
                "-c",
9075
                "[email protected]",
9076
                "-c",
9077
                "commit.gpgsign=false",
9078
            ])
9079
            .args(args)
9080
            .output()
9081
            .unwrap();
9082
        assert!(
9083
            out.status.success(),
9084
            "git {args:?}: {}",
9085
            String::from_utf8_lossy(&out.stderr)
9086
        );
9087
    };
9088
    git(&["init", "-q", "-b", "main"]);
9089
    write(&g, "d/list.txt", b"one\ntwo\nthree\nfour\n");
9090
    write(&g, "keep.txt", b"k\n");
9091
    git(&["add", "."]);
9092
    git(&["commit", "-qm", "base"]);
9093
    fs::create_dir_all(g.join("d/sub")).unwrap();
9094
    git(&["mv", "d/list.txt", "d/sub/list.txt"]);
9095
    git(&["commit", "-qm", "into sub"]);
9096
    git(&["checkout", "-qb", "side"]);
9097
    git(&["mv", "d/sub/list.txt", "d/list.txt"]);
9098
    git(&["commit", "-qm", "back, on side"]);
9099
    git(&["checkout", "-q", "main"]);
9100
    git(&["mv", "d/sub/list.txt", "d/list.txt"]);
9101
    git(&["commit", "-qm", "back, on main"]);
9102
    git(&["merge", "-q", "--no-edit", "side"]);
9103
    git(&["rm", "-rq", "d"]);
9104
    git(&["commit", "-qm", "d goes"]);
9105
9106
    let repo = Repo::init(&root.join("o")).unwrap();
9107
    repo.import_git(&g, "main").unwrap();
9108
    let v = repo.verify_git_import(&g, "main").unwrap();
9109
    assert!(v.mismatches.is_empty(), "{:?}", v.mismatches);
9110
    let st = repo
9111
        .load_state_history(&repo.bookmark_heads().unwrap())
9112
        .unwrap();
9113
    let view = st.tree().view();
9114
    assert!(view.conflicts.is_empty(), "{:?}", view.conflicts);
9115
    assert_eq!(view.entries.keys().collect::<Vec<_>>(), vec!["keep.txt"]);
9116
}
9117
9118
/// oxygen#94: a state index's file histories are read, and checked by
9119
/// their own hashes, only when a file is built. One found damaged is an
9120
/// error that says so, the index is removed, and the next read rebuilds it.
9121
#[test]
9122
fn a_damaged_file_history_in_the_state_index_is_rebuilt() {
9123
    hermetic();
9124
    let dir = tempfile::tempdir().unwrap();
9125
    let repo = Repo::init(dir.path()).unwrap();
9126
    for i in 0..6 {
9127
        write(
9128
            dir.path(),
9129
            &format!("f{i}.txt"),
9130
            format!("one {i}\n").as_bytes(),
9131
        );
9132
    }
9133
    repo.snapshot("t").unwrap();
9134
    repo.commit("first", &[]).unwrap();
9135
    for i in 0..6 {
9136
        write(
9137
            dir.path(),
9138
            &format!("f{i}.txt"),
9139
            format!("one {i}\ntwo\n").as_bytes(),
9140
        );
9141
    }
9142
    repo.snapshot("t").unwrap();
9143
    repo.commit("second", &[]).unwrap();
9144
    let want: Vec<Vec<u8>> = (0..6)
9145
        .map(|i| format!("one {i}\ntwo\n").into_bytes())
9146
        .collect();
9147
    // The index of the working copy's base, holding every file's history
9148
    // (a few changes behind, an index is replayed onto, not rewritten).
9149
    let (_, wc) = repo.working_copy().unwrap();
9150
    let base = repo.load_state_history(&wc.deps).unwrap();
9151
    repo.write_state_index(&wc.deps, &base);
9152
    for (i, w) in want.iter().enumerate() {
9153
        assert_eq!(&repo.file_at(&format!("f{i}.txt"), None).unwrap(), w);
9154
    }
9155
    let index = repo.state_indexes();
9156
    assert!(!index.is_empty(), "a state index was written");
9157
    // The histories are last in the file: damage the last of them.
9158
    let mut bytes = fs::read(&index[0]).unwrap();
9159
    let last = bytes.len() - 1;
9160
    bytes[last] ^= 0x40;
9161
    fs::write(&index[0], &bytes).unwrap();
9162
9163
    let reads: Vec<_> = (0..6)
9164
        .map(|i| repo.file_at(&format!("f{i}.txt"), None))
9165
        .collect();
9166
    let damaged: Vec<String> = reads
9167
        .iter()
9168
        .filter_map(|r| r.as_ref().err().map(|e| e.to_string()))
9169
        .collect();
9170
    assert_eq!(damaged.len(), 1, "{damaged:?}");
9171
    assert!(
9172
        damaged[0].contains("state index was damaged")
9173
            && damaged[0].contains("run the command again"),
9174
        "{}",
9175
        damaged[0]
9176
    );
9177
    // Every file reads right again, from an index rebuilt from history.
9178
    for (i, w) in want.iter().enumerate() {
9179
        assert_eq!(&repo.file_at(&format!("f{i}.txt"), None).unwrap(), w);
9180
    }
9181
}
9182
9183
/// oxygen#95: a push longer than `push.batch-bytes` goes in parts, each
9184
/// objects alone and in dependency order, and the last moves the bookmark.
9185
/// The remote ends with every change and the same state, and says how each
9186
/// part went.
9187
#[test]
9188
fn a_long_push_goes_in_parts() {
9189
    hermetic();
9190
    let dir = tempfile::tempdir().unwrap();
9191
    let root = dir.path();
9192
    let origin = root.join("origin");
9193
    Repo::init_bare_unbound(&origin).unwrap();
9194
    let main = root.join("main");
9195
    let mut repo = Repo::init(&main).unwrap();
9196
    repo.config
9197
        .set("remote.origin.url", &origin.to_string_lossy())
9198
        .unwrap();
9199
    // One byte: every change is a part of its own.
9200
    repo.config.set("push.batch-bytes", "1").unwrap();
9201
    repo.save_config().unwrap();
9202
    for i in 0..6 {
9203
        write(
9204
            &main,
9205
            &format!("f{i}.txt"),
9206
            format!("file {i}\n").as_bytes(),
9207
        );
9208
        repo.commit(&format!("c{i}"), &[]).unwrap();
9209
    }
9210
    let mut parts = Vec::new();
9211
    let results = repo
9212
        .push_bookmark_with("origin", "main", false, &mut |m| parts.push(m.to_string()))
9213
        .unwrap();
9214
    assert!(
9215
        results.iter().any(|r| r.ok && r.name == "main"),
9216
        "{results:?}"
9217
    );
9218
    assert_eq!(parts.len(), 6, "{parts:?}");
9219
    assert_eq!(parts[0], "part 1 of 6: 1 changes");
9220
9221
    let remote = Repo::open(&origin).unwrap();
9222
    let heads = repo.bookmark_heads().unwrap();
9223
    assert_eq!(remote.bookmark_heads().unwrap(), heads);
9224
    assert_eq!(
9225
        remote.log_state(&heads).unwrap().len(),
9226
        repo.log_state(&heads).unwrap().len()
9227
    );
9228
    // A push of objects alone reports how it went, as `objects`.
9229
    let got = remote
9230
        .receive_push(Bundle::default(), vec![], None, vec![])
9231
        .unwrap();
9232
    assert_eq!(got.len(), 1);
9233
    assert!(got[0].ok && got[0].name == OBJECTS_RESULT, "{got:?}");
9234
}
9235
9236
/// oxygen#97: with `git.claim`, an import authors the importing identity's
9237
/// own commits (Git author email = its email, any case) with its key, and
9238
/// leaves anyone else's with the zero key; the history verifies as before.
9239
#[test]
9240
fn git_import_claims_your_own_commits() {
9241
    hermetic();
9242
    if std::process::Command::new("git")
9243
        .arg("--version")
9244
        .output()
9245
        .is_err()
9246
    {
9247
        eprintln!("git not installed; skipping");
9248
        return;
9249
    }
9250
    let dir = tempfile::tempdir().unwrap();
9251
    let root = dir.path();
9252
    let g = root.join("src.git");
9253
    fs::create_dir_all(&g).unwrap();
9254
    let git = |who: &str, args: &[&str]| {
9255
        let (name, email) = who.split_once(' ').unwrap();
9256
        let out = std::process::Command::new("git")
9257
            .arg("-C")
9258
            .arg(&g)
9259
            .args([
9260
                "-c",
9261
                &format!("user.name={name}"),
9262
                "-c",
9263
                &format!("user.email={email}"),
9264
                "-c",
9265
                "commit.gpgsign=false",
9266
            ])
9267
            .args(args)
9268
            .output()
9269
            .unwrap();
9270
        assert!(
9271
            out.status.success(),
9272
            "git {args:?}: {}",
9273
            String::from_utf8_lossy(&out.stderr)
9274
        );
9275
    };
9276
    git("Grace [email protected]", &["init", "-q", "-b", "main"]);
9277
    write(&g, "a.txt", b"a\n");
9278
    git("Grace [email protected]", &["add", "."]);
9279
    git("Grace [email protected]", &["commit", "-qm", "mine"]);
9280
    write(&g, "b.txt", b"b\n");
9281
    git("Ada [email protected]", &["add", "."]);
9282
    git("Ada [email protected]", &["commit", "-qm", "someone else's"]);
9283
9284
    let mut repo = Repo::init(&root.join("o")).unwrap();
9285
    let (key, _) = repo
9286
        .create_identity("Grace", "[email protected]", IdentityScope::Repo)
9287
        .unwrap();
9288
    repo.config.set("git.claim", "true").unwrap();
9289
    repo.save_config().unwrap();
9290
    let repo = Repo::open(&root.join("o")).unwrap();
9291
    repo.import_git(&g, "main").unwrap();
9292
    let v = repo.verify_git_import(&g, "main").unwrap();
9293
    assert!(v.mismatches.is_empty(), "{:?}", v.mismatches);
9294
    let heads = repo.bookmark_heads().unwrap();
9295
    let by_message: std::collections::HashMap<String, KeyId> = repo
9296
        .log_state(&heads)
9297
        .unwrap()
9298
        .into_iter()
9299
        .map(|e| {
9300
            (
9301
                e.change.message.lines().next().unwrap_or("").to_string(),
9302
                e.change.author,
9303
            )
9304
        })
9305
        .collect();
9306
    assert_eq!(by_message["mine"], key, "her own commit, any case of email");
9307
    assert_eq!(by_message["someone else's"], ObjectRef::ZERO, "not hers");
9308
}
9309
9310
/// oxygen#86: removing a remote removes all of it: every `remote.NAME.*`
9311
/// key (URL, token, CA), its tracking bookmarks, and nothing else.
9312
#[test]
9313
fn removing_a_remote_leaves_nothing_of_it() {
9314
    hermetic();
9315
    let dir = tempfile::tempdir().unwrap();
9316
    let origin = dir.path().join("origin");
9317
    Repo::init_bare_unbound(&origin).unwrap();
9318
    let main = dir.path().join("main");
9319
    let mut repo = Repo::init(&main).unwrap();
9320
    repo.config
9321
        .set("remote.origin.url", &origin.to_string_lossy())
9322
        .unwrap();
9323
    repo.config
9324
        .set("remote.origin.token", "secret-ish")
9325
        .unwrap();
9326
    repo.config
9327
        .set("remote.keep.url", &origin.to_string_lossy())
9328
        .unwrap();
9329
    repo.save_config().unwrap();
9330
    write(&main, "a.txt", b"a\n");
9331
    repo.commit("a", &[]).unwrap();
9332
    assert!(repo.push("origin", false).unwrap()[0].ok);
9333
    assert!(
9334
        repo.view().unwrap().remotes.contains_key("origin"),
9335
        "a tracking bookmark"
9336
    );
9337
9338
    repo.remove_remote("origin").unwrap();
9339
    let again = Repo::open(&main).unwrap();
9340
    assert!(
9341
        !again
9342
            .config
9343
            .repo_layer()
9344
            .keys()
9345
            .any(|k| k.starts_with("remote.origin.")),
9346
        "{:?}",
9347
        again.config.repo_layer()
9348
    );
9349
    assert!(!again.config.remotes.contains_key("origin"));
9350
    assert!(
9351
        !again.view().unwrap().remotes.contains_key("origin"),
9352
        "its tracking bookmarks go"
9353
    );
9354
    assert!(
9355
        again.config.remotes.contains_key("keep"),
9356
        "another remote stays"
9357
    );
9358
    let mut again = again;
9359
    assert!(
9360
        again.remove_remote("origin").is_err(),
9361
        "a second removal is refused"
9362
    );
9363
}
9364
9365
/// oxygenhub#126: a blob a host stored for itself (a job's artifact) is
9366
/// unreachable from history, so gc prunes it, unless the host names it:
9367
/// then it and its chunks stay, and it reads back whole.
9368
#[test]
9369
fn gc_keeps_the_blobs_a_host_names() {
9370
    hermetic();
9371
    let dir = tempfile::tempdir().unwrap();
9372
    let repo = Repo::init(dir.path()).unwrap();
9373
    write(dir.path(), "a.txt", b"a\n");
9374
    repo.commit("a", &[]).unwrap();
9375
    // Large enough to be several chunks.
9376
    let body: Vec<u8> = (0..400_000u32)
9377
        .flat_map(|i| (i.wrapping_mul(2654435761)).to_le_bytes())
9378
        .collect();
9379
    let kept = repo.store_blob(&body).unwrap();
9380
    let lost = repo.store_blob(b"an artifact nobody names").unwrap();
9381
    repo.gc_keeping(true, &[kept], &mut |_| {}).unwrap();
9382
    assert_eq!(repo.read_blob(&kept).unwrap(), body, "named: kept whole");
9383
    assert!(!repo.store().has(&lost), "not named: pruned");
9384
    repo.gc(true).unwrap();
9385
    assert!(!repo.store().has(&kept), "a plain gc prunes it");
9386
}
9387
9388
/// oxygen#99: undo in one workspace undoes that workspace's last command,
9389
/// never another workspace's, says what it undid, and goes further back
9390
/// when run again.
9391
#[test]
9392
fn undo_is_scoped_to_its_workspace() {
9393
    hermetic();
9394
    let dir = tempfile::tempdir().unwrap();
9395
    let root = dir.path().join("main");
9396
    let a = Repo::init(&root).unwrap();
9397
    write(&root, "base.txt", b"base\n");
9398
    let base = a.commit("base", &[]).unwrap();
9399
    a.bookmark_create("feature", None).unwrap();
9400
    let ws_dir = dir.path().join("ws");
9401
    let heads = a.resolve_heads("feature").unwrap();
9402
    let b = a
9403
        .workspace_add_on(&ws_dir, Some(&heads), Some("feature"))
9404
        .unwrap();
9405
9406
    // A commits on main, then B commits on feature: B's is the newest.
9407
    write(&root, "a.txt", b"a\n");
9408
    let ca = a.commit("from a", &[]).unwrap();
9409
    write(&ws_dir, "b.txt", b"b\n");
9410
    let cb = b.commit("from b", &[]).unwrap();
9411
9412
    // A's undo undoes A's commit and leaves B's.
9413
    let u = a.undo().unwrap();
9414
    assert_eq!(u.command, "oxy commit -m \"from a\"");
9415
    assert_eq!(u.others_kept, 1, "B's newer commit is left");
9416
    assert!(!u.changes.is_empty());
9417
    let view = a.view().unwrap();
9418
    // (Independent changes commute, so a bookmark's heads may hold base too.)
9419
    assert_eq!(a.heads_of(&view, "main").unwrap(), vec![base]);
9420
    assert!(
9421
        a.heads_of(&view, "feature").unwrap().contains(&cb),
9422
        "B's commit stands"
9423
    );
9424
    assert!(
9425
        a.store().get_change(&ca).is_ok(),
9426
        "the change itself is still in the store"
9427
    );
9428
    // A's working copy was clean, so its files followed; B's are untouched.
9429
    assert!(!root.join("a.txt").exists());
9430
    assert!(a.snapshot("oxy status").unwrap().statuses.is_empty());
9431
    assert!(ws_dir.join("b.txt").exists());
9432
9433
    // B's undo still finds B's own commit, under A's undo.
9434
    let u = b.undo().unwrap();
9435
    assert_eq!(u.command, "oxy commit -m \"from b\"");
9436
    assert!(!b
9437
        .heads_of(&b.view().unwrap(), "feature")
9438
        .unwrap()
9439
        .contains(&cb));
9440
    assert_eq!(
9441
        a.heads_of(&a.view().unwrap(), "main").unwrap(),
9442
        vec![base],
9443
        "A's undo stands"
9444
    );
9445
9446
    // A's next undo goes past the commit it already undid, to adding B's
9447
    // workspace: refused, since B has worked there since.
9448
    let e = a.undo().unwrap_err().to_string();
9449
    assert!(e.contains("the workspace at") && e.contains("ws"), "{e}");
9450
}
9451
9452
/// oxygen#99: two workspaces on one bookmark: an undo takes back only its
9453
/// own commit's head, and the other workspace's head stays.
9454
#[test]
9455
fn undo_on_a_shared_bookmark_keeps_the_other_workspaces_head() {
9456
    hermetic();
9457
    let dir = tempfile::tempdir().unwrap();
9458
    let root = dir.path().join("main");
9459
    let a = Repo::init(&root).unwrap();
9460
    write(&root, "base.txt", b"base\n");
9461
    a.commit("base", &[]).unwrap();
9462
    let ws_dir = dir.path().join("ws");
9463
    let b = a.workspace_add(&ws_dir, None).unwrap();
9464
    write(&root, "a.txt", b"a\n");
9465
    let ca = a.commit("from a", &[]).unwrap();
9466
    write(&ws_dir, "b.txt", b"b\n");
9467
    let cb = b.commit("from b", &[]).unwrap();
9468
    let u = a.undo().unwrap();
9469
    assert_eq!(u.command, "oxy commit -m \"from a\"");
9470
    let heads = a.heads_of(&a.view().unwrap(), "main").unwrap();
9471
    assert!(heads.contains(&cb) && !heads.contains(&ca), "{heads:?}");
9472
}
9473
9474
/// oxygen#99: an undo that would also take back what another workspace
9475
/// did since to the same bookmark is refused, naming it.
9476
#[test]
9477
fn undo_refuses_to_take_back_another_workspaces_work() {
9478
    hermetic();
9479
    let dir = tempfile::tempdir().unwrap();
9480
    let root = dir.path().join("main");
9481
    let a = Repo::init(&root).unwrap();
9482
    write(&root, "base.txt", b"base\n");
9483
    a.commit("base", &[]).unwrap();
9484
    let ws_dir = dir.path().join("ws");
9485
    let b = a.workspace_add(&ws_dir, None).unwrap();
9486
    // Both on main: A commits, then B builds on it, editing A's file.
9487
    write(&root, "a.txt", b"a\n");
9488
    a.commit("from a", &[]).unwrap();
9489
    b.refresh().unwrap();
9490
    let heads = b.resolve_heads("main").unwrap();
9491
    b.checkout(&heads, false, "oxy checkout").unwrap();
9492
    write(&ws_dir, "a.txt", b"a, then b\n");
9493
    b.commit("from b", &[]).unwrap();
9494
    let e = a.undo().unwrap_err().to_string();
9495
    assert!(
9496
        e.contains("bookmark main") && e.contains("builds on"),
9497
        "{e}"
9498
    );
9499
    assert!(e.contains("oxy op restore"), "{e}");
9500
}
9501
9502
/// oxygen#99: undoing a commit that was already pushed says so: the remote
9503
/// still has it.
9504
#[test]
9505
fn undo_says_when_the_commit_was_pushed() {
9506
    hermetic();
9507
    let dir = tempfile::tempdir().unwrap();
9508
    let root = dir.path();
9509
    Repo::init(&root.join("origin")).unwrap();
9510
    let url = root.join("origin").to_string_lossy().to_string();
9511
    let repo = Repo::clone(&url, &root.join("work"))
9512
        .unwrap()
9513
        .with_home(root.join("home"));
9514
    write(&root.join("work"), "a.txt", b"a\n");
9515
    repo.commit("a", &[]).unwrap();
9516
    assert!(repo.push("origin", false).unwrap()[0].ok);
9517
    // The push itself is passed over: the remote keeps what it was sent.
9518
    let u = repo.undo().unwrap();
9519
    assert_eq!(u.command, "oxy commit -m \"a\"");
9520
    assert_eq!(u.pushed, vec![("main".to_string(), "origin".to_string())]);
9521
}
9522
9523
/// oxygen#98: a new untracked file over snapshot.max-new-file-size is left
9524
/// out of the snapshot and named; tracked files and files already in the
9525
/// working copy are not.
9526
#[test]
9527
fn large_new_files_are_left_out_of_snapshots() {
9528
    hermetic();
9529
    let dir = tempfile::tempdir().unwrap();
9530
    let root = dir.path();
9531
    let mut repo = Repo::init(root).unwrap();
9532
    repo.config.max_new_file = 1024;
9533
    write(root, "small.txt", b"small\n");
9534
    write(root, "big.bin", &vec![0u8; 4096]);
9535
    let s = repo.snapshot("oxy status").unwrap();
9536
    let paths: Vec<_> = s.statuses.iter().map(|p| p.path.as_str()).collect();
9537
    assert_eq!(paths, ["small.txt"]);
9538
    assert_eq!(repo.skipped_large(), vec![("big.bin".to_string(), 4096)]);
9539
    repo.commit("small", &[]).unwrap();
9540
9541
    // A tracked file may grow past the limit.
9542
    write(root, "small.txt", &vec![b'x'; 4096]);
9543
    let s = repo.snapshot("oxy status").unwrap();
9544
    assert!(s.statuses.iter().any(|p| p.path == "small.txt"));
9545
    // With no limit the big file is taken in, and stays once it is.
9546
    repo.config.max_new_file = 0;
9547
    let s = repo.snapshot("oxy status").unwrap();
9548
    assert!(s.statuses.iter().any(|p| p.path == "big.bin"));
9549
    repo.config.max_new_file = 1024;
9550
    let s = repo.snapshot("oxy status").unwrap();
9551
    assert!(
9552
        s.statuses.iter().any(|p| p.path == "big.bin"),
9553
        "already in the working copy"
9554
    );
9555
    assert!(repo.skipped_large().is_empty());
9556
}
9557
9558
/// oxygen#98: a file only a past working-copy snapshot held is pruned once
9559
/// snapshots expire, and kept while they have not.
9560
#[test]
9561
fn gc_prunes_what_only_expired_snapshots_held() {
9562
    hermetic();
9563
    let dir = tempfile::tempdir().unwrap();
9564
    let root = dir.path();
9565
    let mut repo = Repo::init(root).unwrap();
9566
    repo.config.gc_grace_days = 0;
9567
    write(root, "a.txt", b"a\n");
9568
    repo.commit("a", &[]).unwrap();
9569
    let image: Vec<u8> = (0..200_000u32).map(|i| (i % 7) as u8).collect();
9570
    write(root, "image.tar", &image);
9571
    repo.snapshot("oxy status").unwrap();
9572
    std::fs::remove_file(root.join("image.tar")).unwrap();
9573
    repo.snapshot("oxy status").unwrap();
9574
    let blob = Repo::blob_ref(&image);
9575
    assert!(repo.store().has(&blob));
9576
    repo.gc(true).unwrap();
9577
    assert!(repo.store().has(&blob), "a recent snapshot keeps it");
9578
    repo.config.snapshot_retention_days = 0;
9579
    repo.gc(true).unwrap();
9580
    assert!(!repo.store().has(&blob), "an expired snapshot does not");
9581
    assert_eq!(
9582
        repo.file_at("a.txt", None).unwrap(),
9583
        b"a\n",
9584
        "committed files stay"
9585
    );
9586
}
9587
9588
/// oxygen#100: uncommitted work byte-for-byte what the bookmark switched to
9589
/// already has is no conflict: the switch goes through, nothing is lost,
9590
/// and other carried work still comes along.
9591
#[test]
9592
fn carrying_work_the_target_already_has_is_no_conflict() {
9593
    hermetic();
9594
    let dir = tempfile::tempdir().unwrap();
9595
    let root = dir.path();
9596
    let mut repo = Repo::init(root).unwrap();
9597
    write(root, "a.txt", b"one\n");
9598
    write(root, "b.txt", b"b\n");
9599
    repo.commit("one", &[]).unwrap();
9600
    repo.bookmark_create("landed", None).unwrap();
9601
    // On landed, a.txt becomes "two" (as a proposal landing would).
9602
    repo.bookmark_switch("landed", false).unwrap();
9603
    write(root, "a.txt", b"two\n");
9604
    repo.commit("two", &[]).unwrap();
9605
    repo.bookmark_switch("main", false).unwrap();
9606
    assert_eq!(std::fs::read(root.join("a.txt")).unwrap(), b"one\n");
9607
    // The same edit, uncommitted, on main; and another edit besides.
9608
    write(root, "a.txt", b"two\n");
9609
    write(root, "b.txt", b"b, edited\n");
9610
    let (_, carried) = repo.bookmark_switch_carry("landed").unwrap();
9611
    assert_eq!(
9612
        carried,
9613
        vec!["b.txt".to_string()],
9614
        "only the work landed lacks is carried"
9615
    );
9616
    assert_eq!(std::fs::read(root.join("a.txt")).unwrap(), b"two\n");
9617
    assert_eq!(std::fs::read(root.join("b.txt")).unwrap(), b"b, edited\n");
9618
    let s = repo.snapshot("oxy status").unwrap();
9619
    let paths: Vec<_> = s.statuses.iter().map(|p| p.path.as_str()).collect();
9620
    assert_eq!(paths, ["b.txt"]);
9621
9622
    // A real difference is still refused.
9623
    repo.bookmark_switch("main", true).unwrap();
9624
    write(root, "a.txt", b"three\n");
9625
    let e = repo
9626
        .bookmark_switch_carry("landed")
9627
        .unwrap_err()
9628
        .to_string();
9629
    assert!(e.contains("a.txt") && e.contains("--discard"), "{e}");
9630
}
9631
9632
/// oxygen#103: a full change hash as `--json` prints it, without `#`,
9633
/// resolves, so JSON output feeds back into commands.
9634
#[test]
9635
fn a_full_hash_resolves_without_its_hash_sign() {
9636
    hermetic();
9637
    let dir = tempfile::tempdir().unwrap();
9638
    let root = dir.path();
9639
    let repo = Repo::init(root).unwrap();
9640
    write(root, "a.txt", b"a\n");
9641
    let h = repo.commit("a", &[]).unwrap();
9642
    assert_eq!(repo.resolve_change(&h.to_hex()).unwrap(), h);
9643
    assert_eq!(repo.resolve_change(&format!("#{}", h.to_hex())).unwrap(), h);
9644
    assert!(repo
9645
        .resolve_change(&"0".repeat(64))
9646
        .unwrap_err()
9647
        .to_string()
9648
        .contains("no change matches"));
9649
}
9650
9651
#[test]
9652
fn a_pin_change_moves_only_the_pin() {
9653
    hermetic();
9654
    let dir = tempfile::tempdir().unwrap();
9655
    let root = dir.path();
9656
    let _lib_origin = Repo::init(&root.join("lib-origin")).unwrap();
9657
    let lib_url = root.join("lib-origin").to_string_lossy().to_string();
9658
    let lib = Repo::clone(&lib_url, &root.join("lib"))
9659
        .unwrap()
9660
        .with_home(root.join("home"));
9661
    write(&root.join("lib"), "lib.txt", b"v1\n");
9662
    lib.commit("lib v1", &[]).unwrap();
9663
    assert!(lib.push("origin", false).unwrap()[0].ok);
9664
    let _app_origin = Repo::init(&root.join("app-origin")).unwrap();
9665
    let app_dir = root.join("app");
9666
    let app = Repo::clone(&root.join("app-origin").to_string_lossy(), &app_dir)
9667
        .unwrap()
9668
        .with_home(root.join("home"));
9669
    write(&app_dir, "main.txt", b"app\n");
9670
    let pin1 = app.submodule_add(&lib_url, "libs/lib", None).unwrap();
9671
    let a1 = app.commit("app with lib", &[]).unwrap();
9672
    // The library moves on.
9673
    write(&root.join("lib"), "more.txt", b"v2\n");
9674
    let l2 = lib.commit("lib v2", &[]).unwrap();
9675
    let crate::subrepo::Pin::Oxy { repo, bookmark, .. } = pin1 else {
9676
        panic!("an Oxygen pin")
9677
    };
9678
    let pin2 = crate::subrepo::Pin::Oxy {
9679
        repo,
9680
        heads: vec![l2],
9681
        bookmark,
9682
    };
9683
    let author = app.store().get_change(&a1).unwrap().author;
9684
    let change = app
9685
        .build_pin_change(&[a1], "libs/lib", &pin2, "Move lib to v2", author)
9686
        .unwrap();
9687
    let mut state = app.load_state(&[a1]).unwrap();
9688
    state.add(change).unwrap();
9689
    let files = state.materialize().files;
9690
    assert_eq!(files["libs/lib"].kind, NodeKind::Subrepo);
9691
    let FileContent::Opaque { blobs } = &files["libs/lib"].content else {
9692
        panic!("a pin is opaque")
9693
    };
9694
    let read = crate::subrepo::Pin::decode(&app.read_blob(&blobs[0]).unwrap()).unwrap();
9695
    assert_eq!(read, pin2, "the new pin");
9696
    assert!(
9697
        matches!(&files["main.txt"].content, FileContent::Text { bytes, .. } if bytes.as_slice() == b"app\n"),
9698
        "nothing else changes"
9699
    );
9700
    // Only a subrepo's pin can be moved this way.
9701
    let e = app.build_pin_change(&[a1], "main.txt", &pin2, "x", author);
9702
    assert!(format!("{:?}", e.unwrap_err()).contains("not a subrepo"));
9703
    let e = app.build_pin_change(&[a1], "libs/none", &pin2, "x", author);
9704
    assert!(format!("{:?}", e.unwrap_err()).contains("does not exist"));
9705
}
9706
9707
/// oxygenhub#249: a handle reads the operation head once and keeps it,
9708
/// so one command or request never mixes two heads; another handle's
9709
/// operation shows only after `refresh`. Its own operations move it, and
9710
/// one recorded from the head it kept merges with what landed since, as
9711
/// any concurrent operation does.
9712
#[test]
9713
fn one_handle_keeps_one_head_until_it_refreshes() {
9714
    hermetic();
9715
    let dir = tempfile::tempdir().unwrap();
9716
    let root = dir.path();
9717
    let writer = Repo::init(root).unwrap();
9718
    write(root, "a.txt", b"one\n");
9719
    let h1 = writer.commit("one", &[]).unwrap();
9720
    let reader = Repo::open(root).unwrap();
9721
    let before = reader.view().unwrap();
9722
    assert_eq!(reader.bookmark_heads().unwrap(), vec![h1]);
9723
    write(root, "a.txt", b"two\n");
9724
    let h2 = writer.commit("two", &[]).unwrap();
9725
    assert_eq!(
9726
        writer.bookmark_heads().unwrap(),
9727
        vec![h2],
9728
        "its own operation"
9729
    );
9730
    assert_eq!(reader.view().unwrap(), before, "the head it read first");
9731
    assert_eq!(reader.bookmark_heads().unwrap(), vec![h1]);
9732
    reader.refresh().unwrap();
9733
    assert_eq!(reader.bookmark_heads().unwrap(), vec![h2]);
9734
9735
    // A handle recording from an older head merges with the newer one.
9736
    let stale = Repo::open(root).unwrap();
9737
    assert_eq!(stale.bookmark_heads().unwrap(), vec![h2]);
9738
    write(root, "a.txt", b"three\n");
9739
    let h3 = writer.commit("three", &[]).unwrap();
9740
    stale.bookmark_create("feature", Some(&[h1])).unwrap();
9741
    let view = stale.view().unwrap();
9742
    assert!(view.bookmarks.contains_key("feature"));
9743
    assert_eq!(
9744
        stale.bookmark_heads().unwrap(),
9745
        vec![h3],
9746
        "merged, not lost"
9747
    );
9748
    let fresh = Repo::open(root).unwrap();
9749
    assert_eq!(fresh.view().unwrap(), view);
9750
}
9751
9752
/// oxygenhub#249 over a store (a bucket's compare-and-swap): the same.
9753
#[test]
9754
fn over_a_store_one_handle_keeps_one_head() {
9755
    hermetic();
9756
    let backend = std::sync::Arc::new(crate::strata::MemoryStore::new());
9757
    crate::store::TEST_BACKEND.with(|t| *t.borrow_mut() = Some(backend.clone()));
9758
    let dir = tempfile::tempdir().unwrap();
9759
    let a = Repo::init(dir.path()).unwrap();
9760
    let (h0, _) = a.head_op().unwrap();
9761
    let b = Repo::open(dir.path()).unwrap();
9762
    assert_eq!(b.head_op().unwrap().0, h0);
9763
    let state = a.store.put_state(&StateObject::new(vec![])).unwrap();
9764
    let mut view = a.view().unwrap();
9765
    view.bookmarks.insert("x".into(), state);
9766
    let r = a.record_op(&[h0], "bookmark x", view).unwrap();
9767
    assert_eq!(a.head_op().unwrap().0, r);
9768
    assert_eq!(b.head_op().unwrap().0, h0, "b keeps its head");
9769
    b.refresh().unwrap();
9770
    assert_eq!(b.head_op().unwrap().0, r);
9771
    crate::store::TEST_BACKEND.with(|t| *t.borrow_mut() = None);
9772
}
9773
9774
/// oxygenhub#249: gc retires what it repacks rather than deleting it; a
9775
/// reader opened before reads on, then and after the next gc deletes the
9776
/// retired files once their hour is up. Younger ones are kept.
9777
#[test]
9778
fn gc_retires_and_a_later_gc_deletes_after_the_hour() {
9779
    hermetic();
9780
    let dir = tempfile::tempdir().unwrap();
9781
    let root = dir.path();
9782
    let repo = Repo::init(root).unwrap();
9783
    let mut heads = Vec::new();
9784
    for i in 0..4 {
9785
        write(root, &format!("f{i}.txt"), format!("{i}\n").as_bytes());
9786
        heads.push(repo.commit(&format!("c{i}"), &[]).unwrap());
9787
    }
9788
    let reader = Repo::open(root).unwrap();
9789
    assert_eq!(reader.log().unwrap().len(), 5);
9790
    let r = repo.gc(true).unwrap();
9791
    assert_eq!(r.retired, crate::store::RetiredReport::default());
9792
    assert_eq!(repo.store().loose_count().unwrap(), 0);
9793
    assert_eq!(reader.log().unwrap().len(), 5, "read on from what it had");
9794
    // Nothing is an hour old yet: a gc keeps it all.
9795
    let r = repo.gc(true).unwrap();
9796
    assert_eq!((r.retired.packs, r.retired.loose), (0, 0));
9797
    assert!(r.retired.kept > 0, "{r:?}");
9798
    write(root, "f9.txt", b"9\n");
9799
    heads.push(repo.commit("c9", &[]).unwrap());
9800
    crate::store::reader_tests::age_retired(
9801
        repo.store(),
9802
        crate::store::RETIRED_FOR + std::time::Duration::from_secs(60),
9803
    );
9804
    let r = repo.gc(true).unwrap();
9805
    assert!(r.retired.packs >= 1 && r.retired.loose > 0, "{r:?}");
9806
    assert_eq!(r.retired.kept, 0, "{r:?}");
9807
    let r = repo.gc(true).unwrap();
9808
    assert_eq!((r.retired.packs, r.retired.loose), (0, 0));
9809
    assert!(r.retired.kept > 0, "what the last gc retired is young");
9810
    // The reader opened before all of it still reads everything, from
9811
    // the packs it finds when what it loaded is gone.
9812
    assert_eq!(reader.log().unwrap().len(), 5);
9813
    for h in &heads[..4] {
9814
        reader.store().get_change(h).unwrap();
9815
    }
9816
    reader.refresh().unwrap();
9817
    assert_eq!(reader.log().unwrap().len(), 6);
9818
    let fresh = Repo::open(root).unwrap();
9819
    assert_eq!(
9820
        fresh.store().pack_count(),
9821
        1,
9822
        "retired packs are not loaded"
9823
    );
9824
}
9825
9826
/// oxygenhub#249: a repository opens when its store's pack listing names
9827
/// an index that is not there (deleted between the listing and the read).
9828
#[test]
9829
fn a_repository_opens_when_a_listed_index_is_gone() {
9830
    hermetic();
9831
    let backend = crate::store::reader_tests::racing(true);
9832
    let dyn_backend: std::sync::Arc<crate::store::Backend> = backend.clone();
9833
    crate::store::TEST_BACKEND.with(|t| *t.borrow_mut() = Some(dyn_backend));
9834
    let dir = tempfile::tempdir().unwrap();
9835
    let repo = Repo::init(dir.path()).unwrap();
9836
    write(dir.path(), "a.txt", b"a\n");
9837
    let h = repo.commit("a", &[]).unwrap();
9838
    repo.gc(true).unwrap();
9839
    let again = Repo::open(dir.path()).unwrap();
9840
    assert_eq!(again.store().pack_count(), 1);
9841
    assert_eq!(again.bookmark_heads().unwrap(), vec![h]);
9842
    // And when one is deleted between the listing and the read: a copy of
9843
    // the live pack, whose index goes as the store opens.
9844
    use crate::strata::Store as _;
9845
    let idx = backend
9846
        .list("pack-")
9847
        .unwrap()
9848
        .into_iter()
9849
        .map(|e| e.key)
9850
        .find(|k| k.ends_with(".idx") && k != "pack-0000.idx")
9851
        .unwrap();
9852
    let stem = idx.trim_end_matches(".idx");
9853
    for ext in ["pack", "idx"] {
9854
        let bytes = backend.get(&format!("{stem}.{ext}")).unwrap();
9855
        backend
9856
            .put_new(&format!("pack-copy.{ext}"), &bytes)
9857
            .unwrap();
9858
    }
9859
    *backend.doomed.lock().unwrap() = Some("pack-copy.idx".into());
9860
    let again = Repo::open(dir.path()).unwrap();
9861
    assert_eq!(again.store().pack_count(), 1);
9862
    assert_eq!(again.bookmark_heads().unwrap(), vec![h]);
9863
    assert!(!backend.has("pack-copy.idx").unwrap());
9864
    crate::store::TEST_BACKEND.with(|t| *t.borrow_mut() = None);
9865
}