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