OXYGENHUB
# 6f06d9f912b4 oxygen / crates / oxy-core / src / repo / tests.rs
343.0 KiB · Rust · last changed Readers never wait: one head per handle, retry on a miss, retire before deleting 18 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
/// Keyless step 5 (oxygenhub#241): an agent's fresh key, certified for a
1138
/// subject the author granted, seals changes in the author's name; with
1139
/// no grant, a stranger's, or one that had ended, it is neither the
1140
/// author nor a delegate.
1141
#[test]
1142
fn a_certified_key_acts_for_its_author_under_a_grant() {
1143
    use crate::cert::{Certificate, Grant, SignedCertificate, SignedGrant};
1144
    use crate::identity::{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
    let (ada, _) = a
1154
        .create_identity("Ada", "[email protected]", IdentityScope::User)
1155
        .unwrap();
1156
    write(&root.join("a"), "a.txt", b"a\n");
1157
    a.commit("a", &[]).unwrap();
1158
    a.policy_init().unwrap();
1159
    assert!(a.push("origin", false).unwrap().iter().all(|r| r.ok));
1160
    let hub_sk = SecretKey::generate();
1161
    let hub = hub_sk.identity("hub", "[email protected]", 1);
1162
    a.policy_grant_subject(
1163
        "agent:claude@ada",
1164
        hub.clone(),
1165
        Scope::CHANGES | Scope::REFS,
1166
        None,
1167
    )
1168
    .unwrap();
1169
    assert!(a.push("origin", false).unwrap().iter().all(|r| r.ok));
1170
    let (_, ada_sk) = a.secret_key().unwrap().unwrap();
1171
    let ada_id = a.identity(&ada).unwrap();
1172
1173
    let now = Hlc::now().wall_ms;
1174
    let grant = |by: &Identity, sk: &SecretKey, from: u64, to: u64| {
1175
        SignedGrant::sign(
1176
            Grant {
1177
                grantor: by.hash(),
1178
                subject: "agent:claude@ada".into(),
1179
                issuer: hub.hash(),
1180
                scope: Scope::CHANGES | Scope::SEAL,
1181
                not_before: from,
1182
                expires: to,
1183
            },
1184
            by,
1185
            sk,
1186
        )
1187
    };
1188
    // Ada's work as an agent runs it: Ada the author, a fresh key the hub
1189
    // certified (with `g` inside) the signer.
1190
    let agent = |name: &str, g: Option<SignedGrant>| {
1191
        let mut r = Repo::clone(&url, &root.join(name))
1192
            .unwrap()
1193
            .with_home(root.join(format!("home-{name}")));
1194
        let (key, id) = r
1195
            .create_identity(name, "[email protected]", IdentityScope::User)
1196
            .unwrap();
1197
        r.set_user_config("author.key", &ada.to_hex()).unwrap();
1198
        r.set_user_config("author.signer", &key.to_hex()).unwrap();
1199
        let cert = SignedCertificate::sign(
1200
            Certificate {
1201
                key: id,
1202
                issuer: hub.hash(),
1203
                subject: "agent:claude@ada".into(),
1204
                claims: vec![],
1205
                scope: Scope::CHANGES | Scope::REFS | Scope::SEAL,
1206
                not_before: now - 60_000,
1207
                expires: now + 600_000,
1208
                grant: g,
1209
            },
1210
            &hub,
1211
            &hub_sk,
1212
        );
1213
        r.store().put_identity(&hub).unwrap();
1214
        r.store().put_certificate(&cert).unwrap();
1215
        write(&root.join(name), &format!("{name}.txt"), b"agent work\n");
1216
        let h = r.commit("work", &[]).unwrap();
1217
        assert_eq!(r.store().get_change_meta(&h).unwrap().author, ada);
1218
        (r, key, h)
1219
    };
1220
1221
    let (claude, key, h) = agent(
1222
        "claude",
1223
        Some(grant(&ada_id, &ada_sk, now - 60_000, now + 86_400_000)),
1224
    );
1225
    let r = claude.push("origin", false).unwrap();
1226
    assert!(r.iter().all(|x| x.ok), "{r:?}");
1227
    let host = Repo::open(&root.join("origin")).unwrap();
1228
    assert!(
1229
        matches!(
1230
            host.authenticate_change(&h).unwrap(),
1231
            SignatureStatus::Valid { key: k, sealed: true, name, .. } if k == key && name == "agent:claude@ada"
1232
        ),
1233
        "named by its certificate's subject"
1234
    );
1235
    a.pull("origin").unwrap();
1236
    assert!(matches!(
1237
        a.authenticate_change(&h).unwrap(),
1238
        SignatureStatus::Valid { key: k, .. } if k == key
1239
    ));
1240
1241
    let (none, _, _) = agent("none", None);
1242
    let r = none.push("origin", false).unwrap();
1243
    assert!(r.iter().all(|x| !x.ok), "no grant: {r:?}");
1244
    let mallory_sk = SecretKey::generate();
1245
    let mallory = mallory_sk.identity("Mallory", "[email protected]", 1);
1246
    let (stranger, _, _) = agent(
1247
        "stranger",
1248
        Some(grant(&mallory, &mallory_sk, now - 60_000, now + 600_000)),
1249
    );
1250
    let r = stranger.push("origin", false).unwrap();
1251
    assert!(r.iter().all(|x| !x.ok), "a stranger's grant: {r:?}");
1252
    let (ended, _, eh) = agent(
1253
        "ended",
1254
        Some(grant(&ada_id, &ada_sk, now - 7_200_000, now - 3_600_000)),
1255
    );
1256
    let r = ended.push("origin", false).unwrap();
1257
    assert!(r.iter().all(|x| !x.ok), "an ended grant: {r:?}");
1258
    assert!(matches!(
1259
        ended.authenticate_change(&eh).unwrap(),
1260
        SignatureStatus::Invalid(e) if e.contains("grant did not cover")
1261
    ));
1262
}
1263
1264
#[test]
1265
fn trust_policy_governs_pushes_and_fetches() {
1266
    hermetic();
1267
    let dir = tempfile::tempdir().unwrap();
1268
    let root = dir.path();
1269
    let origin = Repo::init(&root.join("origin")).unwrap();
1270
    let url = root.join("origin").to_string_lossy().to_string();
1271
1272
    // A is the root. Before the policy, an unsigned push from B is fine.
1273
    let mut a = Repo::clone(&url, &root.join("a"))
1274
        .unwrap()
1275
        .with_home(root.join("home-a"));
1276
    let (key_a, _) = a
1277
        .create_identity("Ada", "[email protected]", IdentityScope::User)
1278
        .unwrap();
1279
    let mut b = Repo::clone(&url, &root.join("b"))
1280
        .unwrap()
1281
        .with_home(root.join("home-b"));
1282
    write(&root.join("b"), "b.txt", b"b\n");
1283
    b.commit("unsigned before policy", &[]).unwrap();
1284
    assert!(b.push("origin", false).unwrap()[0].ok);
1285
    origin.refresh().unwrap();
1286
1287
    // A creates the policy and pushes it; origin now enforces it.
1288
    write(&root.join("a"), "a.txt", b"a\n");
1289
    a.commit("a", &[]).unwrap();
1290
    let sp = a.policy_init().unwrap();
1291
    assert_eq!(sp.policy.serial, 1);
1292
    a.pull("origin").unwrap();
1293
    let results = a.push("origin", false).unwrap();
1294
    origin.refresh().unwrap();
1295
    assert!(results.iter().all(|r| r.ok), "{results:?}");
1296
    assert_eq!(origin.current_policy().unwrap().unwrap().1.policy.serial, 1);
1297
1298
    // B pulls the policy. Without an identity B cannot push at all.
1299
    b.pull("origin").unwrap();
1300
    assert!(
1301
        b.current_policy().unwrap().is_some(),
1302
        "the policy arrived with the fetch"
1303
    );
1304
    assert!(b.push("origin", false).is_err());
1305
    // With an identity the policy does not list, the push is rejected by origin.
1306
    let (key_b, id_b) = b
1307
        .create_identity("Bob", "[email protected]", IdentityScope::User)
1308
        .unwrap();
1309
    write(&root.join("b"), "b.txt", b"b2\n");
1310
    let h_b2 = b.commit("b2 as Bob", &[]).unwrap();
1311
    assert_eq!(b.store().get_change(&h_b2).unwrap().author, key_b);
1312
    let r = b.push("origin", false).unwrap();
1313
    origin.refresh().unwrap();
1314
    assert!(
1315
        !r[0].ok && r[0].reason.contains("may not update"),
1316
        "{:?}",
1317
        r
1318
    );
1319
1320
    // A grants B (identity handed over as a file) and publishes the policy.
1321
    let sp = a.policy_grant(id_b.clone(), None).unwrap();
1322
    assert_eq!(sp.policy.serial, 2);
1323
    let r = a.push("origin", false).unwrap();
1324
    origin.refresh().unwrap();
1325
    assert!(r.iter().any(|x| x.name == "policy" && x.ok), "{r:?}");
1326
    // B must fetch the new policy before pushing.
1327
    assert!(b
1328
        .push("origin", false)
1329
        .unwrap_or_else(|e| vec![RefResult {
1330
            name: "main".into(),
1331
            ok: false,
1332
            reason: e.to_string()
1333
        }])
1334
        .iter()
1335
        .all(|x| !x.ok));
1336
    b.pull("origin").unwrap();
1337
    assert_eq!(b.current_policy().unwrap().unwrap().1.policy.serial, 2);
1338
    let r = b.push("origin", false).unwrap();
1339
    origin.refresh().unwrap();
1340
    assert!(r[0].ok, "{:?}", r);
1341
    // Origin verified B's change under the policy.
1342
    let heads = origin.bookmark_heads().unwrap();
1343
    for h in &heads {
1344
        let c = origin.store().get_change(h).unwrap();
1345
        if c.author == key_b {
1346
            origin
1347
                .change_allowed(
1348
                    h,
1349
                    &origin.current_policy().unwrap().unwrap().1.policy,
1350
                    "main",
1351
                )
1352
                .unwrap();
1353
        }
1354
    }
1355
1356
    // A policy signed by a non-root (B) is refused, as is a replayed serial.
1357
    let mut forged = b.current_policy().unwrap().unwrap().1.policy.clone();
1358
    forged.serial = 3;
1359
    forged.roots = vec![key_b];
1360
    let fh = forged.hash();
1361
    let (_, sk_b) = b.secret_key().unwrap().unwrap();
1362
    let forged = SignedPolicy {
1363
        policy: forged,
1364
        sigs: vec![sk_b.sign(Domain::Policy, &key_b, &fh)],
1365
    };
1366
    let r = origin
1367
        .receive_push(Bundle::default(), vec![], Some(forged), vec![])
1368
        .unwrap();
1369
    assert!(!r[0].ok && r[0].reason.contains("root"), "{:?}", r);
1370
    let stale = a.current_policy().unwrap().unwrap().1;
1371
    let mut old = stale.clone();
1372
    old.policy.serial = 1;
1373
    let r = origin
1374
        .receive_push(Bundle::default(), vec![], Some(old), vec![])
1375
        .unwrap();
1376
    assert!(!r[0].ok && r[0].reason.contains("serial"), "{:?}", r);
1377
1378
    // A revokes B; after B pulls the policy, B's pushes are refused again.
1379
    a.pull("origin").unwrap();
1380
    a.policy_revoke(&key_b).unwrap();
1381
    let r = a.push("origin", false).unwrap();
1382
    origin.refresh().unwrap();
1383
    assert!(r.iter().any(|x| x.name == "policy" && x.ok), "{r:?}");
1384
    b.pull("origin").unwrap();
1385
    write(&root.join("b"), "b.txt", b"b3\n");
1386
    b.commit("b3", &[]).unwrap();
1387
    let r = b.push("origin", false).unwrap();
1388
    origin.refresh().unwrap();
1389
    assert!(!r[0].ok, "{:?}", r);
1390
1391
    // A clone by a third party receives and verifies everything.
1392
    let c = Repo::clone(&url, &root.join("c"))
1393
        .unwrap()
1394
        .with_home(root.join("home-c"));
1395
    assert_eq!(c.current_policy().unwrap().unwrap().1.policy.serial, 3);
1396
    assert!(c
1397
        .current_policy()
1398
        .unwrap()
1399
        .unwrap()
1400
        .1
1401
        .policy
1402
        .roots
1403
        .contains(&key_a));
1404
    assert!(!c.snapshot("status").unwrap().changed);
1405
}
1406
1407
/// oxygen#66: a gc says what it is doing, phase by phase.
1408
#[test]
1409
fn gc_reports_its_phases() {
1410
    hermetic();
1411
    let dir = tempfile::tempdir().unwrap();
1412
    let repo = Repo::init(dir.path()).unwrap();
1413
    for i in 0..3 {
1414
        write(
1415
            dir.path(),
1416
            &format!("f{i}.txt"),
1417
            format!("{i}\n").as_bytes(),
1418
        );
1419
        repo.commit(&format!("c{i}"), &[]).unwrap();
1420
    }
1421
    let mut phases = Vec::new();
1422
    repo.gc_with(true, &mut |p| phases.push(p.to_string()))
1423
        .unwrap();
1424
    assert_eq!(phases[0], "finding what is reachable", "{phases:?}");
1425
    assert!(
1426
        phases.iter().any(|p| p.starts_with("pruning")),
1427
        "{phases:?}"
1428
    );
1429
    assert!(
1430
        phases.iter().any(|p| p.starts_with("packing 0 of ")),
1431
        "{phases:?}"
1432
    );
1433
    assert!(
1434
        phases
1435
            .iter()
1436
            .any(|p| p.starts_with("writing the index of ")),
1437
        "{phases:?}"
1438
    );
1439
}
1440
1441
#[test]
1442
fn gc_packs_objects_and_history_still_works() {
1443
    hermetic();
1444
    let dir = tempfile::tempdir().unwrap();
1445
    let root = dir.path();
1446
    let mut repo = Repo::init(root).unwrap().with_home(root.join("home"));
1447
    repo.create_identity("Ada", "a@b", IdentityScope::User)
1448
        .unwrap();
1449
    repo.set_user_config("core.sign", "change").unwrap();
1450
    write(root, "a.txt", b"one\n");
1451
    let h1 = repo.commit("one", &[]).unwrap();
1452
    write(root, "a.txt", b"two\n");
1453
    write(root, "big.bin", &vec![0u8; 100_000]);
1454
    let h2 = repo.commit("two", &[]).unwrap();
1455
    // Several snapshots leave superseded working-copy versions behind.
1456
    for i in 0..5 {
1457
        write(root, "a.txt", format!("two\n{i}\n").as_bytes());
1458
        repo.snapshot("status").unwrap();
1459
    }
1460
    write(root, "a.txt", b"two\n");
1461
    repo.snapshot("status").unwrap();
1462
    let before = repo.store().list().unwrap();
1463
    assert!(repo.store().loose_count().unwrap() > 0);
1464
1465
    // With the default retention every operation's view is a root: nothing prunes.
1466
    let r = repo.gc(true).unwrap();
1467
    assert_eq!(r.packed.objects, before.len());
1468
    assert_eq!(r.pruned.objects, 0);
1469
    assert_eq!(repo.store().loose_count().unwrap(), 0);
1470
    assert_eq!(repo.store().list().unwrap(), before);
1471
1472
    // With zero retention only the current view is a root: superseded
1473
    // working copies go, everything reachable stays.
1474
    repo.config.set("core.op-retention", "0").unwrap();
1475
    repo.save_config().unwrap();
1476
    let mut repo = Repo::open(root).unwrap().with_home(root.join("home"));
1477
    let r = repo.gc(true).unwrap();
1478
    assert!(r.pruned.objects >= 5, "{r:?}");
1479
    let after = repo.store().list().unwrap();
1480
    assert!(after.len() < before.len());
1481
    assert!(after.contains(&h1) && after.contains(&h2));
1482
    for (_, op) in repo.op_log().unwrap() {
1483
        assert!(!op.command.is_empty(), "operation objects are all kept");
1484
    }
1485
    // Everything still works from the pruned, packed store.
1486
    assert_eq!(repo.bookmark_heads().unwrap(), vec![h2]);
1487
    assert!(matches!(
1488
        repo.verify_change(&h2).unwrap(),
1489
        SignatureStatus::Valid { .. }
1490
    ));
1491
    assert_eq!(repo.log().unwrap().len(), 3);
1492
    repo.checkout(&[h1], false, "checkout").unwrap();
1493
    assert_eq!(fs::read(root.join("a.txt")).unwrap(), b"one\n");
1494
    repo.checkout(&[h2], false, "checkout").unwrap();
1495
    assert_eq!(fs::read(root.join("big.bin")).unwrap().len(), 100_000);
1496
    assert!(!repo.snapshot("status").unwrap().changed);
1497
    // Grace period defers pruning of young garbage.
1498
    write(root, "a.txt", b"three\n");
1499
    repo.commit("three", &[]).unwrap();
1500
    let r = repo.gc(false).unwrap();
1501
    assert_eq!(r.pruned.objects, 0);
1502
    assert!(r.pruned.deferred > 0);
1503
    let r = repo.gc(true).unwrap();
1504
    assert!(r.pruned.objects > 0);
1505
    assert_eq!(repo.log().unwrap().len(), 4);
1506
    // Restoring the default retention makes the old views roots again; the
1507
    // working copies they name were pruned, which gc tolerates.
1508
    repo.config.set("core.op-retention", "90").unwrap();
1509
    repo.save_config().unwrap();
1510
    let repo = Repo::open(root).unwrap().with_home(root.join("home"));
1511
    let r = repo.gc(false).unwrap();
1512
    assert_eq!(r.pruned.objects, 0);
1513
    assert_eq!(repo.log().unwrap().len(), 4);
1514
}
1515
1516
#[test]
1517
fn describe_amend_abandon_heads() {
1518
    hermetic();
1519
    let dir = tempfile::tempdir().unwrap();
1520
    let root = dir.path();
1521
    let mut repo = Repo::init(root).unwrap().with_home(root.join("home"));
1522
    repo.create_identity("Ada", "a@b", IdentityScope::User)
1523
        .unwrap();
1524
    repo.set_user_config("core.sign", "change").unwrap();
1525
    write(root, "a.txt", b"one\n");
1526
    let h1 = repo.commit("first", &[]).unwrap();
1527
    write(root, "a.txt", b"one\ntwo\n");
1528
    let h2 = repo.commit("secnod", &[]).unwrap();
1529
    let id2 = repo.store().get_change(&h2).unwrap().change_id;
1530
1531
    // describe: same ChangeId, new hash, bookmark and working copy follow.
1532
    let h2b = repo.describe(&h2, "second").unwrap();
1533
    assert_ne!(h2b, h2);
1534
    let c = repo.store().get_change(&h2b).unwrap();
1535
    assert_eq!(
1536
        (c.change_id, c.message.as_str(), c.deps.clone()),
1537
        (id2, "second", vec![h1])
1538
    );
1539
    assert_eq!(repo.bookmark_heads().unwrap(), vec![h2b]);
1540
    assert!(matches!(
1541
        repo.verify_change(&h2b).unwrap(),
1542
        SignatureStatus::Valid { .. }
1543
    ));
1544
    let s = repo.snapshot("status").unwrap();
1545
    assert!(s.statuses.is_empty(), "{:?}", s.statuses);
1546
    assert_eq!(
1547
        repo.resolve_change(&id2.short(8)).unwrap(),
1548
        h2b,
1549
        "the old object is no longer reachable from the log"
1550
    );
1551
    // Describing a non-head rewrites its dependents (h2b → h2c') and the working copy.
1552
    let h1b = repo.describe(&h1, "first, described").unwrap();
1553
    assert_ne!(h1b, h1);
1554
    let heads = repo.bookmark_heads().unwrap();
1555
    assert_eq!(heads.len(), 1);
1556
    let top = repo.store().get_change(&heads[0]).unwrap();
1557
    assert_eq!((top.change_id, top.deps.clone()), (id2, vec![h1b]));
1558
    assert!(
1559
        matches!(
1560
            repo.verify_change(&heads[0]).unwrap(),
1561
            SignatureStatus::Valid { .. }
1562
        ),
1563
        "rewritten own change is re-signed"
1564
    );
1565
    let (_, wc) = repo.working_copy().unwrap();
1566
    assert_eq!(
1567
        wc.deps,
1568
        vec![heads[0]],
1569
        "the working copy follows the rewrite"
1570
    );
1571
    assert!(!repo.snapshot("status").unwrap().changed);
1572
    let snap = repo.load_state(&heads).unwrap().materialize();
1573
    assert!(
1574
        matches!(&snap.files["a.txt"].content, FileContent::Text { bytes, .. } if bytes == b"one\ntwo\n")
1575
    );
1576
1577
    // amend: fold an edit into the head; the result is one change from h1.
1578
    write(root, "a.txt", b"one\ntwo\nthree\n");
1579
    write(root, "b.txt", b"b\n");
1580
    let h2c = repo.amend(None).unwrap();
1581
    let c = repo.store().get_change(&h2c).unwrap();
1582
    assert_eq!(c.change_id, id2);
1583
    assert_eq!(c.message, "second");
1584
    assert_eq!(repo.bookmark_heads().unwrap(), vec![h2c]);
1585
    assert_eq!(
1586
        repo.log().unwrap().len(),
1587
        3,
1588
        "working copy, amended head, first"
1589
    );
1590
    let snap = repo.load_state(&[h2c]).unwrap().materialize();
1591
    assert!(
1592
        matches!(&snap.files["a.txt"].content, FileContent::Text { bytes, .. } if bytes == b"one\ntwo\nthree\n")
1593
    );
1594
    assert!(snap.files.contains_key("b.txt"));
1595
    assert!(!repo.snapshot("status").unwrap().changed);
1596
    assert!(
1597
        repo.amend(None).is_err(),
1598
        "clean working copy and no message"
1599
    );
1600
    let h2d = repo.amend(Some("second, amended")).unwrap();
1601
    assert_eq!(
1602
        repo.store().get_change(&h2d).unwrap().message,
1603
        "second, amended"
1604
    );
1605
1606
    // abandon: the head goes, its content stays as uncommitted work.
1607
    repo.abandon(&h2d).unwrap();
1608
    assert_eq!(
1609
        repo.bookmark_heads().unwrap(),
1610
        vec![h1b],
1611
        "the described first change is the head again"
1612
    );
1613
    let s = repo.snapshot("status").unwrap();
1614
    let paths: Vec<_> = s
1615
        .statuses
1616
        .iter()
1617
        .map(|p| (p.path.as_str(), p.status))
1618
        .collect();
1619
    assert_eq!(
1620
        paths,
1621
        vec![
1622
            ("a.txt", ChangeStatus::Modified),
1623
            ("b.txt", ChangeStatus::Added)
1624
        ]
1625
    );
1626
    assert_eq!(fs::read(root.join("a.txt")).unwrap(), b"one\ntwo\nthree\n");
1627
    let h3 = repo.commit("recommitted", &[]).unwrap();
1628
    assert_eq!(repo.bookmark_heads().unwrap(), vec![h3]);
1629
    // undo brings the abandoned head back.
1630
    repo.undo().unwrap();
1631
    repo.undo().unwrap();
1632
    assert_eq!(repo.bookmark_heads().unwrap(), vec![h2d]);
1633
1634
    // Abandoning a non-head whose dependent references its atoms reifies
1635
    // the references (here: a.txt vanishes with it, so the dependent's edit
1636
    // of a.txt is dropped with a note) instead of refusing; undo restores it.
1637
    let base = repo.bookmark_heads().unwrap()[0];
1638
    let base_change = repo.store().get_change(&base).unwrap();
1639
    let h1_now = base_change.deps[0];
1640
    let notes = repo.abandon(&h1_now).unwrap();
1641
    assert!(
1642
        !notes.is_empty(),
1643
        "the dependent's edit of a.txt was reified"
1644
    );
1645
    let heads = repo.bookmark_heads().unwrap();
1646
    let after = repo.load_state(&heads).unwrap().materialize();
1647
    assert!(
1648
        !after.files.contains_key("a.txt") && after.files.contains_key("b.txt"),
1649
        "{:?}",
1650
        after.files.keys()
1651
    );
1652
    repo.undo().unwrap();
1653
    assert_eq!(repo.bookmark_heads().unwrap(), vec![base]);
1654
    write(root, "c.txt", b"c\n");
1655
    let hc = repo.commit("c", &[]).unwrap();
1656
    write(root, "d.txt", b"d\n");
1657
    let hd = repo.commit("d", &[hc]).unwrap();
1658
    assert_eq!(repo.store().get_change(&hd).unwrap().deps, vec![hc]);
1659
    repo.abandon(&hc).unwrap();
1660
    let heads: BTreeSet<_> = repo.bookmark_heads().unwrap().into_iter().collect();
1661
    assert!(!heads.contains(&hc));
1662
    let d_now = heads
1663
        .iter()
1664
        .find(|h| repo.store().get_change(h).unwrap().message == "d")
1665
        .copied()
1666
        .unwrap();
1667
    assert!(
1668
        repo.store().get_change(&d_now).unwrap().deps.is_empty(),
1669
        "d inherited c's (empty) dependencies"
1670
    );
1671
    let s = repo.snapshot("status").unwrap();
1672
    assert_eq!(
1673
        s.statuses
1674
            .iter()
1675
            .map(|p| p.path.as_str())
1676
            .collect::<Vec<_>>(),
1677
        vec!["c.txt"],
1678
        "c's content is now uncommitted work"
1679
    );
1680
}
1681
1682
#[test]
1683
fn git_export_mirrors_history() {
1684
    hermetic();
1685
    if std::process::Command::new("git")
1686
        .arg("--version")
1687
        .output()
1688
        .is_err()
1689
    {
1690
        eprintln!("git not installed; skipping");
1691
        return;
1692
    }
1693
    let dir = tempfile::tempdir().unwrap();
1694
    let root = dir.path();
1695
    let mut repo = Repo::init(&root.join("r"))
1696
        .unwrap()
1697
        .with_home(root.join("home"));
1698
    repo.create_identity("Ada Lovelace", "[email protected]", IdentityScope::User)
1699
        .unwrap();
1700
    let r = root.join("r");
1701
    write(&r, "README.md", b"hello\n");
1702
    write(&r, "src/main.rs", b"fn main() {}\n");
1703
    let h1 = repo.commit("first", &[]).unwrap();
1704
    write(&r, "src/main.rs", b"fn main() { run(); }\n");
1705
    write(&r, "logo.png", b"\x89PNG\0\0");
1706
    let h2 = repo.commit("second", &[]).unwrap();
1707
1708
    let git_dir = root.join("mirror.git");
1709
    let rep = repo.git_export(&git_dir).unwrap();
1710
    assert_eq!((rep.exported, rep.skipped, rep.heads), (2, 0, 1));
1711
    let git = |args: &[&str]| -> String {
1712
        let out = std::process::Command::new("git")
1713
            .arg("-C")
1714
            .arg(&git_dir)
1715
            .args(args)
1716
            .output()
1717
            .unwrap();
1718
        assert!(
1719
            out.status.success(),
1720
            "{}",
1721
            String::from_utf8_lossy(&out.stderr)
1722
        );
1723
        String::from_utf8_lossy(&out.stdout).trim().to_string()
1724
    };
1725
    assert_eq!(git(&["log", "--format=%s", "main"]), "second\nfirst");
1726
    assert_eq!(git(&["show", "main:src/main.rs"]), "fn main() { run(); }");
1727
    assert_eq!(git(&["show", "main:README.md"]), "hello");
1728
    let body = git(&["log", "-1", "--format=%B", "main"]);
1729
    assert!(
1730
        body.contains(&format!("Oxy-Hash: {}", h2.to_hex())),
1731
        "{body}"
1732
    );
1733
    assert!(body.contains("Change-Id: "), "{body}");
1734
    assert_eq!(
1735
        git(&["log", "-1", "--format=%an <%ae>", "main"]),
1736
        "Ada Lovelace <[email protected]>"
1737
    );
1738
    assert_eq!(
1739
        git(&["ls-tree", "--name-only", "main"]),
1740
        "README.md\nlogo.png\nsrc"
1741
    );
1742
1743
    // Re-export is incremental.
1744
    let rep = repo.git_export(&git_dir).unwrap();
1745
    assert_eq!((rep.exported, rep.skipped), (0, 2));
1746
1747
    // An independent change makes two heads; the next state is one more
1748
    // commit on the linear branch whose tree is the union.
1749
    repo.checkout(&[h1], false, "checkout").unwrap();
1750
    write(&r, "other.txt", b"o\n");
1751
    let h3 = repo.commit("third", &[]).unwrap();
1752
    let rep = repo.git_export(&git_dir).unwrap();
1753
    assert_eq!((rep.exported, rep.heads), (1, 2));
1754
    assert_eq!(git(&["log", "--format=%s", "main"]), "third\nsecond\nfirst");
1755
    let parents = git(&["rev-list", "--parents", "-1", "main"]);
1756
    assert_eq!(parents.split(' ').count(), 2, "one parent: {parents}");
1757
    assert_eq!(git(&["show", "main:other.txt"]), "o");
1758
    assert_eq!(git(&["show", "main:src/main.rs"]), "fn main() { run(); }");
1759
    assert_eq!(
1760
        git(&["ls-tree", "--name-only", "main"]),
1761
        "README.md\nlogo.png\nother.txt\nsrc"
1762
    );
1763
    let body = git(&["log", "-1", "--format=%B", "main"]);
1764
    assert!(
1765
        body.contains(&format!("Oxy-Hash: {}", h3.to_hex())) && body.contains("Oxy-State: "),
1766
        "{body}"
1767
    );
1768
    // A rewrite is a new state whose one new change is the rewritten one.
1769
    repo.describe(&h3, "third, described").unwrap();
1770
    let rep = repo.git_export(&git_dir).unwrap();
1771
    assert_eq!(rep.exported, 1);
1772
    assert_eq!(
1773
        git(&["log", "-1", "--format=%s", "main"]),
1774
        "third, described"
1775
    );
1776
    assert_eq!(git(&["log", "--format=%s", "main"]).lines().count(), 4);
1777
    let _ = h2;
1778
}
1779
1780
#[test]
1781
fn git_import_reproduces_trees() {
1782
    git_import_reproduces_trees_with(None);
1783
}
1784
1785
/// The same import with every merge rendered in batches of one file
1786
/// (oxygen#25): what a merge onto a base of thousands of files takes.
1787
#[test]
1788
fn git_import_reproduces_trees_in_batches() {
1789
    git_import_reproduces_trees_with(Some(1));
1790
}
1791
1792
fn git_import_reproduces_trees_with(batch: Option<usize>) {
1793
    crate::repo::git::set_merge_batch_for_tests(batch);
1794
    hermetic();
1795
    if std::process::Command::new("git")
1796
        .arg("--version")
1797
        .output()
1798
        .is_err()
1799
    {
1800
        eprintln!("git not installed; skipping");
1801
        return;
1802
    }
1803
    let dir = tempfile::tempdir().unwrap();
1804
    let root = dir.path();
1805
    let g = root.join("src.git");
1806
    fs::create_dir_all(&g).unwrap();
1807
    let git = |args: &[&str]| -> String {
1808
        let out = std::process::Command::new("git")
1809
            .arg("-C")
1810
            .arg(&g)
1811
            .args([
1812
                "-c",
1813
                "user.name=Grace",
1814
                "-c",
1815
                "[email protected]",
1816
                "-c",
1817
                "commit.gpgsign=false",
1818
            ])
1819
            .args(args)
1820
            .output()
1821
            .unwrap();
1822
        assert!(
1823
            out.status.success(),
1824
            "git {args:?}: {}",
1825
            String::from_utf8_lossy(&out.stderr)
1826
        );
1827
        String::from_utf8_lossy(&out.stdout).trim().to_string()
1828
    };
1829
    git(&["init", "-q", "-b", "main"]);
1830
    write(&g, "README.md", b"# Hi\n");
1831
    write(&g, "src/lib.rs", b"pub fn a() {}\n");
1832
    git(&["add", "."]);
1833
    git(&["commit", "-q", "-m", "initial"]);
1834
    write(&g, "src/lib.rs", b"pub fn a() {}\npub fn b() {}\n");
1835
    write(&g, "run.sh", b"#!/bin/sh\n");
1836
    #[cfg(unix)]
1837
    {
1838
        use std::os::unix::fs::PermissionsExt;
1839
        fs::set_permissions(g.join("run.sh"), fs::Permissions::from_mode(0o755)).unwrap();
1840
    }
1841
    write(&g, "logo.png", b"\x89PNG\0\0\x01");
1842
    git(&["add", "."]);
1843
    git(&[
1844
        "commit",
1845
        "-q",
1846
        "-m",
1847
        "second\n\nChange-Id: 0123456789abcdef0123456789abcdef",
1848
    ]);
1849
    // A branch that edits README, merged back with a conflict-free merge.
1850
    git(&["checkout", "-q", "-b", "topic", "HEAD~1"]);
1851
    write(&g, "README.md", b"# Hi\n\nMore.\n");
1852
    git(&["commit", "-q", "-am", "readme"]);
1853
    git(&["checkout", "-q", "main"]);
1854
    git(&["merge", "-q", "--no-ff", "-m", "merge topic", "topic"]);
1855
    // A branch from the initial commit inserting at the same place as
1856
    // "second": concurrent in Oxygen too, so the merge commit is a resolution.
1857
    let initial = git(&["rev-list", "--max-parents=0", "HEAD"]);
1858
    git(&["checkout", "-q", "-b", "clash", &initial]);
1859
    write(&g, "src/lib.rs", b"pub fn a() {}\npub fn c() {}\n");
1860
    git(&["commit", "-q", "-am", "clash"]);
1861
    git(&["checkout", "-q", "main"]);
1862
    let _ = std::process::Command::new("git")
1863
        .arg("-C")
1864
        .arg(&g)
1865
        .args(["merge", "-q", "clash"])
1866
        .output();
1867
    write(
1868
        &g,
1869
        "src/lib.rs",
1870
        b"pub fn a() {}\npub fn b() {}\npub fn c() {}\n",
1871
    );
1872
    git(&["add", "."]);
1873
    git(&["commit", "-q", "-m", "resolve clash"]);
1874
    git(&["rm", "-q", "logo.png"]);
1875
    git(&["commit", "-q", "-m", "drop logo"]);
1876
    // A rename with a small edit is imported as a move of the same node.
1877
    git(&["mv", "src/lib.rs", "src/lib2.rs"]);
1878
    write(
1879
        &g,
1880
        "src/lib2.rs",
1881
        b"pub fn a() {}\npub fn b() {}\npub fn c() {}\npub fn d() {}\n",
1882
    );
1883
    git(&["add", "."]);
1884
    git(&["commit", "-q", "-m", "rename lib"]);
1885
    // A branch that edits run.sh, merged keeping main's tree (`-s ours`):
1886
    // run.sh is the same as in the first parent's tree, but the merged
1887
    // change touched it, so the importer must compare it, not skip it.
1888
    git(&["checkout", "-q", "-b", "discarded"]);
1889
    write(&g, "run.sh", b"#!/bin/sh\necho discarded\n");
1890
    git(&["commit", "-q", "-am", "discarded edit"]);
1891
    git(&["checkout", "-q", "main"]);
1892
    git(&[
1893
        "merge",
1894
        "-q",
1895
        "-s",
1896
        "ours",
1897
        "-m",
1898
        "merge discarded, keeping ours",
1899
        "discarded",
1900
    ]);
1901
    let expected_count: usize = git(&["rev-list", "--count", "main"]).parse().unwrap();
1902
1903
    let dest = root.join("oxy");
1904
    let repo = Repo::init(&dest).unwrap().with_home(root.join("home"));
1905
    let rep = repo.import_git(&g, "main").unwrap();
1906
    assert_eq!(rep.commits, expected_count);
1907
    assert_eq!(rep.merges, 3);
1908
    assert_eq!(
1909
        fs::read(dest.join("run.sh")).unwrap(),
1910
        b"#!/bin/sh\n",
1911
        "the ours merge kept main's run.sh"
1912
    );
1913
    let v = repo.verify_git_import(&g, "main").unwrap();
1914
    assert_eq!(v.commits, expected_count, "every commit's tree reproduced");
1915
    assert!(v.mismatches.is_empty(), "{:?}", v.mismatches);
1916
    // The working copy equals the Git tree at main.
1917
    assert_eq!(
1918
        fs::read(dest.join("src/lib2.rs")).unwrap(),
1919
        b"pub fn a() {}\npub fn b() {}\npub fn c() {}\npub fn d() {}\n"
1920
    );
1921
    assert!(!dest.join("src/lib.rs").exists());
1922
    assert_eq!(
1923
        fs::read(dest.join("README.md")).unwrap(),
1924
        b"# Hi\n\nMore.\n"
1925
    );
1926
    assert!(!dest.join("logo.png").exists());
1927
    #[cfg(unix)]
1928
    {
1929
        use std::os::unix::fs::PermissionsExt;
1930
        assert!(
1931
            fs::metadata(dest.join("run.sh"))
1932
                .unwrap()
1933
                .permissions()
1934
                .mode()
1935
                & 0o111
1936
                != 0
1937
        );
1938
    }
1939
    assert!(
1940
        !repo.snapshot("status").unwrap().changed,
1941
        "clean after import"
1942
    );
1943
    let heads = repo.bookmark_heads().unwrap();
1944
    let st = repo.load_state(&heads).unwrap();
1945
    assert!(!st.materialize().is_conflicted());
1946
    assert_eq!(st.len(), expected_count);
1947
    let tip = repo
1948
        .log()
1949
        .unwrap()
1950
        .into_iter()
1951
        .find(|e| e.change.message.starts_with("rename lib"))
1952
        .unwrap();
1953
    let c = repo.store().get_change(&tip.hash).unwrap();
1954
    assert!(
1955
        c.tree_ops
1956
            .iter()
1957
            .any(|op| matches!(op, TreeOp::Move { name, .. } if name == "lib2.rs")),
1958
        "{:?}",
1959
        c.tree_ops
1960
    );
1961
    assert!(!c
1962
        .tree_ops
1963
        .iter()
1964
        .any(|op| matches!(op, TreeOp::AddNode { .. })));
1965
    // Messages carry Git trailers; the Change-Id trailer was honoured.
1966
    let log = repo.log().unwrap();
1967
    let second = log
1968
        .iter()
1969
        .find(|e| e.change.message.starts_with("second"))
1970
        .unwrap();
1971
    assert_eq!(
1972
        second.change.change_id,
1973
        ChangeId::from_hex("0123456789abcdef0123456789abcdef").unwrap()
1974
    );
1975
    assert!(second
1976
        .change
1977
        .message
1978
        .contains("Git-Author: Grace <[email protected]>"));
1979
    let resolve = log
1980
        .iter()
1981
        .find(|e| e.change.message.starts_with("resolve clash"))
1982
        .unwrap();
1983
    assert_eq!(
1984
        resolve.change.kind,
1985
        ChangeKind::Resolution,
1986
        "a conflicting Git merge becomes a resolution"
1987
    );
1988
    // Re-importing into another fresh repository gives the same ChangeIds.
1989
    let repo2 = Repo::init(&root.join("oxy2"))
1990
        .unwrap()
1991
        .with_home(root.join("home"));
1992
    repo2.import_git(&g, "main").unwrap();
1993
    // New nodes' identifiers derive from the commit (spec §23), so the
1994
    // re-import is not just the same ChangeIds but the same changes.
1995
    assert_eq!(
1996
        repo2.bookmark_heads().unwrap(),
1997
        repo.bookmark_heads().unwrap()
1998
    );
1999
    let ids: BTreeSet<ChangeId> = repo
2000
        .log()
2001
        .unwrap()
2002
        .iter()
2003
        .filter(|e| !e.is_working_copy)
2004
        .map(|e| e.change.change_id)
2005
        .collect();
2006
    let ids2: BTreeSet<ChangeId> = repo2
2007
        .log()
2008
        .unwrap()
2009
        .iter()
2010
        .filter(|e| !e.is_working_copy)
2011
        .map(|e| e.change.change_id)
2012
        .collect();
2013
    assert_eq!(ids, ids2);
2014
    // Round trip back out to Git reproduces the tip tree.
2015
    let mirror = root.join("mirror.git");
2016
    repo.git_export(&mirror).unwrap();
2017
    let out = std::process::Command::new("git")
2018
        .arg("-C")
2019
        .arg(&mirror)
2020
        .args(["show", "main:src/lib2.rs"])
2021
        .output()
2022
        .unwrap();
2023
    assert_eq!(
2024
        String::from_utf8_lossy(&out.stdout),
2025
        "pub fn a() {}\npub fn b() {}\npub fn c() {}\npub fn d() {}\n"
2026
    );
2027
    let out = std::process::Command::new("git")
2028
        .arg("-C")
2029
        .arg(&mirror)
2030
        .args(["show", "main:src/lib.rs"])
2031
        .output()
2032
        .unwrap();
2033
    assert!(
2034
        !out.status.success(),
2035
        "the old path is gone from the export"
2036
    );
2037
}
2038
2039
#[test]
2040
fn checkpoints_accelerate_loading_and_stay_correct() {
2041
    hermetic();
2042
    let dir = tempfile::tempdir().unwrap();
2043
    let root = dir.path();
2044
    let mut repo = Repo::init(root).unwrap().with_home(root.join("home"));
2045
    repo.config.set("core.checkpoint-interval", "5").unwrap();
2046
    repo.save_config().unwrap();
2047
    let repo = Repo::open(root).unwrap().with_home(root.join("home"));
2048
    let mut hashes = Vec::new();
2049
    for i in 0..12 {
2050
        write(
2051
            root,
2052
            "a.txt",
2053
            format!(
2054
                "{}\n",
2055
                (0..=i)
2056
                    .map(|k| k.to_string())
2057
                    .collect::<Vec<_>>()
2058
                    .join("\n")
2059
            )
2060
            .as_bytes(),
2061
        );
2062
        write(root, &format!("f{i}.txt"), b"x\n");
2063
        hashes.push(repo.commit(&format!("c{i}"), &[]).unwrap());
2064
    }
2065
    let (_, cp) = repo
2066
        .latest_checkpoint("main")
2067
        .unwrap()
2068
        .expect("automatic checkpoint");
2069
    assert!(cp.count >= 5 && cp.count <= 12, "{}", cp.count);
2070
    // Loading through the checkpoint equals loading everything.
2071
    let heads = repo.bookmark_heads().unwrap();
2072
    let fast = repo.load_state(&heads).unwrap();
2073
    let full = repo.load_state_full(&heads).unwrap();
2074
    assert_eq!(fast.len(), full.len());
2075
    assert_eq!(fast.heads(), full.heads());
2076
    let (a, b) = (fast.materialize(), full.materialize());
2077
    assert_eq!(
2078
        a.files.keys().collect::<Vec<_>>(),
2079
        b.files.keys().collect::<Vec<_>>()
2080
    );
2081
    for (p, f) in &a.files {
2082
        assert_eq!(f.content, b.files[p].content, "{p}");
2083
    }
2084
    assert!(repo.load_state_checkpointed(&heads).unwrap().is_some());
2085
    // A head set that does not contain the checkpoint's heads falls back.
2086
    assert!(repo
2087
        .load_state_checkpointed(&[hashes[0]])
2088
        .unwrap()
2089
        .is_none());
2090
    assert_eq!(repo.load_state(&[hashes[0]]).unwrap().len(), 1);
2091
    // Everything else keeps working on top of the checkpoint.
2092
    assert!(!repo.snapshot("status").unwrap().changed);
2093
    let h = repo.describe(&hashes[3], "c3 described").unwrap();
2094
    assert_eq!(repo.store().get_change(&h).unwrap().message, "c3 described");
2095
    let (r, n, bytes) = repo.checkpoint().unwrap();
2096
    assert!(n >= 12 && bytes > 0);
2097
    assert_eq!(repo.latest_checkpoint("main").unwrap().unwrap().0, r);
2098
    write(root, "a.txt", b"after\n");
2099
    let h_after = repo.commit("after", &[]).unwrap();
2100
    let st = repo.load_state(&repo.bookmark_heads().unwrap()).unwrap();
2101
    assert!(st.contains(&h_after));
2102
    assert!(
2103
        matches!(&st.materialize().files["a.txt"].content, FileContent::Text { bytes, .. } if bytes == b"after\n")
2104
    );
2105
    assert_eq!(repo.log().unwrap().len(), 14);
2106
    // Checkpoints survive gc.
2107
    repo.gc(true).unwrap();
2108
    assert!(repo.latest_checkpoint("main").unwrap().is_some());
2109
    assert!(repo
2110
        .load_state_checkpointed(&repo.bookmark_heads().unwrap())
2111
        .unwrap()
2112
        .is_some());
2113
}
2114
2115
#[test]
2116
fn quick_status_for_prompts() {
2117
    hermetic();
2118
    let dir = tempfile::tempdir().unwrap();
2119
    let root = dir.path();
2120
    let origin = Repo::init(&root.join("origin")).unwrap();
2121
    let url = root.join("origin").to_string_lossy().to_string();
2122
    let a = Repo::clone(&url, &root.join("a"))
2123
        .unwrap()
2124
        .with_home(root.join("home"));
2125
    let ops_before = a.op_log().unwrap().len();
2126
    let info = a.quick_status().unwrap();
2127
    assert_eq!(
2128
        (
2129
            info.bookmark.as_str(),
2130
            info.heads,
2131
            info.dirty,
2132
            info.conflicted,
2133
            info.ahead,
2134
            info.behind
2135
        ),
2136
        ("main", 0, false, false, Some(0), Some(0))
2137
    );
2138
    write(&root.join("a"), "f.txt", b"f\n");
2139
    assert!(a.quick_status().unwrap().dirty, "a new file is dirty");
2140
    assert_eq!(
2141
        a.op_log().unwrap().len(),
2142
        ops_before,
2143
        "quick_status records nothing"
2144
    );
2145
    // A snapshotted but uncommitted change is still dirty.
2146
    a.snapshot("status").unwrap();
2147
    assert!(a.quick_status().unwrap().dirty);
2148
    a.commit("f", &[]).unwrap();
2149
    let info = a.quick_status().unwrap();
2150
    assert!(!info.dirty, "clean right after a commit");
2151
    assert_eq!((info.ahead, info.behind), (Some(1), Some(0)));
2152
    assert_eq!(
2153
        info.format("%b %c%d%x%A%D"),
2154
        format!("main {}+1", info.change_id)
2155
    );
2156
    assert_eq!(info.format("[%h heads] %a/%B %%"), "[1 heads] 1/0 %");
2157
    // Touching a file without changing it is not dirty; changing content of
2158
    // the same size is.
2159
    let p = root.join("a/f.txt");
2160
    let content = fs::read(&p).unwrap();
2161
    fs::write(&p, &content).unwrap();
2162
    assert!(!a.quick_status().unwrap().dirty);
2163
    fs::write(&p, b"g\n").unwrap();
2164
    assert!(a.quick_status().unwrap().dirty);
2165
    fs::write(&p, b"f\n").unwrap();
2166
    // Push, then a second clone commits and pushes: we are behind.
2167
    assert!(a.push("origin", false).unwrap()[0].ok);
2168
    assert_eq!(a.quick_status().unwrap().ahead, Some(0));
2169
    let b = Repo::clone(&url, &root.join("b"))
2170
        .unwrap()
2171
        .with_home(root.join("home-b"));
2172
    write(&root.join("b"), "g.txt", b"g\n");
2173
    b.commit("g", &[]).unwrap();
2174
    b.push("origin", false).unwrap();
2175
    a.fetch("origin").unwrap();
2176
    let info = a.quick_status().unwrap();
2177
    assert_eq!((info.ahead, info.behind), (Some(0), Some(1)));
2178
    assert_eq!(info.format("%A%D"), "-1");
2179
    let _ = origin;
2180
}
2181
2182
#[test]
2183
fn lazy_blobs_are_fetched_on_first_read() {
2184
    hermetic();
2185
    let dir = tempfile::tempdir().unwrap();
2186
    let root = dir.path();
2187
    let origin_dir = root.join("origin");
2188
    let origin = Repo::init(&origin_dir)
2189
        .unwrap()
2190
        .with_home(root.join("home"));
2191
    let url = origin_dir.to_string_lossy().to_string();
2192
    let big: Vec<u8> = (0..200_000u32).map(|i| (i % 251) as u8).collect(); // has NUL bytes: opaque
2193
    write(&origin_dir, "big.bin", &big);
2194
    write(&origin_dir, "small.bin", &[0u8, 1, 2]);
2195
    write(&origin_dir, "t.txt", b"t\n");
2196
    let h = origin.commit("blobs", &[]).unwrap();
2197
    let big_ref = Repo::blob_ref(&big);
2198
2199
    // Fetch only (no checkout) with a filter: the big blob stays absent.
2200
    let a = Repo::init_with_id(&root.join("a"), origin.id().unwrap())
2201
        .unwrap()
2202
        .with_home(root.join("home"));
2203
    let a = {
2204
        let mut a = a;
2205
        a.config.set("remote.origin.url", &url).unwrap();
2206
        a.config.set("filter.max-blob", "100K").unwrap();
2207
        a.save_config().unwrap();
2208
        a
2209
    };
2210
    assert_eq!(a.config.max_blob, Some(100 * 1024));
2211
    a.fetch("origin").unwrap();
2212
    assert!(a.store().has(&h));
2213
    assert!(!a.store().has(&big_ref), "withheld");
2214
    assert!(
2215
        a.store().has(&Repo::blob_ref(&[0u8, 1, 2])),
2216
        "small blob came along"
2217
    );
2218
    assert_eq!(a.lazy_remote(&big_ref).as_deref(), Some("origin"));
2219
2220
    // status and commit do not need it: adopt the state, edit a text file, commit.
2221
    let (op_ref, op) = a.head_op().unwrap();
2222
    let mut view = op.view.clone();
2223
    view.bookmarks.insert(
2224
        "main".into(),
2225
        a.store().put_state(&StateObject::new(vec![h])).unwrap(),
2226
    );
2227
    a.record_op(&[op_ref], "adopt", view).unwrap();
2228
    // Checkout reads the blob lazily, which fetches it.
2229
    a.checkout(&[h], true, "checkout").unwrap();
2230
    assert!(a.store().has(&big_ref), "fetched on first read");
2231
    assert_eq!(fs::read(root.join("a/big.bin")).unwrap(), big);
2232
    assert!(a.lazy_remote(&big_ref).is_none(), "no longer registered");
2233
    write(&root.join("a"), "t.txt", b"t2\n");
2234
    a.commit("text edit", &[]).unwrap();
2235
2236
    // clone --max-blob records the filter; the checkout fetches lazily.
2237
    let b = Repo::clone_with(&url, &root.join("b"), Some(1024), &[]).unwrap();
2238
    assert_eq!(b.config.max_blob, Some(1024));
2239
    assert_eq!(fs::read(root.join("b/big.bin")).unwrap(), big);
2240
    assert_eq!(parse_size("2M").unwrap(), 2 << 20);
2241
    assert!(parse_size("lots").is_err());
2242
}
2243
2244
#[test]
2245
fn sparse_checkout_materializes_only_chosen_paths() {
2246
    hermetic();
2247
    let dir = tempfile::tempdir().unwrap();
2248
    let root = dir.path();
2249
    let origin_dir = root.join("origin");
2250
    let origin = Repo::init(&origin_dir)
2251
        .unwrap()
2252
        .with_home(root.join("home"));
2253
    write(&origin_dir, "src/main.rs", b"fn main() {}\n");
2254
    write(&origin_dir, "src/lib.rs", b"pub fn a() {}\n");
2255
    write(&origin_dir, "docs/guide.md", b"# guide\n");
2256
    let logo: Vec<u8> = (0..50_000u32).map(|i| (i % 7) as u8).collect();
2257
    write(&origin_dir, "docs/logo.png", &logo);
2258
    write(&origin_dir, "README.md", b"# top\n");
2259
    let h1 = origin.commit("tree", &[]).unwrap();
2260
    let url = origin_dir.to_string_lossy().to_string();
2261
2262
    let a = Repo::clone_with(&url, &root.join("a"), None, &["src".into()])
2263
        .unwrap()
2264
        .with_home(root.join("home"));
2265
    assert_eq!(a.config.sparse_paths, vec!["src"]);
2266
    assert_eq!(a.config.max_blob, Some(0), "sparse implies lazy blobs");
2267
    assert!(root.join("a/src/main.rs").exists());
2268
    assert!(!root.join("a/docs").exists() && !root.join("a/README.md").exists());
2269
    assert!(
2270
        !a.store().has(&Repo::blob_ref(&logo)),
2271
        "out-of-scope blob never fetched"
2272
    );
2273
    assert!(
2274
        !a.snapshot("status").unwrap().changed,
2275
        "out-of-scope files are not removals"
2276
    );
2277
    assert!(!a.quick_status().unwrap().dirty);
2278
2279
    // Edits in scope commit normally and keep the rest of the tree intact.
2280
    write(
2281
        &root.join("a"),
2282
        "src/lib.rs",
2283
        b"pub fn a() {}\npub fn b() {}\n",
2284
    );
2285
    let h2 = a.commit("edit lib", &[]).unwrap();
2286
    let st = a.load_state(&[h2]).unwrap().materialize();
2287
    assert!(
2288
        st.files.contains_key("docs/guide.md"),
2289
        "the state still has everything"
2290
    );
2291
    assert!(a.push("origin", false).unwrap()[0].ok);
2292
    origin.refresh().unwrap();
2293
    // Files created outside the scope are ignored by status.
2294
    write(&root.join("a"), "docs/new.md", b"ignored\n");
2295
    assert!(a.snapshot("status").unwrap().statuses.is_empty());
2296
2297
    // Widening the filter checks out the rest; narrowing leaves stray files alone.
2298
    let mut a = a;
2299
    a.config.set("filter.paths", "src,docs").unwrap();
2300
    a.save_config().unwrap();
2301
    let r = a
2302
        .checkout(&a.bookmark_heads().unwrap(), true, "widen")
2303
        .unwrap();
2304
    assert!(r.written >= 2);
2305
    assert_eq!(
2306
        fs::read(root.join("a/docs/logo.png")).unwrap(),
2307
        logo,
2308
        "now fetched lazily"
2309
    );
2310
    assert!(!root.join("a/README.md").exists());
2311
    // Origin sees the change made under a sparse checkout with the full tree intact.
2312
    origin.pull("origin").err();
2313
    let full = origin
2314
        .load_state(&origin.bookmark_heads().unwrap())
2315
        .unwrap()
2316
        .materialize();
2317
    assert!(
2318
        matches!(&full.files["src/lib.rs"].content, FileContent::Text { bytes, .. } if bytes == b"pub fn a() {}\npub fn b() {}\n")
2319
    );
2320
    assert!(full.files.contains_key("README.md"));
2321
    let _ = h1;
2322
}
2323
2324
#[test]
2325
fn shallow_clone_and_deepen() {
2326
    hermetic();
2327
    let dir = tempfile::tempdir().unwrap();
2328
    let root = dir.path();
2329
    let origin_dir = root.join("origin");
2330
    let origin = Repo::init(&origin_dir)
2331
        .unwrap()
2332
        .with_home(root.join("home"));
2333
    let mut hashes = Vec::new();
2334
    for i in 0..8 {
2335
        write(
2336
            &origin_dir,
2337
            "a.txt",
2338
            format!(
2339
                "{}\n",
2340
                (0..=i)
2341
                    .map(|k| k.to_string())
2342
                    .collect::<Vec<_>>()
2343
                    .join("\n")
2344
            )
2345
            .as_bytes(),
2346
        );
2347
        hashes.push(origin.commit(&format!("c{i}"), &[]).unwrap());
2348
    }
2349
    let url = origin_dir.to_string_lossy().to_string();
2350
    let a = Repo::clone_shallow(&url, &root.join("a"), 3, None, &[])
2351
        .unwrap()
2352
        .with_home(root.join("home"));
2353
    assert!(a.is_shallow());
2354
    assert_eq!(
2355
        fs::read_to_string(root.join("a/a.txt")).unwrap(),
2356
        "0\n1\n2\n3\n4\n5\n6\n7\n"
2357
    );
2358
    assert!(
2359
        a.store().has(&hashes[7]) && a.store().has(&hashes[5]),
2360
        "three levels present"
2361
    );
2362
    assert!(!a.store().has(&hashes[4]), "beyond the depth is absent");
2363
    assert_eq!(a.boundary(), [hashes[4]].into_iter().collect());
2364
    assert_eq!(
2365
        a.log().unwrap().len(),
2366
        9,
2367
        "the log shows every change from the checkpoint's metadata"
2368
    );
2369
    assert!(!a.snapshot("status").unwrap().changed);
2370
    assert_eq!(a.quick_status().unwrap().heads, 1);
2371
2372
    // Work continues on top of the shallow history and pushes back.
2373
    write(&root.join("a"), "a.txt", b"0\n1\n2\n3\n4\n5\n6\n7\n8\n");
2374
    let h_new = a.commit("c8", &[]).unwrap();
2375
    assert!(a.push("origin", false).unwrap()[0].ok);
2376
    origin.refresh().unwrap();
2377
    assert_eq!(origin.bookmark_heads().unwrap(), vec![h_new]);
2378
    // Fetching new work from origin into the shallow clone works too.
2379
    write(&origin_dir, "b.txt", b"b\n");
2380
    origin.pull("origin").err();
2381
    let (_, wc) = origin.working_copy().unwrap();
2382
    let _ = wc;
2383
    origin
2384
        .checkout(&origin.bookmark_heads().unwrap(), true, "co")
2385
        .unwrap();
2386
    write(&origin_dir, "b.txt", b"b\n");
2387
    let h_b = origin.commit("b", &[]).unwrap();
2388
    let pr = a.pull("origin").unwrap();
2389
    assert!(pr.changed);
2390
    assert!(a.store().has(&h_b));
2391
    assert!(root.join("a/b.txt").exists());
2392
2393
    // Deepening fetches older history until the boundary is gone.
2394
    // Every commit also depends on the change that created the file, so two
2395
    // levels below the boundary hold h4, h3, and the root.
2396
    assert!(a.deepen("origin", 2).unwrap() >= 2);
2397
    assert!(a.store().has(&hashes[3]));
2398
    assert!(a.is_shallow());
2399
    a.deepen("origin", 100).unwrap();
2400
    assert!(!a.is_shallow(), "boundary reached the root");
2401
    assert!(a.store().has(&hashes[0]));
2402
    assert_eq!(
2403
        a.load_state_full(&a.bookmark_heads().unwrap())
2404
            .unwrap()
2405
            .len(),
2406
        10
2407
    );
2408
}
2409
2410
#[test]
2411
fn tags_are_immutable_named_states_and_travel() {
2412
    hermetic();
2413
    let dir = tempfile::tempdir().unwrap();
2414
    let root = dir.path();
2415
    let origin = Repo::init(&root.join("origin")).unwrap();
2416
    let url = root.join("origin").to_string_lossy().to_string();
2417
    let mut a = Repo::clone(&url, &root.join("a"))
2418
        .unwrap()
2419
        .with_home(root.join("home-a"));
2420
    let (key_a, _) = a
2421
        .create_identity("Ada", "[email protected]", IdentityScope::User)
2422
        .unwrap();
2423
    write(&root.join("a"), "f.txt", b"1\n");
2424
    let h1 = a.commit("one", &[]).unwrap();
2425
    write(&root.join("a"), "f.txt", b"1\n2\n");
2426
    let h2 = a.commit("two", &[]).unwrap();
2427
2428
    let t = a.tag_create("v1", &[h1], "first release").unwrap();
2429
    assert_eq!(
2430
        (t.heads.clone(), t.signer.as_deref()),
2431
        (vec![h1], Some("Ada"))
2432
    );
2433
    assert!(a.tag_create("v1", &[h2], "").is_err(), "immutable");
2434
    assert!(a.tag_create("bad/name", &[h2], "").is_err());
2435
    assert_eq!(a.tag_heads("v1").unwrap(), Some(vec![h1]));
2436
    assert_eq!(a.resolve_heads("v1").unwrap(), vec![h1]);
2437
    assert_eq!(a.resolve_heads("main").unwrap(), vec![h2]);
2438
    let (_, sa) = a.tag_attest("v1").unwrap().unwrap();
2439
    assert_eq!(sa.sigs[0].key, key_a);
2440
    // Checkout by tag.
2441
    a.checkout(&a.resolve_heads("v1").unwrap(), false, "co")
2442
        .unwrap();
2443
    assert_eq!(fs::read(root.join("a/f.txt")).unwrap(), b"1\n");
2444
    a.checkout(&a.bookmark_heads().unwrap(), false, "co")
2445
        .unwrap();
2446
2447
    // Push carries the tag; a second attestation for the name is refused.
2448
    let r = a.push("origin", false).unwrap();
2449
    origin.refresh().unwrap();
2450
    assert!(r.iter().any(|x| x.name == "tags/v1" && x.ok), "{r:?}");
2451
    assert_eq!(origin.tag_heads("v1").unwrap(), Some(vec![h1]));
2452
    let mut forged = a
2453
        .tag_refs()
2454
        .unwrap()
2455
        .into_iter()
2456
        .find(|t| t.name == "v1")
2457
        .unwrap();
2458
    forged.state = origin
2459
        .store()
2460
        .put_state(&StateObject::new(vec![h2]))
2461
        .unwrap();
2462
    forged.heads = vec![h2];
2463
    forged.attestation = None;
2464
    let r = origin
2465
        .receive_push(Bundle::default(), vec![], None, vec![forged])
2466
        .unwrap();
2467
    assert!(!r[0].ok && r[0].reason.contains("immutable"), "{r:?}");
2468
2469
    // A clone gets the tag; a later tag arrives on fetch.
2470
    let b = Repo::clone(&url, &root.join("b"))
2471
        .unwrap()
2472
        .with_home(root.join("home-b"));
2473
    assert_eq!(b.tag_heads("v1").unwrap(), Some(vec![h1]));
2474
    assert!(b.tags().unwrap()[0].signer.as_deref() == Some("Ada"));
2475
    a.tag_create("v2", &[h2], "second").unwrap();
2476
    a.push("origin", false).unwrap();
2477
    origin.refresh().unwrap();
2478
    let rep = b.fetch("origin").unwrap();
2479
    assert_eq!(rep.new_tags, 1);
2480
    assert_eq!(b.tag_heads("v2").unwrap(), Some(vec![h2]));
2481
2482
    // Under a policy, an unattested tag is refused and an attested one by the root passes.
2483
    a.policy_init().unwrap();
2484
    a.push("origin", false).unwrap();
2485
    origin.refresh().unwrap();
2486
    let unattested = crate::protocol::TagRef {
2487
        name: "v3".into(),
2488
        state: origin
2489
            .store()
2490
            .put_state(&StateObject::new(vec![h2]))
2491
            .unwrap(),
2492
        heads: vec![h2],
2493
        attestation: None,
2494
    };
2495
    let r = origin
2496
        .receive_push(Bundle::default(), vec![], None, vec![unattested])
2497
        .unwrap();
2498
    assert!(!r[0].ok && r[0].reason.contains("attestation"), "{r:?}");
2499
    a.tag_create("v3", &[h2], "").unwrap();
2500
    let r = a.push("origin", false).unwrap();
2501
    origin.refresh().unwrap();
2502
    assert!(r.iter().any(|x| x.name == "tags/v3" && x.ok), "{r:?}");
2503
    assert!(a.gc(true).is_ok());
2504
    assert_eq!(a.tags().unwrap().len(), 3, "tags survive gc");
2505
2506
    // After a rotation the policy names only the new key, yet a fresh clone
2507
    // still takes the tags the old key made before it; the old key makes
2508
    // nothing new.
2509
    let rot = a.rotate_identity().unwrap();
2510
    let r = a.push("origin", false).unwrap();
2511
    origin.refresh().unwrap();
2512
    assert!(r.iter().all(|x| x.ok), "{r:?}");
2513
    let c = Repo::clone(&url, &root.join("c"))
2514
        .unwrap()
2515
        .with_home(root.join("home-c"));
2516
    assert_eq!(c.tag_heads("v3").unwrap(), Some(vec![h2]));
2517
    let (_, sp) = c.current_policy().unwrap().unwrap();
2518
    assert!(!sp.policy.authorizes(&key_a, "tags/v9"));
2519
    let made = c.identity(&rot.new).unwrap().created;
2520
    assert!(c.predecessor_authorized(&sp.policy, &key_a, "tags/v9", made - 1));
2521
    assert!(!c.predecessor_authorized(&sp.policy, &key_a, "tags/v9", made));
2522
    assert!(!c.predecessor_authorized(&sp.policy, &rot.new, "tags/v9", 0));
2523
}
2524
2525
#[test]
2526
fn multiple_workspaces_share_a_repository() {
2527
    hermetic();
2528
    let dir = tempfile::tempdir().unwrap();
2529
    let root = dir.path();
2530
    let main_dir = root.join("main");
2531
    let repo = Repo::init(&main_dir).unwrap().with_home(root.join("home"));
2532
    write(&main_dir, "a.txt", b"a\n");
2533
    let h1 = repo.commit("a", &[]).unwrap();
2534
    assert_eq!(repo.workspaces().unwrap().len(), 1);
2535
2536
    // A second workspace elsewhere, checked out on the bookmark.
2537
    let ws_dir = root.join("ws2");
2538
    let ws = repo.workspace_add(&ws_dir, None).unwrap();
2539
    assert!(ws_dir.join(".oxy").is_file());
2540
    assert_eq!(fs::read(ws_dir.join("a.txt")).unwrap(), b"a\n");
2541
    assert_ne!(ws.workspace(), repo.workspace());
2542
    let list = repo.workspaces().unwrap();
2543
    assert_eq!(list.len(), 2);
2544
    assert!(list
2545
        .iter()
2546
        .any(|w| w.id == ws.workspace() && w.path == ws_dir.canonicalize().unwrap() && !w.current));
2547
    assert!(!ws.snapshot("status").unwrap().changed);
2548
2549
    // Work in the second workspace: its own working copy, shared bookmark.
2550
    write(&ws_dir, "b.txt", b"b\n");
2551
    let s = ws.snapshot("status").unwrap();
2552
    assert_eq!(s.statuses.len(), 1);
2553
    assert!(
2554
        !repo.snapshot("status").unwrap().changed,
2555
        "the first workspace is untouched"
2556
    );
2557
    let h2 = ws.commit("b from ws2", &[]).unwrap();
2558
    repo.refresh().unwrap();
2559
    let mut heads = repo.bookmark_heads().unwrap();
2560
    heads.sort();
2561
    let mut want = vec![h1, h2];
2562
    want.sort();
2563
    assert_eq!(heads, want, "both workspaces see the bookmark move");
2564
    assert!(!main_dir.join("b.txt").exists());
2565
    repo.checkout(&repo.bookmark_heads().unwrap(), false, "co")
2566
        .unwrap();
2567
    assert!(main_dir.join("b.txt").exists());
2568
2569
    // Reopening from inside the second workspace finds the shared repository.
2570
    let reopened = Repo::open(&ws_dir).unwrap();
2571
    assert_eq!(reopened.workspace(), ws.workspace());
2572
    assert_eq!(reopened.id().unwrap(), repo.id().unwrap());
2573
    assert_eq!(reopened.quick_status().unwrap().heads, 2);
2574
2575
    // Workspaces cannot nest; forget drops one from the view but keeps files.
2576
    assert!(repo.workspace_add(&main_dir.join("inner"), None).is_err());
2577
    assert!(repo.workspace_forget(&repo.workspace()).is_err());
2578
    repo.workspace_forget(&ws.workspace()).unwrap();
2579
    assert_eq!(repo.workspaces().unwrap().len(), 1);
2580
    assert!(ws_dir.join("b.txt").exists());
2581
    assert!(
2582
        ws.snapshot("status").is_err(),
2583
        "a forgotten workspace is no longer in the view"
2584
    );
2585
2586
    // The working-copy lock: re-entrant in a thread; a lock whose process
2587
    // is gone is taken over, and a live process's is not, however old.
2588
    let lock = repo.lock_snapshot().unwrap();
2589
    let again = repo.lock_working_copy().unwrap();
2590
    drop(again);
2591
    drop(lock);
2592
    let lock_path = main_dir
2593
        .join(".oxy/workspaces")
2594
        .join(repo.workspace().to_hex())
2595
        .join("lock");
2596
    let old = std::time::SystemTime::now() - std::time::Duration::from_secs(120);
2597
    let age = |p: &Path| fs::File::open(p).unwrap().set_modified(old).unwrap();
2598
    fs::write(&lock_path, std::process::id().to_string()).unwrap();
2599
    age(&lock_path);
2600
    assert!(
2601
        !super::workspace::lock_is_stale(&lock_path),
2602
        "a live process keeps its lock"
2603
    );
2604
    fs::write(&lock_path, "4294967295").unwrap();
2605
    age(&lock_path);
2606
    assert!(repo.lock_snapshot().is_ok(), "stale lock taken over");
2607
}
2608
2609
#[test]
2610
fn attributes_binary_eol_nocompress_lockable() {
2611
    hermetic();
2612
    let dir = tempfile::tempdir().unwrap();
2613
    let root = dir.path();
2614
    let repo = Repo::init(root).unwrap().with_home(root.join("home"));
2615
    write(
2616
        root,
2617
        ".oxyattributes",
2618
        b"*.dat binary nocompress\n*.txt eol=crlf\nassets/** lockable\n",
2619
    );
2620
    write(root, "plain.dat", b"no nul bytes here\n");
2621
    write(root, "notes.txt", b"one\r\ntwo\r\n");
2622
    write(root, "assets/model.bin", b"\0model");
2623
    let h = repo.commit("attrs", &[]).unwrap();
2624
    let snap = repo.load_state(&[h]).unwrap().materialize();
2625
    assert!(
2626
        snap.files["plain.dat"].mode.opaque,
2627
        "binary attribute forces opaque without NUL bytes"
2628
    );
2629
    assert!(
2630
        matches!(&snap.files["notes.txt"].content, FileContent::Text { bytes, .. } if bytes == b"one\ntwo\n"),
2631
        "stored with LF"
2632
    );
2633
    assert!(
2634
        !repo.snapshot("status").unwrap().changed,
2635
        "CRLF on disk equals LF in the state"
2636
    );
2637
    // nocompress chunks pack raw.
2638
    let r = repo.gc(true).unwrap();
2639
    assert!(r.packed.objects > 0);
2640
    // Checkout writes CRLF for eol=crlf and makes lockable files read-only.
2641
    fs::remove_file(root.join("notes.txt")).unwrap();
2642
    repo.checkout(&[h], true, "co").unwrap();
2643
    assert_eq!(fs::read(root.join("notes.txt")).unwrap(), b"one\r\ntwo\r\n");
2644
    assert!(fs::metadata(root.join("assets/model.bin"))
2645
        .unwrap()
2646
        .permissions()
2647
        .readonly());
2648
    assert!(repo.lock_path("plain.dat").is_err(), "not lockable");
2649
    repo.lock_path("assets/model.bin").unwrap();
2650
    assert!(!fs::metadata(root.join("assets/model.bin"))
2651
        .unwrap()
2652
        .permissions()
2653
        .readonly());
2654
    assert!(repo.is_locked("assets/model.bin"));
2655
    write(root, "assets/model.bin", b"\0model2");
2656
    repo.commit("edit model", &[]).unwrap();
2657
    repo.unlock_path("assets/model.bin").unwrap();
2658
    assert!(fs::metadata(root.join("assets/model.bin"))
2659
        .unwrap()
2660
        .permissions()
2661
        .readonly());
2662
    // A later checkout can still overwrite a read-only lockable file.
2663
    repo.checkout(&[h], true, "co").unwrap();
2664
    assert_eq!(fs::read(root.join("assets/model.bin")).unwrap(), b"\0model");
2665
}
2666
2667
#[cfg(unix)]
2668
#[test]
2669
fn hooks_can_veto_observe_and_add_dependencies() {
2670
    use std::os::unix::fs::PermissionsExt;
2671
    hermetic();
2672
    let dir = tempfile::tempdir().unwrap();
2673
    let root = dir.path();
2674
    let mut repo = Repo::init(root).unwrap().with_home(root.join("home"));
2675
    let hooks = root.join(".oxy/hooks");
2676
    fs::create_dir_all(&hooks).unwrap();
2677
    let hook = |name: &str, body: &str| {
2678
        let p = hooks.join(name);
2679
        fs::write(&p, format!("#!/bin/sh\n{body}\n")).unwrap();
2680
        fs::set_permissions(&p, fs::Permissions::from_mode(0o755)).unwrap();
2681
    };
2682
    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");
2683
    hook("post-commit", "cat > \"$OXY_ROOT/.last-post-commit\"");
2684
    hook("post-checkout", "cat > \"$OXY_ROOT/.last-post-checkout\"");
2685
    hook("pre-push", "echo pushing blocked >&2; exit 3");
2686
    write(root, ".oxyignore", b".last-*\n");
2687
    write(root, "a.txt", b"a\n");
2688
    let err = repo.commit("WIP: nope", &[]).unwrap_err().to_string();
2689
    assert!(err.contains("pre-commit refused: no WIP commits"), "{err}");
2690
    let h1 = repo.commit("first", &[]).unwrap();
2691
    let pre = fs::read_to_string(root.join(".last-pre-commit")).unwrap();
2692
    assert!(
2693
        pre.contains("\"event\":\"pre-commit\"")
2694
            && pre.contains("\"path\":\"a.txt\"")
2695
            && pre.contains("\"message\":\"first\""),
2696
        "{pre}"
2697
    );
2698
    let post = fs::read_to_string(root.join(".last-post-commit")).unwrap();
2699
    assert!(post.contains(&h1.to_hex()), "{post}");
2700
    repo.checkout(&[h1], false, "co").unwrap();
2701
    assert!(fs::read_to_string(root.join(".last-post-checkout"))
2702
        .unwrap()
2703
        .contains("post-checkout"));
2704
    repo.config.set("remote.origin.url", "/nowhere").unwrap();
2705
    repo.save_config().unwrap();
2706
    let err = repo.push("origin", false).unwrap_err().to_string();
2707
    assert!(err.contains("pre-push refused: pushing blocked"), "{err}");
2708
2709
    // semantic-deps: only when enabled; adds an explicit dependency.
2710
    write(root, "b.txt", b"b\n");
2711
    hook(
2712
        "semantic-deps",
2713
        &format!(
2714
            "cat > \"$OXY_ROOT/.last-semantic\"; echo '{{\"deps\": [\"{}\"]}}'",
2715
            h1.to_hex()
2716
        ),
2717
    );
2718
    let h2 = repo.commit("b without hook", &[]).unwrap();
2719
    assert!(
2720
        repo.store().get_change(&h2).unwrap().deps.is_empty(),
2721
        "hook disabled by default"
2722
    );
2723
    repo.config.set("hooks.semantic-deps", "true").unwrap();
2724
    repo.save_config().unwrap();
2725
    write(root, "c.txt", b"c\n");
2726
    let h3 = repo.commit("c with hook", &[]).unwrap();
2727
    assert_eq!(repo.store().get_change(&h3).unwrap().deps, vec![h1]);
2728
    let sem = fs::read_to_string(root.join(".last-semantic")).unwrap();
2729
    assert!(
2730
        sem.contains("\"touched_paths\":[\"c.txt\"]") && sem.contains("candidate_deps"),
2731
        "{sem}"
2732
    );
2733
    assert_eq!(json_str("a\"b\\c\n"), "\"a\\\"b\\\\c\\n\"");
2734
}
2735
2736
#[test]
2737
fn amend_into_older_change_and_split() {
2738
    hermetic();
2739
    let dir = tempfile::tempdir().unwrap();
2740
    let root = dir.path();
2741
    let mut repo = Repo::init(root).unwrap().with_home(root.join("home"));
2742
    repo.create_identity("Ada", "a@b", IdentityScope::User)
2743
        .unwrap();
2744
    repo.set_user_config("core.sign", "change").unwrap();
2745
    write(root, "a.txt", b"one\ntwo\n");
2746
    let h0 = repo.commit("base", &[]).unwrap();
2747
    write(root, "a.txt", b"one\nTWO\n");
2748
    let h1 = repo.commit("edit two", &[]).unwrap();
2749
    write(root, "a.txt", b"one\nTWO\nthree\n");
2750
    let h2 = repo.commit("add three", &[]).unwrap();
2751
    let id1 = repo.store().get_change(&h1).unwrap().change_id;
2752
2753
    // Fixing the line h1 introduced folds into h1; h2 is rewritten on top.
2754
    write(root, "a.txt", b"one\nTWO!\nthree\n");
2755
    let h1b = repo.amend_into(&h1, None).unwrap();
2756
    assert_ne!(h1b, h1);
2757
    let c1b = repo.store().get_change(&h1b).unwrap();
2758
    assert_eq!(c1b.change_id, id1);
2759
    assert_eq!(c1b.deps, vec![h0]);
2760
    assert!(matches!(
2761
        repo.verify_change(&h1b).unwrap(),
2762
        SignatureStatus::Valid { .. }
2763
    ));
2764
    let heads = repo.bookmark_heads().unwrap();
2765
    assert_eq!(heads.len(), 1);
2766
    let top = repo.store().get_change(&heads[0]).unwrap();
2767
    assert_eq!(top.message, "add three");
2768
    assert_eq!(
2769
        top.deps.iter().copied().collect::<BTreeSet<_>>(),
2770
        [h0, h1b].into_iter().collect(),
2771
        "depends on the file's creator and the rewritten line"
2772
    );
2773
    let snap = repo.load_state(&heads).unwrap().materialize();
2774
    assert!(
2775
        matches!(&snap.files["a.txt"].content, FileContent::Text { bytes, .. } if bytes == b"one\nTWO!\nthree\n")
2776
    );
2777
    assert!(
2778
        !repo.snapshot("status").unwrap().changed,
2779
        "the working copy is clean after folding"
2780
    );
2781
    // Only h1b's own state shows the fix without "three".
2782
    let only = repo.load_state(&[h1b]).unwrap().materialize();
2783
    assert!(
2784
        matches!(&only.files["a.txt"].content, FileContent::Text { bytes, .. } if bytes == b"one\nTWO!\n")
2785
    );
2786
    assert_eq!(repo.log().unwrap().len(), 4);
2787
2788
    // An edit to a line introduced by h2 cannot fold into h1.
2789
    write(root, "a.txt", b"one\nTWO!\nthree!\n");
2790
    let err = repo.amend_into(&h1b, None).unwrap_err().to_string();
2791
    assert!(err.contains("introduced after"), "{err}");
2792
    assert!(
2793
        repo.snapshot("status").unwrap().statuses.len() == 1,
2794
        "nothing was changed by the refusal"
2795
    );
2796
    write(root, "a.txt", b"one\nTWO!\nthree\n");
2797
2798
    // Split the head that touches two files.
2799
    write(root, "b.txt", b"b\n");
2800
    write(root, "c.txt", b"c\n");
2801
    let h3 = repo.commit("b and c", &[]).unwrap();
2802
    let id3 = repo.store().get_change(&h3).unwrap().change_id;
2803
    let (p1, p2) = repo.split(&h3, &["b.txt".into()]).unwrap();
2804
    let c_1 = repo.store().get_change(&p1).unwrap();
2805
    let c_2 = repo.store().get_change(&p2).unwrap();
2806
    assert!(c_1.message.contains("part 1: b.txt"));
2807
    assert_eq!(c_2.change_id, id3);
2808
    let heads: BTreeSet<_> = repo.bookmark_heads().unwrap().into_iter().collect();
2809
    assert!(
2810
        heads.contains(&p1) && heads.contains(&p2),
2811
        "independent parts are both heads"
2812
    );
2813
    let snap = repo
2814
        .load_state(&repo.bookmark_heads().unwrap())
2815
        .unwrap()
2816
        .materialize();
2817
    assert!(snap.files.contains_key("b.txt") && snap.files.contains_key("c.txt"));
2818
    let only1 = repo.load_state(&[p1]).unwrap().materialize();
2819
    assert!(only1.files.contains_key("b.txt") && !only1.files.contains_key("c.txt"));
2820
    assert!(!repo.snapshot("status").unwrap().changed);
2821
    assert!(repo.split(&p2, &["nope.txt".into()]).is_err());
2822
    let _ = h2;
2823
}
2824
2825
#[test]
2826
fn identity_lifecycle() {
2827
    hermetic();
2828
    let dir = tempfile::tempdir().unwrap();
2829
    let root = dir.path();
2830
    let origin = Repo::init(&root.join("origin")).unwrap();
2831
    let url = root.join("origin").to_string_lossy().to_string();
2832
    let mut a = Repo::clone(&url, &root.join("a"))
2833
        .unwrap()
2834
        .with_home(root.join("home-a"));
2835
    a.set_user_config("core.sign", "change").unwrap();
2836
    let (key_a, _) = a
2837
        .create_identity("Ada", "[email protected]", IdentityScope::User)
2838
        .unwrap();
2839
    write(&root.join("a"), "a.txt", b"a\n");
2840
    let h1 = a.commit("one", &[]).unwrap();
2841
    assert!(a.policy_init().unwrap().applied);
2842
    assert!(a.push("origin", false).unwrap().iter().all(|r| r.ok));
2843
    origin.refresh().unwrap();
2844
2845
    // Expiry: an identity that had expired when the change was made does not authenticate it.
2846
    let mut e = Repo::init(&root.join("e"))
2847
        .unwrap()
2848
        .with_home(root.join("home-e"));
2849
    e.set_user_config("core.sign", "change").unwrap();
2850
    e.create_identity_with(
2851
        "Eve",
2852
        "[email protected]",
2853
        IdentityScope::User,
2854
        Some(Hlc::now().wall_ms - 1),
2855
    )
2856
    .unwrap();
2857
    write(&root.join("e"), "e.txt", b"e\n");
2858
    let he = e.commit("late", &[]).unwrap();
2859
    assert!(
2860
        matches!(e.verify_change(&he).unwrap(), SignatureStatus::Invalid(m) if m.contains("expired"))
2861
    );
2862
    // Renewal re-issues the identity (same keys, new KeyId) with a later expiry.
2863
    let r = e
2864
        .renew_identity(Some(Hlc::now().wall_ms + 86_400_000))
2865
        .unwrap();
2866
    assert_eq!(e.identity(&r.new).unwrap().previous, Some(r.old));
2867
    write(&root.join("e"), "e.txt", b"e2\n");
2868
    let he2 = e.commit("in time", &[]).unwrap();
2869
    assert!(
2870
        matches!(e.verify_change(&he2).unwrap(), SignatureStatus::Valid { key, .. } if key == r.new)
2871
    );
2872
2873
    // Rotation: a fresh key; the old change still verifies; the policy follows.
2874
    let r = a.rotate_identity().unwrap();
2875
    assert_eq!(r.old, key_a);
2876
    assert_eq!(a.config.author_key, Some(r.new));
2877
    assert_eq!(a.identity(&r.new).unwrap().previous, Some(key_a));
2878
    assert!(r.policy.as_ref().unwrap().applied);
2879
    let (_, sp) = a.current_policy().unwrap().unwrap();
2880
    assert_eq!(
2881
        (sp.policy.serial, sp.policy.roots.clone()),
2882
        (2, vec![r.new])
2883
    );
2884
    assert!(
2885
        !sp.policy.revoked.contains(&key_a) && sp.policy.authorizes(&r.new, "main"),
2886
        "superseded, not revoked"
2887
    );
2888
    assert!(sp.policy.succeeds(&r.new, &key_a) && !sp.policy.succeeds(&key_a, &r.new));
2889
    assert!(
2890
        matches!(a.verify_change(&h1).unwrap(), SignatureStatus::Valid { key, revoked: false, .. } if key == key_a)
2891
    );
2892
    write(&root.join("a"), "a.txt", b"a2\n");
2893
    let h2 = a.commit("two", &[]).unwrap();
2894
    assert!(
2895
        matches!(a.verify_change(&h2).unwrap(), SignatureStatus::Valid { key, revoked: false, .. } if key == r.new)
2896
    );
2897
    // Origin accepts the rotated policy (signed by the old root) and the new key's change.
2898
    let res = a.push("origin", false).unwrap();
2899
    origin.refresh().unwrap();
2900
    assert!(res.iter().all(|x| x.ok), "{res:?}");
2901
    assert_eq!(origin.current_policy().unwrap().unwrap().1.policy.serial, 2);
2902
    let key_a = r.new;
2903
2904
    // Delegation: Bob may sign on Ada's behalf. Delegates live in the
2905
    // identity object, so Ada's KeyId changes while her keys stay the same.
2906
    let mut b = Repo::clone(&url, &root.join("b"))
2907
        .unwrap()
2908
        .with_home(root.join("home-b"));
2909
    let (key_b, id_b) = b
2910
        .create_identity("Bob", "[email protected]", IdentityScope::User)
2911
        .unwrap();
2912
    let r = a.delegate_add(id_b.clone(), Scope::ALL, None).unwrap();
2913
    assert_eq!(r.old, key_a);
2914
    let key_a2 = r.new;
2915
    assert_eq!(
2916
        a.identity(&key_a2).unwrap().delegates,
2917
        vec![Delegate::full(key_b)]
2918
    );
2919
    assert_eq!(
2920
        a.identity(&key_a2).unwrap().ed25519_pk,
2921
        a.identity(&key_a).unwrap().ed25519_pk
2922
    );
2923
    assert!(
2924
        a.delegate_add(id_b.clone(), Scope::ALL, None).is_err(),
2925
        "already a delegate"
2926
    );
2927
    assert!(a.push("origin", false).unwrap().iter().all(|x| x.ok));
2928
    origin.refresh().unwrap();
2929
    write(&root.join("a"), "a.txt", b"a3\n");
2930
    let h3 = a.commit("three", &[]).unwrap();
2931
    assert!(
2932
        matches!(a.verify_change(&h3).unwrap(), SignatureStatus::Valid { key, .. } if key == key_a2),
2933
        "the same secret signs under the new KeyId"
2934
    );
2935
    // A change authored by Ada but signed only by Bob verifies through the delegation.
2936
    a.set_user_config("core.sign", "seal").unwrap();
2937
    write(&root.join("a"), "a.txt", b"a4\n");
2938
    let h4 = a.commit("four", &[]).unwrap();
2939
    assert_eq!(a.verify_change(&h4).unwrap(), SignatureStatus::Unsigned);
2940
    let (_, sk_b) = b.secret_key().unwrap().unwrap();
2941
    a.store()
2942
        .put_signature(&h4, &sk_b.sign(Domain::Change, &key_b, &h4))
2943
        .unwrap();
2944
    assert!(
2945
        matches!(a.verify_change(&h4).unwrap(), SignatureStatus::Valid { key, .. } if key == key_b)
2946
    );
2947
    a.set_user_config("core.sign", "change").unwrap();
2948
    // Withdrawing the delegation re-issues the identity again.
2949
    let r = a.delegate_remove(&key_b).unwrap();
2950
    assert!(a.identity(&r.new).unwrap().delegates.is_empty());
2951
    assert!(a.delegate_remove(&key_b).is_err());
2952
    let key_a3 = r.new;
2953
    let res = a.push("origin", false).unwrap();
2954
    origin.refresh().unwrap();
2955
    assert!(res.iter().all(|x| x.ok), "{res:?}");
2956
2957
    // Multi-signer policy: Bob becomes a root and the threshold rises to 2,
2958
    // both applied under the old threshold of 1. A grant then needs Bob too.
2959
    assert!(a.policy_root_add(id_b.clone()).unwrap().applied);
2960
    assert!(a.policy_root_add(id_b.clone()).is_err());
2961
    assert!(a.policy_set_threshold(3).is_err());
2962
    assert!(a.policy_set_threshold(2).unwrap().applied);
2963
    assert!(a.push("origin", false).unwrap().iter().all(|x| x.ok));
2964
    origin.refresh().unwrap();
2965
    b.pull("origin").unwrap();
2966
    assert_eq!(
2967
        b.current_policy().unwrap().unwrap().1.policy.root_threshold,
2968
        2
2969
    );
2970
    let mut c = Repo::init(&root.join("c"))
2971
        .unwrap()
2972
        .with_home(root.join("home-c"));
2973
    let (key_c, id_c) = c
2974
        .create_identity("Cy", "[email protected]", IdentityScope::User)
2975
        .unwrap();
2976
    let serial_before = a.current_policy().unwrap().unwrap().1.policy.serial;
2977
    let proposal = a.policy_grant(id_c, None).unwrap();
2978
    assert!(!proposal.applied && proposal.sigs.len() == 1);
2979
    assert_eq!(proposal.policy.serial, serial_before + 1);
2980
    assert_eq!(
2981
        a.current_policy().unwrap().unwrap().1.policy.serial,
2982
        serial_before,
2983
        "a proposal changes nothing yet"
2984
    );
2985
    // Bob signs the proposal, handed over as a file, and it applies for him.
2986
    let bytes = proposal.signed().encode();
2987
    let signed = b
2988
        .policy_sign(SignedPolicy::decode(&bytes).unwrap())
2989
        .unwrap();
2990
    assert!(signed.applied && signed.sigs.len() == 2);
2991
    assert!(b
2992
        .current_policy()
2993
        .unwrap()
2994
        .unwrap()
2995
        .1
2996
        .policy
2997
        .authorizes(&key_c, "main"));
2998
    assert!(
2999
        b.policy_sign(signed.signed()).is_err(),
3000
        "a stale proposal is refused"
3001
    );
3002
    // Bob publishes it and Ada picks it up.
3003
    assert!(b
3004
        .push("origin", false)
3005
        .unwrap()
3006
        .iter()
3007
        .any(|x| x.name == "policy" && x.ok));
3008
    origin.refresh().unwrap();
3009
    a.pull("origin").unwrap();
3010
    assert_eq!(
3011
        a.current_policy().unwrap().unwrap().1.policy.serial,
3012
        serial_before + 1
3013
    );
3014
    // A root cannot revoke itself; revoking Cy needs both roots but is recorded locally at once.
3015
    assert!(a.policy_revoke(&key_a3).is_err());
3016
    let u = a
3017
        .revoke_identity(&key_c, "left the project")
3018
        .unwrap()
3019
        .unwrap();
3020
    assert!(!u.applied);
3021
    assert!(a.is_revoked(&key_c).unwrap());
3022
    assert!(!b.is_revoked(&key_c).unwrap());
3023
    let u = b.policy_sign(u.signed()).unwrap();
3024
    assert!(u.applied && u.policy.is_revoked(&key_c));
3025
    assert!(b.is_revoked(&key_c).unwrap());
3026
    // Bob can revoke Ada's root key, leaving himself as the only root (threshold 2 would be unmeetable).
3027
    assert!(
3028
        b.policy_revoke(&key_a3).is_err(),
3029
        "would leave one root for a threshold of 2"
3030
    );
3031
    // Revoking one's own key without a policy root works locally: a plain marker plus attestation.
3032
    let key_c_own = c.config.author_key.unwrap();
3033
    assert!(c
3034
        .revoke_identity(&key_c_own, "lost laptop")
3035
        .unwrap()
3036
        .is_none());
3037
    assert!(c.is_revoked(&key_c_own).unwrap());
3038
    assert_eq!(key_c_own, key_c);
3039
}
3040
3041
#[test]
3042
fn renames_are_detected_and_tracked_as_moves() {
3043
    hermetic();
3044
    let dir = tempfile::tempdir().unwrap();
3045
    let root = dir.path();
3046
    let repo = Repo::init(root).unwrap().with_home(root.join("home"));
3047
    write(
3048
        root,
3049
        "src/old.rs",
3050
        b"fn a() {}\nfn b() {}\nfn c() {}\nfn d() {}\n",
3051
    );
3052
    write(root, "img.bin", b"\x89PNG\0\0\x01\x02");
3053
    write(root, "tiny.txt", b"x\n");
3054
    let h1 = repo.commit("base", &[]).unwrap();
3055
    let node_old = repo.load_state(&[h1]).unwrap().materialize().files["src/old.rs"].node;
3056
    let node_img = repo.load_state(&[h1]).unwrap().materialize().files["img.bin"].node;
3057
3058
    // Rename with a small edit, a binary moved unchanged, and a rewrite
3059
    // that shares nothing with the removed file.
3060
    fs::remove_file(root.join("src/old.rs")).unwrap();
3061
    write(
3062
        root,
3063
        "lib/new.rs",
3064
        b"fn a() {}\nfn b() {}\nfn c() {}\nfn e() {}\n",
3065
    );
3066
    fs::remove_file(root.join("img.bin")).unwrap();
3067
    write(root, "assets/img.bin", b"\x89PNG\0\0\x01\x02");
3068
    fs::remove_file(root.join("tiny.txt")).unwrap();
3069
    write(root, "other.txt", b"completely different\n");
3070
    let snap = repo.snapshot("status").unwrap();
3071
    let statuses: Vec<(&str, ChangeStatus)> = snap
3072
        .statuses
3073
        .iter()
3074
        .map(|s| (s.path.as_str(), s.status))
3075
        .collect();
3076
    assert_eq!(
3077
        statuses,
3078
        vec![
3079
            ("assets/img.bin", ChangeStatus::Renamed),
3080
            ("lib/new.rs", ChangeStatus::Renamed),
3081
            ("other.txt", ChangeStatus::Added),
3082
            ("src", ChangeStatus::Removed),
3083
            ("tiny.txt", ChangeStatus::Removed)
3084
        ]
3085
    );
3086
    let h2 = repo.commit("move things", &[]).unwrap();
3087
    let c = repo.store().get_change(&h2).unwrap();
3088
    let moves: Vec<_> = c
3089
        .tree_ops
3090
        .iter()
3091
        .filter(|op| matches!(op, TreeOp::Move { .. }))
3092
        .collect();
3093
    assert_eq!(moves.len(), 2, "{:?}", c.tree_ops);
3094
    assert!(c.tree_ops.iter().any(
3095
        |op| matches!(op, TreeOp::Move { node, name, .. } if *node == node_old && name == "new.rs")
3096
    ));
3097
    assert!(c.tree_ops.iter().any(
3098
        |op| matches!(op, TreeOp::Move { node, name, .. } if *node == node_img && name == "img.bin")
3099
    ));
3100
    let snap = repo.load_state(&[h2]).unwrap().materialize();
3101
    assert_eq!(
3102
        snap.files["lib/new.rs"].node, node_old,
3103
        "the node survives the rename"
3104
    );
3105
    assert!(
3106
        matches!(&snap.files["lib/new.rs"].content, FileContent::Text { bytes, .. } if bytes == b"fn a() {}\nfn b() {}\nfn c() {}\nfn e() {}\n")
3107
    );
3108
    assert!(!snap.files.contains_key("src/old.rs") && !snap.files.contains_key("src"));
3109
    assert!(render_change(
3110
        &c,
3111
        &repo.load_state(&[h1]).unwrap(),
3112
        &repo.load_state(&[h1]).unwrap().materialize()
3113
    )
3114
    .contains("R "));
3115
    // A fresh checkout reproduces the tree.
3116
    let other = tempfile::tempdir().unwrap();
3117
    let clone = Repo::clone(&root.to_string_lossy(), other.path()).unwrap();
3118
    assert_eq!(
3119
        fs::read(other.path().join("lib/new.rs")).unwrap(),
3120
        b"fn a() {}\nfn b() {}\nfn c() {}\nfn e() {}\n"
3121
    );
3122
    assert!(!other.path().join("src").exists());
3123
    assert!(!clone.snapshot("status").unwrap().changed);
3124
    // Similarity is line based, byte weighted.
3125
    assert_eq!(similarity(b"a\nb\n", b"a\nb\n"), 100);
3126
    assert_eq!(similarity(b"a\nb\nc\nd\n", b"a\nb\nx\ny\n"), 50);
3127
    assert_eq!(similarity(b"hello\n", b"world\n"), 0);
3128
    assert_eq!(similarity(b"", b"x\n"), 0);
3129
}
3130
3131
#[test]
3132
fn git_fetch_and_push_round_trip() {
3133
    hermetic();
3134
    if std::process::Command::new("git")
3135
        .arg("--version")
3136
        .output()
3137
        .is_err()
3138
    {
3139
        eprintln!("git not installed; skipping");
3140
        return;
3141
    }
3142
    let dir = tempfile::tempdir().unwrap();
3143
    let root = dir.path();
3144
    let git_in = |d: &Path, args: &[&str]| -> String {
3145
        let out = std::process::Command::new("git")
3146
            .arg("-C")
3147
            .arg(d)
3148
            .args([
3149
                "-c",
3150
                "user.name=Grace",
3151
                "-c",
3152
                "[email protected]",
3153
                "-c",
3154
                "commit.gpgsign=false",
3155
            ])
3156
            .args(args)
3157
            .output()
3158
            .unwrap();
3159
        assert!(
3160
            out.status.success(),
3161
            "git {args:?}: {}",
3162
            String::from_utf8_lossy(&out.stderr)
3163
        );
3164
        String::from_utf8_lossy(&out.stdout).trim().to_string()
3165
    };
3166
    // A bare "remote" and a work tree that pushes to it.
3167
    let remote = root.join("remote.git");
3168
    fs::create_dir_all(&remote).unwrap();
3169
    git_in(&remote, &["init", "-q", "--bare", "-b", "main"]);
3170
    let work = root.join("work");
3171
    git_in(
3172
        root,
3173
        &[
3174
            "clone",
3175
            "-q",
3176
            remote.to_str().unwrap(),
3177
            work.to_str().unwrap(),
3178
        ],
3179
    );
3180
    git_in(&work, &["checkout", "-q", "-b", "main"]);
3181
    write(&work, "README.md", b"# Project\n");
3182
    write(&work, "src/lib.rs", b"pub fn a() {}\n");
3183
    git_in(&work, &["add", "."]);
3184
    git_in(&work, &["commit", "-q", "-m", "initial"]);
3185
    write(&work, "src/lib.rs", b"pub fn a() {}\npub fn b() {}\n");
3186
    git_in(&work, &["commit", "-q", "-am", "second"]);
3187
    git_in(&work, &["push", "-q", "origin", "main"]);
3188
    let tip1 = git_in(&work, &["rev-parse", "HEAD"]);
3189
3190
    // Fetch into a fresh oxy repository.
3191
    let o = root.join("oxy");
3192
    let mut repo = Repo::init(&o).unwrap().with_home(root.join("home"));
3193
    repo.create_identity("Ada", "[email protected]", IdentityScope::User)
3194
        .unwrap();
3195
    let url = remote.to_string_lossy().to_string();
3196
    let r = repo.git_fetch(&url, "main").unwrap();
3197
    assert_eq!((r.commits, r.heads), (2, 1));
3198
    assert_eq!(
3199
        fs::read(o.join("src/lib.rs")).unwrap(),
3200
        b"pub fn a() {}\npub fn b() {}\n"
3201
    );
3202
    assert!(!repo.snapshot("status").unwrap().changed);
3203
    assert_eq!(
3204
        repo.git_fetch(&url, "main").unwrap().commits,
3205
        0,
3206
        "nothing new"
3207
    );
3208
3209
    // An oxy change, pushed back: one commit on top of the Git tip.
3210
    write(
3211
        &o,
3212
        "src/lib.rs",
3213
        b"pub fn a() {}\npub fn b() {}\npub fn c() {}\n",
3214
    );
3215
    write(&o, "NOTES.md", b"from oxy\n");
3216
    let h_oxy = repo.commit("add c and notes", &[]).unwrap();
3217
    let r = repo.git_push(&url, "main").unwrap();
3218
    assert_eq!(r.exported, 1, "{r:?}");
3219
    git_in(&work, &["pull", "-q", "--ff-only", "origin", "main"]);
3220
    assert_eq!(
3221
        git_in(&work, &["log", "--format=%s", "main"]),
3222
        "add c and notes\nsecond\ninitial"
3223
    );
3224
    assert_eq!(git_in(&work, &["rev-parse", "HEAD~1"]), tip1);
3225
    assert_eq!(fs::read(work.join("NOTES.md")).unwrap(), b"from oxy\n");
3226
    assert_eq!(git_in(&work, &["log", "-1", "--format=%an", "main"]), "Ada");
3227
    assert!(git_in(&work, &["log", "-1", "--format=%B", "main"])
3228
        .contains(&format!("Oxy-Hash: {}", h_oxy.to_hex())));
3229
    assert_eq!(
3230
        repo.git_push(&url, "main").unwrap().exported,
3231
        0,
3232
        "already pushed"
3233
    );
3234
3235
    // Git moves on; pushing without fetching is refused, fetching brings
3236
    // the commit in and the working copy follows.
3237
    write(&work, "README.md", b"# Project\n\nMore.\n");
3238
    git_in(&work, &["commit", "-q", "-am", "readme from git"]);
3239
    git_in(&work, &["push", "-q", "origin", "main"]);
3240
    let tip2 = git_in(&work, &["rev-parse", "HEAD"]);
3241
    assert!(repo
3242
        .git_push(&url, "main")
3243
        .unwrap_err()
3244
        .to_string()
3245
        .contains("fetch"));
3246
    let r = repo.git_fetch(&url, "main").unwrap();
3247
    assert_eq!(
3248
        (r.commits, r.heads),
3249
        (1, 2),
3250
        "the Git change and the oxy change commute"
3251
    );
3252
    assert_eq!(
3253
        fs::read(o.join("README.md")).unwrap(),
3254
        b"# Project\n\nMore.\n"
3255
    );
3256
    assert_eq!(fs::read(o.join("NOTES.md")).unwrap(), b"from oxy\n");
3257
    assert!(!repo.snapshot("status").unwrap().changed);
3258
    // Another oxy change pushes on top of Git's newest commit.
3259
    write(&o, "NOTES.md", b"from oxy\nagain\n");
3260
    repo.commit("notes again", &[]).unwrap();
3261
    assert_eq!(repo.git_push(&url, "main").unwrap().exported, 1);
3262
    git_in(&work, &["pull", "-q", "--ff-only", "origin", "main"]);
3263
    assert_eq!(git_in(&work, &["rev-parse", "HEAD~1"]), tip2);
3264
    assert_eq!(
3265
        fs::read(work.join("NOTES.md")).unwrap(),
3266
        b"from oxy\nagain\n"
3267
    );
3268
    assert_eq!(
3269
        git_in(&work, &["log", "--format=%s", "main"])
3270
            .lines()
3271
            .count(),
3272
        5
3273
    );
3274
}
3275
3276
/// Benchmark, not a gate: `cargo test --release -p oxy-core --lib bench_one_gibibyte -- --ignored --nocapture`.
3277
/// Commits, stores, clones, and reads back a 1 GiB incompressible file.
3278
#[test]
3279
#[ignore]
3280
fn bench_one_gibibyte_file() {
3281
    hermetic();
3282
    // /tmp is often a small tmpfs; `OXY_BENCH_DIR` picks a roomier disk.
3283
    let dir = match std::env::var_os("OXY_BENCH_DIR") {
3284
        Some(d) => tempfile::tempdir_in(d).unwrap(),
3285
        None => tempfile::tempdir().unwrap(),
3286
    };
3287
    let root = dir.path();
3288
    let repo = Repo::init(&root.join("r"))
3289
        .unwrap()
3290
        .with_home(root.join("home"));
3291
    let size = 1usize << 30;
3292
    let mut data = vec![0u8; size];
3293
    let mut x = 0x9e3779b97f4a7c15u64;
3294
    for chunk in data.chunks_mut(8) {
3295
        x ^= x << 13;
3296
        x ^= x >> 7;
3297
        x ^= x << 17;
3298
        let b = x.to_le_bytes();
3299
        chunk.copy_from_slice(&b[..chunk.len()]);
3300
    }
3301
    let t = std::time::Instant::now();
3302
    write(&root.join("r"), "big.bin", &data);
3303
    eprintln!("write 1 GiB to disk: {:.2?}", t.elapsed());
3304
    let t = std::time::Instant::now();
3305
    let h = repo.commit("big", &[]).unwrap();
3306
    eprintln!("commit (chunk + hash + store): {:.2?}", t.elapsed());
3307
    let t = std::time::Instant::now();
3308
    assert!(!repo.snapshot("status").unwrap().changed);
3309
    eprintln!("status on a clean 1 GiB working copy: {:.2?}", t.elapsed());
3310
    let t = std::time::Instant::now();
3311
    let objects = repo.store().list().unwrap().len();
3312
    eprintln!("objects stored: {objects} ({:.2?} to list)", t.elapsed());
3313
    let t = std::time::Instant::now();
3314
    let g = repo.gc(true).unwrap();
3315
    eprintln!("gc (pack): {:.2?} {g:?}", t.elapsed());
3316
    let t = std::time::Instant::now();
3317
    let clone = Repo::clone(&root.join("r").to_string_lossy(), &root.join("c")).unwrap();
3318
    eprintln!("clone (fetch + checkout): {:.2?}", t.elapsed());
3319
    let t = std::time::Instant::now();
3320
    let back = fs::read(root.join("c/big.bin")).unwrap();
3321
    assert_eq!(blake3::hash(&back), blake3::hash(&data));
3322
    eprintln!("read back and verify: {:.2?}", t.elapsed());
3323
    assert_eq!(clone.bookmark_heads().unwrap(), vec![h]);
3324
    let store_bytes: u64 = walkdir_size(&root.join("r/.oxy/objects"));
3325
    eprintln!(
3326
        "store size: {:.1} MiB for 1 GiB of data",
3327
        store_bytes as f64 / (1024.0 * 1024.0)
3328
    );
3329
}
3330
3331
fn walkdir_size(p: &Path) -> u64 {
3332
    let mut total = 0;
3333
    if let Ok(rd) = fs::read_dir(p) {
3334
        for e in rd.flatten() {
3335
            let path = e.path();
3336
            if path.is_dir() {
3337
                total += walkdir_size(&path);
3338
            } else if let Ok(m) = fs::metadata(&path) {
3339
                total += m.len();
3340
            }
3341
        }
3342
    }
3343
    total
3344
}
3345
3346
/// An opaque file whose size and mtime match the manifest is not read on
3347
/// the next snapshot: its blob comes from the manifest's stat cache.
3348
#[cfg(unix)]
3349
#[test]
3350
fn stat_cache_skips_reading_unchanged_opaque_files() {
3351
    use std::os::unix::fs::PermissionsExt;
3352
    hermetic();
3353
    let dir = tempfile::tempdir().unwrap();
3354
    let root = dir.path();
3355
    let repo = Repo::init(root).unwrap().with_home(root.join("home"));
3356
    let mut big = vec![0u8; 300 * 1024];
3357
    for (i, b) in big.iter_mut().enumerate() {
3358
        *b = (i as u32).wrapping_mul(2654435761).to_le_bytes()[1];
3359
    }
3360
    big[0] = 0;
3361
    write(root, "big.bin", &big);
3362
    write(root, "a.txt", b"text\n");
3363
    let h1 = repo.commit("base", &[]).unwrap();
3364
    let (_, _, m) = repo.read_manifest().unwrap().unwrap();
3365
    assert!(
3366
        m.entries["big.bin"].blob.is_some(),
3367
        "opaque files record their blob"
3368
    );
3369
    assert!(m.entries["a.txt"].blob.is_none());
3370
    let blob = m.entries["big.bin"].blob.unwrap();
3371
    assert!(repo.store().has(&blob));
3372
3373
    // Files modified within two seconds of the manifest are racy and still
3374
    // read; age the file so the cache applies, then snapshot to record it.
3375
    let old = std::time::SystemTime::now() - std::time::Duration::from_secs(30);
3376
    fs::File::options()
3377
        .write(true)
3378
        .open(root.join("big.bin"))
3379
        .unwrap()
3380
        .set_modified(old)
3381
        .unwrap();
3382
    assert!(!repo.snapshot("status").unwrap().changed);
3383
    // Now the file cannot be read at all; the snapshot succeeds without it.
3384
    fs::set_permissions(root.join("big.bin"), fs::Permissions::from_mode(0o000)).unwrap();
3385
    let snap = repo.snapshot("status").unwrap();
3386
    assert!(
3387
        !snap.changed && snap.statuses.is_empty(),
3388
        "{:?}",
3389
        snap.statuses
3390
    );
3391
    fs::set_permissions(root.join("big.bin"), fs::Permissions::from_mode(0o644)).unwrap();
3392
    // A real change (new mtime, new content) is seen and committed correctly.
3393
    let mut big2 = big.clone();
3394
    big2[10] ^= 0xff;
3395
    write(root, "big.bin", &big2);
3396
    let snap = repo.snapshot("status").unwrap();
3397
    assert_eq!(
3398
        snap.statuses
3399
            .iter()
3400
            .map(|s| (s.path.as_str(), s.status))
3401
            .collect::<Vec<_>>(),
3402
        vec![("big.bin", ChangeStatus::Modified)]
3403
    );
3404
    let h2 = repo.commit("edit", &[]).unwrap();
3405
    let files = repo.load_state(&[h2]).unwrap().materialize().files;
3406
    assert_eq!(
3407
        files["big.bin"].content,
3408
        FileContent::Opaque {
3409
            blobs: vec![Repo::blob_ref(&big2)]
3410
        }
3411
    );
3412
    // Checkout writes a manifest with blobs too, so the next status is cached.
3413
    repo.checkout(&[h1], false, "checkout").unwrap();
3414
    let (_, _, m) = repo.read_manifest().unwrap().unwrap();
3415
    assert_eq!(m.entries["big.bin"].blob, Some(Repo::blob_ref(&big)));
3416
    assert!(!repo.snapshot("status").unwrap().changed);
3417
}
3418
3419
#[test]
3420
fn status_json_lists_conflicts_with_contributors() {
3421
    hermetic();
3422
    let dir = tempfile::tempdir().unwrap();
3423
    let root = dir.path();
3424
    let repo = Repo::init(root).unwrap().with_home(root.join("home"));
3425
    write(root, "a.txt", b"one\n");
3426
    let h1 = repo.commit("base", &[]).unwrap();
3427
    write(root, "a.txt", b"one\nleft\n");
3428
    let ha = repo.commit("left", &[]).unwrap();
3429
    repo.checkout(&[h1], true, "checkout").unwrap();
3430
    write(root, "a.txt", b"one\nright\n");
3431
    let hb = repo.commit("right", &[]).unwrap();
3432
    repo.checkout(&[ha, hb], true, "checkout").unwrap();
3433
    let snap = repo.snapshot("status").unwrap();
3434
    assert!(snap.base_snapshot.is_conflicted());
3435
    let json = repo.status_json(&snap).unwrap();
3436
    let ida = repo.store().get_change(&ha).unwrap().change_id.to_hex();
3437
    let idb = repo.store().get_change(&hb).unwrap().change_id.to_hex();
3438
    assert!(json.contains("\"conflicted\":true"), "{json}");
3439
    assert!(
3440
        json.contains("\"kind\":\"text\",\"path\":\"a.txt\""),
3441
        "{json}"
3442
    );
3443
    assert!(json.contains(&ida) && json.contains(&idb), "{json}");
3444
    assert!(json.contains("\"resolved\":false"), "{json}");
3445
    assert!(json.starts_with('{') && json.ends_with('}'));
3446
    // Resolve and the report says so; a clean copy has no conflicts.
3447
    write(root, "a.txt", b"one\nleft\nright\n");
3448
    let snap = repo.snapshot("status").unwrap();
3449
    let json = repo.status_json(&snap).unwrap();
3450
    assert!(json.contains("\"resolved\":true"), "{json}");
3451
    repo.commit("resolve", &[]).unwrap();
3452
    let snap = repo.snapshot("status").unwrap();
3453
    let json = repo.status_json(&snap).unwrap();
3454
    assert!(
3455
        json.contains("\"clean\":true,\"conflicted\":false,\"paths\":[],\"conflicts\":[]"),
3456
        "{json}"
3457
    );
3458
}
3459
3460
#[test]
3461
fn ignore_rules_do_not_untrack_files() {
3462
    hermetic();
3463
    let dir = tempfile::tempdir().unwrap();
3464
    let root = dir.path();
3465
    let repo = Repo::init(root).unwrap().with_home(root.join("home"));
3466
    write(root, "src.c", b"int x;\n");
3467
    write(root, "build/out.o", b"\0obj");
3468
    write(root, "sub/keep.log", b"keep\n");
3469
    write(root, "sub/junk.log", b"junk\n");
3470
    write(root, ".oxyignore", b"/build\n*.log\n!sub/keep.log\n");
3471
    let snap = repo.snapshot("status").unwrap();
3472
    let added: Vec<&str> = snap.statuses.iter().map(|s| s.path.as_str()).collect();
3473
    assert_eq!(
3474
        added,
3475
        vec![".oxyignore", "src.c", "sub/keep.log"],
3476
        "anchored, glob, and negated rules"
3477
    );
3478
    let h1 = repo.commit("base", &[]).unwrap();
3479
    // Ignoring a tracked file changes nothing about it.
3480
    write(root, ".oxyignore", b"/build\n*.log\n!sub/keep.log\nsrc.c\n");
3481
    let snap = repo.snapshot("status").unwrap();
3482
    assert_eq!(
3483
        snap.statuses
3484
            .iter()
3485
            .map(|s| s.path.as_str())
3486
            .collect::<Vec<_>>(),
3487
        vec![".oxyignore"]
3488
    );
3489
    let h2 = repo.commit("ignore src.c", &[]).unwrap();
3490
    assert!(repo
3491
        .load_state(&[h2])
3492
        .unwrap()
3493
        .materialize()
3494
        .files
3495
        .contains_key("src.c"));
3496
    // Its edits are still seen, by status and by the prompt.
3497
    assert_eq!(repo.quick_dirty().unwrap(), Some(false));
3498
    write(root, "src.c", b"int x, y;\n");
3499
    assert_eq!(repo.quick_dirty().unwrap(), Some(true));
3500
    let snap = repo.snapshot("status").unwrap();
3501
    assert_eq!(
3502
        snap.statuses
3503
            .iter()
3504
            .map(|s| (s.path.as_str(), s.status))
3505
            .collect::<Vec<_>>(),
3506
        vec![("src.c", ChangeStatus::Modified)]
3507
    );
3508
    let h3 = repo.commit("edit src.c", &[]).unwrap();
3509
    assert!(
3510
        matches!(&repo.load_state(&[h3]).unwrap().materialize().files["src.c"].content, FileContent::Text { bytes, .. } if bytes == b"int x, y;\n")
3511
    );
3512
    // Deleting it on disk removes it, ignored or not; a checkout brings it back.
3513
    fs::remove_file(root.join("src.c")).unwrap();
3514
    let snap = repo.snapshot("status").unwrap();
3515
    assert_eq!(
3516
        snap.statuses
3517
            .iter()
3518
            .map(|s| (s.path.as_str(), s.status))
3519
            .collect::<Vec<_>>(),
3520
        vec![("src.c", ChangeStatus::Removed)]
3521
    );
3522
    repo.checkout(&[h3], true, "checkout").unwrap();
3523
    assert_eq!(fs::read(root.join("src.c")).unwrap(), b"int x, y;\n");
3524
    assert!(!repo.snapshot("status").unwrap().changed);
3525
    let _ = h1;
3526
}
3527
3528
#[test]
3529
fn split_works_on_non_heads_by_node() {
3530
    hermetic();
3531
    let dir = tempfile::tempdir().unwrap();
3532
    let root = dir.path();
3533
    let repo = Repo::init(root).unwrap().with_home(root.join("home"));
3534
    write(root, "a.txt", b"one\n");
3535
    write(root, "junk/x.lock", b"lock\n");
3536
    let h1 = repo.commit("work plus junk", &[]).unwrap();
3537
    write(root, "a.txt", b"one\ntwo\n");
3538
    let h2 = repo.commit("more work", &[]).unwrap();
3539
    assert_eq!(repo.store().get_change(&h2).unwrap().deps, vec![h1]);
3540
    let id1 = repo.store().get_change(&h1).unwrap().change_id;
3541
    // h1 is not a head: split it by node.
3542
    let (hj, h1b) = repo.split(&h1, &["junk".into()]).unwrap();
3543
    assert_ne!(h1b, h1);
3544
    assert_eq!(
3545
        repo.store().get_change(&h1b).unwrap().change_id,
3546
        id1,
3547
        "the rest keeps the ChangeId"
3548
    );
3549
    let junk = repo.store().get_change(&hj).unwrap();
3550
    assert!(junk.tree_ops.iter().all(
3551
        |op| matches!(op, TreeOp::AddNode { name, .. } if name == "junk" || name == "x.lock")
3552
    ));
3553
    let heads = repo.bookmark_heads().unwrap();
3554
    assert!(
3555
        heads.contains(&hj),
3556
        "the split-off part is a head of its own"
3557
    );
3558
    let snap = repo.load_state(&heads).unwrap().materialize();
3559
    assert!(
3560
        matches!(&snap.files["a.txt"].content, FileContent::Text { bytes, .. } if bytes == b"one\ntwo\n"),
3561
        "the dependent was rewritten onto the new hash"
3562
    );
3563
    assert!(snap.files.contains_key("junk/x.lock"));
3564
    let h2b = heads
3565
        .iter()
3566
        .find(|h| repo.store().get_change(h).unwrap().message == "more work")
3567
        .copied()
3568
        .unwrap();
3569
    assert_eq!(repo.store().get_change(&h2b).unwrap().deps, vec![h1b]);
3570
    assert!(!repo.snapshot("status").unwrap().changed);
3571
    // Abandoning the split-off head removes the junk from history.
3572
    repo.abandon(&hj).unwrap();
3573
    let heads = repo.bookmark_heads().unwrap();
3574
    let snap = repo.load_state(&heads).unwrap().materialize();
3575
    assert!(!snap.files.contains_key("junk/x.lock") && !snap.files.contains_key("junk"));
3576
    assert!(snap.files.contains_key("a.txt"));
3577
    // A dependent that touches the split-off paths blocks the split.
3578
    write(root, "junk/y.lock", b"y\n");
3579
    let hb = repo.commit("junk base", &[]).unwrap();
3580
    write(root, "junk/y.lock", b"yy\n");
3581
    write(root, "b.txt", b"b\n");
3582
    repo.commit("touches junk", &[]).unwrap();
3583
    let err = repo.split(&hb, &["junk".into()]).unwrap_err().to_string();
3584
    assert!(err.contains("depends on the split-off paths"), "{err}");
3585
}
3586
3587
#[test]
3588
fn bookmarks_switch_merge_and_push() {
3589
    hermetic();
3590
    let dir = tempfile::tempdir().unwrap();
3591
    let root = dir.path();
3592
    let origin = Repo::init(&root.join("origin")).unwrap();
3593
    let url = root.join("origin").to_string_lossy().to_string();
3594
    let mut repo = Repo::clone(&url, &root.join("r"))
3595
        .unwrap()
3596
        .with_home(root.join("home"));
3597
    let r = root.join("r");
3598
    write(&r, "a.txt", b"a\n");
3599
    let h_a = repo.commit("a", &[]).unwrap();
3600
    assert!(repo.push("origin", false).unwrap()[0].ok);
3601
    origin.refresh().unwrap();
3602
3603
    // A bookmark at the working copy's base, then work on it.
3604
    assert!(repo.bookmark_create("bad name..", None).is_err());
3605
    assert!(repo.bookmark_create("-x", None).is_err());
3606
    assert_eq!(repo.bookmark_create("feature", None).unwrap(), vec![h_a]);
3607
    assert!(repo.bookmark_create("feature", None).is_err(), "exists");
3608
    repo.bookmark_switch("feature", false).unwrap();
3609
    assert_eq!(repo.config.bookmark, "feature");
3610
    write(&r, "a.txt", b"a\nb\n");
3611
    write(&r, "b.txt", b"b\n");
3612
    let h_b = repo.commit("b on feature", &[]).unwrap();
3613
    assert_eq!(
3614
        repo.bookmark_heads().unwrap(),
3615
        vec![h_b],
3616
        "b edits a.txt, so it depends on a"
3617
    );
3618
    assert_eq!(
3619
        repo.resolve_heads("main").unwrap(),
3620
        vec![h_a],
3621
        "main is untouched"
3622
    );
3623
    assert_eq!(
3624
        repo.resolve_change("feature").unwrap(),
3625
        h_b,
3626
        "a one-head bookmark names its change"
3627
    );
3628
    // Reopening keeps the workspace's bookmark.
3629
    let reopened = Repo::open(&r).unwrap().with_home(root.join("home"));
3630
    assert_eq!(reopened.config.bookmark, "feature");
3631
    // Back to main: b.txt goes away; work there.
3632
    repo.bookmark_switch("main", false).unwrap();
3633
    assert!(!r.join("b.txt").exists());
3634
    assert_eq!(fs::read(r.join("a.txt")).unwrap(), b"a\n");
3635
    write(&r, "c.txt", b"c\n");
3636
    let h_c = repo.commit("c on main", &[]).unwrap();
3637
    let list = repo.bookmarks().unwrap();
3638
    assert_eq!(
3639
        list.iter()
3640
            .map(|b| (b.name.as_str(), b.current))
3641
            .collect::<Vec<_>>(),
3642
        vec![("feature", false), ("main", true)]
3643
    );
3644
    assert_eq!(
3645
        list.iter().find(|b| b.name == "main").unwrap().ahead,
3646
        Some(1),
3647
        "c is not on origin yet"
3648
    );
3649
    // Merge feature into main: the union, both heads, no merge change.
3650
    let m = repo.merge("feature").unwrap();
3651
    assert!(m.changed && m.checked_out);
3652
    let mut want = vec![h_b, h_c];
3653
    want.sort();
3654
    assert_eq!(m.heads, want);
3655
    assert_eq!(fs::read(r.join("b.txt")).unwrap(), b"b\n");
3656
    assert!(!repo.merge("feature").unwrap().changed, "already merged");
3657
    assert!(repo.merge("main").is_err());
3658
    // The other bookmark can be pushed by name and appears at origin.
3659
    assert!(repo.push_bookmark("origin", "feature", false).unwrap()[0].ok);
3660
    origin.refresh().unwrap();
3661
    assert_eq!(origin.resolve_heads("feature").unwrap(), vec![h_b]);
3662
    assert!(repo.push("origin", false).unwrap()[0].ok);
3663
    origin.refresh().unwrap();
3664
    assert_eq!(
3665
        repo.bookmarks()
3666
            .unwrap()
3667
            .iter()
3668
            .find(|b| b.name == "main")
3669
            .unwrap()
3670
            .ahead,
3671
        Some(0)
3672
    );
3673
    // A second workspace inherits the current bookmark and can switch independently.
3674
    let ws = repo.workspace_add(&root.join("ws"), None).unwrap();
3675
    assert_eq!(ws.config.bookmark, "main");
3676
    let mut ws = ws;
3677
    ws.bookmark_switch("feature", false).unwrap();
3678
    assert_eq!(
3679
        Repo::open(&r).unwrap().config.bookmark,
3680
        "main",
3681
        "the first workspace is unaffected"
3682
    );
3683
    assert!(
3684
        repo.bookmark_delete("feature").is_err(),
3685
        "current bookmark of another workspace"
3686
    );
3687
    ws.bookmark_switch("main", false).unwrap();
3688
    // Set and delete.
3689
    assert_eq!(repo.bookmark_set("feature", &[h_a]).unwrap(), vec![h_a]);
3690
    assert!(repo.bookmark_delete("main").is_err(), "current here");
3691
    repo.bookmark_delete("feature").unwrap();
3692
    assert!(repo.resolve_heads("feature").is_err());
3693
    assert!(repo.bookmark_set("feature", &[h_a]).is_err());
3694
    assert!(
3695
        repo.checkout(&[h_a], false, "checkout").is_ok(),
3696
        "changes of a deleted bookmark remain"
3697
    );
3698
}
3699
3700
#[test]
3701
fn oxygen_subrepos_pin_follow_and_update() {
3702
    hermetic();
3703
    let dir = tempfile::tempdir().unwrap();
3704
    let root = dir.path();
3705
    // A library repository with two commits, and a bare-ish origin for it.
3706
    let lib_origin = Repo::init(&root.join("lib-origin")).unwrap();
3707
    let lib_url = root.join("lib-origin").to_string_lossy().to_string();
3708
    let lib = Repo::clone(&lib_url, &root.join("lib"))
3709
        .unwrap()
3710
        .with_home(root.join("home"));
3711
    write(&root.join("lib"), "lib.txt", b"v1\n");
3712
    let l1 = lib.commit("lib v1", &[]).unwrap();
3713
    assert!(lib.push("origin", false).unwrap()[0].ok);
3714
    let _ = lib_origin;
3715
3716
    // The application (a clone of its own origin) adds it as a subrepo.
3717
    let app_origin = Repo::init(&root.join("app-origin")).unwrap();
3718
    let app_url = root.join("app-origin").to_string_lossy().to_string();
3719
    let _ = app_origin;
3720
    let app_dir = root.join("app");
3721
    let app = Repo::clone(&app_url, &app_dir)
3722
        .unwrap()
3723
        .with_home(root.join("home"));
3724
    write(&app_dir, "main.txt", b"app\n");
3725
    let pin = app.submodule_add(&lib_url, "libs/lib", None).unwrap();
3726
    assert!(matches!(&pin, crate::subrepo::Pin::Oxy { heads, .. } if heads == &vec![l1]));
3727
    assert!(app_dir.join(".oxymodules").exists() && app_dir.join("libs/lib/.oxy").is_dir());
3728
    let snap = app.snapshot("status").unwrap();
3729
    let paths: Vec<&str> = snap.statuses.iter().map(|s| s.path.as_str()).collect();
3730
    assert_eq!(
3731
        paths,
3732
        vec![".oxymodules", "libs/lib", "main.txt"],
3733
        "the nested files are not walked"
3734
    );
3735
    let a1 = app.commit("app with lib", &[]).unwrap();
3736
    let files = app.load_state(&[a1]).unwrap().materialize().files;
3737
    assert_eq!(files["libs/lib"].kind, NodeKind::Subrepo);
3738
    assert!(!files.contains_key("libs/lib/lib.txt"));
3739
    assert!(!app.snapshot("status").unwrap().changed);
3740
    let subs = app.subrepos().unwrap();
3741
    assert_eq!(subs.len(), 1);
3742
    assert_eq!(subs[0].actual.as_ref(), Some(&subs[0].pin));
3743
3744
    // Advance the nested repository: the parent sees a modified pin.
3745
    let nested = Repo::open(&app_dir.join("libs/lib"))
3746
        .unwrap()
3747
        .with_home(root.join("home"));
3748
    write(&app_dir.join("libs/lib"), "lib.txt", b"v2\n");
3749
    let l2 = nested.commit("lib v2", &[]).unwrap();
3750
    assert!(nested.push("origin", false).unwrap()[0].ok);
3751
    let snap = app.snapshot("status").unwrap();
3752
    assert_eq!(
3753
        snap.statuses
3754
            .iter()
3755
            .map(|s| (s.path.as_str(), s.status))
3756
            .collect::<Vec<_>>(),
3757
        vec![("libs/lib", ChangeStatus::Modified)]
3758
    );
3759
    let a2 = app.commit("bump lib", &[]).unwrap();
3760
    // Checking out the older app state brings the nested working copy back
3761
    // to the older pin, but never moves its bookmark backwards (oxygen#38).
3762
    let r = app.checkout(&[a1], false, "checkout").unwrap();
3763
    assert!(
3764
        r.notes.len() == 1 && r.notes[0].contains("keeps 1 newer change"),
3765
        "{:?}",
3766
        r.notes
3767
    );
3768
    assert_eq!(fs::read(app_dir.join("libs/lib/lib.txt")).unwrap(), b"v1\n");
3769
    let nested = Repo::open(&app_dir.join("libs/lib")).unwrap();
3770
    assert_eq!(nested.bookmark_heads().unwrap(), vec![l2]);
3771
    assert_eq!(nested.working_copy().unwrap().1.deps, vec![l1]);
3772
    assert!(!app.snapshot("status").unwrap().changed);
3773
    // A dirty nested repository is left alone and reported.
3774
    write(&app_dir.join("libs/lib"), "scratch.txt", b"wip\n");
3775
    let r = app.checkout(&[a2], false, "checkout").unwrap();
3776
    assert!(
3777
        r.notes.iter().any(|n| n.contains("uncommitted")),
3778
        "{:?}",
3779
        r.notes
3780
    );
3781
    assert_eq!(fs::read(app_dir.join("libs/lib/lib.txt")).unwrap(), b"v1\n");
3782
    fs::remove_file(app_dir.join("libs/lib/scratch.txt")).unwrap();
3783
    let r = app.submodule_update(false, &[]).unwrap();
3784
    assert_eq!(r, vec![("libs/lib".to_string(), SubrepoSync::Updated)]);
3785
    assert_eq!(fs::read(app_dir.join("libs/lib/lib.txt")).unwrap(), b"v2\n");
3786
    let _ = l2;
3787
3788
    // A fresh clone of the app has the pin but no nested repository until update --init.
3789
    assert!(app.push("origin", false).unwrap()[0].ok);
3790
    let clone_dir = root.join("app-clone");
3791
    let clone = Repo::clone(&app_url, &clone_dir)
3792
        .unwrap()
3793
        .with_home(root.join("home"));
3794
    assert!(!clone_dir.join("libs/lib/.oxy").exists());
3795
    assert_eq!(
3796
        clone.submodule_update(false, &[]).unwrap(),
3797
        vec![("libs/lib".to_string(), SubrepoSync::Missing)]
3798
    );
3799
    assert_eq!(
3800
        clone.submodule_update(true, &[]).unwrap(),
3801
        vec![("libs/lib".to_string(), SubrepoSync::Updated)]
3802
    );
3803
    assert_eq!(
3804
        fs::read(clone_dir.join("libs/lib/lib.txt")).unwrap(),
3805
        b"v2\n"
3806
    );
3807
    assert!(!clone.snapshot("status").unwrap().changed);
3808
    // Removing the subrepo leaves the directory and drops the node.
3809
    clone.submodule_remove("libs/lib").unwrap();
3810
    let snap = clone.snapshot("status").unwrap();
3811
    assert!(
3812
        snap.statuses
3813
            .iter()
3814
            .any(|s| s.path == "libs/lib" && s.status == ChangeStatus::Removed),
3815
        "{:?}",
3816
        snap.statuses
3817
    );
3818
    let c = clone.commit("drop lib", &[]).unwrap();
3819
    assert!(!clone
3820
        .load_state(&[c])
3821
        .unwrap()
3822
        .materialize()
3823
        .files
3824
        .contains_key("libs/lib"));
3825
    assert!(clone_dir.join("libs/lib/lib.txt").exists());
3826
    assert!(
3827
        !clone.snapshot("status").unwrap().changed,
3828
        "an unregistered nested repository is ignored"
3829
    );
3830
}
3831
3832
#[test]
3833
fn git_submodules_import_and_export_as_gitlinks() {
3834
    hermetic();
3835
    if std::process::Command::new("git")
3836
        .arg("--version")
3837
        .output()
3838
        .is_err()
3839
    {
3840
        eprintln!("git not installed; skipping");
3841
        return;
3842
    }
3843
    let dir = tempfile::tempdir().unwrap();
3844
    let root = dir.path();
3845
    let git_in = |d: &Path, args: &[&str]| -> String {
3846
        let out = std::process::Command::new("git")
3847
            .arg("-C")
3848
            .arg(d)
3849
            .args([
3850
                "-c",
3851
                "user.name=Grace",
3852
                "-c",
3853
                "[email protected]",
3854
                "-c",
3855
                "commit.gpgsign=false",
3856
                "-c",
3857
                "protocol.file.allow=always",
3858
            ])
3859
            .args(args)
3860
            .output()
3861
            .unwrap();
3862
        assert!(
3863
            out.status.success(),
3864
            "git {args:?}: {}",
3865
            String::from_utf8_lossy(&out.stderr)
3866
        );
3867
        String::from_utf8_lossy(&out.stdout).trim().to_string()
3868
    };
3869
    let sub = root.join("sub");
3870
    fs::create_dir_all(&sub).unwrap();
3871
    git_in(&sub, &["init", "-q", "-b", "main"]);
3872
    write(&sub, "s.txt", b"sub\n");
3873
    git_in(&sub, &["add", "."]);
3874
    git_in(&sub, &["commit", "-q", "-m", "sub initial"]);
3875
    let sub_sha = git_in(&sub, &["rev-parse", "HEAD"]);
3876
    let g = root.join("main.git");
3877
    fs::create_dir_all(&g).unwrap();
3878
    git_in(&g, &["init", "-q", "-b", "main"]);
3879
    write(&g, "README.md", b"# app\n");
3880
    git_in(&g, &["add", "."]);
3881
    git_in(&g, &["commit", "-q", "-m", "initial"]);
3882
    git_in(
3883
        &g,
3884
        &[
3885
            "submodule",
3886
            "add",
3887
            "-q",
3888
            sub.to_str().unwrap(),
3889
            "vendor/sub",
3890
        ],
3891
    );
3892
    git_in(&g, &["commit", "-q", "-m", "add submodule"]);
3893
3894
    let dest = root.join("oxy");
3895
    let repo = Repo::init(&dest).unwrap().with_home(root.join("home"));
3896
    let rep = repo.import_git(&g, "main").unwrap();
3897
    assert_eq!((rep.commits, rep.submodules), (2, 1));
3898
    let files = repo
3899
        .load_state(&repo.bookmark_heads().unwrap())
3900
        .unwrap()
3901
        .materialize()
3902
        .files;
3903
    assert_eq!(files["vendor/sub"].kind, NodeKind::Subrepo);
3904
    let FileContent::Opaque { blobs } = &files["vendor/sub"].content else {
3905
        panic!()
3906
    };
3907
    assert_eq!(
3908
        crate::subrepo::Pin::decode(&repo.read_blob(&blobs[0]).unwrap()).unwrap(),
3909
        crate::subrepo::Pin::Git {
3910
            sha: sub_sha.clone(),
3911
            branch: "HEAD".into()
3912
        }
3913
    );
3914
    let modules =
3915
        crate::subrepo::Modules::parse(&fs::read_to_string(dest.join(".oxymodules")).unwrap());
3916
    assert_eq!(modules.entries["vendor/sub"].url, sub.to_string_lossy());
3917
    assert!(modules.entries["vendor/sub"].git);
3918
    assert!(
3919
        files.contains_key(".gitmodules"),
3920
        "the Git file is kept for round trips"
3921
    );
3922
    assert!(
3923
        !dest.join("vendor/sub/.git").exists(),
3924
        "not cloned until update --init"
3925
    );
3926
    assert!(!repo.snapshot("status").unwrap().changed);
3927
    // update --init clones it at the pinned commit; status is unchanged.
3928
    assert_eq!(
3929
        repo.submodule_update(true, &[]).unwrap(),
3930
        vec![("vendor/sub".to_string(), SubrepoSync::Updated)]
3931
    );
3932
    assert_eq!(
3933
        git_in(&dest.join("vendor/sub"), &["rev-parse", "HEAD"]),
3934
        sub_sha
3935
    );
3936
    assert!(!repo.snapshot("status").unwrap().changed);
3937
    // Export writes the gitlink and .gitmodules back.
3938
    let mirror = root.join("mirror.git");
3939
    let rep = repo.git_export(&mirror).unwrap();
3940
    assert_eq!(rep.skipped_subrepos, 0);
3941
    let ls = git_in(&mirror, &["ls-tree", "main", "vendor/sub"]);
3942
    assert!(
3943
        ls.starts_with("160000 commit ") && ls.contains(&sub_sha),
3944
        "{ls}"
3945
    );
3946
    assert_eq!(
3947
        git_in(&mirror, &["ls-tree", "--name-only", "main"]),
3948
        ".gitmodules\nREADME.md\nvendor"
3949
    );
3950
    let orig_tree = git_in(&g, &["rev-parse", "main^{tree}"]);
3951
    assert_eq!(
3952
        git_in(&mirror, &["rev-parse", "main^{tree}"]),
3953
        orig_tree,
3954
        "tree round trip"
3955
    );
3956
}
3957
3958
#[test]
3959
fn partial_commits_by_path_and_by_hunk() {
3960
    hermetic();
3961
    let dir = tempfile::tempdir().unwrap();
3962
    let root = dir.path();
3963
    let repo = Repo::init(root).unwrap().with_home(root.join("home"));
3964
    write(root, "a.txt", b"1\n2\n3\n");
3965
    write(root, "b.txt", b"b\n");
3966
    let h0 = repo.commit("base", &[]).unwrap();
3967
    write(root, "a.txt", b"0\n1\n2\n3\n4\n");
3968
    write(root, "b.txt", b"b\nbb\n");
3969
    write(root, "c.txt", b"c\n");
3970
    // By path: only a.txt goes in; the rest stays on disk as uncommitted work.
3971
    let h1 = repo
3972
        .commit_selection("a only", &[], &Selection::Paths(vec!["a.txt".into()]))
3973
        .unwrap();
3974
    let c1 = repo.store().get_change(&h1).unwrap();
3975
    assert!(
3976
        c1.tree_ops.is_empty() && c1.edits.iter().all(|e| e.node() == c1.edits[0].node()),
3977
        "{:?}",
3978
        c1.tree_ops
3979
    );
3980
    assert_eq!(c1.deps, vec![h0]);
3981
    let files = repo.load_state(&[h1]).unwrap().materialize().files;
3982
    assert!(
3983
        matches!(&files["a.txt"].content, FileContent::Text { bytes, .. } if bytes == b"0\n1\n2\n3\n4\n")
3984
    );
3985
    assert!(matches!(&files["b.txt"].content, FileContent::Text { bytes, .. } if bytes == b"b\n"));
3986
    assert!(!files.contains_key("c.txt"));
3987
    let snap = repo.snapshot("status").unwrap();
3988
    assert_eq!(
3989
        snap.statuses
3990
            .iter()
3991
            .map(|s| (s.path.as_str(), s.status))
3992
            .collect::<Vec<_>>(),
3993
        vec![
3994
            ("b.txt", ChangeStatus::Modified),
3995
            ("c.txt", ChangeStatus::Added)
3996
        ]
3997
    );
3998
    assert_eq!(
3999
        fs::read(root.join("b.txt")).unwrap(),
4000
        b"b\nbb\n",
4001
        "disk untouched"
4002
    );
4003
    // By hunk: pick the b.txt insert; c.txt's addition is left.
4004
    let (_, hunks) = repo.hunks().unwrap();
4005
    let b_hunk = hunks
4006
        .iter()
4007
        .find(|h| h.path == "b.txt" && h.text.contains("+bb"))
4008
        .unwrap()
4009
        .index;
4010
    let h2 = repo
4011
        .commit_selection("b only", &[], &Selection::Hunks(vec![b_hunk]))
4012
        .unwrap();
4013
    let files = repo.load_state(&[h2]).unwrap().materialize().files;
4014
    assert!(
4015
        matches!(&files["b.txt"].content, FileContent::Text { bytes, .. } if bytes == b"b\nbb\n")
4016
    );
4017
    assert!(!files.contains_key("c.txt"));
4018
    let snap = repo.snapshot("status").unwrap();
4019
    assert_eq!(
4020
        snap.statuses
4021
            .iter()
4022
            .map(|s| s.path.as_str())
4023
            .collect::<Vec<_>>(),
4024
        vec!["c.txt"]
4025
    );
4026
    // Choosing only the content hunk of a file in a new directory pulls in
4027
    // the directory and file additions it needs.
4028
    write(root, "d/e.txt", b"e\n");
4029
    let (_, hunks) = repo.hunks().unwrap();
4030
    let e_insert = hunks
4031
        .iter()
4032
        .find(|h| h.path == "d/e.txt" && h.text.contains("+e"))
4033
        .unwrap()
4034
        .index;
4035
    let h3 = repo
4036
        .commit_selection("e only", &[], &Selection::Hunks(vec![e_insert]))
4037
        .unwrap();
4038
    let c3 = repo.store().get_change(&h3).unwrap();
4039
    assert_eq!(c3.tree_ops.len(), 2, "{:?}", c3.tree_ops);
4040
    let files = repo.load_state(&[h3]).unwrap().materialize().files;
4041
    assert!(files.contains_key("d/e.txt") && !files.contains_key("c.txt"));
4042
    // Choosing a new file's addition hunk brings its content along.
4043
    write(root, "f/g.txt", b"g\n");
4044
    let (_, hunks) = repo.hunks().unwrap();
4045
    let g_add = hunks
4046
        .iter()
4047
        .find(|h| h.path == "f/g.txt" && h.text.starts_with("A "))
4048
        .unwrap()
4049
        .index;
4050
    let h4 = repo
4051
        .commit_selection("g by addition", &[], &Selection::Hunks(vec![g_add]))
4052
        .unwrap();
4053
    let files = repo.load_state(&[h4]).unwrap().materialize().files;
4054
    assert!(
4055
        matches!(&files["f/g.txt"].content, FileContent::Text { bytes, .. } if bytes == b"g\n")
4056
    );
4057
    assert!(!repo
4058
        .snapshot("status")
4059
        .unwrap()
4060
        .statuses
4061
        .iter()
4062
        .any(|s| s.path == "f/g.txt"));
4063
    // Everything left commits normally; the working copy is then clean.
4064
    repo.commit("the rest", &[]).unwrap();
4065
    assert!(!repo.snapshot("status").unwrap().changed);
4066
    let files = repo
4067
        .load_state(&repo.bookmark_heads().unwrap())
4068
        .unwrap()
4069
        .materialize()
4070
        .files;
4071
    assert!(files.contains_key("c.txt"));
4072
}
4073
4074
#[test]
4075
fn blame_attributes_lines_to_introducing_changes_across_renames() {
4076
    hermetic();
4077
    let dir = tempfile::tempdir().unwrap();
4078
    let root = dir.path();
4079
    let mut repo = Repo::init(root).unwrap().with_home(root.join("home"));
4080
    repo.create_identity("Ada", "[email protected]", IdentityScope::User)
4081
        .unwrap();
4082
    write(root, "a.txt", b"one\n");
4083
    let h1 = repo.commit("first", &[]).unwrap();
4084
    write(root, "a.txt", b"one\ntwo\n");
4085
    let h2 = repo.commit("second", &[]).unwrap();
4086
    let b = repo.blame("a.txt").unwrap();
4087
    assert_eq!(
4088
        b.iter()
4089
            .map(|l| (l.line, l.hash, l.text.as_slice()))
4090
            .collect::<Vec<_>>(),
4091
        vec![(1, h1, b"one\n".as_slice()), (2, h2, b"two\n".as_slice())]
4092
    );
4093
    assert!(b.iter().all(|l| l.author == "Ada"));
4094
    assert_eq!(
4095
        b[0].change_id,
4096
        repo.store().get_change(&h1).unwrap().change_id
4097
    );
4098
    fs::rename(root.join("a.txt"), root.join("b.txt")).unwrap();
4099
    repo.commit("rename", &[]).unwrap();
4100
    let b = repo.blame("b.txt").unwrap();
4101
    assert_eq!(
4102
        b.iter().map(|l| l.hash).collect::<Vec<_>>(),
4103
        vec![h1, h2],
4104
        "the node survives the rename"
4105
    );
4106
    assert!(repo.blame("a.txt").is_err());
4107
}
4108
4109
#[test]
4110
fn bisect_finds_the_first_bad_change() {
4111
    hermetic();
4112
    let dir = tempfile::tempdir().unwrap();
4113
    let root = dir.path();
4114
    let repo = Repo::init(root).unwrap().with_home(root.join("home"));
4115
    let mut content = String::new();
4116
    let mut hashes = Vec::new();
4117
    for i in 1..=8 {
4118
        content.push_str(&format!("line {i}{}\n", if i == 5 { " bug" } else { "" }));
4119
        write(root, "f.txt", content.as_bytes());
4120
        hashes.push(repo.commit(&format!("step {i}"), &[]).unwrap());
4121
    }
4122
    // Each step appends after the previous line, so the chain is linear.
4123
    assert_eq!(repo.bookmark_heads().unwrap(), vec![hashes[7]]);
4124
    repo.bisect_start().unwrap();
4125
    assert!(matches!(
4126
        repo.bisect_mark(Some(true), &[hashes[0]]).unwrap(),
4127
        BisectStep::NeedMarks { good: 1, bad: 0 }
4128
    ));
4129
    let step = repo.bisect_mark(Some(false), &[hashes[7]]).unwrap();
4130
    assert!(
4131
        matches!(step, BisectStep::Testing { remaining: 7, .. }),
4132
        "{step:?}"
4133
    );
4134
    // Automated: bad when the bug line is present.
4135
    let step = repo
4136
        .bisect_run(&["sh".into(), "-c".into(), "! grep -q bug f.txt".into()])
4137
        .unwrap();
4138
    assert_eq!(step, BisectStep::Found { culprit: hashes[4] });
4139
    assert_eq!(
4140
        repo.bisect_status().unwrap(),
4141
        Some(BisectStep::Found { culprit: hashes[4] })
4142
    );
4143
    repo.bisect_reset().unwrap();
4144
    assert_eq!(fs::read_to_string(root.join("f.txt")).unwrap(), content);
4145
    assert!(repo.bisect_status().unwrap().is_none());
4146
    assert!(!repo.snapshot("status").unwrap().changed);
4147
    // Manual marks and a skip.
4148
    repo.bisect_start().unwrap();
4149
    repo.bisect_mark(Some(true), &[hashes[0]]).unwrap();
4150
    let mut step = repo.bisect_mark(Some(false), &[hashes[7]]).unwrap();
4151
    let mut skipped_once = false;
4152
    let mut guard = 0;
4153
    while let BisectStep::Testing { .. } = step {
4154
        guard += 1;
4155
        assert!(guard < 20);
4156
        let text = fs::read_to_string(root.join("f.txt")).unwrap();
4157
        if !skipped_once && text.contains("line 6") {
4158
            // An untestable state away from the boundary: the search routes around it.
4159
            skipped_once = true;
4160
            step = repo.bisect_mark(None, &[]).unwrap();
4161
            continue;
4162
        }
4163
        step = repo.bisect_mark(Some(!text.contains("bug")), &[]).unwrap();
4164
    }
4165
    assert!(skipped_once);
4166
    assert_eq!(step, BisectStep::Found { culprit: hashes[4] });
4167
    repo.bisect_reset().unwrap();
4168
    // Skipping the culprit itself leaves it among the candidates reported.
4169
    repo.bisect_start().unwrap();
4170
    repo.bisect_mark(Some(true), &[hashes[0]]).unwrap();
4171
    let mut step = repo.bisect_mark(Some(false), &[hashes[7]]).unwrap();
4172
    let mut guard = 0;
4173
    while let BisectStep::Testing { heads, .. } = &step {
4174
        guard += 1;
4175
        assert!(guard < 20);
4176
        let text = fs::read_to_string(root.join("f.txt")).unwrap();
4177
        let is_culprit_state =
4178
            heads.contains(&hashes[4]) && !heads.iter().any(|h| hashes[5..].contains(h));
4179
        step = if is_culprit_state {
4180
            repo.bisect_mark(None, &[]).unwrap()
4181
        } else {
4182
            repo.bisect_mark(Some(!text.contains("bug")), &[]).unwrap()
4183
        };
4184
    }
4185
    match step {
4186
        BisectStep::Inconclusive { candidates } => assert!(
4187
            candidates.contains(&hashes[4]) && candidates.len() <= 2,
4188
            "{candidates:?}"
4189
        ),
4190
        other => panic!("{other:?}"),
4191
    }
4192
    repo.bisect_reset().unwrap();
4193
}
4194
4195
#[test]
4196
fn squash_folds_a_change_into_its_dependency() {
4197
    hermetic();
4198
    let dir = tempfile::tempdir().unwrap();
4199
    let root = dir.path();
4200
    let repo = Repo::init(root).unwrap().with_home(root.join("home"));
4201
    write(root, "a.txt", b"1\n");
4202
    let a = repo.commit("A", &[]).unwrap();
4203
    write(root, "a.txt", b"1\n2\n");
4204
    let c = repo.commit("C", &[]).unwrap();
4205
    write(root, "a.txt", b"1\n2\n3\n");
4206
    let e = repo.commit("E", &[]).unwrap();
4207
    write(root, "b.txt", b"b\n");
4208
    let b = repo.commit("B", &[]).unwrap();
4209
    let id_a = repo.store().get_change(&a).unwrap().change_id;
4210
    let id_e = repo.store().get_change(&e).unwrap().change_id;
4211
    // E depends on C which A lacks: refused, naming it.
4212
    let err = repo.squash(&e, &a).unwrap_err().to_string();
4213
    assert!(err.contains(&c.short(12)), "{err}");
4214
    // C into A: A' has both, C is gone, E follows and still reads the same.
4215
    let a2 = repo.squash(&c, &a).unwrap();
4216
    let a2c = repo.store().get_change(&a2).unwrap();
4217
    assert_eq!(a2c.change_id, id_a);
4218
    assert!(a2c.deps.is_empty());
4219
    let heads = repo.bookmark_heads().unwrap();
4220
    let st = repo.load_state(&heads).unwrap();
4221
    assert!(!st.contains(&c) && !st.contains(&a) && !st.contains(&e));
4222
    let e2 = st
4223
        .changes()
4224
        .find(|(_, m)| m.change_id == id_e)
4225
        .map(|(h, _)| *h)
4226
        .unwrap();
4227
    assert_eq!(
4228
        repo.store().get_change(&e2).unwrap().deps,
4229
        vec![a2],
4230
        "E now depends on A' alone"
4231
    );
4232
    let files = st.materialize().files;
4233
    assert!(
4234
        matches!(&files["a.txt"].content, FileContent::Text { bytes, .. } if bytes == b"1\n2\n3\n")
4235
    );
4236
    assert!(files.contains_key("b.txt"));
4237
    assert!(st.contains(&b));
4238
    assert!(!repo.snapshot("status").unwrap().changed);
4239
    assert_eq!(repo.log().unwrap().len(), 4, "working copy, B, E', A'");
4240
    // Undo restores the three original changes.
4241
    repo.undo().unwrap();
4242
    repo.undo().unwrap();
4243
    let st = repo.load_state(&repo.bookmark_heads().unwrap()).unwrap();
4244
    assert!(st.contains(&c) && st.contains(&a) && st.contains(&e));
4245
}
4246
4247
#[test]
4248
fn rebase_re_expresses_a_change_against_another_base() {
4249
    hermetic();
4250
    let dir = tempfile::tempdir().unwrap();
4251
    let root = dir.path();
4252
    let repo = Repo::init(root).unwrap().with_home(root.join("home"));
4253
    write(root, "a.txt", b"1\n2\n");
4254
    let a = repo.commit("A", &[]).unwrap();
4255
    write(root, "a.txt", b"1\n2\n3\n");
4256
    let c = repo.commit("C: append 3", &[]).unwrap();
4257
    write(root, "a.txt", b"1\n2\n3\n4\n");
4258
    let e = repo.commit("E: append 4", &[]).unwrap();
4259
    // A different base: A plus a change that prepends a line.
4260
    repo.checkout(&[a], true, "checkout").unwrap();
4261
    write(root, "a.txt", b"0\n1\n2\n");
4262
    let d = repo.commit("D: prepend 0", &[]).unwrap();
4263
    let id_c = repo.store().get_change(&c).unwrap().change_id;
4264
    let id_e = repo.store().get_change(&e).unwrap().change_id;
4265
    // Rebase C onto D: its effect (append 3) re-derived against D's text.
4266
    let c2 = repo.rebase(&c, &[d]).unwrap();
4267
    let c2c = repo.store().get_change(&c2).unwrap();
4268
    assert_eq!(c2c.change_id, id_c);
4269
    assert!(c2c.deps.contains(&d), "{:?}", c2c.deps);
4270
    let heads = repo.bookmark_heads().unwrap();
4271
    let st = repo.load_state(&heads).unwrap();
4272
    assert!(!st.contains(&c) && st.contains(&d));
4273
    let e2 = st
4274
        .changes()
4275
        .find(|(_, m)| m.change_id == id_e)
4276
        .map(|(h, _)| *h)
4277
        .unwrap();
4278
    let e2deps = repo.store().get_change(&e2).unwrap().deps;
4279
    assert!(
4280
        e2deps.contains(&c2) && !e2deps.contains(&c) && e2deps.contains(&a),
4281
        "E follows C by content and still depends on A, which introduced the file: {e2deps:?}"
4282
    );
4283
    let files = st.materialize().files;
4284
    assert!(
4285
        matches!(&files["a.txt"].content, FileContent::Text { bytes, .. } if bytes == b"0\n1\n2\n3\n4\n"),
4286
        "{:?}",
4287
        files["a.txt"].content
4288
    );
4289
    assert!(!files["a.txt"].is_conflicted());
4290
    // Rebasing onto a state that already contains the change is refused.
4291
    assert!(repo.rebase(&c2, &[c2]).is_err());
4292
    let err = repo.rebase(&e2, &[d]).unwrap_err().to_string();
4293
    assert!(
4294
        err.contains("lacks dependencies"),
4295
        "E needs C, which D's state does not have: {err}"
4296
    );
4297
}
4298
4299
#[test]
4300
fn unsigned_tags_keep_their_message() {
4301
    hermetic();
4302
    let dir = tempfile::tempdir().unwrap();
4303
    let root = dir.path();
4304
    let repo = Repo::init(root).unwrap().with_home(root.join("home"));
4305
    write(root, "a.txt", b"a\n");
4306
    repo.commit("a", &[]).unwrap();
4307
    assert!(repo.secret_key().unwrap().is_none());
4308
    repo.tag_create("v1", &repo.bookmark_heads().unwrap(), "first release")
4309
        .unwrap();
4310
    let tags = repo.tags().unwrap();
4311
    assert_eq!(
4312
        (
4313
            tags[0].name.as_str(),
4314
            tags[0].message.as_str(),
4315
            tags[0].signer.as_deref()
4316
        ),
4317
        ("v1", "first release", None)
4318
    );
4319
    assert!(
4320
        repo.tag_refs().unwrap()[0].attestation.is_none(),
4321
        "an unsigned attestation is not advertised"
4322
    );
4323
}
4324
4325
#[test]
4326
fn fsck_passes_a_sound_repository_and_names_each_fault() {
4327
    // Files on disk are what this tests: tampering with them, and the
4328
    // directory store's crash points.
4329
    if std::env::var_os("OXY_STORE_BACKEND").is_some() {
4330
        return;
4331
    }
4332
    hermetic();
4333
    let dir = tempfile::tempdir().unwrap();
4334
    let root = dir.path();
4335
    let origin_path = root.join("origin");
4336
    let origin = Repo::init(&origin_path).unwrap();
4337
    let mut a = Repo::clone(&origin_path.to_string_lossy(), &root.join("a"))
4338
        .unwrap()
4339
        .with_home(root.join("home-a"));
4340
    a.create_identity("Ada", "[email protected]", IdentityScope::Repo)
4341
        .unwrap();
4342
    write(&root.join("a"), "f.txt", b"one\n");
4343
    write(&root.join("a"), "bin.dat", b"\0\x01\x02binary");
4344
    let h1 = a.commit("first", &[]).unwrap();
4345
    write(&root.join("a"), "f.txt", b"one\ntwo\n");
4346
    let h2 = a.commit("second", &[]).unwrap();
4347
    a.tag_create("v1", &[h2], "first release").unwrap();
4348
    a.checkpoint().unwrap();
4349
    assert!(a.push("origin", false).unwrap()[0].ok);
4350
    origin.refresh().unwrap();
4351
4352
    // Sound: signed changes, a seal, a tag, a checkpoint, a ref attestation.
4353
    for repo in [&a, &origin] {
4354
        let rep = repo.fsck().unwrap();
4355
        assert_eq!(rep.problems, vec![], "{rep:?}");
4356
        // The two commits, plus the working copy's change in `a`.
4357
        assert!(rep.changes >= 2 && rep.signed >= 2, "{rep:?}");
4358
        assert!(rep.ops > 1 && rep.objects > 5);
4359
    }
4360
    assert!(origin.fsck().unwrap().attestations >= 1);
4361
4362
    // A flipped byte in a stored object is corruption, named by hash.
4363
    let c1 = a.store().path_for(&h1);
4364
    let pristine = fs::read(&c1).unwrap();
4365
    let mut bytes = pristine.clone();
4366
    *bytes.last_mut().unwrap() ^= 1;
4367
    fs::write(&c1, &bytes).unwrap();
4368
    let rep = a.fsck().unwrap();
4369
    assert!(rep.errors() >= 1);
4370
    assert!(
4371
        rep.problems
4372
            .iter()
4373
            .any(|p| p.object == Some(h1) && p.what.contains("unreadable")),
4374
        "{rep:?}"
4375
    );
4376
    fs::write(&c1, &pristine).unwrap();
4377
    assert_eq!(a.fsck().unwrap().errors(), 0);
4378
4379
    // A missing change is named with what needed it.
4380
    fs::remove_file(&c1).unwrap();
4381
    let rep = a.fsck().unwrap();
4382
    assert!(
4383
        rep.problems.iter().any(|p| p.severity == Severity::Error
4384
            && p.object == Some(h1)
4385
            && p.what.contains("change missing, needed by change")),
4386
        "{rep:?}"
4387
    );
4388
    fs::write(&c1, &pristine).unwrap();
4389
4390
    // A missing blob is an error in a full clone.
4391
    let c2 = a.store().get_change(&h1).unwrap();
4392
    let blob = c2
4393
        .edits
4394
        .iter()
4395
        .find_map(|e| match e {
4396
            Edit::Replace { new: Some(b), .. } => Some(*b),
4397
            _ => None,
4398
        })
4399
        .expect("the binary file is a blob");
4400
    let bp = a.store().path_for(&blob);
4401
    let blob_bytes = fs::read(&bp).unwrap();
4402
    fs::remove_file(&bp).unwrap();
4403
    let rep = a.fsck().unwrap();
4404
    assert!(
4405
        rep.problems
4406
            .iter()
4407
            .any(|p| p.object == Some(blob) && p.what.contains("blob missing")),
4408
        "{rep:?}"
4409
    );
4410
    fs::write(&bp, &blob_bytes).unwrap();
4411
4412
    // A broken op log head is reported, not a crash.
4413
    let head = root.join("a/.oxy/ops/head");
4414
    let saved = fs::read(&head).unwrap();
4415
    fs::write(&head, b"not a hash").unwrap();
4416
    let rep = a.fsck().unwrap();
4417
    assert!(
4418
        rep.problems.iter().any(|p| p.what.contains("ops/head")),
4419
        "{rep:?}"
4420
    );
4421
    fs::write(&head, saved).unwrap();
4422
    assert_eq!(a.fsck().unwrap().problems, vec![]);
4423
}
4424
4425
/// Copy a directory tree (for restoring a pristine repository).
4426
fn copy_tree(from: &Path, to: &Path) {
4427
    fs::create_dir_all(to).unwrap();
4428
    for e in fs::read_dir(from).unwrap() {
4429
        let e = e.unwrap();
4430
        let target = to.join(e.file_name());
4431
        if e.file_type().unwrap().is_dir() {
4432
            copy_tree(&e.path(), &target);
4433
        } else {
4434
            fs::copy(e.path(), &target).unwrap();
4435
        }
4436
    }
4437
}
4438
4439
/// Spec §13.6: stop `commit` and `push` at every durable step, as a crash
4440
/// would, and check that both repositories still open, pass `fsck`, and
4441
/// accept the same operation again.
4442
#[test]
4443
fn crash_at_every_step_of_commit_and_push_leaves_sound_repositories() {
4444
    // Files on disk are what this tests: tampering with them, and the
4445
    // directory store's crash points.
4446
    if std::env::var_os("OXY_STORE_BACKEND").is_some() {
4447
        return;
4448
    }
4449
    use crate::durable::failpoint;
4450
    hermetic();
4451
    let dir = tempfile::tempdir().unwrap();
4452
    let pristine = dir.path().join("pristine");
4453
    let origin_path = pristine.join("origin");
4454
    Repo::init(&origin_path).unwrap();
4455
    let mut a = Repo::clone(&origin_path.to_string_lossy(), &pristine.join("a"))
4456
        .unwrap()
4457
        .with_home(dir.path().join("home"));
4458
    a.create_identity("Ada", "[email protected]", IdentityScope::Repo)
4459
        .unwrap();
4460
    write(&pristine.join("a"), "f.txt", b"one\n");
4461
    a.commit("first", &[]).unwrap();
4462
    assert!(a.push("origin", false).unwrap()[0].ok);
4463
    drop(a);
4464
4465
    type Op = fn(&Repo) -> Result<()>;
4466
    let edit_and_commit: Op = |r| {
4467
        write(r.root(), "f.txt", b"one\ntwo\n");
4468
        write(r.root(), "big.bin", &vec![7u8; 300_000]);
4469
        r.commit("second", &[]).map(|_| ())
4470
    };
4471
    let push: Op = |r| {
4472
        let res = r.push("origin", false)?;
4473
        if res.iter().all(|x| x.ok) {
4474
            Ok(())
4475
        } else {
4476
            Err(RepoError::Msg(format!("{res:?}")))
4477
        }
4478
    };
4479
4480
    for (name, prepare, op) in [
4481
        ("commit", None, edit_and_commit),
4482
        ("push", Some(edit_and_commit), push),
4483
    ] {
4484
        let mut steps = 0;
4485
        for n in 1.. {
4486
            let run = dir.path().join(format!("{name}-{n}"));
4487
            copy_tree(&pristine, &run);
4488
            // Clones record their remote by path; point it at this copy.
4489
            let open = |p: &Path| {
4490
                let mut r = Repo::open(p).unwrap().with_home(dir.path().join("home"));
4491
                r.config
4492
                    .set("remote.origin.url", &run.join("origin").to_string_lossy())
4493
                    .unwrap();
4494
                r.save_config().unwrap();
4495
                r
4496
            };
4497
            let a = open(&run.join("a"));
4498
            if let Some(prep) = prepare {
4499
                prep(&a).unwrap();
4500
            }
4501
            failpoint::crash_after(n);
4502
            let outcome = op(&a);
4503
            let crashed = failpoint::disarm();
4504
            drop(a);
4505
            if !crashed {
4506
                outcome.unwrap_or_else(|e| panic!("{name} failed without a crash: {e}"));
4507
                steps = n - 1;
4508
                break;
4509
            }
4510
            assert!(
4511
                outcome.is_err(),
4512
                "{name}: a crash at step {n} was swallowed"
4513
            );
4514
            for repo in ["a", "origin"] {
4515
                let r = Repo::open(&run.join(repo)).unwrap_or_else(|e| {
4516
                    panic!("{name} crash at step {n}: {repo} no longer opens: {e}")
4517
                });
4518
                let rep = r.fsck().unwrap();
4519
                assert_eq!(
4520
                    rep.errors(),
4521
                    0,
4522
                    "{name} crash at step {n}: {repo} fails fsck: {:?}",
4523
                    rep.problems
4524
                );
4525
            }
4526
            // The interrupted operation can simply be run again.
4527
            let a = open(&run.join("a"));
4528
            // A crash after the commit point leaves the commit done.
4529
            let landed = a
4530
                .bookmark_heads()
4531
                .unwrap()
4532
                .iter()
4533
                .any(|h| a.store().get_change(h).unwrap().message == "second");
4534
            let again = match (name, landed) {
4535
                ("commit", true) => Ok(()),
4536
                ("commit", false) => a.commit("second", &[]).map(|_| ()),
4537
                _ => op(&a),
4538
            };
4539
            again.unwrap_or_else(|e| panic!("{name} crash at step {n}: retry failed: {e}"));
4540
            assert_eq!(a.fsck().unwrap().errors(), 0);
4541
            fs::remove_dir_all(&run).unwrap();
4542
        }
4543
        assert!(steps >= 3, "{name} has only {steps} durable steps?");
4544
    }
4545
}
4546
4547
/// Spec §12.1: commands in two workspaces of one repository, and pushes,
4548
/// running at the same time lose nothing: every commit ends up on the
4549
/// bookmark, locally and on the remote, and the repository passes fsck.
4550
#[test]
4551
fn concurrent_commits_in_two_workspaces_lose_nothing() {
4552
    hermetic();
4553
    let dir = tempfile::tempdir().unwrap();
4554
    let root = dir.path();
4555
    let origin = root.join("origin");
4556
    Repo::init_bare_unbound(&origin).unwrap();
4557
    let main = root.join("main");
4558
    let mut repo = Repo::init(&main).unwrap();
4559
    repo.config
4560
        .set("remote.origin.url", &origin.to_string_lossy())
4561
        .unwrap();
4562
    repo.save_config().unwrap();
4563
    write(&main, "seed.txt", b"seed\n");
4564
    repo.commit("seed", &[]).unwrap();
4565
    let second = root.join("second");
4566
    repo.workspace_add(&second, None).unwrap();
4567
    drop(repo);
4568
4569
    const EACH: usize = 15;
4570
    std::thread::scope(|s| {
4571
        for (tag, dir, push) in [("a", main.clone(), true), ("b", second.clone(), false)] {
4572
            s.spawn(move || {
4573
                let r = Repo::open(&dir).unwrap();
4574
                for i in 0..EACH {
4575
                    write(
4576
                        &dir,
4577
                        &format!("{tag}-{i}.txt"),
4578
                        format!("{tag} {i}\n").as_bytes(),
4579
                    );
4580
                    r.commit(&format!("{tag} {i}"), &[]).unwrap();
4581
                    if push && i % 5 == 4 {
4582
                        // A push may be refused while the other workspace moves the bookmark; nothing may be lost either way.
4583
                        let _ = r.push("origin", false);
4584
                    }
4585
                }
4586
            });
4587
        }
4588
    });
4589
4590
    let repo = Repo::open(&main).unwrap();
4591
    let heads = repo.bookmark_heads().unwrap();
4592
    let state = repo.load_state(&heads).unwrap();
4593
    let messages: BTreeSet<String> = state.changes().map(|(_, m)| m.message.clone()).collect();
4594
    for tag in ["a", "b"] {
4595
        for i in 0..EACH {
4596
            assert!(
4597
                messages.contains(&format!("{tag} {i}")),
4598
                "lost commit {tag} {i}; have {messages:?}"
4599
            );
4600
        }
4601
    }
4602
    let rep = repo.fsck().unwrap();
4603
    assert_eq!(rep.errors(), 0, "{:?}", rep.problems);
4604
    assert!(repo.push("origin", false).unwrap().iter().all(|r| r.ok));
4605
    let hosted = Repo::open(&origin).unwrap();
4606
    let hosted_heads = hosted.bookmark_heads().unwrap();
4607
    assert_eq!(
4608
        hosted.load_state(&hosted_heads).unwrap().len(),
4609
        state.len(),
4610
        "the remote has every commit"
4611
    );
4612
}
4613
4614
/// Two operations recorded from the same parent (what two processes do
4615
/// when they race) are merged: both bookmarks' heads survive, and a
4616
/// change made on one side only is kept.
4617
#[test]
4618
fn operations_from_the_same_parent_are_merged() {
4619
    hermetic();
4620
    let dir = tempfile::tempdir().unwrap();
4621
    let root = dir.path();
4622
    let repo = Repo::init(root).unwrap();
4623
    write(root, "a.txt", b"a\n");
4624
    let a = repo.commit("a", &[]).unwrap();
4625
    write(root, "b.txt", b"b\n");
4626
    let b = repo.commit("b", &[]).unwrap();
4627
    let (x, op) = repo.head_op().unwrap();
4628
    let state = |heads: Vec<ChangeHash>| repo.store().put_state(&StateObject::new(heads)).unwrap();
4629
4630
    // Side one moves main to just `a` and adds a bookmark; side two moves main to just `b`.
4631
    let mut one = op.view.clone();
4632
    one.bookmarks.insert("main".into(), state(vec![a]));
4633
    one.bookmarks.insert("topic".into(), state(vec![a]));
4634
    let mut two = op.view.clone();
4635
    two.bookmarks.insert("main".into(), state(vec![b]));
4636
    repo.record_op(&[x], "one", one).unwrap();
4637
    let merged = repo.record_op(&[x], "two", two).unwrap();
4638
4639
    let (head, op) = repo.head_op().unwrap();
4640
    assert_eq!(head, merged);
4641
    assert_eq!(op.parents.len(), 2, "a merge of the two operations");
4642
    assert!(op.command.contains("merged with a concurrent operation"));
4643
    let mut main = repo
4644
        .store()
4645
        .get_state(&op.view.bookmarks["main"])
4646
        .unwrap()
4647
        .heads;
4648
    main.sort();
4649
    let mut want = vec![a, b];
4650
    want.sort();
4651
    assert_eq!(main, want, "both sides' heads are kept");
4652
    assert!(
4653
        op.view.bookmarks.contains_key("topic"),
4654
        "a one-sided change survives"
4655
    );
4656
    assert_eq!(repo.fsck().unwrap().errors(), 0);
4657
}
4658
4659
#[test]
4660
fn failed_requests_come_with_a_next_step() {
4661
    use crate::protocol::hint_for;
4662
    assert!(hint_for("https://h/x/oxy/v1/push: HTTP 401: bad token")
4663
        .unwrap()
4664
        .contains("token"));
4665
    assert!(hint_for("…: HTTP 403: forbidden")
4666
        .unwrap()
4667
        .contains("repo:write"));
4668
    assert!(hint_for("…: HTTP 404: no such repository")
4669
        .unwrap()
4670
        .contains("owner and repository name"));
4671
    assert!(hint_for("invalid peer certificate: UnknownIssuer")
4672
        .unwrap()
4673
        .contains("oxyhub-ca.pem"));
4674
    assert!(hint_for("Connect error: Connection refused (os error 111)")
4675
        .unwrap()
4676
        .contains("running"));
4677
    assert!(hint_for("Dns Failed: failed to lookup address information")
4678
        .unwrap()
4679
        .contains("resolve"));
4680
    assert_eq!(hint_for("something else entirely"), None);
4681
}
4682
4683
#[test]
4684
fn doctor_names_problems_and_what_to_do() {
4685
    hermetic();
4686
    let dir = tempfile::tempdir().unwrap();
4687
    let root = dir.path();
4688
    let origin = root.join("origin");
4689
    Repo::init_bare_unbound(&origin).unwrap();
4690
    let mut repo = Repo::init(&root.join("r"))
4691
        .unwrap()
4692
        .with_home(root.join("home"));
4693
    let find = |r: &DoctorReport, area: &str, h: Health| {
4694
        r.checks
4695
            .iter()
4696
            .find(|c| c.area == area && c.health == h)
4697
            .cloned()
4698
    };
4699
4700
    let r = repo.doctor(true);
4701
    assert!(find(&r, "identity", Health::Warn)
4702
        .unwrap()
4703
        .hint
4704
        .unwrap()
4705
        .contains("oxy identity create"));
4706
    assert!(find(&r, "repository", Health::Ok).is_some());
4707
4708
    repo.create_identity("Ada", "[email protected]", IdentityScope::Repo)
4709
        .unwrap();
4710
    repo.config.set("author.name", "Ada").unwrap();
4711
    repo.config.set("author.email", "[email protected]").unwrap();
4712
    repo.config
4713
        .set("remote.origin.url", &origin.to_string_lossy())
4714
        .unwrap();
4715
    repo.config
4716
        .set("remote.down.url", "http://127.0.0.1:9/a/b")
4717
        .unwrap();
4718
    repo.config.set("remote.down.token", "t").unwrap();
4719
    repo.config
4720
        .set("remote.badca.url", "https://example.invalid/a/b")
4721
        .unwrap();
4722
    repo.config
4723
        .set(
4724
            "remote.badca.ca",
4725
            &root.join("missing.pem").to_string_lossy(),
4726
        )
4727
        .unwrap();
4728
    repo.save_config().unwrap();
4729
4730
    let r = repo.doctor(true);
4731
    assert!(find(&r, "identity", Health::Ok).is_some(), "{r:?}");
4732
    assert!(find(&r, "author", Health::Ok).is_some(), "{r:?}");
4733
    assert!(find(&r, "remote origin", Health::Ok)
4734
        .unwrap()
4735
        .message
4736
        .contains("first push binds it"));
4737
    let down = find(&r, "remote down", Health::Fail).unwrap();
4738
    assert!(
4739
        down.hint.as_deref().unwrap_or("").contains("running"),
4740
        "{down:?}"
4741
    );
4742
    let badca = find(&r, "remote badca", Health::Fail).unwrap();
4743
    assert!(
4744
        badca.hint.unwrap().contains("remote.badca.ca"),
4745
        "the remote's own name is in the hint"
4746
    );
4747
    assert_eq!(r.worst(), Health::Fail);
4748
4749
    // Offline, nothing is contacted.
4750
    let r = repo.doctor(false);
4751
    assert!(find(&r, "remote down", Health::Fail).is_none());
4752
    assert!(find(&r, "remote down", Health::Ok)
4753
        .unwrap()
4754
        .message
4755
        .contains("not contacted"));
4756
}
4757
4758
/// Spec §8.1: deleting a line depends on whoever inserted the lines right
4759
/// after it. Inserting after `b` and then deleting `b`, one commit after
4760
/// the other, must not leave a delete/insert conflict.
4761
#[test]
4762
fn deleting_a_line_after_an_insertion_below_it_is_not_a_conflict() {
4763
    hermetic();
4764
    let dir = tempfile::tempdir().unwrap();
4765
    let root = dir.path();
4766
    let repo = Repo::init(root).unwrap();
4767
    write(root, "f", b"a\nb\nc\n");
4768
    repo.commit("base", &[]).unwrap();
4769
    write(root, "f", b"a\nb\nx\nc\n");
4770
    let insert = repo.commit("insert x after b", &[]).unwrap();
4771
    write(root, "f", b"a\nx\nc\n");
4772
    let delete = repo.commit("delete b", &[]).unwrap();
4773
    assert!(
4774
        repo.store()
4775
            .get_change(&delete)
4776
            .unwrap()
4777
            .deps
4778
            .contains(&insert),
4779
        "the deletion depends on the insertion below the deleted line"
4780
    );
4781
    let heads = repo.bookmark_heads().unwrap();
4782
    assert_eq!(heads, vec![delete]);
4783
    let snap = repo.load_state(&heads).unwrap().materialize();
4784
    assert!(!snap.is_conflicted());
4785
    assert!(
4786
        matches!(&snap.files["f"].content, FileContent::Text { bytes, .. } if bytes == b"a\nx\nc\n")
4787
    );
4788
}
4789
4790
/// Spec §9.3: a binary file reverted to an earlier blob keeps it, and each
4791
/// replacement depends on the change that set the blob it replaces.
4792
#[test]
4793
fn a_binary_file_reverted_to_an_earlier_blob_keeps_it() {
4794
    hermetic();
4795
    let dir = tempfile::tempdir().unwrap();
4796
    let root = dir.path();
4797
    let repo = Repo::init(root).unwrap();
4798
    write(root, "bin", b"\0A");
4799
    let v1 = repo.commit("v1", &[]).unwrap();
4800
    write(root, "bin", b"\0B");
4801
    let v2 = repo.commit("v2", &[]).unwrap();
4802
    assert!(repo.store().get_change(&v2).unwrap().deps.contains(&v1));
4803
    write(root, "bin", b"\0A");
4804
    let v3 = repo.commit("back to A", &[]).unwrap();
4805
    assert!(repo.store().get_change(&v3).unwrap().deps.contains(&v2));
4806
    assert_eq!(repo.bookmark_heads().unwrap(), vec![v3]);
4807
    let state = repo.load_state(&[v3]).unwrap();
4808
    let snap = state.materialize();
4809
    let FileContent::Opaque { blobs } = &snap.files["bin"].content else {
4810
        panic!("opaque")
4811
    };
4812
    assert_eq!(blobs.len(), 1, "one live blob, not none and not two");
4813
    assert_eq!(repo.read_blob(&blobs[0]).unwrap(), b"\0A");
4814
}
4815
4816
/// Spec §23: a binary file changed on two branches and merged in Git to
4817
/// one side's version comes back as that version at the merge, and the
4818
/// import verifies commit by commit.
4819
#[test]
4820
fn git_import_resolves_a_binary_merged_in_git_and_verifies() {
4821
    hermetic();
4822
    if std::process::Command::new("git")
4823
        .arg("--version")
4824
        .output()
4825
        .is_err()
4826
    {
4827
        eprintln!("git not installed; skipping");
4828
        return;
4829
    }
4830
    let dir = tempfile::tempdir().unwrap();
4831
    let root = dir.path();
4832
    let g = root.join("src.git");
4833
    fs::create_dir_all(&g).unwrap();
4834
    let git = |args: &[&str]| -> String {
4835
        let out = std::process::Command::new("git")
4836
            .arg("-C")
4837
            .arg(&g)
4838
            .args([
4839
                "-c",
4840
                "user.name=Grace",
4841
                "-c",
4842
                "[email protected]",
4843
                "-c",
4844
                "commit.gpgsign=false",
4845
            ])
4846
            .args(args)
4847
            .output()
4848
            .unwrap();
4849
        assert!(
4850
            out.status.success(),
4851
            "git {args:?}: {}",
4852
            String::from_utf8_lossy(&out.stderr)
4853
        );
4854
        String::from_utf8_lossy(&out.stdout).trim().to_string()
4855
    };
4856
    git(&["init", "-q", "-b", "main"]);
4857
    write(&g, "logo.bin", b"\0base");
4858
    write(&g, "notes.txt", b"a\nb\nc\n");
4859
    git(&["add", "."]);
4860
    git(&["commit", "-qm", "base"]);
4861
    git(&["checkout", "-qb", "side"]);
4862
    write(&g, "logo.bin", b"\0side");
4863
    write(&g, "notes.txt", b"a\nb\nx\nc\n");
4864
    git(&["commit", "-qam", "side"]);
4865
    git(&["checkout", "-q", "main"]);
4866
    write(&g, "logo.bin", b"\0main");
4867
    git(&["commit", "-qam", "main"]);
4868
    // Git cannot merge the binary; the merge takes main's and keeps side's text.
4869
    let _ = std::process::Command::new("git")
4870
        .arg("-C")
4871
        .arg(&g)
4872
        .args([
4873
            "-c",
4874
            "user.name=G",
4875
            "-c",
4876
            "user.email=g@e",
4877
            "merge",
4878
            "-q",
4879
            "side",
4880
        ])
4881
        .output();
4882
    write(&g, "logo.bin", b"\0main");
4883
    git(&["add", "."]);
4884
    git(&["commit", "-qm", "merge side"]);
4885
    // Then a revert of the binary to its first version.
4886
    write(&g, "logo.bin", b"\0base");
4887
    git(&["commit", "-qam", "back to base"]);
4888
4889
    let repo = Repo::init(&root.join("o")).unwrap();
4890
    let rep = repo.import_git(&g, "main").unwrap();
4891
    assert_eq!(rep.merges, 1);
4892
    let v = repo.verify_git_import(&g, "main").unwrap();
4893
    assert!(v.mismatches.is_empty(), "{:?}", v.mismatches);
4894
    assert_eq!(v.commits, 5);
4895
    let snap = repo
4896
        .load_state(&repo.bookmark_heads().unwrap())
4897
        .unwrap()
4898
        .materialize();
4899
    assert!(!snap.is_conflicted());
4900
    let FileContent::Opaque { blobs } = &snap.files["logo.bin"].content else {
4901
        panic!("opaque")
4902
    };
4903
    assert_eq!(repo.read_blob(&blobs[0]).unwrap(), b"\0base");
4904
}
4905
4906
/// Spec §7.7 on a file system without executable bits or symlinks: the
4907
/// recorded bit is kept, and a symlink checked out as a plain file holding
4908
/// its target is still that symlink.
4909
#[cfg(unix)]
4910
#[test]
4911
fn windows_file_systems_keep_exec_bits_and_symlinks() {
4912
    use crate::portable::Platform;
4913
    use std::os::unix::fs::PermissionsExt;
4914
    hermetic();
4915
    let dir = tempfile::tempdir().unwrap();
4916
    let root = dir.path();
4917
    let repo = Repo::init(root).unwrap();
4918
    write(root, "run.sh", b"#!/bin/sh\n");
4919
    fs::set_permissions(root.join("run.sh"), fs::Permissions::from_mode(0o755)).unwrap();
4920
    std::os::unix::fs::symlink("run.sh", root.join("link")).unwrap();
4921
    repo.commit("script and link", &[]).unwrap();
4922
    drop(repo);
4923
4924
    // What checking out on Windows leaves: no exec bit, the link as a file.
4925
    fs::set_permissions(root.join("run.sh"), fs::Permissions::from_mode(0o644)).unwrap();
4926
    fs::remove_file(root.join("link")).unwrap();
4927
    write(root, "link", b"run.sh");
4928
    let win = Repo::open(root).unwrap().with_platform(Platform::windows());
4929
    let s = win.snapshot("oxy status").unwrap();
4930
    assert!(
4931
        s.statuses.is_empty(),
4932
        "nothing changed on Windows: {:?}",
4933
        statuses(&s)
4934
    );
4935
    // Editing the file is a content change, not a mode change; retargeting the link keeps it a link.
4936
    write(root, "run.sh", b"#!/bin/sh\necho hi\n");
4937
    write(root, "link", b"other");
4938
    let h = win.commit("edit on Windows", &[]).unwrap();
4939
    let snap = win.load_state(&[h]).unwrap().materialize();
4940
    assert!(snap.files["run.sh"].mode.exec, "the exec bit survives");
4941
    assert_eq!(snap.files["link"].kind, NodeKind::Symlink);
4942
    // The same working copy read as Linux sees the lost bit and the plain file.
4943
    let linux = Repo::open(root).unwrap();
4944
    assert!(!linux.snapshot("oxy status").unwrap().statuses.is_empty());
4945
}
4946
4947
/// Paths that collide on case-insensitive or Windows file systems are
4948
/// named at checkout there, and by doctor everywhere.
4949
#[test]
4950
fn paths_other_platforms_cannot_hold_are_reported() {
4951
    use crate::portable::Platform;
4952
    hermetic();
4953
    let dir = tempfile::tempdir().unwrap();
4954
    let root = dir.path();
4955
    let repo = Repo::init(root).unwrap();
4956
    write(root, "README.md", b"a\n");
4957
    write(root, "readme.md", b"b\n");
4958
    write(root, "src/aux.c", b"int x;\n");
4959
    let h = repo.commit("unportable", &[]).unwrap();
4960
    let r = repo.doctor(false);
4961
    let port = r.checks.iter().find(|c| c.area == "portability").unwrap();
4962
    assert_eq!(port.health, Health::Warn);
4963
    assert!(
4964
        port.message.contains("differ only in case") && port.message.contains("aux.c"),
4965
        "{}",
4966
        port.message
4967
    );
4968
    let mac = Repo::open(root).unwrap().with_platform(Platform::macos());
4969
    let rep = mac.checkout(&[h], true, "oxy checkout").unwrap();
4970
    assert!(
4971
        rep.notes
4972
            .iter()
4973
            .any(|n| n.contains("README.md and readme.md")),
4974
        "{:?}",
4975
        rep.notes
4976
    );
4977
    assert!(
4978
        !rep.notes.iter().any(|n| n.contains("aux.c")),
4979
        "macOS allows aux.c"
4980
    );
4981
}
4982
4983
#[test]
4984
fn history_and_blame_of_a_loaded_state_match_the_full_walk() {
4985
    hermetic();
4986
    let dir = tempfile::tempdir().unwrap();
4987
    let repo = Repo::init(dir.path()).unwrap();
4988
    write(dir.path(), "a.txt", b"one\n");
4989
    write(dir.path(), "other.txt", b"x\n");
4990
    write(dir.path(), "bin.dat", &[0u8, 1, 2, 0, 255]);
4991
    repo.snapshot("t").unwrap();
4992
    let c1 = repo.commit("first", &[]).unwrap();
4993
    write(dir.path(), "other.txt", b"y\n");
4994
    repo.snapshot("t").unwrap();
4995
    repo.commit("other only", &[]).unwrap();
4996
    write(dir.path(), "a.txt", b"one\ntwo\n");
4997
    repo.snapshot("t").unwrap();
4998
    let c3 = repo.commit("second line", &[]).unwrap();
4999
    write(dir.path(), "other.txt", b"z\n");
5000
    repo.snapshot("t").unwrap();
5001
    repo.commit("other again", &[]).unwrap();
5002
5003
    let heads = repo.bookmark_heads().unwrap();
5004
    let state = repo.load_state(&heads).unwrap();
5005
    let full: Vec<ChangeHash> = repo
5006
        .log_for_path_in("a.txt", &heads)
5007
        .unwrap()
5008
        .iter()
5009
        .map(|e| e.hash)
5010
        .collect();
5011
    assert_eq!(
5012
        full,
5013
        vec![c3, c1],
5014
        "newest first, only changes touching the path"
5015
    );
5016
    let newest: Vec<ChangeHash> = repo
5017
        .log_for_path_of(&state, "a.txt", Some(1))
5018
        .unwrap()
5019
        .iter()
5020
        .map(|e| e.hash)
5021
        .collect();
5022
    assert_eq!(newest, vec![c3], "stops at the first");
5023
    assert_eq!(
5024
        repo.log_for_path_of(&state, "a.txt", None).unwrap().len(),
5025
        2
5026
    );
5027
    assert!(repo
5028
        .log_for_path_of(&state, "missing.txt", Some(1))
5029
        .is_err());
5030
    assert_eq!(
5031
        repo.log_state(&heads).unwrap().len(),
5032
        repo.log_of(&state).len()
5033
    );
5034
5035
    let tree = state.tree().view();
5036
    let via_state = repo.blame_of(&state, &tree, "a.txt").unwrap();
5037
    let via_heads = repo.blame_in("a.txt", &heads).unwrap();
5038
    assert_eq!(
5039
        via_state
5040
            .iter()
5041
            .map(|l| (l.hash, l.text.clone()))
5042
            .collect::<Vec<_>>(),
5043
        via_heads
5044
            .iter()
5045
            .map(|l| (l.hash, l.text.clone()))
5046
            .collect::<Vec<_>>()
5047
    );
5048
    assert_eq!(
5049
        via_state.iter().map(|l| l.hash).collect::<Vec<_>>(),
5050
        vec![c1, c3]
5051
    );
5052
    assert!(repo.blame_of(&state, &tree, "missing.txt").is_err());
5053
}
5054
5055
/// A text file whose stat matches the manifest and whose recorded hash is
5056
/// the base's content is taken from the base without reading it; anything
5057
/// else is read, so no edit is missed (spec §12.3).
5058
#[cfg(unix)]
5059
#[test]
5060
fn stat_cache_takes_unchanged_text_from_the_base_and_misses_no_edit() {
5061
    use std::os::unix::fs::PermissionsExt;
5062
    hermetic();
5063
    let dir = tempfile::tempdir().unwrap();
5064
    let root = dir.path();
5065
    let repo = Repo::init(root).unwrap().with_home(root.join("home"));
5066
    write(root, "a.txt", b"one\ntwo\n");
5067
    write(root, "b.txt", b"bee\n");
5068
    repo.commit("base", &[]).unwrap();
5069
    let age = |p: &str| {
5070
        let old = std::time::SystemTime::now() - std::time::Duration::from_secs(30);
5071
        fs::File::options()
5072
            .write(true)
5073
            .open(root.join(p))
5074
            .unwrap()
5075
            .set_modified(old)
5076
            .unwrap();
5077
    };
5078
    age("a.txt");
5079
    age("b.txt");
5080
    assert!(
5081
        !repo.snapshot("status").unwrap().changed,
5082
        "records the aged stat"
5083
    );
5084
5085
    // Clean and equal to the base: not read at all.
5086
    fs::set_permissions(root.join("a.txt"), fs::Permissions::from_mode(0o000)).unwrap();
5087
    let snap = repo.snapshot("status").unwrap();
5088
    assert!(
5089
        !snap.changed && snap.statuses.is_empty(),
5090
        "{:?}",
5091
        snap.statuses
5092
    );
5093
    fs::set_permissions(root.join("a.txt"), fs::Permissions::from_mode(0o644)).unwrap();
5094
5095
    // An uncommitted edit that is older than the manifest: stat-clean, but
5096
    // its hash is not the base's, so it is read and stays visible.
5097
    write(root, "b.txt", b"bee edited\n");
5098
    age("b.txt");
5099
    let first = repo.snapshot("status").unwrap();
5100
    assert_eq!(
5101
        statuses(&first),
5102
        vec![("b.txt".to_string(), ChangeStatus::Modified)]
5103
    );
5104
    let again = repo.snapshot("status").unwrap();
5105
    assert_eq!(
5106
        statuses(&again),
5107
        vec![("b.txt".to_string(), ChangeStatus::Modified)],
5108
        "still seen once stat-clean"
5109
    );
5110
    assert!(!again.changed, "and the working copy hashes the same");
5111
    fs::set_permissions(root.join("b.txt"), fs::Permissions::from_mode(0o000)).unwrap();
5112
    assert!(
5113
        repo.snapshot("status").is_err(),
5114
        "an edited file must be read, never taken from the base"
5115
    );
5116
    fs::set_permissions(root.join("b.txt"), fs::Permissions::from_mode(0o644)).unwrap();
5117
5118
    // A same-size edit made just now is racy and read.
5119
    write(root, "a.txt", b"one\nTWO\n");
5120
    assert_eq!(
5121
        statuses(&repo.snapshot("status").unwrap()),
5122
        vec![
5123
            ("a.txt".to_string(), ChangeStatus::Modified),
5124
            ("b.txt".to_string(), ChangeStatus::Modified)
5125
        ]
5126
    );
5127
    // Committing makes the edits the base: both are clean and served from it again.
5128
    repo.commit("edits", &[]).unwrap();
5129
    age("a.txt");
5130
    age("b.txt");
5131
    assert!(repo.snapshot("status").unwrap().statuses.is_empty());
5132
    fs::set_permissions(root.join("a.txt"), fs::Permissions::from_mode(0o000)).unwrap();
5133
    fs::set_permissions(root.join("b.txt"), fs::Permissions::from_mode(0o000)).unwrap();
5134
    let snap = repo.snapshot("status").unwrap();
5135
    assert!(!snap.changed && snap.statuses.is_empty());
5136
    fs::set_permissions(root.join("a.txt"), fs::Permissions::from_mode(0o644)).unwrap();
5137
    fs::set_permissions(root.join("b.txt"), fs::Permissions::from_mode(0o644)).unwrap();
5138
}
5139
5140
/// Version 2 checkpoints (spec §11): a large file's graph is a blob of its
5141
/// own, kept by gc, checked by fsck, shared by the next checkpoint when the
5142
/// file is unchanged, and loading through the checkpoint equals a full load.
5143
#[test]
5144
fn checkpoints_keep_large_graphs_as_blobs_of_their_own() {
5145
    hermetic();
5146
    let dir = tempfile::tempdir().unwrap();
5147
    let root = dir.path();
5148
    let repo = Repo::init(root).unwrap().with_home(root.join("home"));
5149
    let long: String = (0..300)
5150
        .map(|i| format!("line {i} of a long file\n"))
5151
        .collect();
5152
    write(root, "long.txt", long.as_bytes());
5153
    write(root, "short.txt", b"short\n");
5154
    repo.commit("base", &[]).unwrap();
5155
    let (r1, _, _) = repo.checkpoint().unwrap();
5156
    let cp1 = crate::objects::Checkpoint::decode(
5157
        &repo.store().get_typed(&r1, ObjectType::Checkpoint).unwrap(),
5158
    )
5159
    .unwrap();
5160
    let graphs1 = repo.checkpoint_graph_blobs(&cp1).unwrap();
5161
    assert_eq!(graphs1.len(), 1, "only the long file's graph is a blob");
5162
5163
    // gc keeps the graph blob; fsck finds the checkpoint sound.
5164
    repo.gc(true).unwrap();
5165
    assert!(repo.store().has(&graphs1[0]));
5166
    let report = repo.fsck().unwrap();
5167
    assert_eq!(report.errors(), 0, "{:?}", report.problems);
5168
5169
    // Loading through the checkpoint equals a full load.
5170
    write(root, "short.txt", b"short, edited\n");
5171
    repo.commit("edit the short file", &[]).unwrap();
5172
    let heads = repo.bookmark_heads().unwrap();
5173
    let fast = repo.load_state(&heads).unwrap();
5174
    let full = repo.load_state_full(&heads).unwrap();
5175
    assert_eq!(fast.checkpoint_payload(), full.checkpoint_payload());
5176
5177
    // The next checkpoint shares the unchanged long file's graph.
5178
    let (r2, _, _) = repo.checkpoint().unwrap();
5179
    let cp2 = crate::objects::Checkpoint::decode(
5180
        &repo.store().get_typed(&r2, ObjectType::Checkpoint).unwrap(),
5181
    )
5182
    .unwrap();
5183
    assert_eq!(repo.checkpoint_graph_blobs(&cp2).unwrap(), graphs1);
5184
5185
    // A shallow clone's bundle carries the graph blob with the checkpoint.
5186
    let bundle = repo.checkpoint_bundle_for(&heads).unwrap();
5187
    assert!(bundle.objects.iter().any(|(t, body)| *t == ObjectType::Blob
5188
        && crate::hash::hash_object(ObjectType::Blob, body) == graphs1[0]));
5189
5190
    // A version 1 checkpoint written by an older oxy still loads.
5191
    let state = repo.load_state_full(&heads).unwrap();
5192
    let old = repo.store_blob(&state.checkpoint_payload()).unwrap();
5193
    let cp_old = crate::objects::Checkpoint {
5194
        heads: cp2.heads.clone(),
5195
        count: cp2.count,
5196
        payload: old,
5197
    };
5198
    let r_old = repo
5199
        .store()
5200
        .put(ObjectType::Checkpoint, &cp_old.encode())
5201
        .unwrap();
5202
    repo.install_checkpoint("main", &r_old).unwrap();
5203
    assert_eq!(
5204
        repo.load_state(&heads).unwrap().checkpoint_payload(),
5205
        full.checkpoint_payload()
5206
    );
5207
    assert_eq!(repo.fsck().unwrap().errors(), 0);
5208
5209
    // A lost graph blob fails the load loudly rather than dropping the
5210
    // file, and fsck reports it (a fresh repository, objects still loose).
5211
    let dir2 = tempfile::tempdir().unwrap();
5212
    let root2 = dir2.path();
5213
    let repo2 = Repo::init(root2).unwrap().with_home(root2.join("home"));
5214
    write(root2, "long.txt", long.as_bytes());
5215
    repo2.commit("base", &[]).unwrap();
5216
    let (r, _, _) = repo2.checkpoint().unwrap();
5217
    let cp = crate::objects::Checkpoint::decode(
5218
        &repo2.store().get_typed(&r, ObjectType::Checkpoint).unwrap(),
5219
    )
5220
    .unwrap();
5221
    let graph = repo2.checkpoint_graph_blobs(&cp).unwrap()[0];
5222
    repo2.store().remove_loose_for_test(&graph).unwrap();
5223
    assert!(repo2.load_state(&repo2.bookmark_heads().unwrap()).is_err());
5224
    assert!(repo2.fsck().unwrap().errors() > 0, "fsck reports it");
5225
}
5226
5227
/// A new repository has not stored the user's identity yet (that happens
5228
/// at the first signed change); looking it up falls back to the key
5229
/// directory, and a file there that does not hash to the key is refused.
5230
#[test]
5231
fn identity_is_found_in_the_key_directory_for_a_new_repository() {
5232
    hermetic();
5233
    let dir = tempfile::tempdir().unwrap();
5234
    let home = dir.path().join("home");
5235
    let mut first = Repo::init(&dir.path().join("a"))
5236
        .unwrap()
5237
        .with_home(home.clone());
5238
    let (key, _) = first
5239
        .create_identity("Ada", "[email protected]", IdentityScope::User)
5240
        .unwrap();
5241
    let fresh = Repo::init(&dir.path().join("b"))
5242
        .unwrap()
5243
        .with_home(home.clone());
5244
    assert!(!fresh.store().has(&key), "nothing stored yet");
5245
    let id = fresh.identity(&key).unwrap();
5246
    assert_eq!((id.name.as_str(), id.hash()), ("Ada", key));
5247
    // A key file that is not this identity is an error, not a wrong answer.
5248
    let keys = fresh.keys_dir.clone();
5249
    let (other, _) = first
5250
        .create_identity("Bob", "[email protected]", IdentityScope::User)
5251
        .unwrap();
5252
    fs::copy(
5253
        keys.join(format!("{}.identity", other.to_hex())),
5254
        keys.join(format!("{}.identity", key.to_hex())),
5255
    )
5256
    .unwrap();
5257
    assert!(fresh
5258
        .identity(&key)
5259
        .unwrap_err()
5260
        .to_string()
5261
        .contains("does not hold identity"));
5262
}
5263
5264
/// Status snapshots (spec §12.3): a text file whose stat matches the
5265
/// manifest, and whose base graph key is the one the manifest recorded it
5266
/// equal to, is neither read nor rendered; any edit, and any change to the
5267
/// file's graph in the base, brings it back.
5268
#[cfg(unix)]
5269
#[test]
5270
fn status_snapshots_skip_files_unchanged_since_the_manifest() {
5271
    use std::os::unix::fs::PermissionsExt;
5272
    hermetic();
5273
    let dir = tempfile::tempdir().unwrap();
5274
    let root = dir.path();
5275
    let repo = Repo::init(root).unwrap().with_home(root.join("home"));
5276
    for (p, c) in [("a.txt", "one\n"), ("b.txt", "bee\n"), ("d/c.txt", "sea\n")] {
5277
        write(root, p, c.as_bytes());
5278
    }
5279
    repo.commit("base", &[]).unwrap();
5280
    let age = |p: &str| {
5281
        let old = std::time::SystemTime::now() - std::time::Duration::from_secs(30);
5282
        fs::File::options()
5283
            .write(true)
5284
            .open(root.join(p))
5285
            .unwrap()
5286
            .set_modified(old)
5287
            .unwrap();
5288
    };
5289
    let lock = |p: &str, mode: u32| {
5290
        fs::set_permissions(root.join(p), fs::Permissions::from_mode(mode)).unwrap()
5291
    };
5292
    for p in ["a.txt", "b.txt", "d/c.txt"] {
5293
        age(p);
5294
    }
5295
    assert!(repo.snapshot("status").unwrap().statuses.is_empty());
5296
    let (_, _, m) = repo.read_manifest().unwrap().unwrap();
5297
    assert!(
5298
        m.entries.values().all(|e| e.graph.is_some()),
5299
        "keys recorded"
5300
    );
5301
5302
    // Unreadable files prove they are not read; the status snapshot does
5303
    // not render them either, and its base lacks their graphs.
5304
    lock("a.txt", 0o000);
5305
    lock("b.txt", 0o000);
5306
    let snap = repo.snapshot_status("status").unwrap();
5307
    assert!(!snap.changed && snap.statuses.is_empty());
5308
    assert_eq!(
5309
        snap.base_snapshot
5310
            .unrendered
5311
            .iter()
5312
            .cloned()
5313
            .collect::<Vec<_>>(),
5314
        vec!["a.txt", "b.txt", "d/c.txt"]
5315
    );
5316
    assert!(!snap.base.is_full());
5317
    assert!(!snap.base_snapshot.is_conflicted());
5318
    // A full snapshot does not read them either, but renders everything.
5319
    let full = repo.snapshot("status").unwrap();
5320
    assert!(full.statuses.is_empty() && full.base.is_full());
5321
    assert!(full.base_snapshot.unrendered.is_empty());
5322
    assert!(matches!(&full.base_snapshot.files["a.txt"].content,
5323
        FileContent::Text { bytes, .. } if bytes == b"one\n"));
5324
5325
    // An edit is seen; the file is rendered, the others still are not.
5326
    write(root, "d/c.txt", b"sea edited\n");
5327
    let snap = repo.snapshot_status("status").unwrap();
5328
    assert_eq!(
5329
        statuses(&snap),
5330
        vec![("d/c.txt".to_string(), ChangeStatus::Modified)]
5331
    );
5332
    assert!(!snap.base_snapshot.unrendered.contains("d/c.txt"));
5333
    // So is a mode change of an unread file.
5334
    lock("b.txt", 0o100);
5335
    assert_eq!(
5336
        statuses(&repo.snapshot_status("status").unwrap()),
5337
        vec![
5338
            ("b.txt".to_string(), ChangeStatus::ModeChanged),
5339
            ("d/c.txt".to_string(), ChangeStatus::Modified)
5340
        ]
5341
    );
5342
    lock("b.txt", 0o000);
5343
5344
    // Committing c.txt changes its graph in the base, not a.txt's: a.txt
5345
    // stays unread, c.txt is read once and then skipped too.
5346
    repo.commit_selection("edit c", &[], &Selection::Paths(vec!["d/c.txt".into()]))
5347
        .unwrap();
5348
    age("d/c.txt");
5349
    let snap = repo.snapshot_status("status").unwrap();
5350
    assert!(snap.statuses.is_empty(), "{:?}", snap.statuses);
5351
    assert!(snap.base_snapshot.unrendered.contains("a.txt"));
5352
    lock("d/c.txt", 0o000);
5353
    let snap = repo.snapshot_status("status").unwrap();
5354
    assert!(snap.statuses.is_empty());
5355
    assert!(snap.base_snapshot.unrendered.contains("d/c.txt"));
5356
    for p in ["a.txt", "b.txt", "d/c.txt"] {
5357
        lock(p, 0o644);
5358
    }
5359
}
5360
5361
/// Attributes decide how a file compares with the base, so a changed
5362
/// `.oxyattributes` makes every text file be compared again.
5363
#[cfg(unix)]
5364
#[test]
5365
fn a_changed_attributes_file_disables_skipping_unchanged_files() {
5366
    hermetic();
5367
    let dir = tempfile::tempdir().unwrap();
5368
    let root = dir.path();
5369
    let repo = Repo::init(root).unwrap().with_home(root.join("home"));
5370
    write(root, "a.txt", b"crlf\r\n");
5371
    repo.commit("base", &[]).unwrap();
5372
    let old = std::time::SystemTime::now() - std::time::Duration::from_secs(30);
5373
    fs::File::options()
5374
        .write(true)
5375
        .open(root.join("a.txt"))
5376
        .unwrap()
5377
        .set_modified(old)
5378
        .unwrap();
5379
    assert!(repo.snapshot_status("status").unwrap().statuses.is_empty());
5380
    assert!(repo
5381
        .snapshot_status("status")
5382
        .unwrap()
5383
        .base_snapshot
5384
        .unrendered
5385
        .contains("a.txt"));
5386
    // With eol=lf, a.txt as stored no longer equals the base.
5387
    write(root, ".oxyattributes", b"*.txt eol=lf\n");
5388
    let snap = repo.snapshot_status("status").unwrap();
5389
    assert_eq!(
5390
        statuses(&snap),
5391
        vec![
5392
            (".oxyattributes".to_string(), ChangeStatus::Added),
5393
            ("a.txt".to_string(), ChangeStatus::Modified)
5394
        ]
5395
    );
5396
}
5397
5398
/// Bookmarks with `/` in their names: pushing records their
5399
/// attestations, and checkpoints are kept for them, beside `feature`
5400
/// itself.
5401
#[test]
5402
fn bookmarks_with_slashes_push_and_checkpoint() {
5403
    hermetic();
5404
    let dir = tempfile::tempdir().unwrap();
5405
    let root = dir.path();
5406
    let origin = Repo::init(&root.join("origin")).unwrap();
5407
    let url = root.join("origin").to_string_lossy().to_string();
5408
    let mut repo = Repo::clone(&url, &root.join("r"))
5409
        .unwrap()
5410
        .with_home(root.join("home"));
5411
    // With an identity, pushes carry reference attestations: the case
5412
    // that failed, since the attestation is a file named after the bookmark.
5413
    repo.create_identity("Ada", "[email protected]", IdentityScope::Repo)
5414
        .unwrap();
5415
    let r = root.join("r");
5416
    write(&r, "a.txt", b"a\n");
5417
    let h_a = repo.commit("a", &[]).unwrap();
5418
    assert!(repo.push("origin", false).unwrap()[0].ok);
5419
    origin.refresh().unwrap();
5420
    repo.bookmark_create("feature", None).unwrap();
5421
    repo.bookmark_create("feature/x", None).unwrap();
5422
    repo.bookmark_switch("feature/x", false).unwrap();
5423
    write(&r, "b.txt", b"b\n");
5424
    let h_b = repo.commit("b", &[]).unwrap();
5425
    for name in ["feature", "feature/x"] {
5426
        let res = repo.push_bookmark("origin", name, false).unwrap();
5427
        origin.refresh().unwrap();
5428
        assert!(res[0].ok, "{name}: {res:?}");
5429
    }
5430
    assert_eq!(origin.resolve_heads("feature").unwrap(), vec![h_a]);
5431
    assert_eq!(
5432
        origin.resolve_heads("feature/x").unwrap(),
5433
        repo.resolve_heads("feature/x").unwrap()
5434
    );
5435
    assert!(origin.resolve_heads("feature/x").unwrap().contains(&h_b));
5436
    assert!(origin.latest_ref_attest("feature/x").unwrap().is_some());
5437
    assert!(origin.latest_ref_attest("feature").unwrap().is_some());
5438
5439
    // A checkpoint of feature/x is found again when loading its state.
5440
    let (cp, _, _) = repo.checkpoint().unwrap();
5441
    assert_eq!(repo.latest_checkpoint("feature/x").unwrap().unwrap().0, cp);
5442
    assert!(repo.latest_checkpoint("feature").unwrap().is_none());
5443
    let heads = repo.resolve_heads("feature/x").unwrap();
5444
    assert!(repo.load_state_checkpointed(&heads).unwrap().is_some());
5445
}
5446
5447
/// Deleting a bookmark on a remote (spec §16.4): attested like any update,
5448
/// never the remote's own bookmark, and a bookmark created again later is
5449
/// accepted although the deletion's attestation stays the latest.
5450
#[test]
5451
fn bookmarks_are_deleted_on_a_remote() {
5452
    hermetic();
5453
    let dir = tempfile::tempdir().unwrap();
5454
    let root = dir.path();
5455
    let origin = Repo::init(&root.join("origin")).unwrap();
5456
    let url = root.join("origin").to_string_lossy().to_string();
5457
    let mut repo = Repo::clone(&url, &root.join("r"))
5458
        .unwrap()
5459
        .with_home(root.join("home"));
5460
    repo.create_identity("Ada", "[email protected]", IdentityScope::Repo)
5461
        .unwrap();
5462
    let r = root.join("r");
5463
    write(&r, "a.txt", b"a\n");
5464
    repo.commit("a", &[]).unwrap();
5465
    assert!(repo.push("origin", false).unwrap()[0].ok);
5466
    origin.refresh().unwrap();
5467
    repo.bookmark_create("feature/x", None).unwrap();
5468
    assert!(repo.push_bookmark("origin", "feature/x", false).unwrap()[0].ok);
5469
    origin.refresh().unwrap();
5470
    assert!(origin.resolve_heads("feature/x").is_ok());
5471
5472
    let res = repo.push_delete("origin", "feature/x").unwrap();
5473
    origin.refresh().unwrap();
5474
    assert!(res[0].ok, "{res:?}");
5475
    assert!(!origin.view().unwrap().bookmarks.contains_key("feature/x"));
5476
    let (_, att) = origin.latest_ref_attest("feature/x").unwrap().unwrap();
5477
    assert!(
5478
        matches!(att.attest.body, AttestBody::Ref { new_state, .. } if new_state.is_zero()),
5479
        "the deletion is attested"
5480
    );
5481
    assert!(
5482
        repo.view().unwrap().bookmarks.contains_key("feature/x"),
5483
        "the local bookmark stays"
5484
    );
5485
    assert!(!repo
5486
        .view()
5487
        .unwrap()
5488
        .remotes
5489
        .get("origin")
5490
        .is_some_and(|m| m.contains_key("feature/x")));
5491
5492
    // Pushing it again creates it again, past the deletion's serial.
5493
    let res = repo.push_bookmark("origin", "feature/x", false).unwrap();
5494
    origin.refresh().unwrap();
5495
    assert!(res[0].ok, "{res:?}");
5496
    assert!(origin.view().unwrap().bookmarks.contains_key("feature/x"));
5497
5498
    // Nothing to delete, and never the remote's own bookmark.
5499
    assert!(repo.push_delete("origin", "nope").is_err());
5500
    let res = repo.push_delete("origin", "main").unwrap();
5501
    origin.refresh().unwrap();
5502
    assert!(
5503
        !res[0].ok && res[0].reason.contains("default bookmark"),
5504
        "{res:?}"
5505
    );
5506
    assert!(origin.view().unwrap().bookmarks.contains_key("main"));
5507
}
5508
5509
/// `bookmark switch --carry` (spec §10.1): uncommitted work goes along
5510
/// when the target has the same versions of the files it touches, and is
5511
/// refused, untouched, when it has others.
5512
#[test]
5513
fn switching_bookmarks_carries_uncommitted_work() {
5514
    hermetic();
5515
    let dir = tempfile::tempdir().unwrap();
5516
    let root = dir.path();
5517
    let mut repo = Repo::init(root).unwrap().with_home(root.join("home"));
5518
    write(root, "a.txt", b"a\n");
5519
    write(root, "b.txt", b"b\n");
5520
    write(root, "gone.txt", b"gone\n");
5521
    repo.commit("base", &[]).unwrap();
5522
    repo.bookmark_create("feature", None).unwrap();
5523
    // Started on main, belongs on feature: edit, add, remove.
5524
    write(root, "a.txt", b"a\nmore\n");
5525
    write(root, "new.txt", b"new\n");
5526
    fs::remove_file(root.join("gone.txt")).unwrap();
5527
    let (_, carried) = repo.bookmark_switch_carry("feature").unwrap();
5528
    assert_eq!(carried, vec!["a.txt", "gone.txt", "new.txt"]);
5529
    assert_eq!(repo.config.bookmark, "feature");
5530
    assert_eq!(fs::read(root.join("a.txt")).unwrap(), b"a\nmore\n");
5531
    assert_eq!(fs::read(root.join("new.txt")).unwrap(), b"new\n");
5532
    assert!(!root.join("gone.txt").exists());
5533
    let snap = repo.snapshot("status").unwrap();
5534
    assert_eq!(
5535
        statuses(&snap),
5536
        vec![
5537
            ("a.txt".to_string(), ChangeStatus::Modified),
5538
            ("gone.txt".to_string(), ChangeStatus::Removed),
5539
            ("new.txt".to_string(), ChangeStatus::Added)
5540
        ]
5541
    );
5542
    repo.commit("the work", &[]).unwrap();
5543
    assert!(repo.resolve_heads("main").unwrap().len() == 1);
5544
5545
    // main moves b.txt on; work on feature touching b.txt cannot follow.
5546
    repo.bookmark_switch("main", false).unwrap();
5547
    write(root, "b.txt", b"b on main\n");
5548
    repo.commit("b on main", &[]).unwrap();
5549
    repo.bookmark_switch("feature", false).unwrap();
5550
    write(root, "b.txt", b"b edited\n");
5551
    let err = repo.bookmark_switch_carry("main").unwrap_err().to_string();
5552
    assert!(err.contains("b.txt") && err.contains("--discard"), "{err}");
5553
    assert_eq!(repo.config.bookmark, "feature", "nothing happened");
5554
    assert_eq!(fs::read(root.join("b.txt")).unwrap(), b"b edited\n");
5555
}
5556
5557
/// Merging and checking out (feedback 3): a working copy without changes
5558
/// follows a merge whichever state it sat on; a refused checkout names
5559
/// what is in the way; `checkout --carry` takes the work along.
5560
#[test]
5561
fn merges_move_clean_working_copies_and_checkouts_say_what_blocks_them() {
5562
    hermetic();
5563
    let dir = tempfile::tempdir().unwrap();
5564
    let root = dir.path();
5565
    let mut repo = Repo::init(root).unwrap().with_home(root.join("home"));
5566
    write(root, "a.txt", b"a\n");
5567
    let h1 = repo.commit("a", &[]).unwrap();
5568
    write(root, "b.txt", b"b\n");
5569
    repo.commit("b", &[]).unwrap();
5570
    repo.bookmark_create("feature", None).unwrap();
5571
    repo.bookmark_switch("feature", false).unwrap();
5572
    write(root, "c.txt", b"c\n");
5573
    repo.commit("c on feature", &[]).unwrap();
5574
    repo.bookmark_switch("main", false).unwrap();
5575
    // The working copy sits on an older state than main's heads.
5576
    repo.checkout(&[h1], false, "checkout").unwrap();
5577
    assert!(!root.join("b.txt").exists());
5578
    let m = repo.merge("feature").unwrap();
5579
    assert!(m.checked_out, "a clean working copy follows the merge");
5580
    for f in ["a.txt", "b.txt", "c.txt"] {
5581
        assert!(root.join(f).exists(), "{f}");
5582
    }
5583
5584
    // A refusal says which paths are in the way and what to do.
5585
    fs::remove_file(root.join("b.txt")).unwrap();
5586
    write(root, "a.txt", b"a edited\n");
5587
    let err = repo
5588
        .checkout(&[h1], false, "checkout")
5589
        .unwrap_err()
5590
        .to_string();
5591
    assert!(
5592
        err.contains("modified a.txt") && err.contains("removed b.txt") && err.contains("--carry"),
5593
        "{err}"
5594
    );
5595
    // --carry takes them along: h1 has a.txt as the base has it, and the
5596
    // removed b.txt is already as h1 has it (none), so that is no conflict
5597
    // either (oxygen#100).
5598
    let (_, carried) = repo
5599
        .checkout_carry(&[h1], "the first change", "checkout")
5600
        .unwrap();
5601
    assert_eq!(carried, vec!["a.txt"]);
5602
    assert_eq!(fs::read(root.join("a.txt")).unwrap(), b"a edited\n");
5603
    assert!(!root.join("b.txt").exists(), "h1 has no b.txt");
5604
}
5605
5606
/// Doctor and subrepos before the first commit (feedback 5 and 8): a
5607
/// user identity not stored in a new repository yet is fine while its
5608
/// secret key is there; an added subrepo is listed as not committed yet.
5609
#[test]
5610
fn a_new_repository_is_healthy_before_its_first_commit() {
5611
    hermetic();
5612
    let dir = tempfile::tempdir().unwrap();
5613
    let root = dir.path();
5614
    let home = root.join("home");
5615
    let mut first = Repo::init(&root.join("first"))
5616
        .unwrap()
5617
        .with_home(home.clone());
5618
    let (key, _) = first
5619
        .create_identity("Ada", "[email protected]", IdentityScope::User)
5620
        .unwrap();
5621
    let repo = Repo::init(&root.join("second"))
5622
        .unwrap()
5623
        .with_home(home.clone());
5624
    // Only the secret key: no identity object anywhere this repository sees.
5625
    let keys = repo.keys_dir.clone();
5626
    let _ = fs::remove_file(keys.join(format!("{}.identity", key.to_hex())));
5627
    assert!(keys.join(format!("{}.secret", key.to_hex())).is_file());
5628
    let r = repo.doctor(true);
5629
    let id = r.checks.iter().find(|c| c.area == "identity").unwrap();
5630
    assert_eq!(id.health, Health::Ok, "{}", id.message);
5631
    assert!(id.message.contains("first signed change"), "{}", id.message);
5632
5633
    // A subrepo added and not committed yet is listed, pinned where it is.
5634
    let lib = root.join("lib");
5635
    let l = Repo::init(&lib).unwrap().with_home(home.clone());
5636
    write(&lib, "x.txt", b"x\n");
5637
    l.commit("x", &[]).unwrap();
5638
    let second = root.join("second");
5639
    write(&second, "a.txt", b"a\n");
5640
    repo.submodule_add(&lib.to_string_lossy(), "deps/lib", None)
5641
        .unwrap();
5642
    let subs = repo.subrepos().unwrap();
5643
    assert_eq!(subs.len(), 1);
5644
    assert_eq!(
5645
        (subs[0].path.as_str(), subs[0].committed),
5646
        ("deps/lib", false)
5647
    );
5648
    assert_eq!(subs[0].actual.as_ref(), Some(&subs[0].pin));
5649
    repo.commit("add lib", &[]).unwrap();
5650
    let subs = repo.subrepos().unwrap();
5651
    assert!(subs[0].committed, "committed now");
5652
}
5653
5654
/// Commit, diff, hunks and discard use the partial snapshot: a file
5655
/// unchanged since the manifest is neither read nor rendered, and showing
5656
/// a change renders only what it edits, the same as from a full base.
5657
#[cfg(unix)]
5658
#[test]
5659
fn commits_and_diffs_leave_unchanged_files_alone() {
5660
    use std::os::unix::fs::PermissionsExt;
5661
    hermetic();
5662
    let dir = tempfile::tempdir().unwrap();
5663
    let root = dir.path();
5664
    let repo = Repo::init(root).unwrap().with_home(root.join("home"));
5665
    write(root, "big.txt", b"lots\nof\nlines\n");
5666
    write(root, "a.txt", b"one\ntwo\n");
5667
    repo.commit("base", &[]).unwrap();
5668
    let old = std::time::SystemTime::now() - std::time::Duration::from_secs(30);
5669
    for f in ["big.txt", "a.txt"] {
5670
        fs::File::options()
5671
            .write(true)
5672
            .open(root.join(f))
5673
            .unwrap()
5674
            .set_modified(old)
5675
            .unwrap();
5676
    }
5677
    assert!(repo.snapshot_status("status").unwrap().statuses.is_empty());
5678
    // big.txt cannot be read at all from here on.
5679
    fs::set_permissions(root.join("big.txt"), fs::Permissions::from_mode(0o000)).unwrap();
5680
5681
    write(root, "a.txt", b"one\nTWO\nthree\n");
5682
    let diff = repo.diff_files(None).unwrap();
5683
    assert_eq!(
5684
        diff.iter().map(|f| f.path.as_str()).collect::<Vec<_>>(),
5685
        ["a.txt"]
5686
    );
5687
    let (_, hunks) = repo.hunks().unwrap();
5688
    assert!(!hunks.is_empty() && hunks.iter().all(|h| h.path == "a.txt"));
5689
    let h = repo.commit("edit a", &[]).unwrap();
5690
5691
    // Showing the change needs only a.txt's graph, and renders as a full base does.
5692
    let c = repo.store().get_change(&h).unwrap();
5693
    let full = repo.load_state(&c.deps).unwrap();
5694
    let want = render_change(&c, &full, &full.materialize());
5695
    assert_eq!(repo.describe_change(&h).unwrap(), want);
5696
    let (base, snap) = repo.change_base(&c).unwrap();
5697
    assert!(!base.is_full() && snap.unrendered.contains("big.txt"));
5698
5699
    // Discarding works the same way.
5700
    write(root, "a.txt", b"scratch\n");
5701
    assert_eq!(repo.discard(&["a.txt".into()]).unwrap(), 1);
5702
    assert_eq!(fs::read(root.join("a.txt")).unwrap(), b"one\nTWO\nthree\n");
5703
    fs::set_permissions(root.join("big.txt"), fs::Permissions::from_mode(0o644)).unwrap();
5704
}
5705
5706
/// A replace conflict (spec §9.3) is settled by a change that writes one
5707
/// candidate, or new bytes, at the path when the caller names it; a plain
5708
/// snapshot of a checkout never settles it on its own.
5709
#[test]
5710
fn replace_conflicts_are_settled_when_asked() {
5711
    hermetic();
5712
    let dir = tempfile::tempdir().unwrap();
5713
    let root = dir.path();
5714
    let mut repo = Repo::init(root).unwrap().with_home(root.join("home"));
5715
    let blob = |n: u8| {
5716
        let mut v = vec![0u8; 64];
5717
        v[1] = n;
5718
        v
5719
    };
5720
    write(root, "img.bin", &blob(1));
5721
    repo.commit("add img", &[]).unwrap();
5722
    repo.bookmark_create("other", None).unwrap();
5723
    write(root, "img.bin", &blob(2));
5724
    repo.commit("img two", &[]).unwrap();
5725
    repo.bookmark_switch("other", false).unwrap();
5726
    write(root, "img.bin", &blob(3));
5727
    repo.commit("img three", &[]).unwrap();
5728
    repo.bookmark_switch("main", false).unwrap();
5729
    repo.merge("other").unwrap();
5730
    let heads = repo.bookmark_heads().unwrap();
5731
    let merged = repo.load_state(&heads).unwrap().materialize();
5732
    assert!(
5733
        matches!(&merged.files["img.bin"].content, FileContent::Opaque { blobs } if blobs.len() == 2),
5734
        "a replace conflict"
5735
    );
5736
    // A snapshot of the checkout records nothing.
5737
    assert!(repo
5738
        .snapshot("status")
5739
        .unwrap()
5740
        .statuses
5741
        .iter()
5742
        .all(|s| s.path != "img.bin"));
5743
5744
    // Keeping candidate 3 settles it.
5745
    let author = repo.author();
5746
    let edits = [FileEdit {
5747
        path: "img.bin".into(),
5748
        content: Some(blob(3)),
5749
    }];
5750
    let c = repo
5751
        .build_change(&heads, &edits, "keep three", author)
5752
        .unwrap();
5753
    assert_eq!(c.kind, ChangeKind::Resolution);
5754
    let mut st = repo.load_state(&heads).unwrap();
5755
    for d in &c.deps {
5756
        assert!(st.contains(d));
5757
    }
5758
    assert!(
5759
        heads.iter().all(|h| c.deps.contains(h)),
5760
        "depends on both contributors"
5761
    );
5762
    st.add(c).unwrap();
5763
    let after = st.materialize();
5764
    assert!(!after.is_conflicted());
5765
    assert_eq!(
5766
        after.files["img.bin"].content,
5767
        FileContent::Opaque {
5768
            blobs: vec![Repo::blob_ref(&blob(3))]
5769
        }
5770
    );
5771
5772
    // New bytes settle it too.
5773
    let edits = [FileEdit {
5774
        path: "img.bin".into(),
5775
        content: Some(blob(9)),
5776
    }];
5777
    let c = repo.build_change(&heads, &edits, "new", author).unwrap();
5778
    let mut st = repo.load_state(&heads).unwrap();
5779
    st.add(c).unwrap();
5780
    assert_eq!(
5781
        st.materialize().files["img.bin"].content,
5782
        FileContent::Opaque {
5783
            blobs: vec![Repo::blob_ref(&blob(9))]
5784
        }
5785
    );
5786
}
5787
5788
/// The history of a range of lines (spec §27): the changes that wrote
5789
/// or deleted its atoms, or deleted atoms from between them; edits outside
5790
/// the range and changes the range's lines survived are not in it.
5791
#[test]
5792
fn line_ranges_have_exact_histories() {
5793
    hermetic();
5794
    let dir = tempfile::tempdir().unwrap();
5795
    let root = dir.path();
5796
    let repo = Repo::init(root).unwrap().with_home(root.join("home"));
5797
    write(root, "f.rs", b"use x;\nfn a() {\n  one();\n  two();\n}\n");
5798
    let base = repo.commit("add f", &[]).unwrap();
5799
    write(root, "f.rs", b"use y;\nfn a() {\n  one();\n  two();\n}\n");
5800
    let outside = repo.commit("change the import", &[]).unwrap();
5801
    write(root, "f.rs", b"use y;\nfn a() {\n  ONE();\n  two();\n}\n");
5802
    let inside = repo.commit("edit a line of a", &[]).unwrap();
5803
    write(root, "f.rs", b"use y;\nfn a() {\n  ONE();\n}\n");
5804
    let deleted = repo.commit("delete a line of a", &[]).unwrap();
5805
    write(root, "f.rs", b"use y;\nfn a() {\n  ONE();\n}\nfn b() {}\n");
5806
    let after = repo.commit("add b after a", &[]).unwrap();
5807
    let heads = repo.bookmark_heads().unwrap();
5808
5809
    // Lines 2..4 are `fn a() {`, `ONE();`, `}` now.
5810
    let hist: Vec<ChangeHash> = repo
5811
        .line_history(&heads, "f.rs", 2, 4)
5812
        .unwrap()
5813
        .iter()
5814
        .map(|e| e.hash)
5815
        .collect();
5816
    for (h, what) in [
5817
        (base, "wrote it"),
5818
        (inside, "edited a line"),
5819
        (deleted, "deleted a line from inside"),
5820
    ] {
5821
        assert!(hist.contains(&h), "{what}");
5822
    }
5823
    for (h, what) in [(outside, "an edit above"), (after, "an addition below")] {
5824
        assert!(!hist.contains(&h), "{what}");
5825
    }
5826
    assert_eq!(hist[0], deleted, "newest first");
5827
    // One line: only what touched it.
5828
    let one: Vec<ChangeHash> = repo
5829
        .line_history(&heads, "f.rs", 1, 1)
5830
        .unwrap()
5831
        .iter()
5832
        .map(|e| e.hash)
5833
        .collect();
5834
    assert!(one.contains(&outside) && !one.contains(&inside));
5835
    assert!(repo.line_history(&heads, "f.rs", 3, 9).is_err());
5836
    assert!(repo.line_history(&heads, "f.rs", 0, 1).is_err());
5837
    assert!(repo.line_history(&heads, "nope.rs", 1, 1).is_err());
5838
}
5839
5840
#[test]
5841
fn receipts_are_kept_with_their_state_and_verified() {
5842
    use crate::receipt::{Receipt, SignedReceipt};
5843
    hermetic();
5844
    let dir = tempfile::tempdir().unwrap();
5845
    let root = dir.path();
5846
    let repo = Repo::init(root).unwrap().with_home(root.join("home"));
5847
    write(root, "a.txt", b"1\n");
5848
    repo.commit("A", &[]).unwrap();
5849
    let heads = repo.bookmark_heads().unwrap();
5850
    let state = repo
5851
        .store()
5852
        .put_state(&StateObject::new(heads.clone()))
5853
        .unwrap();
5854
    let out = repo.store_blob(b"built\n").unwrap();
5855
    let receipt = Receipt {
5856
        job_name: "build".into(),
5857
        pipeline_hash: ObjectRef([1; 32]),
5858
        scope_tree_hash: ObjectRef([2; 32]),
5859
        inputs: vec![],
5860
        environment: ObjectRef([3; 32]),
5861
        outputs: vec![out],
5862
        exit_code: 0,
5863
        duration_ms: 42,
5864
    };
5865
    let sk = SecretKey::generate();
5866
    let runner = sk.identity("earth-1", "runner@earth", 1);
5867
    let sr = SignedReceipt::sign(
5868
        receipt.clone(),
5869
        repo.id().unwrap(),
5870
        state,
5871
        "demo#1",
5872
        &runner,
5873
        &sk,
5874
    );
5875
5876
    let r = repo.add_receipt(&sr).unwrap();
5877
    let found = repo.receipts(&heads).unwrap();
5878
    assert_eq!(found.len(), 1);
5879
    assert_eq!(found[0].attest, r);
5880
    assert_eq!(found[0].signed, sr);
5881
    assert!(found[0].problem.is_none() && !found[0].revoked);
5882
    assert!(repo.receipts(&[ObjectRef([5; 32])]).unwrap().is_empty());
5883
5884
    // Another repository's receipt, or a forged one, is refused.
5885
    let elsewhere = SignedReceipt::sign(receipt.clone(), [0; 16], state, "x", &runner, &sk);
5886
    assert!(repo
5887
        .add_receipt(&elsewhere)
5888
        .unwrap_err()
5889
        .to_string()
5890
        .contains("another repository"));
5891
    let mut forged = sr.clone();
5892
    forged.receipt.exit_code = 1;
5893
    assert!(repo
5894
        .add_receipt(&forged)
5895
        .unwrap_err()
5896
        .to_string()
5897
        .contains("does not verify"));
5898
5899
    // A receipt signed by a short-lived key keeps its certificate and the
5900
    // issuer's identity, and reads back with them (oxygenhub#241).
5901
    let hub_sk = SecretKey::generate();
5902
    let hub = hub_sk.identity("oxygenhub.io", "[email protected]", 1);
5903
    let job_sk = SecretKey::generate();
5904
    let job = job_sk.identity("job 2 test", "[email protected]", 1);
5905
    let mut test_receipt = receipt.clone();
5906
    test_receipt.job_name = "test".into();
5907
    let plain = SignedReceipt::sign(
5908
        test_receipt,
5909
        repo.id().unwrap(),
5910
        state,
5911
        "demo#2",
5912
        &job,
5913
        &job_sk,
5914
    );
5915
    let now = plain.attest.hlc.wall_ms;
5916
    let cert = crate::cert::SignedCertificate::sign(
5917
        crate::cert::Certificate {
5918
            key: job.clone(),
5919
            issuer: hub.hash(),
5920
            subject: "repo:andy/demo:bookmark:main".into(),
5921
            claims: vec![],
5922
            scope: crate::identity::Scope::SEAL,
5923
            not_before: now - 1_000,
5924
            expires: now + 600_000,
5925
            grant: None,
5926
        },
5927
        &hub,
5928
        &hub_sk,
5929
    );
5930
    let certified = plain.with_certificate(cert, hub.clone());
5931
    repo.add_receipt(&certified).unwrap();
5932
    let found = repo.receipts(&heads).unwrap();
5933
    let got = found
5934
        .iter()
5935
        .find(|i| i.signed.receipt.job_name == "test")
5936
        .unwrap();
5937
    assert_eq!(got.signed, certified);
5938
    assert!(got.problem.is_none(), "{:?}", got.problem);
5939
5940
    // gc keeps the receipts, their runners, the certificate and its issuer,
5941
    // and the output while the state lives.
5942
    repo.gc(true).unwrap();
5943
    let found = repo.receipts(&heads).unwrap();
5944
    assert_eq!(found.len(), 2);
5945
    let got = found
5946
        .iter()
5947
        .find(|i| i.signed.receipt.job_name == "test")
5948
        .unwrap();
5949
    assert_eq!(got.signed, certified, "the certificate survives gc");
5950
    assert!(got.problem.is_none());
5951
    assert_eq!(repo.read_blob(&out).unwrap(), b"built\n");
5952
    assert!(repo.fsck().unwrap().problems.is_empty());
5953
}
5954
5955
#[test]
5956
fn approvals_are_kept_with_their_state_and_survive_gc() {
5957
    hermetic();
5958
    let dir = tempfile::tempdir().unwrap();
5959
    let root = dir.path();
5960
    let repo = Repo::init(root).unwrap().with_home(root.join("home"));
5961
    write(root, "a.txt", b"1\n");
5962
    repo.commit("A", &[]).unwrap();
5963
    let heads = repo.bookmark_heads().unwrap();
5964
    let state = repo.store().put_state(&StateObject::new(heads)).unwrap();
5965
    let plan = repo.store_blob(b"the reviewed plan\n").unwrap();
5966
    let sk = SecretKey::generate();
5967
    let andy = sk.identity("Andy", "[email protected]", 1);
5968
    let statement = crate::approval::Statement {
5969
        repo: repo.id().unwrap(),
5970
        run: "https://hub.example/andy/infra/flow/8".into(),
5971
        job: "apply".into(),
5972
        job_hash: ObjectRef([1; 32]),
5973
        state,
5974
        inputs: vec![plan],
5975
        environment: "prod".into(),
5976
        approve: true,
5977
    };
5978
    let sa = crate::approval::SignedApproval::sign(&statement, &andy, &sk);
5979
    let r = repo.add_approval(&sa).unwrap();
5980
    assert_eq!(repo.store().approvals_for(&state).unwrap(), vec![r]);
5981
    // Another repository's approval, or a changed one, is refused.
5982
    let elsewhere = crate::approval::SignedApproval::sign(
5983
        &crate::approval::Statement {
5984
            repo: [0; 16],
5985
            ..statement.clone()
5986
        },
5987
        &andy,
5988
        &sk,
5989
    );
5990
    assert!(repo
5991
        .add_approval(&elsewhere)
5992
        .unwrap_err()
5993
        .to_string()
5994
        .contains("another repository"));
5995
    let mut forged = sa.clone();
5996
    if let AttestBody::Approval { environment, .. } = &mut forged.attest.body {
5997
        *environment = "dev".into();
5998
    }
5999
    assert!(repo
6000
        .add_approval(&forged)
6001
        .unwrap_err()
6002
        .to_string()
6003
        .contains("does not verify"));
6004
    // gc keeps it, its signature and its signer while the state lives.
6005
    repo.gc(true).unwrap();
6006
    assert_eq!(repo.store().approvals_for(&state).unwrap(), vec![r]);
6007
    assert_eq!(repo.store().get_attest(&r).unwrap(), sa.attest);
6008
    assert_eq!(repo.store().signatures(&r).unwrap(), sa.sigs);
6009
    assert!(repo.fsck().unwrap().problems.is_empty());
6010
}
6011
6012
#[test]
6013
fn status_leaves_an_unchanged_manifest_alone() {
6014
    hermetic();
6015
    let dir = tempfile::tempdir().unwrap();
6016
    let root = dir.path();
6017
    let repo = Repo::init(root).unwrap().with_home(root.join("home"));
6018
    write(root, "a.txt", b"1\n");
6019
    write(root, "b.txt", b"2\n");
6020
    repo.commit("A", &[]).unwrap();
6021
    // Files last touched well outside the racy window.
6022
    let old = std::time::SystemTime::now() - std::time::Duration::from_secs(60);
6023
    for f in ["a.txt", "b.txt"] {
6024
        fs::File::options()
6025
            .write(true)
6026
            .open(root.join(f))
6027
            .unwrap()
6028
            .set_modified(old)
6029
            .unwrap();
6030
    }
6031
    repo.snapshot_status("status").unwrap();
6032
    let path = repo.manifest_path();
6033
    let first = fs::read(&path).unwrap();
6034
    repo.snapshot_status("status").unwrap();
6035
    assert_eq!(
6036
        fs::read(&path).unwrap(),
6037
        first,
6038
        "an unchanged tree does not rewrite the manifest"
6039
    );
6040
    // A change rewrites it.
6041
    write(root, "a.txt", b"1\n2\n");
6042
    repo.snapshot_status("status").unwrap();
6043
    assert_ne!(fs::read(&path).unwrap(), first);
6044
}
6045
6046
#[test]
6047
fn large_text_files_travel_and_survive_gc_as_text_blobs() {
6048
    hermetic();
6049
    let dir = tempfile::tempdir().unwrap();
6050
    let root = dir.path();
6051
    let origin_path = root.join("origin");
6052
    Repo::init(&origin_path).unwrap();
6053
    let origin_url = origin_path.to_string_lossy().to_string();
6054
    let a = Repo::clone(&origin_url, &root.join("a")).unwrap();
6055
    let big: String = (0..5000).map(|i| format!("line {i}\n")).collect();
6056
    write(&root.join("a"), "big.txt", big.as_bytes());
6057
    write(&root.join("a"), "small.txt", b"small\n");
6058
    let h1 = a.commit("large", &[]).unwrap();
6059
    let (_, body) = a.store().get(&h1).unwrap();
6060
    assert!(body.len() < 2048, "the change is {} bytes", body.len());
6061
    assert!(a.push("origin", false).unwrap()[0].ok);
6062
6063
    // A clone reads the text from the blobs that came with the change.
6064
    let b = Repo::clone(&origin_url, &root.join("b")).unwrap();
6065
    assert_eq!(fs::read(root.join("b/big.txt")).unwrap(), big.as_bytes());
6066
    // An edit in the middle of the stored insert is an ordinary change.
6067
    let edited = big.replace("line 2500\n", "line 2500, edited\n");
6068
    write(&root.join("b"), "big.txt", edited.as_bytes());
6069
    let h2 = b.commit("edit", &[]).unwrap();
6070
    assert!(b.store().get_change(&h2).unwrap().edits.len() <= 2);
6071
    assert!(b.push("origin", false).unwrap()[0].ok);
6072
    assert!(a.pull("origin").unwrap().checked_out);
6073
    assert_eq!(fs::read(root.join("a/big.txt")).unwrap(), edited.as_bytes());
6074
    assert_eq!(
6075
        a.fsck().unwrap().errors(),
6076
        0,
6077
        "{:?}",
6078
        a.fsck().unwrap().problems
6079
    );
6080
6081
    // With zero retention gc keeps the text blobs of every kept change.
6082
    let mut a = Repo::open(&root.join("a")).unwrap();
6083
    a.config.set("core.op-retention", "0").unwrap();
6084
    a.save_config().unwrap();
6085
    let a = Repo::open(&root.join("a")).unwrap();
6086
    a.gc(true).unwrap();
6087
    let a = Repo::open(&root.join("a")).unwrap();
6088
    assert_eq!(a.store().get_change(&h1).unwrap().message, "large");
6089
    assert_eq!(
6090
        a.fsck().unwrap().errors(),
6091
        0,
6092
        "{:?}",
6093
        a.fsck().unwrap().problems
6094
    );
6095
    // And a clone of the packed repository reads them from its packs.
6096
    let c = Repo::clone(&root.join("a").to_string_lossy(), &root.join("c")).unwrap();
6097
    assert_eq!(fs::read(root.join("c/big.txt")).unwrap(), edited.as_bytes());
6098
    drop(c);
6099
}
6100
6101
#[test]
6102
fn operations_that_both_replace_a_working_copy_are_not_merged() {
6103
    hermetic();
6104
    let dir = tempfile::tempdir().unwrap();
6105
    let root = dir.path();
6106
    let repo = Repo::init(root).unwrap();
6107
    write(root, "a.txt", b"a\n");
6108
    let a = repo.commit("a", &[]).unwrap();
6109
    write(root, "b.txt", b"b\n");
6110
    repo.commit("b", &[]).unwrap();
6111
    let (x, op) = repo.head_op().unwrap();
6112
    let ws = *op.view.workspaces.keys().next().unwrap();
6113
    let mut one = op.view.clone();
6114
    one.workspaces.insert(ws, a);
6115
    let mut two = op.view.clone();
6116
    two.workspaces.insert(ws, ObjectRef([7; 32]));
6117
    let first = repo.record_op(&[x], "one", one).unwrap();
6118
    let e = repo.record_op(&[x], "two", two).unwrap_err();
6119
    assert!(
6120
        e.to_string()
6121
            .contains("changed this working copy at the same time"),
6122
        "{e}"
6123
    );
6124
    assert_eq!(
6125
        repo.head_op().unwrap().0,
6126
        first,
6127
        "the second is not recorded"
6128
    );
6129
}
6130
6131
/// Metalgear, 2026-09-29 (oxygen#36): a status run while a bookmark switch
6132
/// rewrote the working copy recorded the half-written files as edits, and
6133
/// its view replaced the switch's.
6134
#[test]
6135
fn a_snapshot_during_a_switch_never_records_the_switch_as_edits() {
6136
    hermetic();
6137
    let dir = tempfile::tempdir().unwrap();
6138
    let root = dir.path().to_path_buf();
6139
    let mut repo = Repo::init(&root).unwrap();
6140
    write(&root, "keep.txt", b"keep\n");
6141
    repo.commit("base", &[]).unwrap();
6142
    repo.bookmark_create("small", None).unwrap();
6143
    for i in 0..300 {
6144
        write(
6145
            &root,
6146
            &format!("many/f{i}.txt"),
6147
            format!("file {i}\n").as_bytes(),
6148
        );
6149
    }
6150
    repo.commit("many", &[]).unwrap();
6151
    let stop = std::sync::Arc::new(std::sync::atomic::AtomicBool::new(false));
6152
    let watcher = {
6153
        let (root, stop) = (root.clone(), stop.clone());
6154
        std::thread::spawn(move || {
6155
            let r = Repo::open(&root).unwrap();
6156
            let mut ran = 0;
6157
            while !stop.load(std::sync::atomic::Ordering::Relaxed) {
6158
                if r.snapshot_status("oxy status").is_ok() {
6159
                    ran += 1;
6160
                }
6161
            }
6162
            ran
6163
        })
6164
    };
6165
    for i in 0..20 {
6166
        let to = if i % 2 == 0 { "small" } else { "main" };
6167
        repo.bookmark_switch(to, false).unwrap();
6168
    }
6169
    stop.store(true, std::sync::atomic::Ordering::Relaxed);
6170
    assert!(watcher.join().unwrap() > 0, "the watcher snapshotted");
6171
    // Back on main, clean, with every file where main has it.
6172
    let repo = Repo::open(&root).unwrap();
6173
    let s = repo.snapshot_status("oxy status").unwrap();
6174
    assert!(s.statuses.is_empty(), "{:?}", statuses(&s));
6175
    assert!(s.wc.edits.is_empty() && s.wc.tree_ops.is_empty());
6176
    assert_eq!(s.wc.deps, repo.bookmark_heads().unwrap());
6177
    assert!(root.join("many/f299.txt").exists());
6178
}
6179
6180
/// Metalgear, 2026-09-29 (oxygen#38): a parent's `bookmark switch --carry`
6181
/// put a subrepo that was ahead of its pin back at the pin and moved the
6182
/// subrepo's own bookmark backwards.
6183
#[test]
6184
fn a_parent_switch_with_carry_leaves_a_subrepo_ahead_of_its_pin_alone() {
6185
    hermetic();
6186
    let dir = tempfile::tempdir().unwrap();
6187
    let root = dir.path();
6188
    Repo::init(&root.join("lib-origin")).unwrap();
6189
    let lib_url = root.join("lib-origin").to_string_lossy().to_string();
6190
    let lib = Repo::clone(&lib_url, &root.join("lib")).unwrap();
6191
    write(&root.join("lib"), "lib.txt", b"v1\n");
6192
    lib.commit("lib v1", &[]).unwrap();
6193
    assert!(lib.push("origin", false).unwrap()[0].ok);
6194
6195
    let app_dir = root.join("app");
6196
    let mut app = Repo::init(&app_dir).unwrap();
6197
    write(&app_dir, "main.txt", b"app\n");
6198
    app.submodule_add(&lib_url, "libs/lib", None).unwrap();
6199
    app.commit("app with lib", &[]).unwrap();
6200
    app.bookmark_create("feature", None).unwrap();
6201
6202
    // New work in the subrepo, not yet pinned by the parent.
6203
    let nested_dir = app_dir.join("libs/lib");
6204
    let nested = Repo::open(&nested_dir).unwrap();
6205
    write(&nested_dir, "new.txt", b"new\n");
6206
    let l2 = nested.commit("lib: new file", &[]).unwrap();
6207
    drop(nested);
6208
6209
    let (_, carried) = app.bookmark_switch_carry("feature").unwrap();
6210
    assert!(carried.contains(&"libs/lib".to_string()), "{carried:?}");
6211
    let nested = Repo::open(&nested_dir).unwrap();
6212
    assert!(
6213
        nested.bookmark_heads().unwrap().contains(&l2),
6214
        "its bookmark kept its work"
6215
    );
6216
    assert!(nested_dir.join("new.txt").exists(), "and its files");
6217
    let s = app.snapshot("status").unwrap();
6218
    assert_eq!(
6219
        statuses(&s),
6220
        vec![("libs/lib".to_string(), ChangeStatus::Modified)]
6221
    );
6222
}
6223
6224
/// oxygen#29 (metalgear, rstar-api): after a proposal landed on the hub,
6225
/// moving `main` to a change this clone had pushed on another bookmark,
6226
/// the first `pull` said "Already up to date" while `main` was behind.
6227
#[test]
6228
fn pull_takes_a_remote_move_to_changes_already_here() {
6229
    hermetic();
6230
    let dir = tempfile::tempdir().unwrap();
6231
    let root = dir.path();
6232
    let origin_path = root.join("origin");
6233
    let origin = Repo::init(&origin_path).unwrap();
6234
    let url = origin_path.to_string_lossy().to_string();
6235
    let mut b = Repo::clone(&url, &root.join("b")).unwrap();
6236
    write(&root.join("b"), "base.txt", b"base\n");
6237
    b.commit("base", &[]).unwrap();
6238
    assert!(b.push("origin", false).unwrap()[0].ok);
6239
    origin.refresh().unwrap();
6240
6241
    // A feature bookmark with one change, pushed.
6242
    b.bookmark_create("feat", None).unwrap();
6243
    b.bookmark_switch("feat", false).unwrap();
6244
    write(&root.join("b"), "x.txt", b"x\n");
6245
    let x = b.commit("x", &[]).unwrap();
6246
    assert!(b.push("origin", false).unwrap()[0].ok);
6247
    origin.refresh().unwrap();
6248
    b.bookmark_switch("main", false).unwrap();
6249
6250
    // The remote lands it: its main moves to the feature's state.
6251
    let feat = origin
6252
        .store()
6253
        .get_state(&origin.view().unwrap().bookmarks["feat"])
6254
        .unwrap()
6255
        .heads;
6256
    origin.bookmark_set("main", &feat).unwrap();
6257
6258
    let r = b.pull("origin").unwrap();
6259
    assert!(r.changed, "{r:?}");
6260
    assert!(r.heads.contains(&x) || b.load_state(&r.heads).unwrap().contains(&x));
6261
    let main = b
6262
        .bookmarks()
6263
        .unwrap()
6264
        .into_iter()
6265
        .find(|m| m.name == "main")
6266
        .unwrap();
6267
    assert_eq!(main.behind, Some(0), "{main:?}");
6268
}
6269
6270
/// oxygen#48: a remote's bookmarks are names here (`origin/NAME`); switching
6271
/// to one only the remote has makes a local bookmark from it; a pull moves
6272
/// every local bookmark the remote has too; a clone checks out the remote's
6273
/// default bookmark.
6274
#[test]
6275
fn remote_bookmarks_are_named_switched_to_pulled_and_cloned() {
6276
    hermetic();
6277
    let dir = tempfile::tempdir().unwrap();
6278
    let root = dir.path();
6279
    let origin_path = root.join("origin");
6280
    let mut origin = Repo::init(&origin_path).unwrap();
6281
    let url = origin_path.to_string_lossy().to_string();
6282
    let mut a = Repo::clone(&url, &root.join("a")).unwrap();
6283
    write(&root.join("a"), "base.txt", b"base\n");
6284
    a.commit("base", &[]).unwrap();
6285
    assert!(a.push("origin", false).unwrap()[0].ok);
6286
    a.bookmark_create("develop", None).unwrap();
6287
    a.bookmark_switch("develop", false).unwrap();
6288
    write(&root.join("a"), "base.txt", b"base\nd1\n");
6289
    let d1 = a.commit("d1", &[]).unwrap();
6290
    assert!(a.push("origin", false).unwrap()[0].ok);
6291
6292
    // A clone has main only; origin/develop is a name all the same.
6293
    let c_root = root.join("c");
6294
    let mut c = Repo::clone(&url, &c_root).unwrap();
6295
    assert_eq!(c.config.bookmark, "main");
6296
    assert!(!c.view().unwrap().bookmarks.contains_key("develop"));
6297
    assert_eq!(c.resolve_heads("origin/develop").unwrap(), vec![d1]);
6298
    assert_eq!(c.resolve_change("origin/develop").unwrap(), d1);
6299
    assert_eq!(c.remote_only_bookmarks().unwrap().len(), 1);
6300
6301
    // Switching makes the local bookmark from origin's.
6302
    c.bookmark_switch("develop", false).unwrap();
6303
    assert_eq!(c.config.bookmark, "develop");
6304
    assert_eq!(c.bookmark_heads().unwrap(), vec![d1]);
6305
    assert_eq!(fs::read(c_root.join("base.txt")).unwrap(), b"base\nd1\n");
6306
    assert!(c.remote_only_bookmarks().unwrap().is_empty());
6307
    assert!(c.bookmark_switch("nowhere", false).is_err());
6308
6309
    // Both bookmarks move on the remote; one pull takes both.
6310
    write(&root.join("a"), "base.txt", b"base\nd1\nd2\n");
6311
    let d2 = a.commit("d2", &[]).unwrap();
6312
    assert!(a.push("origin", false).unwrap()[0].ok);
6313
    a.bookmark_switch("main", false).unwrap();
6314
    write(&root.join("a"), "m.txt", b"m\n");
6315
    let m = a.commit("m", &[]).unwrap();
6316
    assert!(a.push("origin", false).unwrap()[0].ok);
6317
    let r = c.pull("origin").unwrap();
6318
    assert!(r.changed && r.checked_out, "{r:?}");
6319
    assert_eq!(r.heads, vec![d2]);
6320
    assert_eq!(r.others, vec!["main".to_string()]);
6321
    assert!(c.resolve_heads("main").unwrap().contains(&m));
6322
    assert_eq!(
6323
        fs::read(c_root.join("base.txt")).unwrap(),
6324
        b"base\nd1\nd2\n"
6325
    );
6326
    let again = c.pull("origin").unwrap();
6327
    assert!(!again.changed && again.others.is_empty(), "{again:?}");
6328
6329
    // A clone checks out the remote's default bookmark.
6330
    origin.config.set("workspace.bookmark", "develop").unwrap();
6331
    origin.save_config().unwrap();
6332
    let e = Repo::clone(&url, &root.join("e")).unwrap();
6333
    assert_eq!(e.config.bookmark, "develop");
6334
    assert_eq!(e.bookmark_heads().unwrap(), vec![d2]);
6335
    let reopened = Repo::open(&root.join("e")).unwrap();
6336
    assert_eq!(reopened.config.bookmark, "develop");
6337
    // REMOTE/NAME names the remote's bookmark to switch to.
6338
    let mut e = reopened;
6339
    e.bookmark_switch("origin/main", false).unwrap();
6340
    assert_eq!(e.config.bookmark, "main");
6341
    assert!(e.bookmark_heads().unwrap().contains(&m));
6342
}
6343
6344
/// oxygen#51, #52: --at-op reads an earlier view and refuses changes;
6345
/// op restore goes back to an operation, files included, and undo takes
6346
/// the restore back whole; op revert undoes one operation alone; each
6347
/// operation's changes are described from the views.
6348
#[test]
6349
fn operations_can_be_read_restored_and_reverted() {
6350
    hermetic();
6351
    let dir = tempfile::tempdir().unwrap();
6352
    let root = dir.path();
6353
    let repo = Repo::init(root).unwrap();
6354
    write(root, "a.txt", b"a\n");
6355
    let first = repo.commit("first", &[]).unwrap();
6356
    write(root, "a.txt", b"a\nb\n");
6357
    let second = repo.commit("second", &[]).unwrap();
6358
    let at_second = repo.head_op().unwrap().0.to_hex();
6359
    repo.bookmark_create("keep", None).unwrap();
6360
    let created = repo.head_op().unwrap().0.to_hex();
6361
    write(root, "n.txt", b"n\n");
6362
    let third = repo.commit("third", &[]).unwrap();
6363
6364
    // What each operation changed.
6365
    let ops = repo.op_log().unwrap();
6366
    let changes = repo.view_changes(&ops[1].1.view, &ops[0].1.view).unwrap();
6367
    assert!(
6368
        changes
6369
            .iter()
6370
            .any(|c| matches!(c, ViewChange::BookmarkMoved { name, .. } if name == "main")),
6371
        "{changes:?}"
6372
    );
6373
    assert!(changes
6374
        .iter()
6375
        .any(|c| matches!(c, ViewChange::WorkingCopy { .. })));
6376
6377
    // Reading at an earlier operation.
6378
    let old = Repo::open(root).unwrap().at_op(&at_second[..10]).unwrap();
6379
    assert_eq!(old.bookmark_heads().unwrap(), vec![second]);
6380
    assert!(!old.view().unwrap().bookmarks.contains_key("keep"));
6381
    write(root, "z.txt", b"z\n");
6382
    assert!(old.commit("refused", &[]).is_err(), "--at-op is read-only");
6383
    fs::remove_file(root.join("z.txt")).unwrap();
6384
    assert!(repo.resolve_op("zz").is_err());
6385
    assert_eq!(repo.resolve_op("@").unwrap().0, repo.head_op().unwrap().0);
6386
6387
    // Restore goes back, files and all; undo takes it back whole.
6388
    repo.op_restore(&at_second, false).unwrap();
6389
    assert_eq!(repo.bookmark_heads().unwrap(), vec![second]);
6390
    assert!(!root.join("n.txt").exists());
6391
    repo.undo().unwrap();
6392
    let mut heads = repo.bookmark_heads().unwrap();
6393
    heads.sort();
6394
    let mut want = vec![second, third];
6395
    want.sort();
6396
    assert_eq!(heads, want);
6397
    assert!(
6398
        root.join("n.txt").exists(),
6399
        "the files came back with the undo"
6400
    );
6401
6402
    // Revert the bookmark's creation alone: the commit after it stays.
6403
    let r = repo.op_revert(&created).unwrap();
6404
    assert_eq!(r.reverted, vec!["keep".to_string()]);
6405
    assert!(!repo.view().unwrap().bookmarks.contains_key("keep"));
6406
    assert!(repo
6407
        .load_state(&repo.bookmark_heads().unwrap())
6408
        .unwrap()
6409
        .contains(&third));
6410
    assert!(repo.op_revert(&created).is_err(), "nothing left to revert");
6411
    let _ = first;
6412
}
6413
6414
/// oxygen#41: with uncommitted work, a status after a snapshot is answered
6415
/// from the status cache while every file is as the snapshot left it, and
6416
/// from a snapshot again as soon as one is not.
6417
#[test]
6418
fn status_with_uncommitted_work_comes_from_the_cache_until_a_file_changes() {
6419
    hermetic();
6420
    let dir = tempfile::tempdir().unwrap();
6421
    let root = dir.path();
6422
    let repo = Repo::init(root).unwrap();
6423
    write(root, "a.txt", b"a\n");
6424
    write(root, "b.txt", b"b\n");
6425
    repo.commit("base", &[]).unwrap();
6426
    assert_eq!(repo.status_by_manifest().unwrap(), Some(vec![]), "clean");
6427
6428
    write(root, "a.txt", b"a\nmore\n");
6429
    assert_eq!(
6430
        repo.status_by_manifest().unwrap(),
6431
        None,
6432
        "no snapshot of the edit yet"
6433
    );
6434
    let snap = repo.snapshot_status("oxy status").unwrap();
6435
    assert_eq!(snap.statuses.len(), 1);
6436
    let cached = repo
6437
        .status_by_manifest()
6438
        .unwrap()
6439
        .expect("answered from the cache");
6440
    assert_eq!(cached.len(), 1);
6441
    assert_eq!(
6442
        (cached[0].path.as_str(), cached[0].status),
6443
        ("a.txt", ChangeStatus::Modified)
6444
    );
6445
6446
    // Any further change sends status back to a snapshot.
6447
    write(root, "a.txt", b"a\nmore\nand more\n");
6448
    assert_eq!(repo.status_by_manifest().unwrap(), None, "edited again");
6449
    repo.snapshot_status("oxy status").unwrap();
6450
    assert!(repo.status_by_manifest().unwrap().is_some());
6451
    write(root, "new.txt", b"n\n");
6452
    assert_eq!(repo.status_by_manifest().unwrap(), None, "a file added");
6453
    fs::remove_file(root.join("new.txt")).unwrap();
6454
    assert!(
6455
        repo.status_by_manifest().unwrap().is_some(),
6456
        "back as it was"
6457
    );
6458
    fs::remove_file(root.join("b.txt")).unwrap();
6459
    assert_eq!(repo.status_by_manifest().unwrap(), None, "a file removed");
6460
    write(root, "b.txt", b"b\n");
6461
6462
    // A commit leaves nothing uncommitted: clean again, no cache needed.
6463
    repo.snapshot_status("oxy status").unwrap();
6464
    repo.commit("more", &[]).unwrap();
6465
    assert_eq!(repo.status_by_manifest().unwrap(), Some(vec![]));
6466
}
6467
6468
/// oxygen#41: while the status cache holds, the working copy's diff is
6469
/// rendered from the stored working-copy change, and says exactly what a
6470
/// snapshot's diff says.
6471
#[test]
6472
fn the_working_copy_diff_from_the_cache_matches_a_snapshot() {
6473
    hermetic();
6474
    let dir = tempfile::tempdir().unwrap();
6475
    let root = dir.path();
6476
    let repo = Repo::init(root).unwrap();
6477
    write(root, "a.txt", b"one\ntwo\nthree\n");
6478
    write(root, "gone.txt", b"bye\n");
6479
    repo.commit("base", &[]).unwrap();
6480
    write(root, "a.txt", b"one\n2\nthree\nfour\n");
6481
    write(root, "new.txt", b"hello\n");
6482
    fs::remove_file(root.join("gone.txt")).unwrap();
6483
    let snap = repo.snapshot_status("oxy status").unwrap();
6484
    let slow = render_change(&snap.wc, &snap.base, &snap.base_snapshot);
6485
    assert!(
6486
        repo.status_by_manifest().unwrap().is_some(),
6487
        "the cache holds"
6488
    );
6489
    let (wc, base, snapshot) = repo.working_copy_with_base().unwrap();
6490
    assert_eq!(render_change(&wc, &base, &snapshot), slow);
6491
    assert_eq!(repo.diff_files(None).unwrap().len(), 3);
6492
}
6493
6494
/// oxygen#41: a manifest written from a walk keeps every directory's time;
6495
/// while none has moved, the check stats the tracked files without listing
6496
/// the tree, and a file added or removed anywhere moves its directory's
6497
/// time, so the tree is listed again.
6498
#[test]
6499
fn the_manifest_check_skips_listing_while_no_directory_changed() {
6500
    hermetic();
6501
    let dir = tempfile::tempdir().unwrap();
6502
    let root = dir.path();
6503
    let repo = Repo::init(root).unwrap();
6504
    write(root, "a.txt", b"a\n");
6505
    write(root, "sub/deep/b.txt", b"b\n");
6506
    repo.commit("base", &[]).unwrap();
6507
    // Out of the racy window: every file and directory a minute old.
6508
    let old = std::time::SystemTime::now() - std::time::Duration::from_secs(60);
6509
    for p in ["a.txt", "sub/deep/b.txt", "sub/deep", "sub", ""] {
6510
        fs::File::open(root.join(p))
6511
            .unwrap()
6512
            .set_modified(old)
6513
            .unwrap();
6514
    }
6515
    repo.snapshot_status("oxy status").unwrap();
6516
    repo.write_manifest(false, false).unwrap();
6517
    let m = repo.read_manifest().unwrap().unwrap().2;
6518
    assert!(m.dirs.iter().any(|(d, _)| d == "sub/deep"), "{:?}", m.dirs);
6519
    assert_eq!(
6520
        repo.disk_differs_by_dirs(&m),
6521
        Some(false),
6522
        "no listing needed"
6523
    );
6524
    assert_eq!(repo.status_by_manifest().unwrap(), Some(vec![]));
6525
6526
    // A same-size edit with a new time: found by its stat.
6527
    write(root, "sub/deep/b.txt", b"c\n");
6528
    assert_eq!(repo.disk_differs_by_dirs(&m), Some(true));
6529
    write(root, "sub/deep/b.txt", b"b\n");
6530
    fs::File::open(root.join("sub/deep/b.txt"))
6531
        .unwrap()
6532
        .set_modified(old)
6533
        .unwrap();
6534
    assert_eq!(repo.disk_differs_by_dirs(&m), Some(false));
6535
6536
    // A new file moves its directory's time: the tree must be listed.
6537
    write(root, "sub/deep/new.txt", b"n\n");
6538
    assert_eq!(repo.disk_differs_by_dirs(&m), None);
6539
    assert_eq!(repo.status_by_manifest().unwrap(), None);
6540
    fs::remove_file(root.join("sub/deep/new.txt")).unwrap();
6541
    // A removed one too.
6542
    fs::remove_file(root.join("a.txt")).unwrap();
6543
    assert_eq!(repo.disk_differs_by_dirs(&m), None);
6544
}
6545
6546
/// oxygen#41: a commit right after a status takes the snapshot the status
6547
/// left (the status cache holds) rather than walking again, and commits
6548
/// exactly what a snapshot would have.
6549
#[test]
6550
fn a_commit_after_a_status_uses_the_cached_snapshot() {
6551
    hermetic();
6552
    let dir = tempfile::tempdir().unwrap();
6553
    let root = dir.path();
6554
    let repo = Repo::init(root).unwrap();
6555
    write(root, "a.txt", b"a\nb\n");
6556
    write(root, ".oxyattributes", b"*.bin binary\n");
6557
    repo.commit("base", &[]).unwrap();
6558
    write(root, "a.txt", b"a\nB\n");
6559
    write(root, "new.txt", b"new\n");
6560
    let snap = repo.snapshot_status("oxy status").unwrap();
6561
    let cached = repo
6562
        .snapshot_from_cache()
6563
        .unwrap()
6564
        .expect("the cache holds");
6565
    assert_eq!(cached.wc_hash, snap.wc_hash);
6566
    assert_eq!(cached.statuses, snap.statuses);
6567
    assert!(
6568
        !cached.attributes.is_empty(),
6569
        "the .oxyattributes file was read"
6570
    );
6571
    let h = repo.commit("edit", &[]).unwrap();
6572
    let c = repo.store().get_change(&h).unwrap();
6573
    assert_eq!(
6574
        c.tree_ops.len() + c.edits.len(),
6575
        snap.wc.tree_ops.len() + snap.wc.edits.len()
6576
    );
6577
    assert_eq!(
6578
        repo.status_by_manifest().unwrap(),
6579
        Some(vec![]),
6580
        "clean after the commit"
6581
    );
6582
    assert_eq!(fs::read(root.join("a.txt")).unwrap(), b"a\nB\n");
6583
}
6584
6585
/// oxygen#41: a clean check that verified racy entries restamps the
6586
/// manifest, so later checks can trust them, and a same-size rewrite
6587
/// straight afterwards is still found: entries within two seconds of the
6588
/// new time stay racy.
6589
#[test]
6590
fn a_verified_clean_check_restamps_the_manifest_safely() {
6591
    hermetic();
6592
    let dir = tempfile::tempdir().unwrap();
6593
    let root = dir.path();
6594
    let repo = Repo::init(root).unwrap();
6595
    write(root, "a.txt", b"one\n");
6596
    repo.commit("one", &[]).unwrap();
6597
    let before = repo.read_manifest().unwrap().unwrap().2.written_ns;
6598
    assert!(repo.clean_by_manifest().unwrap());
6599
    let after = repo.read_manifest().unwrap().unwrap().2.written_ns;
6600
    assert!(after > before, "restamped");
6601
    write(root, "a.txt", b"two\n");
6602
    assert!(
6603
        !repo.clean_by_manifest().unwrap(),
6604
        "a same-size rewrite is still seen"
6605
    );
6606
}
6607
6608
/// oxygen#35: a history-only state keeps no inserted text. It reads a
6609
/// stored insert's text blob only when it builds that file's graph, and
6610
/// builds the same graph a full load does.
6611
#[test]
6612
fn history_only_states_read_text_only_for_the_graphs_they_build() {
6613
    hermetic();
6614
    let dir = tempfile::tempdir().unwrap();
6615
    let root = dir.path();
6616
    let repo = Repo::init(root).unwrap();
6617
    let big: String = (0..3000).map(|i| format!("big line {i}\n")).collect();
6618
    let other: String = (0..3000).map(|i| format!("other line {i}\n")).collect();
6619
    write(root, "big.txt", big.as_bytes());
6620
    write(root, "other.txt", other.as_bytes());
6621
    let h = repo.commit("two large files", &[]).unwrap();
6622
    write(root, "big.txt", format!("{big}one more\n").as_bytes());
6623
    let h2 = repo.commit("append", &[]).unwrap();
6624
6625
    let full = repo.load_state_full(&[h2]).unwrap().materialize();
6626
    let text = |snap: &crate::state::Snapshot, p: &str| match &snap.files[p].content {
6627
        FileContent::Text { bytes, .. } => bytes.clone(),
6628
        other => panic!("{other:?}"),
6629
    };
6630
    // Built on demand, every graph renders as the full load's.
6631
    let mut hist = repo.load_state_history(&[h2]).unwrap();
6632
    let big_node = full.files["big.txt"].node;
6633
    assert!(hist.graph_key(&big_node).is_some(), "not built yet");
6634
    repo.load_all_graphs(&mut hist).unwrap();
6635
    let rendered = hist.materialize();
6636
    for p in ["big.txt", "other.txt"] {
6637
        assert_eq!(text(&rendered, p), text(&full, p), "{p}");
6638
    }
6639
6640
    // Without other.txt's text blob, history still loads and big.txt still
6641
    // builds: nothing read the other text.
6642
    let (_, texts) = repo.store().get_change_lazy(&h).unwrap();
6643
    assert_eq!(texts.len(), 2);
6644
    let content = |r: &ObjectRef| -> Vec<u8> {
6645
        let blob = crate::objects::Blob::decode(&repo.store().get(r).unwrap().1).unwrap();
6646
        blob.chunks
6647
            .iter()
6648
            .flat_map(|c| repo.store().get(c).unwrap().1)
6649
            .collect()
6650
    };
6651
    let other_text = texts
6652
        .iter()
6653
        .filter_map(|t| match t {
6654
            crate::objects::TextRef::Blob(r, _, _) => Some(*r),
6655
            _ => None,
6656
        })
6657
        .find(|r| content(r).windows(12).any(|w| w == b"other line 1"))
6658
        .unwrap();
6659
    repo.store().remove_loose_for_test(&other_text).unwrap();
6660
    let mut hist = repo.load_state_history(&[h2]).unwrap();
6661
    repo.load_graphs_of(&mut hist, &[big_node]).unwrap();
6662
    assert!(repo
6663
        .load_graphs_of(&mut hist, &[full.files["other.txt"].node])
6664
        .is_err());
6665
}
6666
6667
/// oxygen#35: the first status after a commit read and rendered every
6668
/// file (79 s and more than 14 GB on the Linux tree), because the
6669
/// manifest had no graph keys for files the commit added.
6670
#[test]
6671
fn a_commit_leaves_a_manifest_the_next_status_trusts() {
6672
    use std::os::unix::fs::PermissionsExt;
6673
    hermetic();
6674
    let dir = tempfile::tempdir().unwrap();
6675
    let root = dir.path();
6676
    let repo = Repo::init(root).unwrap();
6677
    let files = ["a.txt", "b.txt", "d/c.txt"];
6678
    for p in files {
6679
        write(root, p, format!("{p}\n").as_bytes());
6680
        let old = std::time::SystemTime::now() - std::time::Duration::from_secs(30);
6681
        fs::File::options()
6682
            .write(true)
6683
            .open(root.join(p))
6684
            .unwrap()
6685
            .set_modified(old)
6686
            .unwrap();
6687
    }
6688
    repo.commit("added", &[]).unwrap();
6689
    let (_, _, m) = repo.read_manifest().unwrap().unwrap();
6690
    assert!(
6691
        m.entries.values().all(|e| e.graph.is_some()),
6692
        "keys recorded at commit"
6693
    );
6694
    // Unreadable files prove the next status reads none of them.
6695
    for p in files {
6696
        fs::set_permissions(root.join(p), fs::Permissions::from_mode(0o000)).unwrap();
6697
    }
6698
    let snap = repo.snapshot_status("status").unwrap();
6699
    for p in files {
6700
        fs::set_permissions(root.join(p), fs::Permissions::from_mode(0o644)).unwrap();
6701
    }
6702
    assert!(!snap.changed && snap.statuses.is_empty());
6703
    assert_eq!(snap.base_snapshot.unrendered.len(), files.len());
6704
}
6705
6706
/// oxygen#35: a checkout reads, renders and writes only the files whose
6707
/// graphs differ, and renders the rest a batch at a time.
6708
#[test]
6709
fn checkout_touches_only_what_differs_and_renders_in_batches() {
6710
    use std::os::unix::fs::PermissionsExt;
6711
    hermetic();
6712
    let dir = tempfile::tempdir().unwrap();
6713
    let root = dir.path();
6714
    let origin = root.join("origin");
6715
    let mut repo = Repo::init(&origin).unwrap();
6716
    // More files than one batch holds.
6717
    let n = 2100;
6718
    let old = std::time::SystemTime::now() - std::time::Duration::from_secs(30);
6719
    for i in 0..n {
6720
        let p = format!("f/{i:04}.txt");
6721
        write(&origin, &p, format!("file {i}\n").as_bytes());
6722
        fs::File::options()
6723
            .write(true)
6724
            .open(origin.join(&p))
6725
            .unwrap()
6726
            .set_modified(old)
6727
            .unwrap();
6728
    }
6729
    repo.commit("many", &[]).unwrap();
6730
    repo.bookmark_create("feature", None).unwrap();
6731
    repo.bookmark_switch("feature", false).unwrap();
6732
    write(&origin, "f/0007.txt", b"changed\n");
6733
    repo.commit("one change", &[]).unwrap();
6734
6735
    // Switching back to main must not read the unchanged files.
6736
    for i in 0..n {
6737
        if i != 7 {
6738
            let p = origin.join(format!("f/{i:04}.txt"));
6739
            fs::set_permissions(&p, fs::Permissions::from_mode(0o000)).unwrap();
6740
        }
6741
    }
6742
    let r = repo.bookmark_switch("main", false).unwrap();
6743
    for i in 0..n {
6744
        let p = origin.join(format!("f/{i:04}.txt"));
6745
        fs::set_permissions(&p, fs::Permissions::from_mode(0o644)).unwrap();
6746
    }
6747
    assert_eq!((r.written, r.removed), (1, 0), "{r:?}");
6748
    assert_eq!(fs::read(origin.join("f/0007.txt")).unwrap(), b"file 7\n");
6749
    assert!(repo.snapshot_status("status").unwrap().statuses.is_empty());
6750
6751
    // A clone renders every file, across batches.
6752
    let c = root.join("clone");
6753
    Repo::clone(&origin.to_string_lossy(), &c).unwrap();
6754
    for i in [0, 2047, 2048, n - 1] {
6755
        assert_eq!(
6756
            fs::read(c.join(format!("f/{i:04}.txt"))).unwrap(),
6757
            format!("file {i}\n").as_bytes()
6758
        );
6759
    }
6760
    let cloned = Repo::open(&c).unwrap();
6761
    assert!(cloned
6762
        .snapshot_status("status")
6763
        .unwrap()
6764
        .statuses
6765
        .is_empty());
6766
}
6767
6768
/// A file written just before the manifest (inside the racy window) is
6769
/// checked by its hash: trusted when equal, caught when edited in place
6770
/// with the same size and time.
6771
#[test]
6772
fn a_racy_manifest_entry_is_checked_by_hash() {
6773
    hermetic();
6774
    let dir = tempfile::tempdir().unwrap();
6775
    let root = dir.path();
6776
    let repo = Repo::init(root).unwrap();
6777
    write(root, "a.txt", b"one\n");
6778
    repo.commit("fresh", &[]).unwrap();
6779
    assert!(repo.clean_by_manifest().unwrap(), "fresh but equal");
6780
    let t = fs::metadata(root.join("a.txt"))
6781
        .unwrap()
6782
        .modified()
6783
        .unwrap();
6784
    write(root, "a.txt", b"two\n");
6785
    fs::File::options()
6786
        .write(true)
6787
        .open(root.join("a.txt"))
6788
        .unwrap()
6789
        .set_modified(t)
6790
        .unwrap();
6791
    assert!(
6792
        !repo.clean_by_manifest().unwrap(),
6793
        "same size and time, other bytes"
6794
    );
6795
    assert_eq!(
6796
        statuses(&repo.snapshot_status("status").unwrap()),
6797
        vec![("a.txt".to_string(), ChangeStatus::Modified)]
6798
    );
6799
}
6800
6801
/// A fetch on one machine moves changes as stored, text blobs among the
6802
/// objects; a change whose text blob did not come is refused, not stored.
6803
#[test]
6804
fn a_raw_bundle_without_a_changes_text_is_refused() {
6805
    hermetic();
6806
    let dir = tempfile::tempdir().unwrap();
6807
    let root = dir.path();
6808
    let a = Repo::init(&root.join("a")).unwrap();
6809
    let big: String = (0..3000).map(|i| format!("line {i}\n")).collect();
6810
    write(&root.join("a"), "big.txt", big.as_bytes());
6811
    let h = a.commit("big", &[]).unwrap();
6812
    let bundle = a.bundle_raw_for(&[h], None).unwrap();
6813
    assert_eq!(bundle.raw_changes.len(), 1);
6814
    assert!(bundle.changes.is_empty());
6815
    let b = Repo::init(&root.join("b")).unwrap();
6816
    let mut without = bundle.clone();
6817
    without.objects.retain(|(ty, _)| *ty != ObjectType::Blob);
6818
    let e = b.import_bundle(&without, false).unwrap_err();
6819
    assert!(e.to_string().contains("came without its text blob"), "{e}");
6820
    assert!(!b.store().has(&h));
6821
    assert_eq!(b.import_bundle(&bundle, false).unwrap(), vec![h]);
6822
    assert_eq!(b.store().get_change(&h).unwrap().message, "big");
6823
}
6824
6825
/// oxygen#30 (vscode): a directory deleted in one line of history and made
6826
/// again was a second node for one Git path, so a file moved into it on
6827
/// another line, where the first node still stood, ended up in two places.
6828
/// An import now brings the directory back rather than make a new one.
6829
#[test]
6830
fn git_import_brings_a_directory_back_rather_than_making_a_second() {
6831
    hermetic();
6832
    if std::process::Command::new("git")
6833
        .arg("--version")
6834
        .output()
6835
        .is_err()
6836
    {
6837
        eprintln!("git not installed; skipping");
6838
        return;
6839
    }
6840
    let dir = tempfile::tempdir().unwrap();
6841
    let root = dir.path();
6842
    let g = root.join("src.git");
6843
    fs::create_dir_all(&g).unwrap();
6844
    let git = |args: &[&str]| -> String {
6845
        let out = std::process::Command::new("git")
6846
            .arg("-C")
6847
            .arg(&g)
6848
            .args([
6849
                "-c",
6850
                "user.name=Grace",
6851
                "-c",
6852
                "[email protected]",
6853
                "-c",
6854
                "commit.gpgsign=false",
6855
            ])
6856
            .args(args)
6857
            .output()
6858
            .unwrap();
6859
        assert!(
6860
            out.status.success(),
6861
            "git {args:?}: {}",
6862
            String::from_utf8_lossy(&out.stderr)
6863
        );
6864
        String::from_utf8_lossy(&out.stdout).trim().to_string()
6865
    };
6866
    git(&["init", "-q", "-b", "main"]);
6867
    write(&g, "d/a.txt", b"a\n");
6868
    write(&g, "c/x.txt", b"x\n");
6869
    git(&["add", "."]);
6870
    git(&["commit", "-qm", "base"]);
6871
    // One line: move x into d while d still stands.
6872
    git(&["checkout", "-qb", "side"]);
6873
    git(&["mv", "c/x.txt", "d/x.txt"]);
6874
    git(&["commit", "-qm", "x into d"]);
6875
    // The other: d goes, comes back, and x moves into it too.
6876
    git(&["checkout", "-q", "main"]);
6877
    git(&["rm", "-q", "d/a.txt"]);
6878
    git(&["commit", "-qm", "d goes"]);
6879
    write(&g, "d/b.txt", b"b\n");
6880
    git(&["add", "."]);
6881
    git(&["commit", "-qm", "d comes back"]);
6882
    git(&["mv", "c/x.txt", "d/x.txt"]);
6883
    git(&["commit", "-qm", "x into d again"]);
6884
    git(&["merge", "-q", "--no-edit", "side"]);
6885
6886
    let repo = Repo::init(&root.join("o")).unwrap();
6887
    repo.import_git(&g, "main").unwrap();
6888
    let v = repo.verify_git_import(&g, "main").unwrap();
6889
    assert!(v.mismatches.is_empty(), "{:?}", v.mismatches);
6890
    let st = repo
6891
        .load_state_history(&repo.bookmark_heads().unwrap())
6892
        .unwrap();
6893
    let view = st.tree().view();
6894
    assert!(view.conflicts.is_empty(), "{:?}", view.conflicts);
6895
    // The directory is the one the first commit made.
6896
    // Commits made in one second tie on time: find the first by its message.
6897
    let first = repo
6898
        .log()
6899
        .unwrap()
6900
        .into_iter()
6901
        .find(|e| e.change.message.starts_with("base"))
6902
        .unwrap();
6903
    let base = repo
6904
        .load_state_history(&[first.hash])
6905
        .unwrap()
6906
        .tree()
6907
        .view();
6908
    assert_eq!(view.entries["d"].node, base.entries["d"].node);
6909
}
6910
6911
/// oxygen#30, the rest: a placement left under a directory another line
6912
/// removed is out of sight, so no diff reaches it; the merge that settles
6913
/// where the file is retires it.
6914
#[test]
6915
fn git_import_merge_retires_a_placement_under_a_removed_directory() {
6916
    hermetic();
6917
    if std::process::Command::new("git")
6918
        .arg("--version")
6919
        .output()
6920
        .is_err()
6921
    {
6922
        eprintln!("git not installed; skipping");
6923
        return;
6924
    }
6925
    let dir = tempfile::tempdir().unwrap();
6926
    let root = dir.path();
6927
    let g = root.join("src.git");
6928
    fs::create_dir_all(&g).unwrap();
6929
    let run = |args: &[&str]| {
6930
        std::process::Command::new("git")
6931
            .arg("-C")
6932
            .arg(&g)
6933
            .args([
6934
                "-c",
6935
                "user.name=Grace",
6936
                "-c",
6937
                "[email protected]",
6938
                "-c",
6939
                "commit.gpgsign=false",
6940
            ])
6941
            .args(args)
6942
            .output()
6943
            .unwrap()
6944
    };
6945
    let git = |args: &[&str]| {
6946
        let out = run(args);
6947
        assert!(
6948
            out.status.success(),
6949
            "git {args:?}: {}",
6950
            String::from_utf8_lossy(&out.stderr)
6951
        );
6952
    };
6953
    git(&["init", "-q", "-b", "main"]);
6954
    write(&g, "c/x.txt", b"x\n");
6955
    write(&g, "keep.txt", b"k\n");
6956
    git(&["add", "."]);
6957
    git(&["commit", "-qm", "base"]);
6958
    // One line renames the file within c; the other moves it out of c,
6959
    // which goes.
6960
    git(&["checkout", "-qb", "side"]);
6961
    git(&["mv", "c/x.txt", "c/y.txt"]);
6962
    git(&["commit", "-qm", "rename within c"]);
6963
    git(&["checkout", "-q", "main"]);
6964
    fs::create_dir_all(g.join("n")).unwrap();
6965
    git(&["mv", "c/x.txt", "n/x.txt"]);
6966
    git(&["commit", "-qm", "move out of c"]);
6967
    // Git cannot merge the two renames; the merge keeps n/x.txt.
6968
    let _ = run(&["merge", "-q", "side"]);
6969
    let _ = run(&[
6970
        "rm",
6971
        "-q",
6972
        "--cached",
6973
        "--ignore-unmatch",
6974
        "c/y.txt",
6975
        "c/x.txt",
6976
    ]);
6977
    let _ = std::fs::remove_dir_all(g.join("c"));
6978
    write(&g, "n/x.txt", b"x\n");
6979
    git(&["add", "-A"]);
6980
    git(&["commit", "-qm", "merge: keep n/x.txt"]);
6981
6982
    let repo = Repo::init(&root.join("o")).unwrap();
6983
    repo.import_git(&g, "main").unwrap();
6984
    let v = repo.verify_git_import(&g, "main").unwrap();
6985
    assert!(v.mismatches.is_empty(), "{:?}", v.mismatches);
6986
    let st = repo
6987
        .load_state_history(&repo.bookmark_heads().unwrap())
6988
        .unwrap();
6989
    let view = st.tree().view();
6990
    assert!(view.conflicts.is_empty(), "{:?}", view.conflicts);
6991
    assert!(view.entries.contains_key("n/x.txt"));
6992
}
6993
6994
/// oxygen#30, orphans: a file added on one line into a directory the other
6995
/// line removed is placed where the tree cannot show it; Git's merge keeps
6996
/// the file, and the import's merge leaves exactly one of it.
6997
#[test]
6998
fn git_import_merge_leaves_no_orphan_behind() {
6999
    hermetic();
7000
    if std::process::Command::new("git")
7001
        .arg("--version")
7002
        .output()
7003
        .is_err()
7004
    {
7005
        eprintln!("git not installed; skipping");
7006
        return;
7007
    }
7008
    let dir = tempfile::tempdir().unwrap();
7009
    let root = dir.path();
7010
    let g = root.join("src.git");
7011
    fs::create_dir_all(&g).unwrap();
7012
    let git = |args: &[&str]| {
7013
        let out = std::process::Command::new("git")
7014
            .arg("-C")
7015
            .arg(&g)
7016
            .args([
7017
                "-c",
7018
                "user.name=Grace",
7019
                "-c",
7020
                "[email protected]",
7021
                "-c",
7022
                "commit.gpgsign=false",
7023
            ])
7024
            .args(args)
7025
            .output()
7026
            .unwrap();
7027
        assert!(
7028
            out.status.success(),
7029
            "git {args:?}: {}",
7030
            String::from_utf8_lossy(&out.stderr)
7031
        );
7032
    };
7033
    git(&["init", "-q", "-b", "main"]);
7034
    write(&g, "d/f.txt", b"f\n");
7035
    write(&g, "keep.txt", b"k\n");
7036
    git(&["add", "."]);
7037
    git(&["commit", "-qm", "base"]);
7038
    git(&["checkout", "-qb", "side"]);
7039
    write(&g, "d/new.txt", b"new\n");
7040
    git(&["add", "."]);
7041
    git(&["commit", "-qm", "add into d"]);
7042
    git(&["checkout", "-q", "main"]);
7043
    git(&["rm", "-q", "d/f.txt"]);
7044
    git(&["commit", "-qm", "d goes"]);
7045
    git(&["merge", "-q", "--no-edit", "side"]);
7046
7047
    let repo = Repo::init(&root.join("o")).unwrap();
7048
    repo.import_git(&g, "main").unwrap();
7049
    let v = repo.verify_git_import(&g, "main").unwrap();
7050
    assert!(v.mismatches.is_empty(), "{:?}", v.mismatches);
7051
    let st = repo
7052
        .load_state_history(&repo.bookmark_heads().unwrap())
7053
        .unwrap();
7054
    let view = st.tree().view();
7055
    assert!(view.conflicts.is_empty(), "{:?}", view.conflicts);
7056
    assert!(view.entries.contains_key("d/new.txt"));
7057
}
7058
7059
/// fsck checks a change's text as the blobs it is stored in, without
7060
/// decoding it: a missing text blob is an error named for the change.
7061
#[test]
7062
fn fsck_names_a_missing_text_blob() {
7063
    hermetic();
7064
    let dir = tempfile::tempdir().unwrap();
7065
    let root = dir.path();
7066
    let repo = Repo::init(root).unwrap();
7067
    let big: String = (0..3000).map(|i| format!("line {i}\n")).collect();
7068
    write(root, "big.txt", big.as_bytes());
7069
    let h = repo.commit("big", &[]).unwrap();
7070
    assert_eq!(repo.fsck().unwrap().errors(), 0);
7071
    let (_, texts) = repo.store().get_change_lazy(&h).unwrap();
7072
    let Some(crate::objects::TextRef::Blob(b, _, _)) = texts.first().copied() else {
7073
        panic!("a stored text")
7074
    };
7075
    repo.store().remove_loose_for_test(&b).unwrap();
7076
    let rep = repo.fsck().unwrap();
7077
    assert!(rep.errors() > 0);
7078
    assert!(
7079
        rep.problems.iter().any(|p| p.what.contains(&h.short(12))),
7080
        "{:?}",
7081
        rep.problems
7082
    );
7083
}
7084
7085
/// oxygen#32: a subrepo on the same hub as one of the parent's remotes is
7086
/// reached with that remote's token and CA (a private subrepo then clones
7087
/// for anyone who can read the parent); another hub gets none of them.
7088
#[test]
7089
fn a_subrepo_on_the_parents_hub_borrows_its_credentials() {
7090
    hermetic();
7091
    let dir = tempfile::tempdir().unwrap();
7092
    let mut repo = Repo::init(dir.path()).unwrap();
7093
    repo.config
7094
        .set(
7095
            "remote.origin.url",
7096
            "https://Hub.example:7343/doomsdayone/metalgear",
7097
        )
7098
        .unwrap();
7099
    repo.config.set("remote.origin.token", "secret").unwrap();
7100
    repo.config
7101
        .set("remote.origin.ca", "/tmp/hub-ca.pem")
7102
        .unwrap();
7103
    let same = repo.credentials_for("https://hub.example:7343/doomsdayone/rstar-api");
7104
    assert_eq!(same.token.as_deref(), Some("secret"));
7105
    assert_eq!(same.ca.as_deref(), Some(Path::new("/tmp/hub-ca.pem")));
7106
    for other in [
7107
        "https://elsewhere.example:7343/doomsdayone/rstar-api",
7108
        "https://hub.example/doomsdayone/rstar-api",
7109
        "http://hub.example:7343/doomsdayone/rstar-api",
7110
    ] {
7111
        let o = repo.credentials_for(other);
7112
        assert_ne!(o.token.as_deref(), Some("secret"), "{other}");
7113
    }
7114
}
7115
7116
/// oxygen#47: a remote with no token of its own uses the user's credential
7117
/// store for its hub, and a nested checkout finds its parent's remote
7118
/// token there instead of keeping a copy.
7119
#[test]
7120
fn remotes_use_the_credential_store_and_the_enclosing_checkout() {
7121
    hermetic();
7122
    let home = tempfile::tempdir().unwrap();
7123
    let dir = tempfile::tempdir().unwrap();
7124
    let mut parent = Repo::init(dir.path()).unwrap().with_home(home.path());
7125
    parent
7126
        .config
7127
        .set("remote.origin.url", "https://hub.example/o/parent")
7128
        .unwrap();
7129
    parent.save_config().unwrap();
7130
    assert_eq!(parent.remote_options("origin").token, None);
7131
    crate::credentials::Credentials::at(home.path())
7132
        .save("https://hub.example", "stored", Some("andy"), None)
7133
        .unwrap();
7134
    assert_eq!(
7135
        parent.remote_options("origin").token.as_deref(),
7136
        Some("stored")
7137
    );
7138
7139
    let empty_home = tempfile::tempdir().unwrap();
7140
    let nested = dir.path().join("deps").join("child");
7141
    let mut child = Repo::init(&nested).unwrap().with_home(empty_home.path());
7142
    child
7143
        .config
7144
        .set("remote.origin.url", "https://hub.example/o/child")
7145
        .unwrap();
7146
    child.save_config().unwrap();
7147
    assert_eq!(child.remote_options("origin").token, None);
7148
    parent
7149
        .config
7150
        .set("remote.origin.token", "checkout")
7151
        .unwrap();
7152
    parent.save_config().unwrap();
7153
    assert_eq!(
7154
        child.remote_options("origin").token.as_deref(),
7155
        Some("checkout")
7156
    );
7157
    // Another hub's checkout token is not borrowed.
7158
    child
7159
        .config
7160
        .set("remote.origin.url", "https://other.example/o/child")
7161
        .unwrap();
7162
    assert_eq!(child.remote_options("origin").token, None);
7163
}
7164
7165
#[test]
7166
fn the_metadata_cache_survives_a_torn_tail() {
7167
    hermetic();
7168
    let dir = tempfile::tempdir().unwrap();
7169
    let root = dir.path();
7170
    let repo = Repo::init(root).unwrap();
7171
    write(root, "a.txt", b"1\n");
7172
    let h = repo.commit("first", &[]).unwrap();
7173
    let meta = repo.store().get_change_meta(&h).unwrap();
7174
    let cache = repo.store().dir().join("metas");
7175
    let len = fs::metadata(&cache).unwrap().len();
7176
    assert!(len > 0, "a change read is cached");
7177
    // A torn record at the end: the cache reads up to it and cuts it off.
7178
    fs::OpenOptions::new()
7179
        .append(true)
7180
        .open(&cache)
7181
        .unwrap()
7182
        .write_all(&[7; 20])
7183
        .unwrap();
7184
    let again = Repo::open(root).unwrap();
7185
    assert_eq!(again.store().get_change_meta(&h).unwrap(), meta);
7186
    assert_eq!(fs::metadata(&cache).unwrap().len(), len);
7187
}
7188
7189
#[test]
7190
fn a_manifest_that_does_not_check_reads_as_none() {
7191
    hermetic();
7192
    let dir = tempfile::tempdir().unwrap();
7193
    let root = dir.path();
7194
    let repo = Repo::init(root).unwrap();
7195
    write(root, "a.txt", b"1\n");
7196
    repo.commit("first", &[]).unwrap();
7197
    let path = repo.manifest_path();
7198
    let mut bytes = fs::read(&path).unwrap();
7199
    assert!(Repo::open(root).unwrap().read_manifest().unwrap().is_some());
7200
    let last = bytes.len() - 1;
7201
    bytes[last] ^= 1;
7202
    fs::write(&path, &bytes).unwrap();
7203
    assert!(Repo::open(root).unwrap().read_manifest().unwrap().is_none());
7204
    // The next status reads the files and writes it again.
7205
    let again = Repo::open(root).unwrap();
7206
    assert!(!again.snapshot("status").unwrap().changed);
7207
    assert!(again.read_manifest().unwrap().is_some());
7208
}
7209
7210
#[test]
7211
fn a_commit_leaves_a_manifest_that_proves_the_working_copy_clean() {
7212
    hermetic();
7213
    let dir = tempfile::tempdir().unwrap();
7214
    let root = dir.path();
7215
    let repo = Repo::init(root).unwrap();
7216
    write(root, "a.txt", b"1\n");
7217
    write(root, "b.txt", b"2\n");
7218
    // b.txt outside the racy window, so snapshots take it as unchanged.
7219
    let old = std::time::SystemTime::now() - std::time::Duration::from_secs(60);
7220
    fs::File::options()
7221
        .write(true)
7222
        .open(root.join("b.txt"))
7223
        .unwrap()
7224
        .set_modified(old)
7225
        .unwrap();
7226
    repo.commit("first", &[]).unwrap();
7227
    assert!(repo.clean_by_manifest().unwrap(), "after the first commit");
7228
    repo.snapshot_status("status").unwrap();
7229
    write(root, "a.txt", b"1\n2\n");
7230
    repo.commit("second", &[]).unwrap();
7231
    assert!(
7232
        repo.clean_by_manifest().unwrap(),
7233
        "after a commit of one file"
7234
    );
7235
    // Edited, seen by a status, edited again, then committed: the status
7236
    // left the first edit's stat, which the commit must not keep.
7237
    write(root, "a.txt", b"1\n2\n3\n");
7238
    repo.snapshot_status("status").unwrap();
7239
    write(root, "a.txt", b"1\n2\n3\n4\n5\n");
7240
    repo.commit("third", &[]).unwrap();
7241
    assert!(
7242
        repo.clean_by_manifest().unwrap(),
7243
        "after an edit a status saw"
7244
    );
7245
}
7246
7247
#[test]
7248
fn a_conflicted_rebase_can_be_resolved_in_the_working_copy() {
7249
    hermetic();
7250
    let dir = tempfile::tempdir().unwrap();
7251
    let root = dir.path();
7252
    let mut repo = Repo::init(root).unwrap().with_home(root.join("home"));
7253
    write(root, "a.txt", b"1\n2\n");
7254
    let a = repo.commit("A", &[]).unwrap();
7255
    repo.bookmark_create("develop", Some(&[a])).unwrap();
7256
    write(root, "a.txt", b"1\nX\n");
7257
    let c = repo.commit("C: 2 to X", &[]).unwrap();
7258
    repo.bookmark_switch("develop", false).unwrap();
7259
    write(root, "a.txt", b"1\nY\n");
7260
    let d = repo.commit("D: 2 to Y", &[]).unwrap();
7261
    repo.bookmark_switch("main", false).unwrap();
7262
7263
    let err = repo.rebase(&c, &[d]).unwrap_err();
7264
    assert!(matches!(err, RepoError::Conflicted(_)), "{err}");
7265
    let r = repo.rebase_into_working_copy(&c, &[d]).unwrap();
7266
    assert!(r.changed && r.checked_out);
7267
    let snap = repo.snapshot_status("status").unwrap();
7268
    assert!(
7269
        snap.base_snapshot.is_conflicted(),
7270
        "the conflict is in the working copy"
7271
    );
7272
    let text = fs::read_to_string(root.join("a.txt")).unwrap();
7273
    assert!(text.contains('X') && text.contains('Y'), "{text}");
7274
7275
    write(root, "a.txt", b"1\nXY\n");
7276
    repo.commit("Resolve", &[]).unwrap();
7277
    let st = repo.load_state(&repo.bookmark_heads().unwrap()).unwrap();
7278
    assert!(st.contains(&c) && st.contains(&d));
7279
    let files = st.materialize().files;
7280
    assert!(!files["a.txt"].is_conflicted());
7281
    assert!(
7282
        matches!(&files["a.txt"].content, FileContent::Text { bytes, .. } if bytes == b"1\nXY\n")
7283
    );
7284
7285
    // A change the current bookmark does not hold is refused.
7286
    repo.bookmark_switch("develop", false).unwrap();
7287
    write(root, "b.txt", b"b\n");
7288
    let e = repo.commit("E", &[]).unwrap();
7289
    repo.bookmark_switch("main", false).unwrap();
7290
    let err = repo.rebase_into_working_copy(&e, &[a]).unwrap_err();
7291
    assert!(
7292
        err.to_string().contains("not on the current bookmark"),
7293
        "{err}"
7294
    );
7295
}
7296
7297
#[test]
7298
fn an_ignore_rule_drops_an_added_file_but_not_a_tracked_one() {
7299
    hermetic();
7300
    let dir = tempfile::tempdir().unwrap();
7301
    let root = dir.path();
7302
    let repo = Repo::init(root).unwrap();
7303
    write(root, "a.txt", b"a\n");
7304
    write(root, "kept.log", b"tracked\n");
7305
    repo.commit("first", &[]).unwrap();
7306
    write(root, "build.log", b"made\n");
7307
    let snap = repo.snapshot_status("status").unwrap();
7308
    assert!(snap.statuses.iter().any(|s| s.path == "build.log"));
7309
    // A rule written afterwards leaves the added file out again, while the
7310
    // committed one stays tracked.
7311
    write(root, ".gitignore", b"*.log\n");
7312
    let snap = repo.snapshot_status("status").unwrap();
7313
    let paths: Vec<&str> = snap.statuses.iter().map(|s| s.path.as_str()).collect();
7314
    assert_eq!(paths, vec![".gitignore"], "{paths:?}");
7315
    write(root, "kept.log", b"tracked, edited\n");
7316
    let snap = repo.snapshot_status("status").unwrap();
7317
    assert!(snap.statuses.iter().any(|s| s.path == "kept.log"));
7318
}
7319
7320
#[test]
7321
fn shed_graphs_come_back_the_same() {
7322
    hermetic();
7323
    let dir = tempfile::tempdir().unwrap();
7324
    let root = dir.path();
7325
    let repo = Repo::init(root).unwrap();
7326
    write(root, "a.txt", b"1\n2\n3\n");
7327
    write(root, "b.txt", b"x\n");
7328
    repo.commit("first", &[]).unwrap();
7329
    write(root, "a.txt", b"1\ntwo\n3\n4\n");
7330
    repo.commit("second", &[]).unwrap();
7331
    let heads = repo.bookmark_heads().unwrap();
7332
    let mut st = repo.load_state_history(&heads).unwrap();
7333
    let view = st.tree().view();
7334
    let nodes: Vec<NodeId> = ["a.txt", "b.txt"]
7335
        .iter()
7336
        .map(|p| view.entries[*p].node)
7337
        .collect();
7338
    repo.load_graphs_of(&mut st, &nodes).unwrap();
7339
    let before: Vec<Vec<u8>> = nodes.iter().map(|n| st.render_file(n).0).collect();
7340
    assert_eq!(st.built_count(), 2);
7341
    let shed = st.shed_graphs(|b| repo.store_blob(b)).unwrap();
7342
    assert_eq!((shed, st.built_count()), (2, 0));
7343
    // A later change applies on top of the shed history.
7344
    write(root, "a.txt", b"1\ntwo\n3\n4\n5\n");
7345
    let h3 = repo.commit("third", &[]).unwrap();
7346
    let (skeleton, texts) = repo.store().get_change_lazy(&h3).unwrap();
7347
    st.add_known(h3, skeleton, texts);
7348
    repo.load_graphs_of(&mut st, &nodes).unwrap();
7349
    let after: Vec<Vec<u8>> = nodes.iter().map(|n| st.render_file(n).0).collect();
7350
    assert_eq!(after[1], before[1]);
7351
    assert_eq!(after[0], b"1\ntwo\n3\n4\n5\n");
7352
}
7353
7354
#[test]
7355
fn many_edited_files_diff_in_parallel() {
7356
    // Enough edited files that the builder diffs them in parallel; the
7357
    // commit must hold exactly what is on disk, and a second snapshot
7358
    // must find nothing left to commit.
7359
    hermetic();
7360
    let dir = tempfile::tempdir().unwrap();
7361
    let root = dir.path();
7362
    let repo = Repo::init(root).unwrap();
7363
    let text = |i: usize, round: usize| {
7364
        let mut s = String::new();
7365
        for line in 0..50 {
7366
            if round > 0 && line % 7 == i % 7 {
7367
                s.push_str(&format!("edited {round} {i} {line}\n"));
7368
            } else {
7369
                s.push_str(&format!("file {i} line {line}\n"));
7370
            }
7371
        }
7372
        if round > 0 && i.is_multiple_of(3) {
7373
            s.push_str("appended\n");
7374
        }
7375
        s
7376
    };
7377
    for i in 0..40 {
7378
        write(root, &format!("d/f{i}.txt"), text(i, 0).as_bytes());
7379
    }
7380
    repo.commit("first", &[]).unwrap();
7381
    for i in 0..40 {
7382
        write(root, &format!("d/f{i}.txt"), text(i, 1).as_bytes());
7383
    }
7384
    let h = repo.commit("edit every file", &[]).unwrap();
7385
    let snap = repo.load_state(&[h]).unwrap().materialize();
7386
    for i in 0..40 {
7387
        let want = text(i, 1);
7388
        assert!(
7389
            matches!(&snap.files[&format!("d/f{i}.txt")].content, FileContent::Text { bytes, .. } if bytes == want.as_bytes()),
7390
            "d/f{i}.txt as committed"
7391
        );
7392
    }
7393
    assert!(
7394
        repo.commit("nothing", &[]).is_err(),
7395
        "nothing left to commit"
7396
    );
7397
}
7398
7399
/// oxygen#56: after a fetch, how a bookmark stands against its remote copy
7400
/// is known (fetch printed "up to date" while main was behind), a change
7401
/// only fetched resolves and says where it is, and a checkout whose only
7402
/// remote is not `origin` uses that one.
7403
#[test]
7404
fn a_fetched_change_shows_as_behind_and_resolves() {
7405
    hermetic();
7406
    let dir = tempfile::tempdir().unwrap();
7407
    let root = dir.path();
7408
    let origin = Repo::init(&root.join("origin")).unwrap();
7409
    drop(origin);
7410
    let url = root.join("origin").to_string_lossy().to_string();
7411
    let a = Repo::clone(&url, &root.join("a"))
7412
        .unwrap()
7413
        .with_home(root.join("home-a"));
7414
    write(&root.join("a"), "f.txt", b"one\n");
7415
    a.commit("one", &[]).unwrap();
7416
    a.push("origin", false).unwrap();
7417
    let b = Repo::clone(&url, &root.join("b"))
7418
        .unwrap()
7419
        .with_home(root.join("home-b"));
7420
    assert_eq!(b.tracking("origin", "main").unwrap(), Some((0, 0)));
7421
7422
    write(&root.join("a"), "f.txt", b"one\ntwo\n");
7423
    let h2 = a.commit("two", &[]).unwrap();
7424
    a.push("origin", false).unwrap();
7425
    b.fetch("origin").unwrap();
7426
    // Fetched, not pulled: one behind, the change found and placed.
7427
    assert_eq!(b.tracking("origin", "main").unwrap(), Some((0, 1)));
7428
    assert_eq!(b.tracking("origin", "nope").unwrap(), None);
7429
    assert_eq!(
7430
        b.resolve_change(&format!("#{}", &h2.to_hex()[..12]))
7431
            .unwrap(),
7432
        h2
7433
    );
7434
    assert_eq!(
7435
        b.remote_only_location(&h2).unwrap().as_deref(),
7436
        Some("origin/main")
7437
    );
7438
    // Fetching again changes nothing: still behind, which is what the
7439
    // CLI now says rather than "up to date".
7440
    b.fetch("origin").unwrap();
7441
    assert_eq!(b.tracking("origin", "main").unwrap(), Some((0, 1)));
7442
    b.pull("origin").unwrap();
7443
    assert_eq!(b.tracking("origin", "main").unwrap(), Some((0, 0)));
7444
    assert_eq!(b.remote_only_location(&h2).unwrap(), None);
7445
7446
    // One remote, not called origin: it is the default.
7447
    let mut c = Repo::init(&root.join("c")).unwrap();
7448
    assert_eq!(c.default_remote(), "origin");
7449
    c.config.set("remote.earth.url", &url).unwrap();
7450
    assert_eq!(c.default_remote(), "earth");
7451
    c.config.set("remote.origin.url", &url).unwrap();
7452
    assert_eq!(c.default_remote(), "origin");
7453
}
7454
7455
/// oxygen#57: a clone from a relative local path records the remote as an
7456
/// absolute path, so fetch still finds it from inside the clone.
7457
#[test]
7458
fn a_clone_from_a_relative_path_records_it_absolute() {
7459
    hermetic();
7460
    let dir = tempfile::tempdir().unwrap();
7461
    let root = dir.path();
7462
    Repo::init(&root.join("origin")).unwrap();
7463
    let rel = crate::protocol::stored_url("relative/repo");
7464
    assert!(std::path::Path::new(&rel).is_absolute(), "{rel}");
7465
    assert_eq!(
7466
        crate::protocol::stored_url("https://hub.example/o/n"),
7467
        "https://hub.example/o/n"
7468
    );
7469
    assert!(crate::protocol::stored_url("file://x").starts_with("file:///"));
7470
    assert!(crate::protocol::stored_url("dir://x").starts_with("dir:///"));
7471
    // A bucket is kept as written: it is not a path.
7472
    assert_eq!(
7473
        crate::protocol::stored_url("s3://bucket/prefix?profile=p"),
7474
        "s3://bucket/prefix?profile=p"
7475
    );
7476
    let url = root.join("origin").to_string_lossy().to_string();
7477
    let b = Repo::clone(&url, &root.join("b")).unwrap();
7478
    assert_eq!(b.config.remotes["origin"], url);
7479
    b.fetch("origin").unwrap();
7480
}
7481
7482
/// oxygen#60 and #61: a workspace added on a bookmark is on that bookmark,
7483
/// and gets its subrepos at their pins from this workspace's copies, with
7484
/// their remotes pointing where the subrepos come from.
7485
#[test]
7486
fn a_workspace_added_on_a_bookmark_is_on_it_with_its_subrepos() {
7487
    hermetic();
7488
    let dir = tempfile::tempdir().unwrap();
7489
    let root = dir.path();
7490
    Repo::init(&root.join("lib-origin")).unwrap();
7491
    let lib_url = root.join("lib-origin").to_string_lossy().to_string();
7492
    let lib = Repo::clone(&lib_url, &root.join("lib"))
7493
        .unwrap()
7494
        .with_home(root.join("home"));
7495
    write(&root.join("lib"), "lib.txt", b"v1\n");
7496
    let l1 = lib.commit("lib v1", &[]).unwrap();
7497
    assert!(lib.push("origin", false).unwrap()[0].ok);
7498
7499
    let app_dir = root.join("app");
7500
    let app = Repo::init(&app_dir).unwrap().with_home(root.join("home"));
7501
    write(&app_dir, "main.txt", b"app\n");
7502
    app.submodule_add(&lib_url, "libs/lib", None).unwrap();
7503
    app.commit("app with lib", &[]).unwrap();
7504
    // A second bookmark, and the main workspace on another.
7505
    app.bookmark_create("develop", None).unwrap();
7506
    app.bookmark_create("feature", None).unwrap();
7507
    let mut app = app;
7508
    app.bookmark_switch("feature", false).unwrap();
7509
    assert_eq!(app.config.bookmark, "feature");
7510
7511
    // The library's origin goes away: the subrepo must come from here.
7512
    std::fs::rename(root.join("lib-origin"), root.join("lib-origin-gone")).unwrap();
7513
    let heads = app.resolve_heads("develop").unwrap();
7514
    let ws = app
7515
        .workspace_add_on(&root.join("ws"), Some(&heads), Some("develop"))
7516
        .unwrap();
7517
    assert_eq!(
7518
        ws.config.bookmark, "develop",
7519
        "the new workspace is on develop"
7520
    );
7521
    assert_eq!(
7522
        app.config.bookmark, "feature",
7523
        "and this one stays on its own"
7524
    );
7525
    let sub = Repo::open(&root.join("ws/libs/lib")).unwrap();
7526
    assert_eq!(
7527
        sub.config.remotes["origin"], lib_url,
7528
        "its origin is the subrepo's URL"
7529
    );
7530
    assert_eq!(sub.bookmark_heads().unwrap(), vec![l1], "at its pin");
7531
    assert_eq!(
7532
        std::fs::read(root.join("ws/libs/lib/lib.txt")).unwrap(),
7533
        b"v1\n"
7534
    );
7535
}
7536
7537
/// Revsets (docs/revset_query_language.md): symbols, relations, set
7538
/// operators and the predicates, over a small graph with two heads and
7539
/// a rename.
7540
#[test]
7541
fn revsets_select_changes_by_relation_author_text_date_and_path() {
7542
    hermetic();
7543
    let dir = tempfile::tempdir().unwrap();
7544
    let root = dir.path();
7545
    let mut repo = Repo::init(root).unwrap().with_home(root.join("home"));
7546
    repo.create_identity("Ada", "[email protected]", IdentityScope::User)
7547
        .unwrap();
7548
    write(root, "src/a.rs", b"one\n");
7549
    let a = repo.commit("first: add a", &[]).unwrap();
7550
    write(root, "src/a.rs", b"one\ntwo\n");
7551
    let b = repo.commit("second: grow a", &[]).unwrap();
7552
    // A second head, independent of b: a new file on top of a.
7553
    repo.checkout(&[a], false, "checkout a").unwrap();
7554
    write(root, "docs/notes.md", b"notes\n");
7555
    let c = repo.commit("third: notes", &[]).unwrap();
7556
    // Back to both heads, then rename a.rs: the node keeps its identity.
7557
    repo.checkout(&repo.bookmark_heads().unwrap(), false, "checkout main")
7558
        .unwrap();
7559
    fs::remove_file(root.join("src/a.rs")).unwrap();
7560
    write(root, "src/z.rs", b"one\ntwo\n");
7561
    let d = repo.commit("fourth: rename a to z", &[]).unwrap();
7562
    let wc = repo.working_copy().unwrap().0;
7563
    // A saved revset is checked when set.
7564
    repo.set_user_config("revset.mine", "author(me) & ::main")
7565
        .unwrap();
7566
    assert!(repo.set_user_config("revset.bad", "a &").is_err());
7567
    let set = |src: &str| -> Vec<ChangeHash> {
7568
        let mut v = repo.revset(src).unwrap().hashes;
7569
        v.sort();
7570
        v
7571
    };
7572
    let sorted = |hs: &[ChangeHash]| -> Vec<ChangeHash> {
7573
        let mut v = hs.to_vec();
7574
        v.sort();
7575
        v
7576
    };
7577
7578
    // Changes commute: a new file depends on nothing and the rename on the
7579
    // file's creation, so the graph is a, b->a, d->a, c, and the working
7580
    // copy on the three heads b, c, d.
7581
    let heads = sorted(&repo.bookmark_heads().unwrap());
7582
    let meta = |h: &ChangeHash| repo.store().get_change_meta(h).unwrap();
7583
    assert!(heads.contains(&d) && heads.contains(&c));
7584
    // Symbols and closures.
7585
    assert_eq!(set("main"), heads);
7586
    assert_eq!(set("::main"), sorted(&[a, b, c, d]));
7587
    assert_eq!(set("@"), vec![wc]);
7588
    assert_eq!(set("::@"), sorted(&[a, b, c, d, wc]));
7589
    assert_eq!(set(&format!("::#{}", b.short(12))), sorted(&[a, b]));
7590
    assert_eq!(set(&format!("#{}::", a.short(12))), sorted(&[a, b, d, wc]));
7591
    assert_eq!(
7592
        set(&format!("#{}::#{}", a.short(12), b.short(12))),
7593
        sorted(&[a, b])
7594
    );
7595
    // Ranges: what main has beyond b, and `..` forms.
7596
    assert_eq!(set(&format!("#{}..main", b.short(12))), sorted(&[c, d]));
7597
    assert_eq!(set(&format!("#{}..", c.short(12))), sorted(&[a, b, d, wc]));
7598
    assert_eq!(set("..main"), sorted(&[a, b, c, d]));
7599
    // Operators and precedence: ~ binds tighter than &, & than |.
7600
    assert_eq!(
7601
        set(&format!("::main ~ #{}", d.short(12))),
7602
        sorted(&[a, b, c])
7603
    );
7604
    assert_eq!(
7605
        set(&format!("::main & #{} | #{}", b.short(12), c.short(12))),
7606
        sorted(&[b, c])
7607
    );
7608
    assert_eq!(set("all() ~ ::main"), vec![wc]);
7609
    // Relations.
7610
    let mut head_deps: Vec<ChangeHash> = heads.iter().flat_map(|h| meta(h).deps).collect();
7611
    head_deps.sort();
7612
    head_deps.dedup();
7613
    assert_eq!(set("deps(main)"), head_deps);
7614
    let on_a: Vec<ChangeHash> = [b, c, d]
7615
        .into_iter()
7616
        .filter(|h| meta(h).deps.contains(&a))
7617
        .collect();
7618
    assert_eq!(set(&format!("dependents(#{})", a.short(12))), sorted(&on_a));
7619
    assert_eq!(set("heads(::main)"), heads);
7620
    assert_eq!(set("roots(::main)"), sorted(&[a, c]));
7621
    assert_eq!(
7622
        set(&format!(
7623
            "heads(#{} | #{} | #{})",
7624
            a.short(12),
7625
            b.short(12),
7626
            c.short(12)
7627
        )),
7628
        sorted(&[b, c])
7629
    );
7630
    assert_eq!(set("latest(::main, 1)"), vec![d]);
7631
    assert_eq!(set("kind(working-copy)"), vec![wc]);
7632
    assert_eq!(set("none()"), vec![]);
7633
    // Predicates: author by name, email, key prefix and `me`.
7634
    let key = repo.config.author_key.unwrap();
7635
    assert_eq!(set("author(ada) & ::main"), sorted(&[a, b, c, d]));
7636
    assert_eq!(set("author(\"[email protected]\") & ::main").len(), 4);
7637
    assert_eq!(set(&format!("author({}) & ::main", key.short(12))).len(), 4);
7638
    assert_eq!(set("author(me) & ::main").len(), 4);
7639
    assert_eq!(set("author(nobody)"), vec![]);
7640
    assert_eq!(set("description(notes)"), vec![c]);
7641
    assert_eq!(set("description(\"rename a\")"), vec![d]);
7642
    assert_eq!(set("date(-1h..) & ::main").len(), 4);
7643
    assert_eq!(set("date(..2000-01-01)"), vec![]);
7644
    // touches follows the node through the rename, in the current state.
7645
    assert_eq!(set("touches(\"src/z.rs\")"), sorted(&[a, b, d]));
7646
    assert_eq!(set("touches(\"src/**\") & ::main"), sorted(&[a, b, d]));
7647
    assert_eq!(set("touches(\"docs/*\")"), vec![c]);
7648
    assert_eq!(set("touches(\"nothing/*\")"), vec![]);
7649
    // Newest first in the result order.
7650
    assert_eq!(repo.revset("::main").unwrap().hashes[0], d);
7651
    // The saved revset, and errors that say what is wrong.
7652
    assert_eq!(set("mine()").len(), 4);
7653
    let e = repo.revset("nosuch()").unwrap_err().to_string();
7654
    assert!(e.contains("unknown function nosuch()"), "{e}");
7655
    let e = repo.revset("main &").unwrap_err().to_string();
7656
    assert!(e.contains("at character"), "{e}");
7657
    let e = repo.revset("zzzz").unwrap_err().to_string();
7658
    assert!(e.contains("no change matches"), "{e}");
7659
    let e = repo
7660
        .revset_with_budget("::main", std::time::Duration::ZERO)
7661
        .unwrap_err()
7662
        .to_string();
7663
    assert!(e.contains("budget"), "{e}");
7664
    // The log entries carry the bookmark's heads and the working copy.
7665
    let entries = repo.log_revset("::@").unwrap();
7666
    assert!(entries[0].is_working_copy && entries.iter().any(|e| e.is_head && e.hash == d));
7667
    // Trust predicates (§2.4): nothing is signed yet (core.sign = seal, no
7668
    // push); then a signed change, a tag, and a revocation.
7669
    assert_eq!(set("unsigned() & ::main"), sorted(&[a, b, c, d]));
7670
    assert_eq!(set("signed_by(me)"), vec![]);
7671
    repo.sign_change(&d).unwrap();
7672
    assert_eq!(set("signed_by(me)"), vec![d]);
7673
    assert_eq!(set("signed_by([email protected])"), vec![d]);
7674
    assert_eq!(set(&format!("signed_by({})", key.short(12))), vec![d]);
7675
    assert_eq!(set("unsigned() & ::main"), sorted(&[a, b, c]));
7676
    assert_eq!(set("delegated()"), vec![]);
7677
    assert_eq!(set("revoked()"), vec![]);
7678
    assert_eq!(set("attested(tag)"), vec![]);
7679
    repo.tag_create("v1", &[b], "first").unwrap();
7680
    assert_eq!(set("attested(tag)"), sorted(&[a, b]));
7681
    assert_eq!(set("attested(tag) & unsigned()"), sorted(&[a, b]));
7682
    assert_eq!(set("attested(receipt)"), vec![]);
7683
    assert_eq!(set("built(test)"), vec![]);
7684
    let e = repo.revset("attested(seal)").unwrap_err().to_string();
7685
    assert!(e.contains("tag, receipt or ref"), "{e}");
7686
    repo.revoke_identity(&key, "test").unwrap();
7687
    assert_eq!(set("revoked()"), vec![d]);
7688
    assert_eq!(set("signed_by(me) ~ revoked()"), vec![]);
7689
}
7690
7691
#[test]
7692
fn a_rotation_is_recorded_wherever_the_old_key_was_named() {
7693
    let dir = tempfile::tempdir().unwrap();
7694
    let root = dir.path();
7695
    let home = root.join("home");
7696
    // Ada's identity lives in the user file; repository `a` pins the same
7697
    // key in its own file, repository `b` names none.
7698
    let mut a = Repo::init(&root.join("a")).unwrap().with_home(&home);
7699
    let (key, _) = a
7700
        .create_identity("Ada", "[email protected]", IdentityScope::User)
7701
        .unwrap();
7702
    a.config.set("author.key", &key.to_hex()).unwrap();
7703
    a.save_config().unwrap();
7704
    let agent = SecretKey::generate().identity("Agent", "[email protected]", 1);
7705
    let r = a
7706
        .delegate_add(agent.clone(), crate::identity::Scope::CHANGES, None)
7707
        .unwrap();
7708
    assert_eq!(
7709
        read_config_file(&home.join("config.toml")).unwrap()["author.key"],
7710
        r.new.to_hex(),
7711
        "the user file follows"
7712
    );
7713
    assert_eq!(
7714
        read_config_file(&root.join("a/.oxy/config")).unwrap()["author.key"],
7715
        r.new.to_hex(),
7716
        "the pinning repository follows"
7717
    );
7718
    let b = Repo::init(&root.join("b")).unwrap().with_home(&home);
7719
    assert_eq!(
7720
        b.config.author_key,
7721
        Some(r.new),
7722
        "a checkout without a pin follows the user file"
7723
    );
7724
    // A repository-scoped identity leaves the user file alone.
7725
    let other_home = root.join("home2");
7726
    let mut c = Repo::init(&root.join("c")).unwrap().with_home(&other_home);
7727
    let (ck, _) = c
7728
        .create_identity("Cy", "[email protected]", IdentityScope::Repo)
7729
        .unwrap();
7730
    assert!(!other_home.join("config.toml").exists());
7731
    let r2 = c.rotate_identity().unwrap();
7732
    assert_ne!(r2.new, ck);
7733
    assert_eq!(
7734
        read_config_file(&root.join("c/.oxy/config")).unwrap()["author.key"],
7735
        r2.new.to_hex()
7736
    );
7737
    assert!(
7738
        !other_home.join("config.toml").exists(),
7739
        "a repository-scoped identity stays repository-scoped"
7740
    );
7741
    // Several delegates in one rotation; a repeat is refused.
7742
    let (d1, d2) = (
7743
        SecretKey::generate().identity("D1", "d1@x", 1),
7744
        SecretKey::generate().identity("D2", "d2@x", 1),
7745
    );
7746
    let r3 = c
7747
        .delegate_add_many(vec![d1.clone(), d2], crate::identity::Scope::CHANGES, None)
7748
        .unwrap();
7749
    assert_eq!(r3.identity.delegates.len(), 2);
7750
    assert!(c
7751
        .delegate_add(d1, crate::identity::Scope::CHANGES, None)
7752
        .is_err());
7753
}
7754
7755
/// Two unrelated histories that both add the same file, joined by two
7756
/// independent merges on two branches, then those branches merged: Git
7757
/// merges identical additions cleanly, and the import must too (#71,
7758
/// found in VS Code's history).
7759
#[test]
7760
fn git_import_joins_unrelated_histories_that_add_the_same_file() {
7761
    // Batches of one: every merge renders apart from the state, where a
7762
    // file whose graph the state had built came out empty (#71).
7763
    crate::repo::git::set_merge_batch_for_tests(Some(1));
7764
    hermetic();
7765
    if std::process::Command::new("git")
7766
        .arg("--version")
7767
        .output()
7768
        .is_err()
7769
    {
7770
        eprintln!("git not installed; skipping");
7771
        return;
7772
    }
7773
    let dir = tempfile::tempdir().unwrap();
7774
    let root = dir.path();
7775
    let g = root.join("src.git");
7776
    fs::create_dir_all(&g).unwrap();
7777
    let git = |args: &[&str]| -> String {
7778
        let out = std::process::Command::new("git")
7779
            .arg("-C")
7780
            .arg(&g)
7781
            .args([
7782
                "-c",
7783
                "user.name=Grace",
7784
                "-c",
7785
                "[email protected]",
7786
                "-c",
7787
                "commit.gpgsign=false",
7788
            ])
7789
            .args(args)
7790
            .output()
7791
            .unwrap();
7792
        assert!(
7793
            out.status.success(),
7794
            "git {args:?}: {}",
7795
            String::from_utf8_lossy(&out.stderr)
7796
        );
7797
        String::from_utf8_lossy(&out.stdout).trim().to_string()
7798
    };
7799
    let text = b"/* header */\nconst a = 1;\nconst b = 2;\n";
7800
    // History A: main.
7801
    git(&["init", "-q", "-b", "main"]);
7802
    write(&g, "gulpfile.js", text);
7803
    write(&g, "a.txt", b"a\n");
7804
    git(&["add", "."]);
7805
    git(&["commit", "-q", "-m", "A root"]);
7806
    // History B: an unrelated root adding the same file, identical.
7807
    git(&["checkout", "-q", "--orphan", "fork"]);
7808
    git(&["rm", "-q", "-r", "--cached", "."]);
7809
    for f in ["gulpfile.js", "a.txt"] {
7810
        let _ = fs::remove_file(g.join(f));
7811
    }
7812
    write(&g, "gulpfile.js", text);
7813
    write(&g, "b.txt", b"b\n");
7814
    git(&["add", "."]);
7815
    git(&["commit", "-q", "-m", "B root"]);
7816
    // Two branches from main, each joining B on its own.
7817
    git(&["checkout", "-q", "-b", "one", "main"]);
7818
    git(&[
7819
        "merge",
7820
        "-q",
7821
        "--no-ff",
7822
        "--allow-unrelated-histories",
7823
        "-m",
7824
        "join on one",
7825
        "fork",
7826
    ]);
7827
    git(&["checkout", "-q", "-b", "two", "main"]);
7828
    write(&g, "a.txt", b"a\ntwo\n");
7829
    git(&["commit", "-q", "-am", "work on two"]);
7830
    git(&[
7831
        "merge",
7832
        "-q",
7833
        "--no-ff",
7834
        "--allow-unrelated-histories",
7835
        "-m",
7836
        "join on two",
7837
        "fork",
7838
    ]);
7839
    // Then the two joins meet, and the file is reformatted after.
7840
    git(&["checkout", "-q", "main"]);
7841
    git(&["merge", "-q", "--no-ff", "-m", "merge one", "one"]);
7842
    git(&["merge", "-q", "--no-ff", "-m", "merge two", "two"]);
7843
    write(
7844
        &g,
7845
        "gulpfile.js",
7846
        b"/* header */\nconst a = 1;\nconst b = 3;\n",
7847
    );
7848
    git(&["commit", "-q", "-am", "after"]);
7849
7850
    let dest = root.join("dest");
7851
    let repo = Repo::init(&dest).unwrap().with_home(root.join("home"));
7852
    repo.import_git(&g, "main").unwrap();
7853
    let v = repo.verify_git_import(&g, "main").unwrap();
7854
    assert!(v.mismatches.is_empty(), "{:?}", v.mismatches);
7855
    assert_eq!(
7856
        fs::read(dest.join("gulpfile.js")).unwrap(),
7857
        b"/* header */\nconst a = 1;\nconst b = 3;\n"
7858
    );
7859
}
7860
7861
/// As above, but the two joins keep different copies (each branch had a
7862
/// different version when it joined), and later work edits each copy:
7863
/// the shape of VS Code's c67ef57cda90 (#71).
7864
#[test]
7865
fn git_import_joins_where_each_join_kept_a_different_copy() {
7866
    // Batches of one: every merge renders apart from the state, where a
7867
    // file whose graph the state had built came out empty (#71).
7868
    crate::repo::git::set_merge_batch_for_tests(Some(1));
7869
    hermetic();
7870
    if std::process::Command::new("git")
7871
        .arg("--version")
7872
        .output()
7873
        .is_err()
7874
    {
7875
        eprintln!("git not installed; skipping");
7876
        return;
7877
    }
7878
    let dir = tempfile::tempdir().unwrap();
7879
    let root = dir.path();
7880
    let g = root.join("src.git");
7881
    fs::create_dir_all(&g).unwrap();
7882
    let run = |args: &[&str]| {
7883
        std::process::Command::new("git")
7884
            .arg("-C")
7885
            .arg(&g)
7886
            .args([
7887
                "-c",
7888
                "user.name=Grace",
7889
                "-c",
7890
                "[email protected]",
7891
                "-c",
7892
                "commit.gpgsign=false",
7893
            ])
7894
            .args(args)
7895
            .output()
7896
            .unwrap()
7897
    };
7898
    let git = |args: &[&str]| -> String {
7899
        let out = run(args);
7900
        assert!(
7901
            out.status.success(),
7902
            "git {args:?}: {}",
7903
            String::from_utf8_lossy(&out.stderr)
7904
        );
7905
        String::from_utf8_lossy(&out.stdout).trim().to_string()
7906
    };
7907
    git(&["init", "-q", "-b", "main"]);
7908
    write(
7909
        &g,
7910
        "gulpfile.js",
7911
        b"/* header */\nconst a = 1;\nconst b = 2;\n",
7912
    );
7913
    git(&["add", "."]);
7914
    git(&["commit", "-q", "-m", "A root"]);
7915
    write(
7916
        &g,
7917
        "gulpfile.js",
7918
        b"/* header */\nconst a = 1;\n\nconst b = 2;\n",
7919
    );
7920
    git(&["commit", "-q", "-am", "whitespace"]);
7921
    git(&["checkout", "-q", "--orphan", "fork"]);
7922
    git(&["rm", "-q", "-r", "--cached", "."]);
7923
    let _ = fs::remove_file(g.join("gulpfile.js"));
7924
    write(
7925
        &g,
7926
        "gulpfile.js",
7927
        b"/* header */\nconst a = 1;\nconst b = 2;\nconst c = 3;\n",
7928
    );
7929
    git(&["add", "."]);
7930
    git(&["commit", "-q", "-m", "B root"]);
7931
    // Branch one joins B keeping main's copy; branch two keeps B's.
7932
    for (branch, keep) in [("one", "ours"), ("two", "theirs")] {
7933
        git(&["checkout", "-q", "-b", branch, "main"]);
7934
        let _ = run(&[
7935
            "merge",
7936
            "-q",
7937
            "--no-ff",
7938
            "--allow-unrelated-histories",
7939
            "-m",
7940
            "join",
7941
            "fork",
7942
        ]);
7943
        git(&["checkout", &format!("--{keep}"), "gulpfile.js"]);
7944
        git(&["add", "gulpfile.js"]);
7945
        git(&["commit", "-q", "-m", &format!("join on {branch}")]);
7946
    }
7947
    // Each branch then edits its copy.
7948
    git(&["checkout", "-q", "one"]);
7949
    write(
7950
        &g,
7951
        "gulpfile.js",
7952
        b"/* header */\nconst a = 1;\n\nconst b = 2;\n// tslint\n",
7953
    );
7954
    git(&["commit", "-q", "-am", "tslint on one"]);
7955
    git(&["checkout", "-q", "two"]);
7956
    write(
7957
        &g,
7958
        "gulpfile.js",
7959
        b"/* header */\nconst a = 1;\nconst b = 2;\nconst c = 3;\n// fmt\n",
7960
    );
7961
    write(&g, "extra.txt", b"x\n");
7962
    write(&g, "more.txt", b"m\n");
7963
    git(&["add", "."]);
7964
    git(&["commit", "-q", "-am", "fmt on two"]);
7965
    // They meet: resolved by hand.
7966
    git(&["checkout", "-q", "one"]);
7967
    let _ = run(&["merge", "-q", "--no-ff", "-m", "merge two", "two"]);
7968
    write(
7969
        &g,
7970
        "gulpfile.js",
7971
        b"/* header */\nconst a = 1;\nconst b = 2;\nconst c = 3;\n// tslint\n// fmt\n",
7972
    );
7973
    git(&["add", "gulpfile.js"]);
7974
    git(&["commit", "-q", "-m", "merge two into one"]);
7975
7976
    let dest = root.join("dest");
7977
    let repo = Repo::init(&dest).unwrap().with_home(root.join("home"));
7978
    repo.import_git(&g, "one").unwrap();
7979
    let v = repo.verify_git_import(&g, "one").unwrap();
7980
    assert!(v.mismatches.is_empty(), "{:?}", v.mismatches);
7981
}
7982
7983
/// oxygen#68: on a store that is not this disk's directory, the operation
7984
/// head is the store's reference record, moved by compare-and-swap. Two
7985
/// handles recording from the same head both get through, merged; a swap
7986
/// from a stale version is refused; a second repository cannot start on a
7987
/// store that already holds one.
7988
#[test]
7989
fn over_a_store_the_operation_head_moves_by_compare_and_swap() {
7990
    use crate::strata::{MemoryStore, Store as _};
7991
    let backend = std::sync::Arc::new(MemoryStore::new());
7992
    crate::store::TEST_BACKEND.with(|t| *t.borrow_mut() = Some(backend.clone()));
7993
    let dir = tempfile::tempdir().unwrap();
7994
    let a = Repo::init(dir.path()).unwrap();
7995
    assert!(
7996
        !dir.path().join(".oxy/ops/head").exists(),
7997
        "the head is not a file"
7998
    );
7999
    let (h0, op0) = a.head_op().unwrap();
8000
    let record = backend
8001
        .read_ref(HEAD_RECORD)
8002
        .unwrap()
8003
        .expect("the head is the store's record");
8004
    assert_eq!(String::from_utf8(record.0).unwrap(), h0.to_hex());
8005
8006
    let b = Repo::open(dir.path()).unwrap();
8007
    let state = a.store.put_state(&StateObject::new(vec![])).unwrap();
8008
    let mut va = op0.view.clone();
8009
    va.bookmarks.insert("from-a".into(), state);
8010
    let mut vb = op0.view.clone();
8011
    vb.bookmarks.insert("from-b".into(), state);
8012
    let rb = b.record_op(&[h0], "bookmark from-b", vb).unwrap();
8013
    assert_eq!(b.head_ref().unwrap(), rb);
8014
    // a recorded from h0 too: the head moved, so the two are merged.
8015
    let ra = a.record_op(&[h0], "bookmark from-a", va).unwrap();
8016
    let (head, op) = Repo::open(dir.path()).unwrap().head_op().unwrap();
8017
    assert_eq!(head, ra);
8018
    assert!(
8019
        op.command.ends_with("(merged with a concurrent operation)"),
8020
        "{}",
8021
        op.command
8022
    );
8023
    assert_eq!(op.parents, vec![rb, op.parents[1]]);
8024
    assert!(op.view.bookmarks.contains_key("from-a") && op.view.bookmarks.contains_key("from-b"));
8025
8026
    // A swap from a version that is no longer current moves nothing.
8027
    let (h, v) = a.read_head().unwrap();
8028
    assert!(b.swap_head(&rb, v.as_ref()).unwrap());
8029
    assert!(!a.swap_head(&h, v.as_ref()).unwrap(), "stale");
8030
    a.refresh().unwrap();
8031
    assert_eq!(a.head_ref().unwrap(), rb);
8032
8033
    let other = tempfile::tempdir().unwrap();
8034
    let err = Repo::init(other.path())
8035
        .err()
8036
        .expect("the store already holds a log")
8037
        .to_string();
8038
    assert!(
8039
        err.contains("already holds a repository's operation log"),
8040
        "{err}"
8041
    );
8042
    crate::store::TEST_BACKEND.with(|t| *t.borrow_mut() = None);
8043
}
8044
8045
/// oxygen#68: a repository kept on a store (`storage.url`) holds its
8046
/// objects and operation head there, with `.oxy/cache` in front: it works
8047
/// as one on disk does, reopens, and survives losing its cache.
8048
#[test]
8049
fn a_repository_runs_on_a_store_with_a_cache_in_front() {
8050
    hermetic();
8051
    if std::env::var_os("OXY_STORE_BACKEND").is_some() {
8052
        return;
8053
    }
8054
    let dir = tempfile::tempdir().unwrap();
8055
    let (root, bucket) = (dir.path().join("work"), dir.path().join("bucket"));
8056
    let url = format!("dir://{}", bucket.display());
8057
    let repo = Repo::init_on(&root, [7; 16], Some(&url)).unwrap();
8058
    assert_eq!(repo.config.storage_url.as_deref(), Some(url.as_str()));
8059
    write(&root, "a.txt", b"one\n");
8060
    let h1 = repo.commit("First", &[]).unwrap();
8061
    write(&root, "a.txt", b"one\ntwo\n");
8062
    let h2 = repo.commit("Second", &[]).unwrap();
8063
    assert!(
8064
        !root.join(".oxy/ops/head").exists(),
8065
        "the head is in the store"
8066
    );
8067
    assert!(bucket.join("ops/head").is_file());
8068
    assert!(root.join(".oxy/cache").is_dir());
8069
    drop(repo);
8070
8071
    // Reopened, and again with no cache at all: everything comes from the store.
8072
    for drop_cache in [false, true] {
8073
        if drop_cache {
8074
            std::fs::remove_dir_all(root.join(".oxy/cache")).unwrap();
8075
        }
8076
        let repo = Repo::open(&root).unwrap();
8077
        let log: Vec<String> = repo
8078
            .op_log()
8079
            .unwrap()
8080
            .into_iter()
8081
            .map(|(_, op)| op.command)
8082
            .collect();
8083
        assert!(log.len() >= 3, "{log:?}");
8084
        assert_eq!(repo.store().get_change(&h1).unwrap().message, "First");
8085
        let heads = repo
8086
            .store()
8087
            .get_state(&repo.view().unwrap().bookmarks["main"])
8088
            .unwrap()
8089
            .heads;
8090
        assert_eq!(heads, vec![h2]);
8091
        assert_eq!(
8092
            repo.load_state(&heads).unwrap().materialize().files.len(),
8093
            1
8094
        );
8095
    }
8096
8097
    // A second repository cannot start on the same store.
8098
    let err = Repo::init_on(&dir.path().join("other"), [8; 16], Some(&url))
8099
        .err()
8100
        .unwrap()
8101
        .to_string();
8102
    assert!(
8103
        err.contains("already holds a repository's operation log"),
8104
        "{err}"
8105
    );
8106
    let err = Repo::init_on(&dir.path().join("third"), [9; 16], Some("nope://x"))
8107
        .err()
8108
        .unwrap()
8109
        .to_string();
8110
    assert!(err.contains("cannot open that kind of store"), "{err}");
8111
}
8112
8113
/// oxygen#75: the prompt's quick check agrees with status in a repository
8114
/// with a subrepo: clean after a commit, dirty when the subrepo moves to
8115
/// another state, clean again once that pin is committed. (It compared the
8116
/// subrepo's directory as if it were a file, so it was always dirty.)
8117
#[test]
8118
fn the_quick_dirty_check_compares_a_subrepo_by_its_pin() {
8119
    hermetic();
8120
    let dir = tempfile::tempdir().unwrap();
8121
    let root = dir.path();
8122
    let _lib_origin = Repo::init(&root.join("lib-origin")).unwrap();
8123
    let lib_url = root.join("lib-origin").to_string_lossy().to_string();
8124
    let lib = Repo::clone(&lib_url, &root.join("lib"))
8125
        .unwrap()
8126
        .with_home(root.join("home"));
8127
    write(&root.join("lib"), "lib.txt", b"v1\n");
8128
    lib.commit("lib v1", &[]).unwrap();
8129
    assert!(lib.push("origin", false).unwrap()[0].ok);
8130
    let app_dir = root.join("app");
8131
    let app = Repo::init(&app_dir).unwrap().with_home(root.join("home"));
8132
    write(&app_dir, "main.txt", b"app\n");
8133
    app.submodule_add(&lib_url, "libs/lib", None).unwrap();
8134
    app.commit("app with lib", &[]).unwrap();
8135
    // Out of the racy window, so the stat-only path decides.
8136
    std::thread::sleep(std::time::Duration::from_millis(2100));
8137
    let reopen = || Repo::open(&app_dir).unwrap();
8138
    assert_eq!(
8139
        reopen().quick_dirty().unwrap(),
8140
        Some(false),
8141
        "clean, as status says"
8142
    );
8143
    let nested = Repo::open(&app_dir.join("libs/lib")).unwrap();
8144
    write(&app_dir.join("libs/lib"), "lib.txt", b"v2\n");
8145
    nested.commit("lib v2", &[]).unwrap();
8146
    assert_eq!(
8147
        reopen().quick_dirty().unwrap(),
8148
        Some(true),
8149
        "the subrepo moved"
8150
    );
8151
    reopen().commit("pin lib v2", &[]).unwrap();
8152
    std::thread::sleep(std::time::Duration::from_millis(2100));
8153
    assert_eq!(
8154
        reopen().quick_dirty().unwrap(),
8155
        Some(false),
8156
        "the new pin is committed"
8157
    );
8158
}
8159
8160
#[test]
8161
fn a_module_entry_that_was_never_added_is_reported_as_unpinned() {
8162
    // oxygen#72: a .oxymodules section with no subrepo behind it.
8163
    hermetic();
8164
    let dir = tempfile::tempdir().unwrap();
8165
    let root = dir.path();
8166
    let _lib_origin = Repo::init(&root.join("lib-origin")).unwrap();
8167
    let lib_url = root.join("lib-origin").to_string_lossy().to_string();
8168
    let lib = Repo::clone(&lib_url, &root.join("lib"))
8169
        .unwrap()
8170
        .with_home(root.join("home"));
8171
    write(&root.join("lib"), "lib.txt", b"v1\n");
8172
    lib.commit("lib v1", &[]).unwrap();
8173
    assert!(lib.push("origin", false).unwrap()[0].ok);
8174
    let app_dir = root.join("app");
8175
    let app = Repo::init(&app_dir).unwrap().with_home(root.join("home"));
8176
    write(
8177
        &app_dir,
8178
        ".oxymodules",
8179
        format!("[libs/lib]\nurl = {lib_url}\n").as_bytes(),
8180
    );
8181
    let unpinned = app.unpinned_modules().unwrap();
8182
    assert_eq!(unpinned.len(), 1);
8183
    assert_eq!(unpinned[0].0, "libs/lib");
8184
    assert_eq!(unpinned[0].1.url, lib_url);
8185
    assert!(app.submodule_update(true, &[]).unwrap().is_empty());
8186
    app.submodule_add(&lib_url, "libs/lib", None).unwrap();
8187
    assert!(app.unpinned_modules().unwrap().is_empty(), "added now");
8188
}
8189
8190
#[test]
8191
fn the_bookmark_revset_function_names_only_bookmarks() {
8192
    // oxygen#73: bookmark(NAME) is a bookmark's heads, never a tag or prefix.
8193
    hermetic();
8194
    let dir = tempfile::tempdir().unwrap();
8195
    let repo = Repo::init(dir.path()).unwrap();
8196
    write(dir.path(), "a.txt", b"a\n");
8197
    let a = repo.commit("A", &[]).unwrap();
8198
    write(dir.path(), "b.txt", b"b\n");
8199
    let b = repo.commit("B", &[]).unwrap();
8200
    let mut heads = repo.revset("bookmark(main)").unwrap().hashes;
8201
    heads.sort();
8202
    let mut want = repo.bookmark_heads().unwrap();
8203
    want.sort();
8204
    assert_eq!(heads, want);
8205
    assert!(heads.contains(&b));
8206
    assert_eq!(repo.revset("main").unwrap().hashes.len(), heads.len());
8207
    // A change prefix is a symbol, not a bookmark.
8208
    let prefix = repo.store().get_change_meta(&a).unwrap().change_id.short(8);
8209
    assert!(repo.revset(&prefix).is_ok());
8210
    let e = repo
8211
        .revset(&format!("bookmark({prefix})"))
8212
        .unwrap_err()
8213
        .to_string();
8214
    assert!(e.contains("no such bookmark"), "{e}");
8215
}
8216
8217
#[test]
8218
fn carrying_work_over_a_subrepo_already_at_the_target_pin_is_no_conflict() {
8219
    // oxygen#74: a stale state with .oxymodules but no pin, a newer one
8220
    // pinning the subrepo, and the nested repository on disk at that pin.
8221
    hermetic();
8222
    let dir = tempfile::tempdir().unwrap();
8223
    let root = dir.path();
8224
    let _lib_origin = Repo::init(&root.join("lib-origin")).unwrap();
8225
    let lib_url = root.join("lib-origin").to_string_lossy().to_string();
8226
    let lib = Repo::clone(&lib_url, &root.join("lib"))
8227
        .unwrap()
8228
        .with_home(root.join("home"));
8229
    write(&root.join("lib"), "lib.txt", b"v1\n");
8230
    lib.commit("lib v1", &[]).unwrap();
8231
    assert!(lib.push("origin", false).unwrap()[0].ok);
8232
    let app_dir = root.join("app");
8233
    let app = Repo::init(&app_dir).unwrap().with_home(root.join("home"));
8234
    write(&app_dir, "main.txt", b"app\n");
8235
    app.submodule_add(&lib_url, "libs/lib", None).unwrap();
8236
    // The stale state: registered in .oxymodules, never pinned.
8237
    fs::rename(app_dir.join("libs/lib"), root.join("aside")).unwrap();
8238
    app.commit("initial", &[]).unwrap();
8239
    let stale = app.bookmark_heads().unwrap();
8240
    fs::rename(root.join("aside"), app_dir.join("libs/lib")).unwrap();
8241
    app.commit("pin lib", &[]).unwrap();
8242
    let newer = app.bookmark_heads().unwrap();
8243
    app.checkout(&stale, false, "test").unwrap();
8244
    write(&app_dir, "notes.txt", b"mine\n");
8245
    let (_, carried) = app.checkout_carry(&newer, "main", "test").unwrap();
8246
    assert_eq!(carried, vec!["notes.txt".to_string()]);
8247
    assert!(app_dir.join("notes.txt").exists());
8248
}
8249
8250
#[test]
8251
fn a_bookmark_only_behind_its_remote_catches_up() {
8252
    // oxygen#74: switch takes the remote's state rather than a stale one.
8253
    hermetic();
8254
    let dir = tempfile::tempdir().unwrap();
8255
    let root = dir.path();
8256
    let _origin = Repo::init(&root.join("origin")).unwrap();
8257
    let url = root.join("origin").to_string_lossy().to_string();
8258
    let one = Repo::clone(&url, &root.join("one"))
8259
        .unwrap()
8260
        .with_home(root.join("home"));
8261
    write(&root.join("one"), "a.txt", b"a\n");
8262
    one.commit("A", &[]).unwrap();
8263
    assert!(one.push("origin", false).unwrap()[0].ok);
8264
    let two = Repo::clone(&url, &root.join("two"))
8265
        .unwrap()
8266
        .with_home(root.join("home"));
8267
    write(&root.join("two"), "b.txt", b"b\n");
8268
    two.commit("B", &[]).unwrap();
8269
    assert!(two.push("origin", false).unwrap()[0].ok);
8270
    assert_eq!(one.catch_up_bookmark("main").unwrap(), None, "not fetched");
8271
    one.fetch("origin").unwrap();
8272
    assert_eq!(one.catch_up_bookmark("main").unwrap(), Some(1));
8273
    assert_eq!(one.bookmarks().unwrap()[0].behind, Some(0));
8274
    // Local work the remote lacks: left alone.
8275
    write(&root.join("one"), "c.txt", b"c\n");
8276
    one.commit("C", &[]).unwrap();
8277
    write(&root.join("two"), "d.txt", b"d\n");
8278
    two.commit("D", &[]).unwrap();
8279
    assert!(two.push("origin", false).unwrap()[0].ok);
8280
    one.fetch("origin").unwrap();
8281
    assert_eq!(one.catch_up_bookmark("main").unwrap(), None);
8282
}
8283
8284
#[test]
8285
fn a_bookmark_is_compared_with_a_remote_that_has_it_when_there_is_no_origin() {
8286
    // oxygen#83: remotes earth and gcs, origin removed.
8287
    hermetic();
8288
    let dir = tempfile::tempdir().unwrap();
8289
    let root = dir.path();
8290
    let _up = Repo::init(&root.join("up")).unwrap();
8291
    let url = root.join("up").to_string_lossy().to_string();
8292
    let other = Repo::clone(&url, &root.join("other"))
8293
        .unwrap()
8294
        .with_home(root.join("home"));
8295
    write(&root.join("other"), "a.txt", b"a\n");
8296
    other.commit("a", &[]).unwrap();
8297
    assert!(other.push("origin", false).unwrap()[0].ok);
8298
    let mut one = Repo::clone(&url, &root.join("one"))
8299
        .unwrap()
8300
        .with_home(root.join("home"));
8301
    one.config.set("remote.earth.url", &url).unwrap();
8302
    one.config.set("remote.gcs.url", &url).unwrap();
8303
    one.config.set("remote.origin.url", "").unwrap();
8304
    one.save_config().unwrap();
8305
    write(&root.join("other"), "b.txt", b"b\n");
8306
    other.commit("b", &[]).unwrap();
8307
    assert!(other.push("origin", false).unwrap()[0].ok);
8308
    one.fetch("earth").unwrap();
8309
    let b = one
8310
        .bookmarks()
8311
        .unwrap()
8312
        .into_iter()
8313
        .find(|b| b.name == "main")
8314
        .unwrap();
8315
    assert_eq!(
8316
        (b.remote.as_deref(), b.behind),
8317
        (Some("earth"), Some(1)),
8318
        "a stale origin copy is not used"
8319
    );
8320
    assert_eq!(
8321
        one.default_remote(),
8322
        "origin",
8323
        "no default chosen among several"
8324
    );
8325
    let e = one.pull(&one.default_remote()).unwrap_err().to_string();
8326
    assert!(e.contains("earth, gcs") && e.contains("core.remote"), "{e}");
8327
    one.config.set("core.remote", "earth").unwrap();
8328
    assert_eq!(one.default_remote(), "earth");
8329
}
8330
8331
#[test]
8332
fn a_missing_author_identity_says_how_to_fix_it() {
8333
    // oxygen#82: an agent home's author.key naming an identity the
8334
    // repository does not hold.
8335
    hermetic();
8336
    let dir = tempfile::tempdir().unwrap();
8337
    let mut repo = Repo::init(dir.path()).unwrap();
8338
    let missing = KeyId::from_hex(&"ab".repeat(32)).unwrap();
8339
    repo.config.set("author.key", &missing.to_hex()).unwrap();
8340
    let e = repo.identity(&missing).unwrap_err().to_string();
8341
    assert!(
8342
        e.contains("this repository has no identity") && e.contains("oxy config author.key"),
8343
        "{e}"
8344
    );
8345
    assert!(e.contains("this repository's config"), "{e}");
8346
}
8347
8348
#[test]
8349
fn a_working_copy_behind_its_bookmark_is_flagged_and_pull_brings_it_up() {
8350
    // oxygen#89 (supermarioland, 2026-10-09): the bookmark moved on without
8351
    // the working copy, a pull with nothing new left it there, and status
8352
    // said "clean".
8353
    hermetic();
8354
    let dir = tempfile::tempdir().unwrap();
8355
    let root = dir.path();
8356
    let _up = Repo::init(&root.join("up")).unwrap();
8357
    let url = root.join("up").to_string_lossy().to_string();
8358
    let other = Repo::clone(&url, &root.join("other"))
8359
        .unwrap()
8360
        .with_home(root.join("home"));
8361
    write(&root.join("other"), "a.txt", b"a\n");
8362
    other.commit("a", &[]).unwrap();
8363
    assert!(other.push("origin", false).unwrap()[0].ok);
8364
    let one = Repo::clone(&url, &root.join("one"))
8365
        .unwrap()
8366
        .with_home(root.join("home"));
8367
    write(&root.join("other"), "b.txt", b"b\n");
8368
    other.commit("b", &[]).unwrap();
8369
    assert!(other.push("origin", false).unwrap()[0].ok);
8370
    one.fetch("origin").unwrap();
8371
    // The bookmark moves; the working copy does not.
8372
    let theirs = one.resolve_heads("origin/main").unwrap();
8373
    one.bookmark_set("main", &theirs).unwrap();
8374
    assert!(!root.join("one/b.txt").exists());
8375
    assert_eq!(one.working_copy_behind().unwrap(), Some(1));
8376
    let r = one.pull("origin").unwrap();
8377
    assert!(
8378
        !r.changed && r.checked_out,
8379
        "nothing new, but the working copy caught up"
8380
    );
8381
    assert!(root.join("one/b.txt").exists());
8382
    assert_eq!(one.working_copy_behind().unwrap(), None);
8383
}
8384
8385
#[test]
8386
fn touched_nodes_cache_answers_as_the_changes_do() {
8387
    hermetic();
8388
    let dir = tempfile::tempdir().unwrap();
8389
    let repo = Repo::init(dir.path()).unwrap();
8390
    write(dir.path(), "a.txt", b"one\n");
8391
    write(dir.path(), "b.txt", b"x\n");
8392
    repo.snapshot("t").unwrap();
8393
    let c1 = repo.commit("first", &[]).unwrap();
8394
    write(dir.path(), "b.txt", b"y\n");
8395
    repo.snapshot("t").unwrap();
8396
    repo.commit("b only", &[]).unwrap();
8397
    fs::rename(dir.path().join("a.txt"), dir.path().join("c.txt")).unwrap();
8398
    write(dir.path(), "c.txt", b"one\ntwo\n");
8399
    repo.snapshot("t").unwrap();
8400
    let c3 = repo.commit("rename and edit", &[]).unwrap();
8401
    // Uncommitted work, so the working copy touches a file too.
8402
    write(dir.path(), "c.txt", b"one\ntwo\nthree\n");
8403
    repo.snapshot("t").unwrap();
8404
8405
    let path = dir.path().join(".oxy/index/touched");
8406
    let hashes = |es: Vec<LogEntry>| es.iter().map(|e| e.hash).collect::<Vec<_>>();
8407
    let cold = hashes(repo.log_for_path("c.txt").unwrap());
8408
    assert!(path.exists(), "the first query writes the cache");
8409
    let warm = hashes(repo.log_for_path("c.txt").unwrap());
8410
    assert_eq!(cold, warm, "the cache answers as the changes do");
8411
    let (wc, _) = repo.working_copy().unwrap();
8412
    assert_eq!(
8413
        cold,
8414
        vec![wc, c3, c1],
8415
        "renames followed, the working copy included"
8416
    );
8417
8418
    // Working-copy changes are not kept: they are replaced by every snapshot.
8419
    let cached = super::touched::read_touched_for_test(&fs::read(&path).unwrap()).unwrap();
8420
    assert!(!cached.contains(&wc), "a working-copy change is not cached");
8421
    assert!(cached.contains(&c1) && cached.contains(&c3));
8422
8423
    // A damaged cache is ignored, not trusted.
8424
    let mut bytes = fs::read(&path).unwrap();
8425
    let last = bytes.len() - 40;
8426
    bytes[last] ^= 1;
8427
    fs::write(&path, &bytes).unwrap();
8428
    assert_eq!(hashes(repo.log_for_path("c.txt").unwrap()), cold);
8429
    let touches = repo.log_revset("touches(\"c.txt\") ~ @").unwrap();
8430
    assert_eq!(hashes(touches), vec![c3, c1]);
8431
}
8432
8433
/// oxygen#88 (vscode 9ab2056393c8): two lines of history that each move a
8434
/// file back where it was leave two placements at one place, which the
8435
/// tree shows as one file. Removing it, and then its directory, retires
8436
/// both, so no copy is left under a directory that is gone.
8437
#[test]
8438
fn git_import_removes_every_copy_of_a_file_at_one_place() {
8439
    hermetic();
8440
    if std::process::Command::new("git")
8441
        .arg("--version")
8442
        .output()
8443
        .is_err()
8444
    {
8445
        eprintln!("git not installed; skipping");
8446
        return;
8447
    }
8448
    let dir = tempfile::tempdir().unwrap();
8449
    let root = dir.path();
8450
    let g = root.join("src.git");
8451
    fs::create_dir_all(&g).unwrap();
8452
    let git = |args: &[&str]| {
8453
        let out = std::process::Command::new("git")
8454
            .arg("-C")
8455
            .arg(&g)
8456
            .args([
8457
                "-c",
8458
                "user.name=Grace",
8459
                "-c",
8460
                "[email protected]",
8461
                "-c",
8462
                "commit.gpgsign=false",
8463
            ])
8464
            .args(args)
8465
            .output()
8466
            .unwrap();
8467
        assert!(
8468
            out.status.success(),
8469
            "git {args:?}: {}",
8470
            String::from_utf8_lossy(&out.stderr)
8471
        );
8472
    };
8473
    git(&["init", "-q", "-b", "main"]);
8474
    write(&g, "d/list.txt", b"one\ntwo\nthree\nfour\n");
8475
    write(&g, "keep.txt", b"k\n");
8476
    git(&["add", "."]);
8477
    git(&["commit", "-qm", "base"]);
8478
    fs::create_dir_all(g.join("d/sub")).unwrap();
8479
    git(&["mv", "d/list.txt", "d/sub/list.txt"]);
8480
    git(&["commit", "-qm", "into sub"]);
8481
    git(&["checkout", "-qb", "side"]);
8482
    git(&["mv", "d/sub/list.txt", "d/list.txt"]);
8483
    git(&["commit", "-qm", "back, on side"]);
8484
    git(&["checkout", "-q", "main"]);
8485
    git(&["mv", "d/sub/list.txt", "d/list.txt"]);
8486
    git(&["commit", "-qm", "back, on main"]);
8487
    git(&["merge", "-q", "--no-edit", "side"]);
8488
    git(&["rm", "-rq", "d"]);
8489
    git(&["commit", "-qm", "d goes"]);
8490
8491
    let repo = Repo::init(&root.join("o")).unwrap();
8492
    repo.import_git(&g, "main").unwrap();
8493
    let v = repo.verify_git_import(&g, "main").unwrap();
8494
    assert!(v.mismatches.is_empty(), "{:?}", v.mismatches);
8495
    let st = repo
8496
        .load_state_history(&repo.bookmark_heads().unwrap())
8497
        .unwrap();
8498
    let view = st.tree().view();
8499
    assert!(view.conflicts.is_empty(), "{:?}", view.conflicts);
8500
    assert_eq!(view.entries.keys().collect::<Vec<_>>(), vec!["keep.txt"]);
8501
}
8502
8503
/// oxygen#94: a state index's file histories are read, and checked by
8504
/// their own hashes, only when a file is built. One found damaged is an
8505
/// error that says so, the index is removed, and the next read rebuilds it.
8506
#[test]
8507
fn a_damaged_file_history_in_the_state_index_is_rebuilt() {
8508
    hermetic();
8509
    let dir = tempfile::tempdir().unwrap();
8510
    let repo = Repo::init(dir.path()).unwrap();
8511
    for i in 0..6 {
8512
        write(
8513
            dir.path(),
8514
            &format!("f{i}.txt"),
8515
            format!("one {i}\n").as_bytes(),
8516
        );
8517
    }
8518
    repo.snapshot("t").unwrap();
8519
    repo.commit("first", &[]).unwrap();
8520
    for i in 0..6 {
8521
        write(
8522
            dir.path(),
8523
            &format!("f{i}.txt"),
8524
            format!("one {i}\ntwo\n").as_bytes(),
8525
        );
8526
    }
8527
    repo.snapshot("t").unwrap();
8528
    repo.commit("second", &[]).unwrap();
8529
    let want: Vec<Vec<u8>> = (0..6)
8530
        .map(|i| format!("one {i}\ntwo\n").into_bytes())
8531
        .collect();
8532
    // The index of the working copy's base, holding every file's history
8533
    // (a few changes behind, an index is replayed onto, not rewritten).
8534
    let (_, wc) = repo.working_copy().unwrap();
8535
    let base = repo.load_state_history(&wc.deps).unwrap();
8536
    repo.write_state_index(&wc.deps, &base);
8537
    for (i, w) in want.iter().enumerate() {
8538
        assert_eq!(&repo.file_at(&format!("f{i}.txt"), None).unwrap(), w);
8539
    }
8540
    let index = repo.state_indexes();
8541
    assert!(!index.is_empty(), "a state index was written");
8542
    // The histories are last in the file: damage the last of them.
8543
    let mut bytes = fs::read(&index[0]).unwrap();
8544
    let last = bytes.len() - 1;
8545
    bytes[last] ^= 0x40;
8546
    fs::write(&index[0], &bytes).unwrap();
8547
8548
    let reads: Vec<_> = (0..6)
8549
        .map(|i| repo.file_at(&format!("f{i}.txt"), None))
8550
        .collect();
8551
    let damaged: Vec<String> = reads
8552
        .iter()
8553
        .filter_map(|r| r.as_ref().err().map(|e| e.to_string()))
8554
        .collect();
8555
    assert_eq!(damaged.len(), 1, "{damaged:?}");
8556
    assert!(
8557
        damaged[0].contains("state index was damaged")
8558
            && damaged[0].contains("run the command again"),
8559
        "{}",
8560
        damaged[0]
8561
    );
8562
    // Every file reads right again, from an index rebuilt from history.
8563
    for (i, w) in want.iter().enumerate() {
8564
        assert_eq!(&repo.file_at(&format!("f{i}.txt"), None).unwrap(), w);
8565
    }
8566
}
8567
8568
/// oxygen#95: a push longer than `push.batch-bytes` goes in parts, each
8569
/// objects alone and in dependency order, and the last moves the bookmark.
8570
/// The remote ends with every change and the same state, and says how each
8571
/// part went.
8572
#[test]
8573
fn a_long_push_goes_in_parts() {
8574
    hermetic();
8575
    let dir = tempfile::tempdir().unwrap();
8576
    let root = dir.path();
8577
    let origin = root.join("origin");
8578
    Repo::init_bare_unbound(&origin).unwrap();
8579
    let main = root.join("main");
8580
    let mut repo = Repo::init(&main).unwrap();
8581
    repo.config
8582
        .set("remote.origin.url", &origin.to_string_lossy())
8583
        .unwrap();
8584
    // One byte: every change is a part of its own.
8585
    repo.config.set("push.batch-bytes", "1").unwrap();
8586
    repo.save_config().unwrap();
8587
    for i in 0..6 {
8588
        write(
8589
            &main,
8590
            &format!("f{i}.txt"),
8591
            format!("file {i}\n").as_bytes(),
8592
        );
8593
        repo.commit(&format!("c{i}"), &[]).unwrap();
8594
    }
8595
    let mut parts = Vec::new();
8596
    let results = repo
8597
        .push_bookmark_with("origin", "main", false, &mut |m| parts.push(m.to_string()))
8598
        .unwrap();
8599
    assert!(
8600
        results.iter().any(|r| r.ok && r.name == "main"),
8601
        "{results:?}"
8602
    );
8603
    assert_eq!(parts.len(), 6, "{parts:?}");
8604
    assert_eq!(parts[0], "part 1 of 6: 1 changes");
8605
8606
    let remote = Repo::open(&origin).unwrap();
8607
    let heads = repo.bookmark_heads().unwrap();
8608
    assert_eq!(remote.bookmark_heads().unwrap(), heads);
8609
    assert_eq!(
8610
        remote.log_state(&heads).unwrap().len(),
8611
        repo.log_state(&heads).unwrap().len()
8612
    );
8613
    // A push of objects alone reports how it went, as `objects`.
8614
    let got = remote
8615
        .receive_push(Bundle::default(), vec![], None, vec![])
8616
        .unwrap();
8617
    assert_eq!(got.len(), 1);
8618
    assert!(got[0].ok && got[0].name == OBJECTS_RESULT, "{got:?}");
8619
}
8620
8621
/// oxygen#97: with `git.claim`, an import authors the importing identity's
8622
/// own commits (Git author email = its email, any case) with its key, and
8623
/// leaves anyone else's with the zero key; the history verifies as before.
8624
#[test]
8625
fn git_import_claims_your_own_commits() {
8626
    hermetic();
8627
    if std::process::Command::new("git")
8628
        .arg("--version")
8629
        .output()
8630
        .is_err()
8631
    {
8632
        eprintln!("git not installed; skipping");
8633
        return;
8634
    }
8635
    let dir = tempfile::tempdir().unwrap();
8636
    let root = dir.path();
8637
    let g = root.join("src.git");
8638
    fs::create_dir_all(&g).unwrap();
8639
    let git = |who: &str, args: &[&str]| {
8640
        let (name, email) = who.split_once(' ').unwrap();
8641
        let out = std::process::Command::new("git")
8642
            .arg("-C")
8643
            .arg(&g)
8644
            .args([
8645
                "-c",
8646
                &format!("user.name={name}"),
8647
                "-c",
8648
                &format!("user.email={email}"),
8649
                "-c",
8650
                "commit.gpgsign=false",
8651
            ])
8652
            .args(args)
8653
            .output()
8654
            .unwrap();
8655
        assert!(
8656
            out.status.success(),
8657
            "git {args:?}: {}",
8658
            String::from_utf8_lossy(&out.stderr)
8659
        );
8660
    };
8661
    git("Grace [email protected]", &["init", "-q", "-b", "main"]);
8662
    write(&g, "a.txt", b"a\n");
8663
    git("Grace [email protected]", &["add", "."]);
8664
    git("Grace [email protected]", &["commit", "-qm", "mine"]);
8665
    write(&g, "b.txt", b"b\n");
8666
    git("Ada [email protected]", &["add", "."]);
8667
    git("Ada [email protected]", &["commit", "-qm", "someone else's"]);
8668
8669
    let mut repo = Repo::init(&root.join("o")).unwrap();
8670
    let (key, _) = repo
8671
        .create_identity("Grace", "[email protected]", IdentityScope::Repo)
8672
        .unwrap();
8673
    repo.config.set("git.claim", "true").unwrap();
8674
    repo.save_config().unwrap();
8675
    let repo = Repo::open(&root.join("o")).unwrap();
8676
    repo.import_git(&g, "main").unwrap();
8677
    let v = repo.verify_git_import(&g, "main").unwrap();
8678
    assert!(v.mismatches.is_empty(), "{:?}", v.mismatches);
8679
    let heads = repo.bookmark_heads().unwrap();
8680
    let by_message: std::collections::HashMap<String, KeyId> = repo
8681
        .log_state(&heads)
8682
        .unwrap()
8683
        .into_iter()
8684
        .map(|e| {
8685
            (
8686
                e.change.message.lines().next().unwrap_or("").to_string(),
8687
                e.change.author,
8688
            )
8689
        })
8690
        .collect();
8691
    assert_eq!(by_message["mine"], key, "her own commit, any case of email");
8692
    assert_eq!(by_message["someone else's"], ObjectRef::ZERO, "not hers");
8693
}
8694
8695
/// oxygen#86: removing a remote removes all of it: every `remote.NAME.*`
8696
/// key (URL, token, CA), its tracking bookmarks, and nothing else.
8697
#[test]
8698
fn removing_a_remote_leaves_nothing_of_it() {
8699
    hermetic();
8700
    let dir = tempfile::tempdir().unwrap();
8701
    let origin = dir.path().join("origin");
8702
    Repo::init_bare_unbound(&origin).unwrap();
8703
    let main = dir.path().join("main");
8704
    let mut repo = Repo::init(&main).unwrap();
8705
    repo.config
8706
        .set("remote.origin.url", &origin.to_string_lossy())
8707
        .unwrap();
8708
    repo.config
8709
        .set("remote.origin.token", "secret-ish")
8710
        .unwrap();
8711
    repo.config
8712
        .set("remote.keep.url", &origin.to_string_lossy())
8713
        .unwrap();
8714
    repo.save_config().unwrap();
8715
    write(&main, "a.txt", b"a\n");
8716
    repo.commit("a", &[]).unwrap();
8717
    assert!(repo.push("origin", false).unwrap()[0].ok);
8718
    assert!(
8719
        repo.view().unwrap().remotes.contains_key("origin"),
8720
        "a tracking bookmark"
8721
    );
8722
8723
    repo.remove_remote("origin").unwrap();
8724
    let again = Repo::open(&main).unwrap();
8725
    assert!(
8726
        !again
8727
            .config
8728
            .repo_layer()
8729
            .keys()
8730
            .any(|k| k.starts_with("remote.origin.")),
8731
        "{:?}",
8732
        again.config.repo_layer()
8733
    );
8734
    assert!(!again.config.remotes.contains_key("origin"));
8735
    assert!(
8736
        !again.view().unwrap().remotes.contains_key("origin"),
8737
        "its tracking bookmarks go"
8738
    );
8739
    assert!(
8740
        again.config.remotes.contains_key("keep"),
8741
        "another remote stays"
8742
    );
8743
    let mut again = again;
8744
    assert!(
8745
        again.remove_remote("origin").is_err(),
8746
        "a second removal is refused"
8747
    );
8748
}
8749
8750
/// oxygenhub#126: a blob a host stored for itself (a job's artifact) is
8751
/// unreachable from history, so gc prunes it, unless the host names it:
8752
/// then it and its chunks stay, and it reads back whole.
8753
#[test]
8754
fn gc_keeps_the_blobs_a_host_names() {
8755
    hermetic();
8756
    let dir = tempfile::tempdir().unwrap();
8757
    let repo = Repo::init(dir.path()).unwrap();
8758
    write(dir.path(), "a.txt", b"a\n");
8759
    repo.commit("a", &[]).unwrap();
8760
    // Large enough to be several chunks.
8761
    let body: Vec<u8> = (0..400_000u32)
8762
        .flat_map(|i| (i.wrapping_mul(2654435761)).to_le_bytes())
8763
        .collect();
8764
    let kept = repo.store_blob(&body).unwrap();
8765
    let lost = repo.store_blob(b"an artifact nobody names").unwrap();
8766
    repo.gc_keeping(true, &[kept], &mut |_| {}).unwrap();
8767
    assert_eq!(repo.read_blob(&kept).unwrap(), body, "named: kept whole");
8768
    assert!(!repo.store().has(&lost), "not named: pruned");
8769
    repo.gc(true).unwrap();
8770
    assert!(!repo.store().has(&kept), "a plain gc prunes it");
8771
}
8772
8773
/// oxygen#99: undo in one workspace undoes that workspace's last command,
8774
/// never another workspace's, says what it undid, and goes further back
8775
/// when run again.
8776
#[test]
8777
fn undo_is_scoped_to_its_workspace() {
8778
    hermetic();
8779
    let dir = tempfile::tempdir().unwrap();
8780
    let root = dir.path().join("main");
8781
    let a = Repo::init(&root).unwrap();
8782
    write(&root, "base.txt", b"base\n");
8783
    let base = a.commit("base", &[]).unwrap();
8784
    a.bookmark_create("feature", None).unwrap();
8785
    let ws_dir = dir.path().join("ws");
8786
    let heads = a.resolve_heads("feature").unwrap();
8787
    let b = a
8788
        .workspace_add_on(&ws_dir, Some(&heads), Some("feature"))
8789
        .unwrap();
8790
8791
    // A commits on main, then B commits on feature: B's is the newest.
8792
    write(&root, "a.txt", b"a\n");
8793
    let ca = a.commit("from a", &[]).unwrap();
8794
    write(&ws_dir, "b.txt", b"b\n");
8795
    let cb = b.commit("from b", &[]).unwrap();
8796
8797
    // A's undo undoes A's commit and leaves B's.
8798
    let u = a.undo().unwrap();
8799
    assert_eq!(u.command, "oxy commit -m \"from a\"");
8800
    assert_eq!(u.others_kept, 1, "B's newer commit is left");
8801
    assert!(!u.changes.is_empty());
8802
    let view = a.view().unwrap();
8803
    // (Independent changes commute, so a bookmark's heads may hold base too.)
8804
    assert_eq!(a.heads_of(&view, "main").unwrap(), vec![base]);
8805
    assert!(
8806
        a.heads_of(&view, "feature").unwrap().contains(&cb),
8807
        "B's commit stands"
8808
    );
8809
    assert!(
8810
        a.store().get_change(&ca).is_ok(),
8811
        "the change itself is still in the store"
8812
    );
8813
    // A's working copy was clean, so its files followed; B's are untouched.
8814
    assert!(!root.join("a.txt").exists());
8815
    assert!(a.snapshot("oxy status").unwrap().statuses.is_empty());
8816
    assert!(ws_dir.join("b.txt").exists());
8817
8818
    // B's undo still finds B's own commit, under A's undo.
8819
    let u = b.undo().unwrap();
8820
    assert_eq!(u.command, "oxy commit -m \"from b\"");
8821
    assert!(!b
8822
        .heads_of(&b.view().unwrap(), "feature")
8823
        .unwrap()
8824
        .contains(&cb));
8825
    assert_eq!(
8826
        a.heads_of(&a.view().unwrap(), "main").unwrap(),
8827
        vec![base],
8828
        "A's undo stands"
8829
    );
8830
8831
    // A's next undo goes past the commit it already undid, to adding B's
8832
    // workspace: refused, since B has worked there since.
8833
    let e = a.undo().unwrap_err().to_string();
8834
    assert!(e.contains("the workspace at") && e.contains("ws"), "{e}");
8835
}
8836
8837
/// oxygen#99: two workspaces on one bookmark: an undo takes back only its
8838
/// own commit's head, and the other workspace's head stays.
8839
#[test]
8840
fn undo_on_a_shared_bookmark_keeps_the_other_workspaces_head() {
8841
    hermetic();
8842
    let dir = tempfile::tempdir().unwrap();
8843
    let root = dir.path().join("main");
8844
    let a = Repo::init(&root).unwrap();
8845
    write(&root, "base.txt", b"base\n");
8846
    a.commit("base", &[]).unwrap();
8847
    let ws_dir = dir.path().join("ws");
8848
    let b = a.workspace_add(&ws_dir, None).unwrap();
8849
    write(&root, "a.txt", b"a\n");
8850
    let ca = a.commit("from a", &[]).unwrap();
8851
    write(&ws_dir, "b.txt", b"b\n");
8852
    let cb = b.commit("from b", &[]).unwrap();
8853
    let u = a.undo().unwrap();
8854
    assert_eq!(u.command, "oxy commit -m \"from a\"");
8855
    let heads = a.heads_of(&a.view().unwrap(), "main").unwrap();
8856
    assert!(heads.contains(&cb) && !heads.contains(&ca), "{heads:?}");
8857
}
8858
8859
/// oxygen#99: an undo that would also take back what another workspace
8860
/// did since to the same bookmark is refused, naming it.
8861
#[test]
8862
fn undo_refuses_to_take_back_another_workspaces_work() {
8863
    hermetic();
8864
    let dir = tempfile::tempdir().unwrap();
8865
    let root = dir.path().join("main");
8866
    let a = Repo::init(&root).unwrap();
8867
    write(&root, "base.txt", b"base\n");
8868
    a.commit("base", &[]).unwrap();
8869
    let ws_dir = dir.path().join("ws");
8870
    let b = a.workspace_add(&ws_dir, None).unwrap();
8871
    // Both on main: A commits, then B builds on it, editing A's file.
8872
    write(&root, "a.txt", b"a\n");
8873
    a.commit("from a", &[]).unwrap();
8874
    b.refresh().unwrap();
8875
    let heads = b.resolve_heads("main").unwrap();
8876
    b.checkout(&heads, false, "oxy checkout").unwrap();
8877
    write(&ws_dir, "a.txt", b"a, then b\n");
8878
    b.commit("from b", &[]).unwrap();
8879
    let e = a.undo().unwrap_err().to_string();
8880
    assert!(
8881
        e.contains("bookmark main") && e.contains("builds on"),
8882
        "{e}"
8883
    );
8884
    assert!(e.contains("oxy op restore"), "{e}");
8885
}
8886
8887
/// oxygen#99: undoing a commit that was already pushed says so: the remote
8888
/// still has it.
8889
#[test]
8890
fn undo_says_when_the_commit_was_pushed() {
8891
    hermetic();
8892
    let dir = tempfile::tempdir().unwrap();
8893
    let root = dir.path();
8894
    Repo::init(&root.join("origin")).unwrap();
8895
    let url = root.join("origin").to_string_lossy().to_string();
8896
    let repo = Repo::clone(&url, &root.join("work"))
8897
        .unwrap()
8898
        .with_home(root.join("home"));
8899
    write(&root.join("work"), "a.txt", b"a\n");
8900
    repo.commit("a", &[]).unwrap();
8901
    assert!(repo.push("origin", false).unwrap()[0].ok);
8902
    // The push itself is passed over: the remote keeps what it was sent.
8903
    let u = repo.undo().unwrap();
8904
    assert_eq!(u.command, "oxy commit -m \"a\"");
8905
    assert_eq!(u.pushed, vec![("main".to_string(), "origin".to_string())]);
8906
}
8907
8908
/// oxygen#98: a new untracked file over snapshot.max-new-file-size is left
8909
/// out of the snapshot and named; tracked files and files already in the
8910
/// working copy are not.
8911
#[test]
8912
fn large_new_files_are_left_out_of_snapshots() {
8913
    hermetic();
8914
    let dir = tempfile::tempdir().unwrap();
8915
    let root = dir.path();
8916
    let mut repo = Repo::init(root).unwrap();
8917
    repo.config.max_new_file = 1024;
8918
    write(root, "small.txt", b"small\n");
8919
    write(root, "big.bin", &vec![0u8; 4096]);
8920
    let s = repo.snapshot("oxy status").unwrap();
8921
    let paths: Vec<_> = s.statuses.iter().map(|p| p.path.as_str()).collect();
8922
    assert_eq!(paths, ["small.txt"]);
8923
    assert_eq!(repo.skipped_large(), vec![("big.bin".to_string(), 4096)]);
8924
    repo.commit("small", &[]).unwrap();
8925
8926
    // A tracked file may grow past the limit.
8927
    write(root, "small.txt", &vec![b'x'; 4096]);
8928
    let s = repo.snapshot("oxy status").unwrap();
8929
    assert!(s.statuses.iter().any(|p| p.path == "small.txt"));
8930
    // With no limit the big file is taken in, and stays once it is.
8931
    repo.config.max_new_file = 0;
8932
    let s = repo.snapshot("oxy status").unwrap();
8933
    assert!(s.statuses.iter().any(|p| p.path == "big.bin"));
8934
    repo.config.max_new_file = 1024;
8935
    let s = repo.snapshot("oxy status").unwrap();
8936
    assert!(
8937
        s.statuses.iter().any(|p| p.path == "big.bin"),
8938
        "already in the working copy"
8939
    );
8940
    assert!(repo.skipped_large().is_empty());
8941
}
8942
8943
/// oxygen#98: a file only a past working-copy snapshot held is pruned once
8944
/// snapshots expire, and kept while they have not.
8945
#[test]
8946
fn gc_prunes_what_only_expired_snapshots_held() {
8947
    hermetic();
8948
    let dir = tempfile::tempdir().unwrap();
8949
    let root = dir.path();
8950
    let mut repo = Repo::init(root).unwrap();
8951
    repo.config.gc_grace_days = 0;
8952
    write(root, "a.txt", b"a\n");
8953
    repo.commit("a", &[]).unwrap();
8954
    let image: Vec<u8> = (0..200_000u32).map(|i| (i % 7) as u8).collect();
8955
    write(root, "image.tar", &image);
8956
    repo.snapshot("oxy status").unwrap();
8957
    std::fs::remove_file(root.join("image.tar")).unwrap();
8958
    repo.snapshot("oxy status").unwrap();
8959
    let blob = Repo::blob_ref(&image);
8960
    assert!(repo.store().has(&blob));
8961
    repo.gc(true).unwrap();
8962
    assert!(repo.store().has(&blob), "a recent snapshot keeps it");
8963
    repo.config.snapshot_retention_days = 0;
8964
    repo.gc(true).unwrap();
8965
    assert!(!repo.store().has(&blob), "an expired snapshot does not");
8966
    assert_eq!(
8967
        repo.file_at("a.txt", None).unwrap(),
8968
        b"a\n",
8969
        "committed files stay"
8970
    );
8971
}
8972
8973
/// oxygen#100: uncommitted work byte-for-byte what the bookmark switched to
8974
/// already has is no conflict: the switch goes through, nothing is lost,
8975
/// and other carried work still comes along.
8976
#[test]
8977
fn carrying_work_the_target_already_has_is_no_conflict() {
8978
    hermetic();
8979
    let dir = tempfile::tempdir().unwrap();
8980
    let root = dir.path();
8981
    let mut repo = Repo::init(root).unwrap();
8982
    write(root, "a.txt", b"one\n");
8983
    write(root, "b.txt", b"b\n");
8984
    repo.commit("one", &[]).unwrap();
8985
    repo.bookmark_create("landed", None).unwrap();
8986
    // On landed, a.txt becomes "two" (as a proposal landing would).
8987
    repo.bookmark_switch("landed", false).unwrap();
8988
    write(root, "a.txt", b"two\n");
8989
    repo.commit("two", &[]).unwrap();
8990
    repo.bookmark_switch("main", false).unwrap();
8991
    assert_eq!(std::fs::read(root.join("a.txt")).unwrap(), b"one\n");
8992
    // The same edit, uncommitted, on main; and another edit besides.
8993
    write(root, "a.txt", b"two\n");
8994
    write(root, "b.txt", b"b, edited\n");
8995
    let (_, carried) = repo.bookmark_switch_carry("landed").unwrap();
8996
    assert_eq!(
8997
        carried,
8998
        vec!["b.txt".to_string()],
8999
        "only the work landed lacks is carried"
9000
    );
9001
    assert_eq!(std::fs::read(root.join("a.txt")).unwrap(), b"two\n");
9002
    assert_eq!(std::fs::read(root.join("b.txt")).unwrap(), b"b, edited\n");
9003
    let s = repo.snapshot("oxy status").unwrap();
9004
    let paths: Vec<_> = s.statuses.iter().map(|p| p.path.as_str()).collect();
9005
    assert_eq!(paths, ["b.txt"]);
9006
9007
    // A real difference is still refused.
9008
    repo.bookmark_switch("main", true).unwrap();
9009
    write(root, "a.txt", b"three\n");
9010
    let e = repo
9011
        .bookmark_switch_carry("landed")
9012
        .unwrap_err()
9013
        .to_string();
9014
    assert!(e.contains("a.txt") && e.contains("--discard"), "{e}");
9015
}
9016
9017
/// oxygen#103: a full change hash as `--json` prints it, without `#`,
9018
/// resolves, so JSON output feeds back into commands.
9019
#[test]
9020
fn a_full_hash_resolves_without_its_hash_sign() {
9021
    hermetic();
9022
    let dir = tempfile::tempdir().unwrap();
9023
    let root = dir.path();
9024
    let repo = Repo::init(root).unwrap();
9025
    write(root, "a.txt", b"a\n");
9026
    let h = repo.commit("a", &[]).unwrap();
9027
    assert_eq!(repo.resolve_change(&h.to_hex()).unwrap(), h);
9028
    assert_eq!(repo.resolve_change(&format!("#{}", h.to_hex())).unwrap(), h);
9029
    assert!(repo
9030
        .resolve_change(&"0".repeat(64))
9031
        .unwrap_err()
9032
        .to_string()
9033
        .contains("no change matches"));
9034
}
9035
9036
#[test]
9037
fn a_pin_change_moves_only_the_pin() {
9038
    hermetic();
9039
    let dir = tempfile::tempdir().unwrap();
9040
    let root = dir.path();
9041
    let _lib_origin = Repo::init(&root.join("lib-origin")).unwrap();
9042
    let lib_url = root.join("lib-origin").to_string_lossy().to_string();
9043
    let lib = Repo::clone(&lib_url, &root.join("lib"))
9044
        .unwrap()
9045
        .with_home(root.join("home"));
9046
    write(&root.join("lib"), "lib.txt", b"v1\n");
9047
    lib.commit("lib v1", &[]).unwrap();
9048
    assert!(lib.push("origin", false).unwrap()[0].ok);
9049
    let _app_origin = Repo::init(&root.join("app-origin")).unwrap();
9050
    let app_dir = root.join("app");
9051
    let app = Repo::clone(&root.join("app-origin").to_string_lossy(), &app_dir)
9052
        .unwrap()
9053
        .with_home(root.join("home"));
9054
    write(&app_dir, "main.txt", b"app\n");
9055
    let pin1 = app.submodule_add(&lib_url, "libs/lib", None).unwrap();
9056
    let a1 = app.commit("app with lib", &[]).unwrap();
9057
    // The library moves on.
9058
    write(&root.join("lib"), "more.txt", b"v2\n");
9059
    let l2 = lib.commit("lib v2", &[]).unwrap();
9060
    let crate::subrepo::Pin::Oxy { repo, bookmark, .. } = pin1 else {
9061
        panic!("an Oxygen pin")
9062
    };
9063
    let pin2 = crate::subrepo::Pin::Oxy {
9064
        repo,
9065
        heads: vec![l2],
9066
        bookmark,
9067
    };
9068
    let author = app.store().get_change(&a1).unwrap().author;
9069
    let change = app
9070
        .build_pin_change(&[a1], "libs/lib", &pin2, "Move lib to v2", author)
9071
        .unwrap();
9072
    let mut state = app.load_state(&[a1]).unwrap();
9073
    state.add(change).unwrap();
9074
    let files = state.materialize().files;
9075
    assert_eq!(files["libs/lib"].kind, NodeKind::Subrepo);
9076
    let FileContent::Opaque { blobs } = &files["libs/lib"].content else {
9077
        panic!("a pin is opaque")
9078
    };
9079
    let read = crate::subrepo::Pin::decode(&app.read_blob(&blobs[0]).unwrap()).unwrap();
9080
    assert_eq!(read, pin2, "the new pin");
9081
    assert!(
9082
        matches!(&files["main.txt"].content, FileContent::Text { bytes, .. } if bytes.as_slice() == b"app\n"),
9083
        "nothing else changes"
9084
    );
9085
    // Only a subrepo's pin can be moved this way.
9086
    let e = app.build_pin_change(&[a1], "main.txt", &pin2, "x", author);
9087
    assert!(format!("{:?}", e.unwrap_err()).contains("not a subrepo"));
9088
    let e = app.build_pin_change(&[a1], "libs/none", &pin2, "x", author);
9089
    assert!(format!("{:?}", e.unwrap_err()).contains("does not exist"));
9090
}
9091
9092
/// oxygenhub#249: a handle reads the operation head once and keeps it,
9093
/// so one command or request never mixes two heads; another handle's
9094
/// operation shows only after `refresh`. Its own operations move it, and
9095
/// one recorded from the head it kept merges with what landed since, as
9096
/// any concurrent operation does.
9097
#[test]
9098
fn one_handle_keeps_one_head_until_it_refreshes() {
9099
    hermetic();
9100
    let dir = tempfile::tempdir().unwrap();
9101
    let root = dir.path();
9102
    let writer = Repo::init(root).unwrap();
9103
    write(root, "a.txt", b"one\n");
9104
    let h1 = writer.commit("one", &[]).unwrap();
9105
    let reader = Repo::open(root).unwrap();
9106
    let before = reader.view().unwrap();
9107
    assert_eq!(reader.bookmark_heads().unwrap(), vec![h1]);
9108
    write(root, "a.txt", b"two\n");
9109
    let h2 = writer.commit("two", &[]).unwrap();
9110
    assert_eq!(
9111
        writer.bookmark_heads().unwrap(),
9112
        vec![h2],
9113
        "its own operation"
9114
    );
9115
    assert_eq!(reader.view().unwrap(), before, "the head it read first");
9116
    assert_eq!(reader.bookmark_heads().unwrap(), vec![h1]);
9117
    reader.refresh().unwrap();
9118
    assert_eq!(reader.bookmark_heads().unwrap(), vec![h2]);
9119
9120
    // A handle recording from an older head merges with the newer one.
9121
    let stale = Repo::open(root).unwrap();
9122
    assert_eq!(stale.bookmark_heads().unwrap(), vec![h2]);
9123
    write(root, "a.txt", b"three\n");
9124
    let h3 = writer.commit("three", &[]).unwrap();
9125
    stale.bookmark_create("feature", Some(&[h1])).unwrap();
9126
    let view = stale.view().unwrap();
9127
    assert!(view.bookmarks.contains_key("feature"));
9128
    assert_eq!(
9129
        stale.bookmark_heads().unwrap(),
9130
        vec![h3],
9131
        "merged, not lost"
9132
    );
9133
    let fresh = Repo::open(root).unwrap();
9134
    assert_eq!(fresh.view().unwrap(), view);
9135
}
9136
9137
/// oxygenhub#249 over a store (a bucket's compare-and-swap): the same.
9138
#[test]
9139
fn over_a_store_one_handle_keeps_one_head() {
9140
    hermetic();
9141
    let backend = std::sync::Arc::new(crate::strata::MemoryStore::new());
9142
    crate::store::TEST_BACKEND.with(|t| *t.borrow_mut() = Some(backend.clone()));
9143
    let dir = tempfile::tempdir().unwrap();
9144
    let a = Repo::init(dir.path()).unwrap();
9145
    let (h0, _) = a.head_op().unwrap();
9146
    let b = Repo::open(dir.path()).unwrap();
9147
    assert_eq!(b.head_op().unwrap().0, h0);
9148
    let state = a.store.put_state(&StateObject::new(vec![])).unwrap();
9149
    let mut view = a.view().unwrap();
9150
    view.bookmarks.insert("x".into(), state);
9151
    let r = a.record_op(&[h0], "bookmark x", view).unwrap();
9152
    assert_eq!(a.head_op().unwrap().0, r);
9153
    assert_eq!(b.head_op().unwrap().0, h0, "b keeps its head");
9154
    b.refresh().unwrap();
9155
    assert_eq!(b.head_op().unwrap().0, r);
9156
    crate::store::TEST_BACKEND.with(|t| *t.borrow_mut() = None);
9157
}
9158
9159
/// oxygenhub#249: gc retires what it repacks rather than deleting it; a
9160
/// reader opened before reads on, then and after the next gc deletes the
9161
/// retired files once their hour is up. Younger ones are kept.
9162
#[test]
9163
fn gc_retires_and_a_later_gc_deletes_after_the_hour() {
9164
    hermetic();
9165
    let dir = tempfile::tempdir().unwrap();
9166
    let root = dir.path();
9167
    let repo = Repo::init(root).unwrap();
9168
    let mut heads = Vec::new();
9169
    for i in 0..4 {
9170
        write(root, &format!("f{i}.txt"), format!("{i}\n").as_bytes());
9171
        heads.push(repo.commit(&format!("c{i}"), &[]).unwrap());
9172
    }
9173
    let reader = Repo::open(root).unwrap();
9174
    assert_eq!(reader.log().unwrap().len(), 5);
9175
    let r = repo.gc(true).unwrap();
9176
    assert_eq!(r.retired, crate::store::RetiredReport::default());
9177
    assert_eq!(repo.store().loose_count().unwrap(), 0);
9178
    assert_eq!(reader.log().unwrap().len(), 5, "read on from what it had");
9179
    // Nothing is an hour old yet: a gc keeps it all.
9180
    let r = repo.gc(true).unwrap();
9181
    assert_eq!((r.retired.packs, r.retired.loose), (0, 0));
9182
    assert!(r.retired.kept > 0, "{r:?}");
9183
    write(root, "f9.txt", b"9\n");
9184
    heads.push(repo.commit("c9", &[]).unwrap());
9185
    crate::store::reader_tests::age_retired(
9186
        repo.store(),
9187
        crate::store::RETIRED_FOR + std::time::Duration::from_secs(60),
9188
    );
9189
    let r = repo.gc(true).unwrap();
9190
    assert!(r.retired.packs >= 1 && r.retired.loose > 0, "{r:?}");
9191
    assert_eq!(r.retired.kept, 0, "{r:?}");
9192
    let r = repo.gc(true).unwrap();
9193
    assert_eq!((r.retired.packs, r.retired.loose), (0, 0));
9194
    assert!(r.retired.kept > 0, "what the last gc retired is young");
9195
    // The reader opened before all of it still reads everything, from
9196
    // the packs it finds when what it loaded is gone.
9197
    assert_eq!(reader.log().unwrap().len(), 5);
9198
    for h in &heads[..4] {
9199
        reader.store().get_change(h).unwrap();
9200
    }
9201
    reader.refresh().unwrap();
9202
    assert_eq!(reader.log().unwrap().len(), 6);
9203
    let fresh = Repo::open(root).unwrap();
9204
    assert_eq!(
9205
        fresh.store().pack_count(),
9206
        1,
9207
        "retired packs are not loaded"
9208
    );
9209
}
9210
9211
/// oxygenhub#249: a repository opens when its store's pack listing names
9212
/// an index that is not there (deleted between the listing and the read).
9213
#[test]
9214
fn a_repository_opens_when_a_listed_index_is_gone() {
9215
    hermetic();
9216
    let backend = crate::store::reader_tests::racing(true);
9217
    let dyn_backend: std::sync::Arc<crate::store::Backend> = backend.clone();
9218
    crate::store::TEST_BACKEND.with(|t| *t.borrow_mut() = Some(dyn_backend));
9219
    let dir = tempfile::tempdir().unwrap();
9220
    let repo = Repo::init(dir.path()).unwrap();
9221
    write(dir.path(), "a.txt", b"a\n");
9222
    let h = repo.commit("a", &[]).unwrap();
9223
    repo.gc(true).unwrap();
9224
    let again = Repo::open(dir.path()).unwrap();
9225
    assert_eq!(again.store().pack_count(), 1);
9226
    assert_eq!(again.bookmark_heads().unwrap(), vec![h]);
9227
    // And when one is deleted between the listing and the read: a copy of
9228
    // the live pack, whose index goes as the store opens.
9229
    use crate::strata::Store as _;
9230
    let idx = backend
9231
        .list("pack-")
9232
        .unwrap()
9233
        .into_iter()
9234
        .map(|e| e.key)
9235
        .find(|k| k.ends_with(".idx") && k != "pack-0000.idx")
9236
        .unwrap();
9237
    let stem = idx.trim_end_matches(".idx");
9238
    for ext in ["pack", "idx"] {
9239
        let bytes = backend.get(&format!("{stem}.{ext}")).unwrap();
9240
        backend
9241
            .put_new(&format!("pack-copy.{ext}"), &bytes)
9242
            .unwrap();
9243
    }
9244
    *backend.doomed.lock().unwrap() = Some("pack-copy.idx".into());
9245
    let again = Repo::open(dir.path()).unwrap();
9246
    assert_eq!(again.store().pack_count(), 1);
9247
    assert_eq!(again.bookmark_heads().unwrap(), vec![h]);
9248
    assert!(!backend.has("pack-copy.idx").unwrap());
9249
    crate::store::TEST_BACKEND.with(|t| *t.borrow_mut() = None);
9250
}