OXYGENHUB
# 767ac6cd0545 oxygen / crates / oxy-core / src / repo / tests.rs
326.7 KiB · Rust · last changed Readers never wait: one head per handle, retry on a miss, retire before deleting 17 days ago source blame history raw
1
//! Tests for the repository layer.
2
3
use super::*;
4
use crate::protocol::SignedPolicy;
5
use crate::repo::{BisectStep, Selection};
6
7
/// Point `$OXY_HOME` at a throwaway directory once per test process so no
8
/// test reads or writes the developer's real user configuration or keys.
9
fn hermetic() {
10
    static ONCE: std::sync::Once = std::sync::Once::new();
11
    static DIR: std::sync::OnceLock<tempfile::TempDir> = std::sync::OnceLock::new();
12
    ONCE.call_once(|| {
13
        let d = tempfile::tempdir().unwrap();
14
        std::env::set_var("OXY_HOME", d.path());
15
        DIR.set(d).ok();
16
    });
17
}
18
19
fn write(root: &Path, rel: &str, content: &[u8]) {
20
    let p = root.join(rel);
21
    fs::create_dir_all(p.parent().unwrap()).unwrap();
22
    fs::write(p, content).unwrap();
23
}
24
25
fn statuses(s: &SnapshotResult) -> Vec<(String, ChangeStatus)> {
26
    s.statuses
27
        .iter()
28
        .map(|p| (p.path.clone(), p.status))
29
        .collect()
30
}
31
32
#[test]
33
fn init_snapshot_commit_log_undo() {
34
    hermetic();
35
    let dir = tempfile::tempdir().unwrap();
36
    let root = dir.path();
37
    let repo = Repo::init(root).unwrap();
38
    assert!(Repo::init(root).is_err());
39
    let ops = repo.op_log().unwrap();
40
    assert_eq!(ops.len(), 1);
41
    assert_eq!(ops[0].1.command, "oxy init");
42
43
    // Empty working copy: snapshot records no operation (spec §12.3).
44
    let s = repo.snapshot("oxy status").unwrap();
45
    assert!(!s.changed);
46
    assert_eq!(repo.op_log().unwrap().len(), 1);
47
48
    write(root, "src/main.rs", b"fn main() {}\n");
49
    write(root, "README.md", b"# Hello\n");
50
    write(root, ".oxyignore", b"/target\n");
51
    write(root, "target/junk.o", b"\0\0\0");
52
    let s = repo.snapshot("oxy status").unwrap();
53
    assert!(s.changed);
54
    assert_eq!(
55
        statuses(&s),
56
        vec![
57
            (".oxyignore".into(), ChangeStatus::Added),
58
            ("README.md".into(), ChangeStatus::Added),
59
            ("src/main.rs".into(), ChangeStatus::Added),
60
        ]
61
    );
62
    assert_eq!(repo.op_log().unwrap().len(), 2);
63
    // Snapshotting again with nothing changed records no op.
64
    let s2 = repo.snapshot("oxy status").unwrap();
65
    assert!(!s2.changed);
66
    assert_eq!(s2.wc_hash, s.wc_hash);
67
    assert_eq!(repo.op_log().unwrap().len(), 2);
68
69
    let h1 = repo.commit("Initial import", &[]).unwrap();
70
    let c1 = repo.store().get_change(&h1).unwrap();
71
    assert_eq!(c1.kind, ChangeKind::Normal);
72
    assert!(c1.deps.is_empty(), "first change has nothing to depend on");
73
    assert_eq!(repo.bookmark_heads().unwrap(), vec![h1]);
74
    let (wc_hash, wc) = repo.working_copy().unwrap();
75
    assert_eq!(wc.deps, vec![h1]);
76
    assert!(wc.edits.is_empty());
77
    assert!(repo.commit("nothing", &[]).is_err());
78
79
    // Modify one file, remove another, add a binary file.
80
    write(
81
        root,
82
        "src/main.rs",
83
        b"fn main() {\n    println!(\"hi\");\n}\n",
84
    );
85
    fs::remove_file(root.join("README.md")).unwrap();
86
    write(root, "logo.png", b"\x89PNG\0\0\x01");
87
    let s = repo.snapshot("oxy status").unwrap();
88
    assert_eq!(
89
        statuses(&s),
90
        vec![
91
            ("README.md".into(), ChangeStatus::Removed),
92
            ("logo.png".into(), ChangeStatus::Added),
93
            ("src/main.rs".into(), ChangeStatus::Modified),
94
        ]
95
    );
96
    assert_ne!(s.wc_hash, wc_hash);
97
    // The rewritten working copy keeps its ChangeId and depends on h1.
98
    assert_eq!(s.wc.change_id, wc.change_id);
99
    assert!(s.wc.deps.contains(&h1));
100
101
    let h2 = repo.commit("Second", &[]).unwrap();
102
    let c2 = repo.store().get_change(&h2).unwrap();
103
    assert_eq!(
104
        c2.deps,
105
        vec![h1],
106
        "everything it touches was introduced by h1"
107
    );
108
    assert_eq!(repo.bookmark_heads().unwrap(), vec![h2]);
109
110
    // The materialized head state matches the working copy.
111
    let st = repo.load_state(&[h2]).unwrap();
112
    let snap = st.materialize();
113
    assert!(!snap.is_conflicted());
114
    assert_eq!(
115
        snap.files.keys().cloned().collect::<Vec<_>>(),
116
        [".oxyignore", "logo.png", "src", "src/main.rs"]
117
    );
118
    assert!(
119
        matches!(&snap.files["src/main.rs"].content, FileContent::Text { bytes, .. } if bytes == b"fn main() {\n    println!(\"hi\");\n}\n")
120
    );
121
    assert!(snap.files["logo.png"].mode.opaque);
122
    if let FileContent::Opaque { blobs } = &snap.files["logo.png"].content {
123
        assert_eq!(repo.read_blob(&blobs[0]).unwrap(), b"\x89PNG\0\0\x01");
124
    } else {
125
        panic!("logo should be opaque");
126
    }
127
128
    // Log: newest first, working copy included.
129
    let log = repo.log().unwrap();
130
    assert_eq!(log.len(), 3);
131
    assert!(log[0].is_working_copy);
132
    assert_eq!(log[1].hash, h2);
133
    assert!(log[1].is_head);
134
    assert_eq!(log[2].hash, h1);
135
    let d = repo.describe_change(&h2).unwrap();
136
    assert!(d.contains("D README.md"), "{d}");
137
    assert!(d.contains("+    println!(\"hi\");"), "{d}");
138
    assert!(d.contains("-fn main() {}"), "{d}");
139
140
    // Resolution by prefix.
141
    assert_eq!(repo.resolve_change(&c2.change_id.short(6)).unwrap(), h2);
142
    assert_eq!(
143
        repo.resolve_change(&format!("#{}", h1.short(8))).unwrap(),
144
        h1
145
    );
146
    assert!(repo.resolve_change("zzzz").is_err());
147
148
    // Undo the commit: bookmark and working copy go back.
149
    repo.undo().unwrap();
150
    assert_eq!(repo.bookmark_heads().unwrap(), vec![h1]);
151
    let s = repo.snapshot("oxy status").unwrap();
152
    assert!(
153
        !s.changed,
154
        "files on disk still match the pre-commit working copy"
155
    );
156
    assert_eq!(s.statuses.len(), 3);
157
}
158
159
/// Make `main` conflicted: two commits on the same base that edit the same line.
160
fn conflicted_repo() -> (tempfile::TempDir, Repo, ChangeHash, ChangeHash, ChangeHash) {
161
    let dir = tempfile::tempdir().unwrap();
162
    let root = dir.path();
163
    let repo = Repo::init(root).unwrap();
164
    write(root, "f.txt", b"a\nb\nc\n");
165
    let h1 = repo.commit("base", &[]).unwrap();
166
    write(root, "f.txt", b"a\nB\nc\n");
167
    let h2 = repo.commit("upper", &[]).unwrap();
168
    repo.checkout(&[h1], false, "checkout").unwrap();
169
    write(root, "f.txt", b"a\nX\nc\n");
170
    let h3 = repo.commit("ex", &[]).unwrap();
171
    (dir, repo, h1, h2, h3)
172
}
173
174
#[test]
175
fn concurrent_edits_conflict_and_can_be_resolved() {
176
    hermetic();
177
    let (dir, repo, h1, h2, h3) = conflicted_repo();
178
    let root = dir.path();
179
    let heads: BTreeSet<_> = repo.bookmark_heads().unwrap().into_iter().collect();
180
    assert_eq!(heads, [h2, h3].into_iter().collect());
181
    let st = repo.load_state(&[h2, h3]).unwrap();
182
    assert!(st.materialize().is_conflicted());
183
184
    // Checking out main writes markers.
185
    let r = repo
186
        .checkout(&repo.bookmark_heads().unwrap(), false, "checkout main")
187
        .unwrap();
188
    assert!(r.conflicted);
189
    let marked = fs::read_to_string(root.join("f.txt")).unwrap();
190
    assert!(
191
        marked.starts_with("a\n<<<<<<< oxy conflict 1 of 1"),
192
        "{marked}"
193
    );
194
    assert!(
195
        marked.contains("B\n") && marked.contains("X\n") && marked.ends_with("end\nc\n"),
196
        "{marked}"
197
    );
198
    assert!(has_conflict_markers(marked.as_bytes()));
199
    // Untouched markers: clean working copy; commit has nothing to do.
200
    let s = repo.snapshot("status").unwrap();
201
    assert!(s.statuses.is_empty());
202
    assert!(!s.resolves);
203
204
    // Partially edited file that still has markers cannot be committed.
205
    write(root, "f.txt", marked.replace("B\n", "BB\n").as_bytes());
206
    let s = repo.snapshot("status").unwrap();
207
    assert_eq!(
208
        statuses(&s),
209
        vec![("f.txt".into(), ChangeStatus::ConflictEdited)]
210
    );
211
    assert!(repo.commit("no", &[]).is_err());
212
213
    // Resolve by keeping one side and adding a line elsewhere.
214
    write(root, "f.txt", b"a\nX\nc\nd\n");
215
    let s = repo.snapshot("status").unwrap();
216
    assert_eq!(statuses(&s), vec![("f.txt".into(), ChangeStatus::Resolved)]);
217
    assert!(s.resolves);
218
    let h4 = repo.commit("resolve", &[]).unwrap();
219
    let c4 = repo.store().get_change(&h4).unwrap();
220
    assert_eq!(c4.kind, ChangeKind::Resolution);
221
    let mut want = vec![h1, h2, h3];
222
    want.sort();
223
    assert_eq!(
224
        c4.deps, want,
225
        "a resolution depends on exactly the contributors and what it references"
226
    );
227
    assert_eq!(repo.bookmark_heads().unwrap(), vec![h4]);
228
    let snap = repo.load_state(&[h4]).unwrap().materialize();
229
    assert!(!snap.is_conflicted());
230
    assert!(
231
        matches!(&snap.files["f.txt"].content, FileContent::Text { bytes, .. } if bytes == b"a\nX\nc\nd\n")
232
    );
233
    assert!(!repo.snapshot("status").unwrap().changed);
234
    // A peer holding only h2 and h3 and receiving h4 sees the same result,
235
    // whatever order the changes arrive in.
236
    let mut st = State::new();
237
    for h in [h4, h3, h1, h2] {
238
        st.add_unchecked(repo.store().get_change(&h).unwrap());
239
    }
240
    st.validate().unwrap();
241
    assert!(
242
        matches!(&st.materialize().files["f.txt"].content, FileContent::Text { bytes, .. } if bytes == b"a\nX\nc\nd\n")
243
    );
244
}
245
246
#[test]
247
fn resolution_may_keep_both_sides_or_neither() {
248
    hermetic();
249
    let (dir, repo, _h1, _h2, _h3) = conflicted_repo();
250
    let root = dir.path();
251
    repo.checkout(&repo.bookmark_heads().unwrap(), false, "checkout main")
252
        .unwrap();
253
    // Keep both sides in a chosen order.
254
    write(root, "f.txt", b"a\nX\nB\nc\n");
255
    let h = repo.commit("both", &[]).unwrap();
256
    let snap = repo.load_state(&[h]).unwrap().materialize();
257
    assert!(!snap.is_conflicted());
258
    assert!(
259
        matches!(&snap.files["f.txt"].content, FileContent::Text { bytes, .. } if bytes == b"a\nX\nB\nc\n")
260
    );
261
    // Undo and instead drop the whole region.
262
    repo.undo().unwrap();
263
    write(root, "f.txt", b"a\nc\n");
264
    let h = repo.commit("neither", &[]).unwrap();
265
    let snap = repo.load_state(&[h]).unwrap().materialize();
266
    assert!(!snap.is_conflicted());
267
    assert!(
268
        matches!(&snap.files["f.txt"].content, FileContent::Text { bytes, .. } if bytes == b"a\nc\n")
269
    );
270
}
271
272
#[test]
273
fn name_conflict_resolved_by_removing_a_candidate() {
274
    hermetic();
275
    let dir = tempfile::tempdir().unwrap();
276
    let root = dir.path();
277
    let repo = Repo::init(root).unwrap();
278
    write(root, "keep.txt", b"k\n");
279
    let h1 = repo.commit("base", &[]).unwrap();
280
    write(root, "new.txt", b"one\n");
281
    repo.commit("one", &[]).unwrap();
282
    repo.checkout(&[h1], false, "checkout").unwrap();
283
    write(root, "new.txt", b"two\n");
284
    repo.commit("two", &[]).unwrap();
285
    let r = repo
286
        .checkout(&repo.bookmark_heads().unwrap(), false, "checkout main")
287
        .unwrap();
288
    assert!(r.conflicted);
289
    assert!(
290
        root.join("new.txt.oxy-conflict-1").exists()
291
            && root.join("new.txt.oxy-conflict-2").exists()
292
    );
293
    assert!(!root.join("new.txt").exists());
294
    // Candidate numbering follows change-hash order, so pick by content:
295
    // keep the "two" candidate under the real name and drop the other.
296
    let (keep, drop) = if fs::read(root.join("new.txt.oxy-conflict-1")).unwrap() == b"two\n" {
297
        (1, 2)
298
    } else {
299
        (2, 1)
300
    };
301
    fs::remove_file(root.join(format!("new.txt.oxy-conflict-{drop}"))).unwrap();
302
    fs::rename(
303
        root.join(format!("new.txt.oxy-conflict-{keep}")),
304
        root.join("new.txt"),
305
    )
306
    .unwrap();
307
    let h = repo.commit("pick two", &[]).unwrap();
308
    assert_eq!(
309
        repo.store().get_change(&h).unwrap().kind,
310
        ChangeKind::Resolution
311
    );
312
    // The resolution does not touch keep.txt, so it does not depend on h1;
313
    // the bookmark keeps both as heads and their union is the state.
314
    let heads: BTreeSet<_> = repo.bookmark_heads().unwrap().into_iter().collect();
315
    assert_eq!(heads, [h1, h].into_iter().collect());
316
    let snap = repo
317
        .load_state(&repo.bookmark_heads().unwrap())
318
        .unwrap()
319
        .materialize();
320
    assert!(!snap.is_conflicted(), "{:?}", snap.tree.conflicts);
321
    assert_eq!(
322
        snap.files.keys().cloned().collect::<Vec<_>>(),
323
        ["keep.txt", "new.txt"]
324
    );
325
    assert!(
326
        matches!(&snap.files["new.txt"].content, FileContent::Text { bytes, .. } if bytes == b"two\n")
327
    );
328
}
329
330
#[test]
331
fn identities_and_signed_commits() {
332
    hermetic();
333
    let dir = tempfile::tempdir().unwrap();
334
    let root = dir.path();
335
    let mut repo = Repo::init(root).unwrap().with_home(root.join("home"));
336
    write(root, "a.txt", b"a\n");
337
    let h0 = repo.commit("unsigned", &[]).unwrap();
338
    assert_eq!(repo.verify_change(&h0).unwrap(), SignatureStatus::Unsigned);
339
    assert_eq!(
340
        repo.store().get_change(&h0).unwrap().author,
341
        ObjectRef::ZERO
342
    );
343
344
    let (key, id) = repo
345
        .create_identity("Ada", "[email protected]", IdentityScope::Repo)
346
        .unwrap();
347
    assert_eq!(id.hash(), key);
348
    assert_eq!(repo.config.author_key, Some(key));
349
    // Config survives reopen; the secret key is found again.
350
    let reopened = Repo::open(root).unwrap().with_home(root.join("home"));
351
    assert_eq!(reopened.config.author_key, Some(key));
352
    assert_eq!(reopened.secret_key().unwrap().unwrap().0, key);
353
354
    // Default core.sign = seal: commits carry the author but no signature.
355
    write(root, "a.txt", b"a\nb\n");
356
    let h1 = repo.commit("authored", &[]).unwrap();
357
    assert_eq!(repo.store().get_change(&h1).unwrap().author, key);
358
    assert_eq!(repo.verify_change(&h1).unwrap(), SignatureStatus::Unsigned);
359
    // Signing later works too.
360
    repo.sign_change(&h1).unwrap();
361
    assert!(
362
        matches!(repo.verify_change(&h1).unwrap(), SignatureStatus::Valid { key: k, .. } if k == key)
363
    );
364
365
    repo.config.set("core.sign", "change").unwrap();
366
    repo.save_config().unwrap();
367
    write(root, "a.txt", b"a\nb\nc\n");
368
    let h2 = repo.commit("signed", &[]).unwrap();
369
    assert_eq!(
370
        repo.verify_change(&h2).unwrap(),
371
        SignatureStatus::Valid {
372
            key,
373
            name: "Ada".into(),
374
            email: "[email protected]".into(),
375
            sealed: false,
376
            revoked: false
377
        }
378
    );
379
380
    // A signature by a key that is not the author or a delegate is rejected
381
    // when the change names an author; an anonymous change (made before any
382
    // identity, author zero) is adopted by whoever signs it (spec §14.4).
383
    let other = SecretKey::generate();
384
    let other_id = other.identity("Mallory", "[email protected]", 0);
385
    let other_key = repo.store().put_identity(&other_id).unwrap();
386
    write(root, "a.txt", b"a\nb\nc\nd\n");
387
    repo.config.set("core.sign", "seal").unwrap();
388
    let h3 = repo.commit("ada's, unsigned", &[]).unwrap();
389
    let forged = other.sign(Domain::Change, &other_key, &h3);
390
    repo.store().put_signature(&h3, &forged).unwrap();
391
    assert!(
392
        matches!(repo.verify_change(&h3).unwrap(), SignatureStatus::Invalid(m) if m.contains("neither the author"))
393
    );
394
    let adopted = other.sign(Domain::Change, &other_key, &h0);
395
    repo.store().put_signature(&h0, &adopted).unwrap();
396
    assert!(
397
        matches!(repo.verify_change(&h0).unwrap(), SignatureStatus::Valid { name, .. } if name == "Mallory")
398
    );
399
400
    // Tampering with the stored signature invalidates it.
401
    let mut sig = repo.store().signatures(&h2).unwrap().remove(0);
402
    sig.ed[0] ^= 1;
403
    repo.store().put_signature(&h2, &sig).unwrap();
404
    assert!(matches!(
405
        repo.verify_change(&h2).unwrap(),
406
        SignatureStatus::Invalid(_)
407
    ));
408
409
    // Without the secret key, signing at commit fails cleanly.
410
    let no_keys = Repo::open(root).unwrap().with_home(root.join("nowhere"));
411
    write(root, "a.txt", b"z\n");
412
    assert!(no_keys.commit("cannot sign", &[]).is_err());
413
}
414
415
#[test]
416
fn checkout_moves_the_working_copy() {
417
    hermetic();
418
    let dir = tempfile::tempdir().unwrap();
419
    let root = dir.path();
420
    let repo = Repo::init(root).unwrap();
421
    write(root, "a.txt", b"one\n");
422
    write(root, "sub/deep/b.txt", b"b\n");
423
    let h1 = repo.commit("first", &[]).unwrap();
424
    write(root, "a.txt", b"two\n");
425
    fs::remove_file(root.join("sub/deep/b.txt")).unwrap();
426
    write(root, "bin.dat", &[0, 1, 2, 3]);
427
    let h2 = repo.commit("second", &[]).unwrap();
428
429
    let r = repo.checkout(&[h1], false, "oxy checkout").unwrap();
430
    assert_eq!(
431
        r,
432
        CheckoutReport {
433
            written: 2,
434
            removed: 1,
435
            conflicted: false,
436
            notes: vec![],
437
            lacks: 1,
438
        }
439
    );
440
    assert_eq!(fs::read(root.join("a.txt")).unwrap(), b"one\n");
441
    assert_eq!(fs::read(root.join("sub/deep/b.txt")).unwrap(), b"b\n");
442
    assert!(!root.join("bin.dat").exists());
443
    let (_, wc) = repo.working_copy().unwrap();
444
    assert_eq!(wc.deps, vec![h1]);
445
    assert!(
446
        !repo.snapshot("status").unwrap().changed,
447
        "checkout leaves a clean working copy"
448
    );
449
    // The bookmark still points at h2.
450
    assert_eq!(repo.bookmark_heads().unwrap(), vec![h2]);
451
452
    // Dirty working copy refuses without --discard.
453
    write(root, "a.txt", b"dirty\n");
454
    assert!(repo.checkout(&[h2], false, "oxy checkout").is_err());
455
    let r = repo
456
        .checkout(&[h2], true, "oxy checkout --discard")
457
        .unwrap();
458
    assert_eq!(fs::read(root.join("a.txt")).unwrap(), b"two\n");
459
    assert_eq!(fs::read(root.join("bin.dat")).unwrap(), [0, 1, 2, 3]);
460
    assert!(!root.join("sub").exists(), "empty directories are pruned");
461
    assert_eq!(r.removed, 1);
462
    assert!(!repo.snapshot("status").unwrap().changed);
463
464
    // Refuses to write through a symlinked directory.
465
    #[cfg(unix)]
466
    {
467
        fs::remove_dir_all(root.join("sub")).ok();
468
        std::os::unix::fs::symlink("/tmp", root.join("sub")).unwrap();
469
        assert!(repo.checkout(&[h1], true, "oxy checkout").is_err());
470
    }
471
}
472
473
#[test]
474
fn large_files_are_chunked_and_read_back() {
475
    hermetic();
476
    let dir = tempfile::tempdir().unwrap();
477
    let repo = Repo::init(dir.path()).unwrap();
478
    let mut big = vec![0u8; 700 * 1024];
479
    for (i, b) in big.iter_mut().enumerate() {
480
        *b = (i as u32).wrapping_mul(2654435761).to_le_bytes()[0];
481
    }
482
    let r = repo.store_blob(&big).unwrap();
483
    let blob = Blob::decode(&repo.store().get_typed(&r, ObjectType::Blob).unwrap()).unwrap();
484
    assert!(blob.chunks.len() >= 3, "{}", blob.chunks.len());
485
    assert_eq!(repo.read_blob(&r).unwrap(), big);
486
    assert_eq!(Repo::blob_ref(&big), r);
487
}
488
489
#[test]
490
fn clone_push_pull_with_seals_and_attestations() {
491
    hermetic();
492
    let dir = tempfile::tempdir().unwrap();
493
    let root = dir.path();
494
    let origin_path = root.join("origin");
495
    let origin = Repo::init(&origin_path).unwrap();
496
    let origin_url = origin_path.to_string_lossy().to_string();
497
498
    // A clones, creates an identity (default core.sign = seal), commits, pushes.
499
    let mut a = Repo::clone(&origin_url, &root.join("a"))
500
        .unwrap()
501
        .with_home(root.join("home-a"));
502
    assert_eq!(a.id().unwrap(), origin.id().unwrap());
503
    let (key_a, _) = a
504
        .create_identity("Ada", "[email protected]", IdentityScope::Repo)
505
        .unwrap();
506
    write(&root.join("a"), "f.txt", b"a\n");
507
    let h1 = a.commit("first", &[]).unwrap();
508
    let results = a.push("origin", false).unwrap();
509
    origin.refresh().unwrap();
510
    assert!(results[0].ok, "{}", results[0].reason);
511
    assert_eq!(origin.bookmark_heads().unwrap(), vec![h1]);
512
    // The change was sealed at push and the reference attested.
513
    assert!(
514
        matches!(origin.authenticate_change(&h1).unwrap(), SignatureStatus::Valid { key, sealed: true, .. } if key == key_a)
515
    );
516
    assert_eq!(
517
        origin.verify_change(&h1).unwrap(),
518
        SignatureStatus::Unsigned
519
    );
520
    let serial_of = |att: &SignedAttest| match att.attest.body {
521
        AttestBody::Ref { serial, .. } => serial,
522
        _ => unreachable!(),
523
    };
524
    let (_, att) = origin.latest_ref_attest("main").unwrap().unwrap();
525
    // A bookmark new to the remote starts at the clock (past any deleted
526
    // namesake's serial); later updates count up from there.
527
    let first = serial_of(&att);
528
    assert!(first > 1_000_000_000_000, "{first}");
529
    let again = a.push("origin", false).unwrap();
530
    origin.refresh().unwrap();
531
    assert!(again[0].ok && again[0].reason.contains("up to date"));
532
    let (_, att) = origin.latest_ref_attest("main").unwrap().unwrap();
533
    assert_eq!(serial_of(&att), first, "a no-op push does not attest again");
534
535
    // B clones and sees the file and the seal.
536
    let b = Repo::clone(&origin_url, &root.join("b")).unwrap();
537
    assert_eq!(fs::read(root.join("b/f.txt")).unwrap(), b"a\n");
538
    assert_eq!(b.bookmark_heads().unwrap(), vec![h1]);
539
    assert!(matches!(
540
        b.authenticate_change(&h1).unwrap(),
541
        SignatureStatus::Valid { sealed: true, .. }
542
    ));
543
544
    // B (no identity) commits and pushes unsigned; the unverified origin accepts.
545
    write(&root.join("b"), "f.txt", b"a\nb\n");
546
    let h2 = b.commit("second", &[]).unwrap();
547
    assert!(b.push("origin", false).unwrap()[0].ok);
548
    origin.refresh().unwrap();
549
    assert_eq!(origin.bookmark_heads().unwrap(), vec![h2]);
550
551
    // A commits an independent change; push is refused until A pulls.
552
    write(&root.join("a"), "g.txt", b"g\n");
553
    let h3 = a.commit("third", &[]).unwrap();
554
    assert!(a.push("origin", false).is_err());
555
    let pr = a.pull("origin").unwrap();
556
    assert!(pr.changed && pr.checked_out);
557
    let mut want = vec![h2, h3];
558
    want.sort();
559
    assert_eq!(pr.heads, want);
560
    assert_eq!(fs::read(root.join("a/f.txt")).unwrap(), b"a\nb\n");
561
    assert_eq!(fs::read(root.join("a/g.txt")).unwrap(), b"g\n");
562
    let results = a.push("origin", false).unwrap();
563
    origin.refresh().unwrap();
564
    assert!(results[0].ok, "{}", results[0].reason);
565
    let mut origin_heads = origin.bookmark_heads().unwrap();
566
    origin_heads.sort();
567
    assert_eq!(origin_heads, want);
568
    let (_, att) = origin.latest_ref_attest("main").unwrap().unwrap();
569
    assert_eq!(serial_of(&att), first + 1);
570
571
    // B pulls and ends up identical.
572
    let pr = b.pull("origin").unwrap();
573
    assert_eq!(pr.heads, want);
574
    assert_eq!(fs::read(root.join("b/g.txt")).unwrap(), b"g\n");
575
    assert!(!b.snapshot("status").unwrap().changed);
576
577
    // Concurrent edits of the same line: the union is a reified conflict.
578
    write(&root.join("a"), "f.txt", b"a\nA\n");
579
    a.commit("a-edit", &[]).unwrap();
580
    a.push("origin", false).unwrap();
581
    origin.refresh().unwrap();
582
    write(&root.join("b"), "f.txt", b"a\nB\n");
583
    b.commit("b-edit", &[]).unwrap();
584
    let pr = b.pull("origin").unwrap();
585
    assert!(pr.changed && pr.checked_out);
586
    let text = fs::read_to_string(root.join("b/f.txt")).unwrap();
587
    assert!(text.contains("<<<<<<< oxy conflict"), "{text}");
588
    write(&root.join("b"), "f.txt", b"a\nAB\n");
589
    let hr = b.commit("resolve", &[]).unwrap();
590
    assert_eq!(
591
        b.store().get_change(&hr).unwrap().kind,
592
        ChangeKind::Resolution
593
    );
594
    assert!(b.push("origin", false).unwrap()[0].ok);
595
    origin.refresh().unwrap();
596
    a.pull("origin").unwrap();
597
    assert_eq!(fs::read(root.join("a/f.txt")).unwrap(), b"a\nAB\n");
598
    // The resolution depends on the conflicting edits, but nothing depends
599
    // on "third" (it only added g.txt), so it stays a head beside it.
600
    let mut want = vec![hr, h3];
601
    want.sort();
602
    assert_eq!(a.bookmark_heads().unwrap(), want);
603
    assert!(!a.load_state(&want).unwrap().materialize().is_conflicted());
604
}
605
606
#[test]
607
fn receive_push_rejects_bad_updates() {
608
    hermetic();
609
    let dir = tempfile::tempdir().unwrap();
610
    let root = dir.path();
611
    let origin = Repo::init(&root.join("origin")).unwrap();
612
    let url = root.join("origin").to_string_lossy().to_string();
613
    let mut a = Repo::clone(&url, &root.join("a"))
614
        .unwrap()
615
        .with_home(root.join("home"));
616
    let (key, _) = a
617
        .create_identity("Ada", "a@b", IdentityScope::Repo)
618
        .unwrap();
619
    write(&root.join("a"), "f.txt", b"x\n");
620
    let h1 = a.commit("one", &[]).unwrap();
621
    assert!(a.push("origin", false).unwrap()[0].ok);
622
    let empty = origin.store().put_state(&StateObject::new(vec![])).unwrap();
623
    let s1 = origin
624
        .store()
625
        .put_state(&StateObject::new(vec![h1]))
626
        .unwrap();
627
628
    // Missing head.
629
    let ghost = origin
630
        .store()
631
        .put_state(&StateObject::new(vec![ObjectRef([9; 32])]))
632
        .unwrap();
633
    let r = origin
634
        .receive_push(
635
            Bundle::default(),
636
            vec![RefUpdate {
637
                name: "main".into(),
638
                old_state: s1,
639
                new_state: ghost,
640
                force: false,
641
                attestation: None,
642
            }],
643
            None,
644
            vec![],
645
        )
646
        .unwrap();
647
    assert!(
648
        !r[0].ok && r[0].reason.contains("missing"),
649
        "{}",
650
        r[0].reason
651
    );
652
653
    // Stale old_state.
654
    let r = origin
655
        .receive_push(
656
            Bundle::default(),
657
            vec![RefUpdate {
658
                name: "main".into(),
659
                old_state: empty,
660
                new_state: s1,
661
                force: false,
662
                attestation: None,
663
            }],
664
            None,
665
            vec![],
666
        )
667
        .unwrap();
668
    assert!(!r[0].ok && r[0].reason.contains("stale"), "{}", r[0].reason);
669
670
    // Non-fast-forward without force is refused; with force it passes.
671
    let r = origin
672
        .receive_push(
673
            Bundle::default(),
674
            vec![RefUpdate {
675
                name: "main".into(),
676
                old_state: s1,
677
                new_state: empty,
678
                force: false,
679
                attestation: None,
680
            }],
681
            None,
682
            vec![],
683
        )
684
        .unwrap();
685
    assert!(
686
        !r[0].ok && r[0].reason.contains("fast-forward"),
687
        "{}",
688
        r[0].reason
689
    );
690
    let r = origin
691
        .receive_push(
692
            Bundle::default(),
693
            vec![RefUpdate {
694
                name: "main".into(),
695
                old_state: s1,
696
                new_state: empty,
697
                force: true,
698
                attestation: None,
699
            }],
700
            None,
701
            vec![],
702
        )
703
        .unwrap();
704
    assert!(r[0].ok);
705
    assert_eq!(origin.bookmark_heads().unwrap(), vec![]);
706
707
    // Attestation with a stale serial is a rollback and is refused.
708
    let sa = a
709
        .sign_attest(&Attest {
710
            repo: a.id().unwrap(),
711
            hlc: Hlc::now(),
712
            body: AttestBody::Ref {
713
                name: "main".into(),
714
                old_state: empty,
715
                new_state: s1,
716
                serial: 1,
717
            },
718
        })
719
        .unwrap();
720
    let r = origin
721
        .receive_push(
722
            Bundle::default(),
723
            vec![RefUpdate {
724
                name: "main".into(),
725
                old_state: empty,
726
                new_state: s1,
727
                force: false,
728
                attestation: Some(sa.clone()),
729
            }],
730
            None,
731
            vec![],
732
        )
733
        .unwrap();
734
    assert!(
735
        !r[0].ok && r[0].reason.contains("serial"),
736
        "{}",
737
        r[0].reason
738
    );
739
    // An attestation for a different update is refused too.
740
    let sa2 = a
741
        .sign_attest(&Attest {
742
            repo: a.id().unwrap(),
743
            hlc: Hlc::now(),
744
            body: AttestBody::Ref {
745
                name: "main".into(),
746
                old_state: s1,
747
                new_state: empty,
748
                serial: 5,
749
            },
750
        })
751
        .unwrap();
752
    let r = origin
753
        .receive_push(
754
            Bundle::default(),
755
            vec![RefUpdate {
756
                name: "main".into(),
757
                old_state: empty,
758
                new_state: s1,
759
                force: false,
760
                attestation: Some(sa2),
761
            }],
762
            None,
763
            vec![],
764
        )
765
        .unwrap();
766
    assert!(
767
        !r[0].ok && r[0].reason.contains("describe"),
768
        "{}",
769
        r[0].reason
770
    );
771
    let _ = key;
772
}
773
774
#[test]
775
fn user_config_supplies_defaults_and_clones_sign() {
776
    hermetic();
777
    let dir = tempfile::tempdir().unwrap();
778
    let root = dir.path();
779
    let home = root.join("home");
780
    let origin = Repo::init(&root.join("origin")).unwrap();
781
    let url = root.join("origin").to_string_lossy().to_string();
782
783
    // Identity at user scope: the repository file stays free of author keys.
784
    let mut a = Repo::init(&root.join("a")).unwrap().with_home(&home);
785
    let (key, _) = a
786
        .create_identity("Ada", "[email protected]", IdentityScope::User)
787
        .unwrap();
788
    assert!(!a.config.repo_layer().contains_key("author.key"));
789
    assert_eq!(a.config.author_key, Some(key));
790
    assert!(home.join("config.toml").exists());
791
    a.set_user_config("core.sign", "change").unwrap();
792
    assert!(a.config.sign_changes);
793
794
    // Repository settings override user settings and are the only ones saved.
795
    a.config.set("core.sign", "seal").unwrap();
796
    a.save_config().unwrap();
797
    let again = Repo::open(&root.join("a")).unwrap().with_home(&home);
798
    assert!(!again.config.sign_changes);
799
    assert_eq!(again.config.author_key, Some(key));
800
    assert_eq!(
801
        read_config_file(&root.join("a/.oxy/config"))
802
            .unwrap()
803
            .get("core.sign")
804
            .map(String::as_str),
805
        Some("seal")
806
    );
807
808
    // A fresh clone made by this user signs with the user-level identity,
809
    // even though the clone's store has never seen the identity object.
810
    let b = Repo::clone(&url, &root.join("b")).unwrap().with_home(&home);
811
    assert!(b.config.sign_changes);
812
    write(&root.join("b"), "f.txt", b"f\n");
813
    let h = b.commit("signed from a clone", &[]).unwrap();
814
    assert!(
815
        matches!(b.verify_change(&h).unwrap(), SignatureStatus::Valid { key: k, .. } if k == key)
816
    );
817
    assert!(b.push("origin", false).unwrap()[0].ok);
818
    assert!(matches!(
819
        origin.verify_change(&h).unwrap(),
820
        SignatureStatus::Valid { .. }
821
    ));
822
}
823
824
#[test]
825
fn format1_repositories_are_migrated_on_open() {
826
    hermetic();
827
    use crate::oplog::{Format1Op, Format1View};
828
    let dir = tempfile::tempdir().unwrap();
829
    let root = dir.path();
830
    let repo = Repo::init(root).unwrap();
831
    write(root, "a.txt", b"a\n");
832
    let h1 = repo.commit("one", &[]).unwrap();
833
    let (wc_hash, _) = repo.working_copy().unwrap();
834
    // Rewrite the op log the way format 1 stored it: two ops, head lists.
835
    let mut v1 = Format1View::default();
836
    v1.bookmarks.insert("main".into(), vec![]);
837
    v1.workspaces.insert(repo.workspace(), wc_hash);
838
    let init = Format1Op {
839
        parents: vec![],
840
        hlc: Hlc::default(),
841
        command: "oxy init".into(),
842
        view: v1.clone(),
843
    };
844
    let init_ref = repo.store().put(ObjectType::Op, &init.encode()).unwrap();
845
    v1.bookmarks.insert("main".into(), vec![h1]);
846
    let commit = Format1Op {
847
        parents: vec![init_ref],
848
        hlc: Hlc::default(),
849
        command: "oxy commit".into(),
850
        view: v1,
851
    };
852
    let commit_ref = repo.store().put(ObjectType::Op, &commit.encode()).unwrap();
853
    write_atomic(&root.join(".oxy/ops/head"), commit_ref.to_hex().as_bytes()).unwrap();
854
    write_atomic(&root.join(".oxy/format"), FORMAT1_LINE.as_bytes()).unwrap();
855
    drop(repo);
856
857
    let repo = Repo::open(root).unwrap();
858
    assert_eq!(
859
        fs::read_to_string(root.join(".oxy/format")).unwrap(),
860
        FORMAT_LINE
861
    );
862
    assert_eq!(repo.bookmark_heads().unwrap(), vec![h1]);
863
    let ops = repo.op_log().unwrap();
864
    assert_eq!(
865
        ops.iter()
866
            .map(|(_, o)| o.command.as_str())
867
            .collect::<Vec<_>>(),
868
        ["oxy commit", "oxy init"]
869
    );
870
    assert_eq!(repo.heads_of(&ops[1].1.view, "main").unwrap(), vec![]);
871
    assert!(!repo.snapshot("status").unwrap().changed);
872
    // Reopening again is a no-op.
873
    assert_eq!(Repo::open(root).unwrap().op_log().unwrap().len(), 2);
874
}
875
876
#[test]
877
fn undo_skips_snapshot_operations() {
878
    hermetic();
879
    let dir = tempfile::tempdir().unwrap();
880
    let root = dir.path();
881
    let repo = Repo::init(root).unwrap();
882
    write(root, "a.txt", b"a\n");
883
    let h1 = repo.commit("a", &[]).unwrap();
884
    // A later command snapshots new edits on top of the commit.
885
    write(root, "b.txt", b"b\n");
886
    let s = repo.snapshot("oxy status").unwrap();
887
    assert!(s.changed);
888
    assert!(repo.head_op().unwrap().1.is_snapshot());
889
    assert_eq!(repo.last_command().unwrap().command, "oxy commit -m \"a\"");
890
    // Undo must undo the commit, not the snapshot.
891
    repo.undo().unwrap();
892
    assert_eq!(repo.bookmark_heads().unwrap(), vec![]);
893
    let s = repo.snapshot("oxy status").unwrap();
894
    let paths: Vec<_> = s.statuses.iter().map(|p| p.path.as_str()).collect();
895
    assert_eq!(
896
        paths,
897
        ["a.txt", "b.txt"],
898
        "both files are back in the working copy"
899
    );
900
    assert!(repo.store().get_change(&h1).unwrap().deps.is_empty());
901
    // Only snapshots remain above `init`, so there is nothing left to undo.
902
    assert_eq!(repo.last_command().unwrap().command, "oxy init");
903
    assert!(repo.undo().is_err());
904
}
905
906
#[test]
907
fn independent_changes_commute_and_make_multiple_heads() {
908
    hermetic();
909
    let dir = tempfile::tempdir().unwrap();
910
    let root = dir.path();
911
    let repo = Repo::init(root).unwrap();
912
    write(root, "a.txt", b"a\n");
913
    let h1 = repo.commit("a", &[]).unwrap();
914
    write(root, "b.txt", b"b\n");
915
    let h2 = repo.commit("b", &[]).unwrap();
916
    let c2 = repo.store().get_change(&h2).unwrap();
917
    assert!(c2.deps.is_empty(), "b.txt touches nothing from h1");
918
    let mut heads = repo.bookmark_heads().unwrap();
919
    heads.sort();
920
    let mut want = vec![h1, h2];
921
    want.sort();
922
    assert_eq!(heads, want);
923
    // Editing a.txt depends on h1 only.
924
    write(root, "a.txt", b"a\na2\n");
925
    let h3 = repo.commit("a2", &[]).unwrap();
926
    assert_eq!(repo.store().get_change(&h3).unwrap().deps, vec![h1]);
927
    let heads: BTreeSet<_> = repo.bookmark_heads().unwrap().into_iter().collect();
928
    assert_eq!(heads, [h2, h3].into_iter().collect());
929
    // Explicit dependency.
930
    write(root, "c.txt", b"c\n");
931
    let h4 = repo.commit("c", &[h2]).unwrap();
932
    assert_eq!(repo.store().get_change(&h4).unwrap().deps, vec![h2]);
933
}
934
935
#[test]
936
fn mode_change_and_text_binary_switch() {
937
    hermetic();
938
    let dir = tempfile::tempdir().unwrap();
939
    let root = dir.path();
940
    let repo = Repo::init(root).unwrap();
941
    write(root, "run.sh", b"#!/bin/sh\n");
942
    repo.commit("add script", &[]).unwrap();
943
    #[cfg(unix)]
944
    {
945
        use std::os::unix::fs::PermissionsExt;
946
        fs::set_permissions(root.join("run.sh"), fs::Permissions::from_mode(0o755)).unwrap();
947
        let s = repo.snapshot("status").unwrap();
948
        assert_eq!(
949
            statuses(&s),
950
            vec![("run.sh".into(), ChangeStatus::ModeChanged)]
951
        );
952
        let h = repo.commit("exec", &[]).unwrap();
953
        let snap = repo.load_state(&[h]).unwrap().materialize();
954
        assert!(snap.files["run.sh"].mode.exec);
955
    }
956
    // Text → binary → text.
957
    write(root, "run.sh", b"\0binary");
958
    let h = repo.commit("binary", &[]).unwrap();
959
    let snap = repo.load_state(&[h]).unwrap().materialize();
960
    assert!(snap.files["run.sh"].mode.opaque);
961
    write(root, "run.sh", b"text again\n");
962
    let h = repo.commit("text", &[]).unwrap();
963
    let snap = repo.load_state(&[h]).unwrap().materialize();
964
    assert!(!snap.files["run.sh"].mode.opaque);
965
    assert!(
966
        matches!(&snap.files["run.sh"].content, FileContent::Text { bytes, .. } if bytes == b"text again\n")
967
    );
968
    assert!(!snap.is_conflicted());
969
}
970
971
#[test]
972
fn trust_policy_governs_pushes_and_fetches() {
973
    hermetic();
974
    let dir = tempfile::tempdir().unwrap();
975
    let root = dir.path();
976
    let origin = Repo::init(&root.join("origin")).unwrap();
977
    let url = root.join("origin").to_string_lossy().to_string();
978
979
    // A is the root. Before the policy, an unsigned push from B is fine.
980
    let mut a = Repo::clone(&url, &root.join("a"))
981
        .unwrap()
982
        .with_home(root.join("home-a"));
983
    let (key_a, _) = a
984
        .create_identity("Ada", "[email protected]", IdentityScope::User)
985
        .unwrap();
986
    let mut b = Repo::clone(&url, &root.join("b"))
987
        .unwrap()
988
        .with_home(root.join("home-b"));
989
    write(&root.join("b"), "b.txt", b"b\n");
990
    b.commit("unsigned before policy", &[]).unwrap();
991
    assert!(b.push("origin", false).unwrap()[0].ok);
992
    origin.refresh().unwrap();
993
994
    // A creates the policy and pushes it; origin now enforces it.
995
    write(&root.join("a"), "a.txt", b"a\n");
996
    a.commit("a", &[]).unwrap();
997
    let sp = a.policy_init().unwrap();
998
    assert_eq!(sp.policy.serial, 1);
999
    a.pull("origin").unwrap();
1000
    let results = a.push("origin", false).unwrap();
1001
    origin.refresh().unwrap();
1002
    assert!(results.iter().all(|r| r.ok), "{results:?}");
1003
    assert_eq!(origin.current_policy().unwrap().unwrap().1.policy.serial, 1);
1004
1005
    // B pulls the policy. Without an identity B cannot push at all.
1006
    b.pull("origin").unwrap();
1007
    assert!(
1008
        b.current_policy().unwrap().is_some(),
1009
        "the policy arrived with the fetch"
1010
    );
1011
    assert!(b.push("origin", false).is_err());
1012
    // With an identity the policy does not list, the push is rejected by origin.
1013
    let (key_b, id_b) = b
1014
        .create_identity("Bob", "[email protected]", IdentityScope::User)
1015
        .unwrap();
1016
    write(&root.join("b"), "b.txt", b"b2\n");
1017
    let h_b2 = b.commit("b2 as Bob", &[]).unwrap();
1018
    assert_eq!(b.store().get_change(&h_b2).unwrap().author, key_b);
1019
    let r = b.push("origin", false).unwrap();
1020
    origin.refresh().unwrap();
1021
    assert!(
1022
        !r[0].ok && r[0].reason.contains("may not update"),
1023
        "{:?}",
1024
        r
1025
    );
1026
1027
    // A grants B (identity handed over as a file) and publishes the policy.
1028
    let sp = a.policy_grant(id_b.clone(), None).unwrap();
1029
    assert_eq!(sp.policy.serial, 2);
1030
    let r = a.push("origin", false).unwrap();
1031
    origin.refresh().unwrap();
1032
    assert!(r.iter().any(|x| x.name == "policy" && x.ok), "{r:?}");
1033
    // B must fetch the new policy before pushing.
1034
    assert!(b
1035
        .push("origin", false)
1036
        .unwrap_or_else(|e| vec![RefResult {
1037
            name: "main".into(),
1038
            ok: false,
1039
            reason: e.to_string()
1040
        }])
1041
        .iter()
1042
        .all(|x| !x.ok));
1043
    b.pull("origin").unwrap();
1044
    assert_eq!(b.current_policy().unwrap().unwrap().1.policy.serial, 2);
1045
    let r = b.push("origin", false).unwrap();
1046
    origin.refresh().unwrap();
1047
    assert!(r[0].ok, "{:?}", r);
1048
    // Origin verified B's change under the policy.
1049
    let heads = origin.bookmark_heads().unwrap();
1050
    for h in &heads {
1051
        let c = origin.store().get_change(h).unwrap();
1052
        if c.author == key_b {
1053
            origin
1054
                .change_allowed(
1055
                    h,
1056
                    &origin.current_policy().unwrap().unwrap().1.policy,
1057
                    "main",
1058
                )
1059
                .unwrap();
1060
        }
1061
    }
1062
1063
    // A policy signed by a non-root (B) is refused, as is a replayed serial.
1064
    let mut forged = b.current_policy().unwrap().unwrap().1.policy.clone();
1065
    forged.serial = 3;
1066
    forged.roots = vec![key_b];
1067
    let fh = forged.hash();
1068
    let (_, sk_b) = b.secret_key().unwrap().unwrap();
1069
    let forged = SignedPolicy {
1070
        policy: forged,
1071
        sigs: vec![sk_b.sign(Domain::Policy, &key_b, &fh)],
1072
    };
1073
    let r = origin
1074
        .receive_push(Bundle::default(), vec![], Some(forged), vec![])
1075
        .unwrap();
1076
    assert!(!r[0].ok && r[0].reason.contains("root"), "{:?}", r);
1077
    let stale = a.current_policy().unwrap().unwrap().1;
1078
    let mut old = stale.clone();
1079
    old.policy.serial = 1;
1080
    let r = origin
1081
        .receive_push(Bundle::default(), vec![], Some(old), vec![])
1082
        .unwrap();
1083
    assert!(!r[0].ok && r[0].reason.contains("serial"), "{:?}", r);
1084
1085
    // A revokes B; after B pulls the policy, B's pushes are refused again.
1086
    a.pull("origin").unwrap();
1087
    a.policy_revoke(&key_b).unwrap();
1088
    let r = a.push("origin", false).unwrap();
1089
    origin.refresh().unwrap();
1090
    assert!(r.iter().any(|x| x.name == "policy" && x.ok), "{r:?}");
1091
    b.pull("origin").unwrap();
1092
    write(&root.join("b"), "b.txt", b"b3\n");
1093
    b.commit("b3", &[]).unwrap();
1094
    let r = b.push("origin", false).unwrap();
1095
    origin.refresh().unwrap();
1096
    assert!(!r[0].ok, "{:?}", r);
1097
1098
    // A clone by a third party receives and verifies everything.
1099
    let c = Repo::clone(&url, &root.join("c"))
1100
        .unwrap()
1101
        .with_home(root.join("home-c"));
1102
    assert_eq!(c.current_policy().unwrap().unwrap().1.policy.serial, 3);
1103
    assert!(c
1104
        .current_policy()
1105
        .unwrap()
1106
        .unwrap()
1107
        .1
1108
        .policy
1109
        .roots
1110
        .contains(&key_a));
1111
    assert!(!c.snapshot("status").unwrap().changed);
1112
}
1113
1114
/// oxygen#66: a gc says what it is doing, phase by phase.
1115
#[test]
1116
fn gc_reports_its_phases() {
1117
    hermetic();
1118
    let dir = tempfile::tempdir().unwrap();
1119
    let repo = Repo::init(dir.path()).unwrap();
1120
    for i in 0..3 {
1121
        write(
1122
            dir.path(),
1123
            &format!("f{i}.txt"),
1124
            format!("{i}\n").as_bytes(),
1125
        );
1126
        repo.commit(&format!("c{i}"), &[]).unwrap();
1127
    }
1128
    let mut phases = Vec::new();
1129
    repo.gc_with(true, &mut |p| phases.push(p.to_string()))
1130
        .unwrap();
1131
    assert_eq!(phases[0], "finding what is reachable", "{phases:?}");
1132
    assert!(
1133
        phases.iter().any(|p| p.starts_with("pruning")),
1134
        "{phases:?}"
1135
    );
1136
    assert!(
1137
        phases.iter().any(|p| p.starts_with("packing 0 of ")),
1138
        "{phases:?}"
1139
    );
1140
    assert!(
1141
        phases
1142
            .iter()
1143
            .any(|p| p.starts_with("writing the index of ")),
1144
        "{phases:?}"
1145
    );
1146
}
1147
1148
#[test]
1149
fn gc_packs_objects_and_history_still_works() {
1150
    hermetic();
1151
    let dir = tempfile::tempdir().unwrap();
1152
    let root = dir.path();
1153
    let mut repo = Repo::init(root).unwrap().with_home(root.join("home"));
1154
    repo.create_identity("Ada", "a@b", IdentityScope::User)
1155
        .unwrap();
1156
    repo.set_user_config("core.sign", "change").unwrap();
1157
    write(root, "a.txt", b"one\n");
1158
    let h1 = repo.commit("one", &[]).unwrap();
1159
    write(root, "a.txt", b"two\n");
1160
    write(root, "big.bin", &vec![0u8; 100_000]);
1161
    let h2 = repo.commit("two", &[]).unwrap();
1162
    // Several snapshots leave superseded working-copy versions behind.
1163
    for i in 0..5 {
1164
        write(root, "a.txt", format!("two\n{i}\n").as_bytes());
1165
        repo.snapshot("status").unwrap();
1166
    }
1167
    write(root, "a.txt", b"two\n");
1168
    repo.snapshot("status").unwrap();
1169
    let before = repo.store().list().unwrap();
1170
    assert!(repo.store().loose_count().unwrap() > 0);
1171
1172
    // With the default retention every operation's view is a root: nothing prunes.
1173
    let r = repo.gc(true).unwrap();
1174
    assert_eq!(r.packed.objects, before.len());
1175
    assert_eq!(r.pruned.objects, 0);
1176
    assert_eq!(repo.store().loose_count().unwrap(), 0);
1177
    assert_eq!(repo.store().list().unwrap(), before);
1178
1179
    // With zero retention only the current view is a root: superseded
1180
    // working copies go, everything reachable stays.
1181
    repo.config.set("core.op-retention", "0").unwrap();
1182
    repo.save_config().unwrap();
1183
    let mut repo = Repo::open(root).unwrap().with_home(root.join("home"));
1184
    let r = repo.gc(true).unwrap();
1185
    assert!(r.pruned.objects >= 5, "{r:?}");
1186
    let after = repo.store().list().unwrap();
1187
    assert!(after.len() < before.len());
1188
    assert!(after.contains(&h1) && after.contains(&h2));
1189
    for (_, op) in repo.op_log().unwrap() {
1190
        assert!(!op.command.is_empty(), "operation objects are all kept");
1191
    }
1192
    // Everything still works from the pruned, packed store.
1193
    assert_eq!(repo.bookmark_heads().unwrap(), vec![h2]);
1194
    assert!(matches!(
1195
        repo.verify_change(&h2).unwrap(),
1196
        SignatureStatus::Valid { .. }
1197
    ));
1198
    assert_eq!(repo.log().unwrap().len(), 3);
1199
    repo.checkout(&[h1], false, "checkout").unwrap();
1200
    assert_eq!(fs::read(root.join("a.txt")).unwrap(), b"one\n");
1201
    repo.checkout(&[h2], false, "checkout").unwrap();
1202
    assert_eq!(fs::read(root.join("big.bin")).unwrap().len(), 100_000);
1203
    assert!(!repo.snapshot("status").unwrap().changed);
1204
    // Grace period defers pruning of young garbage.
1205
    write(root, "a.txt", b"three\n");
1206
    repo.commit("three", &[]).unwrap();
1207
    let r = repo.gc(false).unwrap();
1208
    assert_eq!(r.pruned.objects, 0);
1209
    assert!(r.pruned.deferred > 0);
1210
    let r = repo.gc(true).unwrap();
1211
    assert!(r.pruned.objects > 0);
1212
    assert_eq!(repo.log().unwrap().len(), 4);
1213
    // Restoring the default retention makes the old views roots again; the
1214
    // working copies they name were pruned, which gc tolerates.
1215
    repo.config.set("core.op-retention", "90").unwrap();
1216
    repo.save_config().unwrap();
1217
    let repo = Repo::open(root).unwrap().with_home(root.join("home"));
1218
    let r = repo.gc(false).unwrap();
1219
    assert_eq!(r.pruned.objects, 0);
1220
    assert_eq!(repo.log().unwrap().len(), 4);
1221
}
1222
1223
#[test]
1224
fn describe_amend_abandon_heads() {
1225
    hermetic();
1226
    let dir = tempfile::tempdir().unwrap();
1227
    let root = dir.path();
1228
    let mut repo = Repo::init(root).unwrap().with_home(root.join("home"));
1229
    repo.create_identity("Ada", "a@b", IdentityScope::User)
1230
        .unwrap();
1231
    repo.set_user_config("core.sign", "change").unwrap();
1232
    write(root, "a.txt", b"one\n");
1233
    let h1 = repo.commit("first", &[]).unwrap();
1234
    write(root, "a.txt", b"one\ntwo\n");
1235
    let h2 = repo.commit("secnod", &[]).unwrap();
1236
    let id2 = repo.store().get_change(&h2).unwrap().change_id;
1237
1238
    // describe: same ChangeId, new hash, bookmark and working copy follow.
1239
    let h2b = repo.describe(&h2, "second").unwrap();
1240
    assert_ne!(h2b, h2);
1241
    let c = repo.store().get_change(&h2b).unwrap();
1242
    assert_eq!(
1243
        (c.change_id, c.message.as_str(), c.deps.clone()),
1244
        (id2, "second", vec![h1])
1245
    );
1246
    assert_eq!(repo.bookmark_heads().unwrap(), vec![h2b]);
1247
    assert!(matches!(
1248
        repo.verify_change(&h2b).unwrap(),
1249
        SignatureStatus::Valid { .. }
1250
    ));
1251
    let s = repo.snapshot("status").unwrap();
1252
    assert!(s.statuses.is_empty(), "{:?}", s.statuses);
1253
    assert_eq!(
1254
        repo.resolve_change(&id2.short(8)).unwrap(),
1255
        h2b,
1256
        "the old object is no longer reachable from the log"
1257
    );
1258
    // Describing a non-head rewrites its dependents (h2b → h2c') and the working copy.
1259
    let h1b = repo.describe(&h1, "first, described").unwrap();
1260
    assert_ne!(h1b, h1);
1261
    let heads = repo.bookmark_heads().unwrap();
1262
    assert_eq!(heads.len(), 1);
1263
    let top = repo.store().get_change(&heads[0]).unwrap();
1264
    assert_eq!((top.change_id, top.deps.clone()), (id2, vec![h1b]));
1265
    assert!(
1266
        matches!(
1267
            repo.verify_change(&heads[0]).unwrap(),
1268
            SignatureStatus::Valid { .. }
1269
        ),
1270
        "rewritten own change is re-signed"
1271
    );
1272
    let (_, wc) = repo.working_copy().unwrap();
1273
    assert_eq!(
1274
        wc.deps,
1275
        vec![heads[0]],
1276
        "the working copy follows the rewrite"
1277
    );
1278
    assert!(!repo.snapshot("status").unwrap().changed);
1279
    let snap = repo.load_state(&heads).unwrap().materialize();
1280
    assert!(
1281
        matches!(&snap.files["a.txt"].content, FileContent::Text { bytes, .. } if bytes == b"one\ntwo\n")
1282
    );
1283
1284
    // amend: fold an edit into the head; the result is one change from h1.
1285
    write(root, "a.txt", b"one\ntwo\nthree\n");
1286
    write(root, "b.txt", b"b\n");
1287
    let h2c = repo.amend(None).unwrap();
1288
    let c = repo.store().get_change(&h2c).unwrap();
1289
    assert_eq!(c.change_id, id2);
1290
    assert_eq!(c.message, "second");
1291
    assert_eq!(repo.bookmark_heads().unwrap(), vec![h2c]);
1292
    assert_eq!(
1293
        repo.log().unwrap().len(),
1294
        3,
1295
        "working copy, amended head, first"
1296
    );
1297
    let snap = repo.load_state(&[h2c]).unwrap().materialize();
1298
    assert!(
1299
        matches!(&snap.files["a.txt"].content, FileContent::Text { bytes, .. } if bytes == b"one\ntwo\nthree\n")
1300
    );
1301
    assert!(snap.files.contains_key("b.txt"));
1302
    assert!(!repo.snapshot("status").unwrap().changed);
1303
    assert!(
1304
        repo.amend(None).is_err(),
1305
        "clean working copy and no message"
1306
    );
1307
    let h2d = repo.amend(Some("second, amended")).unwrap();
1308
    assert_eq!(
1309
        repo.store().get_change(&h2d).unwrap().message,
1310
        "second, amended"
1311
    );
1312
1313
    // abandon: the head goes, its content stays as uncommitted work.
1314
    repo.abandon(&h2d).unwrap();
1315
    assert_eq!(
1316
        repo.bookmark_heads().unwrap(),
1317
        vec![h1b],
1318
        "the described first change is the head again"
1319
    );
1320
    let s = repo.snapshot("status").unwrap();
1321
    let paths: Vec<_> = s
1322
        .statuses
1323
        .iter()
1324
        .map(|p| (p.path.as_str(), p.status))
1325
        .collect();
1326
    assert_eq!(
1327
        paths,
1328
        vec![
1329
            ("a.txt", ChangeStatus::Modified),
1330
            ("b.txt", ChangeStatus::Added)
1331
        ]
1332
    );
1333
    assert_eq!(fs::read(root.join("a.txt")).unwrap(), b"one\ntwo\nthree\n");
1334
    let h3 = repo.commit("recommitted", &[]).unwrap();
1335
    assert_eq!(repo.bookmark_heads().unwrap(), vec![h3]);
1336
    // undo brings the abandoned head back.
1337
    repo.undo().unwrap();
1338
    repo.undo().unwrap();
1339
    assert_eq!(repo.bookmark_heads().unwrap(), vec![h2d]);
1340
1341
    // Abandoning a non-head whose dependent references its atoms reifies
1342
    // the references (here: a.txt vanishes with it, so the dependent's edit
1343
    // of a.txt is dropped with a note) instead of refusing; undo restores it.
1344
    let base = repo.bookmark_heads().unwrap()[0];
1345
    let base_change = repo.store().get_change(&base).unwrap();
1346
    let h1_now = base_change.deps[0];
1347
    let notes = repo.abandon(&h1_now).unwrap();
1348
    assert!(
1349
        !notes.is_empty(),
1350
        "the dependent's edit of a.txt was reified"
1351
    );
1352
    let heads = repo.bookmark_heads().unwrap();
1353
    let after = repo.load_state(&heads).unwrap().materialize();
1354
    assert!(
1355
        !after.files.contains_key("a.txt") && after.files.contains_key("b.txt"),
1356
        "{:?}",
1357
        after.files.keys()
1358
    );
1359
    repo.undo().unwrap();
1360
    assert_eq!(repo.bookmark_heads().unwrap(), vec![base]);
1361
    write(root, "c.txt", b"c\n");
1362
    let hc = repo.commit("c", &[]).unwrap();
1363
    write(root, "d.txt", b"d\n");
1364
    let hd = repo.commit("d", &[hc]).unwrap();
1365
    assert_eq!(repo.store().get_change(&hd).unwrap().deps, vec![hc]);
1366
    repo.abandon(&hc).unwrap();
1367
    let heads: BTreeSet<_> = repo.bookmark_heads().unwrap().into_iter().collect();
1368
    assert!(!heads.contains(&hc));
1369
    let d_now = heads
1370
        .iter()
1371
        .find(|h| repo.store().get_change(h).unwrap().message == "d")
1372
        .copied()
1373
        .unwrap();
1374
    assert!(
1375
        repo.store().get_change(&d_now).unwrap().deps.is_empty(),
1376
        "d inherited c's (empty) dependencies"
1377
    );
1378
    let s = repo.snapshot("status").unwrap();
1379
    assert_eq!(
1380
        s.statuses
1381
            .iter()
1382
            .map(|p| p.path.as_str())
1383
            .collect::<Vec<_>>(),
1384
        vec!["c.txt"],
1385
        "c's content is now uncommitted work"
1386
    );
1387
}
1388
1389
#[test]
1390
fn git_export_mirrors_history() {
1391
    hermetic();
1392
    if std::process::Command::new("git")
1393
        .arg("--version")
1394
        .output()
1395
        .is_err()
1396
    {
1397
        eprintln!("git not installed; skipping");
1398
        return;
1399
    }
1400
    let dir = tempfile::tempdir().unwrap();
1401
    let root = dir.path();
1402
    let mut repo = Repo::init(&root.join("r"))
1403
        .unwrap()
1404
        .with_home(root.join("home"));
1405
    repo.create_identity("Ada Lovelace", "[email protected]", IdentityScope::User)
1406
        .unwrap();
1407
    let r = root.join("r");
1408
    write(&r, "README.md", b"hello\n");
1409
    write(&r, "src/main.rs", b"fn main() {}\n");
1410
    let h1 = repo.commit("first", &[]).unwrap();
1411
    write(&r, "src/main.rs", b"fn main() { run(); }\n");
1412
    write(&r, "logo.png", b"\x89PNG\0\0");
1413
    let h2 = repo.commit("second", &[]).unwrap();
1414
1415
    let git_dir = root.join("mirror.git");
1416
    let rep = repo.git_export(&git_dir).unwrap();
1417
    assert_eq!((rep.exported, rep.skipped, rep.heads), (2, 0, 1));
1418
    let git = |args: &[&str]| -> String {
1419
        let out = std::process::Command::new("git")
1420
            .arg("-C")
1421
            .arg(&git_dir)
1422
            .args(args)
1423
            .output()
1424
            .unwrap();
1425
        assert!(
1426
            out.status.success(),
1427
            "{}",
1428
            String::from_utf8_lossy(&out.stderr)
1429
        );
1430
        String::from_utf8_lossy(&out.stdout).trim().to_string()
1431
    };
1432
    assert_eq!(git(&["log", "--format=%s", "main"]), "second\nfirst");
1433
    assert_eq!(git(&["show", "main:src/main.rs"]), "fn main() { run(); }");
1434
    assert_eq!(git(&["show", "main:README.md"]), "hello");
1435
    let body = git(&["log", "-1", "--format=%B", "main"]);
1436
    assert!(
1437
        body.contains(&format!("Oxy-Hash: {}", h2.to_hex())),
1438
        "{body}"
1439
    );
1440
    assert!(body.contains("Change-Id: "), "{body}");
1441
    assert_eq!(
1442
        git(&["log", "-1", "--format=%an <%ae>", "main"]),
1443
        "Ada Lovelace <[email protected]>"
1444
    );
1445
    assert_eq!(
1446
        git(&["ls-tree", "--name-only", "main"]),
1447
        "README.md\nlogo.png\nsrc"
1448
    );
1449
1450
    // Re-export is incremental.
1451
    let rep = repo.git_export(&git_dir).unwrap();
1452
    assert_eq!((rep.exported, rep.skipped), (0, 2));
1453
1454
    // An independent change makes two heads; the next state is one more
1455
    // commit on the linear branch whose tree is the union.
1456
    repo.checkout(&[h1], false, "checkout").unwrap();
1457
    write(&r, "other.txt", b"o\n");
1458
    let h3 = repo.commit("third", &[]).unwrap();
1459
    let rep = repo.git_export(&git_dir).unwrap();
1460
    assert_eq!((rep.exported, rep.heads), (1, 2));
1461
    assert_eq!(git(&["log", "--format=%s", "main"]), "third\nsecond\nfirst");
1462
    let parents = git(&["rev-list", "--parents", "-1", "main"]);
1463
    assert_eq!(parents.split(' ').count(), 2, "one parent: {parents}");
1464
    assert_eq!(git(&["show", "main:other.txt"]), "o");
1465
    assert_eq!(git(&["show", "main:src/main.rs"]), "fn main() { run(); }");
1466
    assert_eq!(
1467
        git(&["ls-tree", "--name-only", "main"]),
1468
        "README.md\nlogo.png\nother.txt\nsrc"
1469
    );
1470
    let body = git(&["log", "-1", "--format=%B", "main"]);
1471
    assert!(
1472
        body.contains(&format!("Oxy-Hash: {}", h3.to_hex())) && body.contains("Oxy-State: "),
1473
        "{body}"
1474
    );
1475
    // A rewrite is a new state whose one new change is the rewritten one.
1476
    repo.describe(&h3, "third, described").unwrap();
1477
    let rep = repo.git_export(&git_dir).unwrap();
1478
    assert_eq!(rep.exported, 1);
1479
    assert_eq!(
1480
        git(&["log", "-1", "--format=%s", "main"]),
1481
        "third, described"
1482
    );
1483
    assert_eq!(git(&["log", "--format=%s", "main"]).lines().count(), 4);
1484
    let _ = h2;
1485
}
1486
1487
#[test]
1488
fn git_import_reproduces_trees() {
1489
    git_import_reproduces_trees_with(None);
1490
}
1491
1492
/// The same import with every merge rendered in batches of one file
1493
/// (oxygen#25): what a merge onto a base of thousands of files takes.
1494
#[test]
1495
fn git_import_reproduces_trees_in_batches() {
1496
    git_import_reproduces_trees_with(Some(1));
1497
}
1498
1499
fn git_import_reproduces_trees_with(batch: Option<usize>) {
1500
    crate::repo::git::set_merge_batch_for_tests(batch);
1501
    hermetic();
1502
    if std::process::Command::new("git")
1503
        .arg("--version")
1504
        .output()
1505
        .is_err()
1506
    {
1507
        eprintln!("git not installed; skipping");
1508
        return;
1509
    }
1510
    let dir = tempfile::tempdir().unwrap();
1511
    let root = dir.path();
1512
    let g = root.join("src.git");
1513
    fs::create_dir_all(&g).unwrap();
1514
    let git = |args: &[&str]| -> String {
1515
        let out = std::process::Command::new("git")
1516
            .arg("-C")
1517
            .arg(&g)
1518
            .args([
1519
                "-c",
1520
                "user.name=Grace",
1521
                "-c",
1522
                "[email protected]",
1523
                "-c",
1524
                "commit.gpgsign=false",
1525
            ])
1526
            .args(args)
1527
            .output()
1528
            .unwrap();
1529
        assert!(
1530
            out.status.success(),
1531
            "git {args:?}: {}",
1532
            String::from_utf8_lossy(&out.stderr)
1533
        );
1534
        String::from_utf8_lossy(&out.stdout).trim().to_string()
1535
    };
1536
    git(&["init", "-q", "-b", "main"]);
1537
    write(&g, "README.md", b"# Hi\n");
1538
    write(&g, "src/lib.rs", b"pub fn a() {}\n");
1539
    git(&["add", "."]);
1540
    git(&["commit", "-q", "-m", "initial"]);
1541
    write(&g, "src/lib.rs", b"pub fn a() {}\npub fn b() {}\n");
1542
    write(&g, "run.sh", b"#!/bin/sh\n");
1543
    #[cfg(unix)]
1544
    {
1545
        use std::os::unix::fs::PermissionsExt;
1546
        fs::set_permissions(g.join("run.sh"), fs::Permissions::from_mode(0o755)).unwrap();
1547
    }
1548
    write(&g, "logo.png", b"\x89PNG\0\0\x01");
1549
    git(&["add", "."]);
1550
    git(&[
1551
        "commit",
1552
        "-q",
1553
        "-m",
1554
        "second\n\nChange-Id: 0123456789abcdef0123456789abcdef",
1555
    ]);
1556
    // A branch that edits README, merged back with a conflict-free merge.
1557
    git(&["checkout", "-q", "-b", "topic", "HEAD~1"]);
1558
    write(&g, "README.md", b"# Hi\n\nMore.\n");
1559
    git(&["commit", "-q", "-am", "readme"]);
1560
    git(&["checkout", "-q", "main"]);
1561
    git(&["merge", "-q", "--no-ff", "-m", "merge topic", "topic"]);
1562
    // A branch from the initial commit inserting at the same place as
1563
    // "second": concurrent in Oxygen too, so the merge commit is a resolution.
1564
    let initial = git(&["rev-list", "--max-parents=0", "HEAD"]);
1565
    git(&["checkout", "-q", "-b", "clash", &initial]);
1566
    write(&g, "src/lib.rs", b"pub fn a() {}\npub fn c() {}\n");
1567
    git(&["commit", "-q", "-am", "clash"]);
1568
    git(&["checkout", "-q", "main"]);
1569
    let _ = std::process::Command::new("git")
1570
        .arg("-C")
1571
        .arg(&g)
1572
        .args(["merge", "-q", "clash"])
1573
        .output();
1574
    write(
1575
        &g,
1576
        "src/lib.rs",
1577
        b"pub fn a() {}\npub fn b() {}\npub fn c() {}\n",
1578
    );
1579
    git(&["add", "."]);
1580
    git(&["commit", "-q", "-m", "resolve clash"]);
1581
    git(&["rm", "-q", "logo.png"]);
1582
    git(&["commit", "-q", "-m", "drop logo"]);
1583
    // A rename with a small edit is imported as a move of the same node.
1584
    git(&["mv", "src/lib.rs", "src/lib2.rs"]);
1585
    write(
1586
        &g,
1587
        "src/lib2.rs",
1588
        b"pub fn a() {}\npub fn b() {}\npub fn c() {}\npub fn d() {}\n",
1589
    );
1590
    git(&["add", "."]);
1591
    git(&["commit", "-q", "-m", "rename lib"]);
1592
    // A branch that edits run.sh, merged keeping main's tree (`-s ours`):
1593
    // run.sh is the same as in the first parent's tree, but the merged
1594
    // change touched it, so the importer must compare it, not skip it.
1595
    git(&["checkout", "-q", "-b", "discarded"]);
1596
    write(&g, "run.sh", b"#!/bin/sh\necho discarded\n");
1597
    git(&["commit", "-q", "-am", "discarded edit"]);
1598
    git(&["checkout", "-q", "main"]);
1599
    git(&[
1600
        "merge",
1601
        "-q",
1602
        "-s",
1603
        "ours",
1604
        "-m",
1605
        "merge discarded, keeping ours",
1606
        "discarded",
1607
    ]);
1608
    let expected_count: usize = git(&["rev-list", "--count", "main"]).parse().unwrap();
1609
1610
    let dest = root.join("oxy");
1611
    let repo = Repo::init(&dest).unwrap().with_home(root.join("home"));
1612
    let rep = repo.import_git(&g, "main").unwrap();
1613
    assert_eq!(rep.commits, expected_count);
1614
    assert_eq!(rep.merges, 3);
1615
    assert_eq!(
1616
        fs::read(dest.join("run.sh")).unwrap(),
1617
        b"#!/bin/sh\n",
1618
        "the ours merge kept main's run.sh"
1619
    );
1620
    let v = repo.verify_git_import(&g, "main").unwrap();
1621
    assert_eq!(v.commits, expected_count, "every commit's tree reproduced");
1622
    assert!(v.mismatches.is_empty(), "{:?}", v.mismatches);
1623
    // The working copy equals the Git tree at main.
1624
    assert_eq!(
1625
        fs::read(dest.join("src/lib2.rs")).unwrap(),
1626
        b"pub fn a() {}\npub fn b() {}\npub fn c() {}\npub fn d() {}\n"
1627
    );
1628
    assert!(!dest.join("src/lib.rs").exists());
1629
    assert_eq!(
1630
        fs::read(dest.join("README.md")).unwrap(),
1631
        b"# Hi\n\nMore.\n"
1632
    );
1633
    assert!(!dest.join("logo.png").exists());
1634
    #[cfg(unix)]
1635
    {
1636
        use std::os::unix::fs::PermissionsExt;
1637
        assert!(
1638
            fs::metadata(dest.join("run.sh"))
1639
                .unwrap()
1640
                .permissions()
1641
                .mode()
1642
                & 0o111
1643
                != 0
1644
        );
1645
    }
1646
    assert!(
1647
        !repo.snapshot("status").unwrap().changed,
1648
        "clean after import"
1649
    );
1650
    let heads = repo.bookmark_heads().unwrap();
1651
    let st = repo.load_state(&heads).unwrap();
1652
    assert!(!st.materialize().is_conflicted());
1653
    assert_eq!(st.len(), expected_count);
1654
    let tip = repo
1655
        .log()
1656
        .unwrap()
1657
        .into_iter()
1658
        .find(|e| e.change.message.starts_with("rename lib"))
1659
        .unwrap();
1660
    let c = repo.store().get_change(&tip.hash).unwrap();
1661
    assert!(
1662
        c.tree_ops
1663
            .iter()
1664
            .any(|op| matches!(op, TreeOp::Move { name, .. } if name == "lib2.rs")),
1665
        "{:?}",
1666
        c.tree_ops
1667
    );
1668
    assert!(!c
1669
        .tree_ops
1670
        .iter()
1671
        .any(|op| matches!(op, TreeOp::AddNode { .. })));
1672
    // Messages carry Git trailers; the Change-Id trailer was honoured.
1673
    let log = repo.log().unwrap();
1674
    let second = log
1675
        .iter()
1676
        .find(|e| e.change.message.starts_with("second"))
1677
        .unwrap();
1678
    assert_eq!(
1679
        second.change.change_id,
1680
        ChangeId::from_hex("0123456789abcdef0123456789abcdef").unwrap()
1681
    );
1682
    assert!(second
1683
        .change
1684
        .message
1685
        .contains("Git-Author: Grace <[email protected]>"));
1686
    let resolve = log
1687
        .iter()
1688
        .find(|e| e.change.message.starts_with("resolve clash"))
1689
        .unwrap();
1690
    assert_eq!(
1691
        resolve.change.kind,
1692
        ChangeKind::Resolution,
1693
        "a conflicting Git merge becomes a resolution"
1694
    );
1695
    // Re-importing into another fresh repository gives the same ChangeIds.
1696
    let repo2 = Repo::init(&root.join("oxy2"))
1697
        .unwrap()
1698
        .with_home(root.join("home"));
1699
    repo2.import_git(&g, "main").unwrap();
1700
    // New nodes' identifiers derive from the commit (spec §23), so the
1701
    // re-import is not just the same ChangeIds but the same changes.
1702
    assert_eq!(
1703
        repo2.bookmark_heads().unwrap(),
1704
        repo.bookmark_heads().unwrap()
1705
    );
1706
    let ids: BTreeSet<ChangeId> = repo
1707
        .log()
1708
        .unwrap()
1709
        .iter()
1710
        .filter(|e| !e.is_working_copy)
1711
        .map(|e| e.change.change_id)
1712
        .collect();
1713
    let ids2: BTreeSet<ChangeId> = repo2
1714
        .log()
1715
        .unwrap()
1716
        .iter()
1717
        .filter(|e| !e.is_working_copy)
1718
        .map(|e| e.change.change_id)
1719
        .collect();
1720
    assert_eq!(ids, ids2);
1721
    // Round trip back out to Git reproduces the tip tree.
1722
    let mirror = root.join("mirror.git");
1723
    repo.git_export(&mirror).unwrap();
1724
    let out = std::process::Command::new("git")
1725
        .arg("-C")
1726
        .arg(&mirror)
1727
        .args(["show", "main:src/lib2.rs"])
1728
        .output()
1729
        .unwrap();
1730
    assert_eq!(
1731
        String::from_utf8_lossy(&out.stdout),
1732
        "pub fn a() {}\npub fn b() {}\npub fn c() {}\npub fn d() {}\n"
1733
    );
1734
    let out = std::process::Command::new("git")
1735
        .arg("-C")
1736
        .arg(&mirror)
1737
        .args(["show", "main:src/lib.rs"])
1738
        .output()
1739
        .unwrap();
1740
    assert!(
1741
        !out.status.success(),
1742
        "the old path is gone from the export"
1743
    );
1744
}
1745
1746
#[test]
1747
fn checkpoints_accelerate_loading_and_stay_correct() {
1748
    hermetic();
1749
    let dir = tempfile::tempdir().unwrap();
1750
    let root = dir.path();
1751
    let mut repo = Repo::init(root).unwrap().with_home(root.join("home"));
1752
    repo.config.set("core.checkpoint-interval", "5").unwrap();
1753
    repo.save_config().unwrap();
1754
    let repo = Repo::open(root).unwrap().with_home(root.join("home"));
1755
    let mut hashes = Vec::new();
1756
    for i in 0..12 {
1757
        write(
1758
            root,
1759
            "a.txt",
1760
            format!(
1761
                "{}\n",
1762
                (0..=i)
1763
                    .map(|k| k.to_string())
1764
                    .collect::<Vec<_>>()
1765
                    .join("\n")
1766
            )
1767
            .as_bytes(),
1768
        );
1769
        write(root, &format!("f{i}.txt"), b"x\n");
1770
        hashes.push(repo.commit(&format!("c{i}"), &[]).unwrap());
1771
    }
1772
    let (_, cp) = repo
1773
        .latest_checkpoint("main")
1774
        .unwrap()
1775
        .expect("automatic checkpoint");
1776
    assert!(cp.count >= 5 && cp.count <= 12, "{}", cp.count);
1777
    // Loading through the checkpoint equals loading everything.
1778
    let heads = repo.bookmark_heads().unwrap();
1779
    let fast = repo.load_state(&heads).unwrap();
1780
    let full = repo.load_state_full(&heads).unwrap();
1781
    assert_eq!(fast.len(), full.len());
1782
    assert_eq!(fast.heads(), full.heads());
1783
    let (a, b) = (fast.materialize(), full.materialize());
1784
    assert_eq!(
1785
        a.files.keys().collect::<Vec<_>>(),
1786
        b.files.keys().collect::<Vec<_>>()
1787
    );
1788
    for (p, f) in &a.files {
1789
        assert_eq!(f.content, b.files[p].content, "{p}");
1790
    }
1791
    assert!(repo.load_state_checkpointed(&heads).unwrap().is_some());
1792
    // A head set that does not contain the checkpoint's heads falls back.
1793
    assert!(repo
1794
        .load_state_checkpointed(&[hashes[0]])
1795
        .unwrap()
1796
        .is_none());
1797
    assert_eq!(repo.load_state(&[hashes[0]]).unwrap().len(), 1);
1798
    // Everything else keeps working on top of the checkpoint.
1799
    assert!(!repo.snapshot("status").unwrap().changed);
1800
    let h = repo.describe(&hashes[3], "c3 described").unwrap();
1801
    assert_eq!(repo.store().get_change(&h).unwrap().message, "c3 described");
1802
    let (r, n, bytes) = repo.checkpoint().unwrap();
1803
    assert!(n >= 12 && bytes > 0);
1804
    assert_eq!(repo.latest_checkpoint("main").unwrap().unwrap().0, r);
1805
    write(root, "a.txt", b"after\n");
1806
    let h_after = repo.commit("after", &[]).unwrap();
1807
    let st = repo.load_state(&repo.bookmark_heads().unwrap()).unwrap();
1808
    assert!(st.contains(&h_after));
1809
    assert!(
1810
        matches!(&st.materialize().files["a.txt"].content, FileContent::Text { bytes, .. } if bytes == b"after\n")
1811
    );
1812
    assert_eq!(repo.log().unwrap().len(), 14);
1813
    // Checkpoints survive gc.
1814
    repo.gc(true).unwrap();
1815
    assert!(repo.latest_checkpoint("main").unwrap().is_some());
1816
    assert!(repo
1817
        .load_state_checkpointed(&repo.bookmark_heads().unwrap())
1818
        .unwrap()
1819
        .is_some());
1820
}
1821
1822
#[test]
1823
fn quick_status_for_prompts() {
1824
    hermetic();
1825
    let dir = tempfile::tempdir().unwrap();
1826
    let root = dir.path();
1827
    let origin = Repo::init(&root.join("origin")).unwrap();
1828
    let url = root.join("origin").to_string_lossy().to_string();
1829
    let a = Repo::clone(&url, &root.join("a"))
1830
        .unwrap()
1831
        .with_home(root.join("home"));
1832
    let ops_before = a.op_log().unwrap().len();
1833
    let info = a.quick_status().unwrap();
1834
    assert_eq!(
1835
        (
1836
            info.bookmark.as_str(),
1837
            info.heads,
1838
            info.dirty,
1839
            info.conflicted,
1840
            info.ahead,
1841
            info.behind
1842
        ),
1843
        ("main", 0, false, false, Some(0), Some(0))
1844
    );
1845
    write(&root.join("a"), "f.txt", b"f\n");
1846
    assert!(a.quick_status().unwrap().dirty, "a new file is dirty");
1847
    assert_eq!(
1848
        a.op_log().unwrap().len(),
1849
        ops_before,
1850
        "quick_status records nothing"
1851
    );
1852
    // A snapshotted but uncommitted change is still dirty.
1853
    a.snapshot("status").unwrap();
1854
    assert!(a.quick_status().unwrap().dirty);
1855
    a.commit("f", &[]).unwrap();
1856
    let info = a.quick_status().unwrap();
1857
    assert!(!info.dirty, "clean right after a commit");
1858
    assert_eq!((info.ahead, info.behind), (Some(1), Some(0)));
1859
    assert_eq!(
1860
        info.format("%b %c%d%x%A%D"),
1861
        format!("main {}+1", info.change_id)
1862
    );
1863
    assert_eq!(info.format("[%h heads] %a/%B %%"), "[1 heads] 1/0 %");
1864
    // Touching a file without changing it is not dirty; changing content of
1865
    // the same size is.
1866
    let p = root.join("a/f.txt");
1867
    let content = fs::read(&p).unwrap();
1868
    fs::write(&p, &content).unwrap();
1869
    assert!(!a.quick_status().unwrap().dirty);
1870
    fs::write(&p, b"g\n").unwrap();
1871
    assert!(a.quick_status().unwrap().dirty);
1872
    fs::write(&p, b"f\n").unwrap();
1873
    // Push, then a second clone commits and pushes: we are behind.
1874
    assert!(a.push("origin", false).unwrap()[0].ok);
1875
    assert_eq!(a.quick_status().unwrap().ahead, Some(0));
1876
    let b = Repo::clone(&url, &root.join("b"))
1877
        .unwrap()
1878
        .with_home(root.join("home-b"));
1879
    write(&root.join("b"), "g.txt", b"g\n");
1880
    b.commit("g", &[]).unwrap();
1881
    b.push("origin", false).unwrap();
1882
    a.fetch("origin").unwrap();
1883
    let info = a.quick_status().unwrap();
1884
    assert_eq!((info.ahead, info.behind), (Some(0), Some(1)));
1885
    assert_eq!(info.format("%A%D"), "-1");
1886
    let _ = origin;
1887
}
1888
1889
#[test]
1890
fn lazy_blobs_are_fetched_on_first_read() {
1891
    hermetic();
1892
    let dir = tempfile::tempdir().unwrap();
1893
    let root = dir.path();
1894
    let origin_dir = root.join("origin");
1895
    let origin = Repo::init(&origin_dir)
1896
        .unwrap()
1897
        .with_home(root.join("home"));
1898
    let url = origin_dir.to_string_lossy().to_string();
1899
    let big: Vec<u8> = (0..200_000u32).map(|i| (i % 251) as u8).collect(); // has NUL bytes: opaque
1900
    write(&origin_dir, "big.bin", &big);
1901
    write(&origin_dir, "small.bin", &[0u8, 1, 2]);
1902
    write(&origin_dir, "t.txt", b"t\n");
1903
    let h = origin.commit("blobs", &[]).unwrap();
1904
    let big_ref = Repo::blob_ref(&big);
1905
1906
    // Fetch only (no checkout) with a filter: the big blob stays absent.
1907
    let a = Repo::init_with_id(&root.join("a"), origin.id().unwrap())
1908
        .unwrap()
1909
        .with_home(root.join("home"));
1910
    let a = {
1911
        let mut a = a;
1912
        a.config.set("remote.origin.url", &url).unwrap();
1913
        a.config.set("filter.max-blob", "100K").unwrap();
1914
        a.save_config().unwrap();
1915
        a
1916
    };
1917
    assert_eq!(a.config.max_blob, Some(100 * 1024));
1918
    a.fetch("origin").unwrap();
1919
    assert!(a.store().has(&h));
1920
    assert!(!a.store().has(&big_ref), "withheld");
1921
    assert!(
1922
        a.store().has(&Repo::blob_ref(&[0u8, 1, 2])),
1923
        "small blob came along"
1924
    );
1925
    assert_eq!(a.lazy_remote(&big_ref).as_deref(), Some("origin"));
1926
1927
    // status and commit do not need it: adopt the state, edit a text file, commit.
1928
    let (op_ref, op) = a.head_op().unwrap();
1929
    let mut view = op.view.clone();
1930
    view.bookmarks.insert(
1931
        "main".into(),
1932
        a.store().put_state(&StateObject::new(vec![h])).unwrap(),
1933
    );
1934
    a.record_op(&[op_ref], "adopt", view).unwrap();
1935
    // Checkout reads the blob lazily, which fetches it.
1936
    a.checkout(&[h], true, "checkout").unwrap();
1937
    assert!(a.store().has(&big_ref), "fetched on first read");
1938
    assert_eq!(fs::read(root.join("a/big.bin")).unwrap(), big);
1939
    assert!(a.lazy_remote(&big_ref).is_none(), "no longer registered");
1940
    write(&root.join("a"), "t.txt", b"t2\n");
1941
    a.commit("text edit", &[]).unwrap();
1942
1943
    // clone --max-blob records the filter; the checkout fetches lazily.
1944
    let b = Repo::clone_with(&url, &root.join("b"), Some(1024), &[]).unwrap();
1945
    assert_eq!(b.config.max_blob, Some(1024));
1946
    assert_eq!(fs::read(root.join("b/big.bin")).unwrap(), big);
1947
    assert_eq!(parse_size("2M").unwrap(), 2 << 20);
1948
    assert!(parse_size("lots").is_err());
1949
}
1950
1951
#[test]
1952
fn sparse_checkout_materializes_only_chosen_paths() {
1953
    hermetic();
1954
    let dir = tempfile::tempdir().unwrap();
1955
    let root = dir.path();
1956
    let origin_dir = root.join("origin");
1957
    let origin = Repo::init(&origin_dir)
1958
        .unwrap()
1959
        .with_home(root.join("home"));
1960
    write(&origin_dir, "src/main.rs", b"fn main() {}\n");
1961
    write(&origin_dir, "src/lib.rs", b"pub fn a() {}\n");
1962
    write(&origin_dir, "docs/guide.md", b"# guide\n");
1963
    let logo: Vec<u8> = (0..50_000u32).map(|i| (i % 7) as u8).collect();
1964
    write(&origin_dir, "docs/logo.png", &logo);
1965
    write(&origin_dir, "README.md", b"# top\n");
1966
    let h1 = origin.commit("tree", &[]).unwrap();
1967
    let url = origin_dir.to_string_lossy().to_string();
1968
1969
    let a = Repo::clone_with(&url, &root.join("a"), None, &["src".into()])
1970
        .unwrap()
1971
        .with_home(root.join("home"));
1972
    assert_eq!(a.config.sparse_paths, vec!["src"]);
1973
    assert_eq!(a.config.max_blob, Some(0), "sparse implies lazy blobs");
1974
    assert!(root.join("a/src/main.rs").exists());
1975
    assert!(!root.join("a/docs").exists() && !root.join("a/README.md").exists());
1976
    assert!(
1977
        !a.store().has(&Repo::blob_ref(&logo)),
1978
        "out-of-scope blob never fetched"
1979
    );
1980
    assert!(
1981
        !a.snapshot("status").unwrap().changed,
1982
        "out-of-scope files are not removals"
1983
    );
1984
    assert!(!a.quick_status().unwrap().dirty);
1985
1986
    // Edits in scope commit normally and keep the rest of the tree intact.
1987
    write(
1988
        &root.join("a"),
1989
        "src/lib.rs",
1990
        b"pub fn a() {}\npub fn b() {}\n",
1991
    );
1992
    let h2 = a.commit("edit lib", &[]).unwrap();
1993
    let st = a.load_state(&[h2]).unwrap().materialize();
1994
    assert!(
1995
        st.files.contains_key("docs/guide.md"),
1996
        "the state still has everything"
1997
    );
1998
    assert!(a.push("origin", false).unwrap()[0].ok);
1999
    origin.refresh().unwrap();
2000
    // Files created outside the scope are ignored by status.
2001
    write(&root.join("a"), "docs/new.md", b"ignored\n");
2002
    assert!(a.snapshot("status").unwrap().statuses.is_empty());
2003
2004
    // Widening the filter checks out the rest; narrowing leaves stray files alone.
2005
    let mut a = a;
2006
    a.config.set("filter.paths", "src,docs").unwrap();
2007
    a.save_config().unwrap();
2008
    let r = a
2009
        .checkout(&a.bookmark_heads().unwrap(), true, "widen")
2010
        .unwrap();
2011
    assert!(r.written >= 2);
2012
    assert_eq!(
2013
        fs::read(root.join("a/docs/logo.png")).unwrap(),
2014
        logo,
2015
        "now fetched lazily"
2016
    );
2017
    assert!(!root.join("a/README.md").exists());
2018
    // Origin sees the change made under a sparse checkout with the full tree intact.
2019
    origin.pull("origin").err();
2020
    let full = origin
2021
        .load_state(&origin.bookmark_heads().unwrap())
2022
        .unwrap()
2023
        .materialize();
2024
    assert!(
2025
        matches!(&full.files["src/lib.rs"].content, FileContent::Text { bytes, .. } if bytes == b"pub fn a() {}\npub fn b() {}\n")
2026
    );
2027
    assert!(full.files.contains_key("README.md"));
2028
    let _ = h1;
2029
}
2030
2031
#[test]
2032
fn shallow_clone_and_deepen() {
2033
    hermetic();
2034
    let dir = tempfile::tempdir().unwrap();
2035
    let root = dir.path();
2036
    let origin_dir = root.join("origin");
2037
    let origin = Repo::init(&origin_dir)
2038
        .unwrap()
2039
        .with_home(root.join("home"));
2040
    let mut hashes = Vec::new();
2041
    for i in 0..8 {
2042
        write(
2043
            &origin_dir,
2044
            "a.txt",
2045
            format!(
2046
                "{}\n",
2047
                (0..=i)
2048
                    .map(|k| k.to_string())
2049
                    .collect::<Vec<_>>()
2050
                    .join("\n")
2051
            )
2052
            .as_bytes(),
2053
        );
2054
        hashes.push(origin.commit(&format!("c{i}"), &[]).unwrap());
2055
    }
2056
    let url = origin_dir.to_string_lossy().to_string();
2057
    let a = Repo::clone_shallow(&url, &root.join("a"), 3, None, &[])
2058
        .unwrap()
2059
        .with_home(root.join("home"));
2060
    assert!(a.is_shallow());
2061
    assert_eq!(
2062
        fs::read_to_string(root.join("a/a.txt")).unwrap(),
2063
        "0\n1\n2\n3\n4\n5\n6\n7\n"
2064
    );
2065
    assert!(
2066
        a.store().has(&hashes[7]) && a.store().has(&hashes[5]),
2067
        "three levels present"
2068
    );
2069
    assert!(!a.store().has(&hashes[4]), "beyond the depth is absent");
2070
    assert_eq!(a.boundary(), [hashes[4]].into_iter().collect());
2071
    assert_eq!(
2072
        a.log().unwrap().len(),
2073
        9,
2074
        "the log shows every change from the checkpoint's metadata"
2075
    );
2076
    assert!(!a.snapshot("status").unwrap().changed);
2077
    assert_eq!(a.quick_status().unwrap().heads, 1);
2078
2079
    // Work continues on top of the shallow history and pushes back.
2080
    write(&root.join("a"), "a.txt", b"0\n1\n2\n3\n4\n5\n6\n7\n8\n");
2081
    let h_new = a.commit("c8", &[]).unwrap();
2082
    assert!(a.push("origin", false).unwrap()[0].ok);
2083
    origin.refresh().unwrap();
2084
    assert_eq!(origin.bookmark_heads().unwrap(), vec![h_new]);
2085
    // Fetching new work from origin into the shallow clone works too.
2086
    write(&origin_dir, "b.txt", b"b\n");
2087
    origin.pull("origin").err();
2088
    let (_, wc) = origin.working_copy().unwrap();
2089
    let _ = wc;
2090
    origin
2091
        .checkout(&origin.bookmark_heads().unwrap(), true, "co")
2092
        .unwrap();
2093
    write(&origin_dir, "b.txt", b"b\n");
2094
    let h_b = origin.commit("b", &[]).unwrap();
2095
    let pr = a.pull("origin").unwrap();
2096
    assert!(pr.changed);
2097
    assert!(a.store().has(&h_b));
2098
    assert!(root.join("a/b.txt").exists());
2099
2100
    // Deepening fetches older history until the boundary is gone.
2101
    // Every commit also depends on the change that created the file, so two
2102
    // levels below the boundary hold h4, h3, and the root.
2103
    assert!(a.deepen("origin", 2).unwrap() >= 2);
2104
    assert!(a.store().has(&hashes[3]));
2105
    assert!(a.is_shallow());
2106
    a.deepen("origin", 100).unwrap();
2107
    assert!(!a.is_shallow(), "boundary reached the root");
2108
    assert!(a.store().has(&hashes[0]));
2109
    assert_eq!(
2110
        a.load_state_full(&a.bookmark_heads().unwrap())
2111
            .unwrap()
2112
            .len(),
2113
        10
2114
    );
2115
}
2116
2117
#[test]
2118
fn tags_are_immutable_named_states_and_travel() {
2119
    hermetic();
2120
    let dir = tempfile::tempdir().unwrap();
2121
    let root = dir.path();
2122
    let origin = Repo::init(&root.join("origin")).unwrap();
2123
    let url = root.join("origin").to_string_lossy().to_string();
2124
    let mut a = Repo::clone(&url, &root.join("a"))
2125
        .unwrap()
2126
        .with_home(root.join("home-a"));
2127
    let (key_a, _) = a
2128
        .create_identity("Ada", "[email protected]", IdentityScope::User)
2129
        .unwrap();
2130
    write(&root.join("a"), "f.txt", b"1\n");
2131
    let h1 = a.commit("one", &[]).unwrap();
2132
    write(&root.join("a"), "f.txt", b"1\n2\n");
2133
    let h2 = a.commit("two", &[]).unwrap();
2134
2135
    let t = a.tag_create("v1", &[h1], "first release").unwrap();
2136
    assert_eq!(
2137
        (t.heads.clone(), t.signer.as_deref()),
2138
        (vec![h1], Some("Ada"))
2139
    );
2140
    assert!(a.tag_create("v1", &[h2], "").is_err(), "immutable");
2141
    assert!(a.tag_create("bad/name", &[h2], "").is_err());
2142
    assert_eq!(a.tag_heads("v1").unwrap(), Some(vec![h1]));
2143
    assert_eq!(a.resolve_heads("v1").unwrap(), vec![h1]);
2144
    assert_eq!(a.resolve_heads("main").unwrap(), vec![h2]);
2145
    let (_, sa) = a.tag_attest("v1").unwrap().unwrap();
2146
    assert_eq!(sa.sigs[0].key, key_a);
2147
    // Checkout by tag.
2148
    a.checkout(&a.resolve_heads("v1").unwrap(), false, "co")
2149
        .unwrap();
2150
    assert_eq!(fs::read(root.join("a/f.txt")).unwrap(), b"1\n");
2151
    a.checkout(&a.bookmark_heads().unwrap(), false, "co")
2152
        .unwrap();
2153
2154
    // Push carries the tag; a second attestation for the name is refused.
2155
    let r = a.push("origin", false).unwrap();
2156
    origin.refresh().unwrap();
2157
    assert!(r.iter().any(|x| x.name == "tags/v1" && x.ok), "{r:?}");
2158
    assert_eq!(origin.tag_heads("v1").unwrap(), Some(vec![h1]));
2159
    let mut forged = a
2160
        .tag_refs()
2161
        .unwrap()
2162
        .into_iter()
2163
        .find(|t| t.name == "v1")
2164
        .unwrap();
2165
    forged.state = origin
2166
        .store()
2167
        .put_state(&StateObject::new(vec![h2]))
2168
        .unwrap();
2169
    forged.heads = vec![h2];
2170
    forged.attestation = None;
2171
    let r = origin
2172
        .receive_push(Bundle::default(), vec![], None, vec![forged])
2173
        .unwrap();
2174
    assert!(!r[0].ok && r[0].reason.contains("immutable"), "{r:?}");
2175
2176
    // A clone gets the tag; a later tag arrives on fetch.
2177
    let b = Repo::clone(&url, &root.join("b"))
2178
        .unwrap()
2179
        .with_home(root.join("home-b"));
2180
    assert_eq!(b.tag_heads("v1").unwrap(), Some(vec![h1]));
2181
    assert!(b.tags().unwrap()[0].signer.as_deref() == Some("Ada"));
2182
    a.tag_create("v2", &[h2], "second").unwrap();
2183
    a.push("origin", false).unwrap();
2184
    origin.refresh().unwrap();
2185
    let rep = b.fetch("origin").unwrap();
2186
    assert_eq!(rep.new_tags, 1);
2187
    assert_eq!(b.tag_heads("v2").unwrap(), Some(vec![h2]));
2188
2189
    // Under a policy, an unattested tag is refused and an attested one by the root passes.
2190
    a.policy_init().unwrap();
2191
    a.push("origin", false).unwrap();
2192
    origin.refresh().unwrap();
2193
    let unattested = crate::protocol::TagRef {
2194
        name: "v3".into(),
2195
        state: origin
2196
            .store()
2197
            .put_state(&StateObject::new(vec![h2]))
2198
            .unwrap(),
2199
        heads: vec![h2],
2200
        attestation: None,
2201
    };
2202
    let r = origin
2203
        .receive_push(Bundle::default(), vec![], None, vec![unattested])
2204
        .unwrap();
2205
    assert!(!r[0].ok && r[0].reason.contains("attestation"), "{r:?}");
2206
    a.tag_create("v3", &[h2], "").unwrap();
2207
    let r = a.push("origin", false).unwrap();
2208
    origin.refresh().unwrap();
2209
    assert!(r.iter().any(|x| x.name == "tags/v3" && x.ok), "{r:?}");
2210
    assert!(a.gc(true).is_ok());
2211
    assert_eq!(a.tags().unwrap().len(), 3, "tags survive gc");
2212
2213
    // After a rotation the policy names only the new key, yet a fresh clone
2214
    // still takes the tags the old key made before it; the old key makes
2215
    // nothing new.
2216
    let rot = a.rotate_identity().unwrap();
2217
    let r = a.push("origin", false).unwrap();
2218
    origin.refresh().unwrap();
2219
    assert!(r.iter().all(|x| x.ok), "{r:?}");
2220
    let c = Repo::clone(&url, &root.join("c"))
2221
        .unwrap()
2222
        .with_home(root.join("home-c"));
2223
    assert_eq!(c.tag_heads("v3").unwrap(), Some(vec![h2]));
2224
    let (_, sp) = c.current_policy().unwrap().unwrap();
2225
    assert!(!sp.policy.authorizes(&key_a, "tags/v9"));
2226
    let made = c.identity(&rot.new).unwrap().created;
2227
    assert!(c.predecessor_authorized(&sp.policy, &key_a, "tags/v9", made - 1));
2228
    assert!(!c.predecessor_authorized(&sp.policy, &key_a, "tags/v9", made));
2229
    assert!(!c.predecessor_authorized(&sp.policy, &rot.new, "tags/v9", 0));
2230
}
2231
2232
#[test]
2233
fn multiple_workspaces_share_a_repository() {
2234
    hermetic();
2235
    let dir = tempfile::tempdir().unwrap();
2236
    let root = dir.path();
2237
    let main_dir = root.join("main");
2238
    let repo = Repo::init(&main_dir).unwrap().with_home(root.join("home"));
2239
    write(&main_dir, "a.txt", b"a\n");
2240
    let h1 = repo.commit("a", &[]).unwrap();
2241
    assert_eq!(repo.workspaces().unwrap().len(), 1);
2242
2243
    // A second workspace elsewhere, checked out on the bookmark.
2244
    let ws_dir = root.join("ws2");
2245
    let ws = repo.workspace_add(&ws_dir, None).unwrap();
2246
    assert!(ws_dir.join(".oxy").is_file());
2247
    assert_eq!(fs::read(ws_dir.join("a.txt")).unwrap(), b"a\n");
2248
    assert_ne!(ws.workspace(), repo.workspace());
2249
    let list = repo.workspaces().unwrap();
2250
    assert_eq!(list.len(), 2);
2251
    assert!(list
2252
        .iter()
2253
        .any(|w| w.id == ws.workspace() && w.path == ws_dir.canonicalize().unwrap() && !w.current));
2254
    assert!(!ws.snapshot("status").unwrap().changed);
2255
2256
    // Work in the second workspace: its own working copy, shared bookmark.
2257
    write(&ws_dir, "b.txt", b"b\n");
2258
    let s = ws.snapshot("status").unwrap();
2259
    assert_eq!(s.statuses.len(), 1);
2260
    assert!(
2261
        !repo.snapshot("status").unwrap().changed,
2262
        "the first workspace is untouched"
2263
    );
2264
    let h2 = ws.commit("b from ws2", &[]).unwrap();
2265
    repo.refresh().unwrap();
2266
    let mut heads = repo.bookmark_heads().unwrap();
2267
    heads.sort();
2268
    let mut want = vec![h1, h2];
2269
    want.sort();
2270
    assert_eq!(heads, want, "both workspaces see the bookmark move");
2271
    assert!(!main_dir.join("b.txt").exists());
2272
    repo.checkout(&repo.bookmark_heads().unwrap(), false, "co")
2273
        .unwrap();
2274
    assert!(main_dir.join("b.txt").exists());
2275
2276
    // Reopening from inside the second workspace finds the shared repository.
2277
    let reopened = Repo::open(&ws_dir).unwrap();
2278
    assert_eq!(reopened.workspace(), ws.workspace());
2279
    assert_eq!(reopened.id().unwrap(), repo.id().unwrap());
2280
    assert_eq!(reopened.quick_status().unwrap().heads, 2);
2281
2282
    // Workspaces cannot nest; forget drops one from the view but keeps files.
2283
    assert!(repo.workspace_add(&main_dir.join("inner"), None).is_err());
2284
    assert!(repo.workspace_forget(&repo.workspace()).is_err());
2285
    repo.workspace_forget(&ws.workspace()).unwrap();
2286
    assert_eq!(repo.workspaces().unwrap().len(), 1);
2287
    assert!(ws_dir.join("b.txt").exists());
2288
    assert!(
2289
        ws.snapshot("status").is_err(),
2290
        "a forgotten workspace is no longer in the view"
2291
    );
2292
2293
    // The working-copy lock: re-entrant in a thread; a lock whose process
2294
    // is gone is taken over, and a live process's is not, however old.
2295
    let lock = repo.lock_snapshot().unwrap();
2296
    let again = repo.lock_working_copy().unwrap();
2297
    drop(again);
2298
    drop(lock);
2299
    let lock_path = main_dir
2300
        .join(".oxy/workspaces")
2301
        .join(repo.workspace().to_hex())
2302
        .join("lock");
2303
    let old = std::time::SystemTime::now() - std::time::Duration::from_secs(120);
2304
    let age = |p: &Path| fs::File::open(p).unwrap().set_modified(old).unwrap();
2305
    fs::write(&lock_path, std::process::id().to_string()).unwrap();
2306
    age(&lock_path);
2307
    assert!(
2308
        !super::workspace::lock_is_stale(&lock_path),
2309
        "a live process keeps its lock"
2310
    );
2311
    fs::write(&lock_path, "4294967295").unwrap();
2312
    age(&lock_path);
2313
    assert!(repo.lock_snapshot().is_ok(), "stale lock taken over");
2314
}
2315
2316
#[test]
2317
fn attributes_binary_eol_nocompress_lockable() {
2318
    hermetic();
2319
    let dir = tempfile::tempdir().unwrap();
2320
    let root = dir.path();
2321
    let repo = Repo::init(root).unwrap().with_home(root.join("home"));
2322
    write(
2323
        root,
2324
        ".oxyattributes",
2325
        b"*.dat binary nocompress\n*.txt eol=crlf\nassets/** lockable\n",
2326
    );
2327
    write(root, "plain.dat", b"no nul bytes here\n");
2328
    write(root, "notes.txt", b"one\r\ntwo\r\n");
2329
    write(root, "assets/model.bin", b"\0model");
2330
    let h = repo.commit("attrs", &[]).unwrap();
2331
    let snap = repo.load_state(&[h]).unwrap().materialize();
2332
    assert!(
2333
        snap.files["plain.dat"].mode.opaque,
2334
        "binary attribute forces opaque without NUL bytes"
2335
    );
2336
    assert!(
2337
        matches!(&snap.files["notes.txt"].content, FileContent::Text { bytes, .. } if bytes == b"one\ntwo\n"),
2338
        "stored with LF"
2339
    );
2340
    assert!(
2341
        !repo.snapshot("status").unwrap().changed,
2342
        "CRLF on disk equals LF in the state"
2343
    );
2344
    // nocompress chunks pack raw.
2345
    let r = repo.gc(true).unwrap();
2346
    assert!(r.packed.objects > 0);
2347
    // Checkout writes CRLF for eol=crlf and makes lockable files read-only.
2348
    fs::remove_file(root.join("notes.txt")).unwrap();
2349
    repo.checkout(&[h], true, "co").unwrap();
2350
    assert_eq!(fs::read(root.join("notes.txt")).unwrap(), b"one\r\ntwo\r\n");
2351
    assert!(fs::metadata(root.join("assets/model.bin"))
2352
        .unwrap()
2353
        .permissions()
2354
        .readonly());
2355
    assert!(repo.lock_path("plain.dat").is_err(), "not lockable");
2356
    repo.lock_path("assets/model.bin").unwrap();
2357
    assert!(!fs::metadata(root.join("assets/model.bin"))
2358
        .unwrap()
2359
        .permissions()
2360
        .readonly());
2361
    assert!(repo.is_locked("assets/model.bin"));
2362
    write(root, "assets/model.bin", b"\0model2");
2363
    repo.commit("edit model", &[]).unwrap();
2364
    repo.unlock_path("assets/model.bin").unwrap();
2365
    assert!(fs::metadata(root.join("assets/model.bin"))
2366
        .unwrap()
2367
        .permissions()
2368
        .readonly());
2369
    // A later checkout can still overwrite a read-only lockable file.
2370
    repo.checkout(&[h], true, "co").unwrap();
2371
    assert_eq!(fs::read(root.join("assets/model.bin")).unwrap(), b"\0model");
2372
}
2373
2374
#[cfg(unix)]
2375
#[test]
2376
fn hooks_can_veto_observe_and_add_dependencies() {
2377
    use std::os::unix::fs::PermissionsExt;
2378
    hermetic();
2379
    let dir = tempfile::tempdir().unwrap();
2380
    let root = dir.path();
2381
    let mut repo = Repo::init(root).unwrap().with_home(root.join("home"));
2382
    let hooks = root.join(".oxy/hooks");
2383
    fs::create_dir_all(&hooks).unwrap();
2384
    let hook = |name: &str, body: &str| {
2385
        let p = hooks.join(name);
2386
        fs::write(&p, format!("#!/bin/sh\n{body}\n")).unwrap();
2387
        fs::set_permissions(&p, fs::Permissions::from_mode(0o755)).unwrap();
2388
    };
2389
    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");
2390
    hook("post-commit", "cat > \"$OXY_ROOT/.last-post-commit\"");
2391
    hook("post-checkout", "cat > \"$OXY_ROOT/.last-post-checkout\"");
2392
    hook("pre-push", "echo pushing blocked >&2; exit 3");
2393
    write(root, ".oxyignore", b".last-*\n");
2394
    write(root, "a.txt", b"a\n");
2395
    let err = repo.commit("WIP: nope", &[]).unwrap_err().to_string();
2396
    assert!(err.contains("pre-commit refused: no WIP commits"), "{err}");
2397
    let h1 = repo.commit("first", &[]).unwrap();
2398
    let pre = fs::read_to_string(root.join(".last-pre-commit")).unwrap();
2399
    assert!(
2400
        pre.contains("\"event\":\"pre-commit\"")
2401
            && pre.contains("\"path\":\"a.txt\"")
2402
            && pre.contains("\"message\":\"first\""),
2403
        "{pre}"
2404
    );
2405
    let post = fs::read_to_string(root.join(".last-post-commit")).unwrap();
2406
    assert!(post.contains(&h1.to_hex()), "{post}");
2407
    repo.checkout(&[h1], false, "co").unwrap();
2408
    assert!(fs::read_to_string(root.join(".last-post-checkout"))
2409
        .unwrap()
2410
        .contains("post-checkout"));
2411
    repo.config.set("remote.origin.url", "/nowhere").unwrap();
2412
    repo.save_config().unwrap();
2413
    let err = repo.push("origin", false).unwrap_err().to_string();
2414
    assert!(err.contains("pre-push refused: pushing blocked"), "{err}");
2415
2416
    // semantic-deps: only when enabled; adds an explicit dependency.
2417
    write(root, "b.txt", b"b\n");
2418
    hook(
2419
        "semantic-deps",
2420
        &format!(
2421
            "cat > \"$OXY_ROOT/.last-semantic\"; echo '{{\"deps\": [\"{}\"]}}'",
2422
            h1.to_hex()
2423
        ),
2424
    );
2425
    let h2 = repo.commit("b without hook", &[]).unwrap();
2426
    assert!(
2427
        repo.store().get_change(&h2).unwrap().deps.is_empty(),
2428
        "hook disabled by default"
2429
    );
2430
    repo.config.set("hooks.semantic-deps", "true").unwrap();
2431
    repo.save_config().unwrap();
2432
    write(root, "c.txt", b"c\n");
2433
    let h3 = repo.commit("c with hook", &[]).unwrap();
2434
    assert_eq!(repo.store().get_change(&h3).unwrap().deps, vec![h1]);
2435
    let sem = fs::read_to_string(root.join(".last-semantic")).unwrap();
2436
    assert!(
2437
        sem.contains("\"touched_paths\":[\"c.txt\"]") && sem.contains("candidate_deps"),
2438
        "{sem}"
2439
    );
2440
    assert_eq!(json_str("a\"b\\c\n"), "\"a\\\"b\\\\c\\n\"");
2441
}
2442
2443
#[test]
2444
fn amend_into_older_change_and_split() {
2445
    hermetic();
2446
    let dir = tempfile::tempdir().unwrap();
2447
    let root = dir.path();
2448
    let mut repo = Repo::init(root).unwrap().with_home(root.join("home"));
2449
    repo.create_identity("Ada", "a@b", IdentityScope::User)
2450
        .unwrap();
2451
    repo.set_user_config("core.sign", "change").unwrap();
2452
    write(root, "a.txt", b"one\ntwo\n");
2453
    let h0 = repo.commit("base", &[]).unwrap();
2454
    write(root, "a.txt", b"one\nTWO\n");
2455
    let h1 = repo.commit("edit two", &[]).unwrap();
2456
    write(root, "a.txt", b"one\nTWO\nthree\n");
2457
    let h2 = repo.commit("add three", &[]).unwrap();
2458
    let id1 = repo.store().get_change(&h1).unwrap().change_id;
2459
2460
    // Fixing the line h1 introduced folds into h1; h2 is rewritten on top.
2461
    write(root, "a.txt", b"one\nTWO!\nthree\n");
2462
    let h1b = repo.amend_into(&h1, None).unwrap();
2463
    assert_ne!(h1b, h1);
2464
    let c1b = repo.store().get_change(&h1b).unwrap();
2465
    assert_eq!(c1b.change_id, id1);
2466
    assert_eq!(c1b.deps, vec![h0]);
2467
    assert!(matches!(
2468
        repo.verify_change(&h1b).unwrap(),
2469
        SignatureStatus::Valid { .. }
2470
    ));
2471
    let heads = repo.bookmark_heads().unwrap();
2472
    assert_eq!(heads.len(), 1);
2473
    let top = repo.store().get_change(&heads[0]).unwrap();
2474
    assert_eq!(top.message, "add three");
2475
    assert_eq!(
2476
        top.deps.iter().copied().collect::<BTreeSet<_>>(),
2477
        [h0, h1b].into_iter().collect(),
2478
        "depends on the file's creator and the rewritten line"
2479
    );
2480
    let snap = repo.load_state(&heads).unwrap().materialize();
2481
    assert!(
2482
        matches!(&snap.files["a.txt"].content, FileContent::Text { bytes, .. } if bytes == b"one\nTWO!\nthree\n")
2483
    );
2484
    assert!(
2485
        !repo.snapshot("status").unwrap().changed,
2486
        "the working copy is clean after folding"
2487
    );
2488
    // Only h1b's own state shows the fix without "three".
2489
    let only = repo.load_state(&[h1b]).unwrap().materialize();
2490
    assert!(
2491
        matches!(&only.files["a.txt"].content, FileContent::Text { bytes, .. } if bytes == b"one\nTWO!\n")
2492
    );
2493
    assert_eq!(repo.log().unwrap().len(), 4);
2494
2495
    // An edit to a line introduced by h2 cannot fold into h1.
2496
    write(root, "a.txt", b"one\nTWO!\nthree!\n");
2497
    let err = repo.amend_into(&h1b, None).unwrap_err().to_string();
2498
    assert!(err.contains("introduced after"), "{err}");
2499
    assert!(
2500
        repo.snapshot("status").unwrap().statuses.len() == 1,
2501
        "nothing was changed by the refusal"
2502
    );
2503
    write(root, "a.txt", b"one\nTWO!\nthree\n");
2504
2505
    // Split the head that touches two files.
2506
    write(root, "b.txt", b"b\n");
2507
    write(root, "c.txt", b"c\n");
2508
    let h3 = repo.commit("b and c", &[]).unwrap();
2509
    let id3 = repo.store().get_change(&h3).unwrap().change_id;
2510
    let (p1, p2) = repo.split(&h3, &["b.txt".into()]).unwrap();
2511
    let c_1 = repo.store().get_change(&p1).unwrap();
2512
    let c_2 = repo.store().get_change(&p2).unwrap();
2513
    assert!(c_1.message.contains("part 1: b.txt"));
2514
    assert_eq!(c_2.change_id, id3);
2515
    let heads: BTreeSet<_> = repo.bookmark_heads().unwrap().into_iter().collect();
2516
    assert!(
2517
        heads.contains(&p1) && heads.contains(&p2),
2518
        "independent parts are both heads"
2519
    );
2520
    let snap = repo
2521
        .load_state(&repo.bookmark_heads().unwrap())
2522
        .unwrap()
2523
        .materialize();
2524
    assert!(snap.files.contains_key("b.txt") && snap.files.contains_key("c.txt"));
2525
    let only1 = repo.load_state(&[p1]).unwrap().materialize();
2526
    assert!(only1.files.contains_key("b.txt") && !only1.files.contains_key("c.txt"));
2527
    assert!(!repo.snapshot("status").unwrap().changed);
2528
    assert!(repo.split(&p2, &["nope.txt".into()]).is_err());
2529
    let _ = h2;
2530
}
2531
2532
#[test]
2533
fn identity_lifecycle() {
2534
    hermetic();
2535
    let dir = tempfile::tempdir().unwrap();
2536
    let root = dir.path();
2537
    let origin = Repo::init(&root.join("origin")).unwrap();
2538
    let url = root.join("origin").to_string_lossy().to_string();
2539
    let mut a = Repo::clone(&url, &root.join("a"))
2540
        .unwrap()
2541
        .with_home(root.join("home-a"));
2542
    a.set_user_config("core.sign", "change").unwrap();
2543
    let (key_a, _) = a
2544
        .create_identity("Ada", "[email protected]", IdentityScope::User)
2545
        .unwrap();
2546
    write(&root.join("a"), "a.txt", b"a\n");
2547
    let h1 = a.commit("one", &[]).unwrap();
2548
    assert!(a.policy_init().unwrap().applied);
2549
    assert!(a.push("origin", false).unwrap().iter().all(|r| r.ok));
2550
    origin.refresh().unwrap();
2551
2552
    // Expiry: an identity that had expired when the change was made does not authenticate it.
2553
    let mut e = Repo::init(&root.join("e"))
2554
        .unwrap()
2555
        .with_home(root.join("home-e"));
2556
    e.set_user_config("core.sign", "change").unwrap();
2557
    e.create_identity_with(
2558
        "Eve",
2559
        "[email protected]",
2560
        IdentityScope::User,
2561
        Some(Hlc::now().wall_ms - 1),
2562
    )
2563
    .unwrap();
2564
    write(&root.join("e"), "e.txt", b"e\n");
2565
    let he = e.commit("late", &[]).unwrap();
2566
    assert!(
2567
        matches!(e.verify_change(&he).unwrap(), SignatureStatus::Invalid(m) if m.contains("expired"))
2568
    );
2569
    // Renewal re-issues the identity (same keys, new KeyId) with a later expiry.
2570
    let r = e
2571
        .renew_identity(Some(Hlc::now().wall_ms + 86_400_000))
2572
        .unwrap();
2573
    assert_eq!(e.identity(&r.new).unwrap().previous, Some(r.old));
2574
    write(&root.join("e"), "e.txt", b"e2\n");
2575
    let he2 = e.commit("in time", &[]).unwrap();
2576
    assert!(
2577
        matches!(e.verify_change(&he2).unwrap(), SignatureStatus::Valid { key, .. } if key == r.new)
2578
    );
2579
2580
    // Rotation: a fresh key; the old change still verifies; the policy follows.
2581
    let r = a.rotate_identity().unwrap();
2582
    assert_eq!(r.old, key_a);
2583
    assert_eq!(a.config.author_key, Some(r.new));
2584
    assert_eq!(a.identity(&r.new).unwrap().previous, Some(key_a));
2585
    assert!(r.policy.as_ref().unwrap().applied);
2586
    let (_, sp) = a.current_policy().unwrap().unwrap();
2587
    assert_eq!(
2588
        (sp.policy.serial, sp.policy.roots.clone()),
2589
        (2, vec![r.new])
2590
    );
2591
    assert!(
2592
        !sp.policy.revoked.contains(&key_a) && sp.policy.authorizes(&r.new, "main"),
2593
        "superseded, not revoked"
2594
    );
2595
    assert!(sp.policy.succeeds(&r.new, &key_a) && !sp.policy.succeeds(&key_a, &r.new));
2596
    assert!(
2597
        matches!(a.verify_change(&h1).unwrap(), SignatureStatus::Valid { key, revoked: false, .. } if key == key_a)
2598
    );
2599
    write(&root.join("a"), "a.txt", b"a2\n");
2600
    let h2 = a.commit("two", &[]).unwrap();
2601
    assert!(
2602
        matches!(a.verify_change(&h2).unwrap(), SignatureStatus::Valid { key, revoked: false, .. } if key == r.new)
2603
    );
2604
    // Origin accepts the rotated policy (signed by the old root) and the new key's change.
2605
    let res = a.push("origin", false).unwrap();
2606
    origin.refresh().unwrap();
2607
    assert!(res.iter().all(|x| x.ok), "{res:?}");
2608
    assert_eq!(origin.current_policy().unwrap().unwrap().1.policy.serial, 2);
2609
    let key_a = r.new;
2610
2611
    // Delegation: Bob may sign on Ada's behalf. Delegates live in the
2612
    // identity object, so Ada's KeyId changes while her keys stay the same.
2613
    let mut b = Repo::clone(&url, &root.join("b"))
2614
        .unwrap()
2615
        .with_home(root.join("home-b"));
2616
    let (key_b, id_b) = b
2617
        .create_identity("Bob", "[email protected]", IdentityScope::User)
2618
        .unwrap();
2619
    let r = a.delegate_add(id_b.clone(), Scope::ALL, None).unwrap();
2620
    assert_eq!(r.old, key_a);
2621
    let key_a2 = r.new;
2622
    assert_eq!(
2623
        a.identity(&key_a2).unwrap().delegates,
2624
        vec![Delegate::full(key_b)]
2625
    );
2626
    assert_eq!(
2627
        a.identity(&key_a2).unwrap().ed25519_pk,
2628
        a.identity(&key_a).unwrap().ed25519_pk
2629
    );
2630
    assert!(
2631
        a.delegate_add(id_b.clone(), Scope::ALL, None).is_err(),
2632
        "already a delegate"
2633
    );
2634
    assert!(a.push("origin", false).unwrap().iter().all(|x| x.ok));
2635
    origin.refresh().unwrap();
2636
    write(&root.join("a"), "a.txt", b"a3\n");
2637
    let h3 = a.commit("three", &[]).unwrap();
2638
    assert!(
2639
        matches!(a.verify_change(&h3).unwrap(), SignatureStatus::Valid { key, .. } if key == key_a2),
2640
        "the same secret signs under the new KeyId"
2641
    );
2642
    // A change authored by Ada but signed only by Bob verifies through the delegation.
2643
    a.set_user_config("core.sign", "seal").unwrap();
2644
    write(&root.join("a"), "a.txt", b"a4\n");
2645
    let h4 = a.commit("four", &[]).unwrap();
2646
    assert_eq!(a.verify_change(&h4).unwrap(), SignatureStatus::Unsigned);
2647
    let (_, sk_b) = b.secret_key().unwrap().unwrap();
2648
    a.store()
2649
        .put_signature(&h4, &sk_b.sign(Domain::Change, &key_b, &h4))
2650
        .unwrap();
2651
    assert!(
2652
        matches!(a.verify_change(&h4).unwrap(), SignatureStatus::Valid { key, .. } if key == key_b)
2653
    );
2654
    a.set_user_config("core.sign", "change").unwrap();
2655
    // Withdrawing the delegation re-issues the identity again.
2656
    let r = a.delegate_remove(&key_b).unwrap();
2657
    assert!(a.identity(&r.new).unwrap().delegates.is_empty());
2658
    assert!(a.delegate_remove(&key_b).is_err());
2659
    let key_a3 = r.new;
2660
    let res = a.push("origin", false).unwrap();
2661
    origin.refresh().unwrap();
2662
    assert!(res.iter().all(|x| x.ok), "{res:?}");
2663
2664
    // Multi-signer policy: Bob becomes a root and the threshold rises to 2,
2665
    // both applied under the old threshold of 1. A grant then needs Bob too.
2666
    assert!(a.policy_root_add(id_b.clone()).unwrap().applied);
2667
    assert!(a.policy_root_add(id_b.clone()).is_err());
2668
    assert!(a.policy_set_threshold(3).is_err());
2669
    assert!(a.policy_set_threshold(2).unwrap().applied);
2670
    assert!(a.push("origin", false).unwrap().iter().all(|x| x.ok));
2671
    origin.refresh().unwrap();
2672
    b.pull("origin").unwrap();
2673
    assert_eq!(
2674
        b.current_policy().unwrap().unwrap().1.policy.root_threshold,
2675
        2
2676
    );
2677
    let mut c = Repo::init(&root.join("c"))
2678
        .unwrap()
2679
        .with_home(root.join("home-c"));
2680
    let (key_c, id_c) = c
2681
        .create_identity("Cy", "[email protected]", IdentityScope::User)
2682
        .unwrap();
2683
    let serial_before = a.current_policy().unwrap().unwrap().1.policy.serial;
2684
    let proposal = a.policy_grant(id_c, None).unwrap();
2685
    assert!(!proposal.applied && proposal.sigs.len() == 1);
2686
    assert_eq!(proposal.policy.serial, serial_before + 1);
2687
    assert_eq!(
2688
        a.current_policy().unwrap().unwrap().1.policy.serial,
2689
        serial_before,
2690
        "a proposal changes nothing yet"
2691
    );
2692
    // Bob signs the proposal, handed over as a file, and it applies for him.
2693
    let bytes = proposal.signed().encode();
2694
    let signed = b
2695
        .policy_sign(SignedPolicy::decode(&bytes).unwrap())
2696
        .unwrap();
2697
    assert!(signed.applied && signed.sigs.len() == 2);
2698
    assert!(b
2699
        .current_policy()
2700
        .unwrap()
2701
        .unwrap()
2702
        .1
2703
        .policy
2704
        .authorizes(&key_c, "main"));
2705
    assert!(
2706
        b.policy_sign(signed.signed()).is_err(),
2707
        "a stale proposal is refused"
2708
    );
2709
    // Bob publishes it and Ada picks it up.
2710
    assert!(b
2711
        .push("origin", false)
2712
        .unwrap()
2713
        .iter()
2714
        .any(|x| x.name == "policy" && x.ok));
2715
    origin.refresh().unwrap();
2716
    a.pull("origin").unwrap();
2717
    assert_eq!(
2718
        a.current_policy().unwrap().unwrap().1.policy.serial,
2719
        serial_before + 1
2720
    );
2721
    // A root cannot revoke itself; revoking Cy needs both roots but is recorded locally at once.
2722
    assert!(a.policy_revoke(&key_a3).is_err());
2723
    let u = a
2724
        .revoke_identity(&key_c, "left the project")
2725
        .unwrap()
2726
        .unwrap();
2727
    assert!(!u.applied);
2728
    assert!(a.is_revoked(&key_c).unwrap());
2729
    assert!(!b.is_revoked(&key_c).unwrap());
2730
    let u = b.policy_sign(u.signed()).unwrap();
2731
    assert!(u.applied && u.policy.is_revoked(&key_c));
2732
    assert!(b.is_revoked(&key_c).unwrap());
2733
    // Bob can revoke Ada's root key, leaving himself as the only root (threshold 2 would be unmeetable).
2734
    assert!(
2735
        b.policy_revoke(&key_a3).is_err(),
2736
        "would leave one root for a threshold of 2"
2737
    );
2738
    // Revoking one's own key without a policy root works locally: a plain marker plus attestation.
2739
    let key_c_own = c.config.author_key.unwrap();
2740
    assert!(c
2741
        .revoke_identity(&key_c_own, "lost laptop")
2742
        .unwrap()
2743
        .is_none());
2744
    assert!(c.is_revoked(&key_c_own).unwrap());
2745
    assert_eq!(key_c_own, key_c);
2746
}
2747
2748
#[test]
2749
fn renames_are_detected_and_tracked_as_moves() {
2750
    hermetic();
2751
    let dir = tempfile::tempdir().unwrap();
2752
    let root = dir.path();
2753
    let repo = Repo::init(root).unwrap().with_home(root.join("home"));
2754
    write(
2755
        root,
2756
        "src/old.rs",
2757
        b"fn a() {}\nfn b() {}\nfn c() {}\nfn d() {}\n",
2758
    );
2759
    write(root, "img.bin", b"\x89PNG\0\0\x01\x02");
2760
    write(root, "tiny.txt", b"x\n");
2761
    let h1 = repo.commit("base", &[]).unwrap();
2762
    let node_old = repo.load_state(&[h1]).unwrap().materialize().files["src/old.rs"].node;
2763
    let node_img = repo.load_state(&[h1]).unwrap().materialize().files["img.bin"].node;
2764
2765
    // Rename with a small edit, a binary moved unchanged, and a rewrite
2766
    // that shares nothing with the removed file.
2767
    fs::remove_file(root.join("src/old.rs")).unwrap();
2768
    write(
2769
        root,
2770
        "lib/new.rs",
2771
        b"fn a() {}\nfn b() {}\nfn c() {}\nfn e() {}\n",
2772
    );
2773
    fs::remove_file(root.join("img.bin")).unwrap();
2774
    write(root, "assets/img.bin", b"\x89PNG\0\0\x01\x02");
2775
    fs::remove_file(root.join("tiny.txt")).unwrap();
2776
    write(root, "other.txt", b"completely different\n");
2777
    let snap = repo.snapshot("status").unwrap();
2778
    let statuses: Vec<(&str, ChangeStatus)> = snap
2779
        .statuses
2780
        .iter()
2781
        .map(|s| (s.path.as_str(), s.status))
2782
        .collect();
2783
    assert_eq!(
2784
        statuses,
2785
        vec![
2786
            ("assets/img.bin", ChangeStatus::Renamed),
2787
            ("lib/new.rs", ChangeStatus::Renamed),
2788
            ("other.txt", ChangeStatus::Added),
2789
            ("src", ChangeStatus::Removed),
2790
            ("tiny.txt", ChangeStatus::Removed)
2791
        ]
2792
    );
2793
    let h2 = repo.commit("move things", &[]).unwrap();
2794
    let c = repo.store().get_change(&h2).unwrap();
2795
    let moves: Vec<_> = c
2796
        .tree_ops
2797
        .iter()
2798
        .filter(|op| matches!(op, TreeOp::Move { .. }))
2799
        .collect();
2800
    assert_eq!(moves.len(), 2, "{:?}", c.tree_ops);
2801
    assert!(c.tree_ops.iter().any(
2802
        |op| matches!(op, TreeOp::Move { node, name, .. } if *node == node_old && name == "new.rs")
2803
    ));
2804
    assert!(c.tree_ops.iter().any(
2805
        |op| matches!(op, TreeOp::Move { node, name, .. } if *node == node_img && name == "img.bin")
2806
    ));
2807
    let snap = repo.load_state(&[h2]).unwrap().materialize();
2808
    assert_eq!(
2809
        snap.files["lib/new.rs"].node, node_old,
2810
        "the node survives the rename"
2811
    );
2812
    assert!(
2813
        matches!(&snap.files["lib/new.rs"].content, FileContent::Text { bytes, .. } if bytes == b"fn a() {}\nfn b() {}\nfn c() {}\nfn e() {}\n")
2814
    );
2815
    assert!(!snap.files.contains_key("src/old.rs") && !snap.files.contains_key("src"));
2816
    assert!(render_change(
2817
        &c,
2818
        &repo.load_state(&[h1]).unwrap(),
2819
        &repo.load_state(&[h1]).unwrap().materialize()
2820
    )
2821
    .contains("R "));
2822
    // A fresh checkout reproduces the tree.
2823
    let other = tempfile::tempdir().unwrap();
2824
    let clone = Repo::clone(&root.to_string_lossy(), other.path()).unwrap();
2825
    assert_eq!(
2826
        fs::read(other.path().join("lib/new.rs")).unwrap(),
2827
        b"fn a() {}\nfn b() {}\nfn c() {}\nfn e() {}\n"
2828
    );
2829
    assert!(!other.path().join("src").exists());
2830
    assert!(!clone.snapshot("status").unwrap().changed);
2831
    // Similarity is line based, byte weighted.
2832
    assert_eq!(similarity(b"a\nb\n", b"a\nb\n"), 100);
2833
    assert_eq!(similarity(b"a\nb\nc\nd\n", b"a\nb\nx\ny\n"), 50);
2834
    assert_eq!(similarity(b"hello\n", b"world\n"), 0);
2835
    assert_eq!(similarity(b"", b"x\n"), 0);
2836
}
2837
2838
#[test]
2839
fn git_fetch_and_push_round_trip() {
2840
    hermetic();
2841
    if std::process::Command::new("git")
2842
        .arg("--version")
2843
        .output()
2844
        .is_err()
2845
    {
2846
        eprintln!("git not installed; skipping");
2847
        return;
2848
    }
2849
    let dir = tempfile::tempdir().unwrap();
2850
    let root = dir.path();
2851
    let git_in = |d: &Path, args: &[&str]| -> String {
2852
        let out = std::process::Command::new("git")
2853
            .arg("-C")
2854
            .arg(d)
2855
            .args([
2856
                "-c",
2857
                "user.name=Grace",
2858
                "-c",
2859
                "[email protected]",
2860
                "-c",
2861
                "commit.gpgsign=false",
2862
            ])
2863
            .args(args)
2864
            .output()
2865
            .unwrap();
2866
        assert!(
2867
            out.status.success(),
2868
            "git {args:?}: {}",
2869
            String::from_utf8_lossy(&out.stderr)
2870
        );
2871
        String::from_utf8_lossy(&out.stdout).trim().to_string()
2872
    };
2873
    // A bare "remote" and a work tree that pushes to it.
2874
    let remote = root.join("remote.git");
2875
    fs::create_dir_all(&remote).unwrap();
2876
    git_in(&remote, &["init", "-q", "--bare", "-b", "main"]);
2877
    let work = root.join("work");
2878
    git_in(
2879
        root,
2880
        &[
2881
            "clone",
2882
            "-q",
2883
            remote.to_str().unwrap(),
2884
            work.to_str().unwrap(),
2885
        ],
2886
    );
2887
    git_in(&work, &["checkout", "-q", "-b", "main"]);
2888
    write(&work, "README.md", b"# Project\n");
2889
    write(&work, "src/lib.rs", b"pub fn a() {}\n");
2890
    git_in(&work, &["add", "."]);
2891
    git_in(&work, &["commit", "-q", "-m", "initial"]);
2892
    write(&work, "src/lib.rs", b"pub fn a() {}\npub fn b() {}\n");
2893
    git_in(&work, &["commit", "-q", "-am", "second"]);
2894
    git_in(&work, &["push", "-q", "origin", "main"]);
2895
    let tip1 = git_in(&work, &["rev-parse", "HEAD"]);
2896
2897
    // Fetch into a fresh oxy repository.
2898
    let o = root.join("oxy");
2899
    let mut repo = Repo::init(&o).unwrap().with_home(root.join("home"));
2900
    repo.create_identity("Ada", "[email protected]", IdentityScope::User)
2901
        .unwrap();
2902
    let url = remote.to_string_lossy().to_string();
2903
    let r = repo.git_fetch(&url, "main").unwrap();
2904
    assert_eq!((r.commits, r.heads), (2, 1));
2905
    assert_eq!(
2906
        fs::read(o.join("src/lib.rs")).unwrap(),
2907
        b"pub fn a() {}\npub fn b() {}\n"
2908
    );
2909
    assert!(!repo.snapshot("status").unwrap().changed);
2910
    assert_eq!(
2911
        repo.git_fetch(&url, "main").unwrap().commits,
2912
        0,
2913
        "nothing new"
2914
    );
2915
2916
    // An oxy change, pushed back: one commit on top of the Git tip.
2917
    write(
2918
        &o,
2919
        "src/lib.rs",
2920
        b"pub fn a() {}\npub fn b() {}\npub fn c() {}\n",
2921
    );
2922
    write(&o, "NOTES.md", b"from oxy\n");
2923
    let h_oxy = repo.commit("add c and notes", &[]).unwrap();
2924
    let r = repo.git_push(&url, "main").unwrap();
2925
    assert_eq!(r.exported, 1, "{r:?}");
2926
    git_in(&work, &["pull", "-q", "--ff-only", "origin", "main"]);
2927
    assert_eq!(
2928
        git_in(&work, &["log", "--format=%s", "main"]),
2929
        "add c and notes\nsecond\ninitial"
2930
    );
2931
    assert_eq!(git_in(&work, &["rev-parse", "HEAD~1"]), tip1);
2932
    assert_eq!(fs::read(work.join("NOTES.md")).unwrap(), b"from oxy\n");
2933
    assert_eq!(git_in(&work, &["log", "-1", "--format=%an", "main"]), "Ada");
2934
    assert!(git_in(&work, &["log", "-1", "--format=%B", "main"])
2935
        .contains(&format!("Oxy-Hash: {}", h_oxy.to_hex())));
2936
    assert_eq!(
2937
        repo.git_push(&url, "main").unwrap().exported,
2938
        0,
2939
        "already pushed"
2940
    );
2941
2942
    // Git moves on; pushing without fetching is refused, fetching brings
2943
    // the commit in and the working copy follows.
2944
    write(&work, "README.md", b"# Project\n\nMore.\n");
2945
    git_in(&work, &["commit", "-q", "-am", "readme from git"]);
2946
    git_in(&work, &["push", "-q", "origin", "main"]);
2947
    let tip2 = git_in(&work, &["rev-parse", "HEAD"]);
2948
    assert!(repo
2949
        .git_push(&url, "main")
2950
        .unwrap_err()
2951
        .to_string()
2952
        .contains("fetch"));
2953
    let r = repo.git_fetch(&url, "main").unwrap();
2954
    assert_eq!(
2955
        (r.commits, r.heads),
2956
        (1, 2),
2957
        "the Git change and the oxy change commute"
2958
    );
2959
    assert_eq!(
2960
        fs::read(o.join("README.md")).unwrap(),
2961
        b"# Project\n\nMore.\n"
2962
    );
2963
    assert_eq!(fs::read(o.join("NOTES.md")).unwrap(), b"from oxy\n");
2964
    assert!(!repo.snapshot("status").unwrap().changed);
2965
    // Another oxy change pushes on top of Git's newest commit.
2966
    write(&o, "NOTES.md", b"from oxy\nagain\n");
2967
    repo.commit("notes again", &[]).unwrap();
2968
    assert_eq!(repo.git_push(&url, "main").unwrap().exported, 1);
2969
    git_in(&work, &["pull", "-q", "--ff-only", "origin", "main"]);
2970
    assert_eq!(git_in(&work, &["rev-parse", "HEAD~1"]), tip2);
2971
    assert_eq!(
2972
        fs::read(work.join("NOTES.md")).unwrap(),
2973
        b"from oxy\nagain\n"
2974
    );
2975
    assert_eq!(
2976
        git_in(&work, &["log", "--format=%s", "main"])
2977
            .lines()
2978
            .count(),
2979
        5
2980
    );
2981
}
2982
2983
/// Benchmark, not a gate: `cargo test --release -p oxy-core --lib bench_one_gibibyte -- --ignored --nocapture`.
2984
/// Commits, stores, clones, and reads back a 1 GiB incompressible file.
2985
#[test]
2986
#[ignore]
2987
fn bench_one_gibibyte_file() {
2988
    hermetic();
2989
    // /tmp is often a small tmpfs; `OXY_BENCH_DIR` picks a roomier disk.
2990
    let dir = match std::env::var_os("OXY_BENCH_DIR") {
2991
        Some(d) => tempfile::tempdir_in(d).unwrap(),
2992
        None => tempfile::tempdir().unwrap(),
2993
    };
2994
    let root = dir.path();
2995
    let repo = Repo::init(&root.join("r"))
2996
        .unwrap()
2997
        .with_home(root.join("home"));
2998
    let size = 1usize << 30;
2999
    let mut data = vec![0u8; size];
3000
    let mut x = 0x9e3779b97f4a7c15u64;
3001
    for chunk in data.chunks_mut(8) {
3002
        x ^= x << 13;
3003
        x ^= x >> 7;
3004
        x ^= x << 17;
3005
        let b = x.to_le_bytes();
3006
        chunk.copy_from_slice(&b[..chunk.len()]);
3007
    }
3008
    let t = std::time::Instant::now();
3009
    write(&root.join("r"), "big.bin", &data);
3010
    eprintln!("write 1 GiB to disk: {:.2?}", t.elapsed());
3011
    let t = std::time::Instant::now();
3012
    let h = repo.commit("big", &[]).unwrap();
3013
    eprintln!("commit (chunk + hash + store): {:.2?}", t.elapsed());
3014
    let t = std::time::Instant::now();
3015
    assert!(!repo.snapshot("status").unwrap().changed);
3016
    eprintln!("status on a clean 1 GiB working copy: {:.2?}", t.elapsed());
3017
    let t = std::time::Instant::now();
3018
    let objects = repo.store().list().unwrap().len();
3019
    eprintln!("objects stored: {objects} ({:.2?} to list)", t.elapsed());
3020
    let t = std::time::Instant::now();
3021
    let g = repo.gc(true).unwrap();
3022
    eprintln!("gc (pack): {:.2?} {g:?}", t.elapsed());
3023
    let t = std::time::Instant::now();
3024
    let clone = Repo::clone(&root.join("r").to_string_lossy(), &root.join("c")).unwrap();
3025
    eprintln!("clone (fetch + checkout): {:.2?}", t.elapsed());
3026
    let t = std::time::Instant::now();
3027
    let back = fs::read(root.join("c/big.bin")).unwrap();
3028
    assert_eq!(blake3::hash(&back), blake3::hash(&data));
3029
    eprintln!("read back and verify: {:.2?}", t.elapsed());
3030
    assert_eq!(clone.bookmark_heads().unwrap(), vec![h]);
3031
    let store_bytes: u64 = walkdir_size(&root.join("r/.oxy/objects"));
3032
    eprintln!(
3033
        "store size: {:.1} MiB for 1 GiB of data",
3034
        store_bytes as f64 / (1024.0 * 1024.0)
3035
    );
3036
}
3037
3038
fn walkdir_size(p: &Path) -> u64 {
3039
    let mut total = 0;
3040
    if let Ok(rd) = fs::read_dir(p) {
3041
        for e in rd.flatten() {
3042
            let path = e.path();
3043
            if path.is_dir() {
3044
                total += walkdir_size(&path);
3045
            } else if let Ok(m) = fs::metadata(&path) {
3046
                total += m.len();
3047
            }
3048
        }
3049
    }
3050
    total
3051
}
3052
3053
/// An opaque file whose size and mtime match the manifest is not read on
3054
/// the next snapshot: its blob comes from the manifest's stat cache.
3055
#[cfg(unix)]
3056
#[test]
3057
fn stat_cache_skips_reading_unchanged_opaque_files() {
3058
    use std::os::unix::fs::PermissionsExt;
3059
    hermetic();
3060
    let dir = tempfile::tempdir().unwrap();
3061
    let root = dir.path();
3062
    let repo = Repo::init(root).unwrap().with_home(root.join("home"));
3063
    let mut big = vec![0u8; 300 * 1024];
3064
    for (i, b) in big.iter_mut().enumerate() {
3065
        *b = (i as u32).wrapping_mul(2654435761).to_le_bytes()[1];
3066
    }
3067
    big[0] = 0;
3068
    write(root, "big.bin", &big);
3069
    write(root, "a.txt", b"text\n");
3070
    let h1 = repo.commit("base", &[]).unwrap();
3071
    let (_, _, m) = repo.read_manifest().unwrap().unwrap();
3072
    assert!(
3073
        m.entries["big.bin"].blob.is_some(),
3074
        "opaque files record their blob"
3075
    );
3076
    assert!(m.entries["a.txt"].blob.is_none());
3077
    let blob = m.entries["big.bin"].blob.unwrap();
3078
    assert!(repo.store().has(&blob));
3079
3080
    // Files modified within two seconds of the manifest are racy and still
3081
    // read; age the file so the cache applies, then snapshot to record it.
3082
    let old = std::time::SystemTime::now() - std::time::Duration::from_secs(30);
3083
    fs::File::options()
3084
        .write(true)
3085
        .open(root.join("big.bin"))
3086
        .unwrap()
3087
        .set_modified(old)
3088
        .unwrap();
3089
    assert!(!repo.snapshot("status").unwrap().changed);
3090
    // Now the file cannot be read at all; the snapshot succeeds without it.
3091
    fs::set_permissions(root.join("big.bin"), fs::Permissions::from_mode(0o000)).unwrap();
3092
    let snap = repo.snapshot("status").unwrap();
3093
    assert!(
3094
        !snap.changed && snap.statuses.is_empty(),
3095
        "{:?}",
3096
        snap.statuses
3097
    );
3098
    fs::set_permissions(root.join("big.bin"), fs::Permissions::from_mode(0o644)).unwrap();
3099
    // A real change (new mtime, new content) is seen and committed correctly.
3100
    let mut big2 = big.clone();
3101
    big2[10] ^= 0xff;
3102
    write(root, "big.bin", &big2);
3103
    let snap = repo.snapshot("status").unwrap();
3104
    assert_eq!(
3105
        snap.statuses
3106
            .iter()
3107
            .map(|s| (s.path.as_str(), s.status))
3108
            .collect::<Vec<_>>(),
3109
        vec![("big.bin", ChangeStatus::Modified)]
3110
    );
3111
    let h2 = repo.commit("edit", &[]).unwrap();
3112
    let files = repo.load_state(&[h2]).unwrap().materialize().files;
3113
    assert_eq!(
3114
        files["big.bin"].content,
3115
        FileContent::Opaque {
3116
            blobs: vec![Repo::blob_ref(&big2)]
3117
        }
3118
    );
3119
    // Checkout writes a manifest with blobs too, so the next status is cached.
3120
    repo.checkout(&[h1], false, "checkout").unwrap();
3121
    let (_, _, m) = repo.read_manifest().unwrap().unwrap();
3122
    assert_eq!(m.entries["big.bin"].blob, Some(Repo::blob_ref(&big)));
3123
    assert!(!repo.snapshot("status").unwrap().changed);
3124
}
3125
3126
#[test]
3127
fn status_json_lists_conflicts_with_contributors() {
3128
    hermetic();
3129
    let dir = tempfile::tempdir().unwrap();
3130
    let root = dir.path();
3131
    let repo = Repo::init(root).unwrap().with_home(root.join("home"));
3132
    write(root, "a.txt", b"one\n");
3133
    let h1 = repo.commit("base", &[]).unwrap();
3134
    write(root, "a.txt", b"one\nleft\n");
3135
    let ha = repo.commit("left", &[]).unwrap();
3136
    repo.checkout(&[h1], true, "checkout").unwrap();
3137
    write(root, "a.txt", b"one\nright\n");
3138
    let hb = repo.commit("right", &[]).unwrap();
3139
    repo.checkout(&[ha, hb], true, "checkout").unwrap();
3140
    let snap = repo.snapshot("status").unwrap();
3141
    assert!(snap.base_snapshot.is_conflicted());
3142
    let json = repo.status_json(&snap).unwrap();
3143
    let ida = repo.store().get_change(&ha).unwrap().change_id.to_hex();
3144
    let idb = repo.store().get_change(&hb).unwrap().change_id.to_hex();
3145
    assert!(json.contains("\"conflicted\":true"), "{json}");
3146
    assert!(
3147
        json.contains("\"kind\":\"text\",\"path\":\"a.txt\""),
3148
        "{json}"
3149
    );
3150
    assert!(json.contains(&ida) && json.contains(&idb), "{json}");
3151
    assert!(json.contains("\"resolved\":false"), "{json}");
3152
    assert!(json.starts_with('{') && json.ends_with('}'));
3153
    // Resolve and the report says so; a clean copy has no conflicts.
3154
    write(root, "a.txt", b"one\nleft\nright\n");
3155
    let snap = repo.snapshot("status").unwrap();
3156
    let json = repo.status_json(&snap).unwrap();
3157
    assert!(json.contains("\"resolved\":true"), "{json}");
3158
    repo.commit("resolve", &[]).unwrap();
3159
    let snap = repo.snapshot("status").unwrap();
3160
    let json = repo.status_json(&snap).unwrap();
3161
    assert!(
3162
        json.contains("\"clean\":true,\"conflicted\":false,\"paths\":[],\"conflicts\":[]"),
3163
        "{json}"
3164
    );
3165
}
3166
3167
#[test]
3168
fn ignore_rules_do_not_untrack_files() {
3169
    hermetic();
3170
    let dir = tempfile::tempdir().unwrap();
3171
    let root = dir.path();
3172
    let repo = Repo::init(root).unwrap().with_home(root.join("home"));
3173
    write(root, "src.c", b"int x;\n");
3174
    write(root, "build/out.o", b"\0obj");
3175
    write(root, "sub/keep.log", b"keep\n");
3176
    write(root, "sub/junk.log", b"junk\n");
3177
    write(root, ".oxyignore", b"/build\n*.log\n!sub/keep.log\n");
3178
    let snap = repo.snapshot("status").unwrap();
3179
    let added: Vec<&str> = snap.statuses.iter().map(|s| s.path.as_str()).collect();
3180
    assert_eq!(
3181
        added,
3182
        vec![".oxyignore", "src.c", "sub/keep.log"],
3183
        "anchored, glob, and negated rules"
3184
    );
3185
    let h1 = repo.commit("base", &[]).unwrap();
3186
    // Ignoring a tracked file changes nothing about it.
3187
    write(root, ".oxyignore", b"/build\n*.log\n!sub/keep.log\nsrc.c\n");
3188
    let snap = repo.snapshot("status").unwrap();
3189
    assert_eq!(
3190
        snap.statuses
3191
            .iter()
3192
            .map(|s| s.path.as_str())
3193
            .collect::<Vec<_>>(),
3194
        vec![".oxyignore"]
3195
    );
3196
    let h2 = repo.commit("ignore src.c", &[]).unwrap();
3197
    assert!(repo
3198
        .load_state(&[h2])
3199
        .unwrap()
3200
        .materialize()
3201
        .files
3202
        .contains_key("src.c"));
3203
    // Its edits are still seen, by status and by the prompt.
3204
    assert_eq!(repo.quick_dirty().unwrap(), Some(false));
3205
    write(root, "src.c", b"int x, y;\n");
3206
    assert_eq!(repo.quick_dirty().unwrap(), Some(true));
3207
    let snap = repo.snapshot("status").unwrap();
3208
    assert_eq!(
3209
        snap.statuses
3210
            .iter()
3211
            .map(|s| (s.path.as_str(), s.status))
3212
            .collect::<Vec<_>>(),
3213
        vec![("src.c", ChangeStatus::Modified)]
3214
    );
3215
    let h3 = repo.commit("edit src.c", &[]).unwrap();
3216
    assert!(
3217
        matches!(&repo.load_state(&[h3]).unwrap().materialize().files["src.c"].content, FileContent::Text { bytes, .. } if bytes == b"int x, y;\n")
3218
    );
3219
    // Deleting it on disk removes it, ignored or not; a checkout brings it back.
3220
    fs::remove_file(root.join("src.c")).unwrap();
3221
    let snap = repo.snapshot("status").unwrap();
3222
    assert_eq!(
3223
        snap.statuses
3224
            .iter()
3225
            .map(|s| (s.path.as_str(), s.status))
3226
            .collect::<Vec<_>>(),
3227
        vec![("src.c", ChangeStatus::Removed)]
3228
    );
3229
    repo.checkout(&[h3], true, "checkout").unwrap();
3230
    assert_eq!(fs::read(root.join("src.c")).unwrap(), b"int x, y;\n");
3231
    assert!(!repo.snapshot("status").unwrap().changed);
3232
    let _ = h1;
3233
}
3234
3235
#[test]
3236
fn split_works_on_non_heads_by_node() {
3237
    hermetic();
3238
    let dir = tempfile::tempdir().unwrap();
3239
    let root = dir.path();
3240
    let repo = Repo::init(root).unwrap().with_home(root.join("home"));
3241
    write(root, "a.txt", b"one\n");
3242
    write(root, "junk/x.lock", b"lock\n");
3243
    let h1 = repo.commit("work plus junk", &[]).unwrap();
3244
    write(root, "a.txt", b"one\ntwo\n");
3245
    let h2 = repo.commit("more work", &[]).unwrap();
3246
    assert_eq!(repo.store().get_change(&h2).unwrap().deps, vec![h1]);
3247
    let id1 = repo.store().get_change(&h1).unwrap().change_id;
3248
    // h1 is not a head: split it by node.
3249
    let (hj, h1b) = repo.split(&h1, &["junk".into()]).unwrap();
3250
    assert_ne!(h1b, h1);
3251
    assert_eq!(
3252
        repo.store().get_change(&h1b).unwrap().change_id,
3253
        id1,
3254
        "the rest keeps the ChangeId"
3255
    );
3256
    let junk = repo.store().get_change(&hj).unwrap();
3257
    assert!(junk.tree_ops.iter().all(
3258
        |op| matches!(op, TreeOp::AddNode { name, .. } if name == "junk" || name == "x.lock")
3259
    ));
3260
    let heads = repo.bookmark_heads().unwrap();
3261
    assert!(
3262
        heads.contains(&hj),
3263
        "the split-off part is a head of its own"
3264
    );
3265
    let snap = repo.load_state(&heads).unwrap().materialize();
3266
    assert!(
3267
        matches!(&snap.files["a.txt"].content, FileContent::Text { bytes, .. } if bytes == b"one\ntwo\n"),
3268
        "the dependent was rewritten onto the new hash"
3269
    );
3270
    assert!(snap.files.contains_key("junk/x.lock"));
3271
    let h2b = heads
3272
        .iter()
3273
        .find(|h| repo.store().get_change(h).unwrap().message == "more work")
3274
        .copied()
3275
        .unwrap();
3276
    assert_eq!(repo.store().get_change(&h2b).unwrap().deps, vec![h1b]);
3277
    assert!(!repo.snapshot("status").unwrap().changed);
3278
    // Abandoning the split-off head removes the junk from history.
3279
    repo.abandon(&hj).unwrap();
3280
    let heads = repo.bookmark_heads().unwrap();
3281
    let snap = repo.load_state(&heads).unwrap().materialize();
3282
    assert!(!snap.files.contains_key("junk/x.lock") && !snap.files.contains_key("junk"));
3283
    assert!(snap.files.contains_key("a.txt"));
3284
    // A dependent that touches the split-off paths blocks the split.
3285
    write(root, "junk/y.lock", b"y\n");
3286
    let hb = repo.commit("junk base", &[]).unwrap();
3287
    write(root, "junk/y.lock", b"yy\n");
3288
    write(root, "b.txt", b"b\n");
3289
    repo.commit("touches junk", &[]).unwrap();
3290
    let err = repo.split(&hb, &["junk".into()]).unwrap_err().to_string();
3291
    assert!(err.contains("depends on the split-off paths"), "{err}");
3292
}
3293
3294
#[test]
3295
fn bookmarks_switch_merge_and_push() {
3296
    hermetic();
3297
    let dir = tempfile::tempdir().unwrap();
3298
    let root = dir.path();
3299
    let origin = Repo::init(&root.join("origin")).unwrap();
3300
    let url = root.join("origin").to_string_lossy().to_string();
3301
    let mut repo = Repo::clone(&url, &root.join("r"))
3302
        .unwrap()
3303
        .with_home(root.join("home"));
3304
    let r = root.join("r");
3305
    write(&r, "a.txt", b"a\n");
3306
    let h_a = repo.commit("a", &[]).unwrap();
3307
    assert!(repo.push("origin", false).unwrap()[0].ok);
3308
    origin.refresh().unwrap();
3309
3310
    // A bookmark at the working copy's base, then work on it.
3311
    assert!(repo.bookmark_create("bad name..", None).is_err());
3312
    assert!(repo.bookmark_create("-x", None).is_err());
3313
    assert_eq!(repo.bookmark_create("feature", None).unwrap(), vec![h_a]);
3314
    assert!(repo.bookmark_create("feature", None).is_err(), "exists");
3315
    repo.bookmark_switch("feature", false).unwrap();
3316
    assert_eq!(repo.config.bookmark, "feature");
3317
    write(&r, "a.txt", b"a\nb\n");
3318
    write(&r, "b.txt", b"b\n");
3319
    let h_b = repo.commit("b on feature", &[]).unwrap();
3320
    assert_eq!(
3321
        repo.bookmark_heads().unwrap(),
3322
        vec![h_b],
3323
        "b edits a.txt, so it depends on a"
3324
    );
3325
    assert_eq!(
3326
        repo.resolve_heads("main").unwrap(),
3327
        vec![h_a],
3328
        "main is untouched"
3329
    );
3330
    assert_eq!(
3331
        repo.resolve_change("feature").unwrap(),
3332
        h_b,
3333
        "a one-head bookmark names its change"
3334
    );
3335
    // Reopening keeps the workspace's bookmark.
3336
    let reopened = Repo::open(&r).unwrap().with_home(root.join("home"));
3337
    assert_eq!(reopened.config.bookmark, "feature");
3338
    // Back to main: b.txt goes away; work there.
3339
    repo.bookmark_switch("main", false).unwrap();
3340
    assert!(!r.join("b.txt").exists());
3341
    assert_eq!(fs::read(r.join("a.txt")).unwrap(), b"a\n");
3342
    write(&r, "c.txt", b"c\n");
3343
    let h_c = repo.commit("c on main", &[]).unwrap();
3344
    let list = repo.bookmarks().unwrap();
3345
    assert_eq!(
3346
        list.iter()
3347
            .map(|b| (b.name.as_str(), b.current))
3348
            .collect::<Vec<_>>(),
3349
        vec![("feature", false), ("main", true)]
3350
    );
3351
    assert_eq!(
3352
        list.iter().find(|b| b.name == "main").unwrap().ahead,
3353
        Some(1),
3354
        "c is not on origin yet"
3355
    );
3356
    // Merge feature into main: the union, both heads, no merge change.
3357
    let m = repo.merge("feature").unwrap();
3358
    assert!(m.changed && m.checked_out);
3359
    let mut want = vec![h_b, h_c];
3360
    want.sort();
3361
    assert_eq!(m.heads, want);
3362
    assert_eq!(fs::read(r.join("b.txt")).unwrap(), b"b\n");
3363
    assert!(!repo.merge("feature").unwrap().changed, "already merged");
3364
    assert!(repo.merge("main").is_err());
3365
    // The other bookmark can be pushed by name and appears at origin.
3366
    assert!(repo.push_bookmark("origin", "feature", false).unwrap()[0].ok);
3367
    origin.refresh().unwrap();
3368
    assert_eq!(origin.resolve_heads("feature").unwrap(), vec![h_b]);
3369
    assert!(repo.push("origin", false).unwrap()[0].ok);
3370
    origin.refresh().unwrap();
3371
    assert_eq!(
3372
        repo.bookmarks()
3373
            .unwrap()
3374
            .iter()
3375
            .find(|b| b.name == "main")
3376
            .unwrap()
3377
            .ahead,
3378
        Some(0)
3379
    );
3380
    // A second workspace inherits the current bookmark and can switch independently.
3381
    let ws = repo.workspace_add(&root.join("ws"), None).unwrap();
3382
    assert_eq!(ws.config.bookmark, "main");
3383
    let mut ws = ws;
3384
    ws.bookmark_switch("feature", false).unwrap();
3385
    assert_eq!(
3386
        Repo::open(&r).unwrap().config.bookmark,
3387
        "main",
3388
        "the first workspace is unaffected"
3389
    );
3390
    assert!(
3391
        repo.bookmark_delete("feature").is_err(),
3392
        "current bookmark of another workspace"
3393
    );
3394
    ws.bookmark_switch("main", false).unwrap();
3395
    // Set and delete.
3396
    assert_eq!(repo.bookmark_set("feature", &[h_a]).unwrap(), vec![h_a]);
3397
    assert!(repo.bookmark_delete("main").is_err(), "current here");
3398
    repo.bookmark_delete("feature").unwrap();
3399
    assert!(repo.resolve_heads("feature").is_err());
3400
    assert!(repo.bookmark_set("feature", &[h_a]).is_err());
3401
    assert!(
3402
        repo.checkout(&[h_a], false, "checkout").is_ok(),
3403
        "changes of a deleted bookmark remain"
3404
    );
3405
}
3406
3407
#[test]
3408
fn oxygen_subrepos_pin_follow_and_update() {
3409
    hermetic();
3410
    let dir = tempfile::tempdir().unwrap();
3411
    let root = dir.path();
3412
    // A library repository with two commits, and a bare-ish origin for it.
3413
    let lib_origin = Repo::init(&root.join("lib-origin")).unwrap();
3414
    let lib_url = root.join("lib-origin").to_string_lossy().to_string();
3415
    let lib = Repo::clone(&lib_url, &root.join("lib"))
3416
        .unwrap()
3417
        .with_home(root.join("home"));
3418
    write(&root.join("lib"), "lib.txt", b"v1\n");
3419
    let l1 = lib.commit("lib v1", &[]).unwrap();
3420
    assert!(lib.push("origin", false).unwrap()[0].ok);
3421
    let _ = lib_origin;
3422
3423
    // The application (a clone of its own origin) adds it as a subrepo.
3424
    let app_origin = Repo::init(&root.join("app-origin")).unwrap();
3425
    let app_url = root.join("app-origin").to_string_lossy().to_string();
3426
    let _ = app_origin;
3427
    let app_dir = root.join("app");
3428
    let app = Repo::clone(&app_url, &app_dir)
3429
        .unwrap()
3430
        .with_home(root.join("home"));
3431
    write(&app_dir, "main.txt", b"app\n");
3432
    let pin = app.submodule_add(&lib_url, "libs/lib", None).unwrap();
3433
    assert!(matches!(&pin, crate::subrepo::Pin::Oxy { heads, .. } if heads == &vec![l1]));
3434
    assert!(app_dir.join(".oxymodules").exists() && app_dir.join("libs/lib/.oxy").is_dir());
3435
    let snap = app.snapshot("status").unwrap();
3436
    let paths: Vec<&str> = snap.statuses.iter().map(|s| s.path.as_str()).collect();
3437
    assert_eq!(
3438
        paths,
3439
        vec![".oxymodules", "libs/lib", "main.txt"],
3440
        "the nested files are not walked"
3441
    );
3442
    let a1 = app.commit("app with lib", &[]).unwrap();
3443
    let files = app.load_state(&[a1]).unwrap().materialize().files;
3444
    assert_eq!(files["libs/lib"].kind, NodeKind::Subrepo);
3445
    assert!(!files.contains_key("libs/lib/lib.txt"));
3446
    assert!(!app.snapshot("status").unwrap().changed);
3447
    let subs = app.subrepos().unwrap();
3448
    assert_eq!(subs.len(), 1);
3449
    assert_eq!(subs[0].actual.as_ref(), Some(&subs[0].pin));
3450
3451
    // Advance the nested repository: the parent sees a modified pin.
3452
    let nested = Repo::open(&app_dir.join("libs/lib"))
3453
        .unwrap()
3454
        .with_home(root.join("home"));
3455
    write(&app_dir.join("libs/lib"), "lib.txt", b"v2\n");
3456
    let l2 = nested.commit("lib v2", &[]).unwrap();
3457
    assert!(nested.push("origin", false).unwrap()[0].ok);
3458
    let snap = app.snapshot("status").unwrap();
3459
    assert_eq!(
3460
        snap.statuses
3461
            .iter()
3462
            .map(|s| (s.path.as_str(), s.status))
3463
            .collect::<Vec<_>>(),
3464
        vec![("libs/lib", ChangeStatus::Modified)]
3465
    );
3466
    let a2 = app.commit("bump lib", &[]).unwrap();
3467
    // Checking out the older app state brings the nested working copy back
3468
    // to the older pin, but never moves its bookmark backwards (oxygen#38).
3469
    let r = app.checkout(&[a1], false, "checkout").unwrap();
3470
    assert!(
3471
        r.notes.len() == 1 && r.notes[0].contains("keeps 1 newer change"),
3472
        "{:?}",
3473
        r.notes
3474
    );
3475
    assert_eq!(fs::read(app_dir.join("libs/lib/lib.txt")).unwrap(), b"v1\n");
3476
    let nested = Repo::open(&app_dir.join("libs/lib")).unwrap();
3477
    assert_eq!(nested.bookmark_heads().unwrap(), vec![l2]);
3478
    assert_eq!(nested.working_copy().unwrap().1.deps, vec![l1]);
3479
    assert!(!app.snapshot("status").unwrap().changed);
3480
    // A dirty nested repository is left alone and reported.
3481
    write(&app_dir.join("libs/lib"), "scratch.txt", b"wip\n");
3482
    let r = app.checkout(&[a2], false, "checkout").unwrap();
3483
    assert!(
3484
        r.notes.iter().any(|n| n.contains("uncommitted")),
3485
        "{:?}",
3486
        r.notes
3487
    );
3488
    assert_eq!(fs::read(app_dir.join("libs/lib/lib.txt")).unwrap(), b"v1\n");
3489
    fs::remove_file(app_dir.join("libs/lib/scratch.txt")).unwrap();
3490
    let r = app.submodule_update(false, &[]).unwrap();
3491
    assert_eq!(r, vec![("libs/lib".to_string(), SubrepoSync::Updated)]);
3492
    assert_eq!(fs::read(app_dir.join("libs/lib/lib.txt")).unwrap(), b"v2\n");
3493
    let _ = l2;
3494
3495
    // A fresh clone of the app has the pin but no nested repository until update --init.
3496
    assert!(app.push("origin", false).unwrap()[0].ok);
3497
    let clone_dir = root.join("app-clone");
3498
    let clone = Repo::clone(&app_url, &clone_dir)
3499
        .unwrap()
3500
        .with_home(root.join("home"));
3501
    assert!(!clone_dir.join("libs/lib/.oxy").exists());
3502
    assert_eq!(
3503
        clone.submodule_update(false, &[]).unwrap(),
3504
        vec![("libs/lib".to_string(), SubrepoSync::Missing)]
3505
    );
3506
    assert_eq!(
3507
        clone.submodule_update(true, &[]).unwrap(),
3508
        vec![("libs/lib".to_string(), SubrepoSync::Updated)]
3509
    );
3510
    assert_eq!(
3511
        fs::read(clone_dir.join("libs/lib/lib.txt")).unwrap(),
3512
        b"v2\n"
3513
    );
3514
    assert!(!clone.snapshot("status").unwrap().changed);
3515
    // Removing the subrepo leaves the directory and drops the node.
3516
    clone.submodule_remove("libs/lib").unwrap();
3517
    let snap = clone.snapshot("status").unwrap();
3518
    assert!(
3519
        snap.statuses
3520
            .iter()
3521
            .any(|s| s.path == "libs/lib" && s.status == ChangeStatus::Removed),
3522
        "{:?}",
3523
        snap.statuses
3524
    );
3525
    let c = clone.commit("drop lib", &[]).unwrap();
3526
    assert!(!clone
3527
        .load_state(&[c])
3528
        .unwrap()
3529
        .materialize()
3530
        .files
3531
        .contains_key("libs/lib"));
3532
    assert!(clone_dir.join("libs/lib/lib.txt").exists());
3533
    assert!(
3534
        !clone.snapshot("status").unwrap().changed,
3535
        "an unregistered nested repository is ignored"
3536
    );
3537
}
3538
3539
#[test]
3540
fn git_submodules_import_and_export_as_gitlinks() {
3541
    hermetic();
3542
    if std::process::Command::new("git")
3543
        .arg("--version")
3544
        .output()
3545
        .is_err()
3546
    {
3547
        eprintln!("git not installed; skipping");
3548
        return;
3549
    }
3550
    let dir = tempfile::tempdir().unwrap();
3551
    let root = dir.path();
3552
    let git_in = |d: &Path, args: &[&str]| -> String {
3553
        let out = std::process::Command::new("git")
3554
            .arg("-C")
3555
            .arg(d)
3556
            .args([
3557
                "-c",
3558
                "user.name=Grace",
3559
                "-c",
3560
                "[email protected]",
3561
                "-c",
3562
                "commit.gpgsign=false",
3563
                "-c",
3564
                "protocol.file.allow=always",
3565
            ])
3566
            .args(args)
3567
            .output()
3568
            .unwrap();
3569
        assert!(
3570
            out.status.success(),
3571
            "git {args:?}: {}",
3572
            String::from_utf8_lossy(&out.stderr)
3573
        );
3574
        String::from_utf8_lossy(&out.stdout).trim().to_string()
3575
    };
3576
    let sub = root.join("sub");
3577
    fs::create_dir_all(&sub).unwrap();
3578
    git_in(&sub, &["init", "-q", "-b", "main"]);
3579
    write(&sub, "s.txt", b"sub\n");
3580
    git_in(&sub, &["add", "."]);
3581
    git_in(&sub, &["commit", "-q", "-m", "sub initial"]);
3582
    let sub_sha = git_in(&sub, &["rev-parse", "HEAD"]);
3583
    let g = root.join("main.git");
3584
    fs::create_dir_all(&g).unwrap();
3585
    git_in(&g, &["init", "-q", "-b", "main"]);
3586
    write(&g, "README.md", b"# app\n");
3587
    git_in(&g, &["add", "."]);
3588
    git_in(&g, &["commit", "-q", "-m", "initial"]);
3589
    git_in(
3590
        &g,
3591
        &[
3592
            "submodule",
3593
            "add",
3594
            "-q",
3595
            sub.to_str().unwrap(),
3596
            "vendor/sub",
3597
        ],
3598
    );
3599
    git_in(&g, &["commit", "-q", "-m", "add submodule"]);
3600
3601
    let dest = root.join("oxy");
3602
    let repo = Repo::init(&dest).unwrap().with_home(root.join("home"));
3603
    let rep = repo.import_git(&g, "main").unwrap();
3604
    assert_eq!((rep.commits, rep.submodules), (2, 1));
3605
    let files = repo
3606
        .load_state(&repo.bookmark_heads().unwrap())
3607
        .unwrap()
3608
        .materialize()
3609
        .files;
3610
    assert_eq!(files["vendor/sub"].kind, NodeKind::Subrepo);
3611
    let FileContent::Opaque { blobs } = &files["vendor/sub"].content else {
3612
        panic!()
3613
    };
3614
    assert_eq!(
3615
        crate::subrepo::Pin::decode(&repo.read_blob(&blobs[0]).unwrap()).unwrap(),
3616
        crate::subrepo::Pin::Git {
3617
            sha: sub_sha.clone(),
3618
            branch: "HEAD".into()
3619
        }
3620
    );
3621
    let modules =
3622
        crate::subrepo::Modules::parse(&fs::read_to_string(dest.join(".oxymodules")).unwrap());
3623
    assert_eq!(modules.entries["vendor/sub"].url, sub.to_string_lossy());
3624
    assert!(modules.entries["vendor/sub"].git);
3625
    assert!(
3626
        files.contains_key(".gitmodules"),
3627
        "the Git file is kept for round trips"
3628
    );
3629
    assert!(
3630
        !dest.join("vendor/sub/.git").exists(),
3631
        "not cloned until update --init"
3632
    );
3633
    assert!(!repo.snapshot("status").unwrap().changed);
3634
    // update --init clones it at the pinned commit; status is unchanged.
3635
    assert_eq!(
3636
        repo.submodule_update(true, &[]).unwrap(),
3637
        vec![("vendor/sub".to_string(), SubrepoSync::Updated)]
3638
    );
3639
    assert_eq!(
3640
        git_in(&dest.join("vendor/sub"), &["rev-parse", "HEAD"]),
3641
        sub_sha
3642
    );
3643
    assert!(!repo.snapshot("status").unwrap().changed);
3644
    // Export writes the gitlink and .gitmodules back.
3645
    let mirror = root.join("mirror.git");
3646
    let rep = repo.git_export(&mirror).unwrap();
3647
    assert_eq!(rep.skipped_subrepos, 0);
3648
    let ls = git_in(&mirror, &["ls-tree", "main", "vendor/sub"]);
3649
    assert!(
3650
        ls.starts_with("160000 commit ") && ls.contains(&sub_sha),
3651
        "{ls}"
3652
    );
3653
    assert_eq!(
3654
        git_in(&mirror, &["ls-tree", "--name-only", "main"]),
3655
        ".gitmodules\nREADME.md\nvendor"
3656
    );
3657
    let orig_tree = git_in(&g, &["rev-parse", "main^{tree}"]);
3658
    assert_eq!(
3659
        git_in(&mirror, &["rev-parse", "main^{tree}"]),
3660
        orig_tree,
3661
        "tree round trip"
3662
    );
3663
}
3664
3665
#[test]
3666
fn partial_commits_by_path_and_by_hunk() {
3667
    hermetic();
3668
    let dir = tempfile::tempdir().unwrap();
3669
    let root = dir.path();
3670
    let repo = Repo::init(root).unwrap().with_home(root.join("home"));
3671
    write(root, "a.txt", b"1\n2\n3\n");
3672
    write(root, "b.txt", b"b\n");
3673
    let h0 = repo.commit("base", &[]).unwrap();
3674
    write(root, "a.txt", b"0\n1\n2\n3\n4\n");
3675
    write(root, "b.txt", b"b\nbb\n");
3676
    write(root, "c.txt", b"c\n");
3677
    // By path: only a.txt goes in; the rest stays on disk as uncommitted work.
3678
    let h1 = repo
3679
        .commit_selection("a only", &[], &Selection::Paths(vec!["a.txt".into()]))
3680
        .unwrap();
3681
    let c1 = repo.store().get_change(&h1).unwrap();
3682
    assert!(
3683
        c1.tree_ops.is_empty() && c1.edits.iter().all(|e| e.node() == c1.edits[0].node()),
3684
        "{:?}",
3685
        c1.tree_ops
3686
    );
3687
    assert_eq!(c1.deps, vec![h0]);
3688
    let files = repo.load_state(&[h1]).unwrap().materialize().files;
3689
    assert!(
3690
        matches!(&files["a.txt"].content, FileContent::Text { bytes, .. } if bytes == b"0\n1\n2\n3\n4\n")
3691
    );
3692
    assert!(matches!(&files["b.txt"].content, FileContent::Text { bytes, .. } if bytes == b"b\n"));
3693
    assert!(!files.contains_key("c.txt"));
3694
    let snap = repo.snapshot("status").unwrap();
3695
    assert_eq!(
3696
        snap.statuses
3697
            .iter()
3698
            .map(|s| (s.path.as_str(), s.status))
3699
            .collect::<Vec<_>>(),
3700
        vec![
3701
            ("b.txt", ChangeStatus::Modified),
3702
            ("c.txt", ChangeStatus::Added)
3703
        ]
3704
    );
3705
    assert_eq!(
3706
        fs::read(root.join("b.txt")).unwrap(),
3707
        b"b\nbb\n",
3708
        "disk untouched"
3709
    );
3710
    // By hunk: pick the b.txt insert; c.txt's addition is left.
3711
    let (_, hunks) = repo.hunks().unwrap();
3712
    let b_hunk = hunks
3713
        .iter()
3714
        .find(|h| h.path == "b.txt" && h.text.contains("+bb"))
3715
        .unwrap()
3716
        .index;
3717
    let h2 = repo
3718
        .commit_selection("b only", &[], &Selection::Hunks(vec![b_hunk]))
3719
        .unwrap();
3720
    let files = repo.load_state(&[h2]).unwrap().materialize().files;
3721
    assert!(
3722
        matches!(&files["b.txt"].content, FileContent::Text { bytes, .. } if bytes == b"b\nbb\n")
3723
    );
3724
    assert!(!files.contains_key("c.txt"));
3725
    let snap = repo.snapshot("status").unwrap();
3726
    assert_eq!(
3727
        snap.statuses
3728
            .iter()
3729
            .map(|s| s.path.as_str())
3730
            .collect::<Vec<_>>(),
3731
        vec!["c.txt"]
3732
    );
3733
    // Choosing only the content hunk of a file in a new directory pulls in
3734
    // the directory and file additions it needs.
3735
    write(root, "d/e.txt", b"e\n");
3736
    let (_, hunks) = repo.hunks().unwrap();
3737
    let e_insert = hunks
3738
        .iter()
3739
        .find(|h| h.path == "d/e.txt" && h.text.contains("+e"))
3740
        .unwrap()
3741
        .index;
3742
    let h3 = repo
3743
        .commit_selection("e only", &[], &Selection::Hunks(vec![e_insert]))
3744
        .unwrap();
3745
    let c3 = repo.store().get_change(&h3).unwrap();
3746
    assert_eq!(c3.tree_ops.len(), 2, "{:?}", c3.tree_ops);
3747
    let files = repo.load_state(&[h3]).unwrap().materialize().files;
3748
    assert!(files.contains_key("d/e.txt") && !files.contains_key("c.txt"));
3749
    // Choosing a new file's addition hunk brings its content along.
3750
    write(root, "f/g.txt", b"g\n");
3751
    let (_, hunks) = repo.hunks().unwrap();
3752
    let g_add = hunks
3753
        .iter()
3754
        .find(|h| h.path == "f/g.txt" && h.text.starts_with("A "))
3755
        .unwrap()
3756
        .index;
3757
    let h4 = repo
3758
        .commit_selection("g by addition", &[], &Selection::Hunks(vec![g_add]))
3759
        .unwrap();
3760
    let files = repo.load_state(&[h4]).unwrap().materialize().files;
3761
    assert!(
3762
        matches!(&files["f/g.txt"].content, FileContent::Text { bytes, .. } if bytes == b"g\n")
3763
    );
3764
    assert!(!repo
3765
        .snapshot("status")
3766
        .unwrap()
3767
        .statuses
3768
        .iter()
3769
        .any(|s| s.path == "f/g.txt"));
3770
    // Everything left commits normally; the working copy is then clean.
3771
    repo.commit("the rest", &[]).unwrap();
3772
    assert!(!repo.snapshot("status").unwrap().changed);
3773
    let files = repo
3774
        .load_state(&repo.bookmark_heads().unwrap())
3775
        .unwrap()
3776
        .materialize()
3777
        .files;
3778
    assert!(files.contains_key("c.txt"));
3779
}
3780
3781
#[test]
3782
fn blame_attributes_lines_to_introducing_changes_across_renames() {
3783
    hermetic();
3784
    let dir = tempfile::tempdir().unwrap();
3785
    let root = dir.path();
3786
    let mut repo = Repo::init(root).unwrap().with_home(root.join("home"));
3787
    repo.create_identity("Ada", "[email protected]", IdentityScope::User)
3788
        .unwrap();
3789
    write(root, "a.txt", b"one\n");
3790
    let h1 = repo.commit("first", &[]).unwrap();
3791
    write(root, "a.txt", b"one\ntwo\n");
3792
    let h2 = repo.commit("second", &[]).unwrap();
3793
    let b = repo.blame("a.txt").unwrap();
3794
    assert_eq!(
3795
        b.iter()
3796
            .map(|l| (l.line, l.hash, l.text.as_slice()))
3797
            .collect::<Vec<_>>(),
3798
        vec![(1, h1, b"one\n".as_slice()), (2, h2, b"two\n".as_slice())]
3799
    );
3800
    assert!(b.iter().all(|l| l.author == "Ada"));
3801
    assert_eq!(
3802
        b[0].change_id,
3803
        repo.store().get_change(&h1).unwrap().change_id
3804
    );
3805
    fs::rename(root.join("a.txt"), root.join("b.txt")).unwrap();
3806
    repo.commit("rename", &[]).unwrap();
3807
    let b = repo.blame("b.txt").unwrap();
3808
    assert_eq!(
3809
        b.iter().map(|l| l.hash).collect::<Vec<_>>(),
3810
        vec![h1, h2],
3811
        "the node survives the rename"
3812
    );
3813
    assert!(repo.blame("a.txt").is_err());
3814
}
3815
3816
#[test]
3817
fn bisect_finds_the_first_bad_change() {
3818
    hermetic();
3819
    let dir = tempfile::tempdir().unwrap();
3820
    let root = dir.path();
3821
    let repo = Repo::init(root).unwrap().with_home(root.join("home"));
3822
    let mut content = String::new();
3823
    let mut hashes = Vec::new();
3824
    for i in 1..=8 {
3825
        content.push_str(&format!("line {i}{}\n", if i == 5 { " bug" } else { "" }));
3826
        write(root, "f.txt", content.as_bytes());
3827
        hashes.push(repo.commit(&format!("step {i}"), &[]).unwrap());
3828
    }
3829
    // Each step appends after the previous line, so the chain is linear.
3830
    assert_eq!(repo.bookmark_heads().unwrap(), vec![hashes[7]]);
3831
    repo.bisect_start().unwrap();
3832
    assert!(matches!(
3833
        repo.bisect_mark(Some(true), &[hashes[0]]).unwrap(),
3834
        BisectStep::NeedMarks { good: 1, bad: 0 }
3835
    ));
3836
    let step = repo.bisect_mark(Some(false), &[hashes[7]]).unwrap();
3837
    assert!(
3838
        matches!(step, BisectStep::Testing { remaining: 7, .. }),
3839
        "{step:?}"
3840
    );
3841
    // Automated: bad when the bug line is present.
3842
    let step = repo
3843
        .bisect_run(&["sh".into(), "-c".into(), "! grep -q bug f.txt".into()])
3844
        .unwrap();
3845
    assert_eq!(step, BisectStep::Found { culprit: hashes[4] });
3846
    assert_eq!(
3847
        repo.bisect_status().unwrap(),
3848
        Some(BisectStep::Found { culprit: hashes[4] })
3849
    );
3850
    repo.bisect_reset().unwrap();
3851
    assert_eq!(fs::read_to_string(root.join("f.txt")).unwrap(), content);
3852
    assert!(repo.bisect_status().unwrap().is_none());
3853
    assert!(!repo.snapshot("status").unwrap().changed);
3854
    // Manual marks and a skip.
3855
    repo.bisect_start().unwrap();
3856
    repo.bisect_mark(Some(true), &[hashes[0]]).unwrap();
3857
    let mut step = repo.bisect_mark(Some(false), &[hashes[7]]).unwrap();
3858
    let mut skipped_once = false;
3859
    let mut guard = 0;
3860
    while let BisectStep::Testing { .. } = step {
3861
        guard += 1;
3862
        assert!(guard < 20);
3863
        let text = fs::read_to_string(root.join("f.txt")).unwrap();
3864
        if !skipped_once && text.contains("line 6") {
3865
            // An untestable state away from the boundary: the search routes around it.
3866
            skipped_once = true;
3867
            step = repo.bisect_mark(None, &[]).unwrap();
3868
            continue;
3869
        }
3870
        step = repo.bisect_mark(Some(!text.contains("bug")), &[]).unwrap();
3871
    }
3872
    assert!(skipped_once);
3873
    assert_eq!(step, BisectStep::Found { culprit: hashes[4] });
3874
    repo.bisect_reset().unwrap();
3875
    // Skipping the culprit itself leaves it among the candidates reported.
3876
    repo.bisect_start().unwrap();
3877
    repo.bisect_mark(Some(true), &[hashes[0]]).unwrap();
3878
    let mut step = repo.bisect_mark(Some(false), &[hashes[7]]).unwrap();
3879
    let mut guard = 0;
3880
    while let BisectStep::Testing { heads, .. } = &step {
3881
        guard += 1;
3882
        assert!(guard < 20);
3883
        let text = fs::read_to_string(root.join("f.txt")).unwrap();
3884
        let is_culprit_state =
3885
            heads.contains(&hashes[4]) && !heads.iter().any(|h| hashes[5..].contains(h));
3886
        step = if is_culprit_state {
3887
            repo.bisect_mark(None, &[]).unwrap()
3888
        } else {
3889
            repo.bisect_mark(Some(!text.contains("bug")), &[]).unwrap()
3890
        };
3891
    }
3892
    match step {
3893
        BisectStep::Inconclusive { candidates } => assert!(
3894
            candidates.contains(&hashes[4]) && candidates.len() <= 2,
3895
            "{candidates:?}"
3896
        ),
3897
        other => panic!("{other:?}"),
3898
    }
3899
    repo.bisect_reset().unwrap();
3900
}
3901
3902
#[test]
3903
fn squash_folds_a_change_into_its_dependency() {
3904
    hermetic();
3905
    let dir = tempfile::tempdir().unwrap();
3906
    let root = dir.path();
3907
    let repo = Repo::init(root).unwrap().with_home(root.join("home"));
3908
    write(root, "a.txt", b"1\n");
3909
    let a = repo.commit("A", &[]).unwrap();
3910
    write(root, "a.txt", b"1\n2\n");
3911
    let c = repo.commit("C", &[]).unwrap();
3912
    write(root, "a.txt", b"1\n2\n3\n");
3913
    let e = repo.commit("E", &[]).unwrap();
3914
    write(root, "b.txt", b"b\n");
3915
    let b = repo.commit("B", &[]).unwrap();
3916
    let id_a = repo.store().get_change(&a).unwrap().change_id;
3917
    let id_e = repo.store().get_change(&e).unwrap().change_id;
3918
    // E depends on C which A lacks: refused, naming it.
3919
    let err = repo.squash(&e, &a).unwrap_err().to_string();
3920
    assert!(err.contains(&c.short(12)), "{err}");
3921
    // C into A: A' has both, C is gone, E follows and still reads the same.
3922
    let a2 = repo.squash(&c, &a).unwrap();
3923
    let a2c = repo.store().get_change(&a2).unwrap();
3924
    assert_eq!(a2c.change_id, id_a);
3925
    assert!(a2c.deps.is_empty());
3926
    let heads = repo.bookmark_heads().unwrap();
3927
    let st = repo.load_state(&heads).unwrap();
3928
    assert!(!st.contains(&c) && !st.contains(&a) && !st.contains(&e));
3929
    let e2 = st
3930
        .changes()
3931
        .find(|(_, m)| m.change_id == id_e)
3932
        .map(|(h, _)| *h)
3933
        .unwrap();
3934
    assert_eq!(
3935
        repo.store().get_change(&e2).unwrap().deps,
3936
        vec![a2],
3937
        "E now depends on A' alone"
3938
    );
3939
    let files = st.materialize().files;
3940
    assert!(
3941
        matches!(&files["a.txt"].content, FileContent::Text { bytes, .. } if bytes == b"1\n2\n3\n")
3942
    );
3943
    assert!(files.contains_key("b.txt"));
3944
    assert!(st.contains(&b));
3945
    assert!(!repo.snapshot("status").unwrap().changed);
3946
    assert_eq!(repo.log().unwrap().len(), 4, "working copy, B, E', A'");
3947
    // Undo restores the three original changes.
3948
    repo.undo().unwrap();
3949
    repo.undo().unwrap();
3950
    let st = repo.load_state(&repo.bookmark_heads().unwrap()).unwrap();
3951
    assert!(st.contains(&c) && st.contains(&a) && st.contains(&e));
3952
}
3953
3954
#[test]
3955
fn rebase_re_expresses_a_change_against_another_base() {
3956
    hermetic();
3957
    let dir = tempfile::tempdir().unwrap();
3958
    let root = dir.path();
3959
    let repo = Repo::init(root).unwrap().with_home(root.join("home"));
3960
    write(root, "a.txt", b"1\n2\n");
3961
    let a = repo.commit("A", &[]).unwrap();
3962
    write(root, "a.txt", b"1\n2\n3\n");
3963
    let c = repo.commit("C: append 3", &[]).unwrap();
3964
    write(root, "a.txt", b"1\n2\n3\n4\n");
3965
    let e = repo.commit("E: append 4", &[]).unwrap();
3966
    // A different base: A plus a change that prepends a line.
3967
    repo.checkout(&[a], true, "checkout").unwrap();
3968
    write(root, "a.txt", b"0\n1\n2\n");
3969
    let d = repo.commit("D: prepend 0", &[]).unwrap();
3970
    let id_c = repo.store().get_change(&c).unwrap().change_id;
3971
    let id_e = repo.store().get_change(&e).unwrap().change_id;
3972
    // Rebase C onto D: its effect (append 3) re-derived against D's text.
3973
    let c2 = repo.rebase(&c, &[d]).unwrap();
3974
    let c2c = repo.store().get_change(&c2).unwrap();
3975
    assert_eq!(c2c.change_id, id_c);
3976
    assert!(c2c.deps.contains(&d), "{:?}", c2c.deps);
3977
    let heads = repo.bookmark_heads().unwrap();
3978
    let st = repo.load_state(&heads).unwrap();
3979
    assert!(!st.contains(&c) && st.contains(&d));
3980
    let e2 = st
3981
        .changes()
3982
        .find(|(_, m)| m.change_id == id_e)
3983
        .map(|(h, _)| *h)
3984
        .unwrap();
3985
    let e2deps = repo.store().get_change(&e2).unwrap().deps;
3986
    assert!(
3987
        e2deps.contains(&c2) && !e2deps.contains(&c) && e2deps.contains(&a),
3988
        "E follows C by content and still depends on A, which introduced the file: {e2deps:?}"
3989
    );
3990
    let files = st.materialize().files;
3991
    assert!(
3992
        matches!(&files["a.txt"].content, FileContent::Text { bytes, .. } if bytes == b"0\n1\n2\n3\n4\n"),
3993
        "{:?}",
3994
        files["a.txt"].content
3995
    );
3996
    assert!(!files["a.txt"].is_conflicted());
3997
    // Rebasing onto a state that already contains the change is refused.
3998
    assert!(repo.rebase(&c2, &[c2]).is_err());
3999
    let err = repo.rebase(&e2, &[d]).unwrap_err().to_string();
4000
    assert!(
4001
        err.contains("lacks dependencies"),
4002
        "E needs C, which D's state does not have: {err}"
4003
    );
4004
}
4005
4006
#[test]
4007
fn unsigned_tags_keep_their_message() {
4008
    hermetic();
4009
    let dir = tempfile::tempdir().unwrap();
4010
    let root = dir.path();
4011
    let repo = Repo::init(root).unwrap().with_home(root.join("home"));
4012
    write(root, "a.txt", b"a\n");
4013
    repo.commit("a", &[]).unwrap();
4014
    assert!(repo.secret_key().unwrap().is_none());
4015
    repo.tag_create("v1", &repo.bookmark_heads().unwrap(), "first release")
4016
        .unwrap();
4017
    let tags = repo.tags().unwrap();
4018
    assert_eq!(
4019
        (
4020
            tags[0].name.as_str(),
4021
            tags[0].message.as_str(),
4022
            tags[0].signer.as_deref()
4023
        ),
4024
        ("v1", "first release", None)
4025
    );
4026
    assert!(
4027
        repo.tag_refs().unwrap()[0].attestation.is_none(),
4028
        "an unsigned attestation is not advertised"
4029
    );
4030
}
4031
4032
#[test]
4033
fn fsck_passes_a_sound_repository_and_names_each_fault() {
4034
    // Files on disk are what this tests: tampering with them, and the
4035
    // directory store's crash points.
4036
    if std::env::var_os("OXY_STORE_BACKEND").is_some() {
4037
        return;
4038
    }
4039
    hermetic();
4040
    let dir = tempfile::tempdir().unwrap();
4041
    let root = dir.path();
4042
    let origin_path = root.join("origin");
4043
    let origin = Repo::init(&origin_path).unwrap();
4044
    let mut a = Repo::clone(&origin_path.to_string_lossy(), &root.join("a"))
4045
        .unwrap()
4046
        .with_home(root.join("home-a"));
4047
    a.create_identity("Ada", "[email protected]", IdentityScope::Repo)
4048
        .unwrap();
4049
    write(&root.join("a"), "f.txt", b"one\n");
4050
    write(&root.join("a"), "bin.dat", b"\0\x01\x02binary");
4051
    let h1 = a.commit("first", &[]).unwrap();
4052
    write(&root.join("a"), "f.txt", b"one\ntwo\n");
4053
    let h2 = a.commit("second", &[]).unwrap();
4054
    a.tag_create("v1", &[h2], "first release").unwrap();
4055
    a.checkpoint().unwrap();
4056
    assert!(a.push("origin", false).unwrap()[0].ok);
4057
    origin.refresh().unwrap();
4058
4059
    // Sound: signed changes, a seal, a tag, a checkpoint, a ref attestation.
4060
    for repo in [&a, &origin] {
4061
        let rep = repo.fsck().unwrap();
4062
        assert_eq!(rep.problems, vec![], "{rep:?}");
4063
        // The two commits, plus the working copy's change in `a`.
4064
        assert!(rep.changes >= 2 && rep.signed >= 2, "{rep:?}");
4065
        assert!(rep.ops > 1 && rep.objects > 5);
4066
    }
4067
    assert!(origin.fsck().unwrap().attestations >= 1);
4068
4069
    // A flipped byte in a stored object is corruption, named by hash.
4070
    let c1 = a.store().path_for(&h1);
4071
    let pristine = fs::read(&c1).unwrap();
4072
    let mut bytes = pristine.clone();
4073
    *bytes.last_mut().unwrap() ^= 1;
4074
    fs::write(&c1, &bytes).unwrap();
4075
    let rep = a.fsck().unwrap();
4076
    assert!(rep.errors() >= 1);
4077
    assert!(
4078
        rep.problems
4079
            .iter()
4080
            .any(|p| p.object == Some(h1) && p.what.contains("unreadable")),
4081
        "{rep:?}"
4082
    );
4083
    fs::write(&c1, &pristine).unwrap();
4084
    assert_eq!(a.fsck().unwrap().errors(), 0);
4085
4086
    // A missing change is named with what needed it.
4087
    fs::remove_file(&c1).unwrap();
4088
    let rep = a.fsck().unwrap();
4089
    assert!(
4090
        rep.problems.iter().any(|p| p.severity == Severity::Error
4091
            && p.object == Some(h1)
4092
            && p.what.contains("change missing, needed by change")),
4093
        "{rep:?}"
4094
    );
4095
    fs::write(&c1, &pristine).unwrap();
4096
4097
    // A missing blob is an error in a full clone.
4098
    let c2 = a.store().get_change(&h1).unwrap();
4099
    let blob = c2
4100
        .edits
4101
        .iter()
4102
        .find_map(|e| match e {
4103
            Edit::Replace { new: Some(b), .. } => Some(*b),
4104
            _ => None,
4105
        })
4106
        .expect("the binary file is a blob");
4107
    let bp = a.store().path_for(&blob);
4108
    let blob_bytes = fs::read(&bp).unwrap();
4109
    fs::remove_file(&bp).unwrap();
4110
    let rep = a.fsck().unwrap();
4111
    assert!(
4112
        rep.problems
4113
            .iter()
4114
            .any(|p| p.object == Some(blob) && p.what.contains("blob missing")),
4115
        "{rep:?}"
4116
    );
4117
    fs::write(&bp, &blob_bytes).unwrap();
4118
4119
    // A broken op log head is reported, not a crash.
4120
    let head = root.join("a/.oxy/ops/head");
4121
    let saved = fs::read(&head).unwrap();
4122
    fs::write(&head, b"not a hash").unwrap();
4123
    let rep = a.fsck().unwrap();
4124
    assert!(
4125
        rep.problems.iter().any(|p| p.what.contains("ops/head")),
4126
        "{rep:?}"
4127
    );
4128
    fs::write(&head, saved).unwrap();
4129
    assert_eq!(a.fsck().unwrap().problems, vec![]);
4130
}
4131
4132
/// Copy a directory tree (for restoring a pristine repository).
4133
fn copy_tree(from: &Path, to: &Path) {
4134
    fs::create_dir_all(to).unwrap();
4135
    for e in fs::read_dir(from).unwrap() {
4136
        let e = e.unwrap();
4137
        let target = to.join(e.file_name());
4138
        if e.file_type().unwrap().is_dir() {
4139
            copy_tree(&e.path(), &target);
4140
        } else {
4141
            fs::copy(e.path(), &target).unwrap();
4142
        }
4143
    }
4144
}
4145
4146
/// Spec §13.6: stop `commit` and `push` at every durable step, as a crash
4147
/// would, and check that both repositories still open, pass `fsck`, and
4148
/// accept the same operation again.
4149
#[test]
4150
fn crash_at_every_step_of_commit_and_push_leaves_sound_repositories() {
4151
    // Files on disk are what this tests: tampering with them, and the
4152
    // directory store's crash points.
4153
    if std::env::var_os("OXY_STORE_BACKEND").is_some() {
4154
        return;
4155
    }
4156
    use crate::durable::failpoint;
4157
    hermetic();
4158
    let dir = tempfile::tempdir().unwrap();
4159
    let pristine = dir.path().join("pristine");
4160
    let origin_path = pristine.join("origin");
4161
    Repo::init(&origin_path).unwrap();
4162
    let mut a = Repo::clone(&origin_path.to_string_lossy(), &pristine.join("a"))
4163
        .unwrap()
4164
        .with_home(dir.path().join("home"));
4165
    a.create_identity("Ada", "[email protected]", IdentityScope::Repo)
4166
        .unwrap();
4167
    write(&pristine.join("a"), "f.txt", b"one\n");
4168
    a.commit("first", &[]).unwrap();
4169
    assert!(a.push("origin", false).unwrap()[0].ok);
4170
    drop(a);
4171
4172
    type Op = fn(&Repo) -> Result<()>;
4173
    let edit_and_commit: Op = |r| {
4174
        write(r.root(), "f.txt", b"one\ntwo\n");
4175
        write(r.root(), "big.bin", &vec![7u8; 300_000]);
4176
        r.commit("second", &[]).map(|_| ())
4177
    };
4178
    let push: Op = |r| {
4179
        let res = r.push("origin", false)?;
4180
        if res.iter().all(|x| x.ok) {
4181
            Ok(())
4182
        } else {
4183
            Err(RepoError::Msg(format!("{res:?}")))
4184
        }
4185
    };
4186
4187
    for (name, prepare, op) in [
4188
        ("commit", None, edit_and_commit),
4189
        ("push", Some(edit_and_commit), push),
4190
    ] {
4191
        let mut steps = 0;
4192
        for n in 1.. {
4193
            let run = dir.path().join(format!("{name}-{n}"));
4194
            copy_tree(&pristine, &run);
4195
            // Clones record their remote by path; point it at this copy.
4196
            let open = |p: &Path| {
4197
                let mut r = Repo::open(p).unwrap().with_home(dir.path().join("home"));
4198
                r.config
4199
                    .set("remote.origin.url", &run.join("origin").to_string_lossy())
4200
                    .unwrap();
4201
                r.save_config().unwrap();
4202
                r
4203
            };
4204
            let a = open(&run.join("a"));
4205
            if let Some(prep) = prepare {
4206
                prep(&a).unwrap();
4207
            }
4208
            failpoint::crash_after(n);
4209
            let outcome = op(&a);
4210
            let crashed = failpoint::disarm();
4211
            drop(a);
4212
            if !crashed {
4213
                outcome.unwrap_or_else(|e| panic!("{name} failed without a crash: {e}"));
4214
                steps = n - 1;
4215
                break;
4216
            }
4217
            assert!(
4218
                outcome.is_err(),
4219
                "{name}: a crash at step {n} was swallowed"
4220
            );
4221
            for repo in ["a", "origin"] {
4222
                let r = Repo::open(&run.join(repo)).unwrap_or_else(|e| {
4223
                    panic!("{name} crash at step {n}: {repo} no longer opens: {e}")
4224
                });
4225
                let rep = r.fsck().unwrap();
4226
                assert_eq!(
4227
                    rep.errors(),
4228
                    0,
4229
                    "{name} crash at step {n}: {repo} fails fsck: {:?}",
4230
                    rep.problems
4231
                );
4232
            }
4233
            // The interrupted operation can simply be run again.
4234
            let a = open(&run.join("a"));
4235
            // A crash after the commit point leaves the commit done.
4236
            let landed = a
4237
                .bookmark_heads()
4238
                .unwrap()
4239
                .iter()
4240
                .any(|h| a.store().get_change(h).unwrap().message == "second");
4241
            let again = match (name, landed) {
4242
                ("commit", true) => Ok(()),
4243
                ("commit", false) => a.commit("second", &[]).map(|_| ()),
4244
                _ => op(&a),
4245
            };
4246
            again.unwrap_or_else(|e| panic!("{name} crash at step {n}: retry failed: {e}"));
4247
            assert_eq!(a.fsck().unwrap().errors(), 0);
4248
            fs::remove_dir_all(&run).unwrap();
4249
        }
4250
        assert!(steps >= 3, "{name} has only {steps} durable steps?");
4251
    }
4252
}
4253
4254
/// Spec §12.1: commands in two workspaces of one repository, and pushes,
4255
/// running at the same time lose nothing: every commit ends up on the
4256
/// bookmark, locally and on the remote, and the repository passes fsck.
4257
#[test]
4258
fn concurrent_commits_in_two_workspaces_lose_nothing() {
4259
    hermetic();
4260
    let dir = tempfile::tempdir().unwrap();
4261
    let root = dir.path();
4262
    let origin = root.join("origin");
4263
    Repo::init_bare_unbound(&origin).unwrap();
4264
    let main = root.join("main");
4265
    let mut repo = Repo::init(&main).unwrap();
4266
    repo.config
4267
        .set("remote.origin.url", &origin.to_string_lossy())
4268
        .unwrap();
4269
    repo.save_config().unwrap();
4270
    write(&main, "seed.txt", b"seed\n");
4271
    repo.commit("seed", &[]).unwrap();
4272
    let second = root.join("second");
4273
    repo.workspace_add(&second, None).unwrap();
4274
    drop(repo);
4275
4276
    const EACH: usize = 15;
4277
    std::thread::scope(|s| {
4278
        for (tag, dir, push) in [("a", main.clone(), true), ("b", second.clone(), false)] {
4279
            s.spawn(move || {
4280
                let r = Repo::open(&dir).unwrap();
4281
                for i in 0..EACH {
4282
                    write(
4283
                        &dir,
4284
                        &format!("{tag}-{i}.txt"),
4285
                        format!("{tag} {i}\n").as_bytes(),
4286
                    );
4287
                    r.commit(&format!("{tag} {i}"), &[]).unwrap();
4288
                    if push && i % 5 == 4 {
4289
                        // A push may be refused while the other workspace moves the bookmark; nothing may be lost either way.
4290
                        let _ = r.push("origin", false);
4291
                    }
4292
                }
4293
            });
4294
        }
4295
    });
4296
4297
    let repo = Repo::open(&main).unwrap();
4298
    let heads = repo.bookmark_heads().unwrap();
4299
    let state = repo.load_state(&heads).unwrap();
4300
    let messages: BTreeSet<String> = state.changes().map(|(_, m)| m.message.clone()).collect();
4301
    for tag in ["a", "b"] {
4302
        for i in 0..EACH {
4303
            assert!(
4304
                messages.contains(&format!("{tag} {i}")),
4305
                "lost commit {tag} {i}; have {messages:?}"
4306
            );
4307
        }
4308
    }
4309
    let rep = repo.fsck().unwrap();
4310
    assert_eq!(rep.errors(), 0, "{:?}", rep.problems);
4311
    assert!(repo.push("origin", false).unwrap().iter().all(|r| r.ok));
4312
    let hosted = Repo::open(&origin).unwrap();
4313
    let hosted_heads = hosted.bookmark_heads().unwrap();
4314
    assert_eq!(
4315
        hosted.load_state(&hosted_heads).unwrap().len(),
4316
        state.len(),
4317
        "the remote has every commit"
4318
    );
4319
}
4320
4321
/// Two operations recorded from the same parent (what two processes do
4322
/// when they race) are merged: both bookmarks' heads survive, and a
4323
/// change made on one side only is kept.
4324
#[test]
4325
fn operations_from_the_same_parent_are_merged() {
4326
    hermetic();
4327
    let dir = tempfile::tempdir().unwrap();
4328
    let root = dir.path();
4329
    let repo = Repo::init(root).unwrap();
4330
    write(root, "a.txt", b"a\n");
4331
    let a = repo.commit("a", &[]).unwrap();
4332
    write(root, "b.txt", b"b\n");
4333
    let b = repo.commit("b", &[]).unwrap();
4334
    let (x, op) = repo.head_op().unwrap();
4335
    let state = |heads: Vec<ChangeHash>| repo.store().put_state(&StateObject::new(heads)).unwrap();
4336
4337
    // Side one moves main to just `a` and adds a bookmark; side two moves main to just `b`.
4338
    let mut one = op.view.clone();
4339
    one.bookmarks.insert("main".into(), state(vec![a]));
4340
    one.bookmarks.insert("topic".into(), state(vec![a]));
4341
    let mut two = op.view.clone();
4342
    two.bookmarks.insert("main".into(), state(vec![b]));
4343
    repo.record_op(&[x], "one", one).unwrap();
4344
    let merged = repo.record_op(&[x], "two", two).unwrap();
4345
4346
    let (head, op) = repo.head_op().unwrap();
4347
    assert_eq!(head, merged);
4348
    assert_eq!(op.parents.len(), 2, "a merge of the two operations");
4349
    assert!(op.command.contains("merged with a concurrent operation"));
4350
    let mut main = repo
4351
        .store()
4352
        .get_state(&op.view.bookmarks["main"])
4353
        .unwrap()
4354
        .heads;
4355
    main.sort();
4356
    let mut want = vec![a, b];
4357
    want.sort();
4358
    assert_eq!(main, want, "both sides' heads are kept");
4359
    assert!(
4360
        op.view.bookmarks.contains_key("topic"),
4361
        "a one-sided change survives"
4362
    );
4363
    assert_eq!(repo.fsck().unwrap().errors(), 0);
4364
}
4365
4366
#[test]
4367
fn failed_requests_come_with_a_next_step() {
4368
    use crate::protocol::hint_for;
4369
    assert!(hint_for("https://h/x/oxy/v1/push: HTTP 401: bad token")
4370
        .unwrap()
4371
        .contains("token"));
4372
    assert!(hint_for("…: HTTP 403: forbidden")
4373
        .unwrap()
4374
        .contains("repo:write"));
4375
    assert!(hint_for("…: HTTP 404: no such repository")
4376
        .unwrap()
4377
        .contains("owner and repository name"));
4378
    assert!(hint_for("invalid peer certificate: UnknownIssuer")
4379
        .unwrap()
4380
        .contains("oxyhub-ca.pem"));
4381
    assert!(hint_for("Connect error: Connection refused (os error 111)")
4382
        .unwrap()
4383
        .contains("running"));
4384
    assert!(hint_for("Dns Failed: failed to lookup address information")
4385
        .unwrap()
4386
        .contains("resolve"));
4387
    assert_eq!(hint_for("something else entirely"), None);
4388
}
4389
4390
#[test]
4391
fn doctor_names_problems_and_what_to_do() {
4392
    hermetic();
4393
    let dir = tempfile::tempdir().unwrap();
4394
    let root = dir.path();
4395
    let origin = root.join("origin");
4396
    Repo::init_bare_unbound(&origin).unwrap();
4397
    let mut repo = Repo::init(&root.join("r"))
4398
        .unwrap()
4399
        .with_home(root.join("home"));
4400
    let find = |r: &DoctorReport, area: &str, h: Health| {
4401
        r.checks
4402
            .iter()
4403
            .find(|c| c.area == area && c.health == h)
4404
            .cloned()
4405
    };
4406
4407
    let r = repo.doctor(true);
4408
    assert!(find(&r, "identity", Health::Warn)
4409
        .unwrap()
4410
        .hint
4411
        .unwrap()
4412
        .contains("oxy identity create"));
4413
    assert!(find(&r, "repository", Health::Ok).is_some());
4414
4415
    repo.create_identity("Ada", "[email protected]", IdentityScope::Repo)
4416
        .unwrap();
4417
    repo.config.set("author.name", "Ada").unwrap();
4418
    repo.config.set("author.email", "[email protected]").unwrap();
4419
    repo.config
4420
        .set("remote.origin.url", &origin.to_string_lossy())
4421
        .unwrap();
4422
    repo.config
4423
        .set("remote.down.url", "http://127.0.0.1:9/a/b")
4424
        .unwrap();
4425
    repo.config.set("remote.down.token", "t").unwrap();
4426
    repo.config
4427
        .set("remote.badca.url", "https://example.invalid/a/b")
4428
        .unwrap();
4429
    repo.config
4430
        .set(
4431
            "remote.badca.ca",
4432
            &root.join("missing.pem").to_string_lossy(),
4433
        )
4434
        .unwrap();
4435
    repo.save_config().unwrap();
4436
4437
    let r = repo.doctor(true);
4438
    assert!(find(&r, "identity", Health::Ok).is_some(), "{r:?}");
4439
    assert!(find(&r, "author", Health::Ok).is_some(), "{r:?}");
4440
    assert!(find(&r, "remote origin", Health::Ok)
4441
        .unwrap()
4442
        .message
4443
        .contains("first push binds it"));
4444
    let down = find(&r, "remote down", Health::Fail).unwrap();
4445
    assert!(
4446
        down.hint.as_deref().unwrap_or("").contains("running"),
4447
        "{down:?}"
4448
    );
4449
    let badca = find(&r, "remote badca", Health::Fail).unwrap();
4450
    assert!(
4451
        badca.hint.unwrap().contains("remote.badca.ca"),
4452
        "the remote's own name is in the hint"
4453
    );
4454
    assert_eq!(r.worst(), Health::Fail);
4455
4456
    // Offline, nothing is contacted.
4457
    let r = repo.doctor(false);
4458
    assert!(find(&r, "remote down", Health::Fail).is_none());
4459
    assert!(find(&r, "remote down", Health::Ok)
4460
        .unwrap()
4461
        .message
4462
        .contains("not contacted"));
4463
}
4464
4465
/// Spec §8.1: deleting a line depends on whoever inserted the lines right
4466
/// after it. Inserting after `b` and then deleting `b`, one commit after
4467
/// the other, must not leave a delete/insert conflict.
4468
#[test]
4469
fn deleting_a_line_after_an_insertion_below_it_is_not_a_conflict() {
4470
    hermetic();
4471
    let dir = tempfile::tempdir().unwrap();
4472
    let root = dir.path();
4473
    let repo = Repo::init(root).unwrap();
4474
    write(root, "f", b"a\nb\nc\n");
4475
    repo.commit("base", &[]).unwrap();
4476
    write(root, "f", b"a\nb\nx\nc\n");
4477
    let insert = repo.commit("insert x after b", &[]).unwrap();
4478
    write(root, "f", b"a\nx\nc\n");
4479
    let delete = repo.commit("delete b", &[]).unwrap();
4480
    assert!(
4481
        repo.store()
4482
            .get_change(&delete)
4483
            .unwrap()
4484
            .deps
4485
            .contains(&insert),
4486
        "the deletion depends on the insertion below the deleted line"
4487
    );
4488
    let heads = repo.bookmark_heads().unwrap();
4489
    assert_eq!(heads, vec![delete]);
4490
    let snap = repo.load_state(&heads).unwrap().materialize();
4491
    assert!(!snap.is_conflicted());
4492
    assert!(
4493
        matches!(&snap.files["f"].content, FileContent::Text { bytes, .. } if bytes == b"a\nx\nc\n")
4494
    );
4495
}
4496
4497
/// Spec §9.3: a binary file reverted to an earlier blob keeps it, and each
4498
/// replacement depends on the change that set the blob it replaces.
4499
#[test]
4500
fn a_binary_file_reverted_to_an_earlier_blob_keeps_it() {
4501
    hermetic();
4502
    let dir = tempfile::tempdir().unwrap();
4503
    let root = dir.path();
4504
    let repo = Repo::init(root).unwrap();
4505
    write(root, "bin", b"\0A");
4506
    let v1 = repo.commit("v1", &[]).unwrap();
4507
    write(root, "bin", b"\0B");
4508
    let v2 = repo.commit("v2", &[]).unwrap();
4509
    assert!(repo.store().get_change(&v2).unwrap().deps.contains(&v1));
4510
    write(root, "bin", b"\0A");
4511
    let v3 = repo.commit("back to A", &[]).unwrap();
4512
    assert!(repo.store().get_change(&v3).unwrap().deps.contains(&v2));
4513
    assert_eq!(repo.bookmark_heads().unwrap(), vec![v3]);
4514
    let state = repo.load_state(&[v3]).unwrap();
4515
    let snap = state.materialize();
4516
    let FileContent::Opaque { blobs } = &snap.files["bin"].content else {
4517
        panic!("opaque")
4518
    };
4519
    assert_eq!(blobs.len(), 1, "one live blob, not none and not two");
4520
    assert_eq!(repo.read_blob(&blobs[0]).unwrap(), b"\0A");
4521
}
4522
4523
/// Spec §23: a binary file changed on two branches and merged in Git to
4524
/// one side's version comes back as that version at the merge, and the
4525
/// import verifies commit by commit.
4526
#[test]
4527
fn git_import_resolves_a_binary_merged_in_git_and_verifies() {
4528
    hermetic();
4529
    if std::process::Command::new("git")
4530
        .arg("--version")
4531
        .output()
4532
        .is_err()
4533
    {
4534
        eprintln!("git not installed; skipping");
4535
        return;
4536
    }
4537
    let dir = tempfile::tempdir().unwrap();
4538
    let root = dir.path();
4539
    let g = root.join("src.git");
4540
    fs::create_dir_all(&g).unwrap();
4541
    let git = |args: &[&str]| -> String {
4542
        let out = std::process::Command::new("git")
4543
            .arg("-C")
4544
            .arg(&g)
4545
            .args([
4546
                "-c",
4547
                "user.name=Grace",
4548
                "-c",
4549
                "[email protected]",
4550
                "-c",
4551
                "commit.gpgsign=false",
4552
            ])
4553
            .args(args)
4554
            .output()
4555
            .unwrap();
4556
        assert!(
4557
            out.status.success(),
4558
            "git {args:?}: {}",
4559
            String::from_utf8_lossy(&out.stderr)
4560
        );
4561
        String::from_utf8_lossy(&out.stdout).trim().to_string()
4562
    };
4563
    git(&["init", "-q", "-b", "main"]);
4564
    write(&g, "logo.bin", b"\0base");
4565
    write(&g, "notes.txt", b"a\nb\nc\n");
4566
    git(&["add", "."]);
4567
    git(&["commit", "-qm", "base"]);
4568
    git(&["checkout", "-qb", "side"]);
4569
    write(&g, "logo.bin", b"\0side");
4570
    write(&g, "notes.txt", b"a\nb\nx\nc\n");
4571
    git(&["commit", "-qam", "side"]);
4572
    git(&["checkout", "-q", "main"]);
4573
    write(&g, "logo.bin", b"\0main");
4574
    git(&["commit", "-qam", "main"]);
4575
    // Git cannot merge the binary; the merge takes main's and keeps side's text.
4576
    let _ = std::process::Command::new("git")
4577
        .arg("-C")
4578
        .arg(&g)
4579
        .args([
4580
            "-c",
4581
            "user.name=G",
4582
            "-c",
4583
            "user.email=g@e",
4584
            "merge",
4585
            "-q",
4586
            "side",
4587
        ])
4588
        .output();
4589
    write(&g, "logo.bin", b"\0main");
4590
    git(&["add", "."]);
4591
    git(&["commit", "-qm", "merge side"]);
4592
    // Then a revert of the binary to its first version.
4593
    write(&g, "logo.bin", b"\0base");
4594
    git(&["commit", "-qam", "back to base"]);
4595
4596
    let repo = Repo::init(&root.join("o")).unwrap();
4597
    let rep = repo.import_git(&g, "main").unwrap();
4598
    assert_eq!(rep.merges, 1);
4599
    let v = repo.verify_git_import(&g, "main").unwrap();
4600
    assert!(v.mismatches.is_empty(), "{:?}", v.mismatches);
4601
    assert_eq!(v.commits, 5);
4602
    let snap = repo
4603
        .load_state(&repo.bookmark_heads().unwrap())
4604
        .unwrap()
4605
        .materialize();
4606
    assert!(!snap.is_conflicted());
4607
    let FileContent::Opaque { blobs } = &snap.files["logo.bin"].content else {
4608
        panic!("opaque")
4609
    };
4610
    assert_eq!(repo.read_blob(&blobs[0]).unwrap(), b"\0base");
4611
}
4612
4613
/// Spec §7.7 on a file system without executable bits or symlinks: the
4614
/// recorded bit is kept, and a symlink checked out as a plain file holding
4615
/// its target is still that symlink.
4616
#[cfg(unix)]
4617
#[test]
4618
fn windows_file_systems_keep_exec_bits_and_symlinks() {
4619
    use crate::portable::Platform;
4620
    use std::os::unix::fs::PermissionsExt;
4621
    hermetic();
4622
    let dir = tempfile::tempdir().unwrap();
4623
    let root = dir.path();
4624
    let repo = Repo::init(root).unwrap();
4625
    write(root, "run.sh", b"#!/bin/sh\n");
4626
    fs::set_permissions(root.join("run.sh"), fs::Permissions::from_mode(0o755)).unwrap();
4627
    std::os::unix::fs::symlink("run.sh", root.join("link")).unwrap();
4628
    repo.commit("script and link", &[]).unwrap();
4629
    drop(repo);
4630
4631
    // What checking out on Windows leaves: no exec bit, the link as a file.
4632
    fs::set_permissions(root.join("run.sh"), fs::Permissions::from_mode(0o644)).unwrap();
4633
    fs::remove_file(root.join("link")).unwrap();
4634
    write(root, "link", b"run.sh");
4635
    let win = Repo::open(root).unwrap().with_platform(Platform::windows());
4636
    let s = win.snapshot("oxy status").unwrap();
4637
    assert!(
4638
        s.statuses.is_empty(),
4639
        "nothing changed on Windows: {:?}",
4640
        statuses(&s)
4641
    );
4642
    // Editing the file is a content change, not a mode change; retargeting the link keeps it a link.
4643
    write(root, "run.sh", b"#!/bin/sh\necho hi\n");
4644
    write(root, "link", b"other");
4645
    let h = win.commit("edit on Windows", &[]).unwrap();
4646
    let snap = win.load_state(&[h]).unwrap().materialize();
4647
    assert!(snap.files["run.sh"].mode.exec, "the exec bit survives");
4648
    assert_eq!(snap.files["link"].kind, NodeKind::Symlink);
4649
    // The same working copy read as Linux sees the lost bit and the plain file.
4650
    let linux = Repo::open(root).unwrap();
4651
    assert!(!linux.snapshot("oxy status").unwrap().statuses.is_empty());
4652
}
4653
4654
/// Paths that collide on case-insensitive or Windows file systems are
4655
/// named at checkout there, and by doctor everywhere.
4656
#[test]
4657
fn paths_other_platforms_cannot_hold_are_reported() {
4658
    use crate::portable::Platform;
4659
    hermetic();
4660
    let dir = tempfile::tempdir().unwrap();
4661
    let root = dir.path();
4662
    let repo = Repo::init(root).unwrap();
4663
    write(root, "README.md", b"a\n");
4664
    write(root, "readme.md", b"b\n");
4665
    write(root, "src/aux.c", b"int x;\n");
4666
    let h = repo.commit("unportable", &[]).unwrap();
4667
    let r = repo.doctor(false);
4668
    let port = r.checks.iter().find(|c| c.area == "portability").unwrap();
4669
    assert_eq!(port.health, Health::Warn);
4670
    assert!(
4671
        port.message.contains("differ only in case") && port.message.contains("aux.c"),
4672
        "{}",
4673
        port.message
4674
    );
4675
    let mac = Repo::open(root).unwrap().with_platform(Platform::macos());
4676
    let rep = mac.checkout(&[h], true, "oxy checkout").unwrap();
4677
    assert!(
4678
        rep.notes
4679
            .iter()
4680
            .any(|n| n.contains("README.md and readme.md")),
4681
        "{:?}",
4682
        rep.notes
4683
    );
4684
    assert!(
4685
        !rep.notes.iter().any(|n| n.contains("aux.c")),
4686
        "macOS allows aux.c"
4687
    );
4688
}
4689
4690
#[test]
4691
fn history_and_blame_of_a_loaded_state_match_the_full_walk() {
4692
    hermetic();
4693
    let dir = tempfile::tempdir().unwrap();
4694
    let repo = Repo::init(dir.path()).unwrap();
4695
    write(dir.path(), "a.txt", b"one\n");
4696
    write(dir.path(), "other.txt", b"x\n");
4697
    write(dir.path(), "bin.dat", &[0u8, 1, 2, 0, 255]);
4698
    repo.snapshot("t").unwrap();
4699
    let c1 = repo.commit("first", &[]).unwrap();
4700
    write(dir.path(), "other.txt", b"y\n");
4701
    repo.snapshot("t").unwrap();
4702
    repo.commit("other only", &[]).unwrap();
4703
    write(dir.path(), "a.txt", b"one\ntwo\n");
4704
    repo.snapshot("t").unwrap();
4705
    let c3 = repo.commit("second line", &[]).unwrap();
4706
    write(dir.path(), "other.txt", b"z\n");
4707
    repo.snapshot("t").unwrap();
4708
    repo.commit("other again", &[]).unwrap();
4709
4710
    let heads = repo.bookmark_heads().unwrap();
4711
    let state = repo.load_state(&heads).unwrap();
4712
    let full: Vec<ChangeHash> = repo
4713
        .log_for_path_in("a.txt", &heads)
4714
        .unwrap()
4715
        .iter()
4716
        .map(|e| e.hash)
4717
        .collect();
4718
    assert_eq!(
4719
        full,
4720
        vec![c3, c1],
4721
        "newest first, only changes touching the path"
4722
    );
4723
    let newest: Vec<ChangeHash> = repo
4724
        .log_for_path_of(&state, "a.txt", Some(1))
4725
        .unwrap()
4726
        .iter()
4727
        .map(|e| e.hash)
4728
        .collect();
4729
    assert_eq!(newest, vec![c3], "stops at the first");
4730
    assert_eq!(
4731
        repo.log_for_path_of(&state, "a.txt", None).unwrap().len(),
4732
        2
4733
    );
4734
    assert!(repo
4735
        .log_for_path_of(&state, "missing.txt", Some(1))
4736
        .is_err());
4737
    assert_eq!(
4738
        repo.log_state(&heads).unwrap().len(),
4739
        repo.log_of(&state).len()
4740
    );
4741
4742
    let tree = state.tree().view();
4743
    let via_state = repo.blame_of(&state, &tree, "a.txt").unwrap();
4744
    let via_heads = repo.blame_in("a.txt", &heads).unwrap();
4745
    assert_eq!(
4746
        via_state
4747
            .iter()
4748
            .map(|l| (l.hash, l.text.clone()))
4749
            .collect::<Vec<_>>(),
4750
        via_heads
4751
            .iter()
4752
            .map(|l| (l.hash, l.text.clone()))
4753
            .collect::<Vec<_>>()
4754
    );
4755
    assert_eq!(
4756
        via_state.iter().map(|l| l.hash).collect::<Vec<_>>(),
4757
        vec![c1, c3]
4758
    );
4759
    assert!(repo.blame_of(&state, &tree, "missing.txt").is_err());
4760
}
4761
4762
/// A text file whose stat matches the manifest and whose recorded hash is
4763
/// the base's content is taken from the base without reading it; anything
4764
/// else is read, so no edit is missed (spec §12.3).
4765
#[cfg(unix)]
4766
#[test]
4767
fn stat_cache_takes_unchanged_text_from_the_base_and_misses_no_edit() {
4768
    use std::os::unix::fs::PermissionsExt;
4769
    hermetic();
4770
    let dir = tempfile::tempdir().unwrap();
4771
    let root = dir.path();
4772
    let repo = Repo::init(root).unwrap().with_home(root.join("home"));
4773
    write(root, "a.txt", b"one\ntwo\n");
4774
    write(root, "b.txt", b"bee\n");
4775
    repo.commit("base", &[]).unwrap();
4776
    let age = |p: &str| {
4777
        let old = std::time::SystemTime::now() - std::time::Duration::from_secs(30);
4778
        fs::File::options()
4779
            .write(true)
4780
            .open(root.join(p))
4781
            .unwrap()
4782
            .set_modified(old)
4783
            .unwrap();
4784
    };
4785
    age("a.txt");
4786
    age("b.txt");
4787
    assert!(
4788
        !repo.snapshot("status").unwrap().changed,
4789
        "records the aged stat"
4790
    );
4791
4792
    // Clean and equal to the base: not read at all.
4793
    fs::set_permissions(root.join("a.txt"), fs::Permissions::from_mode(0o000)).unwrap();
4794
    let snap = repo.snapshot("status").unwrap();
4795
    assert!(
4796
        !snap.changed && snap.statuses.is_empty(),
4797
        "{:?}",
4798
        snap.statuses
4799
    );
4800
    fs::set_permissions(root.join("a.txt"), fs::Permissions::from_mode(0o644)).unwrap();
4801
4802
    // An uncommitted edit that is older than the manifest: stat-clean, but
4803
    // its hash is not the base's, so it is read and stays visible.
4804
    write(root, "b.txt", b"bee edited\n");
4805
    age("b.txt");
4806
    let first = repo.snapshot("status").unwrap();
4807
    assert_eq!(
4808
        statuses(&first),
4809
        vec![("b.txt".to_string(), ChangeStatus::Modified)]
4810
    );
4811
    let again = repo.snapshot("status").unwrap();
4812
    assert_eq!(
4813
        statuses(&again),
4814
        vec![("b.txt".to_string(), ChangeStatus::Modified)],
4815
        "still seen once stat-clean"
4816
    );
4817
    assert!(!again.changed, "and the working copy hashes the same");
4818
    fs::set_permissions(root.join("b.txt"), fs::Permissions::from_mode(0o000)).unwrap();
4819
    assert!(
4820
        repo.snapshot("status").is_err(),
4821
        "an edited file must be read, never taken from the base"
4822
    );
4823
    fs::set_permissions(root.join("b.txt"), fs::Permissions::from_mode(0o644)).unwrap();
4824
4825
    // A same-size edit made just now is racy and read.
4826
    write(root, "a.txt", b"one\nTWO\n");
4827
    assert_eq!(
4828
        statuses(&repo.snapshot("status").unwrap()),
4829
        vec![
4830
            ("a.txt".to_string(), ChangeStatus::Modified),
4831
            ("b.txt".to_string(), ChangeStatus::Modified)
4832
        ]
4833
    );
4834
    // Committing makes the edits the base: both are clean and served from it again.
4835
    repo.commit("edits", &[]).unwrap();
4836
    age("a.txt");
4837
    age("b.txt");
4838
    assert!(repo.snapshot("status").unwrap().statuses.is_empty());
4839
    fs::set_permissions(root.join("a.txt"), fs::Permissions::from_mode(0o000)).unwrap();
4840
    fs::set_permissions(root.join("b.txt"), fs::Permissions::from_mode(0o000)).unwrap();
4841
    let snap = repo.snapshot("status").unwrap();
4842
    assert!(!snap.changed && snap.statuses.is_empty());
4843
    fs::set_permissions(root.join("a.txt"), fs::Permissions::from_mode(0o644)).unwrap();
4844
    fs::set_permissions(root.join("b.txt"), fs::Permissions::from_mode(0o644)).unwrap();
4845
}
4846
4847
/// Version 2 checkpoints (spec §11): a large file's graph is a blob of its
4848
/// own, kept by gc, checked by fsck, shared by the next checkpoint when the
4849
/// file is unchanged, and loading through the checkpoint equals a full load.
4850
#[test]
4851
fn checkpoints_keep_large_graphs_as_blobs_of_their_own() {
4852
    hermetic();
4853
    let dir = tempfile::tempdir().unwrap();
4854
    let root = dir.path();
4855
    let repo = Repo::init(root).unwrap().with_home(root.join("home"));
4856
    let long: String = (0..300)
4857
        .map(|i| format!("line {i} of a long file\n"))
4858
        .collect();
4859
    write(root, "long.txt", long.as_bytes());
4860
    write(root, "short.txt", b"short\n");
4861
    repo.commit("base", &[]).unwrap();
4862
    let (r1, _, _) = repo.checkpoint().unwrap();
4863
    let cp1 = crate::objects::Checkpoint::decode(
4864
        &repo.store().get_typed(&r1, ObjectType::Checkpoint).unwrap(),
4865
    )
4866
    .unwrap();
4867
    let graphs1 = repo.checkpoint_graph_blobs(&cp1).unwrap();
4868
    assert_eq!(graphs1.len(), 1, "only the long file's graph is a blob");
4869
4870
    // gc keeps the graph blob; fsck finds the checkpoint sound.
4871
    repo.gc(true).unwrap();
4872
    assert!(repo.store().has(&graphs1[0]));
4873
    let report = repo.fsck().unwrap();
4874
    assert_eq!(report.errors(), 0, "{:?}", report.problems);
4875
4876
    // Loading through the checkpoint equals a full load.
4877
    write(root, "short.txt", b"short, edited\n");
4878
    repo.commit("edit the short file", &[]).unwrap();
4879
    let heads = repo.bookmark_heads().unwrap();
4880
    let fast = repo.load_state(&heads).unwrap();
4881
    let full = repo.load_state_full(&heads).unwrap();
4882
    assert_eq!(fast.checkpoint_payload(), full.checkpoint_payload());
4883
4884
    // The next checkpoint shares the unchanged long file's graph.
4885
    let (r2, _, _) = repo.checkpoint().unwrap();
4886
    let cp2 = crate::objects::Checkpoint::decode(
4887
        &repo.store().get_typed(&r2, ObjectType::Checkpoint).unwrap(),
4888
    )
4889
    .unwrap();
4890
    assert_eq!(repo.checkpoint_graph_blobs(&cp2).unwrap(), graphs1);
4891
4892
    // A shallow clone's bundle carries the graph blob with the checkpoint.
4893
    let bundle = repo.checkpoint_bundle_for(&heads).unwrap();
4894
    assert!(bundle.objects.iter().any(|(t, body)| *t == ObjectType::Blob
4895
        && crate::hash::hash_object(ObjectType::Blob, body) == graphs1[0]));
4896
4897
    // A version 1 checkpoint written by an older oxy still loads.
4898
    let state = repo.load_state_full(&heads).unwrap();
4899
    let old = repo.store_blob(&state.checkpoint_payload()).unwrap();
4900
    let cp_old = crate::objects::Checkpoint {
4901
        heads: cp2.heads.clone(),
4902
        count: cp2.count,
4903
        payload: old,
4904
    };
4905
    let r_old = repo
4906
        .store()
4907
        .put(ObjectType::Checkpoint, &cp_old.encode())
4908
        .unwrap();
4909
    repo.install_checkpoint("main", &r_old).unwrap();
4910
    assert_eq!(
4911
        repo.load_state(&heads).unwrap().checkpoint_payload(),
4912
        full.checkpoint_payload()
4913
    );
4914
    assert_eq!(repo.fsck().unwrap().errors(), 0);
4915
4916
    // A lost graph blob fails the load loudly rather than dropping the
4917
    // file, and fsck reports it (a fresh repository, objects still loose).
4918
    let dir2 = tempfile::tempdir().unwrap();
4919
    let root2 = dir2.path();
4920
    let repo2 = Repo::init(root2).unwrap().with_home(root2.join("home"));
4921
    write(root2, "long.txt", long.as_bytes());
4922
    repo2.commit("base", &[]).unwrap();
4923
    let (r, _, _) = repo2.checkpoint().unwrap();
4924
    let cp = crate::objects::Checkpoint::decode(
4925
        &repo2.store().get_typed(&r, ObjectType::Checkpoint).unwrap(),
4926
    )
4927
    .unwrap();
4928
    let graph = repo2.checkpoint_graph_blobs(&cp).unwrap()[0];
4929
    repo2.store().remove_loose_for_test(&graph).unwrap();
4930
    assert!(repo2.load_state(&repo2.bookmark_heads().unwrap()).is_err());
4931
    assert!(repo2.fsck().unwrap().errors() > 0, "fsck reports it");
4932
}
4933
4934
/// A new repository has not stored the user's identity yet (that happens
4935
/// at the first signed change); looking it up falls back to the key
4936
/// directory, and a file there that does not hash to the key is refused.
4937
#[test]
4938
fn identity_is_found_in_the_key_directory_for_a_new_repository() {
4939
    hermetic();
4940
    let dir = tempfile::tempdir().unwrap();
4941
    let home = dir.path().join("home");
4942
    let mut first = Repo::init(&dir.path().join("a"))
4943
        .unwrap()
4944
        .with_home(home.clone());
4945
    let (key, _) = first
4946
        .create_identity("Ada", "[email protected]", IdentityScope::User)
4947
        .unwrap();
4948
    let fresh = Repo::init(&dir.path().join("b"))
4949
        .unwrap()
4950
        .with_home(home.clone());
4951
    assert!(!fresh.store().has(&key), "nothing stored yet");
4952
    let id = fresh.identity(&key).unwrap();
4953
    assert_eq!((id.name.as_str(), id.hash()), ("Ada", key));
4954
    // A key file that is not this identity is an error, not a wrong answer.
4955
    let keys = fresh.keys_dir.clone();
4956
    let (other, _) = first
4957
        .create_identity("Bob", "[email protected]", IdentityScope::User)
4958
        .unwrap();
4959
    fs::copy(
4960
        keys.join(format!("{}.identity", other.to_hex())),
4961
        keys.join(format!("{}.identity", key.to_hex())),
4962
    )
4963
    .unwrap();
4964
    assert!(fresh
4965
        .identity(&key)
4966
        .unwrap_err()
4967
        .to_string()
4968
        .contains("does not hold identity"));
4969
}
4970
4971
/// Status snapshots (spec §12.3): a text file whose stat matches the
4972
/// manifest, and whose base graph key is the one the manifest recorded it
4973
/// equal to, is neither read nor rendered; any edit, and any change to the
4974
/// file's graph in the base, brings it back.
4975
#[cfg(unix)]
4976
#[test]
4977
fn status_snapshots_skip_files_unchanged_since_the_manifest() {
4978
    use std::os::unix::fs::PermissionsExt;
4979
    hermetic();
4980
    let dir = tempfile::tempdir().unwrap();
4981
    let root = dir.path();
4982
    let repo = Repo::init(root).unwrap().with_home(root.join("home"));
4983
    for (p, c) in [("a.txt", "one\n"), ("b.txt", "bee\n"), ("d/c.txt", "sea\n")] {
4984
        write(root, p, c.as_bytes());
4985
    }
4986
    repo.commit("base", &[]).unwrap();
4987
    let age = |p: &str| {
4988
        let old = std::time::SystemTime::now() - std::time::Duration::from_secs(30);
4989
        fs::File::options()
4990
            .write(true)
4991
            .open(root.join(p))
4992
            .unwrap()
4993
            .set_modified(old)
4994
            .unwrap();
4995
    };
4996
    let lock = |p: &str, mode: u32| {
4997
        fs::set_permissions(root.join(p), fs::Permissions::from_mode(mode)).unwrap()
4998
    };
4999
    for p in ["a.txt", "b.txt", "d/c.txt"] {
5000
        age(p);
5001
    }
5002
    assert!(repo.snapshot("status").unwrap().statuses.is_empty());
5003
    let (_, _, m) = repo.read_manifest().unwrap().unwrap();
5004
    assert!(
5005
        m.entries.values().all(|e| e.graph.is_some()),
5006
        "keys recorded"
5007
    );
5008
5009
    // Unreadable files prove they are not read; the status snapshot does
5010
    // not render them either, and its base lacks their graphs.
5011
    lock("a.txt", 0o000);
5012
    lock("b.txt", 0o000);
5013
    let snap = repo.snapshot_status("status").unwrap();
5014
    assert!(!snap.changed && snap.statuses.is_empty());
5015
    assert_eq!(
5016
        snap.base_snapshot
5017
            .unrendered
5018
            .iter()
5019
            .cloned()
5020
            .collect::<Vec<_>>(),
5021
        vec!["a.txt", "b.txt", "d/c.txt"]
5022
    );
5023
    assert!(!snap.base.is_full());
5024
    assert!(!snap.base_snapshot.is_conflicted());
5025
    // A full snapshot does not read them either, but renders everything.
5026
    let full = repo.snapshot("status").unwrap();
5027
    assert!(full.statuses.is_empty() && full.base.is_full());
5028
    assert!(full.base_snapshot.unrendered.is_empty());
5029
    assert!(matches!(&full.base_snapshot.files["a.txt"].content,
5030
        FileContent::Text { bytes, .. } if bytes == b"one\n"));
5031
5032
    // An edit is seen; the file is rendered, the others still are not.
5033
    write(root, "d/c.txt", b"sea edited\n");
5034
    let snap = repo.snapshot_status("status").unwrap();
5035
    assert_eq!(
5036
        statuses(&snap),
5037
        vec![("d/c.txt".to_string(), ChangeStatus::Modified)]
5038
    );
5039
    assert!(!snap.base_snapshot.unrendered.contains("d/c.txt"));
5040
    // So is a mode change of an unread file.
5041
    lock("b.txt", 0o100);
5042
    assert_eq!(
5043
        statuses(&repo.snapshot_status("status").unwrap()),
5044
        vec![
5045
            ("b.txt".to_string(), ChangeStatus::ModeChanged),
5046
            ("d/c.txt".to_string(), ChangeStatus::Modified)
5047
        ]
5048
    );
5049
    lock("b.txt", 0o000);
5050
5051
    // Committing c.txt changes its graph in the base, not a.txt's: a.txt
5052
    // stays unread, c.txt is read once and then skipped too.
5053
    repo.commit_selection("edit c", &[], &Selection::Paths(vec!["d/c.txt".into()]))
5054
        .unwrap();
5055
    age("d/c.txt");
5056
    let snap = repo.snapshot_status("status").unwrap();
5057
    assert!(snap.statuses.is_empty(), "{:?}", snap.statuses);
5058
    assert!(snap.base_snapshot.unrendered.contains("a.txt"));
5059
    lock("d/c.txt", 0o000);
5060
    let snap = repo.snapshot_status("status").unwrap();
5061
    assert!(snap.statuses.is_empty());
5062
    assert!(snap.base_snapshot.unrendered.contains("d/c.txt"));
5063
    for p in ["a.txt", "b.txt", "d/c.txt"] {
5064
        lock(p, 0o644);
5065
    }
5066
}
5067
5068
/// Attributes decide how a file compares with the base, so a changed
5069
/// `.oxyattributes` makes every text file be compared again.
5070
#[cfg(unix)]
5071
#[test]
5072
fn a_changed_attributes_file_disables_skipping_unchanged_files() {
5073
    hermetic();
5074
    let dir = tempfile::tempdir().unwrap();
5075
    let root = dir.path();
5076
    let repo = Repo::init(root).unwrap().with_home(root.join("home"));
5077
    write(root, "a.txt", b"crlf\r\n");
5078
    repo.commit("base", &[]).unwrap();
5079
    let old = std::time::SystemTime::now() - std::time::Duration::from_secs(30);
5080
    fs::File::options()
5081
        .write(true)
5082
        .open(root.join("a.txt"))
5083
        .unwrap()
5084
        .set_modified(old)
5085
        .unwrap();
5086
    assert!(repo.snapshot_status("status").unwrap().statuses.is_empty());
5087
    assert!(repo
5088
        .snapshot_status("status")
5089
        .unwrap()
5090
        .base_snapshot
5091
        .unrendered
5092
        .contains("a.txt"));
5093
    // With eol=lf, a.txt as stored no longer equals the base.
5094
    write(root, ".oxyattributes", b"*.txt eol=lf\n");
5095
    let snap = repo.snapshot_status("status").unwrap();
5096
    assert_eq!(
5097
        statuses(&snap),
5098
        vec![
5099
            (".oxyattributes".to_string(), ChangeStatus::Added),
5100
            ("a.txt".to_string(), ChangeStatus::Modified)
5101
        ]
5102
    );
5103
}
5104
5105
/// Bookmarks with `/` in their names: pushing records their
5106
/// attestations, and checkpoints are kept for them, beside `feature`
5107
/// itself.
5108
#[test]
5109
fn bookmarks_with_slashes_push_and_checkpoint() {
5110
    hermetic();
5111
    let dir = tempfile::tempdir().unwrap();
5112
    let root = dir.path();
5113
    let origin = Repo::init(&root.join("origin")).unwrap();
5114
    let url = root.join("origin").to_string_lossy().to_string();
5115
    let mut repo = Repo::clone(&url, &root.join("r"))
5116
        .unwrap()
5117
        .with_home(root.join("home"));
5118
    // With an identity, pushes carry reference attestations: the case
5119
    // that failed, since the attestation is a file named after the bookmark.
5120
    repo.create_identity("Ada", "[email protected]", IdentityScope::Repo)
5121
        .unwrap();
5122
    let r = root.join("r");
5123
    write(&r, "a.txt", b"a\n");
5124
    let h_a = repo.commit("a", &[]).unwrap();
5125
    assert!(repo.push("origin", false).unwrap()[0].ok);
5126
    origin.refresh().unwrap();
5127
    repo.bookmark_create("feature", None).unwrap();
5128
    repo.bookmark_create("feature/x", None).unwrap();
5129
    repo.bookmark_switch("feature/x", false).unwrap();
5130
    write(&r, "b.txt", b"b\n");
5131
    let h_b = repo.commit("b", &[]).unwrap();
5132
    for name in ["feature", "feature/x"] {
5133
        let res = repo.push_bookmark("origin", name, false).unwrap();
5134
        origin.refresh().unwrap();
5135
        assert!(res[0].ok, "{name}: {res:?}");
5136
    }
5137
    assert_eq!(origin.resolve_heads("feature").unwrap(), vec![h_a]);
5138
    assert_eq!(
5139
        origin.resolve_heads("feature/x").unwrap(),
5140
        repo.resolve_heads("feature/x").unwrap()
5141
    );
5142
    assert!(origin.resolve_heads("feature/x").unwrap().contains(&h_b));
5143
    assert!(origin.latest_ref_attest("feature/x").unwrap().is_some());
5144
    assert!(origin.latest_ref_attest("feature").unwrap().is_some());
5145
5146
    // A checkpoint of feature/x is found again when loading its state.
5147
    let (cp, _, _) = repo.checkpoint().unwrap();
5148
    assert_eq!(repo.latest_checkpoint("feature/x").unwrap().unwrap().0, cp);
5149
    assert!(repo.latest_checkpoint("feature").unwrap().is_none());
5150
    let heads = repo.resolve_heads("feature/x").unwrap();
5151
    assert!(repo.load_state_checkpointed(&heads).unwrap().is_some());
5152
}
5153
5154
/// Deleting a bookmark on a remote (spec §16.4): attested like any update,
5155
/// never the remote's own bookmark, and a bookmark created again later is
5156
/// accepted although the deletion's attestation stays the latest.
5157
#[test]
5158
fn bookmarks_are_deleted_on_a_remote() {
5159
    hermetic();
5160
    let dir = tempfile::tempdir().unwrap();
5161
    let root = dir.path();
5162
    let origin = Repo::init(&root.join("origin")).unwrap();
5163
    let url = root.join("origin").to_string_lossy().to_string();
5164
    let mut repo = Repo::clone(&url, &root.join("r"))
5165
        .unwrap()
5166
        .with_home(root.join("home"));
5167
    repo.create_identity("Ada", "[email protected]", IdentityScope::Repo)
5168
        .unwrap();
5169
    let r = root.join("r");
5170
    write(&r, "a.txt", b"a\n");
5171
    repo.commit("a", &[]).unwrap();
5172
    assert!(repo.push("origin", false).unwrap()[0].ok);
5173
    origin.refresh().unwrap();
5174
    repo.bookmark_create("feature/x", None).unwrap();
5175
    assert!(repo.push_bookmark("origin", "feature/x", false).unwrap()[0].ok);
5176
    origin.refresh().unwrap();
5177
    assert!(origin.resolve_heads("feature/x").is_ok());
5178
5179
    let res = repo.push_delete("origin", "feature/x").unwrap();
5180
    origin.refresh().unwrap();
5181
    assert!(res[0].ok, "{res:?}");
5182
    assert!(!origin.view().unwrap().bookmarks.contains_key("feature/x"));
5183
    let (_, att) = origin.latest_ref_attest("feature/x").unwrap().unwrap();
5184
    assert!(
5185
        matches!(att.attest.body, AttestBody::Ref { new_state, .. } if new_state.is_zero()),
5186
        "the deletion is attested"
5187
    );
5188
    assert!(
5189
        repo.view().unwrap().bookmarks.contains_key("feature/x"),
5190
        "the local bookmark stays"
5191
    );
5192
    assert!(!repo
5193
        .view()
5194
        .unwrap()
5195
        .remotes
5196
        .get("origin")
5197
        .is_some_and(|m| m.contains_key("feature/x")));
5198
5199
    // Pushing it again creates it again, past the deletion's serial.
5200
    let res = repo.push_bookmark("origin", "feature/x", false).unwrap();
5201
    origin.refresh().unwrap();
5202
    assert!(res[0].ok, "{res:?}");
5203
    assert!(origin.view().unwrap().bookmarks.contains_key("feature/x"));
5204
5205
    // Nothing to delete, and never the remote's own bookmark.
5206
    assert!(repo.push_delete("origin", "nope").is_err());
5207
    let res = repo.push_delete("origin", "main").unwrap();
5208
    origin.refresh().unwrap();
5209
    assert!(
5210
        !res[0].ok && res[0].reason.contains("default bookmark"),
5211
        "{res:?}"
5212
    );
5213
    assert!(origin.view().unwrap().bookmarks.contains_key("main"));
5214
}
5215
5216
/// `bookmark switch --carry` (spec §10.1): uncommitted work goes along
5217
/// when the target has the same versions of the files it touches, and is
5218
/// refused, untouched, when it has others.
5219
#[test]
5220
fn switching_bookmarks_carries_uncommitted_work() {
5221
    hermetic();
5222
    let dir = tempfile::tempdir().unwrap();
5223
    let root = dir.path();
5224
    let mut repo = Repo::init(root).unwrap().with_home(root.join("home"));
5225
    write(root, "a.txt", b"a\n");
5226
    write(root, "b.txt", b"b\n");
5227
    write(root, "gone.txt", b"gone\n");
5228
    repo.commit("base", &[]).unwrap();
5229
    repo.bookmark_create("feature", None).unwrap();
5230
    // Started on main, belongs on feature: edit, add, remove.
5231
    write(root, "a.txt", b"a\nmore\n");
5232
    write(root, "new.txt", b"new\n");
5233
    fs::remove_file(root.join("gone.txt")).unwrap();
5234
    let (_, carried) = repo.bookmark_switch_carry("feature").unwrap();
5235
    assert_eq!(carried, vec!["a.txt", "gone.txt", "new.txt"]);
5236
    assert_eq!(repo.config.bookmark, "feature");
5237
    assert_eq!(fs::read(root.join("a.txt")).unwrap(), b"a\nmore\n");
5238
    assert_eq!(fs::read(root.join("new.txt")).unwrap(), b"new\n");
5239
    assert!(!root.join("gone.txt").exists());
5240
    let snap = repo.snapshot("status").unwrap();
5241
    assert_eq!(
5242
        statuses(&snap),
5243
        vec![
5244
            ("a.txt".to_string(), ChangeStatus::Modified),
5245
            ("gone.txt".to_string(), ChangeStatus::Removed),
5246
            ("new.txt".to_string(), ChangeStatus::Added)
5247
        ]
5248
    );
5249
    repo.commit("the work", &[]).unwrap();
5250
    assert!(repo.resolve_heads("main").unwrap().len() == 1);
5251
5252
    // main moves b.txt on; work on feature touching b.txt cannot follow.
5253
    repo.bookmark_switch("main", false).unwrap();
5254
    write(root, "b.txt", b"b on main\n");
5255
    repo.commit("b on main", &[]).unwrap();
5256
    repo.bookmark_switch("feature", false).unwrap();
5257
    write(root, "b.txt", b"b edited\n");
5258
    let err = repo.bookmark_switch_carry("main").unwrap_err().to_string();
5259
    assert!(err.contains("b.txt") && err.contains("--discard"), "{err}");
5260
    assert_eq!(repo.config.bookmark, "feature", "nothing happened");
5261
    assert_eq!(fs::read(root.join("b.txt")).unwrap(), b"b edited\n");
5262
}
5263
5264
/// Merging and checking out (feedback 3): a working copy without changes
5265
/// follows a merge whichever state it sat on; a refused checkout names
5266
/// what is in the way; `checkout --carry` takes the work along.
5267
#[test]
5268
fn merges_move_clean_working_copies_and_checkouts_say_what_blocks_them() {
5269
    hermetic();
5270
    let dir = tempfile::tempdir().unwrap();
5271
    let root = dir.path();
5272
    let mut repo = Repo::init(root).unwrap().with_home(root.join("home"));
5273
    write(root, "a.txt", b"a\n");
5274
    let h1 = repo.commit("a", &[]).unwrap();
5275
    write(root, "b.txt", b"b\n");
5276
    repo.commit("b", &[]).unwrap();
5277
    repo.bookmark_create("feature", None).unwrap();
5278
    repo.bookmark_switch("feature", false).unwrap();
5279
    write(root, "c.txt", b"c\n");
5280
    repo.commit("c on feature", &[]).unwrap();
5281
    repo.bookmark_switch("main", false).unwrap();
5282
    // The working copy sits on an older state than main's heads.
5283
    repo.checkout(&[h1], false, "checkout").unwrap();
5284
    assert!(!root.join("b.txt").exists());
5285
    let m = repo.merge("feature").unwrap();
5286
    assert!(m.checked_out, "a clean working copy follows the merge");
5287
    for f in ["a.txt", "b.txt", "c.txt"] {
5288
        assert!(root.join(f).exists(), "{f}");
5289
    }
5290
5291
    // A refusal says which paths are in the way and what to do.
5292
    fs::remove_file(root.join("b.txt")).unwrap();
5293
    write(root, "a.txt", b"a edited\n");
5294
    let err = repo
5295
        .checkout(&[h1], false, "checkout")
5296
        .unwrap_err()
5297
        .to_string();
5298
    assert!(
5299
        err.contains("modified a.txt") && err.contains("removed b.txt") && err.contains("--carry"),
5300
        "{err}"
5301
    );
5302
    // --carry takes them along: h1 has a.txt as the base has it, and no b.txt
5303
    // is carried as absent (h1 has none either, so that is refused).
5304
    let err = repo
5305
        .checkout_carry(&[h1], "the first change", "checkout")
5306
        .unwrap_err()
5307
        .to_string();
5308
    assert!(
5309
        err.contains("b.txt") && err.contains("the first change"),
5310
        "{err}"
5311
    );
5312
    write(root, "b.txt", b"b\n");
5313
    let (_, carried) = repo
5314
        .checkout_carry(&[h1], "the first change", "checkout")
5315
        .unwrap();
5316
    assert_eq!(carried, vec!["a.txt"]);
5317
    assert_eq!(fs::read(root.join("a.txt")).unwrap(), b"a edited\n");
5318
    assert!(!root.join("b.txt").exists(), "h1 has no b.txt");
5319
}
5320
5321
/// Doctor and subrepos before the first commit (feedback 5 and 8): a
5322
/// user identity not stored in a new repository yet is fine while its
5323
/// secret key is there; an added subrepo is listed as not committed yet.
5324
#[test]
5325
fn a_new_repository_is_healthy_before_its_first_commit() {
5326
    hermetic();
5327
    let dir = tempfile::tempdir().unwrap();
5328
    let root = dir.path();
5329
    let home = root.join("home");
5330
    let mut first = Repo::init(&root.join("first"))
5331
        .unwrap()
5332
        .with_home(home.clone());
5333
    let (key, _) = first
5334
        .create_identity("Ada", "[email protected]", IdentityScope::User)
5335
        .unwrap();
5336
    let repo = Repo::init(&root.join("second"))
5337
        .unwrap()
5338
        .with_home(home.clone());
5339
    // Only the secret key: no identity object anywhere this repository sees.
5340
    let keys = repo.keys_dir.clone();
5341
    let _ = fs::remove_file(keys.join(format!("{}.identity", key.to_hex())));
5342
    assert!(keys.join(format!("{}.secret", key.to_hex())).is_file());
5343
    let r = repo.doctor(true);
5344
    let id = r.checks.iter().find(|c| c.area == "identity").unwrap();
5345
    assert_eq!(id.health, Health::Ok, "{}", id.message);
5346
    assert!(id.message.contains("first signed change"), "{}", id.message);
5347
5348
    // A subrepo added and not committed yet is listed, pinned where it is.
5349
    let lib = root.join("lib");
5350
    let l = Repo::init(&lib).unwrap().with_home(home.clone());
5351
    write(&lib, "x.txt", b"x\n");
5352
    l.commit("x", &[]).unwrap();
5353
    let second = root.join("second");
5354
    write(&second, "a.txt", b"a\n");
5355
    repo.submodule_add(&lib.to_string_lossy(), "deps/lib", None)
5356
        .unwrap();
5357
    let subs = repo.subrepos().unwrap();
5358
    assert_eq!(subs.len(), 1);
5359
    assert_eq!(
5360
        (subs[0].path.as_str(), subs[0].committed),
5361
        ("deps/lib", false)
5362
    );
5363
    assert_eq!(subs[0].actual.as_ref(), Some(&subs[0].pin));
5364
    repo.commit("add lib", &[]).unwrap();
5365
    let subs = repo.subrepos().unwrap();
5366
    assert!(subs[0].committed, "committed now");
5367
}
5368
5369
/// Commit, diff, hunks and discard use the partial snapshot: a file
5370
/// unchanged since the manifest is neither read nor rendered, and showing
5371
/// a change renders only what it edits, the same as from a full base.
5372
#[cfg(unix)]
5373
#[test]
5374
fn commits_and_diffs_leave_unchanged_files_alone() {
5375
    use std::os::unix::fs::PermissionsExt;
5376
    hermetic();
5377
    let dir = tempfile::tempdir().unwrap();
5378
    let root = dir.path();
5379
    let repo = Repo::init(root).unwrap().with_home(root.join("home"));
5380
    write(root, "big.txt", b"lots\nof\nlines\n");
5381
    write(root, "a.txt", b"one\ntwo\n");
5382
    repo.commit("base", &[]).unwrap();
5383
    let old = std::time::SystemTime::now() - std::time::Duration::from_secs(30);
5384
    for f in ["big.txt", "a.txt"] {
5385
        fs::File::options()
5386
            .write(true)
5387
            .open(root.join(f))
5388
            .unwrap()
5389
            .set_modified(old)
5390
            .unwrap();
5391
    }
5392
    assert!(repo.snapshot_status("status").unwrap().statuses.is_empty());
5393
    // big.txt cannot be read at all from here on.
5394
    fs::set_permissions(root.join("big.txt"), fs::Permissions::from_mode(0o000)).unwrap();
5395
5396
    write(root, "a.txt", b"one\nTWO\nthree\n");
5397
    let diff = repo.diff_files(None).unwrap();
5398
    assert_eq!(
5399
        diff.iter().map(|f| f.path.as_str()).collect::<Vec<_>>(),
5400
        ["a.txt"]
5401
    );
5402
    let (_, hunks) = repo.hunks().unwrap();
5403
    assert!(!hunks.is_empty() && hunks.iter().all(|h| h.path == "a.txt"));
5404
    let h = repo.commit("edit a", &[]).unwrap();
5405
5406
    // Showing the change needs only a.txt's graph, and renders as a full base does.
5407
    let c = repo.store().get_change(&h).unwrap();
5408
    let full = repo.load_state(&c.deps).unwrap();
5409
    let want = render_change(&c, &full, &full.materialize());
5410
    assert_eq!(repo.describe_change(&h).unwrap(), want);
5411
    let (base, snap) = repo.change_base(&c).unwrap();
5412
    assert!(!base.is_full() && snap.unrendered.contains("big.txt"));
5413
5414
    // Discarding works the same way.
5415
    write(root, "a.txt", b"scratch\n");
5416
    assert_eq!(repo.discard(&["a.txt".into()]).unwrap(), 1);
5417
    assert_eq!(fs::read(root.join("a.txt")).unwrap(), b"one\nTWO\nthree\n");
5418
    fs::set_permissions(root.join("big.txt"), fs::Permissions::from_mode(0o644)).unwrap();
5419
}
5420
5421
/// A replace conflict (spec §9.3) is settled by a change that writes one
5422
/// candidate, or new bytes, at the path when the caller names it; a plain
5423
/// snapshot of a checkout never settles it on its own.
5424
#[test]
5425
fn replace_conflicts_are_settled_when_asked() {
5426
    hermetic();
5427
    let dir = tempfile::tempdir().unwrap();
5428
    let root = dir.path();
5429
    let mut repo = Repo::init(root).unwrap().with_home(root.join("home"));
5430
    let blob = |n: u8| {
5431
        let mut v = vec![0u8; 64];
5432
        v[1] = n;
5433
        v
5434
    };
5435
    write(root, "img.bin", &blob(1));
5436
    repo.commit("add img", &[]).unwrap();
5437
    repo.bookmark_create("other", None).unwrap();
5438
    write(root, "img.bin", &blob(2));
5439
    repo.commit("img two", &[]).unwrap();
5440
    repo.bookmark_switch("other", false).unwrap();
5441
    write(root, "img.bin", &blob(3));
5442
    repo.commit("img three", &[]).unwrap();
5443
    repo.bookmark_switch("main", false).unwrap();
5444
    repo.merge("other").unwrap();
5445
    let heads = repo.bookmark_heads().unwrap();
5446
    let merged = repo.load_state(&heads).unwrap().materialize();
5447
    assert!(
5448
        matches!(&merged.files["img.bin"].content, FileContent::Opaque { blobs } if blobs.len() == 2),
5449
        "a replace conflict"
5450
    );
5451
    // A snapshot of the checkout records nothing.
5452
    assert!(repo
5453
        .snapshot("status")
5454
        .unwrap()
5455
        .statuses
5456
        .iter()
5457
        .all(|s| s.path != "img.bin"));
5458
5459
    // Keeping candidate 3 settles it.
5460
    let author = repo.author();
5461
    let edits = [FileEdit {
5462
        path: "img.bin".into(),
5463
        content: Some(blob(3)),
5464
    }];
5465
    let c = repo
5466
        .build_change(&heads, &edits, "keep three", author)
5467
        .unwrap();
5468
    assert_eq!(c.kind, ChangeKind::Resolution);
5469
    let mut st = repo.load_state(&heads).unwrap();
5470
    for d in &c.deps {
5471
        assert!(st.contains(d));
5472
    }
5473
    assert!(
5474
        heads.iter().all(|h| c.deps.contains(h)),
5475
        "depends on both contributors"
5476
    );
5477
    st.add(c).unwrap();
5478
    let after = st.materialize();
5479
    assert!(!after.is_conflicted());
5480
    assert_eq!(
5481
        after.files["img.bin"].content,
5482
        FileContent::Opaque {
5483
            blobs: vec![Repo::blob_ref(&blob(3))]
5484
        }
5485
    );
5486
5487
    // New bytes settle it too.
5488
    let edits = [FileEdit {
5489
        path: "img.bin".into(),
5490
        content: Some(blob(9)),
5491
    }];
5492
    let c = repo.build_change(&heads, &edits, "new", author).unwrap();
5493
    let mut st = repo.load_state(&heads).unwrap();
5494
    st.add(c).unwrap();
5495
    assert_eq!(
5496
        st.materialize().files["img.bin"].content,
5497
        FileContent::Opaque {
5498
            blobs: vec![Repo::blob_ref(&blob(9))]
5499
        }
5500
    );
5501
}
5502
5503
/// The history of a range of lines (spec §27): the changes that wrote
5504
/// or deleted its atoms, or deleted atoms from between them; edits outside
5505
/// the range and changes the range's lines survived are not in it.
5506
#[test]
5507
fn line_ranges_have_exact_histories() {
5508
    hermetic();
5509
    let dir = tempfile::tempdir().unwrap();
5510
    let root = dir.path();
5511
    let repo = Repo::init(root).unwrap().with_home(root.join("home"));
5512
    write(root, "f.rs", b"use x;\nfn a() {\n  one();\n  two();\n}\n");
5513
    let base = repo.commit("add f", &[]).unwrap();
5514
    write(root, "f.rs", b"use y;\nfn a() {\n  one();\n  two();\n}\n");
5515
    let outside = repo.commit("change the import", &[]).unwrap();
5516
    write(root, "f.rs", b"use y;\nfn a() {\n  ONE();\n  two();\n}\n");
5517
    let inside = repo.commit("edit a line of a", &[]).unwrap();
5518
    write(root, "f.rs", b"use y;\nfn a() {\n  ONE();\n}\n");
5519
    let deleted = repo.commit("delete a line of a", &[]).unwrap();
5520
    write(root, "f.rs", b"use y;\nfn a() {\n  ONE();\n}\nfn b() {}\n");
5521
    let after = repo.commit("add b after a", &[]).unwrap();
5522
    let heads = repo.bookmark_heads().unwrap();
5523
5524
    // Lines 2..4 are `fn a() {`, `ONE();`, `}` now.
5525
    let hist: Vec<ChangeHash> = repo
5526
        .line_history(&heads, "f.rs", 2, 4)
5527
        .unwrap()
5528
        .iter()
5529
        .map(|e| e.hash)
5530
        .collect();
5531
    for (h, what) in [
5532
        (base, "wrote it"),
5533
        (inside, "edited a line"),
5534
        (deleted, "deleted a line from inside"),
5535
    ] {
5536
        assert!(hist.contains(&h), "{what}");
5537
    }
5538
    for (h, what) in [(outside, "an edit above"), (after, "an addition below")] {
5539
        assert!(!hist.contains(&h), "{what}");
5540
    }
5541
    assert_eq!(hist[0], deleted, "newest first");
5542
    // One line: only what touched it.
5543
    let one: Vec<ChangeHash> = repo
5544
        .line_history(&heads, "f.rs", 1, 1)
5545
        .unwrap()
5546
        .iter()
5547
        .map(|e| e.hash)
5548
        .collect();
5549
    assert!(one.contains(&outside) && !one.contains(&inside));
5550
    assert!(repo.line_history(&heads, "f.rs", 3, 9).is_err());
5551
    assert!(repo.line_history(&heads, "f.rs", 0, 1).is_err());
5552
    assert!(repo.line_history(&heads, "nope.rs", 1, 1).is_err());
5553
}
5554
5555
#[test]
5556
fn receipts_are_kept_with_their_state_and_verified() {
5557
    use crate::receipt::{Receipt, SignedReceipt};
5558
    hermetic();
5559
    let dir = tempfile::tempdir().unwrap();
5560
    let root = dir.path();
5561
    let repo = Repo::init(root).unwrap().with_home(root.join("home"));
5562
    write(root, "a.txt", b"1\n");
5563
    repo.commit("A", &[]).unwrap();
5564
    let heads = repo.bookmark_heads().unwrap();
5565
    let state = repo
5566
        .store()
5567
        .put_state(&StateObject::new(heads.clone()))
5568
        .unwrap();
5569
    let out = repo.store_blob(b"built\n").unwrap();
5570
    let receipt = Receipt {
5571
        job_name: "build".into(),
5572
        pipeline_hash: ObjectRef([1; 32]),
5573
        scope_tree_hash: ObjectRef([2; 32]),
5574
        inputs: vec![],
5575
        environment: ObjectRef([3; 32]),
5576
        outputs: vec![out],
5577
        exit_code: 0,
5578
        duration_ms: 42,
5579
    };
5580
    let sk = SecretKey::generate();
5581
    let runner = sk.identity("earth-1", "runner@earth", 1);
5582
    let sr = SignedReceipt::sign(
5583
        receipt.clone(),
5584
        repo.id().unwrap(),
5585
        state,
5586
        "demo#1",
5587
        &runner,
5588
        &sk,
5589
    );
5590
5591
    let r = repo.add_receipt(&sr).unwrap();
5592
    let found = repo.receipts(&heads).unwrap();
5593
    assert_eq!(found.len(), 1);
5594
    assert_eq!(found[0].attest, r);
5595
    assert_eq!(found[0].signed, sr);
5596
    assert!(found[0].problem.is_none() && !found[0].revoked);
5597
    assert!(repo.receipts(&[ObjectRef([5; 32])]).unwrap().is_empty());
5598
5599
    // Another repository's receipt, or a forged one, is refused.
5600
    let elsewhere = SignedReceipt::sign(receipt.clone(), [0; 16], state, "x", &runner, &sk);
5601
    assert!(repo
5602
        .add_receipt(&elsewhere)
5603
        .unwrap_err()
5604
        .to_string()
5605
        .contains("another repository"));
5606
    let mut forged = sr.clone();
5607
    forged.receipt.exit_code = 1;
5608
    assert!(repo
5609
        .add_receipt(&forged)
5610
        .unwrap_err()
5611
        .to_string()
5612
        .contains("does not verify"));
5613
5614
    // gc keeps the receipt, its runner and its output while the state lives.
5615
    repo.gc(true).unwrap();
5616
    assert_eq!(repo.receipts(&heads).unwrap().len(), 1);
5617
    assert_eq!(repo.read_blob(&out).unwrap(), b"built\n");
5618
    assert!(repo.fsck().unwrap().problems.is_empty());
5619
}
5620
5621
#[test]
5622
fn status_leaves_an_unchanged_manifest_alone() {
5623
    hermetic();
5624
    let dir = tempfile::tempdir().unwrap();
5625
    let root = dir.path();
5626
    let repo = Repo::init(root).unwrap().with_home(root.join("home"));
5627
    write(root, "a.txt", b"1\n");
5628
    write(root, "b.txt", b"2\n");
5629
    repo.commit("A", &[]).unwrap();
5630
    // Files last touched well outside the racy window.
5631
    let old = std::time::SystemTime::now() - std::time::Duration::from_secs(60);
5632
    for f in ["a.txt", "b.txt"] {
5633
        fs::File::options()
5634
            .write(true)
5635
            .open(root.join(f))
5636
            .unwrap()
5637
            .set_modified(old)
5638
            .unwrap();
5639
    }
5640
    repo.snapshot_status("status").unwrap();
5641
    let path = repo.manifest_path();
5642
    let first = fs::read(&path).unwrap();
5643
    repo.snapshot_status("status").unwrap();
5644
    assert_eq!(
5645
        fs::read(&path).unwrap(),
5646
        first,
5647
        "an unchanged tree does not rewrite the manifest"
5648
    );
5649
    // A change rewrites it.
5650
    write(root, "a.txt", b"1\n2\n");
5651
    repo.snapshot_status("status").unwrap();
5652
    assert_ne!(fs::read(&path).unwrap(), first);
5653
}
5654
5655
#[test]
5656
fn large_text_files_travel_and_survive_gc_as_text_blobs() {
5657
    hermetic();
5658
    let dir = tempfile::tempdir().unwrap();
5659
    let root = dir.path();
5660
    let origin_path = root.join("origin");
5661
    Repo::init(&origin_path).unwrap();
5662
    let origin_url = origin_path.to_string_lossy().to_string();
5663
    let a = Repo::clone(&origin_url, &root.join("a")).unwrap();
5664
    let big: String = (0..5000).map(|i| format!("line {i}\n")).collect();
5665
    write(&root.join("a"), "big.txt", big.as_bytes());
5666
    write(&root.join("a"), "small.txt", b"small\n");
5667
    let h1 = a.commit("large", &[]).unwrap();
5668
    let (_, body) = a.store().get(&h1).unwrap();
5669
    assert!(body.len() < 2048, "the change is {} bytes", body.len());
5670
    assert!(a.push("origin", false).unwrap()[0].ok);
5671
5672
    // A clone reads the text from the blobs that came with the change.
5673
    let b = Repo::clone(&origin_url, &root.join("b")).unwrap();
5674
    assert_eq!(fs::read(root.join("b/big.txt")).unwrap(), big.as_bytes());
5675
    // An edit in the middle of the stored insert is an ordinary change.
5676
    let edited = big.replace("line 2500\n", "line 2500, edited\n");
5677
    write(&root.join("b"), "big.txt", edited.as_bytes());
5678
    let h2 = b.commit("edit", &[]).unwrap();
5679
    assert!(b.store().get_change(&h2).unwrap().edits.len() <= 2);
5680
    assert!(b.push("origin", false).unwrap()[0].ok);
5681
    assert!(a.pull("origin").unwrap().checked_out);
5682
    assert_eq!(fs::read(root.join("a/big.txt")).unwrap(), edited.as_bytes());
5683
    assert_eq!(
5684
        a.fsck().unwrap().errors(),
5685
        0,
5686
        "{:?}",
5687
        a.fsck().unwrap().problems
5688
    );
5689
5690
    // With zero retention gc keeps the text blobs of every kept change.
5691
    let mut a = Repo::open(&root.join("a")).unwrap();
5692
    a.config.set("core.op-retention", "0").unwrap();
5693
    a.save_config().unwrap();
5694
    let a = Repo::open(&root.join("a")).unwrap();
5695
    a.gc(true).unwrap();
5696
    let a = Repo::open(&root.join("a")).unwrap();
5697
    assert_eq!(a.store().get_change(&h1).unwrap().message, "large");
5698
    assert_eq!(
5699
        a.fsck().unwrap().errors(),
5700
        0,
5701
        "{:?}",
5702
        a.fsck().unwrap().problems
5703
    );
5704
    // And a clone of the packed repository reads them from its packs.
5705
    let c = Repo::clone(&root.join("a").to_string_lossy(), &root.join("c")).unwrap();
5706
    assert_eq!(fs::read(root.join("c/big.txt")).unwrap(), edited.as_bytes());
5707
    drop(c);
5708
}
5709
5710
#[test]
5711
fn operations_that_both_replace_a_working_copy_are_not_merged() {
5712
    hermetic();
5713
    let dir = tempfile::tempdir().unwrap();
5714
    let root = dir.path();
5715
    let repo = Repo::init(root).unwrap();
5716
    write(root, "a.txt", b"a\n");
5717
    let a = repo.commit("a", &[]).unwrap();
5718
    write(root, "b.txt", b"b\n");
5719
    repo.commit("b", &[]).unwrap();
5720
    let (x, op) = repo.head_op().unwrap();
5721
    let ws = *op.view.workspaces.keys().next().unwrap();
5722
    let mut one = op.view.clone();
5723
    one.workspaces.insert(ws, a);
5724
    let mut two = op.view.clone();
5725
    two.workspaces.insert(ws, ObjectRef([7; 32]));
5726
    let first = repo.record_op(&[x], "one", one).unwrap();
5727
    let e = repo.record_op(&[x], "two", two).unwrap_err();
5728
    assert!(
5729
        e.to_string()
5730
            .contains("changed this working copy at the same time"),
5731
        "{e}"
5732
    );
5733
    assert_eq!(
5734
        repo.head_op().unwrap().0,
5735
        first,
5736
        "the second is not recorded"
5737
    );
5738
}
5739
5740
/// Metalgear, 2026-09-29 (oxygen#36): a status run while a bookmark switch
5741
/// rewrote the working copy recorded the half-written files as edits, and
5742
/// its view replaced the switch's.
5743
#[test]
5744
fn a_snapshot_during_a_switch_never_records_the_switch_as_edits() {
5745
    hermetic();
5746
    let dir = tempfile::tempdir().unwrap();
5747
    let root = dir.path().to_path_buf();
5748
    let mut repo = Repo::init(&root).unwrap();
5749
    write(&root, "keep.txt", b"keep\n");
5750
    repo.commit("base", &[]).unwrap();
5751
    repo.bookmark_create("small", None).unwrap();
5752
    for i in 0..300 {
5753
        write(
5754
            &root,
5755
            &format!("many/f{i}.txt"),
5756
            format!("file {i}\n").as_bytes(),
5757
        );
5758
    }
5759
    repo.commit("many", &[]).unwrap();
5760
    let stop = std::sync::Arc::new(std::sync::atomic::AtomicBool::new(false));
5761
    let watcher = {
5762
        let (root, stop) = (root.clone(), stop.clone());
5763
        std::thread::spawn(move || {
5764
            let r = Repo::open(&root).unwrap();
5765
            let mut ran = 0;
5766
            while !stop.load(std::sync::atomic::Ordering::Relaxed) {
5767
                if r.snapshot_status("oxy status").is_ok() {
5768
                    ran += 1;
5769
                }
5770
            }
5771
            ran
5772
        })
5773
    };
5774
    for i in 0..20 {
5775
        let to = if i % 2 == 0 { "small" } else { "main" };
5776
        repo.bookmark_switch(to, false).unwrap();
5777
    }
5778
    stop.store(true, std::sync::atomic::Ordering::Relaxed);
5779
    assert!(watcher.join().unwrap() > 0, "the watcher snapshotted");
5780
    // Back on main, clean, with every file where main has it.
5781
    let repo = Repo::open(&root).unwrap();
5782
    let s = repo.snapshot_status("oxy status").unwrap();
5783
    assert!(s.statuses.is_empty(), "{:?}", statuses(&s));
5784
    assert!(s.wc.edits.is_empty() && s.wc.tree_ops.is_empty());
5785
    assert_eq!(s.wc.deps, repo.bookmark_heads().unwrap());
5786
    assert!(root.join("many/f299.txt").exists());
5787
}
5788
5789
/// Metalgear, 2026-09-29 (oxygen#38): a parent's `bookmark switch --carry`
5790
/// put a subrepo that was ahead of its pin back at the pin and moved the
5791
/// subrepo's own bookmark backwards.
5792
#[test]
5793
fn a_parent_switch_with_carry_leaves_a_subrepo_ahead_of_its_pin_alone() {
5794
    hermetic();
5795
    let dir = tempfile::tempdir().unwrap();
5796
    let root = dir.path();
5797
    Repo::init(&root.join("lib-origin")).unwrap();
5798
    let lib_url = root.join("lib-origin").to_string_lossy().to_string();
5799
    let lib = Repo::clone(&lib_url, &root.join("lib")).unwrap();
5800
    write(&root.join("lib"), "lib.txt", b"v1\n");
5801
    lib.commit("lib v1", &[]).unwrap();
5802
    assert!(lib.push("origin", false).unwrap()[0].ok);
5803
5804
    let app_dir = root.join("app");
5805
    let mut app = Repo::init(&app_dir).unwrap();
5806
    write(&app_dir, "main.txt", b"app\n");
5807
    app.submodule_add(&lib_url, "libs/lib", None).unwrap();
5808
    app.commit("app with lib", &[]).unwrap();
5809
    app.bookmark_create("feature", None).unwrap();
5810
5811
    // New work in the subrepo, not yet pinned by the parent.
5812
    let nested_dir = app_dir.join("libs/lib");
5813
    let nested = Repo::open(&nested_dir).unwrap();
5814
    write(&nested_dir, "new.txt", b"new\n");
5815
    let l2 = nested.commit("lib: new file", &[]).unwrap();
5816
    drop(nested);
5817
5818
    let (_, carried) = app.bookmark_switch_carry("feature").unwrap();
5819
    assert!(carried.contains(&"libs/lib".to_string()), "{carried:?}");
5820
    let nested = Repo::open(&nested_dir).unwrap();
5821
    assert!(
5822
        nested.bookmark_heads().unwrap().contains(&l2),
5823
        "its bookmark kept its work"
5824
    );
5825
    assert!(nested_dir.join("new.txt").exists(), "and its files");
5826
    let s = app.snapshot("status").unwrap();
5827
    assert_eq!(
5828
        statuses(&s),
5829
        vec![("libs/lib".to_string(), ChangeStatus::Modified)]
5830
    );
5831
}
5832
5833
/// oxygen#29 (metalgear, rstar-api): after a proposal landed on the hub,
5834
/// moving `main` to a change this clone had pushed on another bookmark,
5835
/// the first `pull` said "Already up to date" while `main` was behind.
5836
#[test]
5837
fn pull_takes_a_remote_move_to_changes_already_here() {
5838
    hermetic();
5839
    let dir = tempfile::tempdir().unwrap();
5840
    let root = dir.path();
5841
    let origin_path = root.join("origin");
5842
    let origin = Repo::init(&origin_path).unwrap();
5843
    let url = origin_path.to_string_lossy().to_string();
5844
    let mut b = Repo::clone(&url, &root.join("b")).unwrap();
5845
    write(&root.join("b"), "base.txt", b"base\n");
5846
    b.commit("base", &[]).unwrap();
5847
    assert!(b.push("origin", false).unwrap()[0].ok);
5848
    origin.refresh().unwrap();
5849
5850
    // A feature bookmark with one change, pushed.
5851
    b.bookmark_create("feat", None).unwrap();
5852
    b.bookmark_switch("feat", false).unwrap();
5853
    write(&root.join("b"), "x.txt", b"x\n");
5854
    let x = b.commit("x", &[]).unwrap();
5855
    assert!(b.push("origin", false).unwrap()[0].ok);
5856
    origin.refresh().unwrap();
5857
    b.bookmark_switch("main", false).unwrap();
5858
5859
    // The remote lands it: its main moves to the feature's state.
5860
    let feat = origin
5861
        .store()
5862
        .get_state(&origin.view().unwrap().bookmarks["feat"])
5863
        .unwrap()
5864
        .heads;
5865
    origin.bookmark_set("main", &feat).unwrap();
5866
5867
    let r = b.pull("origin").unwrap();
5868
    assert!(r.changed, "{r:?}");
5869
    assert!(r.heads.contains(&x) || b.load_state(&r.heads).unwrap().contains(&x));
5870
    let main = b
5871
        .bookmarks()
5872
        .unwrap()
5873
        .into_iter()
5874
        .find(|m| m.name == "main")
5875
        .unwrap();
5876
    assert_eq!(main.behind, Some(0), "{main:?}");
5877
}
5878
5879
/// oxygen#48: a remote's bookmarks are names here (`origin/NAME`); switching
5880
/// to one only the remote has makes a local bookmark from it; a pull moves
5881
/// every local bookmark the remote has too; a clone checks out the remote's
5882
/// default bookmark.
5883
#[test]
5884
fn remote_bookmarks_are_named_switched_to_pulled_and_cloned() {
5885
    hermetic();
5886
    let dir = tempfile::tempdir().unwrap();
5887
    let root = dir.path();
5888
    let origin_path = root.join("origin");
5889
    let mut origin = Repo::init(&origin_path).unwrap();
5890
    let url = origin_path.to_string_lossy().to_string();
5891
    let mut a = Repo::clone(&url, &root.join("a")).unwrap();
5892
    write(&root.join("a"), "base.txt", b"base\n");
5893
    a.commit("base", &[]).unwrap();
5894
    assert!(a.push("origin", false).unwrap()[0].ok);
5895
    a.bookmark_create("develop", None).unwrap();
5896
    a.bookmark_switch("develop", false).unwrap();
5897
    write(&root.join("a"), "base.txt", b"base\nd1\n");
5898
    let d1 = a.commit("d1", &[]).unwrap();
5899
    assert!(a.push("origin", false).unwrap()[0].ok);
5900
5901
    // A clone has main only; origin/develop is a name all the same.
5902
    let c_root = root.join("c");
5903
    let mut c = Repo::clone(&url, &c_root).unwrap();
5904
    assert_eq!(c.config.bookmark, "main");
5905
    assert!(!c.view().unwrap().bookmarks.contains_key("develop"));
5906
    assert_eq!(c.resolve_heads("origin/develop").unwrap(), vec![d1]);
5907
    assert_eq!(c.resolve_change("origin/develop").unwrap(), d1);
5908
    assert_eq!(c.remote_only_bookmarks().unwrap().len(), 1);
5909
5910
    // Switching makes the local bookmark from origin's.
5911
    c.bookmark_switch("develop", false).unwrap();
5912
    assert_eq!(c.config.bookmark, "develop");
5913
    assert_eq!(c.bookmark_heads().unwrap(), vec![d1]);
5914
    assert_eq!(fs::read(c_root.join("base.txt")).unwrap(), b"base\nd1\n");
5915
    assert!(c.remote_only_bookmarks().unwrap().is_empty());
5916
    assert!(c.bookmark_switch("nowhere", false).is_err());
5917
5918
    // Both bookmarks move on the remote; one pull takes both.
5919
    write(&root.join("a"), "base.txt", b"base\nd1\nd2\n");
5920
    let d2 = a.commit("d2", &[]).unwrap();
5921
    assert!(a.push("origin", false).unwrap()[0].ok);
5922
    a.bookmark_switch("main", false).unwrap();
5923
    write(&root.join("a"), "m.txt", b"m\n");
5924
    let m = a.commit("m", &[]).unwrap();
5925
    assert!(a.push("origin", false).unwrap()[0].ok);
5926
    let r = c.pull("origin").unwrap();
5927
    assert!(r.changed && r.checked_out, "{r:?}");
5928
    assert_eq!(r.heads, vec![d2]);
5929
    assert_eq!(r.others, vec!["main".to_string()]);
5930
    assert!(c.resolve_heads("main").unwrap().contains(&m));
5931
    assert_eq!(
5932
        fs::read(c_root.join("base.txt")).unwrap(),
5933
        b"base\nd1\nd2\n"
5934
    );
5935
    let again = c.pull("origin").unwrap();
5936
    assert!(!again.changed && again.others.is_empty(), "{again:?}");
5937
5938
    // A clone checks out the remote's default bookmark.
5939
    origin.config.set("workspace.bookmark", "develop").unwrap();
5940
    origin.save_config().unwrap();
5941
    let e = Repo::clone(&url, &root.join("e")).unwrap();
5942
    assert_eq!(e.config.bookmark, "develop");
5943
    assert_eq!(e.bookmark_heads().unwrap(), vec![d2]);
5944
    let reopened = Repo::open(&root.join("e")).unwrap();
5945
    assert_eq!(reopened.config.bookmark, "develop");
5946
    // REMOTE/NAME names the remote's bookmark to switch to.
5947
    let mut e = reopened;
5948
    e.bookmark_switch("origin/main", false).unwrap();
5949
    assert_eq!(e.config.bookmark, "main");
5950
    assert!(e.bookmark_heads().unwrap().contains(&m));
5951
}
5952
5953
/// oxygen#51, #52: --at-op reads an earlier view and refuses changes;
5954
/// op restore goes back to an operation, files included, and undo takes
5955
/// the restore back whole; op revert undoes one operation alone; each
5956
/// operation's changes are described from the views.
5957
#[test]
5958
fn operations_can_be_read_restored_and_reverted() {
5959
    hermetic();
5960
    let dir = tempfile::tempdir().unwrap();
5961
    let root = dir.path();
5962
    let repo = Repo::init(root).unwrap();
5963
    write(root, "a.txt", b"a\n");
5964
    let first = repo.commit("first", &[]).unwrap();
5965
    write(root, "a.txt", b"a\nb\n");
5966
    let second = repo.commit("second", &[]).unwrap();
5967
    let at_second = repo.head_op().unwrap().0.to_hex();
5968
    repo.bookmark_create("keep", None).unwrap();
5969
    let created = repo.head_op().unwrap().0.to_hex();
5970
    write(root, "n.txt", b"n\n");
5971
    let third = repo.commit("third", &[]).unwrap();
5972
5973
    // What each operation changed.
5974
    let ops = repo.op_log().unwrap();
5975
    let changes = repo.view_changes(&ops[1].1.view, &ops[0].1.view).unwrap();
5976
    assert!(
5977
        changes
5978
            .iter()
5979
            .any(|c| matches!(c, ViewChange::BookmarkMoved { name, .. } if name == "main")),
5980
        "{changes:?}"
5981
    );
5982
    assert!(changes
5983
        .iter()
5984
        .any(|c| matches!(c, ViewChange::WorkingCopy { .. })));
5985
5986
    // Reading at an earlier operation.
5987
    let old = Repo::open(root).unwrap().at_op(&at_second[..10]).unwrap();
5988
    assert_eq!(old.bookmark_heads().unwrap(), vec![second]);
5989
    assert!(!old.view().unwrap().bookmarks.contains_key("keep"));
5990
    write(root, "z.txt", b"z\n");
5991
    assert!(old.commit("refused", &[]).is_err(), "--at-op is read-only");
5992
    fs::remove_file(root.join("z.txt")).unwrap();
5993
    assert!(repo.resolve_op("zz").is_err());
5994
    assert_eq!(repo.resolve_op("@").unwrap().0, repo.head_op().unwrap().0);
5995
5996
    // Restore goes back, files and all; undo takes it back whole.
5997
    repo.op_restore(&at_second, false).unwrap();
5998
    assert_eq!(repo.bookmark_heads().unwrap(), vec![second]);
5999
    assert!(!root.join("n.txt").exists());
6000
    repo.undo().unwrap();
6001
    let mut heads = repo.bookmark_heads().unwrap();
6002
    heads.sort();
6003
    let mut want = vec![second, third];
6004
    want.sort();
6005
    assert_eq!(heads, want);
6006
    assert!(
6007
        root.join("n.txt").exists(),
6008
        "the files came back with the undo"
6009
    );
6010
6011
    // Revert the bookmark's creation alone: the commit after it stays.
6012
    let r = repo.op_revert(&created).unwrap();
6013
    assert_eq!(r.reverted, vec!["keep".to_string()]);
6014
    assert!(!repo.view().unwrap().bookmarks.contains_key("keep"));
6015
    assert!(repo
6016
        .load_state(&repo.bookmark_heads().unwrap())
6017
        .unwrap()
6018
        .contains(&third));
6019
    assert!(repo.op_revert(&created).is_err(), "nothing left to revert");
6020
    let _ = first;
6021
}
6022
6023
/// oxygen#41: with uncommitted work, a status after a snapshot is answered
6024
/// from the status cache while every file is as the snapshot left it, and
6025
/// from a snapshot again as soon as one is not.
6026
#[test]
6027
fn status_with_uncommitted_work_comes_from_the_cache_until_a_file_changes() {
6028
    hermetic();
6029
    let dir = tempfile::tempdir().unwrap();
6030
    let root = dir.path();
6031
    let repo = Repo::init(root).unwrap();
6032
    write(root, "a.txt", b"a\n");
6033
    write(root, "b.txt", b"b\n");
6034
    repo.commit("base", &[]).unwrap();
6035
    assert_eq!(repo.status_by_manifest().unwrap(), Some(vec![]), "clean");
6036
6037
    write(root, "a.txt", b"a\nmore\n");
6038
    assert_eq!(
6039
        repo.status_by_manifest().unwrap(),
6040
        None,
6041
        "no snapshot of the edit yet"
6042
    );
6043
    let snap = repo.snapshot_status("oxy status").unwrap();
6044
    assert_eq!(snap.statuses.len(), 1);
6045
    let cached = repo
6046
        .status_by_manifest()
6047
        .unwrap()
6048
        .expect("answered from the cache");
6049
    assert_eq!(cached.len(), 1);
6050
    assert_eq!(
6051
        (cached[0].path.as_str(), cached[0].status),
6052
        ("a.txt", ChangeStatus::Modified)
6053
    );
6054
6055
    // Any further change sends status back to a snapshot.
6056
    write(root, "a.txt", b"a\nmore\nand more\n");
6057
    assert_eq!(repo.status_by_manifest().unwrap(), None, "edited again");
6058
    repo.snapshot_status("oxy status").unwrap();
6059
    assert!(repo.status_by_manifest().unwrap().is_some());
6060
    write(root, "new.txt", b"n\n");
6061
    assert_eq!(repo.status_by_manifest().unwrap(), None, "a file added");
6062
    fs::remove_file(root.join("new.txt")).unwrap();
6063
    assert!(
6064
        repo.status_by_manifest().unwrap().is_some(),
6065
        "back as it was"
6066
    );
6067
    fs::remove_file(root.join("b.txt")).unwrap();
6068
    assert_eq!(repo.status_by_manifest().unwrap(), None, "a file removed");
6069
    write(root, "b.txt", b"b\n");
6070
6071
    // A commit leaves nothing uncommitted: clean again, no cache needed.
6072
    repo.snapshot_status("oxy status").unwrap();
6073
    repo.commit("more", &[]).unwrap();
6074
    assert_eq!(repo.status_by_manifest().unwrap(), Some(vec![]));
6075
}
6076
6077
/// oxygen#41: while the status cache holds, the working copy's diff is
6078
/// rendered from the stored working-copy change, and says exactly what a
6079
/// snapshot's diff says.
6080
#[test]
6081
fn the_working_copy_diff_from_the_cache_matches_a_snapshot() {
6082
    hermetic();
6083
    let dir = tempfile::tempdir().unwrap();
6084
    let root = dir.path();
6085
    let repo = Repo::init(root).unwrap();
6086
    write(root, "a.txt", b"one\ntwo\nthree\n");
6087
    write(root, "gone.txt", b"bye\n");
6088
    repo.commit("base", &[]).unwrap();
6089
    write(root, "a.txt", b"one\n2\nthree\nfour\n");
6090
    write(root, "new.txt", b"hello\n");
6091
    fs::remove_file(root.join("gone.txt")).unwrap();
6092
    let snap = repo.snapshot_status("oxy status").unwrap();
6093
    let slow = render_change(&snap.wc, &snap.base, &snap.base_snapshot);
6094
    assert!(
6095
        repo.status_by_manifest().unwrap().is_some(),
6096
        "the cache holds"
6097
    );
6098
    let (wc, base, snapshot) = repo.working_copy_with_base().unwrap();
6099
    assert_eq!(render_change(&wc, &base, &snapshot), slow);
6100
    assert_eq!(repo.diff_files(None).unwrap().len(), 3);
6101
}
6102
6103
/// oxygen#41: a manifest written from a walk keeps every directory's time;
6104
/// while none has moved, the check stats the tracked files without listing
6105
/// the tree, and a file added or removed anywhere moves its directory's
6106
/// time, so the tree is listed again.
6107
#[test]
6108
fn the_manifest_check_skips_listing_while_no_directory_changed() {
6109
    hermetic();
6110
    let dir = tempfile::tempdir().unwrap();
6111
    let root = dir.path();
6112
    let repo = Repo::init(root).unwrap();
6113
    write(root, "a.txt", b"a\n");
6114
    write(root, "sub/deep/b.txt", b"b\n");
6115
    repo.commit("base", &[]).unwrap();
6116
    // Out of the racy window: every file and directory a minute old.
6117
    let old = std::time::SystemTime::now() - std::time::Duration::from_secs(60);
6118
    for p in ["a.txt", "sub/deep/b.txt", "sub/deep", "sub", ""] {
6119
        fs::File::open(root.join(p))
6120
            .unwrap()
6121
            .set_modified(old)
6122
            .unwrap();
6123
    }
6124
    repo.snapshot_status("oxy status").unwrap();
6125
    repo.write_manifest(false, false).unwrap();
6126
    let m = repo.read_manifest().unwrap().unwrap().2;
6127
    assert!(m.dirs.iter().any(|(d, _)| d == "sub/deep"), "{:?}", m.dirs);
6128
    assert_eq!(
6129
        repo.disk_differs_by_dirs(&m),
6130
        Some(false),
6131
        "no listing needed"
6132
    );
6133
    assert_eq!(repo.status_by_manifest().unwrap(), Some(vec![]));
6134
6135
    // A same-size edit with a new time: found by its stat.
6136
    write(root, "sub/deep/b.txt", b"c\n");
6137
    assert_eq!(repo.disk_differs_by_dirs(&m), Some(true));
6138
    write(root, "sub/deep/b.txt", b"b\n");
6139
    fs::File::open(root.join("sub/deep/b.txt"))
6140
        .unwrap()
6141
        .set_modified(old)
6142
        .unwrap();
6143
    assert_eq!(repo.disk_differs_by_dirs(&m), Some(false));
6144
6145
    // A new file moves its directory's time: the tree must be listed.
6146
    write(root, "sub/deep/new.txt", b"n\n");
6147
    assert_eq!(repo.disk_differs_by_dirs(&m), None);
6148
    assert_eq!(repo.status_by_manifest().unwrap(), None);
6149
    fs::remove_file(root.join("sub/deep/new.txt")).unwrap();
6150
    // A removed one too.
6151
    fs::remove_file(root.join("a.txt")).unwrap();
6152
    assert_eq!(repo.disk_differs_by_dirs(&m), None);
6153
}
6154
6155
/// oxygen#41: a commit right after a status takes the snapshot the status
6156
/// left (the status cache holds) rather than walking again, and commits
6157
/// exactly what a snapshot would have.
6158
#[test]
6159
fn a_commit_after_a_status_uses_the_cached_snapshot() {
6160
    hermetic();
6161
    let dir = tempfile::tempdir().unwrap();
6162
    let root = dir.path();
6163
    let repo = Repo::init(root).unwrap();
6164
    write(root, "a.txt", b"a\nb\n");
6165
    write(root, ".oxyattributes", b"*.bin binary\n");
6166
    repo.commit("base", &[]).unwrap();
6167
    write(root, "a.txt", b"a\nB\n");
6168
    write(root, "new.txt", b"new\n");
6169
    let snap = repo.snapshot_status("oxy status").unwrap();
6170
    let cached = repo
6171
        .snapshot_from_cache()
6172
        .unwrap()
6173
        .expect("the cache holds");
6174
    assert_eq!(cached.wc_hash, snap.wc_hash);
6175
    assert_eq!(cached.statuses, snap.statuses);
6176
    assert!(
6177
        !cached.attributes.is_empty(),
6178
        "the .oxyattributes file was read"
6179
    );
6180
    let h = repo.commit("edit", &[]).unwrap();
6181
    let c = repo.store().get_change(&h).unwrap();
6182
    assert_eq!(
6183
        c.tree_ops.len() + c.edits.len(),
6184
        snap.wc.tree_ops.len() + snap.wc.edits.len()
6185
    );
6186
    assert_eq!(
6187
        repo.status_by_manifest().unwrap(),
6188
        Some(vec![]),
6189
        "clean after the commit"
6190
    );
6191
    assert_eq!(fs::read(root.join("a.txt")).unwrap(), b"a\nB\n");
6192
}
6193
6194
/// oxygen#41: a clean check that verified racy entries restamps the
6195
/// manifest, so later checks can trust them, and a same-size rewrite
6196
/// straight afterwards is still found: entries within two seconds of the
6197
/// new time stay racy.
6198
#[test]
6199
fn a_verified_clean_check_restamps_the_manifest_safely() {
6200
    hermetic();
6201
    let dir = tempfile::tempdir().unwrap();
6202
    let root = dir.path();
6203
    let repo = Repo::init(root).unwrap();
6204
    write(root, "a.txt", b"one\n");
6205
    repo.commit("one", &[]).unwrap();
6206
    let before = repo.read_manifest().unwrap().unwrap().2.written_ns;
6207
    assert!(repo.clean_by_manifest().unwrap());
6208
    let after = repo.read_manifest().unwrap().unwrap().2.written_ns;
6209
    assert!(after > before, "restamped");
6210
    write(root, "a.txt", b"two\n");
6211
    assert!(
6212
        !repo.clean_by_manifest().unwrap(),
6213
        "a same-size rewrite is still seen"
6214
    );
6215
}
6216
6217
/// oxygen#35: a history-only state keeps no inserted text. It reads a
6218
/// stored insert's text blob only when it builds that file's graph, and
6219
/// builds the same graph a full load does.
6220
#[test]
6221
fn history_only_states_read_text_only_for_the_graphs_they_build() {
6222
    hermetic();
6223
    let dir = tempfile::tempdir().unwrap();
6224
    let root = dir.path();
6225
    let repo = Repo::init(root).unwrap();
6226
    let big: String = (0..3000).map(|i| format!("big line {i}\n")).collect();
6227
    let other: String = (0..3000).map(|i| format!("other line {i}\n")).collect();
6228
    write(root, "big.txt", big.as_bytes());
6229
    write(root, "other.txt", other.as_bytes());
6230
    let h = repo.commit("two large files", &[]).unwrap();
6231
    write(root, "big.txt", format!("{big}one more\n").as_bytes());
6232
    let h2 = repo.commit("append", &[]).unwrap();
6233
6234
    let full = repo.load_state_full(&[h2]).unwrap().materialize();
6235
    let text = |snap: &crate::state::Snapshot, p: &str| match &snap.files[p].content {
6236
        FileContent::Text { bytes, .. } => bytes.clone(),
6237
        other => panic!("{other:?}"),
6238
    };
6239
    // Built on demand, every graph renders as the full load's.
6240
    let mut hist = repo.load_state_history(&[h2]).unwrap();
6241
    let big_node = full.files["big.txt"].node;
6242
    assert!(hist.graph_key(&big_node).is_some(), "not built yet");
6243
    repo.load_all_graphs(&mut hist).unwrap();
6244
    let rendered = hist.materialize();
6245
    for p in ["big.txt", "other.txt"] {
6246
        assert_eq!(text(&rendered, p), text(&full, p), "{p}");
6247
    }
6248
6249
    // Without other.txt's text blob, history still loads and big.txt still
6250
    // builds: nothing read the other text.
6251
    let (_, texts) = repo.store().get_change_lazy(&h).unwrap();
6252
    assert_eq!(texts.len(), 2);
6253
    let content = |r: &ObjectRef| -> Vec<u8> {
6254
        let blob = crate::objects::Blob::decode(&repo.store().get(r).unwrap().1).unwrap();
6255
        blob.chunks
6256
            .iter()
6257
            .flat_map(|c| repo.store().get(c).unwrap().1)
6258
            .collect()
6259
    };
6260
    let other_text = texts
6261
        .iter()
6262
        .filter_map(|t| match t {
6263
            crate::objects::TextRef::Blob(r, _, _) => Some(*r),
6264
            _ => None,
6265
        })
6266
        .find(|r| content(r).windows(12).any(|w| w == b"other line 1"))
6267
        .unwrap();
6268
    repo.store().remove_loose_for_test(&other_text).unwrap();
6269
    let mut hist = repo.load_state_history(&[h2]).unwrap();
6270
    repo.load_graphs_of(&mut hist, &[big_node]).unwrap();
6271
    assert!(repo
6272
        .load_graphs_of(&mut hist, &[full.files["other.txt"].node])
6273
        .is_err());
6274
}
6275
6276
/// oxygen#35: the first status after a commit read and rendered every
6277
/// file (79 s and more than 14 GB on the Linux tree), because the
6278
/// manifest had no graph keys for files the commit added.
6279
#[test]
6280
fn a_commit_leaves_a_manifest_the_next_status_trusts() {
6281
    use std::os::unix::fs::PermissionsExt;
6282
    hermetic();
6283
    let dir = tempfile::tempdir().unwrap();
6284
    let root = dir.path();
6285
    let repo = Repo::init(root).unwrap();
6286
    let files = ["a.txt", "b.txt", "d/c.txt"];
6287
    for p in files {
6288
        write(root, p, format!("{p}\n").as_bytes());
6289
        let old = std::time::SystemTime::now() - std::time::Duration::from_secs(30);
6290
        fs::File::options()
6291
            .write(true)
6292
            .open(root.join(p))
6293
            .unwrap()
6294
            .set_modified(old)
6295
            .unwrap();
6296
    }
6297
    repo.commit("added", &[]).unwrap();
6298
    let (_, _, m) = repo.read_manifest().unwrap().unwrap();
6299
    assert!(
6300
        m.entries.values().all(|e| e.graph.is_some()),
6301
        "keys recorded at commit"
6302
    );
6303
    // Unreadable files prove the next status reads none of them.
6304
    for p in files {
6305
        fs::set_permissions(root.join(p), fs::Permissions::from_mode(0o000)).unwrap();
6306
    }
6307
    let snap = repo.snapshot_status("status").unwrap();
6308
    for p in files {
6309
        fs::set_permissions(root.join(p), fs::Permissions::from_mode(0o644)).unwrap();
6310
    }
6311
    assert!(!snap.changed && snap.statuses.is_empty());
6312
    assert_eq!(snap.base_snapshot.unrendered.len(), files.len());
6313
}
6314
6315
/// oxygen#35: a checkout reads, renders and writes only the files whose
6316
/// graphs differ, and renders the rest a batch at a time.
6317
#[test]
6318
fn checkout_touches_only_what_differs_and_renders_in_batches() {
6319
    use std::os::unix::fs::PermissionsExt;
6320
    hermetic();
6321
    let dir = tempfile::tempdir().unwrap();
6322
    let root = dir.path();
6323
    let origin = root.join("origin");
6324
    let mut repo = Repo::init(&origin).unwrap();
6325
    // More files than one batch holds.
6326
    let n = 2100;
6327
    let old = std::time::SystemTime::now() - std::time::Duration::from_secs(30);
6328
    for i in 0..n {
6329
        let p = format!("f/{i:04}.txt");
6330
        write(&origin, &p, format!("file {i}\n").as_bytes());
6331
        fs::File::options()
6332
            .write(true)
6333
            .open(origin.join(&p))
6334
            .unwrap()
6335
            .set_modified(old)
6336
            .unwrap();
6337
    }
6338
    repo.commit("many", &[]).unwrap();
6339
    repo.bookmark_create("feature", None).unwrap();
6340
    repo.bookmark_switch("feature", false).unwrap();
6341
    write(&origin, "f/0007.txt", b"changed\n");
6342
    repo.commit("one change", &[]).unwrap();
6343
6344
    // Switching back to main must not read the unchanged files.
6345
    for i in 0..n {
6346
        if i != 7 {
6347
            let p = origin.join(format!("f/{i:04}.txt"));
6348
            fs::set_permissions(&p, fs::Permissions::from_mode(0o000)).unwrap();
6349
        }
6350
    }
6351
    let r = repo.bookmark_switch("main", false).unwrap();
6352
    for i in 0..n {
6353
        let p = origin.join(format!("f/{i:04}.txt"));
6354
        fs::set_permissions(&p, fs::Permissions::from_mode(0o644)).unwrap();
6355
    }
6356
    assert_eq!((r.written, r.removed), (1, 0), "{r:?}");
6357
    assert_eq!(fs::read(origin.join("f/0007.txt")).unwrap(), b"file 7\n");
6358
    assert!(repo.snapshot_status("status").unwrap().statuses.is_empty());
6359
6360
    // A clone renders every file, across batches.
6361
    let c = root.join("clone");
6362
    Repo::clone(&origin.to_string_lossy(), &c).unwrap();
6363
    for i in [0, 2047, 2048, n - 1] {
6364
        assert_eq!(
6365
            fs::read(c.join(format!("f/{i:04}.txt"))).unwrap(),
6366
            format!("file {i}\n").as_bytes()
6367
        );
6368
    }
6369
    let cloned = Repo::open(&c).unwrap();
6370
    assert!(cloned
6371
        .snapshot_status("status")
6372
        .unwrap()
6373
        .statuses
6374
        .is_empty());
6375
}
6376
6377
/// A file written just before the manifest (inside the racy window) is
6378
/// checked by its hash: trusted when equal, caught when edited in place
6379
/// with the same size and time.
6380
#[test]
6381
fn a_racy_manifest_entry_is_checked_by_hash() {
6382
    hermetic();
6383
    let dir = tempfile::tempdir().unwrap();
6384
    let root = dir.path();
6385
    let repo = Repo::init(root).unwrap();
6386
    write(root, "a.txt", b"one\n");
6387
    repo.commit("fresh", &[]).unwrap();
6388
    assert!(repo.clean_by_manifest().unwrap(), "fresh but equal");
6389
    let t = fs::metadata(root.join("a.txt"))
6390
        .unwrap()
6391
        .modified()
6392
        .unwrap();
6393
    write(root, "a.txt", b"two\n");
6394
    fs::File::options()
6395
        .write(true)
6396
        .open(root.join("a.txt"))
6397
        .unwrap()
6398
        .set_modified(t)
6399
        .unwrap();
6400
    assert!(
6401
        !repo.clean_by_manifest().unwrap(),
6402
        "same size and time, other bytes"
6403
    );
6404
    assert_eq!(
6405
        statuses(&repo.snapshot_status("status").unwrap()),
6406
        vec![("a.txt".to_string(), ChangeStatus::Modified)]
6407
    );
6408
}
6409
6410
/// A fetch on one machine moves changes as stored, text blobs among the
6411
/// objects; a change whose text blob did not come is refused, not stored.
6412
#[test]
6413
fn a_raw_bundle_without_a_changes_text_is_refused() {
6414
    hermetic();
6415
    let dir = tempfile::tempdir().unwrap();
6416
    let root = dir.path();
6417
    let a = Repo::init(&root.join("a")).unwrap();
6418
    let big: String = (0..3000).map(|i| format!("line {i}\n")).collect();
6419
    write(&root.join("a"), "big.txt", big.as_bytes());
6420
    let h = a.commit("big", &[]).unwrap();
6421
    let bundle = a.bundle_raw_for(&[h], None).unwrap();
6422
    assert_eq!(bundle.raw_changes.len(), 1);
6423
    assert!(bundle.changes.is_empty());
6424
    let b = Repo::init(&root.join("b")).unwrap();
6425
    let mut without = bundle.clone();
6426
    without.objects.retain(|(ty, _)| *ty != ObjectType::Blob);
6427
    let e = b.import_bundle(&without, false).unwrap_err();
6428
    assert!(e.to_string().contains("came without its text blob"), "{e}");
6429
    assert!(!b.store().has(&h));
6430
    assert_eq!(b.import_bundle(&bundle, false).unwrap(), vec![h]);
6431
    assert_eq!(b.store().get_change(&h).unwrap().message, "big");
6432
}
6433
6434
/// oxygen#30 (vscode): a directory deleted in one line of history and made
6435
/// again was a second node for one Git path, so a file moved into it on
6436
/// another line, where the first node still stood, ended up in two places.
6437
/// An import now brings the directory back rather than make a new one.
6438
#[test]
6439
fn git_import_brings_a_directory_back_rather_than_making_a_second() {
6440
    hermetic();
6441
    if std::process::Command::new("git")
6442
        .arg("--version")
6443
        .output()
6444
        .is_err()
6445
    {
6446
        eprintln!("git not installed; skipping");
6447
        return;
6448
    }
6449
    let dir = tempfile::tempdir().unwrap();
6450
    let root = dir.path();
6451
    let g = root.join("src.git");
6452
    fs::create_dir_all(&g).unwrap();
6453
    let git = |args: &[&str]| -> String {
6454
        let out = std::process::Command::new("git")
6455
            .arg("-C")
6456
            .arg(&g)
6457
            .args([
6458
                "-c",
6459
                "user.name=Grace",
6460
                "-c",
6461
                "[email protected]",
6462
                "-c",
6463
                "commit.gpgsign=false",
6464
            ])
6465
            .args(args)
6466
            .output()
6467
            .unwrap();
6468
        assert!(
6469
            out.status.success(),
6470
            "git {args:?}: {}",
6471
            String::from_utf8_lossy(&out.stderr)
6472
        );
6473
        String::from_utf8_lossy(&out.stdout).trim().to_string()
6474
    };
6475
    git(&["init", "-q", "-b", "main"]);
6476
    write(&g, "d/a.txt", b"a\n");
6477
    write(&g, "c/x.txt", b"x\n");
6478
    git(&["add", "."]);
6479
    git(&["commit", "-qm", "base"]);
6480
    // One line: move x into d while d still stands.
6481
    git(&["checkout", "-qb", "side"]);
6482
    git(&["mv", "c/x.txt", "d/x.txt"]);
6483
    git(&["commit", "-qm", "x into d"]);
6484
    // The other: d goes, comes back, and x moves into it too.
6485
    git(&["checkout", "-q", "main"]);
6486
    git(&["rm", "-q", "d/a.txt"]);
6487
    git(&["commit", "-qm", "d goes"]);
6488
    write(&g, "d/b.txt", b"b\n");
6489
    git(&["add", "."]);
6490
    git(&["commit", "-qm", "d comes back"]);
6491
    git(&["mv", "c/x.txt", "d/x.txt"]);
6492
    git(&["commit", "-qm", "x into d again"]);
6493
    git(&["merge", "-q", "--no-edit", "side"]);
6494
6495
    let repo = Repo::init(&root.join("o")).unwrap();
6496
    repo.import_git(&g, "main").unwrap();
6497
    let v = repo.verify_git_import(&g, "main").unwrap();
6498
    assert!(v.mismatches.is_empty(), "{:?}", v.mismatches);
6499
    let st = repo
6500
        .load_state_history(&repo.bookmark_heads().unwrap())
6501
        .unwrap();
6502
    let view = st.tree().view();
6503
    assert!(view.conflicts.is_empty(), "{:?}", view.conflicts);
6504
    // The directory is the one the first commit made.
6505
    // Commits made in one second tie on time: find the first by its message.
6506
    let first = repo
6507
        .log()
6508
        .unwrap()
6509
        .into_iter()
6510
        .find(|e| e.change.message.starts_with("base"))
6511
        .unwrap();
6512
    let base = repo
6513
        .load_state_history(&[first.hash])
6514
        .unwrap()
6515
        .tree()
6516
        .view();
6517
    assert_eq!(view.entries["d"].node, base.entries["d"].node);
6518
}
6519
6520
/// oxygen#30, the rest: a placement left under a directory another line
6521
/// removed is out of sight, so no diff reaches it; the merge that settles
6522
/// where the file is retires it.
6523
#[test]
6524
fn git_import_merge_retires_a_placement_under_a_removed_directory() {
6525
    hermetic();
6526
    if std::process::Command::new("git")
6527
        .arg("--version")
6528
        .output()
6529
        .is_err()
6530
    {
6531
        eprintln!("git not installed; skipping");
6532
        return;
6533
    }
6534
    let dir = tempfile::tempdir().unwrap();
6535
    let root = dir.path();
6536
    let g = root.join("src.git");
6537
    fs::create_dir_all(&g).unwrap();
6538
    let run = |args: &[&str]| {
6539
        std::process::Command::new("git")
6540
            .arg("-C")
6541
            .arg(&g)
6542
            .args([
6543
                "-c",
6544
                "user.name=Grace",
6545
                "-c",
6546
                "[email protected]",
6547
                "-c",
6548
                "commit.gpgsign=false",
6549
            ])
6550
            .args(args)
6551
            .output()
6552
            .unwrap()
6553
    };
6554
    let git = |args: &[&str]| {
6555
        let out = run(args);
6556
        assert!(
6557
            out.status.success(),
6558
            "git {args:?}: {}",
6559
            String::from_utf8_lossy(&out.stderr)
6560
        );
6561
    };
6562
    git(&["init", "-q", "-b", "main"]);
6563
    write(&g, "c/x.txt", b"x\n");
6564
    write(&g, "keep.txt", b"k\n");
6565
    git(&["add", "."]);
6566
    git(&["commit", "-qm", "base"]);
6567
    // One line renames the file within c; the other moves it out of c,
6568
    // which goes.
6569
    git(&["checkout", "-qb", "side"]);
6570
    git(&["mv", "c/x.txt", "c/y.txt"]);
6571
    git(&["commit", "-qm", "rename within c"]);
6572
    git(&["checkout", "-q", "main"]);
6573
    fs::create_dir_all(g.join("n")).unwrap();
6574
    git(&["mv", "c/x.txt", "n/x.txt"]);
6575
    git(&["commit", "-qm", "move out of c"]);
6576
    // Git cannot merge the two renames; the merge keeps n/x.txt.
6577
    let _ = run(&["merge", "-q", "side"]);
6578
    let _ = run(&[
6579
        "rm",
6580
        "-q",
6581
        "--cached",
6582
        "--ignore-unmatch",
6583
        "c/y.txt",
6584
        "c/x.txt",
6585
    ]);
6586
    let _ = std::fs::remove_dir_all(g.join("c"));
6587
    write(&g, "n/x.txt", b"x\n");
6588
    git(&["add", "-A"]);
6589
    git(&["commit", "-qm", "merge: keep n/x.txt"]);
6590
6591
    let repo = Repo::init(&root.join("o")).unwrap();
6592
    repo.import_git(&g, "main").unwrap();
6593
    let v = repo.verify_git_import(&g, "main").unwrap();
6594
    assert!(v.mismatches.is_empty(), "{:?}", v.mismatches);
6595
    let st = repo
6596
        .load_state_history(&repo.bookmark_heads().unwrap())
6597
        .unwrap();
6598
    let view = st.tree().view();
6599
    assert!(view.conflicts.is_empty(), "{:?}", view.conflicts);
6600
    assert!(view.entries.contains_key("n/x.txt"));
6601
}
6602
6603
/// oxygen#30, orphans: a file added on one line into a directory the other
6604
/// line removed is placed where the tree cannot show it; Git's merge keeps
6605
/// the file, and the import's merge leaves exactly one of it.
6606
#[test]
6607
fn git_import_merge_leaves_no_orphan_behind() {
6608
    hermetic();
6609
    if std::process::Command::new("git")
6610
        .arg("--version")
6611
        .output()
6612
        .is_err()
6613
    {
6614
        eprintln!("git not installed; skipping");
6615
        return;
6616
    }
6617
    let dir = tempfile::tempdir().unwrap();
6618
    let root = dir.path();
6619
    let g = root.join("src.git");
6620
    fs::create_dir_all(&g).unwrap();
6621
    let git = |args: &[&str]| {
6622
        let out = std::process::Command::new("git")
6623
            .arg("-C")
6624
            .arg(&g)
6625
            .args([
6626
                "-c",
6627
                "user.name=Grace",
6628
                "-c",
6629
                "[email protected]",
6630
                "-c",
6631
                "commit.gpgsign=false",
6632
            ])
6633
            .args(args)
6634
            .output()
6635
            .unwrap();
6636
        assert!(
6637
            out.status.success(),
6638
            "git {args:?}: {}",
6639
            String::from_utf8_lossy(&out.stderr)
6640
        );
6641
    };
6642
    git(&["init", "-q", "-b", "main"]);
6643
    write(&g, "d/f.txt", b"f\n");
6644
    write(&g, "keep.txt", b"k\n");
6645
    git(&["add", "."]);
6646
    git(&["commit", "-qm", "base"]);
6647
    git(&["checkout", "-qb", "side"]);
6648
    write(&g, "d/new.txt", b"new\n");
6649
    git(&["add", "."]);
6650
    git(&["commit", "-qm", "add into d"]);
6651
    git(&["checkout", "-q", "main"]);
6652
    git(&["rm", "-q", "d/f.txt"]);
6653
    git(&["commit", "-qm", "d goes"]);
6654
    git(&["merge", "-q", "--no-edit", "side"]);
6655
6656
    let repo = Repo::init(&root.join("o")).unwrap();
6657
    repo.import_git(&g, "main").unwrap();
6658
    let v = repo.verify_git_import(&g, "main").unwrap();
6659
    assert!(v.mismatches.is_empty(), "{:?}", v.mismatches);
6660
    let st = repo
6661
        .load_state_history(&repo.bookmark_heads().unwrap())
6662
        .unwrap();
6663
    let view = st.tree().view();
6664
    assert!(view.conflicts.is_empty(), "{:?}", view.conflicts);
6665
    assert!(view.entries.contains_key("d/new.txt"));
6666
}
6667
6668
/// fsck checks a change's text as the blobs it is stored in, without
6669
/// decoding it: a missing text blob is an error named for the change.
6670
#[test]
6671
fn fsck_names_a_missing_text_blob() {
6672
    hermetic();
6673
    let dir = tempfile::tempdir().unwrap();
6674
    let root = dir.path();
6675
    let repo = Repo::init(root).unwrap();
6676
    let big: String = (0..3000).map(|i| format!("line {i}\n")).collect();
6677
    write(root, "big.txt", big.as_bytes());
6678
    let h = repo.commit("big", &[]).unwrap();
6679
    assert_eq!(repo.fsck().unwrap().errors(), 0);
6680
    let (_, texts) = repo.store().get_change_lazy(&h).unwrap();
6681
    let Some(crate::objects::TextRef::Blob(b, _, _)) = texts.first().copied() else {
6682
        panic!("a stored text")
6683
    };
6684
    repo.store().remove_loose_for_test(&b).unwrap();
6685
    let rep = repo.fsck().unwrap();
6686
    assert!(rep.errors() > 0);
6687
    assert!(
6688
        rep.problems.iter().any(|p| p.what.contains(&h.short(12))),
6689
        "{:?}",
6690
        rep.problems
6691
    );
6692
}
6693
6694
/// oxygen#32: a subrepo on the same hub as one of the parent's remotes is
6695
/// reached with that remote's token and CA (a private subrepo then clones
6696
/// for anyone who can read the parent); another hub gets none of them.
6697
#[test]
6698
fn a_subrepo_on_the_parents_hub_borrows_its_credentials() {
6699
    hermetic();
6700
    let dir = tempfile::tempdir().unwrap();
6701
    let mut repo = Repo::init(dir.path()).unwrap();
6702
    repo.config
6703
        .set(
6704
            "remote.origin.url",
6705
            "https://Hub.example:7343/doomsdayone/metalgear",
6706
        )
6707
        .unwrap();
6708
    repo.config.set("remote.origin.token", "secret").unwrap();
6709
    repo.config
6710
        .set("remote.origin.ca", "/tmp/hub-ca.pem")
6711
        .unwrap();
6712
    let same = repo.credentials_for("https://hub.example:7343/doomsdayone/rstar-api");
6713
    assert_eq!(same.token.as_deref(), Some("secret"));
6714
    assert_eq!(same.ca.as_deref(), Some(Path::new("/tmp/hub-ca.pem")));
6715
    for other in [
6716
        "https://elsewhere.example:7343/doomsdayone/rstar-api",
6717
        "https://hub.example/doomsdayone/rstar-api",
6718
        "http://hub.example:7343/doomsdayone/rstar-api",
6719
    ] {
6720
        let o = repo.credentials_for(other);
6721
        assert_ne!(o.token.as_deref(), Some("secret"), "{other}");
6722
    }
6723
}
6724
6725
/// oxygen#47: a remote with no token of its own uses the user's credential
6726
/// store for its hub, and a nested checkout finds its parent's remote
6727
/// token there instead of keeping a copy.
6728
#[test]
6729
fn remotes_use_the_credential_store_and_the_enclosing_checkout() {
6730
    hermetic();
6731
    let home = tempfile::tempdir().unwrap();
6732
    let dir = tempfile::tempdir().unwrap();
6733
    let mut parent = Repo::init(dir.path()).unwrap().with_home(home.path());
6734
    parent
6735
        .config
6736
        .set("remote.origin.url", "https://hub.example/o/parent")
6737
        .unwrap();
6738
    parent.save_config().unwrap();
6739
    assert_eq!(parent.remote_options("origin").token, None);
6740
    crate::credentials::Credentials::at(home.path())
6741
        .save("https://hub.example", "stored", Some("andy"), None)
6742
        .unwrap();
6743
    assert_eq!(
6744
        parent.remote_options("origin").token.as_deref(),
6745
        Some("stored")
6746
    );
6747
6748
    let empty_home = tempfile::tempdir().unwrap();
6749
    let nested = dir.path().join("deps").join("child");
6750
    let mut child = Repo::init(&nested).unwrap().with_home(empty_home.path());
6751
    child
6752
        .config
6753
        .set("remote.origin.url", "https://hub.example/o/child")
6754
        .unwrap();
6755
    child.save_config().unwrap();
6756
    assert_eq!(child.remote_options("origin").token, None);
6757
    parent
6758
        .config
6759
        .set("remote.origin.token", "checkout")
6760
        .unwrap();
6761
    parent.save_config().unwrap();
6762
    assert_eq!(
6763
        child.remote_options("origin").token.as_deref(),
6764
        Some("checkout")
6765
    );
6766
    // Another hub's checkout token is not borrowed.
6767
    child
6768
        .config
6769
        .set("remote.origin.url", "https://other.example/o/child")
6770
        .unwrap();
6771
    assert_eq!(child.remote_options("origin").token, None);
6772
}
6773
6774
#[test]
6775
fn the_metadata_cache_survives_a_torn_tail() {
6776
    hermetic();
6777
    let dir = tempfile::tempdir().unwrap();
6778
    let root = dir.path();
6779
    let repo = Repo::init(root).unwrap();
6780
    write(root, "a.txt", b"1\n");
6781
    let h = repo.commit("first", &[]).unwrap();
6782
    let meta = repo.store().get_change_meta(&h).unwrap();
6783
    let cache = repo.store().dir().join("metas");
6784
    let len = fs::metadata(&cache).unwrap().len();
6785
    assert!(len > 0, "a change read is cached");
6786
    // A torn record at the end: the cache reads up to it and cuts it off.
6787
    fs::OpenOptions::new()
6788
        .append(true)
6789
        .open(&cache)
6790
        .unwrap()
6791
        .write_all(&[7; 20])
6792
        .unwrap();
6793
    let again = Repo::open(root).unwrap();
6794
    assert_eq!(again.store().get_change_meta(&h).unwrap(), meta);
6795
    assert_eq!(fs::metadata(&cache).unwrap().len(), len);
6796
}
6797
6798
#[test]
6799
fn a_manifest_that_does_not_check_reads_as_none() {
6800
    hermetic();
6801
    let dir = tempfile::tempdir().unwrap();
6802
    let root = dir.path();
6803
    let repo = Repo::init(root).unwrap();
6804
    write(root, "a.txt", b"1\n");
6805
    repo.commit("first", &[]).unwrap();
6806
    let path = repo.manifest_path();
6807
    let mut bytes = fs::read(&path).unwrap();
6808
    assert!(Repo::open(root).unwrap().read_manifest().unwrap().is_some());
6809
    let last = bytes.len() - 1;
6810
    bytes[last] ^= 1;
6811
    fs::write(&path, &bytes).unwrap();
6812
    assert!(Repo::open(root).unwrap().read_manifest().unwrap().is_none());
6813
    // The next status reads the files and writes it again.
6814
    let again = Repo::open(root).unwrap();
6815
    assert!(!again.snapshot("status").unwrap().changed);
6816
    assert!(again.read_manifest().unwrap().is_some());
6817
}
6818
6819
#[test]
6820
fn a_commit_leaves_a_manifest_that_proves_the_working_copy_clean() {
6821
    hermetic();
6822
    let dir = tempfile::tempdir().unwrap();
6823
    let root = dir.path();
6824
    let repo = Repo::init(root).unwrap();
6825
    write(root, "a.txt", b"1\n");
6826
    write(root, "b.txt", b"2\n");
6827
    // b.txt outside the racy window, so snapshots take it as unchanged.
6828
    let old = std::time::SystemTime::now() - std::time::Duration::from_secs(60);
6829
    fs::File::options()
6830
        .write(true)
6831
        .open(root.join("b.txt"))
6832
        .unwrap()
6833
        .set_modified(old)
6834
        .unwrap();
6835
    repo.commit("first", &[]).unwrap();
6836
    assert!(repo.clean_by_manifest().unwrap(), "after the first commit");
6837
    repo.snapshot_status("status").unwrap();
6838
    write(root, "a.txt", b"1\n2\n");
6839
    repo.commit("second", &[]).unwrap();
6840
    assert!(
6841
        repo.clean_by_manifest().unwrap(),
6842
        "after a commit of one file"
6843
    );
6844
    // Edited, seen by a status, edited again, then committed: the status
6845
    // left the first edit's stat, which the commit must not keep.
6846
    write(root, "a.txt", b"1\n2\n3\n");
6847
    repo.snapshot_status("status").unwrap();
6848
    write(root, "a.txt", b"1\n2\n3\n4\n5\n");
6849
    repo.commit("third", &[]).unwrap();
6850
    assert!(
6851
        repo.clean_by_manifest().unwrap(),
6852
        "after an edit a status saw"
6853
    );
6854
}
6855
6856
#[test]
6857
fn a_conflicted_rebase_can_be_resolved_in_the_working_copy() {
6858
    hermetic();
6859
    let dir = tempfile::tempdir().unwrap();
6860
    let root = dir.path();
6861
    let mut repo = Repo::init(root).unwrap().with_home(root.join("home"));
6862
    write(root, "a.txt", b"1\n2\n");
6863
    let a = repo.commit("A", &[]).unwrap();
6864
    repo.bookmark_create("develop", Some(&[a])).unwrap();
6865
    write(root, "a.txt", b"1\nX\n");
6866
    let c = repo.commit("C: 2 to X", &[]).unwrap();
6867
    repo.bookmark_switch("develop", false).unwrap();
6868
    write(root, "a.txt", b"1\nY\n");
6869
    let d = repo.commit("D: 2 to Y", &[]).unwrap();
6870
    repo.bookmark_switch("main", false).unwrap();
6871
6872
    let err = repo.rebase(&c, &[d]).unwrap_err();
6873
    assert!(matches!(err, RepoError::Conflicted(_)), "{err}");
6874
    let r = repo.rebase_into_working_copy(&c, &[d]).unwrap();
6875
    assert!(r.changed && r.checked_out);
6876
    let snap = repo.snapshot_status("status").unwrap();
6877
    assert!(
6878
        snap.base_snapshot.is_conflicted(),
6879
        "the conflict is in the working copy"
6880
    );
6881
    let text = fs::read_to_string(root.join("a.txt")).unwrap();
6882
    assert!(text.contains('X') && text.contains('Y'), "{text}");
6883
6884
    write(root, "a.txt", b"1\nXY\n");
6885
    repo.commit("Resolve", &[]).unwrap();
6886
    let st = repo.load_state(&repo.bookmark_heads().unwrap()).unwrap();
6887
    assert!(st.contains(&c) && st.contains(&d));
6888
    let files = st.materialize().files;
6889
    assert!(!files["a.txt"].is_conflicted());
6890
    assert!(
6891
        matches!(&files["a.txt"].content, FileContent::Text { bytes, .. } if bytes == b"1\nXY\n")
6892
    );
6893
6894
    // A change the current bookmark does not hold is refused.
6895
    repo.bookmark_switch("develop", false).unwrap();
6896
    write(root, "b.txt", b"b\n");
6897
    let e = repo.commit("E", &[]).unwrap();
6898
    repo.bookmark_switch("main", false).unwrap();
6899
    let err = repo.rebase_into_working_copy(&e, &[a]).unwrap_err();
6900
    assert!(
6901
        err.to_string().contains("not on the current bookmark"),
6902
        "{err}"
6903
    );
6904
}
6905
6906
#[test]
6907
fn an_ignore_rule_drops_an_added_file_but_not_a_tracked_one() {
6908
    hermetic();
6909
    let dir = tempfile::tempdir().unwrap();
6910
    let root = dir.path();
6911
    let repo = Repo::init(root).unwrap();
6912
    write(root, "a.txt", b"a\n");
6913
    write(root, "kept.log", b"tracked\n");
6914
    repo.commit("first", &[]).unwrap();
6915
    write(root, "build.log", b"made\n");
6916
    let snap = repo.snapshot_status("status").unwrap();
6917
    assert!(snap.statuses.iter().any(|s| s.path == "build.log"));
6918
    // A rule written afterwards leaves the added file out again, while the
6919
    // committed one stays tracked.
6920
    write(root, ".gitignore", b"*.log\n");
6921
    let snap = repo.snapshot_status("status").unwrap();
6922
    let paths: Vec<&str> = snap.statuses.iter().map(|s| s.path.as_str()).collect();
6923
    assert_eq!(paths, vec![".gitignore"], "{paths:?}");
6924
    write(root, "kept.log", b"tracked, edited\n");
6925
    let snap = repo.snapshot_status("status").unwrap();
6926
    assert!(snap.statuses.iter().any(|s| s.path == "kept.log"));
6927
}
6928
6929
#[test]
6930
fn shed_graphs_come_back_the_same() {
6931
    hermetic();
6932
    let dir = tempfile::tempdir().unwrap();
6933
    let root = dir.path();
6934
    let repo = Repo::init(root).unwrap();
6935
    write(root, "a.txt", b"1\n2\n3\n");
6936
    write(root, "b.txt", b"x\n");
6937
    repo.commit("first", &[]).unwrap();
6938
    write(root, "a.txt", b"1\ntwo\n3\n4\n");
6939
    repo.commit("second", &[]).unwrap();
6940
    let heads = repo.bookmark_heads().unwrap();
6941
    let mut st = repo.load_state_history(&heads).unwrap();
6942
    let view = st.tree().view();
6943
    let nodes: Vec<NodeId> = ["a.txt", "b.txt"]
6944
        .iter()
6945
        .map(|p| view.entries[*p].node)
6946
        .collect();
6947
    repo.load_graphs_of(&mut st, &nodes).unwrap();
6948
    let before: Vec<Vec<u8>> = nodes.iter().map(|n| st.render_file(n).0).collect();
6949
    assert_eq!(st.built_count(), 2);
6950
    let shed = st.shed_graphs(|b| repo.store_blob(b)).unwrap();
6951
    assert_eq!((shed, st.built_count()), (2, 0));
6952
    // A later change applies on top of the shed history.
6953
    write(root, "a.txt", b"1\ntwo\n3\n4\n5\n");
6954
    let h3 = repo.commit("third", &[]).unwrap();
6955
    let (skeleton, texts) = repo.store().get_change_lazy(&h3).unwrap();
6956
    st.add_known(h3, skeleton, texts);
6957
    repo.load_graphs_of(&mut st, &nodes).unwrap();
6958
    let after: Vec<Vec<u8>> = nodes.iter().map(|n| st.render_file(n).0).collect();
6959
    assert_eq!(after[1], before[1]);
6960
    assert_eq!(after[0], b"1\ntwo\n3\n4\n5\n");
6961
}
6962
6963
#[test]
6964
fn many_edited_files_diff_in_parallel() {
6965
    // Enough edited files that the builder diffs them in parallel; the
6966
    // commit must hold exactly what is on disk, and a second snapshot
6967
    // must find nothing left to commit.
6968
    hermetic();
6969
    let dir = tempfile::tempdir().unwrap();
6970
    let root = dir.path();
6971
    let repo = Repo::init(root).unwrap();
6972
    let text = |i: usize, round: usize| {
6973
        let mut s = String::new();
6974
        for line in 0..50 {
6975
            if round > 0 && line % 7 == i % 7 {
6976
                s.push_str(&format!("edited {round} {i} {line}\n"));
6977
            } else {
6978
                s.push_str(&format!("file {i} line {line}\n"));
6979
            }
6980
        }
6981
        if round > 0 && i.is_multiple_of(3) {
6982
            s.push_str("appended\n");
6983
        }
6984
        s
6985
    };
6986
    for i in 0..40 {
6987
        write(root, &format!("d/f{i}.txt"), text(i, 0).as_bytes());
6988
    }
6989
    repo.commit("first", &[]).unwrap();
6990
    for i in 0..40 {
6991
        write(root, &format!("d/f{i}.txt"), text(i, 1).as_bytes());
6992
    }
6993
    let h = repo.commit("edit every file", &[]).unwrap();
6994
    let snap = repo.load_state(&[h]).unwrap().materialize();
6995
    for i in 0..40 {
6996
        let want = text(i, 1);
6997
        assert!(
6998
            matches!(&snap.files[&format!("d/f{i}.txt")].content, FileContent::Text { bytes, .. } if bytes == want.as_bytes()),
6999
            "d/f{i}.txt as committed"
7000
        );
7001
    }
7002
    assert!(
7003
        repo.commit("nothing", &[]).is_err(),
7004
        "nothing left to commit"
7005
    );
7006
}
7007
7008
/// oxygen#56: after a fetch, how a bookmark stands against its remote copy
7009
/// is known (fetch printed "up to date" while main was behind), a change
7010
/// only fetched resolves and says where it is, and a checkout whose only
7011
/// remote is not `origin` uses that one.
7012
#[test]
7013
fn a_fetched_change_shows_as_behind_and_resolves() {
7014
    hermetic();
7015
    let dir = tempfile::tempdir().unwrap();
7016
    let root = dir.path();
7017
    let origin = Repo::init(&root.join("origin")).unwrap();
7018
    drop(origin);
7019
    let url = root.join("origin").to_string_lossy().to_string();
7020
    let a = Repo::clone(&url, &root.join("a"))
7021
        .unwrap()
7022
        .with_home(root.join("home-a"));
7023
    write(&root.join("a"), "f.txt", b"one\n");
7024
    a.commit("one", &[]).unwrap();
7025
    a.push("origin", false).unwrap();
7026
    let b = Repo::clone(&url, &root.join("b"))
7027
        .unwrap()
7028
        .with_home(root.join("home-b"));
7029
    assert_eq!(b.tracking("origin", "main").unwrap(), Some((0, 0)));
7030
7031
    write(&root.join("a"), "f.txt", b"one\ntwo\n");
7032
    let h2 = a.commit("two", &[]).unwrap();
7033
    a.push("origin", false).unwrap();
7034
    b.fetch("origin").unwrap();
7035
    // Fetched, not pulled: one behind, the change found and placed.
7036
    assert_eq!(b.tracking("origin", "main").unwrap(), Some((0, 1)));
7037
    assert_eq!(b.tracking("origin", "nope").unwrap(), None);
7038
    assert_eq!(
7039
        b.resolve_change(&format!("#{}", &h2.to_hex()[..12]))
7040
            .unwrap(),
7041
        h2
7042
    );
7043
    assert_eq!(
7044
        b.remote_only_location(&h2).unwrap().as_deref(),
7045
        Some("origin/main")
7046
    );
7047
    // Fetching again changes nothing: still behind, which is what the
7048
    // CLI now says rather than "up to date".
7049
    b.fetch("origin").unwrap();
7050
    assert_eq!(b.tracking("origin", "main").unwrap(), Some((0, 1)));
7051
    b.pull("origin").unwrap();
7052
    assert_eq!(b.tracking("origin", "main").unwrap(), Some((0, 0)));
7053
    assert_eq!(b.remote_only_location(&h2).unwrap(), None);
7054
7055
    // One remote, not called origin: it is the default.
7056
    let mut c = Repo::init(&root.join("c")).unwrap();
7057
    assert_eq!(c.default_remote(), "origin");
7058
    c.config.set("remote.earth.url", &url).unwrap();
7059
    assert_eq!(c.default_remote(), "earth");
7060
    c.config.set("remote.origin.url", &url).unwrap();
7061
    assert_eq!(c.default_remote(), "origin");
7062
}
7063
7064
/// oxygen#57: a clone from a relative local path records the remote as an
7065
/// absolute path, so fetch still finds it from inside the clone.
7066
#[test]
7067
fn a_clone_from_a_relative_path_records_it_absolute() {
7068
    hermetic();
7069
    let dir = tempfile::tempdir().unwrap();
7070
    let root = dir.path();
7071
    Repo::init(&root.join("origin")).unwrap();
7072
    let rel = crate::protocol::stored_url("relative/repo");
7073
    assert!(std::path::Path::new(&rel).is_absolute(), "{rel}");
7074
    assert_eq!(
7075
        crate::protocol::stored_url("https://hub.example/o/n"),
7076
        "https://hub.example/o/n"
7077
    );
7078
    assert!(crate::protocol::stored_url("file://x").starts_with("file:///"));
7079
    assert!(crate::protocol::stored_url("dir://x").starts_with("dir:///"));
7080
    // A bucket is kept as written: it is not a path.
7081
    assert_eq!(
7082
        crate::protocol::stored_url("s3://bucket/prefix?profile=p"),
7083
        "s3://bucket/prefix?profile=p"
7084
    );
7085
    let url = root.join("origin").to_string_lossy().to_string();
7086
    let b = Repo::clone(&url, &root.join("b")).unwrap();
7087
    assert_eq!(b.config.remotes["origin"], url);
7088
    b.fetch("origin").unwrap();
7089
}
7090
7091
/// oxygen#60 and #61: a workspace added on a bookmark is on that bookmark,
7092
/// and gets its subrepos at their pins from this workspace's copies, with
7093
/// their remotes pointing where the subrepos come from.
7094
#[test]
7095
fn a_workspace_added_on_a_bookmark_is_on_it_with_its_subrepos() {
7096
    hermetic();
7097
    let dir = tempfile::tempdir().unwrap();
7098
    let root = dir.path();
7099
    Repo::init(&root.join("lib-origin")).unwrap();
7100
    let lib_url = root.join("lib-origin").to_string_lossy().to_string();
7101
    let lib = Repo::clone(&lib_url, &root.join("lib"))
7102
        .unwrap()
7103
        .with_home(root.join("home"));
7104
    write(&root.join("lib"), "lib.txt", b"v1\n");
7105
    let l1 = lib.commit("lib v1", &[]).unwrap();
7106
    assert!(lib.push("origin", false).unwrap()[0].ok);
7107
7108
    let app_dir = root.join("app");
7109
    let app = Repo::init(&app_dir).unwrap().with_home(root.join("home"));
7110
    write(&app_dir, "main.txt", b"app\n");
7111
    app.submodule_add(&lib_url, "libs/lib", None).unwrap();
7112
    app.commit("app with lib", &[]).unwrap();
7113
    // A second bookmark, and the main workspace on another.
7114
    app.bookmark_create("develop", None).unwrap();
7115
    app.bookmark_create("feature", None).unwrap();
7116
    let mut app = app;
7117
    app.bookmark_switch("feature", false).unwrap();
7118
    assert_eq!(app.config.bookmark, "feature");
7119
7120
    // The library's origin goes away: the subrepo must come from here.
7121
    std::fs::rename(root.join("lib-origin"), root.join("lib-origin-gone")).unwrap();
7122
    let heads = app.resolve_heads("develop").unwrap();
7123
    let ws = app
7124
        .workspace_add_on(&root.join("ws"), Some(&heads), Some("develop"))
7125
        .unwrap();
7126
    assert_eq!(
7127
        ws.config.bookmark, "develop",
7128
        "the new workspace is on develop"
7129
    );
7130
    assert_eq!(
7131
        app.config.bookmark, "feature",
7132
        "and this one stays on its own"
7133
    );
7134
    let sub = Repo::open(&root.join("ws/libs/lib")).unwrap();
7135
    assert_eq!(
7136
        sub.config.remotes["origin"], lib_url,
7137
        "its origin is the subrepo's URL"
7138
    );
7139
    assert_eq!(sub.bookmark_heads().unwrap(), vec![l1], "at its pin");
7140
    assert_eq!(
7141
        std::fs::read(root.join("ws/libs/lib/lib.txt")).unwrap(),
7142
        b"v1\n"
7143
    );
7144
}
7145
7146
/// Revsets (docs/revset_query_language.md): symbols, relations, set
7147
/// operators and the predicates, over a small graph with two heads and
7148
/// a rename.
7149
#[test]
7150
fn revsets_select_changes_by_relation_author_text_date_and_path() {
7151
    hermetic();
7152
    let dir = tempfile::tempdir().unwrap();
7153
    let root = dir.path();
7154
    let mut repo = Repo::init(root).unwrap().with_home(root.join("home"));
7155
    repo.create_identity("Ada", "[email protected]", IdentityScope::User)
7156
        .unwrap();
7157
    write(root, "src/a.rs", b"one\n");
7158
    let a = repo.commit("first: add a", &[]).unwrap();
7159
    write(root, "src/a.rs", b"one\ntwo\n");
7160
    let b = repo.commit("second: grow a", &[]).unwrap();
7161
    // A second head, independent of b: a new file on top of a.
7162
    repo.checkout(&[a], false, "checkout a").unwrap();
7163
    write(root, "docs/notes.md", b"notes\n");
7164
    let c = repo.commit("third: notes", &[]).unwrap();
7165
    // Back to both heads, then rename a.rs: the node keeps its identity.
7166
    repo.checkout(&repo.bookmark_heads().unwrap(), false, "checkout main")
7167
        .unwrap();
7168
    fs::remove_file(root.join("src/a.rs")).unwrap();
7169
    write(root, "src/z.rs", b"one\ntwo\n");
7170
    let d = repo.commit("fourth: rename a to z", &[]).unwrap();
7171
    let wc = repo.working_copy().unwrap().0;
7172
    // A saved revset is checked when set.
7173
    repo.set_user_config("revset.mine", "author(me) & ::main")
7174
        .unwrap();
7175
    assert!(repo.set_user_config("revset.bad", "a &").is_err());
7176
    let set = |src: &str| -> Vec<ChangeHash> {
7177
        let mut v = repo.revset(src).unwrap().hashes;
7178
        v.sort();
7179
        v
7180
    };
7181
    let sorted = |hs: &[ChangeHash]| -> Vec<ChangeHash> {
7182
        let mut v = hs.to_vec();
7183
        v.sort();
7184
        v
7185
    };
7186
7187
    // Changes commute: a new file depends on nothing and the rename on the
7188
    // file's creation, so the graph is a, b->a, d->a, c, and the working
7189
    // copy on the three heads b, c, d.
7190
    let heads = sorted(&repo.bookmark_heads().unwrap());
7191
    let meta = |h: &ChangeHash| repo.store().get_change_meta(h).unwrap();
7192
    assert!(heads.contains(&d) && heads.contains(&c));
7193
    // Symbols and closures.
7194
    assert_eq!(set("main"), heads);
7195
    assert_eq!(set("::main"), sorted(&[a, b, c, d]));
7196
    assert_eq!(set("@"), vec![wc]);
7197
    assert_eq!(set("::@"), sorted(&[a, b, c, d, wc]));
7198
    assert_eq!(set(&format!("::#{}", b.short(12))), sorted(&[a, b]));
7199
    assert_eq!(set(&format!("#{}::", a.short(12))), sorted(&[a, b, d, wc]));
7200
    assert_eq!(
7201
        set(&format!("#{}::#{}", a.short(12), b.short(12))),
7202
        sorted(&[a, b])
7203
    );
7204
    // Ranges: what main has beyond b, and `..` forms.
7205
    assert_eq!(set(&format!("#{}..main", b.short(12))), sorted(&[c, d]));
7206
    assert_eq!(set(&format!("#{}..", c.short(12))), sorted(&[a, b, d, wc]));
7207
    assert_eq!(set("..main"), sorted(&[a, b, c, d]));
7208
    // Operators and precedence: ~ binds tighter than &, & than |.
7209
    assert_eq!(
7210
        set(&format!("::main ~ #{}", d.short(12))),
7211
        sorted(&[a, b, c])
7212
    );
7213
    assert_eq!(
7214
        set(&format!("::main & #{} | #{}", b.short(12), c.short(12))),
7215
        sorted(&[b, c])
7216
    );
7217
    assert_eq!(set("all() ~ ::main"), vec![wc]);
7218
    // Relations.
7219
    let mut head_deps: Vec<ChangeHash> = heads.iter().flat_map(|h| meta(h).deps).collect();
7220
    head_deps.sort();
7221
    head_deps.dedup();
7222
    assert_eq!(set("deps(main)"), head_deps);
7223
    let on_a: Vec<ChangeHash> = [b, c, d]
7224
        .into_iter()
7225
        .filter(|h| meta(h).deps.contains(&a))
7226
        .collect();
7227
    assert_eq!(set(&format!("dependents(#{})", a.short(12))), sorted(&on_a));
7228
    assert_eq!(set("heads(::main)"), heads);
7229
    assert_eq!(set("roots(::main)"), sorted(&[a, c]));
7230
    assert_eq!(
7231
        set(&format!(
7232
            "heads(#{} | #{} | #{})",
7233
            a.short(12),
7234
            b.short(12),
7235
            c.short(12)
7236
        )),
7237
        sorted(&[b, c])
7238
    );
7239
    assert_eq!(set("latest(::main, 1)"), vec![d]);
7240
    assert_eq!(set("kind(working-copy)"), vec![wc]);
7241
    assert_eq!(set("none()"), vec![]);
7242
    // Predicates: author by name, email, key prefix and `me`.
7243
    let key = repo.config.author_key.unwrap();
7244
    assert_eq!(set("author(ada) & ::main"), sorted(&[a, b, c, d]));
7245
    assert_eq!(set("author(\"[email protected]\") & ::main").len(), 4);
7246
    assert_eq!(set(&format!("author({}) & ::main", key.short(12))).len(), 4);
7247
    assert_eq!(set("author(me) & ::main").len(), 4);
7248
    assert_eq!(set("author(nobody)"), vec![]);
7249
    assert_eq!(set("description(notes)"), vec![c]);
7250
    assert_eq!(set("description(\"rename a\")"), vec![d]);
7251
    assert_eq!(set("date(-1h..) & ::main").len(), 4);
7252
    assert_eq!(set("date(..2000-01-01)"), vec![]);
7253
    // touches follows the node through the rename, in the current state.
7254
    assert_eq!(set("touches(\"src/z.rs\")"), sorted(&[a, b, d]));
7255
    assert_eq!(set("touches(\"src/**\") & ::main"), sorted(&[a, b, d]));
7256
    assert_eq!(set("touches(\"docs/*\")"), vec![c]);
7257
    assert_eq!(set("touches(\"nothing/*\")"), vec![]);
7258
    // Newest first in the result order.
7259
    assert_eq!(repo.revset("::main").unwrap().hashes[0], d);
7260
    // The saved revset, and errors that say what is wrong.
7261
    assert_eq!(set("mine()").len(), 4);
7262
    let e = repo.revset("nosuch()").unwrap_err().to_string();
7263
    assert!(e.contains("unknown function nosuch()"), "{e}");
7264
    let e = repo.revset("main &").unwrap_err().to_string();
7265
    assert!(e.contains("at character"), "{e}");
7266
    let e = repo.revset("zzzz").unwrap_err().to_string();
7267
    assert!(e.contains("no change matches"), "{e}");
7268
    let e = repo
7269
        .revset_with_budget("::main", std::time::Duration::ZERO)
7270
        .unwrap_err()
7271
        .to_string();
7272
    assert!(e.contains("budget"), "{e}");
7273
    // The log entries carry the bookmark's heads and the working copy.
7274
    let entries = repo.log_revset("::@").unwrap();
7275
    assert!(entries[0].is_working_copy && entries.iter().any(|e| e.is_head && e.hash == d));
7276
    // Trust predicates (§2.4): nothing is signed yet (core.sign = seal, no
7277
    // push); then a signed change, a tag, and a revocation.
7278
    assert_eq!(set("unsigned() & ::main"), sorted(&[a, b, c, d]));
7279
    assert_eq!(set("signed_by(me)"), vec![]);
7280
    repo.sign_change(&d).unwrap();
7281
    assert_eq!(set("signed_by(me)"), vec![d]);
7282
    assert_eq!(set("signed_by([email protected])"), vec![d]);
7283
    assert_eq!(set(&format!("signed_by({})", key.short(12))), vec![d]);
7284
    assert_eq!(set("unsigned() & ::main"), sorted(&[a, b, c]));
7285
    assert_eq!(set("delegated()"), vec![]);
7286
    assert_eq!(set("revoked()"), vec![]);
7287
    assert_eq!(set("attested(tag)"), vec![]);
7288
    repo.tag_create("v1", &[b], "first").unwrap();
7289
    assert_eq!(set("attested(tag)"), sorted(&[a, b]));
7290
    assert_eq!(set("attested(tag) & unsigned()"), sorted(&[a, b]));
7291
    assert_eq!(set("attested(receipt)"), vec![]);
7292
    assert_eq!(set("built(test)"), vec![]);
7293
    let e = repo.revset("attested(seal)").unwrap_err().to_string();
7294
    assert!(e.contains("tag, receipt or ref"), "{e}");
7295
    repo.revoke_identity(&key, "test").unwrap();
7296
    assert_eq!(set("revoked()"), vec![d]);
7297
    assert_eq!(set("signed_by(me) ~ revoked()"), vec![]);
7298
}
7299
7300
#[test]
7301
fn a_rotation_is_recorded_wherever_the_old_key_was_named() {
7302
    let dir = tempfile::tempdir().unwrap();
7303
    let root = dir.path();
7304
    let home = root.join("home");
7305
    // Ada's identity lives in the user file; repository `a` pins the same
7306
    // key in its own file, repository `b` names none.
7307
    let mut a = Repo::init(&root.join("a")).unwrap().with_home(&home);
7308
    let (key, _) = a
7309
        .create_identity("Ada", "[email protected]", IdentityScope::User)
7310
        .unwrap();
7311
    a.config.set("author.key", &key.to_hex()).unwrap();
7312
    a.save_config().unwrap();
7313
    let agent = SecretKey::generate().identity("Agent", "[email protected]", 1);
7314
    let r = a
7315
        .delegate_add(agent.clone(), crate::identity::Scope::CHANGES, None)
7316
        .unwrap();
7317
    assert_eq!(
7318
        read_config_file(&home.join("config.toml")).unwrap()["author.key"],
7319
        r.new.to_hex(),
7320
        "the user file follows"
7321
    );
7322
    assert_eq!(
7323
        read_config_file(&root.join("a/.oxy/config")).unwrap()["author.key"],
7324
        r.new.to_hex(),
7325
        "the pinning repository follows"
7326
    );
7327
    let b = Repo::init(&root.join("b")).unwrap().with_home(&home);
7328
    assert_eq!(
7329
        b.config.author_key,
7330
        Some(r.new),
7331
        "a checkout without a pin follows the user file"
7332
    );
7333
    // A repository-scoped identity leaves the user file alone.
7334
    let other_home = root.join("home2");
7335
    let mut c = Repo::init(&root.join("c")).unwrap().with_home(&other_home);
7336
    let (ck, _) = c
7337
        .create_identity("Cy", "[email protected]", IdentityScope::Repo)
7338
        .unwrap();
7339
    assert!(!other_home.join("config.toml").exists());
7340
    let r2 = c.rotate_identity().unwrap();
7341
    assert_ne!(r2.new, ck);
7342
    assert_eq!(
7343
        read_config_file(&root.join("c/.oxy/config")).unwrap()["author.key"],
7344
        r2.new.to_hex()
7345
    );
7346
    assert!(
7347
        !other_home.join("config.toml").exists(),
7348
        "a repository-scoped identity stays repository-scoped"
7349
    );
7350
    // Several delegates in one rotation; a repeat is refused.
7351
    let (d1, d2) = (
7352
        SecretKey::generate().identity("D1", "d1@x", 1),
7353
        SecretKey::generate().identity("D2", "d2@x", 1),
7354
    );
7355
    let r3 = c
7356
        .delegate_add_many(vec![d1.clone(), d2], crate::identity::Scope::CHANGES, None)
7357
        .unwrap();
7358
    assert_eq!(r3.identity.delegates.len(), 2);
7359
    assert!(c
7360
        .delegate_add(d1, crate::identity::Scope::CHANGES, None)
7361
        .is_err());
7362
}
7363
7364
/// Two unrelated histories that both add the same file, joined by two
7365
/// independent merges on two branches, then those branches merged: Git
7366
/// merges identical additions cleanly, and the import must too (#71,
7367
/// found in VS Code's history).
7368
#[test]
7369
fn git_import_joins_unrelated_histories_that_add_the_same_file() {
7370
    // Batches of one: every merge renders apart from the state, where a
7371
    // file whose graph the state had built came out empty (#71).
7372
    crate::repo::git::set_merge_batch_for_tests(Some(1));
7373
    hermetic();
7374
    if std::process::Command::new("git")
7375
        .arg("--version")
7376
        .output()
7377
        .is_err()
7378
    {
7379
        eprintln!("git not installed; skipping");
7380
        return;
7381
    }
7382
    let dir = tempfile::tempdir().unwrap();
7383
    let root = dir.path();
7384
    let g = root.join("src.git");
7385
    fs::create_dir_all(&g).unwrap();
7386
    let git = |args: &[&str]| -> String {
7387
        let out = std::process::Command::new("git")
7388
            .arg("-C")
7389
            .arg(&g)
7390
            .args([
7391
                "-c",
7392
                "user.name=Grace",
7393
                "-c",
7394
                "[email protected]",
7395
                "-c",
7396
                "commit.gpgsign=false",
7397
            ])
7398
            .args(args)
7399
            .output()
7400
            .unwrap();
7401
        assert!(
7402
            out.status.success(),
7403
            "git {args:?}: {}",
7404
            String::from_utf8_lossy(&out.stderr)
7405
        );
7406
        String::from_utf8_lossy(&out.stdout).trim().to_string()
7407
    };
7408
    let text = b"/* header */\nconst a = 1;\nconst b = 2;\n";
7409
    // History A: main.
7410
    git(&["init", "-q", "-b", "main"]);
7411
    write(&g, "gulpfile.js", text);
7412
    write(&g, "a.txt", b"a\n");
7413
    git(&["add", "."]);
7414
    git(&["commit", "-q", "-m", "A root"]);
7415
    // History B: an unrelated root adding the same file, identical.
7416
    git(&["checkout", "-q", "--orphan", "fork"]);
7417
    git(&["rm", "-q", "-r", "--cached", "."]);
7418
    for f in ["gulpfile.js", "a.txt"] {
7419
        let _ = fs::remove_file(g.join(f));
7420
    }
7421
    write(&g, "gulpfile.js", text);
7422
    write(&g, "b.txt", b"b\n");
7423
    git(&["add", "."]);
7424
    git(&["commit", "-q", "-m", "B root"]);
7425
    // Two branches from main, each joining B on its own.
7426
    git(&["checkout", "-q", "-b", "one", "main"]);
7427
    git(&[
7428
        "merge",
7429
        "-q",
7430
        "--no-ff",
7431
        "--allow-unrelated-histories",
7432
        "-m",
7433
        "join on one",
7434
        "fork",
7435
    ]);
7436
    git(&["checkout", "-q", "-b", "two", "main"]);
7437
    write(&g, "a.txt", b"a\ntwo\n");
7438
    git(&["commit", "-q", "-am", "work on two"]);
7439
    git(&[
7440
        "merge",
7441
        "-q",
7442
        "--no-ff",
7443
        "--allow-unrelated-histories",
7444
        "-m",
7445
        "join on two",
7446
        "fork",
7447
    ]);
7448
    // Then the two joins meet, and the file is reformatted after.
7449
    git(&["checkout", "-q", "main"]);
7450
    git(&["merge", "-q", "--no-ff", "-m", "merge one", "one"]);
7451
    git(&["merge", "-q", "--no-ff", "-m", "merge two", "two"]);
7452
    write(
7453
        &g,
7454
        "gulpfile.js",
7455
        b"/* header */\nconst a = 1;\nconst b = 3;\n",
7456
    );
7457
    git(&["commit", "-q", "-am", "after"]);
7458
7459
    let dest = root.join("dest");
7460
    let repo = Repo::init(&dest).unwrap().with_home(root.join("home"));
7461
    repo.import_git(&g, "main").unwrap();
7462
    let v = repo.verify_git_import(&g, "main").unwrap();
7463
    assert!(v.mismatches.is_empty(), "{:?}", v.mismatches);
7464
    assert_eq!(
7465
        fs::read(dest.join("gulpfile.js")).unwrap(),
7466
        b"/* header */\nconst a = 1;\nconst b = 3;\n"
7467
    );
7468
}
7469
7470
/// As above, but the two joins keep different copies (each branch had a
7471
/// different version when it joined), and later work edits each copy:
7472
/// the shape of VS Code's c67ef57cda90 (#71).
7473
#[test]
7474
fn git_import_joins_where_each_join_kept_a_different_copy() {
7475
    // Batches of one: every merge renders apart from the state, where a
7476
    // file whose graph the state had built came out empty (#71).
7477
    crate::repo::git::set_merge_batch_for_tests(Some(1));
7478
    hermetic();
7479
    if std::process::Command::new("git")
7480
        .arg("--version")
7481
        .output()
7482
        .is_err()
7483
    {
7484
        eprintln!("git not installed; skipping");
7485
        return;
7486
    }
7487
    let dir = tempfile::tempdir().unwrap();
7488
    let root = dir.path();
7489
    let g = root.join("src.git");
7490
    fs::create_dir_all(&g).unwrap();
7491
    let run = |args: &[&str]| {
7492
        std::process::Command::new("git")
7493
            .arg("-C")
7494
            .arg(&g)
7495
            .args([
7496
                "-c",
7497
                "user.name=Grace",
7498
                "-c",
7499
                "[email protected]",
7500
                "-c",
7501
                "commit.gpgsign=false",
7502
            ])
7503
            .args(args)
7504
            .output()
7505
            .unwrap()
7506
    };
7507
    let git = |args: &[&str]| -> String {
7508
        let out = run(args);
7509
        assert!(
7510
            out.status.success(),
7511
            "git {args:?}: {}",
7512
            String::from_utf8_lossy(&out.stderr)
7513
        );
7514
        String::from_utf8_lossy(&out.stdout).trim().to_string()
7515
    };
7516
    git(&["init", "-q", "-b", "main"]);
7517
    write(
7518
        &g,
7519
        "gulpfile.js",
7520
        b"/* header */\nconst a = 1;\nconst b = 2;\n",
7521
    );
7522
    git(&["add", "."]);
7523
    git(&["commit", "-q", "-m", "A root"]);
7524
    write(
7525
        &g,
7526
        "gulpfile.js",
7527
        b"/* header */\nconst a = 1;\n\nconst b = 2;\n",
7528
    );
7529
    git(&["commit", "-q", "-am", "whitespace"]);
7530
    git(&["checkout", "-q", "--orphan", "fork"]);
7531
    git(&["rm", "-q", "-r", "--cached", "."]);
7532
    let _ = fs::remove_file(g.join("gulpfile.js"));
7533
    write(
7534
        &g,
7535
        "gulpfile.js",
7536
        b"/* header */\nconst a = 1;\nconst b = 2;\nconst c = 3;\n",
7537
    );
7538
    git(&["add", "."]);
7539
    git(&["commit", "-q", "-m", "B root"]);
7540
    // Branch one joins B keeping main's copy; branch two keeps B's.
7541
    for (branch, keep) in [("one", "ours"), ("two", "theirs")] {
7542
        git(&["checkout", "-q", "-b", branch, "main"]);
7543
        let _ = run(&[
7544
            "merge",
7545
            "-q",
7546
            "--no-ff",
7547
            "--allow-unrelated-histories",
7548
            "-m",
7549
            "join",
7550
            "fork",
7551
        ]);
7552
        git(&["checkout", &format!("--{keep}"), "gulpfile.js"]);
7553
        git(&["add", "gulpfile.js"]);
7554
        git(&["commit", "-q", "-m", &format!("join on {branch}")]);
7555
    }
7556
    // Each branch then edits its copy.
7557
    git(&["checkout", "-q", "one"]);
7558
    write(
7559
        &g,
7560
        "gulpfile.js",
7561
        b"/* header */\nconst a = 1;\n\nconst b = 2;\n// tslint\n",
7562
    );
7563
    git(&["commit", "-q", "-am", "tslint on one"]);
7564
    git(&["checkout", "-q", "two"]);
7565
    write(
7566
        &g,
7567
        "gulpfile.js",
7568
        b"/* header */\nconst a = 1;\nconst b = 2;\nconst c = 3;\n// fmt\n",
7569
    );
7570
    write(&g, "extra.txt", b"x\n");
7571
    write(&g, "more.txt", b"m\n");
7572
    git(&["add", "."]);
7573
    git(&["commit", "-q", "-am", "fmt on two"]);
7574
    // They meet: resolved by hand.
7575
    git(&["checkout", "-q", "one"]);
7576
    let _ = run(&["merge", "-q", "--no-ff", "-m", "merge two", "two"]);
7577
    write(
7578
        &g,
7579
        "gulpfile.js",
7580
        b"/* header */\nconst a = 1;\nconst b = 2;\nconst c = 3;\n// tslint\n// fmt\n",
7581
    );
7582
    git(&["add", "gulpfile.js"]);
7583
    git(&["commit", "-q", "-m", "merge two into one"]);
7584
7585
    let dest = root.join("dest");
7586
    let repo = Repo::init(&dest).unwrap().with_home(root.join("home"));
7587
    repo.import_git(&g, "one").unwrap();
7588
    let v = repo.verify_git_import(&g, "one").unwrap();
7589
    assert!(v.mismatches.is_empty(), "{:?}", v.mismatches);
7590
}
7591
7592
/// oxygen#68: on a store that is not this disk's directory, the operation
7593
/// head is the store's reference record, moved by compare-and-swap. Two
7594
/// handles recording from the same head both get through, merged; a swap
7595
/// from a stale version is refused; a second repository cannot start on a
7596
/// store that already holds one.
7597
#[test]
7598
fn over_a_store_the_operation_head_moves_by_compare_and_swap() {
7599
    use crate::strata::{MemoryStore, Store as _};
7600
    let backend = std::sync::Arc::new(MemoryStore::new());
7601
    crate::store::TEST_BACKEND.with(|t| *t.borrow_mut() = Some(backend.clone()));
7602
    let dir = tempfile::tempdir().unwrap();
7603
    let a = Repo::init(dir.path()).unwrap();
7604
    assert!(
7605
        !dir.path().join(".oxy/ops/head").exists(),
7606
        "the head is not a file"
7607
    );
7608
    let (h0, op0) = a.head_op().unwrap();
7609
    let record = backend
7610
        .read_ref(HEAD_RECORD)
7611
        .unwrap()
7612
        .expect("the head is the store's record");
7613
    assert_eq!(String::from_utf8(record.0).unwrap(), h0.to_hex());
7614
7615
    let b = Repo::open(dir.path()).unwrap();
7616
    let state = a.store.put_state(&StateObject::new(vec![])).unwrap();
7617
    let mut va = op0.view.clone();
7618
    va.bookmarks.insert("from-a".into(), state);
7619
    let mut vb = op0.view.clone();
7620
    vb.bookmarks.insert("from-b".into(), state);
7621
    let rb = b.record_op(&[h0], "bookmark from-b", vb).unwrap();
7622
    assert_eq!(b.head_ref().unwrap(), rb);
7623
    // a recorded from h0 too: the head moved, so the two are merged.
7624
    let ra = a.record_op(&[h0], "bookmark from-a", va).unwrap();
7625
    let (head, op) = Repo::open(dir.path()).unwrap().head_op().unwrap();
7626
    assert_eq!(head, ra);
7627
    assert!(
7628
        op.command.ends_with("(merged with a concurrent operation)"),
7629
        "{}",
7630
        op.command
7631
    );
7632
    assert_eq!(op.parents, vec![rb, op.parents[1]]);
7633
    assert!(op.view.bookmarks.contains_key("from-a") && op.view.bookmarks.contains_key("from-b"));
7634
7635
    // A swap from a version that is no longer current moves nothing.
7636
    let (h, v) = a.read_head().unwrap();
7637
    assert!(b.swap_head(&rb, v.as_ref()).unwrap());
7638
    assert!(!a.swap_head(&h, v.as_ref()).unwrap(), "stale");
7639
    a.refresh().unwrap();
7640
    assert_eq!(a.head_ref().unwrap(), rb);
7641
7642
    let other = tempfile::tempdir().unwrap();
7643
    let err = Repo::init(other.path())
7644
        .err()
7645
        .expect("the store already holds a log")
7646
        .to_string();
7647
    assert!(
7648
        err.contains("already holds a repository's operation log"),
7649
        "{err}"
7650
    );
7651
    crate::store::TEST_BACKEND.with(|t| *t.borrow_mut() = None);
7652
}
7653
7654
/// oxygen#68: a repository kept on a store (`storage.url`) holds its
7655
/// objects and operation head there, with `.oxy/cache` in front: it works
7656
/// as one on disk does, reopens, and survives losing its cache.
7657
#[test]
7658
fn a_repository_runs_on_a_store_with_a_cache_in_front() {
7659
    hermetic();
7660
    if std::env::var_os("OXY_STORE_BACKEND").is_some() {
7661
        return;
7662
    }
7663
    let dir = tempfile::tempdir().unwrap();
7664
    let (root, bucket) = (dir.path().join("work"), dir.path().join("bucket"));
7665
    let url = format!("dir://{}", bucket.display());
7666
    let repo = Repo::init_on(&root, [7; 16], Some(&url)).unwrap();
7667
    assert_eq!(repo.config.storage_url.as_deref(), Some(url.as_str()));
7668
    write(&root, "a.txt", b"one\n");
7669
    let h1 = repo.commit("First", &[]).unwrap();
7670
    write(&root, "a.txt", b"one\ntwo\n");
7671
    let h2 = repo.commit("Second", &[]).unwrap();
7672
    assert!(
7673
        !root.join(".oxy/ops/head").exists(),
7674
        "the head is in the store"
7675
    );
7676
    assert!(bucket.join("ops/head").is_file());
7677
    assert!(root.join(".oxy/cache").is_dir());
7678
    drop(repo);
7679
7680
    // Reopened, and again with no cache at all: everything comes from the store.
7681
    for drop_cache in [false, true] {
7682
        if drop_cache {
7683
            std::fs::remove_dir_all(root.join(".oxy/cache")).unwrap();
7684
        }
7685
        let repo = Repo::open(&root).unwrap();
7686
        let log: Vec<String> = repo
7687
            .op_log()
7688
            .unwrap()
7689
            .into_iter()
7690
            .map(|(_, op)| op.command)
7691
            .collect();
7692
        assert!(log.len() >= 3, "{log:?}");
7693
        assert_eq!(repo.store().get_change(&h1).unwrap().message, "First");
7694
        let heads = repo
7695
            .store()
7696
            .get_state(&repo.view().unwrap().bookmarks["main"])
7697
            .unwrap()
7698
            .heads;
7699
        assert_eq!(heads, vec![h2]);
7700
        assert_eq!(
7701
            repo.load_state(&heads).unwrap().materialize().files.len(),
7702
            1
7703
        );
7704
    }
7705
7706
    // A second repository cannot start on the same store.
7707
    let err = Repo::init_on(&dir.path().join("other"), [8; 16], Some(&url))
7708
        .err()
7709
        .unwrap()
7710
        .to_string();
7711
    assert!(
7712
        err.contains("already holds a repository's operation log"),
7713
        "{err}"
7714
    );
7715
    let err = Repo::init_on(&dir.path().join("third"), [9; 16], Some("nope://x"))
7716
        .err()
7717
        .unwrap()
7718
        .to_string();
7719
    assert!(err.contains("cannot open that kind of store"), "{err}");
7720
}
7721
7722
/// oxygen#75: the prompt's quick check agrees with status in a repository
7723
/// with a subrepo: clean after a commit, dirty when the subrepo moves to
7724
/// another state, clean again once that pin is committed. (It compared the
7725
/// subrepo's directory as if it were a file, so it was always dirty.)
7726
#[test]
7727
fn the_quick_dirty_check_compares_a_subrepo_by_its_pin() {
7728
    hermetic();
7729
    let dir = tempfile::tempdir().unwrap();
7730
    let root = dir.path();
7731
    let _lib_origin = Repo::init(&root.join("lib-origin")).unwrap();
7732
    let lib_url = root.join("lib-origin").to_string_lossy().to_string();
7733
    let lib = Repo::clone(&lib_url, &root.join("lib"))
7734
        .unwrap()
7735
        .with_home(root.join("home"));
7736
    write(&root.join("lib"), "lib.txt", b"v1\n");
7737
    lib.commit("lib v1", &[]).unwrap();
7738
    assert!(lib.push("origin", false).unwrap()[0].ok);
7739
    let app_dir = root.join("app");
7740
    let app = Repo::init(&app_dir).unwrap().with_home(root.join("home"));
7741
    write(&app_dir, "main.txt", b"app\n");
7742
    app.submodule_add(&lib_url, "libs/lib", None).unwrap();
7743
    app.commit("app with lib", &[]).unwrap();
7744
    // Out of the racy window, so the stat-only path decides.
7745
    std::thread::sleep(std::time::Duration::from_millis(2100));
7746
    let reopen = || Repo::open(&app_dir).unwrap();
7747
    assert_eq!(
7748
        reopen().quick_dirty().unwrap(),
7749
        Some(false),
7750
        "clean, as status says"
7751
    );
7752
    let nested = Repo::open(&app_dir.join("libs/lib")).unwrap();
7753
    write(&app_dir.join("libs/lib"), "lib.txt", b"v2\n");
7754
    nested.commit("lib v2", &[]).unwrap();
7755
    assert_eq!(
7756
        reopen().quick_dirty().unwrap(),
7757
        Some(true),
7758
        "the subrepo moved"
7759
    );
7760
    reopen().commit("pin lib v2", &[]).unwrap();
7761
    std::thread::sleep(std::time::Duration::from_millis(2100));
7762
    assert_eq!(
7763
        reopen().quick_dirty().unwrap(),
7764
        Some(false),
7765
        "the new pin is committed"
7766
    );
7767
}
7768
7769
#[test]
7770
fn a_module_entry_that_was_never_added_is_reported_as_unpinned() {
7771
    // oxygen#72: a .oxymodules section with no subrepo behind it.
7772
    hermetic();
7773
    let dir = tempfile::tempdir().unwrap();
7774
    let root = dir.path();
7775
    let _lib_origin = Repo::init(&root.join("lib-origin")).unwrap();
7776
    let lib_url = root.join("lib-origin").to_string_lossy().to_string();
7777
    let lib = Repo::clone(&lib_url, &root.join("lib"))
7778
        .unwrap()
7779
        .with_home(root.join("home"));
7780
    write(&root.join("lib"), "lib.txt", b"v1\n");
7781
    lib.commit("lib v1", &[]).unwrap();
7782
    assert!(lib.push("origin", false).unwrap()[0].ok);
7783
    let app_dir = root.join("app");
7784
    let app = Repo::init(&app_dir).unwrap().with_home(root.join("home"));
7785
    write(
7786
        &app_dir,
7787
        ".oxymodules",
7788
        format!("[libs/lib]\nurl = {lib_url}\n").as_bytes(),
7789
    );
7790
    let unpinned = app.unpinned_modules().unwrap();
7791
    assert_eq!(unpinned.len(), 1);
7792
    assert_eq!(unpinned[0].0, "libs/lib");
7793
    assert_eq!(unpinned[0].1.url, lib_url);
7794
    assert!(app.submodule_update(true, &[]).unwrap().is_empty());
7795
    app.submodule_add(&lib_url, "libs/lib", None).unwrap();
7796
    assert!(app.unpinned_modules().unwrap().is_empty(), "added now");
7797
}
7798
7799
#[test]
7800
fn the_bookmark_revset_function_names_only_bookmarks() {
7801
    // oxygen#73: bookmark(NAME) is a bookmark's heads, never a tag or prefix.
7802
    hermetic();
7803
    let dir = tempfile::tempdir().unwrap();
7804
    let repo = Repo::init(dir.path()).unwrap();
7805
    write(dir.path(), "a.txt", b"a\n");
7806
    let a = repo.commit("A", &[]).unwrap();
7807
    write(dir.path(), "b.txt", b"b\n");
7808
    let b = repo.commit("B", &[]).unwrap();
7809
    let mut heads = repo.revset("bookmark(main)").unwrap().hashes;
7810
    heads.sort();
7811
    let mut want = repo.bookmark_heads().unwrap();
7812
    want.sort();
7813
    assert_eq!(heads, want);
7814
    assert!(heads.contains(&b));
7815
    assert_eq!(repo.revset("main").unwrap().hashes.len(), heads.len());
7816
    // A change prefix is a symbol, not a bookmark.
7817
    let prefix = repo.store().get_change_meta(&a).unwrap().change_id.short(8);
7818
    assert!(repo.revset(&prefix).is_ok());
7819
    let e = repo
7820
        .revset(&format!("bookmark({prefix})"))
7821
        .unwrap_err()
7822
        .to_string();
7823
    assert!(e.contains("no such bookmark"), "{e}");
7824
}
7825
7826
#[test]
7827
fn carrying_work_over_a_subrepo_already_at_the_target_pin_is_no_conflict() {
7828
    // oxygen#74: a stale state with .oxymodules but no pin, a newer one
7829
    // pinning the subrepo, and the nested repository on disk at that pin.
7830
    hermetic();
7831
    let dir = tempfile::tempdir().unwrap();
7832
    let root = dir.path();
7833
    let _lib_origin = Repo::init(&root.join("lib-origin")).unwrap();
7834
    let lib_url = root.join("lib-origin").to_string_lossy().to_string();
7835
    let lib = Repo::clone(&lib_url, &root.join("lib"))
7836
        .unwrap()
7837
        .with_home(root.join("home"));
7838
    write(&root.join("lib"), "lib.txt", b"v1\n");
7839
    lib.commit("lib v1", &[]).unwrap();
7840
    assert!(lib.push("origin", false).unwrap()[0].ok);
7841
    let app_dir = root.join("app");
7842
    let app = Repo::init(&app_dir).unwrap().with_home(root.join("home"));
7843
    write(&app_dir, "main.txt", b"app\n");
7844
    app.submodule_add(&lib_url, "libs/lib", None).unwrap();
7845
    // The stale state: registered in .oxymodules, never pinned.
7846
    fs::rename(app_dir.join("libs/lib"), root.join("aside")).unwrap();
7847
    app.commit("initial", &[]).unwrap();
7848
    let stale = app.bookmark_heads().unwrap();
7849
    fs::rename(root.join("aside"), app_dir.join("libs/lib")).unwrap();
7850
    app.commit("pin lib", &[]).unwrap();
7851
    let newer = app.bookmark_heads().unwrap();
7852
    app.checkout(&stale, false, "test").unwrap();
7853
    write(&app_dir, "notes.txt", b"mine\n");
7854
    let (_, carried) = app.checkout_carry(&newer, "main", "test").unwrap();
7855
    assert_eq!(carried, vec!["notes.txt".to_string()]);
7856
    assert!(app_dir.join("notes.txt").exists());
7857
}
7858
7859
#[test]
7860
fn a_bookmark_only_behind_its_remote_catches_up() {
7861
    // oxygen#74: switch takes the remote's state rather than a stale one.
7862
    hermetic();
7863
    let dir = tempfile::tempdir().unwrap();
7864
    let root = dir.path();
7865
    let _origin = Repo::init(&root.join("origin")).unwrap();
7866
    let url = root.join("origin").to_string_lossy().to_string();
7867
    let one = Repo::clone(&url, &root.join("one"))
7868
        .unwrap()
7869
        .with_home(root.join("home"));
7870
    write(&root.join("one"), "a.txt", b"a\n");
7871
    one.commit("A", &[]).unwrap();
7872
    assert!(one.push("origin", false).unwrap()[0].ok);
7873
    let two = Repo::clone(&url, &root.join("two"))
7874
        .unwrap()
7875
        .with_home(root.join("home"));
7876
    write(&root.join("two"), "b.txt", b"b\n");
7877
    two.commit("B", &[]).unwrap();
7878
    assert!(two.push("origin", false).unwrap()[0].ok);
7879
    assert_eq!(one.catch_up_bookmark("main").unwrap(), None, "not fetched");
7880
    one.fetch("origin").unwrap();
7881
    assert_eq!(one.catch_up_bookmark("main").unwrap(), Some(1));
7882
    assert_eq!(one.bookmarks().unwrap()[0].behind, Some(0));
7883
    // Local work the remote lacks: left alone.
7884
    write(&root.join("one"), "c.txt", b"c\n");
7885
    one.commit("C", &[]).unwrap();
7886
    write(&root.join("two"), "d.txt", b"d\n");
7887
    two.commit("D", &[]).unwrap();
7888
    assert!(two.push("origin", false).unwrap()[0].ok);
7889
    one.fetch("origin").unwrap();
7890
    assert_eq!(one.catch_up_bookmark("main").unwrap(), None);
7891
}
7892
7893
#[test]
7894
fn a_bookmark_is_compared_with_a_remote_that_has_it_when_there_is_no_origin() {
7895
    // oxygen#83: remotes earth and gcs, origin removed.
7896
    hermetic();
7897
    let dir = tempfile::tempdir().unwrap();
7898
    let root = dir.path();
7899
    let _up = Repo::init(&root.join("up")).unwrap();
7900
    let url = root.join("up").to_string_lossy().to_string();
7901
    let other = Repo::clone(&url, &root.join("other"))
7902
        .unwrap()
7903
        .with_home(root.join("home"));
7904
    write(&root.join("other"), "a.txt", b"a\n");
7905
    other.commit("a", &[]).unwrap();
7906
    assert!(other.push("origin", false).unwrap()[0].ok);
7907
    let mut one = Repo::clone(&url, &root.join("one"))
7908
        .unwrap()
7909
        .with_home(root.join("home"));
7910
    one.config.set("remote.earth.url", &url).unwrap();
7911
    one.config.set("remote.gcs.url", &url).unwrap();
7912
    one.config.set("remote.origin.url", "").unwrap();
7913
    one.save_config().unwrap();
7914
    write(&root.join("other"), "b.txt", b"b\n");
7915
    other.commit("b", &[]).unwrap();
7916
    assert!(other.push("origin", false).unwrap()[0].ok);
7917
    one.fetch("earth").unwrap();
7918
    let b = one
7919
        .bookmarks()
7920
        .unwrap()
7921
        .into_iter()
7922
        .find(|b| b.name == "main")
7923
        .unwrap();
7924
    assert_eq!(
7925
        (b.remote.as_deref(), b.behind),
7926
        (Some("earth"), Some(1)),
7927
        "a stale origin copy is not used"
7928
    );
7929
    assert_eq!(
7930
        one.default_remote(),
7931
        "origin",
7932
        "no default chosen among several"
7933
    );
7934
    let e = one.pull(&one.default_remote()).unwrap_err().to_string();
7935
    assert!(e.contains("earth, gcs") && e.contains("core.remote"), "{e}");
7936
    one.config.set("core.remote", "earth").unwrap();
7937
    assert_eq!(one.default_remote(), "earth");
7938
}
7939
7940
#[test]
7941
fn a_missing_author_identity_says_how_to_fix_it() {
7942
    // oxygen#82: an agent home's author.key naming an identity the
7943
    // repository does not hold.
7944
    hermetic();
7945
    let dir = tempfile::tempdir().unwrap();
7946
    let mut repo = Repo::init(dir.path()).unwrap();
7947
    let missing = KeyId::from_hex(&"ab".repeat(32)).unwrap();
7948
    repo.config.set("author.key", &missing.to_hex()).unwrap();
7949
    let e = repo.identity(&missing).unwrap_err().to_string();
7950
    assert!(
7951
        e.contains("this repository has no identity") && e.contains("oxy config author.key"),
7952
        "{e}"
7953
    );
7954
    assert!(e.contains("this repository's config"), "{e}");
7955
}
7956
7957
#[test]
7958
fn a_working_copy_behind_its_bookmark_is_flagged_and_pull_brings_it_up() {
7959
    // oxygen#89 (supermarioland, 2026-10-09): the bookmark moved on without
7960
    // the working copy, a pull with nothing new left it there, and status
7961
    // said "clean".
7962
    hermetic();
7963
    let dir = tempfile::tempdir().unwrap();
7964
    let root = dir.path();
7965
    let _up = Repo::init(&root.join("up")).unwrap();
7966
    let url = root.join("up").to_string_lossy().to_string();
7967
    let other = Repo::clone(&url, &root.join("other"))
7968
        .unwrap()
7969
        .with_home(root.join("home"));
7970
    write(&root.join("other"), "a.txt", b"a\n");
7971
    other.commit("a", &[]).unwrap();
7972
    assert!(other.push("origin", false).unwrap()[0].ok);
7973
    let one = Repo::clone(&url, &root.join("one"))
7974
        .unwrap()
7975
        .with_home(root.join("home"));
7976
    write(&root.join("other"), "b.txt", b"b\n");
7977
    other.commit("b", &[]).unwrap();
7978
    assert!(other.push("origin", false).unwrap()[0].ok);
7979
    one.fetch("origin").unwrap();
7980
    // The bookmark moves; the working copy does not.
7981
    let theirs = one.resolve_heads("origin/main").unwrap();
7982
    one.bookmark_set("main", &theirs).unwrap();
7983
    assert!(!root.join("one/b.txt").exists());
7984
    assert_eq!(one.working_copy_behind().unwrap(), Some(1));
7985
    let r = one.pull("origin").unwrap();
7986
    assert!(
7987
        !r.changed && r.checked_out,
7988
        "nothing new, but the working copy caught up"
7989
    );
7990
    assert!(root.join("one/b.txt").exists());
7991
    assert_eq!(one.working_copy_behind().unwrap(), None);
7992
}
7993
7994
#[test]
7995
fn touched_nodes_cache_answers_as_the_changes_do() {
7996
    hermetic();
7997
    let dir = tempfile::tempdir().unwrap();
7998
    let repo = Repo::init(dir.path()).unwrap();
7999
    write(dir.path(), "a.txt", b"one\n");
8000
    write(dir.path(), "b.txt", b"x\n");
8001
    repo.snapshot("t").unwrap();
8002
    let c1 = repo.commit("first", &[]).unwrap();
8003
    write(dir.path(), "b.txt", b"y\n");
8004
    repo.snapshot("t").unwrap();
8005
    repo.commit("b only", &[]).unwrap();
8006
    fs::rename(dir.path().join("a.txt"), dir.path().join("c.txt")).unwrap();
8007
    write(dir.path(), "c.txt", b"one\ntwo\n");
8008
    repo.snapshot("t").unwrap();
8009
    let c3 = repo.commit("rename and edit", &[]).unwrap();
8010
    // Uncommitted work, so the working copy touches a file too.
8011
    write(dir.path(), "c.txt", b"one\ntwo\nthree\n");
8012
    repo.snapshot("t").unwrap();
8013
8014
    let path = dir.path().join(".oxy/index/touched");
8015
    let hashes = |es: Vec<LogEntry>| es.iter().map(|e| e.hash).collect::<Vec<_>>();
8016
    let cold = hashes(repo.log_for_path("c.txt").unwrap());
8017
    assert!(path.exists(), "the first query writes the cache");
8018
    let warm = hashes(repo.log_for_path("c.txt").unwrap());
8019
    assert_eq!(cold, warm, "the cache answers as the changes do");
8020
    let (wc, _) = repo.working_copy().unwrap();
8021
    assert_eq!(
8022
        cold,
8023
        vec![wc, c3, c1],
8024
        "renames followed, the working copy included"
8025
    );
8026
8027
    // Working-copy changes are not kept: they are replaced by every snapshot.
8028
    let cached = super::touched::read_touched_for_test(&fs::read(&path).unwrap()).unwrap();
8029
    assert!(!cached.contains(&wc), "a working-copy change is not cached");
8030
    assert!(cached.contains(&c1) && cached.contains(&c3));
8031
8032
    // A damaged cache is ignored, not trusted.
8033
    let mut bytes = fs::read(&path).unwrap();
8034
    let last = bytes.len() - 40;
8035
    bytes[last] ^= 1;
8036
    fs::write(&path, &bytes).unwrap();
8037
    assert_eq!(hashes(repo.log_for_path("c.txt").unwrap()), cold);
8038
    let touches = repo.log_revset("touches(\"c.txt\") ~ @").unwrap();
8039
    assert_eq!(hashes(touches), vec![c3, c1]);
8040
}
8041
8042
/// oxygen#88 (vscode 9ab2056393c8): two lines of history that each move a
8043
/// file back where it was leave two placements at one place, which the
8044
/// tree shows as one file. Removing it, and then its directory, retires
8045
/// both, so no copy is left under a directory that is gone.
8046
#[test]
8047
fn git_import_removes_every_copy_of_a_file_at_one_place() {
8048
    hermetic();
8049
    if std::process::Command::new("git")
8050
        .arg("--version")
8051
        .output()
8052
        .is_err()
8053
    {
8054
        eprintln!("git not installed; skipping");
8055
        return;
8056
    }
8057
    let dir = tempfile::tempdir().unwrap();
8058
    let root = dir.path();
8059
    let g = root.join("src.git");
8060
    fs::create_dir_all(&g).unwrap();
8061
    let git = |args: &[&str]| {
8062
        let out = std::process::Command::new("git")
8063
            .arg("-C")
8064
            .arg(&g)
8065
            .args([
8066
                "-c",
8067
                "user.name=Grace",
8068
                "-c",
8069
                "[email protected]",
8070
                "-c",
8071
                "commit.gpgsign=false",
8072
            ])
8073
            .args(args)
8074
            .output()
8075
            .unwrap();
8076
        assert!(
8077
            out.status.success(),
8078
            "git {args:?}: {}",
8079
            String::from_utf8_lossy(&out.stderr)
8080
        );
8081
    };
8082
    git(&["init", "-q", "-b", "main"]);
8083
    write(&g, "d/list.txt", b"one\ntwo\nthree\nfour\n");
8084
    write(&g, "keep.txt", b"k\n");
8085
    git(&["add", "."]);
8086
    git(&["commit", "-qm", "base"]);
8087
    fs::create_dir_all(g.join("d/sub")).unwrap();
8088
    git(&["mv", "d/list.txt", "d/sub/list.txt"]);
8089
    git(&["commit", "-qm", "into sub"]);
8090
    git(&["checkout", "-qb", "side"]);
8091
    git(&["mv", "d/sub/list.txt", "d/list.txt"]);
8092
    git(&["commit", "-qm", "back, on side"]);
8093
    git(&["checkout", "-q", "main"]);
8094
    git(&["mv", "d/sub/list.txt", "d/list.txt"]);
8095
    git(&["commit", "-qm", "back, on main"]);
8096
    git(&["merge", "-q", "--no-edit", "side"]);
8097
    git(&["rm", "-rq", "d"]);
8098
    git(&["commit", "-qm", "d goes"]);
8099
8100
    let repo = Repo::init(&root.join("o")).unwrap();
8101
    repo.import_git(&g, "main").unwrap();
8102
    let v = repo.verify_git_import(&g, "main").unwrap();
8103
    assert!(v.mismatches.is_empty(), "{:?}", v.mismatches);
8104
    let st = repo
8105
        .load_state_history(&repo.bookmark_heads().unwrap())
8106
        .unwrap();
8107
    let view = st.tree().view();
8108
    assert!(view.conflicts.is_empty(), "{:?}", view.conflicts);
8109
    assert_eq!(view.entries.keys().collect::<Vec<_>>(), vec!["keep.txt"]);
8110
}
8111
8112
/// oxygen#94: a state index's file histories are read, and checked by
8113
/// their own hashes, only when a file is built. One found damaged is an
8114
/// error that says so, the index is removed, and the next read rebuilds it.
8115
#[test]
8116
fn a_damaged_file_history_in_the_state_index_is_rebuilt() {
8117
    hermetic();
8118
    let dir = tempfile::tempdir().unwrap();
8119
    let repo = Repo::init(dir.path()).unwrap();
8120
    for i in 0..6 {
8121
        write(
8122
            dir.path(),
8123
            &format!("f{i}.txt"),
8124
            format!("one {i}\n").as_bytes(),
8125
        );
8126
    }
8127
    repo.snapshot("t").unwrap();
8128
    repo.commit("first", &[]).unwrap();
8129
    for i in 0..6 {
8130
        write(
8131
            dir.path(),
8132
            &format!("f{i}.txt"),
8133
            format!("one {i}\ntwo\n").as_bytes(),
8134
        );
8135
    }
8136
    repo.snapshot("t").unwrap();
8137
    repo.commit("second", &[]).unwrap();
8138
    let want: Vec<Vec<u8>> = (0..6)
8139
        .map(|i| format!("one {i}\ntwo\n").into_bytes())
8140
        .collect();
8141
    // The index of the working copy's base, holding every file's history
8142
    // (a few changes behind, an index is replayed onto, not rewritten).
8143
    let (_, wc) = repo.working_copy().unwrap();
8144
    let base = repo.load_state_history(&wc.deps).unwrap();
8145
    repo.write_state_index(&wc.deps, &base);
8146
    for (i, w) in want.iter().enumerate() {
8147
        assert_eq!(&repo.file_at(&format!("f{i}.txt"), None).unwrap(), w);
8148
    }
8149
    let index = repo.state_indexes();
8150
    assert!(!index.is_empty(), "a state index was written");
8151
    // The histories are last in the file: damage the last of them.
8152
    let mut bytes = fs::read(&index[0]).unwrap();
8153
    let last = bytes.len() - 1;
8154
    bytes[last] ^= 0x40;
8155
    fs::write(&index[0], &bytes).unwrap();
8156
8157
    let reads: Vec<_> = (0..6)
8158
        .map(|i| repo.file_at(&format!("f{i}.txt"), None))
8159
        .collect();
8160
    let damaged: Vec<String> = reads
8161
        .iter()
8162
        .filter_map(|r| r.as_ref().err().map(|e| e.to_string()))
8163
        .collect();
8164
    assert_eq!(damaged.len(), 1, "{damaged:?}");
8165
    assert!(
8166
        damaged[0].contains("state index was damaged")
8167
            && damaged[0].contains("run the command again"),
8168
        "{}",
8169
        damaged[0]
8170
    );
8171
    // Every file reads right again, from an index rebuilt from history.
8172
    for (i, w) in want.iter().enumerate() {
8173
        assert_eq!(&repo.file_at(&format!("f{i}.txt"), None).unwrap(), w);
8174
    }
8175
}
8176
8177
/// oxygen#95: a push longer than `push.batch-bytes` goes in parts, each
8178
/// objects alone and in dependency order, and the last moves the bookmark.
8179
/// The remote ends with every change and the same state, and says how each
8180
/// part went.
8181
#[test]
8182
fn a_long_push_goes_in_parts() {
8183
    hermetic();
8184
    let dir = tempfile::tempdir().unwrap();
8185
    let root = dir.path();
8186
    let origin = root.join("origin");
8187
    Repo::init_bare_unbound(&origin).unwrap();
8188
    let main = root.join("main");
8189
    let mut repo = Repo::init(&main).unwrap();
8190
    repo.config
8191
        .set("remote.origin.url", &origin.to_string_lossy())
8192
        .unwrap();
8193
    // One byte: every change is a part of its own.
8194
    repo.config.set("push.batch-bytes", "1").unwrap();
8195
    repo.save_config().unwrap();
8196
    for i in 0..6 {
8197
        write(
8198
            &main,
8199
            &format!("f{i}.txt"),
8200
            format!("file {i}\n").as_bytes(),
8201
        );
8202
        repo.commit(&format!("c{i}"), &[]).unwrap();
8203
    }
8204
    let mut parts = Vec::new();
8205
    let results = repo
8206
        .push_bookmark_with("origin", "main", false, &mut |m| parts.push(m.to_string()))
8207
        .unwrap();
8208
    assert!(
8209
        results.iter().any(|r| r.ok && r.name == "main"),
8210
        "{results:?}"
8211
    );
8212
    assert_eq!(parts.len(), 6, "{parts:?}");
8213
    assert_eq!(parts[0], "part 1 of 6: 1 changes");
8214
8215
    let remote = Repo::open(&origin).unwrap();
8216
    let heads = repo.bookmark_heads().unwrap();
8217
    assert_eq!(remote.bookmark_heads().unwrap(), heads);
8218
    assert_eq!(
8219
        remote.log_state(&heads).unwrap().len(),
8220
        repo.log_state(&heads).unwrap().len()
8221
    );
8222
    // A push of objects alone reports how it went, as `objects`.
8223
    let got = remote
8224
        .receive_push(Bundle::default(), vec![], None, vec![])
8225
        .unwrap();
8226
    assert_eq!(got.len(), 1);
8227
    assert!(got[0].ok && got[0].name == OBJECTS_RESULT, "{got:?}");
8228
}
8229
8230
/// oxygen#97: with `git.claim`, an import authors the importing identity's
8231
/// own commits (Git author email = its email, any case) with its key, and
8232
/// leaves anyone else's with the zero key; the history verifies as before.
8233
#[test]
8234
fn git_import_claims_your_own_commits() {
8235
    hermetic();
8236
    if std::process::Command::new("git")
8237
        .arg("--version")
8238
        .output()
8239
        .is_err()
8240
    {
8241
        eprintln!("git not installed; skipping");
8242
        return;
8243
    }
8244
    let dir = tempfile::tempdir().unwrap();
8245
    let root = dir.path();
8246
    let g = root.join("src.git");
8247
    fs::create_dir_all(&g).unwrap();
8248
    let git = |who: &str, args: &[&str]| {
8249
        let (name, email) = who.split_once(' ').unwrap();
8250
        let out = std::process::Command::new("git")
8251
            .arg("-C")
8252
            .arg(&g)
8253
            .args([
8254
                "-c",
8255
                &format!("user.name={name}"),
8256
                "-c",
8257
                &format!("user.email={email}"),
8258
                "-c",
8259
                "commit.gpgsign=false",
8260
            ])
8261
            .args(args)
8262
            .output()
8263
            .unwrap();
8264
        assert!(
8265
            out.status.success(),
8266
            "git {args:?}: {}",
8267
            String::from_utf8_lossy(&out.stderr)
8268
        );
8269
    };
8270
    git("Grace [email protected]", &["init", "-q", "-b", "main"]);
8271
    write(&g, "a.txt", b"a\n");
8272
    git("Grace [email protected]", &["add", "."]);
8273
    git("Grace [email protected]", &["commit", "-qm", "mine"]);
8274
    write(&g, "b.txt", b"b\n");
8275
    git("Ada [email protected]", &["add", "."]);
8276
    git("Ada [email protected]", &["commit", "-qm", "someone else's"]);
8277
8278
    let mut repo = Repo::init(&root.join("o")).unwrap();
8279
    let (key, _) = repo
8280
        .create_identity("Grace", "[email protected]", IdentityScope::Repo)
8281
        .unwrap();
8282
    repo.config.set("git.claim", "true").unwrap();
8283
    repo.save_config().unwrap();
8284
    let repo = Repo::open(&root.join("o")).unwrap();
8285
    repo.import_git(&g, "main").unwrap();
8286
    let v = repo.verify_git_import(&g, "main").unwrap();
8287
    assert!(v.mismatches.is_empty(), "{:?}", v.mismatches);
8288
    let heads = repo.bookmark_heads().unwrap();
8289
    let by_message: std::collections::HashMap<String, KeyId> = repo
8290
        .log_state(&heads)
8291
        .unwrap()
8292
        .into_iter()
8293
        .map(|e| {
8294
            (
8295
                e.change.message.lines().next().unwrap_or("").to_string(),
8296
                e.change.author,
8297
            )
8298
        })
8299
        .collect();
8300
    assert_eq!(by_message["mine"], key, "her own commit, any case of email");
8301
    assert_eq!(by_message["someone else's"], ObjectRef::ZERO, "not hers");
8302
}
8303
8304
/// oxygen#86: removing a remote removes all of it: every `remote.NAME.*`
8305
/// key (URL, token, CA), its tracking bookmarks, and nothing else.
8306
#[test]
8307
fn removing_a_remote_leaves_nothing_of_it() {
8308
    hermetic();
8309
    let dir = tempfile::tempdir().unwrap();
8310
    let origin = dir.path().join("origin");
8311
    Repo::init_bare_unbound(&origin).unwrap();
8312
    let main = dir.path().join("main");
8313
    let mut repo = Repo::init(&main).unwrap();
8314
    repo.config
8315
        .set("remote.origin.url", &origin.to_string_lossy())
8316
        .unwrap();
8317
    repo.config
8318
        .set("remote.origin.token", "secret-ish")
8319
        .unwrap();
8320
    repo.config
8321
        .set("remote.keep.url", &origin.to_string_lossy())
8322
        .unwrap();
8323
    repo.save_config().unwrap();
8324
    write(&main, "a.txt", b"a\n");
8325
    repo.commit("a", &[]).unwrap();
8326
    assert!(repo.push("origin", false).unwrap()[0].ok);
8327
    assert!(
8328
        repo.view().unwrap().remotes.contains_key("origin"),
8329
        "a tracking bookmark"
8330
    );
8331
8332
    repo.remove_remote("origin").unwrap();
8333
    let again = Repo::open(&main).unwrap();
8334
    assert!(
8335
        !again
8336
            .config
8337
            .repo_layer()
8338
            .keys()
8339
            .any(|k| k.starts_with("remote.origin.")),
8340
        "{:?}",
8341
        again.config.repo_layer()
8342
    );
8343
    assert!(!again.config.remotes.contains_key("origin"));
8344
    assert!(
8345
        !again.view().unwrap().remotes.contains_key("origin"),
8346
        "its tracking bookmarks go"
8347
    );
8348
    assert!(
8349
        again.config.remotes.contains_key("keep"),
8350
        "another remote stays"
8351
    );
8352
    let mut again = again;
8353
    assert!(
8354
        again.remove_remote("origin").is_err(),
8355
        "a second removal is refused"
8356
    );
8357
}
8358
8359
/// oxygenhub#126: a blob a host stored for itself (a job's artifact) is
8360
/// unreachable from history, so gc prunes it, unless the host names it:
8361
/// then it and its chunks stay, and it reads back whole.
8362
#[test]
8363
fn gc_keeps_the_blobs_a_host_names() {
8364
    hermetic();
8365
    let dir = tempfile::tempdir().unwrap();
8366
    let repo = Repo::init(dir.path()).unwrap();
8367
    write(dir.path(), "a.txt", b"a\n");
8368
    repo.commit("a", &[]).unwrap();
8369
    // Large enough to be several chunks.
8370
    let body: Vec<u8> = (0..400_000u32)
8371
        .flat_map(|i| (i.wrapping_mul(2654435761)).to_le_bytes())
8372
        .collect();
8373
    let kept = repo.store_blob(&body).unwrap();
8374
    let lost = repo.store_blob(b"an artifact nobody names").unwrap();
8375
    repo.gc_keeping(true, &[kept], &mut |_| {}).unwrap();
8376
    assert_eq!(repo.read_blob(&kept).unwrap(), body, "named: kept whole");
8377
    assert!(!repo.store().has(&lost), "not named: pruned");
8378
    repo.gc(true).unwrap();
8379
    assert!(!repo.store().has(&kept), "a plain gc prunes it");
8380
}
8381
8382
/// oxygen#99: undo in one workspace undoes that workspace's last command,
8383
/// never another workspace's, says what it undid, and goes further back
8384
/// when run again.
8385
#[test]
8386
fn undo_is_scoped_to_its_workspace() {
8387
    hermetic();
8388
    let dir = tempfile::tempdir().unwrap();
8389
    let root = dir.path().join("main");
8390
    let a = Repo::init(&root).unwrap();
8391
    write(&root, "base.txt", b"base\n");
8392
    let base = a.commit("base", &[]).unwrap();
8393
    a.bookmark_create("feature", None).unwrap();
8394
    let ws_dir = dir.path().join("ws");
8395
    let heads = a.resolve_heads("feature").unwrap();
8396
    let b = a
8397
        .workspace_add_on(&ws_dir, Some(&heads), Some("feature"))
8398
        .unwrap();
8399
8400
    // A commits on main, then B commits on feature: B's is the newest.
8401
    write(&root, "a.txt", b"a\n");
8402
    let ca = a.commit("from a", &[]).unwrap();
8403
    write(&ws_dir, "b.txt", b"b\n");
8404
    let cb = b.commit("from b", &[]).unwrap();
8405
8406
    // A's undo undoes A's commit and leaves B's.
8407
    let u = a.undo().unwrap();
8408
    assert_eq!(u.command, "oxy commit -m \"from a\"");
8409
    assert_eq!(u.others_kept, 1, "B's newer commit is left");
8410
    assert!(!u.changes.is_empty());
8411
    let view = a.view().unwrap();
8412
    // (Independent changes commute, so a bookmark's heads may hold base too.)
8413
    assert_eq!(a.heads_of(&view, "main").unwrap(), vec![base]);
8414
    assert!(
8415
        a.heads_of(&view, "feature").unwrap().contains(&cb),
8416
        "B's commit stands"
8417
    );
8418
    assert!(
8419
        a.store().get_change(&ca).is_ok(),
8420
        "the change itself is still in the store"
8421
    );
8422
    // A's working copy was clean, so its files followed; B's are untouched.
8423
    assert!(!root.join("a.txt").exists());
8424
    assert!(a.snapshot("oxy status").unwrap().statuses.is_empty());
8425
    assert!(ws_dir.join("b.txt").exists());
8426
8427
    // B's undo still finds B's own commit, under A's undo.
8428
    let u = b.undo().unwrap();
8429
    assert_eq!(u.command, "oxy commit -m \"from b\"");
8430
    assert!(!b
8431
        .heads_of(&b.view().unwrap(), "feature")
8432
        .unwrap()
8433
        .contains(&cb));
8434
    assert_eq!(
8435
        a.heads_of(&a.view().unwrap(), "main").unwrap(),
8436
        vec![base],
8437
        "A's undo stands"
8438
    );
8439
8440
    // A's next undo goes past the commit it already undid, to adding B's
8441
    // workspace: refused, since B has worked there since.
8442
    let e = a.undo().unwrap_err().to_string();
8443
    assert!(e.contains("the workspace at") && e.contains("ws"), "{e}");
8444
}
8445
8446
/// oxygen#99: two workspaces on one bookmark: an undo takes back only its
8447
/// own commit's head, and the other workspace's head stays.
8448
#[test]
8449
fn undo_on_a_shared_bookmark_keeps_the_other_workspaces_head() {
8450
    hermetic();
8451
    let dir = tempfile::tempdir().unwrap();
8452
    let root = dir.path().join("main");
8453
    let a = Repo::init(&root).unwrap();
8454
    write(&root, "base.txt", b"base\n");
8455
    a.commit("base", &[]).unwrap();
8456
    let ws_dir = dir.path().join("ws");
8457
    let b = a.workspace_add(&ws_dir, None).unwrap();
8458
    write(&root, "a.txt", b"a\n");
8459
    let ca = a.commit("from a", &[]).unwrap();
8460
    write(&ws_dir, "b.txt", b"b\n");
8461
    let cb = b.commit("from b", &[]).unwrap();
8462
    let u = a.undo().unwrap();
8463
    assert_eq!(u.command, "oxy commit -m \"from a\"");
8464
    let heads = a.heads_of(&a.view().unwrap(), "main").unwrap();
8465
    assert!(heads.contains(&cb) && !heads.contains(&ca), "{heads:?}");
8466
}
8467
8468
/// oxygen#99: an undo that would also take back what another workspace
8469
/// did since to the same bookmark is refused, naming it.
8470
#[test]
8471
fn undo_refuses_to_take_back_another_workspaces_work() {
8472
    hermetic();
8473
    let dir = tempfile::tempdir().unwrap();
8474
    let root = dir.path().join("main");
8475
    let a = Repo::init(&root).unwrap();
8476
    write(&root, "base.txt", b"base\n");
8477
    a.commit("base", &[]).unwrap();
8478
    let ws_dir = dir.path().join("ws");
8479
    let b = a.workspace_add(&ws_dir, None).unwrap();
8480
    // Both on main: A commits, then B builds on it, editing A's file.
8481
    write(&root, "a.txt", b"a\n");
8482
    a.commit("from a", &[]).unwrap();
8483
    b.refresh().unwrap();
8484
    let heads = b.resolve_heads("main").unwrap();
8485
    b.checkout(&heads, false, "oxy checkout").unwrap();
8486
    write(&ws_dir, "a.txt", b"a, then b\n");
8487
    b.commit("from b", &[]).unwrap();
8488
    let e = a.undo().unwrap_err().to_string();
8489
    assert!(
8490
        e.contains("bookmark main") && e.contains("builds on"),
8491
        "{e}"
8492
    );
8493
    assert!(e.contains("oxy op restore"), "{e}");
8494
}
8495
8496
/// oxygen#99: undoing a commit that was already pushed says so: the remote
8497
/// still has it.
8498
#[test]
8499
fn undo_says_when_the_commit_was_pushed() {
8500
    hermetic();
8501
    let dir = tempfile::tempdir().unwrap();
8502
    let root = dir.path();
8503
    Repo::init(&root.join("origin")).unwrap();
8504
    let url = root.join("origin").to_string_lossy().to_string();
8505
    let repo = Repo::clone(&url, &root.join("work"))
8506
        .unwrap()
8507
        .with_home(root.join("home"));
8508
    write(&root.join("work"), "a.txt", b"a\n");
8509
    repo.commit("a", &[]).unwrap();
8510
    assert!(repo.push("origin", false).unwrap()[0].ok);
8511
    // The push itself is passed over: the remote keeps what it was sent.
8512
    let u = repo.undo().unwrap();
8513
    assert_eq!(u.command, "oxy commit -m \"a\"");
8514
    assert_eq!(u.pushed, vec![("main".to_string(), "origin".to_string())]);
8515
}
8516
8517
/// oxygen#98: a new untracked file over snapshot.max-new-file-size is left
8518
/// out of the snapshot and named; tracked files and files already in the
8519
/// working copy are not.
8520
#[test]
8521
fn large_new_files_are_left_out_of_snapshots() {
8522
    hermetic();
8523
    let dir = tempfile::tempdir().unwrap();
8524
    let root = dir.path();
8525
    let mut repo = Repo::init(root).unwrap();
8526
    repo.config.max_new_file = 1024;
8527
    write(root, "small.txt", b"small\n");
8528
    write(root, "big.bin", &vec![0u8; 4096]);
8529
    let s = repo.snapshot("oxy status").unwrap();
8530
    let paths: Vec<_> = s.statuses.iter().map(|p| p.path.as_str()).collect();
8531
    assert_eq!(paths, ["small.txt"]);
8532
    assert_eq!(repo.skipped_large(), vec![("big.bin".to_string(), 4096)]);
8533
    repo.commit("small", &[]).unwrap();
8534
8535
    // A tracked file may grow past the limit.
8536
    write(root, "small.txt", &vec![b'x'; 4096]);
8537
    let s = repo.snapshot("oxy status").unwrap();
8538
    assert!(s.statuses.iter().any(|p| p.path == "small.txt"));
8539
    // With no limit the big file is taken in, and stays once it is.
8540
    repo.config.max_new_file = 0;
8541
    let s = repo.snapshot("oxy status").unwrap();
8542
    assert!(s.statuses.iter().any(|p| p.path == "big.bin"));
8543
    repo.config.max_new_file = 1024;
8544
    let s = repo.snapshot("oxy status").unwrap();
8545
    assert!(
8546
        s.statuses.iter().any(|p| p.path == "big.bin"),
8547
        "already in the working copy"
8548
    );
8549
    assert!(repo.skipped_large().is_empty());
8550
}
8551
8552
/// oxygen#98: a file only a past working-copy snapshot held is pruned once
8553
/// snapshots expire, and kept while they have not.
8554
#[test]
8555
fn gc_prunes_what_only_expired_snapshots_held() {
8556
    hermetic();
8557
    let dir = tempfile::tempdir().unwrap();
8558
    let root = dir.path();
8559
    let mut repo = Repo::init(root).unwrap();
8560
    repo.config.gc_grace_days = 0;
8561
    write(root, "a.txt", b"a\n");
8562
    repo.commit("a", &[]).unwrap();
8563
    let image: Vec<u8> = (0..200_000u32).map(|i| (i % 7) as u8).collect();
8564
    write(root, "image.tar", &image);
8565
    repo.snapshot("oxy status").unwrap();
8566
    std::fs::remove_file(root.join("image.tar")).unwrap();
8567
    repo.snapshot("oxy status").unwrap();
8568
    let blob = Repo::blob_ref(&image);
8569
    assert!(repo.store().has(&blob));
8570
    repo.gc(true).unwrap();
8571
    assert!(repo.store().has(&blob), "a recent snapshot keeps it");
8572
    repo.config.snapshot_retention_days = 0;
8573
    repo.gc(true).unwrap();
8574
    assert!(!repo.store().has(&blob), "an expired snapshot does not");
8575
    assert_eq!(
8576
        repo.file_at("a.txt", None).unwrap(),
8577
        b"a\n",
8578
        "committed files stay"
8579
    );
8580
}
8581
8582
/// oxygen#103: a full change hash as `--json` prints it, without `#`,
8583
/// resolves, so JSON output feeds back into commands.
8584
#[test]
8585
fn a_full_hash_resolves_without_its_hash_sign() {
8586
    hermetic();
8587
    let dir = tempfile::tempdir().unwrap();
8588
    let root = dir.path();
8589
    let repo = Repo::init(root).unwrap();
8590
    write(root, "a.txt", b"a\n");
8591
    let h = repo.commit("a", &[]).unwrap();
8592
    assert_eq!(repo.resolve_change(&h.to_hex()).unwrap(), h);
8593
    assert_eq!(repo.resolve_change(&format!("#{}", h.to_hex())).unwrap(), h);
8594
    assert!(repo
8595
        .resolve_change(&"0".repeat(64))
8596
        .unwrap_err()
8597
        .to_string()
8598
        .contains("no change matches"));
8599
}
8600
8601
#[test]
8602
fn a_pin_change_moves_only_the_pin() {
8603
    hermetic();
8604
    let dir = tempfile::tempdir().unwrap();
8605
    let root = dir.path();
8606
    let _lib_origin = Repo::init(&root.join("lib-origin")).unwrap();
8607
    let lib_url = root.join("lib-origin").to_string_lossy().to_string();
8608
    let lib = Repo::clone(&lib_url, &root.join("lib"))
8609
        .unwrap()
8610
        .with_home(root.join("home"));
8611
    write(&root.join("lib"), "lib.txt", b"v1\n");
8612
    lib.commit("lib v1", &[]).unwrap();
8613
    assert!(lib.push("origin", false).unwrap()[0].ok);
8614
    let _app_origin = Repo::init(&root.join("app-origin")).unwrap();
8615
    let app_dir = root.join("app");
8616
    let app = Repo::clone(&root.join("app-origin").to_string_lossy(), &app_dir)
8617
        .unwrap()
8618
        .with_home(root.join("home"));
8619
    write(&app_dir, "main.txt", b"app\n");
8620
    let pin1 = app.submodule_add(&lib_url, "libs/lib", None).unwrap();
8621
    let a1 = app.commit("app with lib", &[]).unwrap();
8622
    // The library moves on.
8623
    write(&root.join("lib"), "more.txt", b"v2\n");
8624
    let l2 = lib.commit("lib v2", &[]).unwrap();
8625
    let crate::subrepo::Pin::Oxy { repo, bookmark, .. } = pin1 else {
8626
        panic!("an Oxygen pin")
8627
    };
8628
    let pin2 = crate::subrepo::Pin::Oxy {
8629
        repo,
8630
        heads: vec![l2],
8631
        bookmark,
8632
    };
8633
    let author = app.store().get_change(&a1).unwrap().author;
8634
    let change = app
8635
        .build_pin_change(&[a1], "libs/lib", &pin2, "Move lib to v2", author)
8636
        .unwrap();
8637
    let mut state = app.load_state(&[a1]).unwrap();
8638
    state.add(change).unwrap();
8639
    let files = state.materialize().files;
8640
    assert_eq!(files["libs/lib"].kind, NodeKind::Subrepo);
8641
    let FileContent::Opaque { blobs } = &files["libs/lib"].content else {
8642
        panic!("a pin is opaque")
8643
    };
8644
    let read = crate::subrepo::Pin::decode(&app.read_blob(&blobs[0]).unwrap()).unwrap();
8645
    assert_eq!(read, pin2, "the new pin");
8646
    assert!(
8647
        matches!(&files["main.txt"].content, FileContent::Text { bytes, .. } if bytes.as_slice() == b"app\n"),
8648
        "nothing else changes"
8649
    );
8650
    // Only a subrepo's pin can be moved this way.
8651
    let e = app.build_pin_change(&[a1], "main.txt", &pin2, "x", author);
8652
    assert!(format!("{:?}", e.unwrap_err()).contains("not a subrepo"));
8653
    let e = app.build_pin_change(&[a1], "libs/none", &pin2, "x", author);
8654
    assert!(format!("{:?}", e.unwrap_err()).contains("does not exist"));
8655
}
8656
8657
/// oxygenhub#249: a handle reads the operation head once and keeps it,
8658
/// so one command or request never mixes two heads; another handle's
8659
/// operation shows only after `refresh`. Its own operations move it, and
8660
/// one recorded from the head it kept merges with what landed since, as
8661
/// any concurrent operation does.
8662
#[test]
8663
fn one_handle_keeps_one_head_until_it_refreshes() {
8664
    hermetic();
8665
    let dir = tempfile::tempdir().unwrap();
8666
    let root = dir.path();
8667
    let writer = Repo::init(root).unwrap();
8668
    write(root, "a.txt", b"one\n");
8669
    let h1 = writer.commit("one", &[]).unwrap();
8670
    let reader = Repo::open(root).unwrap();
8671
    let before = reader.view().unwrap();
8672
    assert_eq!(reader.bookmark_heads().unwrap(), vec![h1]);
8673
    write(root, "a.txt", b"two\n");
8674
    let h2 = writer.commit("two", &[]).unwrap();
8675
    assert_eq!(
8676
        writer.bookmark_heads().unwrap(),
8677
        vec![h2],
8678
        "its own operation"
8679
    );
8680
    assert_eq!(reader.view().unwrap(), before, "the head it read first");
8681
    assert_eq!(reader.bookmark_heads().unwrap(), vec![h1]);
8682
    reader.refresh().unwrap();
8683
    assert_eq!(reader.bookmark_heads().unwrap(), vec![h2]);
8684
8685
    // A handle recording from an older head merges with the newer one.
8686
    let stale = Repo::open(root).unwrap();
8687
    assert_eq!(stale.bookmark_heads().unwrap(), vec![h2]);
8688
    write(root, "a.txt", b"three\n");
8689
    let h3 = writer.commit("three", &[]).unwrap();
8690
    stale.bookmark_create("feature", Some(&[h1])).unwrap();
8691
    let view = stale.view().unwrap();
8692
    assert!(view.bookmarks.contains_key("feature"));
8693
    assert_eq!(
8694
        stale.bookmark_heads().unwrap(),
8695
        vec![h3],
8696
        "merged, not lost"
8697
    );
8698
    let fresh = Repo::open(root).unwrap();
8699
    assert_eq!(fresh.view().unwrap(), view);
8700
}
8701
8702
/// oxygenhub#249 over a store (a bucket's compare-and-swap): the same.
8703
#[test]
8704
fn over_a_store_one_handle_keeps_one_head() {
8705
    hermetic();
8706
    let backend = std::sync::Arc::new(crate::strata::MemoryStore::new());
8707
    crate::store::TEST_BACKEND.with(|t| *t.borrow_mut() = Some(backend.clone()));
8708
    let dir = tempfile::tempdir().unwrap();
8709
    let a = Repo::init(dir.path()).unwrap();
8710
    let (h0, _) = a.head_op().unwrap();
8711
    let b = Repo::open(dir.path()).unwrap();
8712
    assert_eq!(b.head_op().unwrap().0, h0);
8713
    let state = a.store.put_state(&StateObject::new(vec![])).unwrap();
8714
    let mut view = a.view().unwrap();
8715
    view.bookmarks.insert("x".into(), state);
8716
    let r = a.record_op(&[h0], "bookmark x", view).unwrap();
8717
    assert_eq!(a.head_op().unwrap().0, r);
8718
    assert_eq!(b.head_op().unwrap().0, h0, "b keeps its head");
8719
    b.refresh().unwrap();
8720
    assert_eq!(b.head_op().unwrap().0, r);
8721
    crate::store::TEST_BACKEND.with(|t| *t.borrow_mut() = None);
8722
}
8723
8724
/// oxygenhub#249: gc retires what it repacks rather than deleting it; a
8725
/// reader opened before reads on, then and after the next gc deletes the
8726
/// retired files once their hour is up. Younger ones are kept.
8727
#[test]
8728
fn gc_retires_and_a_later_gc_deletes_after_the_hour() {
8729
    hermetic();
8730
    let dir = tempfile::tempdir().unwrap();
8731
    let root = dir.path();
8732
    let repo = Repo::init(root).unwrap();
8733
    let mut heads = Vec::new();
8734
    for i in 0..4 {
8735
        write(root, &format!("f{i}.txt"), format!("{i}\n").as_bytes());
8736
        heads.push(repo.commit(&format!("c{i}"), &[]).unwrap());
8737
    }
8738
    let reader = Repo::open(root).unwrap();
8739
    assert_eq!(reader.log().unwrap().len(), 5);
8740
    let r = repo.gc(true).unwrap();
8741
    assert_eq!(r.retired, crate::store::RetiredReport::default());
8742
    assert_eq!(repo.store().loose_count().unwrap(), 0);
8743
    assert_eq!(reader.log().unwrap().len(), 5, "read on from what it had");
8744
    // Nothing is an hour old yet: a gc keeps it all.
8745
    let r = repo.gc(true).unwrap();
8746
    assert_eq!((r.retired.packs, r.retired.loose), (0, 0));
8747
    assert!(r.retired.kept > 0, "{r:?}");
8748
    write(root, "f9.txt", b"9\n");
8749
    heads.push(repo.commit("c9", &[]).unwrap());
8750
    crate::store::reader_tests::age_retired(
8751
        repo.store(),
8752
        crate::store::RETIRED_FOR + std::time::Duration::from_secs(60),
8753
    );
8754
    let r = repo.gc(true).unwrap();
8755
    assert!(r.retired.packs >= 1 && r.retired.loose > 0, "{r:?}");
8756
    assert_eq!(r.retired.kept, 0, "{r:?}");
8757
    let r = repo.gc(true).unwrap();
8758
    assert_eq!((r.retired.packs, r.retired.loose), (0, 0));
8759
    assert!(r.retired.kept > 0, "what the last gc retired is young");
8760
    // The reader opened before all of it still reads everything, from
8761
    // the packs it finds when what it loaded is gone.
8762
    assert_eq!(reader.log().unwrap().len(), 5);
8763
    for h in &heads[..4] {
8764
        reader.store().get_change(h).unwrap();
8765
    }
8766
    reader.refresh().unwrap();
8767
    assert_eq!(reader.log().unwrap().len(), 6);
8768
    let fresh = Repo::open(root).unwrap();
8769
    assert_eq!(
8770
        fresh.store().pack_count(),
8771
        1,
8772
        "retired packs are not loaded"
8773
    );
8774
}
8775
8776
/// oxygenhub#249: a repository opens when its store's pack listing names
8777
/// an index that is not there (deleted between the listing and the read).
8778
#[test]
8779
fn a_repository_opens_when_a_listed_index_is_gone() {
8780
    hermetic();
8781
    let backend = crate::store::reader_tests::racing(true);
8782
    let dyn_backend: std::sync::Arc<crate::store::Backend> = backend.clone();
8783
    crate::store::TEST_BACKEND.with(|t| *t.borrow_mut() = Some(dyn_backend));
8784
    let dir = tempfile::tempdir().unwrap();
8785
    let repo = Repo::init(dir.path()).unwrap();
8786
    write(dir.path(), "a.txt", b"a\n");
8787
    let h = repo.commit("a", &[]).unwrap();
8788
    repo.gc(true).unwrap();
8789
    let again = Repo::open(dir.path()).unwrap();
8790
    assert_eq!(again.store().pack_count(), 1);
8791
    assert_eq!(again.bookmark_heads().unwrap(), vec![h]);
8792
    // And when one is deleted between the listing and the read: a copy of
8793
    // the live pack, whose index goes as the store opens.
8794
    use crate::strata::Store as _;
8795
    let idx = backend
8796
        .list("pack-")
8797
        .unwrap()
8798
        .into_iter()
8799
        .map(|e| e.key)
8800
        .find(|k| k.ends_with(".idx") && k != "pack-0000.idx")
8801
        .unwrap();
8802
    let stem = idx.trim_end_matches(".idx");
8803
    for ext in ["pack", "idx"] {
8804
        let bytes = backend.get(&format!("{stem}.{ext}")).unwrap();
8805
        backend
8806
            .put_new(&format!("pack-copy.{ext}"), &bytes)
8807
            .unwrap();
8808
    }
8809
    *backend.doomed.lock().unwrap() = Some("pack-copy.idx".into());
8810
    let again = Repo::open(dir.path()).unwrap();
8811
    assert_eq!(again.store().pack_count(), 1);
8812
    assert_eq!(again.bookmark_heads().unwrap(), vec![h]);
8813
    assert!(!backend.has("pack-copy.idx").unwrap());
8814
    crate::store::TEST_BACKEND.with(|t| *t.borrow_mut() = None);
8815
}