OXYGENHUB
# f0ef9778e587 oxygen / crates / oxy-core / src / repo / tests.rs
365.8 KiB · Rust · last changed Old clients are not sent tags only a certificate authorizes (closes #131) 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
    // Without a policy every client is sent every tag, whatever features
3056
    // it declares (oxygen#131).
3057
    let mut refs = a.remote_refs().unwrap();
3058
    a.refs_for_client(&mut refs, None);
3059
    assert_eq!(refs.tags.len(), 1);
3060
    // Checkout by tag.
3061
    a.checkout(&a.resolve_heads("v1").unwrap(), false, "co")
3062
        .unwrap();
3063
    assert_eq!(fs::read(root.join("a/f.txt")).unwrap(), b"1\n");
3064
    a.checkout(&a.bookmark_heads().unwrap(), false, "co")
3065
        .unwrap();
3066
3067
    // Push carries the tag; a second attestation for the name is refused.
3068
    let r = a.push("origin", false).unwrap();
3069
    origin.refresh().unwrap();
3070
    assert!(r.iter().any(|x| x.name == "tags/v1" && x.ok), "{r:?}");
3071
    assert_eq!(origin.tag_heads("v1").unwrap(), Some(vec![h1]));
3072
    let mut forged = a
3073
        .tag_refs()
3074
        .unwrap()
3075
        .into_iter()
3076
        .find(|t| t.name == "v1")
3077
        .unwrap();
3078
    forged.state = origin
3079
        .store()
3080
        .put_state(&StateObject::new(vec![h2]))
3081
        .unwrap();
3082
    forged.heads = vec![h2];
3083
    forged.attestation = None;
3084
    let r = origin
3085
        .receive_push(Bundle::default(), vec![], None, vec![forged])
3086
        .unwrap();
3087
    assert!(!r[0].ok && r[0].reason.contains("immutable"), "{r:?}");
3088
3089
    // A clone gets the tag; a later tag arrives on fetch.
3090
    let b = Repo::clone(&url, &root.join("b"))
3091
        .unwrap()
3092
        .with_home(root.join("home-b"));
3093
    assert_eq!(b.tag_heads("v1").unwrap(), Some(vec![h1]));
3094
    assert!(b.tags().unwrap()[0].signer.as_deref() == Some("Ada"));
3095
    a.tag_create("v2", &[h2], "second").unwrap();
3096
    a.push("origin", false).unwrap();
3097
    origin.refresh().unwrap();
3098
    let rep = b.fetch("origin").unwrap();
3099
    assert_eq!(rep.new_tags, 1);
3100
    assert_eq!(b.tag_heads("v2").unwrap(), Some(vec![h2]));
3101
3102
    // Under a policy, an unattested tag is refused and an attested one by the root passes.
3103
    a.policy_init().unwrap();
3104
    a.push("origin", false).unwrap();
3105
    origin.refresh().unwrap();
3106
    let unattested = crate::protocol::TagRef::new(
3107
        "v3".into(),
3108
        origin
3109
            .store()
3110
            .put_state(&StateObject::new(vec![h2]))
3111
            .unwrap(),
3112
        vec![h2],
3113
        None,
3114
    );
3115
    let r = origin
3116
        .receive_push(Bundle::default(), vec![], None, vec![unattested])
3117
        .unwrap();
3118
    assert!(!r[0].ok && r[0].reason.contains("attestation"), "{r:?}");
3119
    a.tag_create("v3", &[h2], "").unwrap();
3120
    let r = a.push("origin", false).unwrap();
3121
    origin.refresh().unwrap();
3122
    assert!(r.iter().any(|x| x.name == "tags/v3" && x.ok), "{r:?}");
3123
    assert!(a.gc(true).is_ok());
3124
    assert_eq!(a.tags().unwrap().len(), 3, "tags survive gc");
3125
3126
    // After a rotation the policy names only the new key, yet a fresh clone
3127
    // still takes the tags the old key made before it; the old key makes
3128
    // nothing new.
3129
    let rot = a.rotate_identity().unwrap();
3130
    let r = a.push("origin", false).unwrap();
3131
    origin.refresh().unwrap();
3132
    assert!(r.iter().all(|x| x.ok), "{r:?}");
3133
    let c = Repo::clone(&url, &root.join("c"))
3134
        .unwrap()
3135
        .with_home(root.join("home-c"));
3136
    assert_eq!(c.tag_heads("v3").unwrap(), Some(vec![h2]));
3137
    let (_, sp) = c.current_policy().unwrap().unwrap();
3138
    assert!(!sp.policy.authorizes(&key_a, "tags/v9"));
3139
    let made = c.identity(&rot.new).unwrap().created;
3140
    assert!(c.predecessor_authorized(&sp.policy, &key_a, "tags/v9", made - 1));
3141
    assert!(!c.predecessor_authorized(&sp.policy, &key_a, "tags/v9", made));
3142
    assert!(!c.predecessor_authorized(&sp.policy, &rot.new, "tags/v9", 0));
3143
}
3144
3145
#[test]
3146
fn multiple_workspaces_share_a_repository() {
3147
    hermetic();
3148
    let dir = tempfile::tempdir().unwrap();
3149
    let root = dir.path();
3150
    let main_dir = root.join("main");
3151
    let repo = Repo::init(&main_dir).unwrap().with_home(root.join("home"));
3152
    write(&main_dir, "a.txt", b"a\n");
3153
    let h1 = repo.commit("a", &[]).unwrap();
3154
    assert_eq!(repo.workspaces().unwrap().len(), 1);
3155
3156
    // A second workspace elsewhere, checked out on the bookmark.
3157
    let ws_dir = root.join("ws2");
3158
    let ws = repo.workspace_add(&ws_dir, None).unwrap();
3159
    assert!(ws_dir.join(".oxy").is_file());
3160
    assert_eq!(fs::read(ws_dir.join("a.txt")).unwrap(), b"a\n");
3161
    assert_ne!(ws.workspace(), repo.workspace());
3162
    let list = repo.workspaces().unwrap();
3163
    assert_eq!(list.len(), 2);
3164
    assert!(list
3165
        .iter()
3166
        .any(|w| w.id == ws.workspace() && w.path == ws_dir.canonicalize().unwrap() && !w.current));
3167
    assert!(!ws.snapshot("status").unwrap().changed);
3168
3169
    // Work in the second workspace: its own working copy, shared bookmark.
3170
    write(&ws_dir, "b.txt", b"b\n");
3171
    let s = ws.snapshot("status").unwrap();
3172
    assert_eq!(s.statuses.len(), 1);
3173
    assert!(
3174
        !repo.snapshot("status").unwrap().changed,
3175
        "the first workspace is untouched"
3176
    );
3177
    let h2 = ws.commit("b from ws2", &[]).unwrap();
3178
    repo.refresh().unwrap();
3179
    let mut heads = repo.bookmark_heads().unwrap();
3180
    heads.sort();
3181
    let mut want = vec![h1, h2];
3182
    want.sort();
3183
    assert_eq!(heads, want, "both workspaces see the bookmark move");
3184
    assert!(!main_dir.join("b.txt").exists());
3185
    repo.checkout(&repo.bookmark_heads().unwrap(), false, "co")
3186
        .unwrap();
3187
    assert!(main_dir.join("b.txt").exists());
3188
3189
    // Reopening from inside the second workspace finds the shared repository.
3190
    let reopened = Repo::open(&ws_dir).unwrap();
3191
    assert_eq!(reopened.workspace(), ws.workspace());
3192
    assert_eq!(reopened.id().unwrap(), repo.id().unwrap());
3193
    assert_eq!(reopened.quick_status().unwrap().heads, 2);
3194
3195
    // Workspaces cannot nest; forget drops one from the view but keeps files.
3196
    assert!(repo.workspace_add(&main_dir.join("inner"), None).is_err());
3197
    assert!(repo.workspace_forget(&repo.workspace()).is_err());
3198
    repo.workspace_forget(&ws.workspace()).unwrap();
3199
    assert_eq!(repo.workspaces().unwrap().len(), 1);
3200
    assert!(ws_dir.join("b.txt").exists());
3201
    assert!(
3202
        ws.snapshot("status").is_err(),
3203
        "a forgotten workspace is no longer in the view"
3204
    );
3205
3206
    // The working-copy lock: re-entrant in a thread; a lock whose process
3207
    // is gone is taken over, and a live process's is not, however old.
3208
    let lock = repo.lock_snapshot().unwrap();
3209
    let again = repo.lock_working_copy().unwrap();
3210
    drop(again);
3211
    drop(lock);
3212
    let lock_path = main_dir
3213
        .join(".oxy/workspaces")
3214
        .join(repo.workspace().to_hex())
3215
        .join("lock");
3216
    let old = std::time::SystemTime::now() - std::time::Duration::from_secs(120);
3217
    let age = |p: &Path| fs::File::open(p).unwrap().set_modified(old).unwrap();
3218
    fs::write(&lock_path, std::process::id().to_string()).unwrap();
3219
    age(&lock_path);
3220
    assert!(
3221
        !super::workspace::lock_is_stale(&lock_path),
3222
        "a live process keeps its lock"
3223
    );
3224
    fs::write(&lock_path, "4294967295").unwrap();
3225
    age(&lock_path);
3226
    assert!(repo.lock_snapshot().is_ok(), "stale lock taken over");
3227
}
3228
3229
#[test]
3230
fn attributes_binary_eol_nocompress_lockable() {
3231
    hermetic();
3232
    let dir = tempfile::tempdir().unwrap();
3233
    let root = dir.path();
3234
    let repo = Repo::init(root).unwrap().with_home(root.join("home"));
3235
    write(
3236
        root,
3237
        ".oxyattributes",
3238
        b"*.dat binary nocompress\n*.txt eol=crlf\nassets/** lockable\n",
3239
    );
3240
    write(root, "plain.dat", b"no nul bytes here\n");
3241
    write(root, "notes.txt", b"one\r\ntwo\r\n");
3242
    write(root, "assets/model.bin", b"\0model");
3243
    let h = repo.commit("attrs", &[]).unwrap();
3244
    let snap = repo.load_state(&[h]).unwrap().materialize();
3245
    assert!(
3246
        snap.files["plain.dat"].mode.opaque,
3247
        "binary attribute forces opaque without NUL bytes"
3248
    );
3249
    assert!(
3250
        matches!(&snap.files["notes.txt"].content, FileContent::Text { bytes, .. } if bytes == b"one\ntwo\n"),
3251
        "stored with LF"
3252
    );
3253
    assert!(
3254
        !repo.snapshot("status").unwrap().changed,
3255
        "CRLF on disk equals LF in the state"
3256
    );
3257
    // nocompress chunks pack raw.
3258
    let r = repo.gc(true).unwrap();
3259
    assert!(r.packed.objects > 0);
3260
    // Checkout writes CRLF for eol=crlf and makes lockable files read-only.
3261
    fs::remove_file(root.join("notes.txt")).unwrap();
3262
    repo.checkout(&[h], true, "co").unwrap();
3263
    assert_eq!(fs::read(root.join("notes.txt")).unwrap(), b"one\r\ntwo\r\n");
3264
    assert!(fs::metadata(root.join("assets/model.bin"))
3265
        .unwrap()
3266
        .permissions()
3267
        .readonly());
3268
    assert!(repo.lock_path("plain.dat").is_err(), "not lockable");
3269
    repo.lock_path("assets/model.bin").unwrap();
3270
    assert!(!fs::metadata(root.join("assets/model.bin"))
3271
        .unwrap()
3272
        .permissions()
3273
        .readonly());
3274
    assert!(repo.is_locked("assets/model.bin"));
3275
    write(root, "assets/model.bin", b"\0model2");
3276
    repo.commit("edit model", &[]).unwrap();
3277
    repo.unlock_path("assets/model.bin").unwrap();
3278
    assert!(fs::metadata(root.join("assets/model.bin"))
3279
        .unwrap()
3280
        .permissions()
3281
        .readonly());
3282
    // A later checkout can still overwrite a read-only lockable file.
3283
    repo.checkout(&[h], true, "co").unwrap();
3284
    assert_eq!(fs::read(root.join("assets/model.bin")).unwrap(), b"\0model");
3285
}
3286
3287
#[cfg(unix)]
3288
#[test]
3289
fn hooks_can_veto_observe_and_add_dependencies() {
3290
    use std::os::unix::fs::PermissionsExt;
3291
    hermetic();
3292
    let dir = tempfile::tempdir().unwrap();
3293
    let root = dir.path();
3294
    let mut repo = Repo::init(root).unwrap().with_home(root.join("home"));
3295
    let hooks = root.join(".oxy/hooks");
3296
    fs::create_dir_all(&hooks).unwrap();
3297
    let hook = |name: &str, body: &str| {
3298
        let p = hooks.join(name);
3299
        fs::write(&p, format!("#!/bin/sh\n{body}\n")).unwrap();
3300
        fs::set_permissions(&p, fs::Permissions::from_mode(0o755)).unwrap();
3301
    };
3302
    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");
3303
    hook("post-commit", "cat > \"$OXY_ROOT/.last-post-commit\"");
3304
    hook("post-checkout", "cat > \"$OXY_ROOT/.last-post-checkout\"");
3305
    hook("pre-push", "echo pushing blocked >&2; exit 3");
3306
    write(root, ".oxyignore", b".last-*\n");
3307
    write(root, "a.txt", b"a\n");
3308
    let err = repo.commit("WIP: nope", &[]).unwrap_err().to_string();
3309
    assert!(err.contains("pre-commit refused: no WIP commits"), "{err}");
3310
    let h1 = repo.commit("first", &[]).unwrap();
3311
    let pre = fs::read_to_string(root.join(".last-pre-commit")).unwrap();
3312
    assert!(
3313
        pre.contains("\"event\":\"pre-commit\"")
3314
            && pre.contains("\"path\":\"a.txt\"")
3315
            && pre.contains("\"message\":\"first\""),
3316
        "{pre}"
3317
    );
3318
    let post = fs::read_to_string(root.join(".last-post-commit")).unwrap();
3319
    assert!(post.contains(&h1.to_hex()), "{post}");
3320
    repo.checkout(&[h1], false, "co").unwrap();
3321
    assert!(fs::read_to_string(root.join(".last-post-checkout"))
3322
        .unwrap()
3323
        .contains("post-checkout"));
3324
    repo.config.set("remote.origin.url", "/nowhere").unwrap();
3325
    repo.save_config().unwrap();
3326
    let err = repo.push("origin", false).unwrap_err().to_string();
3327
    assert!(err.contains("pre-push refused: pushing blocked"), "{err}");
3328
3329
    // semantic-deps: only when enabled; adds an explicit dependency.
3330
    write(root, "b.txt", b"b\n");
3331
    hook(
3332
        "semantic-deps",
3333
        &format!(
3334
            "cat > \"$OXY_ROOT/.last-semantic\"; echo '{{\"deps\": [\"{}\"]}}'",
3335
            h1.to_hex()
3336
        ),
3337
    );
3338
    let h2 = repo.commit("b without hook", &[]).unwrap();
3339
    assert!(
3340
        repo.store().get_change(&h2).unwrap().deps.is_empty(),
3341
        "hook disabled by default"
3342
    );
3343
    repo.config.set("hooks.semantic-deps", "true").unwrap();
3344
    repo.save_config().unwrap();
3345
    write(root, "c.txt", b"c\n");
3346
    let h3 = repo.commit("c with hook", &[]).unwrap();
3347
    assert_eq!(repo.store().get_change(&h3).unwrap().deps, vec![h1]);
3348
    let sem = fs::read_to_string(root.join(".last-semantic")).unwrap();
3349
    assert!(
3350
        sem.contains("\"touched_paths\":[\"c.txt\"]") && sem.contains("candidate_deps"),
3351
        "{sem}"
3352
    );
3353
    assert_eq!(json_str("a\"b\\c\n"), "\"a\\\"b\\\\c\\n\"");
3354
}
3355
3356
#[test]
3357
fn amend_into_older_change_and_split() {
3358
    hermetic();
3359
    let dir = tempfile::tempdir().unwrap();
3360
    let root = dir.path();
3361
    let mut repo = Repo::init(root).unwrap().with_home(root.join("home"));
3362
    repo.create_identity("Ada", "a@b", IdentityScope::User)
3363
        .unwrap();
3364
    repo.set_user_config("core.sign", "change").unwrap();
3365
    write(root, "a.txt", b"one\ntwo\n");
3366
    let h0 = repo.commit("base", &[]).unwrap();
3367
    write(root, "a.txt", b"one\nTWO\n");
3368
    let h1 = repo.commit("edit two", &[]).unwrap();
3369
    write(root, "a.txt", b"one\nTWO\nthree\n");
3370
    let h2 = repo.commit("add three", &[]).unwrap();
3371
    let id1 = repo.store().get_change(&h1).unwrap().change_id;
3372
3373
    // Fixing the line h1 introduced folds into h1; h2 is rewritten on top.
3374
    write(root, "a.txt", b"one\nTWO!\nthree\n");
3375
    let h1b = repo.amend_into(&h1, None).unwrap();
3376
    assert_ne!(h1b, h1);
3377
    let c1b = repo.store().get_change(&h1b).unwrap();
3378
    assert_eq!(c1b.change_id, id1);
3379
    assert_eq!(c1b.deps, vec![h0]);
3380
    assert!(matches!(
3381
        repo.verify_change(&h1b).unwrap(),
3382
        SignatureStatus::Valid { .. }
3383
    ));
3384
    let heads = repo.bookmark_heads().unwrap();
3385
    assert_eq!(heads.len(), 1);
3386
    let top = repo.store().get_change(&heads[0]).unwrap();
3387
    assert_eq!(top.message, "add three");
3388
    assert_eq!(
3389
        top.deps.iter().copied().collect::<BTreeSet<_>>(),
3390
        [h0, h1b].into_iter().collect(),
3391
        "depends on the file's creator and the rewritten line"
3392
    );
3393
    let snap = repo.load_state(&heads).unwrap().materialize();
3394
    assert!(
3395
        matches!(&snap.files["a.txt"].content, FileContent::Text { bytes, .. } if bytes == b"one\nTWO!\nthree\n")
3396
    );
3397
    assert!(
3398
        !repo.snapshot("status").unwrap().changed,
3399
        "the working copy is clean after folding"
3400
    );
3401
    // Only h1b's own state shows the fix without "three".
3402
    let only = repo.load_state(&[h1b]).unwrap().materialize();
3403
    assert!(
3404
        matches!(&only.files["a.txt"].content, FileContent::Text { bytes, .. } if bytes == b"one\nTWO!\n")
3405
    );
3406
    assert_eq!(repo.log().unwrap().len(), 4);
3407
3408
    // An edit to a line introduced by h2 cannot fold into h1.
3409
    write(root, "a.txt", b"one\nTWO!\nthree!\n");
3410
    let err = repo.amend_into(&h1b, None).unwrap_err().to_string();
3411
    assert!(err.contains("introduced after"), "{err}");
3412
    assert!(
3413
        repo.snapshot("status").unwrap().statuses.len() == 1,
3414
        "nothing was changed by the refusal"
3415
    );
3416
    write(root, "a.txt", b"one\nTWO!\nthree\n");
3417
3418
    // Split the head that touches two files.
3419
    write(root, "b.txt", b"b\n");
3420
    write(root, "c.txt", b"c\n");
3421
    let h3 = repo.commit("b and c", &[]).unwrap();
3422
    let id3 = repo.store().get_change(&h3).unwrap().change_id;
3423
    let (p1, p2) = repo.split(&h3, &["b.txt".into()]).unwrap();
3424
    let c_1 = repo.store().get_change(&p1).unwrap();
3425
    let c_2 = repo.store().get_change(&p2).unwrap();
3426
    assert!(c_1.message.contains("part 1: b.txt"));
3427
    assert_eq!(c_2.change_id, id3);
3428
    let heads: BTreeSet<_> = repo.bookmark_heads().unwrap().into_iter().collect();
3429
    assert!(
3430
        heads.contains(&p1) && heads.contains(&p2),
3431
        "independent parts are both heads"
3432
    );
3433
    let snap = repo
3434
        .load_state(&repo.bookmark_heads().unwrap())
3435
        .unwrap()
3436
        .materialize();
3437
    assert!(snap.files.contains_key("b.txt") && snap.files.contains_key("c.txt"));
3438
    let only1 = repo.load_state(&[p1]).unwrap().materialize();
3439
    assert!(only1.files.contains_key("b.txt") && !only1.files.contains_key("c.txt"));
3440
    assert!(!repo.snapshot("status").unwrap().changed);
3441
    assert!(repo.split(&p2, &["nope.txt".into()]).is_err());
3442
    let _ = h2;
3443
}
3444
3445
#[test]
3446
fn identity_lifecycle() {
3447
    hermetic();
3448
    let dir = tempfile::tempdir().unwrap();
3449
    let root = dir.path();
3450
    let origin = Repo::init(&root.join("origin")).unwrap();
3451
    let url = root.join("origin").to_string_lossy().to_string();
3452
    let mut a = Repo::clone(&url, &root.join("a"))
3453
        .unwrap()
3454
        .with_home(root.join("home-a"));
3455
    a.set_user_config("core.sign", "change").unwrap();
3456
    let (key_a, _) = a
3457
        .create_identity("Ada", "[email protected]", IdentityScope::User)
3458
        .unwrap();
3459
    write(&root.join("a"), "a.txt", b"a\n");
3460
    let h1 = a.commit("one", &[]).unwrap();
3461
    assert!(a.policy_init().unwrap().applied);
3462
    assert!(a.push("origin", false).unwrap().iter().all(|r| r.ok));
3463
    origin.refresh().unwrap();
3464
3465
    // Expiry: an identity that had expired when the change was made does not authenticate it.
3466
    let mut e = Repo::init(&root.join("e"))
3467
        .unwrap()
3468
        .with_home(root.join("home-e"));
3469
    e.set_user_config("core.sign", "change").unwrap();
3470
    e.create_identity_with(
3471
        "Eve",
3472
        "[email protected]",
3473
        IdentityScope::User,
3474
        Some(Hlc::now().wall_ms - 1),
3475
    )
3476
    .unwrap();
3477
    write(&root.join("e"), "e.txt", b"e\n");
3478
    let he = e.commit("late", &[]).unwrap();
3479
    assert!(
3480
        matches!(e.verify_change(&he).unwrap(), SignatureStatus::Invalid(m) if m.contains("expired"))
3481
    );
3482
    // Renewal re-issues the identity (same keys, new KeyId) with a later expiry.
3483
    let r = e
3484
        .renew_identity(Some(Hlc::now().wall_ms + 86_400_000))
3485
        .unwrap();
3486
    assert_eq!(e.identity(&r.new).unwrap().previous, Some(r.old));
3487
    write(&root.join("e"), "e.txt", b"e2\n");
3488
    let he2 = e.commit("in time", &[]).unwrap();
3489
    assert!(
3490
        matches!(e.verify_change(&he2).unwrap(), SignatureStatus::Valid { key, .. } if key == r.new)
3491
    );
3492
3493
    // Rotation: a fresh key; the old change still verifies; the policy follows.
3494
    let r = a.rotate_identity().unwrap();
3495
    assert_eq!(r.old, key_a);
3496
    assert_eq!(a.config.author_key, Some(r.new));
3497
    assert_eq!(a.identity(&r.new).unwrap().previous, Some(key_a));
3498
    assert!(r.policy.as_ref().unwrap().applied);
3499
    let (_, sp) = a.current_policy().unwrap().unwrap();
3500
    assert_eq!(
3501
        (sp.policy.serial, sp.policy.roots.clone()),
3502
        (2, vec![r.new])
3503
    );
3504
    assert!(
3505
        !sp.policy.revoked.contains(&key_a) && sp.policy.authorizes(&r.new, "main"),
3506
        "superseded, not revoked"
3507
    );
3508
    assert!(sp.policy.succeeds(&r.new, &key_a) && !sp.policy.succeeds(&key_a, &r.new));
3509
    assert!(
3510
        matches!(a.verify_change(&h1).unwrap(), SignatureStatus::Valid { key, revoked: false, .. } if key == key_a)
3511
    );
3512
    write(&root.join("a"), "a.txt", b"a2\n");
3513
    let h2 = a.commit("two", &[]).unwrap();
3514
    assert!(
3515
        matches!(a.verify_change(&h2).unwrap(), SignatureStatus::Valid { key, revoked: false, .. } if key == r.new)
3516
    );
3517
    // Origin accepts the rotated policy (signed by the old root) and the new key's change.
3518
    let res = a.push("origin", false).unwrap();
3519
    origin.refresh().unwrap();
3520
    assert!(res.iter().all(|x| x.ok), "{res:?}");
3521
    assert_eq!(origin.current_policy().unwrap().unwrap().1.policy.serial, 2);
3522
    let key_a = r.new;
3523
3524
    // Delegation: Bob may sign on Ada's behalf. Delegates live in the
3525
    // identity object, so Ada's KeyId changes while her keys stay the same.
3526
    let mut b = Repo::clone(&url, &root.join("b"))
3527
        .unwrap()
3528
        .with_home(root.join("home-b"));
3529
    let (key_b, id_b) = b
3530
        .create_identity("Bob", "[email protected]", IdentityScope::User)
3531
        .unwrap();
3532
    let r = a.delegate_add(id_b.clone(), Scope::ALL, None).unwrap();
3533
    assert_eq!(r.old, key_a);
3534
    let key_a2 = r.new;
3535
    assert_eq!(
3536
        a.identity(&key_a2).unwrap().delegates,
3537
        vec![Delegate::full(key_b)]
3538
    );
3539
    assert_eq!(
3540
        a.identity(&key_a2).unwrap().ed25519_pk,
3541
        a.identity(&key_a).unwrap().ed25519_pk
3542
    );
3543
    assert!(
3544
        a.delegate_add(id_b.clone(), Scope::ALL, None).is_err(),
3545
        "already a delegate"
3546
    );
3547
    assert!(a.push("origin", false).unwrap().iter().all(|x| x.ok));
3548
    origin.refresh().unwrap();
3549
    write(&root.join("a"), "a.txt", b"a3\n");
3550
    let h3 = a.commit("three", &[]).unwrap();
3551
    assert!(
3552
        matches!(a.verify_change(&h3).unwrap(), SignatureStatus::Valid { key, .. } if key == key_a2),
3553
        "the same secret signs under the new KeyId"
3554
    );
3555
    // A change authored by Ada but signed only by Bob verifies through the delegation.
3556
    a.set_user_config("core.sign", "seal").unwrap();
3557
    write(&root.join("a"), "a.txt", b"a4\n");
3558
    let h4 = a.commit("four", &[]).unwrap();
3559
    assert_eq!(a.verify_change(&h4).unwrap(), SignatureStatus::Unsigned);
3560
    let (_, sk_b) = b.secret_key().unwrap().unwrap();
3561
    a.store()
3562
        .put_signature(&h4, &sk_b.sign(Domain::Change, &key_b, &h4))
3563
        .unwrap();
3564
    assert!(
3565
        matches!(a.verify_change(&h4).unwrap(), SignatureStatus::Valid { key, .. } if key == key_b)
3566
    );
3567
    a.set_user_config("core.sign", "change").unwrap();
3568
    // Withdrawing the delegation re-issues the identity again.
3569
    let r = a.delegate_remove(&key_b).unwrap();
3570
    assert!(a.identity(&r.new).unwrap().delegates.is_empty());
3571
    assert!(a.delegate_remove(&key_b).is_err());
3572
    let key_a3 = r.new;
3573
    let res = a.push("origin", false).unwrap();
3574
    origin.refresh().unwrap();
3575
    assert!(res.iter().all(|x| x.ok), "{res:?}");
3576
3577
    // Multi-signer policy: Bob becomes a root and the threshold rises to 2,
3578
    // both applied under the old threshold of 1. A grant then needs Bob too.
3579
    assert!(a.policy_root_add(id_b.clone()).unwrap().applied);
3580
    assert!(a.policy_root_add(id_b.clone()).is_err());
3581
    assert!(a.policy_set_threshold(3).is_err());
3582
    assert!(a.policy_set_threshold(2).unwrap().applied);
3583
    assert!(a.push("origin", false).unwrap().iter().all(|x| x.ok));
3584
    origin.refresh().unwrap();
3585
    b.pull("origin").unwrap();
3586
    assert_eq!(
3587
        b.current_policy().unwrap().unwrap().1.policy.root_threshold,
3588
        2
3589
    );
3590
    let mut c = Repo::init(&root.join("c"))
3591
        .unwrap()
3592
        .with_home(root.join("home-c"));
3593
    let (key_c, id_c) = c
3594
        .create_identity("Cy", "[email protected]", IdentityScope::User)
3595
        .unwrap();
3596
    let serial_before = a.current_policy().unwrap().unwrap().1.policy.serial;
3597
    let proposal = a.policy_grant(id_c, None).unwrap();
3598
    assert!(!proposal.applied && proposal.sigs.len() == 1);
3599
    assert_eq!(proposal.policy.serial, serial_before + 1);
3600
    assert_eq!(
3601
        a.current_policy().unwrap().unwrap().1.policy.serial,
3602
        serial_before,
3603
        "a proposal changes nothing yet"
3604
    );
3605
    // Bob signs the proposal, handed over as a file, and it applies for him.
3606
    let bytes = proposal.signed().encode();
3607
    let signed = b
3608
        .policy_sign(SignedPolicy::decode(&bytes).unwrap())
3609
        .unwrap();
3610
    assert!(signed.applied && signed.sigs.len() == 2);
3611
    assert!(b
3612
        .current_policy()
3613
        .unwrap()
3614
        .unwrap()
3615
        .1
3616
        .policy
3617
        .authorizes(&key_c, "main"));
3618
    assert!(
3619
        b.policy_sign(signed.signed()).is_err(),
3620
        "a stale proposal is refused"
3621
    );
3622
    // Bob publishes it and Ada picks it up.
3623
    assert!(b
3624
        .push("origin", false)
3625
        .unwrap()
3626
        .iter()
3627
        .any(|x| x.name == "policy" && x.ok));
3628
    origin.refresh().unwrap();
3629
    a.pull("origin").unwrap();
3630
    assert_eq!(
3631
        a.current_policy().unwrap().unwrap().1.policy.serial,
3632
        serial_before + 1
3633
    );
3634
    // A root cannot revoke itself; revoking Cy needs both roots but is recorded locally at once.
3635
    assert!(a.policy_revoke(&key_a3).is_err());
3636
    let u = a
3637
        .revoke_identity(&key_c, "left the project")
3638
        .unwrap()
3639
        .unwrap();
3640
    assert!(!u.applied);
3641
    assert!(a.is_revoked(&key_c).unwrap());
3642
    assert!(!b.is_revoked(&key_c).unwrap());
3643
    let u = b.policy_sign(u.signed()).unwrap();
3644
    assert!(u.applied && u.policy.is_revoked(&key_c));
3645
    assert!(b.is_revoked(&key_c).unwrap());
3646
    // Bob can revoke Ada's root key, leaving himself as the only root (threshold 2 would be unmeetable).
3647
    assert!(
3648
        b.policy_revoke(&key_a3).is_err(),
3649
        "would leave one root for a threshold of 2"
3650
    );
3651
    // Revoking one's own key without a policy root works locally: a plain marker plus attestation.
3652
    let key_c_own = c.config.author_key.unwrap();
3653
    assert!(c
3654
        .revoke_identity(&key_c_own, "lost laptop")
3655
        .unwrap()
3656
        .is_none());
3657
    assert!(c.is_revoked(&key_c_own).unwrap());
3658
    assert_eq!(key_c_own, key_c);
3659
}
3660
3661
#[test]
3662
fn renames_are_detected_and_tracked_as_moves() {
3663
    hermetic();
3664
    let dir = tempfile::tempdir().unwrap();
3665
    let root = dir.path();
3666
    let repo = Repo::init(root).unwrap().with_home(root.join("home"));
3667
    write(
3668
        root,
3669
        "src/old.rs",
3670
        b"fn a() {}\nfn b() {}\nfn c() {}\nfn d() {}\n",
3671
    );
3672
    write(root, "img.bin", b"\x89PNG\0\0\x01\x02");
3673
    write(root, "tiny.txt", b"x\n");
3674
    let h1 = repo.commit("base", &[]).unwrap();
3675
    let node_old = repo.load_state(&[h1]).unwrap().materialize().files["src/old.rs"].node;
3676
    let node_img = repo.load_state(&[h1]).unwrap().materialize().files["img.bin"].node;
3677
3678
    // Rename with a small edit, a binary moved unchanged, and a rewrite
3679
    // that shares nothing with the removed file.
3680
    fs::remove_file(root.join("src/old.rs")).unwrap();
3681
    write(
3682
        root,
3683
        "lib/new.rs",
3684
        b"fn a() {}\nfn b() {}\nfn c() {}\nfn e() {}\n",
3685
    );
3686
    fs::remove_file(root.join("img.bin")).unwrap();
3687
    write(root, "assets/img.bin", b"\x89PNG\0\0\x01\x02");
3688
    fs::remove_file(root.join("tiny.txt")).unwrap();
3689
    write(root, "other.txt", b"completely different\n");
3690
    let snap = repo.snapshot("status").unwrap();
3691
    let statuses: Vec<(&str, ChangeStatus)> = snap
3692
        .statuses
3693
        .iter()
3694
        .map(|s| (s.path.as_str(), s.status))
3695
        .collect();
3696
    assert_eq!(
3697
        statuses,
3698
        vec![
3699
            ("assets/img.bin", ChangeStatus::Renamed),
3700
            ("lib/new.rs", ChangeStatus::Renamed),
3701
            ("other.txt", ChangeStatus::Added),
3702
            ("src", ChangeStatus::Removed),
3703
            ("tiny.txt", ChangeStatus::Removed)
3704
        ]
3705
    );
3706
    let h2 = repo.commit("move things", &[]).unwrap();
3707
    let c = repo.store().get_change(&h2).unwrap();
3708
    let moves: Vec<_> = c
3709
        .tree_ops
3710
        .iter()
3711
        .filter(|op| matches!(op, TreeOp::Move { .. }))
3712
        .collect();
3713
    assert_eq!(moves.len(), 2, "{:?}", c.tree_ops);
3714
    assert!(c.tree_ops.iter().any(
3715
        |op| matches!(op, TreeOp::Move { node, name, .. } if *node == node_old && name == "new.rs")
3716
    ));
3717
    assert!(c.tree_ops.iter().any(
3718
        |op| matches!(op, TreeOp::Move { node, name, .. } if *node == node_img && name == "img.bin")
3719
    ));
3720
    let snap = repo.load_state(&[h2]).unwrap().materialize();
3721
    assert_eq!(
3722
        snap.files["lib/new.rs"].node, node_old,
3723
        "the node survives the rename"
3724
    );
3725
    assert!(
3726
        matches!(&snap.files["lib/new.rs"].content, FileContent::Text { bytes, .. } if bytes == b"fn a() {}\nfn b() {}\nfn c() {}\nfn e() {}\n")
3727
    );
3728
    assert!(!snap.files.contains_key("src/old.rs") && !snap.files.contains_key("src"));
3729
    assert!(render_change(
3730
        &c,
3731
        &repo.load_state(&[h1]).unwrap(),
3732
        &repo.load_state(&[h1]).unwrap().materialize()
3733
    )
3734
    .contains("R "));
3735
    // A fresh checkout reproduces the tree.
3736
    let other = tempfile::tempdir().unwrap();
3737
    let clone = Repo::clone(&root.to_string_lossy(), other.path()).unwrap();
3738
    assert_eq!(
3739
        fs::read(other.path().join("lib/new.rs")).unwrap(),
3740
        b"fn a() {}\nfn b() {}\nfn c() {}\nfn e() {}\n"
3741
    );
3742
    assert!(!other.path().join("src").exists());
3743
    assert!(!clone.snapshot("status").unwrap().changed);
3744
    // Similarity is line based, byte weighted.
3745
    assert_eq!(similarity(b"a\nb\n", b"a\nb\n"), 100);
3746
    assert_eq!(similarity(b"a\nb\nc\nd\n", b"a\nb\nx\ny\n"), 50);
3747
    assert_eq!(similarity(b"hello\n", b"world\n"), 0);
3748
    assert_eq!(similarity(b"", b"x\n"), 0);
3749
}
3750
3751
#[test]
3752
fn git_fetch_and_push_round_trip() {
3753
    hermetic();
3754
    if std::process::Command::new("git")
3755
        .arg("--version")
3756
        .output()
3757
        .is_err()
3758
    {
3759
        eprintln!("git not installed; skipping");
3760
        return;
3761
    }
3762
    let dir = tempfile::tempdir().unwrap();
3763
    let root = dir.path();
3764
    let git_in = |d: &Path, args: &[&str]| -> String {
3765
        let out = std::process::Command::new("git")
3766
            .arg("-C")
3767
            .arg(d)
3768
            .args([
3769
                "-c",
3770
                "user.name=Grace",
3771
                "-c",
3772
                "[email protected]",
3773
                "-c",
3774
                "commit.gpgsign=false",
3775
            ])
3776
            .args(args)
3777
            .output()
3778
            .unwrap();
3779
        assert!(
3780
            out.status.success(),
3781
            "git {args:?}: {}",
3782
            String::from_utf8_lossy(&out.stderr)
3783
        );
3784
        String::from_utf8_lossy(&out.stdout).trim().to_string()
3785
    };
3786
    // A bare "remote" and a work tree that pushes to it.
3787
    let remote = root.join("remote.git");
3788
    fs::create_dir_all(&remote).unwrap();
3789
    git_in(&remote, &["init", "-q", "--bare", "-b", "main"]);
3790
    let work = root.join("work");
3791
    git_in(
3792
        root,
3793
        &[
3794
            "clone",
3795
            "-q",
3796
            remote.to_str().unwrap(),
3797
            work.to_str().unwrap(),
3798
        ],
3799
    );
3800
    git_in(&work, &["checkout", "-q", "-b", "main"]);
3801
    write(&work, "README.md", b"# Project\n");
3802
    write(&work, "src/lib.rs", b"pub fn a() {}\n");
3803
    git_in(&work, &["add", "."]);
3804
    git_in(&work, &["commit", "-q", "-m", "initial"]);
3805
    write(&work, "src/lib.rs", b"pub fn a() {}\npub fn b() {}\n");
3806
    git_in(&work, &["commit", "-q", "-am", "second"]);
3807
    git_in(&work, &["push", "-q", "origin", "main"]);
3808
    let tip1 = git_in(&work, &["rev-parse", "HEAD"]);
3809
3810
    // Fetch into a fresh oxy repository.
3811
    let o = root.join("oxy");
3812
    let mut repo = Repo::init(&o).unwrap().with_home(root.join("home"));
3813
    repo.create_identity("Ada", "[email protected]", IdentityScope::User)
3814
        .unwrap();
3815
    let url = remote.to_string_lossy().to_string();
3816
    let r = repo.git_fetch(&url, "main").unwrap();
3817
    assert_eq!((r.commits, r.heads), (2, 1));
3818
    assert_eq!(
3819
        fs::read(o.join("src/lib.rs")).unwrap(),
3820
        b"pub fn a() {}\npub fn b() {}\n"
3821
    );
3822
    assert!(!repo.snapshot("status").unwrap().changed);
3823
    assert_eq!(
3824
        repo.git_fetch(&url, "main").unwrap().commits,
3825
        0,
3826
        "nothing new"
3827
    );
3828
3829
    // An oxy change, pushed back: one commit on top of the Git tip.
3830
    write(
3831
        &o,
3832
        "src/lib.rs",
3833
        b"pub fn a() {}\npub fn b() {}\npub fn c() {}\n",
3834
    );
3835
    write(&o, "NOTES.md", b"from oxy\n");
3836
    let h_oxy = repo.commit("add c and notes", &[]).unwrap();
3837
    let r = repo.git_push(&url, "main").unwrap();
3838
    assert_eq!(r.exported, 1, "{r:?}");
3839
    git_in(&work, &["pull", "-q", "--ff-only", "origin", "main"]);
3840
    assert_eq!(
3841
        git_in(&work, &["log", "--format=%s", "main"]),
3842
        "add c and notes\nsecond\ninitial"
3843
    );
3844
    assert_eq!(git_in(&work, &["rev-parse", "HEAD~1"]), tip1);
3845
    assert_eq!(fs::read(work.join("NOTES.md")).unwrap(), b"from oxy\n");
3846
    assert_eq!(git_in(&work, &["log", "-1", "--format=%an", "main"]), "Ada");
3847
    assert!(git_in(&work, &["log", "-1", "--format=%B", "main"])
3848
        .contains(&format!("Oxy-Hash: {}", h_oxy.to_hex())));
3849
    assert_eq!(
3850
        repo.git_push(&url, "main").unwrap().exported,
3851
        0,
3852
        "already pushed"
3853
    );
3854
3855
    // Git moves on; pushing without fetching is refused, fetching brings
3856
    // the commit in and the working copy follows.
3857
    write(&work, "README.md", b"# Project\n\nMore.\n");
3858
    git_in(&work, &["commit", "-q", "-am", "readme from git"]);
3859
    git_in(&work, &["push", "-q", "origin", "main"]);
3860
    let tip2 = git_in(&work, &["rev-parse", "HEAD"]);
3861
    assert!(repo
3862
        .git_push(&url, "main")
3863
        .unwrap_err()
3864
        .to_string()
3865
        .contains("fetch"));
3866
    let r = repo.git_fetch(&url, "main").unwrap();
3867
    assert_eq!(
3868
        (r.commits, r.heads),
3869
        (1, 2),
3870
        "the Git change and the oxy change commute"
3871
    );
3872
    assert_eq!(
3873
        fs::read(o.join("README.md")).unwrap(),
3874
        b"# Project\n\nMore.\n"
3875
    );
3876
    assert_eq!(fs::read(o.join("NOTES.md")).unwrap(), b"from oxy\n");
3877
    assert!(!repo.snapshot("status").unwrap().changed);
3878
    // Another oxy change pushes on top of Git's newest commit.
3879
    write(&o, "NOTES.md", b"from oxy\nagain\n");
3880
    repo.commit("notes again", &[]).unwrap();
3881
    assert_eq!(repo.git_push(&url, "main").unwrap().exported, 1);
3882
    git_in(&work, &["pull", "-q", "--ff-only", "origin", "main"]);
3883
    assert_eq!(git_in(&work, &["rev-parse", "HEAD~1"]), tip2);
3884
    assert_eq!(
3885
        fs::read(work.join("NOTES.md")).unwrap(),
3886
        b"from oxy\nagain\n"
3887
    );
3888
    assert_eq!(
3889
        git_in(&work, &["log", "--format=%s", "main"])
3890
            .lines()
3891
            .count(),
3892
        5
3893
    );
3894
}
3895
3896
/// Benchmark, not a gate: `cargo test --release -p oxy-core --lib bench_one_gibibyte -- --ignored --nocapture`.
3897
/// Commits, stores, clones, and reads back a 1 GiB incompressible file.
3898
#[test]
3899
#[ignore]
3900
fn bench_one_gibibyte_file() {
3901
    hermetic();
3902
    // /tmp is often a small tmpfs; `OXY_BENCH_DIR` picks a roomier disk.
3903
    let dir = match std::env::var_os("OXY_BENCH_DIR") {
3904
        Some(d) => tempfile::tempdir_in(d).unwrap(),
3905
        None => tempfile::tempdir().unwrap(),
3906
    };
3907
    let root = dir.path();
3908
    let repo = Repo::init(&root.join("r"))
3909
        .unwrap()
3910
        .with_home(root.join("home"));
3911
    let size = 1usize << 30;
3912
    let mut data = vec![0u8; size];
3913
    let mut x = 0x9e3779b97f4a7c15u64;
3914
    for chunk in data.chunks_mut(8) {
3915
        x ^= x << 13;
3916
        x ^= x >> 7;
3917
        x ^= x << 17;
3918
        let b = x.to_le_bytes();
3919
        chunk.copy_from_slice(&b[..chunk.len()]);
3920
    }
3921
    let t = std::time::Instant::now();
3922
    write(&root.join("r"), "big.bin", &data);
3923
    eprintln!("write 1 GiB to disk: {:.2?}", t.elapsed());
3924
    let t = std::time::Instant::now();
3925
    let h = repo.commit("big", &[]).unwrap();
3926
    eprintln!("commit (chunk + hash + store): {:.2?}", t.elapsed());
3927
    let t = std::time::Instant::now();
3928
    assert!(!repo.snapshot("status").unwrap().changed);
3929
    eprintln!("status on a clean 1 GiB working copy: {:.2?}", t.elapsed());
3930
    let t = std::time::Instant::now();
3931
    let objects = repo.store().list().unwrap().len();
3932
    eprintln!("objects stored: {objects} ({:.2?} to list)", t.elapsed());
3933
    let t = std::time::Instant::now();
3934
    let g = repo.gc(true).unwrap();
3935
    eprintln!("gc (pack): {:.2?} {g:?}", t.elapsed());
3936
    let t = std::time::Instant::now();
3937
    let clone = Repo::clone(&root.join("r").to_string_lossy(), &root.join("c")).unwrap();
3938
    eprintln!("clone (fetch + checkout): {:.2?}", t.elapsed());
3939
    let t = std::time::Instant::now();
3940
    let back = fs::read(root.join("c/big.bin")).unwrap();
3941
    assert_eq!(blake3::hash(&back), blake3::hash(&data));
3942
    eprintln!("read back and verify: {:.2?}", t.elapsed());
3943
    assert_eq!(clone.bookmark_heads().unwrap(), vec![h]);
3944
    let store_bytes: u64 = walkdir_size(&root.join("r/.oxy/objects"));
3945
    eprintln!(
3946
        "store size: {:.1} MiB for 1 GiB of data",
3947
        store_bytes as f64 / (1024.0 * 1024.0)
3948
    );
3949
}
3950
3951
fn walkdir_size(p: &Path) -> u64 {
3952
    let mut total = 0;
3953
    if let Ok(rd) = fs::read_dir(p) {
3954
        for e in rd.flatten() {
3955
            let path = e.path();
3956
            if path.is_dir() {
3957
                total += walkdir_size(&path);
3958
            } else if let Ok(m) = fs::metadata(&path) {
3959
                total += m.len();
3960
            }
3961
        }
3962
    }
3963
    total
3964
}
3965
3966
/// An opaque file whose size and mtime match the manifest is not read on
3967
/// the next snapshot: its blob comes from the manifest's stat cache.
3968
#[cfg(unix)]
3969
#[test]
3970
fn stat_cache_skips_reading_unchanged_opaque_files() {
3971
    use std::os::unix::fs::PermissionsExt;
3972
    hermetic();
3973
    let dir = tempfile::tempdir().unwrap();
3974
    let root = dir.path();
3975
    let repo = Repo::init(root).unwrap().with_home(root.join("home"));
3976
    let mut big = vec![0u8; 300 * 1024];
3977
    for (i, b) in big.iter_mut().enumerate() {
3978
        *b = (i as u32).wrapping_mul(2654435761).to_le_bytes()[1];
3979
    }
3980
    big[0] = 0;
3981
    write(root, "big.bin", &big);
3982
    write(root, "a.txt", b"text\n");
3983
    let h1 = repo.commit("base", &[]).unwrap();
3984
    let (_, _, m) = repo.read_manifest().unwrap().unwrap();
3985
    assert!(
3986
        m.entries["big.bin"].blob.is_some(),
3987
        "opaque files record their blob"
3988
    );
3989
    assert!(m.entries["a.txt"].blob.is_none());
3990
    let blob = m.entries["big.bin"].blob.unwrap();
3991
    assert!(repo.store().has(&blob));
3992
3993
    // Files modified within two seconds of the manifest are racy and still
3994
    // read; age the file so the cache applies, then snapshot to record it.
3995
    let old = std::time::SystemTime::now() - std::time::Duration::from_secs(30);
3996
    fs::File::options()
3997
        .write(true)
3998
        .open(root.join("big.bin"))
3999
        .unwrap()
4000
        .set_modified(old)
4001
        .unwrap();
4002
    assert!(!repo.snapshot("status").unwrap().changed);
4003
    // Now the file cannot be read at all; the snapshot succeeds without it.
4004
    fs::set_permissions(root.join("big.bin"), fs::Permissions::from_mode(0o000)).unwrap();
4005
    let snap = repo.snapshot("status").unwrap();
4006
    assert!(
4007
        !snap.changed && snap.statuses.is_empty(),
4008
        "{:?}",
4009
        snap.statuses
4010
    );
4011
    fs::set_permissions(root.join("big.bin"), fs::Permissions::from_mode(0o644)).unwrap();
4012
    // A real change (new mtime, new content) is seen and committed correctly.
4013
    let mut big2 = big.clone();
4014
    big2[10] ^= 0xff;
4015
    write(root, "big.bin", &big2);
4016
    let snap = repo.snapshot("status").unwrap();
4017
    assert_eq!(
4018
        snap.statuses
4019
            .iter()
4020
            .map(|s| (s.path.as_str(), s.status))
4021
            .collect::<Vec<_>>(),
4022
        vec![("big.bin", ChangeStatus::Modified)]
4023
    );
4024
    let h2 = repo.commit("edit", &[]).unwrap();
4025
    let files = repo.load_state(&[h2]).unwrap().materialize().files;
4026
    assert_eq!(
4027
        files["big.bin"].content,
4028
        FileContent::Opaque {
4029
            blobs: vec![Repo::blob_ref(&big2)]
4030
        }
4031
    );
4032
    // Checkout writes a manifest with blobs too, so the next status is cached.
4033
    repo.checkout(&[h1], false, "checkout").unwrap();
4034
    let (_, _, m) = repo.read_manifest().unwrap().unwrap();
4035
    assert_eq!(m.entries["big.bin"].blob, Some(Repo::blob_ref(&big)));
4036
    assert!(!repo.snapshot("status").unwrap().changed);
4037
}
4038
4039
#[test]
4040
fn status_json_lists_conflicts_with_contributors() {
4041
    hermetic();
4042
    let dir = tempfile::tempdir().unwrap();
4043
    let root = dir.path();
4044
    let repo = Repo::init(root).unwrap().with_home(root.join("home"));
4045
    write(root, "a.txt", b"one\n");
4046
    let h1 = repo.commit("base", &[]).unwrap();
4047
    write(root, "a.txt", b"one\nleft\n");
4048
    let ha = repo.commit("left", &[]).unwrap();
4049
    repo.checkout(&[h1], true, "checkout").unwrap();
4050
    write(root, "a.txt", b"one\nright\n");
4051
    let hb = repo.commit("right", &[]).unwrap();
4052
    repo.checkout(&[ha, hb], true, "checkout").unwrap();
4053
    let snap = repo.snapshot("status").unwrap();
4054
    assert!(snap.base_snapshot.is_conflicted());
4055
    let json = repo.status_json(&snap).unwrap();
4056
    let ida = repo.store().get_change(&ha).unwrap().change_id.to_hex();
4057
    let idb = repo.store().get_change(&hb).unwrap().change_id.to_hex();
4058
    assert!(json.contains("\"conflicted\":true"), "{json}");
4059
    assert!(
4060
        json.contains("\"kind\":\"text\",\"path\":\"a.txt\""),
4061
        "{json}"
4062
    );
4063
    assert!(json.contains(&ida) && json.contains(&idb), "{json}");
4064
    assert!(json.contains("\"resolved\":false"), "{json}");
4065
    assert!(json.starts_with('{') && json.ends_with('}'));
4066
    // Resolve and the report says so; a clean copy has no conflicts.
4067
    write(root, "a.txt", b"one\nleft\nright\n");
4068
    let snap = repo.snapshot("status").unwrap();
4069
    let json = repo.status_json(&snap).unwrap();
4070
    assert!(json.contains("\"resolved\":true"), "{json}");
4071
    repo.commit("resolve", &[]).unwrap();
4072
    let snap = repo.snapshot("status").unwrap();
4073
    let json = repo.status_json(&snap).unwrap();
4074
    assert!(
4075
        json.contains("\"clean\":true,\"conflicted\":false,\"paths\":[],\"conflicts\":[]"),
4076
        "{json}"
4077
    );
4078
}
4079
4080
#[test]
4081
fn ignore_rules_do_not_untrack_files() {
4082
    hermetic();
4083
    let dir = tempfile::tempdir().unwrap();
4084
    let root = dir.path();
4085
    let repo = Repo::init(root).unwrap().with_home(root.join("home"));
4086
    write(root, "src.c", b"int x;\n");
4087
    write(root, "build/out.o", b"\0obj");
4088
    write(root, "sub/keep.log", b"keep\n");
4089
    write(root, "sub/junk.log", b"junk\n");
4090
    write(root, ".oxyignore", b"/build\n*.log\n!sub/keep.log\n");
4091
    let snap = repo.snapshot("status").unwrap();
4092
    let added: Vec<&str> = snap.statuses.iter().map(|s| s.path.as_str()).collect();
4093
    assert_eq!(
4094
        added,
4095
        vec![".oxyignore", "src.c", "sub/keep.log"],
4096
        "anchored, glob, and negated rules"
4097
    );
4098
    let h1 = repo.commit("base", &[]).unwrap();
4099
    // Ignoring a tracked file changes nothing about it.
4100
    write(root, ".oxyignore", b"/build\n*.log\n!sub/keep.log\nsrc.c\n");
4101
    let snap = repo.snapshot("status").unwrap();
4102
    assert_eq!(
4103
        snap.statuses
4104
            .iter()
4105
            .map(|s| s.path.as_str())
4106
            .collect::<Vec<_>>(),
4107
        vec![".oxyignore"]
4108
    );
4109
    let h2 = repo.commit("ignore src.c", &[]).unwrap();
4110
    assert!(repo
4111
        .load_state(&[h2])
4112
        .unwrap()
4113
        .materialize()
4114
        .files
4115
        .contains_key("src.c"));
4116
    // Its edits are still seen, by status and by the prompt.
4117
    assert_eq!(repo.quick_dirty().unwrap(), Some(false));
4118
    write(root, "src.c", b"int x, y;\n");
4119
    assert_eq!(repo.quick_dirty().unwrap(), Some(true));
4120
    let snap = repo.snapshot("status").unwrap();
4121
    assert_eq!(
4122
        snap.statuses
4123
            .iter()
4124
            .map(|s| (s.path.as_str(), s.status))
4125
            .collect::<Vec<_>>(),
4126
        vec![("src.c", ChangeStatus::Modified)]
4127
    );
4128
    let h3 = repo.commit("edit src.c", &[]).unwrap();
4129
    assert!(
4130
        matches!(&repo.load_state(&[h3]).unwrap().materialize().files["src.c"].content, FileContent::Text { bytes, .. } if bytes == b"int x, y;\n")
4131
    );
4132
    // Deleting it on disk removes it, ignored or not; a checkout brings it back.
4133
    fs::remove_file(root.join("src.c")).unwrap();
4134
    let snap = repo.snapshot("status").unwrap();
4135
    assert_eq!(
4136
        snap.statuses
4137
            .iter()
4138
            .map(|s| (s.path.as_str(), s.status))
4139
            .collect::<Vec<_>>(),
4140
        vec![("src.c", ChangeStatus::Removed)]
4141
    );
4142
    repo.checkout(&[h3], true, "checkout").unwrap();
4143
    assert_eq!(fs::read(root.join("src.c")).unwrap(), b"int x, y;\n");
4144
    assert!(!repo.snapshot("status").unwrap().changed);
4145
    let _ = h1;
4146
}
4147
4148
#[test]
4149
fn split_works_on_non_heads_by_node() {
4150
    hermetic();
4151
    let dir = tempfile::tempdir().unwrap();
4152
    let root = dir.path();
4153
    let repo = Repo::init(root).unwrap().with_home(root.join("home"));
4154
    write(root, "a.txt", b"one\n");
4155
    write(root, "junk/x.lock", b"lock\n");
4156
    let h1 = repo.commit("work plus junk", &[]).unwrap();
4157
    write(root, "a.txt", b"one\ntwo\n");
4158
    let h2 = repo.commit("more work", &[]).unwrap();
4159
    assert_eq!(repo.store().get_change(&h2).unwrap().deps, vec![h1]);
4160
    let id1 = repo.store().get_change(&h1).unwrap().change_id;
4161
    // h1 is not a head: split it by node.
4162
    let (hj, h1b) = repo.split(&h1, &["junk".into()]).unwrap();
4163
    assert_ne!(h1b, h1);
4164
    assert_eq!(
4165
        repo.store().get_change(&h1b).unwrap().change_id,
4166
        id1,
4167
        "the rest keeps the ChangeId"
4168
    );
4169
    let junk = repo.store().get_change(&hj).unwrap();
4170
    assert!(junk.tree_ops.iter().all(
4171
        |op| matches!(op, TreeOp::AddNode { name, .. } if name == "junk" || name == "x.lock")
4172
    ));
4173
    let heads = repo.bookmark_heads().unwrap();
4174
    assert!(
4175
        heads.contains(&hj),
4176
        "the split-off part is a head of its own"
4177
    );
4178
    let snap = repo.load_state(&heads).unwrap().materialize();
4179
    assert!(
4180
        matches!(&snap.files["a.txt"].content, FileContent::Text { bytes, .. } if bytes == b"one\ntwo\n"),
4181
        "the dependent was rewritten onto the new hash"
4182
    );
4183
    assert!(snap.files.contains_key("junk/x.lock"));
4184
    let h2b = heads
4185
        .iter()
4186
        .find(|h| repo.store().get_change(h).unwrap().message == "more work")
4187
        .copied()
4188
        .unwrap();
4189
    assert_eq!(repo.store().get_change(&h2b).unwrap().deps, vec![h1b]);
4190
    assert!(!repo.snapshot("status").unwrap().changed);
4191
    // Abandoning the split-off head removes the junk from history.
4192
    repo.abandon(&hj).unwrap();
4193
    let heads = repo.bookmark_heads().unwrap();
4194
    let snap = repo.load_state(&heads).unwrap().materialize();
4195
    assert!(!snap.files.contains_key("junk/x.lock") && !snap.files.contains_key("junk"));
4196
    assert!(snap.files.contains_key("a.txt"));
4197
    // A dependent that touches the split-off paths blocks the split.
4198
    write(root, "junk/y.lock", b"y\n");
4199
    let hb = repo.commit("junk base", &[]).unwrap();
4200
    write(root, "junk/y.lock", b"yy\n");
4201
    write(root, "b.txt", b"b\n");
4202
    repo.commit("touches junk", &[]).unwrap();
4203
    let err = repo.split(&hb, &["junk".into()]).unwrap_err().to_string();
4204
    assert!(err.contains("depends on the split-off paths"), "{err}");
4205
}
4206
4207
#[test]
4208
fn bookmarks_switch_merge_and_push() {
4209
    hermetic();
4210
    let dir = tempfile::tempdir().unwrap();
4211
    let root = dir.path();
4212
    let origin = Repo::init(&root.join("origin")).unwrap();
4213
    let url = root.join("origin").to_string_lossy().to_string();
4214
    let mut repo = Repo::clone(&url, &root.join("r"))
4215
        .unwrap()
4216
        .with_home(root.join("home"));
4217
    let r = root.join("r");
4218
    write(&r, "a.txt", b"a\n");
4219
    let h_a = repo.commit("a", &[]).unwrap();
4220
    assert!(repo.push("origin", false).unwrap()[0].ok);
4221
    origin.refresh().unwrap();
4222
4223
    // A bookmark at the working copy's base, then work on it.
4224
    assert!(repo.bookmark_create("bad name..", None).is_err());
4225
    assert!(repo.bookmark_create("-x", None).is_err());
4226
    assert_eq!(repo.bookmark_create("feature", None).unwrap(), vec![h_a]);
4227
    assert!(repo.bookmark_create("feature", None).is_err(), "exists");
4228
    repo.bookmark_switch("feature", false).unwrap();
4229
    assert_eq!(repo.config.bookmark, "feature");
4230
    write(&r, "a.txt", b"a\nb\n");
4231
    write(&r, "b.txt", b"b\n");
4232
    let h_b = repo.commit("b on feature", &[]).unwrap();
4233
    assert_eq!(
4234
        repo.bookmark_heads().unwrap(),
4235
        vec![h_b],
4236
        "b edits a.txt, so it depends on a"
4237
    );
4238
    assert_eq!(
4239
        repo.resolve_heads("main").unwrap(),
4240
        vec![h_a],
4241
        "main is untouched"
4242
    );
4243
    assert_eq!(
4244
        repo.resolve_change("feature").unwrap(),
4245
        h_b,
4246
        "a one-head bookmark names its change"
4247
    );
4248
    // Reopening keeps the workspace's bookmark.
4249
    let reopened = Repo::open(&r).unwrap().with_home(root.join("home"));
4250
    assert_eq!(reopened.config.bookmark, "feature");
4251
    // Back to main: b.txt goes away; work there.
4252
    repo.bookmark_switch("main", false).unwrap();
4253
    assert!(!r.join("b.txt").exists());
4254
    assert_eq!(fs::read(r.join("a.txt")).unwrap(), b"a\n");
4255
    write(&r, "c.txt", b"c\n");
4256
    let h_c = repo.commit("c on main", &[]).unwrap();
4257
    let list = repo.bookmarks().unwrap();
4258
    assert_eq!(
4259
        list.iter()
4260
            .map(|b| (b.name.as_str(), b.current))
4261
            .collect::<Vec<_>>(),
4262
        vec![("feature", false), ("main", true)]
4263
    );
4264
    assert_eq!(
4265
        list.iter().find(|b| b.name == "main").unwrap().ahead,
4266
        Some(1),
4267
        "c is not on origin yet"
4268
    );
4269
    // Merge feature into main: the union, both heads, no merge change.
4270
    let m = repo.merge("feature").unwrap();
4271
    assert!(m.changed && m.checked_out);
4272
    let mut want = vec![h_b, h_c];
4273
    want.sort();
4274
    assert_eq!(m.heads, want);
4275
    assert_eq!(fs::read(r.join("b.txt")).unwrap(), b"b\n");
4276
    assert!(!repo.merge("feature").unwrap().changed, "already merged");
4277
    assert!(repo.merge("main").is_err());
4278
    // The other bookmark can be pushed by name and appears at origin.
4279
    assert!(repo.push_bookmark("origin", "feature", false).unwrap()[0].ok);
4280
    origin.refresh().unwrap();
4281
    assert_eq!(origin.resolve_heads("feature").unwrap(), vec![h_b]);
4282
    assert!(repo.push("origin", false).unwrap()[0].ok);
4283
    origin.refresh().unwrap();
4284
    assert_eq!(
4285
        repo.bookmarks()
4286
            .unwrap()
4287
            .iter()
4288
            .find(|b| b.name == "main")
4289
            .unwrap()
4290
            .ahead,
4291
        Some(0)
4292
    );
4293
    // A second workspace inherits the current bookmark and can switch independently.
4294
    let ws = repo.workspace_add(&root.join("ws"), None).unwrap();
4295
    assert_eq!(ws.config.bookmark, "main");
4296
    let mut ws = ws;
4297
    ws.bookmark_switch("feature", false).unwrap();
4298
    assert_eq!(
4299
        Repo::open(&r).unwrap().config.bookmark,
4300
        "main",
4301
        "the first workspace is unaffected"
4302
    );
4303
    assert!(
4304
        repo.bookmark_delete("feature").is_err(),
4305
        "current bookmark of another workspace"
4306
    );
4307
    ws.bookmark_switch("main", false).unwrap();
4308
    // Set and delete.
4309
    assert_eq!(repo.bookmark_set("feature", &[h_a]).unwrap(), vec![h_a]);
4310
    assert!(repo.bookmark_delete("main").is_err(), "current here");
4311
    repo.bookmark_delete("feature").unwrap();
4312
    assert!(repo.resolve_heads("feature").is_err());
4313
    assert!(repo.bookmark_set("feature", &[h_a]).is_err());
4314
    assert!(
4315
        repo.checkout(&[h_a], false, "checkout").is_ok(),
4316
        "changes of a deleted bookmark remain"
4317
    );
4318
}
4319
4320
#[test]
4321
fn oxygen_subrepos_pin_follow_and_update() {
4322
    hermetic();
4323
    let dir = tempfile::tempdir().unwrap();
4324
    let root = dir.path();
4325
    // A library repository with two commits, and a bare-ish origin for it.
4326
    let lib_origin = Repo::init(&root.join("lib-origin")).unwrap();
4327
    let lib_url = root.join("lib-origin").to_string_lossy().to_string();
4328
    let lib = Repo::clone(&lib_url, &root.join("lib"))
4329
        .unwrap()
4330
        .with_home(root.join("home"));
4331
    write(&root.join("lib"), "lib.txt", b"v1\n");
4332
    let l1 = lib.commit("lib v1", &[]).unwrap();
4333
    assert!(lib.push("origin", false).unwrap()[0].ok);
4334
    let _ = lib_origin;
4335
4336
    // The application (a clone of its own origin) adds it as a subrepo.
4337
    let app_origin = Repo::init(&root.join("app-origin")).unwrap();
4338
    let app_url = root.join("app-origin").to_string_lossy().to_string();
4339
    let _ = app_origin;
4340
    let app_dir = root.join("app");
4341
    let app = Repo::clone(&app_url, &app_dir)
4342
        .unwrap()
4343
        .with_home(root.join("home"));
4344
    write(&app_dir, "main.txt", b"app\n");
4345
    let pin = app.submodule_add(&lib_url, "libs/lib", None).unwrap();
4346
    assert!(matches!(&pin, crate::subrepo::Pin::Oxy { heads, .. } if heads == &vec![l1]));
4347
    assert!(app_dir.join(".oxymodules").exists() && app_dir.join("libs/lib/.oxy").is_dir());
4348
    let snap = app.snapshot("status").unwrap();
4349
    let paths: Vec<&str> = snap.statuses.iter().map(|s| s.path.as_str()).collect();
4350
    assert_eq!(
4351
        paths,
4352
        vec![".oxymodules", "libs/lib", "main.txt"],
4353
        "the nested files are not walked"
4354
    );
4355
    let a1 = app.commit("app with lib", &[]).unwrap();
4356
    let files = app.load_state(&[a1]).unwrap().materialize().files;
4357
    assert_eq!(files["libs/lib"].kind, NodeKind::Subrepo);
4358
    assert!(!files.contains_key("libs/lib/lib.txt"));
4359
    assert!(!app.snapshot("status").unwrap().changed);
4360
    let subs = app.subrepos().unwrap();
4361
    assert_eq!(subs.len(), 1);
4362
    assert_eq!(subs[0].actual.as_ref(), Some(&subs[0].pin));
4363
4364
    // Advance the nested repository: the parent sees a modified pin.
4365
    let nested = Repo::open(&app_dir.join("libs/lib"))
4366
        .unwrap()
4367
        .with_home(root.join("home"));
4368
    write(&app_dir.join("libs/lib"), "lib.txt", b"v2\n");
4369
    let l2 = nested.commit("lib v2", &[]).unwrap();
4370
    assert!(nested.push("origin", false).unwrap()[0].ok);
4371
    let snap = app.snapshot("status").unwrap();
4372
    assert_eq!(
4373
        snap.statuses
4374
            .iter()
4375
            .map(|s| (s.path.as_str(), s.status))
4376
            .collect::<Vec<_>>(),
4377
        vec![("libs/lib", ChangeStatus::Modified)]
4378
    );
4379
    let a2 = app.commit("bump lib", &[]).unwrap();
4380
    // Checking out the older app state brings the nested working copy back
4381
    // to the older pin, but never moves its bookmark backwards (oxygen#38).
4382
    let r = app.checkout(&[a1], false, "checkout").unwrap();
4383
    assert!(
4384
        r.notes.len() == 1 && r.notes[0].contains("keeps 1 newer change"),
4385
        "{:?}",
4386
        r.notes
4387
    );
4388
    assert_eq!(fs::read(app_dir.join("libs/lib/lib.txt")).unwrap(), b"v1\n");
4389
    let nested = Repo::open(&app_dir.join("libs/lib")).unwrap();
4390
    assert_eq!(nested.bookmark_heads().unwrap(), vec![l2]);
4391
    assert_eq!(nested.working_copy().unwrap().1.deps, vec![l1]);
4392
    assert!(!app.snapshot("status").unwrap().changed);
4393
    // A dirty nested repository is left alone and reported.
4394
    write(&app_dir.join("libs/lib"), "scratch.txt", b"wip\n");
4395
    let r = app.checkout(&[a2], false, "checkout").unwrap();
4396
    assert!(
4397
        r.notes.iter().any(|n| n.contains("uncommitted")),
4398
        "{:?}",
4399
        r.notes
4400
    );
4401
    assert_eq!(fs::read(app_dir.join("libs/lib/lib.txt")).unwrap(), b"v1\n");
4402
    fs::remove_file(app_dir.join("libs/lib/scratch.txt")).unwrap();
4403
    let r = app.submodule_update(false, &[]).unwrap();
4404
    assert_eq!(r, vec![("libs/lib".to_string(), SubrepoSync::Updated)]);
4405
    assert_eq!(fs::read(app_dir.join("libs/lib/lib.txt")).unwrap(), b"v2\n");
4406
    let _ = l2;
4407
4408
    // A fresh clone of the app has the pin but no nested repository until update --init.
4409
    assert!(app.push("origin", false).unwrap()[0].ok);
4410
    let clone_dir = root.join("app-clone");
4411
    let clone = Repo::clone(&app_url, &clone_dir)
4412
        .unwrap()
4413
        .with_home(root.join("home"));
4414
    assert!(!clone_dir.join("libs/lib/.oxy").exists());
4415
    assert_eq!(
4416
        clone.submodule_update(false, &[]).unwrap(),
4417
        vec![("libs/lib".to_string(), SubrepoSync::Missing)]
4418
    );
4419
    assert_eq!(
4420
        clone.submodule_update(true, &[]).unwrap(),
4421
        vec![("libs/lib".to_string(), SubrepoSync::Updated)]
4422
    );
4423
    assert_eq!(
4424
        fs::read(clone_dir.join("libs/lib/lib.txt")).unwrap(),
4425
        b"v2\n"
4426
    );
4427
    assert!(!clone.snapshot("status").unwrap().changed);
4428
    // Removing the subrepo leaves the directory and drops the node.
4429
    clone.submodule_remove("libs/lib").unwrap();
4430
    let snap = clone.snapshot("status").unwrap();
4431
    assert!(
4432
        snap.statuses
4433
            .iter()
4434
            .any(|s| s.path == "libs/lib" && s.status == ChangeStatus::Removed),
4435
        "{:?}",
4436
        snap.statuses
4437
    );
4438
    let c = clone.commit("drop lib", &[]).unwrap();
4439
    assert!(!clone
4440
        .load_state(&[c])
4441
        .unwrap()
4442
        .materialize()
4443
        .files
4444
        .contains_key("libs/lib"));
4445
    assert!(clone_dir.join("libs/lib/lib.txt").exists());
4446
    assert!(
4447
        !clone.snapshot("status").unwrap().changed,
4448
        "an unregistered nested repository is ignored"
4449
    );
4450
}
4451
4452
#[test]
4453
fn git_submodules_import_and_export_as_gitlinks() {
4454
    hermetic();
4455
    if std::process::Command::new("git")
4456
        .arg("--version")
4457
        .output()
4458
        .is_err()
4459
    {
4460
        eprintln!("git not installed; skipping");
4461
        return;
4462
    }
4463
    let dir = tempfile::tempdir().unwrap();
4464
    let root = dir.path();
4465
    let git_in = |d: &Path, args: &[&str]| -> String {
4466
        let out = std::process::Command::new("git")
4467
            .arg("-C")
4468
            .arg(d)
4469
            .args([
4470
                "-c",
4471
                "user.name=Grace",
4472
                "-c",
4473
                "[email protected]",
4474
                "-c",
4475
                "commit.gpgsign=false",
4476
                "-c",
4477
                "protocol.file.allow=always",
4478
            ])
4479
            .args(args)
4480
            .output()
4481
            .unwrap();
4482
        assert!(
4483
            out.status.success(),
4484
            "git {args:?}: {}",
4485
            String::from_utf8_lossy(&out.stderr)
4486
        );
4487
        String::from_utf8_lossy(&out.stdout).trim().to_string()
4488
    };
4489
    let sub = root.join("sub");
4490
    fs::create_dir_all(&sub).unwrap();
4491
    git_in(&sub, &["init", "-q", "-b", "main"]);
4492
    write(&sub, "s.txt", b"sub\n");
4493
    git_in(&sub, &["add", "."]);
4494
    git_in(&sub, &["commit", "-q", "-m", "sub initial"]);
4495
    let sub_sha = git_in(&sub, &["rev-parse", "HEAD"]);
4496
    let g = root.join("main.git");
4497
    fs::create_dir_all(&g).unwrap();
4498
    git_in(&g, &["init", "-q", "-b", "main"]);
4499
    write(&g, "README.md", b"# app\n");
4500
    git_in(&g, &["add", "."]);
4501
    git_in(&g, &["commit", "-q", "-m", "initial"]);
4502
    git_in(
4503
        &g,
4504
        &[
4505
            "submodule",
4506
            "add",
4507
            "-q",
4508
            sub.to_str().unwrap(),
4509
            "vendor/sub",
4510
        ],
4511
    );
4512
    git_in(&g, &["commit", "-q", "-m", "add submodule"]);
4513
4514
    let dest = root.join("oxy");
4515
    let repo = Repo::init(&dest).unwrap().with_home(root.join("home"));
4516
    let rep = repo.import_git(&g, "main").unwrap();
4517
    assert_eq!((rep.commits, rep.submodules), (2, 1));
4518
    let files = repo
4519
        .load_state(&repo.bookmark_heads().unwrap())
4520
        .unwrap()
4521
        .materialize()
4522
        .files;
4523
    assert_eq!(files["vendor/sub"].kind, NodeKind::Subrepo);
4524
    let FileContent::Opaque { blobs } = &files["vendor/sub"].content else {
4525
        panic!()
4526
    };
4527
    assert_eq!(
4528
        crate::subrepo::Pin::decode(&repo.read_blob(&blobs[0]).unwrap()).unwrap(),
4529
        crate::subrepo::Pin::Git {
4530
            sha: sub_sha.clone(),
4531
            branch: "HEAD".into()
4532
        }
4533
    );
4534
    let modules =
4535
        crate::subrepo::Modules::parse(&fs::read_to_string(dest.join(".oxymodules")).unwrap());
4536
    assert_eq!(modules.entries["vendor/sub"].url, sub.to_string_lossy());
4537
    assert!(modules.entries["vendor/sub"].git);
4538
    assert!(
4539
        files.contains_key(".gitmodules"),
4540
        "the Git file is kept for round trips"
4541
    );
4542
    assert!(
4543
        !dest.join("vendor/sub/.git").exists(),
4544
        "not cloned until update --init"
4545
    );
4546
    assert!(!repo.snapshot("status").unwrap().changed);
4547
    // update --init clones it at the pinned commit; status is unchanged.
4548
    assert_eq!(
4549
        repo.submodule_update(true, &[]).unwrap(),
4550
        vec![("vendor/sub".to_string(), SubrepoSync::Updated)]
4551
    );
4552
    assert_eq!(
4553
        git_in(&dest.join("vendor/sub"), &["rev-parse", "HEAD"]),
4554
        sub_sha
4555
    );
4556
    assert!(!repo.snapshot("status").unwrap().changed);
4557
    // Export writes the gitlink and .gitmodules back.
4558
    let mirror = root.join("mirror.git");
4559
    let rep = repo.git_export(&mirror).unwrap();
4560
    assert_eq!(rep.skipped_subrepos, 0);
4561
    let ls = git_in(&mirror, &["ls-tree", "main", "vendor/sub"]);
4562
    assert!(
4563
        ls.starts_with("160000 commit ") && ls.contains(&sub_sha),
4564
        "{ls}"
4565
    );
4566
    assert_eq!(
4567
        git_in(&mirror, &["ls-tree", "--name-only", "main"]),
4568
        ".gitmodules\nREADME.md\nvendor"
4569
    );
4570
    let orig_tree = git_in(&g, &["rev-parse", "main^{tree}"]);
4571
    assert_eq!(
4572
        git_in(&mirror, &["rev-parse", "main^{tree}"]),
4573
        orig_tree,
4574
        "tree round trip"
4575
    );
4576
}
4577
4578
#[test]
4579
fn partial_commits_by_path_and_by_hunk() {
4580
    hermetic();
4581
    let dir = tempfile::tempdir().unwrap();
4582
    let root = dir.path();
4583
    let repo = Repo::init(root).unwrap().with_home(root.join("home"));
4584
    write(root, "a.txt", b"1\n2\n3\n");
4585
    write(root, "b.txt", b"b\n");
4586
    let h0 = repo.commit("base", &[]).unwrap();
4587
    write(root, "a.txt", b"0\n1\n2\n3\n4\n");
4588
    write(root, "b.txt", b"b\nbb\n");
4589
    write(root, "c.txt", b"c\n");
4590
    // By path: only a.txt goes in; the rest stays on disk as uncommitted work.
4591
    let h1 = repo
4592
        .commit_selection("a only", &[], &Selection::Paths(vec!["a.txt".into()]))
4593
        .unwrap();
4594
    let c1 = repo.store().get_change(&h1).unwrap();
4595
    assert!(
4596
        c1.tree_ops.is_empty() && c1.edits.iter().all(|e| e.node() == c1.edits[0].node()),
4597
        "{:?}",
4598
        c1.tree_ops
4599
    );
4600
    assert_eq!(c1.deps, vec![h0]);
4601
    let files = repo.load_state(&[h1]).unwrap().materialize().files;
4602
    assert!(
4603
        matches!(&files["a.txt"].content, FileContent::Text { bytes, .. } if bytes == b"0\n1\n2\n3\n4\n")
4604
    );
4605
    assert!(matches!(&files["b.txt"].content, FileContent::Text { bytes, .. } if bytes == b"b\n"));
4606
    assert!(!files.contains_key("c.txt"));
4607
    let snap = repo.snapshot("status").unwrap();
4608
    assert_eq!(
4609
        snap.statuses
4610
            .iter()
4611
            .map(|s| (s.path.as_str(), s.status))
4612
            .collect::<Vec<_>>(),
4613
        vec![
4614
            ("b.txt", ChangeStatus::Modified),
4615
            ("c.txt", ChangeStatus::Added)
4616
        ]
4617
    );
4618
    assert_eq!(
4619
        fs::read(root.join("b.txt")).unwrap(),
4620
        b"b\nbb\n",
4621
        "disk untouched"
4622
    );
4623
    // By hunk: pick the b.txt insert; c.txt's addition is left.
4624
    let (_, hunks) = repo.hunks().unwrap();
4625
    let b_hunk = hunks
4626
        .iter()
4627
        .find(|h| h.path == "b.txt" && h.text.contains("+bb"))
4628
        .unwrap()
4629
        .index;
4630
    let h2 = repo
4631
        .commit_selection("b only", &[], &Selection::Hunks(vec![b_hunk]))
4632
        .unwrap();
4633
    let files = repo.load_state(&[h2]).unwrap().materialize().files;
4634
    assert!(
4635
        matches!(&files["b.txt"].content, FileContent::Text { bytes, .. } if bytes == b"b\nbb\n")
4636
    );
4637
    assert!(!files.contains_key("c.txt"));
4638
    let snap = repo.snapshot("status").unwrap();
4639
    assert_eq!(
4640
        snap.statuses
4641
            .iter()
4642
            .map(|s| s.path.as_str())
4643
            .collect::<Vec<_>>(),
4644
        vec!["c.txt"]
4645
    );
4646
    // Choosing only the content hunk of a file in a new directory pulls in
4647
    // the directory and file additions it needs.
4648
    write(root, "d/e.txt", b"e\n");
4649
    let (_, hunks) = repo.hunks().unwrap();
4650
    let e_insert = hunks
4651
        .iter()
4652
        .find(|h| h.path == "d/e.txt" && h.text.contains("+e"))
4653
        .unwrap()
4654
        .index;
4655
    let h3 = repo
4656
        .commit_selection("e only", &[], &Selection::Hunks(vec![e_insert]))
4657
        .unwrap();
4658
    let c3 = repo.store().get_change(&h3).unwrap();
4659
    assert_eq!(c3.tree_ops.len(), 2, "{:?}", c3.tree_ops);
4660
    let files = repo.load_state(&[h3]).unwrap().materialize().files;
4661
    assert!(files.contains_key("d/e.txt") && !files.contains_key("c.txt"));
4662
    // Choosing a new file's addition hunk brings its content along.
4663
    write(root, "f/g.txt", b"g\n");
4664
    let (_, hunks) = repo.hunks().unwrap();
4665
    let g_add = hunks
4666
        .iter()
4667
        .find(|h| h.path == "f/g.txt" && h.text.starts_with("A "))
4668
        .unwrap()
4669
        .index;
4670
    let h4 = repo
4671
        .commit_selection("g by addition", &[], &Selection::Hunks(vec![g_add]))
4672
        .unwrap();
4673
    let files = repo.load_state(&[h4]).unwrap().materialize().files;
4674
    assert!(
4675
        matches!(&files["f/g.txt"].content, FileContent::Text { bytes, .. } if bytes == b"g\n")
4676
    );
4677
    assert!(!repo
4678
        .snapshot("status")
4679
        .unwrap()
4680
        .statuses
4681
        .iter()
4682
        .any(|s| s.path == "f/g.txt"));
4683
    // Everything left commits normally; the working copy is then clean.
4684
    repo.commit("the rest", &[]).unwrap();
4685
    assert!(!repo.snapshot("status").unwrap().changed);
4686
    let files = repo
4687
        .load_state(&repo.bookmark_heads().unwrap())
4688
        .unwrap()
4689
        .materialize()
4690
        .files;
4691
    assert!(files.contains_key("c.txt"));
4692
}
4693
4694
#[test]
4695
fn blame_attributes_lines_to_introducing_changes_across_renames() {
4696
    hermetic();
4697
    let dir = tempfile::tempdir().unwrap();
4698
    let root = dir.path();
4699
    let mut repo = Repo::init(root).unwrap().with_home(root.join("home"));
4700
    repo.create_identity("Ada", "[email protected]", IdentityScope::User)
4701
        .unwrap();
4702
    write(root, "a.txt", b"one\n");
4703
    let h1 = repo.commit("first", &[]).unwrap();
4704
    write(root, "a.txt", b"one\ntwo\n");
4705
    let h2 = repo.commit("second", &[]).unwrap();
4706
    let b = repo.blame("a.txt").unwrap();
4707
    assert_eq!(
4708
        b.iter()
4709
            .map(|l| (l.line, l.hash, l.text.as_slice()))
4710
            .collect::<Vec<_>>(),
4711
        vec![(1, h1, b"one\n".as_slice()), (2, h2, b"two\n".as_slice())]
4712
    );
4713
    assert!(b.iter().all(|l| l.author == "Ada"));
4714
    assert_eq!(
4715
        b[0].change_id,
4716
        repo.store().get_change(&h1).unwrap().change_id
4717
    );
4718
    fs::rename(root.join("a.txt"), root.join("b.txt")).unwrap();
4719
    repo.commit("rename", &[]).unwrap();
4720
    let b = repo.blame("b.txt").unwrap();
4721
    assert_eq!(
4722
        b.iter().map(|l| l.hash).collect::<Vec<_>>(),
4723
        vec![h1, h2],
4724
        "the node survives the rename"
4725
    );
4726
    assert!(repo.blame("a.txt").is_err());
4727
}
4728
4729
#[test]
4730
fn bisect_finds_the_first_bad_change() {
4731
    hermetic();
4732
    let dir = tempfile::tempdir().unwrap();
4733
    let root = dir.path();
4734
    let repo = Repo::init(root).unwrap().with_home(root.join("home"));
4735
    let mut content = String::new();
4736
    let mut hashes = Vec::new();
4737
    for i in 1..=8 {
4738
        content.push_str(&format!("line {i}{}\n", if i == 5 { " bug" } else { "" }));
4739
        write(root, "f.txt", content.as_bytes());
4740
        hashes.push(repo.commit(&format!("step {i}"), &[]).unwrap());
4741
    }
4742
    // Each step appends after the previous line, so the chain is linear.
4743
    assert_eq!(repo.bookmark_heads().unwrap(), vec![hashes[7]]);
4744
    repo.bisect_start().unwrap();
4745
    assert!(matches!(
4746
        repo.bisect_mark(Some(true), &[hashes[0]]).unwrap(),
4747
        BisectStep::NeedMarks { good: 1, bad: 0 }
4748
    ));
4749
    let step = repo.bisect_mark(Some(false), &[hashes[7]]).unwrap();
4750
    assert!(
4751
        matches!(step, BisectStep::Testing { remaining: 7, .. }),
4752
        "{step:?}"
4753
    );
4754
    // Automated: bad when the bug line is present.
4755
    let step = repo
4756
        .bisect_run(&["sh".into(), "-c".into(), "! grep -q bug f.txt".into()])
4757
        .unwrap();
4758
    assert_eq!(step, BisectStep::Found { culprit: hashes[4] });
4759
    assert_eq!(
4760
        repo.bisect_status().unwrap(),
4761
        Some(BisectStep::Found { culprit: hashes[4] })
4762
    );
4763
    repo.bisect_reset().unwrap();
4764
    assert_eq!(fs::read_to_string(root.join("f.txt")).unwrap(), content);
4765
    assert!(repo.bisect_status().unwrap().is_none());
4766
    assert!(!repo.snapshot("status").unwrap().changed);
4767
    // Manual marks and a skip.
4768
    repo.bisect_start().unwrap();
4769
    repo.bisect_mark(Some(true), &[hashes[0]]).unwrap();
4770
    let mut step = repo.bisect_mark(Some(false), &[hashes[7]]).unwrap();
4771
    let mut skipped_once = false;
4772
    let mut guard = 0;
4773
    while let BisectStep::Testing { .. } = step {
4774
        guard += 1;
4775
        assert!(guard < 20);
4776
        let text = fs::read_to_string(root.join("f.txt")).unwrap();
4777
        if !skipped_once && text.contains("line 6") {
4778
            // An untestable state away from the boundary: the search routes around it.
4779
            skipped_once = true;
4780
            step = repo.bisect_mark(None, &[]).unwrap();
4781
            continue;
4782
        }
4783
        step = repo.bisect_mark(Some(!text.contains("bug")), &[]).unwrap();
4784
    }
4785
    assert!(skipped_once);
4786
    assert_eq!(step, BisectStep::Found { culprit: hashes[4] });
4787
    repo.bisect_reset().unwrap();
4788
    // Skipping the culprit itself leaves it among the candidates reported.
4789
    repo.bisect_start().unwrap();
4790
    repo.bisect_mark(Some(true), &[hashes[0]]).unwrap();
4791
    let mut step = repo.bisect_mark(Some(false), &[hashes[7]]).unwrap();
4792
    let mut guard = 0;
4793
    while let BisectStep::Testing { heads, .. } = &step {
4794
        guard += 1;
4795
        assert!(guard < 20);
4796
        let text = fs::read_to_string(root.join("f.txt")).unwrap();
4797
        let is_culprit_state =
4798
            heads.contains(&hashes[4]) && !heads.iter().any(|h| hashes[5..].contains(h));
4799
        step = if is_culprit_state {
4800
            repo.bisect_mark(None, &[]).unwrap()
4801
        } else {
4802
            repo.bisect_mark(Some(!text.contains("bug")), &[]).unwrap()
4803
        };
4804
    }
4805
    match step {
4806
        BisectStep::Inconclusive { candidates } => assert!(
4807
            candidates.contains(&hashes[4]) && candidates.len() <= 2,
4808
            "{candidates:?}"
4809
        ),
4810
        other => panic!("{other:?}"),
4811
    }
4812
    repo.bisect_reset().unwrap();
4813
}
4814
4815
#[test]
4816
fn squash_folds_a_change_into_its_dependency() {
4817
    hermetic();
4818
    let dir = tempfile::tempdir().unwrap();
4819
    let root = dir.path();
4820
    let repo = Repo::init(root).unwrap().with_home(root.join("home"));
4821
    write(root, "a.txt", b"1\n");
4822
    let a = repo.commit("A", &[]).unwrap();
4823
    write(root, "a.txt", b"1\n2\n");
4824
    let c = repo.commit("C", &[]).unwrap();
4825
    write(root, "a.txt", b"1\n2\n3\n");
4826
    let e = repo.commit("E", &[]).unwrap();
4827
    write(root, "b.txt", b"b\n");
4828
    let b = repo.commit("B", &[]).unwrap();
4829
    let id_a = repo.store().get_change(&a).unwrap().change_id;
4830
    let id_e = repo.store().get_change(&e).unwrap().change_id;
4831
    // E depends on C which A lacks: refused, naming it.
4832
    let err = repo.squash(&e, &a).unwrap_err().to_string();
4833
    assert!(err.contains(&c.short(12)), "{err}");
4834
    // C into A: A' has both, C is gone, E follows and still reads the same.
4835
    let a2 = repo.squash(&c, &a).unwrap();
4836
    let a2c = repo.store().get_change(&a2).unwrap();
4837
    assert_eq!(a2c.change_id, id_a);
4838
    assert!(a2c.deps.is_empty());
4839
    let heads = repo.bookmark_heads().unwrap();
4840
    let st = repo.load_state(&heads).unwrap();
4841
    assert!(!st.contains(&c) && !st.contains(&a) && !st.contains(&e));
4842
    let e2 = st
4843
        .changes()
4844
        .find(|(_, m)| m.change_id == id_e)
4845
        .map(|(h, _)| *h)
4846
        .unwrap();
4847
    assert_eq!(
4848
        repo.store().get_change(&e2).unwrap().deps,
4849
        vec![a2],
4850
        "E now depends on A' alone"
4851
    );
4852
    let files = st.materialize().files;
4853
    assert!(
4854
        matches!(&files["a.txt"].content, FileContent::Text { bytes, .. } if bytes == b"1\n2\n3\n")
4855
    );
4856
    assert!(files.contains_key("b.txt"));
4857
    assert!(st.contains(&b));
4858
    assert!(!repo.snapshot("status").unwrap().changed);
4859
    assert_eq!(repo.log().unwrap().len(), 4, "working copy, B, E', A'");
4860
    // Undo restores the three original changes.
4861
    repo.undo().unwrap();
4862
    repo.undo().unwrap();
4863
    let st = repo.load_state(&repo.bookmark_heads().unwrap()).unwrap();
4864
    assert!(st.contains(&c) && st.contains(&a) && st.contains(&e));
4865
}
4866
4867
#[test]
4868
fn rebase_re_expresses_a_change_against_another_base() {
4869
    hermetic();
4870
    let dir = tempfile::tempdir().unwrap();
4871
    let root = dir.path();
4872
    let repo = Repo::init(root).unwrap().with_home(root.join("home"));
4873
    write(root, "a.txt", b"1\n2\n");
4874
    let a = repo.commit("A", &[]).unwrap();
4875
    write(root, "a.txt", b"1\n2\n3\n");
4876
    let c = repo.commit("C: append 3", &[]).unwrap();
4877
    write(root, "a.txt", b"1\n2\n3\n4\n");
4878
    let e = repo.commit("E: append 4", &[]).unwrap();
4879
    // A different base: A plus a change that prepends a line.
4880
    repo.checkout(&[a], true, "checkout").unwrap();
4881
    write(root, "a.txt", b"0\n1\n2\n");
4882
    let d = repo.commit("D: prepend 0", &[]).unwrap();
4883
    let id_c = repo.store().get_change(&c).unwrap().change_id;
4884
    let id_e = repo.store().get_change(&e).unwrap().change_id;
4885
    // Rebase C onto D: its effect (append 3) re-derived against D's text.
4886
    let c2 = repo.rebase(&c, &[d]).unwrap();
4887
    let c2c = repo.store().get_change(&c2).unwrap();
4888
    assert_eq!(c2c.change_id, id_c);
4889
    assert!(c2c.deps.contains(&d), "{:?}", c2c.deps);
4890
    let heads = repo.bookmark_heads().unwrap();
4891
    let st = repo.load_state(&heads).unwrap();
4892
    assert!(!st.contains(&c) && st.contains(&d));
4893
    let e2 = st
4894
        .changes()
4895
        .find(|(_, m)| m.change_id == id_e)
4896
        .map(|(h, _)| *h)
4897
        .unwrap();
4898
    let e2deps = repo.store().get_change(&e2).unwrap().deps;
4899
    assert!(
4900
        e2deps.contains(&c2) && !e2deps.contains(&c) && e2deps.contains(&a),
4901
        "E follows C by content and still depends on A, which introduced the file: {e2deps:?}"
4902
    );
4903
    let files = st.materialize().files;
4904
    assert!(
4905
        matches!(&files["a.txt"].content, FileContent::Text { bytes, .. } if bytes == b"0\n1\n2\n3\n4\n"),
4906
        "{:?}",
4907
        files["a.txt"].content
4908
    );
4909
    assert!(!files["a.txt"].is_conflicted());
4910
    // Rebasing onto a state that already contains the change is refused.
4911
    assert!(repo.rebase(&c2, &[c2]).is_err());
4912
    let err = repo.rebase(&e2, &[d]).unwrap_err().to_string();
4913
    assert!(
4914
        err.contains("lacks dependencies"),
4915
        "E needs C, which D's state does not have: {err}"
4916
    );
4917
}
4918
4919
#[test]
4920
fn unsigned_tags_keep_their_message() {
4921
    hermetic();
4922
    let dir = tempfile::tempdir().unwrap();
4923
    let root = dir.path();
4924
    let repo = Repo::init(root).unwrap().with_home(root.join("home"));
4925
    write(root, "a.txt", b"a\n");
4926
    repo.commit("a", &[]).unwrap();
4927
    assert!(repo.secret_key().unwrap().is_none());
4928
    repo.tag_create("v1", &repo.bookmark_heads().unwrap(), "first release")
4929
        .unwrap();
4930
    let tags = repo.tags().unwrap();
4931
    assert_eq!(
4932
        (
4933
            tags[0].name.as_str(),
4934
            tags[0].message.as_str(),
4935
            tags[0].signer.as_deref()
4936
        ),
4937
        ("v1", "first release", None)
4938
    );
4939
    assert!(
4940
        repo.tag_refs().unwrap()[0].attestation.is_none(),
4941
        "an unsigned attestation is not advertised"
4942
    );
4943
}
4944
4945
#[test]
4946
fn fsck_passes_a_sound_repository_and_names_each_fault() {
4947
    // Files on disk are what this tests: tampering with them, and the
4948
    // directory store's crash points.
4949
    if std::env::var_os("OXY_STORE_BACKEND").is_some() {
4950
        return;
4951
    }
4952
    hermetic();
4953
    let dir = tempfile::tempdir().unwrap();
4954
    let root = dir.path();
4955
    let origin_path = root.join("origin");
4956
    let origin = Repo::init(&origin_path).unwrap();
4957
    let mut a = Repo::clone(&origin_path.to_string_lossy(), &root.join("a"))
4958
        .unwrap()
4959
        .with_home(root.join("home-a"));
4960
    a.create_identity("Ada", "[email protected]", IdentityScope::Repo)
4961
        .unwrap();
4962
    write(&root.join("a"), "f.txt", b"one\n");
4963
    write(&root.join("a"), "bin.dat", b"\0\x01\x02binary");
4964
    let h1 = a.commit("first", &[]).unwrap();
4965
    write(&root.join("a"), "f.txt", b"one\ntwo\n");
4966
    let h2 = a.commit("second", &[]).unwrap();
4967
    a.tag_create("v1", &[h2], "first release").unwrap();
4968
    a.checkpoint().unwrap();
4969
    assert!(a.push("origin", false).unwrap()[0].ok);
4970
    origin.refresh().unwrap();
4971
4972
    // Sound: signed changes, a seal, a tag, a checkpoint, a ref attestation.
4973
    for repo in [&a, &origin] {
4974
        let rep = repo.fsck().unwrap();
4975
        assert_eq!(rep.problems, vec![], "{rep:?}");
4976
        // The two commits, plus the working copy's change in `a`.
4977
        assert!(rep.changes >= 2 && rep.signed >= 2, "{rep:?}");
4978
        assert!(rep.ops > 1 && rep.objects > 5);
4979
    }
4980
    assert!(origin.fsck().unwrap().attestations >= 1);
4981
4982
    // A flipped byte in a stored object is corruption, named by hash.
4983
    let c1 = a.store().path_for(&h1);
4984
    let pristine = fs::read(&c1).unwrap();
4985
    let mut bytes = pristine.clone();
4986
    *bytes.last_mut().unwrap() ^= 1;
4987
    fs::write(&c1, &bytes).unwrap();
4988
    let rep = a.fsck().unwrap();
4989
    assert!(rep.errors() >= 1);
4990
    assert!(
4991
        rep.problems
4992
            .iter()
4993
            .any(|p| p.object == Some(h1) && p.what.contains("unreadable")),
4994
        "{rep:?}"
4995
    );
4996
    fs::write(&c1, &pristine).unwrap();
4997
    assert_eq!(a.fsck().unwrap().errors(), 0);
4998
4999
    // A missing change is named with what needed it.
5000
    fs::remove_file(&c1).unwrap();
5001
    let rep = a.fsck().unwrap();
5002
    assert!(
5003
        rep.problems.iter().any(|p| p.severity == Severity::Error
5004
            && p.object == Some(h1)
5005
            && p.what.contains("change missing, needed by change")),
5006
        "{rep:?}"
5007
    );
5008
    fs::write(&c1, &pristine).unwrap();
5009
5010
    // A missing blob is an error in a full clone.
5011
    let c2 = a.store().get_change(&h1).unwrap();
5012
    let blob = c2
5013
        .edits
5014
        .iter()
5015
        .find_map(|e| match e {
5016
            Edit::Replace { new: Some(b), .. } => Some(*b),
5017
            _ => None,
5018
        })
5019
        .expect("the binary file is a blob");
5020
    let bp = a.store().path_for(&blob);
5021
    let blob_bytes = fs::read(&bp).unwrap();
5022
    fs::remove_file(&bp).unwrap();
5023
    let rep = a.fsck().unwrap();
5024
    assert!(
5025
        rep.problems
5026
            .iter()
5027
            .any(|p| p.object == Some(blob) && p.what.contains("blob missing")),
5028
        "{rep:?}"
5029
    );
5030
    fs::write(&bp, &blob_bytes).unwrap();
5031
5032
    // A broken op log head is reported, not a crash.
5033
    let head = root.join("a/.oxy/ops/head");
5034
    let saved = fs::read(&head).unwrap();
5035
    fs::write(&head, b"not a hash").unwrap();
5036
    let rep = a.fsck().unwrap();
5037
    assert!(
5038
        rep.problems.iter().any(|p| p.what.contains("ops/head")),
5039
        "{rep:?}"
5040
    );
5041
    fs::write(&head, saved).unwrap();
5042
    assert_eq!(a.fsck().unwrap().problems, vec![]);
5043
}
5044
5045
/// Copy a directory tree (for restoring a pristine repository).
5046
fn copy_tree(from: &Path, to: &Path) {
5047
    fs::create_dir_all(to).unwrap();
5048
    for e in fs::read_dir(from).unwrap() {
5049
        let e = e.unwrap();
5050
        let target = to.join(e.file_name());
5051
        if e.file_type().unwrap().is_dir() {
5052
            copy_tree(&e.path(), &target);
5053
        } else {
5054
            fs::copy(e.path(), &target).unwrap();
5055
        }
5056
    }
5057
}
5058
5059
/// Spec §13.6: stop `commit` and `push` at every durable step, as a crash
5060
/// would, and check that both repositories still open, pass `fsck`, and
5061
/// accept the same operation again.
5062
#[test]
5063
fn crash_at_every_step_of_commit_and_push_leaves_sound_repositories() {
5064
    // Files on disk are what this tests: tampering with them, and the
5065
    // directory store's crash points.
5066
    if std::env::var_os("OXY_STORE_BACKEND").is_some() {
5067
        return;
5068
    }
5069
    use crate::durable::failpoint;
5070
    hermetic();
5071
    let dir = tempfile::tempdir().unwrap();
5072
    let pristine = dir.path().join("pristine");
5073
    let origin_path = pristine.join("origin");
5074
    Repo::init(&origin_path).unwrap();
5075
    let mut a = Repo::clone(&origin_path.to_string_lossy(), &pristine.join("a"))
5076
        .unwrap()
5077
        .with_home(dir.path().join("home"));
5078
    a.create_identity("Ada", "[email protected]", IdentityScope::Repo)
5079
        .unwrap();
5080
    write(&pristine.join("a"), "f.txt", b"one\n");
5081
    a.commit("first", &[]).unwrap();
5082
    assert!(a.push("origin", false).unwrap()[0].ok);
5083
    drop(a);
5084
5085
    type Op = fn(&Repo) -> Result<()>;
5086
    let edit_and_commit: Op = |r| {
5087
        write(r.root(), "f.txt", b"one\ntwo\n");
5088
        write(r.root(), "big.bin", &vec![7u8; 300_000]);
5089
        r.commit("second", &[]).map(|_| ())
5090
    };
5091
    let push: Op = |r| {
5092
        let res = r.push("origin", false)?;
5093
        if res.iter().all(|x| x.ok) {
5094
            Ok(())
5095
        } else {
5096
            Err(RepoError::Msg(format!("{res:?}")))
5097
        }
5098
    };
5099
5100
    for (name, prepare, op) in [
5101
        ("commit", None, edit_and_commit),
5102
        ("push", Some(edit_and_commit), push),
5103
    ] {
5104
        let mut steps = 0;
5105
        for n in 1.. {
5106
            let run = dir.path().join(format!("{name}-{n}"));
5107
            copy_tree(&pristine, &run);
5108
            // Clones record their remote by path; point it at this copy.
5109
            let open = |p: &Path| {
5110
                let mut r = Repo::open(p).unwrap().with_home(dir.path().join("home"));
5111
                r.config
5112
                    .set("remote.origin.url", &run.join("origin").to_string_lossy())
5113
                    .unwrap();
5114
                r.save_config().unwrap();
5115
                r
5116
            };
5117
            let a = open(&run.join("a"));
5118
            if let Some(prep) = prepare {
5119
                prep(&a).unwrap();
5120
            }
5121
            failpoint::crash_after(n);
5122
            let outcome = op(&a);
5123
            let crashed = failpoint::disarm();
5124
            drop(a);
5125
            if !crashed {
5126
                outcome.unwrap_or_else(|e| panic!("{name} failed without a crash: {e}"));
5127
                steps = n - 1;
5128
                break;
5129
            }
5130
            assert!(
5131
                outcome.is_err(),
5132
                "{name}: a crash at step {n} was swallowed"
5133
            );
5134
            for repo in ["a", "origin"] {
5135
                let r = Repo::open(&run.join(repo)).unwrap_or_else(|e| {
5136
                    panic!("{name} crash at step {n}: {repo} no longer opens: {e}")
5137
                });
5138
                let rep = r.fsck().unwrap();
5139
                assert_eq!(
5140
                    rep.errors(),
5141
                    0,
5142
                    "{name} crash at step {n}: {repo} fails fsck: {:?}",
5143
                    rep.problems
5144
                );
5145
            }
5146
            // The interrupted operation can simply be run again.
5147
            let a = open(&run.join("a"));
5148
            // A crash after the commit point leaves the commit done.
5149
            let landed = a
5150
                .bookmark_heads()
5151
                .unwrap()
5152
                .iter()
5153
                .any(|h| a.store().get_change(h).unwrap().message == "second");
5154
            let again = match (name, landed) {
5155
                ("commit", true) => Ok(()),
5156
                ("commit", false) => a.commit("second", &[]).map(|_| ()),
5157
                _ => op(&a),
5158
            };
5159
            again.unwrap_or_else(|e| panic!("{name} crash at step {n}: retry failed: {e}"));
5160
            assert_eq!(a.fsck().unwrap().errors(), 0);
5161
            fs::remove_dir_all(&run).unwrap();
5162
        }
5163
        assert!(steps >= 3, "{name} has only {steps} durable steps?");
5164
    }
5165
}
5166
5167
/// Spec §12.1: commands in two workspaces of one repository, and pushes,
5168
/// running at the same time lose nothing: every commit ends up on the
5169
/// bookmark, locally and on the remote, and the repository passes fsck.
5170
#[test]
5171
fn concurrent_commits_in_two_workspaces_lose_nothing() {
5172
    hermetic();
5173
    let dir = tempfile::tempdir().unwrap();
5174
    let root = dir.path();
5175
    let origin = root.join("origin");
5176
    Repo::init_bare_unbound(&origin).unwrap();
5177
    let main = root.join("main");
5178
    let mut repo = Repo::init(&main).unwrap();
5179
    repo.config
5180
        .set("remote.origin.url", &origin.to_string_lossy())
5181
        .unwrap();
5182
    repo.save_config().unwrap();
5183
    write(&main, "seed.txt", b"seed\n");
5184
    repo.commit("seed", &[]).unwrap();
5185
    let second = root.join("second");
5186
    repo.workspace_add(&second, None).unwrap();
5187
    drop(repo);
5188
5189
    const EACH: usize = 15;
5190
    std::thread::scope(|s| {
5191
        for (tag, dir, push) in [("a", main.clone(), true), ("b", second.clone(), false)] {
5192
            s.spawn(move || {
5193
                let r = Repo::open(&dir).unwrap();
5194
                for i in 0..EACH {
5195
                    write(
5196
                        &dir,
5197
                        &format!("{tag}-{i}.txt"),
5198
                        format!("{tag} {i}\n").as_bytes(),
5199
                    );
5200
                    r.commit(&format!("{tag} {i}"), &[]).unwrap();
5201
                    if push && i % 5 == 4 {
5202
                        // A push may be refused while the other workspace moves the bookmark; nothing may be lost either way.
5203
                        let _ = r.push("origin", false);
5204
                    }
5205
                }
5206
            });
5207
        }
5208
    });
5209
5210
    let repo = Repo::open(&main).unwrap();
5211
    let heads = repo.bookmark_heads().unwrap();
5212
    let state = repo.load_state(&heads).unwrap();
5213
    let messages: BTreeSet<String> = state.changes().map(|(_, m)| m.message.clone()).collect();
5214
    for tag in ["a", "b"] {
5215
        for i in 0..EACH {
5216
            assert!(
5217
                messages.contains(&format!("{tag} {i}")),
5218
                "lost commit {tag} {i}; have {messages:?}"
5219
            );
5220
        }
5221
    }
5222
    let rep = repo.fsck().unwrap();
5223
    assert_eq!(rep.errors(), 0, "{:?}", rep.problems);
5224
    assert!(repo.push("origin", false).unwrap().iter().all(|r| r.ok));
5225
    let hosted = Repo::open(&origin).unwrap();
5226
    let hosted_heads = hosted.bookmark_heads().unwrap();
5227
    assert_eq!(
5228
        hosted.load_state(&hosted_heads).unwrap().len(),
5229
        state.len(),
5230
        "the remote has every commit"
5231
    );
5232
}
5233
5234
/// Two operations recorded from the same parent (what two processes do
5235
/// when they race) are merged: both bookmarks' heads survive, and a
5236
/// change made on one side only is kept.
5237
#[test]
5238
fn operations_from_the_same_parent_are_merged() {
5239
    hermetic();
5240
    let dir = tempfile::tempdir().unwrap();
5241
    let root = dir.path();
5242
    let repo = Repo::init(root).unwrap();
5243
    write(root, "a.txt", b"a\n");
5244
    let a = repo.commit("a", &[]).unwrap();
5245
    write(root, "b.txt", b"b\n");
5246
    let b = repo.commit("b", &[]).unwrap();
5247
    let (x, op) = repo.head_op().unwrap();
5248
    let state = |heads: Vec<ChangeHash>| repo.store().put_state(&StateObject::new(heads)).unwrap();
5249
5250
    // Side one moves main to just `a` and adds a bookmark; side two moves main to just `b`.
5251
    let mut one = op.view.clone();
5252
    one.bookmarks.insert("main".into(), state(vec![a]));
5253
    one.bookmarks.insert("topic".into(), state(vec![a]));
5254
    let mut two = op.view.clone();
5255
    two.bookmarks.insert("main".into(), state(vec![b]));
5256
    repo.record_op(&[x], "one", one).unwrap();
5257
    let merged = repo.record_op(&[x], "two", two).unwrap();
5258
5259
    let (head, op) = repo.head_op().unwrap();
5260
    assert_eq!(head, merged);
5261
    assert_eq!(op.parents.len(), 2, "a merge of the two operations");
5262
    assert!(op.command.contains("merged with a concurrent operation"));
5263
    let mut main = repo
5264
        .store()
5265
        .get_state(&op.view.bookmarks["main"])
5266
        .unwrap()
5267
        .heads;
5268
    main.sort();
5269
    let mut want = vec![a, b];
5270
    want.sort();
5271
    assert_eq!(main, want, "both sides' heads are kept");
5272
    assert!(
5273
        op.view.bookmarks.contains_key("topic"),
5274
        "a one-sided change survives"
5275
    );
5276
    assert_eq!(repo.fsck().unwrap().errors(), 0);
5277
}
5278
5279
#[test]
5280
fn failed_requests_come_with_a_next_step() {
5281
    use crate::protocol::hint_for;
5282
    assert!(hint_for("https://h/x/oxy/v1/push: HTTP 401: bad token")
5283
        .unwrap()
5284
        .contains("token"));
5285
    assert!(hint_for("…: HTTP 403: forbidden")
5286
        .unwrap()
5287
        .contains("repo:write"));
5288
    assert!(hint_for("…: HTTP 404: no such repository")
5289
        .unwrap()
5290
        .contains("owner and repository name"));
5291
    assert!(hint_for("invalid peer certificate: UnknownIssuer")
5292
        .unwrap()
5293
        .contains("oxyhub-ca.pem"));
5294
    assert!(hint_for("Connect error: Connection refused (os error 111)")
5295
        .unwrap()
5296
        .contains("running"));
5297
    assert!(hint_for("Dns Failed: failed to lookup address information")
5298
        .unwrap()
5299
        .contains("resolve"));
5300
    assert_eq!(hint_for("something else entirely"), None);
5301
}
5302
5303
#[test]
5304
fn doctor_names_problems_and_what_to_do() {
5305
    hermetic();
5306
    let dir = tempfile::tempdir().unwrap();
5307
    let root = dir.path();
5308
    let origin = root.join("origin");
5309
    Repo::init_bare_unbound(&origin).unwrap();
5310
    let mut repo = Repo::init(&root.join("r"))
5311
        .unwrap()
5312
        .with_home(root.join("home"));
5313
    let find = |r: &DoctorReport, area: &str, h: Health| {
5314
        r.checks
5315
            .iter()
5316
            .find(|c| c.area == area && c.health == h)
5317
            .cloned()
5318
    };
5319
5320
    let r = repo.doctor(true);
5321
    assert!(find(&r, "identity", Health::Warn)
5322
        .unwrap()
5323
        .hint
5324
        .unwrap()
5325
        .contains("oxy identity create"));
5326
    assert!(find(&r, "repository", Health::Ok).is_some());
5327
5328
    repo.create_identity("Ada", "[email protected]", IdentityScope::Repo)
5329
        .unwrap();
5330
    repo.config.set("author.name", "Ada").unwrap();
5331
    repo.config.set("author.email", "[email protected]").unwrap();
5332
    repo.config
5333
        .set("remote.origin.url", &origin.to_string_lossy())
5334
        .unwrap();
5335
    repo.config
5336
        .set("remote.down.url", "http://127.0.0.1:9/a/b")
5337
        .unwrap();
5338
    repo.config.set("remote.down.token", "t").unwrap();
5339
    repo.config
5340
        .set("remote.badca.url", "https://example.invalid/a/b")
5341
        .unwrap();
5342
    repo.config
5343
        .set(
5344
            "remote.badca.ca",
5345
            &root.join("missing.pem").to_string_lossy(),
5346
        )
5347
        .unwrap();
5348
    repo.save_config().unwrap();
5349
5350
    let r = repo.doctor(true);
5351
    assert!(find(&r, "identity", Health::Ok).is_some(), "{r:?}");
5352
    assert!(find(&r, "author", Health::Ok).is_some(), "{r:?}");
5353
    assert!(find(&r, "remote origin", Health::Ok)
5354
        .unwrap()
5355
        .message
5356
        .contains("first push binds it"));
5357
    let down = find(&r, "remote down", Health::Fail).unwrap();
5358
    assert!(
5359
        down.hint.as_deref().unwrap_or("").contains("running"),
5360
        "{down:?}"
5361
    );
5362
    let badca = find(&r, "remote badca", Health::Fail).unwrap();
5363
    assert!(
5364
        badca.hint.unwrap().contains("remote.badca.ca"),
5365
        "the remote's own name is in the hint"
5366
    );
5367
    assert_eq!(r.worst(), Health::Fail);
5368
5369
    // Offline, nothing is contacted.
5370
    let r = repo.doctor(false);
5371
    assert!(find(&r, "remote down", Health::Fail).is_none());
5372
    assert!(find(&r, "remote down", Health::Ok)
5373
        .unwrap()
5374
        .message
5375
        .contains("not contacted"));
5376
}
5377
5378
/// Spec §8.1: deleting a line depends on whoever inserted the lines right
5379
/// after it. Inserting after `b` and then deleting `b`, one commit after
5380
/// the other, must not leave a delete/insert conflict.
5381
#[test]
5382
fn deleting_a_line_after_an_insertion_below_it_is_not_a_conflict() {
5383
    hermetic();
5384
    let dir = tempfile::tempdir().unwrap();
5385
    let root = dir.path();
5386
    let repo = Repo::init(root).unwrap();
5387
    write(root, "f", b"a\nb\nc\n");
5388
    repo.commit("base", &[]).unwrap();
5389
    write(root, "f", b"a\nb\nx\nc\n");
5390
    let insert = repo.commit("insert x after b", &[]).unwrap();
5391
    write(root, "f", b"a\nx\nc\n");
5392
    let delete = repo.commit("delete b", &[]).unwrap();
5393
    assert!(
5394
        repo.store()
5395
            .get_change(&delete)
5396
            .unwrap()
5397
            .deps
5398
            .contains(&insert),
5399
        "the deletion depends on the insertion below the deleted line"
5400
    );
5401
    let heads = repo.bookmark_heads().unwrap();
5402
    assert_eq!(heads, vec![delete]);
5403
    let snap = repo.load_state(&heads).unwrap().materialize();
5404
    assert!(!snap.is_conflicted());
5405
    assert!(
5406
        matches!(&snap.files["f"].content, FileContent::Text { bytes, .. } if bytes == b"a\nx\nc\n")
5407
    );
5408
}
5409
5410
/// Spec §9.3: a binary file reverted to an earlier blob keeps it, and each
5411
/// replacement depends on the change that set the blob it replaces.
5412
#[test]
5413
fn a_binary_file_reverted_to_an_earlier_blob_keeps_it() {
5414
    hermetic();
5415
    let dir = tempfile::tempdir().unwrap();
5416
    let root = dir.path();
5417
    let repo = Repo::init(root).unwrap();
5418
    write(root, "bin", b"\0A");
5419
    let v1 = repo.commit("v1", &[]).unwrap();
5420
    write(root, "bin", b"\0B");
5421
    let v2 = repo.commit("v2", &[]).unwrap();
5422
    assert!(repo.store().get_change(&v2).unwrap().deps.contains(&v1));
5423
    write(root, "bin", b"\0A");
5424
    let v3 = repo.commit("back to A", &[]).unwrap();
5425
    assert!(repo.store().get_change(&v3).unwrap().deps.contains(&v2));
5426
    assert_eq!(repo.bookmark_heads().unwrap(), vec![v3]);
5427
    let state = repo.load_state(&[v3]).unwrap();
5428
    let snap = state.materialize();
5429
    let FileContent::Opaque { blobs } = &snap.files["bin"].content else {
5430
        panic!("opaque")
5431
    };
5432
    assert_eq!(blobs.len(), 1, "one live blob, not none and not two");
5433
    assert_eq!(repo.read_blob(&blobs[0]).unwrap(), b"\0A");
5434
}
5435
5436
/// Spec §23: a binary file changed on two branches and merged in Git to
5437
/// one side's version comes back as that version at the merge, and the
5438
/// import verifies commit by commit.
5439
#[test]
5440
fn git_import_resolves_a_binary_merged_in_git_and_verifies() {
5441
    hermetic();
5442
    if std::process::Command::new("git")
5443
        .arg("--version")
5444
        .output()
5445
        .is_err()
5446
    {
5447
        eprintln!("git not installed; skipping");
5448
        return;
5449
    }
5450
    let dir = tempfile::tempdir().unwrap();
5451
    let root = dir.path();
5452
    let g = root.join("src.git");
5453
    fs::create_dir_all(&g).unwrap();
5454
    let git = |args: &[&str]| -> String {
5455
        let out = std::process::Command::new("git")
5456
            .arg("-C")
5457
            .arg(&g)
5458
            .args([
5459
                "-c",
5460
                "user.name=Grace",
5461
                "-c",
5462
                "[email protected]",
5463
                "-c",
5464
                "commit.gpgsign=false",
5465
            ])
5466
            .args(args)
5467
            .output()
5468
            .unwrap();
5469
        assert!(
5470
            out.status.success(),
5471
            "git {args:?}: {}",
5472
            String::from_utf8_lossy(&out.stderr)
5473
        );
5474
        String::from_utf8_lossy(&out.stdout).trim().to_string()
5475
    };
5476
    git(&["init", "-q", "-b", "main"]);
5477
    write(&g, "logo.bin", b"\0base");
5478
    write(&g, "notes.txt", b"a\nb\nc\n");
5479
    git(&["add", "."]);
5480
    git(&["commit", "-qm", "base"]);
5481
    git(&["checkout", "-qb", "side"]);
5482
    write(&g, "logo.bin", b"\0side");
5483
    write(&g, "notes.txt", b"a\nb\nx\nc\n");
5484
    git(&["commit", "-qam", "side"]);
5485
    git(&["checkout", "-q", "main"]);
5486
    write(&g, "logo.bin", b"\0main");
5487
    git(&["commit", "-qam", "main"]);
5488
    // Git cannot merge the binary; the merge takes main's and keeps side's text.
5489
    let _ = std::process::Command::new("git")
5490
        .arg("-C")
5491
        .arg(&g)
5492
        .args([
5493
            "-c",
5494
            "user.name=G",
5495
            "-c",
5496
            "user.email=g@e",
5497
            "merge",
5498
            "-q",
5499
            "side",
5500
        ])
5501
        .output();
5502
    write(&g, "logo.bin", b"\0main");
5503
    git(&["add", "."]);
5504
    git(&["commit", "-qm", "merge side"]);
5505
    // Then a revert of the binary to its first version.
5506
    write(&g, "logo.bin", b"\0base");
5507
    git(&["commit", "-qam", "back to base"]);
5508
5509
    let repo = Repo::init(&root.join("o")).unwrap();
5510
    let rep = repo.import_git(&g, "main").unwrap();
5511
    assert_eq!(rep.merges, 1);
5512
    let v = repo.verify_git_import(&g, "main").unwrap();
5513
    assert!(v.mismatches.is_empty(), "{:?}", v.mismatches);
5514
    assert_eq!(v.commits, 5);
5515
    let snap = repo
5516
        .load_state(&repo.bookmark_heads().unwrap())
5517
        .unwrap()
5518
        .materialize();
5519
    assert!(!snap.is_conflicted());
5520
    let FileContent::Opaque { blobs } = &snap.files["logo.bin"].content else {
5521
        panic!("opaque")
5522
    };
5523
    assert_eq!(repo.read_blob(&blobs[0]).unwrap(), b"\0base");
5524
}
5525
5526
/// Spec §7.7 on a file system without executable bits or symlinks: the
5527
/// recorded bit is kept, and a symlink checked out as a plain file holding
5528
/// its target is still that symlink.
5529
#[cfg(unix)]
5530
#[test]
5531
fn windows_file_systems_keep_exec_bits_and_symlinks() {
5532
    use crate::portable::Platform;
5533
    use std::os::unix::fs::PermissionsExt;
5534
    hermetic();
5535
    let dir = tempfile::tempdir().unwrap();
5536
    let root = dir.path();
5537
    let repo = Repo::init(root).unwrap();
5538
    write(root, "run.sh", b"#!/bin/sh\n");
5539
    fs::set_permissions(root.join("run.sh"), fs::Permissions::from_mode(0o755)).unwrap();
5540
    std::os::unix::fs::symlink("run.sh", root.join("link")).unwrap();
5541
    repo.commit("script and link", &[]).unwrap();
5542
    drop(repo);
5543
5544
    // What checking out on Windows leaves: no exec bit, the link as a file.
5545
    fs::set_permissions(root.join("run.sh"), fs::Permissions::from_mode(0o644)).unwrap();
5546
    fs::remove_file(root.join("link")).unwrap();
5547
    write(root, "link", b"run.sh");
5548
    let win = Repo::open(root).unwrap().with_platform(Platform::windows());
5549
    let s = win.snapshot("oxy status").unwrap();
5550
    assert!(
5551
        s.statuses.is_empty(),
5552
        "nothing changed on Windows: {:?}",
5553
        statuses(&s)
5554
    );
5555
    // Editing the file is a content change, not a mode change; retargeting the link keeps it a link.
5556
    write(root, "run.sh", b"#!/bin/sh\necho hi\n");
5557
    write(root, "link", b"other");
5558
    let h = win.commit("edit on Windows", &[]).unwrap();
5559
    let snap = win.load_state(&[h]).unwrap().materialize();
5560
    assert!(snap.files["run.sh"].mode.exec, "the exec bit survives");
5561
    assert_eq!(snap.files["link"].kind, NodeKind::Symlink);
5562
    // The same working copy read as Linux sees the lost bit and the plain file.
5563
    let linux = Repo::open(root).unwrap();
5564
    assert!(!linux.snapshot("oxy status").unwrap().statuses.is_empty());
5565
}
5566
5567
/// Paths that collide on case-insensitive or Windows file systems are
5568
/// named at checkout there, and by doctor everywhere.
5569
#[test]
5570
fn paths_other_platforms_cannot_hold_are_reported() {
5571
    use crate::portable::Platform;
5572
    hermetic();
5573
    let dir = tempfile::tempdir().unwrap();
5574
    let root = dir.path();
5575
    let repo = Repo::init(root).unwrap();
5576
    write(root, "README.md", b"a\n");
5577
    write(root, "readme.md", b"b\n");
5578
    write(root, "src/aux.c", b"int x;\n");
5579
    let h = repo.commit("unportable", &[]).unwrap();
5580
    let r = repo.doctor(false);
5581
    let port = r.checks.iter().find(|c| c.area == "portability").unwrap();
5582
    assert_eq!(port.health, Health::Warn);
5583
    assert!(
5584
        port.message.contains("differ only in case") && port.message.contains("aux.c"),
5585
        "{}",
5586
        port.message
5587
    );
5588
    let mac = Repo::open(root).unwrap().with_platform(Platform::macos());
5589
    let rep = mac.checkout(&[h], true, "oxy checkout").unwrap();
5590
    assert!(
5591
        rep.notes
5592
            .iter()
5593
            .any(|n| n.contains("README.md and readme.md")),
5594
        "{:?}",
5595
        rep.notes
5596
    );
5597
    assert!(
5598
        !rep.notes.iter().any(|n| n.contains("aux.c")),
5599
        "macOS allows aux.c"
5600
    );
5601
}
5602
5603
#[test]
5604
fn history_and_blame_of_a_loaded_state_match_the_full_walk() {
5605
    hermetic();
5606
    let dir = tempfile::tempdir().unwrap();
5607
    let repo = Repo::init(dir.path()).unwrap();
5608
    write(dir.path(), "a.txt", b"one\n");
5609
    write(dir.path(), "other.txt", b"x\n");
5610
    write(dir.path(), "bin.dat", &[0u8, 1, 2, 0, 255]);
5611
    repo.snapshot("t").unwrap();
5612
    let c1 = repo.commit("first", &[]).unwrap();
5613
    write(dir.path(), "other.txt", b"y\n");
5614
    repo.snapshot("t").unwrap();
5615
    repo.commit("other only", &[]).unwrap();
5616
    write(dir.path(), "a.txt", b"one\ntwo\n");
5617
    repo.snapshot("t").unwrap();
5618
    let c3 = repo.commit("second line", &[]).unwrap();
5619
    write(dir.path(), "other.txt", b"z\n");
5620
    repo.snapshot("t").unwrap();
5621
    repo.commit("other again", &[]).unwrap();
5622
5623
    let heads = repo.bookmark_heads().unwrap();
5624
    let state = repo.load_state(&heads).unwrap();
5625
    let full: Vec<ChangeHash> = repo
5626
        .log_for_path_in("a.txt", &heads)
5627
        .unwrap()
5628
        .iter()
5629
        .map(|e| e.hash)
5630
        .collect();
5631
    assert_eq!(
5632
        full,
5633
        vec![c3, c1],
5634
        "newest first, only changes touching the path"
5635
    );
5636
    let newest: Vec<ChangeHash> = repo
5637
        .log_for_path_of(&state, "a.txt", Some(1))
5638
        .unwrap()
5639
        .iter()
5640
        .map(|e| e.hash)
5641
        .collect();
5642
    assert_eq!(newest, vec![c3], "stops at the first");
5643
    assert_eq!(
5644
        repo.log_for_path_of(&state, "a.txt", None).unwrap().len(),
5645
        2
5646
    );
5647
    assert!(repo
5648
        .log_for_path_of(&state, "missing.txt", Some(1))
5649
        .is_err());
5650
    assert_eq!(
5651
        repo.log_state(&heads).unwrap().len(),
5652
        repo.log_of(&state).len()
5653
    );
5654
5655
    let tree = state.tree().view();
5656
    let via_state = repo.blame_of(&state, &tree, "a.txt").unwrap();
5657
    let via_heads = repo.blame_in("a.txt", &heads).unwrap();
5658
    assert_eq!(
5659
        via_state
5660
            .iter()
5661
            .map(|l| (l.hash, l.text.clone()))
5662
            .collect::<Vec<_>>(),
5663
        via_heads
5664
            .iter()
5665
            .map(|l| (l.hash, l.text.clone()))
5666
            .collect::<Vec<_>>()
5667
    );
5668
    assert_eq!(
5669
        via_state.iter().map(|l| l.hash).collect::<Vec<_>>(),
5670
        vec![c1, c3]
5671
    );
5672
    assert!(repo.blame_of(&state, &tree, "missing.txt").is_err());
5673
}
5674
5675
/// A text file whose stat matches the manifest and whose recorded hash is
5676
/// the base's content is taken from the base without reading it; anything
5677
/// else is read, so no edit is missed (spec §12.3).
5678
#[cfg(unix)]
5679
#[test]
5680
fn stat_cache_takes_unchanged_text_from_the_base_and_misses_no_edit() {
5681
    use std::os::unix::fs::PermissionsExt;
5682
    hermetic();
5683
    let dir = tempfile::tempdir().unwrap();
5684
    let root = dir.path();
5685
    let repo = Repo::init(root).unwrap().with_home(root.join("home"));
5686
    write(root, "a.txt", b"one\ntwo\n");
5687
    write(root, "b.txt", b"bee\n");
5688
    repo.commit("base", &[]).unwrap();
5689
    let age = |p: &str| {
5690
        let old = std::time::SystemTime::now() - std::time::Duration::from_secs(30);
5691
        fs::File::options()
5692
            .write(true)
5693
            .open(root.join(p))
5694
            .unwrap()
5695
            .set_modified(old)
5696
            .unwrap();
5697
    };
5698
    age("a.txt");
5699
    age("b.txt");
5700
    assert!(
5701
        !repo.snapshot("status").unwrap().changed,
5702
        "records the aged stat"
5703
    );
5704
5705
    // Clean and equal to the base: not read at all.
5706
    fs::set_permissions(root.join("a.txt"), fs::Permissions::from_mode(0o000)).unwrap();
5707
    let snap = repo.snapshot("status").unwrap();
5708
    assert!(
5709
        !snap.changed && snap.statuses.is_empty(),
5710
        "{:?}",
5711
        snap.statuses
5712
    );
5713
    fs::set_permissions(root.join("a.txt"), fs::Permissions::from_mode(0o644)).unwrap();
5714
5715
    // An uncommitted edit that is older than the manifest: stat-clean, but
5716
    // its hash is not the base's, so it is read and stays visible.
5717
    write(root, "b.txt", b"bee edited\n");
5718
    age("b.txt");
5719
    let first = repo.snapshot("status").unwrap();
5720
    assert_eq!(
5721
        statuses(&first),
5722
        vec![("b.txt".to_string(), ChangeStatus::Modified)]
5723
    );
5724
    let again = repo.snapshot("status").unwrap();
5725
    assert_eq!(
5726
        statuses(&again),
5727
        vec![("b.txt".to_string(), ChangeStatus::Modified)],
5728
        "still seen once stat-clean"
5729
    );
5730
    assert!(!again.changed, "and the working copy hashes the same");
5731
    fs::set_permissions(root.join("b.txt"), fs::Permissions::from_mode(0o000)).unwrap();
5732
    assert!(
5733
        repo.snapshot("status").is_err(),
5734
        "an edited file must be read, never taken from the base"
5735
    );
5736
    fs::set_permissions(root.join("b.txt"), fs::Permissions::from_mode(0o644)).unwrap();
5737
5738
    // A same-size edit made just now is racy and read.
5739
    write(root, "a.txt", b"one\nTWO\n");
5740
    assert_eq!(
5741
        statuses(&repo.snapshot("status").unwrap()),
5742
        vec![
5743
            ("a.txt".to_string(), ChangeStatus::Modified),
5744
            ("b.txt".to_string(), ChangeStatus::Modified)
5745
        ]
5746
    );
5747
    // Committing makes the edits the base: both are clean and served from it again.
5748
    repo.commit("edits", &[]).unwrap();
5749
    age("a.txt");
5750
    age("b.txt");
5751
    assert!(repo.snapshot("status").unwrap().statuses.is_empty());
5752
    fs::set_permissions(root.join("a.txt"), fs::Permissions::from_mode(0o000)).unwrap();
5753
    fs::set_permissions(root.join("b.txt"), fs::Permissions::from_mode(0o000)).unwrap();
5754
    let snap = repo.snapshot("status").unwrap();
5755
    assert!(!snap.changed && snap.statuses.is_empty());
5756
    fs::set_permissions(root.join("a.txt"), fs::Permissions::from_mode(0o644)).unwrap();
5757
    fs::set_permissions(root.join("b.txt"), fs::Permissions::from_mode(0o644)).unwrap();
5758
}
5759
5760
/// Version 2 checkpoints (spec §11): a large file's graph is a blob of its
5761
/// own, kept by gc, checked by fsck, shared by the next checkpoint when the
5762
/// file is unchanged, and loading through the checkpoint equals a full load.
5763
#[test]
5764
fn checkpoints_keep_large_graphs_as_blobs_of_their_own() {
5765
    hermetic();
5766
    let dir = tempfile::tempdir().unwrap();
5767
    let root = dir.path();
5768
    let repo = Repo::init(root).unwrap().with_home(root.join("home"));
5769
    let long: String = (0..300)
5770
        .map(|i| format!("line {i} of a long file\n"))
5771
        .collect();
5772
    write(root, "long.txt", long.as_bytes());
5773
    write(root, "short.txt", b"short\n");
5774
    repo.commit("base", &[]).unwrap();
5775
    let (r1, _, _) = repo.checkpoint().unwrap();
5776
    let cp1 = crate::objects::Checkpoint::decode(
5777
        &repo.store().get_typed(&r1, ObjectType::Checkpoint).unwrap(),
5778
    )
5779
    .unwrap();
5780
    let graphs1 = repo.checkpoint_graph_blobs(&cp1).unwrap();
5781
    assert_eq!(graphs1.len(), 1, "only the long file's graph is a blob");
5782
5783
    // gc keeps the graph blob; fsck finds the checkpoint sound.
5784
    repo.gc(true).unwrap();
5785
    assert!(repo.store().has(&graphs1[0]));
5786
    let report = repo.fsck().unwrap();
5787
    assert_eq!(report.errors(), 0, "{:?}", report.problems);
5788
5789
    // Loading through the checkpoint equals a full load.
5790
    write(root, "short.txt", b"short, edited\n");
5791
    repo.commit("edit the short file", &[]).unwrap();
5792
    let heads = repo.bookmark_heads().unwrap();
5793
    let fast = repo.load_state(&heads).unwrap();
5794
    let full = repo.load_state_full(&heads).unwrap();
5795
    assert_eq!(fast.checkpoint_payload(), full.checkpoint_payload());
5796
5797
    // The next checkpoint shares the unchanged long file's graph.
5798
    let (r2, _, _) = repo.checkpoint().unwrap();
5799
    let cp2 = crate::objects::Checkpoint::decode(
5800
        &repo.store().get_typed(&r2, ObjectType::Checkpoint).unwrap(),
5801
    )
5802
    .unwrap();
5803
    assert_eq!(repo.checkpoint_graph_blobs(&cp2).unwrap(), graphs1);
5804
5805
    // A shallow clone's bundle carries the graph blob with the checkpoint.
5806
    let bundle = repo.checkpoint_bundle_for(&heads).unwrap();
5807
    assert!(bundle.objects.iter().any(|(t, body)| *t == ObjectType::Blob
5808
        && crate::hash::hash_object(ObjectType::Blob, body) == graphs1[0]));
5809
5810
    // A version 1 checkpoint written by an older oxy still loads.
5811
    let state = repo.load_state_full(&heads).unwrap();
5812
    let old = repo.store_blob(&state.checkpoint_payload()).unwrap();
5813
    let cp_old = crate::objects::Checkpoint {
5814
        heads: cp2.heads.clone(),
5815
        count: cp2.count,
5816
        payload: old,
5817
    };
5818
    let r_old = repo
5819
        .store()
5820
        .put(ObjectType::Checkpoint, &cp_old.encode())
5821
        .unwrap();
5822
    repo.install_checkpoint("main", &r_old).unwrap();
5823
    assert_eq!(
5824
        repo.load_state(&heads).unwrap().checkpoint_payload(),
5825
        full.checkpoint_payload()
5826
    );
5827
    assert_eq!(repo.fsck().unwrap().errors(), 0);
5828
5829
    // A lost graph blob fails the load loudly rather than dropping the
5830
    // file, and fsck reports it (a fresh repository, objects still loose).
5831
    let dir2 = tempfile::tempdir().unwrap();
5832
    let root2 = dir2.path();
5833
    let repo2 = Repo::init(root2).unwrap().with_home(root2.join("home"));
5834
    write(root2, "long.txt", long.as_bytes());
5835
    repo2.commit("base", &[]).unwrap();
5836
    let (r, _, _) = repo2.checkpoint().unwrap();
5837
    let cp = crate::objects::Checkpoint::decode(
5838
        &repo2.store().get_typed(&r, ObjectType::Checkpoint).unwrap(),
5839
    )
5840
    .unwrap();
5841
    let graph = repo2.checkpoint_graph_blobs(&cp).unwrap()[0];
5842
    repo2.store().remove_loose_for_test(&graph).unwrap();
5843
    assert!(repo2.load_state(&repo2.bookmark_heads().unwrap()).is_err());
5844
    assert!(repo2.fsck().unwrap().errors() > 0, "fsck reports it");
5845
}
5846
5847
/// A new repository has not stored the user's identity yet (that happens
5848
/// at the first signed change); looking it up falls back to the key
5849
/// directory, and a file there that does not hash to the key is refused.
5850
#[test]
5851
fn identity_is_found_in_the_key_directory_for_a_new_repository() {
5852
    hermetic();
5853
    let dir = tempfile::tempdir().unwrap();
5854
    let home = dir.path().join("home");
5855
    let mut first = Repo::init(&dir.path().join("a"))
5856
        .unwrap()
5857
        .with_home(home.clone());
5858
    let (key, _) = first
5859
        .create_identity("Ada", "[email protected]", IdentityScope::User)
5860
        .unwrap();
5861
    let fresh = Repo::init(&dir.path().join("b"))
5862
        .unwrap()
5863
        .with_home(home.clone());
5864
    assert!(!fresh.store().has(&key), "nothing stored yet");
5865
    let id = fresh.identity(&key).unwrap();
5866
    assert_eq!((id.name.as_str(), id.hash()), ("Ada", key));
5867
    // A key file that is not this identity is an error, not a wrong answer.
5868
    let keys = fresh.keys_dir.clone();
5869
    let (other, _) = first
5870
        .create_identity("Bob", "[email protected]", IdentityScope::User)
5871
        .unwrap();
5872
    fs::copy(
5873
        keys.join(format!("{}.identity", other.to_hex())),
5874
        keys.join(format!("{}.identity", key.to_hex())),
5875
    )
5876
    .unwrap();
5877
    assert!(fresh
5878
        .identity(&key)
5879
        .unwrap_err()
5880
        .to_string()
5881
        .contains("does not hold identity"));
5882
}
5883
5884
/// Status snapshots (spec §12.3): a text file whose stat matches the
5885
/// manifest, and whose base graph key is the one the manifest recorded it
5886
/// equal to, is neither read nor rendered; any edit, and any change to the
5887
/// file's graph in the base, brings it back.
5888
#[cfg(unix)]
5889
#[test]
5890
fn status_snapshots_skip_files_unchanged_since_the_manifest() {
5891
    use std::os::unix::fs::PermissionsExt;
5892
    hermetic();
5893
    let dir = tempfile::tempdir().unwrap();
5894
    let root = dir.path();
5895
    let repo = Repo::init(root).unwrap().with_home(root.join("home"));
5896
    for (p, c) in [("a.txt", "one\n"), ("b.txt", "bee\n"), ("d/c.txt", "sea\n")] {
5897
        write(root, p, c.as_bytes());
5898
    }
5899
    repo.commit("base", &[]).unwrap();
5900
    let age = |p: &str| {
5901
        let old = std::time::SystemTime::now() - std::time::Duration::from_secs(30);
5902
        fs::File::options()
5903
            .write(true)
5904
            .open(root.join(p))
5905
            .unwrap()
5906
            .set_modified(old)
5907
            .unwrap();
5908
    };
5909
    let lock = |p: &str, mode: u32| {
5910
        fs::set_permissions(root.join(p), fs::Permissions::from_mode(mode)).unwrap()
5911
    };
5912
    for p in ["a.txt", "b.txt", "d/c.txt"] {
5913
        age(p);
5914
    }
5915
    assert!(repo.snapshot("status").unwrap().statuses.is_empty());
5916
    let (_, _, m) = repo.read_manifest().unwrap().unwrap();
5917
    assert!(
5918
        m.entries.values().all(|e| e.graph.is_some()),
5919
        "keys recorded"
5920
    );
5921
5922
    // Unreadable files prove they are not read; the status snapshot does
5923
    // not render them either, and its base lacks their graphs.
5924
    lock("a.txt", 0o000);
5925
    lock("b.txt", 0o000);
5926
    let snap = repo.snapshot_status("status").unwrap();
5927
    assert!(!snap.changed && snap.statuses.is_empty());
5928
    assert_eq!(
5929
        snap.base_snapshot
5930
            .unrendered
5931
            .iter()
5932
            .cloned()
5933
            .collect::<Vec<_>>(),
5934
        vec!["a.txt", "b.txt", "d/c.txt"]
5935
    );
5936
    assert!(!snap.base.is_full());
5937
    assert!(!snap.base_snapshot.is_conflicted());
5938
    // A full snapshot does not read them either, but renders everything.
5939
    let full = repo.snapshot("status").unwrap();
5940
    assert!(full.statuses.is_empty() && full.base.is_full());
5941
    assert!(full.base_snapshot.unrendered.is_empty());
5942
    assert!(matches!(&full.base_snapshot.files["a.txt"].content,
5943
        FileContent::Text { bytes, .. } if bytes == b"one\n"));
5944
5945
    // An edit is seen; the file is rendered, the others still are not.
5946
    write(root, "d/c.txt", b"sea edited\n");
5947
    let snap = repo.snapshot_status("status").unwrap();
5948
    assert_eq!(
5949
        statuses(&snap),
5950
        vec![("d/c.txt".to_string(), ChangeStatus::Modified)]
5951
    );
5952
    assert!(!snap.base_snapshot.unrendered.contains("d/c.txt"));
5953
    // So is a mode change of an unread file.
5954
    lock("b.txt", 0o100);
5955
    assert_eq!(
5956
        statuses(&repo.snapshot_status("status").unwrap()),
5957
        vec![
5958
            ("b.txt".to_string(), ChangeStatus::ModeChanged),
5959
            ("d/c.txt".to_string(), ChangeStatus::Modified)
5960
        ]
5961
    );
5962
    lock("b.txt", 0o000);
5963
5964
    // Committing c.txt changes its graph in the base, not a.txt's: a.txt
5965
    // stays unread, c.txt is read once and then skipped too.
5966
    repo.commit_selection("edit c", &[], &Selection::Paths(vec!["d/c.txt".into()]))
5967
        .unwrap();
5968
    age("d/c.txt");
5969
    let snap = repo.snapshot_status("status").unwrap();
5970
    assert!(snap.statuses.is_empty(), "{:?}", snap.statuses);
5971
    assert!(snap.base_snapshot.unrendered.contains("a.txt"));
5972
    lock("d/c.txt", 0o000);
5973
    let snap = repo.snapshot_status("status").unwrap();
5974
    assert!(snap.statuses.is_empty());
5975
    assert!(snap.base_snapshot.unrendered.contains("d/c.txt"));
5976
    for p in ["a.txt", "b.txt", "d/c.txt"] {
5977
        lock(p, 0o644);
5978
    }
5979
}
5980
5981
/// Attributes decide how a file compares with the base, so a changed
5982
/// `.oxyattributes` makes every text file be compared again.
5983
#[cfg(unix)]
5984
#[test]
5985
fn a_changed_attributes_file_disables_skipping_unchanged_files() {
5986
    hermetic();
5987
    let dir = tempfile::tempdir().unwrap();
5988
    let root = dir.path();
5989
    let repo = Repo::init(root).unwrap().with_home(root.join("home"));
5990
    write(root, "a.txt", b"crlf\r\n");
5991
    repo.commit("base", &[]).unwrap();
5992
    let old = std::time::SystemTime::now() - std::time::Duration::from_secs(30);
5993
    fs::File::options()
5994
        .write(true)
5995
        .open(root.join("a.txt"))
5996
        .unwrap()
5997
        .set_modified(old)
5998
        .unwrap();
5999
    assert!(repo.snapshot_status("status").unwrap().statuses.is_empty());
6000
    assert!(repo
6001
        .snapshot_status("status")
6002
        .unwrap()
6003
        .base_snapshot
6004
        .unrendered
6005
        .contains("a.txt"));
6006
    // With eol=lf, a.txt as stored no longer equals the base.
6007
    write(root, ".oxyattributes", b"*.txt eol=lf\n");
6008
    let snap = repo.snapshot_status("status").unwrap();
6009
    assert_eq!(
6010
        statuses(&snap),
6011
        vec![
6012
            (".oxyattributes".to_string(), ChangeStatus::Added),
6013
            ("a.txt".to_string(), ChangeStatus::Modified)
6014
        ]
6015
    );
6016
}
6017
6018
/// Bookmarks with `/` in their names: pushing records their
6019
/// attestations, and checkpoints are kept for them, beside `feature`
6020
/// itself.
6021
#[test]
6022
fn bookmarks_with_slashes_push_and_checkpoint() {
6023
    hermetic();
6024
    let dir = tempfile::tempdir().unwrap();
6025
    let root = dir.path();
6026
    let origin = Repo::init(&root.join("origin")).unwrap();
6027
    let url = root.join("origin").to_string_lossy().to_string();
6028
    let mut repo = Repo::clone(&url, &root.join("r"))
6029
        .unwrap()
6030
        .with_home(root.join("home"));
6031
    // With an identity, pushes carry reference attestations: the case
6032
    // that failed, since the attestation is a file named after the bookmark.
6033
    repo.create_identity("Ada", "[email protected]", IdentityScope::Repo)
6034
        .unwrap();
6035
    let r = root.join("r");
6036
    write(&r, "a.txt", b"a\n");
6037
    let h_a = repo.commit("a", &[]).unwrap();
6038
    assert!(repo.push("origin", false).unwrap()[0].ok);
6039
    origin.refresh().unwrap();
6040
    repo.bookmark_create("feature", None).unwrap();
6041
    repo.bookmark_create("feature/x", None).unwrap();
6042
    repo.bookmark_switch("feature/x", false).unwrap();
6043
    write(&r, "b.txt", b"b\n");
6044
    let h_b = repo.commit("b", &[]).unwrap();
6045
    for name in ["feature", "feature/x"] {
6046
        let res = repo.push_bookmark("origin", name, false).unwrap();
6047
        origin.refresh().unwrap();
6048
        assert!(res[0].ok, "{name}: {res:?}");
6049
    }
6050
    assert_eq!(origin.resolve_heads("feature").unwrap(), vec![h_a]);
6051
    assert_eq!(
6052
        origin.resolve_heads("feature/x").unwrap(),
6053
        repo.resolve_heads("feature/x").unwrap()
6054
    );
6055
    assert!(origin.resolve_heads("feature/x").unwrap().contains(&h_b));
6056
    assert!(origin.latest_ref_attest("feature/x").unwrap().is_some());
6057
    assert!(origin.latest_ref_attest("feature").unwrap().is_some());
6058
6059
    // A checkpoint of feature/x is found again when loading its state.
6060
    let (cp, _, _) = repo.checkpoint().unwrap();
6061
    assert_eq!(repo.latest_checkpoint("feature/x").unwrap().unwrap().0, cp);
6062
    assert!(repo.latest_checkpoint("feature").unwrap().is_none());
6063
    let heads = repo.resolve_heads("feature/x").unwrap();
6064
    assert!(repo.load_state_checkpointed(&heads).unwrap().is_some());
6065
}
6066
6067
/// Deleting a bookmark on a remote (spec §16.4): attested like any update,
6068
/// never the remote's own bookmark, and a bookmark created again later is
6069
/// accepted although the deletion's attestation stays the latest.
6070
#[test]
6071
fn bookmarks_are_deleted_on_a_remote() {
6072
    hermetic();
6073
    let dir = tempfile::tempdir().unwrap();
6074
    let root = dir.path();
6075
    let origin = Repo::init(&root.join("origin")).unwrap();
6076
    let url = root.join("origin").to_string_lossy().to_string();
6077
    let mut repo = Repo::clone(&url, &root.join("r"))
6078
        .unwrap()
6079
        .with_home(root.join("home"));
6080
    repo.create_identity("Ada", "[email protected]", IdentityScope::Repo)
6081
        .unwrap();
6082
    let r = root.join("r");
6083
    write(&r, "a.txt", b"a\n");
6084
    repo.commit("a", &[]).unwrap();
6085
    assert!(repo.push("origin", false).unwrap()[0].ok);
6086
    origin.refresh().unwrap();
6087
    repo.bookmark_create("feature/x", None).unwrap();
6088
    assert!(repo.push_bookmark("origin", "feature/x", false).unwrap()[0].ok);
6089
    origin.refresh().unwrap();
6090
    assert!(origin.resolve_heads("feature/x").is_ok());
6091
6092
    let res = repo.push_delete("origin", "feature/x").unwrap();
6093
    origin.refresh().unwrap();
6094
    assert!(res[0].ok, "{res:?}");
6095
    assert!(!origin.view().unwrap().bookmarks.contains_key("feature/x"));
6096
    let (_, att) = origin.latest_ref_attest("feature/x").unwrap().unwrap();
6097
    assert!(
6098
        matches!(att.attest.body, AttestBody::Ref { new_state, .. } if new_state.is_zero()),
6099
        "the deletion is attested"
6100
    );
6101
    assert!(
6102
        repo.view().unwrap().bookmarks.contains_key("feature/x"),
6103
        "the local bookmark stays"
6104
    );
6105
    assert!(!repo
6106
        .view()
6107
        .unwrap()
6108
        .remotes
6109
        .get("origin")
6110
        .is_some_and(|m| m.contains_key("feature/x")));
6111
6112
    // Pushing it again creates it again, past the deletion's serial.
6113
    let res = repo.push_bookmark("origin", "feature/x", false).unwrap();
6114
    origin.refresh().unwrap();
6115
    assert!(res[0].ok, "{res:?}");
6116
    assert!(origin.view().unwrap().bookmarks.contains_key("feature/x"));
6117
6118
    // Nothing to delete, and never the remote's own bookmark.
6119
    assert!(repo.push_delete("origin", "nope").is_err());
6120
    let res = repo.push_delete("origin", "main").unwrap();
6121
    origin.refresh().unwrap();
6122
    assert!(
6123
        !res[0].ok && res[0].reason.contains("default bookmark"),
6124
        "{res:?}"
6125
    );
6126
    assert!(origin.view().unwrap().bookmarks.contains_key("main"));
6127
}
6128
6129
/// `bookmark switch --carry` (spec §10.1): uncommitted work goes along
6130
/// when the target has the same versions of the files it touches, and is
6131
/// refused, untouched, when it has others.
6132
#[test]
6133
fn switching_bookmarks_carries_uncommitted_work() {
6134
    hermetic();
6135
    let dir = tempfile::tempdir().unwrap();
6136
    let root = dir.path();
6137
    let mut repo = Repo::init(root).unwrap().with_home(root.join("home"));
6138
    write(root, "a.txt", b"a\n");
6139
    write(root, "b.txt", b"b\n");
6140
    write(root, "gone.txt", b"gone\n");
6141
    repo.commit("base", &[]).unwrap();
6142
    repo.bookmark_create("feature", None).unwrap();
6143
    // Started on main, belongs on feature: edit, add, remove.
6144
    write(root, "a.txt", b"a\nmore\n");
6145
    write(root, "new.txt", b"new\n");
6146
    fs::remove_file(root.join("gone.txt")).unwrap();
6147
    let (_, carried) = repo.bookmark_switch_carry("feature").unwrap();
6148
    assert_eq!(carried, vec!["a.txt", "gone.txt", "new.txt"]);
6149
    assert_eq!(repo.config.bookmark, "feature");
6150
    assert_eq!(fs::read(root.join("a.txt")).unwrap(), b"a\nmore\n");
6151
    assert_eq!(fs::read(root.join("new.txt")).unwrap(), b"new\n");
6152
    assert!(!root.join("gone.txt").exists());
6153
    let snap = repo.snapshot("status").unwrap();
6154
    assert_eq!(
6155
        statuses(&snap),
6156
        vec![
6157
            ("a.txt".to_string(), ChangeStatus::Modified),
6158
            ("gone.txt".to_string(), ChangeStatus::Removed),
6159
            ("new.txt".to_string(), ChangeStatus::Added)
6160
        ]
6161
    );
6162
    repo.commit("the work", &[]).unwrap();
6163
    assert!(repo.resolve_heads("main").unwrap().len() == 1);
6164
6165
    // main moves b.txt on; work on feature touching b.txt cannot follow.
6166
    repo.bookmark_switch("main", false).unwrap();
6167
    write(root, "b.txt", b"b on main\n");
6168
    repo.commit("b on main", &[]).unwrap();
6169
    repo.bookmark_switch("feature", false).unwrap();
6170
    write(root, "b.txt", b"b edited\n");
6171
    let err = repo.bookmark_switch_carry("main").unwrap_err().to_string();
6172
    assert!(err.contains("b.txt") && err.contains("--discard"), "{err}");
6173
    assert_eq!(repo.config.bookmark, "feature", "nothing happened");
6174
    assert_eq!(fs::read(root.join("b.txt")).unwrap(), b"b edited\n");
6175
}
6176
6177
/// Merging and checking out (feedback 3): a working copy without changes
6178
/// follows a merge whichever state it sat on; a refused checkout names
6179
/// what is in the way; `checkout --carry` takes the work along.
6180
#[test]
6181
fn merges_move_clean_working_copies_and_checkouts_say_what_blocks_them() {
6182
    hermetic();
6183
    let dir = tempfile::tempdir().unwrap();
6184
    let root = dir.path();
6185
    let mut repo = Repo::init(root).unwrap().with_home(root.join("home"));
6186
    write(root, "a.txt", b"a\n");
6187
    let h1 = repo.commit("a", &[]).unwrap();
6188
    write(root, "b.txt", b"b\n");
6189
    repo.commit("b", &[]).unwrap();
6190
    repo.bookmark_create("feature", None).unwrap();
6191
    repo.bookmark_switch("feature", false).unwrap();
6192
    write(root, "c.txt", b"c\n");
6193
    repo.commit("c on feature", &[]).unwrap();
6194
    repo.bookmark_switch("main", false).unwrap();
6195
    // The working copy sits on an older state than main's heads.
6196
    repo.checkout(&[h1], false, "checkout").unwrap();
6197
    assert!(!root.join("b.txt").exists());
6198
    let m = repo.merge("feature").unwrap();
6199
    assert!(m.checked_out, "a clean working copy follows the merge");
6200
    for f in ["a.txt", "b.txt", "c.txt"] {
6201
        assert!(root.join(f).exists(), "{f}");
6202
    }
6203
6204
    // A refusal says which paths are in the way and what to do.
6205
    fs::remove_file(root.join("b.txt")).unwrap();
6206
    write(root, "a.txt", b"a edited\n");
6207
    let err = repo
6208
        .checkout(&[h1], false, "checkout")
6209
        .unwrap_err()
6210
        .to_string();
6211
    assert!(
6212
        err.contains("modified a.txt") && err.contains("removed b.txt") && err.contains("--carry"),
6213
        "{err}"
6214
    );
6215
    // --carry takes them along: h1 has a.txt as the base has it, and the
6216
    // removed b.txt is already as h1 has it (none), so that is no conflict
6217
    // either (oxygen#100).
6218
    let (_, carried) = repo
6219
        .checkout_carry(&[h1], "the first change", "checkout")
6220
        .unwrap();
6221
    assert_eq!(carried, vec!["a.txt"]);
6222
    assert_eq!(fs::read(root.join("a.txt")).unwrap(), b"a edited\n");
6223
    assert!(!root.join("b.txt").exists(), "h1 has no b.txt");
6224
}
6225
6226
/// Doctor and subrepos before the first commit (feedback 5 and 8): a
6227
/// user identity not stored in a new repository yet is fine while its
6228
/// secret key is there; an added subrepo is listed as not committed yet.
6229
#[test]
6230
fn a_new_repository_is_healthy_before_its_first_commit() {
6231
    hermetic();
6232
    let dir = tempfile::tempdir().unwrap();
6233
    let root = dir.path();
6234
    let home = root.join("home");
6235
    let mut first = Repo::init(&root.join("first"))
6236
        .unwrap()
6237
        .with_home(home.clone());
6238
    let (key, _) = first
6239
        .create_identity("Ada", "[email protected]", IdentityScope::User)
6240
        .unwrap();
6241
    let repo = Repo::init(&root.join("second"))
6242
        .unwrap()
6243
        .with_home(home.clone());
6244
    // Only the secret key: no identity object anywhere this repository sees.
6245
    let keys = repo.keys_dir.clone();
6246
    let _ = fs::remove_file(keys.join(format!("{}.identity", key.to_hex())));
6247
    assert!(keys.join(format!("{}.secret", key.to_hex())).is_file());
6248
    let r = repo.doctor(true);
6249
    let id = r.checks.iter().find(|c| c.area == "identity").unwrap();
6250
    assert_eq!(id.health, Health::Ok, "{}", id.message);
6251
    assert!(id.message.contains("first signed change"), "{}", id.message);
6252
6253
    // A subrepo added and not committed yet is listed, pinned where it is.
6254
    let lib = root.join("lib");
6255
    let l = Repo::init(&lib).unwrap().with_home(home.clone());
6256
    write(&lib, "x.txt", b"x\n");
6257
    l.commit("x", &[]).unwrap();
6258
    let second = root.join("second");
6259
    write(&second, "a.txt", b"a\n");
6260
    repo.submodule_add(&lib.to_string_lossy(), "deps/lib", None)
6261
        .unwrap();
6262
    let subs = repo.subrepos().unwrap();
6263
    assert_eq!(subs.len(), 1);
6264
    assert_eq!(
6265
        (subs[0].path.as_str(), subs[0].committed),
6266
        ("deps/lib", false)
6267
    );
6268
    assert_eq!(subs[0].actual.as_ref(), Some(&subs[0].pin));
6269
    repo.commit("add lib", &[]).unwrap();
6270
    let subs = repo.subrepos().unwrap();
6271
    assert!(subs[0].committed, "committed now");
6272
}
6273
6274
/// Commit, diff, hunks and discard use the partial snapshot: a file
6275
/// unchanged since the manifest is neither read nor rendered, and showing
6276
/// a change renders only what it edits, the same as from a full base.
6277
#[cfg(unix)]
6278
#[test]
6279
fn commits_and_diffs_leave_unchanged_files_alone() {
6280
    use std::os::unix::fs::PermissionsExt;
6281
    hermetic();
6282
    let dir = tempfile::tempdir().unwrap();
6283
    let root = dir.path();
6284
    let repo = Repo::init(root).unwrap().with_home(root.join("home"));
6285
    write(root, "big.txt", b"lots\nof\nlines\n");
6286
    write(root, "a.txt", b"one\ntwo\n");
6287
    repo.commit("base", &[]).unwrap();
6288
    let old = std::time::SystemTime::now() - std::time::Duration::from_secs(30);
6289
    for f in ["big.txt", "a.txt"] {
6290
        fs::File::options()
6291
            .write(true)
6292
            .open(root.join(f))
6293
            .unwrap()
6294
            .set_modified(old)
6295
            .unwrap();
6296
    }
6297
    assert!(repo.snapshot_status("status").unwrap().statuses.is_empty());
6298
    // big.txt cannot be read at all from here on.
6299
    fs::set_permissions(root.join("big.txt"), fs::Permissions::from_mode(0o000)).unwrap();
6300
6301
    write(root, "a.txt", b"one\nTWO\nthree\n");
6302
    let diff = repo.diff_files(None).unwrap();
6303
    assert_eq!(
6304
        diff.iter().map(|f| f.path.as_str()).collect::<Vec<_>>(),
6305
        ["a.txt"]
6306
    );
6307
    let (_, hunks) = repo.hunks().unwrap();
6308
    assert!(!hunks.is_empty() && hunks.iter().all(|h| h.path == "a.txt"));
6309
    let h = repo.commit("edit a", &[]).unwrap();
6310
6311
    // Showing the change needs only a.txt's graph, and renders as a full base does.
6312
    let c = repo.store().get_change(&h).unwrap();
6313
    let full = repo.load_state(&c.deps).unwrap();
6314
    let want = render_change(&c, &full, &full.materialize());
6315
    assert_eq!(repo.describe_change(&h).unwrap(), want);
6316
    let (base, snap) = repo.change_base(&c).unwrap();
6317
    assert!(!base.is_full() && snap.unrendered.contains("big.txt"));
6318
6319
    // Discarding works the same way.
6320
    write(root, "a.txt", b"scratch\n");
6321
    assert_eq!(repo.discard(&["a.txt".into()]).unwrap(), 1);
6322
    assert_eq!(fs::read(root.join("a.txt")).unwrap(), b"one\nTWO\nthree\n");
6323
    fs::set_permissions(root.join("big.txt"), fs::Permissions::from_mode(0o644)).unwrap();
6324
}
6325
6326
/// A replace conflict (spec §9.3) is settled by a change that writes one
6327
/// candidate, or new bytes, at the path when the caller names it; a plain
6328
/// snapshot of a checkout never settles it on its own.
6329
#[test]
6330
fn replace_conflicts_are_settled_when_asked() {
6331
    hermetic();
6332
    let dir = tempfile::tempdir().unwrap();
6333
    let root = dir.path();
6334
    let mut repo = Repo::init(root).unwrap().with_home(root.join("home"));
6335
    let blob = |n: u8| {
6336
        let mut v = vec![0u8; 64];
6337
        v[1] = n;
6338
        v
6339
    };
6340
    write(root, "img.bin", &blob(1));
6341
    repo.commit("add img", &[]).unwrap();
6342
    repo.bookmark_create("other", None).unwrap();
6343
    write(root, "img.bin", &blob(2));
6344
    repo.commit("img two", &[]).unwrap();
6345
    repo.bookmark_switch("other", false).unwrap();
6346
    write(root, "img.bin", &blob(3));
6347
    repo.commit("img three", &[]).unwrap();
6348
    repo.bookmark_switch("main", false).unwrap();
6349
    repo.merge("other").unwrap();
6350
    let heads = repo.bookmark_heads().unwrap();
6351
    let merged = repo.load_state(&heads).unwrap().materialize();
6352
    assert!(
6353
        matches!(&merged.files["img.bin"].content, FileContent::Opaque { blobs } if blobs.len() == 2),
6354
        "a replace conflict"
6355
    );
6356
    // A snapshot of the checkout records nothing.
6357
    assert!(repo
6358
        .snapshot("status")
6359
        .unwrap()
6360
        .statuses
6361
        .iter()
6362
        .all(|s| s.path != "img.bin"));
6363
6364
    // Keeping candidate 3 settles it.
6365
    let author = repo.author();
6366
    let edits = [FileEdit {
6367
        path: "img.bin".into(),
6368
        content: Some(blob(3)),
6369
    }];
6370
    let c = repo
6371
        .build_change(&heads, &edits, "keep three", author)
6372
        .unwrap();
6373
    assert_eq!(c.kind, ChangeKind::Resolution);
6374
    let mut st = repo.load_state(&heads).unwrap();
6375
    for d in &c.deps {
6376
        assert!(st.contains(d));
6377
    }
6378
    assert!(
6379
        heads.iter().all(|h| c.deps.contains(h)),
6380
        "depends on both contributors"
6381
    );
6382
    st.add(c).unwrap();
6383
    let after = st.materialize();
6384
    assert!(!after.is_conflicted());
6385
    assert_eq!(
6386
        after.files["img.bin"].content,
6387
        FileContent::Opaque {
6388
            blobs: vec![Repo::blob_ref(&blob(3))]
6389
        }
6390
    );
6391
6392
    // New bytes settle it too.
6393
    let edits = [FileEdit {
6394
        path: "img.bin".into(),
6395
        content: Some(blob(9)),
6396
    }];
6397
    let c = repo.build_change(&heads, &edits, "new", author).unwrap();
6398
    let mut st = repo.load_state(&heads).unwrap();
6399
    st.add(c).unwrap();
6400
    assert_eq!(
6401
        st.materialize().files["img.bin"].content,
6402
        FileContent::Opaque {
6403
            blobs: vec![Repo::blob_ref(&blob(9))]
6404
        }
6405
    );
6406
}
6407
6408
/// The history of a range of lines (spec §27): the changes that wrote
6409
/// or deleted its atoms, or deleted atoms from between them; edits outside
6410
/// the range and changes the range's lines survived are not in it.
6411
#[test]
6412
fn line_ranges_have_exact_histories() {
6413
    hermetic();
6414
    let dir = tempfile::tempdir().unwrap();
6415
    let root = dir.path();
6416
    let repo = Repo::init(root).unwrap().with_home(root.join("home"));
6417
    write(root, "f.rs", b"use x;\nfn a() {\n  one();\n  two();\n}\n");
6418
    let base = repo.commit("add f", &[]).unwrap();
6419
    write(root, "f.rs", b"use y;\nfn a() {\n  one();\n  two();\n}\n");
6420
    let outside = repo.commit("change the import", &[]).unwrap();
6421
    write(root, "f.rs", b"use y;\nfn a() {\n  ONE();\n  two();\n}\n");
6422
    let inside = repo.commit("edit a line of a", &[]).unwrap();
6423
    write(root, "f.rs", b"use y;\nfn a() {\n  ONE();\n}\n");
6424
    let deleted = repo.commit("delete a line of a", &[]).unwrap();
6425
    write(root, "f.rs", b"use y;\nfn a() {\n  ONE();\n}\nfn b() {}\n");
6426
    let after = repo.commit("add b after a", &[]).unwrap();
6427
    let heads = repo.bookmark_heads().unwrap();
6428
6429
    // Lines 2..4 are `fn a() {`, `ONE();`, `}` now.
6430
    let hist: Vec<ChangeHash> = repo
6431
        .line_history(&heads, "f.rs", 2, 4)
6432
        .unwrap()
6433
        .iter()
6434
        .map(|e| e.hash)
6435
        .collect();
6436
    for (h, what) in [
6437
        (base, "wrote it"),
6438
        (inside, "edited a line"),
6439
        (deleted, "deleted a line from inside"),
6440
    ] {
6441
        assert!(hist.contains(&h), "{what}");
6442
    }
6443
    for (h, what) in [(outside, "an edit above"), (after, "an addition below")] {
6444
        assert!(!hist.contains(&h), "{what}");
6445
    }
6446
    assert_eq!(hist[0], deleted, "newest first");
6447
    // One line: only what touched it.
6448
    let one: Vec<ChangeHash> = repo
6449
        .line_history(&heads, "f.rs", 1, 1)
6450
        .unwrap()
6451
        .iter()
6452
        .map(|e| e.hash)
6453
        .collect();
6454
    assert!(one.contains(&outside) && !one.contains(&inside));
6455
    assert!(repo.line_history(&heads, "f.rs", 3, 9).is_err());
6456
    assert!(repo.line_history(&heads, "f.rs", 0, 1).is_err());
6457
    assert!(repo.line_history(&heads, "nope.rs", 1, 1).is_err());
6458
}
6459
6460
#[test]
6461
fn receipts_are_kept_with_their_state_and_verified() {
6462
    use crate::receipt::{Receipt, SignedReceipt};
6463
    hermetic();
6464
    let dir = tempfile::tempdir().unwrap();
6465
    let root = dir.path();
6466
    let repo = Repo::init(root).unwrap().with_home(root.join("home"));
6467
    write(root, "a.txt", b"1\n");
6468
    repo.commit("A", &[]).unwrap();
6469
    let heads = repo.bookmark_heads().unwrap();
6470
    let state = repo
6471
        .store()
6472
        .put_state(&StateObject::new(heads.clone()))
6473
        .unwrap();
6474
    let out = repo.store_blob(b"built\n").unwrap();
6475
    let receipt = Receipt {
6476
        job_name: "build".into(),
6477
        pipeline_hash: ObjectRef([1; 32]),
6478
        scope_tree_hash: ObjectRef([2; 32]),
6479
        inputs: vec![],
6480
        environment: ObjectRef([3; 32]),
6481
        outputs: vec![out],
6482
        exit_code: 0,
6483
        duration_ms: 42,
6484
    };
6485
    let sk = SecretKey::generate();
6486
    let runner = sk.identity("earth-1", "runner@earth", 1);
6487
    let sr = SignedReceipt::sign(
6488
        receipt.clone(),
6489
        repo.id().unwrap(),
6490
        state,
6491
        "demo#1",
6492
        &runner,
6493
        &sk,
6494
    );
6495
6496
    let r = repo.add_receipt(&sr).unwrap();
6497
    let found = repo.receipts(&heads).unwrap();
6498
    assert_eq!(found.len(), 1);
6499
    assert_eq!(found[0].attest, r);
6500
    assert_eq!(found[0].signed, sr);
6501
    assert!(found[0].problem.is_none() && !found[0].revoked);
6502
    assert!(repo.receipts(&[ObjectRef([5; 32])]).unwrap().is_empty());
6503
6504
    // Another repository's receipt, or a forged one, is refused.
6505
    let elsewhere = SignedReceipt::sign(receipt.clone(), [0; 16], state, "x", &runner, &sk);
6506
    assert!(repo
6507
        .add_receipt(&elsewhere)
6508
        .unwrap_err()
6509
        .to_string()
6510
        .contains("another repository"));
6511
    let mut forged = sr.clone();
6512
    forged.receipt.exit_code = 1;
6513
    assert!(repo
6514
        .add_receipt(&forged)
6515
        .unwrap_err()
6516
        .to_string()
6517
        .contains("does not verify"));
6518
6519
    // A receipt signed by a short-lived key keeps its certificate and the
6520
    // issuer's identity, and reads back with them (oxygenhub#241).
6521
    let hub_sk = SecretKey::generate();
6522
    let hub = hub_sk.identity("oxygenhub.io", "[email protected]", 1);
6523
    let job_sk = SecretKey::generate();
6524
    let job = job_sk.identity("job 2 test", "[email protected]", 1);
6525
    let mut test_receipt = receipt.clone();
6526
    test_receipt.job_name = "test".into();
6527
    let plain = SignedReceipt::sign(
6528
        test_receipt,
6529
        repo.id().unwrap(),
6530
        state,
6531
        "demo#2",
6532
        &job,
6533
        &job_sk,
6534
    );
6535
    let now = plain.attest.hlc.wall_ms;
6536
    let cert = crate::cert::SignedCertificate::sign(
6537
        crate::cert::Certificate {
6538
            key: job.clone(),
6539
            issuer: hub.hash(),
6540
            subject: "repo:andy/demo:bookmark:main".into(),
6541
            claims: vec![],
6542
            scope: crate::identity::Scope::SEAL,
6543
            not_before: now - 1_000,
6544
            expires: now + 600_000,
6545
            grant: None,
6546
        },
6547
        &hub,
6548
        &hub_sk,
6549
    );
6550
    let certified = plain.with_certificate(cert, hub.clone());
6551
    repo.add_receipt(&certified).unwrap();
6552
    let found = repo.receipts(&heads).unwrap();
6553
    let got = found
6554
        .iter()
6555
        .find(|i| i.signed.receipt.job_name == "test")
6556
        .unwrap();
6557
    assert_eq!(got.signed, certified);
6558
    assert!(got.problem.is_none(), "{:?}", got.problem);
6559
6560
    // gc keeps the receipts, their runners, the certificate and its issuer,
6561
    // and the output while the state lives.
6562
    repo.gc(true).unwrap();
6563
    let found = repo.receipts(&heads).unwrap();
6564
    assert_eq!(found.len(), 2);
6565
    let got = found
6566
        .iter()
6567
        .find(|i| i.signed.receipt.job_name == "test")
6568
        .unwrap();
6569
    assert_eq!(got.signed, certified, "the certificate survives gc");
6570
    assert!(got.problem.is_none());
6571
    assert_eq!(repo.read_blob(&out).unwrap(), b"built\n");
6572
    assert!(repo.fsck().unwrap().problems.is_empty());
6573
}
6574
6575
#[test]
6576
fn approvals_are_kept_with_their_state_and_survive_gc() {
6577
    hermetic();
6578
    let dir = tempfile::tempdir().unwrap();
6579
    let root = dir.path();
6580
    let repo = Repo::init(root).unwrap().with_home(root.join("home"));
6581
    write(root, "a.txt", b"1\n");
6582
    repo.commit("A", &[]).unwrap();
6583
    let heads = repo.bookmark_heads().unwrap();
6584
    let state = repo.store().put_state(&StateObject::new(heads)).unwrap();
6585
    let plan = repo.store_blob(b"the reviewed plan\n").unwrap();
6586
    let sk = SecretKey::generate();
6587
    let andy = sk.identity("Andy", "[email protected]", 1);
6588
    let statement = crate::approval::Statement {
6589
        repo: repo.id().unwrap(),
6590
        run: "https://hub.example/andy/infra/flow/8".into(),
6591
        job: "apply".into(),
6592
        job_hash: ObjectRef([1; 32]),
6593
        state,
6594
        inputs: vec![plan],
6595
        environment: "prod".into(),
6596
        approve: true,
6597
    };
6598
    let sa = crate::approval::SignedApproval::sign(&statement, &andy, &sk);
6599
    let r = repo.add_approval(&sa).unwrap();
6600
    assert_eq!(repo.store().approvals_for(&state).unwrap(), vec![r]);
6601
    // Another repository's approval, or a changed one, is refused.
6602
    let elsewhere = crate::approval::SignedApproval::sign(
6603
        &crate::approval::Statement {
6604
            repo: [0; 16],
6605
            ..statement.clone()
6606
        },
6607
        &andy,
6608
        &sk,
6609
    );
6610
    assert!(repo
6611
        .add_approval(&elsewhere)
6612
        .unwrap_err()
6613
        .to_string()
6614
        .contains("another repository"));
6615
    let mut forged = sa.clone();
6616
    if let AttestBody::Approval { environment, .. } = &mut forged.attest.body {
6617
        *environment = "dev".into();
6618
    }
6619
    assert!(repo
6620
        .add_approval(&forged)
6621
        .unwrap_err()
6622
        .to_string()
6623
        .contains("does not verify"));
6624
    // gc keeps it, its signature and its signer while the state lives.
6625
    repo.gc(true).unwrap();
6626
    assert_eq!(repo.store().approvals_for(&state).unwrap(), vec![r]);
6627
    assert_eq!(repo.store().get_attest(&r).unwrap(), sa.attest);
6628
    assert_eq!(repo.store().signatures(&r).unwrap(), sa.sigs);
6629
    assert!(repo.fsck().unwrap().problems.is_empty());
6630
}
6631
6632
#[test]
6633
fn status_leaves_an_unchanged_manifest_alone() {
6634
    hermetic();
6635
    let dir = tempfile::tempdir().unwrap();
6636
    let root = dir.path();
6637
    let repo = Repo::init(root).unwrap().with_home(root.join("home"));
6638
    write(root, "a.txt", b"1\n");
6639
    write(root, "b.txt", b"2\n");
6640
    repo.commit("A", &[]).unwrap();
6641
    // Files last touched well outside the racy window.
6642
    let old = std::time::SystemTime::now() - std::time::Duration::from_secs(60);
6643
    for f in ["a.txt", "b.txt"] {
6644
        fs::File::options()
6645
            .write(true)
6646
            .open(root.join(f))
6647
            .unwrap()
6648
            .set_modified(old)
6649
            .unwrap();
6650
    }
6651
    repo.snapshot_status("status").unwrap();
6652
    let path = repo.manifest_path();
6653
    let first = fs::read(&path).unwrap();
6654
    repo.snapshot_status("status").unwrap();
6655
    assert_eq!(
6656
        fs::read(&path).unwrap(),
6657
        first,
6658
        "an unchanged tree does not rewrite the manifest"
6659
    );
6660
    // A change rewrites it.
6661
    write(root, "a.txt", b"1\n2\n");
6662
    repo.snapshot_status("status").unwrap();
6663
    assert_ne!(fs::read(&path).unwrap(), first);
6664
}
6665
6666
#[test]
6667
fn large_text_files_travel_and_survive_gc_as_text_blobs() {
6668
    hermetic();
6669
    let dir = tempfile::tempdir().unwrap();
6670
    let root = dir.path();
6671
    let origin_path = root.join("origin");
6672
    Repo::init(&origin_path).unwrap();
6673
    let origin_url = origin_path.to_string_lossy().to_string();
6674
    let a = Repo::clone(&origin_url, &root.join("a")).unwrap();
6675
    let big: String = (0..5000).map(|i| format!("line {i}\n")).collect();
6676
    write(&root.join("a"), "big.txt", big.as_bytes());
6677
    write(&root.join("a"), "small.txt", b"small\n");
6678
    let h1 = a.commit("large", &[]).unwrap();
6679
    let (_, body) = a.store().get(&h1).unwrap();
6680
    assert!(body.len() < 2048, "the change is {} bytes", body.len());
6681
    assert!(a.push("origin", false).unwrap()[0].ok);
6682
6683
    // A clone reads the text from the blobs that came with the change.
6684
    let b = Repo::clone(&origin_url, &root.join("b")).unwrap();
6685
    assert_eq!(fs::read(root.join("b/big.txt")).unwrap(), big.as_bytes());
6686
    // An edit in the middle of the stored insert is an ordinary change.
6687
    let edited = big.replace("line 2500\n", "line 2500, edited\n");
6688
    write(&root.join("b"), "big.txt", edited.as_bytes());
6689
    let h2 = b.commit("edit", &[]).unwrap();
6690
    assert!(b.store().get_change(&h2).unwrap().edits.len() <= 2);
6691
    assert!(b.push("origin", false).unwrap()[0].ok);
6692
    assert!(a.pull("origin").unwrap().checked_out);
6693
    assert_eq!(fs::read(root.join("a/big.txt")).unwrap(), edited.as_bytes());
6694
    assert_eq!(
6695
        a.fsck().unwrap().errors(),
6696
        0,
6697
        "{:?}",
6698
        a.fsck().unwrap().problems
6699
    );
6700
6701
    // With zero retention gc keeps the text blobs of every kept change.
6702
    let mut a = Repo::open(&root.join("a")).unwrap();
6703
    a.config.set("core.op-retention", "0").unwrap();
6704
    a.save_config().unwrap();
6705
    let a = Repo::open(&root.join("a")).unwrap();
6706
    a.gc(true).unwrap();
6707
    let a = Repo::open(&root.join("a")).unwrap();
6708
    assert_eq!(a.store().get_change(&h1).unwrap().message, "large");
6709
    assert_eq!(
6710
        a.fsck().unwrap().errors(),
6711
        0,
6712
        "{:?}",
6713
        a.fsck().unwrap().problems
6714
    );
6715
    // And a clone of the packed repository reads them from its packs.
6716
    let c = Repo::clone(&root.join("a").to_string_lossy(), &root.join("c")).unwrap();
6717
    assert_eq!(fs::read(root.join("c/big.txt")).unwrap(), edited.as_bytes());
6718
    drop(c);
6719
}
6720
6721
#[test]
6722
fn operations_that_both_replace_a_working_copy_are_not_merged() {
6723
    hermetic();
6724
    let dir = tempfile::tempdir().unwrap();
6725
    let root = dir.path();
6726
    let repo = Repo::init(root).unwrap();
6727
    write(root, "a.txt", b"a\n");
6728
    let a = repo.commit("a", &[]).unwrap();
6729
    write(root, "b.txt", b"b\n");
6730
    repo.commit("b", &[]).unwrap();
6731
    let (x, op) = repo.head_op().unwrap();
6732
    let ws = *op.view.workspaces.keys().next().unwrap();
6733
    let mut one = op.view.clone();
6734
    one.workspaces.insert(ws, a);
6735
    let mut two = op.view.clone();
6736
    two.workspaces.insert(ws, ObjectRef([7; 32]));
6737
    let first = repo.record_op(&[x], "one", one).unwrap();
6738
    let e = repo.record_op(&[x], "two", two).unwrap_err();
6739
    assert!(
6740
        e.to_string()
6741
            .contains("changed this working copy at the same time"),
6742
        "{e}"
6743
    );
6744
    assert_eq!(
6745
        repo.head_op().unwrap().0,
6746
        first,
6747
        "the second is not recorded"
6748
    );
6749
}
6750
6751
/// Metalgear, 2026-09-29 (oxygen#36): a status run while a bookmark switch
6752
/// rewrote the working copy recorded the half-written files as edits, and
6753
/// its view replaced the switch's.
6754
#[test]
6755
fn a_snapshot_during_a_switch_never_records_the_switch_as_edits() {
6756
    hermetic();
6757
    let dir = tempfile::tempdir().unwrap();
6758
    let root = dir.path().to_path_buf();
6759
    let mut repo = Repo::init(&root).unwrap();
6760
    write(&root, "keep.txt", b"keep\n");
6761
    repo.commit("base", &[]).unwrap();
6762
    repo.bookmark_create("small", None).unwrap();
6763
    for i in 0..300 {
6764
        write(
6765
            &root,
6766
            &format!("many/f{i}.txt"),
6767
            format!("file {i}\n").as_bytes(),
6768
        );
6769
    }
6770
    repo.commit("many", &[]).unwrap();
6771
    let stop = std::sync::Arc::new(std::sync::atomic::AtomicBool::new(false));
6772
    let watcher = {
6773
        let (root, stop) = (root.clone(), stop.clone());
6774
        std::thread::spawn(move || {
6775
            let r = Repo::open(&root).unwrap();
6776
            let mut ran = 0;
6777
            while !stop.load(std::sync::atomic::Ordering::Relaxed) {
6778
                if r.snapshot_status("oxy status").is_ok() {
6779
                    ran += 1;
6780
                }
6781
            }
6782
            ran
6783
        })
6784
    };
6785
    for i in 0..20 {
6786
        let to = if i % 2 == 0 { "small" } else { "main" };
6787
        repo.bookmark_switch(to, false).unwrap();
6788
    }
6789
    stop.store(true, std::sync::atomic::Ordering::Relaxed);
6790
    assert!(watcher.join().unwrap() > 0, "the watcher snapshotted");
6791
    // Back on main, clean, with every file where main has it.
6792
    let repo = Repo::open(&root).unwrap();
6793
    let s = repo.snapshot_status("oxy status").unwrap();
6794
    assert!(s.statuses.is_empty(), "{:?}", statuses(&s));
6795
    assert!(s.wc.edits.is_empty() && s.wc.tree_ops.is_empty());
6796
    assert_eq!(s.wc.deps, repo.bookmark_heads().unwrap());
6797
    assert!(root.join("many/f299.txt").exists());
6798
}
6799
6800
/// Metalgear, 2026-09-29 (oxygen#38): a parent's `bookmark switch --carry`
6801
/// put a subrepo that was ahead of its pin back at the pin and moved the
6802
/// subrepo's own bookmark backwards.
6803
#[test]
6804
fn a_parent_switch_with_carry_leaves_a_subrepo_ahead_of_its_pin_alone() {
6805
    hermetic();
6806
    let dir = tempfile::tempdir().unwrap();
6807
    let root = dir.path();
6808
    Repo::init(&root.join("lib-origin")).unwrap();
6809
    let lib_url = root.join("lib-origin").to_string_lossy().to_string();
6810
    let lib = Repo::clone(&lib_url, &root.join("lib")).unwrap();
6811
    write(&root.join("lib"), "lib.txt", b"v1\n");
6812
    lib.commit("lib v1", &[]).unwrap();
6813
    assert!(lib.push("origin", false).unwrap()[0].ok);
6814
6815
    let app_dir = root.join("app");
6816
    let mut app = Repo::init(&app_dir).unwrap();
6817
    write(&app_dir, "main.txt", b"app\n");
6818
    app.submodule_add(&lib_url, "libs/lib", None).unwrap();
6819
    app.commit("app with lib", &[]).unwrap();
6820
    app.bookmark_create("feature", None).unwrap();
6821
6822
    // New work in the subrepo, not yet pinned by the parent.
6823
    let nested_dir = app_dir.join("libs/lib");
6824
    let nested = Repo::open(&nested_dir).unwrap();
6825
    write(&nested_dir, "new.txt", b"new\n");
6826
    let l2 = nested.commit("lib: new file", &[]).unwrap();
6827
    drop(nested);
6828
6829
    let (_, carried) = app.bookmark_switch_carry("feature").unwrap();
6830
    assert!(carried.contains(&"libs/lib".to_string()), "{carried:?}");
6831
    let nested = Repo::open(&nested_dir).unwrap();
6832
    assert!(
6833
        nested.bookmark_heads().unwrap().contains(&l2),
6834
        "its bookmark kept its work"
6835
    );
6836
    assert!(nested_dir.join("new.txt").exists(), "and its files");
6837
    let s = app.snapshot("status").unwrap();
6838
    assert_eq!(
6839
        statuses(&s),
6840
        vec![("libs/lib".to_string(), ChangeStatus::Modified)]
6841
    );
6842
}
6843
6844
/// oxygen#29 (metalgear, rstar-api): after a proposal landed on the hub,
6845
/// moving `main` to a change this clone had pushed on another bookmark,
6846
/// the first `pull` said "Already up to date" while `main` was behind.
6847
#[test]
6848
fn pull_takes_a_remote_move_to_changes_already_here() {
6849
    hermetic();
6850
    let dir = tempfile::tempdir().unwrap();
6851
    let root = dir.path();
6852
    let origin_path = root.join("origin");
6853
    let origin = Repo::init(&origin_path).unwrap();
6854
    let url = origin_path.to_string_lossy().to_string();
6855
    let mut b = Repo::clone(&url, &root.join("b")).unwrap();
6856
    write(&root.join("b"), "base.txt", b"base\n");
6857
    b.commit("base", &[]).unwrap();
6858
    assert!(b.push("origin", false).unwrap()[0].ok);
6859
    origin.refresh().unwrap();
6860
6861
    // A feature bookmark with one change, pushed.
6862
    b.bookmark_create("feat", None).unwrap();
6863
    b.bookmark_switch("feat", false).unwrap();
6864
    write(&root.join("b"), "x.txt", b"x\n");
6865
    let x = b.commit("x", &[]).unwrap();
6866
    assert!(b.push("origin", false).unwrap()[0].ok);
6867
    origin.refresh().unwrap();
6868
    b.bookmark_switch("main", false).unwrap();
6869
6870
    // The remote lands it: its main moves to the feature's state.
6871
    let feat = origin
6872
        .store()
6873
        .get_state(&origin.view().unwrap().bookmarks["feat"])
6874
        .unwrap()
6875
        .heads;
6876
    origin.bookmark_set("main", &feat).unwrap();
6877
6878
    let r = b.pull("origin").unwrap();
6879
    assert!(r.changed, "{r:?}");
6880
    assert!(r.heads.contains(&x) || b.load_state(&r.heads).unwrap().contains(&x));
6881
    let main = b
6882
        .bookmarks()
6883
        .unwrap()
6884
        .into_iter()
6885
        .find(|m| m.name == "main")
6886
        .unwrap();
6887
    assert_eq!(main.behind, Some(0), "{main:?}");
6888
}
6889
6890
/// oxygen#48: a remote's bookmarks are names here (`origin/NAME`); switching
6891
/// to one only the remote has makes a local bookmark from it; a pull moves
6892
/// every local bookmark the remote has too; a clone checks out the remote's
6893
/// default bookmark.
6894
#[test]
6895
fn remote_bookmarks_are_named_switched_to_pulled_and_cloned() {
6896
    hermetic();
6897
    let dir = tempfile::tempdir().unwrap();
6898
    let root = dir.path();
6899
    let origin_path = root.join("origin");
6900
    let mut origin = Repo::init(&origin_path).unwrap();
6901
    let url = origin_path.to_string_lossy().to_string();
6902
    let mut a = Repo::clone(&url, &root.join("a")).unwrap();
6903
    write(&root.join("a"), "base.txt", b"base\n");
6904
    a.commit("base", &[]).unwrap();
6905
    assert!(a.push("origin", false).unwrap()[0].ok);
6906
    a.bookmark_create("develop", None).unwrap();
6907
    a.bookmark_switch("develop", false).unwrap();
6908
    write(&root.join("a"), "base.txt", b"base\nd1\n");
6909
    let d1 = a.commit("d1", &[]).unwrap();
6910
    assert!(a.push("origin", false).unwrap()[0].ok);
6911
6912
    // A clone has main only; origin/develop is a name all the same.
6913
    let c_root = root.join("c");
6914
    let mut c = Repo::clone(&url, &c_root).unwrap();
6915
    assert_eq!(c.config.bookmark, "main");
6916
    assert!(!c.view().unwrap().bookmarks.contains_key("develop"));
6917
    assert_eq!(c.resolve_heads("origin/develop").unwrap(), vec![d1]);
6918
    assert_eq!(c.resolve_change("origin/develop").unwrap(), d1);
6919
    assert_eq!(c.remote_only_bookmarks().unwrap().len(), 1);
6920
6921
    // Switching makes the local bookmark from origin's.
6922
    c.bookmark_switch("develop", false).unwrap();
6923
    assert_eq!(c.config.bookmark, "develop");
6924
    assert_eq!(c.bookmark_heads().unwrap(), vec![d1]);
6925
    assert_eq!(fs::read(c_root.join("base.txt")).unwrap(), b"base\nd1\n");
6926
    assert!(c.remote_only_bookmarks().unwrap().is_empty());
6927
    assert!(c.bookmark_switch("nowhere", false).is_err());
6928
6929
    // Both bookmarks move on the remote; one pull takes both.
6930
    write(&root.join("a"), "base.txt", b"base\nd1\nd2\n");
6931
    let d2 = a.commit("d2", &[]).unwrap();
6932
    assert!(a.push("origin", false).unwrap()[0].ok);
6933
    a.bookmark_switch("main", false).unwrap();
6934
    write(&root.join("a"), "m.txt", b"m\n");
6935
    let m = a.commit("m", &[]).unwrap();
6936
    assert!(a.push("origin", false).unwrap()[0].ok);
6937
    let r = c.pull("origin").unwrap();
6938
    assert!(r.changed && r.checked_out, "{r:?}");
6939
    assert_eq!(r.heads, vec![d2]);
6940
    assert_eq!(r.others, vec!["main".to_string()]);
6941
    assert!(c.resolve_heads("main").unwrap().contains(&m));
6942
    assert_eq!(
6943
        fs::read(c_root.join("base.txt")).unwrap(),
6944
        b"base\nd1\nd2\n"
6945
    );
6946
    let again = c.pull("origin").unwrap();
6947
    assert!(!again.changed && again.others.is_empty(), "{again:?}");
6948
6949
    // A clone checks out the remote's default bookmark.
6950
    origin.config.set("workspace.bookmark", "develop").unwrap();
6951
    origin.save_config().unwrap();
6952
    let e = Repo::clone(&url, &root.join("e")).unwrap();
6953
    assert_eq!(e.config.bookmark, "develop");
6954
    assert_eq!(e.bookmark_heads().unwrap(), vec![d2]);
6955
    let reopened = Repo::open(&root.join("e")).unwrap();
6956
    assert_eq!(reopened.config.bookmark, "develop");
6957
    // REMOTE/NAME names the remote's bookmark to switch to.
6958
    let mut e = reopened;
6959
    e.bookmark_switch("origin/main", false).unwrap();
6960
    assert_eq!(e.config.bookmark, "main");
6961
    assert!(e.bookmark_heads().unwrap().contains(&m));
6962
}
6963
6964
/// oxygen#51, #52: --at-op reads an earlier view and refuses changes;
6965
/// op restore goes back to an operation, files included, and undo takes
6966
/// the restore back whole; op revert undoes one operation alone; each
6967
/// operation's changes are described from the views.
6968
#[test]
6969
fn operations_can_be_read_restored_and_reverted() {
6970
    hermetic();
6971
    let dir = tempfile::tempdir().unwrap();
6972
    let root = dir.path();
6973
    let repo = Repo::init(root).unwrap();
6974
    write(root, "a.txt", b"a\n");
6975
    let first = repo.commit("first", &[]).unwrap();
6976
    write(root, "a.txt", b"a\nb\n");
6977
    let second = repo.commit("second", &[]).unwrap();
6978
    let at_second = repo.head_op().unwrap().0.to_hex();
6979
    repo.bookmark_create("keep", None).unwrap();
6980
    let created = repo.head_op().unwrap().0.to_hex();
6981
    write(root, "n.txt", b"n\n");
6982
    let third = repo.commit("third", &[]).unwrap();
6983
6984
    // What each operation changed.
6985
    let ops = repo.op_log().unwrap();
6986
    let changes = repo.view_changes(&ops[1].1.view, &ops[0].1.view).unwrap();
6987
    assert!(
6988
        changes
6989
            .iter()
6990
            .any(|c| matches!(c, ViewChange::BookmarkMoved { name, .. } if name == "main")),
6991
        "{changes:?}"
6992
    );
6993
    assert!(changes
6994
        .iter()
6995
        .any(|c| matches!(c, ViewChange::WorkingCopy { .. })));
6996
6997
    // Reading at an earlier operation.
6998
    let old = Repo::open(root).unwrap().at_op(&at_second[..10]).unwrap();
6999
    assert_eq!(old.bookmark_heads().unwrap(), vec![second]);
7000
    assert!(!old.view().unwrap().bookmarks.contains_key("keep"));
7001
    write(root, "z.txt", b"z\n");
7002
    assert!(old.commit("refused", &[]).is_err(), "--at-op is read-only");
7003
    fs::remove_file(root.join("z.txt")).unwrap();
7004
    assert!(repo.resolve_op("zz").is_err());
7005
    assert_eq!(repo.resolve_op("@").unwrap().0, repo.head_op().unwrap().0);
7006
7007
    // Restore goes back, files and all; undo takes it back whole.
7008
    repo.op_restore(&at_second, false).unwrap();
7009
    assert_eq!(repo.bookmark_heads().unwrap(), vec![second]);
7010
    assert!(!root.join("n.txt").exists());
7011
    repo.undo().unwrap();
7012
    let mut heads = repo.bookmark_heads().unwrap();
7013
    heads.sort();
7014
    let mut want = vec![second, third];
7015
    want.sort();
7016
    assert_eq!(heads, want);
7017
    assert!(
7018
        root.join("n.txt").exists(),
7019
        "the files came back with the undo"
7020
    );
7021
7022
    // Revert the bookmark's creation alone: the commit after it stays.
7023
    let r = repo.op_revert(&created).unwrap();
7024
    assert_eq!(r.reverted, vec!["keep".to_string()]);
7025
    assert!(!repo.view().unwrap().bookmarks.contains_key("keep"));
7026
    assert!(repo
7027
        .load_state(&repo.bookmark_heads().unwrap())
7028
        .unwrap()
7029
        .contains(&third));
7030
    assert!(repo.op_revert(&created).is_err(), "nothing left to revert");
7031
    let _ = first;
7032
}
7033
7034
/// oxygen#41: with uncommitted work, a status after a snapshot is answered
7035
/// from the status cache while every file is as the snapshot left it, and
7036
/// from a snapshot again as soon as one is not.
7037
#[test]
7038
fn status_with_uncommitted_work_comes_from_the_cache_until_a_file_changes() {
7039
    hermetic();
7040
    let dir = tempfile::tempdir().unwrap();
7041
    let root = dir.path();
7042
    let repo = Repo::init(root).unwrap();
7043
    write(root, "a.txt", b"a\n");
7044
    write(root, "b.txt", b"b\n");
7045
    repo.commit("base", &[]).unwrap();
7046
    assert_eq!(repo.status_by_manifest().unwrap(), Some(vec![]), "clean");
7047
7048
    write(root, "a.txt", b"a\nmore\n");
7049
    assert_eq!(
7050
        repo.status_by_manifest().unwrap(),
7051
        None,
7052
        "no snapshot of the edit yet"
7053
    );
7054
    let snap = repo.snapshot_status("oxy status").unwrap();
7055
    assert_eq!(snap.statuses.len(), 1);
7056
    let cached = repo
7057
        .status_by_manifest()
7058
        .unwrap()
7059
        .expect("answered from the cache");
7060
    assert_eq!(cached.len(), 1);
7061
    assert_eq!(
7062
        (cached[0].path.as_str(), cached[0].status),
7063
        ("a.txt", ChangeStatus::Modified)
7064
    );
7065
7066
    // Any further change sends status back to a snapshot.
7067
    write(root, "a.txt", b"a\nmore\nand more\n");
7068
    assert_eq!(repo.status_by_manifest().unwrap(), None, "edited again");
7069
    repo.snapshot_status("oxy status").unwrap();
7070
    assert!(repo.status_by_manifest().unwrap().is_some());
7071
    write(root, "new.txt", b"n\n");
7072
    assert_eq!(repo.status_by_manifest().unwrap(), None, "a file added");
7073
    fs::remove_file(root.join("new.txt")).unwrap();
7074
    assert!(
7075
        repo.status_by_manifest().unwrap().is_some(),
7076
        "back as it was"
7077
    );
7078
    fs::remove_file(root.join("b.txt")).unwrap();
7079
    assert_eq!(repo.status_by_manifest().unwrap(), None, "a file removed");
7080
    write(root, "b.txt", b"b\n");
7081
7082
    // A commit leaves nothing uncommitted: clean again, no cache needed.
7083
    repo.snapshot_status("oxy status").unwrap();
7084
    repo.commit("more", &[]).unwrap();
7085
    assert_eq!(repo.status_by_manifest().unwrap(), Some(vec![]));
7086
}
7087
7088
/// oxygen#41: while the status cache holds, the working copy's diff is
7089
/// rendered from the stored working-copy change, and says exactly what a
7090
/// snapshot's diff says.
7091
#[test]
7092
fn the_working_copy_diff_from_the_cache_matches_a_snapshot() {
7093
    hermetic();
7094
    let dir = tempfile::tempdir().unwrap();
7095
    let root = dir.path();
7096
    let repo = Repo::init(root).unwrap();
7097
    write(root, "a.txt", b"one\ntwo\nthree\n");
7098
    write(root, "gone.txt", b"bye\n");
7099
    repo.commit("base", &[]).unwrap();
7100
    write(root, "a.txt", b"one\n2\nthree\nfour\n");
7101
    write(root, "new.txt", b"hello\n");
7102
    fs::remove_file(root.join("gone.txt")).unwrap();
7103
    let snap = repo.snapshot_status("oxy status").unwrap();
7104
    let slow = render_change(&snap.wc, &snap.base, &snap.base_snapshot);
7105
    assert!(
7106
        repo.status_by_manifest().unwrap().is_some(),
7107
        "the cache holds"
7108
    );
7109
    let (wc, base, snapshot) = repo.working_copy_with_base().unwrap();
7110
    assert_eq!(render_change(&wc, &base, &snapshot), slow);
7111
    assert_eq!(repo.diff_files(None).unwrap().len(), 3);
7112
}
7113
7114
/// oxygen#41: a manifest written from a walk keeps every directory's time;
7115
/// while none has moved, the check stats the tracked files without listing
7116
/// the tree, and a file added or removed anywhere moves its directory's
7117
/// time, so the tree is listed again.
7118
#[test]
7119
fn the_manifest_check_skips_listing_while_no_directory_changed() {
7120
    hermetic();
7121
    let dir = tempfile::tempdir().unwrap();
7122
    let root = dir.path();
7123
    let repo = Repo::init(root).unwrap();
7124
    write(root, "a.txt", b"a\n");
7125
    write(root, "sub/deep/b.txt", b"b\n");
7126
    repo.commit("base", &[]).unwrap();
7127
    // Out of the racy window: every file and directory a minute old.
7128
    let old = std::time::SystemTime::now() - std::time::Duration::from_secs(60);
7129
    for p in ["a.txt", "sub/deep/b.txt", "sub/deep", "sub", ""] {
7130
        fs::File::open(root.join(p))
7131
            .unwrap()
7132
            .set_modified(old)
7133
            .unwrap();
7134
    }
7135
    repo.snapshot_status("oxy status").unwrap();
7136
    repo.write_manifest(false, false).unwrap();
7137
    let m = repo.read_manifest().unwrap().unwrap().2;
7138
    assert!(m.dirs.iter().any(|(d, _)| d == "sub/deep"), "{:?}", m.dirs);
7139
    assert_eq!(
7140
        repo.disk_differs_by_dirs(&m),
7141
        Some(false),
7142
        "no listing needed"
7143
    );
7144
    assert_eq!(repo.status_by_manifest().unwrap(), Some(vec![]));
7145
7146
    // A same-size edit with a new time: found by its stat.
7147
    write(root, "sub/deep/b.txt", b"c\n");
7148
    assert_eq!(repo.disk_differs_by_dirs(&m), Some(true));
7149
    write(root, "sub/deep/b.txt", b"b\n");
7150
    fs::File::open(root.join("sub/deep/b.txt"))
7151
        .unwrap()
7152
        .set_modified(old)
7153
        .unwrap();
7154
    assert_eq!(repo.disk_differs_by_dirs(&m), Some(false));
7155
7156
    // A new file moves its directory's time: the tree must be listed.
7157
    write(root, "sub/deep/new.txt", b"n\n");
7158
    assert_eq!(repo.disk_differs_by_dirs(&m), None);
7159
    assert_eq!(repo.status_by_manifest().unwrap(), None);
7160
    fs::remove_file(root.join("sub/deep/new.txt")).unwrap();
7161
    // A removed one too.
7162
    fs::remove_file(root.join("a.txt")).unwrap();
7163
    assert_eq!(repo.disk_differs_by_dirs(&m), None);
7164
}
7165
7166
/// oxygen#41: a commit right after a status takes the snapshot the status
7167
/// left (the status cache holds) rather than walking again, and commits
7168
/// exactly what a snapshot would have.
7169
#[test]
7170
fn a_commit_after_a_status_uses_the_cached_snapshot() {
7171
    hermetic();
7172
    let dir = tempfile::tempdir().unwrap();
7173
    let root = dir.path();
7174
    let repo = Repo::init(root).unwrap();
7175
    write(root, "a.txt", b"a\nb\n");
7176
    write(root, ".oxyattributes", b"*.bin binary\n");
7177
    repo.commit("base", &[]).unwrap();
7178
    write(root, "a.txt", b"a\nB\n");
7179
    write(root, "new.txt", b"new\n");
7180
    let snap = repo.snapshot_status("oxy status").unwrap();
7181
    let cached = repo
7182
        .snapshot_from_cache()
7183
        .unwrap()
7184
        .expect("the cache holds");
7185
    assert_eq!(cached.wc_hash, snap.wc_hash);
7186
    assert_eq!(cached.statuses, snap.statuses);
7187
    assert!(
7188
        !cached.attributes.is_empty(),
7189
        "the .oxyattributes file was read"
7190
    );
7191
    let h = repo.commit("edit", &[]).unwrap();
7192
    let c = repo.store().get_change(&h).unwrap();
7193
    assert_eq!(
7194
        c.tree_ops.len() + c.edits.len(),
7195
        snap.wc.tree_ops.len() + snap.wc.edits.len()
7196
    );
7197
    assert_eq!(
7198
        repo.status_by_manifest().unwrap(),
7199
        Some(vec![]),
7200
        "clean after the commit"
7201
    );
7202
    assert_eq!(fs::read(root.join("a.txt")).unwrap(), b"a\nB\n");
7203
}
7204
7205
/// oxygen#41: a clean check that verified racy entries restamps the
7206
/// manifest, so later checks can trust them, and a same-size rewrite
7207
/// straight afterwards is still found: entries within two seconds of the
7208
/// new time stay racy.
7209
#[test]
7210
fn a_verified_clean_check_restamps_the_manifest_safely() {
7211
    hermetic();
7212
    let dir = tempfile::tempdir().unwrap();
7213
    let root = dir.path();
7214
    let repo = Repo::init(root).unwrap();
7215
    write(root, "a.txt", b"one\n");
7216
    repo.commit("one", &[]).unwrap();
7217
    let before = repo.read_manifest().unwrap().unwrap().2.written_ns;
7218
    assert!(repo.clean_by_manifest().unwrap());
7219
    let after = repo.read_manifest().unwrap().unwrap().2.written_ns;
7220
    assert!(after > before, "restamped");
7221
    write(root, "a.txt", b"two\n");
7222
    assert!(
7223
        !repo.clean_by_manifest().unwrap(),
7224
        "a same-size rewrite is still seen"
7225
    );
7226
}
7227
7228
/// oxygen#35: a history-only state keeps no inserted text. It reads a
7229
/// stored insert's text blob only when it builds that file's graph, and
7230
/// builds the same graph a full load does.
7231
#[test]
7232
fn history_only_states_read_text_only_for_the_graphs_they_build() {
7233
    hermetic();
7234
    let dir = tempfile::tempdir().unwrap();
7235
    let root = dir.path();
7236
    let repo = Repo::init(root).unwrap();
7237
    let big: String = (0..3000).map(|i| format!("big line {i}\n")).collect();
7238
    let other: String = (0..3000).map(|i| format!("other line {i}\n")).collect();
7239
    write(root, "big.txt", big.as_bytes());
7240
    write(root, "other.txt", other.as_bytes());
7241
    let h = repo.commit("two large files", &[]).unwrap();
7242
    write(root, "big.txt", format!("{big}one more\n").as_bytes());
7243
    let h2 = repo.commit("append", &[]).unwrap();
7244
7245
    let full = repo.load_state_full(&[h2]).unwrap().materialize();
7246
    let text = |snap: &crate::state::Snapshot, p: &str| match &snap.files[p].content {
7247
        FileContent::Text { bytes, .. } => bytes.clone(),
7248
        other => panic!("{other:?}"),
7249
    };
7250
    // Built on demand, every graph renders as the full load's.
7251
    let mut hist = repo.load_state_history(&[h2]).unwrap();
7252
    let big_node = full.files["big.txt"].node;
7253
    assert!(hist.graph_key(&big_node).is_some(), "not built yet");
7254
    repo.load_all_graphs(&mut hist).unwrap();
7255
    let rendered = hist.materialize();
7256
    for p in ["big.txt", "other.txt"] {
7257
        assert_eq!(text(&rendered, p), text(&full, p), "{p}");
7258
    }
7259
7260
    // Without other.txt's text blob, history still loads and big.txt still
7261
    // builds: nothing read the other text.
7262
    let (_, texts) = repo.store().get_change_lazy(&h).unwrap();
7263
    assert_eq!(texts.len(), 2);
7264
    let content = |r: &ObjectRef| -> Vec<u8> {
7265
        let blob = crate::objects::Blob::decode(&repo.store().get(r).unwrap().1).unwrap();
7266
        blob.chunks
7267
            .iter()
7268
            .flat_map(|c| repo.store().get(c).unwrap().1)
7269
            .collect()
7270
    };
7271
    let other_text = texts
7272
        .iter()
7273
        .filter_map(|t| match t {
7274
            crate::objects::TextRef::Blob(r, _, _) => Some(*r),
7275
            _ => None,
7276
        })
7277
        .find(|r| content(r).windows(12).any(|w| w == b"other line 1"))
7278
        .unwrap();
7279
    repo.store().remove_loose_for_test(&other_text).unwrap();
7280
    let mut hist = repo.load_state_history(&[h2]).unwrap();
7281
    repo.load_graphs_of(&mut hist, &[big_node]).unwrap();
7282
    assert!(repo
7283
        .load_graphs_of(&mut hist, &[full.files["other.txt"].node])
7284
        .is_err());
7285
}
7286
7287
/// oxygen#35: the first status after a commit read and rendered every
7288
/// file (79 s and more than 14 GB on the Linux tree), because the
7289
/// manifest had no graph keys for files the commit added.
7290
#[test]
7291
fn a_commit_leaves_a_manifest_the_next_status_trusts() {
7292
    use std::os::unix::fs::PermissionsExt;
7293
    hermetic();
7294
    let dir = tempfile::tempdir().unwrap();
7295
    let root = dir.path();
7296
    let repo = Repo::init(root).unwrap();
7297
    let files = ["a.txt", "b.txt", "d/c.txt"];
7298
    for p in files {
7299
        write(root, p, format!("{p}\n").as_bytes());
7300
        let old = std::time::SystemTime::now() - std::time::Duration::from_secs(30);
7301
        fs::File::options()
7302
            .write(true)
7303
            .open(root.join(p))
7304
            .unwrap()
7305
            .set_modified(old)
7306
            .unwrap();
7307
    }
7308
    repo.commit("added", &[]).unwrap();
7309
    let (_, _, m) = repo.read_manifest().unwrap().unwrap();
7310
    assert!(
7311
        m.entries.values().all(|e| e.graph.is_some()),
7312
        "keys recorded at commit"
7313
    );
7314
    // Unreadable files prove the next status reads none of them.
7315
    for p in files {
7316
        fs::set_permissions(root.join(p), fs::Permissions::from_mode(0o000)).unwrap();
7317
    }
7318
    let snap = repo.snapshot_status("status").unwrap();
7319
    for p in files {
7320
        fs::set_permissions(root.join(p), fs::Permissions::from_mode(0o644)).unwrap();
7321
    }
7322
    assert!(!snap.changed && snap.statuses.is_empty());
7323
    assert_eq!(snap.base_snapshot.unrendered.len(), files.len());
7324
}
7325
7326
/// oxygen#35: a checkout reads, renders and writes only the files whose
7327
/// graphs differ, and renders the rest a batch at a time.
7328
#[test]
7329
fn checkout_touches_only_what_differs_and_renders_in_batches() {
7330
    use std::os::unix::fs::PermissionsExt;
7331
    hermetic();
7332
    let dir = tempfile::tempdir().unwrap();
7333
    let root = dir.path();
7334
    let origin = root.join("origin");
7335
    let mut repo = Repo::init(&origin).unwrap();
7336
    // More files than one batch holds.
7337
    let n = 2100;
7338
    let old = std::time::SystemTime::now() - std::time::Duration::from_secs(30);
7339
    for i in 0..n {
7340
        let p = format!("f/{i:04}.txt");
7341
        write(&origin, &p, format!("file {i}\n").as_bytes());
7342
        fs::File::options()
7343
            .write(true)
7344
            .open(origin.join(&p))
7345
            .unwrap()
7346
            .set_modified(old)
7347
            .unwrap();
7348
    }
7349
    repo.commit("many", &[]).unwrap();
7350
    repo.bookmark_create("feature", None).unwrap();
7351
    repo.bookmark_switch("feature", false).unwrap();
7352
    write(&origin, "f/0007.txt", b"changed\n");
7353
    repo.commit("one change", &[]).unwrap();
7354
7355
    // Switching back to main must not read the unchanged files.
7356
    for i in 0..n {
7357
        if i != 7 {
7358
            let p = origin.join(format!("f/{i:04}.txt"));
7359
            fs::set_permissions(&p, fs::Permissions::from_mode(0o000)).unwrap();
7360
        }
7361
    }
7362
    let r = repo.bookmark_switch("main", false).unwrap();
7363
    for i in 0..n {
7364
        let p = origin.join(format!("f/{i:04}.txt"));
7365
        fs::set_permissions(&p, fs::Permissions::from_mode(0o644)).unwrap();
7366
    }
7367
    assert_eq!((r.written, r.removed), (1, 0), "{r:?}");
7368
    assert_eq!(fs::read(origin.join("f/0007.txt")).unwrap(), b"file 7\n");
7369
    assert!(repo.snapshot_status("status").unwrap().statuses.is_empty());
7370
7371
    // A clone renders every file, across batches.
7372
    let c = root.join("clone");
7373
    Repo::clone(&origin.to_string_lossy(), &c).unwrap();
7374
    for i in [0, 2047, 2048, n - 1] {
7375
        assert_eq!(
7376
            fs::read(c.join(format!("f/{i:04}.txt"))).unwrap(),
7377
            format!("file {i}\n").as_bytes()
7378
        );
7379
    }
7380
    let cloned = Repo::open(&c).unwrap();
7381
    assert!(cloned
7382
        .snapshot_status("status")
7383
        .unwrap()
7384
        .statuses
7385
        .is_empty());
7386
}
7387
7388
/// A file written just before the manifest (inside the racy window) is
7389
/// checked by its hash: trusted when equal, caught when edited in place
7390
/// with the same size and time.
7391
#[test]
7392
fn a_racy_manifest_entry_is_checked_by_hash() {
7393
    hermetic();
7394
    let dir = tempfile::tempdir().unwrap();
7395
    let root = dir.path();
7396
    let repo = Repo::init(root).unwrap();
7397
    write(root, "a.txt", b"one\n");
7398
    repo.commit("fresh", &[]).unwrap();
7399
    assert!(repo.clean_by_manifest().unwrap(), "fresh but equal");
7400
    let t = fs::metadata(root.join("a.txt"))
7401
        .unwrap()
7402
        .modified()
7403
        .unwrap();
7404
    write(root, "a.txt", b"two\n");
7405
    fs::File::options()
7406
        .write(true)
7407
        .open(root.join("a.txt"))
7408
        .unwrap()
7409
        .set_modified(t)
7410
        .unwrap();
7411
    assert!(
7412
        !repo.clean_by_manifest().unwrap(),
7413
        "same size and time, other bytes"
7414
    );
7415
    assert_eq!(
7416
        statuses(&repo.snapshot_status("status").unwrap()),
7417
        vec![("a.txt".to_string(), ChangeStatus::Modified)]
7418
    );
7419
}
7420
7421
/// A fetch on one machine moves changes as stored, text blobs among the
7422
/// objects; a change whose text blob did not come is refused, not stored.
7423
#[test]
7424
fn a_raw_bundle_without_a_changes_text_is_refused() {
7425
    hermetic();
7426
    let dir = tempfile::tempdir().unwrap();
7427
    let root = dir.path();
7428
    let a = Repo::init(&root.join("a")).unwrap();
7429
    let big: String = (0..3000).map(|i| format!("line {i}\n")).collect();
7430
    write(&root.join("a"), "big.txt", big.as_bytes());
7431
    let h = a.commit("big", &[]).unwrap();
7432
    let bundle = a.bundle_raw_for(&[h], None).unwrap();
7433
    assert_eq!(bundle.raw_changes.len(), 1);
7434
    assert!(bundle.changes.is_empty());
7435
    let b = Repo::init(&root.join("b")).unwrap();
7436
    let mut without = bundle.clone();
7437
    without.objects.retain(|(ty, _)| *ty != ObjectType::Blob);
7438
    let e = b.import_bundle(&without, false).unwrap_err();
7439
    assert!(e.to_string().contains("came without its text blob"), "{e}");
7440
    assert!(!b.store().has(&h));
7441
    assert_eq!(b.import_bundle(&bundle, false).unwrap(), vec![h]);
7442
    assert_eq!(b.store().get_change(&h).unwrap().message, "big");
7443
}
7444
7445
/// oxygen#30 (vscode): a directory deleted in one line of history and made
7446
/// again was a second node for one Git path, so a file moved into it on
7447
/// another line, where the first node still stood, ended up in two places.
7448
/// An import now brings the directory back rather than make a new one.
7449
#[test]
7450
fn git_import_brings_a_directory_back_rather_than_making_a_second() {
7451
    hermetic();
7452
    if std::process::Command::new("git")
7453
        .arg("--version")
7454
        .output()
7455
        .is_err()
7456
    {
7457
        eprintln!("git not installed; skipping");
7458
        return;
7459
    }
7460
    let dir = tempfile::tempdir().unwrap();
7461
    let root = dir.path();
7462
    let g = root.join("src.git");
7463
    fs::create_dir_all(&g).unwrap();
7464
    let git = |args: &[&str]| -> String {
7465
        let out = std::process::Command::new("git")
7466
            .arg("-C")
7467
            .arg(&g)
7468
            .args([
7469
                "-c",
7470
                "user.name=Grace",
7471
                "-c",
7472
                "[email protected]",
7473
                "-c",
7474
                "commit.gpgsign=false",
7475
            ])
7476
            .args(args)
7477
            .output()
7478
            .unwrap();
7479
        assert!(
7480
            out.status.success(),
7481
            "git {args:?}: {}",
7482
            String::from_utf8_lossy(&out.stderr)
7483
        );
7484
        String::from_utf8_lossy(&out.stdout).trim().to_string()
7485
    };
7486
    git(&["init", "-q", "-b", "main"]);
7487
    write(&g, "d/a.txt", b"a\n");
7488
    write(&g, "c/x.txt", b"x\n");
7489
    git(&["add", "."]);
7490
    git(&["commit", "-qm", "base"]);
7491
    // One line: move x into d while d still stands.
7492
    git(&["checkout", "-qb", "side"]);
7493
    git(&["mv", "c/x.txt", "d/x.txt"]);
7494
    git(&["commit", "-qm", "x into d"]);
7495
    // The other: d goes, comes back, and x moves into it too.
7496
    git(&["checkout", "-q", "main"]);
7497
    git(&["rm", "-q", "d/a.txt"]);
7498
    git(&["commit", "-qm", "d goes"]);
7499
    write(&g, "d/b.txt", b"b\n");
7500
    git(&["add", "."]);
7501
    git(&["commit", "-qm", "d comes back"]);
7502
    git(&["mv", "c/x.txt", "d/x.txt"]);
7503
    git(&["commit", "-qm", "x into d again"]);
7504
    git(&["merge", "-q", "--no-edit", "side"]);
7505
7506
    let repo = Repo::init(&root.join("o")).unwrap();
7507
    repo.import_git(&g, "main").unwrap();
7508
    let v = repo.verify_git_import(&g, "main").unwrap();
7509
    assert!(v.mismatches.is_empty(), "{:?}", v.mismatches);
7510
    let st = repo
7511
        .load_state_history(&repo.bookmark_heads().unwrap())
7512
        .unwrap();
7513
    let view = st.tree().view();
7514
    assert!(view.conflicts.is_empty(), "{:?}", view.conflicts);
7515
    // The directory is the one the first commit made.
7516
    // Commits made in one second tie on time: find the first by its message.
7517
    let first = repo
7518
        .log()
7519
        .unwrap()
7520
        .into_iter()
7521
        .find(|e| e.change.message.starts_with("base"))
7522
        .unwrap();
7523
    let base = repo
7524
        .load_state_history(&[first.hash])
7525
        .unwrap()
7526
        .tree()
7527
        .view();
7528
    assert_eq!(view.entries["d"].node, base.entries["d"].node);
7529
}
7530
7531
/// oxygen#30, the rest: a placement left under a directory another line
7532
/// removed is out of sight, so no diff reaches it; the merge that settles
7533
/// where the file is retires it.
7534
#[test]
7535
fn git_import_merge_retires_a_placement_under_a_removed_directory() {
7536
    hermetic();
7537
    if std::process::Command::new("git")
7538
        .arg("--version")
7539
        .output()
7540
        .is_err()
7541
    {
7542
        eprintln!("git not installed; skipping");
7543
        return;
7544
    }
7545
    let dir = tempfile::tempdir().unwrap();
7546
    let root = dir.path();
7547
    let g = root.join("src.git");
7548
    fs::create_dir_all(&g).unwrap();
7549
    let run = |args: &[&str]| {
7550
        std::process::Command::new("git")
7551
            .arg("-C")
7552
            .arg(&g)
7553
            .args([
7554
                "-c",
7555
                "user.name=Grace",
7556
                "-c",
7557
                "[email protected]",
7558
                "-c",
7559
                "commit.gpgsign=false",
7560
            ])
7561
            .args(args)
7562
            .output()
7563
            .unwrap()
7564
    };
7565
    let git = |args: &[&str]| {
7566
        let out = run(args);
7567
        assert!(
7568
            out.status.success(),
7569
            "git {args:?}: {}",
7570
            String::from_utf8_lossy(&out.stderr)
7571
        );
7572
    };
7573
    git(&["init", "-q", "-b", "main"]);
7574
    write(&g, "c/x.txt", b"x\n");
7575
    write(&g, "keep.txt", b"k\n");
7576
    git(&["add", "."]);
7577
    git(&["commit", "-qm", "base"]);
7578
    // One line renames the file within c; the other moves it out of c,
7579
    // which goes.
7580
    git(&["checkout", "-qb", "side"]);
7581
    git(&["mv", "c/x.txt", "c/y.txt"]);
7582
    git(&["commit", "-qm", "rename within c"]);
7583
    git(&["checkout", "-q", "main"]);
7584
    fs::create_dir_all(g.join("n")).unwrap();
7585
    git(&["mv", "c/x.txt", "n/x.txt"]);
7586
    git(&["commit", "-qm", "move out of c"]);
7587
    // Git cannot merge the two renames; the merge keeps n/x.txt.
7588
    let _ = run(&["merge", "-q", "side"]);
7589
    let _ = run(&[
7590
        "rm",
7591
        "-q",
7592
        "--cached",
7593
        "--ignore-unmatch",
7594
        "c/y.txt",
7595
        "c/x.txt",
7596
    ]);
7597
    let _ = std::fs::remove_dir_all(g.join("c"));
7598
    write(&g, "n/x.txt", b"x\n");
7599
    git(&["add", "-A"]);
7600
    git(&["commit", "-qm", "merge: keep n/x.txt"]);
7601
7602
    let repo = Repo::init(&root.join("o")).unwrap();
7603
    repo.import_git(&g, "main").unwrap();
7604
    let v = repo.verify_git_import(&g, "main").unwrap();
7605
    assert!(v.mismatches.is_empty(), "{:?}", v.mismatches);
7606
    let st = repo
7607
        .load_state_history(&repo.bookmark_heads().unwrap())
7608
        .unwrap();
7609
    let view = st.tree().view();
7610
    assert!(view.conflicts.is_empty(), "{:?}", view.conflicts);
7611
    assert!(view.entries.contains_key("n/x.txt"));
7612
}
7613
7614
/// oxygen#30, orphans: a file added on one line into a directory the other
7615
/// line removed is placed where the tree cannot show it; Git's merge keeps
7616
/// the file, and the import's merge leaves exactly one of it.
7617
#[test]
7618
fn git_import_merge_leaves_no_orphan_behind() {
7619
    hermetic();
7620
    if std::process::Command::new("git")
7621
        .arg("--version")
7622
        .output()
7623
        .is_err()
7624
    {
7625
        eprintln!("git not installed; skipping");
7626
        return;
7627
    }
7628
    let dir = tempfile::tempdir().unwrap();
7629
    let root = dir.path();
7630
    let g = root.join("src.git");
7631
    fs::create_dir_all(&g).unwrap();
7632
    let git = |args: &[&str]| {
7633
        let out = std::process::Command::new("git")
7634
            .arg("-C")
7635
            .arg(&g)
7636
            .args([
7637
                "-c",
7638
                "user.name=Grace",
7639
                "-c",
7640
                "[email protected]",
7641
                "-c",
7642
                "commit.gpgsign=false",
7643
            ])
7644
            .args(args)
7645
            .output()
7646
            .unwrap();
7647
        assert!(
7648
            out.status.success(),
7649
            "git {args:?}: {}",
7650
            String::from_utf8_lossy(&out.stderr)
7651
        );
7652
    };
7653
    git(&["init", "-q", "-b", "main"]);
7654
    write(&g, "d/f.txt", b"f\n");
7655
    write(&g, "keep.txt", b"k\n");
7656
    git(&["add", "."]);
7657
    git(&["commit", "-qm", "base"]);
7658
    git(&["checkout", "-qb", "side"]);
7659
    write(&g, "d/new.txt", b"new\n");
7660
    git(&["add", "."]);
7661
    git(&["commit", "-qm", "add into d"]);
7662
    git(&["checkout", "-q", "main"]);
7663
    git(&["rm", "-q", "d/f.txt"]);
7664
    git(&["commit", "-qm", "d goes"]);
7665
    git(&["merge", "-q", "--no-edit", "side"]);
7666
7667
    let repo = Repo::init(&root.join("o")).unwrap();
7668
    repo.import_git(&g, "main").unwrap();
7669
    let v = repo.verify_git_import(&g, "main").unwrap();
7670
    assert!(v.mismatches.is_empty(), "{:?}", v.mismatches);
7671
    let st = repo
7672
        .load_state_history(&repo.bookmark_heads().unwrap())
7673
        .unwrap();
7674
    let view = st.tree().view();
7675
    assert!(view.conflicts.is_empty(), "{:?}", view.conflicts);
7676
    assert!(view.entries.contains_key("d/new.txt"));
7677
}
7678
7679
/// fsck checks a change's text as the blobs it is stored in, without
7680
/// decoding it: a missing text blob is an error named for the change.
7681
#[test]
7682
fn fsck_names_a_missing_text_blob() {
7683
    hermetic();
7684
    let dir = tempfile::tempdir().unwrap();
7685
    let root = dir.path();
7686
    let repo = Repo::init(root).unwrap();
7687
    let big: String = (0..3000).map(|i| format!("line {i}\n")).collect();
7688
    write(root, "big.txt", big.as_bytes());
7689
    let h = repo.commit("big", &[]).unwrap();
7690
    assert_eq!(repo.fsck().unwrap().errors(), 0);
7691
    let (_, texts) = repo.store().get_change_lazy(&h).unwrap();
7692
    let Some(crate::objects::TextRef::Blob(b, _, _)) = texts.first().copied() else {
7693
        panic!("a stored text")
7694
    };
7695
    repo.store().remove_loose_for_test(&b).unwrap();
7696
    let rep = repo.fsck().unwrap();
7697
    assert!(rep.errors() > 0);
7698
    assert!(
7699
        rep.problems.iter().any(|p| p.what.contains(&h.short(12))),
7700
        "{:?}",
7701
        rep.problems
7702
    );
7703
}
7704
7705
/// oxygen#32: a subrepo on the same hub as one of the parent's remotes is
7706
/// reached with that remote's token and CA (a private subrepo then clones
7707
/// for anyone who can read the parent); another hub gets none of them.
7708
#[test]
7709
fn a_subrepo_on_the_parents_hub_borrows_its_credentials() {
7710
    hermetic();
7711
    let dir = tempfile::tempdir().unwrap();
7712
    let mut repo = Repo::init(dir.path()).unwrap();
7713
    repo.config
7714
        .set(
7715
            "remote.origin.url",
7716
            "https://Hub.example:7343/doomsdayone/metalgear",
7717
        )
7718
        .unwrap();
7719
    repo.config.set("remote.origin.token", "secret").unwrap();
7720
    repo.config
7721
        .set("remote.origin.ca", "/tmp/hub-ca.pem")
7722
        .unwrap();
7723
    let same = repo.credentials_for("https://hub.example:7343/doomsdayone/rstar-api");
7724
    assert_eq!(same.token.as_deref(), Some("secret"));
7725
    assert_eq!(same.ca.as_deref(), Some(Path::new("/tmp/hub-ca.pem")));
7726
    for other in [
7727
        "https://elsewhere.example:7343/doomsdayone/rstar-api",
7728
        "https://hub.example/doomsdayone/rstar-api",
7729
        "http://hub.example:7343/doomsdayone/rstar-api",
7730
    ] {
7731
        let o = repo.credentials_for(other);
7732
        assert_ne!(o.token.as_deref(), Some("secret"), "{other}");
7733
    }
7734
}
7735
7736
/// oxygen#47: a remote with no token of its own uses the user's credential
7737
/// store for its hub, and a nested checkout finds its parent's remote
7738
/// token there instead of keeping a copy.
7739
#[test]
7740
fn remotes_use_the_credential_store_and_the_enclosing_checkout() {
7741
    hermetic();
7742
    let home = tempfile::tempdir().unwrap();
7743
    let dir = tempfile::tempdir().unwrap();
7744
    let mut parent = Repo::init(dir.path()).unwrap().with_home(home.path());
7745
    parent
7746
        .config
7747
        .set("remote.origin.url", "https://hub.example/o/parent")
7748
        .unwrap();
7749
    parent.save_config().unwrap();
7750
    assert_eq!(parent.remote_options("origin").token, None);
7751
    crate::credentials::Credentials::at(home.path())
7752
        .save("https://hub.example", "stored", Some("andy"), None)
7753
        .unwrap();
7754
    assert_eq!(
7755
        parent.remote_options("origin").token.as_deref(),
7756
        Some("stored")
7757
    );
7758
7759
    let empty_home = tempfile::tempdir().unwrap();
7760
    let nested = dir.path().join("deps").join("child");
7761
    let mut child = Repo::init(&nested).unwrap().with_home(empty_home.path());
7762
    child
7763
        .config
7764
        .set("remote.origin.url", "https://hub.example/o/child")
7765
        .unwrap();
7766
    child.save_config().unwrap();
7767
    assert_eq!(child.remote_options("origin").token, None);
7768
    parent
7769
        .config
7770
        .set("remote.origin.token", "checkout")
7771
        .unwrap();
7772
    parent.save_config().unwrap();
7773
    assert_eq!(
7774
        child.remote_options("origin").token.as_deref(),
7775
        Some("checkout")
7776
    );
7777
    // Another hub's checkout token is not borrowed.
7778
    child
7779
        .config
7780
        .set("remote.origin.url", "https://other.example/o/child")
7781
        .unwrap();
7782
    assert_eq!(child.remote_options("origin").token, None);
7783
}
7784
7785
#[test]
7786
fn the_metadata_cache_survives_a_torn_tail() {
7787
    hermetic();
7788
    let dir = tempfile::tempdir().unwrap();
7789
    let root = dir.path();
7790
    let repo = Repo::init(root).unwrap();
7791
    write(root, "a.txt", b"1\n");
7792
    let h = repo.commit("first", &[]).unwrap();
7793
    let meta = repo.store().get_change_meta(&h).unwrap();
7794
    let cache = repo.store().dir().join("metas");
7795
    let len = fs::metadata(&cache).unwrap().len();
7796
    assert!(len > 0, "a change read is cached");
7797
    // A torn record at the end: the cache reads up to it and cuts it off.
7798
    fs::OpenOptions::new()
7799
        .append(true)
7800
        .open(&cache)
7801
        .unwrap()
7802
        .write_all(&[7; 20])
7803
        .unwrap();
7804
    let again = Repo::open(root).unwrap();
7805
    assert_eq!(again.store().get_change_meta(&h).unwrap(), meta);
7806
    assert_eq!(fs::metadata(&cache).unwrap().len(), len);
7807
}
7808
7809
#[test]
7810
fn a_manifest_that_does_not_check_reads_as_none() {
7811
    hermetic();
7812
    let dir = tempfile::tempdir().unwrap();
7813
    let root = dir.path();
7814
    let repo = Repo::init(root).unwrap();
7815
    write(root, "a.txt", b"1\n");
7816
    repo.commit("first", &[]).unwrap();
7817
    let path = repo.manifest_path();
7818
    let mut bytes = fs::read(&path).unwrap();
7819
    assert!(Repo::open(root).unwrap().read_manifest().unwrap().is_some());
7820
    let last = bytes.len() - 1;
7821
    bytes[last] ^= 1;
7822
    fs::write(&path, &bytes).unwrap();
7823
    assert!(Repo::open(root).unwrap().read_manifest().unwrap().is_none());
7824
    // The next status reads the files and writes it again.
7825
    let again = Repo::open(root).unwrap();
7826
    assert!(!again.snapshot("status").unwrap().changed);
7827
    assert!(again.read_manifest().unwrap().is_some());
7828
}
7829
7830
#[test]
7831
fn a_commit_leaves_a_manifest_that_proves_the_working_copy_clean() {
7832
    hermetic();
7833
    let dir = tempfile::tempdir().unwrap();
7834
    let root = dir.path();
7835
    let repo = Repo::init(root).unwrap();
7836
    write(root, "a.txt", b"1\n");
7837
    write(root, "b.txt", b"2\n");
7838
    // b.txt outside the racy window, so snapshots take it as unchanged.
7839
    let old = std::time::SystemTime::now() - std::time::Duration::from_secs(60);
7840
    fs::File::options()
7841
        .write(true)
7842
        .open(root.join("b.txt"))
7843
        .unwrap()
7844
        .set_modified(old)
7845
        .unwrap();
7846
    repo.commit("first", &[]).unwrap();
7847
    assert!(repo.clean_by_manifest().unwrap(), "after the first commit");
7848
    repo.snapshot_status("status").unwrap();
7849
    write(root, "a.txt", b"1\n2\n");
7850
    repo.commit("second", &[]).unwrap();
7851
    assert!(
7852
        repo.clean_by_manifest().unwrap(),
7853
        "after a commit of one file"
7854
    );
7855
    // Edited, seen by a status, edited again, then committed: the status
7856
    // left the first edit's stat, which the commit must not keep.
7857
    write(root, "a.txt", b"1\n2\n3\n");
7858
    repo.snapshot_status("status").unwrap();
7859
    write(root, "a.txt", b"1\n2\n3\n4\n5\n");
7860
    repo.commit("third", &[]).unwrap();
7861
    assert!(
7862
        repo.clean_by_manifest().unwrap(),
7863
        "after an edit a status saw"
7864
    );
7865
}
7866
7867
#[test]
7868
fn a_conflicted_rebase_can_be_resolved_in_the_working_copy() {
7869
    hermetic();
7870
    let dir = tempfile::tempdir().unwrap();
7871
    let root = dir.path();
7872
    let mut repo = Repo::init(root).unwrap().with_home(root.join("home"));
7873
    write(root, "a.txt", b"1\n2\n");
7874
    let a = repo.commit("A", &[]).unwrap();
7875
    repo.bookmark_create("develop", Some(&[a])).unwrap();
7876
    write(root, "a.txt", b"1\nX\n");
7877
    let c = repo.commit("C: 2 to X", &[]).unwrap();
7878
    repo.bookmark_switch("develop", false).unwrap();
7879
    write(root, "a.txt", b"1\nY\n");
7880
    let d = repo.commit("D: 2 to Y", &[]).unwrap();
7881
    repo.bookmark_switch("main", false).unwrap();
7882
7883
    let err = repo.rebase(&c, &[d]).unwrap_err();
7884
    assert!(matches!(err, RepoError::Conflicted(_)), "{err}");
7885
    let r = repo.rebase_into_working_copy(&c, &[d]).unwrap();
7886
    assert!(r.changed && r.checked_out);
7887
    let snap = repo.snapshot_status("status").unwrap();
7888
    assert!(
7889
        snap.base_snapshot.is_conflicted(),
7890
        "the conflict is in the working copy"
7891
    );
7892
    let text = fs::read_to_string(root.join("a.txt")).unwrap();
7893
    assert!(text.contains('X') && text.contains('Y'), "{text}");
7894
7895
    write(root, "a.txt", b"1\nXY\n");
7896
    repo.commit("Resolve", &[]).unwrap();
7897
    let st = repo.load_state(&repo.bookmark_heads().unwrap()).unwrap();
7898
    assert!(st.contains(&c) && st.contains(&d));
7899
    let files = st.materialize().files;
7900
    assert!(!files["a.txt"].is_conflicted());
7901
    assert!(
7902
        matches!(&files["a.txt"].content, FileContent::Text { bytes, .. } if bytes == b"1\nXY\n")
7903
    );
7904
7905
    // A change the current bookmark does not hold is refused.
7906
    repo.bookmark_switch("develop", false).unwrap();
7907
    write(root, "b.txt", b"b\n");
7908
    let e = repo.commit("E", &[]).unwrap();
7909
    repo.bookmark_switch("main", false).unwrap();
7910
    let err = repo.rebase_into_working_copy(&e, &[a]).unwrap_err();
7911
    assert!(
7912
        err.to_string().contains("not on the current bookmark"),
7913
        "{err}"
7914
    );
7915
}
7916
7917
#[test]
7918
fn an_ignore_rule_drops_an_added_file_but_not_a_tracked_one() {
7919
    hermetic();
7920
    let dir = tempfile::tempdir().unwrap();
7921
    let root = dir.path();
7922
    let repo = Repo::init(root).unwrap();
7923
    write(root, "a.txt", b"a\n");
7924
    write(root, "kept.log", b"tracked\n");
7925
    repo.commit("first", &[]).unwrap();
7926
    write(root, "build.log", b"made\n");
7927
    let snap = repo.snapshot_status("status").unwrap();
7928
    assert!(snap.statuses.iter().any(|s| s.path == "build.log"));
7929
    // A rule written afterwards leaves the added file out again, while the
7930
    // committed one stays tracked.
7931
    write(root, ".gitignore", b"*.log\n");
7932
    let snap = repo.snapshot_status("status").unwrap();
7933
    let paths: Vec<&str> = snap.statuses.iter().map(|s| s.path.as_str()).collect();
7934
    assert_eq!(paths, vec![".gitignore"], "{paths:?}");
7935
    write(root, "kept.log", b"tracked, edited\n");
7936
    let snap = repo.snapshot_status("status").unwrap();
7937
    assert!(snap.statuses.iter().any(|s| s.path == "kept.log"));
7938
}
7939
7940
#[test]
7941
fn shed_graphs_come_back_the_same() {
7942
    hermetic();
7943
    let dir = tempfile::tempdir().unwrap();
7944
    let root = dir.path();
7945
    let repo = Repo::init(root).unwrap();
7946
    write(root, "a.txt", b"1\n2\n3\n");
7947
    write(root, "b.txt", b"x\n");
7948
    repo.commit("first", &[]).unwrap();
7949
    write(root, "a.txt", b"1\ntwo\n3\n4\n");
7950
    repo.commit("second", &[]).unwrap();
7951
    let heads = repo.bookmark_heads().unwrap();
7952
    let mut st = repo.load_state_history(&heads).unwrap();
7953
    let view = st.tree().view();
7954
    let nodes: Vec<NodeId> = ["a.txt", "b.txt"]
7955
        .iter()
7956
        .map(|p| view.entries[*p].node)
7957
        .collect();
7958
    repo.load_graphs_of(&mut st, &nodes).unwrap();
7959
    let before: Vec<Vec<u8>> = nodes.iter().map(|n| st.render_file(n).0).collect();
7960
    assert_eq!(st.built_count(), 2);
7961
    let shed = st.shed_graphs(|b| repo.store_blob(b)).unwrap();
7962
    assert_eq!((shed, st.built_count()), (2, 0));
7963
    // A later change applies on top of the shed history.
7964
    write(root, "a.txt", b"1\ntwo\n3\n4\n5\n");
7965
    let h3 = repo.commit("third", &[]).unwrap();
7966
    let (skeleton, texts) = repo.store().get_change_lazy(&h3).unwrap();
7967
    st.add_known(h3, skeleton, texts);
7968
    repo.load_graphs_of(&mut st, &nodes).unwrap();
7969
    let after: Vec<Vec<u8>> = nodes.iter().map(|n| st.render_file(n).0).collect();
7970
    assert_eq!(after[1], before[1]);
7971
    assert_eq!(after[0], b"1\ntwo\n3\n4\n5\n");
7972
}
7973
7974
#[test]
7975
fn many_edited_files_diff_in_parallel() {
7976
    // Enough edited files that the builder diffs them in parallel; the
7977
    // commit must hold exactly what is on disk, and a second snapshot
7978
    // must find nothing left to commit.
7979
    hermetic();
7980
    let dir = tempfile::tempdir().unwrap();
7981
    let root = dir.path();
7982
    let repo = Repo::init(root).unwrap();
7983
    let text = |i: usize, round: usize| {
7984
        let mut s = String::new();
7985
        for line in 0..50 {
7986
            if round > 0 && line % 7 == i % 7 {
7987
                s.push_str(&format!("edited {round} {i} {line}\n"));
7988
            } else {
7989
                s.push_str(&format!("file {i} line {line}\n"));
7990
            }
7991
        }
7992
        if round > 0 && i.is_multiple_of(3) {
7993
            s.push_str("appended\n");
7994
        }
7995
        s
7996
    };
7997
    for i in 0..40 {
7998
        write(root, &format!("d/f{i}.txt"), text(i, 0).as_bytes());
7999
    }
8000
    repo.commit("first", &[]).unwrap();
8001
    for i in 0..40 {
8002
        write(root, &format!("d/f{i}.txt"), text(i, 1).as_bytes());
8003
    }
8004
    let h = repo.commit("edit every file", &[]).unwrap();
8005
    let snap = repo.load_state(&[h]).unwrap().materialize();
8006
    for i in 0..40 {
8007
        let want = text(i, 1);
8008
        assert!(
8009
            matches!(&snap.files[&format!("d/f{i}.txt")].content, FileContent::Text { bytes, .. } if bytes == want.as_bytes()),
8010
            "d/f{i}.txt as committed"
8011
        );
8012
    }
8013
    assert!(
8014
        repo.commit("nothing", &[]).is_err(),
8015
        "nothing left to commit"
8016
    );
8017
}
8018
8019
/// oxygen#56: after a fetch, how a bookmark stands against its remote copy
8020
/// is known (fetch printed "up to date" while main was behind), a change
8021
/// only fetched resolves and says where it is, and a checkout whose only
8022
/// remote is not `origin` uses that one.
8023
#[test]
8024
fn a_fetched_change_shows_as_behind_and_resolves() {
8025
    hermetic();
8026
    let dir = tempfile::tempdir().unwrap();
8027
    let root = dir.path();
8028
    let origin = Repo::init(&root.join("origin")).unwrap();
8029
    drop(origin);
8030
    let url = root.join("origin").to_string_lossy().to_string();
8031
    let a = Repo::clone(&url, &root.join("a"))
8032
        .unwrap()
8033
        .with_home(root.join("home-a"));
8034
    write(&root.join("a"), "f.txt", b"one\n");
8035
    a.commit("one", &[]).unwrap();
8036
    a.push("origin", false).unwrap();
8037
    let b = Repo::clone(&url, &root.join("b"))
8038
        .unwrap()
8039
        .with_home(root.join("home-b"));
8040
    assert_eq!(b.tracking("origin", "main").unwrap(), Some((0, 0)));
8041
8042
    write(&root.join("a"), "f.txt", b"one\ntwo\n");
8043
    let h2 = a.commit("two", &[]).unwrap();
8044
    a.push("origin", false).unwrap();
8045
    b.fetch("origin").unwrap();
8046
    // Fetched, not pulled: one behind, the change found and placed.
8047
    assert_eq!(b.tracking("origin", "main").unwrap(), Some((0, 1)));
8048
    assert_eq!(b.tracking("origin", "nope").unwrap(), None);
8049
    assert_eq!(
8050
        b.resolve_change(&format!("#{}", &h2.to_hex()[..12]))
8051
            .unwrap(),
8052
        h2
8053
    );
8054
    assert_eq!(
8055
        b.remote_only_location(&h2).unwrap().as_deref(),
8056
        Some("origin/main")
8057
    );
8058
    // Fetching again changes nothing: still behind, which is what the
8059
    // CLI now says rather than "up to date".
8060
    b.fetch("origin").unwrap();
8061
    assert_eq!(b.tracking("origin", "main").unwrap(), Some((0, 1)));
8062
    b.pull("origin").unwrap();
8063
    assert_eq!(b.tracking("origin", "main").unwrap(), Some((0, 0)));
8064
    assert_eq!(b.remote_only_location(&h2).unwrap(), None);
8065
8066
    // One remote, not called origin: it is the default.
8067
    let mut c = Repo::init(&root.join("c")).unwrap();
8068
    assert_eq!(c.default_remote(), "origin");
8069
    c.config.set("remote.earth.url", &url).unwrap();
8070
    assert_eq!(c.default_remote(), "earth");
8071
    c.config.set("remote.origin.url", &url).unwrap();
8072
    assert_eq!(c.default_remote(), "origin");
8073
}
8074
8075
/// oxygen#57: a clone from a relative local path records the remote as an
8076
/// absolute path, so fetch still finds it from inside the clone.
8077
#[test]
8078
fn a_clone_from_a_relative_path_records_it_absolute() {
8079
    hermetic();
8080
    let dir = tempfile::tempdir().unwrap();
8081
    let root = dir.path();
8082
    Repo::init(&root.join("origin")).unwrap();
8083
    let rel = crate::protocol::stored_url("relative/repo");
8084
    assert!(std::path::Path::new(&rel).is_absolute(), "{rel}");
8085
    assert_eq!(
8086
        crate::protocol::stored_url("https://hub.example/o/n"),
8087
        "https://hub.example/o/n"
8088
    );
8089
    assert!(crate::protocol::stored_url("file://x").starts_with("file:///"));
8090
    assert!(crate::protocol::stored_url("dir://x").starts_with("dir:///"));
8091
    // A bucket is kept as written: it is not a path.
8092
    assert_eq!(
8093
        crate::protocol::stored_url("s3://bucket/prefix?profile=p"),
8094
        "s3://bucket/prefix?profile=p"
8095
    );
8096
    let url = root.join("origin").to_string_lossy().to_string();
8097
    let b = Repo::clone(&url, &root.join("b")).unwrap();
8098
    assert_eq!(b.config.remotes["origin"], url);
8099
    b.fetch("origin").unwrap();
8100
}
8101
8102
/// oxygen#60 and #61: a workspace added on a bookmark is on that bookmark,
8103
/// and gets its subrepos at their pins from this workspace's copies, with
8104
/// their remotes pointing where the subrepos come from.
8105
#[test]
8106
fn a_workspace_added_on_a_bookmark_is_on_it_with_its_subrepos() {
8107
    hermetic();
8108
    let dir = tempfile::tempdir().unwrap();
8109
    let root = dir.path();
8110
    Repo::init(&root.join("lib-origin")).unwrap();
8111
    let lib_url = root.join("lib-origin").to_string_lossy().to_string();
8112
    let lib = Repo::clone(&lib_url, &root.join("lib"))
8113
        .unwrap()
8114
        .with_home(root.join("home"));
8115
    write(&root.join("lib"), "lib.txt", b"v1\n");
8116
    let l1 = lib.commit("lib v1", &[]).unwrap();
8117
    assert!(lib.push("origin", false).unwrap()[0].ok);
8118
8119
    let app_dir = root.join("app");
8120
    let app = Repo::init(&app_dir).unwrap().with_home(root.join("home"));
8121
    write(&app_dir, "main.txt", b"app\n");
8122
    app.submodule_add(&lib_url, "libs/lib", None).unwrap();
8123
    app.commit("app with lib", &[]).unwrap();
8124
    // A second bookmark, and the main workspace on another.
8125
    app.bookmark_create("develop", None).unwrap();
8126
    app.bookmark_create("feature", None).unwrap();
8127
    let mut app = app;
8128
    app.bookmark_switch("feature", false).unwrap();
8129
    assert_eq!(app.config.bookmark, "feature");
8130
8131
    // The library's origin goes away: the subrepo must come from here.
8132
    std::fs::rename(root.join("lib-origin"), root.join("lib-origin-gone")).unwrap();
8133
    let heads = app.resolve_heads("develop").unwrap();
8134
    let ws = app
8135
        .workspace_add_on(&root.join("ws"), Some(&heads), Some("develop"))
8136
        .unwrap();
8137
    assert_eq!(
8138
        ws.config.bookmark, "develop",
8139
        "the new workspace is on develop"
8140
    );
8141
    assert_eq!(
8142
        app.config.bookmark, "feature",
8143
        "and this one stays on its own"
8144
    );
8145
    let sub = Repo::open(&root.join("ws/libs/lib")).unwrap();
8146
    assert_eq!(
8147
        sub.config.remotes["origin"], lib_url,
8148
        "its origin is the subrepo's URL"
8149
    );
8150
    assert_eq!(sub.bookmark_heads().unwrap(), vec![l1], "at its pin");
8151
    assert_eq!(
8152
        std::fs::read(root.join("ws/libs/lib/lib.txt")).unwrap(),
8153
        b"v1\n"
8154
    );
8155
}
8156
8157
/// Revsets (docs/revset_query_language.md): symbols, relations, set
8158
/// operators and the predicates, over a small graph with two heads and
8159
/// a rename.
8160
#[test]
8161
fn revsets_select_changes_by_relation_author_text_date_and_path() {
8162
    hermetic();
8163
    let dir = tempfile::tempdir().unwrap();
8164
    let root = dir.path();
8165
    let mut repo = Repo::init(root).unwrap().with_home(root.join("home"));
8166
    repo.create_identity("Ada", "[email protected]", IdentityScope::User)
8167
        .unwrap();
8168
    write(root, "src/a.rs", b"one\n");
8169
    let a = repo.commit("first: add a", &[]).unwrap();
8170
    write(root, "src/a.rs", b"one\ntwo\n");
8171
    let b = repo.commit("second: grow a", &[]).unwrap();
8172
    // A second head, independent of b: a new file on top of a.
8173
    repo.checkout(&[a], false, "checkout a").unwrap();
8174
    write(root, "docs/notes.md", b"notes\n");
8175
    let c = repo.commit("third: notes", &[]).unwrap();
8176
    // Back to both heads, then rename a.rs: the node keeps its identity.
8177
    repo.checkout(&repo.bookmark_heads().unwrap(), false, "checkout main")
8178
        .unwrap();
8179
    fs::remove_file(root.join("src/a.rs")).unwrap();
8180
    write(root, "src/z.rs", b"one\ntwo\n");
8181
    let d = repo.commit("fourth: rename a to z", &[]).unwrap();
8182
    let wc = repo.working_copy().unwrap().0;
8183
    // A saved revset is checked when set.
8184
    repo.set_user_config("revset.mine", "author(me) & ::main")
8185
        .unwrap();
8186
    assert!(repo.set_user_config("revset.bad", "a &").is_err());
8187
    let set = |src: &str| -> Vec<ChangeHash> {
8188
        let mut v = repo.revset(src).unwrap().hashes;
8189
        v.sort();
8190
        v
8191
    };
8192
    let sorted = |hs: &[ChangeHash]| -> Vec<ChangeHash> {
8193
        let mut v = hs.to_vec();
8194
        v.sort();
8195
        v
8196
    };
8197
8198
    // Changes commute: a new file depends on nothing and the rename on the
8199
    // file's creation, so the graph is a, b->a, d->a, c, and the working
8200
    // copy on the three heads b, c, d.
8201
    let heads = sorted(&repo.bookmark_heads().unwrap());
8202
    let meta = |h: &ChangeHash| repo.store().get_change_meta(h).unwrap();
8203
    assert!(heads.contains(&d) && heads.contains(&c));
8204
    // Symbols and closures.
8205
    assert_eq!(set("main"), heads);
8206
    assert_eq!(set("::main"), sorted(&[a, b, c, d]));
8207
    assert_eq!(set("@"), vec![wc]);
8208
    assert_eq!(set("::@"), sorted(&[a, b, c, d, wc]));
8209
    assert_eq!(set(&format!("::#{}", b.short(12))), sorted(&[a, b]));
8210
    assert_eq!(set(&format!("#{}::", a.short(12))), sorted(&[a, b, d, wc]));
8211
    assert_eq!(
8212
        set(&format!("#{}::#{}", a.short(12), b.short(12))),
8213
        sorted(&[a, b])
8214
    );
8215
    // Ranges: what main has beyond b, and `..` forms.
8216
    assert_eq!(set(&format!("#{}..main", b.short(12))), sorted(&[c, d]));
8217
    assert_eq!(set(&format!("#{}..", c.short(12))), sorted(&[a, b, d, wc]));
8218
    assert_eq!(set("..main"), sorted(&[a, b, c, d]));
8219
    // Operators and precedence: ~ binds tighter than &, & than |.
8220
    assert_eq!(
8221
        set(&format!("::main ~ #{}", d.short(12))),
8222
        sorted(&[a, b, c])
8223
    );
8224
    assert_eq!(
8225
        set(&format!("::main & #{} | #{}", b.short(12), c.short(12))),
8226
        sorted(&[b, c])
8227
    );
8228
    assert_eq!(set("all() ~ ::main"), vec![wc]);
8229
    // Relations.
8230
    let mut head_deps: Vec<ChangeHash> = heads.iter().flat_map(|h| meta(h).deps).collect();
8231
    head_deps.sort();
8232
    head_deps.dedup();
8233
    assert_eq!(set("deps(main)"), head_deps);
8234
    let on_a: Vec<ChangeHash> = [b, c, d]
8235
        .into_iter()
8236
        .filter(|h| meta(h).deps.contains(&a))
8237
        .collect();
8238
    assert_eq!(set(&format!("dependents(#{})", a.short(12))), sorted(&on_a));
8239
    assert_eq!(set("heads(::main)"), heads);
8240
    assert_eq!(set("roots(::main)"), sorted(&[a, c]));
8241
    assert_eq!(
8242
        set(&format!(
8243
            "heads(#{} | #{} | #{})",
8244
            a.short(12),
8245
            b.short(12),
8246
            c.short(12)
8247
        )),
8248
        sorted(&[b, c])
8249
    );
8250
    assert_eq!(set("latest(::main, 1)"), vec![d]);
8251
    assert_eq!(set("kind(working-copy)"), vec![wc]);
8252
    assert_eq!(set("none()"), vec![]);
8253
    // Predicates: author by name, email, key prefix and `me`.
8254
    let key = repo.config.author_key.unwrap();
8255
    assert_eq!(set("author(ada) & ::main"), sorted(&[a, b, c, d]));
8256
    assert_eq!(set("author(\"[email protected]\") & ::main").len(), 4);
8257
    assert_eq!(set(&format!("author({}) & ::main", key.short(12))).len(), 4);
8258
    assert_eq!(set("author(me) & ::main").len(), 4);
8259
    assert_eq!(set("author(nobody)"), vec![]);
8260
    assert_eq!(set("description(notes)"), vec![c]);
8261
    assert_eq!(set("description(\"rename a\")"), vec![d]);
8262
    assert_eq!(set("date(-1h..) & ::main").len(), 4);
8263
    assert_eq!(set("date(..2000-01-01)"), vec![]);
8264
    // touches follows the node through the rename, in the current state.
8265
    assert_eq!(set("touches(\"src/z.rs\")"), sorted(&[a, b, d]));
8266
    assert_eq!(set("touches(\"src/**\") & ::main"), sorted(&[a, b, d]));
8267
    assert_eq!(set("touches(\"docs/*\")"), vec![c]);
8268
    assert_eq!(set("touches(\"nothing/*\")"), vec![]);
8269
    // Newest first in the result order.
8270
    assert_eq!(repo.revset("::main").unwrap().hashes[0], d);
8271
    // The saved revset, and errors that say what is wrong.
8272
    assert_eq!(set("mine()").len(), 4);
8273
    let e = repo.revset("nosuch()").unwrap_err().to_string();
8274
    assert!(e.contains("unknown function nosuch()"), "{e}");
8275
    let e = repo.revset("main &").unwrap_err().to_string();
8276
    assert!(e.contains("at character"), "{e}");
8277
    let e = repo.revset("zzzz").unwrap_err().to_string();
8278
    assert!(e.contains("no change matches"), "{e}");
8279
    let e = repo
8280
        .revset_with_budget("::main", std::time::Duration::ZERO)
8281
        .unwrap_err()
8282
        .to_string();
8283
    assert!(e.contains("budget"), "{e}");
8284
    // The log entries carry the bookmark's heads and the working copy.
8285
    let entries = repo.log_revset("::@").unwrap();
8286
    assert!(entries[0].is_working_copy && entries.iter().any(|e| e.is_head && e.hash == d));
8287
    // Trust predicates (§2.4): nothing is signed yet (core.sign = seal, no
8288
    // push); then a signed change, a tag, and a revocation.
8289
    assert_eq!(set("unsigned() & ::main"), sorted(&[a, b, c, d]));
8290
    assert_eq!(set("signed_by(me)"), vec![]);
8291
    repo.sign_change(&d).unwrap();
8292
    assert_eq!(set("signed_by(me)"), vec![d]);
8293
    assert_eq!(set("signed_by([email protected])"), vec![d]);
8294
    assert_eq!(set(&format!("signed_by({})", key.short(12))), vec![d]);
8295
    assert_eq!(set("unsigned() & ::main"), sorted(&[a, b, c]));
8296
    assert_eq!(set("delegated()"), vec![]);
8297
    assert_eq!(set("revoked()"), vec![]);
8298
    assert_eq!(set("attested(tag)"), vec![]);
8299
    repo.tag_create("v1", &[b], "first").unwrap();
8300
    assert_eq!(set("attested(tag)"), sorted(&[a, b]));
8301
    assert_eq!(set("attested(tag) & unsigned()"), sorted(&[a, b]));
8302
    assert_eq!(set("attested(receipt)"), vec![]);
8303
    assert_eq!(set("built(test)"), vec![]);
8304
    let e = repo.revset("attested(seal)").unwrap_err().to_string();
8305
    assert!(e.contains("tag, receipt or ref"), "{e}");
8306
    repo.revoke_identity(&key, "test").unwrap();
8307
    assert_eq!(set("revoked()"), vec![d]);
8308
    assert_eq!(set("signed_by(me) ~ revoked()"), vec![]);
8309
}
8310
8311
#[test]
8312
fn a_rotation_is_recorded_wherever_the_old_key_was_named() {
8313
    let dir = tempfile::tempdir().unwrap();
8314
    let root = dir.path();
8315
    let home = root.join("home");
8316
    // Ada's identity lives in the user file; repository `a` pins the same
8317
    // key in its own file, repository `b` names none.
8318
    let mut a = Repo::init(&root.join("a")).unwrap().with_home(&home);
8319
    let (key, _) = a
8320
        .create_identity("Ada", "[email protected]", IdentityScope::User)
8321
        .unwrap();
8322
    a.config.set("author.key", &key.to_hex()).unwrap();
8323
    a.save_config().unwrap();
8324
    let agent = SecretKey::generate().identity("Agent", "[email protected]", 1);
8325
    let r = a
8326
        .delegate_add(agent.clone(), crate::identity::Scope::CHANGES, None)
8327
        .unwrap();
8328
    assert_eq!(
8329
        read_config_file(&home.join("config.toml")).unwrap()["author.key"],
8330
        r.new.to_hex(),
8331
        "the user file follows"
8332
    );
8333
    assert_eq!(
8334
        read_config_file(&root.join("a/.oxy/config")).unwrap()["author.key"],
8335
        r.new.to_hex(),
8336
        "the pinning repository follows"
8337
    );
8338
    let b = Repo::init(&root.join("b")).unwrap().with_home(&home);
8339
    assert_eq!(
8340
        b.config.author_key,
8341
        Some(r.new),
8342
        "a checkout without a pin follows the user file"
8343
    );
8344
    // A repository-scoped identity leaves the user file alone.
8345
    let other_home = root.join("home2");
8346
    let mut c = Repo::init(&root.join("c")).unwrap().with_home(&other_home);
8347
    let (ck, _) = c
8348
        .create_identity("Cy", "[email protected]", IdentityScope::Repo)
8349
        .unwrap();
8350
    assert!(!other_home.join("config.toml").exists());
8351
    let r2 = c.rotate_identity().unwrap();
8352
    assert_ne!(r2.new, ck);
8353
    assert_eq!(
8354
        read_config_file(&root.join("c/.oxy/config")).unwrap()["author.key"],
8355
        r2.new.to_hex()
8356
    );
8357
    assert!(
8358
        !other_home.join("config.toml").exists(),
8359
        "a repository-scoped identity stays repository-scoped"
8360
    );
8361
    // Several delegates in one rotation; a repeat is refused.
8362
    let (d1, d2) = (
8363
        SecretKey::generate().identity("D1", "d1@x", 1),
8364
        SecretKey::generate().identity("D2", "d2@x", 1),
8365
    );
8366
    let r3 = c
8367
        .delegate_add_many(vec![d1.clone(), d2], crate::identity::Scope::CHANGES, None)
8368
        .unwrap();
8369
    assert_eq!(r3.identity.delegates.len(), 2);
8370
    assert!(c
8371
        .delegate_add(d1, crate::identity::Scope::CHANGES, None)
8372
        .is_err());
8373
}
8374
8375
/// Two unrelated histories that both add the same file, joined by two
8376
/// independent merges on two branches, then those branches merged: Git
8377
/// merges identical additions cleanly, and the import must too (#71,
8378
/// found in VS Code's history).
8379
#[test]
8380
fn git_import_joins_unrelated_histories_that_add_the_same_file() {
8381
    // Batches of one: every merge renders apart from the state, where a
8382
    // file whose graph the state had built came out empty (#71).
8383
    crate::repo::git::set_merge_batch_for_tests(Some(1));
8384
    hermetic();
8385
    if std::process::Command::new("git")
8386
        .arg("--version")
8387
        .output()
8388
        .is_err()
8389
    {
8390
        eprintln!("git not installed; skipping");
8391
        return;
8392
    }
8393
    let dir = tempfile::tempdir().unwrap();
8394
    let root = dir.path();
8395
    let g = root.join("src.git");
8396
    fs::create_dir_all(&g).unwrap();
8397
    let git = |args: &[&str]| -> String {
8398
        let out = std::process::Command::new("git")
8399
            .arg("-C")
8400
            .arg(&g)
8401
            .args([
8402
                "-c",
8403
                "user.name=Grace",
8404
                "-c",
8405
                "[email protected]",
8406
                "-c",
8407
                "commit.gpgsign=false",
8408
            ])
8409
            .args(args)
8410
            .output()
8411
            .unwrap();
8412
        assert!(
8413
            out.status.success(),
8414
            "git {args:?}: {}",
8415
            String::from_utf8_lossy(&out.stderr)
8416
        );
8417
        String::from_utf8_lossy(&out.stdout).trim().to_string()
8418
    };
8419
    let text = b"/* header */\nconst a = 1;\nconst b = 2;\n";
8420
    // History A: main.
8421
    git(&["init", "-q", "-b", "main"]);
8422
    write(&g, "gulpfile.js", text);
8423
    write(&g, "a.txt", b"a\n");
8424
    git(&["add", "."]);
8425
    git(&["commit", "-q", "-m", "A root"]);
8426
    // History B: an unrelated root adding the same file, identical.
8427
    git(&["checkout", "-q", "--orphan", "fork"]);
8428
    git(&["rm", "-q", "-r", "--cached", "."]);
8429
    for f in ["gulpfile.js", "a.txt"] {
8430
        let _ = fs::remove_file(g.join(f));
8431
    }
8432
    write(&g, "gulpfile.js", text);
8433
    write(&g, "b.txt", b"b\n");
8434
    git(&["add", "."]);
8435
    git(&["commit", "-q", "-m", "B root"]);
8436
    // Two branches from main, each joining B on its own.
8437
    git(&["checkout", "-q", "-b", "one", "main"]);
8438
    git(&[
8439
        "merge",
8440
        "-q",
8441
        "--no-ff",
8442
        "--allow-unrelated-histories",
8443
        "-m",
8444
        "join on one",
8445
        "fork",
8446
    ]);
8447
    git(&["checkout", "-q", "-b", "two", "main"]);
8448
    write(&g, "a.txt", b"a\ntwo\n");
8449
    git(&["commit", "-q", "-am", "work on two"]);
8450
    git(&[
8451
        "merge",
8452
        "-q",
8453
        "--no-ff",
8454
        "--allow-unrelated-histories",
8455
        "-m",
8456
        "join on two",
8457
        "fork",
8458
    ]);
8459
    // Then the two joins meet, and the file is reformatted after.
8460
    git(&["checkout", "-q", "main"]);
8461
    git(&["merge", "-q", "--no-ff", "-m", "merge one", "one"]);
8462
    git(&["merge", "-q", "--no-ff", "-m", "merge two", "two"]);
8463
    write(
8464
        &g,
8465
        "gulpfile.js",
8466
        b"/* header */\nconst a = 1;\nconst b = 3;\n",
8467
    );
8468
    git(&["commit", "-q", "-am", "after"]);
8469
8470
    let dest = root.join("dest");
8471
    let repo = Repo::init(&dest).unwrap().with_home(root.join("home"));
8472
    repo.import_git(&g, "main").unwrap();
8473
    let v = repo.verify_git_import(&g, "main").unwrap();
8474
    assert!(v.mismatches.is_empty(), "{:?}", v.mismatches);
8475
    assert_eq!(
8476
        fs::read(dest.join("gulpfile.js")).unwrap(),
8477
        b"/* header */\nconst a = 1;\nconst b = 3;\n"
8478
    );
8479
}
8480
8481
/// As above, but the two joins keep different copies (each branch had a
8482
/// different version when it joined), and later work edits each copy:
8483
/// the shape of VS Code's c67ef57cda90 (#71).
8484
#[test]
8485
fn git_import_joins_where_each_join_kept_a_different_copy() {
8486
    // Batches of one: every merge renders apart from the state, where a
8487
    // file whose graph the state had built came out empty (#71).
8488
    crate::repo::git::set_merge_batch_for_tests(Some(1));
8489
    hermetic();
8490
    if std::process::Command::new("git")
8491
        .arg("--version")
8492
        .output()
8493
        .is_err()
8494
    {
8495
        eprintln!("git not installed; skipping");
8496
        return;
8497
    }
8498
    let dir = tempfile::tempdir().unwrap();
8499
    let root = dir.path();
8500
    let g = root.join("src.git");
8501
    fs::create_dir_all(&g).unwrap();
8502
    let run = |args: &[&str]| {
8503
        std::process::Command::new("git")
8504
            .arg("-C")
8505
            .arg(&g)
8506
            .args([
8507
                "-c",
8508
                "user.name=Grace",
8509
                "-c",
8510
                "[email protected]",
8511
                "-c",
8512
                "commit.gpgsign=false",
8513
            ])
8514
            .args(args)
8515
            .output()
8516
            .unwrap()
8517
    };
8518
    let git = |args: &[&str]| -> String {
8519
        let out = run(args);
8520
        assert!(
8521
            out.status.success(),
8522
            "git {args:?}: {}",
8523
            String::from_utf8_lossy(&out.stderr)
8524
        );
8525
        String::from_utf8_lossy(&out.stdout).trim().to_string()
8526
    };
8527
    git(&["init", "-q", "-b", "main"]);
8528
    write(
8529
        &g,
8530
        "gulpfile.js",
8531
        b"/* header */\nconst a = 1;\nconst b = 2;\n",
8532
    );
8533
    git(&["add", "."]);
8534
    git(&["commit", "-q", "-m", "A root"]);
8535
    write(
8536
        &g,
8537
        "gulpfile.js",
8538
        b"/* header */\nconst a = 1;\n\nconst b = 2;\n",
8539
    );
8540
    git(&["commit", "-q", "-am", "whitespace"]);
8541
    git(&["checkout", "-q", "--orphan", "fork"]);
8542
    git(&["rm", "-q", "-r", "--cached", "."]);
8543
    let _ = fs::remove_file(g.join("gulpfile.js"));
8544
    write(
8545
        &g,
8546
        "gulpfile.js",
8547
        b"/* header */\nconst a = 1;\nconst b = 2;\nconst c = 3;\n",
8548
    );
8549
    git(&["add", "."]);
8550
    git(&["commit", "-q", "-m", "B root"]);
8551
    // Branch one joins B keeping main's copy; branch two keeps B's.
8552
    for (branch, keep) in [("one", "ours"), ("two", "theirs")] {
8553
        git(&["checkout", "-q", "-b", branch, "main"]);
8554
        let _ = run(&[
8555
            "merge",
8556
            "-q",
8557
            "--no-ff",
8558
            "--allow-unrelated-histories",
8559
            "-m",
8560
            "join",
8561
            "fork",
8562
        ]);
8563
        git(&["checkout", &format!("--{keep}"), "gulpfile.js"]);
8564
        git(&["add", "gulpfile.js"]);
8565
        git(&["commit", "-q", "-m", &format!("join on {branch}")]);
8566
    }
8567
    // Each branch then edits its copy.
8568
    git(&["checkout", "-q", "one"]);
8569
    write(
8570
        &g,
8571
        "gulpfile.js",
8572
        b"/* header */\nconst a = 1;\n\nconst b = 2;\n// tslint\n",
8573
    );
8574
    git(&["commit", "-q", "-am", "tslint on one"]);
8575
    git(&["checkout", "-q", "two"]);
8576
    write(
8577
        &g,
8578
        "gulpfile.js",
8579
        b"/* header */\nconst a = 1;\nconst b = 2;\nconst c = 3;\n// fmt\n",
8580
    );
8581
    write(&g, "extra.txt", b"x\n");
8582
    write(&g, "more.txt", b"m\n");
8583
    git(&["add", "."]);
8584
    git(&["commit", "-q", "-am", "fmt on two"]);
8585
    // They meet: resolved by hand.
8586
    git(&["checkout", "-q", "one"]);
8587
    let _ = run(&["merge", "-q", "--no-ff", "-m", "merge two", "two"]);
8588
    write(
8589
        &g,
8590
        "gulpfile.js",
8591
        b"/* header */\nconst a = 1;\nconst b = 2;\nconst c = 3;\n// tslint\n// fmt\n",
8592
    );
8593
    git(&["add", "gulpfile.js"]);
8594
    git(&["commit", "-q", "-m", "merge two into one"]);
8595
8596
    let dest = root.join("dest");
8597
    let repo = Repo::init(&dest).unwrap().with_home(root.join("home"));
8598
    repo.import_git(&g, "one").unwrap();
8599
    let v = repo.verify_git_import(&g, "one").unwrap();
8600
    assert!(v.mismatches.is_empty(), "{:?}", v.mismatches);
8601
}
8602
8603
/// oxygen#68: on a store that is not this disk's directory, the operation
8604
/// head is the store's reference record, moved by compare-and-swap. Two
8605
/// handles recording from the same head both get through, merged; a swap
8606
/// from a stale version is refused; a second repository cannot start on a
8607
/// store that already holds one.
8608
#[test]
8609
fn over_a_store_the_operation_head_moves_by_compare_and_swap() {
8610
    use crate::strata::{MemoryStore, Store as _};
8611
    let backend = std::sync::Arc::new(MemoryStore::new());
8612
    crate::store::TEST_BACKEND.with(|t| *t.borrow_mut() = Some(backend.clone()));
8613
    let dir = tempfile::tempdir().unwrap();
8614
    let a = Repo::init(dir.path()).unwrap();
8615
    assert!(
8616
        !dir.path().join(".oxy/ops/head").exists(),
8617
        "the head is not a file"
8618
    );
8619
    let (h0, op0) = a.head_op().unwrap();
8620
    let record = backend
8621
        .read_ref(HEAD_RECORD)
8622
        .unwrap()
8623
        .expect("the head is the store's record");
8624
    assert_eq!(String::from_utf8(record.0).unwrap(), h0.to_hex());
8625
8626
    let b = Repo::open(dir.path()).unwrap();
8627
    let state = a.store.put_state(&StateObject::new(vec![])).unwrap();
8628
    let mut va = op0.view.clone();
8629
    va.bookmarks.insert("from-a".into(), state);
8630
    let mut vb = op0.view.clone();
8631
    vb.bookmarks.insert("from-b".into(), state);
8632
    let rb = b.record_op(&[h0], "bookmark from-b", vb).unwrap();
8633
    assert_eq!(b.head_ref().unwrap(), rb);
8634
    // a recorded from h0 too: the head moved, so the two are merged.
8635
    let ra = a.record_op(&[h0], "bookmark from-a", va).unwrap();
8636
    let (head, op) = Repo::open(dir.path()).unwrap().head_op().unwrap();
8637
    assert_eq!(head, ra);
8638
    assert!(
8639
        op.command.ends_with("(merged with a concurrent operation)"),
8640
        "{}",
8641
        op.command
8642
    );
8643
    assert_eq!(op.parents, vec![rb, op.parents[1]]);
8644
    assert!(op.view.bookmarks.contains_key("from-a") && op.view.bookmarks.contains_key("from-b"));
8645
8646
    // A swap from a version that is no longer current moves nothing.
8647
    let (h, v) = a.read_head().unwrap();
8648
    assert!(b.swap_head(&rb, v.as_ref()).unwrap());
8649
    assert!(!a.swap_head(&h, v.as_ref()).unwrap(), "stale");
8650
    a.refresh().unwrap();
8651
    assert_eq!(a.head_ref().unwrap(), rb);
8652
8653
    let other = tempfile::tempdir().unwrap();
8654
    let err = Repo::init(other.path())
8655
        .err()
8656
        .expect("the store already holds a log")
8657
        .to_string();
8658
    assert!(
8659
        err.contains("already holds a repository's operation log"),
8660
        "{err}"
8661
    );
8662
    crate::store::TEST_BACKEND.with(|t| *t.borrow_mut() = None);
8663
}
8664
8665
/// oxygen#68: a repository kept on a store (`storage.url`) holds its
8666
/// objects and operation head there, with `.oxy/cache` in front: it works
8667
/// as one on disk does, reopens, and survives losing its cache.
8668
#[test]
8669
fn a_repository_runs_on_a_store_with_a_cache_in_front() {
8670
    hermetic();
8671
    if std::env::var_os("OXY_STORE_BACKEND").is_some() {
8672
        return;
8673
    }
8674
    let dir = tempfile::tempdir().unwrap();
8675
    let (root, bucket) = (dir.path().join("work"), dir.path().join("bucket"));
8676
    let url = format!("dir://{}", bucket.display());
8677
    let repo = Repo::init_on(&root, [7; 16], Some(&url)).unwrap();
8678
    assert_eq!(repo.config.storage_url.as_deref(), Some(url.as_str()));
8679
    write(&root, "a.txt", b"one\n");
8680
    let h1 = repo.commit("First", &[]).unwrap();
8681
    write(&root, "a.txt", b"one\ntwo\n");
8682
    let h2 = repo.commit("Second", &[]).unwrap();
8683
    assert!(
8684
        !root.join(".oxy/ops/head").exists(),
8685
        "the head is in the store"
8686
    );
8687
    assert!(bucket.join("ops/head").is_file());
8688
    assert!(root.join(".oxy/cache").is_dir());
8689
    drop(repo);
8690
8691
    // Reopened, and again with no cache at all: everything comes from the store.
8692
    for drop_cache in [false, true] {
8693
        if drop_cache {
8694
            std::fs::remove_dir_all(root.join(".oxy/cache")).unwrap();
8695
        }
8696
        let repo = Repo::open(&root).unwrap();
8697
        let log: Vec<String> = repo
8698
            .op_log()
8699
            .unwrap()
8700
            .into_iter()
8701
            .map(|(_, op)| op.command)
8702
            .collect();
8703
        assert!(log.len() >= 3, "{log:?}");
8704
        assert_eq!(repo.store().get_change(&h1).unwrap().message, "First");
8705
        let heads = repo
8706
            .store()
8707
            .get_state(&repo.view().unwrap().bookmarks["main"])
8708
            .unwrap()
8709
            .heads;
8710
        assert_eq!(heads, vec![h2]);
8711
        assert_eq!(
8712
            repo.load_state(&heads).unwrap().materialize().files.len(),
8713
            1
8714
        );
8715
    }
8716
8717
    // A second repository cannot start on the same store.
8718
    let err = Repo::init_on(&dir.path().join("other"), [8; 16], Some(&url))
8719
        .err()
8720
        .unwrap()
8721
        .to_string();
8722
    assert!(
8723
        err.contains("already holds a repository's operation log"),
8724
        "{err}"
8725
    );
8726
    let err = Repo::init_on(&dir.path().join("third"), [9; 16], Some("nope://x"))
8727
        .err()
8728
        .unwrap()
8729
        .to_string();
8730
    assert!(err.contains("cannot open that kind of store"), "{err}");
8731
}
8732
8733
/// oxygen#75: the prompt's quick check agrees with status in a repository
8734
/// with a subrepo: clean after a commit, dirty when the subrepo moves to
8735
/// another state, clean again once that pin is committed. (It compared the
8736
/// subrepo's directory as if it were a file, so it was always dirty.)
8737
#[test]
8738
fn the_quick_dirty_check_compares_a_subrepo_by_its_pin() {
8739
    hermetic();
8740
    let dir = tempfile::tempdir().unwrap();
8741
    let root = dir.path();
8742
    let _lib_origin = Repo::init(&root.join("lib-origin")).unwrap();
8743
    let lib_url = root.join("lib-origin").to_string_lossy().to_string();
8744
    let lib = Repo::clone(&lib_url, &root.join("lib"))
8745
        .unwrap()
8746
        .with_home(root.join("home"));
8747
    write(&root.join("lib"), "lib.txt", b"v1\n");
8748
    lib.commit("lib v1", &[]).unwrap();
8749
    assert!(lib.push("origin", false).unwrap()[0].ok);
8750
    let app_dir = root.join("app");
8751
    let app = Repo::init(&app_dir).unwrap().with_home(root.join("home"));
8752
    write(&app_dir, "main.txt", b"app\n");
8753
    app.submodule_add(&lib_url, "libs/lib", None).unwrap();
8754
    app.commit("app with lib", &[]).unwrap();
8755
    // Out of the racy window, so the stat-only path decides.
8756
    std::thread::sleep(std::time::Duration::from_millis(2100));
8757
    let reopen = || Repo::open(&app_dir).unwrap();
8758
    assert_eq!(
8759
        reopen().quick_dirty().unwrap(),
8760
        Some(false),
8761
        "clean, as status says"
8762
    );
8763
    let nested = Repo::open(&app_dir.join("libs/lib")).unwrap();
8764
    write(&app_dir.join("libs/lib"), "lib.txt", b"v2\n");
8765
    nested.commit("lib v2", &[]).unwrap();
8766
    assert_eq!(
8767
        reopen().quick_dirty().unwrap(),
8768
        Some(true),
8769
        "the subrepo moved"
8770
    );
8771
    reopen().commit("pin lib v2", &[]).unwrap();
8772
    std::thread::sleep(std::time::Duration::from_millis(2100));
8773
    assert_eq!(
8774
        reopen().quick_dirty().unwrap(),
8775
        Some(false),
8776
        "the new pin is committed"
8777
    );
8778
}
8779
8780
#[test]
8781
fn a_module_entry_that_was_never_added_is_reported_as_unpinned() {
8782
    // oxygen#72: a .oxymodules section with no subrepo behind it.
8783
    hermetic();
8784
    let dir = tempfile::tempdir().unwrap();
8785
    let root = dir.path();
8786
    let _lib_origin = Repo::init(&root.join("lib-origin")).unwrap();
8787
    let lib_url = root.join("lib-origin").to_string_lossy().to_string();
8788
    let lib = Repo::clone(&lib_url, &root.join("lib"))
8789
        .unwrap()
8790
        .with_home(root.join("home"));
8791
    write(&root.join("lib"), "lib.txt", b"v1\n");
8792
    lib.commit("lib v1", &[]).unwrap();
8793
    assert!(lib.push("origin", false).unwrap()[0].ok);
8794
    let app_dir = root.join("app");
8795
    let app = Repo::init(&app_dir).unwrap().with_home(root.join("home"));
8796
    write(
8797
        &app_dir,
8798
        ".oxymodules",
8799
        format!("[libs/lib]\nurl = {lib_url}\n").as_bytes(),
8800
    );
8801
    let unpinned = app.unpinned_modules().unwrap();
8802
    assert_eq!(unpinned.len(), 1);
8803
    assert_eq!(unpinned[0].0, "libs/lib");
8804
    assert_eq!(unpinned[0].1.url, lib_url);
8805
    assert!(app.submodule_update(true, &[]).unwrap().is_empty());
8806
    app.submodule_add(&lib_url, "libs/lib", None).unwrap();
8807
    assert!(app.unpinned_modules().unwrap().is_empty(), "added now");
8808
}
8809
8810
#[test]
8811
fn the_bookmark_revset_function_names_only_bookmarks() {
8812
    // oxygen#73: bookmark(NAME) is a bookmark's heads, never a tag or prefix.
8813
    hermetic();
8814
    let dir = tempfile::tempdir().unwrap();
8815
    let repo = Repo::init(dir.path()).unwrap();
8816
    write(dir.path(), "a.txt", b"a\n");
8817
    let a = repo.commit("A", &[]).unwrap();
8818
    write(dir.path(), "b.txt", b"b\n");
8819
    let b = repo.commit("B", &[]).unwrap();
8820
    let mut heads = repo.revset("bookmark(main)").unwrap().hashes;
8821
    heads.sort();
8822
    let mut want = repo.bookmark_heads().unwrap();
8823
    want.sort();
8824
    assert_eq!(heads, want);
8825
    assert!(heads.contains(&b));
8826
    assert_eq!(repo.revset("main").unwrap().hashes.len(), heads.len());
8827
    // A change prefix is a symbol, not a bookmark.
8828
    let prefix = repo.store().get_change_meta(&a).unwrap().change_id.short(8);
8829
    assert!(repo.revset(&prefix).is_ok());
8830
    let e = repo
8831
        .revset(&format!("bookmark({prefix})"))
8832
        .unwrap_err()
8833
        .to_string();
8834
    assert!(e.contains("no such bookmark"), "{e}");
8835
}
8836
8837
#[test]
8838
fn carrying_work_over_a_subrepo_already_at_the_target_pin_is_no_conflict() {
8839
    // oxygen#74: a stale state with .oxymodules but no pin, a newer one
8840
    // pinning the subrepo, and the nested repository on disk at that pin.
8841
    hermetic();
8842
    let dir = tempfile::tempdir().unwrap();
8843
    let root = dir.path();
8844
    let _lib_origin = Repo::init(&root.join("lib-origin")).unwrap();
8845
    let lib_url = root.join("lib-origin").to_string_lossy().to_string();
8846
    let lib = Repo::clone(&lib_url, &root.join("lib"))
8847
        .unwrap()
8848
        .with_home(root.join("home"));
8849
    write(&root.join("lib"), "lib.txt", b"v1\n");
8850
    lib.commit("lib v1", &[]).unwrap();
8851
    assert!(lib.push("origin", false).unwrap()[0].ok);
8852
    let app_dir = root.join("app");
8853
    let app = Repo::init(&app_dir).unwrap().with_home(root.join("home"));
8854
    write(&app_dir, "main.txt", b"app\n");
8855
    app.submodule_add(&lib_url, "libs/lib", None).unwrap();
8856
    // The stale state: registered in .oxymodules, never pinned.
8857
    fs::rename(app_dir.join("libs/lib"), root.join("aside")).unwrap();
8858
    app.commit("initial", &[]).unwrap();
8859
    let stale = app.bookmark_heads().unwrap();
8860
    fs::rename(root.join("aside"), app_dir.join("libs/lib")).unwrap();
8861
    app.commit("pin lib", &[]).unwrap();
8862
    let newer = app.bookmark_heads().unwrap();
8863
    app.checkout(&stale, false, "test").unwrap();
8864
    write(&app_dir, "notes.txt", b"mine\n");
8865
    let (_, carried) = app.checkout_carry(&newer, "main", "test").unwrap();
8866
    assert_eq!(carried, vec!["notes.txt".to_string()]);
8867
    assert!(app_dir.join("notes.txt").exists());
8868
}
8869
8870
#[test]
8871
fn a_bookmark_only_behind_its_remote_catches_up() {
8872
    // oxygen#74: switch takes the remote's state rather than a stale one.
8873
    hermetic();
8874
    let dir = tempfile::tempdir().unwrap();
8875
    let root = dir.path();
8876
    let _origin = Repo::init(&root.join("origin")).unwrap();
8877
    let url = root.join("origin").to_string_lossy().to_string();
8878
    let one = Repo::clone(&url, &root.join("one"))
8879
        .unwrap()
8880
        .with_home(root.join("home"));
8881
    write(&root.join("one"), "a.txt", b"a\n");
8882
    one.commit("A", &[]).unwrap();
8883
    assert!(one.push("origin", false).unwrap()[0].ok);
8884
    let two = Repo::clone(&url, &root.join("two"))
8885
        .unwrap()
8886
        .with_home(root.join("home"));
8887
    write(&root.join("two"), "b.txt", b"b\n");
8888
    two.commit("B", &[]).unwrap();
8889
    assert!(two.push("origin", false).unwrap()[0].ok);
8890
    assert_eq!(one.catch_up_bookmark("main").unwrap(), None, "not fetched");
8891
    one.fetch("origin").unwrap();
8892
    assert_eq!(one.catch_up_bookmark("main").unwrap(), Some(1));
8893
    assert_eq!(one.bookmarks().unwrap()[0].behind, Some(0));
8894
    // Local work the remote lacks: left alone.
8895
    write(&root.join("one"), "c.txt", b"c\n");
8896
    one.commit("C", &[]).unwrap();
8897
    write(&root.join("two"), "d.txt", b"d\n");
8898
    two.commit("D", &[]).unwrap();
8899
    assert!(two.push("origin", false).unwrap()[0].ok);
8900
    one.fetch("origin").unwrap();
8901
    assert_eq!(one.catch_up_bookmark("main").unwrap(), None);
8902
}
8903
8904
#[test]
8905
fn a_bookmark_is_compared_with_a_remote_that_has_it_when_there_is_no_origin() {
8906
    // oxygen#83: remotes earth and gcs, origin removed.
8907
    hermetic();
8908
    let dir = tempfile::tempdir().unwrap();
8909
    let root = dir.path();
8910
    let _up = Repo::init(&root.join("up")).unwrap();
8911
    let url = root.join("up").to_string_lossy().to_string();
8912
    let other = Repo::clone(&url, &root.join("other"))
8913
        .unwrap()
8914
        .with_home(root.join("home"));
8915
    write(&root.join("other"), "a.txt", b"a\n");
8916
    other.commit("a", &[]).unwrap();
8917
    assert!(other.push("origin", false).unwrap()[0].ok);
8918
    let mut one = Repo::clone(&url, &root.join("one"))
8919
        .unwrap()
8920
        .with_home(root.join("home"));
8921
    one.config.set("remote.earth.url", &url).unwrap();
8922
    one.config.set("remote.gcs.url", &url).unwrap();
8923
    one.config.set("remote.origin.url", "").unwrap();
8924
    one.save_config().unwrap();
8925
    write(&root.join("other"), "b.txt", b"b\n");
8926
    other.commit("b", &[]).unwrap();
8927
    assert!(other.push("origin", false).unwrap()[0].ok);
8928
    one.fetch("earth").unwrap();
8929
    let b = one
8930
        .bookmarks()
8931
        .unwrap()
8932
        .into_iter()
8933
        .find(|b| b.name == "main")
8934
        .unwrap();
8935
    assert_eq!(
8936
        (b.remote.as_deref(), b.behind),
8937
        (Some("earth"), Some(1)),
8938
        "a stale origin copy is not used"
8939
    );
8940
    assert_eq!(
8941
        one.default_remote(),
8942
        "origin",
8943
        "no default chosen among several"
8944
    );
8945
    let e = one.pull(&one.default_remote()).unwrap_err().to_string();
8946
    assert!(e.contains("earth, gcs") && e.contains("core.remote"), "{e}");
8947
    one.config.set("core.remote", "earth").unwrap();
8948
    assert_eq!(one.default_remote(), "earth");
8949
}
8950
8951
#[test]
8952
fn a_missing_author_identity_says_how_to_fix_it() {
8953
    // oxygen#82: an agent home's author.key naming an identity the
8954
    // repository does not hold.
8955
    hermetic();
8956
    let dir = tempfile::tempdir().unwrap();
8957
    let mut repo = Repo::init(dir.path()).unwrap();
8958
    let missing = KeyId::from_hex(&"ab".repeat(32)).unwrap();
8959
    repo.config.set("author.key", &missing.to_hex()).unwrap();
8960
    let e = repo.identity(&missing).unwrap_err().to_string();
8961
    assert!(
8962
        e.contains("this repository has no identity") && e.contains("oxy config author.key"),
8963
        "{e}"
8964
    );
8965
    assert!(e.contains("this repository's config"), "{e}");
8966
}
8967
8968
#[test]
8969
fn a_working_copy_behind_its_bookmark_is_flagged_and_pull_brings_it_up() {
8970
    // oxygen#89 (supermarioland, 2026-10-09): the bookmark moved on without
8971
    // the working copy, a pull with nothing new left it there, and status
8972
    // said "clean".
8973
    hermetic();
8974
    let dir = tempfile::tempdir().unwrap();
8975
    let root = dir.path();
8976
    let _up = Repo::init(&root.join("up")).unwrap();
8977
    let url = root.join("up").to_string_lossy().to_string();
8978
    let other = Repo::clone(&url, &root.join("other"))
8979
        .unwrap()
8980
        .with_home(root.join("home"));
8981
    write(&root.join("other"), "a.txt", b"a\n");
8982
    other.commit("a", &[]).unwrap();
8983
    assert!(other.push("origin", false).unwrap()[0].ok);
8984
    let one = Repo::clone(&url, &root.join("one"))
8985
        .unwrap()
8986
        .with_home(root.join("home"));
8987
    write(&root.join("other"), "b.txt", b"b\n");
8988
    other.commit("b", &[]).unwrap();
8989
    assert!(other.push("origin", false).unwrap()[0].ok);
8990
    one.fetch("origin").unwrap();
8991
    // The bookmark moves; the working copy does not.
8992
    let theirs = one.resolve_heads("origin/main").unwrap();
8993
    one.bookmark_set("main", &theirs).unwrap();
8994
    assert!(!root.join("one/b.txt").exists());
8995
    assert_eq!(one.working_copy_behind().unwrap(), Some(1));
8996
    let r = one.pull("origin").unwrap();
8997
    assert!(
8998
        !r.changed && r.checked_out,
8999
        "nothing new, but the working copy caught up"
9000
    );
9001
    assert!(root.join("one/b.txt").exists());
9002
    assert_eq!(one.working_copy_behind().unwrap(), None);
9003
}
9004
9005
#[test]
9006
fn touched_nodes_cache_answers_as_the_changes_do() {
9007
    hermetic();
9008
    let dir = tempfile::tempdir().unwrap();
9009
    let repo = Repo::init(dir.path()).unwrap();
9010
    write(dir.path(), "a.txt", b"one\n");
9011
    write(dir.path(), "b.txt", b"x\n");
9012
    repo.snapshot("t").unwrap();
9013
    let c1 = repo.commit("first", &[]).unwrap();
9014
    write(dir.path(), "b.txt", b"y\n");
9015
    repo.snapshot("t").unwrap();
9016
    repo.commit("b only", &[]).unwrap();
9017
    fs::rename(dir.path().join("a.txt"), dir.path().join("c.txt")).unwrap();
9018
    write(dir.path(), "c.txt", b"one\ntwo\n");
9019
    repo.snapshot("t").unwrap();
9020
    let c3 = repo.commit("rename and edit", &[]).unwrap();
9021
    // Uncommitted work, so the working copy touches a file too.
9022
    write(dir.path(), "c.txt", b"one\ntwo\nthree\n");
9023
    repo.snapshot("t").unwrap();
9024
9025
    let path = dir.path().join(".oxy/index/touched");
9026
    let hashes = |es: Vec<LogEntry>| es.iter().map(|e| e.hash).collect::<Vec<_>>();
9027
    let cold = hashes(repo.log_for_path("c.txt").unwrap());
9028
    assert!(path.exists(), "the first query writes the cache");
9029
    let warm = hashes(repo.log_for_path("c.txt").unwrap());
9030
    assert_eq!(cold, warm, "the cache answers as the changes do");
9031
    let (wc, _) = repo.working_copy().unwrap();
9032
    assert_eq!(
9033
        cold,
9034
        vec![wc, c3, c1],
9035
        "renames followed, the working copy included"
9036
    );
9037
9038
    // Working-copy changes are not kept: they are replaced by every snapshot.
9039
    let cached = super::touched::read_touched_for_test(&fs::read(&path).unwrap()).unwrap();
9040
    assert!(!cached.contains(&wc), "a working-copy change is not cached");
9041
    assert!(cached.contains(&c1) && cached.contains(&c3));
9042
9043
    // A damaged cache is ignored, not trusted.
9044
    let mut bytes = fs::read(&path).unwrap();
9045
    let last = bytes.len() - 40;
9046
    bytes[last] ^= 1;
9047
    fs::write(&path, &bytes).unwrap();
9048
    assert_eq!(hashes(repo.log_for_path("c.txt").unwrap()), cold);
9049
    let touches = repo.log_revset("touches(\"c.txt\") ~ @").unwrap();
9050
    assert_eq!(hashes(touches), vec![c3, c1]);
9051
}
9052
9053
/// oxygen#88 (vscode 9ab2056393c8): two lines of history that each move a
9054
/// file back where it was leave two placements at one place, which the
9055
/// tree shows as one file. Removing it, and then its directory, retires
9056
/// both, so no copy is left under a directory that is gone.
9057
#[test]
9058
fn git_import_removes_every_copy_of_a_file_at_one_place() {
9059
    hermetic();
9060
    if std::process::Command::new("git")
9061
        .arg("--version")
9062
        .output()
9063
        .is_err()
9064
    {
9065
        eprintln!("git not installed; skipping");
9066
        return;
9067
    }
9068
    let dir = tempfile::tempdir().unwrap();
9069
    let root = dir.path();
9070
    let g = root.join("src.git");
9071
    fs::create_dir_all(&g).unwrap();
9072
    let git = |args: &[&str]| {
9073
        let out = std::process::Command::new("git")
9074
            .arg("-C")
9075
            .arg(&g)
9076
            .args([
9077
                "-c",
9078
                "user.name=Grace",
9079
                "-c",
9080
                "[email protected]",
9081
                "-c",
9082
                "commit.gpgsign=false",
9083
            ])
9084
            .args(args)
9085
            .output()
9086
            .unwrap();
9087
        assert!(
9088
            out.status.success(),
9089
            "git {args:?}: {}",
9090
            String::from_utf8_lossy(&out.stderr)
9091
        );
9092
    };
9093
    git(&["init", "-q", "-b", "main"]);
9094
    write(&g, "d/list.txt", b"one\ntwo\nthree\nfour\n");
9095
    write(&g, "keep.txt", b"k\n");
9096
    git(&["add", "."]);
9097
    git(&["commit", "-qm", "base"]);
9098
    fs::create_dir_all(g.join("d/sub")).unwrap();
9099
    git(&["mv", "d/list.txt", "d/sub/list.txt"]);
9100
    git(&["commit", "-qm", "into sub"]);
9101
    git(&["checkout", "-qb", "side"]);
9102
    git(&["mv", "d/sub/list.txt", "d/list.txt"]);
9103
    git(&["commit", "-qm", "back, on side"]);
9104
    git(&["checkout", "-q", "main"]);
9105
    git(&["mv", "d/sub/list.txt", "d/list.txt"]);
9106
    git(&["commit", "-qm", "back, on main"]);
9107
    git(&["merge", "-q", "--no-edit", "side"]);
9108
    git(&["rm", "-rq", "d"]);
9109
    git(&["commit", "-qm", "d goes"]);
9110
9111
    let repo = Repo::init(&root.join("o")).unwrap();
9112
    repo.import_git(&g, "main").unwrap();
9113
    let v = repo.verify_git_import(&g, "main").unwrap();
9114
    assert!(v.mismatches.is_empty(), "{:?}", v.mismatches);
9115
    let st = repo
9116
        .load_state_history(&repo.bookmark_heads().unwrap())
9117
        .unwrap();
9118
    let view = st.tree().view();
9119
    assert!(view.conflicts.is_empty(), "{:?}", view.conflicts);
9120
    assert_eq!(view.entries.keys().collect::<Vec<_>>(), vec!["keep.txt"]);
9121
}
9122
9123
/// oxygen#94: a state index's file histories are read, and checked by
9124
/// their own hashes, only when a file is built. One found damaged is an
9125
/// error that says so, the index is removed, and the next read rebuilds it.
9126
#[test]
9127
fn a_damaged_file_history_in_the_state_index_is_rebuilt() {
9128
    hermetic();
9129
    let dir = tempfile::tempdir().unwrap();
9130
    let repo = Repo::init(dir.path()).unwrap();
9131
    for i in 0..6 {
9132
        write(
9133
            dir.path(),
9134
            &format!("f{i}.txt"),
9135
            format!("one {i}\n").as_bytes(),
9136
        );
9137
    }
9138
    repo.snapshot("t").unwrap();
9139
    repo.commit("first", &[]).unwrap();
9140
    for i in 0..6 {
9141
        write(
9142
            dir.path(),
9143
            &format!("f{i}.txt"),
9144
            format!("one {i}\ntwo\n").as_bytes(),
9145
        );
9146
    }
9147
    repo.snapshot("t").unwrap();
9148
    repo.commit("second", &[]).unwrap();
9149
    let want: Vec<Vec<u8>> = (0..6)
9150
        .map(|i| format!("one {i}\ntwo\n").into_bytes())
9151
        .collect();
9152
    // The index of the working copy's base, holding every file's history
9153
    // (a few changes behind, an index is replayed onto, not rewritten).
9154
    let (_, wc) = repo.working_copy().unwrap();
9155
    let base = repo.load_state_history(&wc.deps).unwrap();
9156
    repo.write_state_index(&wc.deps, &base);
9157
    for (i, w) in want.iter().enumerate() {
9158
        assert_eq!(&repo.file_at(&format!("f{i}.txt"), None).unwrap(), w);
9159
    }
9160
    let index = repo.state_indexes();
9161
    assert!(!index.is_empty(), "a state index was written");
9162
    // The histories are last in the file: damage the last of them.
9163
    let mut bytes = fs::read(&index[0]).unwrap();
9164
    let last = bytes.len() - 1;
9165
    bytes[last] ^= 0x40;
9166
    fs::write(&index[0], &bytes).unwrap();
9167
9168
    let reads: Vec<_> = (0..6)
9169
        .map(|i| repo.file_at(&format!("f{i}.txt"), None))
9170
        .collect();
9171
    let damaged: Vec<String> = reads
9172
        .iter()
9173
        .filter_map(|r| r.as_ref().err().map(|e| e.to_string()))
9174
        .collect();
9175
    assert_eq!(damaged.len(), 1, "{damaged:?}");
9176
    assert!(
9177
        damaged[0].contains("state index was damaged")
9178
            && damaged[0].contains("run the command again"),
9179
        "{}",
9180
        damaged[0]
9181
    );
9182
    // Every file reads right again, from an index rebuilt from history.
9183
    for (i, w) in want.iter().enumerate() {
9184
        assert_eq!(&repo.file_at(&format!("f{i}.txt"), None).unwrap(), w);
9185
    }
9186
}
9187
9188
/// oxygen#95: a push longer than `push.batch-bytes` goes in parts, each
9189
/// objects alone and in dependency order, and the last moves the bookmark.
9190
/// The remote ends with every change and the same state, and says how each
9191
/// part went.
9192
#[test]
9193
fn a_long_push_goes_in_parts() {
9194
    hermetic();
9195
    let dir = tempfile::tempdir().unwrap();
9196
    let root = dir.path();
9197
    let origin = root.join("origin");
9198
    Repo::init_bare_unbound(&origin).unwrap();
9199
    let main = root.join("main");
9200
    let mut repo = Repo::init(&main).unwrap();
9201
    repo.config
9202
        .set("remote.origin.url", &origin.to_string_lossy())
9203
        .unwrap();
9204
    // One byte: every change is a part of its own.
9205
    repo.config.set("push.batch-bytes", "1").unwrap();
9206
    repo.save_config().unwrap();
9207
    for i in 0..6 {
9208
        write(
9209
            &main,
9210
            &format!("f{i}.txt"),
9211
            format!("file {i}\n").as_bytes(),
9212
        );
9213
        repo.commit(&format!("c{i}"), &[]).unwrap();
9214
    }
9215
    let mut parts = Vec::new();
9216
    let results = repo
9217
        .push_bookmark_with("origin", "main", false, &mut |m| parts.push(m.to_string()))
9218
        .unwrap();
9219
    assert!(
9220
        results.iter().any(|r| r.ok && r.name == "main"),
9221
        "{results:?}"
9222
    );
9223
    assert_eq!(parts.len(), 6, "{parts:?}");
9224
    assert_eq!(parts[0], "part 1 of 6: 1 changes");
9225
9226
    let remote = Repo::open(&origin).unwrap();
9227
    let heads = repo.bookmark_heads().unwrap();
9228
    assert_eq!(remote.bookmark_heads().unwrap(), heads);
9229
    assert_eq!(
9230
        remote.log_state(&heads).unwrap().len(),
9231
        repo.log_state(&heads).unwrap().len()
9232
    );
9233
    // A push of objects alone reports how it went, as `objects`.
9234
    let got = remote
9235
        .receive_push(Bundle::default(), vec![], None, vec![])
9236
        .unwrap();
9237
    assert_eq!(got.len(), 1);
9238
    assert!(got[0].ok && got[0].name == OBJECTS_RESULT, "{got:?}");
9239
}
9240
9241
/// oxygen#97: with `git.claim`, an import authors the importing identity's
9242
/// own commits (Git author email = its email, any case) with its key, and
9243
/// leaves anyone else's with the zero key; the history verifies as before.
9244
#[test]
9245
fn git_import_claims_your_own_commits() {
9246
    hermetic();
9247
    if std::process::Command::new("git")
9248
        .arg("--version")
9249
        .output()
9250
        .is_err()
9251
    {
9252
        eprintln!("git not installed; skipping");
9253
        return;
9254
    }
9255
    let dir = tempfile::tempdir().unwrap();
9256
    let root = dir.path();
9257
    let g = root.join("src.git");
9258
    fs::create_dir_all(&g).unwrap();
9259
    let git = |who: &str, args: &[&str]| {
9260
        let (name, email) = who.split_once(' ').unwrap();
9261
        let out = std::process::Command::new("git")
9262
            .arg("-C")
9263
            .arg(&g)
9264
            .args([
9265
                "-c",
9266
                &format!("user.name={name}"),
9267
                "-c",
9268
                &format!("user.email={email}"),
9269
                "-c",
9270
                "commit.gpgsign=false",
9271
            ])
9272
            .args(args)
9273
            .output()
9274
            .unwrap();
9275
        assert!(
9276
            out.status.success(),
9277
            "git {args:?}: {}",
9278
            String::from_utf8_lossy(&out.stderr)
9279
        );
9280
    };
9281
    git("Grace [email protected]", &["init", "-q", "-b", "main"]);
9282
    write(&g, "a.txt", b"a\n");
9283
    git("Grace [email protected]", &["add", "."]);
9284
    git("Grace [email protected]", &["commit", "-qm", "mine"]);
9285
    write(&g, "b.txt", b"b\n");
9286
    git("Ada [email protected]", &["add", "."]);
9287
    git("Ada [email protected]", &["commit", "-qm", "someone else's"]);
9288
9289
    let mut repo = Repo::init(&root.join("o")).unwrap();
9290
    let (key, _) = repo
9291
        .create_identity("Grace", "[email protected]", IdentityScope::Repo)
9292
        .unwrap();
9293
    repo.config.set("git.claim", "true").unwrap();
9294
    repo.save_config().unwrap();
9295
    let repo = Repo::open(&root.join("o")).unwrap();
9296
    repo.import_git(&g, "main").unwrap();
9297
    let v = repo.verify_git_import(&g, "main").unwrap();
9298
    assert!(v.mismatches.is_empty(), "{:?}", v.mismatches);
9299
    let heads = repo.bookmark_heads().unwrap();
9300
    let by_message: std::collections::HashMap<String, KeyId> = repo
9301
        .log_state(&heads)
9302
        .unwrap()
9303
        .into_iter()
9304
        .map(|e| {
9305
            (
9306
                e.change.message.lines().next().unwrap_or("").to_string(),
9307
                e.change.author,
9308
            )
9309
        })
9310
        .collect();
9311
    assert_eq!(by_message["mine"], key, "her own commit, any case of email");
9312
    assert_eq!(by_message["someone else's"], ObjectRef::ZERO, "not hers");
9313
}
9314
9315
/// oxygen#86: removing a remote removes all of it: every `remote.NAME.*`
9316
/// key (URL, token, CA), its tracking bookmarks, and nothing else.
9317
#[test]
9318
fn removing_a_remote_leaves_nothing_of_it() {
9319
    hermetic();
9320
    let dir = tempfile::tempdir().unwrap();
9321
    let origin = dir.path().join("origin");
9322
    Repo::init_bare_unbound(&origin).unwrap();
9323
    let main = dir.path().join("main");
9324
    let mut repo = Repo::init(&main).unwrap();
9325
    repo.config
9326
        .set("remote.origin.url", &origin.to_string_lossy())
9327
        .unwrap();
9328
    repo.config
9329
        .set("remote.origin.token", "secret-ish")
9330
        .unwrap();
9331
    repo.config
9332
        .set("remote.keep.url", &origin.to_string_lossy())
9333
        .unwrap();
9334
    repo.save_config().unwrap();
9335
    write(&main, "a.txt", b"a\n");
9336
    repo.commit("a", &[]).unwrap();
9337
    assert!(repo.push("origin", false).unwrap()[0].ok);
9338
    assert!(
9339
        repo.view().unwrap().remotes.contains_key("origin"),
9340
        "a tracking bookmark"
9341
    );
9342
9343
    repo.remove_remote("origin").unwrap();
9344
    let again = Repo::open(&main).unwrap();
9345
    assert!(
9346
        !again
9347
            .config
9348
            .repo_layer()
9349
            .keys()
9350
            .any(|k| k.starts_with("remote.origin.")),
9351
        "{:?}",
9352
        again.config.repo_layer()
9353
    );
9354
    assert!(!again.config.remotes.contains_key("origin"));
9355
    assert!(
9356
        !again.view().unwrap().remotes.contains_key("origin"),
9357
        "its tracking bookmarks go"
9358
    );
9359
    assert!(
9360
        again.config.remotes.contains_key("keep"),
9361
        "another remote stays"
9362
    );
9363
    let mut again = again;
9364
    assert!(
9365
        again.remove_remote("origin").is_err(),
9366
        "a second removal is refused"
9367
    );
9368
}
9369
9370
/// oxygenhub#126: a blob a host stored for itself (a job's artifact) is
9371
/// unreachable from history, so gc prunes it, unless the host names it:
9372
/// then it and its chunks stay, and it reads back whole.
9373
#[test]
9374
fn gc_keeps_the_blobs_a_host_names() {
9375
    hermetic();
9376
    let dir = tempfile::tempdir().unwrap();
9377
    let repo = Repo::init(dir.path()).unwrap();
9378
    write(dir.path(), "a.txt", b"a\n");
9379
    repo.commit("a", &[]).unwrap();
9380
    // Large enough to be several chunks.
9381
    let body: Vec<u8> = (0..400_000u32)
9382
        .flat_map(|i| (i.wrapping_mul(2654435761)).to_le_bytes())
9383
        .collect();
9384
    let kept = repo.store_blob(&body).unwrap();
9385
    let lost = repo.store_blob(b"an artifact nobody names").unwrap();
9386
    repo.gc_keeping(true, &[kept], &mut |_| {}).unwrap();
9387
    assert_eq!(repo.read_blob(&kept).unwrap(), body, "named: kept whole");
9388
    assert!(!repo.store().has(&lost), "not named: pruned");
9389
    repo.gc(true).unwrap();
9390
    assert!(!repo.store().has(&kept), "a plain gc prunes it");
9391
}
9392
9393
/// oxygen#99: undo in one workspace undoes that workspace's last command,
9394
/// never another workspace's, says what it undid, and goes further back
9395
/// when run again.
9396
#[test]
9397
fn undo_is_scoped_to_its_workspace() {
9398
    hermetic();
9399
    let dir = tempfile::tempdir().unwrap();
9400
    let root = dir.path().join("main");
9401
    let a = Repo::init(&root).unwrap();
9402
    write(&root, "base.txt", b"base\n");
9403
    let base = a.commit("base", &[]).unwrap();
9404
    a.bookmark_create("feature", None).unwrap();
9405
    let ws_dir = dir.path().join("ws");
9406
    let heads = a.resolve_heads("feature").unwrap();
9407
    let b = a
9408
        .workspace_add_on(&ws_dir, Some(&heads), Some("feature"))
9409
        .unwrap();
9410
9411
    // A commits on main, then B commits on feature: B's is the newest.
9412
    write(&root, "a.txt", b"a\n");
9413
    let ca = a.commit("from a", &[]).unwrap();
9414
    write(&ws_dir, "b.txt", b"b\n");
9415
    let cb = b.commit("from b", &[]).unwrap();
9416
9417
    // A's undo undoes A's commit and leaves B's.
9418
    let u = a.undo().unwrap();
9419
    assert_eq!(u.command, "oxy commit -m \"from a\"");
9420
    assert_eq!(u.others_kept, 1, "B's newer commit is left");
9421
    assert!(!u.changes.is_empty());
9422
    let view = a.view().unwrap();
9423
    // (Independent changes commute, so a bookmark's heads may hold base too.)
9424
    assert_eq!(a.heads_of(&view, "main").unwrap(), vec![base]);
9425
    assert!(
9426
        a.heads_of(&view, "feature").unwrap().contains(&cb),
9427
        "B's commit stands"
9428
    );
9429
    assert!(
9430
        a.store().get_change(&ca).is_ok(),
9431
        "the change itself is still in the store"
9432
    );
9433
    // A's working copy was clean, so its files followed; B's are untouched.
9434
    assert!(!root.join("a.txt").exists());
9435
    assert!(a.snapshot("oxy status").unwrap().statuses.is_empty());
9436
    assert!(ws_dir.join("b.txt").exists());
9437
9438
    // B's undo still finds B's own commit, under A's undo.
9439
    let u = b.undo().unwrap();
9440
    assert_eq!(u.command, "oxy commit -m \"from b\"");
9441
    assert!(!b
9442
        .heads_of(&b.view().unwrap(), "feature")
9443
        .unwrap()
9444
        .contains(&cb));
9445
    assert_eq!(
9446
        a.heads_of(&a.view().unwrap(), "main").unwrap(),
9447
        vec![base],
9448
        "A's undo stands"
9449
    );
9450
9451
    // A's next undo goes past the commit it already undid, to adding B's
9452
    // workspace: refused, since B has worked there since.
9453
    let e = a.undo().unwrap_err().to_string();
9454
    assert!(e.contains("the workspace at") && e.contains("ws"), "{e}");
9455
}
9456
9457
/// oxygen#99: two workspaces on one bookmark: an undo takes back only its
9458
/// own commit's head, and the other workspace's head stays.
9459
#[test]
9460
fn undo_on_a_shared_bookmark_keeps_the_other_workspaces_head() {
9461
    hermetic();
9462
    let dir = tempfile::tempdir().unwrap();
9463
    let root = dir.path().join("main");
9464
    let a = Repo::init(&root).unwrap();
9465
    write(&root, "base.txt", b"base\n");
9466
    a.commit("base", &[]).unwrap();
9467
    let ws_dir = dir.path().join("ws");
9468
    let b = a.workspace_add(&ws_dir, None).unwrap();
9469
    write(&root, "a.txt", b"a\n");
9470
    let ca = a.commit("from a", &[]).unwrap();
9471
    write(&ws_dir, "b.txt", b"b\n");
9472
    let cb = b.commit("from b", &[]).unwrap();
9473
    let u = a.undo().unwrap();
9474
    assert_eq!(u.command, "oxy commit -m \"from a\"");
9475
    let heads = a.heads_of(&a.view().unwrap(), "main").unwrap();
9476
    assert!(heads.contains(&cb) && !heads.contains(&ca), "{heads:?}");
9477
}
9478
9479
/// oxygen#99: an undo that would also take back what another workspace
9480
/// did since to the same bookmark is refused, naming it.
9481
#[test]
9482
fn undo_refuses_to_take_back_another_workspaces_work() {
9483
    hermetic();
9484
    let dir = tempfile::tempdir().unwrap();
9485
    let root = dir.path().join("main");
9486
    let a = Repo::init(&root).unwrap();
9487
    write(&root, "base.txt", b"base\n");
9488
    a.commit("base", &[]).unwrap();
9489
    let ws_dir = dir.path().join("ws");
9490
    let b = a.workspace_add(&ws_dir, None).unwrap();
9491
    // Both on main: A commits, then B builds on it, editing A's file.
9492
    write(&root, "a.txt", b"a\n");
9493
    a.commit("from a", &[]).unwrap();
9494
    b.refresh().unwrap();
9495
    let heads = b.resolve_heads("main").unwrap();
9496
    b.checkout(&heads, false, "oxy checkout").unwrap();
9497
    write(&ws_dir, "a.txt", b"a, then b\n");
9498
    b.commit("from b", &[]).unwrap();
9499
    let e = a.undo().unwrap_err().to_string();
9500
    assert!(
9501
        e.contains("bookmark main") && e.contains("builds on"),
9502
        "{e}"
9503
    );
9504
    assert!(e.contains("oxy op restore"), "{e}");
9505
}
9506
9507
/// oxygen#99: undoing a commit that was already pushed says so: the remote
9508
/// still has it.
9509
#[test]
9510
fn undo_says_when_the_commit_was_pushed() {
9511
    hermetic();
9512
    let dir = tempfile::tempdir().unwrap();
9513
    let root = dir.path();
9514
    Repo::init(&root.join("origin")).unwrap();
9515
    let url = root.join("origin").to_string_lossy().to_string();
9516
    let repo = Repo::clone(&url, &root.join("work"))
9517
        .unwrap()
9518
        .with_home(root.join("home"));
9519
    write(&root.join("work"), "a.txt", b"a\n");
9520
    repo.commit("a", &[]).unwrap();
9521
    assert!(repo.push("origin", false).unwrap()[0].ok);
9522
    // The push itself is passed over: the remote keeps what it was sent.
9523
    let u = repo.undo().unwrap();
9524
    assert_eq!(u.command, "oxy commit -m \"a\"");
9525
    assert_eq!(u.pushed, vec![("main".to_string(), "origin".to_string())]);
9526
}
9527
9528
/// oxygen#98: a new untracked file over snapshot.max-new-file-size is left
9529
/// out of the snapshot and named; tracked files and files already in the
9530
/// working copy are not.
9531
#[test]
9532
fn large_new_files_are_left_out_of_snapshots() {
9533
    hermetic();
9534
    let dir = tempfile::tempdir().unwrap();
9535
    let root = dir.path();
9536
    let mut repo = Repo::init(root).unwrap();
9537
    repo.config.max_new_file = 1024;
9538
    write(root, "small.txt", b"small\n");
9539
    write(root, "big.bin", &vec![0u8; 4096]);
9540
    let s = repo.snapshot("oxy status").unwrap();
9541
    let paths: Vec<_> = s.statuses.iter().map(|p| p.path.as_str()).collect();
9542
    assert_eq!(paths, ["small.txt"]);
9543
    assert_eq!(repo.skipped_large(), vec![("big.bin".to_string(), 4096)]);
9544
    repo.commit("small", &[]).unwrap();
9545
9546
    // A tracked file may grow past the limit.
9547
    write(root, "small.txt", &vec![b'x'; 4096]);
9548
    let s = repo.snapshot("oxy status").unwrap();
9549
    assert!(s.statuses.iter().any(|p| p.path == "small.txt"));
9550
    // With no limit the big file is taken in, and stays once it is.
9551
    repo.config.max_new_file = 0;
9552
    let s = repo.snapshot("oxy status").unwrap();
9553
    assert!(s.statuses.iter().any(|p| p.path == "big.bin"));
9554
    repo.config.max_new_file = 1024;
9555
    let s = repo.snapshot("oxy status").unwrap();
9556
    assert!(
9557
        s.statuses.iter().any(|p| p.path == "big.bin"),
9558
        "already in the working copy"
9559
    );
9560
    assert!(repo.skipped_large().is_empty());
9561
}
9562
9563
/// oxygen#98: a file only a past working-copy snapshot held is pruned once
9564
/// snapshots expire, and kept while they have not.
9565
#[test]
9566
fn gc_prunes_what_only_expired_snapshots_held() {
9567
    hermetic();
9568
    let dir = tempfile::tempdir().unwrap();
9569
    let root = dir.path();
9570
    let mut repo = Repo::init(root).unwrap();
9571
    repo.config.gc_grace_days = 0;
9572
    write(root, "a.txt", b"a\n");
9573
    repo.commit("a", &[]).unwrap();
9574
    let image: Vec<u8> = (0..200_000u32).map(|i| (i % 7) as u8).collect();
9575
    write(root, "image.tar", &image);
9576
    repo.snapshot("oxy status").unwrap();
9577
    std::fs::remove_file(root.join("image.tar")).unwrap();
9578
    repo.snapshot("oxy status").unwrap();
9579
    let blob = Repo::blob_ref(&image);
9580
    assert!(repo.store().has(&blob));
9581
    repo.gc(true).unwrap();
9582
    assert!(repo.store().has(&blob), "a recent snapshot keeps it");
9583
    repo.config.snapshot_retention_days = 0;
9584
    repo.gc(true).unwrap();
9585
    assert!(!repo.store().has(&blob), "an expired snapshot does not");
9586
    assert_eq!(
9587
        repo.file_at("a.txt", None).unwrap(),
9588
        b"a\n",
9589
        "committed files stay"
9590
    );
9591
}
9592
9593
/// oxygen#100: uncommitted work byte-for-byte what the bookmark switched to
9594
/// already has is no conflict: the switch goes through, nothing is lost,
9595
/// and other carried work still comes along.
9596
#[test]
9597
fn carrying_work_the_target_already_has_is_no_conflict() {
9598
    hermetic();
9599
    let dir = tempfile::tempdir().unwrap();
9600
    let root = dir.path();
9601
    let mut repo = Repo::init(root).unwrap();
9602
    write(root, "a.txt", b"one\n");
9603
    write(root, "b.txt", b"b\n");
9604
    repo.commit("one", &[]).unwrap();
9605
    repo.bookmark_create("landed", None).unwrap();
9606
    // On landed, a.txt becomes "two" (as a proposal landing would).
9607
    repo.bookmark_switch("landed", false).unwrap();
9608
    write(root, "a.txt", b"two\n");
9609
    repo.commit("two", &[]).unwrap();
9610
    repo.bookmark_switch("main", false).unwrap();
9611
    assert_eq!(std::fs::read(root.join("a.txt")).unwrap(), b"one\n");
9612
    // The same edit, uncommitted, on main; and another edit besides.
9613
    write(root, "a.txt", b"two\n");
9614
    write(root, "b.txt", b"b, edited\n");
9615
    let (_, carried) = repo.bookmark_switch_carry("landed").unwrap();
9616
    assert_eq!(
9617
        carried,
9618
        vec!["b.txt".to_string()],
9619
        "only the work landed lacks is carried"
9620
    );
9621
    assert_eq!(std::fs::read(root.join("a.txt")).unwrap(), b"two\n");
9622
    assert_eq!(std::fs::read(root.join("b.txt")).unwrap(), b"b, edited\n");
9623
    let s = repo.snapshot("oxy status").unwrap();
9624
    let paths: Vec<_> = s.statuses.iter().map(|p| p.path.as_str()).collect();
9625
    assert_eq!(paths, ["b.txt"]);
9626
9627
    // A real difference is still refused.
9628
    repo.bookmark_switch("main", true).unwrap();
9629
    write(root, "a.txt", b"three\n");
9630
    let e = repo
9631
        .bookmark_switch_carry("landed")
9632
        .unwrap_err()
9633
        .to_string();
9634
    assert!(e.contains("a.txt") && e.contains("--discard"), "{e}");
9635
}
9636
9637
/// oxygen#103: a full change hash as `--json` prints it, without `#`,
9638
/// resolves, so JSON output feeds back into commands.
9639
#[test]
9640
fn a_full_hash_resolves_without_its_hash_sign() {
9641
    hermetic();
9642
    let dir = tempfile::tempdir().unwrap();
9643
    let root = dir.path();
9644
    let repo = Repo::init(root).unwrap();
9645
    write(root, "a.txt", b"a\n");
9646
    let h = repo.commit("a", &[]).unwrap();
9647
    assert_eq!(repo.resolve_change(&h.to_hex()).unwrap(), h);
9648
    assert_eq!(repo.resolve_change(&format!("#{}", h.to_hex())).unwrap(), h);
9649
    assert!(repo
9650
        .resolve_change(&"0".repeat(64))
9651
        .unwrap_err()
9652
        .to_string()
9653
        .contains("no change matches"));
9654
}
9655
9656
#[test]
9657
fn a_pin_change_moves_only_the_pin() {
9658
    hermetic();
9659
    let dir = tempfile::tempdir().unwrap();
9660
    let root = dir.path();
9661
    let _lib_origin = Repo::init(&root.join("lib-origin")).unwrap();
9662
    let lib_url = root.join("lib-origin").to_string_lossy().to_string();
9663
    let lib = Repo::clone(&lib_url, &root.join("lib"))
9664
        .unwrap()
9665
        .with_home(root.join("home"));
9666
    write(&root.join("lib"), "lib.txt", b"v1\n");
9667
    lib.commit("lib v1", &[]).unwrap();
9668
    assert!(lib.push("origin", false).unwrap()[0].ok);
9669
    let _app_origin = Repo::init(&root.join("app-origin")).unwrap();
9670
    let app_dir = root.join("app");
9671
    let app = Repo::clone(&root.join("app-origin").to_string_lossy(), &app_dir)
9672
        .unwrap()
9673
        .with_home(root.join("home"));
9674
    write(&app_dir, "main.txt", b"app\n");
9675
    let pin1 = app.submodule_add(&lib_url, "libs/lib", None).unwrap();
9676
    let a1 = app.commit("app with lib", &[]).unwrap();
9677
    // The library moves on.
9678
    write(&root.join("lib"), "more.txt", b"v2\n");
9679
    let l2 = lib.commit("lib v2", &[]).unwrap();
9680
    let crate::subrepo::Pin::Oxy { repo, bookmark, .. } = pin1 else {
9681
        panic!("an Oxygen pin")
9682
    };
9683
    let pin2 = crate::subrepo::Pin::Oxy {
9684
        repo,
9685
        heads: vec![l2],
9686
        bookmark,
9687
    };
9688
    let author = app.store().get_change(&a1).unwrap().author;
9689
    let change = app
9690
        .build_pin_change(&[a1], "libs/lib", &pin2, "Move lib to v2", author)
9691
        .unwrap();
9692
    let mut state = app.load_state(&[a1]).unwrap();
9693
    state.add(change).unwrap();
9694
    let files = state.materialize().files;
9695
    assert_eq!(files["libs/lib"].kind, NodeKind::Subrepo);
9696
    let FileContent::Opaque { blobs } = &files["libs/lib"].content else {
9697
        panic!("a pin is opaque")
9698
    };
9699
    let read = crate::subrepo::Pin::decode(&app.read_blob(&blobs[0]).unwrap()).unwrap();
9700
    assert_eq!(read, pin2, "the new pin");
9701
    assert!(
9702
        matches!(&files["main.txt"].content, FileContent::Text { bytes, .. } if bytes.as_slice() == b"app\n"),
9703
        "nothing else changes"
9704
    );
9705
    // Only a subrepo's pin can be moved this way.
9706
    let e = app.build_pin_change(&[a1], "main.txt", &pin2, "x", author);
9707
    assert!(format!("{:?}", e.unwrap_err()).contains("not a subrepo"));
9708
    let e = app.build_pin_change(&[a1], "libs/none", &pin2, "x", author);
9709
    assert!(format!("{:?}", e.unwrap_err()).contains("does not exist"));
9710
}
9711
9712
/// oxygenhub#249: a handle reads the operation head once and keeps it,
9713
/// so one command or request never mixes two heads; another handle's
9714
/// operation shows only after `refresh`. Its own operations move it, and
9715
/// one recorded from the head it kept merges with what landed since, as
9716
/// any concurrent operation does.
9717
#[test]
9718
fn one_handle_keeps_one_head_until_it_refreshes() {
9719
    hermetic();
9720
    let dir = tempfile::tempdir().unwrap();
9721
    let root = dir.path();
9722
    let writer = Repo::init(root).unwrap();
9723
    write(root, "a.txt", b"one\n");
9724
    let h1 = writer.commit("one", &[]).unwrap();
9725
    let reader = Repo::open(root).unwrap();
9726
    let before = reader.view().unwrap();
9727
    assert_eq!(reader.bookmark_heads().unwrap(), vec![h1]);
9728
    write(root, "a.txt", b"two\n");
9729
    let h2 = writer.commit("two", &[]).unwrap();
9730
    assert_eq!(
9731
        writer.bookmark_heads().unwrap(),
9732
        vec![h2],
9733
        "its own operation"
9734
    );
9735
    assert_eq!(reader.view().unwrap(), before, "the head it read first");
9736
    assert_eq!(reader.bookmark_heads().unwrap(), vec![h1]);
9737
    reader.refresh().unwrap();
9738
    assert_eq!(reader.bookmark_heads().unwrap(), vec![h2]);
9739
9740
    // A handle recording from an older head merges with the newer one.
9741
    let stale = Repo::open(root).unwrap();
9742
    assert_eq!(stale.bookmark_heads().unwrap(), vec![h2]);
9743
    write(root, "a.txt", b"three\n");
9744
    let h3 = writer.commit("three", &[]).unwrap();
9745
    stale.bookmark_create("feature", Some(&[h1])).unwrap();
9746
    let view = stale.view().unwrap();
9747
    assert!(view.bookmarks.contains_key("feature"));
9748
    assert_eq!(
9749
        stale.bookmark_heads().unwrap(),
9750
        vec![h3],
9751
        "merged, not lost"
9752
    );
9753
    let fresh = Repo::open(root).unwrap();
9754
    assert_eq!(fresh.view().unwrap(), view);
9755
}
9756
9757
/// oxygenhub#249 over a store (a bucket's compare-and-swap): the same.
9758
#[test]
9759
fn over_a_store_one_handle_keeps_one_head() {
9760
    hermetic();
9761
    let backend = std::sync::Arc::new(crate::strata::MemoryStore::new());
9762
    crate::store::TEST_BACKEND.with(|t| *t.borrow_mut() = Some(backend.clone()));
9763
    let dir = tempfile::tempdir().unwrap();
9764
    let a = Repo::init(dir.path()).unwrap();
9765
    let (h0, _) = a.head_op().unwrap();
9766
    let b = Repo::open(dir.path()).unwrap();
9767
    assert_eq!(b.head_op().unwrap().0, h0);
9768
    let state = a.store.put_state(&StateObject::new(vec![])).unwrap();
9769
    let mut view = a.view().unwrap();
9770
    view.bookmarks.insert("x".into(), state);
9771
    let r = a.record_op(&[h0], "bookmark x", view).unwrap();
9772
    assert_eq!(a.head_op().unwrap().0, r);
9773
    assert_eq!(b.head_op().unwrap().0, h0, "b keeps its head");
9774
    b.refresh().unwrap();
9775
    assert_eq!(b.head_op().unwrap().0, r);
9776
    crate::store::TEST_BACKEND.with(|t| *t.borrow_mut() = None);
9777
}
9778
9779
/// oxygenhub#249: gc retires what it repacks rather than deleting it; a
9780
/// reader opened before reads on, then and after the next gc deletes the
9781
/// retired files once their hour is up. Younger ones are kept.
9782
#[test]
9783
fn gc_retires_and_a_later_gc_deletes_after_the_hour() {
9784
    hermetic();
9785
    let dir = tempfile::tempdir().unwrap();
9786
    let root = dir.path();
9787
    let repo = Repo::init(root).unwrap();
9788
    let mut heads = Vec::new();
9789
    for i in 0..4 {
9790
        write(root, &format!("f{i}.txt"), format!("{i}\n").as_bytes());
9791
        heads.push(repo.commit(&format!("c{i}"), &[]).unwrap());
9792
    }
9793
    let reader = Repo::open(root).unwrap();
9794
    assert_eq!(reader.log().unwrap().len(), 5);
9795
    let r = repo.gc(true).unwrap();
9796
    assert_eq!(r.retired, crate::store::RetiredReport::default());
9797
    assert_eq!(repo.store().loose_count().unwrap(), 0);
9798
    assert_eq!(reader.log().unwrap().len(), 5, "read on from what it had");
9799
    // Nothing is an hour old yet: a gc keeps it all.
9800
    let r = repo.gc(true).unwrap();
9801
    assert_eq!((r.retired.packs, r.retired.loose), (0, 0));
9802
    assert!(r.retired.kept > 0, "{r:?}");
9803
    write(root, "f9.txt", b"9\n");
9804
    heads.push(repo.commit("c9", &[]).unwrap());
9805
    crate::store::reader_tests::age_retired(
9806
        repo.store(),
9807
        crate::store::RETIRED_FOR + std::time::Duration::from_secs(60),
9808
    );
9809
    let r = repo.gc(true).unwrap();
9810
    assert!(r.retired.packs >= 1 && r.retired.loose > 0, "{r:?}");
9811
    assert_eq!(r.retired.kept, 0, "{r:?}");
9812
    let r = repo.gc(true).unwrap();
9813
    assert_eq!((r.retired.packs, r.retired.loose), (0, 0));
9814
    assert!(r.retired.kept > 0, "what the last gc retired is young");
9815
    // The reader opened before all of it still reads everything, from
9816
    // the packs it finds when what it loaded is gone.
9817
    assert_eq!(reader.log().unwrap().len(), 5);
9818
    for h in &heads[..4] {
9819
        reader.store().get_change(h).unwrap();
9820
    }
9821
    reader.refresh().unwrap();
9822
    assert_eq!(reader.log().unwrap().len(), 6);
9823
    let fresh = Repo::open(root).unwrap();
9824
    assert_eq!(
9825
        fresh.store().pack_count(),
9826
        1,
9827
        "retired packs are not loaded"
9828
    );
9829
}
9830
9831
/// oxygenhub#249: a repository opens when its store's pack listing names
9832
/// an index that is not there (deleted between the listing and the read).
9833
#[test]
9834
fn a_repository_opens_when_a_listed_index_is_gone() {
9835
    hermetic();
9836
    let backend = crate::store::reader_tests::racing(true);
9837
    let dyn_backend: std::sync::Arc<crate::store::Backend> = backend.clone();
9838
    crate::store::TEST_BACKEND.with(|t| *t.borrow_mut() = Some(dyn_backend));
9839
    let dir = tempfile::tempdir().unwrap();
9840
    let repo = Repo::init(dir.path()).unwrap();
9841
    write(dir.path(), "a.txt", b"a\n");
9842
    let h = repo.commit("a", &[]).unwrap();
9843
    repo.gc(true).unwrap();
9844
    let again = Repo::open(dir.path()).unwrap();
9845
    assert_eq!(again.store().pack_count(), 1);
9846
    assert_eq!(again.bookmark_heads().unwrap(), vec![h]);
9847
    // And when one is deleted between the listing and the read: a copy of
9848
    // the live pack, whose index goes as the store opens.
9849
    use crate::strata::Store as _;
9850
    let idx = backend
9851
        .list("pack-")
9852
        .unwrap()
9853
        .into_iter()
9854
        .map(|e| e.key)
9855
        .find(|k| k.ends_with(".idx") && k != "pack-0000.idx")
9856
        .unwrap();
9857
    let stem = idx.trim_end_matches(".idx");
9858
    for ext in ["pack", "idx"] {
9859
        let bytes = backend.get(&format!("{stem}.{ext}")).unwrap();
9860
        backend
9861
            .put_new(&format!("pack-copy.{ext}"), &bytes)
9862
            .unwrap();
9863
    }
9864
    *backend.doomed.lock().unwrap() = Some("pack-copy.idx".into());
9865
    let again = Repo::open(dir.path()).unwrap();
9866
    assert_eq!(again.store().pack_count(), 1);
9867
    assert_eq!(again.bookmark_heads().unwrap(), vec![h]);
9868
    assert!(!backend.has("pack-copy.idx").unwrap());
9869
    crate::store::TEST_BACKEND.with(|t| *t.borrow_mut() = None);
9870
}