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