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