OXYGENHUB
# 7ba155f20aa0 oxygen / crates / oxy-core / src / repo / tests.rs
185.5 KiB · Rust · last changed Scoped, expiring delegates, and revocation by the delegator 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
#[test]
1101
fn gc_packs_objects_and_history_still_works() {
1102
    hermetic();
1103
    let dir = tempfile::tempdir().unwrap();
1104
    let root = dir.path();
1105
    let mut repo = Repo::init(root).unwrap().with_home(root.join("home"));
1106
    repo.create_identity("Ada", "a@b", IdentityScope::User)
1107
        .unwrap();
1108
    repo.set_user_config("core.sign", "change").unwrap();
1109
    write(root, "a.txt", b"one\n");
1110
    let h1 = repo.commit("one", &[]).unwrap();
1111
    write(root, "a.txt", b"two\n");
1112
    write(root, "big.bin", &vec![0u8; 100_000]);
1113
    let h2 = repo.commit("two", &[]).unwrap();
1114
    // Several snapshots leave superseded working-copy versions behind.
1115
    for i in 0..5 {
1116
        write(root, "a.txt", format!("two\n{i}\n").as_bytes());
1117
        repo.snapshot("status").unwrap();
1118
    }
1119
    write(root, "a.txt", b"two\n");
1120
    repo.snapshot("status").unwrap();
1121
    let before = repo.store().list().unwrap();
1122
    assert!(repo.store().loose_count().unwrap() > 0);
1123
1124
    // With the default retention every operation's view is a root: nothing prunes.
1125
    let r = repo.gc(true).unwrap();
1126
    assert_eq!(r.packed.objects, before.len());
1127
    assert_eq!(r.pruned.objects, 0);
1128
    assert_eq!(repo.store().loose_count().unwrap(), 0);
1129
    assert_eq!(repo.store().list().unwrap(), before);
1130
1131
    // With zero retention only the current view is a root: superseded
1132
    // working copies go, everything reachable stays.
1133
    repo.config.set("core.op-retention", "0").unwrap();
1134
    repo.save_config().unwrap();
1135
    let repo = Repo::open(root).unwrap().with_home(root.join("home"));
1136
    let r = repo.gc(true).unwrap();
1137
    assert!(r.pruned.objects >= 5, "{r:?}");
1138
    let after = repo.store().list().unwrap();
1139
    assert!(after.len() < before.len());
1140
    assert!(after.contains(&h1) && after.contains(&h2));
1141
    for (_, op) in repo.op_log().unwrap() {
1142
        assert!(!op.command.is_empty(), "operation objects are all kept");
1143
    }
1144
    // Everything still works from the pruned, packed store.
1145
    assert_eq!(repo.bookmark_heads().unwrap(), vec![h2]);
1146
    assert!(matches!(
1147
        repo.verify_change(&h2).unwrap(),
1148
        SignatureStatus::Valid { .. }
1149
    ));
1150
    assert_eq!(repo.log().unwrap().len(), 3);
1151
    repo.checkout(&[h1], false, "checkout").unwrap();
1152
    assert_eq!(fs::read(root.join("a.txt")).unwrap(), b"one\n");
1153
    repo.checkout(&[h2], false, "checkout").unwrap();
1154
    assert_eq!(fs::read(root.join("big.bin")).unwrap().len(), 100_000);
1155
    assert!(!repo.snapshot("status").unwrap().changed);
1156
    // Grace period defers pruning of young garbage.
1157
    write(root, "a.txt", b"three\n");
1158
    repo.commit("three", &[]).unwrap();
1159
    let r = repo.gc(false).unwrap();
1160
    assert_eq!(r.pruned.objects, 0);
1161
    assert!(r.pruned.deferred > 0);
1162
    let r = repo.gc(true).unwrap();
1163
    assert!(r.pruned.objects > 0);
1164
    assert_eq!(repo.log().unwrap().len(), 4);
1165
}
1166
1167
#[test]
1168
fn describe_amend_abandon_heads() {
1169
    hermetic();
1170
    let dir = tempfile::tempdir().unwrap();
1171
    let root = dir.path();
1172
    let mut repo = Repo::init(root).unwrap().with_home(root.join("home"));
1173
    repo.create_identity("Ada", "a@b", IdentityScope::User)
1174
        .unwrap();
1175
    repo.set_user_config("core.sign", "change").unwrap();
1176
    write(root, "a.txt", b"one\n");
1177
    let h1 = repo.commit("first", &[]).unwrap();
1178
    write(root, "a.txt", b"one\ntwo\n");
1179
    let h2 = repo.commit("secnod", &[]).unwrap();
1180
    let id2 = repo.store().get_change(&h2).unwrap().change_id;
1181
1182
    // describe: same ChangeId, new hash, bookmark and working copy follow.
1183
    let h2b = repo.describe(&h2, "second").unwrap();
1184
    assert_ne!(h2b, h2);
1185
    let c = repo.store().get_change(&h2b).unwrap();
1186
    assert_eq!(
1187
        (c.change_id, c.message.as_str(), c.deps.clone()),
1188
        (id2, "second", vec![h1])
1189
    );
1190
    assert_eq!(repo.bookmark_heads().unwrap(), vec![h2b]);
1191
    assert!(matches!(
1192
        repo.verify_change(&h2b).unwrap(),
1193
        SignatureStatus::Valid { .. }
1194
    ));
1195
    let s = repo.snapshot("status").unwrap();
1196
    assert!(s.statuses.is_empty(), "{:?}", s.statuses);
1197
    assert_eq!(
1198
        repo.resolve_change(&id2.short(8)).unwrap(),
1199
        h2b,
1200
        "the old object is no longer reachable from the log"
1201
    );
1202
    // Describing a non-head rewrites its dependents (h2b → h2c') and the working copy.
1203
    let h1b = repo.describe(&h1, "first, described").unwrap();
1204
    assert_ne!(h1b, h1);
1205
    let heads = repo.bookmark_heads().unwrap();
1206
    assert_eq!(heads.len(), 1);
1207
    let top = repo.store().get_change(&heads[0]).unwrap();
1208
    assert_eq!((top.change_id, top.deps.clone()), (id2, vec![h1b]));
1209
    assert!(
1210
        matches!(
1211
            repo.verify_change(&heads[0]).unwrap(),
1212
            SignatureStatus::Valid { .. }
1213
        ),
1214
        "rewritten own change is re-signed"
1215
    );
1216
    let (_, wc) = repo.working_copy().unwrap();
1217
    assert_eq!(
1218
        wc.deps,
1219
        vec![heads[0]],
1220
        "the working copy follows the rewrite"
1221
    );
1222
    assert!(!repo.snapshot("status").unwrap().changed);
1223
    let snap = repo.load_state(&heads).unwrap().materialize();
1224
    assert!(
1225
        matches!(&snap.files["a.txt"].content, FileContent::Text { bytes, .. } if bytes == b"one\ntwo\n")
1226
    );
1227
1228
    // amend: fold an edit into the head; the result is one change from h1.
1229
    write(root, "a.txt", b"one\ntwo\nthree\n");
1230
    write(root, "b.txt", b"b\n");
1231
    let h2c = repo.amend(None).unwrap();
1232
    let c = repo.store().get_change(&h2c).unwrap();
1233
    assert_eq!(c.change_id, id2);
1234
    assert_eq!(c.message, "second");
1235
    assert_eq!(repo.bookmark_heads().unwrap(), vec![h2c]);
1236
    assert_eq!(
1237
        repo.log().unwrap().len(),
1238
        3,
1239
        "working copy, amended head, first"
1240
    );
1241
    let snap = repo.load_state(&[h2c]).unwrap().materialize();
1242
    assert!(
1243
        matches!(&snap.files["a.txt"].content, FileContent::Text { bytes, .. } if bytes == b"one\ntwo\nthree\n")
1244
    );
1245
    assert!(snap.files.contains_key("b.txt"));
1246
    assert!(!repo.snapshot("status").unwrap().changed);
1247
    assert!(
1248
        repo.amend(None).is_err(),
1249
        "clean working copy and no message"
1250
    );
1251
    let h2d = repo.amend(Some("second, amended")).unwrap();
1252
    assert_eq!(
1253
        repo.store().get_change(&h2d).unwrap().message,
1254
        "second, amended"
1255
    );
1256
1257
    // abandon: the head goes, its content stays as uncommitted work.
1258
    repo.abandon(&h2d).unwrap();
1259
    assert_eq!(
1260
        repo.bookmark_heads().unwrap(),
1261
        vec![h1b],
1262
        "the described first change is the head again"
1263
    );
1264
    let s = repo.snapshot("status").unwrap();
1265
    let paths: Vec<_> = s
1266
        .statuses
1267
        .iter()
1268
        .map(|p| (p.path.as_str(), p.status))
1269
        .collect();
1270
    assert_eq!(
1271
        paths,
1272
        vec![
1273
            ("a.txt", ChangeStatus::Modified),
1274
            ("b.txt", ChangeStatus::Added)
1275
        ]
1276
    );
1277
    assert_eq!(fs::read(root.join("a.txt")).unwrap(), b"one\ntwo\nthree\n");
1278
    let h3 = repo.commit("recommitted", &[]).unwrap();
1279
    assert_eq!(repo.bookmark_heads().unwrap(), vec![h3]);
1280
    // undo brings the abandoned head back.
1281
    repo.undo().unwrap();
1282
    repo.undo().unwrap();
1283
    assert_eq!(repo.bookmark_heads().unwrap(), vec![h2d]);
1284
1285
    // Abandoning a non-head whose dependent references its atoms reifies
1286
    // the references (here: a.txt vanishes with it, so the dependent's edit
1287
    // of a.txt is dropped with a note) instead of refusing; undo restores it.
1288
    let base = repo.bookmark_heads().unwrap()[0];
1289
    let base_change = repo.store().get_change(&base).unwrap();
1290
    let h1_now = base_change.deps[0];
1291
    let notes = repo.abandon(&h1_now).unwrap();
1292
    assert!(
1293
        !notes.is_empty(),
1294
        "the dependent's edit of a.txt was reified"
1295
    );
1296
    let heads = repo.bookmark_heads().unwrap();
1297
    let after = repo.load_state(&heads).unwrap().materialize();
1298
    assert!(
1299
        !after.files.contains_key("a.txt") && after.files.contains_key("b.txt"),
1300
        "{:?}",
1301
        after.files.keys()
1302
    );
1303
    repo.undo().unwrap();
1304
    assert_eq!(repo.bookmark_heads().unwrap(), vec![base]);
1305
    write(root, "c.txt", b"c\n");
1306
    let hc = repo.commit("c", &[]).unwrap();
1307
    write(root, "d.txt", b"d\n");
1308
    let hd = repo.commit("d", &[hc]).unwrap();
1309
    assert_eq!(repo.store().get_change(&hd).unwrap().deps, vec![hc]);
1310
    repo.abandon(&hc).unwrap();
1311
    let heads: BTreeSet<_> = repo.bookmark_heads().unwrap().into_iter().collect();
1312
    assert!(!heads.contains(&hc));
1313
    let d_now = heads
1314
        .iter()
1315
        .find(|h| repo.store().get_change(h).unwrap().message == "d")
1316
        .copied()
1317
        .unwrap();
1318
    assert!(
1319
        repo.store().get_change(&d_now).unwrap().deps.is_empty(),
1320
        "d inherited c's (empty) dependencies"
1321
    );
1322
    let s = repo.snapshot("status").unwrap();
1323
    assert_eq!(
1324
        s.statuses
1325
            .iter()
1326
            .map(|p| p.path.as_str())
1327
            .collect::<Vec<_>>(),
1328
        vec!["c.txt"],
1329
        "c's content is now uncommitted work"
1330
    );
1331
}
1332
1333
#[test]
1334
fn git_export_mirrors_history() {
1335
    hermetic();
1336
    if std::process::Command::new("git")
1337
        .arg("--version")
1338
        .output()
1339
        .is_err()
1340
    {
1341
        eprintln!("git not installed; skipping");
1342
        return;
1343
    }
1344
    let dir = tempfile::tempdir().unwrap();
1345
    let root = dir.path();
1346
    let mut repo = Repo::init(&root.join("r"))
1347
        .unwrap()
1348
        .with_home(root.join("home"));
1349
    repo.create_identity("Ada Lovelace", "[email protected]", IdentityScope::User)
1350
        .unwrap();
1351
    let r = root.join("r");
1352
    write(&r, "README.md", b"hello\n");
1353
    write(&r, "src/main.rs", b"fn main() {}\n");
1354
    let h1 = repo.commit("first", &[]).unwrap();
1355
    write(&r, "src/main.rs", b"fn main() { run(); }\n");
1356
    write(&r, "logo.png", b"\x89PNG\0\0");
1357
    let h2 = repo.commit("second", &[]).unwrap();
1358
1359
    let git_dir = root.join("mirror.git");
1360
    let rep = repo.git_export(&git_dir).unwrap();
1361
    assert_eq!((rep.exported, rep.skipped, rep.heads), (2, 0, 1));
1362
    let git = |args: &[&str]| -> String {
1363
        let out = std::process::Command::new("git")
1364
            .arg("-C")
1365
            .arg(&git_dir)
1366
            .args(args)
1367
            .output()
1368
            .unwrap();
1369
        assert!(
1370
            out.status.success(),
1371
            "{}",
1372
            String::from_utf8_lossy(&out.stderr)
1373
        );
1374
        String::from_utf8_lossy(&out.stdout).trim().to_string()
1375
    };
1376
    assert_eq!(git(&["log", "--format=%s", "main"]), "second\nfirst");
1377
    assert_eq!(git(&["show", "main:src/main.rs"]), "fn main() { run(); }");
1378
    assert_eq!(git(&["show", "main:README.md"]), "hello");
1379
    let body = git(&["log", "-1", "--format=%B", "main"]);
1380
    assert!(
1381
        body.contains(&format!("Oxy-Hash: {}", h2.to_hex())),
1382
        "{body}"
1383
    );
1384
    assert!(body.contains("Change-Id: "), "{body}");
1385
    assert_eq!(
1386
        git(&["log", "-1", "--format=%an <%ae>", "main"]),
1387
        "Ada Lovelace <[email protected]>"
1388
    );
1389
    assert_eq!(
1390
        git(&["ls-tree", "--name-only", "main"]),
1391
        "README.md\nlogo.png\nsrc"
1392
    );
1393
1394
    // Re-export is incremental.
1395
    let rep = repo.git_export(&git_dir).unwrap();
1396
    assert_eq!((rep.exported, rep.skipped), (0, 2));
1397
1398
    // An independent change makes two heads; the next state is one more
1399
    // commit on the linear branch whose tree is the union.
1400
    repo.checkout(&[h1], false, "checkout").unwrap();
1401
    write(&r, "other.txt", b"o\n");
1402
    let h3 = repo.commit("third", &[]).unwrap();
1403
    let rep = repo.git_export(&git_dir).unwrap();
1404
    assert_eq!((rep.exported, rep.heads), (1, 2));
1405
    assert_eq!(git(&["log", "--format=%s", "main"]), "third\nsecond\nfirst");
1406
    let parents = git(&["rev-list", "--parents", "-1", "main"]);
1407
    assert_eq!(parents.split(' ').count(), 2, "one parent: {parents}");
1408
    assert_eq!(git(&["show", "main:other.txt"]), "o");
1409
    assert_eq!(git(&["show", "main:src/main.rs"]), "fn main() { run(); }");
1410
    assert_eq!(
1411
        git(&["ls-tree", "--name-only", "main"]),
1412
        "README.md\nlogo.png\nother.txt\nsrc"
1413
    );
1414
    let body = git(&["log", "-1", "--format=%B", "main"]);
1415
    assert!(
1416
        body.contains(&format!("Oxy-Hash: {}", h3.to_hex())) && body.contains("Oxy-State: "),
1417
        "{body}"
1418
    );
1419
    // A rewrite is a new state whose one new change is the rewritten one.
1420
    repo.describe(&h3, "third, described").unwrap();
1421
    let rep = repo.git_export(&git_dir).unwrap();
1422
    assert_eq!(rep.exported, 1);
1423
    assert_eq!(
1424
        git(&["log", "-1", "--format=%s", "main"]),
1425
        "third, described"
1426
    );
1427
    assert_eq!(git(&["log", "--format=%s", "main"]).lines().count(), 4);
1428
    let _ = h2;
1429
}
1430
1431
#[test]
1432
fn git_import_reproduces_trees() {
1433
    hermetic();
1434
    if std::process::Command::new("git")
1435
        .arg("--version")
1436
        .output()
1437
        .is_err()
1438
    {
1439
        eprintln!("git not installed; skipping");
1440
        return;
1441
    }
1442
    let dir = tempfile::tempdir().unwrap();
1443
    let root = dir.path();
1444
    let g = root.join("src.git");
1445
    fs::create_dir_all(&g).unwrap();
1446
    let git = |args: &[&str]| -> String {
1447
        let out = std::process::Command::new("git")
1448
            .arg("-C")
1449
            .arg(&g)
1450
            .args([
1451
                "-c",
1452
                "user.name=Grace",
1453
                "-c",
1454
                "[email protected]",
1455
                "-c",
1456
                "commit.gpgsign=false",
1457
            ])
1458
            .args(args)
1459
            .output()
1460
            .unwrap();
1461
        assert!(
1462
            out.status.success(),
1463
            "git {args:?}: {}",
1464
            String::from_utf8_lossy(&out.stderr)
1465
        );
1466
        String::from_utf8_lossy(&out.stdout).trim().to_string()
1467
    };
1468
    git(&["init", "-q", "-b", "main"]);
1469
    write(&g, "README.md", b"# Hi\n");
1470
    write(&g, "src/lib.rs", b"pub fn a() {}\n");
1471
    git(&["add", "."]);
1472
    git(&["commit", "-q", "-m", "initial"]);
1473
    write(&g, "src/lib.rs", b"pub fn a() {}\npub fn b() {}\n");
1474
    write(&g, "run.sh", b"#!/bin/sh\n");
1475
    #[cfg(unix)]
1476
    {
1477
        use std::os::unix::fs::PermissionsExt;
1478
        fs::set_permissions(g.join("run.sh"), fs::Permissions::from_mode(0o755)).unwrap();
1479
    }
1480
    write(&g, "logo.png", b"\x89PNG\0\0\x01");
1481
    git(&["add", "."]);
1482
    git(&[
1483
        "commit",
1484
        "-q",
1485
        "-m",
1486
        "second\n\nChange-Id: 0123456789abcdef0123456789abcdef",
1487
    ]);
1488
    // A branch that edits README, merged back with a conflict-free merge.
1489
    git(&["checkout", "-q", "-b", "topic", "HEAD~1"]);
1490
    write(&g, "README.md", b"# Hi\n\nMore.\n");
1491
    git(&["commit", "-q", "-am", "readme"]);
1492
    git(&["checkout", "-q", "main"]);
1493
    git(&["merge", "-q", "--no-ff", "-m", "merge topic", "topic"]);
1494
    // A branch from the initial commit inserting at the same place as
1495
    // "second": concurrent in Oxygen too, so the merge commit is a resolution.
1496
    let initial = git(&["rev-list", "--max-parents=0", "HEAD"]);
1497
    git(&["checkout", "-q", "-b", "clash", &initial]);
1498
    write(&g, "src/lib.rs", b"pub fn a() {}\npub fn c() {}\n");
1499
    git(&["commit", "-q", "-am", "clash"]);
1500
    git(&["checkout", "-q", "main"]);
1501
    let _ = std::process::Command::new("git")
1502
        .arg("-C")
1503
        .arg(&g)
1504
        .args(["merge", "-q", "clash"])
1505
        .output();
1506
    write(
1507
        &g,
1508
        "src/lib.rs",
1509
        b"pub fn a() {}\npub fn b() {}\npub fn c() {}\n",
1510
    );
1511
    git(&["add", "."]);
1512
    git(&["commit", "-q", "-m", "resolve clash"]);
1513
    git(&["rm", "-q", "logo.png"]);
1514
    git(&["commit", "-q", "-m", "drop logo"]);
1515
    // A rename with a small edit is imported as a move of the same node.
1516
    git(&["mv", "src/lib.rs", "src/lib2.rs"]);
1517
    write(
1518
        &g,
1519
        "src/lib2.rs",
1520
        b"pub fn a() {}\npub fn b() {}\npub fn c() {}\npub fn d() {}\n",
1521
    );
1522
    git(&["add", "."]);
1523
    git(&["commit", "-q", "-m", "rename lib"]);
1524
    let expected_count: usize = git(&["rev-list", "--count", "main"]).parse().unwrap();
1525
1526
    let dest = root.join("oxy");
1527
    let repo = Repo::init(&dest).unwrap().with_home(root.join("home"));
1528
    let rep = repo.import_git(&g, "main").unwrap();
1529
    assert_eq!(rep.commits, expected_count);
1530
    assert_eq!(rep.merges, 2);
1531
    // The working copy equals the Git tree at main.
1532
    assert_eq!(
1533
        fs::read(dest.join("src/lib2.rs")).unwrap(),
1534
        b"pub fn a() {}\npub fn b() {}\npub fn c() {}\npub fn d() {}\n"
1535
    );
1536
    assert!(!dest.join("src/lib.rs").exists());
1537
    assert_eq!(
1538
        fs::read(dest.join("README.md")).unwrap(),
1539
        b"# Hi\n\nMore.\n"
1540
    );
1541
    assert!(!dest.join("logo.png").exists());
1542
    #[cfg(unix)]
1543
    {
1544
        use std::os::unix::fs::PermissionsExt;
1545
        assert!(
1546
            fs::metadata(dest.join("run.sh"))
1547
                .unwrap()
1548
                .permissions()
1549
                .mode()
1550
                & 0o111
1551
                != 0
1552
        );
1553
    }
1554
    assert!(
1555
        !repo.snapshot("status").unwrap().changed,
1556
        "clean after import"
1557
    );
1558
    let heads = repo.bookmark_heads().unwrap();
1559
    let st = repo.load_state(&heads).unwrap();
1560
    assert!(!st.materialize().is_conflicted());
1561
    assert_eq!(st.len(), expected_count);
1562
    let tip = repo
1563
        .log()
1564
        .unwrap()
1565
        .into_iter()
1566
        .find(|e| e.change.message.starts_with("rename lib"))
1567
        .unwrap();
1568
    let c = repo.store().get_change(&tip.hash).unwrap();
1569
    assert!(
1570
        c.tree_ops
1571
            .iter()
1572
            .any(|op| matches!(op, TreeOp::Move { name, .. } if name == "lib2.rs")),
1573
        "{:?}",
1574
        c.tree_ops
1575
    );
1576
    assert!(!c
1577
        .tree_ops
1578
        .iter()
1579
        .any(|op| matches!(op, TreeOp::AddNode { .. })));
1580
    // Messages carry Git trailers; the Change-Id trailer was honoured.
1581
    let log = repo.log().unwrap();
1582
    let second = log
1583
        .iter()
1584
        .find(|e| e.change.message.starts_with("second"))
1585
        .unwrap();
1586
    assert_eq!(
1587
        second.change.change_id,
1588
        ChangeId::from_hex("0123456789abcdef0123456789abcdef").unwrap()
1589
    );
1590
    assert!(second
1591
        .change
1592
        .message
1593
        .contains("Git-Author: Grace <[email protected]>"));
1594
    let resolve = log
1595
        .iter()
1596
        .find(|e| e.change.message.starts_with("resolve clash"))
1597
        .unwrap();
1598
    assert_eq!(
1599
        resolve.change.kind,
1600
        ChangeKind::Resolution,
1601
        "a conflicting Git merge becomes a resolution"
1602
    );
1603
    // Re-importing into another fresh repository gives the same ChangeIds.
1604
    let repo2 = Repo::init(&root.join("oxy2"))
1605
        .unwrap()
1606
        .with_home(root.join("home"));
1607
    repo2.import_git(&g, "main").unwrap();
1608
    let ids: BTreeSet<ChangeId> = repo
1609
        .log()
1610
        .unwrap()
1611
        .iter()
1612
        .filter(|e| !e.is_working_copy)
1613
        .map(|e| e.change.change_id)
1614
        .collect();
1615
    let ids2: BTreeSet<ChangeId> = repo2
1616
        .log()
1617
        .unwrap()
1618
        .iter()
1619
        .filter(|e| !e.is_working_copy)
1620
        .map(|e| e.change.change_id)
1621
        .collect();
1622
    assert_eq!(ids, ids2);
1623
    // Round trip back out to Git reproduces the tip tree.
1624
    let mirror = root.join("mirror.git");
1625
    repo.git_export(&mirror).unwrap();
1626
    let out = std::process::Command::new("git")
1627
        .arg("-C")
1628
        .arg(&mirror)
1629
        .args(["show", "main:src/lib2.rs"])
1630
        .output()
1631
        .unwrap();
1632
    assert_eq!(
1633
        String::from_utf8_lossy(&out.stdout),
1634
        "pub fn a() {}\npub fn b() {}\npub fn c() {}\npub fn d() {}\n"
1635
    );
1636
    let out = std::process::Command::new("git")
1637
        .arg("-C")
1638
        .arg(&mirror)
1639
        .args(["show", "main:src/lib.rs"])
1640
        .output()
1641
        .unwrap();
1642
    assert!(
1643
        !out.status.success(),
1644
        "the old path is gone from the export"
1645
    );
1646
}
1647
1648
#[test]
1649
fn checkpoints_accelerate_loading_and_stay_correct() {
1650
    hermetic();
1651
    let dir = tempfile::tempdir().unwrap();
1652
    let root = dir.path();
1653
    let mut repo = Repo::init(root).unwrap().with_home(root.join("home"));
1654
    repo.config.set("core.checkpoint-interval", "5").unwrap();
1655
    repo.save_config().unwrap();
1656
    let repo = Repo::open(root).unwrap().with_home(root.join("home"));
1657
    let mut hashes = Vec::new();
1658
    for i in 0..12 {
1659
        write(
1660
            root,
1661
            "a.txt",
1662
            format!(
1663
                "{}\n",
1664
                (0..=i)
1665
                    .map(|k| k.to_string())
1666
                    .collect::<Vec<_>>()
1667
                    .join("\n")
1668
            )
1669
            .as_bytes(),
1670
        );
1671
        write(root, &format!("f{i}.txt"), b"x\n");
1672
        hashes.push(repo.commit(&format!("c{i}"), &[]).unwrap());
1673
    }
1674
    let (_, cp) = repo
1675
        .latest_checkpoint("main")
1676
        .unwrap()
1677
        .expect("automatic checkpoint");
1678
    assert!(cp.count >= 5 && cp.count <= 12, "{}", cp.count);
1679
    // Loading through the checkpoint equals loading everything.
1680
    let heads = repo.bookmark_heads().unwrap();
1681
    let fast = repo.load_state(&heads).unwrap();
1682
    let full = repo.load_state_full(&heads).unwrap();
1683
    assert_eq!(fast.len(), full.len());
1684
    assert_eq!(fast.heads(), full.heads());
1685
    let (a, b) = (fast.materialize(), full.materialize());
1686
    assert_eq!(
1687
        a.files.keys().collect::<Vec<_>>(),
1688
        b.files.keys().collect::<Vec<_>>()
1689
    );
1690
    for (p, f) in &a.files {
1691
        assert_eq!(f.content, b.files[p].content, "{p}");
1692
    }
1693
    assert!(repo.load_state_checkpointed(&heads).unwrap().is_some());
1694
    // A head set that does not contain the checkpoint's heads falls back.
1695
    assert!(repo
1696
        .load_state_checkpointed(&[hashes[0]])
1697
        .unwrap()
1698
        .is_none());
1699
    assert_eq!(repo.load_state(&[hashes[0]]).unwrap().len(), 1);
1700
    // Everything else keeps working on top of the checkpoint.
1701
    assert!(!repo.snapshot("status").unwrap().changed);
1702
    let h = repo.describe(&hashes[3], "c3 described").unwrap();
1703
    assert_eq!(repo.store().get_change(&h).unwrap().message, "c3 described");
1704
    let (r, n, bytes) = repo.checkpoint().unwrap();
1705
    assert!(n >= 12 && bytes > 0);
1706
    assert_eq!(repo.latest_checkpoint("main").unwrap().unwrap().0, r);
1707
    write(root, "a.txt", b"after\n");
1708
    let h_after = repo.commit("after", &[]).unwrap();
1709
    let st = repo.load_state(&repo.bookmark_heads().unwrap()).unwrap();
1710
    assert!(st.contains(&h_after));
1711
    assert!(
1712
        matches!(&st.materialize().files["a.txt"].content, FileContent::Text { bytes, .. } if bytes == b"after\n")
1713
    );
1714
    assert_eq!(repo.log().unwrap().len(), 14);
1715
    // Checkpoints survive gc.
1716
    repo.gc(true).unwrap();
1717
    assert!(repo.latest_checkpoint("main").unwrap().is_some());
1718
    assert!(repo
1719
        .load_state_checkpointed(&repo.bookmark_heads().unwrap())
1720
        .unwrap()
1721
        .is_some());
1722
}
1723
1724
#[test]
1725
fn quick_status_for_prompts() {
1726
    hermetic();
1727
    let dir = tempfile::tempdir().unwrap();
1728
    let root = dir.path();
1729
    let origin = Repo::init(&root.join("origin")).unwrap();
1730
    let url = root.join("origin").to_string_lossy().to_string();
1731
    let a = Repo::clone(&url, &root.join("a"))
1732
        .unwrap()
1733
        .with_home(root.join("home"));
1734
    let ops_before = a.op_log().unwrap().len();
1735
    let info = a.quick_status().unwrap();
1736
    assert_eq!(
1737
        (
1738
            info.bookmark.as_str(),
1739
            info.heads,
1740
            info.dirty,
1741
            info.conflicted,
1742
            info.ahead,
1743
            info.behind
1744
        ),
1745
        ("main", 0, false, false, Some(0), Some(0))
1746
    );
1747
    write(&root.join("a"), "f.txt", b"f\n");
1748
    assert!(a.quick_status().unwrap().dirty, "a new file is dirty");
1749
    assert_eq!(
1750
        a.op_log().unwrap().len(),
1751
        ops_before,
1752
        "quick_status records nothing"
1753
    );
1754
    // A snapshotted but uncommitted change is still dirty.
1755
    a.snapshot("status").unwrap();
1756
    assert!(a.quick_status().unwrap().dirty);
1757
    a.commit("f", &[]).unwrap();
1758
    let info = a.quick_status().unwrap();
1759
    assert!(!info.dirty, "clean right after a commit");
1760
    assert_eq!((info.ahead, info.behind), (Some(1), Some(0)));
1761
    assert_eq!(
1762
        info.format("%b %c%d%x%A%D"),
1763
        format!("main {}+1", info.change_id)
1764
    );
1765
    assert_eq!(info.format("[%h heads] %a/%B %%"), "[1 heads] 1/0 %");
1766
    // Touching a file without changing it is not dirty; changing content of
1767
    // the same size is.
1768
    let p = root.join("a/f.txt");
1769
    let content = fs::read(&p).unwrap();
1770
    fs::write(&p, &content).unwrap();
1771
    assert!(!a.quick_status().unwrap().dirty);
1772
    fs::write(&p, b"g\n").unwrap();
1773
    assert!(a.quick_status().unwrap().dirty);
1774
    fs::write(&p, b"f\n").unwrap();
1775
    // Push, then a second clone commits and pushes: we are behind.
1776
    assert!(a.push("origin", false).unwrap()[0].ok);
1777
    assert_eq!(a.quick_status().unwrap().ahead, Some(0));
1778
    let b = Repo::clone(&url, &root.join("b"))
1779
        .unwrap()
1780
        .with_home(root.join("home-b"));
1781
    write(&root.join("b"), "g.txt", b"g\n");
1782
    b.commit("g", &[]).unwrap();
1783
    b.push("origin", false).unwrap();
1784
    a.fetch("origin").unwrap();
1785
    let info = a.quick_status().unwrap();
1786
    assert_eq!((info.ahead, info.behind), (Some(0), Some(1)));
1787
    assert_eq!(info.format("%A%D"), "-1");
1788
    let _ = origin;
1789
}
1790
1791
#[test]
1792
fn lazy_blobs_are_fetched_on_first_read() {
1793
    hermetic();
1794
    let dir = tempfile::tempdir().unwrap();
1795
    let root = dir.path();
1796
    let origin_dir = root.join("origin");
1797
    let origin = Repo::init(&origin_dir)
1798
        .unwrap()
1799
        .with_home(root.join("home"));
1800
    let url = origin_dir.to_string_lossy().to_string();
1801
    let big: Vec<u8> = (0..200_000u32).map(|i| (i % 251) as u8).collect(); // has NUL bytes: opaque
1802
    write(&origin_dir, "big.bin", &big);
1803
    write(&origin_dir, "small.bin", &[0u8, 1, 2]);
1804
    write(&origin_dir, "t.txt", b"t\n");
1805
    let h = origin.commit("blobs", &[]).unwrap();
1806
    let big_ref = Repo::blob_ref(&big);
1807
1808
    // Fetch only (no checkout) with a filter: the big blob stays absent.
1809
    let a = Repo::init_with_id(&root.join("a"), origin.id().unwrap())
1810
        .unwrap()
1811
        .with_home(root.join("home"));
1812
    let a = {
1813
        let mut a = a;
1814
        a.config.set("remote.origin.url", &url).unwrap();
1815
        a.config.set("filter.max-blob", "100K").unwrap();
1816
        a.save_config().unwrap();
1817
        a
1818
    };
1819
    assert_eq!(a.config.max_blob, Some(100 * 1024));
1820
    a.fetch("origin").unwrap();
1821
    assert!(a.store().has(&h));
1822
    assert!(!a.store().has(&big_ref), "withheld");
1823
    assert!(
1824
        a.store().has(&Repo::blob_ref(&[0u8, 1, 2])),
1825
        "small blob came along"
1826
    );
1827
    assert_eq!(a.lazy_remote(&big_ref).as_deref(), Some("origin"));
1828
1829
    // status and commit do not need it: adopt the state, edit a text file, commit.
1830
    let (op_ref, op) = a.head_op().unwrap();
1831
    let mut view = op.view.clone();
1832
    view.bookmarks.insert(
1833
        "main".into(),
1834
        a.store().put_state(&StateObject::new(vec![h])).unwrap(),
1835
    );
1836
    a.record_op(&[op_ref], "adopt", view).unwrap();
1837
    // Checkout reads the blob lazily, which fetches it.
1838
    a.checkout(&[h], true, "checkout").unwrap();
1839
    assert!(a.store().has(&big_ref), "fetched on first read");
1840
    assert_eq!(fs::read(root.join("a/big.bin")).unwrap(), big);
1841
    assert!(a.lazy_remote(&big_ref).is_none(), "no longer registered");
1842
    write(&root.join("a"), "t.txt", b"t2\n");
1843
    a.commit("text edit", &[]).unwrap();
1844
1845
    // clone --max-blob records the filter; the checkout fetches lazily.
1846
    let b = Repo::clone_with(&url, &root.join("b"), Some(1024), &[]).unwrap();
1847
    assert_eq!(b.config.max_blob, Some(1024));
1848
    assert_eq!(fs::read(root.join("b/big.bin")).unwrap(), big);
1849
    assert_eq!(parse_size("2M").unwrap(), 2 << 20);
1850
    assert!(parse_size("lots").is_err());
1851
}
1852
1853
#[test]
1854
fn sparse_checkout_materializes_only_chosen_paths() {
1855
    hermetic();
1856
    let dir = tempfile::tempdir().unwrap();
1857
    let root = dir.path();
1858
    let origin_dir = root.join("origin");
1859
    let origin = Repo::init(&origin_dir)
1860
        .unwrap()
1861
        .with_home(root.join("home"));
1862
    write(&origin_dir, "src/main.rs", b"fn main() {}\n");
1863
    write(&origin_dir, "src/lib.rs", b"pub fn a() {}\n");
1864
    write(&origin_dir, "docs/guide.md", b"# guide\n");
1865
    let logo: Vec<u8> = (0..50_000u32).map(|i| (i % 7) as u8).collect();
1866
    write(&origin_dir, "docs/logo.png", &logo);
1867
    write(&origin_dir, "README.md", b"# top\n");
1868
    let h1 = origin.commit("tree", &[]).unwrap();
1869
    let url = origin_dir.to_string_lossy().to_string();
1870
1871
    let a = Repo::clone_with(&url, &root.join("a"), None, &["src".into()])
1872
        .unwrap()
1873
        .with_home(root.join("home"));
1874
    assert_eq!(a.config.sparse_paths, vec!["src"]);
1875
    assert_eq!(a.config.max_blob, Some(0), "sparse implies lazy blobs");
1876
    assert!(root.join("a/src/main.rs").exists());
1877
    assert!(!root.join("a/docs").exists() && !root.join("a/README.md").exists());
1878
    assert!(
1879
        !a.store().has(&Repo::blob_ref(&logo)),
1880
        "out-of-scope blob never fetched"
1881
    );
1882
    assert!(
1883
        !a.snapshot("status").unwrap().changed,
1884
        "out-of-scope files are not removals"
1885
    );
1886
    assert!(!a.quick_status().unwrap().dirty);
1887
1888
    // Edits in scope commit normally and keep the rest of the tree intact.
1889
    write(
1890
        &root.join("a"),
1891
        "src/lib.rs",
1892
        b"pub fn a() {}\npub fn b() {}\n",
1893
    );
1894
    let h2 = a.commit("edit lib", &[]).unwrap();
1895
    let st = a.load_state(&[h2]).unwrap().materialize();
1896
    assert!(
1897
        st.files.contains_key("docs/guide.md"),
1898
        "the state still has everything"
1899
    );
1900
    assert!(a.push("origin", false).unwrap()[0].ok);
1901
    // Files created outside the scope are ignored by status.
1902
    write(&root.join("a"), "docs/new.md", b"ignored\n");
1903
    assert!(a.snapshot("status").unwrap().statuses.is_empty());
1904
1905
    // Widening the filter checks out the rest; narrowing leaves stray files alone.
1906
    let mut a = a;
1907
    a.config.set("filter.paths", "src,docs").unwrap();
1908
    a.save_config().unwrap();
1909
    let r = a
1910
        .checkout(&a.bookmark_heads().unwrap(), true, "widen")
1911
        .unwrap();
1912
    assert!(r.written >= 2);
1913
    assert_eq!(
1914
        fs::read(root.join("a/docs/logo.png")).unwrap(),
1915
        logo,
1916
        "now fetched lazily"
1917
    );
1918
    assert!(!root.join("a/README.md").exists());
1919
    // Origin sees the change made under a sparse checkout with the full tree intact.
1920
    origin.pull("origin").err();
1921
    let full = origin
1922
        .load_state(&origin.bookmark_heads().unwrap())
1923
        .unwrap()
1924
        .materialize();
1925
    assert!(
1926
        matches!(&full.files["src/lib.rs"].content, FileContent::Text { bytes, .. } if bytes == b"pub fn a() {}\npub fn b() {}\n")
1927
    );
1928
    assert!(full.files.contains_key("README.md"));
1929
    let _ = h1;
1930
}
1931
1932
#[test]
1933
fn shallow_clone_and_deepen() {
1934
    hermetic();
1935
    let dir = tempfile::tempdir().unwrap();
1936
    let root = dir.path();
1937
    let origin_dir = root.join("origin");
1938
    let origin = Repo::init(&origin_dir)
1939
        .unwrap()
1940
        .with_home(root.join("home"));
1941
    let mut hashes = Vec::new();
1942
    for i in 0..8 {
1943
        write(
1944
            &origin_dir,
1945
            "a.txt",
1946
            format!(
1947
                "{}\n",
1948
                (0..=i)
1949
                    .map(|k| k.to_string())
1950
                    .collect::<Vec<_>>()
1951
                    .join("\n")
1952
            )
1953
            .as_bytes(),
1954
        );
1955
        hashes.push(origin.commit(&format!("c{i}"), &[]).unwrap());
1956
    }
1957
    let url = origin_dir.to_string_lossy().to_string();
1958
    let a = Repo::clone_shallow(&url, &root.join("a"), 3, None, &[])
1959
        .unwrap()
1960
        .with_home(root.join("home"));
1961
    assert!(a.is_shallow());
1962
    assert_eq!(
1963
        fs::read_to_string(root.join("a/a.txt")).unwrap(),
1964
        "0\n1\n2\n3\n4\n5\n6\n7\n"
1965
    );
1966
    assert!(
1967
        a.store().has(&hashes[7]) && a.store().has(&hashes[5]),
1968
        "three levels present"
1969
    );
1970
    assert!(!a.store().has(&hashes[4]), "beyond the depth is absent");
1971
    assert_eq!(a.boundary(), [hashes[4]].into_iter().collect());
1972
    assert_eq!(
1973
        a.log().unwrap().len(),
1974
        9,
1975
        "the log shows every change from the checkpoint's metadata"
1976
    );
1977
    assert!(!a.snapshot("status").unwrap().changed);
1978
    assert_eq!(a.quick_status().unwrap().heads, 1);
1979
1980
    // Work continues on top of the shallow history and pushes back.
1981
    write(&root.join("a"), "a.txt", b"0\n1\n2\n3\n4\n5\n6\n7\n8\n");
1982
    let h_new = a.commit("c8", &[]).unwrap();
1983
    assert!(a.push("origin", false).unwrap()[0].ok);
1984
    assert_eq!(origin.bookmark_heads().unwrap(), vec![h_new]);
1985
    // Fetching new work from origin into the shallow clone works too.
1986
    write(&origin_dir, "b.txt", b"b\n");
1987
    origin.pull("origin").err();
1988
    let (_, wc) = origin.working_copy().unwrap();
1989
    let _ = wc;
1990
    origin
1991
        .checkout(&origin.bookmark_heads().unwrap(), true, "co")
1992
        .unwrap();
1993
    write(&origin_dir, "b.txt", b"b\n");
1994
    let h_b = origin.commit("b", &[]).unwrap();
1995
    let pr = a.pull("origin").unwrap();
1996
    assert!(pr.changed);
1997
    assert!(a.store().has(&h_b));
1998
    assert!(root.join("a/b.txt").exists());
1999
2000
    // Deepening fetches older history until the boundary is gone.
2001
    // Every commit also depends on the change that created the file, so two
2002
    // levels below the boundary hold h4, h3, and the root.
2003
    assert!(a.deepen("origin", 2).unwrap() >= 2);
2004
    assert!(a.store().has(&hashes[3]));
2005
    assert!(a.is_shallow());
2006
    a.deepen("origin", 100).unwrap();
2007
    assert!(!a.is_shallow(), "boundary reached the root");
2008
    assert!(a.store().has(&hashes[0]));
2009
    assert_eq!(
2010
        a.load_state_full(&a.bookmark_heads().unwrap())
2011
            .unwrap()
2012
            .len(),
2013
        10
2014
    );
2015
}
2016
2017
#[test]
2018
fn tags_are_immutable_named_states_and_travel() {
2019
    hermetic();
2020
    let dir = tempfile::tempdir().unwrap();
2021
    let root = dir.path();
2022
    let origin = Repo::init(&root.join("origin")).unwrap();
2023
    let url = root.join("origin").to_string_lossy().to_string();
2024
    let mut a = Repo::clone(&url, &root.join("a"))
2025
        .unwrap()
2026
        .with_home(root.join("home-a"));
2027
    let (key_a, _) = a
2028
        .create_identity("Ada", "[email protected]", IdentityScope::User)
2029
        .unwrap();
2030
    write(&root.join("a"), "f.txt", b"1\n");
2031
    let h1 = a.commit("one", &[]).unwrap();
2032
    write(&root.join("a"), "f.txt", b"1\n2\n");
2033
    let h2 = a.commit("two", &[]).unwrap();
2034
2035
    let t = a.tag_create("v1", &[h1], "first release").unwrap();
2036
    assert_eq!(
2037
        (t.heads.clone(), t.signer.as_deref()),
2038
        (vec![h1], Some("Ada"))
2039
    );
2040
    assert!(a.tag_create("v1", &[h2], "").is_err(), "immutable");
2041
    assert!(a.tag_create("bad/name", &[h2], "").is_err());
2042
    assert_eq!(a.tag_heads("v1").unwrap(), Some(vec![h1]));
2043
    assert_eq!(a.resolve_heads("v1").unwrap(), vec![h1]);
2044
    assert_eq!(a.resolve_heads("main").unwrap(), vec![h2]);
2045
    let (_, sa) = a.tag_attest("v1").unwrap().unwrap();
2046
    assert_eq!(sa.sigs[0].key, key_a);
2047
    // Checkout by tag.
2048
    a.checkout(&a.resolve_heads("v1").unwrap(), false, "co")
2049
        .unwrap();
2050
    assert_eq!(fs::read(root.join("a/f.txt")).unwrap(), b"1\n");
2051
    a.checkout(&a.bookmark_heads().unwrap(), false, "co")
2052
        .unwrap();
2053
2054
    // Push carries the tag; a second attestation for the name is refused.
2055
    let r = a.push("origin", false).unwrap();
2056
    assert!(r.iter().any(|x| x.name == "tags/v1" && x.ok), "{r:?}");
2057
    assert_eq!(origin.tag_heads("v1").unwrap(), Some(vec![h1]));
2058
    let mut forged = a
2059
        .tag_refs()
2060
        .unwrap()
2061
        .into_iter()
2062
        .find(|t| t.name == "v1")
2063
        .unwrap();
2064
    forged.state = origin
2065
        .store()
2066
        .put_state(&StateObject::new(vec![h2]))
2067
        .unwrap();
2068
    forged.heads = vec![h2];
2069
    forged.attestation = None;
2070
    let r = origin
2071
        .receive_push(Bundle::default(), vec![], None, vec![forged])
2072
        .unwrap();
2073
    assert!(!r[0].ok && r[0].reason.contains("immutable"), "{r:?}");
2074
2075
    // A clone gets the tag; a later tag arrives on fetch.
2076
    let b = Repo::clone(&url, &root.join("b"))
2077
        .unwrap()
2078
        .with_home(root.join("home-b"));
2079
    assert_eq!(b.tag_heads("v1").unwrap(), Some(vec![h1]));
2080
    assert!(b.tags().unwrap()[0].signer.as_deref() == Some("Ada"));
2081
    a.tag_create("v2", &[h2], "second").unwrap();
2082
    a.push("origin", false).unwrap();
2083
    let rep = b.fetch("origin").unwrap();
2084
    assert_eq!(rep.new_tags, 1);
2085
    assert_eq!(b.tag_heads("v2").unwrap(), Some(vec![h2]));
2086
2087
    // Under a policy, an unattested tag is refused and an attested one by the root passes.
2088
    a.policy_init().unwrap();
2089
    a.push("origin", false).unwrap();
2090
    let unattested = crate::protocol::TagRef {
2091
        name: "v3".into(),
2092
        state: origin
2093
            .store()
2094
            .put_state(&StateObject::new(vec![h2]))
2095
            .unwrap(),
2096
        heads: vec![h2],
2097
        attestation: None,
2098
    };
2099
    let r = origin
2100
        .receive_push(Bundle::default(), vec![], None, vec![unattested])
2101
        .unwrap();
2102
    assert!(!r[0].ok && r[0].reason.contains("attestation"), "{r:?}");
2103
    a.tag_create("v3", &[h2], "").unwrap();
2104
    let r = a.push("origin", false).unwrap();
2105
    assert!(r.iter().any(|x| x.name == "tags/v3" && x.ok), "{r:?}");
2106
    assert!(a.gc(true).is_ok());
2107
    assert_eq!(a.tags().unwrap().len(), 3, "tags survive gc");
2108
}
2109
2110
#[test]
2111
fn multiple_workspaces_share_a_repository() {
2112
    hermetic();
2113
    let dir = tempfile::tempdir().unwrap();
2114
    let root = dir.path();
2115
    let main_dir = root.join("main");
2116
    let repo = Repo::init(&main_dir).unwrap().with_home(root.join("home"));
2117
    write(&main_dir, "a.txt", b"a\n");
2118
    let h1 = repo.commit("a", &[]).unwrap();
2119
    assert_eq!(repo.workspaces().unwrap().len(), 1);
2120
2121
    // A second workspace elsewhere, checked out on the bookmark.
2122
    let ws_dir = root.join("ws2");
2123
    let ws = repo.workspace_add(&ws_dir, None).unwrap();
2124
    assert!(ws_dir.join(".oxy").is_file());
2125
    assert_eq!(fs::read(ws_dir.join("a.txt")).unwrap(), b"a\n");
2126
    assert_ne!(ws.workspace(), repo.workspace());
2127
    let list = repo.workspaces().unwrap();
2128
    assert_eq!(list.len(), 2);
2129
    assert!(list
2130
        .iter()
2131
        .any(|w| w.id == ws.workspace() && w.path == ws_dir.canonicalize().unwrap() && !w.current));
2132
    assert!(!ws.snapshot("status").unwrap().changed);
2133
2134
    // Work in the second workspace: its own working copy, shared bookmark.
2135
    write(&ws_dir, "b.txt", b"b\n");
2136
    let s = ws.snapshot("status").unwrap();
2137
    assert_eq!(s.statuses.len(), 1);
2138
    assert!(
2139
        !repo.snapshot("status").unwrap().changed,
2140
        "the first workspace is untouched"
2141
    );
2142
    let h2 = ws.commit("b from ws2", &[]).unwrap();
2143
    let mut heads = repo.bookmark_heads().unwrap();
2144
    heads.sort();
2145
    let mut want = vec![h1, h2];
2146
    want.sort();
2147
    assert_eq!(heads, want, "both workspaces see the bookmark move");
2148
    assert!(!main_dir.join("b.txt").exists());
2149
    repo.checkout(&repo.bookmark_heads().unwrap(), false, "co")
2150
        .unwrap();
2151
    assert!(main_dir.join("b.txt").exists());
2152
2153
    // Reopening from inside the second workspace finds the shared repository.
2154
    let reopened = Repo::open(&ws_dir).unwrap();
2155
    assert_eq!(reopened.workspace(), ws.workspace());
2156
    assert_eq!(reopened.id().unwrap(), repo.id().unwrap());
2157
    assert_eq!(reopened.quick_status().unwrap().heads, 2);
2158
2159
    // Workspaces cannot nest; forget drops one from the view but keeps files.
2160
    assert!(repo.workspace_add(&main_dir.join("inner"), None).is_err());
2161
    assert!(repo.workspace_forget(&repo.workspace()).is_err());
2162
    repo.workspace_forget(&ws.workspace()).unwrap();
2163
    assert_eq!(repo.workspaces().unwrap().len(), 1);
2164
    assert!(ws_dir.join("b.txt").exists());
2165
    assert!(
2166
        ws.snapshot("status").is_err(),
2167
        "a forgotten workspace is no longer in the view"
2168
    );
2169
2170
    // The snapshot lock: a fresh lock blocks a second, a stale one is taken over.
2171
    let lock = repo.lock_snapshot().unwrap();
2172
    drop(lock);
2173
    let lock_path = main_dir
2174
        .join(".oxy/workspaces")
2175
        .join(repo.workspace().to_hex())
2176
        .join("lock");
2177
    fs::write(&lock_path, "1").unwrap();
2178
    let old = std::time::SystemTime::now() - std::time::Duration::from_secs(120);
2179
    fs::File::open(&lock_path)
2180
        .unwrap()
2181
        .set_modified(old)
2182
        .unwrap();
2183
    assert!(repo.lock_snapshot().is_ok(), "stale lock taken over");
2184
}
2185
2186
#[test]
2187
fn attributes_binary_eol_nocompress_lockable() {
2188
    hermetic();
2189
    let dir = tempfile::tempdir().unwrap();
2190
    let root = dir.path();
2191
    let repo = Repo::init(root).unwrap().with_home(root.join("home"));
2192
    write(
2193
        root,
2194
        ".oxyattributes",
2195
        b"*.dat binary nocompress\n*.txt eol=crlf\nassets/** lockable\n",
2196
    );
2197
    write(root, "plain.dat", b"no nul bytes here\n");
2198
    write(root, "notes.txt", b"one\r\ntwo\r\n");
2199
    write(root, "assets/model.bin", b"\0model");
2200
    let h = repo.commit("attrs", &[]).unwrap();
2201
    let snap = repo.load_state(&[h]).unwrap().materialize();
2202
    assert!(
2203
        snap.files["plain.dat"].mode.opaque,
2204
        "binary attribute forces opaque without NUL bytes"
2205
    );
2206
    assert!(
2207
        matches!(&snap.files["notes.txt"].content, FileContent::Text { bytes, .. } if bytes == b"one\ntwo\n"),
2208
        "stored with LF"
2209
    );
2210
    assert!(
2211
        !repo.snapshot("status").unwrap().changed,
2212
        "CRLF on disk equals LF in the state"
2213
    );
2214
    // nocompress chunks pack raw.
2215
    let r = repo.gc(true).unwrap();
2216
    assert!(r.packed.objects > 0);
2217
    // Checkout writes CRLF for eol=crlf and makes lockable files read-only.
2218
    fs::remove_file(root.join("notes.txt")).unwrap();
2219
    repo.checkout(&[h], true, "co").unwrap();
2220
    assert_eq!(fs::read(root.join("notes.txt")).unwrap(), b"one\r\ntwo\r\n");
2221
    assert!(fs::metadata(root.join("assets/model.bin"))
2222
        .unwrap()
2223
        .permissions()
2224
        .readonly());
2225
    assert!(repo.lock_path("plain.dat").is_err(), "not lockable");
2226
    repo.lock_path("assets/model.bin").unwrap();
2227
    assert!(!fs::metadata(root.join("assets/model.bin"))
2228
        .unwrap()
2229
        .permissions()
2230
        .readonly());
2231
    assert!(repo.is_locked("assets/model.bin"));
2232
    write(root, "assets/model.bin", b"\0model2");
2233
    repo.commit("edit model", &[]).unwrap();
2234
    repo.unlock_path("assets/model.bin").unwrap();
2235
    assert!(fs::metadata(root.join("assets/model.bin"))
2236
        .unwrap()
2237
        .permissions()
2238
        .readonly());
2239
    // A later checkout can still overwrite a read-only lockable file.
2240
    repo.checkout(&[h], true, "co").unwrap();
2241
    assert_eq!(fs::read(root.join("assets/model.bin")).unwrap(), b"\0model");
2242
}
2243
2244
#[cfg(unix)]
2245
#[test]
2246
fn hooks_can_veto_observe_and_add_dependencies() {
2247
    use std::os::unix::fs::PermissionsExt;
2248
    hermetic();
2249
    let dir = tempfile::tempdir().unwrap();
2250
    let root = dir.path();
2251
    let mut repo = Repo::init(root).unwrap().with_home(root.join("home"));
2252
    let hooks = root.join(".oxy/hooks");
2253
    fs::create_dir_all(&hooks).unwrap();
2254
    let hook = |name: &str, body: &str| {
2255
        let p = hooks.join(name);
2256
        fs::write(&p, format!("#!/bin/sh\n{body}\n")).unwrap();
2257
        fs::set_permissions(&p, fs::Permissions::from_mode(0o755)).unwrap();
2258
    };
2259
    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");
2260
    hook("post-commit", "cat > \"$OXY_ROOT/.last-post-commit\"");
2261
    hook("post-checkout", "cat > \"$OXY_ROOT/.last-post-checkout\"");
2262
    hook("pre-push", "echo pushing blocked >&2; exit 3");
2263
    write(root, ".oxyignore", b".last-*\n");
2264
    write(root, "a.txt", b"a\n");
2265
    let err = repo.commit("WIP: nope", &[]).unwrap_err().to_string();
2266
    assert!(err.contains("pre-commit refused: no WIP commits"), "{err}");
2267
    let h1 = repo.commit("first", &[]).unwrap();
2268
    let pre = fs::read_to_string(root.join(".last-pre-commit")).unwrap();
2269
    assert!(
2270
        pre.contains("\"event\":\"pre-commit\"")
2271
            && pre.contains("\"path\":\"a.txt\"")
2272
            && pre.contains("\"message\":\"first\""),
2273
        "{pre}"
2274
    );
2275
    let post = fs::read_to_string(root.join(".last-post-commit")).unwrap();
2276
    assert!(post.contains(&h1.to_hex()), "{post}");
2277
    repo.checkout(&[h1], false, "co").unwrap();
2278
    assert!(fs::read_to_string(root.join(".last-post-checkout"))
2279
        .unwrap()
2280
        .contains("post-checkout"));
2281
    repo.config.set("remote.origin.url", "/nowhere").unwrap();
2282
    repo.save_config().unwrap();
2283
    let err = repo.push("origin", false).unwrap_err().to_string();
2284
    assert!(err.contains("pre-push refused: pushing blocked"), "{err}");
2285
2286
    // semantic-deps: only when enabled; adds an explicit dependency.
2287
    write(root, "b.txt", b"b\n");
2288
    hook(
2289
        "semantic-deps",
2290
        &format!(
2291
            "cat > \"$OXY_ROOT/.last-semantic\"; echo '{{\"deps\": [\"{}\"]}}'",
2292
            h1.to_hex()
2293
        ),
2294
    );
2295
    let h2 = repo.commit("b without hook", &[]).unwrap();
2296
    assert!(
2297
        repo.store().get_change(&h2).unwrap().deps.is_empty(),
2298
        "hook disabled by default"
2299
    );
2300
    repo.config.set("hooks.semantic-deps", "true").unwrap();
2301
    repo.save_config().unwrap();
2302
    write(root, "c.txt", b"c\n");
2303
    let h3 = repo.commit("c with hook", &[]).unwrap();
2304
    assert_eq!(repo.store().get_change(&h3).unwrap().deps, vec![h1]);
2305
    let sem = fs::read_to_string(root.join(".last-semantic")).unwrap();
2306
    assert!(
2307
        sem.contains("\"touched_paths\":[\"c.txt\"]") && sem.contains("candidate_deps"),
2308
        "{sem}"
2309
    );
2310
    assert_eq!(json_str("a\"b\\c\n"), "\"a\\\"b\\\\c\\n\"");
2311
}
2312
2313
#[test]
2314
fn amend_into_older_change_and_split() {
2315
    hermetic();
2316
    let dir = tempfile::tempdir().unwrap();
2317
    let root = dir.path();
2318
    let mut repo = Repo::init(root).unwrap().with_home(root.join("home"));
2319
    repo.create_identity("Ada", "a@b", IdentityScope::User)
2320
        .unwrap();
2321
    repo.set_user_config("core.sign", "change").unwrap();
2322
    write(root, "a.txt", b"one\ntwo\n");
2323
    let h0 = repo.commit("base", &[]).unwrap();
2324
    write(root, "a.txt", b"one\nTWO\n");
2325
    let h1 = repo.commit("edit two", &[]).unwrap();
2326
    write(root, "a.txt", b"one\nTWO\nthree\n");
2327
    let h2 = repo.commit("add three", &[]).unwrap();
2328
    let id1 = repo.store().get_change(&h1).unwrap().change_id;
2329
2330
    // Fixing the line h1 introduced folds into h1; h2 is rewritten on top.
2331
    write(root, "a.txt", b"one\nTWO!\nthree\n");
2332
    let h1b = repo.amend_into(&h1, None).unwrap();
2333
    assert_ne!(h1b, h1);
2334
    let c1b = repo.store().get_change(&h1b).unwrap();
2335
    assert_eq!(c1b.change_id, id1);
2336
    assert_eq!(c1b.deps, vec![h0]);
2337
    assert!(matches!(
2338
        repo.verify_change(&h1b).unwrap(),
2339
        SignatureStatus::Valid { .. }
2340
    ));
2341
    let heads = repo.bookmark_heads().unwrap();
2342
    assert_eq!(heads.len(), 1);
2343
    let top = repo.store().get_change(&heads[0]).unwrap();
2344
    assert_eq!(top.message, "add three");
2345
    assert_eq!(
2346
        top.deps.iter().copied().collect::<BTreeSet<_>>(),
2347
        [h0, h1b].into_iter().collect(),
2348
        "depends on the file's creator and the rewritten line"
2349
    );
2350
    let snap = repo.load_state(&heads).unwrap().materialize();
2351
    assert!(
2352
        matches!(&snap.files["a.txt"].content, FileContent::Text { bytes, .. } if bytes == b"one\nTWO!\nthree\n")
2353
    );
2354
    assert!(
2355
        !repo.snapshot("status").unwrap().changed,
2356
        "the working copy is clean after folding"
2357
    );
2358
    // Only h1b's own state shows the fix without "three".
2359
    let only = repo.load_state(&[h1b]).unwrap().materialize();
2360
    assert!(
2361
        matches!(&only.files["a.txt"].content, FileContent::Text { bytes, .. } if bytes == b"one\nTWO!\n")
2362
    );
2363
    assert_eq!(repo.log().unwrap().len(), 4);
2364
2365
    // An edit to a line introduced by h2 cannot fold into h1.
2366
    write(root, "a.txt", b"one\nTWO!\nthree!\n");
2367
    let err = repo.amend_into(&h1b, None).unwrap_err().to_string();
2368
    assert!(err.contains("introduced after"), "{err}");
2369
    assert!(
2370
        repo.snapshot("status").unwrap().statuses.len() == 1,
2371
        "nothing was changed by the refusal"
2372
    );
2373
    write(root, "a.txt", b"one\nTWO!\nthree\n");
2374
2375
    // Split the head that touches two files.
2376
    write(root, "b.txt", b"b\n");
2377
    write(root, "c.txt", b"c\n");
2378
    let h3 = repo.commit("b and c", &[]).unwrap();
2379
    let id3 = repo.store().get_change(&h3).unwrap().change_id;
2380
    let (p1, p2) = repo.split(&h3, &["b.txt".into()]).unwrap();
2381
    let c_1 = repo.store().get_change(&p1).unwrap();
2382
    let c_2 = repo.store().get_change(&p2).unwrap();
2383
    assert!(c_1.message.contains("part 1: b.txt"));
2384
    assert_eq!(c_2.change_id, id3);
2385
    let heads: BTreeSet<_> = repo.bookmark_heads().unwrap().into_iter().collect();
2386
    assert!(
2387
        heads.contains(&p1) && heads.contains(&p2),
2388
        "independent parts are both heads"
2389
    );
2390
    let snap = repo
2391
        .load_state(&repo.bookmark_heads().unwrap())
2392
        .unwrap()
2393
        .materialize();
2394
    assert!(snap.files.contains_key("b.txt") && snap.files.contains_key("c.txt"));
2395
    let only1 = repo.load_state(&[p1]).unwrap().materialize();
2396
    assert!(only1.files.contains_key("b.txt") && !only1.files.contains_key("c.txt"));
2397
    assert!(!repo.snapshot("status").unwrap().changed);
2398
    assert!(repo.split(&p2, &["nope.txt".into()]).is_err());
2399
    let _ = h2;
2400
}
2401
2402
#[test]
2403
fn identity_lifecycle() {
2404
    hermetic();
2405
    let dir = tempfile::tempdir().unwrap();
2406
    let root = dir.path();
2407
    let origin = Repo::init(&root.join("origin")).unwrap();
2408
    let url = root.join("origin").to_string_lossy().to_string();
2409
    let mut a = Repo::clone(&url, &root.join("a"))
2410
        .unwrap()
2411
        .with_home(root.join("home-a"));
2412
    a.set_user_config("core.sign", "change").unwrap();
2413
    let (key_a, _) = a
2414
        .create_identity("Ada", "[email protected]", IdentityScope::User)
2415
        .unwrap();
2416
    write(&root.join("a"), "a.txt", b"a\n");
2417
    let h1 = a.commit("one", &[]).unwrap();
2418
    assert!(a.policy_init().unwrap().applied);
2419
    assert!(a.push("origin", false).unwrap().iter().all(|r| r.ok));
2420
2421
    // Expiry: an identity that had expired when the change was made does not authenticate it.
2422
    let mut e = Repo::init(&root.join("e"))
2423
        .unwrap()
2424
        .with_home(root.join("home-e"));
2425
    e.set_user_config("core.sign", "change").unwrap();
2426
    e.create_identity_with(
2427
        "Eve",
2428
        "[email protected]",
2429
        IdentityScope::User,
2430
        Some(Hlc::now().wall_ms - 1),
2431
    )
2432
    .unwrap();
2433
    write(&root.join("e"), "e.txt", b"e\n");
2434
    let he = e.commit("late", &[]).unwrap();
2435
    assert!(
2436
        matches!(e.verify_change(&he).unwrap(), SignatureStatus::Invalid(m) if m.contains("expired"))
2437
    );
2438
    // Renewal re-issues the identity (same keys, new KeyId) with a later expiry.
2439
    let r = e
2440
        .renew_identity(Some(Hlc::now().wall_ms + 86_400_000))
2441
        .unwrap();
2442
    assert_eq!(e.identity(&r.new).unwrap().previous, Some(r.old));
2443
    write(&root.join("e"), "e.txt", b"e2\n");
2444
    let he2 = e.commit("in time", &[]).unwrap();
2445
    assert!(
2446
        matches!(e.verify_change(&he2).unwrap(), SignatureStatus::Valid { key, .. } if key == r.new)
2447
    );
2448
2449
    // Rotation: a fresh key; the old change still verifies; the policy follows.
2450
    let r = a.rotate_identity().unwrap();
2451
    assert_eq!(r.old, key_a);
2452
    assert_eq!(a.config.author_key, Some(r.new));
2453
    assert_eq!(a.identity(&r.new).unwrap().previous, Some(key_a));
2454
    assert!(r.policy.as_ref().unwrap().applied);
2455
    let (_, sp) = a.current_policy().unwrap().unwrap();
2456
    assert_eq!(
2457
        (sp.policy.serial, sp.policy.roots.clone()),
2458
        (2, vec![r.new])
2459
    );
2460
    assert!(
2461
        !sp.policy.revoked.contains(&key_a) && sp.policy.authorizes(&r.new, "main"),
2462
        "superseded, not revoked"
2463
    );
2464
    assert!(sp.policy.succeeds(&r.new, &key_a) && !sp.policy.succeeds(&key_a, &r.new));
2465
    assert!(
2466
        matches!(a.verify_change(&h1).unwrap(), SignatureStatus::Valid { key, revoked: false, .. } if key == key_a)
2467
    );
2468
    write(&root.join("a"), "a.txt", b"a2\n");
2469
    let h2 = a.commit("two", &[]).unwrap();
2470
    assert!(
2471
        matches!(a.verify_change(&h2).unwrap(), SignatureStatus::Valid { key, revoked: false, .. } if key == r.new)
2472
    );
2473
    // Origin accepts the rotated policy (signed by the old root) and the new key's change.
2474
    let res = a.push("origin", false).unwrap();
2475
    assert!(res.iter().all(|x| x.ok), "{res:?}");
2476
    assert_eq!(origin.current_policy().unwrap().unwrap().1.policy.serial, 2);
2477
    let key_a = r.new;
2478
2479
    // Delegation: Bob may sign on Ada's behalf. Delegates live in the
2480
    // identity object, so Ada's KeyId changes while her keys stay the same.
2481
    let mut b = Repo::clone(&url, &root.join("b"))
2482
        .unwrap()
2483
        .with_home(root.join("home-b"));
2484
    let (key_b, id_b) = b
2485
        .create_identity("Bob", "[email protected]", IdentityScope::User)
2486
        .unwrap();
2487
    let r = a.delegate_add(id_b.clone(), Scope::ALL, None).unwrap();
2488
    assert_eq!(r.old, key_a);
2489
    let key_a2 = r.new;
2490
    assert_eq!(
2491
        a.identity(&key_a2).unwrap().delegates,
2492
        vec![Delegate::full(key_b)]
2493
    );
2494
    assert_eq!(
2495
        a.identity(&key_a2).unwrap().ed25519_pk,
2496
        a.identity(&key_a).unwrap().ed25519_pk
2497
    );
2498
    assert!(
2499
        a.delegate_add(id_b.clone(), Scope::ALL, None).is_err(),
2500
        "already a delegate"
2501
    );
2502
    assert!(a.push("origin", false).unwrap().iter().all(|x| x.ok));
2503
    write(&root.join("a"), "a.txt", b"a3\n");
2504
    let h3 = a.commit("three", &[]).unwrap();
2505
    assert!(
2506
        matches!(a.verify_change(&h3).unwrap(), SignatureStatus::Valid { key, .. } if key == key_a2),
2507
        "the same secret signs under the new KeyId"
2508
    );
2509
    // A change authored by Ada but signed only by Bob verifies through the delegation.
2510
    a.set_user_config("core.sign", "seal").unwrap();
2511
    write(&root.join("a"), "a.txt", b"a4\n");
2512
    let h4 = a.commit("four", &[]).unwrap();
2513
    assert_eq!(a.verify_change(&h4).unwrap(), SignatureStatus::Unsigned);
2514
    let (_, sk_b) = b.secret_key().unwrap().unwrap();
2515
    a.store()
2516
        .put_signature(&h4, &sk_b.sign(Domain::Change, &key_b, &h4))
2517
        .unwrap();
2518
    assert!(
2519
        matches!(a.verify_change(&h4).unwrap(), SignatureStatus::Valid { key, .. } if key == key_b)
2520
    );
2521
    a.set_user_config("core.sign", "change").unwrap();
2522
    // Withdrawing the delegation re-issues the identity again.
2523
    let r = a.delegate_remove(&key_b).unwrap();
2524
    assert!(a.identity(&r.new).unwrap().delegates.is_empty());
2525
    assert!(a.delegate_remove(&key_b).is_err());
2526
    let key_a3 = r.new;
2527
    let res = a.push("origin", false).unwrap();
2528
    assert!(res.iter().all(|x| x.ok), "{res:?}");
2529
2530
    // Multi-signer policy: Bob becomes a root and the threshold rises to 2,
2531
    // both applied under the old threshold of 1. A grant then needs Bob too.
2532
    assert!(a.policy_root_add(id_b.clone()).unwrap().applied);
2533
    assert!(a.policy_root_add(id_b.clone()).is_err());
2534
    assert!(a.policy_set_threshold(3).is_err());
2535
    assert!(a.policy_set_threshold(2).unwrap().applied);
2536
    assert!(a.push("origin", false).unwrap().iter().all(|x| x.ok));
2537
    b.pull("origin").unwrap();
2538
    assert_eq!(
2539
        b.current_policy().unwrap().unwrap().1.policy.root_threshold,
2540
        2
2541
    );
2542
    let mut c = Repo::init(&root.join("c"))
2543
        .unwrap()
2544
        .with_home(root.join("home-c"));
2545
    let (key_c, id_c) = c
2546
        .create_identity("Cy", "[email protected]", IdentityScope::User)
2547
        .unwrap();
2548
    let serial_before = a.current_policy().unwrap().unwrap().1.policy.serial;
2549
    let proposal = a.policy_grant(id_c, None).unwrap();
2550
    assert!(!proposal.applied && proposal.sigs.len() == 1);
2551
    assert_eq!(proposal.policy.serial, serial_before + 1);
2552
    assert_eq!(
2553
        a.current_policy().unwrap().unwrap().1.policy.serial,
2554
        serial_before,
2555
        "a proposal changes nothing yet"
2556
    );
2557
    // Bob signs the proposal, handed over as a file, and it applies for him.
2558
    let bytes = proposal.signed().encode();
2559
    let signed = b
2560
        .policy_sign(SignedPolicy::decode(&bytes).unwrap())
2561
        .unwrap();
2562
    assert!(signed.applied && signed.sigs.len() == 2);
2563
    assert!(b
2564
        .current_policy()
2565
        .unwrap()
2566
        .unwrap()
2567
        .1
2568
        .policy
2569
        .authorizes(&key_c, "main"));
2570
    assert!(
2571
        b.policy_sign(signed.signed()).is_err(),
2572
        "a stale proposal is refused"
2573
    );
2574
    // Bob publishes it and Ada picks it up.
2575
    assert!(b
2576
        .push("origin", false)
2577
        .unwrap()
2578
        .iter()
2579
        .any(|x| x.name == "policy" && x.ok));
2580
    a.pull("origin").unwrap();
2581
    assert_eq!(
2582
        a.current_policy().unwrap().unwrap().1.policy.serial,
2583
        serial_before + 1
2584
    );
2585
    // A root cannot revoke itself; revoking Cy needs both roots but is recorded locally at once.
2586
    assert!(a.policy_revoke(&key_a3).is_err());
2587
    let u = a
2588
        .revoke_identity(&key_c, "left the project")
2589
        .unwrap()
2590
        .unwrap();
2591
    assert!(!u.applied);
2592
    assert!(a.is_revoked(&key_c).unwrap());
2593
    assert!(!b.is_revoked(&key_c).unwrap());
2594
    let u = b.policy_sign(u.signed()).unwrap();
2595
    assert!(u.applied && u.policy.is_revoked(&key_c));
2596
    assert!(b.is_revoked(&key_c).unwrap());
2597
    // Bob can revoke Ada's root key, leaving himself as the only root (threshold 2 would be unmeetable).
2598
    assert!(
2599
        b.policy_revoke(&key_a3).is_err(),
2600
        "would leave one root for a threshold of 2"
2601
    );
2602
    // Revoking one's own key without a policy root works locally: a plain marker plus attestation.
2603
    let key_c_own = c.config.author_key.unwrap();
2604
    assert!(c
2605
        .revoke_identity(&key_c_own, "lost laptop")
2606
        .unwrap()
2607
        .is_none());
2608
    assert!(c.is_revoked(&key_c_own).unwrap());
2609
    assert_eq!(key_c_own, key_c);
2610
}
2611
2612
#[test]
2613
fn renames_are_detected_and_tracked_as_moves() {
2614
    hermetic();
2615
    let dir = tempfile::tempdir().unwrap();
2616
    let root = dir.path();
2617
    let repo = Repo::init(root).unwrap().with_home(root.join("home"));
2618
    write(
2619
        root,
2620
        "src/old.rs",
2621
        b"fn a() {}\nfn b() {}\nfn c() {}\nfn d() {}\n",
2622
    );
2623
    write(root, "img.bin", b"\x89PNG\0\0\x01\x02");
2624
    write(root, "tiny.txt", b"x\n");
2625
    let h1 = repo.commit("base", &[]).unwrap();
2626
    let node_old = repo.load_state(&[h1]).unwrap().materialize().files["src/old.rs"].node;
2627
    let node_img = repo.load_state(&[h1]).unwrap().materialize().files["img.bin"].node;
2628
2629
    // Rename with a small edit, a binary moved unchanged, and a rewrite
2630
    // that shares nothing with the removed file.
2631
    fs::remove_file(root.join("src/old.rs")).unwrap();
2632
    write(
2633
        root,
2634
        "lib/new.rs",
2635
        b"fn a() {}\nfn b() {}\nfn c() {}\nfn e() {}\n",
2636
    );
2637
    fs::remove_file(root.join("img.bin")).unwrap();
2638
    write(root, "assets/img.bin", b"\x89PNG\0\0\x01\x02");
2639
    fs::remove_file(root.join("tiny.txt")).unwrap();
2640
    write(root, "other.txt", b"completely different\n");
2641
    let snap = repo.snapshot("status").unwrap();
2642
    let statuses: Vec<(&str, ChangeStatus)> = snap
2643
        .statuses
2644
        .iter()
2645
        .map(|s| (s.path.as_str(), s.status))
2646
        .collect();
2647
    assert_eq!(
2648
        statuses,
2649
        vec![
2650
            ("assets/img.bin", ChangeStatus::Renamed),
2651
            ("lib/new.rs", ChangeStatus::Renamed),
2652
            ("other.txt", ChangeStatus::Added),
2653
            ("src", ChangeStatus::Removed),
2654
            ("tiny.txt", ChangeStatus::Removed)
2655
        ]
2656
    );
2657
    let h2 = repo.commit("move things", &[]).unwrap();
2658
    let c = repo.store().get_change(&h2).unwrap();
2659
    let moves: Vec<_> = c
2660
        .tree_ops
2661
        .iter()
2662
        .filter(|op| matches!(op, TreeOp::Move { .. }))
2663
        .collect();
2664
    assert_eq!(moves.len(), 2, "{:?}", c.tree_ops);
2665
    assert!(c.tree_ops.iter().any(
2666
        |op| matches!(op, TreeOp::Move { node, name, .. } if *node == node_old && name == "new.rs")
2667
    ));
2668
    assert!(c.tree_ops.iter().any(
2669
        |op| matches!(op, TreeOp::Move { node, name, .. } if *node == node_img && name == "img.bin")
2670
    ));
2671
    let snap = repo.load_state(&[h2]).unwrap().materialize();
2672
    assert_eq!(
2673
        snap.files["lib/new.rs"].node, node_old,
2674
        "the node survives the rename"
2675
    );
2676
    assert!(
2677
        matches!(&snap.files["lib/new.rs"].content, FileContent::Text { bytes, .. } if bytes == b"fn a() {}\nfn b() {}\nfn c() {}\nfn e() {}\n")
2678
    );
2679
    assert!(!snap.files.contains_key("src/old.rs") && !snap.files.contains_key("src"));
2680
    assert!(render_change(
2681
        &c,
2682
        &repo.load_state(&[h1]).unwrap(),
2683
        &repo.load_state(&[h1]).unwrap().materialize()
2684
    )
2685
    .contains("R "));
2686
    // A fresh checkout reproduces the tree.
2687
    let other = tempfile::tempdir().unwrap();
2688
    let clone = Repo::clone(&root.to_string_lossy(), other.path()).unwrap();
2689
    assert_eq!(
2690
        fs::read(other.path().join("lib/new.rs")).unwrap(),
2691
        b"fn a() {}\nfn b() {}\nfn c() {}\nfn e() {}\n"
2692
    );
2693
    assert!(!other.path().join("src").exists());
2694
    assert!(!clone.snapshot("status").unwrap().changed);
2695
    // Similarity is line based, byte weighted.
2696
    assert_eq!(similarity(b"a\nb\n", b"a\nb\n"), 100);
2697
    assert_eq!(similarity(b"a\nb\nc\nd\n", b"a\nb\nx\ny\n"), 50);
2698
    assert_eq!(similarity(b"hello\n", b"world\n"), 0);
2699
    assert_eq!(similarity(b"", b"x\n"), 0);
2700
}
2701
2702
#[test]
2703
fn git_fetch_and_push_round_trip() {
2704
    hermetic();
2705
    if std::process::Command::new("git")
2706
        .arg("--version")
2707
        .output()
2708
        .is_err()
2709
    {
2710
        eprintln!("git not installed; skipping");
2711
        return;
2712
    }
2713
    let dir = tempfile::tempdir().unwrap();
2714
    let root = dir.path();
2715
    let git_in = |d: &Path, args: &[&str]| -> String {
2716
        let out = std::process::Command::new("git")
2717
            .arg("-C")
2718
            .arg(d)
2719
            .args([
2720
                "-c",
2721
                "user.name=Grace",
2722
                "-c",
2723
                "[email protected]",
2724
                "-c",
2725
                "commit.gpgsign=false",
2726
            ])
2727
            .args(args)
2728
            .output()
2729
            .unwrap();
2730
        assert!(
2731
            out.status.success(),
2732
            "git {args:?}: {}",
2733
            String::from_utf8_lossy(&out.stderr)
2734
        );
2735
        String::from_utf8_lossy(&out.stdout).trim().to_string()
2736
    };
2737
    // A bare "remote" and a work tree that pushes to it.
2738
    let remote = root.join("remote.git");
2739
    fs::create_dir_all(&remote).unwrap();
2740
    git_in(&remote, &["init", "-q", "--bare", "-b", "main"]);
2741
    let work = root.join("work");
2742
    git_in(
2743
        root,
2744
        &[
2745
            "clone",
2746
            "-q",
2747
            remote.to_str().unwrap(),
2748
            work.to_str().unwrap(),
2749
        ],
2750
    );
2751
    git_in(&work, &["checkout", "-q", "-b", "main"]);
2752
    write(&work, "README.md", b"# Project\n");
2753
    write(&work, "src/lib.rs", b"pub fn a() {}\n");
2754
    git_in(&work, &["add", "."]);
2755
    git_in(&work, &["commit", "-q", "-m", "initial"]);
2756
    write(&work, "src/lib.rs", b"pub fn a() {}\npub fn b() {}\n");
2757
    git_in(&work, &["commit", "-q", "-am", "second"]);
2758
    git_in(&work, &["push", "-q", "origin", "main"]);
2759
    let tip1 = git_in(&work, &["rev-parse", "HEAD"]);
2760
2761
    // Fetch into a fresh oxy repository.
2762
    let o = root.join("oxy");
2763
    let mut repo = Repo::init(&o).unwrap().with_home(root.join("home"));
2764
    repo.create_identity("Ada", "[email protected]", IdentityScope::User)
2765
        .unwrap();
2766
    let url = remote.to_string_lossy().to_string();
2767
    let r = repo.git_fetch(&url, "main").unwrap();
2768
    assert_eq!((r.commits, r.heads), (2, 1));
2769
    assert_eq!(
2770
        fs::read(o.join("src/lib.rs")).unwrap(),
2771
        b"pub fn a() {}\npub fn b() {}\n"
2772
    );
2773
    assert!(!repo.snapshot("status").unwrap().changed);
2774
    assert_eq!(
2775
        repo.git_fetch(&url, "main").unwrap().commits,
2776
        0,
2777
        "nothing new"
2778
    );
2779
2780
    // An oxy change, pushed back: one commit on top of the Git tip.
2781
    write(
2782
        &o,
2783
        "src/lib.rs",
2784
        b"pub fn a() {}\npub fn b() {}\npub fn c() {}\n",
2785
    );
2786
    write(&o, "NOTES.md", b"from oxy\n");
2787
    let h_oxy = repo.commit("add c and notes", &[]).unwrap();
2788
    let r = repo.git_push(&url, "main").unwrap();
2789
    assert_eq!(r.exported, 1, "{r:?}");
2790
    git_in(&work, &["pull", "-q", "--ff-only", "origin", "main"]);
2791
    assert_eq!(
2792
        git_in(&work, &["log", "--format=%s", "main"]),
2793
        "add c and notes\nsecond\ninitial"
2794
    );
2795
    assert_eq!(git_in(&work, &["rev-parse", "HEAD~1"]), tip1);
2796
    assert_eq!(fs::read(work.join("NOTES.md")).unwrap(), b"from oxy\n");
2797
    assert_eq!(git_in(&work, &["log", "-1", "--format=%an", "main"]), "Ada");
2798
    assert!(git_in(&work, &["log", "-1", "--format=%B", "main"])
2799
        .contains(&format!("Oxy-Hash: {}", h_oxy.to_hex())));
2800
    assert_eq!(
2801
        repo.git_push(&url, "main").unwrap().exported,
2802
        0,
2803
        "already pushed"
2804
    );
2805
2806
    // Git moves on; pushing without fetching is refused, fetching brings
2807
    // the commit in and the working copy follows.
2808
    write(&work, "README.md", b"# Project\n\nMore.\n");
2809
    git_in(&work, &["commit", "-q", "-am", "readme from git"]);
2810
    git_in(&work, &["push", "-q", "origin", "main"]);
2811
    let tip2 = git_in(&work, &["rev-parse", "HEAD"]);
2812
    assert!(repo
2813
        .git_push(&url, "main")
2814
        .unwrap_err()
2815
        .to_string()
2816
        .contains("fetch"));
2817
    let r = repo.git_fetch(&url, "main").unwrap();
2818
    assert_eq!(
2819
        (r.commits, r.heads),
2820
        (1, 2),
2821
        "the Git change and the oxy change commute"
2822
    );
2823
    assert_eq!(
2824
        fs::read(o.join("README.md")).unwrap(),
2825
        b"# Project\n\nMore.\n"
2826
    );
2827
    assert_eq!(fs::read(o.join("NOTES.md")).unwrap(), b"from oxy\n");
2828
    assert!(!repo.snapshot("status").unwrap().changed);
2829
    // Another oxy change pushes on top of Git's newest commit.
2830
    write(&o, "NOTES.md", b"from oxy\nagain\n");
2831
    repo.commit("notes again", &[]).unwrap();
2832
    assert_eq!(repo.git_push(&url, "main").unwrap().exported, 1);
2833
    git_in(&work, &["pull", "-q", "--ff-only", "origin", "main"]);
2834
    assert_eq!(git_in(&work, &["rev-parse", "HEAD~1"]), tip2);
2835
    assert_eq!(
2836
        fs::read(work.join("NOTES.md")).unwrap(),
2837
        b"from oxy\nagain\n"
2838
    );
2839
    assert_eq!(
2840
        git_in(&work, &["log", "--format=%s", "main"])
2841
            .lines()
2842
            .count(),
2843
        5
2844
    );
2845
}
2846
2847
/// Benchmark, not a gate: `cargo test --release -p oxy-core --lib bench_one_gibibyte -- --ignored --nocapture`.
2848
/// Commits, stores, clones, and reads back a 1 GiB incompressible file.
2849
#[test]
2850
#[ignore]
2851
fn bench_one_gibibyte_file() {
2852
    hermetic();
2853
    // /tmp is often a small tmpfs; `OXY_BENCH_DIR` picks a roomier disk.
2854
    let dir = match std::env::var_os("OXY_BENCH_DIR") {
2855
        Some(d) => tempfile::tempdir_in(d).unwrap(),
2856
        None => tempfile::tempdir().unwrap(),
2857
    };
2858
    let root = dir.path();
2859
    let repo = Repo::init(&root.join("r"))
2860
        .unwrap()
2861
        .with_home(root.join("home"));
2862
    let size = 1usize << 30;
2863
    let mut data = vec![0u8; size];
2864
    let mut x = 0x9e3779b97f4a7c15u64;
2865
    for chunk in data.chunks_mut(8) {
2866
        x ^= x << 13;
2867
        x ^= x >> 7;
2868
        x ^= x << 17;
2869
        let b = x.to_le_bytes();
2870
        chunk.copy_from_slice(&b[..chunk.len()]);
2871
    }
2872
    let t = std::time::Instant::now();
2873
    write(&root.join("r"), "big.bin", &data);
2874
    eprintln!("write 1 GiB to disk: {:.2?}", t.elapsed());
2875
    let t = std::time::Instant::now();
2876
    let h = repo.commit("big", &[]).unwrap();
2877
    eprintln!("commit (chunk + hash + store): {:.2?}", t.elapsed());
2878
    let t = std::time::Instant::now();
2879
    assert!(!repo.snapshot("status").unwrap().changed);
2880
    eprintln!("status on a clean 1 GiB working copy: {:.2?}", t.elapsed());
2881
    let t = std::time::Instant::now();
2882
    let objects = repo.store().list().unwrap().len();
2883
    eprintln!("objects stored: {objects} ({:.2?} to list)", t.elapsed());
2884
    let t = std::time::Instant::now();
2885
    let g = repo.gc(true).unwrap();
2886
    eprintln!("gc (pack): {:.2?} {g:?}", t.elapsed());
2887
    let t = std::time::Instant::now();
2888
    let clone = Repo::clone(&root.join("r").to_string_lossy(), &root.join("c")).unwrap();
2889
    eprintln!("clone (fetch + checkout): {:.2?}", t.elapsed());
2890
    let t = std::time::Instant::now();
2891
    let back = fs::read(root.join("c/big.bin")).unwrap();
2892
    assert_eq!(blake3::hash(&back), blake3::hash(&data));
2893
    eprintln!("read back and verify: {:.2?}", t.elapsed());
2894
    assert_eq!(clone.bookmark_heads().unwrap(), vec![h]);
2895
    let store_bytes: u64 = walkdir_size(&root.join("r/.oxy/objects"));
2896
    eprintln!(
2897
        "store size: {:.1} MiB for 1 GiB of data",
2898
        store_bytes as f64 / (1024.0 * 1024.0)
2899
    );
2900
}
2901
2902
fn walkdir_size(p: &Path) -> u64 {
2903
    let mut total = 0;
2904
    if let Ok(rd) = fs::read_dir(p) {
2905
        for e in rd.flatten() {
2906
            let path = e.path();
2907
            if path.is_dir() {
2908
                total += walkdir_size(&path);
2909
            } else if let Ok(m) = fs::metadata(&path) {
2910
                total += m.len();
2911
            }
2912
        }
2913
    }
2914
    total
2915
}
2916
2917
/// An opaque file whose size and mtime match the manifest is not read on
2918
/// the next snapshot: its blob comes from the manifest's stat cache.
2919
#[cfg(unix)]
2920
#[test]
2921
fn stat_cache_skips_reading_unchanged_opaque_files() {
2922
    use std::os::unix::fs::PermissionsExt;
2923
    hermetic();
2924
    let dir = tempfile::tempdir().unwrap();
2925
    let root = dir.path();
2926
    let repo = Repo::init(root).unwrap().with_home(root.join("home"));
2927
    let mut big = vec![0u8; 300 * 1024];
2928
    for (i, b) in big.iter_mut().enumerate() {
2929
        *b = (i as u32).wrapping_mul(2654435761).to_le_bytes()[1];
2930
    }
2931
    big[0] = 0;
2932
    write(root, "big.bin", &big);
2933
    write(root, "a.txt", b"text\n");
2934
    let h1 = repo.commit("base", &[]).unwrap();
2935
    let (_, _, m) = repo.read_manifest().unwrap().unwrap();
2936
    assert!(
2937
        m.entries["big.bin"].blob.is_some(),
2938
        "opaque files record their blob"
2939
    );
2940
    assert!(m.entries["a.txt"].blob.is_none());
2941
    let blob = m.entries["big.bin"].blob.unwrap();
2942
    assert!(repo.store().has(&blob));
2943
2944
    // Files modified within two seconds of the manifest are racy and still
2945
    // read; age the file so the cache applies, then snapshot to record it.
2946
    let old = std::time::SystemTime::now() - std::time::Duration::from_secs(30);
2947
    fs::File::options()
2948
        .write(true)
2949
        .open(root.join("big.bin"))
2950
        .unwrap()
2951
        .set_modified(old)
2952
        .unwrap();
2953
    assert!(!repo.snapshot("status").unwrap().changed);
2954
    // Now the file cannot be read at all; the snapshot succeeds without it.
2955
    fs::set_permissions(root.join("big.bin"), fs::Permissions::from_mode(0o000)).unwrap();
2956
    let snap = repo.snapshot("status").unwrap();
2957
    assert!(
2958
        !snap.changed && snap.statuses.is_empty(),
2959
        "{:?}",
2960
        snap.statuses
2961
    );
2962
    fs::set_permissions(root.join("big.bin"), fs::Permissions::from_mode(0o644)).unwrap();
2963
    // A real change (new mtime, new content) is seen and committed correctly.
2964
    let mut big2 = big.clone();
2965
    big2[10] ^= 0xff;
2966
    write(root, "big.bin", &big2);
2967
    let snap = repo.snapshot("status").unwrap();
2968
    assert_eq!(
2969
        snap.statuses
2970
            .iter()
2971
            .map(|s| (s.path.as_str(), s.status))
2972
            .collect::<Vec<_>>(),
2973
        vec![("big.bin", ChangeStatus::Modified)]
2974
    );
2975
    let h2 = repo.commit("edit", &[]).unwrap();
2976
    let files = repo.load_state(&[h2]).unwrap().materialize().files;
2977
    assert_eq!(
2978
        files["big.bin"].content,
2979
        FileContent::Opaque {
2980
            blobs: vec![Repo::blob_ref(&big2)]
2981
        }
2982
    );
2983
    // Checkout writes a manifest with blobs too, so the next status is cached.
2984
    repo.checkout(&[h1], false, "checkout").unwrap();
2985
    let (_, _, m) = repo.read_manifest().unwrap().unwrap();
2986
    assert_eq!(m.entries["big.bin"].blob, Some(Repo::blob_ref(&big)));
2987
    assert!(!repo.snapshot("status").unwrap().changed);
2988
}
2989
2990
#[test]
2991
fn status_json_lists_conflicts_with_contributors() {
2992
    hermetic();
2993
    let dir = tempfile::tempdir().unwrap();
2994
    let root = dir.path();
2995
    let repo = Repo::init(root).unwrap().with_home(root.join("home"));
2996
    write(root, "a.txt", b"one\n");
2997
    let h1 = repo.commit("base", &[]).unwrap();
2998
    write(root, "a.txt", b"one\nleft\n");
2999
    let ha = repo.commit("left", &[]).unwrap();
3000
    repo.checkout(&[h1], true, "checkout").unwrap();
3001
    write(root, "a.txt", b"one\nright\n");
3002
    let hb = repo.commit("right", &[]).unwrap();
3003
    repo.checkout(&[ha, hb], true, "checkout").unwrap();
3004
    let snap = repo.snapshot("status").unwrap();
3005
    assert!(snap.base_snapshot.is_conflicted());
3006
    let json = repo.status_json(&snap).unwrap();
3007
    let ida = repo.store().get_change(&ha).unwrap().change_id.to_hex();
3008
    let idb = repo.store().get_change(&hb).unwrap().change_id.to_hex();
3009
    assert!(json.contains("\"conflicted\":true"), "{json}");
3010
    assert!(
3011
        json.contains("\"kind\":\"text\",\"path\":\"a.txt\""),
3012
        "{json}"
3013
    );
3014
    assert!(json.contains(&ida) && json.contains(&idb), "{json}");
3015
    assert!(json.contains("\"resolved\":false"), "{json}");
3016
    assert!(json.starts_with('{') && json.ends_with('}'));
3017
    // Resolve and the report says so; a clean copy has no conflicts.
3018
    write(root, "a.txt", b"one\nleft\nright\n");
3019
    let snap = repo.snapshot("status").unwrap();
3020
    let json = repo.status_json(&snap).unwrap();
3021
    assert!(json.contains("\"resolved\":true"), "{json}");
3022
    repo.commit("resolve", &[]).unwrap();
3023
    let snap = repo.snapshot("status").unwrap();
3024
    let json = repo.status_json(&snap).unwrap();
3025
    assert!(
3026
        json.contains("\"clean\":true,\"conflicted\":false,\"paths\":[],\"conflicts\":[]"),
3027
        "{json}"
3028
    );
3029
}
3030
3031
#[test]
3032
fn ignore_rules_do_not_untrack_files() {
3033
    hermetic();
3034
    let dir = tempfile::tempdir().unwrap();
3035
    let root = dir.path();
3036
    let repo = Repo::init(root).unwrap().with_home(root.join("home"));
3037
    write(root, "src.c", b"int x;\n");
3038
    write(root, "build/out.o", b"\0obj");
3039
    write(root, "sub/keep.log", b"keep\n");
3040
    write(root, "sub/junk.log", b"junk\n");
3041
    write(root, ".oxyignore", b"/build\n*.log\n!sub/keep.log\n");
3042
    let snap = repo.snapshot("status").unwrap();
3043
    let added: Vec<&str> = snap.statuses.iter().map(|s| s.path.as_str()).collect();
3044
    assert_eq!(
3045
        added,
3046
        vec![".oxyignore", "src.c", "sub/keep.log"],
3047
        "anchored, glob, and negated rules"
3048
    );
3049
    let h1 = repo.commit("base", &[]).unwrap();
3050
    // Ignoring a tracked file changes nothing about it.
3051
    write(root, ".oxyignore", b"/build\n*.log\n!sub/keep.log\nsrc.c\n");
3052
    let snap = repo.snapshot("status").unwrap();
3053
    assert_eq!(
3054
        snap.statuses
3055
            .iter()
3056
            .map(|s| s.path.as_str())
3057
            .collect::<Vec<_>>(),
3058
        vec![".oxyignore"]
3059
    );
3060
    let h2 = repo.commit("ignore src.c", &[]).unwrap();
3061
    assert!(repo
3062
        .load_state(&[h2])
3063
        .unwrap()
3064
        .materialize()
3065
        .files
3066
        .contains_key("src.c"));
3067
    // Its edits are still seen, by status and by the prompt.
3068
    assert_eq!(repo.quick_dirty().unwrap(), Some(false));
3069
    write(root, "src.c", b"int x, y;\n");
3070
    assert_eq!(repo.quick_dirty().unwrap(), Some(true));
3071
    let snap = repo.snapshot("status").unwrap();
3072
    assert_eq!(
3073
        snap.statuses
3074
            .iter()
3075
            .map(|s| (s.path.as_str(), s.status))
3076
            .collect::<Vec<_>>(),
3077
        vec![("src.c", ChangeStatus::Modified)]
3078
    );
3079
    let h3 = repo.commit("edit src.c", &[]).unwrap();
3080
    assert!(
3081
        matches!(&repo.load_state(&[h3]).unwrap().materialize().files["src.c"].content, FileContent::Text { bytes, .. } if bytes == b"int x, y;\n")
3082
    );
3083
    // Deleting it on disk removes it, ignored or not; a checkout brings it back.
3084
    fs::remove_file(root.join("src.c")).unwrap();
3085
    let snap = repo.snapshot("status").unwrap();
3086
    assert_eq!(
3087
        snap.statuses
3088
            .iter()
3089
            .map(|s| (s.path.as_str(), s.status))
3090
            .collect::<Vec<_>>(),
3091
        vec![("src.c", ChangeStatus::Removed)]
3092
    );
3093
    repo.checkout(&[h3], true, "checkout").unwrap();
3094
    assert_eq!(fs::read(root.join("src.c")).unwrap(), b"int x, y;\n");
3095
    assert!(!repo.snapshot("status").unwrap().changed);
3096
    let _ = h1;
3097
}
3098
3099
#[test]
3100
fn split_works_on_non_heads_by_node() {
3101
    hermetic();
3102
    let dir = tempfile::tempdir().unwrap();
3103
    let root = dir.path();
3104
    let repo = Repo::init(root).unwrap().with_home(root.join("home"));
3105
    write(root, "a.txt", b"one\n");
3106
    write(root, "junk/x.lock", b"lock\n");
3107
    let h1 = repo.commit("work plus junk", &[]).unwrap();
3108
    write(root, "a.txt", b"one\ntwo\n");
3109
    let h2 = repo.commit("more work", &[]).unwrap();
3110
    assert_eq!(repo.store().get_change(&h2).unwrap().deps, vec![h1]);
3111
    let id1 = repo.store().get_change(&h1).unwrap().change_id;
3112
    // h1 is not a head: split it by node.
3113
    let (hj, h1b) = repo.split(&h1, &["junk".into()]).unwrap();
3114
    assert_ne!(h1b, h1);
3115
    assert_eq!(
3116
        repo.store().get_change(&h1b).unwrap().change_id,
3117
        id1,
3118
        "the rest keeps the ChangeId"
3119
    );
3120
    let junk = repo.store().get_change(&hj).unwrap();
3121
    assert!(junk.tree_ops.iter().all(
3122
        |op| matches!(op, TreeOp::AddNode { name, .. } if name == "junk" || name == "x.lock")
3123
    ));
3124
    let heads = repo.bookmark_heads().unwrap();
3125
    assert!(
3126
        heads.contains(&hj),
3127
        "the split-off part is a head of its own"
3128
    );
3129
    let snap = repo.load_state(&heads).unwrap().materialize();
3130
    assert!(
3131
        matches!(&snap.files["a.txt"].content, FileContent::Text { bytes, .. } if bytes == b"one\ntwo\n"),
3132
        "the dependent was rewritten onto the new hash"
3133
    );
3134
    assert!(snap.files.contains_key("junk/x.lock"));
3135
    let h2b = heads
3136
        .iter()
3137
        .find(|h| repo.store().get_change(h).unwrap().message == "more work")
3138
        .copied()
3139
        .unwrap();
3140
    assert_eq!(repo.store().get_change(&h2b).unwrap().deps, vec![h1b]);
3141
    assert!(!repo.snapshot("status").unwrap().changed);
3142
    // Abandoning the split-off head removes the junk from history.
3143
    repo.abandon(&hj).unwrap();
3144
    let heads = repo.bookmark_heads().unwrap();
3145
    let snap = repo.load_state(&heads).unwrap().materialize();
3146
    assert!(!snap.files.contains_key("junk/x.lock") && !snap.files.contains_key("junk"));
3147
    assert!(snap.files.contains_key("a.txt"));
3148
    // A dependent that touches the split-off paths blocks the split.
3149
    write(root, "junk/y.lock", b"y\n");
3150
    let hb = repo.commit("junk base", &[]).unwrap();
3151
    write(root, "junk/y.lock", b"yy\n");
3152
    write(root, "b.txt", b"b\n");
3153
    repo.commit("touches junk", &[]).unwrap();
3154
    let err = repo.split(&hb, &["junk".into()]).unwrap_err().to_string();
3155
    assert!(err.contains("depends on the split-off paths"), "{err}");
3156
}
3157
3158
#[test]
3159
fn bookmarks_switch_merge_and_push() {
3160
    hermetic();
3161
    let dir = tempfile::tempdir().unwrap();
3162
    let root = dir.path();
3163
    let origin = Repo::init(&root.join("origin")).unwrap();
3164
    let url = root.join("origin").to_string_lossy().to_string();
3165
    let mut repo = Repo::clone(&url, &root.join("r"))
3166
        .unwrap()
3167
        .with_home(root.join("home"));
3168
    let r = root.join("r");
3169
    write(&r, "a.txt", b"a\n");
3170
    let h_a = repo.commit("a", &[]).unwrap();
3171
    assert!(repo.push("origin", false).unwrap()[0].ok);
3172
3173
    // A bookmark at the working copy's base, then work on it.
3174
    assert!(repo.bookmark_create("bad name..", None).is_err());
3175
    assert!(repo.bookmark_create("-x", None).is_err());
3176
    assert_eq!(repo.bookmark_create("feature", None).unwrap(), vec![h_a]);
3177
    assert!(repo.bookmark_create("feature", None).is_err(), "exists");
3178
    repo.bookmark_switch("feature", false).unwrap();
3179
    assert_eq!(repo.config.bookmark, "feature");
3180
    write(&r, "a.txt", b"a\nb\n");
3181
    write(&r, "b.txt", b"b\n");
3182
    let h_b = repo.commit("b on feature", &[]).unwrap();
3183
    assert_eq!(
3184
        repo.bookmark_heads().unwrap(),
3185
        vec![h_b],
3186
        "b edits a.txt, so it depends on a"
3187
    );
3188
    assert_eq!(
3189
        repo.resolve_heads("main").unwrap(),
3190
        vec![h_a],
3191
        "main is untouched"
3192
    );
3193
    assert_eq!(
3194
        repo.resolve_change("feature").unwrap(),
3195
        h_b,
3196
        "a one-head bookmark names its change"
3197
    );
3198
    // Reopening keeps the workspace's bookmark.
3199
    let reopened = Repo::open(&r).unwrap().with_home(root.join("home"));
3200
    assert_eq!(reopened.config.bookmark, "feature");
3201
    // Back to main: b.txt goes away; work there.
3202
    repo.bookmark_switch("main", false).unwrap();
3203
    assert!(!r.join("b.txt").exists());
3204
    assert_eq!(fs::read(r.join("a.txt")).unwrap(), b"a\n");
3205
    write(&r, "c.txt", b"c\n");
3206
    let h_c = repo.commit("c on main", &[]).unwrap();
3207
    let list = repo.bookmarks().unwrap();
3208
    assert_eq!(
3209
        list.iter()
3210
            .map(|b| (b.name.as_str(), b.current))
3211
            .collect::<Vec<_>>(),
3212
        vec![("feature", false), ("main", true)]
3213
    );
3214
    assert_eq!(
3215
        list.iter().find(|b| b.name == "main").unwrap().ahead,
3216
        Some(1),
3217
        "c is not on origin yet"
3218
    );
3219
    // Merge feature into main: the union, both heads, no merge change.
3220
    let m = repo.merge("feature").unwrap();
3221
    assert!(m.changed && m.checked_out);
3222
    let mut want = vec![h_b, h_c];
3223
    want.sort();
3224
    assert_eq!(m.heads, want);
3225
    assert_eq!(fs::read(r.join("b.txt")).unwrap(), b"b\n");
3226
    assert!(!repo.merge("feature").unwrap().changed, "already merged");
3227
    assert!(repo.merge("main").is_err());
3228
    // The other bookmark can be pushed by name and appears at origin.
3229
    assert!(repo.push_bookmark("origin", "feature", false).unwrap()[0].ok);
3230
    assert_eq!(origin.resolve_heads("feature").unwrap(), vec![h_b]);
3231
    assert!(repo.push("origin", false).unwrap()[0].ok);
3232
    assert_eq!(
3233
        repo.bookmarks()
3234
            .unwrap()
3235
            .iter()
3236
            .find(|b| b.name == "main")
3237
            .unwrap()
3238
            .ahead,
3239
        Some(0)
3240
    );
3241
    // A second workspace inherits the current bookmark and can switch independently.
3242
    let ws = repo.workspace_add(&root.join("ws"), None).unwrap();
3243
    assert_eq!(ws.config.bookmark, "main");
3244
    let mut ws = ws;
3245
    ws.bookmark_switch("feature", false).unwrap();
3246
    assert_eq!(
3247
        Repo::open(&r).unwrap().config.bookmark,
3248
        "main",
3249
        "the first workspace is unaffected"
3250
    );
3251
    assert!(
3252
        repo.bookmark_delete("feature").is_err(),
3253
        "current bookmark of another workspace"
3254
    );
3255
    ws.bookmark_switch("main", false).unwrap();
3256
    // Set and delete.
3257
    assert_eq!(repo.bookmark_set("feature", &[h_a]).unwrap(), vec![h_a]);
3258
    assert!(repo.bookmark_delete("main").is_err(), "current here");
3259
    repo.bookmark_delete("feature").unwrap();
3260
    assert!(repo.resolve_heads("feature").is_err());
3261
    assert!(repo.bookmark_set("feature", &[h_a]).is_err());
3262
    assert!(
3263
        repo.checkout(&[h_a], false, "checkout").is_ok(),
3264
        "changes of a deleted bookmark remain"
3265
    );
3266
}
3267
3268
#[test]
3269
fn oxygen_subrepos_pin_follow_and_update() {
3270
    hermetic();
3271
    let dir = tempfile::tempdir().unwrap();
3272
    let root = dir.path();
3273
    // A library repository with two commits, and a bare-ish origin for it.
3274
    let lib_origin = Repo::init(&root.join("lib-origin")).unwrap();
3275
    let lib_url = root.join("lib-origin").to_string_lossy().to_string();
3276
    let lib = Repo::clone(&lib_url, &root.join("lib"))
3277
        .unwrap()
3278
        .with_home(root.join("home"));
3279
    write(&root.join("lib"), "lib.txt", b"v1\n");
3280
    let l1 = lib.commit("lib v1", &[]).unwrap();
3281
    assert!(lib.push("origin", false).unwrap()[0].ok);
3282
    let _ = lib_origin;
3283
3284
    // The application (a clone of its own origin) adds it as a subrepo.
3285
    let app_origin = Repo::init(&root.join("app-origin")).unwrap();
3286
    let app_url = root.join("app-origin").to_string_lossy().to_string();
3287
    let _ = app_origin;
3288
    let app_dir = root.join("app");
3289
    let app = Repo::clone(&app_url, &app_dir)
3290
        .unwrap()
3291
        .with_home(root.join("home"));
3292
    write(&app_dir, "main.txt", b"app\n");
3293
    let pin = app.submodule_add(&lib_url, "libs/lib", None).unwrap();
3294
    assert!(matches!(&pin, crate::subrepo::Pin::Oxy { heads, .. } if heads == &vec![l1]));
3295
    assert!(app_dir.join(".oxymodules").exists() && app_dir.join("libs/lib/.oxy").is_dir());
3296
    let snap = app.snapshot("status").unwrap();
3297
    let paths: Vec<&str> = snap.statuses.iter().map(|s| s.path.as_str()).collect();
3298
    assert_eq!(
3299
        paths,
3300
        vec![".oxymodules", "libs/lib", "main.txt"],
3301
        "the nested files are not walked"
3302
    );
3303
    let a1 = app.commit("app with lib", &[]).unwrap();
3304
    let files = app.load_state(&[a1]).unwrap().materialize().files;
3305
    assert_eq!(files["libs/lib"].kind, NodeKind::Subrepo);
3306
    assert!(!files.contains_key("libs/lib/lib.txt"));
3307
    assert!(!app.snapshot("status").unwrap().changed);
3308
    let subs = app.subrepos().unwrap();
3309
    assert_eq!(subs.len(), 1);
3310
    assert_eq!(subs[0].actual.as_ref(), Some(&subs[0].pin));
3311
3312
    // Advance the nested repository: the parent sees a modified pin.
3313
    let nested = Repo::open(&app_dir.join("libs/lib"))
3314
        .unwrap()
3315
        .with_home(root.join("home"));
3316
    write(&app_dir.join("libs/lib"), "lib.txt", b"v2\n");
3317
    let l2 = nested.commit("lib v2", &[]).unwrap();
3318
    assert!(nested.push("origin", false).unwrap()[0].ok);
3319
    let snap = app.snapshot("status").unwrap();
3320
    assert_eq!(
3321
        snap.statuses
3322
            .iter()
3323
            .map(|s| (s.path.as_str(), s.status))
3324
            .collect::<Vec<_>>(),
3325
        vec![("libs/lib", ChangeStatus::Modified)]
3326
    );
3327
    let a2 = app.commit("bump lib", &[]).unwrap();
3328
    // Checking out the older app state moves the nested repository back.
3329
    let r = app.checkout(&[a1], false, "checkout").unwrap();
3330
    assert!(r.notes.is_empty(), "{:?}", r.notes);
3331
    assert_eq!(fs::read(app_dir.join("libs/lib/lib.txt")).unwrap(), b"v1\n");
3332
    assert_eq!(
3333
        Repo::open(&app_dir.join("libs/lib"))
3334
            .unwrap()
3335
            .bookmark_heads()
3336
            .unwrap(),
3337
        vec![l1]
3338
    );
3339
    assert!(!app.snapshot("status").unwrap().changed);
3340
    // A dirty nested repository is left alone and reported.
3341
    write(&app_dir.join("libs/lib"), "scratch.txt", b"wip\n");
3342
    let r = app.checkout(&[a2], false, "checkout").unwrap();
3343
    assert!(
3344
        r.notes.iter().any(|n| n.contains("uncommitted")),
3345
        "{:?}",
3346
        r.notes
3347
    );
3348
    assert_eq!(fs::read(app_dir.join("libs/lib/lib.txt")).unwrap(), b"v1\n");
3349
    fs::remove_file(app_dir.join("libs/lib/scratch.txt")).unwrap();
3350
    let r = app.submodule_update(false, &[]).unwrap();
3351
    assert_eq!(r, vec![("libs/lib".to_string(), SubrepoSync::Updated)]);
3352
    assert_eq!(fs::read(app_dir.join("libs/lib/lib.txt")).unwrap(), b"v2\n");
3353
    let _ = l2;
3354
3355
    // A fresh clone of the app has the pin but no nested repository until update --init.
3356
    assert!(app.push("origin", false).unwrap()[0].ok);
3357
    let clone_dir = root.join("app-clone");
3358
    let clone = Repo::clone(&app_url, &clone_dir)
3359
        .unwrap()
3360
        .with_home(root.join("home"));
3361
    assert!(!clone_dir.join("libs/lib/.oxy").exists());
3362
    assert_eq!(
3363
        clone.submodule_update(false, &[]).unwrap(),
3364
        vec![("libs/lib".to_string(), SubrepoSync::Missing)]
3365
    );
3366
    assert_eq!(
3367
        clone.submodule_update(true, &[]).unwrap(),
3368
        vec![("libs/lib".to_string(), SubrepoSync::Updated)]
3369
    );
3370
    assert_eq!(
3371
        fs::read(clone_dir.join("libs/lib/lib.txt")).unwrap(),
3372
        b"v2\n"
3373
    );
3374
    assert!(!clone.snapshot("status").unwrap().changed);
3375
    // Removing the subrepo leaves the directory and drops the node.
3376
    clone.submodule_remove("libs/lib").unwrap();
3377
    let snap = clone.snapshot("status").unwrap();
3378
    assert!(
3379
        snap.statuses
3380
            .iter()
3381
            .any(|s| s.path == "libs/lib" && s.status == ChangeStatus::Removed),
3382
        "{:?}",
3383
        snap.statuses
3384
    );
3385
    let c = clone.commit("drop lib", &[]).unwrap();
3386
    assert!(!clone
3387
        .load_state(&[c])
3388
        .unwrap()
3389
        .materialize()
3390
        .files
3391
        .contains_key("libs/lib"));
3392
    assert!(clone_dir.join("libs/lib/lib.txt").exists());
3393
    assert!(
3394
        !clone.snapshot("status").unwrap().changed,
3395
        "an unregistered nested repository is ignored"
3396
    );
3397
}
3398
3399
#[test]
3400
fn git_submodules_import_and_export_as_gitlinks() {
3401
    hermetic();
3402
    if std::process::Command::new("git")
3403
        .arg("--version")
3404
        .output()
3405
        .is_err()
3406
    {
3407
        eprintln!("git not installed; skipping");
3408
        return;
3409
    }
3410
    let dir = tempfile::tempdir().unwrap();
3411
    let root = dir.path();
3412
    let git_in = |d: &Path, args: &[&str]| -> String {
3413
        let out = std::process::Command::new("git")
3414
            .arg("-C")
3415
            .arg(d)
3416
            .args([
3417
                "-c",
3418
                "user.name=Grace",
3419
                "-c",
3420
                "[email protected]",
3421
                "-c",
3422
                "commit.gpgsign=false",
3423
                "-c",
3424
                "protocol.file.allow=always",
3425
            ])
3426
            .args(args)
3427
            .output()
3428
            .unwrap();
3429
        assert!(
3430
            out.status.success(),
3431
            "git {args:?}: {}",
3432
            String::from_utf8_lossy(&out.stderr)
3433
        );
3434
        String::from_utf8_lossy(&out.stdout).trim().to_string()
3435
    };
3436
    let sub = root.join("sub");
3437
    fs::create_dir_all(&sub).unwrap();
3438
    git_in(&sub, &["init", "-q", "-b", "main"]);
3439
    write(&sub, "s.txt", b"sub\n");
3440
    git_in(&sub, &["add", "."]);
3441
    git_in(&sub, &["commit", "-q", "-m", "sub initial"]);
3442
    let sub_sha = git_in(&sub, &["rev-parse", "HEAD"]);
3443
    let g = root.join("main.git");
3444
    fs::create_dir_all(&g).unwrap();
3445
    git_in(&g, &["init", "-q", "-b", "main"]);
3446
    write(&g, "README.md", b"# app\n");
3447
    git_in(&g, &["add", "."]);
3448
    git_in(&g, &["commit", "-q", "-m", "initial"]);
3449
    git_in(
3450
        &g,
3451
        &[
3452
            "submodule",
3453
            "add",
3454
            "-q",
3455
            sub.to_str().unwrap(),
3456
            "vendor/sub",
3457
        ],
3458
    );
3459
    git_in(&g, &["commit", "-q", "-m", "add submodule"]);
3460
3461
    let dest = root.join("oxy");
3462
    let repo = Repo::init(&dest).unwrap().with_home(root.join("home"));
3463
    let rep = repo.import_git(&g, "main").unwrap();
3464
    assert_eq!((rep.commits, rep.submodules), (2, 1));
3465
    let files = repo
3466
        .load_state(&repo.bookmark_heads().unwrap())
3467
        .unwrap()
3468
        .materialize()
3469
        .files;
3470
    assert_eq!(files["vendor/sub"].kind, NodeKind::Subrepo);
3471
    let FileContent::Opaque { blobs } = &files["vendor/sub"].content else {
3472
        panic!()
3473
    };
3474
    assert_eq!(
3475
        crate::subrepo::Pin::decode(&repo.read_blob(&blobs[0]).unwrap()).unwrap(),
3476
        crate::subrepo::Pin::Git {
3477
            sha: sub_sha.clone(),
3478
            branch: "HEAD".into()
3479
        }
3480
    );
3481
    let modules =
3482
        crate::subrepo::Modules::parse(&fs::read_to_string(dest.join(".oxymodules")).unwrap());
3483
    assert_eq!(modules.entries["vendor/sub"].url, sub.to_string_lossy());
3484
    assert!(modules.entries["vendor/sub"].git);
3485
    assert!(
3486
        files.contains_key(".gitmodules"),
3487
        "the Git file is kept for round trips"
3488
    );
3489
    assert!(
3490
        !dest.join("vendor/sub/.git").exists(),
3491
        "not cloned until update --init"
3492
    );
3493
    assert!(!repo.snapshot("status").unwrap().changed);
3494
    // update --init clones it at the pinned commit; status is unchanged.
3495
    assert_eq!(
3496
        repo.submodule_update(true, &[]).unwrap(),
3497
        vec![("vendor/sub".to_string(), SubrepoSync::Updated)]
3498
    );
3499
    assert_eq!(
3500
        git_in(&dest.join("vendor/sub"), &["rev-parse", "HEAD"]),
3501
        sub_sha
3502
    );
3503
    assert!(!repo.snapshot("status").unwrap().changed);
3504
    // Export writes the gitlink and .gitmodules back.
3505
    let mirror = root.join("mirror.git");
3506
    let rep = repo.git_export(&mirror).unwrap();
3507
    assert_eq!(rep.skipped_subrepos, 0);
3508
    let ls = git_in(&mirror, &["ls-tree", "main", "vendor/sub"]);
3509
    assert!(
3510
        ls.starts_with("160000 commit ") && ls.contains(&sub_sha),
3511
        "{ls}"
3512
    );
3513
    assert_eq!(
3514
        git_in(&mirror, &["ls-tree", "--name-only", "main"]),
3515
        ".gitmodules\nREADME.md\nvendor"
3516
    );
3517
    let orig_tree = git_in(&g, &["rev-parse", "main^{tree}"]);
3518
    assert_eq!(
3519
        git_in(&mirror, &["rev-parse", "main^{tree}"]),
3520
        orig_tree,
3521
        "tree round trip"
3522
    );
3523
}
3524
3525
#[test]
3526
fn partial_commits_by_path_and_by_hunk() {
3527
    hermetic();
3528
    let dir = tempfile::tempdir().unwrap();
3529
    let root = dir.path();
3530
    let repo = Repo::init(root).unwrap().with_home(root.join("home"));
3531
    write(root, "a.txt", b"1\n2\n3\n");
3532
    write(root, "b.txt", b"b\n");
3533
    let h0 = repo.commit("base", &[]).unwrap();
3534
    write(root, "a.txt", b"0\n1\n2\n3\n4\n");
3535
    write(root, "b.txt", b"b\nbb\n");
3536
    write(root, "c.txt", b"c\n");
3537
    // By path: only a.txt goes in; the rest stays on disk as uncommitted work.
3538
    let h1 = repo
3539
        .commit_selection("a only", &[], &Selection::Paths(vec!["a.txt".into()]))
3540
        .unwrap();
3541
    let c1 = repo.store().get_change(&h1).unwrap();
3542
    assert!(
3543
        c1.tree_ops.is_empty() && c1.edits.iter().all(|e| e.node() == c1.edits[0].node()),
3544
        "{:?}",
3545
        c1.tree_ops
3546
    );
3547
    assert_eq!(c1.deps, vec![h0]);
3548
    let files = repo.load_state(&[h1]).unwrap().materialize().files;
3549
    assert!(
3550
        matches!(&files["a.txt"].content, FileContent::Text { bytes, .. } if bytes == b"0\n1\n2\n3\n4\n")
3551
    );
3552
    assert!(matches!(&files["b.txt"].content, FileContent::Text { bytes, .. } if bytes == b"b\n"));
3553
    assert!(!files.contains_key("c.txt"));
3554
    let snap = repo.snapshot("status").unwrap();
3555
    assert_eq!(
3556
        snap.statuses
3557
            .iter()
3558
            .map(|s| (s.path.as_str(), s.status))
3559
            .collect::<Vec<_>>(),
3560
        vec![
3561
            ("b.txt", ChangeStatus::Modified),
3562
            ("c.txt", ChangeStatus::Added)
3563
        ]
3564
    );
3565
    assert_eq!(
3566
        fs::read(root.join("b.txt")).unwrap(),
3567
        b"b\nbb\n",
3568
        "disk untouched"
3569
    );
3570
    // By hunk: pick the b.txt insert; c.txt's addition is left.
3571
    let (_, hunks) = repo.hunks().unwrap();
3572
    let b_hunk = hunks
3573
        .iter()
3574
        .find(|h| h.path == "b.txt" && h.text.contains("+bb"))
3575
        .unwrap()
3576
        .index;
3577
    let h2 = repo
3578
        .commit_selection("b only", &[], &Selection::Hunks(vec![b_hunk]))
3579
        .unwrap();
3580
    let files = repo.load_state(&[h2]).unwrap().materialize().files;
3581
    assert!(
3582
        matches!(&files["b.txt"].content, FileContent::Text { bytes, .. } if bytes == b"b\nbb\n")
3583
    );
3584
    assert!(!files.contains_key("c.txt"));
3585
    let snap = repo.snapshot("status").unwrap();
3586
    assert_eq!(
3587
        snap.statuses
3588
            .iter()
3589
            .map(|s| s.path.as_str())
3590
            .collect::<Vec<_>>(),
3591
        vec!["c.txt"]
3592
    );
3593
    // Choosing only the content hunk of a file in a new directory pulls in
3594
    // the directory and file additions it needs.
3595
    write(root, "d/e.txt", b"e\n");
3596
    let (_, hunks) = repo.hunks().unwrap();
3597
    let e_insert = hunks
3598
        .iter()
3599
        .find(|h| h.path == "d/e.txt" && h.text.contains("+e"))
3600
        .unwrap()
3601
        .index;
3602
    let h3 = repo
3603
        .commit_selection("e only", &[], &Selection::Hunks(vec![e_insert]))
3604
        .unwrap();
3605
    let c3 = repo.store().get_change(&h3).unwrap();
3606
    assert_eq!(c3.tree_ops.len(), 2, "{:?}", c3.tree_ops);
3607
    let files = repo.load_state(&[h3]).unwrap().materialize().files;
3608
    assert!(files.contains_key("d/e.txt") && !files.contains_key("c.txt"));
3609
    // Choosing a new file's addition hunk brings its content along.
3610
    write(root, "f/g.txt", b"g\n");
3611
    let (_, hunks) = repo.hunks().unwrap();
3612
    let g_add = hunks
3613
        .iter()
3614
        .find(|h| h.path == "f/g.txt" && h.text.starts_with("A "))
3615
        .unwrap()
3616
        .index;
3617
    let h4 = repo
3618
        .commit_selection("g by addition", &[], &Selection::Hunks(vec![g_add]))
3619
        .unwrap();
3620
    let files = repo.load_state(&[h4]).unwrap().materialize().files;
3621
    assert!(
3622
        matches!(&files["f/g.txt"].content, FileContent::Text { bytes, .. } if bytes == b"g\n")
3623
    );
3624
    assert!(!repo
3625
        .snapshot("status")
3626
        .unwrap()
3627
        .statuses
3628
        .iter()
3629
        .any(|s| s.path == "f/g.txt"));
3630
    // Everything left commits normally; the working copy is then clean.
3631
    repo.commit("the rest", &[]).unwrap();
3632
    assert!(!repo.snapshot("status").unwrap().changed);
3633
    let files = repo
3634
        .load_state(&repo.bookmark_heads().unwrap())
3635
        .unwrap()
3636
        .materialize()
3637
        .files;
3638
    assert!(files.contains_key("c.txt"));
3639
}
3640
3641
#[test]
3642
fn blame_attributes_lines_to_introducing_changes_across_renames() {
3643
    hermetic();
3644
    let dir = tempfile::tempdir().unwrap();
3645
    let root = dir.path();
3646
    let mut repo = Repo::init(root).unwrap().with_home(root.join("home"));
3647
    repo.create_identity("Ada", "[email protected]", IdentityScope::User)
3648
        .unwrap();
3649
    write(root, "a.txt", b"one\n");
3650
    let h1 = repo.commit("first", &[]).unwrap();
3651
    write(root, "a.txt", b"one\ntwo\n");
3652
    let h2 = repo.commit("second", &[]).unwrap();
3653
    let b = repo.blame("a.txt").unwrap();
3654
    assert_eq!(
3655
        b.iter()
3656
            .map(|l| (l.line, l.hash, l.text.as_slice()))
3657
            .collect::<Vec<_>>(),
3658
        vec![(1, h1, b"one\n".as_slice()), (2, h2, b"two\n".as_slice())]
3659
    );
3660
    assert!(b.iter().all(|l| l.author == "Ada"));
3661
    assert_eq!(
3662
        b[0].change_id,
3663
        repo.store().get_change(&h1).unwrap().change_id
3664
    );
3665
    fs::rename(root.join("a.txt"), root.join("b.txt")).unwrap();
3666
    repo.commit("rename", &[]).unwrap();
3667
    let b = repo.blame("b.txt").unwrap();
3668
    assert_eq!(
3669
        b.iter().map(|l| l.hash).collect::<Vec<_>>(),
3670
        vec![h1, h2],
3671
        "the node survives the rename"
3672
    );
3673
    assert!(repo.blame("a.txt").is_err());
3674
}
3675
3676
#[test]
3677
fn bisect_finds_the_first_bad_change() {
3678
    hermetic();
3679
    let dir = tempfile::tempdir().unwrap();
3680
    let root = dir.path();
3681
    let repo = Repo::init(root).unwrap().with_home(root.join("home"));
3682
    let mut content = String::new();
3683
    let mut hashes = Vec::new();
3684
    for i in 1..=8 {
3685
        content.push_str(&format!("line {i}{}\n", if i == 5 { " bug" } else { "" }));
3686
        write(root, "f.txt", content.as_bytes());
3687
        hashes.push(repo.commit(&format!("step {i}"), &[]).unwrap());
3688
    }
3689
    // Each step appends after the previous line, so the chain is linear.
3690
    assert_eq!(repo.bookmark_heads().unwrap(), vec![hashes[7]]);
3691
    repo.bisect_start().unwrap();
3692
    assert!(matches!(
3693
        repo.bisect_mark(Some(true), &[hashes[0]]).unwrap(),
3694
        BisectStep::NeedMarks { good: 1, bad: 0 }
3695
    ));
3696
    let step = repo.bisect_mark(Some(false), &[hashes[7]]).unwrap();
3697
    assert!(
3698
        matches!(step, BisectStep::Testing { remaining: 7, .. }),
3699
        "{step:?}"
3700
    );
3701
    // Automated: bad when the bug line is present.
3702
    let step = repo
3703
        .bisect_run(&["sh".into(), "-c".into(), "! grep -q bug f.txt".into()])
3704
        .unwrap();
3705
    assert_eq!(step, BisectStep::Found { culprit: hashes[4] });
3706
    assert_eq!(
3707
        repo.bisect_status().unwrap(),
3708
        Some(BisectStep::Found { culprit: hashes[4] })
3709
    );
3710
    repo.bisect_reset().unwrap();
3711
    assert_eq!(fs::read_to_string(root.join("f.txt")).unwrap(), content);
3712
    assert!(repo.bisect_status().unwrap().is_none());
3713
    assert!(!repo.snapshot("status").unwrap().changed);
3714
    // Manual marks and a skip.
3715
    repo.bisect_start().unwrap();
3716
    repo.bisect_mark(Some(true), &[hashes[0]]).unwrap();
3717
    let mut step = repo.bisect_mark(Some(false), &[hashes[7]]).unwrap();
3718
    let mut skipped_once = false;
3719
    let mut guard = 0;
3720
    while let BisectStep::Testing { .. } = step {
3721
        guard += 1;
3722
        assert!(guard < 20);
3723
        let text = fs::read_to_string(root.join("f.txt")).unwrap();
3724
        if !skipped_once && text.contains("line 6") {
3725
            // An untestable state away from the boundary: the search routes around it.
3726
            skipped_once = true;
3727
            step = repo.bisect_mark(None, &[]).unwrap();
3728
            continue;
3729
        }
3730
        step = repo.bisect_mark(Some(!text.contains("bug")), &[]).unwrap();
3731
    }
3732
    assert!(skipped_once);
3733
    assert_eq!(step, BisectStep::Found { culprit: hashes[4] });
3734
    repo.bisect_reset().unwrap();
3735
    // Skipping the culprit itself leaves it among the candidates reported.
3736
    repo.bisect_start().unwrap();
3737
    repo.bisect_mark(Some(true), &[hashes[0]]).unwrap();
3738
    let mut step = repo.bisect_mark(Some(false), &[hashes[7]]).unwrap();
3739
    let mut guard = 0;
3740
    while let BisectStep::Testing { heads, .. } = &step {
3741
        guard += 1;
3742
        assert!(guard < 20);
3743
        let text = fs::read_to_string(root.join("f.txt")).unwrap();
3744
        let is_culprit_state =
3745
            heads.contains(&hashes[4]) && !heads.iter().any(|h| hashes[5..].contains(h));
3746
        step = if is_culprit_state {
3747
            repo.bisect_mark(None, &[]).unwrap()
3748
        } else {
3749
            repo.bisect_mark(Some(!text.contains("bug")), &[]).unwrap()
3750
        };
3751
    }
3752
    match step {
3753
        BisectStep::Inconclusive { candidates } => assert!(
3754
            candidates.contains(&hashes[4]) && candidates.len() <= 2,
3755
            "{candidates:?}"
3756
        ),
3757
        other => panic!("{other:?}"),
3758
    }
3759
    repo.bisect_reset().unwrap();
3760
}
3761
3762
#[test]
3763
fn squash_folds_a_change_into_its_dependency() {
3764
    hermetic();
3765
    let dir = tempfile::tempdir().unwrap();
3766
    let root = dir.path();
3767
    let repo = Repo::init(root).unwrap().with_home(root.join("home"));
3768
    write(root, "a.txt", b"1\n");
3769
    let a = repo.commit("A", &[]).unwrap();
3770
    write(root, "a.txt", b"1\n2\n");
3771
    let c = repo.commit("C", &[]).unwrap();
3772
    write(root, "a.txt", b"1\n2\n3\n");
3773
    let e = repo.commit("E", &[]).unwrap();
3774
    write(root, "b.txt", b"b\n");
3775
    let b = repo.commit("B", &[]).unwrap();
3776
    let id_a = repo.store().get_change(&a).unwrap().change_id;
3777
    let id_e = repo.store().get_change(&e).unwrap().change_id;
3778
    // E depends on C which A lacks: refused, naming it.
3779
    let err = repo.squash(&e, &a).unwrap_err().to_string();
3780
    assert!(err.contains(&c.short(12)), "{err}");
3781
    // C into A: A' has both, C is gone, E follows and still reads the same.
3782
    let a2 = repo.squash(&c, &a).unwrap();
3783
    let a2c = repo.store().get_change(&a2).unwrap();
3784
    assert_eq!(a2c.change_id, id_a);
3785
    assert!(a2c.deps.is_empty());
3786
    let heads = repo.bookmark_heads().unwrap();
3787
    let st = repo.load_state(&heads).unwrap();
3788
    assert!(!st.contains(&c) && !st.contains(&a) && !st.contains(&e));
3789
    let e2 = st
3790
        .changes()
3791
        .find(|(_, m)| m.change_id == id_e)
3792
        .map(|(h, _)| *h)
3793
        .unwrap();
3794
    assert_eq!(
3795
        repo.store().get_change(&e2).unwrap().deps,
3796
        vec![a2],
3797
        "E now depends on A' alone"
3798
    );
3799
    let files = st.materialize().files;
3800
    assert!(
3801
        matches!(&files["a.txt"].content, FileContent::Text { bytes, .. } if bytes == b"1\n2\n3\n")
3802
    );
3803
    assert!(files.contains_key("b.txt"));
3804
    assert!(st.contains(&b));
3805
    assert!(!repo.snapshot("status").unwrap().changed);
3806
    assert_eq!(repo.log().unwrap().len(), 4, "working copy, B, E', A'");
3807
    // Undo restores the three original changes.
3808
    repo.undo().unwrap();
3809
    repo.undo().unwrap();
3810
    let st = repo.load_state(&repo.bookmark_heads().unwrap()).unwrap();
3811
    assert!(st.contains(&c) && st.contains(&a) && st.contains(&e));
3812
}
3813
3814
#[test]
3815
fn rebase_re_expresses_a_change_against_another_base() {
3816
    hermetic();
3817
    let dir = tempfile::tempdir().unwrap();
3818
    let root = dir.path();
3819
    let repo = Repo::init(root).unwrap().with_home(root.join("home"));
3820
    write(root, "a.txt", b"1\n2\n");
3821
    let a = repo.commit("A", &[]).unwrap();
3822
    write(root, "a.txt", b"1\n2\n3\n");
3823
    let c = repo.commit("C: append 3", &[]).unwrap();
3824
    write(root, "a.txt", b"1\n2\n3\n4\n");
3825
    let e = repo.commit("E: append 4", &[]).unwrap();
3826
    // A different base: A plus a change that prepends a line.
3827
    repo.checkout(&[a], true, "checkout").unwrap();
3828
    write(root, "a.txt", b"0\n1\n2\n");
3829
    let d = repo.commit("D: prepend 0", &[]).unwrap();
3830
    let id_c = repo.store().get_change(&c).unwrap().change_id;
3831
    let id_e = repo.store().get_change(&e).unwrap().change_id;
3832
    // Rebase C onto D: its effect (append 3) re-derived against D's text.
3833
    let c2 = repo.rebase(&c, &[d]).unwrap();
3834
    let c2c = repo.store().get_change(&c2).unwrap();
3835
    assert_eq!(c2c.change_id, id_c);
3836
    assert!(c2c.deps.contains(&d), "{:?}", c2c.deps);
3837
    let heads = repo.bookmark_heads().unwrap();
3838
    let st = repo.load_state(&heads).unwrap();
3839
    assert!(!st.contains(&c) && st.contains(&d));
3840
    let e2 = st
3841
        .changes()
3842
        .find(|(_, m)| m.change_id == id_e)
3843
        .map(|(h, _)| *h)
3844
        .unwrap();
3845
    let e2deps = repo.store().get_change(&e2).unwrap().deps;
3846
    assert!(
3847
        e2deps.contains(&c2) && !e2deps.contains(&c) && e2deps.contains(&a),
3848
        "E follows C by content and still depends on A, which introduced the file: {e2deps:?}"
3849
    );
3850
    let files = st.materialize().files;
3851
    assert!(
3852
        matches!(&files["a.txt"].content, FileContent::Text { bytes, .. } if bytes == b"0\n1\n2\n3\n4\n"),
3853
        "{:?}",
3854
        files["a.txt"].content
3855
    );
3856
    assert!(!files["a.txt"].is_conflicted());
3857
    // Rebasing onto a state that already contains the change is refused.
3858
    assert!(repo.rebase(&c2, &[c2]).is_err());
3859
    let err = repo.rebase(&e2, &[d]).unwrap_err().to_string();
3860
    assert!(
3861
        err.contains("lacks dependencies"),
3862
        "E needs C, which D's state does not have: {err}"
3863
    );
3864
}
3865
3866
#[test]
3867
fn unsigned_tags_keep_their_message() {
3868
    hermetic();
3869
    let dir = tempfile::tempdir().unwrap();
3870
    let root = dir.path();
3871
    let repo = Repo::init(root).unwrap().with_home(root.join("home"));
3872
    write(root, "a.txt", b"a\n");
3873
    repo.commit("a", &[]).unwrap();
3874
    assert!(repo.secret_key().unwrap().is_none());
3875
    repo.tag_create("v1", &repo.bookmark_heads().unwrap(), "first release")
3876
        .unwrap();
3877
    let tags = repo.tags().unwrap();
3878
    assert_eq!(
3879
        (
3880
            tags[0].name.as_str(),
3881
            tags[0].message.as_str(),
3882
            tags[0].signer.as_deref()
3883
        ),
3884
        ("v1", "first release", None)
3885
    );
3886
    assert!(
3887
        repo.tag_refs().unwrap()[0].attestation.is_none(),
3888
        "an unsigned attestation is not advertised"
3889
    );
3890
}
3891
3892
#[test]
3893
fn fsck_passes_a_sound_repository_and_names_each_fault() {
3894
    hermetic();
3895
    let dir = tempfile::tempdir().unwrap();
3896
    let root = dir.path();
3897
    let origin_path = root.join("origin");
3898
    let origin = Repo::init(&origin_path).unwrap();
3899
    let mut a = Repo::clone(&origin_path.to_string_lossy(), &root.join("a"))
3900
        .unwrap()
3901
        .with_home(root.join("home-a"));
3902
    a.create_identity("Ada", "[email protected]", IdentityScope::Repo)
3903
        .unwrap();
3904
    write(&root.join("a"), "f.txt", b"one\n");
3905
    write(&root.join("a"), "bin.dat", b"\0\x01\x02binary");
3906
    let h1 = a.commit("first", &[]).unwrap();
3907
    write(&root.join("a"), "f.txt", b"one\ntwo\n");
3908
    let h2 = a.commit("second", &[]).unwrap();
3909
    a.tag_create("v1", &[h2], "first release").unwrap();
3910
    a.checkpoint().unwrap();
3911
    assert!(a.push("origin", false).unwrap()[0].ok);
3912
3913
    // Sound: signed changes, a seal, a tag, a checkpoint, a ref attestation.
3914
    for repo in [&a, &origin] {
3915
        let rep = repo.fsck().unwrap();
3916
        assert_eq!(rep.problems, vec![], "{rep:?}");
3917
        // The two commits, plus the working copy's change in `a`.
3918
        assert!(rep.changes >= 2 && rep.signed >= 2, "{rep:?}");
3919
        assert!(rep.ops > 1 && rep.objects > 5);
3920
    }
3921
    assert!(origin.fsck().unwrap().attestations >= 1);
3922
3923
    // A flipped byte in a stored object is corruption, named by hash.
3924
    let c1 = a.store().path_for(&h1);
3925
    let pristine = fs::read(&c1).unwrap();
3926
    let mut bytes = pristine.clone();
3927
    *bytes.last_mut().unwrap() ^= 1;
3928
    fs::write(&c1, &bytes).unwrap();
3929
    let rep = a.fsck().unwrap();
3930
    assert!(rep.errors() >= 1);
3931
    assert!(
3932
        rep.problems
3933
            .iter()
3934
            .any(|p| p.object == Some(h1) && p.what.contains("unreadable")),
3935
        "{rep:?}"
3936
    );
3937
    fs::write(&c1, &pristine).unwrap();
3938
    assert_eq!(a.fsck().unwrap().errors(), 0);
3939
3940
    // A missing change is named with what needed it.
3941
    fs::remove_file(&c1).unwrap();
3942
    let rep = a.fsck().unwrap();
3943
    assert!(
3944
        rep.problems.iter().any(|p| p.severity == Severity::Error
3945
            && p.object == Some(h1)
3946
            && p.what.contains("change missing, needed by change")),
3947
        "{rep:?}"
3948
    );
3949
    fs::write(&c1, &pristine).unwrap();
3950
3951
    // A missing blob is an error in a full clone.
3952
    let c2 = a.store().get_change(&h1).unwrap();
3953
    let blob = c2
3954
        .edits
3955
        .iter()
3956
        .find_map(|e| match e {
3957
            Edit::Replace { new: Some(b), .. } => Some(*b),
3958
            _ => None,
3959
        })
3960
        .expect("the binary file is a blob");
3961
    let bp = a.store().path_for(&blob);
3962
    let blob_bytes = fs::read(&bp).unwrap();
3963
    fs::remove_file(&bp).unwrap();
3964
    let rep = a.fsck().unwrap();
3965
    assert!(
3966
        rep.problems
3967
            .iter()
3968
            .any(|p| p.object == Some(blob) && p.what.contains("blob missing")),
3969
        "{rep:?}"
3970
    );
3971
    fs::write(&bp, &blob_bytes).unwrap();
3972
3973
    // A broken op log head is reported, not a crash.
3974
    let head = root.join("a/.oxy/ops/head");
3975
    let saved = fs::read(&head).unwrap();
3976
    fs::write(&head, b"not a hash").unwrap();
3977
    let rep = a.fsck().unwrap();
3978
    assert!(
3979
        rep.problems.iter().any(|p| p.what.contains("ops/head")),
3980
        "{rep:?}"
3981
    );
3982
    fs::write(&head, saved).unwrap();
3983
    assert_eq!(a.fsck().unwrap().problems, vec![]);
3984
}
3985
3986
/// Copy a directory tree (for restoring a pristine repository).
3987
fn copy_tree(from: &Path, to: &Path) {
3988
    fs::create_dir_all(to).unwrap();
3989
    for e in fs::read_dir(from).unwrap() {
3990
        let e = e.unwrap();
3991
        let target = to.join(e.file_name());
3992
        if e.file_type().unwrap().is_dir() {
3993
            copy_tree(&e.path(), &target);
3994
        } else {
3995
            fs::copy(e.path(), &target).unwrap();
3996
        }
3997
    }
3998
}
3999
4000
/// Spec §13.6: stop `commit` and `push` at every durable step, as a crash
4001
/// would, and check that both repositories still open, pass `fsck`, and
4002
/// accept the same operation again.
4003
#[test]
4004
fn crash_at_every_step_of_commit_and_push_leaves_sound_repositories() {
4005
    use crate::durable::failpoint;
4006
    hermetic();
4007
    let dir = tempfile::tempdir().unwrap();
4008
    let pristine = dir.path().join("pristine");
4009
    let origin_path = pristine.join("origin");
4010
    Repo::init(&origin_path).unwrap();
4011
    let mut a = Repo::clone(&origin_path.to_string_lossy(), &pristine.join("a"))
4012
        .unwrap()
4013
        .with_home(dir.path().join("home"));
4014
    a.create_identity("Ada", "[email protected]", IdentityScope::Repo)
4015
        .unwrap();
4016
    write(&pristine.join("a"), "f.txt", b"one\n");
4017
    a.commit("first", &[]).unwrap();
4018
    assert!(a.push("origin", false).unwrap()[0].ok);
4019
    drop(a);
4020
4021
    type Op = fn(&Repo) -> Result<()>;
4022
    let edit_and_commit: Op = |r| {
4023
        write(r.root(), "f.txt", b"one\ntwo\n");
4024
        write(r.root(), "big.bin", &vec![7u8; 300_000]);
4025
        r.commit("second", &[]).map(|_| ())
4026
    };
4027
    let push: Op = |r| {
4028
        let res = r.push("origin", false)?;
4029
        if res.iter().all(|x| x.ok) {
4030
            Ok(())
4031
        } else {
4032
            Err(RepoError::Msg(format!("{res:?}")))
4033
        }
4034
    };
4035
4036
    for (name, prepare, op) in [
4037
        ("commit", None, edit_and_commit),
4038
        ("push", Some(edit_and_commit), push),
4039
    ] {
4040
        let mut steps = 0;
4041
        for n in 1.. {
4042
            let run = dir.path().join(format!("{name}-{n}"));
4043
            copy_tree(&pristine, &run);
4044
            // Clones record their remote by path; point it at this copy.
4045
            let open = |p: &Path| {
4046
                let mut r = Repo::open(p).unwrap().with_home(dir.path().join("home"));
4047
                r.config
4048
                    .set("remote.origin.url", &run.join("origin").to_string_lossy())
4049
                    .unwrap();
4050
                r.save_config().unwrap();
4051
                r
4052
            };
4053
            let a = open(&run.join("a"));
4054
            if let Some(prep) = prepare {
4055
                prep(&a).unwrap();
4056
            }
4057
            failpoint::crash_after(n);
4058
            let outcome = op(&a);
4059
            let crashed = failpoint::disarm();
4060
            drop(a);
4061
            if !crashed {
4062
                outcome.unwrap_or_else(|e| panic!("{name} failed without a crash: {e}"));
4063
                steps = n - 1;
4064
                break;
4065
            }
4066
            assert!(
4067
                outcome.is_err(),
4068
                "{name}: a crash at step {n} was swallowed"
4069
            );
4070
            for repo in ["a", "origin"] {
4071
                let r = Repo::open(&run.join(repo)).unwrap_or_else(|e| {
4072
                    panic!("{name} crash at step {n}: {repo} no longer opens: {e}")
4073
                });
4074
                let rep = r.fsck().unwrap();
4075
                assert_eq!(
4076
                    rep.errors(),
4077
                    0,
4078
                    "{name} crash at step {n}: {repo} fails fsck: {:?}",
4079
                    rep.problems
4080
                );
4081
            }
4082
            // The interrupted operation can simply be run again.
4083
            let a = open(&run.join("a"));
4084
            // A crash after the commit point leaves the commit done.
4085
            let landed = a
4086
                .bookmark_heads()
4087
                .unwrap()
4088
                .iter()
4089
                .any(|h| a.store().get_change(h).unwrap().message == "second");
4090
            let again = match (name, landed) {
4091
                ("commit", true) => Ok(()),
4092
                ("commit", false) => a.commit("second", &[]).map(|_| ()),
4093
                _ => op(&a),
4094
            };
4095
            again.unwrap_or_else(|e| panic!("{name} crash at step {n}: retry failed: {e}"));
4096
            assert_eq!(a.fsck().unwrap().errors(), 0);
4097
            fs::remove_dir_all(&run).unwrap();
4098
        }
4099
        assert!(steps >= 3, "{name} has only {steps} durable steps?");
4100
    }
4101
}
4102
4103
/// Spec §12.1: commands in two workspaces of one repository, and pushes,
4104
/// running at the same time lose nothing: every commit ends up on the
4105
/// bookmark, locally and on the remote, and the repository passes fsck.
4106
#[test]
4107
fn concurrent_commits_in_two_workspaces_lose_nothing() {
4108
    hermetic();
4109
    let dir = tempfile::tempdir().unwrap();
4110
    let root = dir.path();
4111
    let origin = root.join("origin");
4112
    Repo::init_bare_unbound(&origin).unwrap();
4113
    let main = root.join("main");
4114
    let mut repo = Repo::init(&main).unwrap();
4115
    repo.config
4116
        .set("remote.origin.url", &origin.to_string_lossy())
4117
        .unwrap();
4118
    repo.save_config().unwrap();
4119
    write(&main, "seed.txt", b"seed\n");
4120
    repo.commit("seed", &[]).unwrap();
4121
    let second = root.join("second");
4122
    repo.workspace_add(&second, None).unwrap();
4123
    drop(repo);
4124
4125
    const EACH: usize = 15;
4126
    std::thread::scope(|s| {
4127
        for (tag, dir, push) in [("a", main.clone(), true), ("b", second.clone(), false)] {
4128
            s.spawn(move || {
4129
                let r = Repo::open(&dir).unwrap();
4130
                for i in 0..EACH {
4131
                    write(
4132
                        &dir,
4133
                        &format!("{tag}-{i}.txt"),
4134
                        format!("{tag} {i}\n").as_bytes(),
4135
                    );
4136
                    r.commit(&format!("{tag} {i}"), &[]).unwrap();
4137
                    if push && i % 5 == 4 {
4138
                        // A push may be refused while the other workspace moves the bookmark; nothing may be lost either way.
4139
                        let _ = r.push("origin", false);
4140
                    }
4141
                }
4142
            });
4143
        }
4144
    });
4145
4146
    let repo = Repo::open(&main).unwrap();
4147
    let heads = repo.bookmark_heads().unwrap();
4148
    let state = repo.load_state(&heads).unwrap();
4149
    let messages: BTreeSet<String> = state.changes().map(|(_, m)| m.message.clone()).collect();
4150
    for tag in ["a", "b"] {
4151
        for i in 0..EACH {
4152
            assert!(
4153
                messages.contains(&format!("{tag} {i}")),
4154
                "lost commit {tag} {i}; have {messages:?}"
4155
            );
4156
        }
4157
    }
4158
    let rep = repo.fsck().unwrap();
4159
    assert_eq!(rep.errors(), 0, "{:?}", rep.problems);
4160
    assert!(repo.push("origin", false).unwrap().iter().all(|r| r.ok));
4161
    let hosted = Repo::open(&origin).unwrap();
4162
    let hosted_heads = hosted.bookmark_heads().unwrap();
4163
    assert_eq!(
4164
        hosted.load_state(&hosted_heads).unwrap().len(),
4165
        state.len(),
4166
        "the remote has every commit"
4167
    );
4168
}
4169
4170
/// Two operations recorded from the same parent (what two processes do
4171
/// when they race) are merged: both bookmarks' heads survive, and a
4172
/// change made on one side only is kept.
4173
#[test]
4174
fn operations_from_the_same_parent_are_merged() {
4175
    hermetic();
4176
    let dir = tempfile::tempdir().unwrap();
4177
    let root = dir.path();
4178
    let repo = Repo::init(root).unwrap();
4179
    write(root, "a.txt", b"a\n");
4180
    let a = repo.commit("a", &[]).unwrap();
4181
    write(root, "b.txt", b"b\n");
4182
    let b = repo.commit("b", &[]).unwrap();
4183
    let (x, op) = repo.head_op().unwrap();
4184
    let state = |heads: Vec<ChangeHash>| repo.store().put_state(&StateObject::new(heads)).unwrap();
4185
4186
    // Side one moves main to just `a` and adds a bookmark; side two moves main to just `b`.
4187
    let mut one = op.view.clone();
4188
    one.bookmarks.insert("main".into(), state(vec![a]));
4189
    one.bookmarks.insert("topic".into(), state(vec![a]));
4190
    let mut two = op.view.clone();
4191
    two.bookmarks.insert("main".into(), state(vec![b]));
4192
    repo.record_op(&[x], "one", one).unwrap();
4193
    let merged = repo.record_op(&[x], "two", two).unwrap();
4194
4195
    let (head, op) = repo.head_op().unwrap();
4196
    assert_eq!(head, merged);
4197
    assert_eq!(op.parents.len(), 2, "a merge of the two operations");
4198
    assert!(op.command.contains("merged with a concurrent operation"));
4199
    let mut main = repo
4200
        .store()
4201
        .get_state(&op.view.bookmarks["main"])
4202
        .unwrap()
4203
        .heads;
4204
    main.sort();
4205
    let mut want = vec![a, b];
4206
    want.sort();
4207
    assert_eq!(main, want, "both sides' heads are kept");
4208
    assert!(
4209
        op.view.bookmarks.contains_key("topic"),
4210
        "a one-sided change survives"
4211
    );
4212
    assert_eq!(repo.fsck().unwrap().errors(), 0);
4213
}
4214
4215
#[test]
4216
fn failed_requests_come_with_a_next_step() {
4217
    use crate::protocol::hint_for;
4218
    assert!(hint_for("https://h/x/oxy/v1/push: HTTP 401: bad token")
4219
        .unwrap()
4220
        .contains("token"));
4221
    assert!(hint_for("…: HTTP 403: forbidden")
4222
        .unwrap()
4223
        .contains("repo:write"));
4224
    assert!(hint_for("…: HTTP 404: no such repository")
4225
        .unwrap()
4226
        .contains("owner and repository name"));
4227
    assert!(hint_for("invalid peer certificate: UnknownIssuer")
4228
        .unwrap()
4229
        .contains("oxyhub-ca.pem"));
4230
    assert!(hint_for("Connect error: Connection refused (os error 111)")
4231
        .unwrap()
4232
        .contains("running"));
4233
    assert!(hint_for("Dns Failed: failed to lookup address information")
4234
        .unwrap()
4235
        .contains("resolve"));
4236
    assert_eq!(hint_for("something else entirely"), None);
4237
}
4238
4239
#[test]
4240
fn doctor_names_problems_and_what_to_do() {
4241
    hermetic();
4242
    let dir = tempfile::tempdir().unwrap();
4243
    let root = dir.path();
4244
    let origin = root.join("origin");
4245
    Repo::init_bare_unbound(&origin).unwrap();
4246
    let mut repo = Repo::init(&root.join("r"))
4247
        .unwrap()
4248
        .with_home(root.join("home"));
4249
    let find = |r: &DoctorReport, area: &str, h: Health| {
4250
        r.checks
4251
            .iter()
4252
            .find(|c| c.area == area && c.health == h)
4253
            .cloned()
4254
    };
4255
4256
    let r = repo.doctor(true);
4257
    assert!(find(&r, "identity", Health::Warn)
4258
        .unwrap()
4259
        .hint
4260
        .unwrap()
4261
        .contains("oxy identity create"));
4262
    assert!(find(&r, "repository", Health::Ok).is_some());
4263
4264
    repo.create_identity("Ada", "[email protected]", IdentityScope::Repo)
4265
        .unwrap();
4266
    repo.config.set("author.name", "Ada").unwrap();
4267
    repo.config.set("author.email", "[email protected]").unwrap();
4268
    repo.config
4269
        .set("remote.origin.url", &origin.to_string_lossy())
4270
        .unwrap();
4271
    repo.config
4272
        .set("remote.down.url", "http://127.0.0.1:9/a/b")
4273
        .unwrap();
4274
    repo.config.set("remote.down.token", "t").unwrap();
4275
    repo.config
4276
        .set("remote.badca.url", "https://example.invalid/a/b")
4277
        .unwrap();
4278
    repo.config
4279
        .set(
4280
            "remote.badca.ca",
4281
            &root.join("missing.pem").to_string_lossy(),
4282
        )
4283
        .unwrap();
4284
    repo.save_config().unwrap();
4285
4286
    let r = repo.doctor(true);
4287
    assert!(find(&r, "identity", Health::Ok).is_some(), "{r:?}");
4288
    assert!(find(&r, "author", Health::Ok).is_some(), "{r:?}");
4289
    assert!(find(&r, "remote origin", Health::Ok)
4290
        .unwrap()
4291
        .message
4292
        .contains("first push binds it"));
4293
    let down = find(&r, "remote down", Health::Fail).unwrap();
4294
    assert!(
4295
        down.hint.as_deref().unwrap_or("").contains("running"),
4296
        "{down:?}"
4297
    );
4298
    let badca = find(&r, "remote badca", Health::Fail).unwrap();
4299
    assert!(
4300
        badca.hint.unwrap().contains("remote.badca.ca"),
4301
        "the remote's own name is in the hint"
4302
    );
4303
    assert_eq!(r.worst(), Health::Fail);
4304
4305
    // Offline, nothing is contacted.
4306
    let r = repo.doctor(false);
4307
    assert!(find(&r, "remote down", Health::Fail).is_none());
4308
    assert!(find(&r, "remote down", Health::Ok)
4309
        .unwrap()
4310
        .message
4311
        .contains("not contacted"));
4312
}
4313
4314
/// Spec §8.1: deleting a line depends on whoever inserted the lines right
4315
/// after it. Inserting after `b` and then deleting `b`, one commit after
4316
/// the other, must not leave a delete/insert conflict.
4317
#[test]
4318
fn deleting_a_line_after_an_insertion_below_it_is_not_a_conflict() {
4319
    hermetic();
4320
    let dir = tempfile::tempdir().unwrap();
4321
    let root = dir.path();
4322
    let repo = Repo::init(root).unwrap();
4323
    write(root, "f", b"a\nb\nc\n");
4324
    repo.commit("base", &[]).unwrap();
4325
    write(root, "f", b"a\nb\nx\nc\n");
4326
    let insert = repo.commit("insert x after b", &[]).unwrap();
4327
    write(root, "f", b"a\nx\nc\n");
4328
    let delete = repo.commit("delete b", &[]).unwrap();
4329
    assert!(
4330
        repo.store()
4331
            .get_change(&delete)
4332
            .unwrap()
4333
            .deps
4334
            .contains(&insert),
4335
        "the deletion depends on the insertion below the deleted line"
4336
    );
4337
    let heads = repo.bookmark_heads().unwrap();
4338
    assert_eq!(heads, vec![delete]);
4339
    let snap = repo.load_state(&heads).unwrap().materialize();
4340
    assert!(!snap.is_conflicted());
4341
    assert!(
4342
        matches!(&snap.files["f"].content, FileContent::Text { bytes, .. } if bytes == b"a\nx\nc\n")
4343
    );
4344
}
4345
4346
/// Spec §9.3: a binary file reverted to an earlier blob keeps it, and each
4347
/// replacement depends on the change that set the blob it replaces.
4348
#[test]
4349
fn a_binary_file_reverted_to_an_earlier_blob_keeps_it() {
4350
    hermetic();
4351
    let dir = tempfile::tempdir().unwrap();
4352
    let root = dir.path();
4353
    let repo = Repo::init(root).unwrap();
4354
    write(root, "bin", b"\0A");
4355
    let v1 = repo.commit("v1", &[]).unwrap();
4356
    write(root, "bin", b"\0B");
4357
    let v2 = repo.commit("v2", &[]).unwrap();
4358
    assert!(repo.store().get_change(&v2).unwrap().deps.contains(&v1));
4359
    write(root, "bin", b"\0A");
4360
    let v3 = repo.commit("back to A", &[]).unwrap();
4361
    assert!(repo.store().get_change(&v3).unwrap().deps.contains(&v2));
4362
    assert_eq!(repo.bookmark_heads().unwrap(), vec![v3]);
4363
    let state = repo.load_state(&[v3]).unwrap();
4364
    let snap = state.materialize();
4365
    let FileContent::Opaque { blobs } = &snap.files["bin"].content else {
4366
        panic!("opaque")
4367
    };
4368
    assert_eq!(blobs.len(), 1, "one live blob, not none and not two");
4369
    assert_eq!(repo.read_blob(&blobs[0]).unwrap(), b"\0A");
4370
}
4371
4372
/// Spec §23: a binary file changed on two branches and merged in Git to
4373
/// one side's version comes back as that version at the merge, and the
4374
/// import verifies commit by commit.
4375
#[test]
4376
fn git_import_resolves_a_binary_merged_in_git_and_verifies() {
4377
    hermetic();
4378
    if std::process::Command::new("git")
4379
        .arg("--version")
4380
        .output()
4381
        .is_err()
4382
    {
4383
        eprintln!("git not installed; skipping");
4384
        return;
4385
    }
4386
    let dir = tempfile::tempdir().unwrap();
4387
    let root = dir.path();
4388
    let g = root.join("src.git");
4389
    fs::create_dir_all(&g).unwrap();
4390
    let git = |args: &[&str]| -> String {
4391
        let out = std::process::Command::new("git")
4392
            .arg("-C")
4393
            .arg(&g)
4394
            .args([
4395
                "-c",
4396
                "user.name=Grace",
4397
                "-c",
4398
                "[email protected]",
4399
                "-c",
4400
                "commit.gpgsign=false",
4401
            ])
4402
            .args(args)
4403
            .output()
4404
            .unwrap();
4405
        assert!(
4406
            out.status.success(),
4407
            "git {args:?}: {}",
4408
            String::from_utf8_lossy(&out.stderr)
4409
        );
4410
        String::from_utf8_lossy(&out.stdout).trim().to_string()
4411
    };
4412
    git(&["init", "-q", "-b", "main"]);
4413
    write(&g, "logo.bin", b"\0base");
4414
    write(&g, "notes.txt", b"a\nb\nc\n");
4415
    git(&["add", "."]);
4416
    git(&["commit", "-qm", "base"]);
4417
    git(&["checkout", "-qb", "side"]);
4418
    write(&g, "logo.bin", b"\0side");
4419
    write(&g, "notes.txt", b"a\nb\nx\nc\n");
4420
    git(&["commit", "-qam", "side"]);
4421
    git(&["checkout", "-q", "main"]);
4422
    write(&g, "logo.bin", b"\0main");
4423
    git(&["commit", "-qam", "main"]);
4424
    // Git cannot merge the binary; the merge takes main's and keeps side's text.
4425
    let _ = std::process::Command::new("git")
4426
        .arg("-C")
4427
        .arg(&g)
4428
        .args([
4429
            "-c",
4430
            "user.name=G",
4431
            "-c",
4432
            "user.email=g@e",
4433
            "merge",
4434
            "-q",
4435
            "side",
4436
        ])
4437
        .output();
4438
    write(&g, "logo.bin", b"\0main");
4439
    git(&["add", "."]);
4440
    git(&["commit", "-qm", "merge side"]);
4441
    // Then a revert of the binary to its first version.
4442
    write(&g, "logo.bin", b"\0base");
4443
    git(&["commit", "-qam", "back to base"]);
4444
4445
    let repo = Repo::init(&root.join("o")).unwrap();
4446
    let rep = repo.import_git(&g, "main").unwrap();
4447
    assert_eq!(rep.merges, 1);
4448
    let v = repo.verify_git_import(&g, "main").unwrap();
4449
    assert!(v.mismatches.is_empty(), "{:?}", v.mismatches);
4450
    assert_eq!(v.commits, 5);
4451
    let snap = repo
4452
        .load_state(&repo.bookmark_heads().unwrap())
4453
        .unwrap()
4454
        .materialize();
4455
    assert!(!snap.is_conflicted());
4456
    let FileContent::Opaque { blobs } = &snap.files["logo.bin"].content else {
4457
        panic!("opaque")
4458
    };
4459
    assert_eq!(repo.read_blob(&blobs[0]).unwrap(), b"\0base");
4460
}
4461
4462
/// Spec §7.7 on a file system without executable bits or symlinks: the
4463
/// recorded bit is kept, and a symlink checked out as a plain file holding
4464
/// its target is still that symlink.
4465
#[cfg(unix)]
4466
#[test]
4467
fn windows_file_systems_keep_exec_bits_and_symlinks() {
4468
    use crate::portable::Platform;
4469
    use std::os::unix::fs::PermissionsExt;
4470
    hermetic();
4471
    let dir = tempfile::tempdir().unwrap();
4472
    let root = dir.path();
4473
    let repo = Repo::init(root).unwrap();
4474
    write(root, "run.sh", b"#!/bin/sh\n");
4475
    fs::set_permissions(root.join("run.sh"), fs::Permissions::from_mode(0o755)).unwrap();
4476
    std::os::unix::fs::symlink("run.sh", root.join("link")).unwrap();
4477
    repo.commit("script and link", &[]).unwrap();
4478
    drop(repo);
4479
4480
    // What checking out on Windows leaves: no exec bit, the link as a file.
4481
    fs::set_permissions(root.join("run.sh"), fs::Permissions::from_mode(0o644)).unwrap();
4482
    fs::remove_file(root.join("link")).unwrap();
4483
    write(root, "link", b"run.sh");
4484
    let win = Repo::open(root).unwrap().with_platform(Platform::windows());
4485
    let s = win.snapshot("oxy status").unwrap();
4486
    assert!(
4487
        s.statuses.is_empty(),
4488
        "nothing changed on Windows: {:?}",
4489
        statuses(&s)
4490
    );
4491
    // Editing the file is a content change, not a mode change; retargeting the link keeps it a link.
4492
    write(root, "run.sh", b"#!/bin/sh\necho hi\n");
4493
    write(root, "link", b"other");
4494
    let h = win.commit("edit on Windows", &[]).unwrap();
4495
    let snap = win.load_state(&[h]).unwrap().materialize();
4496
    assert!(snap.files["run.sh"].mode.exec, "the exec bit survives");
4497
    assert_eq!(snap.files["link"].kind, NodeKind::Symlink);
4498
    // The same working copy read as Linux sees the lost bit and the plain file.
4499
    let linux = Repo::open(root).unwrap();
4500
    assert!(!linux.snapshot("oxy status").unwrap().statuses.is_empty());
4501
}
4502
4503
/// Paths that collide on case-insensitive or Windows file systems are
4504
/// named at checkout there, and by doctor everywhere.
4505
#[test]
4506
fn paths_other_platforms_cannot_hold_are_reported() {
4507
    use crate::portable::Platform;
4508
    hermetic();
4509
    let dir = tempfile::tempdir().unwrap();
4510
    let root = dir.path();
4511
    let repo = Repo::init(root).unwrap();
4512
    write(root, "README.md", b"a\n");
4513
    write(root, "readme.md", b"b\n");
4514
    write(root, "src/aux.c", b"int x;\n");
4515
    let h = repo.commit("unportable", &[]).unwrap();
4516
    let r = repo.doctor(false);
4517
    let port = r.checks.iter().find(|c| c.area == "portability").unwrap();
4518
    assert_eq!(port.health, Health::Warn);
4519
    assert!(
4520
        port.message.contains("differ only in case") && port.message.contains("aux.c"),
4521
        "{}",
4522
        port.message
4523
    );
4524
    let mac = Repo::open(root).unwrap().with_platform(Platform::macos());
4525
    let rep = mac.checkout(&[h], true, "oxy checkout").unwrap();
4526
    assert!(
4527
        rep.notes
4528
            .iter()
4529
            .any(|n| n.contains("README.md and readme.md")),
4530
        "{:?}",
4531
        rep.notes
4532
    );
4533
    assert!(
4534
        !rep.notes.iter().any(|n| n.contains("aux.c")),
4535
        "macOS allows aux.c"
4536
    );
4537
}
4538
4539
#[test]
4540
fn history_and_blame_of_a_loaded_state_match_the_full_walk() {
4541
    hermetic();
4542
    let dir = tempfile::tempdir().unwrap();
4543
    let repo = Repo::init(dir.path()).unwrap();
4544
    write(dir.path(), "a.txt", b"one\n");
4545
    write(dir.path(), "other.txt", b"x\n");
4546
    write(dir.path(), "bin.dat", &[0u8, 1, 2, 0, 255]);
4547
    repo.snapshot("t").unwrap();
4548
    let c1 = repo.commit("first", &[]).unwrap();
4549
    write(dir.path(), "other.txt", b"y\n");
4550
    repo.snapshot("t").unwrap();
4551
    repo.commit("other only", &[]).unwrap();
4552
    write(dir.path(), "a.txt", b"one\ntwo\n");
4553
    repo.snapshot("t").unwrap();
4554
    let c3 = repo.commit("second line", &[]).unwrap();
4555
    write(dir.path(), "other.txt", b"z\n");
4556
    repo.snapshot("t").unwrap();
4557
    repo.commit("other again", &[]).unwrap();
4558
4559
    let heads = repo.bookmark_heads().unwrap();
4560
    let state = repo.load_state(&heads).unwrap();
4561
    let full: Vec<ChangeHash> = repo
4562
        .log_for_path_in("a.txt", &heads)
4563
        .unwrap()
4564
        .iter()
4565
        .map(|e| e.hash)
4566
        .collect();
4567
    assert_eq!(
4568
        full,
4569
        vec![c3, c1],
4570
        "newest first, only changes touching the path"
4571
    );
4572
    let newest: Vec<ChangeHash> = repo
4573
        .log_for_path_of(&state, "a.txt", Some(1))
4574
        .unwrap()
4575
        .iter()
4576
        .map(|e| e.hash)
4577
        .collect();
4578
    assert_eq!(newest, vec![c3], "stops at the first");
4579
    assert_eq!(
4580
        repo.log_for_path_of(&state, "a.txt", None).unwrap().len(),
4581
        2
4582
    );
4583
    assert!(repo
4584
        .log_for_path_of(&state, "missing.txt", Some(1))
4585
        .is_err());
4586
    assert_eq!(
4587
        repo.log_state(&heads).unwrap().len(),
4588
        repo.log_of(&state).len()
4589
    );
4590
4591
    let tree = state.tree().view();
4592
    let via_state = repo.blame_of(&state, &tree, "a.txt").unwrap();
4593
    let via_heads = repo.blame_in("a.txt", &heads).unwrap();
4594
    assert_eq!(
4595
        via_state
4596
            .iter()
4597
            .map(|l| (l.hash, l.text.clone()))
4598
            .collect::<Vec<_>>(),
4599
        via_heads
4600
            .iter()
4601
            .map(|l| (l.hash, l.text.clone()))
4602
            .collect::<Vec<_>>()
4603
    );
4604
    assert_eq!(
4605
        via_state.iter().map(|l| l.hash).collect::<Vec<_>>(),
4606
        vec![c1, c3]
4607
    );
4608
    assert!(repo.blame_of(&state, &tree, "missing.txt").is_err());
4609
}
4610
4611
/// A text file whose stat matches the manifest and whose recorded hash is
4612
/// the base's content is taken from the base without reading it; anything
4613
/// else is read, so no edit is missed (spec §12.3).
4614
#[cfg(unix)]
4615
#[test]
4616
fn stat_cache_takes_unchanged_text_from_the_base_and_misses_no_edit() {
4617
    use std::os::unix::fs::PermissionsExt;
4618
    hermetic();
4619
    let dir = tempfile::tempdir().unwrap();
4620
    let root = dir.path();
4621
    let repo = Repo::init(root).unwrap().with_home(root.join("home"));
4622
    write(root, "a.txt", b"one\ntwo\n");
4623
    write(root, "b.txt", b"bee\n");
4624
    repo.commit("base", &[]).unwrap();
4625
    let age = |p: &str| {
4626
        let old = std::time::SystemTime::now() - std::time::Duration::from_secs(30);
4627
        fs::File::options()
4628
            .write(true)
4629
            .open(root.join(p))
4630
            .unwrap()
4631
            .set_modified(old)
4632
            .unwrap();
4633
    };
4634
    age("a.txt");
4635
    age("b.txt");
4636
    assert!(
4637
        !repo.snapshot("status").unwrap().changed,
4638
        "records the aged stat"
4639
    );
4640
4641
    // Clean and equal to the base: not read at all.
4642
    fs::set_permissions(root.join("a.txt"), fs::Permissions::from_mode(0o000)).unwrap();
4643
    let snap = repo.snapshot("status").unwrap();
4644
    assert!(
4645
        !snap.changed && snap.statuses.is_empty(),
4646
        "{:?}",
4647
        snap.statuses
4648
    );
4649
    fs::set_permissions(root.join("a.txt"), fs::Permissions::from_mode(0o644)).unwrap();
4650
4651
    // An uncommitted edit that is older than the manifest: stat-clean, but
4652
    // its hash is not the base's, so it is read and stays visible.
4653
    write(root, "b.txt", b"bee edited\n");
4654
    age("b.txt");
4655
    let first = repo.snapshot("status").unwrap();
4656
    assert_eq!(
4657
        statuses(&first),
4658
        vec![("b.txt".to_string(), ChangeStatus::Modified)]
4659
    );
4660
    let again = repo.snapshot("status").unwrap();
4661
    assert_eq!(
4662
        statuses(&again),
4663
        vec![("b.txt".to_string(), ChangeStatus::Modified)],
4664
        "still seen once stat-clean"
4665
    );
4666
    assert!(!again.changed, "and the working copy hashes the same");
4667
    fs::set_permissions(root.join("b.txt"), fs::Permissions::from_mode(0o000)).unwrap();
4668
    assert!(
4669
        repo.snapshot("status").is_err(),
4670
        "an edited file must be read, never taken from the base"
4671
    );
4672
    fs::set_permissions(root.join("b.txt"), fs::Permissions::from_mode(0o644)).unwrap();
4673
4674
    // A same-size edit made just now is racy and read.
4675
    write(root, "a.txt", b"one\nTWO\n");
4676
    assert_eq!(
4677
        statuses(&repo.snapshot("status").unwrap()),
4678
        vec![
4679
            ("a.txt".to_string(), ChangeStatus::Modified),
4680
            ("b.txt".to_string(), ChangeStatus::Modified)
4681
        ]
4682
    );
4683
    // Committing makes the edits the base: both are clean and served from it again.
4684
    repo.commit("edits", &[]).unwrap();
4685
    age("a.txt");
4686
    age("b.txt");
4687
    assert!(repo.snapshot("status").unwrap().statuses.is_empty());
4688
    fs::set_permissions(root.join("a.txt"), fs::Permissions::from_mode(0o000)).unwrap();
4689
    fs::set_permissions(root.join("b.txt"), fs::Permissions::from_mode(0o000)).unwrap();
4690
    let snap = repo.snapshot("status").unwrap();
4691
    assert!(!snap.changed && snap.statuses.is_empty());
4692
    fs::set_permissions(root.join("a.txt"), fs::Permissions::from_mode(0o644)).unwrap();
4693
    fs::set_permissions(root.join("b.txt"), fs::Permissions::from_mode(0o644)).unwrap();
4694
}
4695
4696
/// Version 2 checkpoints (spec §11): a large file's graph is a blob of its
4697
/// own, kept by gc, checked by fsck, shared by the next checkpoint when the
4698
/// file is unchanged, and loading through the checkpoint equals a full load.
4699
#[test]
4700
fn checkpoints_keep_large_graphs_as_blobs_of_their_own() {
4701
    hermetic();
4702
    let dir = tempfile::tempdir().unwrap();
4703
    let root = dir.path();
4704
    let repo = Repo::init(root).unwrap().with_home(root.join("home"));
4705
    let long: String = (0..300)
4706
        .map(|i| format!("line {i} of a long file\n"))
4707
        .collect();
4708
    write(root, "long.txt", long.as_bytes());
4709
    write(root, "short.txt", b"short\n");
4710
    repo.commit("base", &[]).unwrap();
4711
    let (r1, _, _) = repo.checkpoint().unwrap();
4712
    let cp1 = crate::objects::Checkpoint::decode(
4713
        &repo.store().get_typed(&r1, ObjectType::Checkpoint).unwrap(),
4714
    )
4715
    .unwrap();
4716
    let graphs1 = repo.checkpoint_graph_blobs(&cp1).unwrap();
4717
    assert_eq!(graphs1.len(), 1, "only the long file's graph is a blob");
4718
4719
    // gc keeps the graph blob; fsck finds the checkpoint sound.
4720
    repo.gc(true).unwrap();
4721
    assert!(repo.store().has(&graphs1[0]));
4722
    let report = repo.fsck().unwrap();
4723
    assert_eq!(report.errors(), 0, "{:?}", report.problems);
4724
4725
    // Loading through the checkpoint equals a full load.
4726
    write(root, "short.txt", b"short, edited\n");
4727
    repo.commit("edit the short file", &[]).unwrap();
4728
    let heads = repo.bookmark_heads().unwrap();
4729
    let fast = repo.load_state(&heads).unwrap();
4730
    let full = repo.load_state_full(&heads).unwrap();
4731
    assert_eq!(fast.checkpoint_payload(), full.checkpoint_payload());
4732
4733
    // The next checkpoint shares the unchanged long file's graph.
4734
    let (r2, _, _) = repo.checkpoint().unwrap();
4735
    let cp2 = crate::objects::Checkpoint::decode(
4736
        &repo.store().get_typed(&r2, ObjectType::Checkpoint).unwrap(),
4737
    )
4738
    .unwrap();
4739
    assert_eq!(repo.checkpoint_graph_blobs(&cp2).unwrap(), graphs1);
4740
4741
    // A shallow clone's bundle carries the graph blob with the checkpoint.
4742
    let bundle = repo.checkpoint_bundle_for(&heads).unwrap();
4743
    assert!(bundle.objects.iter().any(|(t, body)| *t == ObjectType::Blob
4744
        && crate::hash::hash_object(ObjectType::Blob, body) == graphs1[0]));
4745
4746
    // A version 1 checkpoint written by an older oxy still loads.
4747
    let state = repo.load_state_full(&heads).unwrap();
4748
    let old = repo.store_blob(&state.checkpoint_payload()).unwrap();
4749
    let cp_old = crate::objects::Checkpoint {
4750
        heads: cp2.heads.clone(),
4751
        count: cp2.count,
4752
        payload: old,
4753
    };
4754
    let r_old = repo
4755
        .store()
4756
        .put(ObjectType::Checkpoint, &cp_old.encode())
4757
        .unwrap();
4758
    repo.install_checkpoint("main", &r_old).unwrap();
4759
    assert_eq!(
4760
        repo.load_state(&heads).unwrap().checkpoint_payload(),
4761
        full.checkpoint_payload()
4762
    );
4763
    assert_eq!(repo.fsck().unwrap().errors(), 0);
4764
4765
    // A lost graph blob fails the load loudly rather than dropping the
4766
    // file, and fsck reports it (a fresh repository, objects still loose).
4767
    let dir2 = tempfile::tempdir().unwrap();
4768
    let root2 = dir2.path();
4769
    let repo2 = Repo::init(root2).unwrap().with_home(root2.join("home"));
4770
    write(root2, "long.txt", long.as_bytes());
4771
    repo2.commit("base", &[]).unwrap();
4772
    let (r, _, _) = repo2.checkpoint().unwrap();
4773
    let cp = crate::objects::Checkpoint::decode(
4774
        &repo2.store().get_typed(&r, ObjectType::Checkpoint).unwrap(),
4775
    )
4776
    .unwrap();
4777
    let graph = repo2.checkpoint_graph_blobs(&cp).unwrap()[0];
4778
    fs::remove_file(repo2.store().path_for(&graph)).unwrap();
4779
    assert!(repo2.load_state(&repo2.bookmark_heads().unwrap()).is_err());
4780
    assert!(repo2.fsck().unwrap().errors() > 0, "fsck reports it");
4781
}
4782
4783
/// A new repository has not stored the user's identity yet (that happens
4784
/// at the first signed change); looking it up falls back to the key
4785
/// directory, and a file there that does not hash to the key is refused.
4786
#[test]
4787
fn identity_is_found_in_the_key_directory_for_a_new_repository() {
4788
    hermetic();
4789
    let dir = tempfile::tempdir().unwrap();
4790
    let home = dir.path().join("home");
4791
    let mut first = Repo::init(&dir.path().join("a"))
4792
        .unwrap()
4793
        .with_home(home.clone());
4794
    let (key, _) = first
4795
        .create_identity("Ada", "[email protected]", IdentityScope::User)
4796
        .unwrap();
4797
    let fresh = Repo::init(&dir.path().join("b"))
4798
        .unwrap()
4799
        .with_home(home.clone());
4800
    assert!(!fresh.store().has(&key), "nothing stored yet");
4801
    let id = fresh.identity(&key).unwrap();
4802
    assert_eq!((id.name.as_str(), id.hash()), ("Ada", key));
4803
    // A key file that is not this identity is an error, not a wrong answer.
4804
    let keys = fresh.keys_dir.clone();
4805
    let (other, _) = first
4806
        .create_identity("Bob", "[email protected]", IdentityScope::User)
4807
        .unwrap();
4808
    fs::copy(
4809
        keys.join(format!("{}.identity", other.to_hex())),
4810
        keys.join(format!("{}.identity", key.to_hex())),
4811
    )
4812
    .unwrap();
4813
    assert!(fresh
4814
        .identity(&key)
4815
        .unwrap_err()
4816
        .to_string()
4817
        .contains("does not hold identity"));
4818
}
4819
4820
/// Status snapshots (spec §12.3): a text file whose stat matches the
4821
/// manifest, and whose base graph key is the one the manifest recorded it
4822
/// equal to, is neither read nor rendered; any edit, and any change to the
4823
/// file's graph in the base, brings it back.
4824
#[cfg(unix)]
4825
#[test]
4826
fn status_snapshots_skip_files_unchanged_since_the_manifest() {
4827
    use std::os::unix::fs::PermissionsExt;
4828
    hermetic();
4829
    let dir = tempfile::tempdir().unwrap();
4830
    let root = dir.path();
4831
    let repo = Repo::init(root).unwrap().with_home(root.join("home"));
4832
    for (p, c) in [("a.txt", "one\n"), ("b.txt", "bee\n"), ("d/c.txt", "sea\n")] {
4833
        write(root, p, c.as_bytes());
4834
    }
4835
    repo.commit("base", &[]).unwrap();
4836
    let age = |p: &str| {
4837
        let old = std::time::SystemTime::now() - std::time::Duration::from_secs(30);
4838
        fs::File::options()
4839
            .write(true)
4840
            .open(root.join(p))
4841
            .unwrap()
4842
            .set_modified(old)
4843
            .unwrap();
4844
    };
4845
    let lock = |p: &str, mode: u32| {
4846
        fs::set_permissions(root.join(p), fs::Permissions::from_mode(mode)).unwrap()
4847
    };
4848
    for p in ["a.txt", "b.txt", "d/c.txt"] {
4849
        age(p);
4850
    }
4851
    assert!(repo.snapshot("status").unwrap().statuses.is_empty());
4852
    let (_, _, m) = repo.read_manifest().unwrap().unwrap();
4853
    assert!(
4854
        m.entries.values().all(|e| e.graph.is_some()),
4855
        "keys recorded"
4856
    );
4857
4858
    // Unreadable files prove they are not read; the status snapshot does
4859
    // not render them either, and its base lacks their graphs.
4860
    lock("a.txt", 0o000);
4861
    lock("b.txt", 0o000);
4862
    let snap = repo.snapshot_status("status").unwrap();
4863
    assert!(!snap.changed && snap.statuses.is_empty());
4864
    assert_eq!(
4865
        snap.base_snapshot
4866
            .unrendered
4867
            .iter()
4868
            .cloned()
4869
            .collect::<Vec<_>>(),
4870
        vec!["a.txt", "b.txt", "d/c.txt"]
4871
    );
4872
    assert!(!snap.base.is_full());
4873
    assert!(!snap.base_snapshot.is_conflicted());
4874
    // A full snapshot does not read them either, but renders everything.
4875
    let full = repo.snapshot("status").unwrap();
4876
    assert!(full.statuses.is_empty() && full.base.is_full());
4877
    assert!(full.base_snapshot.unrendered.is_empty());
4878
    assert!(matches!(&full.base_snapshot.files["a.txt"].content,
4879
        FileContent::Text { bytes, .. } if bytes == b"one\n"));
4880
4881
    // An edit is seen; the file is rendered, the others still are not.
4882
    write(root, "d/c.txt", b"sea edited\n");
4883
    let snap = repo.snapshot_status("status").unwrap();
4884
    assert_eq!(
4885
        statuses(&snap),
4886
        vec![("d/c.txt".to_string(), ChangeStatus::Modified)]
4887
    );
4888
    assert!(!snap.base_snapshot.unrendered.contains("d/c.txt"));
4889
    // So is a mode change of an unread file.
4890
    lock("b.txt", 0o100);
4891
    assert_eq!(
4892
        statuses(&repo.snapshot_status("status").unwrap()),
4893
        vec![
4894
            ("b.txt".to_string(), ChangeStatus::ModeChanged),
4895
            ("d/c.txt".to_string(), ChangeStatus::Modified)
4896
        ]
4897
    );
4898
    lock("b.txt", 0o000);
4899
4900
    // Committing c.txt changes its graph in the base, not a.txt's: a.txt
4901
    // stays unread, c.txt is read once and then skipped too.
4902
    repo.commit_selection("edit c", &[], &Selection::Paths(vec!["d/c.txt".into()]))
4903
        .unwrap();
4904
    age("d/c.txt");
4905
    let snap = repo.snapshot_status("status").unwrap();
4906
    assert!(snap.statuses.is_empty(), "{:?}", snap.statuses);
4907
    assert!(snap.base_snapshot.unrendered.contains("a.txt"));
4908
    lock("d/c.txt", 0o000);
4909
    let snap = repo.snapshot_status("status").unwrap();
4910
    assert!(snap.statuses.is_empty());
4911
    assert!(snap.base_snapshot.unrendered.contains("d/c.txt"));
4912
    for p in ["a.txt", "b.txt", "d/c.txt"] {
4913
        lock(p, 0o644);
4914
    }
4915
}
4916
4917
/// Attributes decide how a file compares with the base, so a changed
4918
/// `.oxyattributes` makes every text file be compared again.
4919
#[cfg(unix)]
4920
#[test]
4921
fn a_changed_attributes_file_disables_skipping_unchanged_files() {
4922
    hermetic();
4923
    let dir = tempfile::tempdir().unwrap();
4924
    let root = dir.path();
4925
    let repo = Repo::init(root).unwrap().with_home(root.join("home"));
4926
    write(root, "a.txt", b"crlf\r\n");
4927
    repo.commit("base", &[]).unwrap();
4928
    let old = std::time::SystemTime::now() - std::time::Duration::from_secs(30);
4929
    fs::File::options()
4930
        .write(true)
4931
        .open(root.join("a.txt"))
4932
        .unwrap()
4933
        .set_modified(old)
4934
        .unwrap();
4935
    assert!(repo.snapshot_status("status").unwrap().statuses.is_empty());
4936
    assert!(repo
4937
        .snapshot_status("status")
4938
        .unwrap()
4939
        .base_snapshot
4940
        .unrendered
4941
        .contains("a.txt"));
4942
    // With eol=lf, a.txt as stored no longer equals the base.
4943
    write(root, ".oxyattributes", b"*.txt eol=lf\n");
4944
    let snap = repo.snapshot_status("status").unwrap();
4945
    assert_eq!(
4946
        statuses(&snap),
4947
        vec![
4948
            (".oxyattributes".to_string(), ChangeStatus::Added),
4949
            ("a.txt".to_string(), ChangeStatus::Modified)
4950
        ]
4951
    );
4952
}
4953
4954
/// Bookmarks with `/` in their names: pushing records their
4955
/// attestations, and checkpoints are kept for them, beside `feature`
4956
/// itself.
4957
#[test]
4958
fn bookmarks_with_slashes_push_and_checkpoint() {
4959
    hermetic();
4960
    let dir = tempfile::tempdir().unwrap();
4961
    let root = dir.path();
4962
    let origin = Repo::init(&root.join("origin")).unwrap();
4963
    let url = root.join("origin").to_string_lossy().to_string();
4964
    let mut repo = Repo::clone(&url, &root.join("r"))
4965
        .unwrap()
4966
        .with_home(root.join("home"));
4967
    // With an identity, pushes carry reference attestations: the case
4968
    // that failed, since the attestation is a file named after the bookmark.
4969
    repo.create_identity("Ada", "[email protected]", IdentityScope::Repo)
4970
        .unwrap();
4971
    let r = root.join("r");
4972
    write(&r, "a.txt", b"a\n");
4973
    let h_a = repo.commit("a", &[]).unwrap();
4974
    assert!(repo.push("origin", false).unwrap()[0].ok);
4975
    repo.bookmark_create("feature", None).unwrap();
4976
    repo.bookmark_create("feature/x", None).unwrap();
4977
    repo.bookmark_switch("feature/x", false).unwrap();
4978
    write(&r, "b.txt", b"b\n");
4979
    let h_b = repo.commit("b", &[]).unwrap();
4980
    for name in ["feature", "feature/x"] {
4981
        let res = repo.push_bookmark("origin", name, false).unwrap();
4982
        assert!(res[0].ok, "{name}: {res:?}");
4983
    }
4984
    assert_eq!(origin.resolve_heads("feature").unwrap(), vec![h_a]);
4985
    assert_eq!(
4986
        origin.resolve_heads("feature/x").unwrap(),
4987
        repo.resolve_heads("feature/x").unwrap()
4988
    );
4989
    assert!(origin.resolve_heads("feature/x").unwrap().contains(&h_b));
4990
    assert!(origin.latest_ref_attest("feature/x").unwrap().is_some());
4991
    assert!(origin.latest_ref_attest("feature").unwrap().is_some());
4992
4993
    // A checkpoint of feature/x is found again when loading its state.
4994
    let (cp, _, _) = repo.checkpoint().unwrap();
4995
    assert_eq!(repo.latest_checkpoint("feature/x").unwrap().unwrap().0, cp);
4996
    assert!(repo.latest_checkpoint("feature").unwrap().is_none());
4997
    let heads = repo.resolve_heads("feature/x").unwrap();
4998
    assert!(repo.load_state_checkpointed(&heads).unwrap().is_some());
4999
}
5000
5001
/// Deleting a bookmark on a remote (spec §16.4): attested like any update,
5002
/// never the remote's own bookmark, and a bookmark created again later is
5003
/// accepted although the deletion's attestation stays the latest.
5004
#[test]
5005
fn bookmarks_are_deleted_on_a_remote() {
5006
    hermetic();
5007
    let dir = tempfile::tempdir().unwrap();
5008
    let root = dir.path();
5009
    let origin = Repo::init(&root.join("origin")).unwrap();
5010
    let url = root.join("origin").to_string_lossy().to_string();
5011
    let mut repo = Repo::clone(&url, &root.join("r"))
5012
        .unwrap()
5013
        .with_home(root.join("home"));
5014
    repo.create_identity("Ada", "[email protected]", IdentityScope::Repo)
5015
        .unwrap();
5016
    let r = root.join("r");
5017
    write(&r, "a.txt", b"a\n");
5018
    repo.commit("a", &[]).unwrap();
5019
    assert!(repo.push("origin", false).unwrap()[0].ok);
5020
    repo.bookmark_create("feature/x", None).unwrap();
5021
    assert!(repo.push_bookmark("origin", "feature/x", false).unwrap()[0].ok);
5022
    assert!(origin.resolve_heads("feature/x").is_ok());
5023
5024
    let res = repo.push_delete("origin", "feature/x").unwrap();
5025
    assert!(res[0].ok, "{res:?}");
5026
    assert!(!origin.view().unwrap().bookmarks.contains_key("feature/x"));
5027
    let (_, att) = origin.latest_ref_attest("feature/x").unwrap().unwrap();
5028
    assert!(
5029
        matches!(att.attest.body, AttestBody::Ref { new_state, .. } if new_state.is_zero()),
5030
        "the deletion is attested"
5031
    );
5032
    assert!(
5033
        repo.view().unwrap().bookmarks.contains_key("feature/x"),
5034
        "the local bookmark stays"
5035
    );
5036
    assert!(!repo
5037
        .view()
5038
        .unwrap()
5039
        .remotes
5040
        .get("origin")
5041
        .is_some_and(|m| m.contains_key("feature/x")));
5042
5043
    // Pushing it again creates it again, past the deletion's serial.
5044
    let res = repo.push_bookmark("origin", "feature/x", false).unwrap();
5045
    assert!(res[0].ok, "{res:?}");
5046
    assert!(origin.view().unwrap().bookmarks.contains_key("feature/x"));
5047
5048
    // Nothing to delete, and never the remote's own bookmark.
5049
    assert!(repo.push_delete("origin", "nope").is_err());
5050
    let res = repo.push_delete("origin", "main").unwrap();
5051
    assert!(
5052
        !res[0].ok && res[0].reason.contains("default bookmark"),
5053
        "{res:?}"
5054
    );
5055
    assert!(origin.view().unwrap().bookmarks.contains_key("main"));
5056
}